From 8943bc7189dcd6fb198c1e6c5b9fc748950a9ea3 Mon Sep 17 00:00:00 2001 From: kunxin-chor Date: Wed, 3 Jun 2020 11:42:52 +0000 Subject: [PATCH 1/2] Added new image --- .gitpod.Dockerfile | 7 + .gitpod.yml | 6 +- app/app.js | 26 + app/bin/www | 90 + app/models/UserModel.js | 8 + app/mongoUtil.js | 19 + app/node_modules/.bin/mime | 1 + app/node_modules/.bin/semver | 1 + app/node_modules/.bin/window-size | 1 + app/node_modules/.yarn-integrity | 137 + app/node_modules/accepts/HISTORY.md | 236 + app/node_modules/accepts/LICENSE | 23 + app/node_modules/accepts/README.md | 142 + app/node_modules/accepts/index.js | 238 + app/node_modules/accepts/package.json | 47 + app/node_modules/ansi-regex/index.js | 4 + app/node_modules/ansi-regex/license | 21 + app/node_modules/ansi-regex/package.json | 64 + app/node_modules/ansi-regex/readme.md | 39 + app/node_modules/array-flatten/LICENSE | 21 + app/node_modules/array-flatten/README.md | 43 + .../array-flatten/array-flatten.js | 64 + app/node_modules/array-flatten/package.json | 39 + app/node_modules/async/CHANGELOG.md | 263 + app/node_modules/async/LICENSE | 19 + app/node_modules/async/README.md | 50 + app/node_modules/async/all.js | 50 + app/node_modules/async/allLimit.js | 42 + app/node_modules/async/allSeries.js | 37 + app/node_modules/async/any.js | 52 + app/node_modules/async/anyLimit.js | 43 + app/node_modules/async/anySeries.js | 38 + app/node_modules/async/apply.js | 68 + app/node_modules/async/applyEach.js | 51 + app/node_modules/async/applyEachSeries.js | 37 + app/node_modules/async/asyncify.js | 110 + app/node_modules/async/auto.js | 289 + app/node_modules/async/autoInject.js | 170 + app/node_modules/async/bower.json | 17 + app/node_modules/async/cargo.js | 94 + app/node_modules/async/compose.js | 58 + app/node_modules/async/concat.js | 43 + app/node_modules/async/concatLimit.js | 65 + app/node_modules/async/concatSeries.js | 36 + app/node_modules/async/constant.js | 66 + app/node_modules/async/detect.js | 61 + app/node_modules/async/detectLimit.js | 48 + app/node_modules/async/detectSeries.js | 38 + app/node_modules/async/dir.js | 43 + app/node_modules/async/dist/async.js | 5595 +++++ app/node_modules/async/dist/async.min.js | 2 + app/node_modules/async/dist/async.min.map | 1 + app/node_modules/async/doDuring.js | 66 + app/node_modules/async/doUntil.js | 39 + app/node_modules/async/doWhilst.js | 59 + app/node_modules/async/during.js | 76 + app/node_modules/async/each.js | 82 + app/node_modules/async/eachLimit.js | 45 + app/node_modules/async/eachOf.js | 111 + app/node_modules/async/eachOfLimit.js | 41 + app/node_modules/async/eachOfSeries.js | 35 + app/node_modules/async/eachSeries.js | 37 + app/node_modules/async/ensureAsync.js | 73 + app/node_modules/async/every.js | 50 + app/node_modules/async/everyLimit.js | 42 + app/node_modules/async/everySeries.js | 37 + app/node_modules/async/filter.js | 45 + app/node_modules/async/filterLimit.js | 37 + app/node_modules/async/filterSeries.js | 35 + app/node_modules/async/find.js | 61 + app/node_modules/async/findLimit.js | 48 + app/node_modules/async/findSeries.js | 38 + app/node_modules/async/foldl.js | 78 + app/node_modules/async/foldr.js | 44 + app/node_modules/async/forEach.js | 82 + app/node_modules/async/forEachLimit.js | 45 + app/node_modules/async/forEachOf.js | 111 + app/node_modules/async/forEachOfLimit.js | 41 + app/node_modules/async/forEachOfSeries.js | 35 + app/node_modules/async/forEachSeries.js | 37 + app/node_modules/async/forever.js | 65 + app/node_modules/async/groupBy.js | 54 + app/node_modules/async/groupByLimit.js | 71 + app/node_modules/async/groupBySeries.js | 37 + app/node_modules/async/index.js | 582 + app/node_modules/async/inject.js | 78 + .../async/internal/DoublyLinkedList.js | 88 + app/node_modules/async/internal/applyEach.js | 38 + app/node_modules/async/internal/breakLoop.js | 9 + .../async/internal/consoleFunc.js | 42 + .../async/internal/createTester.js | 44 + app/node_modules/async/internal/doLimit.js | 12 + app/node_modules/async/internal/doParallel.js | 23 + .../async/internal/doParallelLimit.js | 23 + .../async/internal/eachOfLimit.js | 71 + app/node_modules/async/internal/filter.js | 75 + .../async/internal/findGetResult.js | 10 + .../async/internal/getIterator.js | 13 + .../async/internal/initialParams.js | 21 + app/node_modules/async/internal/iterator.js | 58 + app/node_modules/async/internal/map.js | 35 + app/node_modules/async/internal/notId.js | 10 + app/node_modules/async/internal/once.js | 15 + app/node_modules/async/internal/onlyOnce.js | 15 + app/node_modules/async/internal/parallel.js | 42 + app/node_modules/async/internal/queue.js | 204 + app/node_modules/async/internal/reject.js | 21 + .../async/internal/setImmediate.js | 42 + app/node_modules/async/internal/slice.js | 16 + .../async/internal/withoutIndex.js | 12 + app/node_modules/async/internal/wrapAsync.js | 25 + app/node_modules/async/log.js | 41 + app/node_modules/async/map.js | 54 + app/node_modules/async/mapLimit.js | 37 + app/node_modules/async/mapSeries.js | 36 + app/node_modules/async/mapValues.js | 63 + app/node_modules/async/mapValuesLimit.js | 61 + app/node_modules/async/mapValuesSeries.js | 37 + app/node_modules/async/memoize.js | 101 + app/node_modules/async/nextTick.js | 51 + app/node_modules/async/package.json | 83 + app/node_modules/async/parallel.js | 90 + app/node_modules/async/parallelLimit.js | 40 + app/node_modules/async/priorityQueue.js | 98 + app/node_modules/async/queue.js | 130 + app/node_modules/async/race.js | 70 + app/node_modules/async/reduce.js | 78 + app/node_modules/async/reduceRight.js | 44 + app/node_modules/async/reflect.js | 81 + app/node_modules/async/reflectAll.js | 105 + app/node_modules/async/reject.js | 45 + app/node_modules/async/rejectLimit.js | 37 + app/node_modules/async/rejectSeries.js | 35 + app/node_modules/async/retry.js | 156 + app/node_modules/async/retryable.js | 65 + app/node_modules/async/select.js | 45 + app/node_modules/async/selectLimit.js | 37 + app/node_modules/async/selectSeries.js | 35 + app/node_modules/async/seq.js | 91 + app/node_modules/async/series.js | 85 + app/node_modules/async/setImmediate.js | 45 + app/node_modules/async/some.js | 52 + app/node_modules/async/someLimit.js | 43 + app/node_modules/async/someSeries.js | 38 + app/node_modules/async/sortBy.js | 91 + app/node_modules/async/timeout.js | 89 + app/node_modules/async/times.js | 50 + app/node_modules/async/timesLimit.js | 42 + app/node_modules/async/timesSeries.js | 32 + app/node_modules/async/transform.js | 87 + app/node_modules/async/tryEach.js | 81 + app/node_modules/async/unmemoize.js | 25 + app/node_modules/async/until.js | 41 + app/node_modules/async/waterfall.js | 113 + app/node_modules/async/whilst.js | 72 + app/node_modules/async/wrapSync.js | 110 + app/node_modules/basic-auth/HISTORY.md | 52 + app/node_modules/basic-auth/LICENSE | 24 + app/node_modules/basic-auth/README.md | 113 + app/node_modules/basic-auth/index.js | 133 + app/node_modules/basic-auth/package.json | 41 + app/node_modules/bluebird/LICENSE | 21 + app/node_modules/bluebird/README.md | 51 + app/node_modules/bluebird/changelog.md | 1 + .../bluebird/js/browser/bluebird.core.js | 3777 ++++ .../bluebird/js/browser/bluebird.core.min.js | 31 + .../bluebird/js/browser/bluebird.js | 5619 +++++ .../bluebird/js/browser/bluebird.min.js | 31 + app/node_modules/bluebird/js/release/any.js | 21 + .../bluebird/js/release/assert.js | 55 + app/node_modules/bluebird/js/release/async.js | 161 + app/node_modules/bluebird/js/release/bind.js | 67 + .../bluebird/js/release/bluebird.js | 11 + .../bluebird/js/release/call_get.js | 123 + .../bluebird/js/release/cancel.js | 129 + .../bluebird/js/release/catch_filter.js | 42 + .../bluebird/js/release/context.js | 69 + .../bluebird/js/release/debuggability.js | 916 + .../bluebird/js/release/direct_resolve.js | 46 + app/node_modules/bluebird/js/release/each.js | 30 + .../bluebird/js/release/errors.js | 116 + app/node_modules/bluebird/js/release/es5.js | 80 + .../bluebird/js/release/filter.js | 12 + .../bluebird/js/release/finally.js | 146 + .../bluebird/js/release/generators.js | 223 + app/node_modules/bluebird/js/release/join.js | 168 + app/node_modules/bluebird/js/release/map.js | 168 + .../bluebird/js/release/method.js | 55 + .../bluebird/js/release/nodeback.js | 51 + .../bluebird/js/release/nodeify.js | 58 + .../bluebird/js/release/promise.js | 775 + .../bluebird/js/release/promise_array.js | 185 + .../bluebird/js/release/promisify.js | 314 + app/node_modules/bluebird/js/release/props.js | 118 + app/node_modules/bluebird/js/release/queue.js | 73 + app/node_modules/bluebird/js/release/race.js | 49 + .../bluebird/js/release/reduce.js | 172 + .../bluebird/js/release/schedule.js | 61 + .../bluebird/js/release/settle.js | 43 + app/node_modules/bluebird/js/release/some.js | 148 + .../js/release/synchronous_inspection.js | 103 + .../bluebird/js/release/thenables.js | 86 + .../bluebird/js/release/timers.js | 93 + app/node_modules/bluebird/js/release/using.js | 226 + app/node_modules/bluebird/js/release/util.js | 379 + app/node_modules/bluebird/package.json | 77 + app/node_modules/body-parser/HISTORY.md | 588 + app/node_modules/body-parser/LICENSE | 23 + app/node_modules/body-parser/README.md | 445 + app/node_modules/body-parser/index.js | 157 + app/node_modules/body-parser/lib/read.js | 181 + .../body-parser/lib/types/json.js | 230 + app/node_modules/body-parser/lib/types/raw.js | 101 + .../body-parser/lib/types/text.js | 121 + .../body-parser/lib/types/urlencoded.js | 284 + app/node_modules/body-parser/package.json | 52 + app/node_modules/bson/HISTORY.md | 243 + app/node_modules/bson/LICENSE.md | 201 + app/node_modules/bson/README.md | 170 + app/node_modules/bson/bower.json | 25 + app/node_modules/bson/browser_build/bson.js | 17748 ++++++++++++++++ .../bson/browser_build/package.json | 8 + app/node_modules/bson/index.js | 46 + app/node_modules/bson/lib/bson/binary.js | 382 + app/node_modules/bson/lib/bson/bson.js | 385 + app/node_modules/bson/lib/bson/code.js | 24 + app/node_modules/bson/lib/bson/db_ref.js | 32 + app/node_modules/bson/lib/bson/decimal128.js | 818 + app/node_modules/bson/lib/bson/double.js | 33 + .../bson/lib/bson/float_parser.js | 124 + app/node_modules/bson/lib/bson/int_32.js | 33 + app/node_modules/bson/lib/bson/long.js | 851 + app/node_modules/bson/lib/bson/map.js | 128 + app/node_modules/bson/lib/bson/max_key.js | 14 + app/node_modules/bson/lib/bson/min_key.js | 14 + app/node_modules/bson/lib/bson/objectid.js | 387 + .../bson/lib/bson/parser/calculate_size.js | 255 + .../bson/lib/bson/parser/deserializer.js | 780 + .../bson/lib/bson/parser/serializer.js | 1182 + .../bson/lib/bson/parser/utils.js | 14 + app/node_modules/bson/lib/bson/regexp.js | 33 + app/node_modules/bson/lib/bson/symbol.js | 50 + app/node_modules/bson/lib/bson/timestamp.js | 854 + app/node_modules/bson/package.json | 56 + app/node_modules/buffer-shims/index.js | 108 + app/node_modules/buffer-shims/license.md | 19 + app/node_modules/buffer-shims/package.json | 18 + app/node_modules/buffer-shims/readme.md | 21 + app/node_modules/bytes/History.md | 82 + app/node_modules/bytes/LICENSE | 23 + app/node_modules/bytes/Readme.md | 125 + app/node_modules/bytes/index.js | 159 + app/node_modules/bytes/package.json | 39 + app/node_modules/camelcase/index.js | 56 + app/node_modules/camelcase/license | 21 + app/node_modules/camelcase/package.json | 39 + app/node_modules/camelcase/readme.md | 57 + app/node_modules/cliui/CHANGELOG.md | 15 + app/node_modules/cliui/LICENSE.txt | 14 + app/node_modules/cliui/README.md | 110 + app/node_modules/cliui/index.js | 316 + app/node_modules/cliui/package.json | 64 + app/node_modules/code-point-at/index.js | 32 + app/node_modules/code-point-at/license | 21 + app/node_modules/code-point-at/package.json | 38 + app/node_modules/code-point-at/readme.md | 32 + app/node_modules/colors/.travis.yml | 6 + app/node_modules/colors/MIT-LICENSE.txt | 23 + app/node_modules/colors/ReadMe.md | 167 + .../colors/examples/normal-usage.js | 74 + .../colors/examples/safe-string.js | 76 + app/node_modules/colors/lib/colors.js | 176 + app/node_modules/colors/lib/custom/trap.js | 45 + app/node_modules/colors/lib/custom/zalgo.js | 104 + .../colors/lib/extendStringPrototype.js | 118 + app/node_modules/colors/lib/index.js | 12 + app/node_modules/colors/lib/maps/america.js | 12 + app/node_modules/colors/lib/maps/rainbow.js | 13 + app/node_modules/colors/lib/maps/random.js | 8 + app/node_modules/colors/lib/maps/zebra.js | 5 + app/node_modules/colors/lib/styles.js | 77 + .../colors/lib/system/supports-colors.js | 61 + app/node_modules/colors/package.json | 21 + app/node_modules/colors/safe.js | 9 + .../colors/screenshots/colors.png | Bin 0 -> 79787 bytes app/node_modules/colors/tests/basic-test.js | 50 + app/node_modules/colors/tests/safe-test.js | 45 + .../colors/themes/generic-logging.js | 12 + .../content-disposition/HISTORY.md | 50 + app/node_modules/content-disposition/LICENSE | 22 + .../content-disposition/README.md | 141 + app/node_modules/content-disposition/index.js | 445 + .../content-disposition/package.json | 39 + app/node_modules/content-type/HISTORY.md | 24 + app/node_modules/content-type/LICENSE | 22 + app/node_modules/content-type/README.md | 92 + app/node_modules/content-type/index.js | 222 + app/node_modules/content-type/package.json | 40 + app/node_modules/cookie-parser/HISTORY.md | 95 + app/node_modules/cookie-parser/LICENSE | 23 + app/node_modules/cookie-parser/README.md | 102 + app/node_modules/cookie-parser/index.js | 182 + .../node_modules/cookie/HISTORY.md | 123 + .../cookie-parser/node_modules/cookie/LICENSE | 24 + .../node_modules/cookie/README.md | 253 + .../node_modules/cookie/index.js | 198 + .../node_modules/cookie/package.json | 40 + app/node_modules/cookie-parser/package.json | 45 + app/node_modules/cookie-signature/.npmignore | 4 + app/node_modules/cookie-signature/History.md | 38 + app/node_modules/cookie-signature/Readme.md | 42 + app/node_modules/cookie-signature/index.js | 51 + .../cookie-signature/package.json | 18 + app/node_modules/cookie/HISTORY.md | 118 + app/node_modules/cookie/LICENSE | 24 + app/node_modules/cookie/README.md | 220 + app/node_modules/cookie/index.js | 195 + app/node_modules/cookie/package.json | 33 + app/node_modules/core-util-is/LICENSE | 19 + app/node_modules/core-util-is/README.md | 3 + app/node_modules/core-util-is/float.patch | 604 + app/node_modules/core-util-is/lib/util.js | 107 + app/node_modules/core-util-is/package.json | 32 + app/node_modules/core-util-is/test.js | 68 + app/node_modules/cycle/README.md | 49 + app/node_modules/cycle/cycle.js | 170 + app/node_modules/cycle/package.json | 12 + app/node_modules/debug/.coveralls.yml | 1 + app/node_modules/debug/.eslintrc | 11 + app/node_modules/debug/.npmignore | 9 + app/node_modules/debug/.travis.yml | 14 + app/node_modules/debug/CHANGELOG.md | 362 + app/node_modules/debug/LICENSE | 19 + app/node_modules/debug/Makefile | 50 + app/node_modules/debug/README.md | 312 + app/node_modules/debug/component.json | 19 + app/node_modules/debug/karma.conf.js | 70 + app/node_modules/debug/node.js | 1 + app/node_modules/debug/package.json | 49 + app/node_modules/debug/src/browser.js | 185 + app/node_modules/debug/src/debug.js | 202 + app/node_modules/debug/src/index.js | 10 + app/node_modules/debug/src/inspector-log.js | 15 + app/node_modules/debug/src/node.js | 248 + app/node_modules/decamelize/index.js | 13 + app/node_modules/decamelize/license | 21 + app/node_modules/decamelize/package.json | 38 + app/node_modules/decamelize/readme.md | 48 + app/node_modules/depd/History.md | 96 + app/node_modules/depd/LICENSE | 22 + app/node_modules/depd/Readme.md | 280 + app/node_modules/depd/index.js | 522 + app/node_modules/depd/lib/browser/index.js | 77 + .../depd/lib/compat/callsite-tostring.js | 103 + .../depd/lib/compat/event-listener-count.js | 22 + app/node_modules/depd/lib/compat/index.js | 79 + app/node_modules/depd/package.json | 41 + app/node_modules/destroy/LICENSE | 22 + app/node_modules/destroy/README.md | 60 + app/node_modules/destroy/index.js | 75 + app/node_modules/destroy/package.json | 37 + app/node_modules/ee-first/LICENSE | 22 + app/node_modules/ee-first/README.md | 80 + app/node_modules/ee-first/index.js | 95 + app/node_modules/ee-first/package.json | 29 + app/node_modules/encodeurl/HISTORY.md | 14 + app/node_modules/encodeurl/LICENSE | 22 + app/node_modules/encodeurl/README.md | 128 + app/node_modules/encodeurl/index.js | 60 + app/node_modules/encodeurl/package.json | 40 + app/node_modules/es6-promise/CHANGELOG.md | 65 + app/node_modules/es6-promise/LICENSE | 19 + app/node_modules/es6-promise/README.md | 74 + .../es6-promise/dist/es6-promise.js | 959 + .../es6-promise/dist/es6-promise.min.js | 9 + .../es6-promise/lib/es6-promise.umd.js | 18 + .../es6-promise/lib/es6-promise/-internal.js | 273 + .../es6-promise/lib/es6-promise/asap.js | 119 + .../es6-promise/lib/es6-promise/enumerator.js | 118 + .../es6-promise/lib/es6-promise/polyfill.js | 26 + .../es6-promise/lib/es6-promise/promise.js | 384 + .../lib/es6-promise/promise/all.js | 52 + .../lib/es6-promise/promise/race.js | 86 + .../lib/es6-promise/promise/reject.js | 46 + .../lib/es6-promise/promise/resolve.js | 48 + .../es6-promise/lib/es6-promise/then.js | 34 + .../es6-promise/lib/es6-promise/utils.js | 22 + app/node_modules/es6-promise/package.json | 62 + app/node_modules/escape-html/LICENSE | 24 + app/node_modules/escape-html/Readme.md | 43 + app/node_modules/escape-html/index.js | 78 + app/node_modules/escape-html/package.json | 24 + app/node_modules/etag/HISTORY.md | 83 + app/node_modules/etag/LICENSE | 22 + app/node_modules/etag/README.md | 159 + app/node_modules/etag/index.js | 131 + app/node_modules/etag/package.json | 47 + app/node_modules/express/History.md | 3421 +++ app/node_modules/express/LICENSE | 24 + app/node_modules/express/Readme.md | 153 + app/node_modules/express/index.js | 11 + app/node_modules/express/lib/application.js | 644 + app/node_modules/express/lib/express.js | 114 + .../express/lib/middleware/init.js | 43 + .../express/lib/middleware/query.js | 47 + app/node_modules/express/lib/request.js | 521 + app/node_modules/express/lib/response.js | 1137 + app/node_modules/express/lib/router/index.js | 662 + app/node_modules/express/lib/router/layer.js | 181 + app/node_modules/express/lib/router/route.js | 216 + app/node_modules/express/lib/utils.js | 306 + app/node_modules/express/lib/view.js | 182 + app/node_modules/express/package.json | 98 + app/node_modules/eyes/LICENSE | 20 + app/node_modules/eyes/Makefile | 4 + app/node_modules/eyes/README.md | 73 + app/node_modules/eyes/lib/eyes.js | 236 + app/node_modules/eyes/package.json | 14 + app/node_modules/eyes/test/eyes-test.js | 56 + app/node_modules/finalhandler/HISTORY.md | 180 + app/node_modules/finalhandler/LICENSE | 22 + app/node_modules/finalhandler/README.md | 148 + app/node_modules/finalhandler/index.js | 331 + app/node_modules/finalhandler/package.json | 45 + app/node_modules/forwarded/HISTORY.md | 16 + app/node_modules/forwarded/LICENSE | 22 + app/node_modules/forwarded/README.md | 57 + app/node_modules/forwarded/index.js | 76 + app/node_modules/forwarded/package.json | 43 + app/node_modules/fresh/HISTORY.md | 70 + app/node_modules/fresh/LICENSE | 23 + app/node_modules/fresh/README.md | 119 + app/node_modules/fresh/index.js | 137 + app/node_modules/fresh/package.json | 46 + app/node_modules/hooks-fixed/.npmignore | 2 + app/node_modules/hooks-fixed/Makefile | 9 + app/node_modules/hooks-fixed/README.md | 369 + app/node_modules/hooks-fixed/hooks.alt.js | 134 + app/node_modules/hooks-fixed/hooks.js | 192 + app/node_modules/hooks-fixed/package.json | 38 + app/node_modules/hooks-fixed/test.js | 786 + app/node_modules/http-errors/HISTORY.md | 132 + app/node_modules/http-errors/LICENSE | 23 + app/node_modules/http-errors/README.md | 135 + app/node_modules/http-errors/index.js | 260 + .../node_modules/statuses/HISTORY.md | 65 + .../http-errors/node_modules/statuses/LICENSE | 23 + .../node_modules/statuses/README.md | 127 + .../node_modules/statuses/codes.json | 66 + .../node_modules/statuses/index.js | 113 + .../node_modules/statuses/package.json | 48 + app/node_modules/http-errors/package.json | 48 + app/node_modules/iconv-lite/.travis.yml | 23 + app/node_modules/iconv-lite/Changelog.md | 158 + app/node_modules/iconv-lite/LICENSE | 21 + app/node_modules/iconv-lite/README.md | 156 + .../iconv-lite/encodings/dbcs-codec.js | 555 + .../iconv-lite/encodings/dbcs-data.js | 176 + .../iconv-lite/encodings/index.js | 22 + .../iconv-lite/encodings/internal.js | 188 + .../iconv-lite/encodings/sbcs-codec.js | 72 + .../encodings/sbcs-data-generated.js | 451 + .../iconv-lite/encodings/sbcs-data.js | 169 + .../encodings/tables/big5-added.json | 122 + .../iconv-lite/encodings/tables/cp936.json | 264 + .../iconv-lite/encodings/tables/cp949.json | 273 + .../iconv-lite/encodings/tables/cp950.json | 177 + .../iconv-lite/encodings/tables/eucjp.json | 182 + .../encodings/tables/gb18030-ranges.json | 1 + .../encodings/tables/gbk-added.json | 55 + .../iconv-lite/encodings/tables/shiftjis.json | 125 + .../iconv-lite/encodings/utf16.js | 177 + app/node_modules/iconv-lite/encodings/utf7.js | 290 + .../iconv-lite/lib/bom-handling.js | 52 + .../iconv-lite/lib/extend-node.js | 217 + app/node_modules/iconv-lite/lib/index.d.ts | 24 + app/node_modules/iconv-lite/lib/index.js | 153 + app/node_modules/iconv-lite/lib/streams.js | 121 + app/node_modules/iconv-lite/package.json | 46 + app/node_modules/inherits/LICENSE | 16 + app/node_modules/inherits/README.md | 42 + app/node_modules/inherits/inherits.js | 7 + app/node_modules/inherits/inherits_browser.js | 23 + app/node_modules/inherits/package.json | 29 + app/node_modules/ini/LICENSE | 15 + app/node_modules/ini/README.md | 102 + app/node_modules/ini/ini.js | 194 + app/node_modules/ini/package.json | 30 + app/node_modules/invert-kv/index.js | 15 + app/node_modules/invert-kv/package.json | 33 + app/node_modules/invert-kv/readme.md | 25 + app/node_modules/ipaddr.js/LICENSE | 19 + app/node_modules/ipaddr.js/README.md | 233 + app/node_modules/ipaddr.js/ipaddr.min.js | 1 + app/node_modules/ipaddr.js/lib/ipaddr.js | 673 + app/node_modules/ipaddr.js/lib/ipaddr.js.d.ts | 68 + app/node_modules/ipaddr.js/package.json | 35 + .../is-fullwidth-code-point/index.js | 46 + .../is-fullwidth-code-point/license | 21 + .../is-fullwidth-code-point/package.json | 45 + .../is-fullwidth-code-point/readme.md | 39 + app/node_modules/isarray/.npmignore | 1 + app/node_modules/isarray/.travis.yml | 4 + app/node_modules/isarray/Makefile | 6 + app/node_modules/isarray/README.md | 60 + app/node_modules/isarray/component.json | 19 + app/node_modules/isarray/index.js | 5 + app/node_modules/isarray/package.json | 45 + app/node_modules/isarray/test.js | 20 + app/node_modules/isstream/.jshintrc | 59 + app/node_modules/isstream/.npmignore | 1 + app/node_modules/isstream/.travis.yml | 12 + app/node_modules/isstream/LICENSE.md | 11 + app/node_modules/isstream/README.md | 66 + app/node_modules/isstream/isstream.js | 27 + app/node_modules/isstream/package.json | 33 + app/node_modules/isstream/test.js | 168 + app/node_modules/kareem/.npmignore | 28 + app/node_modules/kareem/.travis.yml | 10 + app/node_modules/kareem/LICENSE | 202 + app/node_modules/kareem/Makefile | 5 + app/node_modules/kareem/README.md | 379 + app/node_modules/kareem/docs.js | 37 + app/node_modules/kareem/gulpfile.js | 18 + app/node_modules/kareem/index.js | 352 + app/node_modules/kareem/package.json | 30 + app/node_modules/kareem/test/examples.test.js | 357 + app/node_modules/kareem/test/post.test.js | 155 + app/node_modules/kareem/test/pre.test.js | 277 + app/node_modules/kareem/test/wrap.test.js | 347 + app/node_modules/lcid/index.js | 22 + app/node_modules/lcid/lcid.json | 203 + app/node_modules/lcid/license | 21 + app/node_modules/lcid/package.json | 46 + app/node_modules/lcid/readme.md | 35 + app/node_modules/lodash.get/LICENSE | 47 + app/node_modules/lodash.get/README.md | 18 + app/node_modules/lodash.get/index.js | 931 + app/node_modules/lodash.get/package.json | 17 + app/node_modules/lodash/LICENSE | 47 + app/node_modules/lodash/README.md | 39 + app/node_modules/lodash/_DataView.js | 7 + app/node_modules/lodash/_Hash.js | 32 + app/node_modules/lodash/_LazyWrapper.js | 28 + app/node_modules/lodash/_ListCache.js | 32 + app/node_modules/lodash/_LodashWrapper.js | 22 + app/node_modules/lodash/_Map.js | 7 + app/node_modules/lodash/_MapCache.js | 32 + app/node_modules/lodash/_Promise.js | 7 + app/node_modules/lodash/_Set.js | 7 + app/node_modules/lodash/_SetCache.js | 27 + app/node_modules/lodash/_Stack.js | 27 + app/node_modules/lodash/_Symbol.js | 6 + app/node_modules/lodash/_Uint8Array.js | 6 + app/node_modules/lodash/_WeakMap.js | 7 + app/node_modules/lodash/_apply.js | 21 + app/node_modules/lodash/_arrayAggregator.js | 22 + app/node_modules/lodash/_arrayEach.js | 22 + app/node_modules/lodash/_arrayEachRight.js | 21 + app/node_modules/lodash/_arrayEvery.js | 23 + app/node_modules/lodash/_arrayFilter.js | 25 + app/node_modules/lodash/_arrayIncludes.js | 17 + app/node_modules/lodash/_arrayIncludesWith.js | 22 + app/node_modules/lodash/_arrayLikeKeys.js | 49 + app/node_modules/lodash/_arrayMap.js | 21 + app/node_modules/lodash/_arrayPush.js | 20 + app/node_modules/lodash/_arrayReduce.js | 26 + app/node_modules/lodash/_arrayReduceRight.js | 24 + app/node_modules/lodash/_arraySample.js | 15 + app/node_modules/lodash/_arraySampleSize.js | 17 + app/node_modules/lodash/_arrayShuffle.js | 15 + app/node_modules/lodash/_arraySome.js | 23 + app/node_modules/lodash/_asciiSize.js | 12 + app/node_modules/lodash/_asciiToArray.js | 12 + app/node_modules/lodash/_asciiWords.js | 15 + app/node_modules/lodash/_assignMergeValue.js | 20 + app/node_modules/lodash/_assignValue.js | 28 + app/node_modules/lodash/_assocIndexOf.js | 21 + app/node_modules/lodash/_baseAggregator.js | 21 + app/node_modules/lodash/_baseAssign.js | 17 + app/node_modules/lodash/_baseAssignIn.js | 17 + app/node_modules/lodash/_baseAssignValue.js | 25 + app/node_modules/lodash/_baseAt.js | 23 + app/node_modules/lodash/_baseClamp.js | 22 + app/node_modules/lodash/_baseClone.js | 165 + app/node_modules/lodash/_baseConforms.js | 18 + app/node_modules/lodash/_baseConformsTo.js | 27 + app/node_modules/lodash/_baseCreate.js | 30 + app/node_modules/lodash/_baseDelay.js | 21 + app/node_modules/lodash/_baseDifference.js | 67 + app/node_modules/lodash/_baseEach.js | 14 + app/node_modules/lodash/_baseEachRight.js | 14 + app/node_modules/lodash/_baseEvery.js | 21 + app/node_modules/lodash/_baseExtremum.js | 32 + app/node_modules/lodash/_baseFill.js | 32 + app/node_modules/lodash/_baseFilter.js | 21 + app/node_modules/lodash/_baseFindIndex.js | 24 + app/node_modules/lodash/_baseFindKey.js | 23 + app/node_modules/lodash/_baseFlatten.js | 38 + app/node_modules/lodash/_baseFor.js | 16 + app/node_modules/lodash/_baseForOwn.js | 16 + app/node_modules/lodash/_baseForOwnRight.js | 16 + app/node_modules/lodash/_baseForRight.js | 15 + app/node_modules/lodash/_baseFunctions.js | 19 + app/node_modules/lodash/_baseGet.js | 24 + app/node_modules/lodash/_baseGetAllKeys.js | 20 + app/node_modules/lodash/_baseGetTag.js | 28 + app/node_modules/lodash/_baseGt.js | 14 + app/node_modules/lodash/_baseHas.js | 19 + app/node_modules/lodash/_baseHasIn.js | 13 + app/node_modules/lodash/_baseInRange.js | 18 + app/node_modules/lodash/_baseIndexOf.js | 20 + app/node_modules/lodash/_baseIndexOfWith.js | 23 + app/node_modules/lodash/_baseIntersection.js | 74 + app/node_modules/lodash/_baseInverter.js | 21 + app/node_modules/lodash/_baseInvoke.js | 24 + app/node_modules/lodash/_baseIsArguments.js | 18 + app/node_modules/lodash/_baseIsArrayBuffer.js | 17 + app/node_modules/lodash/_baseIsDate.js | 18 + app/node_modules/lodash/_baseIsEqual.js | 28 + app/node_modules/lodash/_baseIsEqualDeep.js | 83 + app/node_modules/lodash/_baseIsMap.js | 18 + app/node_modules/lodash/_baseIsMatch.js | 62 + app/node_modules/lodash/_baseIsNaN.js | 12 + app/node_modules/lodash/_baseIsNative.js | 47 + app/node_modules/lodash/_baseIsRegExp.js | 18 + app/node_modules/lodash/_baseIsSet.js | 18 + app/node_modules/lodash/_baseIsTypedArray.js | 60 + app/node_modules/lodash/_baseIteratee.js | 31 + app/node_modules/lodash/_baseKeys.js | 30 + app/node_modules/lodash/_baseKeysIn.js | 33 + app/node_modules/lodash/_baseLodash.js | 10 + app/node_modules/lodash/_baseLt.js | 14 + app/node_modules/lodash/_baseMap.js | 22 + app/node_modules/lodash/_baseMatches.js | 22 + .../lodash/_baseMatchesProperty.js | 33 + app/node_modules/lodash/_baseMean.js | 20 + app/node_modules/lodash/_baseMerge.js | 42 + app/node_modules/lodash/_baseMergeDeep.js | 94 + app/node_modules/lodash/_baseNth.js | 20 + app/node_modules/lodash/_baseOrderBy.js | 34 + app/node_modules/lodash/_basePick.js | 19 + app/node_modules/lodash/_basePickBy.js | 30 + app/node_modules/lodash/_baseProperty.js | 14 + app/node_modules/lodash/_basePropertyDeep.js | 16 + app/node_modules/lodash/_basePropertyOf.js | 14 + app/node_modules/lodash/_basePullAll.js | 51 + app/node_modules/lodash/_basePullAt.js | 37 + app/node_modules/lodash/_baseRandom.js | 18 + app/node_modules/lodash/_baseRange.js | 28 + app/node_modules/lodash/_baseReduce.js | 23 + app/node_modules/lodash/_baseRepeat.js | 35 + app/node_modules/lodash/_baseRest.js | 17 + app/node_modules/lodash/_baseSample.js | 15 + app/node_modules/lodash/_baseSampleSize.js | 18 + app/node_modules/lodash/_baseSet.js | 47 + app/node_modules/lodash/_baseSetData.js | 17 + app/node_modules/lodash/_baseSetToString.js | 22 + app/node_modules/lodash/_baseShuffle.js | 15 + app/node_modules/lodash/_baseSlice.js | 31 + app/node_modules/lodash/_baseSome.js | 22 + app/node_modules/lodash/_baseSortBy.js | 21 + app/node_modules/lodash/_baseSortedIndex.js | 42 + app/node_modules/lodash/_baseSortedIndexBy.js | 64 + app/node_modules/lodash/_baseSortedUniq.js | 30 + app/node_modules/lodash/_baseSum.js | 24 + app/node_modules/lodash/_baseTimes.js | 20 + app/node_modules/lodash/_baseToNumber.js | 24 + app/node_modules/lodash/_baseToPairs.js | 18 + app/node_modules/lodash/_baseToString.js | 37 + app/node_modules/lodash/_baseUnary.js | 14 + app/node_modules/lodash/_baseUniq.js | 72 + app/node_modules/lodash/_baseUnset.js | 20 + app/node_modules/lodash/_baseUpdate.js | 18 + app/node_modules/lodash/_baseValues.js | 19 + app/node_modules/lodash/_baseWhile.js | 26 + app/node_modules/lodash/_baseWrapperValue.js | 25 + app/node_modules/lodash/_baseXor.js | 36 + app/node_modules/lodash/_baseZipObject.js | 23 + app/node_modules/lodash/_cacheHas.js | 13 + .../lodash/_castArrayLikeObject.js | 14 + app/node_modules/lodash/_castFunction.js | 14 + app/node_modules/lodash/_castPath.js | 21 + app/node_modules/lodash/_castRest.js | 14 + app/node_modules/lodash/_castSlice.js | 18 + app/node_modules/lodash/_charsEndIndex.js | 19 + app/node_modules/lodash/_charsStartIndex.js | 20 + app/node_modules/lodash/_cloneArrayBuffer.js | 16 + app/node_modules/lodash/_cloneBuffer.js | 35 + app/node_modules/lodash/_cloneDataView.js | 16 + app/node_modules/lodash/_cloneRegExp.js | 17 + app/node_modules/lodash/_cloneSymbol.js | 18 + app/node_modules/lodash/_cloneTypedArray.js | 16 + app/node_modules/lodash/_compareAscending.js | 41 + app/node_modules/lodash/_compareMultiple.js | 44 + app/node_modules/lodash/_composeArgs.js | 39 + app/node_modules/lodash/_composeArgsRight.js | 41 + app/node_modules/lodash/_copyArray.js | 20 + app/node_modules/lodash/_copyObject.js | 40 + app/node_modules/lodash/_copySymbols.js | 16 + app/node_modules/lodash/_copySymbolsIn.js | 16 + app/node_modules/lodash/_coreJsData.js | 6 + app/node_modules/lodash/_countHolders.js | 21 + app/node_modules/lodash/_createAggregator.js | 23 + app/node_modules/lodash/_createAssigner.js | 37 + app/node_modules/lodash/_createBaseEach.js | 32 + app/node_modules/lodash/_createBaseFor.js | 25 + app/node_modules/lodash/_createBind.js | 28 + app/node_modules/lodash/_createCaseFirst.js | 33 + app/node_modules/lodash/_createCompounder.js | 24 + app/node_modules/lodash/_createCtor.js | 37 + app/node_modules/lodash/_createCurry.js | 46 + app/node_modules/lodash/_createFind.js | 25 + app/node_modules/lodash/_createFlow.js | 78 + app/node_modules/lodash/_createHybrid.js | 92 + app/node_modules/lodash/_createInverter.js | 17 + .../lodash/_createMathOperation.js | 38 + app/node_modules/lodash/_createOver.js | 27 + app/node_modules/lodash/_createPadding.js | 33 + app/node_modules/lodash/_createPartial.js | 43 + app/node_modules/lodash/_createRange.js | 30 + app/node_modules/lodash/_createRecurry.js | 56 + .../lodash/_createRelationalOperation.js | 20 + app/node_modules/lodash/_createRound.js | 35 + app/node_modules/lodash/_createSet.js | 19 + app/node_modules/lodash/_createToPairs.js | 30 + app/node_modules/lodash/_createWrap.js | 106 + .../lodash/_customDefaultsAssignIn.js | 29 + .../lodash/_customDefaultsMerge.js | 28 + app/node_modules/lodash/_customOmitClone.js | 16 + app/node_modules/lodash/_deburrLetter.js | 71 + app/node_modules/lodash/_defineProperty.js | 11 + app/node_modules/lodash/_equalArrays.js | 83 + app/node_modules/lodash/_equalByTag.js | 112 + app/node_modules/lodash/_equalObjects.js | 89 + app/node_modules/lodash/_escapeHtmlChar.js | 21 + app/node_modules/lodash/_escapeStringChar.js | 22 + app/node_modules/lodash/_flatRest.js | 16 + app/node_modules/lodash/_freeGlobal.js | 4 + app/node_modules/lodash/_getAllKeys.js | 16 + app/node_modules/lodash/_getAllKeysIn.js | 17 + app/node_modules/lodash/_getData.js | 15 + app/node_modules/lodash/_getFuncName.js | 31 + app/node_modules/lodash/_getHolder.js | 13 + app/node_modules/lodash/_getMapData.js | 18 + app/node_modules/lodash/_getMatchData.js | 24 + app/node_modules/lodash/_getNative.js | 17 + app/node_modules/lodash/_getPrototype.js | 6 + app/node_modules/lodash/_getRawTag.js | 46 + app/node_modules/lodash/_getSymbols.js | 30 + app/node_modules/lodash/_getSymbolsIn.js | 25 + app/node_modules/lodash/_getTag.js | 58 + app/node_modules/lodash/_getValue.js | 13 + app/node_modules/lodash/_getView.js | 33 + app/node_modules/lodash/_getWrapDetails.js | 17 + app/node_modules/lodash/_hasPath.js | 39 + app/node_modules/lodash/_hasUnicode.js | 26 + app/node_modules/lodash/_hasUnicodeWord.js | 15 + app/node_modules/lodash/_hashClear.js | 15 + app/node_modules/lodash/_hashDelete.js | 17 + app/node_modules/lodash/_hashGet.js | 30 + app/node_modules/lodash/_hashHas.js | 23 + app/node_modules/lodash/_hashSet.js | 23 + app/node_modules/lodash/_initCloneArray.js | 26 + app/node_modules/lodash/_initCloneByTag.js | 77 + app/node_modules/lodash/_initCloneObject.js | 18 + app/node_modules/lodash/_insertWrapDetails.js | 23 + app/node_modules/lodash/_isFlattenable.js | 20 + app/node_modules/lodash/_isIndex.js | 25 + app/node_modules/lodash/_isIterateeCall.js | 30 + app/node_modules/lodash/_isKey.js | 29 + app/node_modules/lodash/_isKeyable.js | 15 + app/node_modules/lodash/_isLaziable.js | 28 + app/node_modules/lodash/_isMaskable.js | 14 + app/node_modules/lodash/_isMasked.js | 20 + app/node_modules/lodash/_isPrototype.js | 18 + .../lodash/_isStrictComparable.js | 15 + app/node_modules/lodash/_iteratorToArray.js | 18 + app/node_modules/lodash/_lazyClone.js | 23 + app/node_modules/lodash/_lazyReverse.js | 23 + app/node_modules/lodash/_lazyValue.js | 69 + app/node_modules/lodash/_listCacheClear.js | 13 + app/node_modules/lodash/_listCacheDelete.js | 35 + app/node_modules/lodash/_listCacheGet.js | 19 + app/node_modules/lodash/_listCacheHas.js | 16 + app/node_modules/lodash/_listCacheSet.js | 26 + app/node_modules/lodash/_mapCacheClear.js | 21 + app/node_modules/lodash/_mapCacheDelete.js | 18 + app/node_modules/lodash/_mapCacheGet.js | 16 + app/node_modules/lodash/_mapCacheHas.js | 16 + app/node_modules/lodash/_mapCacheSet.js | 22 + app/node_modules/lodash/_mapToArray.js | 18 + .../lodash/_matchesStrictComparable.js | 20 + app/node_modules/lodash/_memoizeCapped.js | 26 + app/node_modules/lodash/_mergeData.js | 90 + app/node_modules/lodash/_metaMap.js | 6 + app/node_modules/lodash/_nativeCreate.js | 6 + app/node_modules/lodash/_nativeKeys.js | 6 + app/node_modules/lodash/_nativeKeysIn.js | 20 + app/node_modules/lodash/_nodeUtil.js | 30 + app/node_modules/lodash/_objectToString.js | 22 + app/node_modules/lodash/_overArg.js | 15 + app/node_modules/lodash/_overRest.js | 36 + app/node_modules/lodash/_parent.js | 16 + app/node_modules/lodash/_reEscape.js | 4 + app/node_modules/lodash/_reEvaluate.js | 4 + app/node_modules/lodash/_reInterpolate.js | 4 + app/node_modules/lodash/_realNames.js | 4 + app/node_modules/lodash/_reorder.js | 29 + app/node_modules/lodash/_replaceHolders.js | 29 + app/node_modules/lodash/_root.js | 9 + app/node_modules/lodash/_safeGet.js | 21 + app/node_modules/lodash/_setCacheAdd.js | 19 + app/node_modules/lodash/_setCacheHas.js | 14 + app/node_modules/lodash/_setData.js | 20 + app/node_modules/lodash/_setToArray.js | 18 + app/node_modules/lodash/_setToPairs.js | 18 + app/node_modules/lodash/_setToString.js | 14 + app/node_modules/lodash/_setWrapToString.js | 21 + app/node_modules/lodash/_shortOut.js | 37 + app/node_modules/lodash/_shuffleSelf.js | 28 + app/node_modules/lodash/_stackClear.js | 15 + app/node_modules/lodash/_stackDelete.js | 18 + app/node_modules/lodash/_stackGet.js | 14 + app/node_modules/lodash/_stackHas.js | 14 + app/node_modules/lodash/_stackSet.js | 34 + app/node_modules/lodash/_strictIndexOf.js | 23 + app/node_modules/lodash/_strictLastIndexOf.js | 21 + app/node_modules/lodash/_stringSize.js | 18 + app/node_modules/lodash/_stringToArray.js | 18 + app/node_modules/lodash/_stringToPath.js | 27 + app/node_modules/lodash/_toKey.js | 21 + app/node_modules/lodash/_toSource.js | 26 + app/node_modules/lodash/_unescapeHtmlChar.js | 21 + app/node_modules/lodash/_unicodeSize.js | 44 + app/node_modules/lodash/_unicodeToArray.js | 40 + app/node_modules/lodash/_unicodeWords.js | 69 + app/node_modules/lodash/_updateWrapDetails.js | 46 + app/node_modules/lodash/_wrapperClone.js | 23 + app/node_modules/lodash/add.js | 22 + app/node_modules/lodash/after.js | 42 + app/node_modules/lodash/array.js | 67 + app/node_modules/lodash/ary.js | 29 + app/node_modules/lodash/assign.js | 58 + app/node_modules/lodash/assignIn.js | 40 + app/node_modules/lodash/assignInWith.js | 38 + app/node_modules/lodash/assignWith.js | 37 + app/node_modules/lodash/at.js | 23 + app/node_modules/lodash/attempt.js | 35 + app/node_modules/lodash/before.js | 40 + app/node_modules/lodash/bind.js | 57 + app/node_modules/lodash/bindAll.js | 41 + app/node_modules/lodash/bindKey.js | 68 + app/node_modules/lodash/camelCase.js | 29 + app/node_modules/lodash/capitalize.js | 23 + app/node_modules/lodash/castArray.js | 44 + app/node_modules/lodash/ceil.js | 26 + app/node_modules/lodash/chain.js | 38 + app/node_modules/lodash/chunk.js | 50 + app/node_modules/lodash/clamp.js | 39 + app/node_modules/lodash/clone.js | 36 + app/node_modules/lodash/cloneDeep.js | 29 + app/node_modules/lodash/cloneDeepWith.js | 40 + app/node_modules/lodash/cloneWith.js | 42 + app/node_modules/lodash/collection.js | 30 + app/node_modules/lodash/commit.js | 33 + app/node_modules/lodash/compact.js | 31 + app/node_modules/lodash/concat.js | 43 + app/node_modules/lodash/cond.js | 60 + app/node_modules/lodash/conforms.js | 35 + app/node_modules/lodash/conformsTo.js | 32 + app/node_modules/lodash/constant.js | 26 + app/node_modules/lodash/core.js | 3854 ++++ app/node_modules/lodash/core.min.js | 29 + app/node_modules/lodash/countBy.js | 40 + app/node_modules/lodash/create.js | 43 + app/node_modules/lodash/curry.js | 57 + app/node_modules/lodash/curryRight.js | 54 + app/node_modules/lodash/date.js | 3 + app/node_modules/lodash/debounce.js | 191 + app/node_modules/lodash/deburr.js | 45 + app/node_modules/lodash/defaultTo.js | 25 + app/node_modules/lodash/defaults.js | 64 + app/node_modules/lodash/defaultsDeep.js | 30 + app/node_modules/lodash/defer.js | 26 + app/node_modules/lodash/delay.js | 28 + app/node_modules/lodash/difference.js | 33 + app/node_modules/lodash/differenceBy.js | 44 + app/node_modules/lodash/differenceWith.js | 40 + app/node_modules/lodash/divide.js | 22 + app/node_modules/lodash/drop.js | 38 + app/node_modules/lodash/dropRight.js | 39 + app/node_modules/lodash/dropRightWhile.js | 45 + app/node_modules/lodash/dropWhile.js | 45 + app/node_modules/lodash/each.js | 1 + app/node_modules/lodash/eachRight.js | 1 + app/node_modules/lodash/endsWith.js | 43 + app/node_modules/lodash/entries.js | 1 + app/node_modules/lodash/entriesIn.js | 1 + app/node_modules/lodash/eq.js | 37 + app/node_modules/lodash/escape.js | 43 + app/node_modules/lodash/escapeRegExp.js | 32 + app/node_modules/lodash/every.js | 56 + app/node_modules/lodash/extend.js | 1 + app/node_modules/lodash/extendWith.js | 1 + app/node_modules/lodash/fill.js | 45 + app/node_modules/lodash/filter.js | 48 + app/node_modules/lodash/find.js | 42 + app/node_modules/lodash/findIndex.js | 55 + app/node_modules/lodash/findKey.js | 44 + app/node_modules/lodash/findLast.js | 25 + app/node_modules/lodash/findLastIndex.js | 59 + app/node_modules/lodash/findLastKey.js | 44 + app/node_modules/lodash/first.js | 1 + app/node_modules/lodash/flatMap.js | 29 + app/node_modules/lodash/flatMapDeep.js | 31 + app/node_modules/lodash/flatMapDepth.js | 31 + app/node_modules/lodash/flatten.js | 22 + app/node_modules/lodash/flattenDeep.js | 25 + app/node_modules/lodash/flattenDepth.js | 33 + app/node_modules/lodash/flip.js | 28 + app/node_modules/lodash/floor.js | 26 + app/node_modules/lodash/flow.js | 27 + app/node_modules/lodash/flowRight.js | 26 + app/node_modules/lodash/forEach.js | 41 + app/node_modules/lodash/forEachRight.js | 31 + app/node_modules/lodash/forIn.js | 39 + app/node_modules/lodash/forInRight.js | 37 + app/node_modules/lodash/forOwn.js | 36 + app/node_modules/lodash/forOwnRight.js | 34 + app/node_modules/lodash/fp.js | 2 + app/node_modules/lodash/fp/F.js | 1 + app/node_modules/lodash/fp/T.js | 1 + app/node_modules/lodash/fp/__.js | 1 + app/node_modules/lodash/fp/_baseConvert.js | 569 + app/node_modules/lodash/fp/_convertBrowser.js | 18 + app/node_modules/lodash/fp/_falseOptions.js | 7 + app/node_modules/lodash/fp/_mapping.js | 358 + app/node_modules/lodash/fp/_util.js | 16 + app/node_modules/lodash/fp/add.js | 5 + app/node_modules/lodash/fp/after.js | 5 + app/node_modules/lodash/fp/all.js | 1 + app/node_modules/lodash/fp/allPass.js | 1 + app/node_modules/lodash/fp/always.js | 1 + app/node_modules/lodash/fp/any.js | 1 + app/node_modules/lodash/fp/anyPass.js | 1 + app/node_modules/lodash/fp/apply.js | 1 + app/node_modules/lodash/fp/array.js | 2 + app/node_modules/lodash/fp/ary.js | 5 + app/node_modules/lodash/fp/assign.js | 5 + app/node_modules/lodash/fp/assignAll.js | 5 + app/node_modules/lodash/fp/assignAllWith.js | 5 + app/node_modules/lodash/fp/assignIn.js | 5 + app/node_modules/lodash/fp/assignInAll.js | 5 + app/node_modules/lodash/fp/assignInAllWith.js | 5 + app/node_modules/lodash/fp/assignInWith.js | 5 + app/node_modules/lodash/fp/assignWith.js | 5 + app/node_modules/lodash/fp/assoc.js | 1 + app/node_modules/lodash/fp/assocPath.js | 1 + app/node_modules/lodash/fp/at.js | 5 + app/node_modules/lodash/fp/attempt.js | 5 + app/node_modules/lodash/fp/before.js | 5 + app/node_modules/lodash/fp/bind.js | 5 + app/node_modules/lodash/fp/bindAll.js | 5 + app/node_modules/lodash/fp/bindKey.js | 5 + app/node_modules/lodash/fp/camelCase.js | 5 + app/node_modules/lodash/fp/capitalize.js | 5 + app/node_modules/lodash/fp/castArray.js | 5 + app/node_modules/lodash/fp/ceil.js | 5 + app/node_modules/lodash/fp/chain.js | 5 + app/node_modules/lodash/fp/chunk.js | 5 + app/node_modules/lodash/fp/clamp.js | 5 + app/node_modules/lodash/fp/clone.js | 5 + app/node_modules/lodash/fp/cloneDeep.js | 5 + app/node_modules/lodash/fp/cloneDeepWith.js | 5 + app/node_modules/lodash/fp/cloneWith.js | 5 + app/node_modules/lodash/fp/collection.js | 2 + app/node_modules/lodash/fp/commit.js | 5 + app/node_modules/lodash/fp/compact.js | 5 + app/node_modules/lodash/fp/complement.js | 1 + app/node_modules/lodash/fp/compose.js | 1 + app/node_modules/lodash/fp/concat.js | 5 + app/node_modules/lodash/fp/cond.js | 5 + app/node_modules/lodash/fp/conforms.js | 1 + app/node_modules/lodash/fp/conformsTo.js | 5 + app/node_modules/lodash/fp/constant.js | 5 + app/node_modules/lodash/fp/contains.js | 1 + app/node_modules/lodash/fp/convert.js | 18 + app/node_modules/lodash/fp/countBy.js | 5 + app/node_modules/lodash/fp/create.js | 5 + app/node_modules/lodash/fp/curry.js | 5 + app/node_modules/lodash/fp/curryN.js | 5 + app/node_modules/lodash/fp/curryRight.js | 5 + app/node_modules/lodash/fp/curryRightN.js | 5 + app/node_modules/lodash/fp/date.js | 2 + app/node_modules/lodash/fp/debounce.js | 5 + app/node_modules/lodash/fp/deburr.js | 5 + app/node_modules/lodash/fp/defaultTo.js | 5 + app/node_modules/lodash/fp/defaults.js | 5 + app/node_modules/lodash/fp/defaultsAll.js | 5 + app/node_modules/lodash/fp/defaultsDeep.js | 5 + app/node_modules/lodash/fp/defaultsDeepAll.js | 5 + app/node_modules/lodash/fp/defer.js | 5 + app/node_modules/lodash/fp/delay.js | 5 + app/node_modules/lodash/fp/difference.js | 5 + app/node_modules/lodash/fp/differenceBy.js | 5 + app/node_modules/lodash/fp/differenceWith.js | 5 + app/node_modules/lodash/fp/dissoc.js | 1 + app/node_modules/lodash/fp/dissocPath.js | 1 + app/node_modules/lodash/fp/divide.js | 5 + app/node_modules/lodash/fp/drop.js | 5 + app/node_modules/lodash/fp/dropLast.js | 1 + app/node_modules/lodash/fp/dropLastWhile.js | 1 + app/node_modules/lodash/fp/dropRight.js | 5 + app/node_modules/lodash/fp/dropRightWhile.js | 5 + app/node_modules/lodash/fp/dropWhile.js | 5 + app/node_modules/lodash/fp/each.js | 1 + app/node_modules/lodash/fp/eachRight.js | 1 + app/node_modules/lodash/fp/endsWith.js | 5 + app/node_modules/lodash/fp/entries.js | 1 + app/node_modules/lodash/fp/entriesIn.js | 1 + app/node_modules/lodash/fp/eq.js | 5 + app/node_modules/lodash/fp/equals.js | 1 + app/node_modules/lodash/fp/escape.js | 5 + app/node_modules/lodash/fp/escapeRegExp.js | 5 + app/node_modules/lodash/fp/every.js | 5 + app/node_modules/lodash/fp/extend.js | 1 + app/node_modules/lodash/fp/extendAll.js | 1 + app/node_modules/lodash/fp/extendAllWith.js | 1 + app/node_modules/lodash/fp/extendWith.js | 1 + app/node_modules/lodash/fp/fill.js | 5 + app/node_modules/lodash/fp/filter.js | 5 + app/node_modules/lodash/fp/find.js | 5 + app/node_modules/lodash/fp/findFrom.js | 5 + app/node_modules/lodash/fp/findIndex.js | 5 + app/node_modules/lodash/fp/findIndexFrom.js | 5 + app/node_modules/lodash/fp/findKey.js | 5 + app/node_modules/lodash/fp/findLast.js | 5 + app/node_modules/lodash/fp/findLastFrom.js | 5 + app/node_modules/lodash/fp/findLastIndex.js | 5 + .../lodash/fp/findLastIndexFrom.js | 5 + app/node_modules/lodash/fp/findLastKey.js | 5 + app/node_modules/lodash/fp/first.js | 1 + app/node_modules/lodash/fp/flatMap.js | 5 + app/node_modules/lodash/fp/flatMapDeep.js | 5 + app/node_modules/lodash/fp/flatMapDepth.js | 5 + app/node_modules/lodash/fp/flatten.js | 5 + app/node_modules/lodash/fp/flattenDeep.js | 5 + app/node_modules/lodash/fp/flattenDepth.js | 5 + app/node_modules/lodash/fp/flip.js | 5 + app/node_modules/lodash/fp/floor.js | 5 + app/node_modules/lodash/fp/flow.js | 5 + app/node_modules/lodash/fp/flowRight.js | 5 + app/node_modules/lodash/fp/forEach.js | 5 + app/node_modules/lodash/fp/forEachRight.js | 5 + app/node_modules/lodash/fp/forIn.js | 5 + app/node_modules/lodash/fp/forInRight.js | 5 + app/node_modules/lodash/fp/forOwn.js | 5 + app/node_modules/lodash/fp/forOwnRight.js | 5 + app/node_modules/lodash/fp/fromPairs.js | 5 + app/node_modules/lodash/fp/function.js | 2 + app/node_modules/lodash/fp/functions.js | 5 + app/node_modules/lodash/fp/functionsIn.js | 5 + app/node_modules/lodash/fp/get.js | 5 + app/node_modules/lodash/fp/getOr.js | 5 + app/node_modules/lodash/fp/groupBy.js | 5 + app/node_modules/lodash/fp/gt.js | 5 + app/node_modules/lodash/fp/gte.js | 5 + app/node_modules/lodash/fp/has.js | 5 + app/node_modules/lodash/fp/hasIn.js | 5 + app/node_modules/lodash/fp/head.js | 5 + app/node_modules/lodash/fp/identical.js | 1 + app/node_modules/lodash/fp/identity.js | 5 + app/node_modules/lodash/fp/inRange.js | 5 + app/node_modules/lodash/fp/includes.js | 5 + app/node_modules/lodash/fp/includesFrom.js | 5 + app/node_modules/lodash/fp/indexBy.js | 1 + app/node_modules/lodash/fp/indexOf.js | 5 + app/node_modules/lodash/fp/indexOfFrom.js | 5 + app/node_modules/lodash/fp/init.js | 1 + app/node_modules/lodash/fp/initial.js | 5 + app/node_modules/lodash/fp/intersection.js | 5 + app/node_modules/lodash/fp/intersectionBy.js | 5 + .../lodash/fp/intersectionWith.js | 5 + app/node_modules/lodash/fp/invert.js | 5 + app/node_modules/lodash/fp/invertBy.js | 5 + app/node_modules/lodash/fp/invertObj.js | 1 + app/node_modules/lodash/fp/invoke.js | 5 + app/node_modules/lodash/fp/invokeArgs.js | 5 + app/node_modules/lodash/fp/invokeArgsMap.js | 5 + app/node_modules/lodash/fp/invokeMap.js | 5 + app/node_modules/lodash/fp/isArguments.js | 5 + app/node_modules/lodash/fp/isArray.js | 5 + app/node_modules/lodash/fp/isArrayBuffer.js | 5 + app/node_modules/lodash/fp/isArrayLike.js | 5 + .../lodash/fp/isArrayLikeObject.js | 5 + app/node_modules/lodash/fp/isBoolean.js | 5 + app/node_modules/lodash/fp/isBuffer.js | 5 + app/node_modules/lodash/fp/isDate.js | 5 + app/node_modules/lodash/fp/isElement.js | 5 + app/node_modules/lodash/fp/isEmpty.js | 5 + app/node_modules/lodash/fp/isEqual.js | 5 + app/node_modules/lodash/fp/isEqualWith.js | 5 + app/node_modules/lodash/fp/isError.js | 5 + app/node_modules/lodash/fp/isFinite.js | 5 + app/node_modules/lodash/fp/isFunction.js | 5 + app/node_modules/lodash/fp/isInteger.js | 5 + app/node_modules/lodash/fp/isLength.js | 5 + app/node_modules/lodash/fp/isMap.js | 5 + app/node_modules/lodash/fp/isMatch.js | 5 + app/node_modules/lodash/fp/isMatchWith.js | 5 + app/node_modules/lodash/fp/isNaN.js | 5 + app/node_modules/lodash/fp/isNative.js | 5 + app/node_modules/lodash/fp/isNil.js | 5 + app/node_modules/lodash/fp/isNull.js | 5 + app/node_modules/lodash/fp/isNumber.js | 5 + app/node_modules/lodash/fp/isObject.js | 5 + app/node_modules/lodash/fp/isObjectLike.js | 5 + app/node_modules/lodash/fp/isPlainObject.js | 5 + app/node_modules/lodash/fp/isRegExp.js | 5 + app/node_modules/lodash/fp/isSafeInteger.js | 5 + app/node_modules/lodash/fp/isSet.js | 5 + app/node_modules/lodash/fp/isString.js | 5 + app/node_modules/lodash/fp/isSymbol.js | 5 + app/node_modules/lodash/fp/isTypedArray.js | 5 + app/node_modules/lodash/fp/isUndefined.js | 5 + app/node_modules/lodash/fp/isWeakMap.js | 5 + app/node_modules/lodash/fp/isWeakSet.js | 5 + app/node_modules/lodash/fp/iteratee.js | 5 + app/node_modules/lodash/fp/join.js | 5 + app/node_modules/lodash/fp/juxt.js | 1 + app/node_modules/lodash/fp/kebabCase.js | 5 + app/node_modules/lodash/fp/keyBy.js | 5 + app/node_modules/lodash/fp/keys.js | 5 + app/node_modules/lodash/fp/keysIn.js | 5 + app/node_modules/lodash/fp/lang.js | 2 + app/node_modules/lodash/fp/last.js | 5 + app/node_modules/lodash/fp/lastIndexOf.js | 5 + app/node_modules/lodash/fp/lastIndexOfFrom.js | 5 + app/node_modules/lodash/fp/lowerCase.js | 5 + app/node_modules/lodash/fp/lowerFirst.js | 5 + app/node_modules/lodash/fp/lt.js | 5 + app/node_modules/lodash/fp/lte.js | 5 + app/node_modules/lodash/fp/map.js | 5 + app/node_modules/lodash/fp/mapKeys.js | 5 + app/node_modules/lodash/fp/mapValues.js | 5 + app/node_modules/lodash/fp/matches.js | 1 + app/node_modules/lodash/fp/matchesProperty.js | 5 + app/node_modules/lodash/fp/math.js | 2 + app/node_modules/lodash/fp/max.js | 5 + app/node_modules/lodash/fp/maxBy.js | 5 + app/node_modules/lodash/fp/mean.js | 5 + app/node_modules/lodash/fp/meanBy.js | 5 + app/node_modules/lodash/fp/memoize.js | 5 + app/node_modules/lodash/fp/merge.js | 5 + app/node_modules/lodash/fp/mergeAll.js | 5 + app/node_modules/lodash/fp/mergeAllWith.js | 5 + app/node_modules/lodash/fp/mergeWith.js | 5 + app/node_modules/lodash/fp/method.js | 5 + app/node_modules/lodash/fp/methodOf.js | 5 + app/node_modules/lodash/fp/min.js | 5 + app/node_modules/lodash/fp/minBy.js | 5 + app/node_modules/lodash/fp/mixin.js | 5 + app/node_modules/lodash/fp/multiply.js | 5 + app/node_modules/lodash/fp/nAry.js | 1 + app/node_modules/lodash/fp/negate.js | 5 + app/node_modules/lodash/fp/next.js | 5 + app/node_modules/lodash/fp/noop.js | 5 + app/node_modules/lodash/fp/now.js | 5 + app/node_modules/lodash/fp/nth.js | 5 + app/node_modules/lodash/fp/nthArg.js | 5 + app/node_modules/lodash/fp/number.js | 2 + app/node_modules/lodash/fp/object.js | 2 + app/node_modules/lodash/fp/omit.js | 5 + app/node_modules/lodash/fp/omitAll.js | 1 + app/node_modules/lodash/fp/omitBy.js | 5 + app/node_modules/lodash/fp/once.js | 5 + app/node_modules/lodash/fp/orderBy.js | 5 + app/node_modules/lodash/fp/over.js | 5 + app/node_modules/lodash/fp/overArgs.js | 5 + app/node_modules/lodash/fp/overEvery.js | 5 + app/node_modules/lodash/fp/overSome.js | 5 + app/node_modules/lodash/fp/pad.js | 5 + app/node_modules/lodash/fp/padChars.js | 5 + app/node_modules/lodash/fp/padCharsEnd.js | 5 + app/node_modules/lodash/fp/padCharsStart.js | 5 + app/node_modules/lodash/fp/padEnd.js | 5 + app/node_modules/lodash/fp/padStart.js | 5 + app/node_modules/lodash/fp/parseInt.js | 5 + app/node_modules/lodash/fp/partial.js | 5 + app/node_modules/lodash/fp/partialRight.js | 5 + app/node_modules/lodash/fp/partition.js | 5 + app/node_modules/lodash/fp/path.js | 1 + app/node_modules/lodash/fp/pathEq.js | 1 + app/node_modules/lodash/fp/pathOr.js | 1 + app/node_modules/lodash/fp/paths.js | 1 + app/node_modules/lodash/fp/pick.js | 5 + app/node_modules/lodash/fp/pickAll.js | 1 + app/node_modules/lodash/fp/pickBy.js | 5 + app/node_modules/lodash/fp/pipe.js | 1 + app/node_modules/lodash/fp/placeholder.js | 6 + app/node_modules/lodash/fp/plant.js | 5 + app/node_modules/lodash/fp/pluck.js | 1 + app/node_modules/lodash/fp/prop.js | 1 + app/node_modules/lodash/fp/propEq.js | 1 + app/node_modules/lodash/fp/propOr.js | 1 + app/node_modules/lodash/fp/property.js | 1 + app/node_modules/lodash/fp/propertyOf.js | 5 + app/node_modules/lodash/fp/props.js | 1 + app/node_modules/lodash/fp/pull.js | 5 + app/node_modules/lodash/fp/pullAll.js | 5 + app/node_modules/lodash/fp/pullAllBy.js | 5 + app/node_modules/lodash/fp/pullAllWith.js | 5 + app/node_modules/lodash/fp/pullAt.js | 5 + app/node_modules/lodash/fp/random.js | 5 + app/node_modules/lodash/fp/range.js | 5 + app/node_modules/lodash/fp/rangeRight.js | 5 + app/node_modules/lodash/fp/rangeStep.js | 5 + app/node_modules/lodash/fp/rangeStepRight.js | 5 + app/node_modules/lodash/fp/rearg.js | 5 + app/node_modules/lodash/fp/reduce.js | 5 + app/node_modules/lodash/fp/reduceRight.js | 5 + app/node_modules/lodash/fp/reject.js | 5 + app/node_modules/lodash/fp/remove.js | 5 + app/node_modules/lodash/fp/repeat.js | 5 + app/node_modules/lodash/fp/replace.js | 5 + app/node_modules/lodash/fp/rest.js | 5 + app/node_modules/lodash/fp/restFrom.js | 5 + app/node_modules/lodash/fp/result.js | 5 + app/node_modules/lodash/fp/reverse.js | 5 + app/node_modules/lodash/fp/round.js | 5 + app/node_modules/lodash/fp/sample.js | 5 + app/node_modules/lodash/fp/sampleSize.js | 5 + app/node_modules/lodash/fp/seq.js | 2 + app/node_modules/lodash/fp/set.js | 5 + app/node_modules/lodash/fp/setWith.js | 5 + app/node_modules/lodash/fp/shuffle.js | 5 + app/node_modules/lodash/fp/size.js | 5 + app/node_modules/lodash/fp/slice.js | 5 + app/node_modules/lodash/fp/snakeCase.js | 5 + app/node_modules/lodash/fp/some.js | 5 + app/node_modules/lodash/fp/sortBy.js | 5 + app/node_modules/lodash/fp/sortedIndex.js | 5 + app/node_modules/lodash/fp/sortedIndexBy.js | 5 + app/node_modules/lodash/fp/sortedIndexOf.js | 5 + app/node_modules/lodash/fp/sortedLastIndex.js | 5 + .../lodash/fp/sortedLastIndexBy.js | 5 + .../lodash/fp/sortedLastIndexOf.js | 5 + app/node_modules/lodash/fp/sortedUniq.js | 5 + app/node_modules/lodash/fp/sortedUniqBy.js | 5 + app/node_modules/lodash/fp/split.js | 5 + app/node_modules/lodash/fp/spread.js | 5 + app/node_modules/lodash/fp/spreadFrom.js | 5 + app/node_modules/lodash/fp/startCase.js | 5 + app/node_modules/lodash/fp/startsWith.js | 5 + app/node_modules/lodash/fp/string.js | 2 + app/node_modules/lodash/fp/stubArray.js | 5 + app/node_modules/lodash/fp/stubFalse.js | 5 + app/node_modules/lodash/fp/stubObject.js | 5 + app/node_modules/lodash/fp/stubString.js | 5 + app/node_modules/lodash/fp/stubTrue.js | 5 + app/node_modules/lodash/fp/subtract.js | 5 + app/node_modules/lodash/fp/sum.js | 5 + app/node_modules/lodash/fp/sumBy.js | 5 + .../lodash/fp/symmetricDifference.js | 1 + .../lodash/fp/symmetricDifferenceBy.js | 1 + .../lodash/fp/symmetricDifferenceWith.js | 1 + app/node_modules/lodash/fp/tail.js | 5 + app/node_modules/lodash/fp/take.js | 5 + app/node_modules/lodash/fp/takeLast.js | 1 + app/node_modules/lodash/fp/takeLastWhile.js | 1 + app/node_modules/lodash/fp/takeRight.js | 5 + app/node_modules/lodash/fp/takeRightWhile.js | 5 + app/node_modules/lodash/fp/takeWhile.js | 5 + app/node_modules/lodash/fp/tap.js | 5 + app/node_modules/lodash/fp/template.js | 5 + .../lodash/fp/templateSettings.js | 5 + app/node_modules/lodash/fp/throttle.js | 5 + app/node_modules/lodash/fp/thru.js | 5 + app/node_modules/lodash/fp/times.js | 5 + app/node_modules/lodash/fp/toArray.js | 5 + app/node_modules/lodash/fp/toFinite.js | 5 + app/node_modules/lodash/fp/toInteger.js | 5 + app/node_modules/lodash/fp/toIterator.js | 5 + app/node_modules/lodash/fp/toJSON.js | 5 + app/node_modules/lodash/fp/toLength.js | 5 + app/node_modules/lodash/fp/toLower.js | 5 + app/node_modules/lodash/fp/toNumber.js | 5 + app/node_modules/lodash/fp/toPairs.js | 5 + app/node_modules/lodash/fp/toPairsIn.js | 5 + app/node_modules/lodash/fp/toPath.js | 5 + app/node_modules/lodash/fp/toPlainObject.js | 5 + app/node_modules/lodash/fp/toSafeInteger.js | 5 + app/node_modules/lodash/fp/toString.js | 5 + app/node_modules/lodash/fp/toUpper.js | 5 + app/node_modules/lodash/fp/transform.js | 5 + app/node_modules/lodash/fp/trim.js | 5 + app/node_modules/lodash/fp/trimChars.js | 5 + app/node_modules/lodash/fp/trimCharsEnd.js | 5 + app/node_modules/lodash/fp/trimCharsStart.js | 5 + app/node_modules/lodash/fp/trimEnd.js | 5 + app/node_modules/lodash/fp/trimStart.js | 5 + app/node_modules/lodash/fp/truncate.js | 5 + app/node_modules/lodash/fp/unapply.js | 1 + app/node_modules/lodash/fp/unary.js | 5 + app/node_modules/lodash/fp/unescape.js | 5 + app/node_modules/lodash/fp/union.js | 5 + app/node_modules/lodash/fp/unionBy.js | 5 + app/node_modules/lodash/fp/unionWith.js | 5 + app/node_modules/lodash/fp/uniq.js | 5 + app/node_modules/lodash/fp/uniqBy.js | 5 + app/node_modules/lodash/fp/uniqWith.js | 5 + app/node_modules/lodash/fp/uniqueId.js | 5 + app/node_modules/lodash/fp/unnest.js | 1 + app/node_modules/lodash/fp/unset.js | 5 + app/node_modules/lodash/fp/unzip.js | 5 + app/node_modules/lodash/fp/unzipWith.js | 5 + app/node_modules/lodash/fp/update.js | 5 + app/node_modules/lodash/fp/updateWith.js | 5 + app/node_modules/lodash/fp/upperCase.js | 5 + app/node_modules/lodash/fp/upperFirst.js | 5 + app/node_modules/lodash/fp/useWith.js | 1 + app/node_modules/lodash/fp/util.js | 2 + app/node_modules/lodash/fp/value.js | 5 + app/node_modules/lodash/fp/valueOf.js | 5 + app/node_modules/lodash/fp/values.js | 5 + app/node_modules/lodash/fp/valuesIn.js | 5 + app/node_modules/lodash/fp/where.js | 1 + app/node_modules/lodash/fp/whereEq.js | 1 + app/node_modules/lodash/fp/without.js | 5 + app/node_modules/lodash/fp/words.js | 5 + app/node_modules/lodash/fp/wrap.js | 5 + app/node_modules/lodash/fp/wrapperAt.js | 5 + app/node_modules/lodash/fp/wrapperChain.js | 5 + app/node_modules/lodash/fp/wrapperLodash.js | 5 + app/node_modules/lodash/fp/wrapperReverse.js | 5 + app/node_modules/lodash/fp/wrapperValue.js | 5 + app/node_modules/lodash/fp/xor.js | 5 + app/node_modules/lodash/fp/xorBy.js | 5 + app/node_modules/lodash/fp/xorWith.js | 5 + app/node_modules/lodash/fp/zip.js | 5 + app/node_modules/lodash/fp/zipAll.js | 5 + app/node_modules/lodash/fp/zipObj.js | 1 + app/node_modules/lodash/fp/zipObject.js | 5 + app/node_modules/lodash/fp/zipObjectDeep.js | 5 + app/node_modules/lodash/fp/zipWith.js | 5 + app/node_modules/lodash/fromPairs.js | 28 + app/node_modules/lodash/function.js | 25 + app/node_modules/lodash/functions.js | 31 + app/node_modules/lodash/functionsIn.js | 31 + app/node_modules/lodash/get.js | 33 + app/node_modules/lodash/groupBy.js | 41 + app/node_modules/lodash/gt.js | 29 + app/node_modules/lodash/gte.js | 30 + app/node_modules/lodash/has.js | 35 + app/node_modules/lodash/hasIn.js | 34 + app/node_modules/lodash/head.js | 23 + app/node_modules/lodash/identity.js | 21 + app/node_modules/lodash/inRange.js | 55 + app/node_modules/lodash/includes.js | 53 + app/node_modules/lodash/index.js | 1 + app/node_modules/lodash/indexOf.js | 42 + app/node_modules/lodash/initial.js | 22 + app/node_modules/lodash/intersection.js | 30 + app/node_modules/lodash/intersectionBy.js | 45 + app/node_modules/lodash/intersectionWith.js | 41 + app/node_modules/lodash/invert.js | 42 + app/node_modules/lodash/invertBy.js | 56 + app/node_modules/lodash/invoke.js | 24 + app/node_modules/lodash/invokeMap.js | 41 + app/node_modules/lodash/isArguments.js | 36 + app/node_modules/lodash/isArray.js | 26 + app/node_modules/lodash/isArrayBuffer.js | 27 + app/node_modules/lodash/isArrayLike.js | 33 + app/node_modules/lodash/isArrayLikeObject.js | 33 + app/node_modules/lodash/isBoolean.js | 29 + app/node_modules/lodash/isBuffer.js | 38 + app/node_modules/lodash/isDate.js | 27 + app/node_modules/lodash/isElement.js | 25 + app/node_modules/lodash/isEmpty.js | 77 + app/node_modules/lodash/isEqual.js | 35 + app/node_modules/lodash/isEqualWith.js | 41 + app/node_modules/lodash/isError.js | 36 + app/node_modules/lodash/isFinite.js | 36 + app/node_modules/lodash/isFunction.js | 37 + app/node_modules/lodash/isInteger.js | 33 + app/node_modules/lodash/isLength.js | 35 + app/node_modules/lodash/isMap.js | 27 + app/node_modules/lodash/isMatch.js | 36 + app/node_modules/lodash/isMatchWith.js | 41 + app/node_modules/lodash/isNaN.js | 38 + app/node_modules/lodash/isNative.js | 40 + app/node_modules/lodash/isNil.js | 25 + app/node_modules/lodash/isNull.js | 22 + app/node_modules/lodash/isNumber.js | 38 + app/node_modules/lodash/isObject.js | 31 + app/node_modules/lodash/isObjectLike.js | 29 + app/node_modules/lodash/isPlainObject.js | 62 + app/node_modules/lodash/isRegExp.js | 27 + app/node_modules/lodash/isSafeInteger.js | 37 + app/node_modules/lodash/isSet.js | 27 + app/node_modules/lodash/isString.js | 30 + app/node_modules/lodash/isSymbol.js | 29 + app/node_modules/lodash/isTypedArray.js | 27 + app/node_modules/lodash/isUndefined.js | 22 + app/node_modules/lodash/isWeakMap.js | 28 + app/node_modules/lodash/isWeakSet.js | 28 + app/node_modules/lodash/iteratee.js | 53 + app/node_modules/lodash/join.js | 26 + app/node_modules/lodash/kebabCase.js | 28 + app/node_modules/lodash/keyBy.js | 36 + app/node_modules/lodash/keys.js | 37 + app/node_modules/lodash/keysIn.js | 32 + app/node_modules/lodash/lang.js | 58 + app/node_modules/lodash/last.js | 20 + app/node_modules/lodash/lastIndexOf.js | 46 + app/node_modules/lodash/lodash.js | 17112 +++++++++++++++ app/node_modules/lodash/lodash.min.js | 137 + app/node_modules/lodash/lowerCase.js | 27 + app/node_modules/lodash/lowerFirst.js | 22 + app/node_modules/lodash/lt.js | 29 + app/node_modules/lodash/lte.js | 30 + app/node_modules/lodash/map.js | 53 + app/node_modules/lodash/mapKeys.js | 36 + app/node_modules/lodash/mapValues.js | 43 + app/node_modules/lodash/matches.js | 39 + app/node_modules/lodash/matchesProperty.js | 37 + app/node_modules/lodash/math.js | 17 + app/node_modules/lodash/max.js | 29 + app/node_modules/lodash/maxBy.js | 34 + app/node_modules/lodash/mean.js | 22 + app/node_modules/lodash/meanBy.js | 31 + app/node_modules/lodash/memoize.js | 73 + app/node_modules/lodash/merge.js | 39 + app/node_modules/lodash/mergeWith.js | 39 + app/node_modules/lodash/method.js | 34 + app/node_modules/lodash/methodOf.js | 33 + app/node_modules/lodash/min.js | 29 + app/node_modules/lodash/minBy.js | 34 + app/node_modules/lodash/mixin.js | 74 + app/node_modules/lodash/multiply.js | 22 + app/node_modules/lodash/negate.js | 40 + app/node_modules/lodash/next.js | 35 + app/node_modules/lodash/noop.js | 17 + app/node_modules/lodash/now.js | 23 + app/node_modules/lodash/nth.js | 29 + app/node_modules/lodash/nthArg.js | 32 + app/node_modules/lodash/number.js | 5 + app/node_modules/lodash/object.js | 49 + app/node_modules/lodash/omit.js | 57 + app/node_modules/lodash/omitBy.js | 29 + app/node_modules/lodash/once.js | 25 + app/node_modules/lodash/orderBy.js | 47 + app/node_modules/lodash/over.js | 24 + app/node_modules/lodash/overArgs.js | 61 + app/node_modules/lodash/overEvery.js | 30 + app/node_modules/lodash/overSome.js | 30 + app/node_modules/lodash/package.json | 17 + app/node_modules/lodash/pad.js | 49 + app/node_modules/lodash/padEnd.js | 39 + app/node_modules/lodash/padStart.js | 39 + app/node_modules/lodash/parseInt.js | 43 + app/node_modules/lodash/partial.js | 50 + app/node_modules/lodash/partialRight.js | 49 + app/node_modules/lodash/partition.js | 43 + app/node_modules/lodash/pick.js | 25 + app/node_modules/lodash/pickBy.js | 37 + app/node_modules/lodash/plant.js | 48 + app/node_modules/lodash/property.js | 32 + app/node_modules/lodash/propertyOf.js | 30 + app/node_modules/lodash/pull.js | 29 + app/node_modules/lodash/pullAll.js | 29 + app/node_modules/lodash/pullAllBy.js | 33 + app/node_modules/lodash/pullAllWith.js | 32 + app/node_modules/lodash/pullAt.js | 43 + app/node_modules/lodash/random.js | 82 + app/node_modules/lodash/range.js | 46 + app/node_modules/lodash/rangeRight.js | 41 + app/node_modules/lodash/rearg.js | 33 + app/node_modules/lodash/reduce.js | 51 + app/node_modules/lodash/reduceRight.js | 36 + app/node_modules/lodash/reject.js | 46 + app/node_modules/lodash/remove.js | 53 + app/node_modules/lodash/repeat.js | 37 + app/node_modules/lodash/replace.js | 29 + app/node_modules/lodash/rest.js | 40 + app/node_modules/lodash/result.js | 56 + app/node_modules/lodash/reverse.js | 34 + app/node_modules/lodash/round.js | 26 + app/node_modules/lodash/sample.js | 24 + app/node_modules/lodash/sampleSize.js | 37 + app/node_modules/lodash/seq.js | 16 + app/node_modules/lodash/set.js | 35 + app/node_modules/lodash/setWith.js | 32 + app/node_modules/lodash/shuffle.js | 25 + app/node_modules/lodash/size.js | 46 + app/node_modules/lodash/slice.js | 37 + app/node_modules/lodash/snakeCase.js | 28 + app/node_modules/lodash/some.js | 51 + app/node_modules/lodash/sortBy.js | 48 + app/node_modules/lodash/sortedIndex.js | 24 + app/node_modules/lodash/sortedIndexBy.js | 33 + app/node_modules/lodash/sortedIndexOf.js | 31 + app/node_modules/lodash/sortedLastIndex.js | 25 + app/node_modules/lodash/sortedLastIndexBy.js | 33 + app/node_modules/lodash/sortedLastIndexOf.js | 31 + app/node_modules/lodash/sortedUniq.js | 24 + app/node_modules/lodash/sortedUniqBy.js | 26 + app/node_modules/lodash/split.js | 52 + app/node_modules/lodash/spread.js | 63 + app/node_modules/lodash/startCase.js | 29 + app/node_modules/lodash/startsWith.js | 39 + app/node_modules/lodash/string.js | 33 + app/node_modules/lodash/stubArray.js | 23 + app/node_modules/lodash/stubFalse.js | 18 + app/node_modules/lodash/stubObject.js | 23 + app/node_modules/lodash/stubString.js | 18 + app/node_modules/lodash/stubTrue.js | 18 + app/node_modules/lodash/subtract.js | 22 + app/node_modules/lodash/sum.js | 24 + app/node_modules/lodash/sumBy.js | 33 + app/node_modules/lodash/tail.js | 22 + app/node_modules/lodash/take.js | 37 + app/node_modules/lodash/takeRight.js | 39 + app/node_modules/lodash/takeRightWhile.js | 45 + app/node_modules/lodash/takeWhile.js | 45 + app/node_modules/lodash/tap.js | 29 + app/node_modules/lodash/template.js | 253 + app/node_modules/lodash/templateSettings.js | 67 + app/node_modules/lodash/throttle.js | 69 + app/node_modules/lodash/thru.js | 28 + app/node_modules/lodash/times.js | 51 + app/node_modules/lodash/toArray.js | 58 + app/node_modules/lodash/toFinite.js | 42 + app/node_modules/lodash/toInteger.js | 36 + app/node_modules/lodash/toIterator.js | 23 + app/node_modules/lodash/toJSON.js | 1 + app/node_modules/lodash/toLength.js | 38 + app/node_modules/lodash/toLower.js | 28 + app/node_modules/lodash/toNumber.js | 66 + app/node_modules/lodash/toPairs.js | 30 + app/node_modules/lodash/toPairsIn.js | 30 + app/node_modules/lodash/toPath.js | 33 + app/node_modules/lodash/toPlainObject.js | 32 + app/node_modules/lodash/toSafeInteger.js | 37 + app/node_modules/lodash/toString.js | 28 + app/node_modules/lodash/toUpper.js | 28 + app/node_modules/lodash/transform.js | 65 + app/node_modules/lodash/trim.js | 49 + app/node_modules/lodash/trimEnd.js | 43 + app/node_modules/lodash/trimStart.js | 43 + app/node_modules/lodash/truncate.js | 111 + app/node_modules/lodash/unary.js | 22 + app/node_modules/lodash/unescape.js | 34 + app/node_modules/lodash/union.js | 26 + app/node_modules/lodash/unionBy.js | 39 + app/node_modules/lodash/unionWith.js | 34 + app/node_modules/lodash/uniq.js | 25 + app/node_modules/lodash/uniqBy.js | 31 + app/node_modules/lodash/uniqWith.js | 28 + app/node_modules/lodash/uniqueId.js | 28 + app/node_modules/lodash/unset.js | 34 + app/node_modules/lodash/unzip.js | 45 + app/node_modules/lodash/unzipWith.js | 39 + app/node_modules/lodash/update.js | 35 + app/node_modules/lodash/updateWith.js | 33 + app/node_modules/lodash/upperCase.js | 27 + app/node_modules/lodash/upperFirst.js | 22 + app/node_modules/lodash/util.js | 34 + app/node_modules/lodash/value.js | 1 + app/node_modules/lodash/valueOf.js | 1 + app/node_modules/lodash/values.js | 34 + app/node_modules/lodash/valuesIn.js | 32 + app/node_modules/lodash/without.js | 31 + app/node_modules/lodash/words.js | 35 + app/node_modules/lodash/wrap.js | 30 + app/node_modules/lodash/wrapperAt.js | 48 + app/node_modules/lodash/wrapperChain.js | 34 + app/node_modules/lodash/wrapperLodash.js | 147 + app/node_modules/lodash/wrapperReverse.js | 44 + app/node_modules/lodash/wrapperValue.js | 21 + app/node_modules/lodash/xor.js | 28 + app/node_modules/lodash/xorBy.js | 39 + app/node_modules/lodash/xorWith.js | 34 + app/node_modules/lodash/zip.js | 22 + app/node_modules/lodash/zipObject.js | 24 + app/node_modules/lodash/zipObjectDeep.js | 23 + app/node_modules/lodash/zipWith.js | 32 + app/node_modules/media-typer/HISTORY.md | 22 + app/node_modules/media-typer/LICENSE | 22 + app/node_modules/media-typer/README.md | 81 + app/node_modules/media-typer/index.js | 270 + app/node_modules/media-typer/package.json | 26 + app/node_modules/merge-descriptors/HISTORY.md | 21 + app/node_modules/merge-descriptors/LICENSE | 23 + app/node_modules/merge-descriptors/README.md | 48 + app/node_modules/merge-descriptors/index.js | 60 + .../merge-descriptors/package.json | 32 + app/node_modules/methods/HISTORY.md | 29 + app/node_modules/methods/LICENSE | 24 + app/node_modules/methods/README.md | 51 + app/node_modules/methods/index.js | 69 + app/node_modules/methods/package.json | 36 + app/node_modules/mime-db/HISTORY.md | 446 + app/node_modules/mime-db/LICENSE | 22 + app/node_modules/mime-db/README.md | 102 + app/node_modules/mime-db/db.json | 8176 +++++++ app/node_modules/mime-db/index.js | 11 + app/node_modules/mime-db/package.json | 59 + app/node_modules/mime-types/HISTORY.md | 333 + app/node_modules/mime-types/LICENSE | 23 + app/node_modules/mime-types/README.md | 123 + app/node_modules/mime-types/index.js | 188 + app/node_modules/mime-types/package.json | 44 + app/node_modules/mime/LICENSE | 21 + app/node_modules/mime/README.md | 90 + app/node_modules/mime/build/build.js | 11 + app/node_modules/mime/build/test.js | 60 + app/node_modules/mime/cli.js | 8 + app/node_modules/mime/mime.js | 108 + app/node_modules/mime/package.json | 38 + app/node_modules/mime/types.json | 1 + app/node_modules/mongoclient/.npmignore | 2 + app/node_modules/mongoclient/README.md | 20 + app/node_modules/mongoclient/config.js | 33 + app/node_modules/mongoclient/index.js | 8 + app/node_modules/mongoclient/package.json | 17 + app/node_modules/mongodb-core/.coveralls.yml | 1 + app/node_modules/mongodb-core/.eslintrc | 15 + app/node_modules/mongodb-core/HISTORY.md | 714 + app/node_modules/mongodb-core/LICENSE | 201 + app/node_modules/mongodb-core/Makefile | 11 + app/node_modules/mongodb-core/README.md | 228 + app/node_modules/mongodb-core/TESTING.md | 18 + .../mongodb-core/THIRD-PARTY-NOTICES | 41 + app/node_modules/mongodb-core/conf.json | 59 + app/node_modules/mongodb-core/index.js | 32 + .../mongodb-core/lib/auth/gssapi.js | 262 + .../mongodb-core/lib/auth/mongocr.js | 181 + .../mongodb-core/lib/auth/plain.js | 168 + .../mongodb-core/lib/auth/scram.js | 339 + .../mongodb-core/lib/auth/sspi.js | 250 + .../mongodb-core/lib/auth/x509.js | 164 + .../lib/connection/command_result.js | 34 + .../mongodb-core/lib/connection/commands.js | 546 + .../mongodb-core/lib/connection/connection.js | 619 + .../mongodb-core/lib/connection/logger.js | 228 + .../mongodb-core/lib/connection/pool.js | 1387 ++ .../mongodb-core/lib/connection/utils.js | 86 + app/node_modules/mongodb-core/lib/cursor.js | 704 + app/node_modules/mongodb-core/lib/error.js | 44 + .../mongodb-core/lib/tools/smoke_plugin.js | 59 + .../mongodb-core/lib/topologies/mongos.js | 1307 ++ .../lib/topologies/read_preference.js | 118 + .../mongodb-core/lib/topologies/replset.js | 1473 ++ .../lib/topologies/replset_state.js | 1001 + .../mongodb-core/lib/topologies/server.js | 880 + .../mongodb-core/lib/topologies/shared.js | 334 + app/node_modules/mongodb-core/lib/utils.js | 32 + .../lib/wireprotocol/2_4_support.js | 570 + .../lib/wireprotocol/2_6_support.js | 334 + .../lib/wireprotocol/3_2_support.js | 549 + .../mongodb-core/lib/wireprotocol/commands.js | 357 + .../mongodb-core/lib/wireprotocol/shared.js | 27 + app/node_modules/mongodb-core/package.json | 49 + app/node_modules/mongodb-core/test.js | 71 + app/node_modules/mongodb-core/test1.js | 72 + app/node_modules/mongodb/.coveralls.yml | 1 + app/node_modules/mongodb/.eslintrc | 15 + app/node_modules/mongodb/HISTORY.md | 1767 ++ app/node_modules/mongodb/LICENSE | 201 + app/node_modules/mongodb/Makefile | 11 + app/node_modules/mongodb/README.md | 415 + app/node_modules/mongodb/THIRD-PARTY-NOTICES | 41 + app/node_modules/mongodb/boot_auth.js | 52 + app/node_modules/mongodb/conf.json | 76 + app/node_modules/mongodb/index.js | 56 + app/node_modules/mongodb/insert_bench.js | 231 + app/node_modules/mongodb/lib/admin.js | 579 + .../mongodb/lib/aggregation_cursor.js | 438 + app/node_modules/mongodb/lib/apm.js | 596 + app/node_modules/mongodb/lib/authenticate.js | 110 + app/node_modules/mongodb/lib/bulk/common.js | 440 + app/node_modules/mongodb/lib/bulk/ordered.js | 539 + .../mongodb/lib/bulk/unordered.js | 541 + app/node_modules/mongodb/lib/collection.js | 3377 +++ .../mongodb/lib/command_cursor.js | 320 + app/node_modules/mongodb/lib/cursor.js | 1208 ++ app/node_modules/mongodb/lib/db.js | 1805 ++ .../mongodb/lib/gridfs-stream/download.js | 409 + .../mongodb/lib/gridfs-stream/index.js | 367 + .../mongodb/lib/gridfs-stream/upload.js | 527 + app/node_modules/mongodb/lib/gridfs/chunk.js | 230 + .../mongodb/lib/gridfs/grid_store.js | 1954 ++ app/node_modules/mongodb/lib/metadata.js | 64 + app/node_modules/mongodb/lib/mongo_client.js | 531 + app/node_modules/mongodb/lib/mongos.js | 533 + .../mongodb/lib/read_preference.js | 131 + app/node_modules/mongodb/lib/replset.js | 582 + app/node_modules/mongodb/lib/server.js | 518 + app/node_modules/mongodb/lib/topology_base.js | 191 + app/node_modules/mongodb/lib/url_parser.js | 526 + app/node_modules/mongodb/lib/utils.js | 375 + app/node_modules/mongodb/package.json | 63 + app/node_modules/mongodb/rev.md | 931 + app/node_modules/mongodb/yarn.lock | 3299 +++ app/node_modules/mongoose/.eslintignore | 6 + app/node_modules/mongoose/.eslintrc.yml | 31 + .../mongoose/.github/ISSUE_TEMPLATE.md | 12 + .../mongoose/.github/PULL_REQUEST_TEMPLATE.md | 9 + app/node_modules/mongoose/.travis.yml | 26 + app/node_modules/mongoose/CONTRIBUTING.md | 62 + app/node_modules/mongoose/History.md | 4024 ++++ app/node_modules/mongoose/README.md | 325 + app/node_modules/mongoose/examples/README.md | 41 + .../mongoose/examples/aggregate/aggregate.js | 103 + .../mongoose/examples/aggregate/package.json | 14 + .../mongoose/examples/aggregate/person.js | 17 + .../mongoose/examples/doc-methods.js | 77 + .../mongoose/examples/express/README.md | 1 + .../express/connection-sharing/README.md | 6 + .../express/connection-sharing/app.js | 17 + .../express/connection-sharing/modelA.js | 5 + .../express/connection-sharing/package.json | 14 + .../express/connection-sharing/routes.js | 20 + .../examples/geospatial/geoJSONSchema.js | 22 + .../examples/geospatial/geoJSONexample.js | 56 + .../examples/geospatial/geospatial.js | 100 + .../mongoose/examples/geospatial/package.json | 14 + .../mongoose/examples/geospatial/person.js | 27 + .../examples/globalschemas/gs_example.js | 47 + .../mongoose/examples/globalschemas/person.js | 14 + .../mongoose/examples/lean/lean.js | 84 + .../mongoose/examples/lean/package.json | 14 + .../mongoose/examples/lean/person.js | 16 + .../mongoose/examples/mapreduce/mapreduce.js | 100 + .../mongoose/examples/mapreduce/package.json | 14 + .../mongoose/examples/mapreduce/person.js | 16 + .../population-across-three-collections.js | 134 + .../examples/population/population-basic.js | 103 + .../population/population-of-existing-doc.js | 109 + .../population-of-multiple-existing-docs.js | 124 + .../examples/population/population-options.js | 138 + .../population/population-plain-objects.js | 106 + .../mongoose/examples/promises/package.json | 14 + .../mongoose/examples/promises/person.js | 15 + .../mongoose/examples/promises/promise.js | 94 + .../examples/querybuilder/package.json | 14 + .../mongoose/examples/querybuilder/person.js | 15 + .../examples/querybuilder/querybuilder.js | 79 + .../examples/replicasets/package.json | 14 + .../mongoose/examples/replicasets/person.js | 15 + .../examples/replicasets/replica-sets.js | 71 + .../mongoose/examples/schema/schema.js | 119 + .../schema/storing-schemas-as-json/index.js | 27 + .../storing-schemas-as-json/schema.json | 9 + .../mongoose/examples/statics/person.js | 20 + .../mongoose/examples/statics/statics.js | 41 + app/node_modules/mongoose/index.js | 7 + app/node_modules/mongoose/lib/ES6Promise.js | 26 + app/node_modules/mongoose/lib/aggregate.js | 879 + app/node_modules/mongoose/lib/browser.js | 129 + .../mongoose/lib/browserDocument.js | 294 + app/node_modules/mongoose/lib/cast.js | 302 + app/node_modules/mongoose/lib/collection.js | 221 + app/node_modules/mongoose/lib/connection.js | 1155 + .../mongoose/lib/connectionstate.js | 27 + .../mongoose/lib/cursor/AggregationCursor.js | 328 + .../mongoose/lib/cursor/QueryCursor.js | 320 + app/node_modules/mongoose/lib/document.js | 2663 +++ .../mongoose/lib/document_provider.js | 30 + .../mongoose/lib/document_provider.web.js | 17 + app/node_modules/mongoose/lib/drivers/SPEC.md | 4 + .../lib/drivers/browser/ReadPreference.js | 5 + .../mongoose/lib/drivers/browser/binary.js | 12 + .../lib/drivers/browser/decimal128.js | 5 + .../mongoose/lib/drivers/browser/index.js | 8 + .../mongoose/lib/drivers/browser/objectid.js | 14 + .../mongoose/lib/drivers/index.js | 20 + .../mongoose/lib/drivers/index.web.js | 5 + .../node-mongodb-native/ReadPreference.js | 45 + .../lib/drivers/node-mongodb-native/binary.js | 8 + .../drivers/node-mongodb-native/collection.js | 271 + .../drivers/node-mongodb-native/connection.js | 403 + .../drivers/node-mongodb-native/decimal128.js | 5 + .../lib/drivers/node-mongodb-native/index.js | 8 + .../drivers/node-mongodb-native/objectid.js | 14 + .../lib/error/browserMissingSchema.js | 36 + app/node_modules/mongoose/lib/error/cast.js | 60 + .../mongoose/lib/error/disconnected.js | 40 + .../mongoose/lib/error/divergentArray.js | 46 + app/node_modules/mongoose/lib/error/index.js | 66 + .../mongoose/lib/error/messages.js | 44 + .../mongoose/lib/error/missingSchema.js | 37 + .../mongoose/lib/error/notFound.js | 50 + .../mongoose/lib/error/objectExpected.js | 35 + .../mongoose/lib/error/objectParameter.js | 36 + .../mongoose/lib/error/overwriteModel.js | 35 + app/node_modules/mongoose/lib/error/strict.js | 36 + .../mongoose/lib/error/validation.js | 102 + .../mongoose/lib/error/validator.js | 82 + .../mongoose/lib/error/version.js | 36 + app/node_modules/mongoose/lib/index.js | 863 + app/node_modules/mongoose/lib/internal.js | 32 + app/node_modules/mongoose/lib/model.js | 4104 ++++ .../mongoose/lib/plugins/idGetter.js | 26 + .../mongoose/lib/plugins/saveSubdocs.js | 37 + .../mongoose/lib/plugins/sharding.js | 76 + .../lib/plugins/validateBeforeSave.js | 47 + app/node_modules/mongoose/lib/promise.js | 314 + .../mongoose/lib/promise_provider.js | 51 + app/node_modules/mongoose/lib/query.js | 3928 ++++ app/node_modules/mongoose/lib/queryhelpers.js | 219 + app/node_modules/mongoose/lib/querystream.js | 367 + app/node_modules/mongoose/lib/schema.js | 1928 ++ app/node_modules/mongoose/lib/schema/array.js | 349 + .../mongoose/lib/schema/boolean.js | 118 + .../mongoose/lib/schema/buffer.js | 216 + app/node_modules/mongoose/lib/schema/date.js | 296 + .../mongoose/lib/schema/decimal128.js | 150 + .../mongoose/lib/schema/documentarray.js | 395 + .../mongoose/lib/schema/embedded.js | 262 + app/node_modules/mongoose/lib/schema/index.js | 32 + app/node_modules/mongoose/lib/schema/mixed.js | 80 + .../mongoose/lib/schema/number.js | 290 + .../mongoose/lib/schema/objectid.js | 228 + .../mongoose/lib/schema/operators/bitwise.js | 36 + .../mongoose/lib/schema/operators/exists.js | 13 + .../lib/schema/operators/geospatial.js | 100 + .../mongoose/lib/schema/operators/helpers.js | 34 + .../mongoose/lib/schema/operators/type.js | 13 + .../mongoose/lib/schema/string.js | 538 + app/node_modules/mongoose/lib/schematype.js | 1110 + .../mongoose/lib/services/common.js | 87 + .../mongoose/lib/services/cursor/eachAsync.js | 79 + .../document/cleanModifiedSubpaths.js | 18 + .../mongoose/lib/services/document/compile.js | 164 + .../mongoose/lib/services/model/applyHooks.js | 200 + .../lib/services/model/applyMethods.js | 43 + .../lib/services/model/applyStatics.js | 12 + .../lib/services/model/discriminator.js | 144 + .../lib/services/populate/getSchemaTypes.js | 115 + .../projection/isDefiningProjection.js | 18 + .../lib/services/projection/isInclusive.js | 30 + .../projection/isPathSelectedInclusive.js | 28 + .../mongoose/lib/services/query/castUpdate.js | 354 + .../lib/services/query/hasDollarKeys.js | 16 + .../services/query/selectPopulatedFields.js | 45 + .../lib/services/setDefaultsOnInsert.js | 118 + .../mongoose/lib/services/updateValidators.js | 161 + app/node_modules/mongoose/lib/statemachine.js | 178 + app/node_modules/mongoose/lib/types/array.js | 837 + app/node_modules/mongoose/lib/types/buffer.js | 295 + .../mongoose/lib/types/decimal128.js | 11 + .../mongoose/lib/types/documentarray.js | 286 + .../mongoose/lib/types/embedded.js | 368 + app/node_modules/mongoose/lib/types/index.js | 16 + .../mongoose/lib/types/objectid.js | 13 + .../mongoose/lib/types/subdocument.js | 178 + app/node_modules/mongoose/lib/utils.js | 908 + app/node_modules/mongoose/lib/virtualtype.js | 103 + app/node_modules/mongoose/package.json | 98 + app/node_modules/mongoose/release-items.md | 29 + app/node_modules/mongoose/static.js | 24 + app/node_modules/mongoose/tools/auth.js | 30 + app/node_modules/mongoose/tools/repl.js | 36 + app/node_modules/mongoose/tools/sharded.js | 42 + app/node_modules/mongoose/website.js | 87 + app/node_modules/morgan/HISTORY.md | 202 + app/node_modules/morgan/LICENSE | 23 + app/node_modules/morgan/README.md | 414 + app/node_modules/morgan/index.js | 522 + app/node_modules/morgan/package.json | 52 + app/node_modules/mpath/.travis.yml | 11 + app/node_modules/mpath/History.md | 51 + app/node_modules/mpath/LICENSE | 22 + app/node_modules/mpath/Makefile | 4 + app/node_modules/mpath/README.md | 278 + app/node_modules/mpath/bench.js | 109 + app/node_modules/mpath/bench.log | 0 app/node_modules/mpath/bench.out | 52 + app/node_modules/mpath/component.json | 8 + app/node_modules/mpath/index.js | 1 + app/node_modules/mpath/lib/index.js | 299 + app/node_modules/mpath/package.json | 25 + app/node_modules/mpath/test/index.js | 1857 ++ app/node_modules/mpromise/.npmignore | 4 + app/node_modules/mpromise/.travis.yml | 5 + app/node_modules/mpromise/History.md | 80 + app/node_modules/mpromise/LICENSE | 22 + app/node_modules/mpromise/README.md | 224 + app/node_modules/mpromise/lib/promise.js | 445 + app/node_modules/mpromise/package.json | 30 + .../mpromise/test/promise.domain.test.js | 28 + .../mpromise/test/promise.test.js | 554 + .../mpromise/test/promises.Aplus.js | 15 + app/node_modules/mquery/.npmignore | 3 + app/node_modules/mquery/.travis.yml | 8 + app/node_modules/mquery/History.md | 302 + app/node_modules/mquery/LICENSE | 22 + app/node_modules/mquery/Makefile | 22 + app/node_modules/mquery/README.md | 1219 ++ .../mquery/lib/collection/collection.js | 46 + .../mquery/lib/collection/index.js | 13 + .../mquery/lib/collection/node.js | 151 + app/node_modules/mquery/lib/env.js | 22 + app/node_modules/mquery/lib/mquery.js | 3041 +++ app/node_modules/mquery/lib/permissions.js | 88 + app/node_modules/mquery/lib/utils.js | 342 + .../mquery/node_modules/sliced/.npmignore | 2 + .../mquery/node_modules/sliced/.travis.yml | 4 + .../mquery/node_modules/sliced/History.md | 30 + .../mquery/node_modules/sliced/LICENSE | 22 + .../mquery/node_modules/sliced/Makefile | 5 + .../mquery/node_modules/sliced/README.md | 62 + .../mquery/node_modules/sliced/bench.js | 95 + .../mquery/node_modules/sliced/component.json | 14 + .../mquery/node_modules/sliced/index.js | 1 + .../mquery/node_modules/sliced/lib/sliced.js | 33 + .../mquery/node_modules/sliced/package.json | 24 + .../mquery/node_modules/sliced/test/index.js | 80 + app/node_modules/mquery/package.json | 35 + .../mquery/test/collection/browser.js | 0 .../mquery/test/collection/mongo.js | 0 .../mquery/test/collection/node.js | 28 + app/node_modules/mquery/test/env.js | 20 + app/node_modules/mquery/test/index.js | 2944 +++ app/node_modules/mquery/test/utils.test.js | 143 + app/node_modules/ms/index.js | 152 + app/node_modules/ms/license.md | 21 + app/node_modules/ms/package.json | 37 + app/node_modules/ms/readme.md | 51 + app/node_modules/muri/.npmignore | 2 + app/node_modules/muri/.travis.yml | 4 + app/node_modules/muri/History.md | 71 + app/node_modules/muri/LICENSE | 22 + app/node_modules/muri/Makefile | 5 + app/node_modules/muri/README.md | 48 + app/node_modules/muri/index.js | 1 + app/node_modules/muri/lib/index.js | 238 + app/node_modules/muri/package.json | 20 + app/node_modules/muri/test/index.js | 348 + app/node_modules/nconf/.npmignore | 12 + app/node_modules/nconf/.travis.yml | 25 + app/node_modules/nconf/CHANGELOG.md | 334 + app/node_modules/nconf/LICENSE | 19 + app/node_modules/nconf/README.md | 324 + app/node_modules/nconf/lib/nconf.js | 41 + app/node_modules/nconf/lib/nconf/common.js | 123 + app/node_modules/nconf/lib/nconf/formats.js | 28 + app/node_modules/nconf/lib/nconf/provider.js | 599 + .../nconf/lib/nconf/stores/argv.js | 71 + .../nconf/lib/nconf/stores/env.js | 92 + .../nconf/lib/nconf/stores/file.js | 289 + .../nconf/lib/nconf/stores/literal.js | 29 + .../nconf/lib/nconf/stores/memory.js | 225 + .../nconf/node_modules/async/CHANGELOG.md | 125 + .../nconf/node_modules/async/LICENSE | 19 + .../nconf/node_modules/async/README.md | 1877 ++ .../nconf/node_modules/async/dist/async.js | 1265 ++ .../node_modules/async/dist/async.min.js | 2 + .../nconf/node_modules/async/lib/async.js | 1265 ++ .../nconf/node_modules/async/package.json | 85 + app/node_modules/nconf/package.json | 36 + app/node_modules/nconf/test/common-test.js | 32 + app/node_modules/nconf/test/complete-test.js | 159 + app/node_modules/nconf/test/fixtures/bom.json | 19 + .../nconf/test/fixtures/complete.json | 19 + app/node_modules/nconf/test/fixtures/data.js | 30 + .../nconf/test/fixtures/hierarchy/global.json | 5 + .../test/fixtures/hierarchy/hierarchical.json | 3 + .../nconf/test/fixtures/hierarchy/user.json | 4 + .../nconf/test/fixtures/malformed.json | 3 + .../nconf/test/fixtures/merge/file1.json | 19 + .../nconf/test/fixtures/merge/file2.json | 10 + .../nconf/test/fixtures/merge/file3.json | 9 + .../nconf/test/fixtures/no-bom.json | 19 + .../nconf/test/fixtures/scripts/nconf-argv.js | 10 + .../fixtures/scripts/nconf-change-argv.js | 16 + .../nconf/test/fixtures/scripts/nconf-env.js | 10 + .../nconf-hierarchical-defaults-merge.js | 20 + .../scripts/nconf-hierarchical-file-argv.js | 17 + .../scripts/nconf-hierarchical-load-merge.js | 18 + .../scripts/nconf-hierarchical-load-save.js | 32 + .../test/fixtures/scripts/nconf-nested-env.js | 11 + .../test/fixtures/scripts/provider-argv.js | 12 + .../test/fixtures/scripts/provider-env.js | 12 + .../nconf/test/fixtures/secure.json | 18 + app/node_modules/nconf/test/helpers.js | 68 + app/node_modules/nconf/test/hierarchy-test.js | 145 + .../nconf/test/mocks/mock-store.js | 38 + app/node_modules/nconf/test/nconf-test.js | 143 + .../nconf/test/provider-save-test.js | 39 + app/node_modules/nconf/test/provider-test.js | 170 + .../nconf/test/stores/argv-test.js | 22 + .../nconf/test/stores/env-test.js | 24 + .../nconf/test/stores/file-store-test.js | 261 + .../nconf/test/stores/literal-test.js | 31 + .../nconf/test/stores/memory-store-test.js | 125 + app/node_modules/nconf/usage.js | 50 + app/node_modules/negotiator/HISTORY.md | 103 + app/node_modules/negotiator/LICENSE | 24 + app/node_modules/negotiator/README.md | 203 + app/node_modules/negotiator/index.js | 124 + app/node_modules/negotiator/lib/charset.js | 169 + app/node_modules/negotiator/lib/encoding.js | 184 + app/node_modules/negotiator/lib/language.js | 179 + app/node_modules/negotiator/lib/mediaType.js | 294 + app/node_modules/negotiator/package.json | 42 + app/node_modules/number-is-nan/index.js | 4 + app/node_modules/number-is-nan/license | 21 + app/node_modules/number-is-nan/package.json | 35 + app/node_modules/number-is-nan/readme.md | 28 + app/node_modules/on-finished/HISTORY.md | 88 + app/node_modules/on-finished/LICENSE | 23 + app/node_modules/on-finished/README.md | 154 + app/node_modules/on-finished/index.js | 196 + app/node_modules/on-finished/package.json | 31 + app/node_modules/on-headers/HISTORY.md | 21 + app/node_modules/on-headers/LICENSE | 22 + app/node_modules/on-headers/README.md | 81 + app/node_modules/on-headers/index.js | 132 + app/node_modules/on-headers/package.json | 42 + app/node_modules/os-locale/index.js | 127 + app/node_modules/os-locale/license | 21 + app/node_modules/os-locale/package.json | 43 + app/node_modules/os-locale/readme.md | 47 + app/node_modules/parseurl/HISTORY.md | 58 + app/node_modules/parseurl/LICENSE | 24 + app/node_modules/parseurl/README.md | 133 + app/node_modules/parseurl/index.js | 158 + app/node_modules/parseurl/package.json | 40 + app/node_modules/path-to-regexp/History.md | 36 + app/node_modules/path-to-regexp/LICENSE | 21 + app/node_modules/path-to-regexp/Readme.md | 35 + app/node_modules/path-to-regexp/index.js | 129 + app/node_modules/path-to-regexp/package.json | 30 + .../process-nextick-args/.travis.yml | 12 + .../process-nextick-args/index.js | 43 + .../process-nextick-args/license.md | 19 + .../process-nextick-args/package.json | 22 + .../process-nextick-args/readme.md | 18 + app/node_modules/process-nextick-args/test.js | 24 + app/node_modules/proxy-addr/HISTORY.md | 155 + app/node_modules/proxy-addr/LICENSE | 22 + app/node_modules/proxy-addr/README.md | 155 + app/node_modules/proxy-addr/index.js | 327 + app/node_modules/proxy-addr/package.json | 47 + app/node_modules/qs/.editorconfig | 30 + app/node_modules/qs/.eslintignore | 1 + app/node_modules/qs/.eslintrc | 19 + app/node_modules/qs/CHANGELOG.md | 226 + app/node_modules/qs/LICENSE | 28 + app/node_modules/qs/README.md | 475 + app/node_modules/qs/dist/qs.js | 638 + app/node_modules/qs/lib/formats.js | 18 + app/node_modules/qs/lib/index.js | 11 + app/node_modules/qs/lib/parse.js | 174 + app/node_modules/qs/lib/stringify.js | 210 + app/node_modules/qs/lib/utils.js | 213 + app/node_modules/qs/package.json | 52 + app/node_modules/qs/test/.eslintrc | 15 + app/node_modules/qs/test/index.js | 7 + app/node_modules/qs/test/parse.js | 574 + app/node_modules/qs/test/stringify.js | 597 + app/node_modules/qs/test/utils.js | 34 + app/node_modules/range-parser/HISTORY.md | 56 + app/node_modules/range-parser/LICENSE | 23 + app/node_modules/range-parser/README.md | 84 + app/node_modules/range-parser/index.js | 162 + app/node_modules/range-parser/package.json | 44 + app/node_modules/raw-body/HISTORY.md | 258 + app/node_modules/raw-body/LICENSE | 22 + app/node_modules/raw-body/README.md | 219 + app/node_modules/raw-body/index.d.ts | 87 + app/node_modules/raw-body/index.js | 286 + app/node_modules/raw-body/package.json | 48 + app/node_modules/readable-stream/.npmignore | 9 + app/node_modules/readable-stream/.travis.yml | 49 + .../readable-stream/CONTRIBUTING.md | 38 + .../readable-stream/GOVERNANCE.md | 136 + app/node_modules/readable-stream/LICENSE | 47 + app/node_modules/readable-stream/README.md | 57 + .../doc/wg-meetings/2015-01-30.md | 60 + .../readable-stream/duplex-browser.js | 1 + app/node_modules/readable-stream/duplex.js | 1 + .../readable-stream/lib/_stream_duplex.js | 75 + .../lib/_stream_passthrough.js | 26 + .../readable-stream/lib/_stream_readable.js | 941 + .../readable-stream/lib/_stream_transform.js | 182 + .../readable-stream/lib/_stream_writable.js | 551 + .../lib/internal/streams/BufferList.js | 64 + .../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 | 29 + app/node_modules/readable-stream/package.json | 56 + .../readable-stream/passthrough.js | 1 + .../readable-stream/readable-browser.js | 7 + app/node_modules/readable-stream/readable.js | 19 + app/node_modules/readable-stream/transform.js | 1 + .../readable-stream/writable-browser.js | 1 + app/node_modules/readable-stream/writable.js | 8 + app/node_modules/regexp-clone/.npmignore | 2 + app/node_modules/regexp-clone/.travis.yml | 5 + app/node_modules/regexp-clone/History.md | 5 + app/node_modules/regexp-clone/LICENSE | 22 + app/node_modules/regexp-clone/Makefile | 5 + app/node_modules/regexp-clone/README.md | 18 + app/node_modules/regexp-clone/index.js | 20 + app/node_modules/regexp-clone/package.json | 22 + app/node_modules/regexp-clone/test/index.js | 112 + app/node_modules/require_optional/.npmignore | 33 + app/node_modules/require_optional/.travis.yml | 9 + app/node_modules/require_optional/HISTORY.md | 7 + app/node_modules/require_optional/LICENSE | 201 + app/node_modules/require_optional/README.md | 2 + app/node_modules/require_optional/index.js | 128 + .../require_optional/node_modules/.bin/semver | 1 + .../require_optional/package.json | 40 + .../require_optional/test/nestedTest/index.js | 8 + .../test/nestedTest/package.json | 11 + .../test/require_optional_tests.js | 59 + app/node_modules/resolve-from/index.js | 23 + app/node_modules/resolve-from/license | 21 + app/node_modules/resolve-from/package.json | 34 + app/node_modules/resolve-from/readme.md | 58 + app/node_modules/safe-buffer/LICENSE | 21 + app/node_modules/safe-buffer/README.md | 584 + app/node_modules/safe-buffer/index.d.ts | 187 + app/node_modules/safe-buffer/index.js | 62 + app/node_modules/safe-buffer/package.json | 37 + app/node_modules/safer-buffer/LICENSE | 21 + .../safer-buffer/Porting-Buffer.md | 268 + app/node_modules/safer-buffer/Readme.md | 156 + app/node_modules/safer-buffer/dangerous.js | 58 + app/node_modules/safer-buffer/package.json | 34 + app/node_modules/safer-buffer/safer.js | 77 + app/node_modules/safer-buffer/tests.js | 406 + app/node_modules/secure-keys/.npmignore | 29 + app/node_modules/secure-keys/.travis.yml | 5 + app/node_modules/secure-keys/README.md | 40 + app/node_modules/secure-keys/index.js | 74 + app/node_modules/secure-keys/package.json | 22 + .../secure-keys/test/simple-test.js | 29 + .../secure-keys/test/test.secret.key | 27 + app/node_modules/semver/CHANGELOG.md | 39 + app/node_modules/semver/LICENSE | 15 + app/node_modules/semver/README.md | 412 + app/node_modules/semver/bin/semver | 160 + app/node_modules/semver/package.json | 28 + app/node_modules/semver/range.bnf | 16 + app/node_modules/semver/semver.js | 1483 ++ app/node_modules/send/HISTORY.md | 462 + app/node_modules/send/LICENSE | 23 + app/node_modules/send/README.md | 306 + app/node_modules/send/index.js | 1130 + app/node_modules/send/node_modules/.bin/mime | 1 + app/node_modules/send/package.json | 61 + app/node_modules/serve-static/HISTORY.md | 433 + app/node_modules/serve-static/LICENSE | 25 + app/node_modules/serve-static/README.md | 258 + app/node_modules/serve-static/index.js | 210 + app/node_modules/serve-static/package.json | 40 + app/node_modules/setprototypeof/LICENSE | 13 + app/node_modules/setprototypeof/README.md | 26 + app/node_modules/setprototypeof/index.d.ts | 2 + app/node_modules/setprototypeof/index.js | 15 + app/node_modules/setprototypeof/package.json | 25 + app/node_modules/sliced/History.md | 41 + app/node_modules/sliced/LICENSE | 22 + app/node_modules/sliced/README.md | 62 + app/node_modules/sliced/index.js | 33 + app/node_modules/sliced/package.json | 30 + app/node_modules/stack-trace/.npmignore | 1 + app/node_modules/stack-trace/License | 19 + app/node_modules/stack-trace/Makefile | 11 + app/node_modules/stack-trace/Readme.md | 98 + .../stack-trace/lib/stack-trace.js | 136 + app/node_modules/stack-trace/package.json | 21 + app/node_modules/statuses/HISTORY.md | 60 + app/node_modules/statuses/LICENSE | 23 + app/node_modules/statuses/README.md | 127 + app/node_modules/statuses/codes.json | 65 + app/node_modules/statuses/index.js | 113 + app/node_modules/statuses/package.json | 48 + app/node_modules/string-width/index.js | 37 + app/node_modules/string-width/license | 21 + app/node_modules/string-width/package.json | 56 + app/node_modules/string-width/readme.md | 42 + app/node_modules/string_decoder/.npmignore | 2 + app/node_modules/string_decoder/LICENSE | 48 + app/node_modules/string_decoder/README.md | 28 + .../string_decoder/lib/string_decoder.js | 272 + app/node_modules/string_decoder/package.json | 28 + app/node_modules/strip-ansi/index.js | 6 + app/node_modules/strip-ansi/license | 21 + app/node_modules/strip-ansi/package.json | 57 + app/node_modules/strip-ansi/readme.md | 33 + app/node_modules/type-is/HISTORY.md | 259 + app/node_modules/type-is/LICENSE | 23 + app/node_modules/type-is/README.md | 170 + app/node_modules/type-is/index.js | 266 + app/node_modules/type-is/package.json | 45 + app/node_modules/unpipe/HISTORY.md | 4 + app/node_modules/unpipe/LICENSE | 22 + app/node_modules/unpipe/README.md | 43 + app/node_modules/unpipe/index.js | 69 + app/node_modules/unpipe/package.json | 27 + app/node_modules/util-deprecate/History.md | 16 + app/node_modules/util-deprecate/LICENSE | 24 + app/node_modules/util-deprecate/README.md | 53 + app/node_modules/util-deprecate/browser.js | 67 + app/node_modules/util-deprecate/node.js | 6 + app/node_modules/util-deprecate/package.json | 27 + app/node_modules/utils-merge/.npmignore | 9 + app/node_modules/utils-merge/LICENSE | 20 + app/node_modules/utils-merge/README.md | 34 + app/node_modules/utils-merge/index.js | 23 + app/node_modules/utils-merge/package.json | 40 + app/node_modules/vary/HISTORY.md | 39 + app/node_modules/vary/LICENSE | 22 + app/node_modules/vary/README.md | 101 + app/node_modules/vary/index.js | 149 + app/node_modules/vary/package.json | 43 + app/node_modules/window-size/LICENSE | 21 + app/node_modules/window-size/README.md | 45 + app/node_modules/window-size/cli.js | 30 + app/node_modules/window-size/index.js | 32 + app/node_modules/window-size/package.json | 48 + app/node_modules/winston/CHANGELOG.md | 249 + app/node_modules/winston/LICENSE | 19 + app/node_modules/winston/README.md | 864 + app/node_modules/winston/index.d.ts | 501 + app/node_modules/winston/lib/winston.js | 164 + .../winston/lib/winston/common.js | 504 + .../winston/lib/winston/config.js | 68 + .../winston/lib/winston/config/cli-config.js | 35 + .../winston/lib/winston/config/npm-config.js | 27 + .../lib/winston/config/syslog-config.js | 31 + .../winston/lib/winston/container.js | 128 + .../winston/lib/winston/exception.js | 56 + .../winston/lib/winston/logger.js | 729 + .../winston/lib/winston/transports.js | 36 + .../winston/lib/winston/transports/console.js | 130 + .../winston/lib/winston/transports/file.js | 685 + .../winston/lib/winston/transports/http.js | 242 + .../winston/lib/winston/transports/memory.js | 89 + .../lib/winston/transports/transport.js | 135 + .../winston/node_modules/async/.jshintrc | 24 + .../winston/node_modules/async/.travis.yml | 5 + .../winston/node_modules/async/CHANGELOG.md | 16 + .../winston/node_modules/async/LICENSE | 19 + .../winston/node_modules/async/README.md | 1720 ++ .../winston/node_modules/async/bower.json | 40 + .../winston/node_modules/async/component.json | 17 + .../winston/node_modules/async/lib/async.js | 1283 ++ .../winston/node_modules/async/package.json | 57 + .../async/support/sync-package-managers.js | 53 + app/node_modules/winston/package.json | 43 + app/node_modules/winston/test/helpers.js | 273 + .../winston/test/transports/console-test.js | 202 + .../test/transports/file-archive-test.js | 83 + .../test/transports/file-maxfiles-test.js | 102 + .../test/transports/file-maxsize-test.js | 82 + .../winston/test/transports/file-open-test.js | 57 + .../test/transports/file-stress-test.js | 72 + .../test/transports/file-tailrolling-test.js | 92 + .../winston/test/transports/file-test.js | 134 + .../winston/test/transports/http-test.js | 70 + .../winston/test/transports/memory-test.js | 31 + .../winston/test/transports/transport.js | 212 + app/node_modules/wrap-ansi/index.js | 168 + app/node_modules/wrap-ansi/license | 21 + app/node_modules/wrap-ansi/package.json | 68 + app/node_modules/wrap-ansi/readme.md | 73 + app/node_modules/y18n/LICENSE | 13 + app/node_modules/y18n/README.md | 91 + app/node_modules/y18n/index.js | 172 + app/node_modules/y18n/package.json | 37 + app/node_modules/yargs/CHANGELOG.md | 508 + app/node_modules/yargs/LICENSE | 21 + app/node_modules/yargs/README.md | 1243 ++ app/node_modules/yargs/completion.sh.hbs | 28 + app/node_modules/yargs/index.js | 665 + app/node_modules/yargs/lib/completion.js | 91 + app/node_modules/yargs/lib/parser.js | 520 + .../yargs/lib/tokenize-arg-string.js | 32 + app/node_modules/yargs/lib/usage.js | 383 + app/node_modules/yargs/lib/validation.js | 249 + app/node_modules/yargs/locales/de.json | 36 + app/node_modules/yargs/locales/en.json | 36 + app/node_modules/yargs/locales/es.json | 36 + app/node_modules/yargs/locales/fr.json | 36 + app/node_modules/yargs/locales/id.json | 37 + app/node_modules/yargs/locales/ja.json | 36 + app/node_modules/yargs/locales/ko.json | 36 + app/node_modules/yargs/locales/nb.json | 36 + app/node_modules/yargs/locales/pirate.json | 12 + app/node_modules/yargs/locales/pl.json | 36 + app/node_modules/yargs/locales/pt.json | 36 + app/node_modules/yargs/locales/pt_BR.json | 36 + app/node_modules/yargs/locales/tr.json | 36 + app/node_modules/yargs/locales/zh.json | 36 + .../yargs/node_modules/.bin/window-size | 1 + app/node_modules/yargs/package.json | 102 + app/package.json | 16 + app/public/stylesheets/style.css | 8 + app/routes/index.js | 9 + app/routes/users.js | 16 + app/yarn.lock | 749 + 2312 files changed, 282611 insertions(+), 3 deletions(-) create mode 100644 .gitpod.Dockerfile create mode 100644 app/app.js create mode 100755 app/bin/www create mode 100644 app/models/UserModel.js create mode 100644 app/mongoUtil.js create mode 120000 app/node_modules/.bin/mime create mode 120000 app/node_modules/.bin/semver create mode 120000 app/node_modules/.bin/window-size create mode 100644 app/node_modules/.yarn-integrity create mode 100644 app/node_modules/accepts/HISTORY.md create mode 100644 app/node_modules/accepts/LICENSE create mode 100644 app/node_modules/accepts/README.md create mode 100644 app/node_modules/accepts/index.js create mode 100644 app/node_modules/accepts/package.json create mode 100644 app/node_modules/ansi-regex/index.js create mode 100644 app/node_modules/ansi-regex/license create mode 100644 app/node_modules/ansi-regex/package.json create mode 100644 app/node_modules/ansi-regex/readme.md create mode 100644 app/node_modules/array-flatten/LICENSE create mode 100644 app/node_modules/array-flatten/README.md create mode 100644 app/node_modules/array-flatten/array-flatten.js create mode 100644 app/node_modules/array-flatten/package.json create mode 100644 app/node_modules/async/CHANGELOG.md create mode 100644 app/node_modules/async/LICENSE create mode 100644 app/node_modules/async/README.md create mode 100644 app/node_modules/async/all.js create mode 100644 app/node_modules/async/allLimit.js create mode 100644 app/node_modules/async/allSeries.js create mode 100644 app/node_modules/async/any.js create mode 100644 app/node_modules/async/anyLimit.js create mode 100644 app/node_modules/async/anySeries.js create mode 100644 app/node_modules/async/apply.js create mode 100644 app/node_modules/async/applyEach.js create mode 100644 app/node_modules/async/applyEachSeries.js create mode 100644 app/node_modules/async/asyncify.js create mode 100644 app/node_modules/async/auto.js create mode 100644 app/node_modules/async/autoInject.js create mode 100644 app/node_modules/async/bower.json create mode 100644 app/node_modules/async/cargo.js create mode 100644 app/node_modules/async/compose.js create mode 100644 app/node_modules/async/concat.js create mode 100644 app/node_modules/async/concatLimit.js create mode 100644 app/node_modules/async/concatSeries.js create mode 100644 app/node_modules/async/constant.js create mode 100644 app/node_modules/async/detect.js create mode 100644 app/node_modules/async/detectLimit.js create mode 100644 app/node_modules/async/detectSeries.js create mode 100644 app/node_modules/async/dir.js create mode 100644 app/node_modules/async/dist/async.js create mode 100644 app/node_modules/async/dist/async.min.js create mode 100644 app/node_modules/async/dist/async.min.map create mode 100644 app/node_modules/async/doDuring.js create mode 100644 app/node_modules/async/doUntil.js create mode 100644 app/node_modules/async/doWhilst.js create mode 100644 app/node_modules/async/during.js create mode 100644 app/node_modules/async/each.js create mode 100644 app/node_modules/async/eachLimit.js create mode 100644 app/node_modules/async/eachOf.js create mode 100644 app/node_modules/async/eachOfLimit.js create mode 100644 app/node_modules/async/eachOfSeries.js create mode 100644 app/node_modules/async/eachSeries.js create mode 100644 app/node_modules/async/ensureAsync.js create mode 100644 app/node_modules/async/every.js create mode 100644 app/node_modules/async/everyLimit.js create mode 100644 app/node_modules/async/everySeries.js create mode 100644 app/node_modules/async/filter.js create mode 100644 app/node_modules/async/filterLimit.js create mode 100644 app/node_modules/async/filterSeries.js create mode 100644 app/node_modules/async/find.js create mode 100644 app/node_modules/async/findLimit.js create mode 100644 app/node_modules/async/findSeries.js create mode 100644 app/node_modules/async/foldl.js create mode 100644 app/node_modules/async/foldr.js create mode 100644 app/node_modules/async/forEach.js create mode 100644 app/node_modules/async/forEachLimit.js create mode 100644 app/node_modules/async/forEachOf.js create mode 100644 app/node_modules/async/forEachOfLimit.js create mode 100644 app/node_modules/async/forEachOfSeries.js create mode 100644 app/node_modules/async/forEachSeries.js create mode 100644 app/node_modules/async/forever.js create mode 100644 app/node_modules/async/groupBy.js create mode 100644 app/node_modules/async/groupByLimit.js create mode 100644 app/node_modules/async/groupBySeries.js create mode 100644 app/node_modules/async/index.js create mode 100644 app/node_modules/async/inject.js create mode 100644 app/node_modules/async/internal/DoublyLinkedList.js create mode 100644 app/node_modules/async/internal/applyEach.js create mode 100644 app/node_modules/async/internal/breakLoop.js create mode 100644 app/node_modules/async/internal/consoleFunc.js create mode 100644 app/node_modules/async/internal/createTester.js create mode 100644 app/node_modules/async/internal/doLimit.js create mode 100644 app/node_modules/async/internal/doParallel.js create mode 100644 app/node_modules/async/internal/doParallelLimit.js create mode 100644 app/node_modules/async/internal/eachOfLimit.js create mode 100644 app/node_modules/async/internal/filter.js create mode 100644 app/node_modules/async/internal/findGetResult.js create mode 100644 app/node_modules/async/internal/getIterator.js create mode 100644 app/node_modules/async/internal/initialParams.js create mode 100644 app/node_modules/async/internal/iterator.js create mode 100644 app/node_modules/async/internal/map.js create mode 100644 app/node_modules/async/internal/notId.js create mode 100644 app/node_modules/async/internal/once.js create mode 100644 app/node_modules/async/internal/onlyOnce.js create mode 100644 app/node_modules/async/internal/parallel.js create mode 100644 app/node_modules/async/internal/queue.js create mode 100644 app/node_modules/async/internal/reject.js create mode 100644 app/node_modules/async/internal/setImmediate.js create mode 100644 app/node_modules/async/internal/slice.js create mode 100644 app/node_modules/async/internal/withoutIndex.js create mode 100644 app/node_modules/async/internal/wrapAsync.js create mode 100644 app/node_modules/async/log.js create mode 100644 app/node_modules/async/map.js create mode 100644 app/node_modules/async/mapLimit.js create mode 100644 app/node_modules/async/mapSeries.js create mode 100644 app/node_modules/async/mapValues.js create mode 100644 app/node_modules/async/mapValuesLimit.js create mode 100644 app/node_modules/async/mapValuesSeries.js create mode 100644 app/node_modules/async/memoize.js create mode 100644 app/node_modules/async/nextTick.js create mode 100644 app/node_modules/async/package.json create mode 100644 app/node_modules/async/parallel.js create mode 100644 app/node_modules/async/parallelLimit.js create mode 100644 app/node_modules/async/priorityQueue.js create mode 100644 app/node_modules/async/queue.js create mode 100644 app/node_modules/async/race.js create mode 100644 app/node_modules/async/reduce.js create mode 100644 app/node_modules/async/reduceRight.js create mode 100644 app/node_modules/async/reflect.js create mode 100644 app/node_modules/async/reflectAll.js create mode 100644 app/node_modules/async/reject.js create mode 100644 app/node_modules/async/rejectLimit.js create mode 100644 app/node_modules/async/rejectSeries.js create mode 100644 app/node_modules/async/retry.js create mode 100644 app/node_modules/async/retryable.js create mode 100644 app/node_modules/async/select.js create mode 100644 app/node_modules/async/selectLimit.js create mode 100644 app/node_modules/async/selectSeries.js create mode 100644 app/node_modules/async/seq.js create mode 100644 app/node_modules/async/series.js create mode 100644 app/node_modules/async/setImmediate.js create mode 100644 app/node_modules/async/some.js create mode 100644 app/node_modules/async/someLimit.js create mode 100644 app/node_modules/async/someSeries.js create mode 100644 app/node_modules/async/sortBy.js create mode 100644 app/node_modules/async/timeout.js create mode 100644 app/node_modules/async/times.js create mode 100644 app/node_modules/async/timesLimit.js create mode 100644 app/node_modules/async/timesSeries.js create mode 100644 app/node_modules/async/transform.js create mode 100644 app/node_modules/async/tryEach.js create mode 100644 app/node_modules/async/unmemoize.js create mode 100644 app/node_modules/async/until.js create mode 100644 app/node_modules/async/waterfall.js create mode 100644 app/node_modules/async/whilst.js create mode 100644 app/node_modules/async/wrapSync.js create mode 100644 app/node_modules/basic-auth/HISTORY.md create mode 100644 app/node_modules/basic-auth/LICENSE create mode 100644 app/node_modules/basic-auth/README.md create mode 100644 app/node_modules/basic-auth/index.js create mode 100644 app/node_modules/basic-auth/package.json create mode 100644 app/node_modules/bluebird/LICENSE create mode 100644 app/node_modules/bluebird/README.md create mode 100644 app/node_modules/bluebird/changelog.md create mode 100644 app/node_modules/bluebird/js/browser/bluebird.core.js create mode 100644 app/node_modules/bluebird/js/browser/bluebird.core.min.js create mode 100644 app/node_modules/bluebird/js/browser/bluebird.js create mode 100644 app/node_modules/bluebird/js/browser/bluebird.min.js create mode 100644 app/node_modules/bluebird/js/release/any.js create mode 100644 app/node_modules/bluebird/js/release/assert.js create mode 100644 app/node_modules/bluebird/js/release/async.js create mode 100644 app/node_modules/bluebird/js/release/bind.js create mode 100644 app/node_modules/bluebird/js/release/bluebird.js create mode 100644 app/node_modules/bluebird/js/release/call_get.js create mode 100644 app/node_modules/bluebird/js/release/cancel.js create mode 100644 app/node_modules/bluebird/js/release/catch_filter.js create mode 100644 app/node_modules/bluebird/js/release/context.js create mode 100644 app/node_modules/bluebird/js/release/debuggability.js create mode 100644 app/node_modules/bluebird/js/release/direct_resolve.js create mode 100644 app/node_modules/bluebird/js/release/each.js create mode 100644 app/node_modules/bluebird/js/release/errors.js create mode 100644 app/node_modules/bluebird/js/release/es5.js create mode 100644 app/node_modules/bluebird/js/release/filter.js create mode 100644 app/node_modules/bluebird/js/release/finally.js create mode 100644 app/node_modules/bluebird/js/release/generators.js create mode 100644 app/node_modules/bluebird/js/release/join.js create mode 100644 app/node_modules/bluebird/js/release/map.js create mode 100644 app/node_modules/bluebird/js/release/method.js create mode 100644 app/node_modules/bluebird/js/release/nodeback.js create mode 100644 app/node_modules/bluebird/js/release/nodeify.js create mode 100644 app/node_modules/bluebird/js/release/promise.js create mode 100644 app/node_modules/bluebird/js/release/promise_array.js create mode 100644 app/node_modules/bluebird/js/release/promisify.js create mode 100644 app/node_modules/bluebird/js/release/props.js create mode 100644 app/node_modules/bluebird/js/release/queue.js create mode 100644 app/node_modules/bluebird/js/release/race.js create mode 100644 app/node_modules/bluebird/js/release/reduce.js create mode 100644 app/node_modules/bluebird/js/release/schedule.js create mode 100644 app/node_modules/bluebird/js/release/settle.js create mode 100644 app/node_modules/bluebird/js/release/some.js create mode 100644 app/node_modules/bluebird/js/release/synchronous_inspection.js create mode 100644 app/node_modules/bluebird/js/release/thenables.js create mode 100644 app/node_modules/bluebird/js/release/timers.js create mode 100644 app/node_modules/bluebird/js/release/using.js create mode 100644 app/node_modules/bluebird/js/release/util.js create mode 100644 app/node_modules/bluebird/package.json create mode 100644 app/node_modules/body-parser/HISTORY.md create mode 100644 app/node_modules/body-parser/LICENSE create mode 100644 app/node_modules/body-parser/README.md create mode 100644 app/node_modules/body-parser/index.js create mode 100644 app/node_modules/body-parser/lib/read.js create mode 100644 app/node_modules/body-parser/lib/types/json.js create mode 100644 app/node_modules/body-parser/lib/types/raw.js create mode 100644 app/node_modules/body-parser/lib/types/text.js create mode 100644 app/node_modules/body-parser/lib/types/urlencoded.js create mode 100644 app/node_modules/body-parser/package.json create mode 100644 app/node_modules/bson/HISTORY.md create mode 100644 app/node_modules/bson/LICENSE.md create mode 100644 app/node_modules/bson/README.md create mode 100644 app/node_modules/bson/bower.json create mode 100644 app/node_modules/bson/browser_build/bson.js create mode 100644 app/node_modules/bson/browser_build/package.json create mode 100644 app/node_modules/bson/index.js create mode 100644 app/node_modules/bson/lib/bson/binary.js create mode 100644 app/node_modules/bson/lib/bson/bson.js create mode 100644 app/node_modules/bson/lib/bson/code.js create mode 100644 app/node_modules/bson/lib/bson/db_ref.js create mode 100644 app/node_modules/bson/lib/bson/decimal128.js create mode 100644 app/node_modules/bson/lib/bson/double.js create mode 100644 app/node_modules/bson/lib/bson/float_parser.js create mode 100644 app/node_modules/bson/lib/bson/int_32.js create mode 100644 app/node_modules/bson/lib/bson/long.js create mode 100644 app/node_modules/bson/lib/bson/map.js create mode 100644 app/node_modules/bson/lib/bson/max_key.js create mode 100644 app/node_modules/bson/lib/bson/min_key.js create mode 100644 app/node_modules/bson/lib/bson/objectid.js create mode 100644 app/node_modules/bson/lib/bson/parser/calculate_size.js create mode 100644 app/node_modules/bson/lib/bson/parser/deserializer.js create mode 100644 app/node_modules/bson/lib/bson/parser/serializer.js create mode 100644 app/node_modules/bson/lib/bson/parser/utils.js create mode 100644 app/node_modules/bson/lib/bson/regexp.js create mode 100644 app/node_modules/bson/lib/bson/symbol.js create mode 100644 app/node_modules/bson/lib/bson/timestamp.js create mode 100644 app/node_modules/bson/package.json create mode 100644 app/node_modules/buffer-shims/index.js create mode 100644 app/node_modules/buffer-shims/license.md create mode 100644 app/node_modules/buffer-shims/package.json create mode 100644 app/node_modules/buffer-shims/readme.md create mode 100644 app/node_modules/bytes/History.md create mode 100644 app/node_modules/bytes/LICENSE create mode 100644 app/node_modules/bytes/Readme.md create mode 100644 app/node_modules/bytes/index.js create mode 100644 app/node_modules/bytes/package.json create mode 100644 app/node_modules/camelcase/index.js create mode 100644 app/node_modules/camelcase/license create mode 100644 app/node_modules/camelcase/package.json create mode 100644 app/node_modules/camelcase/readme.md create mode 100644 app/node_modules/cliui/CHANGELOG.md create mode 100644 app/node_modules/cliui/LICENSE.txt create mode 100644 app/node_modules/cliui/README.md create mode 100644 app/node_modules/cliui/index.js create mode 100644 app/node_modules/cliui/package.json create mode 100644 app/node_modules/code-point-at/index.js create mode 100644 app/node_modules/code-point-at/license create mode 100644 app/node_modules/code-point-at/package.json create mode 100644 app/node_modules/code-point-at/readme.md create mode 100644 app/node_modules/colors/.travis.yml create mode 100644 app/node_modules/colors/MIT-LICENSE.txt create mode 100644 app/node_modules/colors/ReadMe.md create mode 100644 app/node_modules/colors/examples/normal-usage.js create mode 100644 app/node_modules/colors/examples/safe-string.js create mode 100644 app/node_modules/colors/lib/colors.js create mode 100644 app/node_modules/colors/lib/custom/trap.js create mode 100644 app/node_modules/colors/lib/custom/zalgo.js create mode 100644 app/node_modules/colors/lib/extendStringPrototype.js create mode 100644 app/node_modules/colors/lib/index.js create mode 100644 app/node_modules/colors/lib/maps/america.js create mode 100644 app/node_modules/colors/lib/maps/rainbow.js create mode 100644 app/node_modules/colors/lib/maps/random.js create mode 100644 app/node_modules/colors/lib/maps/zebra.js create mode 100644 app/node_modules/colors/lib/styles.js create mode 100644 app/node_modules/colors/lib/system/supports-colors.js create mode 100644 app/node_modules/colors/package.json create mode 100644 app/node_modules/colors/safe.js create mode 100644 app/node_modules/colors/screenshots/colors.png create mode 100644 app/node_modules/colors/tests/basic-test.js create mode 100644 app/node_modules/colors/tests/safe-test.js create mode 100644 app/node_modules/colors/themes/generic-logging.js create mode 100644 app/node_modules/content-disposition/HISTORY.md create mode 100644 app/node_modules/content-disposition/LICENSE create mode 100644 app/node_modules/content-disposition/README.md create mode 100644 app/node_modules/content-disposition/index.js create mode 100644 app/node_modules/content-disposition/package.json create mode 100644 app/node_modules/content-type/HISTORY.md create mode 100644 app/node_modules/content-type/LICENSE create mode 100644 app/node_modules/content-type/README.md create mode 100644 app/node_modules/content-type/index.js create mode 100644 app/node_modules/content-type/package.json create mode 100644 app/node_modules/cookie-parser/HISTORY.md create mode 100644 app/node_modules/cookie-parser/LICENSE create mode 100644 app/node_modules/cookie-parser/README.md create mode 100644 app/node_modules/cookie-parser/index.js create mode 100644 app/node_modules/cookie-parser/node_modules/cookie/HISTORY.md create mode 100644 app/node_modules/cookie-parser/node_modules/cookie/LICENSE create mode 100644 app/node_modules/cookie-parser/node_modules/cookie/README.md create mode 100644 app/node_modules/cookie-parser/node_modules/cookie/index.js create mode 100644 app/node_modules/cookie-parser/node_modules/cookie/package.json create mode 100644 app/node_modules/cookie-parser/package.json create mode 100644 app/node_modules/cookie-signature/.npmignore create mode 100644 app/node_modules/cookie-signature/History.md create mode 100644 app/node_modules/cookie-signature/Readme.md create mode 100644 app/node_modules/cookie-signature/index.js create mode 100644 app/node_modules/cookie-signature/package.json create mode 100644 app/node_modules/cookie/HISTORY.md create mode 100644 app/node_modules/cookie/LICENSE create mode 100644 app/node_modules/cookie/README.md create mode 100644 app/node_modules/cookie/index.js create mode 100644 app/node_modules/cookie/package.json create mode 100644 app/node_modules/core-util-is/LICENSE create mode 100644 app/node_modules/core-util-is/README.md create mode 100644 app/node_modules/core-util-is/float.patch create mode 100644 app/node_modules/core-util-is/lib/util.js create mode 100644 app/node_modules/core-util-is/package.json create mode 100644 app/node_modules/core-util-is/test.js create mode 100644 app/node_modules/cycle/README.md create mode 100644 app/node_modules/cycle/cycle.js create mode 100644 app/node_modules/cycle/package.json create mode 100644 app/node_modules/debug/.coveralls.yml create mode 100644 app/node_modules/debug/.eslintrc create mode 100644 app/node_modules/debug/.npmignore create mode 100644 app/node_modules/debug/.travis.yml create mode 100644 app/node_modules/debug/CHANGELOG.md create mode 100644 app/node_modules/debug/LICENSE create mode 100644 app/node_modules/debug/Makefile create mode 100644 app/node_modules/debug/README.md create mode 100644 app/node_modules/debug/component.json create mode 100644 app/node_modules/debug/karma.conf.js create mode 100644 app/node_modules/debug/node.js create mode 100644 app/node_modules/debug/package.json create mode 100644 app/node_modules/debug/src/browser.js create mode 100644 app/node_modules/debug/src/debug.js create mode 100644 app/node_modules/debug/src/index.js create mode 100644 app/node_modules/debug/src/inspector-log.js create mode 100644 app/node_modules/debug/src/node.js create mode 100644 app/node_modules/decamelize/index.js create mode 100644 app/node_modules/decamelize/license create mode 100644 app/node_modules/decamelize/package.json create mode 100644 app/node_modules/decamelize/readme.md create mode 100644 app/node_modules/depd/History.md create mode 100644 app/node_modules/depd/LICENSE create mode 100644 app/node_modules/depd/Readme.md create mode 100644 app/node_modules/depd/index.js create mode 100644 app/node_modules/depd/lib/browser/index.js create mode 100644 app/node_modules/depd/lib/compat/callsite-tostring.js create mode 100644 app/node_modules/depd/lib/compat/event-listener-count.js create mode 100644 app/node_modules/depd/lib/compat/index.js create mode 100644 app/node_modules/depd/package.json create mode 100644 app/node_modules/destroy/LICENSE create mode 100644 app/node_modules/destroy/README.md create mode 100644 app/node_modules/destroy/index.js create mode 100644 app/node_modules/destroy/package.json create mode 100644 app/node_modules/ee-first/LICENSE create mode 100644 app/node_modules/ee-first/README.md create mode 100644 app/node_modules/ee-first/index.js create mode 100644 app/node_modules/ee-first/package.json create mode 100644 app/node_modules/encodeurl/HISTORY.md create mode 100644 app/node_modules/encodeurl/LICENSE create mode 100644 app/node_modules/encodeurl/README.md create mode 100644 app/node_modules/encodeurl/index.js create mode 100644 app/node_modules/encodeurl/package.json create mode 100644 app/node_modules/es6-promise/CHANGELOG.md create mode 100644 app/node_modules/es6-promise/LICENSE create mode 100644 app/node_modules/es6-promise/README.md create mode 100644 app/node_modules/es6-promise/dist/es6-promise.js create mode 100644 app/node_modules/es6-promise/dist/es6-promise.min.js create mode 100644 app/node_modules/es6-promise/lib/es6-promise.umd.js create mode 100644 app/node_modules/es6-promise/lib/es6-promise/-internal.js create mode 100644 app/node_modules/es6-promise/lib/es6-promise/asap.js create mode 100644 app/node_modules/es6-promise/lib/es6-promise/enumerator.js create mode 100644 app/node_modules/es6-promise/lib/es6-promise/polyfill.js create mode 100644 app/node_modules/es6-promise/lib/es6-promise/promise.js create mode 100644 app/node_modules/es6-promise/lib/es6-promise/promise/all.js create mode 100644 app/node_modules/es6-promise/lib/es6-promise/promise/race.js create mode 100644 app/node_modules/es6-promise/lib/es6-promise/promise/reject.js create mode 100644 app/node_modules/es6-promise/lib/es6-promise/promise/resolve.js create mode 100644 app/node_modules/es6-promise/lib/es6-promise/then.js create mode 100644 app/node_modules/es6-promise/lib/es6-promise/utils.js create mode 100644 app/node_modules/es6-promise/package.json create mode 100644 app/node_modules/escape-html/LICENSE create mode 100644 app/node_modules/escape-html/Readme.md create mode 100644 app/node_modules/escape-html/index.js create mode 100644 app/node_modules/escape-html/package.json create mode 100644 app/node_modules/etag/HISTORY.md create mode 100644 app/node_modules/etag/LICENSE create mode 100644 app/node_modules/etag/README.md create mode 100644 app/node_modules/etag/index.js create mode 100644 app/node_modules/etag/package.json create mode 100644 app/node_modules/express/History.md create mode 100644 app/node_modules/express/LICENSE create mode 100644 app/node_modules/express/Readme.md create mode 100644 app/node_modules/express/index.js create mode 100644 app/node_modules/express/lib/application.js create mode 100644 app/node_modules/express/lib/express.js create mode 100644 app/node_modules/express/lib/middleware/init.js create mode 100644 app/node_modules/express/lib/middleware/query.js create mode 100644 app/node_modules/express/lib/request.js create mode 100644 app/node_modules/express/lib/response.js create mode 100644 app/node_modules/express/lib/router/index.js create mode 100644 app/node_modules/express/lib/router/layer.js create mode 100644 app/node_modules/express/lib/router/route.js create mode 100644 app/node_modules/express/lib/utils.js create mode 100644 app/node_modules/express/lib/view.js create mode 100644 app/node_modules/express/package.json create mode 100644 app/node_modules/eyes/LICENSE create mode 100644 app/node_modules/eyes/Makefile create mode 100644 app/node_modules/eyes/README.md create mode 100644 app/node_modules/eyes/lib/eyes.js create mode 100644 app/node_modules/eyes/package.json create mode 100644 app/node_modules/eyes/test/eyes-test.js create mode 100644 app/node_modules/finalhandler/HISTORY.md create mode 100644 app/node_modules/finalhandler/LICENSE create mode 100644 app/node_modules/finalhandler/README.md create mode 100644 app/node_modules/finalhandler/index.js create mode 100644 app/node_modules/finalhandler/package.json create mode 100644 app/node_modules/forwarded/HISTORY.md create mode 100644 app/node_modules/forwarded/LICENSE create mode 100644 app/node_modules/forwarded/README.md create mode 100644 app/node_modules/forwarded/index.js create mode 100644 app/node_modules/forwarded/package.json create mode 100644 app/node_modules/fresh/HISTORY.md create mode 100644 app/node_modules/fresh/LICENSE create mode 100644 app/node_modules/fresh/README.md create mode 100644 app/node_modules/fresh/index.js create mode 100644 app/node_modules/fresh/package.json create mode 100644 app/node_modules/hooks-fixed/.npmignore create mode 100644 app/node_modules/hooks-fixed/Makefile create mode 100644 app/node_modules/hooks-fixed/README.md create mode 100644 app/node_modules/hooks-fixed/hooks.alt.js create mode 100644 app/node_modules/hooks-fixed/hooks.js create mode 100644 app/node_modules/hooks-fixed/package.json create mode 100644 app/node_modules/hooks-fixed/test.js create mode 100644 app/node_modules/http-errors/HISTORY.md create mode 100644 app/node_modules/http-errors/LICENSE create mode 100644 app/node_modules/http-errors/README.md create mode 100644 app/node_modules/http-errors/index.js create mode 100644 app/node_modules/http-errors/node_modules/statuses/HISTORY.md create mode 100644 app/node_modules/http-errors/node_modules/statuses/LICENSE create mode 100644 app/node_modules/http-errors/node_modules/statuses/README.md create mode 100644 app/node_modules/http-errors/node_modules/statuses/codes.json create mode 100644 app/node_modules/http-errors/node_modules/statuses/index.js create mode 100644 app/node_modules/http-errors/node_modules/statuses/package.json create mode 100644 app/node_modules/http-errors/package.json create mode 100644 app/node_modules/iconv-lite/.travis.yml create mode 100644 app/node_modules/iconv-lite/Changelog.md create mode 100644 app/node_modules/iconv-lite/LICENSE create mode 100644 app/node_modules/iconv-lite/README.md create mode 100644 app/node_modules/iconv-lite/encodings/dbcs-codec.js create mode 100644 app/node_modules/iconv-lite/encodings/dbcs-data.js create mode 100644 app/node_modules/iconv-lite/encodings/index.js create mode 100644 app/node_modules/iconv-lite/encodings/internal.js create mode 100644 app/node_modules/iconv-lite/encodings/sbcs-codec.js create mode 100644 app/node_modules/iconv-lite/encodings/sbcs-data-generated.js create mode 100644 app/node_modules/iconv-lite/encodings/sbcs-data.js create mode 100644 app/node_modules/iconv-lite/encodings/tables/big5-added.json create mode 100644 app/node_modules/iconv-lite/encodings/tables/cp936.json create mode 100644 app/node_modules/iconv-lite/encodings/tables/cp949.json create mode 100644 app/node_modules/iconv-lite/encodings/tables/cp950.json create mode 100644 app/node_modules/iconv-lite/encodings/tables/eucjp.json create mode 100644 app/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json create mode 100644 app/node_modules/iconv-lite/encodings/tables/gbk-added.json create mode 100644 app/node_modules/iconv-lite/encodings/tables/shiftjis.json create mode 100644 app/node_modules/iconv-lite/encodings/utf16.js create mode 100644 app/node_modules/iconv-lite/encodings/utf7.js create mode 100644 app/node_modules/iconv-lite/lib/bom-handling.js create mode 100644 app/node_modules/iconv-lite/lib/extend-node.js create mode 100644 app/node_modules/iconv-lite/lib/index.d.ts create mode 100644 app/node_modules/iconv-lite/lib/index.js create mode 100644 app/node_modules/iconv-lite/lib/streams.js create mode 100644 app/node_modules/iconv-lite/package.json create mode 100644 app/node_modules/inherits/LICENSE create mode 100644 app/node_modules/inherits/README.md create mode 100644 app/node_modules/inherits/inherits.js create mode 100644 app/node_modules/inherits/inherits_browser.js create mode 100644 app/node_modules/inherits/package.json create mode 100644 app/node_modules/ini/LICENSE create mode 100644 app/node_modules/ini/README.md create mode 100644 app/node_modules/ini/ini.js create mode 100644 app/node_modules/ini/package.json create mode 100644 app/node_modules/invert-kv/index.js create mode 100644 app/node_modules/invert-kv/package.json create mode 100644 app/node_modules/invert-kv/readme.md create mode 100644 app/node_modules/ipaddr.js/LICENSE create mode 100644 app/node_modules/ipaddr.js/README.md create mode 100644 app/node_modules/ipaddr.js/ipaddr.min.js create mode 100644 app/node_modules/ipaddr.js/lib/ipaddr.js create mode 100644 app/node_modules/ipaddr.js/lib/ipaddr.js.d.ts create mode 100644 app/node_modules/ipaddr.js/package.json create mode 100644 app/node_modules/is-fullwidth-code-point/index.js create mode 100644 app/node_modules/is-fullwidth-code-point/license create mode 100644 app/node_modules/is-fullwidth-code-point/package.json create mode 100644 app/node_modules/is-fullwidth-code-point/readme.md create mode 100644 app/node_modules/isarray/.npmignore create mode 100644 app/node_modules/isarray/.travis.yml create mode 100644 app/node_modules/isarray/Makefile create mode 100644 app/node_modules/isarray/README.md create mode 100644 app/node_modules/isarray/component.json create mode 100644 app/node_modules/isarray/index.js create mode 100644 app/node_modules/isarray/package.json create mode 100644 app/node_modules/isarray/test.js create mode 100644 app/node_modules/isstream/.jshintrc create mode 100644 app/node_modules/isstream/.npmignore create mode 100644 app/node_modules/isstream/.travis.yml create mode 100644 app/node_modules/isstream/LICENSE.md create mode 100644 app/node_modules/isstream/README.md create mode 100644 app/node_modules/isstream/isstream.js create mode 100644 app/node_modules/isstream/package.json create mode 100644 app/node_modules/isstream/test.js create mode 100644 app/node_modules/kareem/.npmignore create mode 100644 app/node_modules/kareem/.travis.yml create mode 100644 app/node_modules/kareem/LICENSE create mode 100644 app/node_modules/kareem/Makefile create mode 100644 app/node_modules/kareem/README.md create mode 100644 app/node_modules/kareem/docs.js create mode 100644 app/node_modules/kareem/gulpfile.js create mode 100644 app/node_modules/kareem/index.js create mode 100644 app/node_modules/kareem/package.json create mode 100644 app/node_modules/kareem/test/examples.test.js create mode 100644 app/node_modules/kareem/test/post.test.js create mode 100644 app/node_modules/kareem/test/pre.test.js create mode 100644 app/node_modules/kareem/test/wrap.test.js create mode 100644 app/node_modules/lcid/index.js create mode 100644 app/node_modules/lcid/lcid.json create mode 100644 app/node_modules/lcid/license create mode 100644 app/node_modules/lcid/package.json create mode 100644 app/node_modules/lcid/readme.md create mode 100644 app/node_modules/lodash.get/LICENSE create mode 100644 app/node_modules/lodash.get/README.md create mode 100644 app/node_modules/lodash.get/index.js create mode 100644 app/node_modules/lodash.get/package.json create mode 100644 app/node_modules/lodash/LICENSE create mode 100644 app/node_modules/lodash/README.md create mode 100644 app/node_modules/lodash/_DataView.js create mode 100644 app/node_modules/lodash/_Hash.js create mode 100644 app/node_modules/lodash/_LazyWrapper.js create mode 100644 app/node_modules/lodash/_ListCache.js create mode 100644 app/node_modules/lodash/_LodashWrapper.js create mode 100644 app/node_modules/lodash/_Map.js create mode 100644 app/node_modules/lodash/_MapCache.js create mode 100644 app/node_modules/lodash/_Promise.js create mode 100644 app/node_modules/lodash/_Set.js create mode 100644 app/node_modules/lodash/_SetCache.js create mode 100644 app/node_modules/lodash/_Stack.js create mode 100644 app/node_modules/lodash/_Symbol.js create mode 100644 app/node_modules/lodash/_Uint8Array.js create mode 100644 app/node_modules/lodash/_WeakMap.js create mode 100644 app/node_modules/lodash/_apply.js create mode 100644 app/node_modules/lodash/_arrayAggregator.js create mode 100644 app/node_modules/lodash/_arrayEach.js create mode 100644 app/node_modules/lodash/_arrayEachRight.js create mode 100644 app/node_modules/lodash/_arrayEvery.js create mode 100644 app/node_modules/lodash/_arrayFilter.js create mode 100644 app/node_modules/lodash/_arrayIncludes.js create mode 100644 app/node_modules/lodash/_arrayIncludesWith.js create mode 100644 app/node_modules/lodash/_arrayLikeKeys.js create mode 100644 app/node_modules/lodash/_arrayMap.js create mode 100644 app/node_modules/lodash/_arrayPush.js create mode 100644 app/node_modules/lodash/_arrayReduce.js create mode 100644 app/node_modules/lodash/_arrayReduceRight.js create mode 100644 app/node_modules/lodash/_arraySample.js create mode 100644 app/node_modules/lodash/_arraySampleSize.js create mode 100644 app/node_modules/lodash/_arrayShuffle.js create mode 100644 app/node_modules/lodash/_arraySome.js create mode 100644 app/node_modules/lodash/_asciiSize.js create mode 100644 app/node_modules/lodash/_asciiToArray.js create mode 100644 app/node_modules/lodash/_asciiWords.js create mode 100644 app/node_modules/lodash/_assignMergeValue.js create mode 100644 app/node_modules/lodash/_assignValue.js create mode 100644 app/node_modules/lodash/_assocIndexOf.js create mode 100644 app/node_modules/lodash/_baseAggregator.js create mode 100644 app/node_modules/lodash/_baseAssign.js create mode 100644 app/node_modules/lodash/_baseAssignIn.js create mode 100644 app/node_modules/lodash/_baseAssignValue.js create mode 100644 app/node_modules/lodash/_baseAt.js create mode 100644 app/node_modules/lodash/_baseClamp.js create mode 100644 app/node_modules/lodash/_baseClone.js create mode 100644 app/node_modules/lodash/_baseConforms.js create mode 100644 app/node_modules/lodash/_baseConformsTo.js create mode 100644 app/node_modules/lodash/_baseCreate.js create mode 100644 app/node_modules/lodash/_baseDelay.js create mode 100644 app/node_modules/lodash/_baseDifference.js create mode 100644 app/node_modules/lodash/_baseEach.js create mode 100644 app/node_modules/lodash/_baseEachRight.js create mode 100644 app/node_modules/lodash/_baseEvery.js create mode 100644 app/node_modules/lodash/_baseExtremum.js create mode 100644 app/node_modules/lodash/_baseFill.js create mode 100644 app/node_modules/lodash/_baseFilter.js create mode 100644 app/node_modules/lodash/_baseFindIndex.js create mode 100644 app/node_modules/lodash/_baseFindKey.js create mode 100644 app/node_modules/lodash/_baseFlatten.js create mode 100644 app/node_modules/lodash/_baseFor.js create mode 100644 app/node_modules/lodash/_baseForOwn.js create mode 100644 app/node_modules/lodash/_baseForOwnRight.js create mode 100644 app/node_modules/lodash/_baseForRight.js create mode 100644 app/node_modules/lodash/_baseFunctions.js create mode 100644 app/node_modules/lodash/_baseGet.js create mode 100644 app/node_modules/lodash/_baseGetAllKeys.js create mode 100644 app/node_modules/lodash/_baseGetTag.js create mode 100644 app/node_modules/lodash/_baseGt.js create mode 100644 app/node_modules/lodash/_baseHas.js create mode 100644 app/node_modules/lodash/_baseHasIn.js create mode 100644 app/node_modules/lodash/_baseInRange.js create mode 100644 app/node_modules/lodash/_baseIndexOf.js create mode 100644 app/node_modules/lodash/_baseIndexOfWith.js create mode 100644 app/node_modules/lodash/_baseIntersection.js create mode 100644 app/node_modules/lodash/_baseInverter.js create mode 100644 app/node_modules/lodash/_baseInvoke.js create mode 100644 app/node_modules/lodash/_baseIsArguments.js create mode 100644 app/node_modules/lodash/_baseIsArrayBuffer.js create mode 100644 app/node_modules/lodash/_baseIsDate.js create mode 100644 app/node_modules/lodash/_baseIsEqual.js create mode 100644 app/node_modules/lodash/_baseIsEqualDeep.js create mode 100644 app/node_modules/lodash/_baseIsMap.js create mode 100644 app/node_modules/lodash/_baseIsMatch.js create mode 100644 app/node_modules/lodash/_baseIsNaN.js create mode 100644 app/node_modules/lodash/_baseIsNative.js create mode 100644 app/node_modules/lodash/_baseIsRegExp.js create mode 100644 app/node_modules/lodash/_baseIsSet.js create mode 100644 app/node_modules/lodash/_baseIsTypedArray.js create mode 100644 app/node_modules/lodash/_baseIteratee.js create mode 100644 app/node_modules/lodash/_baseKeys.js create mode 100644 app/node_modules/lodash/_baseKeysIn.js create mode 100644 app/node_modules/lodash/_baseLodash.js create mode 100644 app/node_modules/lodash/_baseLt.js create mode 100644 app/node_modules/lodash/_baseMap.js create mode 100644 app/node_modules/lodash/_baseMatches.js create mode 100644 app/node_modules/lodash/_baseMatchesProperty.js create mode 100644 app/node_modules/lodash/_baseMean.js create mode 100644 app/node_modules/lodash/_baseMerge.js create mode 100644 app/node_modules/lodash/_baseMergeDeep.js create mode 100644 app/node_modules/lodash/_baseNth.js create mode 100644 app/node_modules/lodash/_baseOrderBy.js create mode 100644 app/node_modules/lodash/_basePick.js create mode 100644 app/node_modules/lodash/_basePickBy.js create mode 100644 app/node_modules/lodash/_baseProperty.js create mode 100644 app/node_modules/lodash/_basePropertyDeep.js create mode 100644 app/node_modules/lodash/_basePropertyOf.js create mode 100644 app/node_modules/lodash/_basePullAll.js create mode 100644 app/node_modules/lodash/_basePullAt.js create mode 100644 app/node_modules/lodash/_baseRandom.js create mode 100644 app/node_modules/lodash/_baseRange.js create mode 100644 app/node_modules/lodash/_baseReduce.js create mode 100644 app/node_modules/lodash/_baseRepeat.js create mode 100644 app/node_modules/lodash/_baseRest.js create mode 100644 app/node_modules/lodash/_baseSample.js create mode 100644 app/node_modules/lodash/_baseSampleSize.js create mode 100644 app/node_modules/lodash/_baseSet.js create mode 100644 app/node_modules/lodash/_baseSetData.js create mode 100644 app/node_modules/lodash/_baseSetToString.js create mode 100644 app/node_modules/lodash/_baseShuffle.js create mode 100644 app/node_modules/lodash/_baseSlice.js create mode 100644 app/node_modules/lodash/_baseSome.js create mode 100644 app/node_modules/lodash/_baseSortBy.js create mode 100644 app/node_modules/lodash/_baseSortedIndex.js create mode 100644 app/node_modules/lodash/_baseSortedIndexBy.js create mode 100644 app/node_modules/lodash/_baseSortedUniq.js create mode 100644 app/node_modules/lodash/_baseSum.js create mode 100644 app/node_modules/lodash/_baseTimes.js create mode 100644 app/node_modules/lodash/_baseToNumber.js create mode 100644 app/node_modules/lodash/_baseToPairs.js create mode 100644 app/node_modules/lodash/_baseToString.js create mode 100644 app/node_modules/lodash/_baseUnary.js create mode 100644 app/node_modules/lodash/_baseUniq.js create mode 100644 app/node_modules/lodash/_baseUnset.js create mode 100644 app/node_modules/lodash/_baseUpdate.js create mode 100644 app/node_modules/lodash/_baseValues.js create mode 100644 app/node_modules/lodash/_baseWhile.js create mode 100644 app/node_modules/lodash/_baseWrapperValue.js create mode 100644 app/node_modules/lodash/_baseXor.js create mode 100644 app/node_modules/lodash/_baseZipObject.js create mode 100644 app/node_modules/lodash/_cacheHas.js create mode 100644 app/node_modules/lodash/_castArrayLikeObject.js create mode 100644 app/node_modules/lodash/_castFunction.js create mode 100644 app/node_modules/lodash/_castPath.js create mode 100644 app/node_modules/lodash/_castRest.js create mode 100644 app/node_modules/lodash/_castSlice.js create mode 100644 app/node_modules/lodash/_charsEndIndex.js create mode 100644 app/node_modules/lodash/_charsStartIndex.js create mode 100644 app/node_modules/lodash/_cloneArrayBuffer.js create mode 100644 app/node_modules/lodash/_cloneBuffer.js create mode 100644 app/node_modules/lodash/_cloneDataView.js create mode 100644 app/node_modules/lodash/_cloneRegExp.js create mode 100644 app/node_modules/lodash/_cloneSymbol.js create mode 100644 app/node_modules/lodash/_cloneTypedArray.js create mode 100644 app/node_modules/lodash/_compareAscending.js create mode 100644 app/node_modules/lodash/_compareMultiple.js create mode 100644 app/node_modules/lodash/_composeArgs.js create mode 100644 app/node_modules/lodash/_composeArgsRight.js create mode 100644 app/node_modules/lodash/_copyArray.js create mode 100644 app/node_modules/lodash/_copyObject.js create mode 100644 app/node_modules/lodash/_copySymbols.js create mode 100644 app/node_modules/lodash/_copySymbolsIn.js create mode 100644 app/node_modules/lodash/_coreJsData.js create mode 100644 app/node_modules/lodash/_countHolders.js create mode 100644 app/node_modules/lodash/_createAggregator.js create mode 100644 app/node_modules/lodash/_createAssigner.js create mode 100644 app/node_modules/lodash/_createBaseEach.js create mode 100644 app/node_modules/lodash/_createBaseFor.js create mode 100644 app/node_modules/lodash/_createBind.js create mode 100644 app/node_modules/lodash/_createCaseFirst.js create mode 100644 app/node_modules/lodash/_createCompounder.js create mode 100644 app/node_modules/lodash/_createCtor.js create mode 100644 app/node_modules/lodash/_createCurry.js create mode 100644 app/node_modules/lodash/_createFind.js create mode 100644 app/node_modules/lodash/_createFlow.js create mode 100644 app/node_modules/lodash/_createHybrid.js create mode 100644 app/node_modules/lodash/_createInverter.js create mode 100644 app/node_modules/lodash/_createMathOperation.js create mode 100644 app/node_modules/lodash/_createOver.js create mode 100644 app/node_modules/lodash/_createPadding.js create mode 100644 app/node_modules/lodash/_createPartial.js create mode 100644 app/node_modules/lodash/_createRange.js create mode 100644 app/node_modules/lodash/_createRecurry.js create mode 100644 app/node_modules/lodash/_createRelationalOperation.js create mode 100644 app/node_modules/lodash/_createRound.js create mode 100644 app/node_modules/lodash/_createSet.js create mode 100644 app/node_modules/lodash/_createToPairs.js create mode 100644 app/node_modules/lodash/_createWrap.js create mode 100644 app/node_modules/lodash/_customDefaultsAssignIn.js create mode 100644 app/node_modules/lodash/_customDefaultsMerge.js create mode 100644 app/node_modules/lodash/_customOmitClone.js create mode 100644 app/node_modules/lodash/_deburrLetter.js create mode 100644 app/node_modules/lodash/_defineProperty.js create mode 100644 app/node_modules/lodash/_equalArrays.js create mode 100644 app/node_modules/lodash/_equalByTag.js create mode 100644 app/node_modules/lodash/_equalObjects.js create mode 100644 app/node_modules/lodash/_escapeHtmlChar.js create mode 100644 app/node_modules/lodash/_escapeStringChar.js create mode 100644 app/node_modules/lodash/_flatRest.js create mode 100644 app/node_modules/lodash/_freeGlobal.js create mode 100644 app/node_modules/lodash/_getAllKeys.js create mode 100644 app/node_modules/lodash/_getAllKeysIn.js create mode 100644 app/node_modules/lodash/_getData.js create mode 100644 app/node_modules/lodash/_getFuncName.js create mode 100644 app/node_modules/lodash/_getHolder.js create mode 100644 app/node_modules/lodash/_getMapData.js create mode 100644 app/node_modules/lodash/_getMatchData.js create mode 100644 app/node_modules/lodash/_getNative.js create mode 100644 app/node_modules/lodash/_getPrototype.js create mode 100644 app/node_modules/lodash/_getRawTag.js create mode 100644 app/node_modules/lodash/_getSymbols.js create mode 100644 app/node_modules/lodash/_getSymbolsIn.js create mode 100644 app/node_modules/lodash/_getTag.js create mode 100644 app/node_modules/lodash/_getValue.js create mode 100644 app/node_modules/lodash/_getView.js create mode 100644 app/node_modules/lodash/_getWrapDetails.js create mode 100644 app/node_modules/lodash/_hasPath.js create mode 100644 app/node_modules/lodash/_hasUnicode.js create mode 100644 app/node_modules/lodash/_hasUnicodeWord.js create mode 100644 app/node_modules/lodash/_hashClear.js create mode 100644 app/node_modules/lodash/_hashDelete.js create mode 100644 app/node_modules/lodash/_hashGet.js create mode 100644 app/node_modules/lodash/_hashHas.js create mode 100644 app/node_modules/lodash/_hashSet.js create mode 100644 app/node_modules/lodash/_initCloneArray.js create mode 100644 app/node_modules/lodash/_initCloneByTag.js create mode 100644 app/node_modules/lodash/_initCloneObject.js create mode 100644 app/node_modules/lodash/_insertWrapDetails.js create mode 100644 app/node_modules/lodash/_isFlattenable.js create mode 100644 app/node_modules/lodash/_isIndex.js create mode 100644 app/node_modules/lodash/_isIterateeCall.js create mode 100644 app/node_modules/lodash/_isKey.js create mode 100644 app/node_modules/lodash/_isKeyable.js create mode 100644 app/node_modules/lodash/_isLaziable.js create mode 100644 app/node_modules/lodash/_isMaskable.js create mode 100644 app/node_modules/lodash/_isMasked.js create mode 100644 app/node_modules/lodash/_isPrototype.js create mode 100644 app/node_modules/lodash/_isStrictComparable.js create mode 100644 app/node_modules/lodash/_iteratorToArray.js create mode 100644 app/node_modules/lodash/_lazyClone.js create mode 100644 app/node_modules/lodash/_lazyReverse.js create mode 100644 app/node_modules/lodash/_lazyValue.js create mode 100644 app/node_modules/lodash/_listCacheClear.js create mode 100644 app/node_modules/lodash/_listCacheDelete.js create mode 100644 app/node_modules/lodash/_listCacheGet.js create mode 100644 app/node_modules/lodash/_listCacheHas.js create mode 100644 app/node_modules/lodash/_listCacheSet.js create mode 100644 app/node_modules/lodash/_mapCacheClear.js create mode 100644 app/node_modules/lodash/_mapCacheDelete.js create mode 100644 app/node_modules/lodash/_mapCacheGet.js create mode 100644 app/node_modules/lodash/_mapCacheHas.js create mode 100644 app/node_modules/lodash/_mapCacheSet.js create mode 100644 app/node_modules/lodash/_mapToArray.js create mode 100644 app/node_modules/lodash/_matchesStrictComparable.js create mode 100644 app/node_modules/lodash/_memoizeCapped.js create mode 100644 app/node_modules/lodash/_mergeData.js create mode 100644 app/node_modules/lodash/_metaMap.js create mode 100644 app/node_modules/lodash/_nativeCreate.js create mode 100644 app/node_modules/lodash/_nativeKeys.js create mode 100644 app/node_modules/lodash/_nativeKeysIn.js create mode 100644 app/node_modules/lodash/_nodeUtil.js create mode 100644 app/node_modules/lodash/_objectToString.js create mode 100644 app/node_modules/lodash/_overArg.js create mode 100644 app/node_modules/lodash/_overRest.js create mode 100644 app/node_modules/lodash/_parent.js create mode 100644 app/node_modules/lodash/_reEscape.js create mode 100644 app/node_modules/lodash/_reEvaluate.js create mode 100644 app/node_modules/lodash/_reInterpolate.js create mode 100644 app/node_modules/lodash/_realNames.js create mode 100644 app/node_modules/lodash/_reorder.js create mode 100644 app/node_modules/lodash/_replaceHolders.js create mode 100644 app/node_modules/lodash/_root.js create mode 100644 app/node_modules/lodash/_safeGet.js create mode 100644 app/node_modules/lodash/_setCacheAdd.js create mode 100644 app/node_modules/lodash/_setCacheHas.js create mode 100644 app/node_modules/lodash/_setData.js create mode 100644 app/node_modules/lodash/_setToArray.js create mode 100644 app/node_modules/lodash/_setToPairs.js create mode 100644 app/node_modules/lodash/_setToString.js create mode 100644 app/node_modules/lodash/_setWrapToString.js create mode 100644 app/node_modules/lodash/_shortOut.js create mode 100644 app/node_modules/lodash/_shuffleSelf.js create mode 100644 app/node_modules/lodash/_stackClear.js create mode 100644 app/node_modules/lodash/_stackDelete.js create mode 100644 app/node_modules/lodash/_stackGet.js create mode 100644 app/node_modules/lodash/_stackHas.js create mode 100644 app/node_modules/lodash/_stackSet.js create mode 100644 app/node_modules/lodash/_strictIndexOf.js create mode 100644 app/node_modules/lodash/_strictLastIndexOf.js create mode 100644 app/node_modules/lodash/_stringSize.js create mode 100644 app/node_modules/lodash/_stringToArray.js create mode 100644 app/node_modules/lodash/_stringToPath.js create mode 100644 app/node_modules/lodash/_toKey.js create mode 100644 app/node_modules/lodash/_toSource.js create mode 100644 app/node_modules/lodash/_unescapeHtmlChar.js create mode 100644 app/node_modules/lodash/_unicodeSize.js create mode 100644 app/node_modules/lodash/_unicodeToArray.js create mode 100644 app/node_modules/lodash/_unicodeWords.js create mode 100644 app/node_modules/lodash/_updateWrapDetails.js create mode 100644 app/node_modules/lodash/_wrapperClone.js create mode 100644 app/node_modules/lodash/add.js create mode 100644 app/node_modules/lodash/after.js create mode 100644 app/node_modules/lodash/array.js create mode 100644 app/node_modules/lodash/ary.js create mode 100644 app/node_modules/lodash/assign.js create mode 100644 app/node_modules/lodash/assignIn.js create mode 100644 app/node_modules/lodash/assignInWith.js create mode 100644 app/node_modules/lodash/assignWith.js create mode 100644 app/node_modules/lodash/at.js create mode 100644 app/node_modules/lodash/attempt.js create mode 100644 app/node_modules/lodash/before.js create mode 100644 app/node_modules/lodash/bind.js create mode 100644 app/node_modules/lodash/bindAll.js create mode 100644 app/node_modules/lodash/bindKey.js create mode 100644 app/node_modules/lodash/camelCase.js create mode 100644 app/node_modules/lodash/capitalize.js create mode 100644 app/node_modules/lodash/castArray.js create mode 100644 app/node_modules/lodash/ceil.js create mode 100644 app/node_modules/lodash/chain.js create mode 100644 app/node_modules/lodash/chunk.js create mode 100644 app/node_modules/lodash/clamp.js create mode 100644 app/node_modules/lodash/clone.js create mode 100644 app/node_modules/lodash/cloneDeep.js create mode 100644 app/node_modules/lodash/cloneDeepWith.js create mode 100644 app/node_modules/lodash/cloneWith.js create mode 100644 app/node_modules/lodash/collection.js create mode 100644 app/node_modules/lodash/commit.js create mode 100644 app/node_modules/lodash/compact.js create mode 100644 app/node_modules/lodash/concat.js create mode 100644 app/node_modules/lodash/cond.js create mode 100644 app/node_modules/lodash/conforms.js create mode 100644 app/node_modules/lodash/conformsTo.js create mode 100644 app/node_modules/lodash/constant.js create mode 100644 app/node_modules/lodash/core.js create mode 100644 app/node_modules/lodash/core.min.js create mode 100644 app/node_modules/lodash/countBy.js create mode 100644 app/node_modules/lodash/create.js create mode 100644 app/node_modules/lodash/curry.js create mode 100644 app/node_modules/lodash/curryRight.js create mode 100644 app/node_modules/lodash/date.js create mode 100644 app/node_modules/lodash/debounce.js create mode 100644 app/node_modules/lodash/deburr.js create mode 100644 app/node_modules/lodash/defaultTo.js create mode 100644 app/node_modules/lodash/defaults.js create mode 100644 app/node_modules/lodash/defaultsDeep.js create mode 100644 app/node_modules/lodash/defer.js create mode 100644 app/node_modules/lodash/delay.js create mode 100644 app/node_modules/lodash/difference.js create mode 100644 app/node_modules/lodash/differenceBy.js create mode 100644 app/node_modules/lodash/differenceWith.js create mode 100644 app/node_modules/lodash/divide.js create mode 100644 app/node_modules/lodash/drop.js create mode 100644 app/node_modules/lodash/dropRight.js create mode 100644 app/node_modules/lodash/dropRightWhile.js create mode 100644 app/node_modules/lodash/dropWhile.js create mode 100644 app/node_modules/lodash/each.js create mode 100644 app/node_modules/lodash/eachRight.js create mode 100644 app/node_modules/lodash/endsWith.js create mode 100644 app/node_modules/lodash/entries.js create mode 100644 app/node_modules/lodash/entriesIn.js create mode 100644 app/node_modules/lodash/eq.js create mode 100644 app/node_modules/lodash/escape.js create mode 100644 app/node_modules/lodash/escapeRegExp.js create mode 100644 app/node_modules/lodash/every.js create mode 100644 app/node_modules/lodash/extend.js create mode 100644 app/node_modules/lodash/extendWith.js create mode 100644 app/node_modules/lodash/fill.js create mode 100644 app/node_modules/lodash/filter.js create mode 100644 app/node_modules/lodash/find.js create mode 100644 app/node_modules/lodash/findIndex.js create mode 100644 app/node_modules/lodash/findKey.js create mode 100644 app/node_modules/lodash/findLast.js create mode 100644 app/node_modules/lodash/findLastIndex.js create mode 100644 app/node_modules/lodash/findLastKey.js create mode 100644 app/node_modules/lodash/first.js create mode 100644 app/node_modules/lodash/flatMap.js create mode 100644 app/node_modules/lodash/flatMapDeep.js create mode 100644 app/node_modules/lodash/flatMapDepth.js create mode 100644 app/node_modules/lodash/flatten.js create mode 100644 app/node_modules/lodash/flattenDeep.js create mode 100644 app/node_modules/lodash/flattenDepth.js create mode 100644 app/node_modules/lodash/flip.js create mode 100644 app/node_modules/lodash/floor.js create mode 100644 app/node_modules/lodash/flow.js create mode 100644 app/node_modules/lodash/flowRight.js create mode 100644 app/node_modules/lodash/forEach.js create mode 100644 app/node_modules/lodash/forEachRight.js create mode 100644 app/node_modules/lodash/forIn.js create mode 100644 app/node_modules/lodash/forInRight.js create mode 100644 app/node_modules/lodash/forOwn.js create mode 100644 app/node_modules/lodash/forOwnRight.js create mode 100644 app/node_modules/lodash/fp.js create mode 100644 app/node_modules/lodash/fp/F.js create mode 100644 app/node_modules/lodash/fp/T.js create mode 100644 app/node_modules/lodash/fp/__.js create mode 100644 app/node_modules/lodash/fp/_baseConvert.js create mode 100644 app/node_modules/lodash/fp/_convertBrowser.js create mode 100644 app/node_modules/lodash/fp/_falseOptions.js create mode 100644 app/node_modules/lodash/fp/_mapping.js create mode 100644 app/node_modules/lodash/fp/_util.js create mode 100644 app/node_modules/lodash/fp/add.js create mode 100644 app/node_modules/lodash/fp/after.js create mode 100644 app/node_modules/lodash/fp/all.js create mode 100644 app/node_modules/lodash/fp/allPass.js create mode 100644 app/node_modules/lodash/fp/always.js create mode 100644 app/node_modules/lodash/fp/any.js create mode 100644 app/node_modules/lodash/fp/anyPass.js create mode 100644 app/node_modules/lodash/fp/apply.js create mode 100644 app/node_modules/lodash/fp/array.js create mode 100644 app/node_modules/lodash/fp/ary.js create mode 100644 app/node_modules/lodash/fp/assign.js create mode 100644 app/node_modules/lodash/fp/assignAll.js create mode 100644 app/node_modules/lodash/fp/assignAllWith.js create mode 100644 app/node_modules/lodash/fp/assignIn.js create mode 100644 app/node_modules/lodash/fp/assignInAll.js create mode 100644 app/node_modules/lodash/fp/assignInAllWith.js create mode 100644 app/node_modules/lodash/fp/assignInWith.js create mode 100644 app/node_modules/lodash/fp/assignWith.js create mode 100644 app/node_modules/lodash/fp/assoc.js create mode 100644 app/node_modules/lodash/fp/assocPath.js create mode 100644 app/node_modules/lodash/fp/at.js create mode 100644 app/node_modules/lodash/fp/attempt.js create mode 100644 app/node_modules/lodash/fp/before.js create mode 100644 app/node_modules/lodash/fp/bind.js create mode 100644 app/node_modules/lodash/fp/bindAll.js create mode 100644 app/node_modules/lodash/fp/bindKey.js create mode 100644 app/node_modules/lodash/fp/camelCase.js create mode 100644 app/node_modules/lodash/fp/capitalize.js create mode 100644 app/node_modules/lodash/fp/castArray.js create mode 100644 app/node_modules/lodash/fp/ceil.js create mode 100644 app/node_modules/lodash/fp/chain.js create mode 100644 app/node_modules/lodash/fp/chunk.js create mode 100644 app/node_modules/lodash/fp/clamp.js create mode 100644 app/node_modules/lodash/fp/clone.js create mode 100644 app/node_modules/lodash/fp/cloneDeep.js create mode 100644 app/node_modules/lodash/fp/cloneDeepWith.js create mode 100644 app/node_modules/lodash/fp/cloneWith.js create mode 100644 app/node_modules/lodash/fp/collection.js create mode 100644 app/node_modules/lodash/fp/commit.js create mode 100644 app/node_modules/lodash/fp/compact.js create mode 100644 app/node_modules/lodash/fp/complement.js create mode 100644 app/node_modules/lodash/fp/compose.js create mode 100644 app/node_modules/lodash/fp/concat.js create mode 100644 app/node_modules/lodash/fp/cond.js create mode 100644 app/node_modules/lodash/fp/conforms.js create mode 100644 app/node_modules/lodash/fp/conformsTo.js create mode 100644 app/node_modules/lodash/fp/constant.js create mode 100644 app/node_modules/lodash/fp/contains.js create mode 100644 app/node_modules/lodash/fp/convert.js create mode 100644 app/node_modules/lodash/fp/countBy.js create mode 100644 app/node_modules/lodash/fp/create.js create mode 100644 app/node_modules/lodash/fp/curry.js create mode 100644 app/node_modules/lodash/fp/curryN.js create mode 100644 app/node_modules/lodash/fp/curryRight.js create mode 100644 app/node_modules/lodash/fp/curryRightN.js create mode 100644 app/node_modules/lodash/fp/date.js create mode 100644 app/node_modules/lodash/fp/debounce.js create mode 100644 app/node_modules/lodash/fp/deburr.js create mode 100644 app/node_modules/lodash/fp/defaultTo.js create mode 100644 app/node_modules/lodash/fp/defaults.js create mode 100644 app/node_modules/lodash/fp/defaultsAll.js create mode 100644 app/node_modules/lodash/fp/defaultsDeep.js create mode 100644 app/node_modules/lodash/fp/defaultsDeepAll.js create mode 100644 app/node_modules/lodash/fp/defer.js create mode 100644 app/node_modules/lodash/fp/delay.js create mode 100644 app/node_modules/lodash/fp/difference.js create mode 100644 app/node_modules/lodash/fp/differenceBy.js create mode 100644 app/node_modules/lodash/fp/differenceWith.js create mode 100644 app/node_modules/lodash/fp/dissoc.js create mode 100644 app/node_modules/lodash/fp/dissocPath.js create mode 100644 app/node_modules/lodash/fp/divide.js create mode 100644 app/node_modules/lodash/fp/drop.js create mode 100644 app/node_modules/lodash/fp/dropLast.js create mode 100644 app/node_modules/lodash/fp/dropLastWhile.js create mode 100644 app/node_modules/lodash/fp/dropRight.js create mode 100644 app/node_modules/lodash/fp/dropRightWhile.js create mode 100644 app/node_modules/lodash/fp/dropWhile.js create mode 100644 app/node_modules/lodash/fp/each.js create mode 100644 app/node_modules/lodash/fp/eachRight.js create mode 100644 app/node_modules/lodash/fp/endsWith.js create mode 100644 app/node_modules/lodash/fp/entries.js create mode 100644 app/node_modules/lodash/fp/entriesIn.js create mode 100644 app/node_modules/lodash/fp/eq.js create mode 100644 app/node_modules/lodash/fp/equals.js create mode 100644 app/node_modules/lodash/fp/escape.js create mode 100644 app/node_modules/lodash/fp/escapeRegExp.js create mode 100644 app/node_modules/lodash/fp/every.js create mode 100644 app/node_modules/lodash/fp/extend.js create mode 100644 app/node_modules/lodash/fp/extendAll.js create mode 100644 app/node_modules/lodash/fp/extendAllWith.js create mode 100644 app/node_modules/lodash/fp/extendWith.js create mode 100644 app/node_modules/lodash/fp/fill.js create mode 100644 app/node_modules/lodash/fp/filter.js create mode 100644 app/node_modules/lodash/fp/find.js create mode 100644 app/node_modules/lodash/fp/findFrom.js create mode 100644 app/node_modules/lodash/fp/findIndex.js create mode 100644 app/node_modules/lodash/fp/findIndexFrom.js create mode 100644 app/node_modules/lodash/fp/findKey.js create mode 100644 app/node_modules/lodash/fp/findLast.js create mode 100644 app/node_modules/lodash/fp/findLastFrom.js create mode 100644 app/node_modules/lodash/fp/findLastIndex.js create mode 100644 app/node_modules/lodash/fp/findLastIndexFrom.js create mode 100644 app/node_modules/lodash/fp/findLastKey.js create mode 100644 app/node_modules/lodash/fp/first.js create mode 100644 app/node_modules/lodash/fp/flatMap.js create mode 100644 app/node_modules/lodash/fp/flatMapDeep.js create mode 100644 app/node_modules/lodash/fp/flatMapDepth.js create mode 100644 app/node_modules/lodash/fp/flatten.js create mode 100644 app/node_modules/lodash/fp/flattenDeep.js create mode 100644 app/node_modules/lodash/fp/flattenDepth.js create mode 100644 app/node_modules/lodash/fp/flip.js create mode 100644 app/node_modules/lodash/fp/floor.js create mode 100644 app/node_modules/lodash/fp/flow.js create mode 100644 app/node_modules/lodash/fp/flowRight.js create mode 100644 app/node_modules/lodash/fp/forEach.js create mode 100644 app/node_modules/lodash/fp/forEachRight.js create mode 100644 app/node_modules/lodash/fp/forIn.js create mode 100644 app/node_modules/lodash/fp/forInRight.js create mode 100644 app/node_modules/lodash/fp/forOwn.js create mode 100644 app/node_modules/lodash/fp/forOwnRight.js create mode 100644 app/node_modules/lodash/fp/fromPairs.js create mode 100644 app/node_modules/lodash/fp/function.js create mode 100644 app/node_modules/lodash/fp/functions.js create mode 100644 app/node_modules/lodash/fp/functionsIn.js create mode 100644 app/node_modules/lodash/fp/get.js create mode 100644 app/node_modules/lodash/fp/getOr.js create mode 100644 app/node_modules/lodash/fp/groupBy.js create mode 100644 app/node_modules/lodash/fp/gt.js create mode 100644 app/node_modules/lodash/fp/gte.js create mode 100644 app/node_modules/lodash/fp/has.js create mode 100644 app/node_modules/lodash/fp/hasIn.js create mode 100644 app/node_modules/lodash/fp/head.js create mode 100644 app/node_modules/lodash/fp/identical.js create mode 100644 app/node_modules/lodash/fp/identity.js create mode 100644 app/node_modules/lodash/fp/inRange.js create mode 100644 app/node_modules/lodash/fp/includes.js create mode 100644 app/node_modules/lodash/fp/includesFrom.js create mode 100644 app/node_modules/lodash/fp/indexBy.js create mode 100644 app/node_modules/lodash/fp/indexOf.js create mode 100644 app/node_modules/lodash/fp/indexOfFrom.js create mode 100644 app/node_modules/lodash/fp/init.js create mode 100644 app/node_modules/lodash/fp/initial.js create mode 100644 app/node_modules/lodash/fp/intersection.js create mode 100644 app/node_modules/lodash/fp/intersectionBy.js create mode 100644 app/node_modules/lodash/fp/intersectionWith.js create mode 100644 app/node_modules/lodash/fp/invert.js create mode 100644 app/node_modules/lodash/fp/invertBy.js create mode 100644 app/node_modules/lodash/fp/invertObj.js create mode 100644 app/node_modules/lodash/fp/invoke.js create mode 100644 app/node_modules/lodash/fp/invokeArgs.js create mode 100644 app/node_modules/lodash/fp/invokeArgsMap.js create mode 100644 app/node_modules/lodash/fp/invokeMap.js create mode 100644 app/node_modules/lodash/fp/isArguments.js create mode 100644 app/node_modules/lodash/fp/isArray.js create mode 100644 app/node_modules/lodash/fp/isArrayBuffer.js create mode 100644 app/node_modules/lodash/fp/isArrayLike.js create mode 100644 app/node_modules/lodash/fp/isArrayLikeObject.js create mode 100644 app/node_modules/lodash/fp/isBoolean.js create mode 100644 app/node_modules/lodash/fp/isBuffer.js create mode 100644 app/node_modules/lodash/fp/isDate.js create mode 100644 app/node_modules/lodash/fp/isElement.js create mode 100644 app/node_modules/lodash/fp/isEmpty.js create mode 100644 app/node_modules/lodash/fp/isEqual.js create mode 100644 app/node_modules/lodash/fp/isEqualWith.js create mode 100644 app/node_modules/lodash/fp/isError.js create mode 100644 app/node_modules/lodash/fp/isFinite.js create mode 100644 app/node_modules/lodash/fp/isFunction.js create mode 100644 app/node_modules/lodash/fp/isInteger.js create mode 100644 app/node_modules/lodash/fp/isLength.js create mode 100644 app/node_modules/lodash/fp/isMap.js create mode 100644 app/node_modules/lodash/fp/isMatch.js create mode 100644 app/node_modules/lodash/fp/isMatchWith.js create mode 100644 app/node_modules/lodash/fp/isNaN.js create mode 100644 app/node_modules/lodash/fp/isNative.js create mode 100644 app/node_modules/lodash/fp/isNil.js create mode 100644 app/node_modules/lodash/fp/isNull.js create mode 100644 app/node_modules/lodash/fp/isNumber.js create mode 100644 app/node_modules/lodash/fp/isObject.js create mode 100644 app/node_modules/lodash/fp/isObjectLike.js create mode 100644 app/node_modules/lodash/fp/isPlainObject.js create mode 100644 app/node_modules/lodash/fp/isRegExp.js create mode 100644 app/node_modules/lodash/fp/isSafeInteger.js create mode 100644 app/node_modules/lodash/fp/isSet.js create mode 100644 app/node_modules/lodash/fp/isString.js create mode 100644 app/node_modules/lodash/fp/isSymbol.js create mode 100644 app/node_modules/lodash/fp/isTypedArray.js create mode 100644 app/node_modules/lodash/fp/isUndefined.js create mode 100644 app/node_modules/lodash/fp/isWeakMap.js create mode 100644 app/node_modules/lodash/fp/isWeakSet.js create mode 100644 app/node_modules/lodash/fp/iteratee.js create mode 100644 app/node_modules/lodash/fp/join.js create mode 100644 app/node_modules/lodash/fp/juxt.js create mode 100644 app/node_modules/lodash/fp/kebabCase.js create mode 100644 app/node_modules/lodash/fp/keyBy.js create mode 100644 app/node_modules/lodash/fp/keys.js create mode 100644 app/node_modules/lodash/fp/keysIn.js create mode 100644 app/node_modules/lodash/fp/lang.js create mode 100644 app/node_modules/lodash/fp/last.js create mode 100644 app/node_modules/lodash/fp/lastIndexOf.js create mode 100644 app/node_modules/lodash/fp/lastIndexOfFrom.js create mode 100644 app/node_modules/lodash/fp/lowerCase.js create mode 100644 app/node_modules/lodash/fp/lowerFirst.js create mode 100644 app/node_modules/lodash/fp/lt.js create mode 100644 app/node_modules/lodash/fp/lte.js create mode 100644 app/node_modules/lodash/fp/map.js create mode 100644 app/node_modules/lodash/fp/mapKeys.js create mode 100644 app/node_modules/lodash/fp/mapValues.js create mode 100644 app/node_modules/lodash/fp/matches.js create mode 100644 app/node_modules/lodash/fp/matchesProperty.js create mode 100644 app/node_modules/lodash/fp/math.js create mode 100644 app/node_modules/lodash/fp/max.js create mode 100644 app/node_modules/lodash/fp/maxBy.js create mode 100644 app/node_modules/lodash/fp/mean.js create mode 100644 app/node_modules/lodash/fp/meanBy.js create mode 100644 app/node_modules/lodash/fp/memoize.js create mode 100644 app/node_modules/lodash/fp/merge.js create mode 100644 app/node_modules/lodash/fp/mergeAll.js create mode 100644 app/node_modules/lodash/fp/mergeAllWith.js create mode 100644 app/node_modules/lodash/fp/mergeWith.js create mode 100644 app/node_modules/lodash/fp/method.js create mode 100644 app/node_modules/lodash/fp/methodOf.js create mode 100644 app/node_modules/lodash/fp/min.js create mode 100644 app/node_modules/lodash/fp/minBy.js create mode 100644 app/node_modules/lodash/fp/mixin.js create mode 100644 app/node_modules/lodash/fp/multiply.js create mode 100644 app/node_modules/lodash/fp/nAry.js create mode 100644 app/node_modules/lodash/fp/negate.js create mode 100644 app/node_modules/lodash/fp/next.js create mode 100644 app/node_modules/lodash/fp/noop.js create mode 100644 app/node_modules/lodash/fp/now.js create mode 100644 app/node_modules/lodash/fp/nth.js create mode 100644 app/node_modules/lodash/fp/nthArg.js create mode 100644 app/node_modules/lodash/fp/number.js create mode 100644 app/node_modules/lodash/fp/object.js create mode 100644 app/node_modules/lodash/fp/omit.js create mode 100644 app/node_modules/lodash/fp/omitAll.js create mode 100644 app/node_modules/lodash/fp/omitBy.js create mode 100644 app/node_modules/lodash/fp/once.js create mode 100644 app/node_modules/lodash/fp/orderBy.js create mode 100644 app/node_modules/lodash/fp/over.js create mode 100644 app/node_modules/lodash/fp/overArgs.js create mode 100644 app/node_modules/lodash/fp/overEvery.js create mode 100644 app/node_modules/lodash/fp/overSome.js create mode 100644 app/node_modules/lodash/fp/pad.js create mode 100644 app/node_modules/lodash/fp/padChars.js create mode 100644 app/node_modules/lodash/fp/padCharsEnd.js create mode 100644 app/node_modules/lodash/fp/padCharsStart.js create mode 100644 app/node_modules/lodash/fp/padEnd.js create mode 100644 app/node_modules/lodash/fp/padStart.js create mode 100644 app/node_modules/lodash/fp/parseInt.js create mode 100644 app/node_modules/lodash/fp/partial.js create mode 100644 app/node_modules/lodash/fp/partialRight.js create mode 100644 app/node_modules/lodash/fp/partition.js create mode 100644 app/node_modules/lodash/fp/path.js create mode 100644 app/node_modules/lodash/fp/pathEq.js create mode 100644 app/node_modules/lodash/fp/pathOr.js create mode 100644 app/node_modules/lodash/fp/paths.js create mode 100644 app/node_modules/lodash/fp/pick.js create mode 100644 app/node_modules/lodash/fp/pickAll.js create mode 100644 app/node_modules/lodash/fp/pickBy.js create mode 100644 app/node_modules/lodash/fp/pipe.js create mode 100644 app/node_modules/lodash/fp/placeholder.js create mode 100644 app/node_modules/lodash/fp/plant.js create mode 100644 app/node_modules/lodash/fp/pluck.js create mode 100644 app/node_modules/lodash/fp/prop.js create mode 100644 app/node_modules/lodash/fp/propEq.js create mode 100644 app/node_modules/lodash/fp/propOr.js create mode 100644 app/node_modules/lodash/fp/property.js create mode 100644 app/node_modules/lodash/fp/propertyOf.js create mode 100644 app/node_modules/lodash/fp/props.js create mode 100644 app/node_modules/lodash/fp/pull.js create mode 100644 app/node_modules/lodash/fp/pullAll.js create mode 100644 app/node_modules/lodash/fp/pullAllBy.js create mode 100644 app/node_modules/lodash/fp/pullAllWith.js create mode 100644 app/node_modules/lodash/fp/pullAt.js create mode 100644 app/node_modules/lodash/fp/random.js create mode 100644 app/node_modules/lodash/fp/range.js create mode 100644 app/node_modules/lodash/fp/rangeRight.js create mode 100644 app/node_modules/lodash/fp/rangeStep.js create mode 100644 app/node_modules/lodash/fp/rangeStepRight.js create mode 100644 app/node_modules/lodash/fp/rearg.js create mode 100644 app/node_modules/lodash/fp/reduce.js create mode 100644 app/node_modules/lodash/fp/reduceRight.js create mode 100644 app/node_modules/lodash/fp/reject.js create mode 100644 app/node_modules/lodash/fp/remove.js create mode 100644 app/node_modules/lodash/fp/repeat.js create mode 100644 app/node_modules/lodash/fp/replace.js create mode 100644 app/node_modules/lodash/fp/rest.js create mode 100644 app/node_modules/lodash/fp/restFrom.js create mode 100644 app/node_modules/lodash/fp/result.js create mode 100644 app/node_modules/lodash/fp/reverse.js create mode 100644 app/node_modules/lodash/fp/round.js create mode 100644 app/node_modules/lodash/fp/sample.js create mode 100644 app/node_modules/lodash/fp/sampleSize.js create mode 100644 app/node_modules/lodash/fp/seq.js create mode 100644 app/node_modules/lodash/fp/set.js create mode 100644 app/node_modules/lodash/fp/setWith.js create mode 100644 app/node_modules/lodash/fp/shuffle.js create mode 100644 app/node_modules/lodash/fp/size.js create mode 100644 app/node_modules/lodash/fp/slice.js create mode 100644 app/node_modules/lodash/fp/snakeCase.js create mode 100644 app/node_modules/lodash/fp/some.js create mode 100644 app/node_modules/lodash/fp/sortBy.js create mode 100644 app/node_modules/lodash/fp/sortedIndex.js create mode 100644 app/node_modules/lodash/fp/sortedIndexBy.js create mode 100644 app/node_modules/lodash/fp/sortedIndexOf.js create mode 100644 app/node_modules/lodash/fp/sortedLastIndex.js create mode 100644 app/node_modules/lodash/fp/sortedLastIndexBy.js create mode 100644 app/node_modules/lodash/fp/sortedLastIndexOf.js create mode 100644 app/node_modules/lodash/fp/sortedUniq.js create mode 100644 app/node_modules/lodash/fp/sortedUniqBy.js create mode 100644 app/node_modules/lodash/fp/split.js create mode 100644 app/node_modules/lodash/fp/spread.js create mode 100644 app/node_modules/lodash/fp/spreadFrom.js create mode 100644 app/node_modules/lodash/fp/startCase.js create mode 100644 app/node_modules/lodash/fp/startsWith.js create mode 100644 app/node_modules/lodash/fp/string.js create mode 100644 app/node_modules/lodash/fp/stubArray.js create mode 100644 app/node_modules/lodash/fp/stubFalse.js create mode 100644 app/node_modules/lodash/fp/stubObject.js create mode 100644 app/node_modules/lodash/fp/stubString.js create mode 100644 app/node_modules/lodash/fp/stubTrue.js create mode 100644 app/node_modules/lodash/fp/subtract.js create mode 100644 app/node_modules/lodash/fp/sum.js create mode 100644 app/node_modules/lodash/fp/sumBy.js create mode 100644 app/node_modules/lodash/fp/symmetricDifference.js create mode 100644 app/node_modules/lodash/fp/symmetricDifferenceBy.js create mode 100644 app/node_modules/lodash/fp/symmetricDifferenceWith.js create mode 100644 app/node_modules/lodash/fp/tail.js create mode 100644 app/node_modules/lodash/fp/take.js create mode 100644 app/node_modules/lodash/fp/takeLast.js create mode 100644 app/node_modules/lodash/fp/takeLastWhile.js create mode 100644 app/node_modules/lodash/fp/takeRight.js create mode 100644 app/node_modules/lodash/fp/takeRightWhile.js create mode 100644 app/node_modules/lodash/fp/takeWhile.js create mode 100644 app/node_modules/lodash/fp/tap.js create mode 100644 app/node_modules/lodash/fp/template.js create mode 100644 app/node_modules/lodash/fp/templateSettings.js create mode 100644 app/node_modules/lodash/fp/throttle.js create mode 100644 app/node_modules/lodash/fp/thru.js create mode 100644 app/node_modules/lodash/fp/times.js create mode 100644 app/node_modules/lodash/fp/toArray.js create mode 100644 app/node_modules/lodash/fp/toFinite.js create mode 100644 app/node_modules/lodash/fp/toInteger.js create mode 100644 app/node_modules/lodash/fp/toIterator.js create mode 100644 app/node_modules/lodash/fp/toJSON.js create mode 100644 app/node_modules/lodash/fp/toLength.js create mode 100644 app/node_modules/lodash/fp/toLower.js create mode 100644 app/node_modules/lodash/fp/toNumber.js create mode 100644 app/node_modules/lodash/fp/toPairs.js create mode 100644 app/node_modules/lodash/fp/toPairsIn.js create mode 100644 app/node_modules/lodash/fp/toPath.js create mode 100644 app/node_modules/lodash/fp/toPlainObject.js create mode 100644 app/node_modules/lodash/fp/toSafeInteger.js create mode 100644 app/node_modules/lodash/fp/toString.js create mode 100644 app/node_modules/lodash/fp/toUpper.js create mode 100644 app/node_modules/lodash/fp/transform.js create mode 100644 app/node_modules/lodash/fp/trim.js create mode 100644 app/node_modules/lodash/fp/trimChars.js create mode 100644 app/node_modules/lodash/fp/trimCharsEnd.js create mode 100644 app/node_modules/lodash/fp/trimCharsStart.js create mode 100644 app/node_modules/lodash/fp/trimEnd.js create mode 100644 app/node_modules/lodash/fp/trimStart.js create mode 100644 app/node_modules/lodash/fp/truncate.js create mode 100644 app/node_modules/lodash/fp/unapply.js create mode 100644 app/node_modules/lodash/fp/unary.js create mode 100644 app/node_modules/lodash/fp/unescape.js create mode 100644 app/node_modules/lodash/fp/union.js create mode 100644 app/node_modules/lodash/fp/unionBy.js create mode 100644 app/node_modules/lodash/fp/unionWith.js create mode 100644 app/node_modules/lodash/fp/uniq.js create mode 100644 app/node_modules/lodash/fp/uniqBy.js create mode 100644 app/node_modules/lodash/fp/uniqWith.js create mode 100644 app/node_modules/lodash/fp/uniqueId.js create mode 100644 app/node_modules/lodash/fp/unnest.js create mode 100644 app/node_modules/lodash/fp/unset.js create mode 100644 app/node_modules/lodash/fp/unzip.js create mode 100644 app/node_modules/lodash/fp/unzipWith.js create mode 100644 app/node_modules/lodash/fp/update.js create mode 100644 app/node_modules/lodash/fp/updateWith.js create mode 100644 app/node_modules/lodash/fp/upperCase.js create mode 100644 app/node_modules/lodash/fp/upperFirst.js create mode 100644 app/node_modules/lodash/fp/useWith.js create mode 100644 app/node_modules/lodash/fp/util.js create mode 100644 app/node_modules/lodash/fp/value.js create mode 100644 app/node_modules/lodash/fp/valueOf.js create mode 100644 app/node_modules/lodash/fp/values.js create mode 100644 app/node_modules/lodash/fp/valuesIn.js create mode 100644 app/node_modules/lodash/fp/where.js create mode 100644 app/node_modules/lodash/fp/whereEq.js create mode 100644 app/node_modules/lodash/fp/without.js create mode 100644 app/node_modules/lodash/fp/words.js create mode 100644 app/node_modules/lodash/fp/wrap.js create mode 100644 app/node_modules/lodash/fp/wrapperAt.js create mode 100644 app/node_modules/lodash/fp/wrapperChain.js create mode 100644 app/node_modules/lodash/fp/wrapperLodash.js create mode 100644 app/node_modules/lodash/fp/wrapperReverse.js create mode 100644 app/node_modules/lodash/fp/wrapperValue.js create mode 100644 app/node_modules/lodash/fp/xor.js create mode 100644 app/node_modules/lodash/fp/xorBy.js create mode 100644 app/node_modules/lodash/fp/xorWith.js create mode 100644 app/node_modules/lodash/fp/zip.js create mode 100644 app/node_modules/lodash/fp/zipAll.js create mode 100644 app/node_modules/lodash/fp/zipObj.js create mode 100644 app/node_modules/lodash/fp/zipObject.js create mode 100644 app/node_modules/lodash/fp/zipObjectDeep.js create mode 100644 app/node_modules/lodash/fp/zipWith.js create mode 100644 app/node_modules/lodash/fromPairs.js create mode 100644 app/node_modules/lodash/function.js create mode 100644 app/node_modules/lodash/functions.js create mode 100644 app/node_modules/lodash/functionsIn.js create mode 100644 app/node_modules/lodash/get.js create mode 100644 app/node_modules/lodash/groupBy.js create mode 100644 app/node_modules/lodash/gt.js create mode 100644 app/node_modules/lodash/gte.js create mode 100644 app/node_modules/lodash/has.js create mode 100644 app/node_modules/lodash/hasIn.js create mode 100644 app/node_modules/lodash/head.js create mode 100644 app/node_modules/lodash/identity.js create mode 100644 app/node_modules/lodash/inRange.js create mode 100644 app/node_modules/lodash/includes.js create mode 100644 app/node_modules/lodash/index.js create mode 100644 app/node_modules/lodash/indexOf.js create mode 100644 app/node_modules/lodash/initial.js create mode 100644 app/node_modules/lodash/intersection.js create mode 100644 app/node_modules/lodash/intersectionBy.js create mode 100644 app/node_modules/lodash/intersectionWith.js create mode 100644 app/node_modules/lodash/invert.js create mode 100644 app/node_modules/lodash/invertBy.js create mode 100644 app/node_modules/lodash/invoke.js create mode 100644 app/node_modules/lodash/invokeMap.js create mode 100644 app/node_modules/lodash/isArguments.js create mode 100644 app/node_modules/lodash/isArray.js create mode 100644 app/node_modules/lodash/isArrayBuffer.js create mode 100644 app/node_modules/lodash/isArrayLike.js create mode 100644 app/node_modules/lodash/isArrayLikeObject.js create mode 100644 app/node_modules/lodash/isBoolean.js create mode 100644 app/node_modules/lodash/isBuffer.js create mode 100644 app/node_modules/lodash/isDate.js create mode 100644 app/node_modules/lodash/isElement.js create mode 100644 app/node_modules/lodash/isEmpty.js create mode 100644 app/node_modules/lodash/isEqual.js create mode 100644 app/node_modules/lodash/isEqualWith.js create mode 100644 app/node_modules/lodash/isError.js create mode 100644 app/node_modules/lodash/isFinite.js create mode 100644 app/node_modules/lodash/isFunction.js create mode 100644 app/node_modules/lodash/isInteger.js create mode 100644 app/node_modules/lodash/isLength.js create mode 100644 app/node_modules/lodash/isMap.js create mode 100644 app/node_modules/lodash/isMatch.js create mode 100644 app/node_modules/lodash/isMatchWith.js create mode 100644 app/node_modules/lodash/isNaN.js create mode 100644 app/node_modules/lodash/isNative.js create mode 100644 app/node_modules/lodash/isNil.js create mode 100644 app/node_modules/lodash/isNull.js create mode 100644 app/node_modules/lodash/isNumber.js create mode 100644 app/node_modules/lodash/isObject.js create mode 100644 app/node_modules/lodash/isObjectLike.js create mode 100644 app/node_modules/lodash/isPlainObject.js create mode 100644 app/node_modules/lodash/isRegExp.js create mode 100644 app/node_modules/lodash/isSafeInteger.js create mode 100644 app/node_modules/lodash/isSet.js create mode 100644 app/node_modules/lodash/isString.js create mode 100644 app/node_modules/lodash/isSymbol.js create mode 100644 app/node_modules/lodash/isTypedArray.js create mode 100644 app/node_modules/lodash/isUndefined.js create mode 100644 app/node_modules/lodash/isWeakMap.js create mode 100644 app/node_modules/lodash/isWeakSet.js create mode 100644 app/node_modules/lodash/iteratee.js create mode 100644 app/node_modules/lodash/join.js create mode 100644 app/node_modules/lodash/kebabCase.js create mode 100644 app/node_modules/lodash/keyBy.js create mode 100644 app/node_modules/lodash/keys.js create mode 100644 app/node_modules/lodash/keysIn.js create mode 100644 app/node_modules/lodash/lang.js create mode 100644 app/node_modules/lodash/last.js create mode 100644 app/node_modules/lodash/lastIndexOf.js create mode 100644 app/node_modules/lodash/lodash.js create mode 100644 app/node_modules/lodash/lodash.min.js create mode 100644 app/node_modules/lodash/lowerCase.js create mode 100644 app/node_modules/lodash/lowerFirst.js create mode 100644 app/node_modules/lodash/lt.js create mode 100644 app/node_modules/lodash/lte.js create mode 100644 app/node_modules/lodash/map.js create mode 100644 app/node_modules/lodash/mapKeys.js create mode 100644 app/node_modules/lodash/mapValues.js create mode 100644 app/node_modules/lodash/matches.js create mode 100644 app/node_modules/lodash/matchesProperty.js create mode 100644 app/node_modules/lodash/math.js create mode 100644 app/node_modules/lodash/max.js create mode 100644 app/node_modules/lodash/maxBy.js create mode 100644 app/node_modules/lodash/mean.js create mode 100644 app/node_modules/lodash/meanBy.js create mode 100644 app/node_modules/lodash/memoize.js create mode 100644 app/node_modules/lodash/merge.js create mode 100644 app/node_modules/lodash/mergeWith.js create mode 100644 app/node_modules/lodash/method.js create mode 100644 app/node_modules/lodash/methodOf.js create mode 100644 app/node_modules/lodash/min.js create mode 100644 app/node_modules/lodash/minBy.js create mode 100644 app/node_modules/lodash/mixin.js create mode 100644 app/node_modules/lodash/multiply.js create mode 100644 app/node_modules/lodash/negate.js create mode 100644 app/node_modules/lodash/next.js create mode 100644 app/node_modules/lodash/noop.js create mode 100644 app/node_modules/lodash/now.js create mode 100644 app/node_modules/lodash/nth.js create mode 100644 app/node_modules/lodash/nthArg.js create mode 100644 app/node_modules/lodash/number.js create mode 100644 app/node_modules/lodash/object.js create mode 100644 app/node_modules/lodash/omit.js create mode 100644 app/node_modules/lodash/omitBy.js create mode 100644 app/node_modules/lodash/once.js create mode 100644 app/node_modules/lodash/orderBy.js create mode 100644 app/node_modules/lodash/over.js create mode 100644 app/node_modules/lodash/overArgs.js create mode 100644 app/node_modules/lodash/overEvery.js create mode 100644 app/node_modules/lodash/overSome.js create mode 100644 app/node_modules/lodash/package.json create mode 100644 app/node_modules/lodash/pad.js create mode 100644 app/node_modules/lodash/padEnd.js create mode 100644 app/node_modules/lodash/padStart.js create mode 100644 app/node_modules/lodash/parseInt.js create mode 100644 app/node_modules/lodash/partial.js create mode 100644 app/node_modules/lodash/partialRight.js create mode 100644 app/node_modules/lodash/partition.js create mode 100644 app/node_modules/lodash/pick.js create mode 100644 app/node_modules/lodash/pickBy.js create mode 100644 app/node_modules/lodash/plant.js create mode 100644 app/node_modules/lodash/property.js create mode 100644 app/node_modules/lodash/propertyOf.js create mode 100644 app/node_modules/lodash/pull.js create mode 100644 app/node_modules/lodash/pullAll.js create mode 100644 app/node_modules/lodash/pullAllBy.js create mode 100644 app/node_modules/lodash/pullAllWith.js create mode 100644 app/node_modules/lodash/pullAt.js create mode 100644 app/node_modules/lodash/random.js create mode 100644 app/node_modules/lodash/range.js create mode 100644 app/node_modules/lodash/rangeRight.js create mode 100644 app/node_modules/lodash/rearg.js create mode 100644 app/node_modules/lodash/reduce.js create mode 100644 app/node_modules/lodash/reduceRight.js create mode 100644 app/node_modules/lodash/reject.js create mode 100644 app/node_modules/lodash/remove.js create mode 100644 app/node_modules/lodash/repeat.js create mode 100644 app/node_modules/lodash/replace.js create mode 100644 app/node_modules/lodash/rest.js create mode 100644 app/node_modules/lodash/result.js create mode 100644 app/node_modules/lodash/reverse.js create mode 100644 app/node_modules/lodash/round.js create mode 100644 app/node_modules/lodash/sample.js create mode 100644 app/node_modules/lodash/sampleSize.js create mode 100644 app/node_modules/lodash/seq.js create mode 100644 app/node_modules/lodash/set.js create mode 100644 app/node_modules/lodash/setWith.js create mode 100644 app/node_modules/lodash/shuffle.js create mode 100644 app/node_modules/lodash/size.js create mode 100644 app/node_modules/lodash/slice.js create mode 100644 app/node_modules/lodash/snakeCase.js create mode 100644 app/node_modules/lodash/some.js create mode 100644 app/node_modules/lodash/sortBy.js create mode 100644 app/node_modules/lodash/sortedIndex.js create mode 100644 app/node_modules/lodash/sortedIndexBy.js create mode 100644 app/node_modules/lodash/sortedIndexOf.js create mode 100644 app/node_modules/lodash/sortedLastIndex.js create mode 100644 app/node_modules/lodash/sortedLastIndexBy.js create mode 100644 app/node_modules/lodash/sortedLastIndexOf.js create mode 100644 app/node_modules/lodash/sortedUniq.js create mode 100644 app/node_modules/lodash/sortedUniqBy.js create mode 100644 app/node_modules/lodash/split.js create mode 100644 app/node_modules/lodash/spread.js create mode 100644 app/node_modules/lodash/startCase.js create mode 100644 app/node_modules/lodash/startsWith.js create mode 100644 app/node_modules/lodash/string.js create mode 100644 app/node_modules/lodash/stubArray.js create mode 100644 app/node_modules/lodash/stubFalse.js create mode 100644 app/node_modules/lodash/stubObject.js create mode 100644 app/node_modules/lodash/stubString.js create mode 100644 app/node_modules/lodash/stubTrue.js create mode 100644 app/node_modules/lodash/subtract.js create mode 100644 app/node_modules/lodash/sum.js create mode 100644 app/node_modules/lodash/sumBy.js create mode 100644 app/node_modules/lodash/tail.js create mode 100644 app/node_modules/lodash/take.js create mode 100644 app/node_modules/lodash/takeRight.js create mode 100644 app/node_modules/lodash/takeRightWhile.js create mode 100644 app/node_modules/lodash/takeWhile.js create mode 100644 app/node_modules/lodash/tap.js create mode 100644 app/node_modules/lodash/template.js create mode 100644 app/node_modules/lodash/templateSettings.js create mode 100644 app/node_modules/lodash/throttle.js create mode 100644 app/node_modules/lodash/thru.js create mode 100644 app/node_modules/lodash/times.js create mode 100644 app/node_modules/lodash/toArray.js create mode 100644 app/node_modules/lodash/toFinite.js create mode 100644 app/node_modules/lodash/toInteger.js create mode 100644 app/node_modules/lodash/toIterator.js create mode 100644 app/node_modules/lodash/toJSON.js create mode 100644 app/node_modules/lodash/toLength.js create mode 100644 app/node_modules/lodash/toLower.js create mode 100644 app/node_modules/lodash/toNumber.js create mode 100644 app/node_modules/lodash/toPairs.js create mode 100644 app/node_modules/lodash/toPairsIn.js create mode 100644 app/node_modules/lodash/toPath.js create mode 100644 app/node_modules/lodash/toPlainObject.js create mode 100644 app/node_modules/lodash/toSafeInteger.js create mode 100644 app/node_modules/lodash/toString.js create mode 100644 app/node_modules/lodash/toUpper.js create mode 100644 app/node_modules/lodash/transform.js create mode 100644 app/node_modules/lodash/trim.js create mode 100644 app/node_modules/lodash/trimEnd.js create mode 100644 app/node_modules/lodash/trimStart.js create mode 100644 app/node_modules/lodash/truncate.js create mode 100644 app/node_modules/lodash/unary.js create mode 100644 app/node_modules/lodash/unescape.js create mode 100644 app/node_modules/lodash/union.js create mode 100644 app/node_modules/lodash/unionBy.js create mode 100644 app/node_modules/lodash/unionWith.js create mode 100644 app/node_modules/lodash/uniq.js create mode 100644 app/node_modules/lodash/uniqBy.js create mode 100644 app/node_modules/lodash/uniqWith.js create mode 100644 app/node_modules/lodash/uniqueId.js create mode 100644 app/node_modules/lodash/unset.js create mode 100644 app/node_modules/lodash/unzip.js create mode 100644 app/node_modules/lodash/unzipWith.js create mode 100644 app/node_modules/lodash/update.js create mode 100644 app/node_modules/lodash/updateWith.js create mode 100644 app/node_modules/lodash/upperCase.js create mode 100644 app/node_modules/lodash/upperFirst.js create mode 100644 app/node_modules/lodash/util.js create mode 100644 app/node_modules/lodash/value.js create mode 100644 app/node_modules/lodash/valueOf.js create mode 100644 app/node_modules/lodash/values.js create mode 100644 app/node_modules/lodash/valuesIn.js create mode 100644 app/node_modules/lodash/without.js create mode 100644 app/node_modules/lodash/words.js create mode 100644 app/node_modules/lodash/wrap.js create mode 100644 app/node_modules/lodash/wrapperAt.js create mode 100644 app/node_modules/lodash/wrapperChain.js create mode 100644 app/node_modules/lodash/wrapperLodash.js create mode 100644 app/node_modules/lodash/wrapperReverse.js create mode 100644 app/node_modules/lodash/wrapperValue.js create mode 100644 app/node_modules/lodash/xor.js create mode 100644 app/node_modules/lodash/xorBy.js create mode 100644 app/node_modules/lodash/xorWith.js create mode 100644 app/node_modules/lodash/zip.js create mode 100644 app/node_modules/lodash/zipObject.js create mode 100644 app/node_modules/lodash/zipObjectDeep.js create mode 100644 app/node_modules/lodash/zipWith.js create mode 100644 app/node_modules/media-typer/HISTORY.md create mode 100644 app/node_modules/media-typer/LICENSE create mode 100644 app/node_modules/media-typer/README.md create mode 100644 app/node_modules/media-typer/index.js create mode 100644 app/node_modules/media-typer/package.json create mode 100644 app/node_modules/merge-descriptors/HISTORY.md create mode 100644 app/node_modules/merge-descriptors/LICENSE create mode 100644 app/node_modules/merge-descriptors/README.md create mode 100644 app/node_modules/merge-descriptors/index.js create mode 100644 app/node_modules/merge-descriptors/package.json create mode 100644 app/node_modules/methods/HISTORY.md create mode 100644 app/node_modules/methods/LICENSE create mode 100644 app/node_modules/methods/README.md create mode 100644 app/node_modules/methods/index.js create mode 100644 app/node_modules/methods/package.json create mode 100644 app/node_modules/mime-db/HISTORY.md create mode 100644 app/node_modules/mime-db/LICENSE create mode 100644 app/node_modules/mime-db/README.md create mode 100644 app/node_modules/mime-db/db.json create mode 100644 app/node_modules/mime-db/index.js create mode 100644 app/node_modules/mime-db/package.json create mode 100644 app/node_modules/mime-types/HISTORY.md create mode 100644 app/node_modules/mime-types/LICENSE create mode 100644 app/node_modules/mime-types/README.md create mode 100644 app/node_modules/mime-types/index.js create mode 100644 app/node_modules/mime-types/package.json create mode 100644 app/node_modules/mime/LICENSE create mode 100644 app/node_modules/mime/README.md create mode 100644 app/node_modules/mime/build/build.js create mode 100644 app/node_modules/mime/build/test.js create mode 100755 app/node_modules/mime/cli.js create mode 100644 app/node_modules/mime/mime.js create mode 100644 app/node_modules/mime/package.json create mode 100644 app/node_modules/mime/types.json create mode 100644 app/node_modules/mongoclient/.npmignore create mode 100644 app/node_modules/mongoclient/README.md create mode 100644 app/node_modules/mongoclient/config.js create mode 100644 app/node_modules/mongoclient/index.js create mode 100644 app/node_modules/mongoclient/package.json create mode 100644 app/node_modules/mongodb-core/.coveralls.yml create mode 100644 app/node_modules/mongodb-core/.eslintrc create mode 100644 app/node_modules/mongodb-core/HISTORY.md create mode 100644 app/node_modules/mongodb-core/LICENSE create mode 100644 app/node_modules/mongodb-core/Makefile create mode 100644 app/node_modules/mongodb-core/README.md create mode 100644 app/node_modules/mongodb-core/TESTING.md create mode 100644 app/node_modules/mongodb-core/THIRD-PARTY-NOTICES create mode 100644 app/node_modules/mongodb-core/conf.json create mode 100644 app/node_modules/mongodb-core/index.js create mode 100644 app/node_modules/mongodb-core/lib/auth/gssapi.js create mode 100644 app/node_modules/mongodb-core/lib/auth/mongocr.js create mode 100644 app/node_modules/mongodb-core/lib/auth/plain.js create mode 100644 app/node_modules/mongodb-core/lib/auth/scram.js create mode 100644 app/node_modules/mongodb-core/lib/auth/sspi.js create mode 100644 app/node_modules/mongodb-core/lib/auth/x509.js create mode 100644 app/node_modules/mongodb-core/lib/connection/command_result.js create mode 100644 app/node_modules/mongodb-core/lib/connection/commands.js create mode 100644 app/node_modules/mongodb-core/lib/connection/connection.js create mode 100644 app/node_modules/mongodb-core/lib/connection/logger.js create mode 100644 app/node_modules/mongodb-core/lib/connection/pool.js create mode 100644 app/node_modules/mongodb-core/lib/connection/utils.js create mode 100644 app/node_modules/mongodb-core/lib/cursor.js create mode 100644 app/node_modules/mongodb-core/lib/error.js create mode 100644 app/node_modules/mongodb-core/lib/tools/smoke_plugin.js create mode 100644 app/node_modules/mongodb-core/lib/topologies/mongos.js create mode 100644 app/node_modules/mongodb-core/lib/topologies/read_preference.js create mode 100644 app/node_modules/mongodb-core/lib/topologies/replset.js create mode 100644 app/node_modules/mongodb-core/lib/topologies/replset_state.js create mode 100644 app/node_modules/mongodb-core/lib/topologies/server.js create mode 100644 app/node_modules/mongodb-core/lib/topologies/shared.js create mode 100644 app/node_modules/mongodb-core/lib/utils.js create mode 100644 app/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js create mode 100644 app/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js create mode 100644 app/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js create mode 100644 app/node_modules/mongodb-core/lib/wireprotocol/commands.js create mode 100644 app/node_modules/mongodb-core/lib/wireprotocol/shared.js create mode 100644 app/node_modules/mongodb-core/package.json create mode 100644 app/node_modules/mongodb-core/test.js create mode 100644 app/node_modules/mongodb-core/test1.js create mode 100644 app/node_modules/mongodb/.coveralls.yml create mode 100644 app/node_modules/mongodb/.eslintrc create mode 100644 app/node_modules/mongodb/HISTORY.md create mode 100644 app/node_modules/mongodb/LICENSE create mode 100644 app/node_modules/mongodb/Makefile create mode 100644 app/node_modules/mongodb/README.md create mode 100644 app/node_modules/mongodb/THIRD-PARTY-NOTICES create mode 100644 app/node_modules/mongodb/boot_auth.js create mode 100644 app/node_modules/mongodb/conf.json create mode 100644 app/node_modules/mongodb/index.js create mode 100644 app/node_modules/mongodb/insert_bench.js create mode 100644 app/node_modules/mongodb/lib/admin.js create mode 100644 app/node_modules/mongodb/lib/aggregation_cursor.js create mode 100644 app/node_modules/mongodb/lib/apm.js create mode 100644 app/node_modules/mongodb/lib/authenticate.js create mode 100644 app/node_modules/mongodb/lib/bulk/common.js create mode 100644 app/node_modules/mongodb/lib/bulk/ordered.js create mode 100644 app/node_modules/mongodb/lib/bulk/unordered.js create mode 100644 app/node_modules/mongodb/lib/collection.js create mode 100644 app/node_modules/mongodb/lib/command_cursor.js create mode 100644 app/node_modules/mongodb/lib/cursor.js create mode 100644 app/node_modules/mongodb/lib/db.js create mode 100644 app/node_modules/mongodb/lib/gridfs-stream/download.js create mode 100644 app/node_modules/mongodb/lib/gridfs-stream/index.js create mode 100644 app/node_modules/mongodb/lib/gridfs-stream/upload.js create mode 100644 app/node_modules/mongodb/lib/gridfs/chunk.js create mode 100644 app/node_modules/mongodb/lib/gridfs/grid_store.js create mode 100644 app/node_modules/mongodb/lib/metadata.js create mode 100644 app/node_modules/mongodb/lib/mongo_client.js create mode 100644 app/node_modules/mongodb/lib/mongos.js create mode 100644 app/node_modules/mongodb/lib/read_preference.js create mode 100644 app/node_modules/mongodb/lib/replset.js create mode 100644 app/node_modules/mongodb/lib/server.js create mode 100644 app/node_modules/mongodb/lib/topology_base.js create mode 100644 app/node_modules/mongodb/lib/url_parser.js create mode 100644 app/node_modules/mongodb/lib/utils.js create mode 100644 app/node_modules/mongodb/package.json create mode 100644 app/node_modules/mongodb/rev.md create mode 100644 app/node_modules/mongodb/yarn.lock create mode 100644 app/node_modules/mongoose/.eslintignore create mode 100644 app/node_modules/mongoose/.eslintrc.yml create mode 100644 app/node_modules/mongoose/.github/ISSUE_TEMPLATE.md create mode 100644 app/node_modules/mongoose/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 app/node_modules/mongoose/.travis.yml create mode 100644 app/node_modules/mongoose/CONTRIBUTING.md create mode 100644 app/node_modules/mongoose/History.md create mode 100644 app/node_modules/mongoose/README.md create mode 100644 app/node_modules/mongoose/examples/README.md create mode 100644 app/node_modules/mongoose/examples/aggregate/aggregate.js create mode 100644 app/node_modules/mongoose/examples/aggregate/package.json create mode 100644 app/node_modules/mongoose/examples/aggregate/person.js create mode 100644 app/node_modules/mongoose/examples/doc-methods.js create mode 100644 app/node_modules/mongoose/examples/express/README.md create mode 100644 app/node_modules/mongoose/examples/express/connection-sharing/README.md create mode 100644 app/node_modules/mongoose/examples/express/connection-sharing/app.js create mode 100644 app/node_modules/mongoose/examples/express/connection-sharing/modelA.js create mode 100644 app/node_modules/mongoose/examples/express/connection-sharing/package.json create mode 100644 app/node_modules/mongoose/examples/express/connection-sharing/routes.js create mode 100644 app/node_modules/mongoose/examples/geospatial/geoJSONSchema.js create mode 100644 app/node_modules/mongoose/examples/geospatial/geoJSONexample.js create mode 100644 app/node_modules/mongoose/examples/geospatial/geospatial.js create mode 100644 app/node_modules/mongoose/examples/geospatial/package.json create mode 100644 app/node_modules/mongoose/examples/geospatial/person.js create mode 100644 app/node_modules/mongoose/examples/globalschemas/gs_example.js create mode 100644 app/node_modules/mongoose/examples/globalschemas/person.js create mode 100644 app/node_modules/mongoose/examples/lean/lean.js create mode 100644 app/node_modules/mongoose/examples/lean/package.json create mode 100644 app/node_modules/mongoose/examples/lean/person.js create mode 100644 app/node_modules/mongoose/examples/mapreduce/mapreduce.js create mode 100644 app/node_modules/mongoose/examples/mapreduce/package.json create mode 100644 app/node_modules/mongoose/examples/mapreduce/person.js create mode 100644 app/node_modules/mongoose/examples/population/population-across-three-collections.js create mode 100644 app/node_modules/mongoose/examples/population/population-basic.js create mode 100644 app/node_modules/mongoose/examples/population/population-of-existing-doc.js create mode 100644 app/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js create mode 100644 app/node_modules/mongoose/examples/population/population-options.js create mode 100644 app/node_modules/mongoose/examples/population/population-plain-objects.js create mode 100644 app/node_modules/mongoose/examples/promises/package.json create mode 100644 app/node_modules/mongoose/examples/promises/person.js create mode 100644 app/node_modules/mongoose/examples/promises/promise.js create mode 100644 app/node_modules/mongoose/examples/querybuilder/package.json create mode 100644 app/node_modules/mongoose/examples/querybuilder/person.js create mode 100644 app/node_modules/mongoose/examples/querybuilder/querybuilder.js create mode 100644 app/node_modules/mongoose/examples/replicasets/package.json create mode 100644 app/node_modules/mongoose/examples/replicasets/person.js create mode 100644 app/node_modules/mongoose/examples/replicasets/replica-sets.js create mode 100644 app/node_modules/mongoose/examples/schema/schema.js create mode 100644 app/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js create mode 100644 app/node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json create mode 100644 app/node_modules/mongoose/examples/statics/person.js create mode 100644 app/node_modules/mongoose/examples/statics/statics.js create mode 100644 app/node_modules/mongoose/index.js create mode 100644 app/node_modules/mongoose/lib/ES6Promise.js create mode 100644 app/node_modules/mongoose/lib/aggregate.js create mode 100644 app/node_modules/mongoose/lib/browser.js create mode 100644 app/node_modules/mongoose/lib/browserDocument.js create mode 100644 app/node_modules/mongoose/lib/cast.js create mode 100644 app/node_modules/mongoose/lib/collection.js create mode 100644 app/node_modules/mongoose/lib/connection.js create mode 100644 app/node_modules/mongoose/lib/connectionstate.js create mode 100644 app/node_modules/mongoose/lib/cursor/AggregationCursor.js create mode 100644 app/node_modules/mongoose/lib/cursor/QueryCursor.js create mode 100644 app/node_modules/mongoose/lib/document.js create mode 100644 app/node_modules/mongoose/lib/document_provider.js create mode 100644 app/node_modules/mongoose/lib/document_provider.web.js create mode 100644 app/node_modules/mongoose/lib/drivers/SPEC.md create mode 100644 app/node_modules/mongoose/lib/drivers/browser/ReadPreference.js create mode 100644 app/node_modules/mongoose/lib/drivers/browser/binary.js create mode 100644 app/node_modules/mongoose/lib/drivers/browser/decimal128.js create mode 100644 app/node_modules/mongoose/lib/drivers/browser/index.js create mode 100644 app/node_modules/mongoose/lib/drivers/browser/objectid.js create mode 100644 app/node_modules/mongoose/lib/drivers/index.js create mode 100644 app/node_modules/mongoose/lib/drivers/index.web.js create mode 100644 app/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js create mode 100644 app/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js create mode 100644 app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js create mode 100644 app/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js create mode 100644 app/node_modules/mongoose/lib/drivers/node-mongodb-native/decimal128.js create mode 100644 app/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js create mode 100644 app/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js create mode 100644 app/node_modules/mongoose/lib/error/browserMissingSchema.js create mode 100644 app/node_modules/mongoose/lib/error/cast.js create mode 100644 app/node_modules/mongoose/lib/error/disconnected.js create mode 100644 app/node_modules/mongoose/lib/error/divergentArray.js create mode 100644 app/node_modules/mongoose/lib/error/index.js create mode 100644 app/node_modules/mongoose/lib/error/messages.js create mode 100644 app/node_modules/mongoose/lib/error/missingSchema.js create mode 100644 app/node_modules/mongoose/lib/error/notFound.js create mode 100644 app/node_modules/mongoose/lib/error/objectExpected.js create mode 100644 app/node_modules/mongoose/lib/error/objectParameter.js create mode 100644 app/node_modules/mongoose/lib/error/overwriteModel.js create mode 100644 app/node_modules/mongoose/lib/error/strict.js create mode 100644 app/node_modules/mongoose/lib/error/validation.js create mode 100644 app/node_modules/mongoose/lib/error/validator.js create mode 100644 app/node_modules/mongoose/lib/error/version.js create mode 100644 app/node_modules/mongoose/lib/index.js create mode 100644 app/node_modules/mongoose/lib/internal.js create mode 100644 app/node_modules/mongoose/lib/model.js create mode 100644 app/node_modules/mongoose/lib/plugins/idGetter.js create mode 100644 app/node_modules/mongoose/lib/plugins/saveSubdocs.js create mode 100644 app/node_modules/mongoose/lib/plugins/sharding.js create mode 100644 app/node_modules/mongoose/lib/plugins/validateBeforeSave.js create mode 100644 app/node_modules/mongoose/lib/promise.js create mode 100644 app/node_modules/mongoose/lib/promise_provider.js create mode 100644 app/node_modules/mongoose/lib/query.js create mode 100644 app/node_modules/mongoose/lib/queryhelpers.js create mode 100644 app/node_modules/mongoose/lib/querystream.js create mode 100644 app/node_modules/mongoose/lib/schema.js create mode 100644 app/node_modules/mongoose/lib/schema/array.js create mode 100644 app/node_modules/mongoose/lib/schema/boolean.js create mode 100644 app/node_modules/mongoose/lib/schema/buffer.js create mode 100644 app/node_modules/mongoose/lib/schema/date.js create mode 100644 app/node_modules/mongoose/lib/schema/decimal128.js create mode 100644 app/node_modules/mongoose/lib/schema/documentarray.js create mode 100644 app/node_modules/mongoose/lib/schema/embedded.js create mode 100644 app/node_modules/mongoose/lib/schema/index.js create mode 100644 app/node_modules/mongoose/lib/schema/mixed.js create mode 100644 app/node_modules/mongoose/lib/schema/number.js create mode 100644 app/node_modules/mongoose/lib/schema/objectid.js create mode 100644 app/node_modules/mongoose/lib/schema/operators/bitwise.js create mode 100644 app/node_modules/mongoose/lib/schema/operators/exists.js create mode 100644 app/node_modules/mongoose/lib/schema/operators/geospatial.js create mode 100644 app/node_modules/mongoose/lib/schema/operators/helpers.js create mode 100644 app/node_modules/mongoose/lib/schema/operators/type.js create mode 100644 app/node_modules/mongoose/lib/schema/string.js create mode 100644 app/node_modules/mongoose/lib/schematype.js create mode 100644 app/node_modules/mongoose/lib/services/common.js create mode 100644 app/node_modules/mongoose/lib/services/cursor/eachAsync.js create mode 100644 app/node_modules/mongoose/lib/services/document/cleanModifiedSubpaths.js create mode 100644 app/node_modules/mongoose/lib/services/document/compile.js create mode 100644 app/node_modules/mongoose/lib/services/model/applyHooks.js create mode 100644 app/node_modules/mongoose/lib/services/model/applyMethods.js create mode 100644 app/node_modules/mongoose/lib/services/model/applyStatics.js create mode 100644 app/node_modules/mongoose/lib/services/model/discriminator.js create mode 100644 app/node_modules/mongoose/lib/services/populate/getSchemaTypes.js create mode 100644 app/node_modules/mongoose/lib/services/projection/isDefiningProjection.js create mode 100644 app/node_modules/mongoose/lib/services/projection/isInclusive.js create mode 100644 app/node_modules/mongoose/lib/services/projection/isPathSelectedInclusive.js create mode 100644 app/node_modules/mongoose/lib/services/query/castUpdate.js create mode 100644 app/node_modules/mongoose/lib/services/query/hasDollarKeys.js create mode 100644 app/node_modules/mongoose/lib/services/query/selectPopulatedFields.js create mode 100644 app/node_modules/mongoose/lib/services/setDefaultsOnInsert.js create mode 100644 app/node_modules/mongoose/lib/services/updateValidators.js create mode 100644 app/node_modules/mongoose/lib/statemachine.js create mode 100644 app/node_modules/mongoose/lib/types/array.js create mode 100644 app/node_modules/mongoose/lib/types/buffer.js create mode 100644 app/node_modules/mongoose/lib/types/decimal128.js create mode 100644 app/node_modules/mongoose/lib/types/documentarray.js create mode 100644 app/node_modules/mongoose/lib/types/embedded.js create mode 100644 app/node_modules/mongoose/lib/types/index.js create mode 100644 app/node_modules/mongoose/lib/types/objectid.js create mode 100644 app/node_modules/mongoose/lib/types/subdocument.js create mode 100644 app/node_modules/mongoose/lib/utils.js create mode 100644 app/node_modules/mongoose/lib/virtualtype.js create mode 100644 app/node_modules/mongoose/package.json create mode 100644 app/node_modules/mongoose/release-items.md create mode 100644 app/node_modules/mongoose/static.js create mode 100644 app/node_modules/mongoose/tools/auth.js create mode 100644 app/node_modules/mongoose/tools/repl.js create mode 100644 app/node_modules/mongoose/tools/sharded.js create mode 100644 app/node_modules/mongoose/website.js create mode 100644 app/node_modules/morgan/HISTORY.md create mode 100644 app/node_modules/morgan/LICENSE create mode 100644 app/node_modules/morgan/README.md create mode 100644 app/node_modules/morgan/index.js create mode 100644 app/node_modules/morgan/package.json create mode 100644 app/node_modules/mpath/.travis.yml create mode 100644 app/node_modules/mpath/History.md create mode 100644 app/node_modules/mpath/LICENSE create mode 100644 app/node_modules/mpath/Makefile create mode 100644 app/node_modules/mpath/README.md create mode 100644 app/node_modules/mpath/bench.js create mode 100644 app/node_modules/mpath/bench.log create mode 100644 app/node_modules/mpath/bench.out create mode 100644 app/node_modules/mpath/component.json create mode 100644 app/node_modules/mpath/index.js create mode 100644 app/node_modules/mpath/lib/index.js create mode 100644 app/node_modules/mpath/package.json create mode 100644 app/node_modules/mpath/test/index.js create mode 100644 app/node_modules/mpromise/.npmignore create mode 100644 app/node_modules/mpromise/.travis.yml create mode 100644 app/node_modules/mpromise/History.md create mode 100644 app/node_modules/mpromise/LICENSE create mode 100644 app/node_modules/mpromise/README.md create mode 100644 app/node_modules/mpromise/lib/promise.js create mode 100644 app/node_modules/mpromise/package.json create mode 100644 app/node_modules/mpromise/test/promise.domain.test.js create mode 100644 app/node_modules/mpromise/test/promise.test.js create mode 100644 app/node_modules/mpromise/test/promises.Aplus.js create mode 100644 app/node_modules/mquery/.npmignore create mode 100644 app/node_modules/mquery/.travis.yml create mode 100644 app/node_modules/mquery/History.md create mode 100644 app/node_modules/mquery/LICENSE create mode 100644 app/node_modules/mquery/Makefile create mode 100644 app/node_modules/mquery/README.md create mode 100644 app/node_modules/mquery/lib/collection/collection.js create mode 100644 app/node_modules/mquery/lib/collection/index.js create mode 100644 app/node_modules/mquery/lib/collection/node.js create mode 100644 app/node_modules/mquery/lib/env.js create mode 100644 app/node_modules/mquery/lib/mquery.js create mode 100644 app/node_modules/mquery/lib/permissions.js create mode 100644 app/node_modules/mquery/lib/utils.js create mode 100644 app/node_modules/mquery/node_modules/sliced/.npmignore create mode 100644 app/node_modules/mquery/node_modules/sliced/.travis.yml create mode 100644 app/node_modules/mquery/node_modules/sliced/History.md create mode 100644 app/node_modules/mquery/node_modules/sliced/LICENSE create mode 100644 app/node_modules/mquery/node_modules/sliced/Makefile create mode 100644 app/node_modules/mquery/node_modules/sliced/README.md create mode 100644 app/node_modules/mquery/node_modules/sliced/bench.js create mode 100644 app/node_modules/mquery/node_modules/sliced/component.json create mode 100644 app/node_modules/mquery/node_modules/sliced/index.js create mode 100644 app/node_modules/mquery/node_modules/sliced/lib/sliced.js create mode 100644 app/node_modules/mquery/node_modules/sliced/package.json create mode 100644 app/node_modules/mquery/node_modules/sliced/test/index.js create mode 100644 app/node_modules/mquery/package.json create mode 100644 app/node_modules/mquery/test/collection/browser.js create mode 100644 app/node_modules/mquery/test/collection/mongo.js create mode 100644 app/node_modules/mquery/test/collection/node.js create mode 100644 app/node_modules/mquery/test/env.js create mode 100644 app/node_modules/mquery/test/index.js create mode 100644 app/node_modules/mquery/test/utils.test.js create mode 100644 app/node_modules/ms/index.js create mode 100644 app/node_modules/ms/license.md create mode 100644 app/node_modules/ms/package.json create mode 100644 app/node_modules/ms/readme.md create mode 100644 app/node_modules/muri/.npmignore create mode 100644 app/node_modules/muri/.travis.yml create mode 100644 app/node_modules/muri/History.md create mode 100644 app/node_modules/muri/LICENSE create mode 100644 app/node_modules/muri/Makefile create mode 100644 app/node_modules/muri/README.md create mode 100644 app/node_modules/muri/index.js create mode 100644 app/node_modules/muri/lib/index.js create mode 100644 app/node_modules/muri/package.json create mode 100644 app/node_modules/muri/test/index.js create mode 100644 app/node_modules/nconf/.npmignore create mode 100644 app/node_modules/nconf/.travis.yml create mode 100644 app/node_modules/nconf/CHANGELOG.md create mode 100644 app/node_modules/nconf/LICENSE create mode 100644 app/node_modules/nconf/README.md create mode 100644 app/node_modules/nconf/lib/nconf.js create mode 100644 app/node_modules/nconf/lib/nconf/common.js create mode 100644 app/node_modules/nconf/lib/nconf/formats.js create mode 100644 app/node_modules/nconf/lib/nconf/provider.js create mode 100644 app/node_modules/nconf/lib/nconf/stores/argv.js create mode 100644 app/node_modules/nconf/lib/nconf/stores/env.js create mode 100644 app/node_modules/nconf/lib/nconf/stores/file.js create mode 100644 app/node_modules/nconf/lib/nconf/stores/literal.js create mode 100644 app/node_modules/nconf/lib/nconf/stores/memory.js create mode 100644 app/node_modules/nconf/node_modules/async/CHANGELOG.md create mode 100644 app/node_modules/nconf/node_modules/async/LICENSE create mode 100644 app/node_modules/nconf/node_modules/async/README.md create mode 100644 app/node_modules/nconf/node_modules/async/dist/async.js create mode 100644 app/node_modules/nconf/node_modules/async/dist/async.min.js create mode 100644 app/node_modules/nconf/node_modules/async/lib/async.js create mode 100644 app/node_modules/nconf/node_modules/async/package.json create mode 100644 app/node_modules/nconf/package.json create mode 100644 app/node_modules/nconf/test/common-test.js create mode 100644 app/node_modules/nconf/test/complete-test.js create mode 100644 app/node_modules/nconf/test/fixtures/bom.json create mode 100644 app/node_modules/nconf/test/fixtures/complete.json create mode 100644 app/node_modules/nconf/test/fixtures/data.js create mode 100644 app/node_modules/nconf/test/fixtures/hierarchy/global.json create mode 100644 app/node_modules/nconf/test/fixtures/hierarchy/hierarchical.json create mode 100644 app/node_modules/nconf/test/fixtures/hierarchy/user.json create mode 100644 app/node_modules/nconf/test/fixtures/malformed.json create mode 100644 app/node_modules/nconf/test/fixtures/merge/file1.json create mode 100644 app/node_modules/nconf/test/fixtures/merge/file2.json create mode 100644 app/node_modules/nconf/test/fixtures/merge/file3.json create mode 100644 app/node_modules/nconf/test/fixtures/no-bom.json create mode 100644 app/node_modules/nconf/test/fixtures/scripts/nconf-argv.js create mode 100644 app/node_modules/nconf/test/fixtures/scripts/nconf-change-argv.js create mode 100644 app/node_modules/nconf/test/fixtures/scripts/nconf-env.js create mode 100644 app/node_modules/nconf/test/fixtures/scripts/nconf-hierarchical-defaults-merge.js create mode 100644 app/node_modules/nconf/test/fixtures/scripts/nconf-hierarchical-file-argv.js create mode 100644 app/node_modules/nconf/test/fixtures/scripts/nconf-hierarchical-load-merge.js create mode 100644 app/node_modules/nconf/test/fixtures/scripts/nconf-hierarchical-load-save.js create mode 100644 app/node_modules/nconf/test/fixtures/scripts/nconf-nested-env.js create mode 100644 app/node_modules/nconf/test/fixtures/scripts/provider-argv.js create mode 100644 app/node_modules/nconf/test/fixtures/scripts/provider-env.js create mode 100644 app/node_modules/nconf/test/fixtures/secure.json create mode 100644 app/node_modules/nconf/test/helpers.js create mode 100644 app/node_modules/nconf/test/hierarchy-test.js create mode 100644 app/node_modules/nconf/test/mocks/mock-store.js create mode 100644 app/node_modules/nconf/test/nconf-test.js create mode 100644 app/node_modules/nconf/test/provider-save-test.js create mode 100644 app/node_modules/nconf/test/provider-test.js create mode 100644 app/node_modules/nconf/test/stores/argv-test.js create mode 100644 app/node_modules/nconf/test/stores/env-test.js create mode 100644 app/node_modules/nconf/test/stores/file-store-test.js create mode 100644 app/node_modules/nconf/test/stores/literal-test.js create mode 100644 app/node_modules/nconf/test/stores/memory-store-test.js create mode 100644 app/node_modules/nconf/usage.js create mode 100644 app/node_modules/negotiator/HISTORY.md create mode 100644 app/node_modules/negotiator/LICENSE create mode 100644 app/node_modules/negotiator/README.md create mode 100644 app/node_modules/negotiator/index.js create mode 100644 app/node_modules/negotiator/lib/charset.js create mode 100644 app/node_modules/negotiator/lib/encoding.js create mode 100644 app/node_modules/negotiator/lib/language.js create mode 100644 app/node_modules/negotiator/lib/mediaType.js create mode 100644 app/node_modules/negotiator/package.json create mode 100644 app/node_modules/number-is-nan/index.js create mode 100644 app/node_modules/number-is-nan/license create mode 100644 app/node_modules/number-is-nan/package.json create mode 100644 app/node_modules/number-is-nan/readme.md create mode 100644 app/node_modules/on-finished/HISTORY.md create mode 100644 app/node_modules/on-finished/LICENSE create mode 100644 app/node_modules/on-finished/README.md create mode 100644 app/node_modules/on-finished/index.js create mode 100644 app/node_modules/on-finished/package.json create mode 100644 app/node_modules/on-headers/HISTORY.md create mode 100644 app/node_modules/on-headers/LICENSE create mode 100644 app/node_modules/on-headers/README.md create mode 100644 app/node_modules/on-headers/index.js create mode 100644 app/node_modules/on-headers/package.json create mode 100644 app/node_modules/os-locale/index.js create mode 100644 app/node_modules/os-locale/license create mode 100644 app/node_modules/os-locale/package.json create mode 100644 app/node_modules/os-locale/readme.md create mode 100644 app/node_modules/parseurl/HISTORY.md create mode 100644 app/node_modules/parseurl/LICENSE create mode 100644 app/node_modules/parseurl/README.md create mode 100644 app/node_modules/parseurl/index.js create mode 100644 app/node_modules/parseurl/package.json create mode 100644 app/node_modules/path-to-regexp/History.md create mode 100644 app/node_modules/path-to-regexp/LICENSE create mode 100644 app/node_modules/path-to-regexp/Readme.md create mode 100644 app/node_modules/path-to-regexp/index.js create mode 100644 app/node_modules/path-to-regexp/package.json create mode 100644 app/node_modules/process-nextick-args/.travis.yml create mode 100644 app/node_modules/process-nextick-args/index.js create mode 100644 app/node_modules/process-nextick-args/license.md create mode 100644 app/node_modules/process-nextick-args/package.json create mode 100644 app/node_modules/process-nextick-args/readme.md create mode 100644 app/node_modules/process-nextick-args/test.js create mode 100644 app/node_modules/proxy-addr/HISTORY.md create mode 100644 app/node_modules/proxy-addr/LICENSE create mode 100644 app/node_modules/proxy-addr/README.md create mode 100644 app/node_modules/proxy-addr/index.js create mode 100644 app/node_modules/proxy-addr/package.json create mode 100644 app/node_modules/qs/.editorconfig create mode 100644 app/node_modules/qs/.eslintignore create mode 100644 app/node_modules/qs/.eslintrc create mode 100644 app/node_modules/qs/CHANGELOG.md create mode 100644 app/node_modules/qs/LICENSE create mode 100644 app/node_modules/qs/README.md create mode 100644 app/node_modules/qs/dist/qs.js create mode 100644 app/node_modules/qs/lib/formats.js create mode 100644 app/node_modules/qs/lib/index.js create mode 100644 app/node_modules/qs/lib/parse.js create mode 100644 app/node_modules/qs/lib/stringify.js create mode 100644 app/node_modules/qs/lib/utils.js create mode 100644 app/node_modules/qs/package.json create mode 100644 app/node_modules/qs/test/.eslintrc create mode 100644 app/node_modules/qs/test/index.js create mode 100644 app/node_modules/qs/test/parse.js create mode 100644 app/node_modules/qs/test/stringify.js create mode 100644 app/node_modules/qs/test/utils.js create mode 100644 app/node_modules/range-parser/HISTORY.md create mode 100644 app/node_modules/range-parser/LICENSE create mode 100644 app/node_modules/range-parser/README.md create mode 100644 app/node_modules/range-parser/index.js create mode 100644 app/node_modules/range-parser/package.json create mode 100644 app/node_modules/raw-body/HISTORY.md create mode 100644 app/node_modules/raw-body/LICENSE create mode 100644 app/node_modules/raw-body/README.md create mode 100644 app/node_modules/raw-body/index.d.ts create mode 100644 app/node_modules/raw-body/index.js create mode 100644 app/node_modules/raw-body/package.json create mode 100644 app/node_modules/readable-stream/.npmignore create mode 100644 app/node_modules/readable-stream/.travis.yml create mode 100644 app/node_modules/readable-stream/CONTRIBUTING.md create mode 100644 app/node_modules/readable-stream/GOVERNANCE.md create mode 100644 app/node_modules/readable-stream/LICENSE create mode 100644 app/node_modules/readable-stream/README.md create mode 100644 app/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md create mode 100644 app/node_modules/readable-stream/duplex-browser.js create mode 100644 app/node_modules/readable-stream/duplex.js create mode 100644 app/node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 app/node_modules/readable-stream/lib/_stream_passthrough.js create mode 100644 app/node_modules/readable-stream/lib/_stream_readable.js create mode 100644 app/node_modules/readable-stream/lib/_stream_transform.js create mode 100644 app/node_modules/readable-stream/lib/_stream_writable.js create mode 100644 app/node_modules/readable-stream/lib/internal/streams/BufferList.js create mode 100644 app/node_modules/readable-stream/node_modules/inherits/LICENSE create mode 100644 app/node_modules/readable-stream/node_modules/inherits/README.md create mode 100644 app/node_modules/readable-stream/node_modules/inherits/inherits.js create mode 100644 app/node_modules/readable-stream/node_modules/inherits/inherits_browser.js create mode 100644 app/node_modules/readable-stream/node_modules/inherits/package.json create mode 100644 app/node_modules/readable-stream/package.json create mode 100644 app/node_modules/readable-stream/passthrough.js create mode 100644 app/node_modules/readable-stream/readable-browser.js create mode 100644 app/node_modules/readable-stream/readable.js create mode 100644 app/node_modules/readable-stream/transform.js create mode 100644 app/node_modules/readable-stream/writable-browser.js create mode 100644 app/node_modules/readable-stream/writable.js create mode 100644 app/node_modules/regexp-clone/.npmignore create mode 100644 app/node_modules/regexp-clone/.travis.yml create mode 100644 app/node_modules/regexp-clone/History.md create mode 100644 app/node_modules/regexp-clone/LICENSE create mode 100644 app/node_modules/regexp-clone/Makefile create mode 100644 app/node_modules/regexp-clone/README.md create mode 100644 app/node_modules/regexp-clone/index.js create mode 100644 app/node_modules/regexp-clone/package.json create mode 100644 app/node_modules/regexp-clone/test/index.js create mode 100644 app/node_modules/require_optional/.npmignore create mode 100644 app/node_modules/require_optional/.travis.yml create mode 100644 app/node_modules/require_optional/HISTORY.md create mode 100644 app/node_modules/require_optional/LICENSE create mode 100644 app/node_modules/require_optional/README.md create mode 100644 app/node_modules/require_optional/index.js create mode 120000 app/node_modules/require_optional/node_modules/.bin/semver create mode 100644 app/node_modules/require_optional/package.json create mode 100644 app/node_modules/require_optional/test/nestedTest/index.js create mode 100644 app/node_modules/require_optional/test/nestedTest/package.json create mode 100644 app/node_modules/require_optional/test/require_optional_tests.js create mode 100644 app/node_modules/resolve-from/index.js create mode 100644 app/node_modules/resolve-from/license create mode 100644 app/node_modules/resolve-from/package.json create mode 100644 app/node_modules/resolve-from/readme.md create mode 100644 app/node_modules/safe-buffer/LICENSE create mode 100644 app/node_modules/safe-buffer/README.md create mode 100644 app/node_modules/safe-buffer/index.d.ts create mode 100644 app/node_modules/safe-buffer/index.js create mode 100644 app/node_modules/safe-buffer/package.json create mode 100644 app/node_modules/safer-buffer/LICENSE create mode 100644 app/node_modules/safer-buffer/Porting-Buffer.md create mode 100644 app/node_modules/safer-buffer/Readme.md create mode 100644 app/node_modules/safer-buffer/dangerous.js create mode 100644 app/node_modules/safer-buffer/package.json create mode 100644 app/node_modules/safer-buffer/safer.js create mode 100644 app/node_modules/safer-buffer/tests.js create mode 100644 app/node_modules/secure-keys/.npmignore create mode 100644 app/node_modules/secure-keys/.travis.yml create mode 100644 app/node_modules/secure-keys/README.md create mode 100644 app/node_modules/secure-keys/index.js create mode 100644 app/node_modules/secure-keys/package.json create mode 100644 app/node_modules/secure-keys/test/simple-test.js create mode 100644 app/node_modules/secure-keys/test/test.secret.key create mode 100644 app/node_modules/semver/CHANGELOG.md create mode 100644 app/node_modules/semver/LICENSE create mode 100644 app/node_modules/semver/README.md create mode 100755 app/node_modules/semver/bin/semver create mode 100644 app/node_modules/semver/package.json create mode 100644 app/node_modules/semver/range.bnf create mode 100644 app/node_modules/semver/semver.js create mode 100644 app/node_modules/send/HISTORY.md create mode 100644 app/node_modules/send/LICENSE create mode 100644 app/node_modules/send/README.md create mode 100644 app/node_modules/send/index.js create mode 120000 app/node_modules/send/node_modules/.bin/mime create mode 100644 app/node_modules/send/package.json create mode 100644 app/node_modules/serve-static/HISTORY.md create mode 100644 app/node_modules/serve-static/LICENSE create mode 100644 app/node_modules/serve-static/README.md create mode 100644 app/node_modules/serve-static/index.js create mode 100644 app/node_modules/serve-static/package.json create mode 100644 app/node_modules/setprototypeof/LICENSE create mode 100644 app/node_modules/setprototypeof/README.md create mode 100644 app/node_modules/setprototypeof/index.d.ts create mode 100644 app/node_modules/setprototypeof/index.js create mode 100644 app/node_modules/setprototypeof/package.json create mode 100644 app/node_modules/sliced/History.md create mode 100644 app/node_modules/sliced/LICENSE create mode 100644 app/node_modules/sliced/README.md create mode 100644 app/node_modules/sliced/index.js create mode 100644 app/node_modules/sliced/package.json create mode 100644 app/node_modules/stack-trace/.npmignore create mode 100644 app/node_modules/stack-trace/License create mode 100644 app/node_modules/stack-trace/Makefile create mode 100644 app/node_modules/stack-trace/Readme.md create mode 100644 app/node_modules/stack-trace/lib/stack-trace.js create mode 100644 app/node_modules/stack-trace/package.json create mode 100644 app/node_modules/statuses/HISTORY.md create mode 100644 app/node_modules/statuses/LICENSE create mode 100644 app/node_modules/statuses/README.md create mode 100644 app/node_modules/statuses/codes.json create mode 100644 app/node_modules/statuses/index.js create mode 100644 app/node_modules/statuses/package.json create mode 100644 app/node_modules/string-width/index.js create mode 100644 app/node_modules/string-width/license create mode 100644 app/node_modules/string-width/package.json create mode 100644 app/node_modules/string-width/readme.md create mode 100644 app/node_modules/string_decoder/.npmignore create mode 100644 app/node_modules/string_decoder/LICENSE create mode 100644 app/node_modules/string_decoder/README.md create mode 100644 app/node_modules/string_decoder/lib/string_decoder.js create mode 100644 app/node_modules/string_decoder/package.json create mode 100644 app/node_modules/strip-ansi/index.js create mode 100644 app/node_modules/strip-ansi/license create mode 100644 app/node_modules/strip-ansi/package.json create mode 100644 app/node_modules/strip-ansi/readme.md create mode 100644 app/node_modules/type-is/HISTORY.md create mode 100644 app/node_modules/type-is/LICENSE create mode 100644 app/node_modules/type-is/README.md create mode 100644 app/node_modules/type-is/index.js create mode 100644 app/node_modules/type-is/package.json create mode 100644 app/node_modules/unpipe/HISTORY.md create mode 100644 app/node_modules/unpipe/LICENSE create mode 100644 app/node_modules/unpipe/README.md create mode 100644 app/node_modules/unpipe/index.js create mode 100644 app/node_modules/unpipe/package.json create mode 100644 app/node_modules/util-deprecate/History.md create mode 100644 app/node_modules/util-deprecate/LICENSE create mode 100644 app/node_modules/util-deprecate/README.md create mode 100644 app/node_modules/util-deprecate/browser.js create mode 100644 app/node_modules/util-deprecate/node.js create mode 100644 app/node_modules/util-deprecate/package.json create mode 100644 app/node_modules/utils-merge/.npmignore create mode 100644 app/node_modules/utils-merge/LICENSE create mode 100644 app/node_modules/utils-merge/README.md create mode 100644 app/node_modules/utils-merge/index.js create mode 100644 app/node_modules/utils-merge/package.json create mode 100644 app/node_modules/vary/HISTORY.md create mode 100644 app/node_modules/vary/LICENSE create mode 100644 app/node_modules/vary/README.md create mode 100644 app/node_modules/vary/index.js create mode 100644 app/node_modules/vary/package.json create mode 100644 app/node_modules/window-size/LICENSE create mode 100644 app/node_modules/window-size/README.md create mode 100755 app/node_modules/window-size/cli.js create mode 100644 app/node_modules/window-size/index.js create mode 100644 app/node_modules/window-size/package.json create mode 100644 app/node_modules/winston/CHANGELOG.md create mode 100644 app/node_modules/winston/LICENSE create mode 100644 app/node_modules/winston/README.md create mode 100644 app/node_modules/winston/index.d.ts create mode 100644 app/node_modules/winston/lib/winston.js create mode 100644 app/node_modules/winston/lib/winston/common.js create mode 100644 app/node_modules/winston/lib/winston/config.js create mode 100644 app/node_modules/winston/lib/winston/config/cli-config.js create mode 100644 app/node_modules/winston/lib/winston/config/npm-config.js create mode 100644 app/node_modules/winston/lib/winston/config/syslog-config.js create mode 100644 app/node_modules/winston/lib/winston/container.js create mode 100644 app/node_modules/winston/lib/winston/exception.js create mode 100755 app/node_modules/winston/lib/winston/logger.js create mode 100644 app/node_modules/winston/lib/winston/transports.js create mode 100644 app/node_modules/winston/lib/winston/transports/console.js create mode 100644 app/node_modules/winston/lib/winston/transports/file.js create mode 100644 app/node_modules/winston/lib/winston/transports/http.js create mode 100644 app/node_modules/winston/lib/winston/transports/memory.js create mode 100644 app/node_modules/winston/lib/winston/transports/transport.js create mode 100644 app/node_modules/winston/node_modules/async/.jshintrc create mode 100644 app/node_modules/winston/node_modules/async/.travis.yml create mode 100644 app/node_modules/winston/node_modules/async/CHANGELOG.md create mode 100644 app/node_modules/winston/node_modules/async/LICENSE create mode 100644 app/node_modules/winston/node_modules/async/README.md create mode 100644 app/node_modules/winston/node_modules/async/bower.json create mode 100644 app/node_modules/winston/node_modules/async/component.json create mode 100644 app/node_modules/winston/node_modules/async/lib/async.js create mode 100644 app/node_modules/winston/node_modules/async/package.json create mode 100755 app/node_modules/winston/node_modules/async/support/sync-package-managers.js create mode 100644 app/node_modules/winston/package.json create mode 100644 app/node_modules/winston/test/helpers.js create mode 100644 app/node_modules/winston/test/transports/console-test.js create mode 100644 app/node_modules/winston/test/transports/file-archive-test.js create mode 100644 app/node_modules/winston/test/transports/file-maxfiles-test.js create mode 100644 app/node_modules/winston/test/transports/file-maxsize-test.js create mode 100644 app/node_modules/winston/test/transports/file-open-test.js create mode 100644 app/node_modules/winston/test/transports/file-stress-test.js create mode 100644 app/node_modules/winston/test/transports/file-tailrolling-test.js create mode 100644 app/node_modules/winston/test/transports/file-test.js create mode 100644 app/node_modules/winston/test/transports/http-test.js create mode 100644 app/node_modules/winston/test/transports/memory-test.js create mode 100644 app/node_modules/winston/test/transports/transport.js create mode 100755 app/node_modules/wrap-ansi/index.js create mode 100644 app/node_modules/wrap-ansi/license create mode 100644 app/node_modules/wrap-ansi/package.json create mode 100644 app/node_modules/wrap-ansi/readme.md create mode 100644 app/node_modules/y18n/LICENSE create mode 100644 app/node_modules/y18n/README.md create mode 100644 app/node_modules/y18n/index.js create mode 100644 app/node_modules/y18n/package.json create mode 100644 app/node_modules/yargs/CHANGELOG.md create mode 100644 app/node_modules/yargs/LICENSE create mode 100644 app/node_modules/yargs/README.md create mode 100644 app/node_modules/yargs/completion.sh.hbs create mode 100644 app/node_modules/yargs/index.js create mode 100644 app/node_modules/yargs/lib/completion.js create mode 100644 app/node_modules/yargs/lib/parser.js create mode 100644 app/node_modules/yargs/lib/tokenize-arg-string.js create mode 100644 app/node_modules/yargs/lib/usage.js create mode 100644 app/node_modules/yargs/lib/validation.js create mode 100644 app/node_modules/yargs/locales/de.json create mode 100644 app/node_modules/yargs/locales/en.json create mode 100644 app/node_modules/yargs/locales/es.json create mode 100644 app/node_modules/yargs/locales/fr.json create mode 100644 app/node_modules/yargs/locales/id.json create mode 100644 app/node_modules/yargs/locales/ja.json create mode 100644 app/node_modules/yargs/locales/ko.json create mode 100644 app/node_modules/yargs/locales/nb.json create mode 100644 app/node_modules/yargs/locales/pirate.json create mode 100644 app/node_modules/yargs/locales/pl.json create mode 100644 app/node_modules/yargs/locales/pt.json create mode 100644 app/node_modules/yargs/locales/pt_BR.json create mode 100644 app/node_modules/yargs/locales/tr.json create mode 100644 app/node_modules/yargs/locales/zh.json create mode 120000 app/node_modules/yargs/node_modules/.bin/window-size create mode 100644 app/node_modules/yargs/package.json create mode 100644 app/package.json create mode 100644 app/public/stylesheets/style.css create mode 100644 app/routes/index.js create mode 100644 app/routes/users.js create mode 100644 app/yarn.lock diff --git a/.gitpod.Dockerfile b/.gitpod.Dockerfile new file mode 100644 index 0000000..f0decb6 --- /dev/null +++ b/.gitpod.Dockerfile @@ -0,0 +1,7 @@ +FROM gitpod/workspace-mongodb + +# Install custom tools, runtimes, etc. +# For example "bastet", a command-line tetris clone: +# RUN brew install bastet +# +# More information: https://www.gitpod.io/docs/config-docker/ diff --git a/.gitpod.yml b/.gitpod.yml index 4813706..09b3fcc 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -1,5 +1,5 @@ +image: + file: .gitpod.Dockerfile + tasks: - init: npm install - - ports: - - port: 8080 diff --git a/app/app.js b/app/app.js new file mode 100644 index 0000000..cfcca60 --- /dev/null +++ b/app/app.js @@ -0,0 +1,26 @@ +var express = require('express'); +var path = require('path'); +var cookieParser = require('cookie-parser'); +var logger = require('morgan'); +var mongoUtil = require('./mongoUtil') + +var indexRouter = require('./routes/index'); +var usersRouter = require('./routes/users'); + +var app = express(); + +mongoUtil.connect(function(){ + app.use(logger('dev')); + app.use(express.json()); + app.use(express.urlencoded({ extended: false })); + app.use(cookieParser()); + app.use(express.static(path.join(__dirname, 'public'))); + + app.use('/', indexRouter); + app.use('/users', usersRouter); + +}) + + + +module.exports = app; diff --git a/app/bin/www b/app/bin/www new file mode 100755 index 0000000..a8c2d36 --- /dev/null +++ b/app/bin/www @@ -0,0 +1,90 @@ +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var app = require('../app'); +var debug = require('debug')('app:server'); +var http = require('http'); + +/** + * Get port from environment and store in Express. + */ + +var port = normalizePort(process.env.PORT || '3000'); +app.set('port', port); + +/** + * Create HTTP server. + */ + +var server = http.createServer(app); + +/** + * Listen on provided port, on all network interfaces. + */ + +server.listen(port); +server.on('error', onError); +server.on('listening', onListening); + +/** + * Normalize a port into a number, string, or false. + */ + +function normalizePort(val) { + var port = parseInt(val, 10); + + if (isNaN(port)) { + // named pipe + return val; + } + + if (port >= 0) { + // port number + return port; + } + + return false; +} + +/** + * Event listener for HTTP server "error" event. + */ + +function onError(error) { + if (error.syscall !== 'listen') { + throw error; + } + + var bind = typeof port === 'string' + ? 'Pipe ' + port + : 'Port ' + port; + + // handle specific listen errors with friendly messages + switch (error.code) { + case 'EACCES': + console.error(bind + ' requires elevated privileges'); + process.exit(1); + break; + case 'EADDRINUSE': + console.error(bind + ' is already in use'); + process.exit(1); + break; + default: + throw error; + } +} + +/** + * Event listener for HTTP server "listening" event. + */ + +function onListening() { + var addr = server.address(); + var bind = typeof addr === 'string' + ? 'pipe ' + addr + : 'port ' + addr.port; + debug('Listening on ' + bind); +} diff --git a/app/models/UserModel.js b/app/models/UserModel.js new file mode 100644 index 0000000..085ce02 --- /dev/null +++ b/app/models/UserModel.js @@ -0,0 +1,8 @@ +function getUsers(db) { + let users = await db.collections('users').find({}).toArray(); + return users; +} + +module.exports = { + getUsers +} \ No newline at end of file diff --git a/app/mongoUtil.js b/app/mongoUtil.js new file mode 100644 index 0000000..d7be5c3 --- /dev/null +++ b/app/mongoUtil.js @@ -0,0 +1,19 @@ +const MongoClient = require( 'mongodb' ).MongoClient; +const url = "mongodb+srv://root:rotiprata123@cluster0-encm1.mongodb.net/test?retryWrites=true&w=majority"; +const dbName = "animal_shelter"; +let _db; + +function connect(callback) { + MongoClient.connect(url, {useUnifiedTopology:true}, function(err,client){ + _db = client.db(dbName); + return callback(err, _db); + }) +} + +function getDB() { + return _db; +} + +module.exports = { + connect, getDB +} \ No newline at end of file diff --git a/app/node_modules/.bin/mime b/app/node_modules/.bin/mime new file mode 120000 index 0000000..fbb7ee0 --- /dev/null +++ b/app/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/app/node_modules/.bin/semver b/app/node_modules/.bin/semver new file mode 120000 index 0000000..317eb29 --- /dev/null +++ b/app/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver \ No newline at end of file diff --git a/app/node_modules/.bin/window-size b/app/node_modules/.bin/window-size new file mode 120000 index 0000000..e84c8ec --- /dev/null +++ b/app/node_modules/.bin/window-size @@ -0,0 +1 @@ +../window-size/cli.js \ No newline at end of file diff --git a/app/node_modules/.yarn-integrity b/app/node_modules/.yarn-integrity new file mode 100644 index 0000000..7badc04 --- /dev/null +++ b/app/node_modules/.yarn-integrity @@ -0,0 +1,137 @@ +{ + "systemParams": "linux-x64-72", + "modulesFolders": [ + "node_modules" + ], + "flags": [], + "linkedModules": [], + "topLevelPatterns": [ + "cookie-parser@~1.4.4", + "debug@~2.6.9", + "express@~4.16.1", + "http-errors@~1.6.3", + "mongoclient@^1.0.3", + "morgan@~1.9.1" + ], + "lockfileEntries": { + "accepts@~1.3.5": "https://registry.yarnpkg.com/accepts/-/accepts-1.3.7.tgz#531bc726517a3b2b41f850021c6cc15eaab507cd", + "ansi-regex@^2.0.0": "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df", + "array-flatten@1.1.1": "https://registry.yarnpkg.com/array-flatten/-/array-flatten-1.1.1.tgz#9a5f699051b1e7073328f2a008968b64ea2955d2", + "async@2.6.0": "https://registry.yarnpkg.com/async/-/async-2.6.0.tgz#61a29abb6fcc026fea77e56d1c6ec53a795951f4", + "async@^1.4.0": "https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a", + "async@~1.0.0": "https://registry.yarnpkg.com/async/-/async-1.0.0.tgz#f8fc04ca3a13784ade9e1641af98578cfbd647a9", + "basic-auth@~2.0.0": "https://registry.yarnpkg.com/basic-auth/-/basic-auth-2.0.1.tgz#b998279bf47ce38344b4f3cf916d4679bbf51e3a", + "bluebird@3.5.0": "https://registry.yarnpkg.com/bluebird/-/bluebird-3.5.0.tgz#791420d7f551eea2897453a8a77653f96606d67c", + "body-parser@1.18.3": "https://registry.yarnpkg.com/body-parser/-/body-parser-1.18.3.tgz#5b292198ffdd553b3a0f20ded0592b956955c8b4", + "bson@~1.0.4": "https://registry.yarnpkg.com/bson/-/bson-1.0.9.tgz#12319f8323b1254739b7c6bef8d3e89ae05a2f57", + "buffer-shims@~1.0.0": "https://registry.yarnpkg.com/buffer-shims/-/buffer-shims-1.0.0.tgz#9978ce317388c649ad8793028c3477ef044a8b51", + "bytes@3.0.0": "https://registry.yarnpkg.com/bytes/-/bytes-3.0.0.tgz#d32815404d689699f85a4ea4fa8755dd13a96048", + "camelcase@^2.0.1": "https://registry.yarnpkg.com/camelcase/-/camelcase-2.1.1.tgz#7c1d16d679a1bbe59ca02cacecfb011e201f5a1f", + "cliui@^3.0.3": "https://registry.yarnpkg.com/cliui/-/cliui-3.2.0.tgz#120601537a916d29940f934da3b48d585a39213d", + "code-point-at@^1.0.0": "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77", + "colors@1.0.x": "https://registry.yarnpkg.com/colors/-/colors-1.0.3.tgz#0433f44d809680fdeb60ed260f1b0c262e82a40b", + "content-disposition@0.5.2": "https://registry.yarnpkg.com/content-disposition/-/content-disposition-0.5.2.tgz#0cf68bb9ddf5f2be7961c3a85178cb85dba78cb4", + "content-type@~1.0.4": "https://registry.yarnpkg.com/content-type/-/content-type-1.0.4.tgz#e138cc75e040c727b1966fe5e5f8c9aee256fe3b", + "cookie-parser@~1.4.4": "https://registry.yarnpkg.com/cookie-parser/-/cookie-parser-1.4.5.tgz#3e572d4b7c0c80f9c61daf604e4336831b5d1d49", + "cookie-signature@1.0.6": "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.0.6.tgz#e303a882b342cc3ee8ca513a79999734dab3ae2c", + "cookie@0.3.1": "https://registry.yarnpkg.com/cookie/-/cookie-0.3.1.tgz#e7e0a1f9ef43b4c8ba925c5c5a96e806d16873bb", + "cookie@0.4.0": "https://registry.yarnpkg.com/cookie/-/cookie-0.4.0.tgz#beb437e7022b3b6d49019d088665303ebe9c14ba", + "core-util-is@~1.0.0": "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7", + "cycle@1.0.x": "https://registry.yarnpkg.com/cycle/-/cycle-1.0.3.tgz#21e80b2be8580f98b468f379430662b046c34ad2", + "debug@2.6.9": "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f", + "debug@~2.6.9": "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f", + "decamelize@^1.1.1": "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290", + "depd@~1.1.2": "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9", + "destroy@~1.0.4": "https://registry.yarnpkg.com/destroy/-/destroy-1.0.4.tgz#978857442c44749e4206613e37946205826abd80", + "ee-first@1.1.1": "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d", + "encodeurl@~1.0.2": "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59", + "es6-promise@3.2.1": "https://registry.yarnpkg.com/es6-promise/-/es6-promise-3.2.1.tgz#ec56233868032909207170c39448e24449dd1fc4", + "escape-html@~1.0.3": "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988", + "etag@~1.8.1": "https://registry.yarnpkg.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887", + "express@~4.16.1": "https://registry.yarnpkg.com/express/-/express-4.16.4.tgz#fddef61926109e24c515ea97fd2f1bdbf62df12e", + "eyes@0.1.x": "https://registry.yarnpkg.com/eyes/-/eyes-0.1.8.tgz#62cf120234c683785d902348a800ef3e0cc20bc0", + "finalhandler@1.1.1": "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.1.1.tgz#eebf4ed840079c83f4249038c9d703008301b105", + "forwarded@~0.1.2": "https://registry.yarnpkg.com/forwarded/-/forwarded-0.1.2.tgz#98c23dab1175657b8c0573e8ceccd91b0ff18c84", + "fresh@0.5.2": "https://registry.yarnpkg.com/fresh/-/fresh-0.5.2.tgz#3d8cadd90d976569fa835ab1f8e4b23a105605a7", + "hooks-fixed@2.0.2": "https://registry.yarnpkg.com/hooks-fixed/-/hooks-fixed-2.0.2.tgz#20076daa07e77d8a6106883ce3f1722e051140b0", + "http-errors@1.6.3": "https://registry.yarnpkg.com/http-errors/-/http-errors-1.6.3.tgz#8b55680bb4be283a0b5bf4ea2e38580be1d9320d", + "http-errors@~1.6.2": "https://registry.yarnpkg.com/http-errors/-/http-errors-1.6.3.tgz#8b55680bb4be283a0b5bf4ea2e38580be1d9320d", + "http-errors@~1.6.3": "https://registry.yarnpkg.com/http-errors/-/http-errors-1.6.3.tgz#8b55680bb4be283a0b5bf4ea2e38580be1d9320d", + "iconv-lite@0.4.23": "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.23.tgz#297871f63be507adcfbfca715d0cd0eed84e9a63", + "inherits@2.0.3": "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de", + "inherits@~2.0.1": "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c", + "ini@^1.3.0": "https://registry.yarnpkg.com/ini/-/ini-1.3.5.tgz#eee25f56db1c9ec6085e0c22778083f596abf927", + "invert-kv@^1.0.0": "https://registry.yarnpkg.com/invert-kv/-/invert-kv-1.0.0.tgz#104a8e4aaca6d3d8cd157a8ef8bfab2d7a3ffdb6", + "ipaddr.js@1.9.1": "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz#bff38543eeb8984825079ff3a2a8e6cbd46781b3", + "is-fullwidth-code-point@^1.0.0": "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb", + "isarray@~1.0.0": "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11", + "isstream@0.1.x": "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a", + "kareem@1.5.0": "https://registry.yarnpkg.com/kareem/-/kareem-1.5.0.tgz#e3e4101d9dcfde299769daf4b4db64d895d17448", + "lcid@^1.0.0": "https://registry.yarnpkg.com/lcid/-/lcid-1.0.0.tgz#308accafa0bc483a3867b4b6f2b9506251d1b835", + "lodash.get@4.4.2": "https://registry.yarnpkg.com/lodash.get/-/lodash.get-4.4.2.tgz#2d177f652fa31e939b4438d5341499dfa3825e99", + "lodash@^4.14.0": "https://registry.yarnpkg.com/lodash/-/lodash-4.17.15.tgz#b447f6670a0455bbfeedd11392eff330ea097548", + "media-typer@0.3.0": "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748", + "merge-descriptors@1.0.1": "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-1.0.1.tgz#b00aaa556dd8b44568150ec9d1b953f3f90cbb61", + "methods@~1.1.2": "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee", + "mime-db@1.44.0": "https://registry.yarnpkg.com/mime-db/-/mime-db-1.44.0.tgz#fa11c5eb0aca1334b4233cb4d52f10c5a6272f92", + "mime-types@~2.1.24": "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.27.tgz#47949f98e279ea53119f5722e0f34e529bec009f", + "mime@1.4.1": "https://registry.yarnpkg.com/mime/-/mime-1.4.1.tgz#121f9ebc49e3766f311a76e1fa1c8003c4b03aa6", + "mongoclient@^1.0.3": "https://registry.yarnpkg.com/mongoclient/-/mongoclient-1.0.3.tgz#dd72fa50444f02152cfd3d2e50acceb1067535f1", + "mongodb-core@2.1.18": "https://registry.yarnpkg.com/mongodb-core/-/mongodb-core-2.1.18.tgz#4c46139bdf3a1f032ded91db49f38eec01659050", + "mongodb@2.2.34": "https://registry.yarnpkg.com/mongodb/-/mongodb-2.2.34.tgz#a34f59bbeb61754aec432de72c3fe21526a44c1a", + "mongoose@^4.9.6": "https://registry.yarnpkg.com/mongoose/-/mongoose-4.13.20.tgz#7d6cdc35eca23306bb7388a74a08be1dc1487a7d", + "morgan@~1.9.1": "https://registry.yarnpkg.com/morgan/-/morgan-1.9.1.tgz#0a8d16734a1d9afbc824b99df87e738e58e2da59", + "mpath@0.5.1": "https://registry.yarnpkg.com/mpath/-/mpath-0.5.1.tgz#17131501f1ff9e6e4fbc8ffa875aa7065b5775ab", + "mpromise@0.5.5": "https://registry.yarnpkg.com/mpromise/-/mpromise-0.5.5.tgz#f5b24259d763acc2257b0a0c8c6d866fd51732e6", + "mquery@2.3.3": "https://registry.yarnpkg.com/mquery/-/mquery-2.3.3.tgz#221412e5d4e7290ca5582dd16ea8f190a506b518", + "ms@2.0.0": "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8", + "muri@1.3.0": "https://registry.yarnpkg.com/muri/-/muri-1.3.0.tgz#aeccf3db64c56aa7c5b34e00f95b7878527a4721", + "nconf@^0.8.4": "https://registry.yarnpkg.com/nconf/-/nconf-0.8.5.tgz#f2941e1561952fa906bbb32328cf88d4c635e794", + "negotiator@0.6.2": "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.2.tgz#feacf7ccf525a77ae9634436a64883ffeca346fb", + "number-is-nan@^1.0.0": "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d", + "on-finished@~2.3.0": "https://registry.yarnpkg.com/on-finished/-/on-finished-2.3.0.tgz#20f1336481b083cd75337992a16971aa2d906947", + "on-headers@~1.0.1": "https://registry.yarnpkg.com/on-headers/-/on-headers-1.0.2.tgz#772b0ae6aaa525c399e489adfad90c403eb3c28f", + "os-locale@^1.4.0": "https://registry.yarnpkg.com/os-locale/-/os-locale-1.4.0.tgz#20f9f17ae29ed345e8bde583b13d2009803c14d9", + "parseurl@~1.3.2": "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4", + "path-to-regexp@0.1.7": "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.7.tgz#df604178005f522f15eb4490e7247a1bfaa67f8c", + "process-nextick-args@~1.0.6": "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-1.0.7.tgz#150e20b756590ad3f91093f25a4f2ad8bff30ba3", + "proxy-addr@~2.0.4": "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.6.tgz#fdc2336505447d3f2f2c638ed272caf614bbb2bf", + "qs@6.5.2": "https://registry.yarnpkg.com/qs/-/qs-6.5.2.tgz#cb3ae806e8740444584ef154ce8ee98d403f3e36", + "range-parser@~1.2.0": "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.1.tgz#3cf37023d199e1c24d1a55b84800c2f3e6468031", + "raw-body@2.3.3": "https://registry.yarnpkg.com/raw-body/-/raw-body-2.3.3.tgz#1b324ece6b5706e153855bc1148c65bb7f6ea0c3", + "readable-stream@2.2.7": "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.2.7.tgz#07057acbe2467b22042d36f98c5ad507054e95b1", + "regexp-clone@0.0.1": "https://registry.yarnpkg.com/regexp-clone/-/regexp-clone-0.0.1.tgz#a7c2e09891fdbf38fbb10d376fb73003e68ac589", + "require_optional@~1.0.0": "https://registry.yarnpkg.com/require_optional/-/require_optional-1.0.1.tgz#4cf35a4247f64ca3df8c2ef208cc494b1ca8fc2e", + "resolve-from@^2.0.0": "https://registry.yarnpkg.com/resolve-from/-/resolve-from-2.0.0.tgz#9480ab20e94ffa1d9e80a804c7ea147611966b57", + "safe-buffer@5.1.2": "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d", + "safe-buffer@~5.1.0": "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d", + "safer-buffer@>= 2.1.2 < 3": "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a", + "secure-keys@^1.0.0": "https://registry.yarnpkg.com/secure-keys/-/secure-keys-1.0.0.tgz#f0c82d98a3b139a8776a8808050b824431087fca", + "semver@^5.1.0": "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7", + "send@0.16.2": "https://registry.yarnpkg.com/send/-/send-0.16.2.tgz#6ecca1e0f8c156d141597559848df64730a6bbc1", + "serve-static@1.13.2": "https://registry.yarnpkg.com/serve-static/-/serve-static-1.13.2.tgz#095e8472fd5b46237db50ce486a43f4b86c6cec1", + "setprototypeof@1.1.0": "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.1.0.tgz#d0bd85536887b6fe7c0d818cb962d9d91c54e656", + "sliced@0.0.5": "https://registry.yarnpkg.com/sliced/-/sliced-0.0.5.tgz#5edc044ca4eb6f7816d50ba2fc63e25d8fe4707f", + "sliced@1.0.1": "https://registry.yarnpkg.com/sliced/-/sliced-1.0.1.tgz#0b3a662b5d04c3177b1926bea82b03f837a2ef41", + "stack-trace@0.0.x": "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz#547c70b347e8d32b4e108ea1a2a159e5fdde19c0", + "statuses@>= 1.4.0 < 2": "https://registry.yarnpkg.com/statuses/-/statuses-1.5.0.tgz#161c7dac177659fd9811f43771fa99381478628c", + "statuses@~1.4.0": "https://registry.yarnpkg.com/statuses/-/statuses-1.4.0.tgz#bb73d446da2796106efcc1b601a253d6c46bd087", + "string-width@^1.0.1": "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3", + "string_decoder@~1.0.0": "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.0.3.tgz#0fc67d7c141825de94282dd536bec6b9bce860ab", + "strip-ansi@^3.0.0": "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf", + "strip-ansi@^3.0.1": "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf", + "type-is@~1.6.16": "https://registry.yarnpkg.com/type-is/-/type-is-1.6.18.tgz#4e552cd05df09467dcbc4ef739de89f2cf37c131", + "unpipe@1.0.0": "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "unpipe@~1.0.0": "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec", + "util-deprecate@~1.0.1": "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf", + "utils-merge@1.0.1": "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713", + "vary@~1.1.2": "https://registry.yarnpkg.com/vary/-/vary-1.1.2.tgz#2299f02c6ded30d4a5961b0b9f74524a18f634fc", + "window-size@^0.1.4": "https://registry.yarnpkg.com/window-size/-/window-size-0.1.4.tgz#f8e1aa1ee5a53ec5bf151ffa09742a6ad7697876", + "winston@^2.3.1": "https://registry.yarnpkg.com/winston/-/winston-2.4.4.tgz#a01e4d1d0a103cf4eada6fc1f886b3110d71c34b", + "wrap-ansi@^2.0.0": "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85", + "y18n@^3.2.0": "https://registry.yarnpkg.com/y18n/-/y18n-3.2.1.tgz#6d15fba884c08679c0d77e88e7759e811e07fa41", + "yargs@^3.19.0": "https://registry.yarnpkg.com/yargs/-/yargs-3.32.0.tgz#03088e9ebf9e756b69751611d2a5ef591482c995" + }, + "files": [], + "artifacts": {} +} \ No newline at end of file diff --git a/app/node_modules/accepts/HISTORY.md b/app/node_modules/accepts/HISTORY.md new file mode 100644 index 0000000..0bf0417 --- /dev/null +++ b/app/node_modules/accepts/HISTORY.md @@ -0,0 +1,236 @@ +1.3.7 / 2019-04-29 +================== + + * deps: negotiator@0.6.2 + - Fix sorting charset, encoding, and language with extra parameters + +1.3.6 / 2019-04-28 +================== + + * deps: mime-types@~2.1.24 + - deps: mime-db@~1.40.0 + +1.3.5 / 2018-02-28 +================== + + * deps: mime-types@~2.1.18 + - deps: mime-db@~1.33.0 + +1.3.4 / 2017-08-22 +================== + + * deps: mime-types@~2.1.16 + - deps: mime-db@~1.29.0 + +1.3.3 / 2016-05-02 +================== + + * deps: mime-types@~2.1.11 + - deps: mime-db@~1.23.0 + * deps: negotiator@0.6.1 + - perf: improve `Accept` parsing speed + - perf: improve `Accept-Charset` parsing speed + - perf: improve `Accept-Encoding` parsing speed + - perf: improve `Accept-Language` parsing speed + +1.3.2 / 2016-03-08 +================== + + * deps: mime-types@~2.1.10 + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + - deps: mime-db@~1.22.0 + +1.3.1 / 2016-01-19 +================== + + * deps: mime-types@~2.1.9 + - deps: mime-db@~1.21.0 + +1.3.0 / 2015-09-29 +================== + + * deps: mime-types@~2.1.7 + - deps: mime-db@~1.19.0 + * deps: negotiator@0.6.0 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Lazy-load modules from main entry point + - perf: delay type concatenation until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove closures getting spec properties + - perf: remove a closure from media type parsing + - perf: remove property delete from media type parsing + +1.2.13 / 2015-09-06 +=================== + + * deps: mime-types@~2.1.6 + - deps: mime-db@~1.18.0 + +1.2.12 / 2015-07-30 +=================== + + * deps: mime-types@~2.1.4 + - deps: mime-db@~1.16.0 + +1.2.11 / 2015-07-16 +=================== + + * deps: mime-types@~2.1.3 + - deps: mime-db@~1.15.0 + +1.2.10 / 2015-07-01 +=================== + + * deps: mime-types@~2.1.2 + - deps: mime-db@~1.14.0 + +1.2.9 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - perf: fix deopt during mapping + +1.2.8 / 2015-06-07 +================== + + * deps: mime-types@~2.1.0 + - deps: mime-db@~1.13.0 + * perf: avoid argument reassignment & argument slice + * perf: avoid negotiator recursive construction + * perf: enable strict mode + * perf: remove unnecessary bitwise operator + +1.2.7 / 2015-05-10 +================== + + * deps: negotiator@0.5.3 + - Fix media type parameter matching to be case-insensitive + +1.2.6 / 2015-05-07 +================== + + * deps: mime-types@~2.0.11 + - deps: mime-db@~1.9.1 + * deps: negotiator@0.5.2 + - Fix comparing media types with quoted values + - Fix splitting media types with quoted commas + +1.2.5 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - deps: mime-db@~1.8.0 + +1.2.4 / 2015-02-14 +================== + + * Support Node.js 0.6 + * deps: mime-types@~2.0.9 + - deps: mime-db@~1.7.0 + * deps: negotiator@0.5.1 + - Fix preference sorting to be stable for long acceptable lists + +1.2.3 / 2015-01-31 +================== + + * deps: mime-types@~2.0.8 + - deps: mime-db@~1.6.0 + +1.2.2 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - deps: mime-db@~1.5.0 + +1.2.1 / 2014-12-30 +================== + + * deps: mime-types@~2.0.5 + - deps: mime-db@~1.3.1 + +1.2.0 / 2014-12-19 +================== + + * deps: negotiator@0.5.0 + - Fix list return order when large accepted list + - Fix missing identity encoding when q=0 exists + - Remove dynamic building of Negotiator class + +1.1.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - deps: mime-db@~1.3.0 + +1.1.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - deps: mime-db@~1.2.0 + +1.1.2 / 2014-10-14 +================== + + * deps: negotiator@0.4.9 + - Fix error when media type has invalid parameter + +1.1.1 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - deps: mime-db@~1.1.0 + * deps: negotiator@0.4.8 + - Fix all negotiations to be case-insensitive + - Stable sort preferences of same quality according to client order + +1.1.0 / 2014-09-02 +================== + + * update `mime-types` + +1.0.7 / 2014-07-04 +================== + + * Fix wrong type returned from `type` when match after unknown extension + +1.0.6 / 2014-06-24 +================== + + * deps: negotiator@0.4.7 + +1.0.5 / 2014-06-20 +================== + + * fix crash when unknown extension given + +1.0.4 / 2014-06-19 +================== + + * use `mime-types` + +1.0.3 / 2014-06-11 +================== + + * deps: negotiator@0.4.6 + - Order by specificity when quality is the same + +1.0.2 / 2014-05-29 +================== + + * Fix interpretation when header not in request + * deps: pin negotiator@0.4.5 + +1.0.1 / 2014-01-18 +================== + + * Identity encoding isn't always acceptable + * deps: negotiator@~0.4.0 + +1.0.0 / 2013-12-27 +================== + + * Genesis diff --git a/app/node_modules/accepts/LICENSE b/app/node_modules/accepts/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/app/node_modules/accepts/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +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/app/node_modules/accepts/README.md b/app/node_modules/accepts/README.md new file mode 100644 index 0000000..66a2f54 --- /dev/null +++ b/app/node_modules/accepts/README.md @@ -0,0 +1,142 @@ +# accepts + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). +Extracted from [koa](https://www.npmjs.com/package/koa) for general use. + +In addition to negotiator, it allows: + +- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` + as well as `('text/html', 'application/json')`. +- Allows type shorthands such as `json`. +- Returns `false` when no types match +- Treats non-existent headers as `*` + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install accepts +``` + +## API + + + +```js +var accepts = require('accepts') +``` + +### accepts(req) + +Create a new `Accepts` object for the given `req`. + +#### .charset(charsets) + +Return the first accepted charset. If nothing in `charsets` is accepted, +then `false` is returned. + +#### .charsets() + +Return the charsets that the request accepts, in the order of the client's +preference (most preferred first). + +#### .encoding(encodings) + +Return the first accepted encoding. If nothing in `encodings` is accepted, +then `false` is returned. + +#### .encodings() + +Return the encodings that the request accepts, in the order of the client's +preference (most preferred first). + +#### .language(languages) + +Return the first accepted language. If nothing in `languages` is accepted, +then `false` is returned. + +#### .languages() + +Return the languages that the request accepts, in the order of the client's +preference (most preferred first). + +#### .type(types) + +Return the first accepted type (and it is returned as the same text as what +appears in the `types` array). If nothing in `types` is accepted, then `false` +is returned. + +The `types` array can contain full MIME types or file extensions. Any value +that is not a full MIME types is passed to `require('mime-types').lookup`. + +#### .types() + +Return the types that the request accepts, in the order of the client's +preference (most preferred first). + +## Examples + +### Simple type negotiation + +This simple example shows how to use `accepts` to return a different typed +respond body based on what the client wants to accept. The server lists it's +preferences in order and will get back the best match between the client and +server. + +```js +var accepts = require('accepts') +var http = require('http') + +function app (req, res) { + var accept = accepts(req) + + // the order of this list is significant; should be server preferred order + switch (accept.type(['json', 'html'])) { + case 'json': + res.setHeader('Content-Type', 'application/json') + res.write('{"hello":"world!"}') + break + case 'html': + res.setHeader('Content-Type', 'text/html') + res.write('hello, world!') + break + default: + // the fallback is text/plain, so no need to specify it above + res.setHeader('Content-Type', 'text/plain') + res.write('hello, world!') + break + } + + res.end() +} + +http.createServer(app).listen(3000) +``` + +You can test this out with the cURL program: +```sh +curl -I -H'Accept: text/html' http://localhost:3000/ +``` + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master +[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master +[node-version-image]: https://badgen.net/npm/node/accepts +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/accepts +[npm-url]: https://npmjs.org/package/accepts +[npm-version-image]: https://badgen.net/npm/v/accepts +[travis-image]: https://badgen.net/travis/jshttp/accepts/master +[travis-url]: https://travis-ci.org/jshttp/accepts diff --git a/app/node_modules/accepts/index.js b/app/node_modules/accepts/index.js new file mode 100644 index 0000000..e9b2f63 --- /dev/null +++ b/app/node_modules/accepts/index.js @@ -0,0 +1,238 @@ +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Negotiator = require('negotiator') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = Accepts + +/** + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public + */ + +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) + } + + this.headers = req.headers + this.negotiator = new Negotiator(req) +} + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ + +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i] + } + } + + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } + + // no accept header, return first given type + if (!this.headers.accept) { + return types[0] + } + + var mimes = types.map(extToMime) + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) + var first = accepts[0] + + return first + ? types[mimes.indexOf(first)] + : false +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ + + // support flattened arguments + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length) + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i] + } + } + + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() + } + + return this.negotiator.encodings(encodings)[0] || false +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ + + // support flattened arguments + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length) + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i] + } + } + + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() + } + + return this.negotiator.charsets(charsets)[0] || false +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ + + // support flattened arguments + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length) + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i] + } + } + + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() + } + + return this.negotiator.languages(languages)[0] || false +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private + */ + +function validMime (type) { + return typeof type === 'string' +} diff --git a/app/node_modules/accepts/package.json b/app/node_modules/accepts/package.json new file mode 100644 index 0000000..bc750cf --- /dev/null +++ b/app/node_modules/accepts/package.json @@ -0,0 +1,47 @@ +{ + "name": "accepts", + "description": "Higher-level content negotiation", + "version": "1.3.7", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "jshttp/accepts", + "dependencies": { + "mime-types": "~2.1.24", + "negotiator": "0.6.2" + }, + "devDependencies": { + "deep-equal": "1.0.1", + "eslint": "5.16.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.17.2", + "eslint-plugin-markdown": "1.0.0", + "eslint-plugin-node": "8.0.1", + "eslint-plugin-promise": "4.1.1", + "eslint-plugin-standard": "4.0.0", + "mocha": "6.1.4", + "nyc": "14.0.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-travis": "nyc --reporter=text npm test" + }, + "keywords": [ + "content", + "negotiation", + "accept", + "accepts" + ] +} diff --git a/app/node_modules/ansi-regex/index.js b/app/node_modules/ansi-regex/index.js new file mode 100644 index 0000000..b9574ed --- /dev/null +++ b/app/node_modules/ansi-regex/index.js @@ -0,0 +1,4 @@ +'use strict'; +module.exports = function () { + return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g; +}; diff --git a/app/node_modules/ansi-regex/license b/app/node_modules/ansi-regex/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/app/node_modules/ansi-regex/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/app/node_modules/ansi-regex/package.json b/app/node_modules/ansi-regex/package.json new file mode 100644 index 0000000..eb44fb5 --- /dev/null +++ b/app/node_modules/ansi-regex/package.json @@ -0,0 +1,64 @@ +{ + "name": "ansi-regex", + "version": "2.1.1", + "description": "Regular expression for matching ANSI escape codes", + "license": "MIT", + "repository": "chalk/ansi-regex", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "maintainers": [ + "Sindre Sorhus (sindresorhus.com)", + "Joshua Appelman (jbnicolai.com)", + "JD Ballard (github.com/qix-)" + ], + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava --verbose", + "view-supported": "node fixtures/view-codes.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "text", + "regex", + "regexp", + "re", + "match", + "test", + "find", + "pattern" + ], + "devDependencies": { + "ava": "0.17.0", + "xo": "0.16.0" + }, + "xo": { + "rules": { + "guard-for-in": 0, + "no-loop-func": 0 + } + } +} diff --git a/app/node_modules/ansi-regex/readme.md b/app/node_modules/ansi-regex/readme.md new file mode 100644 index 0000000..6a928ed --- /dev/null +++ b/app/node_modules/ansi-regex/readme.md @@ -0,0 +1,39 @@ +# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex) + +> Regular expression for matching [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code) + + +## Install + +``` +$ npm install --save ansi-regex +``` + + +## Usage + +```js +const ansiRegex = require('ansi-regex'); + +ansiRegex().test('\u001b[4mcake\u001b[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001b[4mcake\u001b[0m'.match(ansiRegex()); +//=> ['\u001b[4m', '\u001b[0m'] +``` + +## FAQ + +### Why do you test for codes not in the ECMA 48 standard? + +Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. If I recall correctly, we test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. + +On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/app/node_modules/array-flatten/LICENSE b/app/node_modules/array-flatten/LICENSE new file mode 100644 index 0000000..983fbe8 --- /dev/null +++ b/app/node_modules/array-flatten/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/app/node_modules/array-flatten/README.md b/app/node_modules/array-flatten/README.md new file mode 100644 index 0000000..91fa5b6 --- /dev/null +++ b/app/node_modules/array-flatten/README.md @@ -0,0 +1,43 @@ +# Array Flatten + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] + +> Flatten an array of nested arrays into a single flat array. Accepts an optional depth. + +## Installation + +``` +npm install array-flatten --save +``` + +## Usage + +```javascript +var flatten = require('array-flatten') + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9]) +//=> [1, 2, 3, 4, 5, 6, 7, 8, 9] + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2) +//=> [1, 2, 3, [4, [5], 6], 7, 8, 9] + +(function () { + flatten(arguments) //=> [1, 2, 3] +})(1, [2, 3]) +``` + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat +[npm-url]: https://npmjs.org/package/array-flatten +[downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat +[downloads-url]: https://npmjs.org/package/array-flatten +[travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat +[travis-url]: https://travis-ci.org/blakeembrey/array-flatten +[coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat +[coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master diff --git a/app/node_modules/array-flatten/array-flatten.js b/app/node_modules/array-flatten/array-flatten.js new file mode 100644 index 0000000..089117b --- /dev/null +++ b/app/node_modules/array-flatten/array-flatten.js @@ -0,0 +1,64 @@ +'use strict' + +/** + * Expose `arrayFlatten`. + */ +module.exports = arrayFlatten + +/** + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} + */ +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) + } + } + + return result +} + +/** + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} + */ +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } + } + + return result +} + +/** + * Flatten an array, with the ability to define a depth. + * + * @param {Array} array + * @param {Number} depth + * @return {Array} + */ +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } + + return flattenWithDepth(array, [], depth) +} diff --git a/app/node_modules/array-flatten/package.json b/app/node_modules/array-flatten/package.json new file mode 100644 index 0000000..1a24e2a --- /dev/null +++ b/app/node_modules/array-flatten/package.json @@ -0,0 +1,39 @@ +{ + "name": "array-flatten", + "version": "1.1.1", + "description": "Flatten an array of nested arrays into a single flat array", + "main": "array-flatten.js", + "files": [ + "array-flatten.js", + "LICENSE" + ], + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "repository": { + "type": "git", + "url": "git://github.com/blakeembrey/array-flatten.git" + }, + "keywords": [ + "array", + "flatten", + "arguments", + "depth" + ], + "author": { + "name": "Blake Embrey", + "email": "hello@blakeembrey.com", + "url": "http://blakeembrey.me" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/blakeembrey/array-flatten/issues" + }, + "homepage": "https://github.com/blakeembrey/array-flatten", + "devDependencies": { + "istanbul": "^0.3.13", + "mocha": "^2.2.4", + "pre-commit": "^1.0.7", + "standard": "^3.7.3" + } +} diff --git a/app/node_modules/async/CHANGELOG.md b/app/node_modules/async/CHANGELOG.md new file mode 100644 index 0000000..de85303 --- /dev/null +++ b/app/node_modules/async/CHANGELOG.md @@ -0,0 +1,263 @@ +# v2.6.0 +- Added missing aliases for many methods. Previously, you could not (e.g.) `require('async/find')` or use `async.anyLimit`. (#1483) +- Improved `queue` performance. (#1448, #1454) +- Add missing sourcemap (#1452, #1453) +- Various doc updates (#1448, #1471, #1483) + +# v2.5.0 +- Added `concatLimit`, the `Limit` equivalent of [`concat`](https://caolan.github.io/async/docs.html#concat) ([#1426](https://github.com/caolan/async/issues/1426), [#1430](https://github.com/caolan/async/pull/1430)) +- `concat` improvements: it now preserves order, handles falsy values and the `iteratee` callback takes a variable number of arguments ([#1437](https://github.com/caolan/async/issues/1437), [#1436](https://github.com/caolan/async/pull/1436)) +- Fixed an issue in `queue` where there was a size discrepancy between `workersList().length` and `running()` ([#1428](https://github.com/caolan/async/issues/1428), [#1429](https://github.com/caolan/async/pull/1429)) +- Various doc fixes ([#1422](https://github.com/caolan/async/issues/1422), [#1424](https://github.com/caolan/async/pull/1424)) + +# v2.4.1 +- Fixed a bug preventing functions wrapped with `timeout()` from being re-used. ([#1418](https://github.com/caolan/async/issues/1418), [#1419](https://github.com/caolan/async/issues/1419)) + +# v2.4.0 +- Added `tryEach`, for running async functions in parallel, where you only expect one to succeed. ([#1365](https://github.com/caolan/async/issues/1365), [#687](https://github.com/caolan/async/issues/687)) +- Improved performance, most notably in `parallel` and `waterfall` ([#1395](https://github.com/caolan/async/issues/1395)) +- Added `queue.remove()`, for removing items in a `queue` ([#1397](https://github.com/caolan/async/issues/1397), [#1391](https://github.com/caolan/async/issues/1391)) +- Fixed using `eval`, preventing Async from running in pages with Content Security Policy ([#1404](https://github.com/caolan/async/issues/1404), [#1403](https://github.com/caolan/async/issues/1403)) +- Fixed errors thrown in an `asyncify`ed function's callback being caught by the underlying Promise ([#1408](https://github.com/caolan/async/issues/1408)) +- Fixed timing of `queue.empty()` ([#1367](https://github.com/caolan/async/issues/1367)) +- Various doc fixes ([#1314](https://github.com/caolan/async/issues/1314), [#1394](https://github.com/caolan/async/issues/1394), [#1412](https://github.com/caolan/async/issues/1412)) + +# v2.3.0 +- Added support for ES2017 `async` functions. Wherever you can pass a Node-style/CPS function that uses a callback, you can also pass an `async` function. Previously, you had to wrap `async` functions with `asyncify`. The caveat is that it will only work if `async` functions are supported natively in your environment, transpiled implementations can't be detected. ([#1386](https://github.com/caolan/async/issues/1386), [#1390](https://github.com/caolan/async/issues/1390)) +- Small doc fix ([#1392](https://github.com/caolan/async/issues/1392)) + +# v2.2.0 +- Added `groupBy`, and the `Series`/`Limit` equivalents, analogous to [`_.groupBy`](http://lodash.com/docs#groupBy) ([#1364](https://github.com/caolan/async/issues/1364)) +- Fixed `transform` bug when `callback` was not passed ([#1381](https://github.com/caolan/async/issues/1381)) +- Added note about `reflect` to `parallel` docs ([#1385](https://github.com/caolan/async/issues/1385)) + +# v2.1.5 +- Fix `auto` bug when function names collided with Array.prototype ([#1358](https://github.com/caolan/async/issues/1358)) +- Improve some error messages ([#1349](https://github.com/caolan/async/issues/1349)) +- Avoid stack overflow case in queue +- Fixed an issue in `some`, `every` and `find` where processing would continue after the result was determined. +- Cleanup implementations of `some`, `every` and `find` + +# v2.1.3 +- Make bundle size smaller +- Create optimized hotpath for `filter` in array case. + +# v2.1.2 +- Fixed a stackoverflow bug with `detect`, `some`, `every` on large inputs ([#1293](https://github.com/caolan/async/issues/1293)). + +# v2.1.0 + +- `retry` and `retryable` now support an optional `errorFilter` function that determines if the `task` should retry on the error ([#1256](https://github.com/caolan/async/issues/1256), [#1261](https://github.com/caolan/async/issues/1261)) +- Optimized array iteration in `race`, `cargo`, `queue`, and `priorityQueue` ([#1253](https://github.com/caolan/async/issues/1253)) +- Added alias documentation to doc site ([#1251](https://github.com/caolan/async/issues/1251), [#1254](https://github.com/caolan/async/issues/1254)) +- Added [BootStrap scrollspy](http://getbootstrap.com/javascript/#scrollspy) to docs to highlight in the sidebar the current method being viewed ([#1289](https://github.com/caolan/async/issues/1289), [#1300](https://github.com/caolan/async/issues/1300)) +- Various minor doc fixes ([#1263](https://github.com/caolan/async/issues/1263), [#1264](https://github.com/caolan/async/issues/1264), [#1271](https://github.com/caolan/async/issues/1271), [#1278](https://github.com/caolan/async/issues/1278), [#1280](https://github.com/caolan/async/issues/1280), [#1282](https://github.com/caolan/async/issues/1282), [#1302](https://github.com/caolan/async/issues/1302)) + +# v2.0.1 + +- Significantly optimized all iteration based collection methods such as `each`, `map`, `filter`, etc ([#1245](https://github.com/caolan/async/issues/1245), [#1246](https://github.com/caolan/async/issues/1246), [#1247](https://github.com/caolan/async/issues/1247)). + +# v2.0.0 + +Lots of changes here! + +First and foremost, we have a slick new [site for docs](https://caolan.github.io/async/). Special thanks to [**@hargasinski**](https://github.com/hargasinski) for his work converting our old docs to `jsdoc` format and implementing the new website. Also huge ups to [**@ivanseidel**](https://github.com/ivanseidel) for designing our new logo. It was a long process for both of these tasks, but I think these changes turned out extraordinary well. + +The biggest feature is modularization. You can now `require("async/series")` to only require the `series` function. Every Async library function is available this way. You still can `require("async")` to require the entire library, like you could do before. + +We also provide Async as a collection of ES2015 modules. You can now `import {each} from 'async-es'` or `import waterfall from 'async-es/waterfall'`. If you are using only a few Async functions, and are using a ES bundler such as Rollup, this can significantly lower your build size. + +Major thanks to [**@Kikobeats**](github.com/Kikobeats), [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for doing the majority of the modularization work, as well as [**@jdalton**](github.com/jdalton) and [**@Rich-Harris**](github.com/Rich-Harris) for advisory work on the general modularization strategy. + +Another one of the general themes of the 2.0 release is standardization of what an "async" function is. We are now more strictly following the node-style continuation passing style. That is, an async function is a function that: + +1. Takes a variable number of arguments +2. The last argument is always a callback +3. The callback can accept any number of arguments +4. The first argument passed to the callback will be treated as an error result, if the argument is truthy +5. Any number of result arguments can be passed after the "error" argument +6. The callback is called once and exactly once, either on the same tick or later tick of the JavaScript event loop. + +There were several cases where Async accepted some functions that did not strictly have these properties, most notably `auto`, `every`, `some`, and `filter`. + +Another theme is performance. We have eliminated internal deferrals in all cases where they make sense. For example, in `waterfall` and `auto`, there was a `setImmediate` between each task -- these deferrals have been removed. A `setImmediate` call can add up to 1ms of delay. This might not seem like a lot, but it can add up if you are using many Async functions in the course of processing a HTTP request, for example. Nearly all asynchronous functions that do I/O already have some sort of deferral built in, so the extra deferral is unnecessary. The trade-off of this change is removing our built-in stack-overflow defense. Many synchronous callback calls in series can quickly overflow the JS call stack. If you do have a function that is sometimes synchronous (calling its callback on the same tick), and are running into stack overflows, wrap it with `async.ensureAsync()`. + +Another big performance win has been re-implementing `queue`, `cargo`, and `priorityQueue` with [doubly linked lists](https://en.wikipedia.org/wiki/Doubly_linked_list) instead of arrays. This has lead to queues being an order of [magnitude faster on large sets of tasks](https://github.com/caolan/async/pull/1205). + +## New Features + +- Async is now modularized. Individual functions can be `require()`d from the main package. (`require('async/auto')`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) +- Async is also available as a collection of ES2015 modules in the new `async-es` package. (`import {forEachSeries} from 'async-es'`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996)) +- Added `race`, analogous to `Promise.race()`. It will run an array of async tasks in parallel and will call its callback with the result of the first task to respond. ([#568](https://github.com/caolan/async/issues/568), [#1038](https://github.com/caolan/async/issues/1038)) +- Collection methods now accept ES2015 iterators. Maps, Sets, and anything that implements the iterator spec can now be passed directly to `each`, `map`, `parallel`, etc.. ([#579](https://github.com/caolan/async/issues/579), [#839](https://github.com/caolan/async/issues/839), [#1074](https://github.com/caolan/async/issues/1074)) +- Added `mapValues`, for mapping over the properties of an object and returning an object with the same keys. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) +- Added `timeout`, a wrapper for an async function that will make the task time-out after the specified time. ([#1007](https://github.com/caolan/async/issues/1007), [#1027](https://github.com/caolan/async/issues/1027)) +- Added `reflect` and `reflectAll`, analagous to [`Promise.reflect()`](http://bluebirdjs.com/docs/api/reflect.html), a wrapper for async tasks that always succeeds, by gathering results and errors into an object. ([#942](https://github.com/caolan/async/issues/942), [#1012](https://github.com/caolan/async/issues/1012), [#1095](https://github.com/caolan/async/issues/1095)) +- `constant` supports dynamic arguments -- it will now always use its last argument as the callback. ([#1016](https://github.com/caolan/async/issues/1016), [#1052](https://github.com/caolan/async/issues/1052)) +- `setImmediate` and `nextTick` now support arguments to partially apply to the deferred function, like the node-native versions do. ([#940](https://github.com/caolan/async/issues/940), [#1053](https://github.com/caolan/async/issues/1053)) +- `auto` now supports resolving cyclic dependencies using [Kahn's algorithm](https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm) ([#1140](https://github.com/caolan/async/issues/1140)). +- Added `autoInject`, a relative of `auto` that automatically spreads a task's dependencies as arguments to the task function. ([#608](https://github.com/caolan/async/issues/608), [#1055](https://github.com/caolan/async/issues/1055), [#1099](https://github.com/caolan/async/issues/1099), [#1100](https://github.com/caolan/async/issues/1100)) +- You can now limit the concurrency of `auto` tasks. ([#635](https://github.com/caolan/async/issues/635), [#637](https://github.com/caolan/async/issues/637)) +- Added `retryable`, a relative of `retry` that wraps an async function, making it retry when called. ([#1058](https://github.com/caolan/async/issues/1058)) +- `retry` now supports specifying a function that determines the next time interval, useful for exponential backoff, logging and other retry strategies. ([#1161](https://github.com/caolan/async/issues/1161)) +- `retry` will now pass all of the arguments the task function was resolved with to the callback ([#1231](https://github.com/caolan/async/issues/1231)). +- Added `q.unsaturated` -- callback called when a `queue`'s number of running workers falls below a threshold. ([#868](https://github.com/caolan/async/issues/868), [#1030](https://github.com/caolan/async/issues/1030), [#1033](https://github.com/caolan/async/issues/1033), [#1034](https://github.com/caolan/async/issues/1034)) +- Added `q.error` -- a callback called whenever a `queue` task calls its callback with an error. ([#1170](https://github.com/caolan/async/issues/1170)) +- `applyEach` and `applyEachSeries` now pass results to the final callback. ([#1088](https://github.com/caolan/async/issues/1088)) + +## Breaking changes + +- Calling a callback more than once is considered an error, and an error will be thrown. This had an explicit breaking change in `waterfall`. If you were relying on this behavior, you should more accurately represent your control flow as an event emitter or stream. ([#814](https://github.com/caolan/async/issues/814), [#815](https://github.com/caolan/async/issues/815), [#1048](https://github.com/caolan/async/issues/1048), [#1050](https://github.com/caolan/async/issues/1050)) +- `auto` task functions now always take the callback as the last argument. If a task has dependencies, the `results` object will be passed as the first argument. To migrate old task functions, wrap them with [`_.flip`](https://lodash.com/docs#flip) ([#1036](https://github.com/caolan/async/issues/1036), [#1042](https://github.com/caolan/async/issues/1042)) +- Internal `setImmediate` calls have been refactored away. This may make existing flows vulnerable to stack overflows if you use many synchronous functions in series. Use `ensureAsync` to work around this. ([#696](https://github.com/caolan/async/issues/696), [#704](https://github.com/caolan/async/issues/704), [#1049](https://github.com/caolan/async/issues/1049), [#1050](https://github.com/caolan/async/issues/1050)) +- `map` used to return an object when iterating over an object. `map` now always returns an array, like in other libraries. The previous object behavior has been split out into `mapValues`. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177)) +- `filter`, `reject`, `some`, `every`, and related functions now expect an error as the first callback argument, rather than just a simple boolean. Pass `null` as the first argument, or use `fs.access` instead of `fs.exists`. ([#118](https://github.com/caolan/async/issues/118), [#774](https://github.com/caolan/async/issues/774), [#1028](https://github.com/caolan/async/issues/1028), [#1041](https://github.com/caolan/async/issues/1041)) +- `{METHOD}` and `{METHOD}Series` are now implemented in terms of `{METHOD}Limit`. This is a major internal simplification, and is not expected to cause many problems, but it does subtly affect how functions execute internally. ([#778](https://github.com/caolan/async/issues/778), [#847](https://github.com/caolan/async/issues/847)) +- `retry`'s callback is now optional. Previously, omitting the callback would partially apply the function, meaning it could be passed directly as a task to `series` or `auto`. The partially applied "control-flow" behavior has been separated out into `retryable`. ([#1054](https://github.com/caolan/async/issues/1054), [#1058](https://github.com/caolan/async/issues/1058)) +- The test function for `whilst`, `until`, and `during` used to be passed non-error args from the iteratee function's callback, but this led to weirdness where the first call of the test function would be passed no args. We have made it so the test function is never passed extra arguments, and only the `doWhilst`, `doUntil`, and `doDuring` functions pass iteratee callback arguments to the test function ([#1217](https://github.com/caolan/async/issues/1217), [#1224](https://github.com/caolan/async/issues/1224)) +- The `q.tasks` array has been renamed `q._tasks` and is now implemented as a doubly linked list (DLL). Any code that used to interact with this array will need to be updated to either use the provided helpers or support DLLs ([#1205](https://github.com/caolan/async/issues/1205)). +- The timing of the `q.saturated()` callback in a `queue` has been modified to better reflect when tasks pushed to the queue will start queueing. ([#724](https://github.com/caolan/async/issues/724), [#1078](https://github.com/caolan/async/issues/1078)) +- Removed `iterator` method in favour of [ES2015 iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators ) which natively supports arrays ([#1237](https://github.com/caolan/async/issues/1237)) +- Dropped support for Component, Jam, SPM, and Volo ([#1175](https://github.com/caolan/async/issues/1175), #[#176](https://github.com/caolan/async/issues/176)) + +## Bug Fixes + +- Improved handling of no dependency cases in `auto` & `autoInject` ([#1147](https://github.com/caolan/async/issues/1147)). +- Fixed a bug where the callback generated by `asyncify` with `Promises` could resolve twice ([#1197](https://github.com/caolan/async/issues/1197)). +- Fixed several documented optional callbacks not actually being optional ([#1223](https://github.com/caolan/async/issues/1223)). + +## Other + +- Added `someSeries` and `everySeries` for symmetry, as well as a complete set of `any`/`anyLimit`/`anySeries` and `all`/`/allLmit`/`allSeries` aliases. +- Added `find` as an alias for `detect. (as well as `findLimit` and `findSeries`). +- Various doc fixes ([#1005](https://github.com/caolan/async/issues/1005), [#1008](https://github.com/caolan/async/issues/1008), [#1010](https://github.com/caolan/async/issues/1010), [#1015](https://github.com/caolan/async/issues/1015), [#1021](https://github.com/caolan/async/issues/1021), [#1037](https://github.com/caolan/async/issues/1037), [#1039](https://github.com/caolan/async/issues/1039), [#1051](https://github.com/caolan/async/issues/1051), [#1102](https://github.com/caolan/async/issues/1102), [#1107](https://github.com/caolan/async/issues/1107), [#1121](https://github.com/caolan/async/issues/1121), [#1123](https://github.com/caolan/async/issues/1123), [#1129](https://github.com/caolan/async/issues/1129), [#1135](https://github.com/caolan/async/issues/1135), [#1138](https://github.com/caolan/async/issues/1138), [#1141](https://github.com/caolan/async/issues/1141), [#1153](https://github.com/caolan/async/issues/1153), [#1216](https://github.com/caolan/async/issues/1216), [#1217](https://github.com/caolan/async/issues/1217), [#1232](https://github.com/caolan/async/issues/1232), [#1233](https://github.com/caolan/async/issues/1233), [#1236](https://github.com/caolan/async/issues/1236), [#1238](https://github.com/caolan/async/issues/1238)) + +Thank you [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for taking the lead on version 2 of async. + +------------------------------------------ + +# v1.5.2 +- Allow using `"constructor"` as an argument in `memoize` ([#998](https://github.com/caolan/async/issues/998)) +- Give a better error messsage when `auto` dependency checking fails ([#994](https://github.com/caolan/async/issues/994)) +- Various doc updates ([#936](https://github.com/caolan/async/issues/936), [#956](https://github.com/caolan/async/issues/956), [#979](https://github.com/caolan/async/issues/979), [#1002](https://github.com/caolan/async/issues/1002)) + +# v1.5.1 +- Fix issue with `pause` in `queue` with concurrency enabled ([#946](https://github.com/caolan/async/issues/946)) +- `while` and `until` now pass the final result to callback ([#963](https://github.com/caolan/async/issues/963)) +- `auto` will properly handle concurrency when there is no callback ([#966](https://github.com/caolan/async/issues/966)) +- `auto` will no. properly stop execution when an error occurs ([#988](https://github.com/caolan/async/issues/988), [#993](https://github.com/caolan/async/issues/993)) +- Various doc fixes ([#971](https://github.com/caolan/async/issues/971), [#980](https://github.com/caolan/async/issues/980)) + +# v1.5.0 + +- Added `transform`, analogous to [`_.transform`](http://lodash.com/docs#transform) ([#892](https://github.com/caolan/async/issues/892)) +- `map` now returns an object when an object is passed in, rather than array with non-numeric keys. `map` will begin always returning an array with numeric indexes in the next major release. ([#873](https://github.com/caolan/async/issues/873)) +- `auto` now accepts an optional `concurrency` argument to limit the number o. running tasks ([#637](https://github.com/caolan/async/issues/637)) +- Added `queue#workersList()`, to retrieve the lis. of currently running tasks. ([#891](https://github.com/caolan/async/issues/891)) +- Various code simplifications ([#896](https://github.com/caolan/async/issues/896), [#904](https://github.com/caolan/async/issues/904)) +- Various doc fixes :scroll: ([#890](https://github.com/caolan/async/issues/890), [#894](https://github.com/caolan/async/issues/894), [#903](https://github.com/caolan/async/issues/903), [#905](https://github.com/caolan/async/issues/905), [#912](https://github.com/caolan/async/issues/912)) + +# v1.4.2 + +- Ensure coverage files don't get published on npm ([#879](https://github.com/caolan/async/issues/879)) + +# v1.4.1 + +- Add in overlooked `detectLimit` method ([#866](https://github.com/caolan/async/issues/866)) +- Removed unnecessary files from npm releases ([#861](https://github.com/caolan/async/issues/861)) +- Removed usage of a reserved word to prevent :boom: in older environments ([#870](https://github.com/caolan/async/issues/870)) + +# v1.4.0 + +- `asyncify` now supports promises ([#840](https://github.com/caolan/async/issues/840)) +- Added `Limit` versions of `filter` and `reject` ([#836](https://github.com/caolan/async/issues/836)) +- Add `Limit` versions of `detect`, `some` and `every` ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) +- `some`, `every` and `detect` now short circuit early ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829)) +- Improve detection of the global object ([#804](https://github.com/caolan/async/issues/804)), enabling use in WebWorkers +- `whilst` now called with arguments from iterator ([#823](https://github.com/caolan/async/issues/823)) +- `during` now gets called with arguments from iterator ([#824](https://github.com/caolan/async/issues/824)) +- Code simplifications and optimizations aplenty ([diff](https://github.com/caolan/async/compare/v1.3.0...v1.4.0)) + + +# v1.3.0 + +New Features: +- Added `constant` +- Added `asyncify`/`wrapSync` for making sync functions work with callbacks. ([#671](https://github.com/caolan/async/issues/671), [#806](https://github.com/caolan/async/issues/806)) +- Added `during` and `doDuring`, which are like `whilst` with an async truth test. ([#800](https://github.com/caolan/async/issues/800)) +- `retry` now accepts an `interval` parameter to specify a delay between retries. ([#793](https://github.com/caolan/async/issues/793)) +- `async` should work better in Web Workers due to better `root` detection ([#804](https://github.com/caolan/async/issues/804)) +- Callbacks are now optional in `whilst`, `doWhilst`, `until`, and `doUntil` ([#642](https://github.com/caolan/async/issues/642)) +- Various internal updates ([#786](https://github.com/caolan/async/issues/786), [#801](https://github.com/caolan/async/issues/801), [#802](https://github.com/caolan/async/issues/802), [#803](https://github.com/caolan/async/issues/803)) +- Various doc fixes ([#790](https://github.com/caolan/async/issues/790), [#794](https://github.com/caolan/async/issues/794)) + +Bug Fixes: +- `cargo` now exposes the `payload` size, and `cargo.payload` can be changed on the fly after the `cargo` is created. ([#740](https://github.com/caolan/async/issues/740), [#744](https://github.com/caolan/async/issues/744), [#783](https://github.com/caolan/async/issues/783)) + + +# v1.2.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) + + +# v1.2.0 + +New Features: + +- Added `timesLimit` ([#743](https://github.com/caolan/async/issues/743)) +- `concurrency` can be changed after initialization in `queue` by setting `q.concurrency`. The new concurrency will be reflected the next time a task is processed. ([#747](https://github.com/caolan/async/issues/747), [#772](https://github.com/caolan/async/issues/772)) + +Bug Fixes: + +- Fixed a regression in `each` and family with empty arrays that have additional properties. ([#775](https://github.com/caolan/async/issues/775), [#777](https://github.com/caolan/async/issues/777)) + + +# v1.1.1 + +Bug Fix: + +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782)) + + +# v1.1.0 + +New Features: + +- `cargo` now supports all of the same methods and event callbacks as `queue`. +- Added `ensureAsync` - A wrapper that ensures an async function calls its callback on a later tick. ([#769](https://github.com/caolan/async/issues/769)) +- Optimized `map`, `eachOf`, and `waterfall` families of functions +- Passing a `null` or `undefined` array to `map`, `each`, `parallel` and families will be treated as an empty array ([#667](https://github.com/caolan/async/issues/667)). +- The callback is now optional for the composed results of `compose` and `seq`. ([#618](https://github.com/caolan/async/issues/618)) +- Reduced file size by 4kb, (minified version by 1kb) +- Added code coverage through `nyc` and `coveralls` ([#768](https://github.com/caolan/async/issues/768)) + +Bug Fixes: + +- `forever` will no longer stack overflow with a synchronous iterator ([#622](https://github.com/caolan/async/issues/622)) +- `eachLimit` and other limit functions will stop iterating once an error occurs ([#754](https://github.com/caolan/async/issues/754)) +- Always pass `null` in callbacks when there is no error ([#439](https://github.com/caolan/async/issues/439)) +- Ensure proper conditions when calling `drain()` after pushing an empty data set to a queue ([#668](https://github.com/caolan/async/issues/668)) +- `each` and family will properly handle an empty array ([#578](https://github.com/caolan/async/issues/578)) +- `eachSeries` and family will finish if the underlying array is modified during execution ([#557](https://github.com/caolan/async/issues/557)) +- `queue` will throw if a non-function is passed to `q.push()` ([#593](https://github.com/caolan/async/issues/593)) +- Doc fixes ([#629](https://github.com/caolan/async/issues/629), [#766](https://github.com/caolan/async/issues/766)) + + +# v1.0.0 + +No known breaking changes, we are simply complying with semver from here on out. + +Changes: + +- Start using a changelog! +- Add `forEachOf` for iterating over Objects (or to iterate Arrays with indexes available) ([#168](https://github.com/caolan/async/issues/168) [#704](https://github.com/caolan/async/issues/704) [#321](https://github.com/caolan/async/issues/321)) +- Detect deadlocks in `auto` ([#663](https://github.com/caolan/async/issues/663)) +- Better support for require.js ([#527](https://github.com/caolan/async/issues/527)) +- Throw if queue created with concurrency `0` ([#714](https://github.com/caolan/async/issues/714)) +- Fix unneeded iteration in `queue.resume()` ([#758](https://github.com/caolan/async/issues/758)) +- Guard against timer mocking overriding `setImmediate` ([#609](https://github.com/caolan/async/issues/609) [#611](https://github.com/caolan/async/issues/611)) +- Miscellaneous doc fixes ([#542](https://github.com/caolan/async/issues/542) [#596](https://github.com/caolan/async/issues/596) [#615](https://github.com/caolan/async/issues/615) [#628](https://github.com/caolan/async/issues/628) [#631](https://github.com/caolan/async/issues/631) [#690](https://github.com/caolan/async/issues/690) [#729](https://github.com/caolan/async/issues/729)) +- Use single noop function internally ([#546](https://github.com/caolan/async/issues/546)) +- Optimize internal `_each`, `_map` and `_keys` functions. diff --git a/app/node_modules/async/LICENSE b/app/node_modules/async/LICENSE new file mode 100644 index 0000000..d807c05 --- /dev/null +++ b/app/node_modules/async/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010-2017 Caolan McMahon + +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/app/node_modules/async/README.md b/app/node_modules/async/README.md new file mode 100644 index 0000000..b48c7de --- /dev/null +++ b/app/node_modules/async/README.md @@ -0,0 +1,50 @@ +![Async Logo](https://raw.githubusercontent.com/caolan/async/master/logo/async-logo_readme.jpg) + +[![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async) +[![NPM version](https://img.shields.io/npm/v/async.svg)](https://www.npmjs.com/package/async) +[![Coverage Status](https://coveralls.io/repos/caolan/async/badge.svg?branch=master)](https://coveralls.io/r/caolan/async?branch=master) +[![Join the chat at https://gitter.im/caolan/async](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![libhive - Open source examples](https://www.libhive.com/providers/npm/packages/async/examples/badge.svg)](https://www.libhive.com/providers/npm/packages/async) +[![jsDelivr Hits](https://data.jsdelivr.com/v1/package/npm/async/badge?style=rounded)](https://www.jsdelivr.com/package/npm/async) + + +Async is a utility module which provides straight-forward, powerful functions for working with [asynchronous JavaScript](http://caolan.github.io/async/global.html). Although originally designed for use with [Node.js](https://nodejs.org/) and installable via `npm install --save async`, it can also be used directly in the browser. + +For Documentation, visit + +*For Async v1.5.x documentation, go [HERE](https://github.com/caolan/async/blob/v1.5.2/README.md)* + + +```javascript +// for use with Node-style callbacks... +var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; +var configs = {}; + +async.forEachOf(obj, (value, key, callback) => { + fs.readFile(__dirname + value, "utf8", (err, data) => { + if (err) return callback(err); + try { + configs[key] = JSON.parse(data); + } catch (e) { + return callback(e); + } + callback(); + }); +}, err => { + if (err) console.error(err.message); + // configs is now a map of JSON data + doSomethingWith(configs); +}); +``` + +```javascript +// ...or ES2017 async functions +async.mapLimit(urls, 5, async function(url) { + const response = await fetch(url) + return response.body +}, (err, results) => { + if (err) throw err + // results is now an array of the response bodies + console.log(results) +}) +``` diff --git a/app/node_modules/async/all.js b/app/node_modules/async/all.js new file mode 100644 index 0000000..d0565b0 --- /dev/null +++ b/app/node_modules/async/all.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _doParallel = require('./internal/doParallel'); + +var _doParallel2 = _interopRequireDefault(_doParallel); + +var _notId = require('./internal/notId'); + +var _notId2 = _interopRequireDefault(_notId); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @example + * + * async.every(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then every file exists + * }); + */ +exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/allLimit.js b/app/node_modules/async/allLimit.js new file mode 100644 index 0000000..a1a759a --- /dev/null +++ b/app/node_modules/async/allLimit.js @@ -0,0 +1,42 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _doParallelLimit = require('./internal/doParallelLimit'); + +var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); + +var _notId = require('./internal/notId'); + +var _notId2 = _interopRequireDefault(_notId); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + */ +exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/allSeries.js b/app/node_modules/async/allSeries.js new file mode 100644 index 0000000..23bfebb --- /dev/null +++ b/app/node_modules/async/allSeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _everyLimit = require('./everyLimit'); + +var _everyLimit2 = _interopRequireDefault(_everyLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + */ +exports.default = (0, _doLimit2.default)(_everyLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/any.js b/app/node_modules/async/any.js new file mode 100644 index 0000000..a8e70f7 --- /dev/null +++ b/app/node_modules/async/any.js @@ -0,0 +1,52 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _doParallel = require('./internal/doParallel'); + +var _doParallel2 = _interopRequireDefault(_doParallel); + +var _identity = require('lodash/identity'); + +var _identity2 = _interopRequireDefault(_identity); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @example + * + * async.some(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then at least one of the files exists + * }); + */ +exports.default = (0, _doParallel2.default)((0, _createTester2.default)(Boolean, _identity2.default)); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/anyLimit.js b/app/node_modules/async/anyLimit.js new file mode 100644 index 0000000..24ca3f4 --- /dev/null +++ b/app/node_modules/async/anyLimit.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _doParallelLimit = require('./internal/doParallelLimit'); + +var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); + +var _identity = require('lodash/identity'); + +var _identity2 = _interopRequireDefault(_identity); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + */ +exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(Boolean, _identity2.default)); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/anySeries.js b/app/node_modules/async/anySeries.js new file mode 100644 index 0000000..dc24ed2 --- /dev/null +++ b/app/node_modules/async/anySeries.js @@ -0,0 +1,38 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _someLimit = require('./someLimit'); + +var _someLimit2 = _interopRequireDefault(_someLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + */ +exports.default = (0, _doLimit2.default)(_someLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/apply.js b/app/node_modules/async/apply.js new file mode 100644 index 0000000..f590fa5 --- /dev/null +++ b/app/node_modules/async/apply.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (fn /*, ...args*/) { + var args = (0, _slice2.default)(arguments, 1); + return function () /*callArgs*/{ + var callArgs = (0, _slice2.default)(arguments); + return fn.apply(null, args.concat(callArgs)); + }; +}; + +var _slice = require('./internal/slice'); + +var _slice2 = _interopRequireDefault(_slice); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +; + +/** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/applyEach.js b/app/node_modules/async/applyEach.js new file mode 100644 index 0000000..06c0845 --- /dev/null +++ b/app/node_modules/async/applyEach.js @@ -0,0 +1,51 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _applyEach = require('./internal/applyEach'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _map = require('./map'); + +var _map2 = _interopRequireDefault(_map); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {Function} - If only the first argument, `fns`, is provided, it will + * return a function which lets you pass in the arguments as if it were a single + * function call. The signature is `(..args, callback)`. If invoked with any + * arguments, `callback` is required. + * @example + * + * async.applyEach([enableSearch, updateSchema], 'bucket', callback); + * + * // partial application example: + * async.each( + * buckets, + * async.applyEach([enableSearch, updateSchema]), + * callback + * ); + */ +exports.default = (0, _applyEach2.default)(_map2.default); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/applyEachSeries.js b/app/node_modules/async/applyEachSeries.js new file mode 100644 index 0000000..ad80280 --- /dev/null +++ b/app/node_modules/async/applyEachSeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _applyEach = require('./internal/applyEach'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _mapSeries = require('./mapSeries'); + +var _mapSeries2 = _interopRequireDefault(_mapSeries); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {Function} - If only the first argument is provided, it will return + * a function which lets you pass in the arguments as if it were a single + * function call. + */ +exports.default = (0, _applyEach2.default)(_mapSeries2.default); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/asyncify.js b/app/node_modules/async/asyncify.js new file mode 100644 index 0000000..5e3fc91 --- /dev/null +++ b/app/node_modules/async/asyncify.js @@ -0,0 +1,110 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncify; + +var _isObject = require('lodash/isObject'); + +var _isObject2 = _interopRequireDefault(_isObject); + +var _initialParams = require('./internal/initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _setImmediate = require('./internal/setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + return (0, _initialParams2.default)(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if ((0, _isObject2.default)(result) && typeof result.then === 'function') { + result.then(function (value) { + invokeCallback(callback, null, value); + }, function (err) { + invokeCallback(callback, err.message ? err : new Error(err)); + }); + } else { + callback(null, result); + } + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (e) { + (0, _setImmediate2.default)(rethrow, e); + } +} + +function rethrow(error) { + throw error; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/auto.js b/app/node_modules/async/auto.js new file mode 100644 index 0000000..26c1d56 --- /dev/null +++ b/app/node_modules/async/auto.js @@ -0,0 +1,289 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (tasks, concurrency, callback) { + if (typeof concurrency === 'function') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = (0, _once2.default)(callback || _noop2.default); + var keys = (0, _keys2.default)(tasks); + var numTasks = keys.length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + (0, _baseForOwn2.default)(tasks, function (task, key) { + if (!(0, _isArray2.default)(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + (0, _arrayEach2.default)(dependencies, function (dependencyName) { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', ')); + } + addListener(dependencyName, function () { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(function () { + runTask(key, task); + }); + } + + function processQueue() { + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while (readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + (0, _arrayEach2.default)(taskListeners, function (fn) { + fn(); + }); + processQueue(); + } + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = (0, _onlyOnce2.default)(function (err, result) { + runningTasks--; + if (arguments.length > 2) { + result = (0, _slice2.default)(arguments, 1); + } + if (err) { + var safeResults = {}; + (0, _baseForOwn2.default)(results, function (val, rkey) { + safeResults[rkey] = val; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = (0, _wrapAsync2.default)(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + (0, _arrayEach2.default)(getDependents(currentTask), function (dependent) { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error('async.auto cannot execute tasks due to a recursive dependency'); + } + } + + function getDependents(taskName) { + var result = []; + (0, _baseForOwn2.default)(tasks, function (task, key) { + if ((0, _isArray2.default)(task) && (0, _baseIndexOf2.default)(task, taskName, 0) >= 0) { + result.push(key); + } + }); + return result; + } +}; + +var _arrayEach = require('lodash/_arrayEach'); + +var _arrayEach2 = _interopRequireDefault(_arrayEach); + +var _baseForOwn = require('lodash/_baseForOwn'); + +var _baseForOwn2 = _interopRequireDefault(_baseForOwn); + +var _baseIndexOf = require('lodash/_baseIndexOf'); + +var _baseIndexOf2 = _interopRequireDefault(_baseIndexOf); + +var _isArray = require('lodash/isArray'); + +var _isArray2 = _interopRequireDefault(_isArray); + +var _keys = require('lodash/keys'); + +var _keys2 = _interopRequireDefault(_keys); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _slice = require('./internal/slice'); + +var _slice2 = _interopRequireDefault(_slice); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports['default']; + +/** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns undefined + * @example + * + * async.auto({ + * // this function will just be passed a callback + * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), + * showData: ['readData', function(results, cb) { + * // results.readData is the file's contents + * // ... + * }] + * }, callback); + * + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * console.log('in write_file', JSON.stringify(results)); + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * console.log('in email_link', JSON.stringify(results)); + * // once the file is written let's email a link to it... + * // results.write_file contains the filename returned by write_file. + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * console.log('err = ', err); + * console.log('results = ', results); + * }); + */ \ No newline at end of file diff --git a/app/node_modules/async/autoInject.js b/app/node_modules/async/autoInject.js new file mode 100644 index 0000000..bfbe7e8 --- /dev/null +++ b/app/node_modules/async/autoInject.js @@ -0,0 +1,170 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = autoInject; + +var _auto = require('./auto'); + +var _auto2 = _interopRequireDefault(_auto); + +var _baseForOwn = require('lodash/_baseForOwn'); + +var _baseForOwn2 = _interopRequireDefault(_baseForOwn); + +var _arrayMap = require('lodash/_arrayMap'); + +var _arrayMap2 = _interopRequireDefault(_arrayMap); + +var _isArray = require('lodash/isArray'); + +var _isArray2 = _interopRequireDefault(_isArray); + +var _trim = require('lodash/trim'); + +var _trim2 = _interopRequireDefault(_trim); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m; +var FN_ARG_SPLIT = /,/; +var FN_ARG = /(=.+)?(\s*)$/; +var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; + +function parseParams(func) { + func = func.toString().replace(STRIP_COMMENTS, ''); + func = func.match(FN_ARGS)[2].replace(' ', ''); + func = func ? func.split(FN_ARG_SPLIT) : []; + func = func.map(function (arg) { + return (0, _trim2.default)(arg.replace(FN_ARG, '')); + }); + return func; +} + +/** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ +function autoInject(tasks, callback) { + var newTasks = {}; + + (0, _baseForOwn2.default)(tasks, function (taskFn, key) { + var params; + var fnIsAsync = (0, _wrapAsync.isAsync)(taskFn); + var hasNoDeps = !fnIsAsync && taskFn.length === 1 || fnIsAsync && taskFn.length === 0; + + if ((0, _isArray2.default)(taskFn)) { + params = taskFn.slice(0, -1); + taskFn = taskFn[taskFn.length - 1]; + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = (0, _arrayMap2.default)(params, function (name) { + return results[name]; + }); + newArgs.push(taskCb); + (0, _wrapAsync2.default)(taskFn).apply(null, newArgs); + } + }); + + (0, _auto2.default)(newTasks, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/bower.json b/app/node_modules/async/bower.json new file mode 100644 index 0000000..7dbeb14 --- /dev/null +++ b/app/node_modules/async/bower.json @@ -0,0 +1,17 @@ +{ + "name": "async", + "main": "dist/async.js", + "ignore": [ + "bower_components", + "lib", + "mocha_test", + "node_modules", + "perf", + "support", + "**/.*", + "*.config.js", + "*.json", + "index.js", + "Makefile" + ] +} diff --git a/app/node_modules/async/cargo.js b/app/node_modules/async/cargo.js new file mode 100644 index 0000000..c7e59c7 --- /dev/null +++ b/app/node_modules/async/cargo.js @@ -0,0 +1,94 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = cargo; + +var _queue = require('./internal/queue'); + +var _queue2 = _interopRequireDefault(_queue); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A cargo of tasks for the worker function to complete. Cargo inherits all of + * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}. + * @typedef {Object} CargoObject + * @memberOf module:ControlFlow + * @property {Function} length - A function returning the number of items + * waiting to be processed. Invoke like `cargo.length()`. + * @property {number} payload - An `integer` for determining how many tasks + * should be process per round. This property can be changed after a `cargo` is + * created to alter the payload on-the-fly. + * @property {Function} push - Adds `task` to the `queue`. The callback is + * called once the `worker` has finished processing the task. Instead of a + * single task, an array of `tasks` can be submitted. The respective callback is + * used for every task in the list. Invoke like `cargo.push(task, [callback])`. + * @property {Function} saturated - A callback that is called when the + * `queue.length()` hits the concurrency and further tasks will be queued. + * @property {Function} empty - A callback that is called when the last item + * from the `queue` is given to a `worker`. + * @property {Function} drain - A callback that is called when the last item + * from the `queue` has returned from the `worker`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke like `cargo.idle()`. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke like `cargo.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke like `cargo.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`. + */ + +/** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i async.dir(hello, 'world'); + * {hello: 'world'} + */ +exports.default = (0, _consoleFunc2.default)('dir'); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/dist/async.js b/app/node_modules/async/dist/async.js new file mode 100644 index 0000000..ddb1af7 --- /dev/null +++ b/app/node_modules/async/dist/async.js @@ -0,0 +1,5595 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.async = global.async || {}))); +}(this, (function (exports) { 'use strict'; + +function slice(arrayLike, start) { + start = start|0; + var newLen = Math.max(arrayLike.length - start, 0); + var newArr = Array(newLen); + for(var idx = 0; idx < newLen; idx++) { + newArr[idx] = arrayLike[start + idx]; + } + return newArr; +} + +/** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ +var apply = function(fn/*, ...args*/) { + var args = slice(arguments, 1); + return function(/*callArgs*/) { + var callArgs = slice(arguments); + return fn.apply(null, args.concat(callArgs)); + }; +}; + +var initialParams = function (fn) { + return function (/*...args, callback*/) { + var args = slice(arguments); + var callback = args.pop(); + fn.call(this, args, callback); + }; +}; + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + +function fallback(fn) { + setTimeout(fn, 0); +} + +function wrap(defer) { + return function (fn/*, ...args*/) { + var args = slice(arguments, 1); + defer(function () { + fn.apply(null, args); + }); + }; +} + +var _defer; + +if (hasSetImmediate) { + _defer = setImmediate; +} else if (hasNextTick) { + _defer = process.nextTick; +} else { + _defer = fallback; +} + +var setImmediate$1 = wrap(_defer); + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (isObject(result) && typeof result.then === 'function') { + result.then(function(value) { + invokeCallback(callback, null, value); + }, function(err) { + invokeCallback(callback, err.message ? err : new Error(err)); + }); + } else { + callback(null, result); + } + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (e) { + setImmediate$1(rethrow, e); + } +} + +function rethrow(error) { + throw error; +} + +var supportsSymbol = typeof Symbol === 'function'; + +function isAsync(fn) { + return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; +} + +function wrapAsync(asyncFn) { + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; +} + +function applyEach$1(eachfn) { + return function(fns/*, ...args*/) { + var args = slice(arguments, 1); + var go = initialParams(function(args, callback) { + var that = this; + return eachfn(fns, function (fn, cb) { + wrapAsync(fn).apply(that, args.concat(cb)); + }, callback); + }); + if (args.length) { + return go.apply(this, args); + } + else { + return go; + } + }; +} + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Built-in value references. */ +var Symbol$1 = root.Symbol; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** Built-in value references. */ +var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; + +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag$1), + tag = value[symToStringTag$1]; + + try { + value[symToStringTag$1] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag$1] = tag; + } else { + delete value[symToStringTag$1]; + } + } + return result; +} + +/** Used for built-in method references. */ +var objectProto$1 = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString$1 = objectProto$1.toString; + +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString$1.call(value); +} + +/** `Object#toString` result references. */ +var nullTag = '[object Null]'; +var undefinedTag = '[object Undefined]'; + +/** Built-in value references. */ +var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); +} + +/** `Object#toString` result references. */ +var asyncTag = '[object AsyncFunction]'; +var funcTag = '[object Function]'; +var genTag = '[object GeneratorFunction]'; +var proxyTag = '[object Proxy]'; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +// A temporary value used to identify if the loop should be broken. +// See #1064, #1293 +var breakLoop = {}; + +/** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ +function noop() { + // No operation performed. +} + +function once(fn) { + return function () { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; +} + +var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; + +var getIterator = function (coll) { + return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); +}; + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]'; + +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; +} + +/** Used for built-in method references. */ +var objectProto$3 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$2 = objectProto$3.hasOwnProperty; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); +}; + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} + +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER$1 = 9007199254740991; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER$1 : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +/** `Object#toString` result references. */ +var argsTag$1 = '[object Arguments]'; +var arrayTag = '[object Array]'; +var boolTag = '[object Boolean]'; +var dateTag = '[object Date]'; +var errorTag = '[object Error]'; +var funcTag$1 = '[object Function]'; +var mapTag = '[object Map]'; +var numberTag = '[object Number]'; +var objectTag = '[object Object]'; +var regexpTag = '[object RegExp]'; +var setTag = '[object Set]'; +var stringTag = '[object String]'; +var weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]'; +var dataViewTag = '[object DataView]'; +var float32Tag = '[object Float32Array]'; +var float64Tag = '[object Float64Array]'; +var int8Tag = '[object Int8Array]'; +var int16Tag = '[object Int16Array]'; +var int32Tag = '[object Int32Array]'; +var uint8Tag = '[object Uint8Array]'; +var uint8ClampedTag = '[object Uint8ClampedArray]'; +var uint16Tag = '[object Uint16Array]'; +var uint32Tag = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = +typedArrayTags[mapTag] = typedArrayTags[numberTag] = +typedArrayTags[objectTag] = typedArrayTags[regexpTag] = +typedArrayTags[setTag] = typedArrayTags[stringTag] = +typedArrayTags[weakMapTag] = false; + +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; +} + +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} + +/** Detect free variable `exports`. */ +var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; + +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports$1 && freeGlobal.process; + +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} +}()); + +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + +/** Used for built-in method references. */ +var objectProto$2 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$1 = objectProto$2.hasOwnProperty; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty$1.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; +} + +/** Used for built-in method references. */ +var objectProto$5 = Object.prototype; + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; + + return value === proto; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object); + +/** Used for built-in method references. */ +var objectProto$4 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$3 = objectProto$4.hasOwnProperty; + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty$3.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } +} + +function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } +} + +function createObjectIterator(obj) { + var okeys = keys(obj); + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + return i < len ? {value: obj[key], key: key} : null; + }; +} + +function iterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } + + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); +} + +function onlyOnce(fn) { + return function() { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; +} + +function _eachOfLimit(limit) { + return function (obj, iteratee, callback) { + callback = once(callback || noop); + if (limit <= 0 || !obj) { + return callback(null); + } + var nextElem = iterator(obj); + var done = false; + var running = 0; + + function iterateeCallback(err, value) { + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (value === breakLoop || (done && running <= 0)) { + done = true; + return callback(null); + } + else { + replenish(); + } + } + + function replenish () { + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + } + + replenish(); + }; +} + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ +function eachOfLimit(coll, limit, iteratee, callback) { + _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); +} + +function doLimit(fn, limit) { + return function (iterable, iteratee, callback) { + return fn(iterable, limit, iteratee, callback); + }; +} + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback || noop); + var index = 0, + completed = 0, + length = coll.length; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +var eachOfGeneric = doLimit(eachOfLimit, Infinity); + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ +var eachOf = function(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + eachOfImplementation(coll, wrapAsync(iteratee), callback); +}; + +function doParallel(fn) { + return function (obj, iteratee, callback) { + return fn(eachOf, obj, wrapAsync(iteratee), callback); + }; +} + +function _asyncMap(eachfn, arr, iteratee, callback) { + callback = callback || noop; + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); + + eachfn(arr, function (value, _, callback) { + var index = counter++; + _iteratee(value, function (err, v) { + results[index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); +} + +/** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callback + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @example + * + * async.map(['file1','file2','file3'], fs.stat, function(err, results) { + * // results is now an array of stats for each file + * }); + */ +var map = doParallel(_asyncMap); + +/** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {Function} - If only the first argument, `fns`, is provided, it will + * return a function which lets you pass in the arguments as if it were a single + * function call. The signature is `(..args, callback)`. If invoked with any + * arguments, `callback` is required. + * @example + * + * async.applyEach([enableSearch, updateSchema], 'bucket', callback); + * + * // partial application example: + * async.each( + * buckets, + * async.applyEach([enableSearch, updateSchema]), + * callback + * ); + */ +var applyEach = applyEach$1(map); + +function doParallelLimit(fn) { + return function (obj, limit, iteratee, callback) { + return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback); + }; +} + +/** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + */ +var mapLimit = doParallelLimit(_asyncMap); + +/** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + */ +var mapSeries = doLimit(mapLimit, 1); + +/** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {Function} - If only the first argument is provided, it will return + * a function which lets you pass in the arguments as if it were a single + * function call. + */ +var applyEachSeries = applyEach$1(mapSeries); + +/** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ +function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; +} + +/** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; +} + +/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseFor = createBaseFor(); + +/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ +function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); +} + +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} + +/** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); +} + +/** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns undefined + * @example + * + * async.auto({ + * // this function will just be passed a callback + * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), + * showData: ['readData', function(results, cb) { + * // results.readData is the file's contents + * // ... + * }] + * }, callback); + * + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * console.log('in write_file', JSON.stringify(results)); + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * console.log('in email_link', JSON.stringify(results)); + * // once the file is written let's email a link to it... + * // results.write_file contains the filename returned by write_file. + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * console.log('err = ', err); + * console.log('results = ', results); + * }); + */ +var auto = function (tasks, concurrency, callback) { + if (typeof concurrency === 'function') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || noop); + var keys$$1 = keys(tasks); + var numTasks = keys$$1.length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } + + var results = {}; + var runningTasks = 0; + var hasError = false; + + var listeners = Object.create(null); + + var readyTasks = []; + + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; + + baseForOwn(tasks, function (task, key) { + if (!isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } + + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; + + arrayEach(dependencies, function (dependencyName) { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, function () { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); + + checkForDeadlocks(); + processQueue(); + + function enqueueTask(key, task) { + readyTasks.push(function () { + runTask(key, task); + }); + } + + function processQueue() { + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } + + } + + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } + + taskListeners.push(fn); + } + + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + arrayEach(taskListeners, function (fn) { + fn(); + }); + processQueue(); + } + + + function runTask(key, task) { + if (hasError) return; + + var taskCallback = onlyOnce(function(err, result) { + runningTasks--; + if (arguments.length > 2) { + result = slice(arguments, 1); + } + if (err) { + var safeResults = {}; + baseForOwn(results, function(val, rkey) { + safeResults[rkey] = val; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); + + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } + + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + arrayEach(getDependents(currentTask), function (dependent) { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } + + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } + + function getDependents(taskName) { + var result = []; + baseForOwn(tasks, function (task, key) { + if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) { + result.push(key); + } + }); + return result; + } +}; + +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); +} + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined; +var symbolToString = symbolProto ? symbolProto.toString : undefined; + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +/** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; +} + +/** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ +function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); +} + +/** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ +function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; +} + +/** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ +function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; +} + +/** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function asciiToArray(string) { + return string.split(''); +} + +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff'; +var rsComboMarksRange = '\\u0300-\\u036f'; +var reComboHalfMarksRange = '\\ufe20-\\ufe2f'; +var rsComboSymbolsRange = '\\u20d0-\\u20ff'; +var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; +var rsVarRange = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsZWJ = '\\u200d'; + +/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ +var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + +/** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ +function hasUnicode(string) { + return reHasUnicode.test(string); +} + +/** Used to compose unicode character classes. */ +var rsAstralRange$1 = '\\ud800-\\udfff'; +var rsComboMarksRange$1 = '\\u0300-\\u036f'; +var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f'; +var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff'; +var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1; +var rsVarRange$1 = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsAstral = '[' + rsAstralRange$1 + ']'; +var rsCombo = '[' + rsComboRange$1 + ']'; +var rsFitz = '\\ud83c[\\udffb-\\udfff]'; +var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')'; +var rsNonAstral = '[^' + rsAstralRange$1 + ']'; +var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}'; +var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]'; +var rsZWJ$1 = '\\u200d'; + +/** Used to compose unicode regexes. */ +var reOptMod = rsModifier + '?'; +var rsOptVar = '[' + rsVarRange$1 + ']?'; +var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*'; +var rsSeq = rsOptVar + reOptMod + rsOptJoin; +var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + +/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ +var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + +/** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function unicodeToArray(string) { + return string.match(reUnicode) || []; +} + +/** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); +} + +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ +function toString(value) { + return value == null ? '' : baseToString(value); +} + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** + * Removes leading and trailing whitespace or specified characters from `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to trim. + * @param {string} [chars=whitespace] The characters to trim. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the trimmed string. + * @example + * + * _.trim(' abc '); + * // => 'abc' + * + * _.trim('-_-abc-_-', '_-'); + * // => 'abc' + * + * _.map([' foo ', ' bar '], _.trim); + * // => ['foo', 'bar'] + */ +function trim(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined)) { + return string.replace(reTrim, ''); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), + chrSymbols = stringToArray(chars), + start = charsStartIndex(strSymbols, chrSymbols), + end = charsEndIndex(strSymbols, chrSymbols) + 1; + + return castSlice(strSymbols, start, end).join(''); +} + +var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m; +var FN_ARG_SPLIT = /,/; +var FN_ARG = /(=.+)?(\s*)$/; +var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; + +function parseParams(func) { + func = func.toString().replace(STRIP_COMMENTS, ''); + func = func.match(FN_ARGS)[2].replace(' ', ''); + func = func ? func.split(FN_ARG_SPLIT) : []; + func = func.map(function (arg){ + return trim(arg.replace(FN_ARG, '')); + }); + return func; +} + +/** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ +function autoInject(tasks, callback) { + var newTasks = {}; + + baseForOwn(tasks, function (taskFn, key) { + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); + + if (isArray(taskFn)) { + params = taskFn.slice(0, -1); + taskFn = taskFn[taskFn.length - 1]; + + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } + + // remove callback param + if (!fnIsAsync) params.pop(); + + newTasks[key] = params.concat(newTask); + } + + function newTask(results, taskCb) { + var newArgs = arrayMap(params, function (name) { + return results[name]; + }); + newArgs.push(taskCb); + wrapAsync(taskFn).apply(null, newArgs); + } + }); + + auto(newTasks, callback); +} + +// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation +// used for queues. This implementation assumes that the node provided by the user can be modified +// to adjust the next and last properties. We implement only the minimal functionality +// for queue support. +function DLL() { + this.head = this.tail = null; + this.length = 0; +} + +function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; +} + +DLL.prototype.removeLink = function(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; +}; + +DLL.prototype.empty = function () { + while(this.head) this.shift(); + return this; +}; + +DLL.prototype.insertAfter = function(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; +}; + +DLL.prototype.insertBefore = function(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; +}; + +DLL.prototype.unshift = function(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); +}; + +DLL.prototype.push = function(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); +}; + +DLL.prototype.shift = function() { + return this.head && this.removeLink(this.head); +}; + +DLL.prototype.pop = function() { + return this.tail && this.removeLink(this.tail); +}; + +DLL.prototype.toArray = function () { + var arr = Array(this.length); + var curr = this.head; + for(var idx = 0; idx < this.length; idx++) { + arr[idx] = curr.data; + curr = curr.next; + } + return arr; +}; + +DLL.prototype.remove = function (testFn) { + var curr = this.head; + while(!!curr) { + var next = curr.next; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; +}; + +function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + + var processingScheduled = false; + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!isArray(data)) { + data = [data]; + } + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return setImmediate$1(function() { + q.drain(); + }); + } + + for (var i = 0, l = data.length; i < l; i++) { + var item = { + data: data[i], + callback: callback || noop + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + } + + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(function() { + processingScheduled = false; + q.process(); + }); + } + } + + function _next(tasks) { + return function(err){ + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = baseIndexOf(workersList, task, 0); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback.apply(task, arguments); + + if (err != null) { + q.error(err, task.data); + } + } + + if (numRunning <= (q.concurrency - q.buffer) ) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + q.process(); + }; + } + + var isProcessing = false; + var q = { + _tasks: new DLL(), + concurrency: concurrency, + payload: payload, + saturated: noop, + unsaturated:noop, + buffer: concurrency / 4, + empty: noop, + drain: noop, + error: noop, + started: false, + paused: false, + push: function (data, callback) { + _insert(data, false, callback); + }, + kill: function () { + q.drain = noop; + q._tasks.empty(); + }, + unshift: function (data, callback) { + _insert(data, true, callback); + }, + remove: function (testFn) { + q._tasks.remove(testFn); + }, + process: function () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + q.empty(); + } + + if (numRunning === q.concurrency) { + q.saturated(); + } + + var cb = onlyOnce(_next(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length: function () { + return q._tasks.length; + }, + running: function () { + return numRunning; + }, + workersList: function () { + return workersList; + }, + idle: function() { + return q._tasks.length + numRunning === 0; + }, + pause: function () { + q.paused = true; + }, + resume: function () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + return q; +} + +/** + * A cargo of tasks for the worker function to complete. Cargo inherits all of + * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}. + * @typedef {Object} CargoObject + * @memberOf module:ControlFlow + * @property {Function} length - A function returning the number of items + * waiting to be processed. Invoke like `cargo.length()`. + * @property {number} payload - An `integer` for determining how many tasks + * should be process per round. This property can be changed after a `cargo` is + * created to alter the payload on-the-fly. + * @property {Function} push - Adds `task` to the `queue`. The callback is + * called once the `worker` has finished processing the task. Instead of a + * single task, an array of `tasks` can be submitted. The respective callback is + * used for every task in the list. Invoke like `cargo.push(task, [callback])`. + * @property {Function} saturated - A callback that is called when the + * `queue.length()` hits the concurrency and further tasks will be queued. + * @property {Function} empty - A callback that is called when the last item + * from the `queue` is given to a `worker`. + * @property {Function} drain - A callback that is called when the last item + * from the `queue` has returned from the `worker`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke like `cargo.idle()`. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke like `cargo.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke like `cargo.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`. + */ + +/** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i true + */ +function identity(value) { + return value; +} + +function _createTester(check, getResult) { + return function(eachfn, arr, iteratee, cb) { + cb = cb || noop; + var testPassed = false; + var testResult; + eachfn(arr, function(value, _, callback) { + iteratee(value, function(err, result) { + if (err) { + callback(err); + } else if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + callback(null, breakLoop); + } else { + callback(); + } + }); + }, function(err) { + if (err) { + cb(err); + } else { + cb(null, testPassed ? testResult : getResult(false)); + } + }); + }; +} + +function _findGetResult(v, x) { + return x; +} + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @example + * + * async.detect(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // result now equals the first file in the list that exists + * }); + */ +var detect = doParallel(_createTester(identity, _findGetResult)); + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + */ +var detectLimit = doParallelLimit(_createTester(identity, _findGetResult)); + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + */ +var detectSeries = doLimit(detectLimit, 1); + +function consoleFunc(name) { + return function (fn/*, ...args*/) { + var args = slice(arguments, 1); + args.push(function (err/*, ...args*/) { + var args = slice(arguments, 1); + if (typeof console === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } else if (console[name]) { + arrayEach(args, function (x) { + console[name](x); + }); + } + } + }); + wrapAsync(fn).apply(null, args); + }; +} + +/** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ +var dir = consoleFunc('dir'); + +/** + * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in + * the order of operations, the arguments `test` and `fn` are switched. + * + * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function. + * @name doDuring + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.during]{@link module:ControlFlow.during} + * @category Control Flow + * @param {AsyncFunction} fn - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `fn`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `fn`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `fn` has stopped. `callback` + * will be passed an error if one occurred, otherwise `null`. + */ +function doDuring(fn, test, callback) { + callback = onlyOnce(callback || noop); + var _fn = wrapAsync(fn); + var _test = wrapAsync(test); + + function next(err/*, ...args*/) { + if (err) return callback(err); + var args = slice(arguments, 1); + args.push(check); + _test.apply(this, args); + } + + function check(err, truth) { + if (err) return callback(err); + if (!truth) return callback(null); + _fn(next); + } + + check(null, true); + +} + +/** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {Function} test - synchronous truth test to perform after each + * execution of `iteratee`. Invoked with any non-error callback results of + * `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + */ +function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback || noop); + var _iteratee = wrapAsync(iteratee); + var next = function(err/*, ...args*/) { + if (err) return callback(err); + var args = slice(arguments, 1); + if (test.apply(this, args)) return _iteratee(next); + callback.apply(null, [null].concat(args)); + }; + _iteratee(next); +} + +/** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} test - synchronous truth test to perform after each + * execution of `iteratee`. Invoked with any non-error callback results of + * `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + */ +function doUntil(iteratee, test, callback) { + doWhilst(iteratee, function() { + return !test.apply(this, arguments); + }, callback); +} + +/** + * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that + * is passed a callback in the form of `function (err, truth)`. If error is + * passed to `test` or `fn`, the main callback is immediately called with the + * value of the error. + * + * @name during + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `fn`. Invoked with (callback). + * @param {AsyncFunction} fn - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `fn` has stopped. `callback` + * will be passed an error, if one occurred, otherwise `null`. + * @example + * + * var count = 0; + * + * async.during( + * function (callback) { + * return callback(null, count < 5); + * }, + * function (callback) { + * count++; + * setTimeout(callback, 1000); + * }, + * function (err) { + * // 5 seconds have passed + * } + * ); + */ +function during(test, fn, callback) { + callback = onlyOnce(callback || noop); + var _fn = wrapAsync(fn); + var _test = wrapAsync(test); + + function next(err) { + if (err) return callback(err); + _test(check); + } + + function check(err, truth) { + if (err) return callback(err); + if (!truth) return callback(null); + _fn(next); + } + + _test(check); +} + +function _withoutIndex(iteratee) { + return function (value, index, callback) { + return iteratee(value, callback); + }; +} + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @example + * + * // assuming openFiles is an array of file names and saveFile is a function + * // to save the modified contents of that file: + * + * async.each(openFiles, saveFile, function(err){ + * // if any of the saves produced an error, err would equal that error + * }); + * + * // assuming openFiles is an array of file names + * async.each(openFiles, function(file, callback) { + * + * // Perform operation on file here. + * console.log('Processing file ' + file); + * + * if( file.length > 32 ) { + * console.log('This file name is too long'); + * callback('File name too long'); + * } else { + * // Do work to process file here + * console.log('File processed'); + * callback(); + * } + * }, function(err) { + * // if any of the file processing produced an error, err would equal that error + * if( err ) { + * // One of the iterations produced an error. + * // All processing will now stop. + * console.log('A file failed to process'); + * } else { + * console.log('All files have been processed successfully'); + * } + * }); + */ +function eachLimit(coll, iteratee, callback) { + eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback); +} + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ +function eachLimit$1(coll, limit, iteratee, callback) { + _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); +} + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ +var eachSeries = doLimit(eachLimit$1, 1); + +/** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ +function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return initialParams(function (args, callback) { + var sync = true; + args.push(function () { + var innerArgs = arguments; + if (sync) { + setImmediate$1(function () { + callback.apply(null, innerArgs); + }); + } else { + callback.apply(null, innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }); +} + +function notId(v) { + return !v; +} + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @example + * + * async.every(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then every file exists + * }); + */ +var every = doParallel(_createTester(notId, notId)); + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + */ +var everyLimit = doParallelLimit(_createTester(notId, notId)); + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + */ +var everySeries = doLimit(everyLimit, 1); + +/** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; +} + +function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, function (x, index, callback) { + iteratee(x, function (err, v) { + truthValues[index] = !!v; + callback(err); + }); + }, function (err) { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); +} + +function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, function (x, index, callback) { + iteratee(x, function (err, v) { + if (err) { + callback(err); + } else { + if (v) { + results.push({index: index, value: x}); + } + callback(); + } + }); + }, function (err) { + if (err) { + callback(err); + } else { + callback(null, arrayMap(results.sort(function (a, b) { + return a.index - b.index; + }), baseProperty('value'))); + } + }); +} + +function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + filter(eachfn, coll, wrapAsync(iteratee), callback || noop); +} + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @example + * + * async.filter(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of the existing files + * }); + */ +var filter = doParallel(_filter); + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + */ +var filterLimit = doParallelLimit(_filter); + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + */ +var filterSeries = doLimit(filterLimit, 1); + +/** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ +function forever(fn, errback) { + var done = onlyOnce(errback || noop); + var task = wrapAsync(ensureAsync(fn)); + + function next(err) { + if (err) return done(err); + task(next); + } + next(); +} + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + */ +var groupByLimit = function(coll, limit, iteratee, callback) { + callback = callback || noop; + var _iteratee = wrapAsync(iteratee); + mapLimit(coll, limit, function(val, callback) { + _iteratee(val, function(err, key) { + if (err) return callback(err); + return callback(null, {key: key, val: val}); + }); + }, function(err, mapResults) { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var hasOwnProperty = Object.prototype.hasOwnProperty; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var key = mapResults[i].key; + var val = mapResults[i].val; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); +}; + +/** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @example + * + * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { + * db.findById(userId, function(err, user) { + * if (err) return callback(err); + * return callback(null, user.age); + * }); + * }, function(err, result) { + * // result is object containing the userIds grouped by age + * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; + * }); + */ +var groupBy = doLimit(groupByLimit, Infinity); + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + */ +var groupBySeries = doLimit(groupByLimit, 1); + +/** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ +var log = consoleFunc('log'); + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + */ +function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback || noop); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + eachOfLimit(obj, limit, function(val, key, next) { + _iteratee(val, key, function (err, result) { + if (err) return next(err); + newObj[key] = result; + next(); + }); + }, function (err) { + callback(err, newObj); + }); +} + +/** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @example + * + * async.mapValues({ + * f1: 'file1', + * f2: 'file2', + * f3: 'file3' + * }, function (file, key, callback) { + * fs.stat(file, callback); + * }, function(err, result) { + * // result is now a map of stats for each file, e.g. + * // { + * // f1: [stats for file1], + * // f2: [stats for file2], + * // f3: [stats for file3] + * // } + * }); + */ + +var mapValues = doLimit(mapValuesLimit, Infinity); + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + */ +var mapValuesSeries = doLimit(mapValuesLimit, 1); + +function has(obj, key) { + return key in obj; +} + +/** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ +function memoize(fn, hasher) { + var memo = Object.create(null); + var queues = Object.create(null); + hasher = hasher || identity; + var _fn = wrapAsync(fn); + var memoized = initialParams(function memoized(args, callback) { + var key = hasher.apply(null, args); + if (has(memo, key)) { + setImmediate$1(function() { + callback.apply(null, memo[key]); + }); + } else if (has(queues, key)) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn.apply(null, args.concat(function(/*args*/) { + var args = slice(arguments); + memo[key] = args; + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(null, args); + } + })); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; +} + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTicl`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +var _defer$1; + +if (hasNextTick) { + _defer$1 = process.nextTick; +} else if (hasSetImmediate) { + _defer$1 = setImmediate; +} else { + _defer$1 = fallback; +} + +var nextTick = wrap(_defer$1); + +function _parallel(eachfn, tasks, callback) { + callback = callback || noop; + var results = isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, function (task, key, callback) { + wrapAsync(task)(function (err, result) { + if (arguments.length > 2) { + result = slice(arguments, 1); + } + results[key] = result; + callback(err); + }); + }, function (err) { + callback(err, results); + }); +} + +/** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * + * @example + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // optional callback + * function(err, results) { + * // the results array will equal ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equals to: {one: 1, two: 2} + * }); + */ +function parallelLimit(tasks, callback) { + _parallel(eachOf, tasks, callback); +} + +/** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + */ +function parallelLimit$1(tasks, limit, callback) { + _parallel(_eachOfLimit(limit), tasks, callback); +} + +/** + * A queue of tasks for the worker function to complete. + * @typedef {Object} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {Function} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {Function} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a callback that is called when the number of + * running workers hits the `concurrency` limit, and further tasks will be + * queued. + * @property {Function} unsaturated - a callback that is called when the number + * of running workers is less than the `concurrency` & `buffer` limits, and + * further tasks will not be queued. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a callback that is called when the last item + * from the `queue` is given to a `worker`. + * @property {Function} drain - a callback that is called when the last item + * from the `queue` has returned from the `worker`. + * @property {Function} error - a callback that is called when a task errors. + * Has the signature `function(error, task)`. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + */ + +/** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain = function() { + * console.log('all items have been processed'); + * }; + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * q.push({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ +var queue$1 = function (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue(function (items, cb) { + _worker(items[0], cb); + }, concurrency, 1); +}; + +/** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * The `unshift` method was removed. + */ +var priorityQueue = function(worker, concurrency) { + // Start with a normal queue + var q = queue$1(worker, concurrency); + + // Override push to accept second parameter representing priority + q.push = function(data, priority, callback) { + if (callback == null) callback = noop; + if (typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!isArray(data)) { + data = [data]; + } + if (data.length === 0) { + // call drain immediately if there are no tasks + return setImmediate$1(function() { + q.drain(); + }); + } + + priority = priority || 0; + var nextNode = q._tasks.head; + while (nextNode && priority >= nextNode.priority) { + nextNode = nextNode.next; + } + + for (var i = 0, l = data.length; i < l; i++) { + var item = { + data: data[i], + priority: priority, + callback: callback + }; + + if (nextNode) { + q._tasks.insertBefore(nextNode, item); + } else { + q._tasks.push(item); + } + } + setImmediate$1(q.process); + }; + + // Remove unshift function + delete q.unshift; + + return q; +}; + +/** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns undefined + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ +function race(tasks, callback) { + callback = once(callback || noop); + if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); + } +} + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + */ +function reduceRight (array, memo, iteratee, callback) { + var reversed = slice(array).reverse(); + reduce(reversed, memo, iteratee, callback); +} + +/** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ +function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push(function callback(error, cbArg) { + if (error) { + reflectCallback(null, { error: error }); + } else { + var value; + if (arguments.length <= 2) { + value = cbArg; + } else { + value = slice(arguments, 1); + } + reflectCallback(null, { value: value }); + } + }); + + return _fn.apply(this, args); + }); +} + +/** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ +function reflectAll(tasks) { + var results; + if (isArray(tasks)) { + results = arrayMap(tasks, reflect); + } else { + results = {}; + baseForOwn(tasks, function(task, key) { + results[key] = reflect.call(this, task); + }); + } + return results; +} + +function reject$1(eachfn, arr, iteratee, callback) { + _filter(eachfn, arr, function(value, cb) { + iteratee(value, function(err, v) { + cb(err, !v); + }); + }, callback); +} + +/** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @example + * + * async.reject(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of missing files + * createFiles(results); + * }); + */ +var reject = doParallel(reject$1); + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + */ +var rejectLimit = doParallelLimit(reject$1); + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + */ +var rejectSeries = doLimit(rejectLimit, 1); + +/** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ +function constant$1(value) { + return function() { + return value; + }; +} + +/** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ +function retry(opts, task, callback) { + var DEFAULT_TIMES = 5; + var DEFAULT_INTERVAL = 0; + + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant$1(DEFAULT_INTERVAL) + }; + + function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant$1(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } + } + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || noop; + task = opts; + } else { + parseTimes(options, opts); + callback = callback || noop; + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = wrapAsync(task); + + var attempt = 1; + function retryAttempt() { + _task(function(err) { + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt)); + } else { + callback.apply(null, arguments); + } + }); + } + + retryAttempt(); +} + +/** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ +var retryable = function (opts, task) { + if (!task) { + task = opts; + opts = null; + } + var _task = wrapAsync(task); + return initialParams(function (args, callback) { + function taskFn(cb) { + _task.apply(null, args.concat(cb)); + } + + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); + + }); +}; + +/** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @example + * async.series([ + * function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }, + * function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * } + * ], + * // optional callback + * function(err, results) { + * // results is now equal to ['one', 'two'] + * }); + * + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback){ + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equal to: {one: 1, two: 2} + * }); + */ +function series(tasks, callback) { + _parallel(eachOfSeries, tasks, callback); +} + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @example + * + * async.some(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then at least one of the files exists + * }); + */ +var some = doParallel(_createTester(Boolean, identity)); + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + */ +var someLimit = doParallelLimit(_createTester(Boolean, identity)); + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + */ +var someSeries = doLimit(someLimit, 1); + +/** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @example + * + * async.sortBy(['file1','file2','file3'], function(file, callback) { + * fs.stat(file, function(err, stats) { + * callback(err, stats.mtime); + * }); + * }, function(err, results) { + * // results is now the original array of files sorted by + * // modified date + * }); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x); + * }, function(err,result) { + * // result callback + * }); + * + * // descending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x*-1); //<- x*-1 instead of x, turns the order around + * }, function(err,result) { + * // result callback + * }); + */ +function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + map(coll, function (x, callback) { + _iteratee(x, function (err, criteria) { + if (err) return callback(err); + callback(null, {value: x, criteria: criteria}); + }); + }, function (err, results) { + if (err) return callback(err); + callback(null, arrayMap(results.sort(comparator), baseProperty('value'))); + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } +} + +/** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ +function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); + + return initialParams(function (args, callback) { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push(function () { + if (!timedOut) { + callback.apply(null, arguments); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn.apply(null, args); + }); +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeCeil = Math.ceil; +var nativeMax = Math.max; + +/** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ +function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; +} + +/** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + */ +function timeLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + mapLimit(baseRange(0, count, 1), limit, _iteratee, callback); +} + +/** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ +var times = doLimit(timeLimit, Infinity); + +/** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + */ +var timesSeries = doLimit(timeLimit, 1); + +/** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in series, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @example + * + * async.transform([1,2,3], function(acc, item, index, callback) { + * // pointless async: + * process.nextTick(function() { + * acc.push(item * 2) + * callback(null) + * }); + * }, function(err, result) { + * // result is now equal to [2, 4, 6] + * }); + * + * @example + * + * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { + * setImmediate(function () { + * obj[key] = val * 2; + * callback(); + * }) + * }, function (err, result) { + * // result is equal to {a: 2, b: 4, c: 6} + * }) + */ +function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3) { + callback = iteratee; + iteratee = accumulator; + accumulator = isArray(coll) ? [] : {}; + } + callback = once(callback || noop); + var _iteratee = wrapAsync(iteratee); + + eachOf(coll, function(v, k, cb) { + _iteratee(accumulator, v, k, cb); + }, function(err) { + callback(err, accumulator); + }); +} + +/** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ +function tryEach(tasks, callback) { + var error = null; + var result; + callback = callback || noop; + eachSeries(tasks, function(task, callback) { + wrapAsync(task)(function (err, res/*, ...args*/) { + if (arguments.length > 2) { + result = slice(arguments, 1); + } else { + result = res; + } + error = err; + callback(!err); + }); + }, function () { + callback(error, result); + }); +} + +/** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ +function unmemoize(fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; +} + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Function} test - synchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns undefined + * @example + * + * var count = 0; + * async.whilst( + * function() { return count < 5; }, + * function(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = onlyOnce(callback || noop); + var _iteratee = wrapAsync(iteratee); + if (!test()) return callback(null); + var next = function(err/*, ...args*/) { + if (err) return callback(err); + if (test()) return _iteratee(next); + var args = slice(arguments, 1); + callback.apply(null, [null].concat(args)); + }; + _iteratee(next); +} + +/** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {Function} test - synchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + */ +function until(test, iteratee, callback) { + whilst(function() { + return !test.apply(this, arguments); + }, iteratee, callback); +} + +/** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns undefined + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ +var waterfall = function(tasks, callback) { + callback = once(callback || noop); + if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + args.push(onlyOnce(next)); + task.apply(null, args); + } + + function next(err/*, ...args*/) { + if (err || taskIndex === tasks.length) { + return callback.apply(null, arguments); + } + nextTask(slice(arguments, 1)); + } + + nextTask([]); +}; + +/** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + +/** + * Async is a utility module which provides straight-forward, powerful functions + * for working with asynchronous JavaScript. Although originally designed for + * use with [Node.js](http://nodejs.org) and installable via + * `npm install --save async`, it can also be used directly in the browser. + * @module async + * @see AsyncFunction + */ + + +/** + * A collection of `async` functions for manipulating collections, such as + * arrays and objects. + * @module Collections + */ + +/** + * A collection of `async` functions for controlling the flow through a script. + * @module ControlFlow + */ + +/** + * A collection of `async` utility functions. + * @module Utils + */ + +var index = { + apply: apply, + applyEach: applyEach, + applyEachSeries: applyEachSeries, + asyncify: asyncify, + auto: auto, + autoInject: autoInject, + cargo: cargo, + compose: compose, + concat: concat, + concatLimit: concatLimit, + concatSeries: concatSeries, + constant: constant, + detect: detect, + detectLimit: detectLimit, + detectSeries: detectSeries, + dir: dir, + doDuring: doDuring, + doUntil: doUntil, + doWhilst: doWhilst, + during: during, + each: eachLimit, + eachLimit: eachLimit$1, + eachOf: eachOf, + eachOfLimit: eachOfLimit, + eachOfSeries: eachOfSeries, + eachSeries: eachSeries, + ensureAsync: ensureAsync, + every: every, + everyLimit: everyLimit, + everySeries: everySeries, + filter: filter, + filterLimit: filterLimit, + filterSeries: filterSeries, + forever: forever, + groupBy: groupBy, + groupByLimit: groupByLimit, + groupBySeries: groupBySeries, + log: log, + map: map, + mapLimit: mapLimit, + mapSeries: mapSeries, + mapValues: mapValues, + mapValuesLimit: mapValuesLimit, + mapValuesSeries: mapValuesSeries, + memoize: memoize, + nextTick: nextTick, + parallel: parallelLimit, + parallelLimit: parallelLimit$1, + priorityQueue: priorityQueue, + queue: queue$1, + race: race, + reduce: reduce, + reduceRight: reduceRight, + reflect: reflect, + reflectAll: reflectAll, + reject: reject, + rejectLimit: rejectLimit, + rejectSeries: rejectSeries, + retry: retry, + retryable: retryable, + seq: seq, + series: series, + setImmediate: setImmediate$1, + some: some, + someLimit: someLimit, + someSeries: someSeries, + sortBy: sortBy, + timeout: timeout, + times: times, + timesLimit: timeLimit, + timesSeries: timesSeries, + transform: transform, + tryEach: tryEach, + unmemoize: unmemoize, + until: until, + waterfall: waterfall, + whilst: whilst, + + // aliases + all: every, + allLimit: everyLimit, + allSeries: everySeries, + any: some, + anyLimit: someLimit, + anySeries: someSeries, + find: detect, + findLimit: detectLimit, + findSeries: detectSeries, + forEach: eachLimit, + forEachSeries: eachSeries, + forEachLimit: eachLimit$1, + forEachOf: eachOf, + forEachOfSeries: eachOfSeries, + forEachOfLimit: eachOfLimit, + inject: reduce, + foldl: reduce, + foldr: reduceRight, + select: filter, + selectLimit: filterLimit, + selectSeries: filterSeries, + wrapSync: asyncify +}; + +exports['default'] = index; +exports.apply = apply; +exports.applyEach = applyEach; +exports.applyEachSeries = applyEachSeries; +exports.asyncify = asyncify; +exports.auto = auto; +exports.autoInject = autoInject; +exports.cargo = cargo; +exports.compose = compose; +exports.concat = concat; +exports.concatLimit = concatLimit; +exports.concatSeries = concatSeries; +exports.constant = constant; +exports.detect = detect; +exports.detectLimit = detectLimit; +exports.detectSeries = detectSeries; +exports.dir = dir; +exports.doDuring = doDuring; +exports.doUntil = doUntil; +exports.doWhilst = doWhilst; +exports.during = during; +exports.each = eachLimit; +exports.eachLimit = eachLimit$1; +exports.eachOf = eachOf; +exports.eachOfLimit = eachOfLimit; +exports.eachOfSeries = eachOfSeries; +exports.eachSeries = eachSeries; +exports.ensureAsync = ensureAsync; +exports.every = every; +exports.everyLimit = everyLimit; +exports.everySeries = everySeries; +exports.filter = filter; +exports.filterLimit = filterLimit; +exports.filterSeries = filterSeries; +exports.forever = forever; +exports.groupBy = groupBy; +exports.groupByLimit = groupByLimit; +exports.groupBySeries = groupBySeries; +exports.log = log; +exports.map = map; +exports.mapLimit = mapLimit; +exports.mapSeries = mapSeries; +exports.mapValues = mapValues; +exports.mapValuesLimit = mapValuesLimit; +exports.mapValuesSeries = mapValuesSeries; +exports.memoize = memoize; +exports.nextTick = nextTick; +exports.parallel = parallelLimit; +exports.parallelLimit = parallelLimit$1; +exports.priorityQueue = priorityQueue; +exports.queue = queue$1; +exports.race = race; +exports.reduce = reduce; +exports.reduceRight = reduceRight; +exports.reflect = reflect; +exports.reflectAll = reflectAll; +exports.reject = reject; +exports.rejectLimit = rejectLimit; +exports.rejectSeries = rejectSeries; +exports.retry = retry; +exports.retryable = retryable; +exports.seq = seq; +exports.series = series; +exports.setImmediate = setImmediate$1; +exports.some = some; +exports.someLimit = someLimit; +exports.someSeries = someSeries; +exports.sortBy = sortBy; +exports.timeout = timeout; +exports.times = times; +exports.timesLimit = timeLimit; +exports.timesSeries = timesSeries; +exports.transform = transform; +exports.tryEach = tryEach; +exports.unmemoize = unmemoize; +exports.until = until; +exports.waterfall = waterfall; +exports.whilst = whilst; +exports.all = every; +exports.allLimit = everyLimit; +exports.allSeries = everySeries; +exports.any = some; +exports.anyLimit = someLimit; +exports.anySeries = someSeries; +exports.find = detect; +exports.findLimit = detectLimit; +exports.findSeries = detectSeries; +exports.forEach = eachLimit; +exports.forEachSeries = eachSeries; +exports.forEachLimit = eachLimit$1; +exports.forEachOf = eachOf; +exports.forEachOfSeries = eachOfSeries; +exports.forEachOfLimit = eachOfLimit; +exports.inject = reduce; +exports.foldl = reduce; +exports.foldr = reduceRight; +exports.select = filter; +exports.selectLimit = filterLimit; +exports.selectSeries = filterSeries; +exports.wrapSync = asyncify; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); diff --git a/app/node_modules/async/dist/async.min.js b/app/node_modules/async/dist/async.min.js new file mode 100644 index 0000000..7b8e87c --- /dev/null +++ b/app/node_modules/async/dist/async.min.js @@ -0,0 +1,2 @@ +!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(n.async=n.async||{})}(this,function(n){"use strict";function t(n,t){t|=0;for(var e=Math.max(n.length-t,0),r=Array(e),u=0;u-1&&n%1==0&&n<=Tt}function d(n){return null!=n&&v(n.length)&&!y(n)}function m(){}function g(n){return function(){if(null!==n){var t=n;n=null,t.apply(this,arguments)}}}function b(n,t){for(var e=-1,r=Array(n);++e-1&&n%1==0&&nu?0:u+t),e=e>u?u:e,e<0&&(e+=u),u=t>e?0:e-t>>>0,t>>>=0;for(var i=Array(u);++r=r?n:Z(n,t,e)}function tn(n,t){for(var e=n.length;e--&&J(t,n[e],0)>-1;);return e}function en(n,t){for(var e=-1,r=n.length;++e-1;);return e}function rn(n){return n.split("")}function un(n){return Xe.test(n)}function on(n){return n.match(mr)||[]}function cn(n){return un(n)?on(n):rn(n)}function fn(n){return null==n?"":Y(n)}function an(n,t,e){if(n=fn(n),n&&(e||void 0===t))return n.replace(gr,"");if(!n||!(t=Y(t)))return n;var r=cn(n),u=cn(t),i=en(r,u),o=tn(r,u)+1;return nn(r,i,o).join("")}function ln(n){return n=n.toString().replace(kr,""),n=n.match(br)[2].replace(" ",""),n=n?n.split(jr):[],n=n.map(function(n){return an(n.replace(Sr,""))})}function sn(n,t){var e={};N(n,function(n,t){function r(t,e){var r=K(u,function(n){return t[n]});r.push(e),a(n).apply(null,r)}var u,i=f(n),o=!i&&1===n.length||i&&0===n.length;if(Vt(n))u=n.slice(0,-1),n=n[n.length-1],e[t]=u.concat(u.length>0?r:n);else if(o)e[t]=n;else{if(u=ln(n),0===n.length&&!i&&0===u.length)throw new Error("autoInject task functions require explicit parameters.");i||u.pop(),e[t]=u.concat(r)}}),qe(e,t)}function pn(){this.head=this.tail=null,this.length=0}function hn(n,t){n.length=1,n.head=n.tail=t}function yn(n,t,e){function r(n,t,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");if(s.started=!0,Vt(n)||(n=[n]),0===n.length&&s.idle())return lt(function(){s.drain()});for(var r=0,u=n.length;r0&&c.splice(i,1),u.callback.apply(u,arguments),null!=t&&s.error(t,u.data)}o<=s.concurrency-s.buffer&&s.unsaturated(),s.idle()&&s.drain(),s.process()}}if(null==t)t=1;else if(0===t)throw new Error("Concurrency must not be zero");var i=a(n),o=0,c=[],f=!1,l=!1,s={_tasks:new pn,concurrency:t,payload:e,saturated:m,unsaturated:m,buffer:t/4,empty:m,drain:m,error:m,started:!1,paused:!1,push:function(n,t){r(n,!1,t)},kill:function(){s.drain=m,s._tasks.empty()},unshift:function(n,t){r(n,!0,t)},remove:function(n){s._tasks.remove(n)},process:function(){if(!l){for(l=!0;!s.paused&&o2&&(i=t(arguments,1)),u[e]=i,r(n)})},function(n){r(n,u)})}function Dn(n,t){qn(Ie,n,t)}function Rn(n,t,e){qn(z(t),n,e)}function Cn(n,t){if(t=g(t||m),!Vt(n))return t(new TypeError("First argument to race must be an array of functions"));if(!n.length)return t();for(var e=0,r=n.length;er?1:0}var u=a(t);_e(n,function(n,t){u(n,function(e,r){return e?t(e):void t(null,{value:n,criteria:r})})},function(n,t){return n?e(n):void e(null,K(t.sort(r),Fn("value")))})}function Xn(n,t,e){var r=a(n);return ct(function(u,i){function o(){var t=n.name||"anonymous",r=new Error('Callback function "'+t+'" timed out.');r.code="ETIMEDOUT",e&&(r.info=e),f=!0,i(r)}var c,f=!1;u.push(function(){f||(i.apply(null,arguments),clearTimeout(c))}),c=setTimeout(o,t),r.apply(null,u)})}function Yn(n,t,e,r){for(var u=-1,i=iu(uu((t-n)/(e||1)),0),o=Array(i);i--;)o[r?i:++u]=n,n+=e;return o}function Zn(n,t,e,r){var u=a(e);Ue(Yn(0,n,1),t,u,r)}function nt(n,t,e,r){arguments.length<=3&&(r=e,e=t,t=Vt(n)?[]:{}),r=g(r||m);var u=a(e);Ie(n,function(n,e,r){u(t,n,e,r)},function(n){r(n,t)})}function tt(n,e){var r,u=null;e=e||m,Ur(n,function(n,e){a(n)(function(n,i){r=arguments.length>2?t(arguments,1):i,u=n,e(!n)})},function(){e(u,r)})}function et(n){return function(){return(n.unmemoized||n).apply(null,arguments)}}function rt(n,e,r){r=U(r||m);var u=a(e);if(!n())return r(null);var i=function(e){if(e)return r(e);if(n())return u(i);var o=t(arguments,1);r.apply(null,[null].concat(o))};u(i)}function ut(n,t,e){rt(function(){return!n.apply(this,arguments)},t,e)}var it,ot=function(n){var e=t(arguments,1);return function(){var r=t(arguments);return n.apply(null,e.concat(r))}},ct=function(n){return function(){var e=t(arguments),r=e.pop();n.call(this,e,r)}},ft="function"==typeof setImmediate&&setImmediate,at="object"==typeof process&&"function"==typeof process.nextTick;it=ft?setImmediate:at?process.nextTick:r;var lt=u(it),st="function"==typeof Symbol,pt="object"==typeof global&&global&&global.Object===Object&&global,ht="object"==typeof self&&self&&self.Object===Object&&self,yt=pt||ht||Function("return this")(),vt=yt.Symbol,dt=Object.prototype,mt=dt.hasOwnProperty,gt=dt.toString,bt=vt?vt.toStringTag:void 0,jt=Object.prototype,St=jt.toString,kt="[object Null]",Lt="[object Undefined]",Ot=vt?vt.toStringTag:void 0,wt="[object AsyncFunction]",xt="[object Function]",Et="[object GeneratorFunction]",At="[object Proxy]",Tt=9007199254740991,Bt={},Ft="function"==typeof Symbol&&Symbol.iterator,It=function(n){return Ft&&n[Ft]&&n[Ft]()},_t="[object Arguments]",Mt=Object.prototype,Ut=Mt.hasOwnProperty,zt=Mt.propertyIsEnumerable,Pt=S(function(){return arguments}())?S:function(n){return j(n)&&Ut.call(n,"callee")&&!zt.call(n,"callee")},Vt=Array.isArray,qt="object"==typeof n&&n&&!n.nodeType&&n,Dt=qt&&"object"==typeof module&&module&&!module.nodeType&&module,Rt=Dt&&Dt.exports===qt,Ct=Rt?yt.Buffer:void 0,$t=Ct?Ct.isBuffer:void 0,Wt=$t||k,Nt=9007199254740991,Qt=/^(?:0|[1-9]\d*)$/,Gt="[object Arguments]",Ht="[object Array]",Jt="[object Boolean]",Kt="[object Date]",Xt="[object Error]",Yt="[object Function]",Zt="[object Map]",ne="[object Number]",te="[object Object]",ee="[object RegExp]",re="[object Set]",ue="[object String]",ie="[object WeakMap]",oe="[object ArrayBuffer]",ce="[object DataView]",fe="[object Float32Array]",ae="[object Float64Array]",le="[object Int8Array]",se="[object Int16Array]",pe="[object Int32Array]",he="[object Uint8Array]",ye="[object Uint8ClampedArray]",ve="[object Uint16Array]",de="[object Uint32Array]",me={};me[fe]=me[ae]=me[le]=me[se]=me[pe]=me[he]=me[ye]=me[ve]=me[de]=!0,me[Gt]=me[Ht]=me[oe]=me[Jt]=me[ce]=me[Kt]=me[Xt]=me[Yt]=me[Zt]=me[ne]=me[te]=me[ee]=me[re]=me[ue]=me[ie]=!1;var ge="object"==typeof n&&n&&!n.nodeType&&n,be=ge&&"object"==typeof module&&module&&!module.nodeType&&module,je=be&&be.exports===ge,Se=je&&pt.process,ke=function(){try{return Se&&Se.binding&&Se.binding("util")}catch(n){}}(),Le=ke&&ke.isTypedArray,Oe=Le?w(Le):O,we=Object.prototype,xe=we.hasOwnProperty,Ee=Object.prototype,Ae=A(Object.keys,Object),Te=Object.prototype,Be=Te.hasOwnProperty,Fe=V(P,1/0),Ie=function(n,t,e){var r=d(n)?q:Fe;r(n,a(t),e)},_e=D(R),Me=l(_e),Ue=C(R),ze=V(Ue,1),Pe=l(ze),Ve=W(),qe=function(n,e,r){function u(n,t){j.push(function(){f(n,t)})}function i(){if(0===j.length&&0===v)return r(null,y);for(;j.length&&v2&&(u=t(arguments,1)),e){var i={};N(y,function(n,t){i[t]=n}),i[n]=u,d=!0,b=Object.create(null),r(e,i)}else y[n]=u,c(n)});v++;var i=a(e[e.length-1]);e.length>1?i(y,u):i(u)}}function l(){for(var n,t=0;S.length;)n=S.pop(),t++,$(s(n),function(n){0===--k[n]&&S.push(n)});if(t!==h)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function s(t){var e=[];return N(n,function(n,r){Vt(n)&&J(n,t,0)>=0&&e.push(r)}),e}"function"==typeof e&&(r=e,e=null),r=g(r||m);var p=B(n),h=p.length;if(!h)return r(null);e||(e=h);var y={},v=0,d=!1,b=Object.create(null),j=[],S=[],k={};N(n,function(t,e){if(!Vt(t))return u(e,[t]),void S.push(e);var r=t.slice(0,t.length-1),i=r.length;return 0===i?(u(e,t),void S.push(e)):(k[e]=i,void $(r,function(c){if(!n[c])throw new Error("async.auto task `"+e+"` has a non-existent dependency `"+c+"` in "+r.join(", "));o(c,function(){i--,0===i&&u(e,t)})}))}),l(),i()},De="[object Symbol]",Re=1/0,Ce=vt?vt.prototype:void 0,$e=Ce?Ce.toString:void 0,We="\\ud800-\\udfff",Ne="\\u0300-\\u036f",Qe="\\ufe20-\\ufe2f",Ge="\\u20d0-\\u20ff",He=Ne+Qe+Ge,Je="\\ufe0e\\ufe0f",Ke="\\u200d",Xe=RegExp("["+Ke+We+He+Je+"]"),Ye="\\ud800-\\udfff",Ze="\\u0300-\\u036f",nr="\\ufe20-\\ufe2f",tr="\\u20d0-\\u20ff",er=Ze+nr+tr,rr="\\ufe0e\\ufe0f",ur="["+Ye+"]",ir="["+er+"]",or="\\ud83c[\\udffb-\\udfff]",cr="(?:"+ir+"|"+or+")",fr="[^"+Ye+"]",ar="(?:\\ud83c[\\udde6-\\uddff]){2}",lr="[\\ud800-\\udbff][\\udc00-\\udfff]",sr="\\u200d",pr=cr+"?",hr="["+rr+"]?",yr="(?:"+sr+"(?:"+[fr,ar,lr].join("|")+")"+hr+pr+")*",vr=hr+pr+yr,dr="(?:"+[fr+ir+"?",ir,ar,lr,ur].join("|")+")",mr=RegExp(or+"(?="+or+")|"+dr+vr,"g"),gr=/^\s+|\s+$/g,br=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,jr=/,/,Sr=/(=.+)?(\s*)$/,kr=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;pn.prototype.removeLink=function(n){return n.prev?n.prev.next=n.next:this.head=n.next,n.next?n.next.prev=n.prev:this.tail=n.prev,n.prev=n.next=null,this.length-=1,n},pn.prototype.empty=function(){for(;this.head;)this.shift();return this},pn.prototype.insertAfter=function(n,t){t.prev=n,t.next=n.next,n.next?n.next.prev=t:this.tail=t,n.next=t,this.length+=1},pn.prototype.insertBefore=function(n,t){t.prev=n.prev,t.next=n,n.prev?n.prev.next=t:this.head=t,n.prev=t,this.length+=1},pn.prototype.unshift=function(n){this.head?this.insertBefore(this.head,n):hn(this,n)},pn.prototype.push=function(n){this.tail?this.insertAfter(this.tail,n):hn(this,n)},pn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},pn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},pn.prototype.toArray=function(){for(var n=Array(this.length),t=this.head,e=0;e=u.priority;)u=u.next;for(var i=0,o=n.length;i 32 ) { + * console.log('This file name is too long'); + * callback('File name too long'); + * } else { + * // Do work to process file here + * console.log('File processed'); + * callback(); + * } + * }, function(err) { + * // if any of the file processing produced an error, err would equal that error + * if( err ) { + * // One of the iterations produced an error. + * // All processing will now stop. + * console.log('A file failed to process'); + * } else { + * console.log('All files have been processed successfully'); + * } + * }); + */ +function eachLimit(coll, iteratee, callback) { + (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/eachLimit.js b/app/node_modules/async/eachLimit.js new file mode 100644 index 0000000..fff721b --- /dev/null +++ b/app/node_modules/async/eachLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = eachLimit; + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _withoutIndex = require('./internal/withoutIndex'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ +function eachLimit(coll, limit, iteratee, callback) { + (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/eachOf.js b/app/node_modules/async/eachOf.js new file mode 100644 index 0000000..055b9bd --- /dev/null +++ b/app/node_modules/async/eachOf.js @@ -0,0 +1,111 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (coll, iteratee, callback) { + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; + eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); +}; + +var _isArrayLike = require('lodash/isArrayLike'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _breakLoop = require('./internal/breakLoop'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = (0, _once2.default)(callback || _noop2.default); + var index = 0, + completed = 0, + length = coll.length; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +var eachOfGeneric = (0, _doLimit2.default)(_eachOfLimit2.default, Infinity); + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/eachOfLimit.js b/app/node_modules/async/eachOfLimit.js new file mode 100644 index 0000000..30a1329 --- /dev/null +++ b/app/node_modules/async/eachOfLimit.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = eachOfLimit; + +var _eachOfLimit2 = require('./internal/eachOfLimit'); + +var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ +function eachOfLimit(coll, limit, iteratee, callback) { + (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/eachOfSeries.js b/app/node_modules/async/eachOfSeries.js new file mode 100644 index 0000000..9dfd711 --- /dev/null +++ b/app/node_modules/async/eachOfSeries.js @@ -0,0 +1,35 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + */ +exports.default = (0, _doLimit2.default)(_eachOfLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/eachSeries.js b/app/node_modules/async/eachSeries.js new file mode 100644 index 0000000..55c7840 --- /dev/null +++ b/app/node_modules/async/eachSeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachLimit = require('./eachLimit'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ +exports.default = (0, _doLimit2.default)(_eachLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/ensureAsync.js b/app/node_modules/async/ensureAsync.js new file mode 100644 index 0000000..1f57aec --- /dev/null +++ b/app/node_modules/async/ensureAsync.js @@ -0,0 +1,73 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = ensureAsync; + +var _setImmediate = require('./internal/setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _initialParams = require('./internal/initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ +function ensureAsync(fn) { + if ((0, _wrapAsync.isAsync)(fn)) return fn; + return (0, _initialParams2.default)(function (args, callback) { + var sync = true; + args.push(function () { + var innerArgs = arguments; + if (sync) { + (0, _setImmediate2.default)(function () { + callback.apply(null, innerArgs); + }); + } else { + callback.apply(null, innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/every.js b/app/node_modules/async/every.js new file mode 100644 index 0000000..d0565b0 --- /dev/null +++ b/app/node_modules/async/every.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _doParallel = require('./internal/doParallel'); + +var _doParallel2 = _interopRequireDefault(_doParallel); + +var _notId = require('./internal/notId'); + +var _notId2 = _interopRequireDefault(_notId); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @example + * + * async.every(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then every file exists + * }); + */ +exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/everyLimit.js b/app/node_modules/async/everyLimit.js new file mode 100644 index 0000000..a1a759a --- /dev/null +++ b/app/node_modules/async/everyLimit.js @@ -0,0 +1,42 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _doParallelLimit = require('./internal/doParallelLimit'); + +var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); + +var _notId = require('./internal/notId'); + +var _notId2 = _interopRequireDefault(_notId); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + */ +exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/everySeries.js b/app/node_modules/async/everySeries.js new file mode 100644 index 0000000..23bfebb --- /dev/null +++ b/app/node_modules/async/everySeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _everyLimit = require('./everyLimit'); + +var _everyLimit2 = _interopRequireDefault(_everyLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + */ +exports.default = (0, _doLimit2.default)(_everyLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/filter.js b/app/node_modules/async/filter.js new file mode 100644 index 0000000..54772d5 --- /dev/null +++ b/app/node_modules/async/filter.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter = require('./internal/filter'); + +var _filter2 = _interopRequireDefault(_filter); + +var _doParallel = require('./internal/doParallel'); + +var _doParallel2 = _interopRequireDefault(_doParallel); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @example + * + * async.filter(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of the existing files + * }); + */ +exports.default = (0, _doParallel2.default)(_filter2.default); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/filterLimit.js b/app/node_modules/async/filterLimit.js new file mode 100644 index 0000000..06216f7 --- /dev/null +++ b/app/node_modules/async/filterLimit.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter = require('./internal/filter'); + +var _filter2 = _interopRequireDefault(_filter); + +var _doParallelLimit = require('./internal/doParallelLimit'); + +var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + */ +exports.default = (0, _doParallelLimit2.default)(_filter2.default); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/filterSeries.js b/app/node_modules/async/filterSeries.js new file mode 100644 index 0000000..e48d966 --- /dev/null +++ b/app/node_modules/async/filterSeries.js @@ -0,0 +1,35 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filterLimit = require('./filterLimit'); + +var _filterLimit2 = _interopRequireDefault(_filterLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + */ +exports.default = (0, _doLimit2.default)(_filterLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/find.js b/app/node_modules/async/find.js new file mode 100644 index 0000000..db46783 --- /dev/null +++ b/app/node_modules/async/find.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _identity = require('lodash/identity'); + +var _identity2 = _interopRequireDefault(_identity); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _doParallel = require('./internal/doParallel'); + +var _doParallel2 = _interopRequireDefault(_doParallel); + +var _findGetResult = require('./internal/findGetResult'); + +var _findGetResult2 = _interopRequireDefault(_findGetResult); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @example + * + * async.detect(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // result now equals the first file in the list that exists + * }); + */ +exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default)); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/findLimit.js b/app/node_modules/async/findLimit.js new file mode 100644 index 0000000..6bf6560 --- /dev/null +++ b/app/node_modules/async/findLimit.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _identity = require('lodash/identity'); + +var _identity2 = _interopRequireDefault(_identity); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _doParallelLimit = require('./internal/doParallelLimit'); + +var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); + +var _findGetResult = require('./internal/findGetResult'); + +var _findGetResult2 = _interopRequireDefault(_findGetResult); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + */ +exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default)); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/findSeries.js b/app/node_modules/async/findSeries.js new file mode 100644 index 0000000..6fe16c9 --- /dev/null +++ b/app/node_modules/async/findSeries.js @@ -0,0 +1,38 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _detectLimit = require('./detectLimit'); + +var _detectLimit2 = _interopRequireDefault(_detectLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + */ +exports.default = (0, _doLimit2.default)(_detectLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/foldl.js b/app/node_modules/async/foldl.js new file mode 100644 index 0000000..3fb8019 --- /dev/null +++ b/app/node_modules/async/foldl.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduce; + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @example + * + * async.reduce([1,2,3], 0, function(memo, item, callback) { + * // pointless async: + * process.nextTick(function() { + * callback(null, memo + item) + * }); + * }, function(err, result) { + * // result is now equal to the last value of memo, which is 6 + * }); + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback || _noop2.default); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + (0, _eachOfSeries2.default)(coll, function (x, i, callback) { + _iteratee(memo, x, function (err, v) { + memo = v; + callback(err); + }); + }, function (err) { + callback(err, memo); + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/foldr.js b/app/node_modules/async/foldr.js new file mode 100644 index 0000000..3d17d32 --- /dev/null +++ b/app/node_modules/async/foldr.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduceRight; + +var _reduce = require('./reduce'); + +var _reduce2 = _interopRequireDefault(_reduce); + +var _slice = require('./internal/slice'); + +var _slice2 = _interopRequireDefault(_slice); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + */ +function reduceRight(array, memo, iteratee, callback) { + var reversed = (0, _slice2.default)(array).reverse(); + (0, _reduce2.default)(reversed, memo, iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/forEach.js b/app/node_modules/async/forEach.js new file mode 100644 index 0000000..4b20af3 --- /dev/null +++ b/app/node_modules/async/forEach.js @@ -0,0 +1,82 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = eachLimit; + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _withoutIndex = require('./internal/withoutIndex'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @example + * + * // assuming openFiles is an array of file names and saveFile is a function + * // to save the modified contents of that file: + * + * async.each(openFiles, saveFile, function(err){ + * // if any of the saves produced an error, err would equal that error + * }); + * + * // assuming openFiles is an array of file names + * async.each(openFiles, function(file, callback) { + * + * // Perform operation on file here. + * console.log('Processing file ' + file); + * + * if( file.length > 32 ) { + * console.log('This file name is too long'); + * callback('File name too long'); + * } else { + * // Do work to process file here + * console.log('File processed'); + * callback(); + * } + * }, function(err) { + * // if any of the file processing produced an error, err would equal that error + * if( err ) { + * // One of the iterations produced an error. + * // All processing will now stop. + * console.log('A file failed to process'); + * } else { + * console.log('All files have been processed successfully'); + * } + * }); + */ +function eachLimit(coll, iteratee, callback) { + (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/forEachLimit.js b/app/node_modules/async/forEachLimit.js new file mode 100644 index 0000000..fff721b --- /dev/null +++ b/app/node_modules/async/forEachLimit.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = eachLimit; + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _withoutIndex = require('./internal/withoutIndex'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ +function eachLimit(coll, limit, iteratee, callback) { + (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/forEachOf.js b/app/node_modules/async/forEachOf.js new file mode 100644 index 0000000..055b9bd --- /dev/null +++ b/app/node_modules/async/forEachOf.js @@ -0,0 +1,111 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (coll, iteratee, callback) { + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; + eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); +}; + +var _isArrayLike = require('lodash/isArrayLike'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _breakLoop = require('./internal/breakLoop'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// eachOf implementation optimized for array-likes +function eachOfArrayLike(coll, iteratee, callback) { + callback = (0, _once2.default)(callback || _noop2.default); + var index = 0, + completed = 0, + length = coll.length; + if (length === 0) { + callback(null); + } + + function iteratorCallback(err, value) { + if (err) { + callback(err); + } else if (++completed === length || value === _breakLoop2.default) { + callback(null); + } + } + + for (; index < length; index++) { + iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); + } +} + +// a generic version of eachOf which can handle array, object, and iterator cases. +var eachOfGeneric = (0, _doLimit2.default)(_eachOfLimit2.default, Infinity); + +/** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @example + * + * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; + * var configs = {}; + * + * async.forEachOf(obj, function (value, key, callback) { + * fs.readFile(__dirname + value, "utf8", function (err, data) { + * if (err) return callback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * }, function (err) { + * if (err) console.error(err.message); + * // configs is now a map of JSON data + * doSomethingWith(configs); + * }); + */ +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/forEachOfLimit.js b/app/node_modules/async/forEachOfLimit.js new file mode 100644 index 0000000..30a1329 --- /dev/null +++ b/app/node_modules/async/forEachOfLimit.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = eachOfLimit; + +var _eachOfLimit2 = require('./internal/eachOfLimit'); + +var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ +function eachOfLimit(coll, limit, iteratee, callback) { + (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/forEachOfSeries.js b/app/node_modules/async/forEachOfSeries.js new file mode 100644 index 0000000..9dfd711 --- /dev/null +++ b/app/node_modules/async/forEachOfSeries.js @@ -0,0 +1,35 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + */ +exports.default = (0, _doLimit2.default)(_eachOfLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/forEachSeries.js b/app/node_modules/async/forEachSeries.js new file mode 100644 index 0000000..55c7840 --- /dev/null +++ b/app/node_modules/async/forEachSeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachLimit = require('./eachLimit'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ +exports.default = (0, _doLimit2.default)(_eachLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/forever.js b/app/node_modules/async/forever.js new file mode 100644 index 0000000..6c7b8a4 --- /dev/null +++ b/app/node_modules/async/forever.js @@ -0,0 +1,65 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = forever; + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _ensureAsync = require('./ensureAsync'); + +var _ensureAsync2 = _interopRequireDefault(_ensureAsync); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. + + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ +function forever(fn, errback) { + var done = (0, _onlyOnce2.default)(errback || _noop2.default); + var task = (0, _wrapAsync2.default)((0, _ensureAsync2.default)(fn)); + + function next(err) { + if (err) return done(err); + task(next); + } + next(); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/groupBy.js b/app/node_modules/async/groupBy.js new file mode 100644 index 0000000..755cba7 --- /dev/null +++ b/app/node_modules/async/groupBy.js @@ -0,0 +1,54 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +var _groupByLimit = require('./groupByLimit'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @example + * + * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { + * db.findById(userId, function(err, user) { + * if (err) return callback(err); + * return callback(null, user.age); + * }); + * }, function(err, result) { + * // result is object containing the userIds grouped by age + * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; + * }); + */ +exports.default = (0, _doLimit2.default)(_groupByLimit2.default, Infinity); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/groupByLimit.js b/app/node_modules/async/groupByLimit.js new file mode 100644 index 0000000..fec13f8 --- /dev/null +++ b/app/node_modules/async/groupByLimit.js @@ -0,0 +1,71 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (coll, limit, iteratee, callback) { + callback = callback || _noop2.default; + var _iteratee = (0, _wrapAsync2.default)(iteratee); + (0, _mapLimit2.default)(coll, limit, function (val, callback) { + _iteratee(val, function (err, key) { + if (err) return callback(err); + return callback(null, { key: key, val: val }); + }); + }, function (err, mapResults) { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var hasOwnProperty = Object.prototype.hasOwnProperty; + + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var key = mapResults[i].key; + var val = mapResults[i].val; + + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } + + return callback(err, result); + }); +}; + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _mapLimit = require('./mapLimit'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +; +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + */ +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/groupBySeries.js b/app/node_modules/async/groupBySeries.js new file mode 100644 index 0000000..b94805e --- /dev/null +++ b/app/node_modules/async/groupBySeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +var _groupByLimit = require('./groupByLimit'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + */ +exports.default = (0, _doLimit2.default)(_groupByLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/index.js b/app/node_modules/async/index.js new file mode 100644 index 0000000..c39d8d8 --- /dev/null +++ b/app/node_modules/async/index.js @@ -0,0 +1,582 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.wrapSync = exports.selectSeries = exports.selectLimit = exports.select = exports.foldr = exports.foldl = exports.inject = exports.forEachOfLimit = exports.forEachOfSeries = exports.forEachOf = exports.forEachLimit = exports.forEachSeries = exports.forEach = exports.findSeries = exports.findLimit = exports.find = exports.anySeries = exports.anyLimit = exports.any = exports.allSeries = exports.allLimit = exports.all = exports.whilst = exports.waterfall = exports.until = exports.unmemoize = exports.tryEach = exports.transform = exports.timesSeries = exports.timesLimit = exports.times = exports.timeout = exports.sortBy = exports.someSeries = exports.someLimit = exports.some = exports.setImmediate = exports.series = exports.seq = exports.retryable = exports.retry = exports.rejectSeries = exports.rejectLimit = exports.reject = exports.reflectAll = exports.reflect = exports.reduceRight = exports.reduce = exports.race = exports.queue = exports.priorityQueue = exports.parallelLimit = exports.parallel = exports.nextTick = exports.memoize = exports.mapValuesSeries = exports.mapValuesLimit = exports.mapValues = exports.mapSeries = exports.mapLimit = exports.map = exports.log = exports.groupBySeries = exports.groupByLimit = exports.groupBy = exports.forever = exports.filterSeries = exports.filterLimit = exports.filter = exports.everySeries = exports.everyLimit = exports.every = exports.ensureAsync = exports.eachSeries = exports.eachOfSeries = exports.eachOfLimit = exports.eachOf = exports.eachLimit = exports.each = exports.during = exports.doWhilst = exports.doUntil = exports.doDuring = exports.dir = exports.detectSeries = exports.detectLimit = exports.detect = exports.constant = exports.concatSeries = exports.concatLimit = exports.concat = exports.compose = exports.cargo = exports.autoInject = exports.auto = exports.asyncify = exports.applyEachSeries = exports.applyEach = exports.apply = undefined; + +var _apply = require('./apply'); + +var _apply2 = _interopRequireDefault(_apply); + +var _applyEach = require('./applyEach'); + +var _applyEach2 = _interopRequireDefault(_applyEach); + +var _applyEachSeries = require('./applyEachSeries'); + +var _applyEachSeries2 = _interopRequireDefault(_applyEachSeries); + +var _asyncify = require('./asyncify'); + +var _asyncify2 = _interopRequireDefault(_asyncify); + +var _auto = require('./auto'); + +var _auto2 = _interopRequireDefault(_auto); + +var _autoInject = require('./autoInject'); + +var _autoInject2 = _interopRequireDefault(_autoInject); + +var _cargo = require('./cargo'); + +var _cargo2 = _interopRequireDefault(_cargo); + +var _compose = require('./compose'); + +var _compose2 = _interopRequireDefault(_compose); + +var _concat = require('./concat'); + +var _concat2 = _interopRequireDefault(_concat); + +var _concatLimit = require('./concatLimit'); + +var _concatLimit2 = _interopRequireDefault(_concatLimit); + +var _concatSeries = require('./concatSeries'); + +var _concatSeries2 = _interopRequireDefault(_concatSeries); + +var _constant = require('./constant'); + +var _constant2 = _interopRequireDefault(_constant); + +var _detect = require('./detect'); + +var _detect2 = _interopRequireDefault(_detect); + +var _detectLimit = require('./detectLimit'); + +var _detectLimit2 = _interopRequireDefault(_detectLimit); + +var _detectSeries = require('./detectSeries'); + +var _detectSeries2 = _interopRequireDefault(_detectSeries); + +var _dir = require('./dir'); + +var _dir2 = _interopRequireDefault(_dir); + +var _doDuring = require('./doDuring'); + +var _doDuring2 = _interopRequireDefault(_doDuring); + +var _doUntil = require('./doUntil'); + +var _doUntil2 = _interopRequireDefault(_doUntil); + +var _doWhilst = require('./doWhilst'); + +var _doWhilst2 = _interopRequireDefault(_doWhilst); + +var _during = require('./during'); + +var _during2 = _interopRequireDefault(_during); + +var _each = require('./each'); + +var _each2 = _interopRequireDefault(_each); + +var _eachLimit = require('./eachLimit'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _eachSeries = require('./eachSeries'); + +var _eachSeries2 = _interopRequireDefault(_eachSeries); + +var _ensureAsync = require('./ensureAsync'); + +var _ensureAsync2 = _interopRequireDefault(_ensureAsync); + +var _every = require('./every'); + +var _every2 = _interopRequireDefault(_every); + +var _everyLimit = require('./everyLimit'); + +var _everyLimit2 = _interopRequireDefault(_everyLimit); + +var _everySeries = require('./everySeries'); + +var _everySeries2 = _interopRequireDefault(_everySeries); + +var _filter = require('./filter'); + +var _filter2 = _interopRequireDefault(_filter); + +var _filterLimit = require('./filterLimit'); + +var _filterLimit2 = _interopRequireDefault(_filterLimit); + +var _filterSeries = require('./filterSeries'); + +var _filterSeries2 = _interopRequireDefault(_filterSeries); + +var _forever = require('./forever'); + +var _forever2 = _interopRequireDefault(_forever); + +var _groupBy = require('./groupBy'); + +var _groupBy2 = _interopRequireDefault(_groupBy); + +var _groupByLimit = require('./groupByLimit'); + +var _groupByLimit2 = _interopRequireDefault(_groupByLimit); + +var _groupBySeries = require('./groupBySeries'); + +var _groupBySeries2 = _interopRequireDefault(_groupBySeries); + +var _log = require('./log'); + +var _log2 = _interopRequireDefault(_log); + +var _map = require('./map'); + +var _map2 = _interopRequireDefault(_map); + +var _mapLimit = require('./mapLimit'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _mapSeries = require('./mapSeries'); + +var _mapSeries2 = _interopRequireDefault(_mapSeries); + +var _mapValues = require('./mapValues'); + +var _mapValues2 = _interopRequireDefault(_mapValues); + +var _mapValuesLimit = require('./mapValuesLimit'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +var _mapValuesSeries = require('./mapValuesSeries'); + +var _mapValuesSeries2 = _interopRequireDefault(_mapValuesSeries); + +var _memoize = require('./memoize'); + +var _memoize2 = _interopRequireDefault(_memoize); + +var _nextTick = require('./nextTick'); + +var _nextTick2 = _interopRequireDefault(_nextTick); + +var _parallel = require('./parallel'); + +var _parallel2 = _interopRequireDefault(_parallel); + +var _parallelLimit = require('./parallelLimit'); + +var _parallelLimit2 = _interopRequireDefault(_parallelLimit); + +var _priorityQueue = require('./priorityQueue'); + +var _priorityQueue2 = _interopRequireDefault(_priorityQueue); + +var _queue = require('./queue'); + +var _queue2 = _interopRequireDefault(_queue); + +var _race = require('./race'); + +var _race2 = _interopRequireDefault(_race); + +var _reduce = require('./reduce'); + +var _reduce2 = _interopRequireDefault(_reduce); + +var _reduceRight = require('./reduceRight'); + +var _reduceRight2 = _interopRequireDefault(_reduceRight); + +var _reflect = require('./reflect'); + +var _reflect2 = _interopRequireDefault(_reflect); + +var _reflectAll = require('./reflectAll'); + +var _reflectAll2 = _interopRequireDefault(_reflectAll); + +var _reject = require('./reject'); + +var _reject2 = _interopRequireDefault(_reject); + +var _rejectLimit = require('./rejectLimit'); + +var _rejectLimit2 = _interopRequireDefault(_rejectLimit); + +var _rejectSeries = require('./rejectSeries'); + +var _rejectSeries2 = _interopRequireDefault(_rejectSeries); + +var _retry = require('./retry'); + +var _retry2 = _interopRequireDefault(_retry); + +var _retryable = require('./retryable'); + +var _retryable2 = _interopRequireDefault(_retryable); + +var _seq = require('./seq'); + +var _seq2 = _interopRequireDefault(_seq); + +var _series = require('./series'); + +var _series2 = _interopRequireDefault(_series); + +var _setImmediate = require('./setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _some = require('./some'); + +var _some2 = _interopRequireDefault(_some); + +var _someLimit = require('./someLimit'); + +var _someLimit2 = _interopRequireDefault(_someLimit); + +var _someSeries = require('./someSeries'); + +var _someSeries2 = _interopRequireDefault(_someSeries); + +var _sortBy = require('./sortBy'); + +var _sortBy2 = _interopRequireDefault(_sortBy); + +var _timeout = require('./timeout'); + +var _timeout2 = _interopRequireDefault(_timeout); + +var _times = require('./times'); + +var _times2 = _interopRequireDefault(_times); + +var _timesLimit = require('./timesLimit'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +var _timesSeries = require('./timesSeries'); + +var _timesSeries2 = _interopRequireDefault(_timesSeries); + +var _transform = require('./transform'); + +var _transform2 = _interopRequireDefault(_transform); + +var _tryEach = require('./tryEach'); + +var _tryEach2 = _interopRequireDefault(_tryEach); + +var _unmemoize = require('./unmemoize'); + +var _unmemoize2 = _interopRequireDefault(_unmemoize); + +var _until = require('./until'); + +var _until2 = _interopRequireDefault(_until); + +var _waterfall = require('./waterfall'); + +var _waterfall2 = _interopRequireDefault(_waterfall); + +var _whilst = require('./whilst'); + +var _whilst2 = _interopRequireDefault(_whilst); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = { + apply: _apply2.default, + applyEach: _applyEach2.default, + applyEachSeries: _applyEachSeries2.default, + asyncify: _asyncify2.default, + auto: _auto2.default, + autoInject: _autoInject2.default, + cargo: _cargo2.default, + compose: _compose2.default, + concat: _concat2.default, + concatLimit: _concatLimit2.default, + concatSeries: _concatSeries2.default, + constant: _constant2.default, + detect: _detect2.default, + detectLimit: _detectLimit2.default, + detectSeries: _detectSeries2.default, + dir: _dir2.default, + doDuring: _doDuring2.default, + doUntil: _doUntil2.default, + doWhilst: _doWhilst2.default, + during: _during2.default, + each: _each2.default, + eachLimit: _eachLimit2.default, + eachOf: _eachOf2.default, + eachOfLimit: _eachOfLimit2.default, + eachOfSeries: _eachOfSeries2.default, + eachSeries: _eachSeries2.default, + ensureAsync: _ensureAsync2.default, + every: _every2.default, + everyLimit: _everyLimit2.default, + everySeries: _everySeries2.default, + filter: _filter2.default, + filterLimit: _filterLimit2.default, + filterSeries: _filterSeries2.default, + forever: _forever2.default, + groupBy: _groupBy2.default, + groupByLimit: _groupByLimit2.default, + groupBySeries: _groupBySeries2.default, + log: _log2.default, + map: _map2.default, + mapLimit: _mapLimit2.default, + mapSeries: _mapSeries2.default, + mapValues: _mapValues2.default, + mapValuesLimit: _mapValuesLimit2.default, + mapValuesSeries: _mapValuesSeries2.default, + memoize: _memoize2.default, + nextTick: _nextTick2.default, + parallel: _parallel2.default, + parallelLimit: _parallelLimit2.default, + priorityQueue: _priorityQueue2.default, + queue: _queue2.default, + race: _race2.default, + reduce: _reduce2.default, + reduceRight: _reduceRight2.default, + reflect: _reflect2.default, + reflectAll: _reflectAll2.default, + reject: _reject2.default, + rejectLimit: _rejectLimit2.default, + rejectSeries: _rejectSeries2.default, + retry: _retry2.default, + retryable: _retryable2.default, + seq: _seq2.default, + series: _series2.default, + setImmediate: _setImmediate2.default, + some: _some2.default, + someLimit: _someLimit2.default, + someSeries: _someSeries2.default, + sortBy: _sortBy2.default, + timeout: _timeout2.default, + times: _times2.default, + timesLimit: _timesLimit2.default, + timesSeries: _timesSeries2.default, + transform: _transform2.default, + tryEach: _tryEach2.default, + unmemoize: _unmemoize2.default, + until: _until2.default, + waterfall: _waterfall2.default, + whilst: _whilst2.default, + + // aliases + all: _every2.default, + allLimit: _everyLimit2.default, + allSeries: _everySeries2.default, + any: _some2.default, + anyLimit: _someLimit2.default, + anySeries: _someSeries2.default, + find: _detect2.default, + findLimit: _detectLimit2.default, + findSeries: _detectSeries2.default, + forEach: _each2.default, + forEachSeries: _eachSeries2.default, + forEachLimit: _eachLimit2.default, + forEachOf: _eachOf2.default, + forEachOfSeries: _eachOfSeries2.default, + forEachOfLimit: _eachOfLimit2.default, + inject: _reduce2.default, + foldl: _reduce2.default, + foldr: _reduceRight2.default, + select: _filter2.default, + selectLimit: _filterLimit2.default, + selectSeries: _filterSeries2.default, + wrapSync: _asyncify2.default +}; /** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ + +/** + * Async is a utility module which provides straight-forward, powerful functions + * for working with asynchronous JavaScript. Although originally designed for + * use with [Node.js](http://nodejs.org) and installable via + * `npm install --save async`, it can also be used directly in the browser. + * @module async + * @see AsyncFunction + */ + +/** + * A collection of `async` functions for manipulating collections, such as + * arrays and objects. + * @module Collections + */ + +/** + * A collection of `async` functions for controlling the flow through a script. + * @module ControlFlow + */ + +/** + * A collection of `async` utility functions. + * @module Utils + */ + +exports.apply = _apply2.default; +exports.applyEach = _applyEach2.default; +exports.applyEachSeries = _applyEachSeries2.default; +exports.asyncify = _asyncify2.default; +exports.auto = _auto2.default; +exports.autoInject = _autoInject2.default; +exports.cargo = _cargo2.default; +exports.compose = _compose2.default; +exports.concat = _concat2.default; +exports.concatLimit = _concatLimit2.default; +exports.concatSeries = _concatSeries2.default; +exports.constant = _constant2.default; +exports.detect = _detect2.default; +exports.detectLimit = _detectLimit2.default; +exports.detectSeries = _detectSeries2.default; +exports.dir = _dir2.default; +exports.doDuring = _doDuring2.default; +exports.doUntil = _doUntil2.default; +exports.doWhilst = _doWhilst2.default; +exports.during = _during2.default; +exports.each = _each2.default; +exports.eachLimit = _eachLimit2.default; +exports.eachOf = _eachOf2.default; +exports.eachOfLimit = _eachOfLimit2.default; +exports.eachOfSeries = _eachOfSeries2.default; +exports.eachSeries = _eachSeries2.default; +exports.ensureAsync = _ensureAsync2.default; +exports.every = _every2.default; +exports.everyLimit = _everyLimit2.default; +exports.everySeries = _everySeries2.default; +exports.filter = _filter2.default; +exports.filterLimit = _filterLimit2.default; +exports.filterSeries = _filterSeries2.default; +exports.forever = _forever2.default; +exports.groupBy = _groupBy2.default; +exports.groupByLimit = _groupByLimit2.default; +exports.groupBySeries = _groupBySeries2.default; +exports.log = _log2.default; +exports.map = _map2.default; +exports.mapLimit = _mapLimit2.default; +exports.mapSeries = _mapSeries2.default; +exports.mapValues = _mapValues2.default; +exports.mapValuesLimit = _mapValuesLimit2.default; +exports.mapValuesSeries = _mapValuesSeries2.default; +exports.memoize = _memoize2.default; +exports.nextTick = _nextTick2.default; +exports.parallel = _parallel2.default; +exports.parallelLimit = _parallelLimit2.default; +exports.priorityQueue = _priorityQueue2.default; +exports.queue = _queue2.default; +exports.race = _race2.default; +exports.reduce = _reduce2.default; +exports.reduceRight = _reduceRight2.default; +exports.reflect = _reflect2.default; +exports.reflectAll = _reflectAll2.default; +exports.reject = _reject2.default; +exports.rejectLimit = _rejectLimit2.default; +exports.rejectSeries = _rejectSeries2.default; +exports.retry = _retry2.default; +exports.retryable = _retryable2.default; +exports.seq = _seq2.default; +exports.series = _series2.default; +exports.setImmediate = _setImmediate2.default; +exports.some = _some2.default; +exports.someLimit = _someLimit2.default; +exports.someSeries = _someSeries2.default; +exports.sortBy = _sortBy2.default; +exports.timeout = _timeout2.default; +exports.times = _times2.default; +exports.timesLimit = _timesLimit2.default; +exports.timesSeries = _timesSeries2.default; +exports.transform = _transform2.default; +exports.tryEach = _tryEach2.default; +exports.unmemoize = _unmemoize2.default; +exports.until = _until2.default; +exports.waterfall = _waterfall2.default; +exports.whilst = _whilst2.default; +exports.all = _every2.default; +exports.allLimit = _everyLimit2.default; +exports.allSeries = _everySeries2.default; +exports.any = _some2.default; +exports.anyLimit = _someLimit2.default; +exports.anySeries = _someSeries2.default; +exports.find = _detect2.default; +exports.findLimit = _detectLimit2.default; +exports.findSeries = _detectSeries2.default; +exports.forEach = _each2.default; +exports.forEachSeries = _eachSeries2.default; +exports.forEachLimit = _eachLimit2.default; +exports.forEachOf = _eachOf2.default; +exports.forEachOfSeries = _eachOfSeries2.default; +exports.forEachOfLimit = _eachOfLimit2.default; +exports.inject = _reduce2.default; +exports.foldl = _reduce2.default; +exports.foldr = _reduceRight2.default; +exports.select = _filter2.default; +exports.selectLimit = _filterLimit2.default; +exports.selectSeries = _filterSeries2.default; +exports.wrapSync = _asyncify2.default; \ No newline at end of file diff --git a/app/node_modules/async/inject.js b/app/node_modules/async/inject.js new file mode 100644 index 0000000..3fb8019 --- /dev/null +++ b/app/node_modules/async/inject.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduce; + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @example + * + * async.reduce([1,2,3], 0, function(memo, item, callback) { + * // pointless async: + * process.nextTick(function() { + * callback(null, memo + item) + * }); + * }, function(err, result) { + * // result is now equal to the last value of memo, which is 6 + * }); + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback || _noop2.default); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + (0, _eachOfSeries2.default)(coll, function (x, i, callback) { + _iteratee(memo, x, function (err, v) { + memo = v; + callback(err); + }); + }, function (err) { + callback(err, memo); + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/DoublyLinkedList.js b/app/node_modules/async/internal/DoublyLinkedList.js new file mode 100644 index 0000000..7e71728 --- /dev/null +++ b/app/node_modules/async/internal/DoublyLinkedList.js @@ -0,0 +1,88 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = DLL; +// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation +// used for queues. This implementation assumes that the node provided by the user can be modified +// to adjust the next and last properties. We implement only the minimal functionality +// for queue support. +function DLL() { + this.head = this.tail = null; + this.length = 0; +} + +function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; +} + +DLL.prototype.removeLink = function (node) { + if (node.prev) node.prev.next = node.next;else this.head = node.next; + if (node.next) node.next.prev = node.prev;else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; +}; + +DLL.prototype.empty = function () { + while (this.head) this.shift(); + return this; +}; + +DLL.prototype.insertAfter = function (node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode;else this.tail = newNode; + node.next = newNode; + this.length += 1; +}; + +DLL.prototype.insertBefore = function (node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode;else this.head = newNode; + node.prev = newNode; + this.length += 1; +}; + +DLL.prototype.unshift = function (node) { + if (this.head) this.insertBefore(this.head, node);else setInitial(this, node); +}; + +DLL.prototype.push = function (node) { + if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node); +}; + +DLL.prototype.shift = function () { + return this.head && this.removeLink(this.head); +}; + +DLL.prototype.pop = function () { + return this.tail && this.removeLink(this.tail); +}; + +DLL.prototype.toArray = function () { + var arr = Array(this.length); + var curr = this.head; + for (var idx = 0; idx < this.length; idx++) { + arr[idx] = curr.data; + curr = curr.next; + } + return arr; +}; + +DLL.prototype.remove = function (testFn) { + var curr = this.head; + while (!!curr) { + var next = curr.next; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; +}; +module.exports = exports["default"]; \ No newline at end of file diff --git a/app/node_modules/async/internal/applyEach.js b/app/node_modules/async/internal/applyEach.js new file mode 100644 index 0000000..322e03c --- /dev/null +++ b/app/node_modules/async/internal/applyEach.js @@ -0,0 +1,38 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = applyEach; + +var _slice = require('./slice'); + +var _slice2 = _interopRequireDefault(_slice); + +var _initialParams = require('./initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function applyEach(eachfn) { + return function (fns /*, ...args*/) { + var args = (0, _slice2.default)(arguments, 1); + var go = (0, _initialParams2.default)(function (args, callback) { + var that = this; + return eachfn(fns, function (fn, cb) { + (0, _wrapAsync2.default)(fn).apply(that, args.concat(cb)); + }, callback); + }); + if (args.length) { + return go.apply(this, args); + } else { + return go; + } + }; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/breakLoop.js b/app/node_modules/async/internal/breakLoop.js new file mode 100644 index 0000000..1065058 --- /dev/null +++ b/app/node_modules/async/internal/breakLoop.js @@ -0,0 +1,9 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +// A temporary value used to identify if the loop should be broken. +// See #1064, #1293 +exports.default = {}; +module.exports = exports["default"]; \ No newline at end of file diff --git a/app/node_modules/async/internal/consoleFunc.js b/app/node_modules/async/internal/consoleFunc.js new file mode 100644 index 0000000..603f48e --- /dev/null +++ b/app/node_modules/async/internal/consoleFunc.js @@ -0,0 +1,42 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = consoleFunc; + +var _arrayEach = require('lodash/_arrayEach'); + +var _arrayEach2 = _interopRequireDefault(_arrayEach); + +var _slice = require('./slice'); + +var _slice2 = _interopRequireDefault(_slice); + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function consoleFunc(name) { + return function (fn /*, ...args*/) { + var args = (0, _slice2.default)(arguments, 1); + args.push(function (err /*, ...args*/) { + var args = (0, _slice2.default)(arguments, 1); + if (typeof console === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } else if (console[name]) { + (0, _arrayEach2.default)(args, function (x) { + console[name](x); + }); + } + } + }); + (0, _wrapAsync2.default)(fn).apply(null, args); + }; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/createTester.js b/app/node_modules/async/internal/createTester.js new file mode 100644 index 0000000..ce96e8b --- /dev/null +++ b/app/node_modules/async/internal/createTester.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _createTester; + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _breakLoop = require('./breakLoop'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _createTester(check, getResult) { + return function (eachfn, arr, iteratee, cb) { + cb = cb || _noop2.default; + var testPassed = false; + var testResult; + eachfn(arr, function (value, _, callback) { + iteratee(value, function (err, result) { + if (err) { + callback(err); + } else if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + callback(null, _breakLoop2.default); + } else { + callback(); + } + }); + }, function (err) { + if (err) { + cb(err); + } else { + cb(null, testPassed ? testResult : getResult(false)); + } + }); + }; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/doLimit.js b/app/node_modules/async/internal/doLimit.js new file mode 100644 index 0000000..963c608 --- /dev/null +++ b/app/node_modules/async/internal/doLimit.js @@ -0,0 +1,12 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = doLimit; +function doLimit(fn, limit) { + return function (iterable, iteratee, callback) { + return fn(iterable, limit, iteratee, callback); + }; +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/app/node_modules/async/internal/doParallel.js b/app/node_modules/async/internal/doParallel.js new file mode 100644 index 0000000..bb40207 --- /dev/null +++ b/app/node_modules/async/internal/doParallel.js @@ -0,0 +1,23 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = doParallel; + +var _eachOf = require('../eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function doParallel(fn) { + return function (obj, iteratee, callback) { + return fn(_eachOf2.default, obj, (0, _wrapAsync2.default)(iteratee), callback); + }; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/doParallelLimit.js b/app/node_modules/async/internal/doParallelLimit.js new file mode 100644 index 0000000..a7e963d --- /dev/null +++ b/app/node_modules/async/internal/doParallelLimit.js @@ -0,0 +1,23 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = doParallelLimit; + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function doParallelLimit(fn) { + return function (obj, limit, iteratee, callback) { + return fn((0, _eachOfLimit2.default)(limit), obj, (0, _wrapAsync2.default)(iteratee), callback); + }; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/eachOfLimit.js b/app/node_modules/async/internal/eachOfLimit.js new file mode 100644 index 0000000..e4c74bb --- /dev/null +++ b/app/node_modules/async/internal/eachOfLimit.js @@ -0,0 +1,71 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _eachOfLimit; + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _once = require('./once'); + +var _once2 = _interopRequireDefault(_once); + +var _iterator = require('./iterator'); + +var _iterator2 = _interopRequireDefault(_iterator); + +var _onlyOnce = require('./onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _breakLoop = require('./breakLoop'); + +var _breakLoop2 = _interopRequireDefault(_breakLoop); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _eachOfLimit(limit) { + return function (obj, iteratee, callback) { + callback = (0, _once2.default)(callback || _noop2.default); + if (limit <= 0 || !obj) { + return callback(null); + } + var nextElem = (0, _iterator2.default)(obj); + var done = false; + var running = 0; + + function iterateeCallback(err, value) { + running -= 1; + if (err) { + done = true; + callback(err); + } else if (value === _breakLoop2.default || done && running <= 0) { + done = true; + return callback(null); + } else { + replenish(); + } + } + + function replenish() { + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); + } + } + + replenish(); + }; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/filter.js b/app/node_modules/async/internal/filter.js new file mode 100644 index 0000000..74f3986 --- /dev/null +++ b/app/node_modules/async/internal/filter.js @@ -0,0 +1,75 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _filter; + +var _arrayMap = require('lodash/_arrayMap'); + +var _arrayMap2 = _interopRequireDefault(_arrayMap); + +var _isArrayLike = require('lodash/isArrayLike'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _baseProperty = require('lodash/_baseProperty'); + +var _baseProperty2 = _interopRequireDefault(_baseProperty); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, function (x, index, callback) { + iteratee(x, function (err, v) { + truthValues[index] = !!v; + callback(err); + }); + }, function (err) { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); +} + +function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, function (x, index, callback) { + iteratee(x, function (err, v) { + if (err) { + callback(err); + } else { + if (v) { + results.push({ index: index, value: x }); + } + callback(); + } + }); + }, function (err) { + if (err) { + callback(err); + } else { + callback(null, (0, _arrayMap2.default)(results.sort(function (a, b) { + return a.index - b.index; + }), (0, _baseProperty2.default)('value'))); + } + }); +} + +function _filter(eachfn, coll, iteratee, callback) { + var filter = (0, _isArrayLike2.default)(coll) ? filterArray : filterGeneric; + filter(eachfn, coll, (0, _wrapAsync2.default)(iteratee), callback || _noop2.default); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/findGetResult.js b/app/node_modules/async/internal/findGetResult.js new file mode 100644 index 0000000..f8d3fe0 --- /dev/null +++ b/app/node_modules/async/internal/findGetResult.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _findGetResult; +function _findGetResult(v, x) { + return x; +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/app/node_modules/async/internal/getIterator.js b/app/node_modules/async/internal/getIterator.js new file mode 100644 index 0000000..3eadd24 --- /dev/null +++ b/app/node_modules/async/internal/getIterator.js @@ -0,0 +1,13 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (coll) { + return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); +}; + +var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; + +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/initialParams.js b/app/node_modules/async/internal/initialParams.js new file mode 100644 index 0000000..df02cb1 --- /dev/null +++ b/app/node_modules/async/internal/initialParams.js @@ -0,0 +1,21 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (fn) { + return function () /*...args, callback*/{ + var args = (0, _slice2.default)(arguments); + var callback = args.pop(); + fn.call(this, args, callback); + }; +}; + +var _slice = require('./slice'); + +var _slice2 = _interopRequireDefault(_slice); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/iterator.js b/app/node_modules/async/internal/iterator.js new file mode 100644 index 0000000..3d32942 --- /dev/null +++ b/app/node_modules/async/internal/iterator.js @@ -0,0 +1,58 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = iterator; + +var _isArrayLike = require('lodash/isArrayLike'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _getIterator = require('./getIterator'); + +var _getIterator2 = _interopRequireDefault(_getIterator); + +var _keys = require('lodash/keys'); + +var _keys2 = _interopRequireDefault(_keys); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? { value: coll[i], key: i } : null; + }; +} + +function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) return null; + i++; + return { value: item.value, key: i }; + }; +} + +function createObjectIterator(obj) { + var okeys = (0, _keys2.default)(obj); + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + return i < len ? { value: obj[key], key: key } : null; + }; +} + +function iterator(coll) { + if ((0, _isArrayLike2.default)(coll)) { + return createArrayIterator(coll); + } + + var iterator = (0, _getIterator2.default)(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/map.js b/app/node_modules/async/internal/map.js new file mode 100644 index 0000000..f4f2aa5 --- /dev/null +++ b/app/node_modules/async/internal/map.js @@ -0,0 +1,35 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _asyncMap; + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _asyncMap(eachfn, arr, iteratee, callback) { + callback = callback || _noop2.default; + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = (0, _wrapAsync2.default)(iteratee); + + eachfn(arr, function (value, _, callback) { + var index = counter++; + _iteratee(value, function (err, v) { + results[index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/notId.js b/app/node_modules/async/internal/notId.js new file mode 100644 index 0000000..0106c92 --- /dev/null +++ b/app/node_modules/async/internal/notId.js @@ -0,0 +1,10 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = notId; +function notId(v) { + return !v; +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/app/node_modules/async/internal/once.js b/app/node_modules/async/internal/once.js new file mode 100644 index 0000000..f0c379f --- /dev/null +++ b/app/node_modules/async/internal/once.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = once; +function once(fn) { + return function () { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/app/node_modules/async/internal/onlyOnce.js b/app/node_modules/async/internal/onlyOnce.js new file mode 100644 index 0000000..f2e3001 --- /dev/null +++ b/app/node_modules/async/internal/onlyOnce.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = onlyOnce; +function onlyOnce(fn) { + return function () { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/app/node_modules/async/internal/parallel.js b/app/node_modules/async/internal/parallel.js new file mode 100644 index 0000000..c97293b --- /dev/null +++ b/app/node_modules/async/internal/parallel.js @@ -0,0 +1,42 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _parallel; + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _isArrayLike = require('lodash/isArrayLike'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _slice = require('./slice'); + +var _slice2 = _interopRequireDefault(_slice); + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _parallel(eachfn, tasks, callback) { + callback = callback || _noop2.default; + var results = (0, _isArrayLike2.default)(tasks) ? [] : {}; + + eachfn(tasks, function (task, key, callback) { + (0, _wrapAsync2.default)(task)(function (err, result) { + if (arguments.length > 2) { + result = (0, _slice2.default)(arguments, 1); + } + results[key] = result; + callback(err); + }); + }, function (err) { + callback(err, results); + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/queue.js b/app/node_modules/async/internal/queue.js new file mode 100644 index 0000000..19534a7 --- /dev/null +++ b/app/node_modules/async/internal/queue.js @@ -0,0 +1,204 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = queue; + +var _baseIndexOf = require('lodash/_baseIndexOf'); + +var _baseIndexOf2 = _interopRequireDefault(_baseIndexOf); + +var _isArray = require('lodash/isArray'); + +var _isArray2 = _interopRequireDefault(_isArray); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _onlyOnce = require('./onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _setImmediate = require('./setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _DoublyLinkedList = require('./DoublyLinkedList'); + +var _DoublyLinkedList2 = _interopRequireDefault(_DoublyLinkedList); + +var _wrapAsync = require('./wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var _worker = (0, _wrapAsync2.default)(worker); + var numRunning = 0; + var workersList = []; + + var processingScheduled = false; + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!(0, _isArray2.default)(data)) { + data = [data]; + } + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return (0, _setImmediate2.default)(function () { + q.drain(); + }); + } + + for (var i = 0, l = data.length; i < l; i++) { + var item = { + data: data[i], + callback: callback || _noop2.default + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + } + + if (!processingScheduled) { + processingScheduled = true; + (0, _setImmediate2.default)(function () { + processingScheduled = false; + q.process(); + }); + } + } + + function _next(tasks) { + return function (err) { + numRunning -= 1; + + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; + + var index = (0, _baseIndexOf2.default)(workersList, task, 0); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } + + task.callback.apply(task, arguments); + + if (err != null) { + q.error(err, task.data); + } + } + + if (numRunning <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + q.process(); + }; + } + + var isProcessing = false; + var q = { + _tasks: new _DoublyLinkedList2.default(), + concurrency: concurrency, + payload: payload, + saturated: _noop2.default, + unsaturated: _noop2.default, + buffer: concurrency / 4, + empty: _noop2.default, + drain: _noop2.default, + error: _noop2.default, + started: false, + paused: false, + push: function (data, callback) { + _insert(data, false, callback); + }, + kill: function () { + q.drain = _noop2.default; + q._tasks.empty(); + }, + unshift: function (data, callback) { + _insert(data, true, callback); + }, + remove: function (testFn) { + q._tasks.remove(testFn); + }, + process: function () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while (!q.paused && numRunning < q.concurrency && q._tasks.length) { + var tasks = [], + data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } + + numRunning += 1; + + if (q._tasks.length === 0) { + q.empty(); + } + + if (numRunning === q.concurrency) { + q.saturated(); + } + + var cb = (0, _onlyOnce2.default)(_next(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length: function () { + return q._tasks.length; + }, + running: function () { + return numRunning; + }, + workersList: function () { + return workersList; + }, + idle: function () { + return q._tasks.length + numRunning === 0; + }, + pause: function () { + q.paused = true; + }, + resume: function () { + if (q.paused === false) { + return; + } + q.paused = false; + (0, _setImmediate2.default)(q.process); + } + }; + return q; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/reject.js b/app/node_modules/async/internal/reject.js new file mode 100644 index 0000000..5dbfcfb --- /dev/null +++ b/app/node_modules/async/internal/reject.js @@ -0,0 +1,21 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reject; + +var _filter = require('./filter'); + +var _filter2 = _interopRequireDefault(_filter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function reject(eachfn, arr, iteratee, callback) { + (0, _filter2.default)(eachfn, arr, function (value, cb) { + iteratee(value, function (err, v) { + cb(err, !v); + }); + }, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/internal/setImmediate.js b/app/node_modules/async/internal/setImmediate.js new file mode 100644 index 0000000..3545f2b --- /dev/null +++ b/app/node_modules/async/internal/setImmediate.js @@ -0,0 +1,42 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.hasNextTick = exports.hasSetImmediate = undefined; +exports.fallback = fallback; +exports.wrap = wrap; + +var _slice = require('./slice'); + +var _slice2 = _interopRequireDefault(_slice); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var hasSetImmediate = exports.hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = exports.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + +function fallback(fn) { + setTimeout(fn, 0); +} + +function wrap(defer) { + return function (fn /*, ...args*/) { + var args = (0, _slice2.default)(arguments, 1); + defer(function () { + fn.apply(null, args); + }); + }; +} + +var _defer; + +if (hasSetImmediate) { + _defer = setImmediate; +} else if (hasNextTick) { + _defer = process.nextTick; +} else { + _defer = fallback; +} + +exports.default = wrap(_defer); \ No newline at end of file diff --git a/app/node_modules/async/internal/slice.js b/app/node_modules/async/internal/slice.js new file mode 100644 index 0000000..56f10c0 --- /dev/null +++ b/app/node_modules/async/internal/slice.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = slice; +function slice(arrayLike, start) { + start = start | 0; + var newLen = Math.max(arrayLike.length - start, 0); + var newArr = Array(newLen); + for (var idx = 0; idx < newLen; idx++) { + newArr[idx] = arrayLike[start + idx]; + } + return newArr; +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/app/node_modules/async/internal/withoutIndex.js b/app/node_modules/async/internal/withoutIndex.js new file mode 100644 index 0000000..2bd3579 --- /dev/null +++ b/app/node_modules/async/internal/withoutIndex.js @@ -0,0 +1,12 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _withoutIndex; +function _withoutIndex(iteratee) { + return function (value, index, callback) { + return iteratee(value, callback); + }; +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/app/node_modules/async/internal/wrapAsync.js b/app/node_modules/async/internal/wrapAsync.js new file mode 100644 index 0000000..bc6c966 --- /dev/null +++ b/app/node_modules/async/internal/wrapAsync.js @@ -0,0 +1,25 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isAsync = undefined; + +var _asyncify = require('../asyncify'); + +var _asyncify2 = _interopRequireDefault(_asyncify); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var supportsSymbol = typeof Symbol === 'function'; + +function isAsync(fn) { + return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; +} + +function wrapAsync(asyncFn) { + return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; +} + +exports.default = wrapAsync; +exports.isAsync = isAsync; \ No newline at end of file diff --git a/app/node_modules/async/log.js b/app/node_modules/async/log.js new file mode 100644 index 0000000..c643867 --- /dev/null +++ b/app/node_modules/async/log.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _consoleFunc = require('./internal/consoleFunc'); + +var _consoleFunc2 = _interopRequireDefault(_consoleFunc); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ +exports.default = (0, _consoleFunc2.default)('log'); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/map.js b/app/node_modules/async/map.js new file mode 100644 index 0000000..67c9cda --- /dev/null +++ b/app/node_modules/async/map.js @@ -0,0 +1,54 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _doParallel = require('./internal/doParallel'); + +var _doParallel2 = _interopRequireDefault(_doParallel); + +var _map = require('./internal/map'); + +var _map2 = _interopRequireDefault(_map); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callback + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @example + * + * async.map(['file1','file2','file3'], fs.stat, function(err, results) { + * // results is now an array of stats for each file + * }); + */ +exports.default = (0, _doParallel2.default)(_map2.default); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/mapLimit.js b/app/node_modules/async/mapLimit.js new file mode 100644 index 0000000..c8b60d8 --- /dev/null +++ b/app/node_modules/async/mapLimit.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _doParallelLimit = require('./internal/doParallelLimit'); + +var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); + +var _map = require('./internal/map'); + +var _map2 = _interopRequireDefault(_map); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + */ +exports.default = (0, _doParallelLimit2.default)(_map2.default); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/mapSeries.js b/app/node_modules/async/mapSeries.js new file mode 100644 index 0000000..61b42d0 --- /dev/null +++ b/app/node_modules/async/mapSeries.js @@ -0,0 +1,36 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _mapLimit = require('./mapLimit'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + */ +exports.default = (0, _doLimit2.default)(_mapLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/mapValues.js b/app/node_modules/async/mapValues.js new file mode 100644 index 0000000..3d838ca --- /dev/null +++ b/app/node_modules/async/mapValues.js @@ -0,0 +1,63 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _mapValuesLimit = require('./mapValuesLimit'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @example + * + * async.mapValues({ + * f1: 'file1', + * f2: 'file2', + * f3: 'file3' + * }, function (file, key, callback) { + * fs.stat(file, callback); + * }, function(err, result) { + * // result is now a map of stats for each file, e.g. + * // { + * // f1: [stats for file1], + * // f2: [stats for file2], + * // f3: [stats for file3] + * // } + * }); + */ + +exports.default = (0, _doLimit2.default)(_mapValuesLimit2.default, Infinity); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/mapValuesLimit.js b/app/node_modules/async/mapValuesLimit.js new file mode 100644 index 0000000..912a8b5 --- /dev/null +++ b/app/node_modules/async/mapValuesLimit.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mapValuesLimit; + +var _eachOfLimit = require('./eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + */ +function mapValuesLimit(obj, limit, iteratee, callback) { + callback = (0, _once2.default)(callback || _noop2.default); + var newObj = {}; + var _iteratee = (0, _wrapAsync2.default)(iteratee); + (0, _eachOfLimit2.default)(obj, limit, function (val, key, next) { + _iteratee(val, key, function (err, result) { + if (err) return next(err); + newObj[key] = result; + next(); + }); + }, function (err) { + callback(err, newObj); + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/mapValuesSeries.js b/app/node_modules/async/mapValuesSeries.js new file mode 100644 index 0000000..b378c4a --- /dev/null +++ b/app/node_modules/async/mapValuesSeries.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _mapValuesLimit = require('./mapValuesLimit'); + +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + */ +exports.default = (0, _doLimit2.default)(_mapValuesLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/memoize.js b/app/node_modules/async/memoize.js new file mode 100644 index 0000000..1f2b566 --- /dev/null +++ b/app/node_modules/async/memoize.js @@ -0,0 +1,101 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = memoize; + +var _identity = require('lodash/identity'); + +var _identity2 = _interopRequireDefault(_identity); + +var _slice = require('./internal/slice'); + +var _slice2 = _interopRequireDefault(_slice); + +var _setImmediate = require('./internal/setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _initialParams = require('./internal/initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function has(obj, key) { + return key in obj; +} + +/** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ +function memoize(fn, hasher) { + var memo = Object.create(null); + var queues = Object.create(null); + hasher = hasher || _identity2.default; + var _fn = (0, _wrapAsync2.default)(fn); + var memoized = (0, _initialParams2.default)(function memoized(args, callback) { + var key = hasher.apply(null, args); + if (has(memo, key)) { + (0, _setImmediate2.default)(function () { + callback.apply(null, memo[key]); + }); + } else if (has(queues, key)) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn.apply(null, args.concat(function () /*args*/{ + var args = (0, _slice2.default)(arguments); + memo[key] = args; + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(null, args); + } + })); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/nextTick.js b/app/node_modules/async/nextTick.js new file mode 100644 index 0000000..826495d --- /dev/null +++ b/app/node_modules/async/nextTick.js @@ -0,0 +1,51 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _setImmediate = require('./internal/setImmediate'); + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTicl`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +var _defer; + +if (_setImmediate.hasNextTick) { + _defer = process.nextTick; +} else if (_setImmediate.hasSetImmediate) { + _defer = setImmediate; +} else { + _defer = _setImmediate.fallback; +} + +exports.default = (0, _setImmediate.wrap)(_defer); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/package.json b/app/node_modules/async/package.json new file mode 100644 index 0000000..f672e7d --- /dev/null +++ b/app/node_modules/async/package.json @@ -0,0 +1,83 @@ +{ + "name": "async", + "description": "Higher-order functions and common patterns for asynchronous code", + "version": "2.6.0", + "main": "dist/async.js", + "author": "Caolan McMahon", + "homepage": "https://caolan.github.io/async/", + "repository": { + "type": "git", + "url": "https://github.com/caolan/async.git" + }, + "bugs": { + "url": "https://github.com/caolan/async/issues" + }, + "keywords": [ + "async", + "callback", + "module", + "utility" + ], + "dependencies": { + "lodash": "^4.14.0" + }, + "devDependencies": { + "babel-cli": "^6.24.0", + "babel-core": "^6.24.0", + "babel-plugin-add-module-exports": "^0.2.1", + "babel-plugin-istanbul": "^2.0.1", + "babel-plugin-transform-es2015-modules-commonjs": "^6.3.16", + "babel-preset-es2015": "^6.3.13", + "babel-preset-es2017": "^6.22.0", + "babelify": "^7.2.0", + "benchmark": "^2.1.1", + "bluebird": "^3.4.6", + "chai": "^3.1.0", + "cheerio": "^0.22.0", + "coveralls": "^2.11.2", + "es6-promise": "^2.3.0", + "eslint": "^2.13.1", + "fs-extra": "^0.26.7", + "gh-pages-deploy": "^0.4.2", + "jsdoc": "^3.4.0", + "karma": "^1.3.0", + "karma-browserify": "^5.1.0", + "karma-firefox-launcher": "^1.0.0", + "karma-mocha": "^1.2.0", + "karma-mocha-reporter": "^2.2.0", + "mocha": "^3.1.2", + "native-promise-only": "^0.8.0-a", + "nyc": "^7.0.0", + "recursive-readdir": "^1.3.0", + "rimraf": "^2.5.0", + "rollup": "^0.36.3", + "rollup-plugin-node-resolve": "^2.0.0", + "rollup-plugin-npm": "^2.0.0", + "rsvp": "^3.0.18", + "semver": "^4.3.6", + "uglify-js": "~2.7.3", + "vinyl-buffer": "^1.0.0", + "vinyl-source-stream": "^1.1.0", + "watchify": "^3.7.0", + "yargs": "~3.9.1" + }, + "scripts": { + "coverage": "nyc npm run mocha-node-test -- --grep @nycinvalid --invert", + "coveralls": "npm run coverage && nyc report --reporter=text-lcov | coveralls", + "jsdoc": "jsdoc -c ./support/jsdoc/jsdoc.json && node support/jsdoc/jsdoc-fix-html.js", + "lint": "eslint lib/ mocha_test/ perf/memory.js perf/suites.js perf/benchmark.js support/build/ support/*.js karma.conf.js", + "mocha-browser-test": "karma start", + "mocha-node-test": "mocha mocha_test/ --compilers js:babel-core/register", + "mocha-test": "npm run mocha-node-test && npm run mocha-browser-test", + "test": "npm run lint && npm run mocha-node-test" + }, + "license": "MIT", + "gh-pages-deploy": { + "staticpath": "docs" + }, + "nyc": { + "exclude": [ + "mocha_test" + ] + } +} \ No newline at end of file diff --git a/app/node_modules/async/parallel.js b/app/node_modules/async/parallel.js new file mode 100644 index 0000000..da28a4d --- /dev/null +++ b/app/node_modules/async/parallel.js @@ -0,0 +1,90 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parallelLimit; + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _parallel = require('./internal/parallel'); + +var _parallel2 = _interopRequireDefault(_parallel); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * + * @example + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // optional callback + * function(err, results) { + * // the results array will equal ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equals to: {one: 1, two: 2} + * }); + */ +function parallelLimit(tasks, callback) { + (0, _parallel2.default)(_eachOf2.default, tasks, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/parallelLimit.js b/app/node_modules/async/parallelLimit.js new file mode 100644 index 0000000..a026526 --- /dev/null +++ b/app/node_modules/async/parallelLimit.js @@ -0,0 +1,40 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parallelLimit; + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _parallel = require('./internal/parallel'); + +var _parallel2 = _interopRequireDefault(_parallel); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + */ +function parallelLimit(tasks, limit, callback) { + (0, _parallel2.default)((0, _eachOfLimit2.default)(limit), tasks, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/priorityQueue.js b/app/node_modules/async/priorityQueue.js new file mode 100644 index 0000000..3a5f023 --- /dev/null +++ b/app/node_modules/async/priorityQueue.js @@ -0,0 +1,98 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (worker, concurrency) { + // Start with a normal queue + var q = (0, _queue2.default)(worker, concurrency); + + // Override push to accept second parameter representing priority + q.push = function (data, priority, callback) { + if (callback == null) callback = _noop2.default; + if (typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!(0, _isArray2.default)(data)) { + data = [data]; + } + if (data.length === 0) { + // call drain immediately if there are no tasks + return (0, _setImmediate2.default)(function () { + q.drain(); + }); + } + + priority = priority || 0; + var nextNode = q._tasks.head; + while (nextNode && priority >= nextNode.priority) { + nextNode = nextNode.next; + } + + for (var i = 0, l = data.length; i < l; i++) { + var item = { + data: data[i], + priority: priority, + callback: callback + }; + + if (nextNode) { + q._tasks.insertBefore(nextNode, item); + } else { + q._tasks.push(item); + } + } + (0, _setImmediate2.default)(q.process); + }; + + // Remove unshift function + delete q.unshift; + + return q; +}; + +var _isArray = require('lodash/isArray'); + +var _isArray2 = _interopRequireDefault(_isArray); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _setImmediate = require('./setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _queue = require('./queue'); + +var _queue2 = _interopRequireDefault(_queue); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports['default']; + +/** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * The `unshift` method was removed. + */ \ No newline at end of file diff --git a/app/node_modules/async/queue.js b/app/node_modules/async/queue.js new file mode 100644 index 0000000..0ca8ba2 --- /dev/null +++ b/app/node_modules/async/queue.js @@ -0,0 +1,130 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (worker, concurrency) { + var _worker = (0, _wrapAsync2.default)(worker); + return (0, _queue2.default)(function (items, cb) { + _worker(items[0], cb); + }, concurrency, 1); +}; + +var _queue = require('./internal/queue'); + +var _queue2 = _interopRequireDefault(_queue); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports['default']; + +/** + * A queue of tasks for the worker function to complete. + * @typedef {Object} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {Function} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {Function} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a callback that is called when the number of + * running workers hits the `concurrency` limit, and further tasks will be + * queued. + * @property {Function} unsaturated - a callback that is called when the number + * of running workers is less than the `concurrency` & `buffer` limits, and + * further tasks will not be queued. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a callback that is called when the last item + * from the `queue` is given to a `worker`. + * @property {Function} drain - a callback that is called when the last item + * from the `queue` has returned from the `worker`. + * @property {Function} error - a callback that is called when a task errors. + * Has the signature `function(error, task)`. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + */ + +/** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain = function() { + * console.log('all items have been processed'); + * }; + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * q.push({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ \ No newline at end of file diff --git a/app/node_modules/async/race.js b/app/node_modules/async/race.js new file mode 100644 index 0000000..6713c74 --- /dev/null +++ b/app/node_modules/async/race.js @@ -0,0 +1,70 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = race; + +var _isArray = require('lodash/isArray'); + +var _isArray2 = _interopRequireDefault(_isArray); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns undefined + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ +function race(tasks, callback) { + callback = (0, _once2.default)(callback || _noop2.default); + if (!(0, _isArray2.default)(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + (0, _wrapAsync2.default)(tasks[i])(callback); + } +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/reduce.js b/app/node_modules/async/reduce.js new file mode 100644 index 0000000..3fb8019 --- /dev/null +++ b/app/node_modules/async/reduce.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduce; + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @example + * + * async.reduce([1,2,3], 0, function(memo, item, callback) { + * // pointless async: + * process.nextTick(function() { + * callback(null, memo + item) + * }); + * }, function(err, result) { + * // result is now equal to the last value of memo, which is 6 + * }); + */ +function reduce(coll, memo, iteratee, callback) { + callback = (0, _once2.default)(callback || _noop2.default); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + (0, _eachOfSeries2.default)(coll, function (x, i, callback) { + _iteratee(memo, x, function (err, v) { + memo = v; + callback(err); + }); + }, function (err) { + callback(err, memo); + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/reduceRight.js b/app/node_modules/async/reduceRight.js new file mode 100644 index 0000000..3d17d32 --- /dev/null +++ b/app/node_modules/async/reduceRight.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reduceRight; + +var _reduce = require('./reduce'); + +var _reduce2 = _interopRequireDefault(_reduce); + +var _slice = require('./internal/slice'); + +var _slice2 = _interopRequireDefault(_slice); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee complete with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + */ +function reduceRight(array, memo, iteratee, callback) { + var reversed = (0, _slice2.default)(array).reverse(); + (0, _reduce2.default)(reversed, memo, iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/reflect.js b/app/node_modules/async/reflect.js new file mode 100644 index 0000000..098ba86 --- /dev/null +++ b/app/node_modules/async/reflect.js @@ -0,0 +1,81 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reflect; + +var _initialParams = require('./internal/initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _slice = require('./internal/slice'); + +var _slice2 = _interopRequireDefault(_slice); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ +function reflect(fn) { + var _fn = (0, _wrapAsync2.default)(fn); + return (0, _initialParams2.default)(function reflectOn(args, reflectCallback) { + args.push(function callback(error, cbArg) { + if (error) { + reflectCallback(null, { error: error }); + } else { + var value; + if (arguments.length <= 2) { + value = cbArg; + } else { + value = (0, _slice2.default)(arguments, 1); + } + reflectCallback(null, { value: value }); + } + }); + + return _fn.apply(this, args); + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/reflectAll.js b/app/node_modules/async/reflectAll.js new file mode 100644 index 0000000..966e83d --- /dev/null +++ b/app/node_modules/async/reflectAll.js @@ -0,0 +1,105 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = reflectAll; + +var _reflect = require('./reflect'); + +var _reflect2 = _interopRequireDefault(_reflect); + +var _isArray = require('lodash/isArray'); + +var _isArray2 = _interopRequireDefault(_isArray); + +var _arrayMap2 = require('lodash/_arrayMap'); + +var _arrayMap3 = _interopRequireDefault(_arrayMap2); + +var _baseForOwn = require('lodash/_baseForOwn'); + +var _baseForOwn2 = _interopRequireDefault(_baseForOwn); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ +function reflectAll(tasks) { + var results; + if ((0, _isArray2.default)(tasks)) { + results = (0, _arrayMap3.default)(tasks, _reflect2.default); + } else { + results = {}; + (0, _baseForOwn2.default)(tasks, function (task, key) { + results[key] = _reflect2.default.call(this, task); + }); + } + return results; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/reject.js b/app/node_modules/async/reject.js new file mode 100644 index 0000000..53802b5 --- /dev/null +++ b/app/node_modules/async/reject.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject = require('./internal/reject'); + +var _reject2 = _interopRequireDefault(_reject); + +var _doParallel = require('./internal/doParallel'); + +var _doParallel2 = _interopRequireDefault(_doParallel); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @example + * + * async.reject(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of missing files + * createFiles(results); + * }); + */ +exports.default = (0, _doParallel2.default)(_reject2.default); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/rejectLimit.js b/app/node_modules/async/rejectLimit.js new file mode 100644 index 0000000..74bba7f --- /dev/null +++ b/app/node_modules/async/rejectLimit.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _reject = require('./internal/reject'); + +var _reject2 = _interopRequireDefault(_reject); + +var _doParallelLimit = require('./internal/doParallelLimit'); + +var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + */ +exports.default = (0, _doParallelLimit2.default)(_reject2.default); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/rejectSeries.js b/app/node_modules/async/rejectSeries.js new file mode 100644 index 0000000..f905588 --- /dev/null +++ b/app/node_modules/async/rejectSeries.js @@ -0,0 +1,35 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _rejectLimit = require('./rejectLimit'); + +var _rejectLimit2 = _interopRequireDefault(_rejectLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + */ +exports.default = (0, _doLimit2.default)(_rejectLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/retry.js b/app/node_modules/async/retry.js new file mode 100644 index 0000000..6a1aa1e --- /dev/null +++ b/app/node_modules/async/retry.js @@ -0,0 +1,156 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = retry; + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _constant = require('lodash/constant'); + +var _constant2 = _interopRequireDefault(_constant); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ +function retry(opts, task, callback) { + var DEFAULT_TIMES = 5; + var DEFAULT_INTERVAL = 0; + + var options = { + times: DEFAULT_TIMES, + intervalFunc: (0, _constant2.default)(DEFAULT_INTERVAL) + }; + + function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; + + acc.intervalFunc = typeof t.interval === 'function' ? t.interval : (0, _constant2.default)(+t.interval || DEFAULT_INTERVAL); + + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } + } + + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || _noop2.default; + task = opts; + } else { + parseTimes(options, opts); + callback = callback || _noop2.default; + } + + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } + + var _task = (0, _wrapAsync2.default)(task); + + var attempt = 1; + function retryAttempt() { + _task(function (err) { + if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt)); + } else { + callback.apply(null, arguments); + } + }); + } + + retryAttempt(); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/retryable.js b/app/node_modules/async/retryable.js new file mode 100644 index 0000000..002bfb0 --- /dev/null +++ b/app/node_modules/async/retryable.js @@ -0,0 +1,65 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (opts, task) { + if (!task) { + task = opts; + opts = null; + } + var _task = (0, _wrapAsync2.default)(task); + return (0, _initialParams2.default)(function (args, callback) { + function taskFn(cb) { + _task.apply(null, args.concat(cb)); + } + + if (opts) (0, _retry2.default)(opts, taskFn, callback);else (0, _retry2.default)(taskFn, callback); + }); +}; + +var _retry = require('./retry'); + +var _retry2 = _interopRequireDefault(_retry); + +var _initialParams = require('./internal/initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports['default']; + +/** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ \ No newline at end of file diff --git a/app/node_modules/async/select.js b/app/node_modules/async/select.js new file mode 100644 index 0000000..54772d5 --- /dev/null +++ b/app/node_modules/async/select.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter = require('./internal/filter'); + +var _filter2 = _interopRequireDefault(_filter); + +var _doParallel = require('./internal/doParallel'); + +var _doParallel2 = _interopRequireDefault(_doParallel); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @example + * + * async.filter(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, results) { + * // results now equals an array of the existing files + * }); + */ +exports.default = (0, _doParallel2.default)(_filter2.default); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/selectLimit.js b/app/node_modules/async/selectLimit.js new file mode 100644 index 0000000..06216f7 --- /dev/null +++ b/app/node_modules/async/selectLimit.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filter = require('./internal/filter'); + +var _filter2 = _interopRequireDefault(_filter); + +var _doParallelLimit = require('./internal/doParallelLimit'); + +var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + */ +exports.default = (0, _doParallelLimit2.default)(_filter2.default); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/selectSeries.js b/app/node_modules/async/selectSeries.js new file mode 100644 index 0000000..e48d966 --- /dev/null +++ b/app/node_modules/async/selectSeries.js @@ -0,0 +1,35 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _filterLimit = require('./filterLimit'); + +var _filterLimit2 = _interopRequireDefault(_filterLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + */ +exports.default = (0, _doLimit2.default)(_filterLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/seq.js b/app/node_modules/async/seq.js new file mode 100644 index 0000000..ff86ef9 --- /dev/null +++ b/app/node_modules/async/seq.js @@ -0,0 +1,91 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = seq; + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _slice = require('./internal/slice'); + +var _slice2 = _interopRequireDefault(_slice); + +var _reduce = require('./reduce'); + +var _reduce2 = _interopRequireDefault(_reduce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _arrayMap = require('lodash/_arrayMap'); + +var _arrayMap2 = _interopRequireDefault(_arrayMap); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ +function seq() /*...functions*/{ + var _functions = (0, _arrayMap2.default)(arguments, _wrapAsync2.default); + return function () /*...args*/{ + var args = (0, _slice2.default)(arguments); + var that = this; + + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = _noop2.default; + } + + (0, _reduce2.default)(_functions, args, function (newargs, fn, cb) { + fn.apply(that, newargs.concat(function (err /*, ...nextargs*/) { + var nextargs = (0, _slice2.default)(arguments, 1); + cb(err, nextargs); + })); + }, function (err, results) { + cb.apply(that, [err].concat(results)); + }); + }; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/series.js b/app/node_modules/async/series.js new file mode 100644 index 0000000..e8c2928 --- /dev/null +++ b/app/node_modules/async/series.js @@ -0,0 +1,85 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = series; + +var _parallel = require('./internal/parallel'); + +var _parallel2 = _interopRequireDefault(_parallel); + +var _eachOfSeries = require('./eachOfSeries'); + +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @example + * async.series([ + * function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }, + * function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * } + * ], + * // optional callback + * function(err, results) { + * // results is now equal to ['one', 'two'] + * }); + * + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback){ + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * // results is now equal to: {one: 1, two: 2} + * }); + */ +function series(tasks, callback) { + (0, _parallel2.default)(_eachOfSeries2.default, tasks, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/setImmediate.js b/app/node_modules/async/setImmediate.js new file mode 100644 index 0000000..e52f7c5 --- /dev/null +++ b/app/node_modules/async/setImmediate.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _setImmediate = require('./internal/setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `setImmediate`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name setImmediate + * @static + * @memberOf module:Utils + * @method + * @see [async.nextTick]{@link module:Utils.nextTick} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ +exports.default = _setImmediate2.default; +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/some.js b/app/node_modules/async/some.js new file mode 100644 index 0000000..a8e70f7 --- /dev/null +++ b/app/node_modules/async/some.js @@ -0,0 +1,52 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _doParallel = require('./internal/doParallel'); + +var _doParallel2 = _interopRequireDefault(_doParallel); + +var _identity = require('lodash/identity'); + +var _identity2 = _interopRequireDefault(_identity); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @example + * + * async.some(['file1','file2','file3'], function(filePath, callback) { + * fs.access(filePath, function(err) { + * callback(null, !err) + * }); + * }, function(err, result) { + * // if result is true then at least one of the files exists + * }); + */ +exports.default = (0, _doParallel2.default)((0, _createTester2.default)(Boolean, _identity2.default)); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/someLimit.js b/app/node_modules/async/someLimit.js new file mode 100644 index 0000000..24ca3f4 --- /dev/null +++ b/app/node_modules/async/someLimit.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _createTester = require('./internal/createTester'); + +var _createTester2 = _interopRequireDefault(_createTester); + +var _doParallelLimit = require('./internal/doParallelLimit'); + +var _doParallelLimit2 = _interopRequireDefault(_doParallelLimit); + +var _identity = require('lodash/identity'); + +var _identity2 = _interopRequireDefault(_identity); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + */ +exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(Boolean, _identity2.default)); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/someSeries.js b/app/node_modules/async/someSeries.js new file mode 100644 index 0000000..dc24ed2 --- /dev/null +++ b/app/node_modules/async/someSeries.js @@ -0,0 +1,38 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _someLimit = require('./someLimit'); + +var _someLimit2 = _interopRequireDefault(_someLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + */ +exports.default = (0, _doLimit2.default)(_someLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/sortBy.js b/app/node_modules/async/sortBy.js new file mode 100644 index 0000000..ee5e93d --- /dev/null +++ b/app/node_modules/async/sortBy.js @@ -0,0 +1,91 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = sortBy; + +var _arrayMap = require('lodash/_arrayMap'); + +var _arrayMap2 = _interopRequireDefault(_arrayMap); + +var _baseProperty = require('lodash/_baseProperty'); + +var _baseProperty2 = _interopRequireDefault(_baseProperty); + +var _map = require('./map'); + +var _map2 = _interopRequireDefault(_map); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @example + * + * async.sortBy(['file1','file2','file3'], function(file, callback) { + * fs.stat(file, function(err, stats) { + * callback(err, stats.mtime); + * }); + * }, function(err, results) { + * // results is now the original array of files sorted by + * // modified date + * }); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x); + * }, function(err,result) { + * // result callback + * }); + * + * // descending order + * async.sortBy([1,9,3,5], function(x, callback) { + * callback(null, x*-1); //<- x*-1 instead of x, turns the order around + * }, function(err,result) { + * // result callback + * }); + */ +function sortBy(coll, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + (0, _map2.default)(coll, function (x, callback) { + _iteratee(x, function (err, criteria) { + if (err) return callback(err); + callback(null, { value: x, criteria: criteria }); + }); + }, function (err, results) { + if (err) return callback(err); + callback(null, (0, _arrayMap2.default)(results.sort(comparator), (0, _baseProperty2.default)('value'))); + }); + + function comparator(left, right) { + var a = left.criteria, + b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/timeout.js b/app/node_modules/async/timeout.js new file mode 100644 index 0000000..b5cb505 --- /dev/null +++ b/app/node_modules/async/timeout.js @@ -0,0 +1,89 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timeout; + +var _initialParams = require('./internal/initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ +function timeout(asyncFn, milliseconds, info) { + var fn = (0, _wrapAsync2.default)(asyncFn); + + return (0, _initialParams2.default)(function (args, callback) { + var timedOut = false; + var timer; + + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } + + args.push(function () { + if (!timedOut) { + callback.apply(null, arguments); + clearTimeout(timer); + } + }); + + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn.apply(null, args); + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/times.js b/app/node_modules/async/times.js new file mode 100644 index 0000000..b5ca24d --- /dev/null +++ b/app/node_modules/async/times.js @@ -0,0 +1,50 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _timesLimit = require('./timesLimit'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ +exports.default = (0, _doLimit2.default)(_timesLimit2.default, Infinity); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/timesLimit.js b/app/node_modules/async/timesLimit.js new file mode 100644 index 0000000..aad8495 --- /dev/null +++ b/app/node_modules/async/timesLimit.js @@ -0,0 +1,42 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = timeLimit; + +var _mapLimit = require('./mapLimit'); + +var _mapLimit2 = _interopRequireDefault(_mapLimit); + +var _baseRange = require('lodash/_baseRange'); + +var _baseRange2 = _interopRequireDefault(_baseRange); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + */ +function timeLimit(count, limit, iteratee, callback) { + var _iteratee = (0, _wrapAsync2.default)(iteratee); + (0, _mapLimit2.default)((0, _baseRange2.default)(0, count, 1), limit, _iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/timesSeries.js b/app/node_modules/async/timesSeries.js new file mode 100644 index 0000000..f187a35 --- /dev/null +++ b/app/node_modules/async/timesSeries.js @@ -0,0 +1,32 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _timesLimit = require('./timesLimit'); + +var _timesLimit2 = _interopRequireDefault(_timesLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + */ +exports.default = (0, _doLimit2.default)(_timesLimit2.default, 1); +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/transform.js b/app/node_modules/async/transform.js new file mode 100644 index 0000000..84ee217 --- /dev/null +++ b/app/node_modules/async/transform.js @@ -0,0 +1,87 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = transform; + +var _isArray = require('lodash/isArray'); + +var _isArray2 = _interopRequireDefault(_isArray); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _eachOf = require('./eachOf'); + +var _eachOf2 = _interopRequireDefault(_eachOf); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in series, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @example + * + * async.transform([1,2,3], function(acc, item, index, callback) { + * // pointless async: + * process.nextTick(function() { + * acc.push(item * 2) + * callback(null) + * }); + * }, function(err, result) { + * // result is now equal to [2, 4, 6] + * }); + * + * @example + * + * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { + * setImmediate(function () { + * obj[key] = val * 2; + * callback(); + * }) + * }, function (err, result) { + * // result is equal to {a: 2, b: 4, c: 6} + * }) + */ +function transform(coll, accumulator, iteratee, callback) { + if (arguments.length <= 3) { + callback = iteratee; + iteratee = accumulator; + accumulator = (0, _isArray2.default)(coll) ? [] : {}; + } + callback = (0, _once2.default)(callback || _noop2.default); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + + (0, _eachOf2.default)(coll, function (v, k, cb) { + _iteratee(accumulator, v, k, cb); + }, function (err) { + callback(err, accumulator); + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/tryEach.js b/app/node_modules/async/tryEach.js new file mode 100644 index 0000000..f4e4c97 --- /dev/null +++ b/app/node_modules/async/tryEach.js @@ -0,0 +1,81 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = tryEach; + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _eachSeries = require('./eachSeries'); + +var _eachSeries2 = _interopRequireDefault(_eachSeries); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +var _slice = require('./internal/slice'); + +var _slice2 = _interopRequireDefault(_slice); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ +function tryEach(tasks, callback) { + var error = null; + var result; + callback = callback || _noop2.default; + (0, _eachSeries2.default)(tasks, function (task, callback) { + (0, _wrapAsync2.default)(task)(function (err, res /*, ...args*/) { + if (arguments.length > 2) { + result = (0, _slice2.default)(arguments, 1); + } else { + result = res; + } + error = err; + callback(!err); + }); + }, function () { + callback(error, result); + }); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/unmemoize.js b/app/node_modules/async/unmemoize.js new file mode 100644 index 0000000..08f9f9f --- /dev/null +++ b/app/node_modules/async/unmemoize.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = unmemoize; +/** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ +function unmemoize(fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; +} +module.exports = exports["default"]; \ No newline at end of file diff --git a/app/node_modules/async/until.js b/app/node_modules/async/until.js new file mode 100644 index 0000000..29955ab --- /dev/null +++ b/app/node_modules/async/until.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = until; + +var _whilst = require('./whilst'); + +var _whilst2 = _interopRequireDefault(_whilst); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {Function} test - synchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + */ +function until(test, iteratee, callback) { + (0, _whilst2.default)(function () { + return !test.apply(this, arguments); + }, iteratee, callback); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/waterfall.js b/app/node_modules/async/waterfall.js new file mode 100644 index 0000000..d547d6b --- /dev/null +++ b/app/node_modules/async/waterfall.js @@ -0,0 +1,113 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (tasks, callback) { + callback = (0, _once2.default)(callback || _noop2.default); + if (!(0, _isArray2.default)(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + + function nextTask(args) { + var task = (0, _wrapAsync2.default)(tasks[taskIndex++]); + args.push((0, _onlyOnce2.default)(next)); + task.apply(null, args); + } + + function next(err /*, ...args*/) { + if (err || taskIndex === tasks.length) { + return callback.apply(null, arguments); + } + nextTask((0, _slice2.default)(arguments, 1)); + } + + nextTask([]); +}; + +var _isArray = require('lodash/isArray'); + +var _isArray2 = _interopRequireDefault(_isArray); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _once = require('./internal/once'); + +var _once2 = _interopRequireDefault(_once); + +var _slice = require('./internal/slice'); + +var _slice2 = _interopRequireDefault(_slice); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports['default']; + +/** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns undefined + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ \ No newline at end of file diff --git a/app/node_modules/async/whilst.js b/app/node_modules/async/whilst.js new file mode 100644 index 0000000..9c4d8f6 --- /dev/null +++ b/app/node_modules/async/whilst.js @@ -0,0 +1,72 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = whilst; + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _slice = require('./internal/slice'); + +var _slice2 = _interopRequireDefault(_slice); + +var _onlyOnce = require('./internal/onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _wrapAsync = require('./internal/wrapAsync'); + +var _wrapAsync2 = _interopRequireDefault(_wrapAsync); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Function} test - synchronous truth test to perform before each + * execution of `iteratee`. Invoked with (). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns undefined + * @example + * + * var count = 0; + * async.whilst( + * function() { return count < 5; }, + * function(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ +function whilst(test, iteratee, callback) { + callback = (0, _onlyOnce2.default)(callback || _noop2.default); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + if (!test()) return callback(null); + var next = function (err /*, ...args*/) { + if (err) return callback(err); + if (test()) return _iteratee(next); + var args = (0, _slice2.default)(arguments, 1); + callback.apply(null, [null].concat(args)); + }; + _iteratee(next); +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/async/wrapSync.js b/app/node_modules/async/wrapSync.js new file mode 100644 index 0000000..5e3fc91 --- /dev/null +++ b/app/node_modules/async/wrapSync.js @@ -0,0 +1,110 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncify; + +var _isObject = require('lodash/isObject'); + +var _isObject2 = _interopRequireDefault(_isObject); + +var _initialParams = require('./internal/initialParams'); + +var _initialParams2 = _interopRequireDefault(_initialParams); + +var _setImmediate = require('./internal/setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ +function asyncify(func) { + return (0, _initialParams2.default)(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if ((0, _isObject2.default)(result) && typeof result.then === 'function') { + result.then(function (value) { + invokeCallback(callback, null, value); + }, function (err) { + invokeCallback(callback, err.message ? err : new Error(err)); + }); + } else { + callback(null, result); + } + }); +} + +function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (e) { + (0, _setImmediate2.default)(rethrow, e); + } +} + +function rethrow(error) { + throw error; +} +module.exports = exports['default']; \ No newline at end of file diff --git a/app/node_modules/basic-auth/HISTORY.md b/app/node_modules/basic-auth/HISTORY.md new file mode 100644 index 0000000..2c44a01 --- /dev/null +++ b/app/node_modules/basic-auth/HISTORY.md @@ -0,0 +1,52 @@ +2.0.1 / 2018-09-19 +================== + + * deps: safe-buffer@5.1.2 + +2.0.0 / 2017-09-12 +================== + + * Drop support for Node.js below 0.8 + * Remove `auth(ctx)` signature -- pass in header or `auth(ctx.req)` + * Use `safe-buffer` for improved Buffer API + +1.1.0 / 2016-11-18 +================== + + * Add `auth.parse` for low-level string parsing + +1.0.4 / 2016-05-10 +================== + + * Improve error message when `req` argument is not an object + * Improve error message when `req` missing `headers` property + +1.0.3 / 2015-07-01 +================== + + * Fix regression accepting a Koa context + +1.0.2 / 2015-06-12 +================== + + * Improve error message when `req` argument missing + * perf: enable strict mode + * perf: hoist regular expression + * perf: parse with regular expressions + * perf: remove argument reassignment + +1.0.1 / 2015-05-04 +================== + + * Update readme + +1.0.0 / 2014-07-01 +================== + + * Support empty password + * Support empty username + +0.0.1 / 2013-11-30 +================== + + * Initial release diff --git a/app/node_modules/basic-auth/LICENSE b/app/node_modules/basic-auth/LICENSE new file mode 100644 index 0000000..89041f6 --- /dev/null +++ b/app/node_modules/basic-auth/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2013 TJ Holowaychuk +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015-2016 Douglas Christopher Wilson + +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/app/node_modules/basic-auth/README.md b/app/node_modules/basic-auth/README.md new file mode 100644 index 0000000..5f3d758 --- /dev/null +++ b/app/node_modules/basic-auth/README.md @@ -0,0 +1,113 @@ +# basic-auth + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Generic basic auth Authorization header field parser for whatever. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +``` +$ npm install basic-auth +``` + +## API + + + +```js +var auth = require('basic-auth') +``` + +### auth(req) + +Get the basic auth credentials from the given request. The `Authorization` +header is parsed and if the header is invalid, `undefined` is returned, +otherwise an object with `name` and `pass` properties. + +### auth.parse(string) + +Parse a basic auth authorization header string. This will return an object +with `name` and `pass` properties, or `undefined` if the string is invalid. + +## Example + +Pass a Node.js request object to the module export. If parsing fails +`undefined` is returned, otherwise an object with `.name` and `.pass`. + + + +```js +var auth = require('basic-auth') +var user = auth(req) +// => { name: 'something', pass: 'whatever' } +``` + +A header string from any other location can also be parsed with +`auth.parse`, for example a `Proxy-Authorization` header: + + + +```js +var auth = require('basic-auth') +var user = auth.parse(req.getHeader('Proxy-Authorization')) +``` + +### With vanilla node.js http server + +```js +var http = require('http') +var auth = require('basic-auth') +var compare = require('tsscmp') + +// Create server +var server = http.createServer(function (req, res) { + var credentials = auth(req) + + // Check credentials + // The "check" function will typically be against your user store + if (!credentials || !check(credentials.name, credentials.pass)) { + res.statusCode = 401 + res.setHeader('WWW-Authenticate', 'Basic realm="example"') + res.end('Access denied') + } else { + res.end('Access granted') + } +}) + +// Basic function to validate credentials for example +function check (name, pass) { + var valid = true + + // Simple method to prevent short-circut and use timing-safe compare + valid = compare(name, 'john') && valid + valid = compare(pass, 'secret') && valid + + return valid +} + +// Listen +server.listen(3000) +``` + +# License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/basic-auth/master +[coveralls-url]: https://coveralls.io/r/jshttp/basic-auth?branch=master +[downloads-image]: https://badgen.net/npm/dm/basic-auth +[downloads-url]: https://npmjs.org/package/basic-auth +[node-version-image]: https://badgen.net/npm/node/basic-auth +[node-version-url]: https://nodejs.org/en/download +[npm-image]: https://badgen.net/npm/v/basic-auth +[npm-url]: https://npmjs.org/package/basic-auth +[travis-image]: https://badgen.net/travis/jshttp/basic-auth/master +[travis-url]: https://travis-ci.org/jshttp/basic-auth diff --git a/app/node_modules/basic-auth/index.js b/app/node_modules/basic-auth/index.js new file mode 100644 index 0000000..9106e64 --- /dev/null +++ b/app/node_modules/basic-auth/index.js @@ -0,0 +1,133 @@ +/*! + * basic-auth + * Copyright(c) 2013 TJ Holowaychuk + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('safe-buffer').Buffer + +/** + * Module exports. + * @public + */ + +module.exports = auth +module.exports.parse = parse + +/** + * RegExp for basic auth credentials + * + * credentials = auth-scheme 1*SP token68 + * auth-scheme = "Basic" ; case insensitive + * token68 = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"=" + * @private + */ + +var CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/ + +/** + * RegExp for basic auth user/pass + * + * user-pass = userid ":" password + * userid = * + * password = *TEXT + * @private + */ + +var USER_PASS_REGEXP = /^([^:]*):(.*)$/ + +/** + * Parse the Authorization header field of a request. + * + * @param {object} req + * @return {object} with .name and .pass + * @public + */ + +function auth (req) { + if (!req) { + throw new TypeError('argument req is required') + } + + if (typeof req !== 'object') { + throw new TypeError('argument req is required to be an object') + } + + // get header + var header = getAuthorization(req) + + // parse header + return parse(header) +} + +/** + * Decode base64 string. + * @private + */ + +function decodeBase64 (str) { + return Buffer.from(str, 'base64').toString() +} + +/** + * Get the Authorization header from request object. + * @private + */ + +function getAuthorization (req) { + if (!req.headers || typeof req.headers !== 'object') { + throw new TypeError('argument req is required to have headers property') + } + + return req.headers.authorization +} + +/** + * Parse basic auth to object. + * + * @param {string} string + * @return {object} + * @public + */ + +function parse (string) { + if (typeof string !== 'string') { + return undefined + } + + // parse header + var match = CREDENTIALS_REGEXP.exec(string) + + if (!match) { + return undefined + } + + // decode user pass + var userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1])) + + if (!userPass) { + return undefined + } + + // return credentials object + return new Credentials(userPass[1], userPass[2]) +} + +/** + * Object to represent user credentials. + * @private + */ + +function Credentials (name, pass) { + this.name = name + this.pass = pass +} diff --git a/app/node_modules/basic-auth/package.json b/app/node_modules/basic-auth/package.json new file mode 100644 index 0000000..01bd8dc --- /dev/null +++ b/app/node_modules/basic-auth/package.json @@ -0,0 +1,41 @@ +{ + "name": "basic-auth", + "description": "node.js basic auth parser", + "version": "2.0.1", + "license": "MIT", + "keywords": [ + "basic", + "auth", + "authorization", + "basicauth" + ], + "repository": "jshttp/basic-auth", + "dependencies": { + "safe-buffer": "5.1.2" + }, + "devDependencies": { + "eslint": "5.6.0", + "eslint-config-standard": "12.0.0", + "eslint-plugin-import": "2.14.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "7.0.1", + "eslint-plugin-promise": "4.0.1", + "eslint-plugin-standard": "4.0.0", + "istanbul": "0.4.5", + "mocha": "5.2.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --check-leaks --reporter spec --bail", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/app/node_modules/bluebird/LICENSE b/app/node_modules/bluebird/LICENSE new file mode 100644 index 0000000..ae732d5 --- /dev/null +++ b/app/node_modules/bluebird/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-2017 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/app/node_modules/bluebird/README.md b/app/node_modules/bluebird/README.md new file mode 100644 index 0000000..b7e02b1 --- /dev/null +++ b/app/node_modules/bluebird/README.md @@ -0,0 +1,51 @@ + + Promises/A+ logo + +[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird) +[![coverage-98%](http://img.shields.io/badge/coverage-98%-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html) + +**Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises) + +# Introduction + +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). + +# 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-2017 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/app/node_modules/bluebird/changelog.md b/app/node_modules/bluebird/changelog.md new file mode 100644 index 0000000..73b2eb6 --- /dev/null +++ b/app/node_modules/bluebird/changelog.md @@ -0,0 +1 @@ +[http://bluebirdjs.com/docs/changelog.html](http://bluebirdjs.com/docs/changelog.html) diff --git a/app/node_modules/bluebird/js/browser/bluebird.core.js b/app/node_modules/bluebird/js/browser/bluebird.core.js new file mode 100644 index 0000000..c94f3c2 --- /dev/null +++ b/app/node_modules/bluebird/js/browser/bluebird.core.js @@ -0,0 +1,3777 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2017 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.5.0 + * 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) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._haveDrainedQueues = true; + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = Async; +module.exports.firstLineError = firstLineError; + +},{"./queue":17,"./schedule":18,"./util":21}],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) { +var getDomain = Promise._getDomain; +var async = Promise._async; +var Warning = _dereq_("./errors").Warning; +var util = _dereq_("./util"); +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")); + +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(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +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 domain = getDomain(); + possiblyUnhandledRejection = + typeof fn === "function" ? (domain === null ? + fn : util.domainBind(domain, fn)) + : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var domain = getDomain(); + unhandledRejectionHandled = + typeof fn === "function" ? (domain === null ? + fn : util.domainBind(domain, fn)) + : undefined; +}; + +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; + 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; + Context.deactivateLongStackTraces(); + async.enableTrampoline(); + config.longStackTraces = false; + }; + Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; + Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; + Context.activateLongStackTraces(); + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return config.longStackTraces && longStackTracesIsSupported(); +}; + +var fireDomEvent = (function() { + try { + if (typeof CustomEvent === "function") { + var event = new CustomEvent("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = new CustomEvent(name.toLowerCase(), { + detail: event, + cancelable: true + }); + return !util.global.dispatchEvent(domEvent); + }; + } else if (typeof Event === "function") { + var event = new Event("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = new Event(name.toLowerCase(), { + cancelable: true + }); + domEvent.detail = event; + return !util.global.dispatchEvent(domEvent); + }; + } else { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = document.createEvent("CustomEvent"); + domEvent.initCustomEvent(name.toLowerCase(), false, true, + event); + return !util.global.dispatchEvent(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; + } + } + 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._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 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 +}; + +if (longStackTraces) Promise.longStackTraces(); + +return { + 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,"./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, + getDomain) { +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 domain = getDomain(); + if (domain !== null) { + holder.fn = util.domainBind(domain, 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"); + +var getDomain; +if (util.isNode) { + getDomain = function() { + var ret = process.domain; + if (ret === undefined) ret = null; + return ret; + }; +} else { + getDomain = function() { + return null; + }; +} +util.notEnumerableProp(Promise, "_getDomain", getDomain); + +var 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); +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]; + 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 domain = getDomain(); + 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: domain === null ? handler + : (typeof handler === "function" && + util.domainBind(domain, handler)), + promise: promise, + receiver: receiver, + value: value + }); + } else { + target._addCallbacks(didFulfill, didReject, promise, receiver, domain); + } + + 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; + this._bitField = this._bitField | 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, + domain +) { + 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 = + domain === null ? fulfill : util.domainBind(domain, fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = + domain === null ? reject : util.domainBind(domain, reject); + } + } else { + var base = index * 4 - 4; + this[base + 2] = promise; + this[base + 3] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + domain === null ? fulfill : util.domainBind(domain, fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + domain === null ? reject : util.domainBind(domain, 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(promise); + } 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); + } + } +}; + +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; + } +}; + +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, getDomain); +Promise.Promise = Promise; +Promise.version = "3.5.0"; + + 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}],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); + } + 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))) { + 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 l = 8; + while (l--) new FakeConstructor(); + 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 !== 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 ({}.toString.call(promise) === "[object Promise]") { + return Promise; + } + } catch (e) {} + } +} + +function domainBind(self, cb) { + return self.bind(cb); +} + +var ret = { + 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, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: isNode, + hasEnvVariables: hasEnvVariables, + env: env, + global: globalObject, + getNativePromise: getNativePromise, + domainBind: domainBind +}; +ret.isRecentNode = ret.isNode && (function() { + var version = process.versions.node.split(".").map(Number); + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); + +if (ret.isNode) ret.toFastProperties(process); + +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; + +},{"./es5":10}]},{},[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/app/node_modules/bluebird/js/browser/bluebird.core.min.js b/app/node_modules/bluebird/js/browser/bluebird.core.min.js new file mode 100644 index 0000000..cdfb7da --- /dev/null +++ b/app/node_modules/bluebird/js/browser/bluebird.core.min.js @@ -0,0 +1,31 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2017 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.5.0 + * 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 i(a,s){if(!e[a]){if(!t[a]){var c="function"==typeof _dereq_&&_dereq_;if(!s&&c)return c(a,!0);if(o)return o(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 i(n?n:e)},u,u.exports,r,t,e,n)}return e[a].exports}for(var o="function"==typeof _dereq_&&_dereq_,a=0;a0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=r,e.exports.firstLineError=s},{"./queue":17,"./schedule":18,"./util":21}],2:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},a=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,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(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var l=n(o),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===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":15}],4:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),a=o.tryCatch,s=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,a=t._peekContext,s=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=o,t._peekContext=a,t.prototype._peekContext=s,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}},{}],7:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,e){return{promise:e}}function i(){return!1}function o(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: "+I.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function a(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?I.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function s(){return this._onCancelField}function c(t){this._onCancelField=t}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function u(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 p(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function f(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function h(){this._trace=new x(this._peekContext())}function _(t,e){if(H(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=E(t);I.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),I.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(t,e,n,r,i){if(void 0===t&&null!==e&&X){if(void 0!==i&&i._returnedNonUndefined())return;if(0===(65535&r._bitField))return;n&&(n+=" ");var o="",a="";if(e._trace){for(var s=e._trace.stack.split("\n"),c=C(s),l=c.length-1;l>=0;--l){var u=c[l];if(!V.test(u)){var p=u.match(Q);p&&(o="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 "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+a;r._warn(h,!0,e)}}function v(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),y(n)}function y(t,n,r){if(ot.warnings){var i,o=new U(t);if(n)r._attachExtraTrace(o);else if(ot.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var a=E(o);o.stack=a.message+"\n"+a.stack.join("\n")}tt("warning",o)||k(o,"",!0)}}function g(t,e){for(var n=0;n=0;--s)if(r[s]===o){a=s;break}for(var s=a;s>=0;--s){var c=r[s];if(e[i]!==c)break;e.pop(),i--}e=r}}function C(t){for(var e=[],n=0;n0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function E(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?w(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:C(e)}}function k(t,e,n){if("undefined"!=typeof console){var r;if(I.isObject(t)){var i=t.stack;r=e+G(i,t)}else r=e+String(t);"function"==typeof L?L(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function j(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){B.throwLater(o)}"unhandledRejection"===t?tt(t,n,r)||i||k(n,"Unhandled rejection "):tt(t,r)}function F(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():I.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"(<"+T(e)+">, no stack trace)"}function T(t){var e=41;return t.lengtha||0>s||!n||!r||n!==r||a>=s||(nt=function(t){if(D.test(t))return!0;var e=R(t);return e&&e.fileName===n&&a<=e.line&&e.line<=s?!0:!1})}}function x(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);it(this,x),e>32&&this.uncycle()}var O,A,L,N=e._getDomain,B=e._async,U=t("./errors").Warning,I=t("./util"),H=I.canAttachTrace,D=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,V=/\((?:timers\.js):\d+:\d+\)/,Q=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,q=null,G=null,M=!1,W=!(0==I.env("BLUEBIRD_DEBUG")||!I.env("BLUEBIRD_DEBUG")&&"development"!==I.env("NODE_ENV")),$=!(0==I.env("BLUEBIRD_WARNINGS")||!W&&!I.env("BLUEBIRD_WARNINGS")),z=!(0==I.env("BLUEBIRD_LONG_STACK_TRACES")||!W&&!I.env("BLUEBIRD_LONG_STACK_TRACES")),X=0!=I.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&($||!!I.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){0===(524288&this._bitField)&&(this._setRejectionIsUnhandled(),B.invokeLater(this._notifyUnhandledRejection,this,void 0))},e.prototype._notifyUnhandledRejectionIsHandled=function(){j("rejectionHandled",O,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),j("unhandledRejection",A,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},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 y(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=N();A="function"==typeof t?null===e?t:I.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=N();O="function"==typeof t?null===e?t:I.domainBind(e,t):void 0};var K=function(){};e.longStackTraces=function(){if(B.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!ot.longStackTraces&&P()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;ot.longStackTraces=!0,K=function(){if(B.haveItemsQueued()&&!ot.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,n.deactivateLongStackTraces(),B.enableTrampoline(),ot.longStackTraces=!1},e.prototype._captureStackTrace=h,e.prototype._attachExtraTrace=_,n.activateLongStackTraces(),B.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return ot.longStackTraces&&P()};var J=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return I.global.dispatchEvent(t),function(t,e){var n=new CustomEvent(t.toLowerCase(),{detail:e,cancelable:!0});return!I.global.dispatchEvent(n)}}if("function"==typeof Event){var t=new Event("CustomEvent");return I.global.dispatchEvent(t),function(t,e){var n=new Event(t.toLowerCase(),{cancelable:!0});return n.detail=e,!I.global.dispatchEvent(n)}}var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),I.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!I.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),Y=function(){return I.isNode?function(){return process.emit.apply(process,arguments)}:I.global?function(t){var e="on"+t.toLowerCase(),n=I.global[e];return n?(n.apply(I.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),Z={promiseCreated:r,promiseFulfilled:r,promiseRejected:r,promiseResolved:r,promiseCancelled:r,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:r},tt=function(t){var e=!1;try{e=Y.apply(null,arguments)}catch(n){B.throwLater(n),e=!0}var r=!1;try{r=J(t,Z[t].apply(null,arguments))}catch(n){B.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()&&K()),"warnings"in t){var n=t.warnings;ot.warnings=!!n,X=ot.warnings,I.isObject(n)&&"wForgottenReturn"in n&&(X=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!ot.cancellation){if(B.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=l,e.prototype._propagateFrom=u,e.prototype._onCancel=s,e.prototype._setOnCancel=c,e.prototype._attachCancellationCallback=a,e.prototype._execute=o,et=u,ot.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!ot.monitoring?(ot.monitoring=!0,e.prototype._fireEvent=tt):!t.monitoring&&ot.monitoring&&(ot.monitoring=!1,e.prototype._fireEvent=i)),e},e.prototype._fireEvent=i,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._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var et=p,nt=function(){return!1},rt=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;I.inherits(x,Error),n.CapturedTrace=x,x.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 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}}}},x.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=E(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(C(i.stack.split("\n"))),i=i._parent;b(r),m(r),I.notEnumerableProp(t,"stack",g(n,r)),I.notEnumerableProp(t,"__stackCleaned__",!0)}};var it=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():F(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,q=t,G=e;var n=Error.captureStackTrace;return nt=function(t){return D.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 q=/@/,G=e,M=!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?(G=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?F(e):e.toString()},null):(q=t,G=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&&(L=function(t){console.warn(t)},I.isNode&&process.stderr.isTTY?L=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:I.isNode||"string"!=typeof(new Error).stack||(L=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var ot={warnings:$,longStackTraces:!1,cancellation:!1,monitoring:!1};return z&&e.longStackTraces(),{longStackTraces:function(){return ot.longStackTraces},warnings:function(){return ot.warnings},cancellation:function(){return ot.cancellation},monitoring:function(){return ot.monitoring},propagateFromFunction:function(){return et},boundValueFunction:function(){return f},checkForgottenReturns:d,setBounds:S,warn:y,deprecated:v,CapturedTrace:x,fireDomEvent:J,fireGlobalEvent:Y}}},{"./errors":9,"./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 i=function(){return r};return this.caught(n,i)}}},{}],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 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,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"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,a=RangeError}catch(v){o=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 i=this.promise,l=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?l.call(i._boundValue()):l.call(i._boundValue(),t);if(u===r)return u;if(void 0!==u){i._setReturnedNonUndefined();var h=n(u,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(s,c,void 0,this,void 0)}}}return i.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 i.prototype.isFinallyHandler=function(){return 0===this.type},o.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 i(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,i=new Array(n-1),o=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)));i[o++]=a}i.length=o;var s=arguments[r];return this._passThrough(h(i,s,this),1,void 0,l)},i}},{"./catch_filter":5,"./util":21}],12:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,a){var s=t("./util");s.canEvaluate,s.tryCatch,s.errorObj;e.join=function(){var t,e=arguments.length-1;if(e>0&&"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":21}],13:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){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 i=s(t).apply(this,arguments),a=r._popContext();return o.checkForgottenReturns(i,a,"Promise.method",r),r._resolveFromSyncValue(i),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return i("expecting a function but got "+a.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 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 o.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 i(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),i=0;i1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!h.isObject(o))return p("Catch statement predicate: expecting an object but got "+h.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,P(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(F.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+h.classString(t);arguments.length>1&&(n+=", "+h.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?p("expecting a function but got "+h.classString(t)):this.all()._then(t,void 0,void 0,C,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 k(this).promise()},i.prototype.error=function(t){return this.caught(h.originatesFromRejection,t)},i.getNewLibraryCopy=e.exports,i.is=function(t){return t instanceof i},i.fromNode=i.fromCallback=function(t){var e=new i(b);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=x(t)(R(e,n));return r===S&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new k(t).promise()},i.cast=function(t){var e=E(t);return e instanceof i||(e=new i(b),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new g("expecting a function but got "+h.classString(t));return v.setScheduler(t)},i.prototype._then=function(t,e,n,r,o){var a=void 0!==o,s=a?o:new i(b),l=this._target(),u=l._bitField;a||(s._propagateFrom(this,3),s._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,s));var p=c();if(0!==(50397184&u)){var f,_,d=l._settlePromiseCtx;0!==(33554432&u)?(_=l._rejectionHandler0,f=t):0!==(16777216&u)?(_=l._fulfillmentHandler0,f=e,l._unsetRejectionIsUnhandled()):(d=l._settlePromiseLateCancellationObserver,_=new m("late cancellation observer"),l._attachExtraTrace(_),f=e),v.invoke(d,l,{handler:null===p?f:"function"==typeof f&&h.domainBind(p,f),promise:s,receiver:r,value:_})}else l._addCallbacks(t,e,s,r,p);return s},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(){v.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===f?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=f),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=f),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=null===i?t:h.domainBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:h.domainBind(i,e));else{var a=4*o-4;this[a+2]=n,this[a+3]=r,"function"==typeof t&&(this[a+0]=null===i?t:h.domainBind(i,t)),"function"==typeof e&&(this[a+1]=null===i?e:h.domainBind(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(l(),!1);var n=E(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(l());var o=r._bitField;if(0===(50397184&o)){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(r)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var c=new m("late cancellation observer");r._attachExtraTrace(c),this._reject(c)}}},i.prototype._rejectCallback=function(t,e,n){var r=h.ensureErrorObject(t),i=r===t;if(!i&&!n&&F.warnings()){var o="a promise was rejected with a non-error: "+h.classString(t);this._warn(o,!0)}this._attachExtraTrace(r,e?i:!1),this._reject(t)},i.prototype._resolveFromExecutor=function(t){if(t!==b){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===C?n&&"number"==typeof n.length?o=x(t).apply(this._boundValue(),n):(o=S,o.e=new g("cannot .spread() a non-array: "+h.classString(n))):o=x(t).call(e,n);var a=r._popContext();i=r._bitField,0===(65536&i)&&(o===w?r._reject(n):o===S?r._rejectCallback(o.e,!1):(F.checkForgottenReturns(o,a,"",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 a=t instanceof i,s=this._bitField,c=0!==(134217728&s);0!==(65536&s)?(a&&t._invokeInternalOnCancel(),r instanceof T&&r.isFinallyHandler()?(r.cancelPromise=t,x(e).call(r,o)===S&&t._reject(S.e)):e===u?t._fulfill(u.call(r)):r instanceof n?r._promiseCancelled(t):a||t instanceof k?t._cancel():r.cancel()):"function"==typeof e?a?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,r,o,t)):e.call(r,o,t):r instanceof n?r._isResolved()||(0!==(33554432&s)?r._promiseFulfilled(o,t):r._promiseRejected(o,t)):a&&(c&&t._setAsyncGuaranteed(),0!==(33554432&s)?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=l();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():v.settlePromises(this))}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?v.fatalError(t,h.isNode):void((65535&e)>0?v.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},i.defer=i.pending=function(){F.deprecated("Promise.defer","new Promise");var t=new i(b);return{promise:t,resolve:o,reject:a}},h.notEnumerableProp(i,"_makeSelfResolutionError",l),t("./method")(i,b,E,p,F),t("./bind")(i,b,E,F),t("./cancel")(i,k,p,F),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,k,E,b,v,c),i.Promise=i,i.version="3.5.0",h.toFastProperties(i),h.toFastProperties(i.prototype),s({a:1}),s({b:2}),s({c:3}),s(1),s(function(){}),s(void 0),s(!1),s(new i(b)),F.setBounds(d.firstLineError,h.lastLineError),i}},{"./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}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){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),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,o),s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function l(t,n){var o=r(this._values,this._promise);if(o instanceof e){o=o._target();var s=o._bitField;if(this._values=o,0===(50397184&s))return this._promise._setAsyncGuaranteed(),o._then(l,this._reject,void 0,this,n);if(0===(33554432&s))return 0!==(16777216&s)?this._reject(o._reason()):this._cancel();o=o._value()}if(o=c.asArray(o),null===o){var u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(a(n))):void this._iterate(o)},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 i=this._promise,o=!1,a=null,s=0;n>s;++s){var c=r(t[s],i);c instanceof e?(c=c._target(),a=c._bitField):a=null,o?null!==a&&c.suppressUnhandledRejections():null!==a?0===(50397184&a)?(c._proxy(this,s),this._values[s]=c):o=0!==(33554432&a)?this._promiseFulfilled(c._value(),s):0!==(16777216&a)?this._promiseRejected(c._reason(),s):this._promiseCancelled(s):o=this._promiseFulfilled(c,s)}o||i._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;no;++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._capacityn;++n)i[n]=t[n];return i[n]=e,i}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(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(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return L.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 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),i=0;i10||t[0]>0}(),D.isNode&&D.toFastProperties(process);try{throw new Error}catch(V){D.lastLineError=V}e.exports=D},{"./es5":10}]},{},[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/app/node_modules/bluebird/js/browser/bluebird.js b/app/node_modules/bluebird/js/browser/bluebird.js new file mode 100644 index 0000000..0b823f7 --- /dev/null +++ b/app/node_modules/bluebird/js/browser/bluebird.js @@ -0,0 +1,5619 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2017 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.5.0 + * 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) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._haveDrainedQueues = true; + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = Async; +module.exports.firstLineError = firstLineError; + +},{"./queue":26,"./schedule":29,"./util":36}],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) { +var getDomain = Promise._getDomain; +var async = Promise._async; +var Warning = _dereq_("./errors").Warning; +var util = _dereq_("./util"); +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")); + +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(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +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 domain = getDomain(); + possiblyUnhandledRejection = + typeof fn === "function" ? (domain === null ? + fn : util.domainBind(domain, fn)) + : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var domain = getDomain(); + unhandledRejectionHandled = + typeof fn === "function" ? (domain === null ? + fn : util.domainBind(domain, fn)) + : undefined; +}; + +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; + 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; + Context.deactivateLongStackTraces(); + async.enableTrampoline(); + config.longStackTraces = false; + }; + Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; + Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; + Context.activateLongStackTraces(); + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return config.longStackTraces && longStackTracesIsSupported(); +}; + +var fireDomEvent = (function() { + try { + if (typeof CustomEvent === "function") { + var event = new CustomEvent("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = new CustomEvent(name.toLowerCase(), { + detail: event, + cancelable: true + }); + return !util.global.dispatchEvent(domEvent); + }; + } else if (typeof Event === "function") { + var event = new Event("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = new Event(name.toLowerCase(), { + cancelable: true + }); + domEvent.detail = event; + return !util.global.dispatchEvent(domEvent); + }; + } else { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = document.createEvent("CustomEvent"); + domEvent.initCustomEvent(name.toLowerCase(), false, true, + event); + return !util.global.dispatchEvent(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; + } + } + 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._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 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 +}; + +if (longStackTraces) Promise.longStackTraces(); + +return { + 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,"./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, + getDomain) { +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 domain = getDomain(); + if (domain !== null) { + holder.fn = util.domainBind(domain, 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 getDomain = Promise._getDomain; +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 domain = getDomain(); + this._callback = domain === null ? fn : util.domainBind(domain, fn); + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = []; + async.invoke(this._asyncInit, this, undefined); +} +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"); + +var getDomain; +if (util.isNode) { + getDomain = function() { + var ret = process.domain; + if (ret === undefined) ret = null; + return ret; + }; +} else { + getDomain = function() { + return null; + }; +} +util.notEnumerableProp(Promise, "_getDomain", getDomain); + +var 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); +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]; + 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 domain = getDomain(); + 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: domain === null ? handler + : (typeof handler === "function" && + util.domainBind(domain, handler)), + promise: promise, + receiver: receiver, + value: value + }); + } else { + target._addCallbacks(didFulfill, didReject, promise, receiver, domain); + } + + 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; + this._bitField = this._bitField | 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, + domain +) { + 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 = + domain === null ? fulfill : util.domainBind(domain, fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = + domain === null ? reject : util.domainBind(domain, reject); + } + } else { + var base = index * 4 - 4; + this[base + 2] = promise; + this[base + 3] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + domain === null ? fulfill : util.domainBind(domain, fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + domain === null ? reject : util.domainBind(domain, 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(promise); + } 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); + } + } +}; + +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; + } +}; + +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, getDomain); +Promise.Promise = Promise; +Promise.version = "3.5.0"; +_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +_dereq_('./call_get.js')(Promise); +_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); +_dereq_('./timers.js')(Promise, INTERNAL, debug); +_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, 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_('./filter.js')(Promise, INTERNAL); +_dereq_('./each.js')(Promise, INTERNAL); +_dereq_('./any.js')(Promise); + + 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}],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); + } + 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 getDomain = Promise._getDomain; +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; + +function ReductionPromiseArray(promises, fn, initialValue, _each) { + this.constructor$(promises); + var domain = getDomain(); + this._fn = domain === null ? fn : util.domainBind(domain, 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; + + 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 (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))) { + 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.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 l = 8; + while (l--) new FakeConstructor(); + 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 !== 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 ({}.toString.call(promise) === "[object Promise]") { + return Promise; + } + } catch (e) {} + } +} + +function domainBind(self, cb) { + return self.bind(cb); +} + +var ret = { + 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, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: isNode, + hasEnvVariables: hasEnvVariables, + env: env, + global: globalObject, + getNativePromise: getNativePromise, + domainBind: domainBind +}; +ret.isRecentNode = ret.isNode && (function() { + var version = process.versions.node.split(".").map(Number); + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); + +if (ret.isNode) ret.toFastProperties(process); + +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; + +},{"./es5":13}]},{},[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/app/node_modules/bluebird/js/browser/bluebird.min.js b/app/node_modules/bluebird/js/browser/bluebird.min.js new file mode 100644 index 0000000..59afc96 --- /dev/null +++ b/app/node_modules/bluebird/js/browser/bluebird.min.js @@ -0,0 +1,31 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2017 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.5.0 + * 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 l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var u=e[s]={exports:{}};t[s][0].call(u.exports,function(e){var n=t[s][1][e];return i(n?n:e)},u,u.exports,r,t,e,n)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=r,e.exports.firstLineError=a},{"./queue":26,"./schedule":29,"./util":36}],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 l=n(o),u=new t(e);u._propagateFrom(this,1);var p=this._target();if(u._setBoundTo(l),l instanceof t){var h={promiseRejectionQueued:!1,promise:u,target:p,bindingPromise:l};p._then(e,s,void 0,u,h),l._then(a,c,void 0,u,h),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)}}},{}],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){function r(t,e){return{promise:e}}function i(){return!1}function o(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: "+H.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function s(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?H.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function a(){return this._onCancelField}function c(t){this._onCancelField=t}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function u(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 p(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function h(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function f(){this._trace=new S(this._peekContext())}function _(t,e){if(N(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=j(t);H.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),H.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(t,e,n,r,i){if(void 0===t&&null!==e&&W){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=w(a),l=c.length-1;l>=0;--l){var u=c[l];if(!U.test(u)){var p=u.match(M);p&&(o="at "+p[1]+":"+p[2]+":"+p[3]+" ");break}}if(c.length>0)for(var h=c[0],l=0;l0&&(s="\n"+a[l-1]);break}}var f="a promise was created in a "+n+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+s;r._warn(f,!0,e)}}function v(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),y(n)}function y(t,n,r){if(ot.warnings){var i,o=new L(t);if(n)r._attachExtraTrace(o);else if(ot.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var s=j(o);o.stack=s.message+"\n"+s.stack.join("\n")}tt("warning",o)||E(o,"",!0)}}function m(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 w(t){for(var e=[],n=0;n0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function j(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?C(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:w(e)}}function E(t,e,n){if("undefined"!=typeof console){var r;if(H.isObject(t)){var i=t.stack;r=e+Q(i,t)}else r=e+String(t);"function"==typeof D?D(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function k(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){I.throwLater(o)}"unhandledRejection"===t?tt(t,n,r)||i||E(n,"Unhandled rejection "):tt(t,r)}function F(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():H.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"(<"+x(e)+">, no stack trace)"}function x(t){var e=41;return t.lengths||0>a||!n||!r||n!==r||s>=a||(nt=function(t){if(B.test(t))return!0;var e=P(t);return e&&e.fileName===n&&s<=e.line&&e.line<=a?!0:!1})}}function S(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);it(this,S),e>32&&this.uncycle()}var O,A,D,V=e._getDomain,I=e._async,L=t("./errors").Warning,H=t("./util"),N=H.canAttachTrace,B=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,U=/\((?:timers\.js):\d+:\d+\)/,M=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,q=null,Q=null,$=!1,G=!(0==H.env("BLUEBIRD_DEBUG")||!H.env("BLUEBIRD_DEBUG")&&"development"!==H.env("NODE_ENV")),z=!(0==H.env("BLUEBIRD_WARNINGS")||!G&&!H.env("BLUEBIRD_WARNINGS")),X=!(0==H.env("BLUEBIRD_LONG_STACK_TRACES")||!G&&!H.env("BLUEBIRD_LONG_STACK_TRACES")),W=0!=H.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(z||!!H.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){0===(524288&this._bitField)&&(this._setRejectionIsUnhandled(),I.invokeLater(this._notifyUnhandledRejection,this,void 0))},e.prototype._notifyUnhandledRejectionIsHandled=function(){k("rejectionHandled",O,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),k("unhandledRejection",A,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},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 y(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=V();A="function"==typeof t?null===e?t:H.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=V();O="function"==typeof t?null===e?t:H.domainBind(e,t):void 0};var K=function(){};e.longStackTraces=function(){if(I.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!ot.longStackTraces&&T()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;ot.longStackTraces=!0,K=function(){if(I.haveItemsQueued()&&!ot.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,n.deactivateLongStackTraces(),I.enableTrampoline(),ot.longStackTraces=!1},e.prototype._captureStackTrace=f,e.prototype._attachExtraTrace=_,n.activateLongStackTraces(),I.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return ot.longStackTraces&&T()};var J=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return H.global.dispatchEvent(t),function(t,e){var n=new CustomEvent(t.toLowerCase(),{detail:e,cancelable:!0});return!H.global.dispatchEvent(n)}}if("function"==typeof Event){var t=new Event("CustomEvent");return H.global.dispatchEvent(t),function(t,e){var n=new Event(t.toLowerCase(),{cancelable:!0});return n.detail=e,!H.global.dispatchEvent(n)}}var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),H.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!H.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),Y=function(){return H.isNode?function(){return process.emit.apply(process,arguments)}:H.global?function(t){var e="on"+t.toLowerCase(),n=H.global[e];return n?(n.apply(H.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),Z={promiseCreated:r,promiseFulfilled:r,promiseRejected:r,promiseResolved:r,promiseCancelled:r,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:r},tt=function(t){var e=!1;try{e=Y.apply(null,arguments)}catch(n){I.throwLater(n),e=!0}var r=!1;try{r=J(t,Z[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()&&K()),"warnings"in t){var n=t.warnings;ot.warnings=!!n,W=ot.warnings,H.isObject(n)&&"wForgottenReturn"in n&&(W=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!ot.cancellation){if(I.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=l,e.prototype._propagateFrom=u,e.prototype._onCancel=a,e.prototype._setOnCancel=c,e.prototype._attachCancellationCallback=s,e.prototype._execute=o,et=u,ot.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!ot.monitoring?(ot.monitoring=!0,e.prototype._fireEvent=tt):!t.monitoring&&ot.monitoring&&(ot.monitoring=!1,e.prototype._fireEvent=i)),e},e.prototype._fireEvent=i,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._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var et=p,nt=function(){return!1},rt=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;H.inherits(S,Error),n.CapturedTrace=S,S.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 l=c._length+1,u=r-2;u>=0;--u)e[u]._length=l,l++;return}}}},S.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=j(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(w(i.stack.split("\n"))),i=i._parent;b(r),g(r),H.notEnumerableProp(t,"stack",m(n,r)),H.notEnumerableProp(t,"__stackCleaned__",!0)}};var it=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():F(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,q=t,Q=e;var n=Error.captureStackTrace;return nt=function(t){return B.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 q=/@/,Q=e,$=!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?(Q=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?F(e):e.toString()},null):(q=t,Q=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&&(D=function(t){console.warn(t)},H.isNode&&process.stderr.isTTY?D=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:H.isNode||"string"!=typeof(new Error).stack||(D=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var ot={warnings:z,longStackTraces:!1,cancellation:!1,monitoring:!1};return X&&e.longStackTraces(),{longStackTraces:function(){return ot.longStackTraces},warnings:function(){return ot.warnings},cancellation:function(){return ot.cancellation},monitoring:function(){return ot.monitoring},propagateFromFunction:function(){return et},boundValueFunction:function(){return h},checkForgottenReturns:d,setBounds:R,warn:y,deprecated:v,CapturedTrace:S,fireDomEvent:J,fireGlobalEvent:Y}}},{"./errors":12,"./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 u(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,l=t("./util"),u=l.inherits,p=l.notEnumerableProp,h=r("Warning","warning"),f=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(" "),m=0;m1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function a(){return l.call(this,this.promise._target()._settledValue())}function c(t){return s(this,t)?void 0:(h.e=t,h)}function l(t){var i=this.promise,l=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?l.call(i._boundValue()):l.call(i._boundValue(),t);if(u===r)return u;if(void 0!==u){i._setReturnedNonUndefined();var f=n(u,i);if(f instanceof e){if(null!=this.cancelPromise){if(f._isCancelled()){var _=new p("late cancellation observer");return i._attachExtraTrace(_),h.e=_,h}f.isPending()&&f._attachCancellationCallback(new o(this))}return f._then(a,c,void 0,this,void 0)}}}return i.isRejected()?(s(this),h.e=t,h):(s(this),t)}var u=t("./util"),p=e.CancellationError,h=u.errorObj,f=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,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,i=new Array(n-1),o=0;for(r=0;n-1>r;++r){var s=arguments[r];if(!u.isObject(s))return e.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+u.classString(s)));i[o++]=s}i.length=o;var a=arguments[r];return this._passThrough(f(i,a,this),1,void 0,l)},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,e,n,r){this.constructor$(t),this._promise._captureStackTrace();var i=l();this._callback=null===i?e:u.domainBind(i,e),this._preservedValues=r===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=[],f.invoke(this._asyncInit,this,void 0)}function c(t,n,i,o){if("function"!=typeof n)return r("expecting a function but got "+u.classString(n));var s=0;if(void 0!==i){if("object"!=typeof i||null===i)return e.reject(new TypeError("options argument must be an object but it is "+u.classString(i)));if("number"!=typeof i.concurrency)return e.reject(new TypeError("'concurrency' must be a number but it is "+u.classString(i.concurrency)));s=i.concurrency}return s="number"==typeof s&&isFinite(s)&&s>=1?s:0,new a(t,n,s,o).promise()}var l=e._getDomain,u=t("./util"),p=u.tryCatch,h=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 l=this._promise,u=this._callback,f=l._boundValue();l._pushContext();var _=p(u).call(f,t,n,o),d=l._popContext();if(s.checkForgottenReturns(_,d,null!==a?"Promise.filter":"Promise.map",l),_===h)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 m=++this._totalResolved;return m>=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 l=arguments[1],u=arguments[2];c=s.isArray(l)?a(t).apply(u,l):a(t).call(u,l)}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&&u.getPrototypeOf(t)===Error.prototype}function i(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),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 p("Catch statement predicate: expecting an object but got "+f.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,P(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(x.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?p("expecting a function but got "+f.classString(t)):this.all()._then(t,void 0,void 0,w,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 E(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(b);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=O(t)(R(e,n));return r===S&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new E(t).promise()},i.cast=function(t){var e=j(t);return e instanceof i||(e=new i(b),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new m("expecting a function but got "+f.classString(t));return v.setScheduler(t)},i.prototype._then=function(t,e,n,r,o){var s=void 0!==o,a=s?o:new i(b),l=this._target(),u=l._bitField;s||(a._propagateFrom(this,3),a._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,a));var p=c();if(0!==(50397184&u)){var h,_,d=l._settlePromiseCtx;0!==(33554432&u)?(_=l._rejectionHandler0,h=t):0!==(16777216&u)?(_=l._fulfillmentHandler0,h=e,l._unsetRejectionIsUnhandled()):(d=l._settlePromiseLateCancellationObserver,_=new g("late cancellation observer"),l._attachExtraTrace(_),h=e),v.invoke(d,l,{handler:null===p?h:"function"==typeof h&&f.domainBind(p,h),promise:a,receiver:r,value:_})}else l._addCallbacks(t,e,a,r,p);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(){v.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===h?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=h),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=h),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=null===i?t:f.domainBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:f.domainBind(i,e));else{var s=4*o-4;this[s+2]=n,this[s+3]=r,"function"==typeof t&&(this[s+0]=null===i?t:f.domainBind(i,t)),"function"==typeof e&&(this[s+1]=null===i?e:f.domainBind(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(l(),!1);var n=j(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(l());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(r)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var c=new g("late cancellation observer");r._attachExtraTrace(c),this._reject(c)}}},i.prototype._rejectCallback=function(t,e,n){var r=f.ensureErrorObject(t),i=r===t;if(!i&&!n&&x.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!==b){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===w?n&&"number"==typeof n.length?o=O(t).apply(this._boundValue(),n):(o=S,o.e=new m("cannot .spread() a non-array: "+f.classString(n))):o=O(t).call(e,n);var s=r._popContext();i=r._bitField,0===(65536&i)&&(o===C?r._reject(n):o===S?r._rejectCallback(o.e,!1):(x.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 T&&r.isFinallyHandler()?(r.cancelPromise=t,O(e).call(r,o)===S&&t._reject(S.e)):e===u?t._fulfill(u.call(r)):r instanceof n?r._promiseCancelled(t):s||t instanceof E?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=l();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():v.settlePromises(this))}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?v.fatalError(t,f.isNode):void((65535&e)>0?v.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},i.defer=i.pending=function(){x.deprecated("Promise.defer","new Promise");var t=new i(b);return{promise:t,resolve:o,reject:s}},f.notEnumerableProp(i,"_makeSelfResolutionError",l),t("./method")(i,b,j,p,x),t("./bind")(i,b,j,x),t("./cancel")(i,E,p,x),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,E,j,b,v,c),i.Promise=i,i.version="3.5.0",t("./map.js")(i,E,p,j,b,x),t("./call_get.js")(i),t("./using.js")(i,p,j,F,b,x),t("./timers.js")(i,b,x),t("./generators.js")(i,p,b,j,n,x),t("./nodeify.js")(i),t("./promisify.js")(i,b),t("./props.js")(i,E,j,p),t("./race.js")(i,b,j,p),t("./reduce.js")(i,E,p,j,b,x),t("./settle.js")(i,E,x),t("./some.js")(i,E,p),t("./filter.js")(i,b),t("./each.js")(i,b),t("./any.js")(i),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(b)),x.setBounds(d.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}],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),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 l(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(l,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 u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!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 u=s[c],p=s[c+1],_=u+e;if(r===k)t[_]=k(u,h,u,p,e,i);else{var d=r(p,function(){return k(u,h,u,p,e,i)});f.notEnumerableProp(d,"__isPromisified__",!0),t[_]=d}}return f.toFastProperties(t),t}function u(t,e,n){return k(t,e,void 0,t,null,n)}var p,h={},f=t("./util"),_=t("./nodeback"),d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,m=t("./errors").TypeError,g="Async",b={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],C=new RegExp("^(?:"+w.join("|")+")$"),j=function(t){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},E=function(t){return t.replace(/([$])/,"\\$")},k=y?p:c;e.promisify=function(t,e){if("function"!=typeof t)throw new m("expecting a function but got "+f.classString(t));if(i(t))return t;e=Object(e);var n=void 0===e.context?h:e.context,o=!!e.multiArgs,s=u(t,n,o);return f.copyDescriptors(t,s,r),s},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new m("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=g);var i=e.filter;"function"!=typeof i&&(i=j);var o=e.promisifier;if("function"!=typeof o&&(o=k),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");for(var s=f.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 l(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"),l=c.isObject,u=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}}(),h=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=h(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._capacityh;++h){var _=t[h];(void 0!==_||h in t)&&e.cast(_)._then(u,p,void 0,l,null)}return l}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=h();this._fn=null===s?n:f.domainBind(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 l(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 u(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=_(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 h=e._getDomain,f=t("./util"),_=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;if(void 0!==this._initialValue?(n=this._initialValue,r=0):(n=e.resolve(t[0]),r=1),this._currentCancellable=n,!n.isRejected())for(;i>r;++r){var o={accum:null,value:t[r],index:r,length:i,array:this};n=n._then(u,void 0,void 0,o,void 0)}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 l(this,t,e,null)},e.reduce=function(t,e,n,r){return l(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 l=s.resolve();r=function(t){l.then(t)}}else r="undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&(window.navigator.standalone||window.cordova)?"undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:o: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()}}();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.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,l=s.isArray,u={};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=l(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(u),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(u(t)){if(t instanceof e)return t;var i=o(t);if(i===l){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 l.e=e,l}}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),u=a;i&&i._pushContext(),a._captureStackTrace(),i&&i._popContext();var p=!0,h=c.tryCatch(r).call(t,o,s);return p=!1,a&&h===l&&(a._rejectCallback(h.e,!0,!0),a=null),u}var c=t("./util"),l=c.errorObj,u=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 l=function(t){return u(+this).thenReturn(t)},u=e.delay=function(t,o){var s,a;return void 0!==o?(s=e.resolve(o)._then(l,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 u(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 l(t,n){function i(){if(s>=l)return u._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,l=t.length,u=new e(o);return i(),u}function u(t,e,n){this._data=t,this._promise=e,this._context=n}function p(t,e,n){this.constructor$(t,e,n)}function h(t){return u.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function f(t){this.length=t,this.promise=null,this[t-1]=null}var _=t("./util"),d=t("./errors").TypeError,v=t("./util").inherits,y=_.errorObj,m=_.tryCatch,g={};u.prototype.data=function(){return this._data},u.prototype.promise=function(){return this._promise},u.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():g},u.prototype.tryDispose=function(t){var e=this.resource(),n=this._context;void 0!==n&&n._pushContext();var r=e!==g?this.doDispose(e,t):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,r},u.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},v(p,u),p.prototype.doDispose=function(t,e){var n=this.data();return n.call(t,t,e)},f.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 f(t),p=0;t>p;++p){var d=o[p];if(u.isDisposer(d)){var v=d;d=d.promise(),d._setDisposable(v)}else{var g=r(d);g instanceof e&&(d=g._then(h,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 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(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 h(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 f(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return D.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 null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function m(t){try{u(t,"isOperational",!0)}catch(e){}}function g(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.isNode&&B.toFastProperties(process);try{throw new Error}catch(U){B.lastLineError=U}e.exports=B},{"./es5":13}]},{},[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/app/node_modules/bluebird/js/release/any.js b/app/node_modules/bluebird/js/release/any.js new file mode 100644 index 0000000..05a6228 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/assert.js b/app/node_modules/bluebird/js/release/assert.js new file mode 100644 index 0000000..4518231 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/async.js b/app/node_modules/bluebird/js/release/async.js new file mode 100644 index 0000000..41f6655 --- /dev/null +++ b/app/node_modules/bluebird/js/release/async.js @@ -0,0 +1,161 @@ +"use strict"; +var firstLineError; +try {throw new Error(); } catch (e) {firstLineError = e;} +var schedule = require("./schedule"); +var Queue = require("./queue"); +var util = require("./util"); + +function Async() { + this._customScheduler = false; + this._isTickUsed = false; + this._lateQueue = new Queue(16); + this._normalQueue = new Queue(16); + this._haveDrainedQueues = false; + this._trampolineEnabled = true; + 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.enableTrampoline = function() { + this._trampolineEnabled = true; +}; + +Async.prototype.disableTrampolineIfNecessary = function() { + if (util.hasDevTools) { + this._trampolineEnabled = false; + } +}; + +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(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + this._schedule(function() { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + }); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + this._schedule(function() { + fn.call(receiver, arg); + }); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + this._schedule(function() { + promise._settlePromises(); + }); + } + }; +} + +Async.prototype._drainQueue = function(queue) { + while (queue.length() > 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._haveDrainedQueues = true; + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = Async; +module.exports.firstLineError = firstLineError; diff --git a/app/node_modules/bluebird/js/release/bind.js b/app/node_modules/bluebird/js/release/bind.js new file mode 100644 index 0000000..fc3379d --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/bluebird.js b/app/node_modules/bluebird/js/release/bluebird.js new file mode 100644 index 0000000..1c36cf3 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/call_get.js b/app/node_modules/bluebird/js/release/call_get.js new file mode 100644 index 0000000..0ed7714 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/cancel.js b/app/node_modules/bluebird/js/release/cancel.js new file mode 100644 index 0000000..7a12415 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/catch_filter.js b/app/node_modules/bluebird/js/release/catch_filter.js new file mode 100644 index 0000000..0f24ce2 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/context.js b/app/node_modules/bluebird/js/release/context.js new file mode 100644 index 0000000..c307414 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/debuggability.js b/app/node_modules/bluebird/js/release/debuggability.js new file mode 100644 index 0000000..bf0587c --- /dev/null +++ b/app/node_modules/bluebird/js/release/debuggability.js @@ -0,0 +1,916 @@ +"use strict"; +module.exports = function(Promise, Context) { +var getDomain = Promise._getDomain; +var async = Promise._async; +var Warning = require("./errors").Warning; +var util = require("./util"); +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")); + +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(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +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 domain = getDomain(); + possiblyUnhandledRejection = + typeof fn === "function" ? (domain === null ? + fn : util.domainBind(domain, fn)) + : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var domain = getDomain(); + unhandledRejectionHandled = + typeof fn === "function" ? (domain === null ? + fn : util.domainBind(domain, fn)) + : undefined; +}; + +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; + 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; + Context.deactivateLongStackTraces(); + async.enableTrampoline(); + config.longStackTraces = false; + }; + Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; + Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; + Context.activateLongStackTraces(); + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return config.longStackTraces && longStackTracesIsSupported(); +}; + +var fireDomEvent = (function() { + try { + if (typeof CustomEvent === "function") { + var event = new CustomEvent("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = new CustomEvent(name.toLowerCase(), { + detail: event, + cancelable: true + }); + return !util.global.dispatchEvent(domEvent); + }; + } else if (typeof Event === "function") { + var event = new Event("CustomEvent"); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = new Event(name.toLowerCase(), { + cancelable: true + }); + domEvent.detail = event; + return !util.global.dispatchEvent(domEvent); + }; + } else { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + util.global.dispatchEvent(event); + return function(name, event) { + var domEvent = document.createEvent("CustomEvent"); + domEvent.initCustomEvent(name.toLowerCase(), false, true, + event); + return !util.global.dispatchEvent(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; + } + } + 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._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 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 +}; + +if (longStackTraces) Promise.longStackTraces(); + +return { + 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/app/node_modules/bluebird/js/release/direct_resolve.js b/app/node_modules/bluebird/js/release/direct_resolve.js new file mode 100644 index 0000000..a890298 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/each.js b/app/node_modules/bluebird/js/release/each.js new file mode 100644 index 0000000..e4f3d05 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/errors.js b/app/node_modules/bluebird/js/release/errors.js new file mode 100644 index 0000000..f62f323 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/es5.js b/app/node_modules/bluebird/js/release/es5.js new file mode 100644 index 0000000..ea41d5a --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/filter.js b/app/node_modules/bluebird/js/release/filter.js new file mode 100644 index 0000000..ed57bf0 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/finally.js b/app/node_modules/bluebird/js/release/finally.js new file mode 100644 index 0000000..d57444b --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/generators.js b/app/node_modules/bluebird/js/release/generators.js new file mode 100644 index 0000000..500c280 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/join.js b/app/node_modules/bluebird/js/release/join.js new file mode 100644 index 0000000..4945e3f --- /dev/null +++ b/app/node_modules/bluebird/js/release/join.js @@ -0,0 +1,168 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, + getDomain) { +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 domain = getDomain(); + if (domain !== null) { + holder.fn = util.domainBind(domain, 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/app/node_modules/bluebird/js/release/map.js b/app/node_modules/bluebird/js/release/map.js new file mode 100644 index 0000000..976f15e --- /dev/null +++ b/app/node_modules/bluebird/js/release/map.js @@ -0,0 +1,168 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL, + debug) { +var getDomain = Promise._getDomain; +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 domain = getDomain(); + this._callback = domain === null ? fn : util.domainBind(domain, fn); + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = []; + async.invoke(this._asyncInit, this, undefined); +} +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/app/node_modules/bluebird/js/release/method.js b/app/node_modules/bluebird/js/release/method.js new file mode 100644 index 0000000..ce9e4db --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/nodeback.js b/app/node_modules/bluebird/js/release/nodeback.js new file mode 100644 index 0000000..71e69eb --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/nodeify.js b/app/node_modules/bluebird/js/release/nodeify.js new file mode 100644 index 0000000..ce2b190 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/promise.js b/app/node_modules/bluebird/js/release/promise.js new file mode 100644 index 0000000..99d20f9 --- /dev/null +++ b/app/node_modules/bluebird/js/release/promise.js @@ -0,0 +1,775 @@ +"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"); + +var getDomain; +if (util.isNode) { + getDomain = function() { + var ret = process.domain; + if (ret === undefined) ret = null; + return ret; + }; +} else { + getDomain = function() { + return null; + }; +} +util.notEnumerableProp(Promise, "_getDomain", getDomain); + +var 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); +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]; + 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 domain = getDomain(); + 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: domain === null ? handler + : (typeof handler === "function" && + util.domainBind(domain, handler)), + promise: promise, + receiver: receiver, + value: value + }); + } else { + target._addCallbacks(didFulfill, didReject, promise, receiver, domain); + } + + 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; + this._bitField = this._bitField | 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, + domain +) { + 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 = + domain === null ? fulfill : util.domainBind(domain, fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = + domain === null ? reject : util.domainBind(domain, reject); + } + } else { + var base = index * 4 - 4; + this[base + 2] = promise; + this[base + 3] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + domain === null ? fulfill : util.domainBind(domain, fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + domain === null ? reject : util.domainBind(domain, 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(promise); + } 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); + } + } +}; + +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; + } +}; + +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, getDomain); +Promise.Promise = Promise; +Promise.version = "3.5.0"; +require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +require('./call_get.js')(Promise); +require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); +require('./timers.js')(Promise, INTERNAL, debug); +require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, 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('./filter.js')(Promise, INTERNAL); +require('./each.js')(Promise, INTERNAL); +require('./any.js')(Promise); + + 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/app/node_modules/bluebird/js/release/promise_array.js b/app/node_modules/bluebird/js/release/promise_array.js new file mode 100644 index 0000000..0fb303e --- /dev/null +++ b/app/node_modules/bluebird/js/release/promise_array.js @@ -0,0 +1,185 @@ +"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); + } + 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/app/node_modules/bluebird/js/release/promisify.js b/app/node_modules/bluebird/js/release/promisify.js new file mode 100644 index 0000000..aa98e5b --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/props.js b/app/node_modules/bluebird/js/release/props.js new file mode 100644 index 0000000..6a34aaf --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/queue.js b/app/node_modules/bluebird/js/release/queue.js new file mode 100644 index 0000000..ffd36fd --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/race.js b/app/node_modules/bluebird/js/release/race.js new file mode 100644 index 0000000..b862f46 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/reduce.js b/app/node_modules/bluebird/js/release/reduce.js new file mode 100644 index 0000000..26e2b1a --- /dev/null +++ b/app/node_modules/bluebird/js/release/reduce.js @@ -0,0 +1,172 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL, + debug) { +var getDomain = Promise._getDomain; +var util = require("./util"); +var tryCatch = util.tryCatch; + +function ReductionPromiseArray(promises, fn, initialValue, _each) { + this.constructor$(promises); + var domain = getDomain(); + this._fn = domain === null ? fn : util.domainBind(domain, 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; + + 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 (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/app/node_modules/bluebird/js/release/schedule.js b/app/node_modules/bluebird/js/release/schedule.js new file mode 100644 index 0000000..f70df9f --- /dev/null +++ b/app/node_modules/bluebird/js/release/schedule.js @@ -0,0 +1,61 @@ +"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))) { + 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/app/node_modules/bluebird/js/release/settle.js b/app/node_modules/bluebird/js/release/settle.js new file mode 100644 index 0000000..fade3a1 --- /dev/null +++ b/app/node_modules/bluebird/js/release/settle.js @@ -0,0 +1,43 @@ +"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.prototype.settle = function () { + return Promise.settle(this); +}; +}; diff --git a/app/node_modules/bluebird/js/release/some.js b/app/node_modules/bluebird/js/release/some.js new file mode 100644 index 0000000..400d852 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/synchronous_inspection.js b/app/node_modules/bluebird/js/release/synchronous_inspection.js new file mode 100644 index 0000000..9c49d2e --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/thenables.js b/app/node_modules/bluebird/js/release/thenables.js new file mode 100644 index 0000000..d6ab9aa --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/timers.js b/app/node_modules/bluebird/js/release/timers.js new file mode 100644 index 0000000..cb8f1f4 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/using.js b/app/node_modules/bluebird/js/release/using.js new file mode 100644 index 0000000..65de531 --- /dev/null +++ b/app/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/app/node_modules/bluebird/js/release/util.js b/app/node_modules/bluebird/js/release/util.js new file mode 100644 index 0000000..84c28ec --- /dev/null +++ b/app/node_modules/bluebird/js/release/util.js @@ -0,0 +1,379 @@ +"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 l = 8; + while (l--) new FakeConstructor(); + 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 !== 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 ({}.toString.call(promise) === "[object Promise]") { + return Promise; + } + } catch (e) {} + } +} + +function domainBind(self, cb) { + return self.bind(cb); +} + +var ret = { + 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, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: isNode, + hasEnvVariables: hasEnvVariables, + env: env, + global: globalObject, + getNativePromise: getNativePromise, + domainBind: domainBind +}; +ret.isRecentNode = ret.isNode && (function() { + var version = process.versions.node.split(".").map(Number); + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); + +if (ret.isNode) ret.toFastProperties(process); + +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; diff --git a/app/node_modules/bluebird/package.json b/app/node_modules/bluebird/package.json new file mode 100644 index 0000000..721821e --- /dev/null +++ b/app/node_modules/bluebird/package.json @@ -0,0 +1,77 @@ +{ + "name": "bluebird", + "description": "Full featured Promises/A+ implementation with exceptionally good performance", + "version": "3.5.0", + "keywords": [ + "promise", + "performance", + "promises", + "promises-a", + "promises-aplus", + "async", + "await", + "deferred", + "deferreds", + "future", + "flow control", + "dsl", + "fluent interface" + ], + "scripts": { + "lint": "node scripts/jshint.js", + "test": "node tools/test.js", + "istanbul": "istanbul", + "prepublish": "npm run generate-browser-core && npm run generate-browser-full", + "generate-browser-full": "node tools/build.js --no-clean --no-debug --release --browser --minify", + "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" + }, + "homepage": "https://github.com/petkaantonov/bluebird", + "repository": { + "type": "git", + "url": "git://github.com/petkaantonov/bluebird.git" + }, + "bugs": { + "url": "http://github.com/petkaantonov/bluebird/issues" + }, + "license": "MIT", + "author": { + "name": "Petka Antonov", + "email": "petka_antonov@hotmail.com", + "url": "http://github.com/petkaantonov/" + }, + "devDependencies": { + "acorn": "~0.6.0", + "baconjs": "^0.7.43", + "bluebird": "^2.9.2", + "body-parser": "^1.10.2", + "browserify": "^8.1.1", + "cli-table": "~0.3.1", + "co": "^4.2.0", + "cross-spawn": "^0.2.3", + "glob": "^4.3.2", + "grunt-saucelabs": "~8.4.1", + "highland": "^2.3.0", + "istanbul": "^0.3.5", + "jshint": "^2.6.0", + "jshint-stylish": "~0.2.0", + "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", + "kefir": "^2.4.1" + }, + "readmeFilename": "README.md", + "main": "./js/release/bluebird.js", + "webpack": "./js/release/bluebird.js", + "browser": "./js/browser/bluebird.js", + "files": [ + "js/browser", + "js/release", + "LICENSE" + ] +} diff --git a/app/node_modules/body-parser/HISTORY.md b/app/node_modules/body-parser/HISTORY.md new file mode 100644 index 0000000..d8152cc --- /dev/null +++ b/app/node_modules/body-parser/HISTORY.md @@ -0,0 +1,588 @@ +1.18.3 / 2018-05-14 +=================== + + * Fix stack trace for strict json parse error + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: http-errors@~1.6.3 + - deps: depd@~1.1.2 + - deps: setprototypeof@1.1.0 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.23 + - Fix loading encoding with year appended + - Fix deprecation warnings on Node.js 10+ + * deps: qs@6.5.2 + * deps: raw-body@2.3.3 + - deps: http-errors@1.6.3 + - deps: iconv-lite@0.4.23 + * deps: type-is@~1.6.16 + - deps: mime-types@~2.1.18 + +1.18.2 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: remove argument reassignment + +1.18.1 / 2017-09-12 +=================== + + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: iconv-lite@0.4.19 + - Fix ISO-8859-1 regression + - Update Windows-1255 + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: raw-body@2.3.2 + - deps: iconv-lite@0.4.19 + +1.18.0 / 2017-09-08 +=================== + + * Fix JSON strict violation error to match native parse error + * Include the `body` property on verify errors + * Include the `type` property on all generated errors + * Use `http-errors` to set status code on errors + * deps: bytes@3.0.0 + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + * deps: iconv-lite@0.4.18 + - Add support for React Native + - Add a warning if not loaded as utf-8 + - Fix CESU-8 decoding in Node.js 8 + - Improve speed of ISO-8859-1 encoding + * deps: qs@6.5.0 + * deps: raw-body@2.3.1 + - Use `http-errors` for standard emitted errors + - deps: bytes@3.0.0 + - deps: iconv-lite@0.4.18 + - perf: skip buffer decoding on overage chunk + * perf: prevent internal `throw` when missing charset + +1.17.2 / 2017-05-17 +=================== + + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + +1.17.1 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +1.17.0 / 2017-03-01 +=================== + + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + * deps: qs@6.3.1 + - Fix compacting nested arrays + +1.16.1 / 2017-02-10 +=================== + + * deps: debug@2.6.1 + - Fix deprecation messages in WebStorm and other editors + - Undeprecate `DEBUG_FD` set to `1` or `2` + +1.16.0 / 2017-01-17 +=================== + + * deps: debug@2.6.0 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.15 + - Added encoding MS-31J + - Added encoding MS-932 + - Added encoding MS-936 + - Added encoding MS-949 + - Added encoding MS-950 + - Fix GBK/GB18030 handling of Euro character + * deps: qs@6.2.1 + - Fix array parsing from skipping empty values + * deps: raw-body@~2.2.0 + - deps: iconv-lite@0.4.15 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +1.15.2 / 2016-06-19 +=================== + + * deps: bytes@2.4.0 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: http-errors@~1.5.0 + - Use `setprototypeof` module to replace `__proto__` setting + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: qs@6.2.0 + * deps: raw-body@~2.1.7 + - deps: bytes@2.4.0 + - perf: remove double-cleanup on happy path + * deps: type-is@~1.6.13 + - deps: mime-types@~2.1.11 + +1.15.1 / 2016-05-05 +=================== + + * deps: bytes@2.3.0 + - Drop partial bytes on all parsed units + - Fix parsing byte string that looks like hex + * deps: raw-body@~2.1.6 + - deps: bytes@2.3.0 + * deps: type-is@~1.6.12 + - deps: mime-types@~2.1.10 + +1.15.0 / 2016-02-10 +=================== + + * deps: http-errors@~1.4.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.2.1 < 2' + * deps: qs@6.1.0 + * deps: type-is@~1.6.11 + - deps: mime-types@~2.1.9 + +1.14.2 / 2015-12-16 +=================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + * deps: qs@5.2.0 + * deps: raw-body@~2.1.5 + - deps: bytes@2.2.0 + - deps: iconv-lite@0.4.13 + * deps: type-is@~1.6.10 + - deps: mime-types@~2.1.8 + +1.14.1 / 2015-09-27 +=================== + + * Fix issue where invalid charset results in 400 when `verify` used + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + * deps: raw-body@~2.1.4 + - Fix masking critical errors from `iconv-lite` + - deps: iconv-lite@0.4.12 + * deps: type-is@~1.6.9 + - deps: mime-types@~2.1.7 + +1.14.0 / 2015-09-16 +=================== + + * Fix JSON strict parse error to match syntax errors + * Provide static `require` analysis in `urlencoded` parser + * deps: depd@~1.1.0 + - Support web browser loading + * deps: qs@5.1.0 + * deps: raw-body@~2.1.3 + - Fix sync callback when attaching data listener causes sync read + * deps: type-is@~1.6.8 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.6 + +1.13.3 / 2015-07-31 +=================== + + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +1.13.2 / 2015-07-05 +=================== + + * deps: iconv-lite@0.4.11 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix user-visible incompatibilities from 3.1.0 + - Fix various parsing edge cases + * deps: raw-body@~2.1.2 + - Fix error stack traces to skip `makeError` + - deps: iconv-lite@0.4.11 + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +1.13.1 / 2015-06-16 +=================== + + * deps: qs@2.4.2 + - Downgraded from 3.1.0 because of user-visible incompatibilities + +1.13.0 / 2015-06-14 +=================== + + * Add `statusCode` property on `Error`s, in addition to `status` + * Change `type` default to `application/json` for JSON parser + * Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser + * Provide static `require` analysis + * Use the `http-errors` module to generate errors + * deps: bytes@2.1.0 + - Slight optimizations + * deps: iconv-lite@0.4.10 + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + - Leading BOM is now removed when decoding + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: qs@3.1.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + - Parsed object now has `null` prototype + * deps: raw-body@~2.1.1 + - Use `unpipe` module for unpiping requests + - deps: iconv-lite@0.4.10 + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: remove argument reassignment + * perf: remove delete call + +1.12.4 / 2015-05-10 +=================== + + * deps: debug@~2.2.0 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: on-finished@~2.2.1 + * deps: raw-body@~2.0.1 + - Fix a false-positive when unpiping in Node.js 0.8 + - deps: bytes@2.0.1 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +1.12.3 / 2015-04-15 +=================== + + * Slight efficiency improvement when not debugging + * deps: depd@~1.0.1 + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + * deps: raw-body@1.3.4 + - Fix hanging callback if request aborts during read + - deps: iconv-lite@0.4.8 + +1.12.2 / 2015-03-16 +=================== + + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + +1.12.1 / 2015-03-15 +=================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +1.12.0 / 2015-02-13 +=================== + + * add `debug` messages + * accept a function for the `type` option + * use `content-type` to parse `Content-Type` headers + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + * deps: raw-body@1.3.3 + - deps: iconv-lite@0.4.7 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +1.11.0 / 2015-01-30 +=================== + + * make internal `extended: true` depth limit infinity + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +1.10.2 / 2015-01-20 +=================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + * deps: raw-body@1.3.2 + - deps: iconv-lite@0.4.6 + +1.10.1 / 2015-01-01 +=================== + + * deps: on-finished@~2.2.0 + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +1.10.0 / 2014-12-02 +=================== + + * make internal `extended: true` array limit dynamic + +1.9.3 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + * deps: raw-body@1.3.1 + - deps: iconv-lite@0.4.5 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +1.9.2 / 2014-10-27 +================== + + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +1.9.1 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +1.9.0 / 2014-09-24 +================== + + * include the charset in "unsupported charset" error message + * include the encoding in "unsupported content encoding" error message + * deps: depd@~1.0.0 + +1.8.4 / 2014-09-23 +================== + + * fix content encoding to be case-insensitive + +1.8.3 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +1.8.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + +1.8.1 / 2014-09-07 +================== + + * deps: media-typer@0.3.0 + * deps: type-is@~1.5.1 + +1.8.0 / 2014-09-05 +================== + + * make empty-body-handling consistent between chunked requests + - empty `json` produces `{}` + - empty `raw` produces `new Buffer(0)` + - empty `text` produces `''` + - empty `urlencoded` produces `{}` + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: type-is@~1.5.0 + - fix `hasbody` to be true for `content-length: 0` + +1.7.0 / 2014-09-01 +================== + + * add `parameterLimit` option to `urlencoded` parser + * change `urlencoded` extended array limit to 100 + * respond with 413 when over `parameterLimit` in `urlencoded` + +1.6.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +1.6.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +1.6.5 / 2014-08-16 +================== + + * deps: on-finished@2.1.0 + +1.6.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + +1.6.3 / 2014-08-10 +================== + + * deps: qs@1.2.1 + +1.6.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +1.6.1 / 2014-08-06 +================== + + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +1.6.0 / 2014-08-05 +================== + + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + +1.5.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +1.5.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +1.5.0 / 2014-07-20 +================== + + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + * deps: raw-body@1.3.0 + - deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + - Fix `Cannot switch to old mode now` error on Node.js 0.10+ + * deps: type-is@~1.3.2 + +1.4.3 / 2014-06-19 +================== + + * deps: type-is@1.3.1 + - fix global variable leak + +1.4.2 / 2014-06-19 +================== + + * deps: type-is@1.3.0 + - improve type parsing + +1.4.1 / 2014-06-19 +================== + + * fix urlencoded extended deprecation message + +1.4.0 / 2014-06-19 +================== + + * add `text` parser + * add `raw` parser + * check accepted charset in content-type (accepts utf-8) + * check accepted encoding in content-encoding (accepts identity) + * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed + * deprecate `urlencoded()` without provided `extended` option + * lazy-load urlencoded parsers + * parsers split into files for reduced mem usage + * support gzip and deflate bodies + - set `inflate: false` to turn off + * deps: raw-body@1.2.2 + - Support all encodings from `iconv-lite` + +1.3.1 / 2014-06-11 +================== + + * deps: type-is@1.2.1 + - Switch dependency from mime to mime-types@1.0.0 + +1.3.0 / 2014-05-31 +================== + + * add `extended` option to urlencoded parser + +1.2.2 / 2014-05-27 +================== + + * deps: raw-body@1.1.6 + - assert stream encoding on node.js 0.8 + - assert stream encoding on node.js < 0.10.6 + - deps: bytes@1 + +1.2.1 / 2014-05-26 +================== + + * invoke `next(err)` after request fully read + - prevents hung responses and socket hang ups + +1.2.0 / 2014-05-11 +================== + + * add `verify` option + * deps: type-is@1.2.0 + - support suffix matching + +1.1.2 / 2014-05-11 +================== + + * improve json parser speed + +1.1.1 / 2014-05-11 +================== + + * fix repeated limit parsing with every request + +1.1.0 / 2014-05-10 +================== + + * add `type` option + * deps: pin for safety and consistency + +1.0.2 / 2014-04-14 +================== + + * use `type-is` module + +1.0.1 / 2014-03-20 +================== + + * lower default limits to 100kb diff --git a/app/node_modules/body-parser/LICENSE b/app/node_modules/body-parser/LICENSE new file mode 100644 index 0000000..386b7b6 --- /dev/null +++ b/app/node_modules/body-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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/app/node_modules/body-parser/README.md b/app/node_modules/body-parser/README.md new file mode 100644 index 0000000..d9138bc --- /dev/null +++ b/app/node_modules/body-parser/README.md @@ -0,0 +1,445 @@ +# body-parser + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js body parsing middleware. + +Parse incoming request bodies in a middleware before your handlers, available +under the `req.body` property. + +**Note** As `req.body`'s shape is based on user-controlled input, all +properties and values in this object are untrusted and should be validated +before trusting. For example, `req.body.foo.toString()` may fail in multiple +ways, for example the `foo` property may not be there or may not be a string, +and `toString` may not be a function and instead a string or other user input. + +[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/). + +_This does not handle multipart bodies_, due to their complex and typically +large nature. For multipart bodies, you may be interested in the following +modules: + + * [busboy](https://www.npmjs.org/package/busboy#readme) and + [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) + * [multiparty](https://www.npmjs.org/package/multiparty#readme) and + [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) + * [formidable](https://www.npmjs.org/package/formidable#readme) + * [multer](https://www.npmjs.org/package/multer#readme) + +This module provides the following parsers: + + * [JSON body parser](#bodyparserjsonoptions) + * [Raw body parser](#bodyparserrawoptions) + * [Text body parser](#bodyparsertextoptions) + * [URL-encoded form body parser](#bodyparserurlencodedoptions) + +Other body parsers you might be interested in: + +- [body](https://www.npmjs.org/package/body#readme) +- [co-body](https://www.npmjs.org/package/co-body#readme) + +## Installation + +```sh +$ npm install body-parser +``` + +## API + + + +```js +var bodyParser = require('body-parser') +``` + +The `bodyParser` object exposes various factories to create middlewares. All +middlewares will populate the `req.body` property with the parsed body when +the `Content-Type` request header matches the `type` option, or an empty +object (`{}`) if there was no body to parse, the `Content-Type` was not matched, +or an error occurred. + +The various errors returned by this module are described in the +[errors section](#errors). + +### bodyParser.json([options]) + +Returns middleware that only parses `json` and only looks at requests where +the `Content-Type` header matches the `type` option. This parser accepts any +Unicode encoding of the body and supports automatic inflation of `gzip` and +`deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). + +#### Options + +The `json` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### reviver + +The `reviver` option is passed directly to `JSON.parse` as the second +argument. You can find more information on this argument +[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). + +##### strict + +When set to `true`, will only accept arrays and objects; when `false` will +accept anything `JSON.parse` accepts. Defaults to `true`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not a +function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `json`), a mime type (like `application/json`), or +a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a truthy +value. Defaults to `application/json`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.raw([options]) + +Returns middleware that parses all bodies as a `Buffer` and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a `Buffer` object +of the body. + +#### Options + +The `raw` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. +If not a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this +can be an extension name (like `bin`), a mime type (like +`application/octet-stream`), or a mime type with a wildcard (like `*/*` or +`application/*`). If a function, the `type` option is called as `fn(req)` +and the request is parsed if it returns a truthy value. Defaults to +`application/octet-stream`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.text([options]) + +Returns middleware that parses all bodies as a string and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` string containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a string of the +body. + +#### Options + +The `text` function takes an optional `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the text content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `txt`), a mime type (like `text/plain`), or a mime +type with a wildcard (like `*/*` or `text/*`). If a function, the `type` +option is called as `fn(req)` and the request is parsed if it returns a +truthy value. Defaults to `text/plain`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.urlencoded([options]) + +Returns middleware that only parses `urlencoded` bodies and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser accepts only UTF-8 encoding of the body and supports automatic +inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This object will contain +key-value pairs, where the value can be a string or array (when `extended` is +`false`), or any type (when `extended` is `true`). + +#### Options + +The `urlencoded` function takes an optional `options` object that may contain +any of the following keys: + +##### extended + +The `extended` option allows to choose between parsing the URL-encoded data +with the `querystring` library (when `false`) or the `qs` library (when +`true`). The "extended" syntax allows for rich objects and arrays to be +encoded into the URL-encoded format, allowing for a JSON-like experience +with URL-encoded. For more information, please +[see the qs library](https://www.npmjs.org/package/qs#readme). + +Defaults to `true`, but using the default has been deprecated. Please +research into the difference between `qs` and `querystring` and choose the +appropriate setting. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### parameterLimit + +The `parameterLimit` option controls the maximum number of parameters that +are allowed in the URL-encoded data. If a request contains more parameters +than this value, a 413 will be returned to the client. Defaults to `1000`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a string, array of strings, or a function. If not +a function, `type` option is passed directly to the +[type-is](https://www.npmjs.org/package/type-is#readme) library and this can +be an extension name (like `urlencoded`), a mime type (like +`application/x-www-form-urlencoded`), or a mime type with a wildcard (like +`*/x-www-form-urlencoded`). If a function, the `type` option is called as +`fn(req)` and the request is parsed if it returns a truthy value. Defaults +to `application/x-www-form-urlencoded`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +## Errors + +The middlewares provided by this module create errors depending on the error +condition during parsing. The errors will typically have a `status`/`statusCode` +property that contains the suggested HTTP response code, an `expose` property +to determine if the `message` property should be displayed to the client, a +`type` property to determine the type of error without matching against the +`message`, and a `body` property containing the read body, if available. + +The following are the common errors emitted, though any error can come through +for various reasons. + +### content encoding unsupported + +This error will occur when the request had a `Content-Encoding` header that +contained an encoding but the "inflation" option was set to `false`. The +`status` property is set to `415`, the `type` property is set to +`'encoding.unsupported'`, and the `charset` property will be set to the +encoding that is unsupported. + +### request aborted + +This error will occur when the request is aborted by the client before reading +the body has finished. The `received` property will be set to the number of +bytes received before the request was aborted and the `expected` property is +set to the number of expected bytes. The `status` property is set to `400` +and `type` property is set to `'request.aborted'`. + +### request entity too large + +This error will occur when the request body's size is larger than the "limit" +option. The `limit` property will be set to the byte limit and the `length` +property will be set to the request body's length. The `status` property is +set to `413` and the `type` property is set to `'entity.too.large'`. + +### request size did not match content length + +This error will occur when the request's length did not match the length from +the `Content-Length` header. This typically occurs when the request is malformed, +typically when the `Content-Length` header was calculated based on characters +instead of bytes. The `status` property is set to `400` and the `type` property +is set to `'request.size.invalid'`. + +### stream encoding should not be set + +This error will occur when something called the `req.setEncoding` method prior +to this middleware. This module operates directly on bytes only and you cannot +call `req.setEncoding` when using this module. The `status` property is set to +`500` and the `type` property is set to `'stream.encoding.set'`. + +### too many parameters + +This error will occur when the content of the request exceeds the configured +`parameterLimit` for the `urlencoded` parser. The `status` property is set to +`413` and the `type` property is set to `'parameters.too.many'`. + +### unsupported charset "BOGUS" + +This error will occur when the request had a charset parameter in the +`Content-Type` header, but the `iconv-lite` module does not support it OR the +parser does not support it. The charset is contained in the message as well +as in the `charset` property. The `status` property is set to `415`, the +`type` property is set to `'charset.unsupported'`, and the `charset` property +is set to the charset that is unsupported. + +### unsupported content encoding "bogus" + +This error will occur when the request had a `Content-Encoding` header that +contained an unsupported encoding. The encoding is contained in the message +as well as in the `encoding` property. The `status` property is set to `415`, +the `type` property is set to `'encoding.unsupported'`, and the `encoding` +property is set to the encoding that is unsupported. + +## Examples + +### Express/Connect top-level generic + +This example demonstrates adding a generic JSON and URL-encoded parser as a +top-level middleware, which will parse the bodies of all incoming requests. +This is the simplest setup. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse application/x-www-form-urlencoded +app.use(bodyParser.urlencoded({ extended: false })) + +// parse application/json +app.use(bodyParser.json()) + +app.use(function (req, res) { + res.setHeader('Content-Type', 'text/plain') + res.write('you posted:\n') + res.end(JSON.stringify(req.body, null, 2)) +}) +``` + +### Express route-specific + +This example demonstrates adding body parsers specifically to the routes that +need them. In general, this is the most recommended way to use body-parser with +Express. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// create application/json parser +var jsonParser = bodyParser.json() + +// create application/x-www-form-urlencoded parser +var urlencodedParser = bodyParser.urlencoded({ extended: false }) + +// POST /login gets urlencoded bodies +app.post('/login', urlencodedParser, function (req, res) { + if (!req.body) return res.sendStatus(400) + res.send('welcome, ' + req.body.username) +}) + +// POST /api/users gets JSON bodies +app.post('/api/users', jsonParser, function (req, res) { + if (!req.body) return res.sendStatus(400) + // create user in req.body +}) +``` + +### Change accepted type for parsers + +All the parsers accept a `type` option which allows you to change the +`Content-Type` that the middleware will parse. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse various different custom JSON types as JSON +app.use(bodyParser.json({ type: 'application/*+json' })) + +// parse some custom thing into a Buffer +app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) + +// parse an HTML body into a string +app.use(bodyParser.text({ type: 'text/html' })) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/body-parser.svg +[npm-url]: https://npmjs.org/package/body-parser +[travis-image]: https://img.shields.io/travis/expressjs/body-parser/master.svg +[travis-url]: https://travis-ci.org/expressjs/body-parser +[coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master +[downloads-image]: https://img.shields.io/npm/dm/body-parser.svg +[downloads-url]: https://npmjs.org/package/body-parser diff --git a/app/node_modules/body-parser/index.js b/app/node_modules/body-parser/index.js new file mode 100644 index 0000000..93c3a1f --- /dev/null +++ b/app/node_modules/body-parser/index.js @@ -0,0 +1,157 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('body-parser') + +/** + * Cache of loaded parsers. + * @private + */ + +var parsers = Object.create(null) + +/** + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded + */ + +/** + * Module exports. + * @type {Parsers} + */ + +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') + +/** + * JSON parser. + * @public + */ + +Object.defineProperty(exports, 'json', { + configurable: true, + enumerable: true, + get: createParserGetter('json') +}) + +/** + * Raw parser. + * @public + */ + +Object.defineProperty(exports, 'raw', { + configurable: true, + enumerable: true, + get: createParserGetter('raw') +}) + +/** + * Text parser. + * @public + */ + +Object.defineProperty(exports, 'text', { + configurable: true, + enumerable: true, + get: createParserGetter('text') +}) + +/** + * URL-encoded parser. + * @public + */ + +Object.defineProperty(exports, 'urlencoded', { + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +}) + +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @deprecated + * @public + */ + +function bodyParser (options) { + var opts = {} + + // exclude type option + if (options) { + for (var prop in options) { + if (prop !== 'type') { + opts[prop] = options[prop] + } + } + } + + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) + + return function bodyParser (req, res, next) { + _json(req, res, function (err) { + if (err) return next(err) + _urlencoded(req, res, next) + }) + } +} + +/** + * Create a getter for loading a parser. + * @private + */ + +function createParserGetter (name) { + return function get () { + return loadParser(name) + } +} + +/** + * Load a parser module. + * @private + */ + +function loadParser (parserName) { + var parser = parsers[parserName] + + if (parser !== undefined) { + return parser + } + + // this uses a switch for static require analysis + switch (parserName) { + case 'json': + parser = require('./lib/types/json') + break + case 'raw': + parser = require('./lib/types/raw') + break + case 'text': + parser = require('./lib/types/text') + break + case 'urlencoded': + parser = require('./lib/types/urlencoded') + break + } + + // store to prevent invoking require() + return (parsers[parserName] = parser) +} diff --git a/app/node_modules/body-parser/lib/read.js b/app/node_modules/body-parser/lib/read.js new file mode 100644 index 0000000..c102609 --- /dev/null +++ b/app/node_modules/body-parser/lib/read.js @@ -0,0 +1,181 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var getBody = require('raw-body') +var iconv = require('iconv-lite') +var onFinished = require('on-finished') +var zlib = require('zlib') + +/** + * Module exports. + */ + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {function} debug + * @param {object} options + * @private + */ + +function read (req, res, next, parse, debug, options) { + var length + var opts = options + var stream + + // flag as parsed + req._body = true + + // read options + var encoding = opts.encoding !== null + ? opts.encoding + : null + var verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + var _error + + if (error.type === 'encoding.unsupported') { + // echo back charset + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + }) + } else { + // set status code on error + _error = createError(400, error) + } + + // read off entire request + stream.resume() + onFinished(req, function onfinished () { + next(createError(400, _error)) + }) + return + } + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + next(createError(403, err, { + body: body, + type: err.type || 'entity.verify.failed' + })) + return + } + } + + // parse + var str = body + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str) + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || 'entity.parse.failed' + })) + return + } + + next() + }) +} + +/** + * Get the content stream of the request. + * + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private + */ + +function contentstream (req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + var stream + + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + switch (encoding) { + case 'deflate': + stream = zlib.createInflate() + debug('inflate body') + req.pipe(stream) + break + case 'gzip': + stream = zlib.createGunzip() + debug('gunzip body') + req.pipe(stream) + break + case 'identity': + stream = req + stream.length = length + break + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + return stream +} diff --git a/app/node_modules/body-parser/lib/types/json.js b/app/node_modules/body-parser/lib/types/json.js new file mode 100644 index 0000000..2971dc1 --- /dev/null +++ b/app/node_modules/body-parser/lib/types/json.js @@ -0,0 +1,230 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:json') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = json + +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ + +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex + +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function json (options) { + var opts = options || {} + + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var inflate = opts.inflate !== false + var reviver = opts.reviver + var strict = opts.strict !== false + var type = opts.type || 'application/json' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } + + if (strict) { + var first = firstchar(body) + + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } + } + + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) + } + } + + return function jsonParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset per RFC 7159 sec 8.1 + var charset = getCharset(req) || 'utf-8' + if (charset.substr(0, 4) !== 'utf-') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Create strict violation syntax error matching native error. + * + * @param {string} str + * @param {string} char + * @return {Error} + * @private + */ + +function createStrictSyntaxError (str, char) { + var index = str.indexOf(char) + var partial = str.substring(0, index) + '#' + + try { + JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') + } catch (e) { + return normalizeJsonSyntaxError(e, { + message: e.message.replace('#', char), + stack: e.stack + }) + } +} + +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @private + */ + +function firstchar (str) { + return FIRST_CHAR_REGEXP.exec(str)[1] +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Normalize a SyntaxError for JSON.parse. + * + * @param {SyntaxError} error + * @param {object} obj + * @return {SyntaxError} + */ + +function normalizeJsonSyntaxError (error, obj) { + var keys = Object.getOwnPropertyNames(error) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] + } + } + + // replace stack before message for Node.js 0.10 and below + error.stack = obj.stack.replace(error.message, obj.message) + error.message = obj.message + + return error +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/app/node_modules/body-parser/lib/types/raw.js b/app/node_modules/body-parser/lib/types/raw.js new file mode 100644 index 0000000..f5d1b67 --- /dev/null +++ b/app/node_modules/body-parser/lib/types/raw.js @@ -0,0 +1,101 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var debug = require('debug')('body-parser:raw') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function raw (options) { + var opts = options || {} + + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/octet-stream' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function rawParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/app/node_modules/body-parser/lib/types/text.js b/app/node_modules/body-parser/lib/types/text.js new file mode 100644 index 0000000..083a009 --- /dev/null +++ b/app/node_modules/body-parser/lib/types/text.js @@ -0,0 +1,121 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var debug = require('debug')('body-parser:text') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = text + +/** + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function text (options) { + var opts = options || {} + + var defaultCharset = opts.defaultCharset || 'utf-8' + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'text/plain' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function textParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // get charset + var charset = getCharset(req) || defaultCharset + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/app/node_modules/body-parser/lib/types/urlencoded.js b/app/node_modules/body-parser/lib/types/urlencoded.js new file mode 100644 index 0000000..5ccda21 --- /dev/null +++ b/app/node_modules/body-parser/lib/types/urlencoded.js @@ -0,0 +1,284 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:urlencoded') +var deprecate = require('depd')('body-parser') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = urlencoded + +/** + * Cache of parser modules. + */ + +var parsers = Object.create(null) + +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function urlencoded (options) { + var opts = options || {} + + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') + } + + var extended = opts.extended !== false + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/x-www-form-urlencoded' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + return body.length + ? queryparse(body) + : {} + } + + return function urlencodedParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset + var charset = getCharset(req) || 'utf-8' + if (charset !== 'utf-8') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the extended query parser. + * + * @param {object} options + */ + +function extendedparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('qs') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + var arrayLimit = Math.max(100, paramCount) + + debug('parse extended urlencoding') + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: Infinity, + parameterLimit: parameterLimit + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @api private + */ + +function parameterCount (body, limit) { + var count = 0 + var index = 0 + + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ + + if (count === limit) { + return undefined + } + } + + return count +} + +/** + * Get parser for module name dynamically. + * + * @param {string} name + * @return {function} + * @api private + */ + +function parser (name) { + var mod = parsers[name] + + if (mod !== undefined) { + return mod.parse + } + + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = require('qs') + break + case 'querystring': + mod = require('querystring') + break + } + + // store to prevent invoking require() + parsers[name] = mod + + return mod.parse +} + +/** + * Get the simple query parser. + * + * @param {object} options + */ + +function simpleparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + debug('parse urlencoding') + return parse(body, undefined, undefined, {maxKeys: parameterLimit}) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/app/node_modules/body-parser/package.json b/app/node_modules/body-parser/package.json new file mode 100644 index 0000000..db78b73 --- /dev/null +++ b/app/node_modules/body-parser/package.json @@ -0,0 +1,52 @@ +{ + "name": "body-parser", + "description": "Node.js body parsing middleware", + "version": "1.18.3", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "repository": "expressjs/body-parser", + "dependencies": { + "bytes": "3.0.0", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "~1.1.2", + "http-errors": "~1.6.3", + "iconv-lite": "0.4.23", + "on-finished": "~2.3.0", + "qs": "6.5.2", + "raw-body": "2.3.3", + "type-is": "~1.6.16" + }, + "devDependencies": { + "eslint": "4.19.1", + "eslint-config-standard": "11.0.0", + "eslint-plugin-import": "2.11.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "6.0.1", + "eslint-plugin-promise": "3.7.0", + "eslint-plugin-standard": "3.1.0", + "istanbul": "0.4.5", + "methods": "1.1.2", + "mocha": "2.5.3", + "safe-buffer": "5.1.2", + "supertest": "1.1.0" + }, + "files": [ + "lib/", + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/" + } +} diff --git a/app/node_modules/bson/HISTORY.md b/app/node_modules/bson/HISTORY.md new file mode 100644 index 0000000..ae3acaa --- /dev/null +++ b/app/node_modules/bson/HISTORY.md @@ -0,0 +1,243 @@ + +## [1.0.9](https://github.com/mongodb/js-bson/compare/v1.0.8...v1.0.9) (2018-06-07) + + +### Bug Fixes + +* **serializer:** remove use of `const` ([5feb12f](https://github.com/mongodb/js-bson/commit/5feb12f)) + + + + +## [1.0.7](https://github.com/mongodb/js-bson/compare/v1.0.6...v1.0.7) (2018-06-06) + + +### Bug Fixes + +* **binary:** add type checking for buffer ([26b05b5](https://github.com/mongodb/js-bson/commit/26b05b5)) +* **bson:** fix custom inspect property ([080323b](https://github.com/mongodb/js-bson/commit/080323b)) +* **readme:** clarify documentation about deserialize methods ([20f764c](https://github.com/mongodb/js-bson/commit/20f764c)) +* **serialization:** normalize function stringification ([1320c10](https://github.com/mongodb/js-bson/commit/1320c10)) + + + + +## [1.0.6](https://github.com/mongodb/js-bson/compare/v1.0.5...v1.0.6) (2018-03-12) + + +### Features + +* **serialization:** support arbitrary sizes for the internal serialization buffer ([abe97bc](https://github.com/mongodb/js-bson/commit/abe97bc)) + + + + +## 1.0.5 (2018-02-26) + + +### Bug Fixes + +* **decimal128:** add basic guard against REDOS attacks ([bd61c45](https://github.com/mongodb/js-bson/commit/bd61c45)) +* **objectid:** if pid is 1, use random value ([e188ae6](https://github.com/mongodb/js-bson/commit/e188ae6)) + + + +1.0.4 2016-01-11 +---------------- +- #204 remove Buffer.from as it's partially broken in early 4.x.x. series of node releases. + +1.0.3 2016-01-03 +---------------- +- Fixed toString for ObjectId so it will work with inspect. + +1.0.2 2016-01-02 +---------------- +- Minor optimizations for ObjectID to use Buffer.from where available. + +1.0.1 2016-12-06 +---------------- +- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons. + +1.0.0 2016-12-06 +---------------- +- Introduced new BSON API and documentation. + +0.5.7 2016-11-18 +----------------- +- NODE-848 BSON Regex flags must be alphabetically ordered. + +0.5.6 2016-10-19 +----------------- +- NODE-833, Detects cyclic dependencies in documents and throws error if one is found. +- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke). + +0.5.5 2016-09-15 +----------------- +- Added DBPointer up conversion to DBRef + +0.5.4 2016-08-23 +----------------- +- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only. + +0.5.3 2016-07-11 +----------------- +- Throw error if ObjectId is not a string or a buffer. + +0.5.2 2016-07-11 +----------------- +- All values encoded big-endian style for ObjectId. + +0.5.1 2016-07-11 +----------------- +- Fixed encoding/decoding issue in ObjectId timestamp generation. +- Removed BinaryParser dependency from the serializer/deserializer. + +0.5.0 2016-07-05 +----------------- +- Added Decimal128 type and extended test suite to include entire bson corpus. + +0.4.23 2016-04-08 +----------------- +- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries. +- Remove one package from dependency due to having been pulled from NPM. + +0.4.22 2016-03-04 +----------------- +- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas). +- Fixed issue with undefined type on deserializing. + +0.4.21 2016-01-12 +----------------- +- Minor optimizations to avoid non needed object creation. + +0.4.20 2015-10-15 +----------------- +- Added bower file to repository. +- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed) + +0.4.19 2015-10-15 +----------------- +- Remove all support for bson-ext. + +0.4.18 2015-10-15 +----------------- +- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139 +- add option for deserializing binary into Buffer object #116 + +0.4.17 2015-10-15 +----------------- +- Validate regexp string for null bytes and throw if there is one. + +0.4.16 2015-10-07 +----------------- +- Fixed issue with return statement in Map.js. + +0.4.15 2015-10-06 +----------------- +- Exposed Map correctly via index.js file. + +0.4.14 2015-10-06 +----------------- +- Exposed Map correctly via bson.js file. + +0.4.13 2015-10-06 +----------------- +- Added ES6 Map type serialization as well as a polyfill for ES5. + +0.4.12 2015-09-18 +----------------- +- Made ignore undefined an optional parameter. + +0.4.11 2015-08-06 +----------------- +- Minor fix for invalid key checking. + +0.4.10 2015-08-06 +----------------- +- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. +- Some performance improvements by in lining code. + +0.4.9 2015-08-06 +---------------- +- Undefined fields are omitted from serialization in objects. + +0.4.8 2015-07-14 +---------------- +- Fixed size validation to ensure we can deserialize from dumped files. + +0.4.7 2015-06-26 +---------------- +- Added ability to instruct deserializer to return raw BSON buffers for named array fields. +- Minor deserialization optimization by moving inlined function out. + +0.4.6 2015-06-17 +---------------- +- Fixed serializeWithBufferAndIndex bug. + +0.4.5 2015-06-17 +---------------- +- Removed any references to the shared buffer to avoid non GC collectible bson instances. + +0.4.4 2015-06-17 +---------------- +- Fixed rethrowing of error when not RangeError. + +0.4.3 2015-06-17 +---------------- +- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. + +0.4.2 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.1 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.0 2015-06-16 +---------------- +- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. +- Removed bson-ext extension dependency for now. + +0.3.2 2015-03-27 +---------------- +- Removed node-gyp from install script in package.json. + +0.3.1 2015-03-27 +---------------- +- Return pure js version on native() call if failed to initialize. + +0.3.0 2015-03-26 +---------------- +- Pulled out all C++ code into bson-ext and made it an optional dependency. + +0.2.21 2015-03-21 +----------------- +- Updated Nan to 1.7.0 to support io.js and node 0.12.0 + +0.2.19 2015-02-16 +----------------- +- Updated Nan to 1.6.2 to support io.js and node 0.12.0 + +0.2.18 2015-01-20 +----------------- +- Updated Nan to 1.5.1 to support io.js + +0.2.16 2014-12-17 +----------------- +- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's + +0.2.12 2014-08-24 +----------------- +- Fixes for fortify review of c++ extension +- toBSON correctly allows returns of non objects + +0.2.3 2013-10-01 +---------------- +- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) +- Fixed issue where corrupt CString's could cause endless loop +- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) + +0.1.4 2012-09-25 +---------------- +- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/app/node_modules/bson/LICENSE.md b/app/node_modules/bson/LICENSE.md new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/app/node_modules/bson/LICENSE.md @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/app/node_modules/bson/README.md b/app/node_modules/bson/README.md new file mode 100644 index 0000000..0688341 --- /dev/null +++ b/app/node_modules/bson/README.md @@ -0,0 +1,170 @@ +# BSON parser + +BSON is short for Bin­ary JSON and is the bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. You can learn more about it in [the specification](http://bsonspec.org). + +This browser version of the BSON parser is compiled using [webpack](https://webpack.js.org/) and the current version is pre-compiled in the `browser_build` directory. + +This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext). + +## Usage + +To build a new version perform the following operations: + +``` +npm install +npm run build +``` + +A simple example of how to use BSON in the browser: + +```html + + + +``` + +A simple example of how to use BSON in `Node.js`: + +```js +// Get BSON parser class +var BSON = require('bson') +// Get the Long type +var Long = BSON.Long; +// Create a bson parser instance +var bson = new BSON(); + +// Serialize document +var doc = { long: Long.fromNumber(100) } + +// Serialize a document +var data = bson.serialize(doc) +console.log('data:', data) + +// Deserialize the resulting Buffer +var doc_2 = bson.deserialize(data) +console.log('doc_2:', doc_2) +``` + +## Installation + +`npm install bson` + +## API + +### BSON types + +For all BSON types documentation, please refer to the following sources: + * [MongoDB BSON Type Reference](https://docs.mongodb.com/manual/reference/bson-types/) + * [BSON Spec](https://bsonspec.org/) + +### BSON serialization and deserialiation + +**`new BSON()`** - Creates a new BSON serializer/deserializer you can use to serialize and deserialize BSON. + +#### BSON.serialize + +The BSON `serialize` method takes a JavaScript object and an optional options object and returns a Node.js Buffer. + + * `BSON.serialize(object, options)` + * @param {Object} object the JavaScript object to serialize. + * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. + * @param {Boolean} [options.ignoreUndefined=true] + * @return {Buffer} returns a Buffer instance. + +#### BSON.serializeWithBufferAndIndex + +The BSON `serializeWithBufferAndIndex` method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer. + + * `BSON.serializeWithBufferAndIndex(object, buffer, options)` + * @param {Object} object the JavaScript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields. + * @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + +#### BSON.calculateObjectSize + +The BSON `calculateObjectSize` method takes a JavaScript object and an optional options object and returns the size of the BSON object. + + * `BSON.calculateObjectSize(object, options)` + * @param {Object} object the JavaScript object to serialize. + * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. + * @param {Boolean} [options.ignoreUndefined=true] + * @return {Buffer} returns a Buffer instance. + +#### BSON.deserialize + +The BSON `deserialize` method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object. + + * `BSON.deserialize(buffer, options)` + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + +#### BSON.deserializeStream + +The BSON `deserializeStream` method takes a Node.js Buffer, `startIndex` and allow more control over deserialization of a Buffer containing concatenated BSON documents. + + * `BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options)` + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + +## FAQ + +#### Why does `undefined` get converted to `null`? + +The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. + +#### How do I add custom serialization logic? + +This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. + +```javascript +var bson = new BSON(); + +class CustomSerialize { + toBSON() { + return 42; + } +} + +const obj = { answer: new CustomSerialize() }; +// "{ answer: 42 }" +console.log(bson.deserialize(bson.serialize(obj))); +``` diff --git a/app/node_modules/bson/bower.json b/app/node_modules/bson/bower.json new file mode 100644 index 0000000..b32140e --- /dev/null +++ b/app/node_modules/bson/bower.json @@ -0,0 +1,25 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "author": "Christian Amor Kvalheim ", + "main": "./browser_build/bson.js", + "license": "Apache-2.0", + "moduleType": [ + "globals", + "node" + ], + "ignore": [ + "**/.*", + "alternate_parsers", + "benchmarks", + "bower_components", + "node_modules", + "test", + "tools" + ] +} diff --git a/app/node_modules/bson/browser_build/bson.js b/app/node_modules/bson/browser_build/bson.js new file mode 100644 index 0000000..a02bf14 --- /dev/null +++ b/app/node_modules/bson/browser_build/bson.js @@ -0,0 +1,17748 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else { + var a = factory(); + for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; + } +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/"; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(1); + module.exports = __webpack_require__(327); + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {"use strict"; + + __webpack_require__(2); + + __webpack_require__(323); + + __webpack_require__(324); + + if (global._babelPolyfill) { + throw new Error("only one instance of babel-polyfill is allowed"); + } + global._babelPolyfill = true; + + var DEFINE_PROPERTY = "defineProperty"; + function define(O, key, value) { + O[key] || Object[DEFINE_PROPERTY](O, key, { + writable: true, + configurable: true, + value: value + }); + } + + define(String.prototype, "padLeft", "".padStart); + define(String.prototype, "padRight", "".padEnd); + + "pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) { + [][key] && define(Array, key, Function.call.bind([][key])); + }); + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(3); + __webpack_require__(51); + __webpack_require__(52); + __webpack_require__(53); + __webpack_require__(54); + __webpack_require__(56); + __webpack_require__(59); + __webpack_require__(60); + __webpack_require__(61); + __webpack_require__(62); + __webpack_require__(63); + __webpack_require__(64); + __webpack_require__(65); + __webpack_require__(66); + __webpack_require__(67); + __webpack_require__(69); + __webpack_require__(71); + __webpack_require__(73); + __webpack_require__(75); + __webpack_require__(78); + __webpack_require__(79); + __webpack_require__(80); + __webpack_require__(84); + __webpack_require__(86); + __webpack_require__(88); + __webpack_require__(91); + __webpack_require__(92); + __webpack_require__(93); + __webpack_require__(94); + __webpack_require__(96); + __webpack_require__(97); + __webpack_require__(98); + __webpack_require__(99); + __webpack_require__(100); + __webpack_require__(101); + __webpack_require__(102); + __webpack_require__(104); + __webpack_require__(105); + __webpack_require__(106); + __webpack_require__(108); + __webpack_require__(109); + __webpack_require__(110); + __webpack_require__(112); + __webpack_require__(114); + __webpack_require__(115); + __webpack_require__(116); + __webpack_require__(117); + __webpack_require__(118); + __webpack_require__(119); + __webpack_require__(120); + __webpack_require__(121); + __webpack_require__(122); + __webpack_require__(123); + __webpack_require__(124); + __webpack_require__(125); + __webpack_require__(126); + __webpack_require__(131); + __webpack_require__(132); + __webpack_require__(136); + __webpack_require__(137); + __webpack_require__(138); + __webpack_require__(139); + __webpack_require__(141); + __webpack_require__(142); + __webpack_require__(143); + __webpack_require__(144); + __webpack_require__(145); + __webpack_require__(146); + __webpack_require__(147); + __webpack_require__(148); + __webpack_require__(149); + __webpack_require__(150); + __webpack_require__(151); + __webpack_require__(152); + __webpack_require__(153); + __webpack_require__(154); + __webpack_require__(155); + __webpack_require__(157); + __webpack_require__(158); + __webpack_require__(160); + __webpack_require__(161); + __webpack_require__(167); + __webpack_require__(168); + __webpack_require__(170); + __webpack_require__(171); + __webpack_require__(172); + __webpack_require__(176); + __webpack_require__(177); + __webpack_require__(178); + __webpack_require__(179); + __webpack_require__(180); + __webpack_require__(182); + __webpack_require__(183); + __webpack_require__(184); + __webpack_require__(185); + __webpack_require__(188); + __webpack_require__(190); + __webpack_require__(191); + __webpack_require__(192); + __webpack_require__(194); + __webpack_require__(196); + __webpack_require__(198); + __webpack_require__(199); + __webpack_require__(200); + __webpack_require__(202); + __webpack_require__(203); + __webpack_require__(204); + __webpack_require__(205); + __webpack_require__(216); + __webpack_require__(220); + __webpack_require__(221); + __webpack_require__(223); + __webpack_require__(224); + __webpack_require__(228); + __webpack_require__(229); + __webpack_require__(231); + __webpack_require__(232); + __webpack_require__(233); + __webpack_require__(234); + __webpack_require__(235); + __webpack_require__(236); + __webpack_require__(237); + __webpack_require__(238); + __webpack_require__(239); + __webpack_require__(240); + __webpack_require__(241); + __webpack_require__(242); + __webpack_require__(243); + __webpack_require__(244); + __webpack_require__(245); + __webpack_require__(246); + __webpack_require__(247); + __webpack_require__(248); + __webpack_require__(249); + __webpack_require__(251); + __webpack_require__(252); + __webpack_require__(253); + __webpack_require__(254); + __webpack_require__(255); + __webpack_require__(257); + __webpack_require__(258); + __webpack_require__(259); + __webpack_require__(261); + __webpack_require__(262); + __webpack_require__(263); + __webpack_require__(264); + __webpack_require__(265); + __webpack_require__(266); + __webpack_require__(267); + __webpack_require__(268); + __webpack_require__(270); + __webpack_require__(271); + __webpack_require__(273); + __webpack_require__(274); + __webpack_require__(275); + __webpack_require__(276); + __webpack_require__(279); + __webpack_require__(280); + __webpack_require__(282); + __webpack_require__(283); + __webpack_require__(284); + __webpack_require__(285); + __webpack_require__(287); + __webpack_require__(288); + __webpack_require__(289); + __webpack_require__(290); + __webpack_require__(291); + __webpack_require__(292); + __webpack_require__(293); + __webpack_require__(294); + __webpack_require__(295); + __webpack_require__(296); + __webpack_require__(298); + __webpack_require__(299); + __webpack_require__(300); + __webpack_require__(301); + __webpack_require__(302); + __webpack_require__(303); + __webpack_require__(304); + __webpack_require__(305); + __webpack_require__(306); + __webpack_require__(307); + __webpack_require__(308); + __webpack_require__(310); + __webpack_require__(311); + __webpack_require__(312); + __webpack_require__(313); + __webpack_require__(314); + __webpack_require__(315); + __webpack_require__(316); + __webpack_require__(317); + __webpack_require__(318); + __webpack_require__(319); + __webpack_require__(320); + __webpack_require__(321); + __webpack_require__(322); + module.exports = __webpack_require__(9); + + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // ECMAScript 6 symbols shim + var global = __webpack_require__(4); + var has = __webpack_require__(5); + var DESCRIPTORS = __webpack_require__(6); + var $export = __webpack_require__(8); + var redefine = __webpack_require__(18); + var META = __webpack_require__(22).KEY; + var $fails = __webpack_require__(7); + var shared = __webpack_require__(23); + var setToStringTag = __webpack_require__(25); + var uid = __webpack_require__(19); + var wks = __webpack_require__(26); + var wksExt = __webpack_require__(27); + var wksDefine = __webpack_require__(28); + var enumKeys = __webpack_require__(29); + var isArray = __webpack_require__(44); + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var toIObject = __webpack_require__(32); + var toPrimitive = __webpack_require__(16); + var createDesc = __webpack_require__(17); + var _create = __webpack_require__(45); + var gOPNExt = __webpack_require__(48); + var $GOPD = __webpack_require__(50); + var $DP = __webpack_require__(11); + var $keys = __webpack_require__(30); + var gOPD = $GOPD.f; + var dP = $DP.f; + var gOPN = gOPNExt.f; + var $Symbol = global.Symbol; + var $JSON = global.JSON; + var _stringify = $JSON && $JSON.stringify; + var PROTOTYPE = 'prototype'; + var HIDDEN = wks('_hidden'); + var TO_PRIMITIVE = wks('toPrimitive'); + var isEnum = {}.propertyIsEnumerable; + var SymbolRegistry = shared('symbol-registry'); + var AllSymbols = shared('symbols'); + var OPSymbols = shared('op-symbols'); + var ObjectProto = Object[PROTOTYPE]; + var USE_NATIVE = typeof $Symbol == 'function'; + var QObject = global.QObject; + // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 + var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; + + // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 + var setSymbolDesc = DESCRIPTORS && $fails(function () { + return _create(dP({}, 'a', { + get: function () { return dP(this, 'a', { value: 7 }).a; } + })).a != 7; + }) ? function (it, key, D) { + var protoDesc = gOPD(ObjectProto, key); + if (protoDesc) delete ObjectProto[key]; + dP(it, key, D); + if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); + } : dP; + + var wrap = function (tag) { + var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); + sym._k = tag; + return sym; + }; + + var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { + return typeof it == 'symbol'; + } : function (it) { + return it instanceof $Symbol; + }; + + var $defineProperty = function defineProperty(it, key, D) { + if (it === ObjectProto) $defineProperty(OPSymbols, key, D); + anObject(it); + key = toPrimitive(key, true); + anObject(D); + if (has(AllSymbols, key)) { + if (!D.enumerable) { + if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); + it[HIDDEN][key] = true; + } else { + if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; + D = _create(D, { enumerable: createDesc(0, false) }); + } return setSymbolDesc(it, key, D); + } return dP(it, key, D); + }; + var $defineProperties = function defineProperties(it, P) { + anObject(it); + var keys = enumKeys(P = toIObject(P)); + var i = 0; + var l = keys.length; + var key; + while (l > i) $defineProperty(it, key = keys[i++], P[key]); + return it; + }; + var $create = function create(it, P) { + return P === undefined ? _create(it) : $defineProperties(_create(it), P); + }; + var $propertyIsEnumerable = function propertyIsEnumerable(key) { + var E = isEnum.call(this, key = toPrimitive(key, true)); + if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; + return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; + }; + var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { + it = toIObject(it); + key = toPrimitive(key, true); + if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; + var D = gOPD(it, key); + if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; + return D; + }; + var $getOwnPropertyNames = function getOwnPropertyNames(it) { + var names = gOPN(toIObject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); + } return result; + }; + var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { + var IS_OP = it === ObjectProto; + var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); + } return result; + }; + + // 19.4.1.1 Symbol([description]) + if (!USE_NATIVE) { + $Symbol = function Symbol() { + if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); + var tag = uid(arguments.length > 0 ? arguments[0] : undefined); + var $set = function (value) { + if (this === ObjectProto) $set.call(OPSymbols, value); + if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; + setSymbolDesc(this, tag, createDesc(1, value)); + }; + if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); + return wrap(tag); + }; + redefine($Symbol[PROTOTYPE], 'toString', function toString() { + return this._k; + }); + + $GOPD.f = $getOwnPropertyDescriptor; + $DP.f = $defineProperty; + __webpack_require__(49).f = gOPNExt.f = $getOwnPropertyNames; + __webpack_require__(43).f = $propertyIsEnumerable; + __webpack_require__(42).f = $getOwnPropertySymbols; + + if (DESCRIPTORS && !__webpack_require__(24)) { + redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); + } + + wksExt.f = function (name) { + return wrap(wks(name)); + }; + } + + $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); + + for (var es6Symbols = ( + // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' + ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); + + for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); + + $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { + // 19.4.2.1 Symbol.for(key) + 'for': function (key) { + return has(SymbolRegistry, key += '') + ? SymbolRegistry[key] + : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(sym) { + if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); + for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; + }, + useSetter: function () { setter = true; }, + useSimple: function () { setter = false; } + }); + + $export($export.S + $export.F * !USE_NATIVE, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols + }); + + // 24.3.2 JSON.stringify(value [, replacer [, space]]) + $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; + })), 'JSON', { + stringify: function stringify(it) { + var args = [it]; + var i = 1; + var replacer, $replacer; + while (arguments.length > i) args.push(arguments[i++]); + $replacer = replacer = args[1]; + if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined + if (!isArray(replacer)) replacer = function (key, value) { + if (typeof $replacer == 'function') value = $replacer.call(this, key, value); + if (!isSymbol(value)) return value; + }; + args[1] = replacer; + return _stringify.apply($JSON, args); + } + }); + + // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) + $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(10)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); + // 19.4.3.5 Symbol.prototype[@@toStringTag] + setToStringTag($Symbol, 'Symbol'); + // 20.2.1.9 Math[@@toStringTag] + setToStringTag(Math, 'Math', true); + // 24.3.3 JSON[@@toStringTag] + setToStringTag(global.JSON, 'JSON', true); + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 + var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); + if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef + + +/***/ }), +/* 5 */ +/***/ (function(module, exports) { + + var hasOwnProperty = {}.hasOwnProperty; + module.exports = function (it, key) { + return hasOwnProperty.call(it, key); + }; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + // Thank's IE8 for his funny defineProperty + module.exports = !__webpack_require__(7)(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; + }); + + +/***/ }), +/* 7 */ +/***/ (function(module, exports) { + + module.exports = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; + } + }; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var core = __webpack_require__(9); + var hide = __webpack_require__(10); + var redefine = __webpack_require__(18); + var ctx = __webpack_require__(20); + var PROTOTYPE = 'prototype'; + + var $export = function (type, name, source) { + var IS_FORCED = type & $export.F; + var IS_GLOBAL = type & $export.G; + var IS_STATIC = type & $export.S; + var IS_PROTO = type & $export.P; + var IS_BIND = type & $export.B; + var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]; + var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); + var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); + var key, own, out, exp; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + // export native or passed + out = (own ? target : source)[key]; + // bind timers to global for call from export context + exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; + // extend global + if (target) redefine(target, key, out, type & $export.U); + // export + if (exports[key] != out) hide(exports, key, exp); + if (IS_PROTO && expProto[key] != out) expProto[key] = out; + } + }; + global.core = core; + // type bitmap + $export.F = 1; // forced + $export.G = 2; // global + $export.S = 4; // static + $export.P = 8; // proto + $export.B = 16; // bind + $export.W = 32; // wrap + $export.U = 64; // safe + $export.R = 128; // real proto method for `library` + module.exports = $export; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + var core = module.exports = { version: '2.5.7' }; + if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11); + var createDesc = __webpack_require__(17); + module.exports = __webpack_require__(6) ? function (object, key, value) { + return dP.f(object, key, createDesc(1, value)); + } : function (object, key, value) { + object[key] = value; + return object; + }; + + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + + var anObject = __webpack_require__(12); + var IE8_DOM_DEFINE = __webpack_require__(14); + var toPrimitive = __webpack_require__(16); + var dP = Object.defineProperty; + + exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes) { + anObject(O); + P = toPrimitive(P, true); + anObject(Attributes); + if (IE8_DOM_DEFINE) try { + return dP(O, P, Attributes); + } catch (e) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; + }; + + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + module.exports = function (it) { + if (!isObject(it)) throw TypeError(it + ' is not an object!'); + return it; + }; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports) { + + module.exports = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; + }; + + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + + module.exports = !__webpack_require__(6) && !__webpack_require__(7)(function () { + return Object.defineProperty(__webpack_require__(15)('div'), 'a', { get: function () { return 7; } }).a != 7; + }); + + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + var document = __webpack_require__(4).document; + // typeof document.createElement is 'object' in old IE + var is = isObject(document) && isObject(document.createElement); + module.exports = function (it) { + return is ? document.createElement(it) : {}; + }; + + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.1.1 ToPrimitive(input [, PreferredType]) + var isObject = __webpack_require__(13); + // instead of the ES6 spec version, we didn't implement @@toPrimitive case + // and the second argument - flag - preferred type is a string + module.exports = function (it, S) { + if (!isObject(it)) return it; + var fn, val; + if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; + if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; + if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; + throw TypeError("Can't convert object to primitive value"); + }; + + +/***/ }), +/* 17 */ +/***/ (function(module, exports) { + + module.exports = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; + }; + + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var hide = __webpack_require__(10); + var has = __webpack_require__(5); + var SRC = __webpack_require__(19)('src'); + var TO_STRING = 'toString'; + var $toString = Function[TO_STRING]; + var TPL = ('' + $toString).split(TO_STRING); + + __webpack_require__(9).inspectSource = function (it) { + return $toString.call(it); + }; + + (module.exports = function (O, key, val, safe) { + var isFunction = typeof val == 'function'; + if (isFunction) has(val, 'name') || hide(val, 'name', key); + if (O[key] === val) return; + if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); + if (O === global) { + O[key] = val; + } else if (!safe) { + delete O[key]; + hide(O, key, val); + } else if (O[key]) { + O[key] = val; + } else { + hide(O, key, val); + } + // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative + })(Function.prototype, TO_STRING, function toString() { + return typeof this == 'function' && this[SRC] || $toString.call(this); + }); + + +/***/ }), +/* 19 */ +/***/ (function(module, exports) { + + var id = 0; + var px = Math.random(); + module.exports = function (key) { + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); + }; + + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + + // optional / simple context binding + var aFunction = __webpack_require__(21); + module.exports = function (fn, that, length) { + aFunction(fn); + if (that === undefined) return fn; + switch (length) { + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; + }; + + +/***/ }), +/* 21 */ +/***/ (function(module, exports) { + + module.exports = function (it) { + if (typeof it != 'function') throw TypeError(it + ' is not a function!'); + return it; + }; + + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + + var META = __webpack_require__(19)('meta'); + var isObject = __webpack_require__(13); + var has = __webpack_require__(5); + var setDesc = __webpack_require__(11).f; + var id = 0; + var isExtensible = Object.isExtensible || function () { + return true; + }; + var FREEZE = !__webpack_require__(7)(function () { + return isExtensible(Object.preventExtensions({})); + }); + var setMeta = function (it) { + setDesc(it, META, { value: { + i: 'O' + ++id, // object ID + w: {} // weak collections IDs + } }); + }; + var fastKey = function (it, create) { + // return primitive with prefix + if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMeta(it); + // return object ID + } return it[META].i; + }; + var getWeak = function (it, create) { + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMeta(it); + // return hash weak collections IDs + } return it[META].w; + }; + // add metadata on freeze-family methods calling + var onFreeze = function (it) { + if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); + return it; + }; + var meta = module.exports = { + KEY: META, + NEED: false, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze + }; + + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + + var core = __webpack_require__(9); + var global = __webpack_require__(4); + var SHARED = '__core-js_shared__'; + var store = global[SHARED] || (global[SHARED] = {}); + + (module.exports = function (key, value) { + return store[key] || (store[key] = value !== undefined ? value : {}); + })('versions', []).push({ + version: core.version, + mode: __webpack_require__(24) ? 'pure' : 'global', + copyright: '© 2018 Denis Pushkarev (zloirock.ru)' + }); + + +/***/ }), +/* 24 */ +/***/ (function(module, exports) { + + module.exports = false; + + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + + var def = __webpack_require__(11).f; + var has = __webpack_require__(5); + var TAG = __webpack_require__(26)('toStringTag'); + + module.exports = function (it, tag, stat) { + if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); + }; + + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + + var store = __webpack_require__(23)('wks'); + var uid = __webpack_require__(19); + var Symbol = __webpack_require__(4).Symbol; + var USE_SYMBOL = typeof Symbol == 'function'; + + var $exports = module.exports = function (name) { + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); + }; + + $exports.store = store; + + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + + exports.f = __webpack_require__(26); + + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var core = __webpack_require__(9); + var LIBRARY = __webpack_require__(24); + var wksExt = __webpack_require__(27); + var defineProperty = __webpack_require__(11).f; + module.exports = function (name) { + var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); + if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); + }; + + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + + // all enumerable object keys, includes symbols + var getKeys = __webpack_require__(30); + var gOPS = __webpack_require__(42); + var pIE = __webpack_require__(43); + module.exports = function (it) { + var result = getKeys(it); + var getSymbols = gOPS.f; + if (getSymbols) { + var symbols = getSymbols(it); + var isEnum = pIE.f; + var i = 0; + var key; + while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); + } return result; + }; + + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.14 / 15.2.3.14 Object.keys(O) + var $keys = __webpack_require__(31); + var enumBugKeys = __webpack_require__(41); + + module.exports = Object.keys || function keys(O) { + return $keys(O, enumBugKeys); + }; + + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + + var has = __webpack_require__(5); + var toIObject = __webpack_require__(32); + var arrayIndexOf = __webpack_require__(36)(false); + var IE_PROTO = __webpack_require__(40)('IE_PROTO'); + + module.exports = function (object, names) { + var O = toIObject(object); + var i = 0; + var result = []; + var key; + for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); + // Don't enum bug & hidden keys + while (names.length > i) if (has(O, key = names[i++])) { + ~arrayIndexOf(result, key) || result.push(key); + } + return result; + }; + + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + + // to indexed object, toObject with fallback for non-array-like ES3 strings + var IObject = __webpack_require__(33); + var defined = __webpack_require__(35); + module.exports = function (it) { + return IObject(defined(it)); + }; + + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + + // fallback for non-array-like ES3 and non-enumerable old V8 strings + var cof = __webpack_require__(34); + // eslint-disable-next-line no-prototype-builtins + module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { + return cof(it) == 'String' ? it.split('') : Object(it); + }; + + +/***/ }), +/* 34 */ +/***/ (function(module, exports) { + + var toString = {}.toString; + + module.exports = function (it) { + return toString.call(it).slice(8, -1); + }; + + +/***/ }), +/* 35 */ +/***/ (function(module, exports) { + + // 7.2.1 RequireObjectCoercible(argument) + module.exports = function (it) { + if (it == undefined) throw TypeError("Can't call method on " + it); + return it; + }; + + +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + + // false -> Array#indexOf + // true -> Array#includes + var toIObject = __webpack_require__(32); + var toLength = __webpack_require__(37); + var toAbsoluteIndex = __webpack_require__(39); + module.exports = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = toIObject($this); + var length = toLength(O.length); + var index = toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) if (IS_INCLUDES || index in O) { + if (O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; + }; + + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.1.15 ToLength + var toInteger = __webpack_require__(38); + var min = Math.min; + module.exports = function (it) { + return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 + }; + + +/***/ }), +/* 38 */ +/***/ (function(module, exports) { + + // 7.1.4 ToInteger + var ceil = Math.ceil; + var floor = Math.floor; + module.exports = function (it) { + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); + }; + + +/***/ }), +/* 39 */ +/***/ (function(module, exports, __webpack_require__) { + + var toInteger = __webpack_require__(38); + var max = Math.max; + var min = Math.min; + module.exports = function (index, length) { + index = toInteger(index); + return index < 0 ? max(index + length, 0) : min(index, length); + }; + + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + + var shared = __webpack_require__(23)('keys'); + var uid = __webpack_require__(19); + module.exports = function (key) { + return shared[key] || (shared[key] = uid(key)); + }; + + +/***/ }), +/* 41 */ +/***/ (function(module, exports) { + + // IE 8- don't enum bug keys + module.exports = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' + ).split(','); + + +/***/ }), +/* 42 */ +/***/ (function(module, exports) { + + exports.f = Object.getOwnPropertySymbols; + + +/***/ }), +/* 43 */ +/***/ (function(module, exports) { + + exports.f = {}.propertyIsEnumerable; + + +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.2.2 IsArray(argument) + var cof = __webpack_require__(34); + module.exports = Array.isArray || function isArray(arg) { + return cof(arg) == 'Array'; + }; + + +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + var anObject = __webpack_require__(12); + var dPs = __webpack_require__(46); + var enumBugKeys = __webpack_require__(41); + var IE_PROTO = __webpack_require__(40)('IE_PROTO'); + var Empty = function () { /* empty */ }; + var PROTOTYPE = 'prototype'; + + // Create object with fake `null` prototype: use iframe Object with cleared prototype + var createDict = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = __webpack_require__(15)('iframe'); + var i = enumBugKeys.length; + var lt = '<'; + var gt = '>'; + var iframeDocument; + iframe.style.display = 'none'; + __webpack_require__(47).appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; + return createDict(); + }; + + module.exports = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + Empty[PROTOTYPE] = anObject(O); + result = new Empty(); + Empty[PROTOTYPE] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = createDict(); + return Properties === undefined ? result : dPs(result, Properties); + }; + + +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11); + var anObject = __webpack_require__(12); + var getKeys = __webpack_require__(30); + + module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties) { + anObject(O); + var keys = getKeys(Properties); + var length = keys.length; + var i = 0; + var P; + while (length > i) dP.f(O, P = keys[i++], Properties[P]); + return O; + }; + + +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { + + var document = __webpack_require__(4).document; + module.exports = document && document.documentElement; + + +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { + + // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window + var toIObject = __webpack_require__(32); + var gOPN = __webpack_require__(49).f; + var toString = {}.toString; + + var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + + var getWindowNames = function (it) { + try { + return gOPN(it); + } catch (e) { + return windowNames.slice(); + } + }; + + module.exports.f = function getOwnPropertyNames(it) { + return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); + }; + + +/***/ }), +/* 49 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) + var $keys = __webpack_require__(31); + var hiddenKeys = __webpack_require__(41).concat('length', 'prototype'); + + exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return $keys(O, hiddenKeys); + }; + + +/***/ }), +/* 50 */ +/***/ (function(module, exports, __webpack_require__) { + + var pIE = __webpack_require__(43); + var createDesc = __webpack_require__(17); + var toIObject = __webpack_require__(32); + var toPrimitive = __webpack_require__(16); + var has = __webpack_require__(5); + var IE8_DOM_DEFINE = __webpack_require__(14); + var gOPD = Object.getOwnPropertyDescriptor; + + exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P) { + O = toIObject(O); + P = toPrimitive(P, true); + if (IE8_DOM_DEFINE) try { + return gOPD(O, P); + } catch (e) { /* empty */ } + if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); + }; + + +/***/ }), +/* 51 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + $export($export.S, 'Object', { create: __webpack_require__(45) }); + + +/***/ }), +/* 52 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) + $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperty: __webpack_require__(11).f }); + + +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) + $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperties: __webpack_require__(46) }); + + +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + var toIObject = __webpack_require__(32); + var $getOwnPropertyDescriptor = __webpack_require__(50).f; + + __webpack_require__(55)('getOwnPropertyDescriptor', function () { + return function getOwnPropertyDescriptor(it, key) { + return $getOwnPropertyDescriptor(toIObject(it), key); + }; + }); + + +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { + + // most Object methods by ES6 should accept primitives + var $export = __webpack_require__(8); + var core = __webpack_require__(9); + var fails = __webpack_require__(7); + module.exports = function (KEY, exec) { + var fn = (core.Object || {})[KEY] || Object[KEY]; + var exp = {}; + exp[KEY] = exec(fn); + $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); + }; + + +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.9 Object.getPrototypeOf(O) + var toObject = __webpack_require__(57); + var $getPrototypeOf = __webpack_require__(58); + + __webpack_require__(55)('getPrototypeOf', function () { + return function getPrototypeOf(it) { + return $getPrototypeOf(toObject(it)); + }; + }); + + +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.1.13 ToObject(argument) + var defined = __webpack_require__(35); + module.exports = function (it) { + return Object(defined(it)); + }; + + +/***/ }), +/* 58 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) + var has = __webpack_require__(5); + var toObject = __webpack_require__(57); + var IE_PROTO = __webpack_require__(40)('IE_PROTO'); + var ObjectProto = Object.prototype; + + module.exports = Object.getPrototypeOf || function (O) { + O = toObject(O); + if (has(O, IE_PROTO)) return O[IE_PROTO]; + if (typeof O.constructor == 'function' && O instanceof O.constructor) { + return O.constructor.prototype; + } return O instanceof Object ? ObjectProto : null; + }; + + +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.14 Object.keys(O) + var toObject = __webpack_require__(57); + var $keys = __webpack_require__(30); + + __webpack_require__(55)('keys', function () { + return function keys(it) { + return $keys(toObject(it)); + }; + }); + + +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.7 Object.getOwnPropertyNames(O) + __webpack_require__(55)('getOwnPropertyNames', function () { + return __webpack_require__(48).f; + }); + + +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.5 Object.freeze(O) + var isObject = __webpack_require__(13); + var meta = __webpack_require__(22).onFreeze; + + __webpack_require__(55)('freeze', function ($freeze) { + return function freeze(it) { + return $freeze && isObject(it) ? $freeze(meta(it)) : it; + }; + }); + + +/***/ }), +/* 62 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.17 Object.seal(O) + var isObject = __webpack_require__(13); + var meta = __webpack_require__(22).onFreeze; + + __webpack_require__(55)('seal', function ($seal) { + return function seal(it) { + return $seal && isObject(it) ? $seal(meta(it)) : it; + }; + }); + + +/***/ }), +/* 63 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.15 Object.preventExtensions(O) + var isObject = __webpack_require__(13); + var meta = __webpack_require__(22).onFreeze; + + __webpack_require__(55)('preventExtensions', function ($preventExtensions) { + return function preventExtensions(it) { + return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; + }; + }); + + +/***/ }), +/* 64 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.12 Object.isFrozen(O) + var isObject = __webpack_require__(13); + + __webpack_require__(55)('isFrozen', function ($isFrozen) { + return function isFrozen(it) { + return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; + }; + }); + + +/***/ }), +/* 65 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.13 Object.isSealed(O) + var isObject = __webpack_require__(13); + + __webpack_require__(55)('isSealed', function ($isSealed) { + return function isSealed(it) { + return isObject(it) ? $isSealed ? $isSealed(it) : false : true; + }; + }); + + +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.11 Object.isExtensible(O) + var isObject = __webpack_require__(13); + + __webpack_require__(55)('isExtensible', function ($isExtensible) { + return function isExtensible(it) { + return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; + }; + }); + + +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.3.1 Object.assign(target, source) + var $export = __webpack_require__(8); + + $export($export.S + $export.F, 'Object', { assign: __webpack_require__(68) }); + + +/***/ }), +/* 68 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 19.1.2.1 Object.assign(target, source, ...) + var getKeys = __webpack_require__(30); + var gOPS = __webpack_require__(42); + var pIE = __webpack_require__(43); + var toObject = __webpack_require__(57); + var IObject = __webpack_require__(33); + var $assign = Object.assign; + + // should work with symbols and should have deterministic property order (V8 bug) + module.exports = !$assign || __webpack_require__(7)(function () { + var A = {}; + var B = {}; + // eslint-disable-next-line no-undef + var S = Symbol(); + var K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function (k) { B[k] = k; }); + return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; + }) ? function assign(target, source) { // eslint-disable-line no-unused-vars + var T = toObject(target); + var aLen = arguments.length; + var index = 1; + var getSymbols = gOPS.f; + var isEnum = pIE.f; + while (aLen > index) { + var S = IObject(arguments[index++]); + var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); + var length = keys.length; + var j = 0; + var key; + while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; + } return T; + } : $assign; + + +/***/ }), +/* 69 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.3.10 Object.is(value1, value2) + var $export = __webpack_require__(8); + $export($export.S, 'Object', { is: __webpack_require__(70) }); + + +/***/ }), +/* 70 */ +/***/ (function(module, exports) { + + // 7.2.9 SameValue(x, y) + module.exports = Object.is || function is(x, y) { + // eslint-disable-next-line no-self-compare + return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; + }; + + +/***/ }), +/* 71 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.3.19 Object.setPrototypeOf(O, proto) + var $export = __webpack_require__(8); + $export($export.S, 'Object', { setPrototypeOf: __webpack_require__(72).set }); + + +/***/ }), +/* 72 */ +/***/ (function(module, exports, __webpack_require__) { + + // Works with __proto__ only. Old v8 can't work with null proto objects. + /* eslint-disable no-proto */ + var isObject = __webpack_require__(13); + var anObject = __webpack_require__(12); + var check = function (O, proto) { + anObject(O); + if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); + }; + module.exports = { + set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line + function (test, buggy, set) { + try { + set = __webpack_require__(20)(Function.call, __webpack_require__(50).f(Object.prototype, '__proto__').set, 2); + set(test, []); + buggy = !(test instanceof Array); + } catch (e) { buggy = true; } + return function setPrototypeOf(O, proto) { + check(O, proto); + if (buggy) O.__proto__ = proto; + else set(O, proto); + return O; + }; + }({}, false) : undefined), + check: check + }; + + +/***/ }), +/* 73 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 19.1.3.6 Object.prototype.toString() + var classof = __webpack_require__(74); + var test = {}; + test[__webpack_require__(26)('toStringTag')] = 'z'; + if (test + '' != '[object z]') { + __webpack_require__(18)(Object.prototype, 'toString', function toString() { + return '[object ' + classof(this) + ']'; + }, true); + } + + +/***/ }), +/* 74 */ +/***/ (function(module, exports, __webpack_require__) { + + // getting tag from 19.1.3.6 Object.prototype.toString() + var cof = __webpack_require__(34); + var TAG = __webpack_require__(26)('toStringTag'); + // ES3 wrong here + var ARG = cof(function () { return arguments; }()) == 'Arguments'; + + // fallback for IE11 Script Access Denied error + var tryGet = function (it, key) { + try { + return it[key]; + } catch (e) { /* empty */ } + }; + + module.exports = function (it) { + var O, T, B; + return it === undefined ? 'Undefined' : it === null ? 'Null' + // @@toStringTag case + : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T + // builtinTag case + : ARG ? cof(O) + // ES3 arguments fallback + : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; + }; + + +/***/ }), +/* 75 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) + var $export = __webpack_require__(8); + + $export($export.P, 'Function', { bind: __webpack_require__(76) }); + + +/***/ }), +/* 76 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var aFunction = __webpack_require__(21); + var isObject = __webpack_require__(13); + var invoke = __webpack_require__(77); + var arraySlice = [].slice; + var factories = {}; + + var construct = function (F, len, args) { + if (!(len in factories)) { + for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']'; + // eslint-disable-next-line no-new-func + factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); + } return factories[len](F, args); + }; + + module.exports = Function.bind || function bind(that /* , ...args */) { + var fn = aFunction(this); + var partArgs = arraySlice.call(arguments, 1); + var bound = function (/* args... */) { + var args = partArgs.concat(arraySlice.call(arguments)); + return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); + }; + if (isObject(fn.prototype)) bound.prototype = fn.prototype; + return bound; + }; + + +/***/ }), +/* 77 */ +/***/ (function(module, exports) { + + // fast apply, http://jsperf.lnkit.com/fast-apply/5 + module.exports = function (fn, args, that) { + var un = that === undefined; + switch (args.length) { + case 0: return un ? fn() + : fn.call(that); + case 1: return un ? fn(args[0]) + : fn.call(that, args[0]); + case 2: return un ? fn(args[0], args[1]) + : fn.call(that, args[0], args[1]); + case 3: return un ? fn(args[0], args[1], args[2]) + : fn.call(that, args[0], args[1], args[2]); + case 4: return un ? fn(args[0], args[1], args[2], args[3]) + : fn.call(that, args[0], args[1], args[2], args[3]); + } return fn.apply(that, args); + }; + + +/***/ }), +/* 78 */ +/***/ (function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11).f; + var FProto = Function.prototype; + var nameRE = /^\s*function ([^ (]*)/; + var NAME = 'name'; + + // 19.2.4.2 name + NAME in FProto || __webpack_require__(6) && dP(FProto, NAME, { + configurable: true, + get: function () { + try { + return ('' + this).match(nameRE)[1]; + } catch (e) { + return ''; + } + } + }); + + +/***/ }), +/* 79 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var isObject = __webpack_require__(13); + var getPrototypeOf = __webpack_require__(58); + var HAS_INSTANCE = __webpack_require__(26)('hasInstance'); + var FunctionProto = Function.prototype; + // 19.2.3.6 Function.prototype[@@hasInstance](V) + if (!(HAS_INSTANCE in FunctionProto)) __webpack_require__(11).f(FunctionProto, HAS_INSTANCE, { value: function (O) { + if (typeof this != 'function' || !isObject(O)) return false; + if (!isObject(this.prototype)) return O instanceof this; + // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: + while (O = getPrototypeOf(O)) if (this.prototype === O) return true; + return false; + } }); + + +/***/ }), +/* 80 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseInt = __webpack_require__(81); + // 18.2.5 parseInt(string, radix) + $export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt }); + + +/***/ }), +/* 81 */ +/***/ (function(module, exports, __webpack_require__) { + + var $parseInt = __webpack_require__(4).parseInt; + var $trim = __webpack_require__(82).trim; + var ws = __webpack_require__(83); + var hex = /^[-+]?0[xX]/; + + module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix) { + var string = $trim(String(str), 3); + return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); + } : $parseInt; + + +/***/ }), +/* 82 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var defined = __webpack_require__(35); + var fails = __webpack_require__(7); + var spaces = __webpack_require__(83); + var space = '[' + spaces + ']'; + var non = '\u200b\u0085'; + var ltrim = RegExp('^' + space + space + '*'); + var rtrim = RegExp(space + space + '*$'); + + var exporter = function (KEY, exec, ALIAS) { + var exp = {}; + var FORCE = fails(function () { + return !!spaces[KEY]() || non[KEY]() != non; + }); + var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; + if (ALIAS) exp[ALIAS] = fn; + $export($export.P + $export.F * FORCE, 'String', exp); + }; + + // 1 -> String#trimLeft + // 2 -> String#trimRight + // 3 -> String#trim + var trim = exporter.trim = function (string, TYPE) { + string = String(defined(string)); + if (TYPE & 1) string = string.replace(ltrim, ''); + if (TYPE & 2) string = string.replace(rtrim, ''); + return string; + }; + + module.exports = exporter; + + +/***/ }), +/* 83 */ +/***/ (function(module, exports) { + + module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + + +/***/ }), +/* 84 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseFloat = __webpack_require__(85); + // 18.2.4 parseFloat(string) + $export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat }); + + +/***/ }), +/* 85 */ +/***/ (function(module, exports, __webpack_require__) { + + var $parseFloat = __webpack_require__(4).parseFloat; + var $trim = __webpack_require__(82).trim; + + module.exports = 1 / $parseFloat(__webpack_require__(83) + '-0') !== -Infinity ? function parseFloat(str) { + var string = $trim(String(str), 3); + var result = $parseFloat(string); + return result === 0 && string.charAt(0) == '-' ? -0 : result; + } : $parseFloat; + + +/***/ }), +/* 86 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var has = __webpack_require__(5); + var cof = __webpack_require__(34); + var inheritIfRequired = __webpack_require__(87); + var toPrimitive = __webpack_require__(16); + var fails = __webpack_require__(7); + var gOPN = __webpack_require__(49).f; + var gOPD = __webpack_require__(50).f; + var dP = __webpack_require__(11).f; + var $trim = __webpack_require__(82).trim; + var NUMBER = 'Number'; + var $Number = global[NUMBER]; + var Base = $Number; + var proto = $Number.prototype; + // Opera ~12 has broken Object#toString + var BROKEN_COF = cof(__webpack_require__(45)(proto)) == NUMBER; + var TRIM = 'trim' in String.prototype; + + // 7.1.3 ToNumber(argument) + var toNumber = function (argument) { + var it = toPrimitive(argument, false); + if (typeof it == 'string' && it.length > 2) { + it = TRIM ? it.trim() : $trim(it, 3); + var first = it.charCodeAt(0); + var third, radix, maxCode; + if (first === 43 || first === 45) { + third = it.charCodeAt(2); + if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix + } else if (first === 48) { + switch (it.charCodeAt(1)) { + case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i + case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i + default: return +it; + } + for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) { + code = digits.charCodeAt(i); + // parseInt parses a string to a first unavailable symbol + // but ToNumber should return NaN if a string contains unavailable symbols + if (code < 48 || code > maxCode) return NaN; + } return parseInt(digits, radix); + } + } return +it; + }; + + if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) { + $Number = function Number(value) { + var it = arguments.length < 1 ? 0 : value; + var that = this; + return that instanceof $Number + // check on 1..constructor(foo) case + && (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER) + ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); + }; + for (var keys = __webpack_require__(6) ? gOPN(Base) : ( + // ES3: + 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + + // ES6 (in case, if modules with ES6 Number statics required before): + 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' + ).split(','), j = 0, key; keys.length > j; j++) { + if (has(Base, key = keys[j]) && !has($Number, key)) { + dP($Number, key, gOPD(Base, key)); + } + } + $Number.prototype = proto; + proto.constructor = $Number; + __webpack_require__(18)(global, NUMBER, $Number); + } + + +/***/ }), +/* 87 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + var setPrototypeOf = __webpack_require__(72).set; + module.exports = function (that, target, C) { + var S = target.constructor; + var P; + if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) { + setPrototypeOf(that, P); + } return that; + }; + + +/***/ }), +/* 88 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toInteger = __webpack_require__(38); + var aNumberValue = __webpack_require__(89); + var repeat = __webpack_require__(90); + var $toFixed = 1.0.toFixed; + var floor = Math.floor; + var data = [0, 0, 0, 0, 0, 0]; + var ERROR = 'Number.toFixed: incorrect invocation!'; + var ZERO = '0'; + + var multiply = function (n, c) { + var i = -1; + var c2 = c; + while (++i < 6) { + c2 += n * data[i]; + data[i] = c2 % 1e7; + c2 = floor(c2 / 1e7); + } + }; + var divide = function (n) { + var i = 6; + var c = 0; + while (--i >= 0) { + c += data[i]; + data[i] = floor(c / n); + c = (c % n) * 1e7; + } + }; + var numToString = function () { + var i = 6; + var s = ''; + while (--i >= 0) { + if (s !== '' || i === 0 || data[i] !== 0) { + var t = String(data[i]); + s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; + } + } return s; + }; + var pow = function (x, n, acc) { + return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); + }; + var log = function (x) { + var n = 0; + var x2 = x; + while (x2 >= 4096) { + n += 12; + x2 /= 4096; + } + while (x2 >= 2) { + n += 1; + x2 /= 2; + } return n; + }; + + $export($export.P + $export.F * (!!$toFixed && ( + 0.00008.toFixed(3) !== '0.000' || + 0.9.toFixed(0) !== '1' || + 1.255.toFixed(2) !== '1.25' || + 1000000000000000128.0.toFixed(0) !== '1000000000000000128' + ) || !__webpack_require__(7)(function () { + // V8 ~ Android 4.3- + $toFixed.call({}); + })), 'Number', { + toFixed: function toFixed(fractionDigits) { + var x = aNumberValue(this, ERROR); + var f = toInteger(fractionDigits); + var s = ''; + var m = ZERO; + var e, z, j, k; + if (f < 0 || f > 20) throw RangeError(ERROR); + // eslint-disable-next-line no-self-compare + if (x != x) return 'NaN'; + if (x <= -1e21 || x >= 1e21) return String(x); + if (x < 0) { + s = '-'; + x = -x; + } + if (x > 1e-21) { + e = log(x * pow(2, 69, 1)) - 69; + z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); + z *= 0x10000000000000; + e = 52 - e; + if (e > 0) { + multiply(0, z); + j = f; + while (j >= 7) { + multiply(1e7, 0); + j -= 7; + } + multiply(pow(10, j, 1), 0); + j = e - 1; + while (j >= 23) { + divide(1 << 23); + j -= 23; + } + divide(1 << j); + multiply(1, 1); + divide(2); + m = numToString(); + } else { + multiply(0, z); + multiply(1 << -e, 0); + m = numToString() + repeat.call(ZERO, f); + } + } + if (f > 0) { + k = m.length; + m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); + } else { + m = s + m; + } return m; + } + }); + + +/***/ }), +/* 89 */ +/***/ (function(module, exports, __webpack_require__) { + + var cof = __webpack_require__(34); + module.exports = function (it, msg) { + if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg); + return +it; + }; + + +/***/ }), +/* 90 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var toInteger = __webpack_require__(38); + var defined = __webpack_require__(35); + + module.exports = function repeat(count) { + var str = String(defined(this)); + var res = ''; + var n = toInteger(count); + if (n < 0 || n == Infinity) throw RangeError("Count can't be negative"); + for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str; + return res; + }; + + +/***/ }), +/* 91 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $fails = __webpack_require__(7); + var aNumberValue = __webpack_require__(89); + var $toPrecision = 1.0.toPrecision; + + $export($export.P + $export.F * ($fails(function () { + // IE7- + return $toPrecision.call(1, undefined) !== '1'; + }) || !$fails(function () { + // V8 ~ Android 4.3- + $toPrecision.call({}); + })), 'Number', { + toPrecision: function toPrecision(precision) { + var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); + return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); + } + }); + + +/***/ }), +/* 92 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.1 Number.EPSILON + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { EPSILON: Math.pow(2, -52) }); + + +/***/ }), +/* 93 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.2 Number.isFinite(number) + var $export = __webpack_require__(8); + var _isFinite = __webpack_require__(4).isFinite; + + $export($export.S, 'Number', { + isFinite: function isFinite(it) { + return typeof it == 'number' && _isFinite(it); + } + }); + + +/***/ }), +/* 94 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.3 Number.isInteger(number) + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { isInteger: __webpack_require__(95) }); + + +/***/ }), +/* 95 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.3 Number.isInteger(number) + var isObject = __webpack_require__(13); + var floor = Math.floor; + module.exports = function isInteger(it) { + return !isObject(it) && isFinite(it) && floor(it) === it; + }; + + +/***/ }), +/* 96 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.4 Number.isNaN(number) + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { + isNaN: function isNaN(number) { + // eslint-disable-next-line no-self-compare + return number != number; + } + }); + + +/***/ }), +/* 97 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.5 Number.isSafeInteger(number) + var $export = __webpack_require__(8); + var isInteger = __webpack_require__(95); + var abs = Math.abs; + + $export($export.S, 'Number', { + isSafeInteger: function isSafeInteger(number) { + return isInteger(number) && abs(number) <= 0x1fffffffffffff; + } + }); + + +/***/ }), +/* 98 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.6 Number.MAX_SAFE_INTEGER + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff }); + + +/***/ }), +/* 99 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.10 Number.MIN_SAFE_INTEGER + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff }); + + +/***/ }), +/* 100 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseFloat = __webpack_require__(85); + // 20.1.2.12 Number.parseFloat(string) + $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat }); + + +/***/ }), +/* 101 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseInt = __webpack_require__(81); + // 20.1.2.13 Number.parseInt(string, radix) + $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt }); + + +/***/ }), +/* 102 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.3 Math.acosh(x) + var $export = __webpack_require__(8); + var log1p = __webpack_require__(103); + var sqrt = Math.sqrt; + var $acosh = Math.acosh; + + $export($export.S + $export.F * !($acosh + // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 + && Math.floor($acosh(Number.MAX_VALUE)) == 710 + // Tor Browser bug: Math.acosh(Infinity) -> NaN + && $acosh(Infinity) == Infinity + ), 'Math', { + acosh: function acosh(x) { + return (x = +x) < 1 ? NaN : x > 94906265.62425156 + ? Math.log(x) + Math.LN2 + : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); + } + }); + + +/***/ }), +/* 103 */ +/***/ (function(module, exports) { + + // 20.2.2.20 Math.log1p(x) + module.exports = Math.log1p || function log1p(x) { + return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); + }; + + +/***/ }), +/* 104 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.5 Math.asinh(x) + var $export = __webpack_require__(8); + var $asinh = Math.asinh; + + function asinh(x) { + return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); + } + + // Tor Browser bug: Math.asinh(0) -> -0 + $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh }); + + +/***/ }), +/* 105 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.7 Math.atanh(x) + var $export = __webpack_require__(8); + var $atanh = Math.atanh; + + // Tor Browser bug: Math.atanh(-0) -> 0 + $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { + atanh: function atanh(x) { + return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; + } + }); + + +/***/ }), +/* 106 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.9 Math.cbrt(x) + var $export = __webpack_require__(8); + var sign = __webpack_require__(107); + + $export($export.S, 'Math', { + cbrt: function cbrt(x) { + return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); + } + }); + + +/***/ }), +/* 107 */ +/***/ (function(module, exports) { + + // 20.2.2.28 Math.sign(x) + module.exports = Math.sign || function sign(x) { + // eslint-disable-next-line no-self-compare + return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; + }; + + +/***/ }), +/* 108 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.11 Math.clz32(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + clz32: function clz32(x) { + return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; + } + }); + + +/***/ }), +/* 109 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.12 Math.cosh(x) + var $export = __webpack_require__(8); + var exp = Math.exp; + + $export($export.S, 'Math', { + cosh: function cosh(x) { + return (exp(x = +x) + exp(-x)) / 2; + } + }); + + +/***/ }), +/* 110 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.14 Math.expm1(x) + var $export = __webpack_require__(8); + var $expm1 = __webpack_require__(111); + + $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 }); + + +/***/ }), +/* 111 */ +/***/ (function(module, exports) { + + // 20.2.2.14 Math.expm1(x) + var $expm1 = Math.expm1; + module.exports = (!$expm1 + // Old FF bug + || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 + // Tor Browser bug + || $expm1(-2e-17) != -2e-17 + ) ? function expm1(x) { + return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; + } : $expm1; + + +/***/ }), +/* 112 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.16 Math.fround(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { fround: __webpack_require__(113) }); + + +/***/ }), +/* 113 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.16 Math.fround(x) + var sign = __webpack_require__(107); + var pow = Math.pow; + var EPSILON = pow(2, -52); + var EPSILON32 = pow(2, -23); + var MAX32 = pow(2, 127) * (2 - EPSILON32); + var MIN32 = pow(2, -126); + + var roundTiesToEven = function (n) { + return n + 1 / EPSILON - 1 / EPSILON; + }; + + module.exports = Math.fround || function fround(x) { + var $abs = Math.abs(x); + var $sign = sign(x); + var a, result; + if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; + a = (1 + EPSILON32 / EPSILON) * $abs; + result = a - (a - $abs); + // eslint-disable-next-line no-self-compare + if (result > MAX32 || result != result) return $sign * Infinity; + return $sign * result; + }; + + +/***/ }), +/* 114 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) + var $export = __webpack_require__(8); + var abs = Math.abs; + + $export($export.S, 'Math', { + hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars + var sum = 0; + var i = 0; + var aLen = arguments.length; + var larg = 0; + var arg, div; + while (i < aLen) { + arg = abs(arguments[i++]); + if (larg < arg) { + div = larg / arg; + sum = sum * div * div + 1; + larg = arg; + } else if (arg > 0) { + div = arg / larg; + sum += div * div; + } else sum += arg; + } + return larg === Infinity ? Infinity : larg * Math.sqrt(sum); + } + }); + + +/***/ }), +/* 115 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.18 Math.imul(x, y) + var $export = __webpack_require__(8); + var $imul = Math.imul; + + // some WebKit versions fails with big numbers, some has wrong arity + $export($export.S + $export.F * __webpack_require__(7)(function () { + return $imul(0xffffffff, 5) != -5 || $imul.length != 2; + }), 'Math', { + imul: function imul(x, y) { + var UINT16 = 0xffff; + var xn = +x; + var yn = +y; + var xl = UINT16 & xn; + var yl = UINT16 & yn; + return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); + } + }); + + +/***/ }), +/* 116 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.21 Math.log10(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + log10: function log10(x) { + return Math.log(x) * Math.LOG10E; + } + }); + + +/***/ }), +/* 117 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.20 Math.log1p(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { log1p: __webpack_require__(103) }); + + +/***/ }), +/* 118 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.22 Math.log2(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + log2: function log2(x) { + return Math.log(x) / Math.LN2; + } + }); + + +/***/ }), +/* 119 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.28 Math.sign(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { sign: __webpack_require__(107) }); + + +/***/ }), +/* 120 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.30 Math.sinh(x) + var $export = __webpack_require__(8); + var expm1 = __webpack_require__(111); + var exp = Math.exp; + + // V8 near Chromium 38 has a problem with very small numbers + $export($export.S + $export.F * __webpack_require__(7)(function () { + return !Math.sinh(-2e-17) != -2e-17; + }), 'Math', { + sinh: function sinh(x) { + return Math.abs(x = +x) < 1 + ? (expm1(x) - expm1(-x)) / 2 + : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); + } + }); + + +/***/ }), +/* 121 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.33 Math.tanh(x) + var $export = __webpack_require__(8); + var expm1 = __webpack_require__(111); + var exp = Math.exp; + + $export($export.S, 'Math', { + tanh: function tanh(x) { + var a = expm1(x = +x); + var b = expm1(-x); + return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); + } + }); + + +/***/ }), +/* 122 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.34 Math.trunc(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + trunc: function trunc(it) { + return (it > 0 ? Math.floor : Math.ceil)(it); + } + }); + + +/***/ }), +/* 123 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var toAbsoluteIndex = __webpack_require__(39); + var fromCharCode = String.fromCharCode; + var $fromCodePoint = String.fromCodePoint; + + // length should be 1, old FF problem + $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { + // 21.1.2.2 String.fromCodePoint(...codePoints) + fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars + var res = []; + var aLen = arguments.length; + var i = 0; + var code; + while (aLen > i) { + code = +arguments[i++]; + if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point'); + res.push(code < 0x10000 + ? fromCharCode(code) + : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) + ); + } return res.join(''); + } + }); + + +/***/ }), +/* 124 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var toIObject = __webpack_require__(32); + var toLength = __webpack_require__(37); + + $export($export.S, 'String', { + // 21.1.2.4 String.raw(callSite, ...substitutions) + raw: function raw(callSite) { + var tpl = toIObject(callSite.raw); + var len = toLength(tpl.length); + var aLen = arguments.length; + var res = []; + var i = 0; + while (len > i) { + res.push(String(tpl[i++])); + if (i < aLen) res.push(String(arguments[i])); + } return res.join(''); + } + }); + + +/***/ }), +/* 125 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 21.1.3.25 String.prototype.trim() + __webpack_require__(82)('trim', function ($trim) { + return function trim() { + return $trim(this, 3); + }; + }); + + +/***/ }), +/* 126 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $at = __webpack_require__(127)(true); + + // 21.1.3.27 String.prototype[@@iterator]() + __webpack_require__(128)(String, 'String', function (iterated) { + this._t = String(iterated); // target + this._i = 0; // next index + // 21.1.5.2.1 %StringIteratorPrototype%.next() + }, function () { + var O = this._t; + var index = this._i; + var point; + if (index >= O.length) return { value: undefined, done: true }; + point = $at(O, index); + this._i += point.length; + return { value: point, done: false }; + }); + + +/***/ }), +/* 127 */ +/***/ (function(module, exports, __webpack_require__) { + + var toInteger = __webpack_require__(38); + var defined = __webpack_require__(35); + // true -> String#at + // false -> String#codePointAt + module.exports = function (TO_STRING) { + return function (that, pos) { + var s = String(defined(that)); + var i = toInteger(pos); + var l = s.length; + var a, b; + if (i < 0 || i >= l) return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; + }; + + +/***/ }), +/* 128 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var LIBRARY = __webpack_require__(24); + var $export = __webpack_require__(8); + var redefine = __webpack_require__(18); + var hide = __webpack_require__(10); + var Iterators = __webpack_require__(129); + var $iterCreate = __webpack_require__(130); + var setToStringTag = __webpack_require__(25); + var getPrototypeOf = __webpack_require__(58); + var ITERATOR = __webpack_require__(26)('iterator'); + var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` + var FF_ITERATOR = '@@iterator'; + var KEYS = 'keys'; + var VALUES = 'values'; + + var returnThis = function () { return this; }; + + module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { + $iterCreate(Constructor, NAME, next); + var getMethod = function (kind) { + if (!BUGGY && kind in proto) return proto[kind]; + switch (kind) { + case KEYS: return function keys() { return new Constructor(this, kind); }; + case VALUES: return function values() { return new Constructor(this, kind); }; + } return function entries() { return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator'; + var DEF_VALUES = DEFAULT == VALUES; + var VALUES_BUG = false; + var proto = Base.prototype; + var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; + var $default = $native || getMethod(DEFAULT); + var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; + var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; + var methods, key, IteratorPrototype; + // Fix native + if ($anyNative) { + IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); + if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { + // Set @@toStringTag to native iterators + setToStringTag(IteratorPrototype, TAG, true); + // fix for some old engines + if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); + } + } + // fix Array#{values, @@iterator}.name in V8 / FF + if (DEF_VALUES && $native && $native.name !== VALUES) { + VALUES_BUG = true; + $default = function values() { return $native.call(this); }; + } + // Define iterator + if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { + hide(proto, ITERATOR, $default); + } + // Plug for library + Iterators[NAME] = $default; + Iterators[TAG] = returnThis; + if (DEFAULT) { + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }; + if (FORCED) for (key in methods) { + if (!(key in proto)) redefine(proto, key, methods[key]); + } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); + } + return methods; + }; + + +/***/ }), +/* 129 */ +/***/ (function(module, exports) { + + module.exports = {}; + + +/***/ }), +/* 130 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var create = __webpack_require__(45); + var descriptor = __webpack_require__(17); + var setToStringTag = __webpack_require__(25); + var IteratorPrototype = {}; + + // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() + __webpack_require__(10)(IteratorPrototype, __webpack_require__(26)('iterator'), function () { return this; }); + + module.exports = function (Constructor, NAME, next) { + Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); + setToStringTag(Constructor, NAME + ' Iterator'); + }; + + +/***/ }), +/* 131 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $at = __webpack_require__(127)(false); + $export($export.P, 'String', { + // 21.1.3.3 String.prototype.codePointAt(pos) + codePointAt: function codePointAt(pos) { + return $at(this, pos); + } + }); + + +/***/ }), +/* 132 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) + 'use strict'; + var $export = __webpack_require__(8); + var toLength = __webpack_require__(37); + var context = __webpack_require__(133); + var ENDS_WITH = 'endsWith'; + var $endsWith = ''[ENDS_WITH]; + + $export($export.P + $export.F * __webpack_require__(135)(ENDS_WITH), 'String', { + endsWith: function endsWith(searchString /* , endPosition = @length */) { + var that = context(this, searchString, ENDS_WITH); + var endPosition = arguments.length > 1 ? arguments[1] : undefined; + var len = toLength(that.length); + var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); + var search = String(searchString); + return $endsWith + ? $endsWith.call(that, search, end) + : that.slice(end - search.length, end) === search; + } + }); + + +/***/ }), +/* 133 */ +/***/ (function(module, exports, __webpack_require__) { + + // helper for String#{startsWith, endsWith, includes} + var isRegExp = __webpack_require__(134); + var defined = __webpack_require__(35); + + module.exports = function (that, searchString, NAME) { + if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!"); + return String(defined(that)); + }; + + +/***/ }), +/* 134 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.2.8 IsRegExp(argument) + var isObject = __webpack_require__(13); + var cof = __webpack_require__(34); + var MATCH = __webpack_require__(26)('match'); + module.exports = function (it) { + var isRegExp; + return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); + }; + + +/***/ }), +/* 135 */ +/***/ (function(module, exports, __webpack_require__) { + + var MATCH = __webpack_require__(26)('match'); + module.exports = function (KEY) { + var re = /./; + try { + '/./'[KEY](re); + } catch (e) { + try { + re[MATCH] = false; + return !'/./'[KEY](re); + } catch (f) { /* empty */ } + } return true; + }; + + +/***/ }), +/* 136 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.1.3.7 String.prototype.includes(searchString, position = 0) + 'use strict'; + var $export = __webpack_require__(8); + var context = __webpack_require__(133); + var INCLUDES = 'includes'; + + $export($export.P + $export.F * __webpack_require__(135)(INCLUDES), 'String', { + includes: function includes(searchString /* , position = 0 */) { + return !!~context(this, searchString, INCLUDES) + .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); + } + }); + + +/***/ }), +/* 137 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + + $export($export.P, 'String', { + // 21.1.3.13 String.prototype.repeat(count) + repeat: __webpack_require__(90) + }); + + +/***/ }), +/* 138 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) + 'use strict'; + var $export = __webpack_require__(8); + var toLength = __webpack_require__(37); + var context = __webpack_require__(133); + var STARTS_WITH = 'startsWith'; + var $startsWith = ''[STARTS_WITH]; + + $export($export.P + $export.F * __webpack_require__(135)(STARTS_WITH), 'String', { + startsWith: function startsWith(searchString /* , position = 0 */) { + var that = context(this, searchString, STARTS_WITH); + var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)); + var search = String(searchString); + return $startsWith + ? $startsWith.call(that, search, index) + : that.slice(index, index + search.length) === search; + } + }); + + +/***/ }), +/* 139 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.2 String.prototype.anchor(name) + __webpack_require__(140)('anchor', function (createHTML) { + return function anchor(name) { + return createHTML(this, 'a', 'name', name); + }; + }); + + +/***/ }), +/* 140 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var fails = __webpack_require__(7); + var defined = __webpack_require__(35); + var quot = /"/g; + // B.2.3.2.1 CreateHTML(string, tag, attribute, value) + var createHTML = function (string, tag, attribute, value) { + var S = String(defined(string)); + var p1 = '<' + tag; + if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; + return p1 + '>' + S + ''; + }; + module.exports = function (NAME, exec) { + var O = {}; + O[NAME] = exec(createHTML); + $export($export.P + $export.F * fails(function () { + var test = ''[NAME]('"'); + return test !== test.toLowerCase() || test.split('"').length > 3; + }), 'String', O); + }; + + +/***/ }), +/* 141 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.3 String.prototype.big() + __webpack_require__(140)('big', function (createHTML) { + return function big() { + return createHTML(this, 'big', '', ''); + }; + }); + + +/***/ }), +/* 142 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.4 String.prototype.blink() + __webpack_require__(140)('blink', function (createHTML) { + return function blink() { + return createHTML(this, 'blink', '', ''); + }; + }); + + +/***/ }), +/* 143 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.5 String.prototype.bold() + __webpack_require__(140)('bold', function (createHTML) { + return function bold() { + return createHTML(this, 'b', '', ''); + }; + }); + + +/***/ }), +/* 144 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.6 String.prototype.fixed() + __webpack_require__(140)('fixed', function (createHTML) { + return function fixed() { + return createHTML(this, 'tt', '', ''); + }; + }); + + +/***/ }), +/* 145 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.7 String.prototype.fontcolor(color) + __webpack_require__(140)('fontcolor', function (createHTML) { + return function fontcolor(color) { + return createHTML(this, 'font', 'color', color); + }; + }); + + +/***/ }), +/* 146 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.8 String.prototype.fontsize(size) + __webpack_require__(140)('fontsize', function (createHTML) { + return function fontsize(size) { + return createHTML(this, 'font', 'size', size); + }; + }); + + +/***/ }), +/* 147 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.9 String.prototype.italics() + __webpack_require__(140)('italics', function (createHTML) { + return function italics() { + return createHTML(this, 'i', '', ''); + }; + }); + + +/***/ }), +/* 148 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.10 String.prototype.link(url) + __webpack_require__(140)('link', function (createHTML) { + return function link(url) { + return createHTML(this, 'a', 'href', url); + }; + }); + + +/***/ }), +/* 149 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.11 String.prototype.small() + __webpack_require__(140)('small', function (createHTML) { + return function small() { + return createHTML(this, 'small', '', ''); + }; + }); + + +/***/ }), +/* 150 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.12 String.prototype.strike() + __webpack_require__(140)('strike', function (createHTML) { + return function strike() { + return createHTML(this, 'strike', '', ''); + }; + }); + + +/***/ }), +/* 151 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.13 String.prototype.sub() + __webpack_require__(140)('sub', function (createHTML) { + return function sub() { + return createHTML(this, 'sub', '', ''); + }; + }); + + +/***/ }), +/* 152 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.14 String.prototype.sup() + __webpack_require__(140)('sup', function (createHTML) { + return function sup() { + return createHTML(this, 'sup', '', ''); + }; + }); + + +/***/ }), +/* 153 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.3.3.1 / 15.9.4.4 Date.now() + var $export = __webpack_require__(8); + + $export($export.S, 'Date', { now: function () { return new Date().getTime(); } }); + + +/***/ }), +/* 154 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var toPrimitive = __webpack_require__(16); + + $export($export.P + $export.F * __webpack_require__(7)(function () { + return new Date(NaN).toJSON() !== null + || Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1; + }), 'Date', { + // eslint-disable-next-line no-unused-vars + toJSON: function toJSON(key) { + var O = toObject(this); + var pv = toPrimitive(O); + return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); + } + }); + + +/***/ }), +/* 155 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() + var $export = __webpack_require__(8); + var toISOString = __webpack_require__(156); + + // PhantomJS / old WebKit has a broken implementations + $export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', { + toISOString: toISOString + }); + + +/***/ }), +/* 156 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() + var fails = __webpack_require__(7); + var getTime = Date.prototype.getTime; + var $toISOString = Date.prototype.toISOString; + + var lz = function (num) { + return num > 9 ? num : '0' + num; + }; + + // PhantomJS / old WebKit has a broken implementations + module.exports = (fails(function () { + return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z'; + }) || !fails(function () { + $toISOString.call(new Date(NaN)); + })) ? function toISOString() { + if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value'); + var d = this; + var y = d.getUTCFullYear(); + var m = d.getUTCMilliseconds(); + var s = y < 0 ? '-' : y > 9999 ? '+' : ''; + return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; + } : $toISOString; + + +/***/ }), +/* 157 */ +/***/ (function(module, exports, __webpack_require__) { + + var DateProto = Date.prototype; + var INVALID_DATE = 'Invalid Date'; + var TO_STRING = 'toString'; + var $toString = DateProto[TO_STRING]; + var getTime = DateProto.getTime; + if (new Date(NaN) + '' != INVALID_DATE) { + __webpack_require__(18)(DateProto, TO_STRING, function toString() { + var value = getTime.call(this); + // eslint-disable-next-line no-self-compare + return value === value ? $toString.call(this) : INVALID_DATE; + }); + } + + +/***/ }), +/* 158 */ +/***/ (function(module, exports, __webpack_require__) { + + var TO_PRIMITIVE = __webpack_require__(26)('toPrimitive'); + var proto = Date.prototype; + + if (!(TO_PRIMITIVE in proto)) __webpack_require__(10)(proto, TO_PRIMITIVE, __webpack_require__(159)); + + +/***/ }), +/* 159 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var anObject = __webpack_require__(12); + var toPrimitive = __webpack_require__(16); + var NUMBER = 'number'; + + module.exports = function (hint) { + if (hint !== 'string' && hint !== NUMBER && hint !== 'default') throw TypeError('Incorrect hint'); + return toPrimitive(anObject(this), hint != NUMBER); + }; + + +/***/ }), +/* 160 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) + var $export = __webpack_require__(8); + + $export($export.S, 'Array', { isArray: __webpack_require__(44) }); + + +/***/ }), +/* 161 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var ctx = __webpack_require__(20); + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var call = __webpack_require__(162); + var isArrayIter = __webpack_require__(163); + var toLength = __webpack_require__(37); + var createProperty = __webpack_require__(164); + var getIterFn = __webpack_require__(165); + + $export($export.S + $export.F * !__webpack_require__(166)(function (iter) { Array.from(iter); }), 'Array', { + // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) + from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { + var O = toObject(arrayLike); + var C = typeof this == 'function' ? this : Array; + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var index = 0; + var iterFn = getIterFn(O); + var length, result, step, iterator; + if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); + // if object isn't iterable or it's array with default iterator - use simple case + if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { + for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { + createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); + } + } else { + length = toLength(O.length); + for (result = new C(length); length > index; index++) { + createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); + } + } + result.length = index; + return result; + } + }); + + +/***/ }), +/* 162 */ +/***/ (function(module, exports, __webpack_require__) { + + // call something on iterator step with safe closing on error + var anObject = __webpack_require__(12); + module.exports = function (iterator, fn, value, entries) { + try { + return entries ? fn(anObject(value)[0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) + } catch (e) { + var ret = iterator['return']; + if (ret !== undefined) anObject(ret.call(iterator)); + throw e; + } + }; + + +/***/ }), +/* 163 */ +/***/ (function(module, exports, __webpack_require__) { + + // check on default Array iterator + var Iterators = __webpack_require__(129); + var ITERATOR = __webpack_require__(26)('iterator'); + var ArrayProto = Array.prototype; + + module.exports = function (it) { + return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); + }; + + +/***/ }), +/* 164 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $defineProperty = __webpack_require__(11); + var createDesc = __webpack_require__(17); + + module.exports = function (object, index, value) { + if (index in object) $defineProperty.f(object, index, createDesc(0, value)); + else object[index] = value; + }; + + +/***/ }), +/* 165 */ +/***/ (function(module, exports, __webpack_require__) { + + var classof = __webpack_require__(74); + var ITERATOR = __webpack_require__(26)('iterator'); + var Iterators = __webpack_require__(129); + module.exports = __webpack_require__(9).getIteratorMethod = function (it) { + if (it != undefined) return it[ITERATOR] + || it['@@iterator'] + || Iterators[classof(it)]; + }; + + +/***/ }), +/* 166 */ +/***/ (function(module, exports, __webpack_require__) { + + var ITERATOR = __webpack_require__(26)('iterator'); + var SAFE_CLOSING = false; + + try { + var riter = [7][ITERATOR](); + riter['return'] = function () { SAFE_CLOSING = true; }; + // eslint-disable-next-line no-throw-literal + Array.from(riter, function () { throw 2; }); + } catch (e) { /* empty */ } + + module.exports = function (exec, skipClosing) { + if (!skipClosing && !SAFE_CLOSING) return false; + var safe = false; + try { + var arr = [7]; + var iter = arr[ITERATOR](); + iter.next = function () { return { done: safe = true }; }; + arr[ITERATOR] = function () { return iter; }; + exec(arr); + } catch (e) { /* empty */ } + return safe; + }; + + +/***/ }), +/* 167 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var createProperty = __webpack_require__(164); + + // WebKit Array.of isn't generic + $export($export.S + $export.F * __webpack_require__(7)(function () { + function F() { /* empty */ } + return !(Array.of.call(F) instanceof F); + }), 'Array', { + // 22.1.2.3 Array.of( ...items) + of: function of(/* ...args */) { + var index = 0; + var aLen = arguments.length; + var result = new (typeof this == 'function' ? this : Array)(aLen); + while (aLen > index) createProperty(result, index, arguments[index++]); + result.length = aLen; + return result; + } + }); + + +/***/ }), +/* 168 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.13 Array.prototype.join(separator) + var $export = __webpack_require__(8); + var toIObject = __webpack_require__(32); + var arrayJoin = [].join; + + // fallback for not array-like strings + $export($export.P + $export.F * (__webpack_require__(33) != Object || !__webpack_require__(169)(arrayJoin)), 'Array', { + join: function join(separator) { + return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); + } + }); + + +/***/ }), +/* 169 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var fails = __webpack_require__(7); + + module.exports = function (method, arg) { + return !!method && fails(function () { + // eslint-disable-next-line no-useless-call + arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null); + }); + }; + + +/***/ }), +/* 170 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var html = __webpack_require__(47); + var cof = __webpack_require__(34); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + var arraySlice = [].slice; + + // fallback for not array-like ES3 strings and DOM objects + $export($export.P + $export.F * __webpack_require__(7)(function () { + if (html) arraySlice.call(html); + }), 'Array', { + slice: function slice(begin, end) { + var len = toLength(this.length); + var klass = cof(this); + end = end === undefined ? len : end; + if (klass == 'Array') return arraySlice.call(this, begin, end); + var start = toAbsoluteIndex(begin, len); + var upTo = toAbsoluteIndex(end, len); + var size = toLength(upTo - start); + var cloned = new Array(size); + var i = 0; + for (; i < size; i++) cloned[i] = klass == 'String' + ? this.charAt(start + i) + : this[start + i]; + return cloned; + } + }); + + +/***/ }), +/* 171 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var aFunction = __webpack_require__(21); + var toObject = __webpack_require__(57); + var fails = __webpack_require__(7); + var $sort = [].sort; + var test = [1, 2, 3]; + + $export($export.P + $export.F * (fails(function () { + // IE8- + test.sort(undefined); + }) || !fails(function () { + // V8 bug + test.sort(null); + // Old WebKit + }) || !__webpack_require__(169)($sort)), 'Array', { + // 22.1.3.25 Array.prototype.sort(comparefn) + sort: function sort(comparefn) { + return comparefn === undefined + ? $sort.call(toObject(this)) + : $sort.call(toObject(this), aFunction(comparefn)); + } + }); + + +/***/ }), +/* 172 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $forEach = __webpack_require__(173)(0); + var STRICT = __webpack_require__(169)([].forEach, true); + + $export($export.P + $export.F * !STRICT, 'Array', { + // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) + forEach: function forEach(callbackfn /* , thisArg */) { + return $forEach(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 173 */ +/***/ (function(module, exports, __webpack_require__) { + + // 0 -> Array#forEach + // 1 -> Array#map + // 2 -> Array#filter + // 3 -> Array#some + // 4 -> Array#every + // 5 -> Array#find + // 6 -> Array#findIndex + var ctx = __webpack_require__(20); + var IObject = __webpack_require__(33); + var toObject = __webpack_require__(57); + var toLength = __webpack_require__(37); + var asc = __webpack_require__(174); + module.exports = function (TYPE, $create) { + var IS_MAP = TYPE == 1; + var IS_FILTER = TYPE == 2; + var IS_SOME = TYPE == 3; + var IS_EVERY = TYPE == 4; + var IS_FIND_INDEX = TYPE == 6; + var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; + var create = $create || asc; + return function ($this, callbackfn, that) { + var O = toObject($this); + var self = IObject(O); + var f = ctx(callbackfn, that, 3); + var length = toLength(self.length); + var index = 0; + var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; + var val, res; + for (;length > index; index++) if (NO_HOLES || index in self) { + val = self[index]; + res = f(val, index, O); + if (TYPE) { + if (IS_MAP) result[index] = res; // map + else if (res) switch (TYPE) { + case 3: return true; // some + case 5: return val; // find + case 6: return index; // findIndex + case 2: result.push(val); // filter + } else if (IS_EVERY) return false; // every + } + } + return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; + }; + }; + + +/***/ }), +/* 174 */ +/***/ (function(module, exports, __webpack_require__) { + + // 9.4.2.3 ArraySpeciesCreate(originalArray, length) + var speciesConstructor = __webpack_require__(175); + + module.exports = function (original, length) { + return new (speciesConstructor(original))(length); + }; + + +/***/ }), +/* 175 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + var isArray = __webpack_require__(44); + var SPECIES = __webpack_require__(26)('species'); + + module.exports = function (original) { + var C; + if (isArray(original)) { + C = original.constructor; + // cross-realm fallback + if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; + if (isObject(C)) { + C = C[SPECIES]; + if (C === null) C = undefined; + } + } return C === undefined ? Array : C; + }; + + +/***/ }), +/* 176 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $map = __webpack_require__(173)(1); + + $export($export.P + $export.F * !__webpack_require__(169)([].map, true), 'Array', { + // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) + map: function map(callbackfn /* , thisArg */) { + return $map(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 177 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $filter = __webpack_require__(173)(2); + + $export($export.P + $export.F * !__webpack_require__(169)([].filter, true), 'Array', { + // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) + filter: function filter(callbackfn /* , thisArg */) { + return $filter(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 178 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $some = __webpack_require__(173)(3); + + $export($export.P + $export.F * !__webpack_require__(169)([].some, true), 'Array', { + // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) + some: function some(callbackfn /* , thisArg */) { + return $some(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 179 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $every = __webpack_require__(173)(4); + + $export($export.P + $export.F * !__webpack_require__(169)([].every, true), 'Array', { + // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) + every: function every(callbackfn /* , thisArg */) { + return $every(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 180 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $reduce = __webpack_require__(181); + + $export($export.P + $export.F * !__webpack_require__(169)([].reduce, true), 'Array', { + // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) + reduce: function reduce(callbackfn /* , initialValue */) { + return $reduce(this, callbackfn, arguments.length, arguments[1], false); + } + }); + + +/***/ }), +/* 181 */ +/***/ (function(module, exports, __webpack_require__) { + + var aFunction = __webpack_require__(21); + var toObject = __webpack_require__(57); + var IObject = __webpack_require__(33); + var toLength = __webpack_require__(37); + + module.exports = function (that, callbackfn, aLen, memo, isRight) { + aFunction(callbackfn); + var O = toObject(that); + var self = IObject(O); + var length = toLength(O.length); + var index = isRight ? length - 1 : 0; + var i = isRight ? -1 : 1; + if (aLen < 2) for (;;) { + if (index in self) { + memo = self[index]; + index += i; + break; + } + index += i; + if (isRight ? index < 0 : length <= index) { + throw TypeError('Reduce of empty array with no initial value'); + } + } + for (;isRight ? index >= 0 : length > index; index += i) if (index in self) { + memo = callbackfn(memo, self[index], index, O); + } + return memo; + }; + + +/***/ }), +/* 182 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $reduce = __webpack_require__(181); + + $export($export.P + $export.F * !__webpack_require__(169)([].reduceRight, true), 'Array', { + // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) + reduceRight: function reduceRight(callbackfn /* , initialValue */) { + return $reduce(this, callbackfn, arguments.length, arguments[1], true); + } + }); + + +/***/ }), +/* 183 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $indexOf = __webpack_require__(36)(false); + var $native = [].indexOf; + var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; + + $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { + // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) + indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { + return NEGATIVE_ZERO + // convert -0 to +0 + ? $native.apply(this, arguments) || 0 + : $indexOf(this, searchElement, arguments[1]); + } + }); + + +/***/ }), +/* 184 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toIObject = __webpack_require__(32); + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + var $native = [].lastIndexOf; + var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; + + $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { + // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) + lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { + // convert -0 to +0 + if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0; + var O = toIObject(this); + var length = toLength(O.length); + var index = length - 1; + if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1])); + if (index < 0) index = length + index; + for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0; + return -1; + } + }); + + +/***/ }), +/* 185 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) + var $export = __webpack_require__(8); + + $export($export.P, 'Array', { copyWithin: __webpack_require__(186) }); + + __webpack_require__(187)('copyWithin'); + + +/***/ }), +/* 186 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) + 'use strict'; + var toObject = __webpack_require__(57); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + + module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { + var O = toObject(this); + var len = toLength(O.length); + var to = toAbsoluteIndex(target, len); + var from = toAbsoluteIndex(start, len); + var end = arguments.length > 2 ? arguments[2] : undefined; + var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); + var inc = 1; + if (from < to && to < from + count) { + inc = -1; + from += count - 1; + to += count - 1; + } + while (count-- > 0) { + if (from in O) O[to] = O[from]; + else delete O[to]; + to += inc; + from += inc; + } return O; + }; + + +/***/ }), +/* 187 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.31 Array.prototype[@@unscopables] + var UNSCOPABLES = __webpack_require__(26)('unscopables'); + var ArrayProto = Array.prototype; + if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(10)(ArrayProto, UNSCOPABLES, {}); + module.exports = function (key) { + ArrayProto[UNSCOPABLES][key] = true; + }; + + +/***/ }), +/* 188 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) + var $export = __webpack_require__(8); + + $export($export.P, 'Array', { fill: __webpack_require__(189) }); + + __webpack_require__(187)('fill'); + + +/***/ }), +/* 189 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) + 'use strict'; + var toObject = __webpack_require__(57); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + module.exports = function fill(value /* , start = 0, end = @length */) { + var O = toObject(this); + var length = toLength(O.length); + var aLen = arguments.length; + var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length); + var end = aLen > 2 ? arguments[2] : undefined; + var endPos = end === undefined ? length : toAbsoluteIndex(end, length); + while (endPos > index) O[index++] = value; + return O; + }; + + +/***/ }), +/* 190 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) + var $export = __webpack_require__(8); + var $find = __webpack_require__(173)(5); + var KEY = 'find'; + var forced = true; + // Shouldn't skip holes + if (KEY in []) Array(1)[KEY](function () { forced = false; }); + $export($export.P + $export.F * forced, 'Array', { + find: function find(callbackfn /* , that = undefined */) { + return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + __webpack_require__(187)(KEY); + + +/***/ }), +/* 191 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) + var $export = __webpack_require__(8); + var $find = __webpack_require__(173)(6); + var KEY = 'findIndex'; + var forced = true; + // Shouldn't skip holes + if (KEY in []) Array(1)[KEY](function () { forced = false; }); + $export($export.P + $export.F * forced, 'Array', { + findIndex: function findIndex(callbackfn /* , that = undefined */) { + return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + __webpack_require__(187)(KEY); + + +/***/ }), +/* 192 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(193)('Array'); + + +/***/ }), +/* 193 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var dP = __webpack_require__(11); + var DESCRIPTORS = __webpack_require__(6); + var SPECIES = __webpack_require__(26)('species'); + + module.exports = function (KEY) { + var C = global[KEY]; + if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { + configurable: true, + get: function () { return this; } + }); + }; + + +/***/ }), +/* 194 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var addToUnscopables = __webpack_require__(187); + var step = __webpack_require__(195); + var Iterators = __webpack_require__(129); + var toIObject = __webpack_require__(32); + + // 22.1.3.4 Array.prototype.entries() + // 22.1.3.13 Array.prototype.keys() + // 22.1.3.29 Array.prototype.values() + // 22.1.3.30 Array.prototype[@@iterator]() + module.exports = __webpack_require__(128)(Array, 'Array', function (iterated, kind) { + this._t = toIObject(iterated); // target + this._i = 0; // next index + this._k = kind; // kind + // 22.1.5.2.1 %ArrayIteratorPrototype%.next() + }, function () { + var O = this._t; + var kind = this._k; + var index = this._i++; + if (!O || index >= O.length) { + this._t = undefined; + return step(1); + } + if (kind == 'keys') return step(0, index); + if (kind == 'values') return step(0, O[index]); + return step(0, [index, O[index]]); + }, 'values'); + + // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) + Iterators.Arguments = Iterators.Array; + + addToUnscopables('keys'); + addToUnscopables('values'); + addToUnscopables('entries'); + + +/***/ }), +/* 195 */ +/***/ (function(module, exports) { + + module.exports = function (done, value) { + return { value: value, done: !!done }; + }; + + +/***/ }), +/* 196 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var inheritIfRequired = __webpack_require__(87); + var dP = __webpack_require__(11).f; + var gOPN = __webpack_require__(49).f; + var isRegExp = __webpack_require__(134); + var $flags = __webpack_require__(197); + var $RegExp = global.RegExp; + var Base = $RegExp; + var proto = $RegExp.prototype; + var re1 = /a/g; + var re2 = /a/g; + // "new" creates a new object, old webkit buggy here + var CORRECT_NEW = new $RegExp(re1) !== re1; + + if (__webpack_require__(6) && (!CORRECT_NEW || __webpack_require__(7)(function () { + re2[__webpack_require__(26)('match')] = false; + // RegExp constructor can alter flags and IsRegExp works correct with @@match + return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; + }))) { + $RegExp = function RegExp(p, f) { + var tiRE = this instanceof $RegExp; + var piRE = isRegExp(p); + var fiU = f === undefined; + return !tiRE && piRE && p.constructor === $RegExp && fiU ? p + : inheritIfRequired(CORRECT_NEW + ? new Base(piRE && !fiU ? p.source : p, f) + : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) + , tiRE ? this : proto, $RegExp); + }; + var proxy = function (key) { + key in $RegExp || dP($RegExp, key, { + configurable: true, + get: function () { return Base[key]; }, + set: function (it) { Base[key] = it; } + }); + }; + for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]); + proto.constructor = $RegExp; + $RegExp.prototype = proto; + __webpack_require__(18)(global, 'RegExp', $RegExp); + } + + __webpack_require__(193)('RegExp'); + + +/***/ }), +/* 197 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 21.2.5.3 get RegExp.prototype.flags + var anObject = __webpack_require__(12); + module.exports = function () { + var that = anObject(this); + var result = ''; + if (that.global) result += 'g'; + if (that.ignoreCase) result += 'i'; + if (that.multiline) result += 'm'; + if (that.unicode) result += 'u'; + if (that.sticky) result += 'y'; + return result; + }; + + +/***/ }), +/* 198 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + __webpack_require__(199); + var anObject = __webpack_require__(12); + var $flags = __webpack_require__(197); + var DESCRIPTORS = __webpack_require__(6); + var TO_STRING = 'toString'; + var $toString = /./[TO_STRING]; + + var define = function (fn) { + __webpack_require__(18)(RegExp.prototype, TO_STRING, fn, true); + }; + + // 21.2.5.14 RegExp.prototype.toString() + if (__webpack_require__(7)(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) { + define(function toString() { + var R = anObject(this); + return '/'.concat(R.source, '/', + 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); + }); + // FF44- RegExp#toString has a wrong name + } else if ($toString.name != TO_STRING) { + define(function toString() { + return $toString.call(this); + }); + } + + +/***/ }), +/* 199 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.2.5.3 get RegExp.prototype.flags() + if (__webpack_require__(6) && /./g.flags != 'g') __webpack_require__(11).f(RegExp.prototype, 'flags', { + configurable: true, + get: __webpack_require__(197) + }); + + +/***/ }), +/* 200 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@match logic + __webpack_require__(201)('match', 1, function (defined, MATCH, $match) { + // 21.1.3.11 String.prototype.match(regexp) + return [function match(regexp) { + 'use strict'; + var O = defined(this); + var fn = regexp == undefined ? undefined : regexp[MATCH]; + return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); + }, $match]; + }); + + +/***/ }), +/* 201 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var hide = __webpack_require__(10); + var redefine = __webpack_require__(18); + var fails = __webpack_require__(7); + var defined = __webpack_require__(35); + var wks = __webpack_require__(26); + + module.exports = function (KEY, length, exec) { + var SYMBOL = wks(KEY); + var fns = exec(defined, SYMBOL, ''[KEY]); + var strfn = fns[0]; + var rxfn = fns[1]; + if (fails(function () { + var O = {}; + O[SYMBOL] = function () { return 7; }; + return ''[KEY](O) != 7; + })) { + redefine(String.prototype, KEY, strfn); + hide(RegExp.prototype, SYMBOL, length == 2 + // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) + // 21.2.5.11 RegExp.prototype[@@split](string, limit) + ? function (string, arg) { return rxfn.call(string, this, arg); } + // 21.2.5.6 RegExp.prototype[@@match](string) + // 21.2.5.9 RegExp.prototype[@@search](string) + : function (string) { return rxfn.call(string, this); } + ); + } + }; + + +/***/ }), +/* 202 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@replace logic + __webpack_require__(201)('replace', 2, function (defined, REPLACE, $replace) { + // 21.1.3.14 String.prototype.replace(searchValue, replaceValue) + return [function replace(searchValue, replaceValue) { + 'use strict'; + var O = defined(this); + var fn = searchValue == undefined ? undefined : searchValue[REPLACE]; + return fn !== undefined + ? fn.call(searchValue, O, replaceValue) + : $replace.call(String(O), searchValue, replaceValue); + }, $replace]; + }); + + +/***/ }), +/* 203 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@search logic + __webpack_require__(201)('search', 1, function (defined, SEARCH, $search) { + // 21.1.3.15 String.prototype.search(regexp) + return [function search(regexp) { + 'use strict'; + var O = defined(this); + var fn = regexp == undefined ? undefined : regexp[SEARCH]; + return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); + }, $search]; + }); + + +/***/ }), +/* 204 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@split logic + __webpack_require__(201)('split', 2, function (defined, SPLIT, $split) { + 'use strict'; + var isRegExp = __webpack_require__(134); + var _split = $split; + var $push = [].push; + var $SPLIT = 'split'; + var LENGTH = 'length'; + var LAST_INDEX = 'lastIndex'; + if ( + 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || + 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || + 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || + '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || + '.'[$SPLIT](/()()/)[LENGTH] > 1 || + ''[$SPLIT](/.?/)[LENGTH] + ) { + var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group + // based on es5-shim implementation, need to rework it + $split = function (separator, limit) { + var string = String(this); + if (separator === undefined && limit === 0) return []; + // If `separator` is not a regex, use native split + if (!isRegExp(separator)) return _split.call(string, separator, limit); + var output = []; + var flags = (separator.ignoreCase ? 'i' : '') + + (separator.multiline ? 'm' : '') + + (separator.unicode ? 'u' : '') + + (separator.sticky ? 'y' : ''); + var lastLastIndex = 0; + var splitLimit = limit === undefined ? 4294967295 : limit >>> 0; + // Make `global` and avoid `lastIndex` issues by working with a copy + var separatorCopy = new RegExp(separator.source, flags + 'g'); + var separator2, match, lastIndex, lastLength, i; + // Doesn't need flags gy, but they don't hurt + if (!NPCG) separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); + while (match = separatorCopy.exec(string)) { + // `separatorCopy.lastIndex` is not reliable cross-browser + lastIndex = match.index + match[0][LENGTH]; + if (lastIndex > lastLastIndex) { + output.push(string.slice(lastLastIndex, match.index)); + // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG + // eslint-disable-next-line no-loop-func + if (!NPCG && match[LENGTH] > 1) match[0].replace(separator2, function () { + for (i = 1; i < arguments[LENGTH] - 2; i++) if (arguments[i] === undefined) match[i] = undefined; + }); + if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1)); + lastLength = match[0][LENGTH]; + lastLastIndex = lastIndex; + if (output[LENGTH] >= splitLimit) break; + } + if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop + } + if (lastLastIndex === string[LENGTH]) { + if (lastLength || !separatorCopy.test('')) output.push(''); + } else output.push(string.slice(lastLastIndex)); + return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; + }; + // Chakra, V8 + } else if ('0'[$SPLIT](undefined, 0)[LENGTH]) { + $split = function (separator, limit) { + return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit); + }; + } + // 21.1.3.17 String.prototype.split(separator, limit) + return [function split(separator, limit) { + var O = defined(this); + var fn = separator == undefined ? undefined : separator[SPLIT]; + return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit); + }, $split]; + }); + + +/***/ }), +/* 205 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var LIBRARY = __webpack_require__(24); + var global = __webpack_require__(4); + var ctx = __webpack_require__(20); + var classof = __webpack_require__(74); + var $export = __webpack_require__(8); + var isObject = __webpack_require__(13); + var aFunction = __webpack_require__(21); + var anInstance = __webpack_require__(206); + var forOf = __webpack_require__(207); + var speciesConstructor = __webpack_require__(208); + var task = __webpack_require__(209).set; + var microtask = __webpack_require__(210)(); + var newPromiseCapabilityModule = __webpack_require__(211); + var perform = __webpack_require__(212); + var userAgent = __webpack_require__(213); + var promiseResolve = __webpack_require__(214); + var PROMISE = 'Promise'; + var TypeError = global.TypeError; + var process = global.process; + var versions = process && process.versions; + var v8 = versions && versions.v8 || ''; + var $Promise = global[PROMISE]; + var isNode = classof(process) == 'process'; + var empty = function () { /* empty */ }; + var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; + var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; + + var USE_NATIVE = !!function () { + try { + // correct subclassing with @@species support + var promise = $Promise.resolve(1); + var FakePromise = (promise.constructor = {})[__webpack_require__(26)('species')] = function (exec) { + exec(empty, empty); + }; + // unhandled rejections tracking support, NodeJS Promise without it fails @@species test + return (isNode || typeof PromiseRejectionEvent == 'function') + && promise.then(empty) instanceof FakePromise + // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables + // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 + // we can't detect it synchronously, so just check versions + && v8.indexOf('6.6') !== 0 + && userAgent.indexOf('Chrome/66') === -1; + } catch (e) { /* empty */ } + }(); + + // helpers + var isThenable = function (it) { + var then; + return isObject(it) && typeof (then = it.then) == 'function' ? then : false; + }; + var notify = function (promise, isReject) { + if (promise._n) return; + promise._n = true; + var chain = promise._c; + microtask(function () { + var value = promise._v; + var ok = promise._s == 1; + var i = 0; + var run = function (reaction) { + var handler = ok ? reaction.ok : reaction.fail; + var resolve = reaction.resolve; + var reject = reaction.reject; + var domain = reaction.domain; + var result, then, exited; + try { + if (handler) { + if (!ok) { + if (promise._h == 2) onHandleUnhandled(promise); + promise._h = 1; + } + if (handler === true) result = value; + else { + if (domain) domain.enter(); + result = handler(value); // may throw + if (domain) { + domain.exit(); + exited = true; + } + } + if (result === reaction.promise) { + reject(TypeError('Promise-chain cycle')); + } else if (then = isThenable(result)) { + then.call(result, resolve, reject); + } else resolve(result); + } else reject(value); + } catch (e) { + if (domain && !exited) domain.exit(); + reject(e); + } + }; + while (chain.length > i) run(chain[i++]); // variable length - can't use forEach + promise._c = []; + promise._n = false; + if (isReject && !promise._h) onUnhandled(promise); + }); + }; + var onUnhandled = function (promise) { + task.call(global, function () { + var value = promise._v; + var unhandled = isUnhandled(promise); + var result, handler, console; + if (unhandled) { + result = perform(function () { + if (isNode) { + process.emit('unhandledRejection', value, promise); + } else if (handler = global.onunhandledrejection) { + handler({ promise: promise, reason: value }); + } else if ((console = global.console) && console.error) { + console.error('Unhandled promise rejection', value); + } + }); + // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should + promise._h = isNode || isUnhandled(promise) ? 2 : 1; + } promise._a = undefined; + if (unhandled && result.e) throw result.v; + }); + }; + var isUnhandled = function (promise) { + return promise._h !== 1 && (promise._a || promise._c).length === 0; + }; + var onHandleUnhandled = function (promise) { + task.call(global, function () { + var handler; + if (isNode) { + process.emit('rejectionHandled', promise); + } else if (handler = global.onrejectionhandled) { + handler({ promise: promise, reason: promise._v }); + } + }); + }; + var $reject = function (value) { + var promise = this; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + promise._v = value; + promise._s = 2; + if (!promise._a) promise._a = promise._c.slice(); + notify(promise, true); + }; + var $resolve = function (value) { + var promise = this; + var then; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + try { + if (promise === value) throw TypeError("Promise can't be resolved itself"); + if (then = isThenable(value)) { + microtask(function () { + var wrapper = { _w: promise, _d: false }; // wrap + try { + then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); + } catch (e) { + $reject.call(wrapper, e); + } + }); + } else { + promise._v = value; + promise._s = 1; + notify(promise, false); + } + } catch (e) { + $reject.call({ _w: promise, _d: false }, e); // wrap + } + }; + + // constructor polyfill + if (!USE_NATIVE) { + // 25.4.3.1 Promise(executor) + $Promise = function Promise(executor) { + anInstance(this, $Promise, PROMISE, '_h'); + aFunction(executor); + Internal.call(this); + try { + executor(ctx($resolve, this, 1), ctx($reject, this, 1)); + } catch (err) { + $reject.call(this, err); + } + }; + // eslint-disable-next-line no-unused-vars + Internal = function Promise(executor) { + this._c = []; // <- awaiting reactions + this._a = undefined; // <- checked in isUnhandled reactions + this._s = 0; // <- state + this._d = false; // <- done + this._v = undefined; // <- value + this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled + this._n = false; // <- notify + }; + Internal.prototype = __webpack_require__(215)($Promise.prototype, { + // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) + then: function then(onFulfilled, onRejected) { + var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); + reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; + reaction.fail = typeof onRejected == 'function' && onRejected; + reaction.domain = isNode ? process.domain : undefined; + this._c.push(reaction); + if (this._a) this._a.push(reaction); + if (this._s) notify(this, false); + return reaction.promise; + }, + // 25.4.5.1 Promise.prototype.catch(onRejected) + 'catch': function (onRejected) { + return this.then(undefined, onRejected); + } + }); + OwnPromiseCapability = function () { + var promise = new Internal(); + this.promise = promise; + this.resolve = ctx($resolve, promise, 1); + this.reject = ctx($reject, promise, 1); + }; + newPromiseCapabilityModule.f = newPromiseCapability = function (C) { + return C === $Promise || C === Wrapper + ? new OwnPromiseCapability(C) + : newGenericPromiseCapability(C); + }; + } + + $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); + __webpack_require__(25)($Promise, PROMISE); + __webpack_require__(193)(PROMISE); + Wrapper = __webpack_require__(9)[PROMISE]; + + // statics + $export($export.S + $export.F * !USE_NATIVE, PROMISE, { + // 25.4.4.5 Promise.reject(r) + reject: function reject(r) { + var capability = newPromiseCapability(this); + var $$reject = capability.reject; + $$reject(r); + return capability.promise; + } + }); + $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { + // 25.4.4.6 Promise.resolve(x) + resolve: function resolve(x) { + return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); + } + }); + $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(166)(function (iter) { + $Promise.all(iter)['catch'](empty); + })), PROMISE, { + // 25.4.4.1 Promise.all(iterable) + all: function all(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var resolve = capability.resolve; + var reject = capability.reject; + var result = perform(function () { + var values = []; + var index = 0; + var remaining = 1; + forOf(iterable, false, function (promise) { + var $index = index++; + var alreadyCalled = false; + values.push(undefined); + remaining++; + C.resolve(promise).then(function (value) { + if (alreadyCalled) return; + alreadyCalled = true; + values[$index] = value; + --remaining || resolve(values); + }, reject); + }); + --remaining || resolve(values); + }); + if (result.e) reject(result.v); + return capability.promise; + }, + // 25.4.4.4 Promise.race(iterable) + race: function race(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var reject = capability.reject; + var result = perform(function () { + forOf(iterable, false, function (promise) { + C.resolve(promise).then(capability.resolve, reject); + }); + }); + if (result.e) reject(result.v); + return capability.promise; + } + }); + + +/***/ }), +/* 206 */ +/***/ (function(module, exports) { + + module.exports = function (it, Constructor, name, forbiddenField) { + if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { + throw TypeError(name + ': incorrect invocation!'); + } return it; + }; + + +/***/ }), +/* 207 */ +/***/ (function(module, exports, __webpack_require__) { + + var ctx = __webpack_require__(20); + var call = __webpack_require__(162); + var isArrayIter = __webpack_require__(163); + var anObject = __webpack_require__(12); + var toLength = __webpack_require__(37); + var getIterFn = __webpack_require__(165); + var BREAK = {}; + var RETURN = {}; + var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { + var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); + var f = ctx(fn, that, entries ? 2 : 1); + var index = 0; + var length, step, iterator, result; + if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); + // fast case for arrays with default iterator + if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { + result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); + if (result === BREAK || result === RETURN) return result; + } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { + result = call(iterator, f, step.value, entries); + if (result === BREAK || result === RETURN) return result; + } + }; + exports.BREAK = BREAK; + exports.RETURN = RETURN; + + +/***/ }), +/* 208 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.3.20 SpeciesConstructor(O, defaultConstructor) + var anObject = __webpack_require__(12); + var aFunction = __webpack_require__(21); + var SPECIES = __webpack_require__(26)('species'); + module.exports = function (O, D) { + var C = anObject(O).constructor; + var S; + return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); + }; + + +/***/ }), +/* 209 */ +/***/ (function(module, exports, __webpack_require__) { + + var ctx = __webpack_require__(20); + var invoke = __webpack_require__(77); + var html = __webpack_require__(47); + var cel = __webpack_require__(15); + var global = __webpack_require__(4); + var process = global.process; + var setTask = global.setImmediate; + var clearTask = global.clearImmediate; + var MessageChannel = global.MessageChannel; + var Dispatch = global.Dispatch; + var counter = 0; + var queue = {}; + var ONREADYSTATECHANGE = 'onreadystatechange'; + var defer, channel, port; + var run = function () { + var id = +this; + // eslint-disable-next-line no-prototype-builtins + if (queue.hasOwnProperty(id)) { + var fn = queue[id]; + delete queue[id]; + fn(); + } + }; + var listener = function (event) { + run.call(event.data); + }; + // Node.js 0.9+ & IE10+ has setImmediate, otherwise: + if (!setTask || !clearTask) { + setTask = function setImmediate(fn) { + var args = []; + var i = 1; + while (arguments.length > i) args.push(arguments[i++]); + queue[++counter] = function () { + // eslint-disable-next-line no-new-func + invoke(typeof fn == 'function' ? fn : Function(fn), args); + }; + defer(counter); + return counter; + }; + clearTask = function clearImmediate(id) { + delete queue[id]; + }; + // Node.js 0.8- + if (__webpack_require__(34)(process) == 'process') { + defer = function (id) { + process.nextTick(ctx(run, id, 1)); + }; + // Sphere (JS game engine) Dispatch API + } else if (Dispatch && Dispatch.now) { + defer = function (id) { + Dispatch.now(ctx(run, id, 1)); + }; + // Browsers with MessageChannel, includes WebWorkers + } else if (MessageChannel) { + channel = new MessageChannel(); + port = channel.port2; + channel.port1.onmessage = listener; + defer = ctx(port.postMessage, port, 1); + // Browsers with postMessage, skip WebWorkers + // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' + } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { + defer = function (id) { + global.postMessage(id + '', '*'); + }; + global.addEventListener('message', listener, false); + // IE8- + } else if (ONREADYSTATECHANGE in cel('script')) { + defer = function (id) { + html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { + html.removeChild(this); + run.call(id); + }; + }; + // Rest old browsers + } else { + defer = function (id) { + setTimeout(ctx(run, id, 1), 0); + }; + } + } + module.exports = { + set: setTask, + clear: clearTask + }; + + +/***/ }), +/* 210 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var macrotask = __webpack_require__(209).set; + var Observer = global.MutationObserver || global.WebKitMutationObserver; + var process = global.process; + var Promise = global.Promise; + var isNode = __webpack_require__(34)(process) == 'process'; + + module.exports = function () { + var head, last, notify; + + var flush = function () { + var parent, fn; + if (isNode && (parent = process.domain)) parent.exit(); + while (head) { + fn = head.fn; + head = head.next; + try { + fn(); + } catch (e) { + if (head) notify(); + else last = undefined; + throw e; + } + } last = undefined; + if (parent) parent.enter(); + }; + + // Node.js + if (isNode) { + notify = function () { + process.nextTick(flush); + }; + // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 + } else if (Observer && !(global.navigator && global.navigator.standalone)) { + var toggle = true; + var node = document.createTextNode(''); + new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new + notify = function () { + node.data = toggle = !toggle; + }; + // environments with maybe non-completely correct, but existent Promise + } else if (Promise && Promise.resolve) { + // Promise.resolve without an argument throws an error in LG WebOS 2 + var promise = Promise.resolve(undefined); + notify = function () { + promise.then(flush); + }; + // for other environments - macrotask based on: + // - setImmediate + // - MessageChannel + // - window.postMessag + // - onreadystatechange + // - setTimeout + } else { + notify = function () { + // strange IE + webpack dev server bug - use .call(global) + macrotask.call(global, flush); + }; + } + + return function (fn) { + var task = { fn: fn, next: undefined }; + if (last) last.next = task; + if (!head) { + head = task; + notify(); + } last = task; + }; + }; + + +/***/ }), +/* 211 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 25.4.1.5 NewPromiseCapability(C) + var aFunction = __webpack_require__(21); + + function PromiseCapability(C) { + var resolve, reject; + this.promise = new C(function ($$resolve, $$reject) { + if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); + resolve = $$resolve; + reject = $$reject; + }); + this.resolve = aFunction(resolve); + this.reject = aFunction(reject); + } + + module.exports.f = function (C) { + return new PromiseCapability(C); + }; + + +/***/ }), +/* 212 */ +/***/ (function(module, exports) { + + module.exports = function (exec) { + try { + return { e: false, v: exec() }; + } catch (e) { + return { e: true, v: e }; + } + }; + + +/***/ }), +/* 213 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var navigator = global.navigator; + + module.exports = navigator && navigator.userAgent || ''; + + +/***/ }), +/* 214 */ +/***/ (function(module, exports, __webpack_require__) { + + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var newPromiseCapability = __webpack_require__(211); + + module.exports = function (C, x) { + anObject(C); + if (isObject(x) && x.constructor === C) return x; + var promiseCapability = newPromiseCapability.f(C); + var resolve = promiseCapability.resolve; + resolve(x); + return promiseCapability.promise; + }; + + +/***/ }), +/* 215 */ +/***/ (function(module, exports, __webpack_require__) { + + var redefine = __webpack_require__(18); + module.exports = function (target, src, safe) { + for (var key in src) redefine(target, key, src[key], safe); + return target; + }; + + +/***/ }), +/* 216 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var strong = __webpack_require__(217); + var validate = __webpack_require__(218); + var MAP = 'Map'; + + // 23.1 Map Objects + module.exports = __webpack_require__(219)(MAP, function (get) { + return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.1.3.6 Map.prototype.get(key) + get: function get(key) { + var entry = strong.getEntry(validate(this, MAP), key); + return entry && entry.v; + }, + // 23.1.3.9 Map.prototype.set(key, value) + set: function set(key, value) { + return strong.def(validate(this, MAP), key === 0 ? 0 : key, value); + } + }, strong, true); + + +/***/ }), +/* 217 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var dP = __webpack_require__(11).f; + var create = __webpack_require__(45); + var redefineAll = __webpack_require__(215); + var ctx = __webpack_require__(20); + var anInstance = __webpack_require__(206); + var forOf = __webpack_require__(207); + var $iterDefine = __webpack_require__(128); + var step = __webpack_require__(195); + var setSpecies = __webpack_require__(193); + var DESCRIPTORS = __webpack_require__(6); + var fastKey = __webpack_require__(22).fastKey; + var validate = __webpack_require__(218); + var SIZE = DESCRIPTORS ? '_s' : 'size'; + + var getEntry = function (that, key) { + // fast case + var index = fastKey(key); + var entry; + if (index !== 'F') return that._i[index]; + // frozen object case + for (entry = that._f; entry; entry = entry.n) { + if (entry.k == key) return entry; + } + }; + + module.exports = { + getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + anInstance(that, C, NAME, '_i'); + that._t = NAME; // collection type + that._i = create(null); // index + that._f = undefined; // first entry + that._l = undefined; // last entry + that[SIZE] = 0; // size + if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); + }); + redefineAll(C.prototype, { + // 23.1.3.1 Map.prototype.clear() + // 23.2.3.2 Set.prototype.clear() + clear: function clear() { + for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) { + entry.r = true; + if (entry.p) entry.p = entry.p.n = undefined; + delete data[entry.i]; + } + that._f = that._l = undefined; + that[SIZE] = 0; + }, + // 23.1.3.3 Map.prototype.delete(key) + // 23.2.3.4 Set.prototype.delete(value) + 'delete': function (key) { + var that = validate(this, NAME); + var entry = getEntry(that, key); + if (entry) { + var next = entry.n; + var prev = entry.p; + delete that._i[entry.i]; + entry.r = true; + if (prev) prev.n = next; + if (next) next.p = prev; + if (that._f == entry) that._f = next; + if (that._l == entry) that._l = prev; + that[SIZE]--; + } return !!entry; + }, + // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) + // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) + forEach: function forEach(callbackfn /* , that = undefined */) { + validate(this, NAME); + var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + var entry; + while (entry = entry ? entry.n : this._f) { + f(entry.v, entry.k, this); + // revert to the last existing entry + while (entry && entry.r) entry = entry.p; + } + }, + // 23.1.3.7 Map.prototype.has(key) + // 23.2.3.7 Set.prototype.has(value) + has: function has(key) { + return !!getEntry(validate(this, NAME), key); + } + }); + if (DESCRIPTORS) dP(C.prototype, 'size', { + get: function () { + return validate(this, NAME)[SIZE]; + } + }); + return C; + }, + def: function (that, key, value) { + var entry = getEntry(that, key); + var prev, index; + // change existing entry + if (entry) { + entry.v = value; + // create new entry + } else { + that._l = entry = { + i: index = fastKey(key, true), // <- index + k: key, // <- key + v: value, // <- value + p: prev = that._l, // <- previous entry + n: undefined, // <- next entry + r: false // <- removed + }; + if (!that._f) that._f = entry; + if (prev) prev.n = entry; + that[SIZE]++; + // add to index + if (index !== 'F') that._i[index] = entry; + } return that; + }, + getEntry: getEntry, + setStrong: function (C, NAME, IS_MAP) { + // add .keys, .values, .entries, [@@iterator] + // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 + $iterDefine(C, NAME, function (iterated, kind) { + this._t = validate(iterated, NAME); // target + this._k = kind; // kind + this._l = undefined; // previous + }, function () { + var that = this; + var kind = that._k; + var entry = that._l; + // revert to the last existing entry + while (entry && entry.r) entry = entry.p; + // get next entry + if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) { + // or finish the iteration + that._t = undefined; + return step(1); + } + // return step by kind + if (kind == 'keys') return step(0, entry.k); + if (kind == 'values') return step(0, entry.v); + return step(0, [entry.k, entry.v]); + }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); + + // add [@@species], 23.1.2.2, 23.2.2.2 + setSpecies(NAME); + } + }; + + +/***/ }), +/* 218 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + module.exports = function (it, TYPE) { + if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); + return it; + }; + + +/***/ }), +/* 219 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var $export = __webpack_require__(8); + var redefine = __webpack_require__(18); + var redefineAll = __webpack_require__(215); + var meta = __webpack_require__(22); + var forOf = __webpack_require__(207); + var anInstance = __webpack_require__(206); + var isObject = __webpack_require__(13); + var fails = __webpack_require__(7); + var $iterDetect = __webpack_require__(166); + var setToStringTag = __webpack_require__(25); + var inheritIfRequired = __webpack_require__(87); + + module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { + var Base = global[NAME]; + var C = Base; + var ADDER = IS_MAP ? 'set' : 'add'; + var proto = C && C.prototype; + var O = {}; + var fixMethod = function (KEY) { + var fn = proto[KEY]; + redefine(proto, KEY, + KEY == 'delete' ? function (a) { + return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'has' ? function has(a) { + return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'get' ? function get(a) { + return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; } + : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; } + ); + }; + if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () { + new C().entries().next(); + }))) { + // create collection constructor + C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); + redefineAll(C.prototype, methods); + meta.NEED = true; + } else { + var instance = new C(); + // early implementations not supports chaining + var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; + // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false + var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); + // most early implementations doesn't supports iterables, most modern - not close it correctly + var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new + // for early implementations -0 and +0 not the same + var BUGGY_ZERO = !IS_WEAK && fails(function () { + // V8 ~ Chromium 42- fails only with 5+ elements + var $instance = new C(); + var index = 5; + while (index--) $instance[ADDER](index, index); + return !$instance.has(-0); + }); + if (!ACCEPT_ITERABLES) { + C = wrapper(function (target, iterable) { + anInstance(target, C, NAME); + var that = inheritIfRequired(new Base(), target, C); + if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); + return that; + }); + C.prototype = proto; + proto.constructor = C; + } + if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { + fixMethod('delete'); + fixMethod('has'); + IS_MAP && fixMethod('get'); + } + if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); + // weak collections should not contains .clear method + if (IS_WEAK && proto.clear) delete proto.clear; + } + + setToStringTag(C, NAME); + + O[NAME] = C; + $export($export.G + $export.W + $export.F * (C != Base), O); + + if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP); + + return C; + }; + + +/***/ }), +/* 220 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var strong = __webpack_require__(217); + var validate = __webpack_require__(218); + var SET = 'Set'; + + // 23.2 Set Objects + module.exports = __webpack_require__(219)(SET, function (get) { + return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.2.3.1 Set.prototype.add(value) + add: function add(value) { + return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value); + } + }, strong); + + +/***/ }), +/* 221 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var each = __webpack_require__(173)(0); + var redefine = __webpack_require__(18); + var meta = __webpack_require__(22); + var assign = __webpack_require__(68); + var weak = __webpack_require__(222); + var isObject = __webpack_require__(13); + var fails = __webpack_require__(7); + var validate = __webpack_require__(218); + var WEAK_MAP = 'WeakMap'; + var getWeak = meta.getWeak; + var isExtensible = Object.isExtensible; + var uncaughtFrozenStore = weak.ufstore; + var tmp = {}; + var InternalMap; + + var wrapper = function (get) { + return function WeakMap() { + return get(this, arguments.length > 0 ? arguments[0] : undefined); + }; + }; + + var methods = { + // 23.3.3.3 WeakMap.prototype.get(key) + get: function get(key) { + if (isObject(key)) { + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key); + return data ? data[this._i] : undefined; + } + }, + // 23.3.3.5 WeakMap.prototype.set(key, value) + set: function set(key, value) { + return weak.def(validate(this, WEAK_MAP), key, value); + } + }; + + // 23.3 WeakMap Objects + var $WeakMap = module.exports = __webpack_require__(219)(WEAK_MAP, wrapper, methods, weak, true, true); + + // IE11 WeakMap frozen keys fix + if (fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) { + InternalMap = weak.getConstructor(wrapper, WEAK_MAP); + assign(InternalMap.prototype, methods); + meta.NEED = true; + each(['delete', 'has', 'get', 'set'], function (key) { + var proto = $WeakMap.prototype; + var method = proto[key]; + redefine(proto, key, function (a, b) { + // store frozen objects on internal weakmap shim + if (isObject(a) && !isExtensible(a)) { + if (!this._f) this._f = new InternalMap(); + var result = this._f[key](a, b); + return key == 'set' ? this : result; + // store all the rest on native weakmap + } return method.call(this, a, b); + }); + }); + } + + +/***/ }), +/* 222 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var redefineAll = __webpack_require__(215); + var getWeak = __webpack_require__(22).getWeak; + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var anInstance = __webpack_require__(206); + var forOf = __webpack_require__(207); + var createArrayMethod = __webpack_require__(173); + var $has = __webpack_require__(5); + var validate = __webpack_require__(218); + var arrayFind = createArrayMethod(5); + var arrayFindIndex = createArrayMethod(6); + var id = 0; + + // fallback for uncaught frozen keys + var uncaughtFrozenStore = function (that) { + return that._l || (that._l = new UncaughtFrozenStore()); + }; + var UncaughtFrozenStore = function () { + this.a = []; + }; + var findUncaughtFrozen = function (store, key) { + return arrayFind(store.a, function (it) { + return it[0] === key; + }); + }; + UncaughtFrozenStore.prototype = { + get: function (key) { + var entry = findUncaughtFrozen(this, key); + if (entry) return entry[1]; + }, + has: function (key) { + return !!findUncaughtFrozen(this, key); + }, + set: function (key, value) { + var entry = findUncaughtFrozen(this, key); + if (entry) entry[1] = value; + else this.a.push([key, value]); + }, + 'delete': function (key) { + var index = arrayFindIndex(this.a, function (it) { + return it[0] === key; + }); + if (~index) this.a.splice(index, 1); + return !!~index; + } + }; + + module.exports = { + getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + anInstance(that, C, NAME, '_i'); + that._t = NAME; // collection type + that._i = id++; // collection id + that._l = undefined; // leak store for uncaught frozen objects + if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); + }); + redefineAll(C.prototype, { + // 23.3.3.2 WeakMap.prototype.delete(key) + // 23.4.3.3 WeakSet.prototype.delete(value) + 'delete': function (key) { + if (!isObject(key)) return false; + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key); + return data && $has(data, this._i) && delete data[this._i]; + }, + // 23.3.3.4 WeakMap.prototype.has(key) + // 23.4.3.4 WeakSet.prototype.has(value) + has: function has(key) { + if (!isObject(key)) return false; + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key); + return data && $has(data, this._i); + } + }); + return C; + }, + def: function (that, key, value) { + var data = getWeak(anObject(key), true); + if (data === true) uncaughtFrozenStore(that).set(key, value); + else data[that._i] = value; + return that; + }, + ufstore: uncaughtFrozenStore + }; + + +/***/ }), +/* 223 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var weak = __webpack_require__(222); + var validate = __webpack_require__(218); + var WEAK_SET = 'WeakSet'; + + // 23.4 WeakSet Objects + __webpack_require__(219)(WEAK_SET, function (get) { + return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.4.3.1 WeakSet.prototype.add(value) + add: function add(value) { + return weak.def(validate(this, WEAK_SET), value, true); + } + }, weak, false, true); + + +/***/ }), +/* 224 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $typed = __webpack_require__(225); + var buffer = __webpack_require__(226); + var anObject = __webpack_require__(12); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + var isObject = __webpack_require__(13); + var ArrayBuffer = __webpack_require__(4).ArrayBuffer; + var speciesConstructor = __webpack_require__(208); + var $ArrayBuffer = buffer.ArrayBuffer; + var $DataView = buffer.DataView; + var $isView = $typed.ABV && ArrayBuffer.isView; + var $slice = $ArrayBuffer.prototype.slice; + var VIEW = $typed.VIEW; + var ARRAY_BUFFER = 'ArrayBuffer'; + + $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer }); + + $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { + // 24.1.3.1 ArrayBuffer.isView(arg) + isView: function isView(it) { + return $isView && $isView(it) || isObject(it) && VIEW in it; + } + }); + + $export($export.P + $export.U + $export.F * __webpack_require__(7)(function () { + return !new $ArrayBuffer(2).slice(1, undefined).byteLength; + }), ARRAY_BUFFER, { + // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) + slice: function slice(start, end) { + if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix + var len = anObject(this).byteLength; + var first = toAbsoluteIndex(start, len); + var fin = toAbsoluteIndex(end === undefined ? len : end, len); + var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(fin - first)); + var viewS = new $DataView(this); + var viewT = new $DataView(result); + var index = 0; + while (first < fin) { + viewT.setUint8(index++, viewS.getUint8(first++)); + } return result; + } + }); + + __webpack_require__(193)(ARRAY_BUFFER); + + +/***/ }), +/* 225 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var hide = __webpack_require__(10); + var uid = __webpack_require__(19); + var TYPED = uid('typed_array'); + var VIEW = uid('view'); + var ABV = !!(global.ArrayBuffer && global.DataView); + var CONSTR = ABV; + var i = 0; + var l = 9; + var Typed; + + var TypedArrayConstructors = ( + 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' + ).split(','); + + while (i < l) { + if (Typed = global[TypedArrayConstructors[i++]]) { + hide(Typed.prototype, TYPED, true); + hide(Typed.prototype, VIEW, true); + } else CONSTR = false; + } + + module.exports = { + ABV: ABV, + CONSTR: CONSTR, + TYPED: TYPED, + VIEW: VIEW + }; + + +/***/ }), +/* 226 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var DESCRIPTORS = __webpack_require__(6); + var LIBRARY = __webpack_require__(24); + var $typed = __webpack_require__(225); + var hide = __webpack_require__(10); + var redefineAll = __webpack_require__(215); + var fails = __webpack_require__(7); + var anInstance = __webpack_require__(206); + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + var toIndex = __webpack_require__(227); + var gOPN = __webpack_require__(49).f; + var dP = __webpack_require__(11).f; + var arrayFill = __webpack_require__(189); + var setToStringTag = __webpack_require__(25); + var ARRAY_BUFFER = 'ArrayBuffer'; + var DATA_VIEW = 'DataView'; + var PROTOTYPE = 'prototype'; + var WRONG_LENGTH = 'Wrong length!'; + var WRONG_INDEX = 'Wrong index!'; + var $ArrayBuffer = global[ARRAY_BUFFER]; + var $DataView = global[DATA_VIEW]; + var Math = global.Math; + var RangeError = global.RangeError; + // eslint-disable-next-line no-shadow-restricted-names + var Infinity = global.Infinity; + var BaseBuffer = $ArrayBuffer; + var abs = Math.abs; + var pow = Math.pow; + var floor = Math.floor; + var log = Math.log; + var LN2 = Math.LN2; + var BUFFER = 'buffer'; + var BYTE_LENGTH = 'byteLength'; + var BYTE_OFFSET = 'byteOffset'; + var $BUFFER = DESCRIPTORS ? '_b' : BUFFER; + var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH; + var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; + + // IEEE754 conversions based on https://github.com/feross/ieee754 + function packIEEE754(value, mLen, nBytes) { + var buffer = new Array(nBytes); + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0; + var i = 0; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + var e, m, c; + value = abs(value); + // eslint-disable-next-line no-self-compare + if (value != value || value === Infinity) { + // eslint-disable-next-line no-self-compare + m = value != value ? 1 : 0; + e = eMax; + } else { + e = floor(log(value) / LN2); + if (value * (c = pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * pow(2, mLen); + e = e + eBias; + } else { + m = value * pow(2, eBias - 1) * pow(2, mLen); + e = 0; + } + } + for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); + buffer[--i] |= s * 128; + return buffer; + } + function unpackIEEE754(buffer, mLen, nBytes) { + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = eLen - 7; + var i = nBytes - 1; + var s = buffer[i--]; + var e = s & 127; + var m; + s >>= 7; + for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : s ? -Infinity : Infinity; + } else { + m = m + pow(2, mLen); + e = e - eBias; + } return (s ? -1 : 1) * m * pow(2, e - mLen); + } + + function unpackI32(bytes) { + return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; + } + function packI8(it) { + return [it & 0xff]; + } + function packI16(it) { + return [it & 0xff, it >> 8 & 0xff]; + } + function packI32(it) { + return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; + } + function packF64(it) { + return packIEEE754(it, 52, 8); + } + function packF32(it) { + return packIEEE754(it, 23, 4); + } + + function addGetter(C, key, internal) { + dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } }); + } + + function get(view, bytes, index, isLittleEndian) { + var numIndex = +index; + var intIndex = toIndex(numIndex); + if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); + var store = view[$BUFFER]._b; + var start = intIndex + view[$OFFSET]; + var pack = store.slice(start, start + bytes); + return isLittleEndian ? pack : pack.reverse(); + } + function set(view, bytes, index, conversion, value, isLittleEndian) { + var numIndex = +index; + var intIndex = toIndex(numIndex); + if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); + var store = view[$BUFFER]._b; + var start = intIndex + view[$OFFSET]; + var pack = conversion(+value); + for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; + } + + if (!$typed.ABV) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer, ARRAY_BUFFER); + var byteLength = toIndex(length); + this._b = arrayFill.call(new Array(byteLength), 0); + this[$LENGTH] = byteLength; + }; + + $DataView = function DataView(buffer, byteOffset, byteLength) { + anInstance(this, $DataView, DATA_VIEW); + anInstance(buffer, $ArrayBuffer, DATA_VIEW); + var bufferLength = buffer[$LENGTH]; + var offset = toInteger(byteOffset); + if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!'); + byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); + if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH); + this[$BUFFER] = buffer; + this[$OFFSET] = offset; + this[$LENGTH] = byteLength; + }; + + if (DESCRIPTORS) { + addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); + addGetter($DataView, BUFFER, '_b'); + addGetter($DataView, BYTE_LENGTH, '_l'); + addGetter($DataView, BYTE_OFFSET, '_o'); + } + + redefineAll($DataView[PROTOTYPE], { + getInt8: function getInt8(byteOffset) { + return get(this, 1, byteOffset)[0] << 24 >> 24; + }, + getUint8: function getUint8(byteOffset) { + return get(this, 1, byteOffset)[0]; + }, + getInt16: function getInt16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments[1]); + return (bytes[1] << 8 | bytes[0]) << 16 >> 16; + }, + getUint16: function getUint16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments[1]); + return bytes[1] << 8 | bytes[0]; + }, + getInt32: function getInt32(byteOffset /* , littleEndian */) { + return unpackI32(get(this, 4, byteOffset, arguments[1])); + }, + getUint32: function getUint32(byteOffset /* , littleEndian */) { + return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; + }, + getFloat32: function getFloat32(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); + }, + getFloat64: function getFloat64(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); + }, + setInt8: function setInt8(byteOffset, value) { + set(this, 1, byteOffset, packI8, value); + }, + setUint8: function setUint8(byteOffset, value) { + set(this, 1, byteOffset, packI8, value); + }, + setInt16: function setInt16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packI16, value, arguments[2]); + }, + setUint16: function setUint16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packI16, value, arguments[2]); + }, + setInt32: function setInt32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packI32, value, arguments[2]); + }, + setUint32: function setUint32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packI32, value, arguments[2]); + }, + setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packF32, value, arguments[2]); + }, + setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { + set(this, 8, byteOffset, packF64, value, arguments[2]); + } + }); + } else { + if (!fails(function () { + $ArrayBuffer(1); + }) || !fails(function () { + new $ArrayBuffer(-1); // eslint-disable-line no-new + }) || fails(function () { + new $ArrayBuffer(); // eslint-disable-line no-new + new $ArrayBuffer(1.5); // eslint-disable-line no-new + new $ArrayBuffer(NaN); // eslint-disable-line no-new + return $ArrayBuffer.name != ARRAY_BUFFER; + })) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer); + return new BaseBuffer(toIndex(length)); + }; + var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; + for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) { + if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]); + } + if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer; + } + // iOS Safari 7.x bug + var view = new $DataView(new $ArrayBuffer(2)); + var $setInt8 = $DataView[PROTOTYPE].setInt8; + view.setInt8(0, 2147483648); + view.setInt8(1, 2147483649); + if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], { + setInt8: function setInt8(byteOffset, value) { + $setInt8.call(this, byteOffset, value << 24 >> 24); + }, + setUint8: function setUint8(byteOffset, value) { + $setInt8.call(this, byteOffset, value << 24 >> 24); + } + }, true); + } + setToStringTag($ArrayBuffer, ARRAY_BUFFER); + setToStringTag($DataView, DATA_VIEW); + hide($DataView[PROTOTYPE], $typed.VIEW, true); + exports[ARRAY_BUFFER] = $ArrayBuffer; + exports[DATA_VIEW] = $DataView; + + +/***/ }), +/* 227 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/ecma262/#sec-toindex + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + module.exports = function (it) { + if (it === undefined) return 0; + var number = toInteger(it); + var length = toLength(number); + if (number !== length) throw RangeError('Wrong length!'); + return length; + }; + + +/***/ }), +/* 228 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + $export($export.G + $export.W + $export.F * !__webpack_require__(225).ABV, { + DataView: __webpack_require__(226).DataView + }); + + +/***/ }), +/* 229 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Int8', 1, function (init) { + return function Int8Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 230 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + if (__webpack_require__(6)) { + var LIBRARY = __webpack_require__(24); + var global = __webpack_require__(4); + var fails = __webpack_require__(7); + var $export = __webpack_require__(8); + var $typed = __webpack_require__(225); + var $buffer = __webpack_require__(226); + var ctx = __webpack_require__(20); + var anInstance = __webpack_require__(206); + var propertyDesc = __webpack_require__(17); + var hide = __webpack_require__(10); + var redefineAll = __webpack_require__(215); + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + var toIndex = __webpack_require__(227); + var toAbsoluteIndex = __webpack_require__(39); + var toPrimitive = __webpack_require__(16); + var has = __webpack_require__(5); + var classof = __webpack_require__(74); + var isObject = __webpack_require__(13); + var toObject = __webpack_require__(57); + var isArrayIter = __webpack_require__(163); + var create = __webpack_require__(45); + var getPrototypeOf = __webpack_require__(58); + var gOPN = __webpack_require__(49).f; + var getIterFn = __webpack_require__(165); + var uid = __webpack_require__(19); + var wks = __webpack_require__(26); + var createArrayMethod = __webpack_require__(173); + var createArrayIncludes = __webpack_require__(36); + var speciesConstructor = __webpack_require__(208); + var ArrayIterators = __webpack_require__(194); + var Iterators = __webpack_require__(129); + var $iterDetect = __webpack_require__(166); + var setSpecies = __webpack_require__(193); + var arrayFill = __webpack_require__(189); + var arrayCopyWithin = __webpack_require__(186); + var $DP = __webpack_require__(11); + var $GOPD = __webpack_require__(50); + var dP = $DP.f; + var gOPD = $GOPD.f; + var RangeError = global.RangeError; + var TypeError = global.TypeError; + var Uint8Array = global.Uint8Array; + var ARRAY_BUFFER = 'ArrayBuffer'; + var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER; + var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; + var PROTOTYPE = 'prototype'; + var ArrayProto = Array[PROTOTYPE]; + var $ArrayBuffer = $buffer.ArrayBuffer; + var $DataView = $buffer.DataView; + var arrayForEach = createArrayMethod(0); + var arrayFilter = createArrayMethod(2); + var arraySome = createArrayMethod(3); + var arrayEvery = createArrayMethod(4); + var arrayFind = createArrayMethod(5); + var arrayFindIndex = createArrayMethod(6); + var arrayIncludes = createArrayIncludes(true); + var arrayIndexOf = createArrayIncludes(false); + var arrayValues = ArrayIterators.values; + var arrayKeys = ArrayIterators.keys; + var arrayEntries = ArrayIterators.entries; + var arrayLastIndexOf = ArrayProto.lastIndexOf; + var arrayReduce = ArrayProto.reduce; + var arrayReduceRight = ArrayProto.reduceRight; + var arrayJoin = ArrayProto.join; + var arraySort = ArrayProto.sort; + var arraySlice = ArrayProto.slice; + var arrayToString = ArrayProto.toString; + var arrayToLocaleString = ArrayProto.toLocaleString; + var ITERATOR = wks('iterator'); + var TAG = wks('toStringTag'); + var TYPED_CONSTRUCTOR = uid('typed_constructor'); + var DEF_CONSTRUCTOR = uid('def_constructor'); + var ALL_CONSTRUCTORS = $typed.CONSTR; + var TYPED_ARRAY = $typed.TYPED; + var VIEW = $typed.VIEW; + var WRONG_LENGTH = 'Wrong length!'; + + var $map = createArrayMethod(1, function (O, length) { + return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); + }); + + var LITTLE_ENDIAN = fails(function () { + // eslint-disable-next-line no-undef + return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; + }); + + var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () { + new Uint8Array(1).set({}); + }); + + var toOffset = function (it, BYTES) { + var offset = toInteger(it); + if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!'); + return offset; + }; + + var validate = function (it) { + if (isObject(it) && TYPED_ARRAY in it) return it; + throw TypeError(it + ' is not a typed array!'); + }; + + var allocate = function (C, length) { + if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) { + throw TypeError('It is not a typed array constructor!'); + } return new C(length); + }; + + var speciesFromList = function (O, list) { + return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); + }; + + var fromList = function (C, list) { + var index = 0; + var length = list.length; + var result = allocate(C, length); + while (length > index) result[index] = list[index++]; + return result; + }; + + var addGetter = function (it, key, internal) { + dP(it, key, { get: function () { return this._d[internal]; } }); + }; + + var $from = function from(source /* , mapfn, thisArg */) { + var O = toObject(source); + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var iterFn = getIterFn(O); + var i, length, values, result, step, iterator; + if (iterFn != undefined && !isArrayIter(iterFn)) { + for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) { + values.push(step.value); + } O = values; + } + if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2); + for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) { + result[i] = mapping ? mapfn(O[i], i) : O[i]; + } + return result; + }; + + var $of = function of(/* ...items */) { + var index = 0; + var length = arguments.length; + var result = allocate(this, length); + while (length > index) result[index] = arguments[index++]; + return result; + }; + + // iOS Safari 6.x fails here + var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); }); + + var $toLocaleString = function toLocaleString() { + return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); + }; + + var proto = { + copyWithin: function copyWithin(target, start /* , end */) { + return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); + }, + every: function every(callbackfn /* , thisArg */) { + return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars + return arrayFill.apply(validate(this), arguments); + }, + filter: function filter(callbackfn /* , thisArg */) { + return speciesFromList(this, arrayFilter(validate(this), callbackfn, + arguments.length > 1 ? arguments[1] : undefined)); + }, + find: function find(predicate /* , thisArg */) { + return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }, + findIndex: function findIndex(predicate /* , thisArg */) { + return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }, + forEach: function forEach(callbackfn /* , thisArg */) { + arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + indexOf: function indexOf(searchElement /* , fromIndex */) { + return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }, + includes: function includes(searchElement /* , fromIndex */) { + return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }, + join: function join(separator) { // eslint-disable-line no-unused-vars + return arrayJoin.apply(validate(this), arguments); + }, + lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars + return arrayLastIndexOf.apply(validate(this), arguments); + }, + map: function map(mapfn /* , thisArg */) { + return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); + }, + reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars + return arrayReduce.apply(validate(this), arguments); + }, + reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars + return arrayReduceRight.apply(validate(this), arguments); + }, + reverse: function reverse() { + var that = this; + var length = validate(that).length; + var middle = Math.floor(length / 2); + var index = 0; + var value; + while (index < middle) { + value = that[index]; + that[index++] = that[--length]; + that[length] = value; + } return that; + }, + some: function some(callbackfn /* , thisArg */) { + return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + sort: function sort(comparefn) { + return arraySort.call(validate(this), comparefn); + }, + subarray: function subarray(begin, end) { + var O = validate(this); + var length = O.length; + var $begin = toAbsoluteIndex(begin, length); + return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( + O.buffer, + O.byteOffset + $begin * O.BYTES_PER_ELEMENT, + toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin) + ); + } + }; + + var $slice = function slice(start, end) { + return speciesFromList(this, arraySlice.call(validate(this), start, end)); + }; + + var $set = function set(arrayLike /* , offset */) { + validate(this); + var offset = toOffset(arguments[1], 1); + var length = this.length; + var src = toObject(arrayLike); + var len = toLength(src.length); + var index = 0; + if (len + offset > length) throw RangeError(WRONG_LENGTH); + while (index < len) this[offset + index] = src[index++]; + }; + + var $iterators = { + entries: function entries() { + return arrayEntries.call(validate(this)); + }, + keys: function keys() { + return arrayKeys.call(validate(this)); + }, + values: function values() { + return arrayValues.call(validate(this)); + } + }; + + var isTAIndex = function (target, key) { + return isObject(target) + && target[TYPED_ARRAY] + && typeof key != 'symbol' + && key in target + && String(+key) == String(key); + }; + var $getDesc = function getOwnPropertyDescriptor(target, key) { + return isTAIndex(target, key = toPrimitive(key, true)) + ? propertyDesc(2, target[key]) + : gOPD(target, key); + }; + var $setDesc = function defineProperty(target, key, desc) { + if (isTAIndex(target, key = toPrimitive(key, true)) + && isObject(desc) + && has(desc, 'value') + && !has(desc, 'get') + && !has(desc, 'set') + // TODO: add validation descriptor w/o calling accessors + && !desc.configurable + && (!has(desc, 'writable') || desc.writable) + && (!has(desc, 'enumerable') || desc.enumerable) + ) { + target[key] = desc.value; + return target; + } return dP(target, key, desc); + }; + + if (!ALL_CONSTRUCTORS) { + $GOPD.f = $getDesc; + $DP.f = $setDesc; + } + + $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { + getOwnPropertyDescriptor: $getDesc, + defineProperty: $setDesc + }); + + if (fails(function () { arrayToString.call({}); })) { + arrayToString = arrayToLocaleString = function toString() { + return arrayJoin.call(this); + }; + } + + var $TypedArrayPrototype$ = redefineAll({}, proto); + redefineAll($TypedArrayPrototype$, $iterators); + hide($TypedArrayPrototype$, ITERATOR, $iterators.values); + redefineAll($TypedArrayPrototype$, { + slice: $slice, + set: $set, + constructor: function () { /* noop */ }, + toString: arrayToString, + toLocaleString: $toLocaleString + }); + addGetter($TypedArrayPrototype$, 'buffer', 'b'); + addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); + addGetter($TypedArrayPrototype$, 'byteLength', 'l'); + addGetter($TypedArrayPrototype$, 'length', 'e'); + dP($TypedArrayPrototype$, TAG, { + get: function () { return this[TYPED_ARRAY]; } + }); + + // eslint-disable-next-line max-statements + module.exports = function (KEY, BYTES, wrapper, CLAMPED) { + CLAMPED = !!CLAMPED; + var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'; + var GETTER = 'get' + KEY; + var SETTER = 'set' + KEY; + var TypedArray = global[NAME]; + var Base = TypedArray || {}; + var TAC = TypedArray && getPrototypeOf(TypedArray); + var FORCED = !TypedArray || !$typed.ABV; + var O = {}; + var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; + var getter = function (that, index) { + var data = that._d; + return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); + }; + var setter = function (that, index, value) { + var data = that._d; + if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; + data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); + }; + var addElement = function (that, index) { + dP(that, index, { + get: function () { + return getter(this, index); + }, + set: function (value) { + return setter(this, index, value); + }, + enumerable: true + }); + }; + if (FORCED) { + TypedArray = wrapper(function (that, data, $offset, $length) { + anInstance(that, TypedArray, NAME, '_d'); + var index = 0; + var offset = 0; + var buffer, byteLength, length, klass; + if (!isObject(data)) { + length = toIndex(data); + byteLength = length * BYTES; + buffer = new $ArrayBuffer(byteLength); + } else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { + buffer = data; + offset = toOffset($offset, BYTES); + var $len = data.byteLength; + if ($length === undefined) { + if ($len % BYTES) throw RangeError(WRONG_LENGTH); + byteLength = $len - offset; + if (byteLength < 0) throw RangeError(WRONG_LENGTH); + } else { + byteLength = toLength($length) * BYTES; + if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH); + } + length = byteLength / BYTES; + } else if (TYPED_ARRAY in data) { + return fromList(TypedArray, data); + } else { + return $from.call(TypedArray, data); + } + hide(that, '_d', { + b: buffer, + o: offset, + l: byteLength, + e: length, + v: new $DataView(buffer) + }); + while (index < length) addElement(that, index++); + }); + TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); + hide(TypedArrayPrototype, 'constructor', TypedArray); + } else if (!fails(function () { + TypedArray(1); + }) || !fails(function () { + new TypedArray(-1); // eslint-disable-line no-new + }) || !$iterDetect(function (iter) { + new TypedArray(); // eslint-disable-line no-new + new TypedArray(null); // eslint-disable-line no-new + new TypedArray(1.5); // eslint-disable-line no-new + new TypedArray(iter); // eslint-disable-line no-new + }, true)) { + TypedArray = wrapper(function (that, data, $offset, $length) { + anInstance(that, TypedArray, NAME); + var klass; + // `ws` module bug, temporarily remove validation length for Uint8Array + // https://github.com/websockets/ws/pull/645 + if (!isObject(data)) return new Base(toIndex(data)); + if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { + return $length !== undefined + ? new Base(data, toOffset($offset, BYTES), $length) + : $offset !== undefined + ? new Base(data, toOffset($offset, BYTES)) + : new Base(data); + } + if (TYPED_ARRAY in data) return fromList(TypedArray, data); + return $from.call(TypedArray, data); + }); + arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) { + if (!(key in TypedArray)) hide(TypedArray, key, Base[key]); + }); + TypedArray[PROTOTYPE] = TypedArrayPrototype; + if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray; + } + var $nativeIterator = TypedArrayPrototype[ITERATOR]; + var CORRECT_ITER_NAME = !!$nativeIterator + && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined); + var $iterator = $iterators.values; + hide(TypedArray, TYPED_CONSTRUCTOR, true); + hide(TypedArrayPrototype, TYPED_ARRAY, NAME); + hide(TypedArrayPrototype, VIEW, true); + hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); + + if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) { + dP(TypedArrayPrototype, TAG, { + get: function () { return NAME; } + }); + } + + O[NAME] = TypedArray; + + $export($export.G + $export.W + $export.F * (TypedArray != Base), O); + + $export($export.S, NAME, { + BYTES_PER_ELEMENT: BYTES + }); + + $export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, { + from: $from, + of: $of + }); + + if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); + + $export($export.P, NAME, proto); + + setSpecies(NAME); + + $export($export.P + $export.F * FORCED_SET, NAME, { set: $set }); + + $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); + + if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString; + + $export($export.P + $export.F * fails(function () { + new TypedArray(1).slice(); + }), NAME, { slice: $slice }); + + $export($export.P + $export.F * (fails(function () { + return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString(); + }) || !fails(function () { + TypedArrayPrototype.toLocaleString.call([1, 2]); + })), NAME, { toLocaleString: $toLocaleString }); + + Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; + if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator); + }; + } else module.exports = function () { /* empty */ }; + + +/***/ }), +/* 231 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint8', 1, function (init) { + return function Uint8Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 232 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint8', 1, function (init) { + return function Uint8ClampedArray(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }, true); + + +/***/ }), +/* 233 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Int16', 2, function (init) { + return function Int16Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 234 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint16', 2, function (init) { + return function Uint16Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 235 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Int32', 4, function (init) { + return function Int32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 236 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint32', 4, function (init) { + return function Uint32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 237 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Float32', 4, function (init) { + return function Float32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 238 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Float64', 8, function (init) { + return function Float64Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 239 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) + var $export = __webpack_require__(8); + var aFunction = __webpack_require__(21); + var anObject = __webpack_require__(12); + var rApply = (__webpack_require__(4).Reflect || {}).apply; + var fApply = Function.apply; + // MS Edge argumentsList argument is optional + $export($export.S + $export.F * !__webpack_require__(7)(function () { + rApply(function () { /* empty */ }); + }), 'Reflect', { + apply: function apply(target, thisArgument, argumentsList) { + var T = aFunction(target); + var L = anObject(argumentsList); + return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L); + } + }); + + +/***/ }), +/* 240 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) + var $export = __webpack_require__(8); + var create = __webpack_require__(45); + var aFunction = __webpack_require__(21); + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var fails = __webpack_require__(7); + var bind = __webpack_require__(76); + var rConstruct = (__webpack_require__(4).Reflect || {}).construct; + + // MS Edge supports only 2 arguments and argumentsList argument is optional + // FF Nightly sets third argument as `new.target`, but does not create `this` from it + var NEW_TARGET_BUG = fails(function () { + function F() { /* empty */ } + return !(rConstruct(function () { /* empty */ }, [], F) instanceof F); + }); + var ARGS_BUG = !fails(function () { + rConstruct(function () { /* empty */ }); + }); + + $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { + construct: function construct(Target, args /* , newTarget */) { + aFunction(Target); + anObject(args); + var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); + if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget); + if (Target == newTarget) { + // w/o altered newTarget, optimization for 0-4 arguments + switch (args.length) { + case 0: return new Target(); + case 1: return new Target(args[0]); + case 2: return new Target(args[0], args[1]); + case 3: return new Target(args[0], args[1], args[2]); + case 4: return new Target(args[0], args[1], args[2], args[3]); + } + // w/o altered newTarget, lot of arguments case + var $args = [null]; + $args.push.apply($args, args); + return new (bind.apply(Target, $args))(); + } + // with altered newTarget, not support built-in constructors + var proto = newTarget.prototype; + var instance = create(isObject(proto) ? proto : Object.prototype); + var result = Function.apply.call(Target, instance, args); + return isObject(result) ? result : instance; + } + }); + + +/***/ }), +/* 241 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) + var dP = __webpack_require__(11); + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var toPrimitive = __webpack_require__(16); + + // MS Edge has broken Reflect.defineProperty - throwing instead of returning false + $export($export.S + $export.F * __webpack_require__(7)(function () { + // eslint-disable-next-line no-undef + Reflect.defineProperty(dP.f({}, 1, { value: 1 }), 1, { value: 2 }); + }), 'Reflect', { + defineProperty: function defineProperty(target, propertyKey, attributes) { + anObject(target); + propertyKey = toPrimitive(propertyKey, true); + anObject(attributes); + try { + dP.f(target, propertyKey, attributes); + return true; + } catch (e) { + return false; + } + } + }); + + +/***/ }), +/* 242 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.4 Reflect.deleteProperty(target, propertyKey) + var $export = __webpack_require__(8); + var gOPD = __webpack_require__(50).f; + var anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + deleteProperty: function deleteProperty(target, propertyKey) { + var desc = gOPD(anObject(target), propertyKey); + return desc && !desc.configurable ? false : delete target[propertyKey]; + } + }); + + +/***/ }), +/* 243 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 26.1.5 Reflect.enumerate(target) + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var Enumerate = function (iterated) { + this._t = anObject(iterated); // target + this._i = 0; // next index + var keys = this._k = []; // keys + var key; + for (key in iterated) keys.push(key); + }; + __webpack_require__(130)(Enumerate, 'Object', function () { + var that = this; + var keys = that._k; + var key; + do { + if (that._i >= keys.length) return { value: undefined, done: true }; + } while (!((key = keys[that._i++]) in that._t)); + return { value: key, done: false }; + }); + + $export($export.S, 'Reflect', { + enumerate: function enumerate(target) { + return new Enumerate(target); + } + }); + + +/***/ }), +/* 244 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.6 Reflect.get(target, propertyKey [, receiver]) + var gOPD = __webpack_require__(50); + var getPrototypeOf = __webpack_require__(58); + var has = __webpack_require__(5); + var $export = __webpack_require__(8); + var isObject = __webpack_require__(13); + var anObject = __webpack_require__(12); + + function get(target, propertyKey /* , receiver */) { + var receiver = arguments.length < 3 ? target : arguments[2]; + var desc, proto; + if (anObject(target) === receiver) return target[propertyKey]; + if (desc = gOPD.f(target, propertyKey)) return has(desc, 'value') + ? desc.value + : desc.get !== undefined + ? desc.get.call(receiver) + : undefined; + if (isObject(proto = getPrototypeOf(target))) return get(proto, propertyKey, receiver); + } + + $export($export.S, 'Reflect', { get: get }); + + +/***/ }), +/* 245 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) + var gOPD = __webpack_require__(50); + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { + return gOPD.f(anObject(target), propertyKey); + } + }); + + +/***/ }), +/* 246 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.8 Reflect.getPrototypeOf(target) + var $export = __webpack_require__(8); + var getProto = __webpack_require__(58); + var anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + getPrototypeOf: function getPrototypeOf(target) { + return getProto(anObject(target)); + } + }); + + +/***/ }), +/* 247 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.9 Reflect.has(target, propertyKey) + var $export = __webpack_require__(8); + + $export($export.S, 'Reflect', { + has: function has(target, propertyKey) { + return propertyKey in target; + } + }); + + +/***/ }), +/* 248 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.10 Reflect.isExtensible(target) + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var $isExtensible = Object.isExtensible; + + $export($export.S, 'Reflect', { + isExtensible: function isExtensible(target) { + anObject(target); + return $isExtensible ? $isExtensible(target) : true; + } + }); + + +/***/ }), +/* 249 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.11 Reflect.ownKeys(target) + var $export = __webpack_require__(8); + + $export($export.S, 'Reflect', { ownKeys: __webpack_require__(250) }); + + +/***/ }), +/* 250 */ +/***/ (function(module, exports, __webpack_require__) { + + // all object keys, includes non-enumerable and symbols + var gOPN = __webpack_require__(49); + var gOPS = __webpack_require__(42); + var anObject = __webpack_require__(12); + var Reflect = __webpack_require__(4).Reflect; + module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) { + var keys = gOPN.f(anObject(it)); + var getSymbols = gOPS.f; + return getSymbols ? keys.concat(getSymbols(it)) : keys; + }; + + +/***/ }), +/* 251 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.12 Reflect.preventExtensions(target) + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var $preventExtensions = Object.preventExtensions; + + $export($export.S, 'Reflect', { + preventExtensions: function preventExtensions(target) { + anObject(target); + try { + if ($preventExtensions) $preventExtensions(target); + return true; + } catch (e) { + return false; + } + } + }); + + +/***/ }), +/* 252 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) + var dP = __webpack_require__(11); + var gOPD = __webpack_require__(50); + var getPrototypeOf = __webpack_require__(58); + var has = __webpack_require__(5); + var $export = __webpack_require__(8); + var createDesc = __webpack_require__(17); + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + + function set(target, propertyKey, V /* , receiver */) { + var receiver = arguments.length < 4 ? target : arguments[3]; + var ownDesc = gOPD.f(anObject(target), propertyKey); + var existingDescriptor, proto; + if (!ownDesc) { + if (isObject(proto = getPrototypeOf(target))) { + return set(proto, propertyKey, V, receiver); + } + ownDesc = createDesc(0); + } + if (has(ownDesc, 'value')) { + if (ownDesc.writable === false || !isObject(receiver)) return false; + if (existingDescriptor = gOPD.f(receiver, propertyKey)) { + if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false; + existingDescriptor.value = V; + dP.f(receiver, propertyKey, existingDescriptor); + } else dP.f(receiver, propertyKey, createDesc(0, V)); + return true; + } + return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); + } + + $export($export.S, 'Reflect', { set: set }); + + +/***/ }), +/* 253 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.14 Reflect.setPrototypeOf(target, proto) + var $export = __webpack_require__(8); + var setProto = __webpack_require__(72); + + if (setProto) $export($export.S, 'Reflect', { + setPrototypeOf: function setPrototypeOf(target, proto) { + setProto.check(target, proto); + try { + setProto.set(target, proto); + return true; + } catch (e) { + return false; + } + } + }); + + +/***/ }), +/* 254 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/Array.prototype.includes + var $export = __webpack_require__(8); + var $includes = __webpack_require__(36)(true); + + $export($export.P, 'Array', { + includes: function includes(el /* , fromIndex = 0 */) { + return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); + } + }); + + __webpack_require__(187)('includes'); + + +/***/ }), +/* 255 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap + var $export = __webpack_require__(8); + var flattenIntoArray = __webpack_require__(256); + var toObject = __webpack_require__(57); + var toLength = __webpack_require__(37); + var aFunction = __webpack_require__(21); + var arraySpeciesCreate = __webpack_require__(174); + + $export($export.P, 'Array', { + flatMap: function flatMap(callbackfn /* , thisArg */) { + var O = toObject(this); + var sourceLen, A; + aFunction(callbackfn); + sourceLen = toLength(O.length); + A = arraySpeciesCreate(O, 0); + flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments[1]); + return A; + } + }); + + __webpack_require__(187)('flatMap'); + + +/***/ }), +/* 256 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray + var isArray = __webpack_require__(44); + var isObject = __webpack_require__(13); + var toLength = __webpack_require__(37); + var ctx = __webpack_require__(20); + var IS_CONCAT_SPREADABLE = __webpack_require__(26)('isConcatSpreadable'); + + function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) { + var targetIndex = start; + var sourceIndex = 0; + var mapFn = mapper ? ctx(mapper, thisArg, 3) : false; + var element, spreadable; + + while (sourceIndex < sourceLen) { + if (sourceIndex in source) { + element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; + + spreadable = false; + if (isObject(element)) { + spreadable = element[IS_CONCAT_SPREADABLE]; + spreadable = spreadable !== undefined ? !!spreadable : isArray(element); + } + + if (spreadable && depth > 0) { + targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1; + } else { + if (targetIndex >= 0x1fffffffffffff) throw TypeError(); + target[targetIndex] = element; + } + + targetIndex++; + } + sourceIndex++; + } + return targetIndex; + } + + module.exports = flattenIntoArray; + + +/***/ }), +/* 257 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten + var $export = __webpack_require__(8); + var flattenIntoArray = __webpack_require__(256); + var toObject = __webpack_require__(57); + var toLength = __webpack_require__(37); + var toInteger = __webpack_require__(38); + var arraySpeciesCreate = __webpack_require__(174); + + $export($export.P, 'Array', { + flatten: function flatten(/* depthArg = 1 */) { + var depthArg = arguments[0]; + var O = toObject(this); + var sourceLen = toLength(O.length); + var A = arraySpeciesCreate(O, 0); + flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg)); + return A; + } + }); + + __webpack_require__(187)('flatten'); + + +/***/ }), +/* 258 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/mathiasbynens/String.prototype.at + var $export = __webpack_require__(8); + var $at = __webpack_require__(127)(true); + + $export($export.P, 'String', { + at: function at(pos) { + return $at(this, pos); + } + }); + + +/***/ }), +/* 259 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-string-pad-start-end + var $export = __webpack_require__(8); + var $pad = __webpack_require__(260); + var userAgent = __webpack_require__(213); + + // https://github.com/zloirock/core-js/issues/280 + $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { + padStart: function padStart(maxLength /* , fillString = ' ' */) { + return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); + } + }); + + +/***/ }), +/* 260 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-string-pad-start-end + var toLength = __webpack_require__(37); + var repeat = __webpack_require__(90); + var defined = __webpack_require__(35); + + module.exports = function (that, maxLength, fillString, left) { + var S = String(defined(that)); + var stringLength = S.length; + var fillStr = fillString === undefined ? ' ' : String(fillString); + var intMaxLength = toLength(maxLength); + if (intMaxLength <= stringLength || fillStr == '') return S; + var fillLen = intMaxLength - stringLength; + var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); + if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen); + return left ? stringFiller + S : S + stringFiller; + }; + + +/***/ }), +/* 261 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-string-pad-start-end + var $export = __webpack_require__(8); + var $pad = __webpack_require__(260); + var userAgent = __webpack_require__(213); + + // https://github.com/zloirock/core-js/issues/280 + $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { + padEnd: function padEnd(maxLength /* , fillString = ' ' */) { + return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); + } + }); + + +/***/ }), +/* 262 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/sebmarkbage/ecmascript-string-left-right-trim + __webpack_require__(82)('trimLeft', function ($trim) { + return function trimLeft() { + return $trim(this, 1); + }; + }, 'trimStart'); + + +/***/ }), +/* 263 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/sebmarkbage/ecmascript-string-left-right-trim + __webpack_require__(82)('trimRight', function ($trim) { + return function trimRight() { + return $trim(this, 2); + }; + }, 'trimEnd'); + + +/***/ }), +/* 264 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/String.prototype.matchAll/ + var $export = __webpack_require__(8); + var defined = __webpack_require__(35); + var toLength = __webpack_require__(37); + var isRegExp = __webpack_require__(134); + var getFlags = __webpack_require__(197); + var RegExpProto = RegExp.prototype; + + var $RegExpStringIterator = function (regexp, string) { + this._r = regexp; + this._s = string; + }; + + __webpack_require__(130)($RegExpStringIterator, 'RegExp String', function next() { + var match = this._r.exec(this._s); + return { value: match, done: match === null }; + }); + + $export($export.P, 'String', { + matchAll: function matchAll(regexp) { + defined(this); + if (!isRegExp(regexp)) throw TypeError(regexp + ' is not a regexp!'); + var S = String(this); + var flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp); + var rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); + rx.lastIndex = toLength(regexp.lastIndex); + return new $RegExpStringIterator(rx, S); + } + }); + + +/***/ }), +/* 265 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(28)('asyncIterator'); + + +/***/ }), +/* 266 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(28)('observable'); + + +/***/ }), +/* 267 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-getownpropertydescriptors + var $export = __webpack_require__(8); + var ownKeys = __webpack_require__(250); + var toIObject = __webpack_require__(32); + var gOPD = __webpack_require__(50); + var createProperty = __webpack_require__(164); + + $export($export.S, 'Object', { + getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { + var O = toIObject(object); + var getDesc = gOPD.f; + var keys = ownKeys(O); + var result = {}; + var i = 0; + var key, desc; + while (keys.length > i) { + desc = getDesc(O, key = keys[i++]); + if (desc !== undefined) createProperty(result, key, desc); + } + return result; + } + }); + + +/***/ }), +/* 268 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-values-entries + var $export = __webpack_require__(8); + var $values = __webpack_require__(269)(false); + + $export($export.S, 'Object', { + values: function values(it) { + return $values(it); + } + }); + + +/***/ }), +/* 269 */ +/***/ (function(module, exports, __webpack_require__) { + + var getKeys = __webpack_require__(30); + var toIObject = __webpack_require__(32); + var isEnum = __webpack_require__(43).f; + module.exports = function (isEntries) { + return function (it) { + var O = toIObject(it); + var keys = getKeys(O); + var length = keys.length; + var i = 0; + var result = []; + var key; + while (length > i) if (isEnum.call(O, key = keys[i++])) { + result.push(isEntries ? [key, O[key]] : O[key]); + } return result; + }; + }; + + +/***/ }), +/* 270 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-values-entries + var $export = __webpack_require__(8); + var $entries = __webpack_require__(269)(true); + + $export($export.S, 'Object', { + entries: function entries(it) { + return $entries(it); + } + }); + + +/***/ }), +/* 271 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var aFunction = __webpack_require__(21); + var $defineProperty = __webpack_require__(11); + + // B.2.2.2 Object.prototype.__defineGetter__(P, getter) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __defineGetter__: function __defineGetter__(P, getter) { + $defineProperty.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true }); + } + }); + + +/***/ }), +/* 272 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // Forced replacement prototype accessors methods + module.exports = __webpack_require__(24) || !__webpack_require__(7)(function () { + var K = Math.random(); + // In FF throws only define methods + // eslint-disable-next-line no-undef, no-useless-call + __defineSetter__.call(null, K, function () { /* empty */ }); + delete __webpack_require__(4)[K]; + }); + + +/***/ }), +/* 273 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var aFunction = __webpack_require__(21); + var $defineProperty = __webpack_require__(11); + + // B.2.2.3 Object.prototype.__defineSetter__(P, setter) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __defineSetter__: function __defineSetter__(P, setter) { + $defineProperty.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true }); + } + }); + + +/***/ }), +/* 274 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var toPrimitive = __webpack_require__(16); + var getPrototypeOf = __webpack_require__(58); + var getOwnPropertyDescriptor = __webpack_require__(50).f; + + // B.2.2.4 Object.prototype.__lookupGetter__(P) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __lookupGetter__: function __lookupGetter__(P) { + var O = toObject(this); + var K = toPrimitive(P, true); + var D; + do { + if (D = getOwnPropertyDescriptor(O, K)) return D.get; + } while (O = getPrototypeOf(O)); + } + }); + + +/***/ }), +/* 275 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var toPrimitive = __webpack_require__(16); + var getPrototypeOf = __webpack_require__(58); + var getOwnPropertyDescriptor = __webpack_require__(50).f; + + // B.2.2.5 Object.prototype.__lookupSetter__(P) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __lookupSetter__: function __lookupSetter__(P) { + var O = toObject(this); + var K = toPrimitive(P, true); + var D; + do { + if (D = getOwnPropertyDescriptor(O, K)) return D.set; + } while (O = getPrototypeOf(O)); + } + }); + + +/***/ }), +/* 276 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var $export = __webpack_require__(8); + + $export($export.P + $export.R, 'Map', { toJSON: __webpack_require__(277)('Map') }); + + +/***/ }), +/* 277 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var classof = __webpack_require__(74); + var from = __webpack_require__(278); + module.exports = function (NAME) { + return function toJSON() { + if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic"); + return from(this); + }; + }; + + +/***/ }), +/* 278 */ +/***/ (function(module, exports, __webpack_require__) { + + var forOf = __webpack_require__(207); + + module.exports = function (iter, ITERATOR) { + var result = []; + forOf(iter, false, result.push, result, ITERATOR); + return result; + }; + + +/***/ }), +/* 279 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var $export = __webpack_require__(8); + + $export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(277)('Set') }); + + +/***/ }), +/* 280 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-map.of + __webpack_require__(281)('Map'); + + +/***/ }), +/* 281 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-setmap-offrom/ + var $export = __webpack_require__(8); + + module.exports = function (COLLECTION) { + $export($export.S, COLLECTION, { of: function of() { + var length = arguments.length; + var A = new Array(length); + while (length--) A[length] = arguments[length]; + return new this(A); + } }); + }; + + +/***/ }), +/* 282 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-set.of + __webpack_require__(281)('Set'); + + +/***/ }), +/* 283 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of + __webpack_require__(281)('WeakMap'); + + +/***/ }), +/* 284 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of + __webpack_require__(281)('WeakSet'); + + +/***/ }), +/* 285 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-map.from + __webpack_require__(286)('Map'); + + +/***/ }), +/* 286 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-setmap-offrom/ + var $export = __webpack_require__(8); + var aFunction = __webpack_require__(21); + var ctx = __webpack_require__(20); + var forOf = __webpack_require__(207); + + module.exports = function (COLLECTION) { + $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) { + var mapFn = arguments[1]; + var mapping, A, n, cb; + aFunction(this); + mapping = mapFn !== undefined; + if (mapping) aFunction(mapFn); + if (source == undefined) return new this(); + A = []; + if (mapping) { + n = 0; + cb = ctx(mapFn, arguments[2], 2); + forOf(source, false, function (nextItem) { + A.push(cb(nextItem, n++)); + }); + } else { + forOf(source, false, A.push, A); + } + return new this(A); + } }); + }; + + +/***/ }), +/* 287 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-set.from + __webpack_require__(286)('Set'); + + +/***/ }), +/* 288 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from + __webpack_require__(286)('WeakMap'); + + +/***/ }), +/* 289 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from + __webpack_require__(286)('WeakSet'); + + +/***/ }), +/* 290 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-global + var $export = __webpack_require__(8); + + $export($export.G, { global: __webpack_require__(4) }); + + +/***/ }), +/* 291 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-global + var $export = __webpack_require__(8); + + $export($export.S, 'System', { global: __webpack_require__(4) }); + + +/***/ }), +/* 292 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/ljharb/proposal-is-error + var $export = __webpack_require__(8); + var cof = __webpack_require__(34); + + $export($export.S, 'Error', { + isError: function isError(it) { + return cof(it) === 'Error'; + } + }); + + +/***/ }), +/* 293 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + clamp: function clamp(x, lower, upper) { + return Math.min(upper, Math.max(lower, x)); + } + }); + + +/***/ }), +/* 294 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { DEG_PER_RAD: Math.PI / 180 }); + + +/***/ }), +/* 295 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + var RAD_PER_DEG = 180 / Math.PI; + + $export($export.S, 'Math', { + degrees: function degrees(radians) { + return radians * RAD_PER_DEG; + } + }); + + +/***/ }), +/* 296 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + var scale = __webpack_require__(297); + var fround = __webpack_require__(113); + + $export($export.S, 'Math', { + fscale: function fscale(x, inLow, inHigh, outLow, outHigh) { + return fround(scale(x, inLow, inHigh, outLow, outHigh)); + } + }); + + +/***/ }), +/* 297 */ +/***/ (function(module, exports) { + + // https://rwaldron.github.io/proposal-math-extensions/ + module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) { + if ( + arguments.length === 0 + // eslint-disable-next-line no-self-compare + || x != x + // eslint-disable-next-line no-self-compare + || inLow != inLow + // eslint-disable-next-line no-self-compare + || inHigh != inHigh + // eslint-disable-next-line no-self-compare + || outLow != outLow + // eslint-disable-next-line no-self-compare + || outHigh != outHigh + ) return NaN; + if (x === Infinity || x === -Infinity) return x; + return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow; + }; + + +/***/ }), +/* 298 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + iaddh: function iaddh(x0, x1, y0, y1) { + var $x0 = x0 >>> 0; + var $x1 = x1 >>> 0; + var $y0 = y0 >>> 0; + return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; + } + }); + + +/***/ }), +/* 299 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + isubh: function isubh(x0, x1, y0, y1) { + var $x0 = x0 >>> 0; + var $x1 = x1 >>> 0; + var $y0 = y0 >>> 0; + return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; + } + }); + + +/***/ }), +/* 300 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + imulh: function imulh(u, v) { + var UINT16 = 0xffff; + var $u = +u; + var $v = +v; + var u0 = $u & UINT16; + var v0 = $v & UINT16; + var u1 = $u >> 16; + var v1 = $v >> 16; + var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); + return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); + } + }); + + +/***/ }), +/* 301 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { RAD_PER_DEG: 180 / Math.PI }); + + +/***/ }), +/* 302 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + var DEG_PER_RAD = Math.PI / 180; + + $export($export.S, 'Math', { + radians: function radians(degrees) { + return degrees * DEG_PER_RAD; + } + }); + + +/***/ }), +/* 303 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { scale: __webpack_require__(297) }); + + +/***/ }), +/* 304 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + umulh: function umulh(u, v) { + var UINT16 = 0xffff; + var $u = +u; + var $v = +v; + var u0 = $u & UINT16; + var v0 = $v & UINT16; + var u1 = $u >>> 16; + var v1 = $v >>> 16; + var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); + return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); + } + }); + + +/***/ }), +/* 305 */ +/***/ (function(module, exports, __webpack_require__) { + + // http://jfbastien.github.io/papers/Math.signbit.html + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { signbit: function signbit(x) { + // eslint-disable-next-line no-self-compare + return (x = +x) != x ? x : x == 0 ? 1 / x == Infinity : x > 0; + } }); + + +/***/ }), +/* 306 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-promise-finally + 'use strict'; + var $export = __webpack_require__(8); + var core = __webpack_require__(9); + var global = __webpack_require__(4); + var speciesConstructor = __webpack_require__(208); + var promiseResolve = __webpack_require__(214); + + $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { + var C = speciesConstructor(this, core.Promise || global.Promise); + var isFunction = typeof onFinally == 'function'; + return this.then( + isFunction ? function (x) { + return promiseResolve(C, onFinally()).then(function () { return x; }); + } : onFinally, + isFunction ? function (e) { + return promiseResolve(C, onFinally()).then(function () { throw e; }); + } : onFinally + ); + } }); + + +/***/ }), +/* 307 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-promise-try + var $export = __webpack_require__(8); + var newPromiseCapability = __webpack_require__(211); + var perform = __webpack_require__(212); + + $export($export.S, 'Promise', { 'try': function (callbackfn) { + var promiseCapability = newPromiseCapability.f(this); + var result = perform(callbackfn); + (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); + return promiseCapability.promise; + } }); + + +/***/ }), +/* 308 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var toMetaKey = metadata.key; + var ordinaryDefineOwnMetadata = metadata.set; + + metadata.exp({ defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey) { + ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); + } }); + + +/***/ }), +/* 309 */ +/***/ (function(module, exports, __webpack_require__) { + + var Map = __webpack_require__(216); + var $export = __webpack_require__(8); + var shared = __webpack_require__(23)('metadata'); + var store = shared.store || (shared.store = new (__webpack_require__(221))()); + + var getOrCreateMetadataMap = function (target, targetKey, create) { + var targetMetadata = store.get(target); + if (!targetMetadata) { + if (!create) return undefined; + store.set(target, targetMetadata = new Map()); + } + var keyMetadata = targetMetadata.get(targetKey); + if (!keyMetadata) { + if (!create) return undefined; + targetMetadata.set(targetKey, keyMetadata = new Map()); + } return keyMetadata; + }; + var ordinaryHasOwnMetadata = function (MetadataKey, O, P) { + var metadataMap = getOrCreateMetadataMap(O, P, false); + return metadataMap === undefined ? false : metadataMap.has(MetadataKey); + }; + var ordinaryGetOwnMetadata = function (MetadataKey, O, P) { + var metadataMap = getOrCreateMetadataMap(O, P, false); + return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); + }; + var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) { + getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); + }; + var ordinaryOwnMetadataKeys = function (target, targetKey) { + var metadataMap = getOrCreateMetadataMap(target, targetKey, false); + var keys = []; + if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); }); + return keys; + }; + var toMetaKey = function (it) { + return it === undefined || typeof it == 'symbol' ? it : String(it); + }; + var exp = function (O) { + $export($export.S, 'Reflect', O); + }; + + module.exports = { + store: store, + map: getOrCreateMetadataMap, + has: ordinaryHasOwnMetadata, + get: ordinaryGetOwnMetadata, + set: ordinaryDefineOwnMetadata, + keys: ordinaryOwnMetadataKeys, + key: toMetaKey, + exp: exp + }; + + +/***/ }), +/* 310 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var toMetaKey = metadata.key; + var getOrCreateMetadataMap = metadata.map; + var store = metadata.store; + + metadata.exp({ deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) { + var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]); + var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); + if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false; + if (metadataMap.size) return true; + var targetMetadata = store.get(target); + targetMetadata['delete'](targetKey); + return !!targetMetadata.size || store['delete'](target); + } }); + + +/***/ }), +/* 311 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var getPrototypeOf = __webpack_require__(58); + var ordinaryHasOwnMetadata = metadata.has; + var ordinaryGetOwnMetadata = metadata.get; + var toMetaKey = metadata.key; + + var ordinaryGetMetadata = function (MetadataKey, O, P) { + var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P); + var parent = getPrototypeOf(O); + return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; + }; + + metadata.exp({ getMetadata: function getMetadata(metadataKey, target /* , targetKey */) { + return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 312 */ +/***/ (function(module, exports, __webpack_require__) { + + var Set = __webpack_require__(220); + var from = __webpack_require__(278); + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var getPrototypeOf = __webpack_require__(58); + var ordinaryOwnMetadataKeys = metadata.keys; + var toMetaKey = metadata.key; + + var ordinaryMetadataKeys = function (O, P) { + var oKeys = ordinaryOwnMetadataKeys(O, P); + var parent = getPrototypeOf(O); + if (parent === null) return oKeys; + var pKeys = ordinaryMetadataKeys(parent, P); + return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; + }; + + metadata.exp({ getMetadataKeys: function getMetadataKeys(target /* , targetKey */) { + return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); + } }); + + +/***/ }), +/* 313 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var ordinaryGetOwnMetadata = metadata.get; + var toMetaKey = metadata.key; + + metadata.exp({ getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) { + return ordinaryGetOwnMetadata(metadataKey, anObject(target) + , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 314 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var ordinaryOwnMetadataKeys = metadata.keys; + var toMetaKey = metadata.key; + + metadata.exp({ getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) { + return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); + } }); + + +/***/ }), +/* 315 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var getPrototypeOf = __webpack_require__(58); + var ordinaryHasOwnMetadata = metadata.has; + var toMetaKey = metadata.key; + + var ordinaryHasMetadata = function (MetadataKey, O, P) { + var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn) return true; + var parent = getPrototypeOf(O); + return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; + }; + + metadata.exp({ hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) { + return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 316 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var ordinaryHasOwnMetadata = metadata.has; + var toMetaKey = metadata.key; + + metadata.exp({ hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) { + return ordinaryHasOwnMetadata(metadataKey, anObject(target) + , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 317 */ +/***/ (function(module, exports, __webpack_require__) { + + var $metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var aFunction = __webpack_require__(21); + var toMetaKey = $metadata.key; + var ordinaryDefineOwnMetadata = $metadata.set; + + $metadata.exp({ metadata: function metadata(metadataKey, metadataValue) { + return function decorator(target, targetKey) { + ordinaryDefineOwnMetadata( + metadataKey, metadataValue, + (targetKey !== undefined ? anObject : aFunction)(target), + toMetaKey(targetKey) + ); + }; + } }); + + +/***/ }), +/* 318 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask + var $export = __webpack_require__(8); + var microtask = __webpack_require__(210)(); + var process = __webpack_require__(4).process; + var isNode = __webpack_require__(34)(process) == 'process'; + + $export($export.G, { + asap: function asap(fn) { + var domain = isNode && process.domain; + microtask(domain ? domain.bind(fn) : fn); + } + }); + + +/***/ }), +/* 319 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/zenparsing/es-observable + var $export = __webpack_require__(8); + var global = __webpack_require__(4); + var core = __webpack_require__(9); + var microtask = __webpack_require__(210)(); + var OBSERVABLE = __webpack_require__(26)('observable'); + var aFunction = __webpack_require__(21); + var anObject = __webpack_require__(12); + var anInstance = __webpack_require__(206); + var redefineAll = __webpack_require__(215); + var hide = __webpack_require__(10); + var forOf = __webpack_require__(207); + var RETURN = forOf.RETURN; + + var getMethod = function (fn) { + return fn == null ? undefined : aFunction(fn); + }; + + var cleanupSubscription = function (subscription) { + var cleanup = subscription._c; + if (cleanup) { + subscription._c = undefined; + cleanup(); + } + }; + + var subscriptionClosed = function (subscription) { + return subscription._o === undefined; + }; + + var closeSubscription = function (subscription) { + if (!subscriptionClosed(subscription)) { + subscription._o = undefined; + cleanupSubscription(subscription); + } + }; + + var Subscription = function (observer, subscriber) { + anObject(observer); + this._c = undefined; + this._o = observer; + observer = new SubscriptionObserver(this); + try { + var cleanup = subscriber(observer); + var subscription = cleanup; + if (cleanup != null) { + if (typeof cleanup.unsubscribe === 'function') cleanup = function () { subscription.unsubscribe(); }; + else aFunction(cleanup); + this._c = cleanup; + } + } catch (e) { + observer.error(e); + return; + } if (subscriptionClosed(this)) cleanupSubscription(this); + }; + + Subscription.prototype = redefineAll({}, { + unsubscribe: function unsubscribe() { closeSubscription(this); } + }); + + var SubscriptionObserver = function (subscription) { + this._s = subscription; + }; + + SubscriptionObserver.prototype = redefineAll({}, { + next: function next(value) { + var subscription = this._s; + if (!subscriptionClosed(subscription)) { + var observer = subscription._o; + try { + var m = getMethod(observer.next); + if (m) return m.call(observer, value); + } catch (e) { + try { + closeSubscription(subscription); + } finally { + throw e; + } + } + } + }, + error: function error(value) { + var subscription = this._s; + if (subscriptionClosed(subscription)) throw value; + var observer = subscription._o; + subscription._o = undefined; + try { + var m = getMethod(observer.error); + if (!m) throw value; + value = m.call(observer, value); + } catch (e) { + try { + cleanupSubscription(subscription); + } finally { + throw e; + } + } cleanupSubscription(subscription); + return value; + }, + complete: function complete(value) { + var subscription = this._s; + if (!subscriptionClosed(subscription)) { + var observer = subscription._o; + subscription._o = undefined; + try { + var m = getMethod(observer.complete); + value = m ? m.call(observer, value) : undefined; + } catch (e) { + try { + cleanupSubscription(subscription); + } finally { + throw e; + } + } cleanupSubscription(subscription); + return value; + } + } + }); + + var $Observable = function Observable(subscriber) { + anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); + }; + + redefineAll($Observable.prototype, { + subscribe: function subscribe(observer) { + return new Subscription(observer, this._f); + }, + forEach: function forEach(fn) { + var that = this; + return new (core.Promise || global.Promise)(function (resolve, reject) { + aFunction(fn); + var subscription = that.subscribe({ + next: function (value) { + try { + return fn(value); + } catch (e) { + reject(e); + subscription.unsubscribe(); + } + }, + error: reject, + complete: resolve + }); + }); + } + }); + + redefineAll($Observable, { + from: function from(x) { + var C = typeof this === 'function' ? this : $Observable; + var method = getMethod(anObject(x)[OBSERVABLE]); + if (method) { + var observable = anObject(method.call(x)); + return observable.constructor === C ? observable : new C(function (observer) { + return observable.subscribe(observer); + }); + } + return new C(function (observer) { + var done = false; + microtask(function () { + if (!done) { + try { + if (forOf(x, false, function (it) { + observer.next(it); + if (done) return RETURN; + }) === RETURN) return; + } catch (e) { + if (done) throw e; + observer.error(e); + return; + } observer.complete(); + } + }); + return function () { done = true; }; + }); + }, + of: function of() { + for (var i = 0, l = arguments.length, items = new Array(l); i < l;) items[i] = arguments[i++]; + return new (typeof this === 'function' ? this : $Observable)(function (observer) { + var done = false; + microtask(function () { + if (!done) { + for (var j = 0; j < items.length; ++j) { + observer.next(items[j]); + if (done) return; + } observer.complete(); + } + }); + return function () { done = true; }; + }); + } + }); + + hide($Observable.prototype, OBSERVABLE, function () { return this; }); + + $export($export.G, { Observable: $Observable }); + + __webpack_require__(193)('Observable'); + + +/***/ }), +/* 320 */ +/***/ (function(module, exports, __webpack_require__) { + + // ie9- setTimeout & setInterval additional parameters fix + var global = __webpack_require__(4); + var $export = __webpack_require__(8); + var userAgent = __webpack_require__(213); + var slice = [].slice; + var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check + var wrap = function (set) { + return function (fn, time /* , ...args */) { + var boundArgs = arguments.length > 2; + var args = boundArgs ? slice.call(arguments, 2) : false; + return set(boundArgs ? function () { + // eslint-disable-next-line no-new-func + (typeof fn == 'function' ? fn : Function(fn)).apply(this, args); + } : fn, time); + }; + }; + $export($export.G + $export.B + $export.F * MSIE, { + setTimeout: wrap(global.setTimeout), + setInterval: wrap(global.setInterval) + }); + + +/***/ }), +/* 321 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $task = __webpack_require__(209); + $export($export.G + $export.B, { + setImmediate: $task.set, + clearImmediate: $task.clear + }); + + +/***/ }), +/* 322 */ +/***/ (function(module, exports, __webpack_require__) { + + var $iterators = __webpack_require__(194); + var getKeys = __webpack_require__(30); + var redefine = __webpack_require__(18); + var global = __webpack_require__(4); + var hide = __webpack_require__(10); + var Iterators = __webpack_require__(129); + var wks = __webpack_require__(26); + var ITERATOR = wks('iterator'); + var TO_STRING_TAG = wks('toStringTag'); + var ArrayValues = Iterators.Array; + + var DOMIterables = { + CSSRuleList: true, // TODO: Not spec compliant, should be false. + CSSStyleDeclaration: false, + CSSValueList: false, + ClientRectList: false, + DOMRectList: false, + DOMStringList: false, + DOMTokenList: true, + DataTransferItemList: false, + FileList: false, + HTMLAllCollection: false, + HTMLCollection: false, + HTMLFormElement: false, + HTMLSelectElement: false, + MediaList: true, // TODO: Not spec compliant, should be false. + MimeTypeArray: false, + NamedNodeMap: false, + NodeList: true, + PaintRequestList: false, + Plugin: false, + PluginArray: false, + SVGLengthList: false, + SVGNumberList: false, + SVGPathSegList: false, + SVGPointList: false, + SVGStringList: false, + SVGTransformList: false, + SourceBufferList: false, + StyleSheetList: true, // TODO: Not spec compliant, should be false. + TextTrackCueList: false, + TextTrackList: false, + TouchList: false + }; + + for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) { + var NAME = collections[i]; + var explicit = DOMIterables[NAME]; + var Collection = global[NAME]; + var proto = Collection && Collection.prototype; + var key; + if (proto) { + if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues); + if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); + Iterators[NAME] = ArrayValues; + if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true); + } + } + + +/***/ }), +/* 323 */ +/***/ (function(module, exports) { + + /* WEBPACK VAR INJECTION */(function(global) {/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ + + !(function(global) { + "use strict"; + + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + var inModule = typeof module === "object"; + var runtime = global.regeneratorRuntime; + if (runtime) { + if (inModule) { + // If regeneratorRuntime is defined globally and we're in a module, + // make the exports object identical to regeneratorRuntime. + module.exports = runtime; + } + // Don't bother evaluating the rest of this file if the runtime was + // already defined globally. + return; + } + + // Define the runtime globally (as expected by generated code) as either + // module.exports (if we're in a module) or a new, empty object. + runtime = global.regeneratorRuntime = inModule ? module.exports : {}; + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + runtime.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + IteratorPrototype[iteratorSymbol] = function () { + return this; + }; + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunctionPrototype[toStringTagSymbol] = + GeneratorFunction.displayName = "GeneratorFunction"; + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + prototype[method] = function(arg) { + return this._invoke(method, arg); + }; + }); + } + + runtime.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + runtime.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + if (!(toStringTagSymbol in genFun)) { + genFun[toStringTagSymbol] = "GeneratorFunction"; + } + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + runtime.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return Promise.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return Promise.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. If the Promise is rejected, however, the + // result for this iteration will be rejected with the same + // reason. Note that rejections of yielded Promises are not + // thrown back into the generator function, as is the case + // when an awaited Promise is rejected. This difference in + // behavior between yield and await is important, because it + // allows the consumer to decide what to do with the yielded + // rejection (swallow it and continue, manually .throw it back + // into the generator, abandon iteration, whatever). With + // await, by contrast, there is no opportunity to examine the + // rejection reason outside the generator function, so the + // only option is to throw it from the await expression, and + // let the generator function handle the exception. + result.value = unwrapped; + resolve(result); + }, reject); + } + } + + if (typeof global.process === "object" && global.process.domain) { + invoke = global.process.domain.bind(invoke); + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new Promise(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + AsyncIterator.prototype[asyncIteratorSymbol] = function () { + return this; + }; + runtime.AsyncIterator = AsyncIterator; + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + runtime.async = function(innerFn, outerFn, self, tryLocsList) { + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList) + ); + + return runtime.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } + + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + + if (context.method === "throw") { + if (delegate.iterator.return) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; + } + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined; + } + + } else { + // Re-yield the result returned by the delegate method. + return info; + } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + Gp[toStringTagSymbol] = "Generator"; + + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + Gp[iteratorSymbol] = function() { + return this; + }; + + Gp.toString = function() { + return "[object Generator]"; + }; + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + runtime.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + runtime.values = values; + + function doneResult() { + return { value: undefined, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; + + this.method = "next"; + this.arg = undefined; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined; + } + + return !! caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined; + } + + return ContinueSentinel; + } + }; + })( + // Among the various tricks for obtaining a reference to the global + // object, this seems to be the most reliable technique that does not + // use indirect eval (which violates Content Security Policy). + typeof global === "object" ? global : + typeof window === "object" ? window : + typeof self === "object" ? self : this + ); + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 324 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(325); + module.exports = __webpack_require__(9).RegExp.escape; + + +/***/ }), +/* 325 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/benjamingr/RexExp.escape + var $export = __webpack_require__(8); + var $re = __webpack_require__(326)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); + + $export($export.S, 'RegExp', { escape: function escape(it) { return $re(it); } }); + + +/***/ }), +/* 326 */ +/***/ (function(module, exports) { + + module.exports = function (regExp, replace) { + var replacer = replace === Object(replace) ? function (part) { + return replace[part]; + } : replace; + return function (it) { + return String(it).replace(regExp, replacer); + }; + }; + + +/***/ }), +/* 327 */ +/***/ (function(module, exports, __webpack_require__) { + + var BSON = __webpack_require__(328), + Binary = __webpack_require__(350), + Code = __webpack_require__(345), + DBRef = __webpack_require__(349), + Decimal128 = __webpack_require__(346), + Double = __webpack_require__(335), + Int32 = __webpack_require__(344), + Long = __webpack_require__(334), + Map = __webpack_require__(333), + MaxKey = __webpack_require__(348), + MinKey = __webpack_require__(347), + ObjectId = __webpack_require__(337), + BSONRegExp = __webpack_require__(342), + Symbol = __webpack_require__(343), + Timestamp = __webpack_require__(336); + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Add BSON types to function creation + BSON.Binary = Binary; + BSON.Code = Code; + BSON.DBRef = DBRef; + BSON.Decimal128 = Decimal128; + BSON.Double = Double; + BSON.Int32 = Int32; + BSON.Long = Long; + BSON.Map = Map; + BSON.MaxKey = MaxKey; + BSON.MinKey = MinKey; + BSON.ObjectId = ObjectId; + BSON.ObjectID = ObjectId; + BSON.BSONRegExp = BSONRegExp; + BSON.Symbol = Symbol; + BSON.Timestamp = Timestamp; + + // Return the BSON + module.exports = BSON; + +/***/ }), +/* 328 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var Map = __webpack_require__(333), + Long = __webpack_require__(334), + Double = __webpack_require__(335), + Timestamp = __webpack_require__(336), + ObjectID = __webpack_require__(337), + BSONRegExp = __webpack_require__(342), + Symbol = __webpack_require__(343), + Int32 = __webpack_require__(344), + Code = __webpack_require__(345), + Decimal128 = __webpack_require__(346), + MinKey = __webpack_require__(347), + MaxKey = __webpack_require__(348), + DBRef = __webpack_require__(349), + Binary = __webpack_require__(350); + + // Parts of the parser + var deserialize = __webpack_require__(351), + serializer = __webpack_require__(352), + calculateObjectSize = __webpack_require__(355); + + /** + * @ignore + * @api private + */ + // Default Max Size + var MAXSIZE = 1024 * 1024 * 17; + + // Current Internal Temporary Serialization Buffer + var buffer = new Buffer(MAXSIZE); + + var BSON = function () {}; + + /** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ + BSON.prototype.serialize = function serialize(object, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = new Buffer(minInternalBufferSize); + } + + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); + // Create the final buffer + var finishedBuffer = new Buffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; + }; + + /** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + * @api public + */ + BSON.prototype.serializeWithBufferAndIndex = function (object, finalBuffer, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + + // Attempt to serialize + var serializationIndex = serializer(finalBuffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); + + // Return the index + return serializationIndex - 1; + }; + + /** + * Deserialize data as BSON. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ + BSON.prototype.deserialize = function (buffer, options) { + return deserialize(buffer, options); + }; + + /** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ + BSON.prototype.calculateObjectSize = function (object, options) { + options = options || {}; + + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); + }; + + /** + * Deserialize stream data as BSON documents. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ + BSON.prototype.deserializeStream = function (data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = this.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; + }; + + /** + * @ignore + * @api private + */ + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // Return BSON + module.exports = BSON; + module.exports.Code = Code; + module.exports.Map = Map; + module.exports.Symbol = Symbol; + module.exports.BSON = BSON; + module.exports.DBRef = DBRef; + module.exports.Binary = Binary; + module.exports.ObjectID = ObjectID; + module.exports.Long = Long; + module.exports.Timestamp = Timestamp; + module.exports.Double = Double; + module.exports.Int32 = Int32; + module.exports.MinKey = MinKey; + module.exports.MaxKey = MaxKey; + module.exports.BSONRegExp = BSONRegExp; + module.exports.Decimal128 = Decimal128; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) + +/***/ }), +/* 329 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /* eslint-disable no-proto */ + + 'use strict' + + var base64 = __webpack_require__(330) + var ieee754 = __webpack_require__(331) + var isArray = __webpack_require__(332) + + exports.Buffer = Buffer + exports.SlowBuffer = SlowBuffer + exports.INSPECT_MAX_BYTES = 50 + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + + /* + * Export kMaxLength after typed array support is determined. + */ + exports.kMaxLength = kMaxLength() + + function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } + } + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192 // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr + } + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + } + + function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + } + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + } + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that + } + + function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) + } + + Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + } + + Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer + } + + function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + Buffer.byteLength = byteLength + + function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true + + function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this + } + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this + } + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this + } + + Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + } + + Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + } + + Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' + } + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + } + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + } + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + } + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + } + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000 + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf + } + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val + } + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val + } + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] + } + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) + } + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] + } + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + } + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + } + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + } + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + } + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + } + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) + } + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) + } + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) + } + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) + } + + function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 + } + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 + } + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 + } + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 + } + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 + } + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 + } + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 + } + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 + } + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 + } + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 + } + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + } + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + } + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len + } + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this + } + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray + } + + function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 330 */ +/***/ (function(module, exports) { + + 'use strict' + + exports.byteLength = byteLength + exports.toByteArray = toByteArray + exports.fromByteArray = fromByteArray + + var lookup = [] + var revLookup = [] + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i + } + + // Support decoding URL-safe base64 strings, as Node.js does. + // See: https://en.wikipedia.org/wiki/Base64#URL_applications + revLookup['-'.charCodeAt(0)] = 62 + revLookup['_'.charCodeAt(0)] = 63 + + function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] + } + + // base64 is 4/3 + up to two characters of the original data + function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } + + function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } + + function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + for (var i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') + } + + function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk( + uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) + )) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') + } + + +/***/ }), +/* 331 */ +/***/ (function(module, exports) { + + exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 + } + + +/***/ }), +/* 332 */ +/***/ (function(module, exports) { + + var toString = {}.toString; + + module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + +/***/ }), +/* 333 */ +/***/ (function(module, exports) { + + /* WEBPACK VAR INJECTION */(function(global) {'use strict'; + + // We have an ES6 Map available, return the native instance + + if (typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; + } else { + // We will return a polyfill + var Map = function (array) { + this._keys = []; + this._values = {}; + + for (var i = 0; i < array.length; i++) { + if (array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + }; + + Map.prototype.clear = function () { + this._keys = []; + this._values = {}; + }; + + Map.prototype.delete = function (key) { + var value = this._values[key]; + if (value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + + Map.prototype.entries = function () { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.forEach = function (callback, self) { + self = self || this; + + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + + Map.prototype.get = function (key) { + return this._values[key] ? this._values[key].v : undefined; + }; + + Map.prototype.has = function (key) { + return this._values[key] != null; + }; + + Map.prototype.keys = function () { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.set = function (key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + + Map.prototype.values = function () { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable: true, + get: function () { + return this._keys.length; + } + }); + + module.exports = Map; + module.exports.Map = Map; + } + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 334 */ +/***/ (function(module, exports) { + + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + // Copyright 2009 Google Inc. All Rights Reserved + + /** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ + function Long(low, high) { + if (!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. + } + + /** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ + Long.prototype.toInt = function () { + return this.low_; + }; + + /** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ + Long.prototype.toNumber = function () { + return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); + }; + + /** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ + Long.prototype.toJSON = function () { + return this.toString(); + }; + + /** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ + Long.prototype.toString = function (opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } + }; + + /** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ + Long.prototype.getHighBits = function () { + return this.high_; + }; + + /** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ + Long.prototype.getLowBits = function () { + return this.low_; + }; + + /** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ + Long.prototype.getLowBitsUnsigned = function () { + return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; + }; + + /** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ + Long.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & 1 << bit) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } + }; + + /** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ + Long.prototype.isZero = function () { + return this.high_ === 0 && this.low_ === 0; + }; + + /** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ + Long.prototype.isNegative = function () { + return this.high_ < 0; + }; + + /** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ + Long.prototype.isOdd = function () { + return (this.low_ & 1) === 1; + }; + + /** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ + Long.prototype.equals = function (other) { + return this.high_ === other.high_ && this.low_ === other.low_; + }; + + /** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ + Long.prototype.notEquals = function (other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; + }; + + /** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ + Long.prototype.lessThan = function (other) { + return this.compare(other) < 0; + }; + + /** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ + Long.prototype.lessThanOrEqual = function (other) { + return this.compare(other) <= 0; + }; + + /** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ + Long.prototype.greaterThan = function (other) { + return this.compare(other) > 0; + }; + + /** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ + Long.prototype.greaterThanOrEqual = function (other) { + return this.compare(other) >= 0; + }; + + /** + * Compares this Long with the given one. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ + Long.prototype.compare = function (other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } + }; + + /** + * The negation of this value. + * + * @method + * @return {Long} the negation of this value. + */ + Long.prototype.negate = function () { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } + }; + + /** + * Returns the sum of this and the given Long. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ + Long.prototype.add = function (other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns the difference of this and the given Long. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ + Long.prototype.subtract = function (other) { + return this.add(other.negate()); + }; + + /** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ + Long.prototype.multiply = function (other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns this Long divided by the given one. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ + Long.prototype.div = function (other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; + }; + + /** + * Returns this Long modulo the given one. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ + Long.prototype.modulo = function (other) { + return this.subtract(this.div(other).multiply(other)); + }; + + /** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ + Long.prototype.not = function () { + return Long.fromBits(~this.low_, ~this.high_); + }; + + /** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ + Long.prototype.and = function (other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); + }; + + /** + * Returns the bitwise-OR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ + Long.prototype.or = function (other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); + }; + + /** + * Returns the bitwise-XOR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ + Long.prototype.xor = function (other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); + }; + + /** + * Returns this Long with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ + Long.prototype.shiftLeft = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); + } else { + return Long.fromBits(0, low << numBits - 32); + } + } + }; + + /** + * Returns this Long with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ + Long.prototype.shiftRight = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); + } else { + return Long.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); + } + } + }; + + /** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ + Long.prototype.shiftRightUnsigned = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); + } else if (numBits === 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> numBits - 32, 0); + } + } + }; + + /** + * Returns a Long representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ + Long.fromInt = function (value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; + }; + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ + Long.fromNumber = function (value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long(value % Long.TWO_PWR_32_DBL_ | 0, value / Long.TWO_PWR_32_DBL_ | 0); + } + }; + + /** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ + Long.fromBits = function (lowBits, highBits) { + return new Long(lowBits, highBits); + }; + + /** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Long. + * @param {number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + */ + Long.fromString = function (str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; + }; + + // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the + // from* methods on which they depend. + + /** + * A cache of the Long representations of small integer values. + * @type {Object} + * @ignore + */ + Long.INT_CACHE_ = {}; + + // NOTE: the compiler should inline these constant values below and then remove + // these variables, so there should be no runtime penalty for these. + + /** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ + Long.TWO_PWR_16_DBL_ = 1 << 16; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_24_DBL_ = 1 << 24; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + + /** @type {Long} */ + Long.ZERO = Long.fromInt(0); + + /** @type {Long} */ + Long.ONE = Long.fromInt(1); + + /** @type {Long} */ + Long.NEG_ONE = Long.fromInt(-1); + + /** @type {Long} */ + Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); + + /** @type {Long} */ + Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + + /** + * @type {Long} + * @ignore + */ + Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + + /** + * Expose. + */ + module.exports = Long; + module.exports.Long = Long; + +/***/ }), +/* 335 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON Double type. + * + * @class + * @param {number} value the number we want to represent as a double. + * @return {Double} + */ + function Double(value) { + if (!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; + } + + /** + * Access the number value. + * + * @method + * @return {number} returns the wrapped double number. + */ + Double.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Double.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Double; + module.exports.Double = Double; + +/***/ }), +/* 336 */ +/***/ (function(module, exports) { + + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + // Copyright 2009 Google Inc. All Rights Reserved + + /** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Timestamp. + * @param {number} high the high (signed) 32 bits of the Timestamp. + */ + function Timestamp(low, high) { + if (!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. + } + + /** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ + Timestamp.prototype.toInt = function () { + return this.low_; + }; + + /** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ + Timestamp.prototype.toNumber = function () { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); + }; + + /** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ + Timestamp.prototype.toJSON = function () { + return this.toString(); + }; + + /** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ + Timestamp.prototype.toString = function (opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } + }; + + /** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ + Timestamp.prototype.getHighBits = function () { + return this.high_; + }; + + /** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ + Timestamp.prototype.getLowBits = function () { + return this.low_; + }; + + /** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ + Timestamp.prototype.getLowBitsUnsigned = function () { + return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; + }; + + /** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ + Timestamp.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & 1 << bit) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } + }; + + /** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ + Timestamp.prototype.isZero = function () { + return this.high_ === 0 && this.low_ === 0; + }; + + /** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ + Timestamp.prototype.isNegative = function () { + return this.high_ < 0; + }; + + /** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ + Timestamp.prototype.isOdd = function () { + return (this.low_ & 1) === 1; + }; + + /** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ + Timestamp.prototype.equals = function (other) { + return this.high_ === other.high_ && this.low_ === other.low_; + }; + + /** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ + Timestamp.prototype.notEquals = function (other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; + }; + + /** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ + Timestamp.prototype.lessThan = function (other) { + return this.compare(other) < 0; + }; + + /** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ + Timestamp.prototype.lessThanOrEqual = function (other) { + return this.compare(other) <= 0; + }; + + /** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ + Timestamp.prototype.greaterThan = function (other) { + return this.compare(other) > 0; + }; + + /** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ + Timestamp.prototype.greaterThanOrEqual = function (other) { + return this.compare(other) >= 0; + }; + + /** + * Compares this Timestamp with the given one. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ + Timestamp.prototype.compare = function (other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } + }; + + /** + * The negation of this value. + * + * @method + * @return {Timestamp} the negation of this value. + */ + Timestamp.prototype.negate = function () { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } + }; + + /** + * Returns the sum of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ + Timestamp.prototype.add = function (other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns the difference of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ + Timestamp.prototype.subtract = function (other) { + return this.add(other.negate()); + }; + + /** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ + Timestamp.prototype.multiply = function (other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns this Timestamp divided by the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ + Timestamp.prototype.div = function (other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; + }; + + /** + * Returns this Timestamp modulo the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ + Timestamp.prototype.modulo = function (other) { + return this.subtract(this.div(other).multiply(other)); + }; + + /** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ + Timestamp.prototype.not = function () { + return Timestamp.fromBits(~this.low_, ~this.high_); + }; + + /** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ + Timestamp.prototype.and = function (other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); + }; + + /** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ + Timestamp.prototype.or = function (other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); + }; + + /** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ + Timestamp.prototype.xor = function (other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); + }; + + /** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ + Timestamp.prototype.shiftLeft = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); + } else { + return Timestamp.fromBits(0, low << numBits - 32); + } + } + }; + + /** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ + Timestamp.prototype.shiftRight = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); + } else { + return Timestamp.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); + } + } + }; + + /** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ + Timestamp.prototype.shiftRightUnsigned = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); + } else if (numBits === 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> numBits - 32, 0); + } + } + }; + + /** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromInt = function (value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; + }; + + /** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromNumber = function (value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp(value % Timestamp.TWO_PWR_32_DBL_ | 0, value / Timestamp.TWO_PWR_32_DBL_ | 0); + } + }; + + /** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromBits = function (lowBits, highBits) { + return new Timestamp(lowBits, highBits); + }; + + /** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Timestamp. + * @param {number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromString = function (str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; + }; + + // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the + // from* methods on which they depend. + + /** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @ignore + */ + Timestamp.INT_CACHE_ = {}; + + // NOTE: the compiler should inline these constant values below and then remove + // these variables, so there should be no runtime penalty for these. + + /** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + + /** @type {Timestamp} */ + Timestamp.ZERO = Timestamp.fromInt(0); + + /** @type {Timestamp} */ + Timestamp.ONE = Timestamp.fromInt(1); + + /** @type {Timestamp} */ + Timestamp.NEG_ONE = Timestamp.fromInt(-1); + + /** @type {Timestamp} */ + Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); + + /** @type {Timestamp} */ + Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + + /** + * @type {Timestamp} + * @ignore + */ + Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + + /** + * Expose. + */ + module.exports = Timestamp; + module.exports.Timestamp = Timestamp; + +/***/ }), +/* 337 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer, process) {// Custom inspect property name / symbol. + var inspect = 'inspect'; + + /** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + * @ignore + */ + var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); + + // Regular expression that checks for hex value + var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + + // Check if buffer exists + try { + if (Buffer && Buffer.from) { + var hasBufferType = true; + inspect = __webpack_require__(339).inspect.custom || 'inspect'; + } + } catch (err) { + hasBufferType = false; + } + + /** + * Create a new ObjectID instance + * + * @class + * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. + * @property {number} generationTime The generation time of this ObjectId instance + * @return {ObjectID} instance of ObjectID. + */ + var ObjectID = function ObjectID(id) { + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectID) return id; + if (!(this instanceof ObjectID)) return new ObjectID(id); + + this._bsontype = 'ObjectID'; + + // The most common usecase (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this.id = this.generate(id); + // If we are caching the hex string + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); + // Return the object + return; + } + + // Check if the passed in id is valid + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if (!valid && id != null) { + throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { + return new ObjectID(new Buffer(id, 'hex')); + } else if (valid && typeof id === 'string' && id.length === 24) { + return ObjectID.createFromHexString(id); + } else if (id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } else if (id != null && id.toHexString) { + // Duck-typing to support ObjectId from different npm packages + return id; + } else { + throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); + }; + + // Allow usage of ObjectId as well as ObjectID + // var ObjectId = ObjectID; + + // Precomputed hex table enables speedy hex string conversion + var hexTable = []; + for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); + } + + /** + * Return the ObjectID id as a 24 byte hex string representation + * + * @method + * @return {string} return the 24 byte hex string representation. + */ + ObjectID.prototype.toHexString = function () { + if (ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + if (!this.id || !this.id.length) { + throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']'); + } + + if (this.id instanceof _Buffer) { + hexString = convertToHex(this.id); + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + } + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + }; + + /** + * Update the ObjectID index used in generating new ObjectID's on the driver + * + * @method + * @return {number} returns next index value. + * @ignore + */ + ObjectID.prototype.get_inc = function () { + return ObjectID.index = (ObjectID.index + 1) % 0xffffff; + }; + + /** + * Update the ObjectID index used in generating new ObjectID's on the driver + * + * @method + * @return {number} returns next index value. + * @ignore + */ + ObjectID.prototype.getInc = function () { + return this.get_inc(); + }; + + /** + * Generate a 12 byte id buffer used in ObjectID's + * + * @method + * @param {number} [time] optional parameter allowing to pass in a second based timestamp. + * @return {Buffer} return the 12 byte id buffer string. + */ + ObjectID.prototype.generate = function (time) { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + + // Use pid + var pid = (typeof process === 'undefined' || process.pid === 1 ? Math.floor(Math.random() * 100000) : process.pid) % 0xffff; + var inc = this.get_inc(); + // Buffer used + var buffer = new Buffer(12); + // Encode time + buffer[3] = time & 0xff; + buffer[2] = time >> 8 & 0xff; + buffer[1] = time >> 16 & 0xff; + buffer[0] = time >> 24 & 0xff; + // Encode machine + buffer[6] = MACHINE_ID & 0xff; + buffer[5] = MACHINE_ID >> 8 & 0xff; + buffer[4] = MACHINE_ID >> 16 & 0xff; + // Encode pid + buffer[8] = pid & 0xff; + buffer[7] = pid >> 8 & 0xff; + // Encode index + buffer[11] = inc & 0xff; + buffer[10] = inc >> 8 & 0xff; + buffer[9] = inc >> 16 & 0xff; + // Return the buffer + return buffer; + }; + + /** + * Converts the id into a 24 byte hex string for printing + * + * @param {String} format The Buffer toString format parameter. + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype.toString = function (format) { + // Is the id a buffer then use the buffer toString method to return the format + if (this.id && this.id.copy) { + return this.id.toString(typeof format === 'string' ? format : 'hex'); + } + + // if(this.buffer ) + return this.toHexString(); + }; + + /** + * Converts to a string representation of this Id. + * + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype[inspect] = ObjectID.prototype.toString; + + /** + * Converts to its JSON representation. + * + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype.toJSON = function () { + return this.toHexString(); + }; + + /** + * Compares the equality of this ObjectID with `otherID`. + * + * @method + * @param {object} otherID ObjectID instance to compare against. + * @return {boolean} the result of comparing two ObjectID's + */ + ObjectID.prototype.equals = function equals(otherId) { + // var id; + + if (otherId instanceof ObjectID) { + return this.toString() === otherId.toString(); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12 && this.id instanceof _Buffer) { + return otherId === this.id.toString('binary'); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { + return otherId === this.id; + } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { + return otherId.toHexString() === this.toHexString(); + } else { + return false; + } + }; + + /** + * Returns the generation date (accurate up to the second) that this ID was generated. + * + * @method + * @return {date} the generation date + */ + ObjectID.prototype.getTimestamp = function () { + var timestamp = new Date(); + var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + }; + + /** + * @ignore + */ + ObjectID.index = ~~(Math.random() * 0xffffff); + + /** + * @ignore + */ + ObjectID.createPk = function createPk() { + return new ObjectID(); + }; + + /** + * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. + * + * @method + * @param {number} time an integer number representing a number of seconds. + * @return {ObjectID} return the created ObjectID + */ + ObjectID.createFromTime = function createFromTime(time) { + var buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer[3] = time & 0xff; + buffer[2] = time >> 8 & 0xff; + buffer[1] = time >> 16 & 0xff; + buffer[0] = time >> 24 & 0xff; + // Return the new objectId + return new ObjectID(buffer); + }; + + // Lookup tables + //var encodeLookup = '0123456789abcdef'.split(''); + var decodeLookup = []; + i = 0; + while (i < 10) decodeLookup[0x30 + i] = i++; + while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; + + var _Buffer = Buffer; + var convertToHex = function (bytes) { + return bytes.toString('hex'); + }; + + /** + * Creates an ObjectID from a hex string representation of an ObjectID. + * + * @method + * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. + * @return {ObjectID} return the created ObjectID + */ + ObjectID.createFromHexString = function createFromHexString(string) { + // Throw an error if it's not a valid setup + if (typeof string === 'undefined' || string != null && string.length !== 24) { + throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + + // Use Buffer.from method if available + if (hasBufferType) return new ObjectID(new Buffer(string, 'hex')); + + // Calculate lengths + var array = new _Buffer(12); + var n = 0; + var i = 0; + + while (i < 24) { + array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]; + } + + return new ObjectID(array); + }; + + /** + * Checks if a value is a valid bson ObjectId + * + * @method + * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. + */ + ObjectID.isValid = function isValid(id) { + if (id == null) return false; + + if (typeof id === 'number') { + return true; + } + + if (typeof id === 'string') { + return id.length === 12 || id.length === 24 && checkForHexRegExp.test(id); + } + + if (id instanceof ObjectID) { + return true; + } + + if (id instanceof _Buffer) { + return true; + } + + // Duck-Typing detection of ObjectId like objects + if (id.toHexString) { + return id.id.length === 12 || id.id.length === 24 && checkForHexRegExp.test(id.id); + } + + return false; + }; + + /** + * @ignore + */ + Object.defineProperty(ObjectID.prototype, 'generationTime', { + enumerable: true, + get: function () { + return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; + }, + set: function (value) { + // Encode time into first 4 bytes + this.id[3] = value & 0xff; + this.id[2] = value >> 8 & 0xff; + this.id[1] = value >> 16 & 0xff; + this.id[0] = value >> 24 & 0xff; + } + }); + + /** + * Expose. + */ + module.exports = ObjectID; + module.exports.ObjectID = ObjectID; + module.exports.ObjectId = ObjectID; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer, __webpack_require__(338))) + +/***/ }), +/* 338 */ +/***/ (function(module, exports) { + + // shim for using process in browser + var process = module.exports = {}; + + // cached from whatever global is present so that test runners that stub it + // don't break things. But we need to wrap it in a try catch in case it is + // wrapped in strict mode code which doesn't define any globals. It's inside a + // function because try/catches deoptimize in certain engines. + + var cachedSetTimeout; + var cachedClearTimeout; + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + (function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + } ()) + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + + process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + process.title = 'browser'; + process.browser = true; + process.env = {}; + process.argv = []; + process.version = ''; // empty string to avoid regexp issues + process.versions = {}; + + function noop() {} + + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + process.prependListener = noop; + process.prependOnceListener = noop; + + process.listeners = function (name) { return [] } + + process.binding = function (name) { + throw new Error('process.binding is not supported'); + }; + + process.cwd = function () { return '/' }; + process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); + }; + process.umask = function() { return 0; }; + + +/***/ }), +/* 339 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var formatRegExp = /%[sdj%]/g; + exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + }; + + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + }; + + + var debugs = {}; + var debugEnviron; + exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + }; + + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + exports.inspect = inspect; + + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + exports.isArray = isArray; + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + exports.isBoolean = isBoolean; + + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + + function isNumber(arg) { + return typeof arg === 'number'; + } + exports.isNumber = isNumber; + + function isString(arg) { + return typeof arg === 'string'; + } + exports.isString = isString; + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + exports.isSymbol = isSymbol; + + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + exports.isRegExp = isRegExp; + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + exports.isObject = isObject; + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + exports.isDate = isDate; + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + exports.isError = isError; + + function isFunction(arg) { + return typeof arg === 'function'; + } + exports.isFunction = isFunction; + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + exports.isPrimitive = isPrimitive; + + exports.isBuffer = __webpack_require__(340); + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); + }; + + + /** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ + exports.inherits = __webpack_require__(341); + + exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + }; + + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(338))) + +/***/ }), +/* 340 */ +/***/ (function(module, exports) { + + module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; + } + +/***/ }), +/* 341 */ +/***/ (function(module, exports) { + + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } + + +/***/ }), +/* 342 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ + function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern || ''; + this.options = options || ''; + + // Validate options + for (var i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || this.options[i] === 'm' || this.options[i] === 'x' || this.options[i] === 'l' || this.options[i] === 's' || this.options[i] === 'u')) { + throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); + } + } + } + + module.exports = BSONRegExp; + module.exports.BSONRegExp = BSONRegExp; + +/***/ }), +/* 343 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {// Custom inspect property name / symbol. + var inspect = Buffer ? __webpack_require__(339).inspect.custom || 'inspect' : 'inspect'; + + /** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @param {string} value the string representing the symbol. + * @return {Symbol} + */ + function Symbol(value) { + if (!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; + } + + /** + * Access the wrapped string value. + * + * @method + * @return {String} returns the wrapped string. + */ + Symbol.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype.toString = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype[inspect] = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Symbol; + module.exports.Symbol = Symbol; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) + +/***/ }), +/* 344 */ +/***/ (function(module, exports) { + + /** + * A class representation of a BSON Int32 type. + * + * @class + * @param {number} value the number we want to represent as an int32. + * @return {Int32} + */ + var Int32 = function (value) { + if (!(this instanceof Int32)) return new Int32(value); + + this._bsontype = 'Int32'; + this.value = value; + }; + + /** + * Access the number value. + * + * @method + * @return {number} returns the wrapped int32 number. + */ + Int32.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Int32.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Int32; + module.exports.Int32 = Int32; + +/***/ }), +/* 345 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ + var Code = function Code(code, scope) { + if (!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope; + }; + + /** + * @ignore + */ + Code.prototype.toJSON = function () { + return { scope: this.scope, code: this.code }; + }; + + module.exports = Code; + module.exports.Code = Code; + +/***/ }), +/* 346 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var Long = __webpack_require__(334); + + var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; + var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; + var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + + var EXPONENT_MAX = 6111; + var EXPONENT_MIN = -6176; + var EXPONENT_BIAS = 6176; + var MAX_DIGITS = 34; + + // Nan value bits as 32 bit values (due to lack of longs) + var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + // Infinity value bits 32 bit values (due to lack of longs) + var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + + var EXPONENT_REGEX = /^([-+])?(\d+)?$/; + + // Detect if the value is a digit + var isDigit = function (value) { + return !isNaN(parseInt(value, 10)); + }; + + // Divide two uint128 values + var divideu128 = function (value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + var i = 0; + + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for (i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low_; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; + }; + + // Multiply two Long values and return the 128 bit value + var multiply64x2 = function (left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return { high: productHigh, low: productLow }; + }; + + var lessThan = function (left, right) { + // Make values unsigned + var uhleft = left.high_ >>> 0; + var uhright = right.high_ >>> 0; + + // Compare high bits first + if (uhleft < uhright) { + return true; + } else if (uhleft === uhright) { + var ulleft = left.low_ >>> 0; + var ulright = right.low_ >>> 0; + if (ulleft < ulright) return true; + } + + return false; + }; + + // var longtoHex = function(value) { + // var buffer = new Buffer(8); + // var index = 0; + // // Encode the low 64 bits of the decimal + // // Encode low bits + // buffer[index++] = value.low_ & 0xff; + // buffer[index++] = (value.low_ >> 8) & 0xff; + // buffer[index++] = (value.low_ >> 16) & 0xff; + // buffer[index++] = (value.low_ >> 24) & 0xff; + // // Encode high bits + // buffer[index++] = value.high_ & 0xff; + // buffer[index++] = (value.high_ >> 8) & 0xff; + // buffer[index++] = (value.high_ >> 16) & 0xff; + // buffer[index++] = (value.high_ >> 24) & 0xff; + // return buffer.reverse().toString('hex'); + // }; + + // var int32toHex = function(value) { + // var buffer = new Buffer(4); + // var index = 0; + // // Encode the low 64 bits of the decimal + // // Encode low bits + // buffer[index++] = value & 0xff; + // buffer[index++] = (value >> 8) & 0xff; + // buffer[index++] = (value >> 16) & 0xff; + // buffer[index++] = (value >> 24) & 0xff; + // return buffer.reverse().toString('hex'); + // }; + + /** + * A class representation of the BSON Decimal128 type. + * + * @class + * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. + * @return {Double} + */ + var Decimal128 = function (bytes) { + this._bsontype = 'Decimal128'; + this.bytes = bytes; + }; + + /** + * Create a Decimal128 instance from a string representation + * + * @method + * @param {string} string a numeric string representation. + * @return {Decimal128} returns a Decimal128 instance. + */ + Decimal128.fromString = function (string) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = [0, 0]; + // The low 17 digits of the significand + var significandLow = [0, 0]; + // The biased exponent + var biasedExponent = 0; + + // Read index + var index = 0; + + // Trim the string + string = string.trim(); + + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (string.length >= 7000) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Results + var stringMatch = string.match(PARSE_STRING_REGEXP); + var infMatch = string.match(PARSE_INF_REGEXP); + var nanMatch = string.match(PARSE_NAN_REGEXP); + + // Validate the string + if (!stringMatch && !infMatch && !nanMatch || string.length === 0) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Check if we have an illegal exponent format + if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Get the negative or positive sign + if (string[index] === '+' || string[index] === '-') { + isNegative = string[index++] === '-'; + } + + // Check if user passed Infinity or NaN + if (!isDigit(string[index]) && string[index] !== '.') { + if (string[index] === 'i' || string[index] === 'I') { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } else if (string[index] === 'N') { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + } + + // Read all the digits + while (isDigit(string[index]) || string[index] === '.') { + if (string[index] === '.') { + if (sawRadix) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + sawRadix = true; + index = index + 1; + continue; + } + + if (nDigitsStored < 34) { + if (string[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(string[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if (foundNonZero) { + nDigits = nDigits + 1; + } + + if (sawRadix) { + radixPosition = radixPosition + 1; + } + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if (sawRadix && !nDigitsRead) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Read exponent if exists + if (string[index] === 'e' || string[index] === 'E') { + // Read exponent digits + var match = string.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if (!match || !match[2]) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if (string[index]) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + + if (exponent !== 0 && significantDigits !== 1) { + while (string[firstNonZero + significantDigits - 1] === '0') { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + + exponent = exponent - 1; + } + + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit + if (lastDigit === 0) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { + var endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix && exponent === EXPONENT_MIN) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + + if (roundDigit >= 5) { + roundBit = 1; + + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1; + + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(string[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if (roundBit) { + var dIdx = lastDigit; + + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } else { + break; + } + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit - firstDigit < 17) { + dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + + significand.low = significand.low.add(significandLow); + + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber)) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + var buffer = new Buffer(16); + index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low_ & 0xff; + buffer[index++] = dec.low.low_ >> 8 & 0xff; + buffer[index++] = dec.low.low_ >> 16 & 0xff; + buffer[index++] = dec.low.low_ >> 24 & 0xff; + // Encode high bits + buffer[index++] = dec.low.high_ & 0xff; + buffer[index++] = dec.low.high_ >> 8 & 0xff; + buffer[index++] = dec.low.high_ >> 16 & 0xff; + buffer[index++] = dec.low.high_ >> 24 & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low_ & 0xff; + buffer[index++] = dec.high.low_ >> 8 & 0xff; + buffer[index++] = dec.high.low_ >> 16 & 0xff; + buffer[index++] = dec.high.low_ >> 24 & 0xff; + // Encode high bits + buffer[index++] = dec.high.high_ & 0xff; + buffer[index++] = dec.high.high_ >> 8 & 0xff; + buffer[index++] = dec.high.high_ >> 16 & 0xff; + buffer[index++] = dec.high.high_ >> 24 & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); + }; + + // Extract least significant 5 bits + var COMBINATION_MASK = 0x1f; + // Extract least significant 14 bits + var EXPONENT_MASK = 0x3fff; + // Value of combination field for Inf + var COMBINATION_INFINITY = 30; + // Value of combination field for NaN + var COMBINATION_NAN = 31; + // Value of combination field for NaN + // var COMBINATION_SNAN = 32; + // decimal128 exponent bias + EXPONENT_BIAS = 6176; + + /** + * Create a string representation of the raw Decimal128 value + * + * @method + * @return {string} returns a Decimal128 string representation. + */ + Decimal128.prototype.toString = function () { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // bits 0 - 31 + var high; + // bits 32 - 63 + var midh; + // bits 64 - 95 + var midl; + // bits 96 - 127 + var low; + // bits 1 - 5 + var combination; + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + var index = 0; + + // unbiased exponent + var exponent; + // the exponent if scientific notation is used + var scientific_exponent; + + // true if the number is zero + var is_zero = false; + + // the most signifcant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: new Array(4) }; + // indexing variables + i; + var j, k; + + // Output string + var string = []; + + // Unpack index + index = 0; + + // Buffer reference + var buffer = this.bytes; + + // Unpack the low 64bits into a long + low = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + midl = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Unpack the high 64bits into a long + midh = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + high = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Unpack index + index = 0; + + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + combination = high >> 26 & COMBINATION_MASK; + + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } else if (combination === COMBINATION_NAN) { + return 'NaN'; + } else { + biased_exponent = high >> 15 & EXPONENT_MASK; + significand_msb = 0x08 + (high >> 14 & 0x01); + } + } else { + significand_msb = high >> 14 & 0x07; + biased_exponent = high >> 17 & EXPONENT_MASK; + } + + exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) { + is_zero = true; + } else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Peform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low_; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) continue; + + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + i = 0; + + while (!significand[index]) { + i++; + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + string.push(significand[index++]); + significand_digits = significand_digits - 1; + + if (significand_digits) { + string.push('.'); + } + + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } else { + string.push(scientific_exponent); + } + } else { + // Regular format with no decimal place + if (exponent >= 0) { + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + } else { + var radix_position = significand_digits + exponent; + + // non-zero digits before radix + if (radix_position > 0) { + for (i = 0; i < radix_position; i++) { + string.push(significand[index++]); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + + for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(significand[index++]); + } + } + } + + return string.join(''); + }; + + Decimal128.prototype.toJSON = function () { + return { $numberDecimal: this.toString() }; + }; + + module.exports = Decimal128; + module.exports.Decimal128 = Decimal128; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) + +/***/ }), +/* 347 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ + function MinKey() { + if (!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; + } + + module.exports = MinKey; + module.exports.MinKey = MinKey; + +/***/ }), +/* 348 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ + function MaxKey() { + if (!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; + } + + module.exports = MaxKey; + module.exports.MaxKey = MaxKey; + +/***/ }), +/* 349 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON DBRef type. + * + * @class + * @param {string} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {string} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ + function DBRef(namespace, oid, db) { + if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; + } + + /** + * @ignore + * @api private + */ + DBRef.prototype.toJSON = function () { + return { + $ref: this.namespace, + $id: this.oid, + $db: this.db == null ? '' : this.db + }; + }; + + module.exports = DBRef; + module.exports.DBRef = DBRef; + +/***/ }), +/* 350 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {/** + * Module dependencies. + * @ignore + */ + + // Test if we're in Node via presence of "global" not absence of "window" + // to support hybrid environments like Electron + if (typeof global !== 'undefined') { + var Buffer = __webpack_require__(329).Buffer; // TODO just use global Buffer + } + + /** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ + function Binary(buffer, subType) { + if (!(this instanceof Binary)) return new Binary(buffer, subType); + + if (buffer != null && !(typeof buffer === 'string') && !Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array) && !Array.isArray(buffer)) { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + + this._bsontype = 'Binary'; + + if (buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if (buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if (typeof buffer === 'string') { + // Different ways of writing the length of the string for the different types + if (typeof Buffer !== 'undefined') { + this.buffer = new Buffer(buffer); + } else if (typeof Uint8Array !== 'undefined' || Object.prototype.toString.call(buffer) === '[object Array]') { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if (typeof Buffer !== 'undefined') { + this.buffer = new Buffer(Binary.BUFFER_SIZE); + } else if (typeof Uint8Array !== 'undefined') { + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } + } + + /** + * Updates this binary with byte_value. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ + Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) throw new Error('only accepts single character String, Uint8Array or Array'); + if (typeof byte_value !== 'number' && byte_value < 0 || byte_value > 255) throw new Error('only accepts number in a valid unsigned byte range 0-255'); + + // Decode the byte value once + var decoded_byte = null; + if (typeof byte_value === 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if (byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + buffer = null; + // Create a new buffer (typed or normal array) + if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for (var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } + }; + + /** + * Writes a buffer or string to the binary. + * + * @method + * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. + * @param {number} offset specify the binary of where to write the content. + * @return {null} + */ + Binary.prototype.write = function write(string, offset) { + offset = typeof offset === 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = new Buffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); + // Copy the content + for (var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length + } else if (typeof Buffer !== 'undefined' && typeof string === 'string' && Buffer.isBuffer(this.buffer)) { + this.buffer.write(string, offset, 'binary'); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length; + } else if (Object.prototype.toString.call(string) === '[object Uint8Array]' || Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if (typeof string === 'string') { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } + }; + + /** + * Reads **length** bytes starting at **position**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ + Binary.prototype.read = function read(position, length) { + length = length && length > 0 ? length : this.position; + + // Let's return the data based on the type we have + if (this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); + for (var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; + }; + + /** + * Returns the value of this binary as a string. + * + * @method + * @return {string} + */ + Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length === this.position) return this.buffer; + + // If it's a node.js buffer object + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); + } else { + if (asRaw) { + // we support the slice command use it + if (this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); + // Copy content + for (var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } + }; + + /** + * Length. + * + * @method + * @return {number} the length of the binary. + */ + Binary.prototype.length = function length() { + return this.position; + }; + + /** + * @ignore + */ + Binary.prototype.toJSON = function () { + return this.buffer != null ? this.buffer.toString('base64') : ''; + }; + + /** + * @ignore + */ + Binary.prototype.toString = function (format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; + }; + + /** + * Binary default subtype + * @ignore + */ + var BSON_BINARY_SUBTYPE_DEFAULT = 0; + + /** + * @ignore + */ + var writeStringToArray = function (data) { + // Create a buffer + var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); + // Write the content to the buffer + for (var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; + }; + + /** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + */ + var convertArraytoUtf8BinaryString = function (byteArray, startIndex, endIndex) { + var result = ''; + for (var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; + }; + + Binary.BUFFER_SIZE = 256; + + /** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_DEFAULT = 0; + /** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_FUNCTION = 1; + /** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_BYTE_ARRAY = 2; + /** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_UUID_OLD = 3; + /** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_UUID = 4; + /** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_MD5 = 5; + /** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_USER_DEFINED = 128; + + /** + * Expose. + */ + module.exports = Binary; + module.exports.Binary = Binary; + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 351 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var Long = __webpack_require__(334).Long, + Double = __webpack_require__(335).Double, + Timestamp = __webpack_require__(336).Timestamp, + ObjectID = __webpack_require__(337).ObjectID, + Symbol = __webpack_require__(343).Symbol, + Code = __webpack_require__(345).Code, + MinKey = __webpack_require__(347).MinKey, + MaxKey = __webpack_require__(348).MaxKey, + Decimal128 = __webpack_require__(346), + Int32 = __webpack_require__(344), + DBRef = __webpack_require__(349).DBRef, + BSONRegExp = __webpack_require__(342).BSONRegExp, + Binary = __webpack_require__(350).Binary; + + var deserialize = function (buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + + // Ensure buffer is valid size + if (size < 5 || buffer.length < size || size + index > buffer.length) { + throw new Error('corrupt bson message'); + } + + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); + }; + + var deserializeObject = function (buffer, index, options, isArray) { + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + + if (!cacheFunctionsCrc32) var crc32 = null; + + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + + // Set the start index + var startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); + + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + + var done = false; + + // While we have more left data left keep parsing + // while (buffer[index + 1] !== 0) { + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) break; + + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + + index = i + 1; + + if (elementType === BSON.BSON_DATA_STRING) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_OID) { + var oid = new Buffer(12); + buffer.copy(oid, 0, index, index + 12); + object[name] = new ObjectID(oid); + index = index + 12; + } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { + object[name] = new Int32(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); + } else if (elementType === BSON.BSON_DATA_INT) { + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { + object[name] = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_NUMBER) { + object[name] = buffer.readDoubleLE(index); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_DATE) { + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType === BSON.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); + object[name] = buffer[index++] === 1; + } else if (elementType === BSON.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + if (objectSize <= 0 || objectSize > buffer.length - index) throw new Error('bad embedded document length in bson'); + + // We have a raw value + if (raw) { + object[name] = buffer.slice(index, index + objectSize); + } else { + object[name] = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if (elementType === BSON.BSON_DATA_ARRAY) { + _index = index; + objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + var arrayOptions = options; + + // Stop index + var stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + object[name] = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); + if (index !== stopIndex) throw new Error('corrupted array bson'); + } else if (elementType === BSON.BSON_DATA_UNDEFINED) { + object[name] = undefined; + } else if (elementType === BSON.BSON_DATA_NULL) { + object[name] = null; + } else if (elementType === BSON.BSON_DATA_LONG) { + // Unpack the low and high bits + lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + } else if (elementType === BSON.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = new Buffer(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; + } else if (elementType === BSON.BSON_DATA_BINARY) { + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var totalBinarySize = binarySize; + var subType = buffer[index++]; + + // Did we have a negative binary size, throw + if (binarySize < 0) throw new Error('Negative binary type element size found'); + + // Is the length longer than the document + if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + if (promoteBuffers && promoteValues) { + object[name] = buffer.slice(index, index + binarySize); + } else { + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } + } else { + var _buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + + if (promoteBuffers && promoteValues) { + object[name] = _buffer; + } else { + object[name] = new Binary(_buffer, subType); + } + } + + // Update the index + index = index + binarySize; + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + source = buffer.toString('utf8', index, i); + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if (elementType === BSON.BSON_DATA_SYMBOL) { + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { + lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + object[name] = new Timestamp(lowBits, highBits); + } else if (elementType === BSON.BSON_DATA_MIN_KEY) { + object[name] = new MinKey(); + } else if (elementType === BSON.BSON_DATA_MAX_KEY) { + object[name] = new MaxKey(); + } else if (elementType === BSON.BSON_DATA_CODE) { + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString); + } + + // Update parse index position + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new Error('code_w_scope total size shorter minimum expected length'); + } + + // Get the code string size + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Check if we have a valid string + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + + // Javascript function + functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + _index = index; + // Decode the size of the object document + objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is to short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to short, truncating scope'); + } + + // Check if totalSize field is to long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to long, clips outer document'); + } + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } else if (elementType === BSON.BSON_DATA_DBPOINTER) { + // Get the code string size + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Check if we have a valid string + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + // Namespace + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + + // Read the oid + var oidBuffer = new Buffer(12); + buffer.copy(oidBuffer, 0, index, index + 12); + oid = new ObjectID(oidBuffer); + + // Update the index + index = index + 12; + + // Split the namespace + var parts = namespace.split('.'); + var db = parts.shift(); + var collection = parts.join('.'); + // Upgrade to DBRef type + object[name] = new DBRef(collection, oid, db); + } else { + throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '", are you using the latest BSON parser'); + } + } + + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) throw new Error('corrupt array bson'); + throw new Error('corrupt object bson'); + } + + // Check if we have a db ref object + if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + return object; + }; + + /** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ + var isolateEvalWithHash = function (functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if (functionCache[hash] == null) { + eval('value = ' + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); + }; + + /** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ + var isolateEval = function (functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval('value = ' + functionString); + return value; + }; + + var BSON = {}; + + /** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ + var functionCache = BSON.functionCache = {}; + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ + BSON.BSON_DATA_UNDEFINED = 6; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_DBPOINTER + **/ + BSON.BSON_DATA_DBPOINTER = 12; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ + BSON.BSON_DATA_DECIMAL128 = 19; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = deserialize; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) + +/***/ }), +/* 352 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var writeIEEE754 = __webpack_require__(353).writeIEEE754, + Long = __webpack_require__(334).Long, + MinKey = __webpack_require__(347).MinKey, + Map = __webpack_require__(333), + Binary = __webpack_require__(350).Binary; + + const normalizedFunctionString = __webpack_require__(354).normalizedFunctionString; + + // try { + // var _Buffer = Uint8Array; + // } catch (e) { + // _Buffer = Buffer; + // } + + var regexp = /\x00/; // eslint-disable-line no-control-regex + + // To ensure that 0.4 of node works correctly + var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; + }; + + var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; + }; + + var serializeString = function (buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = size + 1 >> 24 & 0xff; + buffer[index + 2] = size + 1 >> 16 & 0xff; + buffer[index + 1] = size + 1 >> 8 & 0xff; + buffer[index] = size + 1 & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; + }; + + var serializeNumber = function (buffer, key, value, index, isArray) { + // We have an integer value + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = value >> 8 & 0xff; + buffer[index++] = value >> 16 & 0xff; + buffer[index++] = value >> 24 & 0xff; + } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; + }; + + var serializeNull = function (buffer, key, value, index, isArray) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + }; + + var serializeBoolean = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + }; + + var serializeDate = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + return index; + }; + + var serializeRegExp = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.global) buffer[index++] = 0x73; // s + if (value.ignoreCase) buffer[index++] = 0x69; // i + if (value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + }; + + var serializeBSONRegExp = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; + }; + + var serializeMinMax = function (buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if (value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + }; + + var serializeObjectId = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, 'binary'); + } else if (value.id && value.id.copy) { + value.id.copy(buffer, index, 0, 12); + } else { + throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + + // Ajust index + return index + 12; + }; + + var serializeBuffer = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; + }; + + var serializeObject = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { + for (var i = 0; i < path.length; i++) { + if (path[i] === value) throw new Error('cyclic dependency detected'); + } + + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + // Pop stack + path.pop(); + // Write size + return endIndex; + }; + + var serializeDecimal128 = function (buffer, key, value, index, isArray) { + buffer[index++] = BSON.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + value.bytes.copy(buffer, index, 0, 16); + return index + 16; + }; + + var serializeLong = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + return index; + }; + + var serializeInt32 = function (buffer, key, value, index, isArray) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = value >> 8 & 0xff; + buffer[index++] = value >> 16 & 0xff; + buffer[index++] = value >> 24 & 0xff; + return index; + }; + + var serializeDouble = function (buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; + }; + + var serializeFunction = function (buffer, key, value, index, checkKeys, depth, isArray) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = normalizedFunctionString(value); + + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; + }; + + var serializeCode = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = codeSize >> 8 & 0xff; + buffer[index + 2] = codeSize >> 16 & 0xff; + buffer[index + 3] = codeSize >> 24 & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = totalSize >> 8 & 0xff; + buffer[startIndex++] = totalSize >> 16 & 0xff; + buffer[startIndex++] = totalSize >> 24 & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; + }; + + var serializeBinary = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; + }; + + var serializeSymbol = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + }; + + var serializeDBRef = function (buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if (null != value.db) { + endIndex = serializeInto(buffer, { + $ref: value.namespace, + $id: value.oid, + $db: value.db + }, false, index, depth + 1, serializeFunctions); + } else { + endIndex = serializeInto(buffer, { + $ref: value.namespace, + $id: value.oid + }, false, index, depth + 1, serializeFunctions); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = size >> 8 & 0xff; + buffer[startIndex++] = size >> 16 & 0xff; + buffer[startIndex++] = size >> 24 & 0xff; + // Set index + return endIndex; + }; + + var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + startingIndex = startingIndex || 0; + path = path || []; + + // Push the object to the path + path.push(object); + + // Start place to serialize into + var index = startingIndex + 4; + // var self = this; + + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + var type = typeof value; + if (type === 'string') { + index = serializeString(buffer, key, value, index, true); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + } + } else if (object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if (done) continue; + + // Get the entry values + key = entry.value[0]; + value = entry.value[1]; + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (key !== '$db' && key !== '$ref' && key !== '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + // } else if (value === undefined && ignoreUndefined === true) { + } else if (value === null || value === undefined && ignoreUndefined === false) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') throw new Error('toBSON function did not return an object'); + } + + // Iterate over all the keys + for (key in object) { + value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (key !== '$db' && key !== '$ref' && key !== '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // Remove the path + path.pop(); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = size >> 8 & 0xff; + buffer[startingIndex++] = size >> 16 & 0xff; + buffer[startingIndex++] = size >> 24 & 0xff; + return index; + }; + + var BSON = {}; + + /** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ + // var functionCache = (BSON.functionCache = {}); + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * ObjectID BSON Type, deprecated + * + * @classconstant BSON_DATA_UNDEFINED + **/ + BSON.BSON_DATA_UNDEFINED = 6; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ + BSON.BSON_DATA_DECIMAL128 = 19; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = serializeInto; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) + +/***/ }), +/* 353 */ +/***/ (function(module, exports) { + + // Copyright (c) 2008, Fair Oaks Labs, Inc. + // All rights reserved. + // + // Redistribution and use in source and binary forms, with or without + // modification, are permitted provided that the following conditions are met: + // + // * Redistributions of source code must retain the above copyright notice, + // this list of conditions and the following disclaimer. + // + // * Redistributions in binary form must reproduce the above copyright notice, + // this list of conditions and the following disclaimer in the documentation + // and/or other materials provided with the distribution. + // + // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors + // may be used to endorse or promote products derived from this software + // without specific prior written permission. + // + // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + // POSSIBILITY OF SUCH DAMAGE. + // + // + // Modifications to writeIEEE754 to support negative zeroes made by Brian White + + var readIEEE754 = function (buffer, offset, endian, mLen, nBytes) { + var e, + m, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : nBytes - 1, + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); + }; + + var writeIEEE754 = function (buffer, value, offset, endian, mLen, nBytes) { + var e, + m, + c, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, + i = bBE ? nBytes - 1 : 0, + d = bBE ? -1 : 1, + s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; + }; + + exports.readIEEE754 = readIEEE754; + exports.writeIEEE754 = writeIEEE754; + +/***/ }), +/* 354 */ +/***/ (function(module, exports) { + + 'use strict'; + + /** + * Normalizes our expected stringified form of a function across versions of node + * @param {Function} fn The function to stringify + */ + + function normalizedFunctionString(fn) { + return fn.toString().replace(/function *\(/, 'function ('); + } + + module.exports = { + normalizedFunctionString: normalizedFunctionString + }; + +/***/ }), +/* 355 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var Long = __webpack_require__(334).Long, + Double = __webpack_require__(335).Double, + Timestamp = __webpack_require__(336).Timestamp, + ObjectID = __webpack_require__(337).ObjectID, + Symbol = __webpack_require__(343).Symbol, + BSONRegExp = __webpack_require__(342).BSONRegExp, + Code = __webpack_require__(345).Code, + Decimal128 = __webpack_require__(346), + MinKey = __webpack_require__(347).MinKey, + MaxKey = __webpack_require__(348).MaxKey, + DBRef = __webpack_require__(349).DBRef, + Binary = __webpack_require__(350).Binary; + + var normalizedFunctionString = __webpack_require__(354).normalizedFunctionString; + + // To ensure that 0.4 of node works correctly + var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; + }; + + var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { + var totalLength = 4 + 1; + + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + + return totalLength; + }; + + /** + * @ignore + * @api private + */ + function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + + switch (typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // 32 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length; + } else if (value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] === 'Long' || value['_bsontype'] === 'Double' || value['_bsontype'] === 'Timestamp') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } else if (value instanceof Code || value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; + } + } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1); + } + } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; + } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + $ref: value.namespace, + $id: value.oid + }; + + // Add db reference if it exists + if (null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); + } else if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; + } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1; + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) === '[object RegExp]') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; + } else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else if (serializeFunctions) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1; + } + } + } + + return 0; + } + + var BSON = {}; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = calculateObjectSize; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(329).Buffer)) + +/***/ }) +/******/ ]) +}); +; \ No newline at end of file diff --git a/app/node_modules/bson/browser_build/package.json b/app/node_modules/bson/browser_build/package.json new file mode 100644 index 0000000..980db7f --- /dev/null +++ b/app/node_modules/bson/browser_build/package.json @@ -0,0 +1,8 @@ +{ "name" : "bson" +, "description" : "A bson parser for node.js and the browser" +, "main": "../" +, "directories" : { "lib" : "../lib/bson" } +, "engines" : { "node" : ">=0.6.0" } +, "licenses" : [ { "type" : "Apache License, Version 2.0" + , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] +} diff --git a/app/node_modules/bson/index.js b/app/node_modules/bson/index.js new file mode 100644 index 0000000..6502552 --- /dev/null +++ b/app/node_modules/bson/index.js @@ -0,0 +1,46 @@ +var BSON = require('./lib/bson/bson'), + Binary = require('./lib/bson/binary'), + Code = require('./lib/bson/code'), + DBRef = require('./lib/bson/db_ref'), + Decimal128 = require('./lib/bson/decimal128'), + Double = require('./lib/bson/double'), + Int32 = require('./lib/bson/int_32'), + Long = require('./lib/bson/long'), + Map = require('./lib/bson/map'), + MaxKey = require('./lib/bson/max_key'), + MinKey = require('./lib/bson/min_key'), + ObjectId = require('./lib/bson/objectid'), + BSONRegExp = require('./lib/bson/regexp'), + Symbol = require('./lib/bson/symbol'), + Timestamp = require('./lib/bson/timestamp'); + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Add BSON types to function creation +BSON.Binary = Binary; +BSON.Code = Code; +BSON.DBRef = DBRef; +BSON.Decimal128 = Decimal128; +BSON.Double = Double; +BSON.Int32 = Int32; +BSON.Long = Long; +BSON.Map = Map; +BSON.MaxKey = MaxKey; +BSON.MinKey = MinKey; +BSON.ObjectId = ObjectId; +BSON.ObjectID = ObjectId; +BSON.BSONRegExp = BSONRegExp; +BSON.Symbol = Symbol; +BSON.Timestamp = Timestamp; + +// Return the BSON +module.exports = BSON; diff --git a/app/node_modules/bson/lib/bson/binary.js b/app/node_modules/bson/lib/bson/binary.js new file mode 100644 index 0000000..f3f695d --- /dev/null +++ b/app/node_modules/bson/lib/bson/binary.js @@ -0,0 +1,382 @@ +/** + * Module dependencies. + * @ignore + */ + +// Test if we're in Node via presence of "global" not absence of "window" +// to support hybrid environments like Electron +if (typeof global !== 'undefined') { + var Buffer = require('buffer').Buffer; // TODO just use global Buffer +} + +/** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ +function Binary(buffer, subType) { + if (!(this instanceof Binary)) return new Binary(buffer, subType); + + if ( + buffer != null && + !(typeof buffer === 'string') && + !Buffer.isBuffer(buffer) && + !(buffer instanceof Uint8Array) && + !Array.isArray(buffer) + ) { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + + this._bsontype = 'Binary'; + + if (buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if (buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if (typeof buffer === 'string') { + // Different ways of writing the length of the string for the different types + if (typeof Buffer !== 'undefined') { + this.buffer = new Buffer(buffer); + } else if ( + typeof Uint8Array !== 'undefined' || + Object.prototype.toString.call(buffer) === '[object Array]' + ) { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if (typeof Buffer !== 'undefined') { + this.buffer = new Buffer(Binary.BUFFER_SIZE); + } else if (typeof Uint8Array !== 'undefined') { + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } +} + +/** + * Updates this binary with byte_value. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ +Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) + throw new Error('only accepts single character String, Uint8Array or Array'); + if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255) + throw new Error('only accepts number in a valid unsigned byte range 0-255'); + + // Decode the byte value once + var decoded_byte = null; + if (typeof byte_value === 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if (byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + buffer = null; + // Create a new buffer (typed or normal array) + if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for (var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } +}; + +/** + * Writes a buffer or string to the binary. + * + * @method + * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. + * @param {number} offset specify the binary of where to write the content. + * @return {null} + */ +Binary.prototype.write = function write(string, offset) { + offset = typeof offset === 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = new Buffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); + // Copy the content + for (var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length + } else if ( + typeof Buffer !== 'undefined' && + typeof string === 'string' && + Buffer.isBuffer(this.buffer) + ) { + this.buffer.write(string, offset, 'binary'); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length; + } else if ( + Object.prototype.toString.call(string) === '[object Uint8Array]' || + (Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') + ) { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if (typeof string === 'string') { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } +}; + +/** + * Reads **length** bytes starting at **position**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ +Binary.prototype.read = function read(position, length) { + length = length && length > 0 ? length : this.position; + + // Let's return the data based on the type we have + if (this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = + typeof Uint8Array !== 'undefined' + ? new Uint8Array(new ArrayBuffer(length)) + : new Array(length); + for (var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; +}; + +/** + * Returns the value of this binary as a string. + * + * @method + * @return {string} + */ +Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if ( + asRaw && + typeof Buffer !== 'undefined' && + Buffer.isBuffer(this.buffer) && + this.buffer.length === this.position + ) + return this.buffer; + + // If it's a node.js buffer object + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw + ? this.buffer.slice(0, this.position) + : this.buffer.toString('binary', 0, this.position); + } else { + if (asRaw) { + // we support the slice command use it + if (this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = + Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' + ? new Uint8Array(new ArrayBuffer(this.position)) + : new Array(this.position); + // Copy content + for (var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } +}; + +/** + * Length. + * + * @method + * @return {number} the length of the binary. + */ +Binary.prototype.length = function length() { + return this.position; +}; + +/** + * @ignore + */ +Binary.prototype.toJSON = function() { + return this.buffer != null ? this.buffer.toString('base64') : ''; +}; + +/** + * @ignore + */ +Binary.prototype.toString = function(format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; +}; + +/** + * Binary default subtype + * @ignore + */ +var BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** + * @ignore + */ +var writeStringToArray = function(data) { + // Create a buffer + var buffer = + typeof Uint8Array !== 'undefined' + ? new Uint8Array(new ArrayBuffer(data.length)) + : new Array(data.length); + // Write the content to the buffer + for (var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; +}; + +/** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + */ +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ''; + for (var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; +}; + +Binary.BUFFER_SIZE = 256; + +/** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_DEFAULT = 0; +/** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_FUNCTION = 1; +/** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_BYTE_ARRAY = 2; +/** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID_OLD = 3; +/** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID = 4; +/** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_MD5 = 5; +/** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_USER_DEFINED = 128; + +/** + * Expose. + */ +module.exports = Binary; +module.exports.Binary = Binary; diff --git a/app/node_modules/bson/lib/bson/bson.js b/app/node_modules/bson/lib/bson/bson.js new file mode 100644 index 0000000..956f152 --- /dev/null +++ b/app/node_modules/bson/lib/bson/bson.js @@ -0,0 +1,385 @@ +'use strict'; + +var Map = require('./map'), + Long = require('./long'), + Double = require('./double'), + Timestamp = require('./timestamp'), + ObjectID = require('./objectid'), + BSONRegExp = require('./regexp'), + Symbol = require('./symbol'), + Int32 = require('./int_32'), + Code = require('./code'), + Decimal128 = require('./decimal128'), + MinKey = require('./min_key'), + MaxKey = require('./max_key'), + DBRef = require('./db_ref'), + Binary = require('./binary'); + +// Parts of the parser +var deserialize = require('./parser/deserializer'), + serializer = require('./parser/serializer'), + calculateObjectSize = require('./parser/calculate_size'); + +/** + * @ignore + * @api private + */ +// Default Max Size +var MAXSIZE = 1024 * 1024 * 17; + +// Current Internal Temporary Serialization Buffer +var buffer = new Buffer(MAXSIZE); + +var BSON = function() {}; + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function serialize(object, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = + typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = new Buffer(minInternalBufferSize); + } + + // Attempt to serialize + var serializationIndex = serializer( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined, + [] + ); + // Create the final buffer + var finishedBuffer = new Buffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +}; + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + + // Attempt to serialize + var serializationIndex = serializer( + finalBuffer, + object, + checkKeys, + startIndex || 0, + 0, + serializeFunctions, + ignoreUndefined + ); + + // Return the index + return serializationIndex - 1; +}; + +/** + * Deserialize data as BSON. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(buffer, options) { + return deserialize(buffer, options); +}; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, options) { + options = options || {}; + + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); +}; + +/** + * Deserialize stream data as BSON documents. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function( + data, + startIndex, + numberOfDocuments, + documents, + docStartIndex, + options +) { + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = + data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24); + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = this.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +}; + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// Return BSON +module.exports = BSON; +module.exports.Code = Code; +module.exports.Map = Map; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.Int32 = Int32; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.BSONRegExp = BSONRegExp; +module.exports.Decimal128 = Decimal128; diff --git a/app/node_modules/bson/lib/bson/code.js b/app/node_modules/bson/lib/bson/code.js new file mode 100644 index 0000000..c2984cd --- /dev/null +++ b/app/node_modules/bson/lib/bson/code.js @@ -0,0 +1,24 @@ +/** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ +var Code = function Code(code, scope) { + if (!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope; +}; + +/** + * @ignore + */ +Code.prototype.toJSON = function() { + return { scope: this.scope, code: this.code }; +}; + +module.exports = Code; +module.exports.Code = Code; diff --git a/app/node_modules/bson/lib/bson/db_ref.js b/app/node_modules/bson/lib/bson/db_ref.js new file mode 100644 index 0000000..f95795b --- /dev/null +++ b/app/node_modules/bson/lib/bson/db_ref.js @@ -0,0 +1,32 @@ +/** + * A class representation of the BSON DBRef type. + * + * @class + * @param {string} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {string} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ +function DBRef(namespace, oid, db) { + if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; +} + +/** + * @ignore + * @api private + */ +DBRef.prototype.toJSON = function() { + return { + $ref: this.namespace, + $id: this.oid, + $db: this.db == null ? '' : this.db + }; +}; + +module.exports = DBRef; +module.exports.DBRef = DBRef; diff --git a/app/node_modules/bson/lib/bson/decimal128.js b/app/node_modules/bson/lib/bson/decimal128.js new file mode 100644 index 0000000..1dc2f00 --- /dev/null +++ b/app/node_modules/bson/lib/bson/decimal128.js @@ -0,0 +1,818 @@ +'use strict'; + +var Long = require('./long'); + +var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + +var EXPONENT_MAX = 6111; +var EXPONENT_MIN = -6176; +var EXPONENT_BIAS = 6176; +var MAX_DIGITS = 34; + +// Nan value bits as 32 bit values (due to lack of longs) +var NAN_BUFFER = [ + 0x7c, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); +// Infinity value bits 32 bit values (due to lack of longs) +var INF_NEGATIVE_BUFFER = [ + 0xf8, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); +var INF_POSITIVE_BUFFER = [ + 0x78, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); + +var EXPONENT_REGEX = /^([-+])?(\d+)?$/; + +// Detect if the value is a digit +var isDigit = function(value) { + return !isNaN(parseInt(value, 10)); +}; + +// Divide two uint128 values +var divideu128 = function(value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + var i = 0; + + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for (i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low_; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; +}; + +// Multiply two Long values and return the 128 bit value +var multiply64x2 = function(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return { high: productHigh, low: productLow }; +}; + +var lessThan = function(left, right) { + // Make values unsigned + var uhleft = left.high_ >>> 0; + var uhright = right.high_ >>> 0; + + // Compare high bits first + if (uhleft < uhright) { + return true; + } else if (uhleft === uhright) { + var ulleft = left.low_ >>> 0; + var ulright = right.low_ >>> 0; + if (ulleft < ulright) return true; + } + + return false; +}; + +// var longtoHex = function(value) { +// var buffer = new Buffer(8); +// var index = 0; +// // Encode the low 64 bits of the decimal +// // Encode low bits +// buffer[index++] = value.low_ & 0xff; +// buffer[index++] = (value.low_ >> 8) & 0xff; +// buffer[index++] = (value.low_ >> 16) & 0xff; +// buffer[index++] = (value.low_ >> 24) & 0xff; +// // Encode high bits +// buffer[index++] = value.high_ & 0xff; +// buffer[index++] = (value.high_ >> 8) & 0xff; +// buffer[index++] = (value.high_ >> 16) & 0xff; +// buffer[index++] = (value.high_ >> 24) & 0xff; +// return buffer.reverse().toString('hex'); +// }; + +// var int32toHex = function(value) { +// var buffer = new Buffer(4); +// var index = 0; +// // Encode the low 64 bits of the decimal +// // Encode low bits +// buffer[index++] = value & 0xff; +// buffer[index++] = (value >> 8) & 0xff; +// buffer[index++] = (value >> 16) & 0xff; +// buffer[index++] = (value >> 24) & 0xff; +// return buffer.reverse().toString('hex'); +// }; + +/** + * A class representation of the BSON Decimal128 type. + * + * @class + * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. + * @return {Double} + */ +var Decimal128 = function(bytes) { + this._bsontype = 'Decimal128'; + this.bytes = bytes; +}; + +/** + * Create a Decimal128 instance from a string representation + * + * @method + * @param {string} string a numeric string representation. + * @return {Decimal128} returns a Decimal128 instance. + */ +Decimal128.fromString = function(string) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = [0, 0]; + // The low 17 digits of the significand + var significandLow = [0, 0]; + // The biased exponent + var biasedExponent = 0; + + // Read index + var index = 0; + + // Trim the string + string = string.trim(); + + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (string.length >= 7000) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Results + var stringMatch = string.match(PARSE_STRING_REGEXP); + var infMatch = string.match(PARSE_INF_REGEXP); + var nanMatch = string.match(PARSE_NAN_REGEXP); + + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Check if we have an illegal exponent format + if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Get the negative or positive sign + if (string[index] === '+' || string[index] === '-') { + isNegative = string[index++] === '-'; + } + + // Check if user passed Infinity or NaN + if (!isDigit(string[index]) && string[index] !== '.') { + if (string[index] === 'i' || string[index] === 'I') { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } else if (string[index] === 'N') { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + } + + // Read all the digits + while (isDigit(string[index]) || string[index] === '.') { + if (string[index] === '.') { + if (sawRadix) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + sawRadix = true; + index = index + 1; + continue; + } + + if (nDigitsStored < 34) { + if (string[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(string[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if (foundNonZero) { + nDigits = nDigits + 1; + } + + if (sawRadix) { + radixPosition = radixPosition + 1; + } + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if (sawRadix && !nDigitsRead) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Read exponent if exists + if (string[index] === 'e' || string[index] === 'E') { + // Read exponent digits + var match = string.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if (!match || !match[2]) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if (string[index]) { + return new Decimal128(new Buffer(NAN_BUFFER)); + } + + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + + if (exponent !== 0 && significantDigits !== 1) { + while (string[firstNonZero + significantDigits - 1] === '0') { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + + exponent = exponent - 1; + } + + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit + if (lastDigit === 0) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { + var endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix && exponent === EXPONENT_MIN) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + + if (roundDigit >= 5) { + roundBit = 1; + + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1; + + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(string[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if (roundBit) { + var dIdx = lastDigit; + + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128( + new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) + ); + } + } + } else { + break; + } + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit - firstDigit < 17) { + dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + + significand.low = significand.low.add(significandLow); + + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if ( + significand.high + .shiftRightUnsigned(49) + .and(Long.fromNumber(1)) + .equals(Long.fromNumber) + ) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or( + Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) + ); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + var buffer = new Buffer(16); + index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low_ & 0xff; + buffer[index++] = (dec.low.low_ >> 8) & 0xff; + buffer[index++] = (dec.low.low_ >> 16) & 0xff; + buffer[index++] = (dec.low.low_ >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high_ & 0xff; + buffer[index++] = (dec.low.high_ >> 8) & 0xff; + buffer[index++] = (dec.low.high_ >> 16) & 0xff; + buffer[index++] = (dec.low.high_ >> 24) & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low_ & 0xff; + buffer[index++] = (dec.high.low_ >> 8) & 0xff; + buffer[index++] = (dec.high.low_ >> 16) & 0xff; + buffer[index++] = (dec.high.low_ >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high_ & 0xff; + buffer[index++] = (dec.high.high_ >> 8) & 0xff; + buffer[index++] = (dec.high.high_ >> 16) & 0xff; + buffer[index++] = (dec.high.high_ >> 24) & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); +}; + +// Extract least significant 5 bits +var COMBINATION_MASK = 0x1f; +// Extract least significant 14 bits +var EXPONENT_MASK = 0x3fff; +// Value of combination field for Inf +var COMBINATION_INFINITY = 30; +// Value of combination field for NaN +var COMBINATION_NAN = 31; +// Value of combination field for NaN +// var COMBINATION_SNAN = 32; +// decimal128 exponent bias +EXPONENT_BIAS = 6176; + +/** + * Create a string representation of the raw Decimal128 value + * + * @method + * @return {string} returns a Decimal128 string representation. + */ +Decimal128.prototype.toString = function() { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // bits 0 - 31 + var high; + // bits 32 - 63 + var midh; + // bits 64 - 95 + var midl; + // bits 96 - 127 + var low; + // bits 1 - 5 + var combination; + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + var index = 0; + + // unbiased exponent + var exponent; + // the exponent if scientific notation is used + var scientific_exponent; + + // true if the number is zero + var is_zero = false; + + // the most signifcant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: new Array(4) }; + // indexing variables + i; + var j, k; + + // Output string + var string = []; + + // Unpack index + index = 0; + + // Buffer reference + var buffer = this.bytes; + + // Unpack the low 64bits into a long + low = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + midl = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack the high 64bits into a long + midh = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + high = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack index + index = 0; + + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + combination = (high >> 26) & COMBINATION_MASK; + + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } else if (combination === COMBINATION_NAN) { + return 'NaN'; + } else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + + exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if ( + significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0 + ) { + is_zero = true; + } else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Peform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low_; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) continue; + + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + i = 0; + + while (!significand[index]) { + i++; + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + string.push(significand[index++]); + significand_digits = significand_digits - 1; + + if (significand_digits) { + string.push('.'); + } + + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } else { + string.push(scientific_exponent); + } + } else { + // Regular format with no decimal place + if (exponent >= 0) { + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + } else { + var radix_position = significand_digits + exponent; + + // non-zero digits before radix + if (radix_position > 0) { + for (i = 0; i < radix_position; i++) { + string.push(significand[index++]); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + + for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(significand[index++]); + } + } + } + + return string.join(''); +}; + +Decimal128.prototype.toJSON = function() { + return { $numberDecimal: this.toString() }; +}; + +module.exports = Decimal128; +module.exports.Decimal128 = Decimal128; diff --git a/app/node_modules/bson/lib/bson/double.js b/app/node_modules/bson/lib/bson/double.js new file mode 100644 index 0000000..523c21f --- /dev/null +++ b/app/node_modules/bson/lib/bson/double.js @@ -0,0 +1,33 @@ +/** + * A class representation of the BSON Double type. + * + * @class + * @param {number} value the number we want to represent as a double. + * @return {Double} + */ +function Double(value) { + if (!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; +} + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped double number. + */ +Double.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Double.prototype.toJSON = function() { + return this.value; +}; + +module.exports = Double; +module.exports.Double = Double; diff --git a/app/node_modules/bson/lib/bson/float_parser.js b/app/node_modules/bson/lib/bson/float_parser.js new file mode 100644 index 0000000..0054a2f --- /dev/null +++ b/app/node_modules/bson/lib/bson/float_parser.js @@ -0,0 +1,124 @@ +// Copyright (c) 2008, Fair Oaks Labs, Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// +// Modifications to writeIEEE754 to support negative zeroes made by Brian White + +var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { + var e, + m, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : nBytes - 1, + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << -nBits) - 1); + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << -nBits) - 1); + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { + var e, + m, + c, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, + i = bBE ? nBytes - 1 : 0, + d = bBE ? -1 : 1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +exports.readIEEE754 = readIEEE754; +exports.writeIEEE754 = writeIEEE754; diff --git a/app/node_modules/bson/lib/bson/int_32.js b/app/node_modules/bson/lib/bson/int_32.js new file mode 100644 index 0000000..85dbdec --- /dev/null +++ b/app/node_modules/bson/lib/bson/int_32.js @@ -0,0 +1,33 @@ +/** + * A class representation of a BSON Int32 type. + * + * @class + * @param {number} value the number we want to represent as an int32. + * @return {Int32} + */ +var Int32 = function(value) { + if (!(this instanceof Int32)) return new Int32(value); + + this._bsontype = 'Int32'; + this.value = value; +}; + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped int32 number. + */ +Int32.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Int32.prototype.toJSON = function() { + return this.value; +}; + +module.exports = Int32; +module.exports.Int32 = Int32; diff --git a/app/node_modules/bson/lib/bson/long.js b/app/node_modules/bson/lib/bson/long.js new file mode 100644 index 0000000..78215aa --- /dev/null +++ b/app/node_modules/bson/lib/bson/long.js @@ -0,0 +1,851 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ +function Long(low, high) { + if (!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +} + +/** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ +Long.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Long.prototype.toNumber = function() { + return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Long.prototype.toJSON = function() { + return this.toString(); +}; + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Long.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Long.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Long.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Long.prototype.getLowBitsUnsigned = function() { + return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ +Long.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Long.prototype.isZero = function() { + return this.high_ === 0 && this.low_ === 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Long.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Long.prototype.isOdd = function() { + return (this.low_ & 1) === 1; +}; + +/** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ +Long.prototype.equals = function(other) { + return this.high_ === other.high_ && this.low_ === other.low_; +}; + +/** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ +Long.prototype.notEquals = function(other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; +}; + +/** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ +Long.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ +Long.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ +Long.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ +Long.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Long with the given one. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Long.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Long} the negation of this value. + */ +Long.prototype.negate = function() { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } +}; + +/** + * Returns the sum of this and the given Long. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ +Long.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Long. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ +Long.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ +Long.prototype.multiply = function(other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate() + .multiply(other) + .negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Long divided by the given one. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ +Long.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate() + .div(other) + .negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Long modulo the given one. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ +Long.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ +Long.prototype.not = function() { + return Long.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ +Long.prototype.and = function(other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ +Long.prototype.or = function(other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ +Long.prototype.xor = function(other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ +Long.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); + } else { + return Long.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ +Long.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); + } else { + return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Long.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); + } else if (numBits === 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Long representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ +Long.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ +Long.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ +Long.fromBits = function(lowBits, highBits) { + return new Long(lowBits, highBits); +}; + +/** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Long. + * @param {number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + */ +Long.fromString = function(str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + +/** + * A cache of the Long representations of small integer values. + * @type {Object} + * @ignore + */ +Long.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Long.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + +/** @type {Long} */ +Long.ZERO = Long.fromInt(0); + +/** @type {Long} */ +Long.ONE = Long.fromInt(1); + +/** @type {Long} */ +Long.NEG_ONE = Long.fromInt(-1); + +/** @type {Long} */ +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); + +/** @type {Long} */ +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + +/** + * @type {Long} + * @ignore + */ +Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Long; +module.exports.Long = Long; diff --git a/app/node_modules/bson/lib/bson/map.js b/app/node_modules/bson/lib/bson/map.js new file mode 100644 index 0000000..7edb4f2 --- /dev/null +++ b/app/node_modules/bson/lib/bson/map.js @@ -0,0 +1,128 @@ +'use strict'; + +// We have an ES6 Map available, return the native instance +if (typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; +} else { + // We will return a polyfill + var Map = function(array) { + this._keys = []; + this._values = {}; + + for (var i = 0; i < array.length; i++) { + if (array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + }; + + Map.prototype.clear = function() { + this._keys = []; + this._values = {}; + }; + + Map.prototype.delete = function(key) { + var value = this._values[key]; + if (value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + + Map.prototype.entries = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.forEach = function(callback, self) { + self = self || this; + + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + + Map.prototype.get = function(key) { + return this._values[key] ? this._values[key].v : undefined; + }; + + Map.prototype.has = function(key) { + return this._values[key] != null; + }; + + Map.prototype.keys = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.set = function(key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + + Map.prototype.values = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable: true, + get: function() { + return this._keys.length; + } + }); + + module.exports = Map; + module.exports.Map = Map; +} diff --git a/app/node_modules/bson/lib/bson/max_key.js b/app/node_modules/bson/lib/bson/max_key.js new file mode 100644 index 0000000..eebca7b --- /dev/null +++ b/app/node_modules/bson/lib/bson/max_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ +function MaxKey() { + if (!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; +} + +module.exports = MaxKey; +module.exports.MaxKey = MaxKey; diff --git a/app/node_modules/bson/lib/bson/min_key.js b/app/node_modules/bson/lib/bson/min_key.js new file mode 100644 index 0000000..15f4522 --- /dev/null +++ b/app/node_modules/bson/lib/bson/min_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ +function MinKey() { + if (!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; +} + +module.exports = MinKey; +module.exports.MinKey = MinKey; diff --git a/app/node_modules/bson/lib/bson/objectid.js b/app/node_modules/bson/lib/bson/objectid.js new file mode 100644 index 0000000..f76ecbb --- /dev/null +++ b/app/node_modules/bson/lib/bson/objectid.js @@ -0,0 +1,387 @@ +// Custom inspect property name / symbol. +var inspect = 'inspect'; + +/** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + * @ignore + */ +var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + +// Check if buffer exists +try { + if (Buffer && Buffer.from) { + var hasBufferType = true; + inspect = require('util').inspect.custom || 'inspect'; + } +} catch (err) { + hasBufferType = false; +} + +/** +* Create a new ObjectID instance +* +* @class +* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. +* @property {number} generationTime The generation time of this ObjectId instance +* @return {ObjectID} instance of ObjectID. +*/ +var ObjectID = function ObjectID(id) { + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectID) return id; + if (!(this instanceof ObjectID)) return new ObjectID(id); + + this._bsontype = 'ObjectID'; + + // The most common usecase (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this.id = this.generate(id); + // If we are caching the hex string + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); + // Return the object + return; + } + + // Check if the passed in id is valid + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if (!valid && id != null) { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { + return new ObjectID(new Buffer(id, 'hex')); + } else if (valid && typeof id === 'string' && id.length === 24) { + return ObjectID.createFromHexString(id); + } else if (id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } else if (id != null && id.toHexString) { + // Duck-typing to support ObjectId from different npm packages + return id; + } else { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } + + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); +}; + +// Allow usage of ObjectId as well as ObjectID +// var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* Return the ObjectID id as a 24 byte hex string representation +* +* @method +* @return {string} return the 24 byte hex string representation. +*/ +ObjectID.prototype.toHexString = function() { + if (ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + if (!this.id || !this.id.length) { + throw new Error( + 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + + JSON.stringify(this.id) + + ']' + ); + } + + if (this.id instanceof _Buffer) { + hexString = convertToHex(this.id); + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + } + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.get_inc = function() { + return (ObjectID.index = (ObjectID.index + 1) % 0xffffff); +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.getInc = function() { + return this.get_inc(); +}; + +/** +* Generate a 12 byte id buffer used in ObjectID's +* +* @method +* @param {number} [time] optional parameter allowing to pass in a second based timestamp. +* @return {Buffer} return the 12 byte id buffer string. +*/ +ObjectID.prototype.generate = function(time) { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + + // Use pid + var pid = + (typeof process === 'undefined' || process.pid === 1 + ? Math.floor(Math.random() * 100000) + : process.pid) % 0xffff; + var inc = this.get_inc(); + // Buffer used + var buffer = new Buffer(12); + // Encode time + buffer[3] = time & 0xff; + buffer[2] = (time >> 8) & 0xff; + buffer[1] = (time >> 16) & 0xff; + buffer[0] = (time >> 24) & 0xff; + // Encode machine + buffer[6] = MACHINE_ID & 0xff; + buffer[5] = (MACHINE_ID >> 8) & 0xff; + buffer[4] = (MACHINE_ID >> 16) & 0xff; + // Encode pid + buffer[8] = pid & 0xff; + buffer[7] = (pid >> 8) & 0xff; + // Encode index + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + // Return the buffer + return buffer; +}; + +/** +* Converts the id into a 24 byte hex string for printing +* +* @param {String} format The Buffer toString format parameter. +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toString = function(format) { + // Is the id a buffer then use the buffer toString method to return the format + if (this.id && this.id.copy) { + return this.id.toString(typeof format === 'string' ? format : 'hex'); + } + + // if(this.buffer ) + return this.toHexString(); +}; + +/** +* Converts to a string representation of this Id. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype[inspect] = ObjectID.prototype.toString; + +/** +* Converts to its JSON representation. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toJSON = function() { + return this.toHexString(); +}; + +/** +* Compares the equality of this ObjectID with `otherID`. +* +* @method +* @param {object} otherID ObjectID instance to compare against. +* @return {boolean} the result of comparing two ObjectID's +*/ +ObjectID.prototype.equals = function equals(otherId) { + // var id; + + if (otherId instanceof ObjectID) { + return this.toString() === otherId.toString(); + } else if ( + typeof otherId === 'string' && + ObjectID.isValid(otherId) && + otherId.length === 12 && + this.id instanceof _Buffer + ) { + return otherId === this.id.toString('binary'); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { + return otherId === this.id; + } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { + return otherId.toHexString() === this.toHexString(); + } else { + return false; + } +}; + +/** +* Returns the generation date (accurate up to the second) that this ID was generated. +* +* @method +* @return {date} the generation date +*/ +ObjectID.prototype.getTimestamp = function() { + var timestamp = new Date(); + var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; +}; + +/** +* @ignore +*/ +ObjectID.index = ~~(Math.random() * 0xffffff); + +/** +* @ignore +*/ +ObjectID.createPk = function createPk() { + return new ObjectID(); +}; + +/** +* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. +* +* @method +* @param {number} time an integer number representing a number of seconds. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromTime = function createFromTime(time) { + var buffer = new Buffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer[3] = time & 0xff; + buffer[2] = (time >> 8) & 0xff; + buffer[1] = (time >> 16) & 0xff; + buffer[0] = (time >> 24) & 0xff; + // Return the new objectId + return new ObjectID(buffer); +}; + +// Lookup tables +//var encodeLookup = '0123456789abcdef'.split(''); +var decodeLookup = []; +i = 0; +while (i < 10) decodeLookup[0x30 + i] = i++; +while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; + +var _Buffer = Buffer; +var convertToHex = function(bytes) { + return bytes.toString('hex'); +}; + +/** +* Creates an ObjectID from a hex string representation of an ObjectID. +* +* @method +* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromHexString = function createFromHexString(string) { + // Throw an error if it's not a valid setup + if (typeof string === 'undefined' || (string != null && string.length !== 24)) { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } + + // Use Buffer.from method if available + if (hasBufferType) return new ObjectID(new Buffer(string, 'hex')); + + // Calculate lengths + var array = new _Buffer(12); + var n = 0; + var i = 0; + + while (i < 24) { + array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)]; + } + + return new ObjectID(array); +}; + +/** +* Checks if a value is a valid bson ObjectId +* +* @method +* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. +*/ +ObjectID.isValid = function isValid(id) { + if (id == null) return false; + + if (typeof id === 'number') { + return true; + } + + if (typeof id === 'string') { + return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); + } + + if (id instanceof ObjectID) { + return true; + } + + if (id instanceof _Buffer) { + return true; + } + + // Duck-Typing detection of ObjectId like objects + if (id.toHexString) { + return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id)); + } + + return false; +}; + +/** +* @ignore +*/ +Object.defineProperty(ObjectID.prototype, 'generationTime', { + enumerable: true, + get: function() { + return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); + }, + set: function(value) { + // Encode time into first 4 bytes + this.id[3] = value & 0xff; + this.id[2] = (value >> 8) & 0xff; + this.id[1] = (value >> 16) & 0xff; + this.id[0] = (value >> 24) & 0xff; + } +}); + +/** + * Expose. + */ +module.exports = ObjectID; +module.exports.ObjectID = ObjectID; +module.exports.ObjectId = ObjectID; diff --git a/app/node_modules/bson/lib/bson/parser/calculate_size.js b/app/node_modules/bson/lib/bson/parser/calculate_size.js new file mode 100644 index 0000000..f174519 --- /dev/null +++ b/app/node_modules/bson/lib/bson/parser/calculate_size.js @@ -0,0 +1,255 @@ +'use strict'; + +var Long = require('../long').Long, + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + BSONRegExp = require('../regexp').BSONRegExp, + Code = require('../code').Code, + Decimal128 = require('../decimal128'), + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + DBRef = require('../db_ref').DBRef, + Binary = require('../binary').Binary; + +var normalizedFunctionString = require('./utils').normalizedFunctionString; + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +}; + +var calculateObjectSize = function calculateObjectSize( + object, + serializeFunctions, + ignoreUndefined +) { + var totalLength = 4 + 1; + + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement( + i.toString(), + object[i], + serializeFunctions, + true, + ignoreUndefined + ); + } + } else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + + return totalLength; +}; + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + + switch (typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // 32 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if ( + value == null || + value instanceof MinKey || + value instanceof MaxKey || + value['_bsontype'] === 'MinKey' || + value['_bsontype'] === 'MaxKey' + ) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length + ); + } else if ( + value instanceof Long || + value instanceof Double || + value instanceof Timestamp || + value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp' + ) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } else if (value instanceof Code || value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + ); + } + } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + (value.position + 1 + 4 + 1 + 4) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) + ); + } + } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + Buffer.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1 + ); + } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + $ref: value.namespace, + $id: value.oid + }; + + // Add db reference if it exists + if (null != value.db) { + ordered_values['$db'] = value.db; + } + + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) + ); + } else if ( + value instanceof RegExp || + Object.prototype.toString.call(value) === '[object RegExp]' + ) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.pattern, 'utf8') + + 1 + + Buffer.byteLength(value.options, 'utf8') + + 1 + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1 + ); + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if ( + value instanceof RegExp || + Object.prototype.toString.call(value) === '[object RegExp]' || + String.call(value) === '[object RegExp]' + ) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else if (serializeFunctions) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + ); + } + } + } + + return 0; +} + +var BSON = {}; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = calculateObjectSize; diff --git a/app/node_modules/bson/lib/bson/parser/deserializer.js b/app/node_modules/bson/lib/bson/parser/deserializer.js new file mode 100644 index 0000000..b7f45d7 --- /dev/null +++ b/app/node_modules/bson/lib/bson/parser/deserializer.js @@ -0,0 +1,780 @@ +'use strict'; + +var Long = require('../long').Long, + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + Code = require('../code').Code, + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + Decimal128 = require('../decimal128'), + Int32 = require('../int_32'), + DBRef = require('../db_ref').DBRef, + BSONRegExp = require('../regexp').BSONRegExp, + Binary = require('../binary').Binary; + +var deserialize = function(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + + // Ensure buffer is valid size + if (size < 5 || buffer.length < size || size + index > buffer.length) { + throw new Error('corrupt bson message'); + } + + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); +}; + +var deserializeObject = function(buffer, index, options, isArray) { + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = + options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + + if (!cacheFunctionsCrc32) var crc32 = null; + + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + + // Set the start index + var startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); + + // Read the document size + var size = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); + + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + + var done = false; + + // While we have more left data left keep parsing + // while (buffer[index + 1] !== 0) { + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) break; + + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + + index = i + 1; + + if (elementType === BSON.BSON_DATA_STRING) { + var stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_OID) { + var oid = new Buffer(12); + buffer.copy(oid, 0, index, index + 12); + object[name] = new ObjectID(oid); + index = index + 12; + } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { + object[name] = new Int32( + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) + ); + } else if (elementType === BSON.BSON_DATA_INT) { + object[name] = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { + object[name] = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_NUMBER) { + object[name] = buffer.readDoubleLE(index); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_DATE) { + var lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType === BSON.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); + object[name] = buffer[index++] === 1; + } else if (elementType === BSON.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new Error('bad embedded document length in bson'); + + // We have a raw value + if (raw) { + object[name] = buffer.slice(index, index + objectSize); + } else { + object[name] = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if (elementType === BSON.BSON_DATA_ARRAY) { + _index = index; + objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + var arrayOptions = options; + + // Stop index + var stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + object[name] = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); + if (index !== stopIndex) throw new Error('corrupted array bson'); + } else if (elementType === BSON.BSON_DATA_UNDEFINED) { + object[name] = undefined; + } else if (elementType === BSON.BSON_DATA_NULL) { + object[name] = null; + } else if (elementType === BSON.BSON_DATA_LONG) { + // Unpack the low and high bits + lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + object[name] = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } else { + object[name] = long; + } + } else if (elementType === BSON.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = new Buffer(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; + } else if (elementType === BSON.BSON_DATA_BINARY) { + var binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var totalBinarySize = binarySize; + var subType = buffer[index++]; + + // Did we have a negative binary size, throw + if (binarySize < 0) throw new Error('Negative binary type element size found'); + + // Is the length longer than the document + if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + if (promoteBuffers && promoteValues) { + object[name] = buffer.slice(index, index + binarySize); + } else { + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } + } else { + var _buffer = + typeof Uint8Array !== 'undefined' + ? new Uint8Array(new ArrayBuffer(binarySize)) + : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + + if (promoteBuffers && promoteValues) { + object[name] = _buffer; + } else { + object[name] = new Binary(_buffer, subType); + } + } + + // Update the index + index = index + binarySize; + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + source = buffer.toString('utf8', index, i); + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if (elementType === BSON.BSON_DATA_SYMBOL) { + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { + lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + object[name] = new Timestamp(lowBits, highBits); + } else if (elementType === BSON.BSON_DATA_MIN_KEY) { + object[name] = new MinKey(); + } else if (elementType === BSON.BSON_DATA_MAX_KEY) { + object[name] = new MaxKey(); + } else if (elementType === BSON.BSON_DATA_CODE) { + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString); + } + + // Update parse index position + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { + var totalSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new Error('code_w_scope total size shorter minimum expected length'); + } + + // Get the code string size + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + + // Javascript function + functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + _index = index; + // Decode the size of the object document + objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is to short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to short, truncating scope'); + } + + // Check if totalSize field is to long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to long, clips outer document'); + } + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } else if (elementType === BSON.BSON_DATA_DBPOINTER) { + // Get the code string size + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + // Namespace + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + + // Read the oid + var oidBuffer = new Buffer(12); + buffer.copy(oidBuffer, 0, index, index + 12); + oid = new ObjectID(oidBuffer); + + // Update the index + index = index + 12; + + // Split the namespace + var parts = namespace.split('.'); + var db = parts.shift(); + var collection = parts.join('.'); + // Upgrade to DBRef type + object[name] = new DBRef(collection, oid, db); + } else { + throw new Error( + 'Detected unknown BSON type ' + + elementType.toString(16) + + ' for fieldname "' + + name + + '", are you using the latest BSON parser' + ); + } + } + + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) throw new Error('corrupt array bson'); + throw new Error('corrupt object bson'); + } + + // Check if we have a db ref object + if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + return object; +}; + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if (functionCache[hash] == null) { + eval('value = ' + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +}; + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval('value = ' + functionString); + return value; +}; + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = (BSON.functionCache = {}); + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_DBPOINTER + **/ +BSON.BSON_DATA_DBPOINTER = 12; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ +BSON.BSON_DATA_DECIMAL128 = 19; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = deserialize; diff --git a/app/node_modules/bson/lib/bson/parser/serializer.js b/app/node_modules/bson/lib/bson/parser/serializer.js new file mode 100644 index 0000000..12c6b2d --- /dev/null +++ b/app/node_modules/bson/lib/bson/parser/serializer.js @@ -0,0 +1,1182 @@ +'use strict'; + +var writeIEEE754 = require('../float_parser').writeIEEE754, + Long = require('../long').Long, + MinKey = require('../min_key').MinKey, + Map = require('../map'), + Binary = require('../binary').Binary; + +var normalizedFunctionString = require('./utils').normalizedFunctionString; + +// try { +// var _Buffer = Uint8Array; +// } catch (e) { +// _Buffer = Buffer; +// } + +var regexp = /\x00/; // eslint-disable-line no-control-regex + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +}; + +var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +}; + +var serializeString = function(buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = ((size + 1) >> 24) & 0xff; + buffer[index + 2] = ((size + 1) >> 16) & 0xff; + buffer[index + 1] = ((size + 1) >> 8) & 0xff; + buffer[index] = (size + 1) & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +}; + +var serializeNumber = function(buffer, key, value, index, isArray) { + // We have an integer value + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; +}; + +var serializeNull = function(buffer, key, value, index, isArray) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +}; + +var serializeBoolean = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +}; + +var serializeDate = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +}; + +var serializeRegExp = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.global) buffer[index++] = 0x73; // s + if (value.ignoreCase) buffer[index++] = 0x69; // i + if (value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +}; + +var serializeBSONRegExp = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = + index + + buffer.write( + value.options + .split('') + .sort() + .join(''), + index, + 'utf8' + ); + // Add ending zero + buffer[index++] = 0x00; + return index; +}; + +var serializeMinMax = function(buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if (value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +}; + +var serializeObjectId = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, 'binary'); + } else if (value.id && value.id.copy) { + value.id.copy(buffer, index, 0, 12); + } else { + throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + + // Ajust index + return index + 12; +}; + +var serializeBuffer = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; +}; + +var serializeObject = function( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + isArray, + path +) { + for (var i = 0; i < path.length; i++) { + if (path[i] === value) throw new Error('cyclic dependency detected'); + } + + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto( + buffer, + value, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined, + path + ); + // Pop stack + path.pop(); + // Write size + return endIndex; +}; + +var serializeDecimal128 = function(buffer, key, value, index, isArray) { + buffer[index++] = BSON.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + value.bytes.copy(buffer, index, 0, 16); + return index + 16; +}; + +var serializeLong = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +}; + +var serializeInt32 = function(buffer, key, value, index, isArray) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; +}; + +var serializeDouble = function(buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; +}; + +var serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = normalizedFunctionString(value); + + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +}; + +var serializeCode = function( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + isArray +) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto( + buffer, + value.scope, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined + ); + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +}; + +var serializeBinary = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; +}; + +var serializeSymbol = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +}; + +var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if (null != value.db) { + endIndex = serializeInto( + buffer, + { + $ref: value.namespace, + $id: value.oid, + $db: value.db + }, + false, + index, + depth + 1, + serializeFunctions + ); + } else { + endIndex = serializeInto( + buffer, + { + $ref: value.namespace, + $id: value.oid + }, + false, + index, + depth + 1, + serializeFunctions + ); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +}; + +var serializeInto = function serializeInto( + buffer, + object, + checkKeys, + startingIndex, + depth, + serializeFunctions, + ignoreUndefined, + path +) { + startingIndex = startingIndex || 0; + path = path || []; + + // Push the object to the path + path.push(object); + + // Start place to serialize into + var index = startingIndex + 4; + // var self = this; + + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + var type = typeof value; + if (type === 'string') { + index = serializeString(buffer, key, value, index, true); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index, true); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + true + ); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true + ); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + } + } else if (object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if (done) continue; + + // Get the entry values + key = entry.value[0]; + value = entry.value[1]; + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (key !== '$db' && key !== '$ref' && key !== '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + // } else if (value === undefined && ignoreUndefined === true) { + } else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') + throw new Error('toBSON function did not return an object'); + } + + // Iterate over all the keys + for (key in object) { + value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (key !== '$db' && key !== '$ref' && key !== '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // Remove the path + path.pop(); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +}; + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +// var functionCache = (BSON.functionCache = {}); + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type, deprecated + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ +BSON.BSON_DATA_DECIMAL128 = 19; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = serializeInto; diff --git a/app/node_modules/bson/lib/bson/parser/utils.js b/app/node_modules/bson/lib/bson/parser/utils.js new file mode 100644 index 0000000..6b8395f --- /dev/null +++ b/app/node_modules/bson/lib/bson/parser/utils.js @@ -0,0 +1,14 @@ +'use strict'; + +/** + * Normalizes our expected stringified form of a function across versions of node + * @param {Function} fn The function to stringify + */ +function normalizedFunctionString(fn) { + return fn.toString().replace(/function *\(/, 'function ('); +} + +module.exports = { + normalizedFunctionString: normalizedFunctionString +}; + diff --git a/app/node_modules/bson/lib/bson/regexp.js b/app/node_modules/bson/lib/bson/regexp.js new file mode 100644 index 0000000..108f016 --- /dev/null +++ b/app/node_modules/bson/lib/bson/regexp.js @@ -0,0 +1,33 @@ +/** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ +function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern || ''; + this.options = options || ''; + + // Validate options + for (var i = 0; i < this.options.length; i++) { + if ( + !( + this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u' + ) + ) { + throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); + } + } +} + +module.exports = BSONRegExp; +module.exports.BSONRegExp = BSONRegExp; diff --git a/app/node_modules/bson/lib/bson/symbol.js b/app/node_modules/bson/lib/bson/symbol.js new file mode 100644 index 0000000..ba20cab --- /dev/null +++ b/app/node_modules/bson/lib/bson/symbol.js @@ -0,0 +1,50 @@ +// Custom inspect property name / symbol. +var inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect'; + +/** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @param {string} value the string representing the symbol. + * @return {Symbol} + */ +function Symbol(value) { + if (!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; +} + +/** + * Access the wrapped string value. + * + * @method + * @return {String} returns the wrapped string. + */ +Symbol.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toString = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype[inspect] = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toJSON = function() { + return this.value; +}; + +module.exports = Symbol; +module.exports.Symbol = Symbol; diff --git a/app/node_modules/bson/lib/bson/timestamp.js b/app/node_modules/bson/lib/bson/timestamp.js new file mode 100644 index 0000000..dc61a6c --- /dev/null +++ b/app/node_modules/bson/lib/bson/timestamp.js @@ -0,0 +1,854 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Timestamp. + * @param {number} high the high (signed) 32 bits of the Timestamp. + */ +function Timestamp(low, high) { + if (!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +} + +/** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ +Timestamp.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Timestamp.prototype.toNumber = function() { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Timestamp.prototype.toJSON = function() { + return this.toString(); +}; + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Timestamp.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Timestamp.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Timestamp.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Timestamp.prototype.getLowBitsUnsigned = function() { + return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ +Timestamp.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Timestamp.prototype.isZero = function() { + return this.high_ === 0 && this.low_ === 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Timestamp.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Timestamp.prototype.isOdd = function() { + return (this.low_ & 1) === 1; +}; + +/** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ +Timestamp.prototype.equals = function(other) { + return this.high_ === other.high_ && this.low_ === other.low_; +}; + +/** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ +Timestamp.prototype.notEquals = function(other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; +}; + +/** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ +Timestamp.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ +Timestamp.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ +Timestamp.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ +Timestamp.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Timestamp with the given one. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Timestamp.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Timestamp} the negation of this value. + */ +Timestamp.prototype.negate = function() { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } +}; + +/** + * Returns the sum of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ +Timestamp.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ +Timestamp.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ +Timestamp.prototype.multiply = function(other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate() + .multiply(other) + .negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Timestamp divided by the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ +Timestamp.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate() + .div(other) + .negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Timestamp modulo the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ +Timestamp.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ +Timestamp.prototype.not = function() { + return Timestamp.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ +Timestamp.prototype.and = function(other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ +Timestamp.prototype.or = function(other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ +Timestamp.prototype.xor = function(other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ +Timestamp.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); + } else { + return Timestamp.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ +Timestamp.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); + } else { + return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Timestamp.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); + } else if (numBits === 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp( + (value % Timestamp.TWO_PWR_32_DBL_) | 0, + (value / Timestamp.TWO_PWR_32_DBL_) | 0 + ); + } +}; + +/** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromBits = function(lowBits, highBits) { + return new Timestamp(lowBits, highBits); +}; + +/** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Timestamp. + * @param {number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromString = function(str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + +/** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @ignore + */ +Timestamp.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + +/** @type {Timestamp} */ +Timestamp.ZERO = Timestamp.fromInt(0); + +/** @type {Timestamp} */ +Timestamp.ONE = Timestamp.fromInt(1); + +/** @type {Timestamp} */ +Timestamp.NEG_ONE = Timestamp.fromInt(-1); + +/** @type {Timestamp} */ +Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); + +/** @type {Timestamp} */ +Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + +/** + * @type {Timestamp} + * @ignore + */ +Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Timestamp; +module.exports.Timestamp = Timestamp; diff --git a/app/node_modules/bson/package.json b/app/node_modules/bson/package.json new file mode 100644 index 0000000..da342c5 --- /dev/null +++ b/app/node_modules/bson/package.json @@ -0,0 +1,56 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "files": [ + "lib", + "index.js", + "browser_build", + "bower.json" + ], + "version": "1.0.9", + "author": "Christian Amor Kvalheim ", + "contributors": [], + "repository": "mongodb/js-bson", + "bugs": { + "mail": "node-mongodb-native@googlegroups.com", + "url": "https://github.com/mongodb/js-bson/issues" + }, + "devDependencies": { + "benchmark": "1.0.0", + "colors": "1.1.0", + "nodeunit": "0.9.0", + "babel-core": "^6.14.0", + "babel-loader": "^6.2.5", + "babel-polyfill": "^6.13.0", + "babel-preset-es2015": "^6.14.0", + "babel-preset-stage-0": "^6.5.0", + "babel-register": "^6.14.0", + "conventional-changelog-cli": "^1.3.5", + "webpack": "^1.13.2", + "webpack-polyfills-plugin": "0.0.9" + }, + "config": { + "native": false + }, + "main": "./index", + "directories": { + "lib": "./lib/bson" + }, + "engines": { + "node": ">=0.6.19" + }, + "scripts": { + "test": "nodeunit ./test/node", + "build": "webpack --config ./webpack.dist.config.js", + "changelog": "conventional-changelog -p angular -i HISTORY.md -s", + "lint": "eslint lib test", + "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'" + }, + "browser": "lib/bson/bson.js", + "license": "Apache-2.0" +} diff --git a/app/node_modules/buffer-shims/index.js b/app/node_modules/buffer-shims/index.js new file mode 100644 index 0000000..1cab4c0 --- /dev/null +++ b/app/node_modules/buffer-shims/index.js @@ -0,0 +1,108 @@ +'use strict'; + +var buffer = require('buffer'); +var Buffer = buffer.Buffer; +var SlowBuffer = buffer.SlowBuffer; +var MAX_LEN = buffer.kMaxLength || 2147483647; +exports.alloc = function alloc(size, fill, encoding) { + if (typeof Buffer.alloc === 'function') { + return Buffer.alloc(size, fill, encoding); + } + if (typeof encoding === 'number') { + throw new TypeError('encoding must not be number'); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + var enc = encoding; + var _fill = fill; + if (_fill === undefined) { + enc = undefined; + _fill = 0; + } + var buf = new Buffer(size); + if (typeof _fill === 'string') { + var fillBuf = new Buffer(_fill, enc); + var flen = fillBuf.length; + var i = -1; + while (++i < size) { + buf[i] = fillBuf[i % flen]; + } + } else { + buf.fill(_fill); + } + return buf; +} +exports.allocUnsafe = function allocUnsafe(size) { + if (typeof Buffer.allocUnsafe === 'function') { + return Buffer.allocUnsafe(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + return new Buffer(size); +} +exports.from = function from(value, encodingOrOffset, length) { + if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { + return Buffer.from(value, encodingOrOffset, length); + } + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number'); + } + if (typeof value === 'string') { + return new Buffer(value, encodingOrOffset); + } + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + var offset = encodingOrOffset; + if (arguments.length === 1) { + return new Buffer(value); + } + if (typeof offset === 'undefined') { + offset = 0; + } + var len = length; + if (typeof len === 'undefined') { + len = value.byteLength - offset; + } + if (offset >= value.byteLength) { + throw new RangeError('\'offset\' is out of bounds'); + } + if (len > value.byteLength - offset) { + throw new RangeError('\'length\' is out of bounds'); + } + return new Buffer(value.slice(offset, offset + len)); + } + if (Buffer.isBuffer(value)) { + var out = new Buffer(value.length); + value.copy(out, 0, 0, value.length); + return out; + } + if (value) { + if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { + return new Buffer(value); + } + if (value.type === 'Buffer' && Array.isArray(value.data)) { + return new Buffer(value.data); + } + } + + throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); +} +exports.allocUnsafeSlow = function allocUnsafeSlow(size) { + if (typeof Buffer.allocUnsafeSlow === 'function') { + return Buffer.allocUnsafeSlow(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size >= MAX_LEN) { + throw new RangeError('size is too large'); + } + return new SlowBuffer(size); +} diff --git a/app/node_modules/buffer-shims/license.md b/app/node_modules/buffer-shims/license.md new file mode 100644 index 0000000..01cfaef --- /dev/null +++ b/app/node_modules/buffer-shims/license.md @@ -0,0 +1,19 @@ +# Copyright (c) 2016 Calvin Metcalf + +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/app/node_modules/buffer-shims/package.json b/app/node_modules/buffer-shims/package.json new file mode 100644 index 0000000..be34aa4 --- /dev/null +++ b/app/node_modules/buffer-shims/package.json @@ -0,0 +1,18 @@ +{ + "name": "buffer-shims", + "version": "1.0.0", + "description": "some shims for node buffers", + "main": "index.js", + "scripts": { + "test": "tape test/*.js" + }, + "files": ["index.js"], + "license": "MIT", + "devDependencies": { + "tape": "^4.5.1" + }, + "repository": { + "type": "git", + "url": "git@github.com:calvinmetcalf/buffer-shims.git" + } +} diff --git a/app/node_modules/buffer-shims/readme.md b/app/node_modules/buffer-shims/readme.md new file mode 100644 index 0000000..7ea6475 --- /dev/null +++ b/app/node_modules/buffer-shims/readme.md @@ -0,0 +1,21 @@ +buffer-shims +=== + +functions to make sure the new buffer methods work in older browsers. + +```js +var bufferShim = require('buffer-shims'); +bufferShim.from('foo'); +bufferShim.alloc(9, 'cafeface', 'hex'); +bufferShim.allocUnsafe(15); +bufferShim.allocUnsafeSlow(21); +``` + +should just use the original in newer nodes and on older nodes uses fallbacks. + +Known Issues +=== +- this does not patch the buffer object, only the constructor stuff +- it's actually a polyfill + +![](https://i.imgur.com/zxII3jJ.gif) diff --git a/app/node_modules/bytes/History.md b/app/node_modules/bytes/History.md new file mode 100644 index 0000000..13d463a --- /dev/null +++ b/app/node_modules/bytes/History.md @@ -0,0 +1,82 @@ +3.0.0 / 2017-08-31 +================== + + * Change "kB" to "KB" in format output + * Remove support for Node.js 0.6 + * Remove support for ComponentJS + +2.5.0 / 2017-03-24 +================== + + * Add option "unit" + +2.4.0 / 2016-06-01 +================== + + * Add option "unitSeparator" + +2.3.0 / 2016-02-15 +================== + + * Drop partial bytes on all parsed units + * Fix non-finite numbers to `.format` to return `null` + * Fix parsing byte string that looks like hex + * perf: hoist regular expressions + +2.2.0 / 2015-11-13 +================== + + * add option "decimalPlaces" + * add option "fixedDecimals" + +2.1.0 / 2015-05-21 +================== + + * add `.format` export + * add `.parse` export + +2.0.2 / 2015-05-20 +================== + + * remove map recreation + * remove unnecessary object construction + +2.0.1 / 2015-05-07 +================== + + * fix browserify require + * remove node.extend dependency + +2.0.0 / 2015-04-12 +================== + + * add option "case" + * add option "thousandsSeparator" + * return "null" on invalid parse input + * support proper round-trip: bytes(bytes(num)) === num + * units no longer case sensitive when parsing + +1.0.0 / 2014-05-05 +================== + + * add negative support. fixes #6 + +0.3.0 / 2014-03-19 +================== + + * added terabyte support + +0.2.1 / 2013-04-01 +================== + + * add .component + +0.2.0 / 2012-10-28 +================== + + * bytes(200).should.eql('200b') + +0.1.0 / 2012-07-04 +================== + + * add bytes to string conversion [yields] diff --git a/app/node_modules/bytes/LICENSE b/app/node_modules/bytes/LICENSE new file mode 100644 index 0000000..63e95a9 --- /dev/null +++ b/app/node_modules/bytes/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015 Jed Watson + +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/app/node_modules/bytes/Readme.md b/app/node_modules/bytes/Readme.md new file mode 100644 index 0000000..9b53745 --- /dev/null +++ b/app/node_modules/bytes/Readme.md @@ -0,0 +1,125 @@ +# Bytes utility + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install bytes +``` + +## Usage + +```js +var bytes = require('bytes'); +``` + +#### bytes.format(number value, [options]): string|null + +Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is + rounded. + +**Arguments** + +| Name | Type | Description | +|---------|----------|--------------------| +| value | `number` | Value in bytes | +| options | `Object` | Conversion options | + +**Options** + +| Property | Type | Description | +|-------------------|--------|-----------------------------------------------------------------------------------------| +| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. | +| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` | +| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `.`... Default value to `''`. | +| unit | `string`|`null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). | +| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. | + +**Returns** + +| Name | Type | Description | +|---------|------------------|-------------------------------------------------| +| results | `string`|`null` | Return null upon error. String value otherwise. | + +**Example** + +```js +bytes(1024); +// output: '1KB' + +bytes(1000); +// output: '1000B' + +bytes(1000, {thousandsSeparator: ' '}); +// output: '1 000B' + +bytes(1024 * 1.7, {decimalPlaces: 0}); +// output: '2KB' + +bytes(1024, {unitSeparator: ' '}); +// output: '1 KB' + +``` + +#### bytes.parse(string|number value): number|null + +Parse the string value into an integer in bytes. If no unit is given, or `value` +is a number, it is assumed the value is in bytes. + +Supported units and abbreviations are as follows and are case-insensitive: + + * `b` for bytes + * `kb` for kilobytes + * `mb` for megabytes + * `gb` for gigabytes + * `tb` for terabytes + +The units are in powers of two, not ten. This means 1kb = 1024b according to this parser. + +**Arguments** + +| Name | Type | Description | +|---------------|--------|--------------------| +| value | `string`|`number` | String to parse, or number in bytes. | + +**Returns** + +| Name | Type | Description | +|---------|-------------|-------------------------| +| results | `number`|`null` | Return null upon error. Value in bytes otherwise. | + +**Example** + +```js +bytes('1KB'); +// output: 1024 + +bytes('1024'); +// output: 1024 + +bytes(1024); +// output: 1024 +``` + +## License + +[MIT](LICENSE) + +[downloads-image]: https://img.shields.io/npm/dm/bytes.svg +[downloads-url]: https://npmjs.org/package/bytes +[npm-image]: https://img.shields.io/npm/v/bytes.svg +[npm-url]: https://npmjs.org/package/bytes +[travis-image]: https://img.shields.io/travis/visionmedia/bytes.js/master.svg +[travis-url]: https://travis-ci.org/visionmedia/bytes.js +[coveralls-image]: https://img.shields.io/coveralls/visionmedia/bytes.js/master.svg +[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master diff --git a/app/node_modules/bytes/index.js b/app/node_modules/bytes/index.js new file mode 100644 index 0000000..1e39afd --- /dev/null +++ b/app/node_modules/bytes/index.js @@ -0,0 +1,159 @@ +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; + +/** + * Module variables. + * @private + */ + +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; + +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; + +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: ((1 << 30) * 1024) +}; + +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb)$/i; + +/** + * Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ + +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } + + if (typeof value === 'number') { + return format(value, options); + } + + return null; +} + +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public + */ + +function format(value, options) { + if (!Number.isFinite(value)) { + return null; + } + + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; + + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'KB'; + } else { + unit = 'B'; + } + } + + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); + + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } + + if (thousandsSeparator) { + str = str.replace(formatThousandsRegExp, thousandsSeparator); + } + + return str + unitSeparator + unit; +} + +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * + * @returns {number|null} + * @public + */ + +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; + } + + if (typeof val !== 'string') { + return null; + } + + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; + + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + + return Math.floor(map[unit] * floatValue); +} diff --git a/app/node_modules/bytes/package.json b/app/node_modules/bytes/package.json new file mode 100644 index 0000000..2193296 --- /dev/null +++ b/app/node_modules/bytes/package.json @@ -0,0 +1,39 @@ +{ + "name": "bytes", + "description": "Utility to parse a string bytes to bytes and vice-versa", + "version": "3.0.0", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "contributors": [ + "Jed Watson ", + "Théo FIDRY " + ], + "license": "MIT", + "keywords": [ + "byte", + "bytes", + "utility", + "parse", + "parser", + "convert", + "converter" + ], + "repository": "visionmedia/bytes.js", + "devDependencies": { + "mocha": "2.5.3", + "nyc": "10.3.2" + }, + "files": [ + "History.md", + "LICENSE", + "Readme.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "test": "mocha --check-leaks --reporter spec", + "test-ci": "nyc --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/app/node_modules/camelcase/index.js b/app/node_modules/camelcase/index.js new file mode 100644 index 0000000..929facb --- /dev/null +++ b/app/node_modules/camelcase/index.js @@ -0,0 +1,56 @@ +'use strict'; + +function preserveCamelCase(str) { + var isLastCharLower = false; + + for (var i = 0; i < str.length; i++) { + var c = str.charAt(i); + + if (isLastCharLower && (/[a-zA-Z]/).test(c) && c.toUpperCase() === c) { + str = str.substr(0, i) + '-' + str.substr(i); + isLastCharLower = false; + i++; + } else { + isLastCharLower = (c.toLowerCase() === c); + } + } + + return str; +} + +module.exports = function () { + var str = [].map.call(arguments, function (str) { + return str.trim(); + }).filter(function (str) { + return str.length; + }).join('-'); + + if (!str.length) { + return ''; + } + + if (str.length === 1) { + return str; + } + + if (!(/[_.\- ]+/).test(str)) { + if (str === str.toUpperCase()) { + return str.toLowerCase(); + } + + if (str[0] !== str[0].toLowerCase()) { + return str[0].toLowerCase() + str.slice(1); + } + + return str; + } + + str = preserveCamelCase(str); + + return str + .replace(/^[_.\- ]+/, '') + .toLowerCase() + .replace(/[_.\- ]+(\w|$)/g, function (m, p1) { + return p1.toUpperCase(); + }); +}; diff --git a/app/node_modules/camelcase/license b/app/node_modules/camelcase/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/app/node_modules/camelcase/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/app/node_modules/camelcase/package.json b/app/node_modules/camelcase/package.json new file mode 100644 index 0000000..6cee2b5 --- /dev/null +++ b/app/node_modules/camelcase/package.json @@ -0,0 +1,39 @@ +{ + "name": "camelcase", + "version": "2.1.1", + "description": "Convert a dash/dot/underscore/space separated string to camelCase: foo-bar → fooBar", + "license": "MIT", + "repository": "sindresorhus/camelcase", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "camelcase", + "camel-case", + "camel", + "case", + "dash", + "hyphen", + "dot", + "underscore", + "separator", + "string", + "text", + "convert" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + } +} diff --git a/app/node_modules/camelcase/readme.md b/app/node_modules/camelcase/readme.md new file mode 100644 index 0000000..080b2a1 --- /dev/null +++ b/app/node_modules/camelcase/readme.md @@ -0,0 +1,57 @@ +# camelcase [![Build Status](https://travis-ci.org/sindresorhus/camelcase.svg?branch=master)](https://travis-ci.org/sindresorhus/camelcase) + +> Convert a dash/dot/underscore/space separated string to camelCase: `foo-bar` → `fooBar` + + +## Install + +``` +$ npm install --save camelcase +``` + + +## Usage + +```js +const camelCase = require('camelcase'); + +camelCase('foo-bar'); +//=> 'fooBar' + +camelCase('foo_bar'); +//=> 'fooBar' + +camelCase('Foo-Bar'); +//=> 'fooBar' + +camelCase('--foo.bar'); +//=> 'fooBar' + +camelCase('__foo__bar__'); +//=> 'fooBar' + +camelCase('foo bar'); +//=> 'fooBar' + +console.log(process.argv[3]); +//=> '--foo-bar' +camelCase(process.argv[3]); +//=> 'fooBar' + +camelCase('foo', 'bar'); +//=> 'fooBar' + +camelCase('__foo__', '--bar'); +//=> 'fooBar' +``` + + +## Related + +- [decamelize](https://github.com/sindresorhus/decamelize) - The inverse of this module +- [uppercamelcase](https://github.com/SamVerschueren/uppercamelcase) - Like this module, but to PascalCase instead of camelCase + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/app/node_modules/cliui/CHANGELOG.md b/app/node_modules/cliui/CHANGELOG.md new file mode 100644 index 0000000..ef6a35e --- /dev/null +++ b/app/node_modules/cliui/CHANGELOG.md @@ -0,0 +1,15 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +# [3.2.0](https://github.com/yargs/cliui/compare/v3.1.2...v3.2.0) (2016-04-11) + + +### Bug Fixes + +* reduces tarball size ([acc6c33](https://github.com/yargs/cliui/commit/acc6c33)) + +### Features + +* adds standard-version for release management ([ff84e32](https://github.com/yargs/cliui/commit/ff84e32)) diff --git a/app/node_modules/cliui/LICENSE.txt b/app/node_modules/cliui/LICENSE.txt new file mode 100644 index 0000000..c7e2747 --- /dev/null +++ b/app/node_modules/cliui/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/app/node_modules/cliui/README.md b/app/node_modules/cliui/README.md new file mode 100644 index 0000000..028392c --- /dev/null +++ b/app/node_modules/cliui/README.md @@ -0,0 +1,110 @@ +# cliui + +[![Build Status](https://travis-ci.org/yargs/cliui.svg)](https://travis-ci.org/yargs/cliui) +[![Coverage Status](https://coveralls.io/repos/yargs/cliui/badge.svg?branch=)](https://coveralls.io/r/yargs/cliui?branch=) +[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) +[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) + +easily create complex multi-column command-line-interfaces. + +## Example + +```js +var ui = require('cliui')({ + width: 80 +}) + +ui.div('Usage: $0 [command] [options]') + +ui.div({ + text: 'Options:', + padding: [2, 0, 2, 0] +}) + +ui.div( + { + text: "-f, --file", + width: 20, + padding: [0, 4, 0, 4] + }, + { + text: "the file to load." + + chalk.green("(if this description is long it wraps).") + , + width: 20 + }, + { + text: chalk.red("[required]"), + align: 'right' + } +) + +console.log(ui.toString()) +``` + + + +## Layout DSL + +cliui exposes a simple layout DSL: + +If you create a single `ui.row`, passing a string rather than an +object: + +* `\n`: characters will be interpreted as new rows. +* `\t`: characters will be interpreted as new columns. +* `\s`: characters will be interpreted as padding. + +**as an example...** + +```js +var ui = require('./')({ + width: 60 +}) + +ui.div( + 'Usage: node ./bin/foo.js\n' + + ' \t provide a regex\n' + + ' \t provide a glob\t [required]' +) + +console.log(ui.toString()) +``` + +**will output:** + +```shell +Usage: node ./bin/foo.js + provide a regex + provide a glob [required] +``` + +## Methods + +```js +cliui = require('cliui') +``` + +### cliui({width: integer}) + +Specify the maximum width of the UI being generated. + +### cliui({wrap: boolean}) + +Enable or disable the wrapping of text in a column. + +### cliui.div(column, column, column) + +Create a row with any number of columns, a column +can either be a string, or an object with the following +options: + +* **width:** the width of a column. +* **align:** alignment, `right` or `center`. +* **padding:** `[top, right, bottom, left]`. +* **border:** should a border be placed around the div? + +### cliui.span(column, column, column) + +Similar to `div`, except the next row will be appended without +a new line being created. diff --git a/app/node_modules/cliui/index.js b/app/node_modules/cliui/index.js new file mode 100644 index 0000000..e501e78 --- /dev/null +++ b/app/node_modules/cliui/index.js @@ -0,0 +1,316 @@ +var stringWidth = require('string-width') +var stripAnsi = require('strip-ansi') +var wrap = require('wrap-ansi') +var align = { + right: alignRight, + center: alignCenter +} +var top = 0 +var right = 1 +var bottom = 2 +var left = 3 + +function UI (opts) { + this.width = opts.width + this.wrap = opts.wrap + this.rows = [] +} + +UI.prototype.span = function () { + var cols = this.div.apply(this, arguments) + cols.span = true +} + +UI.prototype.div = function () { + if (arguments.length === 0) this.div('') + if (this.wrap && this._shouldApplyLayoutDSL.apply(this, arguments)) { + return this._applyLayoutDSL(arguments[0]) + } + + var cols = [] + + for (var i = 0, arg; (arg = arguments[i]) !== undefined; i++) { + if (typeof arg === 'string') cols.push(this._colFromString(arg)) + else cols.push(arg) + } + + this.rows.push(cols) + return cols +} + +UI.prototype._shouldApplyLayoutDSL = function () { + return arguments.length === 1 && typeof arguments[0] === 'string' && + /[\t\n]/.test(arguments[0]) +} + +UI.prototype._applyLayoutDSL = function (str) { + var _this = this + var rows = str.split('\n') + var leftColumnWidth = 0 + + // simple heuristic for layout, make sure the + // second column lines up along the left-hand. + // don't allow the first column to take up more + // than 50% of the screen. + rows.forEach(function (row) { + var columns = row.split('\t') + if (columns.length > 1 && stringWidth(columns[0]) > leftColumnWidth) { + leftColumnWidth = Math.min( + Math.floor(_this.width * 0.5), + stringWidth(columns[0]) + ) + } + }) + + // generate a table: + // replacing ' ' with padding calculations. + // using the algorithmically generated width. + rows.forEach(function (row) { + var columns = row.split('\t') + _this.div.apply(_this, columns.map(function (r, i) { + return { + text: r.trim(), + padding: _this._measurePadding(r), + width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined + } + })) + }) + + return this.rows[this.rows.length - 1] +} + +UI.prototype._colFromString = function (str) { + return { + text: str, + padding: this._measurePadding(str) + } +} + +UI.prototype._measurePadding = function (str) { + // measure padding without ansi escape codes + var noAnsi = stripAnsi(str) + return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length] +} + +UI.prototype.toString = function () { + var _this = this + var lines = [] + + _this.rows.forEach(function (row, i) { + _this.rowToString(row, lines) + }) + + // don't display any lines with the + // hidden flag set. + lines = lines.filter(function (line) { + return !line.hidden + }) + + return lines.map(function (line) { + return line.text + }).join('\n') +} + +UI.prototype.rowToString = function (row, lines) { + var _this = this + var padding + var rrows = this._rasterize(row) + var str = '' + var ts + var width + var wrapWidth + + rrows.forEach(function (rrow, r) { + str = '' + rrow.forEach(function (col, c) { + ts = '' // temporary string used during alignment/padding. + width = row[c].width // the width with padding. + wrapWidth = _this._negatePadding(row[c]) // the width without padding. + + ts += col + + for (var i = 0; i < wrapWidth - stringWidth(col); i++) { + ts += ' ' + } + + // align the string within its column. + if (row[c].align && row[c].align !== 'left' && _this.wrap) { + ts = align[row[c].align](ts, wrapWidth) + if (stringWidth(ts) < wrapWidth) ts += new Array(width - stringWidth(ts)).join(' ') + } + + // apply border and padding to string. + padding = row[c].padding || [0, 0, 0, 0] + if (padding[left]) str += new Array(padding[left] + 1).join(' ') + str += addBorder(row[c], ts, '| ') + str += ts + str += addBorder(row[c], ts, ' |') + if (padding[right]) str += new Array(padding[right] + 1).join(' ') + + // if prior row is span, try to render the + // current row on the prior line. + if (r === 0 && lines.length > 0) { + str = _this._renderInline(str, lines[lines.length - 1]) + } + }) + + // remove trailing whitespace. + lines.push({ + text: str.replace(/ +$/, ''), + span: row.span + }) + }) + + return lines +} + +function addBorder (col, ts, style) { + if (col.border) { + if (/[.']-+[.']/.test(ts)) return '' + else if (ts.trim().length) return style + else return ' ' + } + return '' +} + +// if the full 'source' can render in +// the target line, do so. +UI.prototype._renderInline = function (source, previousLine) { + var leadingWhitespace = source.match(/^ */)[0].length + var target = previousLine.text + var targetTextWidth = stringWidth(target.trimRight()) + + if (!previousLine.span) return source + + // if we're not applying wrapping logic, + // just always append to the span. + if (!this.wrap) { + previousLine.hidden = true + return target + source + } + + if (leadingWhitespace < targetTextWidth) return source + + previousLine.hidden = true + + return target.trimRight() + new Array(leadingWhitespace - targetTextWidth + 1).join(' ') + source.trimLeft() +} + +UI.prototype._rasterize = function (row) { + var _this = this + var i + var rrow + var rrows = [] + var widths = this._columnWidths(row) + var wrapped + + // word wrap all columns, and create + // a data-structure that is easy to rasterize. + row.forEach(function (col, c) { + // leave room for left and right padding. + col.width = widths[c] + if (_this.wrap) wrapped = wrap(col.text, _this._negatePadding(col), {hard: true}).split('\n') + else wrapped = col.text.split('\n') + + if (col.border) { + wrapped.unshift('.' + new Array(_this._negatePadding(col) + 3).join('-') + '.') + wrapped.push("'" + new Array(_this._negatePadding(col) + 3).join('-') + "'") + } + + // add top and bottom padding. + if (col.padding) { + for (i = 0; i < (col.padding[top] || 0); i++) wrapped.unshift('') + for (i = 0; i < (col.padding[bottom] || 0); i++) wrapped.push('') + } + + wrapped.forEach(function (str, r) { + if (!rrows[r]) rrows.push([]) + + rrow = rrows[r] + + for (var i = 0; i < c; i++) { + if (rrow[i] === undefined) rrow.push('') + } + rrow.push(str) + }) + }) + + return rrows +} + +UI.prototype._negatePadding = function (col) { + var wrapWidth = col.width + if (col.padding) wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0) + if (col.border) wrapWidth -= 4 + return wrapWidth +} + +UI.prototype._columnWidths = function (row) { + var _this = this + var widths = [] + var unset = row.length + var unsetWidth + var remainingWidth = this.width + + // column widths can be set in config. + row.forEach(function (col, i) { + if (col.width) { + unset-- + widths[i] = col.width + remainingWidth -= col.width + } else { + widths[i] = undefined + } + }) + + // any unset widths should be calculated. + if (unset) unsetWidth = Math.floor(remainingWidth / unset) + widths.forEach(function (w, i) { + if (!_this.wrap) widths[i] = row[i].width || stringWidth(row[i].text) + else if (w === undefined) widths[i] = Math.max(unsetWidth, _minWidth(row[i])) + }) + + return widths +} + +// calculates the minimum width of +// a column, based on padding preferences. +function _minWidth (col) { + var padding = col.padding || [] + var minWidth = 1 + (padding[left] || 0) + (padding[right] || 0) + if (col.border) minWidth += 4 + return minWidth +} + +function alignRight (str, width) { + str = str.trim() + var padding = '' + var strWidth = stringWidth(str) + + if (strWidth < width) { + padding = new Array(width - strWidth + 1).join(' ') + } + + return padding + str +} + +function alignCenter (str, width) { + str = str.trim() + var padding = '' + var strWidth = stringWidth(str.trim()) + + if (strWidth < width) { + padding = new Array(parseInt((width - strWidth) / 2, 10) + 1).join(' ') + } + + return padding + str +} + +module.exports = function (opts) { + opts = opts || {} + + return new UI({ + width: (opts || {}).width || 80, + wrap: typeof opts.wrap === 'boolean' ? opts.wrap : true + }) +} diff --git a/app/node_modules/cliui/package.json b/app/node_modules/cliui/package.json new file mode 100644 index 0000000..31c654c --- /dev/null +++ b/app/node_modules/cliui/package.json @@ -0,0 +1,64 @@ +{ + "name": "cliui", + "version": "3.2.0", + "description": "easily create complex multi-column command-line-interfaces", + "main": "index.js", + "scripts": { + "pretest": "standard", + "test": "nyc mocha", + "coverage": "nyc --reporter=text-lcov mocha | coveralls", + "version": "standard-version" + }, + "repository": { + "type": "git", + "url": "http://github.com/yargs/cliui.git" + }, + "config": { + "blanket": { + "pattern": [ + "index.js" + ], + "data-cover-never": [ + "node_modules", + "test" + ], + "output-reporter": "spec" + } + }, + "standard": { + "ignore": [ + "**/example/**" + ], + "globals": [ + "it" + ] + }, + "keywords": [ + "cli", + "command-line", + "layout", + "design", + "console", + "wrap", + "table" + ], + "author": "Ben Coe ", + "license": "ISC", + "dependencies": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wrap-ansi": "^2.0.0" + }, + "devDependencies": { + "chai": "^3.5.0", + "chalk": "^1.1.2", + "coveralls": "^2.11.8", + "mocha": "^2.4.5", + "nyc": "^6.4.0", + "standard": "^6.0.8", + "standard-version": "^2.1.2" + }, + "files": [ + "index.js" + ] +} \ No newline at end of file diff --git a/app/node_modules/code-point-at/index.js b/app/node_modules/code-point-at/index.js new file mode 100644 index 0000000..0432fe6 --- /dev/null +++ b/app/node_modules/code-point-at/index.js @@ -0,0 +1,32 @@ +/* eslint-disable babel/new-cap, xo/throw-new-error */ +'use strict'; +module.exports = function (str, pos) { + if (str === null || str === undefined) { + throw TypeError(); + } + + str = String(str); + + var size = str.length; + var i = pos ? Number(pos) : 0; + + if (Number.isNaN(i)) { + i = 0; + } + + if (i < 0 || i >= size) { + return undefined; + } + + var first = str.charCodeAt(i); + + if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { + var second = str.charCodeAt(i + 1); + + if (second >= 0xDC00 && second <= 0xDFFF) { + return ((first - 0xD800) * 0x400) + second - 0xDC00 + 0x10000; + } + } + + return first; +}; diff --git a/app/node_modules/code-point-at/license b/app/node_modules/code-point-at/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/app/node_modules/code-point-at/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/app/node_modules/code-point-at/package.json b/app/node_modules/code-point-at/package.json new file mode 100644 index 0000000..c5907a5 --- /dev/null +++ b/app/node_modules/code-point-at/package.json @@ -0,0 +1,38 @@ +{ + "name": "code-point-at", + "version": "1.1.0", + "description": "ES2015 `String#codePointAt()` ponyfill", + "license": "MIT", + "repository": "sindresorhus/code-point-at", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "es2015", + "ponyfill", + "polyfill", + "shim", + "string", + "str", + "code", + "point", + "at", + "codepoint", + "unicode" + ], + "devDependencies": { + "ava": "*", + "xo": "^0.16.0" + } +} diff --git a/app/node_modules/code-point-at/readme.md b/app/node_modules/code-point-at/readme.md new file mode 100644 index 0000000..4c97730 --- /dev/null +++ b/app/node_modules/code-point-at/readme.md @@ -0,0 +1,32 @@ +# code-point-at [![Build Status](https://travis-ci.org/sindresorhus/code-point-at.svg?branch=master)](https://travis-ci.org/sindresorhus/code-point-at) + +> ES2015 [`String#codePointAt()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) [ponyfill](https://ponyfill.com) + + +## Install + +``` +$ npm install --save code-point-at +``` + + +## Usage + +```js +var codePointAt = require('code-point-at'); + +codePointAt('🐴'); +//=> 128052 + +codePointAt('abc', 2); +//=> 99 +``` + +## API + +### codePointAt(input, [position]) + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/app/node_modules/colors/.travis.yml b/app/node_modules/colors/.travis.yml new file mode 100644 index 0000000..ec43125 --- /dev/null +++ b/app/node_modules/colors/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.8" + - "0.6" \ No newline at end of file diff --git a/app/node_modules/colors/MIT-LICENSE.txt b/app/node_modules/colors/MIT-LICENSE.txt new file mode 100644 index 0000000..3de4e33 --- /dev/null +++ b/app/node_modules/colors/MIT-LICENSE.txt @@ -0,0 +1,23 @@ +Original Library + - Copyright (c) Marak Squires + +Additional Functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/app/node_modules/colors/ReadMe.md b/app/node_modules/colors/ReadMe.md new file mode 100644 index 0000000..beb5b14 --- /dev/null +++ b/app/node_modules/colors/ReadMe.md @@ -0,0 +1,167 @@ +# colors.js + +## get color and style in your node.js console + + + +## Installation + + npm install colors + +## colors and styles! + +### text colors + + - black + - red + - green + - yellow + - blue + - magenta + - cyan + - white + - gray + - grey + +### background colors + + + + - bgBlack + - bgRed + - bgGreen + - bgYellow + - bgBlue + - bgMagenta + - bgCyan + - bgWhite + +### styles + + - reset + - bold + - dim + - italic + - underline + - inverse + - hidden + - strikethrough + +### extras + + - rainbow + - zebra + - america + - trap + - random + + +## Usage + +By popular demand, `colors` now ships with two types of usages! + +The super nifty way + +```js +var colors = require('colors'); + +console.log('hello'.green); // outputs green text +console.log('i like cake and pies'.underline.red) // outputs red underlined text +console.log('inverse the color'.inverse); // inverses the color +console.log('OMG Rainbows!'.rainbow); // rainbow +console.log('Run the trap'.trap); // Drops the bass + +``` + +or a slightly less nifty way which doesn't extend `String.prototype` + +```js +var colors = require('colors/safe'); + +console.log(colors.green('hello')); // outputs green text +console.log(colors.red.underline('i like cake and pies')) // outputs red underlined text +console.log(colors.inverse('inverse the color')); // inverses the color +console.log(colors.rainbow('OMG Rainbows!')); // rainbow +console.log(colors.trap('Run the trap')); // Drops the bass + +``` + +I prefer the first way. Some people seem to be afraid of extending `String.prototype` and prefer the second way. + +If you are writing good code you will never have an issue with the first approach. If you really don't want to touch `String.prototype`, the second usage will not touch `String` native object. + +## Disabling Colors + +To disable colors you can pass the following arguments in the command line to your application: + +```bash +node myapp.js --no-color +``` + +## Console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data) + +```js +var name = 'Marak'; +console.log(colors.green('Hello %s'), name); +// outputs -> 'Hello Marak' +``` + +## Custom themes + +### Using standard API + +```js + +var colors = require('colors'); + +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log("this is an error".error); + +// outputs yellow text +console.log("this is a warning".warn); +``` + +### Using string safe API + +```js +var colors = require('colors/safe'); + +// set single property +var error = colors.red; +error('this is red'); + +// set theme +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log(colors.error("this is an error")); + +// outputs yellow text +console.log(colors.warn("this is a warning")); +``` + +*Protip: There is a secret undocumented style in `colors`. If you find the style you can summon him.* \ No newline at end of file diff --git a/app/node_modules/colors/examples/normal-usage.js b/app/node_modules/colors/examples/normal-usage.js new file mode 100644 index 0000000..2818741 --- /dev/null +++ b/app/node_modules/colors/examples/normal-usage.js @@ -0,0 +1,74 @@ +var colors = require('../lib/index'); + +console.log("First some yellow text".yellow); + +console.log("Underline that text".yellow.underline); + +console.log("Make it bold and red".red.bold); + +console.log(("Double Raindows All Day Long").rainbow) + +console.log("Drop the bass".trap) + +console.log("DROP THE RAINBOW BASS".trap.rainbow) + + +console.log('Chains are also cool.'.bold.italic.underline.red); // styles not widely supported + +console.log('So '.green + 'are'.underline + ' ' + 'inverse'.inverse + ' styles! '.yellow.bold); // styles not widely supported +console.log("Zebras are so fun!".zebra); + +// +// Remark: .strikethrough may not work with Mac OS Terminal App +// +console.log("This is " + "not".strikethrough + " fun."); + +console.log('Background color attack!'.black.bgWhite) +console.log('Use random styles on everything!'.random) +console.log('America, Heck Yeah!'.america) + + +console.log('Setting themes is useful') + +// +// Custom themes +// +console.log('Generic logging theme as JSON'.green.bold.underline); +// Load theme with JSON literal +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log("this is an error".error); + +// outputs yellow text +console.log("this is a warning".warn); + +// outputs grey text +console.log("this is an input".input); + +console.log('Generic logging theme as file'.green.bold.underline); + +// Load a theme from file +colors.setTheme(__dirname + '/../themes/generic-logging.js'); + +// outputs red text +console.log("this is an error".error); + +// outputs yellow text +console.log("this is a warning".warn); + +// outputs grey text +console.log("this is an input".input); + +//console.log("Don't summon".zalgo) \ No newline at end of file diff --git a/app/node_modules/colors/examples/safe-string.js b/app/node_modules/colors/examples/safe-string.js new file mode 100644 index 0000000..111b363 --- /dev/null +++ b/app/node_modules/colors/examples/safe-string.js @@ -0,0 +1,76 @@ +var colors = require('../safe'); + +console.log(colors.yellow("First some yellow text")); + +console.log(colors.yellow.underline("Underline that text")); + +console.log(colors.red.bold("Make it bold and red")); + +console.log(colors.rainbow("Double Raindows All Day Long")) + +console.log(colors.trap("Drop the bass")) + +console.log(colors.rainbow(colors.trap("DROP THE RAINBOW BASS"))); + +console.log(colors.bold.italic.underline.red('Chains are also cool.')); // styles not widely supported + + +console.log(colors.green('So ') + colors.underline('are') + ' ' + colors.inverse('inverse') + colors.yellow.bold(' styles! ')); // styles not widely supported + +console.log(colors.zebra("Zebras are so fun!")); + +console.log("This is " + colors.strikethrough("not") + " fun."); + + +console.log(colors.black.bgWhite('Background color attack!')); +console.log(colors.random('Use random styles on everything!')) +console.log(colors.america('America, Heck Yeah!')); + +console.log('Setting themes is useful') + +// +// Custom themes +// +//console.log('Generic logging theme as JSON'.green.bold.underline); +// Load theme with JSON literal +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log(colors.error("this is an error")); + +// outputs yellow text +console.log(colors.warn("this is a warning")); + +// outputs grey text +console.log(colors.input("this is an input")); + + +// console.log('Generic logging theme as file'.green.bold.underline); + +// Load a theme from file +colors.setTheme(__dirname + '/../themes/generic-logging.js'); + +// outputs red text +console.log(colors.error("this is an error")); + +// outputs yellow text +console.log(colors.warn("this is a warning")); + +// outputs grey text +console.log(colors.input("this is an input")); + +// console.log(colors.zalgo("Don't summon him")) + + + diff --git a/app/node_modules/colors/lib/colors.js b/app/node_modules/colors/lib/colors.js new file mode 100644 index 0000000..59898de --- /dev/null +++ b/app/node_modules/colors/lib/colors.js @@ -0,0 +1,176 @@ +/* + +The MIT License (MIT) + +Original Library + - Copyright (c) Marak Squires + +Additional functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +var colors = {}; +module['exports'] = colors; + +colors.themes = {}; + +var ansiStyles = colors.styles = require('./styles'); +var defineProps = Object.defineProperties; + +colors.supportsColor = require('./system/supports-colors'); + +if (typeof colors.enabled === "undefined") { + colors.enabled = colors.supportsColor; +} + +colors.stripColors = colors.strip = function(str){ + return ("" + str).replace(/\x1B\[\d+m/g, ''); +}; + + +var stylize = colors.stylize = function stylize (str, style) { + return ansiStyles[style].open + str + ansiStyles[style].close; +} + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +var escapeStringRegexp = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + return str.replace(matchOperatorsRe, '\\$&'); +} + +function build(_styles) { + var builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + builder._styles = _styles; + // __proto__ is used because we must return a function, but there is + // no way to create a function with a different prototype. + builder.__proto__ = proto; + return builder; +} + +var styles = (function () { + var ret = {}; + ansiStyles.grey = ansiStyles.gray; + Object.keys(ansiStyles).forEach(function (key) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + ret[key] = { + get: function () { + return build(this._styles.concat(key)); + } + }; + }); + return ret; +})(); + +var proto = defineProps(function colors() {}, styles); + +function applyStyle() { + var args = arguments; + var argsLen = args.length; + var str = argsLen !== 0 && String(arguments[0]); + if (argsLen > 1) { + for (var a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!colors.enabled || !str) { + return str; + } + + var nestedStyles = this._styles; + + var i = nestedStyles.length; + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + str = code.open + str.replace(code.closeRe, code.open) + code.close; + } + + return str; +} + +function applyTheme (theme) { + for (var style in theme) { + (function(style){ + colors[style] = function(str){ + return colors[theme[style]](str); + }; + })(style) + } +} + +colors.setTheme = function (theme) { + if (typeof theme === 'string') { + try { + colors.themes[theme] = require(theme); + applyTheme(colors.themes[theme]); + return colors.themes[theme]; + } catch (err) { + console.log(err); + return err; + } + } else { + applyTheme(theme); + } +}; + +function init() { + var ret = {}; + Object.keys(styles).forEach(function (name) { + ret[name] = { + get: function () { + return build([name]); + } + }; + }); + return ret; +} + +var sequencer = function sequencer (map, str) { + var exploded = str.split(""), i = 0; + exploded = exploded.map(map); + return exploded.join(""); +}; + +// custom formatter methods +colors.trap = require('./custom/trap'); +colors.zalgo = require('./custom/zalgo'); + +// maps +colors.maps = {}; +colors.maps.america = require('./maps/america'); +colors.maps.zebra = require('./maps/zebra'); +colors.maps.rainbow = require('./maps/rainbow'); +colors.maps.random = require('./maps/random') + +for (var map in colors.maps) { + (function(map){ + colors[map] = function (str) { + return sequencer(colors.maps[map], str); + } + })(map) +} + +defineProps(colors, init()); \ No newline at end of file diff --git a/app/node_modules/colors/lib/custom/trap.js b/app/node_modules/colors/lib/custom/trap.js new file mode 100644 index 0000000..3f09143 --- /dev/null +++ b/app/node_modules/colors/lib/custom/trap.js @@ -0,0 +1,45 @@ +module['exports'] = function runTheTrap (text, options) { + var result = ""; + text = text || "Run the trap, drop the bass"; + text = text.split(''); + var trap = { + a: ["\u0040", "\u0104", "\u023a", "\u0245", "\u0394", "\u039b", "\u0414"], + b: ["\u00df", "\u0181", "\u0243", "\u026e", "\u03b2", "\u0e3f"], + c: ["\u00a9", "\u023b", "\u03fe"], + d: ["\u00d0", "\u018a", "\u0500" , "\u0501" ,"\u0502", "\u0503"], + e: ["\u00cb", "\u0115", "\u018e", "\u0258", "\u03a3", "\u03be", "\u04bc", "\u0a6c"], + f: ["\u04fa"], + g: ["\u0262"], + h: ["\u0126", "\u0195", "\u04a2", "\u04ba", "\u04c7", "\u050a"], + i: ["\u0f0f"], + j: ["\u0134"], + k: ["\u0138", "\u04a0", "\u04c3", "\u051e"], + l: ["\u0139"], + m: ["\u028d", "\u04cd", "\u04ce", "\u0520", "\u0521", "\u0d69"], + n: ["\u00d1", "\u014b", "\u019d", "\u0376", "\u03a0", "\u048a"], + o: ["\u00d8", "\u00f5", "\u00f8", "\u01fe", "\u0298", "\u047a", "\u05dd", "\u06dd", "\u0e4f"], + p: ["\u01f7", "\u048e"], + q: ["\u09cd"], + r: ["\u00ae", "\u01a6", "\u0210", "\u024c", "\u0280", "\u042f"], + s: ["\u00a7", "\u03de", "\u03df", "\u03e8"], + t: ["\u0141", "\u0166", "\u0373"], + u: ["\u01b1", "\u054d"], + v: ["\u05d8"], + w: ["\u0428", "\u0460", "\u047c", "\u0d70"], + x: ["\u04b2", "\u04fe", "\u04fc", "\u04fd"], + y: ["\u00a5", "\u04b0", "\u04cb"], + z: ["\u01b5", "\u0240"] + } + text.forEach(function(c){ + c = c.toLowerCase(); + var chars = trap[c] || [" "]; + var rand = Math.floor(Math.random() * chars.length); + if (typeof trap[c] !== "undefined") { + result += trap[c][rand]; + } else { + result += c; + } + }); + return result; + +} diff --git a/app/node_modules/colors/lib/custom/zalgo.js b/app/node_modules/colors/lib/custom/zalgo.js new file mode 100644 index 0000000..4dc20c8 --- /dev/null +++ b/app/node_modules/colors/lib/custom/zalgo.js @@ -0,0 +1,104 @@ +// please no +module['exports'] = function zalgo(text, options) { + text = text || " he is here "; + var soul = { + "up" : [ + '̍', '̎', '̄', '̅', + '̿', '̑', '̆', '̐', + '͒', '͗', '͑', '̇', + '̈', '̊', '͂', '̓', + '̈', '͊', '͋', '͌', + '̃', '̂', '̌', '͐', + '̀', '́', '̋', '̏', + '̒', '̓', '̔', '̽', + '̉', 'ͣ', 'ͤ', 'ͥ', + 'ͦ', 'ͧ', 'ͨ', 'ͩ', + 'ͪ', 'ͫ', 'ͬ', 'ͭ', + 'ͮ', 'ͯ', '̾', '͛', + '͆', '̚' + ], + "down" : [ + '̖', '̗', '̘', '̙', + '̜', '̝', '̞', '̟', + '̠', '̤', '̥', '̦', + '̩', '̪', '̫', '̬', + '̭', '̮', '̯', '̰', + '̱', '̲', '̳', '̹', + '̺', '̻', '̼', 'ͅ', + '͇', '͈', '͉', '͍', + '͎', '͓', '͔', '͕', + '͖', '͙', '͚', '̣' + ], + "mid" : [ + '̕', '̛', '̀', '́', + '͘', '̡', '̢', '̧', + '̨', '̴', '̵', '̶', + '͜', '͝', '͞', + '͟', '͠', '͢', '̸', + '̷', '͡', ' ҉' + ] + }, + all = [].concat(soul.up, soul.down, soul.mid), + zalgo = {}; + + function randomNumber(range) { + var r = Math.floor(Math.random() * range); + return r; + } + + function is_char(character) { + var bool = false; + all.filter(function (i) { + bool = (i === character); + }); + return bool; + } + + + function heComes(text, options) { + var result = '', counts, l; + options = options || {}; + options["up"] = options["up"] || true; + options["mid"] = options["mid"] || true; + options["down"] = options["down"] || true; + options["size"] = options["size"] || "maxi"; + text = text.split(''); + for (l in text) { + if (is_char(l)) { + continue; + } + result = result + text[l]; + counts = {"up" : 0, "down" : 0, "mid" : 0}; + switch (options.size) { + case 'mini': + counts.up = randomNumber(8); + counts.min = randomNumber(2); + counts.down = randomNumber(8); + break; + case 'maxi': + counts.up = randomNumber(16) + 3; + counts.min = randomNumber(4) + 1; + counts.down = randomNumber(64) + 3; + break; + default: + counts.up = randomNumber(8) + 1; + counts.mid = randomNumber(6) / 2; + counts.down = randomNumber(8) + 1; + break; + } + + var arr = ["up", "mid", "down"]; + for (var d in arr) { + var index = arr[d]; + for (var i = 0 ; i <= counts[index]; i++) { + if (options[index]) { + result = result + soul[index][randomNumber(soul[index].length)]; + } + } + } + } + return result; + } + // don't summon him + return heComes(text); +} diff --git a/app/node_modules/colors/lib/extendStringPrototype.js b/app/node_modules/colors/lib/extendStringPrototype.js new file mode 100644 index 0000000..b6b5b03 --- /dev/null +++ b/app/node_modules/colors/lib/extendStringPrototype.js @@ -0,0 +1,118 @@ +var colors = require('./colors'), + styles = require('./styles'); + +module['exports'] = function () { + + // + // Extends prototype of native string object to allow for "foo".red syntax + // + var addProperty = function (color, func) { + String.prototype.__defineGetter__(color, func); + }; + + var sequencer = function sequencer (map, str) { + return function () { + var exploded = this.split(""), i = 0; + exploded = exploded.map(map); + return exploded.join(""); + } + }; + + var stylize = function stylize (str, style) { + return styles[style].open + str + styles[style].close; + } + + addProperty('strip', function () { + return colors.strip(this); + }); + + addProperty('stripColors', function () { + return colors.strip(this); + }); + + addProperty("trap", function(){ + return colors.trap(this); + }); + + addProperty("zalgo", function(){ + return colors.zalgo(this); + }); + + addProperty("zebra", function(){ + return colors.zebra(this); + }); + + addProperty("rainbow", function(){ + return colors.rainbow(this); + }); + + addProperty("random", function(){ + return colors.random(this); + }); + + addProperty("america", function(){ + return colors.america(this); + }); + + // + // Iterate through all default styles and colors + // + var x = Object.keys(colors.styles); + x.forEach(function (style) { + addProperty(style, function () { + return stylize(this, style); + }); + }); + + function applyTheme(theme) { + // + // Remark: This is a list of methods that exist + // on String that you should not overwrite. + // + var stringPrototypeBlacklist = [ + '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', 'charAt', 'constructor', + 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf', 'charCodeAt', + 'indexOf', 'lastIndexof', 'length', 'localeCompare', 'match', 'replace', 'search', 'slice', 'split', 'substring', + 'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight' + ]; + + Object.keys(theme).forEach(function (prop) { + if (stringPrototypeBlacklist.indexOf(prop) !== -1) { + console.log('warn: '.red + ('String.prototype' + prop).magenta + ' is probably something you don\'t want to override. Ignoring style name'); + } + else { + if (typeof(theme[prop]) === 'string') { + colors[prop] = colors[theme[prop]]; + addProperty(prop, function () { + return colors[theme[prop]](this); + }); + } + else { + addProperty(prop, function () { + var ret = this; + for (var t = 0; t < theme[prop].length; t++) { + ret = exports[theme[prop][t]](ret); + } + return ret; + }); + } + } + }); + } + + colors.setTheme = function (theme) { + if (typeof theme === 'string') { + try { + colors.themes[theme] = require(theme); + applyTheme(colors.themes[theme]); + return colors.themes[theme]; + } catch (err) { + console.log(err); + return err; + } + } else { + applyTheme(theme); + } + }; + +}; \ No newline at end of file diff --git a/app/node_modules/colors/lib/index.js b/app/node_modules/colors/lib/index.js new file mode 100644 index 0000000..96d2b84 --- /dev/null +++ b/app/node_modules/colors/lib/index.js @@ -0,0 +1,12 @@ +var colors = require('./colors'); +module['exports'] = colors; + +// Remark: By default, colors will add style properties to String.prototype +// +// If you don't wish to extend String.prototype you can do this instead and native String will not be touched +// +// var colors = require('colors/safe); +// colors.red("foo") +// +// +var extendStringPrototype = require('./extendStringPrototype')(); \ No newline at end of file diff --git a/app/node_modules/colors/lib/maps/america.js b/app/node_modules/colors/lib/maps/america.js new file mode 100644 index 0000000..a07d832 --- /dev/null +++ b/app/node_modules/colors/lib/maps/america.js @@ -0,0 +1,12 @@ +var colors = require('../colors'); + +module['exports'] = (function() { + return function (letter, i, exploded) { + if(letter === " ") return letter; + switch(i%3) { + case 0: return colors.red(letter); + case 1: return colors.white(letter) + case 2: return colors.blue(letter) + } + } +})(); \ No newline at end of file diff --git a/app/node_modules/colors/lib/maps/rainbow.js b/app/node_modules/colors/lib/maps/rainbow.js new file mode 100644 index 0000000..a7ce24e --- /dev/null +++ b/app/node_modules/colors/lib/maps/rainbow.js @@ -0,0 +1,13 @@ +var colors = require('../colors'); + +module['exports'] = (function () { + var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; //RoY G BiV + return function (letter, i, exploded) { + if (letter === " ") { + return letter; + } else { + return colors[rainbowColors[i++ % rainbowColors.length]](letter); + } + }; +})(); + diff --git a/app/node_modules/colors/lib/maps/random.js b/app/node_modules/colors/lib/maps/random.js new file mode 100644 index 0000000..5cd101f --- /dev/null +++ b/app/node_modules/colors/lib/maps/random.js @@ -0,0 +1,8 @@ +var colors = require('../colors'); + +module['exports'] = (function () { + var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta']; + return function(letter, i, exploded) { + return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 1))]](letter); + }; +})(); \ No newline at end of file diff --git a/app/node_modules/colors/lib/maps/zebra.js b/app/node_modules/colors/lib/maps/zebra.js new file mode 100644 index 0000000..bf7dcde --- /dev/null +++ b/app/node_modules/colors/lib/maps/zebra.js @@ -0,0 +1,5 @@ +var colors = require('../colors'); + +module['exports'] = function (letter, i, exploded) { + return i % 2 === 0 ? letter : colors.inverse(letter); +}; \ No newline at end of file diff --git a/app/node_modules/colors/lib/styles.js b/app/node_modules/colors/lib/styles.js new file mode 100644 index 0000000..067d590 --- /dev/null +++ b/app/node_modules/colors/lib/styles.js @@ -0,0 +1,77 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +var styles = {}; +module['exports'] = styles; + +var codes = { + reset: [0, 0], + + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + grey: [90, 39], + + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // legacy styles for colors pre v1.0.0 + blackBG: [40, 49], + redBG: [41, 49], + greenBG: [42, 49], + yellowBG: [43, 49], + blueBG: [44, 49], + magentaBG: [45, 49], + cyanBG: [46, 49], + whiteBG: [47, 49] + +}; + +Object.keys(codes).forEach(function (key) { + var val = codes[key]; + var style = styles[key] = []; + style.open = '\u001b[' + val[0] + 'm'; + style.close = '\u001b[' + val[1] + 'm'; +}); \ No newline at end of file diff --git a/app/node_modules/colors/lib/system/supports-colors.js b/app/node_modules/colors/lib/system/supports-colors.js new file mode 100644 index 0000000..3e008aa --- /dev/null +++ b/app/node_modules/colors/lib/system/supports-colors.js @@ -0,0 +1,61 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +var argv = process.argv; + +module.exports = (function () { + if (argv.indexOf('--no-color') !== -1 || + argv.indexOf('--color=false') !== -1) { + return false; + } + + if (argv.indexOf('--color') !== -1 || + argv.indexOf('--color=true') !== -1 || + argv.indexOf('--color=always') !== -1) { + return true; + } + + if (process.stdout && !process.stdout.isTTY) { + return false; + } + + if (process.platform === 'win32') { + return true; + } + + if ('COLORTERM' in process.env) { + return true; + } + + if (process.env.TERM === 'dumb') { + return false; + } + + if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { + return true; + } + + return false; +})(); \ No newline at end of file diff --git a/app/node_modules/colors/package.json b/app/node_modules/colors/package.json new file mode 100644 index 0000000..dc6ce6b --- /dev/null +++ b/app/node_modules/colors/package.json @@ -0,0 +1,21 @@ +{ + "name": "colors", + "description": "get colors in your node.js console", + "version": "1.0.3", + "author": "Marak Squires", + "homepage": "https://github.com/Marak/colors.js", + "bugs": "https://github.com/Marak/colors.js/issues", + "keywords": [ "ansi", "terminal", "colors" ], + "repository": { + "type": "git", + "url": "http://github.com/Marak/colors.js.git" + }, + "license": "MIT", + "scripts": { + "test": "node tests/basic-test.js && node tests/safe-test.js" + }, + "engines": { + "node": ">=0.1.90" + }, + "main": "./lib/index" +} diff --git a/app/node_modules/colors/safe.js b/app/node_modules/colors/safe.js new file mode 100644 index 0000000..a6a1f3a --- /dev/null +++ b/app/node_modules/colors/safe.js @@ -0,0 +1,9 @@ +// +// Remark: Requiring this file will use the "safe" colors API which will not touch String.prototype +// +// var colors = require('colors/safe); +// colors.red("foo") +// +// +var colors = require('./lib/colors'); +module['exports'] = colors; \ No newline at end of file diff --git a/app/node_modules/colors/screenshots/colors.png b/app/node_modules/colors/screenshots/colors.png new file mode 100644 index 0000000000000000000000000000000000000000..7200a623590c35e8b4a8e74a8df49a42998ca9c5 GIT binary patch literal 79787 zcmZ^~V{~RgurB<@wrx#p+nFS9oJ?%nwylXKnAo;$+qP|ebMT#e*1GHNU)@#pRPCx> ztM}^aXGbW=OCrGH!U6yQ1ZgQTB>(`F0{{Rih6ep7p@odZ0RXV6EJQ^Wq(w!E6&&qM zEv!ud01cQ*4>!J)?eFi_D~s#S=PfV0x@T*L_4^^4WJQ?}Y8aec5fqtzXle7m#uVf* zh2b(JIJf+6`=4LlgxlNC-P@1u8_SO!y2l>6$1b|Z+Q%JJ=aBy8*~lm;k%j=`Xlyyh z4HNR6t6D99APkc~7%>3C99lpTCG_cOY3IA6D^7^ABYQm2ice5@O$K1VQy>6b575#J|Ra2{p#(02es-8l?%)x6@hW+*8TF^>Ju^g+wH64eIt*Cv1bgCV?ARB-QR9Ga zz3{pqc7=Qg=Xkqfiwuxr%!0X9D zl>p0sZLYApo!Zm;7+wNss6WNo<_j(ji^K?i-|+<{O8edB@N9iAyliu%2e{3Ef%xIT zvculPYWbaiuN!63Oo5xlvi3{o&Cj@;FgQcCL2X8Mfq~CF&&r+XKJc@A87*(CK`V$n z!LIfz_P~11A`N_al6~1+cXy!QBkjjQ^3d?8?m%0i2t(7sy%j?&>#0F~GSV~0?;>cy zhiaGm4eiJ2U^AcSs79kmV7=kIVfTmbg4SVUoH&R^3*dvPQh&Okf46hi^?au`8~Hs_ zfOmv_LPtIEVj~=*G9ku=lR-d$OTc0GEzSWYdIC?#sL1{n{4D_;v0_XI>#5tXX2&o% z|5nHJ#RF7&axL3@|9;&8F-L~H)h5bK*h{7LG#l7qdq%@Q06wm;<@k=myX*!D05Gz94d-fcKI$K(qEm+>qskv*iVw6MKf!7{+js5{6@;`XeV` zlcR8l8WXRMcod+QirA7&N!(#-4diR64Km~4Nnu9K59t_FaL6;efG;7^^J*# zAS;YPbU9CJN839#TZA!hnVAcoRRTZ;Cpm||A9&j|$^_M7dJjnN{-!op(E9Kqae zUSi&KPHk4;Z&tyl@USeEq?z#X&r~sWv1KVvvFG&cMBU`Acwa#uJ|99K0w2LoQZR}j z>>y^afL$h06j9cG>i!>Otofw*1V-5VG((m{ghSkvd`Z|zG)au}4n>YdP_lOEvlD$2 zLlXiM!)c7Hf`-{9y|v->8a3ec#x>ezr$)aFO$=2HTuk^!GzUE6Tp|%BDThpZF~?j( zFFDqs*CBZs+ezAq-ld;3pGcnA5p5B{5CvnMWAX4Axj48Wxa7D+xuzYrcD*MQ!P;aP+=&EE@dfSD=8{-E&EbYRwpZ6ESoHkD)B1CDvz_Q zF<-IDoI6<>u*9{Xv}m%dvMRL@x7u8K%cCzR$kVChFD9$nFLwHMTv-**Al$6tCIb|j z{&}6amE84LK)74hZ%AmRXZdg6PEc-vLCr3E|Fi_G1bIGWKD!b9zUa^;rFoJLIiB_&;2vz3L)WgGI<;Od zai`f%UZ&4wS8}VobwKa!ULXGV)~B$m?qlg|>6?oCKF?MURWBQq3uu#IRXezA!)pp6 zqa5!X2tBZE?QIW1oo?%Hq_4KG)h{QIHV|%*`+&CqkANuQA>reoF33Mndhoh%wQ!~I zt1vEbohTA0M;J@8#-yRhM4|T~MDRq>@v%}7X^{(&d|0hwb)>3dB#Q5O8F|0-23WS@^JkG7`)e-kAMs_N^^s8B1VskXQX+ z+V#rD_)Mzau+cE59zlAKd_lLVdlu&?>#rw?yU7@u#!|0&%K1)KdDiN!w+D(pU(CNB#Ce;la~hm*4NK)m%9Qel+4{t~z>LnO&qBtc&E&~s8S0)Bvzl(WLZU*_ddOPxGW0Ts z7oHoD8-X{jwZqltxM`>BqP8>4k#S#O=o3C0UKbvm(hiddQIAlN#4iF6B2-EIXXhk7 zaVE@wsQ;8qg;YnXR*`#_)6mn<4AFY1c3_-5jlz>Kk~cHS`Ez7H-!9P)-;9ssw_);G zf&`BTPbX#m^Fp(1HtW)_u<0c;#-qrb`-$;UKb0C+-MW!{uF8X{kky~Eg>NP#hsBI~ zt#fM3ny;0SO`2sxADTUn3u|R~Ks(>oN!?<->+Sei4X@&Ai`tOAD*f^y{&kM!_t;Ag z0?aH*BzVFzzB%`b4T^30&HnZJN8^Ljn5|?pueXCY*SB}bDWo?f8h)th;V?YCgJ`kn zwHTTXWA9czfx9x3y}9$`(HhPv<+b@h)|d3bX0YosGq^1(-xbbc)@lCkF9+jX+uMoa z_-Ru;@a_vb8$UF?Ck^gqp4y@ZGBY1DR#PjF_ns+4d_Ow<5av88YEY-}AC9QM#9H%1 zXWsQcoI%e0jfOh=xAR*>eu@2-)RDdScMZ}FBZ;^rVa*WFVGpQG`9z?C!`k@mq2xjP z+V)}wE&$hsg^Srm+Bz$IMHU^t{vGC1KQn}Vc4w{;usj& z_#^dvK@tpk>3y&P6O&*Y`{UfQ8^X0@{7{q+yyYSpx8J$yUp#*0@mMBB*PX)skNS*u-u;KO7}Yr|~Z^4)eYdmDUg zfg%R3iSUVRhwzFcMvX* z)E?(TaLqIOd+zre*JbbM)B_ZbPH}b?;bx8}cV3XV!i-FX4x^rpsMd{rrRWl6V)NOJ=KnCdi!VZy$$n?Fn1V z@2S;PFI4BnL=%ZeP=bOwv%j_}$?xWss#~@n*^`tk+1eyy{J%MKiZi@`CE3$yhOAeh4%1BHT8az{W?x_y}2*%X^v{ftw4dPE(>3qFWLYl;jP|d(a`>raLipAlxMQ# z{Dpj^fen6t0dpdC-0qYU`x7d~bM0RZ+d9+ha7@$>hYoqs%P^*C2>vbL zOG#VFuM#|SbMqgTqn1BUrOsr|q|e9kN^s9`({Xq+E;td`f3EyC&^1;xTD5$f@SHm; zCm70}7ap4J8C~R_pcrgixXga1jhp1>^Ll)Ky#hX4-)i2a+}u9VKj9(iBRRv3ArT@S z!rfD?N-`D-rXP8SOi3 z9LX+a*OPI3IUe63Vk%(h{+MGR?6yBiG(S~%ouw_qfK%r!kE#-1UfV+Nj#=omG;c{- z#P?j@AuPI-_HsSW4%>@UYvb{9%zhJ`zbGbh7gXWC;P2z)`C|G0eQ#AX8c2x9hk1;V`U<6sS zv4VU-mdSSonvIhq-7BjI=|sj@x>x#I>SexXfnknyVtEpT{enG&eV?|G{+cdW$5x+h z0%yQ^jC?%cH0AKwXWxQo^tO}g)96#87O~wq4y2@8RDhpwwStzZ4 zU(8)>bCvO$@cKD6IY^pBcJ=nRosJdM?&3?P=(CEQAXv@C%YZ1sk#4*c}y1i&iU`y7d z?5gdd|6zaR;MgoRJzoqneeiw+`6DziOjXi8AC1wjTj`H^_JZd;UnP&zXV#AO(t8Z| z^=lObjr)?+hwO)8J$ci^?RktH;dsg6IBgkioVt!$SU0Z^k!HPi`?KhmMa z=%d6Z*U1lZ)!giin}WiWLz?AS^29Ax+oC; zX~>=9)vT<^x~#06!u;SAWBiFlEIqP(Ny$;a%a7+r!RL~7_q)wG?tk|O zSr#f9&Kh#EJVtgl32Pt@qd~)Tk(@>$SDwu+BupKvokO=u#gJC5)%{iIU1YtD2Yk@H~im>pVZvh*`9}y z(ap_`!Ht!{&e4pKnVXxNk%@(og@yi~1-+Apt+RnUy{!}3e>wU8{fL=3897?mJ6qV< z690!^14BC(XMR%B{|NLy&wstAiMz%BiDc{a-)a3zknuk>jLZy7jQ`{NAC&Juq&x~1 z?k3h6ViqKN9#~3H?{K z{!{v|TmrCsjQ>-50ayqF<4*uU2p}yctl|!G(FxFh&*|hR{_EO`lctmfULlP?W$iHoh75j}01A5i^Yp1mhxwrlwDB z#Irf=BA1)H_;z}x;2iC=0E3wRe3;KX1BTXfV9#Nt=>rDqdju>*id%4=@8a(>iz=sANKAFr7iJQc~{13?!-!YAgfu-m9oSyvpCncIhA(e@`pKvu?$S_3x<7WdvvqyBxPUdpj>gS=bFtLF z1Mq##UOKmzE9f_jg#`G(U7RN10>eL+0ReeQuHI{tjDL6B(ZeQ|#y%AB93kflCH|-S>8((l)`_It!bEM8SG3_^!YZ9Fj`%W{4N{UY?c- zv>Qu7Ej83f#`64~esQ-l4(T*e#^C`?n7A4dL4A`e7KgtT>Xwzi`|bK^Ol6>KuR5?` zk##mUIzSyl`hFfPp1Vl)v=`I4&)&F^L@)}M;-GuB|EYdkmjmfzki1@}7|7pk1XmbX z6bJbEg+Hg$8Oi@yd3n@q5>S@uD$=AbV>erj&i})uX6a&q5Vc}kfJ;Y*oHW9&IH<*) zGHqL1!{vs*J)kC?wUEZ+ z@D&JRx-2YicA|n5F?7Xx?LAV3gfb7DJV?$)E2b62ePnlw6nj@@9|Mm})lh$ElcNsv z7JI199by?tjXFai`-s-Mlxjxon9`n$X6HWF6J|mT%e&4GJ|WiHg^upf70HBV+hdwC z;byzidR>u{mgb#MtTP<5{Fg9w)7#d?dX=r;vKG%*PbakAeOR;LW}issc9X1 zLr&hzU*RivqNbQ}*O||^B&}3oUZGsgdnlGDbbdq?51QGZ)Eg2_!pN71O@+qjh8a2> zO%?9M2r({_;cC-1)?9UM;VKNx_N#AMOo2v~t1R}Mzag6cK;bfC8ZPEE#x4XU#HNZ% zt}Zp!-`^FXV}2W)>uS&gZTln?7n%qXLO{i^IFaBrZxK zw-oz1mb%lUR$CB$FE(wnqmkGv=uU?xBl}A~oh`G+T;HWF_Z^3xu`UVwmBH{#XeObV z0=O^qelCrF0hbE0gq=8>#H^t_rsa8-skblOGNj($oY zH$TvrPz$}aFL~TGuUmDYk( zhKZaae!tWmnftIX-3wL>DusXY^=xMQ{utL@Ig*q)aFShQ-#Xu4;HYPMV z-*f_m(a@oP9xXiB1?uaGdlJ+?5usfj=mT#w;d!*pANs(aSw%;un*pQl6ESRE#n z3=S*SzhPFi_FIXl)SOy$bPb!wa0*@FEk?s5q}#_BRoLrk{_$e&S$}4_aVki#q!pfQ-oPv-XPg*BgSrYD#rFEw1aJ ziVDQxu*uCgUn#>_#5ww|)U*n7-r+NaX!xx$FY(Uo>v*ia1mb-`xl{u>*>%yb-!gE zB$%PAOB~0XmKHa0M-d^V>)Kkv2 zH?CE}O5A|vu>4xLZK?S~^#fig-nJM*7T0mEN9$KTR${H?eo<U%MILCv}cWREG; z+HAZOeY!s^iWD$mMsd(X6q?q!!+E26mF~yLK{{Oq(s=HYSdI5yW`Lu><6h#k>6Mo? z9ZBI;5>`vT1SyxD*5Pg#lh^L$E*6Ejx@Se3lZZ3hCKusL*PHa0Rm^Aqe#oKerfy{rUTz!wHCp} zSL4rLec*7dZ>>unk@hnLbkkh6;oBlGEiJ8%?gBv=96N@x=!{uX)yb&nIlX%*2kV<2 zyMXIU`RM&sD&p3qhzU)AvC<5*|K~JCM6>Ip-xq!5=2t|AqJod~wELF=AfL%I@gK#6 z<7^U5W~vavUw}sSc6aRewYn8Q9brn30zFsk?)}~y*kOnDr^uXuu&>2)l{NxLsy#Q5 z#v`l=SZVg`*J1M6q@6<`Yw5%G#WG9P465-fvKct$ySa- z`WvO88NuA(PcB-Ul!zrP5J$o8d_aZ|g_<4N^{5Z*B(7IyyWj0{qvhSoWZd`E(Tq3y z^`n4n>3L8wQ<`sf$Cxd&1}FNET4q53edX?nkqKtP_MUX8ckU;@;JMYM>juMgFs78* zGVoXJMPTC6P?Hmd+epQ?*lMBeV^1i{Ueo3W=C-a@t(pY5=_f-O?Wuq7tXGzUr5&U9 zfC8A!p((`zz(E}akc$z$TYTDQ^iD4syG7QEwZbN`EbCt;-u49TE3%~o497OK8S*{m zSt9&nmoWQ;pHCr=HwJR)vjryJJBDf^+?>MSr^&MK=PHYRBN+QYX6jy>@y_fCL>}tD zM|o&M!cfq1hZwgHp5X6fDC7IX1+0h?9iX0P&gWU-pl|3xX+;J*KdnU>Nq%diKI8?u zv#r37AzABje;)-OKP3g6*?$=u%`UxKKjJyvBu*%-)eo_dEgkb zKX3(v_WAbNf!__!X$$Y9@?F2aI*daD(Rke=+4~H~Z?|8@J&Q(3Abihx4y)8s|GEAo zOPMm!>Ml7-R`6Nre!Z$!?PWS@6$Y(qQNMg;c&I78B~8S=8(>nv^l|)o`E!5utE-iY z{|UC7v&Qfgp1-&H>BT^J=yFr+n#b|&jy)S(X*R9SdeU<50q;-hvkmR}GCE4o^c0$( zo>OENrG0aOCRPi!AI-bcMi<;*jf40D}98IP%AEt`j+9=Jp4F<`jeQcuqACV_>}}R^2syNpGUMO z)6TzW5AH3JxOul{iCuXoM%V7z#5UxFiz_6dwjz^n;J68op{qR)n(%eQC6W&|GAGc` z3338K)b@Ebh*up8Ym(uIujl1@J7TsaiF}PMy{Y?82kBi|f={P*UU{3skcwjYnzdh0 zylMN&w&S}56mU^dm<+Vs3ZeuaLx>!6IOM`tT;f{^!iGNyY|=kDeDhX=vbkuN92~Ca z#Y5^-J16lIT$k;kY#WOF4MPZW+MGYmd&HJm>7gyPt7XI4s5sZfB<`4jr;L5unWT;NmI z#@Q{|Mzh^{HS)Q;Xo}d;l3+;O8%Ab=*hvh@_vP|ntMYtnOL3~TBC6^m4L8w}AO+CV z&bML%!DmB%^!TiNwKq%bEc6Wp3cA3pJboLZ?Naii&&D>AQ*jd6BQ%-MF{&GHJ;ecX zzw4^9H-nquxC2A-6poU~_M`hwNDdu&9OueB4?a4?MGg`Y&IcrTT}fHy5oRg#Q6aIM zBTE?77>FjWFVAiO&+iJFS_iJ3jZN1PRn&5*CPs8^f?8KihZY4n^r++R6S~aj+A(g! z_9a9xcJzm#%D06vyfJpzugTw;RLU|poY5AT@C7@_8WI<8c+`fLJC|#PG9>cv=rN%` zyZ!)y=FR@Le|fYq6s!Z?S83Dt^1`l&dRAWpjt=V|9MR<)5XF<-1_s6bs0;eO*|hO@NWb6v3zfjhfap%%0^}WJ zj0@RON9bY5yY|}m*3oB-J2oq~u>ZwhK{hFUt6XNP4@6o#WG*|S4(Au}-pCXKzM5UE zeg5a!+1tO)5_=2ZZYQXc^ki1H^7y#m-A;#QJYKDbVUpN*z>eD}n(ia?kqmL=h~G3X zn=ymYJi6Mw8q}zf>!O+6BDYdIwEFM;aW*T{Gdc6j<3*4} z@8w~QyC2Q-+_F+p@o(8j%TDE&HVUba@GhU%>RO*7Pl>RdTjMorC28Y8b=*6ZYul>3 zVcS#DQ=SQ&9l?f)D#d9VB47QL)2#LfN~Abhb4|(3(H}_h0ETh~x#iFOe~Y0sb{Zul zd?S&`d2AvSmjC4R81J8g@L3ACU%0@7asf&TBjNy6AgO!XMuFD&qr9^HeWhFXBi@ZK zVq8fUW{!s3jH%k*m5#~($quncQ_*|wt{K0@sLy@R_fk&8Mb)}8|1n{Q+PmFE(6?Fq zIzq3^?rr9$jI_D?Za^RksGt>i+AHkV#kr8U2@e19>Fs7rKpD#%Ei|+&4Y!E=n?p)r z5V3T)$rbJyFFb){2k-{AP|QFH*+0nmff!s0++E!lUPU{$<8{pH)IO*EaV+fo1*{^V zjCHOY2rXpQaQ*t{OdkK^BPs6ZGydxlx<=ul1-3=`Sns^cjFWIZ!P0UnBBG*dJFMMi1?ZiaAmOS{nk~)Q+?%_pX`UAiu;k z0GJCYUf3u15ay_%#o@kf03CUd!#ZEysk3(+{pdf*>meOHEd2>m&ZKm49O|E2Sg5Q| zg;2u#(EBjJTeU_U+D$a%ZgJ081h-l8>O`AEeDwUb!hj+MK(=zSB5>7mV^P_oe zMU1Txf!0SV)ay3Fn`d&n-VAByTx6K;LjqfzuHxT$|1u7>MuPTV)$$ zDy-xv^Y95^|9Z780Vv1Gf;m1c}0KEA+dy@D7!v1q$rr;#PpikMyZ5tZ|U@ATc z0L?B2YVpQtzVKp>pa7_U)d-0LMm<%_4#;5#1V4l~kZ)1>sJw~oW{^Z^XlymY5fC@p z`j2&oiqj==r_wt7hoc_%Tk6vk}$<+mMM(`5Z+EAU7aP6$!mUk zx#>2ugHRWUBOOF`$dPXY{Dn6&Oy9+5YHmoaGH6++^Va3zg~OQp)O!e%AF4l@g4R+= z>9q;5|JBV|OJD5k-M6xUjQ2qa3=CZmB}inYB@w29;`ke!&y#Ng#5p%&-D11PxY9#V zJ3ASqMUyNDNz=kF3r1GXzughEM5<+n1VDi_WU&s*N&mpchs~UV`z~GAH1)k1t(XlG z#US~68#dJZ&G7gB0YY^6*mCF9vv|?wvN7kg>(xlWkWT!An`%-jGAfvwTmHg!_eXf) z0#F_s59#NS%hx>R)?B^{d*&CL!EhAiQ%t?<(I<+%=j_s2{jiq}`Hwh#!qp!hZD3U{ zzPWhp+%&X=U7l5ML>aNSKPfzqJ}v2#RemFCAWY-uA_w;fiT30~pcdQpZoZkYo~InR<>wQ? z!Ewa)V@oUjKIAaEX^b46u4G&MS_L5D2w^{KsB1pdpJ^pnf5_W7zrH7?ua zcg4|aOgbmkF2>(s1?44}cZ7hF-Z^Y;6i_f65Z(H#+_Iz$o}2Jp@D={2uhk8Kqt#6N zpAg>3yZ0?m5j&-@g_>8Rr{lk#MlGCH({!+5>BlM8((MDohW&~eefUaRLGl*;M{CL#ZG*#fYZVu!+``B2xP>*75 z_v`p3!I6~QRB{WBvdfA$;TQTgnp{JCQ*1VnL;ad3^6~bO8%Fs$mJz?YuEz62OFfG_ z0}V7fG<&ySSBEgF&{0!B!=;Q=2``}jj2Tx$N0CqJLGacRfZTZ^Pd~b1O0((i@Gi{i zPjF17JZH~8cP*9ORcb>d*|6WEHOv``u-?R%f=#z{S?&8opgtNK?R>IaYP%GqDeH2% zCb>VFkUr_DZ+1BZG`NQY=9+AHML`Bu%Ex_gR+z>aAWJ6xHGA(ya5FOsFP(RB0$CX( zZM%Ph&cjA9tPT2Nf0z>#!tAiK;qaSos(7P{bM3 z0M#lB{lxP8r>j^pUq#T%Fc!Qne|b4LqP-cs*8!%Z$ZlWuS!Hq)>LT(8G^_|TyaxD3 z8a2T93>t`w;{_gcJn0SJOjHxoH0R^RobIamQ|~LG&h=;>!-lB4pS(Y%_-5F-EujWD zqpmeuhw+ub{D34I)lQaWui&3f{RfVra-k0>_56xb9qOx=mu)S2q4#x7!=fj7o}&ZK z;g=F9$4#@4glYc#nN_F?y!J!v3r~5|8!|PtAUN)_2oO9>eLVfe^i5LxLX)Q$1!;yx zUt0g%4B*B9yZxz#hIe~*6(@lsZ4^^xhyslB;+p)A&X zs63xRkn)zKBKhAKcR;))N;I_-BeJ zq3Kjxi6iUqyH^5!EBlNGuSb$%?cpU=AnMY(W?|`ZN%xBTIqR5%%8u`iM7sl5w3bHx z!h&a0oa^LUlD0B9BC*{3JWx`p5~lS_?E3dHfqmg{(e3PX^GhhAT2z7zgJ>{*rF(wEXHsVX;L-{Tb7*<;~tZg@OYj|wun2yK2YUPNkF-0 zV|`wYb)PnMvd6QPtB)mNN+b>ww(}`CzxM#x+ovA!49?e!%>K|Ljj^u9xERDUMw)HI7+wn41a)t3y zym-VJSb{sdH=TCUWv4nj4`aiQL`0ni237^#+DWvq3OH@@waQp4-uLV6)@RJ{6dI)> z^N~FM%56lx{xN}9g(Qc;z0nJrH9Ix;moLSRwt;!W&V_RsKEU)y|J-$;LTF8+#f*W0 z9?}oOddYEu3F;aKy>0EyZCtiNvvPaUN%Ghk-jNvGRu=ptIxp~##W&nSsGxv@^-luF=|Yp_h=Y}ks7b;N+- zpjs{lzfgT(AEZfboMe_1j0_&VEm%)3Fi7YwqMOEo!Q3Df8Y9RT1(cH#ba_E60vlUs z;n}*i#tbgBOMuGuY%`)cE)IGat!OiY$x?a!v|N=TaY3OZ;*>1KF}J`6Bh^ApWMcK# z=HAHAb0ru2(mcjPO{nA&l-;lU*F9`&$xtPJ7c~)gj#`oZAB;wnuWv=6ftogG`2`w= z%v|c)ZdMa_wu~k4SSR1@MKDs}ZK!D!8I^{_XY-^^uIgVgB_+%HQf$ zGyG7^V(>M$Xl`{ud~7Z59QA?xv+s2UhBcwKK`U?H0IJu5zooPhhnD(qGU=~eXk7V` zGu##QLr$_L6=B;c@CfrPf+5CdJGMwon^)YM?Y#h9(ul^=9+ebHME@`8%r#|XhWjZJ z9J8gw-Nq=PvgSi{1aXn196@lpLV4(YMKEz^xX`U7KCcmpjY@RWi*L#iD~p{B>0ej9 zx88M#jxLo|O;hrC)#Bl*t{fiE!GamS7vr~$+h{?+a_%OtUTE*d zP-9+7yLZ{i9}V0oNrcK86{eS(fQrh}W8@P)Euf8Lz^?rIDof7VOANZ=Ik_mO#|mRn zqH0N1h3$QD8+}i99XR_APQG}pQB7}_^+Z3}GNR>& zyW4cU#pu16QYzo$gLiMYak%1UYWc-SE%*NI9|-h)!l|$MmDta3+wyBw@`AAA1Izk) zHv7AJ5Nub1%l@W@wKpQmq@tuvSNM7&fqS6}Buf>Qr>&$|`f{=3Vq0%fx6)MXje=_sJT`e5di@i&YZ~#$}`bw=+~hfxq>NVaVdE z47C468gF&n%S6WwfNXqKfSC7;)Q#({h~g0VIKsKHL!Lx%8Zyq+=9!HE0A4XvOOJqoR`2MX zrh9w3_TsE9Tzpm%A8{v12VzEjB=WnFNjyd`aj%3cda-~0o7s6Pf}Dppbd4}Kdhaaa zld5bfB2@l``pe_5_vh6x-S^BP^^@M0~n4-!URCR;h2@27zL#M z-nze3{Z;=9JSODdFXXH7PA*@RV0dSAl(~%Gnmn?FcB-}l)D?5Jau|4Dvs*L03D9&P z**JkL1*Hx(o}*C+stav!m3j5++HZb>9Xdl7bySEVttVQ@5$RM%wxW5^8;CsOHuGoV zzu(77Tg5Wiow>3q8$++(Sb|AgF0XQdYC3OAM$qCj;8haG<59FoDt$pi6~k7oFJzc8 ztmsYGY%sWVA^8L0rA=S>|2XlR_Mv{^F@-rA#U+|lh&-Pa4O&X!zJd26dO$^WAWB9< zrEm4`m0(1y!W6n4;A^CksC70nfymApng8Sz(v4&eS{5rG{uaJ%9nD^U*5V<-`^b1o zRoR}>B6V6qW>OVP^P0DoVHt`94$J`viK+t&y(9o=$O7 zpiyJ~HFDyiiP0YGt6{k##<8fFQW^BIESht*Tz#JwK|%bHv626&*@+`}*M9VFY0Ujv z{A${cYN)Pklj8ZuNV};Q22_fFT1T#VNx)J5f1JHzlx$tMt(n?s?zC;&Hg?*!ZEL4( z+qP}nwr!*GeZO8s0iF)1XDr!P$XyvD5W64TyVuR>1GsX)zyn=>mTz;P^hh?`4fdj}IG^ z86@81Bm{hihm@vn?c;1sfBEGw#rl^(e8Rp%>G;!5l`@+UEGWM`IM?UKvWHNB z7n@wA*L^3m8&GBw@D9Qm-d3T(w@lA}kWI(rx+RY?zs}PzVjc!P1p_utg#Fl@e-a^r z`Ax&`a~K?xT8te>U?CWB4nqB(o=%jnN2rjfe8KzzWqbx?Z@yfL##4x12(YyznybBDm6_`!n%7#ulY>iASen&u}$uABs#DGs%hCyDFWA2+#LtsLQDZ8 z!4LBT0|!qjvB+b-z4WudS0BWsc$3S!KNRhZ6!|FVK$%Slv^Wu3DH(766`q7ij$kJnM z&6mge){9;cQBaShl4QN`I=vaH@D7X0z3!L$<-_g z|8@&upde_;0wy*SBT+7BZ%j-?cGv@&U<)3Cnk32rz^leYzBMdB7#%_OaK0iHiV>jpIosxEyD~ofeSj~;i@vygHpkRVd^g6W`fM=N=P*cmrD??n`_Z!hw`bIg-N$ik?1 zxQOCq2=7+3y2N^8-7@dD=PPr&Cn@zZONxwWE@GabAkt6;6x#74H z^jM5=L3{+O?mhvs{gw-odkX!~rM4WmrAj}xHU8gt zBwom5u=@_Qe6rAx4I*gl#!d5GXrNpm_Z9M_mNAuJo-up)kS-wrG$xBbijEe?eRM{W zt7%zKcZ*iw&nhWNeHL-aEIkYKUF~WKI}M&>JMm*>qIkm$z+%q4hl|(|6^e<&C?!l~ zzy{jp8S`iZ{7;k zZeJ7}BGSuU)06v^lZ7RA3bw7mNAszQ!SVgD;D*NIVl>q!zMJBemm-^HvCM;kEA48z z1k7o{>J16TccUsl)Y)u`SINQs>ti=+iCp+HMW^@7L?k@Cupi5ar3xIK{(KDr1$m^UJIV+YHy?7+9HHT)){R zds~~j3`K=T`#DsDZh!q%nLeZNL$(~M5w*q-enov!oY$dXxJ*ZX!xtQb4WCU^eGyfm=51q5Y!rS$U*I<&dV z$=io|xlgGfp`s!AVnia?C{NZX3haF(-U_g+S9vsC1IVP5ZQ0xXX+PEg<)|Mg)N&(F zZ{CGf`W@N&sFv1@*^V@fxMY`@kPPjgy&TBLn?`mV{cUX+TIZ<7$F=lmXdEg3dz3wI zDU8KlGmvzpvDm`e8ff)Tq3T9bHGby*0u31j{{anw7Dk>gL;$dI;w#;ML@~+V2VlF* zt-nnl=>N{y3&31>7Tr}dCS}yg{P2m2T-%@}qxv!a>hk>c#Hyn4k#H zj!O+}jE^gn7R5z-0wtfDR*Q=8y*H*Roy7R@Ciy2$#V;qv%OX&c&TSw|igfZOuRiJl z@tT>k2&QxvHhzY5;H&WYj5N+ycL?(~krC1GOk(;nd|>#%+Nz-PvCuxAg?9UINR}AB zo;$x6(4D)(AVs@>Dn1`P0=%iw1c6DNtGZi7k3#q;12a2T*!(bJrj&_7Vm3Ny3oETb zObAY?{FEik!O4EnB?0M6ncGMH>@YMaKIxZJkO1@ahuKCSItT3&#BY#=ZU_NuvLwGf zO^t8s)KGmO_3rZGJK9^ImfAg|xV~*L7Td4%m`+tjr6!c!u@8rb zRgZ#8F*kgva#~cK{?I$7LOoeI3^x{hCZuC6A%#CCZo+AGg&|o3`rvlZdA+}p$ zIeb0;s+>UYC-TzL3V+rG0^RZ_@c?Nyp0OK|ea5exRuUJ3o_L>Lr? z6&K%1^tm~m?gF6O(BTYE?CSaiYUYoIxJUMWhMJJcIBSeY1fVPatB5x$rshQMcj8YS zhUPY>dVm_NF5aCIT^=To?B2nRAg=3vGfYKjA zk#Dnz2jCx?G2+-HhurRJbfk#E!kvtq(s?Vrp0f`!0G;K}ymQfycZ_02DeUnIrU;!Hnd@yT0C|aB0=^ALW{*7h>13eIHM@SV;U#musmjVO$V0l6933SQ%S6>YrhW16@kpE}>x(hi20Nox1ng^lrGwWc>W3E+Po%YZj}`r9M#pg7!wtsQlV1p)sP*ay-jxJ3{dA3~wI+7A3}xn^O~J zRe2%Xq#%dBbeVzQjGjqrOD3#(jpq+dj5<*rr&&}lbtC_!bS0wyTj|0Bn2vuD-r<6l{Ko%<@q2eu4C& z+|P`p|I*cja?%;`{_*Q-h)gZ^JzCV z^@lc;sS3LqJ_?-rqM+U^>{6z35(yaccY&q|Kj9l_z}#IZfZ?VLZ!1yG+5Mv(!}`yg zY02rX{!?F%PduDf+rzpVSpLi{<<~i04wwZ?^xh3wi;8pS-OBdy9sM!TM)D4_6wI1L%rOm{rm#1xjO$;1tOrW>|Gg^j z9jByTfAqf&^0l+cn}*y!SlWfMipQ6LSlfgxd;*z3@c#@kwUmM1h{|#DrrRnV66%5b zWdj1;U%!8u#7HIx2k?Cp;&q@be%r%~{y#HM|KDQrf5=OD;`eMjUWGpeMJNnkPlQGN zWu@xDj5LgjrcwTEJr0^69YgvzYSr=u58ozB?b<3US}D00yY1?-&eLvNNagx7{789> z@Q}gv50JM^rohgSQ>Pv(@w(bEAWy`^*q9D)*_OV@&0v^y z>EcS0r&Y=Tpz=C~qEe%QOP8B|8Par&Wv2JemJl(CPn96#fM7WtNyWvpsstwmx#hFv z(8%nQVd-`dtg=uJS45(d#gHK)(;%0_C6b5t6{d{&cza<(4q!32GQrsE`*@ z5pqMt%szrcv+R4`D}c?pWE&xM`fQpT>mu9xk)WVLIQ0St|yL7 z)ta0tz-;%k6KMq6Pbm*P9dip=a?6i~nVRtNtSx3r1=WTK1|QxLM0F`7X3%CtU>K&a zdp9XZTz|DV=iF%#WF;e$rg`4!s#f+6)`h3H=Vm?QkF!bo=B%-U z?Ugky+8RFfzhOCFR}jz009^+dkJ(d%8wy`atX@n%IM zy3@dZXxnUA47{dyb-#06y@zD*fDv6(8y=y62b3fM`e~ETvVO}zVFns1w-A1FTc%w= zLjp0J_iK9{++~2I~5WKHY?w3o`)l7*HcZwF-(hE_F z|Ng=H^k?W3^%1(uZVghM!u0-thZdkV( zYdPOp>21(a&6mX@AUGfzJTb9!%nsGDX1SK^^I)K)_nAv!a%eS#re!BJ5h+K?Fwc?q z-!-h|1!TEQv4C{o+g|MytS)E+q|r9?mMZsiOumiDWW?Tms3XnSqqJBDtMQI8+aN?p7$pkc|dG?7!f#c5Gx=~|B>Yhe~ zb`awGRpG#_g?vLS*YwEA%$V88vv8@)sFOn|F{N-QsQ%n!dtd^6ht-j2T~sOYv$1f| z!F-Gy<9kWshAC5%60rd{A%#ya7J4NYI&_;@&;C+Hd6iw7dz1uy*zWE3Gi2>Gj~K3z zISpKko}1LOi`(s=pJhRSINLr55MEyU^^bLN(YX~+L>Og*8;6mTmzLj5FCu;sqo0-s z%*GU+>+?=afy;t9ZJ4+>dG)Q12-Mfe<%dkX$59ko?`W9O8Os()_14J*01P(pizAw; z@h_mq_g3MMBUru*nZpwh>R|m`#|X##3Lcoij)*`{aHu`&Ge^zPGPUGvjB?4iw6~xp z8c=ijxN-GmV`J;eAB_<$@dG(BYl`O4QZGtY`piNBE0uBDvUTygmIN>Y_P<>D{bt6D zNx|G4(2SXWT$Vh31;+(;0AIm#?6Y57+SFXKQj!JGG7~w$4Lnbn{v{zL%ZMW|!CxTu zd*KR>KzMPT2))t}q^+vaFKzte2h=a4N{nQ})p1ka_aud3ut=Go#*hejAfUg2urPa+ zq?R@uw-<5 zk^wQ$WA=e|CYK>Ez{xDse|Y}s640|v6CH$8LzcASxMt>3Ud

lt>d3ueR)29x+c zZm{l>z1MP`dsEaxN>tAeO@UK)2C5;U_b)7XSF{+9f7C*Z2kTBilMWmo8XWXb5}_y^ z(YZ{pb;h>!o?m&|s)}MpuwFeFaTO*CYITg>GeXOzUd1Z!pArUK-}sDx7_p+*@g1^A)1zsZ zCa$qMnHx0arnuTjC2Z;zFMq0u^C_pO$!JNUR`NVOV3JKCKwa)t!5UlsdjV#DEM)QM zK?zfy5N4(T>ILE!CI17w1PS|;_wu*2OFF`&qUD7$mHj?3P=-M|w&i8)*j&Si*4kpk zHBvF#mfEk*nup>N;6cbja~^=1EOA%IvtDR}nVH2W0%xrCjt=!kQpPYJ;Xsfs5HnpT z;36k4Egc`UFKx5#lpJ(%vz7Bc(emEKRmS+J=qZ)Y)Cz+o$)v1ILsmWsWF=5!6PZjo zaDg3A{+{GeNV~@`L#IPILhRyA_fha<~_&FDyk+GE?|K{Qm6R4`9B zDuGNs=J}Z~+-pl>vfb~@%OheAY=|x@kY*Fd0&uWndzj@?SaUFAnPv2LYySjnKmR_U zGRzpn3=onR`qd!smUcJ~{|ZK$zpo}t=sySnM4v`nX`!cUpy1o?$UMjs+z%5BP#Upk zI%&gcU?M~QvO$%mb^?^2%g6Lhurfs(_8~)14HOYzhd}1lvR;QM3emP^Mr`&YL>F6Ys3*7G<9WXneEcN5y z@JYrO1CwKv&q_3zC9JU@dfa)z(mW{?r1#LWW^Fz53S3FGErG{1gXL{7rKxd2%>RI7 zFBl^@6c2lZXaSa9Q&d{e(oWq^U}z0|*Vtub*SBA#$y4M_0(_sVjnMn#b@o%4^(DgV z<-M#P;2ge(92OALhu^!*6yA}Aac=g1%>sBTMhFuH*JK5MVUV+JXV=W!>fyL$jMW|{ zWhhY?tkI^cAG|rQSE1RJLmz#s3|;UKqr_!|IIEb~W@l=;MyNVh=h(mrp>$tzf z-e%`giP&IaZP{2X1{Uutdxg1_oTnYoL@&z#1aO<6^zXFxi%xZ~sf>svTDa@orQoxf z0f*XErKNG0y4BbMWeW}WwJ-ra6VpW$%Rw@AtnA*U? z!xhloA>3IPdY#`sVxs#)TEgmx_yj@nZiG~Rh-AE9W@h8nU&WCkMXeZU`eh=vKx=+; z7-MZwj(I}<4#o>vTUZr8OhQOvZJk2sd+CYAGcb8+2yf%thi~Y?q*n$Fa57Ps59BzW z_)JtbmR6hTcaPY&3gz)4?O@T2Nfc)~Vy|z&caJPEQ>NSqK)!{$bYP9 zC+VT`K{c$*&|$t7A1ec&ANX(N6k{E(fqX$Q;c4gHVWVjxReyoK95?o@v|dDiwNE_^ zoi83>NrutrnIyg8S_Oqm!&iZ$<5aZ@myi0VgKjP{O$tuP^<4jv3jo*yWeAZenzK80}w* zkot5{p>5J8PDc0eXzCXP;^s!hnl&g@het-g|AK!8JBl%hBTNNM46e!pdQ)WelmO3~ z;u&-ok|@ms7B-2N$^rN}KN9gZ&j6aQTi3jvGm>+7jNO$3yCYcJxH-c>3$UU@?RUC7 ztb$0LT>xbn1U4J>;h6_VtZLWq;Lcnt2j$auJy6(1LY`c{e5y$(3_bsCyg=s|G1`{eC}@wix`u{Hs_fWy-mJ>sv4_sFK&l_{^i z*j^d7@`8x!Q=rjT3*DqaH0Yn^7^SAFcD$DvF6rnaFhO~OVie$W} zM;2|d8eP|LviH`7jknHZ7>A5e0p~QHHm#*-n#Oo8s>*8S^v?WUp82IaP@5#Uq6;&c zOFb)4!&5;YptJk5C&sPUI(adtr&8;gK9F}={`piC$|?MR`-;Is=zm;k;6G~3$iD65 zDU3~ET6tk$EqLR6fGhaiV%wAvv$c|)E7GSdnE6C^h~om?O$C+M?7c9G0_C_OrNmRy zeD$!cZ|#YZO4`zB0`@%=me9sL{Ljv$mC5Lx2ynlZE2tXC(lG^%&w`QJeT`TaU#)zo zy>n{Bw*6%7{A~NHC(Jw6)$Y)EU}L7z%B<%BYpby(>)P7E3R*Wo0*_aMh4V$oPBzUSKnmCUwzxb!%z4kvVAwZz(e8bV6PyL%|ann~fuU96e9q|6~ULgRcLd z$D;iILIgi=<#&$b_tmCFfW{YrmiZ>1p?PWlX}fnvne{wUFc9tgrsSkNjQB5$uL9G-yh*~pUmh+G1JfQ>vYIZ~^hNF&B zq(hx;^;D* zJD@!rff7)=M6QDEfW598?QHLTRN~EJb&Y#!qJqvi*~Akgkx1m_V1Q`{*3#m|!QvPT ze0qC8rW*4;%d$O^uC(M@Mj8b#EHO0Tq>lg-@!A7zWN{xqjdeMXvz4 zm@b!RFqD(4+aP=Wa6UFrs=$;eJ@NIf)#d?>LbC+=4Un#Om!-2b!o(*HOsvMwAD~W7 z+O?gLg$wK(6YBpNYRukYg8E*e%wUJzy)3}EDvf!m$G}PzStDjdkR=1=#BIORioHgc>d|Ol)>cjo@Cu4tj!5sY+0v%u~l zDBvAFIcwk`+RwBjngqT$nHoE9&_AaHNu4xgMZY?h&LMdQg38zji8FIz$Fsnza>?5U zLh?yEBn&4vQYn2t)sz(qam(0vW*U+S-H_(7q*=rhFLsOP{m3|nvVnu14yL8`669HAm6emVapTd^#ENGMcJk-JuYQEy2Rd2QTiH0s zav1DO4Gr`>|6=(oOx&PH#)}?nJ7>+BjE@F4(e35{DT(wB(lQn9$vU88KI|$F7CupANSTfb&m>OA__Y|jnNE?71K3w1@=KGcZHcwTCOolUrE~e}Eo}Y;oJ7KZNpjQWaF|#>7hmCbe$xWopk@u;`7)ePFd{?6~o&h6~JFZj}iJ05jt`%?5R7Y3l4H_}s^3W@%3bE*PwstL@&T)@t0ArauToeEbtL2jaq#?#EKVx{ zWSiWTlayyLRHL&{NoVuA*?mi#)z--n~a^-mp! zq7+5M0L-@pY<`CU;maeo@r2tw`~c@I;ofWG9^&;3WD(?Fa^ZE^#g~Y|$pj|GBBOU~ z(rC2_mImphTv;Cjm7;7B38!N32TgMp+!T);YHz4)8N_b-aZd%q3{Rtzp0I2*n$K6Z z8}O3)C&6q9X`23mz(7D${3ZUsqSkjE=LL)5wGPVAN5fw=xmjsiuse){#Qc$wKH`Jr zpF#nZa~HUHBZyIbTP=oaF5=fkEE(j2b*TaKsY=5wS8a!Q>>dH zW_Hc6Fq%x<6~X1g*Erp8VwD%hEq+2hyG`n;`Vi6hCdVsS1uZ5*@%P=_o$qiq27O(yIOsA<{|Cl4lx}@g*(FF6^z{A}ri~kVHO4_xcd; zAQ_!kJL|q3Y310e($F7%m$zb)Nhu`CkGC~%D zE2PnH6Vf3Y!0>?LB#;gA+Y&Bx*~rn_j-*PdmPvEXW5?UipC8{ACHY-zY2KoDj?@k3*9aPJTO#is2$FEiQJw9K4R2RD0SGYgCoo+=M#* z{yC9`8ktbX;LvHmKIw<*`o4kZ(e=A#>@LVV5O%bCZqw$zOmUyM706FNvmL(@A1X_D z6l+Gbfi(JS(3u!(ZpqfW;na%ET0cF6^4neY^3Y~+YPvinM#pYGqwM=r!=-g}bA7&f z$mr1Wx+5{v%xD zL4eDT>*ay-WbF_3_Q=Amwl{hP3SpK4c0(u>1}s8%R51q_&AMnKbG%Gey5^#`aH74k z<%MOIWf{ei*K*BSSN^?<_FHXe!4hmZMNa6v!a=htn-r;F z6kr%Yb<*2x-G-F1yHW`QaPi`_#6tW${}b)^^TN|#R|AKJuT^1~1FUWVZZp8el2^TJ zVs(_glh2dwM`G89*nH;jwA~^53kaDAZ!8zF_vCD>WKl(zX0Ll0rSmih2lGz{r^z?z zy2G*PzjvKKrZZ!qTIB~#sLx{rmHi*kqk@A(@KW0r}JS)X#B zW#I;Rpv(8bY8bGcZ8wGdz*Et;x%$bOCo!jWVljPsE|;SG)SN_0n;?_P83$MZ8Ll(Gq5X1Z5CD_)m%Qj=9@!H!gY~dK<&S7+`gfnlrr!~L-=(#Gg zt#TC&a`A9I-R{y0gA~#bB%6w1HAxWE#?_T>7Ij;*XyT1brSqt%Jcs*-m7c#bjTd7l z3$tiAk=D@kRpCww-4|i!8L6`}zyZGv-(v@yS$my-l)aK_dv>}{^P78DAA1}G+bJcSU*S3zs zz9>xtJ(9o(D#sF0D11CRKHa4a$BCZPbQvwf)bv~KXMiom-#g(KHk=@hi78PU`1Aa# z$Hb~{$ORJ=g9EG_a4|+XM-rqk_&y;c7=_=DYfHK->iolkqMt5G0r-Gs25(Cnz@iq* z*J>5h%8wbu9l5z`6}GigoDGVks zuU>X_Oy=Yzwd-o0v4Sw7m@PWRY>_xpLvb=KEBz?nBXnG@JVzOCnLDHw{b9 zbsiHd%?Sgt{#F*km>vQ?%ULveUItK!FvU6L=SNqPmbO}W;Tp=m$SxK($gy;q%qT8g z37It%q~1!>eP_EZy!@FW@G0)%wG!qY(jn%Mi#zZ{USHXWoC!>$OA6V0kuO&?bx>8x z+Z?UaAJxBr->?S)mN9CSF#)`!Hy+f)8BK_#vSXRN>`g^k)wW!TZl^CegitCjmQ>4B z01PP&#L}K{zVzuR?R?lp%>+iB^Oqa^P6*;E*1PaI;dD)jn9B?bID9@>7t#BGs1>n| z&KS{zI;~09RdahDAy!R{Q}CA`eF2m*_8g5k>a09>dFC?F5E%31U(ln$|XF ztAU&VrtAvYNqNDS1)eWf;yb#C=v+HKT-*EthppqHQr*l9JOVdb`xSa^%guk){?;ni zBGjz|SjRBkX^h4>e>Vqu^ZJ8{D5I_3Ej-hq6AWN8tR9=uy%)yJgC@ui7*q2~wAOA< zrJ^)1=r3m1ddjexDCnP z+pJCeZQ1hPwH z2!X!W-uMtYBIK?T)yJEI^aARz=3@l1u(@FoMfFBC#jS!FT>tIj1+^IZHGHU2Y_^qJ zLbQgaGzAKeV)>8!epn9t!vAMwS5UWA$B%$CD@zjNTLYIy<=7 zTMF(8(#IjNB%?DRD7jLt6*K^aO$8`~(^9L@oU;1EOBT*WRR;x*%ivbPInPStWm1(8 zqAHJh!7s3E+~~Qn>}aPhk*SVB(hi|@((=pp@lBm(^>e-7?VD^&MvU0Rf2vH)&rVY2 z#S<~vWk{2N6DKG?yI?h3q*7o<;v5lJDf?6Y#8E7^xGEX4X*)~5w{isa*BTv@P)T_2 z175BSz-zTcSUV^Y=4ZVXmzzoV;{+*pNb;KjMc+u zSJ>nG)ha!mr{HRhrZ;$(fidkyjw9^j`fIEA*6jeiPu9(7^jZ}K*Vkh=Fu;Erb@Hlk zcBLYjL5hbK=RiM_!&%>jm9$lN?h7V>(%dsh@p+lhUxw`9+Mbo&Fjmzos97Iq3PEeB z7cMt}%u<(Nrw|m1oReOum^3o#ynBJbb5K|x3QG(fIsdq*jX63)iypm%hLZ^IER#bh zX{tyWfz_k#ujW{o>g)^lbaPIg6~*`6r8T&k?r~hpG9KG3MP{Rd9ApbHtG)M^LXom1w`;4{ zIR&YV9nKIL!v2M+{X$LPe3|jQplFb8>2j|34-#o+lSohp;(e(vrD)9^oiwK zMwB^`LDTTnVmuSWEg|jI)2;`>U@%CDRVHJ7)h~G<#?pO$NZ`GEWd%lrnP*uM5Hpy` z&f>rkelT{A!d7bIP}1HYXDIrxdDDjT-=jEW;Zlu6)TJrJ(a6X(^}SAUo}{&YNK+!x zY3Da+mx7jE`*FAh7#_}a(|=&TQW*9SLLRd!@Sa`F9QJp9f-Ltx&dTYcB`s-c{$cY& zD7BeQPN^W=5dX=-cTRJ%rF$JjCb5)1eN6#|0Mi1tu5vi^*Sciv+m$12Fja5#(}}$6$JThZw{4hjlTPjSO&bTAgM0hub}Zq$IO= z6-1x3Jlwlh{xn+TjBD-3=$$w4HR+}hbPU3{P@s~G-K#kz=uNg5;>Q;k*znHZNvn)p z=I{Fy5+<5eUB86j>$gUwS@`5m1pz|D%6Ktb3ItBVQ$RIxPFq!MyW#{jF=I)Lr1^J3 z+^xqc@Xld8H(;7)-0`Q?)FPyH*eVr3F96*?StG22sS0>;YWY|sAMf`Ac;fw1DVUIM zp^1diBxs~X@^6sjCiV5am{|$l7ii5#PqTTMFmcNFh4N^$x-zZvp^|B%JPoCP!9$Wh zQ*`WZOm`PNb?m|(ZfaoJK=!L{EI;bxP=9`I^HB+=QH|rE5iWTLl3C>V_3~6 zMEYCZ!gCtC$tdQHYcv?B4IY;x(fxYnsa9KiCF#MsDQZei4t*Q!G6bB8eW7ury zGECz^cTp-Vp2&;V{at-pjDd=V$Zn$daEV5rLEMnJ{imhiV|g1_*ox41ee%>@taio9 zR2}KhL8or4^D>KfX#0329%A#rK3H%^v6GG+kgGvb?}dA%UyT+L;YIVJJU0~;7)M{9 z$|mdJ%W4DK%V>g;h|Zg;h}jo$Qc> zs3}ow?ZRabWI=Lg?2#m(s2d)n)(a*xJH9*KI}Zx~xYztLUX$6v>i&5?L>F!9Hdc2k zx)^4kD|t!Bm=X@LxZyiKtS2Mm(sNw@^U1=F(e^L(fZ%Y1R->HL^|9^h;CX4?g%|Z z0s5D6kt+X+WsuRFKR;&6gdnlQ(mmagjP{r(-Unp*;& zg8j8M0(7xS$I+V7+Djjc5SHIfAVjfLJ4+Ef&39_7%^#l)$=5emXOF@D%26bgsO1>w zl4g=z&a8!b0Irt;pQPlmr3cfD()pRw8Hhv2+vMHPkl59ZnGl4NB_YVj3Ed=#eUUze)#w2!=3Lf|D3Dze1%rP|Ja-0UU#3l-K|=v&QJnQtcxpnfZuQ1TIH^L8_LTx$E4ne1SAEt(p9t!Wv_AY8pm{Z# zLpvKj>?LLal-@^Bh*;uPWVMk5CkanB3<#{wQ~$;B!_&{!1hkExg88NoZsN#jtNlfe z-y7>#OV#usSQxM{NApR#r#tBGo}591+{c`~F$G7WIkl=l%Z+RV`!f)&-$E<4x}Y3% z$|;`N7zbDN$KKCv%I^ZTmT|{3x7{C#*Hsbz9w9Uc0WK}Y^H-cL^{rPTw z4|{FYXygyWt1Cq*y zTU(k$t@n&+e%S?G3S`R#fM!hsdW+y|O9IP#stoO<7jP8&r;FXL zqLN-&uN2Ys>P3e3p1%Qkm%&rg-M-j&)n{R}QVInKU)#h3bTyb0CxZ7EXnFScIr5$n zgw`LsO_~<9NL%fqzs+>>gE9IxF3`Ch3H|ZmsoQ_$-qy?tBagYt&Ky-)lapyI;B}>^ zH$2cX8Cl)iCO)n=dnJZDBs$W-xVTomJg8x1s)E{JaVDK&ND=OytU)@S-#(K)1_oB} zLm?G9xyb~!Lj4!H_Ct6qjFiH^J)g-J{QO01ge`?R(|HJ zad*z^Jx-wg@rSOi-Bl+qsZ(t_ZQZsiPJK(HXK_Vf>I+iSoEncDg4t^d_qMwrs=e|f z6(Csn>Fd>0)^50+k`i5%SG?#|!+;jn0J*aB8dfizk*{Al#Kd7HuqsK8N+McFMAqDk zoR(Q9^u(|aI(Fklr7jo?Xz90Vn$@Pif(`{+S8h>ZZ`5 zQZ1|a`^R#9(=EUkISJkeM6{xX(BSRA?B>1868qI1SLrcE+$e`f#@yyTw;#N=BVHGm zyiXi2_9-N7M)0}7&8LG*BPOhcoFa!0?x*eF^Cx!BgvKLQS zjha)$mu_B-RLKu;D(hYJ$9V8HY>F(&1p~P-@B3) z8NEl$Hj|?lpH7cTeHAbwkYFCOOaMid)C9M^lO`-LV}P^x|Cx8k_ly_QDK67E5|l5Q zd^lTK|20zq+hTH6Qm0_$;y0aN1*`fLcTmyDgeQP(#8uyv3?4G@pF{Q^3xGlLB}=?| znf`H}Svjm+Sg|3Z3tcoRiUE4vo~Av^MEu@bX7I+y9K?o4!Tp;{#~N&S^)A|!J`rd^e(SkMXEkWuxe9PNiwO<3 zHrZl(IRyzEOgA8|<6$>Uu_eo9phhoe;Xemn6k2wIg?}6>R{8!nTx(Xm8>(x5RM@h53|QPbafT; zGq50K885P2US46raNf?x`xYRWj9bZn+%`;_G z^}!y$4#=$5h}84Ei4TSAB596$S{cs|5FX4E%Vz55DE#0D}U`@|DH$5=^5N|Bx-hjrNoLCWiQar(&4c= zrAi+_^oR>(c@|&VW6O3p`eg2POH&%LZ43&iSV!{W<^Z8A7E>l<7YFtHOU=ynM!ALFzlY; zwV})>*gf`1j@}*z1<5MHy6>s--7=f1euSEWFKr zJ|l2ylWq1%q~Nw_eb&4zekhK+R0iF68qF;fnOY!P!QDwPy9j8-+2L@Fo*8J#7afyUJtjj`XAdEPfnUj31)r`8m&O$>Nc zV+uD%#0|cNr{Z$tD6k!LN1AT8iD=d7B&v{N4*hR2dXAK<```-q1#dRj-W;D%YP$fc zTt7g3097aE!kUxDTuC$@Npl~Qqw(!zK(x9al zG3J%O%wCLf)p;^4Z%Q$2x-*LzEGFjFHG7)tbXfy%1bcs^Q&3@IYUDgUB%~KL(?*)m zn$wxXj$h(QpHypAtb=!BTD_SExm35cX+6HCKH<6OP}E&R=yB$7p$!Aid_g_V!IBW}?CWDT@(vRYVrkAby)2 zJ8|5dR#r9VVTe3A(UQfhki?cvp)_O09@YkP*497m0)22qD}6sw@mqGe8#DmsEW= zP<4dU+hxS`_Diw$Fj>kF`g9?o2!&RFx6`gC$R4q6uCH*WZ?GSOklcDp^fEBH_p4|# z!_sa`gw6fHP@g(M`@2xb;jxaMfHOjH`zN}?tXFcsunhVw<`{N7JSikysH{fxvF=;2 zNuHzgy96}7W45X2fPhVy%#k4Mzj4_HAMjw(j#+Qiu0Jm~ln<=Z0Lou_KJ7 zzKo}tQE&bF*JNDHhJsyb+`eb>*a>r%J;-j%nv=(j+=WbJ^AD;~>a3X}eP+HsS;|(A z=I>r5D~&0WY}R8Vkh_LIW{Rcc)c$JFjug=|ARYZQrgHBt27fMt&5uH?UdiC2Bu}z+ zpQ@trd`)yreQ8OXcyh5=C#Q>Mny^c4%xFmUVdh~;!Y-=BT9?h(a`nbE+Iwg)C+bv= z0%5K0J?Jug=)!91_bb`6;{L^r6Htg+t?Y?ow$_Nmu0T~1BC0VXUv#IN>!MdFc zyT9?-deV(mM?~UGDXS#C$YC)@eJk(eS@21%4jrcQL?~hDRzu>CcJT054%E=X=egA13Y$_XN+NGIabo{Ny z_r6}u*)wqu7=^mQ>tByqDX1E?<(|`m?tB$Awg4AG z^4APLW0wOo)VF&(BxJAjsvotxmn!JRKgI#DeY+Izudux&M7^*a|1lzGI6%TxhbC9k zYB%+bJ9xRzpSl~p$su5`xE`)f=R>U`$Y@SK*EU5I_MaJBfz4xyP1oM#;@^tz!c5?6 z%n~|zg^v7gK{M6w`ngUM(*ppp*X!~2Bc@YZaIssw_YyD5DQ28RkDYaxR6l$OO*-cu zYC;N{ArVK$q>G8BzT2W?UhM=InHZ?MatD^Ht%ZzQoJ2HnS1^t4?b8id(-xb^zkUmsT?_9|9i#qFg|{1cOl z%1+y2a3nMZ0~6^|q#~gYAV8vc;tdcV`S=IpxchJ8p=^$O`$( zxdMJPOsAh1WI=JlP^TYIb4@1bF$m!kIInJJ>KMq~)Aw_jU#CYmE0xifRTh<`-UEQk zSVF-bf>o&OF+cqO1{NrYurdl0E_goJ=EabQvSpf9bn{N+Xzm=RWO`0NOrdP5a@|A7 zIU4VHV@^7;;;u0AZh55NAMOshmg@QI0CaaN@{R`G^Fz4x6I;an@KH|SJoGs8t6Mjk z6`v$tU*Dqx0cGp?)7;>T)%CAHOz}^~SL9 zwk?0PhF#T_FaVbck<;~|Qq6H>oVVQ0RKiw_Y%0(Xy8E*+h|CA(=q(#a-EA8+J9?(3 zt{XfUr6i@+=+G^C$)6emP+)jm?@x1oy)Z>>f4K7b^cjrYfW8h)5=31Y%lff@B){ix zM#^}V73iBt5O2)q$qXckG?Bnbg~cdBcB>~zCGXgdo)P_Oqn4h_%flA2QxAMN zq*t3g6WbT4GpJ~xB0xfAc?A}xxHWU%|yE4^Y?w2TlHD( z?6WFIllv-s`;lkq3DOc5oQq0&es3NUKn-ua0|EmEp5Hun69moa_3%^QHv3)m$dRR;tXv>%e^ z9}_>A-wg34>x7t{77zDvtI5z*@%P>(#p=^h|Mk@$V6rv+$v*W{jSQ_)lCR^v!|j>G z&@ln{#ASQt&o)iotI0%{kEpP4oEh`gM{ZeBiGo?-l((Z`Vugt-oc$Syx&GN(M5 zUbU3cakV+U=36@kr?xuJ-vuI^NW^6Nh8T{wH8jA^E+=gwn!M-Ol_S^Ow_Jy!2f$8#p`IQIwQo|nwfm@5C! z)qm@art65q+QWveZGv3NaMz@QVn_X0L=&UsGO*rf_#_)X3OM|<6@cK5rl>!U*-3d> zX{AZ7-H1bwwFI6|ReN1H>zNbr2?d0h!b32vA8+lRxoruGu2|6@=l_K;Y@npZTDyjD zNf8c{ARZjalOEY<3MpC6eFSp3`yaj?l;e-IpJ2N~CBT%W~k1 z^*K146m@SfeI0)8g=vHR^R2sWbLbF_;YIg#UFOf zma}@m#+3y4U)%hXTiOia_k1evqneiB=-=Hi*;E19`q+)Vd$`eJKw}J>Q!o!?MJM%4hBVt#BC_ON3?{|!GE0%9 z|E8~PJU0^O_`oV)#VM$0ezC{YQI<0#F`dK?HhBXLU_$gb35jY*O?MeQ`)$^M5IN}Z z4}hCEy?zs3m%E9`dkKFGd=4TRgI+@p*M{nt{>=(s;x$zVG$j!;5hs{@^zmhQDEjuLeba+Khu=ck z16n(@zev}$?pwdF0zn5^U?<^DD-HFtkxu1PEcdc9T#%+kB+2S`=qP;attX>8crWo* zme)5F^W+#Qe{TTI87tBHOXg7vrpR@-%~5w-n3oi$hs#MCgK%{5G}rA-%H3BJ%H2)J zPdkYl{k;K};Ih&KKy+`SwEU=KdBa2(Yzn6;Ovz(O2pW^C#=Wx?2p@I%t{RNA(}L3f z>&z;*jRZwSz61{vCh}b_!xcbpMgLHSK>%LQLjBIE|5q%L7|rGPolgK|fHl~L^43%C z`>&2h=GWC(s>hSBOu1Zd=Vq~{tLT=pnunTMjMpKICPx}c%1&C8@AAIZuJ{NPZX;s0 z-w>nrt$A=Mm@qYH3lMgTioEs23|vs`nm8&Up}2mfw?^RW6Dw)A0_EzMEV}_(xKmMR z_tkG}-e>aS0VotdRuNkWH##B`3CfY|duD;pA>F#7A|eA+%2bB3qIm0D%Tb#%!<=+xt|Q!%uZS-b`qvq@_pj!+=Aq!L>Eg%zG%vD|Ter%*^7| zL|1}+&K(k5R5CIoh^X+eN8=(Sds@Ht;m>L*V1mo)%B*EesGAeU)>o$yugSW3L{N8m z+G#T4#CL|ylQbcDvbp%d<$CPZ6oSY_ODrvb^qp|lb=3&m$k{#z#)t;- zB2sZ|opH^K*ySosTVRv`kiO%3C~qRgf5E;12^JKd@dE%AwXK8)7&QusCbi`nlID>E zOYADx4T2`}aq8wvqZKJfL&15L*4gTsFwp^eAObBD0!gnQ2rZ_KGGyTp&tP6iJ6$<* z`t0oDM?|Tj3ix1t2Dh)d1IGt1bjiIB#}~P3=yLd8C4;?9*eAAf+`qKikfCSFdaO_} zxEz<r4s^jrY3zFdPOi!QH|R^xA;en54nwFK7WR{jdw`a}K=Tj|c~ z_PbXod4oCyjG}%Mvgb3FY{IjW?vsz)wgp@Ook$cO3QNFb7*{Ov2Vls>cCwv(eVU!r zA>i;Q>SZGL`Wvbucg=dZiS^Tc?U!=t?|wQx?f&Vx&#!mGI{Hwn#@>nE8T zwsfn_E;mH2@jh&pq5V1|Oj;ErraAN-OBWDoh)m|6jaUTA3i{ix+0Q3`ciOEOygv-G;{wDX+UcO? zCH#9Y)@Gw8PpDg25PD1)UU;Z1T&p|wQhLF_r5Q2pb;^qt4cBIPsrP`x;_eLq#DyX( zl;>iiyLeKbbYIhE<>>QQM>l_?mZt&rJTt4n^JMJc01~3;t_Yu!m*aE<zR=bYTPJL=rLK+K#;P9#jt}+g~lujbS6y;V1z!3260lV8AWI7Be{7 zQc`P8%7kg&TUp&(Rq1V@h@cS1$HD=Dx9P9-qs9F2y|*IxmsL<^Gm+gCSK}feug7ud zd{=fv{Wo#R)3Krle{L=?gP*%KZ-5`Grw7pU|1=8f^b2b8L1KE)X^9U*yL9$(o9cEn z4@>Ap_XdK_84wGRBw}Yx>+Z05>)u5PTbVp)9N9B_i09@0Y%VJ!IUY~=%iF5;u%nwF zVPV1fD->lw2=v4|Z{-#X9N)D!ypNLTb!kv&JP31Yo$58}%06pRavY^+M?@{NV{`VY zN?WN>&d5*1QNel&(kbmi6lv+UOquZ)wVvv#&R=?r%h@X~7d)GGcG$iU68b`s7WzL_ z6*6kw3V>a+yZ2O0QcBv%{XMK`Khin;iyE0OMkAF$;=MJ?v6~+weDGYQi~;-eHj1t` z@Y|&TACaA9+25({+gi^Hen>^p?3&L9`;B5lr9kGeCQP>v$eH~HMPk+%*Pyj!KfC1? zUxbq;G%d$LYi$PyO0dl7IIiMh=?)<&m$?1mM-O+e{$*4eW6e=MB+{gi%-I0!>@>kh zQp?@$gB*Kw?LGrY4mqugQv`INsQeK^l<2y(3in%HkM&cS_4J{|J?BIq@W57ve1dj1 zQMc#RP9PV+eFADqCU7=-?KU_!nwF8m*GJo0vGU2btIgEz(T(mhmUwnsaAj}Vqq)(kNYHF#}!w6 z%3M8K6heMMwc1JFbcxXooJ0`=X&vK9c}!nJIZ>7#LcG*04C2;UMOpy9V+Its9RAEq_HjBa z-WgHes^CaWscW7zq3y3*a)1u&i)M`~TGfAj|NJ_SSC*%sA-y+x-MV z^BlRTXpqRSqPExvo2Tw!`UHC^=2v3ho>^`b5eH8A1F7y|_THifhJDpHOi#BE+@MT% z#a)xx$;(F~V^gWLUh^}V@q$;t_49BB0%(YwlVpP@klw_KsqRj?p(zL~I)5{wM2aLZXZG+1(qg;Hv$`+4&>9BW6`bt4u5)kGxs?g(8w1xrOsN#C!TnmZM}aLHmNd+ z?j%b5b;(9Z=*1q#q@(JEor5)H)rY~!E*Z}|eL|i&`REaHE@kdil+uwy(VD2dO1V3S z=`ux&hZVa|aJ6nzZSRk=XJbI=^gglT>j51rTZkG|hAgDA08Ots5dr|i$`xuw2u#C6 z0dkV*zPcDB_TyioWHV1$&D2Zma6hLqeCwm8U8A-eVK8R`sZN8Li5D3_J>eEOZVFyt zl&oOfQr9u2!v`3bj>muQk2MZSh24;YAz9my!?a9V{+8fE&I=@wj1R!3-pUmb8m;`- z2Z+F_Wv5vJ2=)G>kheRl14gfHdI}P$pXAxHF5o8jbqEmLcgCkOH-9wmrdAWaSHPgE zh*c69d|073K!d+DKL3riqnagqC~*l(9gx#j4H zV6qC!g#O*he$_Rq+dGBy?kA160V&OmHp69>dxq|kDTt1jSWSnQ%Xc-T>S|NuRml`* z9#41?*wx2pSPtvV;y)>w^BfM0N_d_(xfUeWS((|nK>``iusbYbaKBG4Ny}bUEg=$J&C;sN z2lQuJ2$-R-SjW5H0B{B0Jo#?r@ph!SzPY(%yRVT7ZY+B~a9g1n?oTc|?#5}L`Ga}}X+Qjksfqz-Y zY&tH%`g~ZpGG*;Lpl{qw8;58K#i*^n77?2oWj};YGS+P@xx_hSkj4Fa6`No2+4%TQ z8Q`gKY`o2VzS5)|IXMp$^)L7jp~|;1%UmvS8~!`PKx2X;pR~RxEA1;4Y}~3qC`e8* zsde}pg*DBj>WCmZ;XfU;XaHOK3?|W3355;1jt}2vXLwzXMEe37R=kG>e2IcWcu-5m zrKq!xW%4NEdmFB0NUpqbLJ-=+5aDGMGQzfw6w0KVmw}{iW&ZPf+V%= zy>mLJQ;>t~(fAl-5|z%$Oc4i(Zw_$b5)Q_-1#qV~6{^+KZU z#OwgR+d%I_A27z>Zt8yFBjkH|Xz91jrRxzjWV&yuf8qHrOcAMa3wSy8xR{A;<4|BA zeiF9|ijnR6;rK1FC-@?L0R5R<$CC_G03tRebBxj zN?W+}-bgzaK+sQ?vTq5!o*`hBk+6teOu!4ZaH#;^g2j*3kTLBeQm8q30783Q!kt&@ z;Q43n&jZJlOqxU2uual-7G`;Kz!^LkNO;jiAqw&Ra&DOnsSP}sO!|*7sh3LT9ACpU z@#KW#g{e!?Rc>6@611dyvkzQZiKUZ)A_u^Qd}eK{EuY#C4%eb=gIOoJ4rjSZNMQY= zSN~10xvSq;NN2O&wa~x{y>s25QP2ygu*RWoSG*nvK}l?6RG9m`w?N@5g%m7*V)C5U zp5~nds*Y_86bACtIhmz_e=#u$hh1u!iEk{c2*pfoT8B$_d$3^O9VPX98*gWv=Oc}$#XHLMX*lQ{hepdwbAp;#wNq06k8{Z9?`lLo4;Cx`h7pGfvOt(%8wH`S!z6vM`3j!sh zmjf3(!K5OirC@ln`v;E6kPi;f4nSwS zK%suG>Y6Gme?GhDsQ`s6qQ1#5z3>@q5VWApT}WJ*tH$33QvI(Py6F?+Yr2OcY> zm{E2dj87ByMuv&8#+Ep+nP$*x;=tkr1CDDB3);}aI>sMZiiN|M>(nW-9Lg>`C8xgP zk&TCI0ryR_T8+#K%R`5HnWqDnLk0rcACYEziku_Zzai&$h{ zluKenBDn(5vZX2&gJ!e{nFLXF)L%){SPUHzNl0I+8Uqi6T?%wPOTq-A7HkFQiy-jR$g*olHac1B(@@7uTHT059lacoL?OeQuxgQUk=g$B2=sy3SBpYx*v z0Sf4b%0fo(zXbp5d^pQDaM9&_wiVc4jB2q$QO_-^N#l-}+eaATv=i|;N06Z>+icwO z`#SiKaL=_R2z`(APF>OHW<0S{+8~0rThX~!g}D*znzi!z(BHd$uG_9#@l#L`*iq5B}Hk>cGJIg zQ?z)Y(%wQ}*Rjc>qx~9dGPJwnVK9)slYih8mNQWBdj#EvbLyb27YFPgV}o*=Y3|v= z&L#I)rYL{ZfUY4$kJn-U%H=}>E#U~&QAB^?HJrw5SQ|IqvRREF{5ZUVKPm+w2b+#| z$lyZZtBRfaJ>-6tJ$apwZ$_`5GSvC{5o4E07)^m#nA_y&O2)3F(F{1%^d?lnlIQ~c z5DXG?pPJ#4Mu$Wd@itUc=Kt;s%F(HhCM~X%VBYpPdvkp;sXz{Xs&T9iSP% zy1(GmZml3YtI!e@MbN`N%~OXhwdHYKvu)EDas`3WQ*!{9h%UTD^j~zfWn-2p6z*-c zE1&+mYqO`v!vL1Ev~ei9fg@AhJo|ts;5Jk2Tdmk@oN1vJ<>X58hd+=g@UK55yno8)H&f0BAjidEB_=0{ejDf0q~RMRQc}7#83Kfi(*l&ADc!3HG2hSm zEPqb{^pGWvwBW;=a8{ul!Fmz^tkVOP{aV!T1{^wO zu7Z7GwF_^Lib2aLIZHO%)c6;)B`;os;jjT>)Ah3kr9~oF!0AagKPoGI3MT|7Kfu61 zW&JnCD>u}48+-?`H|%YN!8oqLEi7pVD{(AC95Jx%pXrN}q(9R1Ne#?T|Ki_!NJ<~T zZsGMU%f;#C_Mnu5WIo!nD51S_E1UhPC{RLd47&OpGuwPXj?Thjjyoe!ZNB6aOHja< zo>oAr-W$B@nD2x91j(MXbZG`Uh$p1`X&kX09T8mf`dJ|i8hukfU#{`5i#q+KF>zF1 z^8Ox`GCwDeQN1nh`@O(|iu-kOE5|&^aP>EWis`f40#<;UQg^;7j!qD|W~UXFOzr*1 z9R~AYOc9U7Ob&b!BQw<&n$DqP|0d*UCmXYjo+SBGnsQi!x$qLrJ4e6K%MXn0Ps;D` ziNfVnoG`T}x7pl1RhG>GmNaRTJ|wut+1fC0Brz6` ziJ4vtd;7`91zx(u_5%Gs#Raqjd$5;<Bu`|bX<@LTaCUW>lZSs-#!D)F~vUo+c|sW}o_IPAQFssVckT))w~Sy;mF=&?}} z)%ZLow1sZ3mTVZRO8`$gY~QV!1JSf?!>?|7$J9z?23_EjcKQR7gJj|eb3*+(q6R!`}vr*Wh;ArT$ zW33dG*+(|t=~oCMwFQ%shC8rIWUxU8x~&4--6mk*hLmy`Tv2XuL!Y;d-XI!H4!LJY zES6h!Pe9;whHFnD@vsY&%oGW>UD5pc;dm+)7H~@4NeaAm2U-_LnJXvdvtY<$6@rD6 zDsc$B&{5Ui@|igfOG5teW7EZpxZ~?C{V5$)uGu9Aksk`65U_T9iU~@F%S-yVZZ_U% z6oR^Q?y4)H)6{AIgijRdvzuVEKlVhofbP@EnU^m9ixf`^CjJT&klfb36PE(0R`_ot zqn5TG)e$a7uZFq24U@)>%BTMLV{k;WP`ScDKL-=G>|>0UQ6|V3oDP-?1pDBo59mk(XId%^U_S)tux6C{u6Nl&leDLAI5K-a+h+9IEwr^nk?e<^fm z6HAFvAs18wfK#biD-!S)<+r(Lw98<~QBr1hf7>J<@@AirOoR#kfLI{_n_zcGD{Imf ztLd8SnY@&dxM|lFcXwjF!`(|&OO4wl*cUjwclkkanQn5}-7mT}KLuMELD{R-N*hd|k!|d901rt^F*Ho9dK@-R zRU)bVNqb~9R#*@}vx8@vhH)cGFC|&qo?{OMP zttGqu@X$PJQJ7i_@KV}vk$i?0n@iZ+bLxo3a<0d&`=rZ;dDt!$()R=B4g%m&A*7N^ z5Ou3y<&QF8E%{9Q(;Bxi#>+tE7_Dh(zr#t%Zbol?aJgu2=4i&~g*cmTH$@Lj=~iyV z#m#to&nJoyB%-y>6`RFPR2r?y$ORI-leZ+YvXR`}>RWgu3@Y47L|^!AHckXQX>-ke zqzbxSG%tBSH&RzH|9Hj_s}v~Cdj?5a-s?C4Rp{Vors2{b>Y3p)76oa?hjilp{7|qR z$3X1DBwF^~BQtCdy-GSCZwCXUjSeTC^Cu-kS|)L7$>cevQ-qMAr#iGhMNh-eKi*B< z{RMbnir(D@0&en3ZTYSk0uyVN{Aok~)Y45sub7!G#?&+~VX3j@JYh6zdvDd~%(<0eaN@a@fZckNVhrc{fq2aP0=kUJUz#HL>cUc6LD@Mtgr)57&e_hCf9p1;I% zHyb02S)1|H@y%|-r5!*Zw6`Ii>8FD7Cw^sFW)-}Y^80Ie^$__aQN6yv+8hv#yzM(G zq1pcEoDA(H%NKui%0tVy7yEPD{1VO|TS0+;$Zx!i2Q+-1Ta+!?<#G|? z7w@4;i(~|))(3NE)tP1`XaXjo{U(9G@`B4fRl7VQOLM>|{x34`uv1QXsX(e!Y@NU; zeUONs`@bL5rwPc);8%tAFRE%bLi-hI_2{x%?CHG%woXtI=${7I2>|f&4HSclYzaUx zZ#4M3rWCqQu7!y_fn9o6TK*3SQ6u87A$igWq!?I6}v= z_B~>7pE-TzC*%TRIl@1%*w29E%?AIzbHPc&kT_~U{n?cGE>)lD!^QnxC*oOlROF+PWpyUO}d4S=Bok2dHfDk477$TosVL6mw_og6#Z=L&* zETm_pNB4*kDI)(oAw7^_{t^W9VQsP&*gXiIc;JHcU+Of!a+Gz z4;B4^>^8Oe)hwBTvIF5V#+}L_Da8>T9}w#)tac^vZ6G*jKt|6K@5jLwG%4X3ohUol z(G6$>1T_T-1)t5w#BmK1Cs44Fz#lzF&oQ|y#7*R>jhmB*UwF`K$cCHx+>@~Na&vaO zrwa#Sz_ST?(|Q0P+0*ibg24dzfDWjS>S;TSmIb4=Hy5au@fL>C7f!R9pneXK!|=K_ z0M}v|RSDD#JN9c|N-ieY9wFedAOJDHv`QpZ#)M21)jOmEIkKMSLz@;GucWR9YzP7z zsXfwKfQ&+&TRu}cgN7qh4K)iz!+MQ|NmWZYntRhX*(!k<0K}o7JP4TSF?C-7=$!01 zVr0z<7F|orZv9Ip0->ByZdwE5W@~45dL7G9!J#Hx>Y7dgyzkhj@~$0_ZX+mMl83=H9QYxYZ=qzXXD z@N5kFo6O^L`NNFO-wZBAxx<#fXxrvml_Y;GQfOlJhRanGiR5vARo=F~m3yR~qIsHn ze{9evAImqcZoC;tB-f-Cwk)E(&@vhG>#PYoFs5gcC)cXowmLk+A6wksPKPTa(AmvS z|GGY-_q6>EzR<6u!@t_l()rZHeIEKm>ZddG%X1P!0{wx15CKih1nark0CXeLSUsH> zWng{|OoMVgBK<%ldyP*w8D@>x86`k){<=FTmU(M#^E!F#vt_=RNVkNG_5O zhTgxO84cPqG3`hFiD=8TgWPjeO`|=Ycrpzj=|Ve6o=S!CoVUJ^HWPq!5EGa`3Xf<%5j9h?AQJr=GiB=ZJwpn=eD_SssC((#TjT^N)l$}}lHD+8 zx-PZ*C=JL|OV7-D;41!Hq)PJ!sN{9C=mu+|Aq!$O)zQOE?Lnous$X5x<#TDJExvA_ z%{RPp+--W6)m|AAhJlV%M<}Xi7p4uy%zw)HQjrf%9PeuGvam`V1vuyza*h?X#66I| zYZT9M2psQvReTlmOw-C{B5-A#e*v>{aZ-WJed~-{GD#OH-$h(RoZ?Wx+Ik<1Iy=v4 z-{2-|nm$)Jcx(pYyGXgAmsh*&ZR>{^tfcQf4Qi~KtdO*V?->-Axe-zzOmx|p+4|QC zSMrj=|JD?DqMuHxR=*_6Gd_CzSUWpd^La)3I1D-)x<@<{n1GnvGo+JaqviB~E0&9j z(9FTXBOJuB*M%ES)ggzzAf}YyH&7hx-yfMndNQGpmX3mL4K@Qr^ z9Rfmwkvv&mdGMh%2vk^+|5gTWcs*&jZw|Bt2 zCw4}jw%qVxJ%3}ctH6wH0WmOQhq@?|zFFP_{T9IF;SHI%xUvTFhzx^U+SMVO{^E_m z)0O~6VG0yC9{2jT00O_4PJywWVVbg};4!Y5ncB?ihg>+{D6d1&J#Z7XqGo`I`?FyF zxNHiG3{o6K`|c^d?G3MIp&t;r^TTTobfT_V4zW;UCL>T8LnuvvI7{f zTcVC()-f;{7R0y?lPawbIp+IqS}Z3+VXa3;`y!>_qagHIP{d*2y&I+J(=iFrO294n zqivI!rgPt{qNaOTb9Z#@S1O1&>S2DEBQHyh*f3ARLgnkBkx9V;_2e4xkRr>e?RB%x zyhWfkM=#0Egbv{|WPKsL(=k!w{oFX&8iTZi3gCc7c(;ghi;ygt@R4nC&lOEvqiA>M@IH(U1 zbDt^C{XGaoFFp2kFP=R2TbCj>?ao!f6yCQ3V%xzLXlsGWcBdPMe5!_vFGNidTo(_# z1?Vh$<-fV4OC~AsGndu`_zOka_wIvkOx9kJZ*K?Zd8KVS`72;~xr5JQe z0MMz7wD-k_8?0N4LNnfQvD997ksF4jT@VWdYeE;V$E$5CZYFg z-3uggQc~Gw#+c#~$Wvw|koT#O&6dR3H>NGOEoP~X-Qc2jsvDiko+Vc}f;oHNHifQ} zC+Uq&S&Di14YciG`&l#@KW5DhA%D^()5~YoP#79|_so<|WBP3=7NB4KJ&44Z&af6g z2FxdM{p_Q2PsoLlr@Dz)DU)P`+VenZz`UD^;fv^W-OqNy?kQ@|S=?T{*$VVSjG2i- zL{L%K=_wk@-)Vu-C1Uo%-kOy!39@WT`_&$(m_A5nqi-(|S_~LQj@nDX&NF?kl@N^= z9)ZC12~lhi)F%ke5W>-zuz_Y*a!oIcC)dJGmkb&m0}=Kui{4;9yb!qW;ImabaeQG0 z`l`Y8K-X>9K^@Ov4NO2K|L#q|g+6|8HDE%Ko&3sQKZw$+VQPtbhN7&g zRK$xQj^b=DY1e(3G>jLl0&jcqJB4dNf?1s^@D+TXHOqh6r5^RO=2o|J{kZ`2hb+dOP9 zg%{{E{{oh2)B`MMN>(gk^usr5ebzr9#wFp7j7V<=GoOlf-Jm{d-Rxj?GHa6u(h3L@ zK#QhF$+&u2!4F%c8lkQr2wc5kt)(df6KdtvH3UX)x@1yf_LUF};EAz*b09Hp7_G+K z=CvQwlQ049fP|1-+K25fp>k!4wAGGZQeteiRvKF5Vcld9JB zepce536_YoU}#gO)ZHIIx#_^4tw0FI^rT2aDa5XZfk-tH<-)@vu&7`Cy~v90DrCT; zCEzYLx}vWFaa8W$FAo#8tdeEPg!1N78mz_RC2#8IfQO97s!eJ`d_|tvpdpjnrX#jT z){@(6@Q1Jf7|vs2*s-$;3?bA=EwTAeu-G%>B*J_D ze$qv3slTaQW={G6zCIzEo6(-F)!>u^{w&)6vX=kv&;QTkj;KJ75AB&~nH&7V{1m3v zGr;qCMp4K4@VegeOWqhEh^;!vjOGID`0>V?Qkx zME;MQy!G3E9Z;WW&#*ZRFd4b0AG(@(|BwiTVvGyucLL8hM^!UuFkCwGuPUR;P9{Oh zPPl;J6FweXJn=052`9$NL+Q;(xpQ}gk*J?iJL3hoW=ztbmaALGA^muZanu8MuY}rl z?!C>9h!EwfflToIn$pw;;U6k*L$)B)9hL7}6yWDEB=OPiE^9hf7FmXhQG}I*edy?4 zE}H?k;Zsrw!k2#UcZTIAS3m+7`%?NEI=*_2bg7!6U=!T2B;FAb+1%87l57d5p~7UP zhfrFHi$nqxqmi7&2Pn<&Yjcl}z_3C&CI=!uBJ1Q1;icG6Rd`<6gZ5>#CqJIzJt|t^ z{@r^>`qZL^O9-tzn=P50vE6=go38)}5s<^ruPh=WuD5quVu|d#1(n1Ym)DmseCj1w zdme12{w*D+K<{dv_Q6>;!=eLgt0=47{-V~b>D9Sa9fIt0V>lWPFuj}Px6u}r(V~jP z5!~|_T#w?%3hfjCE6r*6ge(NlvDv0f43`ZmT>I%^L9ry_0W z9j~8S=tWK2Su#9woNlUJ`f%dwd{U!~h_6WYRwVu3@PY%3-$qRlq^9uJYvkwa)joWj z0)5oB4WLuMD-o~k##vYqXu#2CZR4%E0K1Qjo(N&O>h>|WG**USK&Wd>&i%R!W0C3# zt~WEZUHcFL?pHnP18SC*`=yo1@>D#+KeA$K zS;5odGKr1HY^%Wu$4T=j)7QwE&PpVFnqJq~rD^wfeBnw!Evy6d=l$JgHex(8R)Osk@xY)Sb==@D^@b3Qy`)~5j}a}p70T*h0Xv78dQ02rkQ zj06y{dc1oPK_fJnkDj2%)F}V}(%X7-s|VeGcOMEOjycO_%P&F6!_jW>=-BKNl5lmN z7;F$!d^af%roKsC_EY)!k=LEJGyJ|NkZ4sNMR3Pc0N}nd+<4Po0_xUis5zBWjnxau zeMrAvsZb8YYv4!4f;tPI)pOt-tIqlOl}}C*slYXB<8G}seVixZFWh=JHrP7!cwMvV za_7w*Npt(WpN`LW8v5Odw#GQr@-a+=vz<=4-{(cwtWzY9x*JAs&aYWdYnPEpI*1cU zr-%@|w!xQOd0YeO_|}W_ut#{lM?gL)PuZ)kX0x7Tw>g!L@JB6~m%nh>UD!ve)MBI8 z2f*DViuKTwdN2m4adj8{sl{}<*VPl~w(JdtPZZCV!282OF4G8om9!ej_jf&&HXuS% zK8nUKI-EN8O1CKHtX?2oMrPAm-qyq=XZhb>HiFEF!`iy{15(;+S(il-v9YKq2bc_QBjZXtChEZz6Lek< zRs7?Mw~hO*Mmbt5v1+QaG8Ak(tHApl&m}oZR`^~LDRcCBjUf8c5BsF zybeu-OgnTsED%%2UaS`;eaCkFo@V6YNaTAPu2!+ny1bI-<=~*bqUk`Unf$VlNkO4hpC#xe|7lbmzffsn$6F8EAjeT|XWy+N8Tf!1e$g>PbCPUU8_e)+mNVW$#xn@}|qW!{KG zROIR(UoOaP9U--R1Xg!l;|JLM`; zPcVsJjok-b^b=NtL8Ka-oU^75ojzj>SK<4MmN>Ei@o?>Is)aC|bp_zo%eXG!O_g4^ zw+@c2+7*hU!?Y_3(pnG2JP+^WT>3N0H>;WOaJZZX8~b)XPr$3C@`fg8l{qr87Br~e zo`=4z+C_b#UCl*lmZ6RP$5-kDtnIi-yXln@x$DOCJ%07AmL_EBvMwh)5(d(Uxb2S5 z9!$P{w##-pq87wAw?p`==P`CUcL*ZQhW)y#3W*HA`}KSzNqKmTKqjHpyENG|=ClZy zj(bFcJ_mA)S~}gIsU#I_yey}F{~yBMG03tm=o&2B)n(gVw%ujhw$asP+qP}1%eHOX zcFpbQedmk$F){P=o)b6D*%>=e=3cpSrKQ**!=J$EiyFi%yZZGgQ?JoH9uzb8MEUsV zUEO%+i+p$!i1#{P57#UX1GZ(ft1SjP5^AI_rYRR4xagD~_QLN}u&t4iqtbG7nwnb7 ziA=#j->w2*&@~=`-!DQAyu(CS#rCfCkJ(x$dC-EUw(AX98HXf>o(`x=*HXtnC?;l? z4B3_1%F@MS6_7AYGA{mv<5xF?sDM`o)6#eQta{1sm}A z*LL2d(4I*kfHIK7X6MlnmI)$shDW*ZD;-UNSF_cL2~`Xmns%7QOkM+e_bw`Z(9wR} zH~gsdAuLGFzKDOsNdo6HJ-U2R4%}9_-5T)b1Xp&R-SUsJo5+(Gs&+GiE6T++@lhqK z$t{R*G&N1M<7zNf#RjVXi%ttcz<^~AvQ5Agm5g6)f%UlQeH8QuBL_#kIix=JU00{+ zpovGQyd$e<2z;S2o7ST54lWk-adpVfTZ=a$nP5(R%JUVt=+N;BOBTbD>h*3X+Q02Z5}=+9xTmwc!hi35@MB{x#UQe za;$m!?4Lhh`#uFT6`M5fmNHjb5s#L5?{y`~nI%f45Pdjy@0QVos_~TNe?*PW(c-18fn^coRpTmWl3XesDw+E7Mmwj@%JnX=P?Hn~_Mb zw09d$u%vf=jmS!l)X~&qs(?)$_y|XEn23}Xm2Hh6q#D=1MAiXa1by>=tUcUOx>HIh z&BqkcVEnD2xP`hFskLN zZ95#Uzaxzu8A8X#&=W zwO=oQpI30uAuF^tFg({Q#!;;OIqlD0JW2ldE%_5?H#XGXi2zsfPpDk+I#9A4!fhi} z-ib38zTHon#*tJee+!1!*~sqc+I7m$*IT6mes5~0-S7}*JFLXa*aZqA)%_=%vv^GD zKl#&|6rLfKvx54KM_a=?K86`vsya*cF0Vndk&da3XWpEfW@21XGS2SiAf;_yKS~%g zAA{lX!=pyeKRFc#afJO|!l*KaocO79*(~_ophkDeXI5eGsajTi)6?V*^hXG{=m9E{W>1-sI14z$zkkh(vQdZ1dDL7 zLVoqWS-~M)|Pv9z8d=BxK`P}GGwWw?s`#LVv!Lx9TN*{ z)#GM}S`^Bx8YyQu%sjO1igH#3`n$L1c#>r4?va>2`$=r0&i=e!n!HQ@F}?&J)5px+ zQ9IOgWBA?RJI6)mN5CP;QCaDR!$5;qL@fmCig{JSf(QK__prG^52X}>vl1( z>8#m+H+!Sf@P2sfd;)v`v#Y-kq%bw{^O#XlUR=nz-G33`sEKPln)Mcw1i+z67s<_1 z)s-jk940%CmWrPamZAjRGH-?*k7tC5j5fJn??yBP3l6?V#n2p;_RRHqxHp)iJrnj51M8>t{aEf_)DBCf*2BeAs@=S2(_~;4M!p?Up89&ucC`Ni95}!NU zOZL8a^=!Z1QiMaA(S9&OgHLa)PP;3AZ`ixP)k+yMNO$tK{N&$yTj&`cItSr=?46MW zW%9{U&eZG33A?#&t2w$r-DM9_WHy~+blO26Pxdp}E-}31yN@zF<+?P8II{-Vk*-0V zd~tar%Z==W0@hRcLB{mefHe@&Vl8mVXt&U0aa;NK6s_Rx^E#I11J{ziln0G8Me>Em zc$e%LuX~1tJkVV15+36T{e@v?$K-3p3OFpF9?GP*HPho*9*ka$~!;4vo!59qg@4pV#YrOxWt1s>@)D65#!crugSnLUurDITLqZ`hKa-neyB5DpOlQV|yXBZ@EF8PjQg;em^{RUOjIo%heS+}H{EC(${yDeJc;R^OJ!tiq zlTbh#82tz>r&+#reL$8~m*tr)EZzuUtC4Fa=F}g;YenR+k%NqJn_} zc49p`hXNXPtDwezPUEq9@g2o~kuxZLNUI^!n`-(oWErC;z&LHCM9$*m+karxwIL&3 z*&+i!C?>cr2;aX-Mt|5k-+Q9z!JuGjOax|sM0 zMBGr+m0v$LI67Mp?;jJ|ReHA+elyNirQrA5<2@MWH)%x8rd2Pw`)-Ym;^)K-O8zob}Wy(Vl zMN>WozENJOfx_n$6KPNQYLvsxWw|Ej`6~+Y7^oypIG2<_H&0sJwQ& z=OMlslEQ29Gff7s@Cw@9#m5RuQedt8^Oab&5?RlN=zoTg8{&H6;@TM#P>o0SBk_}^r~n{ofhDkU5Z z)AHX-+r1kX@CL-YK;P7G!{u0iv=y71?E=0*myUfCnJJgYdbLu&s2>>%;#^^J*8}|3 z1Fy(@?`qPz?2tYg)?P^krky;N$-iW$>!7=3kVkt&czHe%L!PT~#hQyHeowfaM`KA# zs^wIbbpQIzog1V7DtIJdek8!H%3JGYHv|)rr=Lv=j0#LK%VbJ7rr&(tXY_is*>?&S zP0eg}obKc>9V_`1H9XYaTjcf_mPjTm#nMGU?{j8kNhB?h@cDh=1+A^D^8Srw3W2G= zf+4CTpui&Nphhd$(15`Tpws#84~@JD?BIVu;Q> zv^4N!*nURgZ!T%ooIW}5xtMsvJo7b#V7<92?UV`WFnX%4b#Xyi4pQC^Mxfs z((2%R!w;vYHWC+GMz(i)GP_9OKW>S(#q_>VvD<)|d zJ=;s+z>>GBh$|=j>8?F5+o&0T{LnGvi_1jfscy5osT39*qmMgo(u|rsyCnv7m8q73 zE6_Azsw_$-^F9ztH9j-OUYeA%l)emyZ48? z?Ai9%nY*pVqJ>O>y>d@Gh%nX~UsZA{Cdh5EKs*)J&8JzJ(~VF0tF4ep=#q52SXfHypHtfzL#vj(Durh(k?t*L|L z)kL+0vK^tRp>na3YT!+;(*9Ul(t&hLI<8aPh>~~tYws9N_ttgR1xl|p1rsFLq<0X-^Q@rOe6A+qTk+{{&rw2wwQrv zk#fNVBDJQACr-OurQEj&RsQc$5CWRcu}r+oS6LuA?rfJ&<(W5sN7na#$# z3fq~GOJJoS6Hhu+Zd)na_%i|%$ExXRTSz3AY($|4e~fMRLcM*{QH`{<6sr3_tj@YU6!ebacF>ABZoL@TOlkq+?0{{yzy zT*Y!q(WF=w^t>|OILIz_&B&xOSn^bCXvQYCXxlohP;l}O%?<_138yYEmG49CX$uKD zccyL&p~uV3%P&gVBica*SwarQUQ9TtJAvVgxNIv7I)2lP=_l8t65yrC@D&n)@^cmP zwQCzVj1kf{$*!)>%&9rvvzDYe9ee7En<-BZI8I)2l_WNN?;)D$W_I{axV!s$FU`T{ zSc&ZcSP2ohU1`B{ZYlGHC(~L<)jB$YF-M}Dw$=V<;&5G3pS~sKuk#tdp)n%C*LdU( z7)Qsg#n;;bM(|^-WYN=FdgKB;?DEZd$J-c_XaV|G|H1V>u=AqY7oStnjx1^i<8p)6 zHZqBDszRXXWK7nN+3u8@97tE_*5bUIvo?Mz~aWy||S zM7$s1zJ23rB|mAV{wAv_dy4}ff<67@6?)^vM+c$5KlIAq$9TAnFDtjTU1>)R93&%? z#+m`uH3Pw}u*?2-nUAkJ&6EeRKMJ%SqK1k}Ej(yL&g)_oMU(aGVqKQK(hSl$T2Bw@ z%cHj6(+8o}DDl4E#~8`i+ z86~ky#+xt;Bo-aiY1E*SqI49PSJswgJPuBv8&QqxJ(X|9gqmtAqoG3zAuHO;@5oIGMP`!V zs@Zwj%bXQ&YwG4cb2r<9rpv6+rrGWwqFlpqLXEtF!r~-9(b#Nm! zS%G0WM`!lVWGTW~S6JTOzDIw1fW0i2o*7KhBDKm*uzo`Rn5=HkUL^a2;4X($dlI+o}{DrpES#RzqL@9YmeCH*xxD~UN;ATtP$3bAx2(trsr z?6@$CM(d+sY3&FB(<5C~?VFK|USNojwe&sdr0~?q#YpX7mPExcBFV}y=7Ll~K#N{I zOT9|3GwH++_QHI7LcqFmjfi9IV{JW>9}7_s|8Fe-3dVBn4`$U*0rsqd~Z>3aafg{V1EtB9(u zJ)P9PRH{DY*Xy%lqkjvpy&8fSk*J_`*HFA?5n6j;;bWv>Ux*qAsWyf8ud9g}wbR+I zJ_W>Lp7Ch&2y!s5XtBbG2UNb*`Icw0I<)G>XrvY8YJ#rel23tsn|@1RIYi-OLzq$= zBMBzHj^+U=-M_?G3-9PEmxb1Ah{oMuHz=wak}=a>J$shRDE;QcPU+E>EzGY(CpZX0 zI)Q>3AfqXp=Jw!LS={sQmD5a1kRHQquJ}7<4nwm*j^e9N3SD}`AomH9sKvm`)M9iLH-{QX!&*yEi=A<05yHSNR2;Uf1gfo1 z1!3?aONJ0zqq-DDPW5mQiPV*Q>Of0L3kodk3s5Q&$_*!$#6a6bDIZw!3OkN&(`R8a z&y4|r??eW9{sG*D=0yvfKgTXjvBYx{{w$l*mUIX$Ftz&~_j4NlR#{CgJ=;>ErS{jx z^)&yKvXejX<}IBQmTgMQ6-mh&Z@@d_hQ^SI1gtPEZFkSf&k|G`4xxfQQ+jmO&p_Mw&bQZc|+DFm7^U5Ls<^4*z3z zQ#?(60Z<0_MFXRyWhxMwkb8Acgfu8y;YlzgwUcr^RbV7&%raMQLR^{)6GDjfjsNCx^=5zW3!j;^L^cV%T|QkL&Cdn-2xZ8hCfv zDa41D-O_tcN+IC=>0+zE>bFmdDPf+vx_659%3oFsojqAqG}*ZEOR9ubt+eI@c$kEI z6AorhbvD3KeB~XxUB7MvaJ|bYB908Oph#sKD{fsgXv81Oqy`Njb4`fj5(weYkMV%URg47`3?LH87*|6y;U&BSP zz&PW9tttwjI8dz4H>!tPk5g)KpK^nJgI26(iJ3;d_Zb{6utz_|K{@JTcp9C_*5N5M z>iVik9aYQK_qKb3Ya7 z(fJ>>=ePTOW=eYOehuX8-xJ`|WIJ0g$MAo9y*+F>JEkK0KCtJ&nRC?;a)H6QXGETD ze2Xe@r<+j}cf8Jx0Le*Hhe^BJUMjCebwDYalteK@oL!PB%S^G7$kEUN2^ zBWm8gXi;kdF?g&@_(o^td&^1y_uPkFCBqUh12O#zcQ)a^qG+tVug7L1yp`y|FASUq zpJIc+AI5T!zuO85aJhY^lf}0zL@-yR&cRKQbjcv0Y2gNu1dXz>1u&_<-xj_{!N|LR z8>6pxf8`l%!Q%lG{W=t`$`-zVW=dG|>7+W}JQ9pxagbM-PQDJ0rg65C+sr>8k$VZl z7c*7yCezF$?_1OHRp$`0kUH|)xyDH32upejQ49w+ z$3w$J1Cr53Okh}0FNLri1=h+SB0k$lpUkm+E{%qF#Bg|{x9MmP{}Zq>yUfk;huTGH zH~}g|^%LRts)-w~FnM|2JkC+tT}*NA;jOkauA1}W8|h;gB*Y83Sks56Jf)w?Pq z{v^nu4fq5$cjroK3?IYy;HO>FzyM+bL{toWS46Hr8$mIJ%@s#(>Akv288Egw2b_<_S=Xq;@kAtdW#JGY-}&yQgt&}l-kCdXRh5^)3KcD zu_hu(dW<=P?`{iK&S6~^%~~;;z%RAe@sf(`E+bX#HA?VMctA!#2<11DL?MkMBI(3L ze{6i5`gwPcXct26VvqB0&o5A(xi(ItHEW4xQ9CMO!83LJ%pA28mt0&2`ceK&tJ zEFwBYVVZ^@Osx|P$p|fAx5>H=EIcnT1r2E@uevyTFmUR?IKPiNKk79w(1p9Sg|U~K zxhlm*z?Y*`T&lFRh?dFEks}FN7Z(w~s(M4{B}nZxr?|jQ;Yj_%1r3dppO&aa1R07! zmY0x2DYbM2zVPT4SpwC+ffLai!@mKEWe0)HJx59B?TIYzMtk59Ql*e~0Xfs= z;~2`Uzl+icz3CO(w>4+_I7KBfTUuju$H=uEY$M4en4xJsOodIFX*r90&cBY8+ae4Z zgNYd6CC^B}ZzII>En_XGifIj5q%+C3;SJ;jN}>j6Ea#Ni?OpwFX$wpGVhan!Y88M6 zC9*b8A*NRbfb{)9%v>Fzvo^Vlsy{f0w;4}0&iD(jg<5vi--BI6Q#4AvVCf*B%+uUS zKsMMn6S^*q8{6BHJT=gcx1bQ^*~Nmj+!Hs4j#gCUOhiFzVzMV~v#pv1pb+M&{AjRF zB`uN7>TwgZVJkD}C{#esWB-@aMMK@dJuEJ2YS#6{3#&-c>BqiIe+ed~#bb`%4bvGg zLZ2(?o=DNc4QR92w~Bx`qpgNa*)O@$%(Hj!ELdAHzzNAjYHiyzkQ>jHs7<(@qT{aD zKdNK>gt5{~)O#sBRZuR0ekT9Q$FQDKwMJwg9lvQ9UGcKekyYgRopM#5c%Mc!K;*~s zo{t?$MEddOWEBV1yNXS~%x_?Rk$KKKLQC(wg6X4g}z6KF*R!~&r z3gpIf+dWPdchRWNkr2Z8#>t#)qhEx;_YV-^o>i7Cr)_u{%>*&`z~BrZxD1E;*Fg17 zOlS%3v9e_hsg{CvkhCn>*-;opy>obczAs2i&{JASY^$BecsnodT4mvQatOoRXej%q5;Z8XXK$tQAzW*ys&6i@v>bMK!mBFr z9HplspddNs6Y~+ zE?2q9>jB&a`nMsxp$O3yy;q2*{`bQF7hCWDmCNV+3rw@g1w&3jeXchO8GkDMtiet? zHG_^e&cI3$1@g}tfUuSZx5(289rM)k;rB_?S(fz z?~ItNgwn2?d~2lp9|O&yG`8zw>Td%&02}~ZF-=;_v!RhLl?4AkJNkA&&wz>O6bV(4 z4_W6HApGJz7?5$9DOOdrIt5bH5k+1gI$HtTaI_udh|)GXibEC0!LuV0^}q{#s=06LGf+> zj_~;pBV3Oe1l_(zUZ#`n{8YAa4zPV4z~;36(1jbd?1>E2Gtj<&PtRTFUVk~D2SOy! z{Fk}JV1pEoi;a#qOakS)D}-nEACK=^bKaM<$D!Mx6T07-SvA3NBp~Lb z#iwP>N`Gl&SQya$EXpHQMqb|BLsrPN5etyxIS2-1B0S1ajhk3r_(TezUJlkLr-+27 ze5Ouol0WrjOk3W{X=$56*Sk!}}i^ehrH2uAbf zL%gxW>KGfYWg`}x0$R2gMhcF;V=WZn?13Y&`rs@lR`Q$Zz!0TPE98U|;-7|-=X!=| zeOOmO&|b{bTFzjEKoO(A{sYc%{hE~&IONq_Yp^NfCEvR}OMNR#JcD_LPk&u{nH@zW zkoRu)Fv8X#Ek|gzI(bZXU>a5hw_i-mNqp`?C23RRahOgGZJH%=!KVCK&(y;cfphg`KayZ+V*1bZk2~CvMbSX-AhRu2GwWhv=g^a>xH=Stx%J*|}jeBl6cf=5; zaUSpi4QX<7(K{x%?jDs_{w{0@& zSqhF?7bh21$39j)BbPOqqE3uM4PD8|_LN2gA5+@-sj1&F?Bww{Y(qhN%bG~46fFIa zKB-}%UJ!ZRH#q1dmKoqNH?>4F!JU-F9SM!3#LHMOZX<5*Wn|^4^={M|qILghK(Gx3wFpF)Lhg zn_~!jN21d?U_l|h9liM0(3J{#&TPj@JhFT*^S--;v__+ikgGBXP7A$qbFdb;9XL-1 zYWF^d;GmHB(HMD`*uinfjW<>mXU2_iJ}6KOK(r1dnQ^6-9M`$aokjVi2oswBc7&LMW`vphdl*LWEf~7@pGHVA_}=Q zap_vZGK~IO4re@69rwrl_ZXWP0UQ;yW>|Ez7SlN-AUUNFiW2r$S8~nyyJ16AwP>If ze-?3Z`=^#botO4As(Ze0#Lt7QMU1bv{gc^*lDkCxl|Y|PPMY*k8L$1jpX>XF@~%jX z9EuusSJFJ$9G_T~>y&?v5)w{3mnwg8;jx`>OC85hgiMrw>vmt&V+C~ly}^W(4tnkK zxDz|+dN3qYjj*z$r@bAe+F6olMkOGz^j?Nw|c$?i`1(V4cPFQw4@@+I-Ji_Lly9AHBW1yf4s z26<=^Pz;Jwo{GSYel!+smRP)hArcWR9p{9mya+v3gU9}tuxywUMi!`Jd?s3Lb#vXS z@xoG^gYI~j=A`C`ID|^F&dbH&NQ*1m_$aX;U>_nm>mO@>Ggj1(ov6GRp8;~=92rM1 zlZrnWFeEG7zh^2cTo02KR)2vhHusua=-7bvN-vxL@w7RP`N4>17YLT=8|`h2x;)MA=gMDatvd5_ zf&;!5kac5|~#F~kFxG-?8qBIW_E0jG5 zKn}<r$q{GKt%Q<;f9{uJ^R7quu4e=;$? zfp#{2eu^TbbnP#3626vURu^jS;+D$zzIX-mCf&#!Z4Oj|92nU;zvW~$HNP-mmuxfP zcF0l@Pi$xc7gcJ#Th&-$N9{W4Sqqy~-trICqQTO8N%mH4I#gr2Nhj*~vf=9*fhU@I zg1RZC6iCv?)EXEF%XTXa_jxk;u~*!;d2e*ckLNX51G*Gy6N9+7LJc;co2R6QIH+;r zReh~HxqfG%0*6Oh8;$QoIQ7{=olIz0k$F{B0yb0D(SlsCf^Pu!qWlA1T%=DtVn}Ho zD#8*brY5rq7e^6fT@GFPPn{ZblxR9UQzH$?K^Da&wm3kQgT)6{3TMEvTU~xT4mDR= zl{D{{HF0wv}`wLsxqsO6`VmTQJPeq+Pt8k?k>;2Td@7ZU<#W=v9%tWJc5O)he)ojZbkFO7!S`Jd)~*B@hP?t{kgnRTh;OSx-q3WOc6`bJfsw zC#k4a1YS+5yZpS~U7Si1WCtp!C#K$x-ILCZbjveTs{LX@o)DSja>X=?7JxV?b`Ph* zWoydIEEa@0Han&LD1o(!>dMPW-zBq!iWV*X^saC6IzLJm>bDsDj;HnLC{R{9r+fIe zOcR1>-Sf~hmOZV$rWxd}msll85pthQfsy$NK3r9z zGGq~1lVl+y(32YiV+aiuG1mw5B@lckIY*!&eGjL{B7blaf?XklsH!B|FePTKG46v- zC2}A$nQtBEba2F$lm}Ub$MZ{V$Rgk|Ec5Q#{9j-jGq zIu{v8qAaq&ZTQ+8I4d||;#@8~Zn)g{;(v6x`9wTlu+uZfxl$f{BLlgl7=f(}i9T#Q z0G8UuBiZIj$EYHFhmc<9xqn`up@{(01r`l^JR$>4@nGXoyb>8KkL)Wj1>!j4s$fk& zt(?vDhhjQhhHVvVPymVXK>shMvvcz?A>M#-?T1F1c`P)M{WNlIJN=l%Sr1Yv^>K_y z2Q2vJ8^rH?uLYH53uY)77(~R9${-vJxlgLU;q~!$GOM>Q7)Pmq#s%abB5!C{e-S(c zRPkj-*>4lQ!&6%_@^Z?VH2$?;uOPiav-kakJC1W5!mD4JVwjhkDG(Hwr7@R`<{vM} zA(R-p)0lm)Zur@lgwp?*b;&uVXLubYKBP&z0|)L~Z(>sd7?lSK6f`>C&7~U*N%TF& z+-*RqABugI?Et3KQ*1wh1TxWV7EZ_l_6tY=mSa6Nz<;2&lSk?zBO}9s84Xl$Kwf`+ zkWkUg1K}>$;I(0oNK6*W&m$D5gxF*_Gp^O~Qsv1JS{(x&V(@3o$q*)3z`mv+YD(AR zhwly$J?B+*+33czP2Z4L>}IlyPxST^@#ZXW?pX=ecvujIy~ECNg)R{rPp?62MTzUQ zUREXRGHIiHc^`dFmgp1f5ZTAumm8{<*Qy+}vD{BXS;M}>JbRX^qc?(xV^VZOVk6pg z93k8m&v`3*HN&^K(bVz#Go(npA&yz4Eaq(#e(3=kg`;De)Ih_{HxF{RNk0_$OSvG?dqp8(zU3VJD7!i-}EKLTky7;g2$ z)%W5ly@*qaaOj8zpoq(~Ibs&;_`=6by2D(V*^E%@pVNYUq}HF@%h`E7zYf$R4p1*x{fp>z8zqX&aotzBPOU`Bit(gmr-{f6F2 zq(}D95I>!b8-R25@coZ$>MOTTkP%cem$q4=psrhnHqjd@zVN?{cW)a zmr;J5i?vPQ?&D10gH@?~arosW_ES=hVkzLHqTZWCe2(1qeOlSkUFPU}?|rl`&^btJ zDy8?VP(|)yn7b1KlQj5NO>g zHtFn$j|QEw9$+0vkjc{08wb?kC>(Z&y#XkW%0Sk|y!17cPG>pJh8kg3v`1_c88lBz zOUrW0L>ceS6J&m+F_;={Qd(vdy_2CgUq-XElpG5>KPseFuicw9c2i^*=aypnS5?{utr1eC5pbrXK;y*cUo)K6g zt(=C^98N=1O*DC%SXQ1Dn9#Ft`?0WaP<>!^ z-VNzB_wLS1o-VhtBIP1xq7(f%-}7lZL*YYux&%Z@F+^uR{@(mzV$%)bpYCLc*APdI zhKDb-vsWt)_Wx{~0v+}v5&xwJTNAqLB`q9`n;w3y29*-(2aH=&9TNiLTW4!sYrqUg z!7z`Fzm=3ksv++N*7N*Jl9H~v1O;Dp?saZ1`*@311ky-GGIioO=ww&OD36T2dtsE<@oVmi*2r0z=kjqoC zGPT6K@@%BHzq4#3`3_TXPSGKigQ?scPc9G!#e5+ba(H+na&_`BfeBw)50nq0EC~33 zk)N_avAqASy(JlT6`(=``Nz2Fh_sYP%V>d%U(gV0M6g(S(o0oZbK(MZCClFNw?TEm zUOW-EP%b=j?OH@WI$Y}B{W&`Ylyz@oP(JWf_s9-)CI7Kq-jU@IZO)Iyng*KY3Fv4= zZ7B^2k2H?P5oL9COl~`cdB3K2{RIszzV&&Z#|SUXOj6kcWr2e1wglJ$`x{?SgF@d( zBxxfNbF+-{Pt#grb<4C&EYqx{stRecDJYOAWs3437o-f0^)+ju0#OB+V{0n}Hu|Yf zs_Drw2fG3DtA@RBi)*Yd&sRsFgU?UvH~rS#I6NXkT;RM#zYV}uF;(TB zouM1vMI2K1%(eZt^LHN)t5A*~-FYpMpmlfqJA;c87S2)7kuJKa-dj*}Dlmz2BCEbN zX^GxcAL|1VD{8z+OsEu?-y5oq&)}=g*AEh$Zw_u2F1p?Uo@7QX$;+B~Nm`Ui+igRP zP8#fsYaDL!ZZ-%PGy#Z>VZJJ8hXb7Y+Ac&UGL4TbBriY}#TrnY*lW1*V4O-%&ll#%=lelV&YCfWPdr7Z~^HH*LcQ-I|D*Q@#q zWuMFT9jFOhVEyy8HJ(vq1t4xIvec?)@`hTn@2jhFnws%f?M@smP-o2CNsE!+Uy5H9 zc4>}|;CU-p6QWZGUviG1gi+@u|N9!3a(>N6+qw1}XXMN|rpu6V)7BG#X@&w;n-q69 z-^E`WrQmb1-mpIopuPSqF3uuGmm#cR6cS*BQ)XcDyQ(WT8|^tGqdQW*m|N!1leffC5~jiD?I7y#ua=JA`1_C|PA*?+J1t#_HmIB|4bS5!Y{V$vLhC80 zv|7RlK7r`dJ&NAv#mgg8>lfegOEd<$9iy;NY5=V{M<)0{&H>iAt9Fgz>F(DFZ_b3B z2?g>oC13~S^-3BY505U5ULh8HH(b92!D28mGt(c)!?d7fYRooH5jXNE)p5SYHsk@? z@}4Hk0F|N_CG|ebmQ`6=WjJ6!sPFZ@_fe(AUc6kOTTf`|r}#5oU9r@ys48GA2-OGz zeD0(Ww7yK9&WsqNlgql=ai}w+7?rfCxRN z6LGM7YW7GZk~sm`#l&hjo{VVRAi0kkHenld;O*fZ_}UK_2BrP zzPuA&3atUOCyzEB{CX^)Ewx`mliF{_K%Gz^)n*AOTiI8Y@K{%QN_;t3f^Jn??wPn( z3E-VB&d+mc`_j1m6y6;sIK?ssYSg7E6dqNeqy@=rv302+j?#C!5eQ`T;fKYH=6fC2 zh?NK?S&axO+(FeV&6&dCd3A{b{qugBMUW&!DLdQ}ZFJz&o6?5wwgre}6pA*WiUVQy z$%Z>dUZQel5N5J4=`CxSR02rYm7yjD7U^r^#irG$hz4M-u1eu z&*XNgs8Z-sObDiDn6qmFwAyePPVy^eq7gRNP->EKF)ayH%arU7Vo;5cAjAms4-d}K z5mBltGOIR0*eFuCo1PyX#?8tpH#gsN>rIwfV0=@yd|S;yma2rE5L>fR1j3*}@>d!^ zqOut9>rQ&kj;e)iq8rMKKU_tt3Noa;Y&s*ZjlLFmVR?2R#^U$Z)yHu0ytrObDKPG0 zn+7D5bRA(K;Q?b29U8=?+-?KwIF-P1dr_lUOP&BxR<&7A3Q*V=&REeT4xZ#(AxA-x z&d<+Zi^VYvLdr!pXGRlsx{!yE86}wR2#-;T)^b1jteZe?Lm;C-fgrjOAOUDrf@XQ) zX}D$kbw$%wqpjw$g@>nuAMe7BTd}xvgcZ2aCrR>D-sA1-Z99Cm@7>j<1!Hz?!?aSIonxkvs(YDa$^4)0wx6I3tg z6ru=G9qvwvy1FM~5hb?X5179wy*?|Hh=>M)xR-KAIQAirhP{q*52$3XChLj>{V(W+ z2nX^@l$Svx2<(55C_oJe@Y|9zdhVZ=2O$_fCSVz&$9Oo76n_^tMeq%Ct(ZCz==J?8 zj7rLFip~$)_LOq`Pzp|agu?0^mnUEFR`SSB1ffg6E$FgJmvQ~ zA~*k8QTPEIiDmkQnA-%c#Cq_bH}Mmk4bT;!vR({ONQb z=)$j^r{yFX9Jd|85o-nGrw)_kj*1_1Jyvk5ZLAA#^3W@B)6DW zD9Un_uXc~Z&Vuuuk3Y)FxxyG`+!v%8kRJ1GaUx8WZZ0>@TRyiV!s7(V_=)%3-4}eD zSbdfgf8NI$8=HHcO_gl(mXM$FoqHHZwjj;QN~&2bBcPCCAo2Wq%u3`4{F)w|P57%{ zsF#Ht8*fPZRhQ2+?Ttc(34!EA{}}u(-KrUun3FIJ@zO#-fu(TYrXRf$@8F@96pm_4 zh0vxPt#nf$J^2hJ)R#NccGLI7DSCO^B%9tQa|8draT_CKky{h%;S;eYbuP0ixu56& zDG*S1H}z>vH$$FD>%hxlL!*HVr z5mV7hb~+kaB}T2;>75@Ed%9lS99N3Y%T?K?Zg;0P=@)DWOZtyPt-5z`dQDP8KR(If zvMbvuHV@VgALeeV{~J{}SmNQs$aP;EsN+!53~W&Hv&2OeN9@X#;3XWSXeS!oIo@AO zvOgMybv%M0Im7kZ~-Fu4@!5QAV=mAiqefFe675zpY z;eB1kyL8$LGN#oPrFUhKhCBrOvPD)QKtWhSp{X<8v2eRt4Rx!AycH2DxyNmRD?n4h z$8q}d^VovVx<9t%uQdKy=qW$lO!-4NkIGW^ow46MnssuajkeGC=@vpZc9jtE z(uR)8+&~fTopVXGBX^Wy)3^O&Y}n=yoU4NqQW%*)oL*LITcp$`u}6cs^S!5V@Z@}= zj#6Rz@Xj@#QnU$HOwFbhaK1g3YT=?-?i`j}GLE-ex|8qEh3CDq{|8ka0ZjO6wdy)F zj)-q%({6qrgXf40w7eYjycs~BhK`Exd19moQZ`$vd$|)$rh4MA6>mTDxD8mv7|53PebO*Q|WdD&Mn(rPVc51iR*9l`SK0>hEho zEvt6TY53K*pa|H+tw)mYX;1&`nWWJ;TgzYL$G4=PT8+|NtfrxggWbAxCQ)>MK0pc6 z>u(sUn%d~hO{Y}gjZb+#f83-U9VSr;I34jhsYzeML54b;49l@cVxmnTpDu0xUzMFx zaAraK?Zb&}J8x`EtT)NT#v~KlwlT47+cqY)ZQFM8&-b0Gb8gPXIs2wBcI~dN?ylau z_OsS+wRiFRVjOVk6m;?D(Gqcbd9SL?p*EpuKYuzL41QKE!<)~KX6q<+u(=ShDj&xs zpk?>BZOh)DpgMoS)Z>j3j;WsbM*OPYyxxHXH)st!Zq&V@ttmR>b>Cwgc#Tv^C~trM zRWtk!%aDko`+)F*?K3)OW2KjiHE~9t6=Br2lFv@pX4>+Ln-PxxE{=@HECXb)Bal|< zQ7>vP3-PziAGzP!H|r9RCcDJOmRF6JE$6TU5%*zpmK+KK{8{rvc*hp+t*-lF+)V&0 zJg)YsJT;>XT8iA)k(KPPNAue}sW8{Puf^z&Abs%n^YIklWzEoVZFsS68MGfb&^KYn z%1j*Wex+bzNBgiezEFTO&aiT!X!VElgomu_2MxED`;>>6_Atqs%X@EZJ;WhhyWwFCe4>I#KEK?{8L=^|Xd&{qZq@F-o2UA&H1) z#M6@xNl;`h_Y>f_L9q4d-U{VeE7i6_Ae6136a7pjK(m)V?)0$kRBH02zczwbl4v(a~cKe5#fSoD5 zdbY-@&q25JtHc&iitgg>&s8<5de6FAh2b$Ev$k|30og>(VPgu`a$pC*)ccw|A#`A#9$451626Tky zi%hTJS1>~gilj1b+xivSY;HSZyXMfT!M3I<8DhbGJar3@+fkI5Q;eA1!U>Z5dQuc; z82?=I1b}7|yR~iol{t|xYt7zXTGms)Cam%gK4e@PVpUKy5^poubmussIqLG&ejp5^ zJc)ko{$g|PYkd~mQO4ZZQQ-tnn{18pboXj2n>=yUFz++_Vv-U)(Q~_E3o8X3gw-&7 zysQ__=kxg>dCRN)?fEb7`&@y!J5_Dh>$kw9k!TW!#qzi$Bv$0m+mp0AErde%&$ywi zr!pKpHNB2eN5KM(x0b{rzs?n}xp~A7r&>IThjmHwdxOc7!EE+|oe2f?lvb78b}je? zyO|P%?Du>;2h}IN)L2}5WWF<-BtGswz>%ZH$tDKVr=19A)$}h%oOJ?GA^cXWy46lW zr@gXM1ftJ;JRfb&%M9-sguYOBX*FhdY>QhRuS(lT3pa4eL_+e$w%TKXX;^}rtpd-v z)2{P0_+7Z9pZqK7^uJ=xh=oPiOA*m)J1y%GP9MGvFBxe(Dr=|=ylANp^J519*bt2^ z23P$lERWd=Ob=0%MEQ6Q53QSo8rr_zYWOteme=6b^B?(bo61wuB$jLua1KO5aky|* z$$ZU#=AkT2oq0w0jg3vxG7B`GGWdjdt=G%_acVd?hE0-EEsr)N<{20k7(p^Qw?y5G z{rdc1KPIpUfFKuO&U3yXyA+$phntq2K0J z??%;fWomo5;$4-Ws+x2w?g=H>``|aLf|HJk3Y+ddf& zMl=jaCgo4i%4w7@t5tnFr>%$8%J@2{hl#iCf}nE@cWyrBMRG!8dzefWEj1_~8Wl4| z^h>p&BHh&zeC5n%j-yfqtli|L#Mlf95|sI12oO~a`7|U|$m;BcNCA`OU^NV;K59zo z!Qt_6-`@noQbr33!Z-35na{LGh(em$j*r`Nn*7?2*#Qx_R4jG_RKh|hut}p}+Bzbh zFv-c%FzMa2SV&Yjd?vXI%a)I9^BM1t@mD@FW1SAgCC9V1Ixe2CBy_u6z~?D}KR>OO zmFm&>Uv9R!;`Ul~Fy*u|rO-KQeY$6OQ6}U%nQf$z&fj8PdB1ktZ|5ZWQpBk-+SN+D zqstV&Gzb;6aQQ!nVhY(A6Y|t`P+DmOO`d&Lg7RJ0aSC5kSXiuU^N-o}OCnIkN;wE2 zx1S^x0X?ZzeYS+fqpktpX7C(VQR-tEWf-R6fwds`TMt(43O2f_naHs`@fX`9w^RfZ z)`e|%CGf($`NIG1Kquqy0_!oYy4Q~et{F@SiU#iFfvt!zvIM6KteB^DU=M`fLf z4%O!k#ATLF8_VTkt^PWlvzs-|#7fq5uI<1cI=Uz-~er-@3Ylf#XVjh;W|*2nV%OUmD6G6#4f z$&|nkIN|(9>#{hi~pufh_yF#oXaim%q2+5)|oGBIWKr?~PXbE=EgU z=&U=~wf&+D!2+TAe(d=ny(|5r{s!ObtOzxE8b!B8k)O1vfbut5{u*V@ zm`zcGwA>sX6!xvkP_Oc*LuGzRU3CkF@W&65+^tJx(E~YAewC9|UO(4u`&d}Eg;cdB zsqwkOW-{dlX>SpNT*Kf3v^eNW6S^JU+F4BXOa(pIyMUZhHj>Gg(xS_d$SSV|OGKv{ zd@`2t^i8m0Kjt%0j7^hfQuEedqCS8K**q5xGGuHR|K;IyS3*gguUil-C7D`cz&4=3 z-39H+M<;IB@~fA-&Rx~Tjl3Z>9!ipGI7CrWapgopDbbVMKqC4uSvo8yJdyV(rP6b0-X5Ej$Q?kn0fHiuA;j0Yam<>;dEc}1SY9DDrtTn zpFPOSp_p|q!hy&`Dpis#4ACbxBZ>;=0peMiCBi=y zblV(S$o1q;meA^mPg0GS84NQa&ccMUaLeqt7n@5E&bA843WmvSXM zq{fD!t+v&&=y;%S#j=94Z88&4-Yx?0&+EF8Lo`c0rOeGcKQCbsQZh}e`z=}bD)yJZ zg(s*xNz42gc>?=*y%{0W@}O0BMZH7~-$?EypxV}oD}(T$yy|TMoj~i~`}%;zhRmgO z{6J`4%2AMQy3x3;$I+)c3jkf|*LQ4fzwc5lBemsWKa)SD#g?(K8FK(ME1r~G{ovWG z1AF8LL2YkI?i@t~nP_EeC9h~|?GwyGrr42SM7`grP)mQJYl}+H0C)au^m%$5`Fe7X z;1Si*8A?OFg&@AKdq9m}v;+0qEe2bWZDWzo)KH(8sBFsPVqL3JmZ2^#D|yPyj;?D> z1Pegl4}VOdW*~=bkmMQsNA>E*l4iWP#a zw>>Nn7j}Ay8sYvk6@!ida9J}t14ORbe^MJ2`8#`fgDh?Q&EOjuKsoo7&RLoF3E~?l zdOYrez4tO{(Gn69foM)9wd9{f^`I1Ks~mmtvRbvLIjKXNu?*{9?Jpw|EmFRo_?`r> z5%%d!V^5uo{!{1PmY4?&&sI4ct?9u9c=U(bw(ikN9F2w&$Rn1&l5j+NOhE=dHAtH; zULDEqqsHL&(@+eALQAKP7)~VYt?9t&^kE+aXx{JGfS} zpYOw-#s`#D%L&Ok?SlkR|LPh{qe#lpQ94Y+#i;mAy2diY`YTAK z_AzuQDznG(EH}2zz*dqs#fdjhCf~Y8_*^enXY$8F-!c#mGqzeJNDr5^u zj)aAw3W>bVmYv`9EJ*-nVgD;AgVr@mGo$>;LsvRfng_e1i^B(W(c#*9>yuJET>$Qy z%6iERK;<|5YQ|9EsuG_eS`A109B|p##n~s0$^rKQ#a*zJi|~)nx2l@E>2uMKrA%8l zo;_(H1%Gl-2k$ZL%jD~bds=Sy&{CuOYI^D8Vhi4dGVzjgrl}vuo@E7N@ty9}g{0Y% zVj7qq>n@eKeF+hqj^Ck$<(uZzb4gYr{SyALArFQ#Ckg+So?^ixGsB5YyC98NKy9q- zJD|WHXSmaB<`6v4Tk=6xEE>QL`h_dU_FBeRK$&)fb`CO@@wZq7fqQt)9#PSt(H%q+ zsNP8owuw*D03xfWm+z069aPj!i@SsDG(mr077mP#fQk-lEAi`dSad%|&ahX(gv#qi zdcS`H9iL#V`TD2V_x5x`(}!2<{SgFl*%_GpHXkm!kk89Y9QkNHlYLTYO<_l_t3jVk z@{8Tw)W*Mw`|PdQ#6~wL{ZQ~>Dz&O9%_5@Nk<`*xmJZeh3MT>=l_RqvWZ!V{Fz5~b z>cwC=1&KqyHtdIMDCNtlXbUn+IH?y?L_M{6lSPMnw9J z?2$YSq11GXszXt<65BW$)b9kO=f3Q5bge{|zp?fe^$fjFjRC8a zd!oi}#`3>eG^}S+g)KK6Uj=HHQE7(wS+V-t1!f4I6pL-#hJbg1X{N{hdGap*R`VyP@>@5 zq>zgSoFTIbjlA*tbhFMi*o>-r7B5ZmP7&Zll=_lK8ieP0Kprh+9p7|{Oi%uPM-0#V zWVi~iz_;**{TBQMkpYp^53WZ%y~D+hzK5U>Tl%eQo&?pp_(sdmHbn$Hhh;Js_ti)y zg)gm4Fz9?$ImA_Y{)=Z!U$Kp;1>lkvI`%o|RN^qY$R+(HqJ^SHMV3`E;NxumPe!fb zyU$Ymm{<9fcjJPvVU%*If%R0K;F?f|XmovU_ybclEO$r=ff76+Mq$AZ#0&y)Mq{T1 zlgK`~%zsM4hzUXt+cALbW4TGZbkx#=6KTfvTdZ9CeemM1Hu6!RbXsqc)m9d=!QuKM z;$s1#Gb{mT>d0HZ3Zt%8hbr%2cnwmtz|N+#5T)4ePg#T@H=KHE_NxPP&W%8TYgci| zIo7kP-<)BN1~7 zq}&k+A=zFYQP)Y9R>dOCZXI%WC+8lyrxcD5`=TvAp6=#`xnHZWLGF`bE=U|JF!6q) zbXCEXk9C6<`^c4sh9znt)G2R+laD|$5jCx^;E_%*Y2lfFg+H}s)g$mScs!(uS3%94 z++j3@?TL^a;UCfEIBm?iS3Y>A8T<*va;(%8VK?jl9%080P(5u=3eYo;v}%dZ6C)Bv zr>bxzfx*}n53)Y14gE$h0s$c~mH-MVE5K|U@(NEJL%D^@=rsR%N4>iL5r5YJ@Q;## z=6;l(4lQn{xK+lNUKRg0&N`j!256k-VS~08=h7>sl+tN2-6lhaZl3EuVt37;e6UEgWJg<zyM&4r<*N$mTJT-1T= za;MkXBz_^U?sQDaa7hSCE+J|R+$^e+%Ph%ipKW_v($6d&-S_r2p`|aQKR@bfMp%pC zk1bVY;376#ZmO6EA+t|vn%_v_Eg6{)r7jMgFr4{=X>52wm6evK3w0#?_`2}m$eCGPel*+*LDxiqhc~+r@j|=XL*h^UX zP6ox|>tn{kp6*rKxFY!C&fKxX()!9oWT%?ytiCGK(*n{`RUfN4de8K+PoJeO$Jq@cv8#O!i@iOOx$?)aTc@qCKi0bEL{4MW7rAe-XR3(IDYwUj@F9j!r`7m3Q6AxbJ%T|p&kvd&7 z&ojKJ0@+`YO<$*Fq+=UivLR4hTR-l9yJ5akG>PfKWeT!ECy6c;zmBxCa+lg3I}va; zZQVsEL50^$X-8np=q(I-xkS>`QZ4^Rzoa>(4S@UyeJUu1!I^XMI7al5)k(~su;_!) z4bV6h5h`-onI*TWn6)Q-c-@s)262;MN$33Esi+3s+h+zQl zIKO$wj1k6#Jp)tM|2?4HGjvoNsNJ&S4TYIf_9>O=W=uQQQQuD{BgH0fl`ot0T%FLTPp<|>qnvzk_H zf7<4~{A2JgMyZl|Jp2+#1J^Mh2Bd_oz%{IR7l9%*U?crJiKjo5LMPu_s&L;+e^rhS zcS~hF4rue<7AVJg{cFt}z)L6qm;pZTHOM*zW%jF$h3=obG;#&-GSh>db4S}plXOP9 zsa>9PRNvH_%R#;B!)5M(yPz1w_qiGp->GS=EY4X=^xf>9FyfucNi*Vo%t2#7a<Bu84g5Gy~*`?NKbBB zU-3&cGT0&_aMC8T@`O7c@_Z{Oo-7&!$Lujfeh@a4 z%btqS#bN$+|3@^Jyfprd@A}aiW#g6pSzTaCdU3j*FC{Ib!9W2bT3nUjM6?_2_Os;) z9`BbT_NWw6W?|n9QFS3DK!iEqwOk<39`U#@r7HZ?KyleZwr>D#S)?4RixLnHl67D3 z)$yk;3|qJf4dDS3Vc<8i&w82f4rI+)RmqTIqR5K?n2mSI+^Dwq+hh+5_@iDup@EV6 z0aUzoZQ6*-7_G{>Xo@;1AQv{C07LuRDXH41KYS$|LWuNz*ZY44Rnt7@Kuxc+*OI* z+e2ce!CIBMpe{sxGD|0IpdghEDx>?)g`=5VgGW42jcuLsnvJR0pT~I56 zx~IkBJ zf2Z~vYCkJo!rfgOW2EarIdm&1IaYB8oD28-44a2^DiV2-j^!|QXxhkV%p2S%T~=_k)tC=sCUMo_jRjh?&MzD8ndye9&6l8nyT+8)q*ey4LK-6*)CJ(&-fBEa7VYqdBX zV<^7h&Kimg;fG5->-jFmau4wxINuQdTR}8^AZ`xhT@PVI-}zw@0Q@gX?Y)4wdhpuA z!dzx-M*RT=!4~Vm=?5}WBzDWOkSeSls7{(-Xhl zw9$p2U{mIFPt76<8g|pUzbTJ|SFDwQS7)vddK5vOgxXSflVT=}5z_bDmYRoEIOe6a zdStN^*GLB}H^f9YioxG308fm&A)VLN-WBk#!9cr?XgK=Rb4-D-^9&40S5SyXM)j2F zboraY_!vB5Wf*OdS*WhmPsoSbo|#1af2@jM>&|AO4$Qw+Fj-^20SLWuv=& zCAK}@&rV0r!nvO_zA1P(9pAt!L@_XKRu9=W4DXmHQkx89V7A2Dh^Tp04=C#YZLh%x z{W*z*r4G@)3fbymaMKqjOPp|7YS|#3(_yu7u+jR{={ESA&<6Opg=D zy(gwj`j}S8*-+9B;0D1?6x233SS0S=h~h0+Cg!!U(EoM<{XaU#{WyTzdRh!9@6NmL z{8frt8w&_9c(-fFHR4$+NH*P19W^3{G^b?(ZCX#$J1DbXwFjHdECD2My%U9vNLsh@ z{@)lbOt6XbaNL8hWkn+K&KWAqP;08uqfJlwvH}J&GV#ZL#NOMV(1brQFtE_E0YgpL z2deA8ZQHYc5BGkwRb2)W)N82e@KtUz%$4(vXByRY$u6G+c3xx%;+2;4_!YPPB0vz# zQ}FUQrkq+q>(N5Ice*rWlJxz&@9KSi{Dn1e$81wfa#?d=oB+#bxGG7gFg}C#t&~9y z5@dbL%d(B{Kfa<(7wl$e zaztii9dE@sAGseDML9bCnqtoWfXc(^!DE7Tq}F>gr>D+Kfa*TxVF00T67WbfR!%_o zgT+fDS9C~{urVMdghF^bR?t^-s}}77PqUY84VnQl?0#1c(- znUc3kni#}gm>Qh23PIH%d7$T%opCGqRZc9o;Bt1EJ{+6pbCf*HdJwr(_wuTa|N3Us zm?ZurMT!26muf zhsJNs`S~44bpeQUG(m2qgyfEEW}+@rOJed|U0WU}cJ&aCe*O=R;F?C5mYDY%V*`_#c&%uFaCIcjgmj4lKtkqibY>mP-XoMeCK|EK4umx7v@( zqL${Jj~Z4JYA!e%1=~IGBJH&)C6eA;u2Bd2#<}FN*b&?Txn*LB-g}qP>u&a`bLcL~ z@~NH0zz88@wuI7!;wx1`>x+$D#lpAk4w!dOKXSWs9KRGw2r2;YGpWKqLyV%Us|T1ODLio%>GeD&sk>G_tRyi26q{yIwcc#(sD>J>4c4aFzTYSqYx{F*1{l7cZK> zRxbfikq1S-G&-y84&x&HKj4dhe1iYN!t4pi$!MVZbTCGTFS9nUF|EZ{&_NWX?L{YL z)FUb-b$LH}#l;w>dAMS$NJz3>>U4NL`m!lelOg4ty!#NUPtC-2j$r((+vP9;woc%- zZk6RWjLWI4C0Z9+#m`)<*0YZI$23=0>fBG5rR?HzZZ;$PS!{CSIa6u`o+rd(BZhVk zI(+LcVc`UD5H?4(e4Ut^6`mCFZL=P#(K%{bIL(;5@ULw@`3^3aJBv;m^Jvh95RGv8 zo`wp)PEUG9vq;DW2Z2|aU#qZpDp4GHJ=wt2r|8a(He@gR{36+wFn>$dtM}a{D_m!? zvi%XzuD)os4ClMm70B*haNi)!MB{Su^^WedLmYDENYTEWnqRy}zuz_=c%%uqj>6}c z#2pWQZ8CZeKabc|7kIJL>+uZ1)#DnHfTnguX*VRd@A-~Qq7=jJj+z4gi?&?F0UZPP z+GGF?EY_~qQTUzHH}nRa&Gp{z03k_Pb-c!PE2eS;+@o0$G1-+#*tAf}p1(Fp2;k_| zr+eZX)y9IBQ>UNE^uwRy>lmE?Xc9tVAtF~CrQ@S!Mp$kFDT%H!4R~Z&PXGq-SshAf zgmUKx=3D7S&Phz>Zutr#6U8EJ#4cAvV7#WI9=g*r!iur%*XulR{{oH7vZpvs0A6Tb z0d;cS$5uRB#lrD6Yctyr{S^%S)Sc8HhNiE(`ZL;uq<9&)$=Wtlfa8vhtvgT>y(}{5 zaAp%D`q}1$={=uX+Cx5Y4=)Li^j{};64LH4g?YehlE&Z&R39%Q~mxkkvnH1=6uv{TFNN}+1)X=i#T z`(5ZP;N6P|iRe*}LGS69n) z^Ya0#tZZ|t^G0^_;;J0ioQYHk!Rx*L;EF*T-e>O6J44?k5Z|n>~Y#D`B*1!7nf#JG_&?} zT^%DIb-6>ENX90q&=2^}*G^NG>@@4EH~X6yJ+fe=tTrm04b9A0|2!KrmFn@X`@h%Uk*WSue}~Ikpy~dZw&o!>lV>jjF0{Li zePH8<&GlbKR}_dvM0n2zb#E&EDosTn|77N9(eJ8d$AtFyIVuoYmS4;US~sAUY!^$t zkb7@>WOh!;PhVg5QQ;57FcXM7LCU$7W0t6o#>B^lw7-Ml0$E%HFXM_tEVJ}@%h5kGmr zlQUMTJY9VyVmy?G{kSC7+Dm*Y*Qtj$D3qJ_R&A*Yko+^xQmn7RS<7*>d ztiZQRgj-@P&ST~BdMU*84o%}#??U5Q=xA@In$DCz6uA{288kHHQ?@==Om)O&&Du2U z65O0#DvtSV#MfF#%dn__J=}c5cmk)6h!~_Nc#`GfcB&n^>9We6clwV=YFffR-Xec= z9pM;O?ScYW@?x06<7nT=+HceliLQ`n>u`Vs(M79$ z2d(mq?buc!k0sq2SHukj0D~?TcdTkp>6*bXr>HKxWg|3+3#@~ z5G@e-T7>654X(&|zm_4jZ@BPB%NZQM>XjA-vHc=_v)T0{Kxkw$hCJx4Fhmv}t11@;d3jpHVNDG1-^aCS2Am7tQjygA+EiLHaYn@xdt?^JxwX3L?J@r(e zXLD+$Vy);9tjDc_c0pv8W5d=i(zyT%9Ns)pY)=o#DWS7-Zw@4eCjNU+Py%?1V;i6) z>GM&xA0mJAs3Eq3#sRh>ZtV5g`{fA#V8VykE{CvSTS>k@1FS+p3PqNAvmYHv(@xVU z7i4G4593yg+u_gH1KT`6Ah~`CyDM4_XV$q3Mm^i{o49XEa61E=YtMgDrz;G=0Nt=B zX|MhGMmNJ;BI*-L_Hbz|n$~&&m$g;QgtFfHO*F(JxG<2GaM_DLmQOL-D=TNADFvu!7fzsjW3*Ujjn8ms=) zcHDk7yU;UPX_-9x69`lhK`>#%Ly8>*w)Df5@)+T0O%Dgq;i{x^BhX8sHOkZ%Mm81A zEt*L+8kuXDDX^l-TyTdfQ&cuISmv4^1LwG8nq&v0mI}&$xdvibqGHwD?CoMbUY`AV z)7CLCuq{dZg6(m8k9OeK$^LpjdOwO;2Q9#gFU@8q^-=$YDMC;{ketQ4bxU*Az_vW2hNsIM2yD5nl{^loiB=n`n0ilqtP3^5fl?Kg^9 z(zny%O!g^d*RDTSHich-@Ah#fmdI#hxa6Qvv4?bXD+w6vtJYcGYGVHDMT!#`qsXG) zyGAk03e#YD0!y;($Q-046i>T_bs&q@WN;0Itj-V7-<2V$)fqwHOaVKwxxb-T>KTlC zwmrejdJ2k{9<0ZjwdK7}i1k$_K7=}<@yD9Y(`*NK?|h{Q7yfm^RL~JB#HGk98EpRf z1WB}8OQ}c2h?XDV3A!(e(CKx5tV2LE6Y96+?QJ(YVu1%R0ayI%-!{Xb^O)aOmj&v4 zWn$+qVcifVj*Gy*?_})rD6v2EY zVWWE0!TpZ<%{_xjfz`~R((I8v15S^RbNITnHe=E^@yhiCzB^Rg$BDpHY<)Mknd;dQ z1LO0Vr%c|rKx(N=;jW^Tz@p^M50~!953aXaQ0BCZWR=Rb6u&6QT$E(2)ci;7AcE|! zsLim|-C4j2RmacYvPy}&gn5F1J!Mp^cGpK3Rzh`6hEpGyWfC}O5U{Zz!MaeIcUX-j zTt}JAEJr6Ut>RK5mJ9w}V>xh%{jf|pn>%r9Jl0Jqj7q$4PI8zM)p$4x8*T}(28q7WrV1VW-Tx9^GZB=;o@gZNEi8D)U6 zrl0a<AtDlj0#p#mv80q5!Myz&jy1=N6)wN}|1U{Q;R zO)ZWA>@)I%@zZFpm370U8m&bya>V|L?`&LWQL;v%;%onvg0M*7)xW3M zS4hw_ugQGn`k+-lM+$;`2_U4!eqp>2^Tj_(f(s{F3)A&s=}R2+G4^Tcu)wG`dq!*S z>A@#UI4N-lou1f~ePbH<{%-3rdQ5NKGHQuuRZ~DQay01h17YIM zdLAVI;nWHjoV$2*_b{**FYRO!zdABEodY?|3_c;A9^=U|_C90-Y!tSv^jl`Di z`5yUZ8Lgtovj0GjwAdW-OX?k>wN$(ei%~Sb#8+Suc!N|GdK^Idp92UU^zv;uPL1S9 zcb$cm?nV7v~PG z=V_=@7%L2JYZnDz^xm~nz@q2JSgX|4*Qu6W19dJ;Itp_pXF90-Hhd3_6%kT$q3sf# zd{VjGTGHfk84_*S^CbI$cw_X!IbIPH=Q|WwY}3N?T0&)eiR1YIwdL8+?!z{MLP<6m zf+zBErT!Z$>|huj;XCdr1Q@y*zKi}C!CfKLWOW#~D^^7s4oneE>ewMU(98e5)R#Qu z-qEl`Cyx@onL$y}04KWi?SHvGAW23Jz4_#9drSQg-E5_L6cnbTw$Bjd6pa^FxSxy% zJ?kL*?Y}65`JcC^ILHOSaI)4g0WYGB-rOt%8p;TD9P9bYX^Lgwd8E05VcGX+EPuZe zCH96|r?nu3@0{K?|nrGYDh=fFkV&uSq{pUZKyi9~qip4_a#s}J`PUCkO|skg48 zw7ltl;II6i^8oOT&czo)!=OP=RBI=KPr=qU4cvB=Ff;NLKIG$6F`n4>Bun!(lhQ&C zND=;_1BdE5HKQ9dVyN%aFPj!3X$I(3WvjkB$oqB(HDTF+eRJ63;p5;PdJypQdv!q| ztf3$R;k=qfvK_XD_*`;LjrDV|&Xq1fp%8pQh_45LAkxZ+{AyCnVVF1f_#Tu{u!7{o zAm4pALxR;zC#OfRnAXZ4*&ACn^{i8Ylzu<+pPT<*O$' + s + ''; +} + +var stylesColors = ['white', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow']; +var stylesAll = stylesColors.concat(['bold', 'italic', 'underline', 'inverse', 'rainbow']); + +colors.mode = 'console'; +assert.equal(s.bold, '\x1B[1m' + s + '\x1B[22m'); +assert.equal(s.italic, '\x1B[3m' + s + '\x1B[23m'); +assert.equal(s.underline, '\x1B[4m' + s + '\x1B[24m'); +assert.equal(s.strikethrough, '\x1B[9m' + s + '\x1B[29m'); +assert.equal(s.inverse, '\x1B[7m' + s + '\x1B[27m'); + +assert.ok(s.rainbow); + +aE(s, 'white', 37); +aE(s, 'grey', 90); +aE(s, 'black', 30); +aE(s, 'blue', 34); +aE(s, 'cyan', 36); +aE(s, 'green', 32); +aE(s, 'magenta', 35); +aE(s, 'red', 31); +aE(s, 'yellow', 33); + +assert.equal(s, 'string'); + +colors.setTheme({error:'red'}); + +assert.equal(typeof("astring".red),'string'); +assert.equal(typeof("astring".error),'string'); + diff --git a/app/node_modules/colors/tests/safe-test.js b/app/node_modules/colors/tests/safe-test.js new file mode 100644 index 0000000..daad4f9 --- /dev/null +++ b/app/node_modules/colors/tests/safe-test.js @@ -0,0 +1,45 @@ +var assert = require('assert'), + colors = require('../safe'); + +var s = 'string'; + +function a(s, code) { + return '\x1B[' + code.toString() + 'm' + s + '\x1B[39m'; +} + +function aE(s, color, code) { + assert.equal(colors[color](s), a(s, code)); + assert.equal(colors.strip(s), s); +} + +function h(s, color) { + return '' + s + ''; +} + +var stylesColors = ['white', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow']; +var stylesAll = stylesColors.concat(['bold', 'italic', 'underline', 'inverse', 'rainbow']); + +colors.mode = 'console'; +assert.equal(colors.bold(s), '\x1B[1m' + s + '\x1B[22m'); +assert.equal(colors.italic(s), '\x1B[3m' + s + '\x1B[23m'); +assert.equal(colors.underline(s), '\x1B[4m' + s + '\x1B[24m'); +assert.equal(colors.strikethrough(s), '\x1B[9m' + s + '\x1B[29m'); +assert.equal(colors.inverse(s), '\x1B[7m' + s + '\x1B[27m'); + +assert.ok(colors.rainbow); + +aE(s, 'white', 37); +aE(s, 'grey', 90); +aE(s, 'black', 30); +aE(s, 'blue', 34); +aE(s, 'cyan', 36); +aE(s, 'green', 32); +aE(s, 'magenta', 35); +aE(s, 'red', 31); +aE(s, 'yellow', 33); + +assert.equal(s, 'string'); +colors.setTheme({error:'red'}); + +assert.equal(typeof(colors.red("astring")), 'string'); +assert.equal(typeof(colors.error("astring")), 'string'); \ No newline at end of file diff --git a/app/node_modules/colors/themes/generic-logging.js b/app/node_modules/colors/themes/generic-logging.js new file mode 100644 index 0000000..571972c --- /dev/null +++ b/app/node_modules/colors/themes/generic-logging.js @@ -0,0 +1,12 @@ +module['exports'] = { + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}; \ No newline at end of file diff --git a/app/node_modules/content-disposition/HISTORY.md b/app/node_modules/content-disposition/HISTORY.md new file mode 100644 index 0000000..53849b6 --- /dev/null +++ b/app/node_modules/content-disposition/HISTORY.md @@ -0,0 +1,50 @@ +0.5.2 / 2016-12-08 +================== + + * Fix `parse` to accept any linear whitespace character + +0.5.1 / 2016-01-17 +================== + + * perf: enable strict mode + +0.5.0 / 2014-10-11 +================== + + * Add `parse` function + +0.4.0 / 2014-09-21 +================== + + * Expand non-Unicode `filename` to the full ISO-8859-1 charset + +0.3.0 / 2014-09-20 +================== + + * Add `fallback` option + * Add `type` option + +0.2.0 / 2014-09-19 +================== + + * Reduce ambiguity of file names with hex escape in buggy browsers + +0.1.2 / 2014-09-19 +================== + + * Fix periodic invalid Unicode filename header + +0.1.1 / 2014-09-19 +================== + + * Fix invalid characters appearing in `filename*` parameter + +0.1.0 / 2014-09-18 +================== + + * Make the `filename` argument optional + +0.0.0 / 2014-09-18 +================== + + * Initial release diff --git a/app/node_modules/content-disposition/LICENSE b/app/node_modules/content-disposition/LICENSE new file mode 100644 index 0000000..b7dce6c --- /dev/null +++ b/app/node_modules/content-disposition/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +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/app/node_modules/content-disposition/README.md b/app/node_modules/content-disposition/README.md new file mode 100644 index 0000000..992d19a --- /dev/null +++ b/app/node_modules/content-disposition/README.md @@ -0,0 +1,141 @@ +# content-disposition + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create and parse HTTP `Content-Disposition` header + +## Installation + +```sh +$ npm install content-disposition +``` + +## API + +```js +var contentDisposition = require('content-disposition') +``` + +### contentDisposition(filename, options) + +Create an attachment `Content-Disposition` header value using the given file name, +if supplied. The `filename` is optional and if no file name is desired, but you +want to specify `options`, set `filename` to `undefined`. + +```js +res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) +``` + +**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this +header through a means different from `setHeader` in Node.js, you'll want to specify +the `'binary'` encoding in Node.js. + +#### Options + +`contentDisposition` accepts these properties in the options object. + +##### fallback + +If the `filename` option is outside ISO-8859-1, then the file name is actually +stored in a supplemental field for clients that support Unicode file names and +a ISO-8859-1 version of the file name is automatically generated. + +This specifies the ISO-8859-1 file name to override the automatic generation or +disables the generation all together, defaults to `true`. + + - A string will specify the ISO-8859-1 file name to use in place of automatic + generation. + - `false` will disable including a ISO-8859-1 file name and only include the + Unicode version (unless the file name is already ISO-8859-1). + - `true` will enable automatic generation if the file name is outside ISO-8859-1. + +If the `filename` option is ISO-8859-1 and this option is specified and has a +different value, then the `filename` option is encoded in the extended field +and this set as the fallback field, even though they are both ISO-8859-1. + +##### type + +Specifies the disposition type, defaults to `"attachment"`. This can also be +`"inline"`, or any other value (all values except inline are treated like +`attachment`, but can convey additional information if both parties agree to +it). The type is normalized to lower-case. + +### contentDisposition.parse(string) + +```js +var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'); +``` + +Parse a `Content-Disposition` header string. This automatically handles extended +("Unicode") parameters by decoding them and providing them under the standard +parameter name. This will return an object with the following properties (examples +are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): + + - `type`: The disposition type (always lower case). Example: `'attachment'` + + - `parameters`: An object of the parameters in the disposition (name of parameter + always lower case and extended versions replace non-extended versions). Example: + `{filename: "€ rates.txt"}` + +## Examples + +### Send a file for download + +```js +var contentDisposition = require('content-disposition') +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +var filePath = '/path/to/public/plans.pdf' + +http.createServer(function onRequest(req, res) { + // set headers + res.setHeader('Content-Type', 'application/pdf') + res.setHeader('Content-Disposition', contentDisposition(filePath)) + + // send file + var stream = fs.createReadStream(filePath) + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## Testing + +```sh +$ npm test +``` + +## References + +- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] +- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] +- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] +- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] + +[rfc-2616]: https://tools.ietf.org/html/rfc2616 +[rfc-5987]: https://tools.ietf.org/html/rfc5987 +[rfc-6266]: https://tools.ietf.org/html/rfc6266 +[tc-2231]: http://greenbytes.de/tech/tc2231/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-disposition.svg?style=flat +[npm-url]: https://npmjs.org/package/content-disposition +[node-version-image]: https://img.shields.io/node/v/content-disposition.svg?style=flat +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/jshttp/content-disposition.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/content-disposition +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master +[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg?style=flat +[downloads-url]: https://npmjs.org/package/content-disposition diff --git a/app/node_modules/content-disposition/index.js b/app/node_modules/content-disposition/index.js new file mode 100644 index 0000000..88a0d0a --- /dev/null +++ b/app/node_modules/content-disposition/index.js @@ -0,0 +1,445 @@ +/*! + * content-disposition + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = contentDisposition +module.exports.parse = parse + +/** + * Module dependencies. + */ + +var basename = require('path').basename + +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + */ + +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex + +/** + * RegExp to match percent encoding escape. + */ + +var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ +var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g + +/** + * RegExp to match non-latin1 characters. + */ + +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g + +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + */ + +var QESC_REGEXP = /\\([\u0000-\u007f])/g + +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + */ + +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp for various RFC 2616 grammar + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * HT = + * CTL = + * OCTET = + */ + +var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ + +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + */ + +var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ + +/** + * RegExp for various RFC 6266 grammar + * + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + */ + +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex + +/** + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @api public + */ + +function contentDisposition (filename, options) { + var opts = options || {} + + // get type + var type = opts.type || 'attachment' + + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) +} + +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @api private + */ + +function createparams (filename, fallback) { + if (filename === undefined) { + return + } + + var params = {} + + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } + + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } + + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } + + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } + + // restrict to file base name + var name = basename(filename) + + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) + + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + + // set extended filename parameter + if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { + params['filename*'] = name + } + + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } + + return params +} + +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @api private + */ + +function format (obj) { + var parameters = obj.parameters + var type = obj.type + + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + // start with normalized type + var string = String(type).toLowerCase() + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) + + string += '; ' + param + '=' + val + } + } + + return string +} + +/** + * Decode a RFC 6987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @api private + */ + +function decodefield (str) { + var match = EXT_VALUE_REGEXP.exec(str) + + if (!match) { + throw new TypeError('invalid extended field value') + } + + var charset = match[1].toLowerCase() + var encoded = match[2] + var value + + // to binary string + var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) + + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = new Buffer(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } + + return value +} + +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @api private + */ + +function getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') +} + +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @api private + */ + +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } + + var match = DISPOSITION_TYPE_REGEXP.exec(string) + + if (!match) { + throw new TypeError('invalid type format') + } + + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() + + var key + var names = [] + var params = {} + var value + + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index + + // match parameters + while ((match = PARAM_REGEXP.exec(string))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } + + names.push(key) + + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) + + // overwrite existing value + params[key] = value + continue + } + + if (typeof params[key] === 'string') { + continue + } + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } + + params[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return new ContentDisposition(type, params) +} + +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @api private + */ + +function pdecode (str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} + +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @api private + */ + +function pencode (char) { + var hex = String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() + return hex.length === 1 + ? '%0' + hex + : '%' + hex +} + +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @api private + */ + +function qstring (val) { + var str = String(val) + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @api private + */ + +function ustring (val) { + var str = String(val) + + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + + return 'UTF-8\'\'' + encoded +} + +/** + * Class for parsed Content-Disposition header for v8 optimization + */ + +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} diff --git a/app/node_modules/content-disposition/package.json b/app/node_modules/content-disposition/package.json new file mode 100644 index 0000000..5c521d6 --- /dev/null +++ b/app/node_modules/content-disposition/package.json @@ -0,0 +1,39 @@ +{ + "name": "content-disposition", + "description": "Create and parse Content-Disposition header", + "version": "0.5.2", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "content-disposition", + "http", + "rfc6266", + "res" + ], + "repository": "jshttp/content-disposition", + "devDependencies": { + "eslint": "3.11.1", + "eslint-config-standard": "6.2.1", + "eslint-plugin-promise": "3.3.0", + "eslint-plugin-standard": "2.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/app/node_modules/content-type/HISTORY.md b/app/node_modules/content-type/HISTORY.md new file mode 100644 index 0000000..8f5cb70 --- /dev/null +++ b/app/node_modules/content-type/HISTORY.md @@ -0,0 +1,24 @@ +1.0.4 / 2017-09-11 +================== + + * perf: skip parameter parsing when no parameters + +1.0.3 / 2017-09-10 +================== + + * perf: remove argument reassignment + +1.0.2 / 2016-05-09 +================== + + * perf: enable strict mode + +1.0.1 / 2015-02-13 +================== + + * Improve missing `Content-Type` header error message + +1.0.0 / 2015-02-01 +================== + + * Initial implementation, derived from `media-typer@0.3.0` diff --git a/app/node_modules/content-type/LICENSE b/app/node_modules/content-type/LICENSE new file mode 100644 index 0000000..34b1a2d --- /dev/null +++ b/app/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +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/app/node_modules/content-type/README.md b/app/node_modules/content-type/README.md new file mode 100644 index 0000000..3ed6741 --- /dev/null +++ b/app/node_modules/content-type/README.md @@ -0,0 +1,92 @@ +# content-type + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create and parse HTTP Content-Type header according to RFC 7231 + +## Installation + +```sh +$ npm install content-type +``` + +## API + +```js +var contentType = require('content-type') +``` + +### contentType.parse(string) + +```js +var obj = contentType.parse('image/svg+xml; charset=utf-8') +``` + +Parse a content type string. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (the type and subtype, always lower case). + Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter + always lower case). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the string is missing or invalid. + +### contentType.parse(req) + +```js +var obj = contentType.parse(req) +``` + +Parse the `content-type` header from the given `req`. Short-cut for +`contentType.parse(req.headers['content-type'])`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.parse(res) + +```js +var obj = contentType.parse(res) +``` + +Parse the `content-type` header set on the given `res`. Short-cut for +`contentType.parse(res.getHeader('content-type'))`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.format(obj) + +```js +var str = contentType.format({type: 'image/svg+xml'}) +``` + +Format an object into a content type string. This will return a string of the +content type for the given object with the following properties (examples are +shown that produce the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of the + parameter will be lower-cased). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-type.svg +[npm-url]: https://npmjs.org/package/content-type +[node-version-image]: https://img.shields.io/node/v/content-type.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/content-type/master.svg +[travis-url]: https://travis-ci.org/jshttp/content-type +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-type/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/content-type +[downloads-image]: https://img.shields.io/npm/dm/content-type.svg +[downloads-url]: https://npmjs.org/package/content-type diff --git a/app/node_modules/content-type/index.js b/app/node_modules/content-type/index.js new file mode 100644 index 0000000..6ce03f2 --- /dev/null +++ b/app/node_modules/content-type/index.js @@ -0,0 +1,222 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g +var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * Module exports. + * @public + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var type = obj.type + + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + var string = type + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } + + string += '; ' + param + '=' + qstring(parameters[param]) + } + } + + return string +} + +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } + + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string + + if (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var index = header.indexOf(';') + var type = index !== -1 + ? header.substr(0, index).trim() + : header.trim() + + if (!TYPE_REGEXP.test(type)) { + throw new TypeError('invalid media type') + } + + var obj = new ContentType(type.toLowerCase()) + + // parse parameters + if (index !== -1) { + var key + var match + var value + + PARAM_REGEXP.lastIndex = index + + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } + + obj.parameters[key] = value + } + + if (index !== header.length) { + throw new TypeError('invalid parameter format') + } + } + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + +function getcontenttype (obj) { + var header + + if (typeof obj.getHeader === 'function') { + // res-like + header = obj.getHeader('content-type') + } else if (typeof obj.headers === 'object') { + // req-like + header = obj.headers && obj.headers['content-type'] + } + + if (typeof header !== 'string') { + throw new TypeError('content-type header is missing from object') + } + + return header +} + +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @private + */ + +function qstring (val) { + var str = String(val) + + // no need to quote tokens + if (TOKEN_REGEXP.test(str)) { + return str + } + + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError('invalid parameter value') + } + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type +} diff --git a/app/node_modules/content-type/package.json b/app/node_modules/content-type/package.json new file mode 100644 index 0000000..f2d31d4 --- /dev/null +++ b/app/node_modules/content-type/package.json @@ -0,0 +1,40 @@ +{ + "name": "content-type", + "description": "Create and parse HTTP Content-Type header", + "version": "1.0.4", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231" + ], + "repository": "jshttp/content-type", + "devDependencies": { + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "~1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + } +} diff --git a/app/node_modules/cookie-parser/HISTORY.md b/app/node_modules/cookie-parser/HISTORY.md new file mode 100644 index 0000000..3405d50 --- /dev/null +++ b/app/node_modules/cookie-parser/HISTORY.md @@ -0,0 +1,95 @@ +1.4.5 / 2020-03-14 +================== + + * deps: cookie@0.4.0 + +1.4.4 / 2019-02-12 +================== + + * perf: normalize `secret` argument only once + +1.4.3 / 2016-05-26 +================== + + * deps: cookie@0.3.1 + - perf: use for loop in parse + +1.4.2 / 2016-05-20 +================== + + * deps: cookie@0.2.4 + - perf: enable strict mode + - perf: use for loop in parse + - perf: use string concatenation for serialization + +1.4.1 / 2016-01-11 +================== + + * deps: cookie@0.2.3 + * perf: enable strict mode + +1.4.0 / 2015-09-18 +================== + + * Accept array of secrets in addition to a single secret + * Fix `JSONCookie` to return `undefined` for non-string arguments + * Fix `signedCookie` to return `undefined` for non-string arguments + * deps: cookie@0.2.2 + +1.3.5 / 2015-05-19 +================== + + * deps: cookie@0.1.3 + - Slight optimizations + +1.3.4 / 2015-02-15 +================== + + * deps: cookie-signature@1.0.6 + +1.3.3 / 2014-09-05 +================== + + * deps: cookie-signature@1.0.5 + +1.3.2 / 2014-06-26 +================== + + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +1.3.1 / 2014-06-17 +================== + + * actually export `signedCookie` + +1.3.0 / 2014-06-17 +================== + + * add `signedCookie` export for single cookie unsigning + +1.2.0 / 2014-06-17 +================== + + * export parsing functions + * `req.cookies` and `req.signedCookies` are now plain objects + * slightly faster parsing of many cookies + +1.1.0 / 2014-05-12 +================== + + * Support for NodeJS version 0.8 + * deps: cookie@0.1.2 + - Fix for maxAge == 0 + - made compat with expires field + - tweak maxAge NaN error message + +1.0.1 / 2014-02-20 +================== + + * add missing dependencies + +1.0.0 / 2014-02-15 +================== + + * Genesis from `connect` diff --git a/app/node_modules/cookie-parser/LICENSE b/app/node_modules/cookie-parser/LICENSE new file mode 100644 index 0000000..343f2ad --- /dev/null +++ b/app/node_modules/cookie-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk +Copyright (c) 2015 Douglas Christopher Wilson + +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/app/node_modules/cookie-parser/README.md b/app/node_modules/cookie-parser/README.md new file mode 100644 index 0000000..bc0d271 --- /dev/null +++ b/app/node_modules/cookie-parser/README.md @@ -0,0 +1,102 @@ +# cookie-parser + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Parse `Cookie` header and populate `req.cookies` with an object keyed by the +cookie names. Optionally you may enable signed cookie support by passing a +`secret` string, which assigns `req.secret` so it may be used by other +middleware. + +## Installation + +```sh +$ npm install cookie-parser +``` + +## API + +```js +var express = require('express') +var cookieParser = require('cookie-parser') + +var app = express() +app.use(cookieParser()) +``` + +### cookieParser(secret, options) + +- `secret` a string or array used for signing cookies. This is optional and if + not specified, will not parse signed cookies. If a string is provided, this + is used as the secret. If an array is provided, an attempt will be made to + unsign the cookie with each secret in order. +- `options` an object that is passed to `cookie.parse` as the second option. Se + [cookie](https://www.npmjs.org/package/cookie) for more information. + - `decode` a function to decode the value of the cookie + +### cookieParser.JSONCookie(str) + +Parse a cookie value as a JSON cookie. This will return the parsed JSON value +if it was a JSON cookie, otherwise, it will return the passed value. + +### cookieParser.JSONCookies(cookies) + +Given an object, this will iterate over the keys and call `JSONCookie` on each +value, replacing the original value with the parsed value. This returns the +same object that was passed in. + +### cookieParser.signedCookie(str, secret) + +Parse a cookie value as a signed cookie. This will return the parsed unsigned +value if it was a signed cookie and the signature was valid. If the value was +not signed, the original value is returned. If the value was signed but the +signature could not be validated, `false` is returned. + +The `secret` argument can be an array or string. If a string is provided, this +is used as the secret. If an array is provided, an attempt will be made to +unsign the cookie with each secret in order. + +### cookieParser.signedCookies(cookies, secret) + +Given an object, this will iterate over the keys and check if any value is a +signed cookie. If it is a signed cookie and the signature is valid, the key +will be deleted from the object and added to the new object that is returned. + +The `secret` argument can be an array or string. If a string is provided, this +is used as the secret. If an array is provided, an attempt will be made to +unsign the cookie with each secret in order. + +## Example + +```js +var express = require('express') +var cookieParser = require('cookie-parser') + +var app = express() +app.use(cookieParser()) + +app.get('/', function (req, res) { + // Cookies that have not been signed + console.log('Cookies: ', req.cookies) + + // Cookies that have been signed + console.log('Signed Cookies: ', req.signedCookies) +}) + +app.listen(8080) + +// curl command that sends an HTTP request with two cookies +// curl http://127.0.0.1:8080 --cookie "Cho=Kim;Greet=Hello" +``` + +### [MIT Licensed](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/cookie-parser/master +[coveralls-url]: https://coveralls.io/r/expressjs/cookie-parser?branch=master +[npm-downloads-image]: https://badgen.net/npm/dm/cookie-parser +[npm-url]: https://npmjs.org/package/cookie-parser +[npm-version-image]: https://badgen.net/npm/v/cookie-parser +[travis-image]: https://badgen.net/travis/expressjs/cookie-parser/master +[travis-url]: https://travis-ci.org/expressjs/cookie-parser diff --git a/app/node_modules/cookie-parser/index.js b/app/node_modules/cookie-parser/index.js new file mode 100644 index 0000000..dd6d479 --- /dev/null +++ b/app/node_modules/cookie-parser/index.js @@ -0,0 +1,182 @@ +/*! + * cookie-parser + * Copyright(c) 2014 TJ Holowaychuk + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var cookie = require('cookie') +var signature = require('cookie-signature') + +/** + * Module exports. + * @public + */ + +module.exports = cookieParser +module.exports.JSONCookie = JSONCookie +module.exports.JSONCookies = JSONCookies +module.exports.signedCookie = signedCookie +module.exports.signedCookies = signedCookies + +/** + * Parse Cookie header and populate `req.cookies` + * with an object keyed by the cookie names. + * + * @param {string|array} [secret] A string (or array of strings) representing cookie signing secret(s). + * @param {Object} [options] + * @return {Function} + * @public + */ + +function cookieParser (secret, options) { + var secrets = !secret || Array.isArray(secret) + ? (secret || []) + : [secret] + + return function cookieParser (req, res, next) { + if (req.cookies) { + return next() + } + + var cookies = req.headers.cookie + + req.secret = secrets[0] + req.cookies = Object.create(null) + req.signedCookies = Object.create(null) + + // no cookies + if (!cookies) { + return next() + } + + req.cookies = cookie.parse(cookies, options) + + // parse signed cookies + if (secrets.length !== 0) { + req.signedCookies = signedCookies(req.cookies, secrets) + req.signedCookies = JSONCookies(req.signedCookies) + } + + // parse JSON cookies + req.cookies = JSONCookies(req.cookies) + + next() + } +} + +/** + * Parse JSON cookie string. + * + * @param {String} str + * @return {Object} Parsed object or undefined if not json cookie + * @public + */ + +function JSONCookie (str) { + if (typeof str !== 'string' || str.substr(0, 2) !== 'j:') { + return undefined + } + + try { + return JSON.parse(str.slice(2)) + } catch (err) { + return undefined + } +} + +/** + * Parse JSON cookies. + * + * @param {Object} obj + * @return {Object} + * @public + */ + +function JSONCookies (obj) { + var cookies = Object.keys(obj) + var key + var val + + for (var i = 0; i < cookies.length; i++) { + key = cookies[i] + val = JSONCookie(obj[key]) + + if (val) { + obj[key] = val + } + } + + return obj +} + +/** + * Parse a signed cookie string, return the decoded value. + * + * @param {String} str signed cookie string + * @param {string|array} secret + * @return {String} decoded value + * @public + */ + +function signedCookie (str, secret) { + if (typeof str !== 'string') { + return undefined + } + + if (str.substr(0, 2) !== 's:') { + return str + } + + var secrets = !secret || Array.isArray(secret) + ? (secret || []) + : [secret] + + for (var i = 0; i < secrets.length; i++) { + var val = signature.unsign(str.slice(2), secrets[i]) + + if (val !== false) { + return val + } + } + + return false +} + +/** + * Parse signed cookies, returning an object containing the decoded key/value + * pairs, while removing the signed key from obj. + * + * @param {Object} obj + * @param {string|array} secret + * @return {Object} + * @public + */ + +function signedCookies (obj, secret) { + var cookies = Object.keys(obj) + var dec + var key + var ret = Object.create(null) + var val + + for (var i = 0; i < cookies.length; i++) { + key = cookies[i] + val = obj[key] + dec = signedCookie(val, secret) + + if (val !== dec) { + ret[key] = dec + delete obj[key] + } + } + + return ret +} diff --git a/app/node_modules/cookie-parser/node_modules/cookie/HISTORY.md b/app/node_modules/cookie-parser/node_modules/cookie/HISTORY.md new file mode 100644 index 0000000..da2bf24 --- /dev/null +++ b/app/node_modules/cookie-parser/node_modules/cookie/HISTORY.md @@ -0,0 +1,123 @@ +0.4.0 / 2019-05-15 +================== + + * Add `SameSite=None` support + +0.3.1 / 2016-05-26 +================== + + * Fix `sameSite: true` to work with draft-7 clients + - `true` now sends `SameSite=Strict` instead of `SameSite` + +0.3.0 / 2016-05-26 +================== + + * Add `sameSite` option + - Replaces `firstPartyOnly` option, never implemented by browsers + * Improve error message when `encode` is not a function + * Improve error message when `expires` is not a `Date` + +0.2.4 / 2016-05-20 +================== + + * perf: enable strict mode + * perf: use for loop in parse + * perf: use string concatination for serialization + +0.2.3 / 2015-10-25 +================== + + * Fix cookie `Max-Age` to never be a floating point number + +0.2.2 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.2.1 / 2015-09-17 +================== + + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.2.0 / 2015-08-13 +================== + + * Add `firstPartyOnly` option + * Throw better error for invalid argument to parse + * perf: hoist regular expression + +0.1.5 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.1.4 / 2015-09-17 +================== + + * Throw better error for invalid argument to parse + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.1.3 / 2015-05-19 +================== + + * Reduce the scope of try-catch deopt + * Remove argument reassignments + +0.1.2 / 2014-04-16 +================== + + * Remove unnecessary files from npm package + +0.1.1 / 2014-02-23 +================== + + * Fix bad parse when cookie value contained a comma + * Fix support for `maxAge` of `0` + +0.1.0 / 2013-05-01 +================== + + * Add `decode` option + * Add `encode` option + +0.0.6 / 2013-04-08 +================== + + * Ignore cookie parts missing `=` + +0.0.5 / 2012-10-29 +================== + + * Return raw cookie value if value unescape errors + +0.0.4 / 2012-06-21 +================== + + * Use encode/decodeURIComponent for cookie encoding/decoding + - Improve server/client interoperability + +0.0.3 / 2012-06-06 +================== + + * Only escape special characters per the cookie RFC + +0.0.2 / 2012-06-01 +================== + + * Fix `maxAge` option to not throw error + +0.0.1 / 2012-05-28 +================== + + * Add more tests + +0.0.0 / 2012-05-28 +================== + + * Initial release diff --git a/app/node_modules/cookie-parser/node_modules/cookie/LICENSE b/app/node_modules/cookie-parser/node_modules/cookie/LICENSE new file mode 100644 index 0000000..058b6b4 --- /dev/null +++ b/app/node_modules/cookie-parser/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +Copyright (c) 2015 Douglas Christopher Wilson + +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/app/node_modules/cookie-parser/node_modules/cookie/README.md b/app/node_modules/cookie-parser/node_modules/cookie/README.md new file mode 100644 index 0000000..857fb77 --- /dev/null +++ b/app/node_modules/cookie-parser/node_modules/cookie/README.md @@ -0,0 +1,253 @@ +# cookie + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Basic HTTP cookie parser and serializer for HTTP servers. + +## Installation + +```sh +$ npm install cookie +``` + +## API + +```js +var cookie = require('cookie'); +``` + +### cookie.parse(str, options) + +Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs. +The `str` argument is the string representing a `Cookie` header value and `options` is an +optional object containing additional parsing options. + +```js +var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2'); +// { foo: 'bar', equation: 'E=mc^2' } +``` + +#### Options + +`cookie.parse` accepts these properties in the options object. + +##### decode + +Specifies a function that will be used to decode a cookie's value. Since the value of a cookie +has a limited character set (and must be a simple string), this function can be used to decode +a previously-encoded cookie value into a JavaScript string or other object. + +The default function is the global `decodeURIComponent`, which will decode any URL-encoded +sequences into their byte representations. + +**note** if an error is thrown from this function, the original, non-decoded cookie value will +be returned as the cookie's value. + +### cookie.serialize(name, value, options) + +Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the +name for the cookie, the `value` argument is the value to set the cookie to, and the `options` +argument is an optional object containing additional serialization options. + +```js +var setCookie = cookie.serialize('foo', 'bar'); +// foo=bar +``` + +#### Options + +`cookie.serialize` accepts these properties in the options object. + +##### domain + +Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6265-5.2.3]. By default, no +domain is set, and most clients will consider the cookie to apply to only the current domain. + +##### encode + +Specifies a function that will be used to encode a cookie's value. Since value of a cookie +has a limited character set (and must be a simple string), this function can be used to encode +a value into a string suited for a cookie's value. + +The default function is the global `encodeURIComponent`, which will encode a JavaScript string +into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range. + +##### expires + +Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6265-5.2.1]. +By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and +will delete it on a condition like exiting a web browser application. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### httpOnly + +Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6265-5.2.6]. When truthy, +the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not allow client-side +JavaScript to see the cookie in `document.cookie`. + +##### maxAge + +Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6265-5.2.2]. +The given number will be converted to an integer by rounding down. By default, no maximum age is set. + +**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and +`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### path + +Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path +is considered the ["default path"][rfc-6265-5.1.4]. + +##### sameSite + +Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-03-4.1.2.7]. + + - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + - `false` will not set the `SameSite` attribute. + - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. + - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. + - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + +More information about the different enforcement levels can be found in +[the specification][rfc-6265bis-03-4.1.2.7]. + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### secure + +Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy, +the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to +the server in the future if the browser does not have an HTTPS connection. + +## Example + +The following example uses this module in conjunction with the Node.js core HTTP server +to prompt a user for their name and display it back on future visits. + +```js +var cookie = require('cookie'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var url = require('url'); + +function onRequest(req, res) { + // Parse the query string + var query = url.parse(req.url, true, true).query; + + if (query && query.name) { + // Set a new cookie with the name + res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), { + httpOnly: true, + maxAge: 60 * 60 * 24 * 7 // 1 week + })); + + // Redirect back after setting cookie + res.statusCode = 302; + res.setHeader('Location', req.headers.referer || '/'); + res.end(); + return; + } + + // Parse the cookies on the request + var cookies = cookie.parse(req.headers.cookie || ''); + + // Get the visitor name set in the cookie + var name = cookies.name; + + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + + if (name) { + res.write('

Welcome back, ' + escapeHtml(name) + '!

'); + } else { + res.write('

Hello, new visitor!

'); + } + + res.write('
'); + res.write(' '); + res.end('
'); +} + +http.createServer(onRequest).listen(3000); +``` + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +``` +$ npm run bench + +> cookie@0.3.1 bench cookie +> node benchmark/index.js + + http_parser@2.8.0 + node@6.14.2 + v8@5.1.281.111 + uv@1.16.1 + zlib@1.2.11 + ares@1.10.1-DEV + icu@58.2 + modules@48 + napi@3 + openssl@1.0.2o + +> node benchmark/parse.js + + cookie.parse + + 6 tests completed. + + simple x 1,200,691 ops/sec ±1.12% (189 runs sampled) + decode x 1,012,994 ops/sec ±0.97% (186 runs sampled) + unquote x 1,074,174 ops/sec ±2.43% (186 runs sampled) + duplicates x 438,424 ops/sec ±2.17% (184 runs sampled) + 10 cookies x 147,154 ops/sec ±1.01% (186 runs sampled) + 100 cookies x 14,274 ops/sec ±1.07% (187 runs sampled) +``` + +## References + +- [RFC 6265: HTTP State Management Mechanism][rfc-6265] +- [Same-site Cookies][rfc-6265bis-03-4.1.2.7] + +[rfc-6265bis-03-4.1.2.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7 +[rfc-6265]: https://tools.ietf.org/html/rfc6265 +[rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4 +[rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1 +[rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2 +[rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3 +[rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4 +[rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5 +[rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6 +[rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3 + +## License + +[MIT](LICENSE) + +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master +[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master +[node-version-image]: https://badgen.net/npm/node/cookie +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/cookie +[npm-url]: https://npmjs.org/package/cookie +[npm-version-image]: https://badgen.net/npm/v/cookie +[travis-image]: https://badgen.net/travis/jshttp/cookie/master +[travis-url]: https://travis-ci.org/jshttp/cookie diff --git a/app/node_modules/cookie-parser/node_modules/cookie/index.js b/app/node_modules/cookie-parser/node_modules/cookie/index.js new file mode 100644 index 0000000..16f56c0 --- /dev/null +++ b/app/node_modules/cookie-parser/node_modules/cookie/index.js @@ -0,0 +1,198 @@ +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +exports.parse = parse; +exports.serialize = serialize; + +/** + * Module variables. + * @private + */ + +var decode = decodeURIComponent; +var encode = encodeURIComponent; +var pairSplitRegExp = /; */; + +/** + * RegExp to match field-content in RFC 7230 sec 3.2 + * + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF + */ + +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; + +/** + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public + */ + +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } + + var obj = {} + var opt = options || {}; + var pairs = str.split(pairSplitRegExp); + var dec = opt.decode || decode; + + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var eq_idx = pair.indexOf('='); + + // skip things that don't look like key=value + if (eq_idx < 0) { + continue; + } + + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); + + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } + + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); + } + } + + return obj; +} + +/** + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public + */ + +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); + } + + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } + + var value = enc(val); + + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } + + var str = name + '=' + value; + + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); + str += '; Max-Age=' + Math.floor(maxAge); + } + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } + + str += '; Domain=' + opt.domain; + } + + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } + + str += '; Path=' + opt.path; + } + + if (opt.expires) { + if (typeof opt.expires.toUTCString !== 'function') { + throw new TypeError('option expires is invalid'); + } + + str += '; Expires=' + opt.expires.toUTCString(); + } + + if (opt.httpOnly) { + str += '; HttpOnly'; + } + + if (opt.secure) { + str += '; Secure'; + } + + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; + + switch (sameSite) { + case true: + str += '; SameSite=Strict'; + break; + case 'lax': + str += '; SameSite=Lax'; + break; + case 'strict': + str += '; SameSite=Strict'; + break; + case 'none': + str += '; SameSite=None'; + break; + default: + throw new TypeError('option sameSite is invalid'); + } + } + + return str; +} + +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ + +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} diff --git a/app/node_modules/cookie-parser/node_modules/cookie/package.json b/app/node_modules/cookie-parser/node_modules/cookie/package.json new file mode 100644 index 0000000..9bfbc47 --- /dev/null +++ b/app/node_modules/cookie-parser/node_modules/cookie/package.json @@ -0,0 +1,40 @@ +{ + "name": "cookie", + "description": "HTTP server cookie parsing and serialization", + "version": "0.4.0", + "author": "Roman Shtylman ", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "cookie", + "cookies" + ], + "repository": "jshttp/cookie", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "5.16.0", + "eslint-plugin-markdown": "1.0.0", + "istanbul": "0.4.5", + "mocha": "6.1.4" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/app/node_modules/cookie-parser/package.json b/app/node_modules/cookie-parser/package.json new file mode 100644 index 0000000..c3d1eaf --- /dev/null +++ b/app/node_modules/cookie-parser/package.json @@ -0,0 +1,45 @@ +{ + "name": "cookie-parser", + "description": "Parse HTTP request cookies", + "version": "1.4.5", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "expressjs/cookie-parser", + "keywords": [ + "cookie", + "middleware" + ], + "dependencies": { + "cookie": "0.4.0", + "cookie-signature": "1.0.6" + }, + "devDependencies": { + "eslint": "6.8.0", + "eslint-config-standard": "14.1.0", + "eslint-plugin-import": "2.20.1", + "eslint-plugin-markdown": "1.0.2", + "eslint-plugin-node": "11.0.0", + "eslint-plugin-promise": "4.2.1", + "eslint-plugin-standard": "4.0.1", + "istanbul": "0.4.5", + "mocha": "7.1.0", + "supertest": "4.0.2" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/app/node_modules/cookie-signature/.npmignore b/app/node_modules/cookie-signature/.npmignore new file mode 100644 index 0000000..f1250e5 --- /dev/null +++ b/app/node_modules/cookie-signature/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/app/node_modules/cookie-signature/History.md b/app/node_modules/cookie-signature/History.md new file mode 100644 index 0000000..78513cc --- /dev/null +++ b/app/node_modules/cookie-signature/History.md @@ -0,0 +1,38 @@ +1.0.6 / 2015-02-03 +================== + +* use `npm test` instead of `make test` to run tests +* clearer assertion messages when checking input + + +1.0.5 / 2014-09-05 +================== + +* add license to package.json + +1.0.4 / 2014-06-25 +================== + + * corrected avoidance of timing attacks (thanks @tenbits!) + +1.0.3 / 2014-01-28 +================== + + * [incorrect] fix for timing attacks + +1.0.2 / 2014-01-28 +================== + + * fix missing repository warning + * fix typo in test + +1.0.1 / 2013-04-15 +================== + + * Revert "Changed underlying HMAC algo. to sha512." + * Revert "Fix for timing attacks on MAC verification." + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/app/node_modules/cookie-signature/Readme.md b/app/node_modules/cookie-signature/Readme.md new file mode 100644 index 0000000..2559e84 --- /dev/null +++ b/app/node_modules/cookie-signature/Readme.md @@ -0,0 +1,42 @@ + +# cookie-signature + + Sign and unsign cookies. + +## Example + +```js +var cookie = require('cookie-signature'); + +var val = cookie.sign('hello', 'tobiiscool'); +val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); + +var val = cookie.sign('hello', 'tobiiscool'); +cookie.unsign(val, 'tobiiscool').should.equal('hello'); +cookie.unsign(val, 'luna').should.be.false; +``` + +## License + +(The MIT License) + +Copyright (c) 2012 LearnBoost <tj@learnboost.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. \ No newline at end of file diff --git a/app/node_modules/cookie-signature/index.js b/app/node_modules/cookie-signature/index.js new file mode 100644 index 0000000..b8c9463 --- /dev/null +++ b/app/node_modules/cookie-signature/index.js @@ -0,0 +1,51 @@ +/** + * Module dependencies. + */ + +var crypto = require('crypto'); + +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + var str = val.slice(0, val.lastIndexOf('.')) + , mac = exports.sign(str, secret); + + return sha1(mac) == sha1(val) ? str : false; +}; + +/** + * Private + */ + +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} diff --git a/app/node_modules/cookie-signature/package.json b/app/node_modules/cookie-signature/package.json new file mode 100644 index 0000000..29c4498 --- /dev/null +++ b/app/node_modules/cookie-signature/package.json @@ -0,0 +1,18 @@ +{ + "name": "cookie-signature", + "version": "1.0.6", + "description": "Sign and unsign cookies", + "keywords": ["cookie", "sign", "unsign"], + "author": "TJ Holowaychuk ", + "license": "MIT", + "repository": { "type": "git", "url": "https://github.com/visionmedia/node-cookie-signature.git"}, + "dependencies": {}, + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "scripts": { + "test": "mocha --require should --reporter spec" + }, + "main": "index" +} diff --git a/app/node_modules/cookie/HISTORY.md b/app/node_modules/cookie/HISTORY.md new file mode 100644 index 0000000..5bd6485 --- /dev/null +++ b/app/node_modules/cookie/HISTORY.md @@ -0,0 +1,118 @@ +0.3.1 / 2016-05-26 +================== + + * Fix `sameSite: true` to work with draft-7 clients + - `true` now sends `SameSite=Strict` instead of `SameSite` + +0.3.0 / 2016-05-26 +================== + + * Add `sameSite` option + - Replaces `firstPartyOnly` option, never implemented by browsers + * Improve error message when `encode` is not a function + * Improve error message when `expires` is not a `Date` + +0.2.4 / 2016-05-20 +================== + + * perf: enable strict mode + * perf: use for loop in parse + * perf: use string concatination for serialization + +0.2.3 / 2015-10-25 +================== + + * Fix cookie `Max-Age` to never be a floating point number + +0.2.2 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.2.1 / 2015-09-17 +================== + + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.2.0 / 2015-08-13 +================== + + * Add `firstPartyOnly` option + * Throw better error for invalid argument to parse + * perf: hoist regular expression + +0.1.5 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.1.4 / 2015-09-17 +================== + + * Throw better error for invalid argument to parse + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.1.3 / 2015-05-19 +================== + + * Reduce the scope of try-catch deopt + * Remove argument reassignments + +0.1.2 / 2014-04-16 +================== + + * Remove unnecessary files from npm package + +0.1.1 / 2014-02-23 +================== + + * Fix bad parse when cookie value contained a comma + * Fix support for `maxAge` of `0` + +0.1.0 / 2013-05-01 +================== + + * Add `decode` option + * Add `encode` option + +0.0.6 / 2013-04-08 +================== + + * Ignore cookie parts missing `=` + +0.0.5 / 2012-10-29 +================== + + * Return raw cookie value if value unescape errors + +0.0.4 / 2012-06-21 +================== + + * Use encode/decodeURIComponent for cookie encoding/decoding + - Improve server/client interoperability + +0.0.3 / 2012-06-06 +================== + + * Only escape special characters per the cookie RFC + +0.0.2 / 2012-06-01 +================== + + * Fix `maxAge` option to not throw error + +0.0.1 / 2012-05-28 +================== + + * Add more tests + +0.0.0 / 2012-05-28 +================== + + * Initial release diff --git a/app/node_modules/cookie/LICENSE b/app/node_modules/cookie/LICENSE new file mode 100644 index 0000000..058b6b4 --- /dev/null +++ b/app/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +Copyright (c) 2015 Douglas Christopher Wilson + +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/app/node_modules/cookie/README.md b/app/node_modules/cookie/README.md new file mode 100644 index 0000000..db0d078 --- /dev/null +++ b/app/node_modules/cookie/README.md @@ -0,0 +1,220 @@ +# cookie + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Basic HTTP cookie parser and serializer for HTTP servers. + +## Installation + +```sh +$ npm install cookie +``` + +## API + +```js +var cookie = require('cookie'); +``` + +### cookie.parse(str, options) + +Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs. +The `str` argument is the string representing a `Cookie` header value and `options` is an +optional object containing additional parsing options. + +```js +var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2'); +// { foo: 'bar', equation: 'E=mc^2' } +``` + +#### Options + +`cookie.parse` accepts these properties in the options object. + +##### decode + +Specifies a function that will be used to decode a cookie's value. Since the value of a cookie +has a limited character set (and must be a simple string), this function can be used to decode +a previously-encoded cookie value into a JavaScript string or other object. + +The default function is the global `decodeURIComponent`, which will decode any URL-encoded +sequences into their byte representations. + +**note** if an error is thrown from this function, the original, non-decoded cookie value will +be returned as the cookie's value. + +### cookie.serialize(name, value, options) + +Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the +name for the cookie, the `value` argument is the value to set the cookie to, and the `options` +argument is an optional object containing additional serialization options. + +```js +var setCookie = cookie.serialize('foo', 'bar'); +// foo=bar +``` + +#### Options + +`cookie.serialize` accepts these properties in the options object. + +##### domain + +Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6266-5.2.3]. By default, no +domain is set, and most clients will consider the cookie to apply to only the current domain. + +##### encode + +Specifies a function that will be used to encode a cookie's value. Since value of a cookie +has a limited character set (and must be a simple string), this function can be used to encode +a value into a string suited for a cookie's value. + +The default function is the global `ecodeURIComponent`, which will encode a JavaScript string +into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range. + +##### expires + +Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6266-5.2.1]. +By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and +will delete it on a condition like exiting a web browser application. + +**note** the [cookie storage model specification][rfc-6266-5.3] states that if both `expires` and +`magAge` are set, then `maxAge` takes precedence, but it is possiblke not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### httpOnly + +Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6266-5.2.6]. When truthy, +the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not allow client-side +JavaScript to see the cookie in `document.cookie`. + +##### maxAge + +Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6266-5.2.2]. +The given number will be converted to an integer by rounding down. By default, no maximum age is set. + +**note** the [cookie storage model specification][rfc-6266-5.3] states that if both `expires` and +`magAge` are set, then `maxAge` takes precedence, but it is possiblke not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### path + +Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6266-5.2.4]. By default, the path +is considered the ["default path"][rfc-6266-5.1.4]. By default, no maximum age is set, and most +clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting +a web browser application. + +##### sameSite + +Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][draft-west-first-party-cookies-07]. + + - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + - `false` will not set the `SameSite` attribute. + - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. + - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + +More information about the different enforcement levels can be found in the specification +https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1.1 + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### secure + +Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6266-5.2.5]. When truthy, +the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to +the server in the future if the browser does not have an HTTPS connection. + +## Example + +The following example uses this module in conjunction with the Node.js core HTTP server +to prompt a user for their name and display it back on future visits. + +```js +var cookie = require('cookie'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var url = require('url'); + +function onRequest(req, res) { + // Parse the query string + var query = url.parse(req.url, true, true).query; + + if (query && query.name) { + // Set a new cookie with the name + res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), { + httpOnly: true, + maxAge: 60 * 60 * 24 * 7 // 1 week + })); + + // Redirect back after setting cookie + res.statusCode = 302; + res.setHeader('Location', req.headers.referer || '/'); + res.end(); + return; + } + + // Parse the cookies on the request + var cookies = cookie.parse(req.headers.cookie || ''); + + // Get the visitor name set in the cookie + var name = cookies.name; + + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + + if (name) { + res.write('

Welcome back, ' + escapeHtml(name) + '!

'); + } else { + res.write('

Hello, new visitor!

'); + } + + res.write('
'); + res.write(' '); + res.end(' values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public + */ + +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } + + var obj = {} + var opt = options || {}; + var pairs = str.split(pairSplitRegExp); + var dec = opt.decode || decode; + + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var eq_idx = pair.indexOf('='); + + // skip things that don't look like key=value + if (eq_idx < 0) { + continue; + } + + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); + + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } + + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); + } + } + + return obj; +} + +/** + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public + */ + +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); + } + + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } + + var value = enc(val); + + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } + + var str = name + '=' + value; + + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); + str += '; Max-Age=' + Math.floor(maxAge); + } + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } + + str += '; Domain=' + opt.domain; + } + + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } + + str += '; Path=' + opt.path; + } + + if (opt.expires) { + if (typeof opt.expires.toUTCString !== 'function') { + throw new TypeError('option expires is invalid'); + } + + str += '; Expires=' + opt.expires.toUTCString(); + } + + if (opt.httpOnly) { + str += '; HttpOnly'; + } + + if (opt.secure) { + str += '; Secure'; + } + + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; + + switch (sameSite) { + case true: + str += '; SameSite=Strict'; + break; + case 'lax': + str += '; SameSite=Lax'; + break; + case 'strict': + str += '; SameSite=Strict'; + break; + default: + throw new TypeError('option sameSite is invalid'); + } + } + + return str; +} + +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ + +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} diff --git a/app/node_modules/cookie/package.json b/app/node_modules/cookie/package.json new file mode 100644 index 0000000..b485150 --- /dev/null +++ b/app/node_modules/cookie/package.json @@ -0,0 +1,33 @@ +{ + "name": "cookie", + "description": "HTTP server cookie parsing and serialization", + "version": "0.3.1", + "author": "Roman Shtylman ", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "cookie", + "cookies" + ], + "repository": "jshttp/cookie", + "devDependencies": { + "istanbul": "0.4.3", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + } +} diff --git a/app/node_modules/core-util-is/LICENSE b/app/node_modules/core-util-is/LICENSE new file mode 100644 index 0000000..d8d7f94 --- /dev/null +++ b/app/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/app/node_modules/core-util-is/README.md b/app/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/app/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/app/node_modules/core-util-is/float.patch b/app/node_modules/core-util-is/float.patch new file mode 100644 index 0000000..a06d5c0 --- /dev/null +++ b/app/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +diff --git a/lib/util.js b/lib/util.js +index a03e874..9074e8e 100644 +--- a/lib/util.js ++++ b/lib/util.js +@@ -19,430 +19,6 @@ + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + +-var formatRegExp = /%[sdj%]/g; +-exports.format = function(f) { +- if (!isString(f)) { +- var objects = []; +- for (var i = 0; i < arguments.length; i++) { +- objects.push(inspect(arguments[i])); +- } +- return objects.join(' '); +- } +- +- var i = 1; +- var args = arguments; +- var len = args.length; +- var str = String(f).replace(formatRegExp, function(x) { +- if (x === '%%') return '%'; +- if (i >= len) return x; +- switch (x) { +- case '%s': return String(args[i++]); +- case '%d': return Number(args[i++]); +- case '%j': +- try { +- return JSON.stringify(args[i++]); +- } catch (_) { +- return '[Circular]'; +- } +- default: +- return x; +- } +- }); +- for (var x = args[i]; i < len; x = args[++i]) { +- if (isNull(x) || !isObject(x)) { +- str += ' ' + x; +- } else { +- str += ' ' + inspect(x); +- } +- } +- return str; +-}; +- +- +-// Mark that a method should not be used. +-// Returns a modified function which warns once by default. +-// If --no-deprecation is set, then it is a no-op. +-exports.deprecate = function(fn, msg) { +- // Allow for deprecating things in the process of starting up. +- if (isUndefined(global.process)) { +- return function() { +- return exports.deprecate(fn, msg).apply(this, arguments); +- }; +- } +- +- if (process.noDeprecation === true) { +- return fn; +- } +- +- var warned = false; +- function deprecated() { +- if (!warned) { +- if (process.throwDeprecation) { +- throw new Error(msg); +- } else if (process.traceDeprecation) { +- console.trace(msg); +- } else { +- console.error(msg); +- } +- warned = true; +- } +- return fn.apply(this, arguments); +- } +- +- return deprecated; +-}; +- +- +-var debugs = {}; +-var debugEnviron; +-exports.debuglog = function(set) { +- if (isUndefined(debugEnviron)) +- debugEnviron = process.env.NODE_DEBUG || ''; +- set = set.toUpperCase(); +- if (!debugs[set]) { +- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { +- var pid = process.pid; +- debugs[set] = function() { +- var msg = exports.format.apply(exports, arguments); +- console.error('%s %d: %s', set, pid, msg); +- }; +- } else { +- debugs[set] = function() {}; +- } +- } +- return debugs[set]; +-}; +- +- +-/** +- * Echos the value of a value. Trys to print the value out +- * in the best way possible given the different types. +- * +- * @param {Object} obj The object to print out. +- * @param {Object} opts Optional options object that alters the output. +- */ +-/* legacy: obj, showHidden, depth, colors*/ +-function inspect(obj, opts) { +- // default options +- var ctx = { +- seen: [], +- stylize: stylizeNoColor +- }; +- // legacy... +- if (arguments.length >= 3) ctx.depth = arguments[2]; +- if (arguments.length >= 4) ctx.colors = arguments[3]; +- if (isBoolean(opts)) { +- // legacy... +- ctx.showHidden = opts; +- } else if (opts) { +- // got an "options" object +- exports._extend(ctx, opts); +- } +- // set default options +- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; +- if (isUndefined(ctx.depth)) ctx.depth = 2; +- if (isUndefined(ctx.colors)) ctx.colors = false; +- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; +- if (ctx.colors) ctx.stylize = stylizeWithColor; +- return formatValue(ctx, obj, ctx.depth); +-} +-exports.inspect = inspect; +- +- +-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +-inspect.colors = { +- 'bold' : [1, 22], +- 'italic' : [3, 23], +- 'underline' : [4, 24], +- 'inverse' : [7, 27], +- 'white' : [37, 39], +- 'grey' : [90, 39], +- 'black' : [30, 39], +- 'blue' : [34, 39], +- 'cyan' : [36, 39], +- 'green' : [32, 39], +- 'magenta' : [35, 39], +- 'red' : [31, 39], +- 'yellow' : [33, 39] +-}; +- +-// Don't use 'blue' not visible on cmd.exe +-inspect.styles = { +- 'special': 'cyan', +- 'number': 'yellow', +- 'boolean': 'yellow', +- 'undefined': 'grey', +- 'null': 'bold', +- 'string': 'green', +- 'date': 'magenta', +- // "name": intentionally not styling +- 'regexp': 'red' +-}; +- +- +-function stylizeWithColor(str, styleType) { +- var style = inspect.styles[styleType]; +- +- if (style) { +- return '\u001b[' + inspect.colors[style][0] + 'm' + str + +- '\u001b[' + inspect.colors[style][1] + 'm'; +- } else { +- return str; +- } +-} +- +- +-function stylizeNoColor(str, styleType) { +- return str; +-} +- +- +-function arrayToHash(array) { +- var hash = {}; +- +- array.forEach(function(val, idx) { +- hash[val] = true; +- }); +- +- return hash; +-} +- +- +-function formatValue(ctx, value, recurseTimes) { +- // Provide a hook for user-specified inspect functions. +- // Check that value is an object with an inspect function on it +- if (ctx.customInspect && +- value && +- isFunction(value.inspect) && +- // Filter out the util module, it's inspect function is special +- value.inspect !== exports.inspect && +- // Also filter out any prototype objects using the circular check. +- !(value.constructor && value.constructor.prototype === value)) { +- var ret = value.inspect(recurseTimes, ctx); +- if (!isString(ret)) { +- ret = formatValue(ctx, ret, recurseTimes); +- } +- return ret; +- } +- +- // Primitive types cannot have properties +- var primitive = formatPrimitive(ctx, value); +- if (primitive) { +- return primitive; +- } +- +- // Look up the keys of the object. +- var keys = Object.keys(value); +- var visibleKeys = arrayToHash(keys); +- +- if (ctx.showHidden) { +- keys = Object.getOwnPropertyNames(value); +- } +- +- // Some type of object without properties can be shortcutted. +- if (keys.length === 0) { +- if (isFunction(value)) { +- var name = value.name ? ': ' + value.name : ''; +- return ctx.stylize('[Function' + name + ']', 'special'); +- } +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } +- if (isDate(value)) { +- return ctx.stylize(Date.prototype.toString.call(value), 'date'); +- } +- if (isError(value)) { +- return formatError(value); +- } +- } +- +- var base = '', array = false, braces = ['{', '}']; +- +- // Make Array say that they are Array +- if (isArray(value)) { +- array = true; +- braces = ['[', ']']; +- } +- +- // Make functions say that they are functions +- if (isFunction(value)) { +- var n = value.name ? ': ' + value.name : ''; +- base = ' [Function' + n + ']'; +- } +- +- // Make RegExps say that they are RegExps +- if (isRegExp(value)) { +- base = ' ' + RegExp.prototype.toString.call(value); +- } +- +- // Make dates with properties first say the date +- if (isDate(value)) { +- base = ' ' + Date.prototype.toUTCString.call(value); +- } +- +- // Make error with message first say the error +- if (isError(value)) { +- base = ' ' + formatError(value); +- } +- +- if (keys.length === 0 && (!array || value.length == 0)) { +- return braces[0] + base + braces[1]; +- } +- +- if (recurseTimes < 0) { +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } else { +- return ctx.stylize('[Object]', 'special'); +- } +- } +- +- ctx.seen.push(value); +- +- var output; +- if (array) { +- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); +- } else { +- output = keys.map(function(key) { +- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); +- }); +- } +- +- ctx.seen.pop(); +- +- return reduceToSingleString(output, base, braces); +-} +- +- +-function formatPrimitive(ctx, value) { +- if (isUndefined(value)) +- return ctx.stylize('undefined', 'undefined'); +- if (isString(value)) { +- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') +- .replace(/'/g, "\\'") +- .replace(/\\"/g, '"') + '\''; +- return ctx.stylize(simple, 'string'); +- } +- if (isNumber(value)) { +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . +- if (value === 0 && 1 / value < 0) +- return ctx.stylize('-0', 'number'); +- return ctx.stylize('' + value, 'number'); +- } +- if (isBoolean(value)) +- return ctx.stylize('' + value, 'boolean'); +- // For some reason typeof null is "object", so special case here. +- if (isNull(value)) +- return ctx.stylize('null', 'null'); +-} +- +- +-function formatError(value) { +- return '[' + Error.prototype.toString.call(value) + ']'; +-} +- +- +-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { +- var output = []; +- for (var i = 0, l = value.length; i < l; ++i) { +- if (hasOwnProperty(value, String(i))) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- String(i), true)); +- } else { +- output.push(''); +- } +- } +- keys.forEach(function(key) { +- if (!key.match(/^\d+$/)) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- key, true)); +- } +- }); +- return output; +-} +- +- +-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { +- var name, str, desc; +- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; +- if (desc.get) { +- if (desc.set) { +- str = ctx.stylize('[Getter/Setter]', 'special'); +- } else { +- str = ctx.stylize('[Getter]', 'special'); +- } +- } else { +- if (desc.set) { +- str = ctx.stylize('[Setter]', 'special'); +- } +- } +- if (!hasOwnProperty(visibleKeys, key)) { +- name = '[' + key + ']'; +- } +- if (!str) { +- if (ctx.seen.indexOf(desc.value) < 0) { +- if (isNull(recurseTimes)) { +- str = formatValue(ctx, desc.value, null); +- } else { +- str = formatValue(ctx, desc.value, recurseTimes - 1); +- } +- if (str.indexOf('\n') > -1) { +- if (array) { +- str = str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n').substr(2); +- } else { +- str = '\n' + str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n'); +- } +- } +- } else { +- str = ctx.stylize('[Circular]', 'special'); +- } +- } +- if (isUndefined(name)) { +- if (array && key.match(/^\d+$/)) { +- return str; +- } +- name = JSON.stringify('' + key); +- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { +- name = name.substr(1, name.length - 2); +- name = ctx.stylize(name, 'name'); +- } else { +- name = name.replace(/'/g, "\\'") +- .replace(/\\"/g, '"') +- .replace(/(^"|"$)/g, "'"); +- name = ctx.stylize(name, 'string'); +- } +- } +- +- return name + ': ' + str; +-} +- +- +-function reduceToSingleString(output, base, braces) { +- var numLinesEst = 0; +- var length = output.reduce(function(prev, cur) { +- numLinesEst++; +- if (cur.indexOf('\n') >= 0) numLinesEst++; +- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; +- }, 0); +- +- if (length > 60) { +- return braces[0] + +- (base === '' ? '' : base + '\n ') + +- ' ' + +- output.join(',\n ') + +- ' ' + +- braces[1]; +- } +- +- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +-} +- +- + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { +@@ -522,166 +98,10 @@ function isPrimitive(arg) { + exports.isPrimitive = isPrimitive; + + function isBuffer(arg) { +- return arg instanceof Buffer; ++ return Buffer.isBuffer(arg); + } + exports.isBuffer = isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); +-} +- +- +-function pad(n) { +- return n < 10 ? '0' + n.toString(10) : n.toString(10); +-} +- +- +-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', +- 'Oct', 'Nov', 'Dec']; +- +-// 26 Feb 16:19:34 +-function timestamp() { +- var d = new Date(); +- var time = [pad(d.getHours()), +- pad(d.getMinutes()), +- pad(d.getSeconds())].join(':'); +- return [d.getDate(), months[d.getMonth()], time].join(' '); +-} +- +- +-// log is just a thin wrapper to console.log that prepends a timestamp +-exports.log = function() { +- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +-}; +- +- +-/** +- * Inherit the prototype methods from one constructor into another. +- * +- * The Function.prototype.inherits from lang.js rewritten as a standalone +- * function (not on Function.prototype). NOTE: If this file is to be loaded +- * during bootstrapping this function needs to be rewritten using some native +- * functions as prototype setup using normal JavaScript does not work as +- * expected during bootstrapping (see mirror.js in r114903). +- * +- * @param {function} ctor Constructor function which needs to inherit the +- * prototype. +- * @param {function} superCtor Constructor function to inherit prototype from. +- */ +-exports.inherits = function(ctor, superCtor) { +- ctor.super_ = superCtor; +- ctor.prototype = Object.create(superCtor.prototype, { +- constructor: { +- value: ctor, +- enumerable: false, +- writable: true, +- configurable: true +- } +- }); +-}; +- +-exports._extend = function(origin, add) { +- // Don't do anything if add isn't an object +- if (!add || !isObject(add)) return origin; +- +- var keys = Object.keys(add); +- var i = keys.length; +- while (i--) { +- origin[keys[i]] = add[keys[i]]; +- } +- return origin; +-}; +- +-function hasOwnProperty(obj, prop) { +- return Object.prototype.hasOwnProperty.call(obj, prop); +-} +- +- +-// Deprecated old stuff. +- +-exports.p = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- console.error(exports.inspect(arguments[i])); +- } +-}, 'util.p: Use console.error() instead'); +- +- +-exports.exec = exports.deprecate(function() { +- return require('child_process').exec.apply(this, arguments); +-}, 'util.exec is now called `child_process.exec`.'); +- +- +-exports.print = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(String(arguments[i])); +- } +-}, 'util.print: Use console.log instead'); +- +- +-exports.puts = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(arguments[i] + '\n'); +- } +-}, 'util.puts: Use console.log instead'); +- +- +-exports.debug = exports.deprecate(function(x) { +- process.stderr.write('DEBUG: ' + x + '\n'); +-}, 'util.debug: Use console.error instead'); +- +- +-exports.error = exports.deprecate(function(x) { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stderr.write(arguments[i] + '\n'); +- } +-}, 'util.error: Use console.error instead'); +- +- +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) { +- var callbackCalled = false; +- +- function call(a, b, c) { +- if (callback && !callbackCalled) { +- callback(a, b, c); +- callbackCalled = true; +- } +- } +- +- readStream.addListener('data', function(chunk) { +- if (writeStream.write(chunk) === false) readStream.pause(); +- }); +- +- writeStream.addListener('drain', function() { +- readStream.resume(); +- }); +- +- readStream.addListener('end', function() { +- writeStream.end(); +- }); +- +- readStream.addListener('close', function() { +- call(); +- }); +- +- readStream.addListener('error', function(err) { +- writeStream.end(); +- call(err); +- }); +- +- writeStream.addListener('error', function(err) { +- readStream.destroy(); +- call(err); +- }); +-}, 'util.pump(): Use readableStream.pipe() instead'); +- +- +-var uv; +-exports._errnoException = function(err, syscall) { +- if (isUndefined(uv)) uv = process.binding('uv'); +- var errname = uv.errname(err); +- var e = new Error(syscall + ' ' + errname); +- e.code = errname; +- e.errno = errname; +- e.syscall = syscall; +- return e; +-}; ++} \ No newline at end of file diff --git a/app/node_modules/core-util-is/lib/util.js b/app/node_modules/core-util-is/lib/util.js new file mode 100644 index 0000000..ff4c851 --- /dev/null +++ b/app/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 = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/app/node_modules/core-util-is/package.json b/app/node_modules/core-util-is/package.json new file mode 100644 index 0000000..3368e95 --- /dev/null +++ b/app/node_modules/core-util-is/package.json @@ -0,0 +1,32 @@ +{ + "name": "core-util-is", + "version": "1.0.2", + "description": "The `util.is*` functions introduced in Node v0.12.", + "main": "lib/util.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/core-util-is" + }, + "keywords": [ + "util", + "isBuffer", + "isArray", + "isNumber", + "isString", + "isRegExp", + "isThis", + "isThat", + "polyfill" + ], + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "scripts": { + "test": "tap test.js" + }, + "devDependencies": { + "tap": "^2.3.0" + } +} diff --git a/app/node_modules/core-util-is/test.js b/app/node_modules/core-util-is/test.js new file mode 100644 index 0000000..1a490c6 --- /dev/null +++ b/app/node_modules/core-util-is/test.js @@ -0,0 +1,68 @@ +var assert = require('tap'); + +var t = require('./lib/util'); + +assert.equal(t.isArray([]), true); +assert.equal(t.isArray({}), false); + +assert.equal(t.isBoolean(null), false); +assert.equal(t.isBoolean(true), true); +assert.equal(t.isBoolean(false), true); + +assert.equal(t.isNull(null), true); +assert.equal(t.isNull(undefined), false); +assert.equal(t.isNull(false), false); +assert.equal(t.isNull(), false); + +assert.equal(t.isNullOrUndefined(null), true); +assert.equal(t.isNullOrUndefined(undefined), true); +assert.equal(t.isNullOrUndefined(false), false); +assert.equal(t.isNullOrUndefined(), true); + +assert.equal(t.isNumber(null), false); +assert.equal(t.isNumber('1'), false); +assert.equal(t.isNumber(1), true); + +assert.equal(t.isString(null), false); +assert.equal(t.isString('1'), true); +assert.equal(t.isString(1), false); + +assert.equal(t.isSymbol(null), false); +assert.equal(t.isSymbol('1'), false); +assert.equal(t.isSymbol(1), false); +assert.equal(t.isSymbol(Symbol()), true); + +assert.equal(t.isUndefined(null), false); +assert.equal(t.isUndefined(undefined), true); +assert.equal(t.isUndefined(false), false); +assert.equal(t.isUndefined(), true); + +assert.equal(t.isRegExp(null), false); +assert.equal(t.isRegExp('1'), false); +assert.equal(t.isRegExp(new RegExp()), true); + +assert.equal(t.isObject({}), true); +assert.equal(t.isObject([]), true); +assert.equal(t.isObject(new RegExp()), true); +assert.equal(t.isObject(new Date()), true); + +assert.equal(t.isDate(null), false); +assert.equal(t.isDate('1'), false); +assert.equal(t.isDate(new Date()), true); + +assert.equal(t.isError(null), false); +assert.equal(t.isError({ err: true }), false); +assert.equal(t.isError(new Error()), true); + +assert.equal(t.isFunction(null), false); +assert.equal(t.isFunction({ }), false); +assert.equal(t.isFunction(function() {}), true); + +assert.equal(t.isPrimitive(null), true); +assert.equal(t.isPrimitive(''), true); +assert.equal(t.isPrimitive(0), true); +assert.equal(t.isPrimitive(new Date()), false); + +assert.equal(t.isBuffer(null), false); +assert.equal(t.isBuffer({}), false); +assert.equal(t.isBuffer(new Buffer(0)), true); diff --git a/app/node_modules/cycle/README.md b/app/node_modules/cycle/README.md new file mode 100644 index 0000000..de9a06d --- /dev/null +++ b/app/node_modules/cycle/README.md @@ -0,0 +1,49 @@ +Fork of https://github.com/douglascrockford/JSON-js, maintained in npm as `cycle`. + +# Contributors + +* Douglas Crockford +* Nuno Job +* Justin Warkentin + +# JSON in JavaScript + +Douglas Crockford +douglas@crockford.com + +2010-11-18 + + +JSON is a light-weight, language independent, data interchange format. +See http://www.JSON.org/ + +The files in this collection implement JSON encoders/decoders in JavaScript. + +JSON became a built-in feature of JavaScript when the ECMAScript Programming +Language Standard - Fifth Edition was adopted by the ECMA General Assembly +in December 2009. Most of the files in this collection are for applications +that are expected to run in obsolete web browsers. For most purposes, json2.js +is the best choice. + + +json2.js: This file creates a JSON property in the global object, if there +isn't already one, setting its value to an object containing a stringify +method and a parse method. The parse method uses the eval method to do the +parsing, guarding it with several regular expressions to defend against +accidental code execution hazards. On current browsers, this file does nothing, +prefering the built-in JSON object. + +json.js: This file does everything that json2.js does. It also adds a +toJSONString method and a parseJSON method to Object.prototype. Use of this +file is not recommended. + +json_parse.js: This file contains an alternative JSON parse function that +uses recursive descent instead of eval. + +json_parse_state.js: This files contains an alternative JSON parse function that +uses a state machine instead of eval. + +cycle.js: This file contains two functions, JSON.decycle and JSON.retrocycle, +which make it possible to encode cyclical structures and dags in JSON, and to +then recover them. JSONPath is used to represent the links. +http://GOESSNER.net/articles/JsonPath/ diff --git a/app/node_modules/cycle/cycle.js b/app/node_modules/cycle/cycle.js new file mode 100644 index 0000000..2e776ad --- /dev/null +++ b/app/node_modules/cycle/cycle.js @@ -0,0 +1,170 @@ +/* + cycle.js + 2013-02-19 + + Public Domain. + + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. +*/ + +/*jslint evil: true, regexp: true */ + +/*members $ref, apply, call, decycle, hasOwnProperty, length, prototype, push, + retrocycle, stringify, test, toString +*/ + +var cycle = exports; + +cycle.decycle = function decycle(object) { + 'use strict'; + +// Make a deep copy of an object or array, assuring that there is at most +// one instance of each object or array in the resulting structure. The +// duplicate references (which might be forming cycles) are replaced with +// an object of the form +// {$ref: PATH} +// where the PATH is a JSONPath string that locates the first occurance. +// So, +// var a = []; +// a[0] = a; +// return JSON.stringify(JSON.decycle(a)); +// produces the string '[{"$ref":"$"}]'. + +// JSONPath is used to locate the unique object. $ indicates the top level of +// the object or array. [NUMBER] or [STRING] indicates a child member or +// property. + + var objects = [], // Keep a reference to each unique object or array + paths = []; // Keep the path to each unique object or array + + return (function derez(value, path) { + +// The derez recurses through the object, producing the deep copy. + + var i, // The loop counter + name, // Property name + nu; // The new object or array + +// typeof null === 'object', so go on if this value is really an object but not +// one of the weird builtin objects. + + if (typeof value === 'object' && value !== null && + !(value instanceof Boolean) && + !(value instanceof Date) && + !(value instanceof Number) && + !(value instanceof RegExp) && + !(value instanceof String)) { + +// If the value is an object or array, look to see if we have already +// encountered it. If so, return a $ref/path object. This is a hard way, +// linear search that will get slower as the number of unique objects grows. + + for (i = 0; i < objects.length; i += 1) { + if (objects[i] === value) { + return {$ref: paths[i]}; + } + } + +// Otherwise, accumulate the unique value and its path. + + objects.push(value); + paths.push(path); + +// If it is an array, replicate the array. + + if (Object.prototype.toString.apply(value) === '[object Array]') { + nu = []; + for (i = 0; i < value.length; i += 1) { + nu[i] = derez(value[i], path + '[' + i + ']'); + } + } else { + +// If it is an object, replicate the object. + + nu = {}; + for (name in value) { + if (Object.prototype.hasOwnProperty.call(value, name)) { + nu[name] = derez(value[name], + path + '[' + JSON.stringify(name) + ']'); + } + } + } + return nu; + } + return value; + }(object, '$')); +}; + + +cycle.retrocycle = function retrocycle($) { + 'use strict'; + +// Restore an object that was reduced by decycle. Members whose values are +// objects of the form +// {$ref: PATH} +// are replaced with references to the value found by the PATH. This will +// restore cycles. The object will be mutated. + +// The eval function is used to locate the values described by a PATH. The +// root object is kept in a $ variable. A regular expression is used to +// assure that the PATH is extremely well formed. The regexp contains nested +// * quantifiers. That has been known to have extremely bad performance +// problems on some browsers for very long strings. A PATH is expected to be +// reasonably short. A PATH is allowed to belong to a very restricted subset of +// Goessner's JSONPath. + +// So, +// var s = '[{"$ref":"$"}]'; +// return JSON.retrocycle(JSON.parse(s)); +// produces an array containing a single element which is the array itself. + + var px = + /^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/; + + (function rez(value) { + +// The rez function walks recursively through the object looking for $ref +// properties. When it finds one that has a value that is a path, then it +// replaces the $ref object with a reference to the value that is found by +// the path. + + var i, item, name, path; + + if (value && typeof value === 'object') { + if (Object.prototype.toString.apply(value) === '[object Array]') { + for (i = 0; i < value.length; i += 1) { + item = value[i]; + if (item && typeof item === 'object') { + path = item.$ref; + if (typeof path === 'string' && px.test(path)) { + value[i] = eval(path); + } else { + rez(item); + } + } + } + } else { + for (name in value) { + if (typeof value[name] === 'object') { + item = value[name]; + if (item) { + path = item.$ref; + if (typeof path === 'string' && px.test(path)) { + value[name] = eval(path); + } else { + rez(item); + } + } + } + } + } + } + }($)); + return $; +}; diff --git a/app/node_modules/cycle/package.json b/app/node_modules/cycle/package.json new file mode 100644 index 0000000..6d85022 --- /dev/null +++ b/app/node_modules/cycle/package.json @@ -0,0 +1,12 @@ +{ "name" : "cycle" +, "description" : "decycle your json" +, "author" : "" +, "version" : "1.0.3" +, "main" : "./cycle.js" +, "homepage" : "https://github.com/douglascrockford/JSON-js" +, "repository" : + { "type": "git", "url": "http://github.com/dscape/cycle.git" } +, "bugs" : "http://github.com/douglascrockford/JSON-js/issues" +, "keywords" : [ "json", "cycle", "stringify", "parse" ] +, "engines" : { "node" : ">=0.4.0" } +} diff --git a/app/node_modules/debug/.coveralls.yml b/app/node_modules/debug/.coveralls.yml new file mode 100644 index 0000000..20a7068 --- /dev/null +++ b/app/node_modules/debug/.coveralls.yml @@ -0,0 +1 @@ +repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/app/node_modules/debug/.eslintrc b/app/node_modules/debug/.eslintrc new file mode 100644 index 0000000..8a37ae2 --- /dev/null +++ b/app/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/app/node_modules/debug/.npmignore b/app/node_modules/debug/.npmignore new file mode 100644 index 0000000..5f60eec --- /dev/null +++ b/app/node_modules/debug/.npmignore @@ -0,0 +1,9 @@ +support +test +examples +example +*.sock +dist +yarn.lock +coverage +bower.json diff --git a/app/node_modules/debug/.travis.yml b/app/node_modules/debug/.travis.yml new file mode 100644 index 0000000..6c6090c --- /dev/null +++ b/app/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/app/node_modules/debug/CHANGELOG.md b/app/node_modules/debug/CHANGELOG.md new file mode 100644 index 0000000..eadaa18 --- /dev/null +++ b/app/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/app/node_modules/debug/LICENSE b/app/node_modules/debug/LICENSE new file mode 100644 index 0000000..658c933 --- /dev/null +++ b/app/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/app/node_modules/debug/Makefile b/app/node_modules/debug/Makefile new file mode 100644 index 0000000..584da8b --- /dev/null +++ b/app/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/app/node_modules/debug/README.md b/app/node_modules/debug/README.md new file mode 100644 index 0000000..f67be6b --- /dev/null +++ b/app/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/app/node_modules/debug/component.json b/app/node_modules/debug/component.json new file mode 100644 index 0000000..9de2641 --- /dev/null +++ b/app/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/app/node_modules/debug/karma.conf.js b/app/node_modules/debug/karma.conf.js new file mode 100644 index 0000000..103a82d --- /dev/null +++ b/app/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/app/node_modules/debug/node.js b/app/node_modules/debug/node.js new file mode 100644 index 0000000..7fc36fe --- /dev/null +++ b/app/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/app/node_modules/debug/package.json b/app/node_modules/debug/package.json new file mode 100644 index 0000000..dc787ba --- /dev/null +++ b/app/node_modules/debug/package.json @@ -0,0 +1,49 @@ +{ + "name": "debug", + "version": "2.6.9", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": "TJ Holowaychuk ", + "contributors": [ + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne " + ], + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + }, + "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" + }, + "main": "./src/index.js", + "browser": "./src/browser.js", + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + } +} diff --git a/app/node_modules/debug/src/browser.js b/app/node_modules/debug/src/browser.js new file mode 100644 index 0000000..7106924 --- /dev/null +++ b/app/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/app/node_modules/debug/src/debug.js b/app/node_modules/debug/src/debug.js new file mode 100644 index 0000000..6a5e3fc --- /dev/null +++ b/app/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/app/node_modules/debug/src/index.js b/app/node_modules/debug/src/index.js new file mode 100644 index 0000000..e12cf4d --- /dev/null +++ b/app/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/app/node_modules/debug/src/inspector-log.js b/app/node_modules/debug/src/inspector-log.js new file mode 100644 index 0000000..60ea6c0 --- /dev/null +++ b/app/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/app/node_modules/debug/src/node.js b/app/node_modules/debug/src/node.js new file mode 100644 index 0000000..b15109c --- /dev/null +++ b/app/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/app/node_modules/decamelize/index.js b/app/node_modules/decamelize/index.js new file mode 100644 index 0000000..8d5bab7 --- /dev/null +++ b/app/node_modules/decamelize/index.js @@ -0,0 +1,13 @@ +'use strict'; +module.exports = function (str, sep) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + sep = typeof sep === 'undefined' ? '_' : sep; + + return str + .replace(/([a-z\d])([A-Z])/g, '$1' + sep + '$2') + .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + sep + '$2') + .toLowerCase(); +}; diff --git a/app/node_modules/decamelize/license b/app/node_modules/decamelize/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/app/node_modules/decamelize/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/app/node_modules/decamelize/package.json b/app/node_modules/decamelize/package.json new file mode 100644 index 0000000..ca35790 --- /dev/null +++ b/app/node_modules/decamelize/package.json @@ -0,0 +1,38 @@ +{ + "name": "decamelize", + "version": "1.2.0", + "description": "Convert a camelized string into a lowercased one with a custom separator: unicornRainbow → unicorn_rainbow", + "license": "MIT", + "repository": "sindresorhus/decamelize", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "decamelize", + "decamelcase", + "camelcase", + "lowercase", + "case", + "dash", + "hyphen", + "string", + "str", + "text", + "convert" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + } +} diff --git a/app/node_modules/decamelize/readme.md b/app/node_modules/decamelize/readme.md new file mode 100644 index 0000000..624c7ee --- /dev/null +++ b/app/node_modules/decamelize/readme.md @@ -0,0 +1,48 @@ +# decamelize [![Build Status](https://travis-ci.org/sindresorhus/decamelize.svg?branch=master)](https://travis-ci.org/sindresorhus/decamelize) + +> Convert a camelized string into a lowercased one with a custom separator
+> Example: `unicornRainbow` → `unicorn_rainbow` + + +## Install + +``` +$ npm install --save decamelize +``` + + +## Usage + +```js +const decamelize = require('decamelize'); + +decamelize('unicornRainbow'); +//=> 'unicorn_rainbow' + +decamelize('unicornRainbow', '-'); +//=> 'unicorn-rainbow' +``` + + +## API + +### decamelize(input, [separator]) + +#### input + +Type: `string` + +#### separator + +Type: `string`
+Default: `_` + + +## Related + +See [`camelcase`](https://github.com/sindresorhus/camelcase) for the inverse. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/app/node_modules/depd/History.md b/app/node_modules/depd/History.md new file mode 100644 index 0000000..507ecb8 --- /dev/null +++ b/app/node_modules/depd/History.md @@ -0,0 +1,96 @@ +1.1.2 / 2018-01-11 +================== + + * perf: remove argument reassignment + * Support Node.js 0.6 to 9.x + +1.1.1 / 2017-07-27 +================== + + * Remove unnecessary `Buffer` loading + * Support Node.js 0.6 to 8.x + +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/app/node_modules/depd/LICENSE b/app/node_modules/depd/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/app/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/app/node_modules/depd/Readme.md b/app/node_modules/depd/Readme.md new file mode 100644 index 0000000..7790670 --- /dev/null +++ b/app/node_modules/depd/Readme.md @@ -0,0 +1,280 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + + + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction () { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[npm-version-image]: https://img.shields.io/npm/v/depd.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg +[npm-url]: https://npmjs.org/package/depd +[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://img.shields.io/node/v/depd.svg +[node-url]: https://nodejs.org/en/download/ diff --git a/app/node_modules/depd/index.js b/app/node_modules/depd/index.js new file mode 100644 index 0000000..d758d3c --- /dev/null +++ b/app/node_modules/depd/index.js @@ -0,0 +1,522 @@ +/*! + * depd + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var callSiteToString = require('./lib/compat').callSiteToString +var eventListenerCount = require('./lib/compat').eventListenerCount +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() + + for (var i = 0; i < vals.length; i++) { + var val = vals[i] + + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter () { return value } + + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString (arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString (stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if namespace is ignored. + */ + +function isignored (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log (message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + depSite = site + callSite = callSiteLocation(stack[1]) + callSite.name = depSite.name + file = callSite[0] + } else { + // get call site + i = 2 + depSite = callSiteLocation(stack[i]) + callSite = depSite + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var output = format.call(this, msg, caller, stack.slice(i)) + process.stderr.write(output + '\n', 'utf8') +} + +/** + * Get call site location as array. + */ + +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace (obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var deprecate = this // eslint-disable-line no-unused-vars + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + // eslint-disable-next-line no-eval + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) + + return error +} diff --git a/app/node_modules/depd/lib/browser/index.js b/app/node_modules/depd/lib/browser/index.js new file mode 100644 index 0000000..6be45cc --- /dev/null +++ b/app/node_modules/depd/lib/browser/index.js @@ -0,0 +1,77 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate (message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } +} diff --git a/app/node_modules/depd/lib/compat/callsite-tostring.js b/app/node_modules/depd/lib/compat/callsite-tostring.js new file mode 100644 index 0000000..73186dc --- /dev/null +++ b/app/node_modules/depd/lib/compat/callsite-tostring.js @@ -0,0 +1,103 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = callSiteToString + +/** + * Format a CallSite file location to a string. + */ + +function callSiteFileLocation (callSite) { + var fileName + var fileLocation = '' + + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } + + if (fileName) { + fileLocation += fileName + + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber + + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } + + return fileLocation || 'unknown source' +} + +/** + * Format a CallSite to a string. + */ + +function callSiteToString (callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' + + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) + + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } + + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} + +/** + * Get constructor name of reviver. + */ + +function getConstructorName (obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} diff --git a/app/node_modules/depd/lib/compat/event-listener-count.js b/app/node_modules/depd/lib/compat/event-listener-count.js new file mode 100644 index 0000000..3a8925d --- /dev/null +++ b/app/node_modules/depd/lib/compat/event-listener-count.js @@ -0,0 +1,22 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = eventListenerCount + +/** + * Get the count of listeners on an event emitter of a specific type. + */ + +function eventListenerCount (emitter, type) { + return emitter.listeners(type).length +} diff --git a/app/node_modules/depd/lib/compat/index.js b/app/node_modules/depd/lib/compat/index.js new file mode 100644 index 0000000..955b333 --- /dev/null +++ b/app/node_modules/depd/lib/compat/index.js @@ -0,0 +1,79 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var EventEmitter = require('events').EventEmitter + +/** + * Module exports. + * @public + */ + +lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + function prepareObjectStackTrace (obj, stack) { + return stack + } + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 + + // capture the stack + Error.captureStackTrace(obj) + + // slice the stack + var stack = obj.stack.slice() + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : require('./callsite-tostring') +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { + return EventEmitter.listenerCount || require('./event-listener-count') +}) + +/** + * Define a lazy property. + */ + +function lazyProperty (obj, prop, getter) { + function get () { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val + } + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} + +/** + * Call toString() on the obj + */ + +function toString (obj) { + return obj.toString() +} diff --git a/app/node_modules/depd/package.json b/app/node_modules/depd/package.json new file mode 100644 index 0000000..5e3c863 --- /dev/null +++ b/app/node_modules/depd/package.json @@ -0,0 +1,41 @@ +{ + "name": "depd", + "description": "Deprecate all the things", + "version": "1.1.2", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "keywords": [ + "deprecate", + "deprecated" + ], + "repository": "dougwilson/nodejs-depd", + "browser": "lib/browser/index.js", + "devDependencies": { + "benchmark": "2.1.4", + "beautify-benchmark": "0.2.4", + "eslint": "3.19.0", + "eslint-config-standard": "7.1.0", + "eslint-plugin-markdown": "1.0.0-beta.7", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "~1.21.5" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --no-exit test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/" + } +} diff --git a/app/node_modules/destroy/LICENSE b/app/node_modules/destroy/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/app/node_modules/destroy/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/app/node_modules/destroy/README.md b/app/node_modules/destroy/README.md new file mode 100644 index 0000000..6474bc3 --- /dev/null +++ b/app/node_modules/destroy/README.md @@ -0,0 +1,60 @@ +# Destroy + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Destroy a stream. + +This module is meant to ensure a stream gets destroyed, handling different APIs +and Node.js bugs. + +## API + +```js +var destroy = require('destroy') +``` + +### destroy(stream) + +Destroy the given stream. In most cases, this is identical to a simple +`stream.destroy()` call. The rules are as follows for a given stream: + + 1. If the `stream` is an instance of `ReadStream`, then call `stream.destroy()` + and add a listener to the `open` event to call `stream.close()` if it is + fired. This is for a Node.js bug that will leak a file descriptor if + `.destroy()` is called before `open`. + 2. If the `stream` is not an instance of `Stream`, then nothing happens. + 3. If the `stream` has a `.destroy()` method, then call it. + +The function returns the `stream` passed in as the argument. + +## Example + +```js +var destroy = require('destroy') + +var fs = require('fs') +var stream = fs.createReadStream('package.json') + +// ... and later +destroy(stream) +``` + +[npm-image]: https://img.shields.io/npm/v/destroy.svg?style=flat-square +[npm-url]: https://npmjs.org/package/destroy +[github-tag]: http://img.shields.io/github/tag/stream-utils/destroy.svg?style=flat-square +[github-url]: https://github.com/stream-utils/destroy/tags +[travis-image]: https://img.shields.io/travis/stream-utils/destroy.svg?style=flat-square +[travis-url]: https://travis-ci.org/stream-utils/destroy +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/destroy.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/stream-utils/destroy?branch=master +[license-image]: http://img.shields.io/npm/l/destroy.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/destroy.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/destroy +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/app/node_modules/destroy/index.js b/app/node_modules/destroy/index.js new file mode 100644 index 0000000..6da2d26 --- /dev/null +++ b/app/node_modules/destroy/index.js @@ -0,0 +1,75 @@ +/*! + * destroy + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var ReadStream = require('fs').ReadStream +var Stream = require('stream') + +/** + * Module exports. + * @public + */ + +module.exports = destroy + +/** + * Destroy a stream. + * + * @param {object} stream + * @public + */ + +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) + } + + if (!(stream instanceof Stream)) { + return stream + } + + if (typeof stream.destroy === 'function') { + stream.destroy() + } + + return stream +} + +/** + * Destroy a ReadStream. + * + * @param {object} stream + * @private + */ + +function destroyReadStream(stream) { + stream.destroy() + + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) + } + + return stream +} + +/** + * On open handler to close stream. + * @private + */ + +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() + } +} diff --git a/app/node_modules/destroy/package.json b/app/node_modules/destroy/package.json new file mode 100644 index 0000000..024bff9 --- /dev/null +++ b/app/node_modules/destroy/package.json @@ -0,0 +1,37 @@ +{ + "name": "destroy", + "description": "destroy a stream if possible", + "version": "1.0.4", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com", + "twitter": "https://twitter.com/jongleberry" + }, + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "stream-utils/destroy", + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "2.3.4" + }, + "scripts": { + "test": "mocha --reporter spec", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "files": [ + "index.js", + "LICENSE" + ], + "keywords": [ + "stream", + "streams", + "destroy", + "cleanup", + "leak", + "fd" + ] +} diff --git a/app/node_modules/ee-first/LICENSE b/app/node_modules/ee-first/LICENSE new file mode 100644 index 0000000..a7ae8ee --- /dev/null +++ b/app/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/app/node_modules/ee-first/README.md b/app/node_modules/ee-first/README.md new file mode 100644 index 0000000..cbd2478 --- /dev/null +++ b/app/node_modules/ee-first/README.md @@ -0,0 +1,80 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +#### .cancel() + +The group of listeners can be cancelled before being invoked and have all the event +listeners removed from the underlying event emitters. + +```js +var thunk = first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) + +// cancel and clean up +thunk.cancel() +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/app/node_modules/ee-first/index.js b/app/node_modules/ee-first/index.js new file mode 100644 index 0000000..501287c --- /dev/null +++ b/app/node_modules/ee-first/index.js @@ -0,0 +1,95 @@ +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = first + +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ + +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + function callback() { + cleanup() + done.apply(null, arguments) + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } + + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk +} + +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/app/node_modules/ee-first/package.json b/app/node_modules/ee-first/package.json new file mode 100644 index 0000000..b6d0b7d --- /dev/null +++ b/app/node_modules/ee-first/package.json @@ -0,0 +1,29 @@ +{ + "name": "ee-first", + "description": "return the first event in a set of ee/event pairs", + "version": "1.1.1", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com", + "twitter": "https://twitter.com/jongleberry" + }, + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "jonathanong/ee-first", + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "files": [ + "index.js", + "LICENSE" + ], + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/app/node_modules/encodeurl/HISTORY.md b/app/node_modules/encodeurl/HISTORY.md new file mode 100644 index 0000000..41313b2 --- /dev/null +++ b/app/node_modules/encodeurl/HISTORY.md @@ -0,0 +1,14 @@ +1.0.2 / 2018-01-21 +================== + + * Fix encoding `%` as last character + +1.0.1 / 2016-06-09 +================== + + * Fix encoding unpaired surrogates at start/end of string + +1.0.0 / 2016-06-08 +================== + + * Initial release diff --git a/app/node_modules/encodeurl/LICENSE b/app/node_modules/encodeurl/LICENSE new file mode 100644 index 0000000..8812229 --- /dev/null +++ b/app/node_modules/encodeurl/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2016 Douglas Christopher Wilson + +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/app/node_modules/encodeurl/README.md b/app/node_modules/encodeurl/README.md new file mode 100644 index 0000000..127c5a0 --- /dev/null +++ b/app/node_modules/encodeurl/README.md @@ -0,0 +1,128 @@ +# encodeurl + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Encode a URL to a percent-encoded form, excluding already-encoded sequences + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install encodeurl +``` + +## API + +```js +var encodeUrl = require('encodeurl') +``` + +### encodeUrl(url) + +Encode a URL to a percent-encoded form, excluding already-encoded sequences. + +This function will take an already-encoded URL and encode all the non-URL +code points (as UTF-8 byte sequences). This function will not encode the +"%" character unless it is not part of a valid sequence (`%20` will be +left as-is, but `%foo` will be encoded as `%25foo`). + +This encode is meant to be "safe" and does not throw errors. It will try as +hard as it can to properly encode the given URL, including replacing any raw, +unpaired surrogate pairs with the Unicode replacement character prior to +encoding. + +This function is _similar_ to the intrinsic function `encodeURI`, except it +will not encode the `%` character if that is part of a valid sequence, will +not encode `[` and `]` (for IPv6 hostnames) and will replace raw, unpaired +surrogate pairs with the Unicode replacement character (instead of throwing). + +## Examples + +### Encode a URL containing user-controled data + +```js +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') + +http.createServer(function onRequest (req, res) { + // get encoded form of inbound url + var url = encodeUrl(req.url) + + // create html message + var body = '

Location ' + escapeHtml(url) + ' not found

' + + // send a 404 + res.statusCode = 404 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) + res.end(body, 'utf-8') +}) +``` + +### Encode a URL for use in a header field + +```js +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var url = require('url') + +http.createServer(function onRequest (req, res) { + // parse inbound url + var href = url.parse(req) + + // set new host for redirect + href.host = 'localhost' + href.protocol = 'https:' + href.slashes = true + + // create location header + var location = encodeUrl(url.format(href)) + + // create html message + var body = '

Redirecting to new site: ' + escapeHtml(location) + '

' + + // send a 301 + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) + res.setHeader('Location', location) + res.end(body, 'utf-8') +}) +``` + +## Testing + +```sh +$ npm test +$ npm run lint +``` + +## References + +- [RFC 3986: Uniform Resource Identifier (URI): Generic Syntax][rfc-3986] +- [WHATWG URL Living Standard][whatwg-url] + +[rfc-3986]: https://tools.ietf.org/html/rfc3986 +[whatwg-url]: https://url.spec.whatwg.org/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/encodeurl.svg +[npm-url]: https://npmjs.org/package/encodeurl +[node-version-image]: https://img.shields.io/node/v/encodeurl.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/pillarjs/encodeurl.svg +[travis-url]: https://travis-ci.org/pillarjs/encodeurl +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/encodeurl.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/encodeurl?branch=master +[downloads-image]: https://img.shields.io/npm/dm/encodeurl.svg +[downloads-url]: https://npmjs.org/package/encodeurl diff --git a/app/node_modules/encodeurl/index.js b/app/node_modules/encodeurl/index.js new file mode 100644 index 0000000..fc4906c --- /dev/null +++ b/app/node_modules/encodeurl/index.js @@ -0,0 +1,60 @@ +/*! + * encodeurl + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = encodeUrl + +/** + * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") + * and including invalid escape sequences. + * @private + */ + +var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g + +/** + * RegExp to match unmatched surrogate pair. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g + +/** + * String to replace unmatched surrogate pair with. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' + +/** + * Encode a URL to a percent-encoded form, excluding already-encoded sequences. + * + * This function will take an already-encoded URL and encode all the non-URL + * code points. This function will not encode the "%" character unless it is + * not part of a valid sequence (`%20` will be left as-is, but `%foo` will + * be encoded as `%25foo`). + * + * This encode is meant to be "safe" and does not throw errors. It will try as + * hard as it can to properly encode the given URL, including replacing any raw, + * unpaired surrogate pairs with the Unicode replacement character prior to + * encoding. + * + * @param {string} url + * @return {string} + * @public + */ + +function encodeUrl (url) { + return String(url) + .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) + .replace(ENCODE_CHARS_REGEXP, encodeURI) +} diff --git a/app/node_modules/encodeurl/package.json b/app/node_modules/encodeurl/package.json new file mode 100644 index 0000000..b9f25ef --- /dev/null +++ b/app/node_modules/encodeurl/package.json @@ -0,0 +1,40 @@ +{ + "name": "encodeurl", + "description": "Encode a URL to a percent-encoded form, excluding already-encoded sequences", + "version": "1.0.2", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "encode", + "encodeurl", + "url" + ], + "repository": "pillarjs/encodeurl", + "devDependencies": { + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.8.0", + "eslint-plugin-node": "5.2.1", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/app/node_modules/es6-promise/CHANGELOG.md b/app/node_modules/es6-promise/CHANGELOG.md new file mode 100644 index 0000000..cc8aa10 --- /dev/null +++ b/app/node_modules/es6-promise/CHANGELOG.md @@ -0,0 +1,65 @@ +# Master + +# 3.2.0 + +* improve tamper resistence of Promise.all Promise.race and + Promise.prototype.then (note, this isn't complete, but addresses an exception + when used \w core-js, follow up work will address entirely) +* remove spec incompatible then chaining fast-path +* add eslint +* update build deps + +# 3.1.2 + +* fix node detection issues with NWJS/electron + +# 3.1.0 + +* improve performance of Promise.all when it encounters a non-promise input object input +* then/resolve tamper protection +* reduce AST size of promise constructor, to facilitate more inlining +* Update README.md with details about PhantomJS requirement for running tests +* Mangle and compress the minified version + +# 3.0.1 + +* no longer include dist/test in npm releases + +# 3.0.0 + +* use nextTick() instead of setImmediate() to schedule microtasks with node 0.10. Later versions of + nodes are not affected as they were already using nextTick(). Note that using nextTick() might + trigger a depreciation warning on 0.10 as described at https://github.com/cujojs/when/issues/410. + The reason why nextTick() is preferred is that is setImmediate() would schedule a macrotask + instead of a microtask and might result in a different scheduling. + If needed you can revert to the former behavior as follow: + + var Promise = require('es6-promise').Promise; + Promise._setScheduler(setImmediate); + +# 2.3.0 + +* #121: Ability to override the internal asap implementation +* #120: Use an ascii character for an apostrophe, for source maps + +# 2.2.0 + +* #116: Expose asap() and a way to override the scheduling mechanism on Promise +* Lock to v0.2.3 of ember-cli + +# 2.1.1 + +* Fix #100 via #105: tell browserify to ignore vertx require +* Fix #101 via #102: "follow thenable state, not own state" + +# 2.1.0 + +* ? (see the commit log) + +# 2.0.0 + +* re-sync with RSVP. Many large performance improvements and bugfixes. + +# 1.0.0 + +* first subset of RSVP diff --git a/app/node_modules/es6-promise/LICENSE b/app/node_modules/es6-promise/LICENSE new file mode 100644 index 0000000..954ec59 --- /dev/null +++ b/app/node_modules/es6-promise/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and 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/app/node_modules/es6-promise/README.md b/app/node_modules/es6-promise/README.md new file mode 100644 index 0000000..16739ca --- /dev/null +++ b/app/node_modules/es6-promise/README.md @@ -0,0 +1,74 @@ +# ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) + +This is a polyfill of the [ES6 Promise](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js) extracted by @jakearchibald, if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js). + +For API details and how to use promises, see the JavaScript Promises HTML5Rocks article. + +## Downloads + +* [es6-promise](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.js) +* [es6-promise-min](https://raw.githubusercontent.com/stefanpenner/es6-promise/master/dist/es6-promise.min.js) + +## Node.js + +To install: + +```sh +npm install es6-promise +``` + +To use: + +```js +var Promise = require('es6-promise').Promise; +``` + +## Bower + +To install: + +```sh +bower install es6-promise --save +``` + + +## Usage in IE<9 + +`catch` is a reserved word in IE<9, meaning `promise.catch(func)` throws a syntax error. To work around this, you can use a string to access the property as shown in the following example. + +However, please remember that such technique is already provided by most common minifiers, making the resulting code safe for old browsers and production: + +```js +promise['catch'](function(err) { + // ... +}); +``` + +Or use `.then` instead: + +```js +promise.then(undefined, function(err) { + // ... +}); +``` + +## Auto-polyfill + +To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet: + +```js +require('es6-promise').polyfill(); +``` + +Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called. + +## Building & Testing + +You will need to have PhantomJS installed globally in order to run the tests. + +`npm install -g phantomjs` + +* `npm run build` to build +* `npm test` to run tests +* `npm start` to run a build watcher, and webserver to test +* `npm run test:server` for a testem test runner and watching builder diff --git a/app/node_modules/es6-promise/dist/es6-promise.js b/app/node_modules/es6-promise/dist/es6-promise.js new file mode 100644 index 0000000..0755e9b --- /dev/null +++ b/app/node_modules/es6-promise/dist/es6-promise.js @@ -0,0 +1,959 @@ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 3.2.1 + */ + +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); + } + + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; + } + + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$vertxNext; + var lib$es6$promise$asap$$customSchedulerFn; + + var lib$es6$promise$asap$$asap = function asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (lib$es6$promise$asap$$customSchedulerFn) { + lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); + } else { + lib$es6$promise$asap$$scheduleFlush(); + } + } + } + + function lib$es6$promise$asap$$setScheduler(scheduleFn) { + lib$es6$promise$asap$$customSchedulerFn = scheduleFn; + } + + function lib$es6$promise$asap$$setAsap(asapFn) { + lib$es6$promise$asap$$asap = asapFn; + } + + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function lib$es6$promise$asap$$useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function() { + process.nextTick(lib$es6$promise$asap$$flush); + }; + } + + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; + } + + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; + } + + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } + + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; + } + + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; + + callback(arg); + + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; + } + + lib$es6$promise$asap$$len = 0; + } + + function lib$es6$promise$asap$$attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); + } + } + + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + function lib$es6$promise$then$$then(onFulfillment, onRejection) { + var parent = this; + + var child = new this.constructor(lib$es6$promise$$internal$$noop); + + if (child[lib$es6$promise$$internal$$PROMISE_ID] === undefined) { + lib$es6$promise$$internal$$makePromise(child); + } + + var state = parent._state; + + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$asap(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, parent._result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + } + var lib$es6$promise$then$$default = lib$es6$promise$then$$then; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; + } + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + var lib$es6$promise$$internal$$PROMISE_ID = Math.random().toString(36).substring(16); + + function lib$es6$promise$$internal$$noop() {} + + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } + + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; + } + } + + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } + } + + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$asap(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); + } + }, promise); + } + + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + } + + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable, then) { + if (maybeThenable.constructor === promise.constructor && + then === lib$es6$promise$then$$default && + constructor.resolve === lib$es6$promise$promise$resolve$$default) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); + } else { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + } + } + + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value, lib$es6$promise$$internal$$getThen(value)); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + } + + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + lib$es6$promise$$internal$$publish(promise); + } + + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); + } + } + + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); + } + + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); + } + } + + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; + } + + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; + } + } + + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } + } + + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); + } + } + + var lib$es6$promise$$internal$$id = 0; + function lib$es6$promise$$internal$$nextId() { + return lib$es6$promise$$internal$$id++; + } + + function lib$es6$promise$$internal$$makePromise(promise) { + promise[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; + } + + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!lib$es6$promise$utils$$isArray(entries)) { + return new Constructor(function(resolve, reject) { + reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function(resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } + } + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; + } + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + + + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (lib$es6$promise$$internal$$noop !== resolver) { + typeof resolver !== 'function' && lib$es6$promise$promise$$needsResolver(); + this instanceof lib$es6$promise$promise$$Promise ? lib$es6$promise$$internal$$initializePromise(this, resolver) : lib$es6$promise$promise$$needsNew(); + } + } + + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; + lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; + lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; + + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: lib$es6$promise$then$$default, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } + }; + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (!this.promise[lib$es6$promise$$internal$$PROMISE_ID]) { + lib$es6$promise$$internal$$makePromise(this.promise); + } + + if (lib$es6$promise$utils$$isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; + + this._result = new Array(this.length); + + if (this.length === 0) { + lib$es6$promise$$internal$$fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(); + if (this._remaining === 0) { + lib$es6$promise$$internal$$fulfill(this.promise, this._result); + } + } + } else { + lib$es6$promise$$internal$$reject(this.promise, lib$es6$promise$enumerator$$validationError()); + } + } + + function lib$es6$promise$enumerator$$validationError() { + return new Error('Array Methods must be provided an Array'); + } + + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { + var length = this.length; + var input = this._input; + + for (var i = 0; this._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + this._eachEntry(input[i], i); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var c = this._instanceConstructor; + var resolve = c.resolve; + + if (resolve === lib$es6$promise$promise$resolve$$default) { + var then = lib$es6$promise$$internal$$getThen(entry); + + if (then === lib$es6$promise$then$$default && + entry._state !== lib$es6$promise$$internal$$PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === lib$es6$promise$promise$$default) { + var promise = new c(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$handleMaybeThenable(promise, entry, then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function(resolve) { resolve(entry); }), i); + } + } else { + this._willSettleAt(resolve(entry), i); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var promise = this.promise; + + if (promise._state === lib$es6$promise$$internal$$PENDING) { + this._remaining--; + + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } else { + this._result[i] = value; + } + } + + if (this._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, this._result); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$polyfill$$polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = lib$es6$promise$promise$$default; + } + var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; + + var lib$es6$promise$umd$$ES6Promise = { + 'Promise': lib$es6$promise$promise$$default, + 'polyfill': lib$es6$promise$polyfill$$default + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define['amd']) { + define(function() { return lib$es6$promise$umd$$ES6Promise; }); + } else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = lib$es6$promise$umd$$ES6Promise; + } else if (typeof this !== 'undefined') { + this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + } + + lib$es6$promise$polyfill$$default(); +}).call(this); + diff --git a/app/node_modules/es6-promise/dist/es6-promise.min.js b/app/node_modules/es6-promise/dist/es6-promise.min.js new file mode 100644 index 0000000..13151c2 --- /dev/null +++ b/app/node_modules/es6-promise/dist/es6-promise.min.js @@ -0,0 +1,9 @@ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 3.2.1 + */ + +(function(){"use strict";function t(t){return"function"==typeof t||"object"==typeof t&&null!==t}function e(t){return"function"==typeof t}function n(t){G=t}function r(t){Q=t}function o(){return function(){process.nextTick(a)}}function i(){return function(){B(a)}}function s(){var t=0,e=new X(a),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage=a,function(){t.port2.postMessage(0)}}function c(){return function(){setTimeout(a,1)}}function a(){for(var t=0;J>t;t+=2){var e=tt[t],n=tt[t+1];e(n),tt[t]=void 0,tt[t+1]=void 0}J=0}function f(){try{var t=require,e=t("vertx");return B=e.runOnLoop||e.runOnContext,i()}catch(n){return c()}}function l(t,e){var n=this,r=new this.constructor(p);void 0===r[rt]&&k(r);var o=n._state;if(o){var i=arguments[o-1];Q(function(){x(o,r,i,n._result)})}else E(n,r,t,e);return r}function h(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var n=new e(p);return g(n,t),n}function p(){}function _(){return new TypeError("You cannot resolve a promise with itself")}function d(){return new TypeError("A promises callback cannot return that same promise.")}function v(t){try{return t.then}catch(e){return ut.error=e,ut}}function y(t,e,n,r){try{t.call(e,n,r)}catch(o){return o}}function m(t,e,n){Q(function(t){var r=!1,o=y(n,e,function(n){r||(r=!0,e!==n?g(t,n):S(t,n))},function(e){r||(r=!0,j(t,e))},"Settle: "+(t._label||" unknown promise"));!r&&o&&(r=!0,j(t,o))},t)}function b(t,e){e._state===it?S(t,e._result):e._state===st?j(t,e._result):E(e,void 0,function(e){g(t,e)},function(e){j(t,e)})}function w(t,n,r){n.constructor===t.constructor&&r===et&&constructor.resolve===nt?b(t,n):r===ut?j(t,ut.error):void 0===r?S(t,n):e(r)?m(t,n,r):S(t,n)}function g(e,n){e===n?j(e,_()):t(n)?w(e,n,v(n)):S(e,n)}function A(t){t._onerror&&t._onerror(t._result),T(t)}function S(t,e){t._state===ot&&(t._result=e,t._state=it,0!==t._subscribers.length&&Q(T,t))}function j(t,e){t._state===ot&&(t._state=st,t._result=e,Q(A,t))}function E(t,e,n,r){var o=t._subscribers,i=o.length;t._onerror=null,o[i]=e,o[i+it]=n,o[i+st]=r,0===i&&t._state&&Q(T,t)}function T(t){var e=t._subscribers,n=t._state;if(0!==e.length){for(var r,o,i=t._result,s=0;si;i++)e.resolve(t[i]).then(n,r)}:function(t,e){e(new TypeError("You must pass an array to race."))})}function F(t){var e=this,n=new e(p);return j(n,t),n}function D(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function K(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function L(t){this[rt]=O(),this._result=this._state=void 0,this._subscribers=[],p!==t&&("function"!=typeof t&&D(),this instanceof L?C(this,t):K())}function N(t,e){this._instanceConstructor=t,this.promise=new t(p),this.promise[rt]||k(this.promise),I(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?S(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&S(this.promise,this._result))):j(this.promise,U())}function U(){return new Error("Array Methods must be provided an Array")}function W(){var t;if("undefined"!=typeof global)t=global;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var n=t.Promise;(!n||"[object Promise]"!==Object.prototype.toString.call(n.resolve())||n.cast)&&(t.Promise=pt)}var z;z=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var B,G,H,I=z,J=0,Q=function(t,e){tt[J]=t,tt[J+1]=e,J+=2,2===J&&(G?G(a):H())},R="undefined"!=typeof window?window:void 0,V=R||{},X=V.MutationObserver||V.WebKitMutationObserver,Z="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),$="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,tt=new Array(1e3);H=Z?o():X?s():$?u():void 0===R&&"function"==typeof require?f():c();var et=l,nt=h,rt=Math.random().toString(36).substring(16),ot=void 0,it=1,st=2,ut=new M,ct=new M,at=0,ft=Y,lt=q,ht=F,pt=L;L.all=ft,L.race=lt,L.resolve=nt,L.reject=ht,L._setScheduler=n,L._setAsap=r,L._asap=Q,L.prototype={constructor:L,then:et,"catch":function(t){return this.then(null,t)}};var _t=N;N.prototype._enumerate=function(){for(var t=this.length,e=this._input,n=0;this._state===ot&&t>n;n++)this._eachEntry(e[n],n)},N.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,r=n.resolve;if(r===nt){var o=v(t);if(o===et&&t._state!==ot)this._settledAt(t._state,e,t._result);else if("function"!=typeof o)this._remaining--,this._result[e]=t;else if(n===pt){var i=new n(p);w(i,t,o),this._willSettleAt(i,e)}else this._willSettleAt(new n(function(e){e(t)}),e)}else this._willSettleAt(r(t),e)},N.prototype._settledAt=function(t,e,n){var r=this.promise;r._state===ot&&(this._remaining--,t===st?j(r,n):this._result[e]=n),0===this._remaining&&S(r,this._result)},N.prototype._willSettleAt=function(t,e){var n=this;E(t,void 0,function(t){n._settledAt(it,e,t)},function(t){n._settledAt(st,e,t)})};var dt=W,vt={Promise:pt,polyfill:dt};"function"==typeof define&&define.amd?define(function(){return vt}):"undefined"!=typeof module&&module.exports?module.exports=vt:"undefined"!=typeof this&&(this.ES6Promise=vt),dt()}).call(this); \ No newline at end of file diff --git a/app/node_modules/es6-promise/lib/es6-promise.umd.js b/app/node_modules/es6-promise/lib/es6-promise.umd.js new file mode 100644 index 0000000..5984f70 --- /dev/null +++ b/app/node_modules/es6-promise/lib/es6-promise.umd.js @@ -0,0 +1,18 @@ +import Promise from './es6-promise/promise'; +import polyfill from './es6-promise/polyfill'; + +var ES6Promise = { + 'Promise': Promise, + 'polyfill': polyfill +}; + +/* global define:true module:true window: true */ +if (typeof define === 'function' && define['amd']) { + define(function() { return ES6Promise; }); +} else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = ES6Promise; +} else if (typeof this !== 'undefined') { + this['ES6Promise'] = ES6Promise; +} + +polyfill(); diff --git a/app/node_modules/es6-promise/lib/es6-promise/-internal.js b/app/node_modules/es6-promise/lib/es6-promise/-internal.js new file mode 100644 index 0000000..aeebf57 --- /dev/null +++ b/app/node_modules/es6-promise/lib/es6-promise/-internal.js @@ -0,0 +1,273 @@ +import { + objectOrFunction, + isFunction +} from './utils'; + +import { + asap +} from './asap'; + +import originalThen from './then'; +import originalResolve from './promise/resolve'; + +export var PROMISE_ID = Math.random().toString(36).substring(16); + +function noop() {} + +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; + +var GET_THEN_ERROR = new ErrorObject(); + +function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} + +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} + +function getThen(promise) { + try { + return promise.then; + } catch(error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} + +function tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } +} + +function handleForeignThenable(promise, thenable, then) { + asap(function(promise) { + var sealed = false; + var error = tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + resolve(promise, value); + } else { + fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + reject(promise, error); + } + }, promise); +} + +function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function(value) { + resolve(promise, value); + }, function(reason) { + reject(promise, reason); + }); + } +} + +function handleMaybeThenable(promise, maybeThenable, then) { + if (maybeThenable.constructor === promise.constructor && + then === originalThen && + constructor.resolve === originalResolve) { + handleOwnThenable(promise, maybeThenable); + } else { + if (then === GET_THEN_ERROR) { + reject(promise, GET_THEN_ERROR.error); + } else if (then === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then)) { + handleForeignThenable(promise, maybeThenable, then); + } else { + fulfill(promise, maybeThenable); + } + } +} + +function resolve(promise, value) { + if (promise === value) { + reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } +} + +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + publish(promise); +} + +function fulfill(promise, value) { + if (promise._state !== PENDING) { return; } + + promise._result = value; + promise._state = FULFILLED; + + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} + +function reject(promise, reason) { + if (promise._state !== PENDING) { return; } + promise._state = REJECTED; + promise._result = reason; + + asap(publishRejection, promise); +} + +function subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + FULFILLED] = onFulfillment; + subscribers[length + REJECTED] = onRejection; + + if (length === 0 && parent._state) { + asap(publish, parent); + } +} + +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; +} + +function ErrorObject() { + this.error = null; +} + +var TRY_CATCH_ERROR = new ErrorObject(); + +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} + +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = tryCatch(callback, detail); + + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + reject(promise, cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + resolve(promise, value); + } else if (failed) { + reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + reject(promise, value); + } +} + +function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + resolve(promise, value); + }, function rejectPromise(reason) { + reject(promise, reason); + }); + } catch(e) { + reject(promise, e); + } +} + +var id = 0; +function nextId() { + return id++; +} + +function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; +} + +export { + nextId, + makePromise, + getThen, + noop, + resolve, + reject, + fulfill, + subscribe, + publish, + publishRejection, + initializePromise, + invokeCallback, + FULFILLED, + REJECTED, + PENDING, + handleMaybeThenable +}; diff --git a/app/node_modules/es6-promise/lib/es6-promise/asap.js b/app/node_modules/es6-promise/lib/es6-promise/asap.js new file mode 100644 index 0000000..40f1d25 --- /dev/null +++ b/app/node_modules/es6-promise/lib/es6-promise/asap.js @@ -0,0 +1,119 @@ +var len = 0; +var vertxNext; +var customSchedulerFn; + +export var asap = function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (customSchedulerFn) { + customSchedulerFn(flush); + } else { + scheduleFlush(); + } + } +} + +export function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; +} + +export function setAsap(asapFn) { + asap = asapFn; +} + +var browserWindow = (typeof window !== 'undefined') ? window : undefined; +var browserGlobal = browserWindow || {}; +var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; +var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + +// node +function useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function() { + process.nextTick(flush); + }; +} + +// vertx +function useVertxTimer() { + return function() { + vertxNext(flush); + }; +} + +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; +} + +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + channel.port2.postMessage(0); + }; +} + +function useSetTimeout() { + return function() { + setTimeout(flush, 1); + }; +} + +var queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i+=2) { + var callback = queue[i]; + var arg = queue[i+1]; + + callback(arg); + + queue[i] = undefined; + queue[i+1] = undefined; + } + + len = 0; +} + +function attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch(e) { + return useSetTimeout(); + } +} + +var scheduleFlush; +// Decide what async method to use to triggering processing of queued callbacks: +if (isNode) { + scheduleFlush = useNextTick(); +} else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); +} else if (isWorker) { + scheduleFlush = useMessageChannel(); +} else if (browserWindow === undefined && typeof require === 'function') { + scheduleFlush = attemptVertx(); +} else { + scheduleFlush = useSetTimeout(); +} diff --git a/app/node_modules/es6-promise/lib/es6-promise/enumerator.js b/app/node_modules/es6-promise/lib/es6-promise/enumerator.js new file mode 100644 index 0000000..2a7a28f --- /dev/null +++ b/app/node_modules/es6-promise/lib/es6-promise/enumerator.js @@ -0,0 +1,118 @@ +import { + isArray, + isMaybeThenable +} from './utils'; + +import { + noop, + reject, + fulfill, + subscribe, + FULFILLED, + REJECTED, + PENDING, + getThen, + handleMaybeThenable +} from './-internal'; + +import then from './then'; +import Promise from './promise'; +import originalResolve from './promise/resolve'; +import originalThen from './then'; +import { makePromise, PROMISE_ID } from './-internal'; + +export default Enumerator; +function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); + + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } + + if (isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; + + this._result = new Array(this.length); + + if (this.length === 0) { + fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + } + } else { + reject(this.promise, validationError()); + } +} + +function validationError() { + return new Error('Array Methods must be provided an Array'); +}; + +Enumerator.prototype._enumerate = function() { + var length = this.length; + var input = this._input; + + for (var i = 0; this._state === PENDING && i < length; i++) { + this._eachEntry(input[i], i); + } +}; + +Enumerator.prototype._eachEntry = function(entry, i) { + var c = this._instanceConstructor; + var resolve = c.resolve; + + if (resolve === originalResolve) { + var then = getThen(entry); + + if (then === originalThen && + entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === Promise) { + var promise = new c(noop); + handleMaybeThenable(promise, entry, then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function(resolve) { resolve(entry); }), i); + } + } else { + this._willSettleAt(resolve(entry), i); + } +}; + +Enumerator.prototype._settledAt = function(state, i, value) { + var promise = this.promise; + + if (promise._state === PENDING) { + this._remaining--; + + if (state === REJECTED) { + reject(promise, value); + } else { + this._result[i] = value; + } + } + + if (this._remaining === 0) { + fulfill(promise, this._result); + } +}; + +Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + subscribe(promise, undefined, function(value) { + enumerator._settledAt(FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(REJECTED, i, reason); + }); +}; diff --git a/app/node_modules/es6-promise/lib/es6-promise/polyfill.js b/app/node_modules/es6-promise/lib/es6-promise/polyfill.js new file mode 100644 index 0000000..6696dfc --- /dev/null +++ b/app/node_modules/es6-promise/lib/es6-promise/polyfill.js @@ -0,0 +1,26 @@ +/*global self*/ +import Promise from './promise'; + +export default function polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = Promise; +} diff --git a/app/node_modules/es6-promise/lib/es6-promise/promise.js b/app/node_modules/es6-promise/lib/es6-promise/promise.js new file mode 100644 index 0000000..d95951e --- /dev/null +++ b/app/node_modules/es6-promise/lib/es6-promise/promise.js @@ -0,0 +1,384 @@ +import { + isFunction +} from './utils'; + +import { + noop, + nextId, + PROMISE_ID, + initializePromise +} from './-internal'; + +import { + asap, + setAsap, + setScheduler +} from './asap'; + +import all from './promise/all'; +import race from './promise/race'; +import Resolve from './promise/resolve'; +import Reject from './promise/reject'; +import then from './then'; + + +function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); +} + +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} + +export default Promise; +/** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor +*/ +function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } +} + +Promise.all = all; +Promise.race = race; +Promise.resolve = Resolve; +Promise.reject = Reject; +Promise._setScheduler = setScheduler; +Promise._setAsap = setAsap; +Promise._asap = asap; + +Promise.prototype = { + constructor: Promise, + +/** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} +*/ + then: then, + +/** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} +*/ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } +}; diff --git a/app/node_modules/es6-promise/lib/es6-promise/promise/all.js b/app/node_modules/es6-promise/lib/es6-promise/promise/all.js new file mode 100644 index 0000000..03033f0 --- /dev/null +++ b/app/node_modules/es6-promise/lib/es6-promise/promise/all.js @@ -0,0 +1,52 @@ +import Enumerator from '../enumerator'; + +/** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + var promise1 = resolve(1); + var promise2 = resolve(2); + var promise3 = resolve(3); + var promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + var promise1 = resolve(1); + var promise2 = reject(new Error("2")); + var promise3 = reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ +export default function all(entries) { + return new Enumerator(this, entries).promise; +} diff --git a/app/node_modules/es6-promise/lib/es6-promise/promise/race.js b/app/node_modules/es6-promise/lib/es6-promise/promise/race.js new file mode 100644 index 0000000..8c922e3 --- /dev/null +++ b/app/node_modules/es6-promise/lib/es6-promise/promise/race.js @@ -0,0 +1,86 @@ +import { + isArray +} from "../utils"; + +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + var promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + var promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + var promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + var promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ +export default function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!isArray(entries)) { + return new Constructor(function(resolve, reject) { + reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function(resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } +} diff --git a/app/node_modules/es6-promise/lib/es6-promise/promise/reject.js b/app/node_modules/es6-promise/lib/es6-promise/promise/reject.js new file mode 100644 index 0000000..63b86cb --- /dev/null +++ b/app/node_modules/es6-promise/lib/es6-promise/promise/reject.js @@ -0,0 +1,46 @@ +import { + noop, + reject as _reject +} from '../-internal'; + +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + var promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +export default function reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + _reject(promise, reason); + return promise; +} diff --git a/app/node_modules/es6-promise/lib/es6-promise/promise/resolve.js b/app/node_modules/es6-promise/lib/es6-promise/promise/resolve.js new file mode 100644 index 0000000..201a545 --- /dev/null +++ b/app/node_modules/es6-promise/lib/es6-promise/promise/resolve.js @@ -0,0 +1,48 @@ +import { + noop, + resolve as _resolve +} from '../-internal'; + +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + var promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +export default function resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} diff --git a/app/node_modules/es6-promise/lib/es6-promise/then.js b/app/node_modules/es6-promise/lib/es6-promise/then.js new file mode 100644 index 0000000..f97e946 --- /dev/null +++ b/app/node_modules/es6-promise/lib/es6-promise/then.js @@ -0,0 +1,34 @@ +import { + invokeCallback, + subscribe, + FULFILLED, + REJECTED, + noop, + makePromise, + PROMISE_ID +} from './-internal'; + +import { asap } from './asap'; + +export default function then(onFulfillment, onRejection) { + var parent = this; + + var child = new this.constructor(noop); + + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } + + var state = parent._state; + + if (state) { + var callback = arguments[state - 1]; + asap(function(){ + invokeCallback(state, child, callback, parent._result); + }); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + + return child; +} diff --git a/app/node_modules/es6-promise/lib/es6-promise/utils.js b/app/node_modules/es6-promise/lib/es6-promise/utils.js new file mode 100644 index 0000000..31ec6f9 --- /dev/null +++ b/app/node_modules/es6-promise/lib/es6-promise/utils.js @@ -0,0 +1,22 @@ +export function objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); +} + +export function isFunction(x) { + return typeof x === 'function'; +} + +export function isMaybeThenable(x) { + return typeof x === 'object' && x !== null; +} + +var _isArray; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} + +export var isArray = _isArray; diff --git a/app/node_modules/es6-promise/package.json b/app/node_modules/es6-promise/package.json new file mode 100644 index 0000000..8236b42 --- /dev/null +++ b/app/node_modules/es6-promise/package.json @@ -0,0 +1,62 @@ +{ + "name": "es6-promise", + "namespace": "es6-promise", + "version": "3.2.1", + "description": "A lightweight library that provides tools for organizing asynchronous code", + "main": "dist/es6-promise.js", + "directories": { + "lib": "lib" + }, + "files": [ + "dist", + "lib", + "!dist/test" + ], + "devDependencies": { + "babel-eslint": "^6.0.0", + "broccoli-es6-module-transpiler": "^0.5.0", + "broccoli-jshint": "^2.1.0", + "broccoli-merge-trees": "^1.1.1", + "broccoli-replace": "^0.12.0", + "broccoli-stew": "^1.2.0", + "broccoli-uglify-js": "^0.1.3", + "broccoli-watchify": "^0.2.0", + "ember-cli": "2.5.0", + "ember-publisher": "0.0.7", + "git-repo-version": "0.0.3", + "json3": "^3.3.2", + "mocha": "^1.20.1", + "promises-aplus-tests-phantom": "^2.1.0-revise", + "release-it": "0.0.10" + }, + "scripts": { + "build": "ember build", + "build:production": "ember build --environment production", + "start": "ember s", + "test": "ember test", + "test:server": "ember test --server", + "test:node": "ember build && mocha ./dist/test/browserify", + "lint": "jshint lib", + "prepublish": "ember build --environment production", + "dry-run-release": "ember build --environment production && release-it --dry-run --non-interactive" + }, + "repository": { + "type": "git", + "url": "git://github.com/jakearchibald/ES6-Promises.git" + }, + "bugs": { + "url": "https://github.com/jakearchibald/ES6-Promises/issues" + }, + "browser": { + "vertx": false + }, + "keywords": [ + "promises", + "futures" + ], + "author": "Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)", + "license": "MIT", + "spm": { + "main": "dist/es6-promise.js" + } +} diff --git a/app/node_modules/escape-html/LICENSE b/app/node_modules/escape-html/LICENSE new file mode 100644 index 0000000..2e70de9 --- /dev/null +++ b/app/node_modules/escape-html/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2013 TJ Holowaychuk +Copyright (c) 2015 Andreas Lubbe +Copyright (c) 2015 Tiancheng "Timothy" Gu + +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/app/node_modules/escape-html/Readme.md b/app/node_modules/escape-html/Readme.md new file mode 100644 index 0000000..653d9ea --- /dev/null +++ b/app/node_modules/escape-html/Readme.md @@ -0,0 +1,43 @@ + +# escape-html + + Escape string for use in HTML + +## Example + +```js +var escape = require('escape-html'); +var html = escape('foo & bar'); +// -> foo & bar +``` + +## Benchmark + +``` +$ npm run-script bench + +> escape-html@1.0.3 bench nodejs-escape-html +> node benchmark/index.js + + + http_parser@1.0 + node@0.10.33 + v8@3.14.5.9 + ares@1.9.0-DEV + uv@0.10.29 + zlib@1.2.3 + modules@11 + openssl@1.0.1j + + 1 test completed. + 2 tests completed. + 3 tests completed. + + no special characters x 19,435,271 ops/sec ±0.85% (187 runs sampled) + single special character x 6,132,421 ops/sec ±0.67% (194 runs sampled) + many special characters x 3,175,826 ops/sec ±0.65% (193 runs sampled) +``` + +## License + + MIT \ No newline at end of file diff --git a/app/node_modules/escape-html/index.js b/app/node_modules/escape-html/index.js new file mode 100644 index 0000000..bf9e226 --- /dev/null +++ b/app/node_modules/escape-html/index.js @@ -0,0 +1,78 @@ +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ + +'use strict'; + +/** + * Module variables. + * @private + */ + +var matchHtmlRegExp = /["'&<>]/; + +/** + * Module exports. + * @public + */ + +module.exports = escapeHtml; + +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ + +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} diff --git a/app/node_modules/escape-html/package.json b/app/node_modules/escape-html/package.json new file mode 100644 index 0000000..57ec7bd --- /dev/null +++ b/app/node_modules/escape-html/package.json @@ -0,0 +1,24 @@ +{ + "name": "escape-html", + "description": "Escape string for use in HTML", + "version": "1.0.3", + "license": "MIT", + "keywords": [ + "escape", + "html", + "utility" + ], + "repository": "component/escape-html", + "devDependencies": { + "benchmark": "1.0.0", + "beautify-benchmark": "0.2.4" + }, + "files": [ + "LICENSE", + "Readme.md", + "index.js" + ], + "scripts": { + "bench": "node benchmark/index.js" + } +} diff --git a/app/node_modules/etag/HISTORY.md b/app/node_modules/etag/HISTORY.md new file mode 100644 index 0000000..222b293 --- /dev/null +++ b/app/node_modules/etag/HISTORY.md @@ -0,0 +1,83 @@ +1.8.1 / 2017-09-12 +================== + + * perf: replace regular expression with substring + +1.8.0 / 2017-02-18 +================== + + * Use SHA1 instead of MD5 for ETag hashing + - Improves performance for larger entities + - Works with FIPS 140-2 OpenSSL configuration + +1.7.0 / 2015-06-08 +================== + + * Always include entity length in ETags for hash length extensions + * Generate non-Stats ETags using MD5 only (no longer CRC32) + * Improve stat performance by removing hashing + * Remove base64 padding in ETags to shorten + * Use MD5 instead of MD4 in weak ETags over 1KB + +1.6.0 / 2015-05-10 +================== + + * Improve support for JXcore + * Remove requirement of `atime` in the stats object + * Support "fake" stats objects in environments without `fs` + +1.5.1 / 2014-11-19 +================== + + * deps: crc@3.2.1 + - Minor fixes + +1.5.0 / 2014-10-14 +================== + + * Improve string performance + * Slightly improve speed for weak ETags over 1KB + +1.4.0 / 2014-09-21 +================== + + * Support "fake" stats objects + * Support Node.js 0.6 + +1.3.1 / 2014-09-14 +================== + + * Use the (new and improved) `crc` for crc32 + +1.3.0 / 2014-08-29 +================== + + * Default strings to strong ETags + * Improve speed for weak ETags over 1KB + +1.2.1 / 2014-08-29 +================== + + * Use the (much faster) `buffer-crc32` for crc32 + +1.2.0 / 2014-08-24 +================== + + * Add support for file stat objects + +1.1.0 / 2014-08-24 +================== + + * Add fast-path for empty entity + * Add weak ETag generation + * Shrink size of generated ETags + +1.0.1 / 2014-08-24 +================== + + * Fix behavior of string containing Unicode + +1.0.0 / 2014-05-18 +================== + + * Initial release diff --git a/app/node_modules/etag/LICENSE b/app/node_modules/etag/LICENSE new file mode 100644 index 0000000..cab251c --- /dev/null +++ b/app/node_modules/etag/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 Douglas Christopher Wilson + +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/app/node_modules/etag/README.md b/app/node_modules/etag/README.md new file mode 100644 index 0000000..09c2169 --- /dev/null +++ b/app/node_modules/etag/README.md @@ -0,0 +1,159 @@ +# etag + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create simple HTTP ETags + +This module generates HTTP ETags (as defined in RFC 7232) for use in +HTTP responses. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install etag +``` + +## API + + + +```js +var etag = require('etag') +``` + +### etag(entity, [options]) + +Generate a strong ETag for the given entity. This should be the complete +body of the entity. Strings, `Buffer`s, and `fs.Stats` are accepted. By +default, a strong ETag is generated except for `fs.Stats`, which will +generate a weak ETag (this can be overwritten by `options.weak`). + + + +```js +res.setHeader('ETag', etag(body)) +``` + +#### Options + +`etag` accepts these properties in the options object. + +##### weak + +Specifies if the generated ETag will include the weak validator mark (that +is, the leading `W/`). The actual entity tag is the same. The default value +is `false`, unless the `entity` is `fs.Stats`, in which case it is `true`. + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +```bash +$ npm run-script bench + +> etag@1.8.1 bench nodejs-etag +> node benchmark/index.js + + http_parser@2.7.0 + node@6.11.1 + v8@5.1.281.103 + uv@1.11.0 + zlib@1.2.11 + ares@1.10.1-DEV + icu@58.2 + modules@48 + openssl@1.0.2k + +> node benchmark/body0-100b.js + + 100B body + + 4 tests completed. + + buffer - strong x 258,647 ops/sec ±1.07% (180 runs sampled) + buffer - weak x 263,812 ops/sec ±0.61% (184 runs sampled) + string - strong x 259,955 ops/sec ±1.19% (185 runs sampled) + string - weak x 264,356 ops/sec ±1.09% (184 runs sampled) + +> node benchmark/body1-1kb.js + + 1KB body + + 4 tests completed. + + buffer - strong x 189,018 ops/sec ±1.12% (182 runs sampled) + buffer - weak x 190,586 ops/sec ±0.81% (186 runs sampled) + string - strong x 144,272 ops/sec ±0.96% (188 runs sampled) + string - weak x 145,380 ops/sec ±1.43% (187 runs sampled) + +> node benchmark/body2-5kb.js + + 5KB body + + 4 tests completed. + + buffer - strong x 92,435 ops/sec ±0.42% (188 runs sampled) + buffer - weak x 92,373 ops/sec ±0.58% (189 runs sampled) + string - strong x 48,850 ops/sec ±0.56% (186 runs sampled) + string - weak x 49,380 ops/sec ±0.56% (190 runs sampled) + +> node benchmark/body3-10kb.js + + 10KB body + + 4 tests completed. + + buffer - strong x 55,989 ops/sec ±0.93% (188 runs sampled) + buffer - weak x 56,148 ops/sec ±0.55% (190 runs sampled) + string - strong x 27,345 ops/sec ±0.43% (188 runs sampled) + string - weak x 27,496 ops/sec ±0.45% (190 runs sampled) + +> node benchmark/body4-100kb.js + + 100KB body + + 4 tests completed. + + buffer - strong x 7,083 ops/sec ±0.22% (190 runs sampled) + buffer - weak x 7,115 ops/sec ±0.26% (191 runs sampled) + string - strong x 3,068 ops/sec ±0.34% (190 runs sampled) + string - weak x 3,096 ops/sec ±0.35% (190 runs sampled) + +> node benchmark/stats.js + + stat + + 4 tests completed. + + real - strong x 871,642 ops/sec ±0.34% (189 runs sampled) + real - weak x 867,613 ops/sec ±0.39% (190 runs sampled) + fake - strong x 401,051 ops/sec ±0.40% (189 runs sampled) + fake - weak x 400,100 ops/sec ±0.47% (188 runs sampled) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/etag.svg +[npm-url]: https://npmjs.org/package/etag +[node-version-image]: https://img.shields.io/node/v/etag.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/etag/master.svg +[travis-url]: https://travis-ci.org/jshttp/etag +[coveralls-image]: https://img.shields.io/coveralls/jshttp/etag/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master +[downloads-image]: https://img.shields.io/npm/dm/etag.svg +[downloads-url]: https://npmjs.org/package/etag diff --git a/app/node_modules/etag/index.js b/app/node_modules/etag/index.js new file mode 100644 index 0000000..2a585c9 --- /dev/null +++ b/app/node_modules/etag/index.js @@ -0,0 +1,131 @@ +/*! + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = etag + +/** + * Module dependencies. + * @private + */ + +var crypto = require('crypto') +var Stats = require('fs').Stats + +/** + * Module variables. + * @private + */ + +var toString = Object.prototype.toString + +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } + + // compute hash of entity + var hash = crypto + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27) + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } + + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + return obj && typeof obj === 'object' && + 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && + 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && + 'ino' in obj && typeof obj.ino === 'number' && + 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) + + return '"' + size + '-' + mtime + '"' +} diff --git a/app/node_modules/etag/package.json b/app/node_modules/etag/package.json new file mode 100644 index 0000000..b06ab80 --- /dev/null +++ b/app/node_modules/etag/package.json @@ -0,0 +1,47 @@ +{ + "name": "etag", + "description": "Create simple HTTP ETags", + "version": "1.8.1", + "contributors": [ + "Douglas Christopher Wilson ", + "David Björklund " + ], + "license": "MIT", + "keywords": [ + "etag", + "http", + "res" + ], + "repository": "jshttp/etag", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5", + "safe-buffer": "5.1.1", + "seedrandom": "2.4.3" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/app/node_modules/express/History.md b/app/node_modules/express/History.md new file mode 100644 index 0000000..2f6eab1 --- /dev/null +++ b/app/node_modules/express/History.md @@ -0,0 +1,3421 @@ +4.16.4 / 2018-10-10 +=================== + + * Fix issue where `"Request aborted"` may be logged in `res.sendfile` + * Fix JSDoc for `Router` constructor + * deps: body-parser@1.18.3 + - Fix deprecation warnings on Node.js 10+ + - Fix stack trace for strict json parse error + - deps: depd@~1.1.2 + - deps: http-errors@~1.6.3 + - deps: iconv-lite@0.4.23 + - deps: qs@6.5.2 + - deps: raw-body@2.3.3 + - deps: type-is@~1.6.16 + * deps: proxy-addr@~2.0.4 + - deps: ipaddr.js@1.8.0 + * deps: qs@6.5.2 + * deps: safe-buffer@5.1.2 + +4.16.3 / 2018-03-12 +=================== + + * deps: accepts@~1.3.5 + - deps: mime-types@~2.1.18 + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: finalhandler@1.1.1 + - Fix 404 output for bad / missing pathnames + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + * deps: proxy-addr@~2.0.3 + - deps: ipaddr.js@1.6.0 + * deps: send@0.16.2 + - Fix incorrect end tag in default error & redirects + - deps: depd@~1.1.2 + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + * deps: serve-static@1.13.2 + - Fix incorrect end tag in redirects + - deps: encodeurl@~1.0.2 + - deps: send@0.16.2 + * deps: statuses@~1.4.0 + * deps: type-is@~1.6.16 + - deps: mime-types@~2.1.18 + +4.16.2 / 2017-10-09 +=================== + + * Fix `TypeError` in `res.send` when given `Buffer` and `ETag` header set + * perf: skip parsing of entire `X-Forwarded-Proto` header + +4.16.1 / 2017-09-29 +=================== + + * deps: send@0.16.1 + * deps: serve-static@1.13.1 + - Fix regression when `root` is incorrectly set to a file + - deps: send@0.16.1 + +4.16.0 / 2017-09-28 +=================== + + * Add `"json escape"` setting for `res.json` and `res.jsonp` + * Add `express.json` and `express.urlencoded` to parse bodies + * Add `options` argument to `res.download` + * Improve error message when autoloading invalid view engine + * Improve error messages when non-function provided as middleware + * Skip `Buffer` encoding when not generating ETag for small response + * Use `safe-buffer` for improved Buffer API + * deps: accepts@~1.3.4 + - deps: mime-types@~2.1.16 + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: etag@~1.8.1 + - perf: replace regular expression with substring + * deps: finalhandler@1.1.0 + - Use `res.headersSent` when available + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + * deps: proxy-addr@~2.0.2 + - Fix trimming leading / trailing OWS in `X-Forwarded-For` + - deps: forwarded@~0.1.2 + - deps: ipaddr.js@1.5.2 + - perf: reduce overhead when no `X-Forwarded-For` header + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: send@0.16.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Fix missing `` in default error & redirects + - Set charset as "UTF-8" for .js and .json + - Use instance methods on steam to check for listeners + - deps: mime@1.4.1 + - perf: improve path validation speed + * deps: serve-static@1.13.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Set charset as "UTF-8" for .js and .json + - deps: send@0.16.0 + * deps: setprototypeof@1.1.0 + * deps: utils-merge@1.0.1 + * deps: vary@~1.1.2 + - perf: improve header token parsing speed + * perf: re-use options object when generating ETags + * perf: remove dead `.charset` set in `res.jsonp` + +4.15.5 / 2017-09-24 +=================== + + * deps: debug@2.6.9 + * deps: finalhandler@~1.0.6 + - deps: debug@2.6.9 + - deps: parseurl@~1.3.2 + * deps: fresh@0.5.2 + - Fix handling of modified headers with invalid dates + - perf: improve ETag match loop + - perf: improve `If-None-Match` token parsing + * deps: send@0.15.6 + - Fix handling of modified headers with invalid dates + - deps: debug@2.6.9 + - deps: etag@~1.8.1 + - deps: fresh@0.5.2 + - perf: improve `If-Match` token parsing + * deps: serve-static@1.12.6 + - deps: parseurl@~1.3.2 + - deps: send@0.15.6 + - perf: improve slash collapsing + +4.15.4 / 2017-08-06 +=================== + + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: finalhandler@~1.0.4 + - deps: debug@2.6.8 + * deps: proxy-addr@~1.1.5 + - Fix array argument being altered + - deps: ipaddr.js@1.4.0 + * deps: qs@6.5.0 + * deps: send@0.15.4 + - deps: debug@2.6.8 + - deps: depd@~1.1.1 + - deps: http-errors@~1.6.2 + * deps: serve-static@1.12.4 + - deps: send@0.15.4 + +4.15.3 / 2017-05-16 +=================== + + * Fix error when `res.set` cannot add charset to `Content-Type` + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: finalhandler@~1.0.3 + - Fix missing `` in HTML document + - deps: debug@2.6.7 + * deps: proxy-addr@~1.1.4 + - deps: ipaddr.js@1.3.0 + * deps: send@0.15.3 + - deps: debug@2.6.7 + - deps: ms@2.0.0 + * deps: serve-static@1.12.3 + - deps: send@0.15.3 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + * deps: vary@~1.1.1 + - perf: hoist regular expression + +4.15.2 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +4.15.1 / 2017-03-05 +=================== + + * deps: send@0.15.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - Fix strict violation in broken environments + * deps: serve-static@1.12.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - deps: send@0.15.1 + +4.15.0 / 2017-03-01 +=================== + + * Add debug message when loading view engine + * Add `next("router")` to exit from router + * Fix case where `router.use` skipped requests routes did not + * Remove usage of `res._headers` private field + - Improves compatibility with Node.js 8 nightly + * Skip routing when `req.url` is not set + * Use `%o` in path debug to tell types apart + * Use `Object.create` to setup request & response prototypes + * Use `setprototypeof` module to replace `__proto__` setting + * Use `statuses` instead of `http` module for status messages + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: etag@~1.8.0 + - Use SHA1 instead of MD5 for ETag hashing + - Works with FIPS 140-2 OpenSSL configuration + * deps: finalhandler@~1.0.0 + - Fix exception when `err` cannot be converted to a string + - Fully URL-encode the pathname in the 404 + - Only include the pathname in the 404 message + - Send complete HTML document + - Set `Content-Security-Policy: default-src 'self'` header + - deps: debug@2.6.1 + * deps: fresh@0.5.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - perf: delay reading header values until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove duplicate conditional + - perf: remove unnecessary boolean coercions + - perf: skip checking modified time if ETag check failed + - perf: skip parsing `If-None-Match` when no `ETag` header + - perf: use `Date.parse` instead of `new Date` + * deps: qs@6.3.1 + - Fix array parsing from skipping empty values + - Fix compacting nested arrays + * deps: send@0.15.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: debug@2.6.1 + - deps: etag@~1.8.0 + - deps: fresh@0.5.0 + - deps: http-errors@~1.6.1 + * deps: serve-static@1.12.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Send complete HTML document in redirect response + - Set default CSP header in redirect response + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: send@0.15.0 + * perf: add fast match path for `*` route + * perf: improve `req.ips` performance + +4.14.1 / 2017-01-28 +=================== + + * deps: content-disposition@0.5.2 + * deps: finalhandler@0.5.1 + - Fix exception when `err.headers` is not an object + - deps: statuses@~1.3.1 + - perf: hoist regular expressions + - perf: remove duplicate validation path + * deps: proxy-addr@~1.1.3 + - deps: ipaddr.js@1.2.0 + * deps: send@0.14.2 + - deps: http-errors@~1.5.1 + - deps: ms@0.7.2 + - deps: statuses@~1.3.1 + * deps: serve-static@~1.11.2 + - deps: send@0.14.2 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +4.14.0 / 2016-06-16 +=================== + + * Add `acceptRanges` option to `res.sendFile`/`res.sendfile` + * Add `cacheControl` option to `res.sendFile`/`res.sendfile` + * Add `options` argument to `req.range` + - Includes the `combine` option + * Encode URL in `res.location`/`res.redirect` if not already encoded + * Fix some redirect handling in `res.sendFile`/`res.sendfile` + * Fix Windows absolute path check using forward slashes + * Improve error with invalid arguments to `req.get()` + * Improve performance for `res.json`/`res.jsonp` in most cases + * Improve `Range` header handling in `res.sendFile`/`res.sendfile` + * deps: accepts@~1.3.3 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Many performance improvments + - deps: mime-types@~2.1.11 + - deps: negotiator@0.6.1 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: cookie@0.3.1 + - Add `sameSite` option + - Fix cookie `Max-Age` to never be a floating point number + - Improve error message when `encode` is not a function + - Improve error message when `expires` is not a `Date` + - Throw better error for invalid argument to parse + - Throw on invalid values provided to `serialize` + - perf: enable strict mode + - perf: hoist regular expression + - perf: use for loop in parse + - perf: use string concatination for serialization + * deps: finalhandler@0.5.0 + - Change invalid or non-numeric status code to 500 + - Overwrite status message to match set status code + - Prefer `err.statusCode` if `err.status` is invalid + - Set response headers from `err.headers` object + - Use `statuses` instead of `http` module for status messages + * deps: proxy-addr@~1.1.2 + - Fix accepting various invalid netmasks + - Fix IPv6-mapped IPv4 validation edge cases + - IPv4 netmasks must be contingous + - IPv6 addresses cannot be used as a netmask + - deps: ipaddr.js@1.1.1 + * deps: qs@6.2.0 + - Add `decoder` option in `parse` function + * deps: range-parser@~1.2.0 + - Add `combine` option to combine overlapping ranges + - Fix incorrectly returning -1 when there is at least one valid range + - perf: remove internal function + * deps: send@0.14.1 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Correctly inherit from `Stream` class + - Fix `Content-Range` header in 416 responses when using `start`/`end` options + - Fix `Content-Range` header missing from default 416 responses + - Fix redirect error when `path` contains raw non-URL characters + - Fix redirect when `path` starts with multiple forward slashes + - Ignore non-byte `Range` headers + - deps: http-errors@~1.5.0 + - deps: range-parser@~1.2.0 + - deps: statuses@~1.3.0 + - perf: remove argument reassignment + * deps: serve-static@~1.11.1 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Fix redirect error when `req.url` contains raw non-URL characters + - Ignore non-byte `Range` headers + - Use status code 301 for redirects + - deps: send@0.14.1 + * deps: type-is@~1.6.13 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.11 + * deps: vary@~1.1.0 + - Only accept valid field names in the `field` argument + * perf: use strict equality when possible + +4.13.4 / 2016-01-21 +=================== + + * deps: content-disposition@0.5.1 + - perf: enable strict mode + * deps: cookie@0.1.5 + - Throw on invalid values provided to `serialize` + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: finalhandler@0.4.1 + - deps: escape-html@~1.0.3 + * deps: merge-descriptors@1.0.1 + - perf: enable strict mode + * deps: methods@~1.1.2 + - perf: enable strict mode + * deps: parseurl@~1.3.1 + - perf: enable strict mode + * deps: proxy-addr@~1.0.10 + - deps: ipaddr.js@1.0.5 + - perf: enable strict mode + * deps: range-parser@~1.0.3 + - perf: enable strict mode + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + * deps: serve-static@~1.10.2 + - deps: escape-html@~1.0.3 + - deps: parseurl@~1.3.0 + - deps: send@0.13.1 + +4.13.3 / 2015-08-02 +=================== + + * Fix infinite loop condition using `mergeParams: true` + * Fix inner numeric indices incorrectly altering parent `req.params` + +4.13.2 / 2015-07-31 +=================== + + * deps: accepts@~1.2.12 + - deps: mime-types@~2.1.4 + * deps: array-flatten@1.1.1 + - perf: enable strict mode + * deps: path-to-regexp@0.1.7 + - Fix regression with escaped round brackets and matching groups + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +4.13.1 / 2015-07-05 +=================== + + * deps: accepts@~1.2.10 + - deps: mime-types@~2.1.2 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +4.13.0 / 2015-06-20 +=================== + + * Add settings to debug output + * Fix `res.format` error when only `default` provided + * Fix issue where `next('route')` in `app.param` would incorrectly skip values + * Fix hiding platform issues with `decodeURIComponent` + - Only `URIError`s are a 400 + * Fix using `*` before params in routes + * Fix using capture groups before params in routes + * Simplify `res.cookie` to call `res.append` + * Use `array-flatten` module for flattening arrays + * deps: accepts@~1.2.9 + - deps: mime-types@~2.1.1 + - perf: avoid argument reassignment & argument slice + - perf: avoid negotiator recursive construction + - perf: enable strict mode + - perf: remove unnecessary bitwise operator + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: finalhandler@0.4.0 + - Fix a false-positive when unpiping in Node.js 0.8 + - Support `statusCode` property on `Error` objects + - Use `unpipe` module for unpiping requests + - deps: escape-html@1.0.2 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: path-to-regexp@0.1.6 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * deps: serve-static@~1.10.0 + - Add `fallthrough` option + - Fix reading options from options prototype + - Improve the default redirect response headers + - Malformed URLs now `next()` instead of 400 + - deps: escape-html@1.0.2 + - deps: send@0.13.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: isolate `app.render` try block + * perf: remove argument reassignments in application + * perf: remove argument reassignments in request prototype + * perf: remove argument reassignments in response prototype + * perf: remove argument reassignments in routing + * perf: remove argument reassignments in `View` + * perf: skip attempting to decode zero length string + * perf: use saved reference to `http.STATUS_CODES` + +4.12.4 / 2015-05-17 +=================== + + * deps: accepts@~1.2.7 + - deps: mime-types@~2.0.11 + - deps: negotiator@0.5.3 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: finalhandler@0.3.6 + - deps: debug@~2.2.0 + - deps: on-finished@~2.2.1 + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + * deps: serve-static@~1.9.3 + - deps: send@0.12.3 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +4.12.3 / 2015-03-17 +=================== + + * deps: accepts@~1.2.5 + - deps: mime-types@~2.0.10 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: finalhandler@0.3.4 + - deps: debug@~2.1.3 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + * deps: serve-static@~1.9.2 + - deps: send@0.12.2 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +4.12.2 / 2015-03-02 +=================== + + * Fix regression where `"Request aborted"` is logged using `res.sendFile` + +4.12.1 / 2015-03-01 +=================== + + * Fix constructing application with non-configurable prototype properties + * Fix `ECONNRESET` errors from `res.sendFile` usage + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + * Fix wrong `code` on aborted connections from `res.sendFile` + * deps: merge-descriptors@1.0.0 + +4.12.0 / 2015-02-23 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: accepts@~1.2.4 + - Fix preference sorting to be stable for long acceptable lists + - deps: mime-types@~2.0.9 + - deps: negotiator@0.5.1 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + * deps: serve-static@~1.9.1 + - deps: send@0.12.1 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +4.11.2 / 2015-02-01 +=================== + + * Fix `res.redirect` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.2.3 + - deps: mime-types@~2.0.8 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +4.11.1 / 2015-01-20 +=================== + + * deps: send@0.11.1 + - Fix root path disclosure + * deps: serve-static@~1.8.1 + - Fix redirect loop in Node.js 0.11.14 + - Fix root path disclosure + - deps: send@0.11.1 + +4.11.0 / 2015-01-13 +=================== + + * Add `res.append(field, val)` to append headers + * Deprecate leading `:` in `name` for `app.param(name, fn)` + * Deprecate `req.param()` -- use `req.params`, `req.body`, or `req.query` instead + * Deprecate `app.param(fn)` + * Fix `OPTIONS` responses to include the `HEAD` method properly + * Fix `res.sendFile` not always detecting aborted connection + * Match routes iteratively to prevent stack overflows + * deps: accepts@~1.2.2 + - deps: mime-types@~2.0.7 + - deps: negotiator@0.5.0 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + * deps: serve-static@~1.8.0 + - deps: send@0.11.0 + +4.10.8 / 2015-01-13 +=================== + + * Fix crash from error within `OPTIONS` response handler + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + +4.10.7 / 2015-01-04 +=================== + + * Fix `Allow` header for `OPTIONS` to not contain duplicate methods + * Fix incorrect "Request aborted" for `res.sendFile` when `HEAD` or 304 + * deps: debug@~2.1.1 + * deps: finalhandler@0.3.3 + - deps: debug@~2.1.1 + - deps: on-finished@~2.2.0 + * deps: methods@~1.1.1 + * deps: on-finished@~2.2.0 + * deps: serve-static@~1.7.2 + - Fix potential open redirect when mounted at root + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +4.10.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +4.10.5 / 2014-12-10 +=================== + + * Fix `res.send` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.1.4 + - deps: mime-types@~2.0.4 + * deps: type-is@~1.5.4 + - deps: mime-types@~2.0.4 + +4.10.4 / 2014-11-24 +=================== + + * Fix `res.sendfile` logging standard write errors + +4.10.3 / 2014-11-23 +=================== + + * Fix `res.sendFile` logging standard write errors + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + +4.10.2 / 2014-11-09 +=================== + + * Correctly invoke async router callback asynchronously + * deps: accepts@~1.1.3 + - deps: mime-types@~2.0.3 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +4.10.1 / 2014-10-28 +=================== + + * Fix handling of URLs containing `://` in the path + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +4.10.0 / 2014-10-23 +=================== + + * Add support for `app.set('views', array)` + - Views are looked up in sequence in array of directories + * Fix `res.send(status)` to mention `res.sendStatus(status)` + * Fix handling of invalid empty URLs + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `path.resolve` in view lookup + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + * deps: finalhandler@0.3.2 + - Terminate in progress response only on error + - Use `on-finished` to determine request status + - deps: debug@~2.1.0 + - deps: on-finished@~2.1.1 + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: send@0.10.1 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + - deps: on-finished@~2.1.1 + * deps: serve-static@~1.7.1 + - deps: send@0.10.1 + +4.9.8 / 2014-10-17 +================== + + * Fix `res.redirect` body when redirect status specified + * deps: accepts@~1.1.2 + - Fix error when media type has invalid parameter + - deps: negotiator@0.4.9 + +4.9.7 / 2014-10-10 +================== + + * Fix using same param name in array of paths + +4.9.6 / 2014-10-08 +================== + + * deps: accepts@~1.1.1 + - deps: mime-types@~2.0.2 + - deps: negotiator@0.4.8 + * deps: serve-static@~1.6.4 + - Fix redirect loop when index file serving disabled + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +4.9.5 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + * deps: serve-static@~1.6.3 + - deps: send@0.9.3 + +4.9.4 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +4.9.3 / 2014-09-18 +================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +4.9.2 / 2014-09-17 +================== + + * Fix regression for empty string `path` in `app.use` + * Fix `router.use` to accept array of middleware without path + * Improve error message for bad `app.use` arguments + +4.9.1 / 2014-09-16 +================== + + * Fix `app.use` to accept array of middleware without path + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + * deps: serve-static@~1.6.2 + - deps: send@0.9.2 + +4.9.0 / 2014-09-08 +================== + + * Add `res.sendStatus` + * Invoke callback for sendfile when client aborts + - Applies to `res.sendFile`, `res.sendfile`, and `res.download` + - `err` will be populated with request aborted error + * Support IP address host in `req.subdomains` + * Use `etag` to generate `ETag` headers + * deps: accepts@~1.1.0 + - update `mime-types` + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: finalhandler@0.2.0 + - Set `X-Content-Type-Options: nosniff` header + - deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: serve-static@~1.6.1 + - Add `lastModified` option + - deps: send@0.9.1 + * deps: type-is@~1.5.1 + - fix `hasbody` to be true for `content-length: 0` + - deps: media-typer@0.3.0 + - deps: mime-types@~2.0.1 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +4.8.8 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + * deps: serve-static@~1.5.4 + - deps: send@0.8.5 + +4.8.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +4.8.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +4.8.5 / 2014-08-18 +================== + + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + * deps: serve-static@~1.5.3 + - deps: send@0.8.3 + +4.8.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: serve-static@~1.5.2 + - deps: send@0.8.2 + +4.8.3 / 2014-08-10 +================== + + * deps: parseurl@~1.3.0 + * deps: qs@1.2.1 + * deps: serve-static@~1.5.1 + - Fix parsing of weird `req.originalUrl` values + - deps: parseurl@~1.3.0 + - deps: utils-merge@1.0.0 + +4.8.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +4.8.1 / 2014-08-06 +================== + + * fix incorrect deprecation warnings on `res.download` + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +4.8.0 / 2014-08-05 +================== + + * add `res.sendFile` + - accepts a file system path instead of a URL + - requires an absolute path or `root` option specified + * deprecate `res.sendfile` -- use `res.sendFile` instead + * support mounted app as any argument to `app.use()` + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + * deps: send@0.8.1 + - Add `extensions` option + * deps: serve-static@~1.5.0 + - Add `extensions` option + - deps: send@0.8.1 + +4.7.4 / 2014-08-04 +================== + + * fix `res.sendfile` regression for serving directory index files + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + * deps: serve-static@~1.4.4 + - deps: send@0.7.4 + +4.7.3 / 2014-08-04 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + * deps: serve-static@~1.4.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + - deps: send@0.7.3 + +4.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + * deps: serve-static@~1.4.2 + +4.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + * deps: serve-static@~1.4.1 + +4.7.0 / 2014-07-25 +================== + + * fix `req.protocol` for proxy-direct connections + * configurable query parser with `app.set('query parser', parser)` + - `app.set('query parser', 'extended')` parse with "qs" module + - `app.set('query parser', 'simple')` parse with "querystring" core module + - `app.set('query parser', false)` disable query string parsing + - `app.set('query parser', true)` enable simple parsing + * deprecate `res.json(status, obj)` -- use `res.status(status).json(obj)` instead + * deprecate `res.jsonp(status, obj)` -- use `res.status(status).jsonp(obj)` instead + * deprecate `res.send(status, body)` -- use `res.status(status).send(body)` instead + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: finalhandler@0.1.0 + - Respond after request fully read + - deps: debug@1.0.4 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + * deps: serve-static@~1.4.0 + - deps: parseurl@~1.2.0 + - deps: send@0.7.0 + * perf: prevent multiple `Buffer` creation in `res.send` + +4.6.1 / 2014-07-12 +================== + + * fix `subapp.mountpath` regression for `app.use(subapp)` + +4.6.0 / 2014-07-11 +================== + + * accept multiple callbacks to `app.use()` + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * catch errors in multiple `req.param(name, fn)` handlers + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * support non-string `path` in `app.use(path, fn)` + - supports array of paths + - supports `RegExp` + * router: fix optimization on router exit + * router: refactor location of `try` blocks + * router: speed up standard `app.use(fn)` + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: finalhandler@0.0.3 + - deps: debug@1.0.3 + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + * deps: path-to-regexp@0.1.3 + * deps: send@0.6.0 + - deps: debug@1.0.3 + * deps: serve-static@~1.3.2 + - deps: parseurl@~1.1.3 + - deps: send@0.6.0 + * perf: fix arguments reassign deopt in some `res` methods + +4.5.1 / 2014-07-06 +================== + + * fix routing regression when altering `req.method` + +4.5.0 / 2014-07-04 +================== + + * add deprecation message to non-plural `req.accepts*` + * add deprecation message to `res.send(body, status)` + * add deprecation message to `res.vary()` + * add `headers` option to `res.sendfile` + - use to set headers on successful file transfer + * add `mergeParams` option to `Router` + - merges `req.params` from parent routes + * add `req.hostname` -- correct name for what `req.host` returns + * deprecate things with `depd` module + * deprecate `req.host` -- use `req.hostname` instead + * fix behavior when handling request without routes + * fix handling when `route.all` is only route + * invoke `router.param()` only when route matches + * restore `req.params` after invoking router + * use `finalhandler` for final response handling + * use `media-typer` to alter content-type charset + * deps: accepts@~1.0.7 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + * deps: serve-static@~1.3.0 + - Accept string for `maxAge` (converted by `ms`) + - Add `setHeaders` option + - Include HTML link in redirect response + - deps: send@0.5.0 + * deps: type-is@~1.3.2 + +4.4.5 / 2014-06-26 +================== + + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +4.4.4 / 2014-06-20 +================== + + * fix `res.attachment` Unicode filenames in Safari + * fix "trim prefix" debug message in `express:router` + * deps: accepts@~1.0.5 + * deps: buffer-crc32@0.2.3 + +4.4.3 / 2014-06-11 +================== + + * fix persistence of modified `req.params[name]` from `app.param()` + * deps: accepts@1.0.3 + - deps: negotiator@0.4.6 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + * deps: serve-static@1.2.3 + - Do not throw un-catchable error on file open race condition + - deps: send@0.4.3 + +4.4.2 / 2014-06-09 +================== + + * fix catching errors from top-level handlers + * use `vary` module for `res.vary` + * deps: debug@1.0.1 + * deps: proxy-addr@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + * deps: serve-static@1.2.2 + - fix "event emitter leak" warnings + - deps: send@0.4.2 + * deps: type-is@1.2.1 + +4.4.1 / 2014-06-02 +================== + + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + * deps: serve-static@1.2.1 + - use `escape-html` for escaping + - deps: send@0.4.1 + +4.4.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * mark `res.send` ETag as weak and reduce collisions + * update accepts to 1.0.2 + - Fix interpretation when header not in request + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + * update serve-static to 1.2.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: send@0.4.0 + +4.3.2 / 2014-05-28 +================== + + * fix handling of errors from `router.param()` callbacks + +4.3.1 / 2014-05-23 +================== + + * revert "fix behavior of multiple `app.VERB` for the same path" + - this caused a regression in the order of route execution + +4.3.0 / 2014-05-21 +================== + + * add `req.baseUrl` to access the path stripped from `req.url` in routes + * fix behavior of multiple `app.VERB` for the same path + * fix issue routing requests among sub routers + * invoke `router.param()` only when necessary instead of every match + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * set proper `charset` in `Content-Type` for `res.send` + * update type-is to 1.2.0 + - support suffix matching + +4.2.0 / 2014-05-11 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * fix `req.next` when inside router instance + * include `ETag` header in `HEAD` requests + * keep previous `Content-Type` for `res.jsonp` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update debug to 0.8.0 + - add `enable()` method + - change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + +4.1.2 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +4.1.1 / 2014-04-27 +================== + + * fix package.json to reflect supported node version + +4.1.0 / 2014-04-24 +================== + + * pass options from `res.sendfile` to `send` + * preserve casing of headers in `res.header` and `res.set` + * support unicode file names in `res.attachment` and `res.download` + * update accepts to 1.0.1 + - deps: negotiator@0.4.0 + * update cookie to 0.1.2 + - Fix for maxAge == 0 + - made compat with expires field + * update send to 0.3.0 + - Accept API options in options object + - Coerce option types + - Control whether to generate etags + - Default directory access to 403 when index disabled + - Fix sending files with dots without root set + - Include file path in etag + - Make "Can't set headers after they are sent." catchable + - Send full entity-body for multi range requests + - Set etags to "weak" + - Support "If-Range" header + - Support multiple index paths + - deps: mime@1.2.11 + * update serve-static to 1.1.0 + - Accept options directly to `send` module + - Resolve relative paths at middleware setup + - Use parseurl to parse the URL from request + - deps: send@0.3.0 + * update type-is to 1.1.0 + - add non-array values support + - add `multipart` as a shorthand + +4.0.0 / 2014-04-09 +================== + + * remove: + - node 0.8 support + - connect and connect's patches except for charset handling + - express(1) - moved to [express-generator](https://github.com/expressjs/generator) + - `express.createServer()` - it has been deprecated for a long time. Use `express()` + - `app.configure` - use logic in your own app code + - `app.router` - is removed + - `req.auth` - use `basic-auth` instead + - `req.accepted*` - use `req.accepts*()` instead + - `res.location` - relative URL resolution is removed + - `res.charset` - include the charset in the content type when using `res.set()` + - all bundled middleware except `static` + * change: + - `app.route` -> `app.mountpath` when mounting an express app in another express app + - `json spaces` no longer enabled by default in development + - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` + - `req.params` is now an object instead of an array + - `res.locals` is no longer a function. It is a plain js object. Treat it as such. + - `res.headerSent` -> `res.headersSent` to match node.js ServerResponse object + * refactor: + - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) + - `req.is` with [type-is](https://github.com/expressjs/type-is) + - [path-to-regexp](https://github.com/component/path-to-regexp) + * add: + - `app.router()` - returns the app Router instance + - `app.route()` - Proxy to the app's `Router#route()` method to create a new route + - Router & Route - public API + +3.21.2 / 2015-07-31 +=================== + + * deps: connect@2.30.2 + - deps: body-parser@~1.13.3 + - deps: compression@~1.5.2 + - deps: errorhandler@~1.4.2 + - deps: method-override@~2.3.5 + - deps: serve-index@~1.7.2 + - deps: type-is@~1.6.6 + - deps: vhost@~3.0.1 + * deps: vary@~1.0.1 + - Fix setting empty header from empty `field` + - perf: enable strict mode + - perf: remove argument reassignments + +3.21.1 / 2015-07-05 +=================== + + * deps: basic-auth@~1.0.3 + * deps: connect@2.30.1 + - deps: body-parser@~1.13.2 + - deps: compression@~1.5.1 + - deps: errorhandler@~1.4.1 + - deps: morgan@~1.6.1 + - deps: pause@0.1.0 + - deps: qs@4.0.0 + - deps: serve-index@~1.7.1 + - deps: type-is@~1.6.4 + +3.21.0 / 2015-06-18 +=================== + + * deps: basic-auth@1.0.2 + - perf: enable strict mode + - perf: hoist regular expression + - perf: parse with regular expressions + - perf: remove argument reassignment + * deps: connect@2.30.0 + - deps: body-parser@~1.13.1 + - deps: bytes@2.1.0 + - deps: compression@~1.5.0 + - deps: cookie@0.1.3 + - deps: cookie-parser@~1.3.5 + - deps: csurf@~1.8.3 + - deps: errorhandler@~1.4.0 + - deps: express-session@~1.11.3 + - deps: finalhandler@0.4.0 + - deps: fresh@0.3.0 + - deps: morgan@~1.6.0 + - deps: serve-favicon@~2.3.0 + - deps: serve-index@~1.7.0 + - deps: serve-static@~1.10.0 + - deps: type-is@~1.6.3 + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: mkdirp@0.5.1 + - Work in global strict mode + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + +3.20.3 / 2015-05-17 +=================== + + * deps: connect@2.29.2 + - deps: body-parser@~1.12.4 + - deps: compression@~1.4.4 + - deps: connect-timeout@~1.6.2 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: errorhandler@~1.3.6 + - deps: finalhandler@0.3.6 + - deps: method-override@~2.3.3 + - deps: morgan@~1.5.3 + - deps: qs@2.4.2 + - deps: response-time@~2.3.1 + - deps: serve-favicon@~2.2.1 + - deps: serve-index@~1.6.4 + - deps: serve-static@~1.9.3 + - deps: type-is@~1.6.2 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +3.20.2 / 2015-03-16 +=================== + + * deps: connect@2.29.1 + - deps: body-parser@~1.12.2 + - deps: compression@~1.4.3 + - deps: connect-timeout@~1.6.1 + - deps: debug@~2.1.3 + - deps: errorhandler@~1.3.5 + - deps: express-session@~1.10.4 + - deps: finalhandler@0.3.4 + - deps: method-override@~2.3.2 + - deps: morgan@~1.5.2 + - deps: qs@2.4.1 + - deps: serve-index@~1.6.3 + - deps: serve-static@~1.9.2 + - deps: type-is@~1.6.1 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: merge-descriptors@1.0.0 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +3.20.1 / 2015-02-28 +=================== + + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + +3.20.0 / 2015-02-18 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: connect@2.29.0 + - Use `content-type` to parse `Content-Type` headers + - deps: body-parser@~1.12.0 + - deps: compression@~1.4.1 + - deps: connect-timeout@~1.6.0 + - deps: cookie-parser@~1.3.4 + - deps: cookie-signature@1.0.6 + - deps: csurf@~1.7.0 + - deps: errorhandler@~1.3.4 + - deps: express-session@~1.10.3 + - deps: http-errors@~1.3.1 + - deps: response-time@~2.3.0 + - deps: serve-index@~1.6.2 + - deps: serve-static@~1.9.1 + - deps: type-is@~1.6.0 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +3.19.2 / 2015-02-01 +=================== + + * deps: connect@2.28.3 + - deps: compression@~1.3.1 + - deps: csurf@~1.6.6 + - deps: errorhandler@~1.3.3 + - deps: express-session@~1.10.2 + - deps: serve-index@~1.6.1 + - deps: type-is@~1.5.6 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + +3.19.1 / 2015-01-20 +=================== + + * deps: connect@2.28.2 + - deps: body-parser@~1.10.2 + - deps: serve-static@~1.8.1 + * deps: send@0.11.1 + - Fix root path disclosure + +3.19.0 / 2015-01-09 +=================== + + * Fix `OPTIONS` responses to include the `HEAD` method property + * Use `readline` for prompt in `express(1)` + * deps: commander@2.6.0 + * deps: connect@2.28.1 + - deps: body-parser@~1.10.1 + - deps: compression@~1.3.0 + - deps: connect-timeout@~1.5.0 + - deps: csurf@~1.6.4 + - deps: debug@~2.1.1 + - deps: errorhandler@~1.3.2 + - deps: express-session@~1.10.1 + - deps: finalhandler@0.3.3 + - deps: method-override@~2.3.1 + - deps: morgan@~1.5.1 + - deps: serve-favicon@~2.2.0 + - deps: serve-index@~1.6.0 + - deps: serve-static@~1.8.0 + - deps: type-is@~1.5.5 + * deps: debug@~2.1.1 + * deps: methods@~1.1.1 + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + +3.18.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +3.18.5 / 2014-12-11 +=================== + + * deps: connect@2.27.6 + - deps: compression@~1.2.2 + - deps: express-session@~1.9.3 + - deps: http-errors@~1.2.8 + - deps: serve-index@~1.5.3 + - deps: type-is@~1.5.4 + +3.18.4 / 2014-11-23 +=================== + + * deps: connect@2.27.4 + - deps: body-parser@~1.9.3 + - deps: compression@~1.2.1 + - deps: errorhandler@~1.2.3 + - deps: express-session@~1.9.2 + - deps: qs@2.3.3 + - deps: serve-favicon@~2.1.7 + - deps: serve-static@~1.5.1 + - deps: type-is@~1.5.3 + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + +3.18.3 / 2014-11-09 +=================== + + * deps: connect@2.27.3 + - Correctly invoke async callback asynchronously + - deps: csurf@~1.6.3 + +3.18.2 / 2014-10-28 +=================== + + * deps: connect@2.27.2 + - Fix handling of URLs containing `://` in the path + - deps: body-parser@~1.9.2 + - deps: qs@2.3.2 + +3.18.1 / 2014-10-22 +=================== + + * Fix internal `utils.merge` deprecation warnings + * deps: connect@2.27.1 + - deps: body-parser@~1.9.1 + - deps: express-session@~1.9.1 + - deps: finalhandler@0.3.2 + - deps: morgan@~1.4.1 + - deps: qs@2.3.0 + - deps: serve-static@~1.7.1 + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +3.18.0 / 2014-10-17 +=================== + + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `etag` module to generate `ETag` headers + * deps: connect@2.27.0 + - Use `http-errors` module for creating errors + - Use `utils-merge` module for merging objects + - deps: body-parser@~1.9.0 + - deps: compression@~1.2.0 + - deps: connect-timeout@~1.4.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: express-session@~1.9.0 + - deps: finalhandler@0.3.1 + - deps: method-override@~2.3.0 + - deps: morgan@~1.4.0 + - deps: response-time@~2.2.0 + - deps: serve-favicon@~2.1.6 + - deps: serve-index@~1.5.0 + - deps: serve-static@~1.7.0 + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +3.17.8 / 2014-10-15 +=================== + + * deps: connect@2.26.6 + - deps: compression@~1.1.2 + - deps: csurf@~1.6.2 + - deps: errorhandler@~1.2.2 + +3.17.7 / 2014-10-08 +=================== + + * deps: connect@2.26.5 + - Fix accepting non-object arguments to `logger` + - deps: serve-static@~1.6.4 + +3.17.6 / 2014-10-02 +=================== + + * deps: connect@2.26.4 + - deps: morgan@~1.3.2 + - deps: type-is@~1.5.2 + +3.17.5 / 2014-09-24 +=================== + + * deps: connect@2.26.3 + - deps: body-parser@~1.8.4 + - deps: serve-favicon@~2.1.5 + - deps: serve-static@~1.6.3 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +3.17.4 / 2014-09-19 +=================== + + * deps: connect@2.26.2 + - deps: body-parser@~1.8.3 + - deps: qs@2.2.4 + +3.17.3 / 2014-09-18 +=================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +3.17.2 / 2014-09-15 +=================== + + * Use `crc` instead of `buffer-crc32` for speed + * deps: connect@2.26.1 + - deps: body-parser@~1.8.2 + - deps: depd@0.4.5 + - deps: express-session@~1.8.2 + - deps: morgan@~1.3.1 + - deps: serve-favicon@~2.1.3 + - deps: serve-static@~1.6.2 + * deps: depd@0.4.5 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +3.17.1 / 2014-09-08 +=================== + + * Fix error in `req.subdomains` on empty host + +3.17.0 / 2014-09-08 +=================== + + * Support `X-Forwarded-Host` in `req.subdomains` + * Support IP address host in `req.subdomains` + * deps: connect@2.26.0 + - deps: body-parser@~1.8.1 + - deps: compression@~1.1.0 + - deps: connect-timeout@~1.3.0 + - deps: cookie-parser@~1.3.3 + - deps: cookie-signature@1.0.5 + - deps: csurf@~1.6.1 + - deps: debug@~2.0.0 + - deps: errorhandler@~1.2.0 + - deps: express-session@~1.8.1 + - deps: finalhandler@0.2.0 + - deps: fresh@0.2.4 + - deps: media-typer@0.3.0 + - deps: method-override@~2.2.0 + - deps: morgan@~1.3.0 + - deps: qs@2.2.3 + - deps: serve-favicon@~2.1.3 + - deps: serve-index@~1.2.1 + - deps: serve-static@~1.6.1 + - deps: type-is@~1.5.1 + - deps: vhost@~3.0.0 + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +3.16.10 / 2014-09-04 +==================== + + * deps: connect@2.25.10 + - deps: serve-static@~1.5.4 + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +3.16.9 / 2014-08-29 +=================== + + * deps: connect@2.25.9 + - deps: body-parser@~1.6.7 + - deps: qs@2.2.2 + +3.16.8 / 2014-08-27 +=================== + + * deps: connect@2.25.8 + - deps: body-parser@~1.6.6 + - deps: csurf@~1.4.1 + - deps: qs@2.2.0 + +3.16.7 / 2014-08-18 +=================== + + * deps: connect@2.25.7 + - deps: body-parser@~1.6.5 + - deps: express-session@~1.7.6 + - deps: morgan@~1.2.3 + - deps: serve-static@~1.5.3 + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + +3.16.6 / 2014-08-14 +=================== + + * deps: connect@2.25.6 + - deps: body-parser@~1.6.4 + - deps: qs@1.2.2 + - deps: serve-static@~1.5.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +3.16.5 / 2014-08-11 +=================== + + * deps: connect@2.25.5 + - Fix backwards compatibility in `logger` + +3.16.4 / 2014-08-10 +=================== + + * Fix original URL parsing in `res.location` + * deps: connect@2.25.4 + - Fix `query` middleware breaking with argument + - deps: body-parser@~1.6.3 + - deps: compression@~1.0.11 + - deps: connect-timeout@~1.2.2 + - deps: express-session@~1.7.5 + - deps: method-override@~2.1.3 + - deps: on-headers@~1.0.0 + - deps: parseurl@~1.3.0 + - deps: qs@1.2.1 + - deps: response-time@~2.0.1 + - deps: serve-index@~1.1.6 + - deps: serve-static@~1.5.1 + * deps: parseurl@~1.3.0 + +3.16.3 / 2014-08-07 +=================== + + * deps: connect@2.25.3 + - deps: multiparty@3.3.2 + +3.16.2 / 2014-08-07 +=================== + + * deps: connect@2.25.2 + - deps: body-parser@~1.6.2 + - deps: qs@1.2.0 + +3.16.1 / 2014-08-06 +=================== + + * deps: connect@2.25.1 + - deps: body-parser@~1.6.1 + - deps: qs@1.1.0 + +3.16.0 / 2014-08-05 +=================== + + * deps: connect@2.25.0 + - deps: body-parser@~1.6.0 + - deps: compression@~1.0.10 + - deps: csurf@~1.4.0 + - deps: express-session@~1.7.4 + - deps: qs@1.0.2 + - deps: serve-static@~1.5.0 + * deps: send@0.8.1 + - Add `extensions` option + +3.15.3 / 2014-08-04 +=================== + + * fix `res.sendfile` regression for serving directory index files + * deps: connect@2.24.3 + - deps: serve-index@~1.1.5 + - deps: serve-static@~1.4.4 + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + +3.15.2 / 2014-07-27 +=================== + + * deps: connect@2.24.2 + - deps: body-parser@~1.5.2 + - deps: depd@0.4.4 + - deps: express-session@~1.7.2 + - deps: morgan@~1.2.2 + - deps: serve-static@~1.4.2 + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + +3.15.1 / 2014-07-26 +=================== + + * deps: connect@2.24.1 + - deps: body-parser@~1.5.1 + - deps: depd@0.4.3 + - deps: express-session@~1.7.1 + - deps: morgan@~1.2.1 + - deps: serve-index@~1.1.4 + - deps: serve-static@~1.4.1 + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + +3.15.0 / 2014-07-22 +=================== + + * Fix `req.protocol` for proxy-direct connections + * Pass options from `res.sendfile` to `send` + * deps: connect@2.24.0 + - deps: body-parser@~1.5.0 + - deps: compression@~1.0.9 + - deps: connect-timeout@~1.2.1 + - deps: debug@1.0.4 + - deps: depd@0.4.2 + - deps: express-session@~1.7.0 + - deps: finalhandler@0.1.0 + - deps: method-override@~2.1.2 + - deps: morgan@~1.2.0 + - deps: multiparty@3.3.1 + - deps: parseurl@~1.2.0 + - deps: serve-static@~1.4.0 + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +3.14.0 / 2014-07-11 +=================== + + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * deps: basic-auth@1.0.0 + - support empty password + - support empty username + * deps: connect@2.23.0 + - deps: debug@1.0.3 + - deps: express-session@~1.6.4 + - deps: method-override@~2.1.0 + - deps: parseurl@~1.1.3 + - deps: serve-static@~1.3.1 + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +3.13.0 / 2014-07-03 +=================== + + * add deprecation message to `app.configure` + * add deprecation message to `req.auth` + * use `basic-auth` to parse `Authorization` header + * deps: connect@2.22.0 + - deps: csurf@~1.3.0 + - deps: express-session@~1.6.1 + - deps: multiparty@3.3.0 + - deps: serve-static@~1.3.0 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + +3.12.1 / 2014-06-26 +=================== + + * deps: connect@2.21.1 + - deps: cookie-parser@1.3.2 + - deps: cookie-signature@1.0.4 + - deps: express-session@~1.5.2 + - deps: type-is@~1.3.2 + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +3.12.0 / 2014-06-21 +=================== + + * use `media-typer` to alter content-type charset + * deps: connect@2.21.0 + - deprecate `connect(middleware)` -- use `app.use(middleware)` instead + - deprecate `connect.createServer()` -- use `connect()` instead + - fix `res.setHeader()` patch to work with with get -> append -> set pattern + - deps: compression@~1.0.8 + - deps: errorhandler@~1.1.1 + - deps: express-session@~1.5.0 + - deps: serve-index@~1.1.3 + +3.11.0 / 2014-06-19 +=================== + + * deprecate things with `depd` module + * deps: buffer-crc32@0.2.3 + * deps: connect@2.20.2 + - deprecate `verify` option to `json` -- use `body-parser` npm module instead + - deprecate `verify` option to `urlencoded` -- use `body-parser` npm module instead + - deprecate things with `depd` module + - use `finalhandler` for final response handling + - use `media-typer` to parse `content-type` for charset + - deps: body-parser@1.4.3 + - deps: connect-timeout@1.1.1 + - deps: cookie-parser@1.3.1 + - deps: csurf@1.2.2 + - deps: errorhandler@1.1.0 + - deps: express-session@1.4.0 + - deps: multiparty@3.2.9 + - deps: serve-index@1.1.2 + - deps: type-is@1.3.1 + - deps: vhost@2.0.0 + +3.10.5 / 2014-06-11 +=================== + + * deps: connect@2.19.6 + - deps: body-parser@1.3.1 + - deps: compression@1.0.7 + - deps: debug@1.0.2 + - deps: serve-index@1.1.1 + - deps: serve-static@1.2.3 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +3.10.4 / 2014-06-09 +=================== + + * deps: connect@2.19.5 + - fix "event emitter leak" warnings + - deps: csurf@1.2.1 + - deps: debug@1.0.1 + - deps: serve-static@1.2.2 + - deps: type-is@1.2.1 + * deps: debug@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: finished@1.2.1 + - deps: debug@1.0.1 + +3.10.3 / 2014-06-05 +=================== + + * use `vary` module for `res.vary` + * deps: connect@2.19.4 + - deps: errorhandler@1.0.2 + - deps: method-override@2.0.2 + - deps: serve-favicon@2.0.1 + * deps: debug@1.0.0 + +3.10.2 / 2014-06-03 +=================== + + * deps: connect@2.19.3 + - deps: compression@1.0.6 + +3.10.1 / 2014-06-03 +=================== + + * deps: connect@2.19.2 + - deps: compression@1.0.4 + * deps: proxy-addr@1.0.1 + +3.10.0 / 2014-06-02 +=================== + + * deps: connect@2.19.1 + - deprecate `methodOverride()` -- use `method-override` npm module instead + - deps: body-parser@1.3.0 + - deps: method-override@2.0.1 + - deps: multiparty@3.2.8 + - deps: response-time@2.0.0 + - deps: serve-static@1.2.1 + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +3.9.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * Include ETag in HEAD requests + * mark `res.send` ETag as weak and reduce collisions + * update connect to 2.18.0 + - deps: compression@1.0.3 + - deps: serve-index@1.1.0 + - deps: serve-static@1.2.0 + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + +3.8.1 / 2014-05-27 +================== + + * update connect to 2.17.3 + - deps: body-parser@1.2.2 + - deps: express-session@1.2.1 + - deps: method-override@1.0.2 + +3.8.0 / 2014-05-21 +================== + + * keep previous `Content-Type` for `res.jsonp` + * set proper `charset` in `Content-Type` for `res.send` + * update connect to 2.17.1 + - fix `res.charset` appending charset when `content-type` has one + - deps: express-session@1.2.0 + - deps: morgan@1.1.1 + - deps: serve-index@1.0.3 + +3.7.0 / 2014-05-18 +================== + + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * update connect to 2.16.2 + - deprecate `res.headerSent` -- use `res.headersSent` + - deprecate `res.on("header")` -- use on-headers module instead + - fix edge-case in `res.appendHeader` that would append in wrong order + - json: use body-parser + - urlencoded: use body-parser + - dep: bytes@1.0.0 + - dep: cookie-parser@1.1.0 + - dep: csurf@1.2.0 + - dep: express-session@1.1.0 + - dep: method-override@1.0.1 + +3.6.0 / 2014-05-09 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update connect to 2.15.0 + * Add `res.appendHeader` + * Call error stack even when response has been sent + * Patch `res.headerSent` to return Boolean + * Patch `res.headersSent` for node.js 0.8 + * Prevent default 404 handler after response sent + * dep: compression@1.0.2 + * dep: connect-timeout@1.1.0 + * dep: debug@^0.8.0 + * dep: errorhandler@1.0.1 + * dep: express-session@1.0.4 + * dep: morgan@1.0.1 + * dep: serve-favicon@2.0.0 + * dep: serve-index@1.0.2 + * update debug to 0.8.0 + * add `enable()` method + * change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + * update mkdirp to 0.5.0 + +3.5.3 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +3.5.2 / 2014-04-24 +================== + + * update connect to 2.14.5 + * update cookie to 0.1.2 + * update mkdirp to 0.4.0 + * update send to 0.3.0 + +3.5.1 / 2014-03-25 +================== + + * pin less-middleware in generated app + +3.5.0 / 2014-03-06 +================== + + * bump deps + +3.4.8 / 2014-01-13 +================== + + * prevent incorrect automatic OPTIONS responses #1868 @dpatti + * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi + * throw 400 in case of malformed paths @rlidwka + +3.4.7 / 2013-12-10 +================== + + * update connect + +3.4.6 / 2013-12-01 +================== + + * update connect (raw-body) + +3.4.5 / 2013-11-27 +================== + + * update connect + * res.location: remove leading ./ #1802 @kapouer + * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra + * res.send: always send ETag when content-length > 0 + * router: add Router.all() method + +3.4.4 / 2013-10-29 +================== + + * update connect + * update supertest + * update methods + * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 + +3.4.3 / 2013-10-23 +================== + + * update connect + +3.4.2 / 2013-10-18 +================== + + * update connect + * downgrade commander + +3.4.1 / 2013-10-15 +================== + + * update connect + * update commander + * jsonp: check if callback is a function + * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) + * res.format: now includes charset @1747 (@sorribas) + * res.links: allow multiple calls @1746 (@sorribas) + +3.4.0 / 2013-09-07 +================== + + * add res.vary(). Closes #1682 + * update connect + +3.3.8 / 2013-09-02 +================== + + * update connect + +3.3.7 / 2013-08-28 +================== + + * update connect + +3.3.6 / 2013-08-27 +================== + + * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) + * add: req.accepts take an argument list + +3.3.4 / 2013-07-08 +================== + + * update send and connect + +3.3.3 / 2013-07-04 +================== + + * update connect + +3.3.2 / 2013-07-03 +================== + + * update connect + * update send + * remove .version export + +3.3.1 / 2013-06-27 +================== + + * update connect + +3.3.0 / 2013-06-26 +================== + + * update connect + * add support for multiple X-Forwarded-Proto values. Closes #1646 + * change: remove charset from json responses. Closes #1631 + * change: return actual booleans from req.accept* functions + * fix jsonp callback array throw + +3.2.6 / 2013-06-02 +================== + + * update connect + +3.2.5 / 2013-05-21 +================== + + * update connect + * update node-cookie + * add: throw a meaningful error when there is no default engine + * change generation of ETags with res.send() to GET requests only. Closes #1619 + +3.2.4 / 2013-05-09 +================== + + * fix `req.subdomains` when no Host is present + * fix `req.host` when no Host is present, return undefined + +3.2.3 / 2013-05-07 +================== + + * update connect / qs + +3.2.2 / 2013-05-03 +================== + + * update qs + +3.2.1 / 2013-04-29 +================== + + * add app.VERB() paths array deprecation warning + * update connect + * update qs and remove all ~ semver crap + * fix: accept number as value of Signed Cookie + +3.2.0 / 2013-04-15 +================== + + * add "view" constructor setting to override view behaviour + * add req.acceptsEncoding(name) + * add req.acceptedEncodings + * revert cookie signature change causing session race conditions + * fix sorting of Accept values of the same quality + +3.1.2 / 2013-04-12 +================== + + * add support for custom Accept parameters + * update cookie-signature + +3.1.1 / 2013-04-01 +================== + + * add X-Forwarded-Host support to `req.host` + * fix relative redirects + * update mkdirp + * update buffer-crc32 + * remove legacy app.configure() method from app template. + +3.1.0 / 2013-01-25 +================== + + * add support for leading "." in "view engine" setting + * add array support to `res.set()` + * add node 0.8.x to travis.yml + * add "subdomain offset" setting for tweaking `req.subdomains` + * add `res.location(url)` implementing `res.redirect()`-like setting of Location + * use app.get() for x-powered-by setting for inheritance + * fix colons in passwords for `req.auth` + +3.0.6 / 2013-01-04 +================== + + * add http verb methods to Router + * update connect + * fix mangling of the `res.cookie()` options object + * fix jsonp whitespace escape. Closes #1132 + +3.0.5 / 2012-12-19 +================== + + * add throwing when a non-function is passed to a route + * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses + * revert "add 'etag' option" + +3.0.4 / 2012-12-05 +================== + + * add 'etag' option to disable `res.send()` Etags + * add escaping of urls in text/plain in `res.redirect()` + for old browsers interpreting as html + * change crc32 module for a more liberal license + * update connect + +3.0.3 / 2012-11-13 +================== + + * update connect + * update cookie module + * fix cookie max-age + +3.0.2 / 2012-11-08 +================== + + * add OPTIONS to cors example. Closes #1398 + * fix route chaining regression. Closes #1397 + +3.0.1 / 2012-11-01 +================== + + * update connect + +3.0.0 / 2012-10-23 +================== + + * add `make clean` + * add "Basic" check to req.auth + * add `req.auth` test coverage + * add cb && cb(payload) to `res.jsonp()`. Closes #1374 + * add backwards compat for `res.redirect()` status. Closes #1336 + * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 + * update connect + * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 + * remove non-primitive string support for `res.send()` + * fix view-locals example. Closes #1370 + * fix route-separation example + +3.0.0rc5 / 2012-09-18 +================== + + * update connect + * add redis search example + * add static-files example + * add "x-powered-by" setting (`app.disable('x-powered-by')`) + * add "application/octet-stream" redirect Accept test case. Closes #1317 + +3.0.0rc4 / 2012-08-30 +================== + + * add `res.jsonp()`. Closes #1307 + * add "verbose errors" option to error-pages example + * add another route example to express(1) so people are not so confused + * add redis online user activity tracking example + * update connect dep + * fix etag quoting. Closes #1310 + * fix error-pages 404 status + * fix jsonp callback char restrictions + * remove old OPTIONS default response + +3.0.0rc3 / 2012-08-13 +================== + + * update connect dep + * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] + * fix `res.render()` clobbering of "locals" + +3.0.0rc2 / 2012-08-03 +================== + + * add CORS example + * update connect dep + * deprecate `.createServer()` & remove old stale examples + * fix: escape `res.redirect()` link + * fix vhost example + +3.0.0rc1 / 2012-07-24 +================== + + * add more examples to view-locals + * add scheme-relative redirects (`res.redirect("//foo.com")`) support + * update cookie dep + * update connect dep + * update send dep + * fix `express(1)` -h flag, use -H for hogan. Closes #1245 + * fix `res.sendfile()` socket error handling regression + +3.0.0beta7 / 2012-07-16 +================== + + * update connect dep for `send()` root normalization regression + +3.0.0beta6 / 2012-07-13 +================== + + * add `err.view` property for view errors. Closes #1226 + * add "jsonp callback name" setting + * add support for "/foo/:bar*" non-greedy matches + * change `res.sendfile()` to use `send()` module + * change `res.send` to use "response-send" module + * remove `app.locals.use` and `res.locals.use`, use regular middleware + +3.0.0beta5 / 2012-07-03 +================== + + * add "make check" support + * add route-map example + * add `res.json(obj, status)` support back for BC + * add "methods" dep, remove internal methods module + * update connect dep + * update auth example to utilize cores pbkdf2 + * updated tests to use "supertest" + +3.0.0beta4 / 2012-06-25 +================== + + * Added `req.auth` + * Added `req.range(size)` + * Added `res.links(obj)` + * Added `res.send(body, status)` support back for backwards compat + * Added `.default()` support to `res.format()` + * Added 2xx / 304 check to `req.fresh` + * Revert "Added + support to the router" + * Fixed `res.send()` freshness check, respect res.statusCode + +3.0.0beta3 / 2012-06-15 +================== + + * Added hogan `--hjs` to express(1) [nullfirm] + * Added another example to content-negotiation + * Added `fresh` dep + * Changed: `res.send()` always checks freshness + * Fixed: expose connects mime module. Closes #1165 + +3.0.0beta2 / 2012-06-06 +================== + + * Added `+` support to the router + * Added `req.host` + * Changed `req.param()` to check route first + * Update connect dep + +3.0.0beta1 / 2012-06-01 +================== + + * Added `res.format()` callback to override default 406 behaviour + * Fixed `res.redirect()` 406. Closes #1154 + +3.0.0alpha5 / 2012-05-30 +================== + + * Added `req.ip` + * Added `{ signed: true }` option to `res.cookie()` + * Removed `res.signedCookie()` + * Changed: dont reverse `req.ips` + * Fixed "trust proxy" setting check for `req.ips` + +3.0.0alpha4 / 2012-05-09 +================== + + * Added: allow `[]` in jsonp callback. Closes #1128 + * Added `PORT` env var support in generated template. Closes #1118 [benatkin] + * Updated: connect 2.2.2 + +3.0.0alpha3 / 2012-05-04 +================== + + * Added public `app.routes`. Closes #887 + * Added _view-locals_ example + * Added _mvc_ example + * Added `res.locals.use()`. Closes #1120 + * Added conditional-GET support to `res.send()` + * Added: coerce `res.set()` values to strings + * Changed: moved `static()` in generated apps below router + * Changed: `res.send()` only set ETag when not previously set + * Changed connect 2.2.1 dep + * Changed: `make test` now runs unit / acceptance tests + * Fixed req/res proto inheritance + +3.0.0alpha2 / 2012-04-26 +================== + + * Added `make benchmark` back + * Added `res.send()` support for `String` objects + * Added client-side data exposing example + * Added `res.header()` and `req.header()` aliases for BC + * Added `express.createServer()` for BC + * Perf: memoize parsed urls + * Perf: connect 2.2.0 dep + * Changed: make `expressInit()` middleware self-aware + * Fixed: use app.get() for all core settings + * Fixed redis session example + * Fixed session example. Closes #1105 + * Fixed generated express dep. Closes #1078 + +3.0.0alpha1 / 2012-04-15 +================== + + * Added `app.locals.use(callback)` + * Added `app.locals` object + * Added `app.locals(obj)` + * Added `res.locals` object + * Added `res.locals(obj)` + * Added `res.format()` for content-negotiation + * Added `app.engine()` + * Added `res.cookie()` JSON cookie support + * Added "trust proxy" setting + * Added `req.subdomains` + * Added `req.protocol` + * Added `req.secure` + * Added `req.path` + * Added `req.ips` + * Added `req.fresh` + * Added `req.stale` + * Added comma-delimited / array support for `req.accepts()` + * Added debug instrumentation + * Added `res.set(obj)` + * Added `res.set(field, value)` + * Added `res.get(field)` + * Added `app.get(setting)`. Closes #842 + * Added `req.acceptsLanguage()` + * Added `req.acceptsCharset()` + * Added `req.accepted` + * Added `req.acceptedLanguages` + * Added `req.acceptedCharsets` + * Added "json replacer" setting + * Added "json spaces" setting + * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 + * Added `--less` support to express(1) + * Added `express.response` prototype + * Added `express.request` prototype + * Added `express.application` prototype + * Added `app.path()` + * Added `app.render()` + * Added `res.type()` to replace `res.contentType()` + * Changed: `res.redirect()` to add relative support + * Changed: enable "jsonp callback" by default + * Changed: renamed "case sensitive routes" to "case sensitive routing" + * Rewrite of all tests with mocha + * Removed "root" setting + * Removed `res.redirect('home')` support + * Removed `req.notify()` + * Removed `app.register()` + * Removed `app.redirect()` + * Removed `app.is()` + * Removed `app.helpers()` + * Removed `app.dynamicHelpers()` + * Fixed `res.sendfile()` with non-GET. Closes #723 + * Fixed express(1) public dir for windows. Closes #866 + +2.5.9/ 2012-04-02 +================== + + * Added support for PURGE request method [pbuyle] + * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] + +2.5.8 / 2012-02-08 +================== + + * Update mkdirp dep. Closes #991 + +2.5.7 / 2012-02-06 +================== + + * Fixed `app.all` duplicate DELETE requests [mscdex] + +2.5.6 / 2012-01-13 +================== + + * Updated hamljs dev dep. Closes #953 + +2.5.5 / 2012-01-08 +================== + + * Fixed: set `filename` on cached templates [matthewleon] + +2.5.4 / 2012-01-02 +================== + + * Fixed `express(1)` eol on 0.4.x. Closes #947 + +2.5.3 / 2011-12-30 +================== + + * Fixed `req.is()` when a charset is present + +2.5.2 / 2011-12-10 +================== + + * Fixed: express(1) LF -> CRLF for windows + +2.5.1 / 2011-11-17 +================== + + * Changed: updated connect to 1.8.x + * Removed sass.js support from express(1) + +2.5.0 / 2011-10-24 +================== + + * Added ./routes dir for generated app by default + * Added npm install reminder to express(1) app gen + * Added 0.5.x support + * Removed `make test-cov` since it wont work with node 0.5.x + * Fixed express(1) public dir for windows. Closes #866 + +2.4.7 / 2011-10-05 +================== + + * Added mkdirp to express(1). Closes #795 + * Added simple _json-config_ example + * Added shorthand for the parsed request's pathname via `req.path` + * Changed connect dep to 1.7.x to fix npm issue... + * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] + * Fixed `req.flash()`, only escape args + * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] + +2.4.6 / 2011-08-22 +================== + + * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] + +2.4.5 / 2011-08-19 +================== + + * Added support for routes to handle errors. Closes #809 + * Added `app.routes.all()`. Closes #803 + * Added "basepath" setting to work in conjunction with reverse proxies etc. + * Refactored `Route` to use a single array of callbacks + * Added support for multiple callbacks for `app.param()`. Closes #801 +Closes #805 + * Changed: removed .call(self) for route callbacks + * Dependency: `qs >= 0.3.1` + * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 + +2.4.4 / 2011-08-05 +================== + + * Fixed `res.header()` intention of a set, even when `undefined` + * Fixed `*`, value no longer required + * Fixed `res.send(204)` support. Closes #771 + +2.4.3 / 2011-07-14 +================== + + * Added docs for `status` option special-case. Closes #739 + * Fixed `options.filename`, exposing the view path to template engines + +2.4.2. / 2011-07-06 +================== + + * Revert "removed jsonp stripping" for XSS + +2.4.1 / 2011-07-06 +================== + + * Added `res.json()` JSONP support. Closes #737 + * Added _extending-templates_ example. Closes #730 + * Added "strict routing" setting for trailing slashes + * Added support for multiple envs in `app.configure()` calls. Closes #735 + * Changed: `res.send()` using `res.json()` + * Changed: when cookie `path === null` don't default it + * Changed; default cookie path to "home" setting. Closes #731 + * Removed _pids/logs_ creation from express(1) + +2.4.0 / 2011-06-28 +================== + + * Added chainable `res.status(code)` + * Added `res.json()`, an explicit version of `res.send(obj)` + * Added simple web-service example + +2.3.12 / 2011-06-22 +================== + + * \#express is now on freenode! come join! + * Added `req.get(field, param)` + * Added links to Japanese documentation, thanks @hideyukisaito! + * Added; the `express(1)` generated app outputs the env + * Added `content-negotiation` example + * Dependency: connect >= 1.5.1 < 2.0.0 + * Fixed view layout bug. Closes #720 + * Fixed; ignore body on 304. Closes #701 + +2.3.11 / 2011-06-04 +================== + + * Added `npm test` + * Removed generation of dummy test file from `express(1)` + * Fixed; `express(1)` adds express as a dep + * Fixed; prune on `prepublish` + +2.3.10 / 2011-05-27 +================== + + * Added `req.route`, exposing the current route + * Added _package.json_ generation support to `express(1)` + * Fixed call to `app.param()` function for optional params. Closes #682 + +2.3.9 / 2011-05-25 +================== + + * Fixed bug-ish with `../' in `res.partial()` calls + +2.3.8 / 2011-05-24 +================== + + * Fixed `app.options()` + +2.3.7 / 2011-05-23 +================== + + * Added route `Collection`, ex: `app.get('/user/:id').remove();` + * Added support for `app.param(fn)` to define param logic + * Removed `app.param()` support for callback with return value + * Removed module.parent check from express(1) generated app. Closes #670 + * Refactored router. Closes #639 + +2.3.6 / 2011-05-20 +================== + + * Changed; using devDependencies instead of git submodules + * Fixed redis session example + * Fixed markdown example + * Fixed view caching, should not be enabled in development + +2.3.5 / 2011-05-20 +================== + + * Added export `.view` as alias for `.View` + +2.3.4 / 2011-05-08 +================== + + * Added `./examples/say` + * Fixed `res.sendfile()` bug preventing the transfer of files with spaces + +2.3.3 / 2011-05-03 +================== + + * Added "case sensitive routes" option. + * Changed; split methods supported per rfc [slaskis] + * Fixed route-specific middleware when using the same callback function several times + +2.3.2 / 2011-04-27 +================== + + * Fixed view hints + +2.3.1 / 2011-04-26 +================== + + * Added `app.match()` as `app.match.all()` + * Added `app.lookup()` as `app.lookup.all()` + * Added `app.remove()` for `app.remove.all()` + * Added `app.remove.VERB()` + * Fixed template caching collision issue. Closes #644 + * Moved router over from connect and started refactor + +2.3.0 / 2011-04-25 +================== + + * Added options support to `res.clearCookie()` + * Added `res.helpers()` as alias of `res.locals()` + * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` + * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] + * Renamed "cache views" to "view cache". Closes #628 + * Fixed caching of views when using several apps. Closes #637 + * Fixed gotcha invoking `app.param()` callbacks once per route middleware. +Closes #638 + * Fixed partial lookup precedence. Closes #631 +Shaw] + +2.2.2 / 2011-04-12 +================== + + * Added second callback support for `res.download()` connection errors + * Fixed `filename` option passing to template engine + +2.2.1 / 2011-04-04 +================== + + * Added `layout(path)` helper to change the layout within a view. Closes #610 + * Fixed `partial()` collection object support. + Previously only anything with `.length` would work. + When `.length` is present one must still be aware of holes, + however now `{ collection: {foo: 'bar'}}` is valid, exposes + `keyInCollection` and `keysInCollection`. + + * Performance improved with better view caching + * Removed `request` and `response` locals + * Changed; errorHandler page title is now `Express` instead of `Connect` + +2.2.0 / 2011-03-30 +================== + + * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 + * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 + * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. + * Dependency `connect >= 1.2.0` + +2.1.1 / 2011-03-29 +================== + + * Added; expose `err.view` object when failing to locate a view + * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] + * Fixed; `res.send(undefined)` responds with 204 [aheckmann] + +2.1.0 / 2011-03-24 +================== + + * Added `/_?` partial lookup support. Closes #447 + * Added `request`, `response`, and `app` local variables + * Added `settings` local variable, containing the app's settings + * Added `req.flash()` exception if `req.session` is not available + * Added `res.send(bool)` support (json response) + * Fixed stylus example for latest version + * Fixed; wrap try/catch around `res.render()` + +2.0.0 / 2011-03-17 +================== + + * Fixed up index view path alternative. + * Changed; `res.locals()` without object returns the locals + +2.0.0rc3 / 2011-03-17 +================== + + * Added `res.locals(obj)` to compliment `res.local(key, val)` + * Added `res.partial()` callback support + * Fixed recursive error reporting issue in `res.render()` + +2.0.0rc2 / 2011-03-17 +================== + + * Changed; `partial()` "locals" are now optional + * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] + * Fixed .filename view engine option [reported by drudge] + * Fixed blog example + * Fixed `{req,res}.app` reference when mounting [Ben Weaver] + +2.0.0rc / 2011-03-14 +================== + + * Fixed; expose `HTTPSServer` constructor + * Fixed express(1) default test charset. Closes #579 [reported by secoif] + * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] + +2.0.0beta3 / 2011-03-09 +================== + + * Added support for `res.contentType()` literal + The original `res.contentType('.json')`, + `res.contentType('application/json')`, and `res.contentType('json')` + will work now. + * Added `res.render()` status option support back + * Added charset option for `res.render()` + * Added `.charset` support (via connect 1.0.4) + * Added view resolution hints when in development and a lookup fails + * Added layout lookup support relative to the page view. + For example while rendering `./views/user/index.jade` if you create + `./views/user/layout.jade` it will be used in favour of the root layout. + * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] + * Fixed; default `res.send()` string charset to utf8 + * Removed `Partial` constructor (not currently used) + +2.0.0beta2 / 2011-03-07 +================== + + * Added res.render() `.locals` support back to aid in migration process + * Fixed flash example + +2.0.0beta / 2011-03-03 +================== + + * Added HTTPS support + * Added `res.cookie()` maxAge support + * Added `req.header()` _Referrer_ / _Referer_ special-case, either works + * Added mount support for `res.redirect()`, now respects the mount-point + * Added `union()` util, taking place of `merge(clone())` combo + * Added stylus support to express(1) generated app + * Added secret to session middleware used in examples and generated app + * Added `res.local(name, val)` for progressive view locals + * Added default param support to `req.param(name, default)` + * Added `app.disabled()` and `app.enabled()` + * Added `app.register()` support for omitting leading ".", either works + * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 + * Added `app.param()` to map route params to async/sync logic + * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 + * Added extname with no leading "." support to `res.contentType()` + * Added `cache views` setting, defaulting to enabled in "production" env + * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. + * Added `req.accepts()` support for extensions + * Changed; `res.download()` and `res.sendfile()` now utilize Connect's + static file server `connect.static.send()`. + * Changed; replaced `connect.utils.mime()` with npm _mime_ module + * Changed; allow `req.query` to be pre-defined (via middleware or other parent + * Changed view partial resolution, now relative to parent view + * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. + * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 + * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` + * Fixed; using _qs_ module instead of _querystring_ + * Fixed; strip unsafe chars from jsonp callbacks + * Removed "stream threshold" setting + +1.0.8 / 2011-03-01 +================== + + * Allow `req.query` to be pre-defined (via middleware or other parent app) + * "connect": ">= 0.5.0 < 1.0.0". Closes #547 + * Removed the long deprecated __EXPRESS_ENV__ support + +1.0.7 / 2011-02-07 +================== + + * Fixed `render()` setting inheritance. + Mounted apps would not inherit "view engine" + +1.0.6 / 2011-02-07 +================== + + * Fixed `view engine` setting bug when period is in dirname + +1.0.5 / 2011-02-05 +================== + + * Added secret to generated app `session()` call + +1.0.4 / 2011-02-05 +================== + + * Added `qs` dependency to _package.json_ + * Fixed namespaced `require()`s for latest connect support + +1.0.3 / 2011-01-13 +================== + + * Remove unsafe characters from JSONP callback names [Ryan Grove] + +1.0.2 / 2011-01-10 +================== + + * Removed nested require, using `connect.router` + +1.0.1 / 2010-12-29 +================== + + * Fixed for middleware stacked via `createServer()` + previously the `foo` middleware passed to `createServer(foo)` + would not have access to Express methods such as `res.send()` + or props like `req.query` etc. + +1.0.0 / 2010-11-16 +================== + + * Added; deduce partial object names from the last segment. + For example by default `partial('forum/post', postObject)` will + give you the _post_ object, providing a meaningful default. + * Added http status code string representation to `res.redirect()` body + * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. + * Added `req.is()` to aid in content negotiation + * Added partial local inheritance [suggested by masylum]. Closes #102 + providing access to parent template locals. + * Added _-s, --session[s]_ flag to express(1) to add session related middleware + * Added _--template_ flag to express(1) to specify the + template engine to use. + * Added _--css_ flag to express(1) to specify the + stylesheet engine to use (or just plain css by default). + * Added `app.all()` support [thanks aheckmann] + * Added partial direct object support. + You may now `partial('user', user)` providing the "user" local, + vs previously `partial('user', { object: user })`. + * Added _route-separation_ example since many people question ways + to do this with CommonJS modules. Also view the _blog_ example for + an alternative. + * Performance; caching view path derived partial object names + * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 + * Fixed jsonp support; _text/javascript_ as per mailinglist discussion + +1.0.0rc4 / 2010-10-14 +================== + + * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 + * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) + * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] + * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] + * Added `partial()` support for array-like collections. Closes #434 + * Added support for swappable querystring parsers + * Added session usage docs. Closes #443 + * Added dynamic helper caching. Closes #439 [suggested by maritz] + * Added authentication example + * Added basic Range support to `res.sendfile()` (and `res.download()` etc) + * Changed; `express(1)` generated app using 2 spaces instead of 4 + * Default env to "development" again [aheckmann] + * Removed _context_ option is no more, use "scope" + * Fixed; exposing _./support_ libs to examples so they can run without installs + * Fixed mvc example + +1.0.0rc3 / 2010-09-20 +================== + + * Added confirmation for `express(1)` app generation. Closes #391 + * Added extending of flash formatters via `app.flashFormatters` + * Added flash formatter support. Closes #411 + * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" + * Added _stream threshold_ setting for `res.sendfile()` + * Added `res.send()` __HEAD__ support + * Added `res.clearCookie()` + * Added `res.cookie()` + * Added `res.render()` headers option + * Added `res.redirect()` response bodies + * Added `res.render()` status option support. Closes #425 [thanks aheckmann] + * Fixed `res.sendfile()` responding with 403 on malicious path + * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ + * Fixed; mounted apps settings now inherit from parent app [aheckmann] + * Fixed; stripping Content-Length / Content-Type when 204 + * Fixed `res.send()` 204. Closes #419 + * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 + * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] + + +1.0.0rc2 / 2010-08-17 +================== + + * Added `app.register()` for template engine mapping. Closes #390 + * Added `res.render()` callback support as second argument (no options) + * Added callback support to `res.download()` + * Added callback support for `res.sendfile()` + * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` + * Added "partials" setting to docs + * Added default expresso tests to `express(1)` generated app. Closes #384 + * Fixed `res.sendfile()` error handling, defer via `next()` + * Fixed `res.render()` callback when a layout is used [thanks guillermo] + * Fixed; `make install` creating ~/.node_libraries when not present + * Fixed issue preventing error handlers from being defined anywhere. Closes #387 + +1.0.0rc / 2010-07-28 +================== + + * Added mounted hook. Closes #369 + * Added connect dependency to _package.json_ + + * Removed "reload views" setting and support code + development env never caches, production always caches. + + * Removed _param_ in route callbacks, signature is now + simply (req, res, next), previously (req, res, params, next). + Use _req.params_ for path captures, _req.query_ for GET params. + + * Fixed "home" setting + * Fixed middleware/router precedence issue. Closes #366 + * Fixed; _configure()_ callbacks called immediately. Closes #368 + +1.0.0beta2 / 2010-07-23 +================== + + * Added more examples + * Added; exporting `Server` constructor + * Added `Server#helpers()` for view locals + * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 + * Added support for absolute view paths + * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 + * Added Guillermo Rauch to the contributor list + * Added support for "as" for non-collection partials. Closes #341 + * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] + * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] + * Fixed instanceof `Array` checks, now `Array.isArray()` + * Fixed express(1) expansion of public dirs. Closes #348 + * Fixed middleware precedence. Closes #345 + * Fixed view watcher, now async [thanks aheckmann] + +1.0.0beta / 2010-07-15 +================== + + * Re-write + - much faster + - much lighter + - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs + +0.14.0 / 2010-06-15 +================== + + * Utilize relative requires + * Added Static bufferSize option [aheckmann] + * Fixed caching of view and partial subdirectories [aheckmann] + * Fixed mime.type() comments now that ".ext" is not supported + * Updated haml submodule + * Updated class submodule + * Removed bin/express + +0.13.0 / 2010-06-01 +================== + + * Added node v0.1.97 compatibility + * Added support for deleting cookies via Request#cookie('key', null) + * Updated haml submodule + * Fixed not-found page, now using using charset utf-8 + * Fixed show-exceptions page, now using using charset utf-8 + * Fixed view support due to fs.readFile Buffers + * Changed; mime.type() no longer accepts ".type" due to node extname() changes + +0.12.0 / 2010-05-22 +================== + + * Added node v0.1.96 compatibility + * Added view `helpers` export which act as additional local variables + * Updated haml submodule + * Changed ETag; removed inode, modified time only + * Fixed LF to CRLF for setting multiple cookies + * Fixed cookie complation; values are now urlencoded + * Fixed cookies parsing; accepts quoted values and url escaped cookies + +0.11.0 / 2010-05-06 +================== + + * Added support for layouts using different engines + - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) + - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' + - this.render('page.html.haml', { layout: false }) // no layout + * Updated ext submodule + * Updated haml submodule + * Fixed EJS partial support by passing along the context. Issue #307 + +0.10.1 / 2010-05-03 +================== + + * Fixed binary uploads. + +0.10.0 / 2010-04-30 +================== + + * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s + encoding is set to 'utf8' or 'utf-8'. + * Added "encoding" option to Request#render(). Closes #299 + * Added "dump exceptions" setting, which is enabled by default. + * Added simple ejs template engine support + * Added error response support for text/plain, application/json. Closes #297 + * Added callback function param to Request#error() + * Added Request#sendHead() + * Added Request#stream() + * Added support for Request#respond(304, null) for empty response bodies + * Added ETag support to Request#sendfile() + * Added options to Request#sendfile(), passed to fs.createReadStream() + * Added filename arg to Request#download() + * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request + * Performance enhanced by preventing several calls to toLowerCase() in Router#match() + * Changed; Request#sendfile() now streams + * Changed; Renamed Request#halt() to Request#respond(). Closes #289 + * Changed; Using sys.inspect() instead of JSON.encode() for error output + * Changed; run() returns the http.Server instance. Closes #298 + * Changed; Defaulting Server#host to null (INADDR_ANY) + * Changed; Logger "common" format scale of 0.4f + * Removed Logger "request" format + * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found + * Fixed several issues with http client + * Fixed Logger Content-Length output + * Fixed bug preventing Opera from retaining the generated session id. Closes #292 + +0.9.0 / 2010-04-14 +================== + + * Added DSL level error() route support + * Added DSL level notFound() route support + * Added Request#error() + * Added Request#notFound() + * Added Request#render() callback function. Closes #258 + * Added "max upload size" setting + * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 + * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js + * Added callback function support to Request#halt() as 3rd/4th arg + * Added preprocessing of route param wildcards using param(). Closes #251 + * Added view partial support (with collections etc) + * Fixed bug preventing falsey params (such as ?page=0). Closes #286 + * Fixed setting of multiple cookies. Closes #199 + * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) + * Changed; session cookie is now httpOnly + * Changed; Request is no longer global + * Changed; Event is no longer global + * Changed; "sys" module is no longer global + * Changed; moved Request#download to Static plugin where it belongs + * Changed; Request instance created before body parsing. Closes #262 + * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 + * Changed; Pre-caching view partials in memory when "cache view partials" is enabled + * Updated support to node --version 0.1.90 + * Updated dependencies + * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) + * Removed utils.mixin(); use Object#mergeDeep() + +0.8.0 / 2010-03-19 +================== + + * Added coffeescript example app. Closes #242 + * Changed; cache api now async friendly. Closes #240 + * Removed deprecated 'express/static' support. Use 'express/plugins/static' + +0.7.6 / 2010-03-19 +================== + + * Added Request#isXHR. Closes #229 + * Added `make install` (for the executable) + * Added `express` executable for setting up simple app templates + * Added "GET /public/*" to Static plugin, defaulting to /public + * Added Static plugin + * Fixed; Request#render() only calls cache.get() once + * Fixed; Namespacing View caches with "view:" + * Fixed; Namespacing Static caches with "static:" + * Fixed; Both example apps now use the Static plugin + * Fixed set("views"). Closes #239 + * Fixed missing space for combined log format + * Deprecated Request#sendfile() and 'express/static' + * Removed Server#running + +0.7.5 / 2010-03-16 +================== + + * Added Request#flash() support without args, now returns all flashes + * Updated ext submodule + +0.7.4 / 2010-03-16 +================== + + * Fixed session reaper + * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) + +0.7.3 / 2010-03-16 +================== + + * Added package.json + * Fixed requiring of haml / sass due to kiwi removal + +0.7.2 / 2010-03-16 +================== + + * Fixed GIT submodules (HAH!) + +0.7.1 / 2010-03-16 +================== + + * Changed; Express now using submodules again until a PM is adopted + * Changed; chat example using millisecond conversions from ext + +0.7.0 / 2010-03-15 +================== + + * Added Request#pass() support (finds the next matching route, or the given path) + * Added Logger plugin (default "common" format replaces CommonLogger) + * Removed Profiler plugin + * Removed CommonLogger plugin + +0.6.0 / 2010-03-11 +================== + + * Added seed.yml for kiwi package management support + * Added HTTP client query string support when method is GET. Closes #205 + + * Added support for arbitrary view engines. + For example "foo.engine.html" will now require('engine'), + the exports from this module are cached after the first require(). + + * Added async plugin support + + * Removed usage of RESTful route funcs as http client + get() etc, use http.get() and friends + + * Removed custom exceptions + +0.5.0 / 2010-03-10 +================== + + * Added ext dependency (library of js extensions) + * Removed extname() / basename() utils. Use path module + * Removed toArray() util. Use arguments.values + * Removed escapeRegexp() util. Use RegExp.escape() + * Removed process.mixin() dependency. Use utils.mixin() + * Removed Collection + * Removed ElementCollection + * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) + +0.4.0 / 2010-02-11 +================== + + * Added flash() example to sample upload app + * Added high level restful http client module (express/http) + * Changed; RESTful route functions double as HTTP clients. Closes #69 + * Changed; throwing error when routes are added at runtime + * Changed; defaulting render() context to the current Request. Closes #197 + * Updated haml submodule + +0.3.0 / 2010-02-11 +================== + + * Updated haml / sass submodules. Closes #200 + * Added flash message support. Closes #64 + * Added accepts() now allows multiple args. fixes #117 + * Added support for plugins to halt. Closes #189 + * Added alternate layout support. Closes #119 + * Removed Route#run(). Closes #188 + * Fixed broken specs due to use(Cookie) missing + +0.2.1 / 2010-02-05 +================== + + * Added "plot" format option for Profiler (for gnuplot processing) + * Added request number to Profiler plugin + * Fixed binary encoding for multi-part file uploads, was previously defaulting to UTF8 + * Fixed issue with routes not firing when not files are present. Closes #184 + * Fixed process.Promise -> events.Promise + +0.2.0 / 2010-02-03 +================== + + * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 + * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 + * Added expiration support to cache api with reaper. Closes #133 + * Added cache Store.Memory#reap() + * Added Cache; cache api now uses first class Cache instances + * Added abstract session Store. Closes #172 + * Changed; cache Memory.Store#get() utilizing Collection + * Renamed MemoryStore -> Store.Memory + * Fixed use() of the same plugin several time will always use latest options. Closes #176 + +0.1.0 / 2010-02-03 +================== + + * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context + * Updated node support to 0.1.27 Closes #169 + * Updated dirname(__filename) -> __dirname + * Updated libxmljs support to v0.2.0 + * Added session support with memory store / reaping + * Added quick uid() helper + * Added multi-part upload support + * Added Sass.js support / submodule + * Added production env caching view contents and static files + * Added static file caching. Closes #136 + * Added cache plugin with memory stores + * Added support to StaticFile so that it works with non-textual files. + * Removed dirname() helper + * Removed several globals (now their modules must be required) + +0.0.2 / 2010-01-10 +================== + + * Added view benchmarks; currently haml vs ejs + * Added Request#attachment() specs. Closes #116 + * Added use of node's parseQuery() util. Closes #123 + * Added `make init` for submodules + * Updated Haml + * Updated sample chat app to show messages on load + * Updated libxmljs parseString -> parseHtmlString + * Fixed `make init` to work with older versions of git + * Fixed specs can now run independent specs for those who cant build deps. Closes #127 + * Fixed issues introduced by the node url module changes. Closes 126. + * Fixed two assertions failing due to Collection#keys() returning strings + * Fixed faulty Collection#toArray() spec due to keys() returning strings + * Fixed `make test` now builds libxmljs.node before testing + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/app/node_modules/express/LICENSE b/app/node_modules/express/LICENSE new file mode 100644 index 0000000..aa927e4 --- /dev/null +++ b/app/node_modules/express/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2009-2014 TJ Holowaychuk +Copyright (c) 2013-2014 Roman Shtylman +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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/app/node_modules/express/Readme.md b/app/node_modules/express/Readme.md new file mode 100644 index 0000000..582e895 --- /dev/null +++ b/app/node_modules/express/Readme.md @@ -0,0 +1,153 @@ +[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/) + + Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). + + [![NPM Version][npm-image]][npm-url] + [![NPM Downloads][downloads-image]][downloads-url] + [![Linux Build][travis-image]][travis-url] + [![Windows Build][appveyor-image]][appveyor-url] + [![Test Coverage][coveralls-image]][coveralls-url] + +```js +var express = require('express') +var app = express() + +app.get('/', function (req, res) { + res.send('Hello World') +}) + +app.listen(3000) +``` + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). + +Before installing, [download and install Node.js](https://nodejs.org/en/download/). +Node.js 0.10 or higher is required. + +Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install express +``` + +Follow [our installing guide](http://expressjs.com/en/starter/installing.html) +for more information. + +## Features + + * Robust routing + * Focus on high performance + * Super-high test coverage + * HTTP helpers (redirection, caching, etc) + * View system supporting 14+ template engines + * Content negotiation + * Executable for generating applications quickly + +## Docs & Community + + * [Website and Documentation](http://expressjs.com/) - [[website repo](https://github.com/expressjs/expressjs.com)] + * [#express](https://webchat.freenode.net/?channels=express) on freenode IRC + * [GitHub Organization](https://github.com/expressjs) for Official Middleware & Modules + * Visit the [Wiki](https://github.com/expressjs/express/wiki) + * [Google Group](https://groups.google.com/group/express-js) for discussion + * [Gitter](https://gitter.im/expressjs/express) for support and discussion + +**PROTIP** Be sure to read [Migrating from 3.x to 4.x](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x) as well as [New features in 4.x](https://github.com/expressjs/express/wiki/New-features-in-4.x). + +### Security Issues + +If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md). + +## Quick Start + + The quickest way to get started with express is to utilize the executable [`express(1)`](https://github.com/expressjs/generator) to generate an application as shown below: + + Install the executable. The executable's major version will match Express's: + +```bash +$ npm install -g express-generator@4 +``` + + Create the app: + +```bash +$ express /tmp/foo && cd /tmp/foo +``` + + Install dependencies: + +```bash +$ npm install +``` + + Start the server: + +```bash +$ npm start +``` + +## Philosophy + + The Express philosophy is to provide small, robust tooling for HTTP servers, making + it a great solution for single page applications, web sites, hybrids, or public + HTTP APIs. + + Express does not force you to use any specific ORM or template engine. With support for over + 14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js), + you can quickly craft your perfect framework. + +## Examples + + To view the examples, clone the Express repo and install the dependencies: + +```bash +$ git clone git://github.com/expressjs/express.git --depth 1 +$ cd express +$ npm install +``` + + Then run whichever example you want: + +```bash +$ node examples/content-negotiation +``` + +## Tests + + To run the test suite, first install the dependencies, then run `npm test`: + +```bash +$ npm install +$ npm test +``` + +## People + +The original author of Express is [TJ Holowaychuk](https://github.com/tj) + +The current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson) + +[List of all contributors](https://github.com/expressjs/express/graphs/contributors) + +## License + + [MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/express.svg +[npm-url]: https://npmjs.org/package/express +[downloads-image]: https://img.shields.io/npm/dm/express.svg +[downloads-url]: https://npmjs.org/package/express +[travis-image]: https://img.shields.io/travis/expressjs/express/master.svg?label=linux +[travis-url]: https://travis-ci.org/expressjs/express +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/express/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/express +[coveralls-image]: https://img.shields.io/coveralls/expressjs/express/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master +[gratipay-image-visionmedia]: https://img.shields.io/gratipay/visionmedia.svg +[gratipay-url-visionmedia]: https://gratipay.com/visionmedia/ +[gratipay-image-dougwilson]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url-dougwilson]: https://gratipay.com/dougwilson/ diff --git a/app/node_modules/express/index.js b/app/node_modules/express/index.js new file mode 100644 index 0000000..d219b0c --- /dev/null +++ b/app/node_modules/express/index.js @@ -0,0 +1,11 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +module.exports = require('./lib/express'); diff --git a/app/node_modules/express/lib/application.js b/app/node_modules/express/lib/application.js new file mode 100644 index 0000000..91f77d2 --- /dev/null +++ b/app/node_modules/express/lib/application.js @@ -0,0 +1,644 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var finalhandler = require('finalhandler'); +var Router = require('./router'); +var methods = require('methods'); +var middleware = require('./middleware/init'); +var query = require('./middleware/query'); +var debug = require('debug')('express:application'); +var View = require('./view'); +var http = require('http'); +var compileETag = require('./utils').compileETag; +var compileQueryParser = require('./utils').compileQueryParser; +var compileTrust = require('./utils').compileTrust; +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var merge = require('utils-merge'); +var resolve = require('path').resolve; +var setPrototypeOf = require('setprototypeof') +var slice = Array.prototype.slice; + +/** + * Application prototype. + */ + +var app = exports = module.exports = {}; + +/** + * Variable for trust proxy inheritance back-compat + * @private + */ + +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + +/** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private + */ + +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; + + this.defaultConfiguration(); +}; + +/** + * Initialize application configuration. + * @private + */ + +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; + + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + this.set('subdomain offset', 2); + this.set('trust proxy', false); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); + + debug('booting in %s mode', env); + + this.on('mount', function onmount(parent) { + // inherit trust proxy + if (this.settings[trustProxyDefaultSymbol] === true + && typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy']; + delete this.settings['trust proxy fn']; + } + + // inherit protos + setPrototypeOf(this.request, parent.request) + setPrototypeOf(this.response, parent.response) + setPrototypeOf(this.engines, parent.engines) + setPrototypeOf(this.settings, parent.settings) + }); + + // setup locals + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; + + // default locals + this.locals.settings = this.settings; + + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); + } + + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); +}; + +/** + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @private + */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); + + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } +}; + +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private + */ + +app.handle = function handle(req, res, callback) { + var router = this._router; + + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); + + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } + + router.handle(req, res, done); +}; + +/** + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @public + */ + +app.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var fns = flatten(slice.call(arguments, offset)); + + if (fns.length === 0) { + throw new TypeError('app.use() requires a middleware function') + } + + // setup router + this.lazyrouter(); + var router = this._router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } + + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + setPrototypeOf(req, orig.request) + setPrototypeOf(res, orig.response) + next(err); + }); + }); + + // mounted an app + fn.emit('mount', this); + }, this); + + return this; +}; + +/** + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. + * + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * + * @public + */ + +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; + +/** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.ejs" file Express will invoke the following internally: + * + * app.engine('ejs', require('ejs').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } + + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; + + // store engine + this.engines[extension] = fn; + + return this; +}; + +/** + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.param = function param(name, fn) { + this.lazyrouter(); + + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); + } + + return this; + } + + this._router.param(name, fn); + + return this; +}; + +/** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.set('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public + */ + +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; + } + + debug('set "%s" to %o', setting, val); + + // set value + this.settings[setting] = val; + + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + + break; + } + + return this; +}; + +/** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + * + * @return {String} + * @private + */ + +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; + +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; + +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.disabled = function disabled(setting) { + return !this.set(setting); +}; + +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.enable = function enable(setting) { + return this.set(setting, true); +}; + +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.disable = function disable(setting) { + return this.set(setting, false); +}; + +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ + +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } + + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +/** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param {String} path + * @param {Function} ... + * @return {app} for chaining + * @public + */ + +app.all = function all(path) { + this.lazyrouter(); + + var route = this._router.route(path); + var args = slice.call(arguments, 1); + + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } + + return this; +}; + +// del -> delete alias + +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + +/** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback + * @public + */ + +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge app.locals + merge(renderOptions, this.locals); + + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } + + // merge options + merge(renderOptions, opts); + + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } + + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } + + // view + if (!view) { + var View = this.get('view'); + + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); + + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } + + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } + + // render + tryRender(view, renderOptions, done); +}; + +/** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @public + */ + +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; + +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ + +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} + +/** + * Try rendering a view. + * @private + */ + +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } +} diff --git a/app/node_modules/express/lib/express.js b/app/node_modules/express/lib/express.js new file mode 100644 index 0000000..594007b --- /dev/null +++ b/app/node_modules/express/lib/express.js @@ -0,0 +1,114 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var bodyParser = require('body-parser') +var EventEmitter = require('events').EventEmitter; +var mixin = require('merge-descriptors'); +var proto = require('./application'); +var Route = require('./router/route'); +var Router = require('./router'); +var req = require('./request'); +var res = require('./response'); + +/** + * Expose `createApplication()`. + */ + +exports = module.exports = createApplication; + +/** + * Create an express application. + * + * @return {Function} + * @api public + */ + +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; + + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); + + // expose the prototype that will get set on requests + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + // expose the prototype that will get set on responses + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + app.init(); + return app; +} + +/** + * Expose the prototypes. + */ + +exports.application = proto; +exports.request = req; +exports.response = res; + +/** + * Expose constructors. + */ + +exports.Route = Route; +exports.Router = Router; + +/** + * Expose middleware + */ + +exports.json = bodyParser.json +exports.query = require('./middleware/query'); +exports.static = require('serve-static'); +exports.urlencoded = bodyParser.urlencoded + +/** + * Replace removed middleware with an appropriate error message. + */ + +var removedMiddlewares = [ + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache' +] + +removedMiddlewares.forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); diff --git a/app/node_modules/express/lib/middleware/init.js b/app/node_modules/express/lib/middleware/init.js new file mode 100644 index 0000000..dfd0427 --- /dev/null +++ b/app/node_modules/express/lib/middleware/init.js @@ -0,0 +1,43 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var setPrototypeOf = require('setprototypeof') + +/** + * Initialization middleware, exposing the + * request and response to each other, as well + * as defaulting the X-Powered-By header field. + * + * @param {Function} app + * @return {Function} + * @api private + */ + +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; + + setPrototypeOf(req, app.request) + setPrototypeOf(res, app.response) + + res.locals = res.locals || Object.create(null); + + next(); + }; +}; + diff --git a/app/node_modules/express/lib/middleware/query.js b/app/node_modules/express/lib/middleware/query.js new file mode 100644 index 0000000..7e91669 --- /dev/null +++ b/app/node_modules/express/lib/middleware/query.js @@ -0,0 +1,47 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var merge = require('utils-merge') +var parseUrl = require('parseurl'); +var qs = require('qs'); + +/** + * @param {Object} options + * @return {Function} + * @api public + */ + +module.exports = function query(options) { + var opts = merge({}, options) + var queryparse = qs.parse; + + if (typeof options === 'function') { + queryparse = options; + opts = undefined; + } + + if (opts !== undefined && opts.allowPrototypes === undefined) { + // back-compat for qs module + opts.allowPrototypes = true; + } + + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } + + next(); + }; +}; diff --git a/app/node_modules/express/lib/request.js b/app/node_modules/express/lib/request.js new file mode 100644 index 0000000..8bb86a9 --- /dev/null +++ b/app/node_modules/express/lib/request.js @@ -0,0 +1,521 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var accepts = require('accepts'); +var deprecate = require('depd')('express'); +var isIP = require('net').isIP; +var typeis = require('type-is'); +var http = require('http'); +var fresh = require('fresh'); +var parseRange = require('range-parser'); +var parse = require('parseurl'); +var proxyaddr = require('proxy-addr'); + +/** + * Request prototype. + * @public + */ + +var req = Object.create(http.IncomingMessage.prototype) + +/** + * Module exports. + * @public + */ + +module.exports = req + +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public + */ + +req.get = +req.header = function header(name) { + if (!name) { + throw new TypeError('name argument is required to req.get'); + } + + if (typeof name !== 'string') { + throw new TypeError('name must be a string to req.get'); + } + + var lc = name.toLowerCase(); + + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } +}; + +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given, the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; + +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ + +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; + +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); + +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ + +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; + +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); + +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ + +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; + +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); + +/** + * Parse Range header field, capping to the given `size`. + * + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. If the + * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, + * and `-2` when syntactically invalid. + * + * When ranges are returned, the array has a "type" property which is the type of + * range that is required (most commonly, "bytes"). Each array element is an object + * with a "start" and "end" property for the portion of the range. + * + * The "combine" option can be set to `true` and overlapping & adjacent ranges + * will be combined into a single range. + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. + * + * @param {number} size + * @param {object} [options] + * @param {boolean} [options.combine=false] + * @return {number|array} + * @public + */ + +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); +}; + +/** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @public + */ + +req.param = function param(name, defaultValue) { + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; + + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; + + return defaultValue; +}; + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +req.is = function is(types) { + var arr = types; + + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } + + return typeis(this, arr); +}; + +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ + +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); + + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } + + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + var header = this.get('X-Forwarded-Proto') || proto + var index = header.indexOf(',') + + return index !== -1 + ? header.substring(0, index).trim() + : header.trim() +}); + +/** + * Short-hand for: + * + * req.protocol === 'https' + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); + +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ + +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); + +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); + + // reverse the order (to farthest -> closest) + // and remove socket address + addrs.reverse().pop() + + return addrs +}); + +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; + + if (!hostname) return []; + + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; + + return subdomains.slice(offset); +}); + +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ + +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); + +/** + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public + */ + +defineGetter(req, 'hostname', function hostname(){ + var trust = this.app.get('trust proxy fn'); + var host = this.get('X-Forwarded-Host'); + + if (!host || !trust(this.connection.remoteAddress, 0)) { + host = this.get('Host'); + } + + if (!host) return; + + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); + + return index !== -1 + ? host.substring(0, index) + : host; +}); + +// TODO: change req.host to return host in next major + +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); + +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'fresh', function(){ + var method = this.method; + var res = this.res + var status = res.statusCode + + // GET or HEAD for weak freshness validation only + if ('GET' !== method && 'HEAD' !== method) return false; + + // 2xx or 304 as per rfc2616 14.26 + if ((status >= 200 && status < 300) || 304 === status) { + return fresh(this.headers, { + 'etag': res.get('ETag'), + 'last-modified': res.get('Last-Modified') + }) + } + + return false; +}); + +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); + +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); + +/** + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private + */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +} diff --git a/app/node_modules/express/lib/response.js b/app/node_modules/express/lib/response.js new file mode 100644 index 0000000..2e445ac --- /dev/null +++ b/app/node_modules/express/lib/response.js @@ -0,0 +1,1137 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('safe-buffer').Buffer +var contentDisposition = require('content-disposition'); +var deprecate = require('depd')('express'); +var encodeUrl = require('encodeurl'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var isAbsolute = require('./utils').isAbsolute; +var onFinished = require('on-finished'); +var path = require('path'); +var statuses = require('statuses') +var merge = require('utils-merge'); +var sign = require('cookie-signature').sign; +var normalizeType = require('./utils').normalizeType; +var normalizeTypes = require('./utils').normalizeTypes; +var setCharset = require('./utils').setCharset; +var cookie = require('cookie'); +var send = require('send'); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = require('vary'); + +/** + * Response prototype. + * @public + */ + +var res = Object.create(http.ServerResponse.prototype) + +/** + * Module exports. + * @public + */ + +module.exports = res + +/** + * Module variables. + * @private + */ + +var charsetRegExp = /;\s*charset\s*=/; + +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public + */ + +res.status = function status(code) { + this.statusCode = code; + return this; +}; + +/** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param {Object} links + * @return {ServerResponse} + * @public + */ + +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; + +/** + * Send a response. + * + * Examples: + * + * res.send(Buffer.from('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * + * @param {string|number|boolean|object|Buffer} body + * @public + */ + +res.send = function send(body) { + var chunk = body; + var encoding; + var req = this.req; + var type; + + // settings + var app = this.app; + + // allow status / body + if (arguments.length === 2) { + // res.send(body, status) backwards compat + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; + } + } + + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); + } + + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statuses[chunk] + } + + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; + } + + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); + + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } + + // determine if ETag should be generated + var etagFn = app.get('etag fn') + var generateETag = !this.get('ETag') && typeof etagFn === 'function' + + // populate Content-Length + var len + if (chunk !== undefined) { + if (Buffer.isBuffer(chunk)) { + // get length of Buffer + len = chunk.length + } else if (!generateETag && chunk.length < 1000) { + // just calculate length when no ETag + small chunk + len = Buffer.byteLength(chunk, encoding) + } else { + // convert chunk to Buffer and calculate + chunk = Buffer.from(chunk, encoding) + encoding = undefined; + len = chunk.length + } + + this.set('Content-Length', len); + } + + // populate ETag + var etag; + if (generateETag && len !== undefined) { + if ((etag = etagFn(chunk, encoding))) { + this.set('ETag', etag); + } + } + + // freshness + if (req.fresh) this.statusCode = 304; + + // strip irrelevant headers + if (204 === this.statusCode || 304 === this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } + + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } + + return this; +}; + +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.json = function json(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } + + return this.send(body); +}; + +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.jsonp = function jsonp(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + var callback = this.req.query[app.get('jsonp callback name')]; + + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } + + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } + + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); + + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); + + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); + + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + } + + return this.send(body); +}; + +/** + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @public + */ + +res.sendStatus = function sendStatus(statusCode) { + var body = statuses[statusCode] || String(statusCode) + + this.statusCode = statusCode; + this.type('txt'); + + return this.send(body); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); + } + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + if (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } + + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // create file stream + var file = send(req, path, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); + +/** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. + * + * Optionally providing an `options` object to use with `res.sendFile()`. + * This function will set the `Content-Disposition` header, overriding + * any `Content-Disposition` header passed as header options in order + * to set the attachment and filename. + * + * This method uses `res.sendFile()`. + * + * @public + */ + +res.download = function download (path, filename, options, callback) { + var done = callback; + var name = filename; + var opts = options || null + + // support function as second or third arg + if (typeof filename === 'function') { + done = filename; + name = null; + opts = null + } else if (typeof options === 'function') { + done = options + opts = null + } + + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; + + // merge user-provided headers + if (opts && opts.headers) { + var keys = Object.keys(opts.headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key.toLowerCase() !== 'content-disposition') { + headers[key] = opts.headers[key] + } + } + } + + // merge user-provided options + opts = Object.create(opts) + opts.headers = headers + + // Resolve the full path for sendFile + var fullPath = resolve(path); + + // send file + return this.sendFile(fullPath, opts, done) +}; + +/** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param {String} type + * @return {ServerResponse} for chaining + * @public + */ + +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; + + return this.set('Content-Type', ct); +}; + +/** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param {Object} obj + * @return {ServerResponse} for chaining + * @public + */ + +res.format = function(obj){ + var req = this.req; + var next = req.next; + + var fn = obj.default; + if (fn) delete obj.default; + var keys = Object.keys(obj); + + var key = keys.length > 0 + ? req.accepts(keys) + : false; + + this.vary("Accept"); + + if (key) { + this.set('Content-Type', normalizeType(key).value); + obj[key](req, this, next); + } else if (fn) { + fn(); + } else { + var err = new Error('Not Acceptable'); + err.status = err.statusCode = 406; + err.types = normalizeTypes(keys).map(function(o){ return o.value }); + next(err); + } + + return this; +}; + +/** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param {String} filename + * @return {ServerResponse} + * @public + */ + +res.attachment = function attachment(filename) { + if (filename) { + this.type(extname(filename)); + } + + this.set('Content-Disposition', contentDisposition(filename)); + + return this; +}; + +/** + * Append additional header `field` with value `val`. + * + * Example: + * + * res.append('Link', ['', '']); + * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * res.append('Warning', '199 Miscellaneous warning'); + * + * @param {String} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ + +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; + + if (prev) { + // concat the new and prev vals + value = Array.isArray(prev) ? prev.concat(val) + : Array.isArray(val) ? [prev].concat(val) + : [prev, val]; + } + + return this.set(field, value); +}; + +/** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + * + * @param {String|Object} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ + +res.set = +res.header = function header(field, val) { + if (arguments.length === 2) { + var value = Array.isArray(val) + ? val.map(String) + : String(val); + + // add charset to content-type + if (field.toLowerCase() === 'content-type') { + if (Array.isArray(value)) { + throw new TypeError('Content-Type cannot be set to an Array'); + } + if (!charsetRegExp.test(value)) { + var charset = mime.charsets.lookup(value.split(';')[0]); + if (charset) value += '; charset=' + charset.toLowerCase(); + } + } + + this.setHeader(field, value); + } else { + for (var key in field) { + this.set(key, field[key]); + } + } + return this; +}; + +/** + * Get value for header `field`. + * + * @param {String} field + * @return {String} + * @public + */ + +res.get = function(field){ + return this.getHeader(field); +}; + +/** + * Clear cookie `name`. + * + * @param {String} name + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ + +res.clearCookie = function clearCookie(name, options) { + var opts = merge({ expires: new Date(1), path: '/' }, options); + + return this.cookie(name, '', opts); +}; + +/** + * Set cookie `name` to `value`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // save as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + * + * @param {String} name + * @param {String|Object} value + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ + +res.cookie = function (name, value, options) { + var opts = merge({}, options); + var secret = this.req.secret; + var signed = opts.signed; + + if (signed && !secret) { + throw new Error('cookieParser("secret") required for signed cookies'); + } + + var val = typeof value === 'object' + ? 'j:' + JSON.stringify(value) + : String(value); + + if (signed) { + val = 's:' + sign(val, secret); + } + + if ('maxAge' in opts) { + opts.expires = new Date(Date.now() + opts.maxAge); + opts.maxAge /= 1000; + } + + if (opts.path == null) { + opts.path = '/'; + } + + this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); + + return this; +}; + +/** + * Set the location header to `url`. + * + * The given `url` can also be "back", which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); + * + * @param {String} url + * @return {ServerResponse} for chaining + * @public + */ + +res.location = function location(url) { + var loc = url; + + // "back" is an alias for the referrer + if (url === 'back') { + loc = this.req.get('Referrer') || '/'; + } + + // set location + return this.set('Location', encodeUrl(loc)); +}; + +/** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + * + * @public + */ + +res.redirect = function redirect(url) { + var address = url; + var body; + var status = 302; + + // allow status / url + if (arguments.length === 2) { + if (typeof arguments[0] === 'number') { + status = arguments[0]; + address = arguments[1]; + } else { + deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); + status = arguments[1]; + } + } + + // Set location header + address = this.location(address).get('Location'); + + // Support text/{plain,html} by default + this.format({ + text: function(){ + body = statuses[status] + '. Redirecting to ' + address + }, + + html: function(){ + var u = escapeHtml(address); + body = '

' + statuses[status] + '. Redirecting to ' + u + '

' + }, + + default: function(){ + body = ''; + } + }); + + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); + + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; + +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public + */ + +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } + + vary(this, field); + + return this; +}; + +/** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + * + * @public + */ + +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge res.locals + opts._locals = self.locals; + + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; + + // render + app.render(view, opts, done); +}; + +// pipe the send file stream +function sendfile(res, file, options, callback) { + var done = false; + var streaming; + + // request aborted + function onaborted() { + if (done) return; + done = true; + + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); + } + + // directory + function ondirectory() { + if (done) return; + done = true; + + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } + + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } + + // ended + function onend() { + if (done) return; + done = true; + callback(); + } + + // file + function onfile() { + streaming = false; + } + + // finished + function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); + if (err) return onerror(err); + if (done) return; + + setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } + + if (done) return; + done = true; + callback(); + }); + } + + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); + + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } + + // pipe + file.pipe(res); +} + +/** + * Stringify JSON, like JSON.stringify, but v8 optimized, with the + * ability to escape characters that can trigger HTML sniffing. + * + * @param {*} value + * @param {function} replaces + * @param {number} spaces + * @param {boolean} escape + * @returns {string} + * @private + */ + +function stringify (value, replacer, spaces, escape) { + // v8 checks arguments.length for optimizing simple call + // https://bugs.chromium.org/p/v8/issues/detail?id=4730 + var json = replacer || spaces + ? JSON.stringify(value, replacer, spaces) + : JSON.stringify(value); + + if (escape) { + json = json.replace(/[<>&]/g, function (c) { + switch (c.charCodeAt(0)) { + case 0x3c: + return '\\u003c' + case 0x3e: + return '\\u003e' + case 0x26: + return '\\u0026' + default: + return c + } + }) + } + + return json +} diff --git a/app/node_modules/express/lib/router/index.js b/app/node_modules/express/lib/router/index.js new file mode 100644 index 0000000..69e6d38 --- /dev/null +++ b/app/node_modules/express/lib/router/index.js @@ -0,0 +1,662 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Route = require('./route'); +var Layer = require('./layer'); +var methods = require('methods'); +var mixin = require('utils-merge'); +var debug = require('debug')('express:router'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var parseUrl = require('parseurl'); +var setPrototypeOf = require('setprototypeof') + +/** + * Module variables. + * @private + */ + +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Initialize a new `Router` with the given `options`. + * + * @param {Object} [options] + * @return {Router} which is an callable function + * @public + */ + +var proto = module.exports = function(options) { + var opts = options || {}; + + function router(req, res, next) { + router.handle(req, res, next); + } + + // mixin Router class functions + setPrototypeOf(router, proto) + + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; + + return router; +}; + +/** + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); + * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +proto.param = function param(name, fn) { + // param logic + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); + this._params.push(name); + return; + } + + // apply param functions + var params = this._params; + var len = params.length; + var ret; + + if (name[0] === ':') { + deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); + name = name.substr(1); + } + + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; + } + } + + // ensure we end up with a + // middleware function + if ('function' !== typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); + } + + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; + +/** + * Dispatch a req, res into the router. + * @private + */ + +proto.handle = function handle(req, res, out) { + var self = this; + + debug('dispatching %s %s', req.method, req.url); + + var idx = 0; + var protohost = getProtohost(req.url) || '' + var removed = ''; + var slashAdded = false; + var paramcalled = {}; + + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; + + // middleware and routes + var stack = self.stack; + + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); + + // setup next layer + req.next = next; + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); + } + + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; + + next(); + + function next(err) { + var layerError = err === 'route' + ? null + : err; + + // remove added slash + if (slashAdded) { + req.url = req.url.substr(1); + slashAdded = false; + } + + // restore altered req.url + if (removed.length !== 0) { + req.baseUrl = parentUrl; + req.url = protohost + removed + req.url.substr(protohost.length); + removed = ''; + } + + // signal to exit router + if (layerError === 'router') { + setImmediate(done, null) + return + } + + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; + } + + // get pathname of request + var path = getPathname(req); + + if (path == null) { + return done(layerError); + } + + // find next matching layer + var layer; + var match; + var route; + + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = matchLayer(layer, path); + route = layer.route; + + if (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match; + } + + if (match !== true) { + continue; + } + + if (!route) { + // process non-route handlers normally + continue; + } + + if (layerError) { + // routes do not match with a pending error + match = false; + continue; + } + + var method = req.method; + var has_method = route._handles_method(method); + + // build up automatic options response + if (!has_method && method === 'OPTIONS') { + appendMethods(options, route._options()); + } + + // don't even bother matching route + if (!has_method && method !== 'HEAD') { + match = false; + continue; + } + } + + // no match + if (match !== true) { + return done(layerError); + } + + // store route for dispatch on change + if (route) { + req.route = route; + } + + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params; + var layerPath = layer.path; + + // this should be done for the layer + self.process_params(layer, paramcalled, req, res, function (err) { + if (err) { + return next(layerError || err); + } + + if (route) { + return layer.handle_request(req, res, next); + } + + trim_prefix(layer, layerError, layerPath, path); + }); + } + + function trim_prefix(layer, layerError, layerPath, path) { + if (layerPath.length !== 0) { + // Validate path breaks on a path separator + var c = path[layerPath.length] + if (c && c !== '/' && c !== '.') return next(layerError) + + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.substr(protohost.length + removed.length); + + // Ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); + } + + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Process any parameters for the layer. + * @private + */ + +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; + + // captured parameters from the layer, keys and values + var keys = layer.keys; + + // fast track + if (!keys || keys.length === 0) { + return done(); + } + + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; + + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } + + if (i >= keys.length ) { + return done(); + } + + paramIndex = 0; + key = keys[i++]; + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; + + if (paramVal === undefined || !paramCallbacks) { + return param(); + } + + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal + || (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[name] = paramCalled.value; + + // next param + return param(paramCalled.error); + } + + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; + + paramCallback(); + } + + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; + + // store updated value + paramCalled.value = req.params[key.name]; + + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } + + if (!fn) return param(); + + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } + } + + param(); +}; + +/** + * Use the given middleware function, with optional path, defaulting to "/". + * + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public + */ + +proto.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var callbacks = flatten(slice.call(arguments, offset)); + + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires a middleware function') + } + + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; + + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) + } + + // add the middleware + debug('use %o %s', path, fn.name || '') + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); + + layer.route = undefined; + + this.stack.push(layer); + } + + return this; +}; + +/** + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {String} path + * @return {Route} + * @public + */ + +proto.route = function route(path) { + var route = new Route(path); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); + + layer.route = route; + + this.stack.push(layer); + return route; +}; + +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +// append methods to a list of methods +function appendMethods(list, addition) { + for (var i = 0; i < addition.length; i++) { + var method = addition[i]; + if (list.indexOf(method) === -1) { + list.push(method); + } + } +} + +// get pathname of request +function getPathname(req) { + try { + return parseUrl(req).pathname; + } catch (err) { + return undefined; + } +} + +// Get get protocol + host for a URL +function getProtohost(url) { + if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { + return undefined + } + + var searchIndex = url.indexOf('?') + var pathLength = searchIndex !== -1 + ? searchIndex + : url.length + var fqdnIndex = url.substr(0, pathLength).indexOf('://') + + return fqdnIndex !== -1 + ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined +} + +// get type for error message +function gettype(obj) { + var type = typeof obj; + + if (type !== 'object') { + return type; + } + + // inspect [[Class]] for objects + return toString.call(obj) + .replace(objectRegExp, '$1'); +} + +/** + * Match path to a layer. + * + * @param {Layer} layer + * @param {string} path + * @private + */ + +function matchLayer(layer, path) { + try { + return layer.match(path); + } catch (err) { + return err; + } +} + +// merge params with parent params +function mergeParams(params, parent) { + if (typeof parent !== 'object' || !parent) { + return params; + } + + // make copy of parent for base + var obj = mixin({}, parent); + + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } + + var i = 0; + var o = 0; + + // determine numeric gaps + while (i in params) { + i++; + } + + while (o in parent) { + o++; + } + + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; + + // create holes for the merge when necessary + if (i < o) { + delete params[i]; + } + } + + return mixin(obj, params); +} + +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); + + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; + } + + return function () { + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } + + return fn.apply(this, arguments); + }; +} + +// send an OPTIONS response +function sendOptionsResponse(res, options, next) { + try { + var body = options.join(','); + res.set('Allow', body); + res.send(body); + } catch (err) { + next(err); + } +} + +// wrap a function +function wrap(old, fn) { + return function proxy() { + var args = new Array(arguments.length + 1); + + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } + + fn.apply(this, args); + }; +} diff --git a/app/node_modules/express/lib/router/layer.js b/app/node_modules/express/lib/router/layer.js new file mode 100644 index 0000000..4dc8e86 --- /dev/null +++ b/app/node_modules/express/lib/router/layer.js @@ -0,0 +1,181 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var pathRegexp = require('path-to-regexp'); +var debug = require('debug')('express:router:layer'); + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Module exports. + * @public + */ + +module.exports = Layer; + +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); + } + + debug('new %o', path) + var opts = options || {}; + + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); + + // set fast path flags + this.regexp.fast_star = path === '*' + this.regexp.fast_slash = path === '/' && opts.end === false +} + +/** + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; + + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } + + try { + fn(error, req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; + + if (fn.length > 3) { + // not a standard request handler + return next(); + } + + try { + fn(req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Layer.prototype.match = function match(path) { + var match + + if (path != null) { + // fast path non-ending match for / (any path matches) + if (this.regexp.fast_slash) { + this.params = {} + this.path = '' + return true + } + + // fast path for * (everything matched in a param) + if (this.regexp.fast_star) { + this.params = {'0': decode_param(path)} + this.path = path + return true + } + + // match the path + match = this.regexp.exec(path) + } + + if (!match) { + this.params = undefined; + this.path = undefined; + return false; + } + + // store values + this.params = {}; + this.path = match[0] + + var keys = this.keys; + var params = this.params; + + for (var i = 1; i < match.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(match[i]) + + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } + } + + return true; +}; + +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ + +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } + + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } + + throw err; + } +} diff --git a/app/node_modules/express/lib/router/route.js b/app/node_modules/express/lib/router/route.js new file mode 100644 index 0000000..178df0d --- /dev/null +++ b/app/node_modules/express/lib/router/route.js @@ -0,0 +1,216 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:router:route'); +var flatten = require('array-flatten'); +var Layer = require('./layer'); +var methods = require('methods'); + +/** + * Module variables. + * @private + */ + +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Module exports. + * @public + */ + +module.exports = Route; + +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @public + */ + +function Route(path) { + this.path = path; + this.stack = []; + + debug('new %o', path) + + // route handlers for various http methods + this.methods = {}; +} + +/** + * Determine if the route handles a given method. + * @private + */ + +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } + + var name = method.toLowerCase(); + + if (name === 'head' && !this.methods['head']) { + name = 'get'; + } + + return Boolean(this.methods[name]); +}; + +/** + * @return {Array} supported HTTP methods + * @private + */ + +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); + + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); + } + + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); + } + + return methods; +}; + +/** + * dispatch req, res into this route + * @private + */ + +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); + } + + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } + + req.route = this; + + next(); + + function next(err) { + // signal to exit route + if (err && err === 'route') { + return done(); + } + + // signal to exit router + if (err && err === 'router') { + return done(err) + } + + var layer = stack[idx++]; + if (!layer) { + return done(err); + } + + if (layer.method && layer.method !== method) { + return next(err); + } + + if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public + */ + +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires a callback function but got a ' + type + throw new TypeError(msg); + } + + var layer = Layer('/', {}, handle); + layer.method = undefined; + + this.methods._all = true; + this.stack.push(layer); + } + + return this; +}; + +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires a callback function but got a ' + type + throw new Error(msg); + } + + debug('%s %o', method, this.path) + + var layer = Layer('/', {}, handle); + layer.method = method; + + this.methods[method] = true; + this.stack.push(layer); + } + + return this; + }; +}); diff --git a/app/node_modules/express/lib/utils.js b/app/node_modules/express/lib/utils.js new file mode 100644 index 0000000..bd81ac7 --- /dev/null +++ b/app/node_modules/express/lib/utils.js @@ -0,0 +1,306 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @api private + */ + +var Buffer = require('safe-buffer').Buffer +var contentDisposition = require('content-disposition'); +var contentType = require('content-type'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var mime = require('send').mime; +var etag = require('etag'); +var proxyaddr = require('proxy-addr'); +var qs = require('qs'); +var querystring = require('querystring'); + +/** + * Return strong ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.etag = createETagGenerator({ weak: false }) + +/** + * Return weak ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.wetag = createETagGenerator({ weak: true }) + +/** + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +exports.isAbsolute = function(path){ + if ('/' === path[0]) return true; + if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path + if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; + +/** + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private + */ + +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); + +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; + +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ + +exports.normalizeTypes = function(types){ + var ret = []; + + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } + + return ret; +}; + +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ + +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); + +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting + * + * @param {String} str + * @return {Object} + * @api private + */ + +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' === pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } + } + + return ret; +} + +/** + * Compile "etag" value to function. + * + * @param {Boolean|String|Function} val + * @return {Function} + * @api private + */ + +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + case 'weak': + fn = exports.wetag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } + + return fn; +} + +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ + +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + case 'simple': + fn = querystring.parse; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } + + return fn; +} + +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ + +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } + + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } + + return proxyaddr.compile(val || []); +} + +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ + +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + + // parse type + var parsed = contentType.parse(type); + + // set charset + parsed.parameters.charset = charset; + + // format type + return contentType.format(parsed); +}; + +/** + * Create an ETag generator function, generating ETags with + * the given options. + * + * @param {object} options + * @return {function} + * @private + */ + +function createETagGenerator (options) { + return function generateETag (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? Buffer.from(body, encoding) + : body + + return etag(buf, options) + } +} + +/** + * Parse an extended query string with qs. + * + * @return {Object} + * @private + */ + +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); +} + +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ + +function newObject() { + return {}; +} diff --git a/app/node_modules/express/lib/view.js b/app/node_modules/express/lib/view.js new file mode 100644 index 0000000..cf101ca --- /dev/null +++ b/app/node_modules/express/lib/view.js @@ -0,0 +1,182 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:view'); +var path = require('path'); +var fs = require('fs'); + +/** + * Module variables. + * @private + */ + +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; + +/** + * Module exports. + * @public + */ + +module.exports = View; + +/** + * Initialize a new `View` with the given `name`. + * + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public + */ + +function View(name, options) { + var opts = options || {}; + + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; + + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } + + var fileName = name; + + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; + + fileName += this.ext; + } + + if (!opts.engines[this.ext]) { + // load engine + var mod = this.ext.substr(1) + debug('require "%s"', mod) + + // default engine export + var fn = require(mod).__express + + if (typeof fn !== 'function') { + throw new Error('Module "' + mod + '" does not provide a view engine.') + } + + opts.engines[this.ext] = fn + } + + // store loaded engine + this.engine = opts.engines[this.ext]; + + // lookup path + this.path = this.lookup(fileName); +} + +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ + +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); + + debug('lookup "%s"', name); + + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; + + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); + + // resolve the file + path = this.resolve(dir, file); + } + + return path; +}; + +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private + */ + +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; + +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ + +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; + + // . + var path = join(dir, file); + var stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } + + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } +}; + +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } +} diff --git a/app/node_modules/express/package.json b/app/node_modules/express/package.json new file mode 100644 index 0000000..74196ad --- /dev/null +++ b/app/node_modules/express/package.json @@ -0,0 +1,98 @@ +{ + "name": "express", + "description": "Fast, unopinionated, minimalist web framework", + "version": "4.16.4", + "author": "TJ Holowaychuk ", + "contributors": [ + "Aaron Heckmann ", + "Ciaran Jessup ", + "Douglas Christopher Wilson ", + "Guillermo Rauch ", + "Jonathan Ong ", + "Roman Shtylman ", + "Young Jae Sim " + ], + "license": "MIT", + "repository": "expressjs/express", + "homepage": "http://expressjs.com/", + "keywords": [ + "express", + "framework", + "sinatra", + "web", + "rest", + "restful", + "router", + "app", + "api" + ], + "dependencies": { + "accepts": "~1.3.5", + "array-flatten": "1.1.1", + "body-parser": "1.18.3", + "content-disposition": "0.5.2", + "content-type": "~1.0.4", + "cookie": "0.3.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~1.1.2", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.1.1", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.2", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.4", + "qs": "6.5.2", + "range-parser": "~1.2.0", + "safe-buffer": "5.1.2", + "send": "0.16.2", + "serve-static": "1.13.2", + "setprototypeof": "1.1.0", + "statuses": "~1.4.0", + "type-is": "~1.6.16", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "devDependencies": { + "after": "0.8.2", + "connect-redis": "3.4.0", + "cookie-parser": "~1.4.3", + "cookie-session": "1.3.2", + "ejs": "2.6.1", + "eslint": "2.13.1", + "express-session": "1.15.6", + "hbs": "4.0.1", + "istanbul": "0.4.5", + "marked": "0.5.1", + "method-override": "3.0.0", + "mocha": "5.2.0", + "morgan": "1.9.1", + "multiparty": "4.2.1", + "pbkdf2-password": "1.2.1", + "should": "13.2.3", + "supertest": "3.3.0", + "vhost": "~3.0.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "files": [ + "LICENSE", + "History.md", + "Readme.md", + "index.js", + "lib/" + ], + "scripts": { + "lint": "eslint .", + "test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/ test/acceptance/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/", + "test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/" + } +} diff --git a/app/node_modules/eyes/LICENSE b/app/node_modules/eyes/LICENSE new file mode 100644 index 0000000..a1edd93 --- /dev/null +++ b/app/node_modules/eyes/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2009 cloudhead + +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/app/node_modules/eyes/Makefile b/app/node_modules/eyes/Makefile new file mode 100644 index 0000000..a121dea --- /dev/null +++ b/app/node_modules/eyes/Makefile @@ -0,0 +1,4 @@ +test: + @@node test/eyes-test.js + +.PHONY: test diff --git a/app/node_modules/eyes/README.md b/app/node_modules/eyes/README.md new file mode 100644 index 0000000..c4f6f76 --- /dev/null +++ b/app/node_modules/eyes/README.md @@ -0,0 +1,73 @@ +eyes +==== + +a customizable value inspector for Node.js + +synopsis +-------- + +I was tired of looking at cluttered output in the console -- something needed to be done, +`sys.inspect()` didn't display regexps correctly, and was too verbose, and I had an hour or two to spare. +So I decided to have some fun. _eyes_ were born. + +![eyes-ss](http://dl.dropbox.com/u/251849/eyes-js-ss.gif) + +_example of the output of a user-customized eyes.js inspector_ + +*eyes* also deals with circular objects in an intelligent way, and can pretty-print object literals. + +usage +----- + + var inspect = require('eyes').inspector({styles: {all: 'magenta'}}); + + inspect(something); // inspect with the settings passed to `inspector` + +or + + var eyes = require('eyes'); + + eyes.inspect(something); // inspect with the default settings + +you can pass a _label_ to `inspect()`, to keep track of your inspections: + + eyes.inspect(something, "a random value"); + +If you want to return the output of eyes without printing it, you can set it up this way: + + var inspect = require('eyes').inspector({ stream: null }); + + sys.puts(inspect({ something: 42 })); + +customization +------------- + +These are the default styles and settings used by _eyes_. + + styles: { // Styles applied to stdout + all: 'cyan', // Overall style applied to everything + label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]` + other: 'inverted', // Objects which don't have a literal representation, such as functions + key: 'bold', // The keys in object literals, like 'a' in `{a: 1}` + special: 'grey', // null, undefined... + string: 'green', + number: 'magenta', + bool: 'blue', // true false + regexp: 'green', // /\d+/ + }, + + pretty: true, // Indent object literals + hideFunctions: false, // Don't output functions at all + stream: process.stdout, // Stream to write to, or null + maxLength: 2048 // Truncate output if longer + +You can overwrite them with your own, by passing a similar object to `inspector()` or `inspect()`. + + var inspect = require('eyes').inspector({ + styles: { + all: 'magenta', + special: 'bold' + }, + maxLength: 512 + }); + diff --git a/app/node_modules/eyes/lib/eyes.js b/app/node_modules/eyes/lib/eyes.js new file mode 100644 index 0000000..10d964b --- /dev/null +++ b/app/node_modules/eyes/lib/eyes.js @@ -0,0 +1,236 @@ +// +// Eyes.js - a customizable value inspector for Node.js +// +// usage: +// +// var inspect = require('eyes').inspector({styles: {all: 'magenta'}}); +// inspect(something); // inspect with the settings passed to `inspector` +// +// or +// +// var eyes = require('eyes'); +// eyes.inspect(something); // inspect with the default settings +// +var eyes = exports, + stack = []; + +eyes.defaults = { + styles: { // Styles applied to stdout + all: 'cyan', // Overall style applied to everything + label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]` + other: 'inverted', // Objects which don't have a literal representation, such as functions + key: 'bold', // The keys in object literals, like 'a' in `{a: 1}` + special: 'grey', // null, undefined... + string: 'green', + number: 'magenta', + bool: 'blue', // true false + regexp: 'green', // /\d+/ + }, + pretty: true, // Indent object literals + hideFunctions: false, + showHidden: false, + stream: process.stdout, + maxLength: 2048 // Truncate output if longer +}; + +// Return a curried inspect() function, with the `options` argument filled in. +eyes.inspector = function (options) { + var that = this; + return function (obj, label, opts) { + return that.inspect.call(that, obj, label, + merge(options || {}, opts || {})); + }; +}; + +// If we have a `stream` defined, use it to print a styled string, +// if not, we just return the stringified object. +eyes.inspect = function (obj, label, options) { + options = merge(this.defaults, options || {}); + + if (options.stream) { + return this.print(stringify(obj, options), label, options); + } else { + return stringify(obj, options) + (options.styles ? '\033[39m' : ''); + } +}; + +// Output using the 'stream', and an optional label +// Loop through `str`, and truncate it after `options.maxLength` has been reached. +// Because escape sequences are, at this point embeded within +// the output string, we can't measure the length of the string +// in a useful way, without separating what is an escape sequence, +// versus a printable character (`c`). So we resort to counting the +// length manually. +eyes.print = function (str, label, options) { + for (var c = 0, i = 0; i < str.length; i++) { + if (str.charAt(i) === '\033') { i += 4 } // `4` because '\033[25m'.length + 1 == 5 + else if (c === options.maxLength) { + str = str.slice(0, i - 1) + '…'; + break; + } else { c++ } + } + return options.stream.write.call(options.stream, (label ? + this.stylize(label, options.styles.label, options.styles) + ': ' : '') + + this.stylize(str, options.styles.all, options.styles) + '\033[0m' + "\n"); +}; + +// Apply a style to a string, eventually, +// I'd like this to support passing multiple +// styles. +eyes.stylize = function (str, style, styles) { + var codes = { + 'bold' : [1, 22], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'cyan' : [36, 39], + 'magenta' : [35, 39], + 'blue' : [34, 39], + 'yellow' : [33, 39], + 'green' : [32, 39], + 'red' : [31, 39], + 'grey' : [90, 39] + }, endCode; + + if (style && codes[style]) { + endCode = (codes[style][1] === 39 && styles.all) ? codes[styles.all][0] + : codes[style][1]; + return '\033[' + codes[style][0] + 'm' + str + + '\033[' + endCode + 'm'; + } else { return str } +}; + +// Convert any object to a string, ready for output. +// When an 'array' or an 'object' are encountered, they are +// passed to specialized functions, which can then recursively call +// stringify(). +function stringify(obj, options) { + var that = this, stylize = function (str, style) { + return eyes.stylize(str, options.styles[style], options.styles) + }, index, result; + + if ((index = stack.indexOf(obj)) !== -1) { + return stylize(new(Array)(stack.length - index + 1).join('.'), 'special'); + } + stack.push(obj); + + result = (function (obj) { + switch (typeOf(obj)) { + case "string" : obj = stringifyString(obj.indexOf("'") === -1 ? "'" + obj + "'" + : '"' + obj + '"'); + return stylize(obj, 'string'); + case "regexp" : return stylize('/' + obj.source + '/', 'regexp'); + case "number" : return stylize(obj + '', 'number'); + case "function" : return options.stream ? stylize("Function", 'other') : '[Function]'; + case "null" : return stylize("null", 'special'); + case "undefined": return stylize("undefined", 'special'); + case "boolean" : return stylize(obj + '', 'bool'); + case "date" : return stylize(obj.toUTCString()); + case "array" : return stringifyArray(obj, options, stack.length); + case "object" : return stringifyObject(obj, options, stack.length); + } + })(obj); + + stack.pop(); + return result; +}; + +// Escape invisible characters in a string +function stringifyString (str, options) { + return str.replace(/\\/g, '\\\\') + .replace(/\n/g, '\\n') + .replace(/[\u0001-\u001F]/g, function (match) { + return '\\0' + match[0].charCodeAt(0).toString(8); + }); +} + +// Convert an array to a string, such as [1, 2, 3]. +// This function calls stringify() for each of the elements +// in the array. +function stringifyArray(ary, options, level) { + var out = []; + var pretty = options.pretty && (ary.length > 4 || ary.some(function (o) { + return (o !== null && typeof(o) === 'object' && Object.keys(o).length > 0) || + (Array.isArray(o) && o.length > 0); + })); + var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' '; + + for (var i = 0; i < ary.length; i++) { + out.push(stringify(ary[i], options)); + } + + if (out.length === 0) { + return '[]'; + } else { + return '[' + ws + + out.join(',' + (pretty ? ws : ' ')) + + (pretty ? ws.slice(0, -4) : ws) + + ']'; + } +}; + +// Convert an object to a string, such as {a: 1}. +// This function calls stringify() for each of its values, +// and does not output functions or prototype values. +function stringifyObject(obj, options, level) { + var out = []; + var pretty = options.pretty && (Object.keys(obj).length > 2 || + Object.keys(obj).some(function (k) { return typeof(obj[k]) === 'object' })); + var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' '; + + var keys = options.showHidden ? Object.keys(obj) : Object.getOwnPropertyNames(obj); + keys.forEach(function (k) { + if (Object.prototype.hasOwnProperty.call(obj, k) + && !(obj[k] instanceof Function && options.hideFunctions)) { + out.push(eyes.stylize(k, options.styles.key, options.styles) + ': ' + + stringify(obj[k], options)); + } + }); + + if (out.length === 0) { + return '{}'; + } else { + return "{" + ws + + out.join(',' + (pretty ? ws : ' ')) + + (pretty ? ws.slice(0, -4) : ws) + + "}"; + } +}; + +// A better `typeof` +function typeOf(value) { + var s = typeof(value), + types = [Object, Array, String, RegExp, Number, Function, Boolean, Date]; + + if (s === 'object' || s === 'function') { + if (value) { + types.forEach(function (t) { + if (value instanceof t) { s = t.name.toLowerCase() } + }); + } else { s = 'null' } + } + return s; +} + +function merge(/* variable args */) { + var objs = Array.prototype.slice.call(arguments); + var target = {}; + + objs.forEach(function (o) { + Object.keys(o).forEach(function (k) { + if (k === 'styles') { + if (! o.styles) { + target.styles = false; + } else { + target.styles = {} + for (var s in o.styles) { + target.styles[s] = o.styles[s]; + } + } + } else { + target[k] = o[k]; + } + }); + }); + return target; +} + diff --git a/app/node_modules/eyes/package.json b/app/node_modules/eyes/package.json new file mode 100644 index 0000000..bc40240 --- /dev/null +++ b/app/node_modules/eyes/package.json @@ -0,0 +1,14 @@ +{ + "name" : "eyes", + "description" : "a customizable value inspector", + "url" : "http://github.com/cloudhead/eyes.js", + "keywords" : ["inspector", "debug", "inspect", "print"], + "author" : "Alexis Sellier ", + "contributors" : [{ "name": "Charlie Robbins", "email": "charlie@nodejitsu.com" }], + "licenses" : ["MIT"], + "main" : "./lib/eyes", + "version" : "0.1.8", + "scripts" : { "test": "node test/*-test.js" }, + "directories" : { "lib": "./lib", "test": "./test" }, + "engines" : { "node": "> 0.1.90" } +} diff --git a/app/node_modules/eyes/test/eyes-test.js b/app/node_modules/eyes/test/eyes-test.js new file mode 100644 index 0000000..1f9606a --- /dev/null +++ b/app/node_modules/eyes/test/eyes-test.js @@ -0,0 +1,56 @@ +var util = require('util'); +var eyes = require('../lib/eyes'); + +eyes.inspect({ + number: 42, + string: "John Galt", + regexp: /[a-z]+/, + array: [99, 168, 'x', {}], + func: function () {}, + bool: false, + nil: null, + undef: undefined, + object: {attr: []} +}, "native types"); + +eyes.inspect({ + number: new(Number)(42), + string: new(String)("John Galt"), + regexp: new(RegExp)(/[a-z]+/), + array: new(Array)(99, 168, 'x', {}), + bool: new(Boolean)(false), + object: new(Object)({attr: []}), + date: new(Date) +}, "wrapped types"); + +var obj = {}; +obj.that = { self: obj }; +obj.self = obj; + +eyes.inspect(obj, "circular object"); +eyes.inspect({hello: 'moto'}, "small object"); +eyes.inspect({hello: new(Array)(6) }, "big object"); +eyes.inspect(["hello 'world'", 'hello "world"'], "quotes"); +eyes.inspect({ + recommendations: [{ + id: 'a7a6576c2c822c8e2bd81a27e41437d8', + key: [ 'spree', 3.764316258020699 ], + value: { + _id: 'a7a6576c2c822c8e2bd81a27e41437d8', + _rev: '1-2e2d2f7fd858c4a5984bcf809d22ed98', + type: 'domain', + domain: 'spree', + weight: 3.764316258020699, + product_id: 30 + } + }] +}, 'complex'); + +eyes.inspect([null], "null in array"); + +var inspect = eyes.inspector({ stream: null }); + +util.puts(inspect('something', "something")); +util.puts(inspect("something else")); + +util.puts(inspect(["no color"], null, { styles: false })); diff --git a/app/node_modules/finalhandler/HISTORY.md b/app/node_modules/finalhandler/HISTORY.md new file mode 100644 index 0000000..9e43d2a --- /dev/null +++ b/app/node_modules/finalhandler/HISTORY.md @@ -0,0 +1,180 @@ +1.1.1 / 2018-03-06 +================== + + * Fix 404 output for bad / missing pathnames + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: statuses@~1.4.0 + +1.1.0 / 2017-09-24 +================== + + * Use `res.headersSent` when available + +1.0.6 / 2017-09-22 +================== + + * deps: debug@2.6.9 + +1.0.5 / 2017-09-15 +================== + + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + +1.0.4 / 2017-08-03 +================== + + * deps: debug@2.6.8 + +1.0.3 / 2017-05-16 +================== + + * deps: debug@2.6.7 + - deps: ms@2.0.0 + +1.0.2 / 2017-04-22 +================== + + * deps: debug@2.6.4 + - deps: ms@0.7.3 + +1.0.1 / 2017-03-21 +================== + + * Fix missing `` in HTML document + * deps: debug@2.6.3 + - Fix: `DEBUG_MAX_ARRAY_LENGTH` + +1.0.0 / 2017-02-15 +================== + + * Fix exception when `err` cannot be converted to a string + * Fully URL-encode the pathname in the 404 message + * Only include the pathname in the 404 message + * Send complete HTML document + * Set `Content-Security-Policy: default-src 'self'` header + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + +0.5.1 / 2016-11-12 +================== + + * Fix exception when `err.headers` is not an object + * deps: statuses@~1.3.1 + * perf: hoist regular expressions + * perf: remove duplicate validation path + +0.5.0 / 2016-06-15 +================== + + * Change invalid or non-numeric status code to 500 + * Overwrite status message to match set status code + * Prefer `err.statusCode` if `err.status` is invalid + * Set response headers from `err.headers` object + * Use `statuses` instead of `http` module for status messages + - Includes all defined status messages + +0.4.1 / 2015-12-02 +================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + +0.4.0 / 2015-06-14 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + * Support `statusCode` property on `Error` objects + * Use `unpipe` module for unpiping requests + * deps: escape-html@1.0.2 + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove argument reassignment + +0.3.6 / 2015-05-11 +================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + +0.3.5 / 2015-04-22 +================== + + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + +0.3.4 / 2015-03-15 +================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.3.3 / 2015-01-01 +================== + + * deps: debug@~2.1.1 + * deps: on-finished@~2.2.0 + +0.3.2 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.3.1 / 2014-10-16 +================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + +0.3.0 / 2014-09-17 +================== + + * Terminate in progress response only on error + * Use `on-finished` to determine request status + +0.2.0 / 2014-09-03 +================== + + * Set `X-Content-Type-Options: nosniff` header + * deps: debug@~2.0.0 + +0.1.0 / 2014-07-16 +================== + + * Respond after request fully read + - prevents hung responses and socket hang ups + * deps: debug@1.0.4 + +0.0.3 / 2014-07-11 +================== + + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.0.2 / 2014-06-19 +================== + + * Handle invalid status codes + +0.0.1 / 2014-06-05 +================== + + * deps: debug@1.0.2 + +0.0.0 / 2014-06-05 +================== + + * Extracted from connect/express diff --git a/app/node_modules/finalhandler/LICENSE b/app/node_modules/finalhandler/LICENSE new file mode 100644 index 0000000..fb30982 --- /dev/null +++ b/app/node_modules/finalhandler/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/app/node_modules/finalhandler/README.md b/app/node_modules/finalhandler/README.md new file mode 100644 index 0000000..6756f0c --- /dev/null +++ b/app/node_modules/finalhandler/README.md @@ -0,0 +1,148 @@ +# finalhandler + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js function to invoke as the final step to respond to HTTP request. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install finalhandler +``` + +## API + + + +```js +var finalhandler = require('finalhandler') +``` + +### finalhandler(req, res, [options]) + +Returns function to be invoked as the final step for the given `req` and `res`. +This function is to be invoked as `fn(err)`. If `err` is falsy, the handler will +write out a 404 response to the `res`. If it is truthy, an error response will +be written out to the `res`. + +When an error is written, the following information is added to the response: + + * The `res.statusCode` is set from `err.status` (or `err.statusCode`). If + this value is outside the 4xx or 5xx range, it will be set to 500. + * The `res.statusMessage` is set according to the status code. + * The body will be the HTML of the status code message if `env` is + `'production'`, otherwise will be `err.stack`. + * Any headers specified in an `err.headers` object. + +The final handler will also unpipe anything from `req` when it is invoked. + +#### options.env + +By default, the environment is determined by `NODE_ENV` variable, but it can be +overridden by this option. + +#### options.onerror + +Provide a function to be called with the `err` when it exists. Can be used for +writing errors to a central location without excessive function generation. Called +as `onerror(err, req, res)`. + +## Examples + +### always 404 + +```js +var finalhandler = require('finalhandler') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + done() +}) + +server.listen(3000) +``` + +### perform simple action + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) +``` + +### use with middleware-style functions + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +var serve = serveStatic('public') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + serve(req, res, done) +}) + +server.listen(3000) +``` + +### keep log of all errors + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res, {onerror: logerror}) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) + +function logerror (err) { + console.error(err.stack || err.toString()) +} +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/finalhandler.svg +[npm-url]: https://npmjs.org/package/finalhandler +[node-image]: https://img.shields.io/node/v/finalhandler.svg +[node-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/pillarjs/finalhandler.svg +[travis-url]: https://travis-ci.org/pillarjs/finalhandler +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/finalhandler.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master +[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg +[downloads-url]: https://npmjs.org/package/finalhandler diff --git a/app/node_modules/finalhandler/index.js b/app/node_modules/finalhandler/index.js new file mode 100644 index 0000000..f20ffe3 --- /dev/null +++ b/app/node_modules/finalhandler/index.js @@ -0,0 +1,331 @@ +/*! + * finalhandler + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('finalhandler') +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var onFinished = require('on-finished') +var parseUrl = require('parseurl') +var statuses = require('statuses') +var unpipe = require('unpipe') + +/** + * Module variables. + * @private + */ + +var DOUBLE_SPACE_REGEXP = /\x20{2}/g +var NEWLINE_REGEXP = /\n/g + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } +var isFinished = onFinished.isFinished + +/** + * Create a minimal HTML document. + * + * @param {string} message + * @private + */ + +function createHtmlDocument (message) { + var body = escapeHtml(message) + .replace(NEWLINE_REGEXP, '
') + .replace(DOUBLE_SPACE_REGEXP, '  ') + + return '\n' + + '\n' + + '\n' + + '\n' + + 'Error\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Module exports. + * @public + */ + +module.exports = finalhandler + +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ + +function finalhandler (req, res, options) { + var opts = options || {} + + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' + + // get error callback + var onerror = opts.onerror + + return function (err) { + var headers + var msg + var status + + // ignore 404 on in-flight response + if (!err && headersSent(res)) { + debug('cannot 404 after headers sent') + return + } + + // unhandled error + if (err) { + // respect status code from error + status = getErrorStatusCode(err) + + if (status === undefined) { + // fallback to status code on response + status = getResponseStatusCode(res) + } else { + // respect headers from error + headers = getErrorHeaders(err) + } + + // get error message + msg = getErrorMessage(err, status, env) + } else { + // not found + status = 404 + msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) + } + + debug('default %s', status) + + // schedule onerror callback + if (err && onerror) { + defer(onerror, err, req, res) + } + + // cannot actually respond + if (headersSent(res)) { + debug('cannot %d after headers sent', status) + req.socket.destroy() + return + } + + // send response + send(req, res, status, headers, msg) + } +} + +/** + * Get headers from Error object. + * + * @param {Error} err + * @return {object} + * @private + */ + +function getErrorHeaders (err) { + if (!err.headers || typeof err.headers !== 'object') { + return undefined + } + + var headers = Object.create(null) + var keys = Object.keys(err.headers) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + headers[key] = err.headers[key] + } + + return headers +} + +/** + * Get message from Error object, fallback to status message. + * + * @param {Error} err + * @param {number} status + * @param {string} env + * @return {string} + * @private + */ + +function getErrorMessage (err, status, env) { + var msg + + if (env !== 'production') { + // use err.stack, which typically includes err.message + msg = err.stack + + // fallback to err.toString() when possible + if (!msg && typeof err.toString === 'function') { + msg = err.toString() + } + } + + return msg || statuses[status] +} + +/** + * Get status code from Error object. + * + * @param {Error} err + * @return {number} + * @private + */ + +function getErrorStatusCode (err) { + // check err.status + if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { + return err.status + } + + // check err.statusCode + if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { + return err.statusCode + } + + return undefined +} + +/** + * Get resource name for the request. + * + * This is typically just the original pathname of the request + * but will fallback to "resource" is that cannot be determined. + * + * @param {IncomingMessage} req + * @return {string} + * @private + */ + +function getResourceName (req) { + try { + return parseUrl.original(req).pathname + } catch (e) { + return 'resource' + } +} + +/** + * Get status code from response. + * + * @param {OutgoingMessage} res + * @return {number} + * @private + */ + +function getResponseStatusCode (res) { + var status = res.statusCode + + // default status code to 500 if outside valid range + if (typeof status !== 'number' || status < 400 || status > 599) { + status = 500 + } + + return status +} + +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ + +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} + +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {object} headers + * @param {string} message + * @private + */ + +function send (req, res, status, headers, message) { + function write () { + // response body + var body = createHtmlDocument(message) + + // response status + res.statusCode = status + res.statusMessage = statuses[status] + + // response headers + setHeaders(res, headers) + + // security headers + res.setHeader('Content-Security-Policy', "default-src 'self'") + res.setHeader('X-Content-Type-Options', 'nosniff') + + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) + + if (req.method === 'HEAD') { + res.end() + return + } + + res.end(body, 'utf8') + } + + if (isFinished(req)) { + write() + return + } + + // unpipe everything from the request + unpipe(req) + + // flush the request + onFinished(req, write) + req.resume() +} + +/** + * Set response headers from an object. + * + * @param {OutgoingMessage} res + * @param {object} headers + * @private + */ + +function setHeaders (res, headers) { + if (!headers) { + return + } + + var keys = Object.keys(headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } +} diff --git a/app/node_modules/finalhandler/package.json b/app/node_modules/finalhandler/package.json new file mode 100644 index 0000000..f552e03 --- /dev/null +++ b/app/node_modules/finalhandler/package.json @@ -0,0 +1,45 @@ +{ + "name": "finalhandler", + "description": "Node.js final http responder", + "version": "1.1.1", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "pillarjs/finalhandler", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.2", + "statuses": "~1.4.0", + "unpipe": "~1.0.0" + }, + "devDependencies": { + "eslint": "4.18.1", + "eslint-config-standard": "11.0.0", + "eslint-plugin-import": "2.9.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "6.0.1", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3", + "readable-stream": "2.3.4", + "safe-buffer": "5.1.1", + "supertest": "1.1.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + } +} diff --git a/app/node_modules/forwarded/HISTORY.md b/app/node_modules/forwarded/HISTORY.md new file mode 100644 index 0000000..2599a55 --- /dev/null +++ b/app/node_modules/forwarded/HISTORY.md @@ -0,0 +1,16 @@ +0.1.2 / 2017-09-14 +================== + + * perf: improve header parsing + * perf: reduce overhead when no `X-Forwarded-For` header + +0.1.1 / 2017-09-10 +================== + + * Fix trimming leading / trailing OWS + * perf: hoist regular expression + +0.1.0 / 2014-09-21 +================== + + * Initial release diff --git a/app/node_modules/forwarded/LICENSE b/app/node_modules/forwarded/LICENSE new file mode 100644 index 0000000..84441fb --- /dev/null +++ b/app/node_modules/forwarded/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/app/node_modules/forwarded/README.md b/app/node_modules/forwarded/README.md new file mode 100644 index 0000000..c776ee5 --- /dev/null +++ b/app/node_modules/forwarded/README.md @@ -0,0 +1,57 @@ +# forwarded + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Parse HTTP X-Forwarded-For header + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install forwarded +``` + +## API + +```js +var forwarded = require('forwarded') +``` + +### forwarded(req) + +```js +var addresses = forwarded(req) +``` + +Parse the `X-Forwarded-For` header from the request. Returns an array +of the addresses, including the socket address for the `req`, in reverse +order (i.e. index `0` is the socket address and the last index is the +furthest address, typically the end-user). + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/forwarded.svg +[npm-url]: https://npmjs.org/package/forwarded +[node-version-image]: https://img.shields.io/node/v/forwarded.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/forwarded/master.svg +[travis-url]: https://travis-ci.org/jshttp/forwarded +[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master +[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg +[downloads-url]: https://npmjs.org/package/forwarded diff --git a/app/node_modules/forwarded/index.js b/app/node_modules/forwarded/index.js new file mode 100644 index 0000000..7833b3d --- /dev/null +++ b/app/node_modules/forwarded/index.js @@ -0,0 +1,76 @@ +/*! + * forwarded + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = forwarded + +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {object} req + * @return {array} + * @public + */ + +function forwarded (req) { + if (!req) { + throw new TypeError('argument req is required') + } + + // simple header parsing + var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') + var socketAddr = req.connection.remoteAddress + var addrs = [socketAddr].concat(proxyAddrs) + + // return all addresses + return addrs +} + +/** + * Parse the X-Forwarded-For header. + * + * @param {string} header + * @private + */ + +function parse (header) { + var end = header.length + var list = [] + var start = header.length + + // gather addresses, backwards + for (var i = header.length - 1; i >= 0; i--) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + } + break + case 0x2c: /* , */ + if (start !== end) { + list.push(header.substring(start, end)) + } + start = end = i + break + default: + start = i + break + } + } + + // final address + if (start !== end) { + list.push(header.substring(start, end)) + } + + return list +} diff --git a/app/node_modules/forwarded/package.json b/app/node_modules/forwarded/package.json new file mode 100644 index 0000000..501f6d2 --- /dev/null +++ b/app/node_modules/forwarded/package.json @@ -0,0 +1,43 @@ +{ + "name": "forwarded", + "description": "Parse HTTP X-Forwarded-For header", + "version": "0.1.2", + "contributors": [ + "Douglas Christopher Wilson " + ], + "license": "MIT", + "keywords": [ + "x-forwarded-for", + "http", + "req" + ], + "repository": "jshttp/forwarded", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/app/node_modules/fresh/HISTORY.md b/app/node_modules/fresh/HISTORY.md new file mode 100644 index 0000000..4586996 --- /dev/null +++ b/app/node_modules/fresh/HISTORY.md @@ -0,0 +1,70 @@ +0.5.2 / 2017-09-13 +================== + + * Fix regression matching multiple ETags in `If-None-Match` + * perf: improve `If-None-Match` token parsing + +0.5.1 / 2017-09-11 +================== + + * Fix handling of modified headers with invalid dates + * perf: improve ETag match loop + +0.5.0 / 2017-02-21 +================== + + * Fix incorrect result when `If-None-Match` has both `*` and ETags + * Fix weak `ETag` matching to match spec + * perf: delay reading header values until needed + * perf: skip checking modified time if ETag check failed + * perf: skip parsing `If-None-Match` when no `ETag` header + * perf: use `Date.parse` instead of `new Date` + +0.4.0 / 2017-02-05 +================== + + * Fix false detection of `no-cache` request directive + * perf: enable strict mode + * perf: hoist regular expressions + * perf: remove duplicate conditional + * perf: remove unnecessary boolean coercions + +0.3.0 / 2015-05-12 +================== + + * Add weak `ETag` matching support + +0.2.4 / 2014-09-07 +================== + + * Support Node.js 0.6 + +0.2.3 / 2014-09-07 +================== + + * Move repository to jshttp + +0.2.2 / 2014-02-19 +================== + + * Revert "Fix for blank page on Safari reload" + +0.2.1 / 2014-01-29 +================== + + * Fix for blank page on Safari reload + +0.2.0 / 2013-08-11 +================== + + * Return stale for `Cache-Control: no-cache` + +0.1.0 / 2012-06-15 +================== + + * Add `If-None-Match: *` support + +0.0.1 / 2012-06-10 +================== + + * Initial release diff --git a/app/node_modules/fresh/LICENSE b/app/node_modules/fresh/LICENSE new file mode 100644 index 0000000..1434ade --- /dev/null +++ b/app/node_modules/fresh/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2016-2017 Douglas Christopher Wilson + +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/app/node_modules/fresh/README.md b/app/node_modules/fresh/README.md new file mode 100644 index 0000000..1c1c680 --- /dev/null +++ b/app/node_modules/fresh/README.md @@ -0,0 +1,119 @@ +# fresh + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP response freshness testing + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +``` +$ npm install fresh +``` + +## API + + + +```js +var fresh = require('fresh') +``` + +### fresh(reqHeaders, resHeaders) + +Check freshness of the response using request and response headers. + +When the response is still "fresh" in the client's cache `true` is +returned, otherwise `false` is returned to indicate that the client +cache is now stale and the full response should be sent. + +When a client sends the `Cache-Control: no-cache` request header to +indicate an end-to-end reload request, this module will return `false` +to make handling these requests transparent. + +## Known Issues + +This module is designed to only follow the HTTP specifications, not +to work-around all kinda of client bugs (especially since this module +typically does not recieve enough information to understand what the +client actually is). + +There is a known issue that in certain versions of Safari, Safari +will incorrectly make a request that allows this module to validate +freshness of the resource even when Safari does not have a +representation of the resource in the cache. The module +[jumanji](https://www.npmjs.com/package/jumanji) can be used in +an Express application to work-around this issue and also provides +links to further reading on this Safari bug. + +## Example + +### API usage + + + +```js +var reqHeaders = { 'if-none-match': '"foo"' } +var resHeaders = { 'etag': '"bar"' } +fresh(reqHeaders, resHeaders) +// => false + +var reqHeaders = { 'if-none-match': '"foo"' } +var resHeaders = { 'etag': '"foo"' } +fresh(reqHeaders, resHeaders) +// => true +``` + +### Using with Node.js http server + +```js +var fresh = require('fresh') +var http = require('http') + +var server = http.createServer(function (req, res) { + // perform server logic + // ... including adding ETag / Last-Modified response headers + + if (isFresh(req, res)) { + // client has a fresh copy of resource + res.statusCode = 304 + res.end() + return + } + + // send the resource + res.statusCode = 200 + res.end('hello, world!') +}) + +function isFresh (req, res) { + return fresh(req.headers, { + 'etag': res.getHeader('ETag'), + 'last-modified': res.getHeader('Last-Modified') + }) +} + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/fresh.svg +[npm-url]: https://npmjs.org/package/fresh +[node-version-image]: https://img.shields.io/node/v/fresh.svg +[node-version-url]: https://nodejs.org/en/ +[travis-image]: https://img.shields.io/travis/jshttp/fresh/master.svg +[travis-url]: https://travis-ci.org/jshttp/fresh +[coveralls-image]: https://img.shields.io/coveralls/jshttp/fresh/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/fresh?branch=master +[downloads-image]: https://img.shields.io/npm/dm/fresh.svg +[downloads-url]: https://npmjs.org/package/fresh diff --git a/app/node_modules/fresh/index.js b/app/node_modules/fresh/index.js new file mode 100644 index 0000000..d154f5a --- /dev/null +++ b/app/node_modules/fresh/index.js @@ -0,0 +1,137 @@ +/*! + * fresh + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2016-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to check for no-cache token in Cache-Control. + * @private + */ + +var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = fresh + +/** + * Check freshness of the response using request and response headers. + * + * @param {Object} reqHeaders + * @param {Object} resHeaders + * @return {Boolean} + * @public + */ + +function fresh (reqHeaders, resHeaders) { + // fields + var modifiedSince = reqHeaders['if-modified-since'] + var noneMatch = reqHeaders['if-none-match'] + + // unconditional request + if (!modifiedSince && !noneMatch) { + return false + } + + // Always return stale when Cache-Control: no-cache + // to support end-to-end reload requests + // https://tools.ietf.org/html/rfc2616#section-14.9.4 + var cacheControl = reqHeaders['cache-control'] + if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { + return false + } + + // if-none-match + if (noneMatch && noneMatch !== '*') { + var etag = resHeaders['etag'] + + if (!etag) { + return false + } + + var etagStale = true + var matches = parseTokenList(noneMatch) + for (var i = 0; i < matches.length; i++) { + var match = matches[i] + if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { + etagStale = false + break + } + } + + if (etagStale) { + return false + } + } + + // if-modified-since + if (modifiedSince) { + var lastModified = resHeaders['last-modified'] + var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) + + if (modifiedStale) { + return false + } + } + + return true +} + +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) + + // istanbul ignore next: guard against date.js Date.parse patching + return typeof timestamp === 'number' + ? timestamp + : NaN +} + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(str.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(str.substring(start, end)) + + return list +} diff --git a/app/node_modules/fresh/package.json b/app/node_modules/fresh/package.json new file mode 100644 index 0000000..c2fa0f4 --- /dev/null +++ b/app/node_modules/fresh/package.json @@ -0,0 +1,46 @@ +{ + "name": "fresh", + "description": "HTTP response freshness testing", + "version": "0.5.2", + "author": "TJ Holowaychuk (http://tjholowaychuk.com)", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "fresh", + "http", + "conditional", + "cache" + ], + "repository": "jshttp/fresh", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + } +} diff --git a/app/node_modules/hooks-fixed/.npmignore b/app/node_modules/hooks-fixed/.npmignore new file mode 100644 index 0000000..96e29a8 --- /dev/null +++ b/app/node_modules/hooks-fixed/.npmignore @@ -0,0 +1,2 @@ +**.swp +node_modules diff --git a/app/node_modules/hooks-fixed/Makefile b/app/node_modules/hooks-fixed/Makefile new file mode 100644 index 0000000..1db5d65 --- /dev/null +++ b/app/node_modules/hooks-fixed/Makefile @@ -0,0 +1,9 @@ +test: + @NODE_ENV=test ./node_modules/expresso/bin/expresso \ + $(TESTFLAGS) \ + ./test.js + +test-cov: + @TESTFLAGS=--cov $(MAKE) test + +.PHONY: test test-cov diff --git a/app/node_modules/hooks-fixed/README.md b/app/node_modules/hooks-fixed/README.md new file mode 100644 index 0000000..98fe85b --- /dev/null +++ b/app/node_modules/hooks-fixed/README.md @@ -0,0 +1,369 @@ +hooks +============ + +Add pre and post middleware hooks to your JavaScript methods. + +## Installation + npm install hooks + +## Motivation +Suppose you have a JavaScript object with a `save` method. + +It would be nice to be able to declare code that runs before `save` and after `save`. +For example, you might want to run validation code before every `save`, +and you might want to dispatch a job to a background job queue after `save`. + +One might have an urge to hard code this all into `save`, but that turns out to +couple all these pieces of functionality (validation, save, and job creation) more +tightly than is necessary. For example, what if someone does not want to do background +job creation after the logical save? + +It is nicer to tack on functionality using what we call `pre` and `post` hooks. These +are functions that you define and that you direct to execute before or after particular +methods. + +## Example +We can use `hooks` to add validation and background jobs in the following way: + +```javascript +var hooks = require('hooks') + , Document = require('./path/to/some/document/constructor'); + +// Add hooks' methods: `hook`, `pre`, and `post` +for (var k in hooks) { + Document[k] = hooks[k]; +} + +// Define a new method that is able to invoke pre and post middleware +Document.hook('save', Document.prototype.save); + +// Define a middleware function to be invoked before 'save' +Document.pre('save', function validate (next) { + // The `this` context inside of `pre` and `post` functions + // is the Document instance + if (this.isValid()) next(); // next() passes control to the next middleware + // or to the target method itself + else next(new Error("Invalid")); // next(error) invokes an error callback +}); + +// Define a middleware function to be invoked after 'save' +Document.post('save', function createJob (next) { + this.sendToBackgroundQueue(); + next(); +}); +``` + +If you already have defined `Document.prototype` methods for which you want pres and posts, +then you do not need to explicitly invoke `Document.hook(...)`. Invoking `Document.pre(methodName, fn)` +or `Document.post(methodName, fn)` will automatically and lazily change `Document.prototype[methodName]` +so that it plays well with `hooks`. An equivalent way to implement the previous example is: + +```javascript +var hooks = require('hooks') + , Document = require('./path/to/some/document/constructor'); + +// Add hooks' methods: `hook`, `pre`, and `post` +for (var k in hooks) { + Document[k] = hooks[k]; +} + +Document.prototype.save = function () { + // ... +}; + +// Define a middleware function to be invoked before 'save' +Document.pre('save', function validate (next) { + // The `this` context inside of `pre` and `post` functions + // is the Document instance + if (this.isValid()) next(); // next() passes control to the next middleware + // or to the target method itself + else next(new Error("Invalid")); // next(error) invokes an error callback +}); + +// Define a middleware function to be invoked after 'save' +Document.post('save', function createJob (next) { + this.sendToBackgroundQueue(); + next(); +}); +``` + +## Pres and Posts as Middleware +We structure pres and posts as middleware to give you maximum flexibility: + +1. You can define **multiple** pres (or posts) for a single method. +2. These pres (or posts) are then executed as a chain of methods. +3. Any functions in this middleware chain can choose to halt the chain's execution by `next`ing an Error from that middleware function. If this occurs, then none of the other middleware in the chain will execute, and the main method (e.g., `save`) will not execute. This is nice, for example, when we don't want a document to save if it is invalid. + +## Defining multiple pres (or posts) +`pre` and `post` are chainable, so you can define multiple via: +```javascript +Document.pre('save', function (next) { + console.log("hello"); + next(); +}).pre('save', function (next) { + console.log("world"); + next(); +}); + +Document.post('save', function (next) { + console.log("hello"); + next(); +}).post('save', function (next) { + console.log("world"); + next(); +}); +``` + +As soon as one pre finishes executing, the next one will be invoked, and so on. + +## Error Handling +You can define a default error handler by passing a 2nd function as the 3rd argument to `hook`: +```javascript +Document.hook('set', function (path, val) { + this[path] = val; +}, function (err) { + // Handler the error here + console.error(err); +}); +``` + +Then, we can pass errors to this handler from a pre or post middleware function: +```javascript +Document.pre('set', function (next, path, val) { + next(new Error()); +}); +``` + +If you do not set up a default handler, then `hooks` makes the default handler that just throws the `Error`. + +The default error handler can be over-rided on a per method invocation basis. + +If the main method that you are surrounding with pre and post middleware expects its last argument to be a function +with callback signature `function (error, ...)`, then that callback becomes the error handler, over-riding the default +error handler you may have set up. + +```javascript +Document.hook('save', function (callback) { + // Save logic goes here + ... +}); + +var doc = new Document(); +doc.save( function (err, saved) { + // We can pass err via `next` in any of our pre or post middleware functions + if (err) console.error(err); + + // Rest of callback logic follows ... +}); +``` + +## Mutating Arguments via Middleware +`pre` and `post` middleware can also accept the intended arguments for the method +they augment. This is useful if you want to mutate the arguments before passing +them along to the next middleware and eventually pass a mutated arguments list to +the main method itself. + +As a simple example, let's define a method `set` that just sets a key, value pair. +If we want to namespace the key, we can do so by adding a `pre` middleware hook +that runs before `set`, alters the arguments by namespacing the `key` argument, and passes them onto `set`: + +```javascript +Document.hook('set', function (key, val) { + this[key] = val; +}); +Document.pre('set', function (next, key, val) { + next('namespace-' + key, val); +}); +var doc = new Document(); +doc.set('hello', 'world'); +console.log(doc.hello); // undefined +console.log(doc['namespace-hello']); // 'world' +``` + +As you can see above, we pass arguments via `next`. + +If you are not mutating the arguments, then you can pass zero arguments +to `next`, and the next middleware function will still have access +to the arguments. + +```javascript +Document.hook('set', function (key, val) { + this[key] = val; +}); +Document.pre('set', function (next, key, val) { + // I have access to key and val here + next(); // We don't need to pass anything to next +}); +Document.pre('set', function (next, key, val) { + // And I still have access to the original key and val here + next(); +}); +``` + +Finally, you can add arguments that downstream middleware can also see: + +```javascript +// Note that in the definition of `set`, there is no 3rd argument, options +Document.hook('set', function (key, val) { + // But... + var options = arguments[2]; // ...I have access to an options argument + // because of pre function pre2 (defined below) + console.log(options); // '{debug: true}' + this[key] = val; +}); +Document.pre('set', function pre1 (next, key, val) { + // I only have access to key and val arguments + console.log(arguments.length); // 3 + next(key, val, {debug: true}); +}); +Document.pre('set', function pre2 (next, key, val, options) { + console.log(arguments.length); // 4 + console.log(options); // '{ debug: true}' + next(); +}); +Document.pre('set', function pre3 (next, key, val, options) { + // I still have access to key, val, AND the options argument introduced via the preceding middleware + console.log(arguments.length); // 4 + console.log(options); // '{ debug: true}' + next(); +}); + +var doc = new Document() +doc.set('hey', 'there'); +``` + +## Post middleware + +Post middleware intercepts the callback originally sent to the asynchronous function you have hooked to. + +This means that the following chain of execution will occur in a typical `save` operation: + +(1) doc.save -> (2) pre --(next)--> (3) save calls back -> (4) post --(next)--> (5) targetFn + +Illustrated below: + +``` +Document.pre('save', function (next) { + this.key = "value"; + next(); +}); +// Post handler occurs before `set` calls back. This is useful if we need to grab something +// async before `set` finishes. +Document.post('set', function (next) { + var me = this; + getSomethingAsync(function(value){ // let's assume it returns "Hello Async" + me.key2 = value; + next(); + }); +}); + +var doc = new Document(); +doc.save(function(err){ + console.log(this.key); // "value" - this value was saved + console.log(this.key2); // "Hello Async" - this value was *not* saved +} + +``` + +Post middleware must call `next()` or execution will stop. + +## Parallel `pre` middleware + +All middleware up to this point has been "serial" middleware -- i.e., middleware whose logic +is executed as a serial chain. + +Some scenarios call for parallel middleware -- i.e., middleware that can wait for several +asynchronous services at once to respond. + +For instance, you may only want to save a Document only after you have checked +that the Document is valid according to two different remote services. + +We accomplish asynchronous middleware by adding a second kind of flow control callback +(the only flow control callback so far has been `next`), called `done`. + +- `next` passes control to the next middleware in the chain +- `done` keeps track of how many parallel middleware have invoked `done` and passes + control to the target method when ALL parallel middleware have invoked `done`. If + you pass an `Error` to `done`, then the error is handled, and the main method that is + wrapped by pres and posts will not get invoked. + +We declare pre middleware that is parallel by passing a 3rd boolean argument to our `pre` +definition method. + +We illustrate via the parallel validation example mentioned above: + +```javascript +Document.hook('save', function targetFn (callback) { + // Save logic goes here + // ... + // This only gets run once the two `done`s are both invoked via preOne and preTwo. +}); + + // true marks this as parallel middleware +Document.pre('save', true, function preOne (next, doneOne, callback) { + remoteServiceOne.validate(this.serialize(), function (err, isValid) { + // The code in here will probably be run after the `next` below this block + // and could possibly be run after the console.log("Hola") in `preTwo + if (err) return doneOne(err); + if (isValid) doneOne(); + }); + next(); // Pass control to the next middleware +}); + +// We will suppose that we need 2 different remote services to validate our document +Document.pre('save', true, function preTwo (next, doneTwo, callback) { + remoteServiceTwo.validate(this.serialize(), function (err, isValid) { + if (err) return doneTwo(err); + if (isValid) doneTwo(); + }); + next(); +}); + +// While preOne and preTwo are parallel, preThree is a serial pre middleware +Document.pre('save', function preThree (next, callback) { + next(); +}); + +var doc = new Document(); +doc.save( function (err, doc) { + // Do stuff with the saved doc here... +}); +``` + +In the above example, flow control may happen in the following way: + +(1) doc.save -> (2) preOne --(next)--> (3) preTwo --(next)--> (4) preThree --(next)--> (wait for dones to invoke) -> (5) doneTwo -> (6) doneOne -> (7) targetFn + +So what's happening is that: + +1. You call `doc.save(...)` +2. First, your preOne middleware gets executed. It makes a remote call to the validation service and `next()`s to the preTwo middleware. +3. Now, your preTwo middleware gets executed. It makes a remote call to another validation service and `next()`s to the preThree middleware. +4. Your preThree middleware gets executed. It immediately `next()`s. But nothing else gets executing until both `doneOne` and `doneTwo` are invoked inside the callbacks handling the response from the two valiation services. +5. We will suppose that validation remoteServiceTwo returns a response to us first. In this case, we call `doneTwo` inside the callback to remoteServiceTwo. +6. Some fractions of a second later, remoteServiceOne returns a response to us. In this case, we call `doneOne` inside the callback to remoteServiceOne. +7. `hooks` implementation keeps track of how many parallel middleware has been defined per target function. It detects that both asynchronous pre middlewares (`preOne` and `preTwo`) have finally called their `done` functions (`doneOne` and `doneTwo`), so the implementation finally invokes our `targetFn` (i.e., our core `save` business logic). + +## Removing Pres + +You can remove a particular pre associated with a hook: + + Document.pre('set', someFn); + Document.removePre('set', someFn); + +And you can also remove all pres associated with a hook: + Document.removePre('set'); // Removes all declared `pre`s on the hook 'set' + +## Tests +To run the tests: + make test + +### Contributors +- [Brian Noguchi](https://github.com/bnoguchi) + +### License +MIT License + +--- +### Author +Brian Noguchi diff --git a/app/node_modules/hooks-fixed/hooks.alt.js b/app/node_modules/hooks-fixed/hooks.alt.js new file mode 100644 index 0000000..6ced357 --- /dev/null +++ b/app/node_modules/hooks-fixed/hooks.alt.js @@ -0,0 +1,134 @@ +/** + * Hooks are useful if we want to add a method that automatically has `pre` and `post` hooks. + * For example, it would be convenient to have `pre` and `post` hooks for `save`. + * _.extend(Model, mixins.hooks); + * Model.hook('save', function () { + * console.log('saving'); + * }); + * Model.pre('save', function (next, done) { + * console.log('about to save'); + * next(); + * }); + * Model.post('save', function (next, done) { + * console.log('saved'); + * next(); + * }); + * + * var m = new Model(); + * m.save(); + * // about to save + * // saving + * // saved + */ + +// TODO Add in pre and post skipping options +module.exports = { + /** + * Declares a new hook to which you can add pres and posts + * @param {String} name of the function + * @param {Function} the method + * @param {Function} the error handler callback + */ + hook: function (name, fn, err) { + if (arguments.length === 1 && typeof name === 'object') { + for (var k in name) { // `name` is a hash of hookName->hookFn + this.hook(k, name[k]); + } + return; + } + + if (!err) err = fn; + + var proto = this.prototype || this + , pres = proto._pres = proto._pres || {} + , posts = proto._posts = proto._posts || {}; + pres[name] = pres[name] || []; + posts[name] = posts[name] || []; + + function noop () {} + + proto[name] = function () { + var self = this + , pres = this._pres[name] + , posts = this._posts[name] + , numAsyncPres = 0 + , hookArgs = [].slice.call(arguments) + , preChain = pres.map( function (pre, i) { + var wrapper = function () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + if (numAsyncPres) { + // arguments[1] === asyncComplete + if (arguments.length) + hookArgs = [].slice.call(arguments, 2); + pre.apply(self, + [ preChain[i+1] || allPresInvoked, + asyncComplete + ].concat(hookArgs) + ); + } else { + if (arguments.length) + hookArgs = [].slice.call(arguments); + pre.apply(self, + [ preChain[i+1] || allPresDone ].concat(hookArgs)); + } + }; // end wrapper = function () {... + if (wrapper.isAsync = pre.isAsync) + numAsyncPres++; + return wrapper; + }); // end posts.map(...) + function allPresInvoked () { + if (arguments[0] instanceof Error) + err(arguments[0]); + } + + function allPresDone () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + if (arguments.length) + hookArgs = [].slice.call(arguments); + fn.apply(self, hookArgs); + var postChain = posts.map( function (post, i) { + var wrapper = function () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + if (arguments.length) + hookArgs = [].slice.call(arguments); + post.apply(self, + [ postChain[i+1] || noop].concat(hookArgs)); + }; // end wrapper = function () {... + return wrapper; + }); // end posts.map(...) + if (postChain.length) postChain[0](); + } + + if (numAsyncPres) { + complete = numAsyncPres; + function asyncComplete () { + if (arguments[0] instanceof Error) + return err(arguments[0]); + --complete || allPresDone.call(this); + } + } + (preChain[0] || allPresDone)(); + }; + + return this; + }, + + pre: function (name, fn, isAsync) { + var proto = this.prototype + , pres = proto._pres = proto._pres || {}; + if (fn.isAsync = isAsync) { + this.prototype[name].numAsyncPres++; + } + (pres[name] = pres[name] || []).push(fn); + return this; + }, + post: function (name, fn, isAsync) { + var proto = this.prototype + , posts = proto._posts = proto._posts || {}; + (posts[name] = posts[name] || []).push(fn); + return this; + } +}; diff --git a/app/node_modules/hooks-fixed/hooks.js b/app/node_modules/hooks-fixed/hooks.js new file mode 100644 index 0000000..abbf134 --- /dev/null +++ b/app/node_modules/hooks-fixed/hooks.js @@ -0,0 +1,192 @@ +// TODO Add in pre and post skipping options +module.exports = { + /** + * Declares a new hook to which you can add pres and posts + * @param {String} name of the function + * @param {Function} the method + * @param {Function} the error handler callback + */ + $hook: function (name, fn, errorCb) { + if (arguments.length === 1 && typeof name === 'object') { + for (var k in name) { // `name` is a hash of hookName->hookFn + this.$hook(k, name[k]); + } + return; + } + + var proto = this.prototype || this + , pres = proto._pres = proto._pres || {} + , posts = proto._posts = proto._posts || {}; + pres[name] = pres[name] || []; + posts[name] = posts[name] || []; + + proto[name] = function () { + var self = this + , hookArgs // arguments eventually passed to the hook - are mutable + , lastArg = arguments[arguments.length-1] + , pres = this._pres[name] + , posts = this._posts[name] + , _total = pres.length + , _current = -1 + , _asyncsLeft = proto[name].numAsyncPres + , _asyncsDone = function(err) { + if (err) { + return handleError(err); + } + --_asyncsLeft || _done.apply(self, hookArgs); + } + , handleError = function(err) { + if ('function' == typeof lastArg) + return lastArg(err); + if (errorCb) return errorCb.call(self, err); + throw err; + } + , _next = function () { + if (arguments[0] instanceof Error) { + return handleError(arguments[0]); + } + var _args = Array.prototype.slice.call(arguments) + , currPre + , preArgs; + if (_args.length && !(arguments[0] == null && typeof lastArg === 'function')) + hookArgs = _args; + if (++_current < _total) { + currPre = pres[_current] + if (currPre.isAsync && currPre.length < 2) + throw new Error("Your pre must have next and done arguments -- e.g., function (next, done, ...)"); + if (currPre.length < 1) + throw new Error("Your pre must have a next argument -- e.g., function (next, ...)"); + preArgs = (currPre.isAsync + ? [once(_next), once(_asyncsDone)] + : [once(_next)]).concat(hookArgs); + try { + return currPre.apply(self, preArgs); + } catch (error) { + _next(error); + } + } else if (!_asyncsLeft) { + return _done.apply(self, hookArgs); + } + } + , _done = function () { + var args_ = Array.prototype.slice.call(arguments) + , ret, total_, current_, next_, done_, postArgs; + + if (_current === _total) { + + next_ = function () { + if (arguments[0] instanceof Error) { + return handleError(arguments[0]); + } + var args_ = Array.prototype.slice.call(arguments, 1) + , currPost + , postArgs; + if (args_.length) hookArgs = args_; + if (++current_ < total_) { + currPost = posts[current_] + if (currPost.length < 1) + throw new Error("Your post must have a next argument -- e.g., function (next, ...)"); + postArgs = [once(next_)].concat(hookArgs); + return currPost.apply(self, postArgs); + } else if (typeof lastArg === 'function'){ + // All post handlers are done, call original callback function + return lastArg.apply(self, arguments); + } + }; + + // We are assuming that if the last argument provided to the wrapped function is a function, it was expecting + // a callback. We trap that callback and wait to call it until all post handlers have finished. + if(typeof lastArg === 'function'){ + args_[args_.length - 1] = once(next_); + } + + total_ = posts.length; + current_ = -1; + ret = fn.apply(self, args_); // Execute wrapped function, post handlers come afterward + + if (total_ && typeof lastArg !== 'function') return next_(); // no callback provided, execute next_() manually + return ret; + } + }; + + return _next.apply(this, arguments); + }; + + proto[name].numAsyncPres = 0; + + return this; + }, + + pre: function (name, isAsync, fn, errorCb) { + if ('boolean' !== typeof arguments[1]) { + errorCb = fn; + fn = isAsync; + isAsync = false; + } + var proto = this.prototype || this + , pres = proto._pres = proto._pres || {}; + + this._lazySetupHooks(proto, name, errorCb); + + if (fn.isAsync = isAsync) { + proto[name].numAsyncPres++; + } + + (pres[name] = pres[name] || []).push(fn); + return this; + }, + post: function (name, isAsync, fn) { + if (arguments.length === 2) { + fn = isAsync; + isAsync = false; + } + var proto = this.prototype || this + , posts = proto._posts = proto._posts || {}; + + this._lazySetupHooks(proto, name); + (posts[name] = posts[name] || []).push(fn); + return this; + }, + removePre: function (name, fnToRemove) { + var proto = this.prototype || this + , pres = proto._pres || (proto._pres || {}); + if (!pres[name]) return this; + if (arguments.length === 1) { + // Remove all pre callbacks for hook `name` + pres[name].length = 0; + } else { + pres[name] = pres[name].filter( function (currFn) { + return currFn !== fnToRemove; + }); + } + return this; + }, + removePost: function (name, fnToRemove) { + var proto = this.prototype || this + , posts = proto._posts || (proto._posts || {}); + if (!posts[name]) return this; + if (arguments.length === 1) { + // Remove all post callbacks for hook `name` + posts[name].length = 0; + } else { + posts[name] = posts[name].filter( function (currFn) { + return currFn !== fnToRemove; + }); + } + return this; + }, + + _lazySetupHooks: function (proto, methodName, errorCb) { + if ('undefined' === typeof proto[methodName].numAsyncPres) { + this.$hook(methodName, proto[methodName], errorCb); + } + } +}; + +function once (fn, scope) { + return function fnWrapper () { + if (fnWrapper.hookCalled) return; + fnWrapper.hookCalled = true; + fn.apply(scope, arguments); + }; +} diff --git a/app/node_modules/hooks-fixed/package.json b/app/node_modules/hooks-fixed/package.json new file mode 100644 index 0000000..ad00e90 --- /dev/null +++ b/app/node_modules/hooks-fixed/package.json @@ -0,0 +1,38 @@ +{ + "name": "hooks-fixed", + "description": "Adds pre and post hook functionality to your JavaScript methods.", + "version": "2.0.2", + "keywords": [ + "node", + "hooks", + "middleware", + "pre", + "post" + ], + "homepage": "https://github.com/vkarpov15/hooks-fixed/", + "repository": { + "type": "git", + "url": "git://github.com/vkarpov15/hooks-fixed.git" + }, + "author": "Brian Noguchi (https://github.com/bnoguchi/)", + "main": "./hooks.js", + "directories": { + "lib": "." + }, + "scripts": { + "test": "make test" + }, + "dependencies": {}, + "devDependencies": { + "expresso": ">=0.7.6", + "should": ">=0.2.1", + "underscore": ">=1.1.4" + }, + "engines": { + "node": ">=0.4.0" + }, + "licenses": [ + "MIT" + ], + "optionalDependencies": {} +} diff --git a/app/node_modules/hooks-fixed/test.js b/app/node_modules/hooks-fixed/test.js new file mode 100644 index 0000000..c500fb4 --- /dev/null +++ b/app/node_modules/hooks-fixed/test.js @@ -0,0 +1,786 @@ +var hooks = require('./hooks') + , should = require('should') + , assert = require('assert') + , _ = require('underscore'); + +// TODO Add in test for making sure all pres get called if pre is defined directly on an instance. +// TODO Test for calling `done` twice or `next` twice in the same function counts only once +module.exports = { + 'should be able to assign multiple hooks at once': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook({ + hook1: function (a) {}, + hook2: function (b) {} + }); + var a = new A(); + assert.equal(typeof a.hook1, 'function'); + assert.equal(typeof a.hook2, 'function'); + }, + 'should run without pres and posts when not present': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 1; + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + }, + 'should run with pres when present': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValue = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.preValue.should.equal(2); + }, + 'should run with posts when present': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.value = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(2); + }, + 'should run pres and posts when present': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValue = 2; + next(); + }); + A.post('save', function (next) { + this.value = 3; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(3); + a.preValue.should.equal(2); + }, + 'should run posts after pres': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.override = 100; + next(); + }); + A.post('save', function (next) { + this.override = 200; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.override.should.equal(200); + }, + 'should not run a hook if a pre fails': function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.$hook('save', function () { + this.value = 1; + }, function (err) { + counter++; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save(); + counter.should.equal(1); + assert.equal(typeof a.value, 'undefined'); + }, + 'should be able to run multiple pres': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.v1 = 1; + next(); + }).pre('save', function (next) { + this.v2 = 2; + next(); + }); + var a = new A(); + a.save(); + a.v1.should.equal(1); + a.v2.should.equal(2); + }, + 'should run multiple pres until a pre fails and not call the hook': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 1; + }, function (err) {}); + A.pre('save', function (next) { + this.v1 = 1; + next(); + }).pre('save', function (next) { + next(new Error()); + }).pre('save', function (next) { + this.v3 = 3; + next(); + }); + var a = new A(); + a.save(); + a.v1.should.equal(1); + assert.equal(typeof a.v3, 'undefined'); + assert.equal(typeof a.value, 'undefined'); + }, + 'should be able to run multiple posts': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.value = 2; + next(); + }).post('save', function (next) { + this.value = 3.14; + next(); + }).post('save', function (next) { + this.v3 = 3; + next(); + }); + var a = new A(); + a.save(); + assert.equal(a.value, 3.14); + assert.equal(a.v3, 3); + }, + 'should run only posts up until an error': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 1; + }, function (err) {}); + A.post('save', function (next) { + this.value = 2; + next(); + }).post('save', function (next) { + this.value = 3; + next(new Error()); + }).post('save', function (next) { + this.value = 4; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(3); + }, + "should fall back first to the hook method's last argument as the error handler if it is a function of arity 1 or 2": function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.$hook('save', function (callback) { + this.value = 1; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save( function (err) { + if (err instanceof Error) counter++; + }); + counter.should.equal(1); + should.deepEqual(undefined, a.value); + }, + 'should fall back second to the default error handler if specified': function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.$hook('save', function (callback) { + this.value = 1; + }, function (err) { + if (err instanceof Error) counter++; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save(); + counter.should.equal(1); + should.deepEqual(undefined, a.value); + }, + 'fallback default error handler should scope to the object': function () { + var A = function () { + this.counter = 0; + }; + _.extend(A, hooks); + var counter = 0; + A.$hook('save', function (callback) { + this.value = 1; + }, function (err) { + if (err instanceof Error) this.counter++; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + a.save(); + a.counter.should.equal(1); + should.deepEqual(undefined, a.value); + }, + 'should fall back last to throwing the error': function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.$hook('save', function (err) { + if (err instanceof Error) return counter++; + this.value = 1; + }); + A.pre('save', true, function (next, done) { + next(new Error()); + }); + var a = new A(); + var didCatch = false; + try { + a.save(); + } catch (e) { + didCatch = true; + e.should.be.an.instanceof(Error); + counter.should.equal(0); + assert.equal(typeof a.value, 'undefined'); + } + didCatch.should.be.true; + }, + "should proceed without mutating arguments if `next(null|undefined)` is called in a serial pre, and the last argument of the target method is a callback with node-like signature function (err, obj) {...} or function (err) {...}": function () { + var A = function () {}; + _.extend(A, hooks); + var counter = 0; + A.prototype.save = function (callback) { + this.value = 1; + callback(); + }; + A.pre('save', function (next) { + next(null); + }); + A.pre('save', function (next) { + next(undefined); + }); + var a = new A(); + a.save( function (err) { + if (err instanceof Error) counter++; + else counter--; + }); + counter.should.equal(-1); + a.value.should.eql(1); + }, + "should proceed with mutating arguments if `next(null|undefined)` is callback in a serial pre, and the last argument of the target method is not a function": function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.set = function (v) { + this.value = v; + }; + A.pre('set', function (next) { + next(undefined); + }); + A.pre('set', function (next) { + next(null); + }); + var a = new A(); + a.set(1); + should.strictEqual(null, a.value); + }, + 'should not run any posts if a pre fails': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 2; + }, function (err) {}); + A.pre('save', function (next) { + this.value = 1; + next(new Error()); + }).post('save', function (next) { + this.value = 3; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + }, + + "can pass the hook's arguments verbatim to pres": function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('set', function (path, val) { + this[path] = val; + }); + A.pre('set', function (next, path, val) { + path.should.equal('hello'); + val.should.equal('world'); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + a.hello.should.equal('world'); + }, +// "can pass the hook's arguments as an array to pres": function () { +// // Great for dynamic arity - e.g., slice(...) +// var A = function () {}; +// _.extend(A, hooks); +// A.hook('set', function (path, val) { +// this[path] = val; +// }); +// A.pre('set', function (next, hello, world) { +// hello.should.equal('hello'); +// world.should.equal('world'); +// next(); +// }); +// var a = new A(); +// a.set('hello', 'world'); +// assert.equal(a.hello, 'world'); +// }, + "can pass the hook's arguments verbatim to posts": function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('set', function (path, val) { + this[path] = val; + }); + A.post('set', function (next, path, val) { + path.should.equal('hello'); + val.should.equal('world'); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + assert.equal(a.hello, 'world'); + }, +// "can pass the hook's arguments as an array to posts": function () { +// var A = function () {}; +// _.extend(A, hooks); +// A.hook('set', function (path, val) { +// this[path] = val; +// }); +// A.post('set', function (next, halt, args) { +// assert.equal(args[0], 'hello'); +// assert.equal(args[1], 'world'); +// next(); +// }); +// var a = new A(); +// a.set('hello', 'world'); +// assert.equal(a.hello, 'world'); +// }, + "pres should be able to modify and pass on a modified version of the hook's arguments": function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('set', function (path, val) { + this[path] = val; + assert.equal(arguments[2], 'optional'); + }); + A.pre('set', function (next, path, val) { + next('foo', 'bar'); + }); + A.pre('set', function (next, path, val) { + assert.equal(path, 'foo'); + assert.equal(val, 'bar'); + next('rock', 'says', 'optional'); + }); + A.pre('set', function (next, path, val, opt) { + assert.equal(path, 'rock'); + assert.equal(val, 'says'); + assert.equal(opt, 'optional'); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + assert.equal(typeof a.hello, 'undefined'); + a.rock.should.equal('says'); + }, + 'posts should see the modified version of arguments if the pres modified them': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('set', function (path, val) { + this[path] = val; + }); + A.pre('set', function (next, path, val) { + next('foo', 'bar'); + }); + A.post('set', function (next, path, val) { + path.should.equal('foo'); + val.should.equal('bar'); + }); + var a = new A(); + a.set('hello', 'world'); + assert.equal(typeof a.hello, 'undefined'); + a.foo.should.equal('bar'); + }, + 'should pad missing arguments (relative to expected arguments of the hook) with null': function () { + // Otherwise, with hookFn = function (a, b, next, ), + // if we use hookFn(a), then because the pre functions are of the form + // preFn = function (a, b, next, ), then it actually gets executed with + // preFn(a, next, ), so when we call next() from within preFn, we are actually + // calling () + + var A = function () {}; + _.extend(A, hooks); + A.$hook('set', function (path, val, opts) { + this[path] = val; + }); + A.pre('set', function (next, path, val, opts) { + next('foo', 'bar'); + assert.equal(typeof opts, 'undefined'); + }); + var a = new A(); + a.set('hello', 'world'); + }, + + 'should not invoke the target method until all asynchronous middleware have invoked dones': function () { + var counter = 0; + var A = function () {}; + _.extend(A, hooks); + A.$hook('set', function (path, val) { + counter++; + this[path] = val; + counter.should.equal(7); + }); + A.pre('set', function (next, path, val) { + counter++; + next(); + }); + A.pre('set', true, function (next, done, path, val) { + counter++; + setTimeout(function () { + counter++; + done(); + }, 1000); + next(); + }); + A.pre('set', function (next, path, val) { + counter++; + next(); + }); + A.pre('set', true, function (next, done, path, val) { + counter++; + setTimeout(function () { + counter++; + done(); + }, 500); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + }, + + 'invoking a method twice should run its async middleware twice': function () { + var counter = 0; + var A = function () {}; + _.extend(A, hooks); + A.$hook('set', function (path, val) { + this[path] = val; + if (path === 'hello') counter.should.equal(1); + if (path === 'foo') counter.should.equal(2); + }); + A.pre('set', true, function (next, done, path, val) { + setTimeout(function () { + counter++; + done(); + }, 1000); + next(); + }); + var a = new A(); + a.set('hello', 'world'); + a.set('foo', 'bar'); + }, + + 'calling the same done multiple times should have the effect of only calling it once': function () { + var A = function () { + this.acked = false; + }; + _.extend(A, hooks); + A.$hook('ack', function () { + console.log("UH OH, YOU SHOULD NOT BE SEEING THIS"); + this.acked = true; + }); + A.pre('ack', true, function (next, done) { + next(); + done(); + done(); + }); + A.pre('ack', true, function (next, done) { + next(); + // Notice that done() is not invoked here + }); + var a = new A(); + a.ack(); + setTimeout( function () { + a.acked.should.be.false; + }, 1000); + }, + + 'calling the same next multiple times should have the effect of only calling it once': function (beforeExit) { + var A = function () { + this.acked = false; + }; + _.extend(A, hooks); + A.$hook('ack', function () { + console.log("UH OH, YOU SHOULD NOT BE SEEING THIS"); + this.acked = true; + }); + A.pre('ack', function (next) { + // force a throw to re-exec next() + try { + next(new Error('bam')); + } catch (err) { + next(); + } + }); + A.pre('ack', function (next) { + next(); + }); + var a = new A(); + a.ack(); + beforeExit( function () { + a.acked.should.be.false; + }); + }, + + 'asynchronous middleware should be able to pass an error via `done`, stopping the middleware chain': function () { + var counter = 0; + var A = function () {}; + _.extend(A, hooks); + A.$hook('set', function (path, val, fn) { + counter++; + this[path] = val; + fn(null); + }); + A.pre('set', true, function (next, done, path, val, fn) { + setTimeout(function () { + counter++; + done(new Error); + }, 1000); + next(); + }); + var a = new A(); + a.set('hello', 'world', function (err) { + err.should.be.an.instanceof(Error); + should.strictEqual(undefined, a['hello']); + counter.should.eql(1); + }); + }, + + 'should be able to remove a particular pre': function () { + var A = function () {} + , preTwo; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValueOne = 2; + next(); + }); + A.pre('save', preTwo = function (next) { + this.preValueTwo = 4; + next(); + }); + A.removePre('save', preTwo); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.preValueOne.should.equal(2); + should.strictEqual(undefined, a.preValueTwo); + }, + + 'should be able to remove all pres associated with a hook': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 1; + }); + A.pre('save', function (next) { + this.preValueOne = 2; + next(); + }); + A.pre('save', function (next) { + this.preValueTwo = 4; + next(); + }); + A.removePre('save'); + var a = new A(); + a.save(); + a.value.should.equal(1); + should.strictEqual(undefined, a.preValueOne); + should.strictEqual(undefined, a.preValueTwo); + }, + + 'should be able to remove a particular post': function () { + var A = function () {} + , postTwo; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.postValueOne = 2; + next(); + }); + A.post('save', postTwo = function (next) { + this.postValueTwo = 4; + next(); + }); + A.removePost('save', postTwo); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.postValueOne.should.equal(2); + should.strictEqual(undefined, a.postValueTwo); + }, + + 'should be able to remove all posts associated with a hook': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function () { + this.value = 1; + }); + A.post('save', function (next) { + this.postValueOne = 2; + next(); + }); + A.post('save', function (next) { + this.postValueTwo = 4; + next(); + }); + A.removePost('save'); + var a = new A(); + a.save(); + a.value.should.equal(1); + should.strictEqual(undefined, a.postValueOne); + should.strictEqual(undefined, a.postValueTwo); + }, + + '#pre should lazily make a method hookable': function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.save = function () { + this.value = 1; + }; + A.pre('save', function (next) { + this.preValue = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(1); + a.preValue.should.equal(2); + }, + + '#pre lazily making a method hookable should be able to provide a default errorHandler as the last argument': function () { + var A = function () {}; + var preValue = ""; + _.extend(A, hooks); + A.prototype.save = function () { + this.value = 1; + }; + A.pre('save', function (next) { + next(new Error); + }, function (err) { + preValue = 'ERROR'; + }); + var a = new A(); + a.save(); + should.strictEqual(undefined, a.value); + preValue.should.equal('ERROR'); + }, + + '#post should lazily make a method hookable': function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.save = function () { + this.value = 1; + }; + A.post('save', function (next) { + this.value = 2; + next(); + }); + var a = new A(); + a.save(); + a.value.should.equal(2); + }, + + "a lazy hooks setup should handle errors via a method's last argument, if it's a callback": function () { + var A = function () {}; + _.extend(A, hooks); + A.prototype.save = function (fn) {}; + A.pre('save', function (next) { + next(new Error("hi there")); + }); + var a = new A(); + a.save( function (err) { + err.should.be.an.instanceof(Error); + }); + }, + + 'should intercept method callbacks for post handlers': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function (val, callback) { + this.value = val; + callback(); + }); + A.post('save', function (next) { + assert.equal(a.value, 2); + this.value += 2; + setTimeout(next, 10); + }).post('save', function (next) { + assert.equal(a.value, 4); + this.value += 3; + setTimeout(next, 10); + }).post('save', function (next) { + assert.equal(a.value, 7); + this.value2 = 3; + setTimeout(next, 10); + }); + var a = new A(); + a.save(2, function(){ + assert.equal(a.value, 7); + assert.equal(a.value2, 3); + }); + }, + + 'should handle parallel followed by serial': function () { + var A = function () {}; + _.extend(A, hooks); + A.$hook('save', function (val, callback) { + this.value = val; + callback(); + }); + A.pre('save', true, function(next, done) { + process.nextTick(function() { + done(); + }); + next(); + }).pre('save', function(done) { + process.nextTick(function() { + done(); + }); + }); + var a = new A(); + a.save(2, function(){ + assert.ok(true); + }); + } +}; diff --git a/app/node_modules/http-errors/HISTORY.md b/app/node_modules/http-errors/HISTORY.md new file mode 100644 index 0000000..cba86e2 --- /dev/null +++ b/app/node_modules/http-errors/HISTORY.md @@ -0,0 +1,132 @@ +2018-03-29 / 1.6.3 +================== + + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: setprototypeof@1.1.0 + * deps: statuses@'>= 1.3.1 < 2' + +2017-08-04 / 1.6.2 +================== + + * deps: depd@1.1.1 + - Remove unnecessary `Buffer` loading + +2017-02-20 / 1.6.1 +================== + + * deps: setprototypeof@1.0.3 + - Fix shim for old browsers + +2017-02-14 / 1.6.0 +================== + + * Accept custom 4xx and 5xx status codes in factory + * Add deprecation message to `"I'mateapot"` export + * Deprecate passing status code as anything except first argument in factory + * Deprecate using non-error status codes + * Make `message` property enumerable for `HttpError`s + +2016-11-16 / 1.5.1 +================== + + * deps: inherits@2.0.3 + - Fix issue loading in browser + * deps: setprototypeof@1.0.2 + * deps: statuses@'>= 1.3.1 < 2' + +2016-05-18 / 1.5.0 +================== + + * Support new code `421 Misdirected Request` + * Use `setprototypeof` module to replace `__proto__` setting + * deps: statuses@'>= 1.3.0 < 2' + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: enable strict mode + +2016-01-28 / 1.4.0 +================== + + * Add `HttpError` export, for `err instanceof createError.HttpError` + * deps: inherits@2.0.1 + * deps: statuses@'>= 1.2.1 < 2' + - Fix message for status 451 + - Remove incorrect nginx status code + +2015-02-02 / 1.3.1 +================== + + * Fix regression where status can be overwritten in `createError` `props` + +2015-02-01 / 1.3.0 +================== + + * Construct errors using defined constructors from `createError` + * Fix error names that are not identifiers + - `createError["I'mateapot"]` is now `createError.ImATeapot` + * Set a meaningful `name` property on constructed errors + +2014-12-09 / 1.2.8 +================== + + * Fix stack trace from exported function + * Remove `arguments.callee` usage + +2014-10-14 / 1.2.7 +================== + + * Remove duplicate line + +2014-10-02 / 1.2.6 +================== + + * Fix `expose` to be `true` for `ClientError` constructor + +2014-09-28 / 1.2.5 +================== + + * deps: statuses@1 + +2014-09-21 / 1.2.4 +================== + + * Fix dependency version to work with old `npm`s + +2014-09-21 / 1.2.3 +================== + + * deps: statuses@~1.1.0 + +2014-09-21 / 1.2.2 +================== + + * Fix publish error + +2014-09-21 / 1.2.1 +================== + + * Support Node.js 0.6 + * Use `inherits` instead of `util` + +2014-09-09 / 1.2.0 +================== + + * Fix the way inheriting functions + * Support `expose` being provided in properties argument + +2014-09-08 / 1.1.0 +================== + + * Default status to 500 + * Support provided `error` to extend + +2014-09-08 / 1.0.1 +================== + + * Fix accepting string message + +2014-09-08 / 1.0.0 +================== + + * Initial release diff --git a/app/node_modules/http-errors/LICENSE b/app/node_modules/http-errors/LICENSE new file mode 100644 index 0000000..82af4df --- /dev/null +++ b/app/node_modules/http-errors/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com +Copyright (c) 2016 Douglas Christopher Wilson doug@somethingdoug.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/app/node_modules/http-errors/README.md b/app/node_modules/http-errors/README.md new file mode 100644 index 0000000..79663d8 --- /dev/null +++ b/app/node_modules/http-errors/README.md @@ -0,0 +1,135 @@ +# http-errors + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create HTTP errors for Express, Koa, Connect, etc. with ease. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install http-errors +``` + +## Example + +```js +var createError = require('http-errors') +var express = require('express') +var app = express() + +app.use(function (req, res, next) { + if (!req.user) return next(createError(401, 'Please login to view this page.')) + next() +}) +``` + +## API + +This is the current API, currently extracted from Koa and subject to change. + +All errors inherit from JavaScript `Error` and the exported `createError.HttpError`. + +### Error Properties + +- `expose` - can be used to signal if `message` should be sent to the client, + defaulting to `false` when `status` >= 500 +- `headers` - can be an object of header names to values to be sent to the + client, defaulting to `undefined`. When defined, the key names should all + be lower-cased +- `message` - the traditional error message, which should be kept short and all + single line +- `status` - the status code of the error, mirroring `statusCode` for general + compatibility +- `statusCode` - the status code of the error, defaulting to `500` + +### createError([status], [message], [properties]) + + + +```js +var err = createError(404, 'This video does not exist!') +``` + +- `status: 500` - the status code as a number +- `message` - the message of the error, defaulting to node's text for that status code. +- `properties` - custom properties to attach to the object + +### new createError\[code || name\](\[msg]\)) + + + +```js +var err = new createError.NotFound() +``` + +- `code` - the status code as a number +- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. + +#### List of all constructors + +|Status Code|Constructor Name | +|-----------|-----------------------------| +|400 |BadRequest | +|401 |Unauthorized | +|402 |PaymentRequired | +|403 |Forbidden | +|404 |NotFound | +|405 |MethodNotAllowed | +|406 |NotAcceptable | +|407 |ProxyAuthenticationRequired | +|408 |RequestTimeout | +|409 |Conflict | +|410 |Gone | +|411 |LengthRequired | +|412 |PreconditionFailed | +|413 |PayloadTooLarge | +|414 |URITooLong | +|415 |UnsupportedMediaType | +|416 |RangeNotSatisfiable | +|417 |ExpectationFailed | +|418 |ImATeapot | +|421 |MisdirectedRequest | +|422 |UnprocessableEntity | +|423 |Locked | +|424 |FailedDependency | +|425 |UnorderedCollection | +|426 |UpgradeRequired | +|428 |PreconditionRequired | +|429 |TooManyRequests | +|431 |RequestHeaderFieldsTooLarge | +|451 |UnavailableForLegalReasons | +|500 |InternalServerError | +|501 |NotImplemented | +|502 |BadGateway | +|503 |ServiceUnavailable | +|504 |GatewayTimeout | +|505 |HTTPVersionNotSupported | +|506 |VariantAlsoNegotiates | +|507 |InsufficientStorage | +|508 |LoopDetected | +|509 |BandwidthLimitExceeded | +|510 |NotExtended | +|511 |NetworkAuthenticationRequired| + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/http-errors.svg +[npm-url]: https://npmjs.org/package/http-errors +[node-version-image]: https://img.shields.io/node/v/http-errors.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/http-errors.svg +[travis-url]: https://travis-ci.org/jshttp/http-errors +[coveralls-image]: https://img.shields.io/coveralls/jshttp/http-errors.svg +[coveralls-url]: https://coveralls.io/r/jshttp/http-errors +[downloads-image]: https://img.shields.io/npm/dm/http-errors.svg +[downloads-url]: https://npmjs.org/package/http-errors diff --git a/app/node_modules/http-errors/index.js b/app/node_modules/http-errors/index.js new file mode 100644 index 0000000..9509303 --- /dev/null +++ b/app/node_modules/http-errors/index.js @@ -0,0 +1,260 @@ +/*! + * http-errors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('http-errors') +var setPrototypeOf = require('setprototypeof') +var statuses = require('statuses') +var inherits = require('inherits') + +/** + * Module exports. + * @public + */ + +module.exports = createError +module.exports.HttpError = createHttpErrorConstructor() + +// Populate exports for all constructors +populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) + +/** + * Get the code class of a status code. + * @private + */ + +function codeClass (status) { + return Number(String(status).charAt(0) + '00') +} + +/** + * Create a new HTTP Error. + * + * @returns {Error} + * @public + */ + +function createError () { + // so much arity going on ~_~ + var err + var msg + var status = 500 + var props = {} + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i] + if (arg instanceof Error) { + err = arg + status = err.status || err.statusCode || status + continue + } + switch (typeof arg) { + case 'string': + msg = arg + break + case 'number': + status = arg + if (i !== 0) { + deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)') + } + break + case 'object': + props = arg + break + } + } + + if (typeof status === 'number' && (status < 400 || status >= 600)) { + deprecate('non-error status code; use only 4xx or 5xx status codes') + } + + if (typeof status !== 'number' || + (!statuses[status] && (status < 400 || status >= 600))) { + status = 500 + } + + // constructor + var HttpError = createError[status] || createError[codeClass(status)] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, createError) + } + + if (!HttpError || !(err instanceof HttpError) || err.status !== status) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] + } + } + + return err +} + +/** + * Create HTTP error abstract base class. + * @private + */ + +function createHttpErrorConstructor () { + function HttpError () { + throw new TypeError('cannot construct abstract class') + } + + inherits(HttpError, Error) + + return HttpError +} + +/** + * Create a constructor for a client error. + * @private + */ + +function createClientErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' + + function ClientError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ClientError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ClientError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ClientError, HttpError) + + ClientError.prototype.status = code + ClientError.prototype.statusCode = code + ClientError.prototype.expose = true + + return ClientError +} + +/** + * Create a constructor for a server error. + * @private + */ + +function createServerErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' + + function ServerError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ServerError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ServerError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ServerError, HttpError) + + ServerError.prototype.status = code + ServerError.prototype.statusCode = code + ServerError.prototype.expose = false + + return ServerError +} + +/** + * Populate the exports object with constructors for every error class. + * @private + */ + +function populateConstructorExports (exports, codes, HttpError) { + codes.forEach(function forEachCode (code) { + var CodeError + var name = toIdentifier(statuses[code]) + + switch (codeClass(code)) { + case 400: + CodeError = createClientErrorConstructor(HttpError, name, code) + break + case 500: + CodeError = createServerErrorConstructor(HttpError, name, code) + break + } + + if (CodeError) { + // export the constructor + exports[code] = CodeError + exports[name] = CodeError + } + }) + + // backwards-compatibility + exports["I'mateapot"] = deprecate.function(exports.ImATeapot, + '"I\'mateapot"; use "ImATeapot" instead') +} + +/** + * Convert a string of words to a JavaScript identifier. + * @private + */ + +function toIdentifier (str) { + return str.split(' ').map(function (token) { + return token.slice(0, 1).toUpperCase() + token.slice(1) + }).join('').replace(/[^ _0-9a-z]/gi, '') +} diff --git a/app/node_modules/http-errors/node_modules/statuses/HISTORY.md b/app/node_modules/http-errors/node_modules/statuses/HISTORY.md new file mode 100644 index 0000000..a1977b2 --- /dev/null +++ b/app/node_modules/http-errors/node_modules/statuses/HISTORY.md @@ -0,0 +1,65 @@ +1.5.0 / 2018-03-27 +================== + + * Add `103 Early Hints` + +1.4.0 / 2017-10-20 +================== + + * Add `STATUS_CODES` export + +1.3.1 / 2016-11-11 +================== + + * Fix return type in JSDoc + +1.3.0 / 2016-05-17 +================== + + * Add `421 Misdirected Request` + * perf: enable strict mode + +1.2.1 / 2015-02-01 +================== + + * Fix message for status 451 + - `451 Unavailable For Legal Reasons` + +1.2.0 / 2014-09-28 +================== + + * Add `208 Already Repored` + * Add `226 IM Used` + * Add `306 (Unused)` + * Add `415 Unable For Legal Reasons` + * Add `508 Loop Detected` + +1.1.1 / 2014-09-24 +================== + + * Add missing 308 to `codes.json` + +1.1.0 / 2014-09-21 +================== + + * Add `codes.json` for universal support + +1.0.4 / 2014-08-20 +================== + + * Package cleanup + +1.0.3 / 2014-06-08 +================== + + * Add 308 to `.redirect` category + +1.0.2 / 2014-03-13 +================== + + * Add `.retry` category + +1.0.1 / 2014-03-12 +================== + + * Initial release diff --git a/app/node_modules/http-errors/node_modules/statuses/LICENSE b/app/node_modules/http-errors/node_modules/statuses/LICENSE new file mode 100644 index 0000000..28a3161 --- /dev/null +++ b/app/node_modules/http-errors/node_modules/statuses/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2016 Douglas Christopher Wilson + +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/app/node_modules/http-errors/node_modules/statuses/README.md b/app/node_modules/http-errors/node_modules/statuses/README.md new file mode 100644 index 0000000..0fe5720 --- /dev/null +++ b/app/node_modules/http-errors/node_modules/statuses/README.md @@ -0,0 +1,127 @@ +# Statuses + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP status utility for node. + +This module provides a list of status codes and messages sourced from +a few different projects: + + * The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) + * The [Node.js project](https://nodejs.org/) + * The [NGINX project](https://www.nginx.com/) + * The [Apache HTTP Server project](https://httpd.apache.org/) + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install statuses +``` + +## API + + + +```js +var status = require('statuses') +``` + +### var code = status(Integer || String) + +If `Integer` or `String` is a valid HTTP code or status message, then the +appropriate `code` will be returned. Otherwise, an error will be thrown. + + + +```js +status(403) // => 403 +status('403') // => 403 +status('forbidden') // => 403 +status('Forbidden') // => 403 +status(306) // throws, as it's not supported by node.js +``` + +### status.STATUS_CODES + +Returns an object which maps status codes to status messages, in +the same format as the +[Node.js http module](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes). + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### var msg = status[code] + +Map of `code` to `status message`. `undefined` for invalid `code`s. + + + +```js +status[404] // => 'Not Found' +``` + +### var code = status[msg] + +Map of `status message` to `code`. `msg` can either be title-cased or +lower-cased. `undefined` for invalid `status message`s. + + + +```js +status['not found'] // => 404 +status['Not Found'] // => 404 +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + + + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + + + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + + + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +[npm-image]: https://img.shields.io/npm/v/statuses.svg +[npm-url]: https://npmjs.org/package/statuses +[node-version-image]: https://img.shields.io/node/v/statuses.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/jshttp/statuses.svg +[travis-url]: https://travis-ci.org/jshttp/statuses +[coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[downloads-image]: https://img.shields.io/npm/dm/statuses.svg +[downloads-url]: https://npmjs.org/package/statuses diff --git a/app/node_modules/http-errors/node_modules/statuses/codes.json b/app/node_modules/http-errors/node_modules/statuses/codes.json new file mode 100644 index 0000000..a09283a --- /dev/null +++ b/app/node_modules/http-errors/node_modules/statuses/codes.json @@ -0,0 +1,66 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "(Unused)", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} diff --git a/app/node_modules/http-errors/node_modules/statuses/index.js b/app/node_modules/http-errors/node_modules/statuses/index.js new file mode 100644 index 0000000..4df469a --- /dev/null +++ b/app/node_modules/http-errors/node_modules/statuses/index.js @@ -0,0 +1,113 @@ +/*! + * statuses + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var codes = require('./codes.json') + +/** + * Module exports. + * @public + */ + +module.exports = status + +// status code to message map +status.STATUS_CODES = codes + +// array of status codes +status.codes = populateStatusesMap(status, codes) + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true +} + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true +} + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true +} + +/** + * Populate the statuses map for given codes. + * @private + */ + +function populateStatusesMap (statuses, codes) { + var arr = [] + + Object.keys(codes).forEach(function forEachCode (code) { + var message = codes[code] + var status = Number(code) + + // Populate properties + statuses[status] = message + statuses[message] = status + statuses[message.toLowerCase()] = status + + // Add to array + arr.push(status) + }) + + return arr +} + +/** + * Get the status code. + * + * Given a number, this will throw if it is not a known status + * code, otherwise the code will be returned. Given a string, + * the string will be parsed for a number and return the code + * if valid, otherwise will lookup the code assuming this is + * the status message. + * + * @param {string|number} code + * @returns {number} + * @public + */ + +function status (code) { + if (typeof code === 'number') { + if (!status[code]) throw new Error('invalid status code: ' + code) + return code + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string') + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + if (!status[n]) throw new Error('invalid status code: ' + n) + return n + } + + n = status[code.toLowerCase()] + if (!n) throw new Error('invalid status message: "' + code + '"') + return n +} diff --git a/app/node_modules/http-errors/node_modules/statuses/package.json b/app/node_modules/http-errors/node_modules/statuses/package.json new file mode 100644 index 0000000..7595e2b --- /dev/null +++ b/app/node_modules/http-errors/node_modules/statuses/package.json @@ -0,0 +1,48 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "1.5.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "jshttp/statuses", + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "HISTORY.md", + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "1.2.4", + "eslint": "4.19.1", + "eslint-config-standard": "11.0.0", + "eslint-plugin-import": "2.9.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "6.0.1", + "eslint-plugin-promise": "3.7.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5", + "raw-body": "2.3.2", + "stream-to-array": "2.3.0" + }, + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build.js", + "fetch": "node scripts/fetch-apache.js && node scripts/fetch-iana.js && node scripts/fetch-nginx.js && node scripts/fetch-node.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "update": "npm run fetch && npm run build" + } +} diff --git a/app/node_modules/http-errors/package.json b/app/node_modules/http-errors/package.json new file mode 100644 index 0000000..a8d28e4 --- /dev/null +++ b/app/node_modules/http-errors/package.json @@ -0,0 +1,48 @@ +{ + "name": "http-errors", + "description": "Create HTTP error objects", + "version": "1.6.3", + "author": "Jonathan Ong (http://jongleberry.com)", + "contributors": [ + "Alan Plum ", + "Douglas Christopher Wilson " + ], + "license": "MIT", + "repository": "jshttp/http-errors", + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.0", + "statuses": ">= 1.4.0 < 2" + }, + "devDependencies": { + "eslint": "4.18.1", + "eslint-config-standard": "11.0.0", + "eslint-plugin-import": "2.9.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "6.0.1", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "keywords": [ + "http", + "error" + ], + "files": [ + "index.js", + "HISTORY.md", + "LICENSE", + "README.md" + ] +} diff --git a/app/node_modules/iconv-lite/.travis.yml b/app/node_modules/iconv-lite/.travis.yml new file mode 100644 index 0000000..3eab7fd --- /dev/null +++ b/app/node_modules/iconv-lite/.travis.yml @@ -0,0 +1,23 @@ + sudo: false + language: node_js + node_js: + - "0.10" + - "0.11" + - "0.12" + - "iojs" + - "4" + - "6" + - "8" + - "node" + + + env: + - CXX=g++-4.8 + addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - gcc-4.8 + - g++-4.8 + diff --git a/app/node_modules/iconv-lite/Changelog.md b/app/node_modules/iconv-lite/Changelog.md new file mode 100644 index 0000000..e31cd0c --- /dev/null +++ b/app/node_modules/iconv-lite/Changelog.md @@ -0,0 +1,158 @@ + +# 0.4.23 / 2018-05-07 + + * Fix deprecation warning in Node v10 due to the last usage of `new Buffer` (#185, by @felixbuenemann) + * Switched from NodeBuffer to Buffer in typings (#155 by @felixfbecker, #186 by @larssn) + + +# 0.4.22 / 2018-05-05 + + * Use older semver style for dependencies to be compatible with Node version 0.10 (#182, by @dougwilson) + * Fix tests to accomodate fixes in Node v10 (#182, by @dougwilson) + + +# 0.4.21 / 2018-04-06 + + * Fix encoding canonicalization (#156) + * Fix the paths in the "browser" field in package.json (#174 by @LMLB) + * Removed "contributors" section in package.json - see Git history instead. + + +# 0.4.20 / 2018-04-06 + + * Updated `new Buffer()` usages with recommended replacements as it's being deprecated in Node v10 (#176, #178 by @ChALkeR) + + +# 0.4.19 / 2017-09-09 + + * Fixed iso8859-1 codec regression in handling untranslatable characters (#162, caused by #147) + * Re-generated windows1255 codec, because it was updated in iconv project + * Fixed grammar in error message when iconv-lite is loaded with encoding other than utf8 + + +# 0.4.18 / 2017-06-13 + + * Fixed CESU-8 regression in Node v8. + + +# 0.4.17 / 2017-04-22 + + * Updated typescript definition file to support Angular 2 AoT mode (#153 by @larssn) + + +# 0.4.16 / 2017-04-22 + + * Added support for React Native (#150) + * Changed iso8859-1 encoding to usine internal 'binary' encoding, as it's the same thing (#147 by @mscdex) + * Fixed typo in Readme (#138 by @jiangzhuo) + * Fixed build for Node v6.10+ by making correct version comparison + * Added a warning if iconv-lite is loaded not as utf-8 (see #142) + + +# 0.4.15 / 2016-11-21 + + * Fixed typescript type definition (#137) + + +# 0.4.14 / 2016-11-20 + + * Preparation for v1.0 + * Added Node v6 and latest Node versions to Travis CI test rig + * Deprecated Node v0.8 support + * Typescript typings (@larssn) + * Fix encoding of Euro character in GB 18030 (inspired by @lygstate) + * Add ms prefix to dbcs windows encodings (@rokoroku) + + +# 0.4.13 / 2015-10-01 + + * Fix silly mistake in deprecation notice. + + +# 0.4.12 / 2015-09-26 + + * Node v4 support: + * Added CESU-8 decoding (#106) + * Added deprecation notice for `extendNodeEncodings` + * Added Travis tests for Node v4 and io.js latest (#105 by @Mithgol) + + +# 0.4.11 / 2015-07-03 + + * Added CESU-8 encoding. + + +# 0.4.10 / 2015-05-26 + + * Changed UTF-16 endianness heuristic to take into account any ASCII chars, not + just spaces. This should minimize the importance of "default" endianness. + + +# 0.4.9 / 2015-05-24 + + * Streamlined BOM handling: strip BOM by default, add BOM when encoding if + addBOM: true. Added docs to Readme. + * UTF16 now uses UTF16-LE by default. + * Fixed minor issue with big5 encoding. + * Added io.js testing on Travis; updated node-iconv version to test against. + Now we just skip testing SBCS encodings that node-iconv doesn't support. + * (internal refactoring) Updated codec interface to use classes. + * Use strict mode in all files. + + +# 0.4.8 / 2015-04-14 + + * added alias UNICODE-1-1-UTF-7 for UTF-7 encoding (#94) + + +# 0.4.7 / 2015-02-05 + + * stop official support of Node.js v0.8. Should still work, but no guarantees. + reason: Packages needed for testing are hard to get on Travis CI. + * work in environment where Object.prototype is monkey patched with enumerable + props (#89). + + +# 0.4.6 / 2015-01-12 + + * fix rare aliases of single-byte encodings (thanks @mscdex) + * double the timeout for dbcs tests to make them less flaky on travis + + +# 0.4.5 / 2014-11-20 + + * fix windows-31j and x-sjis encoding support (@nleush) + * minor fix: undefined variable reference when internal error happens + + +# 0.4.4 / 2014-07-16 + + * added encodings UTF-7 (RFC2152) and UTF-7-IMAP (RFC3501 Section 5.1.3) + * fixed streaming base64 encoding + + +# 0.4.3 / 2014-06-14 + + * added encodings UTF-16BE and UTF-16 with BOM + + +# 0.4.2 / 2014-06-12 + + * don't throw exception if `extendNodeEncodings()` is called more than once + + +# 0.4.1 / 2014-06-11 + + * codepage 808 added + + +# 0.4.0 / 2014-06-10 + + * code is rewritten from scratch + * all widespread encodings are supported + * streaming interface added + * browserify compatibility added + * (optional) extend core primitive encodings to make usage even simpler + * moved from vows to mocha as the testing framework + + diff --git a/app/node_modules/iconv-lite/LICENSE b/app/node_modules/iconv-lite/LICENSE new file mode 100644 index 0000000..d518d83 --- /dev/null +++ b/app/node_modules/iconv-lite/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011 Alexander Shtuchkin + +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/app/node_modules/iconv-lite/README.md b/app/node_modules/iconv-lite/README.md new file mode 100644 index 0000000..c981c37 --- /dev/null +++ b/app/node_modules/iconv-lite/README.md @@ -0,0 +1,156 @@ +## Pure JS character encoding conversion [![Build Status](https://travis-ci.org/ashtuchkin/iconv-lite.svg?branch=master)](https://travis-ci.org/ashtuchkin/iconv-lite) + + * Doesn't need native code compilation. Works on Windows and in sandboxed environments like [Cloud9](http://c9.io). + * Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser), + [Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others. + * Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison). + * Intuitive encode/decode API + * Streaming support for Node v0.10+ + * [Deprecated] Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings. + * In-browser usage via [Browserify](https://github.com/substack/node-browserify) (~180k gzip compressed with Buffer shim included). + * Typescript [type definition file](https://github.com/ashtuchkin/iconv-lite/blob/master/lib/index.d.ts) included. + * React Native is supported (need to explicitly `npm install` two more modules: `buffer` and `stream`). + * License: MIT. + +[![NPM Stats](https://nodei.co/npm/iconv-lite.png?downloads=true&downloadRank=true)](https://npmjs.org/packages/iconv-lite/) + +## Usage +### Basic API +```javascript +var iconv = require('iconv-lite'); + +// Convert from an encoded buffer to js string. +str = iconv.decode(Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); + +// Convert from js string to an encoded buffer. +buf = iconv.encode("Sample input string", 'win1251'); + +// Check if encoding is supported +iconv.encodingExists("us-ascii") +``` + +### Streaming API (Node v0.10+) +```javascript + +// Decode stream (from binary stream to js strings) +http.createServer(function(req, res) { + var converterStream = iconv.decodeStream('win1251'); + req.pipe(converterStream); + + converterStream.on('data', function(str) { + console.log(str); // Do something with decoded strings, chunk-by-chunk. + }); +}); + +// Convert encoding streaming example +fs.createReadStream('file-in-win1251.txt') + .pipe(iconv.decodeStream('win1251')) + .pipe(iconv.encodeStream('ucs2')) + .pipe(fs.createWriteStream('file-in-ucs2.txt')); + +// Sugar: all encode/decode streams have .collect(cb) method to accumulate data. +http.createServer(function(req, res) { + req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) { + assert(typeof body == 'string'); + console.log(body); // full request body string + }); +}); +``` + +### [Deprecated] Extend Node.js own encodings +> NOTE: This doesn't work on latest Node versions. See [details](https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility). + +```javascript +// After this call all Node basic primitives will understand iconv-lite encodings. +iconv.extendNodeEncodings(); + +// Examples: +buf = new Buffer(str, 'win1251'); +buf.write(str, 'gbk'); +str = buf.toString('latin1'); +assert(Buffer.isEncoding('iso-8859-15')); +Buffer.byteLength(str, 'us-ascii'); + +http.createServer(function(req, res) { + req.setEncoding('big5'); + req.collect(function(err, body) { + console.log(body); + }); +}); + +fs.createReadStream("file.txt", "shift_jis"); + +// External modules are also supported (if they use Node primitives, which they probably do). +request = require('request'); +request({ + url: "http://github.com/", + encoding: "cp932" +}); + +// To remove extensions +iconv.undoExtendNodeEncodings(); +``` + +## Supported encodings + + * All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex. + * Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap. + * All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, + IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. + Aliases like 'latin1', 'us-ascii' also supported. + * All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP. + +See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings). + +Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors! + +Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors! + + +## Encoding/decoding speed + +Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). +Note: your results may vary, so please always check on your hardware. + + operation iconv@2.1.4 iconv-lite@0.4.7 + ---------------------------------------------------------- + encode('win1251') ~96 Mb/s ~320 Mb/s + decode('win1251') ~95 Mb/s ~246 Mb/s + +## BOM handling + + * Decoding: BOM is stripped by default, unless overridden by passing `stripBOM: false` in options + (f.ex. `iconv.decode(buf, enc, {stripBOM: false})`). + A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found. + * If you want to detect UTF-8 BOM when decoding other encodings, use [node-autodetect-decoder-stream](https://github.com/danielgindi/node-autodetect-decoder-stream) module. + * Encoding: No BOM added, unless overridden by `addBOM: true` option. + +## UTF-16 Encodings + +This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be +smart about endianness in the following ways: + * Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be + overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`. + * Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override. + +## Other notes + +When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding). +Untranslatable characters are set to � or ?. No transliteration is currently supported. +Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see #65, #77). + +## Testing + +```bash +$ git clone git@github.com:ashtuchkin/iconv-lite.git +$ cd iconv-lite +$ npm install +$ npm test + +$ # To view performance: +$ node test/performance.js + +$ # To view test coverage: +$ npm run coverage +$ open coverage/lcov-report/index.html +``` diff --git a/app/node_modules/iconv-lite/encodings/dbcs-codec.js b/app/node_modules/iconv-lite/encodings/dbcs-codec.js new file mode 100644 index 0000000..1fe3e16 --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/dbcs-codec.js @@ -0,0 +1,555 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. + +exports._dbcs = DBCSCodec; + +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; + +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; + + +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) + throw new Error("DBCS codec is called without the data.") + if (!codecOptions.table) + throw new Error("Encoding '" + this.encodingName + "' has no data."); + + // Load tables. + var mappingTable = codecOptions.table(); + + + // Decode tables: MBCS -> Unicode. + + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; + + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); + + this.defaultCharUnicode = iconv.defaultCharUnicode; + + + // Encode tables: Unicode -> DBCS. + + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; + + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') + skipEncodeChars[val] = true; + else + for (var j = val.from; j <= val.to; j++) + skipEncodeChars[j] = true; + } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); + + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); + } + + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); + + + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + + // Add GB18030 decode tables. + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; + var secondByteNode = this.decodeTables[secondByteNodeIdx]; + for (var j = 0x30; j <= 0x39; j++) + secondByteNode[j] = NODE_START - thirdByteNodeIdx; + } + for (var i = 0x81; i <= 0xFE; i++) + thirdByteNode[i] = NODE_START - fourthByteNodeIdx; + for (var i = 0x30; i <= 0x39; i++) + fourthByteNode[i] = GB18030_CODE + } +} + +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; + +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); + + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; + + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; + } + else + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + } + return node; +} + + +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); + + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; + + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char + } + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; + } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + } + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} + +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; +} + +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} + +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } + + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; + else { + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal + } + } + + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} + +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; + + if (uCode >= 0) + this._setEncodeChar(uCode, mbCode); + else if (uCode <= NODE_START) + this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); + else if (uCode <= SEQ_START) + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + } +} + + + +// == Encoder ================================================================== + +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; + + // Static data + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; +} + +DBCSEncoder.prototype.write = function(str) { + var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; + + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); + } + else { + var uCode = nextChar; + nextChar = -1; + } + + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + + } + } + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; + } + + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; + + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; + + } else if (resCode == undefined) { // Current character is not part of the sequence. + + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. + + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined; + } + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } + + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } + } + + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + else { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } + + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} + +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. + + var newBuf = Buffer.alloc(10), j = 0; + + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + } else { + // See todo above. + } + this.seqObj = undefined; + } + + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + + return newBuf.slice(0, j); +} + +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; + + +// == Decoder ================================================================== + +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = Buffer.alloc(0); + + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} + +DBCSDecoder.prototype.write = function(buf) { + var newBuf = Buffer.alloc(buf.length*2), + nodeIdx = this.nodeIdx, + prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, + seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. + uCode; + + if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. + prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; + + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; + + if (uCode >= 0) { + // Normal character, just use it. + } + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). + uCode = this.defaultCharUnicode.charCodeAt(0); + } + else if (uCode === GB18030_CODE) { + var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; + } + else + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode > 0xFFFF) { + uCode -= 0x10000; + var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; + + uCode = 0xDC00 + uCode % 0x400; + } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + + // Reset trie node. + nodeIdx = 0; seqStart = i+1; + } + + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} + +DBCSDecoder.prototype.end = function() { + var ret = ''; + + // Try to parse all remaining chars. + while (this.prevBuf.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var buf = this.prevBuf.slice(1); + + // Parse remaining as usual. + this.prevBuf = Buffer.alloc(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += this.write(buf); + } + + this.nodeIdx = 0; + return ret; +} + +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; + + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + Math.floor((r-l+1)/2); + if (table[mid] <= val) + l = mid; + else + r = mid; + } + return l; +} + diff --git a/app/node_modules/iconv-lite/encodings/dbcs-data.js b/app/node_modules/iconv-lite/encodings/dbcs-data.js new file mode 100644 index 0000000..4b61914 --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/dbcs-data.js @@ -0,0 +1,176 @@ +"use strict"; + +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. + +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) + + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html + + 'shiftjis': { + type: '_dbcs', + table: function() { return require('./tables/shiftjis.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + encodeSkipVals: [{from: 0xED40, to: 0xF940}], + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows31j': 'shiftjis', + 'ms31j': 'shiftjis', + 'xsjis': 'shiftjis', + 'windows932': 'shiftjis', + 'ms932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', + + 'eucjp': { + type: '_dbcs', + table: function() { return require('./tables/eucjp.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, + + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + + + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', + + // Microsoft's CP936 is a subset and approximation of GBK. + 'windows936': 'cp936', + 'ms936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json') }, + }, + + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + }, + 'xgbk': 'gbk', + 'isoir58': 'gbk', + + // GB18030 is an algorithmic extension of GBK. + // Main source: https://www.w3.org/TR/encoding/#gbk-encoder + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + 'gb18030': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + gb18030: function() { return require('./tables/gb18030-ranges.json') }, + encodeSkipVals: [0x80], + encodeAdd: {'€': 0xA2E3}, + }, + + 'chinese': 'gb18030', + + + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + 'ms949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function() { return require('./tables/cp949.json') }, + }, + + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', + + + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + + 'windows950': 'cp950', + 'ms950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json') }, + }, + + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) }, + encodeSkipVals: [0xa2cc], + }, + + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', +}; diff --git a/app/node_modules/iconv-lite/encodings/index.js b/app/node_modules/iconv-lite/encodings/index.js new file mode 100644 index 0000000..e304003 --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/index.js @@ -0,0 +1,22 @@ +"use strict"; + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + require("./internal"), + require("./utf16"), + require("./utf7"), + require("./sbcs-codec"), + require("./sbcs-data"), + require("./sbcs-data-generated"), + require("./dbcs-codec"), + require("./dbcs-data"), +]; + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; +} diff --git a/app/node_modules/iconv-lite/encodings/internal.js b/app/node_modules/iconv-lite/encodings/internal.js new file mode 100644 index 0000000..05ce38b --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/internal.js @@ -0,0 +1,188 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Export Node.js internal encodings. + +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", + + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", + + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, + + // Codec. + _internal: InternalCodec, +}; + +//------------------------------------------------------------------------------ + +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; + + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; + + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; + } + } +} + +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; + +//------------------------------------------------------------------------------ + +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = require('string_decoder').StringDecoder; + +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; + + +function InternalDecoder(options, codec) { + StringDecoder.call(this, codec.enc); +} + +InternalDecoder.prototype = StringDecoder.prototype; + + +//------------------------------------------------------------------------------ +// Encoder is mostly trivial + +function InternalEncoder(options, codec) { + this.enc = codec.enc; +} + +InternalEncoder.prototype.write = function(str) { + return Buffer.from(str, this.enc); +} + +InternalEncoder.prototype.end = function() { +} + + +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. + +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} + +InternalEncoderBase64.prototype.write = function(str) { + str = this.prevStr + str; + var completeQuads = str.length - (str.length % 4); + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); + + return Buffer.from(str, "base64"); +} + +InternalEncoderBase64.prototype.end = function() { + return Buffer.from(this.prevStr, "base64"); +} + + +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. + +function InternalEncoderCesu8(options, codec) { +} + +InternalEncoderCesu8.prototype.write = function(str) { + var buf = Buffer.alloc(str.length * 3), bufIdx = 0; + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i); + // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). + if (charCode < 0x80) + buf[bufIdx++] = charCode; + else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + else { // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12); + buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + } + return buf.slice(0, bufIdx); +} + +InternalEncoderCesu8.prototype.end = function() { +} + +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ + +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; +} + +InternalDecoderCesu8.prototype.write = function(buf) { + var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, + res = ''; + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i]; + if ((curByte & 0xC0) !== 0x80) { // Leading byte + if (contBytes > 0) { // Previous code is invalid + res += this.defaultCharUnicode; + contBytes = 0; + } + + if (curByte < 0x80) { // Single-byte code + res += String.fromCharCode(curByte); + } else if (curByte < 0xE0) { // Two-byte code + acc = curByte & 0x1F; + contBytes = 1; accBytes = 1; + } else if (curByte < 0xF0) { // Three-byte code + acc = curByte & 0x0F; + contBytes = 2; accBytes = 1; + } else { // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode; + } + } else { // Continuation byte + if (contBytes > 0) { // We're waiting for it. + acc = (acc << 6) | (curByte & 0x3f); + contBytes--; accBytes++; + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) + res += this.defaultCharUnicode; + else if (accBytes === 3 && acc < 0x800) + res += this.defaultCharUnicode; + else + // Actually add character. + res += String.fromCharCode(acc); + } + } else { // Unexpected continuation byte + res += this.defaultCharUnicode; + } + } + } + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; + return res; +} + +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; +} diff --git a/app/node_modules/iconv-lite/encodings/sbcs-codec.js b/app/node_modules/iconv-lite/encodings/sbcs-codec.js new file mode 100644 index 0000000..f225823 --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/sbcs-codec.js @@ -0,0 +1,72 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). + +exports._sbcs = SBCSCodec; +function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) + throw new Error("SBCS codec is called without the data.") + + // Prepare char buffer for decoding. + if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) + throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); + + if (codecOptions.chars.length === 128) { + var asciiString = ""; + for (var i = 0; i < 128; i++) + asciiString += String.fromCharCode(i); + codecOptions.chars = asciiString + codecOptions.chars; + } + + this.decodeBuf = new Buffer.from(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = new Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); + + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + + this.encodeBuf = encodeBuf; +} + +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; + + +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; +} + +SBCSEncoder.prototype.write = function(str) { + var buf = Buffer.alloc(str.length); + for (var i = 0; i < str.length; i++) + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + + return buf; +} + +SBCSEncoder.prototype.end = function() { +} + + +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; +} + +SBCSDecoder.prototype.write = function(buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = Buffer.alloc(buf.length*2); + var idx1 = 0, idx2 = 0; + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i]*2; idx2 = i*2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2+1] = decodeBuf[idx1+1]; + } + return newBuf.toString('ucs2'); +} + +SBCSDecoder.prototype.end = function() { +} diff --git a/app/node_modules/iconv-lite/encodings/sbcs-data-generated.js b/app/node_modules/iconv-lite/encodings/sbcs-data-generated.js new file mode 100644 index 0000000..9b48236 --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/sbcs-data-generated.js @@ -0,0 +1,451 @@ +"use strict"; + +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } +} \ No newline at end of file diff --git a/app/node_modules/iconv-lite/encodings/sbcs-data.js b/app/node_modules/iconv-lite/encodings/sbcs-data.js new file mode 100644 index 0000000..2d6f846 --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/sbcs-data.js @@ -0,0 +1,169 @@ +"use strict"; + +// Manually added data to be used by sbcs codec in addition to generated one. + +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, + + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, + + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix34": "ascii", + "ansix341968": "ascii", + "ansix341986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646irv": "ascii", + "us": "ascii", + + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", + + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", + + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", + + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", + + "cp819": "iso88591", + "ibm819": "iso88591", + + "cyrillic": "iso88595", + + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", + + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", + + "hebrew": "iso88598", + "hebrew8": "iso88598", + + "turkish": "iso88599", + "turkish8": "iso88599", + + "thai": "iso885911", + "thai8": "iso885911", + + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", + + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", + + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", + + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", + + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", + + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", + + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", + + "strk10482002": "rk1048", + + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", + + "gb198880": "iso646cn", + "cn": "iso646cn", + + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", + + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", + + "mac": "macintosh", + "csmacintosh": "macintosh", +}; + diff --git a/app/node_modules/iconv-lite/encodings/tables/big5-added.json b/app/node_modules/iconv-lite/encodings/tables/big5-added.json new file mode 100644 index 0000000..3c3d3c2 --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/tables/big5-added.json @@ -0,0 +1,122 @@ +[ +["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"], +["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"], +["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"], +["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"], +["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"], +["8940","𪎩𡅅"], +["8943","攊"], +["8946","丽滝鵎釟"], +["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"], +["89a1","琑糼緍楆竉刧"], +["89ab","醌碸酞肼"], +["89b0","贋胶𠧧"], +["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"], +["89c1","溚舾甙"], +["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"], +["8a40","𧶄唥"], +["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"], +["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"], +["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"], +["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"], +["8aac","䠋𠆩㿺塳𢶍"], +["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"], +["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"], +["8ac9","𪘁𠸉𢫏𢳉"], +["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"], +["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"], +["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"], +["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"], +["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"], +["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"], +["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"], +["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"], +["8ca1","𣏹椙橃𣱣泿"], +["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"], +["8cc9","顨杫䉶圽"], +["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"], +["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"], +["8d40","𠮟"], +["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"], +["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"], +["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"], +["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"], +["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"], +["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"], +["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"], +["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"], +["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"], +["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"], +["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"], +["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"], +["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"], +["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"], +["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"], +["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"], +["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"], +["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"], +["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"], +["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"], +["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"], +["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"], +["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"], +["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"], +["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"], +["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"], +["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"], +["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"], +["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"], +["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"], +["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"], +["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"], +["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"], +["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"], +["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"], +["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"], +["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"], +["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"], +["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"], +["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"], +["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"], +["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"], +["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"], +["9fae","酙隁酜"], +["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"], +["9fc1","𤤙盖鮝个𠳔莾衂"], +["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"], +["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"], +["9fe7","毺蠘罸"], +["9feb","嘠𪙊蹷齓"], +["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"], +["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"], +["a055","𡠻𦸅"], +["a058","詾𢔛"], +["a05b","惽癧髗鵄鍮鮏蟵"], +["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"], +["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"], +["a0a1","嵗𨯂迚𨸹"], +["a0a6","僙𡵆礆匲阸𠼻䁥"], +["a0ae","矾"], +["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"], +["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"], +["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"], +["a3c0","␀",31,"␡"], +["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23], +["c740","す",58,"ァアィイ"], +["c7a1","ゥ",81,"А",5,"ЁЖ",4], +["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"], +["c8a1","龰冈龱𧘇"], +["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"], +["c8f5","ʃɐɛɔɵœøŋʊɪ"], +["f9fe","■"], +["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"], +["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"], +["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"], +["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"], +["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"], +["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"], +["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"], +["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"], +["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"], +["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"] +] diff --git a/app/node_modules/iconv-lite/encodings/tables/cp936.json b/app/node_modules/iconv-lite/encodings/tables/cp936.json new file mode 100644 index 0000000..49ddb9a --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/tables/cp936.json @@ -0,0 +1,264 @@ +[ +["0","\u0000",127,"€"], +["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"], +["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"], +["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11], +["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"], +["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"], +["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5], +["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"], +["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"], +["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"], +["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"], +["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"], +["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"], +["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4], +["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6], +["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"], +["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7], +["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"], +["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"], +["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"], +["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5], +["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"], +["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6], +["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"], +["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4], +["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4], +["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"], +["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"], +["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6], +["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"], +["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"], +["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"], +["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6], +["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"], +["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"], +["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"], +["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"], +["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"], +["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"], +["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8], +["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"], +["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"], +["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"], +["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"], +["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5], +["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"], +["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"], +["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"], +["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"], +["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5], +["9980","檧檨檪檭",114,"欥欦欨",6], +["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"], +["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"], +["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"], +["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"], +["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"], +["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5], +["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"], +["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"], +["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6], +["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"], +["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"], +["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4], +["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19], +["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"], +["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"], +["a2a1","ⅰ",9], +["a2b1","⒈",19,"⑴",19,"①",9], +["a2e5","㈠",9], +["a2f1","Ⅰ",11], +["a3a1","!"#¥%",88," ̄"], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"], +["a6ee","︻︼︷︸︱"], +["a6f4","︳︴"], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6], +["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"], +["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"], +["a8bd","ńň"], +["a8c0","ɡ"], +["a8c5","ㄅ",36], +["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"], +["a959","℡㈱"], +["a95c","‐"], +["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8], +["a980","﹢",4,"﹨﹩﹪﹫"], +["a996","〇"], +["a9a4","─",75], +["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8], +["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"], +["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4], +["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4], +["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11], +["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"], +["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12], +["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"], +["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"], +["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"], +["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"], +["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"], +["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"], +["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"], +["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"], +["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"], +["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4], +["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"], +["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"], +["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"], +["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9], +["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"], +["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"], +["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"], +["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"], +["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"], +["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16], +["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"], +["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"], +["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"], +["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"], +["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"], +["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"], +["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"], +["bb40","籃",9,"籎",36,"籵",5,"籾",9], +["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"], +["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5], +["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"], +["bd40","紷",54,"絯",7], +["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"], +["be40","継",12,"綧",6,"綯",42], +["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"], +["bf40","緻",62], +["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"], +["c040","繞",35,"纃",23,"纜纝纞"], +["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"], +["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"], +["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"], +["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"], +["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"], +["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"], +["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"], +["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"], +["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"], +["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"], +["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"], +["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"], +["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"], +["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"], +["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"], +["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"], +["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"], +["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"], +["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"], +["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10], +["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"], +["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"], +["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"], +["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"], +["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"], +["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"], +["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"], +["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"], +["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"], +["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9], +["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"], +["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"], +["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"], +["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5], +["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"], +["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"], +["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"], +["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6], +["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"], +["d440","訞",31,"訿",8,"詉",21], +["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"], +["d540","誁",7,"誋",7,"誔",46], +["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"], +["d640","諤",34,"謈",27], +["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"], +["d740","譆",31,"譧",4,"譭",25], +["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"], +["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"], +["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"], +["d940","貮",62], +["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"], +["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"], +["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"], +["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"], +["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"], +["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7], +["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"], +["dd40","軥",62], +["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"], +["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"], +["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"], +["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"], +["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"], +["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"], +["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"], +["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"], +["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"], +["e240","釦",62], +["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"], +["e340","鉆",45,"鉵",16], +["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"], +["e440","銨",5,"銯",24,"鋉",31], +["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"], +["e540","錊",51,"錿",10], +["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"], +["e640","鍬",34,"鎐",27], +["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"], +["e740","鏎",7,"鏗",54], +["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"], +["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"], +["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"], +["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42], +["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"], +["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"], +["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"], +["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"], +["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"], +["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7], +["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"], +["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46], +["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"], +["ee40","頏",62], +["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"], +["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4], +["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"], +["f040","餈",4,"餎餏餑",28,"餯",26], +["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"], +["f140","馌馎馚",10,"馦馧馩",47], +["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"], +["f240","駺",62], +["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"], +["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"], +["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"], +["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5], +["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"], +["f540","魼",62], +["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"], +["f640","鯜",62], +["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"], +["f740","鰼",62], +["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"], +["f840","鳣",62], +["f880","鴢",32], +["f940","鵃",62], +["f980","鶂",32], +["fa40","鶣",62], +["fa80","鷢",32], +["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"], +["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"], +["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6], +["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"], +["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38], +["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"], +["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"] +] diff --git a/app/node_modules/iconv-lite/encodings/tables/cp949.json b/app/node_modules/iconv-lite/encodings/tables/cp949.json new file mode 100644 index 0000000..2022a00 --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/tables/cp949.json @@ -0,0 +1,273 @@ +[ +["0","\u0000",127], +["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"], +["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"], +["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"], +["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5], +["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"], +["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18], +["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7], +["8361","긝",18,"긲긳긵긶긹긻긼"], +["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8], +["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8], +["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18], +["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"], +["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4], +["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"], +["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"], +["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"], +["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10], +["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"], +["8741","놞",9,"놩",15], +["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"], +["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4], +["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4], +["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"], +["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"], +["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"], +["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"], +["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15], +["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"], +["8a61","둧",4,"둭",18,"뒁뒂"], +["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"], +["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"], +["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8], +["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18], +["8c41","똀",15,"똒똓똕똖똗똙",4], +["8c61","똞",6,"똦",5,"똭",6,"똵",5], +["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16], +["8d41","뛃",16,"뛕",8], +["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"], +["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"], +["8e41","랟랡",6,"랪랮",5,"랶랷랹",8], +["8e61","럂",4,"럈럊",19], +["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7], +["8f41","뢅",7,"뢎",17], +["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4], +["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5], +["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"], +["9061","륾",5,"릆릈릋릌릏",15], +["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"], +["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5], +["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5], +["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6], +["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"], +["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4], +["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"], +["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"], +["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8], +["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"], +["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8], +["9461","봞",5,"봥",6,"봭",12], +["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24], +["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"], +["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"], +["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14], +["9641","뺸",23,"뻒뻓"], +["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8], +["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44], +["9741","뾃",16,"뾕",8], +["9761","뾞",17,"뾱",7], +["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"], +["9841","쁀",16,"쁒",5,"쁙쁚쁛"], +["9861","쁝쁞쁟쁡",6,"쁪",15], +["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"], +["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"], +["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"], +["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"], +["9a41","숤숥숦숧숪숬숮숰숳숵",16], +["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"], +["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"], +["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8], +["9b61","쌳",17,"썆",7], +["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"], +["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5], +["9c61","쏿",8,"쐉",6,"쐑",9], +["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12], +["9d41","쒪",13,"쒹쒺쒻쒽",8], +["9d61","쓆",25], +["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"], +["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"], +["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"], +["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"], +["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"], +["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"], +["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"], +["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"], +["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13], +["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"], +["a141","좥좦좧좩",18,"좾좿죀죁"], +["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"], +["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"], +["a241","줐줒",5,"줙",18], +["a261","줭",6,"줵",18], +["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"], +["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"], +["a361","즑",6,"즚즜즞",16], +["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"], +["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"], +["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12], +["a481","쨦쨧쨨쨪",28,"ㄱ",93], +["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"], +["a561","쩫",17,"쩾",5,"쪅쪆"], +["a581","쪇",16,"쪙",14,"ⅰ",9], +["a5b0","Ⅰ",9], +["a5c1","Α",16,"Σ",6], +["a5e1","α",16,"σ",6], +["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"], +["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6], +["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7], +["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7], +["a761","쬪",22,"쭂쭃쭄"], +["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"], +["a841","쭭",10,"쭺",14], +["a861","쮉",18,"쮝",6], +["a881","쮤",19,"쮹",11,"ÆÐªĦ"], +["a8a6","IJ"], +["a8a8","ĿŁØŒºÞŦŊ"], +["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"], +["a941","쯅",14,"쯕",10], +["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18], +["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"], +["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"], +["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"], +["aa81","챳챴챶",29,"ぁ",82], +["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"], +["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5], +["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85], +["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"], +["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4], +["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25], +["acd1","а",5,"ёж",25], +["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7], +["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"], +["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"], +["ae41","췆",5,"췍췎췏췑",16], +["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4], +["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"], +["af41","츬츭츮츯츲츴츶",19], +["af61","칊",13,"칚칛칝칞칢",5,"칪칬"], +["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"], +["b041","캚",5,"캢캦",5,"캮",12], +["b061","캻",5,"컂",19], +["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"], +["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"], +["b161","켥",6,"켮켲",5,"켹",11], +["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"], +["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"], +["b261","쾎",18,"쾢",5,"쾩"], +["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"], +["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"], +["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5], +["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"], +["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5], +["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"], +["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"], +["b541","킕",14,"킦킧킩킪킫킭",5], +["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4], +["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"], +["b641","턅",7,"턎",17], +["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"], +["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"], +["b741","텮",13,"텽",6,"톅톆톇톉톊"], +["b761","톋",20,"톢톣톥톦톧"], +["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"], +["b841","퇐",7,"퇙",17], +["b861","퇫",8,"퇵퇶퇷퇹",13], +["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"], +["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"], +["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"], +["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"], +["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"], +["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5], +["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"], +["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"], +["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"], +["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"], +["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"], +["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"], +["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"], +["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"], +["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13], +["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"], +["be41","퐸",7,"푁푂푃푅",14], +["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"], +["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"], +["bf41","풞",10,"풪",14], +["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"], +["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"], +["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5], +["c061","픞",25], +["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"], +["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"], +["c161","햌햍햎햏햑",19,"햦햧"], +["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"], +["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"], +["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"], +["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"], +["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4], +["c361","홢",4,"홨홪",5,"홲홳홵",11], +["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"], +["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"], +["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4], +["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"], +["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"], +["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4], +["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"], +["c641","힍힎힏힑",6,"힚힜힞",5], +["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"], +["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"], +["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"], +["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"], +["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"], +["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"], +["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"], +["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"], +["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"], +["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"], +["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"], +["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"], +["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"], +["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"], +["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"], +["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"], +["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"], +["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"], +["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"], +["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"], +["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"], +["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"], +["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"], +["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"], +["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"], +["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"], +["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"], +["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"], +["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"], +["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"], +["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"], +["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"], +["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"], +["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"], +["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"], +["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"], +["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"], +["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"], +["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"], +["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"], +["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"], +["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"], +["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"], +["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"], +["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"], +["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"], +["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"], +["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"], +["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"], +["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"], +["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"], +["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"], +["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"], +["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"], +["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"] +] diff --git a/app/node_modules/iconv-lite/encodings/tables/cp950.json b/app/node_modules/iconv-lite/encodings/tables/cp950.json new file mode 100644 index 0000000..d8bc871 --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/tables/cp950.json @@ -0,0 +1,177 @@ +[ +["0","\u0000",127], +["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"], +["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"], +["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"], +["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21], +["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10], +["a3a1","ㄐ",25,"˙ˉˊˇˋ"], +["a3e1","€"], +["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"], +["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"], +["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"], +["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"], +["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"], +["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"], +["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"], +["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"], +["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"], +["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"], +["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"], +["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"], +["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"], +["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"], +["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"], +["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"], +["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"], +["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"], +["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"], +["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"], +["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"], +["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"], +["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"], +["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"], +["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"], +["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"], +["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"], +["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"], +["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"], +["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"], +["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"], +["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"], +["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"], +["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"], +["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"], +["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"], +["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"], +["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"], +["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"], +["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"], +["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"], +["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"], +["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"], +["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"], +["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"], +["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"], +["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"], +["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"], +["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"], +["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"], +["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"], +["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"], +["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"], +["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"], +["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"], +["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"], +["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"], +["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"], +["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"], +["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"], +["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"], +["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"], +["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"], +["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"], +["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"], +["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"], +["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"], +["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"], +["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"], +["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"], +["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"], +["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"], +["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"], +["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"], +["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"], +["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"], +["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"], +["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"], +["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"], +["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"], +["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"], +["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"], +["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"], +["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"], +["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"], +["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"], +["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"], +["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"], +["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"], +["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"], +["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"], +["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"], +["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"], +["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"], +["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"], +["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"], +["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"], +["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"], +["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"], +["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"], +["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"], +["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"], +["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"], +["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"], +["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"], +["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"], +["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"], +["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"], +["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"], +["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"], +["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"], +["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"], +["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"], +["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"], +["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"], +["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"], +["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"], +["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"], +["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"], +["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"], +["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"], +["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"], +["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"], +["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"], +["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"], +["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"], +["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"], +["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"], +["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"], +["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"], +["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"], +["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"], +["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"], +["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"], +["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"], +["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"], +["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"], +["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"], +["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"], +["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"], +["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"], +["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"], +["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"], +["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"], +["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"], +["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"], +["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"], +["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"], +["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"], +["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"], +["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"], +["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"], +["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"], +["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"], +["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"], +["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"], +["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"], +["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"], +["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"], +["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"], +["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"], +["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"], +["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"], +["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"], +["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"], +["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"], +["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"] +] diff --git a/app/node_modules/iconv-lite/encodings/tables/eucjp.json b/app/node_modules/iconv-lite/encodings/tables/eucjp.json new file mode 100644 index 0000000..4fa61ca --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/tables/eucjp.json @@ -0,0 +1,182 @@ +[ +["0","\u0000",127], +["8ea1","。",62], +["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"], +["a2a1","◆□■△▲▽▼※〒→←↑↓〓"], +["a2ba","∈∋⊆⊇⊂⊃∪∩"], +["a2ca","∧∨¬⇒⇔∀∃"], +["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["a2f2","ʼn♯♭♪†‡¶"], +["a2fe","◯"], +["a3b0","0",9], +["a3c1","A",25], +["a3e1","a",25], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["ada1","①",19,"Ⅰ",9], +["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"], +["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"], +["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"], +["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"], +["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"], +["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"], +["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"], +["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"], +["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"], +["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"], +["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"], +["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"], +["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"], +["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"], +["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"], +["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"], +["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"], +["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"], +["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"], +["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"], +["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"], +["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"], +["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"], +["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"], +["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"], +["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"], +["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"], +["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"], +["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"], +["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"], +["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"], +["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"], +["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"], +["f4a1","堯槇遙瑤凜熙"], +["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"], +["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"], +["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["fcf1","ⅰ",9,"¬¦'""], +["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"], +["8fa2c2","¡¦¿"], +["8fa2eb","ºª©®™¤№"], +["8fa6e1","ΆΈΉΊΪ"], +["8fa6e7","Ό"], +["8fa6e9","ΎΫ"], +["8fa6ec","Ώ"], +["8fa6f1","άέήίϊΐόςύϋΰώ"], +["8fa7c2","Ђ",10,"ЎЏ"], +["8fa7f2","ђ",10,"ўџ"], +["8fa9a1","ÆĐ"], +["8fa9a4","Ħ"], +["8fa9a6","IJ"], +["8fa9a8","ŁĿ"], +["8fa9ab","ŊØŒ"], +["8fa9af","ŦÞ"], +["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"], +["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"], +["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"], +["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"], +["8fabbd","ġĥíìïîǐ"], +["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"], +["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"], +["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"], +["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"], +["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"], +["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"], +["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"], +["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"], +["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"], +["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"], +["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"], +["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"], +["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"], +["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"], +["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"], +["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"], +["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"], +["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"], +["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"], +["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"], +["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"], +["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"], +["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"], +["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"], +["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"], +["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"], +["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"], +["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"], +["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"], +["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"], +["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"], +["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"], +["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"], +["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"], +["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"], +["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5], +["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"], +["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"], +["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"], +["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"], +["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"], +["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"], +["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"], +["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"], +["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"], +["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"], +["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"], +["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"], +["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"], +["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"], +["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"], +["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"], +["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"], +["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"], +["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"], +["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"], +["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"], +["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"], +["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4], +["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"], +["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"], +["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"], +["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"] +] diff --git a/app/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json b/app/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json new file mode 100644 index 0000000..85c6934 --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json @@ -0,0 +1 @@ +{"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]} \ No newline at end of file diff --git a/app/node_modules/iconv-lite/encodings/tables/gbk-added.json b/app/node_modules/iconv-lite/encodings/tables/gbk-added.json new file mode 100644 index 0000000..8abfa9f --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/tables/gbk-added.json @@ -0,0 +1,55 @@ +[ +["a140","",62], +["a180","",32], +["a240","",62], +["a280","",32], +["a2ab","",5], +["a2e3","€"], +["a2ef",""], +["a2fd",""], +["a340","",62], +["a380","",31," "], +["a440","",62], +["a480","",32], +["a4f4","",10], +["a540","",62], +["a580","",32], +["a5f7","",7], +["a640","",62], +["a680","",32], +["a6b9","",7], +["a6d9","",6], +["a6ec",""], +["a6f3",""], +["a6f6","",8], +["a740","",62], +["a780","",32], +["a7c2","",14], +["a7f2","",12], +["a896","",10], +["a8bc",""], +["a8bf","ǹ"], +["a8c1",""], +["a8ea","",20], +["a958",""], +["a95b",""], +["a95d",""], +["a989","〾⿰",11], +["a997","",12], +["a9f0","",14], +["aaa1","",93], +["aba1","",93], +["aca1","",93], +["ada1","",93], +["aea1","",93], +["afa1","",93], +["d7fa","",4], +["f8a1","",93], +["f9a1","",93], +["faa1","",93], +["fba1","",93], +["fca1","",93], +["fda1","",93], +["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"], +["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93] +] diff --git a/app/node_modules/iconv-lite/encodings/tables/shiftjis.json b/app/node_modules/iconv-lite/encodings/tables/shiftjis.json new file mode 100644 index 0000000..5a3a43c --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/tables/shiftjis.json @@ -0,0 +1,125 @@ +[ +["0","\u0000",128], +["a1","。",62], +["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"], +["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"], +["81b8","∈∋⊆⊇⊂⊃∪∩"], +["81c8","∧∨¬⇒⇔∀∃"], +["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["81f0","ʼn♯♭♪†‡¶"], +["81fc","◯"], +["824f","0",9], +["8260","A",25], +["8281","a",25], +["829f","ぁ",82], +["8340","ァ",62], +["8380","ム",22], +["839f","Α",16,"Σ",6], +["83bf","α",16,"σ",6], +["8440","А",5,"ЁЖ",25], +["8470","а",5,"ёж",7], +["8480","о",17], +["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["8740","①",19,"Ⅰ",9], +["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["877e","㍻"], +["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"], +["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"], +["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"], +["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"], +["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"], +["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"], +["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"], +["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"], +["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"], +["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"], +["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"], +["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"], +["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"], +["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"], +["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"], +["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"], +["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"], +["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"], +["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"], +["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"], +["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"], +["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"], +["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"], +["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"], +["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"], +["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"], +["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"], +["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"], +["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"], +["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"], +["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"], +["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"], +["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"], +["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"], +["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"], +["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"], +["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["eeef","ⅰ",9,"¬¦'""], +["f040","",62], +["f080","",124], +["f140","",62], +["f180","",124], +["f240","",62], +["f280","",124], +["f340","",62], +["f380","",124], +["f440","",62], +["f480","",124], +["f540","",62], +["f580","",124], +["f640","",62], +["f680","",124], +["f740","",62], +["f780","",124], +["f840","",62], +["f880","",124], +["f940",""], +["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"], +["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"], +["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"], +["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"], +["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"] +] diff --git a/app/node_modules/iconv-lite/encodings/utf16.js b/app/node_modules/iconv-lite/encodings/utf16.js new file mode 100644 index 0000000..54765ae --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/utf16.js @@ -0,0 +1,177 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js + +// == UTF16-BE codec. ========================================================== + +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { +} + +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf16BEEncoder() { +} + +Utf16BEEncoder.prototype.write = function(str) { + var buf = Buffer.from(str, 'ucs2'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; + } + return buf; +} + +Utf16BEEncoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf16BEDecoder() { + this.overflowByte = -1; +} + +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; + + var buf2 = Buffer.alloc(buf.length + 1), + i = 0, j = 0; + + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; + } + + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; + } + + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + + return buf2.slice(0, j).toString('ucs2'); +} + +Utf16BEDecoder.prototype.end = function() { +} + + +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; +} + +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; + + +// -- Encoding (pass-through) + +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); +} + +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); +} + +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); +} + + +// -- Decoding + +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBytes = []; + this.initialBytesLen = 0; + + this.options = options || {}; + this.iconv = codec.iconv; +} + +Utf16Decoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBytes.push(buf); + this.initialBytesLen += buf.length; + + if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> detect endianness. + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + this.initialBytes.length = this.initialBytesLen = 0; + } + + return this.decoder.write(buf); +} + +Utf16Decoder.prototype.end = function() { + if (!this.decoder) { + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var res = this.decoder.write(buf), + trail = this.decoder.end(); + + return trail ? (res + trail) : res; + } + return this.decoder.end(); +} + +function detectEncoding(buf, defaultEncoding) { + var enc = defaultEncoding || 'utf-16le'; + + if (buf.length >= 2) { + // Check BOM. + if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM + enc = 'utf-16be'; + else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM + enc = 'utf-16le'; + else { + // No BOM found. Try to deduce encoding from initial content. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions + _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. + + for (var i = 0; i < _len; i += 2) { + if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; + if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; + } + + if (asciiCharsBE > asciiCharsLE) + enc = 'utf-16be'; + else if (asciiCharsBE < asciiCharsLE) + enc = 'utf-16le'; + } + } + + return enc; +} + + diff --git a/app/node_modules/iconv-lite/encodings/utf7.js b/app/node_modules/iconv-lite/encodings/utf7.js new file mode 100644 index 0000000..b7631c2 --- /dev/null +++ b/app/node_modules/iconv-lite/encodings/utf7.js @@ -0,0 +1,290 @@ +"use strict"; +var Buffer = require("safer-buffer").Buffer; + +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; + + +// -- Encoding + +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; +} + +Utf7Encoder.prototype.write = function(str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return Buffer.from(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === '+' ? '' : + this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + + "-"; + }.bind(this))); +} + +Utf7Encoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); + +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString(); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString(); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7Decoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. + + +exports.utf7imap = Utf7IMAPCodec; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = Buffer.alloc(6); + this.base64AccumIdx = 0; +} + +Utf7IMAPEncoder.prototype.write = function(str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i); + if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; + } + + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character + + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } + + } else { // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. + inBase64 = true; + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 0xFF; + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; + } + } + } + } + + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + + return buf.slice(0, bufIdx); +} + +Utf7IMAPEncoder.prototype.end = function() { + var buf = Buffer.alloc(10), bufIdx = 0; + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + this.base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; + } + + return buf.slice(0, bufIdx); +} + + +// -- Decoding + +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; + +Utf7IMAPDecoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64IMAPChars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" + res += "&"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + diff --git a/app/node_modules/iconv-lite/lib/bom-handling.js b/app/node_modules/iconv-lite/lib/bom-handling.js new file mode 100644 index 0000000..1050872 --- /dev/null +++ b/app/node_modules/iconv-lite/lib/bom-handling.js @@ -0,0 +1,52 @@ +"use strict"; + +var BOMChar = '\uFEFF'; + +exports.PrependBOM = PrependBOMWrapper +function PrependBOMWrapper(encoder, options) { + this.encoder = encoder; + this.addBOM = true; +} + +PrependBOMWrapper.prototype.write = function(str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; + } + + return this.encoder.write(str); +} + +PrependBOMWrapper.prototype.end = function() { + return this.encoder.end(); +} + + +//------------------------------------------------------------------------------ + +exports.StripBOM = StripBOMWrapper; +function StripBOMWrapper(decoder, options) { + this.decoder = decoder; + this.pass = false; + this.options = options || {}; +} + +StripBOMWrapper.prototype.write = function(buf) { + var res = this.decoder.write(buf); + if (this.pass || !res) + return res; + + if (res[0] === BOMChar) { + res = res.slice(1); + if (typeof this.options.stripBOM === 'function') + this.options.stripBOM(); + } + + this.pass = true; + return res; +} + +StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); +} + diff --git a/app/node_modules/iconv-lite/lib/extend-node.js b/app/node_modules/iconv-lite/lib/extend-node.js new file mode 100644 index 0000000..87f5394 --- /dev/null +++ b/app/node_modules/iconv-lite/lib/extend-node.js @@ -0,0 +1,217 @@ +"use strict"; +var Buffer = require("buffer").Buffer; +// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer + +// == Extend Node primitives to use iconv-lite ================================= + +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. + + // Node authors rewrote Buffer internals to make it compatible with + // Uint8Array and we cannot patch key functions since then. + // Note: this does use older Buffer API on a purpose + iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); + + iconv.extendNodeEncodings = function extendNodeEncodings() { + if (original) return; + original = {}; + + if (!iconv.supportsNodeEncodingsExtension) { + console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); + console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); + return; + } + + var nodeNativeEncodings = { + 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, + 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, + }; + + Buffer.isNativeEncoding = function(enc) { + return enc && nodeNativeEncodings[enc.toLowerCase()]; + } + + // -- SlowBuffer ----------------------------------------------------------- + var SlowBuffer = require('buffer').SlowBuffer; + + original.SlowBufferToString = SlowBuffer.prototype.toString; + SlowBuffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.SlowBufferWrite = SlowBuffer.prototype.write; + SlowBuffer.prototype.write = function(string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferWrite.call(this, string, offset, length, encoding); + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + } + + // -- Buffer --------------------------------------------------------------- + + original.BufferIsEncoding = Buffer.isEncoding; + Buffer.isEncoding = function(encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); + } + + original.BufferByteLength = Buffer.byteLength; + Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferByteLength.call(this, str, encoding); + + // Slow, I know, but we don't have a better way yet. + return iconv.encode(str, encoding).length; + } + + original.BufferToString = Buffer.prototype.toString; + Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.BufferWrite = Buffer.prototype.write; + Buffer.prototype.write = function(string, offset, length, encoding) { + var _offset = offset, _length = length, _encoding = encoding; + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferWrite.call(this, string, _offset, _length, _encoding); + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + + // TODO: Set _charsWritten. + } + + + // -- Readable ------------------------------------------------------------- + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + original.ReadableSetEncoding = Readable.prototype.setEncoding; + Readable.prototype.setEncoding = function setEncoding(enc, options) { + // Use our own decoder, it has the same interface. + // We cannot use original function as it doesn't handle BOM-s. + this._readableState.decoder = iconv.getDecoder(enc, options); + this._readableState.encoding = enc; + } + + Readable.prototype.collect = iconv._collect; + } + } + + // Remove iconv-lite Node primitive extensions. + iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { + if (!iconv.supportsNodeEncodingsExtension) + return; + if (!original) + throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") + + delete Buffer.isNativeEncoding; + + var SlowBuffer = require('buffer').SlowBuffer; + + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; + + Buffer.isEncoding = original.BufferIsEncoding; + Buffer.byteLength = original.BufferByteLength; + Buffer.prototype.toString = original.BufferToString; + Buffer.prototype.write = original.BufferWrite; + + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; + } + + original = undefined; + } +} diff --git a/app/node_modules/iconv-lite/lib/index.d.ts b/app/node_modules/iconv-lite/lib/index.d.ts new file mode 100644 index 0000000..0547eb3 --- /dev/null +++ b/app/node_modules/iconv-lite/lib/index.d.ts @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + * REQUIREMENT: This definition is dependent on the @types/node definition. + * Install with `npm install @types/node --save-dev` + *--------------------------------------------------------------------------------------------*/ + +declare module 'iconv-lite' { + export function decode(buffer: Buffer, encoding: string, options?: Options): string; + + export function encode(content: string, encoding: string, options?: Options): Buffer; + + export function encodingExists(encoding: string): boolean; + + export function decodeStream(encoding: string, options?: Options): NodeJS.ReadWriteStream; + + export function encodeStream(encoding: string, options?: Options): NodeJS.ReadWriteStream; +} + +export interface Options { + stripBOM?: boolean; + addBOM?: boolean; + defaultEncoding?: string; +} diff --git a/app/node_modules/iconv-lite/lib/index.js b/app/node_modules/iconv-lite/lib/index.js new file mode 100644 index 0000000..5391919 --- /dev/null +++ b/app/node_modules/iconv-lite/lib/index.js @@ -0,0 +1,153 @@ +"use strict"; + +// Some environments don't have global Buffer (e.g. React Native). +// Solution would be installing npm modules "buffer" and "stream" explicitly. +var Buffer = require("safer-buffer").Buffer; + +var bomHandling = require("./bom-handling"), + iconv = module.exports; + +// All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. +iconv.encodings = null; + +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; + +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. + + var encoder = iconv.getEncoder(encoding, options); + + var res = encoder.write(str); + var trail = encoder.end(); + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +} + +iconv.decode = function decode(buf, encoding, options) { + if (typeof buf === 'string') { + if (!iconv.skipDecodeWarning) { + console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); + iconv.skipDecodeWarning = true; + } + + buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. + } + + var decoder = iconv.getDecoder(encoding, options); + + var res = decoder.write(buf); + var trail = decoder.end(); + + return trail ? (res + trail) : res; +} + +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); + return true; + } catch (e) { + return false; + } +} + +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; + +// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. +iconv._codecDataCache = {}; +iconv.getCodec = function getCodec(encoding) { + if (!iconv.encodings) + iconv.encodings = require("../encodings"); // Lazy load all encoding definitions. + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = iconv._canonicalizeEncoding(encoding); + + // Traverse iconv.encodings to find actual codec. + var codecOptions = {}; + while (true) { + var codec = iconv._codecDataCache[enc]; + if (codec) + return codec; + + var codecDef = iconv.encodings[enc]; + + switch (typeof codecDef) { + case "string": // Direct alias to other encoding. + enc = codecDef; + break; + + case "object": // Alias with options. Can be layered. + for (var key in codecDef) + codecOptions[key] = codecDef[key]; + + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + enc = codecDef.type; + break; + + case "function": // Codec itself. + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + codec = new codecDef(codecOptions, iconv); + + iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. + return codec; + + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); + } + } +} + +iconv._canonicalizeEncoding = function(encoding) { + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); +} + +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); + + if (codec.bomAware && options && options.addBOM) + encoder = new bomHandling.PrependBOM(encoder, options); + + return encoder; +} + +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); + + if (codec.bomAware && !(options && options.stripBOM === false)) + decoder = new bomHandling.StripBOM(decoder, options); + + return decoder; +} + + +// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. +var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; +if (nodeVer) { + + // Load streaming support in Node v0.10+ + var nodeVerArr = nodeVer.split(".").map(Number); + if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { + require("./streams")(iconv); + } + + // Load Node primitive extensions. + require("./extend-node")(iconv); +} + +if ("Ā" != "\u0100") { + console.error("iconv-lite warning: javascript files use encoding different from utf-8. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info."); +} diff --git a/app/node_modules/iconv-lite/lib/streams.js b/app/node_modules/iconv-lite/lib/streams.js new file mode 100644 index 0000000..4409552 --- /dev/null +++ b/app/node_modules/iconv-lite/lib/streams.js @@ -0,0 +1,121 @@ +"use strict"; + +var Buffer = require("buffer").Buffer, + Transform = require("stream").Transform; + + +// == Exports ================================================================== +module.exports = function(iconv) { + + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); + } + + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); + } + + iconv.supportsStreams = true; + + + // Not published yet. + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; + + +// == Encoder stream ======================================================= +function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); +} + +IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } +}); + +IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); + }); + return this; +} + + +// == Decoder stream ======================================================= +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); +} + +IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } +}); + +IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; +} + diff --git a/app/node_modules/iconv-lite/package.json b/app/node_modules/iconv-lite/package.json new file mode 100644 index 0000000..fff6478 --- /dev/null +++ b/app/node_modules/iconv-lite/package.json @@ -0,0 +1,46 @@ +{ + "name": "iconv-lite", + "description": "Convert character encodings in pure javascript.", + "version": "0.4.23", + "license": "MIT", + "keywords": [ + "iconv", + "convert", + "charset", + "icu" + ], + "author": "Alexander Shtuchkin ", + "main": "./lib/index.js", + "typings": "./lib/index.d.ts", + "homepage": "https://github.com/ashtuchkin/iconv-lite", + "bugs": "https://github.com/ashtuchkin/iconv-lite/issues", + "repository": { + "type": "git", + "url": "git://github.com/ashtuchkin/iconv-lite.git" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "coverage": "istanbul cover _mocha -- --grep .", + "coverage-open": "open coverage/lcov-report/index.html", + "test": "mocha --reporter spec --grep ." + }, + "browser": { + "./lib/extend-node": false, + "./lib/streams": false + }, + "devDependencies": { + "mocha": "^3.1.0", + "request": "~2.81.0", + "unorm": "*", + "errto": "*", + "async": "*", + "istanbul": "*", + "semver": "*", + "iconv": "*" + }, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + } +} diff --git a/app/node_modules/inherits/LICENSE b/app/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/app/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/app/node_modules/inherits/README.md b/app/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/app/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/app/node_modules/inherits/inherits.js b/app/node_modules/inherits/inherits.js new file mode 100644 index 0000000..3b94763 --- /dev/null +++ b/app/node_modules/inherits/inherits.js @@ -0,0 +1,7 @@ +try { + var util = require('util'); + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + module.exports = require('./inherits_browser.js'); +} diff --git a/app/node_modules/inherits/inherits_browser.js b/app/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/app/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/app/node_modules/inherits/package.json b/app/node_modules/inherits/package.json new file mode 100644 index 0000000..7cf62b9 --- /dev/null +++ b/app/node_modules/inherits/package.json @@ -0,0 +1,29 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.3", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": "git://github.com/isaacs/inherits", + "license": "ISC", + "scripts": { + "test": "node test" + }, + "devDependencies": { + "tap": "^7.1.0" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ] +} diff --git a/app/node_modules/ini/LICENSE b/app/node_modules/ini/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/app/node_modules/ini/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/app/node_modules/ini/README.md b/app/node_modules/ini/README.md new file mode 100644 index 0000000..33df258 --- /dev/null +++ b/app/node_modules/ini/README.md @@ -0,0 +1,102 @@ +An ini format parser and serializer for node. + +Sections are treated as nested objects. Items before the first +heading are saved on the object directly. + +## Usage + +Consider an ini-file `config.ini` that looks like this: + + ; this comment is being ignored + scope = global + + [database] + user = dbuser + password = dbpassword + database = use_this_database + + [paths.default] + datadir = /var/lib/data + array[] = first value + array[] = second value + array[] = third value + +You can read, manipulate and write the ini-file like so: + + var fs = require('fs') + , ini = require('ini') + + var config = ini.parse(fs.readFileSync('./config.ini', 'utf-8')) + + config.scope = 'local' + config.database.database = 'use_another_database' + config.paths.default.tmpdir = '/tmp' + delete config.paths.default.datadir + config.paths.default.array.push('fourth value') + + fs.writeFileSync('./config_modified.ini', ini.stringify(config, { section: 'section' })) + +This will result in a file called `config_modified.ini` being written +to the filesystem with the following content: + + [section] + scope=local + [section.database] + user=dbuser + password=dbpassword + database=use_another_database + [section.paths.default] + tmpdir=/tmp + array[]=first value + array[]=second value + array[]=third value + array[]=fourth value + + +## API + +### decode(inistring) + +Decode the ini-style formatted `inistring` into a nested object. + +### parse(inistring) + +Alias for `decode(inistring)` + +### encode(object, [options]) + +Encode the object `object` into an ini-style formatted string. If the +optional parameter `section` is given, then all top-level properties +of the object are put into this section and the `section`-string is +prepended to all sub-sections, see the usage example above. + +The `options` object may contain the following: + +* `section` A string which will be the first `section` in the encoded + ini data. Defaults to none. +* `whitespace` Boolean to specify whether to put whitespace around the + `=` character. By default, whitespace is omitted, to be friendly to + some persnickety old parsers that don't tolerate it well. But some + find that it's more human-readable and pretty with the whitespace. + +For backwards compatibility reasons, if a `string` options is passed +in, then it is assumed to be the `section` value. + +### stringify(object, [options]) + +Alias for `encode(object, [options])` + +### safe(val) + +Escapes the string `val` such that it is safe to be used as a key or +value in an ini-file. Basically escapes quotes. For example + + ini.safe('"unsafe string"') + +would result in + + "\"unsafe string\"" + +### unsafe(val) + +Unescapes the string `val` diff --git a/app/node_modules/ini/ini.js b/app/node_modules/ini/ini.js new file mode 100644 index 0000000..590195d --- /dev/null +++ b/app/node_modules/ini/ini.js @@ -0,0 +1,194 @@ +exports.parse = exports.decode = decode + +exports.stringify = exports.encode = encode + +exports.safe = safe +exports.unsafe = unsafe + +var eol = typeof process !== 'undefined' && + process.platform === 'win32' ? '\r\n' : '\n' + +function encode (obj, opt) { + var children = [] + var out = '' + + if (typeof opt === 'string') { + opt = { + section: opt, + whitespace: false + } + } else { + opt = opt || {} + opt.whitespace = opt.whitespace === true + } + + var separator = opt.whitespace ? ' = ' : '=' + + Object.keys(obj).forEach(function (k, _, __) { + var val = obj[k] + if (val && Array.isArray(val)) { + val.forEach(function (item) { + out += safe(k + '[]') + separator + safe(item) + '\n' + }) + } else if (val && typeof val === 'object') { + children.push(k) + } else { + out += safe(k) + separator + safe(val) + eol + } + }) + + if (opt.section && out.length) { + out = '[' + safe(opt.section) + ']' + eol + out + } + + children.forEach(function (k, _, __) { + var nk = dotSplit(k).join('\\.') + var section = (opt.section ? opt.section + '.' : '') + nk + var child = encode(obj[k], { + section: section, + whitespace: opt.whitespace + }) + if (out.length && child.length) { + out += eol + } + out += child + }) + + return out +} + +function dotSplit (str) { + return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002') + .replace(/\\\./g, '\u0001') + .split(/\./).map(function (part) { + return part.replace(/\1/g, '\\.') + .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001') + }) +} + +function decode (str) { + var out = {} + var p = out + var section = null + // section |key = value + var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i + var lines = str.split(/[\r\n]+/g) + + lines.forEach(function (line, _, __) { + if (!line || line.match(/^\s*[;#]/)) return + var match = line.match(re) + if (!match) return + if (match[1] !== undefined) { + section = unsafe(match[1]) + p = out[section] = out[section] || {} + return + } + var key = unsafe(match[2]) + var value = match[3] ? unsafe(match[4]) : true + switch (value) { + case 'true': + case 'false': + case 'null': value = JSON.parse(value) + } + + // Convert keys with '[]' suffix to an array + if (key.length > 2 && key.slice(-2) === '[]') { + key = key.substring(0, key.length - 2) + if (!p[key]) { + p[key] = [] + } else if (!Array.isArray(p[key])) { + p[key] = [p[key]] + } + } + + // safeguard against resetting a previously defined + // array by accidentally forgetting the brackets + if (Array.isArray(p[key])) { + p[key].push(value) + } else { + p[key] = value + } + }) + + // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}} + // use a filter to return the keys that have to be deleted. + Object.keys(out).filter(function (k, _, __) { + if (!out[k] || + typeof out[k] !== 'object' || + Array.isArray(out[k])) { + return false + } + // see if the parent section is also an object. + // if so, add it to that, and mark this one for deletion + var parts = dotSplit(k) + var p = out + var l = parts.pop() + var nl = l.replace(/\\\./g, '.') + parts.forEach(function (part, _, __) { + if (!p[part] || typeof p[part] !== 'object') p[part] = {} + p = p[part] + }) + if (p === out && nl === l) { + return false + } + p[nl] = out[k] + return true + }).forEach(function (del, _, __) { + delete out[del] + }) + + return out +} + +function isQuoted (val) { + return (val.charAt(0) === '"' && val.slice(-1) === '"') || + (val.charAt(0) === "'" && val.slice(-1) === "'") +} + +function safe (val) { + return (typeof val !== 'string' || + val.match(/[=\r\n]/) || + val.match(/^\[/) || + (val.length > 1 && + isQuoted(val)) || + val !== val.trim()) + ? JSON.stringify(val) + : val.replace(/;/g, '\\;').replace(/#/g, '\\#') +} + +function unsafe (val, doUnesc) { + val = (val || '').trim() + if (isQuoted(val)) { + // remove the single quotes before calling JSON.parse + if (val.charAt(0) === "'") { + val = val.substr(1, val.length - 2) + } + try { val = JSON.parse(val) } catch (_) {} + } else { + // walk the val to find the first not-escaped ; character + var esc = false + var unesc = '' + for (var i = 0, l = val.length; i < l; i++) { + var c = val.charAt(i) + if (esc) { + if ('\\;#'.indexOf(c) !== -1) { + unesc += c + } else { + unesc += '\\' + c + } + esc = false + } else if (';#'.indexOf(c) !== -1) { + break + } else if (c === '\\') { + esc = true + } else { + unesc += c + } + } + if (esc) { + unesc += '\\' + } + return unesc.trim() + } + return val +} diff --git a/app/node_modules/ini/package.json b/app/node_modules/ini/package.json new file mode 100644 index 0000000..269bc15 --- /dev/null +++ b/app/node_modules/ini/package.json @@ -0,0 +1,30 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "name": "ini", + "description": "An ini encoder/decoder for node", + "version": "1.3.5", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/ini.git" + }, + "main": "ini.js", + "scripts": { + "pretest": "standard ini.js", + "test": "tap test/*.js --100 -J", + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --all; git push origin --tags" + }, + "engines": { + "node": "*" + }, + "dependencies": {}, + "devDependencies": { + "standard": "^10.0.3", + "tap": "^10.7.3 || 11" + }, + "license": "ISC", + "files": [ + "ini.js" + ] +} diff --git a/app/node_modules/invert-kv/index.js b/app/node_modules/invert-kv/index.js new file mode 100644 index 0000000..61e2196 --- /dev/null +++ b/app/node_modules/invert-kv/index.js @@ -0,0 +1,15 @@ +'use strict'; +module.exports = function (obj) { + if (typeof obj !== 'object') { + throw new TypeError('Expected an object'); + } + + var ret = {}; + + for (var key in obj) { + var val = obj[key]; + ret[val] = key; + } + + return ret; +}; diff --git a/app/node_modules/invert-kv/package.json b/app/node_modules/invert-kv/package.json new file mode 100644 index 0000000..1e85d9b --- /dev/null +++ b/app/node_modules/invert-kv/package.json @@ -0,0 +1,33 @@ +{ + "name": "invert-kv", + "version": "1.0.0", + "description": "Invert the key/value of an object. Example: {foo: 'bar'} → {bar: 'foo'}", + "license": "MIT", + "repository": "sindresorhus/invert-kv", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "http://sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "files": [ + "index.js" + ], + "keywords": [ + "object", + "obj", + "key", + "value", + "val", + "kv", + "invert" + ], + "devDependencies": { + "mocha": "*" + } +} diff --git a/app/node_modules/invert-kv/readme.md b/app/node_modules/invert-kv/readme.md new file mode 100644 index 0000000..039fc7c --- /dev/null +++ b/app/node_modules/invert-kv/readme.md @@ -0,0 +1,25 @@ +# invert-kv [![Build Status](https://travis-ci.org/sindresorhus/invert-kv.svg?branch=master)](https://travis-ci.org/sindresorhus/invert-kv) + +> Invert the key/value of an object. Example: `{foo: 'bar'}` → `{bar: 'foo'}` + + +## Install + +```sh +$ npm install --save invert-kv +``` + + +## Usage + +```js +var invertKv = require('invert-kv'); + +invertKv({foo: 'bar', unicorn: 'rainbow'}); +//=> {bar: 'foo', rainbow: 'unicorn'} +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/app/node_modules/ipaddr.js/LICENSE b/app/node_modules/ipaddr.js/LICENSE new file mode 100644 index 0000000..f6b37b5 --- /dev/null +++ b/app/node_modules/ipaddr.js/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011-2017 whitequark + +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/app/node_modules/ipaddr.js/README.md b/app/node_modules/ipaddr.js/README.md new file mode 100644 index 0000000..f57725b --- /dev/null +++ b/app/node_modules/ipaddr.js/README.md @@ -0,0 +1,233 @@ +# ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js) + +ipaddr.js is a small (1.9K minified and gzipped) library for manipulating +IP addresses in JavaScript environments. It runs on both CommonJS runtimes +(e.g. [nodejs]) and in a web browser. + +ipaddr.js allows you to verify and parse string representation of an IP +address, match it against a CIDR range or range list, determine if it falls +into some reserved ranges (examples include loopback and private ranges), +and convert between IPv4 and IPv4-mapped IPv6 addresses. + +[nodejs]: http://nodejs.org + +## Installation + +`npm install ipaddr.js` + +or + +`bower install ipaddr.js` + +## API + +ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, +it is exported from the module: + +```js +var ipaddr = require('ipaddr.js'); +``` + +The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. + +### Global methods + +There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and +`ipaddr.process`. All of them receive a string as a single parameter. + +The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or +IPv6 address, and `false` otherwise. It does not throw any exceptions. + +The `ipaddr.parse` method returns an object representing the IP address, +or throws an `Error` if the passed string is not a valid representation of an +IP address. + +The `ipaddr.process` method works just like the `ipaddr.parse` one, but it +automatically converts IPv4-mapped IPv6 addresses to their IPv4 counterparts +before returning. It is useful when you have a Node.js instance listening +on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its +equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 +connections on your IPv6-only socket, but the remote address will be mangled. +Use `ipaddr.process` method to automatically demangle it. + +### Object representation + +Parsing methods return an object which descends from `ipaddr.IPv6` or +`ipaddr.IPv4`. These objects share some properties, but most of them differ. + +#### Shared properties + +One can determine the type of address by calling `addr.kind()`. It will return +either `"ipv6"` or `"ipv4"`. + +An address can be converted back to its string representation with `addr.toString()`. +Note that this method: + * does not return the original string used to create the object (in fact, there is + no way of getting that string) + * returns a compact representation (when it is applicable) + +A `match(range, bits)` method can be used to check if the address falls into a +certain CIDR range. +Note that an address can be (obviously) matched only against an address of the same type. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); +var range = ipaddr.parse("2001:db8::"); + +addr.match(range, 32); // => true +``` + +Alternatively, `match` can also be called as `match([range, bits])`. In this way, +it can be used together with the `parseCIDR(string)` method, which parses an IP +address together with a CIDR range. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); + +addr.match(ipaddr.parseCIDR("2001:db8::/32")); // => true +``` + +A `range()` method returns one of predefined names for several special ranges defined +by IP protocols. The exact names (and their respective CIDR ranges) can be looked up +in the source: [IPv6 ranges] and [IPv4 ranges]. Some common ones include `"unicast"` +(the default one) and `"reserved"`. + +You can match against your own range list by using +`ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with a mix of IPv6 or IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: + +```js +var rangeList = { + documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], + tunnelProviders: [ + [ ipaddr.parse('2001:470::'), 32 ], // he.net + [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 + ] +}; +ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "tunnelProviders" +``` + +The addresses can be converted to their byte representation with `toByteArray()`. +(Actually, JavaScript mostly does not know about byte buffers. They are emulated with +arrays of numbers, each in range of 0..255.) + +```js +var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com +bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, , 0x00, 0x68 ] +``` + +The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them +have the same interface for both protocols, and are similar to global methods. + +`ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address +for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. + +`ipaddr.IPvX.isValid(string)` uses the same format for parsing as the POSIX `inet_ntoa` function, which accepts unusual formats like `0xc0.168.1.1` or `0x10000000`. The function `ipaddr.IPv4.isValidFourPartDecimal(string)` validates the IPv4 address and also ensures that it is written in four-part decimal format. + +[IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186 +[IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71 + +#### IPv6 properties + +Sometimes you will want to convert IPv6 not to a compact string representation (with +the `::` substitution); the `toNormalizedString()` method will return an address where +all zeroes are explicit. + +For example: + +```js +var addr = ipaddr.parse("2001:0db8::0001"); +addr.toString(); // => "2001:db8::1" +addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1" +``` + +The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped +one, and `toIPv4Address()` will return an IPv4 object address. + +To access the underlying binary representation of the address, use `addr.parts`. + +```js +var addr = ipaddr.parse("2001:db8:10::1234:DEAD"); +addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] +``` + +A IPv6 zone index can be accessed via `addr.zoneId`: + +```js +var addr = ipaddr.parse("2001:db8::%eth0"); +addr.zoneId // => 'eth0' +``` + +#### IPv4 properties + +`toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. + +To access the underlying representation of the address, use `addr.octets`. + +```js +var addr = ipaddr.parse("192.168.1.1"); +addr.octets // => [192, 168, 1, 1] +``` + +`prefixLengthFromSubnetMask()` will return a CIDR prefix length for a valid IPv4 netmask or +null if the netmask is not valid. + +```js +ipaddr.IPv4.parse('255.255.255.240').prefixLengthFromSubnetMask() == 28 +ipaddr.IPv4.parse('255.192.164.0').prefixLengthFromSubnetMask() == null +``` + +`subnetMaskFromPrefixLength()` will return an IPv4 netmask for a valid CIDR prefix length. + +```js +ipaddr.IPv4.subnetMaskFromPrefixLength(24) == "255.255.255.0" +ipaddr.IPv4.subnetMaskFromPrefixLength(29) == "255.255.255.248" +``` + +`broadcastAddressFromCIDR()` will return the broadcast address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.broadcastAddressFromCIDR("172.0.0.1/24") == "172.0.0.255" +``` +`networkAddressFromCIDR()` will return the network address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.networkAddressFromCIDR("172.0.0.1/24") == "172.0.0.0" +``` + +#### Conversion + +IPv4 and IPv6 can be converted bidirectionally to and from network byte order (MSB) byte arrays. + +The `fromByteArray()` method will take an array and create an appropriate IPv4 or IPv6 object +if the input satisfies the requirements. For IPv4 it has to be an array of four 8-bit values, +while for IPv6 it has to be an array of sixteen 8-bit values. + +For example: +```js +var addr = ipaddr.fromByteArray([0x7f, 0, 0, 1]); +addr.toString(); // => "127.0.0.1" +``` + +or + +```js +var addr = ipaddr.fromByteArray([0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) +addr.toString(); // => "2001:db8::1" +``` + +Both objects also offer a `toByteArray()` method, which returns an array in network byte order (MSB). + +For example: +```js +var addr = ipaddr.parse("127.0.0.1"); +addr.toByteArray(); // => [0x7f, 0, 0, 1] +``` + +or + +```js +var addr = ipaddr.parse("2001:db8::1"); +addr.toByteArray(); // => [0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] +``` diff --git a/app/node_modules/ipaddr.js/ipaddr.min.js b/app/node_modules/ipaddr.js/ipaddr.min.js new file mode 100644 index 0000000..b54a7cc --- /dev/null +++ b/app/node_modules/ipaddr.js/ipaddr.min.js @@ -0,0 +1 @@ +(function(){var r,t,n,e,i,o,a,s;t={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:s.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;e>0;){if((o=n-e)<0&&(o=0),r[i]>>o!=t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;null==n&&(n="unicast");for(o in t)for(!(a=t[o])[0]||a[0]instanceof Array||(a=[a]),e=0,i=a.length;e=0;t=n+=-1){if(!((e=this.octets[t])in a))return null;if(o=a[e],i&&0!==o)return null;8!==o&&(i=!0),r+=o}return 32-r},r}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(a=[],r=0,e=(o=t.slice(1,6)).length;r4294967295||a<0)throw new Error("ipaddr: address outside defined range");return function(){var r,t;for(t=[],o=r=0;r<=24;o=r+=8)t.push(a>>o&255);return t}().reverse()}return null},t.IPv6=function(){function r(r,t){var n,e,i,o,a,s;if(16===r.length)for(this.parts=[],n=e=0;e<=14;n=e+=2)this.parts.push(r[n]<<8|r[n+1]);else{if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=r}for(i=0,o=(s=this.parts).length;it&&(r=n.index,t=n[0].length);return t<0?i:i.substring(0,r)+"::"+i.substring(r+t)},r.prototype.toByteArray=function(){var r,t,n,e,i;for(r=[],t=0,n=(i=this.parts).length;t>8),r.push(255&e);return r},r.prototype.toNormalizedString=function(){var r,t,n;return r=function(){var r,n,e,i;for(i=[],r=0,n=(e=this.parts).length;r>8,255&r,n>>8,255&n])},r.prototype.prefixLengthFromSubnetMask=function(){var r,t,n,e,i,o,a;for(a={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r=0,i=!1,t=n=7;n>=0;t=n+=-1){if(!((e=this.parts[t])in a))return null;if(o=a[e],i&&0!==o)return null;16!==o&&(i=!0),r+=o}return 128-r},r}(),i="(?:[0-9a-f]+::?)+",o={zoneIndex:new RegExp("%[0-9a-z]{1,}","i"),native:new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?(%[0-9a-z]{1,})?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"(%[0-9a-z]{1,})?$","i")},r=function(r,t){var n,e,i,a,s,p;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for((p=(r.match(o.zoneIndex)||[])[0])&&(p=p.substring(1),r=r.replace(/%.+$/,"")),n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(s=t-n,a=":";s--;)a+="0:";return":"===(r=r.replace("::",a))[0]&&(r=r.slice(1)),":"===r[r.length-1]&&(r=r.slice(0,-1)),t=function(){var t,n,e,o;for(o=[],t=0,n=(e=r.split(":")).length;t=0&&t<=32)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv4.subnetMaskFromPrefixLength=function(r){var t,n,e;if((r=parseInt(r))<0||r>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(e=[0,0,0,0],n=0,t=Math.floor(r/8);n=0&&t<=128)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},t.isValid=function(r){return t.IPv6.isValid(r)||t.IPv4.isValid(r)},t.parse=function(r){if(t.IPv6.isValid(r))return t.IPv6.parse(r);if(t.IPv4.isValid(r))return t.IPv4.parse(r);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},t.parseCIDR=function(r){try{return t.IPv6.parseCIDR(r)}catch(n){n;try{return t.IPv4.parseCIDR(r)}catch(r){throw r,new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},t.fromByteArray=function(r){var n;if(4===(n=r.length))return new t.IPv4(r);if(16===n)return new t.IPv6(r);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},t.process=function(r){var t;return t=this.parse(r),"ipv6"===t.kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(this); \ No newline at end of file diff --git a/app/node_modules/ipaddr.js/lib/ipaddr.js b/app/node_modules/ipaddr.js/lib/ipaddr.js new file mode 100644 index 0000000..18bd93b --- /dev/null +++ b/app/node_modules/ipaddr.js/lib/ipaddr.js @@ -0,0 +1,673 @@ +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; + + ipaddr = {}; + + root = this; + + if ((typeof module !== "undefined" && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } + + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + } + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; + } + return true; + }; + + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var k, len, rangeName, rangeSubnets, subnet; + if (defaultName == null) { + defaultName = 'unicast'; + } + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (k = 0, len = rangeSubnets.length; k < len; k++) { + subnet = rangeSubnets[k]; + if (address.kind() === subnet[0].kind()) { + if (address.match.apply(address, subnet)) { + return rangeName; + } + } + } + } + return defaultName; + }; + + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var k, len, octet; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); + } + } + this.octets = octets; + } + + IPv4.prototype.kind = function() { + return 'ipv4'; + }; + + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + + IPv4.prototype.toNormalizedString = function() { + return this.toString(); + }; + + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; + + IPv4.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv4') { + throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; + + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; + + IPv4.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, octet, stop, zeros, zerotable; + zerotable = { + 0: 8, + 128: 7, + 192: 6, + 224: 5, + 240: 4, + 248: 3, + 252: 2, + 254: 1, + 255: 0 + }; + cidr = 0; + stop = false; + for (i = k = 3; k >= 0; i = k += -1) { + octet = this.octets[i]; + if (octet in zerotable) { + zeros = zerotable[octet]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 8) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 32 - cidr; + }; + + return IPv4; + + })(); + + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; + + ipaddr.IPv4.parser = function(string) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string) { + if (string[0] === "0" && string[1] !== "x") { + return parseInt(string, 8); + } else { + return parseInt(string); + } + }; + if (match = string.match(ipv4Regexes.fourOctet)) { + return (function() { + var k, len, ref, results; + ref = match.slice(1, 6); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseIntAuto(part)); + } + return results; + })(); + } else if (match = string.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return ((function() { + var k, results; + results = []; + for (shift = k = 0; k <= 24; shift = k += 8) { + results.push((value >> shift) & 0xff); + } + return results; + })()).reverse(); + } else { + return null; + } + }; + + ipaddr.IPv6 = (function() { + function IPv6(parts, zoneId) { + var i, k, l, len, part, ref; + if (parts.length === 16) { + this.parts = []; + for (i = k = 0; k <= 14; i = k += 2) { + this.parts.push((parts[i] << 8) | parts[i + 1]); + } + } else if (parts.length === 8) { + this.parts = parts; + } else { + throw new Error("ipaddr: ipv6 part count should be 8 or 16"); + } + ref = this.parts; + for (l = 0, len = ref.length; l < len; l++) { + part = ref[l]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error("ipaddr: ipv6 part should fit in 16 bits"); + } + } + if (zoneId) { + this.zoneId = zoneId; + } + } + + IPv6.prototype.kind = function() { + return 'ipv6'; + }; + + IPv6.prototype.toString = function() { + return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); + }; + + IPv6.prototype.toRFC5952String = function() { + var bestMatchIndex, bestMatchLength, match, regex, string; + regex = /((^|:)(0(:|$)){2,})/g; + string = this.toNormalizedString(); + bestMatchIndex = 0; + bestMatchLength = -1; + while ((match = regex.exec(string))) { + if (match[0].length > bestMatchLength) { + bestMatchIndex = match.index; + bestMatchLength = match[0].length; + } + } + if (bestMatchLength < 0) { + return string; + } + return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength); + }; + + IPv6.prototype.toByteArray = function() { + var bytes, k, len, part, ref; + bytes = []; + ref = this.parts; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + return bytes; + }; + + IPv6.prototype.toNormalizedString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16)); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; + + IPv6.prototype.toFixedLengthString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16).padStart(4, '0')); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; + + IPv6.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv6') { + throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; + + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] + }; + + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; + + IPv6.prototype.toIPv4Address = function() { + var high, low, ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + ref = this.parts.slice(-2), high = ref[0], low = ref[1]; + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; + + IPv6.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, part, stop, zeros, zerotable; + zerotable = { + 0: 16, + 32768: 15, + 49152: 14, + 57344: 13, + 61440: 12, + 63488: 11, + 64512: 10, + 65024: 9, + 65280: 8, + 65408: 7, + 65472: 6, + 65504: 5, + 65520: 4, + 65528: 3, + 65532: 2, + 65534: 1, + 65535: 0 + }; + cidr = 0; + stop = false; + for (i = k = 7; k >= 0; i = k += -1) { + part = this.parts[i]; + if (part in zerotable) { + zeros = zerotable[part]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 16) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 128 - cidr; + }; + + return IPv6; + + })(); + + ipv6Part = "(?:[0-9a-f]+::?)+"; + + zoneIndex = "%[0-9a-z]{1,}"; + + ipv6Regexes = { + zoneIndex: new RegExp(zoneIndex, 'i'), + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'), + transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i') + }; + + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount, zoneId; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; + } + zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; + if (zoneId) { + zoneId = zoneId.substring(1); + string = string.replace(/%.+$/, ''); + } + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; + } + if (string.substr(0, 2) === '::') { + colonCount--; + } + if (string.substr(-2, 2) === '::') { + colonCount--; + } + if (colonCount > parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; + } + string = string.replace('::', replacement); + if (string[0] === ':') { + string = string.slice(1); + } + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + parts = (function() { + var k, len, ref, results; + ref = string.split(":"); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseInt(part, 16)); + } + return results; + })(); + return { + parts: parts, + zoneId: zoneId + }; + }; + + ipaddr.IPv6.parser = function(string) { + var addr, k, len, match, octet, octets, zoneId; + if (ipv6Regexes['native'].test(string)) { + return expandIPv6(string, 8); + } else if (match = string.match(ipv6Regexes['transitional'])) { + zoneId = match[6] || ''; + addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); + if (addr.parts) { + octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + return null; + } + } + addr.parts.push(octets[0] << 8 | octets[1]); + addr.parts.push(octets[2] << 8 | octets[3]); + return { + parts: addr.parts, + zoneId: addr.zoneId + }; + } + } + return null; + }; + + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; + + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + + ipaddr.IPv4.isValidFourPartDecimal = function(string) { + if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { + return true; + } else { + return false; + } + }; + + ipaddr.IPv6.isValid = function(string) { + var addr, e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; + } + try { + addr = this.parser(string); + new this(addr.parts, addr.zoneId); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + + ipaddr.IPv4.parse = function(string) { + var parts; + parts = this.parser(string); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(parts); + }; + + ipaddr.IPv6.parse = function(string) { + var addr; + addr = this.parser(string); + if (addr.parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(addr.parts, addr.zoneId); + }; + + ipaddr.IPv4.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; + + ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { + var filledOctetCount, j, octets; + prefix = parseInt(prefix); + if (prefix < 0 || prefix > 32) { + throw new Error('ipaddr: invalid IPv4 prefix length'); + } + octets = [0, 0, 0, 0]; + j = 0; + filledOctetCount = Math.floor(prefix / 8); + while (j < filledOctetCount) { + octets[j] = 255; + j++; + } + if (filledOctetCount < 4) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); + } + return new this(octets); + }; + + ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + ipaddr.IPv4.networkAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + ipaddr.IPv6.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; + + ipaddr.parse = function(string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + + ipaddr.parseCIDR = function(string) { + var e; + try { + return ipaddr.IPv6.parseCIDR(string); + } catch (error1) { + e = error1; + try { + return ipaddr.IPv4.parseCIDR(string); + } catch (error1) { + e = error1; + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); + } + } + }; + + ipaddr.fromByteArray = function(bytes) { + var length; + length = bytes.length; + if (length === 4) { + return new ipaddr.IPv4(bytes); + } else if (length === 16) { + return new ipaddr.IPv6(bytes); + } else { + throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); + } + }; + + ipaddr.process = function(string) { + var addr; + addr = this.parse(string); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; + +}).call(this); diff --git a/app/node_modules/ipaddr.js/lib/ipaddr.js.d.ts b/app/node_modules/ipaddr.js/lib/ipaddr.js.d.ts new file mode 100644 index 0000000..52174b6 --- /dev/null +++ b/app/node_modules/ipaddr.js/lib/ipaddr.js.d.ts @@ -0,0 +1,68 @@ +declare module "ipaddr.js" { + type IPv4Range = 'unicast' | 'unspecified' | 'broadcast' | 'multicast' | 'linkLocal' | 'loopback' | 'carrierGradeNat' | 'private' | 'reserved'; + type IPv6Range = 'unicast' | 'unspecified' | 'linkLocal' | 'multicast' | 'loopback' | 'uniqueLocal' | 'ipv4Mapped' | 'rfc6145' | 'rfc6052' | '6to4' | 'teredo' | 'reserved'; + + interface RangeList { + [name: string]: [T, number] | [T, number][]; + } + + // Common methods/properties for IPv4 and IPv6 classes. + class IP { + prefixLengthFromSubnetMask(): number | null; + toByteArray(): number[]; + toNormalizedString(): string; + toString(): string; + } + + namespace Address { + export function isValid(addr: string): boolean; + export function fromByteArray(bytes: number[]): IPv4 | IPv6; + export function parse(addr: string): IPv4 | IPv6; + export function parseCIDR(mask: string): [IPv4 | IPv6, number]; + export function process(addr: string): IPv4 | IPv6; + export function subnetMatch(addr: IPv4, rangeList: RangeList, defaultName?: string): string; + export function subnetMatch(addr: IPv6, rangeList: RangeList, defaultName?: string): string; + + export class IPv4 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv4; + static isIPv4(addr: string): boolean; + static isValidFourPartDecimal(addr: string): boolean; + static isValid(addr: string): boolean; + static networkAddressFromCIDR(addr: string): IPv4; + static parse(addr: string): IPv4; + static parseCIDR(addr: string): [IPv4, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv4; + constructor(octets: number[]); + octets: number[] + + kind(): 'ipv4'; + match(addr: IPv4, bits: number): boolean; + match(mask: [IPv4, number]): boolean; + range(): IPv4Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4MappedAddress(): IPv6; + } + + export class IPv6 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv6; + static isIPv6(addr: string): boolean; + static isValid(addr: string): boolean; + static parse(addr: string): IPv6; + static parseCIDR(addr: string): [IPv6, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv6; + constructor(parts: number[]); + parts: number[] + zoneId?: string + + isIPv4MappedAddress(): boolean; + kind(): 'ipv6'; + match(addr: IPv6, bits: number): boolean; + match(mask: [IPv6, number]): boolean; + range(): IPv6Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4Address(): IPv4; + } + } + + export = Address; +} diff --git a/app/node_modules/ipaddr.js/package.json b/app/node_modules/ipaddr.js/package.json new file mode 100644 index 0000000..f4d3547 --- /dev/null +++ b/app/node_modules/ipaddr.js/package.json @@ -0,0 +1,35 @@ +{ + "name": "ipaddr.js", + "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", + "version": "1.9.1", + "author": "whitequark ", + "directories": { + "lib": "./lib" + }, + "dependencies": {}, + "devDependencies": { + "coffee-script": "~1.12.6", + "nodeunit": "^0.11.3", + "uglify-js": "~3.0.19" + }, + "scripts": { + "test": "cake build test" + }, + "files": [ + "lib/", + "LICENSE", + "ipaddr.min.js" + ], + "keywords": [ + "ip", + "ipv4", + "ipv6" + ], + "repository": "git://github.com/whitequark/ipaddr.js", + "main": "./lib/ipaddr.js", + "engines": { + "node": ">= 0.10" + }, + "license": "MIT", + "types": "./lib/ipaddr.js.d.ts" +} diff --git a/app/node_modules/is-fullwidth-code-point/index.js b/app/node_modules/is-fullwidth-code-point/index.js new file mode 100644 index 0000000..a7d3e38 --- /dev/null +++ b/app/node_modules/is-fullwidth-code-point/index.js @@ -0,0 +1,46 @@ +'use strict'; +var numberIsNan = require('number-is-nan'); + +module.exports = function (x) { + if (numberIsNan(x)) { + return false; + } + + // https://github.com/nodejs/io.js/blob/cff7300a578be1b10001f2d967aaedc88aee6402/lib/readline.js#L1369 + + // code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if (x >= 0x1100 && ( + x <= 0x115f || // Hangul Jamo + 0x2329 === x || // LEFT-POINTING ANGLE BRACKET + 0x232a === x || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + 0x3250 <= x && x <= 0x4dbf || + // CJK Unified Ideographs .. Yi Radicals + 0x4e00 <= x && x <= 0xa4c6 || + // Hangul Jamo Extended-A + 0xa960 <= x && x <= 0xa97c || + // Hangul Syllables + 0xac00 <= x && x <= 0xd7a3 || + // CJK Compatibility Ideographs + 0xf900 <= x && x <= 0xfaff || + // Vertical Forms + 0xfe10 <= x && x <= 0xfe19 || + // CJK Compatibility Forms .. Small Form Variants + 0xfe30 <= x && x <= 0xfe6b || + // Halfwidth and Fullwidth Forms + 0xff01 <= x && x <= 0xff60 || + 0xffe0 <= x && x <= 0xffe6 || + // Kana Supplement + 0x1b000 <= x && x <= 0x1b001 || + // Enclosed Ideographic Supplement + 0x1f200 <= x && x <= 0x1f251 || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + 0x20000 <= x && x <= 0x3fffd)) { + return true; + } + + return false; +} diff --git a/app/node_modules/is-fullwidth-code-point/license b/app/node_modules/is-fullwidth-code-point/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/app/node_modules/is-fullwidth-code-point/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/app/node_modules/is-fullwidth-code-point/package.json b/app/node_modules/is-fullwidth-code-point/package.json new file mode 100644 index 0000000..b678d40 --- /dev/null +++ b/app/node_modules/is-fullwidth-code-point/package.json @@ -0,0 +1,45 @@ +{ + "name": "is-fullwidth-code-point", + "version": "1.0.0", + "description": "Check if the character represented by a given Unicode code point is fullwidth", + "license": "MIT", + "repository": "sindresorhus/is-fullwidth-code-point", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "node test.js" + }, + "files": [ + "index.js" + ], + "keywords": [ + "fullwidth", + "full-width", + "full", + "width", + "unicode", + "character", + "char", + "string", + "str", + "codepoint", + "code", + "point", + "is", + "detect", + "check" + ], + "dependencies": { + "number-is-nan": "^1.0.0" + }, + "devDependencies": { + "ava": "0.0.4", + "code-point-at": "^1.0.0" + } +} diff --git a/app/node_modules/is-fullwidth-code-point/readme.md b/app/node_modules/is-fullwidth-code-point/readme.md new file mode 100644 index 0000000..4936464 --- /dev/null +++ b/app/node_modules/is-fullwidth-code-point/readme.md @@ -0,0 +1,39 @@ +# is-fullwidth-code-point [![Build Status](https://travis-ci.org/sindresorhus/is-fullwidth-code-point.svg?branch=master)](https://travis-ci.org/sindresorhus/is-fullwidth-code-point) + +> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) + + +## Install + +``` +$ npm install --save is-fullwidth-code-point +``` + + +## Usage + +```js +var isFullwidthCodePoint = require('is-fullwidth-code-point'); + +isFullwidthCodePoint('谢'.codePointAt()); +//=> true + +isFullwidthCodePoint('a'.codePointAt()); +//=> false +``` + + +## API + +### isFullwidthCodePoint(input) + +#### input + +Type: `number` + +[Code point](https://en.wikipedia.org/wiki/Code_point) of a character. + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/app/node_modules/isarray/.npmignore b/app/node_modules/isarray/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/app/node_modules/isarray/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/app/node_modules/isarray/.travis.yml b/app/node_modules/isarray/.travis.yml new file mode 100644 index 0000000..cc4dba2 --- /dev/null +++ b/app/node_modules/isarray/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/app/node_modules/isarray/Makefile b/app/node_modules/isarray/Makefile new file mode 100644 index 0000000..787d56e --- /dev/null +++ b/app/node_modules/isarray/Makefile @@ -0,0 +1,6 @@ + +test: + @node_modules/.bin/tape test.js + +.PHONY: test + diff --git a/app/node_modules/isarray/README.md b/app/node_modules/isarray/README.md new file mode 100644 index 0000000..16d2c59 --- /dev/null +++ b/app/node_modules/isarray/README.md @@ -0,0 +1,60 @@ + +# isarray + +`Array#isArray` for older browsers. + +[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) +[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) + +[![browser support](https://ci.testling.com/juliangruber/isarray.png) +](https://ci.testling.com/juliangruber/isarray) + +## 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/app/node_modules/isarray/component.json b/app/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/app/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/app/node_modules/isarray/index.js b/app/node_modules/isarray/index.js new file mode 100644 index 0000000..a57f634 --- /dev/null +++ b/app/node_modules/isarray/index.js @@ -0,0 +1,5 @@ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; diff --git a/app/node_modules/isarray/package.json b/app/node_modules/isarray/package.json new file mode 100644 index 0000000..1a4317a --- /dev/null +++ b/app/node_modules/isarray/package.json @@ -0,0 +1,45 @@ +{ + "name": "isarray", + "description": "Array#isArray for older browsers", + "version": "1.0.0", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "homepage": "https://github.com/juliangruber/isarray", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tape": "~2.13.4" + }, + "keywords": [ + "browser", + "isarray", + "array" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test.js", + "browsers": [ + "ie/8..latest", + "firefox/17..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "scripts": { + "test": "tape test.js" + } +} diff --git a/app/node_modules/isarray/test.js b/app/node_modules/isarray/test.js new file mode 100644 index 0000000..e0c3444 --- /dev/null +++ b/app/node_modules/isarray/test.js @@ -0,0 +1,20 @@ +var isArray = require('./'); +var test = require('tape'); + +test('is array', function(t){ + t.ok(isArray([])); + t.notOk(isArray({})); + t.notOk(isArray(null)); + t.notOk(isArray(false)); + + var obj = {}; + obj[0] = true; + t.notOk(isArray(obj)); + + var arr = []; + arr.foo = 'bar'; + t.ok(isArray(arr)); + + t.end(); +}); + diff --git a/app/node_modules/isstream/.jshintrc b/app/node_modules/isstream/.jshintrc new file mode 100644 index 0000000..c8ef3ca --- /dev/null +++ b/app/node_modules/isstream/.jshintrc @@ -0,0 +1,59 @@ +{ + "predef": [ ] + , "bitwise": false + , "camelcase": false + , "curly": false + , "eqeqeq": false + , "forin": false + , "immed": false + , "latedef": false + , "noarg": true + , "noempty": true + , "nonew": true + , "plusplus": false + , "quotmark": true + , "regexp": false + , "undef": true + , "unused": true + , "strict": false + , "trailing": true + , "maxlen": 120 + , "asi": true + , "boss": true + , "debug": true + , "eqnull": true + , "esnext": true + , "evil": true + , "expr": true + , "funcscope": false + , "globalstrict": false + , "iterator": false + , "lastsemic": true + , "laxbreak": true + , "laxcomma": true + , "loopfunc": true + , "multistr": false + , "onecase": false + , "proto": false + , "regexdash": false + , "scripturl": true + , "smarttabs": false + , "shadow": false + , "sub": true + , "supernew": false + , "validthis": true + , "browser": true + , "couch": false + , "devel": false + , "dojo": false + , "mootools": false + , "node": true + , "nonstandard": true + , "prototypejs": false + , "rhino": false + , "worker": true + , "wsh": false + , "nomen": false + , "onevar": false + , "passfail": false +} \ No newline at end of file diff --git a/app/node_modules/isstream/.npmignore b/app/node_modules/isstream/.npmignore new file mode 100644 index 0000000..aa1ec1e --- /dev/null +++ b/app/node_modules/isstream/.npmignore @@ -0,0 +1 @@ +*.tgz diff --git a/app/node_modules/isstream/.travis.yml b/app/node_modules/isstream/.travis.yml new file mode 100644 index 0000000..1fec2ab --- /dev/null +++ b/app/node_modules/isstream/.travis.yml @@ -0,0 +1,12 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.11" +branches: + only: + - master +notifications: + email: + - rod@vagg.org +script: npm test diff --git a/app/node_modules/isstream/LICENSE.md b/app/node_modules/isstream/LICENSE.md new file mode 100644 index 0000000..43f7153 --- /dev/null +++ b/app/node_modules/isstream/LICENSE.md @@ -0,0 +1,11 @@ +The MIT License (MIT) +===================== + +Copyright (c) 2015 Rod Vagg +--------------------------- + +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/app/node_modules/isstream/README.md b/app/node_modules/isstream/README.md new file mode 100644 index 0000000..06770e8 --- /dev/null +++ b/app/node_modules/isstream/README.md @@ -0,0 +1,66 @@ +# isStream + +[![Build Status](https://secure.travis-ci.org/rvagg/isstream.png)](http://travis-ci.org/rvagg/isstream) + +**Test if an object is a `Stream`** + +[![NPM](https://nodei.co/npm/isstream.svg)](https://nodei.co/npm/isstream/) + +The missing `Stream.isStream(obj)`: determine if an object is standard Node.js `Stream`. Works for Node-core `Stream` objects (for 0.8, 0.10, 0.11, and in theory, older and newer versions) and all versions of **[readable-stream](https://github.com/isaacs/readable-stream)**. + +## Usage: + +```js +var isStream = require('isstream') +var Stream = require('stream') + +isStream(new Stream()) // true + +isStream({}) // false + +isStream(new Stream.Readable()) // true +isStream(new Stream.Writable()) // true +isStream(new Stream.Duplex()) // true +isStream(new Stream.Transform()) // true +isStream(new Stream.PassThrough()) // true +``` + +## But wait! There's more! + +You can also test for `isReadable(obj)`, `isWritable(obj)` and `isDuplex(obj)` to test for implementations of Streams2 (and Streams3) base classes. + +```js +var isReadable = require('isstream').isReadable +var isWritable = require('isstream').isWritable +var isDuplex = require('isstream').isDuplex +var Stream = require('stream') + +isReadable(new Stream()) // false +isWritable(new Stream()) // false +isDuplex(new Stream()) // false + +isReadable(new Stream.Readable()) // true +isReadable(new Stream.Writable()) // false +isReadable(new Stream.Duplex()) // true +isReadable(new Stream.Transform()) // true +isReadable(new Stream.PassThrough()) // true + +isWritable(new Stream.Readable()) // false +isWritable(new Stream.Writable()) // true +isWritable(new Stream.Duplex()) // true +isWritable(new Stream.Transform()) // true +isWritable(new Stream.PassThrough()) // true + +isDuplex(new Stream.Readable()) // false +isDuplex(new Stream.Writable()) // false +isDuplex(new Stream.Duplex()) // true +isDuplex(new Stream.Transform()) // true +isDuplex(new Stream.PassThrough()) // true +``` + +*Reminder: when implementing your own streams, please [use **readable-stream** rather than core streams](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).* + + +## License + +**isStream** is Copyright (c) 2015 Rod Vagg [@rvagg](https://twitter.com/rvagg) and licenced under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details. diff --git a/app/node_modules/isstream/isstream.js b/app/node_modules/isstream/isstream.js new file mode 100644 index 0000000..a1d104a --- /dev/null +++ b/app/node_modules/isstream/isstream.js @@ -0,0 +1,27 @@ +var stream = require('stream') + + +function isStream (obj) { + return obj instanceof stream.Stream +} + + +function isReadable (obj) { + return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object' +} + + +function isWritable (obj) { + return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object' +} + + +function isDuplex (obj) { + return isReadable(obj) && isWritable(obj) +} + + +module.exports = isStream +module.exports.isReadable = isReadable +module.exports.isWritable = isWritable +module.exports.isDuplex = isDuplex diff --git a/app/node_modules/isstream/package.json b/app/node_modules/isstream/package.json new file mode 100644 index 0000000..9ee8bf8 --- /dev/null +++ b/app/node_modules/isstream/package.json @@ -0,0 +1,33 @@ +{ + "name": "isstream", + "version": "0.1.2", + "description": "Determine if an object is a Stream", + "main": "isstream.js", + "scripts": { + "test": "tar --xform 's/^package/readable-stream-1.0/' -zxf readable-stream-1.0.*.tgz && tar --xform 's/^package/readable-stream-1.1/' -zxf readable-stream-1.1.*.tgz && node test.js; rm -rf readable-stream-1.?/" + }, + "repository": { + "type": "git", + "url": "https://github.com/rvagg/isstream.git" + }, + "keywords": [ + "stream", + "type", + "streams", + "readable-stream", + "hippo" + ], + "devDependencies": { + "tape": "~2.12.3", + "core-util-is": "~1.0.0", + "isarray": "0.0.1", + "string_decoder": "~0.10.x", + "inherits": "~2.0.1" + }, + "author": "Rod Vagg ", + "license": "MIT", + "bugs": { + "url": "https://github.com/rvagg/isstream/issues" + }, + "homepage": "https://github.com/rvagg/isstream" +} diff --git a/app/node_modules/isstream/test.js b/app/node_modules/isstream/test.js new file mode 100644 index 0000000..8c950c5 --- /dev/null +++ b/app/node_modules/isstream/test.js @@ -0,0 +1,168 @@ +var tape = require('tape') + , EE = require('events').EventEmitter + , util = require('util') + + + , isStream = require('./') + , isReadable = require('./').isReadable + , isWritable = require('./').isWritable + , isDuplex = require('./').isDuplex + + , CoreStreams = require('stream') + , ReadableStream10 = require('./readable-stream-1.0/') + , ReadableStream11 = require('./readable-stream-1.1/') + + +function test (pass, type, stream) { + tape('isStream(' + type + ')', function (t) { + t.plan(1) + t.ok(pass === isStream(stream), type) + }) +} + + +function testReadable (pass, type, stream) { + tape('isReadable(' + type + ')', function (t) { + t.plan(1) + t.ok(pass === isReadable(stream), type) + }) +} + + +function testWritable (pass, type, stream) { + tape('isWritable(' + type + ')', function (t) { + t.plan(1) + t.ok(pass === isWritable(stream), type) + }) +} + + +function testDuplex (pass, type, stream) { + tape('isDuplex(' + type + ')', function (t) { + t.plan(1) + t.ok(pass === isDuplex(stream), type) + }) +} + + +[ undefined, null, '', true, false, 0, 1, 1.0, 'string', {}, function foo () {} ].forEach(function (o) { + test(false, 'non-stream / primitive: ' + (JSON.stringify(o) || (o && o.toString()) || o), o) +}) + + +test(false, 'fake stream obj', { pipe: function () {} }) + + +;(function () { + + // looks like a stream! + + function Stream () { + EE.call(this) + } + util.inherits(Stream, EE) + Stream.prototype.pipe = function () {} + Stream.Stream = Stream + + test(false, 'fake stream "new Stream()"', new Stream()) + +}()) + + +test(true, 'CoreStreams.Stream', new (CoreStreams.Stream)()) +test(true, 'CoreStreams.Readable', new (CoreStreams.Readable)()) +test(true, 'CoreStreams.Writable', new (CoreStreams.Writable)()) +test(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)()) +test(true, 'CoreStreams.Transform', new (CoreStreams.Transform)()) +test(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)()) + +test(true, 'ReadableStream10.Readable', new (ReadableStream10.Readable)()) +test(true, 'ReadableStream10.Writable', new (ReadableStream10.Writable)()) +test(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)()) +test(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)()) +test(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)()) + +test(true, 'ReadableStream11.Readable', new (ReadableStream11.Readable)()) +test(true, 'ReadableStream11.Writable', new (ReadableStream11.Writable)()) +test(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)()) +test(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)()) +test(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)()) + + +testReadable(false, 'CoreStreams.Stream', new (CoreStreams.Stream)()) +testReadable(true, 'CoreStreams.Readable', new (CoreStreams.Readable)()) +testReadable(false, 'CoreStreams.Writable', new (CoreStreams.Writable)()) +testReadable(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)()) +testReadable(true, 'CoreStreams.Transform', new (CoreStreams.Transform)()) +testReadable(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)()) + +testReadable(true, 'ReadableStream10.Readable', new (ReadableStream10.Readable)()) +testReadable(false, 'ReadableStream10.Writable', new (ReadableStream10.Writable)()) +testReadable(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)()) +testReadable(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)()) +testReadable(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)()) + +testReadable(true, 'ReadableStream11.Readable', new (ReadableStream11.Readable)()) +testReadable(false, 'ReadableStream11.Writable', new (ReadableStream11.Writable)()) +testReadable(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)()) +testReadable(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)()) +testReadable(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)()) + + +testWritable(false, 'CoreStreams.Stream', new (CoreStreams.Stream)()) +testWritable(false, 'CoreStreams.Readable', new (CoreStreams.Readable)()) +testWritable(true, 'CoreStreams.Writable', new (CoreStreams.Writable)()) +testWritable(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)()) +testWritable(true, 'CoreStreams.Transform', new (CoreStreams.Transform)()) +testWritable(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)()) + +testWritable(false, 'ReadableStream10.Readable', new (ReadableStream10.Readable)()) +testWritable(true, 'ReadableStream10.Writable', new (ReadableStream10.Writable)()) +testWritable(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)()) +testWritable(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)()) +testWritable(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)()) + +testWritable(false, 'ReadableStream11.Readable', new (ReadableStream11.Readable)()) +testWritable(true, 'ReadableStream11.Writable', new (ReadableStream11.Writable)()) +testWritable(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)()) +testWritable(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)()) +testWritable(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)()) + + +testDuplex(false, 'CoreStreams.Stream', new (CoreStreams.Stream)()) +testDuplex(false, 'CoreStreams.Readable', new (CoreStreams.Readable)()) +testDuplex(false, 'CoreStreams.Writable', new (CoreStreams.Writable)()) +testDuplex(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)()) +testDuplex(true, 'CoreStreams.Transform', new (CoreStreams.Transform)()) +testDuplex(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)()) + +testDuplex(false, 'ReadableStream10.Readable', new (ReadableStream10.Readable)()) +testDuplex(false, 'ReadableStream10.Writable', new (ReadableStream10.Writable)()) +testDuplex(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)()) +testDuplex(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)()) +testDuplex(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)()) + +testDuplex(false, 'ReadableStream11.Readable', new (ReadableStream11.Readable)()) +testDuplex(false, 'ReadableStream11.Writable', new (ReadableStream11.Writable)()) +testDuplex(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)()) +testDuplex(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)()) +testDuplex(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)()) + + +;[ CoreStreams, ReadableStream10, ReadableStream11 ].forEach(function (p) { + [ 'Stream', 'Readable', 'Writable', 'Duplex', 'Transform', 'PassThrough' ].forEach(function (k) { + if (!p[k]) + return + + function SubStream () { + p[k].call(this) + } + util.inherits(SubStream, p[k]) + + test(true, 'Stream subclass: ' + p.name + '.' + k, new SubStream()) + + }) +}) + + + diff --git a/app/node_modules/kareem/.npmignore b/app/node_modules/kareem/.npmignore new file mode 100644 index 0000000..59d842b --- /dev/null +++ b/app/node_modules/kareem/.npmignore @@ -0,0 +1,28 @@ +# Logs +logs +*.log + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +# Commenting this out is preferred by some people, see +# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- +node_modules + +# Users Environment Variables +.lock-wscript diff --git a/app/node_modules/kareem/.travis.yml b/app/node_modules/kareem/.travis.yml new file mode 100644 index 0000000..d28cb66 --- /dev/null +++ b/app/node_modules/kareem/.travis.yml @@ -0,0 +1,10 @@ +language: node_js +node_js: + - "6" + - "5" + - "4" + - "0.12" + - "0.10" + - "iojs" +script: "npm run-script test-travis" +after_script: "npm install coveralls@2.10.0 && cat ./coverage/lcov.info | coveralls" diff --git a/app/node_modules/kareem/LICENSE b/app/node_modules/kareem/LICENSE new file mode 100644 index 0000000..e06d208 --- /dev/null +++ b/app/node_modules/kareem/LICENSE @@ -0,0 +1,202 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/app/node_modules/kareem/Makefile b/app/node_modules/kareem/Makefile new file mode 100644 index 0000000..f71ba90 --- /dev/null +++ b/app/node_modules/kareem/Makefile @@ -0,0 +1,5 @@ +docs: + node ./docs.js + +coverage: + ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- -R spec ./test/* diff --git a/app/node_modules/kareem/README.md b/app/node_modules/kareem/README.md new file mode 100644 index 0000000..7d2dc84 --- /dev/null +++ b/app/node_modules/kareem/README.md @@ -0,0 +1,379 @@ +# kareem + + [![Build Status](https://travis-ci.org/vkarpov15/kareem.svg?branch=master)](https://travis-ci.org/vkarpov15/kareem) + [![Coverage Status](https://img.shields.io/coveralls/vkarpov15/kareem.svg)](https://coveralls.io/r/vkarpov15/kareem) + +Re-imagined take on the [hooks](http://npmjs.org/package/hooks) module, meant to offer additional flexibility in allowing you to execute hooks whenever necessary, as opposed to simply wrapping a single function. + +Named for the NBA's all-time leading scorer Kareem Abdul-Jabbar, known for his mastery of the [hook shot](http://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar#Skyhook) + + + +# API + +## pre hooks + +Much like [hooks](https://npmjs.org/package/hooks), kareem lets you define +pre and post hooks: pre hooks are called before a given function executes. +Unlike hooks, kareem stores hooks and other internal state in a separate +object, rather than relying on inheritance. Furthermore, kareem exposes +an `execPre()` function that allows you to execute your pre hooks when +appropriate, giving you more fine-grained control over your function hooks. + + +#### It runs without any hooks specified + +```javascript + + hooks.execPre('cook', null, function() { + done(); + }); + +``` + +#### It runs basic serial pre hooks + +pre hook functions take one parameter, a "done" function that you execute +when your pre hook is finished. + + +```javascript + + var count = 0; + + hooks.pre('cook', function(done) { + ++count; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count); + done(); + }); + +``` + +#### It can run multipe pre hooks + +```javascript + + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function(done) { + ++count1; + done(); + }); + + hooks.pre('cook', function(done) { + ++count2; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + +``` + +#### It can run fully synchronous pre hooks + +If your pre hook function takes no parameters, its assumed to be +fully synchronous. + + +```javascript + + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function() { + ++count1; + }); + + hooks.pre('cook', function() { + ++count2; + }); + + hooks.execPre('cook', null, function(error) { + assert.equal(null, error); + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + +``` + +#### It properly attaches context to pre hooks + +Pre save hook functions are bound to the second parameter to `execPre()` + + +```javascript + + hooks.pre('cook', function(done) { + this.bacon = 3; + done(); + }); + + hooks.pre('cook', function(done) { + this.eggs = 4; + done(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + // In the pre hooks, `this` will refer to `obj` + hooks.execPre('cook', obj, function(error) { + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + done(); + }); + +``` + +#### It can execute parallel (async) pre hooks + +Like the hooks module, you can declare "async" pre hooks - these take two +parameters, the functions `next()` and `done()`. `next()` passes control to +the next pre hook, but the underlying function won't be called until all +async pre hooks have called `done()`. + + +```javascript + + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + hooks.execPre('cook', obj, function() { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + done(); + }); + +``` + +## post hooks + +#### It runs without any hooks specified + +```javascript + + hooks.execPost('cook', null, [1], function(error, eggs) { + assert.ifError(error); + assert.equal(1, eggs); + done(); + }); + +``` + +#### It executes with parameters passed in + +```javascript + + hooks.post('cook', function(eggs, bacon, callback) { + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + +``` + +#### It can use synchronous post hooks + +```javascript + + var execed = {}; + + hooks.post('cook', function(eggs, bacon) { + execed.first = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + }); + + hooks.post('cook', function(eggs, bacon, callback) { + execed.second = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + +``` + +## wrap() + +#### It wraps pre and post calls into one call + +```javascript + + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.ifError(error); + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj, + args); + +``` + +## createWrapper() + +#### It wraps wrap() into a callable function + +```javascript + + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var cook = hooks.createWrapper( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj); + + cook(obj, function(error, result) { + assert.ifError(error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + +``` + +## clone() + +#### It clones a Kareem object + +```javascript + + var k1 = new Kareem(); + k1.pre('cook', function() {}); + k1.post('cook', function() {}); + + var k2 = k1.clone(); + assert.deepEqual(['cook'], Object.keys(k2._pres)); + assert.deepEqual(['cook'], Object.keys(k2._posts)); + +``` + diff --git a/app/node_modules/kareem/docs.js b/app/node_modules/kareem/docs.js new file mode 100644 index 0000000..4a8d4c8 --- /dev/null +++ b/app/node_modules/kareem/docs.js @@ -0,0 +1,37 @@ +var acquit = require('acquit'); + +var content = require('fs').readFileSync('./test/examples.test.js').toString(); +var blocks = acquit.parse(content); + +var mdOutput = + '# kareem\n\n' + + ' [![Build Status](https://travis-ci.org/vkarpov15/kareem.svg?branch=master)](https://travis-ci.org/vkarpov15/kareem)\n' + + ' [![Coverage Status](https://img.shields.io/coveralls/vkarpov15/kareem.svg)](https://coveralls.io/r/vkarpov15/kareem)\n\n' + + 'Re-imagined take on the [hooks](http://npmjs.org/package/hooks) module, ' + + 'meant to offer additional flexibility in allowing you to execute hooks ' + + 'whenever necessary, as opposed to simply wrapping a single function.\n\n' + + 'Named for the NBA\'s all-time leading scorer Kareem Abdul-Jabbar, known ' + + 'for his mastery of the [hook shot](http://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar#Skyhook)\n\n' + + '\n\n' + + '# API\n\n'; + +for (var i = 0; i < blocks.length; ++i) { + var describe = blocks[i]; + mdOutput += '## ' + describe.contents + '\n\n'; + mdOutput += describe.comments[0] ? + acquit.trimEachLine(describe.comments[0]) + '\n\n' : + ''; + + for (var j = 0; j < describe.blocks.length; ++j) { + var it = describe.blocks[j]; + mdOutput += '#### It ' + it.contents + '\n\n'; + mdOutput += it.comments[0] ? + acquit.trimEachLine(it.comments[0]) + '\n\n' : + ''; + mdOutput += '```javascript\n'; + mdOutput += ' ' + it.code + '\n'; + mdOutput += '```\n\n'; + } +} + +require('fs').writeFileSync('README.md', mdOutput); diff --git a/app/node_modules/kareem/gulpfile.js b/app/node_modules/kareem/gulpfile.js new file mode 100644 index 0000000..635bfc7 --- /dev/null +++ b/app/node_modules/kareem/gulpfile.js @@ -0,0 +1,18 @@ +var gulp = require('gulp'); +var mocha = require('gulp-mocha'); +var config = require('./package.json'); +var jscs = require('gulp-jscs'); + +gulp.task('mocha', function() { + return gulp.src('./test/*'). + pipe(mocha({ reporter: 'dot' })); +}); + +gulp.task('jscs', function() { + return gulp.src('./index.js'). + pipe(jscs(config.jscsConfig)); +}); + +gulp.task('watch', function() { + gulp.watch('./index.js', ['jscs', 'mocha']); +}); diff --git a/app/node_modules/kareem/index.js b/app/node_modules/kareem/index.js new file mode 100644 index 0000000..137a1f4 --- /dev/null +++ b/app/node_modules/kareem/index.js @@ -0,0 +1,352 @@ +'use strict'; + +function Kareem() { + this._pres = {}; + this._posts = {}; +} + +Kareem.prototype.execPre = function(name, context, args, callback) { + if (arguments.length === 3) { + callback = args; + args = []; + } + var pres = this._pres[name] || []; + var numPres = pres.length; + var numAsyncPres = pres.numAsync || 0; + var currentPre = 0; + var asyncPresLeft = numAsyncPres; + var done = false; + var $args = args; + + if (!numPres) { + return process.nextTick(function() { + callback(null); + }); + } + + var next = function() { + if (currentPre >= numPres) { + return; + } + var pre = pres[currentPre]; + + if (pre.isAsync) { + pre.fn.call( + context, + function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + + ++currentPre; + next.apply(context, arguments); + }, + function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + + if (--numAsyncPres === 0) { + return callback(null); + } + }); + } else if (pre.fn.length > 0) { + var args = [function(error) { + if (error) { + if (done) { + return; + } + done = true; + return callback(error); + } + + if (++currentPre >= numPres) { + if (asyncPresLeft > 0) { + // Leave parallel hooks to run + return; + } else { + return callback(null); + } + } + + next.apply(context, arguments); + }]; + var _args = arguments.length >= 2 ? arguments : [null].concat($args); + for (var i = 1; i < _args.length; ++i) { + args.push(_args[i]); + } + pre.fn.apply(context, args); + } else { + pre.fn.call(context); + if (++currentPre >= numPres) { + if (asyncPresLeft > 0) { + // Leave parallel hooks to run + return; + } else { + return process.nextTick(function() { + callback(null); + }); + } + } + next(); + } + }; + + next.apply(null, [null].concat(args)); +}; + +Kareem.prototype.execPreSync = function(name, context) { + var pres = this._pres[name] || []; + var numPres = pres.length; + + for (var i = 0; i < numPres; ++i) { + pres[i].fn.call(context); + } +}; + +Kareem.prototype.execPost = function(name, context, args, options, callback) { + if (arguments.length < 5) { + callback = options; + options = null; + } + var posts = this._posts[name] || []; + var numPosts = posts.length; + var currentPost = 0; + + var firstError = null; + if (options && options.error) { + firstError = options.error; + } + + if (!numPosts) { + return process.nextTick(function() { + callback.apply(null, [firstError].concat(args)); + }); + } + + var next = function() { + var post = posts[currentPost]; + var numArgs = 0; + var argLength = args.length; + var newArgs = []; + for (var i = 0; i < argLength; ++i) { + numArgs += args[i] && args[i]._kareemIgnore ? 0 : 1; + if (!args[i] || !args[i]._kareemIgnore) { + newArgs.push(args[i]); + } + } + + if (firstError) { + if (post.length === numArgs + 2) { + post.apply(context, [firstError].concat(newArgs).concat(function(error) { + if (error) { + firstError = error; + } + if (++currentPost >= numPosts) { + return callback.call(null, firstError); + } + next(); + })); + } else { + if (++currentPost >= numPosts) { + return callback.call(null, firstError); + } + next(); + } + } else { + if (post.length === numArgs + 2) { + // Skip error handlers if no error + if (++currentPost >= numPosts) { + return callback.apply(null, [null].concat(args)); + } + return next(); + } + if (post.length === numArgs + 1) { + post.apply(context, newArgs.concat(function(error) { + if (error) { + firstError = error; + return next(); + } + + if (++currentPost >= numPosts) { + return callback.apply(null, [null].concat(args)); + } + + next(); + })); + } else { + post.apply(context, newArgs); + + if (++currentPost >= numPosts) { + return callback.apply(null, [null].concat(args)); + } + + next(); + } + } + }; + + next(); +}; + +Kareem.prototype.execPostSync = function(name, context) { + var posts = this._posts[name] || []; + var numPosts = posts.length; + + for (var i = 0; i < numPosts; ++i) { + posts[i].call(context); + } +}; + +function _handleWrapError(instance, error, name, context, args, options, callback) { + if (options.useErrorHandlers) { + var _options = { error: error }; + return instance.execPost(name, context, args, _options, function(error) { + return typeof callback === 'function' && callback(error); + }); + } else { + return typeof callback === 'function' ? + callback(error) : + undefined; + } +} + +Kareem.prototype.wrap = function(name, fn, context, args, options) { + var lastArg = (args.length > 0 ? args[args.length - 1] : null); + var argsWithoutCb = typeof lastArg === 'function' ? + args.slice(0, args.length - 1) : + args; + var _this = this; + + var useLegacyPost; + if (typeof options === 'object') { + useLegacyPost = options && options.useLegacyPost; + } else { + useLegacyPost = options; + } + options = options || {}; + + this.execPre(name, context, args, function(error) { + if (error) { + var numCallbackParams = options.numCallbackParams || 0; + var nulls = []; + for (var i = 0; i < numCallbackParams; ++i) { + nulls.push(null); + } + return _handleWrapError(_this, error, name, context, nulls, + options, lastArg); + } + + var end = (typeof lastArg === 'function' ? args.length - 1 : args.length); + + fn.apply(context, args.slice(0, end).concat(function() { + var args = arguments; + var argsWithoutError = Array.prototype.slice.call(arguments, 1); + if (options.nullResultByDefault && argsWithoutError.length === 0) { + argsWithoutError.push(null); + } + if (arguments[0]) { + // Assume error + return _handleWrapError(_this, arguments[0], name, context, + argsWithoutError, options, lastArg); + } else { + if (useLegacyPost && typeof lastArg === 'function') { + lastArg.apply(context, arguments); + } + + _this.execPost(name, context, argsWithoutError, function() { + if (arguments[0]) { + return typeof lastArg === 'function' ? + lastArg(arguments[0]) : + undefined; + } + + return typeof lastArg === 'function' && !useLegacyPost ? + lastArg.apply(context, arguments) : + undefined; + }); + } + })); + }); +}; + +Kareem.prototype.createWrapper = function(name, fn, context, options) { + var _this = this; + return function() { + var args = Array.prototype.slice.call(arguments); + _this.wrap(name, fn, context, args, options); + }; +}; + +Kareem.prototype.pre = function(name, isAsync, fn, error) { + if (typeof arguments[1] !== 'boolean') { + error = fn; + fn = isAsync; + isAsync = false; + } + + this._pres[name] = this._pres[name] || []; + var pres = this._pres[name]; + + if (isAsync) { + pres.numAsync = pres.numAsync || 0; + ++pres.numAsync; + } + + pres.push({ fn: fn, isAsync: isAsync }); + + return this; +}; + +Kareem.prototype.post = function(name, fn) { + (this._posts[name] = this._posts[name] || []).push(fn); + return this; +}; + +Kareem.prototype.clone = function() { + var n = new Kareem(); + for (var key in this._pres) { + if (!this._pres.hasOwnProperty(key)) { + continue; + } + n._pres[key] = this._pres[key].slice(); + n._pres[key].numAsync = this._pres[key].numAsync; + } + for (var key in this._posts) { + if (!this._posts.hasOwnProperty(key)) { + continue; + } + n._posts[key] = this._posts[key].slice(); + } + + return n; +}; + +Kareem.prototype.merge = function(other) { + var ret = this.clone(); + for (var key in other._pres) { + if (!other._pres.hasOwnProperty(key)) { + continue; + } + ret._pres[key] = (ret._pres[key] || []).concat(other._pres[key].slice()); + ret._pres[key].numAsync += other._pres[key].numAsync; + } + for (var key in other._posts) { + if (!other._posts.hasOwnProperty(key)) { + continue; + } + ret._posts[key] = (ret._posts[key] || []).concat(other._posts[key].slice()); + } + + return ret; +}; + +module.exports = Kareem; diff --git a/app/node_modules/kareem/package.json b/app/node_modules/kareem/package.json new file mode 100644 index 0000000..378a394 --- /dev/null +++ b/app/node_modules/kareem/package.json @@ -0,0 +1,30 @@ +{ + "name": "kareem", + "version": "1.5.0", + "description": "Next-generation take on pre/post function hooks", + "main": "index.js", + "scripts": { + "test": "./node_modules/mocha/bin/mocha ./test/*", + "test-travis": "./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- -R spec ./test/*" + }, + "repository": { + "type": "git", + "url": "git://github.com/vkarpov15/kareem.git" + }, + "devDependencies": { + "acquit": "0.4.1", + "gulp": "3.8.10", + "gulp-mocha": "2.0.0", + "gulp-jscs": "1.4.0", + "istanbul": "0.4.5", + "jscs": "1.9.0", + "mocha": "3.2.0" + }, + "jscsConfig": { + "preset": "airbnb", + "requireMultipleVarDecl": null, + "disallowMultipleVarDecl": true + }, + "author": "Valeri Karpov ", + "license": "Apache 2.0" +} diff --git a/app/node_modules/kareem/test/examples.test.js b/app/node_modules/kareem/test/examples.test.js new file mode 100644 index 0000000..cf840ba --- /dev/null +++ b/app/node_modules/kareem/test/examples.test.js @@ -0,0 +1,357 @@ +var assert = require('assert'); +var Kareem = require('../'); + +/* Much like [hooks](https://npmjs.org/package/hooks), kareem lets you define + * pre and post hooks: pre hooks are called before a given function executes. + * Unlike hooks, kareem stores hooks and other internal state in a separate + * object, rather than relying on inheritance. Furthermore, kareem exposes + * an `execPre()` function that allows you to execute your pre hooks when + * appropriate, giving you more fine-grained control over your function hooks. + */ +describe('pre hooks', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('runs without any hooks specified', function(done) { + hooks.execPre('cook', null, function() { + done(); + }); + }); + + /* pre hook functions take one parameter, a "done" function that you execute + * when your pre hook is finished. + */ + it('runs basic serial pre hooks', function(done) { + var count = 0; + + hooks.pre('cook', function(done) { + ++count; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count); + done(); + }); + }); + + it('can run multipe pre hooks', function(done) { + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function(done) { + ++count1; + done(); + }); + + hooks.pre('cook', function(done) { + ++count2; + done(); + }); + + hooks.execPre('cook', null, function() { + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + }); + + /* If your pre hook function takes no parameters, its assumed to be + * fully synchronous. + */ + it('can run fully synchronous pre hooks', function(done) { + var count1 = 0; + var count2 = 0; + + hooks.pre('cook', function() { + ++count1; + }); + + hooks.pre('cook', function() { + ++count2; + }); + + hooks.execPre('cook', null, function(error) { + assert.equal(null, error); + assert.equal(1, count1); + assert.equal(1, count2); + done(); + }); + }); + + /* Pre save hook functions are bound to the second parameter to `execPre()` + */ + it('properly attaches context to pre hooks', function(done) { + hooks.pre('cook', function(done) { + this.bacon = 3; + done(); + }); + + hooks.pre('cook', function(done) { + this.eggs = 4; + done(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + // In the pre hooks, `this` will refer to `obj` + hooks.execPre('cook', obj, function(error) { + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + done(); + }); + }); + + /* Like the hooks module, you can declare "async" pre hooks - these take two + * parameters, the functions `next()` and `done()`. `next()` passes control to + * the next pre hook, but the underlying function won't be called until all + * async pre hooks have called `done()`. + */ + it('can execute parallel (async) pre hooks', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + hooks.execPre('cook', obj, function() { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + done(); + }); + }); +}); + +describe('post hooks', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('runs without any hooks specified', function(done) { + hooks.execPost('cook', null, [1], function(error, eggs) { + assert.ifError(error); + assert.equal(1, eggs); + done(); + }); + }); + + it('executes with parameters passed in', function(done) { + hooks.post('cook', function(eggs, bacon, callback) { + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + }); + + it('can use synchronous post hooks', function(done) { + var execed = {}; + + hooks.post('cook', function(eggs, bacon) { + execed.first = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + }); + + hooks.post('cook', function(eggs, bacon, callback) { + execed.second = true; + assert.equal(1, eggs); + assert.equal(2, bacon); + callback(); + }); + + hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { + assert.ifError(error); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.equal(1, eggs); + assert.equal(2, bacon); + done(); + }); + }); +}); + +describe('wrap()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('wraps pre and post calls into one call', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.ifError(error); + assert.equal(null, error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj, + args); + }); +}); + +describe('createWrapper()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('wraps wrap() into a callable function', function(done) { + hooks.pre('cook', true, function(next, done) { + this.bacon = 3; + next(); + setTimeout(function() { + done(); + }, 5); + }); + + hooks.pre('cook', true, function(next, done) { + next(); + var _this = this; + setTimeout(function() { + _this.eggs = 4; + done(); + }, 10); + }); + + hooks.pre('cook', function(next) { + this.waffles = false; + next(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var cook = hooks.createWrapper( + 'cook', + function(o, callback) { + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + callback(null, o); + }, + obj); + + cook(obj, function(error, result) { + assert.ifError(error); + assert.equal(3, obj.bacon); + assert.equal(4, obj.eggs); + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + + assert.equal(obj, result); + done(); + }); + }); +}); + +describe('clone()', function() { + it('clones a Kareem object', function() { + var k1 = new Kareem(); + k1.pre('cook', function() {}); + k1.post('cook', function() {}); + + var k2 = k1.clone(); + assert.deepEqual(['cook'], Object.keys(k2._pres)); + assert.deepEqual(['cook'], Object.keys(k2._posts)); + }); +}); + +describe('merge()', function() { + it('pulls hooks from another Kareem object', function() { + var k1 = new Kareem(); + var test1 = function() {}; + k1.pre('cook', test1); + k1.post('cook', function() {}); + + var k2 = new Kareem(); + var test2 = function() {}; + k2.pre('cook', test2); + var k3 = k2.merge(k1); + assert.equal(k3._pres['cook'].length, 2); + assert.equal(k3._pres['cook'][0].fn, test2); + assert.equal(k3._pres['cook'][1].fn, test1); + assert.equal(k3._posts['cook'].length, 1); + }); +}); diff --git a/app/node_modules/kareem/test/post.test.js b/app/node_modules/kareem/test/post.test.js new file mode 100644 index 0000000..9fcbb0e --- /dev/null +++ b/app/node_modules/kareem/test/post.test.js @@ -0,0 +1,155 @@ +var assert = require('assert'); +var Kareem = require('../'); + +describe('execPost', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles errors', function(done) { + hooks.post('cook', function(eggs, callback) { + callback('error!'); + }); + + hooks.execPost('cook', null, [4], function(error, eggs) { + assert.equal('error!', error); + assert.ok(!eggs); + done(); + }); + }); + + it('multiple posts', function(done) { + hooks.post('cook', function(eggs, callback) { + setTimeout( + function() { + callback(); + }, + 5); + }); + + hooks.post('cook', function(eggs, callback) { + setTimeout( + function() { + callback(); + }, + 5); + }); + + hooks.execPost('cook', null, [4], function(error, eggs) { + assert.ifError(error); + assert.equal(4, eggs); + done(); + }); + }); + + it('error posts', function(done) { + var called = {}; + hooks.post('cook', function(eggs, callback) { + called.first = true; + callback(); + }); + + hooks.post('cook', function(eggs, callback) { + called.second = true; + callback(new Error('fail')); + }); + + hooks.post('cook', function(eggs, callback) { + assert.ok(false); + }); + + hooks.post('cook', function(error, eggs, callback) { + called.fourth = true; + assert.equal(error.message, 'fail'); + callback(new Error('fourth')); + }); + + hooks.post('cook', function(error, eggs, callback) { + called.fifth = true; + assert.equal(error.message, 'fourth'); + callback(new Error('fifth')); + }); + + hooks.execPost('cook', null, [4], function(error, eggs) { + assert.ok(error); + assert.equal(error.message, 'fifth'); + assert.deepEqual(called, { + first: true, + second: true, + fourth: true, + fifth: true + }); + done(); + }); + }); + + it('error posts with initial error', function(done) { + var called = {}; + + hooks.post('cook', function(eggs, callback) { + assert.ok(false); + }); + + hooks.post('cook', function(error, eggs, callback) { + called.second = true; + assert.equal(error.message, 'fail'); + callback(new Error('second')); + }); + + hooks.post('cook', function(error, eggs, callback) { + called.third = true; + assert.equal(error.message, 'second'); + callback(new Error('third')); + }); + + hooks.post('cook', function(error, eggs, callback) { + called.fourth = true; + assert.equal(error.message, 'third'); + callback(); + }); + + var options = { error: new Error('fail') }; + hooks.execPost('cook', null, [4], options, function(error, eggs) { + assert.ok(error); + assert.equal(error.message, 'third'); + assert.deepEqual(called, { + second: true, + third: true, + fourth: true + }); + done(); + }); + }); +}); + +describe('execPostSync', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('executes hooks synchronously', function() { + var execed = {}; + + hooks.post('cook', function() { + execed.first = true; + }); + + hooks.post('cook', function() { + execed.second = true; + }); + + hooks.execPostSync('cook', null); + assert.ok(execed.first); + assert.ok(execed.second); + }); + + it('works with no hooks specified', function() { + assert.doesNotThrow(function() { + hooks.execPostSync('cook', null); + }); + }); +}); diff --git a/app/node_modules/kareem/test/pre.test.js b/app/node_modules/kareem/test/pre.test.js new file mode 100644 index 0000000..22a9125 --- /dev/null +++ b/app/node_modules/kareem/test/pre.test.js @@ -0,0 +1,277 @@ +var assert = require('assert'); +var Kareem = require('../'); + +describe('execPre', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles errors with multiple pres', function(done) { + var execed = {}; + + hooks.pre('cook', function(done) { + execed.first = true; + done(); + }); + + hooks.pre('cook', function(done) { + execed.second = true; + done('error!'); + }); + + hooks.pre('cook', function(done) { + execed.third = true; + done(); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + done('other error!'); + }, + 10); + + next(); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors in next()', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 15); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + next('error!'); + done('another error!'); + }, + 5); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('handles async errors in next() when already done', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', true, function(next, done) { + execed.second = true; + setTimeout( + function() { + next('error!'); + done('another error!'); + }, + 25); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('other error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('async pres with clone()', function(done) { + var execed = false; + + hooks.pre('cook', true, function(next, done) { + execed = true; + setTimeout( + function() { + done(); + }, + 5); + + next(); + }); + + hooks.clone().execPre('cook', null, function(err) { + assert.ifError(err); + assert.ok(execed); + done(); + }); + }); + + it('returns correct error when async pre errors', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done('other error!'); + }, + 5); + + next(); + }); + + hooks.pre('cook', function(next) { + execed.second = true; + setTimeout( + function() { + next('error!'); + }, + 15); + }); + + hooks.execPre('cook', null, function(err) { + assert.equal('other error!', err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('lets async pres run when fully sync pres are done', function(done) { + var execed = {}; + + hooks.pre('cook', true, function(next, done) { + execed.first = true; + setTimeout( + function() { + done(); + }, + 5); + + next(); + }); + + hooks.pre('cook', function() { + execed.second = true; + }); + + hooks.execPre('cook', null, function(err) { + assert.ifError(err); + assert.equal(2, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + done(); + }); + }); + + it('allows passing arguments to the next pre', function(done) { + var execed = {}; + + hooks.pre('cook', function(next) { + execed.first = true; + next(null, 'test'); + }); + + hooks.pre('cook', function(next, p) { + execed.second = true; + assert.equal(p, 'test'); + next(); + }); + + hooks.pre('cook', function(next, p) { + execed.third = true; + assert.ok(!p); + next(); + }); + + hooks.execPre('cook', null, function(err) { + assert.ifError(err); + assert.equal(3, Object.keys(execed).length); + assert.ok(execed.first); + assert.ok(execed.second); + assert.ok(execed.third); + done(); + }); + }); +}); + +describe('execPreSync', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('executes hooks synchronously', function() { + var execed = {}; + + hooks.pre('cook', function() { + execed.first = true; + }); + + hooks.pre('cook', function() { + execed.second = true; + }); + + hooks.execPreSync('cook', null); + assert.ok(execed.first); + assert.ok(execed.second); + }); + + it('works with no hooks specified', function() { + assert.doesNotThrow(function() { + hooks.execPreSync('cook', null); + }); + }); +}); diff --git a/app/node_modules/kareem/test/wrap.test.js b/app/node_modules/kareem/test/wrap.test.js new file mode 100644 index 0000000..f1f336e --- /dev/null +++ b/app/node_modules/kareem/test/wrap.test.js @@ -0,0 +1,347 @@ +var assert = require('assert'); +var Kareem = require('../'); + +describe('wrap()', function() { + var hooks; + + beforeEach(function() { + hooks = new Kareem(); + }); + + it('handles pre errors', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal(undefined, obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + // Should never get called + assert.ok(false); + callback(null, o); + }, + obj, + args); + }); + + it('handles pre errors when no callback defined', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + + hooks.wrap( + 'cook', + function(o, callback) { + // Should never get called + assert.ok(false); + callback(null, o); + }, + obj, + args); + + setTimeout( + function() { + done(); + }, + 25); + }); + + it('handles errors in wrapped function', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(obj) { + obj.tofu = 'no'; + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal(undefined, obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + callback('error!'); + }, + obj, + args); + }); + + it('handles errors in post', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(obj, callback) { + obj.tofu = 'no'; + callback('error!'); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = [obj]; + args.push(function(error, result) { + assert.equal('error!', error); + assert.ok(!result); + assert.equal('no', obj.tofu); + done(); + }); + + hooks.wrap( + 'cook', + function(o, callback) { + callback(null, o); + }, + obj, + args); + }); + + it('defers errors to post hooks if enabled', function(done) { + hooks.pre('cook', function(done) { + done(new Error('fail')); + }); + + hooks.post('cook', function(error, res, callback) { + callback(new Error('another error occurred')); + }); + + var args = []; + args.push(function(error) { + assert.equal(error.message, 'another error occurred'); + done(); + }); + + hooks.wrap( + 'cook', + function(callback) { + assert.ok(false); + callback(); + }, + null, + args, + { useErrorHandlers: true, numCallbackParams: 1 }); + }); + + it('error handlers with no callback', function(done) { + hooks.pre('cook', function(done) { + done(new Error('fail')); + }); + + hooks.post('cook', function(error, callback) { + assert.equal(error.message, 'fail'); + done(); + }); + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + assert.ok(false); + callback(); + }, + null, + args, + { useErrorHandlers: true }); + }); + + it('error handlers with no error', function(done) { + hooks.post('cook', function(error, callback) { + callback(new Error('another error occurred')); + }); + + var args = []; + args.push(function(error) { + assert.ifError(error); + done(); + }); + + hooks.wrap( + 'cook', + function(callback) { + callback(); + }, + null, + args, + { useErrorHandlers: true }); + }); + + it('works with no args', function(done) { + hooks.pre('cook', function(done) { + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(null); + }, + obj, + args); + + setTimeout( + function() { + assert.equal('no', obj.tofu); + done(); + }, + 25); + }); + + it('handles pre errors with no args', function(done) { + hooks.pre('cook', function(done) { + done('error!'); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(null); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(undefined, obj.tofu); + done(); + }, + 25); + }); + + it('handles wrapped function errors with no args', function(done) { + hooks.pre('cook', function(done) { + obj.waffles = false; + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback(); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback('error!'); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(false, obj.waffles); + assert.equal(undefined, obj.tofu); + done(); + }, + 25); + }); + + it('handles post errors with no args', function(done) { + hooks.pre('cook', function(done) { + obj.waffles = false; + done(); + }); + + hooks.post('cook', function(callback) { + obj.tofu = 'no'; + callback('error!'); + }); + + var obj = { bacon: 0, eggs: 0 }; + + var args = []; + + hooks.wrap( + 'cook', + function(callback) { + callback(); + }, + obj, + args); + + setTimeout( + function() { + assert.equal(false, obj.waffles); + assert.equal('no', obj.tofu); + done(); + }, + 25); + }); + + it('can use legacy post behavior', function(done) { + var called = 0; + hooks.post('cook', function(callback) { + ++called; + callback(); + }); + + var args = [function(error) { + assert.equal(called, 0); + + setTimeout(function() { + assert.equal(called, 1); + done(); + }, 0); + }]; + + hooks.wrap( + 'cook', + function(callback) { + callback(); + }, + null, + args, + true); + }); +}); diff --git a/app/node_modules/lcid/index.js b/app/node_modules/lcid/index.js new file mode 100644 index 0000000..69bd3d2 --- /dev/null +++ b/app/node_modules/lcid/index.js @@ -0,0 +1,22 @@ +'use strict'; +var invertKv = require('invert-kv'); +var all = require('./lcid.json'); +var inverted = invertKv(all); + +exports.from = function (lcidCode) { + if (typeof lcidCode !== 'number') { + throw new TypeError('Expected a number'); + } + + return inverted[lcidCode]; +}; + +exports.to = function (localeId) { + if (typeof localeId !== 'string') { + throw new TypeError('Expected a string'); + } + + return all[localeId]; +}; + +exports.all = all; diff --git a/app/node_modules/lcid/lcid.json b/app/node_modules/lcid/lcid.json new file mode 100644 index 0000000..9c89f6a --- /dev/null +++ b/app/node_modules/lcid/lcid.json @@ -0,0 +1,203 @@ +{ + "af_ZA": 1078, + "am_ET": 1118, + "ar_AE": 14337, + "ar_BH": 15361, + "ar_DZ": 5121, + "ar_EG": 3073, + "ar_IQ": 2049, + "ar_JO": 11265, + "ar_KW": 13313, + "ar_LB": 12289, + "ar_LY": 4097, + "ar_MA": 6145, + "ar_OM": 8193, + "ar_QA": 16385, + "ar_SA": 1025, + "ar_SY": 10241, + "ar_TN": 7169, + "ar_YE": 9217, + "arn_CL": 1146, + "as_IN": 1101, + "az_AZ": 2092, + "ba_RU": 1133, + "be_BY": 1059, + "bg_BG": 1026, + "bn_IN": 1093, + "bo_BT": 2129, + "bo_CN": 1105, + "br_FR": 1150, + "bs_BA": 8218, + "ca_ES": 1027, + "co_FR": 1155, + "cs_CZ": 1029, + "cy_GB": 1106, + "da_DK": 1030, + "de_AT": 3079, + "de_CH": 2055, + "de_DE": 1031, + "de_LI": 5127, + "de_LU": 4103, + "div_MV": 1125, + "dsb_DE": 2094, + "el_GR": 1032, + "en_AU": 3081, + "en_BZ": 10249, + "en_CA": 4105, + "en_CB": 9225, + "en_GB": 2057, + "en_IE": 6153, + "en_IN": 18441, + "en_JA": 8201, + "en_MY": 17417, + "en_NZ": 5129, + "en_PH": 13321, + "en_TT": 11273, + "en_US": 1033, + "en_ZA": 7177, + "en_ZW": 12297, + "es_AR": 11274, + "es_BO": 16394, + "es_CL": 13322, + "es_CO": 9226, + "es_CR": 5130, + "es_DO": 7178, + "es_EC": 12298, + "es_ES": 3082, + "es_GT": 4106, + "es_HN": 18442, + "es_MX": 2058, + "es_NI": 19466, + "es_PA": 6154, + "es_PE": 10250, + "es_PR": 20490, + "es_PY": 15370, + "es_SV": 17418, + "es_UR": 14346, + "es_US": 21514, + "es_VE": 8202, + "et_EE": 1061, + "eu_ES": 1069, + "fa_IR": 1065, + "fi_FI": 1035, + "fil_PH": 1124, + "fo_FO": 1080, + "fr_BE": 2060, + "fr_CA": 3084, + "fr_CH": 4108, + "fr_FR": 1036, + "fr_LU": 5132, + "fr_MC": 6156, + "fy_NL": 1122, + "ga_IE": 2108, + "gbz_AF": 1164, + "gl_ES": 1110, + "gsw_FR": 1156, + "gu_IN": 1095, + "ha_NG": 1128, + "he_IL": 1037, + "hi_IN": 1081, + "hr_BA": 4122, + "hr_HR": 1050, + "hu_HU": 1038, + "hy_AM": 1067, + "id_ID": 1057, + "ii_CN": 1144, + "is_IS": 1039, + "it_CH": 2064, + "it_IT": 1040, + "iu_CA": 2141, + "ja_JP": 1041, + "ka_GE": 1079, + "kh_KH": 1107, + "kk_KZ": 1087, + "kl_GL": 1135, + "kn_IN": 1099, + "ko_KR": 1042, + "kok_IN": 1111, + "ky_KG": 1088, + "lb_LU": 1134, + "lo_LA": 1108, + "lt_LT": 1063, + "lv_LV": 1062, + "mi_NZ": 1153, + "mk_MK": 1071, + "ml_IN": 1100, + "mn_CN": 2128, + "mn_MN": 1104, + "moh_CA": 1148, + "mr_IN": 1102, + "ms_BN": 2110, + "ms_MY": 1086, + "mt_MT": 1082, + "my_MM": 1109, + "nb_NO": 1044, + "ne_NP": 1121, + "nl_BE": 2067, + "nl_NL": 1043, + "nn_NO": 2068, + "ns_ZA": 1132, + "oc_FR": 1154, + "or_IN": 1096, + "pa_IN": 1094, + "pl_PL": 1045, + "ps_AF": 1123, + "pt_BR": 1046, + "pt_PT": 2070, + "qut_GT": 1158, + "quz_BO": 1131, + "quz_EC": 2155, + "quz_PE": 3179, + "rm_CH": 1047, + "ro_RO": 1048, + "ru_RU": 1049, + "rw_RW": 1159, + "sa_IN": 1103, + "sah_RU": 1157, + "se_FI": 3131, + "se_NO": 1083, + "se_SE": 2107, + "si_LK": 1115, + "sk_SK": 1051, + "sl_SI": 1060, + "sma_NO": 6203, + "sma_SE": 7227, + "smj_NO": 4155, + "smj_SE": 5179, + "smn_FI": 9275, + "sms_FI": 8251, + "sq_AL": 1052, + "sr_BA": 7194, + "sr_SP": 3098, + "sv_FI": 2077, + "sv_SE": 1053, + "sw_KE": 1089, + "syr_SY": 1114, + "ta_IN": 1097, + "te_IN": 1098, + "tg_TJ": 1064, + "th_TH": 1054, + "tk_TM": 1090, + "tmz_DZ": 2143, + "tn_ZA": 1074, + "tr_TR": 1055, + "tt_RU": 1092, + "ug_CN": 1152, + "uk_UA": 1058, + "ur_IN": 2080, + "ur_PK": 1056, + "uz_UZ": 2115, + "vi_VN": 1066, + "wen_DE": 1070, + "wo_SN": 1160, + "xh_ZA": 1076, + "yo_NG": 1130, + "zh_CHS": 4, + "zh_CHT": 31748, + "zh_CN": 2052, + "zh_HK": 3076, + "zh_MO": 5124, + "zh_SG": 4100, + "zh_TW": 1028, + "zu_ZA": 1077 +} diff --git a/app/node_modules/lcid/license b/app/node_modules/lcid/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/app/node_modules/lcid/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/app/node_modules/lcid/package.json b/app/node_modules/lcid/package.json new file mode 100644 index 0000000..0340963 --- /dev/null +++ b/app/node_modules/lcid/package.json @@ -0,0 +1,46 @@ +{ + "name": "lcid", + "version": "1.0.0", + "description": "Mapping between standard locale identifiers and Windows locale identifiers (LCID)", + "license": "MIT", + "repository": "sindresorhus/lcid", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "node test.js" + }, + "files": [ + "index.js", + "lcid.json" + ], + "keywords": [ + "lcid", + "locale", + "string", + "str", + "id", + "identifier", + "windows", + "language", + "lang", + "map", + "mapping", + "convert", + "json", + "bcp47", + "ietf", + "tag" + ], + "dependencies": { + "invert-kv": "^1.0.0" + }, + "devDependencies": { + "ava": "0.0.4" + } +} diff --git a/app/node_modules/lcid/readme.md b/app/node_modules/lcid/readme.md new file mode 100644 index 0000000..bee4a70 --- /dev/null +++ b/app/node_modules/lcid/readme.md @@ -0,0 +1,35 @@ +# lcid [![Build Status](https://travis-ci.org/sindresorhus/lcid.svg?branch=master)](https://travis-ci.org/sindresorhus/lcid) + +> Mapping between [standard locale identifiers](http://en.wikipedia.org/wiki/Locale) and [Windows locale identifiers (LCID)](http://en.wikipedia.org/wiki/Locale#Specifics_for_Microsoft_platforms) + +Based on the [mapping](https://github.com/python/cpython/blob/be2a1a76fa43bb1ea1b3577bb5bdd506a2e90e37/Lib/locale.py#L1395-L1604) used in the Python standard library. + +The mapping itself is just a [JSON file](lcid.json) and can be used wherever. + + +## Install + +``` +$ npm install --save lcid +``` + + +## Usage + +```js +var lcid = require('lcid'); + +lcid.from(1044); +//=> 'nb_NO' + +lcid.to('nb_NO'); +//=> 1044 + +lcid.all; +//=> {'af_ZA': 1078, ...} +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/app/node_modules/lodash.get/LICENSE b/app/node_modules/lodash.get/LICENSE new file mode 100644 index 0000000..e0c69d5 --- /dev/null +++ b/app/node_modules/lodash.get/LICENSE @@ -0,0 +1,47 @@ +Copyright jQuery Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +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. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/app/node_modules/lodash.get/README.md b/app/node_modules/lodash.get/README.md new file mode 100644 index 0000000..9079614 --- /dev/null +++ b/app/node_modules/lodash.get/README.md @@ -0,0 +1,18 @@ +# lodash.get v4.4.2 + +The [lodash](https://lodash.com/) method `_.get` exported as a [Node.js](https://nodejs.org/) module. + +## Installation + +Using npm: +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash.get +``` + +In Node.js: +```js +var get = require('lodash.get'); +``` + +See the [documentation](https://lodash.com/docs#get) or [package source](https://github.com/lodash/lodash/blob/4.4.2-npm-packages/lodash.get) for more details. diff --git a/app/node_modules/lodash.get/index.js b/app/node_modules/lodash.get/index.js new file mode 100644 index 0000000..0eaadec --- /dev/null +++ b/app/node_modules/lodash.get/index.js @@ -0,0 +1,931 @@ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** `Object#toString` result references. */ +var funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + symbolTag = '[object Symbol]'; + +/** Used to match property names within property paths. */ +var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + reLeadingDot = /^\./, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to match backslashes in property paths. */ +var reEscapeChar = /\\(\\)?/g; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} + +/** Used for built-in method references. */ +var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** Built-in value references. */ +var Symbol = root.Symbol, + splice = arrayProto.splice; + +/* Built-in method references that are verified to be native. */ +var Map = getNative(root, 'Map'), + nativeCreate = getNative(Object, 'create'); + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; +} + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + return this.has(key) && delete this.__data__[key]; +} + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); +} + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} + +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; +} + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + return true; +} + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries ? entries.length : 0; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; +} + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + return getMapData(this, key)['delete'](key); +} + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + getMapData(this, key).set(key, value); + return this; +} + +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} + +/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ +function baseGet(object, path) { + path = isKey(path, object) ? [path] : castPath(path); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; +} + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +/** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast property path array. + */ +function castPath(value) { + return isArray(value) ? value : stringToPath(value); +} + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} + +/** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ +function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +} + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +/** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ +var stringToPath = memoize(function(string) { + string = toString(string); + + var result = []; + if (reLeadingDot.test(string)) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; +}); + +/** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ +function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to process. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +/** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ +function memoize(func, resolver) { + if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result); + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; +} + +// Assign cache to `_.memoize`. +memoize.Cache = MapCache; + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {string} Returns the string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ +function toString(value) { + return value == null ? '' : baseToString(value); +} + +/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ +function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; +} + +module.exports = get; diff --git a/app/node_modules/lodash.get/package.json b/app/node_modules/lodash.get/package.json new file mode 100644 index 0000000..3dd8e77 --- /dev/null +++ b/app/node_modules/lodash.get/package.json @@ -0,0 +1,17 @@ +{ + "name": "lodash.get", + "version": "4.4.2", + "description": "The lodash method `_.get` exported as a module.", + "homepage": "https://lodash.com/", + "icon": "https://lodash.com/icon.svg", + "license": "MIT", + "keywords": "lodash-modularized, get", + "author": "John-David Dalton (http://allyoucanleet.com/)", + "contributors": [ + "John-David Dalton (http://allyoucanleet.com/)", + "Blaine Bublitz (https://github.com/phated)", + "Mathias Bynens (https://mathiasbynens.be/)" + ], + "repository": "lodash/lodash", + "scripts": { "test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\"" } +} diff --git a/app/node_modules/lodash/LICENSE b/app/node_modules/lodash/LICENSE new file mode 100644 index 0000000..77c42f1 --- /dev/null +++ b/app/node_modules/lodash/LICENSE @@ -0,0 +1,47 @@ +Copyright OpenJS Foundation and other contributors + +Based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at https://github.com/lodash/lodash + +The following license applies to all parts of this software except as +documented below: + +==== + +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. + +==== + +Copyright and related rights for sample code are waived via CC0. Sample +code is defined as all source code displayed within the prose of the +documentation. + +CC0: http://creativecommons.org/publicdomain/zero/1.0/ + +==== + +Files located in the node_modules and vendor directories are externally +maintained libraries used by this software which have their own +licenses; we recommend you read them, as their terms may differ from the +terms above. diff --git a/app/node_modules/lodash/README.md b/app/node_modules/lodash/README.md new file mode 100644 index 0000000..292832f --- /dev/null +++ b/app/node_modules/lodash/README.md @@ -0,0 +1,39 @@ +# lodash v4.17.15 + +The [Lodash](https://lodash.com/) library exported as [Node.js](https://nodejs.org/) modules. + +## Installation + +Using npm: +```shell +$ npm i -g npm +$ npm i --save lodash +``` + +In Node.js: +```js +// Load the full build. +var _ = require('lodash'); +// Load the core build. +var _ = require('lodash/core'); +// Load the FP build for immutable auto-curried iteratee-first data-last methods. +var fp = require('lodash/fp'); + +// Load method categories. +var array = require('lodash/array'); +var object = require('lodash/fp/object'); + +// Cherry-pick methods for smaller browserify/rollup/webpack bundles. +var at = require('lodash/at'); +var curryN = require('lodash/fp/curryN'); +``` + +See the [package source](https://github.com/lodash/lodash/tree/4.17.15-npm) for more details. + +**Note:**
+Install [n_](https://www.npmjs.com/package/n_) for Lodash use in the Node.js < 6 REPL. + +## Support + +Tested in Chrome 74-75, Firefox 66-67, IE 11, Edge 18, Safari 11-12, & Node.js 8-12.
+Automated [browser](https://saucelabs.com/u/lodash) & [CI](https://travis-ci.org/lodash/lodash/) test runs are available. diff --git a/app/node_modules/lodash/_DataView.js b/app/node_modules/lodash/_DataView.js new file mode 100644 index 0000000..ac2d57c --- /dev/null +++ b/app/node_modules/lodash/_DataView.js @@ -0,0 +1,7 @@ +var getNative = require('./_getNative'), + root = require('./_root'); + +/* Built-in method references that are verified to be native. */ +var DataView = getNative(root, 'DataView'); + +module.exports = DataView; diff --git a/app/node_modules/lodash/_Hash.js b/app/node_modules/lodash/_Hash.js new file mode 100644 index 0000000..b504fe3 --- /dev/null +++ b/app/node_modules/lodash/_Hash.js @@ -0,0 +1,32 @@ +var hashClear = require('./_hashClear'), + hashDelete = require('./_hashDelete'), + hashGet = require('./_hashGet'), + hashHas = require('./_hashHas'), + hashSet = require('./_hashSet'); + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +module.exports = Hash; diff --git a/app/node_modules/lodash/_LazyWrapper.js b/app/node_modules/lodash/_LazyWrapper.js new file mode 100644 index 0000000..81786c7 --- /dev/null +++ b/app/node_modules/lodash/_LazyWrapper.js @@ -0,0 +1,28 @@ +var baseCreate = require('./_baseCreate'), + baseLodash = require('./_baseLodash'); + +/** Used as references for the maximum length and index of an array. */ +var MAX_ARRAY_LENGTH = 4294967295; + +/** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */ +function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; +} + +// Ensure `LazyWrapper` is an instance of `baseLodash`. +LazyWrapper.prototype = baseCreate(baseLodash.prototype); +LazyWrapper.prototype.constructor = LazyWrapper; + +module.exports = LazyWrapper; diff --git a/app/node_modules/lodash/_ListCache.js b/app/node_modules/lodash/_ListCache.js new file mode 100644 index 0000000..26895c3 --- /dev/null +++ b/app/node_modules/lodash/_ListCache.js @@ -0,0 +1,32 @@ +var listCacheClear = require('./_listCacheClear'), + listCacheDelete = require('./_listCacheDelete'), + listCacheGet = require('./_listCacheGet'), + listCacheHas = require('./_listCacheHas'), + listCacheSet = require('./_listCacheSet'); + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; + +module.exports = ListCache; diff --git a/app/node_modules/lodash/_LodashWrapper.js b/app/node_modules/lodash/_LodashWrapper.js new file mode 100644 index 0000000..c1e4d9d --- /dev/null +++ b/app/node_modules/lodash/_LodashWrapper.js @@ -0,0 +1,22 @@ +var baseCreate = require('./_baseCreate'), + baseLodash = require('./_baseLodash'); + +/** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ +function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; +} + +LodashWrapper.prototype = baseCreate(baseLodash.prototype); +LodashWrapper.prototype.constructor = LodashWrapper; + +module.exports = LodashWrapper; diff --git a/app/node_modules/lodash/_Map.js b/app/node_modules/lodash/_Map.js new file mode 100644 index 0000000..b73f29a --- /dev/null +++ b/app/node_modules/lodash/_Map.js @@ -0,0 +1,7 @@ +var getNative = require('./_getNative'), + root = require('./_root'); + +/* Built-in method references that are verified to be native. */ +var Map = getNative(root, 'Map'); + +module.exports = Map; diff --git a/app/node_modules/lodash/_MapCache.js b/app/node_modules/lodash/_MapCache.js new file mode 100644 index 0000000..4a4eea7 --- /dev/null +++ b/app/node_modules/lodash/_MapCache.js @@ -0,0 +1,32 @@ +var mapCacheClear = require('./_mapCacheClear'), + mapCacheDelete = require('./_mapCacheDelete'), + mapCacheGet = require('./_mapCacheGet'), + mapCacheHas = require('./_mapCacheHas'), + mapCacheSet = require('./_mapCacheSet'); + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; + +module.exports = MapCache; diff --git a/app/node_modules/lodash/_Promise.js b/app/node_modules/lodash/_Promise.js new file mode 100644 index 0000000..247b9e1 --- /dev/null +++ b/app/node_modules/lodash/_Promise.js @@ -0,0 +1,7 @@ +var getNative = require('./_getNative'), + root = require('./_root'); + +/* Built-in method references that are verified to be native. */ +var Promise = getNative(root, 'Promise'); + +module.exports = Promise; diff --git a/app/node_modules/lodash/_Set.js b/app/node_modules/lodash/_Set.js new file mode 100644 index 0000000..b3c8dcb --- /dev/null +++ b/app/node_modules/lodash/_Set.js @@ -0,0 +1,7 @@ +var getNative = require('./_getNative'), + root = require('./_root'); + +/* Built-in method references that are verified to be native. */ +var Set = getNative(root, 'Set'); + +module.exports = Set; diff --git a/app/node_modules/lodash/_SetCache.js b/app/node_modules/lodash/_SetCache.js new file mode 100644 index 0000000..6468b06 --- /dev/null +++ b/app/node_modules/lodash/_SetCache.js @@ -0,0 +1,27 @@ +var MapCache = require('./_MapCache'), + setCacheAdd = require('./_setCacheAdd'), + setCacheHas = require('./_setCacheHas'); + +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } +} + +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; + +module.exports = SetCache; diff --git a/app/node_modules/lodash/_Stack.js b/app/node_modules/lodash/_Stack.js new file mode 100644 index 0000000..80b2cf1 --- /dev/null +++ b/app/node_modules/lodash/_Stack.js @@ -0,0 +1,27 @@ +var ListCache = require('./_ListCache'), + stackClear = require('./_stackClear'), + stackDelete = require('./_stackDelete'), + stackGet = require('./_stackGet'), + stackHas = require('./_stackHas'), + stackSet = require('./_stackSet'); + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; +} + +// Add methods to `Stack`. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; + +module.exports = Stack; diff --git a/app/node_modules/lodash/_Symbol.js b/app/node_modules/lodash/_Symbol.js new file mode 100644 index 0000000..a013f7c --- /dev/null +++ b/app/node_modules/lodash/_Symbol.js @@ -0,0 +1,6 @@ +var root = require('./_root'); + +/** Built-in value references. */ +var Symbol = root.Symbol; + +module.exports = Symbol; diff --git a/app/node_modules/lodash/_Uint8Array.js b/app/node_modules/lodash/_Uint8Array.js new file mode 100644 index 0000000..2fb30e1 --- /dev/null +++ b/app/node_modules/lodash/_Uint8Array.js @@ -0,0 +1,6 @@ +var root = require('./_root'); + +/** Built-in value references. */ +var Uint8Array = root.Uint8Array; + +module.exports = Uint8Array; diff --git a/app/node_modules/lodash/_WeakMap.js b/app/node_modules/lodash/_WeakMap.js new file mode 100644 index 0000000..567f86c --- /dev/null +++ b/app/node_modules/lodash/_WeakMap.js @@ -0,0 +1,7 @@ +var getNative = require('./_getNative'), + root = require('./_root'); + +/* Built-in method references that are verified to be native. */ +var WeakMap = getNative(root, 'WeakMap'); + +module.exports = WeakMap; diff --git a/app/node_modules/lodash/_apply.js b/app/node_modules/lodash/_apply.js new file mode 100644 index 0000000..36436dd --- /dev/null +++ b/app/node_modules/lodash/_apply.js @@ -0,0 +1,21 @@ +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +module.exports = apply; diff --git a/app/node_modules/lodash/_arrayAggregator.js b/app/node_modules/lodash/_arrayAggregator.js new file mode 100644 index 0000000..d96c3ca --- /dev/null +++ b/app/node_modules/lodash/_arrayAggregator.js @@ -0,0 +1,22 @@ +/** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ +function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; +} + +module.exports = arrayAggregator; diff --git a/app/node_modules/lodash/_arrayEach.js b/app/node_modules/lodash/_arrayEach.js new file mode 100644 index 0000000..2c5f579 --- /dev/null +++ b/app/node_modules/lodash/_arrayEach.js @@ -0,0 +1,22 @@ +/** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ +function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; +} + +module.exports = arrayEach; diff --git a/app/node_modules/lodash/_arrayEachRight.js b/app/node_modules/lodash/_arrayEachRight.js new file mode 100644 index 0000000..976ca5c --- /dev/null +++ b/app/node_modules/lodash/_arrayEachRight.js @@ -0,0 +1,21 @@ +/** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ +function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; +} + +module.exports = arrayEachRight; diff --git a/app/node_modules/lodash/_arrayEvery.js b/app/node_modules/lodash/_arrayEvery.js new file mode 100644 index 0000000..e26a918 --- /dev/null +++ b/app/node_modules/lodash/_arrayEvery.js @@ -0,0 +1,23 @@ +/** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ +function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; +} + +module.exports = arrayEvery; diff --git a/app/node_modules/lodash/_arrayFilter.js b/app/node_modules/lodash/_arrayFilter.js new file mode 100644 index 0000000..75ea254 --- /dev/null +++ b/app/node_modules/lodash/_arrayFilter.js @@ -0,0 +1,25 @@ +/** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ +function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; +} + +module.exports = arrayFilter; diff --git a/app/node_modules/lodash/_arrayIncludes.js b/app/node_modules/lodash/_arrayIncludes.js new file mode 100644 index 0000000..3737a6d --- /dev/null +++ b/app/node_modules/lodash/_arrayIncludes.js @@ -0,0 +1,17 @@ +var baseIndexOf = require('./_baseIndexOf'); + +/** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; +} + +module.exports = arrayIncludes; diff --git a/app/node_modules/lodash/_arrayIncludesWith.js b/app/node_modules/lodash/_arrayIncludesWith.js new file mode 100644 index 0000000..235fd97 --- /dev/null +++ b/app/node_modules/lodash/_arrayIncludesWith.js @@ -0,0 +1,22 @@ +/** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; +} + +module.exports = arrayIncludesWith; diff --git a/app/node_modules/lodash/_arrayLikeKeys.js b/app/node_modules/lodash/_arrayLikeKeys.js new file mode 100644 index 0000000..b2ec9ce --- /dev/null +++ b/app/node_modules/lodash/_arrayLikeKeys.js @@ -0,0 +1,49 @@ +var baseTimes = require('./_baseTimes'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isBuffer = require('./isBuffer'), + isIndex = require('./_isIndex'), + isTypedArray = require('./isTypedArray'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; +} + +module.exports = arrayLikeKeys; diff --git a/app/node_modules/lodash/_arrayMap.js b/app/node_modules/lodash/_arrayMap.js new file mode 100644 index 0000000..22b2246 --- /dev/null +++ b/app/node_modules/lodash/_arrayMap.js @@ -0,0 +1,21 @@ +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +module.exports = arrayMap; diff --git a/app/node_modules/lodash/_arrayPush.js b/app/node_modules/lodash/_arrayPush.js new file mode 100644 index 0000000..7d742b3 --- /dev/null +++ b/app/node_modules/lodash/_arrayPush.js @@ -0,0 +1,20 @@ +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + +module.exports = arrayPush; diff --git a/app/node_modules/lodash/_arrayReduce.js b/app/node_modules/lodash/_arrayReduce.js new file mode 100644 index 0000000..de8b79b --- /dev/null +++ b/app/node_modules/lodash/_arrayReduce.js @@ -0,0 +1,26 @@ +/** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ +function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; +} + +module.exports = arrayReduce; diff --git a/app/node_modules/lodash/_arrayReduceRight.js b/app/node_modules/lodash/_arrayReduceRight.js new file mode 100644 index 0000000..22d8976 --- /dev/null +++ b/app/node_modules/lodash/_arrayReduceRight.js @@ -0,0 +1,24 @@ +/** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ +function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; +} + +module.exports = arrayReduceRight; diff --git a/app/node_modules/lodash/_arraySample.js b/app/node_modules/lodash/_arraySample.js new file mode 100644 index 0000000..fcab010 --- /dev/null +++ b/app/node_modules/lodash/_arraySample.js @@ -0,0 +1,15 @@ +var baseRandom = require('./_baseRandom'); + +/** + * A specialized version of `_.sample` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ +function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; +} + +module.exports = arraySample; diff --git a/app/node_modules/lodash/_arraySampleSize.js b/app/node_modules/lodash/_arraySampleSize.js new file mode 100644 index 0000000..8c7e364 --- /dev/null +++ b/app/node_modules/lodash/_arraySampleSize.js @@ -0,0 +1,17 @@ +var baseClamp = require('./_baseClamp'), + copyArray = require('./_copyArray'), + shuffleSelf = require('./_shuffleSelf'); + +/** + * A specialized version of `_.sampleSize` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ +function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); +} + +module.exports = arraySampleSize; diff --git a/app/node_modules/lodash/_arrayShuffle.js b/app/node_modules/lodash/_arrayShuffle.js new file mode 100644 index 0000000..46313a3 --- /dev/null +++ b/app/node_modules/lodash/_arrayShuffle.js @@ -0,0 +1,15 @@ +var copyArray = require('./_copyArray'), + shuffleSelf = require('./_shuffleSelf'); + +/** + * A specialized version of `_.shuffle` for arrays. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ +function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); +} + +module.exports = arrayShuffle; diff --git a/app/node_modules/lodash/_arraySome.js b/app/node_modules/lodash/_arraySome.js new file mode 100644 index 0000000..6fd02fd --- /dev/null +++ b/app/node_modules/lodash/_arraySome.js @@ -0,0 +1,23 @@ +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; +} + +module.exports = arraySome; diff --git a/app/node_modules/lodash/_asciiSize.js b/app/node_modules/lodash/_asciiSize.js new file mode 100644 index 0000000..11d29c3 --- /dev/null +++ b/app/node_modules/lodash/_asciiSize.js @@ -0,0 +1,12 @@ +var baseProperty = require('./_baseProperty'); + +/** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ +var asciiSize = baseProperty('length'); + +module.exports = asciiSize; diff --git a/app/node_modules/lodash/_asciiToArray.js b/app/node_modules/lodash/_asciiToArray.js new file mode 100644 index 0000000..8e3dd5b --- /dev/null +++ b/app/node_modules/lodash/_asciiToArray.js @@ -0,0 +1,12 @@ +/** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function asciiToArray(string) { + return string.split(''); +} + +module.exports = asciiToArray; diff --git a/app/node_modules/lodash/_asciiWords.js b/app/node_modules/lodash/_asciiWords.js new file mode 100644 index 0000000..d765f0f --- /dev/null +++ b/app/node_modules/lodash/_asciiWords.js @@ -0,0 +1,15 @@ +/** Used to match words composed of alphanumeric characters. */ +var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + +/** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function asciiWords(string) { + return string.match(reAsciiWord) || []; +} + +module.exports = asciiWords; diff --git a/app/node_modules/lodash/_assignMergeValue.js b/app/node_modules/lodash/_assignMergeValue.js new file mode 100644 index 0000000..cb1185e --- /dev/null +++ b/app/node_modules/lodash/_assignMergeValue.js @@ -0,0 +1,20 @@ +var baseAssignValue = require('./_baseAssignValue'), + eq = require('./eq'); + +/** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} + +module.exports = assignMergeValue; diff --git a/app/node_modules/lodash/_assignValue.js b/app/node_modules/lodash/_assignValue.js new file mode 100644 index 0000000..4083957 --- /dev/null +++ b/app/node_modules/lodash/_assignValue.js @@ -0,0 +1,28 @@ +var baseAssignValue = require('./_baseAssignValue'), + eq = require('./eq'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} + +module.exports = assignValue; diff --git a/app/node_modules/lodash/_assocIndexOf.js b/app/node_modules/lodash/_assocIndexOf.js new file mode 100644 index 0000000..5b77a2b --- /dev/null +++ b/app/node_modules/lodash/_assocIndexOf.js @@ -0,0 +1,21 @@ +var eq = require('./eq'); + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} + +module.exports = assocIndexOf; diff --git a/app/node_modules/lodash/_baseAggregator.js b/app/node_modules/lodash/_baseAggregator.js new file mode 100644 index 0000000..4bc9e91 --- /dev/null +++ b/app/node_modules/lodash/_baseAggregator.js @@ -0,0 +1,21 @@ +var baseEach = require('./_baseEach'); + +/** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ +function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; +} + +module.exports = baseAggregator; diff --git a/app/node_modules/lodash/_baseAssign.js b/app/node_modules/lodash/_baseAssign.js new file mode 100644 index 0000000..e5c4a1a --- /dev/null +++ b/app/node_modules/lodash/_baseAssign.js @@ -0,0 +1,17 @@ +var copyObject = require('./_copyObject'), + keys = require('./keys'); + +/** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ +function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); +} + +module.exports = baseAssign; diff --git a/app/node_modules/lodash/_baseAssignIn.js b/app/node_modules/lodash/_baseAssignIn.js new file mode 100644 index 0000000..6624f90 --- /dev/null +++ b/app/node_modules/lodash/_baseAssignIn.js @@ -0,0 +1,17 @@ +var copyObject = require('./_copyObject'), + keysIn = require('./keysIn'); + +/** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ +function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); +} + +module.exports = baseAssignIn; diff --git a/app/node_modules/lodash/_baseAssignValue.js b/app/node_modules/lodash/_baseAssignValue.js new file mode 100644 index 0000000..d6f66ef --- /dev/null +++ b/app/node_modules/lodash/_baseAssignValue.js @@ -0,0 +1,25 @@ +var defineProperty = require('./_defineProperty'); + +/** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } +} + +module.exports = baseAssignValue; diff --git a/app/node_modules/lodash/_baseAt.js b/app/node_modules/lodash/_baseAt.js new file mode 100644 index 0000000..90e4237 --- /dev/null +++ b/app/node_modules/lodash/_baseAt.js @@ -0,0 +1,23 @@ +var get = require('./get'); + +/** + * The base implementation of `_.at` without support for individual paths. + * + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. + */ +function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; +} + +module.exports = baseAt; diff --git a/app/node_modules/lodash/_baseClamp.js b/app/node_modules/lodash/_baseClamp.js new file mode 100644 index 0000000..a1c5692 --- /dev/null +++ b/app/node_modules/lodash/_baseClamp.js @@ -0,0 +1,22 @@ +/** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ +function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; +} + +module.exports = baseClamp; diff --git a/app/node_modules/lodash/_baseClone.js b/app/node_modules/lodash/_baseClone.js new file mode 100644 index 0000000..290de92 --- /dev/null +++ b/app/node_modules/lodash/_baseClone.js @@ -0,0 +1,165 @@ +var Stack = require('./_Stack'), + arrayEach = require('./_arrayEach'), + assignValue = require('./_assignValue'), + baseAssign = require('./_baseAssign'), + baseAssignIn = require('./_baseAssignIn'), + cloneBuffer = require('./_cloneBuffer'), + copyArray = require('./_copyArray'), + copySymbols = require('./_copySymbols'), + copySymbolsIn = require('./_copySymbolsIn'), + getAllKeys = require('./_getAllKeys'), + getAllKeysIn = require('./_getAllKeysIn'), + getTag = require('./_getTag'), + initCloneArray = require('./_initCloneArray'), + initCloneByTag = require('./_initCloneByTag'), + initCloneObject = require('./_initCloneObject'), + isArray = require('./isArray'), + isBuffer = require('./isBuffer'), + isMap = require('./isMap'), + isObject = require('./isObject'), + isSet = require('./isSet'), + keys = require('./keys'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values supported by `_.clone`. */ +var cloneableTags = {}; +cloneableTags[argsTag] = cloneableTags[arrayTag] = +cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = +cloneableTags[boolTag] = cloneableTags[dateTag] = +cloneableTags[float32Tag] = cloneableTags[float64Tag] = +cloneableTags[int8Tag] = cloneableTags[int16Tag] = +cloneableTags[int32Tag] = cloneableTags[mapTag] = +cloneableTags[numberTag] = cloneableTags[objectTag] = +cloneableTags[regexpTag] = cloneableTags[setTag] = +cloneableTags[stringTag] = cloneableTags[symbolTag] = +cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = +cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; +cloneableTags[errorTag] = cloneableTags[funcTag] = +cloneableTags[weakMapTag] = false; + +/** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ +function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + } + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; +} + +module.exports = baseClone; diff --git a/app/node_modules/lodash/_baseConforms.js b/app/node_modules/lodash/_baseConforms.js new file mode 100644 index 0000000..947e20d --- /dev/null +++ b/app/node_modules/lodash/_baseConforms.js @@ -0,0 +1,18 @@ +var baseConformsTo = require('./_baseConformsTo'), + keys = require('./keys'); + +/** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ +function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; +} + +module.exports = baseConforms; diff --git a/app/node_modules/lodash/_baseConformsTo.js b/app/node_modules/lodash/_baseConformsTo.js new file mode 100644 index 0000000..e449cb8 --- /dev/null +++ b/app/node_modules/lodash/_baseConformsTo.js @@ -0,0 +1,27 @@ +/** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */ +function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; +} + +module.exports = baseConformsTo; diff --git a/app/node_modules/lodash/_baseCreate.js b/app/node_modules/lodash/_baseCreate.js new file mode 100644 index 0000000..ffa6a52 --- /dev/null +++ b/app/node_modules/lodash/_baseCreate.js @@ -0,0 +1,30 @@ +var isObject = require('./isObject'); + +/** Built-in value references. */ +var objectCreate = Object.create; + +/** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ +var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; +}()); + +module.exports = baseCreate; diff --git a/app/node_modules/lodash/_baseDelay.js b/app/node_modules/lodash/_baseDelay.js new file mode 100644 index 0000000..1486d69 --- /dev/null +++ b/app/node_modules/lodash/_baseDelay.js @@ -0,0 +1,21 @@ +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ +function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); +} + +module.exports = baseDelay; diff --git a/app/node_modules/lodash/_baseDifference.js b/app/node_modules/lodash/_baseDifference.js new file mode 100644 index 0000000..343ac19 --- /dev/null +++ b/app/node_modules/lodash/_baseDifference.js @@ -0,0 +1,67 @@ +var SetCache = require('./_SetCache'), + arrayIncludes = require('./_arrayIncludes'), + arrayIncludesWith = require('./_arrayIncludesWith'), + arrayMap = require('./_arrayMap'), + baseUnary = require('./_baseUnary'), + cacheHas = require('./_cacheHas'); + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ +function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; +} + +module.exports = baseDifference; diff --git a/app/node_modules/lodash/_baseEach.js b/app/node_modules/lodash/_baseEach.js new file mode 100644 index 0000000..512c067 --- /dev/null +++ b/app/node_modules/lodash/_baseEach.js @@ -0,0 +1,14 @@ +var baseForOwn = require('./_baseForOwn'), + createBaseEach = require('./_createBaseEach'); + +/** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ +var baseEach = createBaseEach(baseForOwn); + +module.exports = baseEach; diff --git a/app/node_modules/lodash/_baseEachRight.js b/app/node_modules/lodash/_baseEachRight.js new file mode 100644 index 0000000..0a8feec --- /dev/null +++ b/app/node_modules/lodash/_baseEachRight.js @@ -0,0 +1,14 @@ +var baseForOwnRight = require('./_baseForOwnRight'), + createBaseEach = require('./_createBaseEach'); + +/** + * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ +var baseEachRight = createBaseEach(baseForOwnRight, true); + +module.exports = baseEachRight; diff --git a/app/node_modules/lodash/_baseEvery.js b/app/node_modules/lodash/_baseEvery.js new file mode 100644 index 0000000..fa52f7b --- /dev/null +++ b/app/node_modules/lodash/_baseEvery.js @@ -0,0 +1,21 @@ +var baseEach = require('./_baseEach'); + +/** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ +function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; +} + +module.exports = baseEvery; diff --git a/app/node_modules/lodash/_baseExtremum.js b/app/node_modules/lodash/_baseExtremum.js new file mode 100644 index 0000000..9d6aa77 --- /dev/null +++ b/app/node_modules/lodash/_baseExtremum.js @@ -0,0 +1,32 @@ +var isSymbol = require('./isSymbol'); + +/** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ +function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; +} + +module.exports = baseExtremum; diff --git a/app/node_modules/lodash/_baseFill.js b/app/node_modules/lodash/_baseFill.js new file mode 100644 index 0000000..46ef9c7 --- /dev/null +++ b/app/node_modules/lodash/_baseFill.js @@ -0,0 +1,32 @@ +var toInteger = require('./toInteger'), + toLength = require('./toLength'); + +/** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ +function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; +} + +module.exports = baseFill; diff --git a/app/node_modules/lodash/_baseFilter.js b/app/node_modules/lodash/_baseFilter.js new file mode 100644 index 0000000..4678477 --- /dev/null +++ b/app/node_modules/lodash/_baseFilter.js @@ -0,0 +1,21 @@ +var baseEach = require('./_baseEach'); + +/** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ +function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; +} + +module.exports = baseFilter; diff --git a/app/node_modules/lodash/_baseFindIndex.js b/app/node_modules/lodash/_baseFindIndex.js new file mode 100644 index 0000000..e3f5d8a --- /dev/null +++ b/app/node_modules/lodash/_baseFindIndex.js @@ -0,0 +1,24 @@ +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; +} + +module.exports = baseFindIndex; diff --git a/app/node_modules/lodash/_baseFindKey.js b/app/node_modules/lodash/_baseFindKey.js new file mode 100644 index 0000000..2e430f3 --- /dev/null +++ b/app/node_modules/lodash/_baseFindKey.js @@ -0,0 +1,23 @@ +/** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ +function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; +} + +module.exports = baseFindKey; diff --git a/app/node_modules/lodash/_baseFlatten.js b/app/node_modules/lodash/_baseFlatten.js new file mode 100644 index 0000000..4b1e009 --- /dev/null +++ b/app/node_modules/lodash/_baseFlatten.js @@ -0,0 +1,38 @@ +var arrayPush = require('./_arrayPush'), + isFlattenable = require('./_isFlattenable'); + +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; +} + +module.exports = baseFlatten; diff --git a/app/node_modules/lodash/_baseFor.js b/app/node_modules/lodash/_baseFor.js new file mode 100644 index 0000000..d946590 --- /dev/null +++ b/app/node_modules/lodash/_baseFor.js @@ -0,0 +1,16 @@ +var createBaseFor = require('./_createBaseFor'); + +/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseFor = createBaseFor(); + +module.exports = baseFor; diff --git a/app/node_modules/lodash/_baseForOwn.js b/app/node_modules/lodash/_baseForOwn.js new file mode 100644 index 0000000..503d523 --- /dev/null +++ b/app/node_modules/lodash/_baseForOwn.js @@ -0,0 +1,16 @@ +var baseFor = require('./_baseFor'), + keys = require('./keys'); + +/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ +function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); +} + +module.exports = baseForOwn; diff --git a/app/node_modules/lodash/_baseForOwnRight.js b/app/node_modules/lodash/_baseForOwnRight.js new file mode 100644 index 0000000..a4b10e6 --- /dev/null +++ b/app/node_modules/lodash/_baseForOwnRight.js @@ -0,0 +1,16 @@ +var baseForRight = require('./_baseForRight'), + keys = require('./keys'); + +/** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ +function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); +} + +module.exports = baseForOwnRight; diff --git a/app/node_modules/lodash/_baseForRight.js b/app/node_modules/lodash/_baseForRight.js new file mode 100644 index 0000000..32842cd --- /dev/null +++ b/app/node_modules/lodash/_baseForRight.js @@ -0,0 +1,15 @@ +var createBaseFor = require('./_createBaseFor'); + +/** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseForRight = createBaseFor(true); + +module.exports = baseForRight; diff --git a/app/node_modules/lodash/_baseFunctions.js b/app/node_modules/lodash/_baseFunctions.js new file mode 100644 index 0000000..d23bc9b --- /dev/null +++ b/app/node_modules/lodash/_baseFunctions.js @@ -0,0 +1,19 @@ +var arrayFilter = require('./_arrayFilter'), + isFunction = require('./isFunction'); + +/** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ +function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); +} + +module.exports = baseFunctions; diff --git a/app/node_modules/lodash/_baseGet.js b/app/node_modules/lodash/_baseGet.js new file mode 100644 index 0000000..a194913 --- /dev/null +++ b/app/node_modules/lodash/_baseGet.js @@ -0,0 +1,24 @@ +var castPath = require('./_castPath'), + toKey = require('./_toKey'); + +/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ +function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; +} + +module.exports = baseGet; diff --git a/app/node_modules/lodash/_baseGetAllKeys.js b/app/node_modules/lodash/_baseGetAllKeys.js new file mode 100644 index 0000000..8ad204e --- /dev/null +++ b/app/node_modules/lodash/_baseGetAllKeys.js @@ -0,0 +1,20 @@ +var arrayPush = require('./_arrayPush'), + isArray = require('./isArray'); + +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ +function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); +} + +module.exports = baseGetAllKeys; diff --git a/app/node_modules/lodash/_baseGetTag.js b/app/node_modules/lodash/_baseGetTag.js new file mode 100644 index 0000000..b927ccc --- /dev/null +++ b/app/node_modules/lodash/_baseGetTag.js @@ -0,0 +1,28 @@ +var Symbol = require('./_Symbol'), + getRawTag = require('./_getRawTag'), + objectToString = require('./_objectToString'); + +/** `Object#toString` result references. */ +var nullTag = '[object Null]', + undefinedTag = '[object Undefined]'; + +/** Built-in value references. */ +var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); +} + +module.exports = baseGetTag; diff --git a/app/node_modules/lodash/_baseGt.js b/app/node_modules/lodash/_baseGt.js new file mode 100644 index 0000000..502d273 --- /dev/null +++ b/app/node_modules/lodash/_baseGt.js @@ -0,0 +1,14 @@ +/** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ +function baseGt(value, other) { + return value > other; +} + +module.exports = baseGt; diff --git a/app/node_modules/lodash/_baseHas.js b/app/node_modules/lodash/_baseHas.js new file mode 100644 index 0000000..1b73032 --- /dev/null +++ b/app/node_modules/lodash/_baseHas.js @@ -0,0 +1,19 @@ +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); +} + +module.exports = baseHas; diff --git a/app/node_modules/lodash/_baseHasIn.js b/app/node_modules/lodash/_baseHasIn.js new file mode 100644 index 0000000..2e0d042 --- /dev/null +++ b/app/node_modules/lodash/_baseHasIn.js @@ -0,0 +1,13 @@ +/** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHasIn(object, key) { + return object != null && key in Object(object); +} + +module.exports = baseHasIn; diff --git a/app/node_modules/lodash/_baseInRange.js b/app/node_modules/lodash/_baseInRange.js new file mode 100644 index 0000000..ec95666 --- /dev/null +++ b/app/node_modules/lodash/_baseInRange.js @@ -0,0 +1,18 @@ +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ +function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); +} + +module.exports = baseInRange; diff --git a/app/node_modules/lodash/_baseIndexOf.js b/app/node_modules/lodash/_baseIndexOf.js new file mode 100644 index 0000000..167e706 --- /dev/null +++ b/app/node_modules/lodash/_baseIndexOf.js @@ -0,0 +1,20 @@ +var baseFindIndex = require('./_baseFindIndex'), + baseIsNaN = require('./_baseIsNaN'), + strictIndexOf = require('./_strictIndexOf'); + +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); +} + +module.exports = baseIndexOf; diff --git a/app/node_modules/lodash/_baseIndexOfWith.js b/app/node_modules/lodash/_baseIndexOfWith.js new file mode 100644 index 0000000..f815fe0 --- /dev/null +++ b/app/node_modules/lodash/_baseIndexOfWith.js @@ -0,0 +1,23 @@ +/** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; +} + +module.exports = baseIndexOfWith; diff --git a/app/node_modules/lodash/_baseIntersection.js b/app/node_modules/lodash/_baseIntersection.js new file mode 100644 index 0000000..c1d250c --- /dev/null +++ b/app/node_modules/lodash/_baseIntersection.js @@ -0,0 +1,74 @@ +var SetCache = require('./_SetCache'), + arrayIncludes = require('./_arrayIncludes'), + arrayIncludesWith = require('./_arrayIncludesWith'), + arrayMap = require('./_arrayMap'), + baseUnary = require('./_baseUnary'), + cacheHas = require('./_cacheHas'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin = Math.min; + +/** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ +function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; +} + +module.exports = baseIntersection; diff --git a/app/node_modules/lodash/_baseInverter.js b/app/node_modules/lodash/_baseInverter.js new file mode 100644 index 0000000..fbc337f --- /dev/null +++ b/app/node_modules/lodash/_baseInverter.js @@ -0,0 +1,21 @@ +var baseForOwn = require('./_baseForOwn'); + +/** + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. + */ +function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; +} + +module.exports = baseInverter; diff --git a/app/node_modules/lodash/_baseInvoke.js b/app/node_modules/lodash/_baseInvoke.js new file mode 100644 index 0000000..49bcf3c --- /dev/null +++ b/app/node_modules/lodash/_baseInvoke.js @@ -0,0 +1,24 @@ +var apply = require('./_apply'), + castPath = require('./_castPath'), + last = require('./last'), + parent = require('./_parent'), + toKey = require('./_toKey'); + +/** + * The base implementation of `_.invoke` without support for individual + * method arguments. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ +function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); +} + +module.exports = baseInvoke; diff --git a/app/node_modules/lodash/_baseIsArguments.js b/app/node_modules/lodash/_baseIsArguments.js new file mode 100644 index 0000000..b3562cc --- /dev/null +++ b/app/node_modules/lodash/_baseIsArguments.js @@ -0,0 +1,18 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]'; + +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; +} + +module.exports = baseIsArguments; diff --git a/app/node_modules/lodash/_baseIsArrayBuffer.js b/app/node_modules/lodash/_baseIsArrayBuffer.js new file mode 100644 index 0000000..a2c4f30 --- /dev/null +++ b/app/node_modules/lodash/_baseIsArrayBuffer.js @@ -0,0 +1,17 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +var arrayBufferTag = '[object ArrayBuffer]'; + +/** + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + */ +function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; +} + +module.exports = baseIsArrayBuffer; diff --git a/app/node_modules/lodash/_baseIsDate.js b/app/node_modules/lodash/_baseIsDate.js new file mode 100644 index 0000000..ba67c78 --- /dev/null +++ b/app/node_modules/lodash/_baseIsDate.js @@ -0,0 +1,18 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var dateTag = '[object Date]'; + +/** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ +function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; +} + +module.exports = baseIsDate; diff --git a/app/node_modules/lodash/_baseIsEqual.js b/app/node_modules/lodash/_baseIsEqual.js new file mode 100644 index 0000000..00a68a4 --- /dev/null +++ b/app/node_modules/lodash/_baseIsEqual.js @@ -0,0 +1,28 @@ +var baseIsEqualDeep = require('./_baseIsEqualDeep'), + isObjectLike = require('./isObjectLike'); + +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ +function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); +} + +module.exports = baseIsEqual; diff --git a/app/node_modules/lodash/_baseIsEqualDeep.js b/app/node_modules/lodash/_baseIsEqualDeep.js new file mode 100644 index 0000000..e3cfd6a --- /dev/null +++ b/app/node_modules/lodash/_baseIsEqualDeep.js @@ -0,0 +1,83 @@ +var Stack = require('./_Stack'), + equalArrays = require('./_equalArrays'), + equalByTag = require('./_equalByTag'), + equalObjects = require('./_equalObjects'), + getTag = require('./_getTag'), + isArray = require('./isArray'), + isBuffer = require('./isBuffer'), + isTypedArray = require('./isTypedArray'); + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + objectTag = '[object Object]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); +} + +module.exports = baseIsEqualDeep; diff --git a/app/node_modules/lodash/_baseIsMap.js b/app/node_modules/lodash/_baseIsMap.js new file mode 100644 index 0000000..02a4021 --- /dev/null +++ b/app/node_modules/lodash/_baseIsMap.js @@ -0,0 +1,18 @@ +var getTag = require('./_getTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var mapTag = '[object Map]'; + +/** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ +function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; +} + +module.exports = baseIsMap; diff --git a/app/node_modules/lodash/_baseIsMatch.js b/app/node_modules/lodash/_baseIsMatch.js new file mode 100644 index 0000000..72494be --- /dev/null +++ b/app/node_modules/lodash/_baseIsMatch.js @@ -0,0 +1,62 @@ +var Stack = require('./_Stack'), + baseIsEqual = require('./_baseIsEqual'); + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ +function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; +} + +module.exports = baseIsMatch; diff --git a/app/node_modules/lodash/_baseIsNaN.js b/app/node_modules/lodash/_baseIsNaN.js new file mode 100644 index 0000000..316f1eb --- /dev/null +++ b/app/node_modules/lodash/_baseIsNaN.js @@ -0,0 +1,12 @@ +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} + +module.exports = baseIsNaN; diff --git a/app/node_modules/lodash/_baseIsNative.js b/app/node_modules/lodash/_baseIsNative.js new file mode 100644 index 0000000..8702330 --- /dev/null +++ b/app/node_modules/lodash/_baseIsNative.js @@ -0,0 +1,47 @@ +var isFunction = require('./isFunction'), + isMasked = require('./_isMasked'), + isObject = require('./isObject'), + toSource = require('./_toSource'); + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} + +module.exports = baseIsNative; diff --git a/app/node_modules/lodash/_baseIsRegExp.js b/app/node_modules/lodash/_baseIsRegExp.js new file mode 100644 index 0000000..6cd7c1a --- /dev/null +++ b/app/node_modules/lodash/_baseIsRegExp.js @@ -0,0 +1,18 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var regexpTag = '[object RegExp]'; + +/** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ +function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; +} + +module.exports = baseIsRegExp; diff --git a/app/node_modules/lodash/_baseIsSet.js b/app/node_modules/lodash/_baseIsSet.js new file mode 100644 index 0000000..6dee367 --- /dev/null +++ b/app/node_modules/lodash/_baseIsSet.js @@ -0,0 +1,18 @@ +var getTag = require('./_getTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var setTag = '[object Set]'; + +/** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ +function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; +} + +module.exports = baseIsSet; diff --git a/app/node_modules/lodash/_baseIsTypedArray.js b/app/node_modules/lodash/_baseIsTypedArray.js new file mode 100644 index 0000000..1edb32f --- /dev/null +++ b/app/node_modules/lodash/_baseIsTypedArray.js @@ -0,0 +1,60 @@ +var baseGetTag = require('./_baseGetTag'), + isLength = require('./isLength'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +typedArrayTags[errorTag] = typedArrayTags[funcTag] = +typedArrayTags[mapTag] = typedArrayTags[numberTag] = +typedArrayTags[objectTag] = typedArrayTags[regexpTag] = +typedArrayTags[setTag] = typedArrayTags[stringTag] = +typedArrayTags[weakMapTag] = false; + +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; +} + +module.exports = baseIsTypedArray; diff --git a/app/node_modules/lodash/_baseIteratee.js b/app/node_modules/lodash/_baseIteratee.js new file mode 100644 index 0000000..995c257 --- /dev/null +++ b/app/node_modules/lodash/_baseIteratee.js @@ -0,0 +1,31 @@ +var baseMatches = require('./_baseMatches'), + baseMatchesProperty = require('./_baseMatchesProperty'), + identity = require('./identity'), + isArray = require('./isArray'), + property = require('./property'); + +/** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ +function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); +} + +module.exports = baseIteratee; diff --git a/app/node_modules/lodash/_baseKeys.js b/app/node_modules/lodash/_baseKeys.js new file mode 100644 index 0000000..45e9e6f --- /dev/null +++ b/app/node_modules/lodash/_baseKeys.js @@ -0,0 +1,30 @@ +var isPrototype = require('./_isPrototype'), + nativeKeys = require('./_nativeKeys'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +module.exports = baseKeys; diff --git a/app/node_modules/lodash/_baseKeysIn.js b/app/node_modules/lodash/_baseKeysIn.js new file mode 100644 index 0000000..ea8a0a1 --- /dev/null +++ b/app/node_modules/lodash/_baseKeysIn.js @@ -0,0 +1,33 @@ +var isObject = require('./isObject'), + isPrototype = require('./_isPrototype'), + nativeKeysIn = require('./_nativeKeysIn'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; +} + +module.exports = baseKeysIn; diff --git a/app/node_modules/lodash/_baseLodash.js b/app/node_modules/lodash/_baseLodash.js new file mode 100644 index 0000000..f76c790 --- /dev/null +++ b/app/node_modules/lodash/_baseLodash.js @@ -0,0 +1,10 @@ +/** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */ +function baseLodash() { + // No operation performed. +} + +module.exports = baseLodash; diff --git a/app/node_modules/lodash/_baseLt.js b/app/node_modules/lodash/_baseLt.js new file mode 100644 index 0000000..8674d29 --- /dev/null +++ b/app/node_modules/lodash/_baseLt.js @@ -0,0 +1,14 @@ +/** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ +function baseLt(value, other) { + return value < other; +} + +module.exports = baseLt; diff --git a/app/node_modules/lodash/_baseMap.js b/app/node_modules/lodash/_baseMap.js new file mode 100644 index 0000000..0bf5cea --- /dev/null +++ b/app/node_modules/lodash/_baseMap.js @@ -0,0 +1,22 @@ +var baseEach = require('./_baseEach'), + isArrayLike = require('./isArrayLike'); + +/** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; +} + +module.exports = baseMap; diff --git a/app/node_modules/lodash/_baseMatches.js b/app/node_modules/lodash/_baseMatches.js new file mode 100644 index 0000000..e56582a --- /dev/null +++ b/app/node_modules/lodash/_baseMatches.js @@ -0,0 +1,22 @@ +var baseIsMatch = require('./_baseIsMatch'), + getMatchData = require('./_getMatchData'), + matchesStrictComparable = require('./_matchesStrictComparable'); + +/** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; +} + +module.exports = baseMatches; diff --git a/app/node_modules/lodash/_baseMatchesProperty.js b/app/node_modules/lodash/_baseMatchesProperty.js new file mode 100644 index 0000000..24afd89 --- /dev/null +++ b/app/node_modules/lodash/_baseMatchesProperty.js @@ -0,0 +1,33 @@ +var baseIsEqual = require('./_baseIsEqual'), + get = require('./get'), + hasIn = require('./hasIn'), + isKey = require('./_isKey'), + isStrictComparable = require('./_isStrictComparable'), + matchesStrictComparable = require('./_matchesStrictComparable'), + toKey = require('./_toKey'); + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; +} + +module.exports = baseMatchesProperty; diff --git a/app/node_modules/lodash/_baseMean.js b/app/node_modules/lodash/_baseMean.js new file mode 100644 index 0000000..fa9e00a --- /dev/null +++ b/app/node_modules/lodash/_baseMean.js @@ -0,0 +1,20 @@ +var baseSum = require('./_baseSum'); + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ +function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; +} + +module.exports = baseMean; diff --git a/app/node_modules/lodash/_baseMerge.js b/app/node_modules/lodash/_baseMerge.js new file mode 100644 index 0000000..c98b5eb --- /dev/null +++ b/app/node_modules/lodash/_baseMerge.js @@ -0,0 +1,42 @@ +var Stack = require('./_Stack'), + assignMergeValue = require('./_assignMergeValue'), + baseFor = require('./_baseFor'), + baseMergeDeep = require('./_baseMergeDeep'), + isObject = require('./isObject'), + keysIn = require('./keysIn'), + safeGet = require('./_safeGet'); + +/** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); +} + +module.exports = baseMerge; diff --git a/app/node_modules/lodash/_baseMergeDeep.js b/app/node_modules/lodash/_baseMergeDeep.js new file mode 100644 index 0000000..4679e8d --- /dev/null +++ b/app/node_modules/lodash/_baseMergeDeep.js @@ -0,0 +1,94 @@ +var assignMergeValue = require('./_assignMergeValue'), + cloneBuffer = require('./_cloneBuffer'), + cloneTypedArray = require('./_cloneTypedArray'), + copyArray = require('./_copyArray'), + initCloneObject = require('./_initCloneObject'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isArrayLikeObject = require('./isArrayLikeObject'), + isBuffer = require('./isBuffer'), + isFunction = require('./isFunction'), + isObject = require('./isObject'), + isPlainObject = require('./isPlainObject'), + isTypedArray = require('./isTypedArray'), + safeGet = require('./_safeGet'), + toPlainObject = require('./toPlainObject'); + +/** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); +} + +module.exports = baseMergeDeep; diff --git a/app/node_modules/lodash/_baseNth.js b/app/node_modules/lodash/_baseNth.js new file mode 100644 index 0000000..0403c2a --- /dev/null +++ b/app/node_modules/lodash/_baseNth.js @@ -0,0 +1,20 @@ +var isIndex = require('./_isIndex'); + +/** + * The base implementation of `_.nth` which doesn't coerce arguments. + * + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. + */ +function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; +} + +module.exports = baseNth; diff --git a/app/node_modules/lodash/_baseOrderBy.js b/app/node_modules/lodash/_baseOrderBy.js new file mode 100644 index 0000000..d8a46ab --- /dev/null +++ b/app/node_modules/lodash/_baseOrderBy.js @@ -0,0 +1,34 @@ +var arrayMap = require('./_arrayMap'), + baseIteratee = require('./_baseIteratee'), + baseMap = require('./_baseMap'), + baseSortBy = require('./_baseSortBy'), + baseUnary = require('./_baseUnary'), + compareMultiple = require('./_compareMultiple'), + identity = require('./identity'); + +/** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ +function baseOrderBy(collection, iteratees, orders) { + var index = -1; + iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee)); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); +} + +module.exports = baseOrderBy; diff --git a/app/node_modules/lodash/_basePick.js b/app/node_modules/lodash/_basePick.js new file mode 100644 index 0000000..09b458a --- /dev/null +++ b/app/node_modules/lodash/_basePick.js @@ -0,0 +1,19 @@ +var basePickBy = require('./_basePickBy'), + hasIn = require('./hasIn'); + +/** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ +function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); +} + +module.exports = basePick; diff --git a/app/node_modules/lodash/_basePickBy.js b/app/node_modules/lodash/_basePickBy.js new file mode 100644 index 0000000..85be68c --- /dev/null +++ b/app/node_modules/lodash/_basePickBy.js @@ -0,0 +1,30 @@ +var baseGet = require('./_baseGet'), + baseSet = require('./_baseSet'), + castPath = require('./_castPath'); + +/** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ +function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; +} + +module.exports = basePickBy; diff --git a/app/node_modules/lodash/_baseProperty.js b/app/node_modules/lodash/_baseProperty.js new file mode 100644 index 0000000..496281e --- /dev/null +++ b/app/node_modules/lodash/_baseProperty.js @@ -0,0 +1,14 @@ +/** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; +} + +module.exports = baseProperty; diff --git a/app/node_modules/lodash/_basePropertyDeep.js b/app/node_modules/lodash/_basePropertyDeep.js new file mode 100644 index 0000000..1e5aae5 --- /dev/null +++ b/app/node_modules/lodash/_basePropertyDeep.js @@ -0,0 +1,16 @@ +var baseGet = require('./_baseGet'); + +/** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; +} + +module.exports = basePropertyDeep; diff --git a/app/node_modules/lodash/_basePropertyOf.js b/app/node_modules/lodash/_basePropertyOf.js new file mode 100644 index 0000000..4617399 --- /dev/null +++ b/app/node_modules/lodash/_basePropertyOf.js @@ -0,0 +1,14 @@ +/** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; +} + +module.exports = basePropertyOf; diff --git a/app/node_modules/lodash/_basePullAll.js b/app/node_modules/lodash/_basePullAll.js new file mode 100644 index 0000000..305720e --- /dev/null +++ b/app/node_modules/lodash/_basePullAll.js @@ -0,0 +1,51 @@ +var arrayMap = require('./_arrayMap'), + baseIndexOf = require('./_baseIndexOf'), + baseIndexOfWith = require('./_baseIndexOfWith'), + baseUnary = require('./_baseUnary'), + copyArray = require('./_copyArray'); + +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/** Built-in value references. */ +var splice = arrayProto.splice; + +/** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ +function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; +} + +module.exports = basePullAll; diff --git a/app/node_modules/lodash/_basePullAt.js b/app/node_modules/lodash/_basePullAt.js new file mode 100644 index 0000000..c3e9e71 --- /dev/null +++ b/app/node_modules/lodash/_basePullAt.js @@ -0,0 +1,37 @@ +var baseUnset = require('./_baseUnset'), + isIndex = require('./_isIndex'); + +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/** Built-in value references. */ +var splice = arrayProto.splice; + +/** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ +function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; +} + +module.exports = basePullAt; diff --git a/app/node_modules/lodash/_baseRandom.js b/app/node_modules/lodash/_baseRandom.js new file mode 100644 index 0000000..94f76a7 --- /dev/null +++ b/app/node_modules/lodash/_baseRandom.js @@ -0,0 +1,18 @@ +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeFloor = Math.floor, + nativeRandom = Math.random; + +/** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */ +function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); +} + +module.exports = baseRandom; diff --git a/app/node_modules/lodash/_baseRange.js b/app/node_modules/lodash/_baseRange.js new file mode 100644 index 0000000..0fb8e41 --- /dev/null +++ b/app/node_modules/lodash/_baseRange.js @@ -0,0 +1,28 @@ +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeCeil = Math.ceil, + nativeMax = Math.max; + +/** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ +function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; +} + +module.exports = baseRange; diff --git a/app/node_modules/lodash/_baseReduce.js b/app/node_modules/lodash/_baseReduce.js new file mode 100644 index 0000000..5a1f8b5 --- /dev/null +++ b/app/node_modules/lodash/_baseReduce.js @@ -0,0 +1,23 @@ +/** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ +function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; +} + +module.exports = baseReduce; diff --git a/app/node_modules/lodash/_baseRepeat.js b/app/node_modules/lodash/_baseRepeat.js new file mode 100644 index 0000000..ee44c31 --- /dev/null +++ b/app/node_modules/lodash/_baseRepeat.js @@ -0,0 +1,35 @@ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeFloor = Math.floor; + +/** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ +function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; +} + +module.exports = baseRepeat; diff --git a/app/node_modules/lodash/_baseRest.js b/app/node_modules/lodash/_baseRest.js new file mode 100644 index 0000000..d0dc4bd --- /dev/null +++ b/app/node_modules/lodash/_baseRest.js @@ -0,0 +1,17 @@ +var identity = require('./identity'), + overRest = require('./_overRest'), + setToString = require('./_setToString'); + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); +} + +module.exports = baseRest; diff --git a/app/node_modules/lodash/_baseSample.js b/app/node_modules/lodash/_baseSample.js new file mode 100644 index 0000000..58582b9 --- /dev/null +++ b/app/node_modules/lodash/_baseSample.js @@ -0,0 +1,15 @@ +var arraySample = require('./_arraySample'), + values = require('./values'); + +/** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ +function baseSample(collection) { + return arraySample(values(collection)); +} + +module.exports = baseSample; diff --git a/app/node_modules/lodash/_baseSampleSize.js b/app/node_modules/lodash/_baseSampleSize.js new file mode 100644 index 0000000..5c90ec5 --- /dev/null +++ b/app/node_modules/lodash/_baseSampleSize.js @@ -0,0 +1,18 @@ +var baseClamp = require('./_baseClamp'), + shuffleSelf = require('./_shuffleSelf'), + values = require('./values'); + +/** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ +function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); +} + +module.exports = baseSampleSize; diff --git a/app/node_modules/lodash/_baseSet.js b/app/node_modules/lodash/_baseSet.js new file mode 100644 index 0000000..612a24c --- /dev/null +++ b/app/node_modules/lodash/_baseSet.js @@ -0,0 +1,47 @@ +var assignValue = require('./_assignValue'), + castPath = require('./_castPath'), + isIndex = require('./_isIndex'), + isObject = require('./isObject'), + toKey = require('./_toKey'); + +/** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ +function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; +} + +module.exports = baseSet; diff --git a/app/node_modules/lodash/_baseSetData.js b/app/node_modules/lodash/_baseSetData.js new file mode 100644 index 0000000..c409947 --- /dev/null +++ b/app/node_modules/lodash/_baseSetData.js @@ -0,0 +1,17 @@ +var identity = require('./identity'), + metaMap = require('./_metaMap'); + +/** + * The base implementation of `setData` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ +var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; +}; + +module.exports = baseSetData; diff --git a/app/node_modules/lodash/_baseSetToString.js b/app/node_modules/lodash/_baseSetToString.js new file mode 100644 index 0000000..89eaca3 --- /dev/null +++ b/app/node_modules/lodash/_baseSetToString.js @@ -0,0 +1,22 @@ +var constant = require('./constant'), + defineProperty = require('./_defineProperty'), + identity = require('./identity'); + +/** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); +}; + +module.exports = baseSetToString; diff --git a/app/node_modules/lodash/_baseShuffle.js b/app/node_modules/lodash/_baseShuffle.js new file mode 100644 index 0000000..023077a --- /dev/null +++ b/app/node_modules/lodash/_baseShuffle.js @@ -0,0 +1,15 @@ +var shuffleSelf = require('./_shuffleSelf'), + values = require('./values'); + +/** + * The base implementation of `_.shuffle`. + * + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + */ +function baseShuffle(collection) { + return shuffleSelf(values(collection)); +} + +module.exports = baseShuffle; diff --git a/app/node_modules/lodash/_baseSlice.js b/app/node_modules/lodash/_baseSlice.js new file mode 100644 index 0000000..786f6c9 --- /dev/null +++ b/app/node_modules/lodash/_baseSlice.js @@ -0,0 +1,31 @@ +/** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; +} + +module.exports = baseSlice; diff --git a/app/node_modules/lodash/_baseSome.js b/app/node_modules/lodash/_baseSome.js new file mode 100644 index 0000000..58f3f44 --- /dev/null +++ b/app/node_modules/lodash/_baseSome.js @@ -0,0 +1,22 @@ +var baseEach = require('./_baseEach'); + +/** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; +} + +module.exports = baseSome; diff --git a/app/node_modules/lodash/_baseSortBy.js b/app/node_modules/lodash/_baseSortBy.js new file mode 100644 index 0000000..a25c92e --- /dev/null +++ b/app/node_modules/lodash/_baseSortBy.js @@ -0,0 +1,21 @@ +/** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ +function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; +} + +module.exports = baseSortBy; diff --git a/app/node_modules/lodash/_baseSortedIndex.js b/app/node_modules/lodash/_baseSortedIndex.js new file mode 100644 index 0000000..638c366 --- /dev/null +++ b/app/node_modules/lodash/_baseSortedIndex.js @@ -0,0 +1,42 @@ +var baseSortedIndexBy = require('./_baseSortedIndexBy'), + identity = require('./identity'), + isSymbol = require('./isSymbol'); + +/** Used as references for the maximum length and index of an array. */ +var MAX_ARRAY_LENGTH = 4294967295, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + +/** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ +function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); +} + +module.exports = baseSortedIndex; diff --git a/app/node_modules/lodash/_baseSortedIndexBy.js b/app/node_modules/lodash/_baseSortedIndexBy.js new file mode 100644 index 0000000..bb22e36 --- /dev/null +++ b/app/node_modules/lodash/_baseSortedIndexBy.js @@ -0,0 +1,64 @@ +var isSymbol = require('./isSymbol'); + +/** Used as references for the maximum length and index of an array. */ +var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeFloor = Math.floor, + nativeMin = Math.min; + +/** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ +function baseSortedIndexBy(array, value, iteratee, retHighest) { + value = iteratee(value); + + var low = 0, + high = array == null ? 0 : array.length, + valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); +} + +module.exports = baseSortedIndexBy; diff --git a/app/node_modules/lodash/_baseSortedUniq.js b/app/node_modules/lodash/_baseSortedUniq.js new file mode 100644 index 0000000..802159a --- /dev/null +++ b/app/node_modules/lodash/_baseSortedUniq.js @@ -0,0 +1,30 @@ +var eq = require('./eq'); + +/** + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ +function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; +} + +module.exports = baseSortedUniq; diff --git a/app/node_modules/lodash/_baseSum.js b/app/node_modules/lodash/_baseSum.js new file mode 100644 index 0000000..a9e84c1 --- /dev/null +++ b/app/node_modules/lodash/_baseSum.js @@ -0,0 +1,24 @@ +/** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ +function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); + } + } + return result; +} + +module.exports = baseSum; diff --git a/app/node_modules/lodash/_baseTimes.js b/app/node_modules/lodash/_baseTimes.js new file mode 100644 index 0000000..0603fc3 --- /dev/null +++ b/app/node_modules/lodash/_baseTimes.js @@ -0,0 +1,20 @@ +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +module.exports = baseTimes; diff --git a/app/node_modules/lodash/_baseToNumber.js b/app/node_modules/lodash/_baseToNumber.js new file mode 100644 index 0000000..04859f3 --- /dev/null +++ b/app/node_modules/lodash/_baseToNumber.js @@ -0,0 +1,24 @@ +var isSymbol = require('./isSymbol'); + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. + * + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. + */ +function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; +} + +module.exports = baseToNumber; diff --git a/app/node_modules/lodash/_baseToPairs.js b/app/node_modules/lodash/_baseToPairs.js new file mode 100644 index 0000000..bff1991 --- /dev/null +++ b/app/node_modules/lodash/_baseToPairs.js @@ -0,0 +1,18 @@ +var arrayMap = require('./_arrayMap'); + +/** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ +function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); +} + +module.exports = baseToPairs; diff --git a/app/node_modules/lodash/_baseToString.js b/app/node_modules/lodash/_baseToString.js new file mode 100644 index 0000000..ada6ad2 --- /dev/null +++ b/app/node_modules/lodash/_baseToString.js @@ -0,0 +1,37 @@ +var Symbol = require('./_Symbol'), + arrayMap = require('./_arrayMap'), + isArray = require('./isArray'), + isSymbol = require('./isSymbol'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +module.exports = baseToString; diff --git a/app/node_modules/lodash/_baseUnary.js b/app/node_modules/lodash/_baseUnary.js new file mode 100644 index 0000000..98639e9 --- /dev/null +++ b/app/node_modules/lodash/_baseUnary.js @@ -0,0 +1,14 @@ +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} + +module.exports = baseUnary; diff --git a/app/node_modules/lodash/_baseUniq.js b/app/node_modules/lodash/_baseUniq.js new file mode 100644 index 0000000..aea459d --- /dev/null +++ b/app/node_modules/lodash/_baseUniq.js @@ -0,0 +1,72 @@ +var SetCache = require('./_SetCache'), + arrayIncludes = require('./_arrayIncludes'), + arrayIncludesWith = require('./_arrayIncludesWith'), + cacheHas = require('./_cacheHas'), + createSet = require('./_createSet'), + setToArray = require('./_setToArray'); + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ +function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; +} + +module.exports = baseUniq; diff --git a/app/node_modules/lodash/_baseUnset.js b/app/node_modules/lodash/_baseUnset.js new file mode 100644 index 0000000..eefc6e3 --- /dev/null +++ b/app/node_modules/lodash/_baseUnset.js @@ -0,0 +1,20 @@ +var castPath = require('./_castPath'), + last = require('./last'), + parent = require('./_parent'), + toKey = require('./_toKey'); + +/** + * The base implementation of `_.unset`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + */ +function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; +} + +module.exports = baseUnset; diff --git a/app/node_modules/lodash/_baseUpdate.js b/app/node_modules/lodash/_baseUpdate.js new file mode 100644 index 0000000..92a6237 --- /dev/null +++ b/app/node_modules/lodash/_baseUpdate.js @@ -0,0 +1,18 @@ +var baseGet = require('./_baseGet'), + baseSet = require('./_baseSet'); + +/** + * The base implementation of `_.update`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ +function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); +} + +module.exports = baseUpdate; diff --git a/app/node_modules/lodash/_baseValues.js b/app/node_modules/lodash/_baseValues.js new file mode 100644 index 0000000..b95faad --- /dev/null +++ b/app/node_modules/lodash/_baseValues.js @@ -0,0 +1,19 @@ +var arrayMap = require('./_arrayMap'); + +/** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ +function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); +} + +module.exports = baseValues; diff --git a/app/node_modules/lodash/_baseWhile.js b/app/node_modules/lodash/_baseWhile.js new file mode 100644 index 0000000..07eac61 --- /dev/null +++ b/app/node_modules/lodash/_baseWhile.js @@ -0,0 +1,26 @@ +var baseSlice = require('./_baseSlice'); + +/** + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ +function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); +} + +module.exports = baseWhile; diff --git a/app/node_modules/lodash/_baseWrapperValue.js b/app/node_modules/lodash/_baseWrapperValue.js new file mode 100644 index 0000000..443e0df --- /dev/null +++ b/app/node_modules/lodash/_baseWrapperValue.js @@ -0,0 +1,25 @@ +var LazyWrapper = require('./_LazyWrapper'), + arrayPush = require('./_arrayPush'), + arrayReduce = require('./_arrayReduce'); + +/** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ +function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); +} + +module.exports = baseWrapperValue; diff --git a/app/node_modules/lodash/_baseXor.js b/app/node_modules/lodash/_baseXor.js new file mode 100644 index 0000000..8e69338 --- /dev/null +++ b/app/node_modules/lodash/_baseXor.js @@ -0,0 +1,36 @@ +var baseDifference = require('./_baseDifference'), + baseFlatten = require('./_baseFlatten'), + baseUniq = require('./_baseUniq'); + +/** + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. + */ +function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, + result = Array(length); + + while (++index < length) { + var array = arrays[index], + othIndex = -1; + + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } + } + return baseUniq(baseFlatten(result, 1), iteratee, comparator); +} + +module.exports = baseXor; diff --git a/app/node_modules/lodash/_baseZipObject.js b/app/node_modules/lodash/_baseZipObject.js new file mode 100644 index 0000000..401f85b --- /dev/null +++ b/app/node_modules/lodash/_baseZipObject.js @@ -0,0 +1,23 @@ +/** + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. + */ +function baseZipObject(props, values, assignFunc) { + var index = -1, + length = props.length, + valsLength = values.length, + result = {}; + + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } + return result; +} + +module.exports = baseZipObject; diff --git a/app/node_modules/lodash/_cacheHas.js b/app/node_modules/lodash/_cacheHas.js new file mode 100644 index 0000000..2dec892 --- /dev/null +++ b/app/node_modules/lodash/_cacheHas.js @@ -0,0 +1,13 @@ +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} + +module.exports = cacheHas; diff --git a/app/node_modules/lodash/_castArrayLikeObject.js b/app/node_modules/lodash/_castArrayLikeObject.js new file mode 100644 index 0000000..92c75fa --- /dev/null +++ b/app/node_modules/lodash/_castArrayLikeObject.js @@ -0,0 +1,14 @@ +var isArrayLikeObject = require('./isArrayLikeObject'); + +/** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ +function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; +} + +module.exports = castArrayLikeObject; diff --git a/app/node_modules/lodash/_castFunction.js b/app/node_modules/lodash/_castFunction.js new file mode 100644 index 0000000..98c91ae --- /dev/null +++ b/app/node_modules/lodash/_castFunction.js @@ -0,0 +1,14 @@ +var identity = require('./identity'); + +/** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ +function castFunction(value) { + return typeof value == 'function' ? value : identity; +} + +module.exports = castFunction; diff --git a/app/node_modules/lodash/_castPath.js b/app/node_modules/lodash/_castPath.js new file mode 100644 index 0000000..017e4c1 --- /dev/null +++ b/app/node_modules/lodash/_castPath.js @@ -0,0 +1,21 @@ +var isArray = require('./isArray'), + isKey = require('./_isKey'), + stringToPath = require('./_stringToPath'), + toString = require('./toString'); + +/** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ +function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); +} + +module.exports = castPath; diff --git a/app/node_modules/lodash/_castRest.js b/app/node_modules/lodash/_castRest.js new file mode 100644 index 0000000..213c66f --- /dev/null +++ b/app/node_modules/lodash/_castRest.js @@ -0,0 +1,14 @@ +var baseRest = require('./_baseRest'); + +/** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. + * + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ +var castRest = baseRest; + +module.exports = castRest; diff --git a/app/node_modules/lodash/_castSlice.js b/app/node_modules/lodash/_castSlice.js new file mode 100644 index 0000000..071faeb --- /dev/null +++ b/app/node_modules/lodash/_castSlice.js @@ -0,0 +1,18 @@ +var baseSlice = require('./_baseSlice'); + +/** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ +function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); +} + +module.exports = castSlice; diff --git a/app/node_modules/lodash/_charsEndIndex.js b/app/node_modules/lodash/_charsEndIndex.js new file mode 100644 index 0000000..07908ff --- /dev/null +++ b/app/node_modules/lodash/_charsEndIndex.js @@ -0,0 +1,19 @@ +var baseIndexOf = require('./_baseIndexOf'); + +/** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ +function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; +} + +module.exports = charsEndIndex; diff --git a/app/node_modules/lodash/_charsStartIndex.js b/app/node_modules/lodash/_charsStartIndex.js new file mode 100644 index 0000000..b17afd2 --- /dev/null +++ b/app/node_modules/lodash/_charsStartIndex.js @@ -0,0 +1,20 @@ +var baseIndexOf = require('./_baseIndexOf'); + +/** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ +function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; +} + +module.exports = charsStartIndex; diff --git a/app/node_modules/lodash/_cloneArrayBuffer.js b/app/node_modules/lodash/_cloneArrayBuffer.js new file mode 100644 index 0000000..c3d8f6e --- /dev/null +++ b/app/node_modules/lodash/_cloneArrayBuffer.js @@ -0,0 +1,16 @@ +var Uint8Array = require('./_Uint8Array'); + +/** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ +function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; +} + +module.exports = cloneArrayBuffer; diff --git a/app/node_modules/lodash/_cloneBuffer.js b/app/node_modules/lodash/_cloneBuffer.js new file mode 100644 index 0000000..27c4810 --- /dev/null +++ b/app/node_modules/lodash/_cloneBuffer.js @@ -0,0 +1,35 @@ +var root = require('./_root'); + +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; + +/** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ +function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; +} + +module.exports = cloneBuffer; diff --git a/app/node_modules/lodash/_cloneDataView.js b/app/node_modules/lodash/_cloneDataView.js new file mode 100644 index 0000000..9c9b7b0 --- /dev/null +++ b/app/node_modules/lodash/_cloneDataView.js @@ -0,0 +1,16 @@ +var cloneArrayBuffer = require('./_cloneArrayBuffer'); + +/** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ +function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); +} + +module.exports = cloneDataView; diff --git a/app/node_modules/lodash/_cloneRegExp.js b/app/node_modules/lodash/_cloneRegExp.js new file mode 100644 index 0000000..64a30df --- /dev/null +++ b/app/node_modules/lodash/_cloneRegExp.js @@ -0,0 +1,17 @@ +/** Used to match `RegExp` flags from their coerced string values. */ +var reFlags = /\w*$/; + +/** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ +function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; +} + +module.exports = cloneRegExp; diff --git a/app/node_modules/lodash/_cloneSymbol.js b/app/node_modules/lodash/_cloneSymbol.js new file mode 100644 index 0000000..bede39f --- /dev/null +++ b/app/node_modules/lodash/_cloneSymbol.js @@ -0,0 +1,18 @@ +var Symbol = require('./_Symbol'); + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + +/** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ +function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; +} + +module.exports = cloneSymbol; diff --git a/app/node_modules/lodash/_cloneTypedArray.js b/app/node_modules/lodash/_cloneTypedArray.js new file mode 100644 index 0000000..7aad84d --- /dev/null +++ b/app/node_modules/lodash/_cloneTypedArray.js @@ -0,0 +1,16 @@ +var cloneArrayBuffer = require('./_cloneArrayBuffer'); + +/** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ +function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); +} + +module.exports = cloneTypedArray; diff --git a/app/node_modules/lodash/_compareAscending.js b/app/node_modules/lodash/_compareAscending.js new file mode 100644 index 0000000..8dc2791 --- /dev/null +++ b/app/node_modules/lodash/_compareAscending.js @@ -0,0 +1,41 @@ +var isSymbol = require('./isSymbol'); + +/** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ +function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; +} + +module.exports = compareAscending; diff --git a/app/node_modules/lodash/_compareMultiple.js b/app/node_modules/lodash/_compareMultiple.js new file mode 100644 index 0000000..ad61f0f --- /dev/null +++ b/app/node_modules/lodash/_compareMultiple.js @@ -0,0 +1,44 @@ +var compareAscending = require('./_compareAscending'); + +/** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ +function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; +} + +module.exports = compareMultiple; diff --git a/app/node_modules/lodash/_composeArgs.js b/app/node_modules/lodash/_composeArgs.js new file mode 100644 index 0000000..1ce40f4 --- /dev/null +++ b/app/node_modules/lodash/_composeArgs.js @@ -0,0 +1,39 @@ +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ +function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; +} + +module.exports = composeArgs; diff --git a/app/node_modules/lodash/_composeArgsRight.js b/app/node_modules/lodash/_composeArgsRight.js new file mode 100644 index 0000000..8dc588d --- /dev/null +++ b/app/node_modules/lodash/_composeArgsRight.js @@ -0,0 +1,41 @@ +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ +function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; +} + +module.exports = composeArgsRight; diff --git a/app/node_modules/lodash/_copyArray.js b/app/node_modules/lodash/_copyArray.js new file mode 100644 index 0000000..cd94d5d --- /dev/null +++ b/app/node_modules/lodash/_copyArray.js @@ -0,0 +1,20 @@ +/** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ +function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; +} + +module.exports = copyArray; diff --git a/app/node_modules/lodash/_copyObject.js b/app/node_modules/lodash/_copyObject.js new file mode 100644 index 0000000..2f2a5c2 --- /dev/null +++ b/app/node_modules/lodash/_copyObject.js @@ -0,0 +1,40 @@ +var assignValue = require('./_assignValue'), + baseAssignValue = require('./_baseAssignValue'); + +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; +} + +module.exports = copyObject; diff --git a/app/node_modules/lodash/_copySymbols.js b/app/node_modules/lodash/_copySymbols.js new file mode 100644 index 0000000..c35944a --- /dev/null +++ b/app/node_modules/lodash/_copySymbols.js @@ -0,0 +1,16 @@ +var copyObject = require('./_copyObject'), + getSymbols = require('./_getSymbols'); + +/** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ +function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); +} + +module.exports = copySymbols; diff --git a/app/node_modules/lodash/_copySymbolsIn.js b/app/node_modules/lodash/_copySymbolsIn.js new file mode 100644 index 0000000..fdf20a7 --- /dev/null +++ b/app/node_modules/lodash/_copySymbolsIn.js @@ -0,0 +1,16 @@ +var copyObject = require('./_copyObject'), + getSymbolsIn = require('./_getSymbolsIn'); + +/** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ +function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); +} + +module.exports = copySymbolsIn; diff --git a/app/node_modules/lodash/_coreJsData.js b/app/node_modules/lodash/_coreJsData.js new file mode 100644 index 0000000..f8e5b4e --- /dev/null +++ b/app/node_modules/lodash/_coreJsData.js @@ -0,0 +1,6 @@ +var root = require('./_root'); + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +module.exports = coreJsData; diff --git a/app/node_modules/lodash/_countHolders.js b/app/node_modules/lodash/_countHolders.js new file mode 100644 index 0000000..718fcda --- /dev/null +++ b/app/node_modules/lodash/_countHolders.js @@ -0,0 +1,21 @@ +/** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ +function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; +} + +module.exports = countHolders; diff --git a/app/node_modules/lodash/_createAggregator.js b/app/node_modules/lodash/_createAggregator.js new file mode 100644 index 0000000..0be42c4 --- /dev/null +++ b/app/node_modules/lodash/_createAggregator.js @@ -0,0 +1,23 @@ +var arrayAggregator = require('./_arrayAggregator'), + baseAggregator = require('./_baseAggregator'), + baseIteratee = require('./_baseIteratee'), + isArray = require('./isArray'); + +/** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ +function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, baseIteratee(iteratee, 2), accumulator); + }; +} + +module.exports = createAggregator; diff --git a/app/node_modules/lodash/_createAssigner.js b/app/node_modules/lodash/_createAssigner.js new file mode 100644 index 0000000..1f904c5 --- /dev/null +++ b/app/node_modules/lodash/_createAssigner.js @@ -0,0 +1,37 @@ +var baseRest = require('./_baseRest'), + isIterateeCall = require('./_isIterateeCall'); + +/** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ +function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); +} + +module.exports = createAssigner; diff --git a/app/node_modules/lodash/_createBaseEach.js b/app/node_modules/lodash/_createBaseEach.js new file mode 100644 index 0000000..d24fdd1 --- /dev/null +++ b/app/node_modules/lodash/_createBaseEach.js @@ -0,0 +1,32 @@ +var isArrayLike = require('./isArrayLike'); + +/** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; +} + +module.exports = createBaseEach; diff --git a/app/node_modules/lodash/_createBaseFor.js b/app/node_modules/lodash/_createBaseFor.js new file mode 100644 index 0000000..94cbf29 --- /dev/null +++ b/app/node_modules/lodash/_createBaseFor.js @@ -0,0 +1,25 @@ +/** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; +} + +module.exports = createBaseFor; diff --git a/app/node_modules/lodash/_createBind.js b/app/node_modules/lodash/_createBind.js new file mode 100644 index 0000000..07cb99f --- /dev/null +++ b/app/node_modules/lodash/_createBind.js @@ -0,0 +1,28 @@ +var createCtor = require('./_createCtor'), + root = require('./_root'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1; + +/** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; +} + +module.exports = createBind; diff --git a/app/node_modules/lodash/_createCaseFirst.js b/app/node_modules/lodash/_createCaseFirst.js new file mode 100644 index 0000000..fe8ea48 --- /dev/null +++ b/app/node_modules/lodash/_createCaseFirst.js @@ -0,0 +1,33 @@ +var castSlice = require('./_castSlice'), + hasUnicode = require('./_hasUnicode'), + stringToArray = require('./_stringToArray'), + toString = require('./toString'); + +/** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ +function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; +} + +module.exports = createCaseFirst; diff --git a/app/node_modules/lodash/_createCompounder.js b/app/node_modules/lodash/_createCompounder.js new file mode 100644 index 0000000..8d4cee2 --- /dev/null +++ b/app/node_modules/lodash/_createCompounder.js @@ -0,0 +1,24 @@ +var arrayReduce = require('./_arrayReduce'), + deburr = require('./deburr'), + words = require('./words'); + +/** Used to compose unicode capture groups. */ +var rsApos = "['\u2019]"; + +/** Used to match apostrophes. */ +var reApos = RegExp(rsApos, 'g'); + +/** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ +function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; +} + +module.exports = createCompounder; diff --git a/app/node_modules/lodash/_createCtor.js b/app/node_modules/lodash/_createCtor.js new file mode 100644 index 0000000..9047aa5 --- /dev/null +++ b/app/node_modules/lodash/_createCtor.js @@ -0,0 +1,37 @@ +var baseCreate = require('./_baseCreate'), + isObject = require('./isObject'); + +/** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ +function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; +} + +module.exports = createCtor; diff --git a/app/node_modules/lodash/_createCurry.js b/app/node_modules/lodash/_createCurry.js new file mode 100644 index 0000000..f06c2cd --- /dev/null +++ b/app/node_modules/lodash/_createCurry.js @@ -0,0 +1,46 @@ +var apply = require('./_apply'), + createCtor = require('./_createCtor'), + createHybrid = require('./_createHybrid'), + createRecurry = require('./_createRecurry'), + getHolder = require('./_getHolder'), + replaceHolders = require('./_replaceHolders'), + root = require('./_root'); + +/** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; +} + +module.exports = createCurry; diff --git a/app/node_modules/lodash/_createFind.js b/app/node_modules/lodash/_createFind.js new file mode 100644 index 0000000..8859ff8 --- /dev/null +++ b/app/node_modules/lodash/_createFind.js @@ -0,0 +1,25 @@ +var baseIteratee = require('./_baseIteratee'), + isArrayLike = require('./isArrayLike'), + keys = require('./keys'); + +/** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ +function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = baseIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; +} + +module.exports = createFind; diff --git a/app/node_modules/lodash/_createFlow.js b/app/node_modules/lodash/_createFlow.js new file mode 100644 index 0000000..baaddbf --- /dev/null +++ b/app/node_modules/lodash/_createFlow.js @@ -0,0 +1,78 @@ +var LodashWrapper = require('./_LodashWrapper'), + flatRest = require('./_flatRest'), + getData = require('./_getData'), + getFuncName = require('./_getFuncName'), + isArray = require('./isArray'), + isLaziable = require('./_isLaziable'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used to compose bitmasks for function metadata. */ +var WRAP_CURRY_FLAG = 8, + WRAP_PARTIAL_FLAG = 32, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256; + +/** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ +function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); +} + +module.exports = createFlow; diff --git a/app/node_modules/lodash/_createHybrid.js b/app/node_modules/lodash/_createHybrid.js new file mode 100644 index 0000000..b671bd1 --- /dev/null +++ b/app/node_modules/lodash/_createHybrid.js @@ -0,0 +1,92 @@ +var composeArgs = require('./_composeArgs'), + composeArgsRight = require('./_composeArgsRight'), + countHolders = require('./_countHolders'), + createCtor = require('./_createCtor'), + createRecurry = require('./_createRecurry'), + getHolder = require('./_getHolder'), + reorder = require('./_reorder'), + replaceHolders = require('./_replaceHolders'), + root = require('./_root'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_ARY_FLAG = 128, + WRAP_FLIP_FLAG = 512; + +/** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, + isBind = bitmask & WRAP_BIND_FLAG, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG, + isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), + isFlip = bitmask & WRAP_FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; +} + +module.exports = createHybrid; diff --git a/app/node_modules/lodash/_createInverter.js b/app/node_modules/lodash/_createInverter.js new file mode 100644 index 0000000..6c0c562 --- /dev/null +++ b/app/node_modules/lodash/_createInverter.js @@ -0,0 +1,17 @@ +var baseInverter = require('./_baseInverter'); + +/** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ +function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; +} + +module.exports = createInverter; diff --git a/app/node_modules/lodash/_createMathOperation.js b/app/node_modules/lodash/_createMathOperation.js new file mode 100644 index 0000000..f1e238a --- /dev/null +++ b/app/node_modules/lodash/_createMathOperation.js @@ -0,0 +1,38 @@ +var baseToNumber = require('./_baseToNumber'), + baseToString = require('./_baseToString'); + +/** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ +function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; +} + +module.exports = createMathOperation; diff --git a/app/node_modules/lodash/_createOver.js b/app/node_modules/lodash/_createOver.js new file mode 100644 index 0000000..3b94551 --- /dev/null +++ b/app/node_modules/lodash/_createOver.js @@ -0,0 +1,27 @@ +var apply = require('./_apply'), + arrayMap = require('./_arrayMap'), + baseIteratee = require('./_baseIteratee'), + baseRest = require('./_baseRest'), + baseUnary = require('./_baseUnary'), + flatRest = require('./_flatRest'); + +/** + * Creates a function like `_.over`. + * + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. + */ +function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(baseIteratee)); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); +} + +module.exports = createOver; diff --git a/app/node_modules/lodash/_createPadding.js b/app/node_modules/lodash/_createPadding.js new file mode 100644 index 0000000..2124612 --- /dev/null +++ b/app/node_modules/lodash/_createPadding.js @@ -0,0 +1,33 @@ +var baseRepeat = require('./_baseRepeat'), + baseToString = require('./_baseToString'), + castSlice = require('./_castSlice'), + hasUnicode = require('./_hasUnicode'), + stringSize = require('./_stringSize'), + stringToArray = require('./_stringToArray'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeCeil = Math.ceil; + +/** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ +function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); +} + +module.exports = createPadding; diff --git a/app/node_modules/lodash/_createPartial.js b/app/node_modules/lodash/_createPartial.js new file mode 100644 index 0000000..e16c248 --- /dev/null +++ b/app/node_modules/lodash/_createPartial.js @@ -0,0 +1,43 @@ +var apply = require('./_apply'), + createCtor = require('./_createCtor'), + root = require('./_root'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1; + +/** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ +function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; +} + +module.exports = createPartial; diff --git a/app/node_modules/lodash/_createRange.js b/app/node_modules/lodash/_createRange.js new file mode 100644 index 0000000..9f52c77 --- /dev/null +++ b/app/node_modules/lodash/_createRange.js @@ -0,0 +1,30 @@ +var baseRange = require('./_baseRange'), + isIterateeCall = require('./_isIterateeCall'), + toFinite = require('./toFinite'); + +/** + * Creates a `_.range` or `_.rangeRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ +function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; +} + +module.exports = createRange; diff --git a/app/node_modules/lodash/_createRecurry.js b/app/node_modules/lodash/_createRecurry.js new file mode 100644 index 0000000..eb29fb2 --- /dev/null +++ b/app/node_modules/lodash/_createRecurry.js @@ -0,0 +1,56 @@ +var isLaziable = require('./_isLaziable'), + setData = require('./_setData'), + setWrapToString = require('./_setWrapToString'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64; + +/** + * Creates a function that wraps `func` to continue currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); +} + +module.exports = createRecurry; diff --git a/app/node_modules/lodash/_createRelationalOperation.js b/app/node_modules/lodash/_createRelationalOperation.js new file mode 100644 index 0000000..a17c6b5 --- /dev/null +++ b/app/node_modules/lodash/_createRelationalOperation.js @@ -0,0 +1,20 @@ +var toNumber = require('./toNumber'); + +/** + * Creates a function that performs a relational operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. + */ +function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; +} + +module.exports = createRelationalOperation; diff --git a/app/node_modules/lodash/_createRound.js b/app/node_modules/lodash/_createRound.js new file mode 100644 index 0000000..88be5df --- /dev/null +++ b/app/node_modules/lodash/_createRound.js @@ -0,0 +1,35 @@ +var root = require('./_root'), + toInteger = require('./toInteger'), + toNumber = require('./toNumber'), + toString = require('./toString'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = root.isFinite, + nativeMin = Math.min; + +/** + * Creates a function like `_.round`. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ +function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision && nativeIsFinite(number)) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; +} + +module.exports = createRound; diff --git a/app/node_modules/lodash/_createSet.js b/app/node_modules/lodash/_createSet.js new file mode 100644 index 0000000..0f644ee --- /dev/null +++ b/app/node_modules/lodash/_createSet.js @@ -0,0 +1,19 @@ +var Set = require('./_Set'), + noop = require('./noop'), + setToArray = require('./_setToArray'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ +var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); +}; + +module.exports = createSet; diff --git a/app/node_modules/lodash/_createToPairs.js b/app/node_modules/lodash/_createToPairs.js new file mode 100644 index 0000000..568417a --- /dev/null +++ b/app/node_modules/lodash/_createToPairs.js @@ -0,0 +1,30 @@ +var baseToPairs = require('./_baseToPairs'), + getTag = require('./_getTag'), + mapToArray = require('./_mapToArray'), + setToPairs = require('./_setToPairs'); + +/** `Object#toString` result references. */ +var mapTag = '[object Map]', + setTag = '[object Set]'; + +/** + * Creates a `_.toPairs` or `_.toPairsIn` function. + * + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. + */ +function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; +} + +module.exports = createToPairs; diff --git a/app/node_modules/lodash/_createWrap.js b/app/node_modules/lodash/_createWrap.js new file mode 100644 index 0000000..33f0633 --- /dev/null +++ b/app/node_modules/lodash/_createWrap.js @@ -0,0 +1,106 @@ +var baseSetData = require('./_baseSetData'), + createBind = require('./_createBind'), + createCurry = require('./_createCurry'), + createHybrid = require('./_createHybrid'), + createPartial = require('./_createPartial'), + getData = require('./_getData'), + mergeData = require('./_mergeData'), + setData = require('./_setData'), + setWrapToString = require('./_setWrapToString'), + toInteger = require('./toInteger'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); +} + +module.exports = createWrap; diff --git a/app/node_modules/lodash/_customDefaultsAssignIn.js b/app/node_modules/lodash/_customDefaultsAssignIn.js new file mode 100644 index 0000000..1f49e6f --- /dev/null +++ b/app/node_modules/lodash/_customDefaultsAssignIn.js @@ -0,0 +1,29 @@ +var eq = require('./eq'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ +function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; +} + +module.exports = customDefaultsAssignIn; diff --git a/app/node_modules/lodash/_customDefaultsMerge.js b/app/node_modules/lodash/_customDefaultsMerge.js new file mode 100644 index 0000000..4cab317 --- /dev/null +++ b/app/node_modules/lodash/_customDefaultsMerge.js @@ -0,0 +1,28 @@ +var baseMerge = require('./_baseMerge'), + isObject = require('./isObject'); + +/** + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ +function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; +} + +module.exports = customDefaultsMerge; diff --git a/app/node_modules/lodash/_customOmitClone.js b/app/node_modules/lodash/_customOmitClone.js new file mode 100644 index 0000000..968db2e --- /dev/null +++ b/app/node_modules/lodash/_customOmitClone.js @@ -0,0 +1,16 @@ +var isPlainObject = require('./isPlainObject'); + +/** + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. + * + * @private + * @param {*} value The value to inspect. + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. + */ +function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; +} + +module.exports = customOmitClone; diff --git a/app/node_modules/lodash/_deburrLetter.js b/app/node_modules/lodash/_deburrLetter.js new file mode 100644 index 0000000..3e531ed --- /dev/null +++ b/app/node_modules/lodash/_deburrLetter.js @@ -0,0 +1,71 @@ +var basePropertyOf = require('./_basePropertyOf'); + +/** Used to map Latin Unicode letters to basic Latin letters. */ +var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' +}; + +/** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ +var deburrLetter = basePropertyOf(deburredLetters); + +module.exports = deburrLetter; diff --git a/app/node_modules/lodash/_defineProperty.js b/app/node_modules/lodash/_defineProperty.js new file mode 100644 index 0000000..b6116d9 --- /dev/null +++ b/app/node_modules/lodash/_defineProperty.js @@ -0,0 +1,11 @@ +var getNative = require('./_getNative'); + +var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} +}()); + +module.exports = defineProperty; diff --git a/app/node_modules/lodash/_equalArrays.js b/app/node_modules/lodash/_equalArrays.js new file mode 100644 index 0000000..f6a3b7c --- /dev/null +++ b/app/node_modules/lodash/_equalArrays.js @@ -0,0 +1,83 @@ +var SetCache = require('./_SetCache'), + arraySome = require('./_arraySome'), + cacheHas = require('./_cacheHas'); + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ +function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; +} + +module.exports = equalArrays; diff --git a/app/node_modules/lodash/_equalByTag.js b/app/node_modules/lodash/_equalByTag.js new file mode 100644 index 0000000..71919e8 --- /dev/null +++ b/app/node_modules/lodash/_equalByTag.js @@ -0,0 +1,112 @@ +var Symbol = require('./_Symbol'), + Uint8Array = require('./_Uint8Array'), + eq = require('./eq'), + equalArrays = require('./_equalArrays'), + mapToArray = require('./_mapToArray'), + setToArray = require('./_setToArray'); + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + mapTag = '[object Map]', + numberTag = '[object Number]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]'; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; +} + +module.exports = equalByTag; diff --git a/app/node_modules/lodash/_equalObjects.js b/app/node_modules/lodash/_equalObjects.js new file mode 100644 index 0000000..17421f3 --- /dev/null +++ b/app/node_modules/lodash/_equalObjects.js @@ -0,0 +1,89 @@ +var getAllKeys = require('./_getAllKeys'); + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; +} + +module.exports = equalObjects; diff --git a/app/node_modules/lodash/_escapeHtmlChar.js b/app/node_modules/lodash/_escapeHtmlChar.js new file mode 100644 index 0000000..7ca68ee --- /dev/null +++ b/app/node_modules/lodash/_escapeHtmlChar.js @@ -0,0 +1,21 @@ +var basePropertyOf = require('./_basePropertyOf'); + +/** Used to map characters to HTML entities. */ +var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; + +/** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ +var escapeHtmlChar = basePropertyOf(htmlEscapes); + +module.exports = escapeHtmlChar; diff --git a/app/node_modules/lodash/_escapeStringChar.js b/app/node_modules/lodash/_escapeStringChar.js new file mode 100644 index 0000000..44eca96 --- /dev/null +++ b/app/node_modules/lodash/_escapeStringChar.js @@ -0,0 +1,22 @@ +/** Used to escape characters for inclusion in compiled string literals. */ +var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' +}; + +/** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ +function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; +} + +module.exports = escapeStringChar; diff --git a/app/node_modules/lodash/_flatRest.js b/app/node_modules/lodash/_flatRest.js new file mode 100644 index 0000000..94ab6cc --- /dev/null +++ b/app/node_modules/lodash/_flatRest.js @@ -0,0 +1,16 @@ +var flatten = require('./flatten'), + overRest = require('./_overRest'), + setToString = require('./_setToString'); + +/** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ +function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); +} + +module.exports = flatRest; diff --git a/app/node_modules/lodash/_freeGlobal.js b/app/node_modules/lodash/_freeGlobal.js new file mode 100644 index 0000000..bbec998 --- /dev/null +++ b/app/node_modules/lodash/_freeGlobal.js @@ -0,0 +1,4 @@ +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +module.exports = freeGlobal; diff --git a/app/node_modules/lodash/_getAllKeys.js b/app/node_modules/lodash/_getAllKeys.js new file mode 100644 index 0000000..a9ce699 --- /dev/null +++ b/app/node_modules/lodash/_getAllKeys.js @@ -0,0 +1,16 @@ +var baseGetAllKeys = require('./_baseGetAllKeys'), + getSymbols = require('./_getSymbols'), + keys = require('./keys'); + +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); +} + +module.exports = getAllKeys; diff --git a/app/node_modules/lodash/_getAllKeysIn.js b/app/node_modules/lodash/_getAllKeysIn.js new file mode 100644 index 0000000..1b46678 --- /dev/null +++ b/app/node_modules/lodash/_getAllKeysIn.js @@ -0,0 +1,17 @@ +var baseGetAllKeys = require('./_baseGetAllKeys'), + getSymbolsIn = require('./_getSymbolsIn'), + keysIn = require('./keysIn'); + +/** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); +} + +module.exports = getAllKeysIn; diff --git a/app/node_modules/lodash/_getData.js b/app/node_modules/lodash/_getData.js new file mode 100644 index 0000000..a1fe7b7 --- /dev/null +++ b/app/node_modules/lodash/_getData.js @@ -0,0 +1,15 @@ +var metaMap = require('./_metaMap'), + noop = require('./noop'); + +/** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ +var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); +}; + +module.exports = getData; diff --git a/app/node_modules/lodash/_getFuncName.js b/app/node_modules/lodash/_getFuncName.js new file mode 100644 index 0000000..21e15b3 --- /dev/null +++ b/app/node_modules/lodash/_getFuncName.js @@ -0,0 +1,31 @@ +var realNames = require('./_realNames'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ +function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; +} + +module.exports = getFuncName; diff --git a/app/node_modules/lodash/_getHolder.js b/app/node_modules/lodash/_getHolder.js new file mode 100644 index 0000000..65e94b5 --- /dev/null +++ b/app/node_modules/lodash/_getHolder.js @@ -0,0 +1,13 @@ +/** + * Gets the argument placeholder value for `func`. + * + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. + */ +function getHolder(func) { + var object = func; + return object.placeholder; +} + +module.exports = getHolder; diff --git a/app/node_modules/lodash/_getMapData.js b/app/node_modules/lodash/_getMapData.js new file mode 100644 index 0000000..17f6303 --- /dev/null +++ b/app/node_modules/lodash/_getMapData.js @@ -0,0 +1,18 @@ +var isKeyable = require('./_isKeyable'); + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +module.exports = getMapData; diff --git a/app/node_modules/lodash/_getMatchData.js b/app/node_modules/lodash/_getMatchData.js new file mode 100644 index 0000000..2cc70f9 --- /dev/null +++ b/app/node_modules/lodash/_getMatchData.js @@ -0,0 +1,24 @@ +var isStrictComparable = require('./_isStrictComparable'), + keys = require('./keys'); + +/** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ +function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; +} + +module.exports = getMatchData; diff --git a/app/node_modules/lodash/_getNative.js b/app/node_modules/lodash/_getNative.js new file mode 100644 index 0000000..97a622b --- /dev/null +++ b/app/node_modules/lodash/_getNative.js @@ -0,0 +1,17 @@ +var baseIsNative = require('./_baseIsNative'), + getValue = require('./_getValue'); + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} + +module.exports = getNative; diff --git a/app/node_modules/lodash/_getPrototype.js b/app/node_modules/lodash/_getPrototype.js new file mode 100644 index 0000000..e808612 --- /dev/null +++ b/app/node_modules/lodash/_getPrototype.js @@ -0,0 +1,6 @@ +var overArg = require('./_overArg'); + +/** Built-in value references. */ +var getPrototype = overArg(Object.getPrototypeOf, Object); + +module.exports = getPrototype; diff --git a/app/node_modules/lodash/_getRawTag.js b/app/node_modules/lodash/_getRawTag.js new file mode 100644 index 0000000..49a95c9 --- /dev/null +++ b/app/node_modules/lodash/_getRawTag.js @@ -0,0 +1,46 @@ +var Symbol = require('./_Symbol'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** Built-in value references. */ +var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; +} + +module.exports = getRawTag; diff --git a/app/node_modules/lodash/_getSymbols.js b/app/node_modules/lodash/_getSymbols.js new file mode 100644 index 0000000..7d6eafe --- /dev/null +++ b/app/node_modules/lodash/_getSymbols.js @@ -0,0 +1,30 @@ +var arrayFilter = require('./_arrayFilter'), + stubArray = require('./stubArray'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols; + +/** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); +}; + +module.exports = getSymbols; diff --git a/app/node_modules/lodash/_getSymbolsIn.js b/app/node_modules/lodash/_getSymbolsIn.js new file mode 100644 index 0000000..cec0855 --- /dev/null +++ b/app/node_modules/lodash/_getSymbolsIn.js @@ -0,0 +1,25 @@ +var arrayPush = require('./_arrayPush'), + getPrototype = require('./_getPrototype'), + getSymbols = require('./_getSymbols'), + stubArray = require('./stubArray'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols; + +/** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; +}; + +module.exports = getSymbolsIn; diff --git a/app/node_modules/lodash/_getTag.js b/app/node_modules/lodash/_getTag.js new file mode 100644 index 0000000..deaf89d --- /dev/null +++ b/app/node_modules/lodash/_getTag.js @@ -0,0 +1,58 @@ +var DataView = require('./_DataView'), + Map = require('./_Map'), + Promise = require('./_Promise'), + Set = require('./_Set'), + WeakMap = require('./_WeakMap'), + baseGetTag = require('./_baseGetTag'), + toSource = require('./_toSource'); + +/** `Object#toString` result references. */ +var mapTag = '[object Map]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + setTag = '[object Set]', + weakMapTag = '[object WeakMap]'; + +var dataViewTag = '[object DataView]'; + +/** Used to detect maps, sets, and weakmaps. */ +var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +var getTag = baseGetTag; + +// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. +if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; +} + +module.exports = getTag; diff --git a/app/node_modules/lodash/_getValue.js b/app/node_modules/lodash/_getValue.js new file mode 100644 index 0000000..5f7d773 --- /dev/null +++ b/app/node_modules/lodash/_getValue.js @@ -0,0 +1,13 @@ +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +module.exports = getValue; diff --git a/app/node_modules/lodash/_getView.js b/app/node_modules/lodash/_getView.js new file mode 100644 index 0000000..df1e5d4 --- /dev/null +++ b/app/node_modules/lodash/_getView.js @@ -0,0 +1,33 @@ +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ +function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; +} + +module.exports = getView; diff --git a/app/node_modules/lodash/_getWrapDetails.js b/app/node_modules/lodash/_getWrapDetails.js new file mode 100644 index 0000000..3bcc6e4 --- /dev/null +++ b/app/node_modules/lodash/_getWrapDetails.js @@ -0,0 +1,17 @@ +/** Used to match wrap detail comments. */ +var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + +/** + * Extracts wrapper details from the `source` body comment. + * + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. + */ +function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; +} + +module.exports = getWrapDetails; diff --git a/app/node_modules/lodash/_hasPath.js b/app/node_modules/lodash/_hasPath.js new file mode 100644 index 0000000..93dbde1 --- /dev/null +++ b/app/node_modules/lodash/_hasPath.js @@ -0,0 +1,39 @@ +var castPath = require('./_castPath'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isIndex = require('./_isIndex'), + isLength = require('./isLength'), + toKey = require('./_toKey'); + +/** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ +function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); +} + +module.exports = hasPath; diff --git a/app/node_modules/lodash/_hasUnicode.js b/app/node_modules/lodash/_hasUnicode.js new file mode 100644 index 0000000..cb6ca15 --- /dev/null +++ b/app/node_modules/lodash/_hasUnicode.js @@ -0,0 +1,26 @@ +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsVarRange = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsZWJ = '\\u200d'; + +/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ +var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + +/** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ +function hasUnicode(string) { + return reHasUnicode.test(string); +} + +module.exports = hasUnicode; diff --git a/app/node_modules/lodash/_hasUnicodeWord.js b/app/node_modules/lodash/_hasUnicodeWord.js new file mode 100644 index 0000000..95d52c4 --- /dev/null +++ b/app/node_modules/lodash/_hasUnicodeWord.js @@ -0,0 +1,15 @@ +/** Used to detect strings that need a more robust regexp to match words. */ +var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + +/** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ +function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); +} + +module.exports = hasUnicodeWord; diff --git a/app/node_modules/lodash/_hashClear.js b/app/node_modules/lodash/_hashClear.js new file mode 100644 index 0000000..5d4b70c --- /dev/null +++ b/app/node_modules/lodash/_hashClear.js @@ -0,0 +1,15 @@ +var nativeCreate = require('./_nativeCreate'); + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; +} + +module.exports = hashClear; diff --git a/app/node_modules/lodash/_hashDelete.js b/app/node_modules/lodash/_hashDelete.js new file mode 100644 index 0000000..ea9dabf --- /dev/null +++ b/app/node_modules/lodash/_hashDelete.js @@ -0,0 +1,17 @@ +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} + +module.exports = hashDelete; diff --git a/app/node_modules/lodash/_hashGet.js b/app/node_modules/lodash/_hashGet.js new file mode 100644 index 0000000..1fc2f34 --- /dev/null +++ b/app/node_modules/lodash/_hashGet.js @@ -0,0 +1,30 @@ +var nativeCreate = require('./_nativeCreate'); + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} + +module.exports = hashGet; diff --git a/app/node_modules/lodash/_hashHas.js b/app/node_modules/lodash/_hashHas.js new file mode 100644 index 0000000..281a551 --- /dev/null +++ b/app/node_modules/lodash/_hashHas.js @@ -0,0 +1,23 @@ +var nativeCreate = require('./_nativeCreate'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); +} + +module.exports = hashHas; diff --git a/app/node_modules/lodash/_hashSet.js b/app/node_modules/lodash/_hashSet.js new file mode 100644 index 0000000..e105528 --- /dev/null +++ b/app/node_modules/lodash/_hashSet.js @@ -0,0 +1,23 @@ +var nativeCreate = require('./_nativeCreate'); + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} + +module.exports = hashSet; diff --git a/app/node_modules/lodash/_initCloneArray.js b/app/node_modules/lodash/_initCloneArray.js new file mode 100644 index 0000000..078c15a --- /dev/null +++ b/app/node_modules/lodash/_initCloneArray.js @@ -0,0 +1,26 @@ +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ +function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; +} + +module.exports = initCloneArray; diff --git a/app/node_modules/lodash/_initCloneByTag.js b/app/node_modules/lodash/_initCloneByTag.js new file mode 100644 index 0000000..f69a008 --- /dev/null +++ b/app/node_modules/lodash/_initCloneByTag.js @@ -0,0 +1,77 @@ +var cloneArrayBuffer = require('./_cloneArrayBuffer'), + cloneDataView = require('./_cloneDataView'), + cloneRegExp = require('./_cloneRegExp'), + cloneSymbol = require('./_cloneSymbol'), + cloneTypedArray = require('./_cloneTypedArray'); + +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]', + dateTag = '[object Date]', + mapTag = '[object Map]', + numberTag = '[object Number]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return new Ctor; + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return new Ctor; + + case symbolTag: + return cloneSymbol(object); + } +} + +module.exports = initCloneByTag; diff --git a/app/node_modules/lodash/_initCloneObject.js b/app/node_modules/lodash/_initCloneObject.js new file mode 100644 index 0000000..5a13e64 --- /dev/null +++ b/app/node_modules/lodash/_initCloneObject.js @@ -0,0 +1,18 @@ +var baseCreate = require('./_baseCreate'), + getPrototype = require('./_getPrototype'), + isPrototype = require('./_isPrototype'); + +/** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; +} + +module.exports = initCloneObject; diff --git a/app/node_modules/lodash/_insertWrapDetails.js b/app/node_modules/lodash/_insertWrapDetails.js new file mode 100644 index 0000000..e790808 --- /dev/null +++ b/app/node_modules/lodash/_insertWrapDetails.js @@ -0,0 +1,23 @@ +/** Used to match wrap detail comments. */ +var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; + +/** + * Inserts wrapper `details` in a comment at the top of the `source` body. + * + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. + */ +function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); +} + +module.exports = insertWrapDetails; diff --git a/app/node_modules/lodash/_isFlattenable.js b/app/node_modules/lodash/_isFlattenable.js new file mode 100644 index 0000000..4cc2c24 --- /dev/null +++ b/app/node_modules/lodash/_isFlattenable.js @@ -0,0 +1,20 @@ +var Symbol = require('./_Symbol'), + isArguments = require('./isArguments'), + isArray = require('./isArray'); + +/** Built-in value references. */ +var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ +function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); +} + +module.exports = isFlattenable; diff --git a/app/node_modules/lodash/_isIndex.js b/app/node_modules/lodash/_isIndex.js new file mode 100644 index 0000000..061cd39 --- /dev/null +++ b/app/node_modules/lodash/_isIndex.js @@ -0,0 +1,25 @@ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); +} + +module.exports = isIndex; diff --git a/app/node_modules/lodash/_isIterateeCall.js b/app/node_modules/lodash/_isIterateeCall.js new file mode 100644 index 0000000..a0bb5a9 --- /dev/null +++ b/app/node_modules/lodash/_isIterateeCall.js @@ -0,0 +1,30 @@ +var eq = require('./eq'), + isArrayLike = require('./isArrayLike'), + isIndex = require('./_isIndex'), + isObject = require('./isObject'); + +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; +} + +module.exports = isIterateeCall; diff --git a/app/node_modules/lodash/_isKey.js b/app/node_modules/lodash/_isKey.js new file mode 100644 index 0000000..ff08b06 --- /dev/null +++ b/app/node_modules/lodash/_isKey.js @@ -0,0 +1,29 @@ +var isArray = require('./isArray'), + isSymbol = require('./isSymbol'); + +/** Used to match property names within property paths. */ +var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; + +/** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ +function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +} + +module.exports = isKey; diff --git a/app/node_modules/lodash/_isKeyable.js b/app/node_modules/lodash/_isKeyable.js new file mode 100644 index 0000000..39f1828 --- /dev/null +++ b/app/node_modules/lodash/_isKeyable.js @@ -0,0 +1,15 @@ +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +module.exports = isKeyable; diff --git a/app/node_modules/lodash/_isLaziable.js b/app/node_modules/lodash/_isLaziable.js new file mode 100644 index 0000000..a57c4f2 --- /dev/null +++ b/app/node_modules/lodash/_isLaziable.js @@ -0,0 +1,28 @@ +var LazyWrapper = require('./_LazyWrapper'), + getData = require('./_getData'), + getFuncName = require('./_getFuncName'), + lodash = require('./wrapperLodash'); + +/** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. + */ +function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; +} + +module.exports = isLaziable; diff --git a/app/node_modules/lodash/_isMaskable.js b/app/node_modules/lodash/_isMaskable.js new file mode 100644 index 0000000..eb98d09 --- /dev/null +++ b/app/node_modules/lodash/_isMaskable.js @@ -0,0 +1,14 @@ +var coreJsData = require('./_coreJsData'), + isFunction = require('./isFunction'), + stubFalse = require('./stubFalse'); + +/** + * Checks if `func` is capable of being masked. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ +var isMaskable = coreJsData ? isFunction : stubFalse; + +module.exports = isMaskable; diff --git a/app/node_modules/lodash/_isMasked.js b/app/node_modules/lodash/_isMasked.js new file mode 100644 index 0000000..4b0f21b --- /dev/null +++ b/app/node_modules/lodash/_isMasked.js @@ -0,0 +1,20 @@ +var coreJsData = require('./_coreJsData'); + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +module.exports = isMasked; diff --git a/app/node_modules/lodash/_isPrototype.js b/app/node_modules/lodash/_isPrototype.js new file mode 100644 index 0000000..0f29498 --- /dev/null +++ b/app/node_modules/lodash/_isPrototype.js @@ -0,0 +1,18 @@ +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +module.exports = isPrototype; diff --git a/app/node_modules/lodash/_isStrictComparable.js b/app/node_modules/lodash/_isStrictComparable.js new file mode 100644 index 0000000..b59f40b --- /dev/null +++ b/app/node_modules/lodash/_isStrictComparable.js @@ -0,0 +1,15 @@ +var isObject = require('./isObject'); + +/** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ +function isStrictComparable(value) { + return value === value && !isObject(value); +} + +module.exports = isStrictComparable; diff --git a/app/node_modules/lodash/_iteratorToArray.js b/app/node_modules/lodash/_iteratorToArray.js new file mode 100644 index 0000000..4768566 --- /dev/null +++ b/app/node_modules/lodash/_iteratorToArray.js @@ -0,0 +1,18 @@ +/** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ +function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; +} + +module.exports = iteratorToArray; diff --git a/app/node_modules/lodash/_lazyClone.js b/app/node_modules/lodash/_lazyClone.js new file mode 100644 index 0000000..d8a51f8 --- /dev/null +++ b/app/node_modules/lodash/_lazyClone.js @@ -0,0 +1,23 @@ +var LazyWrapper = require('./_LazyWrapper'), + copyArray = require('./_copyArray'); + +/** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ +function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; +} + +module.exports = lazyClone; diff --git a/app/node_modules/lodash/_lazyReverse.js b/app/node_modules/lodash/_lazyReverse.js new file mode 100644 index 0000000..c5b5219 --- /dev/null +++ b/app/node_modules/lodash/_lazyReverse.js @@ -0,0 +1,23 @@ +var LazyWrapper = require('./_LazyWrapper'); + +/** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ +function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; +} + +module.exports = lazyReverse; diff --git a/app/node_modules/lodash/_lazyValue.js b/app/node_modules/lodash/_lazyValue.js new file mode 100644 index 0000000..371ca8d --- /dev/null +++ b/app/node_modules/lodash/_lazyValue.js @@ -0,0 +1,69 @@ +var baseWrapperValue = require('./_baseWrapperValue'), + getView = require('./_getView'), + isArray = require('./isArray'); + +/** Used to indicate the type of lazy iteratees. */ +var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin = Math.min; + +/** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ +function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; +} + +module.exports = lazyValue; diff --git a/app/node_modules/lodash/_listCacheClear.js b/app/node_modules/lodash/_listCacheClear.js new file mode 100644 index 0000000..acbe39a --- /dev/null +++ b/app/node_modules/lodash/_listCacheClear.js @@ -0,0 +1,13 @@ +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; +} + +module.exports = listCacheClear; diff --git a/app/node_modules/lodash/_listCacheDelete.js b/app/node_modules/lodash/_listCacheDelete.js new file mode 100644 index 0000000..b1384ad --- /dev/null +++ b/app/node_modules/lodash/_listCacheDelete.js @@ -0,0 +1,35 @@ +var assocIndexOf = require('./_assocIndexOf'); + +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/** Built-in value references. */ +var splice = arrayProto.splice; + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; +} + +module.exports = listCacheDelete; diff --git a/app/node_modules/lodash/_listCacheGet.js b/app/node_modules/lodash/_listCacheGet.js new file mode 100644 index 0000000..f8192fc --- /dev/null +++ b/app/node_modules/lodash/_listCacheGet.js @@ -0,0 +1,19 @@ +var assocIndexOf = require('./_assocIndexOf'); + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +module.exports = listCacheGet; diff --git a/app/node_modules/lodash/_listCacheHas.js b/app/node_modules/lodash/_listCacheHas.js new file mode 100644 index 0000000..2adf671 --- /dev/null +++ b/app/node_modules/lodash/_listCacheHas.js @@ -0,0 +1,16 @@ +var assocIndexOf = require('./_assocIndexOf'); + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} + +module.exports = listCacheHas; diff --git a/app/node_modules/lodash/_listCacheSet.js b/app/node_modules/lodash/_listCacheSet.js new file mode 100644 index 0000000..5855c95 --- /dev/null +++ b/app/node_modules/lodash/_listCacheSet.js @@ -0,0 +1,26 @@ +var assocIndexOf = require('./_assocIndexOf'); + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +module.exports = listCacheSet; diff --git a/app/node_modules/lodash/_mapCacheClear.js b/app/node_modules/lodash/_mapCacheClear.js new file mode 100644 index 0000000..bc9ca20 --- /dev/null +++ b/app/node_modules/lodash/_mapCacheClear.js @@ -0,0 +1,21 @@ +var Hash = require('./_Hash'), + ListCache = require('./_ListCache'), + Map = require('./_Map'); + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; +} + +module.exports = mapCacheClear; diff --git a/app/node_modules/lodash/_mapCacheDelete.js b/app/node_modules/lodash/_mapCacheDelete.js new file mode 100644 index 0000000..946ca3c --- /dev/null +++ b/app/node_modules/lodash/_mapCacheDelete.js @@ -0,0 +1,18 @@ +var getMapData = require('./_getMapData'); + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} + +module.exports = mapCacheDelete; diff --git a/app/node_modules/lodash/_mapCacheGet.js b/app/node_modules/lodash/_mapCacheGet.js new file mode 100644 index 0000000..f29f55c --- /dev/null +++ b/app/node_modules/lodash/_mapCacheGet.js @@ -0,0 +1,16 @@ +var getMapData = require('./_getMapData'); + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +module.exports = mapCacheGet; diff --git a/app/node_modules/lodash/_mapCacheHas.js b/app/node_modules/lodash/_mapCacheHas.js new file mode 100644 index 0000000..a1214c0 --- /dev/null +++ b/app/node_modules/lodash/_mapCacheHas.js @@ -0,0 +1,16 @@ +var getMapData = require('./_getMapData'); + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +module.exports = mapCacheHas; diff --git a/app/node_modules/lodash/_mapCacheSet.js b/app/node_modules/lodash/_mapCacheSet.js new file mode 100644 index 0000000..7346849 --- /dev/null +++ b/app/node_modules/lodash/_mapCacheSet.js @@ -0,0 +1,22 @@ +var getMapData = require('./_getMapData'); + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; +} + +module.exports = mapCacheSet; diff --git a/app/node_modules/lodash/_mapToArray.js b/app/node_modules/lodash/_mapToArray.js new file mode 100644 index 0000000..fe3dd53 --- /dev/null +++ b/app/node_modules/lodash/_mapToArray.js @@ -0,0 +1,18 @@ +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; +} + +module.exports = mapToArray; diff --git a/app/node_modules/lodash/_matchesStrictComparable.js b/app/node_modules/lodash/_matchesStrictComparable.js new file mode 100644 index 0000000..f608af9 --- /dev/null +++ b/app/node_modules/lodash/_matchesStrictComparable.js @@ -0,0 +1,20 @@ +/** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; +} + +module.exports = matchesStrictComparable; diff --git a/app/node_modules/lodash/_memoizeCapped.js b/app/node_modules/lodash/_memoizeCapped.js new file mode 100644 index 0000000..7f71c8f --- /dev/null +++ b/app/node_modules/lodash/_memoizeCapped.js @@ -0,0 +1,26 @@ +var memoize = require('./memoize'); + +/** Used as the maximum memoize cache size. */ +var MAX_MEMOIZE_SIZE = 500; + +/** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ +function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; +} + +module.exports = memoizeCapped; diff --git a/app/node_modules/lodash/_mergeData.js b/app/node_modules/lodash/_mergeData.js new file mode 100644 index 0000000..cb570f9 --- /dev/null +++ b/app/node_modules/lodash/_mergeData.js @@ -0,0 +1,90 @@ +var composeArgs = require('./_composeArgs'), + composeArgsRight = require('./_composeArgsRight'), + replaceHolders = require('./_replaceHolders'); + +/** Used as the internal argument placeholder. */ +var PLACEHOLDER = '__lodash_placeholder__'; + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin = Math.min; + +/** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ +function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; +} + +module.exports = mergeData; diff --git a/app/node_modules/lodash/_metaMap.js b/app/node_modules/lodash/_metaMap.js new file mode 100644 index 0000000..0157a0b --- /dev/null +++ b/app/node_modules/lodash/_metaMap.js @@ -0,0 +1,6 @@ +var WeakMap = require('./_WeakMap'); + +/** Used to store function metadata. */ +var metaMap = WeakMap && new WeakMap; + +module.exports = metaMap; diff --git a/app/node_modules/lodash/_nativeCreate.js b/app/node_modules/lodash/_nativeCreate.js new file mode 100644 index 0000000..c7aede8 --- /dev/null +++ b/app/node_modules/lodash/_nativeCreate.js @@ -0,0 +1,6 @@ +var getNative = require('./_getNative'); + +/* Built-in method references that are verified to be native. */ +var nativeCreate = getNative(Object, 'create'); + +module.exports = nativeCreate; diff --git a/app/node_modules/lodash/_nativeKeys.js b/app/node_modules/lodash/_nativeKeys.js new file mode 100644 index 0000000..479a104 --- /dev/null +++ b/app/node_modules/lodash/_nativeKeys.js @@ -0,0 +1,6 @@ +var overArg = require('./_overArg'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object); + +module.exports = nativeKeys; diff --git a/app/node_modules/lodash/_nativeKeysIn.js b/app/node_modules/lodash/_nativeKeysIn.js new file mode 100644 index 0000000..00ee505 --- /dev/null +++ b/app/node_modules/lodash/_nativeKeysIn.js @@ -0,0 +1,20 @@ +/** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; +} + +module.exports = nativeKeysIn; diff --git a/app/node_modules/lodash/_nodeUtil.js b/app/node_modules/lodash/_nodeUtil.js new file mode 100644 index 0000000..983d78f --- /dev/null +++ b/app/node_modules/lodash/_nodeUtil.js @@ -0,0 +1,30 @@ +var freeGlobal = require('./_freeGlobal'); + +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports && freeGlobal.process; + +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} +}()); + +module.exports = nodeUtil; diff --git a/app/node_modules/lodash/_objectToString.js b/app/node_modules/lodash/_objectToString.js new file mode 100644 index 0000000..c614ec0 --- /dev/null +++ b/app/node_modules/lodash/_objectToString.js @@ -0,0 +1,22 @@ +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString.call(value); +} + +module.exports = objectToString; diff --git a/app/node_modules/lodash/_overArg.js b/app/node_modules/lodash/_overArg.js new file mode 100644 index 0000000..651c5c5 --- /dev/null +++ b/app/node_modules/lodash/_overArg.js @@ -0,0 +1,15 @@ +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +module.exports = overArg; diff --git a/app/node_modules/lodash/_overRest.js b/app/node_modules/lodash/_overRest.js new file mode 100644 index 0000000..c7cdef3 --- /dev/null +++ b/app/node_modules/lodash/_overRest.js @@ -0,0 +1,36 @@ +var apply = require('./_apply'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ +function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; +} + +module.exports = overRest; diff --git a/app/node_modules/lodash/_parent.js b/app/node_modules/lodash/_parent.js new file mode 100644 index 0000000..f174328 --- /dev/null +++ b/app/node_modules/lodash/_parent.js @@ -0,0 +1,16 @@ +var baseGet = require('./_baseGet'), + baseSlice = require('./_baseSlice'); + +/** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ +function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); +} + +module.exports = parent; diff --git a/app/node_modules/lodash/_reEscape.js b/app/node_modules/lodash/_reEscape.js new file mode 100644 index 0000000..7f47eda --- /dev/null +++ b/app/node_modules/lodash/_reEscape.js @@ -0,0 +1,4 @@ +/** Used to match template delimiters. */ +var reEscape = /<%-([\s\S]+?)%>/g; + +module.exports = reEscape; diff --git a/app/node_modules/lodash/_reEvaluate.js b/app/node_modules/lodash/_reEvaluate.js new file mode 100644 index 0000000..6adfc31 --- /dev/null +++ b/app/node_modules/lodash/_reEvaluate.js @@ -0,0 +1,4 @@ +/** Used to match template delimiters. */ +var reEvaluate = /<%([\s\S]+?)%>/g; + +module.exports = reEvaluate; diff --git a/app/node_modules/lodash/_reInterpolate.js b/app/node_modules/lodash/_reInterpolate.js new file mode 100644 index 0000000..d02ff0b --- /dev/null +++ b/app/node_modules/lodash/_reInterpolate.js @@ -0,0 +1,4 @@ +/** Used to match template delimiters. */ +var reInterpolate = /<%=([\s\S]+?)%>/g; + +module.exports = reInterpolate; diff --git a/app/node_modules/lodash/_realNames.js b/app/node_modules/lodash/_realNames.js new file mode 100644 index 0000000..aa0d529 --- /dev/null +++ b/app/node_modules/lodash/_realNames.js @@ -0,0 +1,4 @@ +/** Used to lookup unminified function names. */ +var realNames = {}; + +module.exports = realNames; diff --git a/app/node_modules/lodash/_reorder.js b/app/node_modules/lodash/_reorder.js new file mode 100644 index 0000000..a3502b0 --- /dev/null +++ b/app/node_modules/lodash/_reorder.js @@ -0,0 +1,29 @@ +var copyArray = require('./_copyArray'), + isIndex = require('./_isIndex'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin = Math.min; + +/** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ +function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; +} + +module.exports = reorder; diff --git a/app/node_modules/lodash/_replaceHolders.js b/app/node_modules/lodash/_replaceHolders.js new file mode 100644 index 0000000..74360ec --- /dev/null +++ b/app/node_modules/lodash/_replaceHolders.js @@ -0,0 +1,29 @@ +/** Used as the internal argument placeholder. */ +var PLACEHOLDER = '__lodash_placeholder__'; + +/** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ +function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; +} + +module.exports = replaceHolders; diff --git a/app/node_modules/lodash/_root.js b/app/node_modules/lodash/_root.js new file mode 100644 index 0000000..d2852be --- /dev/null +++ b/app/node_modules/lodash/_root.js @@ -0,0 +1,9 @@ +var freeGlobal = require('./_freeGlobal'); + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +module.exports = root; diff --git a/app/node_modules/lodash/_safeGet.js b/app/node_modules/lodash/_safeGet.js new file mode 100644 index 0000000..b070897 --- /dev/null +++ b/app/node_modules/lodash/_safeGet.js @@ -0,0 +1,21 @@ +/** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; +} + +module.exports = safeGet; diff --git a/app/node_modules/lodash/_setCacheAdd.js b/app/node_modules/lodash/_setCacheAdd.js new file mode 100644 index 0000000..1081a74 --- /dev/null +++ b/app/node_modules/lodash/_setCacheAdd.js @@ -0,0 +1,19 @@ +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; +} + +module.exports = setCacheAdd; diff --git a/app/node_modules/lodash/_setCacheHas.js b/app/node_modules/lodash/_setCacheHas.js new file mode 100644 index 0000000..9a49255 --- /dev/null +++ b/app/node_modules/lodash/_setCacheHas.js @@ -0,0 +1,14 @@ +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} + +module.exports = setCacheHas; diff --git a/app/node_modules/lodash/_setData.js b/app/node_modules/lodash/_setData.js new file mode 100644 index 0000000..e5cf3eb --- /dev/null +++ b/app/node_modules/lodash/_setData.js @@ -0,0 +1,20 @@ +var baseSetData = require('./_baseSetData'), + shortOut = require('./_shortOut'); + +/** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ +var setData = shortOut(baseSetData); + +module.exports = setData; diff --git a/app/node_modules/lodash/_setToArray.js b/app/node_modules/lodash/_setToArray.js new file mode 100644 index 0000000..b87f074 --- /dev/null +++ b/app/node_modules/lodash/_setToArray.js @@ -0,0 +1,18 @@ +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} + +module.exports = setToArray; diff --git a/app/node_modules/lodash/_setToPairs.js b/app/node_modules/lodash/_setToPairs.js new file mode 100644 index 0000000..36ad37a --- /dev/null +++ b/app/node_modules/lodash/_setToPairs.js @@ -0,0 +1,18 @@ +/** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ +function setToPairs(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; +} + +module.exports = setToPairs; diff --git a/app/node_modules/lodash/_setToString.js b/app/node_modules/lodash/_setToString.js new file mode 100644 index 0000000..6ca8419 --- /dev/null +++ b/app/node_modules/lodash/_setToString.js @@ -0,0 +1,14 @@ +var baseSetToString = require('./_baseSetToString'), + shortOut = require('./_shortOut'); + +/** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var setToString = shortOut(baseSetToString); + +module.exports = setToString; diff --git a/app/node_modules/lodash/_setWrapToString.js b/app/node_modules/lodash/_setWrapToString.js new file mode 100644 index 0000000..decdc44 --- /dev/null +++ b/app/node_modules/lodash/_setWrapToString.js @@ -0,0 +1,21 @@ +var getWrapDetails = require('./_getWrapDetails'), + insertWrapDetails = require('./_insertWrapDetails'), + setToString = require('./_setToString'), + updateWrapDetails = require('./_updateWrapDetails'); + +/** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ +function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); +} + +module.exports = setWrapToString; diff --git a/app/node_modules/lodash/_shortOut.js b/app/node_modules/lodash/_shortOut.js new file mode 100644 index 0000000..3300a07 --- /dev/null +++ b/app/node_modules/lodash/_shortOut.js @@ -0,0 +1,37 @@ +/** Used to detect hot functions by number of calls within a span of milliseconds. */ +var HOT_COUNT = 800, + HOT_SPAN = 16; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeNow = Date.now; + +/** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ +function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; +} + +module.exports = shortOut; diff --git a/app/node_modules/lodash/_shuffleSelf.js b/app/node_modules/lodash/_shuffleSelf.js new file mode 100644 index 0000000..8bcc4f5 --- /dev/null +++ b/app/node_modules/lodash/_shuffleSelf.js @@ -0,0 +1,28 @@ +var baseRandom = require('./_baseRandom'); + +/** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */ +function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; +} + +module.exports = shuffleSelf; diff --git a/app/node_modules/lodash/_stackClear.js b/app/node_modules/lodash/_stackClear.js new file mode 100644 index 0000000..ce8e5a9 --- /dev/null +++ b/app/node_modules/lodash/_stackClear.js @@ -0,0 +1,15 @@ +var ListCache = require('./_ListCache'); + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new ListCache; + this.size = 0; +} + +module.exports = stackClear; diff --git a/app/node_modules/lodash/_stackDelete.js b/app/node_modules/lodash/_stackDelete.js new file mode 100644 index 0000000..ff9887a --- /dev/null +++ b/app/node_modules/lodash/_stackDelete.js @@ -0,0 +1,18 @@ +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; +} + +module.exports = stackDelete; diff --git a/app/node_modules/lodash/_stackGet.js b/app/node_modules/lodash/_stackGet.js new file mode 100644 index 0000000..1cdf004 --- /dev/null +++ b/app/node_modules/lodash/_stackGet.js @@ -0,0 +1,14 @@ +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +module.exports = stackGet; diff --git a/app/node_modules/lodash/_stackHas.js b/app/node_modules/lodash/_stackHas.js new file mode 100644 index 0000000..16a3ad1 --- /dev/null +++ b/app/node_modules/lodash/_stackHas.js @@ -0,0 +1,14 @@ +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +module.exports = stackHas; diff --git a/app/node_modules/lodash/_stackSet.js b/app/node_modules/lodash/_stackSet.js new file mode 100644 index 0000000..b790ac5 --- /dev/null +++ b/app/node_modules/lodash/_stackSet.js @@ -0,0 +1,34 @@ +var ListCache = require('./_ListCache'), + Map = require('./_Map'), + MapCache = require('./_MapCache'); + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; +} + +module.exports = stackSet; diff --git a/app/node_modules/lodash/_strictIndexOf.js b/app/node_modules/lodash/_strictIndexOf.js new file mode 100644 index 0000000..0486a49 --- /dev/null +++ b/app/node_modules/lodash/_strictIndexOf.js @@ -0,0 +1,23 @@ +/** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; +} + +module.exports = strictIndexOf; diff --git a/app/node_modules/lodash/_strictLastIndexOf.js b/app/node_modules/lodash/_strictLastIndexOf.js new file mode 100644 index 0000000..d7310dc --- /dev/null +++ b/app/node_modules/lodash/_strictLastIndexOf.js @@ -0,0 +1,21 @@ +/** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; +} + +module.exports = strictLastIndexOf; diff --git a/app/node_modules/lodash/_stringSize.js b/app/node_modules/lodash/_stringSize.js new file mode 100644 index 0000000..17ef462 --- /dev/null +++ b/app/node_modules/lodash/_stringSize.js @@ -0,0 +1,18 @@ +var asciiSize = require('./_asciiSize'), + hasUnicode = require('./_hasUnicode'), + unicodeSize = require('./_unicodeSize'); + +/** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ +function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); +} + +module.exports = stringSize; diff --git a/app/node_modules/lodash/_stringToArray.js b/app/node_modules/lodash/_stringToArray.js new file mode 100644 index 0000000..d161158 --- /dev/null +++ b/app/node_modules/lodash/_stringToArray.js @@ -0,0 +1,18 @@ +var asciiToArray = require('./_asciiToArray'), + hasUnicode = require('./_hasUnicode'), + unicodeToArray = require('./_unicodeToArray'); + +/** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); +} + +module.exports = stringToArray; diff --git a/app/node_modules/lodash/_stringToPath.js b/app/node_modules/lodash/_stringToPath.js new file mode 100644 index 0000000..8f39f8a --- /dev/null +++ b/app/node_modules/lodash/_stringToPath.js @@ -0,0 +1,27 @@ +var memoizeCapped = require('./_memoizeCapped'); + +/** Used to match property names within property paths. */ +var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + +/** Used to match backslashes in property paths. */ +var reEscapeChar = /\\(\\)?/g; + +/** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ +var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; +}); + +module.exports = stringToPath; diff --git a/app/node_modules/lodash/_toKey.js b/app/node_modules/lodash/_toKey.js new file mode 100644 index 0000000..c6d645c --- /dev/null +++ b/app/node_modules/lodash/_toKey.js @@ -0,0 +1,21 @@ +var isSymbol = require('./isSymbol'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ +function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +module.exports = toKey; diff --git a/app/node_modules/lodash/_toSource.js b/app/node_modules/lodash/_toSource.js new file mode 100644 index 0000000..a020b38 --- /dev/null +++ b/app/node_modules/lodash/_toSource.js @@ -0,0 +1,26 @@ +/** Used for built-in method references. */ +var funcProto = Function.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +module.exports = toSource; diff --git a/app/node_modules/lodash/_unescapeHtmlChar.js b/app/node_modules/lodash/_unescapeHtmlChar.js new file mode 100644 index 0000000..a71fecb --- /dev/null +++ b/app/node_modules/lodash/_unescapeHtmlChar.js @@ -0,0 +1,21 @@ +var basePropertyOf = require('./_basePropertyOf'); + +/** Used to map HTML entities to characters. */ +var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" +}; + +/** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ +var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + +module.exports = unescapeHtmlChar; diff --git a/app/node_modules/lodash/_unicodeSize.js b/app/node_modules/lodash/_unicodeSize.js new file mode 100644 index 0000000..68137ec --- /dev/null +++ b/app/node_modules/lodash/_unicodeSize.js @@ -0,0 +1,44 @@ +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsVarRange = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsAstral = '[' + rsAstralRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsZWJ = '\\u200d'; + +/** Used to compose unicode regexes. */ +var reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + +/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ +var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + +/** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ +function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; +} + +module.exports = unicodeSize; diff --git a/app/node_modules/lodash/_unicodeToArray.js b/app/node_modules/lodash/_unicodeToArray.js new file mode 100644 index 0000000..2a725c0 --- /dev/null +++ b/app/node_modules/lodash/_unicodeToArray.js @@ -0,0 +1,40 @@ +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsVarRange = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsAstral = '[' + rsAstralRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsZWJ = '\\u200d'; + +/** Used to compose unicode regexes. */ +var reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + +/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ +var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + +/** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function unicodeToArray(string) { + return string.match(reUnicode) || []; +} + +module.exports = unicodeToArray; diff --git a/app/node_modules/lodash/_unicodeWords.js b/app/node_modules/lodash/_unicodeWords.js new file mode 100644 index 0000000..e72e6e0 --- /dev/null +++ b/app/node_modules/lodash/_unicodeWords.js @@ -0,0 +1,69 @@ +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + +/** Used to compose unicode capture groups. */ +var rsApos = "['\u2019]", + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + +/** Used to compose unicode regexes. */ +var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq; + +/** Used to match complex or compound words. */ +var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji +].join('|'), 'g'); + +/** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function unicodeWords(string) { + return string.match(reUnicodeWord) || []; +} + +module.exports = unicodeWords; diff --git a/app/node_modules/lodash/_updateWrapDetails.js b/app/node_modules/lodash/_updateWrapDetails.js new file mode 100644 index 0000000..8759fbd --- /dev/null +++ b/app/node_modules/lodash/_updateWrapDetails.js @@ -0,0 +1,46 @@ +var arrayEach = require('./_arrayEach'), + arrayIncludes = require('./_arrayIncludes'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256, + WRAP_FLIP_FLAG = 512; + +/** Used to associate wrap methods with their bit flags. */ +var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] +]; + +/** + * Updates wrapper `details` based on `bitmask` flags. + * + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ +function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); +} + +module.exports = updateWrapDetails; diff --git a/app/node_modules/lodash/_wrapperClone.js b/app/node_modules/lodash/_wrapperClone.js new file mode 100644 index 0000000..7bb58a2 --- /dev/null +++ b/app/node_modules/lodash/_wrapperClone.js @@ -0,0 +1,23 @@ +var LazyWrapper = require('./_LazyWrapper'), + LodashWrapper = require('./_LodashWrapper'), + copyArray = require('./_copyArray'); + +/** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ +function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; +} + +module.exports = wrapperClone; diff --git a/app/node_modules/lodash/add.js b/app/node_modules/lodash/add.js new file mode 100644 index 0000000..f069515 --- /dev/null +++ b/app/node_modules/lodash/add.js @@ -0,0 +1,22 @@ +var createMathOperation = require('./_createMathOperation'); + +/** + * Adds two numbers. + * + * @static + * @memberOf _ + * @since 3.4.0 + * @category Math + * @param {number} augend The first number in an addition. + * @param {number} addend The second number in an addition. + * @returns {number} Returns the total. + * @example + * + * _.add(6, 4); + * // => 10 + */ +var add = createMathOperation(function(augend, addend) { + return augend + addend; +}, 0); + +module.exports = add; diff --git a/app/node_modules/lodash/after.js b/app/node_modules/lodash/after.js new file mode 100644 index 0000000..3900c97 --- /dev/null +++ b/app/node_modules/lodash/after.js @@ -0,0 +1,42 @@ +var toInteger = require('./toInteger'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */ +function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; +} + +module.exports = after; diff --git a/app/node_modules/lodash/array.js b/app/node_modules/lodash/array.js new file mode 100644 index 0000000..af688d3 --- /dev/null +++ b/app/node_modules/lodash/array.js @@ -0,0 +1,67 @@ +module.exports = { + 'chunk': require('./chunk'), + 'compact': require('./compact'), + 'concat': require('./concat'), + 'difference': require('./difference'), + 'differenceBy': require('./differenceBy'), + 'differenceWith': require('./differenceWith'), + 'drop': require('./drop'), + 'dropRight': require('./dropRight'), + 'dropRightWhile': require('./dropRightWhile'), + 'dropWhile': require('./dropWhile'), + 'fill': require('./fill'), + 'findIndex': require('./findIndex'), + 'findLastIndex': require('./findLastIndex'), + 'first': require('./first'), + 'flatten': require('./flatten'), + 'flattenDeep': require('./flattenDeep'), + 'flattenDepth': require('./flattenDepth'), + 'fromPairs': require('./fromPairs'), + 'head': require('./head'), + 'indexOf': require('./indexOf'), + 'initial': require('./initial'), + 'intersection': require('./intersection'), + 'intersectionBy': require('./intersectionBy'), + 'intersectionWith': require('./intersectionWith'), + 'join': require('./join'), + 'last': require('./last'), + 'lastIndexOf': require('./lastIndexOf'), + 'nth': require('./nth'), + 'pull': require('./pull'), + 'pullAll': require('./pullAll'), + 'pullAllBy': require('./pullAllBy'), + 'pullAllWith': require('./pullAllWith'), + 'pullAt': require('./pullAt'), + 'remove': require('./remove'), + 'reverse': require('./reverse'), + 'slice': require('./slice'), + 'sortedIndex': require('./sortedIndex'), + 'sortedIndexBy': require('./sortedIndexBy'), + 'sortedIndexOf': require('./sortedIndexOf'), + 'sortedLastIndex': require('./sortedLastIndex'), + 'sortedLastIndexBy': require('./sortedLastIndexBy'), + 'sortedLastIndexOf': require('./sortedLastIndexOf'), + 'sortedUniq': require('./sortedUniq'), + 'sortedUniqBy': require('./sortedUniqBy'), + 'tail': require('./tail'), + 'take': require('./take'), + 'takeRight': require('./takeRight'), + 'takeRightWhile': require('./takeRightWhile'), + 'takeWhile': require('./takeWhile'), + 'union': require('./union'), + 'unionBy': require('./unionBy'), + 'unionWith': require('./unionWith'), + 'uniq': require('./uniq'), + 'uniqBy': require('./uniqBy'), + 'uniqWith': require('./uniqWith'), + 'unzip': require('./unzip'), + 'unzipWith': require('./unzipWith'), + 'without': require('./without'), + 'xor': require('./xor'), + 'xorBy': require('./xorBy'), + 'xorWith': require('./xorWith'), + 'zip': require('./zip'), + 'zipObject': require('./zipObject'), + 'zipObjectDeep': require('./zipObjectDeep'), + 'zipWith': require('./zipWith') +}; diff --git a/app/node_modules/lodash/ary.js b/app/node_modules/lodash/ary.js new file mode 100644 index 0000000..70c87d0 --- /dev/null +++ b/app/node_modules/lodash/ary.js @@ -0,0 +1,29 @@ +var createWrap = require('./_createWrap'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_ARY_FLAG = 128; + +/** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ +function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); +} + +module.exports = ary; diff --git a/app/node_modules/lodash/assign.js b/app/node_modules/lodash/assign.js new file mode 100644 index 0000000..909db26 --- /dev/null +++ b/app/node_modules/lodash/assign.js @@ -0,0 +1,58 @@ +var assignValue = require('./_assignValue'), + copyObject = require('./_copyObject'), + createAssigner = require('./_createAssigner'), + isArrayLike = require('./isArrayLike'), + isPrototype = require('./_isPrototype'), + keys = require('./keys'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ +var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } +}); + +module.exports = assign; diff --git a/app/node_modules/lodash/assignIn.js b/app/node_modules/lodash/assignIn.js new file mode 100644 index 0000000..e663473 --- /dev/null +++ b/app/node_modules/lodash/assignIn.js @@ -0,0 +1,40 @@ +var copyObject = require('./_copyObject'), + createAssigner = require('./_createAssigner'), + keysIn = require('./keysIn'); + +/** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ +var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); +}); + +module.exports = assignIn; diff --git a/app/node_modules/lodash/assignInWith.js b/app/node_modules/lodash/assignInWith.js new file mode 100644 index 0000000..68fcc0b --- /dev/null +++ b/app/node_modules/lodash/assignInWith.js @@ -0,0 +1,38 @@ +var copyObject = require('./_copyObject'), + createAssigner = require('./_createAssigner'), + keysIn = require('./keysIn'); + +/** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); +}); + +module.exports = assignInWith; diff --git a/app/node_modules/lodash/assignWith.js b/app/node_modules/lodash/assignWith.js new file mode 100644 index 0000000..7dc6c76 --- /dev/null +++ b/app/node_modules/lodash/assignWith.js @@ -0,0 +1,37 @@ +var copyObject = require('./_copyObject'), + createAssigner = require('./_createAssigner'), + keys = require('./keys'); + +/** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); +}); + +module.exports = assignWith; diff --git a/app/node_modules/lodash/at.js b/app/node_modules/lodash/at.js new file mode 100644 index 0000000..781ee9e --- /dev/null +++ b/app/node_modules/lodash/at.js @@ -0,0 +1,23 @@ +var baseAt = require('./_baseAt'), + flatRest = require('./_flatRest'); + +/** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */ +var at = flatRest(baseAt); + +module.exports = at; diff --git a/app/node_modules/lodash/attempt.js b/app/node_modules/lodash/attempt.js new file mode 100644 index 0000000..624d015 --- /dev/null +++ b/app/node_modules/lodash/attempt.js @@ -0,0 +1,35 @@ +var apply = require('./_apply'), + baseRest = require('./_baseRest'), + isError = require('./isError'); + +/** + * Attempts to invoke `func`, returning either the result or the caught error + * object. Any additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {Function} func The function to attempt. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {*} Returns the `func` result or error object. + * @example + * + * // Avoid throwing errors for invalid selectors. + * var elements = _.attempt(function(selector) { + * return document.querySelectorAll(selector); + * }, '>_>'); + * + * if (_.isError(elements)) { + * elements = []; + * } + */ +var attempt = baseRest(function(func, args) { + try { + return apply(func, undefined, args); + } catch (e) { + return isError(e) ? e : new Error(e); + } +}); + +module.exports = attempt; diff --git a/app/node_modules/lodash/before.js b/app/node_modules/lodash/before.js new file mode 100644 index 0000000..a3e0a16 --- /dev/null +++ b/app/node_modules/lodash/before.js @@ -0,0 +1,40 @@ +var toInteger = require('./toInteger'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ +function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; +} + +module.exports = before; diff --git a/app/node_modules/lodash/bind.js b/app/node_modules/lodash/bind.js new file mode 100644 index 0000000..b1076e9 --- /dev/null +++ b/app/node_modules/lodash/bind.js @@ -0,0 +1,57 @@ +var baseRest = require('./_baseRest'), + createWrap = require('./_createWrap'), + getHolder = require('./_getHolder'), + replaceHolders = require('./_replaceHolders'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_PARTIAL_FLAG = 32; + +/** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ +var bind = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); +}); + +// Assign default placeholders. +bind.placeholder = {}; + +module.exports = bind; diff --git a/app/node_modules/lodash/bindAll.js b/app/node_modules/lodash/bindAll.js new file mode 100644 index 0000000..a35706d --- /dev/null +++ b/app/node_modules/lodash/bindAll.js @@ -0,0 +1,41 @@ +var arrayEach = require('./_arrayEach'), + baseAssignValue = require('./_baseAssignValue'), + bind = require('./bind'), + flatRest = require('./_flatRest'), + toKey = require('./_toKey'); + +/** + * Binds methods of an object to the object itself, overwriting the existing + * method. + * + * **Note:** This method doesn't set the "length" property of bound functions. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {Object} object The object to bind and assign the bound methods to. + * @param {...(string|string[])} methodNames The object method names to bind. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'click': function() { + * console.log('clicked ' + this.label); + * } + * }; + * + * _.bindAll(view, ['click']); + * jQuery(element).on('click', view.click); + * // => Logs 'clicked docs' when clicked. + */ +var bindAll = flatRest(function(object, methodNames) { + arrayEach(methodNames, function(key) { + key = toKey(key); + baseAssignValue(object, key, bind(object[key], object)); + }); + return object; +}); + +module.exports = bindAll; diff --git a/app/node_modules/lodash/bindKey.js b/app/node_modules/lodash/bindKey.js new file mode 100644 index 0000000..f7fd64c --- /dev/null +++ b/app/node_modules/lodash/bindKey.js @@ -0,0 +1,68 @@ +var baseRest = require('./_baseRest'), + createWrap = require('./_createWrap'), + getHolder = require('./_getHolder'), + replaceHolders = require('./_replaceHolders'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_PARTIAL_FLAG = 32; + +/** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ +var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); +}); + +// Assign default placeholders. +bindKey.placeholder = {}; + +module.exports = bindKey; diff --git a/app/node_modules/lodash/camelCase.js b/app/node_modules/lodash/camelCase.js new file mode 100644 index 0000000..d7390de --- /dev/null +++ b/app/node_modules/lodash/camelCase.js @@ -0,0 +1,29 @@ +var capitalize = require('./capitalize'), + createCompounder = require('./_createCompounder'); + +/** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ +var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); +}); + +module.exports = camelCase; diff --git a/app/node_modules/lodash/capitalize.js b/app/node_modules/lodash/capitalize.js new file mode 100644 index 0000000..3e1600e --- /dev/null +++ b/app/node_modules/lodash/capitalize.js @@ -0,0 +1,23 @@ +var toString = require('./toString'), + upperFirst = require('./upperFirst'); + +/** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ +function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); +} + +module.exports = capitalize; diff --git a/app/node_modules/lodash/castArray.js b/app/node_modules/lodash/castArray.js new file mode 100644 index 0000000..e470bdb --- /dev/null +++ b/app/node_modules/lodash/castArray.js @@ -0,0 +1,44 @@ +var isArray = require('./isArray'); + +/** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ +function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; +} + +module.exports = castArray; diff --git a/app/node_modules/lodash/ceil.js b/app/node_modules/lodash/ceil.js new file mode 100644 index 0000000..56c8722 --- /dev/null +++ b/app/node_modules/lodash/ceil.js @@ -0,0 +1,26 @@ +var createRound = require('./_createRound'); + +/** + * Computes `number` rounded up to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round up. + * @param {number} [precision=0] The precision to round up to. + * @returns {number} Returns the rounded up number. + * @example + * + * _.ceil(4.006); + * // => 5 + * + * _.ceil(6.004, 2); + * // => 6.01 + * + * _.ceil(6040, -2); + * // => 6100 + */ +var ceil = createRound('ceil'); + +module.exports = ceil; diff --git a/app/node_modules/lodash/chain.js b/app/node_modules/lodash/chain.js new file mode 100644 index 0000000..f6cd647 --- /dev/null +++ b/app/node_modules/lodash/chain.js @@ -0,0 +1,38 @@ +var lodash = require('./wrapperLodash'); + +/** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ +function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; +} + +module.exports = chain; diff --git a/app/node_modules/lodash/chunk.js b/app/node_modules/lodash/chunk.js new file mode 100644 index 0000000..5b562fe --- /dev/null +++ b/app/node_modules/lodash/chunk.js @@ -0,0 +1,50 @@ +var baseSlice = require('./_baseSlice'), + isIterateeCall = require('./_isIterateeCall'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeCeil = Math.ceil, + nativeMax = Math.max; + +/** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ +function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; +} + +module.exports = chunk; diff --git a/app/node_modules/lodash/clamp.js b/app/node_modules/lodash/clamp.js new file mode 100644 index 0000000..91a72c9 --- /dev/null +++ b/app/node_modules/lodash/clamp.js @@ -0,0 +1,39 @@ +var baseClamp = require('./_baseClamp'), + toNumber = require('./toNumber'); + +/** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ +function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); +} + +module.exports = clamp; diff --git a/app/node_modules/lodash/clone.js b/app/node_modules/lodash/clone.js new file mode 100644 index 0000000..dd439d6 --- /dev/null +++ b/app/node_modules/lodash/clone.js @@ -0,0 +1,36 @@ +var baseClone = require('./_baseClone'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_SYMBOLS_FLAG = 4; + +/** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ +function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG); +} + +module.exports = clone; diff --git a/app/node_modules/lodash/cloneDeep.js b/app/node_modules/lodash/cloneDeep.js new file mode 100644 index 0000000..4425fbe --- /dev/null +++ b/app/node_modules/lodash/cloneDeep.js @@ -0,0 +1,29 @@ +var baseClone = require('./_baseClone'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1, + CLONE_SYMBOLS_FLAG = 4; + +/** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ +function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); +} + +module.exports = cloneDeep; diff --git a/app/node_modules/lodash/cloneDeepWith.js b/app/node_modules/lodash/cloneDeepWith.js new file mode 100644 index 0000000..fd9c6c0 --- /dev/null +++ b/app/node_modules/lodash/cloneDeepWith.js @@ -0,0 +1,40 @@ +var baseClone = require('./_baseClone'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1, + CLONE_SYMBOLS_FLAG = 4; + +/** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ +function cloneDeepWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); +} + +module.exports = cloneDeepWith; diff --git a/app/node_modules/lodash/cloneWith.js b/app/node_modules/lodash/cloneWith.js new file mode 100644 index 0000000..d2f4e75 --- /dev/null +++ b/app/node_modules/lodash/cloneWith.js @@ -0,0 +1,42 @@ +var baseClone = require('./_baseClone'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_SYMBOLS_FLAG = 4; + +/** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */ +function cloneWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); +} + +module.exports = cloneWith; diff --git a/app/node_modules/lodash/collection.js b/app/node_modules/lodash/collection.js new file mode 100644 index 0000000..77fe837 --- /dev/null +++ b/app/node_modules/lodash/collection.js @@ -0,0 +1,30 @@ +module.exports = { + 'countBy': require('./countBy'), + 'each': require('./each'), + 'eachRight': require('./eachRight'), + 'every': require('./every'), + 'filter': require('./filter'), + 'find': require('./find'), + 'findLast': require('./findLast'), + 'flatMap': require('./flatMap'), + 'flatMapDeep': require('./flatMapDeep'), + 'flatMapDepth': require('./flatMapDepth'), + 'forEach': require('./forEach'), + 'forEachRight': require('./forEachRight'), + 'groupBy': require('./groupBy'), + 'includes': require('./includes'), + 'invokeMap': require('./invokeMap'), + 'keyBy': require('./keyBy'), + 'map': require('./map'), + 'orderBy': require('./orderBy'), + 'partition': require('./partition'), + 'reduce': require('./reduce'), + 'reduceRight': require('./reduceRight'), + 'reject': require('./reject'), + 'sample': require('./sample'), + 'sampleSize': require('./sampleSize'), + 'shuffle': require('./shuffle'), + 'size': require('./size'), + 'some': require('./some'), + 'sortBy': require('./sortBy') +}; diff --git a/app/node_modules/lodash/commit.js b/app/node_modules/lodash/commit.js new file mode 100644 index 0000000..fe4db71 --- /dev/null +++ b/app/node_modules/lodash/commit.js @@ -0,0 +1,33 @@ +var LodashWrapper = require('./_LodashWrapper'); + +/** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ +function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); +} + +module.exports = wrapperCommit; diff --git a/app/node_modules/lodash/compact.js b/app/node_modules/lodash/compact.js new file mode 100644 index 0000000..031fab4 --- /dev/null +++ b/app/node_modules/lodash/compact.js @@ -0,0 +1,31 @@ +/** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ +function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; +} + +module.exports = compact; diff --git a/app/node_modules/lodash/concat.js b/app/node_modules/lodash/concat.js new file mode 100644 index 0000000..1da48a4 --- /dev/null +++ b/app/node_modules/lodash/concat.js @@ -0,0 +1,43 @@ +var arrayPush = require('./_arrayPush'), + baseFlatten = require('./_baseFlatten'), + copyArray = require('./_copyArray'), + isArray = require('./isArray'); + +/** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ +function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); +} + +module.exports = concat; diff --git a/app/node_modules/lodash/cond.js b/app/node_modules/lodash/cond.js new file mode 100644 index 0000000..6455598 --- /dev/null +++ b/app/node_modules/lodash/cond.js @@ -0,0 +1,60 @@ +var apply = require('./_apply'), + arrayMap = require('./_arrayMap'), + baseIteratee = require('./_baseIteratee'), + baseRest = require('./_baseRest'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that iterates over `pairs` and invokes the corresponding + * function of the first predicate to return truthy. The predicate-function + * pairs are invoked with the `this` binding and arguments of the created + * function. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {Array} pairs The predicate-function pairs. + * @returns {Function} Returns the new composite function. + * @example + * + * var func = _.cond([ + * [_.matches({ 'a': 1 }), _.constant('matches A')], + * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], + * [_.stubTrue, _.constant('no match')] + * ]); + * + * func({ 'a': 1, 'b': 2 }); + * // => 'matches A' + * + * func({ 'a': 0, 'b': 1 }); + * // => 'matches B' + * + * func({ 'a': '1', 'b': '2' }); + * // => 'no match' + */ +function cond(pairs) { + var length = pairs == null ? 0 : pairs.length, + toIteratee = baseIteratee; + + pairs = !length ? [] : arrayMap(pairs, function(pair) { + if (typeof pair[1] != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return [toIteratee(pair[0]), pair[1]]; + }); + + return baseRest(function(args) { + var index = -1; + while (++index < length) { + var pair = pairs[index]; + if (apply(pair[0], this, args)) { + return apply(pair[1], this, args); + } + } + }); +} + +module.exports = cond; diff --git a/app/node_modules/lodash/conforms.js b/app/node_modules/lodash/conforms.js new file mode 100644 index 0000000..5501a94 --- /dev/null +++ b/app/node_modules/lodash/conforms.js @@ -0,0 +1,35 @@ +var baseClone = require('./_baseClone'), + baseConforms = require('./_baseConforms'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1; + +/** + * Creates a function that invokes the predicate properties of `source` with + * the corresponding property values of a given object, returning `true` if + * all predicates return truthy, else `false`. + * + * **Note:** The created function is equivalent to `_.conformsTo` with + * `source` partially applied. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + * @example + * + * var objects = [ + * { 'a': 2, 'b': 1 }, + * { 'a': 1, 'b': 2 } + * ]; + * + * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); + * // => [{ 'a': 1, 'b': 2 }] + */ +function conforms(source) { + return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); +} + +module.exports = conforms; diff --git a/app/node_modules/lodash/conformsTo.js b/app/node_modules/lodash/conformsTo.js new file mode 100644 index 0000000..b8a93eb --- /dev/null +++ b/app/node_modules/lodash/conformsTo.js @@ -0,0 +1,32 @@ +var baseConformsTo = require('./_baseConformsTo'), + keys = require('./keys'); + +/** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */ +function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); +} + +module.exports = conformsTo; diff --git a/app/node_modules/lodash/constant.js b/app/node_modules/lodash/constant.js new file mode 100644 index 0000000..655ece3 --- /dev/null +++ b/app/node_modules/lodash/constant.js @@ -0,0 +1,26 @@ +/** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ +function constant(value) { + return function() { + return value; + }; +} + +module.exports = constant; diff --git a/app/node_modules/lodash/core.js b/app/node_modules/lodash/core.js new file mode 100644 index 0000000..89c77de --- /dev/null +++ b/app/node_modules/lodash/core.js @@ -0,0 +1,3854 @@ +/** + * @license + * Lodash (Custom Build) + * Build: `lodash core -o ./dist/lodash.core.js` + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.17.15'; + + /** Error message constants. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** Used to compose bitmasks for function metadata. */ + var WRAP_BIND_FLAG = 1, + WRAP_PARTIAL_FLAG = 32; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + numberTag = '[object Number]', + objectTag = '[object Object]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + stringTag = '[object String]'; + + /** Used to match HTML entities and HTML characters. */ + var reUnescapedHtml = /[&<>"']/g, + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /*--------------------------------------------------------------------------*/ + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + array.push.apply(array, values); + return array; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return baseMap(props, function(key) { + return object[key]; + }); + } + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /*--------------------------------------------------------------------------*/ + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + objectProto = Object.prototype; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Built-in value references. */ + var objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeIsFinite = root.isFinite, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + return value instanceof LodashWrapper + ? value + : new LodashWrapper(value); + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + } + + LodashWrapper.prototype = baseCreate(lodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + object[key] = value; + } + + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !false) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return baseFilter(props, function(key) { + return isFunction(object[key]); + }); + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + return objectToString(value); + } + + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + var baseIsArguments = noop; + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : baseGetTag(object), + othTag = othIsArr ? arrayTag : baseGetTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + stack || (stack = []); + var objStack = find(stack, function(entry) { + return entry[0] == object; + }); + var othStack = find(stack, function(entry) { + return entry[0] == other; + }); + if (objStack && othStack) { + return objStack[1] == other; + } + stack.push([object, other]); + stack.push([other, object]); + if (isSameTag && !objIsObj) { + var result = (objIsArr) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + stack.pop(); + return result; + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + var result = equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + stack.pop(); + return result; + } + } + if (!isSameTag) { + return false; + } + var result = equalObjects(object, other, bitmask, customizer, equalFunc, stack); + stack.pop(); + return result; + } + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(func) { + if (typeof func == 'function') { + return func; + } + if (func == null) { + return identity; + } + return (typeof func == 'object' ? baseMatches : baseProperty)(func); + } + + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var props = nativeKeys(source); + return function(object) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length]; + if (!(key in object && + baseIsEqual(source[key], object[key], COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG) + )) { + return false; + } + } + return true; + }; + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, props) { + object = Object(object); + return reduce(props, function(result, key) { + if (key in object) { + result[key] = object[key]; + } + return result; + }, {}); + } + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source) { + return baseSlice(source, 0, source.length); + } + + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + return reduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = false; + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = false; + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = baseIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return fn.apply(isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? [] : undefined; + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + var compared; + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!baseSome(other, function(othValue, othIndex) { + if (!indexOf(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = keys(object), + objLength = objProps.length, + othProps = keys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + var result = true; + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + var compared; + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + return result; + } + + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); + } + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return func.apply(this, otherArgs); + }; + } + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = identity; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + return baseFilter(array, Boolean); + } + + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, baseIteratee(predicate, 3), index); + } + + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return (array && array.length) ? array[0] : undefined; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (typeof fromIndex == 'number') { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; + } else { + fromIndex = 0; + } + var index = (fromIndex || 0) - 1, + isReflexive = value === value; + + while (++index < length) { + var other = array[index]; + if ((isReflexive ? other === value : other !== other)) { + return index; + } + } + return -1; + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + start = start == null ? 0 : +start; + end = end === undefined ? length : +end; + return length ? baseSlice(array, start, end) : []; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + predicate = guard ? undefined : predicate; + return baseEvery(collection, baseIteratee(predicate)); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + */ + function filter(collection, predicate) { + return baseFilter(collection, baseIteratee(predicate)); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + return baseEach(collection, baseIteratee(iteratee)); + } + + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + return baseMap(collection, baseIteratee(iteratee)); + } + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + return baseReduce(collection, baseIteratee(iteratee), accumulator, arguments.length < 3, baseEach); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + collection = isArrayLike(collection) ? collection : nativeKeys(collection); + return collection.length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + predicate = guard ? undefined : predicate; + return baseSome(collection, baseIteratee(predicate)); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] + */ + function sortBy(collection, iteratee) { + var index = 0; + iteratee = baseIteratee(iteratee); + + return baseMap(baseMap(collection, function(value, key, collection) { + return { 'value': value, 'index': index++, 'criteria': iteratee(value, key, collection) }; + }).sort(function(object, other) { + return compareAscending(object.criteria, other.criteria) || (object.index - other.index); + }), baseProperty('value')); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + return createPartial(func, WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG, thisArg, partials); + }); + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + return !predicate.apply(this, args); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + if (!isObject(value)) { + return value; + } + return isArray(value) ? copyArray(value) : copyObject(value, nativeKeys(value)); + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); + } + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = baseIsDate; + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (isArrayLike(value) && + (isArray(value) || isString(value) || + isFunction(value.splice) || isArguments(value))) { + return !value.length; + } + return !nativeKeys(value).length; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = baseIsRegExp; + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + } + + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!isArrayLike(value)) { + return values(value); + } + return value.length ? copyArray(value) : []; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + var toInteger = Number; + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + var toNumber = Number; + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + if (typeof value == 'string') { + return value; + } + return value == null ? '' : (value + ''); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + copyObject(source, nativeKeys(source), object); + }); + + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, nativeKeysIn(source), object); + }); + + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : assign(result, properties); + } + + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(object, sources) { + object = Object(object); + + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + + if (value === undefined || + (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { + object[key] = source[key]; + } + } + } + + return object; + }); + + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasOwnProperty.call(object, path); + } + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + var keys = nativeKeys; + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + var keysIn = nativeKeysIn; + + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); + }); + + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + var value = object == null ? undefined : object[path]; + if (value === undefined) { + value = defaultValue; + } + return isFunction(value) ? value.call(object) : value; + } + + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object == null ? [] : baseValues(object, keys(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /*------------------------------------------------------------------------*/ + + /** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ + function identity(value) { + return value; + } + + /** + * Creates a function that invokes `func` with the arguments of the created + * function. If `func` is a property name, the created function returns the + * property value for a given element. If `func` is an array or object, the + * created function returns `true` for elements that contain the equivalent + * source properties, otherwise it returns `false`. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Util + * @param {*} [func=_.identity] The value to convert to a callback. + * @returns {Function} Returns the callback. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); + * // => [{ 'user': 'barney', 'age': 36, 'active': true }] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, _.iteratee(['user', 'fred'])); + * // => [{ 'user': 'fred', 'age': 40 }] + * + * // The `_.property` iteratee shorthand. + * _.map(users, _.iteratee('user')); + * // => ['barney', 'fred'] + * + * // Create custom iteratee shorthands. + * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { + * return !_.isRegExp(func) ? iteratee(func) : function(string) { + * return func.test(string); + * }; + * }); + * + * _.filter(['abc', 'def'], /ef/); + * // => ['def'] + */ + var iteratee = baseIteratee; + + /** + * Creates a function that performs a partial deep comparison between a given + * object and `source`, returning `true` if the given object has equivalent + * property values, else `false`. + * + * **Note:** The created function is equivalent to `_.isMatch` with `source` + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + * @example + * + * var objects = [ + * { 'a': 1, 'b': 2, 'c': 3 }, + * { 'a': 4, 'b': 5, 'c': 6 } + * ]; + * + * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); + * // => [{ 'a': 4, 'b': 5, 'c': 6 }] + */ + function matches(source) { + return baseMatches(assign({}, source)); + } + + /** + * Adds all own enumerable string keyed function properties of a source + * object to the destination object. If `object` is a function, then methods + * are added to its prototype as well. + * + * **Note:** Use `_.runInContext` to create a pristine `lodash` function to + * avoid conflicts caused by modifying the original. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {Function|Object} [object=lodash] The destination object. + * @param {Object} source The object of functions to add. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.chain=true] Specify whether mixins are chainable. + * @returns {Function|Object} Returns `object`. + * @example + * + * function vowels(string) { + * return _.filter(string, function(v) { + * return /[aeiou]/i.test(v); + * }); + * } + * + * _.mixin({ 'vowels': vowels }); + * _.vowels('fred'); + * // => ['e'] + * + * _('fred').vowels().value(); + * // => ['e'] + * + * _.mixin({ 'vowels': vowels }, { 'chain': false }); + * _('fred').vowels(); + * // => ['e'] + */ + function mixin(object, source, options) { + var props = keys(source), + methodNames = baseFunctions(source, props); + + if (options == null && + !(isObject(source) && (methodNames.length || !props.length))) { + options = source; + source = object; + object = this; + methodNames = baseFunctions(source, keys(source)); + } + var chain = !(isObject(options) && 'chain' in options) || !!options.chain, + isFunc = isFunction(object); + + baseEach(methodNames, function(methodName) { + var func = source[methodName]; + object[methodName] = func; + if (isFunc) { + object.prototype[methodName] = function() { + var chainAll = this.__chain__; + if (chain || chainAll) { + var result = object(this.__wrapped__), + actions = result.__actions__ = copyArray(this.__actions__); + + actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); + result.__chain__ = chainAll; + return result; + } + return func.apply(object, arrayPush([this.value()], arguments)); + }; + } + }); + + return object; + } + + /** + * Reverts the `_` variable to its previous value and returns a reference to + * the `lodash` function. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @returns {Function} Returns the `lodash` function. + * @example + * + * var lodash = _.noConflict(); + */ + function noConflict() { + if (root._ === this) { + root._ = oldDash; + } + return this; + } + + /** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ + function noop() { + // No operation performed. + } + + /** + * Generates a unique ID. If `prefix` is given, the ID is appended to it. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {string} [prefix=''] The value to prefix the ID with. + * @returns {string} Returns the unique ID. + * @example + * + * _.uniqueId('contact_'); + * // => 'contact_104' + * + * _.uniqueId(); + * // => '105' + */ + function uniqueId(prefix) { + var id = ++idCounter; + return toString(prefix) + id; + } + + /*------------------------------------------------------------------------*/ + + /** + * Computes the maximum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the maximum value. + * @example + * + * _.max([4, 2, 8, 6]); + * // => 8 + * + * _.max([]); + * // => undefined + */ + function max(array) { + return (array && array.length) + ? baseExtremum(array, identity, baseGt) + : undefined; + } + + /** + * Computes the minimum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the minimum value. + * @example + * + * _.min([4, 2, 8, 6]); + * // => 2 + * + * _.min([]); + * // => undefined + */ + function min(array) { + return (array && array.length) + ? baseExtremum(array, identity, baseLt) + : undefined; + } + + /*------------------------------------------------------------------------*/ + + // Add methods that return wrapped values in chain sequences. + lodash.assignIn = assignIn; + lodash.before = before; + lodash.bind = bind; + lodash.chain = chain; + lodash.compact = compact; + lodash.concat = concat; + lodash.create = create; + lodash.defaults = defaults; + lodash.defer = defer; + lodash.delay = delay; + lodash.filter = filter; + lodash.flatten = flatten; + lodash.flattenDeep = flattenDeep; + lodash.iteratee = iteratee; + lodash.keys = keys; + lodash.map = map; + lodash.matches = matches; + lodash.mixin = mixin; + lodash.negate = negate; + lodash.once = once; + lodash.pick = pick; + lodash.slice = slice; + lodash.sortBy = sortBy; + lodash.tap = tap; + lodash.thru = thru; + lodash.toArray = toArray; + lodash.values = values; + + // Add aliases. + lodash.extend = assignIn; + + // Add methods to `lodash.prototype`. + mixin(lodash, lodash); + + /*------------------------------------------------------------------------*/ + + // Add methods that return unwrapped values in chain sequences. + lodash.clone = clone; + lodash.escape = escape; + lodash.every = every; + lodash.find = find; + lodash.forEach = forEach; + lodash.has = has; + lodash.head = head; + lodash.identity = identity; + lodash.indexOf = indexOf; + lodash.isArguments = isArguments; + lodash.isArray = isArray; + lodash.isBoolean = isBoolean; + lodash.isDate = isDate; + lodash.isEmpty = isEmpty; + lodash.isEqual = isEqual; + lodash.isFinite = isFinite; + lodash.isFunction = isFunction; + lodash.isNaN = isNaN; + lodash.isNull = isNull; + lodash.isNumber = isNumber; + lodash.isObject = isObject; + lodash.isRegExp = isRegExp; + lodash.isString = isString; + lodash.isUndefined = isUndefined; + lodash.last = last; + lodash.max = max; + lodash.min = min; + lodash.noConflict = noConflict; + lodash.noop = noop; + lodash.reduce = reduce; + lodash.result = result; + lodash.size = size; + lodash.some = some; + lodash.uniqueId = uniqueId; + + // Add aliases. + lodash.each = forEach; + lodash.first = head; + + mixin(lodash, (function() { + var source = {}; + baseForOwn(lodash, function(func, methodName) { + if (!hasOwnProperty.call(lodash.prototype, methodName)) { + source[methodName] = func; + } + }); + return source; + }()), { 'chain': false }); + + /*------------------------------------------------------------------------*/ + + /** + * The semantic version number. + * + * @static + * @memberOf _ + * @type {string} + */ + lodash.VERSION = VERSION; + + // Add `Array` methods to `lodash.prototype`. + baseEach(['pop', 'join', 'replace', 'reverse', 'split', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { + var func = (/^(?:replace|split)$/.test(methodName) ? String.prototype : arrayProto)[methodName], + chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', + retUnwrapped = /^(?:pop|join|replace|shift)$/.test(methodName); + + lodash.prototype[methodName] = function() { + var args = arguments; + if (retUnwrapped && !this.__chain__) { + var value = this.value(); + return func.apply(isArray(value) ? value : [], args); + } + return this[chainName](function(value) { + return func.apply(isArray(value) ? value : [], args); + }); + }; + }); + + // Add chain sequence methods to the `lodash` wrapper. + lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; + + /*--------------------------------------------------------------------------*/ + + // Some AMD build optimizers, like r.js, check for condition patterns like: + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + // Expose Lodash on the global object to prevent errors when Lodash is + // loaded by a script tag in the presence of an AMD loader. + // See http://requirejs.org/docs/errors.html#mismatch for more details. + // Use `_.noConflict` to remove Lodash from the global object. + root._ = lodash; + + // Define as an anonymous module so, through path mapping, it can be + // referenced as the "underscore" module. + define(function() { + return lodash; + }); + } + // Check for `exports` after `define` in case a build optimizer adds it. + else if (freeModule) { + // Export for Node.js. + (freeModule.exports = lodash)._ = lodash; + // Export for CommonJS support. + freeExports._ = lodash; + } + else { + // Export to the global object. + root._ = lodash; + } +}.call(this)); diff --git a/app/node_modules/lodash/core.min.js b/app/node_modules/lodash/core.min.js new file mode 100644 index 0000000..bb543ff --- /dev/null +++ b/app/node_modules/lodash/core.min.js @@ -0,0 +1,29 @@ +/** + * @license + * Lodash (Custom Build) lodash.com/license | Underscore.js 1.8.3 underscorejs.org/LICENSE + * Build: `lodash core -o ./dist/lodash.core.js` + */ +;(function(){function n(n){return H(n)&&pn.call(n,"callee")&&!yn.call(n,"callee")}function t(n,t){return n.push.apply(n,t),n}function r(n){return function(t){return null==t?Z:t[n]}}function e(n,t,r,e,u){return u(n,function(n,u,o){r=e?(e=false,n):t(r,n,u,o)}),r}function u(n,t){return j(t,function(t){return n[t]})}function o(n){return n instanceof i?n:new i(n)}function i(n,t){this.__wrapped__=n,this.__actions__=[],this.__chain__=!!t}function c(n,t,r){if(typeof n!="function")throw new TypeError("Expected a function"); +return setTimeout(function(){n.apply(Z,r)},t)}function f(n,t){var r=true;return mn(n,function(n,e,u){return r=!!t(n,e,u)}),r}function a(n,t,r){for(var e=-1,u=n.length;++et}function b(n,t,r,e,u){return n===t||(null==n||null==t||!H(n)&&!H(t)?n!==n&&t!==t:y(n,t,r,e,b,u))}function y(n,t,r,e,u,o){var i=Nn(n),c=Nn(t),f=i?"[object Array]":hn.call(n),a=c?"[object Array]":hn.call(t),f="[object Arguments]"==f?"[object Object]":f,a="[object Arguments]"==a?"[object Object]":a,l="[object Object]"==f,c="[object Object]"==a,a=f==a;o||(o=[]);var p=An(o,function(t){return t[0]==n}),s=An(o,function(n){ +return n[0]==t});if(p&&s)return p[1]==t;if(o.push([n,t]),o.push([t,n]),a&&!l){if(i)r=T(n,t,r,e,u,o);else n:{switch(f){case"[object Boolean]":case"[object Date]":case"[object Number]":r=J(+n,+t);break n;case"[object Error]":r=n.name==t.name&&n.message==t.message;break n;case"[object RegExp]":case"[object String]":r=n==t+"";break n}r=false}return o.pop(),r}return 1&r||(i=l&&pn.call(n,"__wrapped__"),f=c&&pn.call(t,"__wrapped__"),!i&&!f)?!!a&&(r=B(n,t,r,e,u,o),o.pop(),r):(i=i?n.value():n,f=f?t.value():t, +r=u(i,f,r,e,o),o.pop(),r)}function g(n){return typeof n=="function"?n:null==n?X:(typeof n=="object"?d:r)(n)}function _(n,t){return nt&&(t=-t>u?0:u+t),r=r>u?u:r,0>r&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0,r=Array(u);++ei))return false;for(var c=-1,f=true,a=2&r?[]:Z;++cr?jn(e+r,0):r:0,r=(r||0)-1;for(var u=t===t;++rarguments.length,mn)}function G(n,t){var r;if(typeof t!="function")throw new TypeError("Expected a function");return n=Fn(n), +function(){return 0<--n&&(r=t.apply(this,arguments)),1>=n&&(t=Z),r}}function J(n,t){return n===t||n!==n&&t!==t}function M(n){var t;return(t=null!=n)&&(t=n.length,t=typeof t=="number"&&-1=t),t&&!U(n)}function U(n){return!!V(n)&&(n=hn.call(n),"[object Function]"==n||"[object GeneratorFunction]"==n||"[object AsyncFunction]"==n||"[object Proxy]"==n)}function V(n){var t=typeof n;return null!=n&&("object"==t||"function"==t)}function H(n){return null!=n&&typeof n=="object"}function K(n){ +return typeof n=="number"||H(n)&&"[object Number]"==hn.call(n)}function L(n){return typeof n=="string"||!Nn(n)&&H(n)&&"[object String]"==hn.call(n)}function Q(n){return typeof n=="string"?n:null==n?"":n+""}function W(n){return null==n?[]:u(n,Dn(n))}function X(n){return n}function Y(n,r,e){var u=Dn(r),o=h(r,u);null!=e||V(r)&&(o.length||!u.length)||(e=r,r=n,n=this,o=h(r,Dn(r)));var i=!(V(e)&&"chain"in e&&!e.chain),c=U(n);return mn(o,function(e){var u=r[e];n[e]=u,c&&(n.prototype[e]=function(){var r=this.__chain__; +if(i||r){var e=n(this.__wrapped__);return(e.__actions__=A(this.__actions__)).push({func:u,args:arguments,thisArg:n}),e.__chain__=r,e}return u.apply(n,t([this.value()],arguments))})}),n}var Z,nn=1/0,tn=/[&<>"']/g,rn=RegExp(tn.source),en=/^(?:0|[1-9]\d*)$/,un=typeof self=="object"&&self&&self.Object===Object&&self,on=typeof global=="object"&&global&&global.Object===Object&&global||un||Function("return this")(),cn=(un=typeof exports=="object"&&exports&&!exports.nodeType&&exports)&&typeof module=="object"&&module&&!module.nodeType&&module,fn=function(n){ +return function(t){return null==n?Z:n[t]}}({"&":"&","<":"<",">":">",'"':""","'":"'"}),an=Array.prototype,ln=Object.prototype,pn=ln.hasOwnProperty,sn=0,hn=ln.toString,vn=on._,bn=Object.create,yn=ln.propertyIsEnumerable,gn=on.isFinite,_n=function(n,t){return function(r){return n(t(r))}}(Object.keys,Object),jn=Math.max,dn=function(){function n(){}return function(t){return V(t)?bn?bn(t):(n.prototype=t,t=new n,n.prototype=Z,t):{}}}();i.prototype=dn(o.prototype),i.prototype.constructor=i; +var mn=function(n,t){return function(r,e){if(null==r)return r;if(!M(r))return n(r,e);for(var u=r.length,o=t?u:-1,i=Object(r);(t?o--:++or&&(r=jn(e+r,0));n:{for(t=g(t),e=n.length,r+=-1;++re||o&&c&&a||!u&&a||!i){r=1;break n}if(!o&&r { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ +var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } +}); + +module.exports = countBy; diff --git a/app/node_modules/lodash/create.js b/app/node_modules/lodash/create.js new file mode 100644 index 0000000..919edb8 --- /dev/null +++ b/app/node_modules/lodash/create.js @@ -0,0 +1,43 @@ +var baseAssign = require('./_baseAssign'), + baseCreate = require('./_baseCreate'); + +/** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ +function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : baseAssign(result, properties); +} + +module.exports = create; diff --git a/app/node_modules/lodash/curry.js b/app/node_modules/lodash/curry.js new file mode 100644 index 0000000..918db1a --- /dev/null +++ b/app/node_modules/lodash/curry.js @@ -0,0 +1,57 @@ +var createWrap = require('./_createWrap'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_CURRY_FLAG = 8; + +/** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ +function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; +} + +// Assign default placeholders. +curry.placeholder = {}; + +module.exports = curry; diff --git a/app/node_modules/lodash/curryRight.js b/app/node_modules/lodash/curryRight.js new file mode 100644 index 0000000..c85b6f3 --- /dev/null +++ b/app/node_modules/lodash/curryRight.js @@ -0,0 +1,54 @@ +var createWrap = require('./_createWrap'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_CURRY_RIGHT_FLAG = 16; + +/** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ +function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; +} + +// Assign default placeholders. +curryRight.placeholder = {}; + +module.exports = curryRight; diff --git a/app/node_modules/lodash/date.js b/app/node_modules/lodash/date.js new file mode 100644 index 0000000..cbf5b41 --- /dev/null +++ b/app/node_modules/lodash/date.js @@ -0,0 +1,3 @@ +module.exports = { + 'now': require('./now') +}; diff --git a/app/node_modules/lodash/debounce.js b/app/node_modules/lodash/debounce.js new file mode 100644 index 0000000..8f751d5 --- /dev/null +++ b/app/node_modules/lodash/debounce.js @@ -0,0 +1,191 @@ +var isObject = require('./isObject'), + now = require('./now'), + toNumber = require('./toNumber'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ +function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + timeWaiting = wait - timeSinceLastCall; + + return maxing + ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) + : timeWaiting; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + clearTimeout(timerId); + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; +} + +module.exports = debounce; diff --git a/app/node_modules/lodash/deburr.js b/app/node_modules/lodash/deburr.js new file mode 100644 index 0000000..f85e314 --- /dev/null +++ b/app/node_modules/lodash/deburr.js @@ -0,0 +1,45 @@ +var deburrLetter = require('./_deburrLetter'), + toString = require('./toString'); + +/** Used to match Latin Unicode letters (excluding mathematical operators). */ +var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + +/** Used to compose unicode character classes. */ +var rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; + +/** Used to compose unicode capture groups. */ +var rsCombo = '[' + rsComboRange + ']'; + +/** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ +var reComboMark = RegExp(rsCombo, 'g'); + +/** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ +function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); +} + +module.exports = deburr; diff --git a/app/node_modules/lodash/defaultTo.js b/app/node_modules/lodash/defaultTo.js new file mode 100644 index 0000000..5b33359 --- /dev/null +++ b/app/node_modules/lodash/defaultTo.js @@ -0,0 +1,25 @@ +/** + * Checks `value` to determine whether a default value should be returned in + * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, + * or `undefined`. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Util + * @param {*} value The value to check. + * @param {*} defaultValue The default value. + * @returns {*} Returns the resolved value. + * @example + * + * _.defaultTo(1, 10); + * // => 1 + * + * _.defaultTo(undefined, 10); + * // => 10 + */ +function defaultTo(value, defaultValue) { + return (value == null || value !== value) ? defaultValue : value; +} + +module.exports = defaultTo; diff --git a/app/node_modules/lodash/defaults.js b/app/node_modules/lodash/defaults.js new file mode 100644 index 0000000..c74df04 --- /dev/null +++ b/app/node_modules/lodash/defaults.js @@ -0,0 +1,64 @@ +var baseRest = require('./_baseRest'), + eq = require('./eq'), + isIterateeCall = require('./_isIterateeCall'), + keysIn = require('./keysIn'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var defaults = baseRest(function(object, sources) { + object = Object(object); + + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + + if (value === undefined || + (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { + object[key] = source[key]; + } + } + } + + return object; +}); + +module.exports = defaults; diff --git a/app/node_modules/lodash/defaultsDeep.js b/app/node_modules/lodash/defaultsDeep.js new file mode 100644 index 0000000..9b5fa3e --- /dev/null +++ b/app/node_modules/lodash/defaultsDeep.js @@ -0,0 +1,30 @@ +var apply = require('./_apply'), + baseRest = require('./_baseRest'), + customDefaultsMerge = require('./_customDefaultsMerge'), + mergeWith = require('./mergeWith'); + +/** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ +var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); +}); + +module.exports = defaultsDeep; diff --git a/app/node_modules/lodash/defer.js b/app/node_modules/lodash/defer.js new file mode 100644 index 0000000..f6d6c6f --- /dev/null +++ b/app/node_modules/lodash/defer.js @@ -0,0 +1,26 @@ +var baseDelay = require('./_baseDelay'), + baseRest = require('./_baseRest'); + +/** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ +var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); +}); + +module.exports = defer; diff --git a/app/node_modules/lodash/delay.js b/app/node_modules/lodash/delay.js new file mode 100644 index 0000000..bd55479 --- /dev/null +++ b/app/node_modules/lodash/delay.js @@ -0,0 +1,28 @@ +var baseDelay = require('./_baseDelay'), + baseRest = require('./_baseRest'), + toNumber = require('./toNumber'); + +/** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ +var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); +}); + +module.exports = delay; diff --git a/app/node_modules/lodash/difference.js b/app/node_modules/lodash/difference.js new file mode 100644 index 0000000..fa28bb3 --- /dev/null +++ b/app/node_modules/lodash/difference.js @@ -0,0 +1,33 @@ +var baseDifference = require('./_baseDifference'), + baseFlatten = require('./_baseFlatten'), + baseRest = require('./_baseRest'), + isArrayLikeObject = require('./isArrayLikeObject'); + +/** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ +var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; +}); + +module.exports = difference; diff --git a/app/node_modules/lodash/differenceBy.js b/app/node_modules/lodash/differenceBy.js new file mode 100644 index 0000000..2cd63e7 --- /dev/null +++ b/app/node_modules/lodash/differenceBy.js @@ -0,0 +1,44 @@ +var baseDifference = require('./_baseDifference'), + baseFlatten = require('./_baseFlatten'), + baseIteratee = require('./_baseIteratee'), + baseRest = require('./_baseRest'), + isArrayLikeObject = require('./isArrayLikeObject'), + last = require('./last'); + +/** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ +var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), baseIteratee(iteratee, 2)) + : []; +}); + +module.exports = differenceBy; diff --git a/app/node_modules/lodash/differenceWith.js b/app/node_modules/lodash/differenceWith.js new file mode 100644 index 0000000..c0233f4 --- /dev/null +++ b/app/node_modules/lodash/differenceWith.js @@ -0,0 +1,40 @@ +var baseDifference = require('./_baseDifference'), + baseFlatten = require('./_baseFlatten'), + baseRest = require('./_baseRest'), + isArrayLikeObject = require('./isArrayLikeObject'), + last = require('./last'); + +/** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ +var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; +}); + +module.exports = differenceWith; diff --git a/app/node_modules/lodash/divide.js b/app/node_modules/lodash/divide.js new file mode 100644 index 0000000..8cae0cd --- /dev/null +++ b/app/node_modules/lodash/divide.js @@ -0,0 +1,22 @@ +var createMathOperation = require('./_createMathOperation'); + +/** + * Divide two numbers. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Math + * @param {number} dividend The first number in a division. + * @param {number} divisor The second number in a division. + * @returns {number} Returns the quotient. + * @example + * + * _.divide(6, 4); + * // => 1.5 + */ +var divide = createMathOperation(function(dividend, divisor) { + return dividend / divisor; +}, 1); + +module.exports = divide; diff --git a/app/node_modules/lodash/drop.js b/app/node_modules/lodash/drop.js new file mode 100644 index 0000000..d5c3cba --- /dev/null +++ b/app/node_modules/lodash/drop.js @@ -0,0 +1,38 @@ +var baseSlice = require('./_baseSlice'), + toInteger = require('./toInteger'); + +/** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ +function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); +} + +module.exports = drop; diff --git a/app/node_modules/lodash/dropRight.js b/app/node_modules/lodash/dropRight.js new file mode 100644 index 0000000..441fe99 --- /dev/null +++ b/app/node_modules/lodash/dropRight.js @@ -0,0 +1,39 @@ +var baseSlice = require('./_baseSlice'), + toInteger = require('./toInteger'); + +/** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ +function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); +} + +module.exports = dropRight; diff --git a/app/node_modules/lodash/dropRightWhile.js b/app/node_modules/lodash/dropRightWhile.js new file mode 100644 index 0000000..9ad36a0 --- /dev/null +++ b/app/node_modules/lodash/dropRightWhile.js @@ -0,0 +1,45 @@ +var baseIteratee = require('./_baseIteratee'), + baseWhile = require('./_baseWhile'); + +/** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ +function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, baseIteratee(predicate, 3), true, true) + : []; +} + +module.exports = dropRightWhile; diff --git a/app/node_modules/lodash/dropWhile.js b/app/node_modules/lodash/dropWhile.js new file mode 100644 index 0000000..903ef56 --- /dev/null +++ b/app/node_modules/lodash/dropWhile.js @@ -0,0 +1,45 @@ +var baseIteratee = require('./_baseIteratee'), + baseWhile = require('./_baseWhile'); + +/** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ +function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, baseIteratee(predicate, 3), true) + : []; +} + +module.exports = dropWhile; diff --git a/app/node_modules/lodash/each.js b/app/node_modules/lodash/each.js new file mode 100644 index 0000000..8800f42 --- /dev/null +++ b/app/node_modules/lodash/each.js @@ -0,0 +1 @@ +module.exports = require('./forEach'); diff --git a/app/node_modules/lodash/eachRight.js b/app/node_modules/lodash/eachRight.js new file mode 100644 index 0000000..3252b2a --- /dev/null +++ b/app/node_modules/lodash/eachRight.js @@ -0,0 +1 @@ +module.exports = require('./forEachRight'); diff --git a/app/node_modules/lodash/endsWith.js b/app/node_modules/lodash/endsWith.js new file mode 100644 index 0000000..76fc866 --- /dev/null +++ b/app/node_modules/lodash/endsWith.js @@ -0,0 +1,43 @@ +var baseClamp = require('./_baseClamp'), + baseToString = require('./_baseToString'), + toInteger = require('./toInteger'), + toString = require('./toString'); + +/** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ +function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; +} + +module.exports = endsWith; diff --git a/app/node_modules/lodash/entries.js b/app/node_modules/lodash/entries.js new file mode 100644 index 0000000..7a88df2 --- /dev/null +++ b/app/node_modules/lodash/entries.js @@ -0,0 +1 @@ +module.exports = require('./toPairs'); diff --git a/app/node_modules/lodash/entriesIn.js b/app/node_modules/lodash/entriesIn.js new file mode 100644 index 0000000..f6c6331 --- /dev/null +++ b/app/node_modules/lodash/entriesIn.js @@ -0,0 +1 @@ +module.exports = require('./toPairsIn'); diff --git a/app/node_modules/lodash/eq.js b/app/node_modules/lodash/eq.js new file mode 100644 index 0000000..a940688 --- /dev/null +++ b/app/node_modules/lodash/eq.js @@ -0,0 +1,37 @@ +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +module.exports = eq; diff --git a/app/node_modules/lodash/escape.js b/app/node_modules/lodash/escape.js new file mode 100644 index 0000000..9247e00 --- /dev/null +++ b/app/node_modules/lodash/escape.js @@ -0,0 +1,43 @@ +var escapeHtmlChar = require('./_escapeHtmlChar'), + toString = require('./toString'); + +/** Used to match HTML entities and HTML characters. */ +var reUnescapedHtml = /[&<>"']/g, + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + +/** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ +function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; +} + +module.exports = escape; diff --git a/app/node_modules/lodash/escapeRegExp.js b/app/node_modules/lodash/escapeRegExp.js new file mode 100644 index 0000000..0a58c69 --- /dev/null +++ b/app/node_modules/lodash/escapeRegExp.js @@ -0,0 +1,32 @@ +var toString = require('./toString'); + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + +/** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ +function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; +} + +module.exports = escapeRegExp; diff --git a/app/node_modules/lodash/every.js b/app/node_modules/lodash/every.js new file mode 100644 index 0000000..25080da --- /dev/null +++ b/app/node_modules/lodash/every.js @@ -0,0 +1,56 @@ +var arrayEvery = require('./_arrayEvery'), + baseEvery = require('./_baseEvery'), + baseIteratee = require('./_baseIteratee'), + isArray = require('./isArray'), + isIterateeCall = require('./_isIterateeCall'); + +/** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ +function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, baseIteratee(predicate, 3)); +} + +module.exports = every; diff --git a/app/node_modules/lodash/extend.js b/app/node_modules/lodash/extend.js new file mode 100644 index 0000000..e00166c --- /dev/null +++ b/app/node_modules/lodash/extend.js @@ -0,0 +1 @@ +module.exports = require('./assignIn'); diff --git a/app/node_modules/lodash/extendWith.js b/app/node_modules/lodash/extendWith.js new file mode 100644 index 0000000..dbdcb3b --- /dev/null +++ b/app/node_modules/lodash/extendWith.js @@ -0,0 +1 @@ +module.exports = require('./assignInWith'); diff --git a/app/node_modules/lodash/fill.js b/app/node_modules/lodash/fill.js new file mode 100644 index 0000000..ae13aa1 --- /dev/null +++ b/app/node_modules/lodash/fill.js @@ -0,0 +1,45 @@ +var baseFill = require('./_baseFill'), + isIterateeCall = require('./_isIterateeCall'); + +/** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ +function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); +} + +module.exports = fill; diff --git a/app/node_modules/lodash/filter.js b/app/node_modules/lodash/filter.js new file mode 100644 index 0000000..52616be --- /dev/null +++ b/app/node_modules/lodash/filter.js @@ -0,0 +1,48 @@ +var arrayFilter = require('./_arrayFilter'), + baseFilter = require('./_baseFilter'), + baseIteratee = require('./_baseIteratee'), + isArray = require('./isArray'); + +/** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + */ +function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, baseIteratee(predicate, 3)); +} + +module.exports = filter; diff --git a/app/node_modules/lodash/find.js b/app/node_modules/lodash/find.js new file mode 100644 index 0000000..de732cc --- /dev/null +++ b/app/node_modules/lodash/find.js @@ -0,0 +1,42 @@ +var createFind = require('./_createFind'), + findIndex = require('./findIndex'); + +/** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ +var find = createFind(findIndex); + +module.exports = find; diff --git a/app/node_modules/lodash/findIndex.js b/app/node_modules/lodash/findIndex.js new file mode 100644 index 0000000..4689069 --- /dev/null +++ b/app/node_modules/lodash/findIndex.js @@ -0,0 +1,55 @@ +var baseFindIndex = require('./_baseFindIndex'), + baseIteratee = require('./_baseIteratee'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ +function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, baseIteratee(predicate, 3), index); +} + +module.exports = findIndex; diff --git a/app/node_modules/lodash/findKey.js b/app/node_modules/lodash/findKey.js new file mode 100644 index 0000000..cac0248 --- /dev/null +++ b/app/node_modules/lodash/findKey.js @@ -0,0 +1,44 @@ +var baseFindKey = require('./_baseFindKey'), + baseForOwn = require('./_baseForOwn'), + baseIteratee = require('./_baseIteratee'); + +/** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ +function findKey(object, predicate) { + return baseFindKey(object, baseIteratee(predicate, 3), baseForOwn); +} + +module.exports = findKey; diff --git a/app/node_modules/lodash/findLast.js b/app/node_modules/lodash/findLast.js new file mode 100644 index 0000000..70b4271 --- /dev/null +++ b/app/node_modules/lodash/findLast.js @@ -0,0 +1,25 @@ +var createFind = require('./_createFind'), + findLastIndex = require('./findLastIndex'); + +/** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ +var findLast = createFind(findLastIndex); + +module.exports = findLast; diff --git a/app/node_modules/lodash/findLastIndex.js b/app/node_modules/lodash/findLastIndex.js new file mode 100644 index 0000000..7da3431 --- /dev/null +++ b/app/node_modules/lodash/findLastIndex.js @@ -0,0 +1,59 @@ +var baseFindIndex = require('./_baseFindIndex'), + baseIteratee = require('./_baseIteratee'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ +function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, baseIteratee(predicate, 3), index, true); +} + +module.exports = findLastIndex; diff --git a/app/node_modules/lodash/findLastKey.js b/app/node_modules/lodash/findLastKey.js new file mode 100644 index 0000000..66fb9fb --- /dev/null +++ b/app/node_modules/lodash/findLastKey.js @@ -0,0 +1,44 @@ +var baseFindKey = require('./_baseFindKey'), + baseForOwnRight = require('./_baseForOwnRight'), + baseIteratee = require('./_baseIteratee'); + +/** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ +function findLastKey(object, predicate) { + return baseFindKey(object, baseIteratee(predicate, 3), baseForOwnRight); +} + +module.exports = findLastKey; diff --git a/app/node_modules/lodash/first.js b/app/node_modules/lodash/first.js new file mode 100644 index 0000000..53f4ad1 --- /dev/null +++ b/app/node_modules/lodash/first.js @@ -0,0 +1 @@ +module.exports = require('./head'); diff --git a/app/node_modules/lodash/flatMap.js b/app/node_modules/lodash/flatMap.js new file mode 100644 index 0000000..e668506 --- /dev/null +++ b/app/node_modules/lodash/flatMap.js @@ -0,0 +1,29 @@ +var baseFlatten = require('./_baseFlatten'), + map = require('./map'); + +/** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ +function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); +} + +module.exports = flatMap; diff --git a/app/node_modules/lodash/flatMapDeep.js b/app/node_modules/lodash/flatMapDeep.js new file mode 100644 index 0000000..4653d60 --- /dev/null +++ b/app/node_modules/lodash/flatMapDeep.js @@ -0,0 +1,31 @@ +var baseFlatten = require('./_baseFlatten'), + map = require('./map'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ +function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); +} + +module.exports = flatMapDeep; diff --git a/app/node_modules/lodash/flatMapDepth.js b/app/node_modules/lodash/flatMapDepth.js new file mode 100644 index 0000000..6d72005 --- /dev/null +++ b/app/node_modules/lodash/flatMapDepth.js @@ -0,0 +1,31 @@ +var baseFlatten = require('./_baseFlatten'), + map = require('./map'), + toInteger = require('./toInteger'); + +/** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ +function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); +} + +module.exports = flatMapDepth; diff --git a/app/node_modules/lodash/flatten.js b/app/node_modules/lodash/flatten.js new file mode 100644 index 0000000..3f09f7f --- /dev/null +++ b/app/node_modules/lodash/flatten.js @@ -0,0 +1,22 @@ +var baseFlatten = require('./_baseFlatten'); + +/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ +function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; +} + +module.exports = flatten; diff --git a/app/node_modules/lodash/flattenDeep.js b/app/node_modules/lodash/flattenDeep.js new file mode 100644 index 0000000..8ad585c --- /dev/null +++ b/app/node_modules/lodash/flattenDeep.js @@ -0,0 +1,25 @@ +var baseFlatten = require('./_baseFlatten'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ +function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; +} + +module.exports = flattenDeep; diff --git a/app/node_modules/lodash/flattenDepth.js b/app/node_modules/lodash/flattenDepth.js new file mode 100644 index 0000000..441fdcc --- /dev/null +++ b/app/node_modules/lodash/flattenDepth.js @@ -0,0 +1,33 @@ +var baseFlatten = require('./_baseFlatten'), + toInteger = require('./toInteger'); + +/** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ +function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); +} + +module.exports = flattenDepth; diff --git a/app/node_modules/lodash/flip.js b/app/node_modules/lodash/flip.js new file mode 100644 index 0000000..c28dd78 --- /dev/null +++ b/app/node_modules/lodash/flip.js @@ -0,0 +1,28 @@ +var createWrap = require('./_createWrap'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_FLIP_FLAG = 512; + +/** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ +function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); +} + +module.exports = flip; diff --git a/app/node_modules/lodash/floor.js b/app/node_modules/lodash/floor.js new file mode 100644 index 0000000..ab6dfa2 --- /dev/null +++ b/app/node_modules/lodash/floor.js @@ -0,0 +1,26 @@ +var createRound = require('./_createRound'); + +/** + * Computes `number` rounded down to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round down. + * @param {number} [precision=0] The precision to round down to. + * @returns {number} Returns the rounded down number. + * @example + * + * _.floor(4.006); + * // => 4 + * + * _.floor(0.046, 2); + * // => 0.04 + * + * _.floor(4060, -2); + * // => 4000 + */ +var floor = createRound('floor'); + +module.exports = floor; diff --git a/app/node_modules/lodash/flow.js b/app/node_modules/lodash/flow.js new file mode 100644 index 0000000..74b6b62 --- /dev/null +++ b/app/node_modules/lodash/flow.js @@ -0,0 +1,27 @@ +var createFlow = require('./_createFlow'); + +/** + * Creates a function that returns the result of invoking the given functions + * with the `this` binding of the created function, where each successive + * invocation is supplied the return value of the previous. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {...(Function|Function[])} [funcs] The functions to invoke. + * @returns {Function} Returns the new composite function. + * @see _.flowRight + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flow([_.add, square]); + * addSquare(1, 2); + * // => 9 + */ +var flow = createFlow(); + +module.exports = flow; diff --git a/app/node_modules/lodash/flowRight.js b/app/node_modules/lodash/flowRight.js new file mode 100644 index 0000000..1146141 --- /dev/null +++ b/app/node_modules/lodash/flowRight.js @@ -0,0 +1,26 @@ +var createFlow = require('./_createFlow'); + +/** + * This method is like `_.flow` except that it creates a function that + * invokes the given functions from right to left. + * + * @static + * @since 3.0.0 + * @memberOf _ + * @category Util + * @param {...(Function|Function[])} [funcs] The functions to invoke. + * @returns {Function} Returns the new composite function. + * @see _.flow + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flowRight([square, _.add]); + * addSquare(1, 2); + * // => 9 + */ +var flowRight = createFlow(true); + +module.exports = flowRight; diff --git a/app/node_modules/lodash/forEach.js b/app/node_modules/lodash/forEach.js new file mode 100644 index 0000000..c64eaa7 --- /dev/null +++ b/app/node_modules/lodash/forEach.js @@ -0,0 +1,41 @@ +var arrayEach = require('./_arrayEach'), + baseEach = require('./_baseEach'), + castFunction = require('./_castFunction'), + isArray = require('./isArray'); + +/** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ +function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, castFunction(iteratee)); +} + +module.exports = forEach; diff --git a/app/node_modules/lodash/forEachRight.js b/app/node_modules/lodash/forEachRight.js new file mode 100644 index 0000000..7390eba --- /dev/null +++ b/app/node_modules/lodash/forEachRight.js @@ -0,0 +1,31 @@ +var arrayEachRight = require('./_arrayEachRight'), + baseEachRight = require('./_baseEachRight'), + castFunction = require('./_castFunction'), + isArray = require('./isArray'); + +/** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ +function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, castFunction(iteratee)); +} + +module.exports = forEachRight; diff --git a/app/node_modules/lodash/forIn.js b/app/node_modules/lodash/forIn.js new file mode 100644 index 0000000..583a596 --- /dev/null +++ b/app/node_modules/lodash/forIn.js @@ -0,0 +1,39 @@ +var baseFor = require('./_baseFor'), + castFunction = require('./_castFunction'), + keysIn = require('./keysIn'); + +/** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ +function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, castFunction(iteratee), keysIn); +} + +module.exports = forIn; diff --git a/app/node_modules/lodash/forInRight.js b/app/node_modules/lodash/forInRight.js new file mode 100644 index 0000000..4aedf58 --- /dev/null +++ b/app/node_modules/lodash/forInRight.js @@ -0,0 +1,37 @@ +var baseForRight = require('./_baseForRight'), + castFunction = require('./_castFunction'), + keysIn = require('./keysIn'); + +/** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ +function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, castFunction(iteratee), keysIn); +} + +module.exports = forInRight; diff --git a/app/node_modules/lodash/forOwn.js b/app/node_modules/lodash/forOwn.js new file mode 100644 index 0000000..94eed84 --- /dev/null +++ b/app/node_modules/lodash/forOwn.js @@ -0,0 +1,36 @@ +var baseForOwn = require('./_baseForOwn'), + castFunction = require('./_castFunction'); + +/** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ +function forOwn(object, iteratee) { + return object && baseForOwn(object, castFunction(iteratee)); +} + +module.exports = forOwn; diff --git a/app/node_modules/lodash/forOwnRight.js b/app/node_modules/lodash/forOwnRight.js new file mode 100644 index 0000000..86f338f --- /dev/null +++ b/app/node_modules/lodash/forOwnRight.js @@ -0,0 +1,34 @@ +var baseForOwnRight = require('./_baseForOwnRight'), + castFunction = require('./_castFunction'); + +/** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ +function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, castFunction(iteratee)); +} + +module.exports = forOwnRight; diff --git a/app/node_modules/lodash/fp.js b/app/node_modules/lodash/fp.js new file mode 100644 index 0000000..e372dbb --- /dev/null +++ b/app/node_modules/lodash/fp.js @@ -0,0 +1,2 @@ +var _ = require('./lodash.min').runInContext(); +module.exports = require('./fp/_baseConvert')(_, _); diff --git a/app/node_modules/lodash/fp/F.js b/app/node_modules/lodash/fp/F.js new file mode 100644 index 0000000..a05a63a --- /dev/null +++ b/app/node_modules/lodash/fp/F.js @@ -0,0 +1 @@ +module.exports = require('./stubFalse'); diff --git a/app/node_modules/lodash/fp/T.js b/app/node_modules/lodash/fp/T.js new file mode 100644 index 0000000..e2ba8ea --- /dev/null +++ b/app/node_modules/lodash/fp/T.js @@ -0,0 +1 @@ +module.exports = require('./stubTrue'); diff --git a/app/node_modules/lodash/fp/__.js b/app/node_modules/lodash/fp/__.js new file mode 100644 index 0000000..4af98de --- /dev/null +++ b/app/node_modules/lodash/fp/__.js @@ -0,0 +1 @@ +module.exports = require('./placeholder'); diff --git a/app/node_modules/lodash/fp/_baseConvert.js b/app/node_modules/lodash/fp/_baseConvert.js new file mode 100644 index 0000000..9baf8e1 --- /dev/null +++ b/app/node_modules/lodash/fp/_baseConvert.js @@ -0,0 +1,569 @@ +var mapping = require('./_mapping'), + fallbackHolder = require('./placeholder'); + +/** Built-in value reference. */ +var push = Array.prototype.push; + +/** + * Creates a function, with an arity of `n`, that invokes `func` with the + * arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} n The arity of the new function. + * @returns {Function} Returns the new function. + */ +function baseArity(func, n) { + return n == 2 + ? function(a, b) { return func.apply(undefined, arguments); } + : function(a) { return func.apply(undefined, arguments); }; +} + +/** + * Creates a function that invokes `func`, with up to `n` arguments, ignoring + * any additional arguments. + * + * @private + * @param {Function} func The function to cap arguments for. + * @param {number} n The arity cap. + * @returns {Function} Returns the new function. + */ +function baseAry(func, n) { + return n == 2 + ? function(a, b) { return func(a, b); } + : function(a) { return func(a); }; +} + +/** + * Creates a clone of `array`. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the cloned array. + */ +function cloneArray(array) { + var length = array ? array.length : 0, + result = Array(length); + + while (length--) { + result[length] = array[length]; + } + return result; +} + +/** + * Creates a function that clones a given object using the assignment `func`. + * + * @private + * @param {Function} func The assignment function. + * @returns {Function} Returns the new cloner function. + */ +function createCloner(func) { + return function(object) { + return func({}, object); + }; +} + +/** + * A specialized version of `_.spread` which flattens the spread array into + * the arguments of the invoked `func`. + * + * @private + * @param {Function} func The function to spread arguments over. + * @param {number} start The start position of the spread. + * @returns {Function} Returns the new function. + */ +function flatSpread(func, start) { + return function() { + var length = arguments.length, + lastIndex = length - 1, + args = Array(length); + + while (length--) { + args[length] = arguments[length]; + } + var array = args[start], + otherArgs = args.slice(0, start); + + if (array) { + push.apply(otherArgs, array); + } + if (start != lastIndex) { + push.apply(otherArgs, args.slice(start + 1)); + } + return func.apply(this, otherArgs); + }; +} + +/** + * Creates a function that wraps `func` and uses `cloner` to clone the first + * argument it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} cloner The function to clone arguments. + * @returns {Function} Returns the new immutable function. + */ +function wrapImmutable(func, cloner) { + return function() { + var length = arguments.length; + if (!length) { + return; + } + var args = Array(length); + while (length--) { + args[length] = arguments[length]; + } + var result = args[0] = cloner.apply(undefined, args); + func.apply(undefined, args); + return result; + }; +} + +/** + * The base implementation of `convert` which accepts a `util` object of methods + * required to perform conversions. + * + * @param {Object} util The util object. + * @param {string} name The name of the function to convert. + * @param {Function} func The function to convert. + * @param {Object} [options] The options object. + * @param {boolean} [options.cap=true] Specify capping iteratee arguments. + * @param {boolean} [options.curry=true] Specify currying. + * @param {boolean} [options.fixed=true] Specify fixed arity. + * @param {boolean} [options.immutable=true] Specify immutable operations. + * @param {boolean} [options.rearg=true] Specify rearranging arguments. + * @returns {Function|Object} Returns the converted function or object. + */ +function baseConvert(util, name, func, options) { + var isLib = typeof name == 'function', + isObj = name === Object(name); + + if (isObj) { + options = func; + func = name; + name = undefined; + } + if (func == null) { + throw new TypeError; + } + options || (options = {}); + + var config = { + 'cap': 'cap' in options ? options.cap : true, + 'curry': 'curry' in options ? options.curry : true, + 'fixed': 'fixed' in options ? options.fixed : true, + 'immutable': 'immutable' in options ? options.immutable : true, + 'rearg': 'rearg' in options ? options.rearg : true + }; + + var defaultHolder = isLib ? func : fallbackHolder, + forceCurry = ('curry' in options) && options.curry, + forceFixed = ('fixed' in options) && options.fixed, + forceRearg = ('rearg' in options) && options.rearg, + pristine = isLib ? func.runInContext() : undefined; + + var helpers = isLib ? func : { + 'ary': util.ary, + 'assign': util.assign, + 'clone': util.clone, + 'curry': util.curry, + 'forEach': util.forEach, + 'isArray': util.isArray, + 'isError': util.isError, + 'isFunction': util.isFunction, + 'isWeakMap': util.isWeakMap, + 'iteratee': util.iteratee, + 'keys': util.keys, + 'rearg': util.rearg, + 'toInteger': util.toInteger, + 'toPath': util.toPath + }; + + var ary = helpers.ary, + assign = helpers.assign, + clone = helpers.clone, + curry = helpers.curry, + each = helpers.forEach, + isArray = helpers.isArray, + isError = helpers.isError, + isFunction = helpers.isFunction, + isWeakMap = helpers.isWeakMap, + keys = helpers.keys, + rearg = helpers.rearg, + toInteger = helpers.toInteger, + toPath = helpers.toPath; + + var aryMethodKeys = keys(mapping.aryMethod); + + var wrappers = { + 'castArray': function(castArray) { + return function() { + var value = arguments[0]; + return isArray(value) + ? castArray(cloneArray(value)) + : castArray.apply(undefined, arguments); + }; + }, + 'iteratee': function(iteratee) { + return function() { + var func = arguments[0], + arity = arguments[1], + result = iteratee(func, arity), + length = result.length; + + if (config.cap && typeof arity == 'number') { + arity = arity > 2 ? (arity - 2) : 1; + return (length && length <= arity) ? result : baseAry(result, arity); + } + return result; + }; + }, + 'mixin': function(mixin) { + return function(source) { + var func = this; + if (!isFunction(func)) { + return mixin(func, Object(source)); + } + var pairs = []; + each(keys(source), function(key) { + if (isFunction(source[key])) { + pairs.push([key, func.prototype[key]]); + } + }); + + mixin(func, Object(source)); + + each(pairs, function(pair) { + var value = pair[1]; + if (isFunction(value)) { + func.prototype[pair[0]] = value; + } else { + delete func.prototype[pair[0]]; + } + }); + return func; + }; + }, + 'nthArg': function(nthArg) { + return function(n) { + var arity = n < 0 ? 1 : (toInteger(n) + 1); + return curry(nthArg(n), arity); + }; + }, + 'rearg': function(rearg) { + return function(func, indexes) { + var arity = indexes ? indexes.length : 0; + return curry(rearg(func, indexes), arity); + }; + }, + 'runInContext': function(runInContext) { + return function(context) { + return baseConvert(util, runInContext(context), options); + }; + } + }; + + /*--------------------------------------------------------------------------*/ + + /** + * Casts `func` to a function with an arity capped iteratee if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @returns {Function} Returns the cast function. + */ + function castCap(name, func) { + if (config.cap) { + var indexes = mapping.iterateeRearg[name]; + if (indexes) { + return iterateeRearg(func, indexes); + } + var n = !isLib && mapping.iterateeAry[name]; + if (n) { + return iterateeAry(func, n); + } + } + return func; + } + + /** + * Casts `func` to a curried function if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @param {number} n The arity of `func`. + * @returns {Function} Returns the cast function. + */ + function castCurry(name, func, n) { + return (forceCurry || (config.curry && n > 1)) + ? curry(func, n) + : func; + } + + /** + * Casts `func` to a fixed arity function if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @param {number} n The arity cap. + * @returns {Function} Returns the cast function. + */ + function castFixed(name, func, n) { + if (config.fixed && (forceFixed || !mapping.skipFixed[name])) { + var data = mapping.methodSpread[name], + start = data && data.start; + + return start === undefined ? ary(func, n) : flatSpread(func, start); + } + return func; + } + + /** + * Casts `func` to an rearged function if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @param {number} n The arity of `func`. + * @returns {Function} Returns the cast function. + */ + function castRearg(name, func, n) { + return (config.rearg && n > 1 && (forceRearg || !mapping.skipRearg[name])) + ? rearg(func, mapping.methodRearg[name] || mapping.aryRearg[n]) + : func; + } + + /** + * Creates a clone of `object` by `path`. + * + * @private + * @param {Object} object The object to clone. + * @param {Array|string} path The path to clone by. + * @returns {Object} Returns the cloned object. + */ + function cloneByPath(object, path) { + path = toPath(path); + + var index = -1, + length = path.length, + lastIndex = length - 1, + result = clone(Object(object)), + nested = result; + + while (nested != null && ++index < length) { + var key = path[index], + value = nested[key]; + + if (value != null && + !(isFunction(value) || isError(value) || isWeakMap(value))) { + nested[key] = clone(index == lastIndex ? value : Object(value)); + } + nested = nested[key]; + } + return result; + } + + /** + * Converts `lodash` to an immutable auto-curried iteratee-first data-last + * version with conversion `options` applied. + * + * @param {Object} [options] The options object. See `baseConvert` for more details. + * @returns {Function} Returns the converted `lodash`. + */ + function convertLib(options) { + return _.runInContext.convert(options)(undefined); + } + + /** + * Create a converter function for `func` of `name`. + * + * @param {string} name The name of the function to convert. + * @param {Function} func The function to convert. + * @returns {Function} Returns the new converter function. + */ + function createConverter(name, func) { + var realName = mapping.aliasToReal[name] || name, + methodName = mapping.remap[realName] || realName, + oldOptions = options; + + return function(options) { + var newUtil = isLib ? pristine : helpers, + newFunc = isLib ? pristine[methodName] : func, + newOptions = assign(assign({}, oldOptions), options); + + return baseConvert(newUtil, realName, newFunc, newOptions); + }; + } + + /** + * Creates a function that wraps `func` to invoke its iteratee, with up to `n` + * arguments, ignoring any additional arguments. + * + * @private + * @param {Function} func The function to cap iteratee arguments for. + * @param {number} n The arity cap. + * @returns {Function} Returns the new function. + */ + function iterateeAry(func, n) { + return overArg(func, function(func) { + return typeof func == 'function' ? baseAry(func, n) : func; + }); + } + + /** + * Creates a function that wraps `func` to invoke its iteratee with arguments + * arranged according to the specified `indexes` where the argument value at + * the first index is provided as the first argument, the argument value at + * the second index is provided as the second argument, and so on. + * + * @private + * @param {Function} func The function to rearrange iteratee arguments for. + * @param {number[]} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + */ + function iterateeRearg(func, indexes) { + return overArg(func, function(func) { + var n = indexes.length; + return baseArity(rearg(baseAry(func, n), indexes), n); + }); + } + + /** + * Creates a function that invokes `func` with its first argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function() { + var length = arguments.length; + if (!length) { + return func(); + } + var args = Array(length); + while (length--) { + args[length] = arguments[length]; + } + var index = config.rearg ? 0 : (length - 1); + args[index] = transform(args[index]); + return func.apply(undefined, args); + }; + } + + /** + * Creates a function that wraps `func` and applys the conversions + * rules by `name`. + * + * @private + * @param {string} name The name of the function to wrap. + * @param {Function} func The function to wrap. + * @returns {Function} Returns the converted function. + */ + function wrap(name, func, placeholder) { + var result, + realName = mapping.aliasToReal[name] || name, + wrapped = func, + wrapper = wrappers[realName]; + + if (wrapper) { + wrapped = wrapper(func); + } + else if (config.immutable) { + if (mapping.mutate.array[realName]) { + wrapped = wrapImmutable(func, cloneArray); + } + else if (mapping.mutate.object[realName]) { + wrapped = wrapImmutable(func, createCloner(func)); + } + else if (mapping.mutate.set[realName]) { + wrapped = wrapImmutable(func, cloneByPath); + } + } + each(aryMethodKeys, function(aryKey) { + each(mapping.aryMethod[aryKey], function(otherName) { + if (realName == otherName) { + var data = mapping.methodSpread[realName], + afterRearg = data && data.afterRearg; + + result = afterRearg + ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey) + : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey); + + result = castCap(realName, result); + result = castCurry(realName, result, aryKey); + return false; + } + }); + return !result; + }); + + result || (result = wrapped); + if (result == func) { + result = forceCurry ? curry(result, 1) : function() { + return func.apply(this, arguments); + }; + } + result.convert = createConverter(realName, func); + result.placeholder = func.placeholder = placeholder; + + return result; + } + + /*--------------------------------------------------------------------------*/ + + if (!isObj) { + return wrap(name, func, defaultHolder); + } + var _ = func; + + // Convert methods by ary cap. + var pairs = []; + each(aryMethodKeys, function(aryKey) { + each(mapping.aryMethod[aryKey], function(key) { + var func = _[mapping.remap[key] || key]; + if (func) { + pairs.push([key, wrap(key, func, _)]); + } + }); + }); + + // Convert remaining methods. + each(keys(_), function(key) { + var func = _[key]; + if (typeof func == 'function') { + var length = pairs.length; + while (length--) { + if (pairs[length][0] == key) { + return; + } + } + func.convert = createConverter(key, func); + pairs.push([key, func]); + } + }); + + // Assign to `_` leaving `_.prototype` unchanged to allow chaining. + each(pairs, function(pair) { + _[pair[0]] = pair[1]; + }); + + _.convert = convertLib; + _.placeholder = _; + + // Assign aliases. + each(keys(_), function(key) { + each(mapping.realToAlias[key] || [], function(alias) { + _[alias] = _[key]; + }); + }); + + return _; +} + +module.exports = baseConvert; diff --git a/app/node_modules/lodash/fp/_convertBrowser.js b/app/node_modules/lodash/fp/_convertBrowser.js new file mode 100644 index 0000000..bde030d --- /dev/null +++ b/app/node_modules/lodash/fp/_convertBrowser.js @@ -0,0 +1,18 @@ +var baseConvert = require('./_baseConvert'); + +/** + * Converts `lodash` to an immutable auto-curried iteratee-first data-last + * version with conversion `options` applied. + * + * @param {Function} lodash The lodash function to convert. + * @param {Object} [options] The options object. See `baseConvert` for more details. + * @returns {Function} Returns the converted `lodash`. + */ +function browserConvert(lodash, options) { + return baseConvert(lodash, lodash, options); +} + +if (typeof _ == 'function' && typeof _.runInContext == 'function') { + _ = browserConvert(_.runInContext()); +} +module.exports = browserConvert; diff --git a/app/node_modules/lodash/fp/_falseOptions.js b/app/node_modules/lodash/fp/_falseOptions.js new file mode 100644 index 0000000..773235e --- /dev/null +++ b/app/node_modules/lodash/fp/_falseOptions.js @@ -0,0 +1,7 @@ +module.exports = { + 'cap': false, + 'curry': false, + 'fixed': false, + 'immutable': false, + 'rearg': false +}; diff --git a/app/node_modules/lodash/fp/_mapping.js b/app/node_modules/lodash/fp/_mapping.js new file mode 100644 index 0000000..a642ec0 --- /dev/null +++ b/app/node_modules/lodash/fp/_mapping.js @@ -0,0 +1,358 @@ +/** Used to map aliases to their real names. */ +exports.aliasToReal = { + + // Lodash aliases. + 'each': 'forEach', + 'eachRight': 'forEachRight', + 'entries': 'toPairs', + 'entriesIn': 'toPairsIn', + 'extend': 'assignIn', + 'extendAll': 'assignInAll', + 'extendAllWith': 'assignInAllWith', + 'extendWith': 'assignInWith', + 'first': 'head', + + // Methods that are curried variants of others. + 'conforms': 'conformsTo', + 'matches': 'isMatch', + 'property': 'get', + + // Ramda aliases. + '__': 'placeholder', + 'F': 'stubFalse', + 'T': 'stubTrue', + 'all': 'every', + 'allPass': 'overEvery', + 'always': 'constant', + 'any': 'some', + 'anyPass': 'overSome', + 'apply': 'spread', + 'assoc': 'set', + 'assocPath': 'set', + 'complement': 'negate', + 'compose': 'flowRight', + 'contains': 'includes', + 'dissoc': 'unset', + 'dissocPath': 'unset', + 'dropLast': 'dropRight', + 'dropLastWhile': 'dropRightWhile', + 'equals': 'isEqual', + 'identical': 'eq', + 'indexBy': 'keyBy', + 'init': 'initial', + 'invertObj': 'invert', + 'juxt': 'over', + 'omitAll': 'omit', + 'nAry': 'ary', + 'path': 'get', + 'pathEq': 'matchesProperty', + 'pathOr': 'getOr', + 'paths': 'at', + 'pickAll': 'pick', + 'pipe': 'flow', + 'pluck': 'map', + 'prop': 'get', + 'propEq': 'matchesProperty', + 'propOr': 'getOr', + 'props': 'at', + 'symmetricDifference': 'xor', + 'symmetricDifferenceBy': 'xorBy', + 'symmetricDifferenceWith': 'xorWith', + 'takeLast': 'takeRight', + 'takeLastWhile': 'takeRightWhile', + 'unapply': 'rest', + 'unnest': 'flatten', + 'useWith': 'overArgs', + 'where': 'conformsTo', + 'whereEq': 'isMatch', + 'zipObj': 'zipObject' +}; + +/** Used to map ary to method names. */ +exports.aryMethod = { + '1': [ + 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create', + 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow', + 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll', + 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse', + 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart', + 'uniqueId', 'words', 'zipAll' + ], + '2': [ + 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith', + 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith', + 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN', + 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference', + 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq', + 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', + 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach', + 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get', + 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection', + 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy', + 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty', + 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit', + 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial', + 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll', + 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove', + 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex', + 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy', + 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight', + 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars', + 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith', + 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject', + 'zipObjectDeep' + ], + '3': [ + 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith', + 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr', + 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith', + 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth', + 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd', + 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight', + 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy', + 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy', + 'xorWith', 'zipWith' + ], + '4': [ + 'fill', 'setWith', 'updateWith' + ] +}; + +/** Used to map ary to rearg configs. */ +exports.aryRearg = { + '2': [1, 0], + '3': [2, 0, 1], + '4': [3, 2, 0, 1] +}; + +/** Used to map method names to their iteratee ary. */ +exports.iterateeAry = { + 'dropRightWhile': 1, + 'dropWhile': 1, + 'every': 1, + 'filter': 1, + 'find': 1, + 'findFrom': 1, + 'findIndex': 1, + 'findIndexFrom': 1, + 'findKey': 1, + 'findLast': 1, + 'findLastFrom': 1, + 'findLastIndex': 1, + 'findLastIndexFrom': 1, + 'findLastKey': 1, + 'flatMap': 1, + 'flatMapDeep': 1, + 'flatMapDepth': 1, + 'forEach': 1, + 'forEachRight': 1, + 'forIn': 1, + 'forInRight': 1, + 'forOwn': 1, + 'forOwnRight': 1, + 'map': 1, + 'mapKeys': 1, + 'mapValues': 1, + 'partition': 1, + 'reduce': 2, + 'reduceRight': 2, + 'reject': 1, + 'remove': 1, + 'some': 1, + 'takeRightWhile': 1, + 'takeWhile': 1, + 'times': 1, + 'transform': 2 +}; + +/** Used to map method names to iteratee rearg configs. */ +exports.iterateeRearg = { + 'mapKeys': [1], + 'reduceRight': [1, 0] +}; + +/** Used to map method names to rearg configs. */ +exports.methodRearg = { + 'assignInAllWith': [1, 0], + 'assignInWith': [1, 2, 0], + 'assignAllWith': [1, 0], + 'assignWith': [1, 2, 0], + 'differenceBy': [1, 2, 0], + 'differenceWith': [1, 2, 0], + 'getOr': [2, 1, 0], + 'intersectionBy': [1, 2, 0], + 'intersectionWith': [1, 2, 0], + 'isEqualWith': [1, 2, 0], + 'isMatchWith': [2, 1, 0], + 'mergeAllWith': [1, 0], + 'mergeWith': [1, 2, 0], + 'padChars': [2, 1, 0], + 'padCharsEnd': [2, 1, 0], + 'padCharsStart': [2, 1, 0], + 'pullAllBy': [2, 1, 0], + 'pullAllWith': [2, 1, 0], + 'rangeStep': [1, 2, 0], + 'rangeStepRight': [1, 2, 0], + 'setWith': [3, 1, 2, 0], + 'sortedIndexBy': [2, 1, 0], + 'sortedLastIndexBy': [2, 1, 0], + 'unionBy': [1, 2, 0], + 'unionWith': [1, 2, 0], + 'updateWith': [3, 1, 2, 0], + 'xorBy': [1, 2, 0], + 'xorWith': [1, 2, 0], + 'zipWith': [1, 2, 0] +}; + +/** Used to map method names to spread configs. */ +exports.methodSpread = { + 'assignAll': { 'start': 0 }, + 'assignAllWith': { 'start': 0 }, + 'assignInAll': { 'start': 0 }, + 'assignInAllWith': { 'start': 0 }, + 'defaultsAll': { 'start': 0 }, + 'defaultsDeepAll': { 'start': 0 }, + 'invokeArgs': { 'start': 2 }, + 'invokeArgsMap': { 'start': 2 }, + 'mergeAll': { 'start': 0 }, + 'mergeAllWith': { 'start': 0 }, + 'partial': { 'start': 1 }, + 'partialRight': { 'start': 1 }, + 'without': { 'start': 1 }, + 'zipAll': { 'start': 0 } +}; + +/** Used to identify methods which mutate arrays or objects. */ +exports.mutate = { + 'array': { + 'fill': true, + 'pull': true, + 'pullAll': true, + 'pullAllBy': true, + 'pullAllWith': true, + 'pullAt': true, + 'remove': true, + 'reverse': true + }, + 'object': { + 'assign': true, + 'assignAll': true, + 'assignAllWith': true, + 'assignIn': true, + 'assignInAll': true, + 'assignInAllWith': true, + 'assignInWith': true, + 'assignWith': true, + 'defaults': true, + 'defaultsAll': true, + 'defaultsDeep': true, + 'defaultsDeepAll': true, + 'merge': true, + 'mergeAll': true, + 'mergeAllWith': true, + 'mergeWith': true, + }, + 'set': { + 'set': true, + 'setWith': true, + 'unset': true, + 'update': true, + 'updateWith': true + } +}; + +/** Used to map real names to their aliases. */ +exports.realToAlias = (function() { + var hasOwnProperty = Object.prototype.hasOwnProperty, + object = exports.aliasToReal, + result = {}; + + for (var key in object) { + var value = object[key]; + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + } + return result; +}()); + +/** Used to map method names to other names. */ +exports.remap = { + 'assignAll': 'assign', + 'assignAllWith': 'assignWith', + 'assignInAll': 'assignIn', + 'assignInAllWith': 'assignInWith', + 'curryN': 'curry', + 'curryRightN': 'curryRight', + 'defaultsAll': 'defaults', + 'defaultsDeepAll': 'defaultsDeep', + 'findFrom': 'find', + 'findIndexFrom': 'findIndex', + 'findLastFrom': 'findLast', + 'findLastIndexFrom': 'findLastIndex', + 'getOr': 'get', + 'includesFrom': 'includes', + 'indexOfFrom': 'indexOf', + 'invokeArgs': 'invoke', + 'invokeArgsMap': 'invokeMap', + 'lastIndexOfFrom': 'lastIndexOf', + 'mergeAll': 'merge', + 'mergeAllWith': 'mergeWith', + 'padChars': 'pad', + 'padCharsEnd': 'padEnd', + 'padCharsStart': 'padStart', + 'propertyOf': 'get', + 'rangeStep': 'range', + 'rangeStepRight': 'rangeRight', + 'restFrom': 'rest', + 'spreadFrom': 'spread', + 'trimChars': 'trim', + 'trimCharsEnd': 'trimEnd', + 'trimCharsStart': 'trimStart', + 'zipAll': 'zip' +}; + +/** Used to track methods that skip fixing their arity. */ +exports.skipFixed = { + 'castArray': true, + 'flow': true, + 'flowRight': true, + 'iteratee': true, + 'mixin': true, + 'rearg': true, + 'runInContext': true +}; + +/** Used to track methods that skip rearranging arguments. */ +exports.skipRearg = { + 'add': true, + 'assign': true, + 'assignIn': true, + 'bind': true, + 'bindKey': true, + 'concat': true, + 'difference': true, + 'divide': true, + 'eq': true, + 'gt': true, + 'gte': true, + 'isEqual': true, + 'lt': true, + 'lte': true, + 'matchesProperty': true, + 'merge': true, + 'multiply': true, + 'overArgs': true, + 'partial': true, + 'partialRight': true, + 'propertyOf': true, + 'random': true, + 'range': true, + 'rangeRight': true, + 'subtract': true, + 'zip': true, + 'zipObject': true, + 'zipObjectDeep': true +}; diff --git a/app/node_modules/lodash/fp/_util.js b/app/node_modules/lodash/fp/_util.js new file mode 100644 index 0000000..1dbf36f --- /dev/null +++ b/app/node_modules/lodash/fp/_util.js @@ -0,0 +1,16 @@ +module.exports = { + 'ary': require('../ary'), + 'assign': require('../_baseAssign'), + 'clone': require('../clone'), + 'curry': require('../curry'), + 'forEach': require('../_arrayEach'), + 'isArray': require('../isArray'), + 'isError': require('../isError'), + 'isFunction': require('../isFunction'), + 'isWeakMap': require('../isWeakMap'), + 'iteratee': require('../iteratee'), + 'keys': require('../_baseKeys'), + 'rearg': require('../rearg'), + 'toInteger': require('../toInteger'), + 'toPath': require('../toPath') +}; diff --git a/app/node_modules/lodash/fp/add.js b/app/node_modules/lodash/fp/add.js new file mode 100644 index 0000000..816eeec --- /dev/null +++ b/app/node_modules/lodash/fp/add.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('add', require('../add')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/after.js b/app/node_modules/lodash/fp/after.js new file mode 100644 index 0000000..21a0167 --- /dev/null +++ b/app/node_modules/lodash/fp/after.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('after', require('../after')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/all.js b/app/node_modules/lodash/fp/all.js new file mode 100644 index 0000000..d0839f7 --- /dev/null +++ b/app/node_modules/lodash/fp/all.js @@ -0,0 +1 @@ +module.exports = require('./every'); diff --git a/app/node_modules/lodash/fp/allPass.js b/app/node_modules/lodash/fp/allPass.js new file mode 100644 index 0000000..79b73ef --- /dev/null +++ b/app/node_modules/lodash/fp/allPass.js @@ -0,0 +1 @@ +module.exports = require('./overEvery'); diff --git a/app/node_modules/lodash/fp/always.js b/app/node_modules/lodash/fp/always.js new file mode 100644 index 0000000..9887703 --- /dev/null +++ b/app/node_modules/lodash/fp/always.js @@ -0,0 +1 @@ +module.exports = require('./constant'); diff --git a/app/node_modules/lodash/fp/any.js b/app/node_modules/lodash/fp/any.js new file mode 100644 index 0000000..900ac25 --- /dev/null +++ b/app/node_modules/lodash/fp/any.js @@ -0,0 +1 @@ +module.exports = require('./some'); diff --git a/app/node_modules/lodash/fp/anyPass.js b/app/node_modules/lodash/fp/anyPass.js new file mode 100644 index 0000000..2774ab3 --- /dev/null +++ b/app/node_modules/lodash/fp/anyPass.js @@ -0,0 +1 @@ +module.exports = require('./overSome'); diff --git a/app/node_modules/lodash/fp/apply.js b/app/node_modules/lodash/fp/apply.js new file mode 100644 index 0000000..2b75712 --- /dev/null +++ b/app/node_modules/lodash/fp/apply.js @@ -0,0 +1 @@ +module.exports = require('./spread'); diff --git a/app/node_modules/lodash/fp/array.js b/app/node_modules/lodash/fp/array.js new file mode 100644 index 0000000..fe939c2 --- /dev/null +++ b/app/node_modules/lodash/fp/array.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../array')); diff --git a/app/node_modules/lodash/fp/ary.js b/app/node_modules/lodash/fp/ary.js new file mode 100644 index 0000000..8edf187 --- /dev/null +++ b/app/node_modules/lodash/fp/ary.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('ary', require('../ary')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/assign.js b/app/node_modules/lodash/fp/assign.js new file mode 100644 index 0000000..23f47af --- /dev/null +++ b/app/node_modules/lodash/fp/assign.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assign', require('../assign')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/assignAll.js b/app/node_modules/lodash/fp/assignAll.js new file mode 100644 index 0000000..b1d36c7 --- /dev/null +++ b/app/node_modules/lodash/fp/assignAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignAll', require('../assign')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/assignAllWith.js b/app/node_modules/lodash/fp/assignAllWith.js new file mode 100644 index 0000000..21e836e --- /dev/null +++ b/app/node_modules/lodash/fp/assignAllWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignAllWith', require('../assignWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/assignIn.js b/app/node_modules/lodash/fp/assignIn.js new file mode 100644 index 0000000..6e7c65f --- /dev/null +++ b/app/node_modules/lodash/fp/assignIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignIn', require('../assignIn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/assignInAll.js b/app/node_modules/lodash/fp/assignInAll.js new file mode 100644 index 0000000..7ba75db --- /dev/null +++ b/app/node_modules/lodash/fp/assignInAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignInAll', require('../assignIn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/assignInAllWith.js b/app/node_modules/lodash/fp/assignInAllWith.js new file mode 100644 index 0000000..e766903 --- /dev/null +++ b/app/node_modules/lodash/fp/assignInAllWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignInAllWith', require('../assignInWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/assignInWith.js b/app/node_modules/lodash/fp/assignInWith.js new file mode 100644 index 0000000..acb5923 --- /dev/null +++ b/app/node_modules/lodash/fp/assignInWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignInWith', require('../assignInWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/assignWith.js b/app/node_modules/lodash/fp/assignWith.js new file mode 100644 index 0000000..eb92521 --- /dev/null +++ b/app/node_modules/lodash/fp/assignWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignWith', require('../assignWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/assoc.js b/app/node_modules/lodash/fp/assoc.js new file mode 100644 index 0000000..7648820 --- /dev/null +++ b/app/node_modules/lodash/fp/assoc.js @@ -0,0 +1 @@ +module.exports = require('./set'); diff --git a/app/node_modules/lodash/fp/assocPath.js b/app/node_modules/lodash/fp/assocPath.js new file mode 100644 index 0000000..7648820 --- /dev/null +++ b/app/node_modules/lodash/fp/assocPath.js @@ -0,0 +1 @@ +module.exports = require('./set'); diff --git a/app/node_modules/lodash/fp/at.js b/app/node_modules/lodash/fp/at.js new file mode 100644 index 0000000..cc39d25 --- /dev/null +++ b/app/node_modules/lodash/fp/at.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('at', require('../at')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/attempt.js b/app/node_modules/lodash/fp/attempt.js new file mode 100644 index 0000000..26ca42e --- /dev/null +++ b/app/node_modules/lodash/fp/attempt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('attempt', require('../attempt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/before.js b/app/node_modules/lodash/fp/before.js new file mode 100644 index 0000000..7a2de65 --- /dev/null +++ b/app/node_modules/lodash/fp/before.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('before', require('../before')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/bind.js b/app/node_modules/lodash/fp/bind.js new file mode 100644 index 0000000..5cbe4f3 --- /dev/null +++ b/app/node_modules/lodash/fp/bind.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('bind', require('../bind')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/bindAll.js b/app/node_modules/lodash/fp/bindAll.js new file mode 100644 index 0000000..6b4a4a0 --- /dev/null +++ b/app/node_modules/lodash/fp/bindAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('bindAll', require('../bindAll')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/bindKey.js b/app/node_modules/lodash/fp/bindKey.js new file mode 100644 index 0000000..6a46c6b --- /dev/null +++ b/app/node_modules/lodash/fp/bindKey.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('bindKey', require('../bindKey')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/camelCase.js b/app/node_modules/lodash/fp/camelCase.js new file mode 100644 index 0000000..87b77b4 --- /dev/null +++ b/app/node_modules/lodash/fp/camelCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('camelCase', require('../camelCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/capitalize.js b/app/node_modules/lodash/fp/capitalize.js new file mode 100644 index 0000000..cac74e1 --- /dev/null +++ b/app/node_modules/lodash/fp/capitalize.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('capitalize', require('../capitalize'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/castArray.js b/app/node_modules/lodash/fp/castArray.js new file mode 100644 index 0000000..8681c09 --- /dev/null +++ b/app/node_modules/lodash/fp/castArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('castArray', require('../castArray')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/ceil.js b/app/node_modules/lodash/fp/ceil.js new file mode 100644 index 0000000..f416b72 --- /dev/null +++ b/app/node_modules/lodash/fp/ceil.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('ceil', require('../ceil')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/chain.js b/app/node_modules/lodash/fp/chain.js new file mode 100644 index 0000000..604fe39 --- /dev/null +++ b/app/node_modules/lodash/fp/chain.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('chain', require('../chain'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/chunk.js b/app/node_modules/lodash/fp/chunk.js new file mode 100644 index 0000000..871ab08 --- /dev/null +++ b/app/node_modules/lodash/fp/chunk.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('chunk', require('../chunk')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/clamp.js b/app/node_modules/lodash/fp/clamp.js new file mode 100644 index 0000000..3b06c01 --- /dev/null +++ b/app/node_modules/lodash/fp/clamp.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('clamp', require('../clamp')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/clone.js b/app/node_modules/lodash/fp/clone.js new file mode 100644 index 0000000..cadb59c --- /dev/null +++ b/app/node_modules/lodash/fp/clone.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('clone', require('../clone'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/cloneDeep.js b/app/node_modules/lodash/fp/cloneDeep.js new file mode 100644 index 0000000..a6107aa --- /dev/null +++ b/app/node_modules/lodash/fp/cloneDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('cloneDeep', require('../cloneDeep'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/cloneDeepWith.js b/app/node_modules/lodash/fp/cloneDeepWith.js new file mode 100644 index 0000000..6f01e44 --- /dev/null +++ b/app/node_modules/lodash/fp/cloneDeepWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('cloneDeepWith', require('../cloneDeepWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/cloneWith.js b/app/node_modules/lodash/fp/cloneWith.js new file mode 100644 index 0000000..aa88578 --- /dev/null +++ b/app/node_modules/lodash/fp/cloneWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('cloneWith', require('../cloneWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/collection.js b/app/node_modules/lodash/fp/collection.js new file mode 100644 index 0000000..fc8b328 --- /dev/null +++ b/app/node_modules/lodash/fp/collection.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../collection')); diff --git a/app/node_modules/lodash/fp/commit.js b/app/node_modules/lodash/fp/commit.js new file mode 100644 index 0000000..130a894 --- /dev/null +++ b/app/node_modules/lodash/fp/commit.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('commit', require('../commit'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/compact.js b/app/node_modules/lodash/fp/compact.js new file mode 100644 index 0000000..ce8f7a1 --- /dev/null +++ b/app/node_modules/lodash/fp/compact.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('compact', require('../compact'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/complement.js b/app/node_modules/lodash/fp/complement.js new file mode 100644 index 0000000..93eb462 --- /dev/null +++ b/app/node_modules/lodash/fp/complement.js @@ -0,0 +1 @@ +module.exports = require('./negate'); diff --git a/app/node_modules/lodash/fp/compose.js b/app/node_modules/lodash/fp/compose.js new file mode 100644 index 0000000..1954e94 --- /dev/null +++ b/app/node_modules/lodash/fp/compose.js @@ -0,0 +1 @@ +module.exports = require('./flowRight'); diff --git a/app/node_modules/lodash/fp/concat.js b/app/node_modules/lodash/fp/concat.js new file mode 100644 index 0000000..e59346a --- /dev/null +++ b/app/node_modules/lodash/fp/concat.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('concat', require('../concat')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/cond.js b/app/node_modules/lodash/fp/cond.js new file mode 100644 index 0000000..6a0120e --- /dev/null +++ b/app/node_modules/lodash/fp/cond.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('cond', require('../cond'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/conforms.js b/app/node_modules/lodash/fp/conforms.js new file mode 100644 index 0000000..3247f64 --- /dev/null +++ b/app/node_modules/lodash/fp/conforms.js @@ -0,0 +1 @@ +module.exports = require('./conformsTo'); diff --git a/app/node_modules/lodash/fp/conformsTo.js b/app/node_modules/lodash/fp/conformsTo.js new file mode 100644 index 0000000..aa7f41e --- /dev/null +++ b/app/node_modules/lodash/fp/conformsTo.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('conformsTo', require('../conformsTo')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/constant.js b/app/node_modules/lodash/fp/constant.js new file mode 100644 index 0000000..9e406fc --- /dev/null +++ b/app/node_modules/lodash/fp/constant.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('constant', require('../constant'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/contains.js b/app/node_modules/lodash/fp/contains.js new file mode 100644 index 0000000..594722a --- /dev/null +++ b/app/node_modules/lodash/fp/contains.js @@ -0,0 +1 @@ +module.exports = require('./includes'); diff --git a/app/node_modules/lodash/fp/convert.js b/app/node_modules/lodash/fp/convert.js new file mode 100644 index 0000000..4795dc4 --- /dev/null +++ b/app/node_modules/lodash/fp/convert.js @@ -0,0 +1,18 @@ +var baseConvert = require('./_baseConvert'), + util = require('./_util'); + +/** + * Converts `func` of `name` to an immutable auto-curried iteratee-first data-last + * version with conversion `options` applied. If `name` is an object its methods + * will be converted. + * + * @param {string} name The name of the function to wrap. + * @param {Function} [func] The function to wrap. + * @param {Object} [options] The options object. See `baseConvert` for more details. + * @returns {Function|Object} Returns the converted function or object. + */ +function convert(name, func, options) { + return baseConvert(util, name, func, options); +} + +module.exports = convert; diff --git a/app/node_modules/lodash/fp/countBy.js b/app/node_modules/lodash/fp/countBy.js new file mode 100644 index 0000000..dfa4643 --- /dev/null +++ b/app/node_modules/lodash/fp/countBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('countBy', require('../countBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/create.js b/app/node_modules/lodash/fp/create.js new file mode 100644 index 0000000..752025f --- /dev/null +++ b/app/node_modules/lodash/fp/create.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('create', require('../create')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/curry.js b/app/node_modules/lodash/fp/curry.js new file mode 100644 index 0000000..b0b4168 --- /dev/null +++ b/app/node_modules/lodash/fp/curry.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('curry', require('../curry')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/curryN.js b/app/node_modules/lodash/fp/curryN.js new file mode 100644 index 0000000..2ae7d00 --- /dev/null +++ b/app/node_modules/lodash/fp/curryN.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('curryN', require('../curry')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/curryRight.js b/app/node_modules/lodash/fp/curryRight.js new file mode 100644 index 0000000..cb619eb --- /dev/null +++ b/app/node_modules/lodash/fp/curryRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('curryRight', require('../curryRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/curryRightN.js b/app/node_modules/lodash/fp/curryRightN.js new file mode 100644 index 0000000..2495afc --- /dev/null +++ b/app/node_modules/lodash/fp/curryRightN.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('curryRightN', require('../curryRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/date.js b/app/node_modules/lodash/fp/date.js new file mode 100644 index 0000000..82cb952 --- /dev/null +++ b/app/node_modules/lodash/fp/date.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../date')); diff --git a/app/node_modules/lodash/fp/debounce.js b/app/node_modules/lodash/fp/debounce.js new file mode 100644 index 0000000..2612229 --- /dev/null +++ b/app/node_modules/lodash/fp/debounce.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('debounce', require('../debounce')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/deburr.js b/app/node_modules/lodash/fp/deburr.js new file mode 100644 index 0000000..96463ab --- /dev/null +++ b/app/node_modules/lodash/fp/deburr.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('deburr', require('../deburr'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/defaultTo.js b/app/node_modules/lodash/fp/defaultTo.js new file mode 100644 index 0000000..d6b52a4 --- /dev/null +++ b/app/node_modules/lodash/fp/defaultTo.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaultTo', require('../defaultTo')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/defaults.js b/app/node_modules/lodash/fp/defaults.js new file mode 100644 index 0000000..e1a8e6e --- /dev/null +++ b/app/node_modules/lodash/fp/defaults.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaults', require('../defaults')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/defaultsAll.js b/app/node_modules/lodash/fp/defaultsAll.js new file mode 100644 index 0000000..238fcc3 --- /dev/null +++ b/app/node_modules/lodash/fp/defaultsAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaultsAll', require('../defaults')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/defaultsDeep.js b/app/node_modules/lodash/fp/defaultsDeep.js new file mode 100644 index 0000000..1f172ff --- /dev/null +++ b/app/node_modules/lodash/fp/defaultsDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaultsDeep', require('../defaultsDeep')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/defaultsDeepAll.js b/app/node_modules/lodash/fp/defaultsDeepAll.js new file mode 100644 index 0000000..6835f2f --- /dev/null +++ b/app/node_modules/lodash/fp/defaultsDeepAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaultsDeepAll', require('../defaultsDeep')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/defer.js b/app/node_modules/lodash/fp/defer.js new file mode 100644 index 0000000..ec7990f --- /dev/null +++ b/app/node_modules/lodash/fp/defer.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defer', require('../defer'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/delay.js b/app/node_modules/lodash/fp/delay.js new file mode 100644 index 0000000..556dbd5 --- /dev/null +++ b/app/node_modules/lodash/fp/delay.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('delay', require('../delay')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/difference.js b/app/node_modules/lodash/fp/difference.js new file mode 100644 index 0000000..2d03765 --- /dev/null +++ b/app/node_modules/lodash/fp/difference.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('difference', require('../difference')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/differenceBy.js b/app/node_modules/lodash/fp/differenceBy.js new file mode 100644 index 0000000..2f91491 --- /dev/null +++ b/app/node_modules/lodash/fp/differenceBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('differenceBy', require('../differenceBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/differenceWith.js b/app/node_modules/lodash/fp/differenceWith.js new file mode 100644 index 0000000..bcf5ad2 --- /dev/null +++ b/app/node_modules/lodash/fp/differenceWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('differenceWith', require('../differenceWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/dissoc.js b/app/node_modules/lodash/fp/dissoc.js new file mode 100644 index 0000000..7ec7be1 --- /dev/null +++ b/app/node_modules/lodash/fp/dissoc.js @@ -0,0 +1 @@ +module.exports = require('./unset'); diff --git a/app/node_modules/lodash/fp/dissocPath.js b/app/node_modules/lodash/fp/dissocPath.js new file mode 100644 index 0000000..7ec7be1 --- /dev/null +++ b/app/node_modules/lodash/fp/dissocPath.js @@ -0,0 +1 @@ +module.exports = require('./unset'); diff --git a/app/node_modules/lodash/fp/divide.js b/app/node_modules/lodash/fp/divide.js new file mode 100644 index 0000000..82048c5 --- /dev/null +++ b/app/node_modules/lodash/fp/divide.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('divide', require('../divide')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/drop.js b/app/node_modules/lodash/fp/drop.js new file mode 100644 index 0000000..2fa9b4f --- /dev/null +++ b/app/node_modules/lodash/fp/drop.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('drop', require('../drop')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/dropLast.js b/app/node_modules/lodash/fp/dropLast.js new file mode 100644 index 0000000..174e525 --- /dev/null +++ b/app/node_modules/lodash/fp/dropLast.js @@ -0,0 +1 @@ +module.exports = require('./dropRight'); diff --git a/app/node_modules/lodash/fp/dropLastWhile.js b/app/node_modules/lodash/fp/dropLastWhile.js new file mode 100644 index 0000000..be2a9d2 --- /dev/null +++ b/app/node_modules/lodash/fp/dropLastWhile.js @@ -0,0 +1 @@ +module.exports = require('./dropRightWhile'); diff --git a/app/node_modules/lodash/fp/dropRight.js b/app/node_modules/lodash/fp/dropRight.js new file mode 100644 index 0000000..e98881f --- /dev/null +++ b/app/node_modules/lodash/fp/dropRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('dropRight', require('../dropRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/dropRightWhile.js b/app/node_modules/lodash/fp/dropRightWhile.js new file mode 100644 index 0000000..cacaa70 --- /dev/null +++ b/app/node_modules/lodash/fp/dropRightWhile.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('dropRightWhile', require('../dropRightWhile')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/dropWhile.js b/app/node_modules/lodash/fp/dropWhile.js new file mode 100644 index 0000000..285f864 --- /dev/null +++ b/app/node_modules/lodash/fp/dropWhile.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('dropWhile', require('../dropWhile')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/each.js b/app/node_modules/lodash/fp/each.js new file mode 100644 index 0000000..8800f42 --- /dev/null +++ b/app/node_modules/lodash/fp/each.js @@ -0,0 +1 @@ +module.exports = require('./forEach'); diff --git a/app/node_modules/lodash/fp/eachRight.js b/app/node_modules/lodash/fp/eachRight.js new file mode 100644 index 0000000..3252b2a --- /dev/null +++ b/app/node_modules/lodash/fp/eachRight.js @@ -0,0 +1 @@ +module.exports = require('./forEachRight'); diff --git a/app/node_modules/lodash/fp/endsWith.js b/app/node_modules/lodash/fp/endsWith.js new file mode 100644 index 0000000..17dc2a4 --- /dev/null +++ b/app/node_modules/lodash/fp/endsWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('endsWith', require('../endsWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/entries.js b/app/node_modules/lodash/fp/entries.js new file mode 100644 index 0000000..7a88df2 --- /dev/null +++ b/app/node_modules/lodash/fp/entries.js @@ -0,0 +1 @@ +module.exports = require('./toPairs'); diff --git a/app/node_modules/lodash/fp/entriesIn.js b/app/node_modules/lodash/fp/entriesIn.js new file mode 100644 index 0000000..f6c6331 --- /dev/null +++ b/app/node_modules/lodash/fp/entriesIn.js @@ -0,0 +1 @@ +module.exports = require('./toPairsIn'); diff --git a/app/node_modules/lodash/fp/eq.js b/app/node_modules/lodash/fp/eq.js new file mode 100644 index 0000000..9a3d21b --- /dev/null +++ b/app/node_modules/lodash/fp/eq.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('eq', require('../eq')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/equals.js b/app/node_modules/lodash/fp/equals.js new file mode 100644 index 0000000..e6a5ce0 --- /dev/null +++ b/app/node_modules/lodash/fp/equals.js @@ -0,0 +1 @@ +module.exports = require('./isEqual'); diff --git a/app/node_modules/lodash/fp/escape.js b/app/node_modules/lodash/fp/escape.js new file mode 100644 index 0000000..52c1fbb --- /dev/null +++ b/app/node_modules/lodash/fp/escape.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('escape', require('../escape'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/escapeRegExp.js b/app/node_modules/lodash/fp/escapeRegExp.js new file mode 100644 index 0000000..369b2ef --- /dev/null +++ b/app/node_modules/lodash/fp/escapeRegExp.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('escapeRegExp', require('../escapeRegExp'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/every.js b/app/node_modules/lodash/fp/every.js new file mode 100644 index 0000000..95c2776 --- /dev/null +++ b/app/node_modules/lodash/fp/every.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('every', require('../every')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/extend.js b/app/node_modules/lodash/fp/extend.js new file mode 100644 index 0000000..e00166c --- /dev/null +++ b/app/node_modules/lodash/fp/extend.js @@ -0,0 +1 @@ +module.exports = require('./assignIn'); diff --git a/app/node_modules/lodash/fp/extendAll.js b/app/node_modules/lodash/fp/extendAll.js new file mode 100644 index 0000000..cc55b64 --- /dev/null +++ b/app/node_modules/lodash/fp/extendAll.js @@ -0,0 +1 @@ +module.exports = require('./assignInAll'); diff --git a/app/node_modules/lodash/fp/extendAllWith.js b/app/node_modules/lodash/fp/extendAllWith.js new file mode 100644 index 0000000..6679d20 --- /dev/null +++ b/app/node_modules/lodash/fp/extendAllWith.js @@ -0,0 +1 @@ +module.exports = require('./assignInAllWith'); diff --git a/app/node_modules/lodash/fp/extendWith.js b/app/node_modules/lodash/fp/extendWith.js new file mode 100644 index 0000000..dbdcb3b --- /dev/null +++ b/app/node_modules/lodash/fp/extendWith.js @@ -0,0 +1 @@ +module.exports = require('./assignInWith'); diff --git a/app/node_modules/lodash/fp/fill.js b/app/node_modules/lodash/fp/fill.js new file mode 100644 index 0000000..b2d47e8 --- /dev/null +++ b/app/node_modules/lodash/fp/fill.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('fill', require('../fill')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/filter.js b/app/node_modules/lodash/fp/filter.js new file mode 100644 index 0000000..796d501 --- /dev/null +++ b/app/node_modules/lodash/fp/filter.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('filter', require('../filter')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/find.js b/app/node_modules/lodash/fp/find.js new file mode 100644 index 0000000..f805d33 --- /dev/null +++ b/app/node_modules/lodash/fp/find.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('find', require('../find')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/findFrom.js b/app/node_modules/lodash/fp/findFrom.js new file mode 100644 index 0000000..da8275e --- /dev/null +++ b/app/node_modules/lodash/fp/findFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findFrom', require('../find')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/findIndex.js b/app/node_modules/lodash/fp/findIndex.js new file mode 100644 index 0000000..8c15fd1 --- /dev/null +++ b/app/node_modules/lodash/fp/findIndex.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findIndex', require('../findIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/findIndexFrom.js b/app/node_modules/lodash/fp/findIndexFrom.js new file mode 100644 index 0000000..32e98cb --- /dev/null +++ b/app/node_modules/lodash/fp/findIndexFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findIndexFrom', require('../findIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/findKey.js b/app/node_modules/lodash/fp/findKey.js new file mode 100644 index 0000000..475bcfa --- /dev/null +++ b/app/node_modules/lodash/fp/findKey.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findKey', require('../findKey')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/findLast.js b/app/node_modules/lodash/fp/findLast.js new file mode 100644 index 0000000..093fe94 --- /dev/null +++ b/app/node_modules/lodash/fp/findLast.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLast', require('../findLast')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/findLastFrom.js b/app/node_modules/lodash/fp/findLastFrom.js new file mode 100644 index 0000000..76c38fb --- /dev/null +++ b/app/node_modules/lodash/fp/findLastFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLastFrom', require('../findLast')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/findLastIndex.js b/app/node_modules/lodash/fp/findLastIndex.js new file mode 100644 index 0000000..36986df --- /dev/null +++ b/app/node_modules/lodash/fp/findLastIndex.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLastIndex', require('../findLastIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/findLastIndexFrom.js b/app/node_modules/lodash/fp/findLastIndexFrom.js new file mode 100644 index 0000000..34c8176 --- /dev/null +++ b/app/node_modules/lodash/fp/findLastIndexFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLastIndexFrom', require('../findLastIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/findLastKey.js b/app/node_modules/lodash/fp/findLastKey.js new file mode 100644 index 0000000..5f81b60 --- /dev/null +++ b/app/node_modules/lodash/fp/findLastKey.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLastKey', require('../findLastKey')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/first.js b/app/node_modules/lodash/fp/first.js new file mode 100644 index 0000000..53f4ad1 --- /dev/null +++ b/app/node_modules/lodash/fp/first.js @@ -0,0 +1 @@ +module.exports = require('./head'); diff --git a/app/node_modules/lodash/fp/flatMap.js b/app/node_modules/lodash/fp/flatMap.js new file mode 100644 index 0000000..d01dc4d --- /dev/null +++ b/app/node_modules/lodash/fp/flatMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flatMap', require('../flatMap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/flatMapDeep.js b/app/node_modules/lodash/fp/flatMapDeep.js new file mode 100644 index 0000000..569c42e --- /dev/null +++ b/app/node_modules/lodash/fp/flatMapDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flatMapDeep', require('../flatMapDeep')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/flatMapDepth.js b/app/node_modules/lodash/fp/flatMapDepth.js new file mode 100644 index 0000000..6eb68fd --- /dev/null +++ b/app/node_modules/lodash/fp/flatMapDepth.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flatMapDepth', require('../flatMapDepth')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/flatten.js b/app/node_modules/lodash/fp/flatten.js new file mode 100644 index 0000000..30425d8 --- /dev/null +++ b/app/node_modules/lodash/fp/flatten.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flatten', require('../flatten'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/flattenDeep.js b/app/node_modules/lodash/fp/flattenDeep.js new file mode 100644 index 0000000..aed5db2 --- /dev/null +++ b/app/node_modules/lodash/fp/flattenDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flattenDeep', require('../flattenDeep'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/flattenDepth.js b/app/node_modules/lodash/fp/flattenDepth.js new file mode 100644 index 0000000..ad65e37 --- /dev/null +++ b/app/node_modules/lodash/fp/flattenDepth.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flattenDepth', require('../flattenDepth')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/flip.js b/app/node_modules/lodash/fp/flip.js new file mode 100644 index 0000000..0547e7b --- /dev/null +++ b/app/node_modules/lodash/fp/flip.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flip', require('../flip'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/floor.js b/app/node_modules/lodash/fp/floor.js new file mode 100644 index 0000000..a6cf335 --- /dev/null +++ b/app/node_modules/lodash/fp/floor.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('floor', require('../floor')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/flow.js b/app/node_modules/lodash/fp/flow.js new file mode 100644 index 0000000..cd83677 --- /dev/null +++ b/app/node_modules/lodash/fp/flow.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flow', require('../flow')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/flowRight.js b/app/node_modules/lodash/fp/flowRight.js new file mode 100644 index 0000000..972a5b9 --- /dev/null +++ b/app/node_modules/lodash/fp/flowRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flowRight', require('../flowRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/forEach.js b/app/node_modules/lodash/fp/forEach.js new file mode 100644 index 0000000..2f49452 --- /dev/null +++ b/app/node_modules/lodash/fp/forEach.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forEach', require('../forEach')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/forEachRight.js b/app/node_modules/lodash/fp/forEachRight.js new file mode 100644 index 0000000..3ff9733 --- /dev/null +++ b/app/node_modules/lodash/fp/forEachRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forEachRight', require('../forEachRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/forIn.js b/app/node_modules/lodash/fp/forIn.js new file mode 100644 index 0000000..9341749 --- /dev/null +++ b/app/node_modules/lodash/fp/forIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forIn', require('../forIn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/forInRight.js b/app/node_modules/lodash/fp/forInRight.js new file mode 100644 index 0000000..cecf8bb --- /dev/null +++ b/app/node_modules/lodash/fp/forInRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forInRight', require('../forInRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/forOwn.js b/app/node_modules/lodash/fp/forOwn.js new file mode 100644 index 0000000..246449e --- /dev/null +++ b/app/node_modules/lodash/fp/forOwn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forOwn', require('../forOwn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/forOwnRight.js b/app/node_modules/lodash/fp/forOwnRight.js new file mode 100644 index 0000000..c5e826e --- /dev/null +++ b/app/node_modules/lodash/fp/forOwnRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forOwnRight', require('../forOwnRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/fromPairs.js b/app/node_modules/lodash/fp/fromPairs.js new file mode 100644 index 0000000..f8cc596 --- /dev/null +++ b/app/node_modules/lodash/fp/fromPairs.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('fromPairs', require('../fromPairs')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/function.js b/app/node_modules/lodash/fp/function.js new file mode 100644 index 0000000..dfe69b1 --- /dev/null +++ b/app/node_modules/lodash/fp/function.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../function')); diff --git a/app/node_modules/lodash/fp/functions.js b/app/node_modules/lodash/fp/functions.js new file mode 100644 index 0000000..09d1bb1 --- /dev/null +++ b/app/node_modules/lodash/fp/functions.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('functions', require('../functions'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/functionsIn.js b/app/node_modules/lodash/fp/functionsIn.js new file mode 100644 index 0000000..2cfeb83 --- /dev/null +++ b/app/node_modules/lodash/fp/functionsIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('functionsIn', require('../functionsIn'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/get.js b/app/node_modules/lodash/fp/get.js new file mode 100644 index 0000000..6d3a328 --- /dev/null +++ b/app/node_modules/lodash/fp/get.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('get', require('../get')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/getOr.js b/app/node_modules/lodash/fp/getOr.js new file mode 100644 index 0000000..7dbf771 --- /dev/null +++ b/app/node_modules/lodash/fp/getOr.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('getOr', require('../get')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/groupBy.js b/app/node_modules/lodash/fp/groupBy.js new file mode 100644 index 0000000..fc0bc78 --- /dev/null +++ b/app/node_modules/lodash/fp/groupBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('groupBy', require('../groupBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/gt.js b/app/node_modules/lodash/fp/gt.js new file mode 100644 index 0000000..9e57c80 --- /dev/null +++ b/app/node_modules/lodash/fp/gt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('gt', require('../gt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/gte.js b/app/node_modules/lodash/fp/gte.js new file mode 100644 index 0000000..4584786 --- /dev/null +++ b/app/node_modules/lodash/fp/gte.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('gte', require('../gte')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/has.js b/app/node_modules/lodash/fp/has.js new file mode 100644 index 0000000..b901298 --- /dev/null +++ b/app/node_modules/lodash/fp/has.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('has', require('../has')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/hasIn.js b/app/node_modules/lodash/fp/hasIn.js new file mode 100644 index 0000000..b3c3d1a --- /dev/null +++ b/app/node_modules/lodash/fp/hasIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('hasIn', require('../hasIn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/head.js b/app/node_modules/lodash/fp/head.js new file mode 100644 index 0000000..2694f0a --- /dev/null +++ b/app/node_modules/lodash/fp/head.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('head', require('../head'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/identical.js b/app/node_modules/lodash/fp/identical.js new file mode 100644 index 0000000..85563f4 --- /dev/null +++ b/app/node_modules/lodash/fp/identical.js @@ -0,0 +1 @@ +module.exports = require('./eq'); diff --git a/app/node_modules/lodash/fp/identity.js b/app/node_modules/lodash/fp/identity.js new file mode 100644 index 0000000..096415a --- /dev/null +++ b/app/node_modules/lodash/fp/identity.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('identity', require('../identity'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/inRange.js b/app/node_modules/lodash/fp/inRange.js new file mode 100644 index 0000000..202d940 --- /dev/null +++ b/app/node_modules/lodash/fp/inRange.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('inRange', require('../inRange')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/includes.js b/app/node_modules/lodash/fp/includes.js new file mode 100644 index 0000000..1146780 --- /dev/null +++ b/app/node_modules/lodash/fp/includes.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('includes', require('../includes')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/includesFrom.js b/app/node_modules/lodash/fp/includesFrom.js new file mode 100644 index 0000000..683afdb --- /dev/null +++ b/app/node_modules/lodash/fp/includesFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('includesFrom', require('../includes')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/indexBy.js b/app/node_modules/lodash/fp/indexBy.js new file mode 100644 index 0000000..7e64bc0 --- /dev/null +++ b/app/node_modules/lodash/fp/indexBy.js @@ -0,0 +1 @@ +module.exports = require('./keyBy'); diff --git a/app/node_modules/lodash/fp/indexOf.js b/app/node_modules/lodash/fp/indexOf.js new file mode 100644 index 0000000..524658e --- /dev/null +++ b/app/node_modules/lodash/fp/indexOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('indexOf', require('../indexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/indexOfFrom.js b/app/node_modules/lodash/fp/indexOfFrom.js new file mode 100644 index 0000000..d99c822 --- /dev/null +++ b/app/node_modules/lodash/fp/indexOfFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('indexOfFrom', require('../indexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/init.js b/app/node_modules/lodash/fp/init.js new file mode 100644 index 0000000..2f88d8b --- /dev/null +++ b/app/node_modules/lodash/fp/init.js @@ -0,0 +1 @@ +module.exports = require('./initial'); diff --git a/app/node_modules/lodash/fp/initial.js b/app/node_modules/lodash/fp/initial.js new file mode 100644 index 0000000..b732ba0 --- /dev/null +++ b/app/node_modules/lodash/fp/initial.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('initial', require('../initial'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/intersection.js b/app/node_modules/lodash/fp/intersection.js new file mode 100644 index 0000000..52936d5 --- /dev/null +++ b/app/node_modules/lodash/fp/intersection.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('intersection', require('../intersection')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/intersectionBy.js b/app/node_modules/lodash/fp/intersectionBy.js new file mode 100644 index 0000000..72629f2 --- /dev/null +++ b/app/node_modules/lodash/fp/intersectionBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('intersectionBy', require('../intersectionBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/intersectionWith.js b/app/node_modules/lodash/fp/intersectionWith.js new file mode 100644 index 0000000..e064f40 --- /dev/null +++ b/app/node_modules/lodash/fp/intersectionWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('intersectionWith', require('../intersectionWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/invert.js b/app/node_modules/lodash/fp/invert.js new file mode 100644 index 0000000..2d5d1f0 --- /dev/null +++ b/app/node_modules/lodash/fp/invert.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invert', require('../invert')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/invertBy.js b/app/node_modules/lodash/fp/invertBy.js new file mode 100644 index 0000000..63ca97e --- /dev/null +++ b/app/node_modules/lodash/fp/invertBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invertBy', require('../invertBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/invertObj.js b/app/node_modules/lodash/fp/invertObj.js new file mode 100644 index 0000000..f1d842e --- /dev/null +++ b/app/node_modules/lodash/fp/invertObj.js @@ -0,0 +1 @@ +module.exports = require('./invert'); diff --git a/app/node_modules/lodash/fp/invoke.js b/app/node_modules/lodash/fp/invoke.js new file mode 100644 index 0000000..fcf17f0 --- /dev/null +++ b/app/node_modules/lodash/fp/invoke.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invoke', require('../invoke')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/invokeArgs.js b/app/node_modules/lodash/fp/invokeArgs.js new file mode 100644 index 0000000..d3f2953 --- /dev/null +++ b/app/node_modules/lodash/fp/invokeArgs.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invokeArgs', require('../invoke')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/invokeArgsMap.js b/app/node_modules/lodash/fp/invokeArgsMap.js new file mode 100644 index 0000000..eaa9f84 --- /dev/null +++ b/app/node_modules/lodash/fp/invokeArgsMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invokeArgsMap', require('../invokeMap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/invokeMap.js b/app/node_modules/lodash/fp/invokeMap.js new file mode 100644 index 0000000..6515fd7 --- /dev/null +++ b/app/node_modules/lodash/fp/invokeMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invokeMap', require('../invokeMap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isArguments.js b/app/node_modules/lodash/fp/isArguments.js new file mode 100644 index 0000000..1d93c9e --- /dev/null +++ b/app/node_modules/lodash/fp/isArguments.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArguments', require('../isArguments'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isArray.js b/app/node_modules/lodash/fp/isArray.js new file mode 100644 index 0000000..ba7ade8 --- /dev/null +++ b/app/node_modules/lodash/fp/isArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArray', require('../isArray'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isArrayBuffer.js b/app/node_modules/lodash/fp/isArrayBuffer.js new file mode 100644 index 0000000..5088513 --- /dev/null +++ b/app/node_modules/lodash/fp/isArrayBuffer.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArrayBuffer', require('../isArrayBuffer'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isArrayLike.js b/app/node_modules/lodash/fp/isArrayLike.js new file mode 100644 index 0000000..8f1856b --- /dev/null +++ b/app/node_modules/lodash/fp/isArrayLike.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArrayLike', require('../isArrayLike'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isArrayLikeObject.js b/app/node_modules/lodash/fp/isArrayLikeObject.js new file mode 100644 index 0000000..2108498 --- /dev/null +++ b/app/node_modules/lodash/fp/isArrayLikeObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArrayLikeObject', require('../isArrayLikeObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isBoolean.js b/app/node_modules/lodash/fp/isBoolean.js new file mode 100644 index 0000000..9339f75 --- /dev/null +++ b/app/node_modules/lodash/fp/isBoolean.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isBoolean', require('../isBoolean'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isBuffer.js b/app/node_modules/lodash/fp/isBuffer.js new file mode 100644 index 0000000..e60b123 --- /dev/null +++ b/app/node_modules/lodash/fp/isBuffer.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isBuffer', require('../isBuffer'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isDate.js b/app/node_modules/lodash/fp/isDate.js new file mode 100644 index 0000000..dc41d08 --- /dev/null +++ b/app/node_modules/lodash/fp/isDate.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isDate', require('../isDate'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isElement.js b/app/node_modules/lodash/fp/isElement.js new file mode 100644 index 0000000..18ee039 --- /dev/null +++ b/app/node_modules/lodash/fp/isElement.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isElement', require('../isElement'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isEmpty.js b/app/node_modules/lodash/fp/isEmpty.js new file mode 100644 index 0000000..0f4ae84 --- /dev/null +++ b/app/node_modules/lodash/fp/isEmpty.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isEmpty', require('../isEmpty'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isEqual.js b/app/node_modules/lodash/fp/isEqual.js new file mode 100644 index 0000000..4138386 --- /dev/null +++ b/app/node_modules/lodash/fp/isEqual.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isEqual', require('../isEqual')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isEqualWith.js b/app/node_modules/lodash/fp/isEqualWith.js new file mode 100644 index 0000000..029ff5c --- /dev/null +++ b/app/node_modules/lodash/fp/isEqualWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isEqualWith', require('../isEqualWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isError.js b/app/node_modules/lodash/fp/isError.js new file mode 100644 index 0000000..3dfd81c --- /dev/null +++ b/app/node_modules/lodash/fp/isError.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isError', require('../isError'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isFinite.js b/app/node_modules/lodash/fp/isFinite.js new file mode 100644 index 0000000..0b647b8 --- /dev/null +++ b/app/node_modules/lodash/fp/isFinite.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isFinite', require('../isFinite'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isFunction.js b/app/node_modules/lodash/fp/isFunction.js new file mode 100644 index 0000000..ff8e5c4 --- /dev/null +++ b/app/node_modules/lodash/fp/isFunction.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isFunction', require('../isFunction'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isInteger.js b/app/node_modules/lodash/fp/isInteger.js new file mode 100644 index 0000000..67af4ff --- /dev/null +++ b/app/node_modules/lodash/fp/isInteger.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isInteger', require('../isInteger'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isLength.js b/app/node_modules/lodash/fp/isLength.js new file mode 100644 index 0000000..fc101c5 --- /dev/null +++ b/app/node_modules/lodash/fp/isLength.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isLength', require('../isLength'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isMap.js b/app/node_modules/lodash/fp/isMap.js new file mode 100644 index 0000000..a209aa6 --- /dev/null +++ b/app/node_modules/lodash/fp/isMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isMap', require('../isMap'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isMatch.js b/app/node_modules/lodash/fp/isMatch.js new file mode 100644 index 0000000..6264ca1 --- /dev/null +++ b/app/node_modules/lodash/fp/isMatch.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isMatch', require('../isMatch')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isMatchWith.js b/app/node_modules/lodash/fp/isMatchWith.js new file mode 100644 index 0000000..d95f319 --- /dev/null +++ b/app/node_modules/lodash/fp/isMatchWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isMatchWith', require('../isMatchWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isNaN.js b/app/node_modules/lodash/fp/isNaN.js new file mode 100644 index 0000000..66a978f --- /dev/null +++ b/app/node_modules/lodash/fp/isNaN.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNaN', require('../isNaN'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isNative.js b/app/node_modules/lodash/fp/isNative.js new file mode 100644 index 0000000..3d775ba --- /dev/null +++ b/app/node_modules/lodash/fp/isNative.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNative', require('../isNative'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isNil.js b/app/node_modules/lodash/fp/isNil.js new file mode 100644 index 0000000..5952c02 --- /dev/null +++ b/app/node_modules/lodash/fp/isNil.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNil', require('../isNil'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isNull.js b/app/node_modules/lodash/fp/isNull.js new file mode 100644 index 0000000..f201a35 --- /dev/null +++ b/app/node_modules/lodash/fp/isNull.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNull', require('../isNull'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isNumber.js b/app/node_modules/lodash/fp/isNumber.js new file mode 100644 index 0000000..a2b5fa0 --- /dev/null +++ b/app/node_modules/lodash/fp/isNumber.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNumber', require('../isNumber'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isObject.js b/app/node_modules/lodash/fp/isObject.js new file mode 100644 index 0000000..231ace0 --- /dev/null +++ b/app/node_modules/lodash/fp/isObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isObject', require('../isObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isObjectLike.js b/app/node_modules/lodash/fp/isObjectLike.js new file mode 100644 index 0000000..f16082e --- /dev/null +++ b/app/node_modules/lodash/fp/isObjectLike.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isObjectLike', require('../isObjectLike'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isPlainObject.js b/app/node_modules/lodash/fp/isPlainObject.js new file mode 100644 index 0000000..b5bea90 --- /dev/null +++ b/app/node_modules/lodash/fp/isPlainObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isPlainObject', require('../isPlainObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isRegExp.js b/app/node_modules/lodash/fp/isRegExp.js new file mode 100644 index 0000000..12a1a3d --- /dev/null +++ b/app/node_modules/lodash/fp/isRegExp.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isRegExp', require('../isRegExp'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isSafeInteger.js b/app/node_modules/lodash/fp/isSafeInteger.js new file mode 100644 index 0000000..7230f55 --- /dev/null +++ b/app/node_modules/lodash/fp/isSafeInteger.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isSafeInteger', require('../isSafeInteger'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isSet.js b/app/node_modules/lodash/fp/isSet.js new file mode 100644 index 0000000..35c01f6 --- /dev/null +++ b/app/node_modules/lodash/fp/isSet.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isSet', require('../isSet'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isString.js b/app/node_modules/lodash/fp/isString.js new file mode 100644 index 0000000..1fd0679 --- /dev/null +++ b/app/node_modules/lodash/fp/isString.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isString', require('../isString'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isSymbol.js b/app/node_modules/lodash/fp/isSymbol.js new file mode 100644 index 0000000..3867695 --- /dev/null +++ b/app/node_modules/lodash/fp/isSymbol.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isSymbol', require('../isSymbol'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isTypedArray.js b/app/node_modules/lodash/fp/isTypedArray.js new file mode 100644 index 0000000..8567953 --- /dev/null +++ b/app/node_modules/lodash/fp/isTypedArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isTypedArray', require('../isTypedArray'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isUndefined.js b/app/node_modules/lodash/fp/isUndefined.js new file mode 100644 index 0000000..ddbca31 --- /dev/null +++ b/app/node_modules/lodash/fp/isUndefined.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isUndefined', require('../isUndefined'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isWeakMap.js b/app/node_modules/lodash/fp/isWeakMap.js new file mode 100644 index 0000000..ef60c61 --- /dev/null +++ b/app/node_modules/lodash/fp/isWeakMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isWeakMap', require('../isWeakMap'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/isWeakSet.js b/app/node_modules/lodash/fp/isWeakSet.js new file mode 100644 index 0000000..c99bfaa --- /dev/null +++ b/app/node_modules/lodash/fp/isWeakSet.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isWeakSet', require('../isWeakSet'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/iteratee.js b/app/node_modules/lodash/fp/iteratee.js new file mode 100644 index 0000000..9f0f717 --- /dev/null +++ b/app/node_modules/lodash/fp/iteratee.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('iteratee', require('../iteratee')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/join.js b/app/node_modules/lodash/fp/join.js new file mode 100644 index 0000000..a220e00 --- /dev/null +++ b/app/node_modules/lodash/fp/join.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('join', require('../join')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/juxt.js b/app/node_modules/lodash/fp/juxt.js new file mode 100644 index 0000000..f71e04e --- /dev/null +++ b/app/node_modules/lodash/fp/juxt.js @@ -0,0 +1 @@ +module.exports = require('./over'); diff --git a/app/node_modules/lodash/fp/kebabCase.js b/app/node_modules/lodash/fp/kebabCase.js new file mode 100644 index 0000000..60737f1 --- /dev/null +++ b/app/node_modules/lodash/fp/kebabCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('kebabCase', require('../kebabCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/keyBy.js b/app/node_modules/lodash/fp/keyBy.js new file mode 100644 index 0000000..9a6a85d --- /dev/null +++ b/app/node_modules/lodash/fp/keyBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('keyBy', require('../keyBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/keys.js b/app/node_modules/lodash/fp/keys.js new file mode 100644 index 0000000..e12bb07 --- /dev/null +++ b/app/node_modules/lodash/fp/keys.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('keys', require('../keys'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/keysIn.js b/app/node_modules/lodash/fp/keysIn.js new file mode 100644 index 0000000..f3eb36a --- /dev/null +++ b/app/node_modules/lodash/fp/keysIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('keysIn', require('../keysIn'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/lang.js b/app/node_modules/lodash/fp/lang.js new file mode 100644 index 0000000..08cc9c1 --- /dev/null +++ b/app/node_modules/lodash/fp/lang.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../lang')); diff --git a/app/node_modules/lodash/fp/last.js b/app/node_modules/lodash/fp/last.js new file mode 100644 index 0000000..0f71699 --- /dev/null +++ b/app/node_modules/lodash/fp/last.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('last', require('../last'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/lastIndexOf.js b/app/node_modules/lodash/fp/lastIndexOf.js new file mode 100644 index 0000000..ddf39c3 --- /dev/null +++ b/app/node_modules/lodash/fp/lastIndexOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lastIndexOf', require('../lastIndexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/lastIndexOfFrom.js b/app/node_modules/lodash/fp/lastIndexOfFrom.js new file mode 100644 index 0000000..1ff6a0b --- /dev/null +++ b/app/node_modules/lodash/fp/lastIndexOfFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lastIndexOfFrom', require('../lastIndexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/lowerCase.js b/app/node_modules/lodash/fp/lowerCase.js new file mode 100644 index 0000000..ea64bc1 --- /dev/null +++ b/app/node_modules/lodash/fp/lowerCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lowerCase', require('../lowerCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/lowerFirst.js b/app/node_modules/lodash/fp/lowerFirst.js new file mode 100644 index 0000000..539720a --- /dev/null +++ b/app/node_modules/lodash/fp/lowerFirst.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lowerFirst', require('../lowerFirst'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/lt.js b/app/node_modules/lodash/fp/lt.js new file mode 100644 index 0000000..a31d21e --- /dev/null +++ b/app/node_modules/lodash/fp/lt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lt', require('../lt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/lte.js b/app/node_modules/lodash/fp/lte.js new file mode 100644 index 0000000..d795d10 --- /dev/null +++ b/app/node_modules/lodash/fp/lte.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lte', require('../lte')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/map.js b/app/node_modules/lodash/fp/map.js new file mode 100644 index 0000000..cf98794 --- /dev/null +++ b/app/node_modules/lodash/fp/map.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('map', require('../map')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/mapKeys.js b/app/node_modules/lodash/fp/mapKeys.js new file mode 100644 index 0000000..1684587 --- /dev/null +++ b/app/node_modules/lodash/fp/mapKeys.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mapKeys', require('../mapKeys')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/mapValues.js b/app/node_modules/lodash/fp/mapValues.js new file mode 100644 index 0000000..4004972 --- /dev/null +++ b/app/node_modules/lodash/fp/mapValues.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mapValues', require('../mapValues')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/matches.js b/app/node_modules/lodash/fp/matches.js new file mode 100644 index 0000000..29d1e1e --- /dev/null +++ b/app/node_modules/lodash/fp/matches.js @@ -0,0 +1 @@ +module.exports = require('./isMatch'); diff --git a/app/node_modules/lodash/fp/matchesProperty.js b/app/node_modules/lodash/fp/matchesProperty.js new file mode 100644 index 0000000..4575bd2 --- /dev/null +++ b/app/node_modules/lodash/fp/matchesProperty.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('matchesProperty', require('../matchesProperty')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/math.js b/app/node_modules/lodash/fp/math.js new file mode 100644 index 0000000..e8f50f7 --- /dev/null +++ b/app/node_modules/lodash/fp/math.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../math')); diff --git a/app/node_modules/lodash/fp/max.js b/app/node_modules/lodash/fp/max.js new file mode 100644 index 0000000..a66acac --- /dev/null +++ b/app/node_modules/lodash/fp/max.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('max', require('../max'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/maxBy.js b/app/node_modules/lodash/fp/maxBy.js new file mode 100644 index 0000000..d083fd6 --- /dev/null +++ b/app/node_modules/lodash/fp/maxBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('maxBy', require('../maxBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/mean.js b/app/node_modules/lodash/fp/mean.js new file mode 100644 index 0000000..3117246 --- /dev/null +++ b/app/node_modules/lodash/fp/mean.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mean', require('../mean'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/meanBy.js b/app/node_modules/lodash/fp/meanBy.js new file mode 100644 index 0000000..556f25e --- /dev/null +++ b/app/node_modules/lodash/fp/meanBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('meanBy', require('../meanBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/memoize.js b/app/node_modules/lodash/fp/memoize.js new file mode 100644 index 0000000..638eec6 --- /dev/null +++ b/app/node_modules/lodash/fp/memoize.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('memoize', require('../memoize')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/merge.js b/app/node_modules/lodash/fp/merge.js new file mode 100644 index 0000000..ac66add --- /dev/null +++ b/app/node_modules/lodash/fp/merge.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('merge', require('../merge')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/mergeAll.js b/app/node_modules/lodash/fp/mergeAll.js new file mode 100644 index 0000000..a3674d6 --- /dev/null +++ b/app/node_modules/lodash/fp/mergeAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mergeAll', require('../merge')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/mergeAllWith.js b/app/node_modules/lodash/fp/mergeAllWith.js new file mode 100644 index 0000000..4bd4206 --- /dev/null +++ b/app/node_modules/lodash/fp/mergeAllWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mergeAllWith', require('../mergeWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/mergeWith.js b/app/node_modules/lodash/fp/mergeWith.js new file mode 100644 index 0000000..00d44d5 --- /dev/null +++ b/app/node_modules/lodash/fp/mergeWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mergeWith', require('../mergeWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/method.js b/app/node_modules/lodash/fp/method.js new file mode 100644 index 0000000..f4060c6 --- /dev/null +++ b/app/node_modules/lodash/fp/method.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('method', require('../method')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/methodOf.js b/app/node_modules/lodash/fp/methodOf.js new file mode 100644 index 0000000..6139905 --- /dev/null +++ b/app/node_modules/lodash/fp/methodOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('methodOf', require('../methodOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/min.js b/app/node_modules/lodash/fp/min.js new file mode 100644 index 0000000..d12c6b4 --- /dev/null +++ b/app/node_modules/lodash/fp/min.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('min', require('../min'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/minBy.js b/app/node_modules/lodash/fp/minBy.js new file mode 100644 index 0000000..fdb9e24 --- /dev/null +++ b/app/node_modules/lodash/fp/minBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('minBy', require('../minBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/mixin.js b/app/node_modules/lodash/fp/mixin.js new file mode 100644 index 0000000..332e6fb --- /dev/null +++ b/app/node_modules/lodash/fp/mixin.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mixin', require('../mixin')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/multiply.js b/app/node_modules/lodash/fp/multiply.js new file mode 100644 index 0000000..4dcf0b0 --- /dev/null +++ b/app/node_modules/lodash/fp/multiply.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('multiply', require('../multiply')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/nAry.js b/app/node_modules/lodash/fp/nAry.js new file mode 100644 index 0000000..f262a76 --- /dev/null +++ b/app/node_modules/lodash/fp/nAry.js @@ -0,0 +1 @@ +module.exports = require('./ary'); diff --git a/app/node_modules/lodash/fp/negate.js b/app/node_modules/lodash/fp/negate.js new file mode 100644 index 0000000..8b6dc7c --- /dev/null +++ b/app/node_modules/lodash/fp/negate.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('negate', require('../negate'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/next.js b/app/node_modules/lodash/fp/next.js new file mode 100644 index 0000000..140155e --- /dev/null +++ b/app/node_modules/lodash/fp/next.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('next', require('../next'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/noop.js b/app/node_modules/lodash/fp/noop.js new file mode 100644 index 0000000..b9e32cc --- /dev/null +++ b/app/node_modules/lodash/fp/noop.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('noop', require('../noop'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/now.js b/app/node_modules/lodash/fp/now.js new file mode 100644 index 0000000..6de2068 --- /dev/null +++ b/app/node_modules/lodash/fp/now.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('now', require('../now'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/nth.js b/app/node_modules/lodash/fp/nth.js new file mode 100644 index 0000000..da4fda7 --- /dev/null +++ b/app/node_modules/lodash/fp/nth.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('nth', require('../nth')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/nthArg.js b/app/node_modules/lodash/fp/nthArg.js new file mode 100644 index 0000000..fce3165 --- /dev/null +++ b/app/node_modules/lodash/fp/nthArg.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('nthArg', require('../nthArg')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/number.js b/app/node_modules/lodash/fp/number.js new file mode 100644 index 0000000..5c10b88 --- /dev/null +++ b/app/node_modules/lodash/fp/number.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../number')); diff --git a/app/node_modules/lodash/fp/object.js b/app/node_modules/lodash/fp/object.js new file mode 100644 index 0000000..ae39a13 --- /dev/null +++ b/app/node_modules/lodash/fp/object.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../object')); diff --git a/app/node_modules/lodash/fp/omit.js b/app/node_modules/lodash/fp/omit.js new file mode 100644 index 0000000..fd68529 --- /dev/null +++ b/app/node_modules/lodash/fp/omit.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('omit', require('../omit')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/omitAll.js b/app/node_modules/lodash/fp/omitAll.js new file mode 100644 index 0000000..144cf4b --- /dev/null +++ b/app/node_modules/lodash/fp/omitAll.js @@ -0,0 +1 @@ +module.exports = require('./omit'); diff --git a/app/node_modules/lodash/fp/omitBy.js b/app/node_modules/lodash/fp/omitBy.js new file mode 100644 index 0000000..90df738 --- /dev/null +++ b/app/node_modules/lodash/fp/omitBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('omitBy', require('../omitBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/once.js b/app/node_modules/lodash/fp/once.js new file mode 100644 index 0000000..f8f0a5c --- /dev/null +++ b/app/node_modules/lodash/fp/once.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('once', require('../once'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/orderBy.js b/app/node_modules/lodash/fp/orderBy.js new file mode 100644 index 0000000..848e210 --- /dev/null +++ b/app/node_modules/lodash/fp/orderBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('orderBy', require('../orderBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/over.js b/app/node_modules/lodash/fp/over.js new file mode 100644 index 0000000..01eba7b --- /dev/null +++ b/app/node_modules/lodash/fp/over.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('over', require('../over')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/overArgs.js b/app/node_modules/lodash/fp/overArgs.js new file mode 100644 index 0000000..738556f --- /dev/null +++ b/app/node_modules/lodash/fp/overArgs.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('overArgs', require('../overArgs')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/overEvery.js b/app/node_modules/lodash/fp/overEvery.js new file mode 100644 index 0000000..9f5a032 --- /dev/null +++ b/app/node_modules/lodash/fp/overEvery.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('overEvery', require('../overEvery')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/overSome.js b/app/node_modules/lodash/fp/overSome.js new file mode 100644 index 0000000..15939d5 --- /dev/null +++ b/app/node_modules/lodash/fp/overSome.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('overSome', require('../overSome')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/pad.js b/app/node_modules/lodash/fp/pad.js new file mode 100644 index 0000000..f1dea4a --- /dev/null +++ b/app/node_modules/lodash/fp/pad.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pad', require('../pad')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/padChars.js b/app/node_modules/lodash/fp/padChars.js new file mode 100644 index 0000000..d6e0804 --- /dev/null +++ b/app/node_modules/lodash/fp/padChars.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padChars', require('../pad')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/padCharsEnd.js b/app/node_modules/lodash/fp/padCharsEnd.js new file mode 100644 index 0000000..d4ab79a --- /dev/null +++ b/app/node_modules/lodash/fp/padCharsEnd.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padCharsEnd', require('../padEnd')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/padCharsStart.js b/app/node_modules/lodash/fp/padCharsStart.js new file mode 100644 index 0000000..a08a300 --- /dev/null +++ b/app/node_modules/lodash/fp/padCharsStart.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padCharsStart', require('../padStart')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/padEnd.js b/app/node_modules/lodash/fp/padEnd.js new file mode 100644 index 0000000..a8522ec --- /dev/null +++ b/app/node_modules/lodash/fp/padEnd.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padEnd', require('../padEnd')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/padStart.js b/app/node_modules/lodash/fp/padStart.js new file mode 100644 index 0000000..f4ca79d --- /dev/null +++ b/app/node_modules/lodash/fp/padStart.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padStart', require('../padStart')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/parseInt.js b/app/node_modules/lodash/fp/parseInt.js new file mode 100644 index 0000000..27314cc --- /dev/null +++ b/app/node_modules/lodash/fp/parseInt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('parseInt', require('../parseInt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/partial.js b/app/node_modules/lodash/fp/partial.js new file mode 100644 index 0000000..5d46015 --- /dev/null +++ b/app/node_modules/lodash/fp/partial.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('partial', require('../partial')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/partialRight.js b/app/node_modules/lodash/fp/partialRight.js new file mode 100644 index 0000000..7f05fed --- /dev/null +++ b/app/node_modules/lodash/fp/partialRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('partialRight', require('../partialRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/partition.js b/app/node_modules/lodash/fp/partition.js new file mode 100644 index 0000000..2ebcacc --- /dev/null +++ b/app/node_modules/lodash/fp/partition.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('partition', require('../partition')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/path.js b/app/node_modules/lodash/fp/path.js new file mode 100644 index 0000000..b29cfb2 --- /dev/null +++ b/app/node_modules/lodash/fp/path.js @@ -0,0 +1 @@ +module.exports = require('./get'); diff --git a/app/node_modules/lodash/fp/pathEq.js b/app/node_modules/lodash/fp/pathEq.js new file mode 100644 index 0000000..36c027a --- /dev/null +++ b/app/node_modules/lodash/fp/pathEq.js @@ -0,0 +1 @@ +module.exports = require('./matchesProperty'); diff --git a/app/node_modules/lodash/fp/pathOr.js b/app/node_modules/lodash/fp/pathOr.js new file mode 100644 index 0000000..4ab5820 --- /dev/null +++ b/app/node_modules/lodash/fp/pathOr.js @@ -0,0 +1 @@ +module.exports = require('./getOr'); diff --git a/app/node_modules/lodash/fp/paths.js b/app/node_modules/lodash/fp/paths.js new file mode 100644 index 0000000..1eb7950 --- /dev/null +++ b/app/node_modules/lodash/fp/paths.js @@ -0,0 +1 @@ +module.exports = require('./at'); diff --git a/app/node_modules/lodash/fp/pick.js b/app/node_modules/lodash/fp/pick.js new file mode 100644 index 0000000..197393d --- /dev/null +++ b/app/node_modules/lodash/fp/pick.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pick', require('../pick')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/pickAll.js b/app/node_modules/lodash/fp/pickAll.js new file mode 100644 index 0000000..a8ecd46 --- /dev/null +++ b/app/node_modules/lodash/fp/pickAll.js @@ -0,0 +1 @@ +module.exports = require('./pick'); diff --git a/app/node_modules/lodash/fp/pickBy.js b/app/node_modules/lodash/fp/pickBy.js new file mode 100644 index 0000000..d832d16 --- /dev/null +++ b/app/node_modules/lodash/fp/pickBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pickBy', require('../pickBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/pipe.js b/app/node_modules/lodash/fp/pipe.js new file mode 100644 index 0000000..b2e1e2c --- /dev/null +++ b/app/node_modules/lodash/fp/pipe.js @@ -0,0 +1 @@ +module.exports = require('./flow'); diff --git a/app/node_modules/lodash/fp/placeholder.js b/app/node_modules/lodash/fp/placeholder.js new file mode 100644 index 0000000..1ce1739 --- /dev/null +++ b/app/node_modules/lodash/fp/placeholder.js @@ -0,0 +1,6 @@ +/** + * The default argument placeholder value for methods. + * + * @type {Object} + */ +module.exports = {}; diff --git a/app/node_modules/lodash/fp/plant.js b/app/node_modules/lodash/fp/plant.js new file mode 100644 index 0000000..eca8f32 --- /dev/null +++ b/app/node_modules/lodash/fp/plant.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('plant', require('../plant'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/pluck.js b/app/node_modules/lodash/fp/pluck.js new file mode 100644 index 0000000..0d1e1ab --- /dev/null +++ b/app/node_modules/lodash/fp/pluck.js @@ -0,0 +1 @@ +module.exports = require('./map'); diff --git a/app/node_modules/lodash/fp/prop.js b/app/node_modules/lodash/fp/prop.js new file mode 100644 index 0000000..b29cfb2 --- /dev/null +++ b/app/node_modules/lodash/fp/prop.js @@ -0,0 +1 @@ +module.exports = require('./get'); diff --git a/app/node_modules/lodash/fp/propEq.js b/app/node_modules/lodash/fp/propEq.js new file mode 100644 index 0000000..36c027a --- /dev/null +++ b/app/node_modules/lodash/fp/propEq.js @@ -0,0 +1 @@ +module.exports = require('./matchesProperty'); diff --git a/app/node_modules/lodash/fp/propOr.js b/app/node_modules/lodash/fp/propOr.js new file mode 100644 index 0000000..4ab5820 --- /dev/null +++ b/app/node_modules/lodash/fp/propOr.js @@ -0,0 +1 @@ +module.exports = require('./getOr'); diff --git a/app/node_modules/lodash/fp/property.js b/app/node_modules/lodash/fp/property.js new file mode 100644 index 0000000..b29cfb2 --- /dev/null +++ b/app/node_modules/lodash/fp/property.js @@ -0,0 +1 @@ +module.exports = require('./get'); diff --git a/app/node_modules/lodash/fp/propertyOf.js b/app/node_modules/lodash/fp/propertyOf.js new file mode 100644 index 0000000..f6273ee --- /dev/null +++ b/app/node_modules/lodash/fp/propertyOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('propertyOf', require('../get')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/props.js b/app/node_modules/lodash/fp/props.js new file mode 100644 index 0000000..1eb7950 --- /dev/null +++ b/app/node_modules/lodash/fp/props.js @@ -0,0 +1 @@ +module.exports = require('./at'); diff --git a/app/node_modules/lodash/fp/pull.js b/app/node_modules/lodash/fp/pull.js new file mode 100644 index 0000000..8d7084f --- /dev/null +++ b/app/node_modules/lodash/fp/pull.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pull', require('../pull')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/pullAll.js b/app/node_modules/lodash/fp/pullAll.js new file mode 100644 index 0000000..98d5c9a --- /dev/null +++ b/app/node_modules/lodash/fp/pullAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pullAll', require('../pullAll')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/pullAllBy.js b/app/node_modules/lodash/fp/pullAllBy.js new file mode 100644 index 0000000..876bc3b --- /dev/null +++ b/app/node_modules/lodash/fp/pullAllBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pullAllBy', require('../pullAllBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/pullAllWith.js b/app/node_modules/lodash/fp/pullAllWith.js new file mode 100644 index 0000000..f71ba4d --- /dev/null +++ b/app/node_modules/lodash/fp/pullAllWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pullAllWith', require('../pullAllWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/pullAt.js b/app/node_modules/lodash/fp/pullAt.js new file mode 100644 index 0000000..e8b3bb6 --- /dev/null +++ b/app/node_modules/lodash/fp/pullAt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pullAt', require('../pullAt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/random.js b/app/node_modules/lodash/fp/random.js new file mode 100644 index 0000000..99d852e --- /dev/null +++ b/app/node_modules/lodash/fp/random.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('random', require('../random')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/range.js b/app/node_modules/lodash/fp/range.js new file mode 100644 index 0000000..a6bb591 --- /dev/null +++ b/app/node_modules/lodash/fp/range.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('range', require('../range')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/rangeRight.js b/app/node_modules/lodash/fp/rangeRight.js new file mode 100644 index 0000000..fdb712f --- /dev/null +++ b/app/node_modules/lodash/fp/rangeRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rangeRight', require('../rangeRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/rangeStep.js b/app/node_modules/lodash/fp/rangeStep.js new file mode 100644 index 0000000..d72dfc2 --- /dev/null +++ b/app/node_modules/lodash/fp/rangeStep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rangeStep', require('../range')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/rangeStepRight.js b/app/node_modules/lodash/fp/rangeStepRight.js new file mode 100644 index 0000000..8b2a67b --- /dev/null +++ b/app/node_modules/lodash/fp/rangeStepRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rangeStepRight', require('../rangeRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/rearg.js b/app/node_modules/lodash/fp/rearg.js new file mode 100644 index 0000000..678e02a --- /dev/null +++ b/app/node_modules/lodash/fp/rearg.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rearg', require('../rearg')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/reduce.js b/app/node_modules/lodash/fp/reduce.js new file mode 100644 index 0000000..4cef0a0 --- /dev/null +++ b/app/node_modules/lodash/fp/reduce.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('reduce', require('../reduce')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/reduceRight.js b/app/node_modules/lodash/fp/reduceRight.js new file mode 100644 index 0000000..caf5bb5 --- /dev/null +++ b/app/node_modules/lodash/fp/reduceRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('reduceRight', require('../reduceRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/reject.js b/app/node_modules/lodash/fp/reject.js new file mode 100644 index 0000000..c163273 --- /dev/null +++ b/app/node_modules/lodash/fp/reject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('reject', require('../reject')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/remove.js b/app/node_modules/lodash/fp/remove.js new file mode 100644 index 0000000..e9d1327 --- /dev/null +++ b/app/node_modules/lodash/fp/remove.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('remove', require('../remove')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/repeat.js b/app/node_modules/lodash/fp/repeat.js new file mode 100644 index 0000000..08470f2 --- /dev/null +++ b/app/node_modules/lodash/fp/repeat.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('repeat', require('../repeat')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/replace.js b/app/node_modules/lodash/fp/replace.js new file mode 100644 index 0000000..2227db6 --- /dev/null +++ b/app/node_modules/lodash/fp/replace.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('replace', require('../replace')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/rest.js b/app/node_modules/lodash/fp/rest.js new file mode 100644 index 0000000..c1f3d64 --- /dev/null +++ b/app/node_modules/lodash/fp/rest.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rest', require('../rest')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/restFrom.js b/app/node_modules/lodash/fp/restFrom.js new file mode 100644 index 0000000..714e42b --- /dev/null +++ b/app/node_modules/lodash/fp/restFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('restFrom', require('../rest')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/result.js b/app/node_modules/lodash/fp/result.js new file mode 100644 index 0000000..f86ce07 --- /dev/null +++ b/app/node_modules/lodash/fp/result.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('result', require('../result')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/reverse.js b/app/node_modules/lodash/fp/reverse.js new file mode 100644 index 0000000..07c9f5e --- /dev/null +++ b/app/node_modules/lodash/fp/reverse.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('reverse', require('../reverse')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/round.js b/app/node_modules/lodash/fp/round.js new file mode 100644 index 0000000..4c0e5c8 --- /dev/null +++ b/app/node_modules/lodash/fp/round.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('round', require('../round')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/sample.js b/app/node_modules/lodash/fp/sample.js new file mode 100644 index 0000000..6bea125 --- /dev/null +++ b/app/node_modules/lodash/fp/sample.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sample', require('../sample'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/sampleSize.js b/app/node_modules/lodash/fp/sampleSize.js new file mode 100644 index 0000000..359ed6f --- /dev/null +++ b/app/node_modules/lodash/fp/sampleSize.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sampleSize', require('../sampleSize')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/seq.js b/app/node_modules/lodash/fp/seq.js new file mode 100644 index 0000000..d8f42b0 --- /dev/null +++ b/app/node_modules/lodash/fp/seq.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../seq')); diff --git a/app/node_modules/lodash/fp/set.js b/app/node_modules/lodash/fp/set.js new file mode 100644 index 0000000..0b56a56 --- /dev/null +++ b/app/node_modules/lodash/fp/set.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('set', require('../set')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/setWith.js b/app/node_modules/lodash/fp/setWith.js new file mode 100644 index 0000000..0b58495 --- /dev/null +++ b/app/node_modules/lodash/fp/setWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('setWith', require('../setWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/shuffle.js b/app/node_modules/lodash/fp/shuffle.js new file mode 100644 index 0000000..aa3a1ca --- /dev/null +++ b/app/node_modules/lodash/fp/shuffle.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('shuffle', require('../shuffle'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/size.js b/app/node_modules/lodash/fp/size.js new file mode 100644 index 0000000..7490136 --- /dev/null +++ b/app/node_modules/lodash/fp/size.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('size', require('../size'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/slice.js b/app/node_modules/lodash/fp/slice.js new file mode 100644 index 0000000..15945d3 --- /dev/null +++ b/app/node_modules/lodash/fp/slice.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('slice', require('../slice')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/snakeCase.js b/app/node_modules/lodash/fp/snakeCase.js new file mode 100644 index 0000000..a0ff780 --- /dev/null +++ b/app/node_modules/lodash/fp/snakeCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('snakeCase', require('../snakeCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/some.js b/app/node_modules/lodash/fp/some.js new file mode 100644 index 0000000..a4fa2d0 --- /dev/null +++ b/app/node_modules/lodash/fp/some.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('some', require('../some')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/sortBy.js b/app/node_modules/lodash/fp/sortBy.js new file mode 100644 index 0000000..e0790ad --- /dev/null +++ b/app/node_modules/lodash/fp/sortBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortBy', require('../sortBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/sortedIndex.js b/app/node_modules/lodash/fp/sortedIndex.js new file mode 100644 index 0000000..364a054 --- /dev/null +++ b/app/node_modules/lodash/fp/sortedIndex.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedIndex', require('../sortedIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/sortedIndexBy.js b/app/node_modules/lodash/fp/sortedIndexBy.js new file mode 100644 index 0000000..9593dbd --- /dev/null +++ b/app/node_modules/lodash/fp/sortedIndexBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedIndexBy', require('../sortedIndexBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/sortedIndexOf.js b/app/node_modules/lodash/fp/sortedIndexOf.js new file mode 100644 index 0000000..c9084ca --- /dev/null +++ b/app/node_modules/lodash/fp/sortedIndexOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedIndexOf', require('../sortedIndexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/sortedLastIndex.js b/app/node_modules/lodash/fp/sortedLastIndex.js new file mode 100644 index 0000000..47fe241 --- /dev/null +++ b/app/node_modules/lodash/fp/sortedLastIndex.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedLastIndex', require('../sortedLastIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/sortedLastIndexBy.js b/app/node_modules/lodash/fp/sortedLastIndexBy.js new file mode 100644 index 0000000..0f9a347 --- /dev/null +++ b/app/node_modules/lodash/fp/sortedLastIndexBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedLastIndexBy', require('../sortedLastIndexBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/sortedLastIndexOf.js b/app/node_modules/lodash/fp/sortedLastIndexOf.js new file mode 100644 index 0000000..0d4d932 --- /dev/null +++ b/app/node_modules/lodash/fp/sortedLastIndexOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedLastIndexOf', require('../sortedLastIndexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/sortedUniq.js b/app/node_modules/lodash/fp/sortedUniq.js new file mode 100644 index 0000000..882d283 --- /dev/null +++ b/app/node_modules/lodash/fp/sortedUniq.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedUniq', require('../sortedUniq'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/sortedUniqBy.js b/app/node_modules/lodash/fp/sortedUniqBy.js new file mode 100644 index 0000000..033db91 --- /dev/null +++ b/app/node_modules/lodash/fp/sortedUniqBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedUniqBy', require('../sortedUniqBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/split.js b/app/node_modules/lodash/fp/split.js new file mode 100644 index 0000000..14de1a7 --- /dev/null +++ b/app/node_modules/lodash/fp/split.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('split', require('../split')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/spread.js b/app/node_modules/lodash/fp/spread.js new file mode 100644 index 0000000..2d11b70 --- /dev/null +++ b/app/node_modules/lodash/fp/spread.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('spread', require('../spread')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/spreadFrom.js b/app/node_modules/lodash/fp/spreadFrom.js new file mode 100644 index 0000000..0b630df --- /dev/null +++ b/app/node_modules/lodash/fp/spreadFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('spreadFrom', require('../spread')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/startCase.js b/app/node_modules/lodash/fp/startCase.js new file mode 100644 index 0000000..ada98c9 --- /dev/null +++ b/app/node_modules/lodash/fp/startCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('startCase', require('../startCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/startsWith.js b/app/node_modules/lodash/fp/startsWith.js new file mode 100644 index 0000000..985e2f2 --- /dev/null +++ b/app/node_modules/lodash/fp/startsWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('startsWith', require('../startsWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/string.js b/app/node_modules/lodash/fp/string.js new file mode 100644 index 0000000..773b037 --- /dev/null +++ b/app/node_modules/lodash/fp/string.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../string')); diff --git a/app/node_modules/lodash/fp/stubArray.js b/app/node_modules/lodash/fp/stubArray.js new file mode 100644 index 0000000..cd604cb --- /dev/null +++ b/app/node_modules/lodash/fp/stubArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubArray', require('../stubArray'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/stubFalse.js b/app/node_modules/lodash/fp/stubFalse.js new file mode 100644 index 0000000..3296664 --- /dev/null +++ b/app/node_modules/lodash/fp/stubFalse.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubFalse', require('../stubFalse'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/stubObject.js b/app/node_modules/lodash/fp/stubObject.js new file mode 100644 index 0000000..c6c8ec4 --- /dev/null +++ b/app/node_modules/lodash/fp/stubObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubObject', require('../stubObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/stubString.js b/app/node_modules/lodash/fp/stubString.js new file mode 100644 index 0000000..701051e --- /dev/null +++ b/app/node_modules/lodash/fp/stubString.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubString', require('../stubString'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/stubTrue.js b/app/node_modules/lodash/fp/stubTrue.js new file mode 100644 index 0000000..9249082 --- /dev/null +++ b/app/node_modules/lodash/fp/stubTrue.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubTrue', require('../stubTrue'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/subtract.js b/app/node_modules/lodash/fp/subtract.js new file mode 100644 index 0000000..d32b16d --- /dev/null +++ b/app/node_modules/lodash/fp/subtract.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('subtract', require('../subtract')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/sum.js b/app/node_modules/lodash/fp/sum.js new file mode 100644 index 0000000..5cce12b --- /dev/null +++ b/app/node_modules/lodash/fp/sum.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sum', require('../sum'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/sumBy.js b/app/node_modules/lodash/fp/sumBy.js new file mode 100644 index 0000000..c882656 --- /dev/null +++ b/app/node_modules/lodash/fp/sumBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sumBy', require('../sumBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/symmetricDifference.js b/app/node_modules/lodash/fp/symmetricDifference.js new file mode 100644 index 0000000..78c16ad --- /dev/null +++ b/app/node_modules/lodash/fp/symmetricDifference.js @@ -0,0 +1 @@ +module.exports = require('./xor'); diff --git a/app/node_modules/lodash/fp/symmetricDifferenceBy.js b/app/node_modules/lodash/fp/symmetricDifferenceBy.js new file mode 100644 index 0000000..298fc7f --- /dev/null +++ b/app/node_modules/lodash/fp/symmetricDifferenceBy.js @@ -0,0 +1 @@ +module.exports = require('./xorBy'); diff --git a/app/node_modules/lodash/fp/symmetricDifferenceWith.js b/app/node_modules/lodash/fp/symmetricDifferenceWith.js new file mode 100644 index 0000000..70bc6fa --- /dev/null +++ b/app/node_modules/lodash/fp/symmetricDifferenceWith.js @@ -0,0 +1 @@ +module.exports = require('./xorWith'); diff --git a/app/node_modules/lodash/fp/tail.js b/app/node_modules/lodash/fp/tail.js new file mode 100644 index 0000000..f122f0a --- /dev/null +++ b/app/node_modules/lodash/fp/tail.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('tail', require('../tail'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/take.js b/app/node_modules/lodash/fp/take.js new file mode 100644 index 0000000..9af98a7 --- /dev/null +++ b/app/node_modules/lodash/fp/take.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('take', require('../take')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/takeLast.js b/app/node_modules/lodash/fp/takeLast.js new file mode 100644 index 0000000..e98c84a --- /dev/null +++ b/app/node_modules/lodash/fp/takeLast.js @@ -0,0 +1 @@ +module.exports = require('./takeRight'); diff --git a/app/node_modules/lodash/fp/takeLastWhile.js b/app/node_modules/lodash/fp/takeLastWhile.js new file mode 100644 index 0000000..5367968 --- /dev/null +++ b/app/node_modules/lodash/fp/takeLastWhile.js @@ -0,0 +1 @@ +module.exports = require('./takeRightWhile'); diff --git a/app/node_modules/lodash/fp/takeRight.js b/app/node_modules/lodash/fp/takeRight.js new file mode 100644 index 0000000..b82950a --- /dev/null +++ b/app/node_modules/lodash/fp/takeRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('takeRight', require('../takeRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/takeRightWhile.js b/app/node_modules/lodash/fp/takeRightWhile.js new file mode 100644 index 0000000..8ffb0a2 --- /dev/null +++ b/app/node_modules/lodash/fp/takeRightWhile.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('takeRightWhile', require('../takeRightWhile')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/takeWhile.js b/app/node_modules/lodash/fp/takeWhile.js new file mode 100644 index 0000000..2813664 --- /dev/null +++ b/app/node_modules/lodash/fp/takeWhile.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('takeWhile', require('../takeWhile')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/tap.js b/app/node_modules/lodash/fp/tap.js new file mode 100644 index 0000000..d33ad6e --- /dev/null +++ b/app/node_modules/lodash/fp/tap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('tap', require('../tap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/template.js b/app/node_modules/lodash/fp/template.js new file mode 100644 index 0000000..74857e1 --- /dev/null +++ b/app/node_modules/lodash/fp/template.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('template', require('../template')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/templateSettings.js b/app/node_modules/lodash/fp/templateSettings.js new file mode 100644 index 0000000..7bcc0a8 --- /dev/null +++ b/app/node_modules/lodash/fp/templateSettings.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('templateSettings', require('../templateSettings'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/throttle.js b/app/node_modules/lodash/fp/throttle.js new file mode 100644 index 0000000..77fff14 --- /dev/null +++ b/app/node_modules/lodash/fp/throttle.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('throttle', require('../throttle')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/thru.js b/app/node_modules/lodash/fp/thru.js new file mode 100644 index 0000000..d42b3b1 --- /dev/null +++ b/app/node_modules/lodash/fp/thru.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('thru', require('../thru')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/times.js b/app/node_modules/lodash/fp/times.js new file mode 100644 index 0000000..0dab06d --- /dev/null +++ b/app/node_modules/lodash/fp/times.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('times', require('../times')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toArray.js b/app/node_modules/lodash/fp/toArray.js new file mode 100644 index 0000000..f0c360a --- /dev/null +++ b/app/node_modules/lodash/fp/toArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toArray', require('../toArray'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toFinite.js b/app/node_modules/lodash/fp/toFinite.js new file mode 100644 index 0000000..3a47687 --- /dev/null +++ b/app/node_modules/lodash/fp/toFinite.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toFinite', require('../toFinite'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toInteger.js b/app/node_modules/lodash/fp/toInteger.js new file mode 100644 index 0000000..e0af6a7 --- /dev/null +++ b/app/node_modules/lodash/fp/toInteger.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toInteger', require('../toInteger'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toIterator.js b/app/node_modules/lodash/fp/toIterator.js new file mode 100644 index 0000000..65e6baa --- /dev/null +++ b/app/node_modules/lodash/fp/toIterator.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toIterator', require('../toIterator'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toJSON.js b/app/node_modules/lodash/fp/toJSON.js new file mode 100644 index 0000000..2d718d0 --- /dev/null +++ b/app/node_modules/lodash/fp/toJSON.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toJSON', require('../toJSON'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toLength.js b/app/node_modules/lodash/fp/toLength.js new file mode 100644 index 0000000..b97cdd9 --- /dev/null +++ b/app/node_modules/lodash/fp/toLength.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toLength', require('../toLength'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toLower.js b/app/node_modules/lodash/fp/toLower.js new file mode 100644 index 0000000..616ef36 --- /dev/null +++ b/app/node_modules/lodash/fp/toLower.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toLower', require('../toLower'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toNumber.js b/app/node_modules/lodash/fp/toNumber.js new file mode 100644 index 0000000..d0c6f4d --- /dev/null +++ b/app/node_modules/lodash/fp/toNumber.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toNumber', require('../toNumber'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toPairs.js b/app/node_modules/lodash/fp/toPairs.js new file mode 100644 index 0000000..af78378 --- /dev/null +++ b/app/node_modules/lodash/fp/toPairs.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toPairs', require('../toPairs'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toPairsIn.js b/app/node_modules/lodash/fp/toPairsIn.js new file mode 100644 index 0000000..66504ab --- /dev/null +++ b/app/node_modules/lodash/fp/toPairsIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toPairsIn', require('../toPairsIn'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toPath.js b/app/node_modules/lodash/fp/toPath.js new file mode 100644 index 0000000..b4d5e50 --- /dev/null +++ b/app/node_modules/lodash/fp/toPath.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toPath', require('../toPath'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toPlainObject.js b/app/node_modules/lodash/fp/toPlainObject.js new file mode 100644 index 0000000..278bb86 --- /dev/null +++ b/app/node_modules/lodash/fp/toPlainObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toPlainObject', require('../toPlainObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toSafeInteger.js b/app/node_modules/lodash/fp/toSafeInteger.js new file mode 100644 index 0000000..367a26f --- /dev/null +++ b/app/node_modules/lodash/fp/toSafeInteger.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toSafeInteger', require('../toSafeInteger'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toString.js b/app/node_modules/lodash/fp/toString.js new file mode 100644 index 0000000..cec4f8e --- /dev/null +++ b/app/node_modules/lodash/fp/toString.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toString', require('../toString'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/toUpper.js b/app/node_modules/lodash/fp/toUpper.js new file mode 100644 index 0000000..54f9a56 --- /dev/null +++ b/app/node_modules/lodash/fp/toUpper.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toUpper', require('../toUpper'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/transform.js b/app/node_modules/lodash/fp/transform.js new file mode 100644 index 0000000..759d088 --- /dev/null +++ b/app/node_modules/lodash/fp/transform.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('transform', require('../transform')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/trim.js b/app/node_modules/lodash/fp/trim.js new file mode 100644 index 0000000..e6319a7 --- /dev/null +++ b/app/node_modules/lodash/fp/trim.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trim', require('../trim')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/trimChars.js b/app/node_modules/lodash/fp/trimChars.js new file mode 100644 index 0000000..c9294de --- /dev/null +++ b/app/node_modules/lodash/fp/trimChars.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimChars', require('../trim')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/trimCharsEnd.js b/app/node_modules/lodash/fp/trimCharsEnd.js new file mode 100644 index 0000000..284bc2f --- /dev/null +++ b/app/node_modules/lodash/fp/trimCharsEnd.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimCharsEnd', require('../trimEnd')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/trimCharsStart.js b/app/node_modules/lodash/fp/trimCharsStart.js new file mode 100644 index 0000000..ff0ee65 --- /dev/null +++ b/app/node_modules/lodash/fp/trimCharsStart.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimCharsStart', require('../trimStart')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/trimEnd.js b/app/node_modules/lodash/fp/trimEnd.js new file mode 100644 index 0000000..7190880 --- /dev/null +++ b/app/node_modules/lodash/fp/trimEnd.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimEnd', require('../trimEnd')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/trimStart.js b/app/node_modules/lodash/fp/trimStart.js new file mode 100644 index 0000000..fda902c --- /dev/null +++ b/app/node_modules/lodash/fp/trimStart.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimStart', require('../trimStart')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/truncate.js b/app/node_modules/lodash/fp/truncate.js new file mode 100644 index 0000000..d265c1d --- /dev/null +++ b/app/node_modules/lodash/fp/truncate.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('truncate', require('../truncate')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/unapply.js b/app/node_modules/lodash/fp/unapply.js new file mode 100644 index 0000000..c5dfe77 --- /dev/null +++ b/app/node_modules/lodash/fp/unapply.js @@ -0,0 +1 @@ +module.exports = require('./rest'); diff --git a/app/node_modules/lodash/fp/unary.js b/app/node_modules/lodash/fp/unary.js new file mode 100644 index 0000000..286c945 --- /dev/null +++ b/app/node_modules/lodash/fp/unary.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unary', require('../unary'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/unescape.js b/app/node_modules/lodash/fp/unescape.js new file mode 100644 index 0000000..fddcb46 --- /dev/null +++ b/app/node_modules/lodash/fp/unescape.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unescape', require('../unescape'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/union.js b/app/node_modules/lodash/fp/union.js new file mode 100644 index 0000000..ef8228d --- /dev/null +++ b/app/node_modules/lodash/fp/union.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('union', require('../union')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/unionBy.js b/app/node_modules/lodash/fp/unionBy.js new file mode 100644 index 0000000..603687a --- /dev/null +++ b/app/node_modules/lodash/fp/unionBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unionBy', require('../unionBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/unionWith.js b/app/node_modules/lodash/fp/unionWith.js new file mode 100644 index 0000000..65bb3a7 --- /dev/null +++ b/app/node_modules/lodash/fp/unionWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unionWith', require('../unionWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/uniq.js b/app/node_modules/lodash/fp/uniq.js new file mode 100644 index 0000000..bc18524 --- /dev/null +++ b/app/node_modules/lodash/fp/uniq.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('uniq', require('../uniq'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/uniqBy.js b/app/node_modules/lodash/fp/uniqBy.js new file mode 100644 index 0000000..634c6a8 --- /dev/null +++ b/app/node_modules/lodash/fp/uniqBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('uniqBy', require('../uniqBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/uniqWith.js b/app/node_modules/lodash/fp/uniqWith.js new file mode 100644 index 0000000..0ec601a --- /dev/null +++ b/app/node_modules/lodash/fp/uniqWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('uniqWith', require('../uniqWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/uniqueId.js b/app/node_modules/lodash/fp/uniqueId.js new file mode 100644 index 0000000..aa8fc2f --- /dev/null +++ b/app/node_modules/lodash/fp/uniqueId.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('uniqueId', require('../uniqueId')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/unnest.js b/app/node_modules/lodash/fp/unnest.js new file mode 100644 index 0000000..5d34060 --- /dev/null +++ b/app/node_modules/lodash/fp/unnest.js @@ -0,0 +1 @@ +module.exports = require('./flatten'); diff --git a/app/node_modules/lodash/fp/unset.js b/app/node_modules/lodash/fp/unset.js new file mode 100644 index 0000000..ea203a0 --- /dev/null +++ b/app/node_modules/lodash/fp/unset.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unset', require('../unset')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/unzip.js b/app/node_modules/lodash/fp/unzip.js new file mode 100644 index 0000000..cc364b3 --- /dev/null +++ b/app/node_modules/lodash/fp/unzip.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unzip', require('../unzip'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/unzipWith.js b/app/node_modules/lodash/fp/unzipWith.js new file mode 100644 index 0000000..182eaa1 --- /dev/null +++ b/app/node_modules/lodash/fp/unzipWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unzipWith', require('../unzipWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/update.js b/app/node_modules/lodash/fp/update.js new file mode 100644 index 0000000..b8ce2cc --- /dev/null +++ b/app/node_modules/lodash/fp/update.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('update', require('../update')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/updateWith.js b/app/node_modules/lodash/fp/updateWith.js new file mode 100644 index 0000000..d5e8282 --- /dev/null +++ b/app/node_modules/lodash/fp/updateWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('updateWith', require('../updateWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/upperCase.js b/app/node_modules/lodash/fp/upperCase.js new file mode 100644 index 0000000..c886f20 --- /dev/null +++ b/app/node_modules/lodash/fp/upperCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('upperCase', require('../upperCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/upperFirst.js b/app/node_modules/lodash/fp/upperFirst.js new file mode 100644 index 0000000..d8c04df --- /dev/null +++ b/app/node_modules/lodash/fp/upperFirst.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('upperFirst', require('../upperFirst'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/useWith.js b/app/node_modules/lodash/fp/useWith.js new file mode 100644 index 0000000..d8b3df5 --- /dev/null +++ b/app/node_modules/lodash/fp/useWith.js @@ -0,0 +1 @@ +module.exports = require('./overArgs'); diff --git a/app/node_modules/lodash/fp/util.js b/app/node_modules/lodash/fp/util.js new file mode 100644 index 0000000..18c00ba --- /dev/null +++ b/app/node_modules/lodash/fp/util.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../util')); diff --git a/app/node_modules/lodash/fp/value.js b/app/node_modules/lodash/fp/value.js new file mode 100644 index 0000000..555eec7 --- /dev/null +++ b/app/node_modules/lodash/fp/value.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('value', require('../value'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/valueOf.js b/app/node_modules/lodash/fp/valueOf.js new file mode 100644 index 0000000..f968807 --- /dev/null +++ b/app/node_modules/lodash/fp/valueOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('valueOf', require('../valueOf'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/values.js b/app/node_modules/lodash/fp/values.js new file mode 100644 index 0000000..2dfc561 --- /dev/null +++ b/app/node_modules/lodash/fp/values.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('values', require('../values'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/valuesIn.js b/app/node_modules/lodash/fp/valuesIn.js new file mode 100644 index 0000000..a1b2bb8 --- /dev/null +++ b/app/node_modules/lodash/fp/valuesIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('valuesIn', require('../valuesIn'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/where.js b/app/node_modules/lodash/fp/where.js new file mode 100644 index 0000000..3247f64 --- /dev/null +++ b/app/node_modules/lodash/fp/where.js @@ -0,0 +1 @@ +module.exports = require('./conformsTo'); diff --git a/app/node_modules/lodash/fp/whereEq.js b/app/node_modules/lodash/fp/whereEq.js new file mode 100644 index 0000000..29d1e1e --- /dev/null +++ b/app/node_modules/lodash/fp/whereEq.js @@ -0,0 +1 @@ +module.exports = require('./isMatch'); diff --git a/app/node_modules/lodash/fp/without.js b/app/node_modules/lodash/fp/without.js new file mode 100644 index 0000000..bad9e12 --- /dev/null +++ b/app/node_modules/lodash/fp/without.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('without', require('../without')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/words.js b/app/node_modules/lodash/fp/words.js new file mode 100644 index 0000000..4a90141 --- /dev/null +++ b/app/node_modules/lodash/fp/words.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('words', require('../words')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/wrap.js b/app/node_modules/lodash/fp/wrap.js new file mode 100644 index 0000000..e93bd8a --- /dev/null +++ b/app/node_modules/lodash/fp/wrap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrap', require('../wrap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/wrapperAt.js b/app/node_modules/lodash/fp/wrapperAt.js new file mode 100644 index 0000000..8f0a310 --- /dev/null +++ b/app/node_modules/lodash/fp/wrapperAt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperAt', require('../wrapperAt'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/wrapperChain.js b/app/node_modules/lodash/fp/wrapperChain.js new file mode 100644 index 0000000..2a48ea2 --- /dev/null +++ b/app/node_modules/lodash/fp/wrapperChain.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperChain', require('../wrapperChain'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/wrapperLodash.js b/app/node_modules/lodash/fp/wrapperLodash.js new file mode 100644 index 0000000..a7162d0 --- /dev/null +++ b/app/node_modules/lodash/fp/wrapperLodash.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperLodash', require('../wrapperLodash'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/wrapperReverse.js b/app/node_modules/lodash/fp/wrapperReverse.js new file mode 100644 index 0000000..e1481aa --- /dev/null +++ b/app/node_modules/lodash/fp/wrapperReverse.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperReverse', require('../wrapperReverse'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/wrapperValue.js b/app/node_modules/lodash/fp/wrapperValue.js new file mode 100644 index 0000000..8eb9112 --- /dev/null +++ b/app/node_modules/lodash/fp/wrapperValue.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperValue', require('../wrapperValue'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/xor.js b/app/node_modules/lodash/fp/xor.js new file mode 100644 index 0000000..29e2819 --- /dev/null +++ b/app/node_modules/lodash/fp/xor.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('xor', require('../xor')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/xorBy.js b/app/node_modules/lodash/fp/xorBy.js new file mode 100644 index 0000000..b355686 --- /dev/null +++ b/app/node_modules/lodash/fp/xorBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('xorBy', require('../xorBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/xorWith.js b/app/node_modules/lodash/fp/xorWith.js new file mode 100644 index 0000000..8e05739 --- /dev/null +++ b/app/node_modules/lodash/fp/xorWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('xorWith', require('../xorWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/zip.js b/app/node_modules/lodash/fp/zip.js new file mode 100644 index 0000000..69e147a --- /dev/null +++ b/app/node_modules/lodash/fp/zip.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zip', require('../zip')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/zipAll.js b/app/node_modules/lodash/fp/zipAll.js new file mode 100644 index 0000000..efa8ccb --- /dev/null +++ b/app/node_modules/lodash/fp/zipAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zipAll', require('../zip')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/zipObj.js b/app/node_modules/lodash/fp/zipObj.js new file mode 100644 index 0000000..f4a3453 --- /dev/null +++ b/app/node_modules/lodash/fp/zipObj.js @@ -0,0 +1 @@ +module.exports = require('./zipObject'); diff --git a/app/node_modules/lodash/fp/zipObject.js b/app/node_modules/lodash/fp/zipObject.js new file mode 100644 index 0000000..462dbb6 --- /dev/null +++ b/app/node_modules/lodash/fp/zipObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zipObject', require('../zipObject')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/zipObjectDeep.js b/app/node_modules/lodash/fp/zipObjectDeep.js new file mode 100644 index 0000000..53a5d33 --- /dev/null +++ b/app/node_modules/lodash/fp/zipObjectDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zipObjectDeep', require('../zipObjectDeep')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fp/zipWith.js b/app/node_modules/lodash/fp/zipWith.js new file mode 100644 index 0000000..c5cf9e2 --- /dev/null +++ b/app/node_modules/lodash/fp/zipWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zipWith', require('../zipWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/app/node_modules/lodash/fromPairs.js b/app/node_modules/lodash/fromPairs.js new file mode 100644 index 0000000..ee7940d --- /dev/null +++ b/app/node_modules/lodash/fromPairs.js @@ -0,0 +1,28 @@ +/** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ +function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; +} + +module.exports = fromPairs; diff --git a/app/node_modules/lodash/function.js b/app/node_modules/lodash/function.js new file mode 100644 index 0000000..b0fc6d9 --- /dev/null +++ b/app/node_modules/lodash/function.js @@ -0,0 +1,25 @@ +module.exports = { + 'after': require('./after'), + 'ary': require('./ary'), + 'before': require('./before'), + 'bind': require('./bind'), + 'bindKey': require('./bindKey'), + 'curry': require('./curry'), + 'curryRight': require('./curryRight'), + 'debounce': require('./debounce'), + 'defer': require('./defer'), + 'delay': require('./delay'), + 'flip': require('./flip'), + 'memoize': require('./memoize'), + 'negate': require('./negate'), + 'once': require('./once'), + 'overArgs': require('./overArgs'), + 'partial': require('./partial'), + 'partialRight': require('./partialRight'), + 'rearg': require('./rearg'), + 'rest': require('./rest'), + 'spread': require('./spread'), + 'throttle': require('./throttle'), + 'unary': require('./unary'), + 'wrap': require('./wrap') +}; diff --git a/app/node_modules/lodash/functions.js b/app/node_modules/lodash/functions.js new file mode 100644 index 0000000..9722928 --- /dev/null +++ b/app/node_modules/lodash/functions.js @@ -0,0 +1,31 @@ +var baseFunctions = require('./_baseFunctions'), + keys = require('./keys'); + +/** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ +function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); +} + +module.exports = functions; diff --git a/app/node_modules/lodash/functionsIn.js b/app/node_modules/lodash/functionsIn.js new file mode 100644 index 0000000..f00345d --- /dev/null +++ b/app/node_modules/lodash/functionsIn.js @@ -0,0 +1,31 @@ +var baseFunctions = require('./_baseFunctions'), + keysIn = require('./keysIn'); + +/** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ +function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); +} + +module.exports = functionsIn; diff --git a/app/node_modules/lodash/get.js b/app/node_modules/lodash/get.js new file mode 100644 index 0000000..8805ff9 --- /dev/null +++ b/app/node_modules/lodash/get.js @@ -0,0 +1,33 @@ +var baseGet = require('./_baseGet'); + +/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ +function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; +} + +module.exports = get; diff --git a/app/node_modules/lodash/groupBy.js b/app/node_modules/lodash/groupBy.js new file mode 100644 index 0000000..babf4f6 --- /dev/null +++ b/app/node_modules/lodash/groupBy.js @@ -0,0 +1,41 @@ +var baseAssignValue = require('./_baseAssignValue'), + createAggregator = require('./_createAggregator'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ +var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } +}); + +module.exports = groupBy; diff --git a/app/node_modules/lodash/gt.js b/app/node_modules/lodash/gt.js new file mode 100644 index 0000000..3a66282 --- /dev/null +++ b/app/node_modules/lodash/gt.js @@ -0,0 +1,29 @@ +var baseGt = require('./_baseGt'), + createRelationalOperation = require('./_createRelationalOperation'); + +/** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ +var gt = createRelationalOperation(baseGt); + +module.exports = gt; diff --git a/app/node_modules/lodash/gte.js b/app/node_modules/lodash/gte.js new file mode 100644 index 0000000..4180a68 --- /dev/null +++ b/app/node_modules/lodash/gte.js @@ -0,0 +1,30 @@ +var createRelationalOperation = require('./_createRelationalOperation'); + +/** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ +var gte = createRelationalOperation(function(value, other) { + return value >= other; +}); + +module.exports = gte; diff --git a/app/node_modules/lodash/has.js b/app/node_modules/lodash/has.js new file mode 100644 index 0000000..34df55e --- /dev/null +++ b/app/node_modules/lodash/has.js @@ -0,0 +1,35 @@ +var baseHas = require('./_baseHas'), + hasPath = require('./_hasPath'); + +/** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ +function has(object, path) { + return object != null && hasPath(object, path, baseHas); +} + +module.exports = has; diff --git a/app/node_modules/lodash/hasIn.js b/app/node_modules/lodash/hasIn.js new file mode 100644 index 0000000..06a3686 --- /dev/null +++ b/app/node_modules/lodash/hasIn.js @@ -0,0 +1,34 @@ +var baseHasIn = require('./_baseHasIn'), + hasPath = require('./_hasPath'); + +/** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ +function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); +} + +module.exports = hasIn; diff --git a/app/node_modules/lodash/head.js b/app/node_modules/lodash/head.js new file mode 100644 index 0000000..dee9d1f --- /dev/null +++ b/app/node_modules/lodash/head.js @@ -0,0 +1,23 @@ +/** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ +function head(array) { + return (array && array.length) ? array[0] : undefined; +} + +module.exports = head; diff --git a/app/node_modules/lodash/identity.js b/app/node_modules/lodash/identity.js new file mode 100644 index 0000000..2d5d963 --- /dev/null +++ b/app/node_modules/lodash/identity.js @@ -0,0 +1,21 @@ +/** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ +function identity(value) { + return value; +} + +module.exports = identity; diff --git a/app/node_modules/lodash/inRange.js b/app/node_modules/lodash/inRange.js new file mode 100644 index 0000000..f20728d --- /dev/null +++ b/app/node_modules/lodash/inRange.js @@ -0,0 +1,55 @@ +var baseInRange = require('./_baseInRange'), + toFinite = require('./toFinite'), + toNumber = require('./toNumber'); + +/** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ +function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); +} + +module.exports = inRange; diff --git a/app/node_modules/lodash/includes.js b/app/node_modules/lodash/includes.js new file mode 100644 index 0000000..ae0deed --- /dev/null +++ b/app/node_modules/lodash/includes.js @@ -0,0 +1,53 @@ +var baseIndexOf = require('./_baseIndexOf'), + isArrayLike = require('./isArrayLike'), + isString = require('./isString'), + toInteger = require('./toInteger'), + values = require('./values'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ +function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); +} + +module.exports = includes; diff --git a/app/node_modules/lodash/index.js b/app/node_modules/lodash/index.js new file mode 100644 index 0000000..5d063e2 --- /dev/null +++ b/app/node_modules/lodash/index.js @@ -0,0 +1 @@ +module.exports = require('./lodash'); \ No newline at end of file diff --git a/app/node_modules/lodash/indexOf.js b/app/node_modules/lodash/indexOf.js new file mode 100644 index 0000000..3c644af --- /dev/null +++ b/app/node_modules/lodash/indexOf.js @@ -0,0 +1,42 @@ +var baseIndexOf = require('./_baseIndexOf'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ +function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); +} + +module.exports = indexOf; diff --git a/app/node_modules/lodash/initial.js b/app/node_modules/lodash/initial.js new file mode 100644 index 0000000..f47fc50 --- /dev/null +++ b/app/node_modules/lodash/initial.js @@ -0,0 +1,22 @@ +var baseSlice = require('./_baseSlice'); + +/** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ +function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; +} + +module.exports = initial; diff --git a/app/node_modules/lodash/intersection.js b/app/node_modules/lodash/intersection.js new file mode 100644 index 0000000..a94c135 --- /dev/null +++ b/app/node_modules/lodash/intersection.js @@ -0,0 +1,30 @@ +var arrayMap = require('./_arrayMap'), + baseIntersection = require('./_baseIntersection'), + baseRest = require('./_baseRest'), + castArrayLikeObject = require('./_castArrayLikeObject'); + +/** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ +var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; +}); + +module.exports = intersection; diff --git a/app/node_modules/lodash/intersectionBy.js b/app/node_modules/lodash/intersectionBy.js new file mode 100644 index 0000000..31461aa --- /dev/null +++ b/app/node_modules/lodash/intersectionBy.js @@ -0,0 +1,45 @@ +var arrayMap = require('./_arrayMap'), + baseIntersection = require('./_baseIntersection'), + baseIteratee = require('./_baseIteratee'), + baseRest = require('./_baseRest'), + castArrayLikeObject = require('./_castArrayLikeObject'), + last = require('./last'); + +/** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ +var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, baseIteratee(iteratee, 2)) + : []; +}); + +module.exports = intersectionBy; diff --git a/app/node_modules/lodash/intersectionWith.js b/app/node_modules/lodash/intersectionWith.js new file mode 100644 index 0000000..63cabfa --- /dev/null +++ b/app/node_modules/lodash/intersectionWith.js @@ -0,0 +1,41 @@ +var arrayMap = require('./_arrayMap'), + baseIntersection = require('./_baseIntersection'), + baseRest = require('./_baseRest'), + castArrayLikeObject = require('./_castArrayLikeObject'), + last = require('./last'); + +/** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ +var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; +}); + +module.exports = intersectionWith; diff --git a/app/node_modules/lodash/invert.js b/app/node_modules/lodash/invert.js new file mode 100644 index 0000000..8c47950 --- /dev/null +++ b/app/node_modules/lodash/invert.js @@ -0,0 +1,42 @@ +var constant = require('./constant'), + createInverter = require('./_createInverter'), + identity = require('./identity'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ +var invert = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + result[value] = key; +}, constant(identity)); + +module.exports = invert; diff --git a/app/node_modules/lodash/invertBy.js b/app/node_modules/lodash/invertBy.js new file mode 100644 index 0000000..3f4f7e5 --- /dev/null +++ b/app/node_modules/lodash/invertBy.js @@ -0,0 +1,56 @@ +var baseIteratee = require('./_baseIteratee'), + createInverter = require('./_createInverter'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ +var invertBy = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } +}, baseIteratee); + +module.exports = invertBy; diff --git a/app/node_modules/lodash/invoke.js b/app/node_modules/lodash/invoke.js new file mode 100644 index 0000000..97d51eb --- /dev/null +++ b/app/node_modules/lodash/invoke.js @@ -0,0 +1,24 @@ +var baseInvoke = require('./_baseInvoke'), + baseRest = require('./_baseRest'); + +/** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ +var invoke = baseRest(baseInvoke); + +module.exports = invoke; diff --git a/app/node_modules/lodash/invokeMap.js b/app/node_modules/lodash/invokeMap.js new file mode 100644 index 0000000..8da5126 --- /dev/null +++ b/app/node_modules/lodash/invokeMap.js @@ -0,0 +1,41 @@ +var apply = require('./_apply'), + baseEach = require('./_baseEach'), + baseInvoke = require('./_baseInvoke'), + baseRest = require('./_baseRest'), + isArrayLike = require('./isArrayLike'); + +/** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ +var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; +}); + +module.exports = invokeMap; diff --git a/app/node_modules/lodash/isArguments.js b/app/node_modules/lodash/isArguments.js new file mode 100644 index 0000000..8b9ed66 --- /dev/null +++ b/app/node_modules/lodash/isArguments.js @@ -0,0 +1,36 @@ +var baseIsArguments = require('./_baseIsArguments'), + isObjectLike = require('./isObjectLike'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); +}; + +module.exports = isArguments; diff --git a/app/node_modules/lodash/isArray.js b/app/node_modules/lodash/isArray.js new file mode 100644 index 0000000..88ab55f --- /dev/null +++ b/app/node_modules/lodash/isArray.js @@ -0,0 +1,26 @@ +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +module.exports = isArray; diff --git a/app/node_modules/lodash/isArrayBuffer.js b/app/node_modules/lodash/isArrayBuffer.js new file mode 100644 index 0000000..12904a6 --- /dev/null +++ b/app/node_modules/lodash/isArrayBuffer.js @@ -0,0 +1,27 @@ +var baseIsArrayBuffer = require('./_baseIsArrayBuffer'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer; + +/** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ +var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + +module.exports = isArrayBuffer; diff --git a/app/node_modules/lodash/isArrayLike.js b/app/node_modules/lodash/isArrayLike.js new file mode 100644 index 0000000..0f96680 --- /dev/null +++ b/app/node_modules/lodash/isArrayLike.js @@ -0,0 +1,33 @@ +var isFunction = require('./isFunction'), + isLength = require('./isLength'); + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +module.exports = isArrayLike; diff --git a/app/node_modules/lodash/isArrayLikeObject.js b/app/node_modules/lodash/isArrayLikeObject.js new file mode 100644 index 0000000..6c4812a --- /dev/null +++ b/app/node_modules/lodash/isArrayLikeObject.js @@ -0,0 +1,33 @@ +var isArrayLike = require('./isArrayLike'), + isObjectLike = require('./isObjectLike'); + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +module.exports = isArrayLikeObject; diff --git a/app/node_modules/lodash/isBoolean.js b/app/node_modules/lodash/isBoolean.js new file mode 100644 index 0000000..a43ed4b --- /dev/null +++ b/app/node_modules/lodash/isBoolean.js @@ -0,0 +1,29 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]'; + +/** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ +function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); +} + +module.exports = isBoolean; diff --git a/app/node_modules/lodash/isBuffer.js b/app/node_modules/lodash/isBuffer.js new file mode 100644 index 0000000..c103cc7 --- /dev/null +++ b/app/node_modules/lodash/isBuffer.js @@ -0,0 +1,38 @@ +var root = require('./_root'), + stubFalse = require('./stubFalse'); + +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; + +module.exports = isBuffer; diff --git a/app/node_modules/lodash/isDate.js b/app/node_modules/lodash/isDate.js new file mode 100644 index 0000000..7f0209f --- /dev/null +++ b/app/node_modules/lodash/isDate.js @@ -0,0 +1,27 @@ +var baseIsDate = require('./_baseIsDate'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsDate = nodeUtil && nodeUtil.isDate; + +/** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ +var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + +module.exports = isDate; diff --git a/app/node_modules/lodash/isElement.js b/app/node_modules/lodash/isElement.js new file mode 100644 index 0000000..76ae29c --- /dev/null +++ b/app/node_modules/lodash/isElement.js @@ -0,0 +1,25 @@ +var isObjectLike = require('./isObjectLike'), + isPlainObject = require('./isPlainObject'); + +/** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ +function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); +} + +module.exports = isElement; diff --git a/app/node_modules/lodash/isEmpty.js b/app/node_modules/lodash/isEmpty.js new file mode 100644 index 0000000..3597294 --- /dev/null +++ b/app/node_modules/lodash/isEmpty.js @@ -0,0 +1,77 @@ +var baseKeys = require('./_baseKeys'), + getTag = require('./_getTag'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isArrayLike = require('./isArrayLike'), + isBuffer = require('./isBuffer'), + isPrototype = require('./_isPrototype'), + isTypedArray = require('./isTypedArray'); + +/** `Object#toString` result references. */ +var mapTag = '[object Map]', + setTag = '[object Set]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ +function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; +} + +module.exports = isEmpty; diff --git a/app/node_modules/lodash/isEqual.js b/app/node_modules/lodash/isEqual.js new file mode 100644 index 0000000..5e23e76 --- /dev/null +++ b/app/node_modules/lodash/isEqual.js @@ -0,0 +1,35 @@ +var baseIsEqual = require('./_baseIsEqual'); + +/** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ +function isEqual(value, other) { + return baseIsEqual(value, other); +} + +module.exports = isEqual; diff --git a/app/node_modules/lodash/isEqualWith.js b/app/node_modules/lodash/isEqualWith.js new file mode 100644 index 0000000..21bdc7f --- /dev/null +++ b/app/node_modules/lodash/isEqualWith.js @@ -0,0 +1,41 @@ +var baseIsEqual = require('./_baseIsEqual'); + +/** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ +function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; +} + +module.exports = isEqualWith; diff --git a/app/node_modules/lodash/isError.js b/app/node_modules/lodash/isError.js new file mode 100644 index 0000000..b4f41e0 --- /dev/null +++ b/app/node_modules/lodash/isError.js @@ -0,0 +1,36 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'), + isPlainObject = require('./isPlainObject'); + +/** `Object#toString` result references. */ +var domExcTag = '[object DOMException]', + errorTag = '[object Error]'; + +/** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ +function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); +} + +module.exports = isError; diff --git a/app/node_modules/lodash/isFinite.js b/app/node_modules/lodash/isFinite.js new file mode 100644 index 0000000..601842b --- /dev/null +++ b/app/node_modules/lodash/isFinite.js @@ -0,0 +1,36 @@ +var root = require('./_root'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = root.isFinite; + +/** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ +function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); +} + +module.exports = isFinite; diff --git a/app/node_modules/lodash/isFunction.js b/app/node_modules/lodash/isFunction.js new file mode 100644 index 0000000..907a8cd --- /dev/null +++ b/app/node_modules/lodash/isFunction.js @@ -0,0 +1,37 @@ +var baseGetTag = require('./_baseGetTag'), + isObject = require('./isObject'); + +/** `Object#toString` result references. */ +var asyncTag = '[object AsyncFunction]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} + +module.exports = isFunction; diff --git a/app/node_modules/lodash/isInteger.js b/app/node_modules/lodash/isInteger.js new file mode 100644 index 0000000..66aa87d --- /dev/null +++ b/app/node_modules/lodash/isInteger.js @@ -0,0 +1,33 @@ +var toInteger = require('./toInteger'); + +/** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ +function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); +} + +module.exports = isInteger; diff --git a/app/node_modules/lodash/isLength.js b/app/node_modules/lodash/isLength.js new file mode 100644 index 0000000..3a95caa --- /dev/null +++ b/app/node_modules/lodash/isLength.js @@ -0,0 +1,35 @@ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +module.exports = isLength; diff --git a/app/node_modules/lodash/isMap.js b/app/node_modules/lodash/isMap.js new file mode 100644 index 0000000..44f8517 --- /dev/null +++ b/app/node_modules/lodash/isMap.js @@ -0,0 +1,27 @@ +var baseIsMap = require('./_baseIsMap'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsMap = nodeUtil && nodeUtil.isMap; + +/** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ +var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + +module.exports = isMap; diff --git a/app/node_modules/lodash/isMatch.js b/app/node_modules/lodash/isMatch.js new file mode 100644 index 0000000..9773a18 --- /dev/null +++ b/app/node_modules/lodash/isMatch.js @@ -0,0 +1,36 @@ +var baseIsMatch = require('./_baseIsMatch'), + getMatchData = require('./_getMatchData'); + +/** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ +function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); +} + +module.exports = isMatch; diff --git a/app/node_modules/lodash/isMatchWith.js b/app/node_modules/lodash/isMatchWith.js new file mode 100644 index 0000000..187b6a6 --- /dev/null +++ b/app/node_modules/lodash/isMatchWith.js @@ -0,0 +1,41 @@ +var baseIsMatch = require('./_baseIsMatch'), + getMatchData = require('./_getMatchData'); + +/** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ +function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); +} + +module.exports = isMatchWith; diff --git a/app/node_modules/lodash/isNaN.js b/app/node_modules/lodash/isNaN.js new file mode 100644 index 0000000..7d0d783 --- /dev/null +++ b/app/node_modules/lodash/isNaN.js @@ -0,0 +1,38 @@ +var isNumber = require('./isNumber'); + +/** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ +function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; +} + +module.exports = isNaN; diff --git a/app/node_modules/lodash/isNative.js b/app/node_modules/lodash/isNative.js new file mode 100644 index 0000000..f0cb8d5 --- /dev/null +++ b/app/node_modules/lodash/isNative.js @@ -0,0 +1,40 @@ +var baseIsNative = require('./_baseIsNative'), + isMaskable = require('./_isMaskable'); + +/** Error message constants. */ +var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.'; + +/** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ +function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); +} + +module.exports = isNative; diff --git a/app/node_modules/lodash/isNil.js b/app/node_modules/lodash/isNil.js new file mode 100644 index 0000000..79f0505 --- /dev/null +++ b/app/node_modules/lodash/isNil.js @@ -0,0 +1,25 @@ +/** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ +function isNil(value) { + return value == null; +} + +module.exports = isNil; diff --git a/app/node_modules/lodash/isNull.js b/app/node_modules/lodash/isNull.js new file mode 100644 index 0000000..c0a374d --- /dev/null +++ b/app/node_modules/lodash/isNull.js @@ -0,0 +1,22 @@ +/** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ +function isNull(value) { + return value === null; +} + +module.exports = isNull; diff --git a/app/node_modules/lodash/isNumber.js b/app/node_modules/lodash/isNumber.js new file mode 100644 index 0000000..cd34ee4 --- /dev/null +++ b/app/node_modules/lodash/isNumber.js @@ -0,0 +1,38 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var numberTag = '[object Number]'; + +/** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ +function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); +} + +module.exports = isNumber; diff --git a/app/node_modules/lodash/isObject.js b/app/node_modules/lodash/isObject.js new file mode 100644 index 0000000..1dc8939 --- /dev/null +++ b/app/node_modules/lodash/isObject.js @@ -0,0 +1,31 @@ +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +module.exports = isObject; diff --git a/app/node_modules/lodash/isObjectLike.js b/app/node_modules/lodash/isObjectLike.js new file mode 100644 index 0000000..301716b --- /dev/null +++ b/app/node_modules/lodash/isObjectLike.js @@ -0,0 +1,29 @@ +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +module.exports = isObjectLike; diff --git a/app/node_modules/lodash/isPlainObject.js b/app/node_modules/lodash/isPlainObject.js new file mode 100644 index 0000000..2387373 --- /dev/null +++ b/app/node_modules/lodash/isPlainObject.js @@ -0,0 +1,62 @@ +var baseGetTag = require('./_baseGetTag'), + getPrototype = require('./_getPrototype'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var objectTag = '[object Object]'; + +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; +} + +module.exports = isPlainObject; diff --git a/app/node_modules/lodash/isRegExp.js b/app/node_modules/lodash/isRegExp.js new file mode 100644 index 0000000..76c9b6e --- /dev/null +++ b/app/node_modules/lodash/isRegExp.js @@ -0,0 +1,27 @@ +var baseIsRegExp = require('./_baseIsRegExp'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp; + +/** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ +var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + +module.exports = isRegExp; diff --git a/app/node_modules/lodash/isSafeInteger.js b/app/node_modules/lodash/isSafeInteger.js new file mode 100644 index 0000000..2a48526 --- /dev/null +++ b/app/node_modules/lodash/isSafeInteger.js @@ -0,0 +1,37 @@ +var isInteger = require('./isInteger'); + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ +function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; +} + +module.exports = isSafeInteger; diff --git a/app/node_modules/lodash/isSet.js b/app/node_modules/lodash/isSet.js new file mode 100644 index 0000000..ab88bdf --- /dev/null +++ b/app/node_modules/lodash/isSet.js @@ -0,0 +1,27 @@ +var baseIsSet = require('./_baseIsSet'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsSet = nodeUtil && nodeUtil.isSet; + +/** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ +var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + +module.exports = isSet; diff --git a/app/node_modules/lodash/isString.js b/app/node_modules/lodash/isString.js new file mode 100644 index 0000000..627eb9c --- /dev/null +++ b/app/node_modules/lodash/isString.js @@ -0,0 +1,30 @@ +var baseGetTag = require('./_baseGetTag'), + isArray = require('./isArray'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var stringTag = '[object String]'; + +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); +} + +module.exports = isString; diff --git a/app/node_modules/lodash/isSymbol.js b/app/node_modules/lodash/isSymbol.js new file mode 100644 index 0000000..dfb60b9 --- /dev/null +++ b/app/node_modules/lodash/isSymbol.js @@ -0,0 +1,29 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); +} + +module.exports = isSymbol; diff --git a/app/node_modules/lodash/isTypedArray.js b/app/node_modules/lodash/isTypedArray.js new file mode 100644 index 0000000..da3f8dd --- /dev/null +++ b/app/node_modules/lodash/isTypedArray.js @@ -0,0 +1,27 @@ +var baseIsTypedArray = require('./_baseIsTypedArray'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + +module.exports = isTypedArray; diff --git a/app/node_modules/lodash/isUndefined.js b/app/node_modules/lodash/isUndefined.js new file mode 100644 index 0000000..377d121 --- /dev/null +++ b/app/node_modules/lodash/isUndefined.js @@ -0,0 +1,22 @@ +/** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ +function isUndefined(value) { + return value === undefined; +} + +module.exports = isUndefined; diff --git a/app/node_modules/lodash/isWeakMap.js b/app/node_modules/lodash/isWeakMap.js new file mode 100644 index 0000000..8d36f66 --- /dev/null +++ b/app/node_modules/lodash/isWeakMap.js @@ -0,0 +1,28 @@ +var getTag = require('./_getTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var weakMapTag = '[object WeakMap]'; + +/** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ +function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; +} + +module.exports = isWeakMap; diff --git a/app/node_modules/lodash/isWeakSet.js b/app/node_modules/lodash/isWeakSet.js new file mode 100644 index 0000000..e628b26 --- /dev/null +++ b/app/node_modules/lodash/isWeakSet.js @@ -0,0 +1,28 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var weakSetTag = '[object WeakSet]'; + +/** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ +function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; +} + +module.exports = isWeakSet; diff --git a/app/node_modules/lodash/iteratee.js b/app/node_modules/lodash/iteratee.js new file mode 100644 index 0000000..61b73a8 --- /dev/null +++ b/app/node_modules/lodash/iteratee.js @@ -0,0 +1,53 @@ +var baseClone = require('./_baseClone'), + baseIteratee = require('./_baseIteratee'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1; + +/** + * Creates a function that invokes `func` with the arguments of the created + * function. If `func` is a property name, the created function returns the + * property value for a given element. If `func` is an array or object, the + * created function returns `true` for elements that contain the equivalent + * source properties, otherwise it returns `false`. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Util + * @param {*} [func=_.identity] The value to convert to a callback. + * @returns {Function} Returns the callback. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); + * // => [{ 'user': 'barney', 'age': 36, 'active': true }] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, _.iteratee(['user', 'fred'])); + * // => [{ 'user': 'fred', 'age': 40 }] + * + * // The `_.property` iteratee shorthand. + * _.map(users, _.iteratee('user')); + * // => ['barney', 'fred'] + * + * // Create custom iteratee shorthands. + * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { + * return !_.isRegExp(func) ? iteratee(func) : function(string) { + * return func.test(string); + * }; + * }); + * + * _.filter(['abc', 'def'], /ef/); + * // => ['def'] + */ +function iteratee(func) { + return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); +} + +module.exports = iteratee; diff --git a/app/node_modules/lodash/join.js b/app/node_modules/lodash/join.js new file mode 100644 index 0000000..45de079 --- /dev/null +++ b/app/node_modules/lodash/join.js @@ -0,0 +1,26 @@ +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeJoin = arrayProto.join; + +/** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ +function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); +} + +module.exports = join; diff --git a/app/node_modules/lodash/kebabCase.js b/app/node_modules/lodash/kebabCase.js new file mode 100644 index 0000000..8a52be6 --- /dev/null +++ b/app/node_modules/lodash/kebabCase.js @@ -0,0 +1,28 @@ +var createCompounder = require('./_createCompounder'); + +/** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ +var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); +}); + +module.exports = kebabCase; diff --git a/app/node_modules/lodash/keyBy.js b/app/node_modules/lodash/keyBy.js new file mode 100644 index 0000000..acc007a --- /dev/null +++ b/app/node_modules/lodash/keyBy.js @@ -0,0 +1,36 @@ +var baseAssignValue = require('./_baseAssignValue'), + createAggregator = require('./_createAggregator'); + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ +var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); +}); + +module.exports = keyBy; diff --git a/app/node_modules/lodash/keys.js b/app/node_modules/lodash/keys.js new file mode 100644 index 0000000..d143c71 --- /dev/null +++ b/app/node_modules/lodash/keys.js @@ -0,0 +1,37 @@ +var arrayLikeKeys = require('./_arrayLikeKeys'), + baseKeys = require('./_baseKeys'), + isArrayLike = require('./isArrayLike'); + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +module.exports = keys; diff --git a/app/node_modules/lodash/keysIn.js b/app/node_modules/lodash/keysIn.js new file mode 100644 index 0000000..a62308f --- /dev/null +++ b/app/node_modules/lodash/keysIn.js @@ -0,0 +1,32 @@ +var arrayLikeKeys = require('./_arrayLikeKeys'), + baseKeysIn = require('./_baseKeysIn'), + isArrayLike = require('./isArrayLike'); + +/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ +function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); +} + +module.exports = keysIn; diff --git a/app/node_modules/lodash/lang.js b/app/node_modules/lodash/lang.js new file mode 100644 index 0000000..a396216 --- /dev/null +++ b/app/node_modules/lodash/lang.js @@ -0,0 +1,58 @@ +module.exports = { + 'castArray': require('./castArray'), + 'clone': require('./clone'), + 'cloneDeep': require('./cloneDeep'), + 'cloneDeepWith': require('./cloneDeepWith'), + 'cloneWith': require('./cloneWith'), + 'conformsTo': require('./conformsTo'), + 'eq': require('./eq'), + 'gt': require('./gt'), + 'gte': require('./gte'), + 'isArguments': require('./isArguments'), + 'isArray': require('./isArray'), + 'isArrayBuffer': require('./isArrayBuffer'), + 'isArrayLike': require('./isArrayLike'), + 'isArrayLikeObject': require('./isArrayLikeObject'), + 'isBoolean': require('./isBoolean'), + 'isBuffer': require('./isBuffer'), + 'isDate': require('./isDate'), + 'isElement': require('./isElement'), + 'isEmpty': require('./isEmpty'), + 'isEqual': require('./isEqual'), + 'isEqualWith': require('./isEqualWith'), + 'isError': require('./isError'), + 'isFinite': require('./isFinite'), + 'isFunction': require('./isFunction'), + 'isInteger': require('./isInteger'), + 'isLength': require('./isLength'), + 'isMap': require('./isMap'), + 'isMatch': require('./isMatch'), + 'isMatchWith': require('./isMatchWith'), + 'isNaN': require('./isNaN'), + 'isNative': require('./isNative'), + 'isNil': require('./isNil'), + 'isNull': require('./isNull'), + 'isNumber': require('./isNumber'), + 'isObject': require('./isObject'), + 'isObjectLike': require('./isObjectLike'), + 'isPlainObject': require('./isPlainObject'), + 'isRegExp': require('./isRegExp'), + 'isSafeInteger': require('./isSafeInteger'), + 'isSet': require('./isSet'), + 'isString': require('./isString'), + 'isSymbol': require('./isSymbol'), + 'isTypedArray': require('./isTypedArray'), + 'isUndefined': require('./isUndefined'), + 'isWeakMap': require('./isWeakMap'), + 'isWeakSet': require('./isWeakSet'), + 'lt': require('./lt'), + 'lte': require('./lte'), + 'toArray': require('./toArray'), + 'toFinite': require('./toFinite'), + 'toInteger': require('./toInteger'), + 'toLength': require('./toLength'), + 'toNumber': require('./toNumber'), + 'toPlainObject': require('./toPlainObject'), + 'toSafeInteger': require('./toSafeInteger'), + 'toString': require('./toString') +}; diff --git a/app/node_modules/lodash/last.js b/app/node_modules/lodash/last.js new file mode 100644 index 0000000..cad1eaf --- /dev/null +++ b/app/node_modules/lodash/last.js @@ -0,0 +1,20 @@ +/** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ +function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; +} + +module.exports = last; diff --git a/app/node_modules/lodash/lastIndexOf.js b/app/node_modules/lodash/lastIndexOf.js new file mode 100644 index 0000000..dabfb61 --- /dev/null +++ b/app/node_modules/lodash/lastIndexOf.js @@ -0,0 +1,46 @@ +var baseFindIndex = require('./_baseFindIndex'), + baseIsNaN = require('./_baseIsNaN'), + strictLastIndexOf = require('./_strictLastIndexOf'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ +function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); +} + +module.exports = lastIndexOf; diff --git a/app/node_modules/lodash/lodash.js b/app/node_modules/lodash/lodash.js new file mode 100644 index 0000000..9b95dfe --- /dev/null +++ b/app/node_modules/lodash/lodash.js @@ -0,0 +1,17112 @@ +/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.17.15'; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', + FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** Used to compose bitmasks for function metadata. */ + var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256, + WRAP_FLIP_FLAG = 512; + + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] + ]; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + domExcTag = '[object DOMException]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + + /** Used to match leading and trailing whitespace. */ + var reTrim = /^\s+|\s+$/g, + reTrimStart = /^\s+/, + reTrimEnd = /\s+$/; + + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + + /** Used to compose unicode capture groups. */ + var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + + /** Used to compose unicode regexes. */ + var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); + + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); + + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + + /** Used to match complex or compound words. */ + var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join('|'), 'g'); + + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + + /** Used to detect strings that need a more robust regexp to match words. */ + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; + + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /*--------------------------------------------------------------------------*/ + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; + } + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } + + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; + } + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); + + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } + + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } + + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } + + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); + } + } + return result; + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + + /** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + var deburrLetter = basePropertyOf(deburredLetters); + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } + + /** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } + + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; + } + + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; + } + + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); + + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, + symIterator = Symbol ? Symbol.iterator : undefined, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */ + function baseLodash() { + // No operation performed. + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; + } + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. + * + * @static + * @memberOf _ + * @type {Object} + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash + } + }; + + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */ + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; + } + + /** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; + } + + /** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; + } + + /** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; + } + + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `_.sample` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; + } + + /** + * A specialized version of `_.sampleSize` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); + } + + /** + * A specialized version of `_.shuffle` for arrays. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } + + /** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * The base implementation of `_.at` without support for individual paths. + * + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. + */ + function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; + } + + /** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; + } + + /** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + } + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; + } + + /** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + + /** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */ + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; + } + + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEachRight = createBaseEach(baseForOwnRight, true); + + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; + } + + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseForRight = createBaseFor(true); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } + + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + + /** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + + /** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. + */ + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; + } + + /** + * The base implementation of `_.invoke` without support for individual + * method arguments. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ + function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + */ + function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; + } + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; + } + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; + } + + /** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.nth` which doesn't coerce arguments. + * + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. + */ + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; + } + + /** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ + function baseOrderBy(collection, iteratees, orders) { + var index = -1; + iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; + } + + /** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */ + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + } + + /** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ + function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; + } + + /** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ + function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; + } + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ + function baseSample(collection) { + return arraySample(values(collection)); + } + + /** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `setData` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** + * The base implementation of `_.shuffle`. + * + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); + } + + /** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndexBy(array, value, iteratee, retHighest) { + value = iteratee(value); + + var low = 0, + high = array == null ? 0 : array.length, + valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + + /** + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; + } + + /** + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. + * + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. + */ + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.unset`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + */ + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; + } + + /** + * The base implementation of `_.update`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); + } + + /** + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } + + /** + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. + */ + function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, + result = Array(length); + + while (++index < length) { + var array = arrays[index], + othIndex = -1; + + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } + } + return baseUniq(baseFlatten(result, 1), iteratee, comparator); + } + + /** + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. + */ + function baseZipObject(props, values, assignFunc) { + var index = -1, + length = props.length, + valsLength = values.length, + result = {}; + + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } + return result; + } + + /** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } + + /** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ + function castFunction(value) { + return typeof value == 'function' ? value : identity; + } + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. + * + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + var castRest = baseRest; + + /** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); + } + + /** + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + + /** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; + } + + /** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + /** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + /** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + + /** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); + } + + /** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); + } + + /** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, getIteratee(iteratee, 2), accumulator); + }; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; + } + + /** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; + } + + /** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } + + /** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, + isBind = bitmask & WRAP_BIND_FLAG, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG, + isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), + isFlip = bitmask & WRAP_FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + + /** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; + } + + /** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; + } + + /** + * Creates a function like `_.over`. + * + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. + */ + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); + } + + /** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); + } + + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a `_.range` or `_.rangeRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + + /** + * Creates a function that performs a relational operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. + */ + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } + + /** + * Creates a function that wraps `func` to continue currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); + } + + /** + * Creates a function like `_.round`. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision && nativeIsFinite(number)) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; + } + + /** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; + + /** + * Creates a `_.toPairs` or `_.toPairsIn` function. + * + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. + */ + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } + + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); + } + + /** + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; + } + + /** + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ + function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; + } + + /** + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. + * + * @private + * @param {*} value The value to inspect. + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. + */ + function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); + } + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + } + + /** + * Gets the argument placeholder value for `func`. + * + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. + */ + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; + } + + /** + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. + * + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. + */ + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + + /** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; + } + + /** + * Extracts wrapper details from the `source` body comment. + * + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. + */ + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return new Ctor; + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return new Ctor; + + case symbolTag: + return cloneSymbol(object); + } + } + + /** + * Inserts wrapper `details` in a comment at the top of the `source` body. + * + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. + */ + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); + } + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. + */ + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * Checks if `func` is capable of being masked. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ + var isMaskable = coreJsData ? isFunction : stubFalse; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + + /** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; + } + + /** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var setData = shortOut(baseSetData); + + /** + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. + */ + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */ + function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; + } + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Updates wrapper `details` based on `bitmask` flags. + * + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + + /** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; + } + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + + /** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; + }); + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } + + /** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } + + /** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return (array && array.length) ? array[0] : undefined; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; + } + + /** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); + + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ + function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); + } + + /** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. + * + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */ + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + } + + /** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */ + var pull = baseRest(pullAll); + + /** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */ + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */ + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; + } + + /** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] + */ + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + + /** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + */ + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } + + /** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */ + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + } + + /** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */ + function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 + */ + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } + + /** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 + * + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */ + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } + + /** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */ + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */ + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; + } + + /** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */ + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.tail([1, 2, 3]); + * // => [2, 3] + */ + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; + } + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */ + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */ + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; + } + + /** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + + /** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); + + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ + function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniqBy(array, iteratee) { + return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */ + function uniqWith(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + * + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */ + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + + /** + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } + + /** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example + * + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */ + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example + * + * _.xor([2, 1], [2, 3]); + * // => [1, 3] + */ + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + + /** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] + * + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); + + /** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */ + var zip = baseRest(unzip); + + /** + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. + * + * @static + * @memberOf _ + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } + */ + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); + } + + /** + * This method is like `_.zipObject` except that it supports property paths. + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + */ + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); + } + + /** + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */ + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * This method is the wrapper version of `_.at`. + * + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] + */ + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; + + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); + + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + + /** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */ + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; + } + + /** + * Enables the wrapper to be iterable. + * + * @name Symbol.iterator + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped[Symbol.iterator]() === wrapped; + * // => true + * + * Array.from(wrapped); + * // => [1, 2] + */ + function wrapperToIterator() { + return this; + } + + /** + * Creates a clone of the chain sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * This method is the wrapper version of `_.reverse`. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + 'func': thru, + 'args': [reverse], + 'thisArg': undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } + }); + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + */ + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ + var findLast = createFind(findLastIndex); + + /** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ + function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); + } + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ + function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } + }); + + /** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + } + + /** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ + var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); + }); + + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */ + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); + } + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + } + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + } + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */ + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + + /** + * Gets a random element from `collection`. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + */ + function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); + } + + /** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. + * @example + * + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] + * + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */ + function sampleSize(collection, n, guard) { + if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); + } + + /** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] + */ + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ + var now = ctxNow || function() { + return root.Date.now(); + }; + + /*------------------------------------------------------------------------*/ + + /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */ + function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ + function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); + } + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); + }); + + /** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ + var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); + }); + + /** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; + } + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; + } + + /** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ + function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + timeWaiting = wait - timeSinceLastCall; + + return maxing + ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) + : timeWaiting; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + clearTimeout(timerId); + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + + /** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ + function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + + /** + * Creates a function that invokes `func` with its arguments transformed. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] + */ + var overArgs = castRest(function(func, transforms) { + transforms = (transforms.length == 1 && isArray(transforms[0])) + ? arrayMap(transforms[0], baseUnary(getIteratee())) + : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, + length = nativeMin(args.length, funcsLength); + + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + + /** + * Creates a function that invokes `func` with `partials` prepended to the + * arguments it receives. This method is like `_.bind` except it does **not** + * alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); + }); + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); + }); + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */ + var rearg = flatRest(function(func, indexes) { + return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); + }); + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); + } + + /** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ + function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start == null ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); + + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); + } + + /** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); + } + + /** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */ + function unary(func) { + return ary(func, 1); + } + + /** + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ + function wrap(value, wrapper) { + return partial(castFunction(wrapper), value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ + function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; + } + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */ + function cloneWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ + function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ + function cloneDeepWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */ + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ + var gt = createRelationalOperation(baseGt); + + /** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ + var gte = createRelationalOperation(function(value, other) { + return value >= other; + }); + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + + /** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + } + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ + function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ + function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + + /** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + + /** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ + function isNil(value) { + return value == null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + + /** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + } + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } + + /** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ + function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; + } + + /** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */ + var lt = createRelationalOperation(baseLt); + + /** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */ + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); + + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (symIterator && value[symIterator]) { + return iteratorToArray(value[symIterator]()); + } + var tag = getTag(value), + func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); + + return func(value); + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; + } + + /** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toLength(3.2); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */ + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + } + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toSafeInteger(3.2); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 + */ + function toSafeInteger(value) { + return value + ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); + } + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + return value == null ? '' : baseToString(value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); + + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); + }); + + /** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + + /** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); + }); + + /** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */ + var at = flatRest(baseAt); + + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : baseAssign(result, properties); + } + + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(object, sources) { + object = Object(object); + + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + + if (value === undefined || + (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { + object[key] = source[key]; + } + } + } + + return object; + }); + + /** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ + var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); + }); + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + + /** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ + function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ + function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forOwn(object, iteratee) { + return object && baseForOwn(object, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ + function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + } + + /** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); + } + + /** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ + var invert = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + result[value] = key; + }, constant(identity)); + + /** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ + var invertBy = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + }, getIteratee); + + /** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ + var invoke = baseRest(baseInvoke); + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable property paths of `object` that are not omitted. + * + * **Note:** This method is considerably slower than `_.pick`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to omit. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */ + var omit = flatRest(function(object, paths) { + var result = {}; + if (object == null) { + return result; + } + var isDeep = false; + paths = arrayMap(paths, function(path) { + path = castPath(path, object); + isDeep || (isDeep = path.length > 1); + return path; + }); + copyObject(object, getAllKeysIn(object), result); + if (isDeep) { + result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); + } + var length = paths.length; + while (length--) { + baseUnset(result, paths[length]); + } + return result; + }); + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); + }); + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = getIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + path = castPath(path, object); + + var index = -1, + length = path.length; + + // Ensure the loop is entered when path is empty. + if (!length) { + length = 1; + object = undefined; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } + + /** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + + /** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */ + function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); + } + + /** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */ + var toPairs = createToPairs(keys); + + /** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */ + var toPairsIn = createToPairs(keysIn); + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function transform(object, iteratee, accumulator) { + var isArr = isArray(object), + isArrLike = isArr || isBuffer(object) || isTypedArray(object); + + iteratee = getIteratee(iteratee, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor : []; + } + else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } + else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Removes the property at `path` of `object`. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + */ + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + + /** + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 + * + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 + */ + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + + /** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */ + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object == null ? [] : baseValues(object, keys(object)); + } + + /** + * Creates an array of the own and inherited enumerable string keyed property + * values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ + function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); + } + + /** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + + /** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(lower, upper, floating) { + if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == 'boolean') { + floating = upper; + upper = undefined; + } + else if (typeof lower == 'boolean') { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } + else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); + } + return baseRandom(lower, upper); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); + }); + + /** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + + /** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; + } + + /** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */ + var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toLowerCase(); + }); + + /** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */ + var lowerFirst = createCaseFirst('toLowerCase'); + + /** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return ( + createPadding(nativeFloor(mid), chars) + + string + + createPadding(nativeCeil(mid), chars) + ); + } + + /** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */ + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (string + createPadding(length - strLength, chars)) + : string; + } + + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (createPadding(length - strLength, chars) + string) + : string; + } + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a + * hexadecimal, in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the + * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category String + * @param {string} string The string to convert. + * @param {number} [radix=10] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); + } + + /** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */ + function replace() { + var args = arguments, + string = toString(args[0]); + + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + + /** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */ + function split(string, separator, limit) { + if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && ( + typeof separator == 'string' || + (separator != null && !isRegExp(separator)) + )) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + + /** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + upperFirst(word); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = toString(string); + position = position == null + ? 0 + : baseClamp(toInteger(position), 0, string.length); + + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': ' + +``` + +## Documentation + +Some functions are also available in the following forms: +* `Series` - the same as `` but runs only a single async operation at a time +* `Limit` - the same as `` but runs a maximum of `limit` async operations at a time + +### Collections + +* [`each`](#each), `eachSeries`, `eachLimit` +* [`forEachOf`](#forEachOf), `forEachOfSeries`, `forEachOfLimit` +* [`map`](#map), `mapSeries`, `mapLimit` +* [`filter`](#filter), `filterSeries`, `filterLimit` +* [`reject`](#reject), `rejectSeries`, `rejectLimit` +* [`reduce`](#reduce), [`reduceRight`](#reduceRight) +* [`detect`](#detect), `detectSeries`, `detectLimit` +* [`sortBy`](#sortBy) +* [`some`](#some), `someLimit` +* [`every`](#every), `everyLimit` +* [`concat`](#concat), `concatSeries` + +### Control Flow + +* [`series`](#seriestasks-callback) +* [`parallel`](#parallel), `parallelLimit` +* [`whilst`](#whilst), [`doWhilst`](#doWhilst) +* [`until`](#until), [`doUntil`](#doUntil) +* [`during`](#during), [`doDuring`](#doDuring) +* [`forever`](#forever) +* [`waterfall`](#waterfall) +* [`compose`](#compose) +* [`seq`](#seq) +* [`applyEach`](#applyEach), `applyEachSeries` +* [`queue`](#queue), [`priorityQueue`](#priorityQueue) +* [`cargo`](#cargo) +* [`auto`](#auto) +* [`retry`](#retry) +* [`iterator`](#iterator) +* [`times`](#times), `timesSeries`, `timesLimit` + +### Utils + +* [`apply`](#apply) +* [`nextTick`](#nextTick) +* [`memoize`](#memoize) +* [`unmemoize`](#unmemoize) +* [`ensureAsync`](#ensureAsync) +* [`constant`](#constant) +* [`asyncify`](#asyncify) +* [`wrapSync`](#wrapSync) +* [`log`](#log) +* [`dir`](#dir) +* [`noConflict`](#noConflict) + +## Collections + + + +### each(arr, iterator, [callback]) + +Applies the function `iterator` to each item in `arr`, in parallel. +The `iterator` is called with an item from the list, and a callback for when it +has finished. If the `iterator` passes an error to its `callback`, the main +`callback` (for the `each` function) is immediately called with the error. + +Note, that since this function applies `iterator` to each item in parallel, +there is no guarantee that the iterator functions will complete in order. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err)` which must be called once it has + completed. If no error has occurred, the `callback` should be run without + arguments or with an explicit `null` argument. The array index is not passed + to the iterator. If you need the index, use [`forEachOf`](#forEachOf). +* `callback(err)` - *Optional* A callback which is called when all `iterator` functions + have finished, or an error occurs. + +__Examples__ + + +```js +// assuming openFiles is an array of file names and saveFile is a function +// to save the modified contents of that file: + +async.each(openFiles, saveFile, function(err){ + // if any of the saves produced an error, err would equal that error +}); +``` + +```js +// assuming openFiles is an array of file names + +async.each(openFiles, function(file, callback) { + + // Perform operation on file here. + console.log('Processing file ' + file); + + if( file.length > 32 ) { + console.log('This file name is too long'); + callback('File name too long'); + } else { + // Do work to process file here + console.log('File processed'); + callback(); + } +}, function(err){ + // if any of the file processing produced an error, err would equal that error + if( err ) { + // One of the iterations produced an error. + // All processing will now stop. + console.log('A file failed to process'); + } else { + console.log('All files have been processed successfully'); + } +}); +``` + +__Related__ + +* eachSeries(arr, iterator, [callback]) +* eachLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + + + +### forEachOf(obj, iterator, [callback]) + +Like `each`, except that it iterates over objects, and passes the key as the second argument to the iterator. + +__Arguments__ + +* `obj` - An object or array to iterate over. +* `iterator(item, key, callback)` - A function to apply to each item in `obj`. +The `key` is the item's key, or index in the case of an array. The iterator is +passed a `callback(err)` which must be called once it has completed. If no +error has occurred, the callback should be run without arguments or with an +explicit `null` argument. +* `callback(err)` - *Optional* A callback which is called when all `iterator` functions have finished, or an error occurs. + +__Example__ + +```js +var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; +var configs = {}; + +async.forEachOf(obj, function (value, key, callback) { + fs.readFile(__dirname + value, "utf8", function (err, data) { + if (err) return callback(err); + try { + configs[key] = JSON.parse(data); + } catch (e) { + return callback(e); + } + callback(); + }) +}, function (err) { + if (err) console.error(err.message); + // configs is now a map of JSON data + doSomethingWith(configs); +}) +``` + +__Related__ + +* forEachOfSeries(obj, iterator, [callback]) +* forEachOfLimit(obj, limit, iterator, [callback]) + +--------------------------------------- + + +### map(arr, iterator, [callback]) + +Produces a new array of values by mapping each value in `arr` through +the `iterator` function. The `iterator` is called with an item from `arr` and a +callback for when it has finished processing. Each of these callback takes 2 arguments: +an `error`, and the transformed item from `arr`. If `iterator` passes an error to its +callback, the main `callback` (for the `map` function) is immediately called with the error. + +Note, that since this function applies the `iterator` to each item in parallel, +there is no guarantee that the `iterator` functions will complete in order. +However, the results array will be in the same order as the original `arr`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, transformed)` which must be called once + it has completed with an error (which can be `null`) and a transformed item. +* `callback(err, results)` - *Optional* A callback which is called when all `iterator` + functions have finished, or an error occurs. Results is an array of the + transformed items from the `arr`. + +__Example__ + +```js +async.map(['file1','file2','file3'], fs.stat, function(err, results){ + // results is now an array of stats for each file +}); +``` + +__Related__ +* mapSeries(arr, iterator, [callback]) +* mapLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + + +### filter(arr, iterator, [callback]) + +__Alias:__ `select` + +Returns a new array of all the values in `arr` which pass an async truth test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. This operation is +performed in parallel, but the results array will be in the same order as the +original. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The `iterator` is passed a `callback(truthValue)`, which must be called with a + boolean argument once it has completed. +* `callback(results)` - *Optional* A callback which is called after all the `iterator` + functions have finished. + +__Example__ + +```js +async.filter(['file1','file2','file3'], fs.exists, function(results){ + // results now equals an array of the existing files +}); +``` + +__Related__ + +* filterSeries(arr, iterator, [callback]) +* filterLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + +### reject(arr, iterator, [callback]) + +The opposite of [`filter`](#filter). Removes values that pass an `async` truth test. + +__Related__ + +* rejectSeries(arr, iterator, [callback]) +* rejectLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + +### reduce(arr, memo, iterator, [callback]) + +__Aliases:__ `inject`, `foldl` + +Reduces `arr` into a single value using an async `iterator` to return +each successive step. `memo` is the initial state of the reduction. +This function only operates in series. + +For performance reasons, it may make sense to split a call to this function into +a parallel map, and then use the normal `Array.prototype.reduce` on the results. +This function is for situations where each step in the reduction needs to be async; +if you can get the data before reducing it, then it's probably a good idea to do so. + +__Arguments__ + +* `arr` - An array to iterate over. +* `memo` - The initial state of the reduction. +* `iterator(memo, item, callback)` - A function applied to each item in the + array to produce the next step in the reduction. The `iterator` is passed a + `callback(err, reduction)` which accepts an optional error as its first + argument, and the state of the reduction as the second. If an error is + passed to the callback, the reduction is stopped and the main `callback` is + immediately called with the error. +* `callback(err, result)` - *Optional* A callback which is called after all the `iterator` + functions have finished. Result is the reduced value. + +__Example__ + +```js +async.reduce([1,2,3], 0, function(memo, item, callback){ + // pointless async: + process.nextTick(function(){ + callback(null, memo + item) + }); +}, function(err, result){ + // result is now equal to the last value of memo, which is 6 +}); +``` + +--------------------------------------- + + +### reduceRight(arr, memo, iterator, [callback]) + +__Alias:__ `foldr` + +Same as [`reduce`](#reduce), only operates on `arr` in reverse order. + + +--------------------------------------- + + +### detect(arr, iterator, [callback]) + +Returns the first value in `arr` that passes an async truth test. The +`iterator` is applied in parallel, meaning the first iterator to return `true` will +fire the detect `callback` with that result. That means the result might not be +the first item in the original `arr` (in terms of order) that passes the test. + +If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries). + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The iterator is passed a `callback(truthValue)` which must be called with a + boolean argument once it has completed. **Note: this callback does not take an error as its first argument.** +* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns + `true`, or after all the `iterator` functions have finished. Result will be + the first item in the array that passes the truth test (iterator) or the + value `undefined` if none passed. **Note: this callback does not take an error as its first argument.** + +__Example__ + +```js +async.detect(['file1','file2','file3'], fs.exists, function(result){ + // result now equals the first file in the list that exists +}); +``` + +__Related__ + +* detectSeries(arr, iterator, [callback]) +* detectLimit(arr, limit, iterator, [callback]) + +--------------------------------------- + + +### sortBy(arr, iterator, [callback]) + +Sorts a list by the results of running each `arr` value through an async `iterator`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, sortValue)` which must be called once it + has completed with an error (which can be `null`) and a value to use as the sort + criteria. +* `callback(err, results)` - *Optional* A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is the items from + the original `arr` sorted by the values returned by the `iterator` calls. + +__Example__ + +```js +async.sortBy(['file1','file2','file3'], function(file, callback){ + fs.stat(file, function(err, stats){ + callback(err, stats.mtime); + }); +}, function(err, results){ + // results is now the original array of files sorted by + // modified date +}); +``` + +__Sort Order__ + +By modifying the callback parameter the sorting order can be influenced: + +```js +//ascending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x); +}, function(err,result){ + //result callback +} ); + +//descending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x*-1); //<- x*-1 instead of x, turns the order around +}, function(err,result){ + //result callback +} ); +``` + +--------------------------------------- + + +### some(arr, iterator, [callback]) + +__Alias:__ `any` + +Returns `true` if at least one element in the `arr` satisfies an async test. +_The callback for each iterator call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. Once any iterator +call returns `true`, the main `callback` is immediately called. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a `callback(truthValue)`` which must be + called with a boolean argument once it has completed. +* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns + `true`, or after all the iterator functions have finished. Result will be + either `true` or `false` depending on the values of the async tests. + + **Note: the callbacks do not take an error as their first argument.** +__Example__ + +```js +async.some(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then at least one of the files exists +}); +``` + +__Related__ + +* someLimit(arr, limit, iterator, callback) + +--------------------------------------- + + +### every(arr, iterator, [callback]) + +__Alias:__ `all` + +Returns `true` if every element in `arr` satisfies an async test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a `callback(truthValue)` which must be + called with a boolean argument once it has completed. +* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns + `false`, or after all the iterator functions have finished. Result will be + either `true` or `false` depending on the values of the async tests. + + **Note: the callbacks do not take an error as their first argument.** + +__Example__ + +```js +async.every(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then every file exists +}); +``` + +__Related__ + +* everyLimit(arr, limit, iterator, callback) + +--------------------------------------- + + +### concat(arr, iterator, [callback]) + +Applies `iterator` to each item in `arr`, concatenating the results. Returns the +concatenated list. The `iterator`s are called in parallel, and the results are +concatenated as they return. There is no guarantee that the results array will +be returned in the original order of `arr` passed to the `iterator` function. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, results)` which must be called once it + has completed with an error (which can be `null`) and an array of results. +* `callback(err, results)` - *Optional* A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is an array containing + the concatenated results of the `iterator` function. + +__Example__ + +```js +async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){ + // files is now a list of filenames that exist in the 3 directories +}); +``` + +__Related__ + +* concatSeries(arr, iterator, [callback]) + + +## Control Flow + + +### series(tasks, [callback]) + +Run the functions in the `tasks` array in series, each one running once the previous +function has completed. If any functions in the series pass an error to its +callback, no more functions are run, and `callback` is immediately called with the value of the error. +Otherwise, `callback` receives an array of results when `tasks` have completed. + +It is also possible to use an object instead of an array. Each property will be +run as a function, and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`series`](#series). + +**Note** that while many implementations preserve the order of object properties, the +[ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) +explicitly states that + +> The mechanics and order of enumerating the properties is not specified. + +So if you rely on the order in which your series of functions are executed, and want +this to work on all platforms, consider using an array. + +__Arguments__ + +* `tasks` - An array or object containing functions to run, each function is passed + a `callback(err, result)` it must call on completion with an error `err` (which can + be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the `task` callbacks. + +__Example__ + +```js +async.series([ + function(callback){ + // do some stuff ... + callback(null, 'one'); + }, + function(callback){ + // do some more stuff ... + callback(null, 'two'); + } +], +// optional callback +function(err, results){ + // results is now equal to ['one', 'two'] +}); + + +// an example using an object instead of an array +async.series({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equal to: {one: 1, two: 2} +}); +``` + +--------------------------------------- + + +### parallel(tasks, [callback]) + +Run the `tasks` array of functions in parallel, without waiting until the previous +function has completed. If any of the functions pass an error to its +callback, the main `callback` is immediately called with the value of the error. +Once the `tasks` have completed, the results are passed to the final `callback` as an +array. + +**Note:** `parallel` is about kicking-off I/O tasks in parallel, not about parallel execution of code. If your tasks do not use any timers or perform any I/O, they will actually be executed in series. Any synchronous setup sections for each task will happen one after the other. JavaScript remains single-threaded. + +It is also possible to use an object instead of an array. Each property will be +run as a function and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`parallel`](#parallel). + + +__Arguments__ + +* `tasks` - An array or object containing functions to run. Each function is passed + a `callback(err, result)` which it must call on completion with an error `err` + (which can be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed successfully. This function gets a results array (or object) containing all + the result arguments passed to the task callbacks. + +__Example__ + +```js +async.parallel([ + function(callback){ + setTimeout(function(){ + callback(null, 'one'); + }, 200); + }, + function(callback){ + setTimeout(function(){ + callback(null, 'two'); + }, 100); + } +], +// optional callback +function(err, results){ + // the results array will equal ['one','two'] even though + // the second function had a shorter timeout. +}); + + +// an example using an object instead of an array +async.parallel({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equals to: {one: 1, two: 2} +}); +``` + +__Related__ + +* parallelLimit(tasks, limit, [callback]) + +--------------------------------------- + + +### whilst(test, fn, callback) + +Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped, +or an error occurs. + +__Arguments__ + +* `test()` - synchronous truth test to perform before each execution of `fn`. +* `fn(callback)` - A function which is called each time `test` passes. The function is + passed a `callback(err)`, which must be called once it has completed with an + optional `err` argument. +* `callback(err, [results])` - A callback which is called after the test + function has failed and repeated execution of `fn` has stopped. `callback` + will be passed an error and any arguments passed to the final `fn`'s callback. + +__Example__ + +```js +var count = 0; + +async.whilst( + function () { return count < 5; }, + function (callback) { + count++; + setTimeout(function () { + callback(null, count); + }, 1000); + }, + function (err, n) { + // 5 seconds have passed, n = 5 + } +); +``` + +--------------------------------------- + + +### doWhilst(fn, test, callback) + +The post-check version of [`whilst`](#whilst). To reflect the difference in +the order of operations, the arguments `test` and `fn` are switched. + +`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + +--------------------------------------- + + +### until(test, fn, callback) + +Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped, +or an error occurs. `callback` will be passed an error and any arguments passed +to the final `fn`'s callback. + +The inverse of [`whilst`](#whilst). + +--------------------------------------- + + +### doUntil(fn, test, callback) + +Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`. + +--------------------------------------- + + +### during(test, fn, callback) + +Like [`whilst`](#whilst), except the `test` is an asynchronous function that is passed a callback in the form of `function (err, truth)`. If error is passed to `test` or `fn`, the main callback is immediately called with the value of the error. + +__Example__ + +```js +var count = 0; + +async.during( + function (callback) { + return callback(null, count < 5); + }, + function (callback) { + count++; + setTimeout(callback, 1000); + }, + function (err) { + // 5 seconds have passed + } +); +``` + +--------------------------------------- + + +### doDuring(fn, test, callback) + +The post-check version of [`during`](#during). To reflect the difference in +the order of operations, the arguments `test` and `fn` are switched. + +Also a version of [`doWhilst`](#doWhilst) with asynchronous `test` function. + +--------------------------------------- + + +### forever(fn, [errback]) + +Calls the asynchronous function `fn` with a callback parameter that allows it to +call itself again, in series, indefinitely. + +If an error is passed to the callback then `errback` is called with the +error, and execution stops, otherwise it will never be called. + +```js +async.forever( + function(next) { + // next is suitable for passing to things that need a callback(err [, whatever]); + // it will result in this function being called again. + }, + function(err) { + // if next is called with a value in its first parameter, it will appear + // in here as 'err', and execution will stop. + } +); +``` + +--------------------------------------- + + +### waterfall(tasks, [callback]) + +Runs the `tasks` array of functions in series, each passing their results to the next in +the array. However, if any of the `tasks` pass an error to their own callback, the +next function is not executed, and the main `callback` is immediately called with +the error. + +__Arguments__ + +* `tasks` - An array of functions to run, each function is passed a + `callback(err, result1, result2, ...)` it must call on completion. The first + argument is an error (which can be `null`) and any further arguments will be + passed as arguments in order to the next task. +* `callback(err, [results])` - An optional callback to run once all the functions + have completed. This will be passed the results of the last task's callback. + + + +__Example__ + +```js +async.waterfall([ + function(callback) { + callback(null, 'one', 'two'); + }, + function(arg1, arg2, callback) { + // arg1 now equals 'one' and arg2 now equals 'two' + callback(null, 'three'); + }, + function(arg1, callback) { + // arg1 now equals 'three' + callback(null, 'done'); + } +], function (err, result) { + // result now equals 'done' +}); +``` +Or, with named functions: + +```js +async.waterfall([ + myFirstFunction, + mySecondFunction, + myLastFunction, +], function (err, result) { + // result now equals 'done' +}); +function myFirstFunction(callback) { + callback(null, 'one', 'two'); +} +function mySecondFunction(arg1, arg2, callback) { + // arg1 now equals 'one' and arg2 now equals 'two' + callback(null, 'three'); +} +function myLastFunction(arg1, callback) { + // arg1 now equals 'three' + callback(null, 'done'); +} +``` + +Or, if you need to pass any argument to the first function: + +```js +async.waterfall([ + async.apply(myFirstFunction, 'zero'), + mySecondFunction, + myLastFunction, +], function (err, result) { + // result now equals 'done' +}); +function myFirstFunction(arg1, callback) { + // arg1 now equals 'zero' + callback(null, 'one', 'two'); +} +function mySecondFunction(arg1, arg2, callback) { + // arg1 now equals 'one' and arg2 now equals 'two' + callback(null, 'three'); +} +function myLastFunction(arg1, callback) { + // arg1 now equals 'three' + callback(null, 'done'); +} +``` + +--------------------------------------- + +### compose(fn1, fn2...) + +Creates a function which is a composition of the passed asynchronous +functions. Each function consumes the return value of the function that +follows. Composing functions `f()`, `g()`, and `h()` would produce the result of +`f(g(h()))`, only this version uses callbacks to obtain the return values. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* `functions...` - the asynchronous functions to compose + + +__Example__ + +```js +function add1(n, callback) { + setTimeout(function () { + callback(null, n + 1); + }, 10); +} + +function mul3(n, callback) { + setTimeout(function () { + callback(null, n * 3); + }, 10); +} + +var add1mul3 = async.compose(mul3, add1); + +add1mul3(4, function (err, result) { + // result now equals 15 +}); +``` + +--------------------------------------- + +### seq(fn1, fn2...) + +Version of the compose function that is more natural to read. +Each function consumes the return value of the previous function. +It is the equivalent of [`compose`](#compose) with the arguments reversed. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* `functions...` - the asynchronous functions to compose + + +__Example__ + +```js +// Requires lodash (or underscore), express3 and dresende's orm2. +// Part of an app, that fetches cats of the logged user. +// This example uses `seq` function to avoid overnesting and error +// handling clutter. +app.get('/cats', function(request, response) { + var User = request.models.User; + async.seq( + _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + function(user, fn) { + user.getCats(fn); // 'getCats' has signature (callback(err, data)) + } + )(req.session.user_id, function (err, cats) { + if (err) { + console.error(err); + response.json({ status: 'error', message: err.message }); + } else { + response.json({ status: 'ok', message: 'Cats found', data: cats }); + } + }); +}); +``` + +--------------------------------------- + +### applyEach(fns, args..., callback) + +Applies the provided arguments to each function in the array, calling +`callback` after all functions have completed. If you only provide the first +argument, then it will return a function which lets you pass in the +arguments as if it were a single function call. + +__Arguments__ + +* `fns` - the asynchronous functions to all call with the same arguments +* `args...` - any number of separate arguments to pass to the function +* `callback` - the final argument should be the callback, called when all + functions have completed processing + + +__Example__ + +```js +async.applyEach([enableSearch, updateSchema], 'bucket', callback); + +// partial application example: +async.each( + buckets, + async.applyEach([enableSearch, updateSchema]), + callback +); +``` + +__Related__ + +* applyEachSeries(tasks, args..., [callback]) + +--------------------------------------- + + +### queue(worker, [concurrency]) + +Creates a `queue` object with the specified `concurrency`. Tasks added to the +`queue` are processed in parallel (up to the `concurrency` limit). If all +`worker`s are in progress, the task is queued until one becomes available. +Once a `worker` completes a `task`, that `task`'s callback is called. + +__Arguments__ + +* `worker(task, callback)` - An asynchronous function for processing a queued + task, which must call its `callback(err)` argument when finished, with an + optional `error` as an argument. If you want to handle errors from an individual task, pass a callback to `q.push()`. +* `concurrency` - An `integer` for determining how many `worker` functions should be + run in parallel. If omitted, the concurrency defaults to `1`. If the concurrency is `0`, an error is thrown. + +__Queue objects__ + +The `queue` object returned by this function has the following properties and +methods: + +* `length()` - a function returning the number of items waiting to be processed. +* `started` - a function returning whether or not any items have been pushed and processed by the queue +* `running()` - a function returning the number of items currently being processed. +* `workersList()` - a function returning the array of items currently being processed. +* `idle()` - a function returning false if there are items waiting or being processed, or true if not. +* `concurrency` - an integer for determining how many `worker` functions should be + run in parallel. This property can be changed after a `queue` is created to + alter the concurrency on-the-fly. +* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once + the `worker` has finished processing the task. Instead of a single task, a `tasks` array + can be submitted. The respective callback is used for every task in the list. +* `unshift(task, [callback])` - add a new task to the front of the `queue`. +* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit, + and further tasks will be queued. +* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`. +* `paused` - a boolean for determining whether the queue is in a paused state +* `pause()` - a function that pauses the processing of tasks until `resume()` is called. +* `resume()` - a function that resumes the processing of queued tasks when the queue is paused. +* `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle. + +__Example__ + +```js +// create a queue object with concurrency 2 + +var q = async.queue(function (task, callback) { + console.log('hello ' + task.name); + callback(); +}, 2); + + +// assign a callback +q.drain = function() { + console.log('all items have been processed'); +} + +// add some items to the queue + +q.push({name: 'foo'}, function (err) { + console.log('finished processing foo'); +}); +q.push({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); + +// add some items to the queue (batch-wise) + +q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) { + console.log('finished processing item'); +}); + +// add some items to the front of the queue + +q.unshift({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); +``` + + +--------------------------------------- + + +### priorityQueue(worker, concurrency) + +The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects: + +* `push(task, priority, [callback])` - `priority` should be a number. If an array of + `tasks` is given, all tasks will be assigned the same priority. +* The `unshift` method was removed. + +--------------------------------------- + + +### cargo(worker, [payload]) + +Creates a `cargo` object with the specified payload. Tasks added to the +cargo will be processed altogether (up to the `payload` limit). If the +`worker` is in progress, the task is queued until it becomes available. Once +the `worker` has completed some tasks, each callback of those tasks is called. +Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) for how `cargo` and `queue` work. + +While [queue](#queue) passes only one task to one of a group of workers +at a time, cargo passes an array of tasks to a single worker, repeating +when the worker is finished. + +__Arguments__ + +* `worker(tasks, callback)` - An asynchronous function for processing an array of + queued tasks, which must call its `callback(err)` argument when finished, with + an optional `err` argument. +* `payload` - An optional `integer` for determining how many tasks should be + processed per round; if omitted, the default is unlimited. + +__Cargo objects__ + +The `cargo` object returned by this function has the following properties and +methods: + +* `length()` - A function returning the number of items waiting to be processed. +* `payload` - An `integer` for determining how many tasks should be + process per round. This property can be changed after a `cargo` is created to + alter the payload on-the-fly. +* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called + once the `worker` has finished processing the task. Instead of a single task, an array of `tasks` + can be submitted. The respective callback is used for every task in the list. +* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued. +* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`. +* `idle()`, `pause()`, `resume()`, `kill()` - cargo inherits all of the same methods and event calbacks as [`queue`](#queue) + +__Example__ + +```js +// create a cargo object with payload 2 + +var cargo = async.cargo(function (tasks, callback) { + for(var i=0; i +### auto(tasks, [concurrency], [callback]) + +Determines the best order for running the functions in `tasks`, based on their requirements. Each function can optionally depend on other functions being completed first, and each function is run as soon as its requirements are satisfied. + +If any of the functions pass an error to their callback, the `auto` sequence will stop. Further tasks will not execute (so any other functions depending on it will not run), and the main `callback` is immediately called with the error. Functions also receive an object containing the results of functions which have completed so far. + +Note, all functions are called with a `results` object as a second argument, +so it is unsafe to pass functions in the `tasks` object which cannot handle the +extra argument. + +For example, this snippet of code: + +```js +async.auto({ + readData: async.apply(fs.readFile, 'data.txt', 'utf-8') +}, callback); +``` + +will have the effect of calling `readFile` with the results object as the last +argument, which will fail: + +```js +fs.readFile('data.txt', 'utf-8', cb, {}); +``` + +Instead, wrap the call to `readFile` in a function which does not forward the +`results` object: + +```js +async.auto({ + readData: function(cb, results){ + fs.readFile('data.txt', 'utf-8', cb); + } +}, callback); +``` + +__Arguments__ + +* `tasks` - An object. Each of its properties is either a function or an array of + requirements, with the function itself the last item in the array. The object's key + of a property serves as the name of the task defined by that property, + i.e. can be used when specifying requirements for other tasks. + The function receives two arguments: (1) a `callback(err, result)` which must be + called when finished, passing an `error` (which can be `null`) and the result of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions. +* `concurrency` - An optional `integer` for determining the maximum number of tasks that can be run in parallel. By default, as many as possible. +* `callback(err, results)` - An optional callback which is called when all the + tasks have been completed. It receives the `err` argument if any `tasks` + pass an error to their callback. Results are always returned; however, if + an error occurs, no further `tasks` will be performed, and the results + object will only contain partial results. + + +__Example__ + +```js +async.auto({ + get_data: function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + make_folder: function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + }, + write_file: ['get_data', 'make_folder', function(callback, results){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + callback(null, 'filename'); + }], + email_link: ['write_file', function(callback, results){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + // results.write_file contains the filename returned by write_file. + callback(null, {'file':results.write_file, 'email':'user@example.com'}); + }] +}, function(err, results) { + console.log('err = ', err); + console.log('results = ', results); +}); +``` + +This is a fairly trivial example, but to do this using the basic parallel and +series functions would look like this: + +```js +async.parallel([ + function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + } +], +function(err, results){ + async.series([ + function(callback){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + results.push('filename'); + callback(null); + }, + function(callback){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + callback(null, {'file':results.pop(), 'email':'user@example.com'}); + } + ]); +}); +``` + +For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding +new tasks much easier (and the code more readable). + + +--------------------------------------- + + +### retry([opts = {times: 5, interval: 0}| 5], task, [callback]) + +Attempts to get a successful response from `task` no more than `times` times before +returning an error. If the task is successful, the `callback` will be passed the result +of the successful task. If all attempts fail, the callback will be passed the error and +result (if any) of the final attempt. + +__Arguments__ + +* `opts` - Can be either an object with `times` and `interval` or a number. + * `times` - The number of attempts to make before giving up. The default is `5`. + * `interval` - The time to wait between retries, in milliseconds. The default is `0`. + * If `opts` is a number, the number specifies the number of times to retry, with the default interval of `0`. +* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)` + which must be called when finished, passing `err` (which can be `null`) and the `result` of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions (if nested inside another control flow). +* `callback(err, results)` - An optional callback which is called when the + task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`. + +The [`retry`](#retry) function can be used as a stand-alone control flow by passing a callback, as shown below: + +```js +// try calling apiMethod 3 times +async.retry(3, apiMethod, function(err, result) { + // do something with the result +}); +``` + +```js +// try calling apiMethod 3 times, waiting 200 ms between each retry +async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + // do something with the result +}); +``` + +```js +// try calling apiMethod the default 5 times no delay between each retry +async.retry(apiMethod, function(err, result) { + // do something with the result +}); +``` + +It can also be embedded within other control flow functions to retry individual methods +that are not as reliable, like this: + +```js +async.auto({ + users: api.getUsers.bind(api), + payments: async.retry(3, api.getPayments.bind(api)) +}, function(err, results) { + // do something with the results +}); +``` + + +--------------------------------------- + + +### iterator(tasks) + +Creates an iterator function which calls the next function in the `tasks` array, +returning a continuation to call the next one after that. It's also possible to +“peek” at the next iterator with `iterator.next()`. + +This function is used internally by the `async` module, but can be useful when +you want to manually control the flow of functions in series. + +__Arguments__ + +* `tasks` - An array of functions to run. + +__Example__ + +```js +var iterator = async.iterator([ + function(){ sys.p('one'); }, + function(){ sys.p('two'); }, + function(){ sys.p('three'); } +]); + +node> var iterator2 = iterator(); +'one' +node> var iterator3 = iterator2(); +'two' +node> iterator3(); +'three' +node> var nextfn = iterator2.next(); +node> nextfn(); +'three' +``` + +--------------------------------------- + + +### apply(function, arguments..) + +Creates a continuation function with some arguments already applied. + +Useful as a shorthand when combined with other control flow functions. Any arguments +passed to the returned function are added to the arguments originally passed +to apply. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to automatically apply when the + continuation is called. + +__Example__ + +```js +// using apply + +async.parallel([ + async.apply(fs.writeFile, 'testfile1', 'test1'), + async.apply(fs.writeFile, 'testfile2', 'test2'), +]); + + +// the same process without using apply + +async.parallel([ + function(callback){ + fs.writeFile('testfile1', 'test1', callback); + }, + function(callback){ + fs.writeFile('testfile2', 'test2', callback); + } +]); +``` + +It's possible to pass any number of additional arguments when calling the +continuation: + +```js +node> var fn = async.apply(sys.puts, 'one'); +node> fn('two', 'three'); +one +two +three +``` + +--------------------------------------- + + +### nextTick(callback), setImmediate(callback) + +Calls `callback` on a later loop around the event loop. In Node.js this just +calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)` +if available, otherwise `setTimeout(callback, 0)`, which means other higher priority +events may precede the execution of `callback`. + +This is used internally for browser-compatibility purposes. + +__Arguments__ + +* `callback` - The function to call on a later loop around the event loop. + +__Example__ + +```js +var call_order = []; +async.nextTick(function(){ + call_order.push('two'); + // call_order now equals ['one','two'] +}); +call_order.push('one') +``` + + +### times(n, iterator, [callback]) + +Calls the `iterator` function `n` times, and accumulates results in the same manner +you would use with [`map`](#map). + +__Arguments__ + +* `n` - The number of times to run the function. +* `iterator` - The function to call `n` times. +* `callback` - see [`map`](#map) + +__Example__ + +```js +// Pretend this is some complicated async factory +var createUser = function(id, callback) { + callback(null, { + id: 'user' + id + }) +} +// generate 5 users +async.times(5, function(n, next){ + createUser(n, function(err, user) { + next(err, user) + }) +}, function(err, users) { + // we should now have 5 users +}); +``` + +__Related__ + +* timesSeries(n, iterator, [callback]) +* timesLimit(n, limit, iterator, [callback]) + + +## Utils + + +### memoize(fn, [hasher]) + +Caches the results of an `async` function. When creating a hash to store function +results against, the callback is omitted from the hash and an optional hash +function can be used. + +If no hash function is specified, the first argument is used as a hash key, which may work reasonably if it is a string or a data type that converts to a distinct string. Note that objects and arrays will not behave reasonably. Neither will cases where the other arguments are significant. In such cases, specify your own hash function. + +The cache of results is exposed as the `memo` property of the function returned +by `memoize`. + +__Arguments__ + +* `fn` - The function to proxy and cache results from. +* `hasher` - An optional function for generating a custom hash for storing + results. It has all the arguments applied to it apart from the callback, and + must be synchronous. + +__Example__ + +```js +var slow_fn = function (name, callback) { + // do something + callback(null, result); +}; +var fn = async.memoize(slow_fn); + +// fn can now be used as if it were slow_fn +fn('some name', function () { + // callback +}); +``` + + +### unmemoize(fn) + +Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized +form. Handy for testing. + +__Arguments__ + +* `fn` - the memoized function + +--------------------------------------- + + +### ensureAsync(fn) + +Wrap an async function and ensure it calls its callback on a later tick of the event loop. If the function already calls its callback on a next tick, no extra deferral is added. This is useful for preventing stack overflows (`RangeError: Maximum call stack size exceeded`) and generally keeping [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) contained. + +__Arguments__ + +* `fn` - an async function, one that expects a node-style callback as its last argument + +Returns a wrapped function with the exact same call signature as the function passed in. + +__Example__ + +```js +function sometimesAsync(arg, callback) { + if (cache[arg]) { + return callback(null, cache[arg]); // this would be synchronous!! + } else { + doSomeIO(arg, callback); // this IO would be asynchronous + } +} + +// this has a risk of stack overflows if many results are cached in a row +async.mapSeries(args, sometimesAsync, done); + +// this will defer sometimesAsync's callback if necessary, +// preventing stack overflows +async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + +``` + +--------------------------------------- + + +### constant(values...) + +Returns a function that when called, calls-back with the values provided. Useful as the first function in a `waterfall`, or for plugging values in to `auto`. + +__Example__ + +```js +async.waterfall([ + async.constant(42), + function (value, next) { + // value === 42 + }, + //... +], callback); + +async.waterfall([ + async.constant(filename, "utf8"), + fs.readFile, + function (fileData, next) { + //... + } + //... +], callback); + +async.auto({ + hostname: async.constant("https://server.net/"), + port: findFreePort, + launchServer: ["hostname", "port", function (cb, options) { + startServer(options, cb); + }], + //... +}, callback); + +``` + +--------------------------------------- + + + +### asyncify(func) + +__Alias:__ `wrapSync` + +Take a sync function and make it async, passing its return value to a callback. This is useful for plugging sync functions into a waterfall, series, or other async functions. Any arguments passed to the generated function will be passed to the wrapped function (except for the final callback argument). Errors thrown will be passed to the callback. + +__Example__ + +```js +async.waterfall([ + async.apply(fs.readFile, filename, "utf8"), + async.asyncify(JSON.parse), + function (data, next) { + // data is the result of parsing the text. + // If there was a parsing error, it would have been caught. + } +], callback) +``` + +If the function passed to `asyncify` returns a Promise, that promises's resolved/rejected state will be used to call the callback, rather than simply the synchronous return value. Example: + +```js +async.waterfall([ + async.apply(fs.readFile, filename, "utf8"), + async.asyncify(function (contents) { + return db.model.create(contents); + }), + function (model, next) { + // `model` is the instantiated model object. + // If there was an error, this function would be skipped. + } +], callback) +``` + +This also means you can asyncify ES2016 `async` functions. + +```js +var q = async.queue(async.asyncify(async function (file) { + var intermediateStep = await processFile(file); + return await somePromise(intermediateStep) +})); + +q.push(files); +``` + +--------------------------------------- + + +### log(function, arguments) + +Logs the result of an `async` function to the `console`. Only works in Node.js or +in browsers that support `console.log` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.log` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, 'hello ' + name); + }, 1000); +}; +``` +```js +node> async.log(hello, 'world'); +'hello world' +``` + +--------------------------------------- + + +### dir(function, arguments) + +Logs the result of an `async` function to the `console` using `console.dir` to +display the properties of the resulting object. Only works in Node.js or +in browsers that support `console.dir` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.dir` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, {hello: name}); + }, 1000); +}; +``` +```js +node> async.dir(hello, 'world'); +{hello: 'world'} +``` + +--------------------------------------- + + +### noConflict() + +Changes the value of `async` back to its original value, returning a reference to the +`async` object. diff --git a/app/node_modules/nconf/node_modules/async/dist/async.js b/app/node_modules/nconf/node_modules/async/dist/async.js new file mode 100644 index 0000000..31e7620 --- /dev/null +++ b/app/node_modules/nconf/node_modules/async/dist/async.js @@ -0,0 +1,1265 @@ +/*! + * async + * https://github.com/caolan/async + * + * Copyright 2010-2014 Caolan McMahon + * Released under the MIT license + */ +(function () { + + var async = {}; + function noop() {} + function identity(v) { + return v; + } + function toBool(v) { + return !!v; + } + function notId(v) { + return !v; + } + + // global on the server, window in the browser + var previous_async; + + // Establish the root object, `window` (`self`) in the browser, `global` + // on the server, or `this` in some virtual machines. We use `self` + // instead of `window` for `WebWorker` support. + var root = typeof self === 'object' && self.self === self && self || + typeof global === 'object' && global.global === global && global || + this; + + if (root != null) { + previous_async = root.async; + } + + async.noConflict = function () { + root.async = previous_async; + return async; + }; + + function only_once(fn) { + return function() { + if (fn === null) throw new Error("Callback was already called."); + fn.apply(this, arguments); + fn = null; + }; + } + + function _once(fn) { + return function() { + if (fn === null) return; + fn.apply(this, arguments); + fn = null; + }; + } + + //// cross-browser compatiblity functions //// + + var _toString = Object.prototype.toString; + + var _isArray = Array.isArray || function (obj) { + return _toString.call(obj) === '[object Array]'; + }; + + // Ported from underscore.js isObject + var _isObject = function(obj) { + var type = typeof obj; + return type === 'function' || type === 'object' && !!obj; + }; + + function _isArrayLike(arr) { + return _isArray(arr) || ( + // has a positive integer length property + typeof arr.length === "number" && + arr.length >= 0 && + arr.length % 1 === 0 + ); + } + + function _arrayEach(arr, iterator) { + var index = -1, + length = arr.length; + + while (++index < length) { + iterator(arr[index], index, arr); + } + } + + function _map(arr, iterator) { + var index = -1, + length = arr.length, + result = Array(length); + + while (++index < length) { + result[index] = iterator(arr[index], index, arr); + } + return result; + } + + function _range(count) { + return _map(Array(count), function (v, i) { return i; }); + } + + function _reduce(arr, iterator, memo) { + _arrayEach(arr, function (x, i, a) { + memo = iterator(memo, x, i, a); + }); + return memo; + } + + function _forEachOf(object, iterator) { + _arrayEach(_keys(object), function (key) { + iterator(object[key], key); + }); + } + + function _indexOf(arr, item) { + for (var i = 0; i < arr.length; i++) { + if (arr[i] === item) return i; + } + return -1; + } + + var _keys = Object.keys || function (obj) { + var keys = []; + for (var k in obj) { + if (obj.hasOwnProperty(k)) { + keys.push(k); + } + } + return keys; + }; + + function _keyIterator(coll) { + var i = -1; + var len; + var keys; + if (_isArrayLike(coll)) { + len = coll.length; + return function next() { + i++; + return i < len ? i : null; + }; + } else { + keys = _keys(coll); + len = keys.length; + return function next() { + i++; + return i < len ? keys[i] : null; + }; + } + } + + // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) + // This accumulates the arguments passed into an array, after a given index. + // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). + function _restParam(func, startIndex) { + startIndex = startIndex == null ? func.length - 1 : +startIndex; + return function() { + var length = Math.max(arguments.length - startIndex, 0); + var rest = Array(length); + for (var index = 0; index < length; index++) { + rest[index] = arguments[index + startIndex]; + } + switch (startIndex) { + case 0: return func.call(this, rest); + case 1: return func.call(this, arguments[0], rest); + } + // Currently unused but handle cases outside of the switch statement: + // var args = Array(startIndex + 1); + // for (index = 0; index < startIndex; index++) { + // args[index] = arguments[index]; + // } + // args[startIndex] = rest; + // return func.apply(this, args); + }; + } + + function _withoutIndex(iterator) { + return function (value, index, callback) { + return iterator(value, callback); + }; + } + + //// exported async module functions //// + + //// nextTick implementation with browser-compatible fallback //// + + // capture the global reference to guard against fakeTimer mocks + var _setImmediate = typeof setImmediate === 'function' && setImmediate; + + var _delay = _setImmediate ? function(fn) { + // not a direct alias for IE10 compatibility + _setImmediate(fn); + } : function(fn) { + setTimeout(fn, 0); + }; + + if (typeof process === 'object' && typeof process.nextTick === 'function') { + async.nextTick = process.nextTick; + } else { + async.nextTick = _delay; + } + async.setImmediate = _setImmediate ? _delay : async.nextTick; + + + async.forEach = + async.each = function (arr, iterator, callback) { + return async.eachOf(arr, _withoutIndex(iterator), callback); + }; + + async.forEachSeries = + async.eachSeries = function (arr, iterator, callback) { + return async.eachOfSeries(arr, _withoutIndex(iterator), callback); + }; + + + async.forEachLimit = + async.eachLimit = function (arr, limit, iterator, callback) { + return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); + }; + + async.forEachOf = + async.eachOf = function (object, iterator, callback) { + callback = _once(callback || noop); + object = object || []; + + var iter = _keyIterator(object); + var key, completed = 0; + + while ((key = iter()) != null) { + completed += 1; + iterator(object[key], key, only_once(done)); + } + + if (completed === 0) callback(null); + + function done(err) { + completed--; + if (err) { + callback(err); + } + // Check key is null in case iterator isn't exhausted + // and done resolved synchronously. + else if (key === null && completed <= 0) { + callback(null); + } + } + }; + + async.forEachOfSeries = + async.eachOfSeries = function (obj, iterator, callback) { + callback = _once(callback || noop); + obj = obj || []; + var nextKey = _keyIterator(obj); + var key = nextKey(); + function iterate() { + var sync = true; + if (key === null) { + return callback(null); + } + iterator(obj[key], key, only_once(function (err) { + if (err) { + callback(err); + } + else { + key = nextKey(); + if (key === null) { + return callback(null); + } else { + if (sync) { + async.setImmediate(iterate); + } else { + iterate(); + } + } + } + })); + sync = false; + } + iterate(); + }; + + + + async.forEachOfLimit = + async.eachOfLimit = function (obj, limit, iterator, callback) { + _eachOfLimit(limit)(obj, iterator, callback); + }; + + function _eachOfLimit(limit) { + + return function (obj, iterator, callback) { + callback = _once(callback || noop); + obj = obj || []; + var nextKey = _keyIterator(obj); + if (limit <= 0) { + return callback(null); + } + var done = false; + var running = 0; + var errored = false; + + (function replenish () { + if (done && running <= 0) { + return callback(null); + } + + while (running < limit && !errored) { + var key = nextKey(); + if (key === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iterator(obj[key], key, only_once(function (err) { + running -= 1; + if (err) { + callback(err); + errored = true; + } + else { + replenish(); + } + })); + } + })(); + }; + } + + + function doParallel(fn) { + return function (obj, iterator, callback) { + return fn(async.eachOf, obj, iterator, callback); + }; + } + function doParallelLimit(fn) { + return function (obj, limit, iterator, callback) { + return fn(_eachOfLimit(limit), obj, iterator, callback); + }; + } + function doSeries(fn) { + return function (obj, iterator, callback) { + return fn(async.eachOfSeries, obj, iterator, callback); + }; + } + + function _asyncMap(eachfn, arr, iterator, callback) { + callback = _once(callback || noop); + arr = arr || []; + var results = _isArrayLike(arr) ? [] : {}; + eachfn(arr, function (value, index, callback) { + iterator(value, function (err, v) { + results[index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + + async.map = doParallel(_asyncMap); + async.mapSeries = doSeries(_asyncMap); + async.mapLimit = doParallelLimit(_asyncMap); + + // reduce only has a series version, as doing reduce in parallel won't + // work in many situations. + async.inject = + async.foldl = + async.reduce = function (arr, memo, iterator, callback) { + async.eachOfSeries(arr, function (x, i, callback) { + iterator(memo, x, function (err, v) { + memo = v; + callback(err); + }); + }, function (err) { + callback(err, memo); + }); + }; + + async.foldr = + async.reduceRight = function (arr, memo, iterator, callback) { + var reversed = _map(arr, identity).reverse(); + async.reduce(reversed, memo, iterator, callback); + }; + + async.transform = function (arr, memo, iterator, callback) { + if (arguments.length === 3) { + callback = iterator; + iterator = memo; + memo = _isArray(arr) ? [] : {}; + } + + async.eachOf(arr, function(v, k, cb) { + iterator(memo, v, k, cb); + }, function(err) { + callback(err, memo); + }); + }; + + function _filter(eachfn, arr, iterator, callback) { + var results = []; + eachfn(arr, function (x, index, callback) { + iterator(x, function (v) { + if (v) { + results.push({index: index, value: x}); + } + callback(); + }); + }, function () { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + } + + async.select = + async.filter = doParallel(_filter); + + async.selectLimit = + async.filterLimit = doParallelLimit(_filter); + + async.selectSeries = + async.filterSeries = doSeries(_filter); + + function _reject(eachfn, arr, iterator, callback) { + _filter(eachfn, arr, function(value, cb) { + iterator(value, function(v) { + cb(!v); + }); + }, callback); + } + async.reject = doParallel(_reject); + async.rejectLimit = doParallelLimit(_reject); + async.rejectSeries = doSeries(_reject); + + function _createTester(eachfn, check, getResult) { + return function(arr, limit, iterator, cb) { + function done() { + if (cb) cb(getResult(false, void 0)); + } + function iteratee(x, _, callback) { + if (!cb) return callback(); + iterator(x, function (v) { + if (cb && check(v)) { + cb(getResult(true, x)); + cb = iterator = false; + } + callback(); + }); + } + if (arguments.length > 3) { + eachfn(arr, limit, iteratee, done); + } else { + cb = iterator; + iterator = limit; + eachfn(arr, iteratee, done); + } + }; + } + + async.any = + async.some = _createTester(async.eachOf, toBool, identity); + + async.someLimit = _createTester(async.eachOfLimit, toBool, identity); + + async.all = + async.every = _createTester(async.eachOf, notId, notId); + + async.everyLimit = _createTester(async.eachOfLimit, notId, notId); + + function _findGetResult(v, x) { + return x; + } + async.detect = _createTester(async.eachOf, identity, _findGetResult); + async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); + async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); + + async.sortBy = function (arr, iterator, callback) { + async.map(arr, function (x, callback) { + iterator(x, function (err, criteria) { + if (err) { + callback(err); + } + else { + callback(null, {value: x, criteria: criteria}); + } + }); + }, function (err, results) { + if (err) { + return callback(err); + } + else { + callback(null, _map(results.sort(comparator), function (x) { + return x.value; + })); + } + + }); + + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } + }; + + async.auto = function (tasks, concurrency, callback) { + if (typeof arguments[1] === 'function') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = _once(callback || noop); + var keys = _keys(tasks); + var remainingTasks = keys.length; + if (!remainingTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = remainingTasks; + } + + var results = {}; + var runningTasks = 0; + + var hasError = false; + + var listeners = []; + function addListener(fn) { + listeners.unshift(fn); + } + function removeListener(fn) { + var idx = _indexOf(listeners, fn); + if (idx >= 0) listeners.splice(idx, 1); + } + function taskComplete() { + remainingTasks--; + _arrayEach(listeners.slice(0), function (fn) { + fn(); + }); + } + + addListener(function () { + if (!remainingTasks) { + callback(null, results); + } + }); + + _arrayEach(keys, function (k) { + if (hasError) return; + var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; + var taskCallback = _restParam(function(err, args) { + runningTasks--; + if (args.length <= 1) { + args = args[0]; + } + if (err) { + var safeResults = {}; + _forEachOf(results, function(val, rkey) { + safeResults[rkey] = val; + }); + safeResults[k] = args; + hasError = true; + + callback(err, safeResults); + } + else { + results[k] = args; + async.setImmediate(taskComplete); + } + }); + var requires = task.slice(0, task.length - 1); + // prevent dead-locks + var len = requires.length; + var dep; + while (len--) { + if (!(dep = tasks[requires[len]])) { + throw new Error('Has nonexistent dependency in ' + requires.join(', ')); + } + if (_isArray(dep) && _indexOf(dep, k) >= 0) { + throw new Error('Has cyclic dependencies'); + } + } + function ready() { + return runningTasks < concurrency && _reduce(requires, function (a, x) { + return (a && results.hasOwnProperty(x)); + }, true) && !results.hasOwnProperty(k); + } + if (ready()) { + runningTasks++; + task[task.length - 1](taskCallback, results); + } + else { + addListener(listener); + } + function listener() { + if (ready()) { + runningTasks++; + removeListener(listener); + task[task.length - 1](taskCallback, results); + } + } + }); + }; + + + + async.retry = function(times, task, callback) { + var DEFAULT_TIMES = 5; + var DEFAULT_INTERVAL = 0; + + var attempts = []; + + var opts = { + times: DEFAULT_TIMES, + interval: DEFAULT_INTERVAL + }; + + function parseTimes(acc, t){ + if(typeof t === 'number'){ + acc.times = parseInt(t, 10) || DEFAULT_TIMES; + } else if(typeof t === 'object'){ + acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; + acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; + } else { + throw new Error('Unsupported argument type for \'times\': ' + typeof t); + } + } + + var length = arguments.length; + if (length < 1 || length > 3) { + throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); + } else if (length <= 2 && typeof times === 'function') { + callback = task; + task = times; + } + if (typeof times !== 'function') { + parseTimes(opts, times); + } + opts.callback = callback; + opts.task = task; + + function wrappedTask(wrappedCallback, wrappedResults) { + function retryAttempt(task, finalAttempt) { + return function(seriesCallback) { + task(function(err, result){ + seriesCallback(!err || finalAttempt, {err: err, result: result}); + }, wrappedResults); + }; + } + + function retryInterval(interval){ + return function(seriesCallback){ + setTimeout(function(){ + seriesCallback(null); + }, interval); + }; + } + + while (opts.times) { + + var finalAttempt = !(opts.times-=1); + attempts.push(retryAttempt(opts.task, finalAttempt)); + if(!finalAttempt && opts.interval > 0){ + attempts.push(retryInterval(opts.interval)); + } + } + + async.series(attempts, function(done, data){ + data = data[data.length - 1]; + (wrappedCallback || opts.callback)(data.err, data.result); + }); + } + + // If a callback is passed, run this as a controll flow + return opts.callback ? wrappedTask() : wrappedTask; + }; + + async.waterfall = function (tasks, callback) { + callback = _once(callback || noop); + if (!_isArray(tasks)) { + var err = new Error('First argument to waterfall must be an array of functions'); + return callback(err); + } + if (!tasks.length) { + return callback(); + } + function wrapIterator(iterator) { + return _restParam(function (err, args) { + if (err) { + callback.apply(null, [err].concat(args)); + } + else { + var next = iterator.next(); + if (next) { + args.push(wrapIterator(next)); + } + else { + args.push(callback); + } + ensureAsync(iterator).apply(null, args); + } + }); + } + wrapIterator(async.iterator(tasks))(); + }; + + function _parallel(eachfn, tasks, callback) { + callback = callback || noop; + var results = _isArrayLike(tasks) ? [] : {}; + + eachfn(tasks, function (task, key, callback) { + task(_restParam(function (err, args) { + if (args.length <= 1) { + args = args[0]; + } + results[key] = args; + callback(err); + })); + }, function (err) { + callback(err, results); + }); + } + + async.parallel = function (tasks, callback) { + _parallel(async.eachOf, tasks, callback); + }; + + async.parallelLimit = function(tasks, limit, callback) { + _parallel(_eachOfLimit(limit), tasks, callback); + }; + + async.series = function(tasks, callback) { + _parallel(async.eachOfSeries, tasks, callback); + }; + + async.iterator = function (tasks) { + function makeCallback(index) { + function fn() { + if (tasks.length) { + tasks[index].apply(null, arguments); + } + return fn.next(); + } + fn.next = function () { + return (index < tasks.length - 1) ? makeCallback(index + 1): null; + }; + return fn; + } + return makeCallback(0); + }; + + async.apply = _restParam(function (fn, args) { + return _restParam(function (callArgs) { + return fn.apply( + null, args.concat(callArgs) + ); + }); + }); + + function _concat(eachfn, arr, fn, callback) { + var result = []; + eachfn(arr, function (x, index, cb) { + fn(x, function (err, y) { + result = result.concat(y || []); + cb(err); + }); + }, function (err) { + callback(err, result); + }); + } + async.concat = doParallel(_concat); + async.concatSeries = doSeries(_concat); + + async.whilst = function (test, iterator, callback) { + callback = callback || noop; + if (test()) { + var next = _restParam(function(err, args) { + if (err) { + callback(err); + } else if (test.apply(this, args)) { + iterator(next); + } else { + callback.apply(null, [null].concat(args)); + } + }); + iterator(next); + } else { + callback(null); + } + }; + + async.doWhilst = function (iterator, test, callback) { + var calls = 0; + return async.whilst(function() { + return ++calls <= 1 || test.apply(this, arguments); + }, iterator, callback); + }; + + async.until = function (test, iterator, callback) { + return async.whilst(function() { + return !test.apply(this, arguments); + }, iterator, callback); + }; + + async.doUntil = function (iterator, test, callback) { + return async.doWhilst(iterator, function() { + return !test.apply(this, arguments); + }, callback); + }; + + async.during = function (test, iterator, callback) { + callback = callback || noop; + + var next = _restParam(function(err, args) { + if (err) { + callback(err); + } else { + args.push(check); + test.apply(this, args); + } + }); + + var check = function(err, truth) { + if (err) { + callback(err); + } else if (truth) { + iterator(next); + } else { + callback(null); + } + }; + + test(check); + }; + + async.doDuring = function (iterator, test, callback) { + var calls = 0; + async.during(function(next) { + if (calls++ < 1) { + next(null, true); + } else { + test.apply(this, arguments); + } + }, iterator, callback); + }; + + function _queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + function _insert(q, data, pos, callback) { + if (callback != null && typeof callback !== "function") { + throw new Error("task callback must be a function"); + } + q.started = true; + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + q.drain(); + }); + } + _arrayEach(data, function(task) { + var item = { + data: task, + callback: callback || noop + }; + + if (pos) { + q.tasks.unshift(item); + } else { + q.tasks.push(item); + } + + if (q.tasks.length === q.concurrency) { + q.saturated(); + } + }); + async.setImmediate(q.process); + } + function _next(q, tasks) { + return function(){ + workers -= 1; + + var removed = false; + var args = arguments; + _arrayEach(tasks, function (task) { + _arrayEach(workersList, function (worker, index) { + if (worker === task && !removed) { + workersList.splice(index, 1); + removed = true; + } + }); + + task.callback.apply(task, args); + }); + if (q.tasks.length + workers === 0) { + q.drain(); + } + q.process(); + }; + } + + var workers = 0; + var workersList = []; + var q = { + tasks: [], + concurrency: concurrency, + payload: payload, + saturated: noop, + empty: noop, + drain: noop, + started: false, + paused: false, + push: function (data, callback) { + _insert(q, data, false, callback); + }, + kill: function () { + q.drain = noop; + q.tasks = []; + }, + unshift: function (data, callback) { + _insert(q, data, true, callback); + }, + process: function () { + while(!q.paused && workers < q.concurrency && q.tasks.length){ + + var tasks = q.payload ? + q.tasks.splice(0, q.payload) : + q.tasks.splice(0, q.tasks.length); + + var data = _map(tasks, function (task) { + return task.data; + }); + + if (q.tasks.length === 0) { + q.empty(); + } + workers += 1; + workersList.push(tasks[0]); + var cb = only_once(_next(q, tasks)); + worker(data, cb); + } + }, + length: function () { + return q.tasks.length; + }, + running: function () { + return workers; + }, + workersList: function () { + return workersList; + }, + idle: function() { + return q.tasks.length + workers === 0; + }, + pause: function () { + q.paused = true; + }, + resume: function () { + if (q.paused === false) { return; } + q.paused = false; + var resumeCount = Math.min(q.concurrency, q.tasks.length); + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= resumeCount; w++) { + async.setImmediate(q.process); + } + } + }; + return q; + } + + async.queue = function (worker, concurrency) { + var q = _queue(function (items, cb) { + worker(items[0], cb); + }, concurrency, 1); + + return q; + }; + + async.priorityQueue = function (worker, concurrency) { + + function _compareTasks(a, b){ + return a.priority - b.priority; + } + + function _binarySearch(sequence, item, compare) { + var beg = -1, + end = sequence.length - 1; + while (beg < end) { + var mid = beg + ((end - beg + 1) >>> 1); + if (compare(item, sequence[mid]) >= 0) { + beg = mid; + } else { + end = mid - 1; + } + } + return beg; + } + + function _insert(q, data, priority, callback) { + if (callback != null && typeof callback !== "function") { + throw new Error("task callback must be a function"); + } + q.started = true; + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + q.drain(); + }); + } + _arrayEach(data, function(task) { + var item = { + data: task, + priority: priority, + callback: typeof callback === 'function' ? callback : noop + }; + + q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); + + if (q.tasks.length === q.concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + // Start with a normal queue + var q = async.queue(worker, concurrency); + + // Override push to accept second parameter representing priority + q.push = function (data, priority, callback) { + _insert(q, data, priority, callback); + }; + + // Remove unshift function + delete q.unshift; + + return q; + }; + + async.cargo = function (worker, payload) { + return _queue(worker, 1, payload); + }; + + function _console_fn(name) { + return _restParam(function (fn, args) { + fn.apply(null, args.concat([_restParam(function (err, args) { + if (typeof console === 'object') { + if (err) { + if (console.error) { + console.error(err); + } + } + else if (console[name]) { + _arrayEach(args, function (x) { + console[name](x); + }); + } + } + })])); + }); + } + async.log = _console_fn('log'); + async.dir = _console_fn('dir'); + /*async.info = _console_fn('info'); + async.warn = _console_fn('warn'); + async.error = _console_fn('error');*/ + + async.memoize = function (fn, hasher) { + var memo = {}; + var queues = {}; + var has = Object.prototype.hasOwnProperty; + hasher = hasher || identity; + var memoized = _restParam(function memoized(args) { + var callback = args.pop(); + var key = hasher.apply(null, args); + if (has.call(memo, key)) { + async.setImmediate(function () { + callback.apply(null, memo[key]); + }); + } + else if (has.call(queues, key)) { + queues[key].push(callback); + } + else { + queues[key] = [callback]; + fn.apply(null, args.concat([_restParam(function (args) { + memo[key] = args; + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(null, args); + } + })])); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + }; + + async.unmemoize = function (fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; + }; + + function _times(mapper) { + return function (count, iterator, callback) { + mapper(_range(count), iterator, callback); + }; + } + + async.times = _times(async.map); + async.timesSeries = _times(async.mapSeries); + async.timesLimit = function (count, limit, iterator, callback) { + return async.mapLimit(_range(count), limit, iterator, callback); + }; + + async.seq = function (/* functions... */) { + var fns = arguments; + return _restParam(function (args) { + var that = this; + + var callback = args[args.length - 1]; + if (typeof callback == 'function') { + args.pop(); + } else { + callback = noop; + } + + async.reduce(fns, args, function (newargs, fn, cb) { + fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { + cb(err, nextargs); + })])); + }, + function (err, results) { + callback.apply(that, [err].concat(results)); + }); + }); + }; + + async.compose = function (/* functions... */) { + return async.seq.apply(null, Array.prototype.reverse.call(arguments)); + }; + + + function _applyEach(eachfn) { + return _restParam(function(fns, args) { + var go = _restParam(function(args) { + var that = this; + var callback = args.pop(); + return eachfn(fns, function (fn, _, cb) { + fn.apply(that, args.concat([cb])); + }, + callback); + }); + if (args.length) { + return go.apply(this, args); + } + else { + return go; + } + }); + } + + async.applyEach = _applyEach(async.eachOf); + async.applyEachSeries = _applyEach(async.eachOfSeries); + + + async.forever = function (fn, callback) { + var done = only_once(callback || noop); + var task = ensureAsync(fn); + function next(err) { + if (err) { + return done(err); + } + task(next); + } + next(); + }; + + function ensureAsync(fn) { + return _restParam(function (args) { + var callback = args.pop(); + args.push(function () { + var innerArgs = arguments; + if (sync) { + async.setImmediate(function () { + callback.apply(null, innerArgs); + }); + } else { + callback.apply(null, innerArgs); + } + }); + var sync = true; + fn.apply(this, args); + sync = false; + }); + } + + async.ensureAsync = ensureAsync; + + async.constant = _restParam(function(values) { + var args = [null].concat(values); + return function (callback) { + return callback.apply(this, args); + }; + }); + + async.wrapSync = + async.asyncify = function asyncify(func) { + return _restParam(function (args) { + var callback = args.pop(); + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (_isObject(result) && typeof result.then === "function") { + result.then(function(value) { + callback(null, value); + })["catch"](function(err) { + callback(err.message ? err : new Error(err)); + }); + } else { + callback(null, result); + } + }); + }; + + // Node.js + if (typeof module === 'object' && module.exports) { + module.exports = async; + } + // AMD / RequireJS + else if (typeof define === 'function' && define.amd) { + define([], function () { + return async; + }); + } + // included directly via + +``` + +## Documentation + +### Collections + +* [`each`](#each) +* [`eachSeries`](#eachSeries) +* [`eachLimit`](#eachLimit) +* [`forEachOf`](#forEachOf) +* [`forEachOfSeries`](#forEachOfSeries) +* [`forEachOfLimit`](#forEachOfLimit) +* [`map`](#map) +* [`mapSeries`](#mapSeries) +* [`mapLimit`](#mapLimit) +* [`filter`](#filter) +* [`filterSeries`](#filterSeries) +* [`reject`](#reject) +* [`rejectSeries`](#rejectSeries) +* [`reduce`](#reduce) +* [`reduceRight`](#reduceRight) +* [`detect`](#detect) +* [`detectSeries`](#detectSeries) +* [`sortBy`](#sortBy) +* [`some`](#some) +* [`every`](#every) +* [`concat`](#concat) +* [`concatSeries`](#concatSeries) + +### Control Flow + +* [`series`](#seriestasks-callback) +* [`parallel`](#parallel) +* [`parallelLimit`](#parallellimittasks-limit-callback) +* [`whilst`](#whilst) +* [`doWhilst`](#doWhilst) +* [`until`](#until) +* [`doUntil`](#doUntil) +* [`forever`](#forever) +* [`waterfall`](#waterfall) +* [`compose`](#compose) +* [`seq`](#seq) +* [`applyEach`](#applyEach) +* [`applyEachSeries`](#applyEachSeries) +* [`queue`](#queue) +* [`priorityQueue`](#priorityQueue) +* [`cargo`](#cargo) +* [`auto`](#auto) +* [`retry`](#retry) +* [`iterator`](#iterator) +* [`apply`](#apply) +* [`nextTick`](#nextTick) +* [`times`](#times) +* [`timesSeries`](#timesSeries) + +### Utils + +* [`memoize`](#memoize) +* [`unmemoize`](#unmemoize) +* [`log`](#log) +* [`dir`](#dir) +* [`noConflict`](#noConflict) + + +## Collections + + + +### each(arr, iterator, callback) + +Applies the function `iterator` to each item in `arr`, in parallel. +The `iterator` is called with an item from the list, and a callback for when it +has finished. If the `iterator` passes an error to its `callback`, the main +`callback` (for the `each` function) is immediately called with the error. + +Note, that since this function applies `iterator` to each item in parallel, +there is no guarantee that the iterator functions will complete in order. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err)` which must be called once it has + completed. If no error has occurred, the `callback` should be run without + arguments or with an explicit `null` argument. The array index is not passed + to the iterator. If you need the index, use [`forEachOf`](#forEachOf). +* `callback(err)` - A callback which is called when all `iterator` functions + have finished, or an error occurs. + +__Examples__ + + +```js +// assuming openFiles is an array of file names and saveFile is a function +// to save the modified contents of that file: + +async.each(openFiles, saveFile, function(err){ + // if any of the saves produced an error, err would equal that error +}); +``` + +```js +// assuming openFiles is an array of file names + +async.each(openFiles, function(file, callback) { + + // Perform operation on file here. + console.log('Processing file ' + file); + + if( file.length > 32 ) { + console.log('This file name is too long'); + callback('File name too long'); + } else { + // Do work to process file here + console.log('File processed'); + callback(); + } +}, function(err){ + // if any of the file processing produced an error, err would equal that error + if( err ) { + // One of the iterations produced an error. + // All processing will now stop. + console.log('A file failed to process'); + } else { + console.log('All files have been processed successfully'); + } +}); +``` + +--------------------------------------- + + + +### eachSeries(arr, iterator, callback) + +The same as [`each`](#each), only `iterator` is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +This means the `iterator` functions will complete in order. + + +--------------------------------------- + + + +### eachLimit(arr, limit, iterator, callback) + +The same as [`each`](#each), only no more than `limit` `iterator`s will be simultaneously +running at any time. + +Note that the items in `arr` are not processed in batches, so there is no guarantee that +the first `limit` `iterator` functions will complete before any others are started. + +__Arguments__ + +* `arr` - An array to iterate over. +* `limit` - The maximum number of `iterator`s to run at any time. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err)` which must be called once it has + completed. If no error has occurred, the callback should be run without + arguments or with an explicit `null` argument. +* `callback(err)` - A callback which is called when all `iterator` functions + have finished, or an error occurs. + +__Example__ + +```js +// Assume documents is an array of JSON objects and requestApi is a +// function that interacts with a rate-limited REST api. + +async.eachLimit(documents, 20, requestApi, function(err){ + // if any of the saves produced an error, err would equal that error +}); +``` + +--------------------------------------- + + + + +### forEachOf(obj, iterator, callback) + +Like `each`, except that it iterates over objects, and passes the key as the second argument to the iterator. + +__Arguments__ + +* `obj` - An object or array to iterate over. +* `iterator(item, key, callback)` - A function to apply to each item in `obj`. +The `key` is the item's key, or index in the case of an array. The iterator is +passed a `callback(err)` which must be called once it has completed. If no +error has occurred, the callback should be run without arguments or with an +explicit `null` argument. +* `callback(err)` - A callback which is called when all `iterator` functions have finished, or an error occurs. + +__Example__ + +```js +var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; +var configs = {}; + +async.forEachOf(obj, function (value, key, callback) { + fs.readFile(__dirname + value, "utf8", function (err, data) { + if (err) return callback(err); + try { + configs[key] = JSON.parse(data); + } catch (e) { + return callback(e); + } + callback(); + }) +}, function (err) { + if (err) console.error(err.message); + // configs is now a map of JSON data + doSomethingWith(configs); +}) +``` + +--------------------------------------- + + + + +### forEachOfSeries(obj, iterator, callback) + +Like [`forEachOf`](#forEachOf), except only one `iterator` is run at a time. The order of execution is not guaranteed for objects, but it will be guaranteed for arrays. + +--------------------------------------- + + + + +### forEachOfLimit(obj, limit, iterator, callback) + +Like [`forEachOf`](#forEachOf), except the number of `iterator`s running at a given time is controlled by `limit`. + + +--------------------------------------- + + +### map(arr, iterator, callback) + +Produces a new array of values by mapping each value in `arr` through +the `iterator` function. The `iterator` is called with an item from `arr` and a +callback for when it has finished processing. Each of these callback takes 2 arguments: +an `error`, and the transformed item from `arr`. If `iterator` passes an error to its +callback, the main `callback` (for the `map` function) is immediately called with the error. + +Note, that since this function applies the `iterator` to each item in parallel, +there is no guarantee that the `iterator` functions will complete in order. +However, the results array will be in the same order as the original `arr`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, transformed)` which must be called once + it has completed with an error (which can be `null`) and a transformed item. +* `callback(err, results)` - A callback which is called when all `iterator` + functions have finished, or an error occurs. Results is an array of the + transformed items from the `arr`. + +__Example__ + +```js +async.map(['file1','file2','file3'], fs.stat, function(err, results){ + // results is now an array of stats for each file +}); +``` + +--------------------------------------- + + +### mapSeries(arr, iterator, callback) + +The same as [`map`](#map), only the `iterator` is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +The results array will be in the same order as the original. + + +--------------------------------------- + + +### mapLimit(arr, limit, iterator, callback) + +The same as [`map`](#map), only no more than `limit` `iterator`s will be simultaneously +running at any time. + +Note that the items are not processed in batches, so there is no guarantee that +the first `limit` `iterator` functions will complete before any others are started. + +__Arguments__ + +* `arr` - An array to iterate over. +* `limit` - The maximum number of `iterator`s to run at any time. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, transformed)` which must be called once + it has completed with an error (which can be `null`) and a transformed item. +* `callback(err, results)` - A callback which is called when all `iterator` + calls have finished, or an error occurs. The result is an array of the + transformed items from the original `arr`. + +__Example__ + +```js +async.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){ + // results is now an array of stats for each file +}); +``` + +--------------------------------------- + + + +### filter(arr, iterator, callback) + +__Alias:__ `select` + +Returns a new array of all the values in `arr` which pass an async truth test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. This operation is +performed in parallel, but the results array will be in the same order as the +original. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The `iterator` is passed a `callback(truthValue)`, which must be called with a + boolean argument once it has completed. +* `callback(results)` - A callback which is called after all the `iterator` + functions have finished. + +__Example__ + +```js +async.filter(['file1','file2','file3'], fs.exists, function(results){ + // results now equals an array of the existing files +}); +``` + +--------------------------------------- + + + +### filterSeries(arr, iterator, callback) + +__Alias:__ `selectSeries` + +The same as [`filter`](#filter) only the `iterator` is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +The results array will be in the same order as the original. + +--------------------------------------- + + +### reject(arr, iterator, callback) + +The opposite of [`filter`](#filter). Removes values that pass an `async` truth test. + +--------------------------------------- + + +### rejectSeries(arr, iterator, callback) + +The same as [`reject`](#reject), only the `iterator` is applied to each item in `arr` +in series. + + +--------------------------------------- + + +### reduce(arr, memo, iterator, callback) + +__Aliases:__ `inject`, `foldl` + +Reduces `arr` into a single value using an async `iterator` to return +each successive step. `memo` is the initial state of the reduction. +This function only operates in series. + +For performance reasons, it may make sense to split a call to this function into +a parallel map, and then use the normal `Array.prototype.reduce` on the results. +This function is for situations where each step in the reduction needs to be async; +if you can get the data before reducing it, then it's probably a good idea to do so. + +__Arguments__ + +* `arr` - An array to iterate over. +* `memo` - The initial state of the reduction. +* `iterator(memo, item, callback)` - A function applied to each item in the + array to produce the next step in the reduction. The `iterator` is passed a + `callback(err, reduction)` which accepts an optional error as its first + argument, and the state of the reduction as the second. If an error is + passed to the callback, the reduction is stopped and the main `callback` is + immediately called with the error. +* `callback(err, result)` - A callback which is called after all the `iterator` + functions have finished. Result is the reduced value. + +__Example__ + +```js +async.reduce([1,2,3], 0, function(memo, item, callback){ + // pointless async: + process.nextTick(function(){ + callback(null, memo + item) + }); +}, function(err, result){ + // result is now equal to the last value of memo, which is 6 +}); +``` + +--------------------------------------- + + +### reduceRight(arr, memo, iterator, callback) + +__Alias:__ `foldr` + +Same as [`reduce`](#reduce), only operates on `arr` in reverse order. + + +--------------------------------------- + + +### detect(arr, iterator, callback) + +Returns the first value in `arr` that passes an async truth test. The +`iterator` is applied in parallel, meaning the first iterator to return `true` will +fire the detect `callback` with that result. That means the result might not be +the first item in the original `arr` (in terms of order) that passes the test. + +If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries). + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The iterator is passed a `callback(truthValue)` which must be called with a + boolean argument once it has completed. +* `callback(result)` - A callback which is called as soon as any iterator returns + `true`, or after all the `iterator` functions have finished. Result will be + the first item in the array that passes the truth test (iterator) or the + value `undefined` if none passed. + +__Example__ + +```js +async.detect(['file1','file2','file3'], fs.exists, function(result){ + // result now equals the first file in the list that exists +}); +``` + +--------------------------------------- + + +### detectSeries(arr, iterator, callback) + +The same as [`detect`](#detect), only the `iterator` is applied to each item in `arr` +in series. This means the result is always the first in the original `arr` (in +terms of array order) that passes the truth test. + + +--------------------------------------- + + +### sortBy(arr, iterator, callback) + +Sorts a list by the results of running each `arr` value through an async `iterator`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, sortValue)` which must be called once it + has completed with an error (which can be `null`) and a value to use as the sort + criteria. +* `callback(err, results)` - A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is the items from + the original `arr` sorted by the values returned by the `iterator` calls. + +__Example__ + +```js +async.sortBy(['file1','file2','file3'], function(file, callback){ + fs.stat(file, function(err, stats){ + callback(err, stats.mtime); + }); +}, function(err, results){ + // results is now the original array of files sorted by + // modified date +}); +``` + +__Sort Order__ + +By modifying the callback parameter the sorting order can be influenced: + +```js +//ascending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x); +}, function(err,result){ + //result callback +} ); + +//descending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x*-1); //<- x*-1 instead of x, turns the order around +}, function(err,result){ + //result callback +} ); +``` + +--------------------------------------- + + +### some(arr, iterator, callback) + +__Alias:__ `any` + +Returns `true` if at least one element in the `arr` satisfies an async test. +_The callback for each iterator call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. Once any iterator +call returns `true`, the main `callback` is immediately called. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a callback(truthValue) which must be + called with a boolean argument once it has completed. +* `callback(result)` - A callback which is called as soon as any iterator returns + `true`, or after all the iterator functions have finished. Result will be + either `true` or `false` depending on the values of the async tests. + +__Example__ + +```js +async.some(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then at least one of the files exists +}); +``` + +--------------------------------------- + + +### every(arr, iterator, callback) + +__Alias:__ `all` + +Returns `true` if every element in `arr` satisfies an async test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a callback(truthValue) which must be + called with a boolean argument once it has completed. +* `callback(result)` - A callback which is called after all the `iterator` + functions have finished. Result will be either `true` or `false` depending on + the values of the async tests. + +__Example__ + +```js +async.every(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then every file exists +}); +``` + +--------------------------------------- + + +### concat(arr, iterator, callback) + +Applies `iterator` to each item in `arr`, concatenating the results. Returns the +concatenated list. The `iterator`s are called in parallel, and the results are +concatenated as they return. There is no guarantee that the results array will +be returned in the original order of `arr` passed to the `iterator` function. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, results)` which must be called once it + has completed with an error (which can be `null`) and an array of results. +* `callback(err, results)` - A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is an array containing + the concatenated results of the `iterator` function. + +__Example__ + +```js +async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){ + // files is now a list of filenames that exist in the 3 directories +}); +``` + +--------------------------------------- + + +### concatSeries(arr, iterator, callback) + +Same as [`concat`](#concat), but executes in series instead of parallel. + + +## Control Flow + + +### series(tasks, [callback]) + +Run the functions in the `tasks` array in series, each one running once the previous +function has completed. If any functions in the series pass an error to its +callback, no more functions are run, and `callback` is immediately called with the value of the error. +Otherwise, `callback` receives an array of results when `tasks` have completed. + +It is also possible to use an object instead of an array. Each property will be +run as a function, and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`series`](#series). + +**Note** that while many implementations preserve the order of object properties, the +[ECMAScript Language Specifcation](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) +explicitly states that + +> The mechanics and order of enumerating the properties is not specified. + +So if you rely on the order in which your series of functions are executed, and want +this to work on all platforms, consider using an array. + +__Arguments__ + +* `tasks` - An array or object containing functions to run, each function is passed + a `callback(err, result)` it must call on completion with an error `err` (which can + be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the `task` callbacks. + +__Example__ + +```js +async.series([ + function(callback){ + // do some stuff ... + callback(null, 'one'); + }, + function(callback){ + // do some more stuff ... + callback(null, 'two'); + } +], +// optional callback +function(err, results){ + // results is now equal to ['one', 'two'] +}); + + +// an example using an object instead of an array +async.series({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equal to: {one: 1, two: 2} +}); +``` + +--------------------------------------- + + +### parallel(tasks, [callback]) + +Run the `tasks` array of functions in parallel, without waiting until the previous +function has completed. If any of the functions pass an error to its +callback, the main `callback` is immediately called with the value of the error. +Once the `tasks` have completed, the results are passed to the final `callback` as an +array. + +It is also possible to use an object instead of an array. Each property will be +run as a function and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`parallel`](#parallel). + + +__Arguments__ + +* `tasks` - An array or object containing functions to run. Each function is passed + a `callback(err, result)` which it must call on completion with an error `err` + (which can be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the task callbacks. + +__Example__ + +```js +async.parallel([ + function(callback){ + setTimeout(function(){ + callback(null, 'one'); + }, 200); + }, + function(callback){ + setTimeout(function(){ + callback(null, 'two'); + }, 100); + } +], +// optional callback +function(err, results){ + // the results array will equal ['one','two'] even though + // the second function had a shorter timeout. +}); + + +// an example using an object instead of an array +async.parallel({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equals to: {one: 1, two: 2} +}); +``` + +--------------------------------------- + + +### parallelLimit(tasks, limit, [callback]) + +The same as [`parallel`](#parallel), only `tasks` are executed in parallel +with a maximum of `limit` tasks executing at any time. + +Note that the `tasks` are not executed in batches, so there is no guarantee that +the first `limit` tasks will complete before any others are started. + +__Arguments__ + +* `tasks` - An array or object containing functions to run, each function is passed + a `callback(err, result)` it must call on completion with an error `err` (which can + be `null`) and an optional `result` value. +* `limit` - The maximum number of `tasks` to run at any time. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the `task` callbacks. + +--------------------------------------- + + +### whilst(test, fn, callback) + +Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped, +or an error occurs. + +__Arguments__ + +* `test()` - synchronous truth test to perform before each execution of `fn`. +* `fn(callback)` - A function which is called each time `test` passes. The function is + passed a `callback(err)`, which must be called once it has completed with an + optional `err` argument. +* `callback(err)` - A callback which is called after the test fails and repeated + execution of `fn` has stopped. + +__Example__ + +```js +var count = 0; + +async.whilst( + function () { return count < 5; }, + function (callback) { + count++; + setTimeout(callback, 1000); + }, + function (err) { + // 5 seconds have passed + } +); +``` + +--------------------------------------- + + +### doWhilst(fn, test, callback) + +The post-check version of [`whilst`](#whilst). To reflect the difference in +the order of operations, the arguments `test` and `fn` are switched. + +`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + +--------------------------------------- + + +### until(test, fn, callback) + +Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped, +or an error occurs. + +The inverse of [`whilst`](#whilst). + +--------------------------------------- + + +### doUntil(fn, test, callback) + +Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`. + +--------------------------------------- + + +### forever(fn, errback) + +Calls the asynchronous function `fn` with a callback parameter that allows it to +call itself again, in series, indefinitely. + +If an error is passed to the callback then `errback` is called with the +error, and execution stops, otherwise it will never be called. + +```js +async.forever( + function(next) { + // next is suitable for passing to things that need a callback(err [, whatever]); + // it will result in this function being called again. + }, + function(err) { + // if next is called with a value in its first parameter, it will appear + // in here as 'err', and execution will stop. + } +); +``` + +--------------------------------------- + + +### waterfall(tasks, [callback]) + +Runs the `tasks` array of functions in series, each passing their results to the next in +the array. However, if any of the `tasks` pass an error to their own callback, the +next function is not executed, and the main `callback` is immediately called with +the error. + +__Arguments__ + +* `tasks` - An array of functions to run, each function is passed a + `callback(err, result1, result2, ...)` it must call on completion. The first + argument is an error (which can be `null`) and any further arguments will be + passed as arguments in order to the next task. +* `callback(err, [results])` - An optional callback to run once all the functions + have completed. This will be passed the results of the last task's callback. + + + +__Example__ + +```js +async.waterfall([ + function(callback) { + callback(null, 'one', 'two'); + }, + function(arg1, arg2, callback) { + // arg1 now equals 'one' and arg2 now equals 'two' + callback(null, 'three'); + }, + function(arg1, callback) { + // arg1 now equals 'three' + callback(null, 'done'); + } +], function (err, result) { + // result now equals 'done' +}); +``` + +--------------------------------------- + +### compose(fn1, fn2...) + +Creates a function which is a composition of the passed asynchronous +functions. Each function consumes the return value of the function that +follows. Composing functions `f()`, `g()`, and `h()` would produce the result of +`f(g(h()))`, only this version uses callbacks to obtain the return values. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* `functions...` - the asynchronous functions to compose + + +__Example__ + +```js +function add1(n, callback) { + setTimeout(function () { + callback(null, n + 1); + }, 10); +} + +function mul3(n, callback) { + setTimeout(function () { + callback(null, n * 3); + }, 10); +} + +var add1mul3 = async.compose(mul3, add1); + +add1mul3(4, function (err, result) { + // result now equals 15 +}); +``` + +--------------------------------------- + +### seq(fn1, fn2...) + +Version of the compose function that is more natural to read. +Each function consumes the return value of the previous function. +It is the equivalent of [`compose`](#compose) with the arguments reversed. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* functions... - the asynchronous functions to compose + + +__Example__ + +```js +// Requires lodash (or underscore), express3 and dresende's orm2. +// Part of an app, that fetches cats of the logged user. +// This example uses `seq` function to avoid overnesting and error +// handling clutter. +app.get('/cats', function(request, response) { + var User = request.models.User; + async.seq( + _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + function(user, fn) { + user.getCats(fn); // 'getCats' has signature (callback(err, data)) + } + )(req.session.user_id, function (err, cats) { + if (err) { + console.error(err); + response.json({ status: 'error', message: err.message }); + } else { + response.json({ status: 'ok', message: 'Cats found', data: cats }); + } + }); +}); +``` + +--------------------------------------- + +### applyEach(fns, args..., callback) + +Applies the provided arguments to each function in the array, calling +`callback` after all functions have completed. If you only provide the first +argument, then it will return a function which lets you pass in the +arguments as if it were a single function call. + +__Arguments__ + +* `fns` - the asynchronous functions to all call with the same arguments +* `args...` - any number of separate arguments to pass to the function +* `callback` - the final argument should be the callback, called when all + functions have completed processing + + +__Example__ + +```js +async.applyEach([enableSearch, updateSchema], 'bucket', callback); + +// partial application example: +async.each( + buckets, + async.applyEach([enableSearch, updateSchema]), + callback +); +``` + +--------------------------------------- + + +### applyEachSeries(arr, args..., callback) + +The same as [`applyEach`](#applyEach) only the functions are applied in series. + +--------------------------------------- + + +### queue(worker, concurrency) + +Creates a `queue` object with the specified `concurrency`. Tasks added to the +`queue` are processed in parallel (up to the `concurrency` limit). If all +`worker`s are in progress, the task is queued until one becomes available. +Once a `worker` completes a `task`, that `task`'s callback is called. + +__Arguments__ + +* `worker(task, callback)` - An asynchronous function for processing a queued + task, which must call its `callback(err)` argument when finished, with an + optional `error` as an argument. +* `concurrency` - An `integer` for determining how many `worker` functions should be + run in parallel. + +__Queue objects__ + +The `queue` object returned by this function has the following properties and +methods: + +* `length()` - a function returning the number of items waiting to be processed. +* `started` - a function returning whether or not any items have been pushed and processed by the queue +* `running()` - a function returning the number of items currently being processed. +* `idle()` - a function returning false if there are items waiting or being processed, or true if not. +* `concurrency` - an integer for determining how many `worker` functions should be + run in parallel. This property can be changed after a `queue` is created to + alter the concurrency on-the-fly. +* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once + the `worker` has finished processing the task. Instead of a single task, a `tasks` array + can be submitted. The respective callback is used for every task in the list. +* `unshift(task, [callback])` - add a new task to the front of the `queue`. +* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit, + and further tasks will be queued. +* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`. +* `paused` - a boolean for determining whether the queue is in a paused state +* `pause()` - a function that pauses the processing of tasks until `resume()` is called. +* `resume()` - a function that resumes the processing of queued tasks when the queue is paused. +* `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle. + +__Example__ + +```js +// create a queue object with concurrency 2 + +var q = async.queue(function (task, callback) { + console.log('hello ' + task.name); + callback(); +}, 2); + + +// assign a callback +q.drain = function() { + console.log('all items have been processed'); +} + +// add some items to the queue + +q.push({name: 'foo'}, function (err) { + console.log('finished processing foo'); +}); +q.push({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); + +// add some items to the queue (batch-wise) + +q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) { + console.log('finished processing item'); +}); + +// add some items to the front of the queue + +q.unshift({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); +``` + + +--------------------------------------- + + +### priorityQueue(worker, concurrency) + +The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects: + +* `push(task, priority, [callback])` - `priority` should be a number. If an array of + `tasks` is given, all tasks will be assigned the same priority. +* The `unshift` method was removed. + +--------------------------------------- + + +### cargo(worker, [payload]) + +Creates a `cargo` object with the specified payload. Tasks added to the +cargo will be processed altogether (up to the `payload` limit). If the +`worker` is in progress, the task is queued until it becomes available. Once +the `worker` has completed some tasks, each callback of those tasks is called. +Check out [this animation](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) for how `cargo` and `queue` work. + +While [queue](#queue) passes only one task to one of a group of workers +at a time, cargo passes an array of tasks to a single worker, repeating +when the worker is finished. + +__Arguments__ + +* `worker(tasks, callback)` - An asynchronous function for processing an array of + queued tasks, which must call its `callback(err)` argument when finished, with + an optional `err` argument. +* `payload` - An optional `integer` for determining how many tasks should be + processed per round; if omitted, the default is unlimited. + +__Cargo objects__ + +The `cargo` object returned by this function has the following properties and +methods: + +* `length()` - A function returning the number of items waiting to be processed. +* `payload` - An `integer` for determining how many tasks should be + process per round. This property can be changed after a `cargo` is created to + alter the payload on-the-fly. +* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called + once the `worker` has finished processing the task. Instead of a single task, an array of `tasks` + can be submitted. The respective callback is used for every task in the list. +* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued. +* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`. + +__Example__ + +```js +// create a cargo object with payload 2 + +var cargo = async.cargo(function (tasks, callback) { + for(var i=0; i +### auto(tasks, [callback]) + +Determines the best order for running the functions in `tasks`, based on their +requirements. Each function can optionally depend on other functions being completed +first, and each function is run as soon as its requirements are satisfied. + +If any of the functions pass an error to their callback, it will not +complete (so any other functions depending on it will not run), and the main +`callback` is immediately called with the error. Functions also receive an +object containing the results of functions which have completed so far. + +Note, all functions are called with a `results` object as a second argument, +so it is unsafe to pass functions in the `tasks` object which cannot handle the +extra argument. + +For example, this snippet of code: + +```js +async.auto({ + readData: async.apply(fs.readFile, 'data.txt', 'utf-8') +}, callback); +``` + +will have the effect of calling `readFile` with the results object as the last +argument, which will fail: + +```js +fs.readFile('data.txt', 'utf-8', cb, {}); +``` + +Instead, wrap the call to `readFile` in a function which does not forward the +`results` object: + +```js +async.auto({ + readData: function(cb, results){ + fs.readFile('data.txt', 'utf-8', cb); + } +}, callback); +``` + +__Arguments__ + +* `tasks` - An object. Each of its properties is either a function or an array of + requirements, with the function itself the last item in the array. The object's key + of a property serves as the name of the task defined by that property, + i.e. can be used when specifying requirements for other tasks. + The function receives two arguments: (1) a `callback(err, result)` which must be + called when finished, passing an `error` (which can be `null`) and the result of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions. +* `callback(err, results)` - An optional callback which is called when all the + tasks have been completed. It receives the `err` argument if any `tasks` + pass an error to their callback. Results are always returned; however, if + an error occurs, no further `tasks` will be performed, and the results + object will only contain partial results. + + +__Example__ + +```js +async.auto({ + get_data: function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + make_folder: function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + }, + write_file: ['get_data', 'make_folder', function(callback, results){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + callback(null, 'filename'); + }], + email_link: ['write_file', function(callback, results){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + // results.write_file contains the filename returned by write_file. + callback(null, {'file':results.write_file, 'email':'user@example.com'}); + }] +}, function(err, results) { + console.log('err = ', err); + console.log('results = ', results); +}); +``` + +This is a fairly trivial example, but to do this using the basic parallel and +series functions would look like this: + +```js +async.parallel([ + function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + } +], +function(err, results){ + async.series([ + function(callback){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + results.push('filename'); + callback(null); + }, + function(callback){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + callback(null, {'file':results.pop(), 'email':'user@example.com'}); + } + ]); +}); +``` + +For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding +new tasks much easier (and the code more readable). + + +--------------------------------------- + + +### retry([times = 5], task, [callback]) + +Attempts to get a successful response from `task` no more than `times` times before +returning an error. If the task is successful, the `callback` will be passed the result +of the successful task. If all attempts fail, the callback will be passed the error and +result (if any) of the final attempt. + +__Arguments__ + +* `times` - An integer indicating how many times to attempt the `task` before giving up. Defaults to 5. +* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)` + which must be called when finished, passing `err` (which can be `null`) and the `result` of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions (if nested inside another control flow). +* `callback(err, results)` - An optional callback which is called when the + task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`. + +The [`retry`](#retry) function can be used as a stand-alone control flow by passing a +callback, as shown below: + +```js +async.retry(3, apiMethod, function(err, result) { + // do something with the result +}); +``` + +It can also be embeded within other control flow functions to retry individual methods +that are not as reliable, like this: + +```js +async.auto({ + users: api.getUsers.bind(api), + payments: async.retry(3, api.getPayments.bind(api)) +}, function(err, results) { + // do something with the results +}); +``` + + +--------------------------------------- + + +### iterator(tasks) + +Creates an iterator function which calls the next function in the `tasks` array, +returning a continuation to call the next one after that. It's also possible to +“peek” at the next iterator with `iterator.next()`. + +This function is used internally by the `async` module, but can be useful when +you want to manually control the flow of functions in series. + +__Arguments__ + +* `tasks` - An array of functions to run. + +__Example__ + +```js +var iterator = async.iterator([ + function(){ sys.p('one'); }, + function(){ sys.p('two'); }, + function(){ sys.p('three'); } +]); + +node> var iterator2 = iterator(); +'one' +node> var iterator3 = iterator2(); +'two' +node> iterator3(); +'three' +node> var nextfn = iterator2.next(); +node> nextfn(); +'three' +``` + +--------------------------------------- + + +### apply(function, arguments..) + +Creates a continuation function with some arguments already applied. + +Useful as a shorthand when combined with other control flow functions. Any arguments +passed to the returned function are added to the arguments originally passed +to apply. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to automatically apply when the + continuation is called. + +__Example__ + +```js +// using apply + +async.parallel([ + async.apply(fs.writeFile, 'testfile1', 'test1'), + async.apply(fs.writeFile, 'testfile2', 'test2'), +]); + + +// the same process without using apply + +async.parallel([ + function(callback){ + fs.writeFile('testfile1', 'test1', callback); + }, + function(callback){ + fs.writeFile('testfile2', 'test2', callback); + } +]); +``` + +It's possible to pass any number of additional arguments when calling the +continuation: + +```js +node> var fn = async.apply(sys.puts, 'one'); +node> fn('two', 'three'); +one +two +three +``` + +--------------------------------------- + + +### nextTick(callback), setImmediate(callback) + +Calls `callback` on a later loop around the event loop. In Node.js this just +calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)` +if available, otherwise `setTimeout(callback, 0)`, which means other higher priority +events may precede the execution of `callback`. + +This is used internally for browser-compatibility purposes. + +__Arguments__ + +* `callback` - The function to call on a later loop around the event loop. + +__Example__ + +```js +var call_order = []; +async.nextTick(function(){ + call_order.push('two'); + // call_order now equals ['one','two'] +}); +call_order.push('one') +``` + + +### times(n, callback) + +Calls the `callback` function `n` times, and accumulates results in the same manner +you would use with [`map`](#map). + +__Arguments__ + +* `n` - The number of times to run the function. +* `iterator` - The function to call `n` times. +* `callback` - see [`map`](#map) + +__Example__ + +```js +// Pretend this is some complicated async factory +var createUser = function(id, callback) { + callback(null, { + id: 'user' + id + }) +} +// generate 5 users +async.times(5, function(n, next){ + createUser(n, function(err, user) { + next(err, user) + }) +}, function(err, users) { + // we should now have 5 users +}); +``` + + +### timesSeries(n, callback) + +The same as [`times`](#times), only the iterator is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +The results array will be in the same order as the original. + + +## Utils + + +### memoize(fn, [hasher]) + +Caches the results of an `async` function. When creating a hash to store function +results against, the callback is omitted from the hash and an optional hash +function can be used. + +If no hash function is specified, the first argument is used as a hash key, which may work reasonably if it is a string or a data type that converts to a distinct string. Note that objects and arrays will not behave reasonably. Neither will cases where the other arguments are significant. In such cases, specify your own hash function. + +The cache of results is exposed as the `memo` property of the function returned +by `memoize`. + +__Arguments__ + +* `fn` - The function to proxy and cache results from. +* `hasher` - An optional function for generating a custom hash for storing + results. It has all the arguments applied to it apart from the callback, and + must be synchronous. + +__Example__ + +```js +var slow_fn = function (name, callback) { + // do something + callback(null, result); +}; +var fn = async.memoize(slow_fn); + +// fn can now be used as if it were slow_fn +fn('some name', function () { + // callback +}); +``` + + +### unmemoize(fn) + +Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized +form. Handy for testing. + +__Arguments__ + +* `fn` - the memoized function + + +### log(function, arguments) + +Logs the result of an `async` function to the `console`. Only works in Node.js or +in browsers that support `console.log` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.log` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, 'hello ' + name); + }, 1000); +}; +``` +```js +node> async.log(hello, 'world'); +'hello world' +``` + +--------------------------------------- + + +### dir(function, arguments) + +Logs the result of an `async` function to the `console` using `console.dir` to +display the properties of the resulting object. Only works in Node.js or +in browsers that support `console.dir` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.dir` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, {hello: name}); + }, 1000); +}; +``` +```js +node> async.dir(hello, 'world'); +{hello: 'world'} +``` + +--------------------------------------- + + +### noConflict() + +Changes the value of `async` back to its original value, returning a reference to the +`async` object. diff --git a/app/node_modules/winston/node_modules/async/bower.json b/app/node_modules/winston/node_modules/async/bower.json new file mode 100644 index 0000000..9e4156d --- /dev/null +++ b/app/node_modules/winston/node_modules/async/bower.json @@ -0,0 +1,40 @@ +{ + "name": "async", + "description": "Higher-order functions and common patterns for asynchronous code", + "version": "1.0.0", + "main": "lib/async.js", + "keywords": [ + "async", + "callback", + "utility", + "module" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/caolan/async.git" + }, + "devDependencies": { + "benchmark": "~1.0.0", + "jshint": "~2.7.0", + "lodash": ">=2.4.1", + "mkdirp": "~0.5.1", + "nodeunit": ">0.0.0", + "uglify-js": "1.2.x" + }, + "moduleType": [ + "amd", + "globals", + "node" + ], + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ], + "authors": [ + "Caolan McMahon" + ] +} \ No newline at end of file diff --git a/app/node_modules/winston/node_modules/async/component.json b/app/node_modules/winston/node_modules/async/component.json new file mode 100644 index 0000000..c876b0a --- /dev/null +++ b/app/node_modules/winston/node_modules/async/component.json @@ -0,0 +1,17 @@ +{ + "name": "async", + "description": "Higher-order functions and common patterns for asynchronous code", + "version": "1.0.0", + "keywords": [ + "async", + "callback", + "utility", + "module" + ], + "license": "MIT", + "main": "lib/async.js", + "repository": "caolan/async", + "scripts": [ + "lib/async.js" + ] +} \ No newline at end of file diff --git a/app/node_modules/winston/node_modules/async/lib/async.js b/app/node_modules/winston/node_modules/async/lib/async.js new file mode 100644 index 0000000..1e76ee8 --- /dev/null +++ b/app/node_modules/winston/node_modules/async/lib/async.js @@ -0,0 +1,1283 @@ +/*! + * async + * https://github.com/caolan/async + * + * Copyright 2010-2014 Caolan McMahon + * Released under the MIT license + */ +(function () { + + var async = {}; + var noop = function () {}; + + // global on the server, window in the browser + var root, previous_async; + + if (typeof window == 'object' && this === window) { + root = window; + } + else if (typeof global == 'object' && this === global) { + root = global; + } + else { + root = this; + } + + if (root != null) { + previous_async = root.async; + } + + async.noConflict = function () { + root.async = previous_async; + return async; + }; + + function only_once(fn) { + var called = false; + return function() { + if (called) throw new Error("Callback was already called."); + called = true; + fn.apply(root, arguments); + }; + } + + //// cross-browser compatiblity functions //// + + var _toString = Object.prototype.toString; + + var _isArray = Array.isArray || function (obj) { + return _toString.call(obj) === '[object Array]'; + }; + + var _each = function (arr, iterator) { + var index = -1, + length = arr.length; + + while (++index < length) { + iterator(arr[index], index, arr); + } + }; + + var _map = function (arr, iterator) { + var index = -1, + length = arr.length, + result = Array(length); + + while (++index < length) { + result[index] = iterator(arr[index], index, arr); + } + return result; + }; + + var _reduce = function (arr, iterator, memo) { + _each(arr, function (x, i, a) { + memo = iterator(memo, x, i, a); + }); + return memo; + }; + + var _forEachOf = function (object, iterator) { + _each(_keys(object), function (key) { + iterator(object[key], key); + }); + }; + + var _keys = Object.keys || function (obj) { + var keys = []; + for (var k in obj) { + if (obj.hasOwnProperty(k)) { + keys.push(k); + } + } + return keys; + }; + + var _baseSlice = function (arr, start) { + start = start || 0; + var index = -1; + var length = arr.length; + + if (start) { + length -= start; + length = length < 0 ? 0 : length; + } + var result = Array(length); + + while (++index < length) { + result[index] = arr[index + start]; + } + return result; + }; + + //// exported async module functions //// + + //// nextTick implementation with browser-compatible fallback //// + + // capture the global reference to guard against fakeTimer mocks + var _setImmediate; + if (typeof setImmediate === 'function') { + _setImmediate = setImmediate; + } + + if (typeof process === 'undefined' || !(process.nextTick)) { + if (_setImmediate) { + async.nextTick = function (fn) { + // not a direct alias for IE10 compatibility + _setImmediate(fn); + }; + async.setImmediate = async.nextTick; + } + else { + async.nextTick = function (fn) { + setTimeout(fn, 0); + }; + async.setImmediate = async.nextTick; + } + } + else { + async.nextTick = process.nextTick; + if (_setImmediate) { + async.setImmediate = function (fn) { + // not a direct alias for IE10 compatibility + _setImmediate(fn); + }; + } + else { + async.setImmediate = async.nextTick; + } + } + + async.each = function (arr, iterator, callback) { + callback = callback || noop; + if (!arr.length) { + return callback(); + } + var completed = 0; + _each(arr, function (x) { + iterator(x, only_once(done) ); + }); + function done(err) { + if (err) { + callback(err); + callback = noop; + } + else { + completed += 1; + if (completed >= arr.length) { + callback(); + } + } + } + }; + async.forEach = async.each; + + async.eachSeries = function (arr, iterator, callback) { + callback = callback || noop; + if (!arr.length) { + return callback(); + } + var completed = 0; + var iterate = function () { + iterator(arr[completed], function (err) { + if (err) { + callback(err); + callback = noop; + } + else { + completed += 1; + if (completed >= arr.length) { + callback(); + } + else { + iterate(); + } + } + }); + }; + iterate(); + }; + async.forEachSeries = async.eachSeries; + + + async.eachLimit = function (arr, limit, iterator, callback) { + var fn = _eachLimit(limit); + fn.apply(null, [arr, iterator, callback]); + }; + async.forEachLimit = async.eachLimit; + + var _eachLimit = function (limit) { + + return function (arr, iterator, callback) { + callback = callback || noop; + if (!arr.length || limit <= 0) { + return callback(); + } + var completed = 0; + var started = 0; + var running = 0; + + (function replenish () { + if (completed >= arr.length) { + return callback(); + } + + while (running < limit && started < arr.length) { + started += 1; + running += 1; + iterator(arr[started - 1], function (err) { + if (err) { + callback(err); + callback = noop; + } + else { + completed += 1; + running -= 1; + if (completed >= arr.length) { + callback(); + } + else { + replenish(); + } + } + }); + } + })(); + }; + }; + + + + async.forEachOf = async.eachOf = function (object, iterator, callback) { + callback = callback || function () {}; + var size = object.length || _keys(object).length; + var completed = 0; + if (!size) { + return callback(); + } + _forEachOf(object, function (value, key) { + iterator(object[key], key, function (err) { + if (err) { + callback(err); + callback = function () {}; + } else { + completed += 1; + if (completed === size) { + callback(null); + } + } + }); + }); + }; + + async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { + callback = callback || function () {}; + var keys = _keys(obj); + var size = keys.length; + if (!size) { + return callback(); + } + var completed = 0; + var iterate = function () { + var sync = true; + var key = keys[completed]; + iterator(obj[key], key, function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + if (completed >= size) { + callback(null); + } + else { + if (sync) { + async.nextTick(iterate); + } + else { + iterate(); + } + } + } + }); + sync = false; + }; + iterate(); + }; + + + + async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { + _forEachOfLimit(limit)(obj, iterator, callback); + }; + + var _forEachOfLimit = function (limit) { + + return function (obj, iterator, callback) { + callback = callback || function () {}; + var keys = _keys(obj); + var size = keys.length; + if (!size || limit <= 0) { + return callback(); + } + var completed = 0; + var started = 0; + var running = 0; + + (function replenish () { + if (completed >= size) { + return callback(); + } + + while (running < limit && started < size) { + started += 1; + running += 1; + var key = keys[started - 1]; + iterator(obj[key], key, function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + running -= 1; + if (completed >= size) { + callback(); + } + else { + replenish(); + } + } + }); + } + })(); + }; + }; + + + var doParallel = function (fn) { + return function () { + var args = _baseSlice(arguments); + return fn.apply(null, [async.each].concat(args)); + }; + }; + var doParallelLimit = function(limit, fn) { + return function () { + var args = _baseSlice(arguments); + return fn.apply(null, [_eachLimit(limit)].concat(args)); + }; + }; + var doSeries = function (fn) { + return function () { + var args = _baseSlice(arguments); + return fn.apply(null, [async.eachSeries].concat(args)); + }; + }; + + + var _asyncMap = function (eachfn, arr, iterator, callback) { + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + if (!callback) { + eachfn(arr, function (x, callback) { + iterator(x.value, function (err) { + callback(err); + }); + }); + } else { + var results = []; + eachfn(arr, function (x, callback) { + iterator(x.value, function (err, v) { + results[x.index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + async.map = doParallel(_asyncMap); + async.mapSeries = doSeries(_asyncMap); + async.mapLimit = function (arr, limit, iterator, callback) { + return _mapLimit(limit)(arr, iterator, callback); + }; + + var _mapLimit = function(limit) { + return doParallelLimit(limit, _asyncMap); + }; + + // reduce only has a series version, as doing reduce in parallel won't + // work in many situations. + async.reduce = function (arr, memo, iterator, callback) { + async.eachSeries(arr, function (x, callback) { + iterator(memo, x, function (err, v) { + memo = v; + callback(err); + }); + }, function (err) { + callback(err, memo); + }); + }; + // inject alias + async.inject = async.reduce; + // foldl alias + async.foldl = async.reduce; + + async.reduceRight = function (arr, memo, iterator, callback) { + var reversed = _map(arr, function (x) { + return x; + }).reverse(); + async.reduce(reversed, memo, iterator, callback); + }; + // foldr alias + async.foldr = async.reduceRight; + + var _filter = function (eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, callback) { + iterator(x.value, function (v) { + if (v) { + results.push(x); + } + callback(); + }); + }, function (err) { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + }; + async.filter = doParallel(_filter); + async.filterSeries = doSeries(_filter); + // select alias + async.select = async.filter; + async.selectSeries = async.filterSeries; + + var _reject = function (eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, callback) { + iterator(x.value, function (v) { + if (!v) { + results.push(x); + } + callback(); + }); + }, function (err) { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + }; + async.reject = doParallel(_reject); + async.rejectSeries = doSeries(_reject); + + var _detect = function (eachfn, arr, iterator, main_callback) { + eachfn(arr, function (x, callback) { + iterator(x, function (result) { + if (result) { + main_callback(x); + main_callback = noop; + } + else { + callback(); + } + }); + }, function (err) { + main_callback(); + }); + }; + async.detect = doParallel(_detect); + async.detectSeries = doSeries(_detect); + + async.some = function (arr, iterator, main_callback) { + async.each(arr, function (x, callback) { + iterator(x, function (v) { + if (v) { + main_callback(true); + main_callback = noop; + } + callback(); + }); + }, function (err) { + main_callback(false); + }); + }; + // any alias + async.any = async.some; + + async.every = function (arr, iterator, main_callback) { + async.each(arr, function (x, callback) { + iterator(x, function (v) { + if (!v) { + main_callback(false); + main_callback = noop; + } + callback(); + }); + }, function (err) { + main_callback(true); + }); + }; + // all alias + async.all = async.every; + + async.sortBy = function (arr, iterator, callback) { + async.map(arr, function (x, callback) { + iterator(x, function (err, criteria) { + if (err) { + callback(err); + } + else { + callback(null, {value: x, criteria: criteria}); + } + }); + }, function (err, results) { + if (err) { + return callback(err); + } + else { + var fn = function (left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }; + callback(null, _map(results.sort(fn), function (x) { + return x.value; + })); + } + }); + }; + + async.auto = function (tasks, callback) { + callback = callback || noop; + var keys = _keys(tasks); + var remainingTasks = keys.length; + if (!remainingTasks) { + return callback(); + } + + var results = {}; + + var listeners = []; + var addListener = function (fn) { + listeners.unshift(fn); + }; + var removeListener = function (fn) { + for (var i = 0; i < listeners.length; i += 1) { + if (listeners[i] === fn) { + listeners.splice(i, 1); + return; + } + } + }; + var taskComplete = function () { + remainingTasks--; + _each(listeners.slice(0), function (fn) { + fn(); + }); + }; + + addListener(function () { + if (!remainingTasks) { + var theCallback = callback; + // prevent final callback from calling itself if it errors + callback = noop; + + theCallback(null, results); + } + }); + + _each(keys, function (k) { + var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; + var taskCallback = function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + if (err) { + var safeResults = {}; + _each(_keys(results), function(rkey) { + safeResults[rkey] = results[rkey]; + }); + safeResults[k] = args; + callback(err, safeResults); + // stop subsequent errors hitting callback multiple times + callback = noop; + } + else { + results[k] = args; + async.setImmediate(taskComplete); + } + }; + var requires = task.slice(0, Math.abs(task.length - 1)) || []; + // prevent dead-locks + var len = requires.length; + var dep; + while (len--) { + if (!(dep = tasks[requires[len]])) { + throw new Error('Has inexistant dependency'); + } + if (_isArray(dep) && !!~dep.indexOf(k)) { + throw new Error('Has cyclic dependencies'); + } + } + var ready = function () { + return _reduce(requires, function (a, x) { + return (a && results.hasOwnProperty(x)); + }, true) && !results.hasOwnProperty(k); + }; + if (ready()) { + task[task.length - 1](taskCallback, results); + } + else { + var listener = function () { + if (ready()) { + removeListener(listener); + task[task.length - 1](taskCallback, results); + } + }; + addListener(listener); + } + }); + }; + + async.retry = function(times, task, callback) { + var DEFAULT_TIMES = 5; + var attempts = []; + // Use defaults if times not passed + if (typeof times === 'function') { + callback = task; + task = times; + times = DEFAULT_TIMES; + } + // Make sure times is a number + times = parseInt(times, 10) || DEFAULT_TIMES; + var wrappedTask = function(wrappedCallback, wrappedResults) { + var retryAttempt = function(task, finalAttempt) { + return function(seriesCallback) { + task(function(err, result){ + seriesCallback(!err || finalAttempt, {err: err, result: result}); + }, wrappedResults); + }; + }; + while (times) { + attempts.push(retryAttempt(task, !(times-=1))); + } + async.series(attempts, function(done, data){ + data = data[data.length - 1]; + (wrappedCallback || callback)(data.err, data.result); + }); + }; + // If a callback is passed, run this as a controll flow + return callback ? wrappedTask() : wrappedTask; + }; + + async.waterfall = function (tasks, callback) { + callback = callback || noop; + if (!_isArray(tasks)) { + var err = new Error('First argument to waterfall must be an array of functions'); + return callback(err); + } + if (!tasks.length) { + return callback(); + } + var wrapIterator = function (iterator) { + return function (err) { + if (err) { + callback.apply(null, arguments); + callback = noop; + } + else { + var args = _baseSlice(arguments, 1); + var next = iterator.next(); + if (next) { + args.push(wrapIterator(next)); + } + else { + args.push(callback); + } + async.setImmediate(function () { + iterator.apply(null, args); + }); + } + }; + }; + wrapIterator(async.iterator(tasks))(); + }; + + var _parallel = function(eachfn, tasks, callback) { + callback = callback || noop; + if (_isArray(tasks)) { + eachfn.map(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + callback.call(null, err, args); + }); + } + }, callback); + } + else { + var results = {}; + eachfn.each(_keys(tasks), function (k, callback) { + tasks[k](function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[k] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + + async.parallel = function (tasks, callback) { + _parallel({ map: async.map, each: async.each }, tasks, callback); + }; + + async.parallelLimit = function(tasks, limit, callback) { + _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); + }; + + async.series = function (tasks, callback) { + callback = callback || noop; + if (_isArray(tasks)) { + async.mapSeries(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + callback.call(null, err, args); + }); + } + }, callback); + } + else { + var results = {}; + async.eachSeries(_keys(tasks), function (k, callback) { + tasks[k](function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[k] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + + async.iterator = function (tasks) { + var makeCallback = function (index) { + var fn = function () { + if (tasks.length) { + tasks[index].apply(null, arguments); + } + return fn.next(); + }; + fn.next = function () { + return (index < tasks.length - 1) ? makeCallback(index + 1): null; + }; + return fn; + }; + return makeCallback(0); + }; + + async.apply = function (fn) { + var args = _baseSlice(arguments, 1); + return function () { + return fn.apply( + null, args.concat(_baseSlice(arguments)) + ); + }; + }; + + var _concat = function (eachfn, arr, fn, callback) { + var r = []; + eachfn(arr, function (x, cb) { + fn(x, function (err, y) { + r = r.concat(y || []); + cb(err); + }); + }, function (err) { + callback(err, r); + }); + }; + async.concat = doParallel(_concat); + async.concatSeries = doSeries(_concat); + + async.whilst = function (test, iterator, callback) { + if (test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.whilst(test, iterator, callback); + }); + } + else { + callback(); + } + }; + + async.doWhilst = function (iterator, test, callback) { + iterator(function (err) { + if (err) { + return callback(err); + } + var args = _baseSlice(arguments, 1); + if (test.apply(null, args)) { + async.doWhilst(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.until = function (test, iterator, callback) { + if (!test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.until(test, iterator, callback); + }); + } + else { + callback(); + } + }; + + async.doUntil = function (iterator, test, callback) { + iterator(function (err) { + if (err) { + return callback(err); + } + var args = _baseSlice(arguments, 1); + if (!test.apply(null, args)) { + async.doUntil(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.queue = function (worker, concurrency) { + if (concurrency === undefined) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + function _insert(q, data, pos, callback) { + if (!q.started){ + q.started = true; + } + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + if (q.drain) { + q.drain(); + } + }); + } + _each(data, function(task) { + var item = { + data: task, + callback: typeof callback === 'function' ? callback : null + }; + + if (pos) { + q.tasks.unshift(item); + } else { + q.tasks.push(item); + } + + if (q.saturated && q.tasks.length === q.concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + var workers = 0; + var q = { + tasks: [], + concurrency: concurrency, + saturated: null, + empty: null, + drain: null, + started: false, + paused: false, + push: function (data, callback) { + _insert(q, data, false, callback); + }, + kill: function () { + q.drain = null; + q.tasks = []; + }, + unshift: function (data, callback) { + _insert(q, data, true, callback); + }, + process: function () { + if (!q.paused && workers < q.concurrency && q.tasks.length) { + var task = q.tasks.shift(); + if (q.empty && q.tasks.length === 0) { + q.empty(); + } + workers += 1; + var next = function () { + workers -= 1; + if (task.callback) { + task.callback.apply(task, arguments); + } + if (q.drain && q.tasks.length + workers === 0) { + q.drain(); + } + q.process(); + }; + var cb = only_once(next); + worker(task.data, cb); + } + }, + length: function () { + return q.tasks.length; + }, + running: function () { + return workers; + }, + idle: function() { + return q.tasks.length + workers === 0; + }, + pause: function () { + if (q.paused === true) { return; } + q.paused = true; + }, + resume: function () { + if (q.paused === false) { return; } + q.paused = false; + var resumeCount = Math.min(q.concurrency, q.tasks.length); + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= resumeCount; w++) { + async.setImmediate(q.process); + } + } + }; + return q; + }; + + async.priorityQueue = function (worker, concurrency) { + + function _compareTasks(a, b){ + return a.priority - b.priority; + } + + function _binarySearch(sequence, item, compare) { + var beg = -1, + end = sequence.length - 1; + while (beg < end) { + var mid = beg + ((end - beg + 1) >>> 1); + if (compare(item, sequence[mid]) >= 0) { + beg = mid; + } else { + end = mid - 1; + } + } + return beg; + } + + function _insert(q, data, priority, callback) { + if (!q.started){ + q.started = true; + } + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + if (q.drain) { + q.drain(); + } + }); + } + _each(data, function(task) { + var item = { + data: task, + priority: priority, + callback: typeof callback === 'function' ? callback : null + }; + + q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); + + if (q.saturated && q.tasks.length === q.concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + // Start with a normal queue + var q = async.queue(worker, concurrency); + + // Override push to accept second parameter representing priority + q.push = function (data, priority, callback) { + _insert(q, data, priority, callback); + }; + + // Remove unshift function + delete q.unshift; + + return q; + }; + + async.cargo = function (worker, payload) { + var working = false, + tasks = []; + + var cargo = { + tasks: tasks, + payload: payload, + saturated: null, + empty: null, + drain: null, + drained: true, + push: function (data, callback) { + if (!_isArray(data)) { + data = [data]; + } + _each(data, function(task) { + tasks.push({ + data: task, + callback: typeof callback === 'function' ? callback : null + }); + cargo.drained = false; + if (cargo.saturated && tasks.length === payload) { + cargo.saturated(); + } + }); + async.setImmediate(cargo.process); + }, + process: function process() { + if (working) return; + if (tasks.length === 0) { + if(cargo.drain && !cargo.drained) cargo.drain(); + cargo.drained = true; + return; + } + + var ts = typeof payload === 'number' ? + tasks.splice(0, payload) : + tasks.splice(0, tasks.length); + + var ds = _map(ts, function (task) { + return task.data; + }); + + if(cargo.empty) cargo.empty(); + working = true; + worker(ds, function () { + working = false; + + var args = arguments; + _each(ts, function (data) { + if (data.callback) { + data.callback.apply(null, args); + } + }); + + process(); + }); + }, + length: function () { + return tasks.length; + }, + running: function () { + return working; + } + }; + return cargo; + }; + + var _console_fn = function (name) { + return function (fn) { + var args = _baseSlice(arguments, 1); + fn.apply(null, args.concat([function (err) { + var args = _baseSlice(arguments, 1); + if (typeof console !== 'undefined') { + if (err) { + if (console.error) { + console.error(err); + } + } + else if (console[name]) { + _each(args, function (x) { + console[name](x); + }); + } + } + }])); + }; + }; + async.log = _console_fn('log'); + async.dir = _console_fn('dir'); + /*async.info = _console_fn('info'); + async.warn = _console_fn('warn'); + async.error = _console_fn('error');*/ + + async.memoize = function (fn, hasher) { + var memo = {}; + var queues = {}; + hasher = hasher || function (x) { + return x; + }; + var memoized = function () { + var args = _baseSlice(arguments); + var callback = args.pop(); + var key = hasher.apply(null, args); + if (key in memo) { + async.nextTick(function () { + callback.apply(null, memo[key]); + }); + } + else if (key in queues) { + queues[key].push(callback); + } + else { + queues[key] = [callback]; + fn.apply(null, args.concat([function () { + memo[key] = _baseSlice(arguments); + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(null, arguments); + } + }])); + } + }; + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + }; + + async.unmemoize = function (fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; + }; + + async.times = function (count, iterator, callback) { + var counter = []; + for (var i = 0; i < count; i++) { + counter.push(i); + } + return async.map(counter, iterator, callback); + }; + + async.timesSeries = function (count, iterator, callback) { + var counter = []; + for (var i = 0; i < count; i++) { + counter.push(i); + } + return async.mapSeries(counter, iterator, callback); + }; + + async.seq = function (/* functions... */) { + var fns = arguments; + return function () { + var that = this; + var args = _baseSlice(arguments); + var callback = args.pop(); + async.reduce(fns, args, function (newargs, fn, cb) { + fn.apply(that, newargs.concat([function () { + var err = arguments[0]; + var nextargs = _baseSlice(arguments, 1); + cb(err, nextargs); + }])); + }, + function (err, results) { + callback.apply(that, [err].concat(results)); + }); + }; + }; + + async.compose = function (/* functions... */) { + return async.seq.apply(null, Array.prototype.reverse.call(arguments)); + }; + + var _applyEach = function (eachfn, fns /*args...*/) { + var go = function () { + var that = this; + var args = _baseSlice(arguments); + var callback = args.pop(); + return eachfn(fns, function (fn, cb) { + fn.apply(that, args.concat([cb])); + }, + callback); + }; + if (arguments.length > 2) { + var args = _baseSlice(arguments, 2); + return go.apply(this, args); + } + else { + return go; + } + }; + async.applyEach = doParallel(_applyEach); + async.applyEachSeries = doSeries(_applyEach); + + async.forever = function (fn, callback) { + function next(err) { + if (err) { + if (callback) { + return callback(err); + } + throw err; + } + fn(next); + } + next(); + }; + + // Node.js + if (typeof module !== 'undefined' && module.exports) { + module.exports = async; + } + // AMD / RequireJS + else if (typeof define !== 'undefined' && define.amd) { + define([], function () { + return async; + }); + } + // included directly via ` - -## methods - -`base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. - -* `byteLength` - Takes a base64 string and returns length of byte array -* `toByteArray` - Takes a base64 string and returns a byte array -* `fromByteArray` - Takes a byte array and returns a base64 string - -## license - -MIT diff --git a/node_modules/base64-js/base64js.min.js b/node_modules/base64-js/base64js.min.js deleted file mode 100644 index b0279c0..0000000 --- a/node_modules/base64-js/base64js.min.js +++ /dev/null @@ -1 +0,0 @@ -(function(r){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=r()}else if(typeof define==="function"&&define.amd){define([],r)}else{var e;if(typeof window!=="undefined"){e=window}else if(typeof global!=="undefined"){e=global}else if(typeof self!=="undefined"){e=self}else{e=this}e.base64js=r()}})(function(){var r,e,n;return function(){function d(a,f,i){function u(n,r){if(!f[n]){if(!a[n]){var e="function"==typeof require&&require;if(!r&&e)return e(n,!0);if(v)return v(n,!0);var t=new Error("Cannot find module '"+n+"'");throw t.code="MODULE_NOT_FOUND",t}var o=f[n]={exports:{}};a[n][0].call(o.exports,function(r){var e=a[n][1][r];return u(e||r)},o,o.exports,d,a,f,i)}return f[n].exports}for(var v="function"==typeof require&&require,r=0;r0){throw new Error("Invalid string. Length must be a multiple of 4")}var n=r.indexOf("=");if(n===-1)n=e;var t=n===e?0:4-n%4;return[n,t]}function f(r){var e=c(r);var n=e[0];var t=e[1];return(n+t)*3/4-t}function h(r,e,n){return(e+n)*3/4-n}function i(r){var e;var n=c(r);var t=n[0];var o=n[1];var a=new d(h(r,t,o));var f=0;var i=o>0?t-4:t;var u;for(u=0;u>16&255;a[f++]=e>>8&255;a[f++]=e&255}if(o===2){e=v[r.charCodeAt(u)]<<2|v[r.charCodeAt(u+1)]>>4;a[f++]=e&255}if(o===1){e=v[r.charCodeAt(u)]<<10|v[r.charCodeAt(u+1)]<<4|v[r.charCodeAt(u+2)]>>2;a[f++]=e>>8&255;a[f++]=e&255}return a}function s(r){return u[r>>18&63]+u[r>>12&63]+u[r>>6&63]+u[r&63]}function l(r,e,n){var t;var o=[];for(var a=e;ai?i:f+a))}if(t===1){e=r[n-1];o.push(u[e>>2]+u[e<<4&63]+"==")}else if(t===2){e=(r[n-2]<<8)+r[n-1];o.push(u[e>>10]+u[e>>4&63]+u[e<<2&63]+"=")}return o.join("")}},{}]},{},[])("/")}); diff --git a/node_modules/base64-js/index.js b/node_modules/base64-js/index.js deleted file mode 100644 index f087f5b..0000000 --- a/node_modules/base64-js/index.js +++ /dev/null @@ -1,152 +0,0 @@ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk( - uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) - )) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} diff --git a/node_modules/base64-js/package.json b/node_modules/base64-js/package.json deleted file mode 100644 index c5c5c88..0000000 --- a/node_modules/base64-js/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "_from": "base64-js@^1.0.2", - "_id": "base64-js@1.3.1", - "_inBundle": false, - "_integrity": "sha512-mLQ4i2QO1ytvGWFWmcngKO//JXAQueZvwEKtjgQFM4jIK0kU+ytMfplL8j+n5mspOfjHwoAg+9yhb7BwAHm36g==", - "_location": "/base64-js", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "base64-js@^1.0.2", - "name": "base64-js", - "escapedName": "base64-js", - "rawSpec": "^1.0.2", - "saveSpec": null, - "fetchSpec": "^1.0.2" - }, - "_requiredBy": [ - "/buffer" - ], - "_resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.1.tgz", - "_shasum": "58ece8cb75dd07e71ed08c736abc5fac4dbf8df1", - "_spec": "base64-js@^1.0.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/buffer", - "author": { - "name": "T. Jameson Little", - "email": "t.jameson.little@gmail.com" - }, - "bugs": { - "url": "https://github.com/beatgammit/base64-js/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Base64 encoding/decoding in pure JS", - "devDependencies": { - "benchmark": "^2.1.4", - "browserify": "^16.3.0", - "standard": "*", - "tape": "4.x", - "uglify-js": "^3.6.0" - }, - "homepage": "https://github.com/beatgammit/base64-js", - "keywords": [ - "base64" - ], - "license": "MIT", - "main": "index.js", - "name": "base64-js", - "repository": { - "type": "git", - "url": "git://github.com/beatgammit/base64-js.git" - }, - "scripts": { - "build": "browserify -s base64js -r ./ | uglifyjs -m > base64js.min.js", - "lint": "standard", - "test": "npm run lint && npm run unit", - "unit": "tape test/*.js" - }, - "version": "1.3.1" -} diff --git a/node_modules/bindings/LICENSE.md b/node_modules/bindings/LICENSE.md deleted file mode 100644 index 5a92289..0000000 --- a/node_modules/bindings/LICENSE.md +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 Nathan Rajlich <nathan@tootallnate.net> - -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/bindings/README.md b/node_modules/bindings/README.md deleted file mode 100644 index 5b3e7a8..0000000 --- a/node_modules/bindings/README.md +++ /dev/null @@ -1,98 +0,0 @@ -node-bindings -============= -### Helper module for loading your native module's `.node` file - -This is a helper module for authors of Node.js native addon modules. -It is basically the "swiss army knife" of `require()`ing your native module's -`.node` file. - -Throughout the course of Node's native addon history, addons have ended up being -compiled in a variety of different places, depending on which build tool and which -version of node was used. To make matters worse, now the `gyp` build tool can -produce either a __Release__ or __Debug__ build, each being built into different -locations. - -This module checks _all_ the possible locations that a native addon would be built -at, and returns the first one that loads successfully. - - -Installation ------------- - -Install with `npm`: - -``` bash -$ npm install --save bindings -``` - -Or add it to the `"dependencies"` section of your `package.json` file. - - -Example -------- - -`require()`ing the proper bindings file for the current node version, platform -and architecture is as simple as: - -``` js -var bindings = require('bindings')('binding.node') - -// Use your bindings defined in your C files -bindings.your_c_function() -``` - - -Nice Error Output ------------------ - -When the `.node` file could not be loaded, `node-bindings` throws an Error with -a nice error message telling you exactly what was tried. You can also check the -`err.tries` Array property. - -``` -Error: Could not load the bindings file. Tried: - → /Users/nrajlich/ref/build/binding.node - → /Users/nrajlich/ref/build/Debug/binding.node - → /Users/nrajlich/ref/build/Release/binding.node - → /Users/nrajlich/ref/out/Debug/binding.node - → /Users/nrajlich/ref/Debug/binding.node - → /Users/nrajlich/ref/out/Release/binding.node - → /Users/nrajlich/ref/Release/binding.node - → /Users/nrajlich/ref/build/default/binding.node - → /Users/nrajlich/ref/compiled/0.8.2/darwin/x64/binding.node - at bindings (/Users/nrajlich/ref/node_modules/bindings/bindings.js:84:13) - at Object. (/Users/nrajlich/ref/lib/ref.js:5:47) - at Module._compile (module.js:449:26) - at Object.Module._extensions..js (module.js:467:10) - at Module.load (module.js:356:32) - at Function.Module._load (module.js:312:12) - ... -``` - -The searching for the `.node` file will originate from the first directory in which has a `package.json` file is found. - -License -------- - -(The MIT License) - -Copyright (c) 2012 Nathan Rajlich <nathan@tootallnate.net> - -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/bindings/bindings.js b/node_modules/bindings/bindings.js deleted file mode 100644 index 727413a..0000000 --- a/node_modules/bindings/bindings.js +++ /dev/null @@ -1,221 +0,0 @@ -/** - * Module dependencies. - */ - -var fs = require('fs'), - path = require('path'), - fileURLToPath = require('file-uri-to-path'), - join = path.join, - dirname = path.dirname, - exists = - (fs.accessSync && - function(path) { - try { - fs.accessSync(path); - } catch (e) { - return false; - } - return true; - }) || - fs.existsSync || - path.existsSync, - defaults = { - arrow: process.env.NODE_BINDINGS_ARROW || ' → ', - compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled', - platform: process.platform, - arch: process.arch, - nodePreGyp: - 'node-v' + - process.versions.modules + - '-' + - process.platform + - '-' + - process.arch, - version: process.versions.node, - bindings: 'bindings.node', - try: [ - // node-gyp's linked version in the "build" dir - ['module_root', 'build', 'bindings'], - // node-waf and gyp_addon (a.k.a node-gyp) - ['module_root', 'build', 'Debug', 'bindings'], - ['module_root', 'build', 'Release', 'bindings'], - // Debug files, for development (legacy behavior, remove for node v0.9) - ['module_root', 'out', 'Debug', 'bindings'], - ['module_root', 'Debug', 'bindings'], - // Release files, but manually compiled (legacy behavior, remove for node v0.9) - ['module_root', 'out', 'Release', 'bindings'], - ['module_root', 'Release', 'bindings'], - // Legacy from node-waf, node <= 0.4.x - ['module_root', 'build', 'default', 'bindings'], - // Production "Release" buildtype binary (meh...) - ['module_root', 'compiled', 'version', 'platform', 'arch', 'bindings'], - // node-qbs builds - ['module_root', 'addon-build', 'release', 'install-root', 'bindings'], - ['module_root', 'addon-build', 'debug', 'install-root', 'bindings'], - ['module_root', 'addon-build', 'default', 'install-root', 'bindings'], - // node-pre-gyp path ./lib/binding/{node_abi}-{platform}-{arch} - ['module_root', 'lib', 'binding', 'nodePreGyp', 'bindings'] - ] - }; - -/** - * The main `bindings()` function loads the compiled bindings for a given module. - * It uses V8's Error API to determine the parent filename that this function is - * being invoked from, which is then used to find the root directory. - */ - -function bindings(opts) { - // Argument surgery - if (typeof opts == 'string') { - opts = { bindings: opts }; - } else if (!opts) { - opts = {}; - } - - // maps `defaults` onto `opts` object - Object.keys(defaults).map(function(i) { - if (!(i in opts)) opts[i] = defaults[i]; - }); - - // Get the module root - if (!opts.module_root) { - opts.module_root = exports.getRoot(exports.getFileName()); - } - - // Ensure the given bindings name ends with .node - if (path.extname(opts.bindings) != '.node') { - opts.bindings += '.node'; - } - - // https://github.com/webpack/webpack/issues/4175#issuecomment-342931035 - var requireFunc = - typeof __webpack_require__ === 'function' - ? __non_webpack_require__ - : require; - - var tries = [], - i = 0, - l = opts.try.length, - n, - b, - err; - - for (; i < l; i++) { - n = join.apply( - null, - opts.try[i].map(function(p) { - return opts[p] || p; - }) - ); - tries.push(n); - try { - b = opts.path ? requireFunc.resolve(n) : requireFunc(n); - if (!opts.path) { - b.path = n; - } - return b; - } catch (e) { - if (e.code !== 'MODULE_NOT_FOUND' && - e.code !== 'QUALIFIED_PATH_RESOLUTION_FAILED' && - !/not find/i.test(e.message)) { - throw e; - } - } - } - - err = new Error( - 'Could not locate the bindings file. Tried:\n' + - tries - .map(function(a) { - return opts.arrow + a; - }) - .join('\n') - ); - err.tries = tries; - throw err; -} -module.exports = exports = bindings; - -/** - * Gets the filename of the JavaScript file that invokes this function. - * Used to help find the root directory of a module. - * Optionally accepts an filename argument to skip when searching for the invoking filename - */ - -exports.getFileName = function getFileName(calling_file) { - var origPST = Error.prepareStackTrace, - origSTL = Error.stackTraceLimit, - dummy = {}, - fileName; - - Error.stackTraceLimit = 10; - - Error.prepareStackTrace = function(e, st) { - for (var i = 0, l = st.length; i < l; i++) { - fileName = st[i].getFileName(); - if (fileName !== __filename) { - if (calling_file) { - if (fileName !== calling_file) { - return; - } - } else { - return; - } - } - } - }; - - // run the 'prepareStackTrace' function above - Error.captureStackTrace(dummy); - dummy.stack; - - // cleanup - Error.prepareStackTrace = origPST; - Error.stackTraceLimit = origSTL; - - // handle filename that starts with "file://" - var fileSchema = 'file://'; - if (fileName.indexOf(fileSchema) === 0) { - fileName = fileURLToPath(fileName); - } - - return fileName; -}; - -/** - * Gets the root directory of a module, given an arbitrary filename - * somewhere in the module tree. The "root directory" is the directory - * containing the `package.json` file. - * - * In: /home/nate/node-native-module/lib/index.js - * Out: /home/nate/node-native-module - */ - -exports.getRoot = function getRoot(file) { - var dir = dirname(file), - prev; - while (true) { - if (dir === '.') { - // Avoids an infinite loop in rare cases, like the REPL - dir = process.cwd(); - } - if ( - exists(join(dir, 'package.json')) || - exists(join(dir, 'node_modules')) - ) { - // Found the 'package.json' file or 'node_modules' dir; we're done - return dir; - } - if (prev === dir) { - // Got to the top - throw new Error( - 'Could not find module root given file: "' + - file + - '". Do you have a `package.json` file? ' - ); - } - // Try the parent dir next - prev = dir; - dir = join(dir, '..'); - } -}; diff --git a/node_modules/bindings/package.json b/node_modules/bindings/package.json deleted file mode 100644 index 1f67e15..0000000 --- a/node_modules/bindings/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "_from": "bindings@^1.5.0", - "_id": "bindings@1.5.0", - "_inBundle": false, - "_integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", - "_location": "/bindings", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "bindings@^1.5.0", - "name": "bindings", - "escapedName": "bindings", - "rawSpec": "^1.5.0", - "saveSpec": null, - "fetchSpec": "^1.5.0" - }, - "_requiredBy": [ - "/kerberos" - ], - "_resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", - "_shasum": "10353c9e945334bc0511a6d90b38fbc7c9c504df", - "_spec": "bindings@^1.5.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/kerberos", - "author": { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net", - "url": "http://tootallnate.net" - }, - "bugs": { - "url": "https://github.com/TooTallNate/node-bindings/issues" - }, - "bundleDependencies": false, - "dependencies": { - "file-uri-to-path": "1.0.0" - }, - "deprecated": false, - "description": "Helper module for loading your native module's .node file", - "homepage": "https://github.com/TooTallNate/node-bindings", - "keywords": [ - "native", - "addon", - "bindings", - "gyp", - "waf", - "c", - "c++" - ], - "license": "MIT", - "main": "./bindings.js", - "name": "bindings", - "repository": { - "type": "git", - "url": "git://github.com/TooTallNate/node-bindings.git" - }, - "version": "1.5.0" -} diff --git a/node_modules/bl/.jshintrc b/node_modules/bl/.jshintrc deleted file mode 100644 index be119b2..0000000 --- a/node_modules/bl/.jshintrc +++ /dev/null @@ -1,60 +0,0 @@ -{ - "predef": [ ] - , "bitwise": false - , "camelcase": false - , "curly": false - , "eqeqeq": false - , "forin": false - , "immed": false - , "latedef": false - , "noarg": true - , "noempty": true - , "nonew": true - , "plusplus": false - , "quotmark": true - , "regexp": false - , "undef": true - , "unused": true - , "strict": false - , "trailing": true - , "maxlen": 120 - , "asi": true - , "boss": true - , "debug": true - , "eqnull": true - , "esnext": false - , "evil": true - , "expr": true - , "funcscope": false - , "globalstrict": false - , "iterator": false - , "lastsemic": true - , "laxbreak": true - , "laxcomma": true - , "loopfunc": true - , "multistr": false - , "onecase": false - , "proto": false - , "regexdash": false - , "scripturl": true - , "smarttabs": false - , "shadow": false - , "sub": true - , "supernew": false - , "validthis": true - , "browser": true - , "couch": false - , "devel": false - , "dojo": false - , "mootools": false - , "node": true - , "nonstandard": true - , "prototypejs": false - , "rhino": false - , "worker": true - , "wsh": false - , "nomen": false - , "onevar": false - , "passfail": false - , "esversion": 3 -} \ No newline at end of file diff --git a/node_modules/bl/.travis.yml b/node_modules/bl/.travis.yml deleted file mode 100644 index 1044a09..0000000 --- a/node_modules/bl/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -sudo: false -language: node_js -node_js: - - '4' - - '6' - - '8' - - '9' - - '10' -branches: - only: - - master -notifications: - email: - - rod@vagg.org - - matteo.collina@gmail.com diff --git a/node_modules/bl/LICENSE.md b/node_modules/bl/LICENSE.md deleted file mode 100644 index dea757d..0000000 --- a/node_modules/bl/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -The MIT License (MIT) -===================== - -Copyright (c) 2013-2018 bl contributors ----------------------------------- - -*bl contributors listed at * - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/bl/README.md b/node_modules/bl/README.md deleted file mode 100644 index 79dca35..0000000 --- a/node_modules/bl/README.md +++ /dev/null @@ -1,218 +0,0 @@ -# bl *(BufferList)* - -[![Build Status](https://travis-ci.org/rvagg/bl.svg?branch=master)](https://travis-ci.org/rvagg/bl) - -**A Node.js Buffer list collector, reader and streamer thingy.** - -[![NPM](https://nodei.co/npm/bl.png?downloads=true&downloadRank=true)](https://nodei.co/npm/bl/) -[![NPM](https://nodei.co/npm-dl/bl.png?months=6&height=3)](https://nodei.co/npm/bl/) - -**bl** is a storage object for collections of Node Buffers, exposing them with the main Buffer readable API. Also works as a duplex stream so you can collect buffers from a stream that emits them and emit buffers to a stream that consumes them! - -The original buffers are kept intact and copies are only done as necessary. Any reads that require the use of a single original buffer will return a slice of that buffer only (which references the same memory as the original buffer). Reads that span buffers perform concatenation as required and return the results transparently. - -```js -const BufferList = require('bl') - -var bl = new BufferList() -bl.append(Buffer.from('abcd')) -bl.append(Buffer.from('efg')) -bl.append('hi') // bl will also accept & convert Strings -bl.append(Buffer.from('j')) -bl.append(Buffer.from([ 0x3, 0x4 ])) - -console.log(bl.length) // 12 - -console.log(bl.slice(0, 10).toString('ascii')) // 'abcdefghij' -console.log(bl.slice(3, 10).toString('ascii')) // 'defghij' -console.log(bl.slice(3, 6).toString('ascii')) // 'def' -console.log(bl.slice(3, 8).toString('ascii')) // 'defgh' -console.log(bl.slice(5, 10).toString('ascii')) // 'fghij' - -console.log(bl.indexOf('def')) // 3 -console.log(bl.indexOf('asdf')) // -1 - -// or just use toString! -console.log(bl.toString()) // 'abcdefghij\u0003\u0004' -console.log(bl.toString('ascii', 3, 8)) // 'defgh' -console.log(bl.toString('ascii', 5, 10)) // 'fghij' - -// other standard Buffer readables -console.log(bl.readUInt16BE(10)) // 0x0304 -console.log(bl.readUInt16LE(10)) // 0x0403 -``` - -Give it a callback in the constructor and use it just like **[concat-stream](https://github.com/maxogden/node-concat-stream)**: - -```js -const bl = require('bl') - , fs = require('fs') - -fs.createReadStream('README.md') - .pipe(bl(function (err, data) { // note 'new' isn't strictly required - // `data` is a complete Buffer object containing the full data - console.log(data.toString()) - })) -``` - -Note that when you use the *callback* method like this, the resulting `data` parameter is a concatenation of all `Buffer` objects in the list. If you want to avoid the overhead of this concatenation (in cases of extreme performance consciousness), then avoid the *callback* method and just listen to `'end'` instead, like a standard Stream. - -Or to fetch a URL using [hyperquest](https://github.com/substack/hyperquest) (should work with [request](http://github.com/mikeal/request) and even plain Node http too!): -```js -const hyperquest = require('hyperquest') - , bl = require('bl') - , url = 'https://raw.github.com/rvagg/bl/master/README.md' - -hyperquest(url).pipe(bl(function (err, data) { - console.log(data.toString()) -})) -``` - -Or, use it as a readable stream to recompose a list of Buffers to an output source: - -```js -const BufferList = require('bl') - , fs = require('fs') - -var bl = new BufferList() -bl.append(Buffer.from('abcd')) -bl.append(Buffer.from('efg')) -bl.append(Buffer.from('hi')) -bl.append(Buffer.from('j')) - -bl.pipe(fs.createWriteStream('gibberish.txt')) -``` - -## API - - * new BufferList([ callback ]) - * bl.length - * bl.append(buffer) - * bl.get(index) - * bl.indexOf(value[, byteOffset][, encoding]) - * bl.slice([ start[, end ] ]) - * bl.shallowSlice([ start[, end ] ]) - * bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ]) - * bl.duplicate() - * bl.consume(bytes) - * bl.toString([encoding, [ start, [ end ]]]) - * bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8() - * Streams - --------------------------------------------------------- - -### new BufferList([ callback | Buffer | Buffer array | BufferList | BufferList array | String ]) -The constructor takes an optional callback, if supplied, the callback will be called with an error argument followed by a reference to the **bl** instance, when `bl.end()` is called (i.e. from a piped stream). This is a convenient method of collecting the entire contents of a stream, particularly when the stream is *chunky*, such as a network stream. - -Normally, no arguments are required for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` object. - -`new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with: - -```js -var bl = require('bl') -var myinstance = bl() - -// equivalent to: - -var BufferList = require('bl') -var myinstance = new BufferList() -``` - --------------------------------------------------------- - -### bl.length -Get the length of the list in bytes. This is the sum of the lengths of all of the buffers contained in the list, minus any initial offset for a semi-consumed buffer at the beginning. Should accurately represent the total number of bytes that can be read from the list. - --------------------------------------------------------- - -### bl.append(Buffer | Buffer array | BufferList | BufferList array | String) -`append(buffer)` adds an additional buffer or BufferList to the internal list. `this` is returned so it can be chained. - --------------------------------------------------------- - -### bl.get(index) -`get()` will return the byte at the specified index. - --------------------------------------------------------- - -### bl.indexOf(value[, byteOffset][, encoding]) -`get()` will return the byte at the specified index. -`indexOf()` method returns the first index at which a given element can be found in the BufferList, or -1 if it is not present. - --------------------------------------------------------- - -### bl.slice([ start, [ end ] ]) -`slice()` returns a new `Buffer` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively. - -If the requested range spans a single internal buffer then a slice of that buffer will be returned which shares the original memory range of that Buffer. If the range spans multiple buffers then copy operations will likely occur to give you a uniform Buffer. - --------------------------------------------------------- - -### bl.shallowSlice([ start, [ end ] ]) -`shallowSlice()` returns a new `BufferList` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively. - -No copies will be performed. All buffers in the result share memory with the original list. - --------------------------------------------------------- - -### bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ]) -`copy()` copies the content of the list in the `dest` buffer, starting from `destStart` and containing the bytes within the range specified with `srcStart` to `srcEnd`. `destStart`, `start` and `end` are optional and will default to the beginning of the `dest` buffer, and the beginning and end of the list respectively. - --------------------------------------------------------- - -### bl.duplicate() -`duplicate()` performs a **shallow-copy** of the list. The internal Buffers remains the same, so if you change the underlying Buffers, the change will be reflected in both the original and the duplicate. This method is needed if you want to call `consume()` or `pipe()` and still keep the original list.Example: - -```js -var bl = new BufferList() - -bl.append('hello') -bl.append(' world') -bl.append('\n') - -bl.duplicate().pipe(process.stdout, { end: false }) - -console.log(bl.toString()) -``` - --------------------------------------------------------- - -### bl.consume(bytes) -`consume()` will shift bytes *off the start of the list*. The number of bytes consumed don't need to line up with the sizes of the internal Buffers—initial offsets will be calculated accordingly in order to give you a consistent view of the data. - --------------------------------------------------------- - -### bl.toString([encoding, [ start, [ end ]]]) -`toString()` will return a string representation of the buffer. The optional `start` and `end` arguments are passed on to `slice()`, while the `encoding` is passed on to `toString()` of the resulting Buffer. See the [Buffer#toString()](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_tostring_encoding_start_end) documentation for more information. - --------------------------------------------------------- - -### bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8() - -All of the standard byte-reading methods of the `Buffer` interface are implemented and will operate across internal Buffer boundaries transparently. - -See the [Buffer](http://nodejs.org/docs/latest/api/buffer.html) documentation for how these work. - --------------------------------------------------------- - -### Streams -**bl** is a Node **[Duplex Stream](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_duplex)**, so it can be read from and written to like a standard Node stream. You can also `pipe()` to and from a **bl** instance. - --------------------------------------------------------- - -## Contributors - -**bl** is brought to you by the following hackers: - - * [Rod Vagg](https://github.com/rvagg) - * [Matteo Collina](https://github.com/mcollina) - * [Jarett Cruger](https://github.com/jcrugzz) - -======= - - -## License & copyright - -Copyright (c) 2013-2018 bl contributors (listed above). - -bl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details. diff --git a/node_modules/bl/bl.js b/node_modules/bl/bl.js deleted file mode 100644 index af49483..0000000 --- a/node_modules/bl/bl.js +++ /dev/null @@ -1,383 +0,0 @@ -'use strict' -var DuplexStream = require('readable-stream').Duplex - , util = require('util') - , Buffer = require('safe-buffer').Buffer - -function BufferList (callback) { - if (!(this instanceof BufferList)) - return new BufferList(callback) - - this._bufs = [] - this.length = 0 - - if (typeof callback == 'function') { - this._callback = callback - - var piper = function piper (err) { - if (this._callback) { - this._callback(err) - this._callback = null - } - }.bind(this) - - this.on('pipe', function onPipe (src) { - src.on('error', piper) - }) - this.on('unpipe', function onUnpipe (src) { - src.removeListener('error', piper) - }) - } else { - this.append(callback) - } - - DuplexStream.call(this) -} - - -util.inherits(BufferList, DuplexStream) - - -BufferList.prototype._offset = function _offset (offset) { - var tot = 0, i = 0, _t - if (offset === 0) return [ 0, 0 ] - for (; i < this._bufs.length; i++) { - _t = tot + this._bufs[i].length - if (offset < _t || i == this._bufs.length - 1) { - return [ i, offset - tot ] - } - tot = _t - } -} - -BufferList.prototype._reverseOffset = function (blOffset) { - var bufferId = blOffset[0] - var offset = blOffset[1] - for (var i = 0; i < bufferId; i++) { - offset += this._bufs[i].length - } - return offset -} - -BufferList.prototype.append = function append (buf) { - var i = 0 - - if (Buffer.isBuffer(buf)) { - this._appendBuffer(buf) - } else if (Array.isArray(buf)) { - for (; i < buf.length; i++) - this.append(buf[i]) - } else if (buf instanceof BufferList) { - // unwrap argument into individual BufferLists - for (; i < buf._bufs.length; i++) - this.append(buf._bufs[i]) - } else if (buf != null) { - // coerce number arguments to strings, since Buffer(number) does - // uninitialized memory allocation - if (typeof buf == 'number') - buf = buf.toString() - - this._appendBuffer(Buffer.from(buf)) - } - - return this -} - - -BufferList.prototype._appendBuffer = function appendBuffer (buf) { - this._bufs.push(buf) - this.length += buf.length -} - - -BufferList.prototype._write = function _write (buf, encoding, callback) { - this._appendBuffer(buf) - - if (typeof callback == 'function') - callback() -} - - -BufferList.prototype._read = function _read (size) { - if (!this.length) - return this.push(null) - - size = Math.min(size, this.length) - this.push(this.slice(0, size)) - this.consume(size) -} - - -BufferList.prototype.end = function end (chunk) { - DuplexStream.prototype.end.call(this, chunk) - - if (this._callback) { - this._callback(null, this.slice()) - this._callback = null - } -} - - -BufferList.prototype.get = function get (index) { - if (index > this.length || index < 0) { - return undefined - } - var offset = this._offset(index) - return this._bufs[offset[0]][offset[1]] -} - - -BufferList.prototype.slice = function slice (start, end) { - if (typeof start == 'number' && start < 0) - start += this.length - if (typeof end == 'number' && end < 0) - end += this.length - return this.copy(null, 0, start, end) -} - - -BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { - if (typeof srcStart != 'number' || srcStart < 0) - srcStart = 0 - if (typeof srcEnd != 'number' || srcEnd > this.length) - srcEnd = this.length - if (srcStart >= this.length) - return dst || Buffer.alloc(0) - if (srcEnd <= 0) - return dst || Buffer.alloc(0) - - var copy = !!dst - , off = this._offset(srcStart) - , len = srcEnd - srcStart - , bytes = len - , bufoff = (copy && dstStart) || 0 - , start = off[1] - , l - , i - - // copy/slice everything - if (srcStart === 0 && srcEnd == this.length) { - if (!copy) { // slice, but full concat if multiple buffers - return this._bufs.length === 1 - ? this._bufs[0] - : Buffer.concat(this._bufs, this.length) - } - - // copy, need to copy individual buffers - for (i = 0; i < this._bufs.length; i++) { - this._bufs[i].copy(dst, bufoff) - bufoff += this._bufs[i].length - } - - return dst - } - - // easy, cheap case where it's a subset of one of the buffers - if (bytes <= this._bufs[off[0]].length - start) { - return copy - ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) - : this._bufs[off[0]].slice(start, start + bytes) - } - - if (!copy) // a slice, we need something to copy in to - dst = Buffer.allocUnsafe(len) - - for (i = off[0]; i < this._bufs.length; i++) { - l = this._bufs[i].length - start - - if (bytes > l) { - this._bufs[i].copy(dst, bufoff, start) - } else { - this._bufs[i].copy(dst, bufoff, start, start + bytes) - break - } - - bufoff += l - bytes -= l - - if (start) - start = 0 - } - - return dst -} - -BufferList.prototype.shallowSlice = function shallowSlice (start, end) { - start = start || 0 - end = typeof end !== 'number' ? this.length : end - - if (start < 0) - start += this.length - if (end < 0) - end += this.length - - if (start === end) { - return new BufferList() - } - var startOffset = this._offset(start) - , endOffset = this._offset(end) - , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) - - if (endOffset[1] == 0) - buffers.pop() - else - buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1]) - - if (startOffset[1] != 0) - buffers[0] = buffers[0].slice(startOffset[1]) - - return new BufferList(buffers) -} - -BufferList.prototype.toString = function toString (encoding, start, end) { - return this.slice(start, end).toString(encoding) -} - -BufferList.prototype.consume = function consume (bytes) { - while (this._bufs.length) { - if (bytes >= this._bufs[0].length) { - bytes -= this._bufs[0].length - this.length -= this._bufs[0].length - this._bufs.shift() - } else { - this._bufs[0] = this._bufs[0].slice(bytes) - this.length -= bytes - break - } - } - return this -} - - -BufferList.prototype.duplicate = function duplicate () { - var i = 0 - , copy = new BufferList() - - for (; i < this._bufs.length; i++) - copy.append(this._bufs[i]) - - return copy -} - - -BufferList.prototype.destroy = function destroy () { - this._bufs.length = 0 - this.length = 0 - this.push(null) -} - - -BufferList.prototype.indexOf = function (search, offset, encoding) { - if (encoding === undefined && typeof offset === 'string') { - encoding = offset - offset = undefined - } - if (typeof search === 'function' || Array.isArray(search)) { - throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') - } else if (typeof search === 'number') { - search = Buffer.from([search]) - } else if (typeof search === 'string') { - search = Buffer.from(search, encoding) - } else if (search instanceof BufferList) { - search = search.slice() - } else if (!Buffer.isBuffer(search)) { - search = Buffer.from(search) - } - - offset = Number(offset || 0) - if (isNaN(offset)) { - offset = 0 - } - - if (offset < 0) { - offset = this.length + offset - } - - if (offset < 0) { - offset = 0 - } - - if (search.length === 0) { - return offset > this.length ? this.length : offset - } - - var blOffset = this._offset(offset) - var blIndex = blOffset[0] // index of which internal buffer we're working on - var buffOffset = blOffset[1] // offset of the internal buffer we're working on - - // scan over each buffer - for (blIndex; blIndex < this._bufs.length; blIndex++) { - var buff = this._bufs[blIndex] - while(buffOffset < buff.length) { - var availableWindow = buff.length - buffOffset - if (availableWindow >= search.length) { - var nativeSearchResult = buff.indexOf(search, buffOffset) - if (nativeSearchResult !== -1) { - return this._reverseOffset([blIndex, nativeSearchResult]) - } - buffOffset = buff.length - search.length + 1 // end of native search window - } else { - var revOffset = this._reverseOffset([blIndex, buffOffset]) - if (this._match(revOffset, search)) { - return revOffset - } - buffOffset++ - } - } - buffOffset = 0 - } - return -1 -} - -BufferList.prototype._match = function(offset, search) { - if (this.length - offset < search.length) { - return false - } - for (var searchOffset = 0; searchOffset < search.length ; searchOffset++) { - if(this.get(offset + searchOffset) !== search[searchOffset]){ - return false - } - } - return true -} - - -;(function () { - var methods = { - 'readDoubleBE' : 8 - , 'readDoubleLE' : 8 - , 'readFloatBE' : 4 - , 'readFloatLE' : 4 - , 'readInt32BE' : 4 - , 'readInt32LE' : 4 - , 'readUInt32BE' : 4 - , 'readUInt32LE' : 4 - , 'readInt16BE' : 2 - , 'readInt16LE' : 2 - , 'readUInt16BE' : 2 - , 'readUInt16LE' : 2 - , 'readInt8' : 1 - , 'readUInt8' : 1 - , 'readIntBE' : null - , 'readIntLE' : null - , 'readUIntBE' : null - , 'readUIntLE' : null - } - - for (var m in methods) { - (function (m) { - if (methods[m] === null) { - BufferList.prototype[m] = function (offset, byteLength) { - return this.slice(offset, offset + byteLength)[m](0, byteLength) - } - } - else { - BufferList.prototype[m] = function (offset) { - return this.slice(offset, offset + methods[m])[m](0) - } - } - }(m)) - } -}()) - - -module.exports = BufferList diff --git a/node_modules/bl/package.json b/node_modules/bl/package.json deleted file mode 100644 index bed9625..0000000 --- a/node_modules/bl/package.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "_from": "bl@^2.2.0", - "_id": "bl@2.2.0", - "_inBundle": false, - "_integrity": "sha512-wbgvOpqopSr7uq6fJrLH8EsvYMJf9gzfo2jCsL2eTy75qXPukA4pCgHamOQkZtY5vmfVtjB+P3LNlMHW5CEZXA==", - "_location": "/bl", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "bl@^2.2.0", - "name": "bl", - "escapedName": "bl", - "rawSpec": "^2.2.0", - "saveSpec": null, - "fetchSpec": "^2.2.0" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/bl/-/bl-2.2.0.tgz", - "_shasum": "e1a574cdf528e4053019bb800b041c0ac88da493", - "_spec": "bl@^2.2.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mongodb", - "authors": [ - "Rod Vagg (https://github.com/rvagg)", - "Matteo Collina (https://github.com/mcollina)", - "Jarett Cruger (https://github.com/jcrugzz)" - ], - "bugs": { - "url": "https://github.com/rvagg/bl/issues" - }, - "bundleDependencies": false, - "dependencies": { - "readable-stream": "^2.3.5", - "safe-buffer": "^5.1.1" - }, - "deprecated": false, - "description": "Buffer List: collect buffers and access with a standard readable Buffer interface, streamable too!", - "devDependencies": { - "faucet": "0.0.1", - "hash_file": "~0.1.1", - "tape": "~4.9.0" - }, - "homepage": "https://github.com/rvagg/bl", - "keywords": [ - "buffer", - "buffers", - "stream", - "awesomesauce" - ], - "license": "MIT", - "main": "bl.js", - "name": "bl", - "repository": { - "type": "git", - "url": "git+https://github.com/rvagg/bl.git" - }, - "scripts": { - "test": "node test/test.js | faucet" - }, - "version": "2.2.0" -} diff --git a/node_modules/bl/test/indexOf.js b/node_modules/bl/test/indexOf.js deleted file mode 100644 index 68435e1..0000000 --- a/node_modules/bl/test/indexOf.js +++ /dev/null @@ -1,463 +0,0 @@ -'use strict' - -var tape = require('tape') - , BufferList = require('../') - , Buffer = require('safe-buffer').Buffer - -tape('indexOf single byte needle', t => { - const bl = new BufferList(['abcdefg', 'abcdefg', '12345']) - t.equal(bl.indexOf('e'), 4) - t.equal(bl.indexOf('e', 5), 11) - t.equal(bl.indexOf('e', 12), -1) - t.equal(bl.indexOf('5'), 18) - t.end() -}) - -tape('indexOf multiple byte needle', t => { - const bl = new BufferList(['abcdefg', 'abcdefg']) - t.equal(bl.indexOf('ef'), 4) - t.equal(bl.indexOf('ef', 5), 11) - t.end() -}) - -tape('indexOf multiple byte needles across buffer boundaries', t => { - const bl = new BufferList(['abcdefg', 'abcdefg']) - t.equal(bl.indexOf('fgabc'), 5) - t.end() -}) - -tape('indexOf takes a buffer list search', t => { - const bl = new BufferList(['abcdefg', 'abcdefg']) - const search = new BufferList('fgabc') - t.equal(bl.indexOf(search), 5) - t.end() -}) - -tape('indexOf a zero byte needle', t => { - const b = new BufferList('abcdef') - const buf_empty = Buffer.from('') - t.equal(b.indexOf(''), 0) - t.equal(b.indexOf('', 1), 1) - t.equal(b.indexOf('', b.length + 1), b.length) - t.equal(b.indexOf('', Infinity), b.length) - t.equal(b.indexOf(buf_empty), 0) - t.equal(b.indexOf(buf_empty, 1), 1) - t.equal(b.indexOf(buf_empty, b.length + 1), b.length) - t.equal(b.indexOf(buf_empty, Infinity), b.length) - t.end() -}) - -tape('indexOf buffers smaller and larger than the needle', t => { - const bl = new BufferList(['abcdefg', 'a', 'bcdefg', 'a', 'bcfgab']) - t.equal(bl.indexOf('fgabc'), 5) - t.equal(bl.indexOf('fgabc', 6), 12) - t.equal(bl.indexOf('fgabc', 13), -1) - t.end() -}) - -// only present in node 6+ -;(process.version.substr(1).split('.')[0] >= 6) && tape('indexOf latin1 and binary encoding', t => { - const b = new BufferList('abcdef') - - // test latin1 encoding - t.equal( - new BufferList(Buffer.from(b.toString('latin1'), 'latin1')) - .indexOf('d', 0, 'latin1'), - 3 - ) - t.equal( - new BufferList(Buffer.from(b.toString('latin1'), 'latin1')) - .indexOf(Buffer.from('d', 'latin1'), 0, 'latin1'), - 3 - ) - t.equal( - new BufferList(Buffer.from('aa\u00e8aa', 'latin1')) - .indexOf('\u00e8', 'latin1'), - 2 - ) - t.equal( - new BufferList(Buffer.from('\u00e8', 'latin1')) - .indexOf('\u00e8', 'latin1'), - 0 - ) - t.equal( - new BufferList(Buffer.from('\u00e8', 'latin1')) - .indexOf(Buffer.from('\u00e8', 'latin1'), 'latin1'), - 0 - ) - - // test binary encoding - t.equal( - new BufferList(Buffer.from(b.toString('binary'), 'binary')) - .indexOf('d', 0, 'binary'), - 3 - ) - t.equal( - new BufferList(Buffer.from(b.toString('binary'), 'binary')) - .indexOf(Buffer.from('d', 'binary'), 0, 'binary'), - 3 - ) - t.equal( - new BufferList(Buffer.from('aa\u00e8aa', 'binary')) - .indexOf('\u00e8', 'binary'), - 2 - ) - t.equal( - new BufferList(Buffer.from('\u00e8', 'binary')) - .indexOf('\u00e8', 'binary'), - 0 - ) - t.equal( - new BufferList(Buffer.from('\u00e8', 'binary')) - .indexOf(Buffer.from('\u00e8', 'binary'), 'binary'), - 0 - ) - t.end() -}) - -tape('indexOf the entire nodejs10 buffer test suite', t => { - const b = new BufferList('abcdef') - const buf_a = Buffer.from('a') - const buf_bc = Buffer.from('bc') - const buf_f = Buffer.from('f') - const buf_z = Buffer.from('z') - - const stringComparison = 'abcdef' - - t.equal(b.indexOf('a'), 0) - t.equal(b.indexOf('a', 1), -1) - t.equal(b.indexOf('a', -1), -1) - t.equal(b.indexOf('a', -4), -1) - t.equal(b.indexOf('a', -b.length), 0) - t.equal(b.indexOf('a', NaN), 0) - t.equal(b.indexOf('a', -Infinity), 0) - t.equal(b.indexOf('a', Infinity), -1) - t.equal(b.indexOf('bc'), 1) - t.equal(b.indexOf('bc', 2), -1) - t.equal(b.indexOf('bc', -1), -1) - t.equal(b.indexOf('bc', -3), -1) - t.equal(b.indexOf('bc', -5), 1) - t.equal(b.indexOf('bc', NaN), 1) - t.equal(b.indexOf('bc', -Infinity), 1) - t.equal(b.indexOf('bc', Infinity), -1) - t.equal(b.indexOf('f'), b.length - 1) - t.equal(b.indexOf('z'), -1) - // empty search tests - t.equal(b.indexOf(buf_a), 0) - t.equal(b.indexOf(buf_a, 1), -1) - t.equal(b.indexOf(buf_a, -1), -1) - t.equal(b.indexOf(buf_a, -4), -1) - t.equal(b.indexOf(buf_a, -b.length), 0) - t.equal(b.indexOf(buf_a, NaN), 0) - t.equal(b.indexOf(buf_a, -Infinity), 0) - t.equal(b.indexOf(buf_a, Infinity), -1) - t.equal(b.indexOf(buf_bc), 1) - t.equal(b.indexOf(buf_bc, 2), -1) - t.equal(b.indexOf(buf_bc, -1), -1) - t.equal(b.indexOf(buf_bc, -3), -1) - t.equal(b.indexOf(buf_bc, -5), 1) - t.equal(b.indexOf(buf_bc, NaN), 1) - t.equal(b.indexOf(buf_bc, -Infinity), 1) - t.equal(b.indexOf(buf_bc, Infinity), -1) - t.equal(b.indexOf(buf_f), b.length - 1) - t.equal(b.indexOf(buf_z), -1) - t.equal(b.indexOf(0x61), 0) - t.equal(b.indexOf(0x61, 1), -1) - t.equal(b.indexOf(0x61, -1), -1) - t.equal(b.indexOf(0x61, -4), -1) - t.equal(b.indexOf(0x61, -b.length), 0) - t.equal(b.indexOf(0x61, NaN), 0) - t.equal(b.indexOf(0x61, -Infinity), 0) - t.equal(b.indexOf(0x61, Infinity), -1) - t.equal(b.indexOf(0x0), -1) - - // test offsets - t.equal(b.indexOf('d', 2), 3) - t.equal(b.indexOf('f', 5), 5) - t.equal(b.indexOf('f', -1), 5) - t.equal(b.indexOf('f', 6), -1) - - t.equal(b.indexOf(Buffer.from('d'), 2), 3) - t.equal(b.indexOf(Buffer.from('f'), 5), 5) - t.equal(b.indexOf(Buffer.from('f'), -1), 5) - t.equal(b.indexOf(Buffer.from('f'), 6), -1) - - t.equal(Buffer.from('ff').indexOf(Buffer.from('f'), 1, 'ucs2'), -1) - - // test invalid and uppercase encoding - t.equal(b.indexOf('b', 'utf8'), 1) - t.equal(b.indexOf('b', 'UTF8'), 1) - t.equal(b.indexOf('62', 'HEX'), 1) - t.throws(() => b.indexOf('bad', 'enc'), TypeError) - - // test hex encoding - t.equal( - Buffer.from(b.toString('hex'), 'hex') - .indexOf('64', 0, 'hex'), - 3 - ) - t.equal( - Buffer.from(b.toString('hex'), 'hex') - .indexOf(Buffer.from('64', 'hex'), 0, 'hex'), - 3 - ) - - // test base64 encoding - t.equal( - Buffer.from(b.toString('base64'), 'base64') - .indexOf('ZA==', 0, 'base64'), - 3 - ) - t.equal( - Buffer.from(b.toString('base64'), 'base64') - .indexOf(Buffer.from('ZA==', 'base64'), 0, 'base64'), - 3 - ) - - // test ascii encoding - t.equal( - Buffer.from(b.toString('ascii'), 'ascii') - .indexOf('d', 0, 'ascii'), - 3 - ) - t.equal( - Buffer.from(b.toString('ascii'), 'ascii') - .indexOf(Buffer.from('d', 'ascii'), 0, 'ascii'), - 3 - ) - - // test optional offset with passed encoding - t.equal(Buffer.from('aaaa0').indexOf('30', 'hex'), 4) - t.equal(Buffer.from('aaaa00a').indexOf('3030', 'hex'), 4) - - { - // test usc2 encoding - const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2') - - t.equal(8, twoByteString.indexOf('\u0395', 4, 'ucs2')) - t.equal(6, twoByteString.indexOf('\u03a3', -4, 'ucs2')) - t.equal(4, twoByteString.indexOf('\u03a3', -6, 'ucs2')) - t.equal(4, twoByteString.indexOf( - Buffer.from('\u03a3', 'ucs2'), -6, 'ucs2')) - t.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2')) - } - - const mixedByteStringUcs2 = - Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2') - t.equal(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2')) - t.equal(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2')) - t.equal(-1, mixedByteStringUcs2.indexOf('\u0396', 0, 'ucs2')) - - t.equal( - 6, mixedByteStringUcs2.indexOf(Buffer.from('bc', 'ucs2'), 0, 'ucs2')) - t.equal( - 10, mixedByteStringUcs2.indexOf(Buffer.from('\u03a3', 'ucs2'), 0, 'ucs2')) - t.equal( - -1, mixedByteStringUcs2.indexOf(Buffer.from('\u0396', 'ucs2'), 0, 'ucs2')) - - { - const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2') - - // Test single char pattern - t.equal(0, twoByteString.indexOf('\u039a', 0, 'ucs2')) - let index = twoByteString.indexOf('\u0391', 0, 'ucs2') - t.equal(2, index, `Alpha - at index ${index}`) - index = twoByteString.indexOf('\u03a3', 0, 'ucs2') - t.equal(4, index, `First Sigma - at index ${index}`) - index = twoByteString.indexOf('\u03a3', 6, 'ucs2') - t.equal(6, index, `Second Sigma - at index ${index}`) - index = twoByteString.indexOf('\u0395', 0, 'ucs2') - t.equal(8, index, `Epsilon - at index ${index}`) - index = twoByteString.indexOf('\u0392', 0, 'ucs2') - t.equal(-1, index, `Not beta - at index ${index}`) - - // Test multi-char pattern - index = twoByteString.indexOf('\u039a\u0391', 0, 'ucs2') - t.equal(0, index, `Lambda Alpha - at index ${index}`) - index = twoByteString.indexOf('\u0391\u03a3', 0, 'ucs2') - t.equal(2, index, `Alpha Sigma - at index ${index}`) - index = twoByteString.indexOf('\u03a3\u03a3', 0, 'ucs2') - t.equal(4, index, `Sigma Sigma - at index ${index}`) - index = twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2') - t.equal(6, index, `Sigma Epsilon - at index ${index}`) - } - - const mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395') - t.equal(5, mixedByteStringUtf8.indexOf('bc')) - t.equal(5, mixedByteStringUtf8.indexOf('bc', 5)) - t.equal(5, mixedByteStringUtf8.indexOf('bc', -8)) - t.equal(7, mixedByteStringUtf8.indexOf('\u03a3')) - t.equal(-1, mixedByteStringUtf8.indexOf('\u0396')) - - - // Test complex string indexOf algorithms. Only trigger for long strings. - // Long string that isn't a simple repeat of a shorter string. - let longString = 'A' - for (let i = 66; i < 76; i++) { // from 'B' to 'K' - longString = longString + String.fromCharCode(i) + longString - } - - const longBufferString = Buffer.from(longString) - - // pattern of 15 chars, repeated every 16 chars in long - let pattern = 'ABACABADABACABA' - for (let i = 0; i < longBufferString.length - pattern.length; i += 7) { - const index = longBufferString.indexOf(pattern, i) - t.equal((i + 15) & ~0xf, index, - `Long ABACABA...-string at index ${i}`) - } - - let index = longBufferString.indexOf('AJABACA') - t.equal(510, index, `Long AJABACA, First J - at index ${index}`) - index = longBufferString.indexOf('AJABACA', 511) - t.equal(1534, index, `Long AJABACA, Second J - at index ${index}`) - - pattern = 'JABACABADABACABA' - index = longBufferString.indexOf(pattern) - t.equal(511, index, `Long JABACABA..., First J - at index ${index}`) - index = longBufferString.indexOf(pattern, 512) - t.equal( - 1535, index, `Long JABACABA..., Second J - at index ${index}`) - - // Search for a non-ASCII string in a pure ASCII string. - const asciiString = Buffer.from( - 'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf') - t.equal(-1, asciiString.indexOf('\x2061')) - t.equal(3, asciiString.indexOf('leb', 0)) - - // Search in string containing many non-ASCII chars. - const allCodePoints = [] - for (let i = 0; i < 65536; i++) allCodePoints[i] = i - const allCharsString = String.fromCharCode.apply(String, allCodePoints) - const allCharsBufferUtf8 = Buffer.from(allCharsString) - const allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2') - - // Search for string long enough to trigger complex search with ASCII pattern - // and UC16 subject. - t.equal(-1, allCharsBufferUtf8.indexOf('notfound')) - t.equal(-1, allCharsBufferUcs2.indexOf('notfound')) - - // Needle is longer than haystack, but only because it's encoded as UTF-16 - t.equal(Buffer.from('aaaa').indexOf('a'.repeat(4), 'ucs2'), -1) - - t.equal(Buffer.from('aaaa').indexOf('a'.repeat(4), 'utf8'), 0) - t.equal(Buffer.from('aaaa').indexOf('你好', 'ucs2'), -1) - - // Haystack has odd length, but the needle is UCS2. - t.equal(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1) - - { - // Find substrings in Utf8. - const lengths = [1, 3, 15]; // Single char, simple and complex. - const indices = [0x5, 0x60, 0x400, 0x680, 0x7ee, 0xFF02, 0x16610, 0x2f77b] - for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) { - for (let i = 0; i < indices.length; i++) { - const index = indices[i] - let length = lengths[lengthIndex] - - if (index + length > 0x7F) { - length = 2 * length - } - - if (index + length > 0x7FF) { - length = 3 * length - } - - if (index + length > 0xFFFF) { - length = 4 * length - } - - const patternBufferUtf8 = allCharsBufferUtf8.slice(index, index + length) - t.equal(index, allCharsBufferUtf8.indexOf(patternBufferUtf8)) - - const patternStringUtf8 = patternBufferUtf8.toString() - t.equal(index, allCharsBufferUtf8.indexOf(patternStringUtf8)) - } - } - } - - { - // Find substrings in Usc2. - const lengths = [2, 4, 16]; // Single char, simple and complex. - const indices = [0x5, 0x65, 0x105, 0x205, 0x285, 0x2005, 0x2085, 0xfff0] - for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) { - for (let i = 0; i < indices.length; i++) { - const index = indices[i] * 2 - const length = lengths[lengthIndex] - - const patternBufferUcs2 = - allCharsBufferUcs2.slice(index, index + length) - t.equal( - index, allCharsBufferUcs2.indexOf(patternBufferUcs2, 0, 'ucs2')) - - const patternStringUcs2 = patternBufferUcs2.toString('ucs2') - t.equal( - index, allCharsBufferUcs2.indexOf(patternStringUcs2, 0, 'ucs2')) - } - } - } - - [ - () => {}, - {}, - [] - ].forEach(val => { - debugger - t.throws(() => b.indexOf(val), TypeError, `"${JSON.stringify(val)}" should throw`) - }) - - // Test weird offset arguments. - // The following offsets coerce to NaN or 0, searching the whole Buffer - t.equal(b.indexOf('b', undefined), 1) - t.equal(b.indexOf('b', {}), 1) - t.equal(b.indexOf('b', 0), 1) - t.equal(b.indexOf('b', null), 1) - t.equal(b.indexOf('b', []), 1) - - // The following offset coerces to 2, in other words +[2] === 2 - t.equal(b.indexOf('b', [2]), -1) - - // Behavior should match String.indexOf() - t.equal( - b.indexOf('b', undefined), - stringComparison.indexOf('b', undefined)) - t.equal( - b.indexOf('b', {}), - stringComparison.indexOf('b', {})) - t.equal( - b.indexOf('b', 0), - stringComparison.indexOf('b', 0)) - t.equal( - b.indexOf('b', null), - stringComparison.indexOf('b', null)) - t.equal( - b.indexOf('b', []), - stringComparison.indexOf('b', [])) - t.equal( - b.indexOf('b', [2]), - stringComparison.indexOf('b', [2])) - - // test truncation of Number arguments to uint8 - { - const buf = Buffer.from('this is a test') - t.equal(buf.indexOf(0x6973), 3) - t.equal(buf.indexOf(0x697320), 4) - t.equal(buf.indexOf(0x69732069), 2) - t.equal(buf.indexOf(0x697374657374), 0) - t.equal(buf.indexOf(0x69737374), 0) - t.equal(buf.indexOf(0x69737465), 11) - t.equal(buf.indexOf(0x69737465), 11) - t.equal(buf.indexOf(-140), 0) - t.equal(buf.indexOf(-152), 1) - t.equal(buf.indexOf(0xff), -1) - t.equal(buf.indexOf(0xffff), -1) - } - - // Test that Uint8Array arguments are okay. - { - const needle = new Uint8Array([ 0x66, 0x6f, 0x6f ]) - const haystack = new BufferList(Buffer.from('a foo b foo')) - t.equal(haystack.indexOf(needle), 2) - } - t.end() -}) diff --git a/node_modules/bl/test/test.js b/node_modules/bl/test/test.js deleted file mode 100644 index 475cda8..0000000 --- a/node_modules/bl/test/test.js +++ /dev/null @@ -1,766 +0,0 @@ -'use strict' - -var tape = require('tape') - , crypto = require('crypto') - , fs = require('fs') - , hash = require('hash_file') - , BufferList = require('../') - , Buffer = require('safe-buffer').Buffer - - , encodings = - ('hex utf8 utf-8 ascii binary base64' - + (process.browser ? '' : ' ucs2 ucs-2 utf16le utf-16le')).split(' ') - -// run the indexOf tests -require('./indexOf') - -tape('single bytes from single buffer', function (t) { - var bl = new BufferList() - bl.append(Buffer.from('abcd')) - - t.equal(bl.length, 4) - t.equal(bl.get(-1), undefined) - t.equal(bl.get(0), 97) - t.equal(bl.get(1), 98) - t.equal(bl.get(2), 99) - t.equal(bl.get(3), 100) - t.equal(bl.get(4), undefined) - - t.end() -}) - -tape('single bytes from multiple buffers', function (t) { - var bl = new BufferList() - bl.append(Buffer.from('abcd')) - bl.append(Buffer.from('efg')) - bl.append(Buffer.from('hi')) - bl.append(Buffer.from('j')) - - t.equal(bl.length, 10) - - t.equal(bl.get(0), 97) - t.equal(bl.get(1), 98) - t.equal(bl.get(2), 99) - t.equal(bl.get(3), 100) - t.equal(bl.get(4), 101) - t.equal(bl.get(5), 102) - t.equal(bl.get(6), 103) - t.equal(bl.get(7), 104) - t.equal(bl.get(8), 105) - t.equal(bl.get(9), 106) - t.end() -}) - -tape('multi bytes from single buffer', function (t) { - var bl = new BufferList() - bl.append(Buffer.from('abcd')) - - t.equal(bl.length, 4) - - t.equal(bl.slice(0, 4).toString('ascii'), 'abcd') - t.equal(bl.slice(0, 3).toString('ascii'), 'abc') - t.equal(bl.slice(1, 4).toString('ascii'), 'bcd') - t.equal(bl.slice(-4, -1).toString('ascii'), 'abc') - - t.end() -}) - -tape('multi bytes from single buffer (negative indexes)', function (t) { - var bl = new BufferList() - bl.append(Buffer.from('buffer')) - - t.equal(bl.length, 6) - - t.equal(bl.slice(-6, -1).toString('ascii'), 'buffe') - t.equal(bl.slice(-6, -2).toString('ascii'), 'buff') - t.equal(bl.slice(-5, -2).toString('ascii'), 'uff') - - t.end() -}) - -tape('multiple bytes from multiple buffers', function (t) { - var bl = new BufferList() - - bl.append(Buffer.from('abcd')) - bl.append(Buffer.from('efg')) - bl.append(Buffer.from('hi')) - bl.append(Buffer.from('j')) - - t.equal(bl.length, 10) - - t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') - t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') - t.equal(bl.slice(3, 6).toString('ascii'), 'def') - t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') - t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') - t.equal(bl.slice(-7, -4).toString('ascii'), 'def') - - t.end() -}) - -tape('multiple bytes from multiple buffer lists', function (t) { - var bl = new BufferList() - - bl.append(new BufferList([ Buffer.from('abcd'), Buffer.from('efg') ])) - bl.append(new BufferList([ Buffer.from('hi'), Buffer.from('j') ])) - - t.equal(bl.length, 10) - - t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') - - t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') - t.equal(bl.slice(3, 6).toString('ascii'), 'def') - t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') - t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') - - t.end() -}) - -// same data as previous test, just using nested constructors -tape('multiple bytes from crazy nested buffer lists', function (t) { - var bl = new BufferList() - - bl.append(new BufferList([ - new BufferList([ - new BufferList(Buffer.from('abc')) - , Buffer.from('d') - , new BufferList(Buffer.from('efg')) - ]) - , new BufferList([ Buffer.from('hi') ]) - , new BufferList(Buffer.from('j')) - ])) - - t.equal(bl.length, 10) - - t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') - - t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') - t.equal(bl.slice(3, 6).toString('ascii'), 'def') - t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') - t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') - - t.end() -}) - -tape('append accepts arrays of Buffers', function (t) { - var bl = new BufferList() - bl.append(Buffer.from('abc')) - bl.append([ Buffer.from('def') ]) - bl.append([ Buffer.from('ghi'), Buffer.from('jkl') ]) - bl.append([ Buffer.from('mnop'), Buffer.from('qrstu'), Buffer.from('vwxyz') ]) - t.equal(bl.length, 26) - t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz') - t.end() -}) - -tape('append accepts arrays of BufferLists', function (t) { - var bl = new BufferList() - bl.append(Buffer.from('abc')) - bl.append([ new BufferList('def') ]) - bl.append(new BufferList([ Buffer.from('ghi'), new BufferList('jkl') ])) - bl.append([ Buffer.from('mnop'), new BufferList([ Buffer.from('qrstu'), Buffer.from('vwxyz') ]) ]) - t.equal(bl.length, 26) - t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz') - t.end() -}) - -tape('append chainable', function (t) { - var bl = new BufferList() - t.ok(bl.append(Buffer.from('abcd')) === bl) - t.ok(bl.append([ Buffer.from('abcd') ]) === bl) - t.ok(bl.append(new BufferList(Buffer.from('abcd'))) === bl) - t.ok(bl.append([ new BufferList(Buffer.from('abcd')) ]) === bl) - t.end() -}) - -tape('append chainable (test results)', function (t) { - var bl = new BufferList('abc') - .append([ new BufferList('def') ]) - .append(new BufferList([ Buffer.from('ghi'), new BufferList('jkl') ])) - .append([ Buffer.from('mnop'), new BufferList([ Buffer.from('qrstu'), Buffer.from('vwxyz') ]) ]) - - t.equal(bl.length, 26) - t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz') - t.end() -}) - -tape('consuming from multiple buffers', function (t) { - var bl = new BufferList() - - bl.append(Buffer.from('abcd')) - bl.append(Buffer.from('efg')) - bl.append(Buffer.from('hi')) - bl.append(Buffer.from('j')) - - t.equal(bl.length, 10) - - t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') - - bl.consume(3) - t.equal(bl.length, 7) - t.equal(bl.slice(0, 7).toString('ascii'), 'defghij') - - bl.consume(2) - t.equal(bl.length, 5) - t.equal(bl.slice(0, 5).toString('ascii'), 'fghij') - - bl.consume(1) - t.equal(bl.length, 4) - t.equal(bl.slice(0, 4).toString('ascii'), 'ghij') - - bl.consume(1) - t.equal(bl.length, 3) - t.equal(bl.slice(0, 3).toString('ascii'), 'hij') - - bl.consume(2) - t.equal(bl.length, 1) - t.equal(bl.slice(0, 1).toString('ascii'), 'j') - - t.end() -}) - -tape('complete consumption', function (t) { - var bl = new BufferList() - - bl.append(Buffer.from('a')) - bl.append(Buffer.from('b')) - - bl.consume(2) - - t.equal(bl.length, 0) - t.equal(bl._bufs.length, 0) - - t.end() -}) - -tape('test readUInt8 / readInt8', function (t) { - var buf1 = Buffer.alloc(1) - , buf2 = Buffer.alloc(3) - , buf3 = Buffer.alloc(3) - , bl = new BufferList() - - buf2[1] = 0x3 - buf2[2] = 0x4 - buf3[0] = 0x23 - buf3[1] = 0x42 - - bl.append(buf1) - bl.append(buf2) - bl.append(buf3) - - t.equal(bl.readUInt8(2), 0x3) - t.equal(bl.readInt8(2), 0x3) - t.equal(bl.readUInt8(3), 0x4) - t.equal(bl.readInt8(3), 0x4) - t.equal(bl.readUInt8(4), 0x23) - t.equal(bl.readInt8(4), 0x23) - t.equal(bl.readUInt8(5), 0x42) - t.equal(bl.readInt8(5), 0x42) - t.end() -}) - -tape('test readUInt16LE / readUInt16BE / readInt16LE / readInt16BE', function (t) { - var buf1 = Buffer.alloc(1) - , buf2 = Buffer.alloc(3) - , buf3 = Buffer.alloc(3) - , bl = new BufferList() - - buf2[1] = 0x3 - buf2[2] = 0x4 - buf3[0] = 0x23 - buf3[1] = 0x42 - - bl.append(buf1) - bl.append(buf2) - bl.append(buf3) - - t.equal(bl.readUInt16BE(2), 0x0304) - t.equal(bl.readUInt16LE(2), 0x0403) - t.equal(bl.readInt16BE(2), 0x0304) - t.equal(bl.readInt16LE(2), 0x0403) - t.equal(bl.readUInt16BE(3), 0x0423) - t.equal(bl.readUInt16LE(3), 0x2304) - t.equal(bl.readInt16BE(3), 0x0423) - t.equal(bl.readInt16LE(3), 0x2304) - t.equal(bl.readUInt16BE(4), 0x2342) - t.equal(bl.readUInt16LE(4), 0x4223) - t.equal(bl.readInt16BE(4), 0x2342) - t.equal(bl.readInt16LE(4), 0x4223) - t.end() -}) - -tape('test readUInt32LE / readUInt32BE / readInt32LE / readInt32BE', function (t) { - var buf1 = Buffer.alloc(1) - , buf2 = Buffer.alloc(3) - , buf3 = Buffer.alloc(3) - , bl = new BufferList() - - buf2[1] = 0x3 - buf2[2] = 0x4 - buf3[0] = 0x23 - buf3[1] = 0x42 - - bl.append(buf1) - bl.append(buf2) - bl.append(buf3) - - t.equal(bl.readUInt32BE(2), 0x03042342) - t.equal(bl.readUInt32LE(2), 0x42230403) - t.equal(bl.readInt32BE(2), 0x03042342) - t.equal(bl.readInt32LE(2), 0x42230403) - t.end() -}) - -tape('test readUIntLE / readUIntBE / readIntLE / readIntBE', function (t) { - var buf1 = Buffer.alloc(1) - , buf2 = Buffer.alloc(3) - , buf3 = Buffer.alloc(3) - , bl = new BufferList() - - buf2[0] = 0x2 - buf2[1] = 0x3 - buf2[2] = 0x4 - buf3[0] = 0x23 - buf3[1] = 0x42 - buf3[2] = 0x61 - - bl.append(buf1) - bl.append(buf2) - bl.append(buf3) - - t.equal(bl.readUIntBE(1, 1), 0x02) - t.equal(bl.readUIntBE(1, 2), 0x0203) - t.equal(bl.readUIntBE(1, 3), 0x020304) - t.equal(bl.readUIntBE(1, 4), 0x02030423) - t.equal(bl.readUIntBE(1, 5), 0x0203042342) - t.equal(bl.readUIntBE(1, 6), 0x020304234261) - t.equal(bl.readUIntLE(1, 1), 0x02) - t.equal(bl.readUIntLE(1, 2), 0x0302) - t.equal(bl.readUIntLE(1, 3), 0x040302) - t.equal(bl.readUIntLE(1, 4), 0x23040302) - t.equal(bl.readUIntLE(1, 5), 0x4223040302) - t.equal(bl.readUIntLE(1, 6), 0x614223040302) - t.equal(bl.readIntBE(1, 1), 0x02) - t.equal(bl.readIntBE(1, 2), 0x0203) - t.equal(bl.readIntBE(1, 3), 0x020304) - t.equal(bl.readIntBE(1, 4), 0x02030423) - t.equal(bl.readIntBE(1, 5), 0x0203042342) - t.equal(bl.readIntBE(1, 6), 0x020304234261) - t.equal(bl.readIntLE(1, 1), 0x02) - t.equal(bl.readIntLE(1, 2), 0x0302) - t.equal(bl.readIntLE(1, 3), 0x040302) - t.equal(bl.readIntLE(1, 4), 0x23040302) - t.equal(bl.readIntLE(1, 5), 0x4223040302) - t.equal(bl.readIntLE(1, 6), 0x614223040302) - t.end() -}) - -tape('test readFloatLE / readFloatBE', function (t) { - var buf1 = Buffer.alloc(1) - , buf2 = Buffer.alloc(3) - , buf3 = Buffer.alloc(3) - , bl = new BufferList() - - buf2[1] = 0x00 - buf2[2] = 0x00 - buf3[0] = 0x80 - buf3[1] = 0x3f - - bl.append(buf1) - bl.append(buf2) - bl.append(buf3) - - t.equal(bl.readFloatLE(2), 0x01) - t.end() -}) - -tape('test readDoubleLE / readDoubleBE', function (t) { - var buf1 = Buffer.alloc(1) - , buf2 = Buffer.alloc(3) - , buf3 = Buffer.alloc(10) - , bl = new BufferList() - - buf2[1] = 0x55 - buf2[2] = 0x55 - buf3[0] = 0x55 - buf3[1] = 0x55 - buf3[2] = 0x55 - buf3[3] = 0x55 - buf3[4] = 0xd5 - buf3[5] = 0x3f - - bl.append(buf1) - bl.append(buf2) - bl.append(buf3) - - t.equal(bl.readDoubleLE(2), 0.3333333333333333) - t.end() -}) - -tape('test toString', function (t) { - var bl = new BufferList() - - bl.append(Buffer.from('abcd')) - bl.append(Buffer.from('efg')) - bl.append(Buffer.from('hi')) - bl.append(Buffer.from('j')) - - t.equal(bl.toString('ascii', 0, 10), 'abcdefghij') - t.equal(bl.toString('ascii', 3, 10), 'defghij') - t.equal(bl.toString('ascii', 3, 6), 'def') - t.equal(bl.toString('ascii', 3, 8), 'defgh') - t.equal(bl.toString('ascii', 5, 10), 'fghij') - - t.end() -}) - -tape('test toString encoding', function (t) { - var bl = new BufferList() - , b = Buffer.from('abcdefghij\xff\x00') - - bl.append(Buffer.from('abcd')) - bl.append(Buffer.from('efg')) - bl.append(Buffer.from('hi')) - bl.append(Buffer.from('j')) - bl.append(Buffer.from('\xff\x00')) - - encodings.forEach(function (enc) { - t.equal(bl.toString(enc), b.toString(enc), enc) - }) - - t.end() -}) - -!process.browser && tape('test stream', function (t) { - var random = crypto.randomBytes(65534) - , rndhash = hash(random, 'md5') - , md5sum = crypto.createHash('md5') - , bl = new BufferList(function (err, buf) { - t.ok(Buffer.isBuffer(buf)) - t.ok(err === null) - t.equal(rndhash, hash(bl.slice(), 'md5')) - t.equal(rndhash, hash(buf, 'md5')) - - bl.pipe(fs.createWriteStream('/tmp/bl_test_rnd_out.dat')) - .on('close', function () { - var s = fs.createReadStream('/tmp/bl_test_rnd_out.dat') - s.on('data', md5sum.update.bind(md5sum)) - s.on('end', function() { - t.equal(rndhash, md5sum.digest('hex'), 'woohoo! correct hash!') - t.end() - }) - }) - - }) - - fs.writeFileSync('/tmp/bl_test_rnd.dat', random) - fs.createReadStream('/tmp/bl_test_rnd.dat').pipe(bl) -}) - -tape('instantiation with Buffer', function (t) { - var buf = crypto.randomBytes(1024) - , buf2 = crypto.randomBytes(1024) - , b = BufferList(buf) - - t.equal(buf.toString('hex'), b.slice().toString('hex'), 'same buffer') - b = BufferList([ buf, buf2 ]) - t.equal(b.slice().toString('hex'), Buffer.concat([ buf, buf2 ]).toString('hex'), 'same buffer') - t.end() -}) - -tape('test String appendage', function (t) { - var bl = new BufferList() - , b = Buffer.from('abcdefghij\xff\x00') - - bl.append('abcd') - bl.append('efg') - bl.append('hi') - bl.append('j') - bl.append('\xff\x00') - - encodings.forEach(function (enc) { - t.equal(bl.toString(enc), b.toString(enc)) - }) - - t.end() -}) - -tape('test Number appendage', function (t) { - var bl = new BufferList() - , b = Buffer.from('1234567890') - - bl.append(1234) - bl.append(567) - bl.append(89) - bl.append(0) - - encodings.forEach(function (enc) { - t.equal(bl.toString(enc), b.toString(enc)) - }) - - t.end() -}) - -tape('write nothing, should get empty buffer', function (t) { - t.plan(3) - BufferList(function (err, data) { - t.notOk(err, 'no error') - t.ok(Buffer.isBuffer(data), 'got a buffer') - t.equal(0, data.length, 'got a zero-length buffer') - t.end() - }).end() -}) - -tape('unicode string', function (t) { - t.plan(2) - var inp1 = '\u2600' - , inp2 = '\u2603' - , exp = inp1 + ' and ' + inp2 - , bl = BufferList() - bl.write(inp1) - bl.write(' and ') - bl.write(inp2) - t.equal(exp, bl.toString()) - t.equal(Buffer.from(exp).toString('hex'), bl.toString('hex')) -}) - -tape('should emit finish', function (t) { - var source = BufferList() - , dest = BufferList() - - source.write('hello') - source.pipe(dest) - - dest.on('finish', function () { - t.equal(dest.toString('utf8'), 'hello') - t.end() - }) -}) - -tape('basic copy', function (t) { - var buf = crypto.randomBytes(1024) - , buf2 = Buffer.alloc(1024) - , b = BufferList(buf) - - b.copy(buf2) - t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer') - t.end() -}) - -tape('copy after many appends', function (t) { - var buf = crypto.randomBytes(512) - , buf2 = Buffer.alloc(1024) - , b = BufferList(buf) - - b.append(buf) - b.copy(buf2) - t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer') - t.end() -}) - -tape('copy at a precise position', function (t) { - var buf = crypto.randomBytes(1004) - , buf2 = Buffer.alloc(1024) - , b = BufferList(buf) - - b.copy(buf2, 20) - t.equal(b.slice().toString('hex'), buf2.slice(20).toString('hex'), 'same buffer') - t.end() -}) - -tape('copy starting from a precise location', function (t) { - var buf = crypto.randomBytes(10) - , buf2 = Buffer.alloc(5) - , b = BufferList(buf) - - b.copy(buf2, 0, 5) - t.equal(b.slice(5).toString('hex'), buf2.toString('hex'), 'same buffer') - t.end() -}) - -tape('copy in an interval', function (t) { - var rnd = crypto.randomBytes(10) - , b = BufferList(rnd) // put the random bytes there - , actual = Buffer.alloc(3) - , expected = Buffer.alloc(3) - - rnd.copy(expected, 0, 5, 8) - b.copy(actual, 0, 5, 8) - - t.equal(actual.toString('hex'), expected.toString('hex'), 'same buffer') - t.end() -}) - -tape('copy an interval between two buffers', function (t) { - var buf = crypto.randomBytes(10) - , buf2 = Buffer.alloc(10) - , b = BufferList(buf) - - b.append(buf) - b.copy(buf2, 0, 5, 15) - - t.equal(b.slice(5, 15).toString('hex'), buf2.toString('hex'), 'same buffer') - t.end() -}) - -tape('shallow slice across buffer boundaries', function (t) { - var bl = new BufferList(['First', 'Second', 'Third']) - - t.equal(bl.shallowSlice(3, 13).toString(), 'stSecondTh') - t.end() -}) - -tape('shallow slice within single buffer', function (t) { - t.plan(2) - var bl = new BufferList(['First', 'Second', 'Third']) - - t.equal(bl.shallowSlice(5, 10).toString(), 'Secon') - t.equal(bl.shallowSlice(7, 10).toString(), 'con') - t.end() -}) - -tape('shallow slice single buffer', function (t) { - t.plan(3) - var bl = new BufferList(['First', 'Second', 'Third']) - - t.equal(bl.shallowSlice(0, 5).toString(), 'First') - t.equal(bl.shallowSlice(5, 11).toString(), 'Second') - t.equal(bl.shallowSlice(11, 16).toString(), 'Third') -}) - -tape('shallow slice with negative or omitted indices', function (t) { - t.plan(4) - var bl = new BufferList(['First', 'Second', 'Third']) - - t.equal(bl.shallowSlice().toString(), 'FirstSecondThird') - t.equal(bl.shallowSlice(5).toString(), 'SecondThird') - t.equal(bl.shallowSlice(5, -3).toString(), 'SecondTh') - t.equal(bl.shallowSlice(-8).toString(), 'ondThird') -}) - -tape('shallow slice does not make a copy', function (t) { - t.plan(1) - var buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')] - var bl = (new BufferList(buffers)).shallowSlice(5, -3) - - buffers[1].fill('h') - buffers[2].fill('h') - - t.equal(bl.toString(), 'hhhhhhhh') -}) - -tape('shallow slice with 0 length', function (t) { - t.plan(1) - var buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')] - var bl = (new BufferList(buffers)).shallowSlice(0, 0) - t.equal(bl.length, 0) -}) - -tape('shallow slice with 0 length from middle', function (t) { - t.plan(1) - var buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')] - var bl = (new BufferList(buffers)).shallowSlice(10, 10) - t.equal(bl.length, 0) -}) - -tape('duplicate', function (t) { - t.plan(2) - - var bl = new BufferList('abcdefghij\xff\x00') - , dup = bl.duplicate() - - t.equal(bl.prototype, dup.prototype) - t.equal(bl.toString('hex'), dup.toString('hex')) -}) - -tape('destroy no pipe', function (t) { - t.plan(2) - - var bl = new BufferList('alsdkfja;lsdkfja;lsdk') - bl.destroy() - - t.equal(bl._bufs.length, 0) - t.equal(bl.length, 0) -}) - -!process.browser && tape('destroy with pipe before read end', function (t) { - t.plan(2) - - var bl = new BufferList() - fs.createReadStream(__dirname + '/test.js') - .pipe(bl) - - bl.destroy() - - t.equal(bl._bufs.length, 0) - t.equal(bl.length, 0) - -}) - -!process.browser && tape('destroy with pipe before read end with race', function (t) { - t.plan(2) - - var bl = new BufferList() - fs.createReadStream(__dirname + '/test.js') - .pipe(bl) - - setTimeout(function () { - bl.destroy() - setTimeout(function () { - t.equal(bl._bufs.length, 0) - t.equal(bl.length, 0) - }, 500) - }, 500) -}) - -!process.browser && tape('destroy with pipe after read end', function (t) { - t.plan(2) - - var bl = new BufferList() - fs.createReadStream(__dirname + '/test.js') - .on('end', onEnd) - .pipe(bl) - - function onEnd () { - bl.destroy() - - t.equal(bl._bufs.length, 0) - t.equal(bl.length, 0) - } -}) - -!process.browser && tape('destroy with pipe while writing to a destination', function (t) { - t.plan(4) - - var bl = new BufferList() - , ds = new BufferList() - - fs.createReadStream(__dirname + '/test.js') - .on('end', onEnd) - .pipe(bl) - - function onEnd () { - bl.pipe(ds) - - setTimeout(function () { - bl.destroy() - - t.equals(bl._bufs.length, 0) - t.equals(bl.length, 0) - - ds.destroy() - - t.equals(bl._bufs.length, 0) - t.equals(bl.length, 0) - - }, 100) - } -}) - -!process.browser && tape('handle error', function (t) { - t.plan(2) - fs.createReadStream('/does/not/exist').pipe(BufferList(function (err, data) { - t.ok(err instanceof Error, 'has error') - t.notOk(data, 'no data') - })) -}) diff --git a/node_modules/bluebird/LICENSE b/node_modules/bluebird/LICENSE deleted file mode 100644 index ae732d5..0000000 --- a/node_modules/bluebird/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013-2017 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 deleted file mode 100644 index ba82f73..0000000 --- a/node_modules/bluebird/README.md +++ /dev/null @@ -1,52 +0,0 @@ - - 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). - -# 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-2017 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 deleted file mode 100644 index 73b2eb6..0000000 --- a/node_modules/bluebird/changelog.md +++ /dev/null @@ -1 +0,0 @@ -[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 deleted file mode 100644 index 85b7791..0000000 --- a/node_modules/bluebird/js/browser/bluebird.core.js +++ /dev/null @@ -1,3781 +0,0 @@ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2017 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.5.1 - * 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) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - continue; - } - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } -}; - -Async.prototype._drainQueues = function () { - this._drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - this._drainQueue(this._lateQueue); -}; - -Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } -}; - -Async.prototype._reset = function () { - this._isTickUsed = false; -}; - -module.exports = Async; -module.exports.firstLineError = firstLineError; - -},{"./queue":17,"./schedule":18,"./util":21}],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) { -var getDomain = Promise._getDomain; -var async = Promise._async; -var Warning = _dereq_("./errors").Warning; -var util = _dereq_("./util"); -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")); - -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(); - var self = this; - setTimeout(function() { - self._notifyUnhandledRejection(); - }, 1); -}; - -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 domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -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; - 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; - Context.deactivateLongStackTraces(); - async.enableTrampoline(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); - } -}; - -Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); -}; - -var fireDomEvent = (function() { - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new CustomEvent(name.toLowerCase(), { - detail: event, - cancelable: true - }); - return !util.global.dispatchEvent(domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new Event(name.toLowerCase(), { - cancelable: true - }); - domEvent.detail = event; - return !util.global.dispatchEvent(domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name.toLowerCase(), false, true, - event); - return !util.global.dispatchEvent(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; - } - } - 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._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 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 -}; - -if (longStackTraces) Promise.longStackTraces(); - -return { - 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,"./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, - getDomain) { -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 domain = getDomain(); - if (domain !== null) { - holder.fn = util.domainBind(domain, 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"); - -var getDomain; -if (util.isNode) { - getDomain = function() { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; -} else { - getDomain = function() { - return null; - }; -} -util.notEnumerableProp(Promise, "_getDomain", getDomain); - -var 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); -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]; - 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 domain = getDomain(); - 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: domain === null ? handler - : (typeof handler === "function" && - util.domainBind(domain, handler)), - promise: promise, - receiver: receiver, - value: value - }); - } else { - target._addCallbacks(didFulfill, didReject, promise, receiver, domain); - } - - 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; - this._bitField = this._bitField | 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, - domain -) { - 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 = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : util.domainBind(domain, reject); - } - } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - domain === null ? reject : util.domainBind(domain, 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(promise); - } 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); - } - } -}; - -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; - } -}; - -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, getDomain); -Promise.Promise = Promise; -Promise.version = "3.5.1"; - - 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}],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); - } - 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))) { - 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 l = 8; - while (l--) new FakeConstructor(); - 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 ({}.toString.call(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } -} - -function domainBind(self, cb) { - return self.bind(cb); -} - -var ret = { - 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, - hasDevTools: typeof chrome !== "undefined" && chrome && - typeof chrome.loadTimes === "function", - isNode: isNode, - hasEnvVariables: hasEnvVariables, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - domainBind: domainBind -}; -ret.isRecentNode = ret.isNode && (function() { - var version = process.versions.node.split(".").map(Number); - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); -})(); - -if (ret.isNode) ret.toFastProperties(process); - -try {throw new Error(); } catch (e) {ret.lastLineError = e;} -module.exports = ret; - -},{"./es5":10}]},{},[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 deleted file mode 100644 index 6aca6aa..0000000 --- a/node_modules/bluebird/js/browser/bluebird.core.min.js +++ /dev/null @@ -1,31 +0,0 @@ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2017 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.5.1 - * 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 i(a,s){if(!e[a]){if(!t[a]){var c="function"==typeof _dereq_&&_dereq_;if(!s&&c)return c(a,!0);if(o)return o(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 i(n?n:e)},u,u.exports,r,t,e,n)}return e[a].exports}for(var o="function"==typeof _dereq_&&_dereq_,a=0;a0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=r,e.exports.firstLineError=s},{"./queue":17,"./schedule":18,"./util":21}],2:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},a=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,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(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var l=n(o),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===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":15}],4:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),a=o.tryCatch,s=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,a=t._peekContext,s=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=o,t._peekContext=a,t.prototype._peekContext=s,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}},{}],7:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,e){return{promise:e}}function i(){return!1}function o(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: "+I.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function a(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?I.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function s(){return this._onCancelField}function c(t){this._onCancelField=t}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function u(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 p(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function f(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function h(){this._trace=new x(this._peekContext())}function _(t,e){if(H(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=E(t);I.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),I.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(t,e,n,r,i){if(void 0===t&&null!==e&&X){if(void 0!==i&&i._returnedNonUndefined())return;if(0===(65535&r._bitField))return;n&&(n+=" ");var o="",a="";if(e._trace){for(var s=e._trace.stack.split("\n"),c=C(s),l=c.length-1;l>=0;--l){var u=c[l];if(!V.test(u)){var p=u.match(Q);p&&(o="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 "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+a;r._warn(h,!0,e)}}function v(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),y(n)}function y(t,n,r){if(ot.warnings){var i,o=new U(t);if(n)r._attachExtraTrace(o);else if(ot.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var a=E(o);o.stack=a.message+"\n"+a.stack.join("\n")}tt("warning",o)||k(o,"",!0)}}function g(t,e){for(var n=0;n=0;--s)if(r[s]===o){a=s;break}for(var s=a;s>=0;--s){var c=r[s];if(e[i]!==c)break;e.pop(),i--}e=r}}function C(t){for(var e=[],n=0;n0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function E(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?w(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:C(e)}}function k(t,e,n){if("undefined"!=typeof console){var r;if(I.isObject(t)){var i=t.stack;r=e+G(i,t)}else r=e+String(t);"function"==typeof N?N(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function j(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){B.throwLater(o)}"unhandledRejection"===t?tt(t,n,r)||i||k(n,"Unhandled rejection "):tt(t,r)}function F(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():I.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"(<"+T(e)+">, no stack trace)"}function T(t){var e=41;return t.lengtha||0>s||!n||!r||n!==r||a>=s||(nt=function(t){if(D.test(t))return!0;var e=R(t);return e&&e.fileName===n&&a<=e.line&&e.line<=s?!0:!1})}}function x(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);it(this,x),e>32&&this.uncycle()}var O,A,N,L=e._getDomain,B=e._async,U=t("./errors").Warning,I=t("./util"),H=I.canAttachTrace,D=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,V=/\((?:timers\.js):\d+:\d+\)/,Q=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,q=null,G=null,M=!1,W=!(0==I.env("BLUEBIRD_DEBUG")||!I.env("BLUEBIRD_DEBUG")&&"development"!==I.env("NODE_ENV")),$=!(0==I.env("BLUEBIRD_WARNINGS")||!W&&!I.env("BLUEBIRD_WARNINGS")),z=!(0==I.env("BLUEBIRD_LONG_STACK_TRACES")||!W&&!I.env("BLUEBIRD_LONG_STACK_TRACES")),X=0!=I.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&($||!!I.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){if(0===(524288&this._bitField)){this._setRejectionIsUnhandled();var t=this;setTimeout(function(){t._notifyUnhandledRejection()},1)}},e.prototype._notifyUnhandledRejectionIsHandled=function(){j("rejectionHandled",O,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),j("unhandledRejection",A,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},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 y(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=L();A="function"==typeof t?null===e?t:I.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=L();O="function"==typeof t?null===e?t:I.domainBind(e,t):void 0};var K=function(){};e.longStackTraces=function(){if(B.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!ot.longStackTraces&&P()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;ot.longStackTraces=!0,K=function(){if(B.haveItemsQueued()&&!ot.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,n.deactivateLongStackTraces(),B.enableTrampoline(),ot.longStackTraces=!1},e.prototype._captureStackTrace=h,e.prototype._attachExtraTrace=_,n.activateLongStackTraces(),B.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return ot.longStackTraces&&P()};var J=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return I.global.dispatchEvent(t),function(t,e){var n=new CustomEvent(t.toLowerCase(),{detail:e,cancelable:!0});return!I.global.dispatchEvent(n)}}if("function"==typeof Event){var t=new Event("CustomEvent");return I.global.dispatchEvent(t),function(t,e){var n=new Event(t.toLowerCase(),{cancelable:!0});return n.detail=e,!I.global.dispatchEvent(n)}}var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),I.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!I.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),Y=function(){return I.isNode?function(){return process.emit.apply(process,arguments)}:I.global?function(t){var e="on"+t.toLowerCase(),n=I.global[e];return n?(n.apply(I.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),Z={promiseCreated:r,promiseFulfilled:r,promiseRejected:r,promiseResolved:r,promiseCancelled:r,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:r},tt=function(t){var e=!1;try{e=Y.apply(null,arguments)}catch(n){B.throwLater(n),e=!0}var r=!1;try{r=J(t,Z[t].apply(null,arguments))}catch(n){B.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()&&K()),"warnings"in t){var n=t.warnings;ot.warnings=!!n,X=ot.warnings,I.isObject(n)&&"wForgottenReturn"in n&&(X=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!ot.cancellation){if(B.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=l,e.prototype._propagateFrom=u,e.prototype._onCancel=s,e.prototype._setOnCancel=c,e.prototype._attachCancellationCallback=a,e.prototype._execute=o,et=u,ot.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!ot.monitoring?(ot.monitoring=!0,e.prototype._fireEvent=tt):!t.monitoring&&ot.monitoring&&(ot.monitoring=!1,e.prototype._fireEvent=i)),e},e.prototype._fireEvent=i,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._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var et=p,nt=function(){return!1},rt=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;I.inherits(x,Error),n.CapturedTrace=x,x.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 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}}}},x.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=E(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(C(i.stack.split("\n"))),i=i._parent;b(r),m(r),I.notEnumerableProp(t,"stack",g(n,r)),I.notEnumerableProp(t,"__stackCleaned__",!0)}};var it=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():F(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,q=t,G=e;var n=Error.captureStackTrace;return nt=function(t){return D.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 q=/@/,G=e,M=!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?(G=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?F(e):e.toString()},null):(q=t,G=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&&(N=function(t){console.warn(t)},I.isNode&&process.stderr.isTTY?N=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:I.isNode||"string"!=typeof(new Error).stack||(N=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var ot={warnings:$,longStackTraces:!1,cancellation:!1,monitoring:!1};return z&&e.longStackTraces(),{longStackTraces:function(){return ot.longStackTraces},warnings:function(){return ot.warnings},cancellation:function(){return ot.cancellation},monitoring:function(){return ot.monitoring},propagateFromFunction:function(){return et},boundValueFunction:function(){return f},checkForgottenReturns:d,setBounds:S,warn:y,deprecated:v,CapturedTrace:x,fireDomEvent:J,fireGlobalEvent:Y}}},{"./errors":9,"./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 i=function(){return r};return this.caught(n,i)}}},{}],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 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,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"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,a=RangeError}catch(v){o=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 i=this.promise,l=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?l.call(i._boundValue()):l.call(i._boundValue(),t);if(u===r)return u;if(void 0!==u){i._setReturnedNonUndefined();var h=n(u,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(s,c,void 0,this,void 0)}}}return i.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 i.prototype.isFinallyHandler=function(){return 0===this.type},o.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 i(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,i=new Array(n-1),o=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)));i[o++]=a}i.length=o;var s=arguments[r];return this._passThrough(h(i,s,this),1,void 0,l)},i}},{"./catch_filter":5,"./util":21}],12:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,a){var s=t("./util");s.canEvaluate,s.tryCatch,s.errorObj;e.join=function(){var t,e=arguments.length-1;if(e>0&&"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":21}],13:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){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 i=s(t).apply(this,arguments),a=r._popContext();return o.checkForgottenReturns(i,a,"Promise.method",r),r._resolveFromSyncValue(i),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return i("expecting a function but got "+a.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 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 o.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 i(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),i=0;i1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!h.isObject(o))return p("Catch statement predicate: expecting an object but got "+h.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,P(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(F.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+h.classString(t);arguments.length>1&&(n+=", "+h.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?p("expecting a function but got "+h.classString(t)):this.all()._then(t,void 0,void 0,C,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 k(this).promise()},i.prototype.error=function(t){return this.caught(h.originatesFromRejection,t)},i.getNewLibraryCopy=e.exports,i.is=function(t){return t instanceof i},i.fromNode=i.fromCallback=function(t){var e=new i(b);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=x(t)(R(e,n));return r===S&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new k(t).promise()},i.cast=function(t){var e=E(t);return e instanceof i||(e=new i(b),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new g("expecting a function but got "+h.classString(t));return v.setScheduler(t)},i.prototype._then=function(t,e,n,r,o){var a=void 0!==o,s=a?o:new i(b),l=this._target(),u=l._bitField;a||(s._propagateFrom(this,3),s._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,s));var p=c();if(0!==(50397184&u)){var f,_,d=l._settlePromiseCtx;0!==(33554432&u)?(_=l._rejectionHandler0,f=t):0!==(16777216&u)?(_=l._fulfillmentHandler0,f=e,l._unsetRejectionIsUnhandled()):(d=l._settlePromiseLateCancellationObserver,_=new m("late cancellation observer"),l._attachExtraTrace(_),f=e),v.invoke(d,l,{handler:null===p?f:"function"==typeof f&&h.domainBind(p,f),promise:s,receiver:r,value:_})}else l._addCallbacks(t,e,s,r,p);return s},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(){v.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===f?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=f),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=f),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=null===i?t:h.domainBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:h.domainBind(i,e));else{var a=4*o-4;this[a+2]=n,this[a+3]=r,"function"==typeof t&&(this[a+0]=null===i?t:h.domainBind(i,t)),"function"==typeof e&&(this[a+1]=null===i?e:h.domainBind(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(l(),!1);var n=E(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(l());var o=r._bitField;if(0===(50397184&o)){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(r)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var c=new m("late cancellation observer");r._attachExtraTrace(c),this._reject(c)}}},i.prototype._rejectCallback=function(t,e,n){var r=h.ensureErrorObject(t),i=r===t;if(!i&&!n&&F.warnings()){var o="a promise was rejected with a non-error: "+h.classString(t);this._warn(o,!0)}this._attachExtraTrace(r,e?i:!1),this._reject(t)},i.prototype._resolveFromExecutor=function(t){if(t!==b){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===C?n&&"number"==typeof n.length?o=x(t).apply(this._boundValue(),n):(o=S,o.e=new g("cannot .spread() a non-array: "+h.classString(n))):o=x(t).call(e,n);var a=r._popContext();i=r._bitField,0===(65536&i)&&(o===w?r._reject(n):o===S?r._rejectCallback(o.e,!1):(F.checkForgottenReturns(o,a,"",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 a=t instanceof i,s=this._bitField,c=0!==(134217728&s);0!==(65536&s)?(a&&t._invokeInternalOnCancel(),r instanceof T&&r.isFinallyHandler()?(r.cancelPromise=t,x(e).call(r,o)===S&&t._reject(S.e)):e===u?t._fulfill(u.call(r)):r instanceof n?r._promiseCancelled(t):a||t instanceof k?t._cancel():r.cancel()):"function"==typeof e?a?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,r,o,t)):e.call(r,o,t):r instanceof n?r._isResolved()||(0!==(33554432&s)?r._promiseFulfilled(o,t):r._promiseRejected(o,t)):a&&(c&&t._setAsyncGuaranteed(),0!==(33554432&s)?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=l();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():v.settlePromises(this))}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?v.fatalError(t,h.isNode):void((65535&e)>0?v.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},i.defer=i.pending=function(){F.deprecated("Promise.defer","new Promise");var t=new i(b);return{promise:t,resolve:o,reject:a}},h.notEnumerableProp(i,"_makeSelfResolutionError",l),t("./method")(i,b,E,p,F),t("./bind")(i,b,E,F),t("./cancel")(i,k,p,F),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,k,E,b,v,c),i.Promise=i,i.version="3.5.1",h.toFastProperties(i),h.toFastProperties(i.prototype),s({a:1}),s({b:2}),s({c:3}),s(1),s(function(){}),s(void 0),s(!1),s(new i(b)),F.setBounds(d.firstLineError,h.lastLineError),i}},{"./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}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){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),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,o),s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function l(t,n){var o=r(this._values,this._promise);if(o instanceof e){o=o._target();var s=o._bitField;if(this._values=o,0===(50397184&s))return this._promise._setAsyncGuaranteed(),o._then(l,this._reject,void 0,this,n);if(0===(33554432&s))return 0!==(16777216&s)?this._reject(o._reason()):this._cancel();o=o._value()}if(o=c.asArray(o),null===o){var u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(a(n))):void this._iterate(o)},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 i=this._promise,o=!1,a=null,s=0;n>s;++s){var c=r(t[s],i);c instanceof e?(c=c._target(),a=c._bitField):a=null,o?null!==a&&c.suppressUnhandledRejections():null!==a?0===(50397184&a)?(c._proxy(this,s),this._values[s]=c):o=0!==(33554432&a)?this._promiseFulfilled(c._value(),s):0!==(16777216&a)?this._promiseRejected(c._reason(),s):this._promiseCancelled(s):o=this._promiseFulfilled(c,s)}o||i._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;no;++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._capacityn;++n)i[n]=t[n];return i[n]=e,i}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(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(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return N.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{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),i=0;i10||t[0]>0}(),D.isNode&&D.toFastProperties(process);try{throw new Error}catch(V){D.lastLineError=V}e.exports=D},{"./es5":10}]},{},[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 deleted file mode 100644 index 2bc524b..0000000 --- a/node_modules/bluebird/js/browser/bluebird.js +++ /dev/null @@ -1,5623 +0,0 @@ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2017 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.5.1 - * 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) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - continue; - } - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } -}; - -Async.prototype._drainQueues = function () { - this._drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - this._drainQueue(this._lateQueue); -}; - -Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } -}; - -Async.prototype._reset = function () { - this._isTickUsed = false; -}; - -module.exports = Async; -module.exports.firstLineError = firstLineError; - -},{"./queue":26,"./schedule":29,"./util":36}],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) { -var getDomain = Promise._getDomain; -var async = Promise._async; -var Warning = _dereq_("./errors").Warning; -var util = _dereq_("./util"); -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")); - -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(); - var self = this; - setTimeout(function() { - self._notifyUnhandledRejection(); - }, 1); -}; - -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 domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -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; - 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; - Context.deactivateLongStackTraces(); - async.enableTrampoline(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); - } -}; - -Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); -}; - -var fireDomEvent = (function() { - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new CustomEvent(name.toLowerCase(), { - detail: event, - cancelable: true - }); - return !util.global.dispatchEvent(domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new Event(name.toLowerCase(), { - cancelable: true - }); - domEvent.detail = event; - return !util.global.dispatchEvent(domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name.toLowerCase(), false, true, - event); - return !util.global.dispatchEvent(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; - } - } - 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._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 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 -}; - -if (longStackTraces) Promise.longStackTraces(); - -return { - 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,"./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, - getDomain) { -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 domain = getDomain(); - if (domain !== null) { - holder.fn = util.domainBind(domain, 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 getDomain = Promise._getDomain; -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 domain = getDomain(); - this._callback = domain === null ? fn : util.domainBind(domain, fn); - this._preservedValues = _filter === INTERNAL - ? new Array(this.length()) - : null; - this._limit = limit; - this._inFlight = 0; - this._queue = []; - async.invoke(this._asyncInit, this, undefined); -} -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"); - -var getDomain; -if (util.isNode) { - getDomain = function() { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; -} else { - getDomain = function() { - return null; - }; -} -util.notEnumerableProp(Promise, "_getDomain", getDomain); - -var 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); -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]; - 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 domain = getDomain(); - 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: domain === null ? handler - : (typeof handler === "function" && - util.domainBind(domain, handler)), - promise: promise, - receiver: receiver, - value: value - }); - } else { - target._addCallbacks(didFulfill, didReject, promise, receiver, domain); - } - - 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; - this._bitField = this._bitField | 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, - domain -) { - 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 = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : util.domainBind(domain, reject); - } - } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - domain === null ? reject : util.domainBind(domain, 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(promise); - } 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); - } - } -}; - -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; - } -}; - -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, getDomain); -Promise.Promise = Promise; -Promise.version = "3.5.1"; -_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -_dereq_('./call_get.js')(Promise); -_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); -_dereq_('./timers.js')(Promise, INTERNAL, debug); -_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, 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_('./filter.js')(Promise, INTERNAL); -_dereq_('./each.js')(Promise, INTERNAL); -_dereq_('./any.js')(Promise); - - 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}],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); - } - 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 getDomain = Promise._getDomain; -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; - -function ReductionPromiseArray(promises, fn, initialValue, _each) { - this.constructor$(promises); - var domain = getDomain(); - this._fn = domain === null ? fn : util.domainBind(domain, 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; - - 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 (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))) { - 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.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 l = 8; - while (l--) new FakeConstructor(); - 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 ({}.toString.call(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } -} - -function domainBind(self, cb) { - return self.bind(cb); -} - -var ret = { - 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, - hasDevTools: typeof chrome !== "undefined" && chrome && - typeof chrome.loadTimes === "function", - isNode: isNode, - hasEnvVariables: hasEnvVariables, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - domainBind: domainBind -}; -ret.isRecentNode = ret.isNode && (function() { - var version = process.versions.node.split(".").map(Number); - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); -})(); - -if (ret.isNode) ret.toFastProperties(process); - -try {throw new Error(); } catch (e) {ret.lastLineError = e;} -module.exports = ret; - -},{"./es5":13}]},{},[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 deleted file mode 100644 index e02a9cd..0000000 --- a/node_modules/bluebird/js/browser/bluebird.min.js +++ /dev/null @@ -1,31 +0,0 @@ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2017 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.5.1 - * 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 l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var u=e[s]={exports:{}};t[s][0].call(u.exports,function(e){var n=t[s][1][e];return i(n?n:e)},u,u.exports,r,t,e,n)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=r,e.exports.firstLineError=a},{"./queue":26,"./schedule":29,"./util":36}],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 l=n(o),u=new t(e);u._propagateFrom(this,1);var p=this._target();if(u._setBoundTo(l),l instanceof t){var h={promiseRejectionQueued:!1,promise:u,target:p,bindingPromise:l};p._then(e,s,void 0,u,h),l._then(a,c,void 0,u,h),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)}}},{}],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){function r(t,e){return{promise:e}}function i(){return!1}function o(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: "+H.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function s(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?H.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function a(){return this._onCancelField}function c(t){this._onCancelField=t}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function u(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 p(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function h(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function f(){this._trace=new S(this._peekContext())}function _(t,e){if(N(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=j(t);H.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),H.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(t,e,n,r,i){if(void 0===t&&null!==e&&W){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=w(a),l=c.length-1;l>=0;--l){var u=c[l];if(!U.test(u)){var p=u.match(M);p&&(o="at "+p[1]+":"+p[2]+":"+p[3]+" ");break}}if(c.length>0)for(var h=c[0],l=0;l0&&(s="\n"+a[l-1]);break}}var f="a promise was created in a "+n+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+s;r._warn(f,!0,e)}}function v(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),y(n)}function y(t,n,r){if(ot.warnings){var i,o=new L(t);if(n)r._attachExtraTrace(o);else if(ot.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var s=j(o);o.stack=s.message+"\n"+s.stack.join("\n")}tt("warning",o)||E(o,"",!0)}}function m(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 w(t){for(var e=[],n=0;n0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function j(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?C(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:w(e)}}function E(t,e,n){if("undefined"!=typeof console){var r;if(H.isObject(t)){var i=t.stack;r=e+Q(i,t)}else r=e+String(t);"function"==typeof D?D(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function k(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){I.throwLater(o)}"unhandledRejection"===t?tt(t,n,r)||i||E(n,"Unhandled rejection "):tt(t,r)}function F(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():H.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"(<"+x(e)+">, no stack trace)"}function x(t){var e=41;return t.lengths||0>a||!n||!r||n!==r||s>=a||(nt=function(t){if(B.test(t))return!0;var e=P(t);return e&&e.fileName===n&&s<=e.line&&e.line<=a?!0:!1})}}function S(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);it(this,S),e>32&&this.uncycle()}var O,A,D,V=e._getDomain,I=e._async,L=t("./errors").Warning,H=t("./util"),N=H.canAttachTrace,B=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,U=/\((?:timers\.js):\d+:\d+\)/,M=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,q=null,Q=null,$=!1,G=!(0==H.env("BLUEBIRD_DEBUG")||!H.env("BLUEBIRD_DEBUG")&&"development"!==H.env("NODE_ENV")),z=!(0==H.env("BLUEBIRD_WARNINGS")||!G&&!H.env("BLUEBIRD_WARNINGS")),X=!(0==H.env("BLUEBIRD_LONG_STACK_TRACES")||!G&&!H.env("BLUEBIRD_LONG_STACK_TRACES")),W=0!=H.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(z||!!H.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){if(0===(524288&this._bitField)){this._setRejectionIsUnhandled();var t=this;setTimeout(function(){t._notifyUnhandledRejection()},1)}},e.prototype._notifyUnhandledRejectionIsHandled=function(){k("rejectionHandled",O,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),k("unhandledRejection",A,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},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 y(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=V();A="function"==typeof t?null===e?t:H.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=V();O="function"==typeof t?null===e?t:H.domainBind(e,t):void 0};var K=function(){};e.longStackTraces=function(){if(I.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!ot.longStackTraces&&T()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;ot.longStackTraces=!0,K=function(){if(I.haveItemsQueued()&&!ot.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,n.deactivateLongStackTraces(),I.enableTrampoline(),ot.longStackTraces=!1},e.prototype._captureStackTrace=f,e.prototype._attachExtraTrace=_,n.activateLongStackTraces(),I.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return ot.longStackTraces&&T()};var J=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return H.global.dispatchEvent(t),function(t,e){var n=new CustomEvent(t.toLowerCase(),{detail:e,cancelable:!0});return!H.global.dispatchEvent(n)}}if("function"==typeof Event){var t=new Event("CustomEvent");return H.global.dispatchEvent(t),function(t,e){var n=new Event(t.toLowerCase(),{cancelable:!0});return n.detail=e,!H.global.dispatchEvent(n)}}var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),H.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!H.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),Y=function(){return H.isNode?function(){return process.emit.apply(process,arguments)}:H.global?function(t){var e="on"+t.toLowerCase(),n=H.global[e];return n?(n.apply(H.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),Z={promiseCreated:r,promiseFulfilled:r,promiseRejected:r,promiseResolved:r,promiseCancelled:r,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:r},tt=function(t){var e=!1;try{e=Y.apply(null,arguments)}catch(n){I.throwLater(n),e=!0}var r=!1;try{r=J(t,Z[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()&&K()),"warnings"in t){var n=t.warnings;ot.warnings=!!n,W=ot.warnings,H.isObject(n)&&"wForgottenReturn"in n&&(W=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!ot.cancellation){if(I.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=l,e.prototype._propagateFrom=u,e.prototype._onCancel=a,e.prototype._setOnCancel=c,e.prototype._attachCancellationCallback=s,e.prototype._execute=o,et=u,ot.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!ot.monitoring?(ot.monitoring=!0,e.prototype._fireEvent=tt):!t.monitoring&&ot.monitoring&&(ot.monitoring=!1,e.prototype._fireEvent=i)),e},e.prototype._fireEvent=i,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._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var et=p,nt=function(){return!1},rt=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;H.inherits(S,Error),n.CapturedTrace=S,S.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 l=c._length+1,u=r-2;u>=0;--u)e[u]._length=l,l++;return}}}},S.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=j(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(w(i.stack.split("\n"))),i=i._parent;b(r),g(r),H.notEnumerableProp(t,"stack",m(n,r)),H.notEnumerableProp(t,"__stackCleaned__",!0)}};var it=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():F(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,q=t,Q=e;var n=Error.captureStackTrace;return nt=function(t){return B.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 q=/@/,Q=e,$=!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?(Q=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?F(e):e.toString()},null):(q=t,Q=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&&(D=function(t){console.warn(t)},H.isNode&&process.stderr.isTTY?D=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:H.isNode||"string"!=typeof(new Error).stack||(D=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var ot={warnings:z,longStackTraces:!1,cancellation:!1,monitoring:!1};return X&&e.longStackTraces(),{longStackTraces:function(){return ot.longStackTraces},warnings:function(){return ot.warnings},cancellation:function(){return ot.cancellation},monitoring:function(){return ot.monitoring},propagateFromFunction:function(){return et},boundValueFunction:function(){return h},checkForgottenReturns:d,setBounds:R,warn:y,deprecated:v,CapturedTrace:S,fireDomEvent:J,fireGlobalEvent:Y}}},{"./errors":12,"./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 u(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,l=t("./util"),u=l.inherits,p=l.notEnumerableProp,h=r("Warning","warning"),f=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(" "),m=0;m1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function a(){return l.call(this,this.promise._target()._settledValue())}function c(t){return s(this,t)?void 0:(h.e=t,h)}function l(t){var i=this.promise,l=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?l.call(i._boundValue()):l.call(i._boundValue(),t);if(u===r)return u;if(void 0!==u){i._setReturnedNonUndefined();var f=n(u,i);if(f instanceof e){if(null!=this.cancelPromise){if(f._isCancelled()){var _=new p("late cancellation observer");return i._attachExtraTrace(_),h.e=_,h}f.isPending()&&f._attachCancellationCallback(new o(this))}return f._then(a,c,void 0,this,void 0)}}}return i.isRejected()?(s(this),h.e=t,h):(s(this),t)}var u=t("./util"),p=e.CancellationError,h=u.errorObj,f=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,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,i=new Array(n-1),o=0;for(r=0;n-1>r;++r){var s=arguments[r];if(!u.isObject(s))return e.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+u.classString(s)));i[o++]=s}i.length=o;var a=arguments[r];return this._passThrough(f(i,a,this),1,void 0,l)},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,e,n,r){this.constructor$(t),this._promise._captureStackTrace();var i=l();this._callback=null===i?e:u.domainBind(i,e),this._preservedValues=r===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=[],f.invoke(this._asyncInit,this,void 0)}function c(t,n,i,o){if("function"!=typeof n)return r("expecting a function but got "+u.classString(n));var s=0;if(void 0!==i){if("object"!=typeof i||null===i)return e.reject(new TypeError("options argument must be an object but it is "+u.classString(i)));if("number"!=typeof i.concurrency)return e.reject(new TypeError("'concurrency' must be a number but it is "+u.classString(i.concurrency)));s=i.concurrency}return s="number"==typeof s&&isFinite(s)&&s>=1?s:0,new a(t,n,s,o).promise()}var l=e._getDomain,u=t("./util"),p=u.tryCatch,h=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 l=this._promise,u=this._callback,f=l._boundValue();l._pushContext();var _=p(u).call(f,t,n,o),d=l._popContext();if(s.checkForgottenReturns(_,d,null!==a?"Promise.filter":"Promise.map",l),_===h)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 m=++this._totalResolved;return m>=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 l=arguments[1],u=arguments[2];c=s.isArray(l)?a(t).apply(u,l):a(t).call(u,l)}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&&u.getPrototypeOf(t)===Error.prototype}function i(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),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 p("Catch statement predicate: expecting an object but got "+f.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,P(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(x.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?p("expecting a function but got "+f.classString(t)):this.all()._then(t,void 0,void 0,w,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 E(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(b);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=O(t)(R(e,n));return r===S&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new E(t).promise()},i.cast=function(t){var e=j(t);return e instanceof i||(e=new i(b),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new m("expecting a function but got "+f.classString(t));return v.setScheduler(t)},i.prototype._then=function(t,e,n,r,o){var s=void 0!==o,a=s?o:new i(b),l=this._target(),u=l._bitField;s||(a._propagateFrom(this,3),a._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,a));var p=c();if(0!==(50397184&u)){var h,_,d=l._settlePromiseCtx;0!==(33554432&u)?(_=l._rejectionHandler0,h=t):0!==(16777216&u)?(_=l._fulfillmentHandler0,h=e,l._unsetRejectionIsUnhandled()):(d=l._settlePromiseLateCancellationObserver,_=new g("late cancellation observer"),l._attachExtraTrace(_),h=e),v.invoke(d,l,{handler:null===p?h:"function"==typeof h&&f.domainBind(p,h),promise:a,receiver:r,value:_})}else l._addCallbacks(t,e,a,r,p);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(){v.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===h?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=h),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=h),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=null===i?t:f.domainBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:f.domainBind(i,e));else{var s=4*o-4;this[s+2]=n,this[s+3]=r,"function"==typeof t&&(this[s+0]=null===i?t:f.domainBind(i,t)),"function"==typeof e&&(this[s+1]=null===i?e:f.domainBind(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(l(),!1);var n=j(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(l());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(r)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var c=new g("late cancellation observer");r._attachExtraTrace(c),this._reject(c)}}},i.prototype._rejectCallback=function(t,e,n){var r=f.ensureErrorObject(t),i=r===t;if(!i&&!n&&x.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!==b){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===w?n&&"number"==typeof n.length?o=O(t).apply(this._boundValue(),n):(o=S,o.e=new m("cannot .spread() a non-array: "+f.classString(n))):o=O(t).call(e,n);var s=r._popContext();i=r._bitField,0===(65536&i)&&(o===C?r._reject(n):o===S?r._rejectCallback(o.e,!1):(x.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 T&&r.isFinallyHandler()?(r.cancelPromise=t,O(e).call(r,o)===S&&t._reject(S.e)):e===u?t._fulfill(u.call(r)):r instanceof n?r._promiseCancelled(t):s||t instanceof E?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=l();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():v.settlePromises(this))}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?v.fatalError(t,f.isNode):void((65535&e)>0?v.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},i.defer=i.pending=function(){x.deprecated("Promise.defer","new Promise");var t=new i(b);return{promise:t,resolve:o,reject:s}},f.notEnumerableProp(i,"_makeSelfResolutionError",l),t("./method")(i,b,j,p,x),t("./bind")(i,b,j,x),t("./cancel")(i,E,p,x),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,E,j,b,v,c),i.Promise=i,i.version="3.5.1",t("./map.js")(i,E,p,j,b,x),t("./call_get.js")(i),t("./using.js")(i,p,j,F,b,x),t("./timers.js")(i,b,x),t("./generators.js")(i,p,b,j,n,x),t("./nodeify.js")(i),t("./promisify.js")(i,b),t("./props.js")(i,E,j,p),t("./race.js")(i,b,j,p),t("./reduce.js")(i,E,p,j,b,x),t("./settle.js")(i,E,x),t("./some.js")(i,E,p),t("./filter.js")(i,b),t("./each.js")(i,b),t("./any.js")(i),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(b)),x.setBounds(d.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}],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),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 l(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(l,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 u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!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 u=s[c],p=s[c+1],_=u+e;if(r===k)t[_]=k(u,h,u,p,e,i);else{var d=r(p,function(){return k(u,h,u,p,e,i)});f.notEnumerableProp(d,"__isPromisified__",!0),t[_]=d}}return f.toFastProperties(t),t}function u(t,e,n){return k(t,e,void 0,t,null,n)}var p,h={},f=t("./util"),_=t("./nodeback"),d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,m=t("./errors").TypeError,g="Async",b={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],C=new RegExp("^(?:"+w.join("|")+")$"),j=function(t){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},E=function(t){return t.replace(/([$])/,"\\$")},k=y?p:c;e.promisify=function(t,e){if("function"!=typeof t)throw new m("expecting a function but got "+f.classString(t));if(i(t))return t;e=Object(e);var n=void 0===e.context?h:e.context,o=!!e.multiArgs,s=u(t,n,o);return f.copyDescriptors(t,s,r),s},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new m("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=g);var i=e.filter;"function"!=typeof i&&(i=j);var o=e.promisifier;if("function"!=typeof o&&(o=k),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");for(var s=f.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 l(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"),l=c.isObject,u=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}}(),h=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=h(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._capacityh;++h){var _=t[h];(void 0!==_||h in t)&&e.cast(_)._then(u,p,void 0,l,null)}return l}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=h();this._fn=null===s?n:f.domainBind(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 l(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 u(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=_(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 h=e._getDomain,f=t("./util"),_=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;if(void 0!==this._initialValue?(n=this._initialValue,r=0):(n=e.resolve(t[0]),r=1),this._currentCancellable=n,!n.isRejected())for(;i>r;++r){var o={accum:null,value:t[r],index:r,length:i,array:this};n=n._then(u,void 0,void 0,o,void 0)}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 l(this,t,e,null)},e.reduce=function(t,e,n,r){return l(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 l=s.resolve();r=function(t){l.then(t)}}else r="undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&(window.navigator.standalone||window.cordova)?"undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:o: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()}}();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.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,l=s.isArray,u={};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=l(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(u),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(u(t)){if(t instanceof e)return t;var i=o(t);if(i===l){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 l.e=e,l}}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),u=a;i&&i._pushContext(),a._captureStackTrace(),i&&i._popContext();var p=!0,h=c.tryCatch(r).call(t,o,s);return p=!1,a&&h===l&&(a._rejectCallback(h.e,!0,!0),a=null),u}var c=t("./util"),l=c.errorObj,u=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 l=function(t){return u(+this).thenReturn(t)},u=e.delay=function(t,o){var s,a;return void 0!==o?(s=e.resolve(o)._then(l,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 u(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 l(t,n){function i(){if(s>=l)return u._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,l=t.length,u=new e(o);return i(),u}function u(t,e,n){this._data=t,this._promise=e,this._context=n}function p(t,e,n){this.constructor$(t,e,n)}function h(t){return u.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function f(t){this.length=t,this.promise=null,this[t-1]=null}var _=t("./util"),d=t("./errors").TypeError,v=t("./util").inherits,y=_.errorObj,m=_.tryCatch,g={};u.prototype.data=function(){return this._data},u.prototype.promise=function(){return this._promise},u.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():g},u.prototype.tryDispose=function(t){var e=this.resource(),n=this._context;void 0!==n&&n._pushContext();var r=e!==g?this.doDispose(e,t):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,r},u.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},v(p,u),p.prototype.doDispose=function(t,e){var n=this.data();return n.call(t,t,e)},f.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 f(t),p=0;t>p;++p){var d=o[p];if(u.isDisposer(d)){var v=d;d=d.promise(),d._setDisposable(v)}else{var g=r(d);g instanceof e&&(d=g._then(h,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 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(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 h(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 f(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return D.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 m(t){try{u(t,"isOperational",!0)}catch(e){}}function g(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.isNode&&B.toFastProperties(process);try{throw new Error}catch(U){B.lastLineError=U}e.exports=B},{"./es5":13}]},{},[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 deleted file mode 100644 index 05a6228..0000000 --- a/node_modules/bluebird/js/release/any.js +++ /dev/null @@ -1,21 +0,0 @@ -"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 deleted file mode 100644 index 4518231..0000000 --- a/node_modules/bluebird/js/release/assert.js +++ /dev/null @@ -1,55 +0,0 @@ -"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 deleted file mode 100644 index 41f6655..0000000 --- a/node_modules/bluebird/js/release/async.js +++ /dev/null @@ -1,161 +0,0 @@ -"use strict"; -var firstLineError; -try {throw new Error(); } catch (e) {firstLineError = e;} -var schedule = require("./schedule"); -var Queue = require("./queue"); -var util = require("./util"); - -function Async() { - this._customScheduler = false; - this._isTickUsed = false; - this._lateQueue = new Queue(16); - this._normalQueue = new Queue(16); - this._haveDrainedQueues = false; - this._trampolineEnabled = true; - 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.enableTrampoline = function() { - this._trampolineEnabled = true; -}; - -Async.prototype.disableTrampolineIfNecessary = function() { - if (util.hasDevTools) { - this._trampolineEnabled = false; - } -}; - -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(); -} - -if (!util.hasDevTools) { - Async.prototype.invokeLater = AsyncInvokeLater; - Async.prototype.invoke = AsyncInvoke; - Async.prototype.settlePromises = AsyncSettlePromises; -} else { - Async.prototype.invokeLater = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvokeLater.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - setTimeout(function() { - fn.call(receiver, arg); - }, 100); - }); - } - }; - - Async.prototype.invoke = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvoke.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - fn.call(receiver, arg); - }); - } - }; - - Async.prototype.settlePromises = function(promise) { - if (this._trampolineEnabled) { - AsyncSettlePromises.call(this, promise); - } else { - this._schedule(function() { - promise._settlePromises(); - }); - } - }; -} - -Async.prototype._drainQueue = function(queue) { - while (queue.length() > 0) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - continue; - } - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } -}; - -Async.prototype._drainQueues = function () { - this._drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - this._drainQueue(this._lateQueue); -}; - -Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } -}; - -Async.prototype._reset = function () { - this._isTickUsed = false; -}; - -module.exports = Async; -module.exports.firstLineError = firstLineError; diff --git a/node_modules/bluebird/js/release/bind.js b/node_modules/bluebird/js/release/bind.js deleted file mode 100644 index fc3379d..0000000 --- a/node_modules/bluebird/js/release/bind.js +++ /dev/null @@ -1,67 +0,0 @@ -"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 deleted file mode 100644 index 1c36cf3..0000000 --- a/node_modules/bluebird/js/release/bluebird.js +++ /dev/null @@ -1,11 +0,0 @@ -"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 deleted file mode 100644 index 0ed7714..0000000 --- a/node_modules/bluebird/js/release/call_get.js +++ /dev/null @@ -1,123 +0,0 @@ -"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 deleted file mode 100644 index 7a12415..0000000 --- a/node_modules/bluebird/js/release/cancel.js +++ /dev/null @@ -1,129 +0,0 @@ -"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 deleted file mode 100644 index 0f24ce2..0000000 --- a/node_modules/bluebird/js/release/catch_filter.js +++ /dev/null @@ -1,42 +0,0 @@ -"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 deleted file mode 100644 index c307414..0000000 --- a/node_modules/bluebird/js/release/context.js +++ /dev/null @@ -1,69 +0,0 @@ -"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 deleted file mode 100644 index 6956804..0000000 --- a/node_modules/bluebird/js/release/debuggability.js +++ /dev/null @@ -1,919 +0,0 @@ -"use strict"; -module.exports = function(Promise, Context) { -var getDomain = Promise._getDomain; -var async = Promise._async; -var Warning = require("./errors").Warning; -var util = require("./util"); -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")); - -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(); - var self = this; - setTimeout(function() { - self._notifyUnhandledRejection(); - }, 1); -}; - -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 domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; -}; - -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; - 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; - Context.deactivateLongStackTraces(); - async.enableTrampoline(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); - } -}; - -Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); -}; - -var fireDomEvent = (function() { - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new CustomEvent(name.toLowerCase(), { - detail: event, - cancelable: true - }); - return !util.global.dispatchEvent(domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new Event(name.toLowerCase(), { - cancelable: true - }); - domEvent.detail = event; - return !util.global.dispatchEvent(domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name.toLowerCase(), false, true, - event); - return !util.global.dispatchEvent(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; - } - } - 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._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 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 -}; - -if (longStackTraces) Promise.longStackTraces(); - -return { - 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 deleted file mode 100644 index a890298..0000000 --- a/node_modules/bluebird/js/release/direct_resolve.js +++ /dev/null @@ -1,46 +0,0 @@ -"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 deleted file mode 100644 index e4f3d05..0000000 --- a/node_modules/bluebird/js/release/each.js +++ /dev/null @@ -1,30 +0,0 @@ -"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 deleted file mode 100644 index f62f323..0000000 --- a/node_modules/bluebird/js/release/errors.js +++ /dev/null @@ -1,116 +0,0 @@ -"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 deleted file mode 100644 index ea41d5a..0000000 --- a/node_modules/bluebird/js/release/es5.js +++ /dev/null @@ -1,80 +0,0 @@ -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 deleted file mode 100644 index ed57bf0..0000000 --- a/node_modules/bluebird/js/release/filter.js +++ /dev/null @@ -1,12 +0,0 @@ -"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 deleted file mode 100644 index d57444b..0000000 --- a/node_modules/bluebird/js/release/finally.js +++ /dev/null @@ -1,146 +0,0 @@ -"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 deleted file mode 100644 index 500c280..0000000 --- a/node_modules/bluebird/js/release/generators.js +++ /dev/null @@ -1,223 +0,0 @@ -"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 deleted file mode 100644 index 4945e3f..0000000 --- a/node_modules/bluebird/js/release/join.js +++ /dev/null @@ -1,168 +0,0 @@ -"use strict"; -module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, - getDomain) { -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 domain = getDomain(); - if (domain !== null) { - holder.fn = util.domainBind(domain, 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 deleted file mode 100644 index 976f15e..0000000 --- a/node_modules/bluebird/js/release/map.js +++ /dev/null @@ -1,168 +0,0 @@ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -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 domain = getDomain(); - this._callback = domain === null ? fn : util.domainBind(domain, fn); - this._preservedValues = _filter === INTERNAL - ? new Array(this.length()) - : null; - this._limit = limit; - this._inFlight = 0; - this._queue = []; - async.invoke(this._asyncInit, this, undefined); -} -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 deleted file mode 100644 index ce9e4db..0000000 --- a/node_modules/bluebird/js/release/method.js +++ /dev/null @@ -1,55 +0,0 @@ -"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 deleted file mode 100644 index 71e69eb..0000000 --- a/node_modules/bluebird/js/release/nodeback.js +++ /dev/null @@ -1,51 +0,0 @@ -"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 deleted file mode 100644 index ce2b190..0000000 --- a/node_modules/bluebird/js/release/nodeify.js +++ /dev/null @@ -1,58 +0,0 @@ -"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 deleted file mode 100644 index f4a641c..0000000 --- a/node_modules/bluebird/js/release/promise.js +++ /dev/null @@ -1,775 +0,0 @@ -"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"); - -var getDomain; -if (util.isNode) { - getDomain = function() { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; -} else { - getDomain = function() { - return null; - }; -} -util.notEnumerableProp(Promise, "_getDomain", getDomain); - -var 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); -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]; - 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 domain = getDomain(); - 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: domain === null ? handler - : (typeof handler === "function" && - util.domainBind(domain, handler)), - promise: promise, - receiver: receiver, - value: value - }); - } else { - target._addCallbacks(didFulfill, didReject, promise, receiver, domain); - } - - 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; - this._bitField = this._bitField | 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, - domain -) { - 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 = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : util.domainBind(domain, reject); - } - } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - domain === null ? reject : util.domainBind(domain, 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(promise); - } 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); - } - } -}; - -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; - } -}; - -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, getDomain); -Promise.Promise = Promise; -Promise.version = "3.5.1"; -require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -require('./call_get.js')(Promise); -require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); -require('./timers.js')(Promise, INTERNAL, debug); -require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, 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('./filter.js')(Promise, INTERNAL); -require('./each.js')(Promise, INTERNAL); -require('./any.js')(Promise); - - 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 deleted file mode 100644 index 0fb303e..0000000 --- a/node_modules/bluebird/js/release/promise_array.js +++ /dev/null @@ -1,185 +0,0 @@ -"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); - } - 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 deleted file mode 100644 index aa98e5b..0000000 --- a/node_modules/bluebird/js/release/promisify.js +++ /dev/null @@ -1,314 +0,0 @@ -"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 deleted file mode 100644 index 6a34aaf..0000000 --- a/node_modules/bluebird/js/release/props.js +++ /dev/null @@ -1,118 +0,0 @@ -"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 deleted file mode 100644 index ffd36fd..0000000 --- a/node_modules/bluebird/js/release/queue.js +++ /dev/null @@ -1,73 +0,0 @@ -"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 deleted file mode 100644 index b862f46..0000000 --- a/node_modules/bluebird/js/release/race.js +++ /dev/null @@ -1,49 +0,0 @@ -"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 deleted file mode 100644 index 26e2b1a..0000000 --- a/node_modules/bluebird/js/release/reduce.js +++ /dev/null @@ -1,172 +0,0 @@ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = require("./util"); -var tryCatch = util.tryCatch; - -function ReductionPromiseArray(promises, fn, initialValue, _each) { - this.constructor$(promises); - var domain = getDomain(); - this._fn = domain === null ? fn : util.domainBind(domain, 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; - - 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 (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 deleted file mode 100644 index f70df9f..0000000 --- a/node_modules/bluebird/js/release/schedule.js +++ /dev/null @@ -1,61 +0,0 @@ -"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))) { - 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 deleted file mode 100644 index fade3a1..0000000 --- a/node_modules/bluebird/js/release/settle.js +++ /dev/null @@ -1,43 +0,0 @@ -"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.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 deleted file mode 100644 index 400d852..0000000 --- a/node_modules/bluebird/js/release/some.js +++ /dev/null @@ -1,148 +0,0 @@ -"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 deleted file mode 100644 index 9c49d2e..0000000 --- a/node_modules/bluebird/js/release/synchronous_inspection.js +++ /dev/null @@ -1,103 +0,0 @@ -"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 deleted file mode 100644 index d6ab9aa..0000000 --- a/node_modules/bluebird/js/release/thenables.js +++ /dev/null @@ -1,86 +0,0 @@ -"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 deleted file mode 100644 index cb8f1f4..0000000 --- a/node_modules/bluebird/js/release/timers.js +++ /dev/null @@ -1,93 +0,0 @@ -"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 deleted file mode 100644 index 65de531..0000000 --- a/node_modules/bluebird/js/release/using.js +++ /dev/null @@ -1,226 +0,0 @@ -"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 deleted file mode 100644 index 7ac0e2f..0000000 --- a/node_modules/bluebird/js/release/util.js +++ /dev/null @@ -1,380 +0,0 @@ -"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 l = 8; - while (l--) new FakeConstructor(); - 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 ({}.toString.call(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } -} - -function domainBind(self, cb) { - return self.bind(cb); -} - -var ret = { - 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, - hasDevTools: typeof chrome !== "undefined" && chrome && - typeof chrome.loadTimes === "function", - isNode: isNode, - hasEnvVariables: hasEnvVariables, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - domainBind: domainBind -}; -ret.isRecentNode = ret.isNode && (function() { - var version = process.versions.node.split(".").map(Number); - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); -})(); - -if (ret.isNode) ret.toFastProperties(process); - -try {throw new Error(); } catch (e) {ret.lastLineError = e;} -module.exports = ret; diff --git a/node_modules/bluebird/package.json b/node_modules/bluebird/package.json deleted file mode 100644 index c4afda5..0000000 --- a/node_modules/bluebird/package.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "_from": "bluebird@3.5.1", - "_id": "bluebird@3.5.1", - "_inBundle": false, - "_integrity": "sha512-MKiLiV+I1AA596t9w1sQJ8jkiSr5+ZKi0WKrYGUn6d1Fx+Ij4tIj+m2WMQSGczs5jZVxV339chE8iwk6F64wjA==", - "_location": "/bluebird", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "bluebird@3.5.1", - "name": "bluebird", - "escapedName": "bluebird", - "rawSpec": "3.5.1", - "saveSpec": null, - "fetchSpec": "3.5.1" - }, - "_requiredBy": [ - "/mquery" - ], - "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz", - "_shasum": "d9551f9de98f1fcda1e683d17ee91a0602ee2eb9", - "_spec": "bluebird@3.5.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mquery", - "author": { - "name": "Petka Antonov", - "email": "petka_antonov@hotmail.com", - "url": "http://github.com/petkaantonov/" - }, - "browser": "./js/browser/bluebird.js", - "bugs": { - "url": "http://github.com/petkaantonov/bluebird/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Full featured Promises/A+ implementation with exceptionally good performance", - "devDependencies": { - "acorn": "~0.6.0", - "baconjs": "^0.7.43", - "bluebird": "^2.9.2", - "body-parser": "^1.10.2", - "browserify": "^8.1.1", - "cli-table": "~0.3.1", - "co": "^4.2.0", - "cross-spawn": "^0.2.3", - "glob": "^4.3.2", - "grunt-saucelabs": "~8.4.1", - "highland": "^2.3.0", - "istanbul": "^0.3.5", - "jshint": "^2.6.0", - "jshint-stylish": "~0.2.0", - "kefir": "^2.4.1", - "mkdirp": "~0.5.0", - "mocha": "~2.1", - "open": "~0.0.5", - "optimist": "~0.6.1", - "rimraf": "~2.2.6", - "rx": "^2.3.25", - "serve-static": "^1.7.1", - "sinon": "~1.7.3", - "uglify-js": "~2.4.16" - }, - "files": [ - "js/browser", - "js/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 tools/test.js" - }, - "version": "3.5.1", - "webpack": "./js/release/bluebird.js" -} diff --git a/node_modules/body-parser/HISTORY.md b/node_modules/body-parser/HISTORY.md deleted file mode 100644 index a1d3fbf..0000000 --- a/node_modules/body-parser/HISTORY.md +++ /dev/null @@ -1,609 +0,0 @@ -1.19.0 / 2019-04-25 -=================== - - * deps: bytes@3.1.0 - - Add petabyte (`pb`) support - * deps: http-errors@1.7.2 - - Set constructor name when possible - - deps: setprototypeof@1.1.1 - - deps: statuses@'>= 1.5.0 < 2' - * deps: iconv-lite@0.4.24 - - Added encoding MIK - * deps: qs@6.7.0 - - Fix parsing array brackets after index - * deps: raw-body@2.4.0 - - deps: bytes@3.1.0 - - deps: http-errors@1.7.2 - - deps: iconv-lite@0.4.24 - * deps: type-is@~1.6.17 - - deps: mime-types@~2.1.24 - - perf: prevent internal `throw` on invalid type - -1.18.3 / 2018-05-14 -=================== - - * Fix stack trace for strict json parse error - * deps: depd@~1.1.2 - - perf: remove argument reassignment - * deps: http-errors@~1.6.3 - - deps: depd@~1.1.2 - - deps: setprototypeof@1.1.0 - - deps: statuses@'>= 1.3.1 < 2' - * deps: iconv-lite@0.4.23 - - Fix loading encoding with year appended - - Fix deprecation warnings on Node.js 10+ - * deps: qs@6.5.2 - * deps: raw-body@2.3.3 - - deps: http-errors@1.6.3 - - deps: iconv-lite@0.4.23 - * deps: type-is@~1.6.16 - - deps: mime-types@~2.1.18 - -1.18.2 / 2017-09-22 -=================== - - * deps: debug@2.6.9 - * perf: remove argument reassignment - -1.18.1 / 2017-09-12 -=================== - - * deps: content-type@~1.0.4 - - perf: remove argument reassignment - - perf: skip parameter parsing when no parameters - * deps: iconv-lite@0.4.19 - - Fix ISO-8859-1 regression - - Update Windows-1255 - * deps: qs@6.5.1 - - Fix parsing & compacting very deep objects - * deps: raw-body@2.3.2 - - deps: iconv-lite@0.4.19 - -1.18.0 / 2017-09-08 -=================== - - * Fix JSON strict violation error to match native parse error - * Include the `body` property on verify errors - * Include the `type` property on all generated errors - * Use `http-errors` to set status code on errors - * deps: bytes@3.0.0 - * deps: debug@2.6.8 - * deps: depd@~1.1.1 - - Remove unnecessary `Buffer` loading - * deps: http-errors@~1.6.2 - - deps: depd@1.1.1 - * deps: iconv-lite@0.4.18 - - Add support for React Native - - Add a warning if not loaded as utf-8 - - Fix CESU-8 decoding in Node.js 8 - - Improve speed of ISO-8859-1 encoding - * deps: qs@6.5.0 - * deps: raw-body@2.3.1 - - Use `http-errors` for standard emitted errors - - deps: bytes@3.0.0 - - deps: iconv-lite@0.4.18 - - perf: skip buffer decoding on overage chunk - * perf: prevent internal `throw` when missing charset - -1.17.2 / 2017-05-17 -=================== - - * deps: debug@2.6.7 - - Fix `DEBUG_MAX_ARRAY_LENGTH` - - deps: ms@2.0.0 - * deps: type-is@~1.6.15 - - deps: mime-types@~2.1.15 - -1.17.1 / 2017-03-06 -=================== - - * deps: qs@6.4.0 - - Fix regression parsing keys starting with `[` - -1.17.0 / 2017-03-01 -=================== - - * deps: http-errors@~1.6.1 - - Make `message` property enumerable for `HttpError`s - - deps: setprototypeof@1.0.3 - * deps: qs@6.3.1 - - Fix compacting nested arrays - -1.16.1 / 2017-02-10 -=================== - - * deps: debug@2.6.1 - - Fix deprecation messages in WebStorm and other editors - - Undeprecate `DEBUG_FD` set to `1` or `2` - -1.16.0 / 2017-01-17 -=================== - - * deps: debug@2.6.0 - - Allow colors in workers - - Deprecated `DEBUG_FD` environment variable - - Fix error when running under React Native - - Use same color for same namespace - - deps: ms@0.7.2 - * deps: http-errors@~1.5.1 - - deps: inherits@2.0.3 - - deps: setprototypeof@1.0.2 - - deps: statuses@'>= 1.3.1 < 2' - * deps: iconv-lite@0.4.15 - - Added encoding MS-31J - - Added encoding MS-932 - - Added encoding MS-936 - - Added encoding MS-949 - - Added encoding MS-950 - - Fix GBK/GB18030 handling of Euro character - * deps: qs@6.2.1 - - Fix array parsing from skipping empty values - * deps: raw-body@~2.2.0 - - deps: iconv-lite@0.4.15 - * deps: type-is@~1.6.14 - - deps: mime-types@~2.1.13 - -1.15.2 / 2016-06-19 -=================== - - * deps: bytes@2.4.0 - * deps: content-type@~1.0.2 - - perf: enable strict mode - * deps: http-errors@~1.5.0 - - Use `setprototypeof` module to replace `__proto__` setting - - deps: statuses@'>= 1.3.0 < 2' - - perf: enable strict mode - * deps: qs@6.2.0 - * deps: raw-body@~2.1.7 - - deps: bytes@2.4.0 - - perf: remove double-cleanup on happy path - * deps: type-is@~1.6.13 - - deps: mime-types@~2.1.11 - -1.15.1 / 2016-05-05 -=================== - - * deps: bytes@2.3.0 - - Drop partial bytes on all parsed units - - Fix parsing byte string that looks like hex - * deps: raw-body@~2.1.6 - - deps: bytes@2.3.0 - * deps: type-is@~1.6.12 - - deps: mime-types@~2.1.10 - -1.15.0 / 2016-02-10 -=================== - - * deps: http-errors@~1.4.0 - - Add `HttpError` export, for `err instanceof createError.HttpError` - - deps: inherits@2.0.1 - - deps: statuses@'>= 1.2.1 < 2' - * deps: qs@6.1.0 - * deps: type-is@~1.6.11 - - deps: mime-types@~2.1.9 - -1.14.2 / 2015-12-16 -=================== - - * deps: bytes@2.2.0 - * deps: iconv-lite@0.4.13 - * deps: qs@5.2.0 - * deps: raw-body@~2.1.5 - - deps: bytes@2.2.0 - - deps: iconv-lite@0.4.13 - * deps: type-is@~1.6.10 - - deps: mime-types@~2.1.8 - -1.14.1 / 2015-09-27 -=================== - - * Fix issue where invalid charset results in 400 when `verify` used - * deps: iconv-lite@0.4.12 - - Fix CESU-8 decoding in Node.js 4.x - * deps: raw-body@~2.1.4 - - Fix masking critical errors from `iconv-lite` - - deps: iconv-lite@0.4.12 - * deps: type-is@~1.6.9 - - deps: mime-types@~2.1.7 - -1.14.0 / 2015-09-16 -=================== - - * Fix JSON strict parse error to match syntax errors - * Provide static `require` analysis in `urlencoded` parser - * deps: depd@~1.1.0 - - Support web browser loading - * deps: qs@5.1.0 - * deps: raw-body@~2.1.3 - - Fix sync callback when attaching data listener causes sync read - * deps: type-is@~1.6.8 - - Fix type error when given invalid type to match against - - deps: mime-types@~2.1.6 - -1.13.3 / 2015-07-31 -=================== - - * deps: type-is@~1.6.6 - - deps: mime-types@~2.1.4 - -1.13.2 / 2015-07-05 -=================== - - * deps: iconv-lite@0.4.11 - * deps: qs@4.0.0 - - Fix dropping parameters like `hasOwnProperty` - - Fix user-visible incompatibilities from 3.1.0 - - Fix various parsing edge cases - * deps: raw-body@~2.1.2 - - Fix error stack traces to skip `makeError` - - deps: iconv-lite@0.4.11 - * deps: type-is@~1.6.4 - - deps: mime-types@~2.1.2 - - perf: enable strict mode - - perf: remove argument reassignment - -1.13.1 / 2015-06-16 -=================== - - * deps: qs@2.4.2 - - Downgraded from 3.1.0 because of user-visible incompatibilities - -1.13.0 / 2015-06-14 -=================== - - * Add `statusCode` property on `Error`s, in addition to `status` - * Change `type` default to `application/json` for JSON parser - * Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser - * Provide static `require` analysis - * Use the `http-errors` module to generate errors - * deps: bytes@2.1.0 - - Slight optimizations - * deps: iconv-lite@0.4.10 - - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails - - Leading BOM is now removed when decoding - * deps: on-finished@~2.3.0 - - Add defined behavior for HTTP `CONNECT` requests - - Add defined behavior for HTTP `Upgrade` requests - - deps: ee-first@1.1.1 - * deps: qs@3.1.0 - - Fix dropping parameters like `hasOwnProperty` - - Fix various parsing edge cases - - Parsed object now has `null` prototype - * deps: raw-body@~2.1.1 - - Use `unpipe` module for unpiping requests - - deps: iconv-lite@0.4.10 - * deps: type-is@~1.6.3 - - deps: mime-types@~2.1.1 - - perf: reduce try block size - - perf: remove bitwise operations - * perf: enable strict mode - * perf: remove argument reassignment - * perf: remove delete call - -1.12.4 / 2015-05-10 -=================== - - * deps: debug@~2.2.0 - * deps: qs@2.4.2 - - Fix allowing parameters like `constructor` - * deps: on-finished@~2.2.1 - * deps: raw-body@~2.0.1 - - Fix a false-positive when unpiping in Node.js 0.8 - - deps: bytes@2.0.1 - * deps: type-is@~1.6.2 - - deps: mime-types@~2.0.11 - -1.12.3 / 2015-04-15 -=================== - - * Slight efficiency improvement when not debugging - * deps: depd@~1.0.1 - * deps: iconv-lite@0.4.8 - - Add encoding alias UNICODE-1-1-UTF-7 - * deps: raw-body@1.3.4 - - Fix hanging callback if request aborts during read - - deps: iconv-lite@0.4.8 - -1.12.2 / 2015-03-16 -=================== - - * deps: qs@2.4.1 - - Fix error when parameter `hasOwnProperty` is present - -1.12.1 / 2015-03-15 -=================== - - * deps: debug@~2.1.3 - - Fix high intensity foreground color for bold - - deps: ms@0.7.0 - * deps: type-is@~1.6.1 - - deps: mime-types@~2.0.10 - -1.12.0 / 2015-02-13 -=================== - - * add `debug` messages - * accept a function for the `type` option - * use `content-type` to parse `Content-Type` headers - * deps: iconv-lite@0.4.7 - - Gracefully support enumerables on `Object.prototype` - * deps: raw-body@1.3.3 - - deps: iconv-lite@0.4.7 - * deps: type-is@~1.6.0 - - fix argument reassignment - - fix false-positives in `hasBody` `Transfer-Encoding` check - - support wildcard for both type and subtype (`*/*`) - - deps: mime-types@~2.0.9 - -1.11.0 / 2015-01-30 -=================== - - * make internal `extended: true` depth limit infinity - * deps: type-is@~1.5.6 - - deps: mime-types@~2.0.8 - -1.10.2 / 2015-01-20 -=================== - - * deps: iconv-lite@0.4.6 - - Fix rare aliases of single-byte encodings - * deps: raw-body@1.3.2 - - deps: iconv-lite@0.4.6 - -1.10.1 / 2015-01-01 -=================== - - * deps: on-finished@~2.2.0 - * deps: type-is@~1.5.5 - - deps: mime-types@~2.0.7 - -1.10.0 / 2014-12-02 -=================== - - * make internal `extended: true` array limit dynamic - -1.9.3 / 2014-11-21 -================== - - * deps: iconv-lite@0.4.5 - - Fix Windows-31J and X-SJIS encoding support - * deps: qs@2.3.3 - - Fix `arrayLimit` behavior - * deps: raw-body@1.3.1 - - deps: iconv-lite@0.4.5 - * deps: type-is@~1.5.3 - - deps: mime-types@~2.0.3 - -1.9.2 / 2014-10-27 -================== - - * deps: qs@2.3.2 - - Fix parsing of mixed objects and values - -1.9.1 / 2014-10-22 -================== - - * deps: on-finished@~2.1.1 - - Fix handling of pipelined requests - * deps: qs@2.3.0 - - Fix parsing of mixed implicit and explicit arrays - * deps: type-is@~1.5.2 - - deps: mime-types@~2.0.2 - -1.9.0 / 2014-09-24 -================== - - * include the charset in "unsupported charset" error message - * include the encoding in "unsupported content encoding" error message - * deps: depd@~1.0.0 - -1.8.4 / 2014-09-23 -================== - - * fix content encoding to be case-insensitive - -1.8.3 / 2014-09-19 -================== - - * deps: qs@2.2.4 - - Fix issue with object keys starting with numbers truncated - -1.8.2 / 2014-09-15 -================== - - * deps: depd@0.4.5 - -1.8.1 / 2014-09-07 -================== - - * deps: media-typer@0.3.0 - * deps: type-is@~1.5.1 - -1.8.0 / 2014-09-05 -================== - - * make empty-body-handling consistent between chunked requests - - empty `json` produces `{}` - - empty `raw` produces `new Buffer(0)` - - empty `text` produces `''` - - empty `urlencoded` produces `{}` - * deps: qs@2.2.3 - - Fix issue where first empty value in array is discarded - * deps: type-is@~1.5.0 - - fix `hasbody` to be true for `content-length: 0` - -1.7.0 / 2014-09-01 -================== - - * add `parameterLimit` option to `urlencoded` parser - * change `urlencoded` extended array limit to 100 - * respond with 413 when over `parameterLimit` in `urlencoded` - -1.6.7 / 2014-08-29 -================== - - * deps: qs@2.2.2 - - Remove unnecessary cloning - -1.6.6 / 2014-08-27 -================== - - * deps: qs@2.2.0 - - Array parsing fix - - Performance improvements - -1.6.5 / 2014-08-16 -================== - - * deps: on-finished@2.1.0 - -1.6.4 / 2014-08-14 -================== - - * deps: qs@1.2.2 - -1.6.3 / 2014-08-10 -================== - - * deps: qs@1.2.1 - -1.6.2 / 2014-08-07 -================== - - * deps: qs@1.2.0 - - Fix parsing array of objects - -1.6.1 / 2014-08-06 -================== - - * deps: qs@1.1.0 - - Accept urlencoded square brackets - - Accept empty values in implicit array notation - -1.6.0 / 2014-08-05 -================== - - * deps: qs@1.0.2 - - Complete rewrite - - Limits array length to 20 - - Limits object depth to 5 - - Limits parameters to 1,000 - -1.5.2 / 2014-07-27 -================== - - * deps: depd@0.4.4 - - Work-around v8 generating empty stack traces - -1.5.1 / 2014-07-26 -================== - - * deps: depd@0.4.3 - - Fix exception when global `Error.stackTraceLimit` is too low - -1.5.0 / 2014-07-20 -================== - - * deps: depd@0.4.2 - - Add `TRACE_DEPRECATION` environment variable - - Remove non-standard grey color from color output - - Support `--no-deprecation` argument - - Support `--trace-deprecation` argument - * deps: iconv-lite@0.4.4 - - Added encoding UTF-7 - * deps: raw-body@1.3.0 - - deps: iconv-lite@0.4.4 - - Added encoding UTF-7 - - Fix `Cannot switch to old mode now` error on Node.js 0.10+ - * deps: type-is@~1.3.2 - -1.4.3 / 2014-06-19 -================== - - * deps: type-is@1.3.1 - - fix global variable leak - -1.4.2 / 2014-06-19 -================== - - * deps: type-is@1.3.0 - - improve type parsing - -1.4.1 / 2014-06-19 -================== - - * fix urlencoded extended deprecation message - -1.4.0 / 2014-06-19 -================== - - * add `text` parser - * add `raw` parser - * check accepted charset in content-type (accepts utf-8) - * check accepted encoding in content-encoding (accepts identity) - * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed - * deprecate `urlencoded()` without provided `extended` option - * lazy-load urlencoded parsers - * parsers split into files for reduced mem usage - * support gzip and deflate bodies - - set `inflate: false` to turn off - * deps: raw-body@1.2.2 - - Support all encodings from `iconv-lite` - -1.3.1 / 2014-06-11 -================== - - * deps: type-is@1.2.1 - - Switch dependency from mime to mime-types@1.0.0 - -1.3.0 / 2014-05-31 -================== - - * add `extended` option to urlencoded parser - -1.2.2 / 2014-05-27 -================== - - * deps: raw-body@1.1.6 - - assert stream encoding on node.js 0.8 - - assert stream encoding on node.js < 0.10.6 - - deps: bytes@1 - -1.2.1 / 2014-05-26 -================== - - * invoke `next(err)` after request fully read - - prevents hung responses and socket hang ups - -1.2.0 / 2014-05-11 -================== - - * add `verify` option - * deps: type-is@1.2.0 - - support suffix matching - -1.1.2 / 2014-05-11 -================== - - * improve json parser speed - -1.1.1 / 2014-05-11 -================== - - * fix repeated limit parsing with every request - -1.1.0 / 2014-05-10 -================== - - * add `type` option - * deps: pin for safety and consistency - -1.0.2 / 2014-04-14 -================== - - * use `type-is` module - -1.0.1 / 2014-03-20 -================== - - * lower default limits to 100kb diff --git a/node_modules/body-parser/LICENSE b/node_modules/body-parser/LICENSE deleted file mode 100644 index 386b7b6..0000000 --- a/node_modules/body-parser/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -(The MIT License) - -Copyright (c) 2014 Jonathan Ong -Copyright (c) 2014-2015 Douglas Christopher Wilson - -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/body-parser/README.md b/node_modules/body-parser/README.md deleted file mode 100644 index aba6297..0000000 --- a/node_modules/body-parser/README.md +++ /dev/null @@ -1,443 +0,0 @@ -# body-parser - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Node.js body parsing middleware. - -Parse incoming request bodies in a middleware before your handlers, available -under the `req.body` property. - -**Note** As `req.body`'s shape is based on user-controlled input, all -properties and values in this object are untrusted and should be validated -before trusting. For example, `req.body.foo.toString()` may fail in multiple -ways, for example the `foo` property may not be there or may not be a string, -and `toString` may not be a function and instead a string or other user input. - -[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/). - -_This does not handle multipart bodies_, due to their complex and typically -large nature. For multipart bodies, you may be interested in the following -modules: - - * [busboy](https://www.npmjs.org/package/busboy#readme) and - [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) - * [multiparty](https://www.npmjs.org/package/multiparty#readme) and - [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) - * [formidable](https://www.npmjs.org/package/formidable#readme) - * [multer](https://www.npmjs.org/package/multer#readme) - -This module provides the following parsers: - - * [JSON body parser](#bodyparserjsonoptions) - * [Raw body parser](#bodyparserrawoptions) - * [Text body parser](#bodyparsertextoptions) - * [URL-encoded form body parser](#bodyparserurlencodedoptions) - -Other body parsers you might be interested in: - -- [body](https://www.npmjs.org/package/body#readme) -- [co-body](https://www.npmjs.org/package/co-body#readme) - -## Installation - -```sh -$ npm install body-parser -``` - -## API - - - -```js -var bodyParser = require('body-parser') -``` - -The `bodyParser` object exposes various factories to create middlewares. All -middlewares will populate the `req.body` property with the parsed body when -the `Content-Type` request header matches the `type` option, or an empty -object (`{}`) if there was no body to parse, the `Content-Type` was not matched, -or an error occurred. - -The various errors returned by this module are described in the -[errors section](#errors). - -### bodyParser.json([options]) - -Returns middleware that only parses `json` and only looks at requests where -the `Content-Type` header matches the `type` option. This parser accepts any -Unicode encoding of the body and supports automatic inflation of `gzip` and -`deflate` encodings. - -A new `body` object containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`). - -#### Options - -The `json` function takes an optional `options` object that may contain any of -the following keys: - -##### inflate - -When set to `true`, then deflated (compressed) bodies will be inflated; when -`false`, deflated bodies are rejected. Defaults to `true`. - -##### limit - -Controls the maximum request body size. If this is a number, then the value -specifies the number of bytes; if it is a string, the value is passed to the -[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults -to `'100kb'`. - -##### reviver - -The `reviver` option is passed directly to `JSON.parse` as the second -argument. You can find more information on this argument -[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). - -##### strict - -When set to `true`, will only accept arrays and objects; when `false` will -accept anything `JSON.parse` accepts. Defaults to `true`. - -##### type - -The `type` option is used to determine what media type the middleware will -parse. This option can be a string, array of strings, or a function. If not a -function, `type` option is passed directly to the -[type-is](https://www.npmjs.org/package/type-is#readme) library and this can -be an extension name (like `json`), a mime type (like `application/json`), or -a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` -option is called as `fn(req)` and the request is parsed if it returns a truthy -value. Defaults to `application/json`. - -##### verify - -The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, -where `buf` is a `Buffer` of the raw request body and `encoding` is the -encoding of the request. The parsing can be aborted by throwing an error. - -### bodyParser.raw([options]) - -Returns middleware that parses all bodies as a `Buffer` and only looks at -requests where the `Content-Type` header matches the `type` option. This -parser supports automatic inflation of `gzip` and `deflate` encodings. - -A new `body` object containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`). This will be a `Buffer` object -of the body. - -#### Options - -The `raw` function takes an optional `options` object that may contain any of -the following keys: - -##### inflate - -When set to `true`, then deflated (compressed) bodies will be inflated; when -`false`, deflated bodies are rejected. Defaults to `true`. - -##### limit - -Controls the maximum request body size. If this is a number, then the value -specifies the number of bytes; if it is a string, the value is passed to the -[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults -to `'100kb'`. - -##### type - -The `type` option is used to determine what media type the middleware will -parse. This option can be a string, array of strings, or a function. -If not a function, `type` option is passed directly to the -[type-is](https://www.npmjs.org/package/type-is#readme) library and this -can be an extension name (like `bin`), a mime type (like -`application/octet-stream`), or a mime type with a wildcard (like `*/*` or -`application/*`). If a function, the `type` option is called as `fn(req)` -and the request is parsed if it returns a truthy value. Defaults to -`application/octet-stream`. - -##### verify - -The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, -where `buf` is a `Buffer` of the raw request body and `encoding` is the -encoding of the request. The parsing can be aborted by throwing an error. - -### bodyParser.text([options]) - -Returns middleware that parses all bodies as a string and only looks at -requests where the `Content-Type` header matches the `type` option. This -parser supports automatic inflation of `gzip` and `deflate` encodings. - -A new `body` string containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`). This will be a string of the -body. - -#### Options - -The `text` function takes an optional `options` object that may contain any of -the following keys: - -##### defaultCharset - -Specify the default character set for the text content if the charset is not -specified in the `Content-Type` header of the request. Defaults to `utf-8`. - -##### inflate - -When set to `true`, then deflated (compressed) bodies will be inflated; when -`false`, deflated bodies are rejected. Defaults to `true`. - -##### limit - -Controls the maximum request body size. If this is a number, then the value -specifies the number of bytes; if it is a string, the value is passed to the -[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults -to `'100kb'`. - -##### type - -The `type` option is used to determine what media type the middleware will -parse. This option can be a string, array of strings, or a function. If not -a function, `type` option is passed directly to the -[type-is](https://www.npmjs.org/package/type-is#readme) library and this can -be an extension name (like `txt`), a mime type (like `text/plain`), or a mime -type with a wildcard (like `*/*` or `text/*`). If a function, the `type` -option is called as `fn(req)` and the request is parsed if it returns a -truthy value. Defaults to `text/plain`. - -##### verify - -The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, -where `buf` is a `Buffer` of the raw request body and `encoding` is the -encoding of the request. The parsing can be aborted by throwing an error. - -### bodyParser.urlencoded([options]) - -Returns middleware that only parses `urlencoded` bodies and only looks at -requests where the `Content-Type` header matches the `type` option. This -parser accepts only UTF-8 encoding of the body and supports automatic -inflation of `gzip` and `deflate` encodings. - -A new `body` object containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`). This object will contain -key-value pairs, where the value can be a string or array (when `extended` is -`false`), or any type (when `extended` is `true`). - -#### Options - -The `urlencoded` function takes an optional `options` object that may contain -any of the following keys: - -##### extended - -The `extended` option allows to choose between parsing the URL-encoded data -with the `querystring` library (when `false`) or the `qs` library (when -`true`). The "extended" syntax allows for rich objects and arrays to be -encoded into the URL-encoded format, allowing for a JSON-like experience -with URL-encoded. For more information, please -[see the qs library](https://www.npmjs.org/package/qs#readme). - -Defaults to `true`, but using the default has been deprecated. Please -research into the difference between `qs` and `querystring` and choose the -appropriate setting. - -##### inflate - -When set to `true`, then deflated (compressed) bodies will be inflated; when -`false`, deflated bodies are rejected. Defaults to `true`. - -##### limit - -Controls the maximum request body size. If this is a number, then the value -specifies the number of bytes; if it is a string, the value is passed to the -[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults -to `'100kb'`. - -##### parameterLimit - -The `parameterLimit` option controls the maximum number of parameters that -are allowed in the URL-encoded data. If a request contains more parameters -than this value, a 413 will be returned to the client. Defaults to `1000`. - -##### type - -The `type` option is used to determine what media type the middleware will -parse. This option can be a string, array of strings, or a function. If not -a function, `type` option is passed directly to the -[type-is](https://www.npmjs.org/package/type-is#readme) library and this can -be an extension name (like `urlencoded`), a mime type (like -`application/x-www-form-urlencoded`), or a mime type with a wildcard (like -`*/x-www-form-urlencoded`). If a function, the `type` option is called as -`fn(req)` and the request is parsed if it returns a truthy value. Defaults -to `application/x-www-form-urlencoded`. - -##### verify - -The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, -where `buf` is a `Buffer` of the raw request body and `encoding` is the -encoding of the request. The parsing can be aborted by throwing an error. - -## Errors - -The middlewares provided by this module create errors depending on the error -condition during parsing. The errors will typically have a `status`/`statusCode` -property that contains the suggested HTTP response code, an `expose` property -to determine if the `message` property should be displayed to the client, a -`type` property to determine the type of error without matching against the -`message`, and a `body` property containing the read body, if available. - -The following are the common errors emitted, though any error can come through -for various reasons. - -### content encoding unsupported - -This error will occur when the request had a `Content-Encoding` header that -contained an encoding but the "inflation" option was set to `false`. The -`status` property is set to `415`, the `type` property is set to -`'encoding.unsupported'`, and the `charset` property will be set to the -encoding that is unsupported. - -### request aborted - -This error will occur when the request is aborted by the client before reading -the body has finished. The `received` property will be set to the number of -bytes received before the request was aborted and the `expected` property is -set to the number of expected bytes. The `status` property is set to `400` -and `type` property is set to `'request.aborted'`. - -### request entity too large - -This error will occur when the request body's size is larger than the "limit" -option. The `limit` property will be set to the byte limit and the `length` -property will be set to the request body's length. The `status` property is -set to `413` and the `type` property is set to `'entity.too.large'`. - -### request size did not match content length - -This error will occur when the request's length did not match the length from -the `Content-Length` header. This typically occurs when the request is malformed, -typically when the `Content-Length` header was calculated based on characters -instead of bytes. The `status` property is set to `400` and the `type` property -is set to `'request.size.invalid'`. - -### stream encoding should not be set - -This error will occur when something called the `req.setEncoding` method prior -to this middleware. This module operates directly on bytes only and you cannot -call `req.setEncoding` when using this module. The `status` property is set to -`500` and the `type` property is set to `'stream.encoding.set'`. - -### too many parameters - -This error will occur when the content of the request exceeds the configured -`parameterLimit` for the `urlencoded` parser. The `status` property is set to -`413` and the `type` property is set to `'parameters.too.many'`. - -### unsupported charset "BOGUS" - -This error will occur when the request had a charset parameter in the -`Content-Type` header, but the `iconv-lite` module does not support it OR the -parser does not support it. The charset is contained in the message as well -as in the `charset` property. The `status` property is set to `415`, the -`type` property is set to `'charset.unsupported'`, and the `charset` property -is set to the charset that is unsupported. - -### unsupported content encoding "bogus" - -This error will occur when the request had a `Content-Encoding` header that -contained an unsupported encoding. The encoding is contained in the message -as well as in the `encoding` property. The `status` property is set to `415`, -the `type` property is set to `'encoding.unsupported'`, and the `encoding` -property is set to the encoding that is unsupported. - -## Examples - -### Express/Connect top-level generic - -This example demonstrates adding a generic JSON and URL-encoded parser as a -top-level middleware, which will parse the bodies of all incoming requests. -This is the simplest setup. - -```js -var express = require('express') -var bodyParser = require('body-parser') - -var app = express() - -// parse application/x-www-form-urlencoded -app.use(bodyParser.urlencoded({ extended: false })) - -// parse application/json -app.use(bodyParser.json()) - -app.use(function (req, res) { - res.setHeader('Content-Type', 'text/plain') - res.write('you posted:\n') - res.end(JSON.stringify(req.body, null, 2)) -}) -``` - -### Express route-specific - -This example demonstrates adding body parsers specifically to the routes that -need them. In general, this is the most recommended way to use body-parser with -Express. - -```js -var express = require('express') -var bodyParser = require('body-parser') - -var app = express() - -// create application/json parser -var jsonParser = bodyParser.json() - -// create application/x-www-form-urlencoded parser -var urlencodedParser = bodyParser.urlencoded({ extended: false }) - -// POST /login gets urlencoded bodies -app.post('/login', urlencodedParser, function (req, res) { - res.send('welcome, ' + req.body.username) -}) - -// POST /api/users gets JSON bodies -app.post('/api/users', jsonParser, function (req, res) { - // create user in req.body -}) -``` - -### Change accepted type for parsers - -All the parsers accept a `type` option which allows you to change the -`Content-Type` that the middleware will parse. - -```js -var express = require('express') -var bodyParser = require('body-parser') - -var app = express() - -// parse various different custom JSON types as JSON -app.use(bodyParser.json({ type: 'application/*+json' })) - -// parse some custom thing into a Buffer -app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) - -// parse an HTML body into a string -app.use(bodyParser.text({ type: 'text/html' })) -``` - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/body-parser.svg -[npm-url]: https://npmjs.org/package/body-parser -[travis-image]: https://img.shields.io/travis/expressjs/body-parser/master.svg -[travis-url]: https://travis-ci.org/expressjs/body-parser -[coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg -[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master -[downloads-image]: https://img.shields.io/npm/dm/body-parser.svg -[downloads-url]: https://npmjs.org/package/body-parser diff --git a/node_modules/body-parser/index.js b/node_modules/body-parser/index.js deleted file mode 100644 index 93c3a1f..0000000 --- a/node_modules/body-parser/index.js +++ /dev/null @@ -1,157 +0,0 @@ -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var deprecate = require('depd')('body-parser') - -/** - * Cache of loaded parsers. - * @private - */ - -var parsers = Object.create(null) - -/** - * @typedef Parsers - * @type {function} - * @property {function} json - * @property {function} raw - * @property {function} text - * @property {function} urlencoded - */ - -/** - * Module exports. - * @type {Parsers} - */ - -exports = module.exports = deprecate.function(bodyParser, - 'bodyParser: use individual json/urlencoded middlewares') - -/** - * JSON parser. - * @public - */ - -Object.defineProperty(exports, 'json', { - configurable: true, - enumerable: true, - get: createParserGetter('json') -}) - -/** - * Raw parser. - * @public - */ - -Object.defineProperty(exports, 'raw', { - configurable: true, - enumerable: true, - get: createParserGetter('raw') -}) - -/** - * Text parser. - * @public - */ - -Object.defineProperty(exports, 'text', { - configurable: true, - enumerable: true, - get: createParserGetter('text') -}) - -/** - * URL-encoded parser. - * @public - */ - -Object.defineProperty(exports, 'urlencoded', { - configurable: true, - enumerable: true, - get: createParserGetter('urlencoded') -}) - -/** - * Create a middleware to parse json and urlencoded bodies. - * - * @param {object} [options] - * @return {function} - * @deprecated - * @public - */ - -function bodyParser (options) { - var opts = {} - - // exclude type option - if (options) { - for (var prop in options) { - if (prop !== 'type') { - opts[prop] = options[prop] - } - } - } - - var _urlencoded = exports.urlencoded(opts) - var _json = exports.json(opts) - - return function bodyParser (req, res, next) { - _json(req, res, function (err) { - if (err) return next(err) - _urlencoded(req, res, next) - }) - } -} - -/** - * Create a getter for loading a parser. - * @private - */ - -function createParserGetter (name) { - return function get () { - return loadParser(name) - } -} - -/** - * Load a parser module. - * @private - */ - -function loadParser (parserName) { - var parser = parsers[parserName] - - if (parser !== undefined) { - return parser - } - - // this uses a switch for static require analysis - switch (parserName) { - case 'json': - parser = require('./lib/types/json') - break - case 'raw': - parser = require('./lib/types/raw') - break - case 'text': - parser = require('./lib/types/text') - break - case 'urlencoded': - parser = require('./lib/types/urlencoded') - break - } - - // store to prevent invoking require() - return (parsers[parserName] = parser) -} diff --git a/node_modules/body-parser/lib/read.js b/node_modules/body-parser/lib/read.js deleted file mode 100644 index c102609..0000000 --- a/node_modules/body-parser/lib/read.js +++ /dev/null @@ -1,181 +0,0 @@ -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var createError = require('http-errors') -var getBody = require('raw-body') -var iconv = require('iconv-lite') -var onFinished = require('on-finished') -var zlib = require('zlib') - -/** - * Module exports. - */ - -module.exports = read - -/** - * Read a request into a buffer and parse. - * - * @param {object} req - * @param {object} res - * @param {function} next - * @param {function} parse - * @param {function} debug - * @param {object} options - * @private - */ - -function read (req, res, next, parse, debug, options) { - var length - var opts = options - var stream - - // flag as parsed - req._body = true - - // read options - var encoding = opts.encoding !== null - ? opts.encoding - : null - var verify = opts.verify - - try { - // get the content stream - stream = contentstream(req, debug, opts.inflate) - length = stream.length - stream.length = undefined - } catch (err) { - return next(err) - } - - // set raw-body options - opts.length = length - opts.encoding = verify - ? null - : encoding - - // assert charset is supported - if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { - return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: 'charset.unsupported' - })) - } - - // read body - debug('read body') - getBody(stream, opts, function (error, body) { - if (error) { - var _error - - if (error.type === 'encoding.unsupported') { - // echo back charset - _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: 'charset.unsupported' - }) - } else { - // set status code on error - _error = createError(400, error) - } - - // read off entire request - stream.resume() - onFinished(req, function onfinished () { - next(createError(400, _error)) - }) - return - } - - // verify - if (verify) { - try { - debug('verify body') - verify(req, res, body, encoding) - } catch (err) { - next(createError(403, err, { - body: body, - type: err.type || 'entity.verify.failed' - })) - return - } - } - - // parse - var str = body - try { - debug('parse body') - str = typeof body !== 'string' && encoding !== null - ? iconv.decode(body, encoding) - : body - req.body = parse(str) - } catch (err) { - next(createError(400, err, { - body: str, - type: err.type || 'entity.parse.failed' - })) - return - } - - next() - }) -} - -/** - * Get the content stream of the request. - * - * @param {object} req - * @param {function} debug - * @param {boolean} [inflate=true] - * @return {object} - * @api private - */ - -function contentstream (req, debug, inflate) { - var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() - var length = req.headers['content-length'] - var stream - - debug('content-encoding "%s"', encoding) - - if (inflate === false && encoding !== 'identity') { - throw createError(415, 'content encoding unsupported', { - encoding: encoding, - type: 'encoding.unsupported' - }) - } - - switch (encoding) { - case 'deflate': - stream = zlib.createInflate() - debug('inflate body') - req.pipe(stream) - break - case 'gzip': - stream = zlib.createGunzip() - debug('gunzip body') - req.pipe(stream) - break - case 'identity': - stream = req - stream.length = length - break - default: - throw createError(415, 'unsupported content encoding "' + encoding + '"', { - encoding: encoding, - type: 'encoding.unsupported' - }) - } - - return stream -} diff --git a/node_modules/body-parser/lib/types/json.js b/node_modules/body-parser/lib/types/json.js deleted file mode 100644 index 2971dc1..0000000 --- a/node_modules/body-parser/lib/types/json.js +++ /dev/null @@ -1,230 +0,0 @@ -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var bytes = require('bytes') -var contentType = require('content-type') -var createError = require('http-errors') -var debug = require('debug')('body-parser:json') -var read = require('../read') -var typeis = require('type-is') - -/** - * Module exports. - */ - -module.exports = json - -/** - * RegExp to match the first non-space in a string. - * - * Allowed whitespace is defined in RFC 7159: - * - * ws = *( - * %x20 / ; Space - * %x09 / ; Horizontal tab - * %x0A / ; Line feed or New line - * %x0D ) ; Carriage return - */ - -var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex - -/** - * Create a middleware to parse JSON bodies. - * - * @param {object} [options] - * @return {function} - * @public - */ - -function json (options) { - var opts = options || {} - - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var inflate = opts.inflate !== false - var reviver = opts.reviver - var strict = opts.strict !== false - var type = opts.type || 'application/json' - var verify = opts.verify || false - - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } - - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (body) { - if (body.length === 0) { - // special-case empty json body, as it's a common client-side mistake - // TODO: maybe make this configurable or part of "strict" option - return {} - } - - if (strict) { - var first = firstchar(body) - - if (first !== '{' && first !== '[') { - debug('strict violation') - throw createStrictSyntaxError(body, first) - } - } - - try { - debug('parse json') - return JSON.parse(body, reviver) - } catch (e) { - throw normalizeJsonSyntaxError(e, { - message: e.message, - stack: e.stack - }) - } - } - - return function jsonParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } - - req.body = req.body || {} - - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } - - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } - - // assert charset per RFC 7159 sec 8.1 - var charset = getCharset(req) || 'utf-8' - if (charset.substr(0, 4) !== 'utf-') { - debug('invalid charset') - next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { - charset: charset, - type: 'charset.unsupported' - })) - return - } - - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} - -/** - * Create strict violation syntax error matching native error. - * - * @param {string} str - * @param {string} char - * @return {Error} - * @private - */ - -function createStrictSyntaxError (str, char) { - var index = str.indexOf(char) - var partial = str.substring(0, index) + '#' - - try { - JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') - } catch (e) { - return normalizeJsonSyntaxError(e, { - message: e.message.replace('#', char), - stack: e.stack - }) - } -} - -/** - * Get the first non-whitespace character in a string. - * - * @param {string} str - * @return {function} - * @private - */ - -function firstchar (str) { - return FIRST_CHAR_REGEXP.exec(str)[1] -} - -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ - -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } -} - -/** - * Normalize a SyntaxError for JSON.parse. - * - * @param {SyntaxError} error - * @param {object} obj - * @return {SyntaxError} - */ - -function normalizeJsonSyntaxError (error, obj) { - var keys = Object.getOwnPropertyNames(error) - - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - if (key !== 'stack' && key !== 'message') { - delete error[key] - } - } - - // replace stack before message for Node.js 0.10 and below - error.stack = obj.stack.replace(error.message, obj.message) - error.message = obj.message - - return error -} - -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} diff --git a/node_modules/body-parser/lib/types/raw.js b/node_modules/body-parser/lib/types/raw.js deleted file mode 100644 index f5d1b67..0000000 --- a/node_modules/body-parser/lib/types/raw.js +++ /dev/null @@ -1,101 +0,0 @@ -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - */ - -var bytes = require('bytes') -var debug = require('debug')('body-parser:raw') -var read = require('../read') -var typeis = require('type-is') - -/** - * Module exports. - */ - -module.exports = raw - -/** - * Create a middleware to parse raw bodies. - * - * @param {object} [options] - * @return {function} - * @api public - */ - -function raw (options) { - var opts = options || {} - - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'application/octet-stream' - var verify = opts.verify || false - - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } - - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (buf) { - return buf - } - - return function rawParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } - - req.body = req.body || {} - - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } - - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } - - // read - read(req, res, next, parse, debug, { - encoding: null, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} - -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} diff --git a/node_modules/body-parser/lib/types/text.js b/node_modules/body-parser/lib/types/text.js deleted file mode 100644 index 083a009..0000000 --- a/node_modules/body-parser/lib/types/text.js +++ /dev/null @@ -1,121 +0,0 @@ -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - */ - -var bytes = require('bytes') -var contentType = require('content-type') -var debug = require('debug')('body-parser:text') -var read = require('../read') -var typeis = require('type-is') - -/** - * Module exports. - */ - -module.exports = text - -/** - * Create a middleware to parse text bodies. - * - * @param {object} [options] - * @return {function} - * @api public - */ - -function text (options) { - var opts = options || {} - - var defaultCharset = opts.defaultCharset || 'utf-8' - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'text/plain' - var verify = opts.verify || false - - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } - - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (buf) { - return buf - } - - return function textParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } - - req.body = req.body || {} - - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } - - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } - - // get charset - var charset = getCharset(req) || defaultCharset - - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} - -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ - -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } -} - -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} diff --git a/node_modules/body-parser/lib/types/urlencoded.js b/node_modules/body-parser/lib/types/urlencoded.js deleted file mode 100644 index b2ca8f1..0000000 --- a/node_modules/body-parser/lib/types/urlencoded.js +++ /dev/null @@ -1,284 +0,0 @@ -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var bytes = require('bytes') -var contentType = require('content-type') -var createError = require('http-errors') -var debug = require('debug')('body-parser:urlencoded') -var deprecate = require('depd')('body-parser') -var read = require('../read') -var typeis = require('type-is') - -/** - * Module exports. - */ - -module.exports = urlencoded - -/** - * Cache of parser modules. - */ - -var parsers = Object.create(null) - -/** - * Create a middleware to parse urlencoded bodies. - * - * @param {object} [options] - * @return {function} - * @public - */ - -function urlencoded (options) { - var opts = options || {} - - // notice because option default will flip in next major - if (opts.extended === undefined) { - deprecate('undefined extended: provide extended option') - } - - var extended = opts.extended !== false - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'application/x-www-form-urlencoded' - var verify = opts.verify || false - - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } - - // create the appropriate query parser - var queryparse = extended - ? extendedparser(opts) - : simpleparser(opts) - - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (body) { - return body.length - ? queryparse(body) - : {} - } - - return function urlencodedParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } - - req.body = req.body || {} - - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } - - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } - - // assert charset - var charset = getCharset(req) || 'utf-8' - if (charset !== 'utf-8') { - debug('invalid charset') - next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { - charset: charset, - type: 'charset.unsupported' - })) - return - } - - // read - read(req, res, next, parse, debug, { - debug: debug, - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} - -/** - * Get the extended query parser. - * - * @param {object} options - */ - -function extendedparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('qs') - - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') - } - - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 - } - - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) - - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) - } - - var arrayLimit = Math.max(100, paramCount) - - debug('parse extended urlencoding') - return parse(body, { - allowPrototypes: true, - arrayLimit: arrayLimit, - depth: Infinity, - parameterLimit: parameterLimit - }) - } -} - -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ - -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } -} - -/** - * Count the number of parameters, stopping once limit reached - * - * @param {string} body - * @param {number} limit - * @api private - */ - -function parameterCount (body, limit) { - var count = 0 - var index = 0 - - while ((index = body.indexOf('&', index)) !== -1) { - count++ - index++ - - if (count === limit) { - return undefined - } - } - - return count -} - -/** - * Get parser for module name dynamically. - * - * @param {string} name - * @return {function} - * @api private - */ - -function parser (name) { - var mod = parsers[name] - - if (mod !== undefined) { - return mod.parse - } - - // this uses a switch for static require analysis - switch (name) { - case 'qs': - mod = require('qs') - break - case 'querystring': - mod = require('querystring') - break - } - - // store to prevent invoking require() - parsers[name] = mod - - return mod.parse -} - -/** - * Get the simple query parser. - * - * @param {object} options - */ - -function simpleparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('querystring') - - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') - } - - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 - } - - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) - - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) - } - - debug('parse urlencoding') - return parse(body, undefined, undefined, { maxKeys: parameterLimit }) - } -} - -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} diff --git a/node_modules/body-parser/node_modules/debug/.coveralls.yml b/node_modules/body-parser/node_modules/debug/.coveralls.yml deleted file mode 100644 index 20a7068..0000000 --- a/node_modules/body-parser/node_modules/debug/.coveralls.yml +++ /dev/null @@ -1 +0,0 @@ -repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/body-parser/node_modules/debug/.eslintrc b/node_modules/body-parser/node_modules/debug/.eslintrc deleted file mode 100644 index 8a37ae2..0000000 --- a/node_modules/body-parser/node_modules/debug/.eslintrc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "env": { - "browser": true, - "node": true - }, - "rules": { - "no-console": 0, - "no-empty": [1, { "allowEmptyCatch": true }] - }, - "extends": "eslint:recommended" -} diff --git a/node_modules/body-parser/node_modules/debug/.npmignore b/node_modules/body-parser/node_modules/debug/.npmignore deleted file mode 100644 index 5f60eec..0000000 --- a/node_modules/body-parser/node_modules/debug/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -support -test -examples -example -*.sock -dist -yarn.lock -coverage -bower.json diff --git a/node_modules/body-parser/node_modules/debug/.travis.yml b/node_modules/body-parser/node_modules/debug/.travis.yml deleted file mode 100644 index 6c6090c..0000000 --- a/node_modules/body-parser/node_modules/debug/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ - -language: node_js -node_js: - - "6" - - "5" - - "4" - -install: - - make node_modules - -script: - - make lint - - make test - - make coveralls diff --git a/node_modules/body-parser/node_modules/debug/CHANGELOG.md b/node_modules/body-parser/node_modules/debug/CHANGELOG.md deleted file mode 100644 index eadaa18..0000000 --- a/node_modules/body-parser/node_modules/debug/CHANGELOG.md +++ /dev/null @@ -1,362 +0,0 @@ - -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/body-parser/node_modules/debug/LICENSE b/node_modules/body-parser/node_modules/debug/LICENSE deleted file mode 100644 index 658c933..0000000 --- a/node_modules/body-parser/node_modules/debug/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -(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/body-parser/node_modules/debug/Makefile b/node_modules/body-parser/node_modules/debug/Makefile deleted file mode 100644 index 584da8b..0000000 --- a/node_modules/body-parser/node_modules/debug/Makefile +++ /dev/null @@ -1,50 +0,0 @@ -# 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/body-parser/node_modules/debug/README.md b/node_modules/body-parser/node_modules/debug/README.md deleted file mode 100644 index f67be6b..0000000 --- a/node_modules/body-parser/node_modules/debug/README.md +++ /dev/null @@ -1,312 +0,0 @@ -# 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/body-parser/node_modules/debug/component.json b/node_modules/body-parser/node_modules/debug/component.json deleted file mode 100644 index 9de2641..0000000 --- a/node_modules/body-parser/node_modules/debug/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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/body-parser/node_modules/debug/karma.conf.js b/node_modules/body-parser/node_modules/debug/karma.conf.js deleted file mode 100644 index 103a82d..0000000 --- a/node_modules/body-parser/node_modules/debug/karma.conf.js +++ /dev/null @@ -1,70 +0,0 @@ -// 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/body-parser/node_modules/debug/node.js b/node_modules/body-parser/node_modules/debug/node.js deleted file mode 100644 index 7fc36fe..0000000 --- a/node_modules/body-parser/node_modules/debug/node.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./src/node'); diff --git a/node_modules/body-parser/node_modules/debug/package.json b/node_modules/body-parser/node_modules/debug/package.json deleted file mode 100644 index a0011fe..0000000 --- a/node_modules/body-parser/node_modules/debug/package.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "_from": "debug@2.6.9", - "_id": "debug@2.6.9", - "_inBundle": false, - "_integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "_location": "/body-parser/debug", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "debug@2.6.9", - "name": "debug", - "escapedName": "debug", - "rawSpec": "2.6.9", - "saveSpec": null, - "fetchSpec": "2.6.9" - }, - "_requiredBy": [ - "/body-parser" - ], - "_resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "_shasum": "5d128515df134ff327e90a4c93f4e077a536341f", - "_spec": "debug@2.6.9", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/body-parser", - "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/body-parser/node_modules/debug/src/browser.js b/node_modules/body-parser/node_modules/debug/src/browser.js deleted file mode 100644 index 7106924..0000000 --- a/node_modules/body-parser/node_modules/debug/src/browser.js +++ /dev/null @@ -1,185 +0,0 @@ -/** - * 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/body-parser/node_modules/debug/src/debug.js b/node_modules/body-parser/node_modules/debug/src/debug.js deleted file mode 100644 index 6a5e3fc..0000000 --- a/node_modules/body-parser/node_modules/debug/src/debug.js +++ /dev/null @@ -1,202 +0,0 @@ - -/** - * 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/body-parser/node_modules/debug/src/index.js b/node_modules/body-parser/node_modules/debug/src/index.js deleted file mode 100644 index e12cf4d..0000000 --- a/node_modules/body-parser/node_modules/debug/src/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/** - * 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/body-parser/node_modules/debug/src/inspector-log.js b/node_modules/body-parser/node_modules/debug/src/inspector-log.js deleted file mode 100644 index 60ea6c0..0000000 --- a/node_modules/body-parser/node_modules/debug/src/inspector-log.js +++ /dev/null @@ -1,15 +0,0 @@ -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/body-parser/node_modules/debug/src/node.js b/node_modules/body-parser/node_modules/debug/src/node.js deleted file mode 100644 index b15109c..0000000 --- a/node_modules/body-parser/node_modules/debug/src/node.js +++ /dev/null @@ -1,248 +0,0 @@ -/** - * 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/body-parser/node_modules/ms/index.js b/node_modules/body-parser/node_modules/ms/index.js deleted file mode 100644 index 6a522b1..0000000 --- a/node_modules/body-parser/node_modules/ms/index.js +++ /dev/null @@ -1,152 +0,0 @@ -/** - * 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/body-parser/node_modules/ms/license.md b/node_modules/body-parser/node_modules/ms/license.md deleted file mode 100644 index 69b6125..0000000 --- a/node_modules/body-parser/node_modules/ms/license.md +++ /dev/null @@ -1,21 +0,0 @@ -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/body-parser/node_modules/ms/package.json b/node_modules/body-parser/node_modules/ms/package.json deleted file mode 100644 index e0f9314..0000000 --- a/node_modules/body-parser/node_modules/ms/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "ms@2.0.0", - "_id": "ms@2.0.0", - "_inBundle": false, - "_integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "_location": "/body-parser/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": [ - "/body-parser/debug" - ], - "_resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "_shasum": "5608aeadfc00be6c2901df5f9861788de0d597c8", - "_spec": "ms@2.0.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/body-parser/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/body-parser/node_modules/ms/readme.md b/node_modules/body-parser/node_modules/ms/readme.md deleted file mode 100644 index 84a9974..0000000 --- a/node_modules/body-parser/node_modules/ms/readme.md +++ /dev/null @@ -1,51 +0,0 @@ -# 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/body-parser/package.json b/node_modules/body-parser/package.json deleted file mode 100644 index 40c7c32..0000000 --- a/node_modules/body-parser/package.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "_from": "body-parser@^1.19.0", - "_id": "body-parser@1.19.0", - "_inBundle": false, - "_integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==", - "_location": "/body-parser", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "body-parser@^1.19.0", - "name": "body-parser", - "escapedName": "body-parser", - "rawSpec": "^1.19.0", - "saveSpec": null, - "fetchSpec": "^1.19.0" - }, - "_requiredBy": [ - "#USER", - "/", - "/express" - ], - "_resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz", - "_shasum": "96b2709e57c9c4e09a6fd66a8fd979844f69f08a", - "_spec": "body-parser@^1.19.0", - "_where": "/workspace/dbproject", - "bugs": { - "url": "https://github.com/expressjs/body-parser/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - } - ], - "dependencies": { - "bytes": "3.1.0", - "content-type": "~1.0.4", - "debug": "2.6.9", - "depd": "~1.1.2", - "http-errors": "1.7.2", - "iconv-lite": "0.4.24", - "on-finished": "~2.3.0", - "qs": "6.7.0", - "raw-body": "2.4.0", - "type-is": "~1.6.17" - }, - "deprecated": false, - "description": "Node.js body parsing middleware", - "devDependencies": { - "eslint": "5.16.0", - "eslint-config-standard": "12.0.0", - "eslint-plugin-import": "2.17.2", - "eslint-plugin-markdown": "1.0.0", - "eslint-plugin-node": "8.0.1", - "eslint-plugin-promise": "4.1.1", - "eslint-plugin-standard": "4.0.0", - "istanbul": "0.4.5", - "methods": "1.1.2", - "mocha": "6.1.4", - "safe-buffer": "5.1.2", - "supertest": "4.0.2" - }, - "engines": { - "node": ">= 0.8" - }, - "files": [ - "lib/", - "LICENSE", - "HISTORY.md", - "index.js" - ], - "homepage": "https://github.com/expressjs/body-parser#readme", - "license": "MIT", - "name": "body-parser", - "repository": { - "type": "git", - "url": "git+https://github.com/expressjs/body-parser.git" - }, - "scripts": { - "lint": "eslint --plugin markdown --ext js,md .", - "test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/" - }, - "version": "1.19.0" -} diff --git a/node_modules/bson/HISTORY.md b/node_modules/bson/HISTORY.md deleted file mode 100644 index 36b90e2..0000000 --- a/node_modules/bson/HISTORY.md +++ /dev/null @@ -1,283 +0,0 @@ - -## [1.1.3](https://github.com/mongodb/js-bson/compare/v1.1.2...v1.1.3) (2019-11-09) - -Reverts 1.1.2 - - -## [1.1.2](https://github.com/mongodb/js-bson/compare/v1.1.1...v1.1.2) (2019-11-08) - - -### Bug Fixes - -* **_bsontype:** only check bsontype if it is a prototype member. ([dd8a349](https://github.com/mongodb/js-bson/commit/dd8a349)) - - - - -## [1.1.1](https://github.com/mongodb/js-bson/compare/v1.1.0...v1.1.1) (2019-03-08) - - -### Bug Fixes - -* **object-id:** support 4.x->1.x interop for MinKey and ObjectId ([53419a5](https://github.com/mongodb/js-bson/commit/53419a5)) - - -### Features - -* replace new Buffer with modern versions ([24aefba](https://github.com/mongodb/js-bson/commit/24aefba)) - - - - -# [1.1.0](https://github.com/mongodb/js-bson/compare/v1.0.9...v1.1.0) (2018-08-13) - - -### Bug Fixes - -* **serializer:** do not use checkKeys for $clusterTime ([573e141](https://github.com/mongodb/js-bson/commit/573e141)) - - - - -## [1.0.9](https://github.com/mongodb/js-bson/compare/v1.0.8...v1.0.9) (2018-06-07) - - -### Bug Fixes - -* **serializer:** remove use of `const` ([5feb12f](https://github.com/mongodb/js-bson/commit/5feb12f)) - - - - -## [1.0.7](https://github.com/mongodb/js-bson/compare/v1.0.6...v1.0.7) (2018-06-06) - - -### Bug Fixes - -* **binary:** add type checking for buffer ([26b05b5](https://github.com/mongodb/js-bson/commit/26b05b5)) -* **bson:** fix custom inspect property ([080323b](https://github.com/mongodb/js-bson/commit/080323b)) -* **readme:** clarify documentation about deserialize methods ([20f764c](https://github.com/mongodb/js-bson/commit/20f764c)) -* **serialization:** normalize function stringification ([1320c10](https://github.com/mongodb/js-bson/commit/1320c10)) - - - - -## [1.0.6](https://github.com/mongodb/js-bson/compare/v1.0.5...v1.0.6) (2018-03-12) - - -### Features - -* **serialization:** support arbitrary sizes for the internal serialization buffer ([abe97bc](https://github.com/mongodb/js-bson/commit/abe97bc)) - - - - -## 1.0.5 (2018-02-26) - - -### Bug Fixes - -* **decimal128:** add basic guard against REDOS attacks ([bd61c45](https://github.com/mongodb/js-bson/commit/bd61c45)) -* **objectid:** if pid is 1, use random value ([e188ae6](https://github.com/mongodb/js-bson/commit/e188ae6)) - - - -1.0.4 2016-01-11 ----------------- -- #204 remove Buffer.from as it's partially broken in early 4.x.x. series of node releases. - -1.0.3 2016-01-03 ----------------- -- Fixed toString for ObjectId so it will work with inspect. - -1.0.2 2016-01-02 ----------------- -- Minor optimizations for ObjectID to use Buffer.from where available. - -1.0.1 2016-12-06 ----------------- -- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons. - -1.0.0 2016-12-06 ----------------- -- Introduced new BSON API and documentation. - -0.5.7 2016-11-18 ------------------ -- NODE-848 BSON Regex flags must be alphabetically ordered. - -0.5.6 2016-10-19 ------------------ -- NODE-833, Detects cyclic dependencies in documents and throws error if one is found. -- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke). - -0.5.5 2016-09-15 ------------------ -- Added DBPointer up conversion to DBRef - -0.5.4 2016-08-23 ------------------ -- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only. - -0.5.3 2016-07-11 ------------------ -- Throw error if ObjectId is not a string or a buffer. - -0.5.2 2016-07-11 ------------------ -- All values encoded big-endian style for ObjectId. - -0.5.1 2016-07-11 ------------------ -- Fixed encoding/decoding issue in ObjectId timestamp generation. -- Removed BinaryParser dependency from the serializer/deserializer. - -0.5.0 2016-07-05 ------------------ -- Added Decimal128 type and extended test suite to include entire bson corpus. - -0.4.23 2016-04-08 ------------------ -- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries. -- Remove one package from dependency due to having been pulled from NPM. - -0.4.22 2016-03-04 ------------------ -- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas). -- Fixed issue with undefined type on deserializing. - -0.4.21 2016-01-12 ------------------ -- Minor optimizations to avoid non needed object creation. - -0.4.20 2015-10-15 ------------------ -- Added bower file to repository. -- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed) - -0.4.19 2015-10-15 ------------------ -- Remove all support for bson-ext. - -0.4.18 2015-10-15 ------------------ -- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139 -- add option for deserializing binary into Buffer object #116 - -0.4.17 2015-10-15 ------------------ -- Validate regexp string for null bytes and throw if there is one. - -0.4.16 2015-10-07 ------------------ -- Fixed issue with return statement in Map.js. - -0.4.15 2015-10-06 ------------------ -- Exposed Map correctly via index.js file. - -0.4.14 2015-10-06 ------------------ -- Exposed Map correctly via bson.js file. - -0.4.13 2015-10-06 ------------------ -- Added ES6 Map type serialization as well as a polyfill for ES5. - -0.4.12 2015-09-18 ------------------ -- Made ignore undefined an optional parameter. - -0.4.11 2015-08-06 ------------------ -- Minor fix for invalid key checking. - -0.4.10 2015-08-06 ------------------ -- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. -- Some performance improvements by in lining code. - -0.4.9 2015-08-06 ----------------- -- Undefined fields are omitted from serialization in objects. - -0.4.8 2015-07-14 ----------------- -- Fixed size validation to ensure we can deserialize from dumped files. - -0.4.7 2015-06-26 ----------------- -- Added ability to instruct deserializer to return raw BSON buffers for named array fields. -- Minor deserialization optimization by moving inlined function out. - -0.4.6 2015-06-17 ----------------- -- Fixed serializeWithBufferAndIndex bug. - -0.4.5 2015-06-17 ----------------- -- Removed any references to the shared buffer to avoid non GC collectible bson instances. - -0.4.4 2015-06-17 ----------------- -- Fixed rethrowing of error when not RangeError. - -0.4.3 2015-06-17 ----------------- -- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. - -0.4.2 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.1 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.0 2015-06-16 ----------------- -- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. -- Removed bson-ext extension dependency for now. - -0.3.2 2015-03-27 ----------------- -- Removed node-gyp from install script in package.json. - -0.3.1 2015-03-27 ----------------- -- Return pure js version on native() call if failed to initialize. - -0.3.0 2015-03-26 ----------------- -- Pulled out all C++ code into bson-ext and made it an optional dependency. - -0.2.21 2015-03-21 ------------------ -- Updated Nan to 1.7.0 to support io.js and node 0.12.0 - -0.2.19 2015-02-16 ------------------ -- Updated Nan to 1.6.2 to support io.js and node 0.12.0 - -0.2.18 2015-01-20 ------------------ -- Updated Nan to 1.5.1 to support io.js - -0.2.16 2014-12-17 ------------------ -- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's - -0.2.12 2014-08-24 ------------------ -- Fixes for fortify review of c++ extension -- toBSON correctly allows returns of non objects - -0.2.3 2013-10-01 ----------------- -- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) -- Fixed issue where corrupt CString's could cause endless loop -- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) - -0.1.4 2012-09-25 ----------------- -- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/node_modules/bson/LICENSE.md b/node_modules/bson/LICENSE.md deleted file mode 100644 index 261eeb9..0000000 --- a/node_modules/bson/LICENSE.md +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/node_modules/bson/README.md b/node_modules/bson/README.md deleted file mode 100644 index 0688341..0000000 --- a/node_modules/bson/README.md +++ /dev/null @@ -1,170 +0,0 @@ -# BSON parser - -BSON is short for Bin­ary JSON and is the bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. You can learn more about it in [the specification](http://bsonspec.org). - -This browser version of the BSON parser is compiled using [webpack](https://webpack.js.org/) and the current version is pre-compiled in the `browser_build` directory. - -This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext). - -## Usage - -To build a new version perform the following operations: - -``` -npm install -npm run build -``` - -A simple example of how to use BSON in the browser: - -```html - - - -``` - -A simple example of how to use BSON in `Node.js`: - -```js -// Get BSON parser class -var BSON = require('bson') -// Get the Long type -var Long = BSON.Long; -// Create a bson parser instance -var bson = new BSON(); - -// Serialize document -var doc = { long: Long.fromNumber(100) } - -// Serialize a document -var data = bson.serialize(doc) -console.log('data:', data) - -// Deserialize the resulting Buffer -var doc_2 = bson.deserialize(data) -console.log('doc_2:', doc_2) -``` - -## Installation - -`npm install bson` - -## API - -### BSON types - -For all BSON types documentation, please refer to the following sources: - * [MongoDB BSON Type Reference](https://docs.mongodb.com/manual/reference/bson-types/) - * [BSON Spec](https://bsonspec.org/) - -### BSON serialization and deserialiation - -**`new BSON()`** - Creates a new BSON serializer/deserializer you can use to serialize and deserialize BSON. - -#### BSON.serialize - -The BSON `serialize` method takes a JavaScript object and an optional options object and returns a Node.js Buffer. - - * `BSON.serialize(object, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] - * @return {Buffer} returns a Buffer instance. - -#### BSON.serializeWithBufferAndIndex - -The BSON `serializeWithBufferAndIndex` method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer. - - * `BSON.serializeWithBufferAndIndex(object, buffer, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields. - * @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - -#### BSON.calculateObjectSize - -The BSON `calculateObjectSize` method takes a JavaScript object and an optional options object and returns the size of the BSON object. - - * `BSON.calculateObjectSize(object, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] - * @return {Buffer} returns a Buffer instance. - -#### BSON.deserialize - -The BSON `deserialize` method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object. - - * `BSON.deserialize(buffer, options)` - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - -#### BSON.deserializeStream - -The BSON `deserializeStream` method takes a Node.js Buffer, `startIndex` and allow more control over deserialization of a Buffer containing concatenated BSON documents. - - * `BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options)` - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - -## FAQ - -#### Why does `undefined` get converted to `null`? - -The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. - -#### How do I add custom serialization logic? - -This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. - -```javascript -var bson = new BSON(); - -class CustomSerialize { - toBSON() { - return 42; - } -} - -const obj = { answer: new CustomSerialize() }; -// "{ answer: 42 }" -console.log(bson.deserialize(bson.serialize(obj))); -``` diff --git a/node_modules/bson/bower.json b/node_modules/bson/bower.json deleted file mode 100644 index b32140e..0000000 --- a/node_modules/bson/bower.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "author": "Christian Amor Kvalheim ", - "main": "./browser_build/bson.js", - "license": "Apache-2.0", - "moduleType": [ - "globals", - "node" - ], - "ignore": [ - "**/.*", - "alternate_parsers", - "benchmarks", - "bower_components", - "node_modules", - "test", - "tools" - ] -} diff --git a/node_modules/bson/browser_build/bson.js b/node_modules/bson/browser_build/bson.js deleted file mode 100644 index 9540a86..0000000 --- a/node_modules/bson/browser_build/bson.js +++ /dev/null @@ -1,18218 +0,0 @@ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else { - var a = factory(); - for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; - } -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; - -/******/ // The require function -/******/ function __webpack_require__(moduleId) { - -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; - -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ exports: {}, -/******/ id: moduleId, -/******/ loaded: false -/******/ }; - -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - -/******/ // Flag the module as loaded -/******/ module.loaded = true; - -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } - - -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; - -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; - -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = "/"; - -/******/ // Load entry module and return exports -/******/ return __webpack_require__(0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(1); - module.exports = __webpack_require__(332); - - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {"use strict"; - - __webpack_require__(2); - - __webpack_require__(328); - - __webpack_require__(329); - - if (global._babelPolyfill) { - throw new Error("only one instance of babel-polyfill is allowed"); - } - global._babelPolyfill = true; - - var DEFINE_PROPERTY = "defineProperty"; - function define(O, key, value) { - O[key] || Object[DEFINE_PROPERTY](O, key, { - writable: true, - configurable: true, - value: value - }); - } - - define(String.prototype, "padLeft", "".padStart); - define(String.prototype, "padRight", "".padEnd); - - "pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) { - [][key] && define(Array, key, Function.call.bind([][key])); - }); - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(3); - __webpack_require__(53); - __webpack_require__(54); - __webpack_require__(55); - __webpack_require__(56); - __webpack_require__(58); - __webpack_require__(60); - __webpack_require__(61); - __webpack_require__(62); - __webpack_require__(63); - __webpack_require__(64); - __webpack_require__(65); - __webpack_require__(66); - __webpack_require__(67); - __webpack_require__(68); - __webpack_require__(70); - __webpack_require__(72); - __webpack_require__(74); - __webpack_require__(76); - __webpack_require__(79); - __webpack_require__(80); - __webpack_require__(81); - __webpack_require__(85); - __webpack_require__(87); - __webpack_require__(89); - __webpack_require__(92); - __webpack_require__(93); - __webpack_require__(94); - __webpack_require__(95); - __webpack_require__(97); - __webpack_require__(98); - __webpack_require__(99); - __webpack_require__(100); - __webpack_require__(101); - __webpack_require__(102); - __webpack_require__(103); - __webpack_require__(105); - __webpack_require__(106); - __webpack_require__(107); - __webpack_require__(109); - __webpack_require__(110); - __webpack_require__(111); - __webpack_require__(113); - __webpack_require__(115); - __webpack_require__(116); - __webpack_require__(117); - __webpack_require__(118); - __webpack_require__(119); - __webpack_require__(120); - __webpack_require__(121); - __webpack_require__(122); - __webpack_require__(123); - __webpack_require__(124); - __webpack_require__(125); - __webpack_require__(126); - __webpack_require__(127); - __webpack_require__(132); - __webpack_require__(133); - __webpack_require__(137); - __webpack_require__(138); - __webpack_require__(139); - __webpack_require__(140); - __webpack_require__(142); - __webpack_require__(143); - __webpack_require__(144); - __webpack_require__(145); - __webpack_require__(146); - __webpack_require__(147); - __webpack_require__(148); - __webpack_require__(149); - __webpack_require__(150); - __webpack_require__(151); - __webpack_require__(152); - __webpack_require__(153); - __webpack_require__(154); - __webpack_require__(155); - __webpack_require__(156); - __webpack_require__(158); - __webpack_require__(159); - __webpack_require__(161); - __webpack_require__(162); - __webpack_require__(168); - __webpack_require__(169); - __webpack_require__(171); - __webpack_require__(172); - __webpack_require__(173); - __webpack_require__(177); - __webpack_require__(178); - __webpack_require__(179); - __webpack_require__(180); - __webpack_require__(181); - __webpack_require__(183); - __webpack_require__(184); - __webpack_require__(185); - __webpack_require__(186); - __webpack_require__(189); - __webpack_require__(191); - __webpack_require__(192); - __webpack_require__(193); - __webpack_require__(195); - __webpack_require__(197); - __webpack_require__(199); - __webpack_require__(201); - __webpack_require__(202); - __webpack_require__(203); - __webpack_require__(207); - __webpack_require__(208); - __webpack_require__(209); - __webpack_require__(211); - __webpack_require__(221); - __webpack_require__(225); - __webpack_require__(226); - __webpack_require__(228); - __webpack_require__(229); - __webpack_require__(233); - __webpack_require__(234); - __webpack_require__(236); - __webpack_require__(237); - __webpack_require__(238); - __webpack_require__(239); - __webpack_require__(240); - __webpack_require__(241); - __webpack_require__(242); - __webpack_require__(243); - __webpack_require__(244); - __webpack_require__(245); - __webpack_require__(246); - __webpack_require__(247); - __webpack_require__(248); - __webpack_require__(249); - __webpack_require__(250); - __webpack_require__(251); - __webpack_require__(252); - __webpack_require__(253); - __webpack_require__(254); - __webpack_require__(256); - __webpack_require__(257); - __webpack_require__(258); - __webpack_require__(259); - __webpack_require__(260); - __webpack_require__(262); - __webpack_require__(263); - __webpack_require__(264); - __webpack_require__(266); - __webpack_require__(267); - __webpack_require__(268); - __webpack_require__(269); - __webpack_require__(270); - __webpack_require__(271); - __webpack_require__(272); - __webpack_require__(273); - __webpack_require__(275); - __webpack_require__(276); - __webpack_require__(278); - __webpack_require__(279); - __webpack_require__(280); - __webpack_require__(281); - __webpack_require__(284); - __webpack_require__(285); - __webpack_require__(287); - __webpack_require__(288); - __webpack_require__(289); - __webpack_require__(290); - __webpack_require__(292); - __webpack_require__(293); - __webpack_require__(294); - __webpack_require__(295); - __webpack_require__(296); - __webpack_require__(297); - __webpack_require__(298); - __webpack_require__(299); - __webpack_require__(300); - __webpack_require__(301); - __webpack_require__(303); - __webpack_require__(304); - __webpack_require__(305); - __webpack_require__(306); - __webpack_require__(307); - __webpack_require__(308); - __webpack_require__(309); - __webpack_require__(310); - __webpack_require__(311); - __webpack_require__(312); - __webpack_require__(313); - __webpack_require__(315); - __webpack_require__(316); - __webpack_require__(317); - __webpack_require__(318); - __webpack_require__(319); - __webpack_require__(320); - __webpack_require__(321); - __webpack_require__(322); - __webpack_require__(323); - __webpack_require__(324); - __webpack_require__(325); - __webpack_require__(326); - __webpack_require__(327); - module.exports = __webpack_require__(9); - - -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // ECMAScript 6 symbols shim - var global = __webpack_require__(4); - var has = __webpack_require__(5); - var DESCRIPTORS = __webpack_require__(6); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var META = __webpack_require__(25).KEY; - var $fails = __webpack_require__(7); - var shared = __webpack_require__(21); - var setToStringTag = __webpack_require__(26); - var uid = __webpack_require__(19); - var wks = __webpack_require__(27); - var wksExt = __webpack_require__(28); - var wksDefine = __webpack_require__(29); - var enumKeys = __webpack_require__(30); - var isArray = __webpack_require__(45); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var toObject = __webpack_require__(46); - var toIObject = __webpack_require__(33); - var toPrimitive = __webpack_require__(16); - var createDesc = __webpack_require__(17); - var _create = __webpack_require__(47); - var gOPNExt = __webpack_require__(50); - var $GOPD = __webpack_require__(52); - var $GOPS = __webpack_require__(43); - var $DP = __webpack_require__(11); - var $keys = __webpack_require__(31); - var gOPD = $GOPD.f; - var dP = $DP.f; - var gOPN = gOPNExt.f; - var $Symbol = global.Symbol; - var $JSON = global.JSON; - var _stringify = $JSON && $JSON.stringify; - var PROTOTYPE = 'prototype'; - var HIDDEN = wks('_hidden'); - var TO_PRIMITIVE = wks('toPrimitive'); - var isEnum = {}.propertyIsEnumerable; - var SymbolRegistry = shared('symbol-registry'); - var AllSymbols = shared('symbols'); - var OPSymbols = shared('op-symbols'); - var ObjectProto = Object[PROTOTYPE]; - var USE_NATIVE = typeof $Symbol == 'function' && !!$GOPS.f; - var QObject = global.QObject; - // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 - var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; - - // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 - var setSymbolDesc = DESCRIPTORS && $fails(function () { - return _create(dP({}, 'a', { - get: function () { return dP(this, 'a', { value: 7 }).a; } - })).a != 7; - }) ? function (it, key, D) { - var protoDesc = gOPD(ObjectProto, key); - if (protoDesc) delete ObjectProto[key]; - dP(it, key, D); - if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); - } : dP; - - var wrap = function (tag) { - var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); - sym._k = tag; - return sym; - }; - - var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { - return typeof it == 'symbol'; - } : function (it) { - return it instanceof $Symbol; - }; - - var $defineProperty = function defineProperty(it, key, D) { - if (it === ObjectProto) $defineProperty(OPSymbols, key, D); - anObject(it); - key = toPrimitive(key, true); - anObject(D); - if (has(AllSymbols, key)) { - if (!D.enumerable) { - if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); - it[HIDDEN][key] = true; - } else { - if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; - D = _create(D, { enumerable: createDesc(0, false) }); - } return setSymbolDesc(it, key, D); - } return dP(it, key, D); - }; - var $defineProperties = function defineProperties(it, P) { - anObject(it); - var keys = enumKeys(P = toIObject(P)); - var i = 0; - var l = keys.length; - var key; - while (l > i) $defineProperty(it, key = keys[i++], P[key]); - return it; - }; - var $create = function create(it, P) { - return P === undefined ? _create(it) : $defineProperties(_create(it), P); - }; - var $propertyIsEnumerable = function propertyIsEnumerable(key) { - var E = isEnum.call(this, key = toPrimitive(key, true)); - if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; - return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; - }; - var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { - it = toIObject(it); - key = toPrimitive(key, true); - if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; - var D = gOPD(it, key); - if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; - return D; - }; - var $getOwnPropertyNames = function getOwnPropertyNames(it) { - var names = gOPN(toIObject(it)); - var result = []; - var i = 0; - var key; - while (names.length > i) { - if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); - } return result; - }; - var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { - var IS_OP = it === ObjectProto; - var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); - var result = []; - var i = 0; - var key; - while (names.length > i) { - if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); - } return result; - }; - - // 19.4.1.1 Symbol([description]) - if (!USE_NATIVE) { - $Symbol = function Symbol() { - if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); - var tag = uid(arguments.length > 0 ? arguments[0] : undefined); - var $set = function (value) { - if (this === ObjectProto) $set.call(OPSymbols, value); - if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; - setSymbolDesc(this, tag, createDesc(1, value)); - }; - if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); - return wrap(tag); - }; - redefine($Symbol[PROTOTYPE], 'toString', function toString() { - return this._k; - }); - - $GOPD.f = $getOwnPropertyDescriptor; - $DP.f = $defineProperty; - __webpack_require__(51).f = gOPNExt.f = $getOwnPropertyNames; - __webpack_require__(44).f = $propertyIsEnumerable; - $GOPS.f = $getOwnPropertySymbols; - - if (DESCRIPTORS && !__webpack_require__(22)) { - redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); - } - - wksExt.f = function (name) { - return wrap(wks(name)); - }; - } - - $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); - - for (var es6Symbols = ( - // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 - 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' - ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); - - for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); - - $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { - // 19.4.2.1 Symbol.for(key) - 'for': function (key) { - return has(SymbolRegistry, key += '') - ? SymbolRegistry[key] - : SymbolRegistry[key] = $Symbol(key); - }, - // 19.4.2.5 Symbol.keyFor(sym) - keyFor: function keyFor(sym) { - if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); - for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; - }, - useSetter: function () { setter = true; }, - useSimple: function () { setter = false; } - }); - - $export($export.S + $export.F * !USE_NATIVE, 'Object', { - // 19.1.2.2 Object.create(O [, Properties]) - create: $create, - // 19.1.2.4 Object.defineProperty(O, P, Attributes) - defineProperty: $defineProperty, - // 19.1.2.3 Object.defineProperties(O, Properties) - defineProperties: $defineProperties, - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - getOwnPropertyDescriptor: $getOwnPropertyDescriptor, - // 19.1.2.7 Object.getOwnPropertyNames(O) - getOwnPropertyNames: $getOwnPropertyNames, - // 19.1.2.8 Object.getOwnPropertySymbols(O) - getOwnPropertySymbols: $getOwnPropertySymbols - }); - - // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives - // https://bugs.chromium.org/p/v8/issues/detail?id=3443 - var FAILS_ON_PRIMITIVES = $fails(function () { $GOPS.f(1); }); - - $export($export.S + $export.F * FAILS_ON_PRIMITIVES, 'Object', { - getOwnPropertySymbols: function getOwnPropertySymbols(it) { - return $GOPS.f(toObject(it)); - } - }); - - // 24.3.2 JSON.stringify(value [, replacer [, space]]) - $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { - var S = $Symbol(); - // MS Edge converts symbol values to JSON as {} - // WebKit converts symbol values to JSON as null - // V8 throws on boxed symbols - return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; - })), 'JSON', { - stringify: function stringify(it) { - var args = [it]; - var i = 1; - var replacer, $replacer; - while (arguments.length > i) args.push(arguments[i++]); - $replacer = replacer = args[1]; - if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined - if (!isArray(replacer)) replacer = function (key, value) { - if (typeof $replacer == 'function') value = $replacer.call(this, key, value); - if (!isSymbol(value)) return value; - }; - args[1] = replacer; - return _stringify.apply($JSON, args); - } - }); - - // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) - $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(10)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); - // 19.4.3.5 Symbol.prototype[@@toStringTag] - setToStringTag($Symbol, 'Symbol'); - // 20.2.1.9 Math[@@toStringTag] - setToStringTag(Math, 'Math', true); - // 24.3.3 JSON[@@toStringTag] - setToStringTag(global.JSON, 'JSON', true); - - -/***/ }), -/* 4 */ -/***/ (function(module, exports) { - - // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self - // eslint-disable-next-line no-new-func - : Function('return this')(); - if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef - - -/***/ }), -/* 5 */ -/***/ (function(module, exports) { - - var hasOwnProperty = {}.hasOwnProperty; - module.exports = function (it, key) { - return hasOwnProperty.call(it, key); - }; - - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - - // Thank's IE8 for his funny defineProperty - module.exports = !__webpack_require__(7)(function () { - return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; - }); - - -/***/ }), -/* 7 */ -/***/ (function(module, exports) { - - module.exports = function (exec) { - try { - return !!exec(); - } catch (e) { - return true; - } - }; - - -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var hide = __webpack_require__(10); - var redefine = __webpack_require__(18); - var ctx = __webpack_require__(23); - var PROTOTYPE = 'prototype'; - - var $export = function (type, name, source) { - var IS_FORCED = type & $export.F; - var IS_GLOBAL = type & $export.G; - var IS_STATIC = type & $export.S; - var IS_PROTO = type & $export.P; - var IS_BIND = type & $export.B; - var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]; - var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); - var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); - var key, own, out, exp; - if (IS_GLOBAL) source = name; - for (key in source) { - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - // export native or passed - out = (own ? target : source)[key]; - // bind timers to global for call from export context - exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // extend global - if (target) redefine(target, key, out, type & $export.U); - // export - if (exports[key] != out) hide(exports, key, exp); - if (IS_PROTO && expProto[key] != out) expProto[key] = out; - } - }; - global.core = core; - // type bitmap - $export.F = 1; // forced - $export.G = 2; // global - $export.S = 4; // static - $export.P = 8; // proto - $export.B = 16; // bind - $export.W = 32; // wrap - $export.U = 64; // safe - $export.R = 128; // real proto method for `library` - module.exports = $export; - - -/***/ }), -/* 9 */ -/***/ (function(module, exports) { - - var core = module.exports = { version: '2.6.10' }; - if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11); - var createDesc = __webpack_require__(17); - module.exports = __webpack_require__(6) ? function (object, key, value) { - return dP.f(object, key, createDesc(1, value)); - } : function (object, key, value) { - object[key] = value; - return object; - }; - - -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(12); - var IE8_DOM_DEFINE = __webpack_require__(14); - var toPrimitive = __webpack_require__(16); - var dP = Object.defineProperty; - - exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes) { - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if (IE8_DOM_DEFINE) try { - return dP(O, P, Attributes); - } catch (e) { /* empty */ } - if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); - if ('value' in Attributes) O[P] = Attributes.value; - return O; - }; - - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - module.exports = function (it) { - if (!isObject(it)) throw TypeError(it + ' is not an object!'); - return it; - }; - - -/***/ }), -/* 13 */ -/***/ (function(module, exports) { - - module.exports = function (it) { - return typeof it === 'object' ? it !== null : typeof it === 'function'; - }; - - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - - module.exports = !__webpack_require__(6) && !__webpack_require__(7)(function () { - return Object.defineProperty(__webpack_require__(15)('div'), 'a', { get: function () { return 7; } }).a != 7; - }); - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var document = __webpack_require__(4).document; - // typeof document.createElement is 'object' in old IE - var is = isObject(document) && isObject(document.createElement); - module.exports = function (it) { - return is ? document.createElement(it) : {}; - }; - - -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.1 ToPrimitive(input [, PreferredType]) - var isObject = __webpack_require__(13); - // instead of the ES6 spec version, we didn't implement @@toPrimitive case - // and the second argument - flag - preferred type is a string - module.exports = function (it, S) { - if (!isObject(it)) return it; - var fn, val; - if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; - if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - throw TypeError("Can't convert object to primitive value"); - }; - - -/***/ }), -/* 17 */ -/***/ (function(module, exports) { - - module.exports = function (bitmap, value) { - return { - enumerable: !(bitmap & 1), - configurable: !(bitmap & 2), - writable: !(bitmap & 4), - value: value - }; - }; - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var has = __webpack_require__(5); - var SRC = __webpack_require__(19)('src'); - var $toString = __webpack_require__(20); - var TO_STRING = 'toString'; - var TPL = ('' + $toString).split(TO_STRING); - - __webpack_require__(9).inspectSource = function (it) { - return $toString.call(it); - }; - - (module.exports = function (O, key, val, safe) { - var isFunction = typeof val == 'function'; - if (isFunction) has(val, 'name') || hide(val, 'name', key); - if (O[key] === val) return; - if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); - if (O === global) { - O[key] = val; - } else if (!safe) { - delete O[key]; - hide(O, key, val); - } else if (O[key]) { - O[key] = val; - } else { - hide(O, key, val); - } - // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative - })(Function.prototype, TO_STRING, function toString() { - return typeof this == 'function' && this[SRC] || $toString.call(this); - }); - - -/***/ }), -/* 19 */ -/***/ (function(module, exports) { - - var id = 0; - var px = Math.random(); - module.exports = function (key) { - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); - }; - - -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { - - module.exports = __webpack_require__(21)('native-function-to-string', Function.toString); - - -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { - - var core = __webpack_require__(9); - var global = __webpack_require__(4); - var SHARED = '__core-js_shared__'; - var store = global[SHARED] || (global[SHARED] = {}); - - (module.exports = function (key, value) { - return store[key] || (store[key] = value !== undefined ? value : {}); - })('versions', []).push({ - version: core.version, - mode: __webpack_require__(22) ? 'pure' : 'global', - copyright: '© 2019 Denis Pushkarev (zloirock.ru)' - }); - - -/***/ }), -/* 22 */ -/***/ (function(module, exports) { - - module.exports = false; - - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - - // optional / simple context binding - var aFunction = __webpack_require__(24); - module.exports = function (fn, that, length) { - aFunction(fn); - if (that === undefined) return fn; - switch (length) { - case 1: return function (a) { - return fn.call(that, a); - }; - case 2: return function (a, b) { - return fn.call(that, a, b); - }; - case 3: return function (a, b, c) { - return fn.call(that, a, b, c); - }; - } - return function (/* ...args */) { - return fn.apply(that, arguments); - }; - }; - - -/***/ }), -/* 24 */ -/***/ (function(module, exports) { - - module.exports = function (it) { - if (typeof it != 'function') throw TypeError(it + ' is not a function!'); - return it; - }; - - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - - var META = __webpack_require__(19)('meta'); - var isObject = __webpack_require__(13); - var has = __webpack_require__(5); - var setDesc = __webpack_require__(11).f; - var id = 0; - var isExtensible = Object.isExtensible || function () { - return true; - }; - var FREEZE = !__webpack_require__(7)(function () { - return isExtensible(Object.preventExtensions({})); - }); - var setMeta = function (it) { - setDesc(it, META, { value: { - i: 'O' + ++id, // object ID - w: {} // weak collections IDs - } }); - }; - var fastKey = function (it, create) { - // return primitive with prefix - if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; - if (!has(it, META)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return 'F'; - // not necessary to add metadata - if (!create) return 'E'; - // add missing metadata - setMeta(it); - // return object ID - } return it[META].i; - }; - var getWeak = function (it, create) { - if (!has(it, META)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return true; - // not necessary to add metadata - if (!create) return false; - // add missing metadata - setMeta(it); - // return hash weak collections IDs - } return it[META].w; - }; - // add metadata on freeze-family methods calling - var onFreeze = function (it) { - if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); - return it; - }; - var meta = module.exports = { - KEY: META, - NEED: false, - fastKey: fastKey, - getWeak: getWeak, - onFreeze: onFreeze - }; - - -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { - - var def = __webpack_require__(11).f; - var has = __webpack_require__(5); - var TAG = __webpack_require__(27)('toStringTag'); - - module.exports = function (it, tag, stat) { - if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); - }; - - -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { - - var store = __webpack_require__(21)('wks'); - var uid = __webpack_require__(19); - var Symbol = __webpack_require__(4).Symbol; - var USE_SYMBOL = typeof Symbol == 'function'; - - var $exports = module.exports = function (name) { - return store[name] || (store[name] = - USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); - }; - - $exports.store = store; - - -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { - - exports.f = __webpack_require__(27); - - -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var LIBRARY = __webpack_require__(22); - var wksExt = __webpack_require__(28); - var defineProperty = __webpack_require__(11).f; - module.exports = function (name) { - var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); - if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); - }; - - -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { - - // all enumerable object keys, includes symbols - var getKeys = __webpack_require__(31); - var gOPS = __webpack_require__(43); - var pIE = __webpack_require__(44); - module.exports = function (it) { - var result = getKeys(it); - var getSymbols = gOPS.f; - if (getSymbols) { - var symbols = getSymbols(it); - var isEnum = pIE.f; - var i = 0; - var key; - while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); - } return result; - }; - - -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.14 / 15.2.3.14 Object.keys(O) - var $keys = __webpack_require__(32); - var enumBugKeys = __webpack_require__(42); - - module.exports = Object.keys || function keys(O) { - return $keys(O, enumBugKeys); - }; - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - - var has = __webpack_require__(5); - var toIObject = __webpack_require__(33); - var arrayIndexOf = __webpack_require__(37)(false); - var IE_PROTO = __webpack_require__(41)('IE_PROTO'); - - module.exports = function (object, names) { - var O = toIObject(object); - var i = 0; - var result = []; - var key; - for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); - // Don't enum bug & hidden keys - while (names.length > i) if (has(O, key = names[i++])) { - ~arrayIndexOf(result, key) || result.push(key); - } - return result; - }; - - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - - // to indexed object, toObject with fallback for non-array-like ES3 strings - var IObject = __webpack_require__(34); - var defined = __webpack_require__(36); - module.exports = function (it) { - return IObject(defined(it)); - }; - - -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { - - // fallback for non-array-like ES3 and non-enumerable old V8 strings - var cof = __webpack_require__(35); - // eslint-disable-next-line no-prototype-builtins - module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { - return cof(it) == 'String' ? it.split('') : Object(it); - }; - - -/***/ }), -/* 35 */ -/***/ (function(module, exports) { - - var toString = {}.toString; - - module.exports = function (it) { - return toString.call(it).slice(8, -1); - }; - - -/***/ }), -/* 36 */ -/***/ (function(module, exports) { - - // 7.2.1 RequireObjectCoercible(argument) - module.exports = function (it) { - if (it == undefined) throw TypeError("Can't call method on " + it); - return it; - }; - - -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { - - // false -> Array#indexOf - // true -> Array#includes - var toIObject = __webpack_require__(33); - var toLength = __webpack_require__(38); - var toAbsoluteIndex = __webpack_require__(40); - module.exports = function (IS_INCLUDES) { - return function ($this, el, fromIndex) { - var O = toIObject($this); - var length = toLength(O.length); - var index = toAbsoluteIndex(fromIndex, length); - var value; - // Array#includes uses SameValueZero equality algorithm - // eslint-disable-next-line no-self-compare - if (IS_INCLUDES && el != el) while (length > index) { - value = O[index++]; - // eslint-disable-next-line no-self-compare - if (value != value) return true; - // Array#indexOf ignores holes, Array#includes - not - } else for (;length > index; index++) if (IS_INCLUDES || index in O) { - if (O[index] === el) return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; - }; - }; - - -/***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.15 ToLength - var toInteger = __webpack_require__(39); - var min = Math.min; - module.exports = function (it) { - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 - }; - - -/***/ }), -/* 39 */ -/***/ (function(module, exports) { - - // 7.1.4 ToInteger - var ceil = Math.ceil; - var floor = Math.floor; - module.exports = function (it) { - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); - }; - - -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { - - var toInteger = __webpack_require__(39); - var max = Math.max; - var min = Math.min; - module.exports = function (index, length) { - index = toInteger(index); - return index < 0 ? max(index + length, 0) : min(index, length); - }; - - -/***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { - - var shared = __webpack_require__(21)('keys'); - var uid = __webpack_require__(19); - module.exports = function (key) { - return shared[key] || (shared[key] = uid(key)); - }; - - -/***/ }), -/* 42 */ -/***/ (function(module, exports) { - - // IE 8- don't enum bug keys - module.exports = ( - 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' - ).split(','); - - -/***/ }), -/* 43 */ -/***/ (function(module, exports) { - - exports.f = Object.getOwnPropertySymbols; - - -/***/ }), -/* 44 */ -/***/ (function(module, exports) { - - exports.f = {}.propertyIsEnumerable; - - -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.2.2 IsArray(argument) - var cof = __webpack_require__(35); - module.exports = Array.isArray || function isArray(arg) { - return cof(arg) == 'Array'; - }; - - -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.13 ToObject(argument) - var defined = __webpack_require__(36); - module.exports = function (it) { - return Object(defined(it)); - }; - - -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) - var anObject = __webpack_require__(12); - var dPs = __webpack_require__(48); - var enumBugKeys = __webpack_require__(42); - var IE_PROTO = __webpack_require__(41)('IE_PROTO'); - var Empty = function () { /* empty */ }; - var PROTOTYPE = 'prototype'; - - // Create object with fake `null` prototype: use iframe Object with cleared prototype - var createDict = function () { - // Thrash, waste and sodomy: IE GC bug - var iframe = __webpack_require__(15)('iframe'); - var i = enumBugKeys.length; - var lt = '<'; - var gt = '>'; - var iframeDocument; - iframe.style.display = 'none'; - __webpack_require__(49).appendChild(iframe); - iframe.src = 'javascript:'; // eslint-disable-line no-script-url - // createDict = iframe.contentWindow.Object; - // html.removeChild(iframe); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); - iframeDocument.close(); - createDict = iframeDocument.F; - while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; - return createDict(); - }; - - module.exports = Object.create || function create(O, Properties) { - var result; - if (O !== null) { - Empty[PROTOTYPE] = anObject(O); - result = new Empty(); - Empty[PROTOTYPE] = null; - // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO] = O; - } else result = createDict(); - return Properties === undefined ? result : dPs(result, Properties); - }; - - -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11); - var anObject = __webpack_require__(12); - var getKeys = __webpack_require__(31); - - module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties) { - anObject(O); - var keys = getKeys(Properties); - var length = keys.length; - var i = 0; - var P; - while (length > i) dP.f(O, P = keys[i++], Properties[P]); - return O; - }; - - -/***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { - - var document = __webpack_require__(4).document; - module.exports = document && document.documentElement; - - -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { - - // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window - var toIObject = __webpack_require__(33); - var gOPN = __webpack_require__(51).f; - var toString = {}.toString; - - var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames - ? Object.getOwnPropertyNames(window) : []; - - var getWindowNames = function (it) { - try { - return gOPN(it); - } catch (e) { - return windowNames.slice(); - } - }; - - module.exports.f = function getOwnPropertyNames(it) { - return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); - }; - - -/***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) - var $keys = __webpack_require__(32); - var hiddenKeys = __webpack_require__(42).concat('length', 'prototype'); - - exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { - return $keys(O, hiddenKeys); - }; - - -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { - - var pIE = __webpack_require__(44); - var createDesc = __webpack_require__(17); - var toIObject = __webpack_require__(33); - var toPrimitive = __webpack_require__(16); - var has = __webpack_require__(5); - var IE8_DOM_DEFINE = __webpack_require__(14); - var gOPD = Object.getOwnPropertyDescriptor; - - exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P) { - O = toIObject(O); - P = toPrimitive(P, true); - if (IE8_DOM_DEFINE) try { - return gOPD(O, P); - } catch (e) { /* empty */ } - if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); - }; - - -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) - $export($export.S, 'Object', { create: __webpack_require__(47) }); - - -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) - $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperty: __webpack_require__(11).f }); - - -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) - $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperties: __webpack_require__(48) }); - - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - var toIObject = __webpack_require__(33); - var $getOwnPropertyDescriptor = __webpack_require__(52).f; - - __webpack_require__(57)('getOwnPropertyDescriptor', function () { - return function getOwnPropertyDescriptor(it, key) { - return $getOwnPropertyDescriptor(toIObject(it), key); - }; - }); - - -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { - - // most Object methods by ES6 should accept primitives - var $export = __webpack_require__(8); - var core = __webpack_require__(9); - var fails = __webpack_require__(7); - module.exports = function (KEY, exec) { - var fn = (core.Object || {})[KEY] || Object[KEY]; - var exp = {}; - exp[KEY] = exec(fn); - $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); - }; - - -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.9 Object.getPrototypeOf(O) - var toObject = __webpack_require__(46); - var $getPrototypeOf = __webpack_require__(59); - - __webpack_require__(57)('getPrototypeOf', function () { - return function getPrototypeOf(it) { - return $getPrototypeOf(toObject(it)); - }; - }); - - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) - var has = __webpack_require__(5); - var toObject = __webpack_require__(46); - var IE_PROTO = __webpack_require__(41)('IE_PROTO'); - var ObjectProto = Object.prototype; - - module.exports = Object.getPrototypeOf || function (O) { - O = toObject(O); - if (has(O, IE_PROTO)) return O[IE_PROTO]; - if (typeof O.constructor == 'function' && O instanceof O.constructor) { - return O.constructor.prototype; - } return O instanceof Object ? ObjectProto : null; - }; - - -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.14 Object.keys(O) - var toObject = __webpack_require__(46); - var $keys = __webpack_require__(31); - - __webpack_require__(57)('keys', function () { - return function keys(it) { - return $keys(toObject(it)); - }; - }); - - -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.7 Object.getOwnPropertyNames(O) - __webpack_require__(57)('getOwnPropertyNames', function () { - return __webpack_require__(50).f; - }); - - -/***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.5 Object.freeze(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(25).onFreeze; - - __webpack_require__(57)('freeze', function ($freeze) { - return function freeze(it) { - return $freeze && isObject(it) ? $freeze(meta(it)) : it; - }; - }); - - -/***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.17 Object.seal(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(25).onFreeze; - - __webpack_require__(57)('seal', function ($seal) { - return function seal(it) { - return $seal && isObject(it) ? $seal(meta(it)) : it; - }; - }); - - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.15 Object.preventExtensions(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(25).onFreeze; - - __webpack_require__(57)('preventExtensions', function ($preventExtensions) { - return function preventExtensions(it) { - return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; - }; - }); - - -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.12 Object.isFrozen(O) - var isObject = __webpack_require__(13); - - __webpack_require__(57)('isFrozen', function ($isFrozen) { - return function isFrozen(it) { - return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; - }; - }); - - -/***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.13 Object.isSealed(O) - var isObject = __webpack_require__(13); - - __webpack_require__(57)('isSealed', function ($isSealed) { - return function isSealed(it) { - return isObject(it) ? $isSealed ? $isSealed(it) : false : true; - }; - }); - - -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.11 Object.isExtensible(O) - var isObject = __webpack_require__(13); - - __webpack_require__(57)('isExtensible', function ($isExtensible) { - return function isExtensible(it) { - return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; - }; - }); - - -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.1 Object.assign(target, source) - var $export = __webpack_require__(8); - - $export($export.S + $export.F, 'Object', { assign: __webpack_require__(69) }); - - -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 19.1.2.1 Object.assign(target, source, ...) - var DESCRIPTORS = __webpack_require__(6); - var getKeys = __webpack_require__(31); - var gOPS = __webpack_require__(43); - var pIE = __webpack_require__(44); - var toObject = __webpack_require__(46); - var IObject = __webpack_require__(34); - var $assign = Object.assign; - - // should work with symbols and should have deterministic property order (V8 bug) - module.exports = !$assign || __webpack_require__(7)(function () { - var A = {}; - var B = {}; - // eslint-disable-next-line no-undef - var S = Symbol(); - var K = 'abcdefghijklmnopqrst'; - A[S] = 7; - K.split('').forEach(function (k) { B[k] = k; }); - return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; - }) ? function assign(target, source) { // eslint-disable-line no-unused-vars - var T = toObject(target); - var aLen = arguments.length; - var index = 1; - var getSymbols = gOPS.f; - var isEnum = pIE.f; - while (aLen > index) { - var S = IObject(arguments[index++]); - var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); - var length = keys.length; - var j = 0; - var key; - while (length > j) { - key = keys[j++]; - if (!DESCRIPTORS || isEnum.call(S, key)) T[key] = S[key]; - } - } return T; - } : $assign; - - -/***/ }), -/* 70 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.10 Object.is(value1, value2) - var $export = __webpack_require__(8); - $export($export.S, 'Object', { is: __webpack_require__(71) }); - - -/***/ }), -/* 71 */ -/***/ (function(module, exports) { - - // 7.2.9 SameValue(x, y) - module.exports = Object.is || function is(x, y) { - // eslint-disable-next-line no-self-compare - return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; - }; - - -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.19 Object.setPrototypeOf(O, proto) - var $export = __webpack_require__(8); - $export($export.S, 'Object', { setPrototypeOf: __webpack_require__(73).set }); - - -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - - // Works with __proto__ only. Old v8 can't work with null proto objects. - /* eslint-disable no-proto */ - var isObject = __webpack_require__(13); - var anObject = __webpack_require__(12); - var check = function (O, proto) { - anObject(O); - if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); - }; - module.exports = { - set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line - function (test, buggy, set) { - try { - set = __webpack_require__(23)(Function.call, __webpack_require__(52).f(Object.prototype, '__proto__').set, 2); - set(test, []); - buggy = !(test instanceof Array); - } catch (e) { buggy = true; } - return function setPrototypeOf(O, proto) { - check(O, proto); - if (buggy) O.__proto__ = proto; - else set(O, proto); - return O; - }; - }({}, false) : undefined), - check: check - }; - - -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 19.1.3.6 Object.prototype.toString() - var classof = __webpack_require__(75); - var test = {}; - test[__webpack_require__(27)('toStringTag')] = 'z'; - if (test + '' != '[object z]') { - __webpack_require__(18)(Object.prototype, 'toString', function toString() { - return '[object ' + classof(this) + ']'; - }, true); - } - - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - - // getting tag from 19.1.3.6 Object.prototype.toString() - var cof = __webpack_require__(35); - var TAG = __webpack_require__(27)('toStringTag'); - // ES3 wrong here - var ARG = cof(function () { return arguments; }()) == 'Arguments'; - - // fallback for IE11 Script Access Denied error - var tryGet = function (it, key) { - try { - return it[key]; - } catch (e) { /* empty */ } - }; - - module.exports = function (it) { - var O, T, B; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T - // builtinTag case - : ARG ? cof(O) - // ES3 arguments fallback - : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; - }; - - -/***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) - var $export = __webpack_require__(8); - - $export($export.P, 'Function', { bind: __webpack_require__(77) }); - - -/***/ }), -/* 77 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var aFunction = __webpack_require__(24); - var isObject = __webpack_require__(13); - var invoke = __webpack_require__(78); - var arraySlice = [].slice; - var factories = {}; - - var construct = function (F, len, args) { - if (!(len in factories)) { - for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']'; - // eslint-disable-next-line no-new-func - factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); - } return factories[len](F, args); - }; - - module.exports = Function.bind || function bind(that /* , ...args */) { - var fn = aFunction(this); - var partArgs = arraySlice.call(arguments, 1); - var bound = function (/* args... */) { - var args = partArgs.concat(arraySlice.call(arguments)); - return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); - }; - if (isObject(fn.prototype)) bound.prototype = fn.prototype; - return bound; - }; - - -/***/ }), -/* 78 */ -/***/ (function(module, exports) { - - // fast apply, http://jsperf.lnkit.com/fast-apply/5 - module.exports = function (fn, args, that) { - var un = that === undefined; - switch (args.length) { - case 0: return un ? fn() - : fn.call(that); - case 1: return un ? fn(args[0]) - : fn.call(that, args[0]); - case 2: return un ? fn(args[0], args[1]) - : fn.call(that, args[0], args[1]); - case 3: return un ? fn(args[0], args[1], args[2]) - : fn.call(that, args[0], args[1], args[2]); - case 4: return un ? fn(args[0], args[1], args[2], args[3]) - : fn.call(that, args[0], args[1], args[2], args[3]); - } return fn.apply(that, args); - }; - - -/***/ }), -/* 79 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11).f; - var FProto = Function.prototype; - var nameRE = /^\s*function ([^ (]*)/; - var NAME = 'name'; - - // 19.2.4.2 name - NAME in FProto || __webpack_require__(6) && dP(FProto, NAME, { - configurable: true, - get: function () { - try { - return ('' + this).match(nameRE)[1]; - } catch (e) { - return ''; - } - } - }); - - -/***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var isObject = __webpack_require__(13); - var getPrototypeOf = __webpack_require__(59); - var HAS_INSTANCE = __webpack_require__(27)('hasInstance'); - var FunctionProto = Function.prototype; - // 19.2.3.6 Function.prototype[@@hasInstance](V) - if (!(HAS_INSTANCE in FunctionProto)) __webpack_require__(11).f(FunctionProto, HAS_INSTANCE, { value: function (O) { - if (typeof this != 'function' || !isObject(O)) return false; - if (!isObject(this.prototype)) return O instanceof this; - // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: - while (O = getPrototypeOf(O)) if (this.prototype === O) return true; - return false; - } }); - - -/***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseInt = __webpack_require__(82); - // 18.2.5 parseInt(string, radix) - $export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt }); - - -/***/ }), -/* 82 */ -/***/ (function(module, exports, __webpack_require__) { - - var $parseInt = __webpack_require__(4).parseInt; - var $trim = __webpack_require__(83).trim; - var ws = __webpack_require__(84); - var hex = /^[-+]?0[xX]/; - - module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix) { - var string = $trim(String(str), 3); - return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); - } : $parseInt; - - -/***/ }), -/* 83 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var defined = __webpack_require__(36); - var fails = __webpack_require__(7); - var spaces = __webpack_require__(84); - var space = '[' + spaces + ']'; - var non = '\u200b\u0085'; - var ltrim = RegExp('^' + space + space + '*'); - var rtrim = RegExp(space + space + '*$'); - - var exporter = function (KEY, exec, ALIAS) { - var exp = {}; - var FORCE = fails(function () { - return !!spaces[KEY]() || non[KEY]() != non; - }); - var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; - if (ALIAS) exp[ALIAS] = fn; - $export($export.P + $export.F * FORCE, 'String', exp); - }; - - // 1 -> String#trimLeft - // 2 -> String#trimRight - // 3 -> String#trim - var trim = exporter.trim = function (string, TYPE) { - string = String(defined(string)); - if (TYPE & 1) string = string.replace(ltrim, ''); - if (TYPE & 2) string = string.replace(rtrim, ''); - return string; - }; - - module.exports = exporter; - - -/***/ }), -/* 84 */ -/***/ (function(module, exports) { - - module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; - - -/***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseFloat = __webpack_require__(86); - // 18.2.4 parseFloat(string) - $export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat }); - - -/***/ }), -/* 86 */ -/***/ (function(module, exports, __webpack_require__) { - - var $parseFloat = __webpack_require__(4).parseFloat; - var $trim = __webpack_require__(83).trim; - - module.exports = 1 / $parseFloat(__webpack_require__(84) + '-0') !== -Infinity ? function parseFloat(str) { - var string = $trim(String(str), 3); - var result = $parseFloat(string); - return result === 0 && string.charAt(0) == '-' ? -0 : result; - } : $parseFloat; - - -/***/ }), -/* 87 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var has = __webpack_require__(5); - var cof = __webpack_require__(35); - var inheritIfRequired = __webpack_require__(88); - var toPrimitive = __webpack_require__(16); - var fails = __webpack_require__(7); - var gOPN = __webpack_require__(51).f; - var gOPD = __webpack_require__(52).f; - var dP = __webpack_require__(11).f; - var $trim = __webpack_require__(83).trim; - var NUMBER = 'Number'; - var $Number = global[NUMBER]; - var Base = $Number; - var proto = $Number.prototype; - // Opera ~12 has broken Object#toString - var BROKEN_COF = cof(__webpack_require__(47)(proto)) == NUMBER; - var TRIM = 'trim' in String.prototype; - - // 7.1.3 ToNumber(argument) - var toNumber = function (argument) { - var it = toPrimitive(argument, false); - if (typeof it == 'string' && it.length > 2) { - it = TRIM ? it.trim() : $trim(it, 3); - var first = it.charCodeAt(0); - var third, radix, maxCode; - if (first === 43 || first === 45) { - third = it.charCodeAt(2); - if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix - } else if (first === 48) { - switch (it.charCodeAt(1)) { - case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i - case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i - default: return +it; - } - for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) { - code = digits.charCodeAt(i); - // parseInt parses a string to a first unavailable symbol - // but ToNumber should return NaN if a string contains unavailable symbols - if (code < 48 || code > maxCode) return NaN; - } return parseInt(digits, radix); - } - } return +it; - }; - - if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) { - $Number = function Number(value) { - var it = arguments.length < 1 ? 0 : value; - var that = this; - return that instanceof $Number - // check on 1..constructor(foo) case - && (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER) - ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); - }; - for (var keys = __webpack_require__(6) ? gOPN(Base) : ( - // ES3: - 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + - // ES6 (in case, if modules with ES6 Number statics required before): - 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + - 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' - ).split(','), j = 0, key; keys.length > j; j++) { - if (has(Base, key = keys[j]) && !has($Number, key)) { - dP($Number, key, gOPD(Base, key)); - } - } - $Number.prototype = proto; - proto.constructor = $Number; - __webpack_require__(18)(global, NUMBER, $Number); - } - - -/***/ }), -/* 88 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var setPrototypeOf = __webpack_require__(73).set; - module.exports = function (that, target, C) { - var S = target.constructor; - var P; - if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) { - setPrototypeOf(that, P); - } return that; - }; - - -/***/ }), -/* 89 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toInteger = __webpack_require__(39); - var aNumberValue = __webpack_require__(90); - var repeat = __webpack_require__(91); - var $toFixed = 1.0.toFixed; - var floor = Math.floor; - var data = [0, 0, 0, 0, 0, 0]; - var ERROR = 'Number.toFixed: incorrect invocation!'; - var ZERO = '0'; - - var multiply = function (n, c) { - var i = -1; - var c2 = c; - while (++i < 6) { - c2 += n * data[i]; - data[i] = c2 % 1e7; - c2 = floor(c2 / 1e7); - } - }; - var divide = function (n) { - var i = 6; - var c = 0; - while (--i >= 0) { - c += data[i]; - data[i] = floor(c / n); - c = (c % n) * 1e7; - } - }; - var numToString = function () { - var i = 6; - var s = ''; - while (--i >= 0) { - if (s !== '' || i === 0 || data[i] !== 0) { - var t = String(data[i]); - s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; - } - } return s; - }; - var pow = function (x, n, acc) { - return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); - }; - var log = function (x) { - var n = 0; - var x2 = x; - while (x2 >= 4096) { - n += 12; - x2 /= 4096; - } - while (x2 >= 2) { - n += 1; - x2 /= 2; - } return n; - }; - - $export($export.P + $export.F * (!!$toFixed && ( - 0.00008.toFixed(3) !== '0.000' || - 0.9.toFixed(0) !== '1' || - 1.255.toFixed(2) !== '1.25' || - 1000000000000000128.0.toFixed(0) !== '1000000000000000128' - ) || !__webpack_require__(7)(function () { - // V8 ~ Android 4.3- - $toFixed.call({}); - })), 'Number', { - toFixed: function toFixed(fractionDigits) { - var x = aNumberValue(this, ERROR); - var f = toInteger(fractionDigits); - var s = ''; - var m = ZERO; - var e, z, j, k; - if (f < 0 || f > 20) throw RangeError(ERROR); - // eslint-disable-next-line no-self-compare - if (x != x) return 'NaN'; - if (x <= -1e21 || x >= 1e21) return String(x); - if (x < 0) { - s = '-'; - x = -x; - } - if (x > 1e-21) { - e = log(x * pow(2, 69, 1)) - 69; - z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); - z *= 0x10000000000000; - e = 52 - e; - if (e > 0) { - multiply(0, z); - j = f; - while (j >= 7) { - multiply(1e7, 0); - j -= 7; - } - multiply(pow(10, j, 1), 0); - j = e - 1; - while (j >= 23) { - divide(1 << 23); - j -= 23; - } - divide(1 << j); - multiply(1, 1); - divide(2); - m = numToString(); - } else { - multiply(0, z); - multiply(1 << -e, 0); - m = numToString() + repeat.call(ZERO, f); - } - } - if (f > 0) { - k = m.length; - m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); - } else { - m = s + m; - } return m; - } - }); - - -/***/ }), -/* 90 */ -/***/ (function(module, exports, __webpack_require__) { - - var cof = __webpack_require__(35); - module.exports = function (it, msg) { - if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg); - return +it; - }; - - -/***/ }), -/* 91 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var toInteger = __webpack_require__(39); - var defined = __webpack_require__(36); - - module.exports = function repeat(count) { - var str = String(defined(this)); - var res = ''; - var n = toInteger(count); - if (n < 0 || n == Infinity) throw RangeError("Count can't be negative"); - for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str; - return res; - }; - - -/***/ }), -/* 92 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $fails = __webpack_require__(7); - var aNumberValue = __webpack_require__(90); - var $toPrecision = 1.0.toPrecision; - - $export($export.P + $export.F * ($fails(function () { - // IE7- - return $toPrecision.call(1, undefined) !== '1'; - }) || !$fails(function () { - // V8 ~ Android 4.3- - $toPrecision.call({}); - })), 'Number', { - toPrecision: function toPrecision(precision) { - var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); - return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); - } - }); - - -/***/ }), -/* 93 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.1 Number.EPSILON - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { EPSILON: Math.pow(2, -52) }); - - -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.2 Number.isFinite(number) - var $export = __webpack_require__(8); - var _isFinite = __webpack_require__(4).isFinite; - - $export($export.S, 'Number', { - isFinite: function isFinite(it) { - return typeof it == 'number' && _isFinite(it); - } - }); - - -/***/ }), -/* 95 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.3 Number.isInteger(number) - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { isInteger: __webpack_require__(96) }); - - -/***/ }), -/* 96 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.3 Number.isInteger(number) - var isObject = __webpack_require__(13); - var floor = Math.floor; - module.exports = function isInteger(it) { - return !isObject(it) && isFinite(it) && floor(it) === it; - }; - - -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.4 Number.isNaN(number) - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { - isNaN: function isNaN(number) { - // eslint-disable-next-line no-self-compare - return number != number; - } - }); - - -/***/ }), -/* 98 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.5 Number.isSafeInteger(number) - var $export = __webpack_require__(8); - var isInteger = __webpack_require__(96); - var abs = Math.abs; - - $export($export.S, 'Number', { - isSafeInteger: function isSafeInteger(number) { - return isInteger(number) && abs(number) <= 0x1fffffffffffff; - } - }); - - -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.6 Number.MAX_SAFE_INTEGER - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff }); - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.10 Number.MIN_SAFE_INTEGER - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff }); - - -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseFloat = __webpack_require__(86); - // 20.1.2.12 Number.parseFloat(string) - $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat }); - - -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseInt = __webpack_require__(82); - // 20.1.2.13 Number.parseInt(string, radix) - $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt }); - - -/***/ }), -/* 103 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.3 Math.acosh(x) - var $export = __webpack_require__(8); - var log1p = __webpack_require__(104); - var sqrt = Math.sqrt; - var $acosh = Math.acosh; - - $export($export.S + $export.F * !($acosh - // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 - && Math.floor($acosh(Number.MAX_VALUE)) == 710 - // Tor Browser bug: Math.acosh(Infinity) -> NaN - && $acosh(Infinity) == Infinity - ), 'Math', { - acosh: function acosh(x) { - return (x = +x) < 1 ? NaN : x > 94906265.62425156 - ? Math.log(x) + Math.LN2 - : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); - } - }); - - -/***/ }), -/* 104 */ -/***/ (function(module, exports) { - - // 20.2.2.20 Math.log1p(x) - module.exports = Math.log1p || function log1p(x) { - return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); - }; - - -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.5 Math.asinh(x) - var $export = __webpack_require__(8); - var $asinh = Math.asinh; - - function asinh(x) { - return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); - } - - // Tor Browser bug: Math.asinh(0) -> -0 - $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh }); - - -/***/ }), -/* 106 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.7 Math.atanh(x) - var $export = __webpack_require__(8); - var $atanh = Math.atanh; - - // Tor Browser bug: Math.atanh(-0) -> 0 - $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { - atanh: function atanh(x) { - return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; - } - }); - - -/***/ }), -/* 107 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.9 Math.cbrt(x) - var $export = __webpack_require__(8); - var sign = __webpack_require__(108); - - $export($export.S, 'Math', { - cbrt: function cbrt(x) { - return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); - } - }); - - -/***/ }), -/* 108 */ -/***/ (function(module, exports) { - - // 20.2.2.28 Math.sign(x) - module.exports = Math.sign || function sign(x) { - // eslint-disable-next-line no-self-compare - return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; - }; - - -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.11 Math.clz32(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - clz32: function clz32(x) { - return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; - } - }); - - -/***/ }), -/* 110 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.12 Math.cosh(x) - var $export = __webpack_require__(8); - var exp = Math.exp; - - $export($export.S, 'Math', { - cosh: function cosh(x) { - return (exp(x = +x) + exp(-x)) / 2; - } - }); - - -/***/ }), -/* 111 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.14 Math.expm1(x) - var $export = __webpack_require__(8); - var $expm1 = __webpack_require__(112); - - $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 }); - - -/***/ }), -/* 112 */ -/***/ (function(module, exports) { - - // 20.2.2.14 Math.expm1(x) - var $expm1 = Math.expm1; - module.exports = (!$expm1 - // Old FF bug - || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 - // Tor Browser bug - || $expm1(-2e-17) != -2e-17 - ) ? function expm1(x) { - return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; - } : $expm1; - - -/***/ }), -/* 113 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.16 Math.fround(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { fround: __webpack_require__(114) }); - - -/***/ }), -/* 114 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.16 Math.fround(x) - var sign = __webpack_require__(108); - var pow = Math.pow; - var EPSILON = pow(2, -52); - var EPSILON32 = pow(2, -23); - var MAX32 = pow(2, 127) * (2 - EPSILON32); - var MIN32 = pow(2, -126); - - var roundTiesToEven = function (n) { - return n + 1 / EPSILON - 1 / EPSILON; - }; - - module.exports = Math.fround || function fround(x) { - var $abs = Math.abs(x); - var $sign = sign(x); - var a, result; - if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; - a = (1 + EPSILON32 / EPSILON) * $abs; - result = a - (a - $abs); - // eslint-disable-next-line no-self-compare - if (result > MAX32 || result != result) return $sign * Infinity; - return $sign * result; - }; - - -/***/ }), -/* 115 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) - var $export = __webpack_require__(8); - var abs = Math.abs; - - $export($export.S, 'Math', { - hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars - var sum = 0; - var i = 0; - var aLen = arguments.length; - var larg = 0; - var arg, div; - while (i < aLen) { - arg = abs(arguments[i++]); - if (larg < arg) { - div = larg / arg; - sum = sum * div * div + 1; - larg = arg; - } else if (arg > 0) { - div = arg / larg; - sum += div * div; - } else sum += arg; - } - return larg === Infinity ? Infinity : larg * Math.sqrt(sum); - } - }); - - -/***/ }), -/* 116 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.18 Math.imul(x, y) - var $export = __webpack_require__(8); - var $imul = Math.imul; - - // some WebKit versions fails with big numbers, some has wrong arity - $export($export.S + $export.F * __webpack_require__(7)(function () { - return $imul(0xffffffff, 5) != -5 || $imul.length != 2; - }), 'Math', { - imul: function imul(x, y) { - var UINT16 = 0xffff; - var xn = +x; - var yn = +y; - var xl = UINT16 & xn; - var yl = UINT16 & yn; - return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); - } - }); - - -/***/ }), -/* 117 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.21 Math.log10(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - log10: function log10(x) { - return Math.log(x) * Math.LOG10E; - } - }); - - -/***/ }), -/* 118 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.20 Math.log1p(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { log1p: __webpack_require__(104) }); - - -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.22 Math.log2(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - log2: function log2(x) { - return Math.log(x) / Math.LN2; - } - }); - - -/***/ }), -/* 120 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.28 Math.sign(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { sign: __webpack_require__(108) }); - - -/***/ }), -/* 121 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.30 Math.sinh(x) - var $export = __webpack_require__(8); - var expm1 = __webpack_require__(112); - var exp = Math.exp; - - // V8 near Chromium 38 has a problem with very small numbers - $export($export.S + $export.F * __webpack_require__(7)(function () { - return !Math.sinh(-2e-17) != -2e-17; - }), 'Math', { - sinh: function sinh(x) { - return Math.abs(x = +x) < 1 - ? (expm1(x) - expm1(-x)) / 2 - : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); - } - }); - - -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.33 Math.tanh(x) - var $export = __webpack_require__(8); - var expm1 = __webpack_require__(112); - var exp = Math.exp; - - $export($export.S, 'Math', { - tanh: function tanh(x) { - var a = expm1(x = +x); - var b = expm1(-x); - return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); - } - }); - - -/***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.34 Math.trunc(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - trunc: function trunc(it) { - return (it > 0 ? Math.floor : Math.ceil)(it); - } - }); - - -/***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var toAbsoluteIndex = __webpack_require__(40); - var fromCharCode = String.fromCharCode; - var $fromCodePoint = String.fromCodePoint; - - // length should be 1, old FF problem - $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { - // 21.1.2.2 String.fromCodePoint(...codePoints) - fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars - var res = []; - var aLen = arguments.length; - var i = 0; - var code; - while (aLen > i) { - code = +arguments[i++]; - if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point'); - res.push(code < 0x10000 - ? fromCharCode(code) - : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) - ); - } return res.join(''); - } - }); - - -/***/ }), -/* 125 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(33); - var toLength = __webpack_require__(38); - - $export($export.S, 'String', { - // 21.1.2.4 String.raw(callSite, ...substitutions) - raw: function raw(callSite) { - var tpl = toIObject(callSite.raw); - var len = toLength(tpl.length); - var aLen = arguments.length; - var res = []; - var i = 0; - while (len > i) { - res.push(String(tpl[i++])); - if (i < aLen) res.push(String(arguments[i])); - } return res.join(''); - } - }); - - -/***/ }), -/* 126 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 21.1.3.25 String.prototype.trim() - __webpack_require__(83)('trim', function ($trim) { - return function trim() { - return $trim(this, 3); - }; - }); - - -/***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $at = __webpack_require__(128)(true); - - // 21.1.3.27 String.prototype[@@iterator]() - __webpack_require__(129)(String, 'String', function (iterated) { - this._t = String(iterated); // target - this._i = 0; // next index - // 21.1.5.2.1 %StringIteratorPrototype%.next() - }, function () { - var O = this._t; - var index = this._i; - var point; - if (index >= O.length) return { value: undefined, done: true }; - point = $at(O, index); - this._i += point.length; - return { value: point, done: false }; - }); - - -/***/ }), -/* 128 */ -/***/ (function(module, exports, __webpack_require__) { - - var toInteger = __webpack_require__(39); - var defined = __webpack_require__(36); - // true -> String#at - // false -> String#codePointAt - module.exports = function (TO_STRING) { - return function (that, pos) { - var s = String(defined(that)); - var i = toInteger(pos); - var l = s.length; - var a, b; - if (i < 0 || i >= l) return TO_STRING ? '' : undefined; - a = s.charCodeAt(i); - return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff - ? TO_STRING ? s.charAt(i) : a - : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; - }; - }; - - -/***/ }), -/* 129 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var LIBRARY = __webpack_require__(22); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var hide = __webpack_require__(10); - var Iterators = __webpack_require__(130); - var $iterCreate = __webpack_require__(131); - var setToStringTag = __webpack_require__(26); - var getPrototypeOf = __webpack_require__(59); - var ITERATOR = __webpack_require__(27)('iterator'); - var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` - var FF_ITERATOR = '@@iterator'; - var KEYS = 'keys'; - var VALUES = 'values'; - - var returnThis = function () { return this; }; - - module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { - $iterCreate(Constructor, NAME, next); - var getMethod = function (kind) { - if (!BUGGY && kind in proto) return proto[kind]; - switch (kind) { - case KEYS: return function keys() { return new Constructor(this, kind); }; - case VALUES: return function values() { return new Constructor(this, kind); }; - } return function entries() { return new Constructor(this, kind); }; - }; - var TAG = NAME + ' Iterator'; - var DEF_VALUES = DEFAULT == VALUES; - var VALUES_BUG = false; - var proto = Base.prototype; - var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; - var $default = $native || getMethod(DEFAULT); - var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; - var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; - var methods, key, IteratorPrototype; - // Fix native - if ($anyNative) { - IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); - if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { - // Set @@toStringTag to native iterators - setToStringTag(IteratorPrototype, TAG, true); - // fix for some old engines - if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); - } - } - // fix Array#{values, @@iterator}.name in V8 / FF - if (DEF_VALUES && $native && $native.name !== VALUES) { - VALUES_BUG = true; - $default = function values() { return $native.call(this); }; - } - // Define iterator - if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { - hide(proto, ITERATOR, $default); - } - // Plug for library - Iterators[NAME] = $default; - Iterators[TAG] = returnThis; - if (DEFAULT) { - methods = { - values: DEF_VALUES ? $default : getMethod(VALUES), - keys: IS_SET ? $default : getMethod(KEYS), - entries: $entries - }; - if (FORCED) for (key in methods) { - if (!(key in proto)) redefine(proto, key, methods[key]); - } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); - } - return methods; - }; - - -/***/ }), -/* 130 */ -/***/ (function(module, exports) { - - module.exports = {}; - - -/***/ }), -/* 131 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var create = __webpack_require__(47); - var descriptor = __webpack_require__(17); - var setToStringTag = __webpack_require__(26); - var IteratorPrototype = {}; - - // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() - __webpack_require__(10)(IteratorPrototype, __webpack_require__(27)('iterator'), function () { return this; }); - - module.exports = function (Constructor, NAME, next) { - Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); - setToStringTag(Constructor, NAME + ' Iterator'); - }; - - -/***/ }), -/* 132 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $at = __webpack_require__(128)(false); - $export($export.P, 'String', { - // 21.1.3.3 String.prototype.codePointAt(pos) - codePointAt: function codePointAt(pos) { - return $at(this, pos); - } - }); - - -/***/ }), -/* 133 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) - 'use strict'; - var $export = __webpack_require__(8); - var toLength = __webpack_require__(38); - var context = __webpack_require__(134); - var ENDS_WITH = 'endsWith'; - var $endsWith = ''[ENDS_WITH]; - - $export($export.P + $export.F * __webpack_require__(136)(ENDS_WITH), 'String', { - endsWith: function endsWith(searchString /* , endPosition = @length */) { - var that = context(this, searchString, ENDS_WITH); - var endPosition = arguments.length > 1 ? arguments[1] : undefined; - var len = toLength(that.length); - var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); - var search = String(searchString); - return $endsWith - ? $endsWith.call(that, search, end) - : that.slice(end - search.length, end) === search; - } - }); - - -/***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { - - // helper for String#{startsWith, endsWith, includes} - var isRegExp = __webpack_require__(135); - var defined = __webpack_require__(36); - - module.exports = function (that, searchString, NAME) { - if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!"); - return String(defined(that)); - }; - - -/***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.2.8 IsRegExp(argument) - var isObject = __webpack_require__(13); - var cof = __webpack_require__(35); - var MATCH = __webpack_require__(27)('match'); - module.exports = function (it) { - var isRegExp; - return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); - }; - - -/***/ }), -/* 136 */ -/***/ (function(module, exports, __webpack_require__) { - - var MATCH = __webpack_require__(27)('match'); - module.exports = function (KEY) { - var re = /./; - try { - '/./'[KEY](re); - } catch (e) { - try { - re[MATCH] = false; - return !'/./'[KEY](re); - } catch (f) { /* empty */ } - } return true; - }; - - -/***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.7 String.prototype.includes(searchString, position = 0) - 'use strict'; - var $export = __webpack_require__(8); - var context = __webpack_require__(134); - var INCLUDES = 'includes'; - - $export($export.P + $export.F * __webpack_require__(136)(INCLUDES), 'String', { - includes: function includes(searchString /* , position = 0 */) { - return !!~context(this, searchString, INCLUDES) - .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - -/***/ }), -/* 138 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - - $export($export.P, 'String', { - // 21.1.3.13 String.prototype.repeat(count) - repeat: __webpack_require__(91) - }); - - -/***/ }), -/* 139 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) - 'use strict'; - var $export = __webpack_require__(8); - var toLength = __webpack_require__(38); - var context = __webpack_require__(134); - var STARTS_WITH = 'startsWith'; - var $startsWith = ''[STARTS_WITH]; - - $export($export.P + $export.F * __webpack_require__(136)(STARTS_WITH), 'String', { - startsWith: function startsWith(searchString /* , position = 0 */) { - var that = context(this, searchString, STARTS_WITH); - var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)); - var search = String(searchString); - return $startsWith - ? $startsWith.call(that, search, index) - : that.slice(index, index + search.length) === search; - } - }); - - -/***/ }), -/* 140 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.2 String.prototype.anchor(name) - __webpack_require__(141)('anchor', function (createHTML) { - return function anchor(name) { - return createHTML(this, 'a', 'name', name); - }; - }); - - -/***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var fails = __webpack_require__(7); - var defined = __webpack_require__(36); - var quot = /"/g; - // B.2.3.2.1 CreateHTML(string, tag, attribute, value) - var createHTML = function (string, tag, attribute, value) { - var S = String(defined(string)); - var p1 = '<' + tag; - if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; - return p1 + '>' + S + ''; - }; - module.exports = function (NAME, exec) { - var O = {}; - O[NAME] = exec(createHTML); - $export($export.P + $export.F * fails(function () { - var test = ''[NAME]('"'); - return test !== test.toLowerCase() || test.split('"').length > 3; - }), 'String', O); - }; - - -/***/ }), -/* 142 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.3 String.prototype.big() - __webpack_require__(141)('big', function (createHTML) { - return function big() { - return createHTML(this, 'big', '', ''); - }; - }); - - -/***/ }), -/* 143 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.4 String.prototype.blink() - __webpack_require__(141)('blink', function (createHTML) { - return function blink() { - return createHTML(this, 'blink', '', ''); - }; - }); - - -/***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.5 String.prototype.bold() - __webpack_require__(141)('bold', function (createHTML) { - return function bold() { - return createHTML(this, 'b', '', ''); - }; - }); - - -/***/ }), -/* 145 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.6 String.prototype.fixed() - __webpack_require__(141)('fixed', function (createHTML) { - return function fixed() { - return createHTML(this, 'tt', '', ''); - }; - }); - - -/***/ }), -/* 146 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.7 String.prototype.fontcolor(color) - __webpack_require__(141)('fontcolor', function (createHTML) { - return function fontcolor(color) { - return createHTML(this, 'font', 'color', color); - }; - }); - - -/***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.8 String.prototype.fontsize(size) - __webpack_require__(141)('fontsize', function (createHTML) { - return function fontsize(size) { - return createHTML(this, 'font', 'size', size); - }; - }); - - -/***/ }), -/* 148 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.9 String.prototype.italics() - __webpack_require__(141)('italics', function (createHTML) { - return function italics() { - return createHTML(this, 'i', '', ''); - }; - }); - - -/***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.10 String.prototype.link(url) - __webpack_require__(141)('link', function (createHTML) { - return function link(url) { - return createHTML(this, 'a', 'href', url); - }; - }); - - -/***/ }), -/* 150 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.11 String.prototype.small() - __webpack_require__(141)('small', function (createHTML) { - return function small() { - return createHTML(this, 'small', '', ''); - }; - }); - - -/***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.12 String.prototype.strike() - __webpack_require__(141)('strike', function (createHTML) { - return function strike() { - return createHTML(this, 'strike', '', ''); - }; - }); - - -/***/ }), -/* 152 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.13 String.prototype.sub() - __webpack_require__(141)('sub', function (createHTML) { - return function sub() { - return createHTML(this, 'sub', '', ''); - }; - }); - - -/***/ }), -/* 153 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.14 String.prototype.sup() - __webpack_require__(141)('sup', function (createHTML) { - return function sup() { - return createHTML(this, 'sup', '', ''); - }; - }); - - -/***/ }), -/* 154 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.3.3.1 / 15.9.4.4 Date.now() - var $export = __webpack_require__(8); - - $export($export.S, 'Date', { now: function () { return new Date().getTime(); } }); - - -/***/ }), -/* 155 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(46); - var toPrimitive = __webpack_require__(16); - - $export($export.P + $export.F * __webpack_require__(7)(function () { - return new Date(NaN).toJSON() !== null - || Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1; - }), 'Date', { - // eslint-disable-next-line no-unused-vars - toJSON: function toJSON(key) { - var O = toObject(this); - var pv = toPrimitive(O); - return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); - } - }); - - -/***/ }), -/* 156 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() - var $export = __webpack_require__(8); - var toISOString = __webpack_require__(157); - - // PhantomJS / old WebKit has a broken implementations - $export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', { - toISOString: toISOString - }); - - -/***/ }), -/* 157 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() - var fails = __webpack_require__(7); - var getTime = Date.prototype.getTime; - var $toISOString = Date.prototype.toISOString; - - var lz = function (num) { - return num > 9 ? num : '0' + num; - }; - - // PhantomJS / old WebKit has a broken implementations - module.exports = (fails(function () { - return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z'; - }) || !fails(function () { - $toISOString.call(new Date(NaN)); - })) ? function toISOString() { - if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value'); - var d = this; - var y = d.getUTCFullYear(); - var m = d.getUTCMilliseconds(); - var s = y < 0 ? '-' : y > 9999 ? '+' : ''; - return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + - '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + - 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + - ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; - } : $toISOString; - - -/***/ }), -/* 158 */ -/***/ (function(module, exports, __webpack_require__) { - - var DateProto = Date.prototype; - var INVALID_DATE = 'Invalid Date'; - var TO_STRING = 'toString'; - var $toString = DateProto[TO_STRING]; - var getTime = DateProto.getTime; - if (new Date(NaN) + '' != INVALID_DATE) { - __webpack_require__(18)(DateProto, TO_STRING, function toString() { - var value = getTime.call(this); - // eslint-disable-next-line no-self-compare - return value === value ? $toString.call(this) : INVALID_DATE; - }); - } - - -/***/ }), -/* 159 */ -/***/ (function(module, exports, __webpack_require__) { - - var TO_PRIMITIVE = __webpack_require__(27)('toPrimitive'); - var proto = Date.prototype; - - if (!(TO_PRIMITIVE in proto)) __webpack_require__(10)(proto, TO_PRIMITIVE, __webpack_require__(160)); - - -/***/ }), -/* 160 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var anObject = __webpack_require__(12); - var toPrimitive = __webpack_require__(16); - var NUMBER = 'number'; - - module.exports = function (hint) { - if (hint !== 'string' && hint !== NUMBER && hint !== 'default') throw TypeError('Incorrect hint'); - return toPrimitive(anObject(this), hint != NUMBER); - }; - - -/***/ }), -/* 161 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) - var $export = __webpack_require__(8); - - $export($export.S, 'Array', { isArray: __webpack_require__(45) }); - - -/***/ }), -/* 162 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var ctx = __webpack_require__(23); - var $export = __webpack_require__(8); - var toObject = __webpack_require__(46); - var call = __webpack_require__(163); - var isArrayIter = __webpack_require__(164); - var toLength = __webpack_require__(38); - var createProperty = __webpack_require__(165); - var getIterFn = __webpack_require__(166); - - $export($export.S + $export.F * !__webpack_require__(167)(function (iter) { Array.from(iter); }), 'Array', { - // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) - from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { - var O = toObject(arrayLike); - var C = typeof this == 'function' ? this : Array; - var aLen = arguments.length; - var mapfn = aLen > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var index = 0; - var iterFn = getIterFn(O); - var length, result, step, iterator; - if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); - // if object isn't iterable or it's array with default iterator - use simple case - if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { - for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { - createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); - } - } else { - length = toLength(O.length); - for (result = new C(length); length > index; index++) { - createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); - } - } - result.length = index; - return result; - } - }); - - -/***/ }), -/* 163 */ -/***/ (function(module, exports, __webpack_require__) { - - // call something on iterator step with safe closing on error - var anObject = __webpack_require__(12); - module.exports = function (iterator, fn, value, entries) { - try { - return entries ? fn(anObject(value)[0], value[1]) : fn(value); - // 7.4.6 IteratorClose(iterator, completion) - } catch (e) { - var ret = iterator['return']; - if (ret !== undefined) anObject(ret.call(iterator)); - throw e; - } - }; - - -/***/ }), -/* 164 */ -/***/ (function(module, exports, __webpack_require__) { - - // check on default Array iterator - var Iterators = __webpack_require__(130); - var ITERATOR = __webpack_require__(27)('iterator'); - var ArrayProto = Array.prototype; - - module.exports = function (it) { - return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); - }; - - -/***/ }), -/* 165 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $defineProperty = __webpack_require__(11); - var createDesc = __webpack_require__(17); - - module.exports = function (object, index, value) { - if (index in object) $defineProperty.f(object, index, createDesc(0, value)); - else object[index] = value; - }; - - -/***/ }), -/* 166 */ -/***/ (function(module, exports, __webpack_require__) { - - var classof = __webpack_require__(75); - var ITERATOR = __webpack_require__(27)('iterator'); - var Iterators = __webpack_require__(130); - module.exports = __webpack_require__(9).getIteratorMethod = function (it) { - if (it != undefined) return it[ITERATOR] - || it['@@iterator'] - || Iterators[classof(it)]; - }; - - -/***/ }), -/* 167 */ -/***/ (function(module, exports, __webpack_require__) { - - var ITERATOR = __webpack_require__(27)('iterator'); - var SAFE_CLOSING = false; - - try { - var riter = [7][ITERATOR](); - riter['return'] = function () { SAFE_CLOSING = true; }; - // eslint-disable-next-line no-throw-literal - Array.from(riter, function () { throw 2; }); - } catch (e) { /* empty */ } - - module.exports = function (exec, skipClosing) { - if (!skipClosing && !SAFE_CLOSING) return false; - var safe = false; - try { - var arr = [7]; - var iter = arr[ITERATOR](); - iter.next = function () { return { done: safe = true }; }; - arr[ITERATOR] = function () { return iter; }; - exec(arr); - } catch (e) { /* empty */ } - return safe; - }; - - -/***/ }), -/* 168 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var createProperty = __webpack_require__(165); - - // WebKit Array.of isn't generic - $export($export.S + $export.F * __webpack_require__(7)(function () { - function F() { /* empty */ } - return !(Array.of.call(F) instanceof F); - }), 'Array', { - // 22.1.2.3 Array.of( ...items) - of: function of(/* ...args */) { - var index = 0; - var aLen = arguments.length; - var result = new (typeof this == 'function' ? this : Array)(aLen); - while (aLen > index) createProperty(result, index, arguments[index++]); - result.length = aLen; - return result; - } - }); - - -/***/ }), -/* 169 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.13 Array.prototype.join(separator) - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(33); - var arrayJoin = [].join; - - // fallback for not array-like strings - $export($export.P + $export.F * (__webpack_require__(34) != Object || !__webpack_require__(170)(arrayJoin)), 'Array', { - join: function join(separator) { - return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); - } - }); - - -/***/ }), -/* 170 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var fails = __webpack_require__(7); - - module.exports = function (method, arg) { - return !!method && fails(function () { - // eslint-disable-next-line no-useless-call - arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null); - }); - }; - - -/***/ }), -/* 171 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var html = __webpack_require__(49); - var cof = __webpack_require__(35); - var toAbsoluteIndex = __webpack_require__(40); - var toLength = __webpack_require__(38); - var arraySlice = [].slice; - - // fallback for not array-like ES3 strings and DOM objects - $export($export.P + $export.F * __webpack_require__(7)(function () { - if (html) arraySlice.call(html); - }), 'Array', { - slice: function slice(begin, end) { - var len = toLength(this.length); - var klass = cof(this); - end = end === undefined ? len : end; - if (klass == 'Array') return arraySlice.call(this, begin, end); - var start = toAbsoluteIndex(begin, len); - var upTo = toAbsoluteIndex(end, len); - var size = toLength(upTo - start); - var cloned = new Array(size); - var i = 0; - for (; i < size; i++) cloned[i] = klass == 'String' - ? this.charAt(start + i) - : this[start + i]; - return cloned; - } - }); - - -/***/ }), -/* 172 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(24); - var toObject = __webpack_require__(46); - var fails = __webpack_require__(7); - var $sort = [].sort; - var test = [1, 2, 3]; - - $export($export.P + $export.F * (fails(function () { - // IE8- - test.sort(undefined); - }) || !fails(function () { - // V8 bug - test.sort(null); - // Old WebKit - }) || !__webpack_require__(170)($sort)), 'Array', { - // 22.1.3.25 Array.prototype.sort(comparefn) - sort: function sort(comparefn) { - return comparefn === undefined - ? $sort.call(toObject(this)) - : $sort.call(toObject(this), aFunction(comparefn)); - } - }); - - -/***/ }), -/* 173 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $forEach = __webpack_require__(174)(0); - var STRICT = __webpack_require__(170)([].forEach, true); - - $export($export.P + $export.F * !STRICT, 'Array', { - // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) - forEach: function forEach(callbackfn /* , thisArg */) { - return $forEach(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 174 */ -/***/ (function(module, exports, __webpack_require__) { - - // 0 -> Array#forEach - // 1 -> Array#map - // 2 -> Array#filter - // 3 -> Array#some - // 4 -> Array#every - // 5 -> Array#find - // 6 -> Array#findIndex - var ctx = __webpack_require__(23); - var IObject = __webpack_require__(34); - var toObject = __webpack_require__(46); - var toLength = __webpack_require__(38); - var asc = __webpack_require__(175); - module.exports = function (TYPE, $create) { - var IS_MAP = TYPE == 1; - var IS_FILTER = TYPE == 2; - var IS_SOME = TYPE == 3; - var IS_EVERY = TYPE == 4; - var IS_FIND_INDEX = TYPE == 6; - var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; - var create = $create || asc; - return function ($this, callbackfn, that) { - var O = toObject($this); - var self = IObject(O); - var f = ctx(callbackfn, that, 3); - var length = toLength(self.length); - var index = 0; - var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; - var val, res; - for (;length > index; index++) if (NO_HOLES || index in self) { - val = self[index]; - res = f(val, index, O); - if (TYPE) { - if (IS_MAP) result[index] = res; // map - else if (res) switch (TYPE) { - case 3: return true; // some - case 5: return val; // find - case 6: return index; // findIndex - case 2: result.push(val); // filter - } else if (IS_EVERY) return false; // every - } - } - return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; - }; - }; - - -/***/ }), -/* 175 */ -/***/ (function(module, exports, __webpack_require__) { - - // 9.4.2.3 ArraySpeciesCreate(originalArray, length) - var speciesConstructor = __webpack_require__(176); - - module.exports = function (original, length) { - return new (speciesConstructor(original))(length); - }; - - -/***/ }), -/* 176 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var isArray = __webpack_require__(45); - var SPECIES = __webpack_require__(27)('species'); - - module.exports = function (original) { - var C; - if (isArray(original)) { - C = original.constructor; - // cross-realm fallback - if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; - if (isObject(C)) { - C = C[SPECIES]; - if (C === null) C = undefined; - } - } return C === undefined ? Array : C; - }; - - -/***/ }), -/* 177 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $map = __webpack_require__(174)(1); - - $export($export.P + $export.F * !__webpack_require__(170)([].map, true), 'Array', { - // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) - map: function map(callbackfn /* , thisArg */) { - return $map(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 178 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $filter = __webpack_require__(174)(2); - - $export($export.P + $export.F * !__webpack_require__(170)([].filter, true), 'Array', { - // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) - filter: function filter(callbackfn /* , thisArg */) { - return $filter(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 179 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $some = __webpack_require__(174)(3); - - $export($export.P + $export.F * !__webpack_require__(170)([].some, true), 'Array', { - // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) - some: function some(callbackfn /* , thisArg */) { - return $some(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 180 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $every = __webpack_require__(174)(4); - - $export($export.P + $export.F * !__webpack_require__(170)([].every, true), 'Array', { - // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) - every: function every(callbackfn /* , thisArg */) { - return $every(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 181 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $reduce = __webpack_require__(182); - - $export($export.P + $export.F * !__webpack_require__(170)([].reduce, true), 'Array', { - // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) - reduce: function reduce(callbackfn /* , initialValue */) { - return $reduce(this, callbackfn, arguments.length, arguments[1], false); - } - }); - - -/***/ }), -/* 182 */ -/***/ (function(module, exports, __webpack_require__) { - - var aFunction = __webpack_require__(24); - var toObject = __webpack_require__(46); - var IObject = __webpack_require__(34); - var toLength = __webpack_require__(38); - - module.exports = function (that, callbackfn, aLen, memo, isRight) { - aFunction(callbackfn); - var O = toObject(that); - var self = IObject(O); - var length = toLength(O.length); - var index = isRight ? length - 1 : 0; - var i = isRight ? -1 : 1; - if (aLen < 2) for (;;) { - if (index in self) { - memo = self[index]; - index += i; - break; - } - index += i; - if (isRight ? index < 0 : length <= index) { - throw TypeError('Reduce of empty array with no initial value'); - } - } - for (;isRight ? index >= 0 : length > index; index += i) if (index in self) { - memo = callbackfn(memo, self[index], index, O); - } - return memo; - }; - - -/***/ }), -/* 183 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $reduce = __webpack_require__(182); - - $export($export.P + $export.F * !__webpack_require__(170)([].reduceRight, true), 'Array', { - // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) - reduceRight: function reduceRight(callbackfn /* , initialValue */) { - return $reduce(this, callbackfn, arguments.length, arguments[1], true); - } - }); - - -/***/ }), -/* 184 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $indexOf = __webpack_require__(37)(false); - var $native = [].indexOf; - var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; - - $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(170)($native)), 'Array', { - // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) - indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { - return NEGATIVE_ZERO - // convert -0 to +0 - ? $native.apply(this, arguments) || 0 - : $indexOf(this, searchElement, arguments[1]); - } - }); - - -/***/ }), -/* 185 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(33); - var toInteger = __webpack_require__(39); - var toLength = __webpack_require__(38); - var $native = [].lastIndexOf; - var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; - - $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(170)($native)), 'Array', { - // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) - lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { - // convert -0 to +0 - if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0; - var O = toIObject(this); - var length = toLength(O.length); - var index = length - 1; - if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1])); - if (index < 0) index = length + index; - for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0; - return -1; - } - }); - - -/***/ }), -/* 186 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) - var $export = __webpack_require__(8); - - $export($export.P, 'Array', { copyWithin: __webpack_require__(187) }); - - __webpack_require__(188)('copyWithin'); - - -/***/ }), -/* 187 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) - 'use strict'; - var toObject = __webpack_require__(46); - var toAbsoluteIndex = __webpack_require__(40); - var toLength = __webpack_require__(38); - - module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { - var O = toObject(this); - var len = toLength(O.length); - var to = toAbsoluteIndex(target, len); - var from = toAbsoluteIndex(start, len); - var end = arguments.length > 2 ? arguments[2] : undefined; - var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); - var inc = 1; - if (from < to && to < from + count) { - inc = -1; - from += count - 1; - to += count - 1; - } - while (count-- > 0) { - if (from in O) O[to] = O[from]; - else delete O[to]; - to += inc; - from += inc; - } return O; - }; - - -/***/ }), -/* 188 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.31 Array.prototype[@@unscopables] - var UNSCOPABLES = __webpack_require__(27)('unscopables'); - var ArrayProto = Array.prototype; - if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(10)(ArrayProto, UNSCOPABLES, {}); - module.exports = function (key) { - ArrayProto[UNSCOPABLES][key] = true; - }; - - -/***/ }), -/* 189 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) - var $export = __webpack_require__(8); - - $export($export.P, 'Array', { fill: __webpack_require__(190) }); - - __webpack_require__(188)('fill'); - - -/***/ }), -/* 190 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) - 'use strict'; - var toObject = __webpack_require__(46); - var toAbsoluteIndex = __webpack_require__(40); - var toLength = __webpack_require__(38); - module.exports = function fill(value /* , start = 0, end = @length */) { - var O = toObject(this); - var length = toLength(O.length); - var aLen = arguments.length; - var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length); - var end = aLen > 2 ? arguments[2] : undefined; - var endPos = end === undefined ? length : toAbsoluteIndex(end, length); - while (endPos > index) O[index++] = value; - return O; - }; - - -/***/ }), -/* 191 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) - var $export = __webpack_require__(8); - var $find = __webpack_require__(174)(5); - var KEY = 'find'; - var forced = true; - // Shouldn't skip holes - if (KEY in []) Array(1)[KEY](function () { forced = false; }); - $export($export.P + $export.F * forced, 'Array', { - find: function find(callbackfn /* , that = undefined */) { - return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - __webpack_require__(188)(KEY); - - -/***/ }), -/* 192 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) - var $export = __webpack_require__(8); - var $find = __webpack_require__(174)(6); - var KEY = 'findIndex'; - var forced = true; - // Shouldn't skip holes - if (KEY in []) Array(1)[KEY](function () { forced = false; }); - $export($export.P + $export.F * forced, 'Array', { - findIndex: function findIndex(callbackfn /* , that = undefined */) { - return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - __webpack_require__(188)(KEY); - - -/***/ }), -/* 193 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(194)('Array'); - - -/***/ }), -/* 194 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var dP = __webpack_require__(11); - var DESCRIPTORS = __webpack_require__(6); - var SPECIES = __webpack_require__(27)('species'); - - module.exports = function (KEY) { - var C = global[KEY]; - if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { - configurable: true, - get: function () { return this; } - }); - }; - - -/***/ }), -/* 195 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var addToUnscopables = __webpack_require__(188); - var step = __webpack_require__(196); - var Iterators = __webpack_require__(130); - var toIObject = __webpack_require__(33); - - // 22.1.3.4 Array.prototype.entries() - // 22.1.3.13 Array.prototype.keys() - // 22.1.3.29 Array.prototype.values() - // 22.1.3.30 Array.prototype[@@iterator]() - module.exports = __webpack_require__(129)(Array, 'Array', function (iterated, kind) { - this._t = toIObject(iterated); // target - this._i = 0; // next index - this._k = kind; // kind - // 22.1.5.2.1 %ArrayIteratorPrototype%.next() - }, function () { - var O = this._t; - var kind = this._k; - var index = this._i++; - if (!O || index >= O.length) { - this._t = undefined; - return step(1); - } - if (kind == 'keys') return step(0, index); - if (kind == 'values') return step(0, O[index]); - return step(0, [index, O[index]]); - }, 'values'); - - // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) - Iterators.Arguments = Iterators.Array; - - addToUnscopables('keys'); - addToUnscopables('values'); - addToUnscopables('entries'); - - -/***/ }), -/* 196 */ -/***/ (function(module, exports) { - - module.exports = function (done, value) { - return { value: value, done: !!done }; - }; - - -/***/ }), -/* 197 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var inheritIfRequired = __webpack_require__(88); - var dP = __webpack_require__(11).f; - var gOPN = __webpack_require__(51).f; - var isRegExp = __webpack_require__(135); - var $flags = __webpack_require__(198); - var $RegExp = global.RegExp; - var Base = $RegExp; - var proto = $RegExp.prototype; - var re1 = /a/g; - var re2 = /a/g; - // "new" creates a new object, old webkit buggy here - var CORRECT_NEW = new $RegExp(re1) !== re1; - - if (__webpack_require__(6) && (!CORRECT_NEW || __webpack_require__(7)(function () { - re2[__webpack_require__(27)('match')] = false; - // RegExp constructor can alter flags and IsRegExp works correct with @@match - return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; - }))) { - $RegExp = function RegExp(p, f) { - var tiRE = this instanceof $RegExp; - var piRE = isRegExp(p); - var fiU = f === undefined; - return !tiRE && piRE && p.constructor === $RegExp && fiU ? p - : inheritIfRequired(CORRECT_NEW - ? new Base(piRE && !fiU ? p.source : p, f) - : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) - , tiRE ? this : proto, $RegExp); - }; - var proxy = function (key) { - key in $RegExp || dP($RegExp, key, { - configurable: true, - get: function () { return Base[key]; }, - set: function (it) { Base[key] = it; } - }); - }; - for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]); - proto.constructor = $RegExp; - $RegExp.prototype = proto; - __webpack_require__(18)(global, 'RegExp', $RegExp); - } - - __webpack_require__(194)('RegExp'); - - -/***/ }), -/* 198 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 21.2.5.3 get RegExp.prototype.flags - var anObject = __webpack_require__(12); - module.exports = function () { - var that = anObject(this); - var result = ''; - if (that.global) result += 'g'; - if (that.ignoreCase) result += 'i'; - if (that.multiline) result += 'm'; - if (that.unicode) result += 'u'; - if (that.sticky) result += 'y'; - return result; - }; - - -/***/ }), -/* 199 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var regexpExec = __webpack_require__(200); - __webpack_require__(8)({ - target: 'RegExp', - proto: true, - forced: regexpExec !== /./.exec - }, { - exec: regexpExec - }); - - -/***/ }), -/* 200 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var regexpFlags = __webpack_require__(198); - - var nativeExec = RegExp.prototype.exec; - // This always refers to the native implementation, because the - // String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js, - // which loads this file before patching the method. - var nativeReplace = String.prototype.replace; - - var patchedExec = nativeExec; - - var LAST_INDEX = 'lastIndex'; - - var UPDATES_LAST_INDEX_WRONG = (function () { - var re1 = /a/, - re2 = /b*/g; - nativeExec.call(re1, 'a'); - nativeExec.call(re2, 'a'); - return re1[LAST_INDEX] !== 0 || re2[LAST_INDEX] !== 0; - })(); - - // nonparticipating capturing group, copied from es5-shim's String#split patch. - var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined; - - var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED; - - if (PATCH) { - patchedExec = function exec(str) { - var re = this; - var lastIndex, reCopy, match, i; - - if (NPCG_INCLUDED) { - reCopy = new RegExp('^' + re.source + '$(?!\\s)', regexpFlags.call(re)); - } - if (UPDATES_LAST_INDEX_WRONG) lastIndex = re[LAST_INDEX]; - - match = nativeExec.call(re, str); - - if (UPDATES_LAST_INDEX_WRONG && match) { - re[LAST_INDEX] = re.global ? match.index + match[0].length : lastIndex; - } - if (NPCG_INCLUDED && match && match.length > 1) { - // Fix browsers whose `exec` methods don't consistently return `undefined` - // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/ - // eslint-disable-next-line no-loop-func - nativeReplace.call(match[0], reCopy, function () { - for (i = 1; i < arguments.length - 2; i++) { - if (arguments[i] === undefined) match[i] = undefined; - } - }); - } - - return match; - }; - } - - module.exports = patchedExec; - - -/***/ }), -/* 201 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - __webpack_require__(202); - var anObject = __webpack_require__(12); - var $flags = __webpack_require__(198); - var DESCRIPTORS = __webpack_require__(6); - var TO_STRING = 'toString'; - var $toString = /./[TO_STRING]; - - var define = function (fn) { - __webpack_require__(18)(RegExp.prototype, TO_STRING, fn, true); - }; - - // 21.2.5.14 RegExp.prototype.toString() - if (__webpack_require__(7)(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) { - define(function toString() { - var R = anObject(this); - return '/'.concat(R.source, '/', - 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); - }); - // FF44- RegExp#toString has a wrong name - } else if ($toString.name != TO_STRING) { - define(function toString() { - return $toString.call(this); - }); - } - - -/***/ }), -/* 202 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.2.5.3 get RegExp.prototype.flags() - if (__webpack_require__(6) && /./g.flags != 'g') __webpack_require__(11).f(RegExp.prototype, 'flags', { - configurable: true, - get: __webpack_require__(198) - }); - - -/***/ }), -/* 203 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var anObject = __webpack_require__(12); - var toLength = __webpack_require__(38); - var advanceStringIndex = __webpack_require__(204); - var regExpExec = __webpack_require__(205); - - // @@match logic - __webpack_require__(206)('match', 1, function (defined, MATCH, $match, maybeCallNative) { - return [ - // `String.prototype.match` method - // https://tc39.github.io/ecma262/#sec-string.prototype.match - function match(regexp) { - var O = defined(this); - var fn = regexp == undefined ? undefined : regexp[MATCH]; - return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); - }, - // `RegExp.prototype[@@match]` method - // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match - function (regexp) { - var res = maybeCallNative($match, regexp, this); - if (res.done) return res.value; - var rx = anObject(regexp); - var S = String(this); - if (!rx.global) return regExpExec(rx, S); - var fullUnicode = rx.unicode; - rx.lastIndex = 0; - var A = []; - var n = 0; - var result; - while ((result = regExpExec(rx, S)) !== null) { - var matchStr = String(result[0]); - A[n] = matchStr; - if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); - n++; - } - return n === 0 ? null : A; - } - ]; - }); - - -/***/ }), -/* 204 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var at = __webpack_require__(128)(true); - - // `AdvanceStringIndex` abstract operation - // https://tc39.github.io/ecma262/#sec-advancestringindex - module.exports = function (S, index, unicode) { - return index + (unicode ? at(S, index).length : 1); - }; - - -/***/ }), -/* 205 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var classof = __webpack_require__(75); - var builtinExec = RegExp.prototype.exec; - - // `RegExpExec` abstract operation - // https://tc39.github.io/ecma262/#sec-regexpexec - module.exports = function (R, S) { - var exec = R.exec; - if (typeof exec === 'function') { - var result = exec.call(R, S); - if (typeof result !== 'object') { - throw new TypeError('RegExp exec method returned something other than an Object or null'); - } - return result; - } - if (classof(R) !== 'RegExp') { - throw new TypeError('RegExp#exec called on incompatible receiver'); - } - return builtinExec.call(R, S); - }; - - -/***/ }), -/* 206 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - __webpack_require__(199); - var redefine = __webpack_require__(18); - var hide = __webpack_require__(10); - var fails = __webpack_require__(7); - var defined = __webpack_require__(36); - var wks = __webpack_require__(27); - var regexpExec = __webpack_require__(200); - - var SPECIES = wks('species'); - - var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () { - // #replace needs built-in support for named groups. - // #match works fine because it just return the exec results, even if it has - // a "grops" property. - var re = /./; - re.exec = function () { - var result = []; - result.groups = { a: '7' }; - return result; - }; - return ''.replace(re, '$') !== '7'; - }); - - var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = (function () { - // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec - var re = /(?:)/; - var originalExec = re.exec; - re.exec = function () { return originalExec.apply(this, arguments); }; - var result = 'ab'.split(re); - return result.length === 2 && result[0] === 'a' && result[1] === 'b'; - })(); - - module.exports = function (KEY, length, exec) { - var SYMBOL = wks(KEY); - - var DELEGATES_TO_SYMBOL = !fails(function () { - // String methods call symbol-named RegEp methods - var O = {}; - O[SYMBOL] = function () { return 7; }; - return ''[KEY](O) != 7; - }); - - var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL ? !fails(function () { - // Symbol-named RegExp methods call .exec - var execCalled = false; - var re = /a/; - re.exec = function () { execCalled = true; return null; }; - if (KEY === 'split') { - // RegExp[@@split] doesn't call the regex's exec method, but first creates - // a new one. We need to return the patched regex when creating the new one. - re.constructor = {}; - re.constructor[SPECIES] = function () { return re; }; - } - re[SYMBOL](''); - return !execCalled; - }) : undefined; - - if ( - !DELEGATES_TO_SYMBOL || - !DELEGATES_TO_EXEC || - (KEY === 'replace' && !REPLACE_SUPPORTS_NAMED_GROUPS) || - (KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC) - ) { - var nativeRegExpMethod = /./[SYMBOL]; - var fns = exec( - defined, - SYMBOL, - ''[KEY], - function maybeCallNative(nativeMethod, regexp, str, arg2, forceStringMethod) { - if (regexp.exec === regexpExec) { - if (DELEGATES_TO_SYMBOL && !forceStringMethod) { - // The native String method already delegates to @@method (this - // polyfilled function), leasing to infinite recursion. - // We avoid it by directly calling the native @@method method. - return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) }; - } - return { done: true, value: nativeMethod.call(str, regexp, arg2) }; - } - return { done: false }; - } - ); - var strfn = fns[0]; - var rxfn = fns[1]; - - redefine(String.prototype, KEY, strfn); - hide(RegExp.prototype, SYMBOL, length == 2 - // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) - // 21.2.5.11 RegExp.prototype[@@split](string, limit) - ? function (string, arg) { return rxfn.call(string, this, arg); } - // 21.2.5.6 RegExp.prototype[@@match](string) - // 21.2.5.9 RegExp.prototype[@@search](string) - : function (string) { return rxfn.call(string, this); } - ); - } - }; - - -/***/ }), -/* 207 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var anObject = __webpack_require__(12); - var toObject = __webpack_require__(46); - var toLength = __webpack_require__(38); - var toInteger = __webpack_require__(39); - var advanceStringIndex = __webpack_require__(204); - var regExpExec = __webpack_require__(205); - var max = Math.max; - var min = Math.min; - var floor = Math.floor; - var SUBSTITUTION_SYMBOLS = /\$([$&`']|\d\d?|<[^>]*>)/g; - var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&`']|\d\d?)/g; - - var maybeToString = function (it) { - return it === undefined ? it : String(it); - }; - - // @@replace logic - __webpack_require__(206)('replace', 2, function (defined, REPLACE, $replace, maybeCallNative) { - return [ - // `String.prototype.replace` method - // https://tc39.github.io/ecma262/#sec-string.prototype.replace - function replace(searchValue, replaceValue) { - var O = defined(this); - var fn = searchValue == undefined ? undefined : searchValue[REPLACE]; - return fn !== undefined - ? fn.call(searchValue, O, replaceValue) - : $replace.call(String(O), searchValue, replaceValue); - }, - // `RegExp.prototype[@@replace]` method - // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace - function (regexp, replaceValue) { - var res = maybeCallNative($replace, regexp, this, replaceValue); - if (res.done) return res.value; - - var rx = anObject(regexp); - var S = String(this); - var functionalReplace = typeof replaceValue === 'function'; - if (!functionalReplace) replaceValue = String(replaceValue); - var global = rx.global; - if (global) { - var fullUnicode = rx.unicode; - rx.lastIndex = 0; - } - var results = []; - while (true) { - var result = regExpExec(rx, S); - if (result === null) break; - results.push(result); - if (!global) break; - var matchStr = String(result[0]); - if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); - } - var accumulatedResult = ''; - var nextSourcePosition = 0; - for (var i = 0; i < results.length; i++) { - result = results[i]; - var matched = String(result[0]); - var position = max(min(toInteger(result.index), S.length), 0); - var captures = []; - // NOTE: This is equivalent to - // captures = result.slice(1).map(maybeToString) - // but for some reason `nativeSlice.call(result, 1, result.length)` (called in - // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and - // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it. - for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j])); - var namedCaptures = result.groups; - if (functionalReplace) { - var replacerArgs = [matched].concat(captures, position, S); - if (namedCaptures !== undefined) replacerArgs.push(namedCaptures); - var replacement = String(replaceValue.apply(undefined, replacerArgs)); - } else { - replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue); - } - if (position >= nextSourcePosition) { - accumulatedResult += S.slice(nextSourcePosition, position) + replacement; - nextSourcePosition = position + matched.length; - } - } - return accumulatedResult + S.slice(nextSourcePosition); - } - ]; - - // https://tc39.github.io/ecma262/#sec-getsubstitution - function getSubstitution(matched, str, position, captures, namedCaptures, replacement) { - var tailPos = position + matched.length; - var m = captures.length; - var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED; - if (namedCaptures !== undefined) { - namedCaptures = toObject(namedCaptures); - symbols = SUBSTITUTION_SYMBOLS; - } - return $replace.call(replacement, symbols, function (match, ch) { - var capture; - switch (ch.charAt(0)) { - case '$': return '$'; - case '&': return matched; - case '`': return str.slice(0, position); - case "'": return str.slice(tailPos); - case '<': - capture = namedCaptures[ch.slice(1, -1)]; - break; - default: // \d\d? - var n = +ch; - if (n === 0) return match; - if (n > m) { - var f = floor(n / 10); - if (f === 0) return match; - if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1); - return match; - } - capture = captures[n - 1]; - } - return capture === undefined ? '' : capture; - }); - } - }); - - -/***/ }), -/* 208 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var anObject = __webpack_require__(12); - var sameValue = __webpack_require__(71); - var regExpExec = __webpack_require__(205); - - // @@search logic - __webpack_require__(206)('search', 1, function (defined, SEARCH, $search, maybeCallNative) { - return [ - // `String.prototype.search` method - // https://tc39.github.io/ecma262/#sec-string.prototype.search - function search(regexp) { - var O = defined(this); - var fn = regexp == undefined ? undefined : regexp[SEARCH]; - return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); - }, - // `RegExp.prototype[@@search]` method - // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@search - function (regexp) { - var res = maybeCallNative($search, regexp, this); - if (res.done) return res.value; - var rx = anObject(regexp); - var S = String(this); - var previousLastIndex = rx.lastIndex; - if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0; - var result = regExpExec(rx, S); - if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex; - return result === null ? -1 : result.index; - } - ]; - }); - - -/***/ }), -/* 209 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var isRegExp = __webpack_require__(135); - var anObject = __webpack_require__(12); - var speciesConstructor = __webpack_require__(210); - var advanceStringIndex = __webpack_require__(204); - var toLength = __webpack_require__(38); - var callRegExpExec = __webpack_require__(205); - var regexpExec = __webpack_require__(200); - var fails = __webpack_require__(7); - var $min = Math.min; - var $push = [].push; - var $SPLIT = 'split'; - var LENGTH = 'length'; - var LAST_INDEX = 'lastIndex'; - var MAX_UINT32 = 0xffffffff; - - // babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError - var SUPPORTS_Y = !fails(function () { RegExp(MAX_UINT32, 'y'); }); - - // @@split logic - __webpack_require__(206)('split', 2, function (defined, SPLIT, $split, maybeCallNative) { - var internalSplit; - if ( - 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || - 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || - 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || - '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || - '.'[$SPLIT](/()()/)[LENGTH] > 1 || - ''[$SPLIT](/.?/)[LENGTH] - ) { - // based on es5-shim implementation, need to rework it - internalSplit = function (separator, limit) { - var string = String(this); - if (separator === undefined && limit === 0) return []; - // If `separator` is not a regex, use native split - if (!isRegExp(separator)) return $split.call(string, separator, limit); - var output = []; - var flags = (separator.ignoreCase ? 'i' : '') + - (separator.multiline ? 'm' : '') + - (separator.unicode ? 'u' : '') + - (separator.sticky ? 'y' : ''); - var lastLastIndex = 0; - var splitLimit = limit === undefined ? MAX_UINT32 : limit >>> 0; - // Make `global` and avoid `lastIndex` issues by working with a copy - var separatorCopy = new RegExp(separator.source, flags + 'g'); - var match, lastIndex, lastLength; - while (match = regexpExec.call(separatorCopy, string)) { - lastIndex = separatorCopy[LAST_INDEX]; - if (lastIndex > lastLastIndex) { - output.push(string.slice(lastLastIndex, match.index)); - if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1)); - lastLength = match[0][LENGTH]; - lastLastIndex = lastIndex; - if (output[LENGTH] >= splitLimit) break; - } - if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop - } - if (lastLastIndex === string[LENGTH]) { - if (lastLength || !separatorCopy.test('')) output.push(''); - } else output.push(string.slice(lastLastIndex)); - return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; - }; - // Chakra, V8 - } else if ('0'[$SPLIT](undefined, 0)[LENGTH]) { - internalSplit = function (separator, limit) { - return separator === undefined && limit === 0 ? [] : $split.call(this, separator, limit); - }; - } else { - internalSplit = $split; - } - - return [ - // `String.prototype.split` method - // https://tc39.github.io/ecma262/#sec-string.prototype.split - function split(separator, limit) { - var O = defined(this); - var splitter = separator == undefined ? undefined : separator[SPLIT]; - return splitter !== undefined - ? splitter.call(separator, O, limit) - : internalSplit.call(String(O), separator, limit); - }, - // `RegExp.prototype[@@split]` method - // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split - // - // NOTE: This cannot be properly polyfilled in engines that don't support - // the 'y' flag. - function (regexp, limit) { - var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== $split); - if (res.done) return res.value; - - var rx = anObject(regexp); - var S = String(this); - var C = speciesConstructor(rx, RegExp); - - var unicodeMatching = rx.unicode; - var flags = (rx.ignoreCase ? 'i' : '') + - (rx.multiline ? 'm' : '') + - (rx.unicode ? 'u' : '') + - (SUPPORTS_Y ? 'y' : 'g'); - - // ^(? + rx + ) is needed, in combination with some S slicing, to - // simulate the 'y' flag. - var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags); - var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; - if (lim === 0) return []; - if (S.length === 0) return callRegExpExec(splitter, S) === null ? [S] : []; - var p = 0; - var q = 0; - var A = []; - while (q < S.length) { - splitter.lastIndex = SUPPORTS_Y ? q : 0; - var z = callRegExpExec(splitter, SUPPORTS_Y ? S : S.slice(q)); - var e; - if ( - z === null || - (e = $min(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p - ) { - q = advanceStringIndex(S, q, unicodeMatching); - } else { - A.push(S.slice(p, q)); - if (A.length === lim) return A; - for (var i = 1; i <= z.length - 1; i++) { - A.push(z[i]); - if (A.length === lim) return A; - } - q = p = e; - } - } - A.push(S.slice(p)); - return A; - } - ]; - }); - - -/***/ }), -/* 210 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.3.20 SpeciesConstructor(O, defaultConstructor) - var anObject = __webpack_require__(12); - var aFunction = __webpack_require__(24); - var SPECIES = __webpack_require__(27)('species'); - module.exports = function (O, D) { - var C = anObject(O).constructor; - var S; - return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); - }; - - -/***/ }), -/* 211 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var LIBRARY = __webpack_require__(22); - var global = __webpack_require__(4); - var ctx = __webpack_require__(23); - var classof = __webpack_require__(75); - var $export = __webpack_require__(8); - var isObject = __webpack_require__(13); - var aFunction = __webpack_require__(24); - var anInstance = __webpack_require__(212); - var forOf = __webpack_require__(213); - var speciesConstructor = __webpack_require__(210); - var task = __webpack_require__(214).set; - var microtask = __webpack_require__(215)(); - var newPromiseCapabilityModule = __webpack_require__(216); - var perform = __webpack_require__(217); - var userAgent = __webpack_require__(218); - var promiseResolve = __webpack_require__(219); - var PROMISE = 'Promise'; - var TypeError = global.TypeError; - var process = global.process; - var versions = process && process.versions; - var v8 = versions && versions.v8 || ''; - var $Promise = global[PROMISE]; - var isNode = classof(process) == 'process'; - var empty = function () { /* empty */ }; - var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; - var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; - - var USE_NATIVE = !!function () { - try { - // correct subclassing with @@species support - var promise = $Promise.resolve(1); - var FakePromise = (promise.constructor = {})[__webpack_require__(27)('species')] = function (exec) { - exec(empty, empty); - }; - // unhandled rejections tracking support, NodeJS Promise without it fails @@species test - return (isNode || typeof PromiseRejectionEvent == 'function') - && promise.then(empty) instanceof FakePromise - // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables - // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 - // we can't detect it synchronously, so just check versions - && v8.indexOf('6.6') !== 0 - && userAgent.indexOf('Chrome/66') === -1; - } catch (e) { /* empty */ } - }(); - - // helpers - var isThenable = function (it) { - var then; - return isObject(it) && typeof (then = it.then) == 'function' ? then : false; - }; - var notify = function (promise, isReject) { - if (promise._n) return; - promise._n = true; - var chain = promise._c; - microtask(function () { - var value = promise._v; - var ok = promise._s == 1; - var i = 0; - var run = function (reaction) { - var handler = ok ? reaction.ok : reaction.fail; - var resolve = reaction.resolve; - var reject = reaction.reject; - var domain = reaction.domain; - var result, then, exited; - try { - if (handler) { - if (!ok) { - if (promise._h == 2) onHandleUnhandled(promise); - promise._h = 1; - } - if (handler === true) result = value; - else { - if (domain) domain.enter(); - result = handler(value); // may throw - if (domain) { - domain.exit(); - exited = true; - } - } - if (result === reaction.promise) { - reject(TypeError('Promise-chain cycle')); - } else if (then = isThenable(result)) { - then.call(result, resolve, reject); - } else resolve(result); - } else reject(value); - } catch (e) { - if (domain && !exited) domain.exit(); - reject(e); - } - }; - while (chain.length > i) run(chain[i++]); // variable length - can't use forEach - promise._c = []; - promise._n = false; - if (isReject && !promise._h) onUnhandled(promise); - }); - }; - var onUnhandled = function (promise) { - task.call(global, function () { - var value = promise._v; - var unhandled = isUnhandled(promise); - var result, handler, console; - if (unhandled) { - result = perform(function () { - if (isNode) { - process.emit('unhandledRejection', value, promise); - } else if (handler = global.onunhandledrejection) { - handler({ promise: promise, reason: value }); - } else if ((console = global.console) && console.error) { - console.error('Unhandled promise rejection', value); - } - }); - // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should - promise._h = isNode || isUnhandled(promise) ? 2 : 1; - } promise._a = undefined; - if (unhandled && result.e) throw result.v; - }); - }; - var isUnhandled = function (promise) { - return promise._h !== 1 && (promise._a || promise._c).length === 0; - }; - var onHandleUnhandled = function (promise) { - task.call(global, function () { - var handler; - if (isNode) { - process.emit('rejectionHandled', promise); - } else if (handler = global.onrejectionhandled) { - handler({ promise: promise, reason: promise._v }); - } - }); - }; - var $reject = function (value) { - var promise = this; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - promise._v = value; - promise._s = 2; - if (!promise._a) promise._a = promise._c.slice(); - notify(promise, true); - }; - var $resolve = function (value) { - var promise = this; - var then; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - try { - if (promise === value) throw TypeError("Promise can't be resolved itself"); - if (then = isThenable(value)) { - microtask(function () { - var wrapper = { _w: promise, _d: false }; // wrap - try { - then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); - } catch (e) { - $reject.call(wrapper, e); - } - }); - } else { - promise._v = value; - promise._s = 1; - notify(promise, false); - } - } catch (e) { - $reject.call({ _w: promise, _d: false }, e); // wrap - } - }; - - // constructor polyfill - if (!USE_NATIVE) { - // 25.4.3.1 Promise(executor) - $Promise = function Promise(executor) { - anInstance(this, $Promise, PROMISE, '_h'); - aFunction(executor); - Internal.call(this); - try { - executor(ctx($resolve, this, 1), ctx($reject, this, 1)); - } catch (err) { - $reject.call(this, err); - } - }; - // eslint-disable-next-line no-unused-vars - Internal = function Promise(executor) { - this._c = []; // <- awaiting reactions - this._a = undefined; // <- checked in isUnhandled reactions - this._s = 0; // <- state - this._d = false; // <- done - this._v = undefined; // <- value - this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled - this._n = false; // <- notify - }; - Internal.prototype = __webpack_require__(220)($Promise.prototype, { - // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) - then: function then(onFulfilled, onRejected) { - var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); - reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; - reaction.fail = typeof onRejected == 'function' && onRejected; - reaction.domain = isNode ? process.domain : undefined; - this._c.push(reaction); - if (this._a) this._a.push(reaction); - if (this._s) notify(this, false); - return reaction.promise; - }, - // 25.4.5.1 Promise.prototype.catch(onRejected) - 'catch': function (onRejected) { - return this.then(undefined, onRejected); - } - }); - OwnPromiseCapability = function () { - var promise = new Internal(); - this.promise = promise; - this.resolve = ctx($resolve, promise, 1); - this.reject = ctx($reject, promise, 1); - }; - newPromiseCapabilityModule.f = newPromiseCapability = function (C) { - return C === $Promise || C === Wrapper - ? new OwnPromiseCapability(C) - : newGenericPromiseCapability(C); - }; - } - - $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); - __webpack_require__(26)($Promise, PROMISE); - __webpack_require__(194)(PROMISE); - Wrapper = __webpack_require__(9)[PROMISE]; - - // statics - $export($export.S + $export.F * !USE_NATIVE, PROMISE, { - // 25.4.4.5 Promise.reject(r) - reject: function reject(r) { - var capability = newPromiseCapability(this); - var $$reject = capability.reject; - $$reject(r); - return capability.promise; - } - }); - $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { - // 25.4.4.6 Promise.resolve(x) - resolve: function resolve(x) { - return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); - } - }); - $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(167)(function (iter) { - $Promise.all(iter)['catch'](empty); - })), PROMISE, { - // 25.4.4.1 Promise.all(iterable) - all: function all(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var resolve = capability.resolve; - var reject = capability.reject; - var result = perform(function () { - var values = []; - var index = 0; - var remaining = 1; - forOf(iterable, false, function (promise) { - var $index = index++; - var alreadyCalled = false; - values.push(undefined); - remaining++; - C.resolve(promise).then(function (value) { - if (alreadyCalled) return; - alreadyCalled = true; - values[$index] = value; - --remaining || resolve(values); - }, reject); - }); - --remaining || resolve(values); - }); - if (result.e) reject(result.v); - return capability.promise; - }, - // 25.4.4.4 Promise.race(iterable) - race: function race(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var reject = capability.reject; - var result = perform(function () { - forOf(iterable, false, function (promise) { - C.resolve(promise).then(capability.resolve, reject); - }); - }); - if (result.e) reject(result.v); - return capability.promise; - } - }); - - -/***/ }), -/* 212 */ -/***/ (function(module, exports) { - - module.exports = function (it, Constructor, name, forbiddenField) { - if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { - throw TypeError(name + ': incorrect invocation!'); - } return it; - }; - - -/***/ }), -/* 213 */ -/***/ (function(module, exports, __webpack_require__) { - - var ctx = __webpack_require__(23); - var call = __webpack_require__(163); - var isArrayIter = __webpack_require__(164); - var anObject = __webpack_require__(12); - var toLength = __webpack_require__(38); - var getIterFn = __webpack_require__(166); - var BREAK = {}; - var RETURN = {}; - var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { - var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); - var f = ctx(fn, that, entries ? 2 : 1); - var index = 0; - var length, step, iterator, result; - if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); - // fast case for arrays with default iterator - if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { - result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); - if (result === BREAK || result === RETURN) return result; - } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { - result = call(iterator, f, step.value, entries); - if (result === BREAK || result === RETURN) return result; - } - }; - exports.BREAK = BREAK; - exports.RETURN = RETURN; - - -/***/ }), -/* 214 */ -/***/ (function(module, exports, __webpack_require__) { - - var ctx = __webpack_require__(23); - var invoke = __webpack_require__(78); - var html = __webpack_require__(49); - var cel = __webpack_require__(15); - var global = __webpack_require__(4); - var process = global.process; - var setTask = global.setImmediate; - var clearTask = global.clearImmediate; - var MessageChannel = global.MessageChannel; - var Dispatch = global.Dispatch; - var counter = 0; - var queue = {}; - var ONREADYSTATECHANGE = 'onreadystatechange'; - var defer, channel, port; - var run = function () { - var id = +this; - // eslint-disable-next-line no-prototype-builtins - if (queue.hasOwnProperty(id)) { - var fn = queue[id]; - delete queue[id]; - fn(); - } - }; - var listener = function (event) { - run.call(event.data); - }; - // Node.js 0.9+ & IE10+ has setImmediate, otherwise: - if (!setTask || !clearTask) { - setTask = function setImmediate(fn) { - var args = []; - var i = 1; - while (arguments.length > i) args.push(arguments[i++]); - queue[++counter] = function () { - // eslint-disable-next-line no-new-func - invoke(typeof fn == 'function' ? fn : Function(fn), args); - }; - defer(counter); - return counter; - }; - clearTask = function clearImmediate(id) { - delete queue[id]; - }; - // Node.js 0.8- - if (__webpack_require__(35)(process) == 'process') { - defer = function (id) { - process.nextTick(ctx(run, id, 1)); - }; - // Sphere (JS game engine) Dispatch API - } else if (Dispatch && Dispatch.now) { - defer = function (id) { - Dispatch.now(ctx(run, id, 1)); - }; - // Browsers with MessageChannel, includes WebWorkers - } else if (MessageChannel) { - channel = new MessageChannel(); - port = channel.port2; - channel.port1.onmessage = listener; - defer = ctx(port.postMessage, port, 1); - // Browsers with postMessage, skip WebWorkers - // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' - } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { - defer = function (id) { - global.postMessage(id + '', '*'); - }; - global.addEventListener('message', listener, false); - // IE8- - } else if (ONREADYSTATECHANGE in cel('script')) { - defer = function (id) { - html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { - html.removeChild(this); - run.call(id); - }; - }; - // Rest old browsers - } else { - defer = function (id) { - setTimeout(ctx(run, id, 1), 0); - }; - } - } - module.exports = { - set: setTask, - clear: clearTask - }; - - -/***/ }), -/* 215 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var macrotask = __webpack_require__(214).set; - var Observer = global.MutationObserver || global.WebKitMutationObserver; - var process = global.process; - var Promise = global.Promise; - var isNode = __webpack_require__(35)(process) == 'process'; - - module.exports = function () { - var head, last, notify; - - var flush = function () { - var parent, fn; - if (isNode && (parent = process.domain)) parent.exit(); - while (head) { - fn = head.fn; - head = head.next; - try { - fn(); - } catch (e) { - if (head) notify(); - else last = undefined; - throw e; - } - } last = undefined; - if (parent) parent.enter(); - }; - - // Node.js - if (isNode) { - notify = function () { - process.nextTick(flush); - }; - // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 - } else if (Observer && !(global.navigator && global.navigator.standalone)) { - var toggle = true; - var node = document.createTextNode(''); - new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new - notify = function () { - node.data = toggle = !toggle; - }; - // environments with maybe non-completely correct, but existent Promise - } else if (Promise && Promise.resolve) { - // Promise.resolve without an argument throws an error in LG WebOS 2 - var promise = Promise.resolve(undefined); - notify = function () { - promise.then(flush); - }; - // for other environments - macrotask based on: - // - setImmediate - // - MessageChannel - // - window.postMessag - // - onreadystatechange - // - setTimeout - } else { - notify = function () { - // strange IE + webpack dev server bug - use .call(global) - macrotask.call(global, flush); - }; - } - - return function (fn) { - var task = { fn: fn, next: undefined }; - if (last) last.next = task; - if (!head) { - head = task; - notify(); - } last = task; - }; - }; - - -/***/ }), -/* 216 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 25.4.1.5 NewPromiseCapability(C) - var aFunction = __webpack_require__(24); - - function PromiseCapability(C) { - var resolve, reject; - this.promise = new C(function ($$resolve, $$reject) { - if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); - resolve = $$resolve; - reject = $$reject; - }); - this.resolve = aFunction(resolve); - this.reject = aFunction(reject); - } - - module.exports.f = function (C) { - return new PromiseCapability(C); - }; - - -/***/ }), -/* 217 */ -/***/ (function(module, exports) { - - module.exports = function (exec) { - try { - return { e: false, v: exec() }; - } catch (e) { - return { e: true, v: e }; - } - }; - - -/***/ }), -/* 218 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var navigator = global.navigator; - - module.exports = navigator && navigator.userAgent || ''; - - -/***/ }), -/* 219 */ -/***/ (function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var newPromiseCapability = __webpack_require__(216); - - module.exports = function (C, x) { - anObject(C); - if (isObject(x) && x.constructor === C) return x; - var promiseCapability = newPromiseCapability.f(C); - var resolve = promiseCapability.resolve; - resolve(x); - return promiseCapability.promise; - }; - - -/***/ }), -/* 220 */ -/***/ (function(module, exports, __webpack_require__) { - - var redefine = __webpack_require__(18); - module.exports = function (target, src, safe) { - for (var key in src) redefine(target, key, src[key], safe); - return target; - }; - - -/***/ }), -/* 221 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var strong = __webpack_require__(222); - var validate = __webpack_require__(223); - var MAP = 'Map'; - - // 23.1 Map Objects - module.exports = __webpack_require__(224)(MAP, function (get) { - return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.1.3.6 Map.prototype.get(key) - get: function get(key) { - var entry = strong.getEntry(validate(this, MAP), key); - return entry && entry.v; - }, - // 23.1.3.9 Map.prototype.set(key, value) - set: function set(key, value) { - return strong.def(validate(this, MAP), key === 0 ? 0 : key, value); - } - }, strong, true); - - -/***/ }), -/* 222 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var dP = __webpack_require__(11).f; - var create = __webpack_require__(47); - var redefineAll = __webpack_require__(220); - var ctx = __webpack_require__(23); - var anInstance = __webpack_require__(212); - var forOf = __webpack_require__(213); - var $iterDefine = __webpack_require__(129); - var step = __webpack_require__(196); - var setSpecies = __webpack_require__(194); - var DESCRIPTORS = __webpack_require__(6); - var fastKey = __webpack_require__(25).fastKey; - var validate = __webpack_require__(223); - var SIZE = DESCRIPTORS ? '_s' : 'size'; - - var getEntry = function (that, key) { - // fast case - var index = fastKey(key); - var entry; - if (index !== 'F') return that._i[index]; - // frozen object case - for (entry = that._f; entry; entry = entry.n) { - if (entry.k == key) return entry; - } - }; - - module.exports = { - getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { - var C = wrapper(function (that, iterable) { - anInstance(that, C, NAME, '_i'); - that._t = NAME; // collection type - that._i = create(null); // index - that._f = undefined; // first entry - that._l = undefined; // last entry - that[SIZE] = 0; // size - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - }); - redefineAll(C.prototype, { - // 23.1.3.1 Map.prototype.clear() - // 23.2.3.2 Set.prototype.clear() - clear: function clear() { - for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) { - entry.r = true; - if (entry.p) entry.p = entry.p.n = undefined; - delete data[entry.i]; - } - that._f = that._l = undefined; - that[SIZE] = 0; - }, - // 23.1.3.3 Map.prototype.delete(key) - // 23.2.3.4 Set.prototype.delete(value) - 'delete': function (key) { - var that = validate(this, NAME); - var entry = getEntry(that, key); - if (entry) { - var next = entry.n; - var prev = entry.p; - delete that._i[entry.i]; - entry.r = true; - if (prev) prev.n = next; - if (next) next.p = prev; - if (that._f == entry) that._f = next; - if (that._l == entry) that._l = prev; - that[SIZE]--; - } return !!entry; - }, - // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) - // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) - forEach: function forEach(callbackfn /* , that = undefined */) { - validate(this, NAME); - var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); - var entry; - while (entry = entry ? entry.n : this._f) { - f(entry.v, entry.k, this); - // revert to the last existing entry - while (entry && entry.r) entry = entry.p; - } - }, - // 23.1.3.7 Map.prototype.has(key) - // 23.2.3.7 Set.prototype.has(value) - has: function has(key) { - return !!getEntry(validate(this, NAME), key); - } - }); - if (DESCRIPTORS) dP(C.prototype, 'size', { - get: function () { - return validate(this, NAME)[SIZE]; - } - }); - return C; - }, - def: function (that, key, value) { - var entry = getEntry(that, key); - var prev, index; - // change existing entry - if (entry) { - entry.v = value; - // create new entry - } else { - that._l = entry = { - i: index = fastKey(key, true), // <- index - k: key, // <- key - v: value, // <- value - p: prev = that._l, // <- previous entry - n: undefined, // <- next entry - r: false // <- removed - }; - if (!that._f) that._f = entry; - if (prev) prev.n = entry; - that[SIZE]++; - // add to index - if (index !== 'F') that._i[index] = entry; - } return that; - }, - getEntry: getEntry, - setStrong: function (C, NAME, IS_MAP) { - // add .keys, .values, .entries, [@@iterator] - // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 - $iterDefine(C, NAME, function (iterated, kind) { - this._t = validate(iterated, NAME); // target - this._k = kind; // kind - this._l = undefined; // previous - }, function () { - var that = this; - var kind = that._k; - var entry = that._l; - // revert to the last existing entry - while (entry && entry.r) entry = entry.p; - // get next entry - if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) { - // or finish the iteration - that._t = undefined; - return step(1); - } - // return step by kind - if (kind == 'keys') return step(0, entry.k); - if (kind == 'values') return step(0, entry.v); - return step(0, [entry.k, entry.v]); - }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); - - // add [@@species], 23.1.2.2, 23.2.2.2 - setSpecies(NAME); - } - }; - - -/***/ }), -/* 223 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - module.exports = function (it, TYPE) { - if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); - return it; - }; - - -/***/ }), -/* 224 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var redefineAll = __webpack_require__(220); - var meta = __webpack_require__(25); - var forOf = __webpack_require__(213); - var anInstance = __webpack_require__(212); - var isObject = __webpack_require__(13); - var fails = __webpack_require__(7); - var $iterDetect = __webpack_require__(167); - var setToStringTag = __webpack_require__(26); - var inheritIfRequired = __webpack_require__(88); - - module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { - var Base = global[NAME]; - var C = Base; - var ADDER = IS_MAP ? 'set' : 'add'; - var proto = C && C.prototype; - var O = {}; - var fixMethod = function (KEY) { - var fn = proto[KEY]; - redefine(proto, KEY, - KEY == 'delete' ? function (a) { - return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'has' ? function has(a) { - return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'get' ? function get(a) { - return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; } - : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; } - ); - }; - if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () { - new C().entries().next(); - }))) { - // create collection constructor - C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); - redefineAll(C.prototype, methods); - meta.NEED = true; - } else { - var instance = new C(); - // early implementations not supports chaining - var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; - // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false - var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); - // most early implementations doesn't supports iterables, most modern - not close it correctly - var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new - // for early implementations -0 and +0 not the same - var BUGGY_ZERO = !IS_WEAK && fails(function () { - // V8 ~ Chromium 42- fails only with 5+ elements - var $instance = new C(); - var index = 5; - while (index--) $instance[ADDER](index, index); - return !$instance.has(-0); - }); - if (!ACCEPT_ITERABLES) { - C = wrapper(function (target, iterable) { - anInstance(target, C, NAME); - var that = inheritIfRequired(new Base(), target, C); - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - return that; - }); - C.prototype = proto; - proto.constructor = C; - } - if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { - fixMethod('delete'); - fixMethod('has'); - IS_MAP && fixMethod('get'); - } - if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); - // weak collections should not contains .clear method - if (IS_WEAK && proto.clear) delete proto.clear; - } - - setToStringTag(C, NAME); - - O[NAME] = C; - $export($export.G + $export.W + $export.F * (C != Base), O); - - if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP); - - return C; - }; - - -/***/ }), -/* 225 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var strong = __webpack_require__(222); - var validate = __webpack_require__(223); - var SET = 'Set'; - - // 23.2 Set Objects - module.exports = __webpack_require__(224)(SET, function (get) { - return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.2.3.1 Set.prototype.add(value) - add: function add(value) { - return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value); - } - }, strong); - - -/***/ }), -/* 226 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var each = __webpack_require__(174)(0); - var redefine = __webpack_require__(18); - var meta = __webpack_require__(25); - var assign = __webpack_require__(69); - var weak = __webpack_require__(227); - var isObject = __webpack_require__(13); - var validate = __webpack_require__(223); - var NATIVE_WEAK_MAP = __webpack_require__(223); - var IS_IE11 = !global.ActiveXObject && 'ActiveXObject' in global; - var WEAK_MAP = 'WeakMap'; - var getWeak = meta.getWeak; - var isExtensible = Object.isExtensible; - var uncaughtFrozenStore = weak.ufstore; - var InternalMap; - - var wrapper = function (get) { - return function WeakMap() { - return get(this, arguments.length > 0 ? arguments[0] : undefined); - }; - }; - - var methods = { - // 23.3.3.3 WeakMap.prototype.get(key) - get: function get(key) { - if (isObject(key)) { - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key); - return data ? data[this._i] : undefined; - } - }, - // 23.3.3.5 WeakMap.prototype.set(key, value) - set: function set(key, value) { - return weak.def(validate(this, WEAK_MAP), key, value); - } - }; - - // 23.3 WeakMap Objects - var $WeakMap = module.exports = __webpack_require__(224)(WEAK_MAP, wrapper, methods, weak, true, true); - - // IE11 WeakMap frozen keys fix - if (NATIVE_WEAK_MAP && IS_IE11) { - InternalMap = weak.getConstructor(wrapper, WEAK_MAP); - assign(InternalMap.prototype, methods); - meta.NEED = true; - each(['delete', 'has', 'get', 'set'], function (key) { - var proto = $WeakMap.prototype; - var method = proto[key]; - redefine(proto, key, function (a, b) { - // store frozen objects on internal weakmap shim - if (isObject(a) && !isExtensible(a)) { - if (!this._f) this._f = new InternalMap(); - var result = this._f[key](a, b); - return key == 'set' ? this : result; - // store all the rest on native weakmap - } return method.call(this, a, b); - }); - }); - } - - -/***/ }), -/* 227 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var redefineAll = __webpack_require__(220); - var getWeak = __webpack_require__(25).getWeak; - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var anInstance = __webpack_require__(212); - var forOf = __webpack_require__(213); - var createArrayMethod = __webpack_require__(174); - var $has = __webpack_require__(5); - var validate = __webpack_require__(223); - var arrayFind = createArrayMethod(5); - var arrayFindIndex = createArrayMethod(6); - var id = 0; - - // fallback for uncaught frozen keys - var uncaughtFrozenStore = function (that) { - return that._l || (that._l = new UncaughtFrozenStore()); - }; - var UncaughtFrozenStore = function () { - this.a = []; - }; - var findUncaughtFrozen = function (store, key) { - return arrayFind(store.a, function (it) { - return it[0] === key; - }); - }; - UncaughtFrozenStore.prototype = { - get: function (key) { - var entry = findUncaughtFrozen(this, key); - if (entry) return entry[1]; - }, - has: function (key) { - return !!findUncaughtFrozen(this, key); - }, - set: function (key, value) { - var entry = findUncaughtFrozen(this, key); - if (entry) entry[1] = value; - else this.a.push([key, value]); - }, - 'delete': function (key) { - var index = arrayFindIndex(this.a, function (it) { - return it[0] === key; - }); - if (~index) this.a.splice(index, 1); - return !!~index; - } - }; - - module.exports = { - getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { - var C = wrapper(function (that, iterable) { - anInstance(that, C, NAME, '_i'); - that._t = NAME; // collection type - that._i = id++; // collection id - that._l = undefined; // leak store for uncaught frozen objects - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - }); - redefineAll(C.prototype, { - // 23.3.3.2 WeakMap.prototype.delete(key) - // 23.4.3.3 WeakSet.prototype.delete(value) - 'delete': function (key) { - if (!isObject(key)) return false; - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key); - return data && $has(data, this._i) && delete data[this._i]; - }, - // 23.3.3.4 WeakMap.prototype.has(key) - // 23.4.3.4 WeakSet.prototype.has(value) - has: function has(key) { - if (!isObject(key)) return false; - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key); - return data && $has(data, this._i); - } - }); - return C; - }, - def: function (that, key, value) { - var data = getWeak(anObject(key), true); - if (data === true) uncaughtFrozenStore(that).set(key, value); - else data[that._i] = value; - return that; - }, - ufstore: uncaughtFrozenStore - }; - - -/***/ }), -/* 228 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var weak = __webpack_require__(227); - var validate = __webpack_require__(223); - var WEAK_SET = 'WeakSet'; - - // 23.4 WeakSet Objects - __webpack_require__(224)(WEAK_SET, function (get) { - return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.4.3.1 WeakSet.prototype.add(value) - add: function add(value) { - return weak.def(validate(this, WEAK_SET), value, true); - } - }, weak, false, true); - - -/***/ }), -/* 229 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $typed = __webpack_require__(230); - var buffer = __webpack_require__(231); - var anObject = __webpack_require__(12); - var toAbsoluteIndex = __webpack_require__(40); - var toLength = __webpack_require__(38); - var isObject = __webpack_require__(13); - var ArrayBuffer = __webpack_require__(4).ArrayBuffer; - var speciesConstructor = __webpack_require__(210); - var $ArrayBuffer = buffer.ArrayBuffer; - var $DataView = buffer.DataView; - var $isView = $typed.ABV && ArrayBuffer.isView; - var $slice = $ArrayBuffer.prototype.slice; - var VIEW = $typed.VIEW; - var ARRAY_BUFFER = 'ArrayBuffer'; - - $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer }); - - $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { - // 24.1.3.1 ArrayBuffer.isView(arg) - isView: function isView(it) { - return $isView && $isView(it) || isObject(it) && VIEW in it; - } - }); - - $export($export.P + $export.U + $export.F * __webpack_require__(7)(function () { - return !new $ArrayBuffer(2).slice(1, undefined).byteLength; - }), ARRAY_BUFFER, { - // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) - slice: function slice(start, end) { - if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix - var len = anObject(this).byteLength; - var first = toAbsoluteIndex(start, len); - var fin = toAbsoluteIndex(end === undefined ? len : end, len); - var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(fin - first)); - var viewS = new $DataView(this); - var viewT = new $DataView(result); - var index = 0; - while (first < fin) { - viewT.setUint8(index++, viewS.getUint8(first++)); - } return result; - } - }); - - __webpack_require__(194)(ARRAY_BUFFER); - - -/***/ }), -/* 230 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var uid = __webpack_require__(19); - var TYPED = uid('typed_array'); - var VIEW = uid('view'); - var ABV = !!(global.ArrayBuffer && global.DataView); - var CONSTR = ABV; - var i = 0; - var l = 9; - var Typed; - - var TypedArrayConstructors = ( - 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' - ).split(','); - - while (i < l) { - if (Typed = global[TypedArrayConstructors[i++]]) { - hide(Typed.prototype, TYPED, true); - hide(Typed.prototype, VIEW, true); - } else CONSTR = false; - } - - module.exports = { - ABV: ABV, - CONSTR: CONSTR, - TYPED: TYPED, - VIEW: VIEW - }; - - -/***/ }), -/* 231 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var DESCRIPTORS = __webpack_require__(6); - var LIBRARY = __webpack_require__(22); - var $typed = __webpack_require__(230); - var hide = __webpack_require__(10); - var redefineAll = __webpack_require__(220); - var fails = __webpack_require__(7); - var anInstance = __webpack_require__(212); - var toInteger = __webpack_require__(39); - var toLength = __webpack_require__(38); - var toIndex = __webpack_require__(232); - var gOPN = __webpack_require__(51).f; - var dP = __webpack_require__(11).f; - var arrayFill = __webpack_require__(190); - var setToStringTag = __webpack_require__(26); - var ARRAY_BUFFER = 'ArrayBuffer'; - var DATA_VIEW = 'DataView'; - var PROTOTYPE = 'prototype'; - var WRONG_LENGTH = 'Wrong length!'; - var WRONG_INDEX = 'Wrong index!'; - var $ArrayBuffer = global[ARRAY_BUFFER]; - var $DataView = global[DATA_VIEW]; - var Math = global.Math; - var RangeError = global.RangeError; - // eslint-disable-next-line no-shadow-restricted-names - var Infinity = global.Infinity; - var BaseBuffer = $ArrayBuffer; - var abs = Math.abs; - var pow = Math.pow; - var floor = Math.floor; - var log = Math.log; - var LN2 = Math.LN2; - var BUFFER = 'buffer'; - var BYTE_LENGTH = 'byteLength'; - var BYTE_OFFSET = 'byteOffset'; - var $BUFFER = DESCRIPTORS ? '_b' : BUFFER; - var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH; - var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; - - // IEEE754 conversions based on https://github.com/feross/ieee754 - function packIEEE754(value, mLen, nBytes) { - var buffer = new Array(nBytes); - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0; - var i = 0; - var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - var e, m, c; - value = abs(value); - // eslint-disable-next-line no-self-compare - if (value != value || value === Infinity) { - // eslint-disable-next-line no-self-compare - m = value != value ? 1 : 0; - e = eMax; - } else { - e = floor(log(value) / LN2); - if (value * (c = pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * pow(2, mLen); - e = e + eBias; - } else { - m = value * pow(2, eBias - 1) * pow(2, mLen); - e = 0; - } - } - for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); - e = e << mLen | m; - eLen += mLen; - for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); - buffer[--i] |= s * 128; - return buffer; - } - function unpackIEEE754(buffer, mLen, nBytes) { - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = eLen - 7; - var i = nBytes - 1; - var s = buffer[i--]; - var e = s & 127; - var m; - s >>= 7; - for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : s ? -Infinity : Infinity; - } else { - m = m + pow(2, mLen); - e = e - eBias; - } return (s ? -1 : 1) * m * pow(2, e - mLen); - } - - function unpackI32(bytes) { - return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; - } - function packI8(it) { - return [it & 0xff]; - } - function packI16(it) { - return [it & 0xff, it >> 8 & 0xff]; - } - function packI32(it) { - return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; - } - function packF64(it) { - return packIEEE754(it, 52, 8); - } - function packF32(it) { - return packIEEE754(it, 23, 4); - } - - function addGetter(C, key, internal) { - dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } }); - } - - function get(view, bytes, index, isLittleEndian) { - var numIndex = +index; - var intIndex = toIndex(numIndex); - if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); - var store = view[$BUFFER]._b; - var start = intIndex + view[$OFFSET]; - var pack = store.slice(start, start + bytes); - return isLittleEndian ? pack : pack.reverse(); - } - function set(view, bytes, index, conversion, value, isLittleEndian) { - var numIndex = +index; - var intIndex = toIndex(numIndex); - if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); - var store = view[$BUFFER]._b; - var start = intIndex + view[$OFFSET]; - var pack = conversion(+value); - for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; - } - - if (!$typed.ABV) { - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, $ArrayBuffer, ARRAY_BUFFER); - var byteLength = toIndex(length); - this._b = arrayFill.call(new Array(byteLength), 0); - this[$LENGTH] = byteLength; - }; - - $DataView = function DataView(buffer, byteOffset, byteLength) { - anInstance(this, $DataView, DATA_VIEW); - anInstance(buffer, $ArrayBuffer, DATA_VIEW); - var bufferLength = buffer[$LENGTH]; - var offset = toInteger(byteOffset); - if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!'); - byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); - if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH); - this[$BUFFER] = buffer; - this[$OFFSET] = offset; - this[$LENGTH] = byteLength; - }; - - if (DESCRIPTORS) { - addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); - addGetter($DataView, BUFFER, '_b'); - addGetter($DataView, BYTE_LENGTH, '_l'); - addGetter($DataView, BYTE_OFFSET, '_o'); - } - - redefineAll($DataView[PROTOTYPE], { - getInt8: function getInt8(byteOffset) { - return get(this, 1, byteOffset)[0] << 24 >> 24; - }, - getUint8: function getUint8(byteOffset) { - return get(this, 1, byteOffset)[0]; - }, - getInt16: function getInt16(byteOffset /* , littleEndian */) { - var bytes = get(this, 2, byteOffset, arguments[1]); - return (bytes[1] << 8 | bytes[0]) << 16 >> 16; - }, - getUint16: function getUint16(byteOffset /* , littleEndian */) { - var bytes = get(this, 2, byteOffset, arguments[1]); - return bytes[1] << 8 | bytes[0]; - }, - getInt32: function getInt32(byteOffset /* , littleEndian */) { - return unpackI32(get(this, 4, byteOffset, arguments[1])); - }, - getUint32: function getUint32(byteOffset /* , littleEndian */) { - return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; - }, - getFloat32: function getFloat32(byteOffset /* , littleEndian */) { - return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); - }, - getFloat64: function getFloat64(byteOffset /* , littleEndian */) { - return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); - }, - setInt8: function setInt8(byteOffset, value) { - set(this, 1, byteOffset, packI8, value); - }, - setUint8: function setUint8(byteOffset, value) { - set(this, 1, byteOffset, packI8, value); - }, - setInt16: function setInt16(byteOffset, value /* , littleEndian */) { - set(this, 2, byteOffset, packI16, value, arguments[2]); - }, - setUint16: function setUint16(byteOffset, value /* , littleEndian */) { - set(this, 2, byteOffset, packI16, value, arguments[2]); - }, - setInt32: function setInt32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packI32, value, arguments[2]); - }, - setUint32: function setUint32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packI32, value, arguments[2]); - }, - setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packF32, value, arguments[2]); - }, - setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { - set(this, 8, byteOffset, packF64, value, arguments[2]); - } - }); - } else { - if (!fails(function () { - $ArrayBuffer(1); - }) || !fails(function () { - new $ArrayBuffer(-1); // eslint-disable-line no-new - }) || fails(function () { - new $ArrayBuffer(); // eslint-disable-line no-new - new $ArrayBuffer(1.5); // eslint-disable-line no-new - new $ArrayBuffer(NaN); // eslint-disable-line no-new - return $ArrayBuffer.name != ARRAY_BUFFER; - })) { - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, $ArrayBuffer); - return new BaseBuffer(toIndex(length)); - }; - var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; - for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) { - if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]); - } - if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer; - } - // iOS Safari 7.x bug - var view = new $DataView(new $ArrayBuffer(2)); - var $setInt8 = $DataView[PROTOTYPE].setInt8; - view.setInt8(0, 2147483648); - view.setInt8(1, 2147483649); - if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], { - setInt8: function setInt8(byteOffset, value) { - $setInt8.call(this, byteOffset, value << 24 >> 24); - }, - setUint8: function setUint8(byteOffset, value) { - $setInt8.call(this, byteOffset, value << 24 >> 24); - } - }, true); - } - setToStringTag($ArrayBuffer, ARRAY_BUFFER); - setToStringTag($DataView, DATA_VIEW); - hide($DataView[PROTOTYPE], $typed.VIEW, true); - exports[ARRAY_BUFFER] = $ArrayBuffer; - exports[DATA_VIEW] = $DataView; - - -/***/ }), -/* 232 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/ecma262/#sec-toindex - var toInteger = __webpack_require__(39); - var toLength = __webpack_require__(38); - module.exports = function (it) { - if (it === undefined) return 0; - var number = toInteger(it); - var length = toLength(number); - if (number !== length) throw RangeError('Wrong length!'); - return length; - }; - - -/***/ }), -/* 233 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - $export($export.G + $export.W + $export.F * !__webpack_require__(230).ABV, { - DataView: __webpack_require__(231).DataView - }); - - -/***/ }), -/* 234 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Int8', 1, function (init) { - return function Int8Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 235 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - if (__webpack_require__(6)) { - var LIBRARY = __webpack_require__(22); - var global = __webpack_require__(4); - var fails = __webpack_require__(7); - var $export = __webpack_require__(8); - var $typed = __webpack_require__(230); - var $buffer = __webpack_require__(231); - var ctx = __webpack_require__(23); - var anInstance = __webpack_require__(212); - var propertyDesc = __webpack_require__(17); - var hide = __webpack_require__(10); - var redefineAll = __webpack_require__(220); - var toInteger = __webpack_require__(39); - var toLength = __webpack_require__(38); - var toIndex = __webpack_require__(232); - var toAbsoluteIndex = __webpack_require__(40); - var toPrimitive = __webpack_require__(16); - var has = __webpack_require__(5); - var classof = __webpack_require__(75); - var isObject = __webpack_require__(13); - var toObject = __webpack_require__(46); - var isArrayIter = __webpack_require__(164); - var create = __webpack_require__(47); - var getPrototypeOf = __webpack_require__(59); - var gOPN = __webpack_require__(51).f; - var getIterFn = __webpack_require__(166); - var uid = __webpack_require__(19); - var wks = __webpack_require__(27); - var createArrayMethod = __webpack_require__(174); - var createArrayIncludes = __webpack_require__(37); - var speciesConstructor = __webpack_require__(210); - var ArrayIterators = __webpack_require__(195); - var Iterators = __webpack_require__(130); - var $iterDetect = __webpack_require__(167); - var setSpecies = __webpack_require__(194); - var arrayFill = __webpack_require__(190); - var arrayCopyWithin = __webpack_require__(187); - var $DP = __webpack_require__(11); - var $GOPD = __webpack_require__(52); - var dP = $DP.f; - var gOPD = $GOPD.f; - var RangeError = global.RangeError; - var TypeError = global.TypeError; - var Uint8Array = global.Uint8Array; - var ARRAY_BUFFER = 'ArrayBuffer'; - var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER; - var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; - var PROTOTYPE = 'prototype'; - var ArrayProto = Array[PROTOTYPE]; - var $ArrayBuffer = $buffer.ArrayBuffer; - var $DataView = $buffer.DataView; - var arrayForEach = createArrayMethod(0); - var arrayFilter = createArrayMethod(2); - var arraySome = createArrayMethod(3); - var arrayEvery = createArrayMethod(4); - var arrayFind = createArrayMethod(5); - var arrayFindIndex = createArrayMethod(6); - var arrayIncludes = createArrayIncludes(true); - var arrayIndexOf = createArrayIncludes(false); - var arrayValues = ArrayIterators.values; - var arrayKeys = ArrayIterators.keys; - var arrayEntries = ArrayIterators.entries; - var arrayLastIndexOf = ArrayProto.lastIndexOf; - var arrayReduce = ArrayProto.reduce; - var arrayReduceRight = ArrayProto.reduceRight; - var arrayJoin = ArrayProto.join; - var arraySort = ArrayProto.sort; - var arraySlice = ArrayProto.slice; - var arrayToString = ArrayProto.toString; - var arrayToLocaleString = ArrayProto.toLocaleString; - var ITERATOR = wks('iterator'); - var TAG = wks('toStringTag'); - var TYPED_CONSTRUCTOR = uid('typed_constructor'); - var DEF_CONSTRUCTOR = uid('def_constructor'); - var ALL_CONSTRUCTORS = $typed.CONSTR; - var TYPED_ARRAY = $typed.TYPED; - var VIEW = $typed.VIEW; - var WRONG_LENGTH = 'Wrong length!'; - - var $map = createArrayMethod(1, function (O, length) { - return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); - }); - - var LITTLE_ENDIAN = fails(function () { - // eslint-disable-next-line no-undef - return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; - }); - - var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () { - new Uint8Array(1).set({}); - }); - - var toOffset = function (it, BYTES) { - var offset = toInteger(it); - if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!'); - return offset; - }; - - var validate = function (it) { - if (isObject(it) && TYPED_ARRAY in it) return it; - throw TypeError(it + ' is not a typed array!'); - }; - - var allocate = function (C, length) { - if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) { - throw TypeError('It is not a typed array constructor!'); - } return new C(length); - }; - - var speciesFromList = function (O, list) { - return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); - }; - - var fromList = function (C, list) { - var index = 0; - var length = list.length; - var result = allocate(C, length); - while (length > index) result[index] = list[index++]; - return result; - }; - - var addGetter = function (it, key, internal) { - dP(it, key, { get: function () { return this._d[internal]; } }); - }; - - var $from = function from(source /* , mapfn, thisArg */) { - var O = toObject(source); - var aLen = arguments.length; - var mapfn = aLen > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var iterFn = getIterFn(O); - var i, length, values, result, step, iterator; - if (iterFn != undefined && !isArrayIter(iterFn)) { - for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) { - values.push(step.value); - } O = values; - } - if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2); - for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) { - result[i] = mapping ? mapfn(O[i], i) : O[i]; - } - return result; - }; - - var $of = function of(/* ...items */) { - var index = 0; - var length = arguments.length; - var result = allocate(this, length); - while (length > index) result[index] = arguments[index++]; - return result; - }; - - // iOS Safari 6.x fails here - var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); }); - - var $toLocaleString = function toLocaleString() { - return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); - }; - - var proto = { - copyWithin: function copyWithin(target, start /* , end */) { - return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); - }, - every: function every(callbackfn /* , thisArg */) { - return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars - return arrayFill.apply(validate(this), arguments); - }, - filter: function filter(callbackfn /* , thisArg */) { - return speciesFromList(this, arrayFilter(validate(this), callbackfn, - arguments.length > 1 ? arguments[1] : undefined)); - }, - find: function find(predicate /* , thisArg */) { - return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - findIndex: function findIndex(predicate /* , thisArg */) { - return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - forEach: function forEach(callbackfn /* , thisArg */) { - arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - indexOf: function indexOf(searchElement /* , fromIndex */) { - return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - includes: function includes(searchElement /* , fromIndex */) { - return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - join: function join(separator) { // eslint-disable-line no-unused-vars - return arrayJoin.apply(validate(this), arguments); - }, - lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars - return arrayLastIndexOf.apply(validate(this), arguments); - }, - map: function map(mapfn /* , thisArg */) { - return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); - }, - reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars - return arrayReduce.apply(validate(this), arguments); - }, - reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars - return arrayReduceRight.apply(validate(this), arguments); - }, - reverse: function reverse() { - var that = this; - var length = validate(that).length; - var middle = Math.floor(length / 2); - var index = 0; - var value; - while (index < middle) { - value = that[index]; - that[index++] = that[--length]; - that[length] = value; - } return that; - }, - some: function some(callbackfn /* , thisArg */) { - return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - sort: function sort(comparefn) { - return arraySort.call(validate(this), comparefn); - }, - subarray: function subarray(begin, end) { - var O = validate(this); - var length = O.length; - var $begin = toAbsoluteIndex(begin, length); - return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( - O.buffer, - O.byteOffset + $begin * O.BYTES_PER_ELEMENT, - toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin) - ); - } - }; - - var $slice = function slice(start, end) { - return speciesFromList(this, arraySlice.call(validate(this), start, end)); - }; - - var $set = function set(arrayLike /* , offset */) { - validate(this); - var offset = toOffset(arguments[1], 1); - var length = this.length; - var src = toObject(arrayLike); - var len = toLength(src.length); - var index = 0; - if (len + offset > length) throw RangeError(WRONG_LENGTH); - while (index < len) this[offset + index] = src[index++]; - }; - - var $iterators = { - entries: function entries() { - return arrayEntries.call(validate(this)); - }, - keys: function keys() { - return arrayKeys.call(validate(this)); - }, - values: function values() { - return arrayValues.call(validate(this)); - } - }; - - var isTAIndex = function (target, key) { - return isObject(target) - && target[TYPED_ARRAY] - && typeof key != 'symbol' - && key in target - && String(+key) == String(key); - }; - var $getDesc = function getOwnPropertyDescriptor(target, key) { - return isTAIndex(target, key = toPrimitive(key, true)) - ? propertyDesc(2, target[key]) - : gOPD(target, key); - }; - var $setDesc = function defineProperty(target, key, desc) { - if (isTAIndex(target, key = toPrimitive(key, true)) - && isObject(desc) - && has(desc, 'value') - && !has(desc, 'get') - && !has(desc, 'set') - // TODO: add validation descriptor w/o calling accessors - && !desc.configurable - && (!has(desc, 'writable') || desc.writable) - && (!has(desc, 'enumerable') || desc.enumerable) - ) { - target[key] = desc.value; - return target; - } return dP(target, key, desc); - }; - - if (!ALL_CONSTRUCTORS) { - $GOPD.f = $getDesc; - $DP.f = $setDesc; - } - - $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { - getOwnPropertyDescriptor: $getDesc, - defineProperty: $setDesc - }); - - if (fails(function () { arrayToString.call({}); })) { - arrayToString = arrayToLocaleString = function toString() { - return arrayJoin.call(this); - }; - } - - var $TypedArrayPrototype$ = redefineAll({}, proto); - redefineAll($TypedArrayPrototype$, $iterators); - hide($TypedArrayPrototype$, ITERATOR, $iterators.values); - redefineAll($TypedArrayPrototype$, { - slice: $slice, - set: $set, - constructor: function () { /* noop */ }, - toString: arrayToString, - toLocaleString: $toLocaleString - }); - addGetter($TypedArrayPrototype$, 'buffer', 'b'); - addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); - addGetter($TypedArrayPrototype$, 'byteLength', 'l'); - addGetter($TypedArrayPrototype$, 'length', 'e'); - dP($TypedArrayPrototype$, TAG, { - get: function () { return this[TYPED_ARRAY]; } - }); - - // eslint-disable-next-line max-statements - module.exports = function (KEY, BYTES, wrapper, CLAMPED) { - CLAMPED = !!CLAMPED; - var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'; - var GETTER = 'get' + KEY; - var SETTER = 'set' + KEY; - var TypedArray = global[NAME]; - var Base = TypedArray || {}; - var TAC = TypedArray && getPrototypeOf(TypedArray); - var FORCED = !TypedArray || !$typed.ABV; - var O = {}; - var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; - var getter = function (that, index) { - var data = that._d; - return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); - }; - var setter = function (that, index, value) { - var data = that._d; - if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; - data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); - }; - var addElement = function (that, index) { - dP(that, index, { - get: function () { - return getter(this, index); - }, - set: function (value) { - return setter(this, index, value); - }, - enumerable: true - }); - }; - if (FORCED) { - TypedArray = wrapper(function (that, data, $offset, $length) { - anInstance(that, TypedArray, NAME, '_d'); - var index = 0; - var offset = 0; - var buffer, byteLength, length, klass; - if (!isObject(data)) { - length = toIndex(data); - byteLength = length * BYTES; - buffer = new $ArrayBuffer(byteLength); - } else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { - buffer = data; - offset = toOffset($offset, BYTES); - var $len = data.byteLength; - if ($length === undefined) { - if ($len % BYTES) throw RangeError(WRONG_LENGTH); - byteLength = $len - offset; - if (byteLength < 0) throw RangeError(WRONG_LENGTH); - } else { - byteLength = toLength($length) * BYTES; - if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH); - } - length = byteLength / BYTES; - } else if (TYPED_ARRAY in data) { - return fromList(TypedArray, data); - } else { - return $from.call(TypedArray, data); - } - hide(that, '_d', { - b: buffer, - o: offset, - l: byteLength, - e: length, - v: new $DataView(buffer) - }); - while (index < length) addElement(that, index++); - }); - TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); - hide(TypedArrayPrototype, 'constructor', TypedArray); - } else if (!fails(function () { - TypedArray(1); - }) || !fails(function () { - new TypedArray(-1); // eslint-disable-line no-new - }) || !$iterDetect(function (iter) { - new TypedArray(); // eslint-disable-line no-new - new TypedArray(null); // eslint-disable-line no-new - new TypedArray(1.5); // eslint-disable-line no-new - new TypedArray(iter); // eslint-disable-line no-new - }, true)) { - TypedArray = wrapper(function (that, data, $offset, $length) { - anInstance(that, TypedArray, NAME); - var klass; - // `ws` module bug, temporarily remove validation length for Uint8Array - // https://github.com/websockets/ws/pull/645 - if (!isObject(data)) return new Base(toIndex(data)); - if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { - return $length !== undefined - ? new Base(data, toOffset($offset, BYTES), $length) - : $offset !== undefined - ? new Base(data, toOffset($offset, BYTES)) - : new Base(data); - } - if (TYPED_ARRAY in data) return fromList(TypedArray, data); - return $from.call(TypedArray, data); - }); - arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) { - if (!(key in TypedArray)) hide(TypedArray, key, Base[key]); - }); - TypedArray[PROTOTYPE] = TypedArrayPrototype; - if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray; - } - var $nativeIterator = TypedArrayPrototype[ITERATOR]; - var CORRECT_ITER_NAME = !!$nativeIterator - && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined); - var $iterator = $iterators.values; - hide(TypedArray, TYPED_CONSTRUCTOR, true); - hide(TypedArrayPrototype, TYPED_ARRAY, NAME); - hide(TypedArrayPrototype, VIEW, true); - hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); - - if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) { - dP(TypedArrayPrototype, TAG, { - get: function () { return NAME; } - }); - } - - O[NAME] = TypedArray; - - $export($export.G + $export.W + $export.F * (TypedArray != Base), O); - - $export($export.S, NAME, { - BYTES_PER_ELEMENT: BYTES - }); - - $export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, { - from: $from, - of: $of - }); - - if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); - - $export($export.P, NAME, proto); - - setSpecies(NAME); - - $export($export.P + $export.F * FORCED_SET, NAME, { set: $set }); - - $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); - - if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString; - - $export($export.P + $export.F * fails(function () { - new TypedArray(1).slice(); - }), NAME, { slice: $slice }); - - $export($export.P + $export.F * (fails(function () { - return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString(); - }) || !fails(function () { - TypedArrayPrototype.toLocaleString.call([1, 2]); - })), NAME, { toLocaleString: $toLocaleString }); - - Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; - if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator); - }; - } else module.exports = function () { /* empty */ }; - - -/***/ }), -/* 236 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Uint8', 1, function (init) { - return function Uint8Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 237 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Uint8', 1, function (init) { - return function Uint8ClampedArray(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }, true); - - -/***/ }), -/* 238 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Int16', 2, function (init) { - return function Int16Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 239 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Uint16', 2, function (init) { - return function Uint16Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 240 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Int32', 4, function (init) { - return function Int32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 241 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Uint32', 4, function (init) { - return function Uint32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 242 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Float32', 4, function (init) { - return function Float32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 243 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(235)('Float64', 8, function (init) { - return function Float64Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 244 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(24); - var anObject = __webpack_require__(12); - var rApply = (__webpack_require__(4).Reflect || {}).apply; - var fApply = Function.apply; - // MS Edge argumentsList argument is optional - $export($export.S + $export.F * !__webpack_require__(7)(function () { - rApply(function () { /* empty */ }); - }), 'Reflect', { - apply: function apply(target, thisArgument, argumentsList) { - var T = aFunction(target); - var L = anObject(argumentsList); - return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L); - } - }); - - -/***/ }), -/* 245 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) - var $export = __webpack_require__(8); - var create = __webpack_require__(47); - var aFunction = __webpack_require__(24); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var fails = __webpack_require__(7); - var bind = __webpack_require__(77); - var rConstruct = (__webpack_require__(4).Reflect || {}).construct; - - // MS Edge supports only 2 arguments and argumentsList argument is optional - // FF Nightly sets third argument as `new.target`, but does not create `this` from it - var NEW_TARGET_BUG = fails(function () { - function F() { /* empty */ } - return !(rConstruct(function () { /* empty */ }, [], F) instanceof F); - }); - var ARGS_BUG = !fails(function () { - rConstruct(function () { /* empty */ }); - }); - - $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { - construct: function construct(Target, args /* , newTarget */) { - aFunction(Target); - anObject(args); - var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); - if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget); - if (Target == newTarget) { - // w/o altered newTarget, optimization for 0-4 arguments - switch (args.length) { - case 0: return new Target(); - case 1: return new Target(args[0]); - case 2: return new Target(args[0], args[1]); - case 3: return new Target(args[0], args[1], args[2]); - case 4: return new Target(args[0], args[1], args[2], args[3]); - } - // w/o altered newTarget, lot of arguments case - var $args = [null]; - $args.push.apply($args, args); - return new (bind.apply(Target, $args))(); - } - // with altered newTarget, not support built-in constructors - var proto = newTarget.prototype; - var instance = create(isObject(proto) ? proto : Object.prototype); - var result = Function.apply.call(Target, instance, args); - return isObject(result) ? result : instance; - } - }); - - -/***/ }), -/* 246 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) - var dP = __webpack_require__(11); - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var toPrimitive = __webpack_require__(16); - - // MS Edge has broken Reflect.defineProperty - throwing instead of returning false - $export($export.S + $export.F * __webpack_require__(7)(function () { - // eslint-disable-next-line no-undef - Reflect.defineProperty(dP.f({}, 1, { value: 1 }), 1, { value: 2 }); - }), 'Reflect', { - defineProperty: function defineProperty(target, propertyKey, attributes) { - anObject(target); - propertyKey = toPrimitive(propertyKey, true); - anObject(attributes); - try { - dP.f(target, propertyKey, attributes); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 247 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.4 Reflect.deleteProperty(target, propertyKey) - var $export = __webpack_require__(8); - var gOPD = __webpack_require__(52).f; - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - deleteProperty: function deleteProperty(target, propertyKey) { - var desc = gOPD(anObject(target), propertyKey); - return desc && !desc.configurable ? false : delete target[propertyKey]; - } - }); - - -/***/ }), -/* 248 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 26.1.5 Reflect.enumerate(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var Enumerate = function (iterated) { - this._t = anObject(iterated); // target - this._i = 0; // next index - var keys = this._k = []; // keys - var key; - for (key in iterated) keys.push(key); - }; - __webpack_require__(131)(Enumerate, 'Object', function () { - var that = this; - var keys = that._k; - var key; - do { - if (that._i >= keys.length) return { value: undefined, done: true }; - } while (!((key = keys[that._i++]) in that._t)); - return { value: key, done: false }; - }); - - $export($export.S, 'Reflect', { - enumerate: function enumerate(target) { - return new Enumerate(target); - } - }); - - -/***/ }), -/* 249 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.6 Reflect.get(target, propertyKey [, receiver]) - var gOPD = __webpack_require__(52); - var getPrototypeOf = __webpack_require__(59); - var has = __webpack_require__(5); - var $export = __webpack_require__(8); - var isObject = __webpack_require__(13); - var anObject = __webpack_require__(12); - - function get(target, propertyKey /* , receiver */) { - var receiver = arguments.length < 3 ? target : arguments[2]; - var desc, proto; - if (anObject(target) === receiver) return target[propertyKey]; - if (desc = gOPD.f(target, propertyKey)) return has(desc, 'value') - ? desc.value - : desc.get !== undefined - ? desc.get.call(receiver) - : undefined; - if (isObject(proto = getPrototypeOf(target))) return get(proto, propertyKey, receiver); - } - - $export($export.S, 'Reflect', { get: get }); - - -/***/ }), -/* 250 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) - var gOPD = __webpack_require__(52); - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { - return gOPD.f(anObject(target), propertyKey); - } - }); - - -/***/ }), -/* 251 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.8 Reflect.getPrototypeOf(target) - var $export = __webpack_require__(8); - var getProto = __webpack_require__(59); - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - getPrototypeOf: function getPrototypeOf(target) { - return getProto(anObject(target)); - } - }); - - -/***/ }), -/* 252 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.9 Reflect.has(target, propertyKey) - var $export = __webpack_require__(8); - - $export($export.S, 'Reflect', { - has: function has(target, propertyKey) { - return propertyKey in target; - } - }); - - -/***/ }), -/* 253 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.10 Reflect.isExtensible(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var $isExtensible = Object.isExtensible; - - $export($export.S, 'Reflect', { - isExtensible: function isExtensible(target) { - anObject(target); - return $isExtensible ? $isExtensible(target) : true; - } - }); - - -/***/ }), -/* 254 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.11 Reflect.ownKeys(target) - var $export = __webpack_require__(8); - - $export($export.S, 'Reflect', { ownKeys: __webpack_require__(255) }); - - -/***/ }), -/* 255 */ -/***/ (function(module, exports, __webpack_require__) { - - // all object keys, includes non-enumerable and symbols - var gOPN = __webpack_require__(51); - var gOPS = __webpack_require__(43); - var anObject = __webpack_require__(12); - var Reflect = __webpack_require__(4).Reflect; - module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) { - var keys = gOPN.f(anObject(it)); - var getSymbols = gOPS.f; - return getSymbols ? keys.concat(getSymbols(it)) : keys; - }; - - -/***/ }), -/* 256 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.12 Reflect.preventExtensions(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var $preventExtensions = Object.preventExtensions; - - $export($export.S, 'Reflect', { - preventExtensions: function preventExtensions(target) { - anObject(target); - try { - if ($preventExtensions) $preventExtensions(target); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 257 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) - var dP = __webpack_require__(11); - var gOPD = __webpack_require__(52); - var getPrototypeOf = __webpack_require__(59); - var has = __webpack_require__(5); - var $export = __webpack_require__(8); - var createDesc = __webpack_require__(17); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - - function set(target, propertyKey, V /* , receiver */) { - var receiver = arguments.length < 4 ? target : arguments[3]; - var ownDesc = gOPD.f(anObject(target), propertyKey); - var existingDescriptor, proto; - if (!ownDesc) { - if (isObject(proto = getPrototypeOf(target))) { - return set(proto, propertyKey, V, receiver); - } - ownDesc = createDesc(0); - } - if (has(ownDesc, 'value')) { - if (ownDesc.writable === false || !isObject(receiver)) return false; - if (existingDescriptor = gOPD.f(receiver, propertyKey)) { - if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false; - existingDescriptor.value = V; - dP.f(receiver, propertyKey, existingDescriptor); - } else dP.f(receiver, propertyKey, createDesc(0, V)); - return true; - } - return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); - } - - $export($export.S, 'Reflect', { set: set }); - - -/***/ }), -/* 258 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.14 Reflect.setPrototypeOf(target, proto) - var $export = __webpack_require__(8); - var setProto = __webpack_require__(73); - - if (setProto) $export($export.S, 'Reflect', { - setPrototypeOf: function setPrototypeOf(target, proto) { - setProto.check(target, proto); - try { - setProto.set(target, proto); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 259 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/Array.prototype.includes - var $export = __webpack_require__(8); - var $includes = __webpack_require__(37)(true); - - $export($export.P, 'Array', { - includes: function includes(el /* , fromIndex = 0 */) { - return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - __webpack_require__(188)('includes'); - - -/***/ }), -/* 260 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap - var $export = __webpack_require__(8); - var flattenIntoArray = __webpack_require__(261); - var toObject = __webpack_require__(46); - var toLength = __webpack_require__(38); - var aFunction = __webpack_require__(24); - var arraySpeciesCreate = __webpack_require__(175); - - $export($export.P, 'Array', { - flatMap: function flatMap(callbackfn /* , thisArg */) { - var O = toObject(this); - var sourceLen, A; - aFunction(callbackfn); - sourceLen = toLength(O.length); - A = arraySpeciesCreate(O, 0); - flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments[1]); - return A; - } - }); - - __webpack_require__(188)('flatMap'); - - -/***/ }), -/* 261 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray - var isArray = __webpack_require__(45); - var isObject = __webpack_require__(13); - var toLength = __webpack_require__(38); - var ctx = __webpack_require__(23); - var IS_CONCAT_SPREADABLE = __webpack_require__(27)('isConcatSpreadable'); - - function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) { - var targetIndex = start; - var sourceIndex = 0; - var mapFn = mapper ? ctx(mapper, thisArg, 3) : false; - var element, spreadable; - - while (sourceIndex < sourceLen) { - if (sourceIndex in source) { - element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; - - spreadable = false; - if (isObject(element)) { - spreadable = element[IS_CONCAT_SPREADABLE]; - spreadable = spreadable !== undefined ? !!spreadable : isArray(element); - } - - if (spreadable && depth > 0) { - targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1; - } else { - if (targetIndex >= 0x1fffffffffffff) throw TypeError(); - target[targetIndex] = element; - } - - targetIndex++; - } - sourceIndex++; - } - return targetIndex; - } - - module.exports = flattenIntoArray; - - -/***/ }), -/* 262 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten - var $export = __webpack_require__(8); - var flattenIntoArray = __webpack_require__(261); - var toObject = __webpack_require__(46); - var toLength = __webpack_require__(38); - var toInteger = __webpack_require__(39); - var arraySpeciesCreate = __webpack_require__(175); - - $export($export.P, 'Array', { - flatten: function flatten(/* depthArg = 1 */) { - var depthArg = arguments[0]; - var O = toObject(this); - var sourceLen = toLength(O.length); - var A = arraySpeciesCreate(O, 0); - flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg)); - return A; - } - }); - - __webpack_require__(188)('flatten'); - - -/***/ }), -/* 263 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/mathiasbynens/String.prototype.at - var $export = __webpack_require__(8); - var $at = __webpack_require__(128)(true); - - $export($export.P, 'String', { - at: function at(pos) { - return $at(this, pos); - } - }); - - -/***/ }), -/* 264 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-string-pad-start-end - var $export = __webpack_require__(8); - var $pad = __webpack_require__(265); - var userAgent = __webpack_require__(218); - - // https://github.com/zloirock/core-js/issues/280 - var WEBKIT_BUG = /Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(userAgent); - - $export($export.P + $export.F * WEBKIT_BUG, 'String', { - padStart: function padStart(maxLength /* , fillString = ' ' */) { - return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); - } - }); - - -/***/ }), -/* 265 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-string-pad-start-end - var toLength = __webpack_require__(38); - var repeat = __webpack_require__(91); - var defined = __webpack_require__(36); - - module.exports = function (that, maxLength, fillString, left) { - var S = String(defined(that)); - var stringLength = S.length; - var fillStr = fillString === undefined ? ' ' : String(fillString); - var intMaxLength = toLength(maxLength); - if (intMaxLength <= stringLength || fillStr == '') return S; - var fillLen = intMaxLength - stringLength; - var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); - if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen); - return left ? stringFiller + S : S + stringFiller; - }; - - -/***/ }), -/* 266 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-string-pad-start-end - var $export = __webpack_require__(8); - var $pad = __webpack_require__(265); - var userAgent = __webpack_require__(218); - - // https://github.com/zloirock/core-js/issues/280 - var WEBKIT_BUG = /Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(userAgent); - - $export($export.P + $export.F * WEBKIT_BUG, 'String', { - padEnd: function padEnd(maxLength /* , fillString = ' ' */) { - return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); - } - }); - - -/***/ }), -/* 267 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/sebmarkbage/ecmascript-string-left-right-trim - __webpack_require__(83)('trimLeft', function ($trim) { - return function trimLeft() { - return $trim(this, 1); - }; - }, 'trimStart'); - - -/***/ }), -/* 268 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/sebmarkbage/ecmascript-string-left-right-trim - __webpack_require__(83)('trimRight', function ($trim) { - return function trimRight() { - return $trim(this, 2); - }; - }, 'trimEnd'); - - -/***/ }), -/* 269 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/String.prototype.matchAll/ - var $export = __webpack_require__(8); - var defined = __webpack_require__(36); - var toLength = __webpack_require__(38); - var isRegExp = __webpack_require__(135); - var getFlags = __webpack_require__(198); - var RegExpProto = RegExp.prototype; - - var $RegExpStringIterator = function (regexp, string) { - this._r = regexp; - this._s = string; - }; - - __webpack_require__(131)($RegExpStringIterator, 'RegExp String', function next() { - var match = this._r.exec(this._s); - return { value: match, done: match === null }; - }); - - $export($export.P, 'String', { - matchAll: function matchAll(regexp) { - defined(this); - if (!isRegExp(regexp)) throw TypeError(regexp + ' is not a regexp!'); - var S = String(this); - var flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp); - var rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); - rx.lastIndex = toLength(regexp.lastIndex); - return new $RegExpStringIterator(rx, S); - } - }); - - -/***/ }), -/* 270 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(29)('asyncIterator'); - - -/***/ }), -/* 271 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(29)('observable'); - - -/***/ }), -/* 272 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-getownpropertydescriptors - var $export = __webpack_require__(8); - var ownKeys = __webpack_require__(255); - var toIObject = __webpack_require__(33); - var gOPD = __webpack_require__(52); - var createProperty = __webpack_require__(165); - - $export($export.S, 'Object', { - getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { - var O = toIObject(object); - var getDesc = gOPD.f; - var keys = ownKeys(O); - var result = {}; - var i = 0; - var key, desc; - while (keys.length > i) { - desc = getDesc(O, key = keys[i++]); - if (desc !== undefined) createProperty(result, key, desc); - } - return result; - } - }); - - -/***/ }), -/* 273 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-values-entries - var $export = __webpack_require__(8); - var $values = __webpack_require__(274)(false); - - $export($export.S, 'Object', { - values: function values(it) { - return $values(it); - } - }); - - -/***/ }), -/* 274 */ -/***/ (function(module, exports, __webpack_require__) { - - var DESCRIPTORS = __webpack_require__(6); - var getKeys = __webpack_require__(31); - var toIObject = __webpack_require__(33); - var isEnum = __webpack_require__(44).f; - module.exports = function (isEntries) { - return function (it) { - var O = toIObject(it); - var keys = getKeys(O); - var length = keys.length; - var i = 0; - var result = []; - var key; - while (length > i) { - key = keys[i++]; - if (!DESCRIPTORS || isEnum.call(O, key)) { - result.push(isEntries ? [key, O[key]] : O[key]); - } - } - return result; - }; - }; - - -/***/ }), -/* 275 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-values-entries - var $export = __webpack_require__(8); - var $entries = __webpack_require__(274)(true); - - $export($export.S, 'Object', { - entries: function entries(it) { - return $entries(it); - } - }); - - -/***/ }), -/* 276 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(46); - var aFunction = __webpack_require__(24); - var $defineProperty = __webpack_require__(11); - - // B.2.2.2 Object.prototype.__defineGetter__(P, getter) - __webpack_require__(6) && $export($export.P + __webpack_require__(277), 'Object', { - __defineGetter__: function __defineGetter__(P, getter) { - $defineProperty.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true }); - } - }); - - -/***/ }), -/* 277 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // Forced replacement prototype accessors methods - module.exports = __webpack_require__(22) || !__webpack_require__(7)(function () { - var K = Math.random(); - // In FF throws only define methods - // eslint-disable-next-line no-undef, no-useless-call - __defineSetter__.call(null, K, function () { /* empty */ }); - delete __webpack_require__(4)[K]; - }); - - -/***/ }), -/* 278 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(46); - var aFunction = __webpack_require__(24); - var $defineProperty = __webpack_require__(11); - - // B.2.2.3 Object.prototype.__defineSetter__(P, setter) - __webpack_require__(6) && $export($export.P + __webpack_require__(277), 'Object', { - __defineSetter__: function __defineSetter__(P, setter) { - $defineProperty.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true }); - } - }); - - -/***/ }), -/* 279 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(46); - var toPrimitive = __webpack_require__(16); - var getPrototypeOf = __webpack_require__(59); - var getOwnPropertyDescriptor = __webpack_require__(52).f; - - // B.2.2.4 Object.prototype.__lookupGetter__(P) - __webpack_require__(6) && $export($export.P + __webpack_require__(277), 'Object', { - __lookupGetter__: function __lookupGetter__(P) { - var O = toObject(this); - var K = toPrimitive(P, true); - var D; - do { - if (D = getOwnPropertyDescriptor(O, K)) return D.get; - } while (O = getPrototypeOf(O)); - } - }); - - -/***/ }), -/* 280 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(46); - var toPrimitive = __webpack_require__(16); - var getPrototypeOf = __webpack_require__(59); - var getOwnPropertyDescriptor = __webpack_require__(52).f; - - // B.2.2.5 Object.prototype.__lookupSetter__(P) - __webpack_require__(6) && $export($export.P + __webpack_require__(277), 'Object', { - __lookupSetter__: function __lookupSetter__(P) { - var O = toObject(this); - var K = toPrimitive(P, true); - var D; - do { - if (D = getOwnPropertyDescriptor(O, K)) return D.set; - } while (O = getPrototypeOf(O)); - } - }); - - -/***/ }), -/* 281 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var $export = __webpack_require__(8); - - $export($export.P + $export.R, 'Map', { toJSON: __webpack_require__(282)('Map') }); - - -/***/ }), -/* 282 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var classof = __webpack_require__(75); - var from = __webpack_require__(283); - module.exports = function (NAME) { - return function toJSON() { - if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic"); - return from(this); - }; - }; - - -/***/ }), -/* 283 */ -/***/ (function(module, exports, __webpack_require__) { - - var forOf = __webpack_require__(213); - - module.exports = function (iter, ITERATOR) { - var result = []; - forOf(iter, false, result.push, result, ITERATOR); - return result; - }; - - -/***/ }), -/* 284 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var $export = __webpack_require__(8); - - $export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(282)('Set') }); - - -/***/ }), -/* 285 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-map.of - __webpack_require__(286)('Map'); - - -/***/ }), -/* 286 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-setmap-offrom/ - var $export = __webpack_require__(8); - - module.exports = function (COLLECTION) { - $export($export.S, COLLECTION, { of: function of() { - var length = arguments.length; - var A = new Array(length); - while (length--) A[length] = arguments[length]; - return new this(A); - } }); - }; - - -/***/ }), -/* 287 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-set.of - __webpack_require__(286)('Set'); - - -/***/ }), -/* 288 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of - __webpack_require__(286)('WeakMap'); - - -/***/ }), -/* 289 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of - __webpack_require__(286)('WeakSet'); - - -/***/ }), -/* 290 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-map.from - __webpack_require__(291)('Map'); - - -/***/ }), -/* 291 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-setmap-offrom/ - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(24); - var ctx = __webpack_require__(23); - var forOf = __webpack_require__(213); - - module.exports = function (COLLECTION) { - $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) { - var mapFn = arguments[1]; - var mapping, A, n, cb; - aFunction(this); - mapping = mapFn !== undefined; - if (mapping) aFunction(mapFn); - if (source == undefined) return new this(); - A = []; - if (mapping) { - n = 0; - cb = ctx(mapFn, arguments[2], 2); - forOf(source, false, function (nextItem) { - A.push(cb(nextItem, n++)); - }); - } else { - forOf(source, false, A.push, A); - } - return new this(A); - } }); - }; - - -/***/ }), -/* 292 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-set.from - __webpack_require__(291)('Set'); - - -/***/ }), -/* 293 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from - __webpack_require__(291)('WeakMap'); - - -/***/ }), -/* 294 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from - __webpack_require__(291)('WeakSet'); - - -/***/ }), -/* 295 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-global - var $export = __webpack_require__(8); - - $export($export.G, { global: __webpack_require__(4) }); - - -/***/ }), -/* 296 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-global - var $export = __webpack_require__(8); - - $export($export.S, 'System', { global: __webpack_require__(4) }); - - -/***/ }), -/* 297 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/ljharb/proposal-is-error - var $export = __webpack_require__(8); - var cof = __webpack_require__(35); - - $export($export.S, 'Error', { - isError: function isError(it) { - return cof(it) === 'Error'; - } - }); - - -/***/ }), -/* 298 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - clamp: function clamp(x, lower, upper) { - return Math.min(upper, Math.max(lower, x)); - } - }); - - -/***/ }), -/* 299 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { DEG_PER_RAD: Math.PI / 180 }); - - -/***/ }), -/* 300 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var RAD_PER_DEG = 180 / Math.PI; - - $export($export.S, 'Math', { - degrees: function degrees(radians) { - return radians * RAD_PER_DEG; - } - }); - - -/***/ }), -/* 301 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var scale = __webpack_require__(302); - var fround = __webpack_require__(114); - - $export($export.S, 'Math', { - fscale: function fscale(x, inLow, inHigh, outLow, outHigh) { - return fround(scale(x, inLow, inHigh, outLow, outHigh)); - } - }); - - -/***/ }), -/* 302 */ -/***/ (function(module, exports) { - - // https://rwaldron.github.io/proposal-math-extensions/ - module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) { - if ( - arguments.length === 0 - // eslint-disable-next-line no-self-compare - || x != x - // eslint-disable-next-line no-self-compare - || inLow != inLow - // eslint-disable-next-line no-self-compare - || inHigh != inHigh - // eslint-disable-next-line no-self-compare - || outLow != outLow - // eslint-disable-next-line no-self-compare - || outHigh != outHigh - ) return NaN; - if (x === Infinity || x === -Infinity) return x; - return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow; - }; - - -/***/ }), -/* 303 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - iaddh: function iaddh(x0, x1, y0, y1) { - var $x0 = x0 >>> 0; - var $x1 = x1 >>> 0; - var $y0 = y0 >>> 0; - return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; - } - }); - - -/***/ }), -/* 304 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - isubh: function isubh(x0, x1, y0, y1) { - var $x0 = x0 >>> 0; - var $x1 = x1 >>> 0; - var $y0 = y0 >>> 0; - return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; - } - }); - - -/***/ }), -/* 305 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - imulh: function imulh(u, v) { - var UINT16 = 0xffff; - var $u = +u; - var $v = +v; - var u0 = $u & UINT16; - var v0 = $v & UINT16; - var u1 = $u >> 16; - var v1 = $v >> 16; - var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); - return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); - } - }); - - -/***/ }), -/* 306 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { RAD_PER_DEG: 180 / Math.PI }); - - -/***/ }), -/* 307 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var DEG_PER_RAD = Math.PI / 180; - - $export($export.S, 'Math', { - radians: function radians(degrees) { - return degrees * DEG_PER_RAD; - } - }); - - -/***/ }), -/* 308 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { scale: __webpack_require__(302) }); - - -/***/ }), -/* 309 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - umulh: function umulh(u, v) { - var UINT16 = 0xffff; - var $u = +u; - var $v = +v; - var u0 = $u & UINT16; - var v0 = $v & UINT16; - var u1 = $u >>> 16; - var v1 = $v >>> 16; - var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); - return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); - } - }); - - -/***/ }), -/* 310 */ -/***/ (function(module, exports, __webpack_require__) { - - // http://jfbastien.github.io/papers/Math.signbit.html - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { signbit: function signbit(x) { - // eslint-disable-next-line no-self-compare - return (x = +x) != x ? x : x == 0 ? 1 / x == Infinity : x > 0; - } }); - - -/***/ }), -/* 311 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-promise-finally - 'use strict'; - var $export = __webpack_require__(8); - var core = __webpack_require__(9); - var global = __webpack_require__(4); - var speciesConstructor = __webpack_require__(210); - var promiseResolve = __webpack_require__(219); - - $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { - var C = speciesConstructor(this, core.Promise || global.Promise); - var isFunction = typeof onFinally == 'function'; - return this.then( - isFunction ? function (x) { - return promiseResolve(C, onFinally()).then(function () { return x; }); - } : onFinally, - isFunction ? function (e) { - return promiseResolve(C, onFinally()).then(function () { throw e; }); - } : onFinally - ); - } }); - - -/***/ }), -/* 312 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-promise-try - var $export = __webpack_require__(8); - var newPromiseCapability = __webpack_require__(216); - var perform = __webpack_require__(217); - - $export($export.S, 'Promise', { 'try': function (callbackfn) { - var promiseCapability = newPromiseCapability.f(this); - var result = perform(callbackfn); - (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); - return promiseCapability.promise; - } }); - - -/***/ }), -/* 313 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var toMetaKey = metadata.key; - var ordinaryDefineOwnMetadata = metadata.set; - - metadata.exp({ defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey) { - ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); - } }); - - -/***/ }), -/* 314 */ -/***/ (function(module, exports, __webpack_require__) { - - var Map = __webpack_require__(221); - var $export = __webpack_require__(8); - var shared = __webpack_require__(21)('metadata'); - var store = shared.store || (shared.store = new (__webpack_require__(226))()); - - var getOrCreateMetadataMap = function (target, targetKey, create) { - var targetMetadata = store.get(target); - if (!targetMetadata) { - if (!create) return undefined; - store.set(target, targetMetadata = new Map()); - } - var keyMetadata = targetMetadata.get(targetKey); - if (!keyMetadata) { - if (!create) return undefined; - targetMetadata.set(targetKey, keyMetadata = new Map()); - } return keyMetadata; - }; - var ordinaryHasOwnMetadata = function (MetadataKey, O, P) { - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? false : metadataMap.has(MetadataKey); - }; - var ordinaryGetOwnMetadata = function (MetadataKey, O, P) { - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); - }; - var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) { - getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); - }; - var ordinaryOwnMetadataKeys = function (target, targetKey) { - var metadataMap = getOrCreateMetadataMap(target, targetKey, false); - var keys = []; - if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); }); - return keys; - }; - var toMetaKey = function (it) { - return it === undefined || typeof it == 'symbol' ? it : String(it); - }; - var exp = function (O) { - $export($export.S, 'Reflect', O); - }; - - module.exports = { - store: store, - map: getOrCreateMetadataMap, - has: ordinaryHasOwnMetadata, - get: ordinaryGetOwnMetadata, - set: ordinaryDefineOwnMetadata, - keys: ordinaryOwnMetadataKeys, - key: toMetaKey, - exp: exp - }; - - -/***/ }), -/* 315 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var toMetaKey = metadata.key; - var getOrCreateMetadataMap = metadata.map; - var store = metadata.store; - - metadata.exp({ deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) { - var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]); - var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); - if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false; - if (metadataMap.size) return true; - var targetMetadata = store.get(target); - targetMetadata['delete'](targetKey); - return !!targetMetadata.size || store['delete'](target); - } }); - - -/***/ }), -/* 316 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(59); - var ordinaryHasOwnMetadata = metadata.has; - var ordinaryGetOwnMetadata = metadata.get; - var toMetaKey = metadata.key; - - var ordinaryGetMetadata = function (MetadataKey, O, P) { - var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P); - var parent = getPrototypeOf(O); - return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; - }; - - metadata.exp({ getMetadata: function getMetadata(metadataKey, target /* , targetKey */) { - return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 317 */ -/***/ (function(module, exports, __webpack_require__) { - - var Set = __webpack_require__(225); - var from = __webpack_require__(283); - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(59); - var ordinaryOwnMetadataKeys = metadata.keys; - var toMetaKey = metadata.key; - - var ordinaryMetadataKeys = function (O, P) { - var oKeys = ordinaryOwnMetadataKeys(O, P); - var parent = getPrototypeOf(O); - if (parent === null) return oKeys; - var pKeys = ordinaryMetadataKeys(parent, P); - return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; - }; - - metadata.exp({ getMetadataKeys: function getMetadataKeys(target /* , targetKey */) { - return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); - } }); - - -/***/ }), -/* 318 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var ordinaryGetOwnMetadata = metadata.get; - var toMetaKey = metadata.key; - - metadata.exp({ getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) { - return ordinaryGetOwnMetadata(metadataKey, anObject(target) - , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 319 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var ordinaryOwnMetadataKeys = metadata.keys; - var toMetaKey = metadata.key; - - metadata.exp({ getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) { - return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); - } }); - - -/***/ }), -/* 320 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(59); - var ordinaryHasOwnMetadata = metadata.has; - var toMetaKey = metadata.key; - - var ordinaryHasMetadata = function (MetadataKey, O, P) { - var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn) return true; - var parent = getPrototypeOf(O); - return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; - }; - - metadata.exp({ hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) { - return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 321 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var ordinaryHasOwnMetadata = metadata.has; - var toMetaKey = metadata.key; - - metadata.exp({ hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) { - return ordinaryHasOwnMetadata(metadataKey, anObject(target) - , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 322 */ -/***/ (function(module, exports, __webpack_require__) { - - var $metadata = __webpack_require__(314); - var anObject = __webpack_require__(12); - var aFunction = __webpack_require__(24); - var toMetaKey = $metadata.key; - var ordinaryDefineOwnMetadata = $metadata.set; - - $metadata.exp({ metadata: function metadata(metadataKey, metadataValue) { - return function decorator(target, targetKey) { - ordinaryDefineOwnMetadata( - metadataKey, metadataValue, - (targetKey !== undefined ? anObject : aFunction)(target), - toMetaKey(targetKey) - ); - }; - } }); - - -/***/ }), -/* 323 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask - var $export = __webpack_require__(8); - var microtask = __webpack_require__(215)(); - var process = __webpack_require__(4).process; - var isNode = __webpack_require__(35)(process) == 'process'; - - $export($export.G, { - asap: function asap(fn) { - var domain = isNode && process.domain; - microtask(domain ? domain.bind(fn) : fn); - } - }); - - -/***/ }), -/* 324 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/zenparsing/es-observable - var $export = __webpack_require__(8); - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var microtask = __webpack_require__(215)(); - var OBSERVABLE = __webpack_require__(27)('observable'); - var aFunction = __webpack_require__(24); - var anObject = __webpack_require__(12); - var anInstance = __webpack_require__(212); - var redefineAll = __webpack_require__(220); - var hide = __webpack_require__(10); - var forOf = __webpack_require__(213); - var RETURN = forOf.RETURN; - - var getMethod = function (fn) { - return fn == null ? undefined : aFunction(fn); - }; - - var cleanupSubscription = function (subscription) { - var cleanup = subscription._c; - if (cleanup) { - subscription._c = undefined; - cleanup(); - } - }; - - var subscriptionClosed = function (subscription) { - return subscription._o === undefined; - }; - - var closeSubscription = function (subscription) { - if (!subscriptionClosed(subscription)) { - subscription._o = undefined; - cleanupSubscription(subscription); - } - }; - - var Subscription = function (observer, subscriber) { - anObject(observer); - this._c = undefined; - this._o = observer; - observer = new SubscriptionObserver(this); - try { - var cleanup = subscriber(observer); - var subscription = cleanup; - if (cleanup != null) { - if (typeof cleanup.unsubscribe === 'function') cleanup = function () { subscription.unsubscribe(); }; - else aFunction(cleanup); - this._c = cleanup; - } - } catch (e) { - observer.error(e); - return; - } if (subscriptionClosed(this)) cleanupSubscription(this); - }; - - Subscription.prototype = redefineAll({}, { - unsubscribe: function unsubscribe() { closeSubscription(this); } - }); - - var SubscriptionObserver = function (subscription) { - this._s = subscription; - }; - - SubscriptionObserver.prototype = redefineAll({}, { - next: function next(value) { - var subscription = this._s; - if (!subscriptionClosed(subscription)) { - var observer = subscription._o; - try { - var m = getMethod(observer.next); - if (m) return m.call(observer, value); - } catch (e) { - try { - closeSubscription(subscription); - } finally { - throw e; - } - } - } - }, - error: function error(value) { - var subscription = this._s; - if (subscriptionClosed(subscription)) throw value; - var observer = subscription._o; - subscription._o = undefined; - try { - var m = getMethod(observer.error); - if (!m) throw value; - value = m.call(observer, value); - } catch (e) { - try { - cleanupSubscription(subscription); - } finally { - throw e; - } - } cleanupSubscription(subscription); - return value; - }, - complete: function complete(value) { - var subscription = this._s; - if (!subscriptionClosed(subscription)) { - var observer = subscription._o; - subscription._o = undefined; - try { - var m = getMethod(observer.complete); - value = m ? m.call(observer, value) : undefined; - } catch (e) { - try { - cleanupSubscription(subscription); - } finally { - throw e; - } - } cleanupSubscription(subscription); - return value; - } - } - }); - - var $Observable = function Observable(subscriber) { - anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); - }; - - redefineAll($Observable.prototype, { - subscribe: function subscribe(observer) { - return new Subscription(observer, this._f); - }, - forEach: function forEach(fn) { - var that = this; - return new (core.Promise || global.Promise)(function (resolve, reject) { - aFunction(fn); - var subscription = that.subscribe({ - next: function (value) { - try { - return fn(value); - } catch (e) { - reject(e); - subscription.unsubscribe(); - } - }, - error: reject, - complete: resolve - }); - }); - } - }); - - redefineAll($Observable, { - from: function from(x) { - var C = typeof this === 'function' ? this : $Observable; - var method = getMethod(anObject(x)[OBSERVABLE]); - if (method) { - var observable = anObject(method.call(x)); - return observable.constructor === C ? observable : new C(function (observer) { - return observable.subscribe(observer); - }); - } - return new C(function (observer) { - var done = false; - microtask(function () { - if (!done) { - try { - if (forOf(x, false, function (it) { - observer.next(it); - if (done) return RETURN; - }) === RETURN) return; - } catch (e) { - if (done) throw e; - observer.error(e); - return; - } observer.complete(); - } - }); - return function () { done = true; }; - }); - }, - of: function of() { - for (var i = 0, l = arguments.length, items = new Array(l); i < l;) items[i] = arguments[i++]; - return new (typeof this === 'function' ? this : $Observable)(function (observer) { - var done = false; - microtask(function () { - if (!done) { - for (var j = 0; j < items.length; ++j) { - observer.next(items[j]); - if (done) return; - } observer.complete(); - } - }); - return function () { done = true; }; - }); - } - }); - - hide($Observable.prototype, OBSERVABLE, function () { return this; }); - - $export($export.G, { Observable: $Observable }); - - __webpack_require__(194)('Observable'); - - -/***/ }), -/* 325 */ -/***/ (function(module, exports, __webpack_require__) { - - // ie9- setTimeout & setInterval additional parameters fix - var global = __webpack_require__(4); - var $export = __webpack_require__(8); - var userAgent = __webpack_require__(218); - var slice = [].slice; - var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check - var wrap = function (set) { - return function (fn, time /* , ...args */) { - var boundArgs = arguments.length > 2; - var args = boundArgs ? slice.call(arguments, 2) : false; - return set(boundArgs ? function () { - // eslint-disable-next-line no-new-func - (typeof fn == 'function' ? fn : Function(fn)).apply(this, args); - } : fn, time); - }; - }; - $export($export.G + $export.B + $export.F * MSIE, { - setTimeout: wrap(global.setTimeout), - setInterval: wrap(global.setInterval) - }); - - -/***/ }), -/* 326 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $task = __webpack_require__(214); - $export($export.G + $export.B, { - setImmediate: $task.set, - clearImmediate: $task.clear - }); - - -/***/ }), -/* 327 */ -/***/ (function(module, exports, __webpack_require__) { - - var $iterators = __webpack_require__(195); - var getKeys = __webpack_require__(31); - var redefine = __webpack_require__(18); - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var Iterators = __webpack_require__(130); - var wks = __webpack_require__(27); - var ITERATOR = wks('iterator'); - var TO_STRING_TAG = wks('toStringTag'); - var ArrayValues = Iterators.Array; - - var DOMIterables = { - CSSRuleList: true, // TODO: Not spec compliant, should be false. - CSSStyleDeclaration: false, - CSSValueList: false, - ClientRectList: false, - DOMRectList: false, - DOMStringList: false, - DOMTokenList: true, - DataTransferItemList: false, - FileList: false, - HTMLAllCollection: false, - HTMLCollection: false, - HTMLFormElement: false, - HTMLSelectElement: false, - MediaList: true, // TODO: Not spec compliant, should be false. - MimeTypeArray: false, - NamedNodeMap: false, - NodeList: true, - PaintRequestList: false, - Plugin: false, - PluginArray: false, - SVGLengthList: false, - SVGNumberList: false, - SVGPathSegList: false, - SVGPointList: false, - SVGStringList: false, - SVGTransformList: false, - SourceBufferList: false, - StyleSheetList: true, // TODO: Not spec compliant, should be false. - TextTrackCueList: false, - TextTrackList: false, - TouchList: false - }; - - for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) { - var NAME = collections[i]; - var explicit = DOMIterables[NAME]; - var Collection = global[NAME]; - var proto = Collection && Collection.prototype; - var key; - if (proto) { - if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues); - if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); - Iterators[NAME] = ArrayValues; - if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true); - } - } - - -/***/ }), -/* 328 */ -/***/ (function(module, exports) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ - - !(function(global) { - "use strict"; - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - var inModule = typeof module === "object"; - var runtime = global.regeneratorRuntime; - if (runtime) { - if (inModule) { - // If regeneratorRuntime is defined globally and we're in a module, - // make the exports object identical to regeneratorRuntime. - module.exports = runtime; - } - // Don't bother evaluating the rest of this file if the runtime was - // already defined globally. - return; - } - - // Define the runtime globally (as expected by generated code) as either - // module.exports (if we're in a module) or a new, empty object. - runtime = global.regeneratorRuntime = inModule ? module.exports : {}; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - runtime.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && - NativeIteratorPrototype !== Op && - hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = - Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = - GeneratorFunction.displayName = "GeneratorFunction"; - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - prototype[method] = function(arg) { - return this._invoke(method, arg); - }; - }); - } - - runtime.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; - - runtime.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - runtime.awrap = function(arg) { - return { __await: arg }; - }; - - function AsyncIterator(generator) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && - typeof value === "object" && - hasOwn.call(value, "__await")) { - return Promise.resolve(value.__await).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); - } - - return Promise.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. If the Promise is rejected, however, the - // result for this iteration will be rejected with the same - // reason. Note that rejections of yielded Promises are not - // thrown back into the generator function, as is the case - // when an awaited Promise is rejected. This difference in - // behavior between yield and await is important, because it - // allows the consumer to decide what to do with the yielded - // rejection (swallow it and continue, manually .throw it back - // into the generator, abandon iteration, whatever). With - // await, by contrast, there is no opportunity to examine the - // rejection reason outside the generator function, so the - // only option is to throw it from the await expression, and - // let the generator function handle the exception. - result.value = unwrapped; - resolve(result); - }, reject); - } - } - - if (typeof global.process === "object" && global.process.domain) { - invoke = global.process.domain.bind(invoke); - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new Promise(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - runtime.AsyncIterator = AsyncIterator; - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - runtime.async = function(innerFn, outerFn, self, tryLocsList) { - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList) - ); - - return runtime.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } - - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - if (delegate.iterator.return) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (! info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; - - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; - - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined; - } - - } else { - // Re-yield the result returned by the delegate method. - return info; - } - - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; - } - - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); - - Gp[toStringTagSymbol] = "Generator"; - - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - Gp[iteratorSymbol] = function() { - return this; - }; - - Gp.toString = function() { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - runtime.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined; - next.done = true; - - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - runtime.values = values; - - function doneResult() { - return { value: undefined, done: true }; - } - - Context.prototype = { - constructor: Context, - - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined; - this.done = false; - this.delegate = null; - - this.method = "next"; - this.arg = undefined; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined; - } - } - } - }, - - stop: function() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - - dispatchException: function(exception) { - if (this.done) { - throw exception; - } - - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined; - } - - return !! caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } - - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, - - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined; - } - - return ContinueSentinel; - } - }; - })( - // Among the various tricks for obtaining a reference to the global - // object, this seems to be the most reliable technique that does not - // use indirect eval (which violates Content Security Policy). - typeof global === "object" ? global : - typeof window === "object" ? window : - typeof self === "object" ? self : this - ); - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 329 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(330); - module.exports = __webpack_require__(9).RegExp.escape; - - -/***/ }), -/* 330 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/benjamingr/RexExp.escape - var $export = __webpack_require__(8); - var $re = __webpack_require__(331)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); - - $export($export.S, 'RegExp', { escape: function escape(it) { return $re(it); } }); - - -/***/ }), -/* 331 */ -/***/ (function(module, exports) { - - module.exports = function (regExp, replace) { - var replacer = replace === Object(replace) ? function (part) { - return replace[part]; - } : replace; - return function (it) { - return String(it).replace(regExp, replacer); - }; - }; - - -/***/ }), -/* 332 */ -/***/ (function(module, exports, __webpack_require__) { - - var BSON = __webpack_require__(333), - Binary = __webpack_require__(356), - Code = __webpack_require__(351), - DBRef = __webpack_require__(355), - Decimal128 = __webpack_require__(352), - Double = __webpack_require__(336), - Int32 = __webpack_require__(350), - Long = __webpack_require__(335), - Map = __webpack_require__(334), - MaxKey = __webpack_require__(354), - MinKey = __webpack_require__(353), - ObjectId = __webpack_require__(338), - BSONRegExp = __webpack_require__(348), - Symbol = __webpack_require__(349), - Timestamp = __webpack_require__(337); - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Add BSON types to function creation - BSON.Binary = Binary; - BSON.Code = Code; - BSON.DBRef = DBRef; - BSON.Decimal128 = Decimal128; - BSON.Double = Double; - BSON.Int32 = Int32; - BSON.Long = Long; - BSON.Map = Map; - BSON.MaxKey = MaxKey; - BSON.MinKey = MinKey; - BSON.ObjectId = ObjectId; - BSON.ObjectID = ObjectId; - BSON.BSONRegExp = BSONRegExp; - BSON.Symbol = Symbol; - BSON.Timestamp = Timestamp; - - // Return the BSON - module.exports = BSON; - -/***/ }), -/* 333 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var Map = __webpack_require__(334), - Long = __webpack_require__(335), - Double = __webpack_require__(336), - Timestamp = __webpack_require__(337), - ObjectID = __webpack_require__(338), - BSONRegExp = __webpack_require__(348), - Symbol = __webpack_require__(349), - Int32 = __webpack_require__(350), - Code = __webpack_require__(351), - Decimal128 = __webpack_require__(352), - MinKey = __webpack_require__(353), - MaxKey = __webpack_require__(354), - DBRef = __webpack_require__(355), - Binary = __webpack_require__(356); - - // Parts of the parser - var deserialize = __webpack_require__(357), - serializer = __webpack_require__(358), - calculateObjectSize = __webpack_require__(360), - utils = __webpack_require__(344); - - /** - * @ignore - * @api private - */ - // Default Max Size - var MAXSIZE = 1024 * 1024 * 17; - - // Current Internal Temporary Serialization Buffer - var buffer = utils.allocBuffer(MAXSIZE); - - var BSON = function () {}; - - /** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ - BSON.prototype.serialize = function serialize(object, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = utils.allocBuffer(minInternalBufferSize); - } - - // Attempt to serialize - var serializationIndex = serializer(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); - // Create the final buffer - var finishedBuffer = utils.allocBuffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; - }; - - /** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - * @api public - */ - BSON.prototype.serializeWithBufferAndIndex = function (object, finalBuffer, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - - // Attempt to serialize - var serializationIndex = serializer(finalBuffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); - - // Return the index - return serializationIndex - 1; - }; - - /** - * Deserialize data as BSON. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ - BSON.prototype.deserialize = function (buffer, options) { - return deserialize(buffer, options); - }; - - /** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ - BSON.prototype.calculateObjectSize = function (object, options) { - options = options || {}; - - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); - }; - - /** - * Deserialize stream data as BSON documents. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ - BSON.prototype.deserializeStream = function (data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = this.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; - }; - - /** - * @ignore - * @api private - */ - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // Return BSON - module.exports = BSON; - module.exports.Code = Code; - module.exports.Map = Map; - module.exports.Symbol = Symbol; - module.exports.BSON = BSON; - module.exports.DBRef = DBRef; - module.exports.Binary = Binary; - module.exports.ObjectID = ObjectID; - module.exports.Long = Long; - module.exports.Timestamp = Timestamp; - module.exports.Double = Double; - module.exports.Int32 = Int32; - module.exports.MinKey = MinKey; - module.exports.MaxKey = MaxKey; - module.exports.BSONRegExp = BSONRegExp; - module.exports.Decimal128 = Decimal128; - -/***/ }), -/* 334 */ -/***/ (function(module, exports) { - - /* WEBPACK VAR INJECTION */(function(global) {'use strict'; - - // We have an ES6 Map available, return the native instance - - if (typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; - } else { - // We will return a polyfill - var Map = function (array) { - this._keys = []; - this._values = {}; - - for (var i = 0; i < array.length; i++) { - if (array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - }; - - Map.prototype.clear = function () { - this._keys = []; - this._values = {}; - }; - - Map.prototype.delete = function (key) { - var value = this._values[key]; - if (value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - - Map.prototype.entries = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.forEach = function (callback, self) { - self = self || this; - - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - - Map.prototype.get = function (key) { - return this._values[key] ? this._values[key].v : undefined; - }; - - Map.prototype.has = function (key) { - return this._values[key] != null; - }; - - Map.prototype.keys = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.set = function (key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - - Map.prototype.values = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable: true, - get: function () { - return this._keys.length; - } - }); - - module.exports = Map; - module.exports.Map = Map; - } - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 335 */ -/***/ (function(module, exports) { - - // Licensed under the Apache License, Version 2.0 (the "License"); - // you may not use this file except in compliance with the License. - // You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - // Copyright 2009 Google Inc. All Rights Reserved - - /** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Long. - * @param {number} high the high (signed) 32 bits of the Long. - * @return {Long} - */ - function Long(low, high) { - if (!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. - } - - /** - * Return the int value. - * - * @method - * @return {number} the value, assuming it is a 32-bit integer. - */ - Long.prototype.toInt = function () { - return this.low_; - }; - - /** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ - Long.prototype.toNumber = function () { - return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); - }; - - /** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ - Long.prototype.toJSON = function () { - return this.toString(); - }; - - /** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ - Long.prototype.toString = function (opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } - }; - - /** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ - Long.prototype.getHighBits = function () { - return this.high_; - }; - - /** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ - Long.prototype.getLowBits = function () { - return this.low_; - }; - - /** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ - Long.prototype.getLowBitsUnsigned = function () { - return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; - }; - - /** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Long. - */ - Long.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & 1 << bit) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } - }; - - /** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ - Long.prototype.isZero = function () { - return this.high_ === 0 && this.low_ === 0; - }; - - /** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ - Long.prototype.isNegative = function () { - return this.high_ < 0; - }; - - /** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ - Long.prototype.isOdd = function () { - return (this.low_ & 1) === 1; - }; - - /** - * Return whether this Long equals the other - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long equals the other - */ - Long.prototype.equals = function (other) { - return this.high_ === other.high_ && this.low_ === other.low_; - }; - - /** - * Return whether this Long does not equal the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long does not equal the other. - */ - Long.prototype.notEquals = function (other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; - }; - - /** - * Return whether this Long is less than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than the other. - */ - Long.prototype.lessThan = function (other) { - return this.compare(other) < 0; - }; - - /** - * Return whether this Long is less than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than or equal to the other. - */ - Long.prototype.lessThanOrEqual = function (other) { - return this.compare(other) <= 0; - }; - - /** - * Return whether this Long is greater than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than the other. - */ - Long.prototype.greaterThan = function (other) { - return this.compare(other) > 0; - }; - - /** - * Return whether this Long is greater than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than or equal to the other. - */ - Long.prototype.greaterThanOrEqual = function (other) { - return this.compare(other) >= 0; - }; - - /** - * Compares this Long with the given one. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ - Long.prototype.compare = function (other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } - }; - - /** - * The negation of this value. - * - * @method - * @return {Long} the negation of this value. - */ - Long.prototype.negate = function () { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } - }; - - /** - * Returns the sum of this and the given Long. - * - * @method - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - */ - Long.prototype.add = function (other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns the difference of this and the given Long. - * - * @method - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - */ - Long.prototype.subtract = function (other) { - return this.add(other.negate()); - }; - - /** - * Returns the product of this and the given Long. - * - * @method - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - */ - Long.prototype.multiply = function (other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns this Long divided by the given one. - * - * @method - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - */ - Long.prototype.div = function (other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; - }; - - /** - * Returns this Long modulo the given one. - * - * @method - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - */ - Long.prototype.modulo = function (other) { - return this.subtract(this.div(other).multiply(other)); - }; - - /** - * The bitwise-NOT of this value. - * - * @method - * @return {Long} the bitwise-NOT of this value. - */ - Long.prototype.not = function () { - return Long.fromBits(~this.low_, ~this.high_); - }; - - /** - * Returns the bitwise-AND of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - */ - Long.prototype.and = function (other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); - }; - - /** - * Returns the bitwise-OR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - */ - Long.prototype.or = function (other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); - }; - - /** - * Returns the bitwise-XOR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - */ - Long.prototype.xor = function (other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); - }; - - /** - * Returns this Long with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - */ - Long.prototype.shiftLeft = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); - } else { - return Long.fromBits(0, low << numBits - 32); - } - } - }; - - /** - * Returns this Long with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - */ - Long.prototype.shiftRight = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); - } else { - return Long.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); - } - } - }; - - /** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ - Long.prototype.shiftRightUnsigned = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); - } else if (numBits === 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> numBits - 32, 0); - } - } - }; - - /** - * Returns a Long representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - */ - Long.fromInt = function (value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; - }; - - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Long} the corresponding Long value. - */ - Long.fromNumber = function (value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long(value % Long.TWO_PWR_32_DBL_ | 0, value / Long.TWO_PWR_32_DBL_ | 0); - } - }; - - /** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - */ - Long.fromBits = function (lowBits, highBits) { - return new Long(lowBits, highBits); - }; - - /** - * Returns a Long representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Long. - * @param {number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - */ - Long.fromString = function (str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; - }; - - // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the - // from* methods on which they depend. - - /** - * A cache of the Long representations of small integer values. - * @type {Object} - * @ignore - */ - Long.INT_CACHE_ = {}; - - // NOTE: the compiler should inline these constant values below and then remove - // these variables, so there should be no runtime penalty for these. - - /** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ - Long.TWO_PWR_16_DBL_ = 1 << 16; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_24_DBL_ = 1 << 24; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - - /** @type {Long} */ - Long.ZERO = Long.fromInt(0); - - /** @type {Long} */ - Long.ONE = Long.fromInt(1); - - /** @type {Long} */ - Long.NEG_ONE = Long.fromInt(-1); - - /** @type {Long} */ - Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); - - /** @type {Long} */ - Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - - /** - * @type {Long} - * @ignore - */ - Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - - /** - * Expose. - */ - module.exports = Long; - module.exports.Long = Long; - -/***/ }), -/* 336 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON Double type. - * - * @class - * @param {number} value the number we want to represent as a double. - * @return {Double} - */ - function Double(value) { - if (!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; - } - - /** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ - Double.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Double.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Double; - module.exports.Double = Double; - -/***/ }), -/* 337 */ -/***/ (function(module, exports) { - - // Licensed under the Apache License, Version 2.0 (the "License"); - // you may not use this file except in compliance with the License. - // You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - // Copyright 2009 Google Inc. All Rights Reserved - - /** - * This type is for INTERNAL use in MongoDB only and should not be used in applications. - * The appropriate corresponding type is the JavaScript Date type. - * - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Timestamp. - * @param {number} high the high (signed) 32 bits of the Timestamp. - */ - function Timestamp(low, high) { - if (!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. - } - - /** - * Return the int value. - * - * @return {number} the value, assuming it is a 32-bit integer. - */ - Timestamp.prototype.toInt = function () { - return this.low_; - }; - - /** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ - Timestamp.prototype.toNumber = function () { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); - }; - - /** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ - Timestamp.prototype.toJSON = function () { - return this.toString(); - }; - - /** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ - Timestamp.prototype.toString = function (opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } - }; - - /** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ - Timestamp.prototype.getHighBits = function () { - return this.high_; - }; - - /** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ - Timestamp.prototype.getLowBits = function () { - return this.low_; - }; - - /** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ - Timestamp.prototype.getLowBitsUnsigned = function () { - return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; - }; - - /** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. - */ - Timestamp.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & 1 << bit) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } - }; - - /** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ - Timestamp.prototype.isZero = function () { - return this.high_ === 0 && this.low_ === 0; - }; - - /** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ - Timestamp.prototype.isNegative = function () { - return this.high_ < 0; - }; - - /** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ - Timestamp.prototype.isOdd = function () { - return (this.low_ & 1) === 1; - }; - - /** - * Return whether this Timestamp equals the other - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp equals the other - */ - Timestamp.prototype.equals = function (other) { - return this.high_ === other.high_ && this.low_ === other.low_; - }; - - /** - * Return whether this Timestamp does not equal the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp does not equal the other. - */ - Timestamp.prototype.notEquals = function (other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; - }; - - /** - * Return whether this Timestamp is less than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than the other. - */ - Timestamp.prototype.lessThan = function (other) { - return this.compare(other) < 0; - }; - - /** - * Return whether this Timestamp is less than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than or equal to the other. - */ - Timestamp.prototype.lessThanOrEqual = function (other) { - return this.compare(other) <= 0; - }; - - /** - * Return whether this Timestamp is greater than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than the other. - */ - Timestamp.prototype.greaterThan = function (other) { - return this.compare(other) > 0; - }; - - /** - * Return whether this Timestamp is greater than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than or equal to the other. - */ - Timestamp.prototype.greaterThanOrEqual = function (other) { - return this.compare(other) >= 0; - }; - - /** - * Compares this Timestamp with the given one. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ - Timestamp.prototype.compare = function (other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } - }; - - /** - * The negation of this value. - * - * @method - * @return {Timestamp} the negation of this value. - */ - Timestamp.prototype.negate = function () { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } - }; - - /** - * Returns the sum of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - */ - Timestamp.prototype.add = function (other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns the difference of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - */ - Timestamp.prototype.subtract = function (other) { - return this.add(other.negate()); - }; - - /** - * Returns the product of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - */ - Timestamp.prototype.multiply = function (other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns this Timestamp divided by the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - */ - Timestamp.prototype.div = function (other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; - }; - - /** - * Returns this Timestamp modulo the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - */ - Timestamp.prototype.modulo = function (other) { - return this.subtract(this.div(other).multiply(other)); - }; - - /** - * The bitwise-NOT of this value. - * - * @method - * @return {Timestamp} the bitwise-NOT of this value. - */ - Timestamp.prototype.not = function () { - return Timestamp.fromBits(~this.low_, ~this.high_); - }; - - /** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - */ - Timestamp.prototype.and = function (other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); - }; - - /** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - */ - Timestamp.prototype.or = function (other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); - }; - - /** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - */ - Timestamp.prototype.xor = function (other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); - }; - - /** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - */ - Timestamp.prototype.shiftLeft = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); - } else { - return Timestamp.fromBits(0, low << numBits - 32); - } - } - }; - - /** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - */ - Timestamp.prototype.shiftRight = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); - } else { - return Timestamp.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); - } - } - }; - - /** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ - Timestamp.prototype.shiftRightUnsigned = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); - } else if (numBits === 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> numBits - 32, 0); - } - } - }; - - /** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromInt = function (value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; - }; - - /** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromNumber = function (value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp(value % Timestamp.TWO_PWR_32_DBL_ | 0, value / Timestamp.TWO_PWR_32_DBL_ | 0); - } - }; - - /** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromBits = function (lowBits, highBits) { - return new Timestamp(lowBits, highBits); - }; - - /** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Timestamp. - * @param {number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromString = function (str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; - }; - - // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the - // from* methods on which they depend. - - /** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @ignore - */ - Timestamp.INT_CACHE_ = {}; - - // NOTE: the compiler should inline these constant values below and then remove - // these variables, so there should be no runtime penalty for these. - - /** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - - /** @type {Timestamp} */ - Timestamp.ZERO = Timestamp.fromInt(0); - - /** @type {Timestamp} */ - Timestamp.ONE = Timestamp.fromInt(1); - - /** @type {Timestamp} */ - Timestamp.NEG_ONE = Timestamp.fromInt(-1); - - /** @type {Timestamp} */ - Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); - - /** @type {Timestamp} */ - Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - - /** - * @type {Timestamp} - * @ignore - */ - Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - - /** - * Expose. - */ - module.exports = Timestamp; - module.exports.Timestamp = Timestamp; - -/***/ }), -/* 338 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer, process) {// Custom inspect property name / symbol. - var inspect = 'inspect'; - - var utils = __webpack_require__(344); - - /** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - * @ignore - */ - var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); - - // Regular expression that checks for hex value - var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); - - // Check if buffer exists - try { - if (Buffer && Buffer.from) { - var hasBufferType = true; - inspect = __webpack_require__(345).inspect.custom || 'inspect'; - } - } catch (err) { - hasBufferType = false; - } - - /** - * Create a new ObjectID instance - * - * @class - * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. - * @property {number} generationTime The generation time of this ObjectId instance - * @return {ObjectID} instance of ObjectID. - */ - var ObjectID = function ObjectID(id) { - // Duck-typing to support ObjectId from different npm packages - if (id instanceof ObjectID) return id; - if (!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - - // The most common usecase (blank id, new objectId instance) - if (id == null || typeof id === 'number') { - // Generate a new id - this.id = this.generate(id); - // If we are caching the hex string - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - // Return the object - return; - } - - // Check if the passed in id is valid - var valid = ObjectID.isValid(id); - - // Throw an error if it's not a valid setup - if (!valid && id != null) { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { - return new ObjectID(utils.toBuffer(id, 'hex')); - } else if (valid && typeof id === 'string' && id.length === 24) { - return ObjectID.createFromHexString(id); - } else if (id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if (id != null && id.toHexString) { - // Duck-typing to support ObjectId from different npm packages - return id; - } else { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - }; - - // Allow usage of ObjectId as well as ObjectID - // var ObjectId = ObjectID; - - // Precomputed hex table enables speedy hex string conversion - var hexTable = []; - for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); - } - - /** - * Return the ObjectID id as a 24 byte hex string representation - * - * @method - * @return {string} return the 24 byte hex string representation. - */ - ObjectID.prototype.toHexString = function () { - if (ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - if (!this.id || !this.id.length) { - throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']'); - } - - if (this.id instanceof _Buffer) { - hexString = convertToHex(this.id); - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - } - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - }; - - /** - * Update the ObjectID index used in generating new ObjectID's on the driver - * - * @method - * @return {number} returns next index value. - * @ignore - */ - ObjectID.prototype.get_inc = function () { - return ObjectID.index = (ObjectID.index + 1) % 0xffffff; - }; - - /** - * Update the ObjectID index used in generating new ObjectID's on the driver - * - * @method - * @return {number} returns next index value. - * @ignore - */ - ObjectID.prototype.getInc = function () { - return this.get_inc(); - }; - - /** - * Generate a 12 byte id buffer used in ObjectID's - * - * @method - * @param {number} [time] optional parameter allowing to pass in a second based timestamp. - * @return {Buffer} return the 12 byte id buffer string. - */ - ObjectID.prototype.generate = function (time) { - if ('number' !== typeof time) { - time = ~~(Date.now() / 1000); - } - - // Use pid - var pid = (typeof process === 'undefined' || process.pid === 1 ? Math.floor(Math.random() * 100000) : process.pid) % 0xffff; - var inc = this.get_inc(); - // Buffer used - var buffer = utils.allocBuffer(12); - // Encode time - buffer[3] = time & 0xff; - buffer[2] = time >> 8 & 0xff; - buffer[1] = time >> 16 & 0xff; - buffer[0] = time >> 24 & 0xff; - // Encode machine - buffer[6] = MACHINE_ID & 0xff; - buffer[5] = MACHINE_ID >> 8 & 0xff; - buffer[4] = MACHINE_ID >> 16 & 0xff; - // Encode pid - buffer[8] = pid & 0xff; - buffer[7] = pid >> 8 & 0xff; - // Encode index - buffer[11] = inc & 0xff; - buffer[10] = inc >> 8 & 0xff; - buffer[9] = inc >> 16 & 0xff; - // Return the buffer - return buffer; - }; - - /** - * Converts the id into a 24 byte hex string for printing - * - * @param {String} format The Buffer toString format parameter. - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype.toString = function (format) { - // Is the id a buffer then use the buffer toString method to return the format - if (this.id && this.id.copy) { - return this.id.toString(typeof format === 'string' ? format : 'hex'); - } - - // if(this.buffer ) - return this.toHexString(); - }; - - /** - * Converts to a string representation of this Id. - * - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype[inspect] = ObjectID.prototype.toString; - - /** - * Converts to its JSON representation. - * - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype.toJSON = function () { - return this.toHexString(); - }; - - /** - * Compares the equality of this ObjectID with `otherID`. - * - * @method - * @param {object} otherID ObjectID instance to compare against. - * @return {boolean} the result of comparing two ObjectID's - */ - ObjectID.prototype.equals = function equals(otherId) { - // var id; - - if (otherId instanceof ObjectID) { - return this.toString() === otherId.toString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12 && this.id instanceof _Buffer) { - return otherId === this.id.toString('binary'); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { - return otherId === this.id; - } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { - return otherId.toHexString() === this.toHexString(); - } else { - return false; - } - }; - - /** - * Returns the generation date (accurate up to the second) that this ID was generated. - * - * @method - * @return {date} the generation date - */ - ObjectID.prototype.getTimestamp = function () { - var timestamp = new Date(); - var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - }; - - /** - * @ignore - */ - ObjectID.index = ~~(Math.random() * 0xffffff); - - /** - * @ignore - */ - ObjectID.createPk = function createPk() { - return new ObjectID(); - }; - - /** - * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. - * - * @method - * @param {number} time an integer number representing a number of seconds. - * @return {ObjectID} return the created ObjectID - */ - ObjectID.createFromTime = function createFromTime(time) { - var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer[3] = time & 0xff; - buffer[2] = time >> 8 & 0xff; - buffer[1] = time >> 16 & 0xff; - buffer[0] = time >> 24 & 0xff; - // Return the new objectId - return new ObjectID(buffer); - }; - - // Lookup tables - //var encodeLookup = '0123456789abcdef'.split(''); - var decodeLookup = []; - i = 0; - while (i < 10) decodeLookup[0x30 + i] = i++; - while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; - - var _Buffer = Buffer; - var convertToHex = function (bytes) { - return bytes.toString('hex'); - }; - - /** - * Creates an ObjectID from a hex string representation of an ObjectID. - * - * @method - * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. - * @return {ObjectID} return the created ObjectID - */ - ObjectID.createFromHexString = function createFromHexString(string) { - // Throw an error if it's not a valid setup - if (typeof string === 'undefined' || string != null && string.length !== 24) { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - - // Use Buffer.from method if available - if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); - - // Calculate lengths - var array = new _Buffer(12); - var n = 0; - var i = 0; - - while (i < 24) { - array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]; - } - - return new ObjectID(array); - }; - - /** - * Checks if a value is a valid bson ObjectId - * - * @method - * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. - */ - ObjectID.isValid = function isValid(id) { - if (id == null) return false; - - if (typeof id === 'number') { - return true; - } - - if (typeof id === 'string') { - return id.length === 12 || id.length === 24 && checkForHexRegExp.test(id); - } - - if (id instanceof ObjectID) { - return true; - } - - if (id instanceof _Buffer) { - return true; - } - - // Duck-Typing detection of ObjectId like objects - if (id.toHexString) { - return id.id.length === 12 || id.id.length === 24 && checkForHexRegExp.test(id.id); - } - - return false; - }; - - /** - * @ignore - */ - Object.defineProperty(ObjectID.prototype, 'generationTime', { - enumerable: true, - get: function () { - return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - }, - set: function (value) { - // Encode time into first 4 bytes - this.id[3] = value & 0xff; - this.id[2] = value >> 8 & 0xff; - this.id[1] = value >> 16 & 0xff; - this.id[0] = value >> 24 & 0xff; - } - }); - - /** - * Expose. - */ - module.exports = ObjectID; - module.exports.ObjectID = ObjectID; - module.exports.ObjectId = ObjectID; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(339).Buffer, __webpack_require__(343))) - -/***/ }), -/* 339 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - /* eslint-disable no-proto */ - - 'use strict' - - var base64 = __webpack_require__(340) - var ieee754 = __webpack_require__(341) - var isArray = __webpack_require__(342) - - exports.Buffer = Buffer - exports.SlowBuffer = SlowBuffer - exports.INSPECT_MAX_BYTES = 50 - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - - /* - * Export kMaxLength after typed array support is determined. - */ - exports.kMaxLength = kMaxLength() - - function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } - } - - function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that - } - - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) - } - - Buffer.poolSize = 8192 // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr - } - - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) - } - - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } - } - - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - } - - function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - } - - function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 - } - } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) - } - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - } - - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - var actual = that.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) - } - - return that - } - - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that - } - - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that - } - - function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len) - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - - function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) - } - - Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) - } - - Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } - } - - Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer - } - - function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - Buffer.byteLength = byteLength - - function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer.prototype._isBuffer = true - - function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i - } - - Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this - } - - Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this - } - - Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this - } - - Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - } - - Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 - } - - Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' - } - - Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') - } - - function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 - } - - Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - } - - Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) - } - - Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - } - - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i - } - - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } - - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } - - function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) - } - - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } - - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } - - Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - - Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } - } - - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } - } - - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) - } - - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000 - - function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res - } - - function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret - } - - function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret - } - - function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out - } - - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res - } - - Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] - } - } - - return newBuf - } - - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') - } - - Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val - } - - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val - } - - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] - } - - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) - } - - Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] - } - - Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - } - - Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - } - - Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - } - - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - } - - Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - } - - Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) - } - - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) - } - - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) - } - - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) - } - - function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') - } - - Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 - } - - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } - } - - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } - } - - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 - } - - Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') - } - - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 - } - - Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - } - - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 - } - - Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - } - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } - - return len - } - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this - } - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str - } - - function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes - } - - function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray - } - - function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray - } - - function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) - } - - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i - } - - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 340 */ -/***/ (function(module, exports) { - - 'use strict' - - exports.byteLength = byteLength - exports.toByteArray = toByteArray - exports.fromByteArray = fromByteArray - - var lookup = [] - var revLookup = [] - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i - } - - // Support decoding URL-safe base64 strings, as Node.js does. - // See: https://en.wikipedia.org/wiki/Base64#URL_applications - revLookup['-'.charCodeAt(0)] = 62 - revLookup['_'.charCodeAt(0)] = 63 - - function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] - } - - // base64 is 4/3 + up to two characters of the original data - function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen - } - - function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen - } - - function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr - } - - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] - } - - function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') - } - - function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk( - uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) - )) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') - } - - -/***/ }), -/* 341 */ -/***/ (function(module, exports) { - - exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) - } - - exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 - } - - -/***/ }), -/* 342 */ -/***/ (function(module, exports) { - - var toString = {}.toString; - - module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; - - -/***/ }), -/* 343 */ -/***/ (function(module, exports) { - - // shim for using process in browser - var process = module.exports = {}; - - // cached from whatever global is present so that test runners that stub it - // don't break things. But we need to wrap it in a try catch in case it is - // wrapped in strict mode code which doesn't define any globals. It's inside a - // function because try/catches deoptimize in certain engines. - - var cachedSetTimeout; - var cachedClearTimeout; - - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); - } - (function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } - } ()) - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - - process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - }; - - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - process.title = 'browser'; - process.browser = true; - process.env = {}; - process.argv = []; - process.version = ''; // empty string to avoid regexp issues - process.versions = {}; - - function noop() {} - - process.on = noop; - process.addListener = noop; - process.once = noop; - process.off = noop; - process.removeListener = noop; - process.removeAllListeners = noop; - process.emit = noop; - process.prependListener = noop; - process.prependOnceListener = noop; - - process.listeners = function (name) { return [] } - - process.binding = function (name) { - throw new Error('process.binding is not supported'); - }; - - process.cwd = function () { return '/' }; - process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); - }; - process.umask = function() { return 0; }; - - -/***/ }), -/* 344 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - /** - * Normalizes our expected stringified form of a function across versions of node - * @param {Function} fn The function to stringify - */ - - function normalizedFunctionString(fn) { - return fn.toString().replace(/function *\(/, 'function ('); - } - - function newBuffer(item, encoding) { - return new Buffer(item, encoding); - } - - function allocBuffer() { - return Buffer.alloc.apply(Buffer, arguments); - } - - function toBuffer() { - return Buffer.from.apply(Buffer, arguments); - } - - module.exports = { - normalizedFunctionString: normalizedFunctionString, - allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, - toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer - }; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(339).Buffer)) - -/***/ }), -/* 345 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var formatRegExp = /%[sdj%]/g; - exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; - }; - - - // Mark that a method should not be used. - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; - }; - - - var debugs = {}; - var debugEnviron; - exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; - }; - - - /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ - /* legacy: obj, showHidden, depth, colors*/ - function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } - exports.inspect = inspect; - - - // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] - }; - - // Don't use 'blue' not visible on cmd.exe - inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' - }; - - - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } - } - - - function stylizeNoColor(str, styleType) { - return str; - } - - - function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; - } - - - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); - } - - - function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); - } - - - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } - - - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; - } - - - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; - } - - - function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } - - - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { - return Array.isArray(ar); - } - exports.isArray = isArray; - - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - exports.isBoolean = isBoolean; - - function isNull(arg) { - return arg === null; - } - exports.isNull = isNull; - - function isNullOrUndefined(arg) { - return arg == null; - } - exports.isNullOrUndefined = isNullOrUndefined; - - function isNumber(arg) { - return typeof arg === 'number'; - } - exports.isNumber = isNumber; - - function isString(arg) { - return typeof arg === 'string'; - } - exports.isString = isString; - - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - exports.isSymbol = isSymbol; - - function isUndefined(arg) { - return arg === void 0; - } - exports.isUndefined = isUndefined; - - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } - exports.isRegExp = isRegExp; - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - exports.isObject = isObject; - - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } - exports.isDate = isDate; - - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } - exports.isError = isError; - - function isFunction(arg) { - return typeof arg === 'function'; - } - exports.isFunction = isFunction; - - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - exports.isPrimitive = isPrimitive; - - exports.isBuffer = __webpack_require__(346); - - function objectToString(o) { - return Object.prototype.toString.call(o); - } - - - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); - } - - - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - - // 26 Feb 16:19:34 - function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); - } - - - // log is just a thin wrapper to console.log that prepends a timestamp - exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); - }; - - - /** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ - exports.inherits = __webpack_require__(347); - - exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; - }; - - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(343))) - -/***/ }), -/* 346 */ -/***/ (function(module, exports) { - - module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; - } - -/***/ }), -/* 347 */ -/***/ (function(module, exports) { - - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } - - -/***/ }), -/* 348 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ - function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern || ''; - this.options = options || ''; - - // Validate options - for (var i = 0; i < this.options.length; i++) { - if (!(this.options[i] === 'i' || this.options[i] === 'm' || this.options[i] === 'x' || this.options[i] === 'l' || this.options[i] === 's' || this.options[i] === 'u')) { - throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); - } - } - } - - module.exports = BSONRegExp; - module.exports.BSONRegExp = BSONRegExp; - -/***/ }), -/* 349 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {// Custom inspect property name / symbol. - var inspect = Buffer ? __webpack_require__(345).inspect.custom || 'inspect' : 'inspect'; - - /** - * A class representation of the BSON Symbol type. - * - * @class - * @deprecated - * @param {string} value the string representing the symbol. - * @return {Symbol} - */ - function Symbol(value) { - if (!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; - } - - /** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ - Symbol.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype.toString = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype[inspect] = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Symbol; - module.exports.Symbol = Symbol; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(339).Buffer)) - -/***/ }), -/* 350 */ -/***/ (function(module, exports) { - - /** - * A class representation of a BSON Int32 type. - * - * @class - * @param {number} value the number we want to represent as an int32. - * @return {Int32} - */ - var Int32 = function (value) { - if (!(this instanceof Int32)) return new Int32(value); - - this._bsontype = 'Int32'; - this.value = value; - }; - - /** - * Access the number value. - * - * @method - * @return {number} returns the wrapped int32 number. - */ - Int32.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Int32.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Int32; - module.exports.Int32 = Int32; - -/***/ }), -/* 351 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON Code type. - * - * @class - * @param {(string|function)} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ - var Code = function Code(code, scope) { - if (!(this instanceof Code)) return new Code(code, scope); - this._bsontype = 'Code'; - this.code = code; - this.scope = scope; - }; - - /** - * @ignore - */ - Code.prototype.toJSON = function () { - return { scope: this.scope, code: this.code }; - }; - - module.exports = Code; - module.exports.Code = Code; - -/***/ }), -/* 352 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var Long = __webpack_require__(335); - - var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; - var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; - var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - - var EXPONENT_MAX = 6111; - var EXPONENT_MIN = -6176; - var EXPONENT_BIAS = 6176; - var MAX_DIGITS = 34; - - // Nan value bits as 32 bit values (due to lack of longs) - var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - // Infinity value bits 32 bit values (due to lack of longs) - var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - - var EXPONENT_REGEX = /^([-+])?(\d+)?$/; - - var utils = __webpack_require__(344); - - // Detect if the value is a digit - var isDigit = function (value) { - return !isNaN(parseInt(value, 10)); - }; - - // Divide two uint128 values - var divideu128 = function (value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - var i = 0; - - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - - for (i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low_; - _rem = _rem.modulo(DIVISOR); - } - - return { quotient: value, rem: _rem }; - }; - - // Multiply two Long values and return the 128 bit value - var multiply64x2 = function (left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - - // Return the 128 bit result - return { high: productHigh, low: productLow }; - }; - - var lessThan = function (left, right) { - // Make values unsigned - var uhleft = left.high_ >>> 0; - var uhright = right.high_ >>> 0; - - // Compare high bits first - if (uhleft < uhright) { - return true; - } else if (uhleft === uhright) { - var ulleft = left.low_ >>> 0; - var ulright = right.low_ >>> 0; - if (ulleft < ulright) return true; - } - - return false; - }; - - // var longtoHex = function(value) { - // var buffer = utils.allocBuffer(8); - // var index = 0; - // // Encode the low 64 bits of the decimal - // // Encode low bits - // buffer[index++] = value.low_ & 0xff; - // buffer[index++] = (value.low_ >> 8) & 0xff; - // buffer[index++] = (value.low_ >> 16) & 0xff; - // buffer[index++] = (value.low_ >> 24) & 0xff; - // // Encode high bits - // buffer[index++] = value.high_ & 0xff; - // buffer[index++] = (value.high_ >> 8) & 0xff; - // buffer[index++] = (value.high_ >> 16) & 0xff; - // buffer[index++] = (value.high_ >> 24) & 0xff; - // return buffer.reverse().toString('hex'); - // }; - - // var int32toHex = function(value) { - // var buffer = utils.allocBuffer(4); - // var index = 0; - // // Encode the low 64 bits of the decimal - // // Encode low bits - // buffer[index++] = value & 0xff; - // buffer[index++] = (value >> 8) & 0xff; - // buffer[index++] = (value >> 16) & 0xff; - // buffer[index++] = (value >> 24) & 0xff; - // return buffer.reverse().toString('hex'); - // }; - - /** - * A class representation of the BSON Decimal128 type. - * - * @class - * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. - * @return {Double} - */ - var Decimal128 = function (bytes) { - this._bsontype = 'Decimal128'; - this.bytes = bytes; - }; - - /** - * Create a Decimal128 instance from a string representation - * - * @method - * @param {string} string a numeric string representation. - * @return {Decimal128} returns a Decimal128 instance. - */ - Decimal128.fromString = function (string) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = [0, 0]; - // The low 17 digits of the significand - var significandLow = [0, 0]; - // The biased exponent - var biasedExponent = 0; - - // Read index - var index = 0; - - // Trim the string - string = string.trim(); - - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (string.length >= 7000) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Results - var stringMatch = string.match(PARSE_STRING_REGEXP); - var infMatch = string.match(PARSE_INF_REGEXP); - var nanMatch = string.match(PARSE_NAN_REGEXP); - - // Validate the string - if (!stringMatch && !infMatch && !nanMatch || string.length === 0) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Check if we have an illegal exponent format - if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Get the negative or positive sign - if (string[index] === '+' || string[index] === '-') { - isNegative = string[index++] === '-'; - } - - // Check if user passed Infinity or NaN - if (!isDigit(string[index]) && string[index] !== '.') { - if (string[index] === 'i' || string[index] === 'I') { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } else if (string[index] === 'N') { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - } - - // Read all the digits - while (isDigit(string[index]) || string[index] === '.') { - if (string[index] === '.') { - if (sawRadix) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - sawRadix = true; - index = index + 1; - continue; - } - - if (nDigitsStored < 34) { - if (string[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - - foundNonZero = true; - - // Only store 34 digits - digits[digitsInsert++] = parseInt(string[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - - if (foundNonZero) { - nDigits = nDigits + 1; - } - - if (sawRadix) { - radixPosition = radixPosition + 1; - } - - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - - if (sawRadix && !nDigitsRead) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Read exponent if exists - if (string[index] === 'e' || string[index] === 'E') { - // Read exponent digits - var match = string.substr(++index).match(EXPONENT_REGEX); - - // No digits read - if (!match || !match[2]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Get exponent - exponent = parseInt(match[0], 10); - - // Adjust the index - index = index + match[0].length; - } - - // Return not a number - if (string[index]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - - if (exponent !== 0 && significantDigits !== 1) { - while (string[firstNonZero + significantDigits - 1] === '0') { - significantDigits = significantDigits - 1; - } - } - } - - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; - } - - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - - exponent = exponent - 1; - } - - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit - if (lastDigit === 0) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } else { - // adjust to round - lastDigit = lastDigit - 1; - } - - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - // Check if we have a zero then just hard clamp, otherwise fail - digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { - var endOfString = nDigitsRead; - - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix && exponent === EXPONENT_MIN) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - - var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - - if (roundDigit >= 5) { - roundBit = 1; - - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1; - - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(string[i], 10)) { - roundBit = 1; - break; - } - } - } - } - - if (roundBit) { - var dIdx = lastDigit; - - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } else { - break; - } - } - } - } - - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if (lastDigit - firstDigit < 17) { - dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - - significandLow = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - - significand.low = significand.low.add(significandLow); - - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - - // Encode combination, exponent, and significand. - if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber)) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - - dec.low = significand.low; - - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - - // Encode into a buffer - var buffer = utils.allocBuffer(16); - index = 0; - - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low_ & 0xff; - buffer[index++] = dec.low.low_ >> 8 & 0xff; - buffer[index++] = dec.low.low_ >> 16 & 0xff; - buffer[index++] = dec.low.low_ >> 24 & 0xff; - // Encode high bits - buffer[index++] = dec.low.high_ & 0xff; - buffer[index++] = dec.low.high_ >> 8 & 0xff; - buffer[index++] = dec.low.high_ >> 16 & 0xff; - buffer[index++] = dec.low.high_ >> 24 & 0xff; - - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low_ & 0xff; - buffer[index++] = dec.high.low_ >> 8 & 0xff; - buffer[index++] = dec.high.low_ >> 16 & 0xff; - buffer[index++] = dec.high.low_ >> 24 & 0xff; - // Encode high bits - buffer[index++] = dec.high.high_ & 0xff; - buffer[index++] = dec.high.high_ >> 8 & 0xff; - buffer[index++] = dec.high.high_ >> 16 & 0xff; - buffer[index++] = dec.high.high_ >> 24 & 0xff; - - // Return the new Decimal128 - return new Decimal128(buffer); - }; - - // Extract least significant 5 bits - var COMBINATION_MASK = 0x1f; - // Extract least significant 14 bits - var EXPONENT_MASK = 0x3fff; - // Value of combination field for Inf - var COMBINATION_INFINITY = 30; - // Value of combination field for NaN - var COMBINATION_NAN = 31; - // Value of combination field for NaN - // var COMBINATION_SNAN = 32; - // decimal128 exponent bias - EXPONENT_BIAS = 6176; - - /** - * Create a string representation of the raw Decimal128 value - * - * @method - * @return {string} returns a Decimal128 string representation. - */ - Decimal128.prototype.toString = function () { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - - // bits 0 - 31 - var high; - // bits 32 - 63 - var midh; - // bits 64 - 95 - var midl; - // bits 96 - 127 - var low; - // bits 1 - 5 - var combination; - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) significand[i] = 0; - // read pointer into significand - var index = 0; - - // unbiased exponent - var exponent; - // the exponent if scientific notation is used - var scientific_exponent; - - // true if the number is zero - var is_zero = false; - - // the most signifcant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: new Array(4) }; - // indexing variables - i; - var j, k; - - // Output string - var string = []; - - // Unpack index - index = 0; - - // Buffer reference - var buffer = this.bytes; - - // Unpack the low 64bits into a long - low = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - midl = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack the high 64bits into a long - midh = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - high = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack index - index = 0; - - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - - // Decode combination field and exponent - combination = high >> 26 & COMBINATION_MASK; - - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } else if (combination === COMBINATION_NAN) { - return 'NaN'; - } else { - biased_exponent = high >> 15 & EXPONENT_MASK; - significand_msb = 0x08 + (high >> 14 & 0x01); - } - } else { - significand_msb = high >> 14 & 0x07; - biased_exponent = high >> 17 & EXPONENT_MASK; - } - - exponent = biased_exponent - EXPONENT_BIAS; - - // Create string of significand digits - - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - - if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) { - is_zero = true; - } else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Peform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low_; - - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) continue; - - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } else { - significand_digits = 36; - i = 0; - - while (!significand[index]) { - i++; - significand_digits = significand_digits - 1; - index = index + 1; - } - } - - scientific_exponent = significand_digits - 1 + exponent; - - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - string.push(significand[index++]); - significand_digits = significand_digits - 1; - - if (significand_digits) { - string.push('.'); - } - - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } else { - string.push(scientific_exponent); - } - } else { - // Regular format with no decimal place - if (exponent >= 0) { - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - } else { - var radix_position = significand_digits + exponent; - - // non-zero digits before radix - if (radix_position > 0) { - for (i = 0; i < radix_position; i++) { - string.push(significand[index++]); - } - } else { - string.push('0'); - } - - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - - for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(significand[index++]); - } - } - } - - return string.join(''); - }; - - Decimal128.prototype.toJSON = function () { - return { $numberDecimal: this.toString() }; - }; - - module.exports = Decimal128; - module.exports.Decimal128 = Decimal128; - -/***/ }), -/* 353 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON MinKey type. - * - * @class - * @return {MinKey} A MinKey instance - */ - function MinKey() { - if (!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; - } - - module.exports = MinKey; - module.exports.MinKey = MinKey; - -/***/ }), -/* 354 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON MaxKey type. - * - * @class - * @return {MaxKey} A MaxKey instance - */ - function MaxKey() { - if (!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; - } - - module.exports = MaxKey; - module.exports.MaxKey = MaxKey; - -/***/ }), -/* 355 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON DBRef type. - * - * @class - * @param {string} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {string} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ - function DBRef(namespace, oid, db) { - if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; - } - - /** - * @ignore - * @api private - */ - DBRef.prototype.toJSON = function () { - return { - $ref: this.namespace, - $id: this.oid, - $db: this.db == null ? '' : this.db - }; - }; - - module.exports = DBRef; - module.exports.DBRef = DBRef; - -/***/ }), -/* 356 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies. - * @ignore - */ - - // Test if we're in Node via presence of "global" not absence of "window" - // to support hybrid environments like Electron - if (typeof global !== 'undefined') { - var Buffer = __webpack_require__(339).Buffer; // TODO just use global Buffer - } - - var utils = __webpack_require__(344); - - /** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Binary} - */ - function Binary(buffer, subType) { - if (!(this instanceof Binary)) return new Binary(buffer, subType); - - if (buffer != null && !(typeof buffer === 'string') && !Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array) && !Array.isArray(buffer)) { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - - this._bsontype = 'Binary'; - - if (buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if (buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if (typeof buffer === 'string') { - // Different ways of writing the length of the string for the different types - if (typeof Buffer !== 'undefined') { - this.buffer = utils.toBuffer(buffer); - } else if (typeof Uint8Array !== 'undefined' || Object.prototype.toString.call(buffer) === '[object Array]') { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if (typeof Buffer !== 'undefined') { - this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); - } else if (typeof Uint8Array !== 'undefined') { - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } - } - - /** - * Updates this binary with byte_value. - * - * @method - * @param {string} byte_value a single byte we wish to write. - */ - Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) throw new Error('only accepts single character String, Uint8Array or Array'); - if (typeof byte_value !== 'number' && byte_value < 0 || byte_value > 255) throw new Error('only accepts number in a valid unsigned byte range 0-255'); - - // Decode the byte value once - var decoded_byte = null; - if (typeof byte_value === 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if (byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - buffer = null; - // Create a new buffer (typed or normal array) - if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for (var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } - }; - - /** - * Writes a buffer or string to the binary. - * - * @method - * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. - * @param {number} offset specify the binary of where to write the content. - * @return {null} - */ - Binary.prototype.write = function write(string, offset) { - offset = typeof offset === 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = utils.allocBuffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); - // Copy the content - for (var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length - } else if (typeof Buffer !== 'undefined' && typeof string === 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, offset, 'binary'); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length; - } else if (Object.prototype.toString.call(string) === '[object Uint8Array]' || Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if (typeof string === 'string') { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } - }; - - /** - * Reads **length** bytes starting at **position**. - * - * @method - * @param {number} position read from the given position in the Binary. - * @param {number} length the number of bytes to read. - * @return {Buffer} - */ - Binary.prototype.read = function read(position, length) { - length = length && length > 0 ? length : this.position; - - // Let's return the data based on the type we have - if (this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for (var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; - }; - - /** - * Returns the value of this binary as a string. - * - * @method - * @return {string} - */ - Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if (asRaw && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length === this.position) return this.buffer; - - // If it's a node.js buffer object - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if (asRaw) { - // we support the slice command use it - if (this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for (var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } - }; - - /** - * Length. - * - * @method - * @return {number} the length of the binary. - */ - Binary.prototype.length = function length() { - return this.position; - }; - - /** - * @ignore - */ - Binary.prototype.toJSON = function () { - return this.buffer != null ? this.buffer.toString('base64') : ''; - }; - - /** - * @ignore - */ - Binary.prototype.toString = function (format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; - }; - - /** - * Binary default subtype - * @ignore - */ - var BSON_BINARY_SUBTYPE_DEFAULT = 0; - - /** - * @ignore - */ - var writeStringToArray = function (data) { - // Create a buffer - var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for (var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; - }; - - /** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - */ - var convertArraytoUtf8BinaryString = function (byteArray, startIndex, endIndex) { - var result = ''; - for (var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; - }; - - Binary.BUFFER_SIZE = 256; - - /** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_DEFAULT = 0; - /** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_FUNCTION = 1; - /** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_BYTE_ARRAY = 2; - /** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_UUID_OLD = 3; - /** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_UUID = 4; - /** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_MD5 = 5; - /** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_USER_DEFINED = 128; - - /** - * Expose. - */ - module.exports = Binary; - module.exports.Binary = Binary; - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 357 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var Long = __webpack_require__(335).Long, - Double = __webpack_require__(336).Double, - Timestamp = __webpack_require__(337).Timestamp, - ObjectID = __webpack_require__(338).ObjectID, - Symbol = __webpack_require__(349).Symbol, - Code = __webpack_require__(351).Code, - MinKey = __webpack_require__(353).MinKey, - MaxKey = __webpack_require__(354).MaxKey, - Decimal128 = __webpack_require__(352), - Int32 = __webpack_require__(350), - DBRef = __webpack_require__(355).DBRef, - BSONRegExp = __webpack_require__(348).BSONRegExp, - Binary = __webpack_require__(356).Binary; - - var utils = __webpack_require__(344); - - var deserialize = function (buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - - // Ensure buffer is valid size - if (size < 5 || buffer.length < size || size + index > buffer.length) { - throw new Error('corrupt bson message'); - } - - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); - }; - - var deserializeObject = function (buffer, index, options, isArray) { - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - - if (!cacheFunctionsCrc32) var crc32 = null; - - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - - // Set the start index - var startIndex = index; - - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); - - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - - var done = false; - - // While we have more left data left keep parsing - // while (buffer[index + 1] !== 0) { - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) break; - - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - - index = i + 1; - - if (elementType === BSON.BSON_DATA_STRING) { - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_OID) { - var oid = utils.allocBuffer(12); - buffer.copy(oid, 0, index, index + 12); - object[name] = new ObjectID(oid); - index = index + 12; - } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { - object[name] = new Int32(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); - } else if (elementType === BSON.BSON_DATA_INT) { - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { - object[name] = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_NUMBER) { - object[name] = buffer.readDoubleLE(index); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_DATE) { - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if (elementType === BSON.BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); - object[name] = buffer[index++] === 1; - } else if (elementType === BSON.BSON_DATA_OBJECT) { - var _index = index; - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - if (objectSize <= 0 || objectSize > buffer.length - index) throw new Error('bad embedded document length in bson'); - - // We have a raw value - if (raw) { - object[name] = buffer.slice(index, index + objectSize); - } else { - object[name] = deserializeObject(buffer, _index, options, false); - } - - index = index + objectSize; - } else if (elementType === BSON.BSON_DATA_ARRAY) { - _index = index; - objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - var arrayOptions = options; - - // Stop index - var stopIndex = index + objectSize; - - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - object[name] = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - - if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); - if (index !== stopIndex) throw new Error('corrupted array bson'); - } else if (elementType === BSON.BSON_DATA_UNDEFINED) { - object[name] = undefined; - } else if (elementType === BSON.BSON_DATA_NULL) { - object[name] = null; - } else if (elementType === BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - } else if (elementType === BSON.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = utils.allocBuffer(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; - } else if (elementType === BSON.BSON_DATA_BINARY) { - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var totalBinarySize = binarySize; - var subType = buffer[index++]; - - // Did we have a negative binary size, throw - if (binarySize < 0) throw new Error('Negative binary type element size found'); - - // Is the length longer than the document - if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); - - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - if (promoteBuffers && promoteValues) { - object[name] = buffer.slice(index, index + binarySize); - } else { - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } - } else { - var _buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - - if (promoteBuffers && promoteValues) { - object[name] = _buffer; - } else { - object[name] = new Binary(_buffer, subType); - } - } - - // Update the index - index = index + binarySize; - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - source = buffer.toString('utf8', index, i); - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if (elementType === BSON.BSON_DATA_SYMBOL) { - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { - lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - object[name] = new Timestamp(lowBits, highBits); - } else if (elementType === BSON.BSON_DATA_MIN_KEY) { - object[name] = new MinKey(); - } else if (elementType === BSON.BSON_DATA_MAX_KEY) { - object[name] = new MaxKey(); - } else if (elementType === BSON.BSON_DATA_CODE) { - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString); - } - - // Update parse index position - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new Error('code_w_scope total size shorter minimum expected length'); - } - - // Get the code string size - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - - // Javascript function - functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - _index = index; - // Decode the size of the object document - objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - - // Check if field length is to short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to short, truncating scope'); - } - - // Check if totalSize field is to long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to long, clips outer document'); - } - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } else if (elementType === BSON.BSON_DATA_DBPOINTER) { - // Get the code string size - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - // Namespace - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - - // Read the oid - var oidBuffer = utils.allocBuffer(12); - buffer.copy(oidBuffer, 0, index, index + 12); - oid = new ObjectID(oidBuffer); - - // Update the index - index = index + 12; - - // Split the namespace - var parts = namespace.split('.'); - var db = parts.shift(); - var collection = parts.join('.'); - // Upgrade to DBRef type - object[name] = new DBRef(collection, oid, db); - } else { - throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '", are you using the latest BSON parser'); - } - } - - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) throw new Error('corrupt array bson'); - throw new Error('corrupt object bson'); - } - - // Check if we have a db ref object - if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - return object; - }; - - /** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ - var isolateEvalWithHash = function (functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if (functionCache[hash] == null) { - eval('value = ' + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); - }; - - /** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ - var isolateEval = function (functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval('value = ' + functionString); - return value; - }; - - var BSON = {}; - - /** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ - var functionCache = BSON.functionCache = {}; - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ - BSON.BSON_DATA_UNDEFINED = 6; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_DBPOINTER - **/ - BSON.BSON_DATA_DBPOINTER = 12; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ - BSON.BSON_DATA_DECIMAL128 = 19; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = deserialize; - -/***/ }), -/* 358 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - var writeIEEE754 = __webpack_require__(359).writeIEEE754, - Long = __webpack_require__(335).Long, - Map = __webpack_require__(334), - Binary = __webpack_require__(356).Binary; - - var normalizedFunctionString = __webpack_require__(344).normalizedFunctionString; - - // try { - // var _Buffer = Uint8Array; - // } catch (e) { - // _Buffer = Buffer; - // } - - var regexp = /\x00/; // eslint-disable-line no-control-regex - var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; - - // To ensure that 0.4 of node works correctly - var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; - }; - - var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; - }; - - var serializeString = function (buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = size + 1 >> 24 & 0xff; - buffer[index + 2] = size + 1 >> 16 & 0xff; - buffer[index + 1] = size + 1 >> 8 & 0xff; - buffer[index] = size + 1 & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; - }; - - var serializeNumber = function (buffer, key, value, index, isArray) { - // We have an integer value - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = value >> 8 & 0xff; - buffer[index++] = value >> 16 & 0xff; - buffer[index++] = value >> 24 & 0xff; - } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - }; - - var serializeNull = function (buffer, key, value, index, isArray) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - }; - - var serializeBoolean = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - }; - - var serializeDate = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - return index; - }; - - var serializeRegExp = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.global) buffer[index++] = 0x73; // s - if (value.ignoreCase) buffer[index++] = 0x69; // i - if (value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - }; - - var serializeBSONRegExp = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options.split('').sort().join(''), index, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; - }; - - var serializeMinMax = function (buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - }; - - var serializeObjectId = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, 'binary'); - } else if (value.id && value.id.copy) { - value.id.copy(buffer, index, 0, 12); - } else { - throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - - // Ajust index - return index + 12; - }; - - var serializeBuffer = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - }; - - var serializeObject = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { - for (var i = 0; i < path.length; i++) { - if (path[i] === value) throw new Error('cyclic dependency detected'); - } - - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - // Pop stack - path.pop(); - // Write size - return endIndex; - }; - - var serializeDecimal128 = function (buffer, key, value, index, isArray) { - buffer[index++] = BSON.BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - value.bytes.copy(buffer, index, 0, 16); - return index + 16; - }; - - var serializeLong = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - return index; - }; - - var serializeInt32 = function (buffer, key, value, index, isArray) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = value >> 8 & 0xff; - buffer[index++] = value >> 16 & 0xff; - buffer[index++] = value >> 24 & 0xff; - return index; - }; - - var serializeDouble = function (buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - }; - - var serializeFunction = function (buffer, key, value, index, checkKeys, depth, isArray) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; - }; - - var serializeCode = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - var startIndex = index; - - // Serialize the function - // Get the function string - var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = codeSize >> 8 & 0xff; - buffer[index + 2] = codeSize >> 16 & 0xff; - buffer[index + 3] = codeSize >> 24 & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); - index = endIndex - 1; - - // Writ the total - var totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = totalSize >> 8 & 0xff; - buffer[startIndex++] = totalSize >> 16 & 0xff; - buffer[startIndex++] = totalSize >> 24 & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; - }; - - var serializeBinary = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - } - - // Write the data to the object - data.copy(buffer, index, 0, value.position); - // Adjust the index - index = index + value.position; - return index; - }; - - var serializeSymbol = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - }; - - var serializeDBRef = function (buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if (null != value.db) { - endIndex = serializeInto(buffer, { - $ref: value.namespace, - $id: value.oid, - $db: value.db - }, false, index, depth + 1, serializeFunctions); - } else { - endIndex = serializeInto(buffer, { - $ref: value.namespace, - $id: value.oid - }, false, index, depth + 1, serializeFunctions); - } - - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = size >> 8 & 0xff; - buffer[startIndex++] = size >> 16 & 0xff; - buffer[startIndex++] = size >> 24 & 0xff; - // Set index - return endIndex; - }; - - var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - startingIndex = startingIndex || 0; - path = path || []; - - // Push the object to the path - path.push(object); - - // Start place to serialize into - var index = startingIndex + 4; - // var self = this; - - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = '' + i; - var value = object[i]; - - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - var type = typeof value; - if (type === 'string') { - index = serializeString(buffer, key, value, index, true); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index, true); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } else if (object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if (done) continue; - - // Get the entry values - key = entry.value[0]; - value = entry.value[1]; - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - // } else if (value === undefined && ignoreUndefined === true) { - } else if (value === null || value === undefined && ignoreUndefined === false) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') throw new Error('toBSON function did not return an object'); - } - - // Iterate over all the keys - for (key in object) { - value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === undefined) { - if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); - } else if (value === null) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - - // Remove the path - path.pop(); - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = size >> 8 & 0xff; - buffer[startingIndex++] = size >> 16 & 0xff; - buffer[startingIndex++] = size >> 24 & 0xff; - return index; - }; - - var BSON = {}; - - /** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ - // var functionCache = (BSON.functionCache = {}); - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * ObjectID BSON Type, deprecated - * - * @classconstant BSON_DATA_UNDEFINED - **/ - BSON.BSON_DATA_UNDEFINED = 6; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ - BSON.BSON_DATA_DECIMAL128 = 19; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = serializeInto; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(339).Buffer)) - -/***/ }), -/* 359 */ -/***/ (function(module, exports) { - - // Copyright (c) 2008, Fair Oaks Labs, Inc. - // All rights reserved. - // - // Redistribution and use in source and binary forms, with or without - // modification, are permitted provided that the following conditions are met: - // - // * Redistributions of source code must retain the above copyright notice, - // this list of conditions and the following disclaimer. - // - // * Redistributions in binary form must reproduce the above copyright notice, - // this list of conditions and the following disclaimer in the documentation - // and/or other materials provided with the distribution. - // - // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors - // may be used to endorse or promote products derived from this software - // without specific prior written permission. - // - // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - // POSSIBILITY OF SUCH DAMAGE. - // - // - // Modifications to writeIEEE754 to support negative zeroes made by Brian White - - var readIEEE754 = function (buffer, offset, endian, mLen, nBytes) { - var e, - m, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : nBytes - 1, - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & (1 << -nBits) - 1; - s >>= -nBits; - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); - }; - - var writeIEEE754 = function (buffer, value, offset, endian, mLen, nBytes) { - var e, - m, - c, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, - i = bBE ? nBytes - 1 : 0, - d = bBE ? -1 : 1, - s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = e << mLen | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; - }; - - exports.readIEEE754 = readIEEE754; - exports.writeIEEE754 = writeIEEE754; - -/***/ }), -/* 360 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - var Long = __webpack_require__(335).Long, - Double = __webpack_require__(336).Double, - Timestamp = __webpack_require__(337).Timestamp, - ObjectID = __webpack_require__(338).ObjectID, - Symbol = __webpack_require__(349).Symbol, - BSONRegExp = __webpack_require__(348).BSONRegExp, - Code = __webpack_require__(351).Code, - Decimal128 = __webpack_require__(352), - MinKey = __webpack_require__(353).MinKey, - MaxKey = __webpack_require__(354).MaxKey, - DBRef = __webpack_require__(355).DBRef, - Binary = __webpack_require__(356).Binary; - - var normalizedFunctionString = __webpack_require__(344).normalizedFunctionString; - - // To ensure that 0.4 of node works correctly - var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; - }; - - var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { - var totalLength = 4 + 1; - - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); - } - } else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - - return totalLength; - }; - - /** - * @ignore - * @api private - */ - function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - - switch (typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // 32 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } else { - // 64 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if (value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } else if (value instanceof Date || isDate(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length; - } else if (value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] === 'Long' || value['_bsontype'] === 'Double' || value['_bsontype'] === 'Timestamp') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } else if (value instanceof Code || value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; - } - } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1); - } - } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; - } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - $ref: value.namespace, - $id: value.oid - }; - - // Add db reference if it exists - if (null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); - } else if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; - } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1; - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) === '[object RegExp]') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; - } else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else if (serializeFunctions) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1; - } - } - } - - return 0; - } - - var BSON = {}; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = calculateObjectSize; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(339).Buffer)) - -/***/ }) -/******/ ]) -}); -; \ No newline at end of file diff --git a/node_modules/bson/browser_build/package.json b/node_modules/bson/browser_build/package.json deleted file mode 100644 index 980db7f..0000000 --- a/node_modules/bson/browser_build/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "bson" -, "description" : "A bson parser for node.js and the browser" -, "main": "../" -, "directories" : { "lib" : "../lib/bson" } -, "engines" : { "node" : ">=0.6.0" } -, "licenses" : [ { "type" : "Apache License, Version 2.0" - , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] -} diff --git a/node_modules/bson/index.js b/node_modules/bson/index.js deleted file mode 100644 index 6502552..0000000 --- a/node_modules/bson/index.js +++ /dev/null @@ -1,46 +0,0 @@ -var BSON = require('./lib/bson/bson'), - Binary = require('./lib/bson/binary'), - Code = require('./lib/bson/code'), - DBRef = require('./lib/bson/db_ref'), - Decimal128 = require('./lib/bson/decimal128'), - Double = require('./lib/bson/double'), - Int32 = require('./lib/bson/int_32'), - Long = require('./lib/bson/long'), - Map = require('./lib/bson/map'), - MaxKey = require('./lib/bson/max_key'), - MinKey = require('./lib/bson/min_key'), - ObjectId = require('./lib/bson/objectid'), - BSONRegExp = require('./lib/bson/regexp'), - Symbol = require('./lib/bson/symbol'), - Timestamp = require('./lib/bson/timestamp'); - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Add BSON types to function creation -BSON.Binary = Binary; -BSON.Code = Code; -BSON.DBRef = DBRef; -BSON.Decimal128 = Decimal128; -BSON.Double = Double; -BSON.Int32 = Int32; -BSON.Long = Long; -BSON.Map = Map; -BSON.MaxKey = MaxKey; -BSON.MinKey = MinKey; -BSON.ObjectId = ObjectId; -BSON.ObjectID = ObjectId; -BSON.BSONRegExp = BSONRegExp; -BSON.Symbol = Symbol; -BSON.Timestamp = Timestamp; - -// Return the BSON -module.exports = BSON; diff --git a/node_modules/bson/lib/bson/binary.js b/node_modules/bson/lib/bson/binary.js deleted file mode 100644 index 6d190bc..0000000 --- a/node_modules/bson/lib/bson/binary.js +++ /dev/null @@ -1,384 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ - -// Test if we're in Node via presence of "global" not absence of "window" -// to support hybrid environments like Electron -if (typeof global !== 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -var utils = require('./parser/utils'); - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Binary} - */ -function Binary(buffer, subType) { - if (!(this instanceof Binary)) return new Binary(buffer, subType); - - if ( - buffer != null && - !(typeof buffer === 'string') && - !Buffer.isBuffer(buffer) && - !(buffer instanceof Uint8Array) && - !Array.isArray(buffer) - ) { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - - this._bsontype = 'Binary'; - - if (buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if (buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if (typeof buffer === 'string') { - // Different ways of writing the length of the string for the different types - if (typeof Buffer !== 'undefined') { - this.buffer = utils.toBuffer(buffer); - } else if ( - typeof Uint8Array !== 'undefined' || - Object.prototype.toString.call(buffer) === '[object Array]' - ) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if (typeof Buffer !== 'undefined') { - this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); - } else if (typeof Uint8Array !== 'undefined') { - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -} - -/** - * Updates this binary with byte_value. - * - * @method - * @param {string} byte_value a single byte we wish to write. - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) - throw new Error('only accepts single character String, Uint8Array or Array'); - if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255) - throw new Error('only accepts number in a valid unsigned byte range 0-255'); - - // Decode the byte value once - var decoded_byte = null; - if (typeof byte_value === 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if (byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - buffer = null; - // Create a new buffer (typed or normal array) - if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for (var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @method - * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. - * @param {number} offset specify the binary of where to write the content. - * @return {null} - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset === 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = utils.allocBuffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); - // Copy the content - for (var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length - } else if ( - typeof Buffer !== 'undefined' && - typeof string === 'string' && - Buffer.isBuffer(this.buffer) - ) { - this.buffer.write(string, offset, 'binary'); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length; - } else if ( - Object.prototype.toString.call(string) === '[object Uint8Array]' || - (Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') - ) { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if (typeof string === 'string') { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @method - * @param {number} position read from the given position in the Binary. - * @param {number} length the number of bytes to read. - * @return {Buffer} - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 ? length : this.position; - - // Let's return the data based on the type we have - if (this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = - typeof Uint8Array !== 'undefined' - ? new Uint8Array(new ArrayBuffer(length)) - : new Array(length); - for (var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @method - * @return {string} - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if ( - asRaw && - typeof Buffer !== 'undefined' && - Buffer.isBuffer(this.buffer) && - this.buffer.length === this.position - ) - return this.buffer; - - // If it's a node.js buffer object - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw - ? this.buffer.slice(0, this.position) - : this.buffer.toString('binary', 0, this.position); - } else { - if (asRaw) { - // we support the slice command use it - if (this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = - Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' - ? new Uint8Array(new ArrayBuffer(this.position)) - : new Array(this.position); - // Copy content - for (var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @method - * @return {number} the length of the binary. - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -}; - -/** - * @ignore - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -}; - -/** - * Binary default subtype - * @ignore - */ -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = - typeof Uint8Array !== 'undefined' - ? new Uint8Array(new ArrayBuffer(data.length)) - : new Array(data.length); - // Write the content to the buffer - for (var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -}; - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ''; - for (var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -module.exports = Binary; -module.exports.Binary = Binary; diff --git a/node_modules/bson/lib/bson/bson.js b/node_modules/bson/lib/bson/bson.js deleted file mode 100644 index 912c5b9..0000000 --- a/node_modules/bson/lib/bson/bson.js +++ /dev/null @@ -1,386 +0,0 @@ -'use strict'; - -var Map = require('./map'), - Long = require('./long'), - Double = require('./double'), - Timestamp = require('./timestamp'), - ObjectID = require('./objectid'), - BSONRegExp = require('./regexp'), - Symbol = require('./symbol'), - Int32 = require('./int_32'), - Code = require('./code'), - Decimal128 = require('./decimal128'), - MinKey = require('./min_key'), - MaxKey = require('./max_key'), - DBRef = require('./db_ref'), - Binary = require('./binary'); - -// Parts of the parser -var deserialize = require('./parser/deserializer'), - serializer = require('./parser/serializer'), - calculateObjectSize = require('./parser/calculate_size'), - utils = require('./parser/utils'); - -/** - * @ignore - * @api private - */ -// Default Max Size -var MAXSIZE = 1024 * 1024 * 17; - -// Current Internal Temporary Serialization Buffer -var buffer = utils.allocBuffer(MAXSIZE); - -var BSON = function() {}; - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function serialize(object, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = - typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = utils.allocBuffer(minInternalBufferSize); - } - - // Attempt to serialize - var serializationIndex = serializer( - buffer, - object, - checkKeys, - 0, - 0, - serializeFunctions, - ignoreUndefined, - [] - ); - // Create the final buffer - var finishedBuffer = utils.allocBuffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; -}; - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - - // Attempt to serialize - var serializationIndex = serializer( - finalBuffer, - object, - checkKeys, - startIndex || 0, - 0, - serializeFunctions, - ignoreUndefined - ); - - // Return the index - return serializationIndex - 1; -}; - -/** - * Deserialize data as BSON. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(buffer, options) { - return deserialize(buffer, options); -}; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, options) { - options = options || {}; - - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); -}; - -/** - * Deserialize stream data as BSON documents. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function( - data, - startIndex, - numberOfDocuments, - documents, - docStartIndex, - options -) { - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = - data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24); - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = this.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// Return BSON -module.exports = BSON; -module.exports.Code = Code; -module.exports.Map = Map; -module.exports.Symbol = Symbol; -module.exports.BSON = BSON; -module.exports.DBRef = DBRef; -module.exports.Binary = Binary; -module.exports.ObjectID = ObjectID; -module.exports.Long = Long; -module.exports.Timestamp = Timestamp; -module.exports.Double = Double; -module.exports.Int32 = Int32; -module.exports.MinKey = MinKey; -module.exports.MaxKey = MaxKey; -module.exports.BSONRegExp = BSONRegExp; -module.exports.Decimal128 = Decimal128; diff --git a/node_modules/bson/lib/bson/code.js b/node_modules/bson/lib/bson/code.js deleted file mode 100644 index c2984cd..0000000 --- a/node_modules/bson/lib/bson/code.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * A class representation of the BSON Code type. - * - * @class - * @param {(string|function)} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -var Code = function Code(code, scope) { - if (!(this instanceof Code)) return new Code(code, scope); - this._bsontype = 'Code'; - this.code = code; - this.scope = scope; -}; - -/** - * @ignore - */ -Code.prototype.toJSON = function() { - return { scope: this.scope, code: this.code }; -}; - -module.exports = Code; -module.exports.Code = Code; diff --git a/node_modules/bson/lib/bson/db_ref.js b/node_modules/bson/lib/bson/db_ref.js deleted file mode 100644 index f95795b..0000000 --- a/node_modules/bson/lib/bson/db_ref.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * A class representation of the BSON DBRef type. - * - * @class - * @param {string} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {string} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -} - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - $ref: this.namespace, - $id: this.oid, - $db: this.db == null ? '' : this.db - }; -}; - -module.exports = DBRef; -module.exports.DBRef = DBRef; diff --git a/node_modules/bson/lib/bson/decimal128.js b/node_modules/bson/lib/bson/decimal128.js deleted file mode 100644 index 924513f..0000000 --- a/node_modules/bson/lib/bson/decimal128.js +++ /dev/null @@ -1,820 +0,0 @@ -'use strict'; - -var Long = require('./long'); - -var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; -var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; -var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - -var EXPONENT_MAX = 6111; -var EXPONENT_MIN = -6176; -var EXPONENT_BIAS = 6176; -var MAX_DIGITS = 34; - -// Nan value bits as 32 bit values (due to lack of longs) -var NAN_BUFFER = [ - 0x7c, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); -// Infinity value bits 32 bit values (due to lack of longs) -var INF_NEGATIVE_BUFFER = [ - 0xf8, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); -var INF_POSITIVE_BUFFER = [ - 0x78, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); - -var EXPONENT_REGEX = /^([-+])?(\d+)?$/; - -var utils = require('./parser/utils'); - -// Detect if the value is a digit -var isDigit = function(value) { - return !isNaN(parseInt(value, 10)); -}; - -// Divide two uint128 values -var divideu128 = function(value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - var i = 0; - - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - - for (i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low_; - _rem = _rem.modulo(DIVISOR); - } - - return { quotient: value, rem: _rem }; -}; - -// Multiply two Long values and return the 128 bit value -var multiply64x2 = function(left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - - // Return the 128 bit result - return { high: productHigh, low: productLow }; -}; - -var lessThan = function(left, right) { - // Make values unsigned - var uhleft = left.high_ >>> 0; - var uhright = right.high_ >>> 0; - - // Compare high bits first - if (uhleft < uhright) { - return true; - } else if (uhleft === uhright) { - var ulleft = left.low_ >>> 0; - var ulright = right.low_ >>> 0; - if (ulleft < ulright) return true; - } - - return false; -}; - -// var longtoHex = function(value) { -// var buffer = utils.allocBuffer(8); -// var index = 0; -// // Encode the low 64 bits of the decimal -// // Encode low bits -// buffer[index++] = value.low_ & 0xff; -// buffer[index++] = (value.low_ >> 8) & 0xff; -// buffer[index++] = (value.low_ >> 16) & 0xff; -// buffer[index++] = (value.low_ >> 24) & 0xff; -// // Encode high bits -// buffer[index++] = value.high_ & 0xff; -// buffer[index++] = (value.high_ >> 8) & 0xff; -// buffer[index++] = (value.high_ >> 16) & 0xff; -// buffer[index++] = (value.high_ >> 24) & 0xff; -// return buffer.reverse().toString('hex'); -// }; - -// var int32toHex = function(value) { -// var buffer = utils.allocBuffer(4); -// var index = 0; -// // Encode the low 64 bits of the decimal -// // Encode low bits -// buffer[index++] = value & 0xff; -// buffer[index++] = (value >> 8) & 0xff; -// buffer[index++] = (value >> 16) & 0xff; -// buffer[index++] = (value >> 24) & 0xff; -// return buffer.reverse().toString('hex'); -// }; - -/** - * A class representation of the BSON Decimal128 type. - * - * @class - * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. - * @return {Double} - */ -var Decimal128 = function(bytes) { - this._bsontype = 'Decimal128'; - this.bytes = bytes; -}; - -/** - * Create a Decimal128 instance from a string representation - * - * @method - * @param {string} string a numeric string representation. - * @return {Decimal128} returns a Decimal128 instance. - */ -Decimal128.fromString = function(string) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = [0, 0]; - // The low 17 digits of the significand - var significandLow = [0, 0]; - // The biased exponent - var biasedExponent = 0; - - // Read index - var index = 0; - - // Trim the string - string = string.trim(); - - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (string.length >= 7000) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Results - var stringMatch = string.match(PARSE_STRING_REGEXP); - var infMatch = string.match(PARSE_INF_REGEXP); - var nanMatch = string.match(PARSE_NAN_REGEXP); - - // Validate the string - if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Check if we have an illegal exponent format - if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Get the negative or positive sign - if (string[index] === '+' || string[index] === '-') { - isNegative = string[index++] === '-'; - } - - // Check if user passed Infinity or NaN - if (!isDigit(string[index]) && string[index] !== '.') { - if (string[index] === 'i' || string[index] === 'I') { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } else if (string[index] === 'N') { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - } - - // Read all the digits - while (isDigit(string[index]) || string[index] === '.') { - if (string[index] === '.') { - if (sawRadix) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - sawRadix = true; - index = index + 1; - continue; - } - - if (nDigitsStored < 34) { - if (string[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - - foundNonZero = true; - - // Only store 34 digits - digits[digitsInsert++] = parseInt(string[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - - if (foundNonZero) { - nDigits = nDigits + 1; - } - - if (sawRadix) { - radixPosition = radixPosition + 1; - } - - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - - if (sawRadix && !nDigitsRead) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Read exponent if exists - if (string[index] === 'e' || string[index] === 'E') { - // Read exponent digits - var match = string.substr(++index).match(EXPONENT_REGEX); - - // No digits read - if (!match || !match[2]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Get exponent - exponent = parseInt(match[0], 10); - - // Adjust the index - index = index + match[0].length; - } - - // Return not a number - if (string[index]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - - if (exponent !== 0 && significantDigits !== 1) { - while (string[firstNonZero + significantDigits - 1] === '0') { - significantDigits = significantDigits - 1; - } - } - } - - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; - } - - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - - exponent = exponent - 1; - } - - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit - if (lastDigit === 0) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } else { - // adjust to round - lastDigit = lastDigit - 1; - } - - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - // Check if we have a zero then just hard clamp, otherwise fail - digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { - var endOfString = nDigitsRead; - - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix && exponent === EXPONENT_MIN) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - - var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - - if (roundDigit >= 5) { - roundBit = 1; - - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1; - - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(string[i], 10)) { - roundBit = 1; - break; - } - } - } - } - - if (roundBit) { - var dIdx = lastDigit; - - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128( - utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) - ); - } - } - } else { - break; - } - } - } - } - - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if (lastDigit - firstDigit < 17) { - dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - - significandLow = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - - significand.low = significand.low.add(significandLow); - - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - - // Encode combination, exponent, and significand. - if ( - significand.high - .shiftRightUnsigned(49) - .and(Long.fromNumber(1)) - .equals(Long.fromNumber) - ) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or( - Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) - ); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - - dec.low = significand.low; - - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - - // Encode into a buffer - var buffer = utils.allocBuffer(16); - index = 0; - - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low_ & 0xff; - buffer[index++] = (dec.low.low_ >> 8) & 0xff; - buffer[index++] = (dec.low.low_ >> 16) & 0xff; - buffer[index++] = (dec.low.low_ >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.low.high_ & 0xff; - buffer[index++] = (dec.low.high_ >> 8) & 0xff; - buffer[index++] = (dec.low.high_ >> 16) & 0xff; - buffer[index++] = (dec.low.high_ >> 24) & 0xff; - - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low_ & 0xff; - buffer[index++] = (dec.high.low_ >> 8) & 0xff; - buffer[index++] = (dec.high.low_ >> 16) & 0xff; - buffer[index++] = (dec.high.low_ >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.high.high_ & 0xff; - buffer[index++] = (dec.high.high_ >> 8) & 0xff; - buffer[index++] = (dec.high.high_ >> 16) & 0xff; - buffer[index++] = (dec.high.high_ >> 24) & 0xff; - - // Return the new Decimal128 - return new Decimal128(buffer); -}; - -// Extract least significant 5 bits -var COMBINATION_MASK = 0x1f; -// Extract least significant 14 bits -var EXPONENT_MASK = 0x3fff; -// Value of combination field for Inf -var COMBINATION_INFINITY = 30; -// Value of combination field for NaN -var COMBINATION_NAN = 31; -// Value of combination field for NaN -// var COMBINATION_SNAN = 32; -// decimal128 exponent bias -EXPONENT_BIAS = 6176; - -/** - * Create a string representation of the raw Decimal128 value - * - * @method - * @return {string} returns a Decimal128 string representation. - */ -Decimal128.prototype.toString = function() { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - - // bits 0 - 31 - var high; - // bits 32 - 63 - var midh; - // bits 64 - 95 - var midl; - // bits 96 - 127 - var low; - // bits 1 - 5 - var combination; - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) significand[i] = 0; - // read pointer into significand - var index = 0; - - // unbiased exponent - var exponent; - // the exponent if scientific notation is used - var scientific_exponent; - - // true if the number is zero - var is_zero = false; - - // the most signifcant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: new Array(4) }; - // indexing variables - i; - var j, k; - - // Output string - var string = []; - - // Unpack index - index = 0; - - // Buffer reference - var buffer = this.bytes; - - // Unpack the low 64bits into a long - low = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - midl = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Unpack the high 64bits into a long - midh = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - high = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Unpack index - index = 0; - - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - - // Decode combination field and exponent - combination = (high >> 26) & COMBINATION_MASK; - - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } else if (combination === COMBINATION_NAN) { - return 'NaN'; - } else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - - exponent = biased_exponent - EXPONENT_BIAS; - - // Create string of significand digits - - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - - if ( - significand128.parts[0] === 0 && - significand128.parts[1] === 0 && - significand128.parts[2] === 0 && - significand128.parts[3] === 0 - ) { - is_zero = true; - } else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Peform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low_; - - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) continue; - - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } else { - significand_digits = 36; - i = 0; - - while (!significand[index]) { - i++; - significand_digits = significand_digits - 1; - index = index + 1; - } - } - - scientific_exponent = significand_digits - 1 + exponent; - - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - string.push(significand[index++]); - significand_digits = significand_digits - 1; - - if (significand_digits) { - string.push('.'); - } - - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } else { - string.push(scientific_exponent); - } - } else { - // Regular format with no decimal place - if (exponent >= 0) { - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - } else { - var radix_position = significand_digits + exponent; - - // non-zero digits before radix - if (radix_position > 0) { - for (i = 0; i < radix_position; i++) { - string.push(significand[index++]); - } - } else { - string.push('0'); - } - - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - - for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(significand[index++]); - } - } - } - - return string.join(''); -}; - -Decimal128.prototype.toJSON = function() { - return { $numberDecimal: this.toString() }; -}; - -module.exports = Decimal128; -module.exports.Decimal128 = Decimal128; diff --git a/node_modules/bson/lib/bson/double.js b/node_modules/bson/lib/bson/double.js deleted file mode 100644 index 523c21f..0000000 --- a/node_modules/bson/lib/bson/double.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON Double type. - * - * @class - * @param {number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if (!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Double.prototype.toJSON = function() { - return this.value; -}; - -module.exports = Double; -module.exports.Double = Double; diff --git a/node_modules/bson/lib/bson/float_parser.js b/node_modules/bson/lib/bson/float_parser.js deleted file mode 100644 index 0054a2f..0000000 --- a/node_modules/bson/lib/bson/float_parser.js +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, - m, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : nBytes - 1, - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << -nBits) - 1); - s >>= -nBits; - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << -nBits) - 1); - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, - m, - c, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, - i = bBE ? nBytes - 1 : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; diff --git a/node_modules/bson/lib/bson/int_32.js b/node_modules/bson/lib/bson/int_32.js deleted file mode 100644 index 85dbdec..0000000 --- a/node_modules/bson/lib/bson/int_32.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of a BSON Int32 type. - * - * @class - * @param {number} value the number we want to represent as an int32. - * @return {Int32} - */ -var Int32 = function(value) { - if (!(this instanceof Int32)) return new Int32(value); - - this._bsontype = 'Int32'; - this.value = value; -}; - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped int32 number. - */ -Int32.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Int32.prototype.toJSON = function() { - return this.value; -}; - -module.exports = Int32; -module.exports.Int32 = Int32; diff --git a/node_modules/bson/lib/bson/long.js b/node_modules/bson/lib/bson/long.js deleted file mode 100644 index 78215aa..0000000 --- a/node_modules/bson/lib/bson/long.js +++ /dev/null @@ -1,851 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Long. - * @param {number} high the high (signed) 32 bits of the Long. - * @return {Long} - */ -function Long(low, high) { - if (!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -} - -/** - * Return the int value. - * - * @method - * @return {number} the value, assuming it is a 32-bit integer. - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Long.prototype.toJSON = function() { - return this.toString(); -}; - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Long.prototype.getLowBitsUnsigned = function() { - return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Long. - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Long.prototype.isZero = function() { - return this.high_ === 0 && this.low_ === 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) === 1; -}; - -/** - * Return whether this Long equals the other - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long equals the other - */ -Long.prototype.equals = function(other) { - return this.high_ === other.high_ && this.low_ === other.low_; -}; - -/** - * Return whether this Long does not equal the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long does not equal the other. - */ -Long.prototype.notEquals = function(other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; -}; - -/** - * Return whether this Long is less than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than the other. - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than or equal to the other. - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than the other. - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than or equal to the other. - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Long} the negation of this value. - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @method - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @method - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @method - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate() - .multiply(other) - .negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @method - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate() - .div(other) - .negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @method - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Long} the bitwise-NOT of this value. - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); - } else { - return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); - } else if (numBits === 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Long} the corresponding Long value. - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Long. - * @param {number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - */ -Long.fromString = function(str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @ignore - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @ignore - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Long; -module.exports.Long = Long; diff --git a/node_modules/bson/lib/bson/map.js b/node_modules/bson/lib/bson/map.js deleted file mode 100644 index 7edb4f2..0000000 --- a/node_modules/bson/lib/bson/map.js +++ /dev/null @@ -1,128 +0,0 @@ -'use strict'; - -// We have an ES6 Map available, return the native instance -if (typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; -} else { - // We will return a polyfill - var Map = function(array) { - this._keys = []; - this._values = {}; - - for (var i = 0; i < array.length; i++) { - if (array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - }; - - Map.prototype.clear = function() { - this._keys = []; - this._values = {}; - }; - - Map.prototype.delete = function(key) { - var value = this._values[key]; - if (value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - - Map.prototype.entries = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.forEach = function(callback, self) { - self = self || this; - - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - - Map.prototype.get = function(key) { - return this._values[key] ? this._values[key].v : undefined; - }; - - Map.prototype.has = function(key) { - return this._values[key] != null; - }; - - Map.prototype.keys = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.set = function(key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - - Map.prototype.values = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable: true, - get: function() { - return this._keys.length; - } - }); - - module.exports = Map; - module.exports.Map = Map; -} diff --git a/node_modules/bson/lib/bson/max_key.js b/node_modules/bson/lib/bson/max_key.js deleted file mode 100644 index eebca7b..0000000 --- a/node_modules/bson/lib/bson/max_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MaxKey type. - * - * @class - * @return {MaxKey} A MaxKey instance - */ -function MaxKey() { - if (!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -module.exports = MaxKey; -module.exports.MaxKey = MaxKey; diff --git a/node_modules/bson/lib/bson/min_key.js b/node_modules/bson/lib/bson/min_key.js deleted file mode 100644 index 15f4522..0000000 --- a/node_modules/bson/lib/bson/min_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MinKey type. - * - * @class - * @return {MinKey} A MinKey instance - */ -function MinKey() { - if (!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -module.exports = MinKey; -module.exports.MinKey = MinKey; diff --git a/node_modules/bson/lib/bson/objectid.js b/node_modules/bson/lib/bson/objectid.js deleted file mode 100644 index 79de40d..0000000 --- a/node_modules/bson/lib/bson/objectid.js +++ /dev/null @@ -1,389 +0,0 @@ -// Custom inspect property name / symbol. -var inspect = 'inspect'; - -var utils = require('./parser/utils'); - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - * @ignore - */ -var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); - -// Check if buffer exists -try { - if (Buffer && Buffer.from) { - var hasBufferType = true; - inspect = require('util').inspect.custom || 'inspect'; - } -} catch (err) { - hasBufferType = false; -} - -/** -* Create a new ObjectID instance -* -* @class -* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @property {number} generationTime The generation time of this ObjectId instance -* @return {ObjectID} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id) { - // Duck-typing to support ObjectId from different npm packages - if (id instanceof ObjectID) return id; - if (!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - - // The most common usecase (blank id, new objectId instance) - if (id == null || typeof id === 'number') { - // Generate a new id - this.id = this.generate(id); - // If we are caching the hex string - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - // Return the object - return; - } - - // Check if the passed in id is valid - var valid = ObjectID.isValid(id); - - // Throw an error if it's not a valid setup - if (!valid && id != null) { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { - return new ObjectID(utils.toBuffer(id, 'hex')); - } else if (valid && typeof id === 'string' && id.length === 24) { - return ObjectID.createFromHexString(id); - } else if (id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if (id != null && id.toHexString) { - // Duck-typing to support ObjectId from different npm packages - return id; - } else { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } - - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); -}; - -// Allow usage of ObjectId as well as ObjectID -// var ObjectId = ObjectID; - -// Precomputed hex table enables speedy hex string conversion -var hexTable = []; -for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); -} - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @method -* @return {string} return the 24 byte hex string representation. -*/ -ObjectID.prototype.toHexString = function() { - if (ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - if (!this.id || !this.id.length) { - throw new Error( - 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + - JSON.stringify(this.id) + - ']' - ); - } - - if (this.id instanceof _Buffer) { - hexString = convertToHex(this.id); - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - } - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.get_inc = function() { - return (ObjectID.index = (ObjectID.index + 1) % 0xffffff); -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id buffer used in ObjectID's -* -* @method -* @param {number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {Buffer} return the 12 byte id buffer string. -*/ -ObjectID.prototype.generate = function(time) { - if ('number' !== typeof time) { - time = ~~(Date.now() / 1000); - } - - // Use pid - var pid = - (typeof process === 'undefined' || process.pid === 1 - ? Math.floor(Math.random() * 100000) - : process.pid) % 0xffff; - var inc = this.get_inc(); - // Buffer used - var buffer = utils.allocBuffer(12); - // Encode time - buffer[3] = time & 0xff; - buffer[2] = (time >> 8) & 0xff; - buffer[1] = (time >> 16) & 0xff; - buffer[0] = (time >> 24) & 0xff; - // Encode machine - buffer[6] = MACHINE_ID & 0xff; - buffer[5] = (MACHINE_ID >> 8) & 0xff; - buffer[4] = (MACHINE_ID >> 16) & 0xff; - // Encode pid - buffer[8] = pid & 0xff; - buffer[7] = (pid >> 8) & 0xff; - // Encode index - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - // Return the buffer - return buffer; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @param {String} format The Buffer toString format parameter. -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toString = function(format) { - // Is the id a buffer then use the buffer toString method to return the format - if (this.id && this.id.copy) { - return this.id.toString(typeof format === 'string' ? format : 'hex'); - } - - // if(this.buffer ) - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype[inspect] = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @method -* @param {object} otherID ObjectID instance to compare against. -* @return {boolean} the result of comparing two ObjectID's -*/ -ObjectID.prototype.equals = function equals(otherId) { - // var id; - - if (otherId instanceof ObjectID) { - return this.toString() === otherId.toString(); - } else if ( - typeof otherId === 'string' && - ObjectID.isValid(otherId) && - otherId.length === 12 && - this.id instanceof _Buffer - ) { - return otherId === this.id.toString('binary'); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { - return otherId === this.id; - } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { - return otherId.toHexString() === this.toHexString(); - } else { - return false; - } -}; - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @method -* @return {date} the generation date -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; -}; - -/** -* @ignore -*/ -ObjectID.index = ~~(Math.random() * 0xffffff); - -/** -* @ignore -*/ -ObjectID.createPk = function createPk() { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @method -* @param {number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromTime = function createFromTime(time) { - var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer[3] = time & 0xff; - buffer[2] = (time >> 8) & 0xff; - buffer[1] = (time >> 16) & 0xff; - buffer[0] = (time >> 24) & 0xff; - // Return the new objectId - return new ObjectID(buffer); -}; - -// Lookup tables -//var encodeLookup = '0123456789abcdef'.split(''); -var decodeLookup = []; -i = 0; -while (i < 10) decodeLookup[0x30 + i] = i++; -while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; - -var _Buffer = Buffer; -var convertToHex = function(bytes) { - return bytes.toString('hex'); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @method -* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromHexString = function createFromHexString(string) { - // Throw an error if it's not a valid setup - if (typeof string === 'undefined' || (string != null && string.length !== 24)) { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } - - // Use Buffer.from method if available - if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); - - // Calculate lengths - var array = new _Buffer(12); - var n = 0; - var i = 0; - - while (i < 24) { - array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)]; - } - - return new ObjectID(array); -}; - -/** -* Checks if a value is a valid bson ObjectId -* -* @method -* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. -*/ -ObjectID.isValid = function isValid(id) { - if (id == null) return false; - - if (typeof id === 'number') { - return true; - } - - if (typeof id === 'string') { - return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); - } - - if (id instanceof ObjectID) { - return true; - } - - if (id instanceof _Buffer) { - return true; - } - - // Duck-Typing detection of ObjectId like objects - if (id.toHexString) { - return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id)); - } - - return false; -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, 'generationTime', { - enumerable: true, - get: function() { - return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); - }, - set: function(value) { - // Encode time into first 4 bytes - this.id[3] = value & 0xff; - this.id[2] = (value >> 8) & 0xff; - this.id[1] = (value >> 16) & 0xff; - this.id[0] = (value >> 24) & 0xff; - } -}); - -/** - * Expose. - */ -module.exports = ObjectID; -module.exports.ObjectID = ObjectID; -module.exports.ObjectId = ObjectID; diff --git a/node_modules/bson/lib/bson/parser/calculate_size.js b/node_modules/bson/lib/bson/parser/calculate_size.js deleted file mode 100644 index 7e0026c..0000000 --- a/node_modules/bson/lib/bson/parser/calculate_size.js +++ /dev/null @@ -1,255 +0,0 @@ -'use strict'; - -var Long = require('../long').Long, - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - BSONRegExp = require('../regexp').BSONRegExp, - Code = require('../code').Code, - Decimal128 = require('../decimal128'), - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - DBRef = require('../db_ref').DBRef, - Binary = require('../binary').Binary; - -var normalizedFunctionString = require('./utils').normalizedFunctionString; - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -}; - -var calculateObjectSize = function calculateObjectSize( - object, - serializeFunctions, - ignoreUndefined -) { - var totalLength = 4 + 1; - - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement( - i.toString(), - object[i], - serializeFunctions, - true, - ignoreUndefined - ); - } - } else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - - return totalLength; -}; - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - - switch (typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // 32 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } else { - // 64 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if ( - value == null || - value instanceof MinKey || - value instanceof MaxKey || - value['_bsontype'] === 'MinKey' || - value['_bsontype'] === 'MaxKey' - ) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } else if (value instanceof Date || isDate(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length - ); - } else if ( - value instanceof Long || - value instanceof Double || - value instanceof Timestamp || - value['_bsontype'] === 'Long' || - value['_bsontype'] === 'Double' || - value['_bsontype'] === 'Timestamp' - ) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } else if (value instanceof Code || value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(value.code.toString(), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - Buffer.byteLength(value.code.toString(), 'utf8') + - 1 - ); - } - } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - (value.position + 1 + 4 + 1 + 4) - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) - ); - } - } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - Buffer.byteLength(value.value, 'utf8') + - 4 + - 1 + - 1 - ); - } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - $ref: value.namespace, - $id: value.oid - }; - - // Add db reference if it exists - if (null != value.db) { - ordered_values['$db'] = value.db; - } - - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) - ); - } else if ( - value instanceof RegExp || - Object.prototype.toString.call(value) === '[object RegExp]' - ) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1 - ); - } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.pattern, 'utf8') + - 1 + - Buffer.byteLength(value.options, 'utf8') + - 1 - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - calculateObjectSize(value, serializeFunctions, ignoreUndefined) + - 1 - ); - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if ( - value instanceof RegExp || - Object.prototype.toString.call(value) === '[object RegExp]' || - String.call(value) === '[object RegExp]' - ) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1 - ); - } else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) - ); - } else if (serializeFunctions) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1 - ); - } - } - } - - return 0; -} - -var BSON = {}; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = calculateObjectSize; diff --git a/node_modules/bson/lib/bson/parser/deserializer.js b/node_modules/bson/lib/bson/parser/deserializer.js deleted file mode 100644 index be3c865..0000000 --- a/node_modules/bson/lib/bson/parser/deserializer.js +++ /dev/null @@ -1,782 +0,0 @@ -'use strict'; - -var Long = require('../long').Long, - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - Code = require('../code').Code, - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - Decimal128 = require('../decimal128'), - Int32 = require('../int_32'), - DBRef = require('../db_ref').DBRef, - BSONRegExp = require('../regexp').BSONRegExp, - Binary = require('../binary').Binary; - -var utils = require('./utils'); - -var deserialize = function(buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - - // Ensure buffer is valid size - if (size < 5 || buffer.length < size || size + index > buffer.length) { - throw new Error('corrupt bson message'); - } - - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); -}; - -var deserializeObject = function(buffer, index, options, isArray) { - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = - options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - - if (!cacheFunctionsCrc32) var crc32 = null; - - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - - // Set the start index - var startIndex = index; - - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); - - // Read the document size - var size = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); - - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - - var done = false; - - // While we have more left data left keep parsing - // while (buffer[index + 1] !== 0) { - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) break; - - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - - index = i + 1; - - if (elementType === BSON.BSON_DATA_STRING) { - var stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_OID) { - var oid = utils.allocBuffer(12); - buffer.copy(oid, 0, index, index + 12); - object[name] = new ObjectID(oid); - index = index + 12; - } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { - object[name] = new Int32( - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) - ); - } else if (elementType === BSON.BSON_DATA_INT) { - object[name] = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { - object[name] = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_NUMBER) { - object[name] = buffer.readDoubleLE(index); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_DATE) { - var lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if (elementType === BSON.BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); - object[name] = buffer[index++] === 1; - } else if (elementType === BSON.BSON_DATA_OBJECT) { - var _index = index; - var objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (objectSize <= 0 || objectSize > buffer.length - index) - throw new Error('bad embedded document length in bson'); - - // We have a raw value - if (raw) { - object[name] = buffer.slice(index, index + objectSize); - } else { - object[name] = deserializeObject(buffer, _index, options, false); - } - - index = index + objectSize; - } else if (elementType === BSON.BSON_DATA_ARRAY) { - _index = index; - objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - var arrayOptions = options; - - // Stop index - var stopIndex = index + objectSize; - - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - object[name] = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - - if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); - if (index !== stopIndex) throw new Error('corrupted array bson'); - } else if (elementType === BSON.BSON_DATA_UNDEFINED) { - object[name] = undefined; - } else if (elementType === BSON.BSON_DATA_NULL) { - object[name] = null; - } else if (elementType === BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - object[name] = - long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) - ? long.toNumber() - : long; - } else { - object[name] = long; - } - } else if (elementType === BSON.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = utils.allocBuffer(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; - } else if (elementType === BSON.BSON_DATA_BINARY) { - var binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var totalBinarySize = binarySize; - var subType = buffer[index++]; - - // Did we have a negative binary size, throw - if (binarySize < 0) throw new Error('Negative binary type element size found'); - - // Is the length longer than the document - if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); - - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - if (promoteBuffers && promoteValues) { - object[name] = buffer.slice(index, index + binarySize); - } else { - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } - } else { - var _buffer = - typeof Uint8Array !== 'undefined' - ? new Uint8Array(new ArrayBuffer(binarySize)) - : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - - if (promoteBuffers && promoteValues) { - object[name] = _buffer; - } else { - object[name] = new Binary(_buffer, subType); - } - } - - // Update the index - index = index + binarySize; - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - source = buffer.toString('utf8', index, i); - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if (elementType === BSON.BSON_DATA_SYMBOL) { - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { - lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - object[name] = new Timestamp(lowBits, highBits); - } else if (elementType === BSON.BSON_DATA_MIN_KEY) { - object[name] = new MinKey(); - } else if (elementType === BSON.BSON_DATA_MAX_KEY) { - object[name] = new MaxKey(); - } else if (elementType === BSON.BSON_DATA_CODE) { - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString); - } - - // Update parse index position - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { - var totalSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new Error('code_w_scope total size shorter minimum expected length'); - } - - // Get the code string size - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - - // Javascript function - functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - _index = index; - // Decode the size of the object document - objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - - // Check if field length is to short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to short, truncating scope'); - } - - // Check if totalSize field is to long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to long, clips outer document'); - } - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } else if (elementType === BSON.BSON_DATA_DBPOINTER) { - // Get the code string size - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - // Namespace - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - - // Read the oid - var oidBuffer = utils.allocBuffer(12); - buffer.copy(oidBuffer, 0, index, index + 12); - oid = new ObjectID(oidBuffer); - - // Update the index - index = index + 12; - - // Split the namespace - var parts = namespace.split('.'); - var db = parts.shift(); - var collection = parts.join('.'); - // Upgrade to DBRef type - object[name] = new DBRef(collection, oid, db); - } else { - throw new Error( - 'Detected unknown BSON type ' + - elementType.toString(16) + - ' for fieldname "' + - name + - '", are you using the latest BSON parser' - ); - } - } - - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) throw new Error('corrupt array bson'); - throw new Error('corrupt object bson'); - } - - // Check if we have a db ref object - if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - return object; -}; - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if (functionCache[hash] == null) { - eval('value = ' + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -}; - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval('value = ' + functionString); - return value; -}; - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = (BSON.functionCache = {}); - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_DBPOINTER - **/ -BSON.BSON_DATA_DBPOINTER = 12; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ -BSON.BSON_DATA_DECIMAL128 = 19; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = deserialize; diff --git a/node_modules/bson/lib/bson/parser/serializer.js b/node_modules/bson/lib/bson/parser/serializer.js deleted file mode 100644 index 6bb212e..0000000 --- a/node_modules/bson/lib/bson/parser/serializer.js +++ /dev/null @@ -1,1188 +0,0 @@ -'use strict'; - -var writeIEEE754 = require('../float_parser').writeIEEE754, - Long = require('../long').Long, - Map = require('../map'), - Binary = require('../binary').Binary; - -var normalizedFunctionString = require('./utils').normalizedFunctionString; - -// try { -// var _Buffer = Uint8Array; -// } catch (e) { -// _Buffer = Buffer; -// } - -var regexp = /\x00/; // eslint-disable-line no-control-regex -var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -}; - -var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; -}; - -var serializeString = function(buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = ((size + 1) >> 24) & 0xff; - buffer[index + 2] = ((size + 1) >> 16) & 0xff; - buffer[index + 1] = ((size + 1) >> 8) & 0xff; - buffer[index] = (size + 1) & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; -}; - -var serializeNumber = function(buffer, key, value, index, isArray) { - // We have an integer value - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; -}; - -var serializeNull = function(buffer, key, value, index, isArray) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -}; - -var serializeBoolean = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; -}; - -var serializeDate = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -}; - -var serializeRegExp = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.global) buffer[index++] = 0x73; // s - if (value.ignoreCase) buffer[index++] = 0x69; // i - if (value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; -}; - -var serializeBSONRegExp = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = - index + - buffer.write( - value.options - .split('') - .sort() - .join(''), - index, - 'utf8' - ); - // Add ending zero - buffer[index++] = 0x00; - return index; -}; - -var serializeMinMax = function(buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -}; - -var serializeObjectId = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, 'binary'); - } else if (value.id && value.id.copy) { - value.id.copy(buffer, index, 0, 12); - } else { - throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - - // Ajust index - return index + 12; -}; - -var serializeBuffer = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; -}; - -var serializeObject = function( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - isArray, - path -) { - for (var i = 0; i < path.length; i++) { - if (path[i] === value) throw new Error('cyclic dependency detected'); - } - - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto( - buffer, - value, - checkKeys, - index, - depth + 1, - serializeFunctions, - ignoreUndefined, - path - ); - // Pop stack - path.pop(); - // Write size - return endIndex; -}; - -var serializeDecimal128 = function(buffer, key, value, index, isArray) { - buffer[index++] = BSON.BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - value.bytes.copy(buffer, index, 0, 16); - return index + 16; -}; - -var serializeLong = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -}; - -var serializeInt32 = function(buffer, key, value, index, isArray) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return index; -}; - -var serializeDouble = function(buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; -}; - -var serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; -}; - -var serializeCode = function( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - isArray -) { - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - var startIndex = index; - - // Serialize the function - // Get the function string - var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto( - buffer, - value.scope, - checkKeys, - index, - depth + 1, - serializeFunctions, - ignoreUndefined - ); - index = endIndex - 1; - - // Writ the total - var totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; -}; - -var serializeBinary = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - data.copy(buffer, index, 0, value.position); - // Adjust the index - index = index + value.position; - return index; -}; - -var serializeSymbol = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; -}; - -var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if (null != value.db) { - endIndex = serializeInto( - buffer, - { - $ref: value.namespace, - $id: value.oid, - $db: value.db - }, - false, - index, - depth + 1, - serializeFunctions - ); - } else { - endIndex = serializeInto( - buffer, - { - $ref: value.namespace, - $id: value.oid - }, - false, - index, - depth + 1, - serializeFunctions - ); - } - - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; -}; - -var serializeInto = function serializeInto( - buffer, - object, - checkKeys, - startingIndex, - depth, - serializeFunctions, - ignoreUndefined, - path -) { - startingIndex = startingIndex || 0; - path = path || []; - - // Push the object to the path - path.push(object); - - // Start place to serialize into - var index = startingIndex + 4; - // var self = this; - - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = '' + i; - var value = object[i]; - - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - var type = typeof value; - if (type === 'string') { - index = serializeString(buffer, key, value, index, true); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index, true); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - true, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - true - ); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - true - ); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } else if (object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if (done) continue; - - // Get the entry values - key = entry.value[0]; - value = entry.value[1]; - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - // } else if (value === undefined && ignoreUndefined === true) { - } else if (value === null || (value === undefined && ignoreUndefined === false)) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - false, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined - ); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') - throw new Error('toBSON function did not return an object'); - } - - // Iterate over all the keys - for (key in object) { - value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === undefined) { - if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); - } else if (value === null) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - false, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined - ); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } else if (typeof value['_bsontype'] !== 'undefined') { - throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); - } - } - } - - // Remove the path - path.pop(); - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -}; - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -// var functionCache = (BSON.functionCache = {}); - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type, deprecated - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ -BSON.BSON_DATA_DECIMAL128 = 19; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = serializeInto; diff --git a/node_modules/bson/lib/bson/parser/utils.js b/node_modules/bson/lib/bson/parser/utils.js deleted file mode 100644 index 6faa439..0000000 --- a/node_modules/bson/lib/bson/parser/utils.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -/** - * Normalizes our expected stringified form of a function across versions of node - * @param {Function} fn The function to stringify - */ -function normalizedFunctionString(fn) { - return fn.toString().replace(/function *\(/, 'function ('); -} - -function newBuffer(item, encoding) { - return new Buffer(item, encoding); -} - -function allocBuffer() { - return Buffer.alloc.apply(Buffer, arguments); -} - -function toBuffer() { - return Buffer.from.apply(Buffer, arguments); -} - -module.exports = { - normalizedFunctionString: normalizedFunctionString, - allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, - toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer -}; - diff --git a/node_modules/bson/lib/bson/regexp.js b/node_modules/bson/lib/bson/regexp.js deleted file mode 100644 index 108f016..0000000 --- a/node_modules/bson/lib/bson/regexp.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ -function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern || ''; - this.options = options || ''; - - // Validate options - for (var i = 0; i < this.options.length; i++) { - if ( - !( - this.options[i] === 'i' || - this.options[i] === 'm' || - this.options[i] === 'x' || - this.options[i] === 'l' || - this.options[i] === 's' || - this.options[i] === 'u' - ) - ) { - throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); - } - } -} - -module.exports = BSONRegExp; -module.exports.BSONRegExp = BSONRegExp; diff --git a/node_modules/bson/lib/bson/symbol.js b/node_modules/bson/lib/bson/symbol.js deleted file mode 100644 index ba20cab..0000000 --- a/node_modules/bson/lib/bson/symbol.js +++ /dev/null @@ -1,50 +0,0 @@ -// Custom inspect property name / symbol. -var inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect'; - -/** - * A class representation of the BSON Symbol type. - * - * @class - * @deprecated - * @param {string} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if (!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype.toString = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype[inspect] = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype.toJSON = function() { - return this.value; -}; - -module.exports = Symbol; -module.exports.Symbol = Symbol; diff --git a/node_modules/bson/lib/bson/timestamp.js b/node_modules/bson/lib/bson/timestamp.js deleted file mode 100644 index dc61a6c..0000000 --- a/node_modules/bson/lib/bson/timestamp.js +++ /dev/null @@ -1,854 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * This type is for INTERNAL use in MongoDB only and should not be used in applications. - * The appropriate corresponding type is the JavaScript Date type. - * - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Timestamp. - * @param {number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if (!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -} - -/** - * Return the int value. - * - * @return {number} the value, assuming it is a 32-bit integer. - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -}; - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Timestamp.prototype.isZero = function() { - return this.high_ === 0 && this.low_ === 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) === 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp equals the other - */ -Timestamp.prototype.equals = function(other) { - return this.high_ === other.high_ && this.low_ === other.low_; -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp does not equal the other. - */ -Timestamp.prototype.notEquals = function(other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than the other. - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than or equal to the other. - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than the other. - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than or equal to the other. - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Timestamp} the negation of this value. - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate() - .multiply(other) - .negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate() - .div(other) - .negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Timestamp} the bitwise-NOT of this value. - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); - } else { - return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); - } else if (numBits === 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0 - ); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Timestamp. - * @param {number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @ignore - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @ignore - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Timestamp; -module.exports.Timestamp = Timestamp; diff --git a/node_modules/bson/package.json b/node_modules/bson/package.json deleted file mode 100644 index fc74b82..0000000 --- a/node_modules/bson/package.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "_from": "bson@^1.1.4", - "_id": "bson@1.1.4", - "_inBundle": false, - "_integrity": "sha512-S/yKGU1syOMzO86+dGpg2qGoDL0zvzcb262G+gqEy6TgP6rt6z6qxSFX/8X6vLC91P7G7C3nLs0+bvDzmvBA3Q==", - "_location": "/bson", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "bson@^1.1.4", - "name": "bson", - "escapedName": "bson", - "rawSpec": "^1.1.4", - "saveSpec": null, - "fetchSpec": "^1.1.4" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/bson/-/bson-1.1.4.tgz", - "_shasum": "f76870d799f15b854dffb7ee32f0a874797f7e89", - "_spec": "bson@^1.1.4", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mongodb", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "browser": "lib/bson/bson.js", - "bugs": { - "url": "https://github.com/mongodb/js-bson/issues" - }, - "bundleDependencies": false, - "config": { - "native": false - }, - "contributors": [], - "deprecated": false, - "description": "A bson parser for node.js and the browser", - "devDependencies": { - "babel-core": "^6.14.0", - "babel-loader": "^6.2.5", - "babel-polyfill": "^6.13.0", - "babel-preset-es2015": "^6.14.0", - "babel-preset-stage-0": "^6.5.0", - "babel-register": "^6.14.0", - "benchmark": "1.0.0", - "colors": "1.1.0", - "conventional-changelog-cli": "^1.3.5", - "nodeunit": "0.9.0", - "webpack": "^1.13.2", - "webpack-polyfills-plugin": "0.0.9" - }, - "directories": { - "lib": "./lib/bson" - }, - "engines": { - "node": ">=0.6.19" - }, - "files": [ - "lib", - "index.js", - "browser_build", - "bower.json" - ], - "homepage": "https://github.com/mongodb/js-bson#readme", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "license": "Apache-2.0", - "main": "./index", - "name": "bson", - "repository": { - "type": "git", - "url": "git+https://github.com/mongodb/js-bson.git" - }, - "scripts": { - "build": "webpack --config ./webpack.dist.config.js", - "changelog": "conventional-changelog -p angular -i HISTORY.md -s", - "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", - "lint": "eslint lib test", - "test": "nodeunit ./test/node" - }, - "version": "1.1.4" -} diff --git a/node_modules/buffer/AUTHORS.md b/node_modules/buffer/AUTHORS.md deleted file mode 100644 index 396b45f..0000000 --- a/node_modules/buffer/AUTHORS.md +++ /dev/null @@ -1,62 +0,0 @@ -# Authors - -#### Ordered by first contribution. - -- Romain Beauxis (toots@rastageeks.org) -- Tobias Koppers (tobias.koppers@googlemail.com) -- Janus (ysangkok@gmail.com) -- Rainer Dreyer (rdrey1@gmail.com) -- Tõnis Tiigi (tonistiigi@gmail.com) -- James Halliday (mail@substack.net) -- Michael Williamson (mike@zwobble.org) -- elliottcable (github@elliottcable.name) -- rafael (rvalle@livelens.net) -- Andrew Kelley (superjoe30@gmail.com) -- Andreas Madsen (amwebdk@gmail.com) -- Mike Brevoort (mike.brevoort@pearson.com) -- Brian White (mscdex@mscdex.net) -- Feross Aboukhadijeh (feross@feross.org) -- Ruben Verborgh (ruben@verborgh.org) -- eliang (eliang.cs@gmail.com) -- Jesse Tane (jesse.tane@gmail.com) -- Alfonso Boza (alfonso@cloud.com) -- Mathias Buus (mathiasbuus@gmail.com) -- Devon Govett (devongovett@gmail.com) -- Daniel Cousens (github@dcousens.com) -- Joseph Dykstra (josephdykstra@gmail.com) -- Parsha Pourkhomami (parshap+git@gmail.com) -- Damjan Košir (damjan.kosir@gmail.com) -- daverayment (dave.rayment@gmail.com) -- kawanet (u-suke@kawa.net) -- Linus Unnebäck (linus@folkdatorn.se) -- Nolan Lawson (nolan.lawson@gmail.com) -- Calvin Metcalf (calvin.metcalf@gmail.com) -- Koki Takahashi (hakatasiloving@gmail.com) -- Guy Bedford (guybedford@gmail.com) -- Jan Schär (jscissr@gmail.com) -- RaulTsc (tomescu.raul@gmail.com) -- Matthieu Monsch (monsch@alum.mit.edu) -- Dan Ehrenberg (littledan@chromium.org) -- Kirill Fomichev (fanatid@ya.ru) -- Yusuke Kawasaki (u-suke@kawa.net) -- DC (dcposch@dcpos.ch) -- John-David Dalton (john.david.dalton@gmail.com) -- adventure-yunfei (adventure030@gmail.com) -- Emil Bay (github@tixz.dk) -- Sam Sudar (sudar.sam@gmail.com) -- Volker Mische (volker.mische@gmail.com) -- David Walton (support@geekstocks.com) -- Сковорода Никита Андреевич (chalkerx@gmail.com) -- greenkeeper[bot] (greenkeeper[bot]@users.noreply.github.com) -- ukstv (sergey.ukustov@machinomy.com) -- Renée Kooi (renee@kooi.me) -- ranbochen (ranbochen@qq.com) -- Vladimir Borovik (bobahbdb@gmail.com) -- greenkeeper[bot] (23040076+greenkeeper[bot]@users.noreply.github.com) -- kumavis (aaron@kumavis.me) -- Sergey Ukustov (sergey.ukustov@machinomy.com) -- Fei Liu (liu.feiwood@gmail.com) -- Blaine Bublitz (blaine.bublitz@gmail.com) -- Niklas Mischkulnig (mischnic@users.noreply.github.com) - -#### Generated by bin/update-authors.sh. diff --git a/node_modules/buffer/LICENSE b/node_modules/buffer/LICENSE deleted file mode 100644 index d6bf75d..0000000 --- a/node_modules/buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Feross Aboukhadijeh, and other 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/buffer/README.md b/node_modules/buffer/README.md deleted file mode 100644 index 2aab37d..0000000 --- a/node_modules/buffer/README.md +++ /dev/null @@ -1,416 +0,0 @@ -# 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/buffer/master.svg -[travis-url]: https://travis-ci.org/feross/buffer -[npm-image]: https://img.shields.io/npm/v/buffer.svg -[npm-url]: https://npmjs.org/package/buffer -[downloads-image]: https://img.shields.io/npm/dm/buffer.svg -[downloads-url]: https://npmjs.org/package/buffer -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com - -#### The buffer module from [node.js](https://nodejs.org/), for the browser. - -[![saucelabs][saucelabs-image]][saucelabs-url] - -[saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg -[saucelabs-url]: https://saucelabs.com/u/buffer - -With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module. - -The goal is to provide an API that is 100% identical to -[node's Buffer API](https://nodejs.org/api/buffer.html). Read the -[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, -instance methods, and class methods that are supported. - -## features - -- Manipulate binary data like a boss, in all browsers! -- Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`) -- Extremely small bundle size (**6.75KB minified + gzipped**, 51.9KB with comments) -- Excellent browser support (Chrome, Firefox, Edge, Safari 9+, IE 11, iOS 9+, Android, etc.) -- Preserves Node API exactly, with one minor difference (see below) -- Square-bracket `buf[4]` notation works! -- Does not modify any browser prototypes or put anything on `window` -- Comprehensive test suite (including all buffer tests from node.js core) - -## `buffer` for enterprise - -Available as part of the Tidelift Subscription. - -The maintainers of `buffer` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-buffer?utm_source=npm-buffer&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - -## install - -To use this module directly (without browserify), install it: - -```bash -npm install buffer -``` - -This module was previously called **native-buffer-browserify**, but please use **buffer** -from now on. - -If you do not use a bundler, you can use the [standalone script](https://bundle.run/buffer). - -## usage - -The module's API is identical to node's `Buffer` API. Read the -[official docs](https://nodejs.org/api/buffer.html) for the full list of properties, -instance methods, and class methods that are supported. - -As mentioned above, `require('buffer')` or use the `Buffer` global with -[browserify](http://browserify.org) and this module will automatically be included -in your bundle. Almost any npm module will work in the browser, even if it assumes that -the node `Buffer` API will be available. - -To depend on this module explicitly (without browserify), require it like this: - -```js -var Buffer = require('buffer/').Buffer // note: the trailing slash is important! -``` - -To require this module explicitly, use `require('buffer/')` which tells the node.js module -lookup algorithm (also used by browserify) to use the **npm module** named `buffer` -instead of the **node.js core** module named `buffer`! - - -## how does it work? - -The Buffer constructor returns instances of `Uint8Array` that have their prototype -changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, -so the returned instances will have all the node `Buffer` methods and the -`Uint8Array` methods. Square bracket notation works as expected -- it returns a -single octet. - -The `Uint8Array` prototype remains unmodified. - - -## tracking the latest node api - -This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer -API is considered **stable** in the -[node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index), -so it is unlikely that there will ever be breaking changes. -Nonetheless, when/if the Buffer API changes in node, this module's API will change -accordingly. - -## related packages - -- [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - Reverse a buffer -- [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - Bitwise xor a buffer -- [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package - -## conversion packages - -### convert typed array to buffer - -Use [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) to convert any kind of typed array to a `Buffer`. Does not perform a copy, so it's super fast. - -### convert buffer to typed array - -`Buffer` is a subclass of `Uint8Array` (which is a typed array). So there is no need to explicitly convert to typed array. Just use the buffer as a `Uint8Array`. - -### convert blob to buffer - -Use [`blob-to-buffer`](https://www.npmjs.com/package/blob-to-buffer) to convert a `Blob` to a `Buffer`. - -### convert buffer to blob - -To convert a `Buffer` to a `Blob`, use the `Blob` constructor: - -```js -var blob = new Blob([ buffer ]) -``` - -Optionally, specify a mimetype: - -```js -var blob = new Blob([ buffer ], { type: 'text/html' }) -``` - -### convert arraybuffer to buffer - -To convert an `ArrayBuffer` to a `Buffer`, use the `Buffer.from` function. Does not perform a copy, so it's super fast. - -```js -var buffer = Buffer.from(arrayBuffer) -``` - -### convert buffer to arraybuffer - -To convert a `Buffer` to an `ArrayBuffer`, use the `.buffer` property (which is present on all `Uint8Array` objects): - -```js -var arrayBuffer = buffer.buffer.slice( - buffer.byteOffset, buffer.byteOffset + buffer.byteLength -) -``` - -Alternatively, use the [`to-arraybuffer`](https://www.npmjs.com/package/to-arraybuffer) module. - -## performance - -See perf tests in `/perf`. - -`BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a -sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will -always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module, -which is included to compare against. - -NOTE: Performance has improved since these benchmarks were taken. PR welcome to update the README. - -### Chrome 38 - -| Method | Operations | Accuracy | Sampled | Fastest | -|:-------|:-----------|:---------|:--------|:-------:| -| BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ | -| Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | | -| | | | | -| BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | | -| Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ | -| | | | | -| BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | | -| Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ | -| | | | | -| BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | | -| Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ | -| | | | | -| BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | | -| Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ | -| | | | | -| BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | | -| Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ | -| | | | | -| BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ | -| DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | | -| | | | | -| BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ | -| DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | | -| | | | | -| BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ | -| DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | | -| | | | | -| BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | | -| Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ | -| | | | | -| BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | | -| DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ | - - -### Firefox 33 - -| Method | Operations | Accuracy | Sampled | Fastest | -|:-------|:-----------|:---------|:--------|:-------:| -| BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | | -| Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ | -| | | | | -| BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | | -| Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ | -| | | | | -| BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | | -| Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ | -| | | | | -| BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | | -| Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ | -| | | | | -| BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | | -| Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ | -| | | | | -| BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | | -| Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ | -| | | | | -| BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | | -| DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ | -| | | | | -| BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | | -| DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ | -| | | | | -| BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ | -| DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | | -| | | | | -| BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | | -| Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ | -| | | | | -| BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | | -| DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ | - -### Safari 8 - -| Method | Operations | Accuracy | Sampled | Fastest | -|:-------|:-----------|:---------|:--------|:-------:| -| BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ | -| Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | | -| | | | | -| BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | | -| Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ | -| | | | | -| BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | | -| Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ | -| | | | | -| BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | | -| Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ | -| | | | | -| BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | | -| Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ | -| | | | | -| BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | | -| Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ | -| | | | | -| BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | | -| DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ | -| | | | | -| BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | | -| DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ | -| | | | | -| BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | | -| DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ | -| | | | | -| BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | | -| Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ | -| | | | | -| BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | | -| DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ | - - -### Node 0.11.14 - -| Method | Operations | Accuracy | Sampled | Fastest | -|:-------|:-----------|:---------|:--------|:-------:| -| BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | | -| Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ | -| NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | | -| | | | | -| BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | | -| Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ | -| NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | | -| | | | | -| BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | | -| Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ | -| NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | | -| | | | | -| BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | | -| Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ | -| NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | | -| | | | | -| BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | | -| Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | | -| NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ | -| | | | | -| BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | | -| Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ | -| NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | | -| | | | | -| BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ | -| DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | | -| NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | | -| | | | | -| BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ | -| DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | | -| NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | | -| | | | | -| BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | | -| DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | | -| NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ | -| | | | | -| BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | | -| Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ | -| NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | | -| | | | | -| BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | | -| DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ | -| NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | | - -### iojs 1.8.1 - -| Method | Operations | Accuracy | Sampled | Fastest | -|:-------|:-----------|:---------|:--------|:-------:| -| BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | | -| Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | | -| NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ | -| | | | | -| BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | | -| Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | | -| NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ | -| | | | | -| BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | | -| Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | | -| NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ | -| | | | | -| BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | | -| Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ | -| NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | | -| | | | | -| BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | | -| Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | | -| NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ | -| | | | | -| BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | | -| Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ | -| NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | | -| | | | | -| BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ | -| DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | | -| NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | | -| | | | | -| BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ | -| DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | | -| NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | | -| | | | | -| BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | | -| DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | | -| NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ | -| | | | | -| BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | | -| Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | | -| NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ | -| | | | | -| BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | | -| DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ | -| NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | | -| | | | | - -## Testing the project - -First, install the project: - - npm install - -Then, to run tests in Node.js, run: - - npm run test-node - -To test locally in a browser, you can run: - - npm run test-browser-es5-local # For ES5 browsers that don't support ES6 - npm run test-browser-es6-local # For ES6 compliant browsers - -This will print out a URL that you can then open in a browser to run the tests, using [airtap](https://www.npmjs.com/package/airtap). - -To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run: - - npm test - -This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `bin/airtap-es5.yml` and `bin/airtap-es6.yml` files. - -## JavaScript Standard Style - -This module uses [JavaScript Standard Style](https://github.com/feross/standard). - -[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) - -To test that the code conforms to the style, `npm install` and run: - - ./node_modules/.bin/standard - -## credit - -This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify). - -## Security Policies and Procedures - -The `buffer` team and community take all security bugs in `buffer` seriously. Please see our [security policies and procedures](https://github.com/feross/security) document to learn how to report issues. - -## license - -MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis. diff --git a/node_modules/buffer/index.d.ts b/node_modules/buffer/index.d.ts deleted file mode 100644 index 0227c9c..0000000 --- a/node_modules/buffer/index.d.ts +++ /dev/null @@ -1,186 +0,0 @@ -export class Buffer extends Uint8Array { - 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; - reverse(): this; - 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 | Uint8Array): 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; -} diff --git a/node_modules/buffer/index.js b/node_modules/buffer/index.js deleted file mode 100644 index e87bfaa..0000000 --- a/node_modules/buffer/index.js +++ /dev/null @@ -1,1794 +0,0 @@ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') -var customInspectSymbol = - (typeof Symbol === 'function' && typeof Symbol.for === 'function') - ? Symbol.for('nodejs.util.inspect.custom') - : null - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - var proto = { foo: function () { return 42 } } - Object.setPrototypeOf(proto, Uint8Array.prototype) - Object.setPrototypeOf(arr, proto) - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - Object.setPrototypeOf(buf, Buffer.prototype) - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof SharedArrayBuffer !== 'undefined' && - (isInstance(value, SharedArrayBuffer) || - (value && isInstance(value.buffer, SharedArrayBuffer)))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype) -Object.setPrototypeOf(Buffer, Uint8Array) - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - Object.setPrototypeOf(buf, Buffer.prototype) - - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} -if (customInspectSymbol) { - Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += hexSliceLookupTable[buf[i]] - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - Object.setPrototypeOf(newBuf, Buffer.prototype) - - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } else if (typeof val === 'boolean') { - val = Number(val) - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -// Create lookup table for `toString('hex')` -// See: https://github.com/feross/buffer/issues/219 -var hexSliceLookupTable = (function () { - var alphabet = '0123456789abcdef' - var table = new Array(256) - for (var i = 0; i < 16; ++i) { - var i16 = i * 16 - for (var j = 0; j < 16; ++j) { - table[i16 + j] = alphabet[i] + alphabet[j] - } - } - return table -})() diff --git a/node_modules/buffer/package.json b/node_modules/buffer/package.json deleted file mode 100644 index 51362cb..0000000 --- a/node_modules/buffer/package.json +++ /dev/null @@ -1,113 +0,0 @@ -{ - "_from": "buffer@^5.5.0", - "_id": "buffer@5.6.0", - "_inBundle": false, - "_integrity": "sha512-/gDYp/UtU0eA1ys8bOs9J6a+E/KWIY+DZ+Q2WESNUA0jFRsJOc0SNUO6xJ5SGA1xueg3NL65W6s+NY5l9cunuw==", - "_location": "/buffer", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "buffer@^5.5.0", - "name": "buffer", - "escapedName": "buffer", - "rawSpec": "^5.5.0", - "saveSpec": null, - "fetchSpec": "^5.5.0" - }, - "_requiredBy": [ - "/tar-stream/bl" - ], - "_resolved": "https://registry.npmjs.org/buffer/-/buffer-5.6.0.tgz", - "_shasum": "a31749dc7d81d84db08abf937b6b8c4033f62786", - "_spec": "buffer@^5.5.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/tar-stream/node_modules/bl", - "author": { - "name": "Feross Aboukhadijeh", - "email": "feross@feross.org", - "url": "http://feross.org" - }, - "bugs": { - "url": "https://github.com/feross/buffer/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Romain Beauxis", - "email": "toots@rastageeks.org" - }, - { - "name": "James Halliday", - "email": "mail@substack.net" - } - ], - "dependencies": { - "base64-js": "^1.0.2", - "ieee754": "^1.1.4" - }, - "deprecated": false, - "description": "Node.js Buffer API, for the browser", - "devDependencies": { - "airtap": "^3.0.0", - "benchmark": "^2.0.0", - "browserify": "^16.1.0", - "concat-stream": "^2.0.0", - "hyperquest": "^2.0.0", - "is-buffer": "^2.0.0", - "is-nan": "^1.0.1", - "split": "^1.0.0", - "standard": "*", - "tape": "^4.0.0", - "through2": "^3.0.1", - "uglify-js": "^3.4.5" - }, - "homepage": "https://github.com/feross/buffer", - "jspm": { - "map": { - "./index.js": { - "node": "@node/buffer" - } - } - }, - "keywords": [ - "arraybuffer", - "browser", - "browserify", - "buffer", - "compatible", - "dataview", - "uint8array" - ], - "license": "MIT", - "main": "index.js", - "name": "buffer", - "repository": { - "type": "git", - "url": "git://github.com/feross/buffer.git" - }, - "scripts": { - "perf": "browserify --debug perf/bracket-notation.js > perf/bundle.js && open perf/index.html", - "perf-node": "node perf/bracket-notation.js && node perf/concat.js && node perf/copy-big.js && node perf/copy.js && node perf/new-big.js && node perf/new.js && node perf/readDoubleBE.js && node perf/readFloatBE.js && node perf/readUInt32LE.js && node perf/slice.js && node perf/writeFloatBE.js", - "size": "browserify -r ./ | uglifyjs -c -m | gzip | wc -c", - "test": "standard && node ./bin/test.js", - "test-browser-es5": "airtap -- test/*.js", - "test-browser-es5-local": "airtap --local -- test/*.js", - "test-browser-es6": "airtap -- test/*.js test/node/*.js", - "test-browser-es6-local": "airtap --local -- test/*.js test/node/*.js", - "test-node": "tape test/*.js test/node/*.js", - "update-authors": "./bin/update-authors.sh" - }, - "standard": { - "ignore": [ - "test/node/**/*.js", - "test/common.js", - "test/_polyfill.js", - "perf/**/*.js" - ], - "globals": [ - "SharedArrayBuffer" - ] - }, - "types": "index.d.ts", - "version": "5.6.0" -} diff --git a/node_modules/bytes/History.md b/node_modules/bytes/History.md deleted file mode 100644 index cf6a5bb..0000000 --- a/node_modules/bytes/History.md +++ /dev/null @@ -1,87 +0,0 @@ -3.1.0 / 2019-01-22 -================== - - * Add petabyte (`pb`) support - -3.0.0 / 2017-08-31 -================== - - * Change "kB" to "KB" in format output - * Remove support for Node.js 0.6 - * Remove support for ComponentJS - -2.5.0 / 2017-03-24 -================== - - * Add option "unit" - -2.4.0 / 2016-06-01 -================== - - * Add option "unitSeparator" - -2.3.0 / 2016-02-15 -================== - - * Drop partial bytes on all parsed units - * Fix non-finite numbers to `.format` to return `null` - * Fix parsing byte string that looks like hex - * perf: hoist regular expressions - -2.2.0 / 2015-11-13 -================== - - * add option "decimalPlaces" - * add option "fixedDecimals" - -2.1.0 / 2015-05-21 -================== - - * add `.format` export - * add `.parse` export - -2.0.2 / 2015-05-20 -================== - - * remove map recreation - * remove unnecessary object construction - -2.0.1 / 2015-05-07 -================== - - * fix browserify require - * remove node.extend dependency - -2.0.0 / 2015-04-12 -================== - - * add option "case" - * add option "thousandsSeparator" - * return "null" on invalid parse input - * support proper round-trip: bytes(bytes(num)) === num - * units no longer case sensitive when parsing - -1.0.0 / 2014-05-05 -================== - - * add negative support. fixes #6 - -0.3.0 / 2014-03-19 -================== - - * added terabyte support - -0.2.1 / 2013-04-01 -================== - - * add .component - -0.2.0 / 2012-10-28 -================== - - * bytes(200).should.eql('200b') - -0.1.0 / 2012-07-04 -================== - - * add bytes to string conversion [yields] diff --git a/node_modules/bytes/LICENSE b/node_modules/bytes/LICENSE deleted file mode 100644 index 63e95a9..0000000 --- a/node_modules/bytes/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -(The MIT License) - -Copyright (c) 2012-2014 TJ Holowaychuk -Copyright (c) 2015 Jed Watson - -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/bytes/Readme.md b/node_modules/bytes/Readme.md deleted file mode 100644 index 6ad1ec6..0000000 --- a/node_modules/bytes/Readme.md +++ /dev/null @@ -1,126 +0,0 @@ -# Bytes utility - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa. - -## Installation - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```bash -$ npm install bytes -``` - -## Usage - -```js -var bytes = require('bytes'); -``` - -#### bytes.format(number value, [options]): string|null - -Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is - rounded. - -**Arguments** - -| Name | Type | Description | -|---------|----------|--------------------| -| value | `number` | Value in bytes | -| options | `Object` | Conversion options | - -**Options** - -| Property | Type | Description | -|-------------------|--------|-----------------------------------------------------------------------------------------| -| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. | -| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` | -| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `.`... Default value to `''`. | -| unit | `string`|`null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). | -| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. | - -**Returns** - -| Name | Type | Description | -|---------|------------------|-------------------------------------------------| -| results | `string`|`null` | Return null upon error. String value otherwise. | - -**Example** - -```js -bytes(1024); -// output: '1KB' - -bytes(1000); -// output: '1000B' - -bytes(1000, {thousandsSeparator: ' '}); -// output: '1 000B' - -bytes(1024 * 1.7, {decimalPlaces: 0}); -// output: '2KB' - -bytes(1024, {unitSeparator: ' '}); -// output: '1 KB' - -``` - -#### bytes.parse(string|number value): number|null - -Parse the string value into an integer in bytes. If no unit is given, or `value` -is a number, it is assumed the value is in bytes. - -Supported units and abbreviations are as follows and are case-insensitive: - - * `b` for bytes - * `kb` for kilobytes - * `mb` for megabytes - * `gb` for gigabytes - * `tb` for terabytes - * `pb` for petabytes - -The units are in powers of two, not ten. This means 1kb = 1024b according to this parser. - -**Arguments** - -| Name | Type | Description | -|---------------|--------|--------------------| -| value | `string`|`number` | String to parse, or number in bytes. | - -**Returns** - -| Name | Type | Description | -|---------|-------------|-------------------------| -| results | `number`|`null` | Return null upon error. Value in bytes otherwise. | - -**Example** - -```js -bytes('1KB'); -// output: 1024 - -bytes('1024'); -// output: 1024 - -bytes(1024); -// output: 1KB -``` - -## License - -[MIT](LICENSE) - -[coveralls-image]: https://badgen.net/coveralls/c/github/visionmedia/bytes.js/master -[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master -[downloads-image]: https://badgen.net/npm/dm/bytes -[downloads-url]: https://npmjs.org/package/bytes -[npm-image]: https://badgen.net/npm/node/bytes -[npm-url]: https://npmjs.org/package/bytes -[travis-image]: https://badgen.net/travis/visionmedia/bytes.js/master -[travis-url]: https://travis-ci.org/visionmedia/bytes.js diff --git a/node_modules/bytes/index.js b/node_modules/bytes/index.js deleted file mode 100644 index 4975bfb..0000000 --- a/node_modules/bytes/index.js +++ /dev/null @@ -1,162 +0,0 @@ -/*! - * bytes - * Copyright(c) 2012-2014 TJ Holowaychuk - * Copyright(c) 2015 Jed Watson - * MIT Licensed - */ - -'use strict'; - -/** - * Module exports. - * @public - */ - -module.exports = bytes; -module.exports.format = format; -module.exports.parse = parse; - -/** - * Module variables. - * @private - */ - -var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; - -var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; - -var map = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: Math.pow(1024, 4), - pb: Math.pow(1024, 5), -}; - -var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; - -/** - * Convert the given value in bytes into a string or parse to string to an integer in bytes. - * - * @param {string|number} value - * @param {{ - * case: [string], - * decimalPlaces: [number] - * fixedDecimals: [boolean] - * thousandsSeparator: [string] - * unitSeparator: [string] - * }} [options] bytes options. - * - * @returns {string|number|null} - */ - -function bytes(value, options) { - if (typeof value === 'string') { - return parse(value); - } - - if (typeof value === 'number') { - return format(value, options); - } - - return null; -} - -/** - * Format the given value in bytes into a string. - * - * If the value is negative, it is kept as such. If it is a float, - * it is rounded. - * - * @param {number} value - * @param {object} [options] - * @param {number} [options.decimalPlaces=2] - * @param {number} [options.fixedDecimals=false] - * @param {string} [options.thousandsSeparator=] - * @param {string} [options.unit=] - * @param {string} [options.unitSeparator=] - * - * @returns {string|null} - * @public - */ - -function format(value, options) { - if (!Number.isFinite(value)) { - return null; - } - - var mag = Math.abs(value); - var thousandsSeparator = (options && options.thousandsSeparator) || ''; - var unitSeparator = (options && options.unitSeparator) || ''; - var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; - var fixedDecimals = Boolean(options && options.fixedDecimals); - var unit = (options && options.unit) || ''; - - if (!unit || !map[unit.toLowerCase()]) { - if (mag >= map.pb) { - unit = 'PB'; - } else if (mag >= map.tb) { - unit = 'TB'; - } else if (mag >= map.gb) { - unit = 'GB'; - } else if (mag >= map.mb) { - unit = 'MB'; - } else if (mag >= map.kb) { - unit = 'KB'; - } else { - unit = 'B'; - } - } - - var val = value / map[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); - - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, '$1'); - } - - if (thousandsSeparator) { - str = str.replace(formatThousandsRegExp, thousandsSeparator); - } - - return str + unitSeparator + unit; -} - -/** - * Parse the string value into an integer in bytes. - * - * If no unit is given, it is assumed the value is in bytes. - * - * @param {number|string} val - * - * @returns {number|null} - * @public - */ - -function parse(val) { - if (typeof val === 'number' && !isNaN(val)) { - return val; - } - - if (typeof val !== 'string') { - return null; - } - - // Test if the string passed is valid - var results = parseRegExp.exec(val); - var floatValue; - var unit = 'b'; - - if (!results) { - // Nothing could be extracted from the given string - floatValue = parseInt(val, 10); - unit = 'b' - } else { - // Retrieve the value and the unit - floatValue = parseFloat(results[1]); - unit = results[4].toLowerCase(); - } - - return Math.floor(map[unit] * floatValue); -} diff --git a/node_modules/bytes/package.json b/node_modules/bytes/package.json deleted file mode 100644 index 6136856..0000000 --- a/node_modules/bytes/package.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "_from": "bytes@3.1.0", - "_id": "bytes@3.1.0", - "_inBundle": false, - "_integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==", - "_location": "/bytes", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "bytes@3.1.0", - "name": "bytes", - "escapedName": "bytes", - "rawSpec": "3.1.0", - "saveSpec": null, - "fetchSpec": "3.1.0" - }, - "_requiredBy": [ - "/body-parser", - "/raw-body" - ], - "_resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", - "_shasum": "f6cf7933a360e0588fa9fde85651cdc7f805d1f6", - "_spec": "bytes@3.1.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/body-parser", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "bugs": { - "url": "https://github.com/visionmedia/bytes.js/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jed Watson", - "email": "jed.watson@me.com" - }, - { - "name": "Théo FIDRY", - "email": "theo.fidry@gmail.com" - } - ], - "deprecated": false, - "description": "Utility to parse a string bytes to bytes and vice-versa", - "devDependencies": { - "eslint": "5.12.1", - "mocha": "5.2.0", - "nyc": "13.1.0" - }, - "engines": { - "node": ">= 0.8" - }, - "files": [ - "History.md", - "LICENSE", - "Readme.md", - "index.js" - ], - "homepage": "https://github.com/visionmedia/bytes.js#readme", - "keywords": [ - "byte", - "bytes", - "utility", - "parse", - "parser", - "convert", - "converter" - ], - "license": "MIT", - "name": "bytes", - "repository": { - "type": "git", - "url": "git+https://github.com/visionmedia/bytes.js.git" - }, - "scripts": { - "lint": "eslint .", - "test": "mocha --check-leaks --reporter spec", - "test-ci": "nyc --reporter=text npm test", - "test-cov": "nyc --reporter=html --reporter=text npm test" - }, - "version": "3.1.0" -} diff --git a/node_modules/chownr/LICENSE b/node_modules/chownr/LICENSE deleted file mode 100644 index 19129e3..0000000 --- a/node_modules/chownr/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/chownr/README.md b/node_modules/chownr/README.md deleted file mode 100644 index 70e9a54..0000000 --- a/node_modules/chownr/README.md +++ /dev/null @@ -1,3 +0,0 @@ -Like `chown -R`. - -Takes the same arguments as `fs.chown()` diff --git a/node_modules/chownr/chownr.js b/node_modules/chownr/chownr.js deleted file mode 100644 index 0d40932..0000000 --- a/node_modules/chownr/chownr.js +++ /dev/null @@ -1,167 +0,0 @@ -'use strict' -const fs = require('fs') -const path = require('path') - -/* istanbul ignore next */ -const LCHOWN = fs.lchown ? 'lchown' : 'chown' -/* istanbul ignore next */ -const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync' - -/* istanbul ignore next */ -const needEISDIRHandled = fs.lchown && - !process.version.match(/v1[1-9]+\./) && - !process.version.match(/v10\.[6-9]/) - -const lchownSync = (path, uid, gid) => { - try { - return fs[LCHOWNSYNC](path, uid, gid) - } catch (er) { - if (er.code !== 'ENOENT') - throw er - } -} - -/* istanbul ignore next */ -const chownSync = (path, uid, gid) => { - try { - return fs.chownSync(path, uid, gid) - } catch (er) { - if (er.code !== 'ENOENT') - throw er - } -} - -/* istanbul ignore next */ -const handleEISDIR = - needEISDIRHandled ? (path, uid, gid, cb) => er => { - // Node prior to v10 had a very questionable implementation of - // fs.lchown, which would always try to call fs.open on a directory - // Fall back to fs.chown in those cases. - if (!er || er.code !== 'EISDIR') - cb(er) - else - fs.chown(path, uid, gid, cb) - } - : (_, __, ___, cb) => cb - -/* istanbul ignore next */ -const handleEISDirSync = - needEISDIRHandled ? (path, uid, gid) => { - try { - return lchownSync(path, uid, gid) - } catch (er) { - if (er.code !== 'EISDIR') - throw er - chownSync(path, uid, gid) - } - } - : (path, uid, gid) => lchownSync(path, uid, gid) - -// fs.readdir could only accept an options object as of node v6 -const nodeVersion = process.version -let readdir = (path, options, cb) => fs.readdir(path, options, cb) -let readdirSync = (path, options) => fs.readdirSync(path, options) -/* istanbul ignore next */ -if (/^v4\./.test(nodeVersion)) - readdir = (path, options, cb) => fs.readdir(path, cb) - -const chown = (cpath, uid, gid, cb) => { - fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => { - // Skip ENOENT error - cb(er && er.code !== 'ENOENT' ? er : null) - })) -} - -const chownrKid = (p, child, uid, gid, cb) => { - if (typeof child === 'string') - return fs.lstat(path.resolve(p, child), (er, stats) => { - // Skip ENOENT error - if (er) - return cb(er.code !== 'ENOENT' ? er : null) - stats.name = child - chownrKid(p, stats, uid, gid, cb) - }) - - if (child.isDirectory()) { - chownr(path.resolve(p, child.name), uid, gid, er => { - if (er) - return cb(er) - const cpath = path.resolve(p, child.name) - chown(cpath, uid, gid, cb) - }) - } else { - const cpath = path.resolve(p, child.name) - chown(cpath, uid, gid, cb) - } -} - - -const chownr = (p, uid, gid, cb) => { - readdir(p, { withFileTypes: true }, (er, children) => { - // any error other than ENOTDIR or ENOTSUP means it's not readable, - // or doesn't exist. give up. - if (er) { - if (er.code === 'ENOENT') - return cb() - else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP') - return cb(er) - } - if (er || !children.length) - return chown(p, uid, gid, cb) - - let len = children.length - let errState = null - const then = er => { - if (errState) - return - if (er) - return cb(errState = er) - if (-- len === 0) - return chown(p, uid, gid, cb) - } - - children.forEach(child => chownrKid(p, child, uid, gid, then)) - }) -} - -const chownrKidSync = (p, child, uid, gid) => { - if (typeof child === 'string') { - try { - const stats = fs.lstatSync(path.resolve(p, child)) - stats.name = child - child = stats - } catch (er) { - if (er.code === 'ENOENT') - return - else - throw er - } - } - - if (child.isDirectory()) - chownrSync(path.resolve(p, child.name), uid, gid) - - handleEISDirSync(path.resolve(p, child.name), uid, gid) -} - -const chownrSync = (p, uid, gid) => { - let children - try { - children = readdirSync(p, { withFileTypes: true }) - } catch (er) { - if (er.code === 'ENOENT') - return - else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP') - return handleEISDirSync(p, uid, gid) - else - throw er - } - - if (children && children.length) - children.forEach(child => chownrKidSync(p, child, uid, gid)) - - return handleEISDirSync(p, uid, gid) -} - -module.exports = chownr -chownr.sync = chownrSync diff --git a/node_modules/chownr/package.json b/node_modules/chownr/package.json deleted file mode 100644 index 79e689f..0000000 --- a/node_modules/chownr/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "_from": "chownr@^1.1.1", - "_id": "chownr@1.1.4", - "_inBundle": false, - "_integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", - "_location": "/chownr", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "chownr@^1.1.1", - "name": "chownr", - "escapedName": "chownr", - "rawSpec": "^1.1.1", - "saveSpec": null, - "fetchSpec": "^1.1.1" - }, - "_requiredBy": [ - "/tar-fs" - ], - "_resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", - "_shasum": "6fc9d7b42d32a583596337666e7d08084da2cc6b", - "_spec": "chownr@^1.1.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/tar-fs", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "bugs": { - "url": "https://github.com/isaacs/chownr/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "like `chown -R`", - "devDependencies": { - "mkdirp": "0.3", - "rimraf": "^2.7.1", - "tap": "^14.10.6" - }, - "files": [ - "chownr.js" - ], - "homepage": "https://github.com/isaacs/chownr#readme", - "license": "ISC", - "main": "chownr.js", - "name": "chownr", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/chownr.git" - }, - "scripts": { - "postversion": "npm publish", - "prepublishOnly": "git push origin --follow-tags", - "preversion": "npm test", - "test": "tap" - }, - "tap": { - "check-coverage": true - }, - "version": "1.1.4" -} diff --git a/node_modules/code-point-at/index.js b/node_modules/code-point-at/index.js deleted file mode 100644 index 0432fe6..0000000 --- a/node_modules/code-point-at/index.js +++ /dev/null @@ -1,32 +0,0 @@ -/* eslint-disable babel/new-cap, xo/throw-new-error */ -'use strict'; -module.exports = function (str, pos) { - if (str === null || str === undefined) { - throw TypeError(); - } - - str = String(str); - - var size = str.length; - var i = pos ? Number(pos) : 0; - - if (Number.isNaN(i)) { - i = 0; - } - - if (i < 0 || i >= size) { - return undefined; - } - - var first = str.charCodeAt(i); - - if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { - var second = str.charCodeAt(i + 1); - - if (second >= 0xDC00 && second <= 0xDFFF) { - return ((first - 0xD800) * 0x400) + second - 0xDC00 + 0x10000; - } - } - - return first; -}; diff --git a/node_modules/code-point-at/license b/node_modules/code-point-at/license deleted file mode 100644 index 654d0bf..0000000 --- a/node_modules/code-point-at/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/code-point-at/package.json b/node_modules/code-point-at/package.json deleted file mode 100644 index 5b5809d..0000000 --- a/node_modules/code-point-at/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "_from": "code-point-at@^1.0.0", - "_id": "code-point-at@1.1.0", - "_inBundle": false, - "_integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", - "_location": "/code-point-at", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "code-point-at@^1.0.0", - "name": "code-point-at", - "escapedName": "code-point-at", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/string-width" - ], - "_resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", - "_shasum": "0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77", - "_spec": "code-point-at@^1.0.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/string-width", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "bugs": { - "url": "https://github.com/sindresorhus/code-point-at/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "ES2015 `String#codePointAt()` ponyfill", - "devDependencies": { - "ava": "*", - "xo": "^0.16.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/sindresorhus/code-point-at#readme", - "keywords": [ - "es2015", - "ponyfill", - "polyfill", - "shim", - "string", - "str", - "code", - "point", - "at", - "codepoint", - "unicode" - ], - "license": "MIT", - "name": "code-point-at", - "repository": { - "type": "git", - "url": "git+https://github.com/sindresorhus/code-point-at.git" - }, - "scripts": { - "test": "xo && ava" - }, - "version": "1.1.0" -} diff --git a/node_modules/code-point-at/readme.md b/node_modules/code-point-at/readme.md deleted file mode 100644 index 4c97730..0000000 --- a/node_modules/code-point-at/readme.md +++ /dev/null @@ -1,32 +0,0 @@ -# code-point-at [![Build Status](https://travis-ci.org/sindresorhus/code-point-at.svg?branch=master)](https://travis-ci.org/sindresorhus/code-point-at) - -> ES2015 [`String#codePointAt()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) [ponyfill](https://ponyfill.com) - - -## Install - -``` -$ npm install --save code-point-at -``` - - -## Usage - -```js -var codePointAt = require('code-point-at'); - -codePointAt('🐴'); -//=> 128052 - -codePointAt('abc', 2); -//=> 99 -``` - -## API - -### codePointAt(input, [position]) - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/console-control-strings/LICENSE b/node_modules/console-control-strings/LICENSE deleted file mode 100644 index e756052..0000000 --- a/node_modules/console-control-strings/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2014, Rebecca Turner - -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/console-control-strings/README.md b/node_modules/console-control-strings/README.md deleted file mode 100644 index f58cc8d..0000000 --- a/node_modules/console-control-strings/README.md +++ /dev/null @@ -1,145 +0,0 @@ -# Console Control Strings - -A library of cross-platform tested terminal/console command strings for -doing things like color and cursor positioning. This is a subset of both -ansi and vt100. All control codes included work on both Windows & Unix-like -OSes, except where noted. - -## Usage - -```js -var consoleControl = require('console-control-strings') - -console.log(consoleControl.color('blue','bgRed', 'bold') + 'hi there' + consoleControl.color('reset')) -process.stdout.write(consoleControl.goto(75, 10)) -``` - -## Why Another? - -There are tons of libraries similar to this one. I wanted one that was: - -1. Very clear about compatibility goals. -2. Could emit, for instance, a start color code without an end one. -3. Returned strings w/o writing to streams. -4. Was not weighed down with other unrelated baggage. - -## Functions - -### var code = consoleControl.up(_num = 1_) - -Returns the escape sequence to move _num_ lines up. - -### var code = consoleControl.down(_num = 1_) - -Returns the escape sequence to move _num_ lines down. - -### var code = consoleControl.forward(_num = 1_) - -Returns the escape sequence to move _num_ lines righ. - -### var code = consoleControl.back(_num = 1_) - -Returns the escape sequence to move _num_ lines left. - -### var code = consoleControl.nextLine(_num = 1_) - -Returns the escape sequence to move _num_ lines down and to the beginning of -the line. - -### var code = consoleControl.previousLine(_num = 1_) - -Returns the escape sequence to move _num_ lines up and to the beginning of -the line. - -### var code = consoleControl.eraseData() - -Returns the escape sequence to erase everything from the current cursor -position to the bottom right of the screen. This is line based, so it -erases the remainder of the current line and all following lines. - -### var code = consoleControl.eraseLine() - -Returns the escape sequence to erase to the end of the current line. - -### var code = consoleControl.goto(_x_, _y_) - -Returns the escape sequence to move the cursor to the designated position. -Note that the origin is _1, 1_ not _0, 0_. - -### var code = consoleControl.gotoSOL() - -Returns the escape sequence to move the cursor to the beginning of the -current line. (That is, it returns a carriage return, `\r`.) - -### var code = consoleControl.beep() - -Returns the escape sequence to cause the termianl to beep. (That is, it -returns unicode character `\x0007`, a Control-G.) - -### var code = consoleControl.hideCursor() - -Returns the escape sequence to hide the cursor. - -### var code = consoleControl.showCursor() - -Returns the escape sequence to show the cursor. - -### var code = consoleControl.color(_colors = []_) - -### var code = consoleControl.color(_color1_, _color2_, _…_, _colorn_) - -Returns the escape sequence to set the current terminal display attributes -(mostly colors). Arguments can either be a list of attributes or an array -of attributes. The difference between passing in an array or list of colors -and calling `.color` separately for each one, is that in the former case a -single escape sequence will be produced where as in the latter each change -will have its own distinct escape sequence. Each attribute can be one of: - -* Reset: - * **reset** – Reset all attributes to the terminal default. -* Styles: - * **bold** – Display text as bold. In some terminals this means using a - bold font, in others this means changing the color. In some it means - both. - * **italic** – Display text as italic. This is not available in most Windows terminals. - * **underline** – Underline text. This is not available in most Windows Terminals. - * **inverse** – Invert the foreground and background colors. - * **stopBold** – Do not display text as bold. - * **stopItalic** – Do not display text as italic. - * **stopUnderline** – Do not underline text. - * **stopInverse** – Do not invert foreground and background. -* Colors: - * **white** - * **black** - * **blue** - * **cyan** - * **green** - * **magenta** - * **red** - * **yellow** - * **grey** / **brightBlack** - * **brightRed** - * **brightGreen** - * **brightYellow** - * **brightBlue** - * **brightMagenta** - * **brightCyan** - * **brightWhite** -* Background Colors: - * **bgWhite** - * **bgBlack** - * **bgBlue** - * **bgCyan** - * **bgGreen** - * **bgMagenta** - * **bgRed** - * **bgYellow** - * **bgGrey** / **bgBrightBlack** - * **bgBrightRed** - * **bgBrightGreen** - * **bgBrightYellow** - * **bgBrightBlue** - * **bgBrightMagenta** - * **bgBrightCyan** - * **bgBrightWhite** - diff --git a/node_modules/console-control-strings/README.md~ b/node_modules/console-control-strings/README.md~ deleted file mode 100644 index 6eb34e8..0000000 --- a/node_modules/console-control-strings/README.md~ +++ /dev/null @@ -1,140 +0,0 @@ -# Console Control Strings - -A library of cross-platform tested terminal/console command strings for -doing things like color and cursor positioning. This is a subset of both -ansi and vt100. All control codes included work on both Windows & Unix-like -OSes, except where noted. - -## Usage - -```js -var consoleControl = require('console-control-strings') - -console.log(consoleControl.color('blue','bgRed', 'bold') + 'hi there' + consoleControl.color('reset')) -process.stdout.write(consoleControl.goto(75, 10)) -``` - -## Why Another? - -There are tons of libraries similar to this one. I wanted one that was: - -1. Very clear about compatibility goals. -2. Could emit, for instance, a start color code without an end one. -3. Returned strings w/o writing to streams. -4. Was not weighed down with other unrelated baggage. - -## Functions - -### var code = consoleControl.up(_num = 1_) - -Returns the escape sequence to move _num_ lines up. - -### var code = consoleControl.down(_num = 1_) - -Returns the escape sequence to move _num_ lines down. - -### var code = consoleControl.forward(_num = 1_) - -Returns the escape sequence to move _num_ lines righ. - -### var code = consoleControl.back(_num = 1_) - -Returns the escape sequence to move _num_ lines left. - -### var code = consoleControl.nextLine(_num = 1_) - -Returns the escape sequence to move _num_ lines down and to the beginning of -the line. - -### var code = consoleControl.previousLine(_num = 1_) - -Returns the escape sequence to move _num_ lines up and to the beginning of -the line. - -### var code = consoleControl.eraseData() - -Returns the escape sequence to erase everything from the current cursor -position to the bottom right of the screen. This is line based, so it -erases the remainder of the current line and all following lines. - -### var code = consoleControl.eraseLine() - -Returns the escape sequence to erase to the end of the current line. - -### var code = consoleControl.goto(_x_, _y_) - -Returns the escape sequence to move the cursor to the designated position. -Note that the origin is _1, 1_ not _0, 0_. - -### var code = consoleControl.gotoSOL() - -Returns the escape sequence to move the cursor to the beginning of the -current line. (That is, it returns a carriage return, `\r`.) - -### var code = consoleControl.hideCursor() - -Returns the escape sequence to hide the cursor. - -### var code = consoleControl.showCursor() - -Returns the escape sequence to show the cursor. - -### var code = consoleControl.color(_colors = []_) - -### var code = consoleControl.color(_color1_, _color2_, _…_, _colorn_) - -Returns the escape sequence to set the current terminal display attributes -(mostly colors). Arguments can either be a list of attributes or an array -of attributes. The difference between passing in an array or list of colors -and calling `.color` separately for each one, is that in the former case a -single escape sequence will be produced where as in the latter each change -will have its own distinct escape sequence. Each attribute can be one of: - -* Reset: - * **reset** – Reset all attributes to the terminal default. -* Styles: - * **bold** – Display text as bold. In some terminals this means using a - bold font, in others this means changing the color. In some it means - both. - * **italic** – Display text as italic. This is not available in most Windows terminals. - * **underline** – Underline text. This is not available in most Windows Terminals. - * **inverse** – Invert the foreground and background colors. - * **stopBold** – Do not display text as bold. - * **stopItalic** – Do not display text as italic. - * **stopUnderline** – Do not underline text. - * **stopInverse** – Do not invert foreground and background. -* Colors: - * **white** - * **black** - * **blue** - * **cyan** - * **green** - * **magenta** - * **red** - * **yellow** - * **grey** / **brightBlack** - * **brightRed** - * **brightGreen** - * **brightYellow** - * **brightBlue** - * **brightMagenta** - * **brightCyan** - * **brightWhite** -* Background Colors: - * **bgWhite** - * **bgBlack** - * **bgBlue** - * **bgCyan** - * **bgGreen** - * **bgMagenta** - * **bgRed** - * **bgYellow** - * **bgGrey** / **bgBrightBlack** - * **bgBrightRed** - * **bgBrightGreen** - * **bgBrightYellow** - * **bgBrightBlue** - * **bgBrightMagenta** - * **bgBrightCyan** - * **bgBrightWhite** - diff --git a/node_modules/console-control-strings/index.js b/node_modules/console-control-strings/index.js deleted file mode 100644 index bf89034..0000000 --- a/node_modules/console-control-strings/index.js +++ /dev/null @@ -1,125 +0,0 @@ -'use strict' - -// These tables borrowed from `ansi` - -var prefix = '\x1b[' - -exports.up = function up (num) { - return prefix + (num || '') + 'A' -} - -exports.down = function down (num) { - return prefix + (num || '') + 'B' -} - -exports.forward = function forward (num) { - return prefix + (num || '') + 'C' -} - -exports.back = function back (num) { - return prefix + (num || '') + 'D' -} - -exports.nextLine = function nextLine (num) { - return prefix + (num || '') + 'E' -} - -exports.previousLine = function previousLine (num) { - return prefix + (num || '') + 'F' -} - -exports.horizontalAbsolute = function horizontalAbsolute (num) { - if (num == null) throw new Error('horizontalAboslute requires a column to position to') - return prefix + num + 'G' -} - -exports.eraseData = function eraseData () { - return prefix + 'J' -} - -exports.eraseLine = function eraseLine () { - return prefix + 'K' -} - -exports.goto = function (x, y) { - return prefix + y + ';' + x + 'H' -} - -exports.gotoSOL = function () { - return '\r' -} - -exports.beep = function () { - return '\x07' -} - -exports.hideCursor = function hideCursor () { - return prefix + '?25l' -} - -exports.showCursor = function showCursor () { - return prefix + '?25h' -} - -var colors = { - reset: 0, -// styles - bold: 1, - italic: 3, - underline: 4, - inverse: 7, -// resets - stopBold: 22, - stopItalic: 23, - stopUnderline: 24, - stopInverse: 27, -// colors - white: 37, - black: 30, - blue: 34, - cyan: 36, - green: 32, - magenta: 35, - red: 31, - yellow: 33, - bgWhite: 47, - bgBlack: 40, - bgBlue: 44, - bgCyan: 46, - bgGreen: 42, - bgMagenta: 45, - bgRed: 41, - bgYellow: 43, - - grey: 90, - brightBlack: 90, - brightRed: 91, - brightGreen: 92, - brightYellow: 93, - brightBlue: 94, - brightMagenta: 95, - brightCyan: 96, - brightWhite: 97, - - bgGrey: 100, - bgBrightBlack: 100, - bgBrightRed: 101, - bgBrightGreen: 102, - bgBrightYellow: 103, - bgBrightBlue: 104, - bgBrightMagenta: 105, - bgBrightCyan: 106, - bgBrightWhite: 107 -} - -exports.color = function color (colorWith) { - if (arguments.length !== 1 || !Array.isArray(colorWith)) { - colorWith = Array.prototype.slice.call(arguments) - } - return prefix + colorWith.map(colorNameToCode).join(';') + 'm' -} - -function colorNameToCode (color) { - if (colors[color] != null) return colors[color] - throw new Error('Unknown color or style name: ' + color) -} diff --git a/node_modules/console-control-strings/package.json b/node_modules/console-control-strings/package.json deleted file mode 100644 index f4f6eaa..0000000 --- a/node_modules/console-control-strings/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "_from": "console-control-strings@~1.1.0", - "_id": "console-control-strings@1.1.0", - "_inBundle": false, - "_integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", - "_location": "/console-control-strings", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "console-control-strings@~1.1.0", - "name": "console-control-strings", - "escapedName": "console-control-strings", - "rawSpec": "~1.1.0", - "saveSpec": null, - "fetchSpec": "~1.1.0" - }, - "_requiredBy": [ - "/gauge", - "/npmlog" - ], - "_resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", - "_shasum": "3d7cf4464db6446ea644bf4b39507f9851008e8e", - "_spec": "console-control-strings@~1.1.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/npmlog", - "author": { - "name": "Rebecca Turner", - "email": "me@re-becca.org", - "url": "http://re-becca.org/" - }, - "bugs": { - "url": "https://github.com/iarna/console-control-strings/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "A library of cross-platform tested terminal/console command strings for doing things like color and cursor positioning. This is a subset of both ansi and vt100. All control codes included work on both Windows & Unix-like OSes, except where noted.", - "devDependencies": { - "standard": "^7.1.2", - "tap": "^5.7.2" - }, - "directories": { - "test": "test" - }, - "files": [ - "LICENSE", - "index.js" - ], - "homepage": "https://github.com/iarna/console-control-strings#readme", - "keywords": [], - "license": "ISC", - "main": "index.js", - "name": "console-control-strings", - "repository": { - "type": "git", - "url": "git+https://github.com/iarna/console-control-strings.git" - }, - "scripts": { - "test": "standard && tap test/*.js" - }, - "version": "1.1.0" -} diff --git a/node_modules/content-disposition/HISTORY.md b/node_modules/content-disposition/HISTORY.md deleted file mode 100644 index 63a3d08..0000000 --- a/node_modules/content-disposition/HISTORY.md +++ /dev/null @@ -1,55 +0,0 @@ -0.5.3 / 2018-12-17 -================== - - * Use `safe-buffer` for improved Buffer API - -0.5.2 / 2016-12-08 -================== - - * Fix `parse` to accept any linear whitespace character - -0.5.1 / 2016-01-17 -================== - - * perf: enable strict mode - -0.5.0 / 2014-10-11 -================== - - * Add `parse` function - -0.4.0 / 2014-09-21 -================== - - * Expand non-Unicode `filename` to the full ISO-8859-1 charset - -0.3.0 / 2014-09-20 -================== - - * Add `fallback` option - * Add `type` option - -0.2.0 / 2014-09-19 -================== - - * Reduce ambiguity of file names with hex escape in buggy browsers - -0.1.2 / 2014-09-19 -================== - - * Fix periodic invalid Unicode filename header - -0.1.1 / 2014-09-19 -================== - - * Fix invalid characters appearing in `filename*` parameter - -0.1.0 / 2014-09-18 -================== - - * Make the `filename` argument optional - -0.0.0 / 2014-09-18 -================== - - * Initial release diff --git a/node_modules/content-disposition/LICENSE b/node_modules/content-disposition/LICENSE deleted file mode 100644 index 84441fb..0000000 --- a/node_modules/content-disposition/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2014-2017 Douglas Christopher Wilson - -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/content-disposition/README.md b/node_modules/content-disposition/README.md deleted file mode 100644 index eebef13..0000000 --- a/node_modules/content-disposition/README.md +++ /dev/null @@ -1,148 +0,0 @@ -# content-disposition - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Create and parse HTTP `Content-Disposition` header - -## Installation - -```sh -$ npm install content-disposition -``` - -## API - - - -```js -var contentDisposition = require('content-disposition') -``` - -### contentDisposition(filename, options) - -Create an attachment `Content-Disposition` header value using the given file name, -if supplied. The `filename` is optional and if no file name is desired, but you -want to specify `options`, set `filename` to `undefined`. - - - -```js -res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) -``` - -**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this -header through a means different from `setHeader` in Node.js, you'll want to specify -the `'binary'` encoding in Node.js. - -#### Options - -`contentDisposition` accepts these properties in the options object. - -##### fallback - -If the `filename` option is outside ISO-8859-1, then the file name is actually -stored in a supplemental field for clients that support Unicode file names and -a ISO-8859-1 version of the file name is automatically generated. - -This specifies the ISO-8859-1 file name to override the automatic generation or -disables the generation all together, defaults to `true`. - - - A string will specify the ISO-8859-1 file name to use in place of automatic - generation. - - `false` will disable including a ISO-8859-1 file name and only include the - Unicode version (unless the file name is already ISO-8859-1). - - `true` will enable automatic generation if the file name is outside ISO-8859-1. - -If the `filename` option is ISO-8859-1 and this option is specified and has a -different value, then the `filename` option is encoded in the extended field -and this set as the fallback field, even though they are both ISO-8859-1. - -##### type - -Specifies the disposition type, defaults to `"attachment"`. This can also be -`"inline"`, or any other value (all values except inline are treated like -`attachment`, but can convey additional information if both parties agree to -it). The type is normalized to lower-case. - -### contentDisposition.parse(string) - - - -```js -var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt') -``` - -Parse a `Content-Disposition` header string. This automatically handles extended -("Unicode") parameters by decoding them and providing them under the standard -parameter name. This will return an object with the following properties (examples -are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): - - - `type`: The disposition type (always lower case). Example: `'attachment'` - - - `parameters`: An object of the parameters in the disposition (name of parameter - always lower case and extended versions replace non-extended versions). Example: - `{filename: "€ rates.txt"}` - -## Examples - -### Send a file for download - -```js -var contentDisposition = require('content-disposition') -var destroy = require('destroy') -var fs = require('fs') -var http = require('http') -var onFinished = require('on-finished') - -var filePath = '/path/to/public/plans.pdf' - -http.createServer(function onRequest (req, res) { - // set headers - res.setHeader('Content-Type', 'application/pdf') - res.setHeader('Content-Disposition', contentDisposition(filePath)) - - // send file - var stream = fs.createReadStream(filePath) - stream.pipe(res) - onFinished(res, function () { - destroy(stream) - }) -}) -``` - -## Testing - -```sh -$ npm test -``` - -## References - -- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] -- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] -- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] -- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] - -[rfc-2616]: https://tools.ietf.org/html/rfc2616 -[rfc-5987]: https://tools.ietf.org/html/rfc5987 -[rfc-6266]: https://tools.ietf.org/html/rfc6266 -[tc-2231]: http://greenbytes.de/tech/tc2231/ - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/content-disposition.svg -[npm-url]: https://npmjs.org/package/content-disposition -[node-version-image]: https://img.shields.io/node/v/content-disposition.svg -[node-version-url]: https://nodejs.org/en/download -[travis-image]: https://img.shields.io/travis/jshttp/content-disposition.svg -[travis-url]: https://travis-ci.org/jshttp/content-disposition -[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg -[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master -[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg -[downloads-url]: https://npmjs.org/package/content-disposition diff --git a/node_modules/content-disposition/index.js b/node_modules/content-disposition/index.js deleted file mode 100644 index 3092a4d..0000000 --- a/node_modules/content-disposition/index.js +++ /dev/null @@ -1,458 +0,0 @@ -/*! - * content-disposition - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module exports. - * @public - */ - -module.exports = contentDisposition -module.exports.parse = parse - -/** - * Module dependencies. - * @private - */ - -var basename = require('path').basename -var Buffer = require('safe-buffer').Buffer - -/** - * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") - * @private - */ - -var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex - -/** - * RegExp to match percent encoding escape. - * @private - */ - -var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ -var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g - -/** - * RegExp to match non-latin1 characters. - * @private - */ - -var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g - -/** - * RegExp to match quoted-pair in RFC 2616 - * - * quoted-pair = "\" CHAR - * CHAR = - * @private - */ - -var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex - -/** - * RegExp to match chars that must be quoted-pair in RFC 2616 - * @private - */ - -var QUOTE_REGEXP = /([\\"])/g - -/** - * RegExp for various RFC 2616 grammar - * - * parameter = token "=" ( token | quoted-string ) - * token = 1* - * separators = "(" | ")" | "<" | ">" | "@" - * | "," | ";" | ":" | "\" | <"> - * | "/" | "[" | "]" | "?" | "=" - * | "{" | "}" | SP | HT - * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - * qdtext = > - * quoted-pair = "\" CHAR - * CHAR = - * TEXT = - * LWS = [CRLF] 1*( SP | HT ) - * CRLF = CR LF - * CR = - * LF = - * SP = - * HT = - * CTL = - * OCTET = - * @private - */ - -var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex -var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ - -/** - * RegExp for various RFC 5987 grammar - * - * ext-value = charset "'" [ language ] "'" value-chars - * charset = "UTF-8" / "ISO-8859-1" / mime-charset - * mime-charset = 1*mime-charsetc - * mime-charsetc = ALPHA / DIGIT - * / "!" / "#" / "$" / "%" / "&" - * / "+" / "-" / "^" / "_" / "`" - * / "{" / "}" / "~" - * language = ( 2*3ALPHA [ extlang ] ) - * / 4ALPHA - * / 5*8ALPHA - * extlang = *3( "-" 3ALPHA ) - * value-chars = *( pct-encoded / attr-char ) - * pct-encoded = "%" HEXDIG HEXDIG - * attr-char = ALPHA / DIGIT - * / "!" / "#" / "$" / "&" / "+" / "-" / "." - * / "^" / "_" / "`" / "|" / "~" - * @private - */ - -var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ - -/** - * RegExp for various RFC 6266 grammar - * - * disposition-type = "inline" | "attachment" | disp-ext-type - * disp-ext-type = token - * disposition-parm = filename-parm | disp-ext-parm - * filename-parm = "filename" "=" value - * | "filename*" "=" ext-value - * disp-ext-parm = token "=" value - * | ext-token "=" ext-value - * ext-token = - * @private - */ - -var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex - -/** - * Create an attachment Content-Disposition header. - * - * @param {string} [filename] - * @param {object} [options] - * @param {string} [options.type=attachment] - * @param {string|boolean} [options.fallback=true] - * @return {string} - * @public - */ - -function contentDisposition (filename, options) { - var opts = options || {} - - // get type - var type = opts.type || 'attachment' - - // get parameters - var params = createparams(filename, opts.fallback) - - // format into string - return format(new ContentDisposition(type, params)) -} - -/** - * Create parameters object from filename and fallback. - * - * @param {string} [filename] - * @param {string|boolean} [fallback=true] - * @return {object} - * @private - */ - -function createparams (filename, fallback) { - if (filename === undefined) { - return - } - - var params = {} - - if (typeof filename !== 'string') { - throw new TypeError('filename must be a string') - } - - // fallback defaults to true - if (fallback === undefined) { - fallback = true - } - - if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { - throw new TypeError('fallback must be a string or boolean') - } - - if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { - throw new TypeError('fallback must be ISO-8859-1 string') - } - - // restrict to file base name - var name = basename(filename) - - // determine if name is suitable for quoted string - var isQuotedString = TEXT_REGEXP.test(name) - - // generate fallback name - var fallbackName = typeof fallback !== 'string' - ? fallback && getlatin1(name) - : basename(fallback) - var hasFallback = typeof fallbackName === 'string' && fallbackName !== name - - // set extended filename parameter - if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { - params['filename*'] = name - } - - // set filename parameter - if (isQuotedString || hasFallback) { - params.filename = hasFallback - ? fallbackName - : name - } - - return params -} - -/** - * Format object to Content-Disposition header. - * - * @param {object} obj - * @param {string} obj.type - * @param {object} [obj.parameters] - * @return {string} - * @private - */ - -function format (obj) { - var parameters = obj.parameters - var type = obj.type - - if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { - throw new TypeError('invalid type') - } - - // start with normalized type - var string = String(type).toLowerCase() - - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() - - for (var i = 0; i < params.length; i++) { - param = params[i] - - var val = param.substr(-1) === '*' - ? ustring(parameters[param]) - : qstring(parameters[param]) - - string += '; ' + param + '=' + val - } - } - - return string -} - -/** - * Decode a RFC 6987 field value (gracefully). - * - * @param {string} str - * @return {string} - * @private - */ - -function decodefield (str) { - var match = EXT_VALUE_REGEXP.exec(str) - - if (!match) { - throw new TypeError('invalid extended field value') - } - - var charset = match[1].toLowerCase() - var encoded = match[2] - var value - - // to binary string - var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) - - switch (charset) { - case 'iso-8859-1': - value = getlatin1(binary) - break - case 'utf-8': - value = Buffer.from(binary, 'binary').toString('utf8') - break - default: - throw new TypeError('unsupported charset in extended field') - } - - return value -} - -/** - * Get ISO-8859-1 version of string. - * - * @param {string} val - * @return {string} - * @private - */ - -function getlatin1 (val) { - // simple Unicode -> ISO-8859-1 transformation - return String(val).replace(NON_LATIN1_REGEXP, '?') -} - -/** - * Parse Content-Disposition header string. - * - * @param {string} string - * @return {object} - * @public - */ - -function parse (string) { - if (!string || typeof string !== 'string') { - throw new TypeError('argument string is required') - } - - var match = DISPOSITION_TYPE_REGEXP.exec(string) - - if (!match) { - throw new TypeError('invalid type format') - } - - // normalize type - var index = match[0].length - var type = match[1].toLowerCase() - - var key - var names = [] - var params = {} - var value - - // calculate index to start at - index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' - ? index - 1 - : index - - // match parameters - while ((match = PARAM_REGEXP.exec(string))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } - - index += match[0].length - key = match[1].toLowerCase() - value = match[2] - - if (names.indexOf(key) !== -1) { - throw new TypeError('invalid duplicate parameter') - } - - names.push(key) - - if (key.indexOf('*') + 1 === key.length) { - // decode extended value - key = key.slice(0, -1) - value = decodefield(value) - - // overwrite existing value - params[key] = value - continue - } - - if (typeof params[key] === 'string') { - continue - } - - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') - } - - params[key] = value - } - - if (index !== -1 && index !== string.length) { - throw new TypeError('invalid parameter format') - } - - return new ContentDisposition(type, params) -} - -/** - * Percent decode a single character. - * - * @param {string} str - * @param {string} hex - * @return {string} - * @private - */ - -function pdecode (str, hex) { - return String.fromCharCode(parseInt(hex, 16)) -} - -/** - * Percent encode a single character. - * - * @param {string} char - * @return {string} - * @private - */ - -function pencode (char) { - return '%' + String(char) - .charCodeAt(0) - .toString(16) - .toUpperCase() -} - -/** - * Quote a string for HTTP. - * - * @param {string} val - * @return {string} - * @private - */ - -function qstring (val) { - var str = String(val) - - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} - -/** - * Encode a Unicode string for HTTP (RFC 5987). - * - * @param {string} val - * @return {string} - * @private - */ - -function ustring (val) { - var str = String(val) - - // percent encode as UTF-8 - var encoded = encodeURIComponent(str) - .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) - - return 'UTF-8\'\'' + encoded -} - -/** - * Class for parsed Content-Disposition header for v8 optimization - * - * @public - * @param {string} type - * @param {object} parameters - * @constructor - */ - -function ContentDisposition (type, parameters) { - this.type = type - this.parameters = parameters -} diff --git a/node_modules/content-disposition/node_modules/safe-buffer/LICENSE b/node_modules/content-disposition/node_modules/safe-buffer/LICENSE deleted file mode 100644 index 0c068ce..0000000 --- a/node_modules/content-disposition/node_modules/safe-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -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/content-disposition/node_modules/safe-buffer/README.md b/node_modules/content-disposition/node_modules/safe-buffer/README.md deleted file mode 100644 index e9a81af..0000000 --- a/node_modules/content-disposition/node_modules/safe-buffer/README.md +++ /dev/null @@ -1,584 +0,0 @@ -# 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/content-disposition/node_modules/safe-buffer/index.d.ts b/node_modules/content-disposition/node_modules/safe-buffer/index.d.ts deleted file mode 100644 index e9fed80..0000000 --- a/node_modules/content-disposition/node_modules/safe-buffer/index.d.ts +++ /dev/null @@ -1,187 +0,0 @@ -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/content-disposition/node_modules/safe-buffer/index.js b/node_modules/content-disposition/node_modules/safe-buffer/index.js deleted file mode 100644 index 22438da..0000000 --- a/node_modules/content-disposition/node_modules/safe-buffer/index.js +++ /dev/null @@ -1,62 +0,0 @@ -/* 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/content-disposition/node_modules/safe-buffer/package.json b/node_modules/content-disposition/node_modules/safe-buffer/package.json deleted file mode 100644 index d493e42..0000000 --- a/node_modules/content-disposition/node_modules/safe-buffer/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "_from": "safe-buffer@5.1.2", - "_id": "safe-buffer@5.1.2", - "_inBundle": false, - "_integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "_location": "/content-disposition/safe-buffer", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "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": [ - "/content-disposition" - ], - "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "_shasum": "991ec69d296e0313747d59bdfd2b745c35f8828d", - "_spec": "safe-buffer@5.1.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/content-disposition", - "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/content-disposition/package.json b/node_modules/content-disposition/package.json deleted file mode 100644 index fbd1b90..0000000 --- a/node_modules/content-disposition/package.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "_from": "content-disposition@0.5.3", - "_id": "content-disposition@0.5.3", - "_inBundle": false, - "_integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", - "_location": "/content-disposition", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "content-disposition@0.5.3", - "name": "content-disposition", - "escapedName": "content-disposition", - "rawSpec": "0.5.3", - "saveSpec": null, - "fetchSpec": "0.5.3" - }, - "_requiredBy": [ - "/express" - ], - "_resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", - "_shasum": "e130caf7e7279087c5616c2007d0485698984fbd", - "_spec": "content-disposition@0.5.3", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "author": { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - "bugs": { - "url": "https://github.com/jshttp/content-disposition/issues" - }, - "bundleDependencies": false, - "dependencies": { - "safe-buffer": "5.1.2" - }, - "deprecated": false, - "description": "Create and parse Content-Disposition header", - "devDependencies": { - "deep-equal": "1.0.1", - "eslint": "5.10.0", - "eslint-config-standard": "12.0.0", - "eslint-plugin-import": "2.14.0", - "eslint-plugin-markdown": "1.0.0-rc.1", - "eslint-plugin-node": "7.0.1", - "eslint-plugin-promise": "4.0.1", - "eslint-plugin-standard": "4.0.0", - "istanbul": "0.4.5", - "mocha": "5.2.0" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "LICENSE", - "HISTORY.md", - "README.md", - "index.js" - ], - "homepage": "https://github.com/jshttp/content-disposition#readme", - "keywords": [ - "content-disposition", - "http", - "rfc6266", - "res" - ], - "license": "MIT", - "name": "content-disposition", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/content-disposition.git" - }, - "scripts": { - "lint": "eslint --plugin markdown --ext js,md .", - "test": "mocha --reporter spec --bail --check-leaks test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" - }, - "version": "0.5.3" -} diff --git a/node_modules/content-type/HISTORY.md b/node_modules/content-type/HISTORY.md deleted file mode 100644 index 8f5cb70..0000000 --- a/node_modules/content-type/HISTORY.md +++ /dev/null @@ -1,24 +0,0 @@ -1.0.4 / 2017-09-11 -================== - - * perf: skip parameter parsing when no parameters - -1.0.3 / 2017-09-10 -================== - - * perf: remove argument reassignment - -1.0.2 / 2016-05-09 -================== - - * perf: enable strict mode - -1.0.1 / 2015-02-13 -================== - - * Improve missing `Content-Type` header error message - -1.0.0 / 2015-02-01 -================== - - * Initial implementation, derived from `media-typer@0.3.0` diff --git a/node_modules/content-type/LICENSE b/node_modules/content-type/LICENSE deleted file mode 100644 index 34b1a2d..0000000 --- a/node_modules/content-type/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2015 Douglas Christopher Wilson - -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/content-type/README.md b/node_modules/content-type/README.md deleted file mode 100644 index 3ed6741..0000000 --- a/node_modules/content-type/README.md +++ /dev/null @@ -1,92 +0,0 @@ -# content-type - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Create and parse HTTP Content-Type header according to RFC 7231 - -## Installation - -```sh -$ npm install content-type -``` - -## API - -```js -var contentType = require('content-type') -``` - -### contentType.parse(string) - -```js -var obj = contentType.parse('image/svg+xml; charset=utf-8') -``` - -Parse a content type string. This will return an object with the following -properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): - - - `type`: The media type (the type and subtype, always lower case). - Example: `'image/svg+xml'` - - - `parameters`: An object of the parameters in the media type (name of parameter - always lower case). Example: `{charset: 'utf-8'}` - -Throws a `TypeError` if the string is missing or invalid. - -### contentType.parse(req) - -```js -var obj = contentType.parse(req) -``` - -Parse the `content-type` header from the given `req`. Short-cut for -`contentType.parse(req.headers['content-type'])`. - -Throws a `TypeError` if the `Content-Type` header is missing or invalid. - -### contentType.parse(res) - -```js -var obj = contentType.parse(res) -``` - -Parse the `content-type` header set on the given `res`. Short-cut for -`contentType.parse(res.getHeader('content-type'))`. - -Throws a `TypeError` if the `Content-Type` header is missing or invalid. - -### contentType.format(obj) - -```js -var str = contentType.format({type: 'image/svg+xml'}) -``` - -Format an object into a content type string. This will return a string of the -content type for the given object with the following properties (examples are -shown that produce the string `'image/svg+xml; charset=utf-8'`): - - - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` - - - `parameters`: An object of the parameters in the media type (name of the - parameter will be lower-cased). Example: `{charset: 'utf-8'}` - -Throws a `TypeError` if the object contains an invalid type or parameter names. - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/content-type.svg -[npm-url]: https://npmjs.org/package/content-type -[node-version-image]: https://img.shields.io/node/v/content-type.svg -[node-version-url]: http://nodejs.org/download/ -[travis-image]: https://img.shields.io/travis/jshttp/content-type/master.svg -[travis-url]: https://travis-ci.org/jshttp/content-type -[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-type/master.svg -[coveralls-url]: https://coveralls.io/r/jshttp/content-type -[downloads-image]: https://img.shields.io/npm/dm/content-type.svg -[downloads-url]: https://npmjs.org/package/content-type diff --git a/node_modules/content-type/index.js b/node_modules/content-type/index.js deleted file mode 100644 index 6ce03f2..0000000 --- a/node_modules/content-type/index.js +++ /dev/null @@ -1,222 +0,0 @@ -/*! - * content-type - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - */ -var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g -var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ - -/** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF - */ -var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g - -/** - * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 - */ -var QUOTE_REGEXP = /([\\"])/g - -/** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token - */ -var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ - -/** - * Module exports. - * @public - */ - -exports.format = format -exports.parse = parse - -/** - * Format object to media type. - * - * @param {object} obj - * @return {string} - * @public - */ - -function format (obj) { - if (!obj || typeof obj !== 'object') { - throw new TypeError('argument obj is required') - } - - var parameters = obj.parameters - var type = obj.type - - if (!type || !TYPE_REGEXP.test(type)) { - throw new TypeError('invalid type') - } - - var string = type - - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() - - for (var i = 0; i < params.length; i++) { - param = params[i] - - if (!TOKEN_REGEXP.test(param)) { - throw new TypeError('invalid parameter name') - } - - string += '; ' + param + '=' + qstring(parameters[param]) - } - } - - return string -} - -/** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public - */ - -function parse (string) { - if (!string) { - throw new TypeError('argument string is required') - } - - // support req/res-like objects as argument - var header = typeof string === 'object' - ? getcontenttype(string) - : string - - if (typeof header !== 'string') { - throw new TypeError('argument string is required to be a string') - } - - var index = header.indexOf(';') - var type = index !== -1 - ? header.substr(0, index).trim() - : header.trim() - - if (!TYPE_REGEXP.test(type)) { - throw new TypeError('invalid media type') - } - - var obj = new ContentType(type.toLowerCase()) - - // parse parameters - if (index !== -1) { - var key - var match - var value - - PARAM_REGEXP.lastIndex = index - - while ((match = PARAM_REGEXP.exec(header))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } - - index += match[0].length - key = match[1].toLowerCase() - value = match[2] - - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') - } - - obj.parameters[key] = value - } - - if (index !== header.length) { - throw new TypeError('invalid parameter format') - } - } - - return obj -} - -/** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private - */ - -function getcontenttype (obj) { - var header - - if (typeof obj.getHeader === 'function') { - // res-like - header = obj.getHeader('content-type') - } else if (typeof obj.headers === 'object') { - // req-like - header = obj.headers && obj.headers['content-type'] - } - - if (typeof header !== 'string') { - throw new TypeError('content-type header is missing from object') - } - - return header -} - -/** - * Quote a string if necessary. - * - * @param {string} val - * @return {string} - * @private - */ - -function qstring (val) { - var str = String(val) - - // no need to quote tokens - if (TOKEN_REGEXP.test(str)) { - return str - } - - if (str.length > 0 && !TEXT_REGEXP.test(str)) { - throw new TypeError('invalid parameter value') - } - - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} - -/** - * Class to represent a content type. - * @private - */ -function ContentType (type) { - this.parameters = Object.create(null) - this.type = type -} diff --git a/node_modules/content-type/package.json b/node_modules/content-type/package.json deleted file mode 100644 index 2064075..0000000 --- a/node_modules/content-type/package.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "_from": "content-type@~1.0.4", - "_id": "content-type@1.0.4", - "_inBundle": false, - "_integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", - "_location": "/content-type", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "content-type@~1.0.4", - "name": "content-type", - "escapedName": "content-type", - "rawSpec": "~1.0.4", - "saveSpec": null, - "fetchSpec": "~1.0.4" - }, - "_requiredBy": [ - "/body-parser", - "/express" - ], - "_resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", - "_shasum": "e138cc75e040c727b1966fe5e5f8c9aee256fe3b", - "_spec": "content-type@~1.0.4", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "author": { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - "bugs": { - "url": "https://github.com/jshttp/content-type/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Create and parse HTTP Content-Type header", - "devDependencies": { - "eslint": "3.19.0", - "eslint-config-standard": "10.2.1", - "eslint-plugin-import": "2.7.0", - "eslint-plugin-node": "5.1.1", - "eslint-plugin-promise": "3.5.0", - "eslint-plugin-standard": "3.0.1", - "istanbul": "0.4.5", - "mocha": "~1.21.5" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "LICENSE", - "HISTORY.md", - "README.md", - "index.js" - ], - "homepage": "https://github.com/jshttp/content-type#readme", - "keywords": [ - "content-type", - "http", - "req", - "res", - "rfc7231" - ], - "license": "MIT", - "name": "content-type", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/content-type.git" - }, - "scripts": { - "lint": "eslint .", - "test": "mocha --reporter spec --check-leaks --bail test/", - "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" - }, - "version": "1.0.4" -} diff --git a/node_modules/cookie-signature/.npmignore b/node_modules/cookie-signature/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/cookie-signature/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/cookie-signature/History.md b/node_modules/cookie-signature/History.md deleted file mode 100644 index 78513cc..0000000 --- a/node_modules/cookie-signature/History.md +++ /dev/null @@ -1,38 +0,0 @@ -1.0.6 / 2015-02-03 -================== - -* use `npm test` instead of `make test` to run tests -* clearer assertion messages when checking input - - -1.0.5 / 2014-09-05 -================== - -* add license to package.json - -1.0.4 / 2014-06-25 -================== - - * corrected avoidance of timing attacks (thanks @tenbits!) - -1.0.3 / 2014-01-28 -================== - - * [incorrect] fix for timing attacks - -1.0.2 / 2014-01-28 -================== - - * fix missing repository warning - * fix typo in test - -1.0.1 / 2013-04-15 -================== - - * Revert "Changed underlying HMAC algo. to sha512." - * Revert "Fix for timing attacks on MAC verification." - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/cookie-signature/Readme.md b/node_modules/cookie-signature/Readme.md deleted file mode 100644 index 2559e84..0000000 --- a/node_modules/cookie-signature/Readme.md +++ /dev/null @@ -1,42 +0,0 @@ - -# cookie-signature - - Sign and unsign cookies. - -## Example - -```js -var cookie = require('cookie-signature'); - -var val = cookie.sign('hello', 'tobiiscool'); -val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); - -var val = cookie.sign('hello', 'tobiiscool'); -cookie.unsign(val, 'tobiiscool').should.equal('hello'); -cookie.unsign(val, 'luna').should.be.false; -``` - -## License - -(The MIT License) - -Copyright (c) 2012 LearnBoost <tj@learnboost.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. \ No newline at end of file diff --git a/node_modules/cookie-signature/index.js b/node_modules/cookie-signature/index.js deleted file mode 100644 index b8c9463..0000000 --- a/node_modules/cookie-signature/index.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Module dependencies. - */ - -var crypto = require('crypto'); - -/** - * Sign the given `val` with `secret`. - * - * @param {String} val - * @param {String} secret - * @return {String} - * @api private - */ - -exports.sign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - return val + '.' + crypto - .createHmac('sha256', secret) - .update(val) - .digest('base64') - .replace(/\=+$/, ''); -}; - -/** - * Unsign and decode the given `val` with `secret`, - * returning `false` if the signature is invalid. - * - * @param {String} val - * @param {String} secret - * @return {String|Boolean} - * @api private - */ - -exports.unsign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - var str = val.slice(0, val.lastIndexOf('.')) - , mac = exports.sign(str, secret); - - return sha1(mac) == sha1(val) ? str : false; -}; - -/** - * Private - */ - -function sha1(str){ - return crypto.createHash('sha1').update(str).digest('hex'); -} diff --git a/node_modules/cookie-signature/package.json b/node_modules/cookie-signature/package.json deleted file mode 100644 index a718c51..0000000 --- a/node_modules/cookie-signature/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "_from": "cookie-signature@1.0.6", - "_id": "cookie-signature@1.0.6", - "_inBundle": false, - "_integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=", - "_location": "/cookie-signature", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "cookie-signature@1.0.6", - "name": "cookie-signature", - "escapedName": "cookie-signature", - "rawSpec": "1.0.6", - "saveSpec": null, - "fetchSpec": "1.0.6" - }, - "_requiredBy": [ - "/express" - ], - "_resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", - "_shasum": "e303a882b342cc3ee8ca513a79999734dab3ae2c", - "_spec": "cookie-signature@1.0.6", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@learnboost.com" - }, - "bugs": { - "url": "https://github.com/visionmedia/node-cookie-signature/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Sign and unsign cookies", - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "homepage": "https://github.com/visionmedia/node-cookie-signature#readme", - "keywords": [ - "cookie", - "sign", - "unsign" - ], - "license": "MIT", - "main": "index", - "name": "cookie-signature", - "repository": { - "type": "git", - "url": "git+https://github.com/visionmedia/node-cookie-signature.git" - }, - "scripts": { - "test": "mocha --require should --reporter spec" - }, - "version": "1.0.6" -} diff --git a/node_modules/cookie/HISTORY.md b/node_modules/cookie/HISTORY.md deleted file mode 100644 index da2bf24..0000000 --- a/node_modules/cookie/HISTORY.md +++ /dev/null @@ -1,123 +0,0 @@ -0.4.0 / 2019-05-15 -================== - - * Add `SameSite=None` support - -0.3.1 / 2016-05-26 -================== - - * Fix `sameSite: true` to work with draft-7 clients - - `true` now sends `SameSite=Strict` instead of `SameSite` - -0.3.0 / 2016-05-26 -================== - - * Add `sameSite` option - - Replaces `firstPartyOnly` option, never implemented by browsers - * Improve error message when `encode` is not a function - * Improve error message when `expires` is not a `Date` - -0.2.4 / 2016-05-20 -================== - - * perf: enable strict mode - * perf: use for loop in parse - * perf: use string concatination for serialization - -0.2.3 / 2015-10-25 -================== - - * Fix cookie `Max-Age` to never be a floating point number - -0.2.2 / 2015-09-17 -================== - - * Fix regression when setting empty cookie value - - Ease the new restriction, which is just basic header-level validation - * Fix typo in invalid value errors - -0.2.1 / 2015-09-17 -================== - - * Throw on invalid values provided to `serialize` - - Ensures the resulting string is a valid HTTP header value - -0.2.0 / 2015-08-13 -================== - - * Add `firstPartyOnly` option - * Throw better error for invalid argument to parse - * perf: hoist regular expression - -0.1.5 / 2015-09-17 -================== - - * Fix regression when setting empty cookie value - - Ease the new restriction, which is just basic header-level validation - * Fix typo in invalid value errors - -0.1.4 / 2015-09-17 -================== - - * Throw better error for invalid argument to parse - * Throw on invalid values provided to `serialize` - - Ensures the resulting string is a valid HTTP header value - -0.1.3 / 2015-05-19 -================== - - * Reduce the scope of try-catch deopt - * Remove argument reassignments - -0.1.2 / 2014-04-16 -================== - - * Remove unnecessary files from npm package - -0.1.1 / 2014-02-23 -================== - - * Fix bad parse when cookie value contained a comma - * Fix support for `maxAge` of `0` - -0.1.0 / 2013-05-01 -================== - - * Add `decode` option - * Add `encode` option - -0.0.6 / 2013-04-08 -================== - - * Ignore cookie parts missing `=` - -0.0.5 / 2012-10-29 -================== - - * Return raw cookie value if value unescape errors - -0.0.4 / 2012-06-21 -================== - - * Use encode/decodeURIComponent for cookie encoding/decoding - - Improve server/client interoperability - -0.0.3 / 2012-06-06 -================== - - * Only escape special characters per the cookie RFC - -0.0.2 / 2012-06-01 -================== - - * Fix `maxAge` option to not throw error - -0.0.1 / 2012-05-28 -================== - - * Add more tests - -0.0.0 / 2012-05-28 -================== - - * Initial release diff --git a/node_modules/cookie/LICENSE b/node_modules/cookie/LICENSE deleted file mode 100644 index 058b6b4..0000000 --- a/node_modules/cookie/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2012-2014 Roman Shtylman -Copyright (c) 2015 Douglas Christopher Wilson - -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/cookie/README.md b/node_modules/cookie/README.md deleted file mode 100644 index 857fb77..0000000 --- a/node_modules/cookie/README.md +++ /dev/null @@ -1,253 +0,0 @@ -# cookie - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][npm-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Basic HTTP cookie parser and serializer for HTTP servers. - -## Installation - -```sh -$ npm install cookie -``` - -## API - -```js -var cookie = require('cookie'); -``` - -### cookie.parse(str, options) - -Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs. -The `str` argument is the string representing a `Cookie` header value and `options` is an -optional object containing additional parsing options. - -```js -var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2'); -// { foo: 'bar', equation: 'E=mc^2' } -``` - -#### Options - -`cookie.parse` accepts these properties in the options object. - -##### decode - -Specifies a function that will be used to decode a cookie's value. Since the value of a cookie -has a limited character set (and must be a simple string), this function can be used to decode -a previously-encoded cookie value into a JavaScript string or other object. - -The default function is the global `decodeURIComponent`, which will decode any URL-encoded -sequences into their byte representations. - -**note** if an error is thrown from this function, the original, non-decoded cookie value will -be returned as the cookie's value. - -### cookie.serialize(name, value, options) - -Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the -name for the cookie, the `value` argument is the value to set the cookie to, and the `options` -argument is an optional object containing additional serialization options. - -```js -var setCookie = cookie.serialize('foo', 'bar'); -// foo=bar -``` - -#### Options - -`cookie.serialize` accepts these properties in the options object. - -##### domain - -Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6265-5.2.3]. By default, no -domain is set, and most clients will consider the cookie to apply to only the current domain. - -##### encode - -Specifies a function that will be used to encode a cookie's value. Since value of a cookie -has a limited character set (and must be a simple string), this function can be used to encode -a value into a string suited for a cookie's value. - -The default function is the global `encodeURIComponent`, which will encode a JavaScript string -into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range. - -##### expires - -Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6265-5.2.1]. -By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and -will delete it on a condition like exiting a web browser application. - -**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and -`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, -so if both are set, they should point to the same date and time. - -##### httpOnly - -Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6265-5.2.6]. When truthy, -the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set. - -**note** be careful when setting this to `true`, as compliant clients will not allow client-side -JavaScript to see the cookie in `document.cookie`. - -##### maxAge - -Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6265-5.2.2]. -The given number will be converted to an integer by rounding down. By default, no maximum age is set. - -**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and -`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this, -so if both are set, they should point to the same date and time. - -##### path - -Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path -is considered the ["default path"][rfc-6265-5.1.4]. - -##### sameSite - -Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-03-4.1.2.7]. - - - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. - - `false` will not set the `SameSite` attribute. - - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. - - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie. - - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. - -More information about the different enforcement levels can be found in -[the specification][rfc-6265bis-03-4.1.2.7]. - -**note** This is an attribute that has not yet been fully standardized, and may change in the future. -This also means many clients may ignore this attribute until they understand it. - -##### secure - -Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy, -the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. - -**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to -the server in the future if the browser does not have an HTTPS connection. - -## Example - -The following example uses this module in conjunction with the Node.js core HTTP server -to prompt a user for their name and display it back on future visits. - -```js -var cookie = require('cookie'); -var escapeHtml = require('escape-html'); -var http = require('http'); -var url = require('url'); - -function onRequest(req, res) { - // Parse the query string - var query = url.parse(req.url, true, true).query; - - if (query && query.name) { - // Set a new cookie with the name - res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), { - httpOnly: true, - maxAge: 60 * 60 * 24 * 7 // 1 week - })); - - // Redirect back after setting cookie - res.statusCode = 302; - res.setHeader('Location', req.headers.referer || '/'); - res.end(); - return; - } - - // Parse the cookies on the request - var cookies = cookie.parse(req.headers.cookie || ''); - - // Get the visitor name set in the cookie - var name = cookies.name; - - res.setHeader('Content-Type', 'text/html; charset=UTF-8'); - - if (name) { - res.write('

Welcome back, ' + escapeHtml(name) + '!

'); - } else { - res.write('

Hello, new visitor!

'); - } - - res.write(''); - res.write(' '); - res.end(''); -} - -http.createServer(onRequest).listen(3000); -``` - -## Testing - -```sh -$ npm test -``` - -## Benchmark - -``` -$ npm run bench - -> cookie@0.3.1 bench cookie -> node benchmark/index.js - - http_parser@2.8.0 - node@6.14.2 - v8@5.1.281.111 - uv@1.16.1 - zlib@1.2.11 - ares@1.10.1-DEV - icu@58.2 - modules@48 - napi@3 - openssl@1.0.2o - -> node benchmark/parse.js - - cookie.parse - - 6 tests completed. - - simple x 1,200,691 ops/sec ±1.12% (189 runs sampled) - decode x 1,012,994 ops/sec ±0.97% (186 runs sampled) - unquote x 1,074,174 ops/sec ±2.43% (186 runs sampled) - duplicates x 438,424 ops/sec ±2.17% (184 runs sampled) - 10 cookies x 147,154 ops/sec ±1.01% (186 runs sampled) - 100 cookies x 14,274 ops/sec ±1.07% (187 runs sampled) -``` - -## References - -- [RFC 6265: HTTP State Management Mechanism][rfc-6265] -- [Same-site Cookies][rfc-6265bis-03-4.1.2.7] - -[rfc-6265bis-03-4.1.2.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7 -[rfc-6265]: https://tools.ietf.org/html/rfc6265 -[rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4 -[rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1 -[rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2 -[rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3 -[rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4 -[rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5 -[rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6 -[rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3 - -## License - -[MIT](LICENSE) - -[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master -[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master -[node-version-image]: https://badgen.net/npm/node/cookie -[node-version-url]: https://nodejs.org/en/download -[npm-downloads-image]: https://badgen.net/npm/dm/cookie -[npm-url]: https://npmjs.org/package/cookie -[npm-version-image]: https://badgen.net/npm/v/cookie -[travis-image]: https://badgen.net/travis/jshttp/cookie/master -[travis-url]: https://travis-ci.org/jshttp/cookie diff --git a/node_modules/cookie/index.js b/node_modules/cookie/index.js deleted file mode 100644 index 16f56c0..0000000 --- a/node_modules/cookie/index.js +++ /dev/null @@ -1,198 +0,0 @@ -/*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module exports. - * @public - */ - -exports.parse = parse; -exports.serialize = serialize; - -/** - * Module variables. - * @private - */ - -var decode = decodeURIComponent; -var encode = encodeURIComponent; -var pairSplitRegExp = /; */; - -/** - * RegExp to match field-content in RFC 7230 sec 3.2 - * - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - * obs-text = %x80-FF - */ - -var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; - -/** - * Parse a cookie header. - * - * Parse the given cookie header string into an object - * The object has the various cookies as keys(names) => values - * - * @param {string} str - * @param {object} [options] - * @return {object} - * @public - */ - -function parse(str, options) { - if (typeof str !== 'string') { - throw new TypeError('argument str must be a string'); - } - - var obj = {} - var opt = options || {}; - var pairs = str.split(pairSplitRegExp); - var dec = opt.decode || decode; - - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var eq_idx = pair.indexOf('='); - - // skip things that don't look like key=value - if (eq_idx < 0) { - continue; - } - - var key = pair.substr(0, eq_idx).trim() - var val = pair.substr(++eq_idx, pair.length).trim(); - - // quoted values - if ('"' == val[0]) { - val = val.slice(1, -1); - } - - // only assign once - if (undefined == obj[key]) { - obj[key] = tryDecode(val, dec); - } - } - - return obj; -} - -/** - * Serialize data into a cookie header. - * - * Serialize the a name value pair into a cookie string suitable for - * http headers. An optional options object specified cookie parameters. - * - * serialize('foo', 'bar', { httpOnly: true }) - * => "foo=bar; httpOnly" - * - * @param {string} name - * @param {string} val - * @param {object} [options] - * @return {string} - * @public - */ - -function serialize(name, val, options) { - var opt = options || {}; - var enc = opt.encode || encode; - - if (typeof enc !== 'function') { - throw new TypeError('option encode is invalid'); - } - - if (!fieldContentRegExp.test(name)) { - throw new TypeError('argument name is invalid'); - } - - var value = enc(val); - - if (value && !fieldContentRegExp.test(value)) { - throw new TypeError('argument val is invalid'); - } - - var str = name + '=' + value; - - if (null != opt.maxAge) { - var maxAge = opt.maxAge - 0; - if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); - str += '; Max-Age=' + Math.floor(maxAge); - } - - if (opt.domain) { - if (!fieldContentRegExp.test(opt.domain)) { - throw new TypeError('option domain is invalid'); - } - - str += '; Domain=' + opt.domain; - } - - if (opt.path) { - if (!fieldContentRegExp.test(opt.path)) { - throw new TypeError('option path is invalid'); - } - - str += '; Path=' + opt.path; - } - - if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { - throw new TypeError('option expires is invalid'); - } - - str += '; Expires=' + opt.expires.toUTCString(); - } - - if (opt.httpOnly) { - str += '; HttpOnly'; - } - - if (opt.secure) { - str += '; Secure'; - } - - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === 'string' - ? opt.sameSite.toLowerCase() : opt.sameSite; - - switch (sameSite) { - case true: - str += '; SameSite=Strict'; - break; - case 'lax': - str += '; SameSite=Lax'; - break; - case 'strict': - str += '; SameSite=Strict'; - break; - case 'none': - str += '; SameSite=None'; - break; - default: - throw new TypeError('option sameSite is invalid'); - } - } - - return str; -} - -/** - * Try decoding a string using a decoding function. - * - * @param {string} str - * @param {function} decode - * @private - */ - -function tryDecode(str, decode) { - try { - return decode(str); - } catch (e) { - return str; - } -} diff --git a/node_modules/cookie/package.json b/node_modules/cookie/package.json deleted file mode 100644 index 8f5fc8e..0000000 --- a/node_modules/cookie/package.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "_from": "cookie@0.4.0", - "_id": "cookie@0.4.0", - "_inBundle": false, - "_integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==", - "_location": "/cookie", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "cookie@0.4.0", - "name": "cookie", - "escapedName": "cookie", - "rawSpec": "0.4.0", - "saveSpec": null, - "fetchSpec": "0.4.0" - }, - "_requiredBy": [ - "/express" - ], - "_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", - "_shasum": "beb437e7022b3b6d49019d088665303ebe9c14ba", - "_spec": "cookie@0.4.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "author": { - "name": "Roman Shtylman", - "email": "shtylman@gmail.com" - }, - "bugs": { - "url": "https://github.com/jshttp/cookie/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - } - ], - "deprecated": false, - "description": "HTTP server cookie parsing and serialization", - "devDependencies": { - "beautify-benchmark": "0.2.4", - "benchmark": "2.1.4", - "eslint": "5.16.0", - "eslint-plugin-markdown": "1.0.0", - "istanbul": "0.4.5", - "mocha": "6.1.4" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "HISTORY.md", - "LICENSE", - "README.md", - "index.js" - ], - "homepage": "https://github.com/jshttp/cookie#readme", - "keywords": [ - "cookie", - "cookies" - ], - "license": "MIT", - "name": "cookie", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/cookie.git" - }, - "scripts": { - "bench": "node benchmark/index.js", - "lint": "eslint --plugin markdown --ext js,md .", - "test": "mocha --reporter spec --bail --check-leaks test/", - "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", - "version": "node scripts/version-history.js && git add HISTORY.md" - }, - "version": "0.4.0" -} diff --git a/node_modules/core-util-is/LICENSE b/node_modules/core-util-is/LICENSE deleted file mode 100644 index d8d7f94..0000000 --- a/node_modules/core-util-is/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 5a76b41..0000000 --- a/node_modules/core-util-is/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# core-util-is - -The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/core-util-is/float.patch b/node_modules/core-util-is/float.patch deleted file mode 100644 index a06d5c0..0000000 --- a/node_modules/core-util-is/float.patch +++ /dev/null @@ -1,604 +0,0 @@ -diff --git a/lib/util.js b/lib/util.js -index a03e874..9074e8e 100644 ---- a/lib/util.js -+++ b/lib/util.js -@@ -19,430 +19,6 @@ - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - --var formatRegExp = /%[sdj%]/g; --exports.format = function(f) { -- if (!isString(f)) { -- var objects = []; -- for (var i = 0; i < arguments.length; i++) { -- objects.push(inspect(arguments[i])); -- } -- return objects.join(' '); -- } -- -- var i = 1; -- var args = arguments; -- var len = args.length; -- var str = String(f).replace(formatRegExp, function(x) { -- if (x === '%%') return '%'; -- if (i >= len) return x; -- switch (x) { -- case '%s': return String(args[i++]); -- case '%d': return Number(args[i++]); -- case '%j': -- try { -- return JSON.stringify(args[i++]); -- } catch (_) { -- return '[Circular]'; -- } -- default: -- return x; -- } -- }); -- for (var x = args[i]; i < len; x = args[++i]) { -- if (isNull(x) || !isObject(x)) { -- str += ' ' + x; -- } else { -- str += ' ' + inspect(x); -- } -- } -- return str; --}; -- -- --// Mark that a method should not be used. --// Returns a modified function which warns once by default. --// If --no-deprecation is set, then it is a no-op. --exports.deprecate = function(fn, msg) { -- // Allow for deprecating things in the process of starting up. -- if (isUndefined(global.process)) { -- return function() { -- return exports.deprecate(fn, msg).apply(this, arguments); -- }; -- } -- -- if (process.noDeprecation === true) { -- return fn; -- } -- -- var warned = false; -- function deprecated() { -- if (!warned) { -- if (process.throwDeprecation) { -- throw new Error(msg); -- } else if (process.traceDeprecation) { -- console.trace(msg); -- } else { -- console.error(msg); -- } -- warned = true; -- } -- return fn.apply(this, arguments); -- } -- -- return deprecated; --}; -- -- --var debugs = {}; --var debugEnviron; --exports.debuglog = function(set) { -- if (isUndefined(debugEnviron)) -- debugEnviron = process.env.NODE_DEBUG || ''; -- set = set.toUpperCase(); -- if (!debugs[set]) { -- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { -- var pid = process.pid; -- debugs[set] = function() { -- var msg = exports.format.apply(exports, arguments); -- console.error('%s %d: %s', set, pid, msg); -- }; -- } else { -- debugs[set] = function() {}; -- } -- } -- return debugs[set]; --}; -- -- --/** -- * Echos the value of a value. Trys to print the value out -- * in the best way possible given the different types. -- * -- * @param {Object} obj The object to print out. -- * @param {Object} opts Optional options object that alters the output. -- */ --/* legacy: obj, showHidden, depth, colors*/ --function inspect(obj, opts) { -- // default options -- var ctx = { -- seen: [], -- stylize: stylizeNoColor -- }; -- // legacy... -- if (arguments.length >= 3) ctx.depth = arguments[2]; -- if (arguments.length >= 4) ctx.colors = arguments[3]; -- if (isBoolean(opts)) { -- // legacy... -- ctx.showHidden = opts; -- } else if (opts) { -- // got an "options" object -- exports._extend(ctx, opts); -- } -- // set default options -- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; -- if (isUndefined(ctx.depth)) ctx.depth = 2; -- if (isUndefined(ctx.colors)) ctx.colors = false; -- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; -- if (ctx.colors) ctx.stylize = stylizeWithColor; -- return formatValue(ctx, obj, ctx.depth); --} --exports.inspect = inspect; -- -- --// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics --inspect.colors = { -- 'bold' : [1, 22], -- 'italic' : [3, 23], -- 'underline' : [4, 24], -- 'inverse' : [7, 27], -- 'white' : [37, 39], -- 'grey' : [90, 39], -- 'black' : [30, 39], -- 'blue' : [34, 39], -- 'cyan' : [36, 39], -- 'green' : [32, 39], -- 'magenta' : [35, 39], -- 'red' : [31, 39], -- 'yellow' : [33, 39] --}; -- --// Don't use 'blue' not visible on cmd.exe --inspect.styles = { -- 'special': 'cyan', -- 'number': 'yellow', -- 'boolean': 'yellow', -- 'undefined': 'grey', -- 'null': 'bold', -- 'string': 'green', -- 'date': 'magenta', -- // "name": intentionally not styling -- 'regexp': 'red' --}; -- -- --function stylizeWithColor(str, styleType) { -- var style = inspect.styles[styleType]; -- -- if (style) { -- return '\u001b[' + inspect.colors[style][0] + 'm' + str + -- '\u001b[' + inspect.colors[style][1] + 'm'; -- } else { -- return str; -- } --} -- -- --function stylizeNoColor(str, styleType) { -- return str; --} -- -- --function arrayToHash(array) { -- var hash = {}; -- -- array.forEach(function(val, idx) { -- hash[val] = true; -- }); -- -- return hash; --} -- -- --function formatValue(ctx, value, recurseTimes) { -- // Provide a hook for user-specified inspect functions. -- // Check that value is an object with an inspect function on it -- if (ctx.customInspect && -- value && -- isFunction(value.inspect) && -- // Filter out the util module, it's inspect function is special -- value.inspect !== exports.inspect && -- // Also filter out any prototype objects using the circular check. -- !(value.constructor && value.constructor.prototype === value)) { -- var ret = value.inspect(recurseTimes, ctx); -- if (!isString(ret)) { -- ret = formatValue(ctx, ret, recurseTimes); -- } -- return ret; -- } -- -- // Primitive types cannot have properties -- var primitive = formatPrimitive(ctx, value); -- if (primitive) { -- return primitive; -- } -- -- // Look up the keys of the object. -- var keys = Object.keys(value); -- var visibleKeys = arrayToHash(keys); -- -- if (ctx.showHidden) { -- keys = Object.getOwnPropertyNames(value); -- } -- -- // Some type of object without properties can be shortcutted. -- if (keys.length === 0) { -- if (isFunction(value)) { -- var name = value.name ? ': ' + value.name : ''; -- return ctx.stylize('[Function' + name + ']', 'special'); -- } -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } -- if (isDate(value)) { -- return ctx.stylize(Date.prototype.toString.call(value), 'date'); -- } -- if (isError(value)) { -- return formatError(value); -- } -- } -- -- var base = '', array = false, braces = ['{', '}']; -- -- // Make Array say that they are Array -- if (isArray(value)) { -- array = true; -- braces = ['[', ']']; -- } -- -- // Make functions say that they are functions -- if (isFunction(value)) { -- var n = value.name ? ': ' + value.name : ''; -- base = ' [Function' + n + ']'; -- } -- -- // Make RegExps say that they are RegExps -- if (isRegExp(value)) { -- base = ' ' + RegExp.prototype.toString.call(value); -- } -- -- // Make dates with properties first say the date -- if (isDate(value)) { -- base = ' ' + Date.prototype.toUTCString.call(value); -- } -- -- // Make error with message first say the error -- if (isError(value)) { -- base = ' ' + formatError(value); -- } -- -- if (keys.length === 0 && (!array || value.length == 0)) { -- return braces[0] + base + braces[1]; -- } -- -- if (recurseTimes < 0) { -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } else { -- return ctx.stylize('[Object]', 'special'); -- } -- } -- -- ctx.seen.push(value); -- -- var output; -- if (array) { -- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); -- } else { -- output = keys.map(function(key) { -- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); -- }); -- } -- -- ctx.seen.pop(); -- -- return reduceToSingleString(output, base, braces); --} -- -- --function formatPrimitive(ctx, value) { -- if (isUndefined(value)) -- return ctx.stylize('undefined', 'undefined'); -- if (isString(value)) { -- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') -- .replace(/'/g, "\\'") -- .replace(/\\"/g, '"') + '\''; -- return ctx.stylize(simple, 'string'); -- } -- if (isNumber(value)) { -- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, -- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . -- if (value === 0 && 1 / value < 0) -- return ctx.stylize('-0', 'number'); -- return ctx.stylize('' + value, 'number'); -- } -- if (isBoolean(value)) -- return ctx.stylize('' + value, 'boolean'); -- // For some reason typeof null is "object", so special case here. -- if (isNull(value)) -- return ctx.stylize('null', 'null'); --} -- -- --function formatError(value) { -- return '[' + Error.prototype.toString.call(value) + ']'; --} -- -- --function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { -- var output = []; -- for (var i = 0, l = value.length; i < l; ++i) { -- if (hasOwnProperty(value, String(i))) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- String(i), true)); -- } else { -- output.push(''); -- } -- } -- keys.forEach(function(key) { -- if (!key.match(/^\d+$/)) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- key, true)); -- } -- }); -- return output; --} -- -- --function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { -- var name, str, desc; -- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; -- if (desc.get) { -- if (desc.set) { -- str = ctx.stylize('[Getter/Setter]', 'special'); -- } else { -- str = ctx.stylize('[Getter]', 'special'); -- } -- } else { -- if (desc.set) { -- str = ctx.stylize('[Setter]', 'special'); -- } -- } -- if (!hasOwnProperty(visibleKeys, key)) { -- name = '[' + key + ']'; -- } -- if (!str) { -- if (ctx.seen.indexOf(desc.value) < 0) { -- if (isNull(recurseTimes)) { -- str = formatValue(ctx, desc.value, null); -- } else { -- str = formatValue(ctx, desc.value, recurseTimes - 1); -- } -- if (str.indexOf('\n') > -1) { -- if (array) { -- str = str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n').substr(2); -- } else { -- str = '\n' + str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n'); -- } -- } -- } else { -- str = ctx.stylize('[Circular]', 'special'); -- } -- } -- if (isUndefined(name)) { -- if (array && key.match(/^\d+$/)) { -- return str; -- } -- name = JSON.stringify('' + key); -- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { -- name = name.substr(1, name.length - 2); -- name = ctx.stylize(name, 'name'); -- } else { -- name = name.replace(/'/g, "\\'") -- .replace(/\\"/g, '"') -- .replace(/(^"|"$)/g, "'"); -- name = ctx.stylize(name, 'string'); -- } -- } -- -- return name + ': ' + str; --} -- -- --function reduceToSingleString(output, base, braces) { -- var numLinesEst = 0; -- var length = output.reduce(function(prev, cur) { -- numLinesEst++; -- if (cur.indexOf('\n') >= 0) numLinesEst++; -- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; -- }, 0); -- -- if (length > 60) { -- return braces[0] + -- (base === '' ? '' : base + '\n ') + -- ' ' + -- output.join(',\n ') + -- ' ' + -- braces[1]; -- } -- -- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; --} -- -- - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { -@@ -522,166 +98,10 @@ function isPrimitive(arg) { - exports.isPrimitive = isPrimitive; - - function isBuffer(arg) { -- return arg instanceof Buffer; -+ return Buffer.isBuffer(arg); - } - exports.isBuffer = isBuffer; - - function objectToString(o) { - return Object.prototype.toString.call(o); --} -- -- --function pad(n) { -- return n < 10 ? '0' + n.toString(10) : n.toString(10); --} -- -- --var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', -- 'Oct', 'Nov', 'Dec']; -- --// 26 Feb 16:19:34 --function timestamp() { -- var d = new Date(); -- var time = [pad(d.getHours()), -- pad(d.getMinutes()), -- pad(d.getSeconds())].join(':'); -- return [d.getDate(), months[d.getMonth()], time].join(' '); --} -- -- --// log is just a thin wrapper to console.log that prepends a timestamp --exports.log = function() { -- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); --}; -- -- --/** -- * Inherit the prototype methods from one constructor into another. -- * -- * The Function.prototype.inherits from lang.js rewritten as a standalone -- * function (not on Function.prototype). NOTE: If this file is to be loaded -- * during bootstrapping this function needs to be rewritten using some native -- * functions as prototype setup using normal JavaScript does not work as -- * expected during bootstrapping (see mirror.js in r114903). -- * -- * @param {function} ctor Constructor function which needs to inherit the -- * prototype. -- * @param {function} superCtor Constructor function to inherit prototype from. -- */ --exports.inherits = function(ctor, superCtor) { -- ctor.super_ = superCtor; -- ctor.prototype = Object.create(superCtor.prototype, { -- constructor: { -- value: ctor, -- enumerable: false, -- writable: true, -- configurable: true -- } -- }); --}; -- --exports._extend = function(origin, add) { -- // Don't do anything if add isn't an object -- if (!add || !isObject(add)) return origin; -- -- var keys = Object.keys(add); -- var i = keys.length; -- while (i--) { -- origin[keys[i]] = add[keys[i]]; -- } -- return origin; --}; -- --function hasOwnProperty(obj, prop) { -- return Object.prototype.hasOwnProperty.call(obj, prop); --} -- -- --// Deprecated old stuff. -- --exports.p = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- console.error(exports.inspect(arguments[i])); -- } --}, 'util.p: Use console.error() instead'); -- -- --exports.exec = exports.deprecate(function() { -- return require('child_process').exec.apply(this, arguments); --}, 'util.exec is now called `child_process.exec`.'); -- -- --exports.print = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(String(arguments[i])); -- } --}, 'util.print: Use console.log instead'); -- -- --exports.puts = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(arguments[i] + '\n'); -- } --}, 'util.puts: Use console.log instead'); -- -- --exports.debug = exports.deprecate(function(x) { -- process.stderr.write('DEBUG: ' + x + '\n'); --}, 'util.debug: Use console.error instead'); -- -- --exports.error = exports.deprecate(function(x) { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stderr.write(arguments[i] + '\n'); -- } --}, 'util.error: Use console.error instead'); -- -- --exports.pump = exports.deprecate(function(readStream, writeStream, callback) { -- var callbackCalled = false; -- -- function call(a, b, c) { -- if (callback && !callbackCalled) { -- callback(a, b, c); -- callbackCalled = true; -- } -- } -- -- readStream.addListener('data', function(chunk) { -- if (writeStream.write(chunk) === false) readStream.pause(); -- }); -- -- writeStream.addListener('drain', function() { -- readStream.resume(); -- }); -- -- readStream.addListener('end', function() { -- writeStream.end(); -- }); -- -- readStream.addListener('close', function() { -- call(); -- }); -- -- readStream.addListener('error', function(err) { -- writeStream.end(); -- call(err); -- }); -- -- writeStream.addListener('error', function(err) { -- readStream.destroy(); -- call(err); -- }); --}, 'util.pump(): Use readableStream.pipe() instead'); -- -- --var uv; --exports._errnoException = function(err, syscall) { -- if (isUndefined(uv)) uv = process.binding('uv'); -- var errname = uv.errname(err); -- var e = new Error(syscall + ' ' + errname); -- e.code = errname; -- e.errno = errname; -- e.syscall = syscall; -- return e; --}; -+} \ No newline at end of file diff --git a/node_modules/core-util-is/lib/util.js b/node_modules/core-util-is/lib/util.js deleted file mode 100644 index ff4c851..0000000 --- a/node_modules/core-util-is/lib/util.js +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. - -function isArray(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 = 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 deleted file mode 100644 index 8f96abc..0000000 --- a/node_modules/core-util-is/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "_from": "core-util-is@~1.0.0", - "_id": "core-util-is@1.0.2", - "_inBundle": false, - "_integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", - "_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.2.tgz", - "_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", - "_spec": "core-util-is@~1.0.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/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": "^2.3.0" - }, - "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": { - "test": "tap test.js" - }, - "version": "1.0.2" -} diff --git a/node_modules/core-util-is/test.js b/node_modules/core-util-is/test.js deleted file mode 100644 index 1a490c6..0000000 --- a/node_modules/core-util-is/test.js +++ /dev/null @@ -1,68 +0,0 @@ -var assert = require('tap'); - -var t = require('./lib/util'); - -assert.equal(t.isArray([]), true); -assert.equal(t.isArray({}), false); - -assert.equal(t.isBoolean(null), false); -assert.equal(t.isBoolean(true), true); -assert.equal(t.isBoolean(false), true); - -assert.equal(t.isNull(null), true); -assert.equal(t.isNull(undefined), false); -assert.equal(t.isNull(false), false); -assert.equal(t.isNull(), false); - -assert.equal(t.isNullOrUndefined(null), true); -assert.equal(t.isNullOrUndefined(undefined), true); -assert.equal(t.isNullOrUndefined(false), false); -assert.equal(t.isNullOrUndefined(), true); - -assert.equal(t.isNumber(null), false); -assert.equal(t.isNumber('1'), false); -assert.equal(t.isNumber(1), true); - -assert.equal(t.isString(null), false); -assert.equal(t.isString('1'), true); -assert.equal(t.isString(1), false); - -assert.equal(t.isSymbol(null), false); -assert.equal(t.isSymbol('1'), false); -assert.equal(t.isSymbol(1), false); -assert.equal(t.isSymbol(Symbol()), true); - -assert.equal(t.isUndefined(null), false); -assert.equal(t.isUndefined(undefined), true); -assert.equal(t.isUndefined(false), false); -assert.equal(t.isUndefined(), true); - -assert.equal(t.isRegExp(null), false); -assert.equal(t.isRegExp('1'), false); -assert.equal(t.isRegExp(new RegExp()), true); - -assert.equal(t.isObject({}), true); -assert.equal(t.isObject([]), true); -assert.equal(t.isObject(new RegExp()), true); -assert.equal(t.isObject(new Date()), true); - -assert.equal(t.isDate(null), false); -assert.equal(t.isDate('1'), false); -assert.equal(t.isDate(new Date()), true); - -assert.equal(t.isError(null), false); -assert.equal(t.isError({ err: true }), false); -assert.equal(t.isError(new Error()), true); - -assert.equal(t.isFunction(null), false); -assert.equal(t.isFunction({ }), false); -assert.equal(t.isFunction(function() {}), true); - -assert.equal(t.isPrimitive(null), true); -assert.equal(t.isPrimitive(''), true); -assert.equal(t.isPrimitive(0), true); -assert.equal(t.isPrimitive(new Date()), false); - -assert.equal(t.isBuffer(null), false); -assert.equal(t.isBuffer({}), false); -assert.equal(t.isBuffer(new Buffer(0)), true); diff --git a/node_modules/debug/.coveralls.yml b/node_modules/debug/.coveralls.yml deleted file mode 100644 index 20a7068..0000000 --- a/node_modules/debug/.coveralls.yml +++ /dev/null @@ -1 +0,0 @@ -repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/debug/.eslintrc b/node_modules/debug/.eslintrc deleted file mode 100644 index 146371e..0000000 --- a/node_modules/debug/.eslintrc +++ /dev/null @@ -1,14 +0,0 @@ -{ - "env": { - "browser": true, - "node": true - }, - "globals": { - "chrome": 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 deleted file mode 100644 index 5f60eec..0000000 --- a/node_modules/debug/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index a764300..0000000 --- a/node_modules/debug/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -sudo: false - -language: node_js - -node_js: - - "4" - - "6" - - "8" - -install: - - make install - -script: - - make lint - - make test - -matrix: - include: - - node_js: '8' - env: BROWSER=1 diff --git a/node_modules/debug/CHANGELOG.md b/node_modules/debug/CHANGELOG.md deleted file mode 100644 index 820d21e..0000000 --- a/node_modules/debug/CHANGELOG.md +++ /dev/null @@ -1,395 +0,0 @@ - -3.1.0 / 2017-09-26 -================== - - * Add `DEBUG_HIDE_DATE` env var (#486) - * Remove ReDoS regexp in %o formatter (#504) - * Remove "component" from package.json - * Remove `component.json` - * Ignore package-lock.json - * Examples: fix colors printout - * Fix: browser detection - * Fix: spelling mistake (#496, @EdwardBetts) - -3.0.1 / 2017-08-24 -================== - - * Fix: Disable colors in Edge and Internet Explorer (#489) - -3.0.0 / 2017-08-08 -================== - - * Breaking: Remove DEBUG_FD (#406) - * Breaking: Use `Date#toISOString()` instead to `Date#toUTCString()` when output is not a TTY (#418) - * Breaking: Make millisecond timer namespace specific and allow 'always enabled' output (#408) - * Addition: document `enabled` flag (#465) - * Addition: add 256 colors mode (#481) - * Addition: `enabled()` updates existing debug instances, add `destroy()` function (#440) - * Update: component: update "ms" to v2.0.0 - * Update: separate the Node and Browser tests in Travis-CI - * Update: refactor Readme, fixed documentation, added "Namespace Colors" section, redid screenshots - * Update: separate Node.js and web browser examples for organization - * Update: update "browserify" to v14.4.0 - * Fix: fix Readme typo (#473) - -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 occur 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 deleted file mode 100644 index 658c933..0000000 --- a/node_modules/debug/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -(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 deleted file mode 100644 index 3ddd136..0000000 --- a/node_modules/debug/Makefile +++ /dev/null @@ -1,58 +0,0 @@ -# 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 - -install: node_modules - -browser: dist/debug.js - -node_modules: package.json - @NODE_ENV= $(PKG) install - @touch node_modules - -dist/debug.js: src/*.js node_modules - @mkdir -p dist - @$(BROWSERIFY) \ - --standalone debug \ - . > dist/debug.js - -lint: - @eslint *.js src/*.js - -test-node: - @istanbul cover node_modules/mocha/bin/_mocha -- test/**.js - @cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js - -test-browser: - @$(MAKE) browser - @karma start --single-run - -test-all: - @concurrently \ - "make test-node" \ - "make test-browser" - -test: - @if [ "x$(BROWSER)" = "x" ]; then \ - $(MAKE) test-node; \ - else \ - $(MAKE) test-browser; \ - fi - -clean: - rimraf dist coverage - -.PHONY: browser install clean lint test test-all test-node test-browser diff --git a/node_modules/debug/README.md b/node_modules/debug/README.md deleted file mode 100644 index 8e754d1..0000000 --- a/node_modules/debug/README.md +++ /dev/null @@ -1,368 +0,0 @@ -# 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 JavaScript debugging utility modelled after Node.js core's debugging -technique. Works in Node.js and web browsers. - -## 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_](./examples/node/app.js): - -```js -var debug = require('debug')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %o', 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_](./examples/node/worker.js): - -```js -var a = require('debug')('worker:a') - , b = require('debug')('worker:b'); - -function work() { - a('doing lots of uninteresting work'); - setTimeout(work, Math.random() * 1000); -} - -work(); - -function workb() { - b('doing some work'); - setTimeout(workb, Math.random() * 2000); -} - -workb(); -``` - -The `DEBUG` environment variable is then used to enable these based on space or -comma-delimited names. - -Here are some examples: - -screen shot 2017-08-08 at 12 53 04 pm -screen shot 2017-08-08 at 12 53 38 pm -screen shot 2017-08-08 at 12 53 25 pm - -#### 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. - - -## Namespace Colors - -Every debug instance has a color generated for it based on its namespace name. -This helps when visually parsing the debug output to identify which debug instance -a debug line belongs to. - -#### Node.js - -In Node.js, colors are enabled when stderr is a TTY. You also _should_ install -the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, -otherwise debug will only use a small handful of basic colors. - - - -#### Web Browser - -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). - - - - -## 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. - - - -When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: - - - - -## Conventions - -If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. - -## 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_HIDE_DATE` | Hide date from debug output (non-TTY). | -| `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); -``` - - -## Output streams - - By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: - -Example [_stdout.js_](./examples/node/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'); -``` - -## Checking whether a debug target is enabled - -After you've created a debug instance, you can determine whether or not it is -enabled by checking the `enabled` property: - -```javascript -const debug = require('debug')('http'); - -if (debug.enabled) { - // do stuff... -} -``` - -You can also manually toggle this property to force the debug instance to be -enabled or disabled. - - -## 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-2017 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/karma.conf.js b/node_modules/debug/karma.conf.js deleted file mode 100644 index 103a82d..0000000 --- a/node_modules/debug/karma.conf.js +++ /dev/null @@ -1,70 +0,0 @@ -// 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 deleted file mode 100644 index 7fc36fe..0000000 --- a/node_modules/debug/node.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./src/node'); diff --git a/node_modules/debug/node_modules/ms/index.js b/node_modules/debug/node_modules/ms/index.js deleted file mode 100644 index 6a522b1..0000000 --- a/node_modules/debug/node_modules/ms/index.js +++ /dev/null @@ -1,152 +0,0 @@ -/** - * 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/debug/node_modules/ms/license.md b/node_modules/debug/node_modules/ms/license.md deleted file mode 100644 index 69b6125..0000000 --- a/node_modules/debug/node_modules/ms/license.md +++ /dev/null @@ -1,21 +0,0 @@ -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/debug/node_modules/ms/package.json b/node_modules/debug/node_modules/ms/package.json deleted file mode 100644 index d0f425f..0000000 --- a/node_modules/debug/node_modules/ms/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "ms@2.0.0", - "_id": "ms@2.0.0", - "_inBundle": false, - "_integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "_location": "/debug/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": "/Users/kai/Desktop/node-course/dbproject/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/debug/node_modules/ms/readme.md b/node_modules/debug/node_modules/ms/readme.md deleted file mode 100644 index 84a9974..0000000 --- a/node_modules/debug/node_modules/ms/readme.md +++ /dev/null @@ -1,51 +0,0 @@ -# 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/debug/package.json b/node_modules/debug/package.json deleted file mode 100644 index 4e1401b..0000000 --- a/node_modules/debug/package.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "_from": "debug@3.1.0", - "_id": "debug@3.1.0", - "_inBundle": false, - "_integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", - "_location": "/debug", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "debug@3.1.0", - "name": "debug", - "escapedName": "debug", - "rawSpec": "3.1.0", - "saveSpec": null, - "fetchSpec": "3.1.0" - }, - "_requiredBy": [ - "/mquery" - ], - "_resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "_shasum": "5bb5a0672628b64149566ba16819e61518c67261", - "_spec": "debug@3.1.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mquery", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "browser": "./src/browser.js", - "bugs": { - "url": "https://github.com/visionmedia/debug/issues" - }, - "bundleDependencies": false, - "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": "14.4.0", - "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": "3.1.0" -} diff --git a/node_modules/debug/src/browser.js b/node_modules/debug/src/browser.js deleted file mode 100644 index f5149ff..0000000 --- a/node_modules/debug/src/browser.js +++ /dev/null @@ -1,195 +0,0 @@ -/** - * 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 = [ - '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', - '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', - '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', - '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', - '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', - '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', - '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', - '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', - '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', - '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', - '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' -]; - -/** - * 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; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // 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 deleted file mode 100644 index 77e6384..0000000 --- a/node_modules/debug/src/debug.js +++ /dev/null @@ -1,225 +0,0 @@ - -/** - * 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'); - -/** - * Active `debug` instances. - */ -exports.instances = []; - -/** - * 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 = {}; - -/** - * 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) { - - var prevTime; - - 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); - debug.destroy = destroy; - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } - - exports.instances.push(debug); - - return debug; -} - -function destroy () { - var index = exports.instances.indexOf(this); - if (index !== -1) { - exports.instances.splice(index, 1); - return true; - } else { - return false; - } -} - -/** - * 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 i; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; - - for (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 + '$')); - } - } - - for (i = 0; i < exports.instances.length; i++) { - var instance = exports.instances[i]; - instance.enabled = exports.enabled(instance.namespace); - } -} - -/** - * 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) { - if (name[name.length - 1] === '*') { - return true; - } - 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 deleted file mode 100644 index cabcbcd..0000000 --- a/node_modules/debug/src/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/** - * 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/node.js b/node_modules/debug/src/node.js deleted file mode 100644 index d666fb9..0000000 --- a/node_modules/debug/src/node.js +++ /dev/null @@ -1,186 +0,0 @@ -/** - * 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 ]; - -try { - var supportsColor = require('supports-color'); - if (supportsColor && supportsColor.level >= 2) { - exports.colors = [ - 20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63, 68, - 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128, 129, 134, - 135, 148, 149, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, - 172, 173, 178, 179, 184, 185, 196, 197, 198, 199, 200, 201, 202, 203, 204, - 205, 206, 207, 208, 209, 214, 215, 220, 221 - ]; - } -} catch (err) { - // swallow - we only care if `supports-color` is available; it doesn't have to be. -} - -/** - * 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; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(process.stderr.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 colorCode = '\u001b[3' + (c < 8 ? c : '8;5;' + c); - var prefix = ' ' + colorCode + ';1m' + name + ' ' + '\u001b[0m'; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } else { - return new Date().toISOString() + ' '; - } -} - -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ - -function log() { - return process.stderr.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; -} - -/** - * 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/decompress-response/index.d.ts b/node_modules/decompress-response/index.d.ts deleted file mode 100644 index 18918fa..0000000 --- a/node_modules/decompress-response/index.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -/// -import {IncomingMessage} from 'http'; - -declare const decompressResponse: { - /** - Decompress a HTTP response if needed. - - @param response - The HTTP incoming stream with compressed data. - @returns The decompressed HTTP response stream. - - @example - ``` - import {http} from 'http'; - import decompressResponse = require('decompress-response'); - - http.get('https://sindresorhus.com', response => { - response = decompressResponse(response); - }); - ``` - */ - (response: IncomingMessage): IncomingMessage; - - // TODO: remove this in the next major version, refactor the whole definition to: - // declare function decompressResponse(response: IncomingMessage): IncomingMessage; - // export = decompressResponse; - default: typeof decompressResponse; -}; - -export = decompressResponse; diff --git a/node_modules/decompress-response/index.js b/node_modules/decompress-response/index.js deleted file mode 100644 index 0379dc5..0000000 --- a/node_modules/decompress-response/index.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; -const {PassThrough: PassThroughStream} = require('stream'); -const zlib = require('zlib'); -const mimicResponse = require('mimic-response'); - -const decompressResponse = response => { - const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase(); - - if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) { - return response; - } - - const isBrotli = contentEncoding === 'br'; - if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') { - return response; - } - - const decompress = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip(); - const stream = new PassThroughStream(); - - mimicResponse(response, stream); - - decompress.on('error', error => { - // Ignore empty response - if (error.code === 'Z_BUF_ERROR') { - stream.end(); - return; - } - - stream.emit('error', error); - }); - - response.pipe(decompress).pipe(stream); - - return stream; -}; - -module.exports = decompressResponse; -// TODO: remove this in the next major version -module.exports.default = decompressResponse; diff --git a/node_modules/decompress-response/license b/node_modules/decompress-response/license deleted file mode 100644 index e7af2f7..0000000 --- a/node_modules/decompress-response/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/decompress-response/package.json b/node_modules/decompress-response/package.json deleted file mode 100644 index 58a700a..0000000 --- a/node_modules/decompress-response/package.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "_from": "decompress-response@^4.2.0", - "_id": "decompress-response@4.2.1", - "_inBundle": false, - "_integrity": "sha512-jOSne2qbyE+/r8G1VU+G/82LBs2Fs4LAsTiLSHOCOMZQl2OKZ6i8i4IyHemTe+/yIXOtTcRQMzPcgyhoFlqPkw==", - "_location": "/decompress-response", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "decompress-response@^4.2.0", - "name": "decompress-response", - "escapedName": "decompress-response", - "rawSpec": "^4.2.0", - "saveSpec": null, - "fetchSpec": "^4.2.0" - }, - "_requiredBy": [ - "/simple-get" - ], - "_resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-4.2.1.tgz", - "_shasum": "414023cc7a302da25ce2ec82d0d5238ccafd8986", - "_spec": "decompress-response@^4.2.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/simple-get", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "bugs": { - "url": "https://github.com/sindresorhus/decompress-response/issues" - }, - "bundleDependencies": false, - "dependencies": { - "mimic-response": "^2.0.0" - }, - "deprecated": false, - "description": "Decompress a HTTP response if needed", - "devDependencies": { - "@types/node": "^12.7.1", - "ava": "^2.2.0", - "get-stream": "^5.0.0", - "pify": "^4.0.1", - "tsd": "^0.7.1", - "xo": "^0.24.0" - }, - "engines": { - "node": ">=8" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "homepage": "https://github.com/sindresorhus/decompress-response#readme", - "keywords": [ - "decompress", - "response", - "http", - "https", - "zlib", - "gzip", - "zip", - "deflate", - "unzip", - "ungzip", - "incoming", - "message", - "stream", - "compressed", - "brotli" - ], - "license": "MIT", - "name": "decompress-response", - "repository": { - "type": "git", - "url": "git+https://github.com/sindresorhus/decompress-response.git" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "version": "4.2.1" -} diff --git a/node_modules/decompress-response/readme.md b/node_modules/decompress-response/readme.md deleted file mode 100644 index c87431a..0000000 --- a/node_modules/decompress-response/readme.md +++ /dev/null @@ -1,52 +0,0 @@ -# decompress-response [![Build Status](https://travis-ci.org/sindresorhus/decompress-response.svg?branch=master)](https://travis-ci.org/sindresorhus/decompress-response) - -> Decompress a HTTP response if needed - -Decompresses the [response](https://nodejs.org/api/http.html#http_class_http_incomingmessage) from [`http.request`](https://nodejs.org/api/http.html#http_http_request_options_callback) if it's gzipped, deflated or compressed with Brotli, otherwise just passes it through. - -Used by [`got`](https://github.com/sindresorhus/got). - - -## Install - -``` -$ npm install decompress-response -``` - - -## Usage - -```js -const http = require('http'); -const decompressResponse = require('decompress-response'); - -http.get('https://sindresorhus.com', response => { - response = decompressResponse(response); -}); -``` - - -## API - -### decompressResponse(response) - -Returns the decompressed HTTP response stream. - -#### response - -Type: [`http.IncomingMessage`](https://nodejs.org/api/http.html#http_class_http_incomingmessage) - -The HTTP incoming stream with compressed data. - - ---- - -
- - Get professional support for this package with a Tidelift subscription - -
- - Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. -
-
diff --git a/node_modules/deep-extend/CHANGELOG.md b/node_modules/deep-extend/CHANGELOG.md deleted file mode 100644 index dd13ec1..0000000 --- a/node_modules/deep-extend/CHANGELOG.md +++ /dev/null @@ -1,46 +0,0 @@ -Changelog -========= - -v0.6.0 ------- - -- Updated "devDependencies" versions to fix vulnerability alerts -- Dropped support of io.js and node.js v0.12.x and lower since new versions of - "devDependencies" couldn't work with those old node.js versions - (minimal supported version of node.js now is v4.0.0) - -v0.5.1 ------- - -- Fix prototype pollution vulnerability (thanks to @mwakerman for the PR) -- Avoid using deprecated Buffer API (thanks to @ChALkeR for the PR) - -v0.5.0 ------- - -- Auto-testing provided by Travis CI; -- Support older Node.JS versions (`v0.11.x` and `v0.10.x`); -- Removed tests files from npm package. - -v0.4.2 ------- - -- Fix for `null` as an argument. - -v0.4.1 ------- - -- Removed test code from npm package - ([see pull request #21](https://github.com/unclechu/node-deep-extend/pull/21)); -- Increased minimal version of Node from `0.4.0` to `0.12.0` - (because can't run tests on lesser version anyway). - -v0.4.0 ------- - -- **WARNING!** Broken backward compatibility with `v0.3.x`; -- Fixed bug with extending arrays instead of cloning; -- Deep cloning for arrays; -- Check for own property; -- Fixed some documentation issues; -- Strict JS mode. diff --git a/node_modules/deep-extend/LICENSE b/node_modules/deep-extend/LICENSE deleted file mode 100644 index 5c58916..0000000 --- a/node_modules/deep-extend/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013-2018, Viacheslav Lotsmanov - -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/deep-extend/README.md b/node_modules/deep-extend/README.md deleted file mode 100644 index 67c7fc0..0000000 --- a/node_modules/deep-extend/README.md +++ /dev/null @@ -1,91 +0,0 @@ -Deep Extend -=========== - -Recursive object extending. - -[![Build Status](https://api.travis-ci.org/unclechu/node-deep-extend.svg?branch=master)](https://travis-ci.org/unclechu/node-deep-extend) - -[![NPM](https://nodei.co/npm/deep-extend.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/deep-extend/) - -Install -------- - -```bash -$ npm install deep-extend -``` - -Usage ------ - -```javascript -var deepExtend = require('deep-extend'); -var obj1 = { - a: 1, - b: 2, - d: { - a: 1, - b: [], - c: { test1: 123, test2: 321 } - }, - f: 5, - g: 123, - i: 321, - j: [1, 2] -}; -var obj2 = { - b: 3, - c: 5, - d: { - b: { first: 'one', second: 'two' }, - c: { test2: 222 } - }, - e: { one: 1, two: 2 }, - f: [], - g: (void 0), - h: /abc/g, - i: null, - j: [3, 4] -}; - -deepExtend(obj1, obj2); - -console.log(obj1); -/* -{ a: 1, - b: 3, - d: - { a: 1, - b: { first: 'one', second: 'two' }, - c: { test1: 123, test2: 222 } }, - f: [], - g: undefined, - c: 5, - e: { one: 1, two: 2 }, - h: /abc/g, - i: null, - j: [3, 4] } -*/ -``` - -Unit testing ------------- - -```bash -$ npm test -``` - -Changelog ---------- - -[CHANGELOG.md](./CHANGELOG.md) - -Any issues? ------------ - -Please, report about issues -[here](https://github.com/unclechu/node-deep-extend/issues). - -License -------- - -[MIT](./LICENSE) diff --git a/node_modules/deep-extend/index.js b/node_modules/deep-extend/index.js deleted file mode 100644 index 762d81e..0000000 --- a/node_modules/deep-extend/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/deep-extend'); diff --git a/node_modules/deep-extend/lib/deep-extend.js b/node_modules/deep-extend/lib/deep-extend.js deleted file mode 100644 index 651fd8d..0000000 --- a/node_modules/deep-extend/lib/deep-extend.js +++ /dev/null @@ -1,150 +0,0 @@ -/*! - * @description Recursive object extending - * @author Viacheslav Lotsmanov - * @license MIT - * - * The MIT License (MIT) - * - * Copyright (c) 2013-2018 Viacheslav Lotsmanov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of - * this software and associated documentation files (the "Software"), to deal in - * the Software without restriction, including without limitation the rights to - * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - * the Software, and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -'use strict'; - -function isSpecificValue(val) { - return ( - val instanceof Buffer - || val instanceof Date - || val instanceof RegExp - ) ? true : false; -} - -function cloneSpecificValue(val) { - if (val instanceof Buffer) { - var x = Buffer.alloc - ? Buffer.alloc(val.length) - : new Buffer(val.length); - val.copy(x); - return x; - } else if (val instanceof Date) { - return new Date(val.getTime()); - } else if (val instanceof RegExp) { - return new RegExp(val); - } else { - throw new Error('Unexpected situation'); - } -} - -/** - * Recursive cloning array. - */ -function deepCloneArray(arr) { - var clone = []; - arr.forEach(function (item, index) { - if (typeof item === 'object' && item !== null) { - if (Array.isArray(item)) { - clone[index] = deepCloneArray(item); - } else if (isSpecificValue(item)) { - clone[index] = cloneSpecificValue(item); - } else { - clone[index] = deepExtend({}, item); - } - } else { - clone[index] = item; - } - }); - return clone; -} - -function safeGetProperty(object, property) { - return property === '__proto__' ? undefined : object[property]; -} - -/** - * Extening object that entered in first argument. - * - * Returns extended object or false if have no target object or incorrect type. - * - * If you wish to clone source object (without modify it), just use empty new - * object as first argument, like this: - * deepExtend({}, yourObj_1, [yourObj_N]); - */ -var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) { - if (arguments.length < 1 || typeof arguments[0] !== 'object') { - return false; - } - - if (arguments.length < 2) { - return arguments[0]; - } - - var target = arguments[0]; - - // convert arguments to array and cut off target object - var args = Array.prototype.slice.call(arguments, 1); - - var val, src, clone; - - args.forEach(function (obj) { - // skip argument if isn't an object, is null, or is an array - if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) { - return; - } - - Object.keys(obj).forEach(function (key) { - src = safeGetProperty(target, key); // source value - val = safeGetProperty(obj, key); // new value - - // recursion prevention - if (val === target) { - return; - - /** - * if new value isn't object then just overwrite by new value - * instead of extending. - */ - } else if (typeof val !== 'object' || val === null) { - target[key] = val; - return; - - // just clone arrays (and recursive clone objects inside) - } else if (Array.isArray(val)) { - target[key] = deepCloneArray(val); - return; - - // custom cloning and overwrite for specific objects - } else if (isSpecificValue(val)) { - target[key] = cloneSpecificValue(val); - return; - - // overwrite by new value if source isn't object or array - } else if (typeof src !== 'object' || src === null || Array.isArray(src)) { - target[key] = deepExtend({}, val); - return; - - // source value and new value is objects both, extending... - } else { - target[key] = deepExtend(src, val); - return; - } - }); - }); - - return target; -}; diff --git a/node_modules/deep-extend/package.json b/node_modules/deep-extend/package.json deleted file mode 100644 index c2de9f0..0000000 --- a/node_modules/deep-extend/package.json +++ /dev/null @@ -1,92 +0,0 @@ -{ - "_from": "deep-extend@^0.6.0", - "_id": "deep-extend@0.6.0", - "_inBundle": false, - "_integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", - "_location": "/deep-extend", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "deep-extend@^0.6.0", - "name": "deep-extend", - "escapedName": "deep-extend", - "rawSpec": "^0.6.0", - "saveSpec": null, - "fetchSpec": "^0.6.0" - }, - "_requiredBy": [ - "/rc" - ], - "_resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "_shasum": "c4fa7c95404a17a9c3e8ca7e1537312b736330ac", - "_spec": "deep-extend@^0.6.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/rc", - "author": { - "name": "Viacheslav Lotsmanov", - "email": "lotsmanov89@gmail.com" - }, - "bugs": { - "url": "https://github.com/unclechu/node-deep-extend/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Romain Prieto", - "url": "https://github.com/rprieto" - }, - { - "name": "Max Maximov", - "url": "https://github.com/maxmaximov" - }, - { - "name": "Marshall Bowers", - "url": "https://github.com/maxdeviant" - }, - { - "name": "Misha Wakerman", - "url": "https://github.com/mwakerman" - } - ], - "deprecated": false, - "description": "Recursive object extending", - "devDependencies": { - "mocha": "5.2.0", - "should": "13.2.1" - }, - "engines": { - "node": ">=4.0.0" - }, - "files": [ - "index.js", - "lib/" - ], - "homepage": "https://github.com/unclechu/node-deep-extend", - "keywords": [ - "deep-extend", - "extend", - "deep", - "recursive", - "xtend", - "clone", - "merge", - "json" - ], - "license": "MIT", - "licenses": [ - { - "type": "MIT", - "url": "https://raw.githubusercontent.com/unclechu/node-deep-extend/master/LICENSE" - } - ], - "main": "lib/deep-extend.js", - "name": "deep-extend", - "repository": { - "type": "git", - "url": "git://github.com/unclechu/node-deep-extend.git" - }, - "scripts": { - "test": "mocha" - }, - "version": "0.6.0" -} diff --git a/node_modules/define-properties/.editorconfig b/node_modules/define-properties/.editorconfig deleted file mode 100644 index eaa2141..0000000 --- a/node_modules/define-properties/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -root = true - -[*] -indent_style = tab; -insert_final_newline = true; -quote_type = auto; -space_after_anonymous_functions = true; -space_after_control_statements = true; -spaces_around_operators = true; -trim_trailing_whitespace = true; -spaces_in_brackets = false; -end_of_line = lf; - diff --git a/node_modules/define-properties/.eslintrc b/node_modules/define-properties/.eslintrc deleted file mode 100644 index db992d7..0000000 --- a/node_modules/define-properties/.eslintrc +++ /dev/null @@ -1,12 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "id-length": [2, { "min": 1, "max": 35 }], - "max-lines-per-function": [2, 100], - "max-params": [2, 4], - "max-statements": [2, 13] - } -} diff --git a/node_modules/define-properties/.jscs.json b/node_modules/define-properties/.jscs.json deleted file mode 100644 index 6f2d7f9..0000000 --- a/node_modules/define-properties/.jscs.json +++ /dev/null @@ -1,175 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 3 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": "asc-insensitive", - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/node_modules/define-properties/.travis.yml b/node_modules/define-properties/.travis.yml deleted file mode 100644 index ec72d5f..0000000 --- a/node_modules/define-properties/.travis.yml +++ /dev/null @@ -1,233 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "10.8" - - "9.11" - - "8.11" - - "7.10" - - "6.14" - - "5.12" - - "4.9" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "4" - env: COVERAGE=true - - node_js: "10.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true - - env: COVERAGE=true diff --git a/node_modules/define-properties/CHANGELOG.md b/node_modules/define-properties/CHANGELOG.md deleted file mode 100644 index 5cad1e2..0000000 --- a/node_modules/define-properties/CHANGELOG.md +++ /dev/null @@ -1,44 +0,0 @@ -1.1.3 / 2018-08-14 -================= - * [Refactor] use a for loop instead of `foreach` to make for smaller bundle sizes - * [Robustness] cache `Array.prototype.concat` and `Object.defineProperty` - * [Deps] update `object-keys` - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `nsp`, `tape`, `jscs`; remove unused eccheck script + dep - * [Tests] use pretest/posttest for linting/security - * [Tests] fix npm upgrades on older nodes - -1.1.2 / 2015-10-14 -================= - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - * [Deps] Update `object-keys` - * [Dev Deps] update `jscs`, `tape`, `eslint`, `@ljharb/eslint-config`, `nsp` - * [Tests] up to `io.js` `v3.3`, `node` `v4.2` - -1.1.1 / 2015-07-21 -================= - * [Deps] Update `object-keys` - * [Dev Deps] Update `tape`, `eslint` - * [Tests] Test on `io.js` `v2.4` - -1.1.0 / 2015-07-01 -================= - * [New] Add support for symbol-valued properties. - * [Dev Deps] Update `nsp`, `eslint` - * [Tests] Test up to `io.js` `v2.3` - -1.0.3 / 2015-05-30 -================= - * Using a more reliable check for supported property descriptors. - -1.0.2 / 2015-05-23 -================= - * Test up to `io.js` `v2.0` - * Update `tape`, `jscs`, `nsp`, `eslint`, `object-keys`, `editorconfig-tools`, `covert` - -1.0.1 / 2015-01-06 -================= - * Update `object-keys` to fix ES3 support - -1.0.0 / 2015-01-04 -================= - * v1.0.0 diff --git a/node_modules/define-properties/LICENSE b/node_modules/define-properties/LICENSE deleted file mode 100644 index 8c271c1..0000000 --- a/node_modules/define-properties/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (C) 2015 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/define-properties/README.md b/node_modules/define-properties/README.md deleted file mode 100644 index 33b6111..0000000 --- a/node_modules/define-properties/README.md +++ /dev/null @@ -1,86 +0,0 @@ -#define-properties [![Version Badge][npm-version-svg]][package-url] - -[![Build Status][travis-svg]][travis-url] -[![dependency status][deps-svg]][deps-url] -[![dev dependency status][dev-deps-svg]][dev-deps-url] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][npm-badge-png]][package-url] - -[![browser support][testling-svg]][testling-url] - -Define multiple non-enumerable properties at once. Uses `Object.defineProperty` when available; falls back to standard assignment in older engines. -Existing properties are not overridden. Accepts a map of property names to a predicate that, when true, force-overrides. - -## Example - -```js -var define = require('define-properties'); -var assert = require('assert'); - -var obj = define({ a: 1, b: 2 }, { - a: 10, - b: 20, - c: 30 -}); -assert(obj.a === 1); -assert(obj.b === 2); -assert(obj.c === 30); -if (define.supportsDescriptors) { - assert.deepEqual(Object.keys(obj), ['a', 'b']); - assert.deepEqual(Object.getOwnPropertyDescriptor(obj, 'c'), { - configurable: true, - enumerable: false, - value: 30, - writable: false - }); -} -``` - -Then, with predicates: -```js -var define = require('define-properties'); -var assert = require('assert'); - -var obj = define({ a: 1, b: 2, c: 3 }, { - a: 10, - b: 20, - c: 30 -}, { - a: function () { return false; }, - b: function () { return true; } -}); -assert(obj.a === 1); -assert(obj.b === 20); -assert(obj.c === 3); -if (define.supportsDescriptors) { - assert.deepEqual(Object.keys(obj), ['a', 'c']); - assert.deepEqual(Object.getOwnPropertyDescriptor(obj, 'b'), { - configurable: true, - enumerable: false, - value: 20, - writable: false - }); -} -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[package-url]: https://npmjs.org/package/define-properties -[npm-version-svg]: http://versionbadg.es/ljharb/define-properties.svg -[travis-svg]: https://travis-ci.org/ljharb/define-properties.svg -[travis-url]: https://travis-ci.org/ljharb/define-properties -[deps-svg]: https://david-dm.org/ljharb/define-properties.svg -[deps-url]: https://david-dm.org/ljharb/define-properties -[dev-deps-svg]: https://david-dm.org/ljharb/define-properties/dev-status.svg -[dev-deps-url]: https://david-dm.org/ljharb/define-properties#info=devDependencies -[testling-svg]: https://ci.testling.com/ljharb/define-properties.png -[testling-url]: https://ci.testling.com/ljharb/define-properties -[npm-badge-png]: https://nodei.co/npm/define-properties.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/define-properties.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/define-properties.svg -[downloads-url]: http://npm-stat.com/charts.html?package=define-properties - diff --git a/node_modules/define-properties/index.js b/node_modules/define-properties/index.js deleted file mode 100644 index cb3ae1c..0000000 --- a/node_modules/define-properties/index.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -var keys = require('object-keys'); -var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; - -var toStr = Object.prototype.toString; -var concat = Array.prototype.concat; -var origDefineProperty = Object.defineProperty; - -var isFunction = function (fn) { - return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; -}; - -var arePropertyDescriptorsSupported = function () { - var obj = {}; - try { - origDefineProperty(obj, 'x', { enumerable: false, value: obj }); - // eslint-disable-next-line no-unused-vars, no-restricted-syntax - for (var _ in obj) { // jscs:ignore disallowUnusedVariables - return false; - } - return obj.x === obj; - } catch (e) { /* this is IE 8. */ - return false; - } -}; -var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported(); - -var defineProperty = function (object, name, value, predicate) { - if (name in object && (!isFunction(predicate) || !predicate())) { - return; - } - if (supportsDescriptors) { - origDefineProperty(object, name, { - configurable: true, - enumerable: false, - value: value, - writable: true - }); - } else { - object[name] = value; - } -}; - -var defineProperties = function (object, map) { - var predicates = arguments.length > 2 ? arguments[2] : {}; - var props = keys(map); - if (hasSymbols) { - props = concat.call(props, Object.getOwnPropertySymbols(map)); - } - for (var i = 0; i < props.length; i += 1) { - defineProperty(object, props[i], map[props[i]], predicates[props[i]]); - } -}; - -defineProperties.supportsDescriptors = !!supportsDescriptors; - -module.exports = defineProperties; diff --git a/node_modules/define-properties/package.json b/node_modules/define-properties/package.json deleted file mode 100644 index 9c309c0..0000000 --- a/node_modules/define-properties/package.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "_from": "define-properties@^1.1.3", - "_id": "define-properties@1.1.3", - "_inBundle": false, - "_integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", - "_location": "/define-properties", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "define-properties@^1.1.3", - "name": "define-properties", - "escapedName": "define-properties", - "rawSpec": "^1.1.3", - "saveSpec": null, - "fetchSpec": "^1.1.3" - }, - "_requiredBy": [ - "/is-nan", - "/object-is", - "/object.assign", - "/string.prototype.trimend", - "/string.prototype.trimleft", - "/string.prototype.trimright", - "/string.prototype.trimstart" - ], - "_resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", - "_shasum": "cf88da6cbee26fe6db7094f61d870cbd84cee9f1", - "_spec": "define-properties@^1.1.3", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/is-nan", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/ljharb/define-properties/issues" - }, - "bundleDependencies": false, - "dependencies": { - "object-keys": "^1.0.12" - }, - "deprecated": false, - "description": "Define multiple non-enumerable properties at once. Uses `Object.defineProperty` when available; falls back to standard assignment in older engines.", - "devDependencies": { - "@ljharb/eslint-config": "^13.0.0", - "covert": "^1.1.0", - "eslint": "^5.3.0", - "jscs": "^3.0.7", - "nsp": "^3.2.1", - "tape": "^4.9.0" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/define-properties#readme", - "keywords": [ - "Object.defineProperty", - "Object.defineProperties", - "object", - "property descriptor", - "descriptor", - "define", - "ES5" - ], - "license": "MIT", - "main": "index.js", - "name": "define-properties", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/define-properties.git" - }, - "scripts": { - "coverage": "covert test/*.js", - "coverage-quiet": "covert test/*.js --quiet", - "eslint": "eslint test/*.js *.js", - "jscs": "jscs test/*.js *.js", - "lint": "npm run --silent jscs && npm run --silent eslint", - "posttest": "npm run --silent security", - "pretest": "npm run --silent lint", - "security": "nsp check", - "test": "npm run --silent tests-only", - "tests-only": "node test/index.js" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.1.3" -} diff --git a/node_modules/define-properties/test/index.js b/node_modules/define-properties/test/index.js deleted file mode 100644 index 3387f6b..0000000 --- a/node_modules/define-properties/test/index.js +++ /dev/null @@ -1,125 +0,0 @@ -'use strict'; - -var define = require('../'); -var test = require('tape'); -var keys = require('object-keys'); - -var arePropertyDescriptorsSupported = function () { - var obj = { a: 1 }; - try { - Object.defineProperty(obj, 'x', { value: obj }); - return obj.x === obj; - } catch (e) { /* this is IE 8. */ - return false; - } -}; -var descriptorsSupported = !!Object.defineProperty && arePropertyDescriptorsSupported(); - -var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; - -test('defineProperties', function (dt) { - dt.test('with descriptor support', { skip: !descriptorsSupported }, function (t) { - var getDescriptor = function (value) { - return { - configurable: true, - enumerable: false, - value: value, - writable: true - }; - }; - - var obj = { - a: 1, - b: 2, - c: 3 - }; - t.deepEqual(keys(obj), ['a', 'b', 'c'], 'all literal-set keys start enumerable'); - define(obj, { - b: 3, - c: 4, - d: 5 - }); - t.deepEqual(obj, { - a: 1, - b: 2, - c: 3 - }, 'existing properties were not overridden'); - t.deepEqual(Object.getOwnPropertyDescriptor(obj, 'd'), getDescriptor(5), 'new property "d" was added and is not enumerable'); - t.deepEqual(['a', 'b', 'c'], keys(obj), 'new keys are not enumerable'); - - define(obj, { - a: 2, - b: 3, - c: 4 - }, { - a: function () { return true; }, - b: function () { return false; } - }); - t.deepEqual(obj, { - b: 2, - c: 3 - }, 'properties only overriden when predicate exists and returns true'); - t.deepEqual(Object.getOwnPropertyDescriptor(obj, 'd'), getDescriptor(5), 'existing property "d" remained and is not enumerable'); - t.deepEqual(Object.getOwnPropertyDescriptor(obj, 'a'), getDescriptor(2), 'existing property "a" was overridden and is not enumerable'); - t.deepEqual(['b', 'c'], keys(obj), 'overridden keys are not enumerable'); - - t.end(); - }); - - dt.test('without descriptor support', { skip: descriptorsSupported }, function (t) { - var obj = { - a: 1, - b: 2, - c: 3 - }; - define(obj, { - b: 3, - c: 4, - d: 5 - }); - t.deepEqual(obj, { - a: 1, - b: 2, - c: 3, - d: 5 - }, 'existing properties were not overridden, new properties were added'); - - define(obj, { - a: 2, - b: 3, - c: 4 - }, { - a: function () { return true; }, - b: function () { return false; } - }); - t.deepEqual(obj, { - a: 2, - b: 2, - c: 3, - d: 5 - }, 'properties only overriden when predicate exists and returns true'); - - t.end(); - }); - - dt.end(); -}); - -test('symbols', { skip: !hasSymbols }, function (t) { - var sym = Symbol('foo'); - var obj = {}; - var aValue = {}; - var bValue = {}; - var properties = { a: aValue }; - properties[sym] = bValue; - - define(obj, properties); - - t.deepEqual(Object.keys(obj), [], 'object has no enumerable keys'); - t.deepEqual(Object.getOwnPropertyNames(obj), ['a'], 'object has non-enumerable "a" key'); - t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'object has non-enumerable symbol key'); - t.equal(obj.a, aValue, 'string keyed value is defined'); - t.equal(obj[sym], bValue, 'symbol keyed value is defined'); - - t.end(); -}); diff --git a/node_modules/delegates/.npmignore b/node_modules/delegates/.npmignore deleted file mode 100644 index c2658d7..0000000 --- a/node_modules/delegates/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules/ diff --git a/node_modules/delegates/History.md b/node_modules/delegates/History.md deleted file mode 100644 index 25959ea..0000000 --- a/node_modules/delegates/History.md +++ /dev/null @@ -1,22 +0,0 @@ - -1.0.0 / 2015-12-14 -================== - - * Merge pull request #12 from kasicka/master - * Add license text - -0.1.0 / 2014-10-17 -================== - - * adds `.fluent()` to api - -0.0.3 / 2014-01-13 -================== - - * fix receiver for .method() - -0.0.2 / 2014-01-13 -================== - - * Object.defineProperty() sucks - * Initial commit diff --git a/node_modules/delegates/License b/node_modules/delegates/License deleted file mode 100644 index 60de60a..0000000 --- a/node_modules/delegates/License +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2015 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/delegates/Makefile b/node_modules/delegates/Makefile deleted file mode 100644 index a9dcfd5..0000000 --- a/node_modules/delegates/Makefile +++ /dev/null @@ -1,8 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --require should \ - --reporter spec \ - --bail - -.PHONY: test \ No newline at end of file diff --git a/node_modules/delegates/Readme.md b/node_modules/delegates/Readme.md deleted file mode 100644 index ab8cf4a..0000000 --- a/node_modules/delegates/Readme.md +++ /dev/null @@ -1,94 +0,0 @@ - -# delegates - - Node method and accessor delegation utilty. - -## Installation - -``` -$ npm install delegates -``` - -## Example - -```js -var delegate = require('delegates'); - -... - -delegate(proto, 'request') - .method('acceptsLanguages') - .method('acceptsEncodings') - .method('acceptsCharsets') - .method('accepts') - .method('is') - .access('querystring') - .access('idempotent') - .access('socket') - .access('length') - .access('query') - .access('search') - .access('status') - .access('method') - .access('path') - .access('body') - .access('host') - .access('url') - .getter('subdomains') - .getter('protocol') - .getter('header') - .getter('stale') - .getter('fresh') - .getter('secure') - .getter('ips') - .getter('ip') -``` - -# API - -## Delegate(proto, prop) - -Creates a delegator instance used to configure using the `prop` on the given -`proto` object. (which is usually a prototype) - -## Delegate#method(name) - -Allows the given method `name` to be accessed on the host. - -## Delegate#getter(name) - -Creates a "getter" for the property with the given `name` on the delegated -object. - -## Delegate#setter(name) - -Creates a "setter" for the property with the given `name` on the delegated -object. - -## Delegate#access(name) - -Creates an "accessor" (ie: both getter *and* setter) for the property with the -given `name` on the delegated object. - -## Delegate#fluent(name) - -A unique type of "accessor" that works for a "fluent" API. When called as a -getter, the method returns the expected value. However, if the method is called -with a value, it will return itself so it can be chained. For example: - -```js -delegate(proto, 'request') - .fluent('query') - -// getter -var q = request.query(); - -// setter (chainable) -request - .query({ a: 1 }) - .query({ b: 2 }); -``` - -# License - - MIT diff --git a/node_modules/delegates/index.js b/node_modules/delegates/index.js deleted file mode 100644 index 17c222d..0000000 --- a/node_modules/delegates/index.js +++ /dev/null @@ -1,121 +0,0 @@ - -/** - * Expose `Delegator`. - */ - -module.exports = Delegator; - -/** - * Initialize a delegator. - * - * @param {Object} proto - * @param {String} target - * @api public - */ - -function Delegator(proto, target) { - if (!(this instanceof Delegator)) return new Delegator(proto, target); - this.proto = proto; - this.target = target; - this.methods = []; - this.getters = []; - this.setters = []; - this.fluents = []; -} - -/** - * Delegate method `name`. - * - * @param {String} name - * @return {Delegator} self - * @api public - */ - -Delegator.prototype.method = function(name){ - var proto = this.proto; - var target = this.target; - this.methods.push(name); - - proto[name] = function(){ - return this[target][name].apply(this[target], arguments); - }; - - return this; -}; - -/** - * Delegator accessor `name`. - * - * @param {String} name - * @return {Delegator} self - * @api public - */ - -Delegator.prototype.access = function(name){ - return this.getter(name).setter(name); -}; - -/** - * Delegator getter `name`. - * - * @param {String} name - * @return {Delegator} self - * @api public - */ - -Delegator.prototype.getter = function(name){ - var proto = this.proto; - var target = this.target; - this.getters.push(name); - - proto.__defineGetter__(name, function(){ - return this[target][name]; - }); - - return this; -}; - -/** - * Delegator setter `name`. - * - * @param {String} name - * @return {Delegator} self - * @api public - */ - -Delegator.prototype.setter = function(name){ - var proto = this.proto; - var target = this.target; - this.setters.push(name); - - proto.__defineSetter__(name, function(val){ - return this[target][name] = val; - }); - - return this; -}; - -/** - * Delegator fluent accessor - * - * @param {String} name - * @return {Delegator} self - * @api public - */ - -Delegator.prototype.fluent = function (name) { - var proto = this.proto; - var target = this.target; - this.fluents.push(name); - - proto[name] = function(val){ - if ('undefined' != typeof val) { - this[target][name] = val; - return this; - } else { - return this[target][name]; - } - }; - - return this; -}; diff --git a/node_modules/delegates/package.json b/node_modules/delegates/package.json deleted file mode 100644 index f04e3ce..0000000 --- a/node_modules/delegates/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "_from": "delegates@^1.0.0", - "_id": "delegates@1.0.0", - "_inBundle": false, - "_integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=", - "_location": "/delegates", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "delegates@^1.0.0", - "name": "delegates", - "escapedName": "delegates", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/are-we-there-yet" - ], - "_resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", - "_shasum": "84c6e159b81904fdca59a0ef44cd870d31250f9a", - "_spec": "delegates@^1.0.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/are-we-there-yet", - "bugs": { - "url": "https://github.com/visionmedia/node-delegates/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "delegate methods and accessors to another property", - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "homepage": "https://github.com/visionmedia/node-delegates#readme", - "keywords": [ - "delegate", - "delegation" - ], - "license": "MIT", - "name": "delegates", - "repository": { - "type": "git", - "url": "git+https://github.com/visionmedia/node-delegates.git" - }, - "version": "1.0.0" -} diff --git a/node_modules/delegates/test/index.js b/node_modules/delegates/test/index.js deleted file mode 100644 index 7b6e3d4..0000000 --- a/node_modules/delegates/test/index.js +++ /dev/null @@ -1,94 +0,0 @@ - -var assert = require('assert'); -var delegate = require('..'); - -describe('.method(name)', function(){ - it('should delegate methods', function(){ - var obj = {}; - - obj.request = { - foo: function(bar){ - assert(this == obj.request); - return bar; - } - }; - - delegate(obj, 'request').method('foo'); - - obj.foo('something').should.equal('something'); - }) -}) - -describe('.getter(name)', function(){ - it('should delegate getters', function(){ - var obj = {}; - - obj.request = { - get type() { - return 'text/html'; - } - } - - delegate(obj, 'request').getter('type'); - - obj.type.should.equal('text/html'); - }) -}) - -describe('.setter(name)', function(){ - it('should delegate setters', function(){ - var obj = {}; - - obj.request = { - get type() { - return this._type.toUpperCase(); - }, - - set type(val) { - this._type = val; - } - } - - delegate(obj, 'request').setter('type'); - - obj.type = 'hey'; - obj.request.type.should.equal('HEY'); - }) -}) - -describe('.access(name)', function(){ - it('should delegate getters and setters', function(){ - var obj = {}; - - obj.request = { - get type() { - return this._type.toUpperCase(); - }, - - set type(val) { - this._type = val; - } - } - - delegate(obj, 'request').access('type'); - - obj.type = 'hey'; - obj.type.should.equal('HEY'); - }) -}) - -describe('.fluent(name)', function () { - it('should delegate in a fluent fashion', function () { - var obj = { - settings: { - env: 'development' - } - }; - - delegate(obj, 'settings').fluent('env'); - - obj.env().should.equal('development'); - obj.env('production').should.equal(obj); - obj.settings.env.should.equal('production'); - }) -}) diff --git a/node_modules/denque/LICENSE b/node_modules/denque/LICENSE deleted file mode 100644 index fd22a2d..0000000 --- a/node_modules/denque/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2018 Mike Diarmid (Salakar) - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this library except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/node_modules/denque/README.md b/node_modules/denque/README.md deleted file mode 100644 index 6821e0d..0000000 --- a/node_modules/denque/README.md +++ /dev/null @@ -1,362 +0,0 @@ -

- -
-
-

Denque

-

- -

- NPM downloads - NPM version - Build version - Build version - License - Chat - Follow on Twitter -

- -Extremely fast and lightweight [double-ended queue](http://en.wikipedia.org/wiki/Double-ended_queue) implementation with zero dependencies. - -Double-ended queues can also be used as a: - -- [Stack](http://en.wikipedia.org/wiki/Stack_\(abstract_data_type\)) -- [Queue](http://en.wikipedia.org/wiki/Queue_\(data_structure\)) - -This implementation is currently the fastest available, even faster than `double-ended-queue`, see the [benchmarks](#benchmarks) - -Every queue operation is done at a constant `O(1)` - including random access from `.peekAt(index)`. - -**Works on all node versions >= v0.10** - -# Quick Start - - npm install denque - -```js -const Denque = require("denque"); - -const denque = new Denque([1,2,3,4]); -denque.shift(); // 1 -denque.pop(); // 4 -``` - - -# API - -- [`new Denque()`](#new-denque---denque) -- [`new Denque(Array items)`](#new-denquearray-items---denque) -- [`push(item)`](#pushitem---int) -- [`unshift(item)`](#unshiftitem---int) -- [`pop()`](#pop---dynamic) -- [`shift()`](#shift---dynamic) -- [`toArray()`](#toarray---array) -- [`peekBack()`](#peekback---dynamic) -- [`peekFront()`](#peekfront---dynamic) -- [`peekAt(int index)`](#peekAtint-index---dynamic) -- [`remove(int index, int count)`](#remove) -- [`removeOne(int index)`](#removeOne) -- [`splice(int index, int count, item1, item2, ...)`](#splice) -- [`isEmpty()`](#isempty---boolean) -- [`clear()`](#clear---void) - -#### `new Denque()` -> `Denque` - -Creates an empty double-ended queue with initial capacity of 4. - -```js -var denque = new Denque(); -denque.push(1); -denque.push(2); -denque.push(3); -denque.shift(); //1 -denque.pop(); //3 -``` - -
- -#### `new Denque(Array items)` -> `Denque` - -Creates a double-ended queue from `items`. - -```js -var denque = new Denque([1,2,3,4]); -denque.shift(); // 1 -denque.pop(); // 4 -``` - -
- - -#### `push(item)` -> `int` - -Push an item to the back of this queue. Returns the amount of items currently in the queue after the operation. - -```js -var denque = new Denque(); -denque.push(1); -denque.pop(); // 1 -denque.push(2); -denque.push(3); -denque.shift(); // 2 -denque.shift(); // 3 -``` - -
- -#### `unshift(item)` -> `int` - -Unshift an item to the front of this queue. Returns the amount of items currently in the queue after the operation. - -```js -var denque = new Denque([2,3]); -denque.unshift(1); -denque.toString(); // "1,2,3" -denque.unshift(-2); -denque.toString(); // "-2,-1,0,1,2,3" -``` - -
- - -#### `pop()` -> `dynamic` - -Pop off the item at the back of this queue. - -Note: The item will be removed from the queue. If you simply want to see what's at the back of the queue use [`peekBack()`](#peekback---dynamic) or [`.peekAt(-1)`](#peekAtint-index---dynamic). - -If the queue is empty, `undefined` is returned. If you need to differentiate between `undefined` values in the queue and `pop()` return value - -check the queue `.length` before popping. - -```js -var denque = new Denque([1,2,3]); -denque.pop(); // 3 -denque.pop(); // 2 -denque.pop(); // 1 -denque.pop(); // undefined -``` - -**Aliases:** `removeBack` - -
- -#### `shift()` -> `dynamic` - -Shifts off the item at the front of this queue. - -Note: The item will be removed from the queue. If you simply want to see what's at the front of the queue use [`peekFront()`](#peekfront---dynamic) or [`.peekAt(0)`](#peekAtint-index---dynamic). - -If the queue is empty, `undefined` is returned. If you need to differentiate between `undefined` values in the queue and `shift()` return value - -check the queue `.length` before shifting. - -```js -var denque = new Denque([1,2,3]); -denque.shift(); // 1 -denque.shift(); // 2 -denque.shift(); // 3 -denque.shift(); // undefined -``` - -
- -#### `toArray()` -> `Array` - -Returns the items in the queue as an array. Starting from the item in the front of the queue and ending to the item at the back of the queue. - -```js -var denque = new Denque([1,2,3]); -denque.push(4); -denque.unshift(0); -denque.toArray(); // [0,1,2,3,4] -``` - -
- -#### `peekBack()` -> `dynamic` - -Returns the item that is at the back of this queue without removing it. - -If the queue is empty, `undefined` is returned. - -```js -var denque = new Denque([1,2,3]); -denque.push(4); -denque.peekBack(); // 4 -``` - -
- -#### `peekFront()` -> `dynamic` - -Returns the item that is at the front of this queue without removing it. - -If the queue is empty, `undefined` is returned. - -```js -var denque = new Denque([1,2,3]); -denque.push(4); -denque.peekFront(); // 1 -``` - -
- -#### `peekAt(int index)` -> `dynamic` - -Returns the item that is at the given `index` of this queue without removing it. - -The index is zero-based, so `.peekAt(0)` will return the item that is at the front, `.peekAt(1)` will return -the item that comes after and so on. - -The index can be negative to read items at the back of the queue. `.peekAt(-1)` returns the item that is at the back of the queue, -`.peekAt(-2)` will return the item that comes before and so on. - -Returns `undefined` if `index` is not a valid index into the queue. - -```js -var denque = new Denque([1,2,3]); -denque.peekAt(0); //1 -denque.peekAt(1); //2 -denque.peekAt(2); //3 - -denque.peekAt(-1); // 3 -denque.peekAt(-2); // 2 -denque.peekAt(-3); // 1 -``` - -**Note**: The implementation has O(1) random access using `.peekAt()`. - -**Aliases:** `get` - -
- -#### `remove(int index, int count)` -> `array` - -Remove number of items from the specified index from the list. - -Returns array of removed items. - -Returns undefined if the list is empty. - -```js -var denque = new Denque([1,2,3,4,5,6,7]); -denque.remove(0,3); //[1,2,3] -denque.remove(1,2); //[5,6] -var denque1 = new Denque([1,2,3,4,5,6,7]); -denque1.remove(4, 100); //[5,6,7] -``` - -
- -#### `removeOne(int index)` -> `dynamic` - -Remove and return the item at the specified index from the list. - -Returns undefined if the list is empty. - -```js -var denque = new Denque([1,2,3,4,5,6,7]); -denque.removeOne(4); // 5 -denque.removeOne(3); // 4 -denque1.removeOne(1); // 2 -``` - -
- -#### `splice(int index, int count, item1, item2, ...)` -> `array` - -Native splice implementation. - -Remove number of items from the specified index from the list and/or add new elements. - -Returns array of removed items or empty array if count == 0. - -Returns undefined if the list is empty. - -```js -var denque = new Denque([1,2,3,4,5,6,7]); -denque.splice(denque.length, 0, 8, 9, 10); // [] -denque.toArray() // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] -denque.splice(3, 3, 44, 55, 66); // [4,5,6] -denque.splice(5,4, 666,667,668,669); // [ 66, 7, 8, 9 ] -denque.toArray() // [ 1, 2, 3, 44, 55, 666, 667, 668, 669, 10 ] -``` - -
- -#### `isEmpty()` -> `boolean` - -Return `true` if this queue is empty, `false` otherwise. - -```js -var denque = new Denque(); -denque.isEmpty(); // true -denque.push(1); -denque.isEmpty(); // false -``` - -
- -#### `clear()` -> `void` - -Remove all items from this queue. Does not change the queue's capacity. - -```js -var denque = new Denque([1,2,3]); -denque.toString(); // "1,2,3" -denque.clear(); -denque.toString(); // "" -``` -
- - -## Benchmarks - -#### Platform info: -``` -Darwin 17.0.0 x64 -Node.JS 9.4.0 -V8 6.2.414.46-node.17 -Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz × 8 -``` - -#### 1000 items in queue - - (3 x shift + 3 x push ops per 'op') - - denque x 64,365,425 ops/sec ±0.69% (92 runs sampled) - double-ended-queue x 26,646,882 ops/sec ±0.47% (94 runs sampled) - -#### 2 million items in queue - - (3 x shift + 3 x push ops per 'op') - - denque x 61,994,249 ops/sec ±0.26% (95 runs sampled) - double-ended-queue x 26,363,500 ops/sec ±0.42% (91 runs sampled) - -#### Splice - - (1 x splice per 'op') - initial size of 100,000 items - - denque.splice x 925,749 ops/sec ±22.29% (77 runs sampled) - native array splice x 7,777 ops/sec ±8.35% (50 runs sampled) - -#### Remove - - (1 x remove + 10 x push per 'op') - initial size of 100,000 items - - denque.remove x 2,635,275 ops/sec ±0.37% (95 runs sampled) - native array splice - Fails to complete: "JavaScript heap out of memory" - -#### Remove One - - (1 x removeOne + 10 x push per 'op') - initial size of 100,000 items - - denque.removeOne x 1,088,240 ops/sec ±0.21% (93 runs sampled) - native array splice x 5,300 ops/sec ±0.41% (96 runs sampled) - ---- - -Built and maintained with 💛 by [Invertase](https://invertase.io). - -- [💼 Hire Us](https://invertase.io/hire-us) -- [☕️ Sponsor Us](https://opencollective.com/react-native-firebase) -- [👩‍💻 Work With Us](https://invertase.io/jobs) diff --git a/node_modules/denque/index.d.ts b/node_modules/denque/index.d.ts deleted file mode 100644 index 803450f..0000000 --- a/node_modules/denque/index.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -declare class Denque { - constructor(); - constructor(array: T[]); - - push(item: T): number; - unshift(item: T): number; - pop(): T | undefined; - removeBack(): T | undefined; - shift(): T | undefined; - peekBack(): T | undefined; - peekFront(): T | undefined; - peekAt(index: number): T | undefined; - get(index: number): T | undefined; - remove(index: number, count: number): T[]; - removeOne(index: number): T | undefined; - splice(index: number, count: number, ...item: T[]): T[] | undefined; - isEmpty(): boolean; - clear(): void; - - toString(): string; - toArray(): T[]; - - length: number; -} - -export = Denque; diff --git a/node_modules/denque/index.js b/node_modules/denque/index.js deleted file mode 100644 index 2f03136..0000000 --- a/node_modules/denque/index.js +++ /dev/null @@ -1,437 +0,0 @@ -'use strict'; - -/** - * Custom implementation of a double ended queue. - */ -function Denque(array) { - this._head = 0; - this._tail = 0; - this._capacityMask = 0x3; - this._list = new Array(4); - if (Array.isArray(array)) { - this._fromArray(array); - } -} - -/** - * ------------- - * PUBLIC API - * ------------- - */ - -/** - * Returns the item at the specified index from the list. - * 0 is the first element, 1 is the second, and so on... - * Elements at negative values are that many from the end: -1 is one before the end - * (the last element), -2 is two before the end (one before last), etc. - * @param index - * @returns {*} - */ -Denque.prototype.peekAt = function peekAt(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - var len = this.size(); - if (i >= len || i < -len) return undefined; - if (i < 0) i += len; - i = (this._head + i) & this._capacityMask; - return this._list[i]; -}; - -/** - * Alias for peakAt() - * @param i - * @returns {*} - */ -Denque.prototype.get = function get(i) { - return this.peekAt(i); -}; - -/** - * Returns the first item in the list without removing it. - * @returns {*} - */ -Denque.prototype.peek = function peek() { - if (this._head === this._tail) return undefined; - return this._list[this._head]; -}; - -/** - * Alias for peek() - * @returns {*} - */ -Denque.prototype.peekFront = function peekFront() { - return this.peek(); -}; - -/** - * Returns the item that is at the back of the queue without removing it. - * Uses peekAt(-1) - */ -Denque.prototype.peekBack = function peekBack() { - return this.peekAt(-1); -}; - -/** - * Returns the current length of the queue - * @return {Number} - */ -Object.defineProperty(Denque.prototype, 'length', { - get: function length() { - return this.size(); - } -}); - -/** - * Return the number of items on the list, or 0 if empty. - * @returns {number} - */ -Denque.prototype.size = function size() { - if (this._head === this._tail) return 0; - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; - -/** - * Add an item at the beginning of the list. - * @param item - */ -Denque.prototype.unshift = function unshift(item) { - if (item === undefined) return this.size(); - var len = this._list.length; - this._head = (this._head - 1 + len) & this._capacityMask; - this._list[this._head] = item; - if (this._tail === this._head) this._growArray(); - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; - -/** - * Remove and return the first item on the list, - * Returns undefined if the list is empty. - * @returns {*} - */ -Denque.prototype.shift = function shift() { - var head = this._head; - if (head === this._tail) return undefined; - var item = this._list[head]; - this._list[head] = undefined; - this._head = (head + 1) & this._capacityMask; - if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); - return item; -}; - -/** - * Add an item to the bottom of the list. - * @param item - */ -Denque.prototype.push = function push(item) { - if (item === undefined) return this.size(); - var tail = this._tail; - this._list[tail] = item; - this._tail = (tail + 1) & this._capacityMask; - if (this._tail === this._head) { - this._growArray(); - } - - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; - -/** - * Remove and return the last item on the list. - * Returns undefined if the list is empty. - * @returns {*} - */ -Denque.prototype.pop = function pop() { - var tail = this._tail; - if (tail === this._head) return undefined; - var len = this._list.length; - this._tail = (tail - 1 + len) & this._capacityMask; - var item = this._list[this._tail]; - this._list[this._tail] = undefined; - if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); - return item; -}; - -/** - * Remove and return the item at the specified index from the list. - * Returns undefined if the list is empty. - * @param index - * @returns {*} - */ -Denque.prototype.removeOne = function removeOne(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size) return void 0; - if (i < 0) i += size; - i = (this._head + i) & this._capacityMask; - var item = this._list[i]; - var k; - if (index < size / 2) { - for (k = index; k > 0; k--) { - this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; - } - this._list[i] = void 0; - this._head = (this._head + 1 + len) & this._capacityMask; - } else { - for (k = size - 1 - index; k > 0; k--) { - this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; - } - this._list[i] = void 0; - this._tail = (this._tail - 1 + len) & this._capacityMask; - } - return item; -}; - -/** - * Remove number of items from the specified index from the list. - * Returns array of removed items. - * Returns undefined if the list is empty. - * @param index - * @param count - * @returns {array} - */ -Denque.prototype.remove = function remove(index, count) { - var i = index; - var removed; - var del_count = count; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size || count < 1) return void 0; - if (i < 0) i += size; - if (count === 1 || !count) { - removed = new Array(1); - removed[0] = this.removeOne(i); - return removed; - } - if (i === 0 && i + count >= size) { - removed = this.toArray(); - this.clear(); - return removed; - } - if (i + count > size) count = size - i; - var k; - removed = new Array(count); - for (k = 0; k < count; k++) { - removed[k] = this._list[(this._head + i + k) & this._capacityMask]; - } - i = (this._head + i) & this._capacityMask; - if (index + count === size) { - this._tail = (this._tail - count + len) & this._capacityMask; - for (k = count; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - } - return removed; - } - if (index === 0) { - this._head = (this._head + count + len) & this._capacityMask; - for (k = count - 1; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - } - return removed; - } - if (i < size / 2) { - this._head = (this._head + index + count + len) & this._capacityMask; - for (k = index; k > 0; k--) { - this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); - } - i = (this._head - 1 + len) & this._capacityMask; - while (del_count > 0) { - this._list[i = (i - 1 + len) & this._capacityMask] = void 0; - del_count--; - } - if (index < 0) this._tail = i; - } else { - this._tail = i; - i = (i + count + len) & this._capacityMask; - for (k = size - (count + index); k > 0; k--) { - this.push(this._list[i++]); - } - i = this._tail; - while (del_count > 0) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - del_count--; - } - } - if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); - return removed; -}; - -/** - * Native splice implementation. - * Remove number of items from the specified index from the list and/or add new elements. - * Returns array of removed items or empty array if count == 0. - * Returns undefined if the list is empty. - * - * @param index - * @param count - * @param {...*} [elements] - * @returns {array} - */ -Denque.prototype.splice = function splice(index, count) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - var size = this.size(); - if (i < 0) i += size; - if (i > size) return void 0; - if (arguments.length > 2) { - var k; - var temp; - var removed; - var arg_len = arguments.length; - var len = this._list.length; - var arguments_index = 2; - if (!size || i < size / 2) { - temp = new Array(i); - for (k = 0; k < i; k++) { - temp[k] = this._list[(this._head + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i > 0) { - this._head = (this._head + i + len) & this._capacityMask; - } - } else { - removed = this.remove(i, count); - this._head = (this._head + i + len) & this._capacityMask; - } - while (arg_len > arguments_index) { - this.unshift(arguments[--arg_len]); - } - for (k = i; k > 0; k--) { - this.unshift(temp[k - 1]); - } - } else { - temp = new Array(size - (i + count)); - var leng = temp.length; - for (k = 0; k < leng; k++) { - temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i != size) { - this._tail = (this._head + i + len) & this._capacityMask; - } - } else { - removed = this.remove(i, count); - this._tail = (this._tail - leng + len) & this._capacityMask; - } - while (arguments_index < arg_len) { - this.push(arguments[arguments_index++]); - } - for (k = 0; k < leng; k++) { - this.push(temp[k]); - } - } - return removed; - } else { - return this.remove(i, count); - } -}; - -/** - * Soft clear - does not reset capacity. - */ -Denque.prototype.clear = function clear() { - this._head = 0; - this._tail = 0; -}; - -/** - * Returns true or false whether the list is empty. - * @returns {boolean} - */ -Denque.prototype.isEmpty = function isEmpty() { - return this._head === this._tail; -}; - -/** - * Returns an array of all queue items. - * @returns {Array} - */ -Denque.prototype.toArray = function toArray() { - return this._copyArray(false); -}; - -/** - * ------------- - * INTERNALS - * ------------- - */ - -/** - * Fills the queue with items from an array - * For use in the constructor - * @param array - * @private - */ -Denque.prototype._fromArray = function _fromArray(array) { - for (var i = 0; i < array.length; i++) this.push(array[i]); -}; - -/** - * - * @param fullCopy - * @returns {Array} - * @private - */ -Denque.prototype._copyArray = function _copyArray(fullCopy) { - var newArray = []; - var list = this._list; - var len = list.length; - var i; - if (fullCopy || this._head > this._tail) { - for (i = this._head; i < len; i++) newArray.push(list[i]); - for (i = 0; i < this._tail; i++) newArray.push(list[i]); - } else { - for (i = this._head; i < this._tail; i++) newArray.push(list[i]); - } - return newArray; -}; - -/** - * Grows the internal list array. - * @private - */ -Denque.prototype._growArray = function _growArray() { - if (this._head) { - // copy existing data, head to end, then beginning to tail. - this._list = this._copyArray(true); - this._head = 0; - } - - // head is at 0 and array is now full, safe to extend - this._tail = this._list.length; - - this._list.length *= 2; - this._capacityMask = (this._capacityMask << 1) | 1; -}; - -/** - * Shrinks the internal list array. - * @private - */ -Denque.prototype._shrinkArray = function _shrinkArray() { - this._list.length >>>= 1; - this._capacityMask >>>= 1; -}; - - -module.exports = Denque; diff --git a/node_modules/denque/package.json b/node_modules/denque/package.json deleted file mode 100644 index 287ee9a..0000000 --- a/node_modules/denque/package.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "_from": "denque@^1.4.1", - "_id": "denque@1.4.1", - "_inBundle": false, - "_integrity": "sha512-OfzPuSZKGcgr96rf1oODnfjqBFmr1DVoc/TrItj3Ohe0Ah1C5WX5Baquw/9U9KovnQ88EqmJbD66rKYUQYN1tQ==", - "_location": "/denque", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "denque@^1.4.1", - "name": "denque", - "escapedName": "denque", - "rawSpec": "^1.4.1", - "saveSpec": null, - "fetchSpec": "^1.4.1" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/denque/-/denque-1.4.1.tgz", - "_shasum": "6744ff7641c148c3f8a69c307e51235c1f4a37cf", - "_spec": "denque@^1.4.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mongodb", - "author": { - "name": "Invertase", - "email": "oss@invertase.io", - "url": "http://github.com/invertase/" - }, - "bugs": { - "url": "https://github.com/invertase/denque/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Mike Diarmid", - "email": "mike@invertase.io", - "url": "Salakar" - } - ], - "deprecated": false, - "description": "The fastest javascript implementation of a double-ended queue. Maintains compatability with deque.", - "devDependencies": { - "benchmark": "^2.1.4", - "coveralls": "^2.13.3", - "double-ended-queue": "^2.1.0-0", - "istanbul": "^0.4.5", - "mocha": "^3.5.3", - "typescript": "^3.4.1" - }, - "engines": { - "node": ">=0.10" - }, - "homepage": "https://github.com/invertase/denque#readme", - "keywords": [ - "data-structure", - "data-structures", - "queue", - "double", - "end", - "ended", - "deque", - "denque", - "double-ended-queue" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "denque", - "repository": { - "type": "git", - "url": "git+https://github.com/invertase/denque.git" - }, - "scripts": { - "benchmark_2mil": "node benchmark/two_million", - "benchmark_remove": "node benchmark/remove", - "benchmark_removeOne": "node benchmark/removeOne", - "benchmark_splice": "node benchmark/splice", - "benchmark_thousand": "node benchmark/thousand", - "coveralls": "cat ./coverage/lcov.info | coveralls", - "test": "istanbul cover --report lcov _mocha && npm run typescript", - "typescript": "tsc --project ./test/type/tsconfig.json" - }, - "version": "1.4.1" -} diff --git a/node_modules/depd/History.md b/node_modules/depd/History.md deleted file mode 100644 index 507ecb8..0000000 --- a/node_modules/depd/History.md +++ /dev/null @@ -1,96 +0,0 @@ -1.1.2 / 2018-01-11 -================== - - * perf: remove argument reassignment - * Support Node.js 0.6 to 9.x - -1.1.1 / 2017-07-27 -================== - - * Remove unnecessary `Buffer` loading - * Support Node.js 0.6 to 8.x - -1.1.0 / 2015-09-14 -================== - - * Enable strict mode in more places - * Support io.js 3.x - * Support io.js 2.x - * Support web browser loading - - Requires bundler like Browserify or webpack - -1.0.1 / 2015-04-07 -================== - - * Fix `TypeError`s when under `'use strict'` code - * Fix useless type name on auto-generated messages - * Support io.js 1.x - * Support Node.js 0.12 - -1.0.0 / 2014-09-17 -================== - - * No changes - -0.4.5 / 2014-09-09 -================== - - * Improve call speed to functions using the function wrapper - * Support Node.js 0.6 - -0.4.4 / 2014-07-27 -================== - - * Work-around v8 generating empty stack traces - -0.4.3 / 2014-07-26 -================== - - * Fix exception when global `Error.stackTraceLimit` is too low - -0.4.2 / 2014-07-19 -================== - - * Correct call site for wrapped functions and properties - -0.4.1 / 2014-07-19 -================== - - * Improve automatic message generation for function properties - -0.4.0 / 2014-07-19 -================== - - * Add `TRACE_DEPRECATION` environment variable - * Remove non-standard grey color from color output - * Support `--no-deprecation` argument - * Support `--trace-deprecation` argument - * Support `deprecate.property(fn, prop, message)` - -0.3.0 / 2014-06-16 -================== - - * Add `NO_DEPRECATION` environment variable - -0.2.0 / 2014-06-15 -================== - - * Add `deprecate.property(obj, prop, message)` - * Remove `supports-color` dependency for node.js 0.8 - -0.1.0 / 2014-06-15 -================== - - * Add `deprecate.function(fn, message)` - * Add `process.on('deprecation', fn)` emitter - * Automatically generate message when omitted from `deprecate()` - -0.0.1 / 2014-06-15 -================== - - * Fix warning for dynamic calls at singe call site - -0.0.0 / 2014-06-15 -================== - - * Initial implementation diff --git a/node_modules/depd/LICENSE b/node_modules/depd/LICENSE deleted file mode 100644 index 84441fb..0000000 --- a/node_modules/depd/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2014-2017 Douglas Christopher Wilson - -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/depd/Readme.md b/node_modules/depd/Readme.md deleted file mode 100644 index 7790670..0000000 --- a/node_modules/depd/Readme.md +++ /dev/null @@ -1,280 +0,0 @@ -# depd - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][npm-url] -[![Node.js Version][node-image]][node-url] -[![Linux Build][travis-image]][travis-url] -[![Windows Build][appveyor-image]][appveyor-url] -[![Coverage Status][coveralls-image]][coveralls-url] - -Deprecate all the things - -> With great modules comes great responsibility; mark things deprecated! - -## Install - -This module is installed directly using `npm`: - -```sh -$ npm install depd -``` - -This module can also be bundled with systems like -[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), -though by default this module will alter it's API to no longer display or -track deprecations. - -## API - - - -```js -var deprecate = require('depd')('my-module') -``` - -This library allows you to display deprecation messages to your users. -This library goes above and beyond with deprecation warnings by -introspection of the call stack (but only the bits that it is interested -in). - -Instead of just warning on the first invocation of a deprecated -function and never again, this module will warn on the first invocation -of a deprecated function per unique call site, making it ideal to alert -users of all deprecated uses across the code base, rather than just -whatever happens to execute first. - -The deprecation warnings from this module also include the file and line -information for the call into the module that the deprecated function was -in. - -**NOTE** this library has a similar interface to the `debug` module, and -this module uses the calling file to get the boundary for the call stacks, -so you should always create a new `deprecate` object in each file and not -within some central file. - -### depd(namespace) - -Create a new deprecate function that uses the given namespace name in the -messages and will display the call site prior to the stack entering the -file this function was called from. It is highly suggested you use the -name of your module as the namespace. - -### deprecate(message) - -Call this function from deprecated code to display a deprecation message. -This message will appear once per unique caller site. Caller site is the -first call site in the stack in a different file from the caller of this -function. - -If the message is omitted, a message is generated for you based on the site -of the `deprecate()` call and will display the name of the function called, -similar to the name displayed in a stack trace. - -### deprecate.function(fn, message) - -Call this function to wrap a given function in a deprecation message on any -call to the function. An optional message can be supplied to provide a custom -message. - -### deprecate.property(obj, prop, message) - -Call this function to wrap a given property on object in a deprecation message -on any accessing or setting of the property. An optional message can be supplied -to provide a custom message. - -The method must be called on the object where the property belongs (not -inherited from the prototype). - -If the property is a data descriptor, it will be converted to an accessor -descriptor in order to display the deprecation message. - -### process.on('deprecation', fn) - -This module will allow easy capturing of deprecation errors by emitting the -errors as the type "deprecation" on the global `process`. If there are no -listeners for this type, the errors are written to STDERR as normal, but if -there are any listeners, nothing will be written to STDERR and instead only -emitted. From there, you can write the errors in a different format or to a -logging source. - -The error represents the deprecation and is emitted only once with the same -rules as writing to STDERR. The error has the following properties: - - - `message` - This is the message given by the library - - `name` - This is always `'DeprecationError'` - - `namespace` - This is the namespace the deprecation came from - - `stack` - This is the stack of the call to the deprecated thing - -Example `error.stack` output: - -``` -DeprecationError: my-cool-module deprecated oldfunction - at Object. ([eval]-wrapper:6:22) - at Module._compile (module.js:456:26) - at evalScript (node.js:532:25) - at startup (node.js:80:7) - at node.js:902:3 -``` - -### process.env.NO_DEPRECATION - -As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` -is provided as a quick solution to silencing deprecation warnings from being -output. The format of this is similar to that of `DEBUG`: - -```sh -$ NO_DEPRECATION=my-module,othermod node app.js -``` - -This will suppress deprecations from being output for "my-module" and "othermod". -The value is a list of comma-separated namespaces. To suppress every warning -across all namespaces, use the value `*` for a namespace. - -Providing the argument `--no-deprecation` to the `node` executable will suppress -all deprecations (only available in Node.js 0.8 or higher). - -**NOTE** This will not suppress the deperecations given to any "deprecation" -event listeners, just the output to STDERR. - -### process.env.TRACE_DEPRECATION - -As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` -is provided as a solution to getting more detailed location information in deprecation -warnings by including the entire stack trace. The format of this is the same as -`NO_DEPRECATION`: - -```sh -$ TRACE_DEPRECATION=my-module,othermod node app.js -``` - -This will include stack traces for deprecations being output for "my-module" and -"othermod". The value is a list of comma-separated namespaces. To trace every -warning across all namespaces, use the value `*` for a namespace. - -Providing the argument `--trace-deprecation` to the `node` executable will trace -all deprecations (only available in Node.js 0.8 or higher). - -**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. - -## Display - -![message](files/message.png) - -When a user calls a function in your library that you mark deprecated, they -will see the following written to STDERR (in the given colors, similar colors -and layout to the `debug` module): - -``` -bright cyan bright yellow -| | reset cyan -| | | | -▼ ▼ ▼ ▼ -my-cool-module deprecated oldfunction [eval]-wrapper:6:22 -▲ ▲ ▲ ▲ -| | | | -namespace | | location of mycoolmod.oldfunction() call - | deprecation message - the word "deprecated" -``` - -If the user redirects their STDERR to a file or somewhere that does not support -colors, they see (similar layout to the `debug` module): - -``` -Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 -▲ ▲ ▲ ▲ ▲ -| | | | | -timestamp of message namespace | | location of mycoolmod.oldfunction() call - | deprecation message - the word "deprecated" -``` - -## Examples - -### Deprecating all calls to a function - -This will display a deprecated message about "oldfunction" being deprecated -from "my-module" on STDERR. - -```js -var deprecate = require('depd')('my-cool-module') - -// message automatically derived from function name -// Object.oldfunction -exports.oldfunction = deprecate.function(function oldfunction () { - // all calls to function are deprecated -}) - -// specific message -exports.oldfunction = deprecate.function(function () { - // all calls to function are deprecated -}, 'oldfunction') -``` - -### Conditionally deprecating a function call - -This will display a deprecated message about "weirdfunction" being deprecated -from "my-module" on STDERR when called with less than 2 arguments. - -```js -var deprecate = require('depd')('my-cool-module') - -exports.weirdfunction = function () { - if (arguments.length < 2) { - // calls with 0 or 1 args are deprecated - deprecate('weirdfunction args < 2') - } -} -``` - -When calling `deprecate` as a function, the warning is counted per call site -within your own module, so you can display different deprecations depending -on different situations and the users will still get all the warnings: - -```js -var deprecate = require('depd')('my-cool-module') - -exports.weirdfunction = function () { - if (arguments.length < 2) { - // calls with 0 or 1 args are deprecated - deprecate('weirdfunction args < 2') - } else if (typeof arguments[0] !== 'string') { - // calls with non-string first argument are deprecated - deprecate('weirdfunction non-string first arg') - } -} -``` - -### Deprecating property access - -This will display a deprecated message about "oldprop" being deprecated -from "my-module" on STDERR when accessed. A deprecation will be displayed -when setting the value and when getting the value. - -```js -var deprecate = require('depd')('my-cool-module') - -exports.oldprop = 'something' - -// message automatically derives from property name -deprecate.property(exports, 'oldprop') - -// explicit message -deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') -``` - -## License - -[MIT](LICENSE) - -[npm-version-image]: https://img.shields.io/npm/v/depd.svg -[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg -[npm-url]: https://npmjs.org/package/depd -[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux -[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd -[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows -[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd -[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg -[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master -[node-image]: https://img.shields.io/node/v/depd.svg -[node-url]: https://nodejs.org/en/download/ diff --git a/node_modules/depd/index.js b/node_modules/depd/index.js deleted file mode 100644 index d758d3c..0000000 --- a/node_modules/depd/index.js +++ /dev/null @@ -1,522 +0,0 @@ -/*! - * depd - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var callSiteToString = require('./lib/compat').callSiteToString -var eventListenerCount = require('./lib/compat').eventListenerCount -var relative = require('path').relative - -/** - * Module exports. - */ - -module.exports = depd - -/** - * Get the path to base files on. - */ - -var basePath = process.cwd() - -/** - * Determine if namespace is contained in the string. - */ - -function containsNamespace (str, namespace) { - var vals = str.split(/[ ,]+/) - var ns = String(namespace).toLowerCase() - - for (var i = 0; i < vals.length; i++) { - var val = vals[i] - - // namespace contained - if (val && (val === '*' || val.toLowerCase() === ns)) { - return true - } - } - - return false -} - -/** - * Convert a data descriptor to accessor descriptor. - */ - -function convertDataDescriptorToAccessor (obj, prop, message) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - var value = descriptor.value - - descriptor.get = function getter () { return value } - - if (descriptor.writable) { - descriptor.set = function setter (val) { return (value = val) } - } - - delete descriptor.value - delete descriptor.writable - - Object.defineProperty(obj, prop, descriptor) - - return descriptor -} - -/** - * Create arguments string to keep arity. - */ - -function createArgumentsString (arity) { - var str = '' - - for (var i = 0; i < arity; i++) { - str += ', arg' + i - } - - return str.substr(2) -} - -/** - * Create stack string from stack. - */ - -function createStackString (stack) { - var str = this.name + ': ' + this.namespace - - if (this.message) { - str += ' deprecated ' + this.message - } - - for (var i = 0; i < stack.length; i++) { - str += '\n at ' + callSiteToString(stack[i]) - } - - return str -} - -/** - * Create deprecate for namespace in caller. - */ - -function depd (namespace) { - if (!namespace) { - throw new TypeError('argument namespace is required') - } - - var stack = getStack() - var site = callSiteLocation(stack[1]) - var file = site[0] - - function deprecate (message) { - // call to self as log - log.call(deprecate, message) - } - - deprecate._file = file - deprecate._ignored = isignored(namespace) - deprecate._namespace = namespace - deprecate._traced = istraced(namespace) - deprecate._warned = Object.create(null) - - deprecate.function = wrapfunction - deprecate.property = wrapproperty - - return deprecate -} - -/** - * Determine if namespace is ignored. - */ - -function isignored (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.noDeprecation) { - // --no-deprecation support - return true - } - - var str = process.env.NO_DEPRECATION || '' - - // namespace ignored - return containsNamespace(str, namespace) -} - -/** - * Determine if namespace is traced. - */ - -function istraced (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.traceDeprecation) { - // --trace-deprecation support - return true - } - - var str = process.env.TRACE_DEPRECATION || '' - - // namespace traced - return containsNamespace(str, namespace) -} - -/** - * Display deprecation message. - */ - -function log (message, site) { - var haslisteners = eventListenerCount(process, 'deprecation') !== 0 - - // abort early if no destination - if (!haslisteners && this._ignored) { - return - } - - var caller - var callFile - var callSite - var depSite - var i = 0 - var seen = false - var stack = getStack() - var file = this._file - - if (site) { - // provided site - depSite = site - callSite = callSiteLocation(stack[1]) - callSite.name = depSite.name - file = callSite[0] - } else { - // get call site - i = 2 - depSite = callSiteLocation(stack[i]) - callSite = depSite - } - - // get caller of deprecated thing in relation to file - for (; i < stack.length; i++) { - caller = callSiteLocation(stack[i]) - callFile = caller[0] - - if (callFile === file) { - seen = true - } else if (callFile === this._file) { - file = this._file - } else if (seen) { - break - } - } - - var key = caller - ? depSite.join(':') + '__' + caller.join(':') - : undefined - - if (key !== undefined && key in this._warned) { - // already warned - return - } - - this._warned[key] = true - - // generate automatic message from call site - var msg = message - if (!msg) { - msg = callSite === depSite || !callSite.name - ? defaultMessage(depSite) - : defaultMessage(callSite) - } - - // emit deprecation if listeners exist - if (haslisteners) { - var err = DeprecationError(this._namespace, msg, stack.slice(i)) - process.emit('deprecation', err) - return - } - - // format and write message - var format = process.stderr.isTTY - ? formatColor - : formatPlain - var output = format.call(this, msg, caller, stack.slice(i)) - process.stderr.write(output + '\n', 'utf8') -} - -/** - * Get call site location as array. - */ - -function callSiteLocation (callSite) { - var file = callSite.getFileName() || '' - var line = callSite.getLineNumber() - var colm = callSite.getColumnNumber() - - if (callSite.isEval()) { - file = callSite.getEvalOrigin() + ', ' + file - } - - var site = [file, line, colm] - - site.callSite = callSite - site.name = callSite.getFunctionName() - - return site -} - -/** - * Generate a default message from the site. - */ - -function defaultMessage (site) { - var callSite = site.callSite - var funcName = site.name - - // make useful anonymous name - if (!funcName) { - funcName = '' - } - - var context = callSite.getThis() - var typeName = context && callSite.getTypeName() - - // ignore useless type name - if (typeName === 'Object') { - typeName = undefined - } - - // make useful type name - if (typeName === 'Function') { - typeName = context.name || typeName - } - - return typeName && callSite.getMethodName() - ? typeName + '.' + funcName - : funcName -} - -/** - * Format deprecation message without color. - */ - -function formatPlain (msg, caller, stack) { - var timestamp = new Date().toUTCString() - - var formatted = timestamp + - ' ' + this._namespace + - ' deprecated ' + msg - - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n at ' + callSiteToString(stack[i]) - } - - return formatted - } - - if (caller) { - formatted += ' at ' + formatLocation(caller) - } - - return formatted -} - -/** - * Format deprecation message with color. - */ - -function formatColor (msg, caller, stack) { - var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan - ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow - ' \x1b[0m' + msg + '\x1b[39m' // reset - - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan - } - - return formatted - } - - if (caller) { - formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan - } - - return formatted -} - -/** - * Format call site location. - */ - -function formatLocation (callSite) { - return relative(basePath, callSite[0]) + - ':' + callSite[1] + - ':' + callSite[2] -} - -/** - * Get the stack as array of call sites. - */ - -function getStack () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace - - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = Math.max(10, limit) - - // capture the stack - Error.captureStackTrace(obj) - - // slice this function off the top - var stack = obj.stack.slice(1) - - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit - - return stack -} - -/** - * Capture call site stack from v8. - */ - -function prepareObjectStackTrace (obj, stack) { - return stack -} - -/** - * Return a wrapped function in a deprecation message. - */ - -function wrapfunction (fn, message) { - if (typeof fn !== 'function') { - throw new TypeError('argument fn must be a function') - } - - var args = createArgumentsString(fn.length) - var deprecate = this // eslint-disable-line no-unused-vars - var stack = getStack() - var site = callSiteLocation(stack[1]) - - site.name = fn.name - - // eslint-disable-next-line no-eval - var deprecatedfn = eval('(function (' + args + ') {\n' + - '"use strict"\n' + - 'log.call(deprecate, message, site)\n' + - 'return fn.apply(this, arguments)\n' + - '})') - - return deprecatedfn -} - -/** - * Wrap property in a deprecation message. - */ - -function wrapproperty (obj, prop, message) { - if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { - throw new TypeError('argument obj must be object') - } - - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - - if (!descriptor) { - throw new TypeError('must call property on owner object') - } - - if (!descriptor.configurable) { - throw new TypeError('property must be configurable') - } - - var deprecate = this - var stack = getStack() - var site = callSiteLocation(stack[1]) - - // set site name - site.name = prop - - // convert data descriptor - if ('value' in descriptor) { - descriptor = convertDataDescriptorToAccessor(obj, prop, message) - } - - var get = descriptor.get - var set = descriptor.set - - // wrap getter - if (typeof get === 'function') { - descriptor.get = function getter () { - log.call(deprecate, message, site) - return get.apply(this, arguments) - } - } - - // wrap setter - if (typeof set === 'function') { - descriptor.set = function setter () { - log.call(deprecate, message, site) - return set.apply(this, arguments) - } - } - - Object.defineProperty(obj, prop, descriptor) -} - -/** - * Create DeprecationError for deprecation - */ - -function DeprecationError (namespace, message, stack) { - var error = new Error() - var stackString - - Object.defineProperty(error, 'constructor', { - value: DeprecationError - }) - - Object.defineProperty(error, 'message', { - configurable: true, - enumerable: false, - value: message, - writable: true - }) - - Object.defineProperty(error, 'name', { - enumerable: false, - configurable: true, - value: 'DeprecationError', - writable: true - }) - - Object.defineProperty(error, 'namespace', { - configurable: true, - enumerable: false, - value: namespace, - writable: true - }) - - Object.defineProperty(error, 'stack', { - configurable: true, - enumerable: false, - get: function () { - if (stackString !== undefined) { - return stackString - } - - // prepare stack trace - return (stackString = createStackString.call(this, stack)) - }, - set: function setter (val) { - stackString = val - } - }) - - return error -} diff --git a/node_modules/depd/lib/browser/index.js b/node_modules/depd/lib/browser/index.js deleted file mode 100644 index 6be45cc..0000000 --- a/node_modules/depd/lib/browser/index.js +++ /dev/null @@ -1,77 +0,0 @@ -/*! - * depd - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module exports. - * @public - */ - -module.exports = depd - -/** - * Create deprecate for namespace in caller. - */ - -function depd (namespace) { - if (!namespace) { - throw new TypeError('argument namespace is required') - } - - function deprecate (message) { - // no-op in browser - } - - deprecate._file = undefined - deprecate._ignored = true - deprecate._namespace = namespace - deprecate._traced = false - deprecate._warned = Object.create(null) - - deprecate.function = wrapfunction - deprecate.property = wrapproperty - - return deprecate -} - -/** - * Return a wrapped function in a deprecation message. - * - * This is a no-op version of the wrapper, which does nothing but call - * validation. - */ - -function wrapfunction (fn, message) { - if (typeof fn !== 'function') { - throw new TypeError('argument fn must be a function') - } - - return fn -} - -/** - * Wrap property in a deprecation message. - * - * This is a no-op version of the wrapper, which does nothing but call - * validation. - */ - -function wrapproperty (obj, prop, message) { - if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { - throw new TypeError('argument obj must be object') - } - - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - - if (!descriptor) { - throw new TypeError('must call property on owner object') - } - - if (!descriptor.configurable) { - throw new TypeError('property must be configurable') - } -} diff --git a/node_modules/depd/lib/compat/callsite-tostring.js b/node_modules/depd/lib/compat/callsite-tostring.js deleted file mode 100644 index 73186dc..0000000 --- a/node_modules/depd/lib/compat/callsite-tostring.js +++ /dev/null @@ -1,103 +0,0 @@ -/*! - * depd - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module exports. - */ - -module.exports = callSiteToString - -/** - * Format a CallSite file location to a string. - */ - -function callSiteFileLocation (callSite) { - var fileName - var fileLocation = '' - - if (callSite.isNative()) { - fileLocation = 'native' - } else if (callSite.isEval()) { - fileName = callSite.getScriptNameOrSourceURL() - if (!fileName) { - fileLocation = callSite.getEvalOrigin() - } - } else { - fileName = callSite.getFileName() - } - - if (fileName) { - fileLocation += fileName - - var lineNumber = callSite.getLineNumber() - if (lineNumber != null) { - fileLocation += ':' + lineNumber - - var columnNumber = callSite.getColumnNumber() - if (columnNumber) { - fileLocation += ':' + columnNumber - } - } - } - - return fileLocation || 'unknown source' -} - -/** - * Format a CallSite to a string. - */ - -function callSiteToString (callSite) { - var addSuffix = true - var fileLocation = callSiteFileLocation(callSite) - var functionName = callSite.getFunctionName() - var isConstructor = callSite.isConstructor() - var isMethodCall = !(callSite.isToplevel() || isConstructor) - var line = '' - - if (isMethodCall) { - var methodName = callSite.getMethodName() - var typeName = getConstructorName(callSite) - - if (functionName) { - if (typeName && functionName.indexOf(typeName) !== 0) { - line += typeName + '.' - } - - line += functionName - - if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { - line += ' [as ' + methodName + ']' - } - } else { - line += typeName + '.' + (methodName || '') - } - } else if (isConstructor) { - line += 'new ' + (functionName || '') - } else if (functionName) { - line += functionName - } else { - addSuffix = false - line += fileLocation - } - - if (addSuffix) { - line += ' (' + fileLocation + ')' - } - - return line -} - -/** - * Get constructor name of reviver. - */ - -function getConstructorName (obj) { - var receiver = obj.receiver - return (receiver.constructor && receiver.constructor.name) || null -} diff --git a/node_modules/depd/lib/compat/event-listener-count.js b/node_modules/depd/lib/compat/event-listener-count.js deleted file mode 100644 index 3a8925d..0000000 --- a/node_modules/depd/lib/compat/event-listener-count.js +++ /dev/null @@ -1,22 +0,0 @@ -/*! - * depd - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module exports. - * @public - */ - -module.exports = eventListenerCount - -/** - * Get the count of listeners on an event emitter of a specific type. - */ - -function eventListenerCount (emitter, type) { - return emitter.listeners(type).length -} diff --git a/node_modules/depd/lib/compat/index.js b/node_modules/depd/lib/compat/index.js deleted file mode 100644 index 955b333..0000000 --- a/node_modules/depd/lib/compat/index.js +++ /dev/null @@ -1,79 +0,0 @@ -/*! - * depd - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var EventEmitter = require('events').EventEmitter - -/** - * Module exports. - * @public - */ - -lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace - - function prepareObjectStackTrace (obj, stack) { - return stack - } - - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = 2 - - // capture the stack - Error.captureStackTrace(obj) - - // slice the stack - var stack = obj.stack.slice() - - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit - - return stack[0].toString ? toString : require('./callsite-tostring') -}) - -lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { - return EventEmitter.listenerCount || require('./event-listener-count') -}) - -/** - * Define a lazy property. - */ - -function lazyProperty (obj, prop, getter) { - function get () { - var val = getter() - - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - value: val - }) - - return val - } - - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - get: get - }) -} - -/** - * Call toString() on the obj - */ - -function toString (obj) { - return obj.toString() -} diff --git a/node_modules/depd/package.json b/node_modules/depd/package.json deleted file mode 100644 index 5834929..0000000 --- a/node_modules/depd/package.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "_from": "depd@~1.1.2", - "_id": "depd@1.1.2", - "_inBundle": false, - "_integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", - "_location": "/depd", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "depd@~1.1.2", - "name": "depd", - "escapedName": "depd", - "rawSpec": "~1.1.2", - "saveSpec": null, - "fetchSpec": "~1.1.2" - }, - "_requiredBy": [ - "/body-parser", - "/express", - "/http-errors", - "/send" - ], - "_resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", - "_shasum": "9bcd52e14c097763e749b274c4346ed2e560b5a9", - "_spec": "depd@~1.1.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "author": { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - "browser": "lib/browser/index.js", - "bugs": { - "url": "https://github.com/dougwilson/nodejs-depd/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Deprecate all the things", - "devDependencies": { - "beautify-benchmark": "0.2.4", - "benchmark": "2.1.4", - "eslint": "3.19.0", - "eslint-config-standard": "7.1.0", - "eslint-plugin-markdown": "1.0.0-beta.7", - "eslint-plugin-promise": "3.6.0", - "eslint-plugin-standard": "3.0.1", - "istanbul": "0.4.5", - "mocha": "~1.21.5" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "lib/", - "History.md", - "LICENSE", - "index.js", - "Readme.md" - ], - "homepage": "https://github.com/dougwilson/nodejs-depd#readme", - "keywords": [ - "deprecate", - "deprecated" - ], - "license": "MIT", - "name": "depd", - "repository": { - "type": "git", - "url": "git+https://github.com/dougwilson/nodejs-depd.git" - }, - "scripts": { - "bench": "node benchmark/index.js", - "lint": "eslint --plugin markdown --ext js,md .", - "test": "mocha --reporter spec --bail test/", - "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --no-exit test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/" - }, - "version": "1.1.2" -} diff --git a/node_modules/destroy/LICENSE b/node_modules/destroy/LICENSE deleted file mode 100644 index a7ae8ee..0000000 --- a/node_modules/destroy/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ - -The MIT License (MIT) - -Copyright (c) 2014 Jonathan Ong me@jongleberry.com - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/destroy/README.md b/node_modules/destroy/README.md deleted file mode 100644 index 6474bc3..0000000 --- a/node_modules/destroy/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# Destroy - -[![NPM version][npm-image]][npm-url] -[![Build status][travis-image]][travis-url] -[![Test coverage][coveralls-image]][coveralls-url] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] -[![Gittip][gittip-image]][gittip-url] - -Destroy a stream. - -This module is meant to ensure a stream gets destroyed, handling different APIs -and Node.js bugs. - -## API - -```js -var destroy = require('destroy') -``` - -### destroy(stream) - -Destroy the given stream. In most cases, this is identical to a simple -`stream.destroy()` call. The rules are as follows for a given stream: - - 1. If the `stream` is an instance of `ReadStream`, then call `stream.destroy()` - and add a listener to the `open` event to call `stream.close()` if it is - fired. This is for a Node.js bug that will leak a file descriptor if - `.destroy()` is called before `open`. - 2. If the `stream` is not an instance of `Stream`, then nothing happens. - 3. If the `stream` has a `.destroy()` method, then call it. - -The function returns the `stream` passed in as the argument. - -## Example - -```js -var destroy = require('destroy') - -var fs = require('fs') -var stream = fs.createReadStream('package.json') - -// ... and later -destroy(stream) -``` - -[npm-image]: https://img.shields.io/npm/v/destroy.svg?style=flat-square -[npm-url]: https://npmjs.org/package/destroy -[github-tag]: http://img.shields.io/github/tag/stream-utils/destroy.svg?style=flat-square -[github-url]: https://github.com/stream-utils/destroy/tags -[travis-image]: https://img.shields.io/travis/stream-utils/destroy.svg?style=flat-square -[travis-url]: https://travis-ci.org/stream-utils/destroy -[coveralls-image]: https://img.shields.io/coveralls/stream-utils/destroy.svg?style=flat-square -[coveralls-url]: https://coveralls.io/r/stream-utils/destroy?branch=master -[license-image]: http://img.shields.io/npm/l/destroy.svg?style=flat-square -[license-url]: LICENSE.md -[downloads-image]: http://img.shields.io/npm/dm/destroy.svg?style=flat-square -[downloads-url]: https://npmjs.org/package/destroy -[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square -[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/node_modules/destroy/index.js b/node_modules/destroy/index.js deleted file mode 100644 index 6da2d26..0000000 --- a/node_modules/destroy/index.js +++ /dev/null @@ -1,75 +0,0 @@ -/*! - * destroy - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var ReadStream = require('fs').ReadStream -var Stream = require('stream') - -/** - * Module exports. - * @public - */ - -module.exports = destroy - -/** - * Destroy a stream. - * - * @param {object} stream - * @public - */ - -function destroy(stream) { - if (stream instanceof ReadStream) { - return destroyReadStream(stream) - } - - if (!(stream instanceof Stream)) { - return stream - } - - if (typeof stream.destroy === 'function') { - stream.destroy() - } - - return stream -} - -/** - * Destroy a ReadStream. - * - * @param {object} stream - * @private - */ - -function destroyReadStream(stream) { - stream.destroy() - - if (typeof stream.close === 'function') { - // node.js core bug work-around - stream.on('open', onOpenClose) - } - - return stream -} - -/** - * On open handler to close stream. - * @private - */ - -function onOpenClose() { - if (typeof this.fd === 'number') { - // actually close down the fd - this.close() - } -} diff --git a/node_modules/destroy/package.json b/node_modules/destroy/package.json deleted file mode 100644 index d969269..0000000 --- a/node_modules/destroy/package.json +++ /dev/null @@ -1,71 +0,0 @@ -{ - "_from": "destroy@~1.0.4", - "_id": "destroy@1.0.4", - "_inBundle": false, - "_integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=", - "_location": "/destroy", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "destroy@~1.0.4", - "name": "destroy", - "escapedName": "destroy", - "rawSpec": "~1.0.4", - "saveSpec": null, - "fetchSpec": "~1.0.4" - }, - "_requiredBy": [ - "/send" - ], - "_resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", - "_shasum": "978857442c44749e4206613e37946205826abd80", - "_spec": "destroy@~1.0.4", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/send", - "author": { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - }, - "bugs": { - "url": "https://github.com/stream-utils/destroy/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - } - ], - "deprecated": false, - "description": "destroy a stream if possible", - "devDependencies": { - "istanbul": "0.4.2", - "mocha": "2.3.4" - }, - "files": [ - "index.js", - "LICENSE" - ], - "homepage": "https://github.com/stream-utils/destroy#readme", - "keywords": [ - "stream", - "streams", - "destroy", - "cleanup", - "leak", - "fd" - ], - "license": "MIT", - "name": "destroy", - "repository": { - "type": "git", - "url": "git+https://github.com/stream-utils/destroy.git" - }, - "scripts": { - "test": "mocha --reporter spec", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" - }, - "version": "1.0.4" -} diff --git a/node_modules/detect-libc/.npmignore b/node_modules/detect-libc/.npmignore deleted file mode 100644 index 8fc0e8d..0000000 --- a/node_modules/detect-libc/.npmignore +++ /dev/null @@ -1,7 +0,0 @@ -.nyc_output -.travis.yml -coverage -test.js -node_modules -/.circleci -/tests/integration diff --git a/node_modules/detect-libc/LICENSE b/node_modules/detect-libc/LICENSE deleted file mode 100644 index 8dada3e..0000000 --- a/node_modules/detect-libc/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/node_modules/detect-libc/README.md b/node_modules/detect-libc/README.md deleted file mode 100644 index 3176357..0000000 --- a/node_modules/detect-libc/README.md +++ /dev/null @@ -1,78 +0,0 @@ -# detect-libc - -Node.js module to detect the C standard library (libc) implementation -family and version in use on a given Linux system. - -Provides a value suitable for use with the `LIBC` option of -[prebuild](https://www.npmjs.com/package/prebuild), -[prebuild-ci](https://www.npmjs.com/package/prebuild-ci) and -[prebuild-install](https://www.npmjs.com/package/prebuild-install), -therefore allowing build and provision of pre-compiled binaries -for musl-based Linux e.g. Alpine as well as glibc-based. - -Currently supports libc detection of `glibc` and `musl`. - -## Install - -```sh -npm install detect-libc -``` - -## Usage - -### API - -```js -const { GLIBC, MUSL, family, version, isNonGlibcLinux } = require('detect-libc'); -``` - -* `GLIBC` is a String containing the value "glibc" for comparison with `family`. -* `MUSL` is a String containing the value "musl" for comparison with `family`. -* `family` is a String representing the system libc family. -* `version` is a String representing the system libc version number. -* `isNonGlibcLinux` is a Boolean representing whether the system is a non-glibc Linux, e.g. Alpine. - -### detect-libc command line tool - -When run on a Linux system with a non-glibc libc, -the child command will be run with the `LIBC` environment variable -set to the relevant value. - -On all other platforms will run the child command as-is. - -The command line feature requires `spawnSync` provided by Node v0.12+. - -```sh -detect-libc child-command -``` - -## Integrating with prebuild - -```json - "scripts": { - "install": "detect-libc prebuild-install || node-gyp rebuild", - "test": "mocha && detect-libc prebuild-ci" - }, - "dependencies": { - "detect-libc": "^1.0.2", - "prebuild-install": "^2.2.0" - }, - "devDependencies": { - "prebuild": "^6.2.1", - "prebuild-ci": "^2.2.3" - } -``` - -## Licence - -Copyright 2017 Lovell Fuller - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0.html) - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/node_modules/detect-libc/bin/detect-libc.js b/node_modules/detect-libc/bin/detect-libc.js deleted file mode 100755 index 5486127..0000000 --- a/node_modules/detect-libc/bin/detect-libc.js +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env node - -'use strict'; - -var spawnSync = require('child_process').spawnSync; -var libc = require('../'); - -var spawnOptions = { - env: process.env, - shell: true, - stdio: 'inherit' -}; - -if (libc.isNonGlibcLinux) { - spawnOptions.env.LIBC = process.env.LIBC || libc.family; -} - -process.exit(spawnSync(process.argv[2], process.argv.slice(3), spawnOptions).status); diff --git a/node_modules/detect-libc/lib/detect-libc.js b/node_modules/detect-libc/lib/detect-libc.js deleted file mode 100644 index 1855fe1..0000000 --- a/node_modules/detect-libc/lib/detect-libc.js +++ /dev/null @@ -1,92 +0,0 @@ -'use strict'; - -var platform = require('os').platform(); -var spawnSync = require('child_process').spawnSync; -var readdirSync = require('fs').readdirSync; - -var GLIBC = 'glibc'; -var MUSL = 'musl'; - -var spawnOptions = { - encoding: 'utf8', - env: process.env -}; - -if (!spawnSync) { - spawnSync = function () { - return { status: 126, stdout: '', stderr: '' }; - }; -} - -function contains (needle) { - return function (haystack) { - return haystack.indexOf(needle) !== -1; - }; -} - -function versionFromMuslLdd (out) { - return out.split(/[\r\n]+/)[1].trim().split(/\s/)[1]; -} - -function safeReaddirSync (path) { - try { - return readdirSync(path); - } catch (e) {} - return []; -} - -var family = ''; -var version = ''; -var method = ''; - -if (platform === 'linux') { - // Try getconf - var glibc = spawnSync('getconf', ['GNU_LIBC_VERSION'], spawnOptions); - if (glibc.status === 0) { - family = GLIBC; - version = glibc.stdout.trim().split(' ')[1]; - method = 'getconf'; - } else { - // Try ldd - var ldd = spawnSync('ldd', ['--version'], spawnOptions); - if (ldd.status === 0 && ldd.stdout.indexOf(MUSL) !== -1) { - family = MUSL; - version = versionFromMuslLdd(ldd.stdout); - method = 'ldd'; - } else if (ldd.status === 1 && ldd.stderr.indexOf(MUSL) !== -1) { - family = MUSL; - version = versionFromMuslLdd(ldd.stderr); - method = 'ldd'; - } else { - // Try filesystem (family only) - var lib = safeReaddirSync('/lib'); - if (lib.some(contains('-linux-gnu'))) { - family = GLIBC; - method = 'filesystem'; - } else if (lib.some(contains('libc.musl-'))) { - family = MUSL; - method = 'filesystem'; - } else if (lib.some(contains('ld-musl-'))) { - family = MUSL; - method = 'filesystem'; - } else { - var usrSbin = safeReaddirSync('/usr/sbin'); - if (usrSbin.some(contains('glibc'))) { - family = GLIBC; - method = 'filesystem'; - } - } - } - } -} - -var isNonGlibcLinux = (family !== '' && family !== GLIBC); - -module.exports = { - GLIBC: GLIBC, - MUSL: MUSL, - family: family, - version: version, - method: method, - isNonGlibcLinux: isNonGlibcLinux -}; diff --git a/node_modules/detect-libc/package.json b/node_modules/detect-libc/package.json deleted file mode 100644 index 04d8d2d..0000000 --- a/node_modules/detect-libc/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "_from": "detect-libc@^1.0.3", - "_id": "detect-libc@1.0.3", - "_inBundle": false, - "_integrity": "sha1-+hN8S9aY7fVc1c0CrFWfkaTEups=", - "_location": "/detect-libc", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "detect-libc@^1.0.3", - "name": "detect-libc", - "escapedName": "detect-libc", - "rawSpec": "^1.0.3", - "saveSpec": null, - "fetchSpec": "^1.0.3" - }, - "_requiredBy": [ - "/prebuild-install" - ], - "_resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-1.0.3.tgz", - "_shasum": "fa137c4bd698edf55cd5cd02ac559f91a4c4ba9b", - "_spec": "detect-libc@^1.0.3", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/prebuild-install", - "author": { - "name": "Lovell Fuller", - "email": "npm@lovell.info" - }, - "bin": { - "detect-libc": "bin/detect-libc.js" - }, - "bugs": { - "url": "https://github.com/lovell/detect-libc/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Niklas Salmoukas", - "email": "niklas@salmoukas.com" - } - ], - "deprecated": false, - "description": "Node.js module to detect the C standard library (libc) implementation family and version", - "devDependencies": { - "ava": "^0.23.0", - "nyc": "^11.3.0", - "proxyquire": "^1.8.0", - "semistandard": "^11.0.0" - }, - "engines": { - "node": ">=0.10" - }, - "homepage": "https://github.com/lovell/detect-libc#readme", - "keywords": [ - "libc", - "glibc", - "musl" - ], - "license": "Apache-2.0", - "main": "lib/detect-libc.js", - "name": "detect-libc", - "repository": { - "type": "git", - "url": "git://github.com/lovell/detect-libc.git" - }, - "scripts": { - "test": "semistandard && nyc --reporter=lcov ava" - }, - "version": "1.0.3" -} diff --git a/node_modules/ee-first/LICENSE b/node_modules/ee-first/LICENSE deleted file mode 100644 index a7ae8ee..0000000 --- a/node_modules/ee-first/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ - -The MIT License (MIT) - -Copyright (c) 2014 Jonathan Ong me@jongleberry.com - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/ee-first/README.md b/node_modules/ee-first/README.md deleted file mode 100644 index cbd2478..0000000 --- a/node_modules/ee-first/README.md +++ /dev/null @@ -1,80 +0,0 @@ -# EE First - -[![NPM version][npm-image]][npm-url] -[![Build status][travis-image]][travis-url] -[![Test coverage][coveralls-image]][coveralls-url] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] -[![Gittip][gittip-image]][gittip-url] - -Get the first event in a set of event emitters and event pairs, -then clean up after itself. - -## Install - -```sh -$ npm install ee-first -``` - -## API - -```js -var first = require('ee-first') -``` - -### first(arr, listener) - -Invoke `listener` on the first event from the list specified in `arr`. `arr` is -an array of arrays, with each array in the format `[ee, ...event]`. `listener` -will be called only once, the first time any of the given events are emitted. If -`error` is one of the listened events, then if that fires first, the `listener` -will be given the `err` argument. - -The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the -first argument emitted from an `error` event, if applicable; `ee` is the event -emitter that fired; `event` is the string event name that fired; and `args` is an -array of the arguments that were emitted on the event. - -```js -var ee1 = new EventEmitter() -var ee2 = new EventEmitter() - -first([ - [ee1, 'close', 'end', 'error'], - [ee2, 'error'] -], function (err, ee, event, args) { - // listener invoked -}) -``` - -#### .cancel() - -The group of listeners can be cancelled before being invoked and have all the event -listeners removed from the underlying event emitters. - -```js -var thunk = first([ - [ee1, 'close', 'end', 'error'], - [ee2, 'error'] -], function (err, ee, event, args) { - // listener invoked -}) - -// cancel and clean up -thunk.cancel() -``` - -[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square -[npm-url]: https://npmjs.org/package/ee-first -[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square -[github-url]: https://github.com/jonathanong/ee-first/tags -[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square -[travis-url]: https://travis-ci.org/jonathanong/ee-first -[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square -[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master -[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square -[license-url]: LICENSE.md -[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square -[downloads-url]: https://npmjs.org/package/ee-first -[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square -[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/node_modules/ee-first/index.js b/node_modules/ee-first/index.js deleted file mode 100644 index 501287c..0000000 --- a/node_modules/ee-first/index.js +++ /dev/null @@ -1,95 +0,0 @@ -/*! - * ee-first - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ - -'use strict' - -/** - * Module exports. - * @public - */ - -module.exports = first - -/** - * Get the first event in a set of event emitters and event pairs. - * - * @param {array} stuff - * @param {function} done - * @public - */ - -function first(stuff, done) { - if (!Array.isArray(stuff)) - throw new TypeError('arg must be an array of [ee, events...] arrays') - - var cleanups = [] - - for (var i = 0; i < stuff.length; i++) { - var arr = stuff[i] - - if (!Array.isArray(arr) || arr.length < 2) - throw new TypeError('each array member must be [ee, events...]') - - var ee = arr[0] - - for (var j = 1; j < arr.length; j++) { - var event = arr[j] - var fn = listener(event, callback) - - // listen to the event - ee.on(event, fn) - // push this listener to the list of cleanups - cleanups.push({ - ee: ee, - event: event, - fn: fn, - }) - } - } - - function callback() { - cleanup() - done.apply(null, arguments) - } - - function cleanup() { - var x - for (var i = 0; i < cleanups.length; i++) { - x = cleanups[i] - x.ee.removeListener(x.event, x.fn) - } - } - - function thunk(fn) { - done = fn - } - - thunk.cancel = cleanup - - return thunk -} - -/** - * Create the event listener. - * @private - */ - -function listener(event, done) { - return function onevent(arg1) { - var args = new Array(arguments.length) - var ee = this - var err = event === 'error' - ? arg1 - : null - - // copy args to prevent arguments escaping scope - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } - - done(err, ee, event, args) - } -} diff --git a/node_modules/ee-first/package.json b/node_modules/ee-first/package.json deleted file mode 100644 index 8d06001..0000000 --- a/node_modules/ee-first/package.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "_from": "ee-first@1.1.1", - "_id": "ee-first@1.1.1", - "_inBundle": false, - "_integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", - "_location": "/ee-first", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "ee-first@1.1.1", - "name": "ee-first", - "escapedName": "ee-first", - "rawSpec": "1.1.1", - "saveSpec": null, - "fetchSpec": "1.1.1" - }, - "_requiredBy": [ - "/on-finished" - ], - "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "_shasum": "590c61156b0ae2f4f0255732a158b266bc56b21d", - "_spec": "ee-first@1.1.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/on-finished", - "author": { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - }, - "bugs": { - "url": "https://github.com/jonathanong/ee-first/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - } - ], - "deprecated": false, - "description": "return the first event in a set of ee/event pairs", - "devDependencies": { - "istanbul": "0.3.9", - "mocha": "2.2.5" - }, - "files": [ - "index.js", - "LICENSE" - ], - "homepage": "https://github.com/jonathanong/ee-first#readme", - "license": "MIT", - "name": "ee-first", - "repository": { - "type": "git", - "url": "git+https://github.com/jonathanong/ee-first.git" - }, - "scripts": { - "test": "mocha --reporter spec --bail --check-leaks test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" - }, - "version": "1.1.1" -} diff --git a/node_modules/encodeurl/HISTORY.md b/node_modules/encodeurl/HISTORY.md deleted file mode 100644 index 41313b2..0000000 --- a/node_modules/encodeurl/HISTORY.md +++ /dev/null @@ -1,14 +0,0 @@ -1.0.2 / 2018-01-21 -================== - - * Fix encoding `%` as last character - -1.0.1 / 2016-06-09 -================== - - * Fix encoding unpaired surrogates at start/end of string - -1.0.0 / 2016-06-08 -================== - - * Initial release diff --git a/node_modules/encodeurl/LICENSE b/node_modules/encodeurl/LICENSE deleted file mode 100644 index 8812229..0000000 --- a/node_modules/encodeurl/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2016 Douglas Christopher Wilson - -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/encodeurl/README.md b/node_modules/encodeurl/README.md deleted file mode 100644 index 127c5a0..0000000 --- a/node_modules/encodeurl/README.md +++ /dev/null @@ -1,128 +0,0 @@ -# encodeurl - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Encode a URL to a percent-encoded form, excluding already-encoded sequences - -## Installation - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install encodeurl -``` - -## API - -```js -var encodeUrl = require('encodeurl') -``` - -### encodeUrl(url) - -Encode a URL to a percent-encoded form, excluding already-encoded sequences. - -This function will take an already-encoded URL and encode all the non-URL -code points (as UTF-8 byte sequences). This function will not encode the -"%" character unless it is not part of a valid sequence (`%20` will be -left as-is, but `%foo` will be encoded as `%25foo`). - -This encode is meant to be "safe" and does not throw errors. It will try as -hard as it can to properly encode the given URL, including replacing any raw, -unpaired surrogate pairs with the Unicode replacement character prior to -encoding. - -This function is _similar_ to the intrinsic function `encodeURI`, except it -will not encode the `%` character if that is part of a valid sequence, will -not encode `[` and `]` (for IPv6 hostnames) and will replace raw, unpaired -surrogate pairs with the Unicode replacement character (instead of throwing). - -## Examples - -### Encode a URL containing user-controled data - -```js -var encodeUrl = require('encodeurl') -var escapeHtml = require('escape-html') - -http.createServer(function onRequest (req, res) { - // get encoded form of inbound url - var url = encodeUrl(req.url) - - // create html message - var body = '

Location ' + escapeHtml(url) + ' not found

' - - // send a 404 - res.statusCode = 404 - res.setHeader('Content-Type', 'text/html; charset=UTF-8') - res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) - res.end(body, 'utf-8') -}) -``` - -### Encode a URL for use in a header field - -```js -var encodeUrl = require('encodeurl') -var escapeHtml = require('escape-html') -var url = require('url') - -http.createServer(function onRequest (req, res) { - // parse inbound url - var href = url.parse(req) - - // set new host for redirect - href.host = 'localhost' - href.protocol = 'https:' - href.slashes = true - - // create location header - var location = encodeUrl(url.format(href)) - - // create html message - var body = '

Redirecting to new site: ' + escapeHtml(location) + '

' - - // send a 301 - res.statusCode = 301 - res.setHeader('Content-Type', 'text/html; charset=UTF-8') - res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) - res.setHeader('Location', location) - res.end(body, 'utf-8') -}) -``` - -## Testing - -```sh -$ npm test -$ npm run lint -``` - -## References - -- [RFC 3986: Uniform Resource Identifier (URI): Generic Syntax][rfc-3986] -- [WHATWG URL Living Standard][whatwg-url] - -[rfc-3986]: https://tools.ietf.org/html/rfc3986 -[whatwg-url]: https://url.spec.whatwg.org/ - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/encodeurl.svg -[npm-url]: https://npmjs.org/package/encodeurl -[node-version-image]: https://img.shields.io/node/v/encodeurl.svg -[node-version-url]: https://nodejs.org/en/download -[travis-image]: https://img.shields.io/travis/pillarjs/encodeurl.svg -[travis-url]: https://travis-ci.org/pillarjs/encodeurl -[coveralls-image]: https://img.shields.io/coveralls/pillarjs/encodeurl.svg -[coveralls-url]: https://coveralls.io/r/pillarjs/encodeurl?branch=master -[downloads-image]: https://img.shields.io/npm/dm/encodeurl.svg -[downloads-url]: https://npmjs.org/package/encodeurl diff --git a/node_modules/encodeurl/index.js b/node_modules/encodeurl/index.js deleted file mode 100644 index fc4906c..0000000 --- a/node_modules/encodeurl/index.js +++ /dev/null @@ -1,60 +0,0 @@ -/*! - * encodeurl - * Copyright(c) 2016 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module exports. - * @public - */ - -module.exports = encodeUrl - -/** - * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") - * and including invalid escape sequences. - * @private - */ - -var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g - -/** - * RegExp to match unmatched surrogate pair. - * @private - */ - -var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g - -/** - * String to replace unmatched surrogate pair with. - * @private - */ - -var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' - -/** - * Encode a URL to a percent-encoded form, excluding already-encoded sequences. - * - * This function will take an already-encoded URL and encode all the non-URL - * code points. This function will not encode the "%" character unless it is - * not part of a valid sequence (`%20` will be left as-is, but `%foo` will - * be encoded as `%25foo`). - * - * This encode is meant to be "safe" and does not throw errors. It will try as - * hard as it can to properly encode the given URL, including replacing any raw, - * unpaired surrogate pairs with the Unicode replacement character prior to - * encoding. - * - * @param {string} url - * @return {string} - * @public - */ - -function encodeUrl (url) { - return String(url) - .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) - .replace(ENCODE_CHARS_REGEXP, encodeURI) -} diff --git a/node_modules/encodeurl/package.json b/node_modules/encodeurl/package.json deleted file mode 100644 index 6264770..0000000 --- a/node_modules/encodeurl/package.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "_from": "encodeurl@~1.0.2", - "_id": "encodeurl@1.0.2", - "_inBundle": false, - "_integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", - "_location": "/encodeurl", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "encodeurl@~1.0.2", - "name": "encodeurl", - "escapedName": "encodeurl", - "rawSpec": "~1.0.2", - "saveSpec": null, - "fetchSpec": "~1.0.2" - }, - "_requiredBy": [ - "/express", - "/finalhandler", - "/send", - "/serve-static" - ], - "_resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "_shasum": "ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59", - "_spec": "encodeurl@~1.0.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "bugs": { - "url": "https://github.com/pillarjs/encodeurl/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - } - ], - "deprecated": false, - "description": "Encode a URL to a percent-encoded form, excluding already-encoded sequences", - "devDependencies": { - "eslint": "3.19.0", - "eslint-config-standard": "10.2.1", - "eslint-plugin-import": "2.8.0", - "eslint-plugin-node": "5.2.1", - "eslint-plugin-promise": "3.6.0", - "eslint-plugin-standard": "3.0.1", - "istanbul": "0.4.5", - "mocha": "2.5.3" - }, - "engines": { - "node": ">= 0.8" - }, - "files": [ - "LICENSE", - "HISTORY.md", - "README.md", - "index.js" - ], - "homepage": "https://github.com/pillarjs/encodeurl#readme", - "keywords": [ - "encode", - "encodeurl", - "url" - ], - "license": "MIT", - "name": "encodeurl", - "repository": { - "type": "git", - "url": "git+https://github.com/pillarjs/encodeurl.git" - }, - "scripts": { - "lint": "eslint .", - "test": "mocha --reporter spec --bail --check-leaks test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" - }, - "version": "1.0.2" -} diff --git a/node_modules/end-of-stream/LICENSE b/node_modules/end-of-stream/LICENSE deleted file mode 100644 index 757562e..0000000 --- a/node_modules/end-of-stream/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Mathias Buus - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/end-of-stream/README.md b/node_modules/end-of-stream/README.md deleted file mode 100644 index 857b14b..0000000 --- a/node_modules/end-of-stream/README.md +++ /dev/null @@ -1,54 +0,0 @@ -# end-of-stream - -A node module that calls a callback when a readable/writable/duplex stream has completed or failed. - - npm install end-of-stream - -[![Build status](https://travis-ci.org/mafintosh/end-of-stream.svg?branch=master)](https://travis-ci.org/mafintosh/end-of-stream) - -## Usage - -Simply pass a stream and a callback to the `eos`. -Both legacy streams, streams2 and stream3 are supported. - -``` js -var eos = require('end-of-stream'); - -eos(readableStream, function(err) { - // this will be set to the stream instance - if (err) return console.log('stream had an error or closed early'); - console.log('stream has ended', this === readableStream); -}); - -eos(writableStream, function(err) { - if (err) return console.log('stream had an error or closed early'); - console.log('stream has finished', this === writableStream); -}); - -eos(duplexStream, function(err) { - if (err) return console.log('stream had an error or closed early'); - console.log('stream has ended and finished', this === duplexStream); -}); - -eos(duplexStream, {readable:false}, function(err) { - if (err) return console.log('stream had an error or closed early'); - console.log('stream has finished but might still be readable'); -}); - -eos(duplexStream, {writable:false}, function(err) { - if (err) return console.log('stream had an error or closed early'); - console.log('stream has ended but might still be writable'); -}); - -eos(readableStream, {error:false}, function(err) { - // do not treat emit('error', err) as a end-of-stream -}); -``` - -## License - -MIT - -## Related - -`end-of-stream` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. diff --git a/node_modules/end-of-stream/index.js b/node_modules/end-of-stream/index.js deleted file mode 100644 index c77f0d5..0000000 --- a/node_modules/end-of-stream/index.js +++ /dev/null @@ -1,94 +0,0 @@ -var once = require('once'); - -var noop = function() {}; - -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; - -var isChildProcess = function(stream) { - return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 -}; - -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - - callback = once(callback || noop); - - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); - var cancelled = false; - - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; - - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream); - }; - - var onend = function() { - readable = false; - if (!writable) callback.call(stream); - }; - - var onexit = function(exitCode) { - callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); - }; - - var onerror = function(err) { - callback.call(stream, err); - }; - - var onclose = function() { - process.nextTick(onclosenexttick); - }; - - var onclosenexttick = function() { - if (cancelled) return; - if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); - }; - - var onrequest = function() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - if (isChildProcess(stream)) stream.on('exit', onexit); - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - - return function() { - cancelled = true; - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('exit', onexit); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -}; - -module.exports = eos; diff --git a/node_modules/end-of-stream/package.json b/node_modules/end-of-stream/package.json deleted file mode 100644 index 69aa964..0000000 --- a/node_modules/end-of-stream/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "_from": "end-of-stream@^1.1.0", - "_id": "end-of-stream@1.4.4", - "_inBundle": false, - "_integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", - "_location": "/end-of-stream", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "end-of-stream@^1.1.0", - "name": "end-of-stream", - "escapedName": "end-of-stream", - "rawSpec": "^1.1.0", - "saveSpec": null, - "fetchSpec": "^1.1.0" - }, - "_requiredBy": [ - "/pump", - "/tar-stream" - ], - "_resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", - "_shasum": "5ae64a5f45057baf3626ec14da0ca5e4b2431eb0", - "_spec": "end-of-stream@^1.1.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/pump", - "author": { - "name": "Mathias Buus", - "email": "mathiasbuus@gmail.com" - }, - "bugs": { - "url": "https://github.com/mafintosh/end-of-stream/issues" - }, - "bundleDependencies": false, - "dependencies": { - "once": "^1.4.0" - }, - "deprecated": false, - "description": "Call a callback when a readable/writable/duplex stream has completed or failed.", - "devDependencies": { - "tape": "^4.11.0" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/mafintosh/end-of-stream", - "keywords": [ - "stream", - "streams", - "callback", - "finish", - "close", - "end", - "wait" - ], - "license": "MIT", - "main": "index.js", - "name": "end-of-stream", - "repository": { - "type": "git", - "url": "git://github.com/mafintosh/end-of-stream.git" - }, - "scripts": { - "test": "node test.js" - }, - "version": "1.4.4" -} diff --git a/node_modules/es-abstract/.editorconfig b/node_modules/es-abstract/.editorconfig deleted file mode 100644 index eaa2141..0000000 --- a/node_modules/es-abstract/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -root = true - -[*] -indent_style = tab; -insert_final_newline = true; -quote_type = auto; -space_after_anonymous_functions = true; -space_after_control_statements = true; -spaces_around_operators = true; -trim_trailing_whitespace = true; -spaces_in_brackets = false; -end_of_line = lf; - diff --git a/node_modules/es-abstract/.eslintignore b/node_modules/es-abstract/.eslintignore deleted file mode 100644 index 4ebc8ae..0000000 --- a/node_modules/es-abstract/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -coverage diff --git a/node_modules/es-abstract/.eslintrc b/node_modules/es-abstract/.eslintrc deleted file mode 100644 index 1bac5b7..0000000 --- a/node_modules/es-abstract/.eslintrc +++ /dev/null @@ -1,66 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "env": { - "es6": true, - }, - - "rules": { - "array-bracket-newline": 0, - "array-element-newline": 0, - "complexity": 0, - "eqeqeq": [2, "allow-null"], - "func-name-matching": 0, - "id-length": [2, { "min": 1, "max": 40 }], - "max-params": [2, 4], - "max-statements-per-line": [2, { "max": 2 }], - "multiline-comment-style": 0, - "no-magic-numbers": 0, - "new-cap": 0, - "no-extra-parens": 1, - "operator-linebreak": [2, "before"], - "sort-keys": 0, - }, - - "overrides": [ - { - "files": "operations/*", - "rules": { - "max-lines": 0, - }, - }, - { - "files": "operations/*.js", - "parserOptions": { - "ecmaVersion": 2020, - }, - "rules": { - "no-console": 0, - "no-multi-str": 0, - }, - }, - { - "files": "operations/getOps.js", - "rules": { - "no-console": 0, - "no-process-exit": 0, - }, - }, - { - "files": "test/**", - "rules": { - "id-length": 0, - "max-lines": 0, - "max-lines-per-function": 0, - "max-statements-per-line": [2, { "max": 3 }], - "max-statements": 0, - "no-implicit-coercion": 0, - "no-invalid-this": 1, - "object-curly-newline": 0, - "prefer-regex-literals": 0, - }, - }, - ], -} diff --git a/node_modules/es-abstract/.gitattributes b/node_modules/es-abstract/.gitattributes deleted file mode 100644 index 9a65c9d..0000000 --- a/node_modules/es-abstract/.gitattributes +++ /dev/null @@ -1,472 +0,0 @@ -2015/AbstractRelationalComparison.js spackled -2015/DateFromTime.js spackled -2015/Day.js spackled -2015/DayFromYear.js spackled -2015/DayWithinYear.js spackled -2015/DaysInYear.js spackled -2015/HourFromTime.js spackled -2015/InLeapYear.js spackled -2015/IsCallable.js spackled -2015/IsPropertyDescriptor.js spackled -2015/MakeDate.js spackled -2015/MakeDay.js spackled -2015/MakeTime.js spackled -2015/MinFromTime.js spackled -2015/MonthFromTime.js spackled -2015/SameValue.js spackled -2015/SecFromTime.js spackled -2015/StrictEqualityComparison.js spackled -2015/TimeClip.js spackled -2015/TimeFromYear.js spackled -2015/TimeWithinDay.js spackled -2015/ToBoolean.js spackled -2015/ToInt32.js spackled -2015/ToPropertyDescriptor.js spackled -2015/ToUint16.js spackled -2015/ToUint32.js spackled -2015/WeekDay.js spackled -2015/YearFromTime.js spackled -2015/modulo.js spackled -2015/msFromTime.js spackled -2016/AbstractEqualityComparison.js spackled -2016/AbstractRelationalComparison.js spackled -2016/AdvanceStringIndex.js spackled -2016/ArrayCreate.js spackled -2016/ArraySetLength.js spackled -2016/ArraySpeciesCreate.js spackled -2016/Call.js spackled -2016/CanonicalNumericIndexString.js spackled -2016/CompletePropertyDescriptor.js spackled -2016/CreateDataProperty.js spackled -2016/CreateDataPropertyOrThrow.js spackled -2016/CreateHTML.js spackled -2016/CreateIterResultObject.js spackled -2016/CreateListFromArrayLike.js spackled -2016/CreateMethodProperty.js spackled -2016/DateFromTime.js spackled -2016/Day.js spackled -2016/DayFromYear.js spackled -2016/DayWithinYear.js spackled -2016/DaysInYear.js spackled -2016/DefinePropertyOrThrow.js spackled -2016/DeletePropertyOrThrow.js spackled -2016/EnumerableOwnNames.js spackled -2016/FromPropertyDescriptor.js spackled -2016/Get.js spackled -2016/GetIterator.js spackled -2016/GetMethod.js spackled -2016/GetOwnPropertyKeys.js spackled -2016/GetPrototypeFromConstructor.js spackled -2016/GetSubstitution.js spackled -2016/GetV.js spackled -2016/HasOwnProperty.js spackled -2016/HasProperty.js spackled -2016/HourFromTime.js spackled -2016/InLeapYear.js spackled -2016/InstanceofOperator.js spackled -2016/Invoke.js spackled -2016/IsAccessorDescriptor.js spackled -2016/IsArray.js spackled -2016/IsCallable.js spackled -2016/IsConcatSpreadable.js spackled -2016/IsConstructor.js spackled -2016/IsDataDescriptor.js spackled -2016/IsExtensible.js spackled -2016/IsGenericDescriptor.js spackled -2016/IsInteger.js spackled -2016/IsPromise.js spackled -2016/IsPropertyDescriptor.js spackled -2016/IsPropertyKey.js spackled -2016/IsRegExp.js spackled -2016/IteratorClose.js spackled -2016/IteratorComplete.js spackled -2016/IteratorNext.js spackled -2016/IteratorStep.js spackled -2016/IteratorValue.js spackled -2016/MakeDate.js spackled -2016/MakeDay.js spackled -2016/MakeTime.js spackled -2016/MinFromTime.js spackled -2016/MonthFromTime.js spackled -2016/ObjectCreate.js spackled -2016/OrdinaryDefineOwnProperty.js spackled -2016/OrdinaryGetOwnProperty.js spackled -2016/OrdinaryHasInstance.js spackled -2016/OrdinaryHasProperty.js spackled -2016/RegExpExec.js spackled -2016/RequireObjectCoercible.js spackled -2016/SameValue.js spackled -2016/SameValueZero.js spackled -2016/SecFromTime.js spackled -2016/Set.js spackled -2016/SetFunctionName.js spackled -2016/SetIntegrityLevel.js spackled -2016/SpeciesConstructor.js spackled -2016/StrictEqualityComparison.js spackled -2016/SymbolDescriptiveString.js spackled -2016/TestIntegrityLevel.js spackled -2016/TimeClip.js spackled -2016/TimeFromYear.js spackled -2016/TimeWithinDay.js spackled -2016/ToBoolean.js spackled -2016/ToDateString.js spackled -2016/ToInt16.js spackled -2016/ToInt32.js spackled -2016/ToInt8.js spackled -2016/ToInteger.js spackled -2016/ToLength.js spackled -2016/ToNumber.js spackled -2016/ToObject.js spackled -2016/ToPrimitive.js spackled -2016/ToPropertyDescriptor.js spackled -2016/ToPropertyKey.js spackled -2016/ToString.js spackled -2016/ToUint16.js spackled -2016/ToUint32.js spackled -2016/ToUint8.js spackled -2016/ToUint8Clamp.js spackled -2016/Type.js spackled -2016/ValidateAndApplyPropertyDescriptor.js spackled -2016/WeekDay.js spackled -2016/YearFromTime.js spackled -2016/modulo.js spackled -2016/msFromTime.js spackled -2016/thisBooleanValue.js spackled -2016/thisNumberValue.js spackled -2016/thisStringValue.js spackled -2016/thisTimeValue.js spackled -2017/AbstractEqualityComparison.js spackled -2017/AbstractRelationalComparison.js spackled -2017/AdvanceStringIndex.js spackled -2017/ArrayCreate.js spackled -2017/ArraySetLength.js spackled -2017/ArraySpeciesCreate.js spackled -2017/Call.js spackled -2017/CanonicalNumericIndexString.js spackled -2017/CompletePropertyDescriptor.js spackled -2017/CreateDataProperty.js spackled -2017/CreateDataPropertyOrThrow.js spackled -2017/CreateHTML.js spackled -2017/CreateIterResultObject.js spackled -2017/CreateListFromArrayLike.js spackled -2017/CreateMethodProperty.js spackled -2017/DateFromTime.js spackled -2017/Day.js spackled -2017/DayFromYear.js spackled -2017/DayWithinYear.js spackled -2017/DaysInYear.js spackled -2017/DefinePropertyOrThrow.js spackled -2017/DeletePropertyOrThrow.js spackled -2017/FromPropertyDescriptor.js spackled -2017/Get.js spackled -2017/GetIterator.js spackled -2017/GetMethod.js spackled -2017/GetOwnPropertyKeys.js spackled -2017/GetPrototypeFromConstructor.js spackled -2017/GetSubstitution.js spackled -2017/GetV.js spackled -2017/HasOwnProperty.js spackled -2017/HasProperty.js spackled -2017/HourFromTime.js spackled -2017/InLeapYear.js spackled -2017/InstanceofOperator.js spackled -2017/Invoke.js spackled -2017/IsAccessorDescriptor.js spackled -2017/IsArray.js spackled -2017/IsCallable.js spackled -2017/IsConcatSpreadable.js spackled -2017/IsConstructor.js spackled -2017/IsDataDescriptor.js spackled -2017/IsExtensible.js spackled -2017/IsGenericDescriptor.js spackled -2017/IsInteger.js spackled -2017/IsPromise.js spackled -2017/IsPropertyDescriptor.js spackled -2017/IsPropertyKey.js spackled -2017/IsRegExp.js spackled -2017/IteratorClose.js spackled -2017/IteratorComplete.js spackled -2017/IteratorNext.js spackled -2017/IteratorStep.js spackled -2017/IteratorValue.js spackled -2017/MakeDate.js spackled -2017/MakeDay.js spackled -2017/MakeTime.js spackled -2017/MinFromTime.js spackled -2017/MonthFromTime.js spackled -2017/ObjectCreate.js spackled -2017/OrdinaryDefineOwnProperty.js spackled -2017/OrdinaryGetOwnProperty.js spackled -2017/OrdinaryGetPrototypeOf.js spackled -2017/OrdinaryHasInstance.js spackled -2017/OrdinaryHasProperty.js spackled -2017/OrdinarySetPrototypeOf.js spackled -2017/RegExpExec.js spackled -2017/RequireObjectCoercible.js spackled -2017/SameValue.js spackled -2017/SameValueNonNumber.js spackled -2017/SameValueZero.js spackled -2017/SecFromTime.js spackled -2017/Set.js spackled -2017/SetFunctionName.js spackled -2017/SetIntegrityLevel.js spackled -2017/SpeciesConstructor.js spackled -2017/StrictEqualityComparison.js spackled -2017/SymbolDescriptiveString.js spackled -2017/TestIntegrityLevel.js spackled -2017/TimeClip.js spackled -2017/TimeFromYear.js spackled -2017/TimeWithinDay.js spackled -2017/ToBoolean.js spackled -2017/ToDateString.js spackled -2017/ToInt16.js spackled -2017/ToInt32.js spackled -2017/ToInt8.js spackled -2017/ToInteger.js spackled -2017/ToLength.js spackled -2017/ToNumber.js spackled -2017/ToObject.js spackled -2017/ToPrimitive.js spackled -2017/ToPropertyDescriptor.js spackled -2017/ToPropertyKey.js spackled -2017/ToString.js spackled -2017/ToUint16.js spackled -2017/ToUint32.js spackled -2017/ToUint8.js spackled -2017/ToUint8Clamp.js spackled -2017/Type.js spackled -2017/ValidateAndApplyPropertyDescriptor.js spackled -2017/WeekDay.js spackled -2017/YearFromTime.js spackled -2017/modulo.js spackled -2017/msFromTime.js spackled -2017/thisBooleanValue.js spackled -2017/thisNumberValue.js spackled -2017/thisStringValue.js spackled -2017/thisTimeValue.js spackled -2018/AbstractEqualityComparison.js spackled -2018/AbstractRelationalComparison.js spackled -2018/AdvanceStringIndex.js spackled -2018/ArrayCreate.js spackled -2018/ArraySetLength.js spackled -2018/ArraySpeciesCreate.js spackled -2018/Call.js spackled -2018/CanonicalNumericIndexString.js spackled -2018/CompletePropertyDescriptor.js spackled -2018/CreateDataProperty.js spackled -2018/CreateDataPropertyOrThrow.js spackled -2018/CreateHTML.js spackled -2018/CreateIterResultObject.js spackled -2018/CreateListFromArrayLike.js spackled -2018/CreateMethodProperty.js spackled -2018/DateFromTime.js spackled -2018/Day.js spackled -2018/DayFromYear.js spackled -2018/DayWithinYear.js spackled -2018/DaysInYear.js spackled -2018/DefinePropertyOrThrow.js spackled -2018/DeletePropertyOrThrow.js spackled -2018/FromPropertyDescriptor.js spackled -2018/Get.js spackled -2018/GetIterator.js spackled -2018/GetMethod.js spackled -2018/GetOwnPropertyKeys.js spackled -2018/GetPrototypeFromConstructor.js spackled -2018/GetV.js spackled -2018/HasOwnProperty.js spackled -2018/HasProperty.js spackled -2018/HourFromTime.js spackled -2018/InLeapYear.js spackled -2018/InstanceofOperator.js spackled -2018/Invoke.js spackled -2018/IsAccessorDescriptor.js spackled -2018/IsArray.js spackled -2018/IsCallable.js spackled -2018/IsConcatSpreadable.js spackled -2018/IsConstructor.js spackled -2018/IsDataDescriptor.js spackled -2018/IsExtensible.js spackled -2018/IsGenericDescriptor.js spackled -2018/IsInteger.js spackled -2018/IsPromise.js spackled -2018/IsPropertyKey.js spackled -2018/IsRegExp.js spackled -2018/IterableToList.js spackled -2018/IteratorClose.js spackled -2018/IteratorComplete.js spackled -2018/IteratorNext.js spackled -2018/IteratorStep.js spackled -2018/IteratorValue.js spackled -2018/MakeDate.js spackled -2018/MakeDay.js spackled -2018/MakeTime.js spackled -2018/MinFromTime.js spackled -2018/MonthFromTime.js spackled -2018/ObjectCreate.js spackled -2018/OrdinaryDefineOwnProperty.js spackled -2018/OrdinaryGetOwnProperty.js spackled -2018/OrdinaryGetPrototypeOf.js spackled -2018/OrdinaryHasInstance.js spackled -2018/OrdinaryHasProperty.js spackled -2018/OrdinarySetPrototypeOf.js spackled -2018/RegExpExec.js spackled -2018/RequireObjectCoercible.js spackled -2018/SameValue.js spackled -2018/SameValueNonNumber.js spackled -2018/SameValueZero.js spackled -2018/SecFromTime.js spackled -2018/Set.js spackled -2018/SetFunctionName.js spackled -2018/SetIntegrityLevel.js spackled -2018/SpeciesConstructor.js spackled -2018/StrictEqualityComparison.js spackled -2018/SymbolDescriptiveString.js spackled -2018/TestIntegrityLevel.js spackled -2018/TimeClip.js spackled -2018/TimeFromYear.js spackled -2018/TimeWithinDay.js spackled -2018/ToBoolean.js spackled -2018/ToDateString.js spackled -2018/ToIndex.js spackled -2018/ToInt16.js spackled -2018/ToInt32.js spackled -2018/ToInt8.js spackled -2018/ToInteger.js spackled -2018/ToLength.js spackled -2018/ToNumber.js spackled -2018/ToObject.js spackled -2018/ToPrimitive.js spackled -2018/ToPropertyDescriptor.js spackled -2018/ToPropertyKey.js spackled -2018/ToString.js spackled -2018/ToUint16.js spackled -2018/ToUint32.js spackled -2018/ToUint8.js spackled -2018/ToUint8Clamp.js spackled -2018/Type.js spackled -2018/ValidateAndApplyPropertyDescriptor.js spackled -2018/WeekDay.js spackled -2018/YearFromTime.js spackled -2018/modulo.js spackled -2018/msFromTime.js spackled -2018/thisBooleanValue.js spackled -2018/thisNumberValue.js spackled -2018/thisStringValue.js spackled -2018/thisTimeValue.js spackled -2019/AbstractEqualityComparison.js spackled -2019/AbstractRelationalComparison.js spackled -2019/AdvanceStringIndex.js spackled -2019/ArrayCreate.js spackled -2019/ArraySetLength.js spackled -2019/ArraySpeciesCreate.js spackled -2019/Call.js spackled -2019/CanonicalNumericIndexString.js spackled -2019/CompletePropertyDescriptor.js spackled -2019/CopyDataProperties.js spackled -2019/CreateDataProperty.js spackled -2019/CreateDataPropertyOrThrow.js spackled -2019/CreateHTML.js spackled -2019/CreateIterResultObject.js spackled -2019/CreateListFromArrayLike.js spackled -2019/CreateMethodProperty.js spackled -2019/DateFromTime.js spackled -2019/DateString.js spackled -2019/Day.js spackled -2019/DayFromYear.js spackled -2019/DayWithinYear.js spackled -2019/DaysInYear.js spackled -2019/DefinePropertyOrThrow.js spackled -2019/DeletePropertyOrThrow.js spackled -2019/EnumerableOwnPropertyNames.js spackled -2019/FromPropertyDescriptor.js spackled -2019/Get.js spackled -2019/GetIterator.js spackled -2019/GetMethod.js spackled -2019/GetOwnPropertyKeys.js spackled -2019/GetPrototypeFromConstructor.js spackled -2019/GetSubstitution.js spackled -2019/GetV.js spackled -2019/HasOwnProperty.js spackled -2019/HasProperty.js spackled -2019/HourFromTime.js spackled -2019/InLeapYear.js spackled -2019/InstanceofOperator.js spackled -2019/Invoke.js spackled -2019/IsAccessorDescriptor.js spackled -2019/IsArray.js spackled -2019/IsCallable.js spackled -2019/IsConcatSpreadable.js spackled -2019/IsConstructor.js spackled -2019/IsDataDescriptor.js spackled -2019/IsExtensible.js spackled -2019/IsGenericDescriptor.js spackled -2019/IsInteger.js spackled -2019/IsPromise.js spackled -2019/IsPropertyKey.js spackled -2019/IsRegExp.js spackled -2019/IsStringPrefix.js spackled -2019/IterableToList.js spackled -2019/IteratorClose.js spackled -2019/IteratorComplete.js spackled -2019/IteratorNext.js spackled -2019/IteratorStep.js spackled -2019/IteratorValue.js spackled -2019/MakeDate.js spackled -2019/MakeDay.js spackled -2019/MakeTime.js spackled -2019/MinFromTime.js spackled -2019/MonthFromTime.js spackled -2019/NumberToString.js spackled -2019/ObjectCreate.js spackled -2019/OrdinaryDefineOwnProperty.js spackled -2019/OrdinaryGetOwnProperty.js spackled -2019/OrdinaryGetPrototypeOf.js spackled -2019/OrdinaryHasInstance.js spackled -2019/OrdinaryHasProperty.js spackled -2019/OrdinarySetPrototypeOf.js spackled -2019/PromiseResolve.js spackled -2019/RegExpExec.js spackled -2019/RequireObjectCoercible.js spackled -2019/SameValue.js spackled -2019/SameValueNonNumber.js spackled -2019/SameValueZero.js spackled -2019/SecFromTime.js spackled -2019/Set.js spackled -2019/SetFunctionName.js spackled -2019/SetIntegrityLevel.js spackled -2019/SpeciesConstructor.js spackled -2019/StrictEqualityComparison.js spackled -2019/SymbolDescriptiveString.js spackled -2019/TestIntegrityLevel.js spackled -2019/TimeClip.js spackled -2019/TimeFromYear.js spackled -2019/TimeString.js spackled -2019/TimeWithinDay.js spackled -2019/ToBoolean.js spackled -2019/ToDateString.js spackled -2019/ToIndex.js spackled -2019/ToInt16.js spackled -2019/ToInt32.js spackled -2019/ToInt8.js spackled -2019/ToInteger.js spackled -2019/ToLength.js spackled -2019/ToNumber.js spackled -2019/ToObject.js spackled -2019/ToPrimitive.js spackled -2019/ToPropertyDescriptor.js spackled -2019/ToPropertyKey.js spackled -2019/ToString.js spackled -2019/ToUint16.js spackled -2019/ToUint32.js spackled -2019/ToUint8.js spackled -2019/ToUint8Clamp.js spackled -2019/Type.js spackled -2019/ValidateAndApplyPropertyDescriptor.js spackled -2019/WeekDay.js spackled -2019/YearFromTime.js spackled -2019/modulo.js spackled -2019/msFromTime.js spackled -2019/thisBooleanValue.js spackled -2019/thisNumberValue.js spackled -2019/thisStringValue.js spackled -2019/thisSymbolValue.js spackled \ No newline at end of file diff --git a/node_modules/es-abstract/.github/FUNDING.yml b/node_modules/es-abstract/.github/FUNDING.yml deleted file mode 100644 index beeb7a2..0000000 --- a/node_modules/es-abstract/.github/FUNDING.yml +++ /dev/null @@ -1,12 +0,0 @@ -# These are supported funding model platforms - -github: [ljharb] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: npm/es-abstract -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/es-abstract/.github/workflows/rebase.yml b/node_modules/es-abstract/.github/workflows/rebase.yml deleted file mode 100644 index 436cb79..0000000 --- a/node_modules/es-abstract/.github/workflows/rebase.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Automatic Rebase - -on: [pull_request] - -jobs: - _: - name: "Automatic Rebase" - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v1 - - uses: ljharb/rebase@master - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/node_modules/es-abstract/.nycrc b/node_modules/es-abstract/.nycrc deleted file mode 100644 index d316b4d..0000000 --- a/node_modules/es-abstract/.nycrc +++ /dev/null @@ -1,14 +0,0 @@ -{ - "all": true, - "check-coverage": false, - "reporter": ["text-summary", "text", "html", "json"], - "lines": 86, - "statements": 85.93, - "functions": 82.43, - "branches": 76.06, - "exclude": [ - "coverage", - "operations", - "test" - ] -} diff --git a/node_modules/es-abstract/.travis.yml b/node_modules/es-abstract/.travis.yml deleted file mode 100644 index 5c34024..0000000 --- a/node_modules/es-abstract/.travis.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: ~> 1.0 -language: node_js -os: - - linux -cache: - directories: - - "$HOME/.npm" - - "$(nvm cache dir)" - - "$(nvm_version_path $(nvm_version_remote 0.4))" - - "$(nvm_version_path $(nvm_version_remote 0.6))" - - "$(nvm_version_path $(nvm_version_remote 0.10))" -import: - - ljharb/travis-ci:node/all.yml - - ljharb/travis-ci:node/pretest.yml - - ljharb/travis-ci:node/posttest.yml -script: - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage && bash <(curl -s https://codecov.io/bash) -f coverage/*.json; fi' -matrix: - include: - - node_js: "8" - env: COVERAGE=true - - node_js: "4" - env: COVERAGE=true - - node_js: "0.12" - env: COVERAGE=true - - node_js: "0.8" - env: COVERAGE=true - exclude: - - node_js: "0.12" - env: TEST=true - - node_js: "0.8" - env: TEST=true diff --git a/node_modules/es-abstract/2015/AbstractEqualityComparison.js b/node_modules/es-abstract/2015/AbstractEqualityComparison.js deleted file mode 100644 index 40b3909..0000000 --- a/node_modules/es-abstract/2015/AbstractEqualityComparison.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); -var ToPrimitive = require('./ToPrimitive'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison - -module.exports = function AbstractEqualityComparison(x, y) { - var xType = Type(x); - var yType = Type(y); - if (xType === yType) { - return x === y; // ES6+ specified this shortcut anyways. - } - if (x == null && y == null) { - return true; - } - if (xType === 'Number' && yType === 'String') { - return AbstractEqualityComparison(x, ToNumber(y)); - } - if (xType === 'String' && yType === 'Number') { - return AbstractEqualityComparison(ToNumber(x), y); - } - if (xType === 'Boolean') { - return AbstractEqualityComparison(ToNumber(x), y); - } - if (yType === 'Boolean') { - return AbstractEqualityComparison(x, ToNumber(y)); - } - if ((xType === 'String' || xType === 'Number' || xType === 'Symbol') && yType === 'Object') { - return AbstractEqualityComparison(x, ToPrimitive(y)); - } - if (xType === 'Object' && (yType === 'String' || yType === 'Number' || yType === 'Symbol')) { - return AbstractEqualityComparison(ToPrimitive(x), y); - } - return false; -}; diff --git a/node_modules/es-abstract/2015/AbstractRelationalComparison.js b/node_modules/es-abstract/2015/AbstractRelationalComparison.js deleted file mode 100644 index bc7ca83..0000000 --- a/node_modules/es-abstract/2015/AbstractRelationalComparison.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Number = GetIntrinsic('%Number%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var isPrefixOf = require('../helpers/isPrefixOf'); - -var ToNumber = require('./ToNumber'); -var ToPrimitive = require('./ToPrimitive'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5 - -// eslint-disable-next-line max-statements -module.exports = function AbstractRelationalComparison(x, y, LeftFirst) { - if (Type(LeftFirst) !== 'Boolean') { - throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean'); - } - var px; - var py; - if (LeftFirst) { - px = ToPrimitive(x, $Number); - py = ToPrimitive(y, $Number); - } else { - py = ToPrimitive(y, $Number); - px = ToPrimitive(x, $Number); - } - var bothStrings = Type(px) === 'String' && Type(py) === 'String'; - if (!bothStrings) { - var nx = ToNumber(px); - var ny = ToNumber(py); - if ($isNaN(nx) || $isNaN(ny)) { - return undefined; - } - if ($isFinite(nx) && $isFinite(ny) && nx === ny) { - return false; - } - if (nx === 0 && ny === 0) { - return false; - } - if (nx === Infinity) { - return false; - } - if (ny === Infinity) { - return true; - } - if (ny === -Infinity) { - return false; - } - if (nx === -Infinity) { - return true; - } - return nx < ny; // by now, these are both nonzero, finite, and not equal - } - if (isPrefixOf(py, px)) { - return false; - } - if (isPrefixOf(px, py)) { - return true; - } - return px < py; // both strings, neither a prefix of the other. shortcut for steps c-f -}; diff --git a/node_modules/es-abstract/2015/AdvanceStringIndex.js b/node_modules/es-abstract/2015/AdvanceStringIndex.js deleted file mode 100644 index 666f578..0000000 --- a/node_modules/es-abstract/2015/AdvanceStringIndex.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var IsInteger = require('./IsInteger'); -var Type = require('./Type'); - -var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $charCodeAt = require('../helpers/callBound')('String.prototype.charCodeAt'); - -// https://ecma-international.org/ecma-262/6.0/#sec-advancestringindex - -module.exports = function AdvanceStringIndex(S, index, unicode) { - if (Type(S) !== 'String') { - throw new $TypeError('Assertion failed: `S` must be a String'); - } - if (!IsInteger(index) || index < 0 || index > MAX_SAFE_INTEGER) { - throw new $TypeError('Assertion failed: `length` must be an integer >= 0 and <= 2**53'); - } - if (Type(unicode) !== 'Boolean') { - throw new $TypeError('Assertion failed: `unicode` must be a Boolean'); - } - if (!unicode) { - return index + 1; - } - var length = S.length; - if ((index + 1) >= length) { - return index + 1; - } - - var first = $charCodeAt(S, index); - if (first < 0xD800 || first > 0xDBFF) { - return index + 1; - } - - var second = $charCodeAt(S, index + 1); - if (second < 0xDC00 || second > 0xDFFF) { - return index + 1; - } - - return index + 2; -}; diff --git a/node_modules/es-abstract/2015/ArrayCreate.js b/node_modules/es-abstract/2015/ArrayCreate.js deleted file mode 100644 index fc9a7cf..0000000 --- a/node_modules/es-abstract/2015/ArrayCreate.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $ArrayPrototype = GetIntrinsic('%Array.prototype%'); -var $RangeError = GetIntrinsic('%RangeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsInteger = require('./IsInteger'); - -var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1; - -var $setProto = GetIntrinsic('%Object.setPrototypeOf%', true) || ( - // eslint-disable-next-line no-proto, no-negated-condition - [].__proto__ !== $ArrayPrototype - ? null - : function (O, proto) { - O.__proto__ = proto; // eslint-disable-line no-proto, no-param-reassign - return O; - } -); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-arraycreate - -module.exports = function ArrayCreate(length) { - if (!IsInteger(length) || length < 0) { - throw new $TypeError('Assertion failed: `length` must be an integer Number >= 0'); - } - if (length > MAX_ARRAY_LENGTH) { - throw new $RangeError('length is greater than (2**32 - 1)'); - } - var proto = arguments.length > 1 ? arguments[1] : $ArrayPrototype; - var A = []; // steps 5 - 7, and 9 - if (proto !== $ArrayPrototype) { // step 8 - if (!$setProto) { - throw new $SyntaxError('ArrayCreate: a `proto` argument that is not `Array.prototype` is not supported in an environment that does not support setting the [[Prototype]]'); - } - $setProto(A, proto); - } - if (length !== 0) { // bypasses the need for step 2 - A.length = length; - } - /* step 10, the above as a shortcut for the below - OrdinaryDefineOwnProperty(A, 'length', { - '[[Configurable]]': false, - '[[Enumerable]]': false, - '[[Value]]': length, - '[[Writable]]': true - }); - */ - return A; -}; diff --git a/node_modules/es-abstract/2015/ArraySetLength.js b/node_modules/es-abstract/2015/ArraySetLength.js deleted file mode 100644 index c9134c6..0000000 --- a/node_modules/es-abstract/2015/ArraySetLength.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $RangeError = GetIntrinsic('%RangeError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var assign = require('object.assign'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var IsArray = require('./IsArray'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var OrdinaryDefineOwnProperty = require('./OrdinaryDefineOwnProperty'); -var OrdinaryGetOwnProperty = require('./OrdinaryGetOwnProperty'); -var ToNumber = require('./ToNumber'); -var ToString = require('./ToString'); -var ToUint32 = require('./ToUint32'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-arraysetlength - -// eslint-disable-next-line max-statements, max-lines-per-function -module.exports = function ArraySetLength(A, Desc) { - if (!IsArray(A)) { - throw new $TypeError('Assertion failed: A must be an Array'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (!('[[Value]]' in Desc)) { - return OrdinaryDefineOwnProperty(A, 'length', Desc); - } - var newLenDesc = assign({}, Desc); - var newLen = ToUint32(Desc['[[Value]]']); - var numberLen = ToNumber(Desc['[[Value]]']); - if (newLen !== numberLen) { - throw new $RangeError('Invalid array length'); - } - newLenDesc['[[Value]]'] = newLen; - var oldLenDesc = OrdinaryGetOwnProperty(A, 'length'); - if (!IsDataDescriptor(oldLenDesc)) { - throw new $TypeError('Assertion failed: an array had a non-data descriptor on `length`'); - } - var oldLen = oldLenDesc['[[Value]]']; - if (newLen >= oldLen) { - return OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - } - if (!oldLenDesc['[[Writable]]']) { - return false; - } - var newWritable; - if (!('[[Writable]]' in newLenDesc) || newLenDesc['[[Writable]]']) { - newWritable = true; - } else { - newWritable = false; - newLenDesc['[[Writable]]'] = true; - } - var succeeded = OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - if (!succeeded) { - return false; - } - while (newLen < oldLen) { - oldLen -= 1; - // eslint-disable-next-line no-param-reassign - var deleteSucceeded = delete A[ToString(oldLen)]; - if (!deleteSucceeded) { - newLenDesc['[[Value]]'] = oldLen + 1; - if (!newWritable) { - newLenDesc['[[Writable]]'] = false; - OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - return false; - } - } - } - if (!newWritable) { - return OrdinaryDefineOwnProperty(A, 'length', { '[[Writable]]': false }); - } - return true; -}; diff --git a/node_modules/es-abstract/2015/ArraySpeciesCreate.js b/node_modules/es-abstract/2015/ArraySpeciesCreate.js deleted file mode 100644 index 98b9b56..0000000 --- a/node_modules/es-abstract/2015/ArraySpeciesCreate.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Array = GetIntrinsic('%Array%'); -var $species = GetIntrinsic('%Symbol.species%', true); -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var IsConstructor = require('./IsConstructor'); -var IsInteger = require('./IsInteger'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-arrayspeciescreate - -module.exports = function ArraySpeciesCreate(originalArray, length) { - if (!IsInteger(length) || length < 0) { - throw new $TypeError('Assertion failed: length must be an integer >= 0'); - } - var len = length === 0 ? 0 : length; - var C; - var isArray = IsArray(originalArray); - if (isArray) { - C = Get(originalArray, 'constructor'); - // TODO: figure out how to make a cross-realm normal Array, a same-realm Array - // if (IsConstructor(C)) { - // if C is another realm's Array, C = undefined - // Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Array))) === null ? - // } - if ($species && Type(C) === 'Object') { - C = Get(C, $species); - if (C === null) { - C = void 0; - } - } - } - if (typeof C === 'undefined') { - return $Array(len); - } - if (!IsConstructor(C)) { - throw new $TypeError('C must be a constructor'); - } - return new C(len); // Construct(C, len); -}; - diff --git a/node_modules/es-abstract/2015/Call.js b/node_modules/es-abstract/2015/Call.js deleted file mode 100644 index f31960d..0000000 --- a/node_modules/es-abstract/2015/Call.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var inspect = require('object-inspect'); - -var IsCallable = require('./IsCallable'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-call - -module.exports = function Call(F, V) { - var args = arguments.length > 2 ? arguments[2] : []; - if (!IsCallable(F)) { - throw new $TypeError(inspect(F) + ' is not a function'); - } - return F.apply(V, args); -}; diff --git a/node_modules/es-abstract/2015/CanonicalNumericIndexString.js b/node_modules/es-abstract/2015/CanonicalNumericIndexString.js deleted file mode 100644 index 625f853..0000000 --- a/node_modules/es-abstract/2015/CanonicalNumericIndexString.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var SameValue = require('./SameValue'); -var ToNumber = require('./ToNumber'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-canonicalnumericindexstring - -module.exports = function CanonicalNumericIndexString(argument) { - if (Type(argument) !== 'String') { - throw new $TypeError('Assertion failed: `argument` must be a String'); - } - if (argument === '-0') { return -0; } - var n = ToNumber(argument); - if (SameValue(ToString(n), argument)) { return n; } - return void 0; -}; diff --git a/node_modules/es-abstract/2015/CompletePropertyDescriptor.js b/node_modules/es-abstract/2015/CompletePropertyDescriptor.js deleted file mode 100644 index 548bf41..0000000 --- a/node_modules/es-abstract/2015/CompletePropertyDescriptor.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsGenericDescriptor = require('./IsGenericDescriptor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-completepropertydescriptor - -module.exports = function CompletePropertyDescriptor(Desc) { - /* eslint no-param-reassign: 0 */ - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (IsGenericDescriptor(Desc) || IsDataDescriptor(Desc)) { - if (!has(Desc, '[[Value]]')) { - Desc['[[Value]]'] = void 0; - } - if (!has(Desc, '[[Writable]]')) { - Desc['[[Writable]]'] = false; - } - } else { - if (!has(Desc, '[[Get]]')) { - Desc['[[Get]]'] = void 0; - } - if (!has(Desc, '[[Set]]')) { - Desc['[[Set]]'] = void 0; - } - } - if (!has(Desc, '[[Enumerable]]')) { - Desc['[[Enumerable]]'] = false; - } - if (!has(Desc, '[[Configurable]]')) { - Desc['[[Configurable]]'] = false; - } - return Desc; -}; diff --git a/node_modules/es-abstract/2015/CreateDataProperty.js b/node_modules/es-abstract/2015/CreateDataProperty.js deleted file mode 100644 index 32a86ef..0000000 --- a/node_modules/es-abstract/2015/CreateDataProperty.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var OrdinaryGetOwnProperty = require('./OrdinaryGetOwnProperty'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createdataproperty - -module.exports = function CreateDataProperty(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - var oldDesc = OrdinaryGetOwnProperty(O, P); - var extensible = !oldDesc || IsExtensible(O); - var immutable = oldDesc && (!oldDesc['[[Writable]]'] || !oldDesc['[[Configurable]]']); - if (immutable || !extensible) { - return false; - } - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': true, - '[[Enumerable]]': true, - '[[Value]]': V, - '[[Writable]]': true - } - ); -}; diff --git a/node_modules/es-abstract/2015/CreateDataPropertyOrThrow.js b/node_modules/es-abstract/2015/CreateDataPropertyOrThrow.js deleted file mode 100644 index 9feaec8..0000000 --- a/node_modules/es-abstract/2015/CreateDataPropertyOrThrow.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var CreateDataProperty = require('./CreateDataProperty'); -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// // https://ecma-international.org/ecma-262/6.0/#sec-createdatapropertyorthrow - -module.exports = function CreateDataPropertyOrThrow(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - var success = CreateDataProperty(O, P, V); - if (!success) { - throw new $TypeError('unable to create data property'); - } - return success; -}; diff --git a/node_modules/es-abstract/2015/CreateHTML.js b/node_modules/es-abstract/2015/CreateHTML.js deleted file mode 100644 index 536c92d..0000000 --- a/node_modules/es-abstract/2015/CreateHTML.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $replace = callBound('String.prototype.replace'); - -var RequireObjectCoercible = require('./RequireObjectCoercible'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createhtml - -module.exports = function CreateHTML(string, tag, attribute, value) { - if (Type(tag) !== 'String' || Type(attribute) !== 'String') { - throw new $TypeError('Assertion failed: `tag` and `attribute` must be strings'); - } - var str = RequireObjectCoercible(string); - var S = ToString(str); - var p1 = '<' + tag; - if (attribute !== '') { - var V = ToString(value); - var escapedV = $replace(V, /\x22/g, '"'); - p1 += '\x20' + attribute + '\x3D\x22' + escapedV + '\x22'; - } - return p1 + '>' + S + ''; -}; diff --git a/node_modules/es-abstract/2015/CreateIterResultObject.js b/node_modules/es-abstract/2015/CreateIterResultObject.js deleted file mode 100644 index aef1d22..0000000 --- a/node_modules/es-abstract/2015/CreateIterResultObject.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-createiterresultobject - -module.exports = function CreateIterResultObject(value, done) { - if (Type(done) !== 'Boolean') { - throw new $TypeError('Assertion failed: Type(done) is not Boolean'); - } - return { - value: value, - done: done - }; -}; diff --git a/node_modules/es-abstract/2015/CreateListFromArrayLike.js b/node_modules/es-abstract/2015/CreateListFromArrayLike.js deleted file mode 100644 index d6b44b5..0000000 --- a/node_modules/es-abstract/2015/CreateListFromArrayLike.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var callBound = require('../helpers/callBound'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $indexOf = callBound('Array.prototype.indexOf', true) || callBound('String.prototype.indexOf'); -var $push = callBound('Array.prototype.push'); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var ToLength = require('./ToLength'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-createlistfromarraylike -module.exports = function CreateListFromArrayLike(obj) { - var elementTypes = arguments.length > 1 - ? arguments[1] - : ['Undefined', 'Null', 'Boolean', 'String', 'Symbol', 'Number', 'Object']; - - if (Type(obj) !== 'Object') { - throw new $TypeError('Assertion failed: `obj` must be an Object'); - } - if (!IsArray(elementTypes)) { - throw new $TypeError('Assertion failed: `elementTypes`, if provided, must be an array'); - } - var len = ToLength(Get(obj, 'length')); - var list = []; - var index = 0; - while (index < len) { - var indexName = ToString(index); - var next = Get(obj, indexName); - var nextType = Type(next); - if ($indexOf(elementTypes, nextType) < 0) { - throw new $TypeError('item type ' + nextType + ' is not a valid elementType'); - } - $push(list, next); - index += 1; - } - return list; -}; diff --git a/node_modules/es-abstract/2015/CreateMethodProperty.js b/node_modules/es-abstract/2015/CreateMethodProperty.js deleted file mode 100644 index 5b599ae..0000000 --- a/node_modules/es-abstract/2015/CreateMethodProperty.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createmethodproperty - -module.exports = function CreateMethodProperty(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - var newDesc = { - '[[Configurable]]': true, - '[[Enumerable]]': false, - '[[Value]]': V, - '[[Writable]]': true - }; - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - newDesc - ); -}; diff --git a/node_modules/es-abstract/2015/DateFromTime.js b/node_modules/es-abstract/2015/DateFromTime.js deleted file mode 100644 index 962dba1..0000000 --- a/node_modules/es-abstract/2015/DateFromTime.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $EvalError = GetIntrinsic('%EvalError%'); - -var DayWithinYear = require('./DayWithinYear'); -var InLeapYear = require('./InLeapYear'); -var MonthFromTime = require('./MonthFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.5 - -module.exports = function DateFromTime(t) { - var m = MonthFromTime(t); - var d = DayWithinYear(t); - if (m === 0) { - return d + 1; - } - if (m === 1) { - return d - 30; - } - var leap = InLeapYear(t); - if (m === 2) { - return d - 58 - leap; - } - if (m === 3) { - return d - 89 - leap; - } - if (m === 4) { - return d - 119 - leap; - } - if (m === 5) { - return d - 150 - leap; - } - if (m === 6) { - return d - 180 - leap; - } - if (m === 7) { - return d - 211 - leap; - } - if (m === 8) { - return d - 242 - leap; - } - if (m === 9) { - return d - 272 - leap; - } - if (m === 10) { - return d - 303 - leap; - } - if (m === 11) { - return d - 333 - leap; - } - throw new $EvalError('Assertion failed: MonthFromTime returned an impossible value: ' + m); -}; diff --git a/node_modules/es-abstract/2015/Day.js b/node_modules/es-abstract/2015/Day.js deleted file mode 100644 index 00df813..0000000 --- a/node_modules/es-abstract/2015/Day.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - -module.exports = function Day(t) { - return $floor(t / msPerDay); -}; diff --git a/node_modules/es-abstract/2015/DayFromYear.js b/node_modules/es-abstract/2015/DayFromYear.js deleted file mode 100644 index 08dd5af..0000000 --- a/node_modules/es-abstract/2015/DayFromYear.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function DayFromYear(y) { - return (365 * (y - 1970)) + $floor((y - 1969) / 4) - $floor((y - 1901) / 100) + $floor((y - 1601) / 400); -}; - diff --git a/node_modules/es-abstract/2015/DayWithinYear.js b/node_modules/es-abstract/2015/DayWithinYear.js deleted file mode 100644 index cfc4002..0000000 --- a/node_modules/es-abstract/2015/DayWithinYear.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var Day = require('./Day'); -var DayFromYear = require('./DayFromYear'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - -module.exports = function DayWithinYear(t) { - return Day(t) - DayFromYear(YearFromTime(t)); -}; diff --git a/node_modules/es-abstract/2015/DaysInYear.js b/node_modules/es-abstract/2015/DaysInYear.js deleted file mode 100644 index db32251..0000000 --- a/node_modules/es-abstract/2015/DaysInYear.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function DaysInYear(y) { - if (mod(y, 4) !== 0) { - return 365; - } - if (mod(y, 100) !== 0) { - return 366; - } - if (mod(y, 400) !== 0) { - return 365; - } - return 366; -}; diff --git a/node_modules/es-abstract/2015/DefinePropertyOrThrow.js b/node_modules/es-abstract/2015/DefinePropertyOrThrow.js deleted file mode 100644 index 7977f6e..0000000 --- a/node_modules/es-abstract/2015/DefinePropertyOrThrow.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-definepropertyorthrow - -module.exports = function DefinePropertyOrThrow(O, P, desc) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - var Desc = isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, desc) ? desc : ToPropertyDescriptor(desc); - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc is not a valid Property Descriptor'); - } - - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); -}; diff --git a/node_modules/es-abstract/2015/DeletePropertyOrThrow.js b/node_modules/es-abstract/2015/DeletePropertyOrThrow.js deleted file mode 100644 index b476817..0000000 --- a/node_modules/es-abstract/2015/DeletePropertyOrThrow.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-deletepropertyorthrow - -module.exports = function DeletePropertyOrThrow(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // eslint-disable-next-line no-param-reassign - var success = delete O[P]; - if (!success) { - throw new $TypeError('Attempt to delete property failed.'); - } - return success; -}; diff --git a/node_modules/es-abstract/2015/EnumerableOwnNames.js b/node_modules/es-abstract/2015/EnumerableOwnNames.js deleted file mode 100644 index d068584..0000000 --- a/node_modules/es-abstract/2015/EnumerableOwnNames.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var keys = require('object-keys'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-enumerableownnames - -module.exports = function EnumerableOwnNames(O) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - return keys(O); -}; diff --git a/node_modules/es-abstract/2015/FromPropertyDescriptor.js b/node_modules/es-abstract/2015/FromPropertyDescriptor.js deleted file mode 100644 index 5ec200e..0000000 --- a/node_modules/es-abstract/2015/FromPropertyDescriptor.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-frompropertydescriptor - -module.exports = function FromPropertyDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return Desc; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - var obj = {}; - if ('[[Value]]' in Desc) { - obj.value = Desc['[[Value]]']; - } - if ('[[Writable]]' in Desc) { - obj.writable = Desc['[[Writable]]']; - } - if ('[[Get]]' in Desc) { - obj.get = Desc['[[Get]]']; - } - if ('[[Set]]' in Desc) { - obj.set = Desc['[[Set]]']; - } - if ('[[Enumerable]]' in Desc) { - obj.enumerable = Desc['[[Enumerable]]']; - } - if ('[[Configurable]]' in Desc) { - obj.configurable = Desc['[[Configurable]]']; - } - return obj; -}; diff --git a/node_modules/es-abstract/2015/Get.js b/node_modules/es-abstract/2015/Get.js deleted file mode 100644 index 5b9ad78..0000000 --- a/node_modules/es-abstract/2015/Get.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var inspect = require('object-inspect'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -/** - * 7.3.1 Get (O, P) - https://ecma-international.org/ecma-262/6.0/#sec-get-o-p - * 1. Assert: Type(O) is Object. - * 2. Assert: IsPropertyKey(P) is true. - * 3. Return O.[[Get]](P, O). - */ - -module.exports = function Get(O, P) { - // 7.3.1.1 - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - // 7.3.1.2 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true, got ' + inspect(P)); - } - // 7.3.1.3 - return O[P]; -}; diff --git a/node_modules/es-abstract/2015/GetIterator.js b/node_modules/es-abstract/2015/GetIterator.js deleted file mode 100644 index 7beddac..0000000 --- a/node_modules/es-abstract/2015/GetIterator.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var getIteratorMethod = require('../helpers/getIteratorMethod'); -var AdvanceStringIndex = require('./AdvanceStringIndex'); -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsArray = require('./IsArray'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-getiterator - -module.exports = function GetIterator(obj, method) { - var actualMethod = method; - if (arguments.length < 2) { - actualMethod = getIteratorMethod( - { - AdvanceStringIndex: AdvanceStringIndex, - GetMethod: GetMethod, - IsArray: IsArray, - Type: Type - }, - obj - ); - } - var iterator = Call(actualMethod, obj); - if (Type(iterator) !== 'Object') { - throw new $TypeError('iterator must return an object'); - } - - return iterator; -}; diff --git a/node_modules/es-abstract/2015/GetMethod.js b/node_modules/es-abstract/2015/GetMethod.js deleted file mode 100644 index aef8cbc..0000000 --- a/node_modules/es-abstract/2015/GetMethod.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var GetV = require('./GetV'); -var IsCallable = require('./IsCallable'); -var IsPropertyKey = require('./IsPropertyKey'); - -/** - * 7.3.9 - https://ecma-international.org/ecma-262/6.0/#sec-getmethod - * 1. Assert: IsPropertyKey(P) is true. - * 2. Let func be GetV(O, P). - * 3. ReturnIfAbrupt(func). - * 4. If func is either undefined or null, return undefined. - * 5. If IsCallable(func) is false, throw a TypeError exception. - * 6. Return func. - */ - -module.exports = function GetMethod(O, P) { - // 7.3.9.1 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // 7.3.9.2 - var func = GetV(O, P); - - // 7.3.9.4 - if (func == null) { - return void 0; - } - - // 7.3.9.5 - if (!IsCallable(func)) { - throw new $TypeError(P + 'is not a function'); - } - - // 7.3.9.6 - return func; -}; diff --git a/node_modules/es-abstract/2015/GetOwnPropertyKeys.js b/node_modules/es-abstract/2015/GetOwnPropertyKeys.js deleted file mode 100644 index 8d7e5ee..0000000 --- a/node_modules/es-abstract/2015/GetOwnPropertyKeys.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var hasSymbols = require('has-symbols')(); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); -var $gOPS = hasSymbols && GetIntrinsic('%Object.getOwnPropertySymbols%'); -var keys = require('object-keys'); - -var esType = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-getownpropertykeys - -module.exports = function GetOwnPropertyKeys(O, Type) { - if (esType(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (Type === 'Symbol') { - return $gOPS ? $gOPS(O) : []; - } - if (Type === 'String') { - if (!$gOPN) { - return keys(O); - } - return $gOPN(O); - } - throw new $TypeError('Assertion failed: `Type` must be `"String"` or `"Symbol"`'); -}; diff --git a/node_modules/es-abstract/2015/GetPrototypeFromConstructor.js b/node_modules/es-abstract/2015/GetPrototypeFromConstructor.js deleted file mode 100644 index 62da8fb..0000000 --- a/node_modules/es-abstract/2015/GetPrototypeFromConstructor.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Function = GetIntrinsic('%Function%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsConstructor = require('./IsConstructor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-getprototypefromconstructor - -module.exports = function GetPrototypeFromConstructor(constructor, intrinsicDefaultProto) { - var intrinsic = GetIntrinsic(intrinsicDefaultProto); // throws if not a valid intrinsic - if (!IsConstructor(constructor)) { - throw new $TypeError('Assertion failed: `constructor` must be a constructor'); - } - var proto = Get(constructor, 'prototype'); - if (Type(proto) !== 'Object') { - if (!(constructor instanceof $Function)) { - // ignore other realms, for now - throw new $TypeError('cross-realm constructors not currently supported'); - } - proto = intrinsic; - } - return proto; -}; diff --git a/node_modules/es-abstract/2015/GetSubstitution.js b/node_modules/es-abstract/2015/GetSubstitution.js deleted file mode 100644 index de41b01..0000000 --- a/node_modules/es-abstract/2015/GetSubstitution.js +++ /dev/null @@ -1,104 +0,0 @@ - -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $parseInt = GetIntrinsic('%parseInt%'); - -var inspect = require('object-inspect'); - -var regexTester = require('../helpers/regexTester'); -var callBound = require('../helpers/callBound'); -var every = require('../helpers/every'); - -var isDigit = regexTester(/^[0-9]$/); - -var $charAt = callBound('String.prototype.charAt'); -var $strSlice = callBound('String.prototype.slice'); - -var IsArray = require('./IsArray'); -var IsInteger = require('./IsInteger'); -var Type = require('./Type'); - -var canDistinguishSparseFromUndefined = 0 in [undefined]; // IE 6 - 8 have a bug where this returns false - -var isStringOrHole = function (capture, index, arr) { - return Type(capture) === 'String' || (canDistinguishSparseFromUndefined ? !(index in arr) : Type(capture) === 'Undefined'); -}; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-getsubstitution - -// eslint-disable-next-line max-statements, max-params, max-lines-per-function -module.exports = function GetSubstitution(matched, str, position, captures, replacement) { - if (Type(matched) !== 'String') { - throw new $TypeError('Assertion failed: `matched` must be a String'); - } - var matchLength = matched.length; - - if (Type(str) !== 'String') { - throw new $TypeError('Assertion failed: `str` must be a String'); - } - var stringLength = str.length; - - if (!IsInteger(position) || position < 0 || position > stringLength) { - throw new $TypeError('Assertion failed: `position` must be a nonnegative integer, and less than or equal to the length of `string`, got ' + inspect(position)); - } - - if (!IsArray(captures) || !every(captures, isStringOrHole)) { - throw new $TypeError('Assertion failed: `captures` must be a List of Strings, got ' + inspect(captures)); - } - - if (Type(replacement) !== 'String') { - throw new $TypeError('Assertion failed: `replacement` must be a String'); - } - - var tailPos = position + matchLength; - var m = captures.length; - - var result = ''; - for (var i = 0; i < replacement.length; i += 1) { - // if this is a $, and it's not the end of the replacement - var current = $charAt(replacement, i); - var isLast = (i + 1) >= replacement.length; - var nextIsLast = (i + 2) >= replacement.length; - if (current === '$' && !isLast) { - var next = $charAt(replacement, i + 1); - if (next === '$') { - result += '$'; - i += 1; - } else if (next === '&') { - result += matched; - i += 1; - } else if (next === '`') { - result += position === 0 ? '' : $strSlice(str, 0, position - 1); - i += 1; - } else if (next === "'") { - result += tailPos >= stringLength ? '' : $strSlice(str, tailPos); - i += 1; - } else { - var nextNext = nextIsLast ? null : $charAt(replacement, i + 2); - if (isDigit(next) && next !== '0' && (nextIsLast || !isDigit(nextNext))) { - // $1 through $9, and not followed by a digit - var n = $parseInt(next, 10); - // if (n > m, impl-defined) - result += (n <= m && Type(captures[n - 1]) === 'Undefined') ? '' : captures[n - 1]; - i += 1; - } else if (isDigit(next) && (nextIsLast || isDigit(nextNext))) { - // $00 through $99 - var nn = next + nextNext; - var nnI = $parseInt(nn, 10) - 1; - // if nn === '00' or nn > m, impl-defined - result += (nn <= m && Type(captures[nnI]) === 'Undefined') ? '' : captures[nnI]; - i += 2; - } else { - result += '$'; - } - } - } else { - // the final $, or else not a $ - result += $charAt(replacement, i); - } - } - return result; -}; diff --git a/node_modules/es-abstract/2015/GetV.js b/node_modules/es-abstract/2015/GetV.js deleted file mode 100644 index 7b5139a..0000000 --- a/node_modules/es-abstract/2015/GetV.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var ToObject = require('./ToObject'); - -/** - * 7.3.2 GetV (V, P) - * 1. Assert: IsPropertyKey(P) is true. - * 2. Let O be ToObject(V). - * 3. ReturnIfAbrupt(O). - * 4. Return O.[[Get]](P, V). - */ - -module.exports = function GetV(V, P) { - // 7.3.2.1 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // 7.3.2.2-3 - var O = ToObject(V); - - // 7.3.2.4 - return O[P]; -}; diff --git a/node_modules/es-abstract/2015/HasOwnProperty.js b/node_modules/es-abstract/2015/HasOwnProperty.js deleted file mode 100644 index 679059f..0000000 --- a/node_modules/es-abstract/2015/HasOwnProperty.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var has = require('has'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-hasownproperty - -module.exports = function HasOwnProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - return has(O, P); -}; diff --git a/node_modules/es-abstract/2015/HasProperty.js b/node_modules/es-abstract/2015/HasProperty.js deleted file mode 100644 index 5f2d212..0000000 --- a/node_modules/es-abstract/2015/HasProperty.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-hasproperty - -module.exports = function HasProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - return P in O; -}; diff --git a/node_modules/es-abstract/2015/HourFromTime.js b/node_modules/es-abstract/2015/HourFromTime.js deleted file mode 100644 index 957ce32..0000000 --- a/node_modules/es-abstract/2015/HourFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerHour = timeConstants.msPerHour; -var HoursPerDay = timeConstants.HoursPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function HourFromTime(t) { - return mod($floor(t / msPerHour), HoursPerDay); -}; diff --git a/node_modules/es-abstract/2015/InLeapYear.js b/node_modules/es-abstract/2015/InLeapYear.js deleted file mode 100644 index 38ba8fd..0000000 --- a/node_modules/es-abstract/2015/InLeapYear.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $EvalError = GetIntrinsic('%EvalError%'); - -var DaysInYear = require('./DaysInYear'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function InLeapYear(t) { - var days = DaysInYear(YearFromTime(t)); - if (days === 365) { - return 0; - } - if (days === 366) { - return 1; - } - throw new $EvalError('Assertion failed: there are not 365 or 366 days in a year, got: ' + days); -}; diff --git a/node_modules/es-abstract/2015/InstanceofOperator.js b/node_modules/es-abstract/2015/InstanceofOperator.js deleted file mode 100644 index ebd308c..0000000 --- a/node_modules/es-abstract/2015/InstanceofOperator.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $hasInstance = GetIntrinsic('Symbol.hasInstance', true); - -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsCallable = require('./IsCallable'); -var OrdinaryHasInstance = require('./OrdinaryHasInstance'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-instanceofoperator - -module.exports = function InstanceofOperator(O, C) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - var instOfHandler = $hasInstance ? GetMethod(C, $hasInstance) : void 0; - if (typeof instOfHandler !== 'undefined') { - return ToBoolean(Call(instOfHandler, C, [O])); - } - if (!IsCallable(C)) { - throw new $TypeError('`C` is not Callable'); - } - return OrdinaryHasInstance(C, O); -}; diff --git a/node_modules/es-abstract/2015/Invoke.js b/node_modules/es-abstract/2015/Invoke.js deleted file mode 100644 index 769f0e3..0000000 --- a/node_modules/es-abstract/2015/Invoke.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $arraySlice = require('../helpers/callBound')('Array.prototype.slice'); - -var Call = require('./Call'); -var GetV = require('./GetV'); -var IsPropertyKey = require('./IsPropertyKey'); - -// https://ecma-international.org/ecma-262/6.0/#sec-invoke - -module.exports = function Invoke(O, P) { - if (!IsPropertyKey(P)) { - throw new $TypeError('P must be a Property Key'); - } - var argumentsList = $arraySlice(arguments, 2); - var func = GetV(O, P); - return Call(func, O, argumentsList); -}; diff --git a/node_modules/es-abstract/2015/IsAccessorDescriptor.js b/node_modules/es-abstract/2015/IsAccessorDescriptor.js deleted file mode 100644 index 5139464..0000000 --- a/node_modules/es-abstract/2015/IsAccessorDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isaccessordescriptor - -module.exports = function IsAccessorDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) { - return false; - } - - return true; -}; diff --git a/node_modules/es-abstract/2015/IsArray.js b/node_modules/es-abstract/2015/IsArray.js deleted file mode 100644 index 7b25f37..0000000 --- a/node_modules/es-abstract/2015/IsArray.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Array = GetIntrinsic('%Array%'); - -// eslint-disable-next-line global-require -var toStr = !$Array.isArray && require('../helpers/callBound')('Object.prototype.toString'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isarray - -module.exports = $Array.isArray || function IsArray(argument) { - return toStr(argument) === '[object Array]'; -}; diff --git a/node_modules/es-abstract/2015/IsCallable.js b/node_modules/es-abstract/2015/IsCallable.js deleted file mode 100644 index e4bfa36..0000000 --- a/node_modules/es-abstract/2015/IsCallable.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.11 - -module.exports = require('is-callable'); diff --git a/node_modules/es-abstract/2015/IsConcatSpreadable.js b/node_modules/es-abstract/2015/IsConcatSpreadable.js deleted file mode 100644 index dc8aae1..0000000 --- a/node_modules/es-abstract/2015/IsConcatSpreadable.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $isConcatSpreadable = GetIntrinsic('%Symbol.isConcatSpreadable%', true); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-isconcatspreadable - -module.exports = function IsConcatSpreadable(O) { - if (Type(O) !== 'Object') { - return false; - } - if ($isConcatSpreadable) { - var spreadable = Get(O, $isConcatSpreadable); - if (typeof spreadable !== 'undefined') { - return ToBoolean(spreadable); - } - } - return IsArray(O); -}; diff --git a/node_modules/es-abstract/2015/IsConstructor.js b/node_modules/es-abstract/2015/IsConstructor.js deleted file mode 100644 index 00ea52c..0000000 --- a/node_modules/es-abstract/2015/IsConstructor.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isconstructor - -module.exports = function IsConstructor(argument) { - return typeof argument === 'function' && !!argument.prototype; // unfortunately there's no way to truly check this without try/catch `new argument` -}; diff --git a/node_modules/es-abstract/2015/IsDataDescriptor.js b/node_modules/es-abstract/2015/IsDataDescriptor.js deleted file mode 100644 index 0ad3045..0000000 --- a/node_modules/es-abstract/2015/IsDataDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isdatadescriptor - -module.exports = function IsDataDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) { - return false; - } - - return true; -}; diff --git a/node_modules/es-abstract/2015/IsExtensible.js b/node_modules/es-abstract/2015/IsExtensible.js deleted file mode 100644 index 0c4c8a6..0000000 --- a/node_modules/es-abstract/2015/IsExtensible.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Object = GetIntrinsic('%Object%'); - -var isPrimitive = require('../helpers/isPrimitive'); - -var $preventExtensions = $Object.preventExtensions; -var $isExtensible = $Object.isExtensible; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isextensible-o - -module.exports = $preventExtensions - ? function IsExtensible(obj) { - return !isPrimitive(obj) && $isExtensible(obj); - } - : function IsExtensible(obj) { - return !isPrimitive(obj); - }; diff --git a/node_modules/es-abstract/2015/IsGenericDescriptor.js b/node_modules/es-abstract/2015/IsGenericDescriptor.js deleted file mode 100644 index 8618ce4..0000000 --- a/node_modules/es-abstract/2015/IsGenericDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var assertRecord = require('../helpers/assertRecord'); - -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isgenericdescriptor - -module.exports = function IsGenericDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!IsAccessorDescriptor(Desc) && !IsDataDescriptor(Desc)) { - return true; - } - - return false; -}; diff --git a/node_modules/es-abstract/2015/IsInteger.js b/node_modules/es-abstract/2015/IsInteger.js deleted file mode 100644 index 0f488b3..0000000 --- a/node_modules/es-abstract/2015/IsInteger.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isinteger - -module.exports = function IsInteger(argument) { - if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) { - return false; - } - var abs = $abs(argument); - return $floor(abs) === abs; -}; diff --git a/node_modules/es-abstract/2015/IsPromise.js b/node_modules/es-abstract/2015/IsPromise.js deleted file mode 100644 index e8e92a2..0000000 --- a/node_modules/es-abstract/2015/IsPromise.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var $PromiseThen = callBound('Promise.prototype.then', true); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ispromise - -module.exports = function IsPromise(x) { - if (Type(x) !== 'Object') { - return false; - } - if (!$PromiseThen) { // Promises are not supported - return false; - } - try { - $PromiseThen(x); // throws if not a promise - } catch (e) { - return false; - } - return true; -}; diff --git a/node_modules/es-abstract/2015/IsPropertyDescriptor.js b/node_modules/es-abstract/2015/IsPropertyDescriptor.js deleted file mode 100644 index 2a96c63..0000000 --- a/node_modules/es-abstract/2015/IsPropertyDescriptor.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var Type = require('./Type'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); - -// https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type - -module.exports = function IsPropertyDescriptor(Desc) { - return isPropertyDescriptor({ - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor, - Type: Type - }, Desc); -}; diff --git a/node_modules/es-abstract/2015/IsPropertyKey.js b/node_modules/es-abstract/2015/IsPropertyKey.js deleted file mode 100644 index 74b8d95..0000000 --- a/node_modules/es-abstract/2015/IsPropertyKey.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ispropertykey - -module.exports = function IsPropertyKey(argument) { - return typeof argument === 'string' || typeof argument === 'symbol'; -}; diff --git a/node_modules/es-abstract/2015/IsRegExp.js b/node_modules/es-abstract/2015/IsRegExp.js deleted file mode 100644 index fdf2323..0000000 --- a/node_modules/es-abstract/2015/IsRegExp.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $match = GetIntrinsic('%Symbol.match%', true); - -var hasRegExpMatcher = require('is-regex'); - -var ToBoolean = require('./ToBoolean'); - -// https://ecma-international.org/ecma-262/6.0/#sec-isregexp - -module.exports = function IsRegExp(argument) { - if (!argument || typeof argument !== 'object') { - return false; - } - if ($match) { - var isRegExp = argument[$match]; - if (typeof isRegExp !== 'undefined') { - return ToBoolean(isRegExp); - } - } - return hasRegExpMatcher(argument); -}; diff --git a/node_modules/es-abstract/2015/IteratorClose.js b/node_modules/es-abstract/2015/IteratorClose.js deleted file mode 100644 index 35c8c2b..0000000 --- a/node_modules/es-abstract/2015/IteratorClose.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorclose - -module.exports = function IteratorClose(iterator, completion) { - if (Type(iterator) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterator) is not Object'); - } - if (!IsCallable(completion)) { - throw new $TypeError('Assertion failed: completion is not a thunk for a Completion Record'); - } - var completionThunk = completion; - - var iteratorReturn = GetMethod(iterator, 'return'); - - if (typeof iteratorReturn === 'undefined') { - return completionThunk(); - } - - var completionRecord; - try { - var innerResult = Call(iteratorReturn, iterator, []); - } catch (e) { - // if we hit here, then "e" is the innerResult completion that needs re-throwing - - // if the completion is of type "throw", this will throw. - completionThunk(); - completionThunk = null; // ensure it's not called twice. - - // if not, then return the innerResult completion - throw e; - } - completionRecord = completionThunk(); // if innerResult worked, then throw if the completion does - completionThunk = null; // ensure it's not called twice. - - if (Type(innerResult) !== 'Object') { - throw new $TypeError('iterator .return must return an object'); - } - - return completionRecord; -}; diff --git a/node_modules/es-abstract/2015/IteratorComplete.js b/node_modules/es-abstract/2015/IteratorComplete.js deleted file mode 100644 index a62b9bf..0000000 --- a/node_modules/es-abstract/2015/IteratorComplete.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorcomplete - -module.exports = function IteratorComplete(iterResult) { - if (Type(iterResult) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); - } - return ToBoolean(Get(iterResult, 'done')); -}; diff --git a/node_modules/es-abstract/2015/IteratorNext.js b/node_modules/es-abstract/2015/IteratorNext.js deleted file mode 100644 index 7e59915..0000000 --- a/node_modules/es-abstract/2015/IteratorNext.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Invoke = require('./Invoke'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratornext - -module.exports = function IteratorNext(iterator, value) { - var result = Invoke(iterator, 'next', arguments.length < 2 ? [] : [value]); - if (Type(result) !== 'Object') { - throw new $TypeError('iterator next must return an object'); - } - return result; -}; diff --git a/node_modules/es-abstract/2015/IteratorStep.js b/node_modules/es-abstract/2015/IteratorStep.js deleted file mode 100644 index 41b9d1b..0000000 --- a/node_modules/es-abstract/2015/IteratorStep.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var IteratorComplete = require('./IteratorComplete'); -var IteratorNext = require('./IteratorNext'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorstep - -module.exports = function IteratorStep(iterator) { - var result = IteratorNext(iterator); - var done = IteratorComplete(result); - return done === true ? false : result; -}; - diff --git a/node_modules/es-abstract/2015/IteratorValue.js b/node_modules/es-abstract/2015/IteratorValue.js deleted file mode 100644 index 5e71a44..0000000 --- a/node_modules/es-abstract/2015/IteratorValue.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorvalue - -module.exports = function IteratorValue(iterResult) { - if (Type(iterResult) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); - } - return Get(iterResult, 'value'); -}; - diff --git a/node_modules/es-abstract/2015/MakeDate.js b/node_modules/es-abstract/2015/MakeDate.js deleted file mode 100644 index 7b592d1..0000000 --- a/node_modules/es-abstract/2015/MakeDate.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $isFinite = require('../helpers/isFinite'); -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.13 - -module.exports = function MakeDate(day, time) { - if (!$isFinite(day) || !$isFinite(time)) { - return NaN; - } - return (day * msPerDay) + time; -}; diff --git a/node_modules/es-abstract/2015/MakeDay.js b/node_modules/es-abstract/2015/MakeDay.js deleted file mode 100644 index f1ab810..0000000 --- a/node_modules/es-abstract/2015/MakeDay.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); -var $DateUTC = GetIntrinsic('%Date.UTC%'); - -var mod = require('../helpers/mod'); -var $isFinite = require('../helpers/isFinite'); - -var DateFromTime = require('./DateFromTime'); -var Day = require('./Day'); -var MonthFromTime = require('./MonthFromTime'); -var ToInteger = require('./ToInteger'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.12 - -module.exports = function MakeDay(year, month, date) { - if (!$isFinite(year) || !$isFinite(month) || !$isFinite(date)) { - return NaN; - } - var y = ToInteger(year); - var m = ToInteger(month); - var dt = ToInteger(date); - var ym = y + $floor(m / 12); - var mn = mod(m, 12); - var t = $DateUTC(ym, mn, 1); - if (YearFromTime(t) !== ym || MonthFromTime(t) !== mn || DateFromTime(t) !== 1) { - return NaN; - } - return Day(t) + dt - 1; -}; diff --git a/node_modules/es-abstract/2015/MakeTime.js b/node_modules/es-abstract/2015/MakeTime.js deleted file mode 100644 index e118500..0000000 --- a/node_modules/es-abstract/2015/MakeTime.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var $isFinite = require('../helpers/isFinite'); -var timeConstants = require('../helpers/timeConstants'); -var msPerSecond = timeConstants.msPerSecond; -var msPerMinute = timeConstants.msPerMinute; -var msPerHour = timeConstants.msPerHour; - -var ToInteger = require('./ToInteger'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.11 - -module.exports = function MakeTime(hour, min, sec, ms) { - if (!$isFinite(hour) || !$isFinite(min) || !$isFinite(sec) || !$isFinite(ms)) { - return NaN; - } - var h = ToInteger(hour); - var m = ToInteger(min); - var s = ToInteger(sec); - var milli = ToInteger(ms); - var t = (h * msPerHour) + (m * msPerMinute) + (s * msPerSecond) + milli; - return t; -}; diff --git a/node_modules/es-abstract/2015/MinFromTime.js b/node_modules/es-abstract/2015/MinFromTime.js deleted file mode 100644 index e80e191..0000000 --- a/node_modules/es-abstract/2015/MinFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerMinute = timeConstants.msPerMinute; -var MinutesPerHour = timeConstants.MinutesPerHour; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function MinFromTime(t) { - return mod($floor(t / msPerMinute), MinutesPerHour); -}; diff --git a/node_modules/es-abstract/2015/MonthFromTime.js b/node_modules/es-abstract/2015/MonthFromTime.js deleted file mode 100644 index 4f120f2..0000000 --- a/node_modules/es-abstract/2015/MonthFromTime.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -var DayWithinYear = require('./DayWithinYear'); -var InLeapYear = require('./InLeapYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - -module.exports = function MonthFromTime(t) { - var day = DayWithinYear(t); - if (0 <= day && day < 31) { - return 0; - } - var leap = InLeapYear(t); - if (31 <= day && day < (59 + leap)) { - return 1; - } - if ((59 + leap) <= day && day < (90 + leap)) { - return 2; - } - if ((90 + leap) <= day && day < (120 + leap)) { - return 3; - } - if ((120 + leap) <= day && day < (151 + leap)) { - return 4; - } - if ((151 + leap) <= day && day < (181 + leap)) { - return 5; - } - if ((181 + leap) <= day && day < (212 + leap)) { - return 6; - } - if ((212 + leap) <= day && day < (243 + leap)) { - return 7; - } - if ((243 + leap) <= day && day < (273 + leap)) { - return 8; - } - if ((273 + leap) <= day && day < (304 + leap)) { - return 9; - } - if ((304 + leap) <= day && day < (334 + leap)) { - return 10; - } - if ((334 + leap) <= day && day < (365 + leap)) { - return 11; - } -}; diff --git a/node_modules/es-abstract/2015/ObjectCreate.js b/node_modules/es-abstract/2015/ObjectCreate.js deleted file mode 100644 index e2445b0..0000000 --- a/node_modules/es-abstract/2015/ObjectCreate.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $ObjectCreate = GetIntrinsic('%Object.create%', true); -var $TypeError = GetIntrinsic('%TypeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); - -var Type = require('./Type'); - -var hasProto = !({ __proto__: null } instanceof Object); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-objectcreate - -module.exports = function ObjectCreate(proto, internalSlotsList) { - if (proto !== null && Type(proto) !== 'Object') { - throw new $TypeError('Assertion failed: `proto` must be null or an object'); - } - var slots = arguments.length < 2 ? [] : internalSlotsList; - if (slots.length > 0) { - throw new $SyntaxError('es-abstract does not yet support internal slots'); - } - - if ($ObjectCreate) { - return $ObjectCreate(proto); - } - if (hasProto) { - return { __proto__: proto }; - } - - if (proto === null) { - throw new $SyntaxError('native Object.create support is required to create null objects'); - } - var T = function T() {}; - T.prototype = proto; - return new T(); -}; diff --git a/node_modules/es-abstract/2015/OrdinaryDefineOwnProperty.js b/node_modules/es-abstract/2015/OrdinaryDefineOwnProperty.js deleted file mode 100644 index 59780b3..0000000 --- a/node_modules/es-abstract/2015/OrdinaryDefineOwnProperty.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var IsPropertyKey = require('./IsPropertyKey'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); -var ValidateAndApplyPropertyDescriptor = require('./ValidateAndApplyPropertyDescriptor'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarydefineownproperty - -module.exports = function OrdinaryDefineOwnProperty(O, P, Desc) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (!$gOPD) { - // ES3/IE 8 fallback - if (IsAccessorDescriptor(Desc)) { - throw new $SyntaxError('This environment does not support accessor property descriptors.'); - } - var creatingNormalDataProperty = !(P in O) - && Desc['[[Writable]]'] - && Desc['[[Enumerable]]'] - && Desc['[[Configurable]]'] - && '[[Value]]' in Desc; - var settingExistingDataProperty = (P in O) - && (!('[[Configurable]]' in Desc) || Desc['[[Configurable]]']) - && (!('[[Enumerable]]' in Desc) || Desc['[[Enumerable]]']) - && (!('[[Writable]]' in Desc) || Desc['[[Writable]]']) - && '[[Value]]' in Desc; - if (creatingNormalDataProperty || settingExistingDataProperty) { - O[P] = Desc['[[Value]]']; // eslint-disable-line no-param-reassign - return SameValue(O[P], Desc['[[Value]]']); - } - throw new $SyntaxError('This environment does not support defining non-writable, non-enumerable, or non-configurable properties'); - } - var desc = $gOPD(O, P); - var current = desc && ToPropertyDescriptor(desc); - var extensible = IsExtensible(O); - return ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current); -}; diff --git a/node_modules/es-abstract/2015/OrdinaryGetOwnProperty.js b/node_modules/es-abstract/2015/OrdinaryGetOwnProperty.js deleted file mode 100644 index b9882e5..0000000 --- a/node_modules/es-abstract/2015/OrdinaryGetOwnProperty.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); - -var has = require('has'); - -var IsArray = require('./IsArray'); -var IsPropertyKey = require('./IsPropertyKey'); -var IsRegExp = require('./IsRegExp'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarygetownproperty - -module.exports = function OrdinaryGetOwnProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - if (!has(O, P)) { - return void 0; - } - if (!$gOPD) { - // ES3 / IE 8 fallback - var arrayLength = IsArray(O) && P === 'length'; - var regexLastIndex = IsRegExp(O) && P === 'lastIndex'; - return { - '[[Configurable]]': !(arrayLength || regexLastIndex), - '[[Enumerable]]': $isEnumerable(O, P), - '[[Value]]': O[P], - '[[Writable]]': true - }; - } - return ToPropertyDescriptor($gOPD(O, P)); -}; diff --git a/node_modules/es-abstract/2015/OrdinaryHasInstance.js b/node_modules/es-abstract/2015/OrdinaryHasInstance.js deleted file mode 100644 index 51abe26..0000000 --- a/node_modules/es-abstract/2015/OrdinaryHasInstance.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance - -module.exports = function OrdinaryHasInstance(C, O) { - if (IsCallable(C) === false) { - return false; - } - if (Type(O) !== 'Object') { - return false; - } - var P = Get(C, 'prototype'); - if (Type(P) !== 'Object') { - throw new $TypeError('OrdinaryHasInstance called on an object with an invalid prototype property.'); - } - return O instanceof C; -}; diff --git a/node_modules/es-abstract/2015/OrdinaryHasProperty.js b/node_modules/es-abstract/2015/OrdinaryHasProperty.js deleted file mode 100644 index 076c25a..0000000 --- a/node_modules/es-abstract/2015/OrdinaryHasProperty.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasproperty - -module.exports = function OrdinaryHasProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - return P in O; -}; diff --git a/node_modules/es-abstract/2015/RegExpExec.js b/node_modules/es-abstract/2015/RegExpExec.js deleted file mode 100644 index 15c9186..0000000 --- a/node_modules/es-abstract/2015/RegExpExec.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var regexExec = require('../helpers/callBound')('RegExp.prototype.exec'); - -var Call = require('./Call'); -var Get = require('./Get'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-regexpexec - -module.exports = function RegExpExec(R, S) { - if (Type(R) !== 'Object') { - throw new $TypeError('Assertion failed: `R` must be an Object'); - } - if (Type(S) !== 'String') { - throw new $TypeError('Assertion failed: `S` must be a String'); - } - var exec = Get(R, 'exec'); - if (IsCallable(exec)) { - var result = Call(exec, R, [S]); - if (result === null || Type(result) === 'Object') { - return result; - } - throw new $TypeError('"exec" method must return `null` or an Object'); - } - return regexExec(R, S); -}; diff --git a/node_modules/es-abstract/2015/RequireObjectCoercible.js b/node_modules/es-abstract/2015/RequireObjectCoercible.js deleted file mode 100644 index 9008359..0000000 --- a/node_modules/es-abstract/2015/RequireObjectCoercible.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('../5/CheckObjectCoercible'); diff --git a/node_modules/es-abstract/2015/SameValue.js b/node_modules/es-abstract/2015/SameValue.js deleted file mode 100644 index 47c936d..0000000 --- a/node_modules/es-abstract/2015/SameValue.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $isNaN = require('../helpers/isNaN'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.12 - -module.exports = function SameValue(x, y) { - if (x === y) { // 0 === -0, but they are not identical. - if (x === 0) { return 1 / x === 1 / y; } - return true; - } - return $isNaN(x) && $isNaN(y); -}; diff --git a/node_modules/es-abstract/2015/SameValueZero.js b/node_modules/es-abstract/2015/SameValueZero.js deleted file mode 100644 index 0dedcd2..0000000 --- a/node_modules/es-abstract/2015/SameValueZero.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var $isNaN = require('../helpers/isNaN'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-samevaluezero - -module.exports = function SameValueZero(x, y) { - return (x === y) || ($isNaN(x) && $isNaN(y)); -}; diff --git a/node_modules/es-abstract/2015/SecFromTime.js b/node_modules/es-abstract/2015/SecFromTime.js deleted file mode 100644 index 7190011..0000000 --- a/node_modules/es-abstract/2015/SecFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerSecond = timeConstants.msPerSecond; -var SecondsPerMinute = timeConstants.SecondsPerMinute; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function SecFromTime(t) { - return mod($floor(t / msPerSecond), SecondsPerMinute); -}; diff --git a/node_modules/es-abstract/2015/Set.js b/node_modules/es-abstract/2015/Set.js deleted file mode 100644 index 18ebd99..0000000 --- a/node_modules/es-abstract/2015/Set.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-set-o-p-v-throw - -module.exports = function Set(O, P, V, Throw) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - if (Type(Throw) !== 'Boolean') { - throw new $TypeError('Assertion failed: `Throw` must be a Boolean'); - } - if (Throw) { - O[P] = V; // eslint-disable-line no-param-reassign - return true; - } else { - try { - O[P] = V; // eslint-disable-line no-param-reassign - } catch (e) { - return false; - } - } -}; diff --git a/node_modules/es-abstract/2015/SetFunctionName.js b/node_modules/es-abstract/2015/SetFunctionName.js deleted file mode 100644 index f93324a..0000000 --- a/node_modules/es-abstract/2015/SetFunctionName.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var has = require('has'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var getSymbolDescription = require('../helpers/getSymbolDescription'); - -var DefinePropertyOrThrow = require('./DefinePropertyOrThrow'); -var IsExtensible = require('./IsExtensible'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-setfunctionname - -module.exports = function SetFunctionName(F, name) { - if (typeof F !== 'function') { - throw new $TypeError('Assertion failed: `F` must be a function'); - } - if (!IsExtensible(F) || has(F, 'name')) { - throw new $TypeError('Assertion failed: `F` must be extensible, and must not have a `name` own property'); - } - var nameType = Type(name); - if (nameType !== 'Symbol' && nameType !== 'String') { - throw new $TypeError('Assertion failed: `name` must be a Symbol or a String'); - } - if (nameType === 'Symbol') { - var description = getSymbolDescription(name); - // eslint-disable-next-line no-param-reassign - name = typeof description === 'undefined' ? '' : '[' + description + ']'; - } - if (arguments.length > 2) { - var prefix = arguments[2]; - // eslint-disable-next-line no-param-reassign - name = prefix + ' ' + name; - } - return DefinePropertyOrThrow(F, 'name', { - '[[Value]]': name, - '[[Writable]]': false, - '[[Enumerable]]': false, - '[[Configurable]]': true - }); -}; diff --git a/node_modules/es-abstract/2015/SetIntegrityLevel.js b/node_modules/es-abstract/2015/SetIntegrityLevel.js deleted file mode 100644 index 3d5c81d..0000000 --- a/node_modules/es-abstract/2015/SetIntegrityLevel.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); -var $preventExtensions = GetIntrinsic('%Object.preventExtensions%'); -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); - -var forEach = require('../helpers/forEach'); - -var DefinePropertyOrThrow = require('./DefinePropertyOrThrow'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-setintegritylevel - -module.exports = function SetIntegrityLevel(O, level) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (level !== 'sealed' && level !== 'frozen') { - throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); - } - if (!$preventExtensions) { - throw new $SyntaxError('SetIntegrityLevel requires native `Object.preventExtensions` support'); - } - var status = $preventExtensions(O); - if (!status) { - return false; - } - if (!$gOPN) { - throw new $SyntaxError('SetIntegrityLevel requires native `Object.getOwnPropertyNames` support'); - } - var theKeys = $gOPN(O); - if (level === 'sealed') { - forEach(theKeys, function (k) { - DefinePropertyOrThrow(O, k, { configurable: false }); - }); - } else if (level === 'frozen') { - forEach(theKeys, function (k) { - var currentDesc = $gOPD(O, k); - if (typeof currentDesc !== 'undefined') { - var desc; - if (IsAccessorDescriptor(ToPropertyDescriptor(currentDesc))) { - desc = { configurable: false }; - } else { - desc = { configurable: false, writable: false }; - } - DefinePropertyOrThrow(O, k, desc); - } - }); - } - return true; -}; diff --git a/node_modules/es-abstract/2015/SpeciesConstructor.js b/node_modules/es-abstract/2015/SpeciesConstructor.js deleted file mode 100644 index 3cdcd74..0000000 --- a/node_modules/es-abstract/2015/SpeciesConstructor.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $species = GetIntrinsic('%Symbol.species%', true); -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsConstructor = require('./IsConstructor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-speciesconstructor - -module.exports = function SpeciesConstructor(O, defaultConstructor) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - var C = O.constructor; - if (typeof C === 'undefined') { - return defaultConstructor; - } - if (Type(C) !== 'Object') { - throw new $TypeError('O.constructor is not an Object'); - } - var S = $species ? C[$species] : void 0; - if (S == null) { - return defaultConstructor; - } - if (IsConstructor(S)) { - return S; - } - throw new $TypeError('no constructor found'); -}; diff --git a/node_modules/es-abstract/2015/StrictEqualityComparison.js b/node_modules/es-abstract/2015/StrictEqualityComparison.js deleted file mode 100644 index eea5df3..0000000 --- a/node_modules/es-abstract/2015/StrictEqualityComparison.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6 - -module.exports = function StrictEqualityComparison(x, y) { - var xType = Type(x); - var yType = Type(y); - if (xType !== yType) { - return false; - } - if (xType === 'Undefined' || xType === 'Null') { - return true; - } - return x === y; // shortcut for steps 4-7 -}; diff --git a/node_modules/es-abstract/2015/SymbolDescriptiveString.js b/node_modules/es-abstract/2015/SymbolDescriptiveString.js deleted file mode 100644 index 7bd8191..0000000 --- a/node_modules/es-abstract/2015/SymbolDescriptiveString.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $SymbolToString = callBound('Symbol.prototype.toString', true); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-symboldescriptivestring - -module.exports = function SymbolDescriptiveString(sym) { - if (Type(sym) !== 'Symbol') { - throw new $TypeError('Assertion failed: `sym` must be a Symbol'); - } - return $SymbolToString(sym); -}; diff --git a/node_modules/es-abstract/2015/TestIntegrityLevel.js b/node_modules/es-abstract/2015/TestIntegrityLevel.js deleted file mode 100644 index 7a57397..0000000 --- a/node_modules/es-abstract/2015/TestIntegrityLevel.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var every = require('../helpers/every'); - -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-testintegritylevel - -module.exports = function TestIntegrityLevel(O, level) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (level !== 'sealed' && level !== 'frozen') { - throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); - } - var status = IsExtensible(O); - if (status) { - return false; - } - var theKeys = $gOPN(O); - return theKeys.length === 0 || every(theKeys, function (k) { - var currentDesc = $gOPD(O, k); - if (typeof currentDesc !== 'undefined') { - if (currentDesc.configurable) { - return false; - } - if (level === 'frozen' && IsDataDescriptor(ToPropertyDescriptor(currentDesc)) && currentDesc.writable) { - return false; - } - } - return true; - }); -}; diff --git a/node_modules/es-abstract/2015/TimeClip.js b/node_modules/es-abstract/2015/TimeClip.js deleted file mode 100644 index 57aa08c..0000000 --- a/node_modules/es-abstract/2015/TimeClip.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Date = GetIntrinsic('%Date%'); -var $Number = GetIntrinsic('%Number%'); -var $abs = GetIntrinsic('%Math.abs%'); - -var $isFinite = require('../helpers/isFinite'); - -var ToNumber = require('./ToNumber'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.14 - -module.exports = function TimeClip(time) { - if (!$isFinite(time) || $abs(time) > 8.64e15) { - return NaN; - } - return $Number(new $Date(ToNumber(time))); -}; - diff --git a/node_modules/es-abstract/2015/TimeFromYear.js b/node_modules/es-abstract/2015/TimeFromYear.js deleted file mode 100644 index df646c3..0000000 --- a/node_modules/es-abstract/2015/TimeFromYear.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var msPerDay = require('../helpers/timeConstants').msPerDay; - -var DayFromYear = require('./DayFromYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function TimeFromYear(y) { - return msPerDay * DayFromYear(y); -}; diff --git a/node_modules/es-abstract/2015/TimeWithinDay.js b/node_modules/es-abstract/2015/TimeWithinDay.js deleted file mode 100644 index c5b21d3..0000000 --- a/node_modules/es-abstract/2015/TimeWithinDay.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - -module.exports = function TimeWithinDay(t) { - return mod(t, msPerDay); -}; - diff --git a/node_modules/es-abstract/2015/ToBoolean.js b/node_modules/es-abstract/2015/ToBoolean.js deleted file mode 100644 index 65d8737..0000000 --- a/node_modules/es-abstract/2015/ToBoolean.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.2 - -module.exports = function ToBoolean(value) { return !!value; }; diff --git a/node_modules/es-abstract/2015/ToDateString.js b/node_modules/es-abstract/2015/ToDateString.js deleted file mode 100644 index 7a6d4c4..0000000 --- a/node_modules/es-abstract/2015/ToDateString.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $Date = GetIntrinsic('%Date%'); - -var $isNaN = require('../helpers/isNaN'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-todatestring - -module.exports = function ToDateString(tv) { - if (Type(tv) !== 'Number') { - throw new $TypeError('Assertion failed: `tv` must be a Number'); - } - if ($isNaN(tv)) { - return 'Invalid Date'; - } - return $Date(tv); -}; diff --git a/node_modules/es-abstract/2015/ToInt16.js b/node_modules/es-abstract/2015/ToInt16.js deleted file mode 100644 index 5a112c2..0000000 --- a/node_modules/es-abstract/2015/ToInt16.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var ToUint16 = require('./ToUint16'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toint16 - -module.exports = function ToInt16(argument) { - var int16bit = ToUint16(argument); - return int16bit >= 0x8000 ? int16bit - 0x10000 : int16bit; -}; diff --git a/node_modules/es-abstract/2015/ToInt32.js b/node_modules/es-abstract/2015/ToInt32.js deleted file mode 100644 index a8d2680..0000000 --- a/node_modules/es-abstract/2015/ToInt32.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.5 - -module.exports = function ToInt32(x) { - return ToNumber(x) >> 0; -}; diff --git a/node_modules/es-abstract/2015/ToInt8.js b/node_modules/es-abstract/2015/ToInt8.js deleted file mode 100644 index d103123..0000000 --- a/node_modules/es-abstract/2015/ToInt8.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var ToUint8 = require('./ToUint8'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toint8 - -module.exports = function ToInt8(argument) { - var int8bit = ToUint8(argument); - return int8bit >= 0x80 ? int8bit - 0x100 : int8bit; -}; diff --git a/node_modules/es-abstract/2015/ToInteger.js b/node_modules/es-abstract/2015/ToInteger.js deleted file mode 100644 index 16f7db9..0000000 --- a/node_modules/es-abstract/2015/ToInteger.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var ES5ToInteger = require('../5/ToInteger'); - -var ToNumber = require('./ToNumber'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tointeger - -module.exports = function ToInteger(value) { - var number = ToNumber(value); - return ES5ToInteger(number); -}; diff --git a/node_modules/es-abstract/2015/ToLength.js b/node_modules/es-abstract/2015/ToLength.js deleted file mode 100644 index 1bef9be..0000000 --- a/node_modules/es-abstract/2015/ToLength.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger'); - -var ToInteger = require('./ToInteger'); - -module.exports = function ToLength(argument) { - var len = ToInteger(argument); - if (len <= 0) { return 0; } // includes converting -0 to +0 - if (len > MAX_SAFE_INTEGER) { return MAX_SAFE_INTEGER; } - return len; -}; diff --git a/node_modules/es-abstract/2015/ToNumber.js b/node_modules/es-abstract/2015/ToNumber.js deleted file mode 100644 index 7a3cdc8..0000000 --- a/node_modules/es-abstract/2015/ToNumber.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $Number = GetIntrinsic('%Number%'); -var $RegExp = GetIntrinsic('%RegExp%'); -var $parseInteger = GetIntrinsic('%parseInt%'); - -var callBound = require('../helpers/callBound'); -var regexTester = require('../helpers/regexTester'); -var isPrimitive = require('../helpers/isPrimitive'); - -var $strSlice = callBound('String.prototype.slice'); -var isBinary = regexTester(/^0b[01]+$/i); -var isOctal = regexTester(/^0o[0-7]+$/i); -var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i); -var nonWS = ['\u0085', '\u200b', '\ufffe'].join(''); -var nonWSregex = new $RegExp('[' + nonWS + ']', 'g'); -var hasNonWS = regexTester(nonWSregex); - -// whitespace from: https://es5.github.io/#x15.5.4.20 -// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 -var ws = [ - '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', - '\u2029\uFEFF' -].join(''); -var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g'); -var $replace = callBound('String.prototype.replace'); -var $trim = function (value) { - return $replace(value, trimRegex, ''); -}; - -var ToPrimitive = require('./ToPrimitive'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tonumber - -module.exports = function ToNumber(argument) { - var value = isPrimitive(argument) ? argument : ToPrimitive(argument, $Number); - if (typeof value === 'symbol') { - throw new $TypeError('Cannot convert a Symbol value to a number'); - } - if (typeof value === 'string') { - if (isBinary(value)) { - return ToNumber($parseInteger($strSlice(value, 2), 2)); - } else if (isOctal(value)) { - return ToNumber($parseInteger($strSlice(value, 2), 8)); - } else if (hasNonWS(value) || isInvalidHexLiteral(value)) { - return NaN; - } else { - var trimmed = $trim(value); - if (trimmed !== value) { - return ToNumber(trimmed); - } - } - } - return $Number(value); -}; diff --git a/node_modules/es-abstract/2015/ToObject.js b/node_modules/es-abstract/2015/ToObject.js deleted file mode 100644 index 50d5b94..0000000 --- a/node_modules/es-abstract/2015/ToObject.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Object = GetIntrinsic('%Object%'); - -var RequireObjectCoercible = require('./RequireObjectCoercible'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toobject - -module.exports = function ToObject(value) { - RequireObjectCoercible(value); - return $Object(value); -}; diff --git a/node_modules/es-abstract/2015/ToPrimitive.js b/node_modules/es-abstract/2015/ToPrimitive.js deleted file mode 100644 index 81c655d..0000000 --- a/node_modules/es-abstract/2015/ToPrimitive.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var toPrimitive = require('es-to-primitive/es2015'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive - -module.exports = function ToPrimitive(input) { - if (arguments.length > 1) { - return toPrimitive(input, arguments[1]); - } - return toPrimitive(input); -}; diff --git a/node_modules/es-abstract/2015/ToPropertyDescriptor.js b/node_modules/es-abstract/2015/ToPropertyDescriptor.js deleted file mode 100644 index 38e536e..0000000 --- a/node_modules/es-abstract/2015/ToPropertyDescriptor.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -var has = require('has'); - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Type = require('./Type'); -var ToBoolean = require('./ToBoolean'); -var IsCallable = require('./IsCallable'); - -// https://ecma-international.org/ecma-262/5.1/#sec-8.10.5 - -module.exports = function ToPropertyDescriptor(Obj) { - if (Type(Obj) !== 'Object') { - throw new $TypeError('ToPropertyDescriptor requires an object'); - } - - var desc = {}; - if (has(Obj, 'enumerable')) { - desc['[[Enumerable]]'] = ToBoolean(Obj.enumerable); - } - if (has(Obj, 'configurable')) { - desc['[[Configurable]]'] = ToBoolean(Obj.configurable); - } - if (has(Obj, 'value')) { - desc['[[Value]]'] = Obj.value; - } - if (has(Obj, 'writable')) { - desc['[[Writable]]'] = ToBoolean(Obj.writable); - } - if (has(Obj, 'get')) { - var getter = Obj.get; - if (typeof getter !== 'undefined' && !IsCallable(getter)) { - throw new TypeError('getter must be a function'); - } - desc['[[Get]]'] = getter; - } - if (has(Obj, 'set')) { - var setter = Obj.set; - if (typeof setter !== 'undefined' && !IsCallable(setter)) { - throw new $TypeError('setter must be a function'); - } - desc['[[Set]]'] = setter; - } - - if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) { - throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute'); - } - return desc; -}; diff --git a/node_modules/es-abstract/2015/ToPropertyKey.js b/node_modules/es-abstract/2015/ToPropertyKey.js deleted file mode 100644 index 38f40dd..0000000 --- a/node_modules/es-abstract/2015/ToPropertyKey.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $String = GetIntrinsic('%String%'); - -var ToPrimitive = require('./ToPrimitive'); -var ToString = require('./ToString'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-topropertykey - -module.exports = function ToPropertyKey(argument) { - var key = ToPrimitive(argument, $String); - return typeof key === 'symbol' ? key : ToString(key); -}; diff --git a/node_modules/es-abstract/2015/ToString.js b/node_modules/es-abstract/2015/ToString.js deleted file mode 100644 index a345431..0000000 --- a/node_modules/es-abstract/2015/ToString.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $String = GetIntrinsic('%String%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tostring - -module.exports = function ToString(argument) { - if (typeof argument === 'symbol') { - throw new $TypeError('Cannot convert a Symbol value to a string'); - } - return $String(argument); -}; diff --git a/node_modules/es-abstract/2015/ToUint16.js b/node_modules/es-abstract/2015/ToUint16.js deleted file mode 100644 index c8a408b..0000000 --- a/node_modules/es-abstract/2015/ToUint16.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var $sign = require('../helpers/sign'); -var $mod = require('../helpers/mod'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.7 - -module.exports = function ToUint16(value) { - var number = ToNumber(value); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = $sign(number) * $floor($abs(number)); - return $mod(posInt, 0x10000); -}; diff --git a/node_modules/es-abstract/2015/ToUint32.js b/node_modules/es-abstract/2015/ToUint32.js deleted file mode 100644 index 3660f62..0000000 --- a/node_modules/es-abstract/2015/ToUint32.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.6 - -module.exports = function ToUint32(x) { - return ToNumber(x) >>> 0; -}; diff --git a/node_modules/es-abstract/2015/ToUint8.js b/node_modules/es-abstract/2015/ToUint8.js deleted file mode 100644 index bf84753..0000000 --- a/node_modules/es-abstract/2015/ToUint8.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var $sign = require('../helpers/sign'); -var $mod = require('../helpers/mod'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -module.exports = function ToUint8(argument) { - var number = ToNumber(argument); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = $sign(number) * $floor($abs(number)); - return $mod(posInt, 0x100); -}; diff --git a/node_modules/es-abstract/2015/ToUint8Clamp.js b/node_modules/es-abstract/2015/ToUint8Clamp.js deleted file mode 100644 index c7f9f56..0000000 --- a/node_modules/es-abstract/2015/ToUint8Clamp.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); - -var $floor = $Math.floor; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-touint8clamp - -module.exports = function ToUint8Clamp(argument) { - var number = ToNumber(argument); - if ($isNaN(number) || number <= 0) { return 0; } - if (number >= 0xFF) { return 0xFF; } - var f = $floor(argument); - if (f + 0.5 < number) { return f + 1; } - if (number < f + 0.5) { return f; } - if (f % 2 !== 0) { return f + 1; } - return f; -}; diff --git a/node_modules/es-abstract/2015/Type.js b/node_modules/es-abstract/2015/Type.js deleted file mode 100644 index 6c99376..0000000 --- a/node_modules/es-abstract/2015/Type.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var ES5Type = require('../5/Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tostring - -module.exports = function Type(x) { - if (typeof x === 'symbol') { - return 'Symbol'; - } - return ES5Type(x); -}; diff --git a/node_modules/es-abstract/2015/ValidateAndApplyPropertyDescriptor.js b/node_modules/es-abstract/2015/ValidateAndApplyPropertyDescriptor.js deleted file mode 100644 index d4b9007..0000000 --- a/node_modules/es-abstract/2015/ValidateAndApplyPropertyDescriptor.js +++ /dev/null @@ -1,170 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); -var isSamePropertyDescriptor = require('../helpers/isSamePropertyDescriptor'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsGenericDescriptor = require('./IsGenericDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-validateandapplypropertydescriptor -// https://www.ecma-international.org/ecma-262/8.0/#sec-validateandapplypropertydescriptor - -// eslint-disable-next-line max-lines-per-function, max-statements, max-params -module.exports = function ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current) { - // this uses the ES2017+ logic, since it fixes a number of bugs in the ES2015 logic. - var oType = Type(O); - if (oType !== 'Undefined' && oType !== 'Object') { - throw new $TypeError('Assertion failed: O must be undefined or an Object'); - } - if (Type(extensible) !== 'Boolean') { - throw new $TypeError('Assertion failed: extensible must be a Boolean'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (Type(current) !== 'Undefined' && !isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, current)) { - throw new $TypeError('Assertion failed: current must be a Property Descriptor, or undefined'); - } - if (oType !== 'Undefined' && !IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: if O is not undefined, P must be a Property Key'); - } - if (Type(current) === 'Undefined') { - if (!extensible) { - return false; - } - if (IsGenericDescriptor(Desc) || IsDataDescriptor(Desc)) { - if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': Desc['[[Configurable]]'], - '[[Enumerable]]': Desc['[[Enumerable]]'], - '[[Value]]': Desc['[[Value]]'], - '[[Writable]]': Desc['[[Writable]]'] - } - ); - } - } else { - if (!IsAccessorDescriptor(Desc)) { - throw new $TypeError('Assertion failed: Desc is not an accessor descriptor'); - } - if (oType !== 'Undefined') { - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); - } - } - return true; - } - if (IsGenericDescriptor(Desc) && !('[[Configurable]]' in Desc) && !('[[Enumerable]]' in Desc)) { - return true; - } - if (isSamePropertyDescriptor({ SameValue: SameValue }, Desc, current)) { - return true; // removed by ES2017, but should still be correct - } - // "if every field in Desc is absent, return true" can't really match the assertion that it's a Property Descriptor - if (!current['[[Configurable]]']) { - if (Desc['[[Configurable]]']) { - return false; - } - if ('[[Enumerable]]' in Desc && !Desc['[[Enumerable]]'] === !!current['[[Enumerable]]']) { - return false; - } - } - if (IsGenericDescriptor(Desc)) { - // no further validation is required. - } else if (IsDataDescriptor(current) !== IsDataDescriptor(Desc)) { - if (!current['[[Configurable]]']) { - return false; - } - if (IsDataDescriptor(current)) { - if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': current['[[Configurable]]'], - '[[Enumerable]]': current['[[Enumerable]]'], - '[[Get]]': undefined - } - ); - } - } else if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': current['[[Configurable]]'], - '[[Enumerable]]': current['[[Enumerable]]'], - '[[Value]]': undefined - } - ); - } - } else if (IsDataDescriptor(current) && IsDataDescriptor(Desc)) { - if (!current['[[Configurable]]'] && !current['[[Writable]]']) { - if ('[[Writable]]' in Desc && Desc['[[Writable]]']) { - return false; - } - if ('[[Value]]' in Desc && !SameValue(Desc['[[Value]]'], current['[[Value]]'])) { - return false; - } - return true; - } - } else if (IsAccessorDescriptor(current) && IsAccessorDescriptor(Desc)) { - if (!current['[[Configurable]]']) { - if ('[[Set]]' in Desc && !SameValue(Desc['[[Set]]'], current['[[Set]]'])) { - return false; - } - if ('[[Get]]' in Desc && !SameValue(Desc['[[Get]]'], current['[[Get]]'])) { - return false; - } - return true; - } - } else { - throw new $TypeError('Assertion failed: current and Desc are not both data, both accessors, or one accessor and one data.'); - } - if (oType !== 'Undefined') { - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); - } - return true; -}; diff --git a/node_modules/es-abstract/2015/WeekDay.js b/node_modules/es-abstract/2015/WeekDay.js deleted file mode 100644 index 2973e02..0000000 --- a/node_modules/es-abstract/2015/WeekDay.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -var Day = require('./Day'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.6 - -module.exports = function WeekDay(t) { - return mod(Day(t) + 4, 7); -}; diff --git a/node_modules/es-abstract/2015/YearFromTime.js b/node_modules/es-abstract/2015/YearFromTime.js deleted file mode 100644 index ff5339f..0000000 --- a/node_modules/es-abstract/2015/YearFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Date = GetIntrinsic('%Date%'); - -var callBound = require('../helpers/callBound'); - -var $getUTCFullYear = callBound('Date.prototype.getUTCFullYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function YearFromTime(t) { - // largest y such that this.TimeFromYear(y) <= t - return $getUTCFullYear(new $Date(t)); -}; diff --git a/node_modules/es-abstract/2015/modulo.js b/node_modules/es-abstract/2015/modulo.js deleted file mode 100644 index bc04c06..0000000 --- a/node_modules/es-abstract/2015/modulo.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -// https://ecma-international.org/ecma-262/5.1/#sec-5.2 - -module.exports = function modulo(x, y) { - return mod(x, y); -}; diff --git a/node_modules/es-abstract/2015/msFromTime.js b/node_modules/es-abstract/2015/msFromTime.js deleted file mode 100644 index c31eda0..0000000 --- a/node_modules/es-abstract/2015/msFromTime.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); -var msPerSecond = require('../helpers/timeConstants').msPerSecond; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function msFromTime(t) { - return mod(t, msPerSecond); -}; diff --git a/node_modules/es-abstract/2015/thisBooleanValue.js b/node_modules/es-abstract/2015/thisBooleanValue.js deleted file mode 100644 index 3ffac9c..0000000 --- a/node_modules/es-abstract/2015/thisBooleanValue.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var $BooleanValueOf = require('../helpers/callBound')('Boolean.prototype.valueOf'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-boolean-prototype-object - -module.exports = function thisBooleanValue(value) { - if (Type(value) === 'Boolean') { - return value; - } - - return $BooleanValueOf(value); -}; diff --git a/node_modules/es-abstract/2015/thisNumberValue.js b/node_modules/es-abstract/2015/thisNumberValue.js deleted file mode 100644 index 0345e52..0000000 --- a/node_modules/es-abstract/2015/thisNumberValue.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var Type = require('./Type'); - -var $NumberValueOf = callBound('Number.prototype.valueOf'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-number-prototype-object - -module.exports = function thisNumberValue(value) { - if (Type(value) === 'Number') { - return value; - } - - return $NumberValueOf(value); -}; - diff --git a/node_modules/es-abstract/2015/thisStringValue.js b/node_modules/es-abstract/2015/thisStringValue.js deleted file mode 100644 index 3b99b6e..0000000 --- a/node_modules/es-abstract/2015/thisStringValue.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var $StringValueOf = require('../helpers/callBound')('String.prototype.valueOf'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-string-prototype-object - -module.exports = function thisStringValue(value) { - if (Type(value) === 'String') { - return value; - } - - return $StringValueOf(value); -}; diff --git a/node_modules/es-abstract/2015/thisTimeValue.js b/node_modules/es-abstract/2015/thisTimeValue.js deleted file mode 100644 index d7cda28..0000000 --- a/node_modules/es-abstract/2015/thisTimeValue.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var $DateValueOf = require('../helpers/callBound')('Date.prototype.valueOf'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-date-prototype-object - -module.exports = function thisTimeValue(value) { - return $DateValueOf(value); -}; diff --git a/node_modules/es-abstract/2016/AbstractEqualityComparison.js b/node_modules/es-abstract/2016/AbstractEqualityComparison.js deleted file mode 100644 index 40b3909..0000000 --- a/node_modules/es-abstract/2016/AbstractEqualityComparison.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); -var ToPrimitive = require('./ToPrimitive'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison - -module.exports = function AbstractEqualityComparison(x, y) { - var xType = Type(x); - var yType = Type(y); - if (xType === yType) { - return x === y; // ES6+ specified this shortcut anyways. - } - if (x == null && y == null) { - return true; - } - if (xType === 'Number' && yType === 'String') { - return AbstractEqualityComparison(x, ToNumber(y)); - } - if (xType === 'String' && yType === 'Number') { - return AbstractEqualityComparison(ToNumber(x), y); - } - if (xType === 'Boolean') { - return AbstractEqualityComparison(ToNumber(x), y); - } - if (yType === 'Boolean') { - return AbstractEqualityComparison(x, ToNumber(y)); - } - if ((xType === 'String' || xType === 'Number' || xType === 'Symbol') && yType === 'Object') { - return AbstractEqualityComparison(x, ToPrimitive(y)); - } - if (xType === 'Object' && (yType === 'String' || yType === 'Number' || yType === 'Symbol')) { - return AbstractEqualityComparison(ToPrimitive(x), y); - } - return false; -}; diff --git a/node_modules/es-abstract/2016/AbstractRelationalComparison.js b/node_modules/es-abstract/2016/AbstractRelationalComparison.js deleted file mode 100644 index bc7ca83..0000000 --- a/node_modules/es-abstract/2016/AbstractRelationalComparison.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Number = GetIntrinsic('%Number%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var isPrefixOf = require('../helpers/isPrefixOf'); - -var ToNumber = require('./ToNumber'); -var ToPrimitive = require('./ToPrimitive'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5 - -// eslint-disable-next-line max-statements -module.exports = function AbstractRelationalComparison(x, y, LeftFirst) { - if (Type(LeftFirst) !== 'Boolean') { - throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean'); - } - var px; - var py; - if (LeftFirst) { - px = ToPrimitive(x, $Number); - py = ToPrimitive(y, $Number); - } else { - py = ToPrimitive(y, $Number); - px = ToPrimitive(x, $Number); - } - var bothStrings = Type(px) === 'String' && Type(py) === 'String'; - if (!bothStrings) { - var nx = ToNumber(px); - var ny = ToNumber(py); - if ($isNaN(nx) || $isNaN(ny)) { - return undefined; - } - if ($isFinite(nx) && $isFinite(ny) && nx === ny) { - return false; - } - if (nx === 0 && ny === 0) { - return false; - } - if (nx === Infinity) { - return false; - } - if (ny === Infinity) { - return true; - } - if (ny === -Infinity) { - return false; - } - if (nx === -Infinity) { - return true; - } - return nx < ny; // by now, these are both nonzero, finite, and not equal - } - if (isPrefixOf(py, px)) { - return false; - } - if (isPrefixOf(px, py)) { - return true; - } - return px < py; // both strings, neither a prefix of the other. shortcut for steps c-f -}; diff --git a/node_modules/es-abstract/2016/AdvanceStringIndex.js b/node_modules/es-abstract/2016/AdvanceStringIndex.js deleted file mode 100644 index 666f578..0000000 --- a/node_modules/es-abstract/2016/AdvanceStringIndex.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var IsInteger = require('./IsInteger'); -var Type = require('./Type'); - -var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $charCodeAt = require('../helpers/callBound')('String.prototype.charCodeAt'); - -// https://ecma-international.org/ecma-262/6.0/#sec-advancestringindex - -module.exports = function AdvanceStringIndex(S, index, unicode) { - if (Type(S) !== 'String') { - throw new $TypeError('Assertion failed: `S` must be a String'); - } - if (!IsInteger(index) || index < 0 || index > MAX_SAFE_INTEGER) { - throw new $TypeError('Assertion failed: `length` must be an integer >= 0 and <= 2**53'); - } - if (Type(unicode) !== 'Boolean') { - throw new $TypeError('Assertion failed: `unicode` must be a Boolean'); - } - if (!unicode) { - return index + 1; - } - var length = S.length; - if ((index + 1) >= length) { - return index + 1; - } - - var first = $charCodeAt(S, index); - if (first < 0xD800 || first > 0xDBFF) { - return index + 1; - } - - var second = $charCodeAt(S, index + 1); - if (second < 0xDC00 || second > 0xDFFF) { - return index + 1; - } - - return index + 2; -}; diff --git a/node_modules/es-abstract/2016/ArrayCreate.js b/node_modules/es-abstract/2016/ArrayCreate.js deleted file mode 100644 index fc9a7cf..0000000 --- a/node_modules/es-abstract/2016/ArrayCreate.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $ArrayPrototype = GetIntrinsic('%Array.prototype%'); -var $RangeError = GetIntrinsic('%RangeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsInteger = require('./IsInteger'); - -var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1; - -var $setProto = GetIntrinsic('%Object.setPrototypeOf%', true) || ( - // eslint-disable-next-line no-proto, no-negated-condition - [].__proto__ !== $ArrayPrototype - ? null - : function (O, proto) { - O.__proto__ = proto; // eslint-disable-line no-proto, no-param-reassign - return O; - } -); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-arraycreate - -module.exports = function ArrayCreate(length) { - if (!IsInteger(length) || length < 0) { - throw new $TypeError('Assertion failed: `length` must be an integer Number >= 0'); - } - if (length > MAX_ARRAY_LENGTH) { - throw new $RangeError('length is greater than (2**32 - 1)'); - } - var proto = arguments.length > 1 ? arguments[1] : $ArrayPrototype; - var A = []; // steps 5 - 7, and 9 - if (proto !== $ArrayPrototype) { // step 8 - if (!$setProto) { - throw new $SyntaxError('ArrayCreate: a `proto` argument that is not `Array.prototype` is not supported in an environment that does not support setting the [[Prototype]]'); - } - $setProto(A, proto); - } - if (length !== 0) { // bypasses the need for step 2 - A.length = length; - } - /* step 10, the above as a shortcut for the below - OrdinaryDefineOwnProperty(A, 'length', { - '[[Configurable]]': false, - '[[Enumerable]]': false, - '[[Value]]': length, - '[[Writable]]': true - }); - */ - return A; -}; diff --git a/node_modules/es-abstract/2016/ArraySetLength.js b/node_modules/es-abstract/2016/ArraySetLength.js deleted file mode 100644 index c9134c6..0000000 --- a/node_modules/es-abstract/2016/ArraySetLength.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $RangeError = GetIntrinsic('%RangeError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var assign = require('object.assign'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var IsArray = require('./IsArray'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var OrdinaryDefineOwnProperty = require('./OrdinaryDefineOwnProperty'); -var OrdinaryGetOwnProperty = require('./OrdinaryGetOwnProperty'); -var ToNumber = require('./ToNumber'); -var ToString = require('./ToString'); -var ToUint32 = require('./ToUint32'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-arraysetlength - -// eslint-disable-next-line max-statements, max-lines-per-function -module.exports = function ArraySetLength(A, Desc) { - if (!IsArray(A)) { - throw new $TypeError('Assertion failed: A must be an Array'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (!('[[Value]]' in Desc)) { - return OrdinaryDefineOwnProperty(A, 'length', Desc); - } - var newLenDesc = assign({}, Desc); - var newLen = ToUint32(Desc['[[Value]]']); - var numberLen = ToNumber(Desc['[[Value]]']); - if (newLen !== numberLen) { - throw new $RangeError('Invalid array length'); - } - newLenDesc['[[Value]]'] = newLen; - var oldLenDesc = OrdinaryGetOwnProperty(A, 'length'); - if (!IsDataDescriptor(oldLenDesc)) { - throw new $TypeError('Assertion failed: an array had a non-data descriptor on `length`'); - } - var oldLen = oldLenDesc['[[Value]]']; - if (newLen >= oldLen) { - return OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - } - if (!oldLenDesc['[[Writable]]']) { - return false; - } - var newWritable; - if (!('[[Writable]]' in newLenDesc) || newLenDesc['[[Writable]]']) { - newWritable = true; - } else { - newWritable = false; - newLenDesc['[[Writable]]'] = true; - } - var succeeded = OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - if (!succeeded) { - return false; - } - while (newLen < oldLen) { - oldLen -= 1; - // eslint-disable-next-line no-param-reassign - var deleteSucceeded = delete A[ToString(oldLen)]; - if (!deleteSucceeded) { - newLenDesc['[[Value]]'] = oldLen + 1; - if (!newWritable) { - newLenDesc['[[Writable]]'] = false; - OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - return false; - } - } - } - if (!newWritable) { - return OrdinaryDefineOwnProperty(A, 'length', { '[[Writable]]': false }); - } - return true; -}; diff --git a/node_modules/es-abstract/2016/ArraySpeciesCreate.js b/node_modules/es-abstract/2016/ArraySpeciesCreate.js deleted file mode 100644 index 98b9b56..0000000 --- a/node_modules/es-abstract/2016/ArraySpeciesCreate.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Array = GetIntrinsic('%Array%'); -var $species = GetIntrinsic('%Symbol.species%', true); -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var IsConstructor = require('./IsConstructor'); -var IsInteger = require('./IsInteger'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-arrayspeciescreate - -module.exports = function ArraySpeciesCreate(originalArray, length) { - if (!IsInteger(length) || length < 0) { - throw new $TypeError('Assertion failed: length must be an integer >= 0'); - } - var len = length === 0 ? 0 : length; - var C; - var isArray = IsArray(originalArray); - if (isArray) { - C = Get(originalArray, 'constructor'); - // TODO: figure out how to make a cross-realm normal Array, a same-realm Array - // if (IsConstructor(C)) { - // if C is another realm's Array, C = undefined - // Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Array))) === null ? - // } - if ($species && Type(C) === 'Object') { - C = Get(C, $species); - if (C === null) { - C = void 0; - } - } - } - if (typeof C === 'undefined') { - return $Array(len); - } - if (!IsConstructor(C)) { - throw new $TypeError('C must be a constructor'); - } - return new C(len); // Construct(C, len); -}; - diff --git a/node_modules/es-abstract/2016/Call.js b/node_modules/es-abstract/2016/Call.js deleted file mode 100644 index f31960d..0000000 --- a/node_modules/es-abstract/2016/Call.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var inspect = require('object-inspect'); - -var IsCallable = require('./IsCallable'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-call - -module.exports = function Call(F, V) { - var args = arguments.length > 2 ? arguments[2] : []; - if (!IsCallable(F)) { - throw new $TypeError(inspect(F) + ' is not a function'); - } - return F.apply(V, args); -}; diff --git a/node_modules/es-abstract/2016/CanonicalNumericIndexString.js b/node_modules/es-abstract/2016/CanonicalNumericIndexString.js deleted file mode 100644 index 625f853..0000000 --- a/node_modules/es-abstract/2016/CanonicalNumericIndexString.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var SameValue = require('./SameValue'); -var ToNumber = require('./ToNumber'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-canonicalnumericindexstring - -module.exports = function CanonicalNumericIndexString(argument) { - if (Type(argument) !== 'String') { - throw new $TypeError('Assertion failed: `argument` must be a String'); - } - if (argument === '-0') { return -0; } - var n = ToNumber(argument); - if (SameValue(ToString(n), argument)) { return n; } - return void 0; -}; diff --git a/node_modules/es-abstract/2016/CompletePropertyDescriptor.js b/node_modules/es-abstract/2016/CompletePropertyDescriptor.js deleted file mode 100644 index 548bf41..0000000 --- a/node_modules/es-abstract/2016/CompletePropertyDescriptor.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsGenericDescriptor = require('./IsGenericDescriptor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-completepropertydescriptor - -module.exports = function CompletePropertyDescriptor(Desc) { - /* eslint no-param-reassign: 0 */ - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (IsGenericDescriptor(Desc) || IsDataDescriptor(Desc)) { - if (!has(Desc, '[[Value]]')) { - Desc['[[Value]]'] = void 0; - } - if (!has(Desc, '[[Writable]]')) { - Desc['[[Writable]]'] = false; - } - } else { - if (!has(Desc, '[[Get]]')) { - Desc['[[Get]]'] = void 0; - } - if (!has(Desc, '[[Set]]')) { - Desc['[[Set]]'] = void 0; - } - } - if (!has(Desc, '[[Enumerable]]')) { - Desc['[[Enumerable]]'] = false; - } - if (!has(Desc, '[[Configurable]]')) { - Desc['[[Configurable]]'] = false; - } - return Desc; -}; diff --git a/node_modules/es-abstract/2016/CreateDataProperty.js b/node_modules/es-abstract/2016/CreateDataProperty.js deleted file mode 100644 index 32a86ef..0000000 --- a/node_modules/es-abstract/2016/CreateDataProperty.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var OrdinaryGetOwnProperty = require('./OrdinaryGetOwnProperty'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createdataproperty - -module.exports = function CreateDataProperty(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - var oldDesc = OrdinaryGetOwnProperty(O, P); - var extensible = !oldDesc || IsExtensible(O); - var immutable = oldDesc && (!oldDesc['[[Writable]]'] || !oldDesc['[[Configurable]]']); - if (immutable || !extensible) { - return false; - } - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': true, - '[[Enumerable]]': true, - '[[Value]]': V, - '[[Writable]]': true - } - ); -}; diff --git a/node_modules/es-abstract/2016/CreateDataPropertyOrThrow.js b/node_modules/es-abstract/2016/CreateDataPropertyOrThrow.js deleted file mode 100644 index 9feaec8..0000000 --- a/node_modules/es-abstract/2016/CreateDataPropertyOrThrow.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var CreateDataProperty = require('./CreateDataProperty'); -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// // https://ecma-international.org/ecma-262/6.0/#sec-createdatapropertyorthrow - -module.exports = function CreateDataPropertyOrThrow(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - var success = CreateDataProperty(O, P, V); - if (!success) { - throw new $TypeError('unable to create data property'); - } - return success; -}; diff --git a/node_modules/es-abstract/2016/CreateHTML.js b/node_modules/es-abstract/2016/CreateHTML.js deleted file mode 100644 index 536c92d..0000000 --- a/node_modules/es-abstract/2016/CreateHTML.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $replace = callBound('String.prototype.replace'); - -var RequireObjectCoercible = require('./RequireObjectCoercible'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createhtml - -module.exports = function CreateHTML(string, tag, attribute, value) { - if (Type(tag) !== 'String' || Type(attribute) !== 'String') { - throw new $TypeError('Assertion failed: `tag` and `attribute` must be strings'); - } - var str = RequireObjectCoercible(string); - var S = ToString(str); - var p1 = '<' + tag; - if (attribute !== '') { - var V = ToString(value); - var escapedV = $replace(V, /\x22/g, '"'); - p1 += '\x20' + attribute + '\x3D\x22' + escapedV + '\x22'; - } - return p1 + '>' + S + ''; -}; diff --git a/node_modules/es-abstract/2016/CreateIterResultObject.js b/node_modules/es-abstract/2016/CreateIterResultObject.js deleted file mode 100644 index aef1d22..0000000 --- a/node_modules/es-abstract/2016/CreateIterResultObject.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-createiterresultobject - -module.exports = function CreateIterResultObject(value, done) { - if (Type(done) !== 'Boolean') { - throw new $TypeError('Assertion failed: Type(done) is not Boolean'); - } - return { - value: value, - done: done - }; -}; diff --git a/node_modules/es-abstract/2016/CreateListFromArrayLike.js b/node_modules/es-abstract/2016/CreateListFromArrayLike.js deleted file mode 100644 index d6b44b5..0000000 --- a/node_modules/es-abstract/2016/CreateListFromArrayLike.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var callBound = require('../helpers/callBound'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $indexOf = callBound('Array.prototype.indexOf', true) || callBound('String.prototype.indexOf'); -var $push = callBound('Array.prototype.push'); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var ToLength = require('./ToLength'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-createlistfromarraylike -module.exports = function CreateListFromArrayLike(obj) { - var elementTypes = arguments.length > 1 - ? arguments[1] - : ['Undefined', 'Null', 'Boolean', 'String', 'Symbol', 'Number', 'Object']; - - if (Type(obj) !== 'Object') { - throw new $TypeError('Assertion failed: `obj` must be an Object'); - } - if (!IsArray(elementTypes)) { - throw new $TypeError('Assertion failed: `elementTypes`, if provided, must be an array'); - } - var len = ToLength(Get(obj, 'length')); - var list = []; - var index = 0; - while (index < len) { - var indexName = ToString(index); - var next = Get(obj, indexName); - var nextType = Type(next); - if ($indexOf(elementTypes, nextType) < 0) { - throw new $TypeError('item type ' + nextType + ' is not a valid elementType'); - } - $push(list, next); - index += 1; - } - return list; -}; diff --git a/node_modules/es-abstract/2016/CreateMethodProperty.js b/node_modules/es-abstract/2016/CreateMethodProperty.js deleted file mode 100644 index 5b599ae..0000000 --- a/node_modules/es-abstract/2016/CreateMethodProperty.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createmethodproperty - -module.exports = function CreateMethodProperty(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - var newDesc = { - '[[Configurable]]': true, - '[[Enumerable]]': false, - '[[Value]]': V, - '[[Writable]]': true - }; - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - newDesc - ); -}; diff --git a/node_modules/es-abstract/2016/DateFromTime.js b/node_modules/es-abstract/2016/DateFromTime.js deleted file mode 100644 index 962dba1..0000000 --- a/node_modules/es-abstract/2016/DateFromTime.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $EvalError = GetIntrinsic('%EvalError%'); - -var DayWithinYear = require('./DayWithinYear'); -var InLeapYear = require('./InLeapYear'); -var MonthFromTime = require('./MonthFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.5 - -module.exports = function DateFromTime(t) { - var m = MonthFromTime(t); - var d = DayWithinYear(t); - if (m === 0) { - return d + 1; - } - if (m === 1) { - return d - 30; - } - var leap = InLeapYear(t); - if (m === 2) { - return d - 58 - leap; - } - if (m === 3) { - return d - 89 - leap; - } - if (m === 4) { - return d - 119 - leap; - } - if (m === 5) { - return d - 150 - leap; - } - if (m === 6) { - return d - 180 - leap; - } - if (m === 7) { - return d - 211 - leap; - } - if (m === 8) { - return d - 242 - leap; - } - if (m === 9) { - return d - 272 - leap; - } - if (m === 10) { - return d - 303 - leap; - } - if (m === 11) { - return d - 333 - leap; - } - throw new $EvalError('Assertion failed: MonthFromTime returned an impossible value: ' + m); -}; diff --git a/node_modules/es-abstract/2016/Day.js b/node_modules/es-abstract/2016/Day.js deleted file mode 100644 index 00df813..0000000 --- a/node_modules/es-abstract/2016/Day.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - -module.exports = function Day(t) { - return $floor(t / msPerDay); -}; diff --git a/node_modules/es-abstract/2016/DayFromYear.js b/node_modules/es-abstract/2016/DayFromYear.js deleted file mode 100644 index 08dd5af..0000000 --- a/node_modules/es-abstract/2016/DayFromYear.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function DayFromYear(y) { - return (365 * (y - 1970)) + $floor((y - 1969) / 4) - $floor((y - 1901) / 100) + $floor((y - 1601) / 400); -}; - diff --git a/node_modules/es-abstract/2016/DayWithinYear.js b/node_modules/es-abstract/2016/DayWithinYear.js deleted file mode 100644 index cfc4002..0000000 --- a/node_modules/es-abstract/2016/DayWithinYear.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var Day = require('./Day'); -var DayFromYear = require('./DayFromYear'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - -module.exports = function DayWithinYear(t) { - return Day(t) - DayFromYear(YearFromTime(t)); -}; diff --git a/node_modules/es-abstract/2016/DaysInYear.js b/node_modules/es-abstract/2016/DaysInYear.js deleted file mode 100644 index db32251..0000000 --- a/node_modules/es-abstract/2016/DaysInYear.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function DaysInYear(y) { - if (mod(y, 4) !== 0) { - return 365; - } - if (mod(y, 100) !== 0) { - return 366; - } - if (mod(y, 400) !== 0) { - return 365; - } - return 366; -}; diff --git a/node_modules/es-abstract/2016/DefinePropertyOrThrow.js b/node_modules/es-abstract/2016/DefinePropertyOrThrow.js deleted file mode 100644 index 7977f6e..0000000 --- a/node_modules/es-abstract/2016/DefinePropertyOrThrow.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-definepropertyorthrow - -module.exports = function DefinePropertyOrThrow(O, P, desc) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - var Desc = isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, desc) ? desc : ToPropertyDescriptor(desc); - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc is not a valid Property Descriptor'); - } - - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); -}; diff --git a/node_modules/es-abstract/2016/DeletePropertyOrThrow.js b/node_modules/es-abstract/2016/DeletePropertyOrThrow.js deleted file mode 100644 index b476817..0000000 --- a/node_modules/es-abstract/2016/DeletePropertyOrThrow.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-deletepropertyorthrow - -module.exports = function DeletePropertyOrThrow(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // eslint-disable-next-line no-param-reassign - var success = delete O[P]; - if (!success) { - throw new $TypeError('Attempt to delete property failed.'); - } - return success; -}; diff --git a/node_modules/es-abstract/2016/EnumerableOwnNames.js b/node_modules/es-abstract/2016/EnumerableOwnNames.js deleted file mode 100644 index d068584..0000000 --- a/node_modules/es-abstract/2016/EnumerableOwnNames.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var keys = require('object-keys'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-enumerableownnames - -module.exports = function EnumerableOwnNames(O) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - return keys(O); -}; diff --git a/node_modules/es-abstract/2016/FromPropertyDescriptor.js b/node_modules/es-abstract/2016/FromPropertyDescriptor.js deleted file mode 100644 index 5ec200e..0000000 --- a/node_modules/es-abstract/2016/FromPropertyDescriptor.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-frompropertydescriptor - -module.exports = function FromPropertyDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return Desc; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - var obj = {}; - if ('[[Value]]' in Desc) { - obj.value = Desc['[[Value]]']; - } - if ('[[Writable]]' in Desc) { - obj.writable = Desc['[[Writable]]']; - } - if ('[[Get]]' in Desc) { - obj.get = Desc['[[Get]]']; - } - if ('[[Set]]' in Desc) { - obj.set = Desc['[[Set]]']; - } - if ('[[Enumerable]]' in Desc) { - obj.enumerable = Desc['[[Enumerable]]']; - } - if ('[[Configurable]]' in Desc) { - obj.configurable = Desc['[[Configurable]]']; - } - return obj; -}; diff --git a/node_modules/es-abstract/2016/Get.js b/node_modules/es-abstract/2016/Get.js deleted file mode 100644 index 5b9ad78..0000000 --- a/node_modules/es-abstract/2016/Get.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var inspect = require('object-inspect'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -/** - * 7.3.1 Get (O, P) - https://ecma-international.org/ecma-262/6.0/#sec-get-o-p - * 1. Assert: Type(O) is Object. - * 2. Assert: IsPropertyKey(P) is true. - * 3. Return O.[[Get]](P, O). - */ - -module.exports = function Get(O, P) { - // 7.3.1.1 - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - // 7.3.1.2 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true, got ' + inspect(P)); - } - // 7.3.1.3 - return O[P]; -}; diff --git a/node_modules/es-abstract/2016/GetIterator.js b/node_modules/es-abstract/2016/GetIterator.js deleted file mode 100644 index 7beddac..0000000 --- a/node_modules/es-abstract/2016/GetIterator.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var getIteratorMethod = require('../helpers/getIteratorMethod'); -var AdvanceStringIndex = require('./AdvanceStringIndex'); -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsArray = require('./IsArray'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-getiterator - -module.exports = function GetIterator(obj, method) { - var actualMethod = method; - if (arguments.length < 2) { - actualMethod = getIteratorMethod( - { - AdvanceStringIndex: AdvanceStringIndex, - GetMethod: GetMethod, - IsArray: IsArray, - Type: Type - }, - obj - ); - } - var iterator = Call(actualMethod, obj); - if (Type(iterator) !== 'Object') { - throw new $TypeError('iterator must return an object'); - } - - return iterator; -}; diff --git a/node_modules/es-abstract/2016/GetMethod.js b/node_modules/es-abstract/2016/GetMethod.js deleted file mode 100644 index aef8cbc..0000000 --- a/node_modules/es-abstract/2016/GetMethod.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var GetV = require('./GetV'); -var IsCallable = require('./IsCallable'); -var IsPropertyKey = require('./IsPropertyKey'); - -/** - * 7.3.9 - https://ecma-international.org/ecma-262/6.0/#sec-getmethod - * 1. Assert: IsPropertyKey(P) is true. - * 2. Let func be GetV(O, P). - * 3. ReturnIfAbrupt(func). - * 4. If func is either undefined or null, return undefined. - * 5. If IsCallable(func) is false, throw a TypeError exception. - * 6. Return func. - */ - -module.exports = function GetMethod(O, P) { - // 7.3.9.1 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // 7.3.9.2 - var func = GetV(O, P); - - // 7.3.9.4 - if (func == null) { - return void 0; - } - - // 7.3.9.5 - if (!IsCallable(func)) { - throw new $TypeError(P + 'is not a function'); - } - - // 7.3.9.6 - return func; -}; diff --git a/node_modules/es-abstract/2016/GetOwnPropertyKeys.js b/node_modules/es-abstract/2016/GetOwnPropertyKeys.js deleted file mode 100644 index 8d7e5ee..0000000 --- a/node_modules/es-abstract/2016/GetOwnPropertyKeys.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var hasSymbols = require('has-symbols')(); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); -var $gOPS = hasSymbols && GetIntrinsic('%Object.getOwnPropertySymbols%'); -var keys = require('object-keys'); - -var esType = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-getownpropertykeys - -module.exports = function GetOwnPropertyKeys(O, Type) { - if (esType(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (Type === 'Symbol') { - return $gOPS ? $gOPS(O) : []; - } - if (Type === 'String') { - if (!$gOPN) { - return keys(O); - } - return $gOPN(O); - } - throw new $TypeError('Assertion failed: `Type` must be `"String"` or `"Symbol"`'); -}; diff --git a/node_modules/es-abstract/2016/GetPrototypeFromConstructor.js b/node_modules/es-abstract/2016/GetPrototypeFromConstructor.js deleted file mode 100644 index 62da8fb..0000000 --- a/node_modules/es-abstract/2016/GetPrototypeFromConstructor.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Function = GetIntrinsic('%Function%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsConstructor = require('./IsConstructor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-getprototypefromconstructor - -module.exports = function GetPrototypeFromConstructor(constructor, intrinsicDefaultProto) { - var intrinsic = GetIntrinsic(intrinsicDefaultProto); // throws if not a valid intrinsic - if (!IsConstructor(constructor)) { - throw new $TypeError('Assertion failed: `constructor` must be a constructor'); - } - var proto = Get(constructor, 'prototype'); - if (Type(proto) !== 'Object') { - if (!(constructor instanceof $Function)) { - // ignore other realms, for now - throw new $TypeError('cross-realm constructors not currently supported'); - } - proto = intrinsic; - } - return proto; -}; diff --git a/node_modules/es-abstract/2016/GetSubstitution.js b/node_modules/es-abstract/2016/GetSubstitution.js deleted file mode 100644 index de41b01..0000000 --- a/node_modules/es-abstract/2016/GetSubstitution.js +++ /dev/null @@ -1,104 +0,0 @@ - -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $parseInt = GetIntrinsic('%parseInt%'); - -var inspect = require('object-inspect'); - -var regexTester = require('../helpers/regexTester'); -var callBound = require('../helpers/callBound'); -var every = require('../helpers/every'); - -var isDigit = regexTester(/^[0-9]$/); - -var $charAt = callBound('String.prototype.charAt'); -var $strSlice = callBound('String.prototype.slice'); - -var IsArray = require('./IsArray'); -var IsInteger = require('./IsInteger'); -var Type = require('./Type'); - -var canDistinguishSparseFromUndefined = 0 in [undefined]; // IE 6 - 8 have a bug where this returns false - -var isStringOrHole = function (capture, index, arr) { - return Type(capture) === 'String' || (canDistinguishSparseFromUndefined ? !(index in arr) : Type(capture) === 'Undefined'); -}; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-getsubstitution - -// eslint-disable-next-line max-statements, max-params, max-lines-per-function -module.exports = function GetSubstitution(matched, str, position, captures, replacement) { - if (Type(matched) !== 'String') { - throw new $TypeError('Assertion failed: `matched` must be a String'); - } - var matchLength = matched.length; - - if (Type(str) !== 'String') { - throw new $TypeError('Assertion failed: `str` must be a String'); - } - var stringLength = str.length; - - if (!IsInteger(position) || position < 0 || position > stringLength) { - throw new $TypeError('Assertion failed: `position` must be a nonnegative integer, and less than or equal to the length of `string`, got ' + inspect(position)); - } - - if (!IsArray(captures) || !every(captures, isStringOrHole)) { - throw new $TypeError('Assertion failed: `captures` must be a List of Strings, got ' + inspect(captures)); - } - - if (Type(replacement) !== 'String') { - throw new $TypeError('Assertion failed: `replacement` must be a String'); - } - - var tailPos = position + matchLength; - var m = captures.length; - - var result = ''; - for (var i = 0; i < replacement.length; i += 1) { - // if this is a $, and it's not the end of the replacement - var current = $charAt(replacement, i); - var isLast = (i + 1) >= replacement.length; - var nextIsLast = (i + 2) >= replacement.length; - if (current === '$' && !isLast) { - var next = $charAt(replacement, i + 1); - if (next === '$') { - result += '$'; - i += 1; - } else if (next === '&') { - result += matched; - i += 1; - } else if (next === '`') { - result += position === 0 ? '' : $strSlice(str, 0, position - 1); - i += 1; - } else if (next === "'") { - result += tailPos >= stringLength ? '' : $strSlice(str, tailPos); - i += 1; - } else { - var nextNext = nextIsLast ? null : $charAt(replacement, i + 2); - if (isDigit(next) && next !== '0' && (nextIsLast || !isDigit(nextNext))) { - // $1 through $9, and not followed by a digit - var n = $parseInt(next, 10); - // if (n > m, impl-defined) - result += (n <= m && Type(captures[n - 1]) === 'Undefined') ? '' : captures[n - 1]; - i += 1; - } else if (isDigit(next) && (nextIsLast || isDigit(nextNext))) { - // $00 through $99 - var nn = next + nextNext; - var nnI = $parseInt(nn, 10) - 1; - // if nn === '00' or nn > m, impl-defined - result += (nn <= m && Type(captures[nnI]) === 'Undefined') ? '' : captures[nnI]; - i += 2; - } else { - result += '$'; - } - } - } else { - // the final $, or else not a $ - result += $charAt(replacement, i); - } - } - return result; -}; diff --git a/node_modules/es-abstract/2016/GetV.js b/node_modules/es-abstract/2016/GetV.js deleted file mode 100644 index 7b5139a..0000000 --- a/node_modules/es-abstract/2016/GetV.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var ToObject = require('./ToObject'); - -/** - * 7.3.2 GetV (V, P) - * 1. Assert: IsPropertyKey(P) is true. - * 2. Let O be ToObject(V). - * 3. ReturnIfAbrupt(O). - * 4. Return O.[[Get]](P, V). - */ - -module.exports = function GetV(V, P) { - // 7.3.2.1 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // 7.3.2.2-3 - var O = ToObject(V); - - // 7.3.2.4 - return O[P]; -}; diff --git a/node_modules/es-abstract/2016/HasOwnProperty.js b/node_modules/es-abstract/2016/HasOwnProperty.js deleted file mode 100644 index 679059f..0000000 --- a/node_modules/es-abstract/2016/HasOwnProperty.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var has = require('has'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-hasownproperty - -module.exports = function HasOwnProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - return has(O, P); -}; diff --git a/node_modules/es-abstract/2016/HasProperty.js b/node_modules/es-abstract/2016/HasProperty.js deleted file mode 100644 index 5f2d212..0000000 --- a/node_modules/es-abstract/2016/HasProperty.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-hasproperty - -module.exports = function HasProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - return P in O; -}; diff --git a/node_modules/es-abstract/2016/HourFromTime.js b/node_modules/es-abstract/2016/HourFromTime.js deleted file mode 100644 index 957ce32..0000000 --- a/node_modules/es-abstract/2016/HourFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerHour = timeConstants.msPerHour; -var HoursPerDay = timeConstants.HoursPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function HourFromTime(t) { - return mod($floor(t / msPerHour), HoursPerDay); -}; diff --git a/node_modules/es-abstract/2016/InLeapYear.js b/node_modules/es-abstract/2016/InLeapYear.js deleted file mode 100644 index 38ba8fd..0000000 --- a/node_modules/es-abstract/2016/InLeapYear.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $EvalError = GetIntrinsic('%EvalError%'); - -var DaysInYear = require('./DaysInYear'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function InLeapYear(t) { - var days = DaysInYear(YearFromTime(t)); - if (days === 365) { - return 0; - } - if (days === 366) { - return 1; - } - throw new $EvalError('Assertion failed: there are not 365 or 366 days in a year, got: ' + days); -}; diff --git a/node_modules/es-abstract/2016/InstanceofOperator.js b/node_modules/es-abstract/2016/InstanceofOperator.js deleted file mode 100644 index ebd308c..0000000 --- a/node_modules/es-abstract/2016/InstanceofOperator.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $hasInstance = GetIntrinsic('Symbol.hasInstance', true); - -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsCallable = require('./IsCallable'); -var OrdinaryHasInstance = require('./OrdinaryHasInstance'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-instanceofoperator - -module.exports = function InstanceofOperator(O, C) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - var instOfHandler = $hasInstance ? GetMethod(C, $hasInstance) : void 0; - if (typeof instOfHandler !== 'undefined') { - return ToBoolean(Call(instOfHandler, C, [O])); - } - if (!IsCallable(C)) { - throw new $TypeError('`C` is not Callable'); - } - return OrdinaryHasInstance(C, O); -}; diff --git a/node_modules/es-abstract/2016/Invoke.js b/node_modules/es-abstract/2016/Invoke.js deleted file mode 100644 index 769f0e3..0000000 --- a/node_modules/es-abstract/2016/Invoke.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $arraySlice = require('../helpers/callBound')('Array.prototype.slice'); - -var Call = require('./Call'); -var GetV = require('./GetV'); -var IsPropertyKey = require('./IsPropertyKey'); - -// https://ecma-international.org/ecma-262/6.0/#sec-invoke - -module.exports = function Invoke(O, P) { - if (!IsPropertyKey(P)) { - throw new $TypeError('P must be a Property Key'); - } - var argumentsList = $arraySlice(arguments, 2); - var func = GetV(O, P); - return Call(func, O, argumentsList); -}; diff --git a/node_modules/es-abstract/2016/IsAccessorDescriptor.js b/node_modules/es-abstract/2016/IsAccessorDescriptor.js deleted file mode 100644 index 5139464..0000000 --- a/node_modules/es-abstract/2016/IsAccessorDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isaccessordescriptor - -module.exports = function IsAccessorDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) { - return false; - } - - return true; -}; diff --git a/node_modules/es-abstract/2016/IsArray.js b/node_modules/es-abstract/2016/IsArray.js deleted file mode 100644 index 7b25f37..0000000 --- a/node_modules/es-abstract/2016/IsArray.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Array = GetIntrinsic('%Array%'); - -// eslint-disable-next-line global-require -var toStr = !$Array.isArray && require('../helpers/callBound')('Object.prototype.toString'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isarray - -module.exports = $Array.isArray || function IsArray(argument) { - return toStr(argument) === '[object Array]'; -}; diff --git a/node_modules/es-abstract/2016/IsCallable.js b/node_modules/es-abstract/2016/IsCallable.js deleted file mode 100644 index e4bfa36..0000000 --- a/node_modules/es-abstract/2016/IsCallable.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.11 - -module.exports = require('is-callable'); diff --git a/node_modules/es-abstract/2016/IsConcatSpreadable.js b/node_modules/es-abstract/2016/IsConcatSpreadable.js deleted file mode 100644 index dc8aae1..0000000 --- a/node_modules/es-abstract/2016/IsConcatSpreadable.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $isConcatSpreadable = GetIntrinsic('%Symbol.isConcatSpreadable%', true); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-isconcatspreadable - -module.exports = function IsConcatSpreadable(O) { - if (Type(O) !== 'Object') { - return false; - } - if ($isConcatSpreadable) { - var spreadable = Get(O, $isConcatSpreadable); - if (typeof spreadable !== 'undefined') { - return ToBoolean(spreadable); - } - } - return IsArray(O); -}; diff --git a/node_modules/es-abstract/2016/IsConstructor.js b/node_modules/es-abstract/2016/IsConstructor.js deleted file mode 100644 index 00ea52c..0000000 --- a/node_modules/es-abstract/2016/IsConstructor.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isconstructor - -module.exports = function IsConstructor(argument) { - return typeof argument === 'function' && !!argument.prototype; // unfortunately there's no way to truly check this without try/catch `new argument` -}; diff --git a/node_modules/es-abstract/2016/IsDataDescriptor.js b/node_modules/es-abstract/2016/IsDataDescriptor.js deleted file mode 100644 index 0ad3045..0000000 --- a/node_modules/es-abstract/2016/IsDataDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isdatadescriptor - -module.exports = function IsDataDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) { - return false; - } - - return true; -}; diff --git a/node_modules/es-abstract/2016/IsExtensible.js b/node_modules/es-abstract/2016/IsExtensible.js deleted file mode 100644 index 0c4c8a6..0000000 --- a/node_modules/es-abstract/2016/IsExtensible.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Object = GetIntrinsic('%Object%'); - -var isPrimitive = require('../helpers/isPrimitive'); - -var $preventExtensions = $Object.preventExtensions; -var $isExtensible = $Object.isExtensible; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isextensible-o - -module.exports = $preventExtensions - ? function IsExtensible(obj) { - return !isPrimitive(obj) && $isExtensible(obj); - } - : function IsExtensible(obj) { - return !isPrimitive(obj); - }; diff --git a/node_modules/es-abstract/2016/IsGenericDescriptor.js b/node_modules/es-abstract/2016/IsGenericDescriptor.js deleted file mode 100644 index 8618ce4..0000000 --- a/node_modules/es-abstract/2016/IsGenericDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var assertRecord = require('../helpers/assertRecord'); - -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isgenericdescriptor - -module.exports = function IsGenericDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!IsAccessorDescriptor(Desc) && !IsDataDescriptor(Desc)) { - return true; - } - - return false; -}; diff --git a/node_modules/es-abstract/2016/IsInteger.js b/node_modules/es-abstract/2016/IsInteger.js deleted file mode 100644 index 0f488b3..0000000 --- a/node_modules/es-abstract/2016/IsInteger.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isinteger - -module.exports = function IsInteger(argument) { - if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) { - return false; - } - var abs = $abs(argument); - return $floor(abs) === abs; -}; diff --git a/node_modules/es-abstract/2016/IsPromise.js b/node_modules/es-abstract/2016/IsPromise.js deleted file mode 100644 index e8e92a2..0000000 --- a/node_modules/es-abstract/2016/IsPromise.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var $PromiseThen = callBound('Promise.prototype.then', true); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ispromise - -module.exports = function IsPromise(x) { - if (Type(x) !== 'Object') { - return false; - } - if (!$PromiseThen) { // Promises are not supported - return false; - } - try { - $PromiseThen(x); // throws if not a promise - } catch (e) { - return false; - } - return true; -}; diff --git a/node_modules/es-abstract/2016/IsPropertyDescriptor.js b/node_modules/es-abstract/2016/IsPropertyDescriptor.js deleted file mode 100644 index 2a96c63..0000000 --- a/node_modules/es-abstract/2016/IsPropertyDescriptor.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var Type = require('./Type'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); - -// https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type - -module.exports = function IsPropertyDescriptor(Desc) { - return isPropertyDescriptor({ - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor, - Type: Type - }, Desc); -}; diff --git a/node_modules/es-abstract/2016/IsPropertyKey.js b/node_modules/es-abstract/2016/IsPropertyKey.js deleted file mode 100644 index 74b8d95..0000000 --- a/node_modules/es-abstract/2016/IsPropertyKey.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ispropertykey - -module.exports = function IsPropertyKey(argument) { - return typeof argument === 'string' || typeof argument === 'symbol'; -}; diff --git a/node_modules/es-abstract/2016/IsRegExp.js b/node_modules/es-abstract/2016/IsRegExp.js deleted file mode 100644 index fdf2323..0000000 --- a/node_modules/es-abstract/2016/IsRegExp.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $match = GetIntrinsic('%Symbol.match%', true); - -var hasRegExpMatcher = require('is-regex'); - -var ToBoolean = require('./ToBoolean'); - -// https://ecma-international.org/ecma-262/6.0/#sec-isregexp - -module.exports = function IsRegExp(argument) { - if (!argument || typeof argument !== 'object') { - return false; - } - if ($match) { - var isRegExp = argument[$match]; - if (typeof isRegExp !== 'undefined') { - return ToBoolean(isRegExp); - } - } - return hasRegExpMatcher(argument); -}; diff --git a/node_modules/es-abstract/2016/IterableToArrayLike.js b/node_modules/es-abstract/2016/IterableToArrayLike.js deleted file mode 100644 index 2f26159..0000000 --- a/node_modules/es-abstract/2016/IterableToArrayLike.js +++ /dev/null @@ -1,74 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $iterator = GetIntrinsic('%Symbol.iterator%', true); - -var callBound = require('../helpers/callBound'); - -var $arrayJoin = callBound('Array.prototype.join'); -var $arrayPush = callBound('Array.prototype.push'); -var $stringSlice = callBound('String.prototype.slice'); -var $stringSplit = callBound('String.prototype.split'); - -var AdvanceStringIndex = require('./AdvanceStringIndex'); -var GetIterator = require('./GetIterator'); -var GetMethod = require('./GetMethod'); -var IsArray = require('./IsArray'); -var IteratorStep = require('./IteratorStep'); -var IteratorValue = require('./IteratorValue'); -var ToObject = require('./ToObject'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/7.0/#sec-iterabletoarraylike - -module.exports = function IterableToArrayLike(items) { - var usingIterator; - if ($iterator) { - usingIterator = GetMethod(items, $iterator); - } else if (IsArray(items)) { - usingIterator = function () { - var i = -1; - var arr = this; // eslint-disable-line no-invalid-this - return { - next: function () { - i += 1; - return { - done: i >= arr.length, - value: arr[i] - }; - } - }; - }; - } else if (Type(items) === 'String') { - usingIterator = function () { - var i = 0; - return { - next: function () { - var nextIndex = AdvanceStringIndex(items, i, true); - var value = $arrayJoin($stringSplit($stringSlice(items, i, nextIndex), ''), ''); - i = nextIndex; - return { - done: nextIndex > items.length, - value: value - }; - } - }; - }; - } - if (typeof usingIterator !== 'undefined') { - var iterator = GetIterator(items, usingIterator); - var values = []; - var next = true; - while (next) { - next = IteratorStep(iterator); - if (next) { - var nextValue = IteratorValue(next); - $arrayPush(values, nextValue); - } - } - return values; - } - - return ToObject(items); -}; diff --git a/node_modules/es-abstract/2016/IteratorClose.js b/node_modules/es-abstract/2016/IteratorClose.js deleted file mode 100644 index 35c8c2b..0000000 --- a/node_modules/es-abstract/2016/IteratorClose.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorclose - -module.exports = function IteratorClose(iterator, completion) { - if (Type(iterator) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterator) is not Object'); - } - if (!IsCallable(completion)) { - throw new $TypeError('Assertion failed: completion is not a thunk for a Completion Record'); - } - var completionThunk = completion; - - var iteratorReturn = GetMethod(iterator, 'return'); - - if (typeof iteratorReturn === 'undefined') { - return completionThunk(); - } - - var completionRecord; - try { - var innerResult = Call(iteratorReturn, iterator, []); - } catch (e) { - // if we hit here, then "e" is the innerResult completion that needs re-throwing - - // if the completion is of type "throw", this will throw. - completionThunk(); - completionThunk = null; // ensure it's not called twice. - - // if not, then return the innerResult completion - throw e; - } - completionRecord = completionThunk(); // if innerResult worked, then throw if the completion does - completionThunk = null; // ensure it's not called twice. - - if (Type(innerResult) !== 'Object') { - throw new $TypeError('iterator .return must return an object'); - } - - return completionRecord; -}; diff --git a/node_modules/es-abstract/2016/IteratorComplete.js b/node_modules/es-abstract/2016/IteratorComplete.js deleted file mode 100644 index a62b9bf..0000000 --- a/node_modules/es-abstract/2016/IteratorComplete.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorcomplete - -module.exports = function IteratorComplete(iterResult) { - if (Type(iterResult) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); - } - return ToBoolean(Get(iterResult, 'done')); -}; diff --git a/node_modules/es-abstract/2016/IteratorNext.js b/node_modules/es-abstract/2016/IteratorNext.js deleted file mode 100644 index 7e59915..0000000 --- a/node_modules/es-abstract/2016/IteratorNext.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Invoke = require('./Invoke'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratornext - -module.exports = function IteratorNext(iterator, value) { - var result = Invoke(iterator, 'next', arguments.length < 2 ? [] : [value]); - if (Type(result) !== 'Object') { - throw new $TypeError('iterator next must return an object'); - } - return result; -}; diff --git a/node_modules/es-abstract/2016/IteratorStep.js b/node_modules/es-abstract/2016/IteratorStep.js deleted file mode 100644 index 41b9d1b..0000000 --- a/node_modules/es-abstract/2016/IteratorStep.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var IteratorComplete = require('./IteratorComplete'); -var IteratorNext = require('./IteratorNext'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorstep - -module.exports = function IteratorStep(iterator) { - var result = IteratorNext(iterator); - var done = IteratorComplete(result); - return done === true ? false : result; -}; - diff --git a/node_modules/es-abstract/2016/IteratorValue.js b/node_modules/es-abstract/2016/IteratorValue.js deleted file mode 100644 index 5e71a44..0000000 --- a/node_modules/es-abstract/2016/IteratorValue.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorvalue - -module.exports = function IteratorValue(iterResult) { - if (Type(iterResult) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); - } - return Get(iterResult, 'value'); -}; - diff --git a/node_modules/es-abstract/2016/MakeDate.js b/node_modules/es-abstract/2016/MakeDate.js deleted file mode 100644 index 7b592d1..0000000 --- a/node_modules/es-abstract/2016/MakeDate.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $isFinite = require('../helpers/isFinite'); -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.13 - -module.exports = function MakeDate(day, time) { - if (!$isFinite(day) || !$isFinite(time)) { - return NaN; - } - return (day * msPerDay) + time; -}; diff --git a/node_modules/es-abstract/2016/MakeDay.js b/node_modules/es-abstract/2016/MakeDay.js deleted file mode 100644 index f1ab810..0000000 --- a/node_modules/es-abstract/2016/MakeDay.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); -var $DateUTC = GetIntrinsic('%Date.UTC%'); - -var mod = require('../helpers/mod'); -var $isFinite = require('../helpers/isFinite'); - -var DateFromTime = require('./DateFromTime'); -var Day = require('./Day'); -var MonthFromTime = require('./MonthFromTime'); -var ToInteger = require('./ToInteger'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.12 - -module.exports = function MakeDay(year, month, date) { - if (!$isFinite(year) || !$isFinite(month) || !$isFinite(date)) { - return NaN; - } - var y = ToInteger(year); - var m = ToInteger(month); - var dt = ToInteger(date); - var ym = y + $floor(m / 12); - var mn = mod(m, 12); - var t = $DateUTC(ym, mn, 1); - if (YearFromTime(t) !== ym || MonthFromTime(t) !== mn || DateFromTime(t) !== 1) { - return NaN; - } - return Day(t) + dt - 1; -}; diff --git a/node_modules/es-abstract/2016/MakeTime.js b/node_modules/es-abstract/2016/MakeTime.js deleted file mode 100644 index e118500..0000000 --- a/node_modules/es-abstract/2016/MakeTime.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var $isFinite = require('../helpers/isFinite'); -var timeConstants = require('../helpers/timeConstants'); -var msPerSecond = timeConstants.msPerSecond; -var msPerMinute = timeConstants.msPerMinute; -var msPerHour = timeConstants.msPerHour; - -var ToInteger = require('./ToInteger'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.11 - -module.exports = function MakeTime(hour, min, sec, ms) { - if (!$isFinite(hour) || !$isFinite(min) || !$isFinite(sec) || !$isFinite(ms)) { - return NaN; - } - var h = ToInteger(hour); - var m = ToInteger(min); - var s = ToInteger(sec); - var milli = ToInteger(ms); - var t = (h * msPerHour) + (m * msPerMinute) + (s * msPerSecond) + milli; - return t; -}; diff --git a/node_modules/es-abstract/2016/MinFromTime.js b/node_modules/es-abstract/2016/MinFromTime.js deleted file mode 100644 index e80e191..0000000 --- a/node_modules/es-abstract/2016/MinFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerMinute = timeConstants.msPerMinute; -var MinutesPerHour = timeConstants.MinutesPerHour; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function MinFromTime(t) { - return mod($floor(t / msPerMinute), MinutesPerHour); -}; diff --git a/node_modules/es-abstract/2016/MonthFromTime.js b/node_modules/es-abstract/2016/MonthFromTime.js deleted file mode 100644 index 4f120f2..0000000 --- a/node_modules/es-abstract/2016/MonthFromTime.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -var DayWithinYear = require('./DayWithinYear'); -var InLeapYear = require('./InLeapYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - -module.exports = function MonthFromTime(t) { - var day = DayWithinYear(t); - if (0 <= day && day < 31) { - return 0; - } - var leap = InLeapYear(t); - if (31 <= day && day < (59 + leap)) { - return 1; - } - if ((59 + leap) <= day && day < (90 + leap)) { - return 2; - } - if ((90 + leap) <= day && day < (120 + leap)) { - return 3; - } - if ((120 + leap) <= day && day < (151 + leap)) { - return 4; - } - if ((151 + leap) <= day && day < (181 + leap)) { - return 5; - } - if ((181 + leap) <= day && day < (212 + leap)) { - return 6; - } - if ((212 + leap) <= day && day < (243 + leap)) { - return 7; - } - if ((243 + leap) <= day && day < (273 + leap)) { - return 8; - } - if ((273 + leap) <= day && day < (304 + leap)) { - return 9; - } - if ((304 + leap) <= day && day < (334 + leap)) { - return 10; - } - if ((334 + leap) <= day && day < (365 + leap)) { - return 11; - } -}; diff --git a/node_modules/es-abstract/2016/ObjectCreate.js b/node_modules/es-abstract/2016/ObjectCreate.js deleted file mode 100644 index e2445b0..0000000 --- a/node_modules/es-abstract/2016/ObjectCreate.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $ObjectCreate = GetIntrinsic('%Object.create%', true); -var $TypeError = GetIntrinsic('%TypeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); - -var Type = require('./Type'); - -var hasProto = !({ __proto__: null } instanceof Object); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-objectcreate - -module.exports = function ObjectCreate(proto, internalSlotsList) { - if (proto !== null && Type(proto) !== 'Object') { - throw new $TypeError('Assertion failed: `proto` must be null or an object'); - } - var slots = arguments.length < 2 ? [] : internalSlotsList; - if (slots.length > 0) { - throw new $SyntaxError('es-abstract does not yet support internal slots'); - } - - if ($ObjectCreate) { - return $ObjectCreate(proto); - } - if (hasProto) { - return { __proto__: proto }; - } - - if (proto === null) { - throw new $SyntaxError('native Object.create support is required to create null objects'); - } - var T = function T() {}; - T.prototype = proto; - return new T(); -}; diff --git a/node_modules/es-abstract/2016/OrdinaryDefineOwnProperty.js b/node_modules/es-abstract/2016/OrdinaryDefineOwnProperty.js deleted file mode 100644 index 59780b3..0000000 --- a/node_modules/es-abstract/2016/OrdinaryDefineOwnProperty.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var IsPropertyKey = require('./IsPropertyKey'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); -var ValidateAndApplyPropertyDescriptor = require('./ValidateAndApplyPropertyDescriptor'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarydefineownproperty - -module.exports = function OrdinaryDefineOwnProperty(O, P, Desc) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (!$gOPD) { - // ES3/IE 8 fallback - if (IsAccessorDescriptor(Desc)) { - throw new $SyntaxError('This environment does not support accessor property descriptors.'); - } - var creatingNormalDataProperty = !(P in O) - && Desc['[[Writable]]'] - && Desc['[[Enumerable]]'] - && Desc['[[Configurable]]'] - && '[[Value]]' in Desc; - var settingExistingDataProperty = (P in O) - && (!('[[Configurable]]' in Desc) || Desc['[[Configurable]]']) - && (!('[[Enumerable]]' in Desc) || Desc['[[Enumerable]]']) - && (!('[[Writable]]' in Desc) || Desc['[[Writable]]']) - && '[[Value]]' in Desc; - if (creatingNormalDataProperty || settingExistingDataProperty) { - O[P] = Desc['[[Value]]']; // eslint-disable-line no-param-reassign - return SameValue(O[P], Desc['[[Value]]']); - } - throw new $SyntaxError('This environment does not support defining non-writable, non-enumerable, or non-configurable properties'); - } - var desc = $gOPD(O, P); - var current = desc && ToPropertyDescriptor(desc); - var extensible = IsExtensible(O); - return ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current); -}; diff --git a/node_modules/es-abstract/2016/OrdinaryGetOwnProperty.js b/node_modules/es-abstract/2016/OrdinaryGetOwnProperty.js deleted file mode 100644 index b9882e5..0000000 --- a/node_modules/es-abstract/2016/OrdinaryGetOwnProperty.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); - -var has = require('has'); - -var IsArray = require('./IsArray'); -var IsPropertyKey = require('./IsPropertyKey'); -var IsRegExp = require('./IsRegExp'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarygetownproperty - -module.exports = function OrdinaryGetOwnProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - if (!has(O, P)) { - return void 0; - } - if (!$gOPD) { - // ES3 / IE 8 fallback - var arrayLength = IsArray(O) && P === 'length'; - var regexLastIndex = IsRegExp(O) && P === 'lastIndex'; - return { - '[[Configurable]]': !(arrayLength || regexLastIndex), - '[[Enumerable]]': $isEnumerable(O, P), - '[[Value]]': O[P], - '[[Writable]]': true - }; - } - return ToPropertyDescriptor($gOPD(O, P)); -}; diff --git a/node_modules/es-abstract/2016/OrdinaryGetPrototypeOf.js b/node_modules/es-abstract/2016/OrdinaryGetPrototypeOf.js deleted file mode 100644 index 344077a..0000000 --- a/node_modules/es-abstract/2016/OrdinaryGetPrototypeOf.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $getProto = require('../helpers/getProto'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/7.0/#sec-ordinarygetprototypeof - -module.exports = function OrdinaryGetPrototypeOf(O) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!$getProto) { - throw new $TypeError('This environment does not support fetching prototypes.'); - } - return $getProto(O); -}; diff --git a/node_modules/es-abstract/2016/OrdinaryHasInstance.js b/node_modules/es-abstract/2016/OrdinaryHasInstance.js deleted file mode 100644 index 51abe26..0000000 --- a/node_modules/es-abstract/2016/OrdinaryHasInstance.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance - -module.exports = function OrdinaryHasInstance(C, O) { - if (IsCallable(C) === false) { - return false; - } - if (Type(O) !== 'Object') { - return false; - } - var P = Get(C, 'prototype'); - if (Type(P) !== 'Object') { - throw new $TypeError('OrdinaryHasInstance called on an object with an invalid prototype property.'); - } - return O instanceof C; -}; diff --git a/node_modules/es-abstract/2016/OrdinaryHasProperty.js b/node_modules/es-abstract/2016/OrdinaryHasProperty.js deleted file mode 100644 index 076c25a..0000000 --- a/node_modules/es-abstract/2016/OrdinaryHasProperty.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasproperty - -module.exports = function OrdinaryHasProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - return P in O; -}; diff --git a/node_modules/es-abstract/2016/OrdinarySetPrototypeOf.js b/node_modules/es-abstract/2016/OrdinarySetPrototypeOf.js deleted file mode 100644 index 3541331..0000000 --- a/node_modules/es-abstract/2016/OrdinarySetPrototypeOf.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $setProto = require('../helpers/setProto'); - -var OrdinaryGetPrototypeOf = require('./OrdinaryGetPrototypeOf'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/7.0/#sec-ordinarysetprototypeof - -module.exports = function OrdinarySetPrototypeOf(O, V) { - if (Type(V) !== 'Object' && Type(V) !== 'Null') { - throw new $TypeError('Assertion failed: V must be Object or Null'); - } - /* - var extensible = IsExtensible(O); - var current = OrdinaryGetPrototypeOf(O); - if (SameValue(V, current)) { - return true; - } - if (!extensible) { - return false; - } - */ - try { - $setProto(O, V); - } catch (e) { - return false; - } - return OrdinaryGetPrototypeOf(O) === V; - /* - var p = V; - var done = false; - while (!done) { - if (p === null) { - done = true; - } else if (SameValue(p, O)) { - return false; - } else { - if (wat) { - done = true; - } else { - p = p.[[Prototype]]; - } - } - } - O.[[Prototype]] = V; - return true; - */ -}; diff --git a/node_modules/es-abstract/2016/RegExpExec.js b/node_modules/es-abstract/2016/RegExpExec.js deleted file mode 100644 index 15c9186..0000000 --- a/node_modules/es-abstract/2016/RegExpExec.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var regexExec = require('../helpers/callBound')('RegExp.prototype.exec'); - -var Call = require('./Call'); -var Get = require('./Get'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-regexpexec - -module.exports = function RegExpExec(R, S) { - if (Type(R) !== 'Object') { - throw new $TypeError('Assertion failed: `R` must be an Object'); - } - if (Type(S) !== 'String') { - throw new $TypeError('Assertion failed: `S` must be a String'); - } - var exec = Get(R, 'exec'); - if (IsCallable(exec)) { - var result = Call(exec, R, [S]); - if (result === null || Type(result) === 'Object') { - return result; - } - throw new $TypeError('"exec" method must return `null` or an Object'); - } - return regexExec(R, S); -}; diff --git a/node_modules/es-abstract/2016/RequireObjectCoercible.js b/node_modules/es-abstract/2016/RequireObjectCoercible.js deleted file mode 100644 index 9008359..0000000 --- a/node_modules/es-abstract/2016/RequireObjectCoercible.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('../5/CheckObjectCoercible'); diff --git a/node_modules/es-abstract/2016/SameValue.js b/node_modules/es-abstract/2016/SameValue.js deleted file mode 100644 index 47c936d..0000000 --- a/node_modules/es-abstract/2016/SameValue.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $isNaN = require('../helpers/isNaN'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.12 - -module.exports = function SameValue(x, y) { - if (x === y) { // 0 === -0, but they are not identical. - if (x === 0) { return 1 / x === 1 / y; } - return true; - } - return $isNaN(x) && $isNaN(y); -}; diff --git a/node_modules/es-abstract/2016/SameValueNonNumber.js b/node_modules/es-abstract/2016/SameValueNonNumber.js deleted file mode 100644 index 5668752..0000000 --- a/node_modules/es-abstract/2016/SameValueNonNumber.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var SameValue = require('./SameValue'); - -// https://www.ecma-international.org/ecma-262/7.0/#sec-samevaluenonnumber - -module.exports = function SameValueNonNumber(x, y) { - if (typeof x === 'number' || typeof x !== typeof y) { - throw new $TypeError('SameValueNonNumber requires two non-number values of the same type.'); - } - return SameValue(x, y); -}; diff --git a/node_modules/es-abstract/2016/SameValueZero.js b/node_modules/es-abstract/2016/SameValueZero.js deleted file mode 100644 index 0dedcd2..0000000 --- a/node_modules/es-abstract/2016/SameValueZero.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var $isNaN = require('../helpers/isNaN'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-samevaluezero - -module.exports = function SameValueZero(x, y) { - return (x === y) || ($isNaN(x) && $isNaN(y)); -}; diff --git a/node_modules/es-abstract/2016/SecFromTime.js b/node_modules/es-abstract/2016/SecFromTime.js deleted file mode 100644 index 7190011..0000000 --- a/node_modules/es-abstract/2016/SecFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerSecond = timeConstants.msPerSecond; -var SecondsPerMinute = timeConstants.SecondsPerMinute; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function SecFromTime(t) { - return mod($floor(t / msPerSecond), SecondsPerMinute); -}; diff --git a/node_modules/es-abstract/2016/Set.js b/node_modules/es-abstract/2016/Set.js deleted file mode 100644 index 18ebd99..0000000 --- a/node_modules/es-abstract/2016/Set.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-set-o-p-v-throw - -module.exports = function Set(O, P, V, Throw) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - if (Type(Throw) !== 'Boolean') { - throw new $TypeError('Assertion failed: `Throw` must be a Boolean'); - } - if (Throw) { - O[P] = V; // eslint-disable-line no-param-reassign - return true; - } else { - try { - O[P] = V; // eslint-disable-line no-param-reassign - } catch (e) { - return false; - } - } -}; diff --git a/node_modules/es-abstract/2016/SetFunctionName.js b/node_modules/es-abstract/2016/SetFunctionName.js deleted file mode 100644 index f93324a..0000000 --- a/node_modules/es-abstract/2016/SetFunctionName.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var has = require('has'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var getSymbolDescription = require('../helpers/getSymbolDescription'); - -var DefinePropertyOrThrow = require('./DefinePropertyOrThrow'); -var IsExtensible = require('./IsExtensible'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-setfunctionname - -module.exports = function SetFunctionName(F, name) { - if (typeof F !== 'function') { - throw new $TypeError('Assertion failed: `F` must be a function'); - } - if (!IsExtensible(F) || has(F, 'name')) { - throw new $TypeError('Assertion failed: `F` must be extensible, and must not have a `name` own property'); - } - var nameType = Type(name); - if (nameType !== 'Symbol' && nameType !== 'String') { - throw new $TypeError('Assertion failed: `name` must be a Symbol or a String'); - } - if (nameType === 'Symbol') { - var description = getSymbolDescription(name); - // eslint-disable-next-line no-param-reassign - name = typeof description === 'undefined' ? '' : '[' + description + ']'; - } - if (arguments.length > 2) { - var prefix = arguments[2]; - // eslint-disable-next-line no-param-reassign - name = prefix + ' ' + name; - } - return DefinePropertyOrThrow(F, 'name', { - '[[Value]]': name, - '[[Writable]]': false, - '[[Enumerable]]': false, - '[[Configurable]]': true - }); -}; diff --git a/node_modules/es-abstract/2016/SetIntegrityLevel.js b/node_modules/es-abstract/2016/SetIntegrityLevel.js deleted file mode 100644 index 3d5c81d..0000000 --- a/node_modules/es-abstract/2016/SetIntegrityLevel.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); -var $preventExtensions = GetIntrinsic('%Object.preventExtensions%'); -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); - -var forEach = require('../helpers/forEach'); - -var DefinePropertyOrThrow = require('./DefinePropertyOrThrow'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-setintegritylevel - -module.exports = function SetIntegrityLevel(O, level) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (level !== 'sealed' && level !== 'frozen') { - throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); - } - if (!$preventExtensions) { - throw new $SyntaxError('SetIntegrityLevel requires native `Object.preventExtensions` support'); - } - var status = $preventExtensions(O); - if (!status) { - return false; - } - if (!$gOPN) { - throw new $SyntaxError('SetIntegrityLevel requires native `Object.getOwnPropertyNames` support'); - } - var theKeys = $gOPN(O); - if (level === 'sealed') { - forEach(theKeys, function (k) { - DefinePropertyOrThrow(O, k, { configurable: false }); - }); - } else if (level === 'frozen') { - forEach(theKeys, function (k) { - var currentDesc = $gOPD(O, k); - if (typeof currentDesc !== 'undefined') { - var desc; - if (IsAccessorDescriptor(ToPropertyDescriptor(currentDesc))) { - desc = { configurable: false }; - } else { - desc = { configurable: false, writable: false }; - } - DefinePropertyOrThrow(O, k, desc); - } - }); - } - return true; -}; diff --git a/node_modules/es-abstract/2016/SpeciesConstructor.js b/node_modules/es-abstract/2016/SpeciesConstructor.js deleted file mode 100644 index 3cdcd74..0000000 --- a/node_modules/es-abstract/2016/SpeciesConstructor.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $species = GetIntrinsic('%Symbol.species%', true); -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsConstructor = require('./IsConstructor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-speciesconstructor - -module.exports = function SpeciesConstructor(O, defaultConstructor) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - var C = O.constructor; - if (typeof C === 'undefined') { - return defaultConstructor; - } - if (Type(C) !== 'Object') { - throw new $TypeError('O.constructor is not an Object'); - } - var S = $species ? C[$species] : void 0; - if (S == null) { - return defaultConstructor; - } - if (IsConstructor(S)) { - return S; - } - throw new $TypeError('no constructor found'); -}; diff --git a/node_modules/es-abstract/2016/StrictEqualityComparison.js b/node_modules/es-abstract/2016/StrictEqualityComparison.js deleted file mode 100644 index eea5df3..0000000 --- a/node_modules/es-abstract/2016/StrictEqualityComparison.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6 - -module.exports = function StrictEqualityComparison(x, y) { - var xType = Type(x); - var yType = Type(y); - if (xType !== yType) { - return false; - } - if (xType === 'Undefined' || xType === 'Null') { - return true; - } - return x === y; // shortcut for steps 4-7 -}; diff --git a/node_modules/es-abstract/2016/SymbolDescriptiveString.js b/node_modules/es-abstract/2016/SymbolDescriptiveString.js deleted file mode 100644 index 7bd8191..0000000 --- a/node_modules/es-abstract/2016/SymbolDescriptiveString.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $SymbolToString = callBound('Symbol.prototype.toString', true); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-symboldescriptivestring - -module.exports = function SymbolDescriptiveString(sym) { - if (Type(sym) !== 'Symbol') { - throw new $TypeError('Assertion failed: `sym` must be a Symbol'); - } - return $SymbolToString(sym); -}; diff --git a/node_modules/es-abstract/2016/TestIntegrityLevel.js b/node_modules/es-abstract/2016/TestIntegrityLevel.js deleted file mode 100644 index 7a57397..0000000 --- a/node_modules/es-abstract/2016/TestIntegrityLevel.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var every = require('../helpers/every'); - -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-testintegritylevel - -module.exports = function TestIntegrityLevel(O, level) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (level !== 'sealed' && level !== 'frozen') { - throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); - } - var status = IsExtensible(O); - if (status) { - return false; - } - var theKeys = $gOPN(O); - return theKeys.length === 0 || every(theKeys, function (k) { - var currentDesc = $gOPD(O, k); - if (typeof currentDesc !== 'undefined') { - if (currentDesc.configurable) { - return false; - } - if (level === 'frozen' && IsDataDescriptor(ToPropertyDescriptor(currentDesc)) && currentDesc.writable) { - return false; - } - } - return true; - }); -}; diff --git a/node_modules/es-abstract/2016/TimeClip.js b/node_modules/es-abstract/2016/TimeClip.js deleted file mode 100644 index 57aa08c..0000000 --- a/node_modules/es-abstract/2016/TimeClip.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Date = GetIntrinsic('%Date%'); -var $Number = GetIntrinsic('%Number%'); -var $abs = GetIntrinsic('%Math.abs%'); - -var $isFinite = require('../helpers/isFinite'); - -var ToNumber = require('./ToNumber'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.14 - -module.exports = function TimeClip(time) { - if (!$isFinite(time) || $abs(time) > 8.64e15) { - return NaN; - } - return $Number(new $Date(ToNumber(time))); -}; - diff --git a/node_modules/es-abstract/2016/TimeFromYear.js b/node_modules/es-abstract/2016/TimeFromYear.js deleted file mode 100644 index df646c3..0000000 --- a/node_modules/es-abstract/2016/TimeFromYear.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var msPerDay = require('../helpers/timeConstants').msPerDay; - -var DayFromYear = require('./DayFromYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function TimeFromYear(y) { - return msPerDay * DayFromYear(y); -}; diff --git a/node_modules/es-abstract/2016/TimeWithinDay.js b/node_modules/es-abstract/2016/TimeWithinDay.js deleted file mode 100644 index c5b21d3..0000000 --- a/node_modules/es-abstract/2016/TimeWithinDay.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - -module.exports = function TimeWithinDay(t) { - return mod(t, msPerDay); -}; - diff --git a/node_modules/es-abstract/2016/ToBoolean.js b/node_modules/es-abstract/2016/ToBoolean.js deleted file mode 100644 index 65d8737..0000000 --- a/node_modules/es-abstract/2016/ToBoolean.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.2 - -module.exports = function ToBoolean(value) { return !!value; }; diff --git a/node_modules/es-abstract/2016/ToDateString.js b/node_modules/es-abstract/2016/ToDateString.js deleted file mode 100644 index 7a6d4c4..0000000 --- a/node_modules/es-abstract/2016/ToDateString.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $Date = GetIntrinsic('%Date%'); - -var $isNaN = require('../helpers/isNaN'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-todatestring - -module.exports = function ToDateString(tv) { - if (Type(tv) !== 'Number') { - throw new $TypeError('Assertion failed: `tv` must be a Number'); - } - if ($isNaN(tv)) { - return 'Invalid Date'; - } - return $Date(tv); -}; diff --git a/node_modules/es-abstract/2016/ToInt16.js b/node_modules/es-abstract/2016/ToInt16.js deleted file mode 100644 index 5a112c2..0000000 --- a/node_modules/es-abstract/2016/ToInt16.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var ToUint16 = require('./ToUint16'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toint16 - -module.exports = function ToInt16(argument) { - var int16bit = ToUint16(argument); - return int16bit >= 0x8000 ? int16bit - 0x10000 : int16bit; -}; diff --git a/node_modules/es-abstract/2016/ToInt32.js b/node_modules/es-abstract/2016/ToInt32.js deleted file mode 100644 index a8d2680..0000000 --- a/node_modules/es-abstract/2016/ToInt32.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.5 - -module.exports = function ToInt32(x) { - return ToNumber(x) >> 0; -}; diff --git a/node_modules/es-abstract/2016/ToInt8.js b/node_modules/es-abstract/2016/ToInt8.js deleted file mode 100644 index d103123..0000000 --- a/node_modules/es-abstract/2016/ToInt8.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var ToUint8 = require('./ToUint8'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toint8 - -module.exports = function ToInt8(argument) { - var int8bit = ToUint8(argument); - return int8bit >= 0x80 ? int8bit - 0x100 : int8bit; -}; diff --git a/node_modules/es-abstract/2016/ToInteger.js b/node_modules/es-abstract/2016/ToInteger.js deleted file mode 100644 index 16f7db9..0000000 --- a/node_modules/es-abstract/2016/ToInteger.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var ES5ToInteger = require('../5/ToInteger'); - -var ToNumber = require('./ToNumber'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tointeger - -module.exports = function ToInteger(value) { - var number = ToNumber(value); - return ES5ToInteger(number); -}; diff --git a/node_modules/es-abstract/2016/ToLength.js b/node_modules/es-abstract/2016/ToLength.js deleted file mode 100644 index 1bef9be..0000000 --- a/node_modules/es-abstract/2016/ToLength.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger'); - -var ToInteger = require('./ToInteger'); - -module.exports = function ToLength(argument) { - var len = ToInteger(argument); - if (len <= 0) { return 0; } // includes converting -0 to +0 - if (len > MAX_SAFE_INTEGER) { return MAX_SAFE_INTEGER; } - return len; -}; diff --git a/node_modules/es-abstract/2016/ToNumber.js b/node_modules/es-abstract/2016/ToNumber.js deleted file mode 100644 index 7a3cdc8..0000000 --- a/node_modules/es-abstract/2016/ToNumber.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $Number = GetIntrinsic('%Number%'); -var $RegExp = GetIntrinsic('%RegExp%'); -var $parseInteger = GetIntrinsic('%parseInt%'); - -var callBound = require('../helpers/callBound'); -var regexTester = require('../helpers/regexTester'); -var isPrimitive = require('../helpers/isPrimitive'); - -var $strSlice = callBound('String.prototype.slice'); -var isBinary = regexTester(/^0b[01]+$/i); -var isOctal = regexTester(/^0o[0-7]+$/i); -var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i); -var nonWS = ['\u0085', '\u200b', '\ufffe'].join(''); -var nonWSregex = new $RegExp('[' + nonWS + ']', 'g'); -var hasNonWS = regexTester(nonWSregex); - -// whitespace from: https://es5.github.io/#x15.5.4.20 -// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 -var ws = [ - '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', - '\u2029\uFEFF' -].join(''); -var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g'); -var $replace = callBound('String.prototype.replace'); -var $trim = function (value) { - return $replace(value, trimRegex, ''); -}; - -var ToPrimitive = require('./ToPrimitive'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tonumber - -module.exports = function ToNumber(argument) { - var value = isPrimitive(argument) ? argument : ToPrimitive(argument, $Number); - if (typeof value === 'symbol') { - throw new $TypeError('Cannot convert a Symbol value to a number'); - } - if (typeof value === 'string') { - if (isBinary(value)) { - return ToNumber($parseInteger($strSlice(value, 2), 2)); - } else if (isOctal(value)) { - return ToNumber($parseInteger($strSlice(value, 2), 8)); - } else if (hasNonWS(value) || isInvalidHexLiteral(value)) { - return NaN; - } else { - var trimmed = $trim(value); - if (trimmed !== value) { - return ToNumber(trimmed); - } - } - } - return $Number(value); -}; diff --git a/node_modules/es-abstract/2016/ToObject.js b/node_modules/es-abstract/2016/ToObject.js deleted file mode 100644 index 50d5b94..0000000 --- a/node_modules/es-abstract/2016/ToObject.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Object = GetIntrinsic('%Object%'); - -var RequireObjectCoercible = require('./RequireObjectCoercible'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toobject - -module.exports = function ToObject(value) { - RequireObjectCoercible(value); - return $Object(value); -}; diff --git a/node_modules/es-abstract/2016/ToPrimitive.js b/node_modules/es-abstract/2016/ToPrimitive.js deleted file mode 100644 index 81c655d..0000000 --- a/node_modules/es-abstract/2016/ToPrimitive.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var toPrimitive = require('es-to-primitive/es2015'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive - -module.exports = function ToPrimitive(input) { - if (arguments.length > 1) { - return toPrimitive(input, arguments[1]); - } - return toPrimitive(input); -}; diff --git a/node_modules/es-abstract/2016/ToPropertyDescriptor.js b/node_modules/es-abstract/2016/ToPropertyDescriptor.js deleted file mode 100644 index 38e536e..0000000 --- a/node_modules/es-abstract/2016/ToPropertyDescriptor.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -var has = require('has'); - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Type = require('./Type'); -var ToBoolean = require('./ToBoolean'); -var IsCallable = require('./IsCallable'); - -// https://ecma-international.org/ecma-262/5.1/#sec-8.10.5 - -module.exports = function ToPropertyDescriptor(Obj) { - if (Type(Obj) !== 'Object') { - throw new $TypeError('ToPropertyDescriptor requires an object'); - } - - var desc = {}; - if (has(Obj, 'enumerable')) { - desc['[[Enumerable]]'] = ToBoolean(Obj.enumerable); - } - if (has(Obj, 'configurable')) { - desc['[[Configurable]]'] = ToBoolean(Obj.configurable); - } - if (has(Obj, 'value')) { - desc['[[Value]]'] = Obj.value; - } - if (has(Obj, 'writable')) { - desc['[[Writable]]'] = ToBoolean(Obj.writable); - } - if (has(Obj, 'get')) { - var getter = Obj.get; - if (typeof getter !== 'undefined' && !IsCallable(getter)) { - throw new TypeError('getter must be a function'); - } - desc['[[Get]]'] = getter; - } - if (has(Obj, 'set')) { - var setter = Obj.set; - if (typeof setter !== 'undefined' && !IsCallable(setter)) { - throw new $TypeError('setter must be a function'); - } - desc['[[Set]]'] = setter; - } - - if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) { - throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute'); - } - return desc; -}; diff --git a/node_modules/es-abstract/2016/ToPropertyKey.js b/node_modules/es-abstract/2016/ToPropertyKey.js deleted file mode 100644 index 38f40dd..0000000 --- a/node_modules/es-abstract/2016/ToPropertyKey.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $String = GetIntrinsic('%String%'); - -var ToPrimitive = require('./ToPrimitive'); -var ToString = require('./ToString'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-topropertykey - -module.exports = function ToPropertyKey(argument) { - var key = ToPrimitive(argument, $String); - return typeof key === 'symbol' ? key : ToString(key); -}; diff --git a/node_modules/es-abstract/2016/ToString.js b/node_modules/es-abstract/2016/ToString.js deleted file mode 100644 index a345431..0000000 --- a/node_modules/es-abstract/2016/ToString.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $String = GetIntrinsic('%String%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tostring - -module.exports = function ToString(argument) { - if (typeof argument === 'symbol') { - throw new $TypeError('Cannot convert a Symbol value to a string'); - } - return $String(argument); -}; diff --git a/node_modules/es-abstract/2016/ToUint16.js b/node_modules/es-abstract/2016/ToUint16.js deleted file mode 100644 index c8a408b..0000000 --- a/node_modules/es-abstract/2016/ToUint16.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var $sign = require('../helpers/sign'); -var $mod = require('../helpers/mod'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.7 - -module.exports = function ToUint16(value) { - var number = ToNumber(value); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = $sign(number) * $floor($abs(number)); - return $mod(posInt, 0x10000); -}; diff --git a/node_modules/es-abstract/2016/ToUint32.js b/node_modules/es-abstract/2016/ToUint32.js deleted file mode 100644 index 3660f62..0000000 --- a/node_modules/es-abstract/2016/ToUint32.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.6 - -module.exports = function ToUint32(x) { - return ToNumber(x) >>> 0; -}; diff --git a/node_modules/es-abstract/2016/ToUint8.js b/node_modules/es-abstract/2016/ToUint8.js deleted file mode 100644 index bf84753..0000000 --- a/node_modules/es-abstract/2016/ToUint8.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var $sign = require('../helpers/sign'); -var $mod = require('../helpers/mod'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -module.exports = function ToUint8(argument) { - var number = ToNumber(argument); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = $sign(number) * $floor($abs(number)); - return $mod(posInt, 0x100); -}; diff --git a/node_modules/es-abstract/2016/ToUint8Clamp.js b/node_modules/es-abstract/2016/ToUint8Clamp.js deleted file mode 100644 index c7f9f56..0000000 --- a/node_modules/es-abstract/2016/ToUint8Clamp.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); - -var $floor = $Math.floor; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-touint8clamp - -module.exports = function ToUint8Clamp(argument) { - var number = ToNumber(argument); - if ($isNaN(number) || number <= 0) { return 0; } - if (number >= 0xFF) { return 0xFF; } - var f = $floor(argument); - if (f + 0.5 < number) { return f + 1; } - if (number < f + 0.5) { return f; } - if (f % 2 !== 0) { return f + 1; } - return f; -}; diff --git a/node_modules/es-abstract/2016/Type.js b/node_modules/es-abstract/2016/Type.js deleted file mode 100644 index 6c99376..0000000 --- a/node_modules/es-abstract/2016/Type.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var ES5Type = require('../5/Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tostring - -module.exports = function Type(x) { - if (typeof x === 'symbol') { - return 'Symbol'; - } - return ES5Type(x); -}; diff --git a/node_modules/es-abstract/2016/ValidateAndApplyPropertyDescriptor.js b/node_modules/es-abstract/2016/ValidateAndApplyPropertyDescriptor.js deleted file mode 100644 index d4b9007..0000000 --- a/node_modules/es-abstract/2016/ValidateAndApplyPropertyDescriptor.js +++ /dev/null @@ -1,170 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); -var isSamePropertyDescriptor = require('../helpers/isSamePropertyDescriptor'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsGenericDescriptor = require('./IsGenericDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-validateandapplypropertydescriptor -// https://www.ecma-international.org/ecma-262/8.0/#sec-validateandapplypropertydescriptor - -// eslint-disable-next-line max-lines-per-function, max-statements, max-params -module.exports = function ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current) { - // this uses the ES2017+ logic, since it fixes a number of bugs in the ES2015 logic. - var oType = Type(O); - if (oType !== 'Undefined' && oType !== 'Object') { - throw new $TypeError('Assertion failed: O must be undefined or an Object'); - } - if (Type(extensible) !== 'Boolean') { - throw new $TypeError('Assertion failed: extensible must be a Boolean'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (Type(current) !== 'Undefined' && !isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, current)) { - throw new $TypeError('Assertion failed: current must be a Property Descriptor, or undefined'); - } - if (oType !== 'Undefined' && !IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: if O is not undefined, P must be a Property Key'); - } - if (Type(current) === 'Undefined') { - if (!extensible) { - return false; - } - if (IsGenericDescriptor(Desc) || IsDataDescriptor(Desc)) { - if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': Desc['[[Configurable]]'], - '[[Enumerable]]': Desc['[[Enumerable]]'], - '[[Value]]': Desc['[[Value]]'], - '[[Writable]]': Desc['[[Writable]]'] - } - ); - } - } else { - if (!IsAccessorDescriptor(Desc)) { - throw new $TypeError('Assertion failed: Desc is not an accessor descriptor'); - } - if (oType !== 'Undefined') { - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); - } - } - return true; - } - if (IsGenericDescriptor(Desc) && !('[[Configurable]]' in Desc) && !('[[Enumerable]]' in Desc)) { - return true; - } - if (isSamePropertyDescriptor({ SameValue: SameValue }, Desc, current)) { - return true; // removed by ES2017, but should still be correct - } - // "if every field in Desc is absent, return true" can't really match the assertion that it's a Property Descriptor - if (!current['[[Configurable]]']) { - if (Desc['[[Configurable]]']) { - return false; - } - if ('[[Enumerable]]' in Desc && !Desc['[[Enumerable]]'] === !!current['[[Enumerable]]']) { - return false; - } - } - if (IsGenericDescriptor(Desc)) { - // no further validation is required. - } else if (IsDataDescriptor(current) !== IsDataDescriptor(Desc)) { - if (!current['[[Configurable]]']) { - return false; - } - if (IsDataDescriptor(current)) { - if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': current['[[Configurable]]'], - '[[Enumerable]]': current['[[Enumerable]]'], - '[[Get]]': undefined - } - ); - } - } else if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': current['[[Configurable]]'], - '[[Enumerable]]': current['[[Enumerable]]'], - '[[Value]]': undefined - } - ); - } - } else if (IsDataDescriptor(current) && IsDataDescriptor(Desc)) { - if (!current['[[Configurable]]'] && !current['[[Writable]]']) { - if ('[[Writable]]' in Desc && Desc['[[Writable]]']) { - return false; - } - if ('[[Value]]' in Desc && !SameValue(Desc['[[Value]]'], current['[[Value]]'])) { - return false; - } - return true; - } - } else if (IsAccessorDescriptor(current) && IsAccessorDescriptor(Desc)) { - if (!current['[[Configurable]]']) { - if ('[[Set]]' in Desc && !SameValue(Desc['[[Set]]'], current['[[Set]]'])) { - return false; - } - if ('[[Get]]' in Desc && !SameValue(Desc['[[Get]]'], current['[[Get]]'])) { - return false; - } - return true; - } - } else { - throw new $TypeError('Assertion failed: current and Desc are not both data, both accessors, or one accessor and one data.'); - } - if (oType !== 'Undefined') { - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); - } - return true; -}; diff --git a/node_modules/es-abstract/2016/WeekDay.js b/node_modules/es-abstract/2016/WeekDay.js deleted file mode 100644 index 2973e02..0000000 --- a/node_modules/es-abstract/2016/WeekDay.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -var Day = require('./Day'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.6 - -module.exports = function WeekDay(t) { - return mod(Day(t) + 4, 7); -}; diff --git a/node_modules/es-abstract/2016/YearFromTime.js b/node_modules/es-abstract/2016/YearFromTime.js deleted file mode 100644 index ff5339f..0000000 --- a/node_modules/es-abstract/2016/YearFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Date = GetIntrinsic('%Date%'); - -var callBound = require('../helpers/callBound'); - -var $getUTCFullYear = callBound('Date.prototype.getUTCFullYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function YearFromTime(t) { - // largest y such that this.TimeFromYear(y) <= t - return $getUTCFullYear(new $Date(t)); -}; diff --git a/node_modules/es-abstract/2016/modulo.js b/node_modules/es-abstract/2016/modulo.js deleted file mode 100644 index bc04c06..0000000 --- a/node_modules/es-abstract/2016/modulo.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -// https://ecma-international.org/ecma-262/5.1/#sec-5.2 - -module.exports = function modulo(x, y) { - return mod(x, y); -}; diff --git a/node_modules/es-abstract/2016/msFromTime.js b/node_modules/es-abstract/2016/msFromTime.js deleted file mode 100644 index c31eda0..0000000 --- a/node_modules/es-abstract/2016/msFromTime.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); -var msPerSecond = require('../helpers/timeConstants').msPerSecond; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function msFromTime(t) { - return mod(t, msPerSecond); -}; diff --git a/node_modules/es-abstract/2016/thisBooleanValue.js b/node_modules/es-abstract/2016/thisBooleanValue.js deleted file mode 100644 index 3ffac9c..0000000 --- a/node_modules/es-abstract/2016/thisBooleanValue.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var $BooleanValueOf = require('../helpers/callBound')('Boolean.prototype.valueOf'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-boolean-prototype-object - -module.exports = function thisBooleanValue(value) { - if (Type(value) === 'Boolean') { - return value; - } - - return $BooleanValueOf(value); -}; diff --git a/node_modules/es-abstract/2016/thisNumberValue.js b/node_modules/es-abstract/2016/thisNumberValue.js deleted file mode 100644 index 0345e52..0000000 --- a/node_modules/es-abstract/2016/thisNumberValue.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var Type = require('./Type'); - -var $NumberValueOf = callBound('Number.prototype.valueOf'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-number-prototype-object - -module.exports = function thisNumberValue(value) { - if (Type(value) === 'Number') { - return value; - } - - return $NumberValueOf(value); -}; - diff --git a/node_modules/es-abstract/2016/thisStringValue.js b/node_modules/es-abstract/2016/thisStringValue.js deleted file mode 100644 index 3b99b6e..0000000 --- a/node_modules/es-abstract/2016/thisStringValue.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var $StringValueOf = require('../helpers/callBound')('String.prototype.valueOf'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-string-prototype-object - -module.exports = function thisStringValue(value) { - if (Type(value) === 'String') { - return value; - } - - return $StringValueOf(value); -}; diff --git a/node_modules/es-abstract/2016/thisTimeValue.js b/node_modules/es-abstract/2016/thisTimeValue.js deleted file mode 100644 index d7cda28..0000000 --- a/node_modules/es-abstract/2016/thisTimeValue.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var $DateValueOf = require('../helpers/callBound')('Date.prototype.valueOf'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-date-prototype-object - -module.exports = function thisTimeValue(value) { - return $DateValueOf(value); -}; diff --git a/node_modules/es-abstract/2017/AbstractEqualityComparison.js b/node_modules/es-abstract/2017/AbstractEqualityComparison.js deleted file mode 100644 index 40b3909..0000000 --- a/node_modules/es-abstract/2017/AbstractEqualityComparison.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); -var ToPrimitive = require('./ToPrimitive'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison - -module.exports = function AbstractEqualityComparison(x, y) { - var xType = Type(x); - var yType = Type(y); - if (xType === yType) { - return x === y; // ES6+ specified this shortcut anyways. - } - if (x == null && y == null) { - return true; - } - if (xType === 'Number' && yType === 'String') { - return AbstractEqualityComparison(x, ToNumber(y)); - } - if (xType === 'String' && yType === 'Number') { - return AbstractEqualityComparison(ToNumber(x), y); - } - if (xType === 'Boolean') { - return AbstractEqualityComparison(ToNumber(x), y); - } - if (yType === 'Boolean') { - return AbstractEqualityComparison(x, ToNumber(y)); - } - if ((xType === 'String' || xType === 'Number' || xType === 'Symbol') && yType === 'Object') { - return AbstractEqualityComparison(x, ToPrimitive(y)); - } - if (xType === 'Object' && (yType === 'String' || yType === 'Number' || yType === 'Symbol')) { - return AbstractEqualityComparison(ToPrimitive(x), y); - } - return false; -}; diff --git a/node_modules/es-abstract/2017/AbstractRelationalComparison.js b/node_modules/es-abstract/2017/AbstractRelationalComparison.js deleted file mode 100644 index bc7ca83..0000000 --- a/node_modules/es-abstract/2017/AbstractRelationalComparison.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Number = GetIntrinsic('%Number%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var isPrefixOf = require('../helpers/isPrefixOf'); - -var ToNumber = require('./ToNumber'); -var ToPrimitive = require('./ToPrimitive'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5 - -// eslint-disable-next-line max-statements -module.exports = function AbstractRelationalComparison(x, y, LeftFirst) { - if (Type(LeftFirst) !== 'Boolean') { - throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean'); - } - var px; - var py; - if (LeftFirst) { - px = ToPrimitive(x, $Number); - py = ToPrimitive(y, $Number); - } else { - py = ToPrimitive(y, $Number); - px = ToPrimitive(x, $Number); - } - var bothStrings = Type(px) === 'String' && Type(py) === 'String'; - if (!bothStrings) { - var nx = ToNumber(px); - var ny = ToNumber(py); - if ($isNaN(nx) || $isNaN(ny)) { - return undefined; - } - if ($isFinite(nx) && $isFinite(ny) && nx === ny) { - return false; - } - if (nx === 0 && ny === 0) { - return false; - } - if (nx === Infinity) { - return false; - } - if (ny === Infinity) { - return true; - } - if (ny === -Infinity) { - return false; - } - if (nx === -Infinity) { - return true; - } - return nx < ny; // by now, these are both nonzero, finite, and not equal - } - if (isPrefixOf(py, px)) { - return false; - } - if (isPrefixOf(px, py)) { - return true; - } - return px < py; // both strings, neither a prefix of the other. shortcut for steps c-f -}; diff --git a/node_modules/es-abstract/2017/AdvanceStringIndex.js b/node_modules/es-abstract/2017/AdvanceStringIndex.js deleted file mode 100644 index 666f578..0000000 --- a/node_modules/es-abstract/2017/AdvanceStringIndex.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var IsInteger = require('./IsInteger'); -var Type = require('./Type'); - -var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $charCodeAt = require('../helpers/callBound')('String.prototype.charCodeAt'); - -// https://ecma-international.org/ecma-262/6.0/#sec-advancestringindex - -module.exports = function AdvanceStringIndex(S, index, unicode) { - if (Type(S) !== 'String') { - throw new $TypeError('Assertion failed: `S` must be a String'); - } - if (!IsInteger(index) || index < 0 || index > MAX_SAFE_INTEGER) { - throw new $TypeError('Assertion failed: `length` must be an integer >= 0 and <= 2**53'); - } - if (Type(unicode) !== 'Boolean') { - throw new $TypeError('Assertion failed: `unicode` must be a Boolean'); - } - if (!unicode) { - return index + 1; - } - var length = S.length; - if ((index + 1) >= length) { - return index + 1; - } - - var first = $charCodeAt(S, index); - if (first < 0xD800 || first > 0xDBFF) { - return index + 1; - } - - var second = $charCodeAt(S, index + 1); - if (second < 0xDC00 || second > 0xDFFF) { - return index + 1; - } - - return index + 2; -}; diff --git a/node_modules/es-abstract/2017/ArrayCreate.js b/node_modules/es-abstract/2017/ArrayCreate.js deleted file mode 100644 index fc9a7cf..0000000 --- a/node_modules/es-abstract/2017/ArrayCreate.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $ArrayPrototype = GetIntrinsic('%Array.prototype%'); -var $RangeError = GetIntrinsic('%RangeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsInteger = require('./IsInteger'); - -var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1; - -var $setProto = GetIntrinsic('%Object.setPrototypeOf%', true) || ( - // eslint-disable-next-line no-proto, no-negated-condition - [].__proto__ !== $ArrayPrototype - ? null - : function (O, proto) { - O.__proto__ = proto; // eslint-disable-line no-proto, no-param-reassign - return O; - } -); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-arraycreate - -module.exports = function ArrayCreate(length) { - if (!IsInteger(length) || length < 0) { - throw new $TypeError('Assertion failed: `length` must be an integer Number >= 0'); - } - if (length > MAX_ARRAY_LENGTH) { - throw new $RangeError('length is greater than (2**32 - 1)'); - } - var proto = arguments.length > 1 ? arguments[1] : $ArrayPrototype; - var A = []; // steps 5 - 7, and 9 - if (proto !== $ArrayPrototype) { // step 8 - if (!$setProto) { - throw new $SyntaxError('ArrayCreate: a `proto` argument that is not `Array.prototype` is not supported in an environment that does not support setting the [[Prototype]]'); - } - $setProto(A, proto); - } - if (length !== 0) { // bypasses the need for step 2 - A.length = length; - } - /* step 10, the above as a shortcut for the below - OrdinaryDefineOwnProperty(A, 'length', { - '[[Configurable]]': false, - '[[Enumerable]]': false, - '[[Value]]': length, - '[[Writable]]': true - }); - */ - return A; -}; diff --git a/node_modules/es-abstract/2017/ArraySetLength.js b/node_modules/es-abstract/2017/ArraySetLength.js deleted file mode 100644 index c9134c6..0000000 --- a/node_modules/es-abstract/2017/ArraySetLength.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $RangeError = GetIntrinsic('%RangeError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var assign = require('object.assign'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var IsArray = require('./IsArray'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var OrdinaryDefineOwnProperty = require('./OrdinaryDefineOwnProperty'); -var OrdinaryGetOwnProperty = require('./OrdinaryGetOwnProperty'); -var ToNumber = require('./ToNumber'); -var ToString = require('./ToString'); -var ToUint32 = require('./ToUint32'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-arraysetlength - -// eslint-disable-next-line max-statements, max-lines-per-function -module.exports = function ArraySetLength(A, Desc) { - if (!IsArray(A)) { - throw new $TypeError('Assertion failed: A must be an Array'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (!('[[Value]]' in Desc)) { - return OrdinaryDefineOwnProperty(A, 'length', Desc); - } - var newLenDesc = assign({}, Desc); - var newLen = ToUint32(Desc['[[Value]]']); - var numberLen = ToNumber(Desc['[[Value]]']); - if (newLen !== numberLen) { - throw new $RangeError('Invalid array length'); - } - newLenDesc['[[Value]]'] = newLen; - var oldLenDesc = OrdinaryGetOwnProperty(A, 'length'); - if (!IsDataDescriptor(oldLenDesc)) { - throw new $TypeError('Assertion failed: an array had a non-data descriptor on `length`'); - } - var oldLen = oldLenDesc['[[Value]]']; - if (newLen >= oldLen) { - return OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - } - if (!oldLenDesc['[[Writable]]']) { - return false; - } - var newWritable; - if (!('[[Writable]]' in newLenDesc) || newLenDesc['[[Writable]]']) { - newWritable = true; - } else { - newWritable = false; - newLenDesc['[[Writable]]'] = true; - } - var succeeded = OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - if (!succeeded) { - return false; - } - while (newLen < oldLen) { - oldLen -= 1; - // eslint-disable-next-line no-param-reassign - var deleteSucceeded = delete A[ToString(oldLen)]; - if (!deleteSucceeded) { - newLenDesc['[[Value]]'] = oldLen + 1; - if (!newWritable) { - newLenDesc['[[Writable]]'] = false; - OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - return false; - } - } - } - if (!newWritable) { - return OrdinaryDefineOwnProperty(A, 'length', { '[[Writable]]': false }); - } - return true; -}; diff --git a/node_modules/es-abstract/2017/ArraySpeciesCreate.js b/node_modules/es-abstract/2017/ArraySpeciesCreate.js deleted file mode 100644 index 98b9b56..0000000 --- a/node_modules/es-abstract/2017/ArraySpeciesCreate.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Array = GetIntrinsic('%Array%'); -var $species = GetIntrinsic('%Symbol.species%', true); -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var IsConstructor = require('./IsConstructor'); -var IsInteger = require('./IsInteger'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-arrayspeciescreate - -module.exports = function ArraySpeciesCreate(originalArray, length) { - if (!IsInteger(length) || length < 0) { - throw new $TypeError('Assertion failed: length must be an integer >= 0'); - } - var len = length === 0 ? 0 : length; - var C; - var isArray = IsArray(originalArray); - if (isArray) { - C = Get(originalArray, 'constructor'); - // TODO: figure out how to make a cross-realm normal Array, a same-realm Array - // if (IsConstructor(C)) { - // if C is another realm's Array, C = undefined - // Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Array))) === null ? - // } - if ($species && Type(C) === 'Object') { - C = Get(C, $species); - if (C === null) { - C = void 0; - } - } - } - if (typeof C === 'undefined') { - return $Array(len); - } - if (!IsConstructor(C)) { - throw new $TypeError('C must be a constructor'); - } - return new C(len); // Construct(C, len); -}; - diff --git a/node_modules/es-abstract/2017/Call.js b/node_modules/es-abstract/2017/Call.js deleted file mode 100644 index f31960d..0000000 --- a/node_modules/es-abstract/2017/Call.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var inspect = require('object-inspect'); - -var IsCallable = require('./IsCallable'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-call - -module.exports = function Call(F, V) { - var args = arguments.length > 2 ? arguments[2] : []; - if (!IsCallable(F)) { - throw new $TypeError(inspect(F) + ' is not a function'); - } - return F.apply(V, args); -}; diff --git a/node_modules/es-abstract/2017/CanonicalNumericIndexString.js b/node_modules/es-abstract/2017/CanonicalNumericIndexString.js deleted file mode 100644 index 625f853..0000000 --- a/node_modules/es-abstract/2017/CanonicalNumericIndexString.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var SameValue = require('./SameValue'); -var ToNumber = require('./ToNumber'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-canonicalnumericindexstring - -module.exports = function CanonicalNumericIndexString(argument) { - if (Type(argument) !== 'String') { - throw new $TypeError('Assertion failed: `argument` must be a String'); - } - if (argument === '-0') { return -0; } - var n = ToNumber(argument); - if (SameValue(ToString(n), argument)) { return n; } - return void 0; -}; diff --git a/node_modules/es-abstract/2017/CompletePropertyDescriptor.js b/node_modules/es-abstract/2017/CompletePropertyDescriptor.js deleted file mode 100644 index 548bf41..0000000 --- a/node_modules/es-abstract/2017/CompletePropertyDescriptor.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsGenericDescriptor = require('./IsGenericDescriptor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-completepropertydescriptor - -module.exports = function CompletePropertyDescriptor(Desc) { - /* eslint no-param-reassign: 0 */ - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (IsGenericDescriptor(Desc) || IsDataDescriptor(Desc)) { - if (!has(Desc, '[[Value]]')) { - Desc['[[Value]]'] = void 0; - } - if (!has(Desc, '[[Writable]]')) { - Desc['[[Writable]]'] = false; - } - } else { - if (!has(Desc, '[[Get]]')) { - Desc['[[Get]]'] = void 0; - } - if (!has(Desc, '[[Set]]')) { - Desc['[[Set]]'] = void 0; - } - } - if (!has(Desc, '[[Enumerable]]')) { - Desc['[[Enumerable]]'] = false; - } - if (!has(Desc, '[[Configurable]]')) { - Desc['[[Configurable]]'] = false; - } - return Desc; -}; diff --git a/node_modules/es-abstract/2017/CreateDataProperty.js b/node_modules/es-abstract/2017/CreateDataProperty.js deleted file mode 100644 index 32a86ef..0000000 --- a/node_modules/es-abstract/2017/CreateDataProperty.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var OrdinaryGetOwnProperty = require('./OrdinaryGetOwnProperty'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createdataproperty - -module.exports = function CreateDataProperty(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - var oldDesc = OrdinaryGetOwnProperty(O, P); - var extensible = !oldDesc || IsExtensible(O); - var immutable = oldDesc && (!oldDesc['[[Writable]]'] || !oldDesc['[[Configurable]]']); - if (immutable || !extensible) { - return false; - } - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': true, - '[[Enumerable]]': true, - '[[Value]]': V, - '[[Writable]]': true - } - ); -}; diff --git a/node_modules/es-abstract/2017/CreateDataPropertyOrThrow.js b/node_modules/es-abstract/2017/CreateDataPropertyOrThrow.js deleted file mode 100644 index 9feaec8..0000000 --- a/node_modules/es-abstract/2017/CreateDataPropertyOrThrow.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var CreateDataProperty = require('./CreateDataProperty'); -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// // https://ecma-international.org/ecma-262/6.0/#sec-createdatapropertyorthrow - -module.exports = function CreateDataPropertyOrThrow(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - var success = CreateDataProperty(O, P, V); - if (!success) { - throw new $TypeError('unable to create data property'); - } - return success; -}; diff --git a/node_modules/es-abstract/2017/CreateHTML.js b/node_modules/es-abstract/2017/CreateHTML.js deleted file mode 100644 index 536c92d..0000000 --- a/node_modules/es-abstract/2017/CreateHTML.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $replace = callBound('String.prototype.replace'); - -var RequireObjectCoercible = require('./RequireObjectCoercible'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createhtml - -module.exports = function CreateHTML(string, tag, attribute, value) { - if (Type(tag) !== 'String' || Type(attribute) !== 'String') { - throw new $TypeError('Assertion failed: `tag` and `attribute` must be strings'); - } - var str = RequireObjectCoercible(string); - var S = ToString(str); - var p1 = '<' + tag; - if (attribute !== '') { - var V = ToString(value); - var escapedV = $replace(V, /\x22/g, '"'); - p1 += '\x20' + attribute + '\x3D\x22' + escapedV + '\x22'; - } - return p1 + '>' + S + ''; -}; diff --git a/node_modules/es-abstract/2017/CreateIterResultObject.js b/node_modules/es-abstract/2017/CreateIterResultObject.js deleted file mode 100644 index aef1d22..0000000 --- a/node_modules/es-abstract/2017/CreateIterResultObject.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-createiterresultobject - -module.exports = function CreateIterResultObject(value, done) { - if (Type(done) !== 'Boolean') { - throw new $TypeError('Assertion failed: Type(done) is not Boolean'); - } - return { - value: value, - done: done - }; -}; diff --git a/node_modules/es-abstract/2017/CreateListFromArrayLike.js b/node_modules/es-abstract/2017/CreateListFromArrayLike.js deleted file mode 100644 index d6b44b5..0000000 --- a/node_modules/es-abstract/2017/CreateListFromArrayLike.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var callBound = require('../helpers/callBound'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $indexOf = callBound('Array.prototype.indexOf', true) || callBound('String.prototype.indexOf'); -var $push = callBound('Array.prototype.push'); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var ToLength = require('./ToLength'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-createlistfromarraylike -module.exports = function CreateListFromArrayLike(obj) { - var elementTypes = arguments.length > 1 - ? arguments[1] - : ['Undefined', 'Null', 'Boolean', 'String', 'Symbol', 'Number', 'Object']; - - if (Type(obj) !== 'Object') { - throw new $TypeError('Assertion failed: `obj` must be an Object'); - } - if (!IsArray(elementTypes)) { - throw new $TypeError('Assertion failed: `elementTypes`, if provided, must be an array'); - } - var len = ToLength(Get(obj, 'length')); - var list = []; - var index = 0; - while (index < len) { - var indexName = ToString(index); - var next = Get(obj, indexName); - var nextType = Type(next); - if ($indexOf(elementTypes, nextType) < 0) { - throw new $TypeError('item type ' + nextType + ' is not a valid elementType'); - } - $push(list, next); - index += 1; - } - return list; -}; diff --git a/node_modules/es-abstract/2017/CreateMethodProperty.js b/node_modules/es-abstract/2017/CreateMethodProperty.js deleted file mode 100644 index 5b599ae..0000000 --- a/node_modules/es-abstract/2017/CreateMethodProperty.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createmethodproperty - -module.exports = function CreateMethodProperty(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - var newDesc = { - '[[Configurable]]': true, - '[[Enumerable]]': false, - '[[Value]]': V, - '[[Writable]]': true - }; - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - newDesc - ); -}; diff --git a/node_modules/es-abstract/2017/DateFromTime.js b/node_modules/es-abstract/2017/DateFromTime.js deleted file mode 100644 index 962dba1..0000000 --- a/node_modules/es-abstract/2017/DateFromTime.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $EvalError = GetIntrinsic('%EvalError%'); - -var DayWithinYear = require('./DayWithinYear'); -var InLeapYear = require('./InLeapYear'); -var MonthFromTime = require('./MonthFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.5 - -module.exports = function DateFromTime(t) { - var m = MonthFromTime(t); - var d = DayWithinYear(t); - if (m === 0) { - return d + 1; - } - if (m === 1) { - return d - 30; - } - var leap = InLeapYear(t); - if (m === 2) { - return d - 58 - leap; - } - if (m === 3) { - return d - 89 - leap; - } - if (m === 4) { - return d - 119 - leap; - } - if (m === 5) { - return d - 150 - leap; - } - if (m === 6) { - return d - 180 - leap; - } - if (m === 7) { - return d - 211 - leap; - } - if (m === 8) { - return d - 242 - leap; - } - if (m === 9) { - return d - 272 - leap; - } - if (m === 10) { - return d - 303 - leap; - } - if (m === 11) { - return d - 333 - leap; - } - throw new $EvalError('Assertion failed: MonthFromTime returned an impossible value: ' + m); -}; diff --git a/node_modules/es-abstract/2017/Day.js b/node_modules/es-abstract/2017/Day.js deleted file mode 100644 index 00df813..0000000 --- a/node_modules/es-abstract/2017/Day.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - -module.exports = function Day(t) { - return $floor(t / msPerDay); -}; diff --git a/node_modules/es-abstract/2017/DayFromYear.js b/node_modules/es-abstract/2017/DayFromYear.js deleted file mode 100644 index 08dd5af..0000000 --- a/node_modules/es-abstract/2017/DayFromYear.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function DayFromYear(y) { - return (365 * (y - 1970)) + $floor((y - 1969) / 4) - $floor((y - 1901) / 100) + $floor((y - 1601) / 400); -}; - diff --git a/node_modules/es-abstract/2017/DayWithinYear.js b/node_modules/es-abstract/2017/DayWithinYear.js deleted file mode 100644 index cfc4002..0000000 --- a/node_modules/es-abstract/2017/DayWithinYear.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var Day = require('./Day'); -var DayFromYear = require('./DayFromYear'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - -module.exports = function DayWithinYear(t) { - return Day(t) - DayFromYear(YearFromTime(t)); -}; diff --git a/node_modules/es-abstract/2017/DaysInYear.js b/node_modules/es-abstract/2017/DaysInYear.js deleted file mode 100644 index db32251..0000000 --- a/node_modules/es-abstract/2017/DaysInYear.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function DaysInYear(y) { - if (mod(y, 4) !== 0) { - return 365; - } - if (mod(y, 100) !== 0) { - return 366; - } - if (mod(y, 400) !== 0) { - return 365; - } - return 366; -}; diff --git a/node_modules/es-abstract/2017/DefinePropertyOrThrow.js b/node_modules/es-abstract/2017/DefinePropertyOrThrow.js deleted file mode 100644 index 7977f6e..0000000 --- a/node_modules/es-abstract/2017/DefinePropertyOrThrow.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-definepropertyorthrow - -module.exports = function DefinePropertyOrThrow(O, P, desc) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - var Desc = isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, desc) ? desc : ToPropertyDescriptor(desc); - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc is not a valid Property Descriptor'); - } - - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); -}; diff --git a/node_modules/es-abstract/2017/DeletePropertyOrThrow.js b/node_modules/es-abstract/2017/DeletePropertyOrThrow.js deleted file mode 100644 index b476817..0000000 --- a/node_modules/es-abstract/2017/DeletePropertyOrThrow.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-deletepropertyorthrow - -module.exports = function DeletePropertyOrThrow(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // eslint-disable-next-line no-param-reassign - var success = delete O[P]; - if (!success) { - throw new $TypeError('Attempt to delete property failed.'); - } - return success; -}; diff --git a/node_modules/es-abstract/2017/EnumerableOwnProperties.js b/node_modules/es-abstract/2017/EnumerableOwnProperties.js deleted file mode 100644 index e2ed722..0000000 --- a/node_modules/es-abstract/2017/EnumerableOwnProperties.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var objectKeys = require('object-keys'); - -var callBound = require('../helpers/callBound'); - -var callBind = require('../helpers/callBind'); - -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); -var $pushApply = callBind.apply(GetIntrinsic('%Array.prototype.push%')); - -var forEach = require('../helpers/forEach'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/8.0/#sec-enumerableownproperties - -module.exports = function EnumerableOwnProperties(O, kind) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - var keys = objectKeys(O); - if (kind === 'key') { - return keys; - } - if (kind === 'value' || kind === 'key+value') { - var results = []; - forEach(keys, function (key) { - if ($isEnumerable(O, key)) { - $pushApply(results, [ - kind === 'value' ? O[key] : [key, O[key]] - ]); - } - }); - return results; - } - throw new $TypeError('Assertion failed: "kind" is not "key", "value", or "key+value": ' + kind); -}; diff --git a/node_modules/es-abstract/2017/FromPropertyDescriptor.js b/node_modules/es-abstract/2017/FromPropertyDescriptor.js deleted file mode 100644 index 5ec200e..0000000 --- a/node_modules/es-abstract/2017/FromPropertyDescriptor.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-frompropertydescriptor - -module.exports = function FromPropertyDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return Desc; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - var obj = {}; - if ('[[Value]]' in Desc) { - obj.value = Desc['[[Value]]']; - } - if ('[[Writable]]' in Desc) { - obj.writable = Desc['[[Writable]]']; - } - if ('[[Get]]' in Desc) { - obj.get = Desc['[[Get]]']; - } - if ('[[Set]]' in Desc) { - obj.set = Desc['[[Set]]']; - } - if ('[[Enumerable]]' in Desc) { - obj.enumerable = Desc['[[Enumerable]]']; - } - if ('[[Configurable]]' in Desc) { - obj.configurable = Desc['[[Configurable]]']; - } - return obj; -}; diff --git a/node_modules/es-abstract/2017/Get.js b/node_modules/es-abstract/2017/Get.js deleted file mode 100644 index 5b9ad78..0000000 --- a/node_modules/es-abstract/2017/Get.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var inspect = require('object-inspect'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -/** - * 7.3.1 Get (O, P) - https://ecma-international.org/ecma-262/6.0/#sec-get-o-p - * 1. Assert: Type(O) is Object. - * 2. Assert: IsPropertyKey(P) is true. - * 3. Return O.[[Get]](P, O). - */ - -module.exports = function Get(O, P) { - // 7.3.1.1 - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - // 7.3.1.2 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true, got ' + inspect(P)); - } - // 7.3.1.3 - return O[P]; -}; diff --git a/node_modules/es-abstract/2017/GetIterator.js b/node_modules/es-abstract/2017/GetIterator.js deleted file mode 100644 index 7beddac..0000000 --- a/node_modules/es-abstract/2017/GetIterator.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var getIteratorMethod = require('../helpers/getIteratorMethod'); -var AdvanceStringIndex = require('./AdvanceStringIndex'); -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsArray = require('./IsArray'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-getiterator - -module.exports = function GetIterator(obj, method) { - var actualMethod = method; - if (arguments.length < 2) { - actualMethod = getIteratorMethod( - { - AdvanceStringIndex: AdvanceStringIndex, - GetMethod: GetMethod, - IsArray: IsArray, - Type: Type - }, - obj - ); - } - var iterator = Call(actualMethod, obj); - if (Type(iterator) !== 'Object') { - throw new $TypeError('iterator must return an object'); - } - - return iterator; -}; diff --git a/node_modules/es-abstract/2017/GetMethod.js b/node_modules/es-abstract/2017/GetMethod.js deleted file mode 100644 index aef8cbc..0000000 --- a/node_modules/es-abstract/2017/GetMethod.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var GetV = require('./GetV'); -var IsCallable = require('./IsCallable'); -var IsPropertyKey = require('./IsPropertyKey'); - -/** - * 7.3.9 - https://ecma-international.org/ecma-262/6.0/#sec-getmethod - * 1. Assert: IsPropertyKey(P) is true. - * 2. Let func be GetV(O, P). - * 3. ReturnIfAbrupt(func). - * 4. If func is either undefined or null, return undefined. - * 5. If IsCallable(func) is false, throw a TypeError exception. - * 6. Return func. - */ - -module.exports = function GetMethod(O, P) { - // 7.3.9.1 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // 7.3.9.2 - var func = GetV(O, P); - - // 7.3.9.4 - if (func == null) { - return void 0; - } - - // 7.3.9.5 - if (!IsCallable(func)) { - throw new $TypeError(P + 'is not a function'); - } - - // 7.3.9.6 - return func; -}; diff --git a/node_modules/es-abstract/2017/GetOwnPropertyKeys.js b/node_modules/es-abstract/2017/GetOwnPropertyKeys.js deleted file mode 100644 index 8d7e5ee..0000000 --- a/node_modules/es-abstract/2017/GetOwnPropertyKeys.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var hasSymbols = require('has-symbols')(); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); -var $gOPS = hasSymbols && GetIntrinsic('%Object.getOwnPropertySymbols%'); -var keys = require('object-keys'); - -var esType = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-getownpropertykeys - -module.exports = function GetOwnPropertyKeys(O, Type) { - if (esType(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (Type === 'Symbol') { - return $gOPS ? $gOPS(O) : []; - } - if (Type === 'String') { - if (!$gOPN) { - return keys(O); - } - return $gOPN(O); - } - throw new $TypeError('Assertion failed: `Type` must be `"String"` or `"Symbol"`'); -}; diff --git a/node_modules/es-abstract/2017/GetPrototypeFromConstructor.js b/node_modules/es-abstract/2017/GetPrototypeFromConstructor.js deleted file mode 100644 index 62da8fb..0000000 --- a/node_modules/es-abstract/2017/GetPrototypeFromConstructor.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Function = GetIntrinsic('%Function%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsConstructor = require('./IsConstructor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-getprototypefromconstructor - -module.exports = function GetPrototypeFromConstructor(constructor, intrinsicDefaultProto) { - var intrinsic = GetIntrinsic(intrinsicDefaultProto); // throws if not a valid intrinsic - if (!IsConstructor(constructor)) { - throw new $TypeError('Assertion failed: `constructor` must be a constructor'); - } - var proto = Get(constructor, 'prototype'); - if (Type(proto) !== 'Object') { - if (!(constructor instanceof $Function)) { - // ignore other realms, for now - throw new $TypeError('cross-realm constructors not currently supported'); - } - proto = intrinsic; - } - return proto; -}; diff --git a/node_modules/es-abstract/2017/GetSubstitution.js b/node_modules/es-abstract/2017/GetSubstitution.js deleted file mode 100644 index de41b01..0000000 --- a/node_modules/es-abstract/2017/GetSubstitution.js +++ /dev/null @@ -1,104 +0,0 @@ - -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $parseInt = GetIntrinsic('%parseInt%'); - -var inspect = require('object-inspect'); - -var regexTester = require('../helpers/regexTester'); -var callBound = require('../helpers/callBound'); -var every = require('../helpers/every'); - -var isDigit = regexTester(/^[0-9]$/); - -var $charAt = callBound('String.prototype.charAt'); -var $strSlice = callBound('String.prototype.slice'); - -var IsArray = require('./IsArray'); -var IsInteger = require('./IsInteger'); -var Type = require('./Type'); - -var canDistinguishSparseFromUndefined = 0 in [undefined]; // IE 6 - 8 have a bug where this returns false - -var isStringOrHole = function (capture, index, arr) { - return Type(capture) === 'String' || (canDistinguishSparseFromUndefined ? !(index in arr) : Type(capture) === 'Undefined'); -}; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-getsubstitution - -// eslint-disable-next-line max-statements, max-params, max-lines-per-function -module.exports = function GetSubstitution(matched, str, position, captures, replacement) { - if (Type(matched) !== 'String') { - throw new $TypeError('Assertion failed: `matched` must be a String'); - } - var matchLength = matched.length; - - if (Type(str) !== 'String') { - throw new $TypeError('Assertion failed: `str` must be a String'); - } - var stringLength = str.length; - - if (!IsInteger(position) || position < 0 || position > stringLength) { - throw new $TypeError('Assertion failed: `position` must be a nonnegative integer, and less than or equal to the length of `string`, got ' + inspect(position)); - } - - if (!IsArray(captures) || !every(captures, isStringOrHole)) { - throw new $TypeError('Assertion failed: `captures` must be a List of Strings, got ' + inspect(captures)); - } - - if (Type(replacement) !== 'String') { - throw new $TypeError('Assertion failed: `replacement` must be a String'); - } - - var tailPos = position + matchLength; - var m = captures.length; - - var result = ''; - for (var i = 0; i < replacement.length; i += 1) { - // if this is a $, and it's not the end of the replacement - var current = $charAt(replacement, i); - var isLast = (i + 1) >= replacement.length; - var nextIsLast = (i + 2) >= replacement.length; - if (current === '$' && !isLast) { - var next = $charAt(replacement, i + 1); - if (next === '$') { - result += '$'; - i += 1; - } else if (next === '&') { - result += matched; - i += 1; - } else if (next === '`') { - result += position === 0 ? '' : $strSlice(str, 0, position - 1); - i += 1; - } else if (next === "'") { - result += tailPos >= stringLength ? '' : $strSlice(str, tailPos); - i += 1; - } else { - var nextNext = nextIsLast ? null : $charAt(replacement, i + 2); - if (isDigit(next) && next !== '0' && (nextIsLast || !isDigit(nextNext))) { - // $1 through $9, and not followed by a digit - var n = $parseInt(next, 10); - // if (n > m, impl-defined) - result += (n <= m && Type(captures[n - 1]) === 'Undefined') ? '' : captures[n - 1]; - i += 1; - } else if (isDigit(next) && (nextIsLast || isDigit(nextNext))) { - // $00 through $99 - var nn = next + nextNext; - var nnI = $parseInt(nn, 10) - 1; - // if nn === '00' or nn > m, impl-defined - result += (nn <= m && Type(captures[nnI]) === 'Undefined') ? '' : captures[nnI]; - i += 2; - } else { - result += '$'; - } - } - } else { - // the final $, or else not a $ - result += $charAt(replacement, i); - } - } - return result; -}; diff --git a/node_modules/es-abstract/2017/GetV.js b/node_modules/es-abstract/2017/GetV.js deleted file mode 100644 index 7b5139a..0000000 --- a/node_modules/es-abstract/2017/GetV.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var ToObject = require('./ToObject'); - -/** - * 7.3.2 GetV (V, P) - * 1. Assert: IsPropertyKey(P) is true. - * 2. Let O be ToObject(V). - * 3. ReturnIfAbrupt(O). - * 4. Return O.[[Get]](P, V). - */ - -module.exports = function GetV(V, P) { - // 7.3.2.1 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // 7.3.2.2-3 - var O = ToObject(V); - - // 7.3.2.4 - return O[P]; -}; diff --git a/node_modules/es-abstract/2017/HasOwnProperty.js b/node_modules/es-abstract/2017/HasOwnProperty.js deleted file mode 100644 index 679059f..0000000 --- a/node_modules/es-abstract/2017/HasOwnProperty.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var has = require('has'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-hasownproperty - -module.exports = function HasOwnProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - return has(O, P); -}; diff --git a/node_modules/es-abstract/2017/HasProperty.js b/node_modules/es-abstract/2017/HasProperty.js deleted file mode 100644 index 5f2d212..0000000 --- a/node_modules/es-abstract/2017/HasProperty.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-hasproperty - -module.exports = function HasProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - return P in O; -}; diff --git a/node_modules/es-abstract/2017/HourFromTime.js b/node_modules/es-abstract/2017/HourFromTime.js deleted file mode 100644 index 957ce32..0000000 --- a/node_modules/es-abstract/2017/HourFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerHour = timeConstants.msPerHour; -var HoursPerDay = timeConstants.HoursPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function HourFromTime(t) { - return mod($floor(t / msPerHour), HoursPerDay); -}; diff --git a/node_modules/es-abstract/2017/InLeapYear.js b/node_modules/es-abstract/2017/InLeapYear.js deleted file mode 100644 index 38ba8fd..0000000 --- a/node_modules/es-abstract/2017/InLeapYear.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $EvalError = GetIntrinsic('%EvalError%'); - -var DaysInYear = require('./DaysInYear'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function InLeapYear(t) { - var days = DaysInYear(YearFromTime(t)); - if (days === 365) { - return 0; - } - if (days === 366) { - return 1; - } - throw new $EvalError('Assertion failed: there are not 365 or 366 days in a year, got: ' + days); -}; diff --git a/node_modules/es-abstract/2017/InstanceofOperator.js b/node_modules/es-abstract/2017/InstanceofOperator.js deleted file mode 100644 index ebd308c..0000000 --- a/node_modules/es-abstract/2017/InstanceofOperator.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $hasInstance = GetIntrinsic('Symbol.hasInstance', true); - -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsCallable = require('./IsCallable'); -var OrdinaryHasInstance = require('./OrdinaryHasInstance'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-instanceofoperator - -module.exports = function InstanceofOperator(O, C) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - var instOfHandler = $hasInstance ? GetMethod(C, $hasInstance) : void 0; - if (typeof instOfHandler !== 'undefined') { - return ToBoolean(Call(instOfHandler, C, [O])); - } - if (!IsCallable(C)) { - throw new $TypeError('`C` is not Callable'); - } - return OrdinaryHasInstance(C, O); -}; diff --git a/node_modules/es-abstract/2017/Invoke.js b/node_modules/es-abstract/2017/Invoke.js deleted file mode 100644 index 769f0e3..0000000 --- a/node_modules/es-abstract/2017/Invoke.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $arraySlice = require('../helpers/callBound')('Array.prototype.slice'); - -var Call = require('./Call'); -var GetV = require('./GetV'); -var IsPropertyKey = require('./IsPropertyKey'); - -// https://ecma-international.org/ecma-262/6.0/#sec-invoke - -module.exports = function Invoke(O, P) { - if (!IsPropertyKey(P)) { - throw new $TypeError('P must be a Property Key'); - } - var argumentsList = $arraySlice(arguments, 2); - var func = GetV(O, P); - return Call(func, O, argumentsList); -}; diff --git a/node_modules/es-abstract/2017/IsAccessorDescriptor.js b/node_modules/es-abstract/2017/IsAccessorDescriptor.js deleted file mode 100644 index 5139464..0000000 --- a/node_modules/es-abstract/2017/IsAccessorDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isaccessordescriptor - -module.exports = function IsAccessorDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) { - return false; - } - - return true; -}; diff --git a/node_modules/es-abstract/2017/IsArray.js b/node_modules/es-abstract/2017/IsArray.js deleted file mode 100644 index 7b25f37..0000000 --- a/node_modules/es-abstract/2017/IsArray.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Array = GetIntrinsic('%Array%'); - -// eslint-disable-next-line global-require -var toStr = !$Array.isArray && require('../helpers/callBound')('Object.prototype.toString'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isarray - -module.exports = $Array.isArray || function IsArray(argument) { - return toStr(argument) === '[object Array]'; -}; diff --git a/node_modules/es-abstract/2017/IsCallable.js b/node_modules/es-abstract/2017/IsCallable.js deleted file mode 100644 index e4bfa36..0000000 --- a/node_modules/es-abstract/2017/IsCallable.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.11 - -module.exports = require('is-callable'); diff --git a/node_modules/es-abstract/2017/IsConcatSpreadable.js b/node_modules/es-abstract/2017/IsConcatSpreadable.js deleted file mode 100644 index dc8aae1..0000000 --- a/node_modules/es-abstract/2017/IsConcatSpreadable.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $isConcatSpreadable = GetIntrinsic('%Symbol.isConcatSpreadable%', true); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-isconcatspreadable - -module.exports = function IsConcatSpreadable(O) { - if (Type(O) !== 'Object') { - return false; - } - if ($isConcatSpreadable) { - var spreadable = Get(O, $isConcatSpreadable); - if (typeof spreadable !== 'undefined') { - return ToBoolean(spreadable); - } - } - return IsArray(O); -}; diff --git a/node_modules/es-abstract/2017/IsConstructor.js b/node_modules/es-abstract/2017/IsConstructor.js deleted file mode 100644 index 00ea52c..0000000 --- a/node_modules/es-abstract/2017/IsConstructor.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isconstructor - -module.exports = function IsConstructor(argument) { - return typeof argument === 'function' && !!argument.prototype; // unfortunately there's no way to truly check this without try/catch `new argument` -}; diff --git a/node_modules/es-abstract/2017/IsDataDescriptor.js b/node_modules/es-abstract/2017/IsDataDescriptor.js deleted file mode 100644 index 0ad3045..0000000 --- a/node_modules/es-abstract/2017/IsDataDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isdatadescriptor - -module.exports = function IsDataDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) { - return false; - } - - return true; -}; diff --git a/node_modules/es-abstract/2017/IsExtensible.js b/node_modules/es-abstract/2017/IsExtensible.js deleted file mode 100644 index 0c4c8a6..0000000 --- a/node_modules/es-abstract/2017/IsExtensible.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Object = GetIntrinsic('%Object%'); - -var isPrimitive = require('../helpers/isPrimitive'); - -var $preventExtensions = $Object.preventExtensions; -var $isExtensible = $Object.isExtensible; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isextensible-o - -module.exports = $preventExtensions - ? function IsExtensible(obj) { - return !isPrimitive(obj) && $isExtensible(obj); - } - : function IsExtensible(obj) { - return !isPrimitive(obj); - }; diff --git a/node_modules/es-abstract/2017/IsGenericDescriptor.js b/node_modules/es-abstract/2017/IsGenericDescriptor.js deleted file mode 100644 index 8618ce4..0000000 --- a/node_modules/es-abstract/2017/IsGenericDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var assertRecord = require('../helpers/assertRecord'); - -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isgenericdescriptor - -module.exports = function IsGenericDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!IsAccessorDescriptor(Desc) && !IsDataDescriptor(Desc)) { - return true; - } - - return false; -}; diff --git a/node_modules/es-abstract/2017/IsInteger.js b/node_modules/es-abstract/2017/IsInteger.js deleted file mode 100644 index 0f488b3..0000000 --- a/node_modules/es-abstract/2017/IsInteger.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isinteger - -module.exports = function IsInteger(argument) { - if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) { - return false; - } - var abs = $abs(argument); - return $floor(abs) === abs; -}; diff --git a/node_modules/es-abstract/2017/IsPromise.js b/node_modules/es-abstract/2017/IsPromise.js deleted file mode 100644 index e8e92a2..0000000 --- a/node_modules/es-abstract/2017/IsPromise.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var $PromiseThen = callBound('Promise.prototype.then', true); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ispromise - -module.exports = function IsPromise(x) { - if (Type(x) !== 'Object') { - return false; - } - if (!$PromiseThen) { // Promises are not supported - return false; - } - try { - $PromiseThen(x); // throws if not a promise - } catch (e) { - return false; - } - return true; -}; diff --git a/node_modules/es-abstract/2017/IsPropertyDescriptor.js b/node_modules/es-abstract/2017/IsPropertyDescriptor.js deleted file mode 100644 index 2a96c63..0000000 --- a/node_modules/es-abstract/2017/IsPropertyDescriptor.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var Type = require('./Type'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); - -// https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type - -module.exports = function IsPropertyDescriptor(Desc) { - return isPropertyDescriptor({ - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor, - Type: Type - }, Desc); -}; diff --git a/node_modules/es-abstract/2017/IsPropertyKey.js b/node_modules/es-abstract/2017/IsPropertyKey.js deleted file mode 100644 index 74b8d95..0000000 --- a/node_modules/es-abstract/2017/IsPropertyKey.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ispropertykey - -module.exports = function IsPropertyKey(argument) { - return typeof argument === 'string' || typeof argument === 'symbol'; -}; diff --git a/node_modules/es-abstract/2017/IsRegExp.js b/node_modules/es-abstract/2017/IsRegExp.js deleted file mode 100644 index fdf2323..0000000 --- a/node_modules/es-abstract/2017/IsRegExp.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $match = GetIntrinsic('%Symbol.match%', true); - -var hasRegExpMatcher = require('is-regex'); - -var ToBoolean = require('./ToBoolean'); - -// https://ecma-international.org/ecma-262/6.0/#sec-isregexp - -module.exports = function IsRegExp(argument) { - if (!argument || typeof argument !== 'object') { - return false; - } - if ($match) { - var isRegExp = argument[$match]; - if (typeof isRegExp !== 'undefined') { - return ToBoolean(isRegExp); - } - } - return hasRegExpMatcher(argument); -}; diff --git a/node_modules/es-abstract/2017/IterableToList.js b/node_modules/es-abstract/2017/IterableToList.js deleted file mode 100644 index 0b8cdcf..0000000 --- a/node_modules/es-abstract/2017/IterableToList.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); -var $arrayPush = callBound('Array.prototype.push'); - -var GetIterator = require('./GetIterator'); -var IteratorStep = require('./IteratorStep'); -var IteratorValue = require('./IteratorValue'); - -// https://www.ecma-international.org/ecma-262/8.0/#sec-iterabletolist - -module.exports = function IterableToList(items, method) { - var iterator = GetIterator(items, method); - var values = []; - var next = true; - while (next) { - next = IteratorStep(iterator); - if (next) { - var nextValue = IteratorValue(next); - $arrayPush(values, nextValue); - } - } - return values; -}; diff --git a/node_modules/es-abstract/2017/IteratorClose.js b/node_modules/es-abstract/2017/IteratorClose.js deleted file mode 100644 index 35c8c2b..0000000 --- a/node_modules/es-abstract/2017/IteratorClose.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorclose - -module.exports = function IteratorClose(iterator, completion) { - if (Type(iterator) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterator) is not Object'); - } - if (!IsCallable(completion)) { - throw new $TypeError('Assertion failed: completion is not a thunk for a Completion Record'); - } - var completionThunk = completion; - - var iteratorReturn = GetMethod(iterator, 'return'); - - if (typeof iteratorReturn === 'undefined') { - return completionThunk(); - } - - var completionRecord; - try { - var innerResult = Call(iteratorReturn, iterator, []); - } catch (e) { - // if we hit here, then "e" is the innerResult completion that needs re-throwing - - // if the completion is of type "throw", this will throw. - completionThunk(); - completionThunk = null; // ensure it's not called twice. - - // if not, then return the innerResult completion - throw e; - } - completionRecord = completionThunk(); // if innerResult worked, then throw if the completion does - completionThunk = null; // ensure it's not called twice. - - if (Type(innerResult) !== 'Object') { - throw new $TypeError('iterator .return must return an object'); - } - - return completionRecord; -}; diff --git a/node_modules/es-abstract/2017/IteratorComplete.js b/node_modules/es-abstract/2017/IteratorComplete.js deleted file mode 100644 index a62b9bf..0000000 --- a/node_modules/es-abstract/2017/IteratorComplete.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorcomplete - -module.exports = function IteratorComplete(iterResult) { - if (Type(iterResult) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); - } - return ToBoolean(Get(iterResult, 'done')); -}; diff --git a/node_modules/es-abstract/2017/IteratorNext.js b/node_modules/es-abstract/2017/IteratorNext.js deleted file mode 100644 index 7e59915..0000000 --- a/node_modules/es-abstract/2017/IteratorNext.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Invoke = require('./Invoke'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratornext - -module.exports = function IteratorNext(iterator, value) { - var result = Invoke(iterator, 'next', arguments.length < 2 ? [] : [value]); - if (Type(result) !== 'Object') { - throw new $TypeError('iterator next must return an object'); - } - return result; -}; diff --git a/node_modules/es-abstract/2017/IteratorStep.js b/node_modules/es-abstract/2017/IteratorStep.js deleted file mode 100644 index 41b9d1b..0000000 --- a/node_modules/es-abstract/2017/IteratorStep.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var IteratorComplete = require('./IteratorComplete'); -var IteratorNext = require('./IteratorNext'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorstep - -module.exports = function IteratorStep(iterator) { - var result = IteratorNext(iterator); - var done = IteratorComplete(result); - return done === true ? false : result; -}; - diff --git a/node_modules/es-abstract/2017/IteratorValue.js b/node_modules/es-abstract/2017/IteratorValue.js deleted file mode 100644 index 5e71a44..0000000 --- a/node_modules/es-abstract/2017/IteratorValue.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorvalue - -module.exports = function IteratorValue(iterResult) { - if (Type(iterResult) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); - } - return Get(iterResult, 'value'); -}; - diff --git a/node_modules/es-abstract/2017/MakeDate.js b/node_modules/es-abstract/2017/MakeDate.js deleted file mode 100644 index 7b592d1..0000000 --- a/node_modules/es-abstract/2017/MakeDate.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $isFinite = require('../helpers/isFinite'); -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.13 - -module.exports = function MakeDate(day, time) { - if (!$isFinite(day) || !$isFinite(time)) { - return NaN; - } - return (day * msPerDay) + time; -}; diff --git a/node_modules/es-abstract/2017/MakeDay.js b/node_modules/es-abstract/2017/MakeDay.js deleted file mode 100644 index f1ab810..0000000 --- a/node_modules/es-abstract/2017/MakeDay.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); -var $DateUTC = GetIntrinsic('%Date.UTC%'); - -var mod = require('../helpers/mod'); -var $isFinite = require('../helpers/isFinite'); - -var DateFromTime = require('./DateFromTime'); -var Day = require('./Day'); -var MonthFromTime = require('./MonthFromTime'); -var ToInteger = require('./ToInteger'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.12 - -module.exports = function MakeDay(year, month, date) { - if (!$isFinite(year) || !$isFinite(month) || !$isFinite(date)) { - return NaN; - } - var y = ToInteger(year); - var m = ToInteger(month); - var dt = ToInteger(date); - var ym = y + $floor(m / 12); - var mn = mod(m, 12); - var t = $DateUTC(ym, mn, 1); - if (YearFromTime(t) !== ym || MonthFromTime(t) !== mn || DateFromTime(t) !== 1) { - return NaN; - } - return Day(t) + dt - 1; -}; diff --git a/node_modules/es-abstract/2017/MakeTime.js b/node_modules/es-abstract/2017/MakeTime.js deleted file mode 100644 index e118500..0000000 --- a/node_modules/es-abstract/2017/MakeTime.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var $isFinite = require('../helpers/isFinite'); -var timeConstants = require('../helpers/timeConstants'); -var msPerSecond = timeConstants.msPerSecond; -var msPerMinute = timeConstants.msPerMinute; -var msPerHour = timeConstants.msPerHour; - -var ToInteger = require('./ToInteger'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.11 - -module.exports = function MakeTime(hour, min, sec, ms) { - if (!$isFinite(hour) || !$isFinite(min) || !$isFinite(sec) || !$isFinite(ms)) { - return NaN; - } - var h = ToInteger(hour); - var m = ToInteger(min); - var s = ToInteger(sec); - var milli = ToInteger(ms); - var t = (h * msPerHour) + (m * msPerMinute) + (s * msPerSecond) + milli; - return t; -}; diff --git a/node_modules/es-abstract/2017/MinFromTime.js b/node_modules/es-abstract/2017/MinFromTime.js deleted file mode 100644 index e80e191..0000000 --- a/node_modules/es-abstract/2017/MinFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerMinute = timeConstants.msPerMinute; -var MinutesPerHour = timeConstants.MinutesPerHour; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function MinFromTime(t) { - return mod($floor(t / msPerMinute), MinutesPerHour); -}; diff --git a/node_modules/es-abstract/2017/MonthFromTime.js b/node_modules/es-abstract/2017/MonthFromTime.js deleted file mode 100644 index 4f120f2..0000000 --- a/node_modules/es-abstract/2017/MonthFromTime.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -var DayWithinYear = require('./DayWithinYear'); -var InLeapYear = require('./InLeapYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - -module.exports = function MonthFromTime(t) { - var day = DayWithinYear(t); - if (0 <= day && day < 31) { - return 0; - } - var leap = InLeapYear(t); - if (31 <= day && day < (59 + leap)) { - return 1; - } - if ((59 + leap) <= day && day < (90 + leap)) { - return 2; - } - if ((90 + leap) <= day && day < (120 + leap)) { - return 3; - } - if ((120 + leap) <= day && day < (151 + leap)) { - return 4; - } - if ((151 + leap) <= day && day < (181 + leap)) { - return 5; - } - if ((181 + leap) <= day && day < (212 + leap)) { - return 6; - } - if ((212 + leap) <= day && day < (243 + leap)) { - return 7; - } - if ((243 + leap) <= day && day < (273 + leap)) { - return 8; - } - if ((273 + leap) <= day && day < (304 + leap)) { - return 9; - } - if ((304 + leap) <= day && day < (334 + leap)) { - return 10; - } - if ((334 + leap) <= day && day < (365 + leap)) { - return 11; - } -}; diff --git a/node_modules/es-abstract/2017/ObjectCreate.js b/node_modules/es-abstract/2017/ObjectCreate.js deleted file mode 100644 index e2445b0..0000000 --- a/node_modules/es-abstract/2017/ObjectCreate.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $ObjectCreate = GetIntrinsic('%Object.create%', true); -var $TypeError = GetIntrinsic('%TypeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); - -var Type = require('./Type'); - -var hasProto = !({ __proto__: null } instanceof Object); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-objectcreate - -module.exports = function ObjectCreate(proto, internalSlotsList) { - if (proto !== null && Type(proto) !== 'Object') { - throw new $TypeError('Assertion failed: `proto` must be null or an object'); - } - var slots = arguments.length < 2 ? [] : internalSlotsList; - if (slots.length > 0) { - throw new $SyntaxError('es-abstract does not yet support internal slots'); - } - - if ($ObjectCreate) { - return $ObjectCreate(proto); - } - if (hasProto) { - return { __proto__: proto }; - } - - if (proto === null) { - throw new $SyntaxError('native Object.create support is required to create null objects'); - } - var T = function T() {}; - T.prototype = proto; - return new T(); -}; diff --git a/node_modules/es-abstract/2017/OrdinaryDefineOwnProperty.js b/node_modules/es-abstract/2017/OrdinaryDefineOwnProperty.js deleted file mode 100644 index 59780b3..0000000 --- a/node_modules/es-abstract/2017/OrdinaryDefineOwnProperty.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var IsPropertyKey = require('./IsPropertyKey'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); -var ValidateAndApplyPropertyDescriptor = require('./ValidateAndApplyPropertyDescriptor'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarydefineownproperty - -module.exports = function OrdinaryDefineOwnProperty(O, P, Desc) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (!$gOPD) { - // ES3/IE 8 fallback - if (IsAccessorDescriptor(Desc)) { - throw new $SyntaxError('This environment does not support accessor property descriptors.'); - } - var creatingNormalDataProperty = !(P in O) - && Desc['[[Writable]]'] - && Desc['[[Enumerable]]'] - && Desc['[[Configurable]]'] - && '[[Value]]' in Desc; - var settingExistingDataProperty = (P in O) - && (!('[[Configurable]]' in Desc) || Desc['[[Configurable]]']) - && (!('[[Enumerable]]' in Desc) || Desc['[[Enumerable]]']) - && (!('[[Writable]]' in Desc) || Desc['[[Writable]]']) - && '[[Value]]' in Desc; - if (creatingNormalDataProperty || settingExistingDataProperty) { - O[P] = Desc['[[Value]]']; // eslint-disable-line no-param-reassign - return SameValue(O[P], Desc['[[Value]]']); - } - throw new $SyntaxError('This environment does not support defining non-writable, non-enumerable, or non-configurable properties'); - } - var desc = $gOPD(O, P); - var current = desc && ToPropertyDescriptor(desc); - var extensible = IsExtensible(O); - return ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current); -}; diff --git a/node_modules/es-abstract/2017/OrdinaryGetOwnProperty.js b/node_modules/es-abstract/2017/OrdinaryGetOwnProperty.js deleted file mode 100644 index b9882e5..0000000 --- a/node_modules/es-abstract/2017/OrdinaryGetOwnProperty.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); - -var has = require('has'); - -var IsArray = require('./IsArray'); -var IsPropertyKey = require('./IsPropertyKey'); -var IsRegExp = require('./IsRegExp'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarygetownproperty - -module.exports = function OrdinaryGetOwnProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - if (!has(O, P)) { - return void 0; - } - if (!$gOPD) { - // ES3 / IE 8 fallback - var arrayLength = IsArray(O) && P === 'length'; - var regexLastIndex = IsRegExp(O) && P === 'lastIndex'; - return { - '[[Configurable]]': !(arrayLength || regexLastIndex), - '[[Enumerable]]': $isEnumerable(O, P), - '[[Value]]': O[P], - '[[Writable]]': true - }; - } - return ToPropertyDescriptor($gOPD(O, P)); -}; diff --git a/node_modules/es-abstract/2017/OrdinaryGetPrototypeOf.js b/node_modules/es-abstract/2017/OrdinaryGetPrototypeOf.js deleted file mode 100644 index 344077a..0000000 --- a/node_modules/es-abstract/2017/OrdinaryGetPrototypeOf.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $getProto = require('../helpers/getProto'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/7.0/#sec-ordinarygetprototypeof - -module.exports = function OrdinaryGetPrototypeOf(O) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!$getProto) { - throw new $TypeError('This environment does not support fetching prototypes.'); - } - return $getProto(O); -}; diff --git a/node_modules/es-abstract/2017/OrdinaryHasInstance.js b/node_modules/es-abstract/2017/OrdinaryHasInstance.js deleted file mode 100644 index 51abe26..0000000 --- a/node_modules/es-abstract/2017/OrdinaryHasInstance.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance - -module.exports = function OrdinaryHasInstance(C, O) { - if (IsCallable(C) === false) { - return false; - } - if (Type(O) !== 'Object') { - return false; - } - var P = Get(C, 'prototype'); - if (Type(P) !== 'Object') { - throw new $TypeError('OrdinaryHasInstance called on an object with an invalid prototype property.'); - } - return O instanceof C; -}; diff --git a/node_modules/es-abstract/2017/OrdinaryHasProperty.js b/node_modules/es-abstract/2017/OrdinaryHasProperty.js deleted file mode 100644 index 076c25a..0000000 --- a/node_modules/es-abstract/2017/OrdinaryHasProperty.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasproperty - -module.exports = function OrdinaryHasProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - return P in O; -}; diff --git a/node_modules/es-abstract/2017/OrdinarySetPrototypeOf.js b/node_modules/es-abstract/2017/OrdinarySetPrototypeOf.js deleted file mode 100644 index 3541331..0000000 --- a/node_modules/es-abstract/2017/OrdinarySetPrototypeOf.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $setProto = require('../helpers/setProto'); - -var OrdinaryGetPrototypeOf = require('./OrdinaryGetPrototypeOf'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/7.0/#sec-ordinarysetprototypeof - -module.exports = function OrdinarySetPrototypeOf(O, V) { - if (Type(V) !== 'Object' && Type(V) !== 'Null') { - throw new $TypeError('Assertion failed: V must be Object or Null'); - } - /* - var extensible = IsExtensible(O); - var current = OrdinaryGetPrototypeOf(O); - if (SameValue(V, current)) { - return true; - } - if (!extensible) { - return false; - } - */ - try { - $setProto(O, V); - } catch (e) { - return false; - } - return OrdinaryGetPrototypeOf(O) === V; - /* - var p = V; - var done = false; - while (!done) { - if (p === null) { - done = true; - } else if (SameValue(p, O)) { - return false; - } else { - if (wat) { - done = true; - } else { - p = p.[[Prototype]]; - } - } - } - O.[[Prototype]] = V; - return true; - */ -}; diff --git a/node_modules/es-abstract/2017/RegExpExec.js b/node_modules/es-abstract/2017/RegExpExec.js deleted file mode 100644 index 15c9186..0000000 --- a/node_modules/es-abstract/2017/RegExpExec.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var regexExec = require('../helpers/callBound')('RegExp.prototype.exec'); - -var Call = require('./Call'); -var Get = require('./Get'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-regexpexec - -module.exports = function RegExpExec(R, S) { - if (Type(R) !== 'Object') { - throw new $TypeError('Assertion failed: `R` must be an Object'); - } - if (Type(S) !== 'String') { - throw new $TypeError('Assertion failed: `S` must be a String'); - } - var exec = Get(R, 'exec'); - if (IsCallable(exec)) { - var result = Call(exec, R, [S]); - if (result === null || Type(result) === 'Object') { - return result; - } - throw new $TypeError('"exec" method must return `null` or an Object'); - } - return regexExec(R, S); -}; diff --git a/node_modules/es-abstract/2017/RequireObjectCoercible.js b/node_modules/es-abstract/2017/RequireObjectCoercible.js deleted file mode 100644 index 9008359..0000000 --- a/node_modules/es-abstract/2017/RequireObjectCoercible.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('../5/CheckObjectCoercible'); diff --git a/node_modules/es-abstract/2017/SameValue.js b/node_modules/es-abstract/2017/SameValue.js deleted file mode 100644 index 47c936d..0000000 --- a/node_modules/es-abstract/2017/SameValue.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $isNaN = require('../helpers/isNaN'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.12 - -module.exports = function SameValue(x, y) { - if (x === y) { // 0 === -0, but they are not identical. - if (x === 0) { return 1 / x === 1 / y; } - return true; - } - return $isNaN(x) && $isNaN(y); -}; diff --git a/node_modules/es-abstract/2017/SameValueNonNumber.js b/node_modules/es-abstract/2017/SameValueNonNumber.js deleted file mode 100644 index 5668752..0000000 --- a/node_modules/es-abstract/2017/SameValueNonNumber.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var SameValue = require('./SameValue'); - -// https://www.ecma-international.org/ecma-262/7.0/#sec-samevaluenonnumber - -module.exports = function SameValueNonNumber(x, y) { - if (typeof x === 'number' || typeof x !== typeof y) { - throw new $TypeError('SameValueNonNumber requires two non-number values of the same type.'); - } - return SameValue(x, y); -}; diff --git a/node_modules/es-abstract/2017/SameValueZero.js b/node_modules/es-abstract/2017/SameValueZero.js deleted file mode 100644 index 0dedcd2..0000000 --- a/node_modules/es-abstract/2017/SameValueZero.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var $isNaN = require('../helpers/isNaN'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-samevaluezero - -module.exports = function SameValueZero(x, y) { - return (x === y) || ($isNaN(x) && $isNaN(y)); -}; diff --git a/node_modules/es-abstract/2017/SecFromTime.js b/node_modules/es-abstract/2017/SecFromTime.js deleted file mode 100644 index 7190011..0000000 --- a/node_modules/es-abstract/2017/SecFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerSecond = timeConstants.msPerSecond; -var SecondsPerMinute = timeConstants.SecondsPerMinute; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function SecFromTime(t) { - return mod($floor(t / msPerSecond), SecondsPerMinute); -}; diff --git a/node_modules/es-abstract/2017/Set.js b/node_modules/es-abstract/2017/Set.js deleted file mode 100644 index 18ebd99..0000000 --- a/node_modules/es-abstract/2017/Set.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-set-o-p-v-throw - -module.exports = function Set(O, P, V, Throw) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - if (Type(Throw) !== 'Boolean') { - throw new $TypeError('Assertion failed: `Throw` must be a Boolean'); - } - if (Throw) { - O[P] = V; // eslint-disable-line no-param-reassign - return true; - } else { - try { - O[P] = V; // eslint-disable-line no-param-reassign - } catch (e) { - return false; - } - } -}; diff --git a/node_modules/es-abstract/2017/SetFunctionName.js b/node_modules/es-abstract/2017/SetFunctionName.js deleted file mode 100644 index f93324a..0000000 --- a/node_modules/es-abstract/2017/SetFunctionName.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var has = require('has'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var getSymbolDescription = require('../helpers/getSymbolDescription'); - -var DefinePropertyOrThrow = require('./DefinePropertyOrThrow'); -var IsExtensible = require('./IsExtensible'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-setfunctionname - -module.exports = function SetFunctionName(F, name) { - if (typeof F !== 'function') { - throw new $TypeError('Assertion failed: `F` must be a function'); - } - if (!IsExtensible(F) || has(F, 'name')) { - throw new $TypeError('Assertion failed: `F` must be extensible, and must not have a `name` own property'); - } - var nameType = Type(name); - if (nameType !== 'Symbol' && nameType !== 'String') { - throw new $TypeError('Assertion failed: `name` must be a Symbol or a String'); - } - if (nameType === 'Symbol') { - var description = getSymbolDescription(name); - // eslint-disable-next-line no-param-reassign - name = typeof description === 'undefined' ? '' : '[' + description + ']'; - } - if (arguments.length > 2) { - var prefix = arguments[2]; - // eslint-disable-next-line no-param-reassign - name = prefix + ' ' + name; - } - return DefinePropertyOrThrow(F, 'name', { - '[[Value]]': name, - '[[Writable]]': false, - '[[Enumerable]]': false, - '[[Configurable]]': true - }); -}; diff --git a/node_modules/es-abstract/2017/SetIntegrityLevel.js b/node_modules/es-abstract/2017/SetIntegrityLevel.js deleted file mode 100644 index 3d5c81d..0000000 --- a/node_modules/es-abstract/2017/SetIntegrityLevel.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); -var $preventExtensions = GetIntrinsic('%Object.preventExtensions%'); -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); - -var forEach = require('../helpers/forEach'); - -var DefinePropertyOrThrow = require('./DefinePropertyOrThrow'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-setintegritylevel - -module.exports = function SetIntegrityLevel(O, level) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (level !== 'sealed' && level !== 'frozen') { - throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); - } - if (!$preventExtensions) { - throw new $SyntaxError('SetIntegrityLevel requires native `Object.preventExtensions` support'); - } - var status = $preventExtensions(O); - if (!status) { - return false; - } - if (!$gOPN) { - throw new $SyntaxError('SetIntegrityLevel requires native `Object.getOwnPropertyNames` support'); - } - var theKeys = $gOPN(O); - if (level === 'sealed') { - forEach(theKeys, function (k) { - DefinePropertyOrThrow(O, k, { configurable: false }); - }); - } else if (level === 'frozen') { - forEach(theKeys, function (k) { - var currentDesc = $gOPD(O, k); - if (typeof currentDesc !== 'undefined') { - var desc; - if (IsAccessorDescriptor(ToPropertyDescriptor(currentDesc))) { - desc = { configurable: false }; - } else { - desc = { configurable: false, writable: false }; - } - DefinePropertyOrThrow(O, k, desc); - } - }); - } - return true; -}; diff --git a/node_modules/es-abstract/2017/SpeciesConstructor.js b/node_modules/es-abstract/2017/SpeciesConstructor.js deleted file mode 100644 index 3cdcd74..0000000 --- a/node_modules/es-abstract/2017/SpeciesConstructor.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $species = GetIntrinsic('%Symbol.species%', true); -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsConstructor = require('./IsConstructor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-speciesconstructor - -module.exports = function SpeciesConstructor(O, defaultConstructor) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - var C = O.constructor; - if (typeof C === 'undefined') { - return defaultConstructor; - } - if (Type(C) !== 'Object') { - throw new $TypeError('O.constructor is not an Object'); - } - var S = $species ? C[$species] : void 0; - if (S == null) { - return defaultConstructor; - } - if (IsConstructor(S)) { - return S; - } - throw new $TypeError('no constructor found'); -}; diff --git a/node_modules/es-abstract/2017/StrictEqualityComparison.js b/node_modules/es-abstract/2017/StrictEqualityComparison.js deleted file mode 100644 index eea5df3..0000000 --- a/node_modules/es-abstract/2017/StrictEqualityComparison.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6 - -module.exports = function StrictEqualityComparison(x, y) { - var xType = Type(x); - var yType = Type(y); - if (xType !== yType) { - return false; - } - if (xType === 'Undefined' || xType === 'Null') { - return true; - } - return x === y; // shortcut for steps 4-7 -}; diff --git a/node_modules/es-abstract/2017/SymbolDescriptiveString.js b/node_modules/es-abstract/2017/SymbolDescriptiveString.js deleted file mode 100644 index 7bd8191..0000000 --- a/node_modules/es-abstract/2017/SymbolDescriptiveString.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $SymbolToString = callBound('Symbol.prototype.toString', true); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-symboldescriptivestring - -module.exports = function SymbolDescriptiveString(sym) { - if (Type(sym) !== 'Symbol') { - throw new $TypeError('Assertion failed: `sym` must be a Symbol'); - } - return $SymbolToString(sym); -}; diff --git a/node_modules/es-abstract/2017/TestIntegrityLevel.js b/node_modules/es-abstract/2017/TestIntegrityLevel.js deleted file mode 100644 index 7a57397..0000000 --- a/node_modules/es-abstract/2017/TestIntegrityLevel.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var every = require('../helpers/every'); - -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-testintegritylevel - -module.exports = function TestIntegrityLevel(O, level) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (level !== 'sealed' && level !== 'frozen') { - throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); - } - var status = IsExtensible(O); - if (status) { - return false; - } - var theKeys = $gOPN(O); - return theKeys.length === 0 || every(theKeys, function (k) { - var currentDesc = $gOPD(O, k); - if (typeof currentDesc !== 'undefined') { - if (currentDesc.configurable) { - return false; - } - if (level === 'frozen' && IsDataDescriptor(ToPropertyDescriptor(currentDesc)) && currentDesc.writable) { - return false; - } - } - return true; - }); -}; diff --git a/node_modules/es-abstract/2017/TimeClip.js b/node_modules/es-abstract/2017/TimeClip.js deleted file mode 100644 index 57aa08c..0000000 --- a/node_modules/es-abstract/2017/TimeClip.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Date = GetIntrinsic('%Date%'); -var $Number = GetIntrinsic('%Number%'); -var $abs = GetIntrinsic('%Math.abs%'); - -var $isFinite = require('../helpers/isFinite'); - -var ToNumber = require('./ToNumber'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.14 - -module.exports = function TimeClip(time) { - if (!$isFinite(time) || $abs(time) > 8.64e15) { - return NaN; - } - return $Number(new $Date(ToNumber(time))); -}; - diff --git a/node_modules/es-abstract/2017/TimeFromYear.js b/node_modules/es-abstract/2017/TimeFromYear.js deleted file mode 100644 index df646c3..0000000 --- a/node_modules/es-abstract/2017/TimeFromYear.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var msPerDay = require('../helpers/timeConstants').msPerDay; - -var DayFromYear = require('./DayFromYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function TimeFromYear(y) { - return msPerDay * DayFromYear(y); -}; diff --git a/node_modules/es-abstract/2017/TimeWithinDay.js b/node_modules/es-abstract/2017/TimeWithinDay.js deleted file mode 100644 index c5b21d3..0000000 --- a/node_modules/es-abstract/2017/TimeWithinDay.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - -module.exports = function TimeWithinDay(t) { - return mod(t, msPerDay); -}; - diff --git a/node_modules/es-abstract/2017/ToBoolean.js b/node_modules/es-abstract/2017/ToBoolean.js deleted file mode 100644 index 65d8737..0000000 --- a/node_modules/es-abstract/2017/ToBoolean.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.2 - -module.exports = function ToBoolean(value) { return !!value; }; diff --git a/node_modules/es-abstract/2017/ToDateString.js b/node_modules/es-abstract/2017/ToDateString.js deleted file mode 100644 index 7a6d4c4..0000000 --- a/node_modules/es-abstract/2017/ToDateString.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $Date = GetIntrinsic('%Date%'); - -var $isNaN = require('../helpers/isNaN'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-todatestring - -module.exports = function ToDateString(tv) { - if (Type(tv) !== 'Number') { - throw new $TypeError('Assertion failed: `tv` must be a Number'); - } - if ($isNaN(tv)) { - return 'Invalid Date'; - } - return $Date(tv); -}; diff --git a/node_modules/es-abstract/2017/ToIndex.js b/node_modules/es-abstract/2017/ToIndex.js deleted file mode 100644 index a55398d..0000000 --- a/node_modules/es-abstract/2017/ToIndex.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $RangeError = GetIntrinsic('%RangeError%'); - -var ToInteger = require('./ToInteger'); -var ToLength = require('./ToLength'); -var SameValueZero = require('./SameValueZero'); - -// https://www.ecma-international.org/ecma-262/8.0/#sec-toindex - -module.exports = function ToIndex(value) { - if (typeof value === 'undefined') { - return 0; - } - var integerIndex = ToInteger(value); - if (integerIndex < 0) { - throw new $RangeError('index must be >= 0'); - } - var index = ToLength(integerIndex); - if (!SameValueZero(integerIndex, index)) { - throw new $RangeError('index must be >= 0 and < 2 ** 53 - 1'); - } - return index; -}; diff --git a/node_modules/es-abstract/2017/ToInt16.js b/node_modules/es-abstract/2017/ToInt16.js deleted file mode 100644 index 5a112c2..0000000 --- a/node_modules/es-abstract/2017/ToInt16.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var ToUint16 = require('./ToUint16'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toint16 - -module.exports = function ToInt16(argument) { - var int16bit = ToUint16(argument); - return int16bit >= 0x8000 ? int16bit - 0x10000 : int16bit; -}; diff --git a/node_modules/es-abstract/2017/ToInt32.js b/node_modules/es-abstract/2017/ToInt32.js deleted file mode 100644 index a8d2680..0000000 --- a/node_modules/es-abstract/2017/ToInt32.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.5 - -module.exports = function ToInt32(x) { - return ToNumber(x) >> 0; -}; diff --git a/node_modules/es-abstract/2017/ToInt8.js b/node_modules/es-abstract/2017/ToInt8.js deleted file mode 100644 index d103123..0000000 --- a/node_modules/es-abstract/2017/ToInt8.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var ToUint8 = require('./ToUint8'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toint8 - -module.exports = function ToInt8(argument) { - var int8bit = ToUint8(argument); - return int8bit >= 0x80 ? int8bit - 0x100 : int8bit; -}; diff --git a/node_modules/es-abstract/2017/ToInteger.js b/node_modules/es-abstract/2017/ToInteger.js deleted file mode 100644 index 16f7db9..0000000 --- a/node_modules/es-abstract/2017/ToInteger.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var ES5ToInteger = require('../5/ToInteger'); - -var ToNumber = require('./ToNumber'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tointeger - -module.exports = function ToInteger(value) { - var number = ToNumber(value); - return ES5ToInteger(number); -}; diff --git a/node_modules/es-abstract/2017/ToLength.js b/node_modules/es-abstract/2017/ToLength.js deleted file mode 100644 index 1bef9be..0000000 --- a/node_modules/es-abstract/2017/ToLength.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger'); - -var ToInteger = require('./ToInteger'); - -module.exports = function ToLength(argument) { - var len = ToInteger(argument); - if (len <= 0) { return 0; } // includes converting -0 to +0 - if (len > MAX_SAFE_INTEGER) { return MAX_SAFE_INTEGER; } - return len; -}; diff --git a/node_modules/es-abstract/2017/ToNumber.js b/node_modules/es-abstract/2017/ToNumber.js deleted file mode 100644 index 7a3cdc8..0000000 --- a/node_modules/es-abstract/2017/ToNumber.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $Number = GetIntrinsic('%Number%'); -var $RegExp = GetIntrinsic('%RegExp%'); -var $parseInteger = GetIntrinsic('%parseInt%'); - -var callBound = require('../helpers/callBound'); -var regexTester = require('../helpers/regexTester'); -var isPrimitive = require('../helpers/isPrimitive'); - -var $strSlice = callBound('String.prototype.slice'); -var isBinary = regexTester(/^0b[01]+$/i); -var isOctal = regexTester(/^0o[0-7]+$/i); -var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i); -var nonWS = ['\u0085', '\u200b', '\ufffe'].join(''); -var nonWSregex = new $RegExp('[' + nonWS + ']', 'g'); -var hasNonWS = regexTester(nonWSregex); - -// whitespace from: https://es5.github.io/#x15.5.4.20 -// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 -var ws = [ - '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', - '\u2029\uFEFF' -].join(''); -var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g'); -var $replace = callBound('String.prototype.replace'); -var $trim = function (value) { - return $replace(value, trimRegex, ''); -}; - -var ToPrimitive = require('./ToPrimitive'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tonumber - -module.exports = function ToNumber(argument) { - var value = isPrimitive(argument) ? argument : ToPrimitive(argument, $Number); - if (typeof value === 'symbol') { - throw new $TypeError('Cannot convert a Symbol value to a number'); - } - if (typeof value === 'string') { - if (isBinary(value)) { - return ToNumber($parseInteger($strSlice(value, 2), 2)); - } else if (isOctal(value)) { - return ToNumber($parseInteger($strSlice(value, 2), 8)); - } else if (hasNonWS(value) || isInvalidHexLiteral(value)) { - return NaN; - } else { - var trimmed = $trim(value); - if (trimmed !== value) { - return ToNumber(trimmed); - } - } - } - return $Number(value); -}; diff --git a/node_modules/es-abstract/2017/ToObject.js b/node_modules/es-abstract/2017/ToObject.js deleted file mode 100644 index 50d5b94..0000000 --- a/node_modules/es-abstract/2017/ToObject.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Object = GetIntrinsic('%Object%'); - -var RequireObjectCoercible = require('./RequireObjectCoercible'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toobject - -module.exports = function ToObject(value) { - RequireObjectCoercible(value); - return $Object(value); -}; diff --git a/node_modules/es-abstract/2017/ToPrimitive.js b/node_modules/es-abstract/2017/ToPrimitive.js deleted file mode 100644 index 81c655d..0000000 --- a/node_modules/es-abstract/2017/ToPrimitive.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var toPrimitive = require('es-to-primitive/es2015'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive - -module.exports = function ToPrimitive(input) { - if (arguments.length > 1) { - return toPrimitive(input, arguments[1]); - } - return toPrimitive(input); -}; diff --git a/node_modules/es-abstract/2017/ToPropertyDescriptor.js b/node_modules/es-abstract/2017/ToPropertyDescriptor.js deleted file mode 100644 index 38e536e..0000000 --- a/node_modules/es-abstract/2017/ToPropertyDescriptor.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -var has = require('has'); - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Type = require('./Type'); -var ToBoolean = require('./ToBoolean'); -var IsCallable = require('./IsCallable'); - -// https://ecma-international.org/ecma-262/5.1/#sec-8.10.5 - -module.exports = function ToPropertyDescriptor(Obj) { - if (Type(Obj) !== 'Object') { - throw new $TypeError('ToPropertyDescriptor requires an object'); - } - - var desc = {}; - if (has(Obj, 'enumerable')) { - desc['[[Enumerable]]'] = ToBoolean(Obj.enumerable); - } - if (has(Obj, 'configurable')) { - desc['[[Configurable]]'] = ToBoolean(Obj.configurable); - } - if (has(Obj, 'value')) { - desc['[[Value]]'] = Obj.value; - } - if (has(Obj, 'writable')) { - desc['[[Writable]]'] = ToBoolean(Obj.writable); - } - if (has(Obj, 'get')) { - var getter = Obj.get; - if (typeof getter !== 'undefined' && !IsCallable(getter)) { - throw new TypeError('getter must be a function'); - } - desc['[[Get]]'] = getter; - } - if (has(Obj, 'set')) { - var setter = Obj.set; - if (typeof setter !== 'undefined' && !IsCallable(setter)) { - throw new $TypeError('setter must be a function'); - } - desc['[[Set]]'] = setter; - } - - if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) { - throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute'); - } - return desc; -}; diff --git a/node_modules/es-abstract/2017/ToPropertyKey.js b/node_modules/es-abstract/2017/ToPropertyKey.js deleted file mode 100644 index 38f40dd..0000000 --- a/node_modules/es-abstract/2017/ToPropertyKey.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $String = GetIntrinsic('%String%'); - -var ToPrimitive = require('./ToPrimitive'); -var ToString = require('./ToString'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-topropertykey - -module.exports = function ToPropertyKey(argument) { - var key = ToPrimitive(argument, $String); - return typeof key === 'symbol' ? key : ToString(key); -}; diff --git a/node_modules/es-abstract/2017/ToString.js b/node_modules/es-abstract/2017/ToString.js deleted file mode 100644 index a345431..0000000 --- a/node_modules/es-abstract/2017/ToString.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $String = GetIntrinsic('%String%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tostring - -module.exports = function ToString(argument) { - if (typeof argument === 'symbol') { - throw new $TypeError('Cannot convert a Symbol value to a string'); - } - return $String(argument); -}; diff --git a/node_modules/es-abstract/2017/ToUint16.js b/node_modules/es-abstract/2017/ToUint16.js deleted file mode 100644 index c8a408b..0000000 --- a/node_modules/es-abstract/2017/ToUint16.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var $sign = require('../helpers/sign'); -var $mod = require('../helpers/mod'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.7 - -module.exports = function ToUint16(value) { - var number = ToNumber(value); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = $sign(number) * $floor($abs(number)); - return $mod(posInt, 0x10000); -}; diff --git a/node_modules/es-abstract/2017/ToUint32.js b/node_modules/es-abstract/2017/ToUint32.js deleted file mode 100644 index 3660f62..0000000 --- a/node_modules/es-abstract/2017/ToUint32.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.6 - -module.exports = function ToUint32(x) { - return ToNumber(x) >>> 0; -}; diff --git a/node_modules/es-abstract/2017/ToUint8.js b/node_modules/es-abstract/2017/ToUint8.js deleted file mode 100644 index bf84753..0000000 --- a/node_modules/es-abstract/2017/ToUint8.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var $sign = require('../helpers/sign'); -var $mod = require('../helpers/mod'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -module.exports = function ToUint8(argument) { - var number = ToNumber(argument); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = $sign(number) * $floor($abs(number)); - return $mod(posInt, 0x100); -}; diff --git a/node_modules/es-abstract/2017/ToUint8Clamp.js b/node_modules/es-abstract/2017/ToUint8Clamp.js deleted file mode 100644 index c7f9f56..0000000 --- a/node_modules/es-abstract/2017/ToUint8Clamp.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); - -var $floor = $Math.floor; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-touint8clamp - -module.exports = function ToUint8Clamp(argument) { - var number = ToNumber(argument); - if ($isNaN(number) || number <= 0) { return 0; } - if (number >= 0xFF) { return 0xFF; } - var f = $floor(argument); - if (f + 0.5 < number) { return f + 1; } - if (number < f + 0.5) { return f; } - if (f % 2 !== 0) { return f + 1; } - return f; -}; diff --git a/node_modules/es-abstract/2017/Type.js b/node_modules/es-abstract/2017/Type.js deleted file mode 100644 index 6c99376..0000000 --- a/node_modules/es-abstract/2017/Type.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var ES5Type = require('../5/Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tostring - -module.exports = function Type(x) { - if (typeof x === 'symbol') { - return 'Symbol'; - } - return ES5Type(x); -}; diff --git a/node_modules/es-abstract/2017/ValidateAndApplyPropertyDescriptor.js b/node_modules/es-abstract/2017/ValidateAndApplyPropertyDescriptor.js deleted file mode 100644 index d4b9007..0000000 --- a/node_modules/es-abstract/2017/ValidateAndApplyPropertyDescriptor.js +++ /dev/null @@ -1,170 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); -var isSamePropertyDescriptor = require('../helpers/isSamePropertyDescriptor'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsGenericDescriptor = require('./IsGenericDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-validateandapplypropertydescriptor -// https://www.ecma-international.org/ecma-262/8.0/#sec-validateandapplypropertydescriptor - -// eslint-disable-next-line max-lines-per-function, max-statements, max-params -module.exports = function ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current) { - // this uses the ES2017+ logic, since it fixes a number of bugs in the ES2015 logic. - var oType = Type(O); - if (oType !== 'Undefined' && oType !== 'Object') { - throw new $TypeError('Assertion failed: O must be undefined or an Object'); - } - if (Type(extensible) !== 'Boolean') { - throw new $TypeError('Assertion failed: extensible must be a Boolean'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (Type(current) !== 'Undefined' && !isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, current)) { - throw new $TypeError('Assertion failed: current must be a Property Descriptor, or undefined'); - } - if (oType !== 'Undefined' && !IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: if O is not undefined, P must be a Property Key'); - } - if (Type(current) === 'Undefined') { - if (!extensible) { - return false; - } - if (IsGenericDescriptor(Desc) || IsDataDescriptor(Desc)) { - if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': Desc['[[Configurable]]'], - '[[Enumerable]]': Desc['[[Enumerable]]'], - '[[Value]]': Desc['[[Value]]'], - '[[Writable]]': Desc['[[Writable]]'] - } - ); - } - } else { - if (!IsAccessorDescriptor(Desc)) { - throw new $TypeError('Assertion failed: Desc is not an accessor descriptor'); - } - if (oType !== 'Undefined') { - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); - } - } - return true; - } - if (IsGenericDescriptor(Desc) && !('[[Configurable]]' in Desc) && !('[[Enumerable]]' in Desc)) { - return true; - } - if (isSamePropertyDescriptor({ SameValue: SameValue }, Desc, current)) { - return true; // removed by ES2017, but should still be correct - } - // "if every field in Desc is absent, return true" can't really match the assertion that it's a Property Descriptor - if (!current['[[Configurable]]']) { - if (Desc['[[Configurable]]']) { - return false; - } - if ('[[Enumerable]]' in Desc && !Desc['[[Enumerable]]'] === !!current['[[Enumerable]]']) { - return false; - } - } - if (IsGenericDescriptor(Desc)) { - // no further validation is required. - } else if (IsDataDescriptor(current) !== IsDataDescriptor(Desc)) { - if (!current['[[Configurable]]']) { - return false; - } - if (IsDataDescriptor(current)) { - if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': current['[[Configurable]]'], - '[[Enumerable]]': current['[[Enumerable]]'], - '[[Get]]': undefined - } - ); - } - } else if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': current['[[Configurable]]'], - '[[Enumerable]]': current['[[Enumerable]]'], - '[[Value]]': undefined - } - ); - } - } else if (IsDataDescriptor(current) && IsDataDescriptor(Desc)) { - if (!current['[[Configurable]]'] && !current['[[Writable]]']) { - if ('[[Writable]]' in Desc && Desc['[[Writable]]']) { - return false; - } - if ('[[Value]]' in Desc && !SameValue(Desc['[[Value]]'], current['[[Value]]'])) { - return false; - } - return true; - } - } else if (IsAccessorDescriptor(current) && IsAccessorDescriptor(Desc)) { - if (!current['[[Configurable]]']) { - if ('[[Set]]' in Desc && !SameValue(Desc['[[Set]]'], current['[[Set]]'])) { - return false; - } - if ('[[Get]]' in Desc && !SameValue(Desc['[[Get]]'], current['[[Get]]'])) { - return false; - } - return true; - } - } else { - throw new $TypeError('Assertion failed: current and Desc are not both data, both accessors, or one accessor and one data.'); - } - if (oType !== 'Undefined') { - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); - } - return true; -}; diff --git a/node_modules/es-abstract/2017/WeekDay.js b/node_modules/es-abstract/2017/WeekDay.js deleted file mode 100644 index 2973e02..0000000 --- a/node_modules/es-abstract/2017/WeekDay.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -var Day = require('./Day'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.6 - -module.exports = function WeekDay(t) { - return mod(Day(t) + 4, 7); -}; diff --git a/node_modules/es-abstract/2017/YearFromTime.js b/node_modules/es-abstract/2017/YearFromTime.js deleted file mode 100644 index ff5339f..0000000 --- a/node_modules/es-abstract/2017/YearFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Date = GetIntrinsic('%Date%'); - -var callBound = require('../helpers/callBound'); - -var $getUTCFullYear = callBound('Date.prototype.getUTCFullYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function YearFromTime(t) { - // largest y such that this.TimeFromYear(y) <= t - return $getUTCFullYear(new $Date(t)); -}; diff --git a/node_modules/es-abstract/2017/modulo.js b/node_modules/es-abstract/2017/modulo.js deleted file mode 100644 index bc04c06..0000000 --- a/node_modules/es-abstract/2017/modulo.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -// https://ecma-international.org/ecma-262/5.1/#sec-5.2 - -module.exports = function modulo(x, y) { - return mod(x, y); -}; diff --git a/node_modules/es-abstract/2017/msFromTime.js b/node_modules/es-abstract/2017/msFromTime.js deleted file mode 100644 index c31eda0..0000000 --- a/node_modules/es-abstract/2017/msFromTime.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); -var msPerSecond = require('../helpers/timeConstants').msPerSecond; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function msFromTime(t) { - return mod(t, msPerSecond); -}; diff --git a/node_modules/es-abstract/2017/thisBooleanValue.js b/node_modules/es-abstract/2017/thisBooleanValue.js deleted file mode 100644 index 3ffac9c..0000000 --- a/node_modules/es-abstract/2017/thisBooleanValue.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var $BooleanValueOf = require('../helpers/callBound')('Boolean.prototype.valueOf'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-boolean-prototype-object - -module.exports = function thisBooleanValue(value) { - if (Type(value) === 'Boolean') { - return value; - } - - return $BooleanValueOf(value); -}; diff --git a/node_modules/es-abstract/2017/thisNumberValue.js b/node_modules/es-abstract/2017/thisNumberValue.js deleted file mode 100644 index 0345e52..0000000 --- a/node_modules/es-abstract/2017/thisNumberValue.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var Type = require('./Type'); - -var $NumberValueOf = callBound('Number.prototype.valueOf'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-number-prototype-object - -module.exports = function thisNumberValue(value) { - if (Type(value) === 'Number') { - return value; - } - - return $NumberValueOf(value); -}; - diff --git a/node_modules/es-abstract/2017/thisStringValue.js b/node_modules/es-abstract/2017/thisStringValue.js deleted file mode 100644 index 3b99b6e..0000000 --- a/node_modules/es-abstract/2017/thisStringValue.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var $StringValueOf = require('../helpers/callBound')('String.prototype.valueOf'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-string-prototype-object - -module.exports = function thisStringValue(value) { - if (Type(value) === 'String') { - return value; - } - - return $StringValueOf(value); -}; diff --git a/node_modules/es-abstract/2017/thisTimeValue.js b/node_modules/es-abstract/2017/thisTimeValue.js deleted file mode 100644 index d7cda28..0000000 --- a/node_modules/es-abstract/2017/thisTimeValue.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var $DateValueOf = require('../helpers/callBound')('Date.prototype.valueOf'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-date-prototype-object - -module.exports = function thisTimeValue(value) { - return $DateValueOf(value); -}; diff --git a/node_modules/es-abstract/2018/AbstractEqualityComparison.js b/node_modules/es-abstract/2018/AbstractEqualityComparison.js deleted file mode 100644 index 40b3909..0000000 --- a/node_modules/es-abstract/2018/AbstractEqualityComparison.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); -var ToPrimitive = require('./ToPrimitive'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison - -module.exports = function AbstractEqualityComparison(x, y) { - var xType = Type(x); - var yType = Type(y); - if (xType === yType) { - return x === y; // ES6+ specified this shortcut anyways. - } - if (x == null && y == null) { - return true; - } - if (xType === 'Number' && yType === 'String') { - return AbstractEqualityComparison(x, ToNumber(y)); - } - if (xType === 'String' && yType === 'Number') { - return AbstractEqualityComparison(ToNumber(x), y); - } - if (xType === 'Boolean') { - return AbstractEqualityComparison(ToNumber(x), y); - } - if (yType === 'Boolean') { - return AbstractEqualityComparison(x, ToNumber(y)); - } - if ((xType === 'String' || xType === 'Number' || xType === 'Symbol') && yType === 'Object') { - return AbstractEqualityComparison(x, ToPrimitive(y)); - } - if (xType === 'Object' && (yType === 'String' || yType === 'Number' || yType === 'Symbol')) { - return AbstractEqualityComparison(ToPrimitive(x), y); - } - return false; -}; diff --git a/node_modules/es-abstract/2018/AbstractRelationalComparison.js b/node_modules/es-abstract/2018/AbstractRelationalComparison.js deleted file mode 100644 index bc7ca83..0000000 --- a/node_modules/es-abstract/2018/AbstractRelationalComparison.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Number = GetIntrinsic('%Number%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var isPrefixOf = require('../helpers/isPrefixOf'); - -var ToNumber = require('./ToNumber'); -var ToPrimitive = require('./ToPrimitive'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5 - -// eslint-disable-next-line max-statements -module.exports = function AbstractRelationalComparison(x, y, LeftFirst) { - if (Type(LeftFirst) !== 'Boolean') { - throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean'); - } - var px; - var py; - if (LeftFirst) { - px = ToPrimitive(x, $Number); - py = ToPrimitive(y, $Number); - } else { - py = ToPrimitive(y, $Number); - px = ToPrimitive(x, $Number); - } - var bothStrings = Type(px) === 'String' && Type(py) === 'String'; - if (!bothStrings) { - var nx = ToNumber(px); - var ny = ToNumber(py); - if ($isNaN(nx) || $isNaN(ny)) { - return undefined; - } - if ($isFinite(nx) && $isFinite(ny) && nx === ny) { - return false; - } - if (nx === 0 && ny === 0) { - return false; - } - if (nx === Infinity) { - return false; - } - if (ny === Infinity) { - return true; - } - if (ny === -Infinity) { - return false; - } - if (nx === -Infinity) { - return true; - } - return nx < ny; // by now, these are both nonzero, finite, and not equal - } - if (isPrefixOf(py, px)) { - return false; - } - if (isPrefixOf(px, py)) { - return true; - } - return px < py; // both strings, neither a prefix of the other. shortcut for steps c-f -}; diff --git a/node_modules/es-abstract/2018/AdvanceStringIndex.js b/node_modules/es-abstract/2018/AdvanceStringIndex.js deleted file mode 100644 index 666f578..0000000 --- a/node_modules/es-abstract/2018/AdvanceStringIndex.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var IsInteger = require('./IsInteger'); -var Type = require('./Type'); - -var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $charCodeAt = require('../helpers/callBound')('String.prototype.charCodeAt'); - -// https://ecma-international.org/ecma-262/6.0/#sec-advancestringindex - -module.exports = function AdvanceStringIndex(S, index, unicode) { - if (Type(S) !== 'String') { - throw new $TypeError('Assertion failed: `S` must be a String'); - } - if (!IsInteger(index) || index < 0 || index > MAX_SAFE_INTEGER) { - throw new $TypeError('Assertion failed: `length` must be an integer >= 0 and <= 2**53'); - } - if (Type(unicode) !== 'Boolean') { - throw new $TypeError('Assertion failed: `unicode` must be a Boolean'); - } - if (!unicode) { - return index + 1; - } - var length = S.length; - if ((index + 1) >= length) { - return index + 1; - } - - var first = $charCodeAt(S, index); - if (first < 0xD800 || first > 0xDBFF) { - return index + 1; - } - - var second = $charCodeAt(S, index + 1); - if (second < 0xDC00 || second > 0xDFFF) { - return index + 1; - } - - return index + 2; -}; diff --git a/node_modules/es-abstract/2018/ArrayCreate.js b/node_modules/es-abstract/2018/ArrayCreate.js deleted file mode 100644 index fc9a7cf..0000000 --- a/node_modules/es-abstract/2018/ArrayCreate.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $ArrayPrototype = GetIntrinsic('%Array.prototype%'); -var $RangeError = GetIntrinsic('%RangeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsInteger = require('./IsInteger'); - -var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1; - -var $setProto = GetIntrinsic('%Object.setPrototypeOf%', true) || ( - // eslint-disable-next-line no-proto, no-negated-condition - [].__proto__ !== $ArrayPrototype - ? null - : function (O, proto) { - O.__proto__ = proto; // eslint-disable-line no-proto, no-param-reassign - return O; - } -); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-arraycreate - -module.exports = function ArrayCreate(length) { - if (!IsInteger(length) || length < 0) { - throw new $TypeError('Assertion failed: `length` must be an integer Number >= 0'); - } - if (length > MAX_ARRAY_LENGTH) { - throw new $RangeError('length is greater than (2**32 - 1)'); - } - var proto = arguments.length > 1 ? arguments[1] : $ArrayPrototype; - var A = []; // steps 5 - 7, and 9 - if (proto !== $ArrayPrototype) { // step 8 - if (!$setProto) { - throw new $SyntaxError('ArrayCreate: a `proto` argument that is not `Array.prototype` is not supported in an environment that does not support setting the [[Prototype]]'); - } - $setProto(A, proto); - } - if (length !== 0) { // bypasses the need for step 2 - A.length = length; - } - /* step 10, the above as a shortcut for the below - OrdinaryDefineOwnProperty(A, 'length', { - '[[Configurable]]': false, - '[[Enumerable]]': false, - '[[Value]]': length, - '[[Writable]]': true - }); - */ - return A; -}; diff --git a/node_modules/es-abstract/2018/ArraySetLength.js b/node_modules/es-abstract/2018/ArraySetLength.js deleted file mode 100644 index c9134c6..0000000 --- a/node_modules/es-abstract/2018/ArraySetLength.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $RangeError = GetIntrinsic('%RangeError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var assign = require('object.assign'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var IsArray = require('./IsArray'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var OrdinaryDefineOwnProperty = require('./OrdinaryDefineOwnProperty'); -var OrdinaryGetOwnProperty = require('./OrdinaryGetOwnProperty'); -var ToNumber = require('./ToNumber'); -var ToString = require('./ToString'); -var ToUint32 = require('./ToUint32'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-arraysetlength - -// eslint-disable-next-line max-statements, max-lines-per-function -module.exports = function ArraySetLength(A, Desc) { - if (!IsArray(A)) { - throw new $TypeError('Assertion failed: A must be an Array'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (!('[[Value]]' in Desc)) { - return OrdinaryDefineOwnProperty(A, 'length', Desc); - } - var newLenDesc = assign({}, Desc); - var newLen = ToUint32(Desc['[[Value]]']); - var numberLen = ToNumber(Desc['[[Value]]']); - if (newLen !== numberLen) { - throw new $RangeError('Invalid array length'); - } - newLenDesc['[[Value]]'] = newLen; - var oldLenDesc = OrdinaryGetOwnProperty(A, 'length'); - if (!IsDataDescriptor(oldLenDesc)) { - throw new $TypeError('Assertion failed: an array had a non-data descriptor on `length`'); - } - var oldLen = oldLenDesc['[[Value]]']; - if (newLen >= oldLen) { - return OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - } - if (!oldLenDesc['[[Writable]]']) { - return false; - } - var newWritable; - if (!('[[Writable]]' in newLenDesc) || newLenDesc['[[Writable]]']) { - newWritable = true; - } else { - newWritable = false; - newLenDesc['[[Writable]]'] = true; - } - var succeeded = OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - if (!succeeded) { - return false; - } - while (newLen < oldLen) { - oldLen -= 1; - // eslint-disable-next-line no-param-reassign - var deleteSucceeded = delete A[ToString(oldLen)]; - if (!deleteSucceeded) { - newLenDesc['[[Value]]'] = oldLen + 1; - if (!newWritable) { - newLenDesc['[[Writable]]'] = false; - OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - return false; - } - } - } - if (!newWritable) { - return OrdinaryDefineOwnProperty(A, 'length', { '[[Writable]]': false }); - } - return true; -}; diff --git a/node_modules/es-abstract/2018/ArraySpeciesCreate.js b/node_modules/es-abstract/2018/ArraySpeciesCreate.js deleted file mode 100644 index 98b9b56..0000000 --- a/node_modules/es-abstract/2018/ArraySpeciesCreate.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Array = GetIntrinsic('%Array%'); -var $species = GetIntrinsic('%Symbol.species%', true); -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var IsConstructor = require('./IsConstructor'); -var IsInteger = require('./IsInteger'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-arrayspeciescreate - -module.exports = function ArraySpeciesCreate(originalArray, length) { - if (!IsInteger(length) || length < 0) { - throw new $TypeError('Assertion failed: length must be an integer >= 0'); - } - var len = length === 0 ? 0 : length; - var C; - var isArray = IsArray(originalArray); - if (isArray) { - C = Get(originalArray, 'constructor'); - // TODO: figure out how to make a cross-realm normal Array, a same-realm Array - // if (IsConstructor(C)) { - // if C is another realm's Array, C = undefined - // Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Array))) === null ? - // } - if ($species && Type(C) === 'Object') { - C = Get(C, $species); - if (C === null) { - C = void 0; - } - } - } - if (typeof C === 'undefined') { - return $Array(len); - } - if (!IsConstructor(C)) { - throw new $TypeError('C must be a constructor'); - } - return new C(len); // Construct(C, len); -}; - diff --git a/node_modules/es-abstract/2018/Call.js b/node_modules/es-abstract/2018/Call.js deleted file mode 100644 index f31960d..0000000 --- a/node_modules/es-abstract/2018/Call.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var inspect = require('object-inspect'); - -var IsCallable = require('./IsCallable'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-call - -module.exports = function Call(F, V) { - var args = arguments.length > 2 ? arguments[2] : []; - if (!IsCallable(F)) { - throw new $TypeError(inspect(F) + ' is not a function'); - } - return F.apply(V, args); -}; diff --git a/node_modules/es-abstract/2018/CanonicalNumericIndexString.js b/node_modules/es-abstract/2018/CanonicalNumericIndexString.js deleted file mode 100644 index 625f853..0000000 --- a/node_modules/es-abstract/2018/CanonicalNumericIndexString.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var SameValue = require('./SameValue'); -var ToNumber = require('./ToNumber'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-canonicalnumericindexstring - -module.exports = function CanonicalNumericIndexString(argument) { - if (Type(argument) !== 'String') { - throw new $TypeError('Assertion failed: `argument` must be a String'); - } - if (argument === '-0') { return -0; } - var n = ToNumber(argument); - if (SameValue(ToString(n), argument)) { return n; } - return void 0; -}; diff --git a/node_modules/es-abstract/2018/CompletePropertyDescriptor.js b/node_modules/es-abstract/2018/CompletePropertyDescriptor.js deleted file mode 100644 index 548bf41..0000000 --- a/node_modules/es-abstract/2018/CompletePropertyDescriptor.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsGenericDescriptor = require('./IsGenericDescriptor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-completepropertydescriptor - -module.exports = function CompletePropertyDescriptor(Desc) { - /* eslint no-param-reassign: 0 */ - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (IsGenericDescriptor(Desc) || IsDataDescriptor(Desc)) { - if (!has(Desc, '[[Value]]')) { - Desc['[[Value]]'] = void 0; - } - if (!has(Desc, '[[Writable]]')) { - Desc['[[Writable]]'] = false; - } - } else { - if (!has(Desc, '[[Get]]')) { - Desc['[[Get]]'] = void 0; - } - if (!has(Desc, '[[Set]]')) { - Desc['[[Set]]'] = void 0; - } - } - if (!has(Desc, '[[Enumerable]]')) { - Desc['[[Enumerable]]'] = false; - } - if (!has(Desc, '[[Configurable]]')) { - Desc['[[Configurable]]'] = false; - } - return Desc; -}; diff --git a/node_modules/es-abstract/2018/CopyDataProperties.js b/node_modules/es-abstract/2018/CopyDataProperties.js deleted file mode 100644 index b75ba42..0000000 --- a/node_modules/es-abstract/2018/CopyDataProperties.js +++ /dev/null @@ -1,60 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); -var forEach = require('../helpers/forEach'); -var OwnPropertyKeys = require('../helpers/OwnPropertyKeys'); - -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); - -var IsArray = require('./IsArray'); -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/9.0/#sec-copydataproperties - -module.exports = function CopyDataProperties(target, source, excludedItems) { - if (Type(target) !== 'Object') { - throw new TypeError('Assertion failed: "target" must be an Object'); - } - - if (!IsArray(excludedItems)) { - throw new TypeError('Assertion failed: "excludedItems" must be a List of Property Keys'); - } - for (var i = 0; i < excludedItems.length; i += 1) { - if (!IsPropertyKey(excludedItems[i])) { - throw new TypeError('Assertion failed: "excludedItems" must be a List of Property Keys'); - } - } - - if (typeof source === 'undefined' || source === null) { - return target; - } - - var ES = this; - - var fromObj = ES.ToObject(source); - - var sourceKeys = OwnPropertyKeys(fromObj); - forEach(sourceKeys, function (nextKey) { - var excluded = false; - - forEach(excludedItems, function (e) { - if (ES.SameValue(e, nextKey) === true) { - excluded = true; - } - }); - - var enumerable = $isEnumerable(fromObj, nextKey) || ( - // this is to handle string keys being non-enumerable in older engines - typeof source === 'string' - && nextKey >= 0 - && ES.IsInteger(ES.ToNumber(nextKey)) - ); - if (excluded === false && enumerable) { - var propValue = ES.Get(fromObj, nextKey); - ES.CreateDataProperty(target, nextKey, propValue); - } - }); - - return target; -}; diff --git a/node_modules/es-abstract/2018/CreateDataProperty.js b/node_modules/es-abstract/2018/CreateDataProperty.js deleted file mode 100644 index 32a86ef..0000000 --- a/node_modules/es-abstract/2018/CreateDataProperty.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var OrdinaryGetOwnProperty = require('./OrdinaryGetOwnProperty'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createdataproperty - -module.exports = function CreateDataProperty(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - var oldDesc = OrdinaryGetOwnProperty(O, P); - var extensible = !oldDesc || IsExtensible(O); - var immutable = oldDesc && (!oldDesc['[[Writable]]'] || !oldDesc['[[Configurable]]']); - if (immutable || !extensible) { - return false; - } - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': true, - '[[Enumerable]]': true, - '[[Value]]': V, - '[[Writable]]': true - } - ); -}; diff --git a/node_modules/es-abstract/2018/CreateDataPropertyOrThrow.js b/node_modules/es-abstract/2018/CreateDataPropertyOrThrow.js deleted file mode 100644 index 9feaec8..0000000 --- a/node_modules/es-abstract/2018/CreateDataPropertyOrThrow.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var CreateDataProperty = require('./CreateDataProperty'); -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// // https://ecma-international.org/ecma-262/6.0/#sec-createdatapropertyorthrow - -module.exports = function CreateDataPropertyOrThrow(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - var success = CreateDataProperty(O, P, V); - if (!success) { - throw new $TypeError('unable to create data property'); - } - return success; -}; diff --git a/node_modules/es-abstract/2018/CreateHTML.js b/node_modules/es-abstract/2018/CreateHTML.js deleted file mode 100644 index 536c92d..0000000 --- a/node_modules/es-abstract/2018/CreateHTML.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $replace = callBound('String.prototype.replace'); - -var RequireObjectCoercible = require('./RequireObjectCoercible'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createhtml - -module.exports = function CreateHTML(string, tag, attribute, value) { - if (Type(tag) !== 'String' || Type(attribute) !== 'String') { - throw new $TypeError('Assertion failed: `tag` and `attribute` must be strings'); - } - var str = RequireObjectCoercible(string); - var S = ToString(str); - var p1 = '<' + tag; - if (attribute !== '') { - var V = ToString(value); - var escapedV = $replace(V, /\x22/g, '"'); - p1 += '\x20' + attribute + '\x3D\x22' + escapedV + '\x22'; - } - return p1 + '>' + S + ''; -}; diff --git a/node_modules/es-abstract/2018/CreateIterResultObject.js b/node_modules/es-abstract/2018/CreateIterResultObject.js deleted file mode 100644 index aef1d22..0000000 --- a/node_modules/es-abstract/2018/CreateIterResultObject.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-createiterresultobject - -module.exports = function CreateIterResultObject(value, done) { - if (Type(done) !== 'Boolean') { - throw new $TypeError('Assertion failed: Type(done) is not Boolean'); - } - return { - value: value, - done: done - }; -}; diff --git a/node_modules/es-abstract/2018/CreateListFromArrayLike.js b/node_modules/es-abstract/2018/CreateListFromArrayLike.js deleted file mode 100644 index d6b44b5..0000000 --- a/node_modules/es-abstract/2018/CreateListFromArrayLike.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var callBound = require('../helpers/callBound'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $indexOf = callBound('Array.prototype.indexOf', true) || callBound('String.prototype.indexOf'); -var $push = callBound('Array.prototype.push'); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var ToLength = require('./ToLength'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-createlistfromarraylike -module.exports = function CreateListFromArrayLike(obj) { - var elementTypes = arguments.length > 1 - ? arguments[1] - : ['Undefined', 'Null', 'Boolean', 'String', 'Symbol', 'Number', 'Object']; - - if (Type(obj) !== 'Object') { - throw new $TypeError('Assertion failed: `obj` must be an Object'); - } - if (!IsArray(elementTypes)) { - throw new $TypeError('Assertion failed: `elementTypes`, if provided, must be an array'); - } - var len = ToLength(Get(obj, 'length')); - var list = []; - var index = 0; - while (index < len) { - var indexName = ToString(index); - var next = Get(obj, indexName); - var nextType = Type(next); - if ($indexOf(elementTypes, nextType) < 0) { - throw new $TypeError('item type ' + nextType + ' is not a valid elementType'); - } - $push(list, next); - index += 1; - } - return list; -}; diff --git a/node_modules/es-abstract/2018/CreateMethodProperty.js b/node_modules/es-abstract/2018/CreateMethodProperty.js deleted file mode 100644 index 5b599ae..0000000 --- a/node_modules/es-abstract/2018/CreateMethodProperty.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createmethodproperty - -module.exports = function CreateMethodProperty(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - var newDesc = { - '[[Configurable]]': true, - '[[Enumerable]]': false, - '[[Value]]': V, - '[[Writable]]': true - }; - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - newDesc - ); -}; diff --git a/node_modules/es-abstract/2018/DateFromTime.js b/node_modules/es-abstract/2018/DateFromTime.js deleted file mode 100644 index 962dba1..0000000 --- a/node_modules/es-abstract/2018/DateFromTime.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $EvalError = GetIntrinsic('%EvalError%'); - -var DayWithinYear = require('./DayWithinYear'); -var InLeapYear = require('./InLeapYear'); -var MonthFromTime = require('./MonthFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.5 - -module.exports = function DateFromTime(t) { - var m = MonthFromTime(t); - var d = DayWithinYear(t); - if (m === 0) { - return d + 1; - } - if (m === 1) { - return d - 30; - } - var leap = InLeapYear(t); - if (m === 2) { - return d - 58 - leap; - } - if (m === 3) { - return d - 89 - leap; - } - if (m === 4) { - return d - 119 - leap; - } - if (m === 5) { - return d - 150 - leap; - } - if (m === 6) { - return d - 180 - leap; - } - if (m === 7) { - return d - 211 - leap; - } - if (m === 8) { - return d - 242 - leap; - } - if (m === 9) { - return d - 272 - leap; - } - if (m === 10) { - return d - 303 - leap; - } - if (m === 11) { - return d - 333 - leap; - } - throw new $EvalError('Assertion failed: MonthFromTime returned an impossible value: ' + m); -}; diff --git a/node_modules/es-abstract/2018/DateString.js b/node_modules/es-abstract/2018/DateString.js deleted file mode 100644 index fc30329..0000000 --- a/node_modules/es-abstract/2018/DateString.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; - -var $isNaN = require('../helpers/isNaN'); -var padTimeComponent = require('../helpers/padTimeComponent'); - -var Type = require('./Type'); -var WeekDay = require('./WeekDay'); -var MonthFromTime = require('./MonthFromTime'); -var YearFromTime = require('./YearFromTime'); -var DateFromTime = require('./DateFromTime'); - -// https://www.ecma-international.org/ecma-262/9.0/#sec-datestring - -module.exports = function DateString(tv) { - if (Type(tv) !== 'Number' || $isNaN(tv)) { - throw new $TypeError('Assertion failed: `tv` must be a non-NaN Number'); - } - var weekday = weekdays[WeekDay(tv)]; - var month = months[MonthFromTime(tv)]; - var day = padTimeComponent(DateFromTime(tv)); - var year = padTimeComponent(YearFromTime(tv), 4); - return weekday + '\x20' + month + '\x20' + day + '\x20' + year; -}; diff --git a/node_modules/es-abstract/2018/Day.js b/node_modules/es-abstract/2018/Day.js deleted file mode 100644 index 00df813..0000000 --- a/node_modules/es-abstract/2018/Day.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - -module.exports = function Day(t) { - return $floor(t / msPerDay); -}; diff --git a/node_modules/es-abstract/2018/DayFromYear.js b/node_modules/es-abstract/2018/DayFromYear.js deleted file mode 100644 index 08dd5af..0000000 --- a/node_modules/es-abstract/2018/DayFromYear.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function DayFromYear(y) { - return (365 * (y - 1970)) + $floor((y - 1969) / 4) - $floor((y - 1901) / 100) + $floor((y - 1601) / 400); -}; - diff --git a/node_modules/es-abstract/2018/DayWithinYear.js b/node_modules/es-abstract/2018/DayWithinYear.js deleted file mode 100644 index cfc4002..0000000 --- a/node_modules/es-abstract/2018/DayWithinYear.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var Day = require('./Day'); -var DayFromYear = require('./DayFromYear'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - -module.exports = function DayWithinYear(t) { - return Day(t) - DayFromYear(YearFromTime(t)); -}; diff --git a/node_modules/es-abstract/2018/DaysInYear.js b/node_modules/es-abstract/2018/DaysInYear.js deleted file mode 100644 index db32251..0000000 --- a/node_modules/es-abstract/2018/DaysInYear.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function DaysInYear(y) { - if (mod(y, 4) !== 0) { - return 365; - } - if (mod(y, 100) !== 0) { - return 366; - } - if (mod(y, 400) !== 0) { - return 365; - } - return 366; -}; diff --git a/node_modules/es-abstract/2018/DefinePropertyOrThrow.js b/node_modules/es-abstract/2018/DefinePropertyOrThrow.js deleted file mode 100644 index 7977f6e..0000000 --- a/node_modules/es-abstract/2018/DefinePropertyOrThrow.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-definepropertyorthrow - -module.exports = function DefinePropertyOrThrow(O, P, desc) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - var Desc = isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, desc) ? desc : ToPropertyDescriptor(desc); - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc is not a valid Property Descriptor'); - } - - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); -}; diff --git a/node_modules/es-abstract/2018/DeletePropertyOrThrow.js b/node_modules/es-abstract/2018/DeletePropertyOrThrow.js deleted file mode 100644 index b476817..0000000 --- a/node_modules/es-abstract/2018/DeletePropertyOrThrow.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-deletepropertyorthrow - -module.exports = function DeletePropertyOrThrow(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // eslint-disable-next-line no-param-reassign - var success = delete O[P]; - if (!success) { - throw new $TypeError('Attempt to delete property failed.'); - } - return success; -}; diff --git a/node_modules/es-abstract/2018/EnumerableOwnPropertyNames.js b/node_modules/es-abstract/2018/EnumerableOwnPropertyNames.js deleted file mode 100644 index e2ed722..0000000 --- a/node_modules/es-abstract/2018/EnumerableOwnPropertyNames.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var objectKeys = require('object-keys'); - -var callBound = require('../helpers/callBound'); - -var callBind = require('../helpers/callBind'); - -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); -var $pushApply = callBind.apply(GetIntrinsic('%Array.prototype.push%')); - -var forEach = require('../helpers/forEach'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/8.0/#sec-enumerableownproperties - -module.exports = function EnumerableOwnProperties(O, kind) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - var keys = objectKeys(O); - if (kind === 'key') { - return keys; - } - if (kind === 'value' || kind === 'key+value') { - var results = []; - forEach(keys, function (key) { - if ($isEnumerable(O, key)) { - $pushApply(results, [ - kind === 'value' ? O[key] : [key, O[key]] - ]); - } - }); - return results; - } - throw new $TypeError('Assertion failed: "kind" is not "key", "value", or "key+value": ' + kind); -}; diff --git a/node_modules/es-abstract/2018/FromPropertyDescriptor.js b/node_modules/es-abstract/2018/FromPropertyDescriptor.js deleted file mode 100644 index 5ec200e..0000000 --- a/node_modules/es-abstract/2018/FromPropertyDescriptor.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-frompropertydescriptor - -module.exports = function FromPropertyDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return Desc; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - var obj = {}; - if ('[[Value]]' in Desc) { - obj.value = Desc['[[Value]]']; - } - if ('[[Writable]]' in Desc) { - obj.writable = Desc['[[Writable]]']; - } - if ('[[Get]]' in Desc) { - obj.get = Desc['[[Get]]']; - } - if ('[[Set]]' in Desc) { - obj.set = Desc['[[Set]]']; - } - if ('[[Enumerable]]' in Desc) { - obj.enumerable = Desc['[[Enumerable]]']; - } - if ('[[Configurable]]' in Desc) { - obj.configurable = Desc['[[Configurable]]']; - } - return obj; -}; diff --git a/node_modules/es-abstract/2018/Get.js b/node_modules/es-abstract/2018/Get.js deleted file mode 100644 index 5b9ad78..0000000 --- a/node_modules/es-abstract/2018/Get.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var inspect = require('object-inspect'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -/** - * 7.3.1 Get (O, P) - https://ecma-international.org/ecma-262/6.0/#sec-get-o-p - * 1. Assert: Type(O) is Object. - * 2. Assert: IsPropertyKey(P) is true. - * 3. Return O.[[Get]](P, O). - */ - -module.exports = function Get(O, P) { - // 7.3.1.1 - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - // 7.3.1.2 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true, got ' + inspect(P)); - } - // 7.3.1.3 - return O[P]; -}; diff --git a/node_modules/es-abstract/2018/GetIterator.js b/node_modules/es-abstract/2018/GetIterator.js deleted file mode 100644 index 7beddac..0000000 --- a/node_modules/es-abstract/2018/GetIterator.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var getIteratorMethod = require('../helpers/getIteratorMethod'); -var AdvanceStringIndex = require('./AdvanceStringIndex'); -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsArray = require('./IsArray'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-getiterator - -module.exports = function GetIterator(obj, method) { - var actualMethod = method; - if (arguments.length < 2) { - actualMethod = getIteratorMethod( - { - AdvanceStringIndex: AdvanceStringIndex, - GetMethod: GetMethod, - IsArray: IsArray, - Type: Type - }, - obj - ); - } - var iterator = Call(actualMethod, obj); - if (Type(iterator) !== 'Object') { - throw new $TypeError('iterator must return an object'); - } - - return iterator; -}; diff --git a/node_modules/es-abstract/2018/GetMethod.js b/node_modules/es-abstract/2018/GetMethod.js deleted file mode 100644 index aef8cbc..0000000 --- a/node_modules/es-abstract/2018/GetMethod.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var GetV = require('./GetV'); -var IsCallable = require('./IsCallable'); -var IsPropertyKey = require('./IsPropertyKey'); - -/** - * 7.3.9 - https://ecma-international.org/ecma-262/6.0/#sec-getmethod - * 1. Assert: IsPropertyKey(P) is true. - * 2. Let func be GetV(O, P). - * 3. ReturnIfAbrupt(func). - * 4. If func is either undefined or null, return undefined. - * 5. If IsCallable(func) is false, throw a TypeError exception. - * 6. Return func. - */ - -module.exports = function GetMethod(O, P) { - // 7.3.9.1 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // 7.3.9.2 - var func = GetV(O, P); - - // 7.3.9.4 - if (func == null) { - return void 0; - } - - // 7.3.9.5 - if (!IsCallable(func)) { - throw new $TypeError(P + 'is not a function'); - } - - // 7.3.9.6 - return func; -}; diff --git a/node_modules/es-abstract/2018/GetOwnPropertyKeys.js b/node_modules/es-abstract/2018/GetOwnPropertyKeys.js deleted file mode 100644 index 8d7e5ee..0000000 --- a/node_modules/es-abstract/2018/GetOwnPropertyKeys.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var hasSymbols = require('has-symbols')(); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); -var $gOPS = hasSymbols && GetIntrinsic('%Object.getOwnPropertySymbols%'); -var keys = require('object-keys'); - -var esType = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-getownpropertykeys - -module.exports = function GetOwnPropertyKeys(O, Type) { - if (esType(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (Type === 'Symbol') { - return $gOPS ? $gOPS(O) : []; - } - if (Type === 'String') { - if (!$gOPN) { - return keys(O); - } - return $gOPN(O); - } - throw new $TypeError('Assertion failed: `Type` must be `"String"` or `"Symbol"`'); -}; diff --git a/node_modules/es-abstract/2018/GetPrototypeFromConstructor.js b/node_modules/es-abstract/2018/GetPrototypeFromConstructor.js deleted file mode 100644 index 62da8fb..0000000 --- a/node_modules/es-abstract/2018/GetPrototypeFromConstructor.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Function = GetIntrinsic('%Function%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsConstructor = require('./IsConstructor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-getprototypefromconstructor - -module.exports = function GetPrototypeFromConstructor(constructor, intrinsicDefaultProto) { - var intrinsic = GetIntrinsic(intrinsicDefaultProto); // throws if not a valid intrinsic - if (!IsConstructor(constructor)) { - throw new $TypeError('Assertion failed: `constructor` must be a constructor'); - } - var proto = Get(constructor, 'prototype'); - if (Type(proto) !== 'Object') { - if (!(constructor instanceof $Function)) { - // ignore other realms, for now - throw new $TypeError('cross-realm constructors not currently supported'); - } - proto = intrinsic; - } - return proto; -}; diff --git a/node_modules/es-abstract/2018/GetSubstitution.js b/node_modules/es-abstract/2018/GetSubstitution.js deleted file mode 100644 index 2ec9ebc..0000000 --- a/node_modules/es-abstract/2018/GetSubstitution.js +++ /dev/null @@ -1,128 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); -var regexTester = require('../helpers/regexTester'); -var every = require('../helpers/every'); - -var $charAt = callBound('String.prototype.charAt'); -var $strSlice = callBound('String.prototype.slice'); -var $indexOf = callBound('String.prototype.indexOf'); -var $parseInt = parseInt; - -var isDigit = regexTester(/^[0-9]$/); - -var inspect = require('object-inspect'); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var IsInteger = require('./IsInteger'); -var ToObject = require('./ToObject'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -var canDistinguishSparseFromUndefined = 0 in [undefined]; // IE 6 - 8 have a bug where this returns false - -var isStringOrHole = function (capture, index, arr) { - return Type(capture) === 'String' || (canDistinguishSparseFromUndefined ? !(index in arr) : Type(capture) === 'Undefined'); -}; - -// http://www.ecma-international.org/ecma-262/9.0/#sec-getsubstitution - -// eslint-disable-next-line max-statements, max-params, max-lines-per-function -module.exports = function GetSubstitution(matched, str, position, captures, namedCaptures, replacement) { - if (Type(matched) !== 'String') { - throw new $TypeError('Assertion failed: `matched` must be a String'); - } - var matchLength = matched.length; - - if (Type(str) !== 'String') { - throw new $TypeError('Assertion failed: `str` must be a String'); - } - var stringLength = str.length; - - if (!IsInteger(position) || position < 0 || position > stringLength) { - throw new $TypeError('Assertion failed: `position` must be a nonnegative integer, and less than or equal to the length of `string`, got ' + inspect(position)); - } - - if (!IsArray(captures) || !every(captures, isStringOrHole)) { - throw new $TypeError('Assertion failed: `captures` must be a List of Strings, got ' + inspect(captures)); - } - - if (Type(replacement) !== 'String') { - throw new $TypeError('Assertion failed: `replacement` must be a String'); - } - - var tailPos = position + matchLength; - var m = captures.length; - if (Type(namedCaptures) !== 'Undefined') { - namedCaptures = ToObject(namedCaptures); // eslint-disable-line no-param-reassign - } - - var result = ''; - for (var i = 0; i < replacement.length; i += 1) { - // if this is a $, and it's not the end of the replacement - var current = $charAt(replacement, i); - var isLast = (i + 1) >= replacement.length; - var nextIsLast = (i + 2) >= replacement.length; - if (current === '$' && !isLast) { - var next = $charAt(replacement, i + 1); - if (next === '$') { - result += '$'; - i += 1; - } else if (next === '&') { - result += matched; - i += 1; - } else if (next === '`') { - result += position === 0 ? '' : $strSlice(str, 0, position - 1); - i += 1; - } else if (next === "'") { - result += tailPos >= stringLength ? '' : $strSlice(str, tailPos); - i += 1; - } else { - var nextNext = nextIsLast ? null : $charAt(replacement, i + 2); - if (isDigit(next) && next !== '0' && (nextIsLast || !isDigit(nextNext))) { - // $1 through $9, and not followed by a digit - var n = $parseInt(next, 10); - // if (n > m, impl-defined) - result += (n <= m && Type(captures[n - 1]) === 'Undefined') ? '' : captures[n - 1]; - i += 1; - } else if (isDigit(next) && (nextIsLast || isDigit(nextNext))) { - // $00 through $99 - var nn = next + nextNext; - var nnI = $parseInt(nn, 10) - 1; - // if nn === '00' or nn > m, impl-defined - result += (nn <= m && Type(captures[nnI]) === 'Undefined') ? '' : captures[nnI]; - i += 2; - } else if (next === '<') { - // eslint-disable-next-line max-depth - if (Type(namedCaptures) === 'Undefined') { - result += '$<'; - i += 2; - } else { - var endIndex = $indexOf(replacement, '>', i); - // eslint-disable-next-line max-depth - if (endIndex > -1) { - var groupName = $strSlice(replacement, i, endIndex); - var capture = Get(namedCaptures, groupName); - // eslint-disable-next-line max-depth - if (Type(capture) !== 'Undefined') { - result += ToString(capture); - } - i += '$<' + groupName + '>'.length; - } - } - } else { - result += '$'; - } - } - } else { - // the final $, or else not a $ - result += $charAt(replacement, i); - } - } - return result; -}; diff --git a/node_modules/es-abstract/2018/GetV.js b/node_modules/es-abstract/2018/GetV.js deleted file mode 100644 index 7b5139a..0000000 --- a/node_modules/es-abstract/2018/GetV.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var ToObject = require('./ToObject'); - -/** - * 7.3.2 GetV (V, P) - * 1. Assert: IsPropertyKey(P) is true. - * 2. Let O be ToObject(V). - * 3. ReturnIfAbrupt(O). - * 4. Return O.[[Get]](P, V). - */ - -module.exports = function GetV(V, P) { - // 7.3.2.1 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // 7.3.2.2-3 - var O = ToObject(V); - - // 7.3.2.4 - return O[P]; -}; diff --git a/node_modules/es-abstract/2018/HasOwnProperty.js b/node_modules/es-abstract/2018/HasOwnProperty.js deleted file mode 100644 index 679059f..0000000 --- a/node_modules/es-abstract/2018/HasOwnProperty.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var has = require('has'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-hasownproperty - -module.exports = function HasOwnProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - return has(O, P); -}; diff --git a/node_modules/es-abstract/2018/HasProperty.js b/node_modules/es-abstract/2018/HasProperty.js deleted file mode 100644 index 5f2d212..0000000 --- a/node_modules/es-abstract/2018/HasProperty.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-hasproperty - -module.exports = function HasProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - return P in O; -}; diff --git a/node_modules/es-abstract/2018/HourFromTime.js b/node_modules/es-abstract/2018/HourFromTime.js deleted file mode 100644 index 957ce32..0000000 --- a/node_modules/es-abstract/2018/HourFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerHour = timeConstants.msPerHour; -var HoursPerDay = timeConstants.HoursPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function HourFromTime(t) { - return mod($floor(t / msPerHour), HoursPerDay); -}; diff --git a/node_modules/es-abstract/2018/InLeapYear.js b/node_modules/es-abstract/2018/InLeapYear.js deleted file mode 100644 index 38ba8fd..0000000 --- a/node_modules/es-abstract/2018/InLeapYear.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $EvalError = GetIntrinsic('%EvalError%'); - -var DaysInYear = require('./DaysInYear'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function InLeapYear(t) { - var days = DaysInYear(YearFromTime(t)); - if (days === 365) { - return 0; - } - if (days === 366) { - return 1; - } - throw new $EvalError('Assertion failed: there are not 365 or 366 days in a year, got: ' + days); -}; diff --git a/node_modules/es-abstract/2018/InstanceofOperator.js b/node_modules/es-abstract/2018/InstanceofOperator.js deleted file mode 100644 index ebd308c..0000000 --- a/node_modules/es-abstract/2018/InstanceofOperator.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $hasInstance = GetIntrinsic('Symbol.hasInstance', true); - -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsCallable = require('./IsCallable'); -var OrdinaryHasInstance = require('./OrdinaryHasInstance'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-instanceofoperator - -module.exports = function InstanceofOperator(O, C) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - var instOfHandler = $hasInstance ? GetMethod(C, $hasInstance) : void 0; - if (typeof instOfHandler !== 'undefined') { - return ToBoolean(Call(instOfHandler, C, [O])); - } - if (!IsCallable(C)) { - throw new $TypeError('`C` is not Callable'); - } - return OrdinaryHasInstance(C, O); -}; diff --git a/node_modules/es-abstract/2018/Invoke.js b/node_modules/es-abstract/2018/Invoke.js deleted file mode 100644 index 769f0e3..0000000 --- a/node_modules/es-abstract/2018/Invoke.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $arraySlice = require('../helpers/callBound')('Array.prototype.slice'); - -var Call = require('./Call'); -var GetV = require('./GetV'); -var IsPropertyKey = require('./IsPropertyKey'); - -// https://ecma-international.org/ecma-262/6.0/#sec-invoke - -module.exports = function Invoke(O, P) { - if (!IsPropertyKey(P)) { - throw new $TypeError('P must be a Property Key'); - } - var argumentsList = $arraySlice(arguments, 2); - var func = GetV(O, P); - return Call(func, O, argumentsList); -}; diff --git a/node_modules/es-abstract/2018/IsAccessorDescriptor.js b/node_modules/es-abstract/2018/IsAccessorDescriptor.js deleted file mode 100644 index 5139464..0000000 --- a/node_modules/es-abstract/2018/IsAccessorDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isaccessordescriptor - -module.exports = function IsAccessorDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) { - return false; - } - - return true; -}; diff --git a/node_modules/es-abstract/2018/IsArray.js b/node_modules/es-abstract/2018/IsArray.js deleted file mode 100644 index 7b25f37..0000000 --- a/node_modules/es-abstract/2018/IsArray.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Array = GetIntrinsic('%Array%'); - -// eslint-disable-next-line global-require -var toStr = !$Array.isArray && require('../helpers/callBound')('Object.prototype.toString'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isarray - -module.exports = $Array.isArray || function IsArray(argument) { - return toStr(argument) === '[object Array]'; -}; diff --git a/node_modules/es-abstract/2018/IsCallable.js b/node_modules/es-abstract/2018/IsCallable.js deleted file mode 100644 index e4bfa36..0000000 --- a/node_modules/es-abstract/2018/IsCallable.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.11 - -module.exports = require('is-callable'); diff --git a/node_modules/es-abstract/2018/IsConcatSpreadable.js b/node_modules/es-abstract/2018/IsConcatSpreadable.js deleted file mode 100644 index dc8aae1..0000000 --- a/node_modules/es-abstract/2018/IsConcatSpreadable.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $isConcatSpreadable = GetIntrinsic('%Symbol.isConcatSpreadable%', true); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-isconcatspreadable - -module.exports = function IsConcatSpreadable(O) { - if (Type(O) !== 'Object') { - return false; - } - if ($isConcatSpreadable) { - var spreadable = Get(O, $isConcatSpreadable); - if (typeof spreadable !== 'undefined') { - return ToBoolean(spreadable); - } - } - return IsArray(O); -}; diff --git a/node_modules/es-abstract/2018/IsConstructor.js b/node_modules/es-abstract/2018/IsConstructor.js deleted file mode 100644 index 00ea52c..0000000 --- a/node_modules/es-abstract/2018/IsConstructor.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isconstructor - -module.exports = function IsConstructor(argument) { - return typeof argument === 'function' && !!argument.prototype; // unfortunately there's no way to truly check this without try/catch `new argument` -}; diff --git a/node_modules/es-abstract/2018/IsDataDescriptor.js b/node_modules/es-abstract/2018/IsDataDescriptor.js deleted file mode 100644 index 0ad3045..0000000 --- a/node_modules/es-abstract/2018/IsDataDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isdatadescriptor - -module.exports = function IsDataDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) { - return false; - } - - return true; -}; diff --git a/node_modules/es-abstract/2018/IsExtensible.js b/node_modules/es-abstract/2018/IsExtensible.js deleted file mode 100644 index 0c4c8a6..0000000 --- a/node_modules/es-abstract/2018/IsExtensible.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Object = GetIntrinsic('%Object%'); - -var isPrimitive = require('../helpers/isPrimitive'); - -var $preventExtensions = $Object.preventExtensions; -var $isExtensible = $Object.isExtensible; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isextensible-o - -module.exports = $preventExtensions - ? function IsExtensible(obj) { - return !isPrimitive(obj) && $isExtensible(obj); - } - : function IsExtensible(obj) { - return !isPrimitive(obj); - }; diff --git a/node_modules/es-abstract/2018/IsGenericDescriptor.js b/node_modules/es-abstract/2018/IsGenericDescriptor.js deleted file mode 100644 index 8618ce4..0000000 --- a/node_modules/es-abstract/2018/IsGenericDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var assertRecord = require('../helpers/assertRecord'); - -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isgenericdescriptor - -module.exports = function IsGenericDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!IsAccessorDescriptor(Desc) && !IsDataDescriptor(Desc)) { - return true; - } - - return false; -}; diff --git a/node_modules/es-abstract/2018/IsInteger.js b/node_modules/es-abstract/2018/IsInteger.js deleted file mode 100644 index 0f488b3..0000000 --- a/node_modules/es-abstract/2018/IsInteger.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isinteger - -module.exports = function IsInteger(argument) { - if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) { - return false; - } - var abs = $abs(argument); - return $floor(abs) === abs; -}; diff --git a/node_modules/es-abstract/2018/IsPromise.js b/node_modules/es-abstract/2018/IsPromise.js deleted file mode 100644 index e8e92a2..0000000 --- a/node_modules/es-abstract/2018/IsPromise.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var $PromiseThen = callBound('Promise.prototype.then', true); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ispromise - -module.exports = function IsPromise(x) { - if (Type(x) !== 'Object') { - return false; - } - if (!$PromiseThen) { // Promises are not supported - return false; - } - try { - $PromiseThen(x); // throws if not a promise - } catch (e) { - return false; - } - return true; -}; diff --git a/node_modules/es-abstract/2018/IsPropertyKey.js b/node_modules/es-abstract/2018/IsPropertyKey.js deleted file mode 100644 index 74b8d95..0000000 --- a/node_modules/es-abstract/2018/IsPropertyKey.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ispropertykey - -module.exports = function IsPropertyKey(argument) { - return typeof argument === 'string' || typeof argument === 'symbol'; -}; diff --git a/node_modules/es-abstract/2018/IsRegExp.js b/node_modules/es-abstract/2018/IsRegExp.js deleted file mode 100644 index fdf2323..0000000 --- a/node_modules/es-abstract/2018/IsRegExp.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $match = GetIntrinsic('%Symbol.match%', true); - -var hasRegExpMatcher = require('is-regex'); - -var ToBoolean = require('./ToBoolean'); - -// https://ecma-international.org/ecma-262/6.0/#sec-isregexp - -module.exports = function IsRegExp(argument) { - if (!argument || typeof argument !== 'object') { - return false; - } - if ($match) { - var isRegExp = argument[$match]; - if (typeof isRegExp !== 'undefined') { - return ToBoolean(isRegExp); - } - } - return hasRegExpMatcher(argument); -}; diff --git a/node_modules/es-abstract/2018/IsStringPrefix.js b/node_modules/es-abstract/2018/IsStringPrefix.js deleted file mode 100644 index f5e2996..0000000 --- a/node_modules/es-abstract/2018/IsStringPrefix.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var isPrefixOf = require('../helpers/isPrefixOf'); - -// var callBound = require('../helpers/callBound'); - -// var $charAt = callBound('String.prototype.charAt'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/9.0/#sec-isstringprefix - -module.exports = function IsStringPrefix(p, q) { - if (Type(p) !== 'String') { - throw new $TypeError('Assertion failed: "p" must be a String'); - } - - if (Type(q) !== 'String') { - throw new $TypeError('Assertion failed: "q" must be a String'); - } - - return isPrefixOf(p, q); - /* - if (p === q || p === '') { - return true; - } - - var pLength = p.length; - var qLength = q.length; - if (pLength >= qLength) { - return false; - } - - // assert: pLength < qLength - - for (var i = 0; i < pLength; i += 1) { - if ($charAt(p, i) !== $charAt(q, i)) { - return false; - } - } - return true; - */ -}; diff --git a/node_modules/es-abstract/2018/IterableToList.js b/node_modules/es-abstract/2018/IterableToList.js deleted file mode 100644 index 0b8cdcf..0000000 --- a/node_modules/es-abstract/2018/IterableToList.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); -var $arrayPush = callBound('Array.prototype.push'); - -var GetIterator = require('./GetIterator'); -var IteratorStep = require('./IteratorStep'); -var IteratorValue = require('./IteratorValue'); - -// https://www.ecma-international.org/ecma-262/8.0/#sec-iterabletolist - -module.exports = function IterableToList(items, method) { - var iterator = GetIterator(items, method); - var values = []; - var next = true; - while (next) { - next = IteratorStep(iterator); - if (next) { - var nextValue = IteratorValue(next); - $arrayPush(values, nextValue); - } - } - return values; -}; diff --git a/node_modules/es-abstract/2018/IteratorClose.js b/node_modules/es-abstract/2018/IteratorClose.js deleted file mode 100644 index 35c8c2b..0000000 --- a/node_modules/es-abstract/2018/IteratorClose.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorclose - -module.exports = function IteratorClose(iterator, completion) { - if (Type(iterator) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterator) is not Object'); - } - if (!IsCallable(completion)) { - throw new $TypeError('Assertion failed: completion is not a thunk for a Completion Record'); - } - var completionThunk = completion; - - var iteratorReturn = GetMethod(iterator, 'return'); - - if (typeof iteratorReturn === 'undefined') { - return completionThunk(); - } - - var completionRecord; - try { - var innerResult = Call(iteratorReturn, iterator, []); - } catch (e) { - // if we hit here, then "e" is the innerResult completion that needs re-throwing - - // if the completion is of type "throw", this will throw. - completionThunk(); - completionThunk = null; // ensure it's not called twice. - - // if not, then return the innerResult completion - throw e; - } - completionRecord = completionThunk(); // if innerResult worked, then throw if the completion does - completionThunk = null; // ensure it's not called twice. - - if (Type(innerResult) !== 'Object') { - throw new $TypeError('iterator .return must return an object'); - } - - return completionRecord; -}; diff --git a/node_modules/es-abstract/2018/IteratorComplete.js b/node_modules/es-abstract/2018/IteratorComplete.js deleted file mode 100644 index a62b9bf..0000000 --- a/node_modules/es-abstract/2018/IteratorComplete.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorcomplete - -module.exports = function IteratorComplete(iterResult) { - if (Type(iterResult) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); - } - return ToBoolean(Get(iterResult, 'done')); -}; diff --git a/node_modules/es-abstract/2018/IteratorNext.js b/node_modules/es-abstract/2018/IteratorNext.js deleted file mode 100644 index 7e59915..0000000 --- a/node_modules/es-abstract/2018/IteratorNext.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Invoke = require('./Invoke'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratornext - -module.exports = function IteratorNext(iterator, value) { - var result = Invoke(iterator, 'next', arguments.length < 2 ? [] : [value]); - if (Type(result) !== 'Object') { - throw new $TypeError('iterator next must return an object'); - } - return result; -}; diff --git a/node_modules/es-abstract/2018/IteratorStep.js b/node_modules/es-abstract/2018/IteratorStep.js deleted file mode 100644 index 41b9d1b..0000000 --- a/node_modules/es-abstract/2018/IteratorStep.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var IteratorComplete = require('./IteratorComplete'); -var IteratorNext = require('./IteratorNext'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorstep - -module.exports = function IteratorStep(iterator) { - var result = IteratorNext(iterator); - var done = IteratorComplete(result); - return done === true ? false : result; -}; - diff --git a/node_modules/es-abstract/2018/IteratorValue.js b/node_modules/es-abstract/2018/IteratorValue.js deleted file mode 100644 index 5e71a44..0000000 --- a/node_modules/es-abstract/2018/IteratorValue.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorvalue - -module.exports = function IteratorValue(iterResult) { - if (Type(iterResult) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); - } - return Get(iterResult, 'value'); -}; - diff --git a/node_modules/es-abstract/2018/MakeDate.js b/node_modules/es-abstract/2018/MakeDate.js deleted file mode 100644 index 7b592d1..0000000 --- a/node_modules/es-abstract/2018/MakeDate.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $isFinite = require('../helpers/isFinite'); -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.13 - -module.exports = function MakeDate(day, time) { - if (!$isFinite(day) || !$isFinite(time)) { - return NaN; - } - return (day * msPerDay) + time; -}; diff --git a/node_modules/es-abstract/2018/MakeDay.js b/node_modules/es-abstract/2018/MakeDay.js deleted file mode 100644 index f1ab810..0000000 --- a/node_modules/es-abstract/2018/MakeDay.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); -var $DateUTC = GetIntrinsic('%Date.UTC%'); - -var mod = require('../helpers/mod'); -var $isFinite = require('../helpers/isFinite'); - -var DateFromTime = require('./DateFromTime'); -var Day = require('./Day'); -var MonthFromTime = require('./MonthFromTime'); -var ToInteger = require('./ToInteger'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.12 - -module.exports = function MakeDay(year, month, date) { - if (!$isFinite(year) || !$isFinite(month) || !$isFinite(date)) { - return NaN; - } - var y = ToInteger(year); - var m = ToInteger(month); - var dt = ToInteger(date); - var ym = y + $floor(m / 12); - var mn = mod(m, 12); - var t = $DateUTC(ym, mn, 1); - if (YearFromTime(t) !== ym || MonthFromTime(t) !== mn || DateFromTime(t) !== 1) { - return NaN; - } - return Day(t) + dt - 1; -}; diff --git a/node_modules/es-abstract/2018/MakeTime.js b/node_modules/es-abstract/2018/MakeTime.js deleted file mode 100644 index e118500..0000000 --- a/node_modules/es-abstract/2018/MakeTime.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var $isFinite = require('../helpers/isFinite'); -var timeConstants = require('../helpers/timeConstants'); -var msPerSecond = timeConstants.msPerSecond; -var msPerMinute = timeConstants.msPerMinute; -var msPerHour = timeConstants.msPerHour; - -var ToInteger = require('./ToInteger'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.11 - -module.exports = function MakeTime(hour, min, sec, ms) { - if (!$isFinite(hour) || !$isFinite(min) || !$isFinite(sec) || !$isFinite(ms)) { - return NaN; - } - var h = ToInteger(hour); - var m = ToInteger(min); - var s = ToInteger(sec); - var milli = ToInteger(ms); - var t = (h * msPerHour) + (m * msPerMinute) + (s * msPerSecond) + milli; - return t; -}; diff --git a/node_modules/es-abstract/2018/MinFromTime.js b/node_modules/es-abstract/2018/MinFromTime.js deleted file mode 100644 index e80e191..0000000 --- a/node_modules/es-abstract/2018/MinFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerMinute = timeConstants.msPerMinute; -var MinutesPerHour = timeConstants.MinutesPerHour; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function MinFromTime(t) { - return mod($floor(t / msPerMinute), MinutesPerHour); -}; diff --git a/node_modules/es-abstract/2018/MonthFromTime.js b/node_modules/es-abstract/2018/MonthFromTime.js deleted file mode 100644 index 4f120f2..0000000 --- a/node_modules/es-abstract/2018/MonthFromTime.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -var DayWithinYear = require('./DayWithinYear'); -var InLeapYear = require('./InLeapYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - -module.exports = function MonthFromTime(t) { - var day = DayWithinYear(t); - if (0 <= day && day < 31) { - return 0; - } - var leap = InLeapYear(t); - if (31 <= day && day < (59 + leap)) { - return 1; - } - if ((59 + leap) <= day && day < (90 + leap)) { - return 2; - } - if ((90 + leap) <= day && day < (120 + leap)) { - return 3; - } - if ((120 + leap) <= day && day < (151 + leap)) { - return 4; - } - if ((151 + leap) <= day && day < (181 + leap)) { - return 5; - } - if ((181 + leap) <= day && day < (212 + leap)) { - return 6; - } - if ((212 + leap) <= day && day < (243 + leap)) { - return 7; - } - if ((243 + leap) <= day && day < (273 + leap)) { - return 8; - } - if ((273 + leap) <= day && day < (304 + leap)) { - return 9; - } - if ((304 + leap) <= day && day < (334 + leap)) { - return 10; - } - if ((334 + leap) <= day && day < (365 + leap)) { - return 11; - } -}; diff --git a/node_modules/es-abstract/2018/NumberToString.js b/node_modules/es-abstract/2018/NumberToString.js deleted file mode 100644 index 2cc70e0..0000000 --- a/node_modules/es-abstract/2018/NumberToString.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $String = GetIntrinsic('%String%'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/9.0/#sec-tostring-applied-to-the-number-type - -module.exports = function NumberToString(m) { - if (Type(m) !== 'Number') { - throw new TypeError('Assertion failed: "m" must be a String'); - } - - return $String(m); -}; - diff --git a/node_modules/es-abstract/2018/ObjectCreate.js b/node_modules/es-abstract/2018/ObjectCreate.js deleted file mode 100644 index e2445b0..0000000 --- a/node_modules/es-abstract/2018/ObjectCreate.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $ObjectCreate = GetIntrinsic('%Object.create%', true); -var $TypeError = GetIntrinsic('%TypeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); - -var Type = require('./Type'); - -var hasProto = !({ __proto__: null } instanceof Object); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-objectcreate - -module.exports = function ObjectCreate(proto, internalSlotsList) { - if (proto !== null && Type(proto) !== 'Object') { - throw new $TypeError('Assertion failed: `proto` must be null or an object'); - } - var slots = arguments.length < 2 ? [] : internalSlotsList; - if (slots.length > 0) { - throw new $SyntaxError('es-abstract does not yet support internal slots'); - } - - if ($ObjectCreate) { - return $ObjectCreate(proto); - } - if (hasProto) { - return { __proto__: proto }; - } - - if (proto === null) { - throw new $SyntaxError('native Object.create support is required to create null objects'); - } - var T = function T() {}; - T.prototype = proto; - return new T(); -}; diff --git a/node_modules/es-abstract/2018/OrdinaryDefineOwnProperty.js b/node_modules/es-abstract/2018/OrdinaryDefineOwnProperty.js deleted file mode 100644 index 59780b3..0000000 --- a/node_modules/es-abstract/2018/OrdinaryDefineOwnProperty.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var IsPropertyKey = require('./IsPropertyKey'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); -var ValidateAndApplyPropertyDescriptor = require('./ValidateAndApplyPropertyDescriptor'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarydefineownproperty - -module.exports = function OrdinaryDefineOwnProperty(O, P, Desc) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (!$gOPD) { - // ES3/IE 8 fallback - if (IsAccessorDescriptor(Desc)) { - throw new $SyntaxError('This environment does not support accessor property descriptors.'); - } - var creatingNormalDataProperty = !(P in O) - && Desc['[[Writable]]'] - && Desc['[[Enumerable]]'] - && Desc['[[Configurable]]'] - && '[[Value]]' in Desc; - var settingExistingDataProperty = (P in O) - && (!('[[Configurable]]' in Desc) || Desc['[[Configurable]]']) - && (!('[[Enumerable]]' in Desc) || Desc['[[Enumerable]]']) - && (!('[[Writable]]' in Desc) || Desc['[[Writable]]']) - && '[[Value]]' in Desc; - if (creatingNormalDataProperty || settingExistingDataProperty) { - O[P] = Desc['[[Value]]']; // eslint-disable-line no-param-reassign - return SameValue(O[P], Desc['[[Value]]']); - } - throw new $SyntaxError('This environment does not support defining non-writable, non-enumerable, or non-configurable properties'); - } - var desc = $gOPD(O, P); - var current = desc && ToPropertyDescriptor(desc); - var extensible = IsExtensible(O); - return ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current); -}; diff --git a/node_modules/es-abstract/2018/OrdinaryGetOwnProperty.js b/node_modules/es-abstract/2018/OrdinaryGetOwnProperty.js deleted file mode 100644 index b9882e5..0000000 --- a/node_modules/es-abstract/2018/OrdinaryGetOwnProperty.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); - -var has = require('has'); - -var IsArray = require('./IsArray'); -var IsPropertyKey = require('./IsPropertyKey'); -var IsRegExp = require('./IsRegExp'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarygetownproperty - -module.exports = function OrdinaryGetOwnProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - if (!has(O, P)) { - return void 0; - } - if (!$gOPD) { - // ES3 / IE 8 fallback - var arrayLength = IsArray(O) && P === 'length'; - var regexLastIndex = IsRegExp(O) && P === 'lastIndex'; - return { - '[[Configurable]]': !(arrayLength || regexLastIndex), - '[[Enumerable]]': $isEnumerable(O, P), - '[[Value]]': O[P], - '[[Writable]]': true - }; - } - return ToPropertyDescriptor($gOPD(O, P)); -}; diff --git a/node_modules/es-abstract/2018/OrdinaryGetPrototypeOf.js b/node_modules/es-abstract/2018/OrdinaryGetPrototypeOf.js deleted file mode 100644 index 344077a..0000000 --- a/node_modules/es-abstract/2018/OrdinaryGetPrototypeOf.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $getProto = require('../helpers/getProto'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/7.0/#sec-ordinarygetprototypeof - -module.exports = function OrdinaryGetPrototypeOf(O) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!$getProto) { - throw new $TypeError('This environment does not support fetching prototypes.'); - } - return $getProto(O); -}; diff --git a/node_modules/es-abstract/2018/OrdinaryHasInstance.js b/node_modules/es-abstract/2018/OrdinaryHasInstance.js deleted file mode 100644 index 51abe26..0000000 --- a/node_modules/es-abstract/2018/OrdinaryHasInstance.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance - -module.exports = function OrdinaryHasInstance(C, O) { - if (IsCallable(C) === false) { - return false; - } - if (Type(O) !== 'Object') { - return false; - } - var P = Get(C, 'prototype'); - if (Type(P) !== 'Object') { - throw new $TypeError('OrdinaryHasInstance called on an object with an invalid prototype property.'); - } - return O instanceof C; -}; diff --git a/node_modules/es-abstract/2018/OrdinaryHasProperty.js b/node_modules/es-abstract/2018/OrdinaryHasProperty.js deleted file mode 100644 index 076c25a..0000000 --- a/node_modules/es-abstract/2018/OrdinaryHasProperty.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasproperty - -module.exports = function OrdinaryHasProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - return P in O; -}; diff --git a/node_modules/es-abstract/2018/OrdinarySetPrototypeOf.js b/node_modules/es-abstract/2018/OrdinarySetPrototypeOf.js deleted file mode 100644 index 3541331..0000000 --- a/node_modules/es-abstract/2018/OrdinarySetPrototypeOf.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $setProto = require('../helpers/setProto'); - -var OrdinaryGetPrototypeOf = require('./OrdinaryGetPrototypeOf'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/7.0/#sec-ordinarysetprototypeof - -module.exports = function OrdinarySetPrototypeOf(O, V) { - if (Type(V) !== 'Object' && Type(V) !== 'Null') { - throw new $TypeError('Assertion failed: V must be Object or Null'); - } - /* - var extensible = IsExtensible(O); - var current = OrdinaryGetPrototypeOf(O); - if (SameValue(V, current)) { - return true; - } - if (!extensible) { - return false; - } - */ - try { - $setProto(O, V); - } catch (e) { - return false; - } - return OrdinaryGetPrototypeOf(O) === V; - /* - var p = V; - var done = false; - while (!done) { - if (p === null) { - done = true; - } else if (SameValue(p, O)) { - return false; - } else { - if (wat) { - done = true; - } else { - p = p.[[Prototype]]; - } - } - } - O.[[Prototype]] = V; - return true; - */ -}; diff --git a/node_modules/es-abstract/2018/PromiseResolve.js b/node_modules/es-abstract/2018/PromiseResolve.js deleted file mode 100644 index f70745d..0000000 --- a/node_modules/es-abstract/2018/PromiseResolve.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var $PromiseResolve = callBound('Promise.resolve', true); - -// https://ecma-international.org/ecma-262/9.0/#sec-promise-resolve - -module.exports = function PromiseResolve(C, x) { - if (!$PromiseResolve) { - throw new SyntaxError('This environment does not support Promises.'); - } - return $PromiseResolve(C, x); -}; - diff --git a/node_modules/es-abstract/2018/RegExpExec.js b/node_modules/es-abstract/2018/RegExpExec.js deleted file mode 100644 index 15c9186..0000000 --- a/node_modules/es-abstract/2018/RegExpExec.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var regexExec = require('../helpers/callBound')('RegExp.prototype.exec'); - -var Call = require('./Call'); -var Get = require('./Get'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-regexpexec - -module.exports = function RegExpExec(R, S) { - if (Type(R) !== 'Object') { - throw new $TypeError('Assertion failed: `R` must be an Object'); - } - if (Type(S) !== 'String') { - throw new $TypeError('Assertion failed: `S` must be a String'); - } - var exec = Get(R, 'exec'); - if (IsCallable(exec)) { - var result = Call(exec, R, [S]); - if (result === null || Type(result) === 'Object') { - return result; - } - throw new $TypeError('"exec" method must return `null` or an Object'); - } - return regexExec(R, S); -}; diff --git a/node_modules/es-abstract/2018/RequireObjectCoercible.js b/node_modules/es-abstract/2018/RequireObjectCoercible.js deleted file mode 100644 index 9008359..0000000 --- a/node_modules/es-abstract/2018/RequireObjectCoercible.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('../5/CheckObjectCoercible'); diff --git a/node_modules/es-abstract/2018/SameValue.js b/node_modules/es-abstract/2018/SameValue.js deleted file mode 100644 index 47c936d..0000000 --- a/node_modules/es-abstract/2018/SameValue.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $isNaN = require('../helpers/isNaN'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.12 - -module.exports = function SameValue(x, y) { - if (x === y) { // 0 === -0, but they are not identical. - if (x === 0) { return 1 / x === 1 / y; } - return true; - } - return $isNaN(x) && $isNaN(y); -}; diff --git a/node_modules/es-abstract/2018/SameValueNonNumber.js b/node_modules/es-abstract/2018/SameValueNonNumber.js deleted file mode 100644 index 5668752..0000000 --- a/node_modules/es-abstract/2018/SameValueNonNumber.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var SameValue = require('./SameValue'); - -// https://www.ecma-international.org/ecma-262/7.0/#sec-samevaluenonnumber - -module.exports = function SameValueNonNumber(x, y) { - if (typeof x === 'number' || typeof x !== typeof y) { - throw new $TypeError('SameValueNonNumber requires two non-number values of the same type.'); - } - return SameValue(x, y); -}; diff --git a/node_modules/es-abstract/2018/SameValueZero.js b/node_modules/es-abstract/2018/SameValueZero.js deleted file mode 100644 index 0dedcd2..0000000 --- a/node_modules/es-abstract/2018/SameValueZero.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var $isNaN = require('../helpers/isNaN'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-samevaluezero - -module.exports = function SameValueZero(x, y) { - return (x === y) || ($isNaN(x) && $isNaN(y)); -}; diff --git a/node_modules/es-abstract/2018/SecFromTime.js b/node_modules/es-abstract/2018/SecFromTime.js deleted file mode 100644 index 7190011..0000000 --- a/node_modules/es-abstract/2018/SecFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerSecond = timeConstants.msPerSecond; -var SecondsPerMinute = timeConstants.SecondsPerMinute; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function SecFromTime(t) { - return mod($floor(t / msPerSecond), SecondsPerMinute); -}; diff --git a/node_modules/es-abstract/2018/Set.js b/node_modules/es-abstract/2018/Set.js deleted file mode 100644 index 18ebd99..0000000 --- a/node_modules/es-abstract/2018/Set.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-set-o-p-v-throw - -module.exports = function Set(O, P, V, Throw) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - if (Type(Throw) !== 'Boolean') { - throw new $TypeError('Assertion failed: `Throw` must be a Boolean'); - } - if (Throw) { - O[P] = V; // eslint-disable-line no-param-reassign - return true; - } else { - try { - O[P] = V; // eslint-disable-line no-param-reassign - } catch (e) { - return false; - } - } -}; diff --git a/node_modules/es-abstract/2018/SetFunctionName.js b/node_modules/es-abstract/2018/SetFunctionName.js deleted file mode 100644 index f93324a..0000000 --- a/node_modules/es-abstract/2018/SetFunctionName.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var has = require('has'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var getSymbolDescription = require('../helpers/getSymbolDescription'); - -var DefinePropertyOrThrow = require('./DefinePropertyOrThrow'); -var IsExtensible = require('./IsExtensible'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-setfunctionname - -module.exports = function SetFunctionName(F, name) { - if (typeof F !== 'function') { - throw new $TypeError('Assertion failed: `F` must be a function'); - } - if (!IsExtensible(F) || has(F, 'name')) { - throw new $TypeError('Assertion failed: `F` must be extensible, and must not have a `name` own property'); - } - var nameType = Type(name); - if (nameType !== 'Symbol' && nameType !== 'String') { - throw new $TypeError('Assertion failed: `name` must be a Symbol or a String'); - } - if (nameType === 'Symbol') { - var description = getSymbolDescription(name); - // eslint-disable-next-line no-param-reassign - name = typeof description === 'undefined' ? '' : '[' + description + ']'; - } - if (arguments.length > 2) { - var prefix = arguments[2]; - // eslint-disable-next-line no-param-reassign - name = prefix + ' ' + name; - } - return DefinePropertyOrThrow(F, 'name', { - '[[Value]]': name, - '[[Writable]]': false, - '[[Enumerable]]': false, - '[[Configurable]]': true - }); -}; diff --git a/node_modules/es-abstract/2018/SetIntegrityLevel.js b/node_modules/es-abstract/2018/SetIntegrityLevel.js deleted file mode 100644 index 3d5c81d..0000000 --- a/node_modules/es-abstract/2018/SetIntegrityLevel.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); -var $preventExtensions = GetIntrinsic('%Object.preventExtensions%'); -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); - -var forEach = require('../helpers/forEach'); - -var DefinePropertyOrThrow = require('./DefinePropertyOrThrow'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-setintegritylevel - -module.exports = function SetIntegrityLevel(O, level) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (level !== 'sealed' && level !== 'frozen') { - throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); - } - if (!$preventExtensions) { - throw new $SyntaxError('SetIntegrityLevel requires native `Object.preventExtensions` support'); - } - var status = $preventExtensions(O); - if (!status) { - return false; - } - if (!$gOPN) { - throw new $SyntaxError('SetIntegrityLevel requires native `Object.getOwnPropertyNames` support'); - } - var theKeys = $gOPN(O); - if (level === 'sealed') { - forEach(theKeys, function (k) { - DefinePropertyOrThrow(O, k, { configurable: false }); - }); - } else if (level === 'frozen') { - forEach(theKeys, function (k) { - var currentDesc = $gOPD(O, k); - if (typeof currentDesc !== 'undefined') { - var desc; - if (IsAccessorDescriptor(ToPropertyDescriptor(currentDesc))) { - desc = { configurable: false }; - } else { - desc = { configurable: false, writable: false }; - } - DefinePropertyOrThrow(O, k, desc); - } - }); - } - return true; -}; diff --git a/node_modules/es-abstract/2018/SpeciesConstructor.js b/node_modules/es-abstract/2018/SpeciesConstructor.js deleted file mode 100644 index 3cdcd74..0000000 --- a/node_modules/es-abstract/2018/SpeciesConstructor.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $species = GetIntrinsic('%Symbol.species%', true); -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsConstructor = require('./IsConstructor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-speciesconstructor - -module.exports = function SpeciesConstructor(O, defaultConstructor) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - var C = O.constructor; - if (typeof C === 'undefined') { - return defaultConstructor; - } - if (Type(C) !== 'Object') { - throw new $TypeError('O.constructor is not an Object'); - } - var S = $species ? C[$species] : void 0; - if (S == null) { - return defaultConstructor; - } - if (IsConstructor(S)) { - return S; - } - throw new $TypeError('no constructor found'); -}; diff --git a/node_modules/es-abstract/2018/StrictEqualityComparison.js b/node_modules/es-abstract/2018/StrictEqualityComparison.js deleted file mode 100644 index eea5df3..0000000 --- a/node_modules/es-abstract/2018/StrictEqualityComparison.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6 - -module.exports = function StrictEqualityComparison(x, y) { - var xType = Type(x); - var yType = Type(y); - if (xType !== yType) { - return false; - } - if (xType === 'Undefined' || xType === 'Null') { - return true; - } - return x === y; // shortcut for steps 4-7 -}; diff --git a/node_modules/es-abstract/2018/SymbolDescriptiveString.js b/node_modules/es-abstract/2018/SymbolDescriptiveString.js deleted file mode 100644 index 7bd8191..0000000 --- a/node_modules/es-abstract/2018/SymbolDescriptiveString.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $SymbolToString = callBound('Symbol.prototype.toString', true); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-symboldescriptivestring - -module.exports = function SymbolDescriptiveString(sym) { - if (Type(sym) !== 'Symbol') { - throw new $TypeError('Assertion failed: `sym` must be a Symbol'); - } - return $SymbolToString(sym); -}; diff --git a/node_modules/es-abstract/2018/TestIntegrityLevel.js b/node_modules/es-abstract/2018/TestIntegrityLevel.js deleted file mode 100644 index 7a57397..0000000 --- a/node_modules/es-abstract/2018/TestIntegrityLevel.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var every = require('../helpers/every'); - -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-testintegritylevel - -module.exports = function TestIntegrityLevel(O, level) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (level !== 'sealed' && level !== 'frozen') { - throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); - } - var status = IsExtensible(O); - if (status) { - return false; - } - var theKeys = $gOPN(O); - return theKeys.length === 0 || every(theKeys, function (k) { - var currentDesc = $gOPD(O, k); - if (typeof currentDesc !== 'undefined') { - if (currentDesc.configurable) { - return false; - } - if (level === 'frozen' && IsDataDescriptor(ToPropertyDescriptor(currentDesc)) && currentDesc.writable) { - return false; - } - } - return true; - }); -}; diff --git a/node_modules/es-abstract/2018/TimeClip.js b/node_modules/es-abstract/2018/TimeClip.js deleted file mode 100644 index 57aa08c..0000000 --- a/node_modules/es-abstract/2018/TimeClip.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Date = GetIntrinsic('%Date%'); -var $Number = GetIntrinsic('%Number%'); -var $abs = GetIntrinsic('%Math.abs%'); - -var $isFinite = require('../helpers/isFinite'); - -var ToNumber = require('./ToNumber'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.14 - -module.exports = function TimeClip(time) { - if (!$isFinite(time) || $abs(time) > 8.64e15) { - return NaN; - } - return $Number(new $Date(ToNumber(time))); -}; - diff --git a/node_modules/es-abstract/2018/TimeFromYear.js b/node_modules/es-abstract/2018/TimeFromYear.js deleted file mode 100644 index df646c3..0000000 --- a/node_modules/es-abstract/2018/TimeFromYear.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var msPerDay = require('../helpers/timeConstants').msPerDay; - -var DayFromYear = require('./DayFromYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function TimeFromYear(y) { - return msPerDay * DayFromYear(y); -}; diff --git a/node_modules/es-abstract/2018/TimeString.js b/node_modules/es-abstract/2018/TimeString.js deleted file mode 100644 index 87642eb..0000000 --- a/node_modules/es-abstract/2018/TimeString.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $isNaN = require('../helpers/isNaN'); -var padTimeComponent = require('../helpers/padTimeComponent'); - -var HourFromTime = require('./HourFromTime'); -var MinFromTime = require('./MinFromTime'); -var SecFromTime = require('./SecFromTime'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/9.0/#sec-timestring - -module.exports = function TimeString(tv) { - if (Type(tv) !== 'Number' || $isNaN(tv)) { - throw new $TypeError('Assertion failed: `tv` must be a non-NaN Number'); - } - var hour = HourFromTime(tv); - var minute = MinFromTime(tv); - var second = SecFromTime(tv); - return padTimeComponent(hour) + ':' + padTimeComponent(minute) + ':' + padTimeComponent(second) + '\x20GMT'; -}; diff --git a/node_modules/es-abstract/2018/TimeWithinDay.js b/node_modules/es-abstract/2018/TimeWithinDay.js deleted file mode 100644 index c5b21d3..0000000 --- a/node_modules/es-abstract/2018/TimeWithinDay.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - -module.exports = function TimeWithinDay(t) { - return mod(t, msPerDay); -}; - diff --git a/node_modules/es-abstract/2018/ToBoolean.js b/node_modules/es-abstract/2018/ToBoolean.js deleted file mode 100644 index 65d8737..0000000 --- a/node_modules/es-abstract/2018/ToBoolean.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.2 - -module.exports = function ToBoolean(value) { return !!value; }; diff --git a/node_modules/es-abstract/2018/ToDateString.js b/node_modules/es-abstract/2018/ToDateString.js deleted file mode 100644 index 7a6d4c4..0000000 --- a/node_modules/es-abstract/2018/ToDateString.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $Date = GetIntrinsic('%Date%'); - -var $isNaN = require('../helpers/isNaN'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-todatestring - -module.exports = function ToDateString(tv) { - if (Type(tv) !== 'Number') { - throw new $TypeError('Assertion failed: `tv` must be a Number'); - } - if ($isNaN(tv)) { - return 'Invalid Date'; - } - return $Date(tv); -}; diff --git a/node_modules/es-abstract/2018/ToIndex.js b/node_modules/es-abstract/2018/ToIndex.js deleted file mode 100644 index a55398d..0000000 --- a/node_modules/es-abstract/2018/ToIndex.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $RangeError = GetIntrinsic('%RangeError%'); - -var ToInteger = require('./ToInteger'); -var ToLength = require('./ToLength'); -var SameValueZero = require('./SameValueZero'); - -// https://www.ecma-international.org/ecma-262/8.0/#sec-toindex - -module.exports = function ToIndex(value) { - if (typeof value === 'undefined') { - return 0; - } - var integerIndex = ToInteger(value); - if (integerIndex < 0) { - throw new $RangeError('index must be >= 0'); - } - var index = ToLength(integerIndex); - if (!SameValueZero(integerIndex, index)) { - throw new $RangeError('index must be >= 0 and < 2 ** 53 - 1'); - } - return index; -}; diff --git a/node_modules/es-abstract/2018/ToInt16.js b/node_modules/es-abstract/2018/ToInt16.js deleted file mode 100644 index 5a112c2..0000000 --- a/node_modules/es-abstract/2018/ToInt16.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var ToUint16 = require('./ToUint16'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toint16 - -module.exports = function ToInt16(argument) { - var int16bit = ToUint16(argument); - return int16bit >= 0x8000 ? int16bit - 0x10000 : int16bit; -}; diff --git a/node_modules/es-abstract/2018/ToInt32.js b/node_modules/es-abstract/2018/ToInt32.js deleted file mode 100644 index a8d2680..0000000 --- a/node_modules/es-abstract/2018/ToInt32.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.5 - -module.exports = function ToInt32(x) { - return ToNumber(x) >> 0; -}; diff --git a/node_modules/es-abstract/2018/ToInt8.js b/node_modules/es-abstract/2018/ToInt8.js deleted file mode 100644 index d103123..0000000 --- a/node_modules/es-abstract/2018/ToInt8.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var ToUint8 = require('./ToUint8'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toint8 - -module.exports = function ToInt8(argument) { - var int8bit = ToUint8(argument); - return int8bit >= 0x80 ? int8bit - 0x100 : int8bit; -}; diff --git a/node_modules/es-abstract/2018/ToInteger.js b/node_modules/es-abstract/2018/ToInteger.js deleted file mode 100644 index 16f7db9..0000000 --- a/node_modules/es-abstract/2018/ToInteger.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var ES5ToInteger = require('../5/ToInteger'); - -var ToNumber = require('./ToNumber'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tointeger - -module.exports = function ToInteger(value) { - var number = ToNumber(value); - return ES5ToInteger(number); -}; diff --git a/node_modules/es-abstract/2018/ToLength.js b/node_modules/es-abstract/2018/ToLength.js deleted file mode 100644 index 1bef9be..0000000 --- a/node_modules/es-abstract/2018/ToLength.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger'); - -var ToInteger = require('./ToInteger'); - -module.exports = function ToLength(argument) { - var len = ToInteger(argument); - if (len <= 0) { return 0; } // includes converting -0 to +0 - if (len > MAX_SAFE_INTEGER) { return MAX_SAFE_INTEGER; } - return len; -}; diff --git a/node_modules/es-abstract/2018/ToNumber.js b/node_modules/es-abstract/2018/ToNumber.js deleted file mode 100644 index 7a3cdc8..0000000 --- a/node_modules/es-abstract/2018/ToNumber.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $Number = GetIntrinsic('%Number%'); -var $RegExp = GetIntrinsic('%RegExp%'); -var $parseInteger = GetIntrinsic('%parseInt%'); - -var callBound = require('../helpers/callBound'); -var regexTester = require('../helpers/regexTester'); -var isPrimitive = require('../helpers/isPrimitive'); - -var $strSlice = callBound('String.prototype.slice'); -var isBinary = regexTester(/^0b[01]+$/i); -var isOctal = regexTester(/^0o[0-7]+$/i); -var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i); -var nonWS = ['\u0085', '\u200b', '\ufffe'].join(''); -var nonWSregex = new $RegExp('[' + nonWS + ']', 'g'); -var hasNonWS = regexTester(nonWSregex); - -// whitespace from: https://es5.github.io/#x15.5.4.20 -// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 -var ws = [ - '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', - '\u2029\uFEFF' -].join(''); -var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g'); -var $replace = callBound('String.prototype.replace'); -var $trim = function (value) { - return $replace(value, trimRegex, ''); -}; - -var ToPrimitive = require('./ToPrimitive'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tonumber - -module.exports = function ToNumber(argument) { - var value = isPrimitive(argument) ? argument : ToPrimitive(argument, $Number); - if (typeof value === 'symbol') { - throw new $TypeError('Cannot convert a Symbol value to a number'); - } - if (typeof value === 'string') { - if (isBinary(value)) { - return ToNumber($parseInteger($strSlice(value, 2), 2)); - } else if (isOctal(value)) { - return ToNumber($parseInteger($strSlice(value, 2), 8)); - } else if (hasNonWS(value) || isInvalidHexLiteral(value)) { - return NaN; - } else { - var trimmed = $trim(value); - if (trimmed !== value) { - return ToNumber(trimmed); - } - } - } - return $Number(value); -}; diff --git a/node_modules/es-abstract/2018/ToObject.js b/node_modules/es-abstract/2018/ToObject.js deleted file mode 100644 index 50d5b94..0000000 --- a/node_modules/es-abstract/2018/ToObject.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Object = GetIntrinsic('%Object%'); - -var RequireObjectCoercible = require('./RequireObjectCoercible'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toobject - -module.exports = function ToObject(value) { - RequireObjectCoercible(value); - return $Object(value); -}; diff --git a/node_modules/es-abstract/2018/ToPrimitive.js b/node_modules/es-abstract/2018/ToPrimitive.js deleted file mode 100644 index 81c655d..0000000 --- a/node_modules/es-abstract/2018/ToPrimitive.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var toPrimitive = require('es-to-primitive/es2015'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive - -module.exports = function ToPrimitive(input) { - if (arguments.length > 1) { - return toPrimitive(input, arguments[1]); - } - return toPrimitive(input); -}; diff --git a/node_modules/es-abstract/2018/ToPropertyDescriptor.js b/node_modules/es-abstract/2018/ToPropertyDescriptor.js deleted file mode 100644 index 38e536e..0000000 --- a/node_modules/es-abstract/2018/ToPropertyDescriptor.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -var has = require('has'); - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Type = require('./Type'); -var ToBoolean = require('./ToBoolean'); -var IsCallable = require('./IsCallable'); - -// https://ecma-international.org/ecma-262/5.1/#sec-8.10.5 - -module.exports = function ToPropertyDescriptor(Obj) { - if (Type(Obj) !== 'Object') { - throw new $TypeError('ToPropertyDescriptor requires an object'); - } - - var desc = {}; - if (has(Obj, 'enumerable')) { - desc['[[Enumerable]]'] = ToBoolean(Obj.enumerable); - } - if (has(Obj, 'configurable')) { - desc['[[Configurable]]'] = ToBoolean(Obj.configurable); - } - if (has(Obj, 'value')) { - desc['[[Value]]'] = Obj.value; - } - if (has(Obj, 'writable')) { - desc['[[Writable]]'] = ToBoolean(Obj.writable); - } - if (has(Obj, 'get')) { - var getter = Obj.get; - if (typeof getter !== 'undefined' && !IsCallable(getter)) { - throw new TypeError('getter must be a function'); - } - desc['[[Get]]'] = getter; - } - if (has(Obj, 'set')) { - var setter = Obj.set; - if (typeof setter !== 'undefined' && !IsCallable(setter)) { - throw new $TypeError('setter must be a function'); - } - desc['[[Set]]'] = setter; - } - - if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) { - throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute'); - } - return desc; -}; diff --git a/node_modules/es-abstract/2018/ToPropertyKey.js b/node_modules/es-abstract/2018/ToPropertyKey.js deleted file mode 100644 index 38f40dd..0000000 --- a/node_modules/es-abstract/2018/ToPropertyKey.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $String = GetIntrinsic('%String%'); - -var ToPrimitive = require('./ToPrimitive'); -var ToString = require('./ToString'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-topropertykey - -module.exports = function ToPropertyKey(argument) { - var key = ToPrimitive(argument, $String); - return typeof key === 'symbol' ? key : ToString(key); -}; diff --git a/node_modules/es-abstract/2018/ToString.js b/node_modules/es-abstract/2018/ToString.js deleted file mode 100644 index a345431..0000000 --- a/node_modules/es-abstract/2018/ToString.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $String = GetIntrinsic('%String%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tostring - -module.exports = function ToString(argument) { - if (typeof argument === 'symbol') { - throw new $TypeError('Cannot convert a Symbol value to a string'); - } - return $String(argument); -}; diff --git a/node_modules/es-abstract/2018/ToUint16.js b/node_modules/es-abstract/2018/ToUint16.js deleted file mode 100644 index c8a408b..0000000 --- a/node_modules/es-abstract/2018/ToUint16.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var $sign = require('../helpers/sign'); -var $mod = require('../helpers/mod'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.7 - -module.exports = function ToUint16(value) { - var number = ToNumber(value); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = $sign(number) * $floor($abs(number)); - return $mod(posInt, 0x10000); -}; diff --git a/node_modules/es-abstract/2018/ToUint32.js b/node_modules/es-abstract/2018/ToUint32.js deleted file mode 100644 index 3660f62..0000000 --- a/node_modules/es-abstract/2018/ToUint32.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.6 - -module.exports = function ToUint32(x) { - return ToNumber(x) >>> 0; -}; diff --git a/node_modules/es-abstract/2018/ToUint8.js b/node_modules/es-abstract/2018/ToUint8.js deleted file mode 100644 index bf84753..0000000 --- a/node_modules/es-abstract/2018/ToUint8.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var $sign = require('../helpers/sign'); -var $mod = require('../helpers/mod'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -module.exports = function ToUint8(argument) { - var number = ToNumber(argument); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = $sign(number) * $floor($abs(number)); - return $mod(posInt, 0x100); -}; diff --git a/node_modules/es-abstract/2018/ToUint8Clamp.js b/node_modules/es-abstract/2018/ToUint8Clamp.js deleted file mode 100644 index c7f9f56..0000000 --- a/node_modules/es-abstract/2018/ToUint8Clamp.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); - -var $floor = $Math.floor; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-touint8clamp - -module.exports = function ToUint8Clamp(argument) { - var number = ToNumber(argument); - if ($isNaN(number) || number <= 0) { return 0; } - if (number >= 0xFF) { return 0xFF; } - var f = $floor(argument); - if (f + 0.5 < number) { return f + 1; } - if (number < f + 0.5) { return f; } - if (f % 2 !== 0) { return f + 1; } - return f; -}; diff --git a/node_modules/es-abstract/2018/Type.js b/node_modules/es-abstract/2018/Type.js deleted file mode 100644 index 6c99376..0000000 --- a/node_modules/es-abstract/2018/Type.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var ES5Type = require('../5/Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tostring - -module.exports = function Type(x) { - if (typeof x === 'symbol') { - return 'Symbol'; - } - return ES5Type(x); -}; diff --git a/node_modules/es-abstract/2018/ValidateAndApplyPropertyDescriptor.js b/node_modules/es-abstract/2018/ValidateAndApplyPropertyDescriptor.js deleted file mode 100644 index d4b9007..0000000 --- a/node_modules/es-abstract/2018/ValidateAndApplyPropertyDescriptor.js +++ /dev/null @@ -1,170 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); -var isSamePropertyDescriptor = require('../helpers/isSamePropertyDescriptor'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsGenericDescriptor = require('./IsGenericDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-validateandapplypropertydescriptor -// https://www.ecma-international.org/ecma-262/8.0/#sec-validateandapplypropertydescriptor - -// eslint-disable-next-line max-lines-per-function, max-statements, max-params -module.exports = function ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current) { - // this uses the ES2017+ logic, since it fixes a number of bugs in the ES2015 logic. - var oType = Type(O); - if (oType !== 'Undefined' && oType !== 'Object') { - throw new $TypeError('Assertion failed: O must be undefined or an Object'); - } - if (Type(extensible) !== 'Boolean') { - throw new $TypeError('Assertion failed: extensible must be a Boolean'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (Type(current) !== 'Undefined' && !isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, current)) { - throw new $TypeError('Assertion failed: current must be a Property Descriptor, or undefined'); - } - if (oType !== 'Undefined' && !IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: if O is not undefined, P must be a Property Key'); - } - if (Type(current) === 'Undefined') { - if (!extensible) { - return false; - } - if (IsGenericDescriptor(Desc) || IsDataDescriptor(Desc)) { - if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': Desc['[[Configurable]]'], - '[[Enumerable]]': Desc['[[Enumerable]]'], - '[[Value]]': Desc['[[Value]]'], - '[[Writable]]': Desc['[[Writable]]'] - } - ); - } - } else { - if (!IsAccessorDescriptor(Desc)) { - throw new $TypeError('Assertion failed: Desc is not an accessor descriptor'); - } - if (oType !== 'Undefined') { - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); - } - } - return true; - } - if (IsGenericDescriptor(Desc) && !('[[Configurable]]' in Desc) && !('[[Enumerable]]' in Desc)) { - return true; - } - if (isSamePropertyDescriptor({ SameValue: SameValue }, Desc, current)) { - return true; // removed by ES2017, but should still be correct - } - // "if every field in Desc is absent, return true" can't really match the assertion that it's a Property Descriptor - if (!current['[[Configurable]]']) { - if (Desc['[[Configurable]]']) { - return false; - } - if ('[[Enumerable]]' in Desc && !Desc['[[Enumerable]]'] === !!current['[[Enumerable]]']) { - return false; - } - } - if (IsGenericDescriptor(Desc)) { - // no further validation is required. - } else if (IsDataDescriptor(current) !== IsDataDescriptor(Desc)) { - if (!current['[[Configurable]]']) { - return false; - } - if (IsDataDescriptor(current)) { - if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': current['[[Configurable]]'], - '[[Enumerable]]': current['[[Enumerable]]'], - '[[Get]]': undefined - } - ); - } - } else if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': current['[[Configurable]]'], - '[[Enumerable]]': current['[[Enumerable]]'], - '[[Value]]': undefined - } - ); - } - } else if (IsDataDescriptor(current) && IsDataDescriptor(Desc)) { - if (!current['[[Configurable]]'] && !current['[[Writable]]']) { - if ('[[Writable]]' in Desc && Desc['[[Writable]]']) { - return false; - } - if ('[[Value]]' in Desc && !SameValue(Desc['[[Value]]'], current['[[Value]]'])) { - return false; - } - return true; - } - } else if (IsAccessorDescriptor(current) && IsAccessorDescriptor(Desc)) { - if (!current['[[Configurable]]']) { - if ('[[Set]]' in Desc && !SameValue(Desc['[[Set]]'], current['[[Set]]'])) { - return false; - } - if ('[[Get]]' in Desc && !SameValue(Desc['[[Get]]'], current['[[Get]]'])) { - return false; - } - return true; - } - } else { - throw new $TypeError('Assertion failed: current and Desc are not both data, both accessors, or one accessor and one data.'); - } - if (oType !== 'Undefined') { - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); - } - return true; -}; diff --git a/node_modules/es-abstract/2018/WeekDay.js b/node_modules/es-abstract/2018/WeekDay.js deleted file mode 100644 index 2973e02..0000000 --- a/node_modules/es-abstract/2018/WeekDay.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -var Day = require('./Day'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.6 - -module.exports = function WeekDay(t) { - return mod(Day(t) + 4, 7); -}; diff --git a/node_modules/es-abstract/2018/YearFromTime.js b/node_modules/es-abstract/2018/YearFromTime.js deleted file mode 100644 index ff5339f..0000000 --- a/node_modules/es-abstract/2018/YearFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Date = GetIntrinsic('%Date%'); - -var callBound = require('../helpers/callBound'); - -var $getUTCFullYear = callBound('Date.prototype.getUTCFullYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function YearFromTime(t) { - // largest y such that this.TimeFromYear(y) <= t - return $getUTCFullYear(new $Date(t)); -}; diff --git a/node_modules/es-abstract/2018/modulo.js b/node_modules/es-abstract/2018/modulo.js deleted file mode 100644 index bc04c06..0000000 --- a/node_modules/es-abstract/2018/modulo.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -// https://ecma-international.org/ecma-262/5.1/#sec-5.2 - -module.exports = function modulo(x, y) { - return mod(x, y); -}; diff --git a/node_modules/es-abstract/2018/msFromTime.js b/node_modules/es-abstract/2018/msFromTime.js deleted file mode 100644 index c31eda0..0000000 --- a/node_modules/es-abstract/2018/msFromTime.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); -var msPerSecond = require('../helpers/timeConstants').msPerSecond; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function msFromTime(t) { - return mod(t, msPerSecond); -}; diff --git a/node_modules/es-abstract/2018/thisBooleanValue.js b/node_modules/es-abstract/2018/thisBooleanValue.js deleted file mode 100644 index 3ffac9c..0000000 --- a/node_modules/es-abstract/2018/thisBooleanValue.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var $BooleanValueOf = require('../helpers/callBound')('Boolean.prototype.valueOf'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-boolean-prototype-object - -module.exports = function thisBooleanValue(value) { - if (Type(value) === 'Boolean') { - return value; - } - - return $BooleanValueOf(value); -}; diff --git a/node_modules/es-abstract/2018/thisNumberValue.js b/node_modules/es-abstract/2018/thisNumberValue.js deleted file mode 100644 index 0345e52..0000000 --- a/node_modules/es-abstract/2018/thisNumberValue.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var Type = require('./Type'); - -var $NumberValueOf = callBound('Number.prototype.valueOf'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-number-prototype-object - -module.exports = function thisNumberValue(value) { - if (Type(value) === 'Number') { - return value; - } - - return $NumberValueOf(value); -}; - diff --git a/node_modules/es-abstract/2018/thisStringValue.js b/node_modules/es-abstract/2018/thisStringValue.js deleted file mode 100644 index 3b99b6e..0000000 --- a/node_modules/es-abstract/2018/thisStringValue.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var $StringValueOf = require('../helpers/callBound')('String.prototype.valueOf'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-string-prototype-object - -module.exports = function thisStringValue(value) { - if (Type(value) === 'String') { - return value; - } - - return $StringValueOf(value); -}; diff --git a/node_modules/es-abstract/2018/thisSymbolValue.js b/node_modules/es-abstract/2018/thisSymbolValue.js deleted file mode 100644 index 3c3b347..0000000 --- a/node_modules/es-abstract/2018/thisSymbolValue.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var $SymbolValueOf = callBound('Symbol.prototype.valueOf', true); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/9.0/#sec-thissymbolvalue - -module.exports = function thisSymbolValue(value) { - if (!$SymbolValueOf) { - throw new SyntaxError('Symbols are not supported; thisSymbolValue requires that `value` be a Symbol or a Symbol object'); - } - if (Type(value) === 'Symbol') { - return value; - } - return $SymbolValueOf(value); -}; diff --git a/node_modules/es-abstract/2018/thisTimeValue.js b/node_modules/es-abstract/2018/thisTimeValue.js deleted file mode 100644 index d7cda28..0000000 --- a/node_modules/es-abstract/2018/thisTimeValue.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var $DateValueOf = require('../helpers/callBound')('Date.prototype.valueOf'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-date-prototype-object - -module.exports = function thisTimeValue(value) { - return $DateValueOf(value); -}; diff --git a/node_modules/es-abstract/2019/AbstractEqualityComparison.js b/node_modules/es-abstract/2019/AbstractEqualityComparison.js deleted file mode 100644 index 40b3909..0000000 --- a/node_modules/es-abstract/2019/AbstractEqualityComparison.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); -var ToPrimitive = require('./ToPrimitive'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison - -module.exports = function AbstractEqualityComparison(x, y) { - var xType = Type(x); - var yType = Type(y); - if (xType === yType) { - return x === y; // ES6+ specified this shortcut anyways. - } - if (x == null && y == null) { - return true; - } - if (xType === 'Number' && yType === 'String') { - return AbstractEqualityComparison(x, ToNumber(y)); - } - if (xType === 'String' && yType === 'Number') { - return AbstractEqualityComparison(ToNumber(x), y); - } - if (xType === 'Boolean') { - return AbstractEqualityComparison(ToNumber(x), y); - } - if (yType === 'Boolean') { - return AbstractEqualityComparison(x, ToNumber(y)); - } - if ((xType === 'String' || xType === 'Number' || xType === 'Symbol') && yType === 'Object') { - return AbstractEqualityComparison(x, ToPrimitive(y)); - } - if (xType === 'Object' && (yType === 'String' || yType === 'Number' || yType === 'Symbol')) { - return AbstractEqualityComparison(ToPrimitive(x), y); - } - return false; -}; diff --git a/node_modules/es-abstract/2019/AbstractRelationalComparison.js b/node_modules/es-abstract/2019/AbstractRelationalComparison.js deleted file mode 100644 index bc7ca83..0000000 --- a/node_modules/es-abstract/2019/AbstractRelationalComparison.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Number = GetIntrinsic('%Number%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var isPrefixOf = require('../helpers/isPrefixOf'); - -var ToNumber = require('./ToNumber'); -var ToPrimitive = require('./ToPrimitive'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5 - -// eslint-disable-next-line max-statements -module.exports = function AbstractRelationalComparison(x, y, LeftFirst) { - if (Type(LeftFirst) !== 'Boolean') { - throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean'); - } - var px; - var py; - if (LeftFirst) { - px = ToPrimitive(x, $Number); - py = ToPrimitive(y, $Number); - } else { - py = ToPrimitive(y, $Number); - px = ToPrimitive(x, $Number); - } - var bothStrings = Type(px) === 'String' && Type(py) === 'String'; - if (!bothStrings) { - var nx = ToNumber(px); - var ny = ToNumber(py); - if ($isNaN(nx) || $isNaN(ny)) { - return undefined; - } - if ($isFinite(nx) && $isFinite(ny) && nx === ny) { - return false; - } - if (nx === 0 && ny === 0) { - return false; - } - if (nx === Infinity) { - return false; - } - if (ny === Infinity) { - return true; - } - if (ny === -Infinity) { - return false; - } - if (nx === -Infinity) { - return true; - } - return nx < ny; // by now, these are both nonzero, finite, and not equal - } - if (isPrefixOf(py, px)) { - return false; - } - if (isPrefixOf(px, py)) { - return true; - } - return px < py; // both strings, neither a prefix of the other. shortcut for steps c-f -}; diff --git a/node_modules/es-abstract/2019/AddEntriesFromIterable.js b/node_modules/es-abstract/2019/AddEntriesFromIterable.js deleted file mode 100644 index 5aed447..0000000 --- a/node_modules/es-abstract/2019/AddEntriesFromIterable.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -var inspect = require('object-inspect'); - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Call = require('./Call'); -var Get = require('./Get'); -var GetIterator = require('./GetIterator'); -var IsCallable = require('./IsCallable'); -var IteratorClose = require('./IteratorClose'); -var IteratorStep = require('./IteratorStep'); -var IteratorValue = require('./IteratorValue'); -var Type = require('./Type'); - -// https://tc39.es/ecma262/#sec-add-entries-from-iterable - -module.exports = function AddEntriesFromIterable(target, iterable, adder) { - if (!IsCallable(adder)) { - throw new $TypeError('Assertion failed: `adder` is not callable'); - } - if (iterable == null) { - throw new $TypeError('Assertion failed: `iterable` is present, and not nullish'); - } - var iteratorRecord = GetIterator(iterable); - while (true) { // eslint-disable-line no-constant-condition - var next = IteratorStep(iteratorRecord); - if (!next) { - return target; - } - var nextItem = IteratorValue(next); - if (Type(nextItem) !== 'Object') { - var error = new $TypeError('iterator next must return an Object, got ' + inspect(nextItem)); - return IteratorClose( - iteratorRecord, - function () { throw error; } // eslint-disable-line no-loop-func - ); - } - try { - var k = Get(nextItem, '0'); - var v = Get(nextItem, '1'); - Call(adder, target, [k, v]); - } catch (e) { - return IteratorClose( - iteratorRecord, - function () { throw e; } - ); - } - } -}; diff --git a/node_modules/es-abstract/2019/AdvanceStringIndex.js b/node_modules/es-abstract/2019/AdvanceStringIndex.js deleted file mode 100644 index 666f578..0000000 --- a/node_modules/es-abstract/2019/AdvanceStringIndex.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var IsInteger = require('./IsInteger'); -var Type = require('./Type'); - -var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $charCodeAt = require('../helpers/callBound')('String.prototype.charCodeAt'); - -// https://ecma-international.org/ecma-262/6.0/#sec-advancestringindex - -module.exports = function AdvanceStringIndex(S, index, unicode) { - if (Type(S) !== 'String') { - throw new $TypeError('Assertion failed: `S` must be a String'); - } - if (!IsInteger(index) || index < 0 || index > MAX_SAFE_INTEGER) { - throw new $TypeError('Assertion failed: `length` must be an integer >= 0 and <= 2**53'); - } - if (Type(unicode) !== 'Boolean') { - throw new $TypeError('Assertion failed: `unicode` must be a Boolean'); - } - if (!unicode) { - return index + 1; - } - var length = S.length; - if ((index + 1) >= length) { - return index + 1; - } - - var first = $charCodeAt(S, index); - if (first < 0xD800 || first > 0xDBFF) { - return index + 1; - } - - var second = $charCodeAt(S, index + 1); - if (second < 0xDC00 || second > 0xDFFF) { - return index + 1; - } - - return index + 2; -}; diff --git a/node_modules/es-abstract/2019/ArrayCreate.js b/node_modules/es-abstract/2019/ArrayCreate.js deleted file mode 100644 index fc9a7cf..0000000 --- a/node_modules/es-abstract/2019/ArrayCreate.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $ArrayPrototype = GetIntrinsic('%Array.prototype%'); -var $RangeError = GetIntrinsic('%RangeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsInteger = require('./IsInteger'); - -var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1; - -var $setProto = GetIntrinsic('%Object.setPrototypeOf%', true) || ( - // eslint-disable-next-line no-proto, no-negated-condition - [].__proto__ !== $ArrayPrototype - ? null - : function (O, proto) { - O.__proto__ = proto; // eslint-disable-line no-proto, no-param-reassign - return O; - } -); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-arraycreate - -module.exports = function ArrayCreate(length) { - if (!IsInteger(length) || length < 0) { - throw new $TypeError('Assertion failed: `length` must be an integer Number >= 0'); - } - if (length > MAX_ARRAY_LENGTH) { - throw new $RangeError('length is greater than (2**32 - 1)'); - } - var proto = arguments.length > 1 ? arguments[1] : $ArrayPrototype; - var A = []; // steps 5 - 7, and 9 - if (proto !== $ArrayPrototype) { // step 8 - if (!$setProto) { - throw new $SyntaxError('ArrayCreate: a `proto` argument that is not `Array.prototype` is not supported in an environment that does not support setting the [[Prototype]]'); - } - $setProto(A, proto); - } - if (length !== 0) { // bypasses the need for step 2 - A.length = length; - } - /* step 10, the above as a shortcut for the below - OrdinaryDefineOwnProperty(A, 'length', { - '[[Configurable]]': false, - '[[Enumerable]]': false, - '[[Value]]': length, - '[[Writable]]': true - }); - */ - return A; -}; diff --git a/node_modules/es-abstract/2019/ArraySetLength.js b/node_modules/es-abstract/2019/ArraySetLength.js deleted file mode 100644 index c9134c6..0000000 --- a/node_modules/es-abstract/2019/ArraySetLength.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $RangeError = GetIntrinsic('%RangeError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var assign = require('object.assign'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var IsArray = require('./IsArray'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var OrdinaryDefineOwnProperty = require('./OrdinaryDefineOwnProperty'); -var OrdinaryGetOwnProperty = require('./OrdinaryGetOwnProperty'); -var ToNumber = require('./ToNumber'); -var ToString = require('./ToString'); -var ToUint32 = require('./ToUint32'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-arraysetlength - -// eslint-disable-next-line max-statements, max-lines-per-function -module.exports = function ArraySetLength(A, Desc) { - if (!IsArray(A)) { - throw new $TypeError('Assertion failed: A must be an Array'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (!('[[Value]]' in Desc)) { - return OrdinaryDefineOwnProperty(A, 'length', Desc); - } - var newLenDesc = assign({}, Desc); - var newLen = ToUint32(Desc['[[Value]]']); - var numberLen = ToNumber(Desc['[[Value]]']); - if (newLen !== numberLen) { - throw new $RangeError('Invalid array length'); - } - newLenDesc['[[Value]]'] = newLen; - var oldLenDesc = OrdinaryGetOwnProperty(A, 'length'); - if (!IsDataDescriptor(oldLenDesc)) { - throw new $TypeError('Assertion failed: an array had a non-data descriptor on `length`'); - } - var oldLen = oldLenDesc['[[Value]]']; - if (newLen >= oldLen) { - return OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - } - if (!oldLenDesc['[[Writable]]']) { - return false; - } - var newWritable; - if (!('[[Writable]]' in newLenDesc) || newLenDesc['[[Writable]]']) { - newWritable = true; - } else { - newWritable = false; - newLenDesc['[[Writable]]'] = true; - } - var succeeded = OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - if (!succeeded) { - return false; - } - while (newLen < oldLen) { - oldLen -= 1; - // eslint-disable-next-line no-param-reassign - var deleteSucceeded = delete A[ToString(oldLen)]; - if (!deleteSucceeded) { - newLenDesc['[[Value]]'] = oldLen + 1; - if (!newWritable) { - newLenDesc['[[Writable]]'] = false; - OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - return false; - } - } - } - if (!newWritable) { - return OrdinaryDefineOwnProperty(A, 'length', { '[[Writable]]': false }); - } - return true; -}; diff --git a/node_modules/es-abstract/2019/ArraySpeciesCreate.js b/node_modules/es-abstract/2019/ArraySpeciesCreate.js deleted file mode 100644 index 98b9b56..0000000 --- a/node_modules/es-abstract/2019/ArraySpeciesCreate.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Array = GetIntrinsic('%Array%'); -var $species = GetIntrinsic('%Symbol.species%', true); -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var IsConstructor = require('./IsConstructor'); -var IsInteger = require('./IsInteger'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-arrayspeciescreate - -module.exports = function ArraySpeciesCreate(originalArray, length) { - if (!IsInteger(length) || length < 0) { - throw new $TypeError('Assertion failed: length must be an integer >= 0'); - } - var len = length === 0 ? 0 : length; - var C; - var isArray = IsArray(originalArray); - if (isArray) { - C = Get(originalArray, 'constructor'); - // TODO: figure out how to make a cross-realm normal Array, a same-realm Array - // if (IsConstructor(C)) { - // if C is another realm's Array, C = undefined - // Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Array))) === null ? - // } - if ($species && Type(C) === 'Object') { - C = Get(C, $species); - if (C === null) { - C = void 0; - } - } - } - if (typeof C === 'undefined') { - return $Array(len); - } - if (!IsConstructor(C)) { - throw new $TypeError('C must be a constructor'); - } - return new C(len); // Construct(C, len); -}; - diff --git a/node_modules/es-abstract/2019/Call.js b/node_modules/es-abstract/2019/Call.js deleted file mode 100644 index f31960d..0000000 --- a/node_modules/es-abstract/2019/Call.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var inspect = require('object-inspect'); - -var IsCallable = require('./IsCallable'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-call - -module.exports = function Call(F, V) { - var args = arguments.length > 2 ? arguments[2] : []; - if (!IsCallable(F)) { - throw new $TypeError(inspect(F) + ' is not a function'); - } - return F.apply(V, args); -}; diff --git a/node_modules/es-abstract/2019/CanonicalNumericIndexString.js b/node_modules/es-abstract/2019/CanonicalNumericIndexString.js deleted file mode 100644 index 625f853..0000000 --- a/node_modules/es-abstract/2019/CanonicalNumericIndexString.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var SameValue = require('./SameValue'); -var ToNumber = require('./ToNumber'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-canonicalnumericindexstring - -module.exports = function CanonicalNumericIndexString(argument) { - if (Type(argument) !== 'String') { - throw new $TypeError('Assertion failed: `argument` must be a String'); - } - if (argument === '-0') { return -0; } - var n = ToNumber(argument); - if (SameValue(ToString(n), argument)) { return n; } - return void 0; -}; diff --git a/node_modules/es-abstract/2019/CompletePropertyDescriptor.js b/node_modules/es-abstract/2019/CompletePropertyDescriptor.js deleted file mode 100644 index 548bf41..0000000 --- a/node_modules/es-abstract/2019/CompletePropertyDescriptor.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsGenericDescriptor = require('./IsGenericDescriptor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-completepropertydescriptor - -module.exports = function CompletePropertyDescriptor(Desc) { - /* eslint no-param-reassign: 0 */ - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (IsGenericDescriptor(Desc) || IsDataDescriptor(Desc)) { - if (!has(Desc, '[[Value]]')) { - Desc['[[Value]]'] = void 0; - } - if (!has(Desc, '[[Writable]]')) { - Desc['[[Writable]]'] = false; - } - } else { - if (!has(Desc, '[[Get]]')) { - Desc['[[Get]]'] = void 0; - } - if (!has(Desc, '[[Set]]')) { - Desc['[[Set]]'] = void 0; - } - } - if (!has(Desc, '[[Enumerable]]')) { - Desc['[[Enumerable]]'] = false; - } - if (!has(Desc, '[[Configurable]]')) { - Desc['[[Configurable]]'] = false; - } - return Desc; -}; diff --git a/node_modules/es-abstract/2019/CopyDataProperties.js b/node_modules/es-abstract/2019/CopyDataProperties.js deleted file mode 100644 index b75ba42..0000000 --- a/node_modules/es-abstract/2019/CopyDataProperties.js +++ /dev/null @@ -1,60 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); -var forEach = require('../helpers/forEach'); -var OwnPropertyKeys = require('../helpers/OwnPropertyKeys'); - -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); - -var IsArray = require('./IsArray'); -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/9.0/#sec-copydataproperties - -module.exports = function CopyDataProperties(target, source, excludedItems) { - if (Type(target) !== 'Object') { - throw new TypeError('Assertion failed: "target" must be an Object'); - } - - if (!IsArray(excludedItems)) { - throw new TypeError('Assertion failed: "excludedItems" must be a List of Property Keys'); - } - for (var i = 0; i < excludedItems.length; i += 1) { - if (!IsPropertyKey(excludedItems[i])) { - throw new TypeError('Assertion failed: "excludedItems" must be a List of Property Keys'); - } - } - - if (typeof source === 'undefined' || source === null) { - return target; - } - - var ES = this; - - var fromObj = ES.ToObject(source); - - var sourceKeys = OwnPropertyKeys(fromObj); - forEach(sourceKeys, function (nextKey) { - var excluded = false; - - forEach(excludedItems, function (e) { - if (ES.SameValue(e, nextKey) === true) { - excluded = true; - } - }); - - var enumerable = $isEnumerable(fromObj, nextKey) || ( - // this is to handle string keys being non-enumerable in older engines - typeof source === 'string' - && nextKey >= 0 - && ES.IsInteger(ES.ToNumber(nextKey)) - ); - if (excluded === false && enumerable) { - var propValue = ES.Get(fromObj, nextKey); - ES.CreateDataProperty(target, nextKey, propValue); - } - }); - - return target; -}; diff --git a/node_modules/es-abstract/2019/CreateDataProperty.js b/node_modules/es-abstract/2019/CreateDataProperty.js deleted file mode 100644 index 32a86ef..0000000 --- a/node_modules/es-abstract/2019/CreateDataProperty.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var OrdinaryGetOwnProperty = require('./OrdinaryGetOwnProperty'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createdataproperty - -module.exports = function CreateDataProperty(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - var oldDesc = OrdinaryGetOwnProperty(O, P); - var extensible = !oldDesc || IsExtensible(O); - var immutable = oldDesc && (!oldDesc['[[Writable]]'] || !oldDesc['[[Configurable]]']); - if (immutable || !extensible) { - return false; - } - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': true, - '[[Enumerable]]': true, - '[[Value]]': V, - '[[Writable]]': true - } - ); -}; diff --git a/node_modules/es-abstract/2019/CreateDataPropertyOrThrow.js b/node_modules/es-abstract/2019/CreateDataPropertyOrThrow.js deleted file mode 100644 index 9feaec8..0000000 --- a/node_modules/es-abstract/2019/CreateDataPropertyOrThrow.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var CreateDataProperty = require('./CreateDataProperty'); -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// // https://ecma-international.org/ecma-262/6.0/#sec-createdatapropertyorthrow - -module.exports = function CreateDataPropertyOrThrow(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - var success = CreateDataProperty(O, P, V); - if (!success) { - throw new $TypeError('unable to create data property'); - } - return success; -}; diff --git a/node_modules/es-abstract/2019/CreateHTML.js b/node_modules/es-abstract/2019/CreateHTML.js deleted file mode 100644 index 536c92d..0000000 --- a/node_modules/es-abstract/2019/CreateHTML.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $replace = callBound('String.prototype.replace'); - -var RequireObjectCoercible = require('./RequireObjectCoercible'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createhtml - -module.exports = function CreateHTML(string, tag, attribute, value) { - if (Type(tag) !== 'String' || Type(attribute) !== 'String') { - throw new $TypeError('Assertion failed: `tag` and `attribute` must be strings'); - } - var str = RequireObjectCoercible(string); - var S = ToString(str); - var p1 = '<' + tag; - if (attribute !== '') { - var V = ToString(value); - var escapedV = $replace(V, /\x22/g, '"'); - p1 += '\x20' + attribute + '\x3D\x22' + escapedV + '\x22'; - } - return p1 + '>' + S + ''; -}; diff --git a/node_modules/es-abstract/2019/CreateIterResultObject.js b/node_modules/es-abstract/2019/CreateIterResultObject.js deleted file mode 100644 index aef1d22..0000000 --- a/node_modules/es-abstract/2019/CreateIterResultObject.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-createiterresultobject - -module.exports = function CreateIterResultObject(value, done) { - if (Type(done) !== 'Boolean') { - throw new $TypeError('Assertion failed: Type(done) is not Boolean'); - } - return { - value: value, - done: done - }; -}; diff --git a/node_modules/es-abstract/2019/CreateListFromArrayLike.js b/node_modules/es-abstract/2019/CreateListFromArrayLike.js deleted file mode 100644 index d6b44b5..0000000 --- a/node_modules/es-abstract/2019/CreateListFromArrayLike.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var callBound = require('../helpers/callBound'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $indexOf = callBound('Array.prototype.indexOf', true) || callBound('String.prototype.indexOf'); -var $push = callBound('Array.prototype.push'); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var ToLength = require('./ToLength'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-createlistfromarraylike -module.exports = function CreateListFromArrayLike(obj) { - var elementTypes = arguments.length > 1 - ? arguments[1] - : ['Undefined', 'Null', 'Boolean', 'String', 'Symbol', 'Number', 'Object']; - - if (Type(obj) !== 'Object') { - throw new $TypeError('Assertion failed: `obj` must be an Object'); - } - if (!IsArray(elementTypes)) { - throw new $TypeError('Assertion failed: `elementTypes`, if provided, must be an array'); - } - var len = ToLength(Get(obj, 'length')); - var list = []; - var index = 0; - while (index < len) { - var indexName = ToString(index); - var next = Get(obj, indexName); - var nextType = Type(next); - if ($indexOf(elementTypes, nextType) < 0) { - throw new $TypeError('item type ' + nextType + ' is not a valid elementType'); - } - $push(list, next); - index += 1; - } - return list; -}; diff --git a/node_modules/es-abstract/2019/CreateMethodProperty.js b/node_modules/es-abstract/2019/CreateMethodProperty.js deleted file mode 100644 index 5b599ae..0000000 --- a/node_modules/es-abstract/2019/CreateMethodProperty.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-createmethodproperty - -module.exports = function CreateMethodProperty(O, P, V) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - var newDesc = { - '[[Configurable]]': true, - '[[Enumerable]]': false, - '[[Value]]': V, - '[[Writable]]': true - }; - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - newDesc - ); -}; diff --git a/node_modules/es-abstract/2019/DateFromTime.js b/node_modules/es-abstract/2019/DateFromTime.js deleted file mode 100644 index 962dba1..0000000 --- a/node_modules/es-abstract/2019/DateFromTime.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $EvalError = GetIntrinsic('%EvalError%'); - -var DayWithinYear = require('./DayWithinYear'); -var InLeapYear = require('./InLeapYear'); -var MonthFromTime = require('./MonthFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.5 - -module.exports = function DateFromTime(t) { - var m = MonthFromTime(t); - var d = DayWithinYear(t); - if (m === 0) { - return d + 1; - } - if (m === 1) { - return d - 30; - } - var leap = InLeapYear(t); - if (m === 2) { - return d - 58 - leap; - } - if (m === 3) { - return d - 89 - leap; - } - if (m === 4) { - return d - 119 - leap; - } - if (m === 5) { - return d - 150 - leap; - } - if (m === 6) { - return d - 180 - leap; - } - if (m === 7) { - return d - 211 - leap; - } - if (m === 8) { - return d - 242 - leap; - } - if (m === 9) { - return d - 272 - leap; - } - if (m === 10) { - return d - 303 - leap; - } - if (m === 11) { - return d - 333 - leap; - } - throw new $EvalError('Assertion failed: MonthFromTime returned an impossible value: ' + m); -}; diff --git a/node_modules/es-abstract/2019/DateString.js b/node_modules/es-abstract/2019/DateString.js deleted file mode 100644 index fc30329..0000000 --- a/node_modules/es-abstract/2019/DateString.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; - -var $isNaN = require('../helpers/isNaN'); -var padTimeComponent = require('../helpers/padTimeComponent'); - -var Type = require('./Type'); -var WeekDay = require('./WeekDay'); -var MonthFromTime = require('./MonthFromTime'); -var YearFromTime = require('./YearFromTime'); -var DateFromTime = require('./DateFromTime'); - -// https://www.ecma-international.org/ecma-262/9.0/#sec-datestring - -module.exports = function DateString(tv) { - if (Type(tv) !== 'Number' || $isNaN(tv)) { - throw new $TypeError('Assertion failed: `tv` must be a non-NaN Number'); - } - var weekday = weekdays[WeekDay(tv)]; - var month = months[MonthFromTime(tv)]; - var day = padTimeComponent(DateFromTime(tv)); - var year = padTimeComponent(YearFromTime(tv), 4); - return weekday + '\x20' + month + '\x20' + day + '\x20' + year; -}; diff --git a/node_modules/es-abstract/2019/Day.js b/node_modules/es-abstract/2019/Day.js deleted file mode 100644 index 00df813..0000000 --- a/node_modules/es-abstract/2019/Day.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - -module.exports = function Day(t) { - return $floor(t / msPerDay); -}; diff --git a/node_modules/es-abstract/2019/DayFromYear.js b/node_modules/es-abstract/2019/DayFromYear.js deleted file mode 100644 index 08dd5af..0000000 --- a/node_modules/es-abstract/2019/DayFromYear.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function DayFromYear(y) { - return (365 * (y - 1970)) + $floor((y - 1969) / 4) - $floor((y - 1901) / 100) + $floor((y - 1601) / 400); -}; - diff --git a/node_modules/es-abstract/2019/DayWithinYear.js b/node_modules/es-abstract/2019/DayWithinYear.js deleted file mode 100644 index cfc4002..0000000 --- a/node_modules/es-abstract/2019/DayWithinYear.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var Day = require('./Day'); -var DayFromYear = require('./DayFromYear'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - -module.exports = function DayWithinYear(t) { - return Day(t) - DayFromYear(YearFromTime(t)); -}; diff --git a/node_modules/es-abstract/2019/DaysInYear.js b/node_modules/es-abstract/2019/DaysInYear.js deleted file mode 100644 index db32251..0000000 --- a/node_modules/es-abstract/2019/DaysInYear.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function DaysInYear(y) { - if (mod(y, 4) !== 0) { - return 365; - } - if (mod(y, 100) !== 0) { - return 366; - } - if (mod(y, 400) !== 0) { - return 365; - } - return 366; -}; diff --git a/node_modules/es-abstract/2019/DefinePropertyOrThrow.js b/node_modules/es-abstract/2019/DefinePropertyOrThrow.js deleted file mode 100644 index 7977f6e..0000000 --- a/node_modules/es-abstract/2019/DefinePropertyOrThrow.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-definepropertyorthrow - -module.exports = function DefinePropertyOrThrow(O, P, desc) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - var Desc = isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, desc) ? desc : ToPropertyDescriptor(desc); - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc is not a valid Property Descriptor'); - } - - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); -}; diff --git a/node_modules/es-abstract/2019/DeletePropertyOrThrow.js b/node_modules/es-abstract/2019/DeletePropertyOrThrow.js deleted file mode 100644 index b476817..0000000 --- a/node_modules/es-abstract/2019/DeletePropertyOrThrow.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-deletepropertyorthrow - -module.exports = function DeletePropertyOrThrow(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // eslint-disable-next-line no-param-reassign - var success = delete O[P]; - if (!success) { - throw new $TypeError('Attempt to delete property failed.'); - } - return success; -}; diff --git a/node_modules/es-abstract/2019/EnumerableOwnPropertyNames.js b/node_modules/es-abstract/2019/EnumerableOwnPropertyNames.js deleted file mode 100644 index e2ed722..0000000 --- a/node_modules/es-abstract/2019/EnumerableOwnPropertyNames.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var objectKeys = require('object-keys'); - -var callBound = require('../helpers/callBound'); - -var callBind = require('../helpers/callBind'); - -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); -var $pushApply = callBind.apply(GetIntrinsic('%Array.prototype.push%')); - -var forEach = require('../helpers/forEach'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/8.0/#sec-enumerableownproperties - -module.exports = function EnumerableOwnProperties(O, kind) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - var keys = objectKeys(O); - if (kind === 'key') { - return keys; - } - if (kind === 'value' || kind === 'key+value') { - var results = []; - forEach(keys, function (key) { - if ($isEnumerable(O, key)) { - $pushApply(results, [ - kind === 'value' ? O[key] : [key, O[key]] - ]); - } - }); - return results; - } - throw new $TypeError('Assertion failed: "kind" is not "key", "value", or "key+value": ' + kind); -}; diff --git a/node_modules/es-abstract/2019/FlattenIntoArray.js b/node_modules/es-abstract/2019/FlattenIntoArray.js deleted file mode 100644 index 313a6ed..0000000 --- a/node_modules/es-abstract/2019/FlattenIntoArray.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger'); - -var Call = require('./Call'); -var CreateDataPropertyOrThrow = require('./CreateDataPropertyOrThrow'); -var Get = require('./Get'); -var HasProperty = require('./HasProperty'); -var IsArray = require('./IsArray'); -var ToLength = require('./ToLength'); -var ToString = require('./ToString'); - -// https://ecma-international.org/ecma-262/10.0/#sec-flattenintoarray - -// eslint-disable-next-line max-params, max-statements -module.exports = function FlattenIntoArray(target, source, sourceLen, start, depth) { - var mapperFunction; - if (arguments.length > 5) { - mapperFunction = arguments[5]; - } - - var targetIndex = start; - var sourceIndex = 0; - while (sourceIndex < sourceLen) { - var P = ToString(sourceIndex); - var exists = HasProperty(source, P); - if (exists === true) { - var element = Get(source, P); - if (typeof mapperFunction !== 'undefined') { - if (arguments.length <= 6) { - throw new $TypeError('Assertion failed: thisArg is required when mapperFunction is provided'); - } - element = Call(mapperFunction, arguments[6], [element, sourceIndex, source]); - } - var shouldFlatten = false; - if (depth > 0) { - shouldFlatten = IsArray(element); - } - if (shouldFlatten) { - var elementLen = ToLength(Get(element, 'length')); - targetIndex = FlattenIntoArray(target, element, elementLen, targetIndex, depth - 1); - } else { - if (targetIndex >= MAX_SAFE_INTEGER) { - throw new $TypeError('index too large'); - } - CreateDataPropertyOrThrow(target, ToString(targetIndex), element); - targetIndex += 1; - } - } - sourceIndex += 1; - } - - return targetIndex; -}; diff --git a/node_modules/es-abstract/2019/FromPropertyDescriptor.js b/node_modules/es-abstract/2019/FromPropertyDescriptor.js deleted file mode 100644 index 5ec200e..0000000 --- a/node_modules/es-abstract/2019/FromPropertyDescriptor.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-frompropertydescriptor - -module.exports = function FromPropertyDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return Desc; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - var obj = {}; - if ('[[Value]]' in Desc) { - obj.value = Desc['[[Value]]']; - } - if ('[[Writable]]' in Desc) { - obj.writable = Desc['[[Writable]]']; - } - if ('[[Get]]' in Desc) { - obj.get = Desc['[[Get]]']; - } - if ('[[Set]]' in Desc) { - obj.set = Desc['[[Set]]']; - } - if ('[[Enumerable]]' in Desc) { - obj.enumerable = Desc['[[Enumerable]]']; - } - if ('[[Configurable]]' in Desc) { - obj.configurable = Desc['[[Configurable]]']; - } - return obj; -}; diff --git a/node_modules/es-abstract/2019/Get.js b/node_modules/es-abstract/2019/Get.js deleted file mode 100644 index 5b9ad78..0000000 --- a/node_modules/es-abstract/2019/Get.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var inspect = require('object-inspect'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -/** - * 7.3.1 Get (O, P) - https://ecma-international.org/ecma-262/6.0/#sec-get-o-p - * 1. Assert: Type(O) is Object. - * 2. Assert: IsPropertyKey(P) is true. - * 3. Return O.[[Get]](P, O). - */ - -module.exports = function Get(O, P) { - // 7.3.1.1 - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - // 7.3.1.2 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true, got ' + inspect(P)); - } - // 7.3.1.3 - return O[P]; -}; diff --git a/node_modules/es-abstract/2019/GetIterator.js b/node_modules/es-abstract/2019/GetIterator.js deleted file mode 100644 index 7beddac..0000000 --- a/node_modules/es-abstract/2019/GetIterator.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var getIteratorMethod = require('../helpers/getIteratorMethod'); -var AdvanceStringIndex = require('./AdvanceStringIndex'); -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsArray = require('./IsArray'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-getiterator - -module.exports = function GetIterator(obj, method) { - var actualMethod = method; - if (arguments.length < 2) { - actualMethod = getIteratorMethod( - { - AdvanceStringIndex: AdvanceStringIndex, - GetMethod: GetMethod, - IsArray: IsArray, - Type: Type - }, - obj - ); - } - var iterator = Call(actualMethod, obj); - if (Type(iterator) !== 'Object') { - throw new $TypeError('iterator must return an object'); - } - - return iterator; -}; diff --git a/node_modules/es-abstract/2019/GetMethod.js b/node_modules/es-abstract/2019/GetMethod.js deleted file mode 100644 index aef8cbc..0000000 --- a/node_modules/es-abstract/2019/GetMethod.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var GetV = require('./GetV'); -var IsCallable = require('./IsCallable'); -var IsPropertyKey = require('./IsPropertyKey'); - -/** - * 7.3.9 - https://ecma-international.org/ecma-262/6.0/#sec-getmethod - * 1. Assert: IsPropertyKey(P) is true. - * 2. Let func be GetV(O, P). - * 3. ReturnIfAbrupt(func). - * 4. If func is either undefined or null, return undefined. - * 5. If IsCallable(func) is false, throw a TypeError exception. - * 6. Return func. - */ - -module.exports = function GetMethod(O, P) { - // 7.3.9.1 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // 7.3.9.2 - var func = GetV(O, P); - - // 7.3.9.4 - if (func == null) { - return void 0; - } - - // 7.3.9.5 - if (!IsCallable(func)) { - throw new $TypeError(P + 'is not a function'); - } - - // 7.3.9.6 - return func; -}; diff --git a/node_modules/es-abstract/2019/GetOwnPropertyKeys.js b/node_modules/es-abstract/2019/GetOwnPropertyKeys.js deleted file mode 100644 index 8d7e5ee..0000000 --- a/node_modules/es-abstract/2019/GetOwnPropertyKeys.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var hasSymbols = require('has-symbols')(); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); -var $gOPS = hasSymbols && GetIntrinsic('%Object.getOwnPropertySymbols%'); -var keys = require('object-keys'); - -var esType = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-getownpropertykeys - -module.exports = function GetOwnPropertyKeys(O, Type) { - if (esType(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (Type === 'Symbol') { - return $gOPS ? $gOPS(O) : []; - } - if (Type === 'String') { - if (!$gOPN) { - return keys(O); - } - return $gOPN(O); - } - throw new $TypeError('Assertion failed: `Type` must be `"String"` or `"Symbol"`'); -}; diff --git a/node_modules/es-abstract/2019/GetPrototypeFromConstructor.js b/node_modules/es-abstract/2019/GetPrototypeFromConstructor.js deleted file mode 100644 index 62da8fb..0000000 --- a/node_modules/es-abstract/2019/GetPrototypeFromConstructor.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Function = GetIntrinsic('%Function%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsConstructor = require('./IsConstructor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-getprototypefromconstructor - -module.exports = function GetPrototypeFromConstructor(constructor, intrinsicDefaultProto) { - var intrinsic = GetIntrinsic(intrinsicDefaultProto); // throws if not a valid intrinsic - if (!IsConstructor(constructor)) { - throw new $TypeError('Assertion failed: `constructor` must be a constructor'); - } - var proto = Get(constructor, 'prototype'); - if (Type(proto) !== 'Object') { - if (!(constructor instanceof $Function)) { - // ignore other realms, for now - throw new $TypeError('cross-realm constructors not currently supported'); - } - proto = intrinsic; - } - return proto; -}; diff --git a/node_modules/es-abstract/2019/GetSubstitution.js b/node_modules/es-abstract/2019/GetSubstitution.js deleted file mode 100644 index 2ec9ebc..0000000 --- a/node_modules/es-abstract/2019/GetSubstitution.js +++ /dev/null @@ -1,128 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); -var regexTester = require('../helpers/regexTester'); -var every = require('../helpers/every'); - -var $charAt = callBound('String.prototype.charAt'); -var $strSlice = callBound('String.prototype.slice'); -var $indexOf = callBound('String.prototype.indexOf'); -var $parseInt = parseInt; - -var isDigit = regexTester(/^[0-9]$/); - -var inspect = require('object-inspect'); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var IsInteger = require('./IsInteger'); -var ToObject = require('./ToObject'); -var ToString = require('./ToString'); -var Type = require('./Type'); - -var canDistinguishSparseFromUndefined = 0 in [undefined]; // IE 6 - 8 have a bug where this returns false - -var isStringOrHole = function (capture, index, arr) { - return Type(capture) === 'String' || (canDistinguishSparseFromUndefined ? !(index in arr) : Type(capture) === 'Undefined'); -}; - -// http://www.ecma-international.org/ecma-262/9.0/#sec-getsubstitution - -// eslint-disable-next-line max-statements, max-params, max-lines-per-function -module.exports = function GetSubstitution(matched, str, position, captures, namedCaptures, replacement) { - if (Type(matched) !== 'String') { - throw new $TypeError('Assertion failed: `matched` must be a String'); - } - var matchLength = matched.length; - - if (Type(str) !== 'String') { - throw new $TypeError('Assertion failed: `str` must be a String'); - } - var stringLength = str.length; - - if (!IsInteger(position) || position < 0 || position > stringLength) { - throw new $TypeError('Assertion failed: `position` must be a nonnegative integer, and less than or equal to the length of `string`, got ' + inspect(position)); - } - - if (!IsArray(captures) || !every(captures, isStringOrHole)) { - throw new $TypeError('Assertion failed: `captures` must be a List of Strings, got ' + inspect(captures)); - } - - if (Type(replacement) !== 'String') { - throw new $TypeError('Assertion failed: `replacement` must be a String'); - } - - var tailPos = position + matchLength; - var m = captures.length; - if (Type(namedCaptures) !== 'Undefined') { - namedCaptures = ToObject(namedCaptures); // eslint-disable-line no-param-reassign - } - - var result = ''; - for (var i = 0; i < replacement.length; i += 1) { - // if this is a $, and it's not the end of the replacement - var current = $charAt(replacement, i); - var isLast = (i + 1) >= replacement.length; - var nextIsLast = (i + 2) >= replacement.length; - if (current === '$' && !isLast) { - var next = $charAt(replacement, i + 1); - if (next === '$') { - result += '$'; - i += 1; - } else if (next === '&') { - result += matched; - i += 1; - } else if (next === '`') { - result += position === 0 ? '' : $strSlice(str, 0, position - 1); - i += 1; - } else if (next === "'") { - result += tailPos >= stringLength ? '' : $strSlice(str, tailPos); - i += 1; - } else { - var nextNext = nextIsLast ? null : $charAt(replacement, i + 2); - if (isDigit(next) && next !== '0' && (nextIsLast || !isDigit(nextNext))) { - // $1 through $9, and not followed by a digit - var n = $parseInt(next, 10); - // if (n > m, impl-defined) - result += (n <= m && Type(captures[n - 1]) === 'Undefined') ? '' : captures[n - 1]; - i += 1; - } else if (isDigit(next) && (nextIsLast || isDigit(nextNext))) { - // $00 through $99 - var nn = next + nextNext; - var nnI = $parseInt(nn, 10) - 1; - // if nn === '00' or nn > m, impl-defined - result += (nn <= m && Type(captures[nnI]) === 'Undefined') ? '' : captures[nnI]; - i += 2; - } else if (next === '<') { - // eslint-disable-next-line max-depth - if (Type(namedCaptures) === 'Undefined') { - result += '$<'; - i += 2; - } else { - var endIndex = $indexOf(replacement, '>', i); - // eslint-disable-next-line max-depth - if (endIndex > -1) { - var groupName = $strSlice(replacement, i, endIndex); - var capture = Get(namedCaptures, groupName); - // eslint-disable-next-line max-depth - if (Type(capture) !== 'Undefined') { - result += ToString(capture); - } - i += '$<' + groupName + '>'.length; - } - } - } else { - result += '$'; - } - } - } else { - // the final $, or else not a $ - result += $charAt(replacement, i); - } - } - return result; -}; diff --git a/node_modules/es-abstract/2019/GetV.js b/node_modules/es-abstract/2019/GetV.js deleted file mode 100644 index 7b5139a..0000000 --- a/node_modules/es-abstract/2019/GetV.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var ToObject = require('./ToObject'); - -/** - * 7.3.2 GetV (V, P) - * 1. Assert: IsPropertyKey(P) is true. - * 2. Let O be ToObject(V). - * 3. ReturnIfAbrupt(O). - * 4. Return O.[[Get]](P, V). - */ - -module.exports = function GetV(V, P) { - // 7.3.2.1 - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // 7.3.2.2-3 - var O = ToObject(V); - - // 7.3.2.4 - return O[P]; -}; diff --git a/node_modules/es-abstract/2019/HasOwnProperty.js b/node_modules/es-abstract/2019/HasOwnProperty.js deleted file mode 100644 index 679059f..0000000 --- a/node_modules/es-abstract/2019/HasOwnProperty.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var has = require('has'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-hasownproperty - -module.exports = function HasOwnProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - return has(O, P); -}; diff --git a/node_modules/es-abstract/2019/HasProperty.js b/node_modules/es-abstract/2019/HasProperty.js deleted file mode 100644 index 5f2d212..0000000 --- a/node_modules/es-abstract/2019/HasProperty.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-hasproperty - -module.exports = function HasProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - return P in O; -}; diff --git a/node_modules/es-abstract/2019/HourFromTime.js b/node_modules/es-abstract/2019/HourFromTime.js deleted file mode 100644 index 957ce32..0000000 --- a/node_modules/es-abstract/2019/HourFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerHour = timeConstants.msPerHour; -var HoursPerDay = timeConstants.HoursPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function HourFromTime(t) { - return mod($floor(t / msPerHour), HoursPerDay); -}; diff --git a/node_modules/es-abstract/2019/InLeapYear.js b/node_modules/es-abstract/2019/InLeapYear.js deleted file mode 100644 index 38ba8fd..0000000 --- a/node_modules/es-abstract/2019/InLeapYear.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $EvalError = GetIntrinsic('%EvalError%'); - -var DaysInYear = require('./DaysInYear'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function InLeapYear(t) { - var days = DaysInYear(YearFromTime(t)); - if (days === 365) { - return 0; - } - if (days === 366) { - return 1; - } - throw new $EvalError('Assertion failed: there are not 365 or 366 days in a year, got: ' + days); -}; diff --git a/node_modules/es-abstract/2019/InstanceofOperator.js b/node_modules/es-abstract/2019/InstanceofOperator.js deleted file mode 100644 index ebd308c..0000000 --- a/node_modules/es-abstract/2019/InstanceofOperator.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $hasInstance = GetIntrinsic('Symbol.hasInstance', true); - -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsCallable = require('./IsCallable'); -var OrdinaryHasInstance = require('./OrdinaryHasInstance'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-instanceofoperator - -module.exports = function InstanceofOperator(O, C) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - var instOfHandler = $hasInstance ? GetMethod(C, $hasInstance) : void 0; - if (typeof instOfHandler !== 'undefined') { - return ToBoolean(Call(instOfHandler, C, [O])); - } - if (!IsCallable(C)) { - throw new $TypeError('`C` is not Callable'); - } - return OrdinaryHasInstance(C, O); -}; diff --git a/node_modules/es-abstract/2019/Invoke.js b/node_modules/es-abstract/2019/Invoke.js deleted file mode 100644 index 769f0e3..0000000 --- a/node_modules/es-abstract/2019/Invoke.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $arraySlice = require('../helpers/callBound')('Array.prototype.slice'); - -var Call = require('./Call'); -var GetV = require('./GetV'); -var IsPropertyKey = require('./IsPropertyKey'); - -// https://ecma-international.org/ecma-262/6.0/#sec-invoke - -module.exports = function Invoke(O, P) { - if (!IsPropertyKey(P)) { - throw new $TypeError('P must be a Property Key'); - } - var argumentsList = $arraySlice(arguments, 2); - var func = GetV(O, P); - return Call(func, O, argumentsList); -}; diff --git a/node_modules/es-abstract/2019/IsAccessorDescriptor.js b/node_modules/es-abstract/2019/IsAccessorDescriptor.js deleted file mode 100644 index 5139464..0000000 --- a/node_modules/es-abstract/2019/IsAccessorDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isaccessordescriptor - -module.exports = function IsAccessorDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) { - return false; - } - - return true; -}; diff --git a/node_modules/es-abstract/2019/IsArray.js b/node_modules/es-abstract/2019/IsArray.js deleted file mode 100644 index 7b25f37..0000000 --- a/node_modules/es-abstract/2019/IsArray.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Array = GetIntrinsic('%Array%'); - -// eslint-disable-next-line global-require -var toStr = !$Array.isArray && require('../helpers/callBound')('Object.prototype.toString'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isarray - -module.exports = $Array.isArray || function IsArray(argument) { - return toStr(argument) === '[object Array]'; -}; diff --git a/node_modules/es-abstract/2019/IsCallable.js b/node_modules/es-abstract/2019/IsCallable.js deleted file mode 100644 index e4bfa36..0000000 --- a/node_modules/es-abstract/2019/IsCallable.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.11 - -module.exports = require('is-callable'); diff --git a/node_modules/es-abstract/2019/IsConcatSpreadable.js b/node_modules/es-abstract/2019/IsConcatSpreadable.js deleted file mode 100644 index dc8aae1..0000000 --- a/node_modules/es-abstract/2019/IsConcatSpreadable.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $isConcatSpreadable = GetIntrinsic('%Symbol.isConcatSpreadable%', true); - -var Get = require('./Get'); -var IsArray = require('./IsArray'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-isconcatspreadable - -module.exports = function IsConcatSpreadable(O) { - if (Type(O) !== 'Object') { - return false; - } - if ($isConcatSpreadable) { - var spreadable = Get(O, $isConcatSpreadable); - if (typeof spreadable !== 'undefined') { - return ToBoolean(spreadable); - } - } - return IsArray(O); -}; diff --git a/node_modules/es-abstract/2019/IsConstructor.js b/node_modules/es-abstract/2019/IsConstructor.js deleted file mode 100644 index 00ea52c..0000000 --- a/node_modules/es-abstract/2019/IsConstructor.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isconstructor - -module.exports = function IsConstructor(argument) { - return typeof argument === 'function' && !!argument.prototype; // unfortunately there's no way to truly check this without try/catch `new argument` -}; diff --git a/node_modules/es-abstract/2019/IsDataDescriptor.js b/node_modules/es-abstract/2019/IsDataDescriptor.js deleted file mode 100644 index 0ad3045..0000000 --- a/node_modules/es-abstract/2019/IsDataDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var has = require('has'); - -var assertRecord = require('../helpers/assertRecord'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isdatadescriptor - -module.exports = function IsDataDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) { - return false; - } - - return true; -}; diff --git a/node_modules/es-abstract/2019/IsExtensible.js b/node_modules/es-abstract/2019/IsExtensible.js deleted file mode 100644 index 0c4c8a6..0000000 --- a/node_modules/es-abstract/2019/IsExtensible.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Object = GetIntrinsic('%Object%'); - -var isPrimitive = require('../helpers/isPrimitive'); - -var $preventExtensions = $Object.preventExtensions; -var $isExtensible = $Object.isExtensible; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isextensible-o - -module.exports = $preventExtensions - ? function IsExtensible(obj) { - return !isPrimitive(obj) && $isExtensible(obj); - } - : function IsExtensible(obj) { - return !isPrimitive(obj); - }; diff --git a/node_modules/es-abstract/2019/IsGenericDescriptor.js b/node_modules/es-abstract/2019/IsGenericDescriptor.js deleted file mode 100644 index 8618ce4..0000000 --- a/node_modules/es-abstract/2019/IsGenericDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var assertRecord = require('../helpers/assertRecord'); - -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isgenericdescriptor - -module.exports = function IsGenericDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!IsAccessorDescriptor(Desc) && !IsDataDescriptor(Desc)) { - return true; - } - - return false; -}; diff --git a/node_modules/es-abstract/2019/IsInteger.js b/node_modules/es-abstract/2019/IsInteger.js deleted file mode 100644 index 0f488b3..0000000 --- a/node_modules/es-abstract/2019/IsInteger.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-isinteger - -module.exports = function IsInteger(argument) { - if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) { - return false; - } - var abs = $abs(argument); - return $floor(abs) === abs; -}; diff --git a/node_modules/es-abstract/2019/IsPromise.js b/node_modules/es-abstract/2019/IsPromise.js deleted file mode 100644 index e8e92a2..0000000 --- a/node_modules/es-abstract/2019/IsPromise.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var $PromiseThen = callBound('Promise.prototype.then', true); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ispromise - -module.exports = function IsPromise(x) { - if (Type(x) !== 'Object') { - return false; - } - if (!$PromiseThen) { // Promises are not supported - return false; - } - try { - $PromiseThen(x); // throws if not a promise - } catch (e) { - return false; - } - return true; -}; diff --git a/node_modules/es-abstract/2019/IsPropertyKey.js b/node_modules/es-abstract/2019/IsPropertyKey.js deleted file mode 100644 index 74b8d95..0000000 --- a/node_modules/es-abstract/2019/IsPropertyKey.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ispropertykey - -module.exports = function IsPropertyKey(argument) { - return typeof argument === 'string' || typeof argument === 'symbol'; -}; diff --git a/node_modules/es-abstract/2019/IsRegExp.js b/node_modules/es-abstract/2019/IsRegExp.js deleted file mode 100644 index fdf2323..0000000 --- a/node_modules/es-abstract/2019/IsRegExp.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $match = GetIntrinsic('%Symbol.match%', true); - -var hasRegExpMatcher = require('is-regex'); - -var ToBoolean = require('./ToBoolean'); - -// https://ecma-international.org/ecma-262/6.0/#sec-isregexp - -module.exports = function IsRegExp(argument) { - if (!argument || typeof argument !== 'object') { - return false; - } - if ($match) { - var isRegExp = argument[$match]; - if (typeof isRegExp !== 'undefined') { - return ToBoolean(isRegExp); - } - } - return hasRegExpMatcher(argument); -}; diff --git a/node_modules/es-abstract/2019/IsStringPrefix.js b/node_modules/es-abstract/2019/IsStringPrefix.js deleted file mode 100644 index f5e2996..0000000 --- a/node_modules/es-abstract/2019/IsStringPrefix.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var isPrefixOf = require('../helpers/isPrefixOf'); - -// var callBound = require('../helpers/callBound'); - -// var $charAt = callBound('String.prototype.charAt'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/9.0/#sec-isstringprefix - -module.exports = function IsStringPrefix(p, q) { - if (Type(p) !== 'String') { - throw new $TypeError('Assertion failed: "p" must be a String'); - } - - if (Type(q) !== 'String') { - throw new $TypeError('Assertion failed: "q" must be a String'); - } - - return isPrefixOf(p, q); - /* - if (p === q || p === '') { - return true; - } - - var pLength = p.length; - var qLength = q.length; - if (pLength >= qLength) { - return false; - } - - // assert: pLength < qLength - - for (var i = 0; i < pLength; i += 1) { - if ($charAt(p, i) !== $charAt(q, i)) { - return false; - } - } - return true; - */ -}; diff --git a/node_modules/es-abstract/2019/IterableToList.js b/node_modules/es-abstract/2019/IterableToList.js deleted file mode 100644 index 0b8cdcf..0000000 --- a/node_modules/es-abstract/2019/IterableToList.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); -var $arrayPush = callBound('Array.prototype.push'); - -var GetIterator = require('./GetIterator'); -var IteratorStep = require('./IteratorStep'); -var IteratorValue = require('./IteratorValue'); - -// https://www.ecma-international.org/ecma-262/8.0/#sec-iterabletolist - -module.exports = function IterableToList(items, method) { - var iterator = GetIterator(items, method); - var values = []; - var next = true; - while (next) { - next = IteratorStep(iterator); - if (next) { - var nextValue = IteratorValue(next); - $arrayPush(values, nextValue); - } - } - return values; -}; diff --git a/node_modules/es-abstract/2019/IteratorClose.js b/node_modules/es-abstract/2019/IteratorClose.js deleted file mode 100644 index 35c8c2b..0000000 --- a/node_modules/es-abstract/2019/IteratorClose.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Call = require('./Call'); -var GetMethod = require('./GetMethod'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorclose - -module.exports = function IteratorClose(iterator, completion) { - if (Type(iterator) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterator) is not Object'); - } - if (!IsCallable(completion)) { - throw new $TypeError('Assertion failed: completion is not a thunk for a Completion Record'); - } - var completionThunk = completion; - - var iteratorReturn = GetMethod(iterator, 'return'); - - if (typeof iteratorReturn === 'undefined') { - return completionThunk(); - } - - var completionRecord; - try { - var innerResult = Call(iteratorReturn, iterator, []); - } catch (e) { - // if we hit here, then "e" is the innerResult completion that needs re-throwing - - // if the completion is of type "throw", this will throw. - completionThunk(); - completionThunk = null; // ensure it's not called twice. - - // if not, then return the innerResult completion - throw e; - } - completionRecord = completionThunk(); // if innerResult worked, then throw if the completion does - completionThunk = null; // ensure it's not called twice. - - if (Type(innerResult) !== 'Object') { - throw new $TypeError('iterator .return must return an object'); - } - - return completionRecord; -}; diff --git a/node_modules/es-abstract/2019/IteratorComplete.js b/node_modules/es-abstract/2019/IteratorComplete.js deleted file mode 100644 index a62b9bf..0000000 --- a/node_modules/es-abstract/2019/IteratorComplete.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var ToBoolean = require('./ToBoolean'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorcomplete - -module.exports = function IteratorComplete(iterResult) { - if (Type(iterResult) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); - } - return ToBoolean(Get(iterResult, 'done')); -}; diff --git a/node_modules/es-abstract/2019/IteratorNext.js b/node_modules/es-abstract/2019/IteratorNext.js deleted file mode 100644 index 7e59915..0000000 --- a/node_modules/es-abstract/2019/IteratorNext.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Invoke = require('./Invoke'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratornext - -module.exports = function IteratorNext(iterator, value) { - var result = Invoke(iterator, 'next', arguments.length < 2 ? [] : [value]); - if (Type(result) !== 'Object') { - throw new $TypeError('iterator next must return an object'); - } - return result; -}; diff --git a/node_modules/es-abstract/2019/IteratorStep.js b/node_modules/es-abstract/2019/IteratorStep.js deleted file mode 100644 index 41b9d1b..0000000 --- a/node_modules/es-abstract/2019/IteratorStep.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var IteratorComplete = require('./IteratorComplete'); -var IteratorNext = require('./IteratorNext'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorstep - -module.exports = function IteratorStep(iterator) { - var result = IteratorNext(iterator); - var done = IteratorComplete(result); - return done === true ? false : result; -}; - diff --git a/node_modules/es-abstract/2019/IteratorValue.js b/node_modules/es-abstract/2019/IteratorValue.js deleted file mode 100644 index 5e71a44..0000000 --- a/node_modules/es-abstract/2019/IteratorValue.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-iteratorvalue - -module.exports = function IteratorValue(iterResult) { - if (Type(iterResult) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); - } - return Get(iterResult, 'value'); -}; - diff --git a/node_modules/es-abstract/2019/MakeDate.js b/node_modules/es-abstract/2019/MakeDate.js deleted file mode 100644 index 7b592d1..0000000 --- a/node_modules/es-abstract/2019/MakeDate.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $isFinite = require('../helpers/isFinite'); -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.13 - -module.exports = function MakeDate(day, time) { - if (!$isFinite(day) || !$isFinite(time)) { - return NaN; - } - return (day * msPerDay) + time; -}; diff --git a/node_modules/es-abstract/2019/MakeDay.js b/node_modules/es-abstract/2019/MakeDay.js deleted file mode 100644 index f1ab810..0000000 --- a/node_modules/es-abstract/2019/MakeDay.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); -var $DateUTC = GetIntrinsic('%Date.UTC%'); - -var mod = require('../helpers/mod'); -var $isFinite = require('../helpers/isFinite'); - -var DateFromTime = require('./DateFromTime'); -var Day = require('./Day'); -var MonthFromTime = require('./MonthFromTime'); -var ToInteger = require('./ToInteger'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.12 - -module.exports = function MakeDay(year, month, date) { - if (!$isFinite(year) || !$isFinite(month) || !$isFinite(date)) { - return NaN; - } - var y = ToInteger(year); - var m = ToInteger(month); - var dt = ToInteger(date); - var ym = y + $floor(m / 12); - var mn = mod(m, 12); - var t = $DateUTC(ym, mn, 1); - if (YearFromTime(t) !== ym || MonthFromTime(t) !== mn || DateFromTime(t) !== 1) { - return NaN; - } - return Day(t) + dt - 1; -}; diff --git a/node_modules/es-abstract/2019/MakeTime.js b/node_modules/es-abstract/2019/MakeTime.js deleted file mode 100644 index e118500..0000000 --- a/node_modules/es-abstract/2019/MakeTime.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var $isFinite = require('../helpers/isFinite'); -var timeConstants = require('../helpers/timeConstants'); -var msPerSecond = timeConstants.msPerSecond; -var msPerMinute = timeConstants.msPerMinute; -var msPerHour = timeConstants.msPerHour; - -var ToInteger = require('./ToInteger'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.11 - -module.exports = function MakeTime(hour, min, sec, ms) { - if (!$isFinite(hour) || !$isFinite(min) || !$isFinite(sec) || !$isFinite(ms)) { - return NaN; - } - var h = ToInteger(hour); - var m = ToInteger(min); - var s = ToInteger(sec); - var milli = ToInteger(ms); - var t = (h * msPerHour) + (m * msPerMinute) + (s * msPerSecond) + milli; - return t; -}; diff --git a/node_modules/es-abstract/2019/MinFromTime.js b/node_modules/es-abstract/2019/MinFromTime.js deleted file mode 100644 index e80e191..0000000 --- a/node_modules/es-abstract/2019/MinFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerMinute = timeConstants.msPerMinute; -var MinutesPerHour = timeConstants.MinutesPerHour; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function MinFromTime(t) { - return mod($floor(t / msPerMinute), MinutesPerHour); -}; diff --git a/node_modules/es-abstract/2019/MonthFromTime.js b/node_modules/es-abstract/2019/MonthFromTime.js deleted file mode 100644 index 4f120f2..0000000 --- a/node_modules/es-abstract/2019/MonthFromTime.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -var DayWithinYear = require('./DayWithinYear'); -var InLeapYear = require('./InLeapYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - -module.exports = function MonthFromTime(t) { - var day = DayWithinYear(t); - if (0 <= day && day < 31) { - return 0; - } - var leap = InLeapYear(t); - if (31 <= day && day < (59 + leap)) { - return 1; - } - if ((59 + leap) <= day && day < (90 + leap)) { - return 2; - } - if ((90 + leap) <= day && day < (120 + leap)) { - return 3; - } - if ((120 + leap) <= day && day < (151 + leap)) { - return 4; - } - if ((151 + leap) <= day && day < (181 + leap)) { - return 5; - } - if ((181 + leap) <= day && day < (212 + leap)) { - return 6; - } - if ((212 + leap) <= day && day < (243 + leap)) { - return 7; - } - if ((243 + leap) <= day && day < (273 + leap)) { - return 8; - } - if ((273 + leap) <= day && day < (304 + leap)) { - return 9; - } - if ((304 + leap) <= day && day < (334 + leap)) { - return 10; - } - if ((334 + leap) <= day && day < (365 + leap)) { - return 11; - } -}; diff --git a/node_modules/es-abstract/2019/NumberToString.js b/node_modules/es-abstract/2019/NumberToString.js deleted file mode 100644 index 2cc70e0..0000000 --- a/node_modules/es-abstract/2019/NumberToString.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $String = GetIntrinsic('%String%'); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/9.0/#sec-tostring-applied-to-the-number-type - -module.exports = function NumberToString(m) { - if (Type(m) !== 'Number') { - throw new TypeError('Assertion failed: "m" must be a String'); - } - - return $String(m); -}; - diff --git a/node_modules/es-abstract/2019/ObjectCreate.js b/node_modules/es-abstract/2019/ObjectCreate.js deleted file mode 100644 index e2445b0..0000000 --- a/node_modules/es-abstract/2019/ObjectCreate.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $ObjectCreate = GetIntrinsic('%Object.create%', true); -var $TypeError = GetIntrinsic('%TypeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); - -var Type = require('./Type'); - -var hasProto = !({ __proto__: null } instanceof Object); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-objectcreate - -module.exports = function ObjectCreate(proto, internalSlotsList) { - if (proto !== null && Type(proto) !== 'Object') { - throw new $TypeError('Assertion failed: `proto` must be null or an object'); - } - var slots = arguments.length < 2 ? [] : internalSlotsList; - if (slots.length > 0) { - throw new $SyntaxError('es-abstract does not yet support internal slots'); - } - - if ($ObjectCreate) { - return $ObjectCreate(proto); - } - if (hasProto) { - return { __proto__: proto }; - } - - if (proto === null) { - throw new $SyntaxError('native Object.create support is required to create null objects'); - } - var T = function T() {}; - T.prototype = proto; - return new T(); -}; diff --git a/node_modules/es-abstract/2019/OrdinaryDefineOwnProperty.js b/node_modules/es-abstract/2019/OrdinaryDefineOwnProperty.js deleted file mode 100644 index 59780b3..0000000 --- a/node_modules/es-abstract/2019/OrdinaryDefineOwnProperty.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var IsPropertyKey = require('./IsPropertyKey'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); -var ValidateAndApplyPropertyDescriptor = require('./ValidateAndApplyPropertyDescriptor'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarydefineownproperty - -module.exports = function OrdinaryDefineOwnProperty(O, P, Desc) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (!$gOPD) { - // ES3/IE 8 fallback - if (IsAccessorDescriptor(Desc)) { - throw new $SyntaxError('This environment does not support accessor property descriptors.'); - } - var creatingNormalDataProperty = !(P in O) - && Desc['[[Writable]]'] - && Desc['[[Enumerable]]'] - && Desc['[[Configurable]]'] - && '[[Value]]' in Desc; - var settingExistingDataProperty = (P in O) - && (!('[[Configurable]]' in Desc) || Desc['[[Configurable]]']) - && (!('[[Enumerable]]' in Desc) || Desc['[[Enumerable]]']) - && (!('[[Writable]]' in Desc) || Desc['[[Writable]]']) - && '[[Value]]' in Desc; - if (creatingNormalDataProperty || settingExistingDataProperty) { - O[P] = Desc['[[Value]]']; // eslint-disable-line no-param-reassign - return SameValue(O[P], Desc['[[Value]]']); - } - throw new $SyntaxError('This environment does not support defining non-writable, non-enumerable, or non-configurable properties'); - } - var desc = $gOPD(O, P); - var current = desc && ToPropertyDescriptor(desc); - var extensible = IsExtensible(O); - return ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current); -}; diff --git a/node_modules/es-abstract/2019/OrdinaryGetOwnProperty.js b/node_modules/es-abstract/2019/OrdinaryGetOwnProperty.js deleted file mode 100644 index b9882e5..0000000 --- a/node_modules/es-abstract/2019/OrdinaryGetOwnProperty.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); - -var has = require('has'); - -var IsArray = require('./IsArray'); -var IsPropertyKey = require('./IsPropertyKey'); -var IsRegExp = require('./IsRegExp'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarygetownproperty - -module.exports = function OrdinaryGetOwnProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - if (!has(O, P)) { - return void 0; - } - if (!$gOPD) { - // ES3 / IE 8 fallback - var arrayLength = IsArray(O) && P === 'length'; - var regexLastIndex = IsRegExp(O) && P === 'lastIndex'; - return { - '[[Configurable]]': !(arrayLength || regexLastIndex), - '[[Enumerable]]': $isEnumerable(O, P), - '[[Value]]': O[P], - '[[Writable]]': true - }; - } - return ToPropertyDescriptor($gOPD(O, P)); -}; diff --git a/node_modules/es-abstract/2019/OrdinaryGetPrototypeOf.js b/node_modules/es-abstract/2019/OrdinaryGetPrototypeOf.js deleted file mode 100644 index 344077a..0000000 --- a/node_modules/es-abstract/2019/OrdinaryGetPrototypeOf.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $getProto = require('../helpers/getProto'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/7.0/#sec-ordinarygetprototypeof - -module.exports = function OrdinaryGetPrototypeOf(O) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!$getProto) { - throw new $TypeError('This environment does not support fetching prototypes.'); - } - return $getProto(O); -}; diff --git a/node_modules/es-abstract/2019/OrdinaryHasInstance.js b/node_modules/es-abstract/2019/OrdinaryHasInstance.js deleted file mode 100644 index 51abe26..0000000 --- a/node_modules/es-abstract/2019/OrdinaryHasInstance.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Get = require('./Get'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance - -module.exports = function OrdinaryHasInstance(C, O) { - if (IsCallable(C) === false) { - return false; - } - if (Type(O) !== 'Object') { - return false; - } - var P = Get(C, 'prototype'); - if (Type(P) !== 'Object') { - throw new $TypeError('OrdinaryHasInstance called on an object with an invalid prototype property.'); - } - return O instanceof C; -}; diff --git a/node_modules/es-abstract/2019/OrdinaryHasProperty.js b/node_modules/es-abstract/2019/OrdinaryHasProperty.js deleted file mode 100644 index 076c25a..0000000 --- a/node_modules/es-abstract/2019/OrdinaryHasProperty.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasproperty - -module.exports = function OrdinaryHasProperty(O, P) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - return P in O; -}; diff --git a/node_modules/es-abstract/2019/OrdinarySetPrototypeOf.js b/node_modules/es-abstract/2019/OrdinarySetPrototypeOf.js deleted file mode 100644 index 3541331..0000000 --- a/node_modules/es-abstract/2019/OrdinarySetPrototypeOf.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $setProto = require('../helpers/setProto'); - -var OrdinaryGetPrototypeOf = require('./OrdinaryGetPrototypeOf'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/7.0/#sec-ordinarysetprototypeof - -module.exports = function OrdinarySetPrototypeOf(O, V) { - if (Type(V) !== 'Object' && Type(V) !== 'Null') { - throw new $TypeError('Assertion failed: V must be Object or Null'); - } - /* - var extensible = IsExtensible(O); - var current = OrdinaryGetPrototypeOf(O); - if (SameValue(V, current)) { - return true; - } - if (!extensible) { - return false; - } - */ - try { - $setProto(O, V); - } catch (e) { - return false; - } - return OrdinaryGetPrototypeOf(O) === V; - /* - var p = V; - var done = false; - while (!done) { - if (p === null) { - done = true; - } else if (SameValue(p, O)) { - return false; - } else { - if (wat) { - done = true; - } else { - p = p.[[Prototype]]; - } - } - } - O.[[Prototype]] = V; - return true; - */ -}; diff --git a/node_modules/es-abstract/2019/PromiseResolve.js b/node_modules/es-abstract/2019/PromiseResolve.js deleted file mode 100644 index f70745d..0000000 --- a/node_modules/es-abstract/2019/PromiseResolve.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var $PromiseResolve = callBound('Promise.resolve', true); - -// https://ecma-international.org/ecma-262/9.0/#sec-promise-resolve - -module.exports = function PromiseResolve(C, x) { - if (!$PromiseResolve) { - throw new SyntaxError('This environment does not support Promises.'); - } - return $PromiseResolve(C, x); -}; - diff --git a/node_modules/es-abstract/2019/RegExpExec.js b/node_modules/es-abstract/2019/RegExpExec.js deleted file mode 100644 index 15c9186..0000000 --- a/node_modules/es-abstract/2019/RegExpExec.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var regexExec = require('../helpers/callBound')('RegExp.prototype.exec'); - -var Call = require('./Call'); -var Get = require('./Get'); -var IsCallable = require('./IsCallable'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-regexpexec - -module.exports = function RegExpExec(R, S) { - if (Type(R) !== 'Object') { - throw new $TypeError('Assertion failed: `R` must be an Object'); - } - if (Type(S) !== 'String') { - throw new $TypeError('Assertion failed: `S` must be a String'); - } - var exec = Get(R, 'exec'); - if (IsCallable(exec)) { - var result = Call(exec, R, [S]); - if (result === null || Type(result) === 'Object') { - return result; - } - throw new $TypeError('"exec" method must return `null` or an Object'); - } - return regexExec(R, S); -}; diff --git a/node_modules/es-abstract/2019/RequireObjectCoercible.js b/node_modules/es-abstract/2019/RequireObjectCoercible.js deleted file mode 100644 index 9008359..0000000 --- a/node_modules/es-abstract/2019/RequireObjectCoercible.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('../5/CheckObjectCoercible'); diff --git a/node_modules/es-abstract/2019/SameValue.js b/node_modules/es-abstract/2019/SameValue.js deleted file mode 100644 index 47c936d..0000000 --- a/node_modules/es-abstract/2019/SameValue.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $isNaN = require('../helpers/isNaN'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.12 - -module.exports = function SameValue(x, y) { - if (x === y) { // 0 === -0, but they are not identical. - if (x === 0) { return 1 / x === 1 / y; } - return true; - } - return $isNaN(x) && $isNaN(y); -}; diff --git a/node_modules/es-abstract/2019/SameValueNonNumber.js b/node_modules/es-abstract/2019/SameValueNonNumber.js deleted file mode 100644 index 5668752..0000000 --- a/node_modules/es-abstract/2019/SameValueNonNumber.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var SameValue = require('./SameValue'); - -// https://www.ecma-international.org/ecma-262/7.0/#sec-samevaluenonnumber - -module.exports = function SameValueNonNumber(x, y) { - if (typeof x === 'number' || typeof x !== typeof y) { - throw new $TypeError('SameValueNonNumber requires two non-number values of the same type.'); - } - return SameValue(x, y); -}; diff --git a/node_modules/es-abstract/2019/SameValueZero.js b/node_modules/es-abstract/2019/SameValueZero.js deleted file mode 100644 index 0dedcd2..0000000 --- a/node_modules/es-abstract/2019/SameValueZero.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var $isNaN = require('../helpers/isNaN'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-samevaluezero - -module.exports = function SameValueZero(x, y) { - return (x === y) || ($isNaN(x) && $isNaN(y)); -}; diff --git a/node_modules/es-abstract/2019/SecFromTime.js b/node_modules/es-abstract/2019/SecFromTime.js deleted file mode 100644 index 7190011..0000000 --- a/node_modules/es-abstract/2019/SecFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerSecond = timeConstants.msPerSecond; -var SecondsPerMinute = timeConstants.SecondsPerMinute; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function SecFromTime(t) { - return mod($floor(t / msPerSecond), SecondsPerMinute); -}; diff --git a/node_modules/es-abstract/2019/Set.js b/node_modules/es-abstract/2019/Set.js deleted file mode 100644 index 18ebd99..0000000 --- a/node_modules/es-abstract/2019/Set.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsPropertyKey = require('./IsPropertyKey'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-set-o-p-v-throw - -module.exports = function Set(O, P, V, Throw) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: `O` must be an Object'); - } - if (!IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: `P` must be a Property Key'); - } - if (Type(Throw) !== 'Boolean') { - throw new $TypeError('Assertion failed: `Throw` must be a Boolean'); - } - if (Throw) { - O[P] = V; // eslint-disable-line no-param-reassign - return true; - } else { - try { - O[P] = V; // eslint-disable-line no-param-reassign - } catch (e) { - return false; - } - } -}; diff --git a/node_modules/es-abstract/2019/SetFunctionName.js b/node_modules/es-abstract/2019/SetFunctionName.js deleted file mode 100644 index f93324a..0000000 --- a/node_modules/es-abstract/2019/SetFunctionName.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var has = require('has'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var getSymbolDescription = require('../helpers/getSymbolDescription'); - -var DefinePropertyOrThrow = require('./DefinePropertyOrThrow'); -var IsExtensible = require('./IsExtensible'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-setfunctionname - -module.exports = function SetFunctionName(F, name) { - if (typeof F !== 'function') { - throw new $TypeError('Assertion failed: `F` must be a function'); - } - if (!IsExtensible(F) || has(F, 'name')) { - throw new $TypeError('Assertion failed: `F` must be extensible, and must not have a `name` own property'); - } - var nameType = Type(name); - if (nameType !== 'Symbol' && nameType !== 'String') { - throw new $TypeError('Assertion failed: `name` must be a Symbol or a String'); - } - if (nameType === 'Symbol') { - var description = getSymbolDescription(name); - // eslint-disable-next-line no-param-reassign - name = typeof description === 'undefined' ? '' : '[' + description + ']'; - } - if (arguments.length > 2) { - var prefix = arguments[2]; - // eslint-disable-next-line no-param-reassign - name = prefix + ' ' + name; - } - return DefinePropertyOrThrow(F, 'name', { - '[[Value]]': name, - '[[Writable]]': false, - '[[Enumerable]]': false, - '[[Configurable]]': true - }); -}; diff --git a/node_modules/es-abstract/2019/SetIntegrityLevel.js b/node_modules/es-abstract/2019/SetIntegrityLevel.js deleted file mode 100644 index 3d5c81d..0000000 --- a/node_modules/es-abstract/2019/SetIntegrityLevel.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $TypeError = GetIntrinsic('%TypeError%'); -var $preventExtensions = GetIntrinsic('%Object.preventExtensions%'); -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); - -var forEach = require('../helpers/forEach'); - -var DefinePropertyOrThrow = require('./DefinePropertyOrThrow'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-setintegritylevel - -module.exports = function SetIntegrityLevel(O, level) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (level !== 'sealed' && level !== 'frozen') { - throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); - } - if (!$preventExtensions) { - throw new $SyntaxError('SetIntegrityLevel requires native `Object.preventExtensions` support'); - } - var status = $preventExtensions(O); - if (!status) { - return false; - } - if (!$gOPN) { - throw new $SyntaxError('SetIntegrityLevel requires native `Object.getOwnPropertyNames` support'); - } - var theKeys = $gOPN(O); - if (level === 'sealed') { - forEach(theKeys, function (k) { - DefinePropertyOrThrow(O, k, { configurable: false }); - }); - } else if (level === 'frozen') { - forEach(theKeys, function (k) { - var currentDesc = $gOPD(O, k); - if (typeof currentDesc !== 'undefined') { - var desc; - if (IsAccessorDescriptor(ToPropertyDescriptor(currentDesc))) { - desc = { configurable: false }; - } else { - desc = { configurable: false, writable: false }; - } - DefinePropertyOrThrow(O, k, desc); - } - }); - } - return true; -}; diff --git a/node_modules/es-abstract/2019/SpeciesConstructor.js b/node_modules/es-abstract/2019/SpeciesConstructor.js deleted file mode 100644 index 3cdcd74..0000000 --- a/node_modules/es-abstract/2019/SpeciesConstructor.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $species = GetIntrinsic('%Symbol.species%', true); -var $TypeError = GetIntrinsic('%TypeError%'); - -var IsConstructor = require('./IsConstructor'); -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-speciesconstructor - -module.exports = function SpeciesConstructor(O, defaultConstructor) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - var C = O.constructor; - if (typeof C === 'undefined') { - return defaultConstructor; - } - if (Type(C) !== 'Object') { - throw new $TypeError('O.constructor is not an Object'); - } - var S = $species ? C[$species] : void 0; - if (S == null) { - return defaultConstructor; - } - if (IsConstructor(S)) { - return S; - } - throw new $TypeError('no constructor found'); -}; diff --git a/node_modules/es-abstract/2019/StrictEqualityComparison.js b/node_modules/es-abstract/2019/StrictEqualityComparison.js deleted file mode 100644 index eea5df3..0000000 --- a/node_modules/es-abstract/2019/StrictEqualityComparison.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6 - -module.exports = function StrictEqualityComparison(x, y) { - var xType = Type(x); - var yType = Type(y); - if (xType !== yType) { - return false; - } - if (xType === 'Undefined' || xType === 'Null') { - return true; - } - return x === y; // shortcut for steps 4-7 -}; diff --git a/node_modules/es-abstract/2019/SymbolDescriptiveString.js b/node_modules/es-abstract/2019/SymbolDescriptiveString.js deleted file mode 100644 index 7bd8191..0000000 --- a/node_modules/es-abstract/2019/SymbolDescriptiveString.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('../helpers/callBound'); - -var $SymbolToString = callBound('Symbol.prototype.toString', true); - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-symboldescriptivestring - -module.exports = function SymbolDescriptiveString(sym) { - if (Type(sym) !== 'Symbol') { - throw new $TypeError('Assertion failed: `sym` must be a Symbol'); - } - return $SymbolToString(sym); -}; diff --git a/node_modules/es-abstract/2019/TestIntegrityLevel.js b/node_modules/es-abstract/2019/TestIntegrityLevel.js deleted file mode 100644 index 7a57397..0000000 --- a/node_modules/es-abstract/2019/TestIntegrityLevel.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = require('../helpers/getOwnPropertyDescriptor'); -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var every = require('../helpers/every'); - -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsExtensible = require('./IsExtensible'); -var ToPropertyDescriptor = require('./ToPropertyDescriptor'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-testintegritylevel - -module.exports = function TestIntegrityLevel(O, level) { - if (Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (level !== 'sealed' && level !== 'frozen') { - throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); - } - var status = IsExtensible(O); - if (status) { - return false; - } - var theKeys = $gOPN(O); - return theKeys.length === 0 || every(theKeys, function (k) { - var currentDesc = $gOPD(O, k); - if (typeof currentDesc !== 'undefined') { - if (currentDesc.configurable) { - return false; - } - if (level === 'frozen' && IsDataDescriptor(ToPropertyDescriptor(currentDesc)) && currentDesc.writable) { - return false; - } - } - return true; - }); -}; diff --git a/node_modules/es-abstract/2019/TimeClip.js b/node_modules/es-abstract/2019/TimeClip.js deleted file mode 100644 index 57aa08c..0000000 --- a/node_modules/es-abstract/2019/TimeClip.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Date = GetIntrinsic('%Date%'); -var $Number = GetIntrinsic('%Number%'); -var $abs = GetIntrinsic('%Math.abs%'); - -var $isFinite = require('../helpers/isFinite'); - -var ToNumber = require('./ToNumber'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.14 - -module.exports = function TimeClip(time) { - if (!$isFinite(time) || $abs(time) > 8.64e15) { - return NaN; - } - return $Number(new $Date(ToNumber(time))); -}; - diff --git a/node_modules/es-abstract/2019/TimeFromYear.js b/node_modules/es-abstract/2019/TimeFromYear.js deleted file mode 100644 index df646c3..0000000 --- a/node_modules/es-abstract/2019/TimeFromYear.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var msPerDay = require('../helpers/timeConstants').msPerDay; - -var DayFromYear = require('./DayFromYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function TimeFromYear(y) { - return msPerDay * DayFromYear(y); -}; diff --git a/node_modules/es-abstract/2019/TimeString.js b/node_modules/es-abstract/2019/TimeString.js deleted file mode 100644 index 87642eb..0000000 --- a/node_modules/es-abstract/2019/TimeString.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var $isNaN = require('../helpers/isNaN'); -var padTimeComponent = require('../helpers/padTimeComponent'); - -var HourFromTime = require('./HourFromTime'); -var MinFromTime = require('./MinFromTime'); -var SecFromTime = require('./SecFromTime'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/9.0/#sec-timestring - -module.exports = function TimeString(tv) { - if (Type(tv) !== 'Number' || $isNaN(tv)) { - throw new $TypeError('Assertion failed: `tv` must be a non-NaN Number'); - } - var hour = HourFromTime(tv); - var minute = MinFromTime(tv); - var second = SecFromTime(tv); - return padTimeComponent(hour) + ':' + padTimeComponent(minute) + ':' + padTimeComponent(second) + '\x20GMT'; -}; diff --git a/node_modules/es-abstract/2019/TimeWithinDay.js b/node_modules/es-abstract/2019/TimeWithinDay.js deleted file mode 100644 index c5b21d3..0000000 --- a/node_modules/es-abstract/2019/TimeWithinDay.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - -module.exports = function TimeWithinDay(t) { - return mod(t, msPerDay); -}; - diff --git a/node_modules/es-abstract/2019/ToBoolean.js b/node_modules/es-abstract/2019/ToBoolean.js deleted file mode 100644 index 65d8737..0000000 --- a/node_modules/es-abstract/2019/ToBoolean.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.2 - -module.exports = function ToBoolean(value) { return !!value; }; diff --git a/node_modules/es-abstract/2019/ToDateString.js b/node_modules/es-abstract/2019/ToDateString.js deleted file mode 100644 index 7a6d4c4..0000000 --- a/node_modules/es-abstract/2019/ToDateString.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $Date = GetIntrinsic('%Date%'); - -var $isNaN = require('../helpers/isNaN'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-todatestring - -module.exports = function ToDateString(tv) { - if (Type(tv) !== 'Number') { - throw new $TypeError('Assertion failed: `tv` must be a Number'); - } - if ($isNaN(tv)) { - return 'Invalid Date'; - } - return $Date(tv); -}; diff --git a/node_modules/es-abstract/2019/ToIndex.js b/node_modules/es-abstract/2019/ToIndex.js deleted file mode 100644 index a55398d..0000000 --- a/node_modules/es-abstract/2019/ToIndex.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $RangeError = GetIntrinsic('%RangeError%'); - -var ToInteger = require('./ToInteger'); -var ToLength = require('./ToLength'); -var SameValueZero = require('./SameValueZero'); - -// https://www.ecma-international.org/ecma-262/8.0/#sec-toindex - -module.exports = function ToIndex(value) { - if (typeof value === 'undefined') { - return 0; - } - var integerIndex = ToInteger(value); - if (integerIndex < 0) { - throw new $RangeError('index must be >= 0'); - } - var index = ToLength(integerIndex); - if (!SameValueZero(integerIndex, index)) { - throw new $RangeError('index must be >= 0 and < 2 ** 53 - 1'); - } - return index; -}; diff --git a/node_modules/es-abstract/2019/ToInt16.js b/node_modules/es-abstract/2019/ToInt16.js deleted file mode 100644 index 5a112c2..0000000 --- a/node_modules/es-abstract/2019/ToInt16.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var ToUint16 = require('./ToUint16'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toint16 - -module.exports = function ToInt16(argument) { - var int16bit = ToUint16(argument); - return int16bit >= 0x8000 ? int16bit - 0x10000 : int16bit; -}; diff --git a/node_modules/es-abstract/2019/ToInt32.js b/node_modules/es-abstract/2019/ToInt32.js deleted file mode 100644 index a8d2680..0000000 --- a/node_modules/es-abstract/2019/ToInt32.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.5 - -module.exports = function ToInt32(x) { - return ToNumber(x) >> 0; -}; diff --git a/node_modules/es-abstract/2019/ToInt8.js b/node_modules/es-abstract/2019/ToInt8.js deleted file mode 100644 index d103123..0000000 --- a/node_modules/es-abstract/2019/ToInt8.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var ToUint8 = require('./ToUint8'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toint8 - -module.exports = function ToInt8(argument) { - var int8bit = ToUint8(argument); - return int8bit >= 0x80 ? int8bit - 0x100 : int8bit; -}; diff --git a/node_modules/es-abstract/2019/ToInteger.js b/node_modules/es-abstract/2019/ToInteger.js deleted file mode 100644 index 16f7db9..0000000 --- a/node_modules/es-abstract/2019/ToInteger.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var ES5ToInteger = require('../5/ToInteger'); - -var ToNumber = require('./ToNumber'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tointeger - -module.exports = function ToInteger(value) { - var number = ToNumber(value); - return ES5ToInteger(number); -}; diff --git a/node_modules/es-abstract/2019/ToLength.js b/node_modules/es-abstract/2019/ToLength.js deleted file mode 100644 index 1bef9be..0000000 --- a/node_modules/es-abstract/2019/ToLength.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger'); - -var ToInteger = require('./ToInteger'); - -module.exports = function ToLength(argument) { - var len = ToInteger(argument); - if (len <= 0) { return 0; } // includes converting -0 to +0 - if (len > MAX_SAFE_INTEGER) { return MAX_SAFE_INTEGER; } - return len; -}; diff --git a/node_modules/es-abstract/2019/ToNumber.js b/node_modules/es-abstract/2019/ToNumber.js deleted file mode 100644 index 7a3cdc8..0000000 --- a/node_modules/es-abstract/2019/ToNumber.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $Number = GetIntrinsic('%Number%'); -var $RegExp = GetIntrinsic('%RegExp%'); -var $parseInteger = GetIntrinsic('%parseInt%'); - -var callBound = require('../helpers/callBound'); -var regexTester = require('../helpers/regexTester'); -var isPrimitive = require('../helpers/isPrimitive'); - -var $strSlice = callBound('String.prototype.slice'); -var isBinary = regexTester(/^0b[01]+$/i); -var isOctal = regexTester(/^0o[0-7]+$/i); -var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i); -var nonWS = ['\u0085', '\u200b', '\ufffe'].join(''); -var nonWSregex = new $RegExp('[' + nonWS + ']', 'g'); -var hasNonWS = regexTester(nonWSregex); - -// whitespace from: https://es5.github.io/#x15.5.4.20 -// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 -var ws = [ - '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', - '\u2029\uFEFF' -].join(''); -var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g'); -var $replace = callBound('String.prototype.replace'); -var $trim = function (value) { - return $replace(value, trimRegex, ''); -}; - -var ToPrimitive = require('./ToPrimitive'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tonumber - -module.exports = function ToNumber(argument) { - var value = isPrimitive(argument) ? argument : ToPrimitive(argument, $Number); - if (typeof value === 'symbol') { - throw new $TypeError('Cannot convert a Symbol value to a number'); - } - if (typeof value === 'string') { - if (isBinary(value)) { - return ToNumber($parseInteger($strSlice(value, 2), 2)); - } else if (isOctal(value)) { - return ToNumber($parseInteger($strSlice(value, 2), 8)); - } else if (hasNonWS(value) || isInvalidHexLiteral(value)) { - return NaN; - } else { - var trimmed = $trim(value); - if (trimmed !== value) { - return ToNumber(trimmed); - } - } - } - return $Number(value); -}; diff --git a/node_modules/es-abstract/2019/ToObject.js b/node_modules/es-abstract/2019/ToObject.js deleted file mode 100644 index 50d5b94..0000000 --- a/node_modules/es-abstract/2019/ToObject.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Object = GetIntrinsic('%Object%'); - -var RequireObjectCoercible = require('./RequireObjectCoercible'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toobject - -module.exports = function ToObject(value) { - RequireObjectCoercible(value); - return $Object(value); -}; diff --git a/node_modules/es-abstract/2019/ToPrimitive.js b/node_modules/es-abstract/2019/ToPrimitive.js deleted file mode 100644 index 81c655d..0000000 --- a/node_modules/es-abstract/2019/ToPrimitive.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var toPrimitive = require('es-to-primitive/es2015'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive - -module.exports = function ToPrimitive(input) { - if (arguments.length > 1) { - return toPrimitive(input, arguments[1]); - } - return toPrimitive(input); -}; diff --git a/node_modules/es-abstract/2019/ToPropertyDescriptor.js b/node_modules/es-abstract/2019/ToPropertyDescriptor.js deleted file mode 100644 index 38e536e..0000000 --- a/node_modules/es-abstract/2019/ToPropertyDescriptor.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -var has = require('has'); - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Type = require('./Type'); -var ToBoolean = require('./ToBoolean'); -var IsCallable = require('./IsCallable'); - -// https://ecma-international.org/ecma-262/5.1/#sec-8.10.5 - -module.exports = function ToPropertyDescriptor(Obj) { - if (Type(Obj) !== 'Object') { - throw new $TypeError('ToPropertyDescriptor requires an object'); - } - - var desc = {}; - if (has(Obj, 'enumerable')) { - desc['[[Enumerable]]'] = ToBoolean(Obj.enumerable); - } - if (has(Obj, 'configurable')) { - desc['[[Configurable]]'] = ToBoolean(Obj.configurable); - } - if (has(Obj, 'value')) { - desc['[[Value]]'] = Obj.value; - } - if (has(Obj, 'writable')) { - desc['[[Writable]]'] = ToBoolean(Obj.writable); - } - if (has(Obj, 'get')) { - var getter = Obj.get; - if (typeof getter !== 'undefined' && !IsCallable(getter)) { - throw new TypeError('getter must be a function'); - } - desc['[[Get]]'] = getter; - } - if (has(Obj, 'set')) { - var setter = Obj.set; - if (typeof setter !== 'undefined' && !IsCallable(setter)) { - throw new $TypeError('setter must be a function'); - } - desc['[[Set]]'] = setter; - } - - if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) { - throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute'); - } - return desc; -}; diff --git a/node_modules/es-abstract/2019/ToPropertyKey.js b/node_modules/es-abstract/2019/ToPropertyKey.js deleted file mode 100644 index 38f40dd..0000000 --- a/node_modules/es-abstract/2019/ToPropertyKey.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $String = GetIntrinsic('%String%'); - -var ToPrimitive = require('./ToPrimitive'); -var ToString = require('./ToString'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-topropertykey - -module.exports = function ToPropertyKey(argument) { - var key = ToPrimitive(argument, $String); - return typeof key === 'symbol' ? key : ToString(key); -}; diff --git a/node_modules/es-abstract/2019/ToString.js b/node_modules/es-abstract/2019/ToString.js deleted file mode 100644 index a345431..0000000 --- a/node_modules/es-abstract/2019/ToString.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $String = GetIntrinsic('%String%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tostring - -module.exports = function ToString(argument) { - if (typeof argument === 'symbol') { - throw new $TypeError('Cannot convert a Symbol value to a string'); - } - return $String(argument); -}; diff --git a/node_modules/es-abstract/2019/ToUint16.js b/node_modules/es-abstract/2019/ToUint16.js deleted file mode 100644 index c8a408b..0000000 --- a/node_modules/es-abstract/2019/ToUint16.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var $sign = require('../helpers/sign'); -var $mod = require('../helpers/mod'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.7 - -module.exports = function ToUint16(value) { - var number = ToNumber(value); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = $sign(number) * $floor($abs(number)); - return $mod(posInt, 0x10000); -}; diff --git a/node_modules/es-abstract/2019/ToUint32.js b/node_modules/es-abstract/2019/ToUint32.js deleted file mode 100644 index 3660f62..0000000 --- a/node_modules/es-abstract/2019/ToUint32.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.6 - -module.exports = function ToUint32(x) { - return ToNumber(x) >>> 0; -}; diff --git a/node_modules/es-abstract/2019/ToUint8.js b/node_modules/es-abstract/2019/ToUint8.js deleted file mode 100644 index bf84753..0000000 --- a/node_modules/es-abstract/2019/ToUint8.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var $sign = require('../helpers/sign'); -var $mod = require('../helpers/mod'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -module.exports = function ToUint8(argument) { - var number = ToNumber(argument); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = $sign(number) * $floor($abs(number)); - return $mod(posInt, 0x100); -}; diff --git a/node_modules/es-abstract/2019/ToUint8Clamp.js b/node_modules/es-abstract/2019/ToUint8Clamp.js deleted file mode 100644 index c7f9f56..0000000 --- a/node_modules/es-abstract/2019/ToUint8Clamp.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); - -var $floor = $Math.floor; - -// https://www.ecma-international.org/ecma-262/6.0/#sec-touint8clamp - -module.exports = function ToUint8Clamp(argument) { - var number = ToNumber(argument); - if ($isNaN(number) || number <= 0) { return 0; } - if (number >= 0xFF) { return 0xFF; } - var f = $floor(argument); - if (f + 0.5 < number) { return f + 1; } - if (number < f + 0.5) { return f; } - if (f % 2 !== 0) { return f + 1; } - return f; -}; diff --git a/node_modules/es-abstract/2019/TrimString.js b/node_modules/es-abstract/2019/TrimString.js deleted file mode 100644 index 32d4675..0000000 --- a/node_modules/es-abstract/2019/TrimString.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -var trimStart = require('string.prototype.trimleft'); -var trimEnd = require('string.prototype.trimright'); - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var RequireObjectCoercible = require('./RequireObjectCoercible'); -var ToString = require('./ToString'); - -// https://ecma-international.org/ecma-262/10.0/#sec-trimstring - -module.exports = function TrimString(string, where) { - var str = RequireObjectCoercible(string); - var S = ToString(str); - var T; - if (where === 'start') { - T = trimStart(S); - } else if (where === 'end') { - T = trimEnd(S); - } else if (where === 'start+end') { - T = trimStart(trimEnd(S)); - } else { - throw new $TypeError('Assertion failed: invalid `where` value; must be "start", "end", or "start+end"'); - } - return T; -}; diff --git a/node_modules/es-abstract/2019/Type.js b/node_modules/es-abstract/2019/Type.js deleted file mode 100644 index 6c99376..0000000 --- a/node_modules/es-abstract/2019/Type.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var ES5Type = require('../5/Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-tostring - -module.exports = function Type(x) { - if (typeof x === 'symbol') { - return 'Symbol'; - } - return ES5Type(x); -}; diff --git a/node_modules/es-abstract/2019/ValidateAndApplyPropertyDescriptor.js b/node_modules/es-abstract/2019/ValidateAndApplyPropertyDescriptor.js deleted file mode 100644 index d4b9007..0000000 --- a/node_modules/es-abstract/2019/ValidateAndApplyPropertyDescriptor.js +++ /dev/null @@ -1,170 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var DefineOwnProperty = require('../helpers/DefineOwnProperty'); -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); -var isSamePropertyDescriptor = require('../helpers/isSamePropertyDescriptor'); - -var FromPropertyDescriptor = require('./FromPropertyDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsGenericDescriptor = require('./IsGenericDescriptor'); -var IsPropertyKey = require('./IsPropertyKey'); -var SameValue = require('./SameValue'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/6.0/#sec-validateandapplypropertydescriptor -// https://www.ecma-international.org/ecma-262/8.0/#sec-validateandapplypropertydescriptor - -// eslint-disable-next-line max-lines-per-function, max-statements, max-params -module.exports = function ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current) { - // this uses the ES2017+ logic, since it fixes a number of bugs in the ES2015 logic. - var oType = Type(O); - if (oType !== 'Undefined' && oType !== 'Object') { - throw new $TypeError('Assertion failed: O must be undefined or an Object'); - } - if (Type(extensible) !== 'Boolean') { - throw new $TypeError('Assertion failed: extensible must be a Boolean'); - } - if (!isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (Type(current) !== 'Undefined' && !isPropertyDescriptor({ - Type: Type, - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor - }, current)) { - throw new $TypeError('Assertion failed: current must be a Property Descriptor, or undefined'); - } - if (oType !== 'Undefined' && !IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: if O is not undefined, P must be a Property Key'); - } - if (Type(current) === 'Undefined') { - if (!extensible) { - return false; - } - if (IsGenericDescriptor(Desc) || IsDataDescriptor(Desc)) { - if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': Desc['[[Configurable]]'], - '[[Enumerable]]': Desc['[[Enumerable]]'], - '[[Value]]': Desc['[[Value]]'], - '[[Writable]]': Desc['[[Writable]]'] - } - ); - } - } else { - if (!IsAccessorDescriptor(Desc)) { - throw new $TypeError('Assertion failed: Desc is not an accessor descriptor'); - } - if (oType !== 'Undefined') { - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); - } - } - return true; - } - if (IsGenericDescriptor(Desc) && !('[[Configurable]]' in Desc) && !('[[Enumerable]]' in Desc)) { - return true; - } - if (isSamePropertyDescriptor({ SameValue: SameValue }, Desc, current)) { - return true; // removed by ES2017, but should still be correct - } - // "if every field in Desc is absent, return true" can't really match the assertion that it's a Property Descriptor - if (!current['[[Configurable]]']) { - if (Desc['[[Configurable]]']) { - return false; - } - if ('[[Enumerable]]' in Desc && !Desc['[[Enumerable]]'] === !!current['[[Enumerable]]']) { - return false; - } - } - if (IsGenericDescriptor(Desc)) { - // no further validation is required. - } else if (IsDataDescriptor(current) !== IsDataDescriptor(Desc)) { - if (!current['[[Configurable]]']) { - return false; - } - if (IsDataDescriptor(current)) { - if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': current['[[Configurable]]'], - '[[Enumerable]]': current['[[Enumerable]]'], - '[[Get]]': undefined - } - ); - } - } else if (oType !== 'Undefined') { - DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - { - '[[Configurable]]': current['[[Configurable]]'], - '[[Enumerable]]': current['[[Enumerable]]'], - '[[Value]]': undefined - } - ); - } - } else if (IsDataDescriptor(current) && IsDataDescriptor(Desc)) { - if (!current['[[Configurable]]'] && !current['[[Writable]]']) { - if ('[[Writable]]' in Desc && Desc['[[Writable]]']) { - return false; - } - if ('[[Value]]' in Desc && !SameValue(Desc['[[Value]]'], current['[[Value]]'])) { - return false; - } - return true; - } - } else if (IsAccessorDescriptor(current) && IsAccessorDescriptor(Desc)) { - if (!current['[[Configurable]]']) { - if ('[[Set]]' in Desc && !SameValue(Desc['[[Set]]'], current['[[Set]]'])) { - return false; - } - if ('[[Get]]' in Desc && !SameValue(Desc['[[Get]]'], current['[[Get]]'])) { - return false; - } - return true; - } - } else { - throw new $TypeError('Assertion failed: current and Desc are not both data, both accessors, or one accessor and one data.'); - } - if (oType !== 'Undefined') { - return DefineOwnProperty( - IsDataDescriptor, - SameValue, - FromPropertyDescriptor, - O, - P, - Desc - ); - } - return true; -}; diff --git a/node_modules/es-abstract/2019/WeekDay.js b/node_modules/es-abstract/2019/WeekDay.js deleted file mode 100644 index 2973e02..0000000 --- a/node_modules/es-abstract/2019/WeekDay.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -var Day = require('./Day'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.6 - -module.exports = function WeekDay(t) { - return mod(Day(t) + 4, 7); -}; diff --git a/node_modules/es-abstract/2019/YearFromTime.js b/node_modules/es-abstract/2019/YearFromTime.js deleted file mode 100644 index ff5339f..0000000 --- a/node_modules/es-abstract/2019/YearFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Date = GetIntrinsic('%Date%'); - -var callBound = require('../helpers/callBound'); - -var $getUTCFullYear = callBound('Date.prototype.getUTCFullYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function YearFromTime(t) { - // largest y such that this.TimeFromYear(y) <= t - return $getUTCFullYear(new $Date(t)); -}; diff --git a/node_modules/es-abstract/2019/modulo.js b/node_modules/es-abstract/2019/modulo.js deleted file mode 100644 index bc04c06..0000000 --- a/node_modules/es-abstract/2019/modulo.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -// https://ecma-international.org/ecma-262/5.1/#sec-5.2 - -module.exports = function modulo(x, y) { - return mod(x, y); -}; diff --git a/node_modules/es-abstract/2019/msFromTime.js b/node_modules/es-abstract/2019/msFromTime.js deleted file mode 100644 index c31eda0..0000000 --- a/node_modules/es-abstract/2019/msFromTime.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); -var msPerSecond = require('../helpers/timeConstants').msPerSecond; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function msFromTime(t) { - return mod(t, msPerSecond); -}; diff --git a/node_modules/es-abstract/2019/thisBooleanValue.js b/node_modules/es-abstract/2019/thisBooleanValue.js deleted file mode 100644 index 3ffac9c..0000000 --- a/node_modules/es-abstract/2019/thisBooleanValue.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var $BooleanValueOf = require('../helpers/callBound')('Boolean.prototype.valueOf'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-boolean-prototype-object - -module.exports = function thisBooleanValue(value) { - if (Type(value) === 'Boolean') { - return value; - } - - return $BooleanValueOf(value); -}; diff --git a/node_modules/es-abstract/2019/thisNumberValue.js b/node_modules/es-abstract/2019/thisNumberValue.js deleted file mode 100644 index 0345e52..0000000 --- a/node_modules/es-abstract/2019/thisNumberValue.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var Type = require('./Type'); - -var $NumberValueOf = callBound('Number.prototype.valueOf'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-number-prototype-object - -module.exports = function thisNumberValue(value) { - if (Type(value) === 'Number') { - return value; - } - - return $NumberValueOf(value); -}; - diff --git a/node_modules/es-abstract/2019/thisStringValue.js b/node_modules/es-abstract/2019/thisStringValue.js deleted file mode 100644 index 3b99b6e..0000000 --- a/node_modules/es-abstract/2019/thisStringValue.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var $StringValueOf = require('../helpers/callBound')('String.prototype.valueOf'); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-string-prototype-object - -module.exports = function thisStringValue(value) { - if (Type(value) === 'String') { - return value; - } - - return $StringValueOf(value); -}; diff --git a/node_modules/es-abstract/2019/thisSymbolValue.js b/node_modules/es-abstract/2019/thisSymbolValue.js deleted file mode 100644 index 3c3b347..0000000 --- a/node_modules/es-abstract/2019/thisSymbolValue.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var $SymbolValueOf = callBound('Symbol.prototype.valueOf', true); - -var Type = require('./Type'); - -// https://ecma-international.org/ecma-262/9.0/#sec-thissymbolvalue - -module.exports = function thisSymbolValue(value) { - if (!$SymbolValueOf) { - throw new SyntaxError('Symbols are not supported; thisSymbolValue requires that `value` be a Symbol or a Symbol object'); - } - if (Type(value) === 'Symbol') { - return value; - } - return $SymbolValueOf(value); -}; diff --git a/node_modules/es-abstract/2019/thisTimeValue.js b/node_modules/es-abstract/2019/thisTimeValue.js deleted file mode 100644 index a9a47ac..0000000 --- a/node_modules/es-abstract/2019/thisTimeValue.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('../2018/thisTimeValue'); diff --git a/node_modules/es-abstract/5/AbstractEqualityComparison.js b/node_modules/es-abstract/5/AbstractEqualityComparison.js deleted file mode 100644 index e55c764..0000000 --- a/node_modules/es-abstract/5/AbstractEqualityComparison.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); -var ToPrimitive = require('./ToPrimitive'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3 - -module.exports = function AbstractEqualityComparison(x, y) { - var xType = Type(x); - var yType = Type(y); - if (xType === yType) { - return x === y; // ES6+ specified this shortcut anyways. - } - if (x == null && y == null) { - return true; - } - if (xType === 'Number' && yType === 'String') { - return AbstractEqualityComparison(x, ToNumber(y)); - } - if (xType === 'String' && yType === 'Number') { - return AbstractEqualityComparison(ToNumber(x), y); - } - if (xType === 'Boolean') { - return AbstractEqualityComparison(ToNumber(x), y); - } - if (yType === 'Boolean') { - return AbstractEqualityComparison(x, ToNumber(y)); - } - if ((xType === 'String' || xType === 'Number') && yType === 'Object') { - return AbstractEqualityComparison(x, ToPrimitive(y)); - } - if (xType === 'Object' && (yType === 'String' || yType === 'Number')) { - return AbstractEqualityComparison(ToPrimitive(x), y); - } - return false; -}; diff --git a/node_modules/es-abstract/5/AbstractRelationalComparison.js b/node_modules/es-abstract/5/AbstractRelationalComparison.js deleted file mode 100644 index bc7ca83..0000000 --- a/node_modules/es-abstract/5/AbstractRelationalComparison.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Number = GetIntrinsic('%Number%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var isPrefixOf = require('../helpers/isPrefixOf'); - -var ToNumber = require('./ToNumber'); -var ToPrimitive = require('./ToPrimitive'); -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5 - -// eslint-disable-next-line max-statements -module.exports = function AbstractRelationalComparison(x, y, LeftFirst) { - if (Type(LeftFirst) !== 'Boolean') { - throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean'); - } - var px; - var py; - if (LeftFirst) { - px = ToPrimitive(x, $Number); - py = ToPrimitive(y, $Number); - } else { - py = ToPrimitive(y, $Number); - px = ToPrimitive(x, $Number); - } - var bothStrings = Type(px) === 'String' && Type(py) === 'String'; - if (!bothStrings) { - var nx = ToNumber(px); - var ny = ToNumber(py); - if ($isNaN(nx) || $isNaN(ny)) { - return undefined; - } - if ($isFinite(nx) && $isFinite(ny) && nx === ny) { - return false; - } - if (nx === 0 && ny === 0) { - return false; - } - if (nx === Infinity) { - return false; - } - if (ny === Infinity) { - return true; - } - if (ny === -Infinity) { - return false; - } - if (nx === -Infinity) { - return true; - } - return nx < ny; // by now, these are both nonzero, finite, and not equal - } - if (isPrefixOf(py, px)) { - return false; - } - if (isPrefixOf(px, py)) { - return true; - } - return px < py; // both strings, neither a prefix of the other. shortcut for steps c-f -}; diff --git a/node_modules/es-abstract/5/CheckObjectCoercible.js b/node_modules/es-abstract/5/CheckObjectCoercible.js deleted file mode 100644 index f02b289..0000000 --- a/node_modules/es-abstract/5/CheckObjectCoercible.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.10 - -module.exports = function CheckObjectCoercible(value, optMessage) { - if (value == null) { - throw new $TypeError(optMessage || ('Cannot call method on ' + value)); - } - return value; -}; diff --git a/node_modules/es-abstract/5/DateFromTime.js b/node_modules/es-abstract/5/DateFromTime.js deleted file mode 100644 index 962dba1..0000000 --- a/node_modules/es-abstract/5/DateFromTime.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $EvalError = GetIntrinsic('%EvalError%'); - -var DayWithinYear = require('./DayWithinYear'); -var InLeapYear = require('./InLeapYear'); -var MonthFromTime = require('./MonthFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.5 - -module.exports = function DateFromTime(t) { - var m = MonthFromTime(t); - var d = DayWithinYear(t); - if (m === 0) { - return d + 1; - } - if (m === 1) { - return d - 30; - } - var leap = InLeapYear(t); - if (m === 2) { - return d - 58 - leap; - } - if (m === 3) { - return d - 89 - leap; - } - if (m === 4) { - return d - 119 - leap; - } - if (m === 5) { - return d - 150 - leap; - } - if (m === 6) { - return d - 180 - leap; - } - if (m === 7) { - return d - 211 - leap; - } - if (m === 8) { - return d - 242 - leap; - } - if (m === 9) { - return d - 272 - leap; - } - if (m === 10) { - return d - 303 - leap; - } - if (m === 11) { - return d - 333 - leap; - } - throw new $EvalError('Assertion failed: MonthFromTime returned an impossible value: ' + m); -}; diff --git a/node_modules/es-abstract/5/Day.js b/node_modules/es-abstract/5/Day.js deleted file mode 100644 index 00df813..0000000 --- a/node_modules/es-abstract/5/Day.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - -module.exports = function Day(t) { - return $floor(t / msPerDay); -}; diff --git a/node_modules/es-abstract/5/DayFromYear.js b/node_modules/es-abstract/5/DayFromYear.js deleted file mode 100644 index 08dd5af..0000000 --- a/node_modules/es-abstract/5/DayFromYear.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function DayFromYear(y) { - return (365 * (y - 1970)) + $floor((y - 1969) / 4) - $floor((y - 1901) / 100) + $floor((y - 1601) / 400); -}; - diff --git a/node_modules/es-abstract/5/DayWithinYear.js b/node_modules/es-abstract/5/DayWithinYear.js deleted file mode 100644 index cfc4002..0000000 --- a/node_modules/es-abstract/5/DayWithinYear.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var Day = require('./Day'); -var DayFromYear = require('./DayFromYear'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - -module.exports = function DayWithinYear(t) { - return Day(t) - DayFromYear(YearFromTime(t)); -}; diff --git a/node_modules/es-abstract/5/DaysInYear.js b/node_modules/es-abstract/5/DaysInYear.js deleted file mode 100644 index db32251..0000000 --- a/node_modules/es-abstract/5/DaysInYear.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function DaysInYear(y) { - if (mod(y, 4) !== 0) { - return 365; - } - if (mod(y, 100) !== 0) { - return 366; - } - if (mod(y, 400) !== 0) { - return 365; - } - return 366; -}; diff --git a/node_modules/es-abstract/5/FromPropertyDescriptor.js b/node_modules/es-abstract/5/FromPropertyDescriptor.js deleted file mode 100644 index a3cefbe..0000000 --- a/node_modules/es-abstract/5/FromPropertyDescriptor.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Type = require('./Type'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); - -var assertRecord = require('../helpers/assertRecord'); - -// https://ecma-international.org/ecma-262/5.1/#sec-8.10.4 - -module.exports = function FromPropertyDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return Desc; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (IsDataDescriptor(Desc)) { - return { - value: Desc['[[Value]]'], - writable: !!Desc['[[Writable]]'], - enumerable: !!Desc['[[Enumerable]]'], - configurable: !!Desc['[[Configurable]]'] - }; - } else if (IsAccessorDescriptor(Desc)) { - return { - get: Desc['[[Get]]'], - set: Desc['[[Set]]'], - enumerable: !!Desc['[[Enumerable]]'], - configurable: !!Desc['[[Configurable]]'] - }; - } else { - throw new $TypeError('FromPropertyDescriptor must be called with a fully populated Property Descriptor'); - } -}; diff --git a/node_modules/es-abstract/5/HourFromTime.js b/node_modules/es-abstract/5/HourFromTime.js deleted file mode 100644 index 957ce32..0000000 --- a/node_modules/es-abstract/5/HourFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerHour = timeConstants.msPerHour; -var HoursPerDay = timeConstants.HoursPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function HourFromTime(t) { - return mod($floor(t / msPerHour), HoursPerDay); -}; diff --git a/node_modules/es-abstract/5/InLeapYear.js b/node_modules/es-abstract/5/InLeapYear.js deleted file mode 100644 index 38ba8fd..0000000 --- a/node_modules/es-abstract/5/InLeapYear.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $EvalError = GetIntrinsic('%EvalError%'); - -var DaysInYear = require('./DaysInYear'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function InLeapYear(t) { - var days = DaysInYear(YearFromTime(t)); - if (days === 365) { - return 0; - } - if (days === 366) { - return 1; - } - throw new $EvalError('Assertion failed: there are not 365 or 366 days in a year, got: ' + days); -}; diff --git a/node_modules/es-abstract/5/IsAccessorDescriptor.js b/node_modules/es-abstract/5/IsAccessorDescriptor.js deleted file mode 100644 index 561382a..0000000 --- a/node_modules/es-abstract/5/IsAccessorDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var has = require('has'); - -var Type = require('./Type'); - -var assertRecord = require('../helpers/assertRecord'); - -// https://ecma-international.org/ecma-262/5.1/#sec-8.10.1 - -module.exports = function IsAccessorDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) { - return false; - } - - return true; -}; diff --git a/node_modules/es-abstract/5/IsCallable.js b/node_modules/es-abstract/5/IsCallable.js deleted file mode 100644 index e4bfa36..0000000 --- a/node_modules/es-abstract/5/IsCallable.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.11 - -module.exports = require('is-callable'); diff --git a/node_modules/es-abstract/5/IsDataDescriptor.js b/node_modules/es-abstract/5/IsDataDescriptor.js deleted file mode 100644 index 783e2dc..0000000 --- a/node_modules/es-abstract/5/IsDataDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var has = require('has'); - -var Type = require('./Type'); - -var assertRecord = require('../helpers/assertRecord'); - -// https://ecma-international.org/ecma-262/5.1/#sec-8.10.2 - -module.exports = function IsDataDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) { - return false; - } - - return true; -}; diff --git a/node_modules/es-abstract/5/IsGenericDescriptor.js b/node_modules/es-abstract/5/IsGenericDescriptor.js deleted file mode 100644 index 93340e9..0000000 --- a/node_modules/es-abstract/5/IsGenericDescriptor.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var Type = require('./Type'); - -var assertRecord = require('../helpers/assertRecord'); - -// https://ecma-international.org/ecma-262/5.1/#sec-8.10.3 - -module.exports = function IsGenericDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(Type, 'Property Descriptor', 'Desc', Desc); - - if (!IsAccessorDescriptor(Desc) && !IsDataDescriptor(Desc)) { - return true; - } - - return false; -}; diff --git a/node_modules/es-abstract/5/IsPropertyDescriptor.js b/node_modules/es-abstract/5/IsPropertyDescriptor.js deleted file mode 100644 index 2a96c63..0000000 --- a/node_modules/es-abstract/5/IsPropertyDescriptor.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var isPropertyDescriptor = require('../helpers/isPropertyDescriptor'); - -var Type = require('./Type'); -var IsDataDescriptor = require('./IsDataDescriptor'); -var IsAccessorDescriptor = require('./IsAccessorDescriptor'); - -// https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type - -module.exports = function IsPropertyDescriptor(Desc) { - return isPropertyDescriptor({ - IsDataDescriptor: IsDataDescriptor, - IsAccessorDescriptor: IsAccessorDescriptor, - Type: Type - }, Desc); -}; diff --git a/node_modules/es-abstract/5/MakeDate.js b/node_modules/es-abstract/5/MakeDate.js deleted file mode 100644 index 7b592d1..0000000 --- a/node_modules/es-abstract/5/MakeDate.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $isFinite = require('../helpers/isFinite'); -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.13 - -module.exports = function MakeDate(day, time) { - if (!$isFinite(day) || !$isFinite(time)) { - return NaN; - } - return (day * msPerDay) + time; -}; diff --git a/node_modules/es-abstract/5/MakeDay.js b/node_modules/es-abstract/5/MakeDay.js deleted file mode 100644 index f1ab810..0000000 --- a/node_modules/es-abstract/5/MakeDay.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); -var $DateUTC = GetIntrinsic('%Date.UTC%'); - -var mod = require('../helpers/mod'); -var $isFinite = require('../helpers/isFinite'); - -var DateFromTime = require('./DateFromTime'); -var Day = require('./Day'); -var MonthFromTime = require('./MonthFromTime'); -var ToInteger = require('./ToInteger'); -var YearFromTime = require('./YearFromTime'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.12 - -module.exports = function MakeDay(year, month, date) { - if (!$isFinite(year) || !$isFinite(month) || !$isFinite(date)) { - return NaN; - } - var y = ToInteger(year); - var m = ToInteger(month); - var dt = ToInteger(date); - var ym = y + $floor(m / 12); - var mn = mod(m, 12); - var t = $DateUTC(ym, mn, 1); - if (YearFromTime(t) !== ym || MonthFromTime(t) !== mn || DateFromTime(t) !== 1) { - return NaN; - } - return Day(t) + dt - 1; -}; diff --git a/node_modules/es-abstract/5/MakeTime.js b/node_modules/es-abstract/5/MakeTime.js deleted file mode 100644 index e118500..0000000 --- a/node_modules/es-abstract/5/MakeTime.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var $isFinite = require('../helpers/isFinite'); -var timeConstants = require('../helpers/timeConstants'); -var msPerSecond = timeConstants.msPerSecond; -var msPerMinute = timeConstants.msPerMinute; -var msPerHour = timeConstants.msPerHour; - -var ToInteger = require('./ToInteger'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.11 - -module.exports = function MakeTime(hour, min, sec, ms) { - if (!$isFinite(hour) || !$isFinite(min) || !$isFinite(sec) || !$isFinite(ms)) { - return NaN; - } - var h = ToInteger(hour); - var m = ToInteger(min); - var s = ToInteger(sec); - var milli = ToInteger(ms); - var t = (h * msPerHour) + (m * msPerMinute) + (s * msPerSecond) + milli; - return t; -}; diff --git a/node_modules/es-abstract/5/MinFromTime.js b/node_modules/es-abstract/5/MinFromTime.js deleted file mode 100644 index e80e191..0000000 --- a/node_modules/es-abstract/5/MinFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerMinute = timeConstants.msPerMinute; -var MinutesPerHour = timeConstants.MinutesPerHour; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function MinFromTime(t) { - return mod($floor(t / msPerMinute), MinutesPerHour); -}; diff --git a/node_modules/es-abstract/5/MonthFromTime.js b/node_modules/es-abstract/5/MonthFromTime.js deleted file mode 100644 index 4f120f2..0000000 --- a/node_modules/es-abstract/5/MonthFromTime.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -var DayWithinYear = require('./DayWithinYear'); -var InLeapYear = require('./InLeapYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - -module.exports = function MonthFromTime(t) { - var day = DayWithinYear(t); - if (0 <= day && day < 31) { - return 0; - } - var leap = InLeapYear(t); - if (31 <= day && day < (59 + leap)) { - return 1; - } - if ((59 + leap) <= day && day < (90 + leap)) { - return 2; - } - if ((90 + leap) <= day && day < (120 + leap)) { - return 3; - } - if ((120 + leap) <= day && day < (151 + leap)) { - return 4; - } - if ((151 + leap) <= day && day < (181 + leap)) { - return 5; - } - if ((181 + leap) <= day && day < (212 + leap)) { - return 6; - } - if ((212 + leap) <= day && day < (243 + leap)) { - return 7; - } - if ((243 + leap) <= day && day < (273 + leap)) { - return 8; - } - if ((273 + leap) <= day && day < (304 + leap)) { - return 9; - } - if ((304 + leap) <= day && day < (334 + leap)) { - return 10; - } - if ((334 + leap) <= day && day < (365 + leap)) { - return 11; - } -}; diff --git a/node_modules/es-abstract/5/SameValue.js b/node_modules/es-abstract/5/SameValue.js deleted file mode 100644 index 47c936d..0000000 --- a/node_modules/es-abstract/5/SameValue.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $isNaN = require('../helpers/isNaN'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.12 - -module.exports = function SameValue(x, y) { - if (x === y) { // 0 === -0, but they are not identical. - if (x === 0) { return 1 / x === 1 / y; } - return true; - } - return $isNaN(x) && $isNaN(y); -}; diff --git a/node_modules/es-abstract/5/SecFromTime.js b/node_modules/es-abstract/5/SecFromTime.js deleted file mode 100644 index 7190011..0000000 --- a/node_modules/es-abstract/5/SecFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $floor = GetIntrinsic('%Math.floor%'); - -var mod = require('../helpers/mod'); -var timeConstants = require('../helpers/timeConstants'); -var msPerSecond = timeConstants.msPerSecond; -var SecondsPerMinute = timeConstants.SecondsPerMinute; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function SecFromTime(t) { - return mod($floor(t / msPerSecond), SecondsPerMinute); -}; diff --git a/node_modules/es-abstract/5/StrictEqualityComparison.js b/node_modules/es-abstract/5/StrictEqualityComparison.js deleted file mode 100644 index eea5df3..0000000 --- a/node_modules/es-abstract/5/StrictEqualityComparison.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var Type = require('./Type'); - -// https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6 - -module.exports = function StrictEqualityComparison(x, y) { - var xType = Type(x); - var yType = Type(y); - if (xType !== yType) { - return false; - } - if (xType === 'Undefined' || xType === 'Null') { - return true; - } - return x === y; // shortcut for steps 4-7 -}; diff --git a/node_modules/es-abstract/5/TimeClip.js b/node_modules/es-abstract/5/TimeClip.js deleted file mode 100644 index 57aa08c..0000000 --- a/node_modules/es-abstract/5/TimeClip.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Date = GetIntrinsic('%Date%'); -var $Number = GetIntrinsic('%Number%'); -var $abs = GetIntrinsic('%Math.abs%'); - -var $isFinite = require('../helpers/isFinite'); - -var ToNumber = require('./ToNumber'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.14 - -module.exports = function TimeClip(time) { - if (!$isFinite(time) || $abs(time) > 8.64e15) { - return NaN; - } - return $Number(new $Date(ToNumber(time))); -}; - diff --git a/node_modules/es-abstract/5/TimeFromYear.js b/node_modules/es-abstract/5/TimeFromYear.js deleted file mode 100644 index df646c3..0000000 --- a/node_modules/es-abstract/5/TimeFromYear.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var msPerDay = require('../helpers/timeConstants').msPerDay; - -var DayFromYear = require('./DayFromYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function TimeFromYear(y) { - return msPerDay * DayFromYear(y); -}; diff --git a/node_modules/es-abstract/5/TimeWithinDay.js b/node_modules/es-abstract/5/TimeWithinDay.js deleted file mode 100644 index c5b21d3..0000000 --- a/node_modules/es-abstract/5/TimeWithinDay.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); -var msPerDay = require('../helpers/timeConstants').msPerDay; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - -module.exports = function TimeWithinDay(t) { - return mod(t, msPerDay); -}; - diff --git a/node_modules/es-abstract/5/ToBoolean.js b/node_modules/es-abstract/5/ToBoolean.js deleted file mode 100644 index 65d8737..0000000 --- a/node_modules/es-abstract/5/ToBoolean.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.2 - -module.exports = function ToBoolean(value) { return !!value; }; diff --git a/node_modules/es-abstract/5/ToInt32.js b/node_modules/es-abstract/5/ToInt32.js deleted file mode 100644 index a8d2680..0000000 --- a/node_modules/es-abstract/5/ToInt32.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.5 - -module.exports = function ToInt32(x) { - return ToNumber(x) >> 0; -}; diff --git a/node_modules/es-abstract/5/ToInteger.js b/node_modules/es-abstract/5/ToInteger.js deleted file mode 100644 index a95265b..0000000 --- a/node_modules/es-abstract/5/ToInteger.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var $sign = require('../helpers/sign'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.4 - -module.exports = function ToInteger(value) { - var number = ToNumber(value); - if ($isNaN(number)) { return 0; } - if (number === 0 || !$isFinite(number)) { return number; } - return $sign(number) * $floor($abs(number)); -}; diff --git a/node_modules/es-abstract/5/ToNumber.js b/node_modules/es-abstract/5/ToNumber.js deleted file mode 100644 index 4a7a3b8..0000000 --- a/node_modules/es-abstract/5/ToNumber.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.3 - -module.exports = function ToNumber(value) { - return +value; // eslint-disable-line no-implicit-coercion -}; diff --git a/node_modules/es-abstract/5/ToObject.js b/node_modules/es-abstract/5/ToObject.js deleted file mode 100644 index 1d27a13..0000000 --- a/node_modules/es-abstract/5/ToObject.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Object = GetIntrinsic('%Object%'); - -var CheckObjectCoercible = require('./CheckObjectCoercible'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.9 - -module.exports = function ToObject(value) { - CheckObjectCoercible(value); - return $Object(value); -}; diff --git a/node_modules/es-abstract/5/ToPrimitive.js b/node_modules/es-abstract/5/ToPrimitive.js deleted file mode 100644 index 071df70..0000000 --- a/node_modules/es-abstract/5/ToPrimitive.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.1 - -module.exports = require('es-to-primitive/es5'); diff --git a/node_modules/es-abstract/5/ToPropertyDescriptor.js b/node_modules/es-abstract/5/ToPropertyDescriptor.js deleted file mode 100644 index 38e536e..0000000 --- a/node_modules/es-abstract/5/ToPropertyDescriptor.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -var has = require('has'); - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var Type = require('./Type'); -var ToBoolean = require('./ToBoolean'); -var IsCallable = require('./IsCallable'); - -// https://ecma-international.org/ecma-262/5.1/#sec-8.10.5 - -module.exports = function ToPropertyDescriptor(Obj) { - if (Type(Obj) !== 'Object') { - throw new $TypeError('ToPropertyDescriptor requires an object'); - } - - var desc = {}; - if (has(Obj, 'enumerable')) { - desc['[[Enumerable]]'] = ToBoolean(Obj.enumerable); - } - if (has(Obj, 'configurable')) { - desc['[[Configurable]]'] = ToBoolean(Obj.configurable); - } - if (has(Obj, 'value')) { - desc['[[Value]]'] = Obj.value; - } - if (has(Obj, 'writable')) { - desc['[[Writable]]'] = ToBoolean(Obj.writable); - } - if (has(Obj, 'get')) { - var getter = Obj.get; - if (typeof getter !== 'undefined' && !IsCallable(getter)) { - throw new TypeError('getter must be a function'); - } - desc['[[Get]]'] = getter; - } - if (has(Obj, 'set')) { - var setter = Obj.set; - if (typeof setter !== 'undefined' && !IsCallable(setter)) { - throw new $TypeError('setter must be a function'); - } - desc['[[Set]]'] = setter; - } - - if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) { - throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute'); - } - return desc; -}; diff --git a/node_modules/es-abstract/5/ToString.js b/node_modules/es-abstract/5/ToString.js deleted file mode 100644 index 80ece42..0000000 --- a/node_modules/es-abstract/5/ToString.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $String = GetIntrinsic('%String%'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.8 - -module.exports = function ToString(value) { - return $String(value); -}; - diff --git a/node_modules/es-abstract/5/ToUint16.js b/node_modules/es-abstract/5/ToUint16.js deleted file mode 100644 index c8a408b..0000000 --- a/node_modules/es-abstract/5/ToUint16.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); - -var ToNumber = require('./ToNumber'); - -var $isNaN = require('../helpers/isNaN'); -var $isFinite = require('../helpers/isFinite'); -var $sign = require('../helpers/sign'); -var $mod = require('../helpers/mod'); - -var $floor = $Math.floor; -var $abs = $Math.abs; - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.7 - -module.exports = function ToUint16(value) { - var number = ToNumber(value); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = $sign(number) * $floor($abs(number)); - return $mod(posInt, 0x10000); -}; diff --git a/node_modules/es-abstract/5/ToUint32.js b/node_modules/es-abstract/5/ToUint32.js deleted file mode 100644 index 3660f62..0000000 --- a/node_modules/es-abstract/5/ToUint32.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ToNumber = require('./ToNumber'); - -// http://www.ecma-international.org/ecma-262/5.1/#sec-9.6 - -module.exports = function ToUint32(x) { - return ToNumber(x) >>> 0; -}; diff --git a/node_modules/es-abstract/5/Type.js b/node_modules/es-abstract/5/Type.js deleted file mode 100644 index 9cc750c..0000000 --- a/node_modules/es-abstract/5/Type.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -// https://www.ecma-international.org/ecma-262/5.1/#sec-8 - -module.exports = function Type(x) { - if (x === null) { - return 'Null'; - } - if (typeof x === 'undefined') { - return 'Undefined'; - } - if (typeof x === 'function' || typeof x === 'object') { - return 'Object'; - } - if (typeof x === 'number') { - return 'Number'; - } - if (typeof x === 'boolean') { - return 'Boolean'; - } - if (typeof x === 'string') { - return 'String'; - } -}; diff --git a/node_modules/es-abstract/5/WeekDay.js b/node_modules/es-abstract/5/WeekDay.js deleted file mode 100644 index 2973e02..0000000 --- a/node_modules/es-abstract/5/WeekDay.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -var Day = require('./Day'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.6 - -module.exports = function WeekDay(t) { - return mod(Day(t) + 4, 7); -}; diff --git a/node_modules/es-abstract/5/YearFromTime.js b/node_modules/es-abstract/5/YearFromTime.js deleted file mode 100644 index ff5339f..0000000 --- a/node_modules/es-abstract/5/YearFromTime.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Date = GetIntrinsic('%Date%'); - -var callBound = require('../helpers/callBound'); - -var $getUTCFullYear = callBound('Date.prototype.getUTCFullYear'); - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - -module.exports = function YearFromTime(t) { - // largest y such that this.TimeFromYear(y) <= t - return $getUTCFullYear(new $Date(t)); -}; diff --git a/node_modules/es-abstract/5/modulo.js b/node_modules/es-abstract/5/modulo.js deleted file mode 100644 index bc04c06..0000000 --- a/node_modules/es-abstract/5/modulo.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); - -// https://ecma-international.org/ecma-262/5.1/#sec-5.2 - -module.exports = function modulo(x, y) { - return mod(x, y); -}; diff --git a/node_modules/es-abstract/5/msFromTime.js b/node_modules/es-abstract/5/msFromTime.js deleted file mode 100644 index c31eda0..0000000 --- a/node_modules/es-abstract/5/msFromTime.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var mod = require('../helpers/mod'); -var msPerSecond = require('../helpers/timeConstants').msPerSecond; - -// https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - -module.exports = function msFromTime(t) { - return mod(t, msPerSecond); -}; diff --git a/node_modules/es-abstract/CHANGELOG.md b/node_modules/es-abstract/CHANGELOG.md deleted file mode 100644 index b3922e5..0000000 --- a/node_modules/es-abstract/CHANGELOG.md +++ /dev/null @@ -1,333 +0,0 @@ -1.17.5 / 2020-03-22 -================= - * [Fix] `CreateDataProperty`: update an existing property - * [Fix] run missing spackle from cd7504701879ddea0f5981e99cbcf93bfea9171d - * [Dev Deps] update `make-arrow-function`, `tape`, `@ljharb/eslint-config` - -1.17.4 / 2020-01-21 -================= - * [Fix] `2015+`: add code to handle IE 8’s problems - * [Tests] fix tests for IE 8 - -1.17.3 / 2020-01-19 -================= - * [Fix] `ObjectCreate` `2015+`: Fall back to `__proto__` and normal `new` in older browsers - * [Fix] `GetIntrinsic`: ensure the `allowMissing` property actually works on dotted intrinsics - -1.17.2 / 2020-01-14 -================= - * [Fix] `helpers/OwnPropertyKeys`: include non-enumerables too - -1.17.1 / 2020-01-14 -================= - * [Refactor] add `OwnPropertyKeys` helper, use it in `CopyDataProperties` - * [Refactor] `IteratorClose`: remove useless assignment - * [Dev Deps] update `eslint`, `tape`, `diff` - -1.17.0 / 2019-12-20 -================= - * [New] Split up each operation into its own file (prereleased) - * [Fix] `GetIntrinsic`: IE 8 has a broken `Object.getOwnPropertyDescriptor` - * [Fix] `object.assign` is a runtime dep (prereleased) - * [Refactor] `GetIntrinsic`: remove the internal property salts, since % already handles that - * [Refactor] `GetIntrinsic`: further simplification - * [Deps] update `is-callable`, `string.prototype.trimleft`, `string.prototype.trimright`, `is-regex` - * [Dev Deps] update `@ljharb/eslint-config`, `object-is`, `object.fromentries`, `tape` - * [Tests] add `.eslintignore` - * [meta] remove unused Makefile and associated utils - * [meta] only run spackle script in publish (#78) (prereleased) - -1.17.0-next.1 / 2019-12-11 -================= - * [Fix] `object.assign` is a runtime dep - * [meta] only run spackle script in publish (#78) - -1.17.0-next.0 / 2019-12-11 -================= - * [New] Split up each operation into its own file - -1.16.3 / 2019-12-04 -================= - * [Fix] `GetIntrinsic`: when given a path to a getter, return the actual getter - * [Dev Deps] update `eslint` - -1.16.2 / 2019-11-24 -================= - * [Fix] IE 6-7 lack JSON - * [Fix] IE 6-8 strings can’t use array slice, they need string slice - * [Dev Deps] update `eslint` - -1.16.1 / 2019-11-24 -================= - * [Fix] `GetIntrinsics`: turns out IE 8 throws when `Object.getOwnPropertyDescriptor(arguments);`, and does not throw on `callee` anyways - * [Deps] update `es-to-primitive`, `has-symbols`, `object-inspect` - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest` - * [meta] re-include year files inside `operations` - * [meta] add `funding` field - * [actions] add Automatic Rebase github action - * [Tests] use shared travis-ci config - * [Tests] disable `check-coverage`, and let codecov do it - -1.16.0 / 2019-10-18 -================= - * [New] `ES2015+`: add `SetFunctionName` - * [New] `ES2015+`: add `GetPrototypeFromConstructor`, with caveats - * [New] `ES2015+`: add `CreateListFromArrayLike` - * [New] `ES2016+`: add `OrdinarySetPrototypeOf` - * [New] `ES2016+`: add `OrdinaryGetPrototypeOf` - * [New] add `getSymbolDescription` and `getInferredName` helpers - * [Fix] `GetIterator`: add fallback for pre-Symbol environments, tests - * [Dev Deps] update `object.fromentries` - * [Tests] add `node` `v12.2` - -1.15.0 / 2019-10-02 -================= - * [New] `ES2018`+: add `DateString`, `TimeString` - * [New] `ES2015`+: add `ToDateString` - * [New] `ES5`+: add `msFromTime`, `SecFromTime`, `MinFromTime`, `HourFromTime`, `TimeWithinDay`, `Day`, `DayFromYear`, `TimeFromYear`, `YearFromTime`, `WeekDay`, `DaysInYear`, `InLeapYear`, `DayWithinYear`, `MonthFromTime`, `DateFromTime`, `MakeDay`, `MakeDate`, `MakeTime`, `TimeClip`, `modulo` - * [New] add `regexTester` helper - * [New] add `callBound` helper - * [New] add ES2020’s intrinsic dot notation - * [New] add `isPrefixOf` helper - * [New] add `maxSafeInteger` helper - * [Deps] update `string.prototype.trimleft`, `string.prototype.trimright` - * [Dev Deps] update `eslint` - * [Tests] on `node` `v12.11` - * [meta] npmignore operations scripts; add "deltas" - -1.14.2 / 2019-09-08 -================= - * [Fix] `ES2016`: `IterableToArrayLike`: add proper fallback for strings, pre-Symbols - * [Tests] on `node` `v12.10` - -1.14.1 / 2019-09-03 -================= - * [meta] republish with some extra files removed - -1.14.0 / 2019-09-02 -================= - * [New] add ES2019 - * [New] `ES2017+`: add `IterableToList` - * [New] `ES2016`: add `IterableToArrayLike` - * [New] `ES2015+`: add `ArrayCreate`, `ArraySetLength`, `OrdinaryDefineOwnProperty`, `OrdinaryGetOwnProperty`, `OrdinaryHasProperty`, `CreateHTML`, `GetOwnPropertyKeys`, `InstanceofOperator`, `SymbolDescriptiveString`, `GetSubstitution`, `ValidateAndApplyPropertyDescriptor`, `IsPromise`, `OrdinaryHasInstance`, `TestIntegrityLevel`, `SetIntegrityLevel` - * [New] add `callBind` helper, and use it - * [New] add helpers: `isPropertyDescriptor`, `every` - * [New] ES5+: add `Abstract Relational Comparison` - * [New] ES5+: add `Abstract Equality Comparison`, `Strict Equality Comparison` - * [Fix] `ES2015+`: `GetIterator`: only require native Symbols when `method` is omitted - * [Fix] `ES2015`: `Call`: error message now properly displays Symbols using `object-inspect` - * [Fix] `ES2015+`: `ValidateAndApplyPropertyDescriptor`: use ES2017 logic to bypass spec bugs - * [Fix] `ES2015+`: `CreateDataProperty`, `DefinePropertyOrThrow`, `ValidateAndApplyPropertyDescriptor`: add fallbacks for ES3 - * [Fix] `ES2015+`: `FromPropertyDescriptor`: no longer requires a fully complete Property Descriptor - * [Fix] `ES5`: `IsPropertyDescriptor`: call into `IsDataDescriptor` and `IsAccessorDescriptor` - * [Refactor] use `has-symbols` for Symbol detection - * [Fix] `helpers/assertRecord`: remove `console.log` - * [Deps] update `object-keys` - * [readme] add security note - * [meta] change http URLs to https - * [meta] linter cleanup - * [meta] fix getOps script - * [meta] add FUNDING.yml - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `semver`, `replace`, `cheerio`, `tape` - * [Tests] up to `node` `v12.9`, `v11.15`, `v10.16`, `v8.16`, `v6.17` - * [Tests] temporarily allow node 0.6 to fail; segfaulting in travis - * [Tests] use the values helper more in es5 tests - * [Tests] fix linting to apply to all files - * [Tests] run `npx aud` only on prod deps - * [Tests] add v.descriptors helpers - * [Tests] use `npx aud` instead of `npm audit` with hoops - * [Tests] use `eclint` instead of `editorconfig-tools` - * [Tests] some intrinsic cleanup - * [Tests] migrate es5 tests to use values helper - * [Tests] add some missing ES2015 ops - -1.13.0 / 2019-01-02 -================= - * [New] add ES2018 - * [New] add ES2015/ES2016: EnumerableOwnNames; ES2017: EnumerableOwnProperties - * [New] `ES2015+`: add `thisBooleanValue`, `thisNumberValue`, `thisStringValue`, `thisTimeValue` - * [New] `ES2015+`: add `DefinePropertyOrThrow`, `DeletePropertyOrThrow`, `CreateMethodProperty` - * [New] add `assertRecord` helper - * [Deps] update `is-callable`, `has`, `object-keys`, `es-to-primitive` - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `semver`, `safe-publish-latest`, `replace` - * [Tests] use `npm audit` instead of `nsp` - * [Tests] remove `jscs` - * [Tests] up to `node` `v11.6`, `v10.15`, `v8.15`, `v6.16` - * [Tests] move descriptor factories to `values` helper - * [Tests] add `getOps` to programmatically fetch abstract operation names - -1.12.0 / 2018-05-31 -================= - * [New] add `GetIntrinsic` entry point - * [New] `ES2015`+: add `ObjectCreate` - * [Robustness]: `ES2015+`: ensure `Math.{abs,floor}` and `Function.call` are cached - -1.11.0 / 2018-03-21 -================= - * [New] `ES2015+`: add iterator abstract ops - * [Dev Deps] update `eslint`, `nsp`, `object.assign`, `semver`, `tape` - * [Tests] up to `node` `v9.8`, `v8.10`, `v6.13` - -1.10.0 / 2017-11-24 -================= - * [New] ES2015+: `AdvanceStringIndex` - * [Dev Deps] update `eslint`, `nsp` - * [Tests] require node 0.6 to pass again - * [Tests] up to `node` `v9.2`, `v8.9`, `v6.12`; use `nvm install-latest-npm`; pin included builds to LTS - -1.9.0 / 2017-09-30 -================= - * [New] `es2015+`: add `ArraySpeciesCreate` - * [New] ES2015+: add `CreateDataProperty` and `CreateDataPropertyOrThrow` - * [Tests] consolidate duplicated tests - * [Tests] increase coverage - * [Dev Deps] update `nsp`, `eslint` - -1.8.2 / 2017-09-03 -================= - * [Fix] `es2015`+: `ToNumber`: provide the proper hint for Date objects (#27) - * [Dev Deps] update `eslint` - -1.8.1 / 2017-08-30 -================= - * [Fix] ES2015+: `ToPropertyKey`: should return a symbol for Symbols (#26) - * [Deps] update `function-bind` - * [Dev Deps] update `eslint`, `@ljharb/eslint-config` - * [Docs] github broke markdown parsing - -1.8.0 / 2017-08-04 -================= - * [New] add ES2017 - * [New] move es6+ to es2015+; leave es6/es7 as aliases - * [New] ES5+: add `IsPropertyDescriptor`, `IsAccessorDescriptor`, `IsDataDescriptor`, `IsGenericDescriptor`, `FromPropertyDescriptor`, `ToPropertyDescriptor` - * [New] ES2015+: add `CompletePropertyDescriptor`, `Set`, `HasOwnProperty`, `HasProperty`, `IsConcatSpreadable`, `Invoke`, `CreateIterResultObject`, `RegExpExec` - * [Fix] es7/es2016: do not mutate ES6 - * [Fix] assign helper only supports one source - * [Deps] update `is-regex` - * [Dev Deps] update `nsp`, `eslint`, `@ljharb/eslint-config` - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `nsp`, `semver`, `tape` - * [Tests] add tests for missing and excess operations - * [Tests] add codecov for coverage - * [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`, `v4.8`; newer npm breaks on older node - * [Tests] use same lists of value types across tests; ensure tests are the same when ops are the same - * [Tests] ES2015: add ToNumber symbol tests - * [Tests] switch to `nyc` for code coverage - * [Tests] make IsRegExp tests consistent across editions - -1.7.0 / 2017-01-22 -================= - * [New] ES6: Add `GetMethod` (#16) - * [New] ES6: Add `GetV` (#16) - * [New] ES6: Add `Get` (#17) - * [Tests] up to `node` `v7.4`, `v6.9`, `v4.6`; improve test matrix - * [Dev Deps] update `tape`, `nsp`, `eslint`, `@ljharb/eslint-config`, `safe-publish-latest` - -1.6.1 / 2016-08-21 -================= - * [Fix] ES6: IsConstructor should return true for `class` constructors. - -1.6.0 / 2016-08-20 -================= - * [New] ES5 / ES6: add `Type` - * [New] ES6: `SpeciesConstructor` - * [Dev Deps] update `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`; add `safe-publish-latest` - * [Tests] up to `node` `v6.4`, `v5.12`, `v4.5` - -1.5.1 / 2016-05-30 -================= - * [Fix] `ES.IsRegExp`: actually look up `Symbol.match` on the argument - * [Refactor] create `isNaN` helper - * [Deps] update `is-callable`, `function-bind` - * [Deps] update `es-to-primitive`, fix ES5 tests - * [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config`, `tape`, `nsp` - * [Tests] up to `node` `v6.2`, `v5.11`, `v4.4` - * [Tests] use pretest/posttest for linting/security - -1.5.0 / 2015-12-27 -================= - * [New] adds `Symbol.toPrimitive` support via `es-to-primitive` - * [Deps] update `is-callable`, `es-to-primitive` - * [Dev Deps] update `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`, `tape` - * [Tests] up to `node` `v5.3` - -1.4.3 / 2015-11-04 -================= - * [Fix] `ES6.ToNumber`: should give `NaN` for explicitly signed hex strings (#4) - * [Refactor] `ES6.ToNumber`: No need to double-trim - * [Refactor] group tests better - * [Tests] should still pass on `node` `v0.8` - -1.4.2 / 2015-11-02 -================= - * [Fix] ensure `ES.ToNumber` trims whitespace, and does not trim non-whitespace (#3) - -1.4.1 / 2015-10-31 -================= - * [Fix] ensure only 0-1 are valid binary and 0-7 are valid octal digits (#2) - * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` - * [Tests] on `node` `v5.0` - * [Tests] fix npm upgrades for older node versions - * package.json: use object form of "authors", add "contributors" - -1.4.0 / 2015-09-26 -================= - * [Deps] update `is-callable` - * [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` - * [Tests] on `node` `v4.2` - * [New] Add `SameValueNonNumber` to ES7 - -1.3.2 / 2015-09-26 -================= - * [Fix] Fix `ES6.IsRegExp` to properly handle `Symbol.match`, per spec. - * [Tests] up to `io.js` `v3.3`, `node` `v4.1` - * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` - -1.3.1 / 2015-08-15 -================= - * [Fix] Ensure that objects that `toString` to a binary or octal literal also convert properly - -1.3.0 / 2015-08-15 -================= - * [New] ES6’s ToNumber now supports binary and octal literals. - * [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config`, `tape` - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - * [Tests] up to `io.js` `v3.0` - -1.2.2 / 2015-07-28 -================= - * [Fix] Both `ES5.CheckObjectCoercible` and `ES6.RequireObjectCoercible` return the value if they don't throw. - * [Tests] Test on latest `io.js` versions. - * [Dev Deps] Update `eslint`, `jscs`, `tape`, `semver`, `covert`, `nsp` - -1.2.1 / 2015-03-20 -================= - * Fix `isFinite` helper. - -1.2.0 / 2015-03-19 -================= - * Use `es-to-primitive` for ToPrimitive methods. - * Test on latest `io.js` versions; allow failures on all but 2 latest `node`/`io.js` versions. - -1.1.2 / 2015-03-20 -================= - * Fix isFinite helper. - -1.1.1 / 2015-03-19 -================= - * Fix isPrimitive check for functions - * Update `eslint`, `editorconfig-tools`, `semver`, `nsp` - -1.1.0 / 2015-02-17 -================= - * Add ES7 export (non-default). - * All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. - * Test on `iojs-v1.2`. - -1.0.1 / 2015-01-30 -================= - * Use `is-callable` instead of an internal function. - * Update `tape`, `jscs`, `nsp`, `eslint` - -1.0.0 / 2015-01-10 -================= - * v1.0.0 diff --git a/node_modules/es-abstract/GetIntrinsic.js b/node_modules/es-abstract/GetIntrinsic.js deleted file mode 100644 index 6e0af00..0000000 --- a/node_modules/es-abstract/GetIntrinsic.js +++ /dev/null @@ -1,218 +0,0 @@ -'use strict'; - -/* globals - Atomics, - SharedArrayBuffer, -*/ - -var undefined; - -var $TypeError = TypeError; - -var $gOPD = Object.getOwnPropertyDescriptor; -if ($gOPD) { - try { - $gOPD({}, ''); - } catch (e) { - $gOPD = null; // this is IE 8, which has a broken gOPD - } -} - -var throwTypeError = function () { throw new $TypeError(); }; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = require('has-symbols')(); - -var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - -var generator; // = function * () {}; -var generatorFunction = generator ? getProto(generator) : undefined; -var asyncFn; // async function() {}; -var asyncFunction = asyncFn ? asyncFn.constructor : undefined; -var asyncGen; // async function * () {}; -var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined; -var asyncGenIterator = asyncGen ? asyncGen() : undefined; - -var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype, - '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, - '%ArrayPrototype%': Array.prototype, - '%ArrayProto_entries%': Array.prototype.entries, - '%ArrayProto_forEach%': Array.prototype.forEach, - '%ArrayProto_keys%': Array.prototype.keys, - '%ArrayProto_values%': Array.prototype.values, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': asyncFunction, - '%AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined, - '%AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined, - '%AsyncGeneratorFunction%': asyncGenFunction, - '%AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined, - '%AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%Boolean%': Boolean, - '%BooleanPrototype%': Boolean.prototype, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype, - '%Date%': Date, - '%DatePrototype%': Date.prototype, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': Error, - '%ErrorPrototype%': Error.prototype, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': EvalError, - '%EvalErrorPrototype%': EvalError.prototype, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype, - '%Function%': Function, - '%FunctionPrototype%': Function.prototype, - '%Generator%': generator ? getProto(generator()) : undefined, - '%GeneratorFunction%': generatorFunction, - '%GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%JSONParse%': typeof JSON === 'object' ? JSON.parse : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), - '%MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype, - '%Math%': Math, - '%Number%': Number, - '%NumberPrototype%': Number.prototype, - '%Object%': Object, - '%ObjectPrototype%': Object.prototype, - '%ObjProto_toString%': Object.prototype.toString, - '%ObjProto_valueOf%': Object.prototype.valueOf, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype, - '%PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then, - '%Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all, - '%Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject, - '%Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': RangeError, - '%RangeErrorPrototype%': RangeError.prototype, - '%ReferenceError%': ReferenceError, - '%ReferenceErrorPrototype%': ReferenceError.prototype, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%RegExpPrototype%': RegExp.prototype, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype, - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, - '%StringPrototype%': String.prototype, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined, - '%SyntaxError%': SyntaxError, - '%SyntaxErrorPrototype%': SyntaxError.prototype, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined, - '%TypeError%': $TypeError, - '%TypeErrorPrototype%': $TypeError.prototype, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype, - '%URIError%': URIError, - '%URIErrorPrototype%': URIError.prototype, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, - '%WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype -}; - -var bind = require('function-bind'); -var $replace = bind.call(Function.call, String.prototype.replace); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : (number || match); - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - if (!(name in INTRINSICS)) { - throw new SyntaxError('intrinsic ' + name + ' does not exist!'); - } - - // istanbul ignore if // hopefully this is impossible to test :-) - if (typeof INTRINSICS[name] === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return INTRINSICS[name]; -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new TypeError('"allowMissing" argument must be a boolean'); - } - - var parts = stringToPath(name); - - var value = getBaseIntrinsic('%' + (parts.length > 0 ? parts[0] : '') + '%', allowMissing); - for (var i = 1; i < parts.length; i += 1) { - if (value != null) { - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, parts[i]); - if (!allowMissing && !(parts[i] in value)) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - value = desc ? (desc.get || desc.value) : value[parts[i]]; - } else { - value = value[parts[i]]; - } - } - } - return value; -}; diff --git a/node_modules/es-abstract/LICENSE b/node_modules/es-abstract/LICENSE deleted file mode 100644 index 8c271c1..0000000 --- a/node_modules/es-abstract/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (C) 2015 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/es-abstract/README.md b/node_modules/es-abstract/README.md deleted file mode 100644 index 20342d1..0000000 --- a/node_modules/es-abstract/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# es-abstract [![Version Badge][npm-version-svg]][package-url] - -[![Build Status][travis-svg]][travis-url] -[![dependency status][deps-svg]][deps-url] -[![dev dependency status][dev-deps-svg]][dev-deps-url] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][npm-badge-png]][package-url] - -[![browser support][testling-svg]][testling-url] - -ECMAScript spec abstract operations. -When different versions of the spec conflict, the default export will be the latest version of the abstract operation. -All abstract operations will also be available under an `es5`/`es2015`/`es2016`/`es2017`/`es2018`/`es2019` entry point, and exported property, if you require a specific version. - -## Example - -```js -var ES = require('es-abstract'); -var assert = require('assert'); - -assert(ES.isCallable(function () {})); -assert(!ES.isCallable(/a/g)); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -## Security - -Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. - -[package-url]: https://npmjs.org/package/es-abstract -[npm-version-svg]: http://versionbadg.es/ljharb/es-abstract.svg -[travis-svg]: https://travis-ci.org/ljharb/es-abstract.svg -[travis-url]: https://travis-ci.org/ljharb/es-abstract -[deps-svg]: https://david-dm.org/ljharb/es-abstract.svg -[deps-url]: https://david-dm.org/ljharb/es-abstract -[dev-deps-svg]: https://david-dm.org/ljharb/es-abstract/dev-status.svg -[dev-deps-url]: https://david-dm.org/ljharb/es-abstract#info=devDependencies -[testling-svg]: https://ci.testling.com/ljharb/es-abstract.png -[testling-url]: https://ci.testling.com/ljharb/es-abstract -[npm-badge-png]: https://nodei.co/npm/es-abstract.png?downloads=true&stars=true -[license-image]: https://img.shields.io/npm/l/es-abstract.svg -[license-url]: LICENSE -[downloads-image]: https://img.shields.io/npm/dm/es-abstract.svg -[downloads-url]: https://npm-stat.com/charts.html?package=es-abstract diff --git a/node_modules/es-abstract/es2015.js b/node_modules/es-abstract/es2015.js deleted file mode 100644 index dc02ca4..0000000 --- a/node_modules/es-abstract/es2015.js +++ /dev/null @@ -1,115 +0,0 @@ -'use strict'; - -/* eslint global-require: 0 */ -// https://www.ecma-international.org/ecma-262/6.0/#sec-abstract-operations -var ES6 = { - 'Abstract Equality Comparison': require('./2015/AbstractEqualityComparison'), - 'Abstract Relational Comparison': require('./2015/AbstractRelationalComparison'), - 'Strict Equality Comparison': require('./2015/StrictEqualityComparison'), - AdvanceStringIndex: require('./2015/AdvanceStringIndex'), - ArrayCreate: require('./2015/ArrayCreate'), - ArraySetLength: require('./2015/ArraySetLength'), - ArraySpeciesCreate: require('./2015/ArraySpeciesCreate'), - Call: require('./2015/Call'), - CanonicalNumericIndexString: require('./2015/CanonicalNumericIndexString'), - CompletePropertyDescriptor: require('./2015/CompletePropertyDescriptor'), - CreateDataProperty: require('./2015/CreateDataProperty'), - CreateDataPropertyOrThrow: require('./2015/CreateDataPropertyOrThrow'), - CreateHTML: require('./2015/CreateHTML'), - CreateIterResultObject: require('./2015/CreateIterResultObject'), - CreateListFromArrayLike: require('./2015/CreateListFromArrayLike'), - CreateMethodProperty: require('./2015/CreateMethodProperty'), - DateFromTime: require('./2015/DateFromTime'), - Day: require('./2015/Day'), - DayFromYear: require('./2015/DayFromYear'), - DaysInYear: require('./2015/DaysInYear'), - DayWithinYear: require('./2015/DayWithinYear'), - DefinePropertyOrThrow: require('./2015/DefinePropertyOrThrow'), - DeletePropertyOrThrow: require('./2015/DeletePropertyOrThrow'), - EnumerableOwnNames: require('./2015/EnumerableOwnNames'), - FromPropertyDescriptor: require('./2015/FromPropertyDescriptor'), - Get: require('./2015/Get'), - GetIterator: require('./2015/GetIterator'), - GetMethod: require('./2015/GetMethod'), - GetOwnPropertyKeys: require('./2015/GetOwnPropertyKeys'), - GetPrototypeFromConstructor: require('./2015/GetPrototypeFromConstructor'), - GetSubstitution: require('./2015/GetSubstitution'), - GetV: require('./2015/GetV'), - HasOwnProperty: require('./2015/HasOwnProperty'), - HasProperty: require('./2015/HasProperty'), - HourFromTime: require('./2015/HourFromTime'), - InLeapYear: require('./2015/InLeapYear'), - InstanceofOperator: require('./2015/InstanceofOperator'), - Invoke: require('./2015/Invoke'), - IsAccessorDescriptor: require('./2015/IsAccessorDescriptor'), - IsArray: require('./2015/IsArray'), - IsCallable: require('./2015/IsCallable'), - IsConcatSpreadable: require('./2015/IsConcatSpreadable'), - IsConstructor: require('./2015/IsConstructor'), - IsDataDescriptor: require('./2015/IsDataDescriptor'), - IsExtensible: require('./2015/IsExtensible'), - IsGenericDescriptor: require('./2015/IsGenericDescriptor'), - IsInteger: require('./2015/IsInteger'), - IsPromise: require('./2015/IsPromise'), - IsPropertyDescriptor: require('./2015/IsPropertyDescriptor'), - IsPropertyKey: require('./2015/IsPropertyKey'), - IsRegExp: require('./2015/IsRegExp'), - IteratorClose: require('./2015/IteratorClose'), - IteratorComplete: require('./2015/IteratorComplete'), - IteratorNext: require('./2015/IteratorNext'), - IteratorStep: require('./2015/IteratorStep'), - IteratorValue: require('./2015/IteratorValue'), - MakeDate: require('./2015/MakeDate'), - MakeDay: require('./2015/MakeDay'), - MakeTime: require('./2015/MakeTime'), - MinFromTime: require('./2015/MinFromTime'), - modulo: require('./2015/modulo'), - MonthFromTime: require('./2015/MonthFromTime'), - msFromTime: require('./2015/msFromTime'), - ObjectCreate: require('./2015/ObjectCreate'), - OrdinaryDefineOwnProperty: require('./2015/OrdinaryDefineOwnProperty'), - OrdinaryGetOwnProperty: require('./2015/OrdinaryGetOwnProperty'), - OrdinaryHasInstance: require('./2015/OrdinaryHasInstance'), - OrdinaryHasProperty: require('./2015/OrdinaryHasProperty'), - RegExpExec: require('./2015/RegExpExec'), - RequireObjectCoercible: require('./2015/RequireObjectCoercible'), - SameValue: require('./2015/SameValue'), - SameValueZero: require('./2015/SameValueZero'), - SecFromTime: require('./2015/SecFromTime'), - Set: require('./2015/Set'), - SetFunctionName: require('./2015/SetFunctionName'), - SetIntegrityLevel: require('./2015/SetIntegrityLevel'), - SpeciesConstructor: require('./2015/SpeciesConstructor'), - SymbolDescriptiveString: require('./2015/SymbolDescriptiveString'), - TestIntegrityLevel: require('./2015/TestIntegrityLevel'), - thisBooleanValue: require('./2015/thisBooleanValue'), - thisNumberValue: require('./2015/thisNumberValue'), - thisStringValue: require('./2015/thisStringValue'), - thisTimeValue: require('./2015/thisTimeValue'), - TimeClip: require('./2015/TimeClip'), - TimeFromYear: require('./2015/TimeFromYear'), - TimeWithinDay: require('./2015/TimeWithinDay'), - ToBoolean: require('./2015/ToBoolean'), - ToDateString: require('./2015/ToDateString'), - ToInt16: require('./2015/ToInt16'), - ToInt32: require('./2015/ToInt32'), - ToInt8: require('./2015/ToInt8'), - ToInteger: require('./2015/ToInteger'), - ToLength: require('./2015/ToLength'), - ToNumber: require('./2015/ToNumber'), - ToObject: require('./2015/ToObject'), - ToPrimitive: require('./2015/ToPrimitive'), - ToPropertyDescriptor: require('./2015/ToPropertyDescriptor'), - ToPropertyKey: require('./2015/ToPropertyKey'), - ToString: require('./2015/ToString'), - ToUint16: require('./2015/ToUint16'), - ToUint32: require('./2015/ToUint32'), - ToUint8: require('./2015/ToUint8'), - ToUint8Clamp: require('./2015/ToUint8Clamp'), - Type: require('./2015/Type'), - ValidateAndApplyPropertyDescriptor: require('./2015/ValidateAndApplyPropertyDescriptor'), - WeekDay: require('./2015/WeekDay'), - YearFromTime: require('./2015/YearFromTime') -}; - -module.exports = ES6; diff --git a/node_modules/es-abstract/es2016.js b/node_modules/es-abstract/es2016.js deleted file mode 100644 index 9e72e82..0000000 --- a/node_modules/es-abstract/es2016.js +++ /dev/null @@ -1,119 +0,0 @@ -'use strict'; - -/* eslint global-require: 0 */ -// https://www.ecma-international.org/ecma-262/7.0/#sec-abstract-operations -var ES2016 = { - 'Abstract Equality Comparison': require('./2016/AbstractEqualityComparison'), - 'Abstract Relational Comparison': require('./2016/AbstractRelationalComparison'), - 'Strict Equality Comparison': require('./2016/StrictEqualityComparison'), - AdvanceStringIndex: require('./2016/AdvanceStringIndex'), - ArrayCreate: require('./2016/ArrayCreate'), - ArraySetLength: require('./2016/ArraySetLength'), - ArraySpeciesCreate: require('./2016/ArraySpeciesCreate'), - Call: require('./2016/Call'), - CanonicalNumericIndexString: require('./2016/CanonicalNumericIndexString'), - CompletePropertyDescriptor: require('./2016/CompletePropertyDescriptor'), - CreateDataProperty: require('./2016/CreateDataProperty'), - CreateDataPropertyOrThrow: require('./2016/CreateDataPropertyOrThrow'), - CreateHTML: require('./2016/CreateHTML'), - CreateIterResultObject: require('./2016/CreateIterResultObject'), - CreateListFromArrayLike: require('./2016/CreateListFromArrayLike'), - CreateMethodProperty: require('./2016/CreateMethodProperty'), - DateFromTime: require('./2016/DateFromTime'), - Day: require('./2016/Day'), - DayFromYear: require('./2016/DayFromYear'), - DaysInYear: require('./2016/DaysInYear'), - DayWithinYear: require('./2016/DayWithinYear'), - DefinePropertyOrThrow: require('./2016/DefinePropertyOrThrow'), - DeletePropertyOrThrow: require('./2016/DeletePropertyOrThrow'), - EnumerableOwnNames: require('./2016/EnumerableOwnNames'), - FromPropertyDescriptor: require('./2016/FromPropertyDescriptor'), - Get: require('./2016/Get'), - GetIterator: require('./2016/GetIterator'), - GetMethod: require('./2016/GetMethod'), - GetOwnPropertyKeys: require('./2016/GetOwnPropertyKeys'), - GetPrototypeFromConstructor: require('./2016/GetPrototypeFromConstructor'), - GetSubstitution: require('./2016/GetSubstitution'), - GetV: require('./2016/GetV'), - HasOwnProperty: require('./2016/HasOwnProperty'), - HasProperty: require('./2016/HasProperty'), - HourFromTime: require('./2016/HourFromTime'), - InLeapYear: require('./2016/InLeapYear'), - InstanceofOperator: require('./2016/InstanceofOperator'), - Invoke: require('./2016/Invoke'), - IsAccessorDescriptor: require('./2016/IsAccessorDescriptor'), - IsArray: require('./2016/IsArray'), - IsCallable: require('./2016/IsCallable'), - IsConcatSpreadable: require('./2016/IsConcatSpreadable'), - IsConstructor: require('./2016/IsConstructor'), - IsDataDescriptor: require('./2016/IsDataDescriptor'), - IsExtensible: require('./2016/IsExtensible'), - IsGenericDescriptor: require('./2016/IsGenericDescriptor'), - IsInteger: require('./2016/IsInteger'), - IsPromise: require('./2016/IsPromise'), - IsPropertyDescriptor: require('./2016/IsPropertyDescriptor'), - IsPropertyKey: require('./2016/IsPropertyKey'), - IsRegExp: require('./2016/IsRegExp'), - IterableToArrayLike: require('./2016/IterableToArrayLike'), - IteratorClose: require('./2016/IteratorClose'), - IteratorComplete: require('./2016/IteratorComplete'), - IteratorNext: require('./2016/IteratorNext'), - IteratorStep: require('./2016/IteratorStep'), - IteratorValue: require('./2016/IteratorValue'), - MakeDate: require('./2016/MakeDate'), - MakeDay: require('./2016/MakeDay'), - MakeTime: require('./2016/MakeTime'), - MinFromTime: require('./2016/MinFromTime'), - modulo: require('./2016/modulo'), - MonthFromTime: require('./2016/MonthFromTime'), - msFromTime: require('./2016/msFromTime'), - ObjectCreate: require('./2016/ObjectCreate'), - OrdinaryDefineOwnProperty: require('./2016/OrdinaryDefineOwnProperty'), - OrdinaryGetOwnProperty: require('./2016/OrdinaryGetOwnProperty'), - OrdinaryGetPrototypeOf: require('./2016/OrdinaryGetPrototypeOf'), - OrdinarySetPrototypeOf: require('./2016/OrdinarySetPrototypeOf'), - OrdinaryHasInstance: require('./2016/OrdinaryHasInstance'), - OrdinaryHasProperty: require('./2016/OrdinaryHasProperty'), - RegExpExec: require('./2016/RegExpExec'), - RequireObjectCoercible: require('./2016/RequireObjectCoercible'), - SameValue: require('./2016/SameValue'), - SameValueNonNumber: require('./2016/SameValueNonNumber'), - SameValueZero: require('./2016/SameValueZero'), - SecFromTime: require('./2016/SecFromTime'), - Set: require('./2016/Set'), - SetFunctionName: require('./2016/SetFunctionName'), - SetIntegrityLevel: require('./2016/SetIntegrityLevel'), - SpeciesConstructor: require('./2016/SpeciesConstructor'), - SymbolDescriptiveString: require('./2016/SymbolDescriptiveString'), - TestIntegrityLevel: require('./2016/TestIntegrityLevel'), - thisBooleanValue: require('./2016/thisBooleanValue'), - thisNumberValue: require('./2016/thisNumberValue'), - thisStringValue: require('./2016/thisStringValue'), - thisTimeValue: require('./2016/thisTimeValue'), - TimeClip: require('./2016/TimeClip'), - TimeFromYear: require('./2016/TimeFromYear'), - TimeWithinDay: require('./2016/TimeWithinDay'), - ToBoolean: require('./2016/ToBoolean'), - ToDateString: require('./2016/ToDateString'), - ToInt16: require('./2016/ToInt16'), - ToInt32: require('./2016/ToInt32'), - ToInt8: require('./2016/ToInt8'), - ToInteger: require('./2016/ToInteger'), - ToLength: require('./2016/ToLength'), - ToNumber: require('./2016/ToNumber'), - ToObject: require('./2016/ToObject'), - ToPrimitive: require('./2016/ToPrimitive'), - ToPropertyDescriptor: require('./2016/ToPropertyDescriptor'), - ToPropertyKey: require('./2016/ToPropertyKey'), - ToString: require('./2016/ToString'), - ToUint16: require('./2016/ToUint16'), - ToUint32: require('./2016/ToUint32'), - ToUint8: require('./2016/ToUint8'), - ToUint8Clamp: require('./2016/ToUint8Clamp'), - Type: require('./2016/Type'), - ValidateAndApplyPropertyDescriptor: require('./2016/ValidateAndApplyPropertyDescriptor'), - WeekDay: require('./2016/WeekDay'), - YearFromTime: require('./2016/YearFromTime') -}; - -module.exports = ES2016; diff --git a/node_modules/es-abstract/es2017.js b/node_modules/es-abstract/es2017.js deleted file mode 100644 index 5f317b7..0000000 --- a/node_modules/es-abstract/es2017.js +++ /dev/null @@ -1,120 +0,0 @@ -'use strict'; - -/* eslint global-require: 0 */ -// https://www.ecma-international.org/ecma-262/8.0/#sec-abstract-operations -var ES2017 = { - 'Abstract Equality Comparison': require('./2017/AbstractEqualityComparison'), - 'Abstract Relational Comparison': require('./2017/AbstractRelationalComparison'), - 'Strict Equality Comparison': require('./2017/StrictEqualityComparison'), - AdvanceStringIndex: require('./2017/AdvanceStringIndex'), - ArrayCreate: require('./2017/ArrayCreate'), - ArraySetLength: require('./2017/ArraySetLength'), - ArraySpeciesCreate: require('./2017/ArraySpeciesCreate'), - Call: require('./2017/Call'), - CanonicalNumericIndexString: require('./2017/CanonicalNumericIndexString'), - CompletePropertyDescriptor: require('./2017/CompletePropertyDescriptor'), - CreateDataProperty: require('./2017/CreateDataProperty'), - CreateDataPropertyOrThrow: require('./2017/CreateDataPropertyOrThrow'), - CreateHTML: require('./2017/CreateHTML'), - CreateIterResultObject: require('./2017/CreateIterResultObject'), - CreateListFromArrayLike: require('./2017/CreateListFromArrayLike'), - CreateMethodProperty: require('./2017/CreateMethodProperty'), - DateFromTime: require('./2017/DateFromTime'), - Day: require('./2017/Day'), - DayFromYear: require('./2017/DayFromYear'), - DaysInYear: require('./2017/DaysInYear'), - DayWithinYear: require('./2017/DayWithinYear'), - DefinePropertyOrThrow: require('./2017/DefinePropertyOrThrow'), - DeletePropertyOrThrow: require('./2017/DeletePropertyOrThrow'), - EnumerableOwnProperties: require('./2017/EnumerableOwnProperties'), - FromPropertyDescriptor: require('./2017/FromPropertyDescriptor'), - Get: require('./2017/Get'), - GetIterator: require('./2017/GetIterator'), - GetMethod: require('./2017/GetMethod'), - GetOwnPropertyKeys: require('./2017/GetOwnPropertyKeys'), - GetPrototypeFromConstructor: require('./2017/GetPrototypeFromConstructor'), - GetSubstitution: require('./2017/GetSubstitution'), - GetV: require('./2017/GetV'), - HasOwnProperty: require('./2017/HasOwnProperty'), - HasProperty: require('./2017/HasProperty'), - HourFromTime: require('./2017/HourFromTime'), - InLeapYear: require('./2017/InLeapYear'), - InstanceofOperator: require('./2017/InstanceofOperator'), - Invoke: require('./2017/Invoke'), - IsAccessorDescriptor: require('./2017/IsAccessorDescriptor'), - IsArray: require('./2017/IsArray'), - IsCallable: require('./2017/IsCallable'), - IsConcatSpreadable: require('./2017/IsConcatSpreadable'), - IsConstructor: require('./2017/IsConstructor'), - IsDataDescriptor: require('./2017/IsDataDescriptor'), - IsExtensible: require('./2017/IsExtensible'), - IsGenericDescriptor: require('./2017/IsGenericDescriptor'), - IsInteger: require('./2017/IsInteger'), - IsPromise: require('./2017/IsPromise'), - IsPropertyDescriptor: require('./2017/IsPropertyDescriptor'), - IsPropertyKey: require('./2017/IsPropertyKey'), - IsRegExp: require('./2017/IsRegExp'), - IterableToList: require('./2017/IterableToList'), - IteratorClose: require('./2017/IteratorClose'), - IteratorComplete: require('./2017/IteratorComplete'), - IteratorNext: require('./2017/IteratorNext'), - IteratorStep: require('./2017/IteratorStep'), - IteratorValue: require('./2017/IteratorValue'), - MakeDate: require('./2017/MakeDate'), - MakeDay: require('./2017/MakeDay'), - MakeTime: require('./2017/MakeTime'), - MinFromTime: require('./2017/MinFromTime'), - modulo: require('./2017/modulo'), - MonthFromTime: require('./2017/MonthFromTime'), - msFromTime: require('./2017/msFromTime'), - ObjectCreate: require('./2017/ObjectCreate'), - OrdinaryDefineOwnProperty: require('./2017/OrdinaryDefineOwnProperty'), - OrdinaryGetOwnProperty: require('./2017/OrdinaryGetOwnProperty'), - OrdinarySetPrototypeOf: require('./2017/OrdinarySetPrototypeOf'), - OrdinaryGetPrototypeOf: require('./2017/OrdinaryGetPrototypeOf'), - OrdinaryHasInstance: require('./2017/OrdinaryHasInstance'), - OrdinaryHasProperty: require('./2017/OrdinaryHasProperty'), - RegExpExec: require('./2017/RegExpExec'), - RequireObjectCoercible: require('./2017/RequireObjectCoercible'), - SameValue: require('./2017/SameValue'), - SameValueNonNumber: require('./2017/SameValueNonNumber'), - SameValueZero: require('./2017/SameValueZero'), - SecFromTime: require('./2017/SecFromTime'), - Set: require('./2017/Set'), - SetFunctionName: require('./2017/SetFunctionName'), - SetIntegrityLevel: require('./2017/SetIntegrityLevel'), - SpeciesConstructor: require('./2017/SpeciesConstructor'), - SymbolDescriptiveString: require('./2017/SymbolDescriptiveString'), - TestIntegrityLevel: require('./2017/TestIntegrityLevel'), - thisBooleanValue: require('./2017/thisBooleanValue'), - thisNumberValue: require('./2017/thisNumberValue'), - thisStringValue: require('./2017/thisStringValue'), - thisTimeValue: require('./2017/thisTimeValue'), - TimeClip: require('./2017/TimeClip'), - TimeFromYear: require('./2017/TimeFromYear'), - TimeWithinDay: require('./2017/TimeWithinDay'), - ToBoolean: require('./2017/ToBoolean'), - ToDateString: require('./2017/ToDateString'), - ToIndex: require('./2017/ToIndex'), - ToInt16: require('./2017/ToInt16'), - ToInt32: require('./2017/ToInt32'), - ToInt8: require('./2017/ToInt8'), - ToInteger: require('./2017/ToInteger'), - ToLength: require('./2017/ToLength'), - ToNumber: require('./2017/ToNumber'), - ToObject: require('./2017/ToObject'), - ToPrimitive: require('./2017/ToPrimitive'), - ToPropertyDescriptor: require('./2017/ToPropertyDescriptor'), - ToPropertyKey: require('./2017/ToPropertyKey'), - ToString: require('./2017/ToString'), - ToUint16: require('./2017/ToUint16'), - ToUint32: require('./2017/ToUint32'), - ToUint8: require('./2017/ToUint8'), - ToUint8Clamp: require('./2017/ToUint8Clamp'), - Type: require('./2017/Type'), - ValidateAndApplyPropertyDescriptor: require('./2017/ValidateAndApplyPropertyDescriptor'), - WeekDay: require('./2017/WeekDay'), - YearFromTime: require('./2017/YearFromTime') -}; - -module.exports = ES2017; diff --git a/node_modules/es-abstract/es2018.js b/node_modules/es-abstract/es2018.js deleted file mode 100644 index e68910b..0000000 --- a/node_modules/es-abstract/es2018.js +++ /dev/null @@ -1,126 +0,0 @@ -'use strict'; - -/* eslint global-require: 0 */ -// https://www.ecma-international.org/ecma-262/9.0/#sec-abstract-operations -var ES2018 = { - 'Abstract Equality Comparison': require('./2018/AbstractEqualityComparison'), - 'Abstract Relational Comparison': require('./2018/AbstractRelationalComparison'), - 'Strict Equality Comparison': require('./2018/StrictEqualityComparison'), - AdvanceStringIndex: require('./2018/AdvanceStringIndex'), - ArrayCreate: require('./2018/ArrayCreate'), - ArraySetLength: require('./2018/ArraySetLength'), - ArraySpeciesCreate: require('./2018/ArraySpeciesCreate'), - Call: require('./2018/Call'), - CanonicalNumericIndexString: require('./2018/CanonicalNumericIndexString'), - CompletePropertyDescriptor: require('./2018/CompletePropertyDescriptor'), - CopyDataProperties: require('./2018/CopyDataProperties'), - CreateDataProperty: require('./2018/CreateDataProperty'), - CreateDataPropertyOrThrow: require('./2018/CreateDataPropertyOrThrow'), - CreateHTML: require('./2018/CreateHTML'), - CreateIterResultObject: require('./2018/CreateIterResultObject'), - CreateListFromArrayLike: require('./2018/CreateListFromArrayLike'), - CreateMethodProperty: require('./2018/CreateMethodProperty'), - DateFromTime: require('./2018/DateFromTime'), - DateString: require('./2018/DateString'), - Day: require('./2018/Day'), - DayFromYear: require('./2018/DayFromYear'), - DaysInYear: require('./2018/DaysInYear'), - DayWithinYear: require('./2018/DayWithinYear'), - DefinePropertyOrThrow: require('./2018/DefinePropertyOrThrow'), - DeletePropertyOrThrow: require('./2018/DeletePropertyOrThrow'), - EnumerableOwnPropertyNames: require('./2018/EnumerableOwnPropertyNames'), - FromPropertyDescriptor: require('./2018/FromPropertyDescriptor'), - Get: require('./2018/Get'), - GetIterator: require('./2018/GetIterator'), - GetMethod: require('./2018/GetMethod'), - GetOwnPropertyKeys: require('./2018/GetOwnPropertyKeys'), - GetPrototypeFromConstructor: require('./2018/GetPrototypeFromConstructor'), - GetSubstitution: require('./2018/GetSubstitution'), - GetV: require('./2018/GetV'), - HasOwnProperty: require('./2018/HasOwnProperty'), - HasProperty: require('./2018/HasProperty'), - HourFromTime: require('./2018/HourFromTime'), - InLeapYear: require('./2018/InLeapYear'), - InstanceofOperator: require('./2018/InstanceofOperator'), - Invoke: require('./2018/Invoke'), - IsAccessorDescriptor: require('./2018/IsAccessorDescriptor'), - IsArray: require('./2018/IsArray'), - IsCallable: require('./2018/IsCallable'), - IsConcatSpreadable: require('./2018/IsConcatSpreadable'), - IsConstructor: require('./2018/IsConstructor'), - IsDataDescriptor: require('./2018/IsDataDescriptor'), - IsExtensible: require('./2018/IsExtensible'), - IsGenericDescriptor: require('./2018/IsGenericDescriptor'), - IsInteger: require('./2018/IsInteger'), - IsPromise: require('./2018/IsPromise'), - IsPropertyKey: require('./2018/IsPropertyKey'), - IsRegExp: require('./2018/IsRegExp'), - IsStringPrefix: require('./2018/IsStringPrefix'), - IterableToList: require('./2018/IterableToList'), - IteratorClose: require('./2018/IteratorClose'), - IteratorComplete: require('./2018/IteratorComplete'), - IteratorNext: require('./2018/IteratorNext'), - IteratorStep: require('./2018/IteratorStep'), - IteratorValue: require('./2018/IteratorValue'), - MakeDate: require('./2018/MakeDate'), - MakeDay: require('./2018/MakeDay'), - MakeTime: require('./2018/MakeTime'), - MinFromTime: require('./2018/MinFromTime'), - modulo: require('./2018/modulo'), - MonthFromTime: require('./2018/MonthFromTime'), - msFromTime: require('./2018/msFromTime'), - NumberToString: require('./2018/NumberToString'), - ObjectCreate: require('./2018/ObjectCreate'), - OrdinaryDefineOwnProperty: require('./2018/OrdinaryDefineOwnProperty'), - OrdinaryGetOwnProperty: require('./2018/OrdinaryGetOwnProperty'), - OrdinaryGetPrototypeOf: require('./2018/OrdinaryGetPrototypeOf'), - OrdinarySetPrototypeOf: require('./2018/OrdinarySetPrototypeOf'), - OrdinaryHasInstance: require('./2018/OrdinaryHasInstance'), - OrdinaryHasProperty: require('./2018/OrdinaryHasProperty'), - PromiseResolve: require('./2018/PromiseResolve'), - RegExpExec: require('./2018/RegExpExec'), - RequireObjectCoercible: require('./2018/RequireObjectCoercible'), - SameValue: require('./2018/SameValue'), - SameValueNonNumber: require('./2018/SameValueNonNumber'), - SameValueZero: require('./2018/SameValueZero'), - SecFromTime: require('./2018/SecFromTime'), - Set: require('./2018/Set'), - SetFunctionName: require('./2018/SetFunctionName'), - SetIntegrityLevel: require('./2018/SetIntegrityLevel'), - SpeciesConstructor: require('./2018/SpeciesConstructor'), - SymbolDescriptiveString: require('./2018/SymbolDescriptiveString'), - TestIntegrityLevel: require('./2018/TestIntegrityLevel'), - thisBooleanValue: require('./2018/thisBooleanValue'), - thisNumberValue: require('./2018/thisNumberValue'), - thisStringValue: require('./2018/thisStringValue'), - thisSymbolValue: require('./2018/thisSymbolValue'), - thisTimeValue: require('./2018/thisTimeValue'), - TimeClip: require('./2018/TimeClip'), - TimeFromYear: require('./2018/TimeFromYear'), - TimeString: require('./2018/TimeString'), - TimeWithinDay: require('./2018/TimeWithinDay'), - ToBoolean: require('./2018/ToBoolean'), - ToDateString: require('./2018/ToDateString'), - ToIndex: require('./2018/ToIndex'), - ToInt16: require('./2018/ToInt16'), - ToInt32: require('./2018/ToInt32'), - ToInt8: require('./2018/ToInt8'), - ToInteger: require('./2018/ToInteger'), - ToLength: require('./2018/ToLength'), - ToNumber: require('./2018/ToNumber'), - ToObject: require('./2018/ToObject'), - ToPrimitive: require('./2018/ToPrimitive'), - ToPropertyDescriptor: require('./2018/ToPropertyDescriptor'), - ToPropertyKey: require('./2018/ToPropertyKey'), - ToString: require('./2018/ToString'), - ToUint16: require('./2018/ToUint16'), - ToUint32: require('./2018/ToUint32'), - ToUint8: require('./2018/ToUint8'), - ToUint8Clamp: require('./2018/ToUint8Clamp'), - Type: require('./2018/Type'), - ValidateAndApplyPropertyDescriptor: require('./2018/ValidateAndApplyPropertyDescriptor'), - WeekDay: require('./2018/WeekDay'), - YearFromTime: require('./2018/YearFromTime') -}; - -module.exports = ES2018; diff --git a/node_modules/es-abstract/es2019.js b/node_modules/es-abstract/es2019.js deleted file mode 100644 index 3bd65e4..0000000 --- a/node_modules/es-abstract/es2019.js +++ /dev/null @@ -1,129 +0,0 @@ -'use strict'; - -/* eslint global-require: 0 */ -// https://www.ecma-international.org/ecma-262/10.0/#sec-abstract-operations -var ES2019 = { - 'Abstract Equality Comparison': require('./2019/AbstractEqualityComparison'), - 'Abstract Relational Comparison': require('./2019/AbstractRelationalComparison'), - 'Strict Equality Comparison': require('./2019/StrictEqualityComparison'), - AddEntriesFromIterable: require('./2019/AddEntriesFromIterable'), - AdvanceStringIndex: require('./2019/AdvanceStringIndex'), - ArrayCreate: require('./2019/ArrayCreate'), - ArraySetLength: require('./2019/ArraySetLength'), - ArraySpeciesCreate: require('./2019/ArraySpeciesCreate'), - Call: require('./2019/Call'), - CanonicalNumericIndexString: require('./2019/CanonicalNumericIndexString'), - CompletePropertyDescriptor: require('./2019/CompletePropertyDescriptor'), - CopyDataProperties: require('./2019/CopyDataProperties'), - CreateDataProperty: require('./2019/CreateDataProperty'), - CreateDataPropertyOrThrow: require('./2019/CreateDataPropertyOrThrow'), - CreateHTML: require('./2019/CreateHTML'), - CreateIterResultObject: require('./2019/CreateIterResultObject'), - CreateListFromArrayLike: require('./2019/CreateListFromArrayLike'), - CreateMethodProperty: require('./2019/CreateMethodProperty'), - DateFromTime: require('./2019/DateFromTime'), - DateString: require('./2019/DateString'), - Day: require('./2019/Day'), - DayFromYear: require('./2019/DayFromYear'), - DaysInYear: require('./2019/DaysInYear'), - DayWithinYear: require('./2019/DayWithinYear'), - DefinePropertyOrThrow: require('./2019/DefinePropertyOrThrow'), - DeletePropertyOrThrow: require('./2019/DeletePropertyOrThrow'), - EnumerableOwnPropertyNames: require('./2019/EnumerableOwnPropertyNames'), - FlattenIntoArray: require('./2019/FlattenIntoArray'), - FromPropertyDescriptor: require('./2019/FromPropertyDescriptor'), - Get: require('./2019/Get'), - GetIterator: require('./2019/GetIterator'), - GetMethod: require('./2019/GetMethod'), - GetOwnPropertyKeys: require('./2019/GetOwnPropertyKeys'), - GetPrototypeFromConstructor: require('./2019/GetPrototypeFromConstructor'), - GetSubstitution: require('./2019/GetSubstitution'), - GetV: require('./2019/GetV'), - HasOwnProperty: require('./2019/HasOwnProperty'), - HasProperty: require('./2019/HasProperty'), - HourFromTime: require('./2019/HourFromTime'), - InLeapYear: require('./2019/InLeapYear'), - InstanceofOperator: require('./2019/InstanceofOperator'), - Invoke: require('./2019/Invoke'), - IsAccessorDescriptor: require('./2019/IsAccessorDescriptor'), - IsArray: require('./2019/IsArray'), - IsCallable: require('./2019/IsCallable'), - IsConcatSpreadable: require('./2019/IsConcatSpreadable'), - IsConstructor: require('./2019/IsConstructor'), - IsDataDescriptor: require('./2019/IsDataDescriptor'), - IsExtensible: require('./2019/IsExtensible'), - IsGenericDescriptor: require('./2019/IsGenericDescriptor'), - IsInteger: require('./2019/IsInteger'), - IsPromise: require('./2019/IsPromise'), - IsPropertyKey: require('./2019/IsPropertyKey'), - IsRegExp: require('./2019/IsRegExp'), - IsStringPrefix: require('./2019/IsStringPrefix'), - IterableToList: require('./2019/IterableToList'), - IteratorClose: require('./2019/IteratorClose'), - IteratorComplete: require('./2019/IteratorComplete'), - IteratorNext: require('./2019/IteratorNext'), - IteratorStep: require('./2019/IteratorStep'), - IteratorValue: require('./2019/IteratorValue'), - MakeDate: require('./2019/MakeDate'), - MakeDay: require('./2019/MakeDay'), - MakeTime: require('./2019/MakeTime'), - MinFromTime: require('./2019/MinFromTime'), - modulo: require('./2019/modulo'), - MonthFromTime: require('./2019/MonthFromTime'), - msFromTime: require('./2019/msFromTime'), - NumberToString: require('./2019/NumberToString'), - ObjectCreate: require('./2019/ObjectCreate'), - OrdinaryDefineOwnProperty: require('./2019/OrdinaryDefineOwnProperty'), - OrdinaryGetOwnProperty: require('./2019/OrdinaryGetOwnProperty'), - OrdinaryGetPrototypeOf: require('./2019/OrdinaryGetPrototypeOf'), - OrdinarySetPrototypeOf: require('./2019/OrdinarySetPrototypeOf'), - OrdinaryHasInstance: require('./2019/OrdinaryHasInstance'), - OrdinaryHasProperty: require('./2019/OrdinaryHasProperty'), - PromiseResolve: require('./2019/PromiseResolve'), - RegExpExec: require('./2019/RegExpExec'), - RequireObjectCoercible: require('./2019/RequireObjectCoercible'), - SameValue: require('./2019/SameValue'), - SameValueNonNumber: require('./2019/SameValueNonNumber'), - SameValueZero: require('./2019/SameValueZero'), - SecFromTime: require('./2019/SecFromTime'), - Set: require('./2019/Set'), - SetFunctionName: require('./2019/SetFunctionName'), - SetIntegrityLevel: require('./2019/SetIntegrityLevel'), - SpeciesConstructor: require('./2019/SpeciesConstructor'), - SymbolDescriptiveString: require('./2019/SymbolDescriptiveString'), - TestIntegrityLevel: require('./2019/TestIntegrityLevel'), - thisBooleanValue: require('./2019/thisBooleanValue'), - thisNumberValue: require('./2019/thisNumberValue'), - thisStringValue: require('./2019/thisStringValue'), - thisSymbolValue: require('./2019/thisSymbolValue'), - thisTimeValue: require('./2019/thisTimeValue'), - TimeClip: require('./2019/TimeClip'), - TimeFromYear: require('./2019/TimeFromYear'), - TimeString: require('./2019/TimeString'), - TimeWithinDay: require('./2019/TimeWithinDay'), - ToBoolean: require('./2019/ToBoolean'), - ToDateString: require('./2019/ToDateString'), - ToIndex: require('./2019/ToIndex'), - ToInt16: require('./2019/ToInt16'), - ToInt32: require('./2019/ToInt32'), - ToInt8: require('./2019/ToInt8'), - ToInteger: require('./2019/ToInteger'), - ToLength: require('./2019/ToLength'), - ToNumber: require('./2019/ToNumber'), - ToObject: require('./2019/ToObject'), - ToPrimitive: require('./2019/ToPrimitive'), - ToPropertyDescriptor: require('./2019/ToPropertyDescriptor'), - ToPropertyKey: require('./2019/ToPropertyKey'), - ToString: require('./2019/ToString'), - ToUint16: require('./2019/ToUint16'), - ToUint32: require('./2019/ToUint32'), - ToUint8: require('./2019/ToUint8'), - ToUint8Clamp: require('./2019/ToUint8Clamp'), - TrimString: require('./2019/TrimString'), - Type: require('./2019/Type'), - ValidateAndApplyPropertyDescriptor: require('./2019/ValidateAndApplyPropertyDescriptor'), - WeekDay: require('./2019/WeekDay'), - YearFromTime: require('./2019/YearFromTime') -}; - -module.exports = ES2019; diff --git a/node_modules/es-abstract/es5.js b/node_modules/es-abstract/es5.js deleted file mode 100644 index 2cc9515..0000000 --- a/node_modules/es-abstract/es5.js +++ /dev/null @@ -1,49 +0,0 @@ -'use strict'; - -/* eslint global-require: 0 */ - -// https://es5.github.io/#x9 -module.exports = { - 'Abstract Equality Comparison': require('./5/AbstractEqualityComparison'), - 'Abstract Relational Comparison': require('./5/AbstractRelationalComparison'), - 'Strict Equality Comparison': require('./5/StrictEqualityComparison'), - CheckObjectCoercible: require('./5/CheckObjectCoercible'), - DateFromTime: require('./5/DateFromTime'), - Day: require('./5/Day'), - DayFromYear: require('./5/DayFromYear'), - DaysInYear: require('./5/DaysInYear'), - DayWithinYear: require('./5/DayWithinYear'), - FromPropertyDescriptor: require('./5/FromPropertyDescriptor'), - HourFromTime: require('./5/HourFromTime'), - InLeapYear: require('./5/InLeapYear'), - IsAccessorDescriptor: require('./5/IsAccessorDescriptor'), - IsCallable: require('./5/IsCallable'), - IsDataDescriptor: require('./5/IsDataDescriptor'), - IsGenericDescriptor: require('./5/IsGenericDescriptor'), - IsPropertyDescriptor: require('./5/IsPropertyDescriptor'), - MakeDate: require('./5/MakeDate'), - MakeDay: require('./5/MakeDay'), - MakeTime: require('./5/MakeTime'), - MinFromTime: require('./5/MinFromTime'), - modulo: require('./5/modulo'), - MonthFromTime: require('./5/MonthFromTime'), - msFromTime: require('./5/msFromTime'), - SameValue: require('./5/SameValue'), - SecFromTime: require('./5/SecFromTime'), - TimeClip: require('./5/TimeClip'), - TimeFromYear: require('./5/TimeFromYear'), - TimeWithinDay: require('./5/TimeWithinDay'), - ToBoolean: require('./5/ToBoolean'), - ToInt32: require('./5/ToInt32'), - ToInteger: require('./5/ToInteger'), - ToNumber: require('./5/ToNumber'), - ToObject: require('./5/ToObject'), - ToPrimitive: require('./5/ToPrimitive'), - ToPropertyDescriptor: require('./5/ToPropertyDescriptor'), - ToString: require('./5/ToString'), - ToUint16: require('./5/ToUint16'), - ToUint32: require('./5/ToUint32'), - Type: require('./5/Type'), - WeekDay: require('./5/WeekDay'), - YearFromTime: require('./5/YearFromTime') -}; diff --git a/node_modules/es-abstract/es6.js b/node_modules/es-abstract/es6.js deleted file mode 100644 index 2d1f4dc..0000000 --- a/node_modules/es-abstract/es6.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('./es2015'); diff --git a/node_modules/es-abstract/es7.js b/node_modules/es-abstract/es7.js deleted file mode 100644 index f2f15c0..0000000 --- a/node_modules/es-abstract/es7.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('./es2016'); diff --git a/node_modules/es-abstract/helpers/DefineOwnProperty.js b/node_modules/es-abstract/helpers/DefineOwnProperty.js deleted file mode 100644 index 99ace10..0000000 --- a/node_modules/es-abstract/helpers/DefineOwnProperty.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); - -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = null; - } -} - -var callBound = require('../helpers/callBound'); - -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); - -// eslint-disable-next-line max-params -module.exports = function DefineOwnProperty(IsDataDescriptor, SameValue, FromPropertyDescriptor, O, P, desc) { - if (!$defineProperty) { - if (!IsDataDescriptor(desc)) { - // ES3 does not support getters/setters - return false; - } - if (!desc['[[Configurable]]'] || !desc['[[Writable]]']) { - return false; - } - - // fallback for ES3 - if (P in O && $isEnumerable(O, P) !== !!desc['[[Enumerable]]']) { - // a non-enumerable existing property - return false; - } - - // property does not exist at all, or exists but is enumerable - var V = desc['[[Value]]']; - // eslint-disable-next-line no-param-reassign - O[P] = V; // will use [[Define]] - return SameValue(O[P], V); - } - $defineProperty(O, P, FromPropertyDescriptor(desc)); - return true; -}; diff --git a/node_modules/es-abstract/helpers/OwnPropertyKeys.js b/node_modules/es-abstract/helpers/OwnPropertyKeys.js deleted file mode 100644 index 7d02196..0000000 --- a/node_modules/es-abstract/helpers/OwnPropertyKeys.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var callBind = require('./callBind'); -var callBound = require('./callBound'); - -var $pushApply = callBind.apply(GetIntrinsic('%Array.prototype.push%')); -var $SymbolValueOf = callBound('Symbol.prototype.valueOf', true); -var $gOPN = GetIntrinsic('%Object.getOwnPropertyNames%', true); -var $gOPS = $SymbolValueOf ? GetIntrinsic('%Object.getOwnPropertySymbols%') : null; - -var keys = require('object-keys'); - -module.exports = function OwnPropertyKeys(source) { - var ownKeys = ($gOPN || keys)(source); - if ($gOPS) { - $pushApply(ownKeys, $gOPS(source)); - } - return ownKeys; -}; diff --git a/node_modules/es-abstract/helpers/assertRecord.js b/node_modules/es-abstract/helpers/assertRecord.js deleted file mode 100644 index 45e115a..0000000 --- a/node_modules/es-abstract/helpers/assertRecord.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); - -var has = require('has'); - -var predicates = { - // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type - 'Property Descriptor': function isPropertyDescriptor(Type, Desc) { - if (Type(Desc) !== 'Object') { - return false; - } - var allowed = { - '[[Configurable]]': true, - '[[Enumerable]]': true, - '[[Get]]': true, - '[[Set]]': true, - '[[Value]]': true, - '[[Writable]]': true - }; - - for (var key in Desc) { // eslint-disable-line - if (has(Desc, key) && !allowed[key]) { - return false; - } - } - - var isData = has(Desc, '[[Value]]'); - var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]'); - if (isData && IsAccessor) { - throw new $TypeError('Property Descriptors may not be both accessor and data descriptors'); - } - return true; - } -}; - -module.exports = function assertRecord(Type, recordType, argumentName, value) { - var predicate = predicates[recordType]; - if (typeof predicate !== 'function') { - throw new $SyntaxError('unknown record type: ' + recordType); - } - if (!predicate(Type, value)) { - throw new $TypeError(argumentName + ' must be a ' + recordType); - } -}; diff --git a/node_modules/es-abstract/helpers/assign.js b/node_modules/es-abstract/helpers/assign.js deleted file mode 100644 index 7e6666e..0000000 --- a/node_modules/es-abstract/helpers/assign.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var has = require('has'); - -var $assign = GetIntrinsic('%Object%').assign; - -module.exports = function assign(target, source) { - if ($assign) { - return $assign(target, source); - } - - // eslint-disable-next-line no-restricted-syntax - for (var key in source) { - if (has(source, key)) { - // eslint-disable-next-line no-param-reassign - target[key] = source[key]; - } - } - return target; -}; diff --git a/node_modules/es-abstract/helpers/callBind.js b/node_modules/es-abstract/helpers/callBind.js deleted file mode 100644 index dd206ab..0000000 --- a/node_modules/es-abstract/helpers/callBind.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var bind = require('function-bind'); - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Function = GetIntrinsic('%Function%'); -var $apply = $Function.apply; -var $call = $Function.call; - -module.exports = function callBind() { - return bind.apply($call, arguments); -}; - -module.exports.apply = function applyBind() { - return bind.apply($apply, arguments); -}; diff --git a/node_modules/es-abstract/helpers/callBound.js b/node_modules/es-abstract/helpers/callBound.js deleted file mode 100644 index 9dc8fc5..0000000 --- a/node_modules/es-abstract/helpers/callBound.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var callBind = require('./callBind'); - -var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); - -module.exports = function callBoundIntrinsic(name, allowMissing) { - var intrinsic = GetIntrinsic(name, !!allowMissing); - if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.')) { - return callBind(intrinsic); - } - return intrinsic; -}; diff --git a/node_modules/es-abstract/helpers/every.js b/node_modules/es-abstract/helpers/every.js deleted file mode 100644 index 42a4582..0000000 --- a/node_modules/es-abstract/helpers/every.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -module.exports = function every(array, predicate) { - for (var i = 0; i < array.length; i += 1) { - if (!predicate(array[i], i, array)) { - return false; - } - } - return true; -}; diff --git a/node_modules/es-abstract/helpers/forEach.js b/node_modules/es-abstract/helpers/forEach.js deleted file mode 100644 index 35915a6..0000000 --- a/node_modules/es-abstract/helpers/forEach.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -module.exports = function forEach(array, callback) { - for (var i = 0; i < array.length; i += 1) { - callback(array[i], i, array); // eslint-disable-line callback-return - } -}; diff --git a/node_modules/es-abstract/helpers/getInferredName.js b/node_modules/es-abstract/helpers/getInferredName.js deleted file mode 100644 index 2dab6e7..0000000 --- a/node_modules/es-abstract/helpers/getInferredName.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var getInferredName; -try { - // eslint-disable-next-line no-new-func - getInferredName = Function('s', 'return { [s]() {} }[s].name;'); -} catch (e) {} - -var inferred = function () {}; -module.exports = getInferredName && inferred.name === 'inferred' ? getInferredName : null; diff --git a/node_modules/es-abstract/helpers/getIteratorMethod.js b/node_modules/es-abstract/helpers/getIteratorMethod.js deleted file mode 100644 index 02f932c..0000000 --- a/node_modules/es-abstract/helpers/getIteratorMethod.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var hasSymbols = require('has-symbols')(); -var GetIntrinsic = require('../GetIntrinsic'); -var callBound = require('./callBound'); - -var $iterator = GetIntrinsic('%Symbol.iterator%', true); -var $stringSlice = callBound('String.prototype.slice'); - -module.exports = function getIteratorMethod(ES, iterable) { - var usingIterator; - if (hasSymbols) { - usingIterator = ES.GetMethod(iterable, $iterator); - } else if (ES.IsArray(iterable)) { - usingIterator = function () { - var i = -1; - var arr = this; // eslint-disable-line no-invalid-this - return { - next: function () { - i += 1; - return { - done: i >= arr.length, - value: arr[i] - }; - } - }; - }; - } else if (ES.Type(iterable) === 'String') { - usingIterator = function () { - var i = 0; - return { - next: function () { - var nextIndex = ES.AdvanceStringIndex(iterable, i, true); - var value = $stringSlice(iterable, i, nextIndex); - i = nextIndex; - return { - done: nextIndex > iterable.length, - value: value - }; - } - }; - }; - } - return usingIterator; -}; diff --git a/node_modules/es-abstract/helpers/getOwnPropertyDescriptor.js b/node_modules/es-abstract/helpers/getOwnPropertyDescriptor.js deleted file mode 100644 index 71168e9..0000000 --- a/node_modules/es-abstract/helpers/getOwnPropertyDescriptor.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%'); -if ($gOPD) { - try { - $gOPD([], 'length'); - } catch (e) { - // IE 8 has a broken gOPD - $gOPD = null; - } -} - -module.exports = $gOPD; diff --git a/node_modules/es-abstract/helpers/getProto.js b/node_modules/es-abstract/helpers/getProto.js deleted file mode 100644 index af10fd8..0000000 --- a/node_modules/es-abstract/helpers/getProto.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var originalGetProto = GetIntrinsic('%Object.getPrototypeOf%', true); -var $ArrayProto = GetIntrinsic('%Array.prototype%'); - -module.exports = originalGetProto || ( - // eslint-disable-next-line no-proto - [].__proto__ === $ArrayProto - ? function (O) { - return O.__proto__; // eslint-disable-line no-proto - } - : null -); diff --git a/node_modules/es-abstract/helpers/getSymbolDescription.js b/node_modules/es-abstract/helpers/getSymbolDescription.js deleted file mode 100644 index dff8fcc..0000000 --- a/node_modules/es-abstract/helpers/getSymbolDescription.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var callBound = require('./callBound'); - -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var symToStr = callBound('Symbol.prototype.toString', true); - -var getInferredName = require('./getInferredName'); - -module.exports = function getSymbolDescription(symbol) { - if (!symToStr) { - throw new $SyntaxError('Symbols are not supported in this environment'); - } - var str = symToStr(symbol); // will throw if not a symbol - - if (getInferredName) { - var name = getInferredName(symbol); - if (name === '') { return; } - // eslint-disable-next-line consistent-return - return name.slice(1, -1); // name.slice('['.length, -']'.length); - } - - var desc = str.slice(7, -1); // str.slice('Symbol('.length, -')'.length); - if (desc) { - // eslint-disable-next-line consistent-return - return desc; - } -}; diff --git a/node_modules/es-abstract/helpers/isFinite.js b/node_modules/es-abstract/helpers/isFinite.js deleted file mode 100644 index 9e7cd4f..0000000 --- a/node_modules/es-abstract/helpers/isFinite.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -var $isNaN = Number.isNaN || function (a) { return a !== a; }; - -module.exports = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; }; diff --git a/node_modules/es-abstract/helpers/isNaN.js b/node_modules/es-abstract/helpers/isNaN.js deleted file mode 100644 index cb8631d..0000000 --- a/node_modules/es-abstract/helpers/isNaN.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -module.exports = Number.isNaN || function isNaN(a) { - return a !== a; -}; diff --git a/node_modules/es-abstract/helpers/isPrefixOf.js b/node_modules/es-abstract/helpers/isPrefixOf.js deleted file mode 100644 index b67d640..0000000 --- a/node_modules/es-abstract/helpers/isPrefixOf.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $strSlice = require('../helpers/callBound')('String.prototype.slice'); - -module.exports = function isPrefixOf(prefix, string) { - if (prefix === string) { - return true; - } - if (prefix.length > string.length) { - return false; - } - return $strSlice(string, 0, prefix.length) === prefix; -}; diff --git a/node_modules/es-abstract/helpers/isPrimitive.js b/node_modules/es-abstract/helpers/isPrimitive.js deleted file mode 100644 index 06f0bf0..0000000 --- a/node_modules/es-abstract/helpers/isPrimitive.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -module.exports = function isPrimitive(value) { - return value === null || (typeof value !== 'function' && typeof value !== 'object'); -}; diff --git a/node_modules/es-abstract/helpers/isPropertyDescriptor.js b/node_modules/es-abstract/helpers/isPropertyDescriptor.js deleted file mode 100644 index 23e8995..0000000 --- a/node_modules/es-abstract/helpers/isPropertyDescriptor.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var has = require('has'); -var $TypeError = GetIntrinsic('%TypeError%'); - -module.exports = function IsPropertyDescriptor(ES, Desc) { - if (ES.Type(Desc) !== 'Object') { - return false; - } - var allowed = { - '[[Configurable]]': true, - '[[Enumerable]]': true, - '[[Get]]': true, - '[[Set]]': true, - '[[Value]]': true, - '[[Writable]]': true - }; - - for (var key in Desc) { // eslint-disable-line - if (has(Desc, key) && !allowed[key]) { - return false; - } - } - - if (ES.IsDataDescriptor(Desc) && ES.IsAccessorDescriptor(Desc)) { - throw new $TypeError('Property Descriptors may not be both accessor and data descriptors'); - } - return true; -}; diff --git a/node_modules/es-abstract/helpers/isSamePropertyDescriptor.js b/node_modules/es-abstract/helpers/isSamePropertyDescriptor.js deleted file mode 100644 index a6162a1..0000000 --- a/node_modules/es-abstract/helpers/isSamePropertyDescriptor.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var every = require('./every'); - -module.exports = function isSamePropertyDescriptor(ES, D1, D2) { - var fields = [ - '[[Configurable]]', - '[[Enumerable]]', - '[[Get]]', - '[[Set]]', - '[[Value]]', - '[[Writable]]' - ]; - return every(fields, function (field) { - if ((field in D1) !== (field in D2)) { - return false; - } - return ES.SameValue(D1[field], D2[field]); - }); -}; diff --git a/node_modules/es-abstract/helpers/maxSafeInteger.js b/node_modules/es-abstract/helpers/maxSafeInteger.js deleted file mode 100644 index 2fe8f38..0000000 --- a/node_modules/es-abstract/helpers/maxSafeInteger.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); -var $Number = GetIntrinsic('%Number%'); - -module.exports = $Number.MAX_SAFE_INTEGER || $Math.pow(2, 53) - 1; diff --git a/node_modules/es-abstract/helpers/mod.js b/node_modules/es-abstract/helpers/mod.js deleted file mode 100644 index 70f0eea..0000000 --- a/node_modules/es-abstract/helpers/mod.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -module.exports = function mod(number, modulo) { - var remain = number % modulo; - return Math.floor(remain >= 0 ? remain : remain + modulo); -}; diff --git a/node_modules/es-abstract/helpers/padTimeComponent.js b/node_modules/es-abstract/helpers/padTimeComponent.js deleted file mode 100644 index cbd8d06..0000000 --- a/node_modules/es-abstract/helpers/padTimeComponent.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var callBound = require('../helpers/callBound'); - -var $strSlice = callBound('String.prototype.slice'); - -module.exports = function padTimeComponent(c, count) { - return $strSlice('00' + c, -(count || 2)); -}; diff --git a/node_modules/es-abstract/helpers/regexTester.js b/node_modules/es-abstract/helpers/regexTester.js deleted file mode 100644 index 982cc9f..0000000 --- a/node_modules/es-abstract/helpers/regexTester.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $test = GetIntrinsic('RegExp.prototype.test'); - -var callBind = require('./callBind'); - -module.exports = function regexTester(regex) { - return callBind($test, regex); -}; diff --git a/node_modules/es-abstract/helpers/setProto.js b/node_modules/es-abstract/helpers/setProto.js deleted file mode 100644 index 29ec991..0000000 --- a/node_modules/es-abstract/helpers/setProto.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var originalSetProto = GetIntrinsic('%Object.setPrototypeOf%', true); -var $ArrayProto = GetIntrinsic('%Array.prototype%'); - -module.exports = originalSetProto || ( - // eslint-disable-next-line no-proto, no-negated-condition - [].__proto__ !== $ArrayProto - ? null - : function (O, proto) { - O.__proto__ = proto; // eslint-disable-line no-proto, no-param-reassign - return O; - } -); diff --git a/node_modules/es-abstract/helpers/sign.js b/node_modules/es-abstract/helpers/sign.js deleted file mode 100644 index 598ea7d..0000000 --- a/node_modules/es-abstract/helpers/sign.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -module.exports = function sign(number) { - return number >= 0 ? 1 : -1; -}; diff --git a/node_modules/es-abstract/helpers/timeConstants.js b/node_modules/es-abstract/helpers/timeConstants.js deleted file mode 100644 index c275b40..0000000 --- a/node_modules/es-abstract/helpers/timeConstants.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var HoursPerDay = 24; -var MinutesPerHour = 60; -var SecondsPerMinute = 60; -var msPerSecond = 1e3; -var msPerMinute = msPerSecond * SecondsPerMinute; -var msPerHour = msPerMinute * MinutesPerHour; -var msPerDay = 86400000; - -module.exports = { - HoursPerDay: HoursPerDay, - MinutesPerHour: MinutesPerHour, - SecondsPerMinute: SecondsPerMinute, - msPerSecond: msPerSecond, - msPerMinute: msPerMinute, - msPerHour: msPerHour, - msPerDay: msPerDay -}; diff --git a/node_modules/es-abstract/index.js b/node_modules/es-abstract/index.js deleted file mode 100644 index 7cef039..0000000 --- a/node_modules/es-abstract/index.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -var assign = require('./helpers/assign'); - -var ES5 = require('./es5'); -var ES2015 = require('./es2015'); -var ES2016 = require('./es2016'); -var ES2017 = require('./es2017'); -var ES2018 = require('./es2018'); -var ES2019 = require('./es2019'); - -var ES = { - ES5: ES5, - ES6: ES2015, - ES2015: ES2015, - ES7: ES2016, - ES2016: ES2016, - ES2017: ES2017, - ES2018: ES2018, - ES2019: ES2019 -}; -assign(ES, ES5); -delete ES.CheckObjectCoercible; // renamed in ES6 to RequireObjectCoercible -assign(ES, ES2015); - -module.exports = ES; diff --git a/node_modules/es-abstract/operations/.eslintrc b/node_modules/es-abstract/operations/.eslintrc deleted file mode 100644 index bcd76f7..0000000 --- a/node_modules/es-abstract/operations/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "rules": { - "id-length": 0, - }, -} diff --git a/node_modules/es-abstract/operations/2015.js b/node_modules/es-abstract/operations/2015.js deleted file mode 100644 index 3f6c358..0000000 --- a/node_modules/es-abstract/operations/2015.js +++ /dev/null @@ -1,117 +0,0 @@ -'use strict'; - -module.exports = { - IsPropertyDescriptor: 'https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type', // not actually an abstract op - - 'Abstract Equality Comparison': 'https://ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison', - 'Abstract Relational Comparison': 'https://ecma-international.org/ecma-262/6.0/#sec-abstract-relational-comparison', - 'Strict Equality Comparison': 'https://ecma-international.org/ecma-262/6.0/#sec-strict-equality-comparison', - AdvanceStringIndex: 'https://ecma-international.org/ecma-262/6.0/#sec-advancestringindex', - ArrayCreate: 'https://ecma-international.org/ecma-262/6.0/#sec-arraycreate', - ArraySetLength: 'https://ecma-international.org/ecma-262/6.0/#sec-arraysetlength', - ArraySpeciesCreate: 'https://ecma-international.org/ecma-262/6.0/#sec-arrayspeciescreate', - Call: 'https://ecma-international.org/ecma-262/6.0/#sec-call', - CanonicalNumericIndexString: 'https://ecma-international.org/ecma-262/6.0/#sec-canonicalnumericindexstring', - CompletePropertyDescriptor: 'https://ecma-international.org/ecma-262/6.0/#sec-completepropertydescriptor', - Construct: 'https://ecma-international.org/ecma-262/6.0/#sec-construct', - CreateArrayFromList: 'https://ecma-international.org/ecma-262/6.0/#sec-createarrayfromlist', - CreateDataProperty: 'https://ecma-international.org/ecma-262/6.0/#sec-createdataproperty', - CreateDataPropertyOrThrow: 'https://ecma-international.org/ecma-262/6.0/#sec-createdatapropertyorthrow', - CreateHTML: 'https://ecma-international.org/ecma-262/6.0/#sec-createhtml', - CreateIterResultObject: 'https://ecma-international.org/ecma-262/6.0/#sec-createiterresultobject', - CreateListFromArrayLike: 'https://ecma-international.org/ecma-262/6.0/#sec-createlistfromarraylike', - CreateListIterator: 'https://ecma-international.org/ecma-262/6.0/#sec-createlistiterator', - CreateMethodProperty: 'https://ecma-international.org/ecma-262/6.0/#sec-createmethodproperty', - DateFromTime: 'https://ecma-international.org/ecma-262/6.0/#sec-date-number', - Day: 'https://ecma-international.org/ecma-262/6.0/#sec-day-number-and-time-within-day', - DayFromYear: 'https://ecma-international.org/ecma-262/6.0/#sec-year-number', - DaysInYear: 'https://ecma-international.org/ecma-262/6.0/#sec-year-number', - DayWithinYear: 'https://ecma-international.org/ecma-262/6.0/#sec-month-number', - DefinePropertyOrThrow: 'https://ecma-international.org/ecma-262/6.0/#sec-definepropertyorthrow', - DeletePropertyOrThrow: 'https://ecma-international.org/ecma-262/6.0/#sec-deletepropertyorthrow', - EnumerableOwnNames: 'https://ecma-international.org/ecma-262/6.0/#sec-enumerableownnames', - FromPropertyDescriptor: 'https://ecma-international.org/ecma-262/6.0/#sec-frompropertydescriptor', - Get: 'https://ecma-international.org/ecma-262/6.0/#sec-get-o-p', - GetIterator: 'https://ecma-international.org/ecma-262/6.0/#sec-getiterator', - GetMethod: 'https://ecma-international.org/ecma-262/6.0/#sec-getmethod', - GetOwnPropertyKeys: 'https://ecma-international.org/ecma-262/6.0/#sec-getownpropertykeys', - GetPrototypeFromConstructor: 'https://ecma-international.org/ecma-262/6.0/#sec-getprototypefromconstructor', - GetSubstitution: 'https://ecma-international.org/ecma-262/6.0/#sec-getsubstitution', - GetV: 'https://ecma-international.org/ecma-262/6.0/#sec-getv', - HasOwnProperty: 'https://ecma-international.org/ecma-262/6.0/#sec-hasownproperty', - HasProperty: 'https://ecma-international.org/ecma-262/6.0/#sec-hasproperty', - HourFromTime: 'https://ecma-international.org/ecma-262/6.0/#sec-hours-minutes-second-and-milliseconds', - InLeapYear: 'https://ecma-international.org/ecma-262/6.0/#sec-year-number', - InstanceofOperator: 'https://ecma-international.org/ecma-262/6.0/#sec-instanceofoperator', - Invoke: 'https://ecma-international.org/ecma-262/6.0/#sec-invoke', - IsAccessorDescriptor: 'https://ecma-international.org/ecma-262/6.0/#sec-isaccessordescriptor', - IsArray: 'https://ecma-international.org/ecma-262/6.0/#sec-isarray', - IsCallable: 'https://ecma-international.org/ecma-262/6.0/#sec-iscallable', - IsConcatSpreadable: 'https://ecma-international.org/ecma-262/6.0/#sec-isconcatspreadable', - IsConstructor: 'https://ecma-international.org/ecma-262/6.0/#sec-isconstructor', - IsDataDescriptor: 'https://ecma-international.org/ecma-262/6.0/#sec-isdatadescriptor', - IsExtensible: 'https://ecma-international.org/ecma-262/6.0/#sec-isextensible-o', - IsGenericDescriptor: 'https://ecma-international.org/ecma-262/6.0/#sec-isgenericdescriptor', - IsInteger: 'https://ecma-international.org/ecma-262/6.0/#sec-isinteger', - IsPromise: 'https://ecma-international.org/ecma-262/6.0/#sec-ispromise', - IsPropertyKey: 'https://ecma-international.org/ecma-262/6.0/#sec-ispropertykey', - IsRegExp: 'https://ecma-international.org/ecma-262/6.0/#sec-isregexp', - IteratorClose: 'https://ecma-international.org/ecma-262/6.0/#sec-iteratorclose', - IteratorComplete: 'https://ecma-international.org/ecma-262/6.0/#sec-iteratorcomplete', - IteratorNext: 'https://ecma-international.org/ecma-262/6.0/#sec-iteratornext', - IteratorStep: 'https://ecma-international.org/ecma-262/6.0/#sec-iteratorstep', - IteratorValue: 'https://ecma-international.org/ecma-262/6.0/#sec-iteratorvalue', - MakeDate: 'https://ecma-international.org/ecma-262/6.0/#sec-makedate', - MakeDay: 'https://ecma-international.org/ecma-262/6.0/#sec-makeday', - MakeTime: 'https://ecma-international.org/ecma-262/6.0/#sec-maketime', - MinFromTime: 'https://ecma-international.org/ecma-262/6.0/#sec-hours-minutes-second-and-milliseconds', - modulo: 'https://ecma-international.org/ecma-262/6.0/#sec-algorithm-conventions', - MonthFromTime: 'https://ecma-international.org/ecma-262/6.0/#sec-month-number', - msFromTime: 'https://ecma-international.org/ecma-262/6.0/#sec-hours-minutes-second-and-milliseconds', - NormalCompletion: 'https://ecma-international.org/ecma-262/6.0/#sec-normalcompletion', - ObjectCreate: 'https://ecma-international.org/ecma-262/6.0/#sec-objectcreate', - OrdinaryDefineOwnProperty: 'https://ecma-international.org/ecma-262/6.0/#sec-ordinarydefineownproperty', - OrdinaryGetOwnProperty: 'https://ecma-international.org/ecma-262/6.0/#sec-ordinarygetownproperty', - OrdinaryHasInstance: 'https://ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance', - OrdinaryHasProperty: 'https://ecma-international.org/ecma-262/6.0/#sec-ordinaryhasproperty', - RegExpBuiltinExec: 'https://ecma-international.org/ecma-262/6.0/#sec-regexpbuiltinexec', - RegExpExec: 'https://ecma-international.org/ecma-262/6.0/#sec-regexpexec', - RequireObjectCoercible: 'https://ecma-international.org/ecma-262/6.0/#sec-requireobjectcoercible', - SameValue: 'https://ecma-international.org/ecma-262/6.0/#sec-samevalue', - SameValueZero: 'https://ecma-international.org/ecma-262/6.0/#sec-samevaluezero', - SecFromTime: 'https://ecma-international.org/ecma-262/6.0/#sec-hours-minutes-second-and-milliseconds', - Set: 'https://ecma-international.org/ecma-262/6.0/#sec-set-o-p-v-throw', - SetFunctionName: 'https://ecma-international.org/ecma-262/6.0/#sec-setfunctionname', - SetIntegrityLevel: 'https://ecma-international.org/ecma-262/6.0/#sec-setintegritylevel', - SpeciesConstructor: 'https://ecma-international.org/ecma-262/6.0/#sec-speciesconstructor', - SymbolDescriptiveString: 'https://ecma-international.org/ecma-262/6.0/#sec-symboldescriptivestring', - TestIntegrityLevel: 'https://ecma-international.org/ecma-262/6.0/#sec-testintegritylevel', - thisBooleanValue: 'https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-boolean-prototype-object', - thisNumberValue: 'https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-number-prototype-object', - thisStringValue: 'https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-string-prototype-object', - thisTimeValue: 'https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-date-prototype-object', - TimeClip: 'https://ecma-international.org/ecma-262/6.0/#sec-timeclip', - TimeFromYear: 'https://ecma-international.org/ecma-262/6.0/#sec-year-number', - TimeWithinDay: 'https://ecma-international.org/ecma-262/6.0/#sec-day-number-and-time-within-day', - ToBoolean: 'https://ecma-international.org/ecma-262/6.0/#sec-toboolean', - ToDateString: 'https://ecma-international.org/ecma-262/6.0/#sec-todatestring', - ToInt16: 'https://ecma-international.org/ecma-262/6.0/#sec-toint16', - ToInt32: 'https://ecma-international.org/ecma-262/6.0/#sec-toint32', - ToInt8: 'https://ecma-international.org/ecma-262/6.0/#sec-toint8', - ToInteger: 'https://ecma-international.org/ecma-262/6.0/#sec-tointeger', - ToLength: 'https://ecma-international.org/ecma-262/6.0/#sec-tolength', - ToNumber: 'https://ecma-international.org/ecma-262/6.0/#sec-tonumber', - ToObject: 'https://ecma-international.org/ecma-262/6.0/#sec-toobject', - ToPrimitive: 'https://ecma-international.org/ecma-262/6.0/#sec-toprimitive', - ToPropertyDescriptor: 'https://ecma-international.org/ecma-262/6.0/#sec-topropertydescriptor', - ToPropertyKey: 'https://ecma-international.org/ecma-262/6.0/#sec-topropertykey', - ToString: 'https://ecma-international.org/ecma-262/6.0/#sec-tostring', - ToUint16: 'https://ecma-international.org/ecma-262/6.0/#sec-touint16', - ToUint32: 'https://ecma-international.org/ecma-262/6.0/#sec-touint32', - ToUint8: 'https://ecma-international.org/ecma-262/6.0/#sec-touint8', - ToUint8Clamp: 'https://ecma-international.org/ecma-262/6.0/#sec-touint8clamp', - Type: 'https://ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types', - ValidateAndApplyPropertyDescriptor: 'https://ecma-international.org/ecma-262/6.0/#sec-validateandapplypropertydescriptor', - WeekDay: 'https://ecma-international.org/ecma-262/6.0/#sec-week-day', - YearFromTime: 'https://ecma-international.org/ecma-262/6.0/#sec-year-number' -}; diff --git a/node_modules/es-abstract/operations/2016.js b/node_modules/es-abstract/operations/2016.js deleted file mode 100644 index 6a58b9c..0000000 --- a/node_modules/es-abstract/operations/2016.js +++ /dev/null @@ -1,276 +0,0 @@ -'use strict'; - -module.exports = { - IsPropertyDescriptor: 'https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type', // not actually an abstract op - - abs: 'https://ecma-international.org/ecma-262/7.0/#sec-algorithm-conventions', - 'Abstract Equality Comparison': 'https://ecma-international.org/ecma-262/7.0/#sec-abstract-equality-comparison', - 'Abstract Relational Comparison': 'https://ecma-international.org/ecma-262/7.0/#sec-abstract-relational-comparison', - AddRestrictedFunctionProperties: 'https://ecma-international.org/ecma-262/7.0/#sec-addrestrictedfunctionproperties', - AdvanceStringIndex: 'https://ecma-international.org/ecma-262/7.0/#sec-advancestringindex', - AllocateArrayBuffer: 'https://ecma-international.org/ecma-262/7.0/#sec-allocatearraybuffer', - AllocateTypedArray: 'https://ecma-international.org/ecma-262/7.0/#sec-allocatetypedarray', - AllocateTypedArrayBuffer: 'https://ecma-international.org/ecma-262/7.0/#sec-allocatetypedarraybuffer', - ArrayCreate: 'https://ecma-international.org/ecma-262/7.0/#sec-arraycreate', - ArraySetLength: 'https://ecma-international.org/ecma-262/7.0/#sec-arraysetlength', - ArraySpeciesCreate: 'https://ecma-international.org/ecma-262/7.0/#sec-arrayspeciescreate', - BlockDeclarationInstantiation: 'https://ecma-international.org/ecma-262/7.0/#sec-blockdeclarationinstantiation', - BoundFunctionCreate: 'https://ecma-international.org/ecma-262/7.0/#sec-boundfunctioncreate', - Call: 'https://ecma-international.org/ecma-262/7.0/#sec-call', - Canonicalize: 'https://ecma-international.org/ecma-262/7.0/#sec-runtime-semantics-canonicalize-ch', - CanonicalNumericIndexString: 'https://ecma-international.org/ecma-262/7.0/#sec-canonicalnumericindexstring', - CharacterRange: 'https://ecma-international.org/ecma-262/7.0/#sec-runtime-semantics-characterrange-abstract-operation', - CharacterRangeOrUnion: 'https://ecma-international.org/ecma-262/7.0/#sec-runtime-semantics-characterrangeorunion-abstract-operation', - CharacterSetMatcher: 'https://ecma-international.org/ecma-262/7.0/#sec-runtime-semantics-charactersetmatcher-abstract-operation', - CloneArrayBuffer: 'https://ecma-international.org/ecma-262/7.0/#sec-clonearraybuffer', - CompletePropertyDescriptor: 'https://ecma-international.org/ecma-262/7.0/#sec-completepropertydescriptor', - Completion: 'https://ecma-international.org/ecma-262/7.0/#sec-completion-record-specification-type', - Construct: 'https://ecma-international.org/ecma-262/7.0/#sec-construct', - CopyDataBlockBytes: 'https://ecma-international.org/ecma-262/7.0/#sec-copydatablockbytes', - CreateArrayFromList: 'https://ecma-international.org/ecma-262/7.0/#sec-createarrayfromlist', - CreateArrayIterator: 'https://ecma-international.org/ecma-262/7.0/#sec-createarrayiterator', - CreateBuiltinFunction: 'https://ecma-international.org/ecma-262/7.0/#sec-createbuiltinfunction', - CreateByteDataBlock: 'https://ecma-international.org/ecma-262/7.0/#sec-createbytedatablock', - CreateDataProperty: 'https://ecma-international.org/ecma-262/7.0/#sec-createdataproperty', - CreateDataPropertyOrThrow: 'https://ecma-international.org/ecma-262/7.0/#sec-createdatapropertyorthrow', - CreateDynamicFunction: 'https://ecma-international.org/ecma-262/7.0/#sec-createdynamicfunction', - CreateHTML: 'https://ecma-international.org/ecma-262/7.0/#sec-createhtml', - CreateIntrinsics: 'https://ecma-international.org/ecma-262/7.0/#sec-createintrinsics', - CreateIterResultObject: 'https://ecma-international.org/ecma-262/7.0/#sec-createiterresultobject', - CreateListFromArrayLike: 'https://ecma-international.org/ecma-262/7.0/#sec-createlistfromarraylike', - CreateListIterator: 'https://ecma-international.org/ecma-262/7.0/#sec-createlistiterator', - CreateMapIterator: 'https://ecma-international.org/ecma-262/7.0/#sec-createmapiterator', - CreateMappedArgumentsObject: 'https://ecma-international.org/ecma-262/7.0/#sec-createmappedargumentsobject', - CreateMethodProperty: 'https://ecma-international.org/ecma-262/7.0/#sec-createmethodproperty', - CreatePerIterationEnvironment: 'https://ecma-international.org/ecma-262/7.0/#sec-createperiterationenvironment', - CreateRealm: 'https://ecma-international.org/ecma-262/7.0/#sec-createrealm', - CreateResolvingFunctions: 'https://ecma-international.org/ecma-262/7.0/#sec-createresolvingfunctions', - CreateSetIterator: 'https://ecma-international.org/ecma-262/7.0/#sec-createsetiterator', - CreateStringIterator: 'https://ecma-international.org/ecma-262/7.0/#sec-createstringiterator', - CreateUnmappedArgumentsObject: 'https://ecma-international.org/ecma-262/7.0/#sec-createunmappedargumentsobject', - DateFromTime: 'https://ecma-international.org/ecma-262/7.0/#sec-date-number', - Day: 'https://ecma-international.org/ecma-262/7.0/#sec-day-number-and-time-within-day', - DayFromYear: 'https://ecma-international.org/ecma-262/7.0/#sec-year-number', - DaysInYear: 'https://ecma-international.org/ecma-262/7.0/#sec-year-number', - DayWithinYear: 'https://ecma-international.org/ecma-262/7.0/#sec-month-number', - Decode: 'https://ecma-international.org/ecma-262/7.0/#sec-decode', - DefinePropertyOrThrow: 'https://ecma-international.org/ecma-262/7.0/#sec-definepropertyorthrow', - DeletePropertyOrThrow: 'https://ecma-international.org/ecma-262/7.0/#sec-deletepropertyorthrow', - DetachArrayBuffer: 'https://ecma-international.org/ecma-262/7.0/#sec-detacharraybuffer', - Encode: 'https://ecma-international.org/ecma-262/7.0/#sec-encode', - EnqueueJob: 'https://ecma-international.org/ecma-262/7.0/#sec-enqueuejob', - EnumerableOwnNames: 'https://ecma-international.org/ecma-262/7.0/#sec-enumerableownnames', - EnumerateObjectProperties: 'https://ecma-international.org/ecma-262/7.0/#sec-enumerate-object-properties', - EscapeRegExpPattern: 'https://ecma-international.org/ecma-262/7.0/#sec-escaperegexppattern', - EvalDeclarationInstantiation: 'https://ecma-international.org/ecma-262/7.0/#sec-evaldeclarationinstantiation', - EvaluateCall: 'https://ecma-international.org/ecma-262/7.0/#sec-evaluatecall', - EvaluateDirectCall: 'https://ecma-international.org/ecma-262/7.0/#sec-evaluatedirectcall', - EvaluateNew: 'https://ecma-international.org/ecma-262/7.0/#sec-evaluatenew', - floor: 'https://ecma-international.org/ecma-262/7.0/#sec-algorithm-conventions', - ForBodyEvaluation: 'https://ecma-international.org/ecma-262/7.0/#sec-forbodyevaluation', - 'ForIn/OfBodyEvaluation': 'https://ecma-international.org/ecma-262/7.0/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset', - 'ForIn/OfHeadEvaluation': 'https://ecma-international.org/ecma-262/7.0/#sec-runtime-semantics-forin-div-ofheadevaluation-tdznames-expr-iterationkind', - FromPropertyDescriptor: 'https://ecma-international.org/ecma-262/7.0/#sec-frompropertydescriptor', - FulfillPromise: 'https://ecma-international.org/ecma-262/7.0/#sec-fulfillpromise', - FunctionAllocate: 'https://ecma-international.org/ecma-262/7.0/#sec-functionallocate', - FunctionCreate: 'https://ecma-international.org/ecma-262/7.0/#sec-functioncreate', - FunctionDeclarationInstantiation: 'https://ecma-international.org/ecma-262/7.0/#sec-functiondeclarationinstantiation', - FunctionInitialize: 'https://ecma-international.org/ecma-262/7.0/#sec-functioninitialize', - GeneratorFunctionCreate: 'https://ecma-international.org/ecma-262/7.0/#sec-generatorfunctioncreate', - GeneratorResume: 'https://ecma-international.org/ecma-262/7.0/#sec-generatorresume', - GeneratorResumeAbrupt: 'https://ecma-international.org/ecma-262/7.0/#sec-generatorresumeabrupt', - GeneratorStart: 'https://ecma-international.org/ecma-262/7.0/#sec-generatorstart', - GeneratorValidate: 'https://ecma-international.org/ecma-262/7.0/#sec-generatorvalidate', - GeneratorYield: 'https://ecma-international.org/ecma-262/7.0/#sec-generatoryield', - Get: 'https://ecma-international.org/ecma-262/7.0/#sec-get-o-p', - GetActiveScriptOrModule: 'https://ecma-international.org/ecma-262/7.0/#sec-getactivescriptormodule', - GetFunctionRealm: 'https://ecma-international.org/ecma-262/7.0/#sec-getfunctionrealm', - GetGlobalObject: 'https://ecma-international.org/ecma-262/7.0/#sec-getglobalobject', - GetIdentifierReference: 'https://ecma-international.org/ecma-262/7.0/#sec-getidentifierreference', - GetIterator: 'https://ecma-international.org/ecma-262/7.0/#sec-getiterator', - GetMethod: 'https://ecma-international.org/ecma-262/7.0/#sec-getmethod', - GetModuleNamespace: 'https://ecma-international.org/ecma-262/7.0/#sec-getmodulenamespace', - GetNewTarget: 'https://ecma-international.org/ecma-262/7.0/#sec-getnewtarget', - GetOwnPropertyKeys: 'https://ecma-international.org/ecma-262/7.0/#sec-getownpropertykeys', - GetPrototypeFromConstructor: 'https://ecma-international.org/ecma-262/7.0/#sec-getprototypefromconstructor', - GetSubstitution: 'https://ecma-international.org/ecma-262/7.0/#sec-getsubstitution', - GetSuperConstructor: 'https://ecma-international.org/ecma-262/7.0/#sec-getsuperconstructor', - GetTemplateObject: 'https://ecma-international.org/ecma-262/7.0/#sec-gettemplateobject', - GetThisEnvironment: 'https://ecma-international.org/ecma-262/7.0/#sec-getthisenvironment', - GetThisValue: 'https://ecma-international.org/ecma-262/7.0/#sec-getthisvalue', - GetV: 'https://ecma-international.org/ecma-262/7.0/#sec-getv', - GetValue: 'https://ecma-international.org/ecma-262/7.0/#sec-getvalue', - GetValueFromBuffer: 'https://ecma-international.org/ecma-262/7.0/#sec-getvaluefrombuffer', - GetViewValue: 'https://ecma-international.org/ecma-262/7.0/#sec-getviewvalue', - GlobalDeclarationInstantiation: 'https://ecma-international.org/ecma-262/7.0/#sec-globaldeclarationinstantiation', - HasOwnProperty: 'https://ecma-international.org/ecma-262/7.0/#sec-hasownproperty', - HasProperty: 'https://ecma-international.org/ecma-262/7.0/#sec-hasproperty', - HostPromiseRejectionTracker: 'https://ecma-international.org/ecma-262/7.0/#sec-host-promise-rejection-tracker', - HostReportErrors: 'https://ecma-international.org/ecma-262/7.0/#sec-host-report-errors', - HostResolveImportedModule: 'https://ecma-international.org/ecma-262/7.0/#sec-hostresolveimportedmodule', - HourFromTime: 'https://ecma-international.org/ecma-262/7.0/#sec-hours-minutes-second-and-milliseconds', - IfAbruptRejectPromise: 'https://ecma-international.org/ecma-262/7.0/#sec-ifabruptrejectpromise', - ImportedLocalNames: 'https://ecma-international.org/ecma-262/7.0/#sec-importedlocalnames', - InitializeBoundName: 'https://ecma-international.org/ecma-262/7.0/#sec-initializeboundname', - InitializeHostDefinedRealm: 'https://ecma-international.org/ecma-262/7.0/#sec-initializehostdefinedrealm', - InitializeReferencedBinding: 'https://ecma-international.org/ecma-262/7.0/#sec-initializereferencedbinding', - InLeapYear: 'https://ecma-international.org/ecma-262/7.0/#sec-year-number', - InstanceofOperator: 'https://ecma-international.org/ecma-262/7.0/#sec-instanceofoperator', - IntegerIndexedElementGet: 'https://ecma-international.org/ecma-262/7.0/#sec-integerindexedelementget', - IntegerIndexedElementSet: 'https://ecma-international.org/ecma-262/7.0/#sec-integerindexedelementset', - IntegerIndexedObjectCreate: 'https://ecma-international.org/ecma-262/7.0/#sec-integerindexedobjectcreate', - InternalizeJSONProperty: 'https://ecma-international.org/ecma-262/7.0/#sec-internalizejsonproperty', - Invoke: 'https://ecma-international.org/ecma-262/7.0/#sec-invoke', - IsAccessorDescriptor: 'https://ecma-international.org/ecma-262/7.0/#sec-isaccessordescriptor', - IsAnonymousFunctionDefinition: 'https://ecma-international.org/ecma-262/7.0/#sec-isanonymousfunctiondefinition', - IsArray: 'https://ecma-international.org/ecma-262/7.0/#sec-isarray', - IsCallable: 'https://ecma-international.org/ecma-262/7.0/#sec-iscallable', - IsCompatiblePropertyDescriptor: 'https://ecma-international.org/ecma-262/7.0/#sec-iscompatiblepropertydescriptor', - IsConcatSpreadable: 'https://ecma-international.org/ecma-262/7.0/#sec-isconcatspreadable', - IsConstructor: 'https://ecma-international.org/ecma-262/7.0/#sec-isconstructor', - IsDataDescriptor: 'https://ecma-international.org/ecma-262/7.0/#sec-isdatadescriptor', - IsDetachedBuffer: 'https://ecma-international.org/ecma-262/7.0/#sec-isdetachedbuffer', - IsExtensible: 'https://ecma-international.org/ecma-262/7.0/#sec-isextensible-o', - IsGenericDescriptor: 'https://ecma-international.org/ecma-262/7.0/#sec-isgenericdescriptor', - IsInTailPosition: 'https://ecma-international.org/ecma-262/7.0/#sec-isintailposition', - IsInteger: 'https://ecma-international.org/ecma-262/7.0/#sec-isinteger', - IsLabelledFunction: 'https://ecma-international.org/ecma-262/7.0/#sec-islabelledfunction', - IsPromise: 'https://ecma-international.org/ecma-262/7.0/#sec-ispromise', - IsPropertyKey: 'https://ecma-international.org/ecma-262/7.0/#sec-ispropertykey', - IsRegExp: 'https://ecma-international.org/ecma-262/7.0/#sec-isregexp', - IsWordChar: 'https://ecma-international.org/ecma-262/7.0/#sec-runtime-semantics-iswordchar-abstract-operation', - IterableToArrayLike: 'https://ecma-international.org/ecma-262/7.0/#sec-iterabletoarraylike', - IteratorClose: 'https://ecma-international.org/ecma-262/7.0/#sec-iteratorclose', - IteratorComplete: 'https://ecma-international.org/ecma-262/7.0/#sec-iteratorcomplete', - IteratorNext: 'https://ecma-international.org/ecma-262/7.0/#sec-iteratornext', - IteratorStep: 'https://ecma-international.org/ecma-262/7.0/#sec-iteratorstep', - IteratorValue: 'https://ecma-international.org/ecma-262/7.0/#sec-iteratorvalue', - LocalTime: 'https://ecma-international.org/ecma-262/7.0/#sec-localtime', - LoopContinues: 'https://ecma-international.org/ecma-262/7.0/#sec-loopcontinues', - MakeArgGetter: 'https://ecma-international.org/ecma-262/7.0/#sec-makearggetter', - MakeArgSetter: 'https://ecma-international.org/ecma-262/7.0/#sec-makeargsetter', - MakeClassConstructor: 'https://ecma-international.org/ecma-262/7.0/#sec-makeclassconstructor', - MakeConstructor: 'https://ecma-international.org/ecma-262/7.0/#sec-makeconstructor', - MakeDate: 'https://ecma-international.org/ecma-262/7.0/#sec-makedate', - MakeDay: 'https://ecma-international.org/ecma-262/7.0/#sec-makeday', - MakeMethod: 'https://ecma-international.org/ecma-262/7.0/#sec-makemethod', - MakeSuperPropertyReference: 'https://ecma-international.org/ecma-262/7.0/#sec-makesuperpropertyreference', - MakeTime: 'https://ecma-international.org/ecma-262/7.0/#sec-maketime', - max: 'https://ecma-international.org/ecma-262/7.0/#sec-algorithm-conventions', - min: 'https://ecma-international.org/ecma-262/7.0/#sec-algorithm-conventions', - MinFromTime: 'https://ecma-international.org/ecma-262/7.0/#sec-hours-minutes-second-and-milliseconds', - ModuleNamespaceCreate: 'https://ecma-international.org/ecma-262/7.0/#sec-modulenamespacecreate', - modulo: 'https://ecma-international.org/ecma-262/7.0/#sec-algorithm-conventions', - MonthFromTime: 'https://ecma-international.org/ecma-262/7.0/#sec-month-number', - msFromTime: 'https://ecma-international.org/ecma-262/7.0/#sec-hours-minutes-second-and-milliseconds', - NewDeclarativeEnvironment: 'https://ecma-international.org/ecma-262/7.0/#sec-newdeclarativeenvironment', - NewFunctionEnvironment: 'https://ecma-international.org/ecma-262/7.0/#sec-newfunctionenvironment', - NewGlobalEnvironment: 'https://ecma-international.org/ecma-262/7.0/#sec-newglobalenvironment', - NewModuleEnvironment: 'https://ecma-international.org/ecma-262/7.0/#sec-newmoduleenvironment', - NewObjectEnvironment: 'https://ecma-international.org/ecma-262/7.0/#sec-newobjectenvironment', - NewPromiseCapability: 'https://ecma-international.org/ecma-262/7.0/#sec-newpromisecapability', - NextJob: 'https://ecma-international.org/ecma-262/7.0/#sec-nextjob-result', - NormalCompletion: 'https://ecma-international.org/ecma-262/7.0/#sec-normalcompletion', - ObjectCreate: 'https://ecma-international.org/ecma-262/7.0/#sec-objectcreate', - ObjectDefineProperties: 'https://ecma-international.org/ecma-262/7.0/#sec-objectdefineproperties', - OrdinaryCallBindThis: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinarycallbindthis', - OrdinaryCallEvaluateBody: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinarycallevaluatebody', - OrdinaryCreateFromConstructor: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinarycreatefromconstructor', - OrdinaryDefineOwnProperty: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinarydefineownproperty', - OrdinaryDelete: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinarydelete', - OrdinaryGet: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinaryget', - OrdinaryGetOwnProperty: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinarygetownproperty', - OrdinaryGetPrototypeOf: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinarygetprototypeof', - OrdinaryHasInstance: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinaryhasinstance', - OrdinaryHasProperty: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinaryhasproperty', - OrdinaryIsExtensible: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinaryisextensible', - OrdinaryOwnPropertyKeys: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinaryownpropertykeys', - OrdinaryPreventExtensions: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinarypreventextensions', - OrdinarySet: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinaryset', - OrdinarySetPrototypeOf: 'https://ecma-international.org/ecma-262/7.0/#sec-ordinarysetprototypeof', - ParseModule: 'https://ecma-international.org/ecma-262/7.0/#sec-parsemodule', - ParseScript: 'https://ecma-international.org/ecma-262/7.0/#sec-parse-script', - PerformEval: 'https://ecma-international.org/ecma-262/7.0/#sec-performeval', - PerformPromiseAll: 'https://ecma-international.org/ecma-262/7.0/#sec-performpromiseall', - PerformPromiseRace: 'https://ecma-international.org/ecma-262/7.0/#sec-performpromiserace', - PerformPromiseThen: 'https://ecma-international.org/ecma-262/7.0/#sec-performpromisethen', - PrepareForOrdinaryCall: 'https://ecma-international.org/ecma-262/7.0/#sec-prepareforordinarycall', - PrepareForTailCall: 'https://ecma-international.org/ecma-262/7.0/#sec-preparefortailcall', - PromiseReactionJob: 'https://ecma-international.org/ecma-262/7.0/#sec-promisereactionjob', - PromiseResolveThenableJob: 'https://ecma-international.org/ecma-262/7.0/#sec-promiseresolvethenablejob', - ProxyCreate: 'https://ecma-international.org/ecma-262/7.0/#sec-proxycreate', - PutValue: 'https://ecma-international.org/ecma-262/7.0/#sec-putvalue', - QuoteJSONString: 'https://ecma-international.org/ecma-262/7.0/#sec-quotejsonstring', - RegExpAlloc: 'https://ecma-international.org/ecma-262/7.0/#sec-regexpalloc', - RegExpBuiltinExec: 'https://ecma-international.org/ecma-262/7.0/#sec-regexpbuiltinexec', - RegExpCreate: 'https://ecma-international.org/ecma-262/7.0/#sec-regexpcreate', - RegExpExec: 'https://ecma-international.org/ecma-262/7.0/#sec-regexpexec', - RegExpInitialize: 'https://ecma-international.org/ecma-262/7.0/#sec-regexpinitialize', - RejectPromise: 'https://ecma-international.org/ecma-262/7.0/#sec-rejectpromise', - RepeatMatcher: 'https://ecma-international.org/ecma-262/7.0/#sec-runtime-semantics-repeatmatcher-abstract-operation', - RequireObjectCoercible: 'https://ecma-international.org/ecma-262/7.0/#sec-requireobjectcoercible', - ResolveBinding: 'https://ecma-international.org/ecma-262/7.0/#sec-resolvebinding', - ResolveThisBinding: 'https://ecma-international.org/ecma-262/7.0/#sec-resolvethisbinding', - ReturnIfAbrupt: 'https://ecma-international.org/ecma-262/7.0/#sec-returnifabrupt', - SameValue: 'https://ecma-international.org/ecma-262/7.0/#sec-samevalue', - SameValueNonNumber: 'https://ecma-international.org/ecma-262/7.0/#sec-samevaluenonnumber', - SameValueZero: 'https://ecma-international.org/ecma-262/7.0/#sec-samevaluezero', - ScriptEvaluation: 'https://ecma-international.org/ecma-262/7.0/#sec-runtime-semantics-scriptevaluation', - ScriptEvaluationJob: 'https://ecma-international.org/ecma-262/7.0/#sec-scriptevaluationjob', - SecFromTime: 'https://ecma-international.org/ecma-262/7.0/#sec-hours-minutes-second-and-milliseconds', - SerializeJSONArray: 'https://ecma-international.org/ecma-262/7.0/#sec-serializejsonarray', - SerializeJSONObject: 'https://ecma-international.org/ecma-262/7.0/#sec-serializejsonobject', - SerializeJSONProperty: 'https://ecma-international.org/ecma-262/7.0/#sec-serializejsonproperty', - Set: 'https://ecma-international.org/ecma-262/7.0/#sec-set-o-p-v-throw', - SetDefaultGlobalBindings: 'https://ecma-international.org/ecma-262/7.0/#sec-setdefaultglobalbindings', - SetFunctionName: 'https://ecma-international.org/ecma-262/7.0/#sec-setfunctionname', - SetIntegrityLevel: 'https://ecma-international.org/ecma-262/7.0/#sec-setintegritylevel', - SetRealmGlobalObject: 'https://ecma-international.org/ecma-262/7.0/#sec-setrealmglobalobject', - SetValueInBuffer: 'https://ecma-international.org/ecma-262/7.0/#sec-setvalueinbuffer', - SetViewValue: 'https://ecma-international.org/ecma-262/7.0/#sec-setviewvalue', - SortCompare: 'https://ecma-international.org/ecma-262/7.0/#sec-sortcompare', - SpeciesConstructor: 'https://ecma-international.org/ecma-262/7.0/#sec-speciesconstructor', - SplitMatch: 'https://ecma-international.org/ecma-262/7.0/#sec-splitmatch', - 'Strict Equality Comparison': 'https://ecma-international.org/ecma-262/7.0/#sec-strict-equality-comparison', - StringCreate: 'https://ecma-international.org/ecma-262/7.0/#sec-stringcreate', - SymbolDescriptiveString: 'https://ecma-international.org/ecma-262/7.0/#sec-symboldescriptivestring', - TestIntegrityLevel: 'https://ecma-international.org/ecma-262/7.0/#sec-testintegritylevel', - thisBooleanValue: 'https://ecma-international.org/ecma-262/7.0/#sec-thisbooleanvalue', - thisNumberValue: 'https://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-number-prototype-object', - thisStringValue: 'https://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-string-prototype-object', - thisTimeValue: 'https://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-date-prototype-object', - TimeClip: 'https://ecma-international.org/ecma-262/7.0/#sec-timeclip', - TimeFromYear: 'https://ecma-international.org/ecma-262/7.0/#sec-year-number', - TimeWithinDay: 'https://ecma-international.org/ecma-262/7.0/#sec-day-number-and-time-within-day', - ToBoolean: 'https://ecma-international.org/ecma-262/7.0/#sec-toboolean', - ToDateString: 'https://ecma-international.org/ecma-262/7.0/#sec-todatestring', - ToInt16: 'https://ecma-international.org/ecma-262/7.0/#sec-toint16', - ToInt32: 'https://ecma-international.org/ecma-262/7.0/#sec-toint32', - ToInt8: 'https://ecma-international.org/ecma-262/7.0/#sec-toint8', - ToInteger: 'https://ecma-international.org/ecma-262/7.0/#sec-tointeger', - ToLength: 'https://ecma-international.org/ecma-262/7.0/#sec-tolength', - ToNumber: 'https://ecma-international.org/ecma-262/7.0/#sec-tonumber', - ToObject: 'https://ecma-international.org/ecma-262/7.0/#sec-toobject', - TopLevelModuleEvaluationJob: 'https://ecma-international.org/ecma-262/7.0/#sec-toplevelmoduleevaluationjob', - ToPrimitive: 'https://ecma-international.org/ecma-262/7.0/#sec-toprimitive', - ToPropertyDescriptor: 'https://ecma-international.org/ecma-262/7.0/#sec-topropertydescriptor', - ToPropertyKey: 'https://ecma-international.org/ecma-262/7.0/#sec-topropertykey', - ToString: 'https://ecma-international.org/ecma-262/7.0/#sec-tostring', - 'ToString Applied to the Number Type': 'https://ecma-international.org/ecma-262/7.0/#sec-tostring-applied-to-the-number-type', - ToUint16: 'https://ecma-international.org/ecma-262/7.0/#sec-touint16', - ToUint32: 'https://ecma-international.org/ecma-262/7.0/#sec-touint32', - ToUint8: 'https://ecma-international.org/ecma-262/7.0/#sec-touint8', - ToUint8Clamp: 'https://ecma-international.org/ecma-262/7.0/#sec-touint8clamp', - TriggerPromiseReactions: 'https://ecma-international.org/ecma-262/7.0/#sec-triggerpromisereactions', - Type: 'https://ecma-international.org/ecma-262/7.0/#sec-ecmascript-data-types-and-values', - TypedArrayCreate: 'https://ecma-international.org/ecma-262/7.0/#typedarray-create', - TypedArraySpeciesCreate: 'https://ecma-international.org/ecma-262/7.0/#typedarray-species-create', - UpdateEmpty: 'https://ecma-international.org/ecma-262/7.0/#sec-updateempty', - UTC: 'https://ecma-international.org/ecma-262/7.0/#sec-utc-t', - UTF16Decode: 'https://ecma-international.org/ecma-262/7.0/#sec-utf16decode', - UTF16Encoding: 'https://ecma-international.org/ecma-262/7.0/#sec-utf16encoding', - ValidateAndApplyPropertyDescriptor: 'https://ecma-international.org/ecma-262/7.0/#sec-validateandapplypropertydescriptor', - ValidateTypedArray: 'https://ecma-international.org/ecma-262/7.0/#sec-validatetypedarray', - WeekDay: 'https://ecma-international.org/ecma-262/7.0/#sec-week-day', - YearFromTime: 'https://ecma-international.org/ecma-262/7.0/#sec-year-number' -}; diff --git a/node_modules/es-abstract/operations/2017.js b/node_modules/es-abstract/operations/2017.js deleted file mode 100644 index 896fcee..0000000 --- a/node_modules/es-abstract/operations/2017.js +++ /dev/null @@ -1,324 +0,0 @@ -'use strict'; - -module.exports = { - IsPropertyDescriptor: 'https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type', // not actually an abstract op - - abs: 'https://ecma-international.org/ecma-262/8.0/#eqn-abs', - 'Abstract Equality Comparison': 'https://ecma-international.org/ecma-262/8.0/#sec-abstract-equality-comparison', - 'Abstract Relational Comparison': 'https://ecma-international.org/ecma-262/8.0/#sec-abstract-relational-comparison', - AddRestrictedFunctionProperties: 'https://ecma-international.org/ecma-262/8.0/#sec-addrestrictedfunctionproperties', - AddWaiter: 'https://ecma-international.org/ecma-262/8.0/#sec-addwaiter', - AdvanceStringIndex: 'https://ecma-international.org/ecma-262/8.0/#sec-advancestringindex', - 'agent-order': 'https://ecma-international.org/ecma-262/8.0/#sec-agent-order', - AgentCanSuspend: 'https://ecma-international.org/ecma-262/8.0/#sec-agentcansuspend', - AgentSignifier: 'https://ecma-international.org/ecma-262/8.0/#sec-agentsignifier', - AllocateArrayBuffer: 'https://ecma-international.org/ecma-262/8.0/#sec-allocatearraybuffer', - AllocateSharedArrayBuffer: 'https://ecma-international.org/ecma-262/8.0/#sec-allocatesharedarraybuffer', - AllocateTypedArray: 'https://ecma-international.org/ecma-262/8.0/#sec-allocatetypedarray', - AllocateTypedArrayBuffer: 'https://ecma-international.org/ecma-262/8.0/#sec-allocatetypedarraybuffer', - ArrayCreate: 'https://ecma-international.org/ecma-262/8.0/#sec-arraycreate', - ArraySetLength: 'https://ecma-international.org/ecma-262/8.0/#sec-arraysetlength', - ArraySpeciesCreate: 'https://ecma-international.org/ecma-262/8.0/#sec-arrayspeciescreate', - AsyncFunctionAwait: 'https://ecma-international.org/ecma-262/8.0/#sec-async-functions-abstract-operations-async-function-await', - AsyncFunctionCreate: 'https://ecma-international.org/ecma-262/8.0/#sec-async-functions-abstract-operations-async-function-create', - AsyncFunctionStart: 'https://ecma-international.org/ecma-262/8.0/#sec-async-functions-abstract-operations-async-function-start', - AtomicLoad: 'https://ecma-international.org/ecma-262/8.0/#sec-atomicload', - AtomicReadModifyWrite: 'https://ecma-international.org/ecma-262/8.0/#sec-atomicreadmodifywrite', - BlockDeclarationInstantiation: 'https://ecma-international.org/ecma-262/8.0/#sec-blockdeclarationinstantiation', - BoundFunctionCreate: 'https://ecma-international.org/ecma-262/8.0/#sec-boundfunctioncreate', - Call: 'https://ecma-international.org/ecma-262/8.0/#sec-call', - Canonicalize: 'https://ecma-international.org/ecma-262/8.0/#sec-runtime-semantics-canonicalize-ch', - CanonicalNumericIndexString: 'https://ecma-international.org/ecma-262/8.0/#sec-canonicalnumericindexstring', - CharacterRange: 'https://ecma-international.org/ecma-262/8.0/#sec-runtime-semantics-characterrange-abstract-operation', - CharacterRangeOrUnion: 'https://ecma-international.org/ecma-262/8.0/#sec-runtime-semantics-characterrangeorunion-abstract-operation', - CharacterSetMatcher: 'https://ecma-international.org/ecma-262/8.0/#sec-runtime-semantics-charactersetmatcher-abstract-operation', - CloneArrayBuffer: 'https://ecma-international.org/ecma-262/8.0/#sec-clonearraybuffer', - CompletePropertyDescriptor: 'https://ecma-international.org/ecma-262/8.0/#sec-completepropertydescriptor', - Completion: 'https://ecma-international.org/ecma-262/8.0/#sec-completion-record-specification-type', - ComposeWriteEventBytes: 'https://ecma-international.org/ecma-262/8.0/#sec-composewriteeventbytes', - Construct: 'https://ecma-international.org/ecma-262/8.0/#sec-construct', - CopyDataBlockBytes: 'https://ecma-international.org/ecma-262/8.0/#sec-copydatablockbytes', - CreateArrayFromList: 'https://ecma-international.org/ecma-262/8.0/#sec-createarrayfromlist', - CreateArrayIterator: 'https://ecma-international.org/ecma-262/8.0/#sec-createarrayiterator', - CreateBuiltinFunction: 'https://ecma-international.org/ecma-262/8.0/#sec-createbuiltinfunction', - CreateByteDataBlock: 'https://ecma-international.org/ecma-262/8.0/#sec-createbytedatablock', - CreateDataProperty: 'https://ecma-international.org/ecma-262/8.0/#sec-createdataproperty', - CreateDataPropertyOrThrow: 'https://ecma-international.org/ecma-262/8.0/#sec-createdatapropertyorthrow', - CreateDynamicFunction: 'https://ecma-international.org/ecma-262/8.0/#sec-createdynamicfunction', - CreateHTML: 'https://ecma-international.org/ecma-262/8.0/#sec-createhtml', - CreateIntrinsics: 'https://ecma-international.org/ecma-262/8.0/#sec-createintrinsics', - CreateIterResultObject: 'https://ecma-international.org/ecma-262/8.0/#sec-createiterresultobject', - CreateListFromArrayLike: 'https://ecma-international.org/ecma-262/8.0/#sec-createlistfromarraylike', - CreateListIterator: 'https://ecma-international.org/ecma-262/8.0/#sec-createlistiterator', - CreateMapIterator: 'https://ecma-international.org/ecma-262/8.0/#sec-createmapiterator', - CreateMappedArgumentsObject: 'https://ecma-international.org/ecma-262/8.0/#sec-createmappedargumentsobject', - CreateMethodProperty: 'https://ecma-international.org/ecma-262/8.0/#sec-createmethodproperty', - CreatePerIterationEnvironment: 'https://ecma-international.org/ecma-262/8.0/#sec-createperiterationenvironment', - CreateRealm: 'https://ecma-international.org/ecma-262/8.0/#sec-createrealm', - CreateResolvingFunctions: 'https://ecma-international.org/ecma-262/8.0/#sec-createresolvingfunctions', - CreateSetIterator: 'https://ecma-international.org/ecma-262/8.0/#sec-createsetiterator', - CreateSharedByteDataBlock: 'https://ecma-international.org/ecma-262/8.0/#sec-createsharedbytedatablock', - CreateStringIterator: 'https://ecma-international.org/ecma-262/8.0/#sec-createstringiterator', - CreateUnmappedArgumentsObject: 'https://ecma-international.org/ecma-262/8.0/#sec-createunmappedargumentsobject', - DateFromTime: 'https://ecma-international.org/ecma-262/8.0/#sec-date-number', - Day: 'https://ecma-international.org/ecma-262/8.0/#eqn-Day', - DayFromYear: 'https://ecma-international.org/ecma-262/8.0/#eqn-DaysFromYear', - DaysInYear: 'https://ecma-international.org/ecma-262/8.0/#eqn-DaysInYear', - DayWithinYear: 'https://ecma-international.org/ecma-262/8.0/#eqn-DayWithinYear', - Decode: 'https://ecma-international.org/ecma-262/8.0/#sec-decode', - DefinePropertyOrThrow: 'https://ecma-international.org/ecma-262/8.0/#sec-definepropertyorthrow', - DeletePropertyOrThrow: 'https://ecma-international.org/ecma-262/8.0/#sec-deletepropertyorthrow', - DetachArrayBuffer: 'https://ecma-international.org/ecma-262/8.0/#sec-detacharraybuffer', - Encode: 'https://ecma-international.org/ecma-262/8.0/#sec-encode', - EnqueueJob: 'https://ecma-international.org/ecma-262/8.0/#sec-enqueuejob', - EnterCriticalSection: 'https://ecma-international.org/ecma-262/8.0/#sec-entercriticalsection', - EnumerableOwnProperties: 'https://ecma-international.org/ecma-262/8.0/#sec-enumerableownproperties', - EnumerateObjectProperties: 'https://ecma-international.org/ecma-262/8.0/#sec-enumerate-object-properties', - EscapeRegExpPattern: 'https://ecma-international.org/ecma-262/8.0/#sec-escaperegexppattern', - EvalDeclarationInstantiation: 'https://ecma-international.org/ecma-262/8.0/#sec-evaldeclarationinstantiation', - EvaluateCall: 'https://ecma-international.org/ecma-262/8.0/#sec-evaluatecall', - EvaluateDirectCall: 'https://ecma-international.org/ecma-262/8.0/#sec-evaluatedirectcall', - EvaluateNew: 'https://ecma-international.org/ecma-262/8.0/#sec-evaluatenew', - EventSet: 'https://ecma-international.org/ecma-262/8.0/#sec-event-set', - floor: 'https://ecma-international.org/ecma-262/8.0/#eqn-floor', - ForBodyEvaluation: 'https://ecma-international.org/ecma-262/8.0/#sec-forbodyevaluation', - 'ForIn/OfBodyEvaluation': 'https://ecma-international.org/ecma-262/8.0/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset', - 'ForIn/OfHeadEvaluation': 'https://ecma-international.org/ecma-262/8.0/#sec-runtime-semantics-forin-div-ofheadevaluation-tdznames-expr-iterationkind', - FromPropertyDescriptor: 'https://ecma-international.org/ecma-262/8.0/#sec-frompropertydescriptor', - FulfillPromise: 'https://ecma-international.org/ecma-262/8.0/#sec-fulfillpromise', - FunctionAllocate: 'https://ecma-international.org/ecma-262/8.0/#sec-functionallocate', - FunctionCreate: 'https://ecma-international.org/ecma-262/8.0/#sec-functioncreate', - FunctionDeclarationInstantiation: 'https://ecma-international.org/ecma-262/8.0/#sec-functiondeclarationinstantiation', - FunctionInitialize: 'https://ecma-international.org/ecma-262/8.0/#sec-functioninitialize', - GeneratorFunctionCreate: 'https://ecma-international.org/ecma-262/8.0/#sec-generatorfunctioncreate', - GeneratorResume: 'https://ecma-international.org/ecma-262/8.0/#sec-generatorresume', - GeneratorResumeAbrupt: 'https://ecma-international.org/ecma-262/8.0/#sec-generatorresumeabrupt', - GeneratorStart: 'https://ecma-international.org/ecma-262/8.0/#sec-generatorstart', - GeneratorValidate: 'https://ecma-international.org/ecma-262/8.0/#sec-generatorvalidate', - GeneratorYield: 'https://ecma-international.org/ecma-262/8.0/#sec-generatoryield', - Get: 'https://ecma-international.org/ecma-262/8.0/#sec-get-o-p', - GetActiveScriptOrModule: 'https://ecma-international.org/ecma-262/8.0/#sec-getactivescriptormodule', - GetBase: 'https://ecma-international.org/ecma-262/8.0/#ao-getbase', - GetFunctionRealm: 'https://ecma-international.org/ecma-262/8.0/#sec-getfunctionrealm', - GetGlobalObject: 'https://ecma-international.org/ecma-262/8.0/#sec-getglobalobject', - GetIdentifierReference: 'https://ecma-international.org/ecma-262/8.0/#sec-getidentifierreference', - GetIterator: 'https://ecma-international.org/ecma-262/8.0/#sec-getiterator', - GetMethod: 'https://ecma-international.org/ecma-262/8.0/#sec-getmethod', - GetModifySetValueInBuffer: 'https://ecma-international.org/ecma-262/8.0/#sec-getmodifysetvalueinbuffer', - GetModuleNamespace: 'https://ecma-international.org/ecma-262/8.0/#sec-getmodulenamespace', - GetNewTarget: 'https://ecma-international.org/ecma-262/8.0/#sec-getnewtarget', - GetOwnPropertyKeys: 'https://ecma-international.org/ecma-262/8.0/#sec-getownpropertykeys', - GetPrototypeFromConstructor: 'https://ecma-international.org/ecma-262/8.0/#sec-getprototypefromconstructor', - GetReferencedName: 'https://ecma-international.org/ecma-262/8.0/#ao-getreferencedname', - GetSubstitution: 'https://ecma-international.org/ecma-262/8.0/#sec-getsubstitution', - GetSuperConstructor: 'https://ecma-international.org/ecma-262/8.0/#sec-getsuperconstructor', - GetTemplateObject: 'https://ecma-international.org/ecma-262/8.0/#sec-gettemplateobject', - GetThisEnvironment: 'https://ecma-international.org/ecma-262/8.0/#sec-getthisenvironment', - GetThisValue: 'https://ecma-international.org/ecma-262/8.0/#sec-getthisvalue', - GetV: 'https://ecma-international.org/ecma-262/8.0/#sec-getv', - GetValue: 'https://ecma-international.org/ecma-262/8.0/#sec-getvalue', - GetValueFromBuffer: 'https://ecma-international.org/ecma-262/8.0/#sec-getvaluefrombuffer', - GetViewValue: 'https://ecma-international.org/ecma-262/8.0/#sec-getviewvalue', - GetWaiterList: 'https://ecma-international.org/ecma-262/8.0/#sec-getwaiterlist', - GlobalDeclarationInstantiation: 'https://ecma-international.org/ecma-262/8.0/#sec-globaldeclarationinstantiation', - 'happens-before': 'https://ecma-international.org/ecma-262/8.0/#sec-happens-before', - HasOwnProperty: 'https://ecma-international.org/ecma-262/8.0/#sec-hasownproperty', - HasPrimitiveBase: 'https://ecma-international.org/ecma-262/8.0/#ao-hasprimitivebase', - HasProperty: 'https://ecma-international.org/ecma-262/8.0/#sec-hasproperty', - 'host-synchronizes-with': 'https://ecma-international.org/ecma-262/8.0/#sec-host-synchronizes-with', - HostEnsureCanCompileStrings: 'https://ecma-international.org/ecma-262/8.0/#sec-hostensurecancompilestrings', - HostEventSet: 'https://ecma-international.org/ecma-262/8.0/#sec-hosteventset', - HostPromiseRejectionTracker: 'https://ecma-international.org/ecma-262/8.0/#sec-host-promise-rejection-tracker', - HostReportErrors: 'https://ecma-international.org/ecma-262/8.0/#sec-host-report-errors', - HostResolveImportedModule: 'https://ecma-international.org/ecma-262/8.0/#sec-hostresolveimportedmodule', - HourFromTime: 'https://ecma-international.org/ecma-262/8.0/#eqn-HourFromTime', - IfAbruptRejectPromise: 'https://ecma-international.org/ecma-262/8.0/#sec-ifabruptrejectpromise', - ImportedLocalNames: 'https://ecma-international.org/ecma-262/8.0/#sec-importedlocalnames', - InitializeBoundName: 'https://ecma-international.org/ecma-262/8.0/#sec-initializeboundname', - InitializeHostDefinedRealm: 'https://ecma-international.org/ecma-262/8.0/#sec-initializehostdefinedrealm', - InitializeReferencedBinding: 'https://ecma-international.org/ecma-262/8.0/#sec-initializereferencedbinding', - InLeapYear: 'https://ecma-international.org/ecma-262/8.0/#eqn-InLeapYear', - InstanceofOperator: 'https://ecma-international.org/ecma-262/8.0/#sec-instanceofoperator', - IntegerIndexedElementGet: 'https://ecma-international.org/ecma-262/8.0/#sec-integerindexedelementget', - IntegerIndexedElementSet: 'https://ecma-international.org/ecma-262/8.0/#sec-integerindexedelementset', - IntegerIndexedObjectCreate: 'https://ecma-international.org/ecma-262/8.0/#sec-integerindexedobjectcreate', - InternalizeJSONProperty: 'https://ecma-international.org/ecma-262/8.0/#sec-internalizejsonproperty', - Invoke: 'https://ecma-international.org/ecma-262/8.0/#sec-invoke', - IsAccessorDescriptor: 'https://ecma-international.org/ecma-262/8.0/#sec-isaccessordescriptor', - IsAnonymousFunctionDefinition: 'https://ecma-international.org/ecma-262/8.0/#sec-isanonymousfunctiondefinition', - IsArray: 'https://ecma-international.org/ecma-262/8.0/#sec-isarray', - IsCallable: 'https://ecma-international.org/ecma-262/8.0/#sec-iscallable', - IsCompatiblePropertyDescriptor: 'https://ecma-international.org/ecma-262/8.0/#sec-iscompatiblepropertydescriptor', - IsConcatSpreadable: 'https://ecma-international.org/ecma-262/8.0/#sec-isconcatspreadable', - IsConstructor: 'https://ecma-international.org/ecma-262/8.0/#sec-isconstructor', - IsDataDescriptor: 'https://ecma-international.org/ecma-262/8.0/#sec-isdatadescriptor', - IsDetachedBuffer: 'https://ecma-international.org/ecma-262/8.0/#sec-isdetachedbuffer', - IsExtensible: 'https://ecma-international.org/ecma-262/8.0/#sec-isextensible-o', - IsGenericDescriptor: 'https://ecma-international.org/ecma-262/8.0/#sec-isgenericdescriptor', - IsInTailPosition: 'https://ecma-international.org/ecma-262/8.0/#sec-isintailposition', - IsInteger: 'https://ecma-international.org/ecma-262/8.0/#sec-isinteger', - IsLabelledFunction: 'https://ecma-international.org/ecma-262/8.0/#sec-islabelledfunction', - IsPromise: 'https://ecma-international.org/ecma-262/8.0/#sec-ispromise', - IsPropertyKey: 'https://ecma-international.org/ecma-262/8.0/#sec-ispropertykey', - IsPropertyReference: 'https://ecma-international.org/ecma-262/8.0/#ao-ispropertyreference', - IsRegExp: 'https://ecma-international.org/ecma-262/8.0/#sec-isregexp', - IsSharedArrayBuffer: 'https://ecma-international.org/ecma-262/8.0/#sec-issharedarraybuffer', - IsStrictReference: 'https://ecma-international.org/ecma-262/8.0/#ao-isstrictreference', - IsSuperReference: 'https://ecma-international.org/ecma-262/8.0/#ao-issuperreference', - IsUnresolvableReference: 'https://ecma-international.org/ecma-262/8.0/#ao-isunresolvablereference', - IsWordChar: 'https://ecma-international.org/ecma-262/8.0/#sec-runtime-semantics-iswordchar-abstract-operation', - IterableToList: 'https://ecma-international.org/ecma-262/8.0/#sec-iterabletolist', - IteratorClose: 'https://ecma-international.org/ecma-262/8.0/#sec-iteratorclose', - IteratorComplete: 'https://ecma-international.org/ecma-262/8.0/#sec-iteratorcomplete', - IteratorNext: 'https://ecma-international.org/ecma-262/8.0/#sec-iteratornext', - IteratorStep: 'https://ecma-international.org/ecma-262/8.0/#sec-iteratorstep', - IteratorValue: 'https://ecma-international.org/ecma-262/8.0/#sec-iteratorvalue', - LeaveCriticalSection: 'https://ecma-international.org/ecma-262/8.0/#sec-leavecriticalsection', - LocalTime: 'https://ecma-international.org/ecma-262/8.0/#sec-localtime', - LoopContinues: 'https://ecma-international.org/ecma-262/8.0/#sec-loopcontinues', - MakeArgGetter: 'https://ecma-international.org/ecma-262/8.0/#sec-makearggetter', - MakeArgSetter: 'https://ecma-international.org/ecma-262/8.0/#sec-makeargsetter', - MakeClassConstructor: 'https://ecma-international.org/ecma-262/8.0/#sec-makeclassconstructor', - MakeConstructor: 'https://ecma-international.org/ecma-262/8.0/#sec-makeconstructor', - MakeDate: 'https://ecma-international.org/ecma-262/8.0/#sec-makedate', - MakeDay: 'https://ecma-international.org/ecma-262/8.0/#sec-makeday', - MakeMethod: 'https://ecma-international.org/ecma-262/8.0/#sec-makemethod', - MakeSuperPropertyReference: 'https://ecma-international.org/ecma-262/8.0/#sec-makesuperpropertyreference', - MakeTime: 'https://ecma-international.org/ecma-262/8.0/#sec-maketime', - max: 'https://ecma-international.org/ecma-262/8.0/#eqn-max', - 'memory-order': 'https://ecma-international.org/ecma-262/8.0/#sec-memory-order', - min: 'https://ecma-international.org/ecma-262/8.0/#eqn-min', - MinFromTime: 'https://ecma-international.org/ecma-262/8.0/#eqn-MinFromTime', - ModuleNamespaceCreate: 'https://ecma-international.org/ecma-262/8.0/#sec-modulenamespacecreate', - modulo: 'https://ecma-international.org/ecma-262/8.0/#eqn-modulo', - MonthFromTime: 'https://ecma-international.org/ecma-262/8.0/#eqn-MonthFromTime', - msFromTime: 'https://ecma-international.org/ecma-262/8.0/#eqn-msFromTime', - NewDeclarativeEnvironment: 'https://ecma-international.org/ecma-262/8.0/#sec-newdeclarativeenvironment', - NewFunctionEnvironment: 'https://ecma-international.org/ecma-262/8.0/#sec-newfunctionenvironment', - NewGlobalEnvironment: 'https://ecma-international.org/ecma-262/8.0/#sec-newglobalenvironment', - NewModuleEnvironment: 'https://ecma-international.org/ecma-262/8.0/#sec-newmoduleenvironment', - NewObjectEnvironment: 'https://ecma-international.org/ecma-262/8.0/#sec-newobjectenvironment', - NewPromiseCapability: 'https://ecma-international.org/ecma-262/8.0/#sec-newpromisecapability', - NormalCompletion: 'https://ecma-international.org/ecma-262/8.0/#sec-normalcompletion', - NumberToRawBytes: 'https://ecma-international.org/ecma-262/8.0/#sec-numbertorawbytes', - ObjectCreate: 'https://ecma-international.org/ecma-262/8.0/#sec-objectcreate', - ObjectDefineProperties: 'https://ecma-international.org/ecma-262/8.0/#sec-objectdefineproperties', - OrdinaryCallBindThis: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinarycallbindthis', - OrdinaryCallEvaluateBody: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinarycallevaluatebody', - OrdinaryCreateFromConstructor: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinarycreatefromconstructor', - OrdinaryDefineOwnProperty: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinarydefineownproperty', - OrdinaryDelete: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinarydelete', - OrdinaryGet: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinaryget', - OrdinaryGetOwnProperty: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinarygetownproperty', - OrdinaryGetPrototypeOf: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinarygetprototypeof', - OrdinaryHasInstance: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinaryhasinstance', - OrdinaryHasProperty: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinaryhasproperty', - OrdinaryIsExtensible: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinaryisextensible', - OrdinaryOwnPropertyKeys: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinaryownpropertykeys', - OrdinaryPreventExtensions: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinarypreventextensions', - OrdinarySet: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinaryset', - OrdinarySetPrototypeOf: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinarysetprototypeof', - OrdinaryToPrimitive: 'https://ecma-international.org/ecma-262/8.0/#sec-ordinarytoprimitive', - ParseModule: 'https://ecma-international.org/ecma-262/8.0/#sec-parsemodule', - ParseScript: 'https://ecma-international.org/ecma-262/8.0/#sec-parse-script', - PerformEval: 'https://ecma-international.org/ecma-262/8.0/#sec-performeval', - PerformPromiseAll: 'https://ecma-international.org/ecma-262/8.0/#sec-performpromiseall', - PerformPromiseRace: 'https://ecma-international.org/ecma-262/8.0/#sec-performpromiserace', - PerformPromiseThen: 'https://ecma-international.org/ecma-262/8.0/#sec-performpromisethen', - PrepareForOrdinaryCall: 'https://ecma-international.org/ecma-262/8.0/#sec-prepareforordinarycall', - PrepareForTailCall: 'https://ecma-international.org/ecma-262/8.0/#sec-preparefortailcall', - PromiseReactionJob: 'https://ecma-international.org/ecma-262/8.0/#sec-promisereactionjob', - PromiseResolveThenableJob: 'https://ecma-international.org/ecma-262/8.0/#sec-promiseresolvethenablejob', - ProxyCreate: 'https://ecma-international.org/ecma-262/8.0/#sec-proxycreate', - PutValue: 'https://ecma-international.org/ecma-262/8.0/#sec-putvalue', - QuoteJSONString: 'https://ecma-international.org/ecma-262/8.0/#sec-quotejsonstring', - RawBytesToNumber: 'https://ecma-international.org/ecma-262/8.0/#sec-rawbytestonumber', - 'reads-bytes-from': 'https://ecma-international.org/ecma-262/8.0/#sec-reads-bytes-from', - 'reads-from': 'https://ecma-international.org/ecma-262/8.0/#sec-reads-from', - RegExpAlloc: 'https://ecma-international.org/ecma-262/8.0/#sec-regexpalloc', - RegExpBuiltinExec: 'https://ecma-international.org/ecma-262/8.0/#sec-regexpbuiltinexec', - RegExpCreate: 'https://ecma-international.org/ecma-262/8.0/#sec-regexpcreate', - RegExpExec: 'https://ecma-international.org/ecma-262/8.0/#sec-regexpexec', - RegExpInitialize: 'https://ecma-international.org/ecma-262/8.0/#sec-regexpinitialize', - RejectPromise: 'https://ecma-international.org/ecma-262/8.0/#sec-rejectpromise', - RemoveWaiter: 'https://ecma-international.org/ecma-262/8.0/#sec-removewaiter', - RemoveWaiters: 'https://ecma-international.org/ecma-262/8.0/#sec-removewaiters', - RepeatMatcher: 'https://ecma-international.org/ecma-262/8.0/#sec-runtime-semantics-repeatmatcher-abstract-operation', - RequireObjectCoercible: 'https://ecma-international.org/ecma-262/8.0/#sec-requireobjectcoercible', - ResolveBinding: 'https://ecma-international.org/ecma-262/8.0/#sec-resolvebinding', - ResolveThisBinding: 'https://ecma-international.org/ecma-262/8.0/#sec-resolvethisbinding', - ReturnIfAbrupt: 'https://ecma-international.org/ecma-262/8.0/#sec-returnifabrupt', - RunJobs: 'https://ecma-international.org/ecma-262/8.0/#sec-runjobs', - SameValue: 'https://ecma-international.org/ecma-262/8.0/#sec-samevalue', - SameValueNonNumber: 'https://ecma-international.org/ecma-262/8.0/#sec-samevaluenonnumber', - SameValueZero: 'https://ecma-international.org/ecma-262/8.0/#sec-samevaluezero', - ScriptEvaluation: 'https://ecma-international.org/ecma-262/8.0/#sec-runtime-semantics-scriptevaluation', - ScriptEvaluationJob: 'https://ecma-international.org/ecma-262/8.0/#sec-scriptevaluationjob', - SecFromTime: 'https://ecma-international.org/ecma-262/8.0/#eqn-SecFromTime', - SerializeJSONArray: 'https://ecma-international.org/ecma-262/8.0/#sec-serializejsonarray', - SerializeJSONObject: 'https://ecma-international.org/ecma-262/8.0/#sec-serializejsonobject', - SerializeJSONProperty: 'https://ecma-international.org/ecma-262/8.0/#sec-serializejsonproperty', - Set: 'https://ecma-international.org/ecma-262/8.0/#sec-set-o-p-v-throw', - SetDefaultGlobalBindings: 'https://ecma-international.org/ecma-262/8.0/#sec-setdefaultglobalbindings', - SetFunctionName: 'https://ecma-international.org/ecma-262/8.0/#sec-setfunctionname', - SetImmutablePrototype: 'https://ecma-international.org/ecma-262/8.0/#sec-set-immutable-prototype', - SetIntegrityLevel: 'https://ecma-international.org/ecma-262/8.0/#sec-setintegritylevel', - SetRealmGlobalObject: 'https://ecma-international.org/ecma-262/8.0/#sec-setrealmglobalobject', - SetValueInBuffer: 'https://ecma-international.org/ecma-262/8.0/#sec-setvalueinbuffer', - SetViewValue: 'https://ecma-international.org/ecma-262/8.0/#sec-setviewvalue', - SharedDataBlockEventSet: 'https://ecma-international.org/ecma-262/8.0/#sec-sharedatablockeventset', - SortCompare: 'https://ecma-international.org/ecma-262/8.0/#sec-sortcompare', - SpeciesConstructor: 'https://ecma-international.org/ecma-262/8.0/#sec-speciesconstructor', - SplitMatch: 'https://ecma-international.org/ecma-262/8.0/#sec-splitmatch', - 'Strict Equality Comparison': 'https://ecma-international.org/ecma-262/8.0/#sec-strict-equality-comparison', - StringCreate: 'https://ecma-international.org/ecma-262/8.0/#sec-stringcreate', - StringGetOwnProperty: 'https://ecma-international.org/ecma-262/8.0/#sec-stringgetownproperty', - Suspend: 'https://ecma-international.org/ecma-262/8.0/#sec-suspend', - SymbolDescriptiveString: 'https://ecma-international.org/ecma-262/8.0/#sec-symboldescriptivestring', - 'synchronizes-with': 'https://ecma-international.org/ecma-262/8.0/#sec-synchronizes-with', - TestIntegrityLevel: 'https://ecma-international.org/ecma-262/8.0/#sec-testintegritylevel', - thisBooleanValue: 'https://ecma-international.org/ecma-262/8.0/#sec-thisbooleanvalue', - thisNumberValue: 'https://ecma-international.org/ecma-262/8.0/#sec-thisnumbervalue', - thisStringValue: 'https://ecma-international.org/ecma-262/8.0/#sec-thisstringvalue', - thisTimeValue: 'https://ecma-international.org/ecma-262/8.0/#sec-thistimevalue', - TimeClip: 'https://ecma-international.org/ecma-262/8.0/#sec-timeclip', - TimeFromYear: 'https://ecma-international.org/ecma-262/8.0/#eqn-TimeFromYear', - TimeWithinDay: 'https://ecma-international.org/ecma-262/8.0/#eqn-TimeWithinDay', - ToBoolean: 'https://ecma-international.org/ecma-262/8.0/#sec-toboolean', - ToDateString: 'https://ecma-international.org/ecma-262/8.0/#sec-todatestring', - ToIndex: 'https://ecma-international.org/ecma-262/8.0/#sec-toindex', - ToInt16: 'https://ecma-international.org/ecma-262/8.0/#sec-toint16', - ToInt32: 'https://ecma-international.org/ecma-262/8.0/#sec-toint32', - ToInt8: 'https://ecma-international.org/ecma-262/8.0/#sec-toint8', - ToInteger: 'https://ecma-international.org/ecma-262/8.0/#sec-tointeger', - ToLength: 'https://ecma-international.org/ecma-262/8.0/#sec-tolength', - ToNumber: 'https://ecma-international.org/ecma-262/8.0/#sec-tonumber', - ToObject: 'https://ecma-international.org/ecma-262/8.0/#sec-toobject', - TopLevelModuleEvaluationJob: 'https://ecma-international.org/ecma-262/8.0/#sec-toplevelmoduleevaluationjob', - ToPrimitive: 'https://ecma-international.org/ecma-262/8.0/#sec-toprimitive', - ToPropertyDescriptor: 'https://ecma-international.org/ecma-262/8.0/#sec-topropertydescriptor', - ToPropertyKey: 'https://ecma-international.org/ecma-262/8.0/#sec-topropertykey', - ToString: 'https://ecma-international.org/ecma-262/8.0/#sec-tostring', - 'ToString Applied to the Number Type': 'https://ecma-international.org/ecma-262/8.0/#sec-tostring-applied-to-the-number-type', - ToUint16: 'https://ecma-international.org/ecma-262/8.0/#sec-touint16', - ToUint32: 'https://ecma-international.org/ecma-262/8.0/#sec-touint32', - ToUint8: 'https://ecma-international.org/ecma-262/8.0/#sec-touint8', - ToUint8Clamp: 'https://ecma-international.org/ecma-262/8.0/#sec-touint8clamp', - TriggerPromiseReactions: 'https://ecma-international.org/ecma-262/8.0/#sec-triggerpromisereactions', - Type: 'https://ecma-international.org/ecma-262/8.0/#sec-ecmascript-data-types-and-values', - TypedArrayCreate: 'https://ecma-international.org/ecma-262/8.0/#typedarray-create', - TypedArraySpeciesCreate: 'https://ecma-international.org/ecma-262/8.0/#typedarray-species-create', - UpdateEmpty: 'https://ecma-international.org/ecma-262/8.0/#sec-updateempty', - UTC: 'https://ecma-international.org/ecma-262/8.0/#sec-utc-t', - UTF16Decode: 'https://ecma-international.org/ecma-262/8.0/#sec-utf16decode', - UTF16Encoding: 'https://ecma-international.org/ecma-262/8.0/#sec-utf16encoding', - ValidateAndApplyPropertyDescriptor: 'https://ecma-international.org/ecma-262/8.0/#sec-validateandapplypropertydescriptor', - ValidateAtomicAccess: 'https://ecma-international.org/ecma-262/8.0/#sec-validateatomicaccess', - ValidateSharedIntegerTypedArray: 'https://ecma-international.org/ecma-262/8.0/#sec-validatesharedintegertypedarray', - ValidateTypedArray: 'https://ecma-international.org/ecma-262/8.0/#sec-validatetypedarray', - ValueOfReadEvent: 'https://ecma-international.org/ecma-262/8.0/#sec-valueofreadevent', - WakeWaiter: 'https://ecma-international.org/ecma-262/8.0/#sec-wakewaiter', - WeekDay: 'https://ecma-international.org/ecma-262/8.0/#sec-week-day', - WordCharacters: 'https://ecma-international.org/ecma-262/8.0/#sec-runtime-semantics-wordcharacters-abstract-operation', - YearFromTime: 'https://ecma-international.org/ecma-262/8.0/#eqn-YearFromTime' -}; diff --git a/node_modules/es-abstract/operations/2018.js b/node_modules/es-abstract/operations/2018.js deleted file mode 100644 index c93b561..0000000 --- a/node_modules/es-abstract/operations/2018.js +++ /dev/null @@ -1,350 +0,0 @@ -'use strict'; - -module.exports = { - abs: 'https://ecma-international.org/ecma-262/9.0/#eqn-abs', - 'Abstract Equality Comparison': 'https://ecma-international.org/ecma-262/9.0/#sec-abstract-equality-comparison', - 'Abstract Relational Comparison': 'https://ecma-international.org/ecma-262/9.0/#sec-abstract-relational-comparison', - AddRestrictedFunctionProperties: 'https://ecma-international.org/ecma-262/9.0/#sec-addrestrictedfunctionproperties', - AddWaiter: 'https://ecma-international.org/ecma-262/9.0/#sec-addwaiter', - AdvanceStringIndex: 'https://ecma-international.org/ecma-262/9.0/#sec-advancestringindex', - 'agent-order': 'https://ecma-international.org/ecma-262/9.0/#sec-agent-order', - AgentCanSuspend: 'https://ecma-international.org/ecma-262/9.0/#sec-agentcansuspend', - AgentSignifier: 'https://ecma-international.org/ecma-262/9.0/#sec-agentsignifier', - AllocateArrayBuffer: 'https://ecma-international.org/ecma-262/9.0/#sec-allocatearraybuffer', - AllocateSharedArrayBuffer: 'https://ecma-international.org/ecma-262/9.0/#sec-allocatesharedarraybuffer', - AllocateTypedArray: 'https://ecma-international.org/ecma-262/9.0/#sec-allocatetypedarray', - AllocateTypedArrayBuffer: 'https://ecma-international.org/ecma-262/9.0/#sec-allocatetypedarraybuffer', - ArrayCreate: 'https://ecma-international.org/ecma-262/9.0/#sec-arraycreate', - ArraySetLength: 'https://ecma-international.org/ecma-262/9.0/#sec-arraysetlength', - ArraySpeciesCreate: 'https://ecma-international.org/ecma-262/9.0/#sec-arrayspeciescreate', - AsyncFunctionCreate: 'https://ecma-international.org/ecma-262/9.0/#sec-async-functions-abstract-operations-async-function-create', - AsyncFunctionStart: 'https://ecma-international.org/ecma-262/9.0/#sec-async-functions-abstract-operations-async-function-start', - AsyncGeneratorEnqueue: 'https://ecma-international.org/ecma-262/9.0/#sec-asyncgeneratorenqueue', - AsyncGeneratorFunctionCreate: 'https://ecma-international.org/ecma-262/9.0/#sec-asyncgeneratorfunctioncreate', - AsyncGeneratorReject: 'https://ecma-international.org/ecma-262/9.0/#sec-asyncgeneratorreject', - AsyncGeneratorResolve: 'https://ecma-international.org/ecma-262/9.0/#sec-asyncgeneratorresolve', - AsyncGeneratorResumeNext: 'https://ecma-international.org/ecma-262/9.0/#sec-asyncgeneratorresumenext', - AsyncGeneratorStart: 'https://ecma-international.org/ecma-262/9.0/#sec-asyncgeneratorstart', - AsyncGeneratorYield: 'https://ecma-international.org/ecma-262/9.0/#sec-asyncgeneratoryield', - AsyncIteratorClose: 'https://ecma-international.org/ecma-262/9.0/#sec-asynciteratorclose', - AtomicLoad: 'https://ecma-international.org/ecma-262/9.0/#sec-atomicload', - AtomicReadModifyWrite: 'https://ecma-international.org/ecma-262/9.0/#sec-atomicreadmodifywrite', - Await: 'https://ecma-international.org/ecma-262/9.0/#await', - BackreferenceMatcher: 'https://ecma-international.org/ecma-262/9.0/#sec-backreference-matcher', - BlockDeclarationInstantiation: 'https://ecma-international.org/ecma-262/9.0/#sec-blockdeclarationinstantiation', - BoundFunctionCreate: 'https://ecma-international.org/ecma-262/9.0/#sec-boundfunctioncreate', - Call: 'https://ecma-international.org/ecma-262/9.0/#sec-call', - Canonicalize: 'https://ecma-international.org/ecma-262/9.0/#sec-runtime-semantics-canonicalize-ch', - CanonicalNumericIndexString: 'https://ecma-international.org/ecma-262/9.0/#sec-canonicalnumericindexstring', - CaseClauseIsSelected: 'https://ecma-international.org/ecma-262/9.0/#sec-runtime-semantics-caseclauseisselected', - CharacterRange: 'https://ecma-international.org/ecma-262/9.0/#sec-runtime-semantics-characterrange-abstract-operation', - CharacterRangeOrUnion: 'https://ecma-international.org/ecma-262/9.0/#sec-runtime-semantics-characterrangeorunion-abstract-operation', - CharacterSetMatcher: 'https://ecma-international.org/ecma-262/9.0/#sec-runtime-semantics-charactersetmatcher-abstract-operation', - CloneArrayBuffer: 'https://ecma-international.org/ecma-262/9.0/#sec-clonearraybuffer', - CompletePropertyDescriptor: 'https://ecma-international.org/ecma-262/9.0/#sec-completepropertydescriptor', - Completion: 'https://ecma-international.org/ecma-262/9.0/#sec-completion-record-specification-type', - ComposeWriteEventBytes: 'https://ecma-international.org/ecma-262/9.0/#sec-composewriteeventbytes', - Construct: 'https://ecma-international.org/ecma-262/9.0/#sec-construct', - CopyDataBlockBytes: 'https://ecma-international.org/ecma-262/9.0/#sec-copydatablockbytes', - CopyDataProperties: 'https://ecma-international.org/ecma-262/9.0/#sec-copydataproperties', - CreateArrayFromList: 'https://ecma-international.org/ecma-262/9.0/#sec-createarrayfromlist', - CreateArrayIterator: 'https://ecma-international.org/ecma-262/9.0/#sec-createarrayiterator', - CreateAsyncFromSyncIterator: 'https://ecma-international.org/ecma-262/9.0/#sec-createasyncfromsynciterator', - CreateBuiltinFunction: 'https://ecma-international.org/ecma-262/9.0/#sec-createbuiltinfunction', - CreateByteDataBlock: 'https://ecma-international.org/ecma-262/9.0/#sec-createbytedatablock', - CreateDataProperty: 'https://ecma-international.org/ecma-262/9.0/#sec-createdataproperty', - CreateDataPropertyOrThrow: 'https://ecma-international.org/ecma-262/9.0/#sec-createdatapropertyorthrow', - CreateDynamicFunction: 'https://ecma-international.org/ecma-262/9.0/#sec-createdynamicfunction', - CreateHTML: 'https://ecma-international.org/ecma-262/9.0/#sec-createhtml', - CreateIntrinsics: 'https://ecma-international.org/ecma-262/9.0/#sec-createintrinsics', - CreateIterResultObject: 'https://ecma-international.org/ecma-262/9.0/#sec-createiterresultobject', - CreateListFromArrayLike: 'https://ecma-international.org/ecma-262/9.0/#sec-createlistfromarraylike', - CreateListIteratorRecord: 'https://ecma-international.org/ecma-262/9.0/#sec-createlistiteratorRecord', - CreateMapIterator: 'https://ecma-international.org/ecma-262/9.0/#sec-createmapiterator', - CreateMappedArgumentsObject: 'https://ecma-international.org/ecma-262/9.0/#sec-createmappedargumentsobject', - CreateMethodProperty: 'https://ecma-international.org/ecma-262/9.0/#sec-createmethodproperty', - CreatePerIterationEnvironment: 'https://ecma-international.org/ecma-262/9.0/#sec-createperiterationenvironment', - CreateRealm: 'https://ecma-international.org/ecma-262/9.0/#sec-createrealm', - CreateResolvingFunctions: 'https://ecma-international.org/ecma-262/9.0/#sec-createresolvingfunctions', - CreateSetIterator: 'https://ecma-international.org/ecma-262/9.0/#sec-createsetiterator', - CreateSharedByteDataBlock: 'https://ecma-international.org/ecma-262/9.0/#sec-createsharedbytedatablock', - CreateStringIterator: 'https://ecma-international.org/ecma-262/9.0/#sec-createstringiterator', - CreateUnmappedArgumentsObject: 'https://ecma-international.org/ecma-262/9.0/#sec-createunmappedargumentsobject', - DateFromTime: 'https://ecma-international.org/ecma-262/9.0/#sec-date-number', - DateString: 'https://ecma-international.org/ecma-262/9.0/#sec-datestring', - Day: 'https://ecma-international.org/ecma-262/9.0/#eqn-Day', - DayFromYear: 'https://ecma-international.org/ecma-262/9.0/#eqn-DaysFromYear', - DaysInYear: 'https://ecma-international.org/ecma-262/9.0/#eqn-DaysInYear', - DayWithinYear: 'https://ecma-international.org/ecma-262/9.0/#eqn-DayWithinYear', - Decode: 'https://ecma-international.org/ecma-262/9.0/#sec-decode', - DefinePropertyOrThrow: 'https://ecma-international.org/ecma-262/9.0/#sec-definepropertyorthrow', - DeletePropertyOrThrow: 'https://ecma-international.org/ecma-262/9.0/#sec-deletepropertyorthrow', - DetachArrayBuffer: 'https://ecma-international.org/ecma-262/9.0/#sec-detacharraybuffer', - Encode: 'https://ecma-international.org/ecma-262/9.0/#sec-encode', - EnqueueJob: 'https://ecma-international.org/ecma-262/9.0/#sec-enqueuejob', - EnterCriticalSection: 'https://ecma-international.org/ecma-262/9.0/#sec-entercriticalsection', - EnumerableOwnPropertyNames: 'https://ecma-international.org/ecma-262/9.0/#sec-enumerableownpropertynames', - EnumerateObjectProperties: 'https://ecma-international.org/ecma-262/9.0/#sec-enumerate-object-properties', - EscapeRegExpPattern: 'https://ecma-international.org/ecma-262/9.0/#sec-escaperegexppattern', - EvalDeclarationInstantiation: 'https://ecma-international.org/ecma-262/9.0/#sec-evaldeclarationinstantiation', - EvaluateCall: 'https://ecma-international.org/ecma-262/9.0/#sec-evaluatecall', - EvaluateNew: 'https://ecma-international.org/ecma-262/9.0/#sec-evaluatenew', - EventSet: 'https://ecma-international.org/ecma-262/9.0/#sec-event-set', - floor: 'https://ecma-international.org/ecma-262/9.0/#eqn-floor', - ForBodyEvaluation: 'https://ecma-international.org/ecma-262/9.0/#sec-forbodyevaluation', - 'ForIn/OfBodyEvaluation': 'https://ecma-international.org/ecma-262/9.0/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset', - 'ForIn/OfHeadEvaluation': 'https://ecma-international.org/ecma-262/9.0/#sec-runtime-semantics-forin-div-ofheadevaluation-tdznames-expr-iterationkind', - FromPropertyDescriptor: 'https://ecma-international.org/ecma-262/9.0/#sec-frompropertydescriptor', - FulfillPromise: 'https://ecma-international.org/ecma-262/9.0/#sec-fulfillpromise', - FunctionAllocate: 'https://ecma-international.org/ecma-262/9.0/#sec-functionallocate', - FunctionCreate: 'https://ecma-international.org/ecma-262/9.0/#sec-functioncreate', - FunctionDeclarationInstantiation: 'https://ecma-international.org/ecma-262/9.0/#sec-functiondeclarationinstantiation', - FunctionInitialize: 'https://ecma-international.org/ecma-262/9.0/#sec-functioninitialize', - GeneratorFunctionCreate: 'https://ecma-international.org/ecma-262/9.0/#sec-generatorfunctioncreate', - GeneratorResume: 'https://ecma-international.org/ecma-262/9.0/#sec-generatorresume', - GeneratorResumeAbrupt: 'https://ecma-international.org/ecma-262/9.0/#sec-generatorresumeabrupt', - GeneratorStart: 'https://ecma-international.org/ecma-262/9.0/#sec-generatorstart', - GeneratorValidate: 'https://ecma-international.org/ecma-262/9.0/#sec-generatorvalidate', - GeneratorYield: 'https://ecma-international.org/ecma-262/9.0/#sec-generatoryield', - Get: 'https://ecma-international.org/ecma-262/9.0/#sec-get-o-p', - GetActiveScriptOrModule: 'https://ecma-international.org/ecma-262/9.0/#sec-getactivescriptormodule', - GetBase: 'https://ecma-international.org/ecma-262/9.0/#sec-getbase', - GetFunctionRealm: 'https://ecma-international.org/ecma-262/9.0/#sec-getfunctionrealm', - GetGeneratorKind: 'https://ecma-international.org/ecma-262/9.0/#sec-getgeneratorkind', - GetGlobalObject: 'https://ecma-international.org/ecma-262/9.0/#sec-getglobalobject', - GetIdentifierReference: 'https://ecma-international.org/ecma-262/9.0/#sec-getidentifierreference', - GetIterator: 'https://ecma-international.org/ecma-262/9.0/#sec-getiterator', - GetMethod: 'https://ecma-international.org/ecma-262/9.0/#sec-getmethod', - GetModifySetValueInBuffer: 'https://ecma-international.org/ecma-262/9.0/#sec-getmodifysetvalueinbuffer', - GetModuleNamespace: 'https://ecma-international.org/ecma-262/9.0/#sec-getmodulenamespace', - GetNewTarget: 'https://ecma-international.org/ecma-262/9.0/#sec-getnewtarget', - GetOwnPropertyKeys: 'https://ecma-international.org/ecma-262/9.0/#sec-getownpropertykeys', - GetPrototypeFromConstructor: 'https://ecma-international.org/ecma-262/9.0/#sec-getprototypefromconstructor', - GetReferencedName: 'https://ecma-international.org/ecma-262/9.0/#sec-getreferencedname', - GetSubstitution: 'https://ecma-international.org/ecma-262/9.0/#sec-getsubstitution', - GetSuperConstructor: 'https://ecma-international.org/ecma-262/9.0/#sec-getsuperconstructor', - GetTemplateObject: 'https://ecma-international.org/ecma-262/9.0/#sec-gettemplateobject', - GetThisEnvironment: 'https://ecma-international.org/ecma-262/9.0/#sec-getthisenvironment', - GetThisValue: 'https://ecma-international.org/ecma-262/9.0/#sec-getthisvalue', - GetV: 'https://ecma-international.org/ecma-262/9.0/#sec-getv', - GetValue: 'https://ecma-international.org/ecma-262/9.0/#sec-getvalue', - GetValueFromBuffer: 'https://ecma-international.org/ecma-262/9.0/#sec-getvaluefrombuffer', - GetViewValue: 'https://ecma-international.org/ecma-262/9.0/#sec-getviewvalue', - GetWaiterList: 'https://ecma-international.org/ecma-262/9.0/#sec-getwaiterlist', - GlobalDeclarationInstantiation: 'https://ecma-international.org/ecma-262/9.0/#sec-globaldeclarationinstantiation', - 'happens-before': 'https://ecma-international.org/ecma-262/9.0/#sec-happens-before', - HasOwnProperty: 'https://ecma-international.org/ecma-262/9.0/#sec-hasownproperty', - HasPrimitiveBase: 'https://ecma-international.org/ecma-262/9.0/#sec-hasprimitivebase', - HasProperty: 'https://ecma-international.org/ecma-262/9.0/#sec-hasproperty', - 'host-synchronizes-with': 'https://ecma-international.org/ecma-262/9.0/#sec-host-synchronizes-with', - HostEnsureCanCompileStrings: 'https://ecma-international.org/ecma-262/9.0/#sec-hostensurecancompilestrings', - HostEventSet: 'https://ecma-international.org/ecma-262/9.0/#sec-hosteventset', - HostPromiseRejectionTracker: 'https://ecma-international.org/ecma-262/9.0/#sec-host-promise-rejection-tracker', - HostReportErrors: 'https://ecma-international.org/ecma-262/9.0/#sec-host-report-errors', - HostResolveImportedModule: 'https://ecma-international.org/ecma-262/9.0/#sec-hostresolveimportedmodule', - HourFromTime: 'https://ecma-international.org/ecma-262/9.0/#eqn-HourFromTime', - IfAbruptRejectPromise: 'https://ecma-international.org/ecma-262/9.0/#sec-ifabruptrejectpromise', - ImportedLocalNames: 'https://ecma-international.org/ecma-262/9.0/#sec-importedlocalnames', - InitializeBoundName: 'https://ecma-international.org/ecma-262/9.0/#sec-initializeboundname', - InitializeHostDefinedRealm: 'https://ecma-international.org/ecma-262/9.0/#sec-initializehostdefinedrealm', - InitializeReferencedBinding: 'https://ecma-international.org/ecma-262/9.0/#sec-initializereferencedbinding', - InLeapYear: 'https://ecma-international.org/ecma-262/9.0/#eqn-InLeapYear', - InnerModuleEvaluation: 'https://ecma-international.org/ecma-262/9.0/#sec-innermoduleevaluation', - InnerModuleInstantiation: 'https://ecma-international.org/ecma-262/9.0/#sec-innermoduleinstantiation', - InstanceofOperator: 'https://ecma-international.org/ecma-262/9.0/#sec-instanceofoperator', - IntegerIndexedElementGet: 'https://ecma-international.org/ecma-262/9.0/#sec-integerindexedelementget', - IntegerIndexedElementSet: 'https://ecma-international.org/ecma-262/9.0/#sec-integerindexedelementset', - IntegerIndexedObjectCreate: 'https://ecma-international.org/ecma-262/9.0/#sec-integerindexedobjectcreate', - InternalizeJSONProperty: 'https://ecma-international.org/ecma-262/9.0/#sec-internalizejsonproperty', - Invoke: 'https://ecma-international.org/ecma-262/9.0/#sec-invoke', - IsAccessorDescriptor: 'https://ecma-international.org/ecma-262/9.0/#sec-isaccessordescriptor', - IsAnonymousFunctionDefinition: 'https://ecma-international.org/ecma-262/9.0/#sec-isanonymousfunctiondefinition', - IsArray: 'https://ecma-international.org/ecma-262/9.0/#sec-isarray', - IsCallable: 'https://ecma-international.org/ecma-262/9.0/#sec-iscallable', - IsCompatiblePropertyDescriptor: 'https://ecma-international.org/ecma-262/9.0/#sec-iscompatiblepropertydescriptor', - IsConcatSpreadable: 'https://ecma-international.org/ecma-262/9.0/#sec-isconcatspreadable', - IsConstructor: 'https://ecma-international.org/ecma-262/9.0/#sec-isconstructor', - IsDataDescriptor: 'https://ecma-international.org/ecma-262/9.0/#sec-isdatadescriptor', - IsDetachedBuffer: 'https://ecma-international.org/ecma-262/9.0/#sec-isdetachedbuffer', - IsExtensible: 'https://ecma-international.org/ecma-262/9.0/#sec-isextensible-o', - IsGenericDescriptor: 'https://ecma-international.org/ecma-262/9.0/#sec-isgenericdescriptor', - IsInTailPosition: 'https://ecma-international.org/ecma-262/9.0/#sec-isintailposition', - IsInteger: 'https://ecma-international.org/ecma-262/9.0/#sec-isinteger', - IsLabelledFunction: 'https://ecma-international.org/ecma-262/9.0/#sec-islabelledfunction', - IsPromise: 'https://ecma-international.org/ecma-262/9.0/#sec-ispromise', - IsPropertyKey: 'https://ecma-international.org/ecma-262/9.0/#sec-ispropertykey', - IsPropertyReference: 'https://ecma-international.org/ecma-262/9.0/#sec-ispropertyreference', - IsRegExp: 'https://ecma-international.org/ecma-262/9.0/#sec-isregexp', - IsSharedArrayBuffer: 'https://ecma-international.org/ecma-262/9.0/#sec-issharedarraybuffer', - IsStrictReference: 'https://ecma-international.org/ecma-262/9.0/#sec-isstrictreference', - IsStringPrefix: 'https://ecma-international.org/ecma-262/9.0/#sec-isstringprefix', - IsSuperReference: 'https://ecma-international.org/ecma-262/9.0/#sec-issuperreference', - IsUnresolvableReference: 'https://ecma-international.org/ecma-262/9.0/#sec-isunresolvablereference', - IsWordChar: 'https://ecma-international.org/ecma-262/9.0/#sec-runtime-semantics-iswordchar-abstract-operation', - IterableToList: 'https://ecma-international.org/ecma-262/9.0/#sec-iterabletolist', - IteratorClose: 'https://ecma-international.org/ecma-262/9.0/#sec-iteratorclose', - IteratorComplete: 'https://ecma-international.org/ecma-262/9.0/#sec-iteratorcomplete', - IteratorNext: 'https://ecma-international.org/ecma-262/9.0/#sec-iteratornext', - IteratorStep: 'https://ecma-international.org/ecma-262/9.0/#sec-iteratorstep', - IteratorValue: 'https://ecma-international.org/ecma-262/9.0/#sec-iteratorvalue', - LeaveCriticalSection: 'https://ecma-international.org/ecma-262/9.0/#sec-leavecriticalsection', - LocalTime: 'https://ecma-international.org/ecma-262/9.0/#sec-localtime', - LoopContinues: 'https://ecma-international.org/ecma-262/9.0/#sec-loopcontinues', - MakeArgGetter: 'https://ecma-international.org/ecma-262/9.0/#sec-makearggetter', - MakeArgSetter: 'https://ecma-international.org/ecma-262/9.0/#sec-makeargsetter', - MakeClassConstructor: 'https://ecma-international.org/ecma-262/9.0/#sec-makeclassconstructor', - MakeConstructor: 'https://ecma-international.org/ecma-262/9.0/#sec-makeconstructor', - MakeDate: 'https://ecma-international.org/ecma-262/9.0/#sec-makedate', - MakeDay: 'https://ecma-international.org/ecma-262/9.0/#sec-makeday', - MakeMethod: 'https://ecma-international.org/ecma-262/9.0/#sec-makemethod', - MakeSuperPropertyReference: 'https://ecma-international.org/ecma-262/9.0/#sec-makesuperpropertyreference', - MakeTime: 'https://ecma-international.org/ecma-262/9.0/#sec-maketime', - max: 'https://ecma-international.org/ecma-262/9.0/#eqn-max', - 'memory-order': 'https://ecma-international.org/ecma-262/9.0/#sec-memory-order', - min: 'https://ecma-international.org/ecma-262/9.0/#eqn-min', - MinFromTime: 'https://ecma-international.org/ecma-262/9.0/#eqn-MinFromTime', - ModuleDeclarationEnvironmentSetup: 'https://ecma-international.org/ecma-262/9.0/#sec-moduledeclarationenvironmentsetup', - ModuleExecution: 'https://ecma-international.org/ecma-262/9.0/#sec-moduleexecution', - ModuleNamespaceCreate: 'https://ecma-international.org/ecma-262/9.0/#sec-modulenamespacecreate', - modulo: 'https://ecma-international.org/ecma-262/9.0/#eqn-modulo', - MonthFromTime: 'https://ecma-international.org/ecma-262/9.0/#eqn-MonthFromTime', - msFromTime: 'https://ecma-international.org/ecma-262/9.0/#eqn-msFromTime', - NewDeclarativeEnvironment: 'https://ecma-international.org/ecma-262/9.0/#sec-newdeclarativeenvironment', - NewFunctionEnvironment: 'https://ecma-international.org/ecma-262/9.0/#sec-newfunctionenvironment', - NewGlobalEnvironment: 'https://ecma-international.org/ecma-262/9.0/#sec-newglobalenvironment', - NewModuleEnvironment: 'https://ecma-international.org/ecma-262/9.0/#sec-newmoduleenvironment', - NewObjectEnvironment: 'https://ecma-international.org/ecma-262/9.0/#sec-newobjectenvironment', - NewPromiseCapability: 'https://ecma-international.org/ecma-262/9.0/#sec-newpromisecapability', - NormalCompletion: 'https://ecma-international.org/ecma-262/9.0/#sec-normalcompletion', - NumberToRawBytes: 'https://ecma-international.org/ecma-262/9.0/#sec-numbertorawbytes', - NumberToString: 'https://ecma-international.org/ecma-262/9.0/#sec-tostring-applied-to-the-number-type', - ObjectCreate: 'https://ecma-international.org/ecma-262/9.0/#sec-objectcreate', - ObjectDefineProperties: 'https://ecma-international.org/ecma-262/9.0/#sec-objectdefineproperties', - OrdinaryCallBindThis: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinarycallbindthis', - OrdinaryCallEvaluateBody: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinarycallevaluatebody', - OrdinaryCreateFromConstructor: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinarycreatefromconstructor', - OrdinaryDefineOwnProperty: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinarydefineownproperty', - OrdinaryDelete: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinarydelete', - OrdinaryGet: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinaryget', - OrdinaryGetOwnProperty: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinarygetownproperty', - OrdinaryGetPrototypeOf: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinarygetprototypeof', - OrdinaryHasInstance: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinaryhasinstance', - OrdinaryHasProperty: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinaryhasproperty', - OrdinaryIsExtensible: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinaryisextensible', - OrdinaryOwnPropertyKeys: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinaryownpropertykeys', - OrdinaryPreventExtensions: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinarypreventextensions', - OrdinarySet: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinaryset', - OrdinarySetPrototypeOf: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinarysetprototypeof', - OrdinarySetWithOwnDescriptor: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinarysetwithowndescriptor', - OrdinaryToPrimitive: 'https://ecma-international.org/ecma-262/9.0/#sec-ordinarytoprimitive', - ParseModule: 'https://ecma-international.org/ecma-262/9.0/#sec-parsemodule', - ParseScript: 'https://ecma-international.org/ecma-262/9.0/#sec-parse-script', - PerformEval: 'https://ecma-international.org/ecma-262/9.0/#sec-performeval', - PerformPromiseAll: 'https://ecma-international.org/ecma-262/9.0/#sec-performpromiseall', - PerformPromiseRace: 'https://ecma-international.org/ecma-262/9.0/#sec-performpromiserace', - PerformPromiseThen: 'https://ecma-international.org/ecma-262/9.0/#sec-performpromisethen', - PrepareForOrdinaryCall: 'https://ecma-international.org/ecma-262/9.0/#sec-prepareforordinarycall', - PrepareForTailCall: 'https://ecma-international.org/ecma-262/9.0/#sec-preparefortailcall', - PromiseReactionJob: 'https://ecma-international.org/ecma-262/9.0/#sec-promisereactionjob', - PromiseResolve: 'https://ecma-international.org/ecma-262/9.0/#sec-promise-resolve', - PromiseResolveThenableJob: 'https://ecma-international.org/ecma-262/9.0/#sec-promiseresolvethenablejob', - ProxyCreate: 'https://ecma-international.org/ecma-262/9.0/#sec-proxycreate', - PutValue: 'https://ecma-international.org/ecma-262/9.0/#sec-putvalue', - QuoteJSONString: 'https://ecma-international.org/ecma-262/9.0/#sec-quotejsonstring', - RawBytesToNumber: 'https://ecma-international.org/ecma-262/9.0/#sec-rawbytestonumber', - 'reads-bytes-from': 'https://ecma-international.org/ecma-262/9.0/#sec-reads-bytes-from', - 'reads-from': 'https://ecma-international.org/ecma-262/9.0/#sec-reads-from', - RegExpAlloc: 'https://ecma-international.org/ecma-262/9.0/#sec-regexpalloc', - RegExpBuiltinExec: 'https://ecma-international.org/ecma-262/9.0/#sec-regexpbuiltinexec', - RegExpCreate: 'https://ecma-international.org/ecma-262/9.0/#sec-regexpcreate', - RegExpExec: 'https://ecma-international.org/ecma-262/9.0/#sec-regexpexec', - RegExpInitialize: 'https://ecma-international.org/ecma-262/9.0/#sec-regexpinitialize', - RejectPromise: 'https://ecma-international.org/ecma-262/9.0/#sec-rejectpromise', - RemoveWaiter: 'https://ecma-international.org/ecma-262/9.0/#sec-removewaiter', - RemoveWaiters: 'https://ecma-international.org/ecma-262/9.0/#sec-removewaiters', - RepeatMatcher: 'https://ecma-international.org/ecma-262/9.0/#sec-runtime-semantics-repeatmatcher-abstract-operation', - RequireObjectCoercible: 'https://ecma-international.org/ecma-262/9.0/#sec-requireobjectcoercible', - ResolveBinding: 'https://ecma-international.org/ecma-262/9.0/#sec-resolvebinding', - ResolveThisBinding: 'https://ecma-international.org/ecma-262/9.0/#sec-resolvethisbinding', - ReturnIfAbrupt: 'https://ecma-international.org/ecma-262/9.0/#sec-returnifabrupt', - RunJobs: 'https://ecma-international.org/ecma-262/9.0/#sec-runjobs', - SameValue: 'https://ecma-international.org/ecma-262/9.0/#sec-samevalue', - SameValueNonNumber: 'https://ecma-international.org/ecma-262/9.0/#sec-samevaluenonnumber', - SameValueZero: 'https://ecma-international.org/ecma-262/9.0/#sec-samevaluezero', - ScriptEvaluation: 'https://ecma-international.org/ecma-262/9.0/#sec-runtime-semantics-scriptevaluation', - ScriptEvaluationJob: 'https://ecma-international.org/ecma-262/9.0/#sec-scriptevaluationjob', - SecFromTime: 'https://ecma-international.org/ecma-262/9.0/#eqn-SecFromTime', - SerializeJSONArray: 'https://ecma-international.org/ecma-262/9.0/#sec-serializejsonarray', - SerializeJSONObject: 'https://ecma-international.org/ecma-262/9.0/#sec-serializejsonobject', - SerializeJSONProperty: 'https://ecma-international.org/ecma-262/9.0/#sec-serializejsonproperty', - Set: 'https://ecma-international.org/ecma-262/9.0/#sec-set-o-p-v-throw', - SetDefaultGlobalBindings: 'https://ecma-international.org/ecma-262/9.0/#sec-setdefaultglobalbindings', - SetFunctionLength: 'https://ecma-international.org/ecma-262/9.0/#sec-setfunctionlength', - SetFunctionName: 'https://ecma-international.org/ecma-262/9.0/#sec-setfunctionname', - SetImmutablePrototype: 'https://ecma-international.org/ecma-262/9.0/#sec-set-immutable-prototype', - SetIntegrityLevel: 'https://ecma-international.org/ecma-262/9.0/#sec-setintegritylevel', - SetRealmGlobalObject: 'https://ecma-international.org/ecma-262/9.0/#sec-setrealmglobalobject', - SetValueInBuffer: 'https://ecma-international.org/ecma-262/9.0/#sec-setvalueinbuffer', - SetViewValue: 'https://ecma-international.org/ecma-262/9.0/#sec-setviewvalue', - SharedDataBlockEventSet: 'https://ecma-international.org/ecma-262/9.0/#sec-sharedatablockeventset', - SortCompare: 'https://ecma-international.org/ecma-262/9.0/#sec-sortcompare', - SpeciesConstructor: 'https://ecma-international.org/ecma-262/9.0/#sec-speciesconstructor', - SplitMatch: 'https://ecma-international.org/ecma-262/9.0/#sec-splitmatch', - 'Strict Equality Comparison': 'https://ecma-international.org/ecma-262/9.0/#sec-strict-equality-comparison', - StringCreate: 'https://ecma-international.org/ecma-262/9.0/#sec-stringcreate', - StringGetOwnProperty: 'https://ecma-international.org/ecma-262/9.0/#sec-stringgetownproperty', - Suspend: 'https://ecma-international.org/ecma-262/9.0/#sec-suspend', - SymbolDescriptiveString: 'https://ecma-international.org/ecma-262/9.0/#sec-symboldescriptivestring', - 'synchronizes-with': 'https://ecma-international.org/ecma-262/9.0/#sec-synchronizes-with', - TestIntegrityLevel: 'https://ecma-international.org/ecma-262/9.0/#sec-testintegritylevel', - thisBooleanValue: 'https://ecma-international.org/ecma-262/9.0/#sec-thisbooleanvalue', - thisNumberValue: 'https://ecma-international.org/ecma-262/9.0/#sec-thisnumbervalue', - thisStringValue: 'https://ecma-international.org/ecma-262/9.0/#sec-thisstringvalue', - thisSymbolValue: 'https://ecma-international.org/ecma-262/9.0/#sec-thissymbolvalue', - thisTimeValue: 'https://ecma-international.org/ecma-262/9.0/#sec-thistimevalue', - ThrowCompletion: 'https://ecma-international.org/ecma-262/9.0/#sec-throwcompletion', - TimeClip: 'https://ecma-international.org/ecma-262/9.0/#sec-timeclip', - TimeFromYear: 'https://ecma-international.org/ecma-262/9.0/#eqn-TimeFromYear', - TimeString: 'https://ecma-international.org/ecma-262/9.0/#sec-timestring', - TimeWithinDay: 'https://ecma-international.org/ecma-262/9.0/#eqn-TimeWithinDay', - TimeZoneString: 'https://ecma-international.org/ecma-262/9.0/#sec-timezoneestring', - ToBoolean: 'https://ecma-international.org/ecma-262/9.0/#sec-toboolean', - ToDateString: 'https://ecma-international.org/ecma-262/9.0/#sec-todatestring', - ToIndex: 'https://ecma-international.org/ecma-262/9.0/#sec-toindex', - ToInt16: 'https://ecma-international.org/ecma-262/9.0/#sec-toint16', - ToInt32: 'https://ecma-international.org/ecma-262/9.0/#sec-toint32', - ToInt8: 'https://ecma-international.org/ecma-262/9.0/#sec-toint8', - ToInteger: 'https://ecma-international.org/ecma-262/9.0/#sec-tointeger', - ToLength: 'https://ecma-international.org/ecma-262/9.0/#sec-tolength', - ToNumber: 'https://ecma-international.org/ecma-262/9.0/#sec-tonumber', - ToObject: 'https://ecma-international.org/ecma-262/9.0/#sec-toobject', - TopLevelModuleEvaluationJob: 'https://ecma-international.org/ecma-262/9.0/#sec-toplevelmoduleevaluationjob', - ToPrimitive: 'https://ecma-international.org/ecma-262/9.0/#sec-toprimitive', - ToPropertyDescriptor: 'https://ecma-international.org/ecma-262/9.0/#sec-topropertydescriptor', - ToPropertyKey: 'https://ecma-international.org/ecma-262/9.0/#sec-topropertykey', - ToString: 'https://ecma-international.org/ecma-262/9.0/#sec-tostring', - ToUint16: 'https://ecma-international.org/ecma-262/9.0/#sec-touint16', - ToUint32: 'https://ecma-international.org/ecma-262/9.0/#sec-touint32', - ToUint8: 'https://ecma-international.org/ecma-262/9.0/#sec-touint8', - ToUint8Clamp: 'https://ecma-international.org/ecma-262/9.0/#sec-touint8clamp', - TriggerPromiseReactions: 'https://ecma-international.org/ecma-262/9.0/#sec-triggerpromisereactions', - Type: 'https://ecma-international.org/ecma-262/9.0/#sec-ecmascript-data-types-and-values', - TypedArrayCreate: 'https://ecma-international.org/ecma-262/9.0/#typedarray-create', - TypedArraySpeciesCreate: 'https://ecma-international.org/ecma-262/9.0/#typedarray-species-create', - UnicodeEscape: 'https://ecma-international.org/ecma-262/9.0/#sec-unicodeescape', - UnicodeMatchProperty: 'https://ecma-international.org/ecma-262/9.0/#sec-runtime-semantics-unicodematchproperty-p', - UnicodeMatchPropertyValue: 'https://ecma-international.org/ecma-262/9.0/#sec-runtime-semantics-unicodematchpropertyvalue-p-v', - UpdateEmpty: 'https://ecma-international.org/ecma-262/9.0/#sec-updateempty', - UTC: 'https://ecma-international.org/ecma-262/9.0/#sec-utc-t', - UTF16Decode: 'https://ecma-international.org/ecma-262/9.0/#sec-utf16decode', - UTF16Encoding: 'https://ecma-international.org/ecma-262/9.0/#sec-utf16encoding', - ValidateAndApplyPropertyDescriptor: 'https://ecma-international.org/ecma-262/9.0/#sec-validateandapplypropertydescriptor', - ValidateAtomicAccess: 'https://ecma-international.org/ecma-262/9.0/#sec-validateatomicaccess', - ValidateSharedIntegerTypedArray: 'https://ecma-international.org/ecma-262/9.0/#sec-validatesharedintegertypedarray', - ValidateTypedArray: 'https://ecma-international.org/ecma-262/9.0/#sec-validatetypedarray', - ValueOfReadEvent: 'https://ecma-international.org/ecma-262/9.0/#sec-valueofreadevent', - WakeWaiter: 'https://ecma-international.org/ecma-262/9.0/#sec-wakewaiter', - WeekDay: 'https://ecma-international.org/ecma-262/9.0/#sec-week-day', - WordCharacters: 'https://ecma-international.org/ecma-262/9.0/#sec-runtime-semantics-wordcharacters-abstract-operation', - YearFromTime: 'https://ecma-international.org/ecma-262/9.0/#eqn-YearFromTime' -}; diff --git a/node_modules/es-abstract/operations/2019.js b/node_modules/es-abstract/operations/2019.js deleted file mode 100644 index 73f05e8..0000000 --- a/node_modules/es-abstract/operations/2019.js +++ /dev/null @@ -1,355 +0,0 @@ -'use strict'; - -module.exports = { - abs: 'https://ecma-international.org/ecma-262/10.0/#eqn-abs', - 'Abstract Equality Comparison': 'https://ecma-international.org/ecma-262/10.0/#sec-abstract-equality-comparison', - 'Abstract Relational Comparison': 'https://ecma-international.org/ecma-262/10.0/#sec-abstract-relational-comparison', - AddEntriesFromIterable: 'https://ecma-international.org/ecma-262/10.0/#sec-add-entries-from-iterable', - AddRestrictedFunctionProperties: 'https://ecma-international.org/ecma-262/10.0/#sec-addrestrictedfunctionproperties', - AddWaiter: 'https://ecma-international.org/ecma-262/10.0/#sec-addwaiter', - AdvanceStringIndex: 'https://ecma-international.org/ecma-262/10.0/#sec-advancestringindex', - 'agent-order': 'https://ecma-international.org/ecma-262/10.0/#sec-agent-order', - AgentCanSuspend: 'https://ecma-international.org/ecma-262/10.0/#sec-agentcansuspend', - AgentSignifier: 'https://ecma-international.org/ecma-262/10.0/#sec-agentsignifier', - AllocateArrayBuffer: 'https://ecma-international.org/ecma-262/10.0/#sec-allocatearraybuffer', - AllocateSharedArrayBuffer: 'https://ecma-international.org/ecma-262/10.0/#sec-allocatesharedarraybuffer', - AllocateTypedArray: 'https://ecma-international.org/ecma-262/10.0/#sec-allocatetypedarray', - AllocateTypedArrayBuffer: 'https://ecma-international.org/ecma-262/10.0/#sec-allocatetypedarraybuffer', - ArrayCreate: 'https://ecma-international.org/ecma-262/10.0/#sec-arraycreate', - ArraySetLength: 'https://ecma-international.org/ecma-262/10.0/#sec-arraysetlength', - ArraySpeciesCreate: 'https://ecma-international.org/ecma-262/10.0/#sec-arrayspeciescreate', - AsyncFromSyncIteratorContinuation: 'https://ecma-international.org/ecma-262/10.0/#sec-asyncfromsynciteratorcontinuation', - AsyncFunctionCreate: 'https://ecma-international.org/ecma-262/10.0/#sec-async-functions-abstract-operations-async-function-create', - AsyncFunctionStart: 'https://ecma-international.org/ecma-262/10.0/#sec-async-functions-abstract-operations-async-function-start', - AsyncGeneratorEnqueue: 'https://ecma-international.org/ecma-262/10.0/#sec-asyncgeneratorenqueue', - AsyncGeneratorFunctionCreate: 'https://ecma-international.org/ecma-262/10.0/#sec-asyncgeneratorfunctioncreate', - AsyncGeneratorReject: 'https://ecma-international.org/ecma-262/10.0/#sec-asyncgeneratorreject', - AsyncGeneratorResolve: 'https://ecma-international.org/ecma-262/10.0/#sec-asyncgeneratorresolve', - AsyncGeneratorResumeNext: 'https://ecma-international.org/ecma-262/10.0/#sec-asyncgeneratorresumenext', - AsyncGeneratorStart: 'https://ecma-international.org/ecma-262/10.0/#sec-asyncgeneratorstart', - AsyncGeneratorYield: 'https://ecma-international.org/ecma-262/10.0/#sec-asyncgeneratoryield', - AsyncIteratorClose: 'https://ecma-international.org/ecma-262/10.0/#sec-asynciteratorclose', - AtomicLoad: 'https://ecma-international.org/ecma-262/10.0/#sec-atomicload', - AtomicReadModifyWrite: 'https://ecma-international.org/ecma-262/10.0/#sec-atomicreadmodifywrite', - Await: 'https://ecma-international.org/ecma-262/10.0/#await', - BackreferenceMatcher: 'https://ecma-international.org/ecma-262/10.0/#sec-backreference-matcher', - BlockDeclarationInstantiation: 'https://ecma-international.org/ecma-262/10.0/#sec-blockdeclarationinstantiation', - BoundFunctionCreate: 'https://ecma-international.org/ecma-262/10.0/#sec-boundfunctioncreate', - Call: 'https://ecma-international.org/ecma-262/10.0/#sec-call', - Canonicalize: 'https://ecma-international.org/ecma-262/10.0/#sec-runtime-semantics-canonicalize-ch', - CanonicalNumericIndexString: 'https://ecma-international.org/ecma-262/10.0/#sec-canonicalnumericindexstring', - CaseClauseIsSelected: 'https://ecma-international.org/ecma-262/10.0/#sec-runtime-semantics-caseclauseisselected', - CharacterRange: 'https://ecma-international.org/ecma-262/10.0/#sec-runtime-semantics-characterrange-abstract-operation', - CharacterRangeOrUnion: 'https://ecma-international.org/ecma-262/10.0/#sec-runtime-semantics-characterrangeorunion-abstract-operation', - CharacterSetMatcher: 'https://ecma-international.org/ecma-262/10.0/#sec-runtime-semantics-charactersetmatcher-abstract-operation', - CloneArrayBuffer: 'https://ecma-international.org/ecma-262/10.0/#sec-clonearraybuffer', - CompletePropertyDescriptor: 'https://ecma-international.org/ecma-262/10.0/#sec-completepropertydescriptor', - Completion: 'https://ecma-international.org/ecma-262/10.0/#sec-completion-record-specification-type', - ComposeWriteEventBytes: 'https://ecma-international.org/ecma-262/10.0/#sec-composewriteeventbytes', - Construct: 'https://ecma-international.org/ecma-262/10.0/#sec-construct', - CopyDataBlockBytes: 'https://ecma-international.org/ecma-262/10.0/#sec-copydatablockbytes', - CopyDataProperties: 'https://ecma-international.org/ecma-262/10.0/#sec-copydataproperties', - CreateArrayFromList: 'https://ecma-international.org/ecma-262/10.0/#sec-createarrayfromlist', - CreateArrayIterator: 'https://ecma-international.org/ecma-262/10.0/#sec-createarrayiterator', - CreateAsyncFromSyncIterator: 'https://ecma-international.org/ecma-262/10.0/#sec-createasyncfromsynciterator', - CreateBuiltinFunction: 'https://ecma-international.org/ecma-262/10.0/#sec-createbuiltinfunction', - CreateByteDataBlock: 'https://ecma-international.org/ecma-262/10.0/#sec-createbytedatablock', - CreateDataProperty: 'https://ecma-international.org/ecma-262/10.0/#sec-createdataproperty', - CreateDataPropertyOrThrow: 'https://ecma-international.org/ecma-262/10.0/#sec-createdatapropertyorthrow', - CreateDynamicFunction: 'https://ecma-international.org/ecma-262/10.0/#sec-createdynamicfunction', - CreateHTML: 'https://ecma-international.org/ecma-262/10.0/#sec-createhtml', - CreateIntrinsics: 'https://ecma-international.org/ecma-262/10.0/#sec-createintrinsics', - CreateIterResultObject: 'https://ecma-international.org/ecma-262/10.0/#sec-createiterresultobject', - CreateListFromArrayLike: 'https://ecma-international.org/ecma-262/10.0/#sec-createlistfromarraylike', - CreateListIteratorRecord: 'https://ecma-international.org/ecma-262/10.0/#sec-createlistiteratorRecord', - CreateMapIterator: 'https://ecma-international.org/ecma-262/10.0/#sec-createmapiterator', - CreateMappedArgumentsObject: 'https://ecma-international.org/ecma-262/10.0/#sec-createmappedargumentsobject', - CreateMethodProperty: 'https://ecma-international.org/ecma-262/10.0/#sec-createmethodproperty', - CreatePerIterationEnvironment: 'https://ecma-international.org/ecma-262/10.0/#sec-createperiterationenvironment', - CreateRealm: 'https://ecma-international.org/ecma-262/10.0/#sec-createrealm', - CreateResolvingFunctions: 'https://ecma-international.org/ecma-262/10.0/#sec-createresolvingfunctions', - CreateSetIterator: 'https://ecma-international.org/ecma-262/10.0/#sec-createsetiterator', - CreateSharedByteDataBlock: 'https://ecma-international.org/ecma-262/10.0/#sec-createsharedbytedatablock', - CreateStringIterator: 'https://ecma-international.org/ecma-262/10.0/#sec-createstringiterator', - CreateUnmappedArgumentsObject: 'https://ecma-international.org/ecma-262/10.0/#sec-createunmappedargumentsobject', - DateFromTime: 'https://ecma-international.org/ecma-262/10.0/#sec-date-number', - DateString: 'https://ecma-international.org/ecma-262/10.0/#sec-datestring', - Day: 'https://ecma-international.org/ecma-262/10.0/#eqn-Day', - DayFromYear: 'https://ecma-international.org/ecma-262/10.0/#eqn-DaysFromYear', - DaysInYear: 'https://ecma-international.org/ecma-262/10.0/#eqn-DaysInYear', - DayWithinYear: 'https://ecma-international.org/ecma-262/10.0/#eqn-DayWithinYear', - Decode: 'https://ecma-international.org/ecma-262/10.0/#sec-decode', - DefinePropertyOrThrow: 'https://ecma-international.org/ecma-262/10.0/#sec-definepropertyorthrow', - DeletePropertyOrThrow: 'https://ecma-international.org/ecma-262/10.0/#sec-deletepropertyorthrow', - DetachArrayBuffer: 'https://ecma-international.org/ecma-262/10.0/#sec-detacharraybuffer', - Encode: 'https://ecma-international.org/ecma-262/10.0/#sec-encode', - EnqueueJob: 'https://ecma-international.org/ecma-262/10.0/#sec-enqueuejob', - EnterCriticalSection: 'https://ecma-international.org/ecma-262/10.0/#sec-entercriticalsection', - EnumerableOwnPropertyNames: 'https://ecma-international.org/ecma-262/10.0/#sec-enumerableownpropertynames', - EnumerateObjectProperties: 'https://ecma-international.org/ecma-262/10.0/#sec-enumerate-object-properties', - EscapeRegExpPattern: 'https://ecma-international.org/ecma-262/10.0/#sec-escaperegexppattern', - EvalDeclarationInstantiation: 'https://ecma-international.org/ecma-262/10.0/#sec-evaldeclarationinstantiation', - EvaluateCall: 'https://ecma-international.org/ecma-262/10.0/#sec-evaluatecall', - EvaluateNew: 'https://ecma-international.org/ecma-262/10.0/#sec-evaluatenew', - EventSet: 'https://ecma-international.org/ecma-262/10.0/#sec-event-set', - ExecuteModule: 'https://ecma-international.org/ecma-262/10.0/#sec-source-text-module-record-execute-module', - FlattenIntoArray: 'https://ecma-international.org/ecma-262/10.0/#sec-flattenintoarray', - floor: 'https://ecma-international.org/ecma-262/10.0/#eqn-floor', - ForBodyEvaluation: 'https://ecma-international.org/ecma-262/10.0/#sec-forbodyevaluation', - 'ForIn/OfBodyEvaluation': 'https://ecma-international.org/ecma-262/10.0/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset', - 'ForIn/OfHeadEvaluation': 'https://ecma-international.org/ecma-262/10.0/#sec-runtime-semantics-forin-div-ofheadevaluation-tdznames-expr-iterationkind', - FromPropertyDescriptor: 'https://ecma-international.org/ecma-262/10.0/#sec-frompropertydescriptor', - FulfillPromise: 'https://ecma-international.org/ecma-262/10.0/#sec-fulfillpromise', - FunctionAllocate: 'https://ecma-international.org/ecma-262/10.0/#sec-functionallocate', - FunctionCreate: 'https://ecma-international.org/ecma-262/10.0/#sec-functioncreate', - FunctionDeclarationInstantiation: 'https://ecma-international.org/ecma-262/10.0/#sec-functiondeclarationinstantiation', - FunctionInitialize: 'https://ecma-international.org/ecma-262/10.0/#sec-functioninitialize', - GeneratorFunctionCreate: 'https://ecma-international.org/ecma-262/10.0/#sec-generatorfunctioncreate', - GeneratorResume: 'https://ecma-international.org/ecma-262/10.0/#sec-generatorresume', - GeneratorResumeAbrupt: 'https://ecma-international.org/ecma-262/10.0/#sec-generatorresumeabrupt', - GeneratorStart: 'https://ecma-international.org/ecma-262/10.0/#sec-generatorstart', - GeneratorValidate: 'https://ecma-international.org/ecma-262/10.0/#sec-generatorvalidate', - GeneratorYield: 'https://ecma-international.org/ecma-262/10.0/#sec-generatoryield', - Get: 'https://ecma-international.org/ecma-262/10.0/#sec-get-o-p', - GetActiveScriptOrModule: 'https://ecma-international.org/ecma-262/10.0/#sec-getactivescriptormodule', - GetBase: 'https://ecma-international.org/ecma-262/10.0/#sec-getbase', - GetFunctionRealm: 'https://ecma-international.org/ecma-262/10.0/#sec-getfunctionrealm', - GetGeneratorKind: 'https://ecma-international.org/ecma-262/10.0/#sec-getgeneratorkind', - GetGlobalObject: 'https://ecma-international.org/ecma-262/10.0/#sec-getglobalobject', - GetIdentifierReference: 'https://ecma-international.org/ecma-262/10.0/#sec-getidentifierreference', - GetIterator: 'https://ecma-international.org/ecma-262/10.0/#sec-getiterator', - GetMethod: 'https://ecma-international.org/ecma-262/10.0/#sec-getmethod', - GetModifySetValueInBuffer: 'https://ecma-international.org/ecma-262/10.0/#sec-getmodifysetvalueinbuffer', - GetModuleNamespace: 'https://ecma-international.org/ecma-262/10.0/#sec-getmodulenamespace', - GetNewTarget: 'https://ecma-international.org/ecma-262/10.0/#sec-getnewtarget', - GetOwnPropertyKeys: 'https://ecma-international.org/ecma-262/10.0/#sec-getownpropertykeys', - GetPrototypeFromConstructor: 'https://ecma-international.org/ecma-262/10.0/#sec-getprototypefromconstructor', - GetReferencedName: 'https://ecma-international.org/ecma-262/10.0/#sec-getreferencedname', - GetSubstitution: 'https://ecma-international.org/ecma-262/10.0/#sec-getsubstitution', - GetSuperConstructor: 'https://ecma-international.org/ecma-262/10.0/#sec-getsuperconstructor', - GetTemplateObject: 'https://ecma-international.org/ecma-262/10.0/#sec-gettemplateobject', - GetThisEnvironment: 'https://ecma-international.org/ecma-262/10.0/#sec-getthisenvironment', - GetThisValue: 'https://ecma-international.org/ecma-262/10.0/#sec-getthisvalue', - GetV: 'https://ecma-international.org/ecma-262/10.0/#sec-getv', - GetValue: 'https://ecma-international.org/ecma-262/10.0/#sec-getvalue', - GetValueFromBuffer: 'https://ecma-international.org/ecma-262/10.0/#sec-getvaluefrombuffer', - GetViewValue: 'https://ecma-international.org/ecma-262/10.0/#sec-getviewvalue', - GetWaiterList: 'https://ecma-international.org/ecma-262/10.0/#sec-getwaiterlist', - GlobalDeclarationInstantiation: 'https://ecma-international.org/ecma-262/10.0/#sec-globaldeclarationinstantiation', - 'happens-before': 'https://ecma-international.org/ecma-262/10.0/#sec-happens-before', - HasOwnProperty: 'https://ecma-international.org/ecma-262/10.0/#sec-hasownproperty', - HasPrimitiveBase: 'https://ecma-international.org/ecma-262/10.0/#sec-hasprimitivebase', - HasProperty: 'https://ecma-international.org/ecma-262/10.0/#sec-hasproperty', - 'host-synchronizes-with': 'https://ecma-international.org/ecma-262/10.0/#sec-host-synchronizes-with', - HostEnsureCanCompileStrings: 'https://ecma-international.org/ecma-262/10.0/#sec-hostensurecancompilestrings', - HostEventSet: 'https://ecma-international.org/ecma-262/10.0/#sec-hosteventset', - HostPromiseRejectionTracker: 'https://ecma-international.org/ecma-262/10.0/#sec-host-promise-rejection-tracker', - HostReportErrors: 'https://ecma-international.org/ecma-262/10.0/#sec-host-report-errors', - HostResolveImportedModule: 'https://ecma-international.org/ecma-262/10.0/#sec-hostresolveimportedmodule', - HourFromTime: 'https://ecma-international.org/ecma-262/10.0/#eqn-HourFromTime', - IfAbruptRejectPromise: 'https://ecma-international.org/ecma-262/10.0/#sec-ifabruptrejectpromise', - ImportedLocalNames: 'https://ecma-international.org/ecma-262/10.0/#sec-importedlocalnames', - InitializeBoundName: 'https://ecma-international.org/ecma-262/10.0/#sec-initializeboundname', - InitializeEnvironment: 'https://ecma-international.org/ecma-262/10.0/#sec-source-text-module-record-initialize-environment', - InitializeHostDefinedRealm: 'https://ecma-international.org/ecma-262/10.0/#sec-initializehostdefinedrealm', - InitializeReferencedBinding: 'https://ecma-international.org/ecma-262/10.0/#sec-initializereferencedbinding', - InLeapYear: 'https://ecma-international.org/ecma-262/10.0/#eqn-InLeapYear', - InnerModuleEvaluation: 'https://ecma-international.org/ecma-262/10.0/#sec-innermoduleevaluation', - InnerModuleInstantiation: 'https://ecma-international.org/ecma-262/10.0/#sec-innermoduleinstantiation', - InstanceofOperator: 'https://ecma-international.org/ecma-262/10.0/#sec-instanceofoperator', - IntegerIndexedElementGet: 'https://ecma-international.org/ecma-262/10.0/#sec-integerindexedelementget', - IntegerIndexedElementSet: 'https://ecma-international.org/ecma-262/10.0/#sec-integerindexedelementset', - IntegerIndexedObjectCreate: 'https://ecma-international.org/ecma-262/10.0/#sec-integerindexedobjectcreate', - InternalizeJSONProperty: 'https://ecma-international.org/ecma-262/10.0/#sec-internalizejsonproperty', - Invoke: 'https://ecma-international.org/ecma-262/10.0/#sec-invoke', - IsAccessorDescriptor: 'https://ecma-international.org/ecma-262/10.0/#sec-isaccessordescriptor', - IsAnonymousFunctionDefinition: 'https://ecma-international.org/ecma-262/10.0/#sec-isanonymousfunctiondefinition', - IsArray: 'https://ecma-international.org/ecma-262/10.0/#sec-isarray', - IsCallable: 'https://ecma-international.org/ecma-262/10.0/#sec-iscallable', - IsCompatiblePropertyDescriptor: 'https://ecma-international.org/ecma-262/10.0/#sec-iscompatiblepropertydescriptor', - IsConcatSpreadable: 'https://ecma-international.org/ecma-262/10.0/#sec-isconcatspreadable', - IsConstructor: 'https://ecma-international.org/ecma-262/10.0/#sec-isconstructor', - IsDataDescriptor: 'https://ecma-international.org/ecma-262/10.0/#sec-isdatadescriptor', - IsDetachedBuffer: 'https://ecma-international.org/ecma-262/10.0/#sec-isdetachedbuffer', - IsExtensible: 'https://ecma-international.org/ecma-262/10.0/#sec-isextensible-o', - IsGenericDescriptor: 'https://ecma-international.org/ecma-262/10.0/#sec-isgenericdescriptor', - IsInTailPosition: 'https://ecma-international.org/ecma-262/10.0/#sec-isintailposition', - IsInteger: 'https://ecma-international.org/ecma-262/10.0/#sec-isinteger', - IsLabelledFunction: 'https://ecma-international.org/ecma-262/10.0/#sec-islabelledfunction', - IsPromise: 'https://ecma-international.org/ecma-262/10.0/#sec-ispromise', - IsPropertyKey: 'https://ecma-international.org/ecma-262/10.0/#sec-ispropertykey', - IsPropertyReference: 'https://ecma-international.org/ecma-262/10.0/#sec-ispropertyreference', - IsRegExp: 'https://ecma-international.org/ecma-262/10.0/#sec-isregexp', - IsSharedArrayBuffer: 'https://ecma-international.org/ecma-262/10.0/#sec-issharedarraybuffer', - IsStrictReference: 'https://ecma-international.org/ecma-262/10.0/#sec-isstrictreference', - IsStringPrefix: 'https://ecma-international.org/ecma-262/10.0/#sec-isstringprefix', - IsSuperReference: 'https://ecma-international.org/ecma-262/10.0/#sec-issuperreference', - IsUnresolvableReference: 'https://ecma-international.org/ecma-262/10.0/#sec-isunresolvablereference', - IsWordChar: 'https://ecma-international.org/ecma-262/10.0/#sec-runtime-semantics-iswordchar-abstract-operation', - IterableToList: 'https://ecma-international.org/ecma-262/10.0/#sec-iterabletolist', - IteratorClose: 'https://ecma-international.org/ecma-262/10.0/#sec-iteratorclose', - IteratorComplete: 'https://ecma-international.org/ecma-262/10.0/#sec-iteratorcomplete', - IteratorNext: 'https://ecma-international.org/ecma-262/10.0/#sec-iteratornext', - IteratorStep: 'https://ecma-international.org/ecma-262/10.0/#sec-iteratorstep', - IteratorValue: 'https://ecma-international.org/ecma-262/10.0/#sec-iteratorvalue', - LeaveCriticalSection: 'https://ecma-international.org/ecma-262/10.0/#sec-leavecriticalsection', - LocalTime: 'https://ecma-international.org/ecma-262/10.0/#sec-localtime', - LoopContinues: 'https://ecma-international.org/ecma-262/10.0/#sec-loopcontinues', - MakeArgGetter: 'https://ecma-international.org/ecma-262/10.0/#sec-makearggetter', - MakeArgSetter: 'https://ecma-international.org/ecma-262/10.0/#sec-makeargsetter', - MakeClassConstructor: 'https://ecma-international.org/ecma-262/10.0/#sec-makeclassconstructor', - MakeConstructor: 'https://ecma-international.org/ecma-262/10.0/#sec-makeconstructor', - MakeDate: 'https://ecma-international.org/ecma-262/10.0/#sec-makedate', - MakeDay: 'https://ecma-international.org/ecma-262/10.0/#sec-makeday', - MakeMethod: 'https://ecma-international.org/ecma-262/10.0/#sec-makemethod', - MakeSuperPropertyReference: 'https://ecma-international.org/ecma-262/10.0/#sec-makesuperpropertyreference', - MakeTime: 'https://ecma-international.org/ecma-262/10.0/#sec-maketime', - max: 'https://ecma-international.org/ecma-262/10.0/#eqn-max', - 'memory-order': 'https://ecma-international.org/ecma-262/10.0/#sec-memory-order', - min: 'https://ecma-international.org/ecma-262/10.0/#eqn-min', - MinFromTime: 'https://ecma-international.org/ecma-262/10.0/#eqn-MinFromTime', - ModuleNamespaceCreate: 'https://ecma-international.org/ecma-262/10.0/#sec-modulenamespacecreate', - modulo: 'https://ecma-international.org/ecma-262/10.0/#eqn-modulo', - MonthFromTime: 'https://ecma-international.org/ecma-262/10.0/#eqn-MonthFromTime', - msFromTime: 'https://ecma-international.org/ecma-262/10.0/#eqn-msFromTime', - NewDeclarativeEnvironment: 'https://ecma-international.org/ecma-262/10.0/#sec-newdeclarativeenvironment', - NewFunctionEnvironment: 'https://ecma-international.org/ecma-262/10.0/#sec-newfunctionenvironment', - NewGlobalEnvironment: 'https://ecma-international.org/ecma-262/10.0/#sec-newglobalenvironment', - NewModuleEnvironment: 'https://ecma-international.org/ecma-262/10.0/#sec-newmoduleenvironment', - NewObjectEnvironment: 'https://ecma-international.org/ecma-262/10.0/#sec-newobjectenvironment', - NewPromiseCapability: 'https://ecma-international.org/ecma-262/10.0/#sec-newpromisecapability', - NormalCompletion: 'https://ecma-international.org/ecma-262/10.0/#sec-normalcompletion', - NotifyWaiter: 'https://ecma-international.org/ecma-262/10.0/#sec-notifywaiter', - NumberToRawBytes: 'https://ecma-international.org/ecma-262/10.0/#sec-numbertorawbytes', - NumberToString: 'https://ecma-international.org/ecma-262/10.0/#sec-tostring-applied-to-the-number-type', - ObjectCreate: 'https://ecma-international.org/ecma-262/10.0/#sec-objectcreate', - ObjectDefineProperties: 'https://ecma-international.org/ecma-262/10.0/#sec-objectdefineproperties', - OrdinaryCallBindThis: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinarycallbindthis', - OrdinaryCallEvaluateBody: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinarycallevaluatebody', - OrdinaryCreateFromConstructor: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinarycreatefromconstructor', - OrdinaryDefineOwnProperty: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinarydefineownproperty', - OrdinaryDelete: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinarydelete', - OrdinaryGet: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinaryget', - OrdinaryGetOwnProperty: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinarygetownproperty', - OrdinaryGetPrototypeOf: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinarygetprototypeof', - OrdinaryHasInstance: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinaryhasinstance', - OrdinaryHasProperty: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinaryhasproperty', - OrdinaryIsExtensible: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinaryisextensible', - OrdinaryOwnPropertyKeys: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinaryownpropertykeys', - OrdinaryPreventExtensions: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinarypreventextensions', - OrdinarySet: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinaryset', - OrdinarySetPrototypeOf: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinarysetprototypeof', - OrdinarySetWithOwnDescriptor: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinarysetwithowndescriptor', - OrdinaryToPrimitive: 'https://ecma-international.org/ecma-262/10.0/#sec-ordinarytoprimitive', - ParseModule: 'https://ecma-international.org/ecma-262/10.0/#sec-parsemodule', - ParseScript: 'https://ecma-international.org/ecma-262/10.0/#sec-parse-script', - PerformEval: 'https://ecma-international.org/ecma-262/10.0/#sec-performeval', - PerformPromiseAll: 'https://ecma-international.org/ecma-262/10.0/#sec-performpromiseall', - PerformPromiseRace: 'https://ecma-international.org/ecma-262/10.0/#sec-performpromiserace', - PerformPromiseThen: 'https://ecma-international.org/ecma-262/10.0/#sec-performpromisethen', - PrepareForOrdinaryCall: 'https://ecma-international.org/ecma-262/10.0/#sec-prepareforordinarycall', - PrepareForTailCall: 'https://ecma-international.org/ecma-262/10.0/#sec-preparefortailcall', - PromiseReactionJob: 'https://ecma-international.org/ecma-262/10.0/#sec-promisereactionjob', - PromiseResolve: 'https://ecma-international.org/ecma-262/10.0/#sec-promise-resolve', - PromiseResolveThenableJob: 'https://ecma-international.org/ecma-262/10.0/#sec-promiseresolvethenablejob', - ProxyCreate: 'https://ecma-international.org/ecma-262/10.0/#sec-proxycreate', - PutValue: 'https://ecma-international.org/ecma-262/10.0/#sec-putvalue', - QuoteJSONString: 'https://ecma-international.org/ecma-262/10.0/#sec-quotejsonstring', - RawBytesToNumber: 'https://ecma-international.org/ecma-262/10.0/#sec-rawbytestonumber', - 'reads-bytes-from': 'https://ecma-international.org/ecma-262/10.0/#sec-reads-bytes-from', - 'reads-from': 'https://ecma-international.org/ecma-262/10.0/#sec-reads-from', - RegExpAlloc: 'https://ecma-international.org/ecma-262/10.0/#sec-regexpalloc', - RegExpBuiltinExec: 'https://ecma-international.org/ecma-262/10.0/#sec-regexpbuiltinexec', - RegExpCreate: 'https://ecma-international.org/ecma-262/10.0/#sec-regexpcreate', - RegExpExec: 'https://ecma-international.org/ecma-262/10.0/#sec-regexpexec', - RegExpInitialize: 'https://ecma-international.org/ecma-262/10.0/#sec-regexpinitialize', - RejectPromise: 'https://ecma-international.org/ecma-262/10.0/#sec-rejectpromise', - RemoveWaiter: 'https://ecma-international.org/ecma-262/10.0/#sec-removewaiter', - RemoveWaiters: 'https://ecma-international.org/ecma-262/10.0/#sec-removewaiters', - RepeatMatcher: 'https://ecma-international.org/ecma-262/10.0/#sec-runtime-semantics-repeatmatcher-abstract-operation', - RequireObjectCoercible: 'https://ecma-international.org/ecma-262/10.0/#sec-requireobjectcoercible', - ResolveBinding: 'https://ecma-international.org/ecma-262/10.0/#sec-resolvebinding', - ResolveThisBinding: 'https://ecma-international.org/ecma-262/10.0/#sec-resolvethisbinding', - ReturnIfAbrupt: 'https://ecma-international.org/ecma-262/10.0/#sec-returnifabrupt', - RunJobs: 'https://ecma-international.org/ecma-262/10.0/#sec-runjobs', - SameValue: 'https://ecma-international.org/ecma-262/10.0/#sec-samevalue', - SameValueNonNumber: 'https://ecma-international.org/ecma-262/10.0/#sec-samevaluenonnumber', - SameValueZero: 'https://ecma-international.org/ecma-262/10.0/#sec-samevaluezero', - ScriptEvaluation: 'https://ecma-international.org/ecma-262/10.0/#sec-runtime-semantics-scriptevaluation', - ScriptEvaluationJob: 'https://ecma-international.org/ecma-262/10.0/#sec-scriptevaluationjob', - SecFromTime: 'https://ecma-international.org/ecma-262/10.0/#eqn-SecFromTime', - SerializeJSONArray: 'https://ecma-international.org/ecma-262/10.0/#sec-serializejsonarray', - SerializeJSONObject: 'https://ecma-international.org/ecma-262/10.0/#sec-serializejsonobject', - SerializeJSONProperty: 'https://ecma-international.org/ecma-262/10.0/#sec-serializejsonproperty', - Set: 'https://ecma-international.org/ecma-262/10.0/#sec-set-o-p-v-throw', - SetDefaultGlobalBindings: 'https://ecma-international.org/ecma-262/10.0/#sec-setdefaultglobalbindings', - SetFunctionLength: 'https://ecma-international.org/ecma-262/10.0/#sec-setfunctionlength', - SetFunctionName: 'https://ecma-international.org/ecma-262/10.0/#sec-setfunctionname', - SetImmutablePrototype: 'https://ecma-international.org/ecma-262/10.0/#sec-set-immutable-prototype', - SetIntegrityLevel: 'https://ecma-international.org/ecma-262/10.0/#sec-setintegritylevel', - SetRealmGlobalObject: 'https://ecma-international.org/ecma-262/10.0/#sec-setrealmglobalobject', - SetValueInBuffer: 'https://ecma-international.org/ecma-262/10.0/#sec-setvalueinbuffer', - SetViewValue: 'https://ecma-international.org/ecma-262/10.0/#sec-setviewvalue', - SharedDataBlockEventSet: 'https://ecma-international.org/ecma-262/10.0/#sec-sharedatablockeventset', - SortCompare: 'https://ecma-international.org/ecma-262/10.0/#sec-sortcompare', - SpeciesConstructor: 'https://ecma-international.org/ecma-262/10.0/#sec-speciesconstructor', - SplitMatch: 'https://ecma-international.org/ecma-262/10.0/#sec-splitmatch', - 'Strict Equality Comparison': 'https://ecma-international.org/ecma-262/10.0/#sec-strict-equality-comparison', - StringCreate: 'https://ecma-international.org/ecma-262/10.0/#sec-stringcreate', - StringGetOwnProperty: 'https://ecma-international.org/ecma-262/10.0/#sec-stringgetownproperty', - Suspend: 'https://ecma-international.org/ecma-262/10.0/#sec-suspend', - SymbolDescriptiveString: 'https://ecma-international.org/ecma-262/10.0/#sec-symboldescriptivestring', - SynchronizeEventSet: 'https://ecma-international.org/ecma-262/10.0/#sec-synchronizeeventset', - 'synchronizes-with': 'https://ecma-international.org/ecma-262/10.0/#sec-synchronizes-with', - TestIntegrityLevel: 'https://ecma-international.org/ecma-262/10.0/#sec-testintegritylevel', - thisBooleanValue: 'https://ecma-international.org/ecma-262/10.0/#sec-thisbooleanvalue', - thisNumberValue: 'https://ecma-international.org/ecma-262/10.0/#sec-thisnumbervalue', - thisStringValue: 'https://ecma-international.org/ecma-262/10.0/#sec-thisstringvalue', - thisSymbolValue: 'https://ecma-international.org/ecma-262/10.0/#sec-thissymbolvalue', - thisTimeValue: 'https://ecma-international.org/ecma-262/10.0/#sec-thistimevalue', - ThrowCompletion: 'https://ecma-international.org/ecma-262/10.0/#sec-throwcompletion', - TimeClip: 'https://ecma-international.org/ecma-262/10.0/#sec-timeclip', - TimeFromYear: 'https://ecma-international.org/ecma-262/10.0/#eqn-TimeFromYear', - TimeString: 'https://ecma-international.org/ecma-262/10.0/#sec-timestring', - TimeWithinDay: 'https://ecma-international.org/ecma-262/10.0/#eqn-TimeWithinDay', - TimeZoneString: 'https://ecma-international.org/ecma-262/10.0/#sec-timezoneestring', - ToBoolean: 'https://ecma-international.org/ecma-262/10.0/#sec-toboolean', - ToDateString: 'https://ecma-international.org/ecma-262/10.0/#sec-todatestring', - ToIndex: 'https://ecma-international.org/ecma-262/10.0/#sec-toindex', - ToInt16: 'https://ecma-international.org/ecma-262/10.0/#sec-toint16', - ToInt32: 'https://ecma-international.org/ecma-262/10.0/#sec-toint32', - ToInt8: 'https://ecma-international.org/ecma-262/10.0/#sec-toint8', - ToInteger: 'https://ecma-international.org/ecma-262/10.0/#sec-tointeger', - ToLength: 'https://ecma-international.org/ecma-262/10.0/#sec-tolength', - ToNumber: 'https://ecma-international.org/ecma-262/10.0/#sec-tonumber', - ToObject: 'https://ecma-international.org/ecma-262/10.0/#sec-toobject', - TopLevelModuleEvaluationJob: 'https://ecma-international.org/ecma-262/10.0/#sec-toplevelmoduleevaluationjob', - ToPrimitive: 'https://ecma-international.org/ecma-262/10.0/#sec-toprimitive', - ToPropertyDescriptor: 'https://ecma-international.org/ecma-262/10.0/#sec-topropertydescriptor', - ToPropertyKey: 'https://ecma-international.org/ecma-262/10.0/#sec-topropertykey', - ToString: 'https://ecma-international.org/ecma-262/10.0/#sec-tostring', - ToUint16: 'https://ecma-international.org/ecma-262/10.0/#sec-touint16', - ToUint32: 'https://ecma-international.org/ecma-262/10.0/#sec-touint32', - ToUint8: 'https://ecma-international.org/ecma-262/10.0/#sec-touint8', - ToUint8Clamp: 'https://ecma-international.org/ecma-262/10.0/#sec-touint8clamp', - TriggerPromiseReactions: 'https://ecma-international.org/ecma-262/10.0/#sec-triggerpromisereactions', - TrimString: 'https://ecma-international.org/ecma-262/10.0/#sec-trimstring', - Type: 'https://ecma-international.org/ecma-262/10.0/#sec-ecmascript-data-types-and-values', - TypedArrayCreate: 'https://ecma-international.org/ecma-262/10.0/#typedarray-create', - TypedArraySpeciesCreate: 'https://ecma-international.org/ecma-262/10.0/#typedarray-species-create', - UnicodeEscape: 'https://ecma-international.org/ecma-262/10.0/#sec-unicodeescape', - UnicodeMatchProperty: 'https://ecma-international.org/ecma-262/10.0/#sec-runtime-semantics-unicodematchproperty-p', - UnicodeMatchPropertyValue: 'https://ecma-international.org/ecma-262/10.0/#sec-runtime-semantics-unicodematchpropertyvalue-p-v', - UpdateEmpty: 'https://ecma-international.org/ecma-262/10.0/#sec-updateempty', - UTC: 'https://ecma-international.org/ecma-262/10.0/#sec-utc-t', - UTF16Decode: 'https://ecma-international.org/ecma-262/10.0/#sec-utf16decode', - UTF16Encoding: 'https://ecma-international.org/ecma-262/10.0/#sec-utf16encoding', - ValidateAndApplyPropertyDescriptor: 'https://ecma-international.org/ecma-262/10.0/#sec-validateandapplypropertydescriptor', - ValidateAtomicAccess: 'https://ecma-international.org/ecma-262/10.0/#sec-validateatomicaccess', - ValidateSharedIntegerTypedArray: 'https://ecma-international.org/ecma-262/10.0/#sec-validatesharedintegertypedarray', - ValidateTypedArray: 'https://ecma-international.org/ecma-262/10.0/#sec-validatetypedarray', - ValueOfReadEvent: 'https://ecma-international.org/ecma-262/10.0/#sec-valueofreadevent', - WeekDay: 'https://ecma-international.org/ecma-262/10.0/#sec-week-day', - WordCharacters: 'https://ecma-international.org/ecma-262/10.0/#sec-runtime-semantics-wordcharacters-abstract-operation', - YearFromTime: 'https://ecma-international.org/ecma-262/10.0/#eqn-YearFromTime' -}; diff --git a/node_modules/es-abstract/package.json b/node_modules/es-abstract/package.json deleted file mode 100644 index 3b6bc70..0000000 --- a/node_modules/es-abstract/package.json +++ /dev/null @@ -1,144 +0,0 @@ -{ - "_from": "es-abstract@^1.17.5", - "_id": "es-abstract@1.17.5", - "_inBundle": false, - "_integrity": "sha512-BR9auzDbySxOcfog0tLECW8l28eRGpDpU3Dm3Hp4q/N+VtLTmyj4EUN088XZWQDW/hzj6sYRDXeOFsaAODKvpg==", - "_location": "/es-abstract", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "es-abstract@^1.17.5", - "name": "es-abstract", - "escapedName": "es-abstract", - "rawSpec": "^1.17.5", - "saveSpec": null, - "fetchSpec": "^1.17.5" - }, - "_requiredBy": [ - "/is-typed-array", - "/object-is", - "/string.prototype.trimend", - "/string.prototype.trimleft", - "/string.prototype.trimright", - "/string.prototype.trimstart", - "/which-typed-array" - ], - "_resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.5.tgz", - "_shasum": "d8c9d1d66c8981fb9200e2251d799eee92774ae9", - "_spec": "es-abstract@^1.17.5", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/object-is", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - }, - "bugs": { - "url": "https://github.com/ljharb/es-abstract/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - } - ], - "dependencies": { - "es-to-primitive": "^1.2.1", - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.1", - "is-callable": "^1.1.5", - "is-regex": "^1.0.5", - "object-inspect": "^1.7.0", - "object-keys": "^1.1.1", - "object.assign": "^4.1.0", - "string.prototype.trimleft": "^2.1.1", - "string.prototype.trimright": "^2.1.1" - }, - "deprecated": false, - "description": "ECMAScript spec abstract operations.", - "devDependencies": { - "@ljharb/eslint-config": "^16.0.0", - "array.prototype.indexof": "^1.0.0", - "cheerio": "^1.0.0-rc.3", - "diff": "^4.0.2", - "eclint": "^2.8.1", - "eslint": "^6.8.0", - "foreach": "^2.0.5", - "functions-have-names": "^1.2.1", - "has-strict-mode": "^1.0.0", - "in-publish": "^2.0.0", - "make-arrow-function": "^1.2.0", - "nyc": "^10.3.2", - "object-is": "^1.0.2", - "object.fromentries": "^2.0.2", - "safe-publish-latest": "^1.1.4", - "tape": "^5.0.0-next.5" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "greenkeeper": { - "//": "nyc is ignored because it requires node 4+, and we support older than that", - "ignore": [ - "nyc" - ] - }, - "homepage": "https://github.com/ljharb/es-abstract#readme", - "keywords": [ - "ECMAScript", - "ES", - "abstract", - "operation", - "abstract operation", - "JavaScript", - "ES5", - "ES6", - "ES7" - ], - "license": "MIT", - "main": "index.js", - "name": "es-abstract", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/es-abstract.git" - }, - "scripts": { - "coverage": "nyc npm run tests-only >/dev/null", - "eccheck": "eclint check *.js **/*.js > /dev/null", - "lint": "eslint .", - "postcoverage": "nyc report", - "postspackle": "git ls-files | xargs git check-attr spackled | grep -v 'unspecified$' | cut -d: -f1 | xargs git add", - "posttest": "npx aud --production", - "prepublish": "safe-publish-latest && (not-in-publish || npm run spackle)", - "prespackle": "git ls-files | xargs git check-attr spackled | grep -v 'unspecified$' | cut -d: -f1 | xargs rm || true", - "pretest": "npm run lint", - "spackle": "node operations/spackle 1", - "test": "npm run tests-only", - "tests-only": "node test" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.17.5" -} diff --git a/node_modules/es-abstract/test/GetIntrinsic.js b/node_modules/es-abstract/test/GetIntrinsic.js deleted file mode 100644 index a3e69a7..0000000 --- a/node_modules/es-abstract/test/GetIntrinsic.js +++ /dev/null @@ -1,94 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var test = require('tape'); -var forEach = require('foreach'); -var debug = require('object-inspect'); - -var v = require('./helpers/values'); - -test('export', function (t) { - t.equal(typeof GetIntrinsic, 'function', 'it is a function'); - t.equal(GetIntrinsic.length, 2, 'function has length of 2'); - - t.end(); -}); - -test('throws', function (t) { - t['throws']( - function () { GetIntrinsic('not an intrinsic'); }, - SyntaxError, - 'nonexistent intrinsic throws a syntax error' - ); - - t['throws']( - function () { GetIntrinsic(''); }, - TypeError, - 'empty string intrinsic throws a type error' - ); - - t['throws']( - function () { GetIntrinsic('.'); }, - SyntaxError, - '"just a dot" intrinsic throws a syntax error' - ); - - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { GetIntrinsic(nonString); }, - TypeError, - debug(nonString) + ' is not a String' - ); - }); - - forEach(v.nonBooleans, function (nonBoolean) { - t['throws']( - function () { GetIntrinsic('%', nonBoolean); }, - TypeError, - debug(nonBoolean) + ' is not a Boolean' - ); - }); - - forEach([ - 'toString', - 'propertyIsEnumerable', - 'hasOwnProperty' - ], function (objectProtoMember) { - t['throws']( - function () { GetIntrinsic(objectProtoMember); }, - SyntaxError, - debug(objectProtoMember) + ' is not an intrinsic' - ); - }); - - t.end(); -}); - -test('base intrinsics', function (t) { - t.equal(GetIntrinsic('%Object%'), Object, '%Object% yields Object'); - t.equal(GetIntrinsic('Object'), Object, 'Object yields Object'); - t.equal(GetIntrinsic('%Array%'), Array, '%Array% yields Array'); - t.equal(GetIntrinsic('Array'), Array, 'Array yields Array'); - - t.end(); -}); - -test('dotted paths', function (t) { - t.equal(GetIntrinsic('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% yields Object.prototype.toString'); - t.equal(GetIntrinsic('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString yields Object.prototype.toString'); - t.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push, '%Array.prototype.push% yields Array.prototype.push'); - t.equal(GetIntrinsic('Array.prototype.push'), Array.prototype.push, 'Array.prototype.push yields Array.prototype.push'); - - t.end(); -}); - -test('accessors', { skip: !Object.getOwnPropertyDescriptor || typeof Map !== 'function' }, function (t) { - var actual = Object.getOwnPropertyDescriptor(Map.prototype, 'size'); - t.ok(actual, 'Map.prototype.size has a descriptor'); - t.equal(typeof actual.get, 'function', 'Map.prototype.size has a getter function'); - t.equal(GetIntrinsic('%Map.prototype.size%'), actual.get, '%Map.prototype.size% yields the getter for it'); - t.equal(GetIntrinsic('Map.prototype.size'), actual.get, 'Map.prototype.size yields the getter for it'); - - t.end(); -}); diff --git a/node_modules/es-abstract/test/diffOps.js b/node_modules/es-abstract/test/diffOps.js deleted file mode 100644 index 602098d..0000000 --- a/node_modules/es-abstract/test/diffOps.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var keys = require('object-keys'); -var forEach = require('foreach'); -var indexOf = require('array.prototype.indexof'); - -module.exports = function diffOperations(actual, expected, expectedMissing) { - var actualKeys = keys(actual); - var expectedKeys = keys(expected); - - var extra = []; - var missing = []; - forEach(actualKeys, function (op) { - if (!(op in expected)) { - extra.push(op); - } else if (indexOf(expectedMissing, op) !== -1) { - extra.push(op); - } - }); - forEach(expectedKeys, function (op) { - if (typeof actual[op] !== 'function' && indexOf(expectedMissing, op) === -1) { - missing.push(op); - } - }); - - return { missing: missing, extra: extra }; -}; diff --git a/node_modules/es-abstract/test/es2015.js b/node_modules/es-abstract/test/es2015.js deleted file mode 100644 index 6db4d6d..0000000 --- a/node_modules/es-abstract/test/es2015.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var ES = require('../').ES2015; - -var ops = require('../operations/2015'); - -var expectedMissing = ['Construct', 'CreateArrayFromList', 'CreateListIterator', 'NormalCompletion', 'RegExpBuiltinExec']; - -require('./tests').es2015(ES, ops, expectedMissing); - -require('./helpers/runManifestTest')(require('tape'), ES, 2015); diff --git a/node_modules/es-abstract/test/es2016.js b/node_modules/es-abstract/test/es2016.js deleted file mode 100644 index 27115f7..0000000 --- a/node_modules/es-abstract/test/es2016.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var ES = require('../').ES2016; - -var ops = require('../operations/2016'); - -var expectedMissing = ['AddRestrictedFunctionProperties', 'AllocateArrayBuffer', 'AllocateTypedArray', 'AllocateTypedArrayBuffer', 'BlockDeclarationInstantiation', 'BoundFunctionCreate', 'Canonicalize', 'CharacterRange', 'CharacterRangeOrUnion', 'CharacterSetMatcher', 'CloneArrayBuffer', 'Completion', 'Construct', 'CopyDataBlockBytes', 'CreateArrayFromList', 'CreateArrayIterator', 'CreateBuiltinFunction', 'CreateByteDataBlock', 'CreateDynamicFunction', 'CreateIntrinsics', 'CreateListIterator', 'CreateMapIterator', 'CreateMappedArgumentsObject', 'CreatePerIterationEnvironment', 'CreateRealm', 'CreateResolvingFunctions', 'CreateSetIterator', 'CreateStringIterator', 'CreateUnmappedArgumentsObject', 'Decode', 'DetachArrayBuffer', 'Encode', 'EnqueueJob', 'EnumerateObjectProperties', 'EscapeRegExpPattern', 'EvalDeclarationInstantiation', 'EvaluateCall', 'EvaluateDirectCall', 'EvaluateNew', 'ForBodyEvaluation', 'ForIn/OfBodyEvaluation', 'ForIn/OfHeadEvaluation', 'FulfillPromise', 'FunctionAllocate', 'FunctionCreate', 'FunctionDeclarationInstantiation', 'FunctionInitialize', 'GeneratorFunctionCreate', 'GeneratorResume', 'GeneratorResumeAbrupt', 'GeneratorStart', 'GeneratorValidate', 'GeneratorYield', 'GetActiveScriptOrModule', 'GetFunctionRealm', 'GetGlobalObject', 'GetIdentifierReference', 'GetModuleNamespace', 'GetNewTarget', 'GetSuperConstructor', 'GetTemplateObject', 'GetThisEnvironment', 'GetThisValue', 'GetValue', 'GetValueFromBuffer', 'GetViewValue', 'GlobalDeclarationInstantiation', 'HostPromiseRejectionTracker', 'HostReportErrors', 'HostResolveImportedModule', 'IfAbruptRejectPromise', 'ImportedLocalNames', 'InitializeBoundName', 'InitializeHostDefinedRealm', 'InitializeReferencedBinding', 'IntegerIndexedElementGet', 'IntegerIndexedElementSet', 'IntegerIndexedObjectCreate', 'InternalizeJSONProperty', 'IsAnonymousFunctionDefinition', 'IsCompatiblePropertyDescriptor', 'IsDetachedBuffer', 'IsInTailPosition', 'IsLabelledFunction', 'IsWordChar', 'LocalTime', 'LoopContinues', 'MakeArgGetter', 'MakeArgSetter', 'MakeClassConstructor', 'MakeConstructor', 'MakeMethod', 'MakeSuperPropertyReference', 'ModuleNamespaceCreate', 'NewDeclarativeEnvironment', 'NewFunctionEnvironment', 'NewGlobalEnvironment', 'NewModuleEnvironment', 'NewObjectEnvironment', 'NewPromiseCapability', 'NextJob', 'NormalCompletion', 'ObjectDefineProperties', 'OrdinaryCallBindThis', 'OrdinaryCallEvaluateBody', 'OrdinaryCreateFromConstructor', 'OrdinaryDelete', 'OrdinaryGet', 'OrdinaryIsExtensible', 'OrdinaryOwnPropertyKeys', 'OrdinaryPreventExtensions', 'OrdinarySet', 'ParseModule', 'ParseScript', 'PerformEval', 'PerformPromiseAll', 'PerformPromiseRace', 'PerformPromiseThen', 'PrepareForOrdinaryCall', 'PrepareForTailCall', 'PromiseReactionJob', 'PromiseResolveThenableJob', 'ProxyCreate', 'PutValue', 'QuoteJSONString', 'RegExpAlloc', 'RegExpBuiltinExec', 'RegExpCreate', 'RegExpInitialize', 'RejectPromise', 'RepeatMatcher', 'ResolveBinding', 'ResolveThisBinding', 'ReturnIfAbrupt', 'ScriptEvaluation', 'ScriptEvaluationJob', 'SerializeJSONArray', 'SerializeJSONObject', 'SerializeJSONProperty', 'SetDefaultGlobalBindings', 'SetRealmGlobalObject', 'SetValueInBuffer', 'SetViewValue', 'SortCompare', 'SplitMatch', 'StringCreate', 'ToString Applied to the Number Type', 'TopLevelModuleEvaluationJob', 'TriggerPromiseReactions', 'TypedArrayCreate', 'TypedArraySpeciesCreate', 'UTC', 'UTF16Decode', 'UTF16Encoding', 'UpdateEmpty', 'ValidateTypedArray', 'abs', 'floor', 'max', 'min']; - -require('./tests').es2016(ES, ops, expectedMissing); - -require('./helpers/runManifestTest')(require('tape'), ES, 2016); diff --git a/node_modules/es-abstract/test/es2017.js b/node_modules/es-abstract/test/es2017.js deleted file mode 100644 index cabff70..0000000 --- a/node_modules/es-abstract/test/es2017.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var ES = require('../').ES2017; - -var ops = require('../operations/2017'); - -var expectedMissing = ['AddRestrictedFunctionProperties', 'AddWaiter', 'AgentCanSuspend', 'AgentSignifier', 'AllocateArrayBuffer', 'AllocateSharedArrayBuffer', 'AllocateTypedArray', 'AllocateTypedArrayBuffer', 'AsyncFunctionAwait', 'AsyncFunctionCreate', 'AsyncFunctionStart', 'AtomicLoad', 'AtomicReadModifyWrite', 'BlockDeclarationInstantiation', 'BoundFunctionCreate', 'Canonicalize', 'CharacterRange', 'CharacterRangeOrUnion', 'CharacterSetMatcher', 'CloneArrayBuffer', 'Completion', 'ComposeWriteEventBytes', 'Construct', 'CopyDataBlockBytes', 'CreateArrayFromList', 'CreateArrayIterator', 'CreateBuiltinFunction', 'CreateByteDataBlock', 'CreateDynamicFunction', 'CreateIntrinsics', 'CreateListIterator', 'CreateMapIterator', 'CreateMappedArgumentsObject', 'CreatePerIterationEnvironment', 'CreateRealm', 'CreateResolvingFunctions', 'CreateSetIterator', 'CreateSharedByteDataBlock', 'CreateStringIterator', 'CreateUnmappedArgumentsObject', 'Decode', 'DetachArrayBuffer', 'Encode', 'EnqueueJob', 'EnterCriticalSection', 'EnumerateObjectProperties', 'EscapeRegExpPattern', 'EvalDeclarationInstantiation', 'EvaluateCall', 'EvaluateDirectCall', 'EvaluateNew', 'EventSet', 'ForBodyEvaluation', 'ForIn/OfBodyEvaluation', 'ForIn/OfHeadEvaluation', 'FulfillPromise', 'FunctionAllocate', 'FunctionCreate', 'FunctionDeclarationInstantiation', 'FunctionInitialize', 'GeneratorFunctionCreate', 'GeneratorResume', 'GeneratorResumeAbrupt', 'GeneratorStart', 'GeneratorValidate', 'GeneratorYield', 'GetActiveScriptOrModule', 'GetBase', 'GetFunctionRealm', 'GetGlobalObject', 'GetIdentifierReference', 'GetModifySetValueInBuffer', 'GetModuleNamespace', 'GetNewTarget', 'GetReferencedName', 'GetSuperConstructor', 'GetTemplateObject', 'GetThisEnvironment', 'GetThisValue', 'GetValue', 'GetValueFromBuffer', 'GetViewValue', 'GetWaiterList', 'GlobalDeclarationInstantiation', 'HasPrimitiveBase', 'HostEnsureCanCompileStrings', 'HostEventSet', 'HostPromiseRejectionTracker', 'HostReportErrors', 'HostResolveImportedModule', 'IfAbruptRejectPromise', 'ImportedLocalNames', 'InitializeBoundName', 'InitializeHostDefinedRealm', 'InitializeReferencedBinding', 'IntegerIndexedElementGet', 'IntegerIndexedElementSet', 'IntegerIndexedObjectCreate', 'InternalizeJSONProperty', 'IsAnonymousFunctionDefinition', 'IsCompatiblePropertyDescriptor', 'IsDetachedBuffer', 'IsInTailPosition', 'IsLabelledFunction', 'IsPropertyReference', 'IsSharedArrayBuffer', 'IsStrictReference', 'IsSuperReference', 'IsUnresolvableReference', 'IsWordChar', 'LeaveCriticalSection', 'LocalTime', 'LoopContinues', 'MakeArgGetter', 'MakeArgSetter', 'MakeClassConstructor', 'MakeConstructor', 'MakeMethod', 'MakeSuperPropertyReference', 'ModuleNamespaceCreate', 'NewDeclarativeEnvironment', 'NewFunctionEnvironment', 'NewGlobalEnvironment', 'NewModuleEnvironment', 'NewObjectEnvironment', 'NewPromiseCapability', 'NormalCompletion', 'NumberToRawBytes', 'ObjectDefineProperties', 'OrdinaryCallBindThis', 'OrdinaryCallEvaluateBody', 'OrdinaryCreateFromConstructor', 'OrdinaryDelete', 'OrdinaryGet', 'OrdinaryIsExtensible', 'OrdinaryOwnPropertyKeys', 'OrdinaryPreventExtensions', 'OrdinarySet', 'OrdinaryToPrimitive', 'ParseModule', 'ParseScript', 'PerformEval', 'PerformPromiseAll', 'PerformPromiseRace', 'PerformPromiseThen', 'PrepareForOrdinaryCall', 'PrepareForTailCall', 'PromiseReactionJob', 'PromiseResolveThenableJob', 'ProxyCreate', 'PutValue', 'QuoteJSONString', 'RawBytesToNumber', 'RegExpAlloc', 'RegExpBuiltinExec', 'RegExpCreate', 'RegExpInitialize', 'RejectPromise', 'RemoveWaiter', 'RemoveWaiters', 'RepeatMatcher', 'ResolveBinding', 'ResolveThisBinding', 'ReturnIfAbrupt', 'RunJobs', 'ScriptEvaluation', 'ScriptEvaluationJob', 'SerializeJSONArray', 'SerializeJSONObject', 'SerializeJSONProperty', 'SetDefaultGlobalBindings', 'SetImmutablePrototype', 'SetRealmGlobalObject', 'SetValueInBuffer', 'SetViewValue', 'SharedDataBlockEventSet', 'SortCompare', 'SplitMatch', 'StringCreate', 'StringGetOwnProperty', 'Suspend', 'ToString Applied to the Number Type', 'TopLevelModuleEvaluationJob', 'TriggerPromiseReactions', 'TypedArrayCreate', 'TypedArraySpeciesCreate', 'UTC', 'UTF16Decode', 'UTF16Encoding', 'UpdateEmpty', 'ValidateAtomicAccess', 'ValidateSharedIntegerTypedArray', 'ValidateTypedArray', 'ValueOfReadEvent', 'WakeWaiter', 'WordCharacters', 'abs', 'agent-order', 'floor', 'happens-before', 'host-synchronizes-with', 'max', 'memory-order', 'min', 'reads-bytes-from', 'reads-from', 'synchronizes-with']; - -require('./tests').es2017(ES, ops, expectedMissing); - -require('./helpers/runManifestTest')(require('tape'), ES, 2017); diff --git a/node_modules/es-abstract/test/es2018.js b/node_modules/es-abstract/test/es2018.js deleted file mode 100644 index df18627..0000000 --- a/node_modules/es-abstract/test/es2018.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var ES = require('../').ES2018; - -var ops = require('../operations/2018'); - -var expectedMissing = ['abs', 'AddRestrictedFunctionProperties', 'AddWaiter', 'agent-order', 'AgentCanSuspend', 'AgentSignifier', 'AllocateArrayBuffer', 'AllocateSharedArrayBuffer', 'AllocateTypedArray', 'AllocateTypedArrayBuffer', 'AsyncFunctionStart', 'AsyncGeneratorEnqueue', 'AsyncGeneratorReject', 'AsyncGeneratorResolve', 'AsyncGeneratorResumeNext', 'AsyncGeneratorStart', 'AsyncGeneratorYield', 'AtomicLoad', 'AtomicReadModifyWrite', 'Await', 'BlockDeclarationInstantiation', 'BoundFunctionCreate', 'Canonicalize', 'CaseClauseIsSelected', 'CharacterRange', 'CharacterRangeOrUnion', 'CharacterSetMatcher', 'CloneArrayBuffer', 'Completion', 'ComposeWriteEventBytes', 'CopyDataBlockBytes', 'CreateArrayIterator', 'CreateAsyncFromSyncIterator', 'CreateBuiltinFunction', 'CreateByteDataBlock', 'CreateDynamicFunction', 'CreateIntrinsics', 'CreateMapIterator', 'CreateMappedArgumentsObject', 'CreatePerIterationEnvironment', 'CreateRealm', 'CreateResolvingFunctions', 'CreateSetIterator', 'CreateSharedByteDataBlock', 'CreateStringIterator', 'CreateUnmappedArgumentsObject', 'Decode', 'DetachArrayBuffer', 'Encode', 'EnqueueJob', 'EnterCriticalSection', 'EnumerateObjectProperties', 'EscapeRegExpPattern', 'EvalDeclarationInstantiation', 'EvaluateCall', 'EvaluateNew', 'EventSet', 'floor', 'ForBodyEvaluation', 'ForIn/OfBodyEvaluation', 'ForIn/OfHeadEvaluation', 'FulfillPromise', 'FunctionAllocate', 'FunctionCreate', 'FunctionDeclarationInstantiation', 'FunctionInitialize', 'GeneratorFunctionCreate', 'GeneratorResume', 'GeneratorResumeAbrupt', 'GeneratorStart', 'GeneratorValidate', 'GeneratorYield', 'GetActiveScriptOrModule', 'GetBase', 'GetFunctionRealm', 'GetGeneratorKind', 'GetGlobalObject', 'GetIdentifierReference', 'GetModifySetValueInBuffer', 'GetModuleNamespace', 'GetNewTarget', 'GetReferencedName', 'GetSuperConstructor', 'GetTemplateObject', 'GetThisEnvironment', 'GetThisValue', 'GetValue', 'GetValueFromBuffer', 'GetViewValue', 'GetWaiterList', 'GlobalDeclarationInstantiation', 'happens-before', 'HasPrimitiveBase', 'host-synchronizes-with', 'HostEnsureCanCompileStrings', 'HostEventSet', 'HostPromiseRejectionTracker', 'HostReportErrors', 'HostResolveImportedModule', 'IfAbruptRejectPromise', 'ImportedLocalNames', 'InitializeBoundName', 'InitializeHostDefinedRealm', 'InitializeReferencedBinding', 'InnerModuleEvaluation', 'InnerModuleInstantiation', 'IntegerIndexedElementGet', 'IntegerIndexedElementSet', 'IntegerIndexedObjectCreate', 'InternalizeJSONProperty', 'IsAnonymousFunctionDefinition', 'IsCompatiblePropertyDescriptor', 'IsDetachedBuffer', 'IsInTailPosition', 'IsLabelledFunction', 'IsPropertyReference', 'IsSharedArrayBuffer', 'IsStrictReference', 'IsSuperReference', 'IsUnresolvableReference', 'IsWordChar', 'LeaveCriticalSection', 'LocalTime', 'LoopContinues', 'MakeArgGetter', 'MakeArgSetter', 'MakeClassConstructor', 'MakeConstructor', 'MakeMethod', 'MakeSuperPropertyReference', 'max', 'memory-order', 'min', 'ModuleDeclarationEnvironmentSetup', 'ModuleExecution', 'ModuleNamespaceCreate', 'NewDeclarativeEnvironment', 'NewFunctionEnvironment', 'NewGlobalEnvironment', 'NewModuleEnvironment', 'NewObjectEnvironment', 'NewPromiseCapability', 'NumberToRawBytes', 'ObjectDefineProperties', 'OrdinaryCallBindThis', 'OrdinaryCallEvaluateBody', 'OrdinaryCreateFromConstructor', 'OrdinaryDelete', 'OrdinaryGet', 'OrdinaryIsExtensible', 'OrdinaryOwnPropertyKeys', 'OrdinaryPreventExtensions', 'OrdinaryToPrimitive', 'ParseModule', 'ParseScript', 'PerformEval', 'PerformPromiseAll', 'PerformPromiseRace', 'PerformPromiseThen', 'PrepareForOrdinaryCall', 'PrepareForTailCall', 'PromiseReactionJob', 'PromiseResolveThenableJob', 'ProxyCreate', 'PutValue', 'QuoteJSONString', 'RawBytesToNumber', 'reads-bytes-from', 'reads-from', 'RegExpAlloc', 'RegExpCreate', 'RegExpInitialize', 'RejectPromise', 'RemoveWaiter', 'RemoveWaiters', 'RepeatMatcher', 'ResolveBinding', 'ResolveThisBinding', 'ReturnIfAbrupt', 'RunJobs', 'ScriptEvaluation', 'ScriptEvaluationJob', 'SerializeJSONArray', 'SerializeJSONObject', 'SerializeJSONProperty', 'SetDefaultGlobalBindings', 'SetImmutablePrototype', 'SetRealmGlobalObject', 'SetValueInBuffer', 'SetViewValue', 'SharedDataBlockEventSet', 'SortCompare', 'SplitMatch', 'StringCreate', 'StringGetOwnProperty', 'Suspend', 'synchronizes-with', 'TimeZoneString', 'TopLevelModuleEvaluationJob', 'TriggerPromiseReactions', 'TypedArrayCreate', 'TypedArraySpeciesCreate', 'UnicodeEscape', 'UpdateEmpty', 'UTC', 'UTF16Decode', 'UTF16Encoding', 'ValidateAtomicAccess', 'ValidateSharedIntegerTypedArray', 'ValidateTypedArray', 'ValueOfReadEvent', 'WakeWaiter', 'WordCharacters', 'AsyncFunctionCreate', 'AsyncGeneratorFunctionCreate', 'AsyncIteratorClose', 'BackreferenceMatcher', 'Construct', 'CreateArrayFromList', 'CreateListIteratorRecord', 'NormalCompletion', 'OrdinarySet', 'OrdinarySetWithOwnDescriptor', 'RegExpBuiltinExec', 'SetFunctionLength', 'ThrowCompletion', 'UnicodeMatchProperty', 'UnicodeMatchPropertyValue']; - -require('./tests').es2018(ES, ops, expectedMissing); - -require('./helpers/runManifestTest')(require('tape'), ES, 2018); diff --git a/node_modules/es-abstract/test/es2019.js b/node_modules/es-abstract/test/es2019.js deleted file mode 100644 index c0486a0..0000000 --- a/node_modules/es-abstract/test/es2019.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var ES = require('../').ES2019; - -var ops = require('../operations/2019'); - -var expectedMissing = ['abs', 'AddRestrictedFunctionProperties', 'AddWaiter', 'agent-order', 'AgentCanSuspend', 'AgentSignifier', 'AllocateArrayBuffer', 'AllocateSharedArrayBuffer', 'AllocateTypedArray', 'AllocateTypedArrayBuffer', 'AsyncFunctionStart', 'AsyncGeneratorEnqueue', 'AsyncGeneratorReject', 'AsyncGeneratorResolve', 'AsyncGeneratorResumeNext', 'AsyncGeneratorStart', 'AsyncGeneratorYield', 'AtomicLoad', 'AtomicReadModifyWrite', 'Await', 'BlockDeclarationInstantiation', 'BoundFunctionCreate', 'Canonicalize', 'CaseClauseIsSelected', 'CharacterRange', 'CharacterRangeOrUnion', 'CharacterSetMatcher', 'CloneArrayBuffer', 'Completion', 'ComposeWriteEventBytes', 'CopyDataBlockBytes', 'CreateArrayIterator', 'CreateAsyncFromSyncIterator', 'CreateBuiltinFunction', 'CreateByteDataBlock', 'CreateDynamicFunction', 'CreateIntrinsics', 'CreateMapIterator', 'CreateMappedArgumentsObject', 'CreatePerIterationEnvironment', 'CreateRealm', 'CreateResolvingFunctions', 'CreateSetIterator', 'CreateSharedByteDataBlock', 'CreateStringIterator', 'CreateUnmappedArgumentsObject', 'Decode', 'DetachArrayBuffer', 'Encode', 'EnqueueJob', 'EnterCriticalSection', 'EnumerateObjectProperties', 'EscapeRegExpPattern', 'EvalDeclarationInstantiation', 'EvaluateCall', 'EvaluateNew', 'EventSet', 'floor', 'ForBodyEvaluation', 'ForIn/OfBodyEvaluation', 'ForIn/OfHeadEvaluation', 'FulfillPromise', 'FunctionAllocate', 'FunctionCreate', 'FunctionDeclarationInstantiation', 'FunctionInitialize', 'GeneratorFunctionCreate', 'GeneratorResume', 'GeneratorResumeAbrupt', 'GeneratorStart', 'GeneratorValidate', 'GeneratorYield', 'GetActiveScriptOrModule', 'GetBase', 'GetFunctionRealm', 'GetGeneratorKind', 'GetGlobalObject', 'GetIdentifierReference', 'GetModifySetValueInBuffer', 'GetModuleNamespace', 'GetNewTarget', 'GetReferencedName', 'GetSuperConstructor', 'GetTemplateObject', 'GetThisEnvironment', 'GetThisValue', 'GetValue', 'GetValueFromBuffer', 'GetViewValue', 'GetWaiterList', 'GlobalDeclarationInstantiation', 'happens-before', 'HasPrimitiveBase', 'host-synchronizes-with', 'HostEnsureCanCompileStrings', 'HostEventSet', 'HostPromiseRejectionTracker', 'HostReportErrors', 'HostResolveImportedModule', 'IfAbruptRejectPromise', 'ImportedLocalNames', 'InitializeBoundName', 'InitializeHostDefinedRealm', 'InitializeReferencedBinding', 'InnerModuleEvaluation', 'InnerModuleInstantiation', 'IntegerIndexedElementGet', 'IntegerIndexedElementSet', 'IntegerIndexedObjectCreate', 'InternalizeJSONProperty', 'IsAnonymousFunctionDefinition', 'IsCompatiblePropertyDescriptor', 'IsDetachedBuffer', 'IsInTailPosition', 'IsLabelledFunction', 'IsPropertyReference', 'IsSharedArrayBuffer', 'IsStrictReference', 'IsSuperReference', 'IsUnresolvableReference', 'IsWordChar', 'LeaveCriticalSection', 'LocalTime', 'LoopContinues', 'MakeArgGetter', 'MakeArgSetter', 'MakeClassConstructor', 'MakeConstructor', 'MakeMethod', 'MakeSuperPropertyReference', 'max', 'memory-order', 'min', 'ModuleDeclarationEnvironmentSetup', 'ModuleExecution', 'ModuleNamespaceCreate', 'NewDeclarativeEnvironment', 'NewFunctionEnvironment', 'NewGlobalEnvironment', 'NewModuleEnvironment', 'NewObjectEnvironment', 'NewPromiseCapability', 'NumberToRawBytes', 'ObjectDefineProperties', 'OrdinaryCallBindThis', 'OrdinaryCallEvaluateBody', 'OrdinaryCreateFromConstructor', 'OrdinaryDelete', 'OrdinaryGet', 'OrdinaryIsExtensible', 'OrdinaryOwnPropertyKeys', 'OrdinaryPreventExtensions', 'OrdinaryToPrimitive', 'ParseModule', 'ParseScript', 'PerformEval', 'PerformPromiseAll', 'PerformPromiseRace', 'PerformPromiseThen', 'PrepareForOrdinaryCall', 'PrepareForTailCall', 'PromiseReactionJob', 'PromiseResolveThenableJob', 'ProxyCreate', 'PutValue', 'QuoteJSONString', 'RawBytesToNumber', 'reads-bytes-from', 'reads-from', 'RegExpAlloc', 'RegExpCreate', 'RegExpInitialize', 'RejectPromise', 'RemoveWaiter', 'RemoveWaiters', 'RepeatMatcher', 'ResolveBinding', 'ResolveThisBinding', 'ReturnIfAbrupt', 'RunJobs', 'ScriptEvaluation', 'ScriptEvaluationJob', 'SerializeJSONArray', 'SerializeJSONObject', 'SerializeJSONProperty', 'SetDefaultGlobalBindings', 'SetImmutablePrototype', 'SetRealmGlobalObject', 'SetValueInBuffer', 'SetViewValue', 'SharedDataBlockEventSet', 'SortCompare', 'SplitMatch', 'StringCreate', 'StringGetOwnProperty', 'Suspend', 'synchronizes-with', 'TimeZoneString', 'TopLevelModuleEvaluationJob', 'TriggerPromiseReactions', 'TypedArrayCreate', 'TypedArraySpeciesCreate', 'UnicodeEscape', 'UpdateEmpty', 'UTC', 'UTF16Decode', 'UTF16Encoding', 'ValidateAtomicAccess', 'ValidateSharedIntegerTypedArray', 'ValidateTypedArray', 'ValueOfReadEvent', 'WakeWaiter', 'WordCharacters', 'AsyncFunctionCreate', 'AsyncGeneratorFunctionCreate', 'AsyncIteratorClose', 'BackreferenceMatcher', 'Construct', 'CreateArrayFromList', 'CreateListIteratorRecord', 'NormalCompletion', 'OrdinarySet', 'OrdinarySetWithOwnDescriptor', 'RegExpBuiltinExec', 'SetFunctionLength', 'ThrowCompletion', 'UnicodeMatchProperty', 'UnicodeMatchPropertyValue', 'AsyncFromSyncIteratorContinuation', 'ExecuteModule', 'InitializeEnvironment', 'NotifyWaiter', 'SynchronizeEventSet']; - -require('./tests').es2019(ES, ops, expectedMissing); - -require('./helpers/runManifestTest')(require('tape'), ES, 2019); diff --git a/node_modules/es-abstract/test/es5.js b/node_modules/es-abstract/test/es5.js deleted file mode 100644 index b4fb7f3..0000000 --- a/node_modules/es-abstract/test/es5.js +++ /dev/null @@ -1,784 +0,0 @@ -'use strict'; - -var ES = require('../').ES5; -var test = require('tape'); - -var forEach = require('foreach'); -var is = require('object-is'); -var debug = require('object-inspect'); - -var v = require('./helpers/values'); - -require('./helpers/runManifestTest')(test, ES, 5); - -test('ToPrimitive', function (t) { - t.test('primitives', function (st) { - var testPrimitive = function (primitive) { - st.ok(is(ES.ToPrimitive(primitive), primitive), debug(primitive) + ' is returned correctly'); - }; - forEach(v.primitives, testPrimitive); - st.end(); - }); - - t.test('objects', function (st) { - st.equal(ES.ToPrimitive(v.coercibleObject), v.coercibleObject.valueOf(), 'coercibleObject coerces to valueOf'); - st.equal(ES.ToPrimitive(v.coercibleObject, Number), v.coercibleObject.valueOf(), 'coercibleObject with hint Number coerces to valueOf'); - st.equal(ES.ToPrimitive(v.coercibleObject, String), v.coercibleObject.toString(), 'coercibleObject with hint String coerces to toString'); - st.equal(ES.ToPrimitive(v.coercibleFnObject), v.coercibleFnObject.toString(), 'coercibleFnObject coerces to toString'); - st.equal(ES.ToPrimitive(v.toStringOnlyObject), v.toStringOnlyObject.toString(), 'toStringOnlyObject returns toString'); - st.equal(ES.ToPrimitive(v.valueOfOnlyObject), v.valueOfOnlyObject.valueOf(), 'valueOfOnlyObject returns valueOf'); - st.equal(ES.ToPrimitive({}), '[object Object]', '{} with no hint coerces to Object#toString'); - st.equal(ES.ToPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); - st.equal(ES.ToPrimitive({}, Number), '[object Object]', '{} with hint Number coerces to Object#toString'); - st['throws'](function () { return ES.ToPrimitive(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws a TypeError'); - st['throws'](function () { return ES.ToPrimitive(v.uncoercibleFnObject); }, TypeError, 'uncoercibleFnObject throws a TypeError'); - st.end(); - }); - - t.end(); -}); - -test('ToBoolean', function (t) { - t.equal(false, ES.ToBoolean(undefined), 'undefined coerces to false'); - t.equal(false, ES.ToBoolean(null), 'null coerces to false'); - t.equal(false, ES.ToBoolean(false), 'false returns false'); - t.equal(true, ES.ToBoolean(true), 'true returns true'); - forEach([0, -0, NaN], function (falsyNumber) { - t.equal(false, ES.ToBoolean(falsyNumber), 'falsy number ' + falsyNumber + ' coerces to false'); - }); - forEach([Infinity, 42, 1, -Infinity], function (truthyNumber) { - t.equal(true, ES.ToBoolean(truthyNumber), 'truthy number ' + truthyNumber + ' coerces to true'); - }); - t.equal(false, ES.ToBoolean(''), 'empty string coerces to false'); - t.equal(true, ES.ToBoolean('foo'), 'nonempty string coerces to true'); - forEach(v.objects, function (obj) { - t.equal(true, ES.ToBoolean(obj), 'object coerces to true'); - }); - t.equal(true, ES.ToBoolean(v.uncoercibleObject), 'uncoercibleObject coerces to true'); - t.end(); -}); - -test('ToNumber', function (t) { - t.ok(is(NaN, ES.ToNumber(undefined)), 'undefined coerces to NaN'); - t.ok(is(ES.ToNumber(null), 0), 'null coerces to +0'); - t.ok(is(ES.ToNumber(false), 0), 'false coerces to +0'); - t.equal(1, ES.ToNumber(true), 'true coerces to 1'); - t.ok(is(NaN, ES.ToNumber(NaN)), 'NaN returns itself'); - forEach([0, -0, 42, Infinity, -Infinity], function (num) { - t.equal(num, ES.ToNumber(num), num + ' returns itself'); - }); - forEach(['foo', '0', '4a', '2.0', 'Infinity', '-Infinity'], function (numString) { - t.ok(is(+numString, ES.ToNumber(numString)), '"' + numString + '" coerces to ' + Number(numString)); - }); - forEach(v.objects, function (object) { - t.ok(is(ES.ToNumber(object), ES.ToNumber(ES.ToPrimitive(object))), 'object ' + object + ' coerces to same as ToPrimitive of object does'); - }); - t['throws'](function () { return ES.ToNumber(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.end(); -}); - -test('ToInteger', function (t) { - t.ok(is(0, ES.ToInteger(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity, 42], function (num) { - t.ok(is(num, ES.ToInteger(num)), num + ' returns itself'); - t.ok(is(-num, ES.ToInteger(-num)), '-' + num + ' returns itself'); - }); - t.equal(3, ES.ToInteger(Math.PI), 'pi returns 3'); - t['throws'](function () { return ES.ToInteger(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.end(); -}); - -test('ToInt32', function (t) { - t.ok(is(0, ES.ToInt32(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToInt32(num)), num + ' returns +0'); - t.ok(is(0, ES.ToInt32(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToInt32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToInt32(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToInt32(0x100000000 - 1), -1), '2^32 - 1 returns -1'); - t.ok(is(ES.ToInt32(0x80000000), -0x80000000), '2^31 returns -2^31'); - t.ok(is(ES.ToInt32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1'); - forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) { - t.ok(is(ES.ToInt32(num), ES.ToInt32(ES.ToUint32(num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for 0x' + num.toString(16)); - t.ok(is(ES.ToInt32(-num), ES.ToInt32(ES.ToUint32(-num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for -0x' + num.toString(16)); - }); - t.end(); -}); - -test('ToUint32', function (t) { - t.ok(is(0, ES.ToUint32(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToUint32(num)), num + ' returns +0'); - t.ok(is(0, ES.ToUint32(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToUint32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToUint32(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToUint32(0x100000000 - 1), 0x100000000 - 1), '2^32 - 1 returns 2^32 - 1'); - t.ok(is(ES.ToUint32(0x80000000), 0x80000000), '2^31 returns 2^31'); - t.ok(is(ES.ToUint32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1'); - forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) { - t.ok(is(ES.ToUint32(num), ES.ToUint32(ES.ToInt32(num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for 0x' + num.toString(16)); - t.ok(is(ES.ToUint32(-num), ES.ToUint32(ES.ToInt32(-num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for -0x' + num.toString(16)); - }); - t.end(); -}); - -test('ToUint16', function (t) { - t.ok(is(0, ES.ToUint16(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToUint16(num)), num + ' returns +0'); - t.ok(is(0, ES.ToUint16(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToUint16(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToUint16(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToUint16(0x100000000 - 1), 0x10000 - 1), '2^32 - 1 returns 2^16 - 1'); - t.ok(is(ES.ToUint16(0x80000000), 0), '2^31 returns +0'); - t.ok(is(ES.ToUint16(0x80000000 - 1), 0x10000 - 1), '2^31 - 1 returns 2^16 - 1'); - t.ok(is(ES.ToUint16(0x10000), 0), '2^16 returns +0'); - t.ok(is(ES.ToUint16(0x10000 - 1), 0x10000 - 1), '2^16 - 1 returns 2^16 - 1'); - t.end(); -}); - -test('ToString', function (t) { - t['throws'](function () { return ES.ToString(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.end(); -}); - -test('ToObject', function (t) { - t['throws'](function () { return ES.ToObject(undefined); }, TypeError, 'undefined throws'); - t['throws'](function () { return ES.ToObject(null); }, TypeError, 'null throws'); - forEach(v.numbers, function (number) { - var obj = ES.ToObject(number); - t.equal(typeof obj, 'object', 'number ' + number + ' coerces to object'); - t.equal(true, obj instanceof Number, 'object of ' + number + ' is Number object'); - t.ok(is(obj.valueOf(), number), 'object of ' + number + ' coerces to ' + number); - }); - t.end(); -}); - -test('CheckObjectCoercible', function (t) { - t['throws'](function () { return ES.CheckObjectCoercible(undefined); }, TypeError, 'undefined throws'); - t['throws'](function () { return ES.CheckObjectCoercible(null); }, TypeError, 'null throws'); - var checkCoercible = function (value) { - t.doesNotThrow(function () { return ES.CheckObjectCoercible(value); }, debug(value) + ' does not throw'); - }; - forEach(v.objects.concat(v.nonNullPrimitives), checkCoercible); - t.end(); -}); - -test('IsCallable', function (t) { - t.equal(true, ES.IsCallable(function () {}), 'function is callable'); - var nonCallables = [/a/g, {}, Object.prototype, NaN].concat(v.primitives); - forEach(nonCallables, function (nonCallable) { - t.equal(false, ES.IsCallable(nonCallable), debug(nonCallable) + ' is not callable'); - }); - t.end(); -}); - -test('SameValue', function (t) { - t.equal(true, ES.SameValue(NaN, NaN), 'NaN is SameValue as NaN'); - t.equal(false, ES.SameValue(0, -0), '+0 is not SameValue as -0'); - forEach(v.objects.concat(v.primitives), function (val) { - t.equal(val === val, ES.SameValue(val, val), debug(val) + ' is SameValue to itself'); - }); - t.end(); -}); - -test('Type', function (t) { - t.equal(ES.Type(), 'Undefined', 'Type() is Undefined'); - t.equal(ES.Type(undefined), 'Undefined', 'Type(undefined) is Undefined'); - t.equal(ES.Type(null), 'Null', 'Type(null) is Null'); - t.equal(ES.Type(true), 'Boolean', 'Type(true) is Boolean'); - t.equal(ES.Type(false), 'Boolean', 'Type(false) is Boolean'); - t.equal(ES.Type(0), 'Number', 'Type(0) is Number'); - t.equal(ES.Type(NaN), 'Number', 'Type(NaN) is Number'); - t.equal(ES.Type('abc'), 'String', 'Type("abc") is String'); - t.equal(ES.Type(function () {}), 'Object', 'Type(function () {}) is Object'); - t.equal(ES.Type({}), 'Object', 'Type({}) is Object'); - t.end(); -}); - -test('IsPropertyDescriptor', function (t) { - forEach(v.primitives, function (primitive) { - t.equal(ES.IsPropertyDescriptor(primitive), false, debug(primitive) + ' is not a Property Descriptor'); - }); - - t.equal(ES.IsPropertyDescriptor({ invalid: true }), false, 'invalid keys not allowed on a Property Descriptor'); - - t.equal(ES.IsPropertyDescriptor({}), true, 'empty object is an incomplete Property Descriptor'); - - t.equal(ES.IsPropertyDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is a Property Descriptor'); - t.equal(ES.IsPropertyDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is a Property Descriptor'); - t.equal(ES.IsPropertyDescriptor(v.dataDescriptor()), true, 'data descriptor is a Property Descriptor'); - t.equal(ES.IsPropertyDescriptor(v.genericDescriptor()), true, 'generic descriptor is a Property Descriptor'); - - t['throws']( - function () { ES.IsPropertyDescriptor(v.bothDescriptor()); }, - TypeError, - 'a Property Descriptor can not be both a Data and an Accessor Descriptor' - ); - - t['throws']( - function () { ES.IsPropertyDescriptor(v.bothDescriptorWritable()); }, - TypeError, - 'a Property Descriptor can not be both a Data and an Accessor Descriptor' - ); - - t.end(); -}); - -test('IsAccessorDescriptor', function (t) { - forEach(v.nonNullPrimitives.concat(null), function (primitive) { - t['throws'](function () { ES.IsAccessorDescriptor(primitive); }, TypeError, debug(primitive) + ' is not a Property Descriptor'); - }); - - t.equal(ES.IsAccessorDescriptor(), false, 'no value is not an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(undefined), false, 'undefined value is not an Accessor Descriptor'); - - t.equal(ES.IsAccessorDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(v.dataDescriptor()), false, 'data descriptor is not an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(v.genericDescriptor()), false, 'generic descriptor is not an Accessor Descriptor'); - - t.end(); -}); - -test('IsDataDescriptor', function (t) { - forEach(v.nonNullPrimitives.concat(null), function (primitive) { - t['throws'](function () { ES.IsDataDescriptor(primitive); }, TypeError, debug(primitive) + ' is not a Property Descriptor'); - }); - - t.equal(ES.IsDataDescriptor(), false, 'no value is not a Data Descriptor'); - t.equal(ES.IsDataDescriptor(undefined), false, 'undefined value is not a Data Descriptor'); - - t.equal(ES.IsDataDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a Data Descriptor'); - t.equal(ES.IsDataDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a Data Descriptor'); - t.equal(ES.IsDataDescriptor(v.dataDescriptor()), true, 'data descriptor is a Data Descriptor'); - t.equal(ES.IsDataDescriptor(v.genericDescriptor()), false, 'generic descriptor is not a Data Descriptor'); - - t.end(); -}); - -test('IsGenericDescriptor', function (t) { - forEach(v.nonNullPrimitives.concat(null), function (primitive) { - t['throws']( - function () { ES.IsGenericDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t.equal(ES.IsGenericDescriptor(), false, 'no value is not a Data Descriptor'); - t.equal(ES.IsGenericDescriptor(undefined), false, 'undefined value is not a Data Descriptor'); - - t.equal(ES.IsGenericDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a generic Descriptor'); - t.equal(ES.IsGenericDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a generic Descriptor'); - t.equal(ES.IsGenericDescriptor(v.dataDescriptor()), false, 'data descriptor is not a generic Descriptor'); - - t.equal(ES.IsGenericDescriptor(v.genericDescriptor()), true, 'generic descriptor is a generic Descriptor'); - - t.end(); -}); - -test('FromPropertyDescriptor', function (t) { - t.equal(ES.FromPropertyDescriptor(), undefined, 'no value begets undefined'); - t.equal(ES.FromPropertyDescriptor(undefined), undefined, 'undefined value begets undefined'); - - forEach(v.nonNullPrimitives.concat(null), function (primitive) { - t['throws']( - function () { ES.FromPropertyDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - var accessor = v.accessorDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(accessor), { - get: accessor['[[Get]]'], - set: accessor['[[Set]]'], - enumerable: !!accessor['[[Enumerable]]'], - configurable: !!accessor['[[Configurable]]'] - }); - - var mutator = v.mutatorDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(mutator), { - get: mutator['[[Get]]'], - set: mutator['[[Set]]'], - enumerable: !!mutator['[[Enumerable]]'], - configurable: !!mutator['[[Configurable]]'] - }); - var data = v.dataDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(data), { - value: data['[[Value]]'], - writable: data['[[Writable]]'], - enumerable: !!data['[[Enumerable]]'], - configurable: !!data['[[Configurable]]'] - }); - - t['throws']( - function () { ES.FromPropertyDescriptor(v.genericDescriptor()); }, - TypeError, - 'a complete Property Descriptor is required' - ); - - t.end(); -}); - -test('ToPropertyDescriptor', function (t) { - forEach(v.nonNullPrimitives.concat(null), function (primitive) { - t['throws']( - function () { ES.ToPropertyDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - var accessor = v.accessorDescriptor(); - t.deepEqual(ES.ToPropertyDescriptor({ - get: accessor['[[Get]]'], - enumerable: !!accessor['[[Enumerable]]'], - configurable: !!accessor['[[Configurable]]'] - }), accessor); - - var mutator = v.mutatorDescriptor(); - t.deepEqual(ES.ToPropertyDescriptor({ - set: mutator['[[Set]]'], - enumerable: !!mutator['[[Enumerable]]'], - configurable: !!mutator['[[Configurable]]'] - }), mutator); - - var data = v.descriptors.nonConfigurable(v.dataDescriptor()); - t.deepEqual(ES.ToPropertyDescriptor({ - value: data['[[Value]]'], - writable: data['[[Writable]]'], - configurable: !!data['[[Configurable]]'] - }), data); - - var both = v.bothDescriptor(); - t['throws']( - function () { - ES.ToPropertyDescriptor({ get: both['[[Get]]'], value: both['[[Value]]'] }); - }, - TypeError, - 'data and accessor descriptors are mutually exclusive' - ); - - t['throws']( - function () { ES.ToPropertyDescriptor({ get: 'not callable' }); }, - TypeError, - '"get" must be undefined or callable' - ); - - t['throws']( - function () { ES.ToPropertyDescriptor({ set: 'not callable' }); }, - TypeError, - '"set" must be undefined or callable' - ); - - t.end(); -}); - -test('Abstract Equality Comparison', function (t) { - t.test('same types use ===', function (st) { - forEach(v.primitives.concat(v.objects), function (value) { - st.equal(ES['Abstract Equality Comparison'](value, value), value === value, debug(value) + ' is abstractly equal to itself'); - }); - st.end(); - }); - - t.test('different types coerce', function (st) { - var pairs = [ - [null, undefined], - [3, '3'], - [true, '3'], - [true, 3], - [false, 0], - [false, '0'], - [3, [3]], - ['3', [3]], - [true, [1]], - [false, [0]], - [String(v.coercibleObject), v.coercibleObject], - [Number(String(v.coercibleObject)), v.coercibleObject], - [Number(v.coercibleObject), v.coercibleObject], - [String(Number(v.coercibleObject)), v.coercibleObject] - ]; - forEach(pairs, function (pair) { - var a = pair[0]; - var b = pair[1]; - // eslint-disable-next-line eqeqeq - st.equal(ES['Abstract Equality Comparison'](a, b), a == b, debug(a) + ' == ' + debug(b)); - // eslint-disable-next-line eqeqeq - st.equal(ES['Abstract Equality Comparison'](b, a), b == a, debug(b) + ' == ' + debug(a)); - }); - st.end(); - }); - - t.end(); -}); - -test('Strict Equality Comparison', function (t) { - t.test('same types use ===', function (st) { - forEach(v.primitives.concat(v.objects), function (value) { - st.equal(ES['Strict Equality Comparison'](value, value), value === value, debug(value) + ' is strictly equal to itself'); - }); - st.end(); - }); - - t.test('different types are not ===', function (st) { - var pairs = [ - [null, undefined], - [3, '3'], - [true, '3'], - [true, 3], - [false, 0], - [false, '0'], - [3, [3]], - ['3', [3]], - [true, [1]], - [false, [0]], - [String(v.coercibleObject), v.coercibleObject], - [Number(String(v.coercibleObject)), v.coercibleObject], - [Number(v.coercibleObject), v.coercibleObject], - [String(Number(v.coercibleObject)), v.coercibleObject] - ]; - forEach(pairs, function (pair) { - var a = pair[0]; - var b = pair[1]; - st.equal(ES['Strict Equality Comparison'](a, b), a === b, debug(a) + ' === ' + debug(b)); - st.equal(ES['Strict Equality Comparison'](b, a), b === a, debug(b) + ' === ' + debug(a)); - }); - st.end(); - }); - - t.end(); -}); - -test('Abstract Relational Comparison', function (t) { - t.test('at least one operand is NaN', function (st) { - st.equal(ES['Abstract Relational Comparison'](NaN, {}, true), undefined, 'LeftFirst: first is NaN, returns undefined'); - st.equal(ES['Abstract Relational Comparison']({}, NaN, true), undefined, 'LeftFirst: second is NaN, returns undefined'); - st.equal(ES['Abstract Relational Comparison'](NaN, {}, false), undefined, '!LeftFirst: first is NaN, returns undefined'); - st.equal(ES['Abstract Relational Comparison']({}, NaN, false), undefined, '!LeftFirst: second is NaN, returns undefined'); - st.end(); - }); - - t.equal(ES['Abstract Relational Comparison'](3, 4, true), true, 'LeftFirst: 3 is less than 4'); - t.equal(ES['Abstract Relational Comparison'](4, 3, true), false, 'LeftFirst: 3 is not less than 4'); - t.equal(ES['Abstract Relational Comparison'](3, 4, false), true, '!LeftFirst: 3 is less than 4'); - t.equal(ES['Abstract Relational Comparison'](4, 3, false), false, '!LeftFirst: 3 is not less than 4'); - - t.equal(ES['Abstract Relational Comparison']('3', '4', true), true, 'LeftFirst: "3" is less than "4"'); - t.equal(ES['Abstract Relational Comparison']('4', '3', true), false, 'LeftFirst: "3" is not less than "4"'); - t.equal(ES['Abstract Relational Comparison']('3', '4', false), true, '!LeftFirst: "3" is less than "4"'); - t.equal(ES['Abstract Relational Comparison']('4', '3', false), false, '!LeftFirst: "3" is not less than "4"'); - - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, true), true, 'LeftFirst: coercible object is less than 42'); - t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, true), false, 'LeftFirst: 42 is not less than coercible object'); - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, false), true, '!LeftFirst: coercible object is less than 42'); - t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, false), false, '!LeftFirst: 42 is not less than coercible object'); - - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', true), false, 'LeftFirst: coercible object is not less than "3"'); - t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, true), false, 'LeftFirst: "3" is not less than coercible object'); - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', false), false, '!LeftFirst: coercible object is not less than "3"'); - t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, false), false, '!LeftFirst: "3" is not less than coercible object'); - - t.end(); -}); - -test('FromPropertyDescriptor', function (t) { - t.equal(ES.FromPropertyDescriptor(), undefined, 'no value begets undefined'); - t.equal(ES.FromPropertyDescriptor(undefined), undefined, 'undefined value begets undefined'); - - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.FromPropertyDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - var accessor = v.accessorDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(accessor), { - get: accessor['[[Get]]'], - set: accessor['[[Set]]'], - enumerable: !!accessor['[[Enumerable]]'], - configurable: !!accessor['[[Configurable]]'] - }); - - var mutator = v.mutatorDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(mutator), { - get: mutator['[[Get]]'], - set: mutator['[[Set]]'], - enumerable: !!mutator['[[Enumerable]]'], - configurable: !!mutator['[[Configurable]]'] - }); - var data = v.dataDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(data), { - value: data['[[Value]]'], - writable: data['[[Writable]]'], - enumerable: !!data['[[Enumerable]]'], - configurable: !!data['[[Configurable]]'] - }); - - t['throws']( - function () { ES.FromPropertyDescriptor(v.genericDescriptor()); }, - TypeError, - 'a complete Property Descriptor is required' - ); - - t.end(); -}); - -test('SecFromTime', function (t) { - var now = new Date(); - t.equal(ES.SecFromTime(now.getTime()), now.getUTCSeconds(), 'second from Date timestamp matches getUTCSeconds'); - t.end(); -}); - -test('MinFromTime', function (t) { - var now = new Date(); - t.equal(ES.MinFromTime(now.getTime()), now.getUTCMinutes(), 'minute from Date timestamp matches getUTCMinutes'); - t.end(); -}); - -test('HourFromTime', function (t) { - var now = new Date(); - t.equal(ES.HourFromTime(now.getTime()), now.getUTCHours(), 'hour from Date timestamp matches getUTCHours'); - t.end(); -}); - -test('msFromTime', function (t) { - var now = new Date(); - t.equal(ES.msFromTime(now.getTime()), now.getUTCMilliseconds(), 'ms from Date timestamp matches getUTCMilliseconds'); - t.end(); -}); - -var msPerSecond = 1e3; -var msPerMinute = 60 * msPerSecond; -var msPerHour = 60 * msPerMinute; -var msPerDay = 24 * msPerHour; - -test('Day', function (t) { - var time = Date.UTC(2019, 8, 10, 2, 3, 4, 5); - var add = 2.5; - var later = new Date(time + (add * msPerDay)); - - t.equal(ES.Day(later.getTime()), ES.Day(time) + Math.floor(add), 'adding 2.5 days worth of ms, gives a Day delta of 2'); - t.end(); -}); - -test('TimeWithinDay', function (t) { - var time = Date.UTC(2019, 8, 10, 2, 3, 4, 5); - var add = 2.5; - var later = new Date(time + (add * msPerDay)); - - t.equal(ES.TimeWithinDay(later.getTime()), ES.TimeWithinDay(time) + (0.5 * msPerDay), 'adding 2.5 days worth of ms, gives a TimeWithinDay delta of +0.5'); - t.end(); -}); - -test('DayFromYear', function (t) { - t.equal(ES.DayFromYear(2021) - ES.DayFromYear(2020), 366, '2021 is a leap year, has 366 days'); - t.equal(ES.DayFromYear(2020) - ES.DayFromYear(2019), 365, '2020 is not a leap year, has 365 days'); - t.equal(ES.DayFromYear(2019) - ES.DayFromYear(2018), 365, '2019 is not a leap year, has 365 days'); - t.equal(ES.DayFromYear(2018) - ES.DayFromYear(2017), 365, '2018 is not a leap year, has 365 days'); - t.equal(ES.DayFromYear(2017) - ES.DayFromYear(2016), 366, '2017 is a leap year, has 366 days'); - - t.end(); -}); - -test('TimeFromYear', function (t) { - for (var i = 1900; i < 2100; i += 1) { - t.equal(ES.TimeFromYear(i), Date.UTC(i, 0, 1), 'TimeFromYear matches a Date object’s year: ' + i); - } - t.end(); -}); - -test('YearFromTime', function (t) { - for (var i = 1900; i < 2100; i += 1) { - t.equal(ES.YearFromTime(Date.UTC(i, 0, 1)), i, 'YearFromTime matches a Date object’s year on 1/1: ' + i); - t.equal(ES.YearFromTime(Date.UTC(i, 10, 1)), i, 'YearFromTime matches a Date object’s year on 10/1: ' + i); - } - t.end(); -}); - -test('WeekDay', function (t) { - var now = new Date(); - var today = now.getUTCDay(); - for (var i = 0; i < 7; i += 1) { - var weekDay = ES.WeekDay(now.getTime() + (i * msPerDay)); - t.equal(weekDay, (today + i) % 7, i + ' days after today (' + today + '), WeekDay is ' + weekDay); - } - t.end(); -}); - -test('DaysInYear', function (t) { - t.equal(ES.DaysInYear(2021), 365, '2021 is not a leap year'); - t.equal(ES.DaysInYear(2020), 366, '2020 is a leap year'); - t.equal(ES.DaysInYear(2019), 365, '2019 is not a leap year'); - t.equal(ES.DaysInYear(2018), 365, '2018 is not a leap year'); - t.equal(ES.DaysInYear(2017), 365, '2017 is not a leap year'); - t.equal(ES.DaysInYear(2016), 366, '2016 is a leap year'); - - t.end(); -}); - -test('InLeapYear', function (t) { - t.equal(ES.InLeapYear(Date.UTC(2021, 0, 1)), 0, '2021 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2020, 0, 1)), 1, '2020 is a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2019, 0, 1)), 0, '2019 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2018, 0, 1)), 0, '2018 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2017, 0, 1)), 0, '2017 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2016, 0, 1)), 1, '2016 is a leap year'); - - t.end(); -}); - -test('DayWithinYear', function (t) { - t.equal(ES.DayWithinYear(Date.UTC(2019, 0, 1)), 0, '1/1 is the 1st day'); - t.equal(ES.DayWithinYear(Date.UTC(2019, 11, 31)), 364, '12/31 is the 365th day in a non leap year'); - t.equal(ES.DayWithinYear(Date.UTC(2016, 11, 31)), 365, '12/31 is the 366th day in a leap year'); - - t.end(); -}); - -test('MonthFromTime', function (t) { - t.equal(ES.MonthFromTime(Date.UTC(2019, 0, 1)), 0, 'non-leap: 1/1 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 0, 31)), 0, 'non-leap: 1/31 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 1)), 1, 'non-leap: 2/1 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 28)), 1, 'non-leap: 2/28 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 29)), 2, 'non-leap: 2/29 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 2, 1)), 2, 'non-leap: 3/1 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 2, 31)), 2, 'non-leap: 3/31 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 3, 1)), 3, 'non-leap: 4/1 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 3, 30)), 3, 'non-leap: 4/30 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 4, 1)), 4, 'non-leap: 5/1 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 4, 31)), 4, 'non-leap: 5/31 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 5, 1)), 5, 'non-leap: 6/1 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 5, 30)), 5, 'non-leap: 6/30 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 6, 1)), 6, 'non-leap: 7/1 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 6, 31)), 6, 'non-leap: 7/31 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 7, 1)), 7, 'non-leap: 8/1 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 7, 30)), 7, 'non-leap: 8/30 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 8, 1)), 8, 'non-leap: 9/1 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 8, 30)), 8, 'non-leap: 9/30 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 9, 1)), 9, 'non-leap: 10/1 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 9, 31)), 9, 'non-leap: 10/31 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 10, 1)), 10, 'non-leap: 11/1 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 10, 30)), 10, 'non-leap: 11/30 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 11, 1)), 11, 'non-leap: 12/1 gives December'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 11, 31)), 11, 'non-leap: 12/31 gives December'); - - t.equal(ES.MonthFromTime(Date.UTC(2016, 0, 1)), 0, 'leap: 1/1 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 0, 31)), 0, 'leap: 1/31 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 1)), 1, 'leap: 2/1 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 28)), 1, 'leap: 2/28 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 29)), 1, 'leap: 2/29 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 2, 1)), 2, 'leap: 3/1 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 2, 31)), 2, 'leap: 3/31 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 3, 1)), 3, 'leap: 4/1 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 3, 30)), 3, 'leap: 4/30 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 4, 1)), 4, 'leap: 5/1 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 4, 31)), 4, 'leap: 5/31 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 5, 1)), 5, 'leap: 6/1 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 5, 30)), 5, 'leap: 6/30 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 6, 1)), 6, 'leap: 7/1 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 6, 31)), 6, 'leap: 7/31 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 7, 1)), 7, 'leap: 8/1 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 7, 30)), 7, 'leap: 8/30 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 8, 1)), 8, 'leap: 9/1 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 8, 30)), 8, 'leap: 9/30 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 9, 1)), 9, 'leap: 10/1 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 9, 31)), 9, 'leap: 10/31 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 10, 1)), 10, 'leap: 11/1 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 10, 30)), 10, 'leap: 11/30 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 11, 1)), 11, 'leap: 12/1 gives December'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 11, 31)), 11, 'leap: 12/31 gives December'); - t.end(); -}); - -test('DateFromTime', function (t) { - var i; - for (i = 1; i <= 28; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2019, 1, i)), i, '2019.02.' + i + ' is date ' + i); - } - for (i = 1; i <= 29; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2016, 1, i)), i, '2016.02.' + i + ' is date ' + i); - } - for (i = 1; i <= 30; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2019, 8, i)), i, '2019.09.' + i + ' is date ' + i); - } - for (i = 1; i <= 31; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2019, 9, i)), i, '2019.10.' + i + ' is date ' + i); - } - t.end(); -}); - -test('MakeDay', function (t) { - var day2015 = 16687; - t.equal(ES.MakeDay(2015, 8, 9), day2015, '2015.09.09 is day 16687'); - var day2016 = day2015 + 366; // 2016 is a leap year - t.equal(ES.MakeDay(2016, 8, 9), day2016, '2015.09.09 is day 17053'); - var day2017 = day2016 + 365; - t.equal(ES.MakeDay(2017, 8, 9), day2017, '2017.09.09 is day 17418'); - var day2018 = day2017 + 365; - t.equal(ES.MakeDay(2018, 8, 9), day2018, '2018.09.09 is day 17783'); - var day2019 = day2018 + 365; - t.equal(ES.MakeDay(2019, 8, 9), day2019, '2019.09.09 is day 18148'); - t.end(); -}); - -test('MakeDate', function (t) { - forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { - t.ok(is(ES.MakeDate(nonFiniteNumber, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `day`'); - t.ok(is(ES.MakeDate(0, nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `time`'); - }); - t.equal(ES.MakeDate(0, 0), 0, 'zero day and zero time is zero date'); - t.equal(ES.MakeDate(0, 123), 123, 'zero day and nonzero time is a date of the "time"'); - t.equal(ES.MakeDate(1, 0), msPerDay, 'day of 1 and zero time is a date of "ms per day"'); - t.equal(ES.MakeDate(3, 0), 3 * msPerDay, 'day of 3 and zero time is a date of thrice "ms per day"'); - t.equal(ES.MakeDate(1, 123), msPerDay + 123, 'day of 1 and nonzero time is a date of "ms per day" plus the "time"'); - t.equal(ES.MakeDate(3, 123), (3 * msPerDay) + 123, 'day of 3 and nonzero time is a date of thrice "ms per day" plus the "time"'); - - t.end(); -}); - -test('MakeTime', function (t) { - forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { - t.ok(is(ES.MakeTime(nonFiniteNumber, 0, 0, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `hour`'); - t.ok(is(ES.MakeTime(0, nonFiniteNumber, 0, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `min`'); - t.ok(is(ES.MakeTime(0, 0, nonFiniteNumber, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `sec`'); - t.ok(is(ES.MakeTime(0, 0, 0, nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `ms`'); - }); - - t.equal( - ES.MakeTime(1.2, 2.3, 3.4, 4.5), - (1 * msPerHour) + (2 * msPerMinute) + (3 * msPerSecond) + 4, - 'all numbers are converted to integer, multiplied by the right number of ms, and summed' - ); - t.end(); -}); - -test('TimeClip', function (t) { - forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { - t.ok(is(ES.TimeClip(nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `time`'); - }); - t.ok(is(ES.TimeClip(8.64e15 + 1), NaN), '8.64e15 is the largest magnitude considered "finite"'); - t.ok(is(ES.TimeClip(-8.64e15 - 1), NaN), '-8.64e15 is the largest magnitude considered "finite"'); - - forEach(v.zeroes.concat([-10, 10, +new Date()]), function (time) { - t.looseEqual(ES.TimeClip(time), time, debug(time) + ' is a time of ' + debug(time)); - }); - - t.end(); -}); - -test('modulo', function (t) { - t.equal(3 % 2, 1, '+3 % 2 is +1'); - t.equal(ES.modulo(3, 2), 1, '+3 mod 2 is +1'); - - t.equal(-3 % 2, -1, '-3 % 2 is -1'); - t.equal(ES.modulo(-3, 2), 1, '-3 mod 2 is +1'); - t.end(); -}); diff --git a/node_modules/es-abstract/test/es6.js b/node_modules/es-abstract/test/es6.js deleted file mode 100644 index e7c9d98..0000000 --- a/node_modules/es-abstract/test/es6.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var test = require('tape'); - -var ES = require('../'); -var ES6 = ES.ES6; -var ES2015 = ES.ES2015; -var ES6entry = require('../es6'); - -test('legacy es6 export', function (t) { - t.equal(ES6, ES2015, 'main ES6 === main ES2015'); - t.end(); -}); - -test('legacy es6 entry point', function (t) { - t.equal(ES6, ES6entry, 'main ES6 === ES6 entry point'); - t.end(); -}); diff --git a/node_modules/es-abstract/test/es7.js b/node_modules/es-abstract/test/es7.js deleted file mode 100644 index ee57e15..0000000 --- a/node_modules/es-abstract/test/es7.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var test = require('tape'); - -var ES = require('../'); -var ES7 = ES.ES7; -var ES2016 = ES.ES2016; -var ES7entry = require('../es7'); - -test('legacy es7 export', function (t) { - t.equal(ES7, ES2016, 'main ES7 === main ES2016'); - t.end(); -}); - -test('legacy es7 entry point', function (t) { - t.equal(ES7, ES7entry, 'main ES7 === ES7 entry point'); - t.end(); -}); diff --git a/node_modules/es-abstract/test/helpers/OwnPropertyKeys.js b/node_modules/es-abstract/test/helpers/OwnPropertyKeys.js deleted file mode 100644 index 9c2b4fc..0000000 --- a/node_modules/es-abstract/test/helpers/OwnPropertyKeys.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -var test = require('tape'); -var hasSymbols = require('has-symbols')(); - -var OwnPropertyKeys = require('../../helpers/OwnPropertyKeys'); -var defineProperty = require('./defineProperty'); - -test('OwnPropertyKeys', function (t) { - t.deepEqual(OwnPropertyKeys({ a: 1, b: 2 }).sort(), ['a', 'b'].sort(), 'returns own string keys'); - - t.test('Symbols', { skip: !hasSymbols }, function (st) { - var o = { a: 1 }; - var sym = Symbol(); - o[sym] = 2; - - st.deepEqual(OwnPropertyKeys(o), ['a', sym], 'returns own string and symbol keys'); - - st.end(); - }); - - t.test('non-enumerables', { skip: !defineProperty.oDP }, function (st) { - var o = { a: 1, b: 42, c: NaN }; - defineProperty(o, 'b', { enumerable: false, value: 42 }); - defineProperty(o, 'c', { enumerable: false, get: function () { return NaN; } }); - - if (hasSymbols) { - defineProperty(o, 'd', { enumerable: false, value: true }); - defineProperty(o, 'e', { enumerable: false, get: function () { return true; } }); - } - - st.deepEqual( - OwnPropertyKeys(o).sort(), - (hasSymbols ? ['a', 'b', 'c', 'd', 'e'] : ['a', 'b', 'c']).sort(), - 'returns non-enumerable own keys, including accessors and symbols if available' - ); - - st.end(); - }); - - t.end(); -}); diff --git a/node_modules/es-abstract/test/helpers/assertRecord.js b/node_modules/es-abstract/test/helpers/assertRecord.js deleted file mode 100644 index d6a80c2..0000000 --- a/node_modules/es-abstract/test/helpers/assertRecord.js +++ /dev/null @@ -1,60 +0,0 @@ -'use strict'; - -var forEach = require('foreach'); -var debug = require('object-inspect'); - -var assertRecord = require('../../helpers/assertRecord'); -var v = require('./values'); - -module.exports = function assertRecordTests(ES, test) { - test('Property Descriptor', function (t) { - var record = 'Property Descriptor'; - - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { assertRecord(ES.Type, record, 'arg', primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t['throws']( - function () { assertRecord(ES.Type, record, 'arg', { invalid: true }); }, - TypeError, - 'invalid keys not allowed on a Property Descriptor' - ); - - t.doesNotThrow( - function () { assertRecord(ES.Type, record, 'arg', {}); }, - 'empty object is an incomplete Property Descriptor' - ); - - t.doesNotThrow( - function () { assertRecord(ES.Type, record, 'arg', v.accessorDescriptor()); }, - 'accessor descriptor is a Property Descriptor' - ); - - t.doesNotThrow( - function () { assertRecord(ES.Type, record, 'arg', v.mutatorDescriptor()); }, - 'mutator descriptor is a Property Descriptor' - ); - - t.doesNotThrow( - function () { assertRecord(ES.Type, record, 'arg', v.dataDescriptor()); }, - 'data descriptor is a Property Descriptor' - ); - - t.doesNotThrow( - function () { assertRecord(ES.Type, record, 'arg', v.genericDescriptor()); }, - 'generic descriptor is a Property Descriptor' - ); - - t['throws']( - function () { assertRecord(ES.Type, record, 'arg', v.bothDescriptor()); }, - TypeError, - 'a Property Descriptor can not be both a Data and an Accessor Descriptor' - ); - - t.end(); - }); -}; diff --git a/node_modules/es-abstract/test/helpers/defineProperty.js b/node_modules/es-abstract/test/helpers/defineProperty.js deleted file mode 100644 index 8f925be..0000000 --- a/node_modules/es-abstract/test/helpers/defineProperty.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var oDP = Object.defineProperty; -try { - oDP({}, 'a', { value: 1 }); -} catch (e) { - // IE 8 - oDP = null; -} - -module.exports = function defineProperty(O, P, Desc) { - if (oDP) { - return oDP(O, P, Desc); - } - if ((Desc.enumerable && Desc.configurable && Desc.writable) || !(P in O)) { - O[P] = Desc.value; // eslint-disable-line no-param-reassign - return O; - } - - throw new SyntaxError('helper does not yet support this configuration'); -}; -module.exports.oDP = oDP; diff --git a/node_modules/es-abstract/test/helpers/getSymbolDescription.js b/node_modules/es-abstract/test/helpers/getSymbolDescription.js deleted file mode 100644 index b05279d..0000000 --- a/node_modules/es-abstract/test/helpers/getSymbolDescription.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -var test = require('tape'); -var debug = require('object-inspect'); -var forEach = require('foreach'); - -var v = require('./values'); -var getSymbolDescription = require('../../helpers/getSymbolDescription'); -var getInferredName = require('../../helpers/getInferredName'); - -test('getSymbolDescription', function (t) { - t.test('no symbols', { skip: v.hasSymbols }, function (st) { - st['throws']( - getSymbolDescription, - SyntaxError, - 'requires Symbol support' - ); - - st.end(); - }); - - forEach(v.nonSymbolPrimitives.concat(v.objects), function (nonSymbol) { - t['throws']( - function () { getSymbolDescription(nonSymbol); }, - v.hasSymbols ? TypeError : SyntaxError, - debug(nonSymbol) + ' is not a Symbol' - ); - }); - - t.test('with symbols', { skip: !v.hasSymbols }, function (st) { - forEach( - [ - [Symbol(), undefined], - [Symbol(undefined), undefined], - [Symbol(null), 'null'], - [Symbol.iterator, 'Symbol.iterator'], - [Symbol('foo'), 'foo'] - ], - function (pair) { - var sym = pair[0]; - var desc = pair[1]; - st.equal(getSymbolDescription(sym), desc, debug(sym) + ' yields ' + debug(desc)); - } - ); - - st.test('only possible when inference is supported', { skip: !getInferredName }, function (s2t) { - s2t.equal(getSymbolDescription(Symbol('')), '', 'Symbol("") description is empty string'); - s2t.end(); - }); - - st.end(); - }); - - t.end(); -}); diff --git a/node_modules/es-abstract/test/helpers/runManifestTest.js b/node_modules/es-abstract/test/helpers/runManifestTest.js deleted file mode 100644 index 2fdb4f2..0000000 --- a/node_modules/es-abstract/test/helpers/runManifestTest.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var path = require('path'); -var fs = require('fs'); - -var forEach = require('foreach'); -var keys = require('object-keys'); - -module.exports = function runManifestTest(test, ES, edition) { - test('ES' + edition + ' manifest', { skip: !fs.readdirSync }, function (t) { - var files = fs.readdirSync(path.join(__dirname, '../../' + edition), 'utf-8'); - var map = { - AbstractEqualityComparison: 'Abstract Equality Comparison', - AbstractRelationalComparison: 'Abstract Relational Comparison', - StrictEqualityComparison: 'Strict Equality Comparison' - }; - forEach(files, function (file) { - var name = path.basename(file, path.extname(file)); - var actual = ES[map[name] || name]; - var expected = require(path.join(__dirname, '../../' + edition + '/', file)); // eslint-disable-line global-require - t.equal(actual, expected, 'ES["' + name + '"] === ' + file); - }); - var actualCount = keys(ES).length; - t.equal(actualCount, files.length, 'expected ' + files.length + ' files, got ' + actualCount); - t.end(); - }); -}; diff --git a/node_modules/es-abstract/test/helpers/values.js b/node_modules/es-abstract/test/helpers/values.js deleted file mode 100644 index ccef743..0000000 --- a/node_modules/es-abstract/test/helpers/values.js +++ /dev/null @@ -1,121 +0,0 @@ -'use strict'; - -var assign = require('../../helpers/assign'); - -var hasSymbols = require('has-symbols')(); - -var coercibleObject = { valueOf: function () { return 3; }, toString: function () { return 42; } }; -var coercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return 42; } -}; -var valueOfOnlyObject = { valueOf: function () { return 4; }, toString: function () { return {}; } }; -var toStringOnlyObject = { valueOf: function () { return {}; }, toString: function () { return 7; } }; -var uncoercibleObject = { valueOf: function () { return {}; }, toString: function () { return {}; } }; -var uncoercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return function toStrFn() {}; } -}; -var objects = [{}, coercibleObject, coercibleFnObject, toStringOnlyObject, valueOfOnlyObject]; -var nullPrimitives = [undefined, null]; -var nonIntegerNumbers = [-1.3, 0.2, 1.8, 1 / 3]; -var zeroes = [0, -0]; -var infinities = [Infinity, -Infinity]; -var numbers = zeroes.concat([42], infinities, nonIntegerNumbers); -var strings = ['', 'foo', 'a\uD83D\uDCA9c']; -var booleans = [true, false]; -var symbols = hasSymbols ? [Symbol.iterator, Symbol('foo')] : []; -var nonSymbolPrimitives = [].concat(nullPrimitives, booleans, strings, numbers); -var nonNumberPrimitives = [].concat(nullPrimitives, booleans, strings, symbols); -var nonNullPrimitives = [].concat(booleans, strings, numbers, symbols); -var nonUndefinedPrimitives = [].concat(null, nonNullPrimitives); -var nonStrings = [].concat(nullPrimitives, booleans, numbers, symbols, objects); -var primitives = [].concat(nullPrimitives, nonNullPrimitives); -var nonPropertyKeys = [].concat(nullPrimitives, booleans, numbers, objects); -var propertyKeys = [].concat(strings, symbols); -var nonBooleans = [].concat(nullPrimitives, strings, symbols, numbers, objects); -var falsies = [].concat(nullPrimitives, false, '', 0, -0, NaN); -var truthies = [].concat(true, 'foo', 42, symbols, objects); -var timestamps = [].concat(0, 946713600000, 1546329600000); -var nonFunctions = [].concat(primitives, objects, [42]); -var nonArrays = [].concat(nonFunctions); - -var descriptors = { - configurable: function (descriptor) { - return assign(assign({}, descriptor), { '[[Configurable]]': true }); - }, - nonConfigurable: function (descriptor) { - return assign(assign({}, descriptor), { '[[Configurable]]': false }); - }, - enumerable: function (descriptor) { - return assign(assign({}, descriptor), { '[[Enumerable]]': true }); - }, - nonEnumerable: function (descriptor) { - return assign(assign({}, descriptor), { '[[Enumerable]]': false }); - }, - writable: function (descriptor) { - return assign(assign({}, descriptor), { '[[Writable]]': true }); - }, - nonWritable: function (descriptor) { - return assign(assign({}, descriptor), { '[[Writable]]': false }); - } -}; - -module.exports = { - coercibleObject: coercibleObject, - coercibleFnObject: coercibleFnObject, - valueOfOnlyObject: valueOfOnlyObject, - toStringOnlyObject: toStringOnlyObject, - uncoercibleObject: uncoercibleObject, - uncoercibleFnObject: uncoercibleFnObject, - objects: objects, - nonFunctions: nonFunctions, - nonArrays: nonArrays, - nullPrimitives: nullPrimitives, - numbers: numbers, - zeroes: zeroes, - infinities: infinities, - strings: strings, - booleans: booleans, - symbols: symbols, - hasSymbols: hasSymbols, - nonSymbolPrimitives: nonSymbolPrimitives, - nonNumberPrimitives: nonNumberPrimitives, - nonNullPrimitives: nonNullPrimitives, - nonUndefinedPrimitives: nonUndefinedPrimitives, - nonStrings: nonStrings, - nonNumbers: nonNumberPrimitives.concat(objects), - nonIntegerNumbers: nonIntegerNumbers, - primitives: primitives, - nonPropertyKeys: nonPropertyKeys, - propertyKeys: propertyKeys, - nonBooleans: nonBooleans, - falsies: falsies, - truthies: truthies, - timestamps: timestamps, - bothDescriptor: function () { - return { '[[Get]]': function () {}, '[[Value]]': true }; - }, - bothDescriptorWritable: function () { - return descriptors.writable({ '[[Get]]': function () {} }); - }, - accessorDescriptor: function (value) { - return descriptors.enumerable(descriptors.configurable({ - '[[Get]]': function get() { return value; } - })); - }, - mutatorDescriptor: function () { - return descriptors.enumerable(descriptors.configurable({ - '[[Set]]': function () {} - })); - }, - dataDescriptor: function (value) { - return descriptors.nonWritable({ - '[[Value]]': arguments.length > 0 ? value : 42 - }); - }, - genericDescriptor: function () { - return descriptors.configurable(descriptors.nonEnumerable()); - }, - descriptors: descriptors -}; diff --git a/node_modules/es-abstract/test/index.js b/node_modules/es-abstract/test/index.js deleted file mode 100644 index 3f1adba..0000000 --- a/node_modules/es-abstract/test/index.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -var ES = require('../'); -var test = require('tape'); -var keys = require('object-keys'); -var forEach = require('foreach'); - -var ESkeys = keys(ES).sort(); -var ES6keys = keys(ES.ES6).sort(); - -test('exposed properties', function (t) { - t.deepEqual(ESkeys, ES6keys.concat(['ES2019', 'ES2018', 'ES2017', 'ES7', 'ES2016', 'ES6', 'ES2015', 'ES5']).sort(), 'main ES object keys match ES6 keys'); - t.end(); -}); - -test('methods match', function (t) { - forEach(ES6keys, function (key) { - t.equal(ES.ES6[key], ES[key], 'method ' + key + ' on main ES object is ES6 method'); - }); - t.end(); -}); - -require('./GetIntrinsic'); - -require('./helpers/getSymbolDescription'); -require('./helpers/OwnPropertyKeys'); - -require('./es5'); -require('./es6'); -require('./es2015'); -require('./es7'); -require('./es2016'); -require('./es2017'); -require('./es2018'); -require('./es2019'); diff --git a/node_modules/es-abstract/test/tests.js b/node_modules/es-abstract/test/tests.js deleted file mode 100644 index 6dbd40a..0000000 --- a/node_modules/es-abstract/test/tests.js +++ /dev/null @@ -1,4128 +0,0 @@ -'use strict'; - -var test = require('tape'); - -var forEach = require('foreach'); -var is = require('object-is'); -var debug = require('object-inspect'); -var assign = require('object.assign'); -var keys = require('object-keys'); -var has = require('has'); -var arrowFns = require('make-arrow-function').list(); -var hasStrictMode = require('has-strict-mode')(); -var functionsHaveNames = require('functions-have-names')(); -var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); - -var $getProto = require('../helpers/getProto'); -var $setProto = require('../helpers/setProto'); -var defineProperty = require('./helpers/defineProperty'); -var getInferredName = require('../helpers/getInferredName'); -var getOwnPropertyDescriptor = require('../helpers/getOwnPropertyDescriptor'); -var assertRecordTests = require('./helpers/assertRecord'); -var v = require('./helpers/values'); -var diffOps = require('./diffOps'); - -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1; - -var canDistinguishSparseFromUndefined = 0 in [undefined]; // IE 6 - 8 have a bug where this returns false - -var getArraySubclassWithSpeciesConstructor = function getArraySubclass(speciesConstructor) { - var Bar = function Bar() { - var inst = []; - Object.setPrototypeOf(inst, Bar.prototype); - defineProperty(inst, 'constructor', { value: Bar }); - return inst; - }; - Bar.prototype = Object.create(Array.prototype); - Object.setPrototypeOf(Bar, Array); - defineProperty(Bar, Symbol.species, { value: speciesConstructor }); - - return Bar; -}; - -var testIterator = function (t, iterator, expected) { - var resultCount = 0; - var result; - while (result = iterator.next(), !result.done) { // eslint-disable-line no-sequences - t.deepEqual(result, { done: false, value: expected[resultCount] }, 'result ' + resultCount); - resultCount += 1; - } - t.equal(resultCount, expected.length, 'expected ' + expected.length + ', got ' + resultCount); -}; - -var hasSpecies = v.hasSymbols && Symbol.species; - -var hasLastIndex = 'lastIndex' in (/a/).exec('a'); // IE 8 -var hasGroups = 'groups' in (/a/).exec('a'); // modern engines -var kludgeMatch = function kludgeMatch(R, matchObject) { - if (hasGroups) { - assign(matchObject, { groups: matchObject.groups }); - } - if (hasLastIndex) { - assign(matchObject, { lastIndex: R.lastIndex }); - } - return matchObject; -}; - -var testEnumerableOwnNames = function (t, enumerableOwnNames) { - forEach(v.primitives, function (nonObject) { - t['throws']( - function () { enumerableOwnNames(nonObject); }, - debug(nonObject) + ' is not an Object' - ); - }); - - var Child = function Child() { - this.own = {}; - }; - Child.prototype = { - inherited: {} - }; - - var obj = new Child(); - - t.equal('own' in obj, true, 'has "own"'); - t.equal(has(obj, 'own'), true, 'has own "own"'); - t.equal(Object.prototype.propertyIsEnumerable.call(obj, 'own'), true, 'has enumerable "own"'); - - t.equal('inherited' in obj, true, 'has "inherited"'); - t.equal(has(obj, 'inherited'), false, 'has non-own "inherited"'); - t.equal(has(Child.prototype, 'inherited'), true, 'Child.prototype has own "inherited"'); - t.equal(Child.prototype.inherited, obj.inherited, 'Child.prototype.inherited === obj.inherited'); - t.equal(Object.prototype.propertyIsEnumerable.call(Child.prototype, 'inherited'), true, 'has enumerable "inherited"'); - - t.equal('toString' in obj, true, 'has "toString"'); - t.equal(has(obj, 'toString'), false, 'has non-own "toString"'); - t.equal(has(Object.prototype, 'toString'), true, 'Object.prototype has own "toString"'); - t.equal(Object.prototype.toString, obj.toString, 'Object.prototype.toString === obj.toString'); - // eslint-disable-next-line no-useless-call - t.equal(Object.prototype.propertyIsEnumerable.call(Object.prototype, 'toString'), false, 'has non-enumerable "toString"'); - - return obj; -}; - -var es2015 = function ES2015(ES, ops, expectedMissing, skips) { - test('has expected operations', function (t) { - var diff = diffOps(ES, ops, expectedMissing); - - t.deepEqual(diff.extra, [], 'no extra ops'); - - t.deepEqual(diff.missing, [], 'no unexpected missing ops'); - - t.end(); - }); - - test('ToPrimitive', function (t) { - t.test('primitives', function (st) { - var testPrimitive = function (primitive) { - st.ok(is(ES.ToPrimitive(primitive), primitive), debug(primitive) + ' is returned correctly'); - }; - forEach(v.primitives, testPrimitive); - st.end(); - }); - - t.test('objects', function (st) { - st.equal(ES.ToPrimitive(v.coercibleObject), 3, 'coercibleObject with no hint coerces to valueOf'); - st.ok(is(ES.ToPrimitive({}), '[object Object]'), '{} with no hint coerces to Object#toString'); - st.equal(ES.ToPrimitive(v.coercibleObject, Number), 3, 'coercibleObject with hint Number coerces to valueOf'); - st.ok(is(ES.ToPrimitive({}, Number), '[object Object]'), '{} with hint Number coerces to NaN'); - st.equal(ES.ToPrimitive(v.coercibleObject, String), 42, 'coercibleObject with hint String coerces to nonstringified toString'); - st.equal(ES.ToPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); - st.equal(ES.ToPrimitive(v.toStringOnlyObject), 7, 'toStringOnlyObject returns non-stringified toString'); - st.equal(ES.ToPrimitive(v.valueOfOnlyObject), 4, 'valueOfOnlyObject returns valueOf'); - st['throws'](function () { return ES.ToPrimitive(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws a TypeError'); - st.end(); - }); - - t.test('dates', function (st) { - var invalid = new Date(NaN); - st.equal(ES.ToPrimitive(invalid), Date.prototype.toString.call(invalid), 'invalid Date coerces to Date#toString'); - var now = new Date(); - st.equal(ES.ToPrimitive(now), Date.prototype.toString.call(now), 'Date coerces to Date#toString'); - st.end(); - }); - - t.end(); - }); - - test('ToBoolean', function (t) { - t.equal(false, ES.ToBoolean(undefined), 'undefined coerces to false'); - t.equal(false, ES.ToBoolean(null), 'null coerces to false'); - t.equal(false, ES.ToBoolean(false), 'false returns false'); - t.equal(true, ES.ToBoolean(true), 'true returns true'); - - t.test('numbers', function (st) { - forEach(v.zeroes.concat(NaN), function (falsyNumber) { - st.equal(false, ES.ToBoolean(falsyNumber), 'falsy number ' + falsyNumber + ' coerces to false'); - }); - forEach(v.infinities.concat([42, 1]), function (truthyNumber) { - st.equal(true, ES.ToBoolean(truthyNumber), 'truthy number ' + truthyNumber + ' coerces to true'); - }); - - st.end(); - }); - - t.equal(false, ES.ToBoolean(''), 'empty string coerces to false'); - t.equal(true, ES.ToBoolean('foo'), 'nonempty string coerces to true'); - - t.test('objects', function (st) { - forEach(v.objects, function (obj) { - st.equal(true, ES.ToBoolean(obj), 'object coerces to true'); - }); - st.equal(true, ES.ToBoolean(v.uncoercibleObject), 'uncoercibleObject coerces to true'); - - st.end(); - }); - - t.end(); - }); - - test('ToNumber', function (t) { - t.ok(is(NaN, ES.ToNumber(undefined)), 'undefined coerces to NaN'); - t.ok(is(ES.ToNumber(null), 0), 'null coerces to +0'); - t.ok(is(ES.ToNumber(false), 0), 'false coerces to +0'); - t.equal(1, ES.ToNumber(true), 'true coerces to 1'); - - t.test('numbers', function (st) { - st.ok(is(NaN, ES.ToNumber(NaN)), 'NaN returns itself'); - forEach(v.zeroes.concat(v.infinities, 42), function (num) { - st.equal(num, ES.ToNumber(num), num + ' returns itself'); - }); - forEach(['foo', '0', '4a', '2.0', 'Infinity', '-Infinity'], function (numString) { - st.ok(is(+numString, ES.ToNumber(numString)), '"' + numString + '" coerces to ' + Number(numString)); - }); - st.end(); - }); - - t.test('objects', function (st) { - forEach(v.objects, function (object) { - st.ok(is(ES.ToNumber(object), ES.ToNumber(ES.ToPrimitive(object))), 'object ' + object + ' coerces to same as ToPrimitive of object does'); - }); - st['throws'](function () { return ES.ToNumber(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - st.end(); - }); - - t.test('binary literals', function (st) { - st.equal(ES.ToNumber('0b10'), 2, '0b10 is 2'); - st.equal(ES.ToNumber({ toString: function () { return '0b11'; } }), 3, 'Object that toStrings to 0b11 is 3'); - - st.equal(true, is(ES.ToNumber('0b12'), NaN), '0b12 is NaN'); - st.equal(true, is(ES.ToNumber({ toString: function () { return '0b112'; } }), NaN), 'Object that toStrings to 0b112 is NaN'); - st.end(); - }); - - t.test('octal literals', function (st) { - st.equal(ES.ToNumber('0o10'), 8, '0o10 is 8'); - st.equal(ES.ToNumber({ toString: function () { return '0o11'; } }), 9, 'Object that toStrings to 0o11 is 9'); - - st.equal(true, is(ES.ToNumber('0o18'), NaN), '0o18 is NaN'); - st.equal(true, is(ES.ToNumber({ toString: function () { return '0o118'; } }), NaN), 'Object that toStrings to 0o118 is NaN'); - st.end(); - }); - - t.test('signed hex numbers', function (st) { - st.equal(true, is(ES.ToNumber('-0xF'), NaN), '-0xF is NaN'); - st.equal(true, is(ES.ToNumber(' -0xF '), NaN), 'space-padded -0xF is NaN'); - st.equal(true, is(ES.ToNumber('+0xF'), NaN), '+0xF is NaN'); - st.equal(true, is(ES.ToNumber(' +0xF '), NaN), 'space-padded +0xF is NaN'); - - st.end(); - }); - - t.test('trimming of whitespace and non-whitespace characters', function (st) { - var whitespace = ' \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'; - st.equal(0, ES.ToNumber(whitespace + 0 + whitespace), 'whitespace is trimmed'); - - // Zero-width space (zws), next line character (nel), and non-character (bom) are not whitespace. - var nonWhitespaces = { - '\\u0085': '\u0085', - '\\u200b': '\u200b', - '\\ufffe': '\ufffe' - }; - - forEach(nonWhitespaces, function (desc, nonWS) { - st.equal(true, is(ES.ToNumber(nonWS + 0 + nonWS), NaN), 'non-whitespace ' + desc + ' not trimmed'); - }); - - st.end(); - }); - - forEach(v.symbols, function (symbol) { - t['throws']( - function () { ES.ToNumber(symbol); }, - TypeError, - 'Symbols can’t be converted to a Number: ' + debug(symbol) - ); - }); - - t.test('dates', function (st) { - var invalid = new Date(NaN); - st.ok(is(ES.ToNumber(invalid), NaN), 'invalid Date coerces to NaN'); - var now = +new Date(); - st.equal(ES.ToNumber(new Date(now)), now, 'Date coerces to timestamp'); - st.end(); - }); - - t.end(); - }); - - test('ToInteger', function (t) { - t.ok(is(0, ES.ToInteger(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity, 42], function (num) { - t.ok(is(num, ES.ToInteger(num)), num + ' returns itself'); - t.ok(is(-num, ES.ToInteger(-num)), '-' + num + ' returns itself'); - }); - t.equal(3, ES.ToInteger(Math.PI), 'pi returns 3'); - t['throws'](function () { return ES.ToInteger(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.end(); - }); - - test('ToInt32', function (t) { - t.ok(is(0, ES.ToInt32(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToInt32(num)), num + ' returns +0'); - t.ok(is(0, ES.ToInt32(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToInt32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToInt32(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToInt32(0x100000000 - 1), -1), '2^32 - 1 returns -1'); - t.ok(is(ES.ToInt32(0x80000000), -0x80000000), '2^31 returns -2^31'); - t.ok(is(ES.ToInt32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1'); - forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) { - t.ok(is(ES.ToInt32(num), ES.ToInt32(ES.ToUint32(num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for 0x' + num.toString(16)); - t.ok(is(ES.ToInt32(-num), ES.ToInt32(ES.ToUint32(-num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for -0x' + num.toString(16)); - }); - t.end(); - }); - - test('ToUint32', function (t) { - t.ok(is(0, ES.ToUint32(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToUint32(num)), num + ' returns +0'); - t.ok(is(0, ES.ToUint32(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToUint32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToUint32(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToUint32(0x100000000 - 1), 0x100000000 - 1), '2^32 - 1 returns 2^32 - 1'); - t.ok(is(ES.ToUint32(0x80000000), 0x80000000), '2^31 returns 2^31'); - t.ok(is(ES.ToUint32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1'); - forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) { - t.ok(is(ES.ToUint32(num), ES.ToUint32(ES.ToInt32(num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for 0x' + num.toString(16)); - t.ok(is(ES.ToUint32(-num), ES.ToUint32(ES.ToInt32(-num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for -0x' + num.toString(16)); - }); - t.end(); - }); - - test('ToInt16', function (t) { - t.ok(is(0, ES.ToInt16(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToInt16(num)), num + ' returns +0'); - t.ok(is(0, ES.ToInt16(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToInt16(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToInt16(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToInt16(0x100000000 - 1), -1), '2^32 - 1 returns -1'); - t.ok(is(ES.ToInt16(0x80000000), 0), '2^31 returns +0'); - t.ok(is(ES.ToInt16(0x80000000 - 1), -1), '2^31 - 1 returns -1'); - t.ok(is(ES.ToInt16(0x10000), 0), '2^16 returns +0'); - t.ok(is(ES.ToInt16(0x10000 - 1), -1), '2^16 - 1 returns -1'); - t.end(); - }); - - test('ToUint16', function (t) { - t.ok(is(0, ES.ToUint16(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToUint16(num)), num + ' returns +0'); - t.ok(is(0, ES.ToUint16(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToUint16(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToUint16(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToUint16(0x100000000 - 1), 0x10000 - 1), '2^32 - 1 returns 2^16 - 1'); - t.ok(is(ES.ToUint16(0x80000000), 0), '2^31 returns +0'); - t.ok(is(ES.ToUint16(0x80000000 - 1), 0x10000 - 1), '2^31 - 1 returns 2^16 - 1'); - t.ok(is(ES.ToUint16(0x10000), 0), '2^16 returns +0'); - t.ok(is(ES.ToUint16(0x10000 - 1), 0x10000 - 1), '2^16 - 1 returns 2^16 - 1'); - t.end(); - }); - - test('ToInt8', function (t) { - t.ok(is(0, ES.ToInt8(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToInt8(num)), num + ' returns +0'); - t.ok(is(0, ES.ToInt8(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToInt8(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToInt8(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToInt8(0x100000000 - 1), -1), '2^32 - 1 returns -1'); - t.ok(is(ES.ToInt8(0x80000000), 0), '2^31 returns +0'); - t.ok(is(ES.ToInt8(0x80000000 - 1), -1), '2^31 - 1 returns -1'); - t.ok(is(ES.ToInt8(0x10000), 0), '2^16 returns +0'); - t.ok(is(ES.ToInt8(0x10000 - 1), -1), '2^16 - 1 returns -1'); - t.ok(is(ES.ToInt8(0x100), 0), '2^8 returns +0'); - t.ok(is(ES.ToInt8(0x100 - 1), -1), '2^8 - 1 returns -1'); - t.ok(is(ES.ToInt8(0x10), 0x10), '2^4 returns 2^4'); - t.end(); - }); - - test('ToUint8', function (t) { - t.ok(is(0, ES.ToUint8(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToUint8(num)), num + ' returns +0'); - t.ok(is(0, ES.ToUint8(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToUint8(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToUint8(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToUint8(0x100000000 - 1), 0x100 - 1), '2^32 - 1 returns 2^8 - 1'); - t.ok(is(ES.ToUint8(0x80000000), 0), '2^31 returns +0'); - t.ok(is(ES.ToUint8(0x80000000 - 1), 0x100 - 1), '2^31 - 1 returns 2^8 - 1'); - t.ok(is(ES.ToUint8(0x10000), 0), '2^16 returns +0'); - t.ok(is(ES.ToUint8(0x10000 - 1), 0x100 - 1), '2^16 - 1 returns 2^8 - 1'); - t.ok(is(ES.ToUint8(0x100), 0), '2^8 returns +0'); - t.ok(is(ES.ToUint8(0x100 - 1), 0x100 - 1), '2^8 - 1 returns 2^16 - 1'); - t.ok(is(ES.ToUint8(0x10), 0x10), '2^4 returns 2^4'); - t.ok(is(ES.ToUint8(0x10 - 1), 0x10 - 1), '2^4 - 1 returns 2^4 - 1'); - t.end(); - }); - - test('ToUint8Clamp', function (t) { - t.ok(is(0, ES.ToUint8Clamp(NaN)), 'NaN coerces to +0'); - t.ok(is(0, ES.ToUint8Clamp(0)), '+0 returns +0'); - t.ok(is(0, ES.ToUint8Clamp(-0)), '-0 returns +0'); - t.ok(is(0, ES.ToUint8Clamp(-Infinity)), '-Infinity returns +0'); - t['throws'](function () { return ES.ToUint8Clamp(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - forEach([255, 256, 0x100000, Infinity], function (number) { - t.ok(is(255, ES.ToUint8Clamp(number)), number + ' coerces to 255'); - }); - t.equal(1, ES.ToUint8Clamp(1.49), '1.49 coerces to 1'); - t.equal(2, ES.ToUint8Clamp(1.5), '1.5 coerces to 2, because 2 is even'); - t.equal(2, ES.ToUint8Clamp(1.51), '1.51 coerces to 2'); - - t.equal(2, ES.ToUint8Clamp(2.49), '2.49 coerces to 2'); - t.equal(2, ES.ToUint8Clamp(2.5), '2.5 coerces to 2, because 2 is even'); - t.equal(3, ES.ToUint8Clamp(2.51), '2.51 coerces to 3'); - t.end(); - }); - - test('ToString', function (t) { - forEach(v.objects.concat(v.nonSymbolPrimitives), function (item) { - t.equal(ES.ToString(item), String(item), 'ES.ToString(' + debug(item) + ') ToStrings to String(' + debug(item) + ')'); - }); - - t['throws'](function () { return ES.ToString(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - - forEach(v.symbols, function (symbol) { - t['throws'](function () { return ES.ToString(symbol); }, TypeError, debug(symbol) + ' throws'); - }); - t.end(); - }); - - test('ToObject', function (t) { - t['throws'](function () { return ES.ToObject(undefined); }, TypeError, 'undefined throws'); - t['throws'](function () { return ES.ToObject(null); }, TypeError, 'null throws'); - forEach(v.numbers, function (number) { - var obj = ES.ToObject(number); - t.equal(typeof obj, 'object', 'number ' + number + ' coerces to object'); - t.equal(true, obj instanceof Number, 'object of ' + number + ' is Number object'); - t.ok(is(obj.valueOf(), number), 'object of ' + number + ' coerces to ' + number); - }); - t.end(); - }); - - test('RequireObjectCoercible', function (t) { - t.equal(false, 'CheckObjectCoercible' in ES, 'CheckObjectCoercible -> RequireObjectCoercible in ES6'); - t['throws'](function () { return ES.RequireObjectCoercible(undefined); }, TypeError, 'undefined throws'); - t['throws'](function () { return ES.RequireObjectCoercible(null); }, TypeError, 'null throws'); - var isCoercible = function (value) { - t.doesNotThrow(function () { return ES.RequireObjectCoercible(value); }, debug(value) + ' does not throw'); - }; - forEach(v.objects.concat(v.nonNullPrimitives), isCoercible); - t.end(); - }); - - test('IsCallable', function (t) { - t.equal(true, ES.IsCallable(function () {}), 'function is callable'); - var nonCallables = [/a/g, {}, Object.prototype, NaN].concat(v.nonFunctions); - forEach(nonCallables, function (nonCallable) { - t.equal(false, ES.IsCallable(nonCallable), debug(nonCallable) + ' is not callable'); - }); - t.end(); - }); - - test('SameValue', function (t) { - t.equal(true, ES.SameValue(NaN, NaN), 'NaN is SameValue as NaN'); - t.equal(false, ES.SameValue(0, -0), '+0 is not SameValue as -0'); - forEach(v.objects.concat(v.primitives), function (val) { - t.equal(val === val, ES.SameValue(val, val), debug(val) + ' is SameValue to itself'); - }); - t.end(); - }); - - test('SameValueZero', function (t) { - t.equal(true, ES.SameValueZero(NaN, NaN), 'NaN is SameValueZero as NaN'); - t.equal(true, ES.SameValueZero(0, -0), '+0 is SameValueZero as -0'); - forEach(v.objects.concat(v.primitives), function (val) { - t.equal(val === val, ES.SameValueZero(val, val), debug(val) + ' is SameValueZero to itself'); - }); - t.end(); - }); - - test('ToPropertyKey', function (t) { - forEach(v.objects.concat(v.nonSymbolPrimitives), function (value) { - t.equal(ES.ToPropertyKey(value), String(value), 'ToPropertyKey(value) === String(value) for non-Symbols'); - }); - - forEach(v.symbols, function (symbol) { - t.equal( - ES.ToPropertyKey(symbol), - symbol, - 'ToPropertyKey(' + debug(symbol) + ') === ' + debug(symbol) - ); - t.equal( - ES.ToPropertyKey(Object(symbol)), - symbol, - 'ToPropertyKey(' + debug(Object(symbol)) + ') === ' + debug(symbol) - ); - }); - - t.end(); - }); - - test('ToLength', function (t) { - t['throws'](function () { return ES.ToLength(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws a TypeError'); - t.equal(3, ES.ToLength(v.coercibleObject), 'coercibleObject coerces to 3'); - t.equal(42, ES.ToLength('42.5'), '"42.5" coerces to 42'); - t.equal(7, ES.ToLength(7.3), '7.3 coerces to 7'); - forEach([-0, -1, -42, -Infinity], function (negative) { - t.ok(is(0, ES.ToLength(negative)), negative + ' coerces to +0'); - }); - t.equal(MAX_SAFE_INTEGER, ES.ToLength(MAX_SAFE_INTEGER + 1), '2^53 coerces to 2^53 - 1'); - t.equal(MAX_SAFE_INTEGER, ES.ToLength(MAX_SAFE_INTEGER + 3), '2^53 + 2 coerces to 2^53 - 1'); - t.end(); - }); - - test('IsArray', function (t) { - t.equal(true, ES.IsArray([]), '[] is array'); - t.equal(false, ES.IsArray({}), '{} is not array'); - t.equal(false, ES.IsArray({ length: 1, 0: true }), 'arraylike object is not array'); - forEach(v.objects.concat(v.primitives), function (value) { - t.equal(false, ES.IsArray(value), debug(value) + ' is not array'); - }); - t.end(); - }); - - test('IsRegExp', function (t) { - forEach([/a/g, new RegExp('a', 'g')], function (regex) { - t.equal(true, ES.IsRegExp(regex), regex + ' is regex'); - }); - - forEach(v.objects.concat(v.primitives), function (nonRegex) { - t.equal(false, ES.IsRegExp(nonRegex), debug(nonRegex) + ' is not regex'); - }); - - t.test('Symbol.match', { skip: !v.hasSymbols || !Symbol.match }, function (st) { - var obj = {}; - obj[Symbol.match] = true; - st.equal(true, ES.IsRegExp(obj), 'object with truthy Symbol.match is regex'); - - var regex = /a/; - regex[Symbol.match] = false; - st.equal(false, ES.IsRegExp(regex), 'regex with falsy Symbol.match is not regex'); - - st.end(); - }); - - t.end(); - }); - - test('IsPropertyKey', function (t) { - forEach(v.numbers.concat(v.objects), function (notKey) { - t.equal(false, ES.IsPropertyKey(notKey), debug(notKey) + ' is not property key'); - }); - - t.equal(true, ES.IsPropertyKey('foo'), 'string is property key'); - - forEach(v.symbols, function (symbol) { - t.equal(true, ES.IsPropertyKey(symbol), debug(symbol) + ' is property key'); - }); - t.end(); - }); - - test('IsInteger', function (t) { - for (var i = -100; i < 100; i += 10) { - t.equal(true, ES.IsInteger(i), i + ' is integer'); - t.equal(false, ES.IsInteger(i + 0.2), (i + 0.2) + ' is not integer'); - } - t.equal(true, ES.IsInteger(-0), '-0 is integer'); - var notInts = v.nonNumbers.concat(v.nonIntegerNumbers, v.infinities, [NaN, [], new Date()]); - forEach(notInts, function (notInt) { - t.equal(false, ES.IsInteger(notInt), debug(notInt) + ' is not integer'); - }); - t.equal(false, ES.IsInteger(v.uncoercibleObject), 'uncoercibleObject is not integer'); - t.end(); - }); - - test('IsExtensible', function (t) { - forEach(v.objects, function (object) { - t.equal(true, ES.IsExtensible(object), debug(object) + ' object is extensible'); - }); - forEach(v.primitives, function (primitive) { - t.equal(false, ES.IsExtensible(primitive), debug(primitive) + ' is not extensible'); - }); - if (Object.preventExtensions) { - t.equal(false, ES.IsExtensible(Object.preventExtensions({})), 'object with extensions prevented is not extensible'); - } - t.end(); - }); - - test('CanonicalNumericIndexString', function (t) { - var throwsOnNonString = function (notString) { - t['throws']( - function () { return ES.CanonicalNumericIndexString(notString); }, - TypeError, - debug(notString) + ' is not a string' - ); - }; - forEach(v.objects.concat(v.numbers), throwsOnNonString); - t.ok(is(-0, ES.CanonicalNumericIndexString('-0')), '"-0" returns -0'); - for (var i = -50; i < 50; i += 10) { - t.equal(i, ES.CanonicalNumericIndexString(String(i)), '"' + i + '" returns ' + i); - t.equal(undefined, ES.CanonicalNumericIndexString(String(i) + 'a'), '"' + i + 'a" returns undefined'); - } - t.end(); - }); - - test('IsConstructor', function (t) { - t.equal(true, ES.IsConstructor(function () {}), 'function is constructor'); - t.equal(false, ES.IsConstructor(/a/g), 'regex is not constructor'); - forEach(v.objects, function (object) { - t.equal(false, ES.IsConstructor(object), object + ' object is not constructor'); - }); - - try { - var foo = Function('return class Foo {}')(); // eslint-disable-line no-new-func - t.equal(ES.IsConstructor(foo), true, 'class is constructor'); - } catch (e) { - t.comment('SKIP: class syntax not supported.'); - } - t.end(); - }); - - test('Call', function (t) { - var receiver = {}; - var notFuncs = v.nonFunctions.concat([/a/g, new RegExp('a', 'g')]); - t.plan(notFuncs.length + 4); - var throwsIfNotCallable = function (notFunc) { - t['throws']( - function () { return ES.Call(notFunc, receiver); }, - TypeError, - debug(notFunc) + ' (' + typeof notFunc + ') is not callable' - ); - }; - forEach(notFuncs, throwsIfNotCallable); - ES.Call( - function (a, b) { - t.equal(this, receiver, 'context matches expected'); - t.deepEqual([a, b], [1, 2], 'named args are correct'); - t.equal(arguments.length, 3, 'extra argument was passed'); - t.equal(arguments[2], 3, 'extra argument was correct'); - }, - receiver, - [1, 2, 3] - ); - t.end(); - }); - - test('GetV', function (t) { - t['throws'](function () { return ES.GetV({ 7: 7 }, 7); }, TypeError, 'Throws a TypeError if `P` is not a property key'); - var obj = { a: function () {} }; - t.equal(ES.GetV(obj, 'a'), obj.a, 'returns property if it exists'); - t.equal(ES.GetV(obj, 'b'), undefined, 'returns undefiend if property does not exist'); - t.end(); - }); - - test('GetMethod', function (t) { - t['throws'](function () { return ES.GetMethod({ 7: 7 }, 7); }, TypeError, 'Throws a TypeError if `P` is not a property key'); - t.equal(ES.GetMethod({}, 'a'), undefined, 'returns undefined in property is undefined'); - t.equal(ES.GetMethod({ a: null }, 'a'), undefined, 'returns undefined if property is null'); - t.equal(ES.GetMethod({ a: undefined }, 'a'), undefined, 'returns undefined if property is undefined'); - var obj = { a: function () {} }; - t['throws'](function () { ES.GetMethod({ a: 'b' }, 'a'); }, TypeError, 'throws TypeError if property exists and is not callable'); - t.equal(ES.GetMethod(obj, 'a'), obj.a, 'returns property if it is callable'); - t.end(); - }); - - test('Get', function (t) { - t['throws'](function () { return ES.Get('a', 'a'); }, TypeError, 'Throws a TypeError if `O` is not an Object'); - t['throws'](function () { return ES.Get({ 7: 7 }, 7); }, TypeError, 'Throws a TypeError if `P` is not a property key'); - - var value = {}; - t.test('Symbols', { skip: !v.hasSymbols }, function (st) { - var sym = Symbol('sym'); - var obj = {}; - obj[sym] = value; - st.equal(ES.Get(obj, sym), value, 'returns property `P` if it exists on object `O`'); - st.end(); - }); - t.equal(ES.Get({ a: value }, 'a'), value, 'returns property `P` if it exists on object `O`'); - t.end(); - }); - - test('Type', { skip: !v.hasSymbols }, function (t) { - t.equal(ES.Type(Symbol.iterator), 'Symbol', 'Type(Symbol.iterator) is Symbol'); - t.end(); - }); - - test('SpeciesConstructor', function (t) { - t['throws'](function () { ES.SpeciesConstructor(null); }, TypeError); - t['throws'](function () { ES.SpeciesConstructor(undefined); }, TypeError); - - var defaultConstructor = function Foo() {}; - - t.equal( - ES.SpeciesConstructor({ constructor: undefined }, defaultConstructor), - defaultConstructor, - 'undefined constructor returns defaultConstructor' - ); - - t['throws']( - function () { return ES.SpeciesConstructor({ constructor: null }, defaultConstructor); }, - TypeError, - 'non-undefined non-object constructor throws' - ); - - t.test('with Symbol.species', { skip: !hasSpecies }, function (st) { - var Bar = function Bar() {}; - Bar[Symbol.species] = null; - - st.equal( - ES.SpeciesConstructor(new Bar(), defaultConstructor), - defaultConstructor, - 'undefined/null Symbol.species returns default constructor' - ); - - var Baz = function Baz() {}; - Baz[Symbol.species] = Bar; - st.equal( - ES.SpeciesConstructor(new Baz(), defaultConstructor), - Bar, - 'returns Symbol.species constructor value' - ); - - Baz[Symbol.species] = {}; - st['throws']( - function () { ES.SpeciesConstructor(new Baz(), defaultConstructor); }, - TypeError, - 'throws when non-constructor non-null non-undefined species value found' - ); - - st.end(); - }); - - t.end(); - }); - - test('IsPropertyDescriptor', { skip: skips && skips.IsPropertyDescriptor }, function (t) { - forEach(v.nonUndefinedPrimitives, function (primitive) { - t.equal( - ES.IsPropertyDescriptor(primitive), - false, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t.equal(ES.IsPropertyDescriptor({ invalid: true }), false, 'invalid keys not allowed on a Property Descriptor'); - - t.equal(ES.IsPropertyDescriptor({}), true, 'empty object is an incomplete Property Descriptor'); - - t.equal(ES.IsPropertyDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is a Property Descriptor'); - t.equal(ES.IsPropertyDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is a Property Descriptor'); - t.equal(ES.IsPropertyDescriptor(v.dataDescriptor()), true, 'data descriptor is a Property Descriptor'); - t.equal(ES.IsPropertyDescriptor(v.genericDescriptor()), true, 'generic descriptor is a Property Descriptor'); - - t['throws']( - function () { ES.IsPropertyDescriptor(v.bothDescriptor()); }, - TypeError, - 'a Property Descriptor can not be both a Data and an Accessor Descriptor' - ); - - t.end(); - }); - - assertRecordTests(ES, test); - - test('IsAccessorDescriptor', function (t) { - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.IsAccessorDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t.equal(ES.IsAccessorDescriptor(), false, 'no value is not an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(undefined), false, 'undefined value is not an Accessor Descriptor'); - - t.equal(ES.IsAccessorDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(v.dataDescriptor()), false, 'data descriptor is not an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(v.genericDescriptor()), false, 'generic descriptor is not an Accessor Descriptor'); - - t.end(); - }); - - test('IsDataDescriptor', function (t) { - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.IsDataDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t.equal(ES.IsDataDescriptor(), false, 'no value is not a Data Descriptor'); - t.equal(ES.IsDataDescriptor(undefined), false, 'undefined value is not a Data Descriptor'); - - t.equal(ES.IsDataDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a Data Descriptor'); - t.equal(ES.IsDataDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a Data Descriptor'); - t.equal(ES.IsDataDescriptor(v.dataDescriptor()), true, 'data descriptor is a Data Descriptor'); - t.equal(ES.IsDataDescriptor(v.genericDescriptor()), false, 'generic descriptor is not a Data Descriptor'); - - t.end(); - }); - - test('IsGenericDescriptor', function (t) { - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.IsGenericDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t.equal(ES.IsGenericDescriptor(), false, 'no value is not a Data Descriptor'); - t.equal(ES.IsGenericDescriptor(undefined), false, 'undefined value is not a Data Descriptor'); - - t.equal(ES.IsGenericDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a generic Descriptor'); - t.equal(ES.IsGenericDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a generic Descriptor'); - t.equal(ES.IsGenericDescriptor(v.dataDescriptor()), false, 'data descriptor is not a generic Descriptor'); - - t.equal(ES.IsGenericDescriptor(v.genericDescriptor()), true, 'generic descriptor is a generic Descriptor'); - - t.end(); - }); - - test('FromPropertyDescriptor', function (t) { - t.equal(ES.FromPropertyDescriptor(), undefined, 'no value begets undefined'); - t.equal(ES.FromPropertyDescriptor(undefined), undefined, 'undefined value begets undefined'); - - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.FromPropertyDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - var accessor = v.accessorDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(accessor), { - get: accessor['[[Get]]'], - enumerable: !!accessor['[[Enumerable]]'], - configurable: !!accessor['[[Configurable]]'] - }); - - var mutator = v.mutatorDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(mutator), { - set: mutator['[[Set]]'], - enumerable: !!mutator['[[Enumerable]]'], - configurable: !!mutator['[[Configurable]]'] - }); - var data = v.dataDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(data), { - value: data['[[Value]]'], - writable: data['[[Writable]]'] - }); - - t.deepEqual(ES.FromPropertyDescriptor(v.genericDescriptor()), { - enumerable: false, - configurable: true - }); - - t.end(); - }); - - test('ToPropertyDescriptor', function (t) { - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.ToPropertyDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - var accessor = v.accessorDescriptor(); - t.deepEqual(ES.ToPropertyDescriptor({ - get: accessor['[[Get]]'], - enumerable: !!accessor['[[Enumerable]]'], - configurable: !!accessor['[[Configurable]]'] - }), accessor); - - var mutator = v.mutatorDescriptor(); - t.deepEqual(ES.ToPropertyDescriptor({ - set: mutator['[[Set]]'], - enumerable: !!mutator['[[Enumerable]]'], - configurable: !!mutator['[[Configurable]]'] - }), mutator); - - var data = v.dataDescriptor(); - t.deepEqual(ES.ToPropertyDescriptor({ - value: data['[[Value]]'], - writable: data['[[Writable]]'], - configurable: !!data['[[Configurable]]'] - }), assign(data, { '[[Configurable]]': false })); - - var both = v.bothDescriptor(); - t['throws']( - function () { - ES.FromPropertyDescriptor({ get: both['[[Get]]'], value: both['[[Value]]'] }); - }, - TypeError, - 'data and accessor descriptors are mutually exclusive' - ); - - t.end(); - }); - - test('CompletePropertyDescriptor', function (t) { - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.CompletePropertyDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - var generic = v.genericDescriptor(); - t.deepEqual( - ES.CompletePropertyDescriptor(generic), - { - '[[Configurable]]': !!generic['[[Configurable]]'], - '[[Enumerable]]': !!generic['[[Enumerable]]'], - '[[Value]]': undefined, - '[[Writable]]': false - }, - 'completes a Generic Descriptor' - ); - - var data = v.dataDescriptor(); - t.deepEqual( - ES.CompletePropertyDescriptor(data), - { - '[[Configurable]]': !!data['[[Configurable]]'], - '[[Enumerable]]': false, - '[[Value]]': data['[[Value]]'], - '[[Writable]]': !!data['[[Writable]]'] - }, - 'completes a Data Descriptor' - ); - - var accessor = v.accessorDescriptor(); - t.deepEqual( - ES.CompletePropertyDescriptor(accessor), - { - '[[Get]]': accessor['[[Get]]'], - '[[Enumerable]]': !!accessor['[[Enumerable]]'], - '[[Configurable]]': !!accessor['[[Configurable]]'], - '[[Set]]': undefined - }, - 'completes an Accessor Descriptor' - ); - - var mutator = v.mutatorDescriptor(); - t.deepEqual( - ES.CompletePropertyDescriptor(mutator), - { - '[[Set]]': mutator['[[Set]]'], - '[[Enumerable]]': !!mutator['[[Enumerable]]'], - '[[Configurable]]': !!mutator['[[Configurable]]'], - '[[Get]]': undefined - }, - 'completes a mutator Descriptor' - ); - - t['throws']( - function () { ES.CompletePropertyDescriptor(v.bothDescriptor()); }, - TypeError, - 'data and accessor descriptors are mutually exclusive' - ); - - t.end(); - }); - - test('Set', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.Set(primitive, '', null, false); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonKey) { - t['throws']( - function () { ES.Set({}, nonKey, null, false); }, - TypeError, - debug(nonKey) + ' is not a Property Key' - ); - }); - - forEach(v.nonBooleans, function (nonBoolean) { - t['throws']( - function () { ES.Set({}, '', null, nonBoolean); }, - TypeError, - debug(nonBoolean) + ' is not a Boolean' - ); - }); - - var o = {}; - var value = {}; - ES.Set(o, 'key', value, true); - t.deepEqual(o, { key: value }, 'key is set'); - - t.test('nonwritable', { skip: !defineProperty.oDP }, function (st) { - var obj = { a: value }; - defineProperty(obj, 'a', { writable: false }); - - st['throws']( - function () { ES.Set(obj, 'a', value, true); }, - TypeError, - 'can not Set nonwritable property' - ); - - st.doesNotThrow( - function () { ES.Set(obj, 'a', value, false); }, - 'setting Throw to false prevents an exception' - ); - - st.end(); - }); - - t.test('nonconfigurable', { skip: !defineProperty.oDP }, function (st) { - var obj = { a: value }; - defineProperty(obj, 'a', { configurable: false }); - - ES.Set(obj, 'a', value, true); - st.deepEqual(obj, { a: value }, 'key is set'); - - st.end(); - }); - - t.end(); - }); - - test('HasOwnProperty', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.HasOwnProperty(primitive, 'key'); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonKey) { - t['throws']( - function () { ES.HasOwnProperty({}, nonKey); }, - TypeError, - debug(nonKey) + ' is not a Property Key' - ); - }); - - t.equal(ES.HasOwnProperty({}, 'toString'), false, 'inherited properties are not own'); - t.equal( - ES.HasOwnProperty({ toString: 1 }, 'toString'), - true, - 'shadowed inherited own properties are own' - ); - t.equal(ES.HasOwnProperty({ a: 1 }, 'a'), true, 'own properties are own'); - - t.end(); - }); - - test('HasProperty', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.HasProperty(primitive, 'key'); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonKey) { - t['throws']( - function () { ES.HasProperty({}, nonKey); }, - TypeError, - debug(nonKey) + ' is not a Property Key' - ); - }); - - t.equal(ES.HasProperty({}, 'nope'), false, 'object does not have nonexistent properties'); - t.equal(ES.HasProperty({}, 'toString'), true, 'object has inherited properties'); - t.equal( - ES.HasProperty({ toString: 1 }, 'toString'), - true, - 'object has shadowed inherited own properties' - ); - t.equal(ES.HasProperty({ a: 1 }, 'a'), true, 'object has own properties'); - - t.end(); - }); - - test('IsConcatSpreadable', function (t) { - forEach(v.primitives, function (primitive) { - t.equal(ES.IsConcatSpreadable(primitive), false, debug(primitive) + ' is not an Object'); - }); - - var hasSymbolConcatSpreadable = v.hasSymbols && Symbol.isConcatSpreadable; - t.test('Symbol.isConcatSpreadable', { skip: !hasSymbolConcatSpreadable }, function (st) { - forEach(v.falsies, function (falsy) { - var obj = {}; - obj[Symbol.isConcatSpreadable] = falsy; - st.equal( - ES.IsConcatSpreadable(obj), - false, - 'an object with ' + debug(falsy) + ' as Symbol.isConcatSpreadable is not concat spreadable' - ); - }); - - forEach(v.truthies, function (truthy) { - var obj = {}; - obj[Symbol.isConcatSpreadable] = truthy; - st.equal( - ES.IsConcatSpreadable(obj), - true, - 'an object with ' + debug(truthy) + ' as Symbol.isConcatSpreadable is concat spreadable' - ); - }); - - st.end(); - }); - - forEach(v.objects, function (object) { - t.equal( - ES.IsConcatSpreadable(object), - false, - 'non-array without Symbol.isConcatSpreadable is not concat spreadable' - ); - }); - - t.equal(ES.IsConcatSpreadable([]), true, 'arrays are concat spreadable'); - - t.end(); - }); - - test('Invoke', function (t) { - forEach(v.nonPropertyKeys, function (nonKey) { - t['throws']( - function () { ES.Invoke({}, nonKey); }, - TypeError, - debug(nonKey) + ' is not a Property Key' - ); - }); - - t['throws'](function () { ES.Invoke({ o: false }, 'o'); }, TypeError, 'fails on a non-function'); - - t.test('invoked callback', function (st) { - var aValue = {}; - var bValue = {}; - var obj = { - f: function (a) { - st.equal(arguments.length, 2, '2 args passed'); - st.equal(a, aValue, 'first arg is correct'); - st.equal(arguments[1], bValue, 'second arg is correct'); - } - }; - st.plan(3); - ES.Invoke(obj, 'f', aValue, bValue); - }); - - t.end(); - }); - - test('GetIterator', function (t) { - var arr = [1, 2]; - testIterator(t, ES.GetIterator(arr), arr); - - testIterator(t, ES.GetIterator('abc'), 'abc'.split('')); - - t.test('Symbol.iterator', { skip: !v.hasSymbols }, function (st) { - var m = new Map(); - m.set(1, 'a'); - m.set(2, 'b'); - - testIterator(st, ES.GetIterator(m), [[1, 'a'], [2, 'b']]); - - st.end(); - }); - - t.end(); - }); - - test('IteratorNext', { skip: true }); - - test('IteratorComplete', { skip: true }); - - test('IteratorValue', { skip: true }); - - test('IteratorStep', { skip: true }); - - test('IteratorClose', { skip: true }); - - test('CreateIterResultObject', function (t) { - forEach(v.nonBooleans, function (nonBoolean) { - t['throws']( - function () { ES.CreateIterResultObject({}, nonBoolean); }, - TypeError, - '"done" argument must be a boolean; ' + debug(nonBoolean) + ' is not' - ); - }); - - var value = {}; - t.deepEqual( - ES.CreateIterResultObject(value, true), - { value: value, done: true }, - 'creates a "done" iteration result' - ); - t.deepEqual( - ES.CreateIterResultObject(value, false), - { value: value, done: false }, - 'creates a "not done" iteration result' - ); - - t.end(); - }); - - test('RegExpExec', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.RegExpExec(primitive); }, - TypeError, - '"R" argument must be an object; ' + debug(primitive) + ' is not' - ); - }); - - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.RegExpExec({}, nonString); }, - TypeError, - '"S" argument must be a String; ' + debug(nonString) + ' is not' - ); - }); - - t.test('gets and calls a callable "exec"', function (st) { - var str = '123'; - var o = { - exec: function (S) { - st.equal(this, o, '"exec" receiver is R'); - st.equal(S, str, '"exec" argument is S'); - - return null; - } - }; - st.plan(2); - ES.RegExpExec(o, str); - st.end(); - }); - - t.test('throws if a callable "exec" returns a non-null non-object', function (st) { - var str = '123'; - st.plan(v.nonNullPrimitives.length); - forEach(v.nonNullPrimitives, function (nonNullPrimitive) { - st['throws']( - function () { ES.RegExpExec({ exec: function () { return nonNullPrimitive; } }, str); }, - TypeError, - '"exec" method must return `null` or an Object; ' + debug(nonNullPrimitive) + ' is not' - ); - }); - st.end(); - }); - - t.test('actual regex that should match against a string', function (st) { - var S = 'aabc'; - var R = /a/g; - var match1 = ES.RegExpExec(R, S); - var expected1 = assign(['a'], kludgeMatch(R, { index: 0, input: S })); - var match2 = ES.RegExpExec(R, S); - var expected2 = assign(['a'], kludgeMatch(R, { index: 1, input: S })); - var match3 = ES.RegExpExec(R, S); - st.deepEqual(match1, expected1, 'match object 1 is as expected'); - st.deepEqual(match2, expected2, 'match object 2 is as expected'); - st.equal(match3, null, 'match 3 is null as expected'); - st.end(); - }); - - t.test('actual regex that should match against a string, with shadowed "exec"', function (st) { - var S = 'aabc'; - var R = /a/g; - R.exec = undefined; - var match1 = ES.RegExpExec(R, S); - var expected1 = assign(['a'], kludgeMatch(R, { index: 0, input: S })); - var match2 = ES.RegExpExec(R, S); - var expected2 = assign(['a'], kludgeMatch(R, { index: 1, input: S })); - var match3 = ES.RegExpExec(R, S); - st.deepEqual(match1, expected1, 'match object 1 is as expected'); - st.deepEqual(match2, expected2, 'match object 2 is as expected'); - st.equal(match3, null, 'match 3 is null as expected'); - st.end(); - }); - t.end(); - }); - - test('ArraySpeciesCreate', function (t) { - t.test('errors', function (st) { - var testNonNumber = function (nonNumber) { - st['throws']( - function () { ES.ArraySpeciesCreate([], nonNumber); }, - TypeError, - debug(nonNumber) + ' is not a number' - ); - }; - forEach(v.nonNumbers, testNonNumber); - - st['throws']( - function () { ES.ArraySpeciesCreate([], -1); }, - TypeError, - '-1 is not >= 0' - ); - st['throws']( - function () { ES.ArraySpeciesCreate([], -Infinity); }, - TypeError, - '-Infinity is not >= 0' - ); - - var testNonIntegers = function (nonInteger) { - st['throws']( - function () { ES.ArraySpeciesCreate([], nonInteger); }, - TypeError, - debug(nonInteger) + ' is not an integer' - ); - }; - forEach(v.nonIntegerNumbers, testNonIntegers); - - st.end(); - }); - - t.test('works with a non-array', function (st) { - forEach(v.objects.concat(v.primitives), function (nonArray) { - var arr = ES.ArraySpeciesCreate(nonArray, 0); - st.ok(ES.IsArray(arr), 'is an array'); - st.equal(arr.length, 0, 'length is correct'); - st.equal(arr.constructor, Array, 'constructor is correct'); - }); - - st.end(); - }); - - t.test('works with a normal array', function (st) { - var len = 2; - var orig = [1, 2, 3]; - var arr = ES.ArraySpeciesCreate(orig, len); - - st.ok(ES.IsArray(arr), 'is an array'); - st.equal(arr.length, len, 'length is correct'); - st.equal(arr.constructor, orig.constructor, 'constructor is correct'); - - st.end(); - }); - - t.test('-0 length produces +0 length', function (st) { - var len = -0; - st.ok(is(len, -0), '-0 is negative zero'); - st.notOk(is(len, 0), '-0 is not positive zero'); - - var orig = [1, 2, 3]; - var arr = ES.ArraySpeciesCreate(orig, len); - - st.equal(ES.IsArray(arr), true); - st.ok(is(arr.length, 0)); - st.equal(arr.constructor, orig.constructor); - - st.end(); - }); - - t.test('works with species construtor', { skip: !hasSpecies }, function (st) { - var sentinel = {}; - var Foo = function Foo(len) { - this.length = len; - this.sentinel = sentinel; - }; - var Bar = getArraySubclassWithSpeciesConstructor(Foo); - var bar = new Bar(); - - st.equal(ES.IsArray(bar), true, 'Bar instance is an array'); - - var arr = ES.ArraySpeciesCreate(bar, 3); - st.equal(arr.constructor, Foo, 'result used species constructor'); - st.equal(arr.length, 3, 'length property is correct'); - st.equal(arr.sentinel, sentinel, 'Foo constructor was exercised'); - - st.end(); - }); - - t.test('works with null species constructor', { skip: !hasSpecies }, function (st) { - var Bar = getArraySubclassWithSpeciesConstructor(null); - var bar = new Bar(); - - st.equal(ES.IsArray(bar), true, 'Bar instance is an array'); - - var arr = ES.ArraySpeciesCreate(bar, 3); - st.equal(arr.constructor, Array, 'result used default constructor'); - st.equal(arr.length, 3, 'length property is correct'); - - st.end(); - }); - - t.test('works with undefined species constructor', { skip: !hasSpecies }, function (st) { - var Bar = getArraySubclassWithSpeciesConstructor(); - var bar = new Bar(); - - st.equal(ES.IsArray(bar), true, 'Bar instance is an array'); - - var arr = ES.ArraySpeciesCreate(bar, 3); - st.equal(arr.constructor, Array, 'result used default constructor'); - st.equal(arr.length, 3, 'length property is correct'); - - st.end(); - }); - - t.test('throws with object non-construtor species constructor', { skip: !hasSpecies }, function (st) { - forEach(v.objects, function (obj) { - var Bar = getArraySubclassWithSpeciesConstructor(obj); - var bar = new Bar(); - - st.equal(ES.IsArray(bar), true, 'Bar instance is an array'); - - st['throws']( - function () { ES.ArraySpeciesCreate(bar, 3); }, - TypeError, - debug(obj) + ' is not a constructor' - ); - }); - - st.end(); - }); - - t.end(); - }); - - test('CreateDataProperty', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.CreateDataProperty(primitive); }, - TypeError, - debug(primitive) + ' is not an object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.CreateDataProperty({}, nonPropertyKey); }, - TypeError, - debug(nonPropertyKey) + ' is not a property key' - ); - }); - - var sentinel = { id: 'sentinel' }; - var secondSentinel = { id: 'second sentinel' }; - forEach(v.propertyKeys, function (propertyKey) { - var obj = {}; - var status = ES.CreateDataProperty(obj, propertyKey, sentinel); - t.equal(status, true, 'status is true'); - t.equal( - obj[propertyKey], - sentinel, - debug(sentinel) + ' is installed on "' + debug(propertyKey) + '" on the object' - ); - var secondStatus = ES.CreateDataProperty(obj, propertyKey, secondSentinel); - t.equal(secondStatus, true, 'second status is true'); - t.equal( - obj[propertyKey], - secondSentinel, - debug(secondSentinel) + ' is installed on "' + debug(propertyKey) + '" on the object' - ); - - t.test('with defineProperty', { skip: !defineProperty.oDP }, function (st) { - var nonWritable = defineProperty({}, propertyKey, { configurable: true, writable: false }); - - var nonWritableStatus = ES.CreateDataProperty(nonWritable, propertyKey, sentinel); - st.equal(nonWritableStatus, false, 'create data property failed'); - st.notEqual( - nonWritable[propertyKey], - sentinel, - debug(sentinel) + ' is not installed on "' + debug(propertyKey) + '" on the object when key is nonwritable' - ); - - var nonConfigurable = defineProperty({}, propertyKey, { configurable: false, writable: true }); - - var nonConfigurableStatus = ES.CreateDataProperty(nonConfigurable, propertyKey, sentinel); - st.equal(nonConfigurableStatus, false, 'create data property failed'); - st.notEqual( - nonConfigurable[propertyKey], - sentinel, - debug(sentinel) + ' is not installed on "' + debug(propertyKey) + '" on the object when key is nonconfigurable' - ); - st.end(); - }); - }); - - t.end(); - }); - - test('CreateDataPropertyOrThrow', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.CreateDataPropertyOrThrow(primitive); }, - TypeError, - debug(primitive) + ' is not an object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.CreateDataPropertyOrThrow({}, nonPropertyKey); }, - TypeError, - debug(nonPropertyKey) + ' is not a property key' - ); - }); - - var sentinel = {}; - forEach(v.propertyKeys, function (propertyKey) { - var obj = {}; - var status = ES.CreateDataPropertyOrThrow(obj, propertyKey, sentinel); - t.equal(status, true, 'status is true'); - t.equal( - obj[propertyKey], - sentinel, - debug(sentinel) + ' is installed on "' + debug(propertyKey) + '" on the object' - ); - - if (typeof Object.preventExtensions === 'function') { - var notExtensible = {}; - Object.preventExtensions(notExtensible); - - t['throws']( - function () { ES.CreateDataPropertyOrThrow(notExtensible, propertyKey, sentinel); }, - TypeError, - 'can not install ' + debug(propertyKey) + ' on non-extensible object' - ); - t.notEqual( - notExtensible[propertyKey], - sentinel, - debug(sentinel) + ' is not installed on "' + debug(propertyKey) + '" on the object' - ); - } - }); - - t.end(); - }); - - test('ObjectCreate', function (t) { - forEach(v.nonNullPrimitives, function (value) { - t['throws']( - function () { ES.ObjectCreate(value); }, - TypeError, - debug(value) + ' is not null, or an object' - ); - }); - - t.test('proto arg', function (st) { - var Parent = function Parent() {}; - Parent.prototype.foo = {}; - var child = ES.ObjectCreate(Parent.prototype); - st.equal(child instanceof Parent, true, 'child is instanceof Parent'); - st.equal(child.foo, Parent.prototype.foo, 'child inherits properties from Parent.prototype'); - - st.end(); - }); - - t.test('internal slots arg', function (st) { - st.doesNotThrow(function () { ES.ObjectCreate({}, []); }, 'an empty slot list is valid'); - - st['throws']( - function () { ES.ObjectCreate({}, ['a']); }, - SyntaxError, - 'internal slots are not supported' - ); - - st.end(); - }); - - t.test('null proto', { skip: !$setProto }, function (st) { - st.equal('toString' in {}, true, 'normal objects have toString'); - st.equal('toString' in ES.ObjectCreate(null), false, 'makes a null object'); - - st.end(); - }); - - t.test('null proto when no native Object.create', { skip: $setProto }, function (st) { - st['throws']( - function () { ES.ObjectCreate(null); }, - SyntaxError, - 'without a native Object.create, can not create null objects' - ); - - st.end(); - }); - - t.end(); - }); - - test('AdvanceStringIndex', function (t) { - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.AdvanceStringIndex(nonString); }, - TypeError, - '"S" argument must be a String; ' + debug(nonString) + ' is not' - ); - }); - - var notInts = v.nonNumbers.concat( - v.nonIntegerNumbers, - v.infinities, - [NaN, [], new Date(), Math.pow(2, 53), -1] - ); - forEach(notInts, function (nonInt) { - t['throws']( - function () { ES.AdvanceStringIndex('abc', nonInt); }, - TypeError, - '"index" argument must be an integer, ' + debug(nonInt) + ' is not.' - ); - }); - - forEach(v.nonBooleans, function (nonBoolean) { - t['throws']( - function () { ES.AdvanceStringIndex('abc', 0, nonBoolean); }, - TypeError, - debug(nonBoolean) + ' is not a Boolean' - ); - }); - - var str = 'a\uD83D\uDCA9c'; - - t.test('non-unicode mode', function (st) { - for (var i = 0; i < str.length + 2; i += 1) { - st.equal(ES.AdvanceStringIndex(str, i, false), i + 1, i + ' advances to ' + (i + 1)); - } - - st.end(); - }); - - t.test('unicode mode', function (st) { - st.equal(ES.AdvanceStringIndex(str, 0, true), 1, '0 advances to 1'); - st.equal(ES.AdvanceStringIndex(str, 1, true), 3, '1 advances to 3'); - st.equal(ES.AdvanceStringIndex(str, 2, true), 3, '2 advances to 3'); - st.equal(ES.AdvanceStringIndex(str, 3, true), 4, '3 advances to 4'); - st.equal(ES.AdvanceStringIndex(str, 4, true), 5, '4 advances to 5'); - - st.end(); - }); - - t.test('lone surrogates', function (st) { - var halfPoo = 'a\uD83Dc'; - - st.equal(ES.AdvanceStringIndex(halfPoo, 0, true), 1, '0 advances to 1'); - st.equal(ES.AdvanceStringIndex(halfPoo, 1, true), 2, '1 advances to 2'); - st.equal(ES.AdvanceStringIndex(halfPoo, 2, true), 3, '2 advances to 3'); - st.equal(ES.AdvanceStringIndex(halfPoo, 3, true), 4, '3 advances to 4'); - - st.end(); - }); - - t.test('surrogate pairs', function (st) { - var lowestPair = String.fromCharCode('0xD800') + String.fromCharCode('0xDC00'); - var highestPair = String.fromCharCode('0xDBFF') + String.fromCharCode('0xDFFF'); - var poop = String.fromCharCode('0xD83D') + String.fromCharCode('0xDCA9'); - - st.equal(ES.AdvanceStringIndex(lowestPair, 0, true), 2, 'lowest surrogate pair, 0 -> 2'); - st.equal(ES.AdvanceStringIndex(highestPair, 0, true), 2, 'highest surrogate pair, 0 -> 2'); - st.equal(ES.AdvanceStringIndex(poop, 0, true), 2, 'poop, 0 -> 2'); - - st.end(); - }); - - t.end(); - }); - - test('CreateMethodProperty', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.CreateMethodProperty(primitive, 'key'); }, - TypeError, - 'O must be an Object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.CreateMethodProperty({}, nonPropertyKey); }, - TypeError, - debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - t.test('defines correctly', function (st) { - var obj = {}; - var key = 'the key'; - var value = { foo: 'bar' }; - - st.equal(ES.CreateMethodProperty(obj, key, value), true, 'defines property successfully'); - st.test('property descriptor', { skip: !getOwnPropertyDescriptor }, function (s2t) { - s2t.deepEqual( - getOwnPropertyDescriptor(obj, key), - { - configurable: true, - enumerable: false, - value: value, - writable: true - }, - 'sets the correct property descriptor' - ); - - s2t.end(); - }); - st.equal(obj[key], value, 'sets the correct value'); - - st.end(); - }); - - t.test('fails as expected on a frozen object', { skip: !Object.freeze }, function (st) { - var obj = Object.freeze({ foo: 'bar' }); - st['throws']( - function () { ES.CreateMethodProperty(obj, 'foo', { value: 'baz' }); }, - TypeError, - 'nonconfigurable key can not be defined' - ); - - st.end(); - }); - - t.test('fails as expected on a function with a nonconfigurable name', { skip: !functionsHaveNames || functionsHaveConfigurableNames }, function (st) { - st['throws']( - function () { ES.CreateMethodProperty(function () {}, 'name', { value: 'baz' }); }, - TypeError, - 'nonconfigurable function name can not be defined' - ); - st.end(); - }); - - t.end(); - }); - - test('DefinePropertyOrThrow', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.DefinePropertyOrThrow(primitive, 'key', {}); }, - TypeError, - 'O must be an Object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.DefinePropertyOrThrow({}, nonPropertyKey, {}); }, - TypeError, - debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - t.test('defines correctly', function (st) { - var obj = {}; - var key = 'the key'; - var descriptor = { - configurable: true, - enumerable: false, - value: { foo: 'bar' }, - writable: true - }; - - st.equal(ES.DefinePropertyOrThrow(obj, key, descriptor), true, 'defines property successfully'); - st.test('property descriptor', { skip: !getOwnPropertyDescriptor }, function (s2t) { - s2t.deepEqual( - getOwnPropertyDescriptor(obj, key), - descriptor, - 'sets the correct property descriptor' - ); - - s2t.end(); - }); - st.deepEqual(obj[key], descriptor.value, 'sets the correct value'); - - st.end(); - }); - - t.test('fails as expected on a frozen object', { skip: !Object.freeze }, function (st) { - var obj = Object.freeze({ foo: 'bar' }); - st['throws']( - function () { - ES.DefinePropertyOrThrow(obj, 'foo', { configurable: true, value: 'baz' }); - }, - TypeError, - 'nonconfigurable key can not be defined' - ); - - st.end(); - }); - - t.test('fails as expected on a function with a nonconfigurable name', { skip: !functionsHaveNames || functionsHaveConfigurableNames }, function (st) { - st['throws']( - function () { - ES.DefinePropertyOrThrow(function () {}, 'name', { configurable: true, value: 'baz' }); - }, - TypeError, - 'nonconfigurable function name can not be defined' - ); - st.end(); - }); - - t.end(); - }); - - test('DeletePropertyOrThrow', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.DeletePropertyOrThrow(primitive, 'key', {}); }, - TypeError, - 'O must be an Object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.DeletePropertyOrThrow({}, nonPropertyKey, {}); }, - TypeError, - debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - t.test('defines correctly', function (st) { - var obj = { 'the key': 42 }; - var key = 'the key'; - - st.equal(ES.DeletePropertyOrThrow(obj, key), true, 'deletes property successfully'); - st.equal(key in obj, false, 'key is no longer in the object'); - - st.end(); - }); - - t.test('fails as expected on a frozen object', { skip: !Object.freeze }, function (st) { - var obj = Object.freeze({ foo: 'bar' }); - st['throws']( - function () { ES.DeletePropertyOrThrow(obj, 'foo'); }, - TypeError, - 'nonconfigurable key can not be deleted' - ); - - st.end(); - }); - - t.test('fails as expected on a function with a nonconfigurable name', { skip: !functionsHaveNames || functionsHaveConfigurableNames }, function (st) { - st['throws']( - function () { ES.DeletePropertyOrThrow(function () {}, 'name'); }, - TypeError, - 'nonconfigurable function name can not be deleted' - ); - st.end(); - }); - - t.end(); - }); - - test('EnumerableOwnNames', { skip: skips && skips.EnumerableOwnNames }, function (t) { - var obj = testEnumerableOwnNames(t, function (O) { return ES.EnumerableOwnNames(O); }); - - t.deepEqual( - ES.EnumerableOwnNames(obj), - ['own'], - 'returns enumerable own names' - ); - - t.end(); - }); - - test('thisNumberValue', function (t) { - forEach(v.nonNumbers, function (nonNumber) { - t['throws']( - function () { ES.thisNumberValue(nonNumber); }, - TypeError, - debug(nonNumber) + ' is not a Number' - ); - }); - - forEach(v.numbers, function (number) { - t.equal(ES.thisNumberValue(number), number, debug(number) + ' is its own thisNumberValue'); - var obj = Object(number); - t.equal(ES.thisNumberValue(obj), number, debug(obj) + ' is the boxed thisNumberValue'); - }); - - t.end(); - }); - - test('thisBooleanValue', function (t) { - forEach(v.nonBooleans, function (nonBoolean) { - t['throws']( - function () { ES.thisBooleanValue(nonBoolean); }, - TypeError, - debug(nonBoolean) + ' is not a Boolean' - ); - }); - - forEach(v.booleans, function (boolean) { - t.equal(ES.thisBooleanValue(boolean), boolean, debug(boolean) + ' is its own thisBooleanValue'); - var obj = Object(boolean); - t.equal(ES.thisBooleanValue(obj), boolean, debug(obj) + ' is the boxed thisBooleanValue'); - }); - - t.end(); - }); - - test('thisStringValue', function (t) { - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.thisStringValue(nonString); }, - TypeError, - debug(nonString) + ' is not a String' - ); - }); - - forEach(v.strings, function (string) { - t.equal(ES.thisStringValue(string), string, debug(string) + ' is its own thisStringValue'); - var obj = Object(string); - t.equal(ES.thisStringValue(obj), string, debug(obj) + ' is the boxed thisStringValue'); - }); - - t.end(); - }); - - test('thisTimeValue', function (t) { - forEach(v.primitives.concat(v.objects), function (nonDate) { - t['throws']( - function () { ES.thisTimeValue(nonDate); }, - TypeError, - debug(nonDate) + ' is not a Date' - ); - }); - - forEach(v.timestamps, function (timestamp) { - var date = new Date(timestamp); - - t.equal(ES.thisTimeValue(date), timestamp, debug(date) + ' is its own thisTimeValue'); - }); - - t.end(); - }); - - test('SetIntegrityLevel', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.SetIntegrityLevel(primitive); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - t['throws']( - function () { ES.SetIntegrityLevel({}); }, - /^TypeError: Assertion failed: `level` must be `"sealed"` or `"frozen"`$/, - '`level` must be `"sealed"` or `"frozen"`' - ); - - var O = { a: 1 }; - t.test('sealed', { skip: !Object.preventExtensions }, function (st) { - st.equal(ES.SetIntegrityLevel(O, 'sealed'), true); - st['throws']( - function () { O.b = 2; }, - /^TypeError: (Cannot|Can't) add property b, object is not extensible$/, - 'sealing prevent new properties from being added' - ); - O.a = 2; - st.equal(O.a, 2, 'pre-frozen, existing properties are mutable'); - st.end(); - }); - - t.test('frozen', { skip: !Object.freeze }, function (st) { - st.equal(ES.SetIntegrityLevel(O, 'frozen'), true); - st['throws']( - function () { O.a = 3; }, - /^TypeError: Cannot assign to read only property 'a' of /, - 'freezing prevents existing properties from being mutated' - ); - st.end(); - }); - - t.end(); - }); - - test('TestIntegrityLevel', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.TestIntegrityLevel(primitive); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - t['throws']( - function () { ES.TestIntegrityLevel({ a: 1 }); }, - /^TypeError: Assertion failed: `level` must be `"sealed"` or `"frozen"`$/, - '`level` must be `"sealed"` or `"frozen"`' - ); - - t.equal(ES.TestIntegrityLevel({ a: 1 }, 'sealed'), false, 'basic object is not sealed'); - t.equal(ES.TestIntegrityLevel({ a: 1 }, 'frozen'), false, 'basic object is not frozen'); - - t.test('preventExtensions', { skip: !Object.preventExtensions }, function (st) { - var o = Object.preventExtensions({ a: 1 }); - st.equal(ES.TestIntegrityLevel(o, 'sealed'), false, 'nonextensible object is not sealed'); - st.equal(ES.TestIntegrityLevel(o, 'frozen'), false, 'nonextensible object is not frozen'); - - var empty = Object.preventExtensions({}); - st.equal(ES.TestIntegrityLevel(empty, 'sealed'), true, 'empty nonextensible object is sealed'); - st.equal(ES.TestIntegrityLevel(empty, 'frozen'), true, 'empty nonextensible object is frozen'); - st.end(); - }); - - t.test('seal', { skip: !Object.seal }, function (st) { - var o = Object.seal({ a: 1 }); - st.equal(ES.TestIntegrityLevel(o, 'sealed'), true, 'sealed object is sealed'); - st.equal(ES.TestIntegrityLevel(o, 'frozen'), false, 'sealed object is not frozen'); - - var empty = Object.seal({}); - st.equal(ES.TestIntegrityLevel(empty, 'sealed'), true, 'empty sealed object is sealed'); - st.equal(ES.TestIntegrityLevel(empty, 'frozen'), true, 'empty sealed object is frozen'); - - st.end(); - }); - - t.test('freeze', { skip: !Object.freeze }, function (st) { - var o = Object.freeze({ a: 1 }); - st.equal(ES.TestIntegrityLevel(o, 'sealed'), true, 'frozen object is sealed'); - st.equal(ES.TestIntegrityLevel(o, 'frozen'), true, 'frozen object is frozen'); - - var empty = Object.freeze({}); - st.equal(ES.TestIntegrityLevel(empty, 'sealed'), true, 'empty frozen object is sealed'); - st.equal(ES.TestIntegrityLevel(empty, 'frozen'), true, 'empty frozen object is frozen'); - - st.end(); - }); - - t.end(); - }); - - test('OrdinaryHasInstance', function (t) { - forEach(v.nonFunctions, function (nonFunction) { - t.equal(ES.OrdinaryHasInstance(nonFunction, {}), false, debug(nonFunction) + ' is not callable'); - }); - - forEach(v.primitives, function (primitive) { - t.equal(ES.OrdinaryHasInstance(function () {}, primitive), false, debug(primitive) + ' is not an object'); - }); - - var C = function C() {}; - var D = function D() {}; - t.equal(ES.OrdinaryHasInstance(C, new C()), true, 'constructor function has an instance of itself'); - t.equal(ES.OrdinaryHasInstance(C, new D()), false, 'constructor/instance mismatch is false'); - t.equal(ES.OrdinaryHasInstance(D, new C()), false, 'instance/constructor mismatch is false'); - t.equal(ES.OrdinaryHasInstance(C, {}), false, 'plain object is not an instance of a constructor'); - t.equal(ES.OrdinaryHasInstance(Object, {}), true, 'plain object is an instance of Object'); - - t.end(); - }); - - test('OrdinaryHasProperty', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.OrdinaryHasProperty(primitive, ''); }, - TypeError, - debug(primitive) + ' is not an object' - ); - }); - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.OrdinaryHasProperty({}, nonPropertyKey); }, - TypeError, - 'P: ' + debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - t.equal(ES.OrdinaryHasProperty({ a: 1 }, 'a'), true, 'own property is true'); - t.equal(ES.OrdinaryHasProperty({}, 'toString'), true, 'inherited property is true'); - t.equal(ES.OrdinaryHasProperty({}, 'nope'), false, 'absent property is false'); - - t.end(); - }); - - test('InstanceofOperator', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.InstanceofOperator(primitive, function () {}); }, - TypeError, - debug(primitive) + ' is not an object' - ); - }); - - forEach(v.nonFunctions, function (nonFunction) { - t['throws']( - function () { ES.InstanceofOperator({}, nonFunction); }, - TypeError, - debug(nonFunction) + ' is not callable' - ); - }); - - var C = function C() {}; - var D = function D() {}; - - t.equal(ES.InstanceofOperator(new C(), C), true, 'constructor function has an instance of itself'); - t.equal(ES.InstanceofOperator(new D(), C), false, 'constructor/instance mismatch is false'); - t.equal(ES.InstanceofOperator(new C(), D), false, 'instance/constructor mismatch is false'); - t.equal(ES.InstanceofOperator({}, C), false, 'plain object is not an instance of a constructor'); - t.equal(ES.InstanceofOperator({}, Object), true, 'plain object is an instance of Object'); - - t.test('Symbol.hasInstance', { skip: !v.hasSymbols || !Symbol.hasInstance }, function (st) { - st.plan(4); - - var O = {}; - var C2 = function () {}; - st.equal(ES.InstanceofOperator(O, C2), false, 'O is not an instance of C2'); - - defineProperty(C2, Symbol.hasInstance, { - value: function (obj) { - st.equal(this, C2, 'hasInstance receiver is C2'); - st.equal(obj, O, 'hasInstance argument is O'); - - return {}; // testing coercion to boolean - } - }); - - st.equal(ES.InstanceofOperator(O, C2), true, 'O is now an instance of C2'); - - st.end(); - }); - - t.end(); - }); - - test('Abstract Equality Comparison', function (t) { - t.test('same types use ===', function (st) { - forEach(v.primitives.concat(v.objects), function (value) { - st.equal(ES['Abstract Equality Comparison'](value, value), value === value, debug(value) + ' is abstractly equal to itself'); - }); - st.end(); - }); - - t.test('different types coerce', function (st) { - var pairs = [ - [null, undefined], - [3, '3'], - [true, '3'], - [true, 3], - [false, 0], - [false, '0'], - [3, [3]], - ['3', [3]], - [true, [1]], - [false, [0]], - [String(v.coercibleObject), v.coercibleObject], - [Number(String(v.coercibleObject)), v.coercibleObject], - [Number(v.coercibleObject), v.coercibleObject], - [String(Number(v.coercibleObject)), v.coercibleObject] - ]; - forEach(pairs, function (pair) { - var a = pair[0]; - var b = pair[1]; - // eslint-disable-next-line eqeqeq - st.equal(ES['Abstract Equality Comparison'](a, b), a == b, debug(a) + ' == ' + debug(b)); - // eslint-disable-next-line eqeqeq - st.equal(ES['Abstract Equality Comparison'](b, a), b == a, debug(b) + ' == ' + debug(a)); - }); - st.end(); - }); - - t.end(); - }); - - test('Strict Equality Comparison', function (t) { - t.test('same types use ===', function (st) { - forEach(v.primitives.concat(v.objects), function (value) { - st.equal(ES['Strict Equality Comparison'](value, value), value === value, debug(value) + ' is strictly equal to itself'); - }); - st.end(); - }); - - t.test('different types are not ===', function (st) { - var pairs = [ - [null, undefined], - [3, '3'], - [true, '3'], - [true, 3], - [false, 0], - [false, '0'], - [3, [3]], - ['3', [3]], - [true, [1]], - [false, [0]], - [String(v.coercibleObject), v.coercibleObject], - [Number(String(v.coercibleObject)), v.coercibleObject], - [Number(v.coercibleObject), v.coercibleObject], - [String(Number(v.coercibleObject)), v.coercibleObject] - ]; - forEach(pairs, function (pair) { - var a = pair[0]; - var b = pair[1]; - st.equal(ES['Strict Equality Comparison'](a, b), a === b, debug(a) + ' === ' + debug(b)); - st.equal(ES['Strict Equality Comparison'](b, a), b === a, debug(b) + ' === ' + debug(a)); - }); - st.end(); - }); - - t.end(); - }); - - test('Abstract Relational Comparison', function (t) { - t.test('at least one operand is NaN', function (st) { - st.equal(ES['Abstract Relational Comparison'](NaN, {}, true), undefined, 'LeftFirst: first is NaN, returns undefined'); - st.equal(ES['Abstract Relational Comparison']({}, NaN, true), undefined, 'LeftFirst: second is NaN, returns undefined'); - st.equal(ES['Abstract Relational Comparison'](NaN, {}, false), undefined, '!LeftFirst: first is NaN, returns undefined'); - st.equal(ES['Abstract Relational Comparison']({}, NaN, false), undefined, '!LeftFirst: second is NaN, returns undefined'); - st.end(); - }); - - t.equal(ES['Abstract Relational Comparison'](3, 4, true), true, 'LeftFirst: 3 is less than 4'); - t.equal(ES['Abstract Relational Comparison'](4, 3, true), false, 'LeftFirst: 3 is not less than 4'); - t.equal(ES['Abstract Relational Comparison'](3, 4, false), true, '!LeftFirst: 3 is less than 4'); - t.equal(ES['Abstract Relational Comparison'](4, 3, false), false, '!LeftFirst: 3 is not less than 4'); - - t.equal(ES['Abstract Relational Comparison']('3', '4', true), true, 'LeftFirst: "3" is less than "4"'); - t.equal(ES['Abstract Relational Comparison']('4', '3', true), false, 'LeftFirst: "3" is not less than "4"'); - t.equal(ES['Abstract Relational Comparison']('3', '4', false), true, '!LeftFirst: "3" is less than "4"'); - t.equal(ES['Abstract Relational Comparison']('4', '3', false), false, '!LeftFirst: "3" is not less than "4"'); - - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, true), true, 'LeftFirst: coercible object is less than 42'); - t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, true), false, 'LeftFirst: 42 is not less than coercible object'); - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, false), true, '!LeftFirst: coercible object is less than 42'); - t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, false), false, '!LeftFirst: 42 is not less than coercible object'); - - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', true), false, 'LeftFirst: coercible object is not less than "3"'); - t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, true), false, 'LeftFirst: "3" is not less than coercible object'); - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', false), false, '!LeftFirst: coercible object is not less than "3"'); - t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, false), false, '!LeftFirst: "3" is not less than coercible object'); - - t.end(); - }); - - test('ValidateAndApplyPropertyDescriptor', function (t) { - forEach(v.nonUndefinedPrimitives, function (nonUndefinedPrimitive) { - t['throws']( - function () { ES.ValidateAndApplyPropertyDescriptor(nonUndefinedPrimitive, '', false, v.genericDescriptor(), v.genericDescriptor()); }, - TypeError, - 'O: ' + debug(nonUndefinedPrimitive) + ' is not undefined or an Object' - ); - }); - - forEach(v.nonBooleans, function (nonBoolean) { - t['throws']( - function () { - return ES.ValidateAndApplyPropertyDescriptor( - undefined, - null, - nonBoolean, - v.genericDescriptor(), - v.genericDescriptor() - ); - }, - TypeError, - 'extensible: ' + debug(nonBoolean) + ' is not a Boolean' - ); - }); - - forEach(v.primitives, function (primitive) { - // Desc must be a Property Descriptor - t['throws']( - function () { - return ES.ValidateAndApplyPropertyDescriptor( - undefined, - null, - false, - primitive, - v.genericDescriptor() - ); - }, - TypeError, - 'Desc: ' + debug(primitive) + ' is not a Property Descriptor' - ); - }); - - forEach(v.nonUndefinedPrimitives, function (primitive) { - // current must be undefined or a Property Descriptor - t['throws']( - function () { - return ES.ValidateAndApplyPropertyDescriptor( - undefined, - null, - false, - v.genericDescriptor(), - primitive - ); - }, - TypeError, - 'current: ' + debug(primitive) + ' is not a Property Descriptor or undefined' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - // if O is an object, P must be a property key - t['throws']( - function () { - return ES.ValidateAndApplyPropertyDescriptor( - {}, - nonPropertyKey, - false, - v.genericDescriptor(), - v.genericDescriptor() - ); - }, - TypeError, - 'P: ' + debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - t.test('current is undefined', function (st) { - var propertyKey = 'howdy'; - - st.test('generic descriptor', function (s2t) { - var generic = v.genericDescriptor(); - generic['[[Enumerable]]'] = true; - var O = {}; - ES.ValidateAndApplyPropertyDescriptor(undefined, propertyKey, true, generic); - s2t.equal( - ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, false, generic), - false, - 'when extensible is false, nothing happens' - ); - s2t.deepEqual(O, {}, 'no changes applied when O is undefined or extensible is false'); - s2t.equal( - ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, true, generic), - true, - 'operation is successful' - ); - var expected = {}; - expected[propertyKey] = undefined; - s2t.deepEqual(O, expected, 'generic descriptor has been defined as an own data property'); - s2t.end(); - }); - - st.test('data descriptor', function (s2t) { - var data = v.dataDescriptor(); - data['[[Enumerable]]'] = true; - - var O = {}; - s2t.equal( - ES.ValidateAndApplyPropertyDescriptor(undefined, propertyKey, true, data), - true, - 'noop when O is undefined' - ); - s2t.equal( - ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, false, data), - false, - 'when extensible is false, nothing happens' - ); - s2t.deepEqual(O, {}, 'no changes applied when O is undefined or extensible is false'); - s2t.equal( - ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, true, data), - true, - 'operation is successful' - ); - var expected = {}; - expected[propertyKey] = data['[[Value]]']; - s2t.deepEqual(O, expected, 'data descriptor has been defined as an own data property'); - s2t.end(); - }); - - st.test('accessor descriptor', { skip: !defineProperty.oDP }, function (s2t) { - var count = 0; - var accessor = v.accessorDescriptor(); - accessor['[[Enumerable]]'] = true; - accessor['[[Get]]'] = function () { - count += 1; - return count; - }; - - var O = {}; - ES.ValidateAndApplyPropertyDescriptor(undefined, propertyKey, true, accessor); - s2t.equal( - ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, false, accessor), - false, - 'when extensible is false, nothing happens' - ); - s2t.deepEqual(O, {}, 'no changes applied when O is undefined or extensible is false'); - s2t.equal( - ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, true, accessor), - true, - 'operation is successful' - ); - var expected = {}; - expected[propertyKey] = accessor['[[Get]]']() + 1; - s2t.deepEqual(O, expected, 'accessor descriptor has been defined as an own accessor property'); - s2t.end(); - }); - - st.end(); - }); - - t.test('every field in Desc is absent', { skip: 'it is unclear if having no fields qualifies Desc to be a Property Descriptor' }); - - forEach([v.dataDescriptor, v.accessorDescriptor, v.mutatorDescriptor], function (getDescriptor) { - t.equal( - ES.ValidateAndApplyPropertyDescriptor(undefined, 'property key', true, getDescriptor(), getDescriptor()), - true, - 'when Desc and current are the same, early return true' - ); - }); - - t.test('current is nonconfigurable', function (st) { - // note: these must not be generic descriptors, or else the algorithm returns an early true - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.configurable(v.dataDescriptor()), - v.descriptors.nonConfigurable(v.dataDescriptor()) - ), - false, - 'false if Desc is configurable' - ); - - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.enumerable(v.dataDescriptor()), - v.descriptors.nonEnumerable(v.dataDescriptor()) - ), - false, - 'false if Desc is Enumerable and current is not' - ); - - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.nonEnumerable(v.dataDescriptor()), - v.descriptors.enumerable(v.dataDescriptor()) - ), - false, - 'false if Desc is not Enumerable and current is' - ); - - var descLackingEnumerable = v.accessorDescriptor(); - delete descLackingEnumerable['[[Enumerable]]']; - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - descLackingEnumerable, - v.descriptors.enumerable(v.accessorDescriptor()) - ), - true, - 'not false if Desc lacks Enumerable' - ); - - st.end(); - }); - - t.test('Desc and current: one is a data descriptor, one is not', { skip: !defineProperty || !getOwnPropertyDescriptor }, function (st) { - // note: Desc must be configurable if current is nonconfigurable, to hit this branch - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.configurable(v.accessorDescriptor()), - v.descriptors.nonConfigurable(v.dataDescriptor()) - ), - false, - 'false if current (data) is nonconfigurable' - ); - - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.configurable(v.dataDescriptor()), - v.descriptors.nonConfigurable(v.accessorDescriptor()) - ), - false, - 'false if current (not data) is nonconfigurable' - ); - - // one is data and one is not, - // // if current is data, convert to accessor - // // else convert to data - - var startsWithData = { - 'property key': 42 - }; - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - startsWithData, - 'property key', - true, - v.descriptors.enumerable(v.descriptors.configurable(v.accessorDescriptor())), - v.descriptors.enumerable(v.descriptors.configurable(v.dataDescriptor())) - ), - true, - 'operation is successful: current is data, Desc is accessor' - ); - var shouldBeAccessor = getOwnPropertyDescriptor(startsWithData, 'property key'); - st.equal(typeof shouldBeAccessor.get, 'function', 'has a getter'); - - var key = 'property key'; - var startsWithAccessor = {}; - defineProperty(startsWithAccessor, key, { - configurable: true, - enumerable: true, - get: function get() { return 42; } - }); - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - startsWithAccessor, - key, - true, - v.descriptors.enumerable(v.descriptors.configurable(v.dataDescriptor())), - v.descriptors.enumerable(v.descriptors.configurable(v.accessorDescriptor(42))) - ), - true, - 'operation is successful: current is accessor, Desc is data' - ); - var shouldBeData = getOwnPropertyDescriptor(startsWithAccessor, 'property key'); - st.deepEqual(shouldBeData, { configurable: true, enumerable: true, value: 42, writable: false }, 'is a data property'); - - st.end(); - }); - - t.test('Desc and current are both data descriptors', function (st) { - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.writable(v.dataDescriptor()), - v.descriptors.nonWritable(v.descriptors.nonConfigurable(v.dataDescriptor())) - ), - false, - 'false if frozen current and writable Desc' - ); - - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.configurable({ '[[Value]]': 42 }), - v.descriptors.nonWritable({ '[[Value]]': 7 }) - ), - false, - 'false if nonwritable current has a different value than Desc' - ); - - st.end(); - }); - - t.test('current is nonconfigurable; Desc and current are both accessor descriptors', function (st) { - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.mutatorDescriptor(), - v.descriptors.nonConfigurable(v.mutatorDescriptor()) - ), - false, - 'false if both Sets are not equal' - ); - - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.accessorDescriptor(), - v.descriptors.nonConfigurable(v.accessorDescriptor()) - ), - false, - 'false if both Gets are not equal' - ); - - st.end(); - }); - - t.end(); - }); - - test('OrdinaryGetOwnProperty', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.OrdinaryGetOwnProperty(primitive, ''); }, - TypeError, - 'O: ' + debug(primitive) + ' is not an Object' - ); - }); - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.OrdinaryGetOwnProperty({}, nonPropertyKey); }, - TypeError, - 'P: ' + debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - t.equal(ES.OrdinaryGetOwnProperty({}, 'not in the object'), undefined, 'missing property yields undefined'); - t.equal(ES.OrdinaryGetOwnProperty({}, 'toString'), undefined, 'inherited non-own property yields undefined'); - - t.deepEqual( - ES.OrdinaryGetOwnProperty({ a: 1 }, 'a'), - ES.ToPropertyDescriptor({ - configurable: true, - enumerable: true, - value: 1, - writable: true - }), - 'own assigned data property yields expected descriptor' - ); - - t.deepEqual( - ES.OrdinaryGetOwnProperty(/a/, 'lastIndex'), - ES.ToPropertyDescriptor({ - configurable: false, - enumerable: false, - value: 0, - writable: true - }), - 'regex lastIndex yields expected descriptor' - ); - - t.deepEqual( - ES.OrdinaryGetOwnProperty([], 'length'), - ES.ToPropertyDescriptor({ - configurable: false, - enumerable: false, - value: 0, - writable: true - }), - 'array length yields expected descriptor' - ); - - t.deepEqual( - ES.OrdinaryGetOwnProperty(Object.prototype, 'toString'), - ES.ToPropertyDescriptor({ - configurable: true, - enumerable: false, - value: Object.prototype.toString, - writable: true - }), - 'own non-enumerable data property yields expected descriptor' - ); - - t.test('ES5+', { skip: !defineProperty.oDP }, function (st) { - var O = {}; - defineProperty(O, 'foo', { - configurable: false, - enumerable: false, - value: O, - writable: true - }); - - st.deepEqual( - ES.OrdinaryGetOwnProperty(O, 'foo'), - ES.ToPropertyDescriptor({ - configurable: false, - enumerable: false, - value: O, - writable: true - }), - 'defined own property yields expected descriptor' - ); - - st.end(); - }); - - t.end(); - }); - - test('OrdinaryDefineOwnProperty', { skip: !getOwnPropertyDescriptor }, function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.CopyDataProperties(primitive, {}, []); }, - TypeError, - 'O: ' + debug(primitive) + ' is not an Object' - ); - }); - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.OrdinaryDefineOwnProperty({}, nonPropertyKey, v.genericDescriptor()); }, - TypeError, - 'P: ' + debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.OrdinaryDefineOwnProperty(primitive, '', v.genericDescriptor()); }, - TypeError, - 'Desc: ' + debug(primitive) + ' is not a Property Descriptor' - ); - }); - - var O = {}; - var P = 'property key'; - var Desc = v.accessorDescriptor(); - t.equal( - ES.OrdinaryDefineOwnProperty(O, P, Desc), - true, - 'operation is successful' - ); - t.deepEqual( - getOwnPropertyDescriptor(O, P), - ES.FromPropertyDescriptor(ES.CompletePropertyDescriptor(Desc)), - 'expected property descriptor is defined' - ); - - t.end(); - }); - - test('ArrayCreate', function (t) { - forEach(v.nonIntegerNumbers.concat([-1]), function (nonIntegerNumber) { - t['throws']( - function () { ES.ArrayCreate(nonIntegerNumber); }, - TypeError, - 'length must be an integer number >= 0' - ); - }); - - t['throws']( - function () { ES.ArrayCreate(Math.pow(2, 32)); }, - RangeError, - 'length must be < 2**32' - ); - - t.deepEqual(ES.ArrayCreate(-0), [], 'length of -0 creates an empty array'); - t.deepEqual(ES.ArrayCreate(0), [], 'length of +0 creates an empty array'); - // eslint-disable-next-line no-sparse-arrays, comma-spacing - t.deepEqual(ES.ArrayCreate(1), [,], 'length of 1 creates a sparse array of length 1'); - // eslint-disable-next-line no-sparse-arrays, comma-spacing - t.deepEqual(ES.ArrayCreate(2), [,,], 'length of 2 creates a sparse array of length 2'); - - t.test('proto argument', { skip: !$setProto }, function (st) { - var fakeProto = { - push: { toString: function () { return 'not array push'; } } - }; - st.equal(ES.ArrayCreate(0, fakeProto).push, fakeProto.push, 'passing the proto argument works'); - st.end(); - }); - - t.end(); - }); - - test('ArraySetLength', function (t) { - forEach(v.primitives.concat(v.objects), function (nonArray) { - t['throws']( - function () { ES.ArraySetLength(nonArray, 0); }, - TypeError, - 'A: ' + debug(nonArray) + ' is not an Array' - ); - }); - - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.ArraySetLength([], primitive); }, - TypeError, - 'Desc: ' + debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t.test('making length nonwritable', { skip: !getOwnPropertyDescriptor }, function (st) { - var a = []; - ES.ArraySetLength(a, { '[[Writable]]': false }); - st.deepEqual( - getOwnPropertyDescriptor(a, 'length'), - { - configurable: false, - enumerable: false, - value: 0, - writable: false - }, - 'without a value, length becomes nonwritable' - ); - st.end(); - }); - - var arr = []; - ES.ArraySetLength(arr, { '[[Value]]': 7 }); - t.equal(arr.length, 7, 'array now has a length of 7'); - - t.end(); - }); - - test('CreateHTML', function (t) { - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.CreateHTML('', nonString, '', ''); }, - TypeError, - 'tag: ' + debug(nonString) + ' is not a String' - ); - t['throws']( - function () { ES.CreateHTML('', '', nonString, ''); }, - TypeError, - 'attribute: ' + debug(nonString) + ' is not a String' - ); - }); - - t.equal( - ES.CreateHTML( - { toString: function () { return 'the string'; } }, - 'some HTML tag!', - '' - ), - 'the string', - 'works with an empty string attribute value' - ); - - t.equal( - ES.CreateHTML( - { toString: function () { return 'the string'; } }, - 'some HTML tag!', - 'attr', - 'value "with quotes"' - ), - 'the string', - 'works with an attribute, and a value with quotes' - ); - - t.end(); - }); - - test('GetOwnPropertyKeys', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.GetOwnPropertyKeys(primitive, 'String'); }, - TypeError, - 'O: ' + debug(primitive) + ' is not an Object' - ); - }); - - t['throws']( - function () { ES.GetOwnPropertyKeys({}, 'not string or symbol'); }, - TypeError, - 'Type: must be "String" or "Symbol"' - ); - - t.test('Symbols', { skip: !v.hasSymbols }, function (st) { - var O = { a: 1 }; - O[Symbol.iterator] = true; - var s = Symbol('test'); - defineProperty(O, s, { enumerable: false, value: true }); - - st.deepEqual( - ES.GetOwnPropertyKeys(O, 'Symbol'), - [Symbol.iterator, s], - 'works with Symbols, enumerable or not' - ); - - st.end(); - }); - - t.test('non-enumerable names', { skip: !defineProperty.oDP }, function (st) { - var O = { a: 1 }; - defineProperty(O, 'b', { enumerable: false, value: 2 }); - if (v.hasSymbols) { - O[Symbol.iterator] = true; - } - - st.deepEqual( - ES.GetOwnPropertyKeys(O, 'String').sort(), - ['a', 'b'].sort(), - 'works with Strings, enumerable or not' - ); - - st.end(); - }); - - t.deepEqual( - ES.GetOwnPropertyKeys({ a: 1, b: 2 }, 'String').sort(), - ['a', 'b'].sort(), - 'works with enumerable keys' - ); - - t.end(); - }); - - test('SymbolDescriptiveString', function (t) { - forEach(v.nonSymbolPrimitives.concat(v.objects), function (nonSymbol) { - t['throws']( - function () { ES.SymbolDescriptiveString(nonSymbol); }, - TypeError, - debug(nonSymbol) + ' is not a Symbol' - ); - }); - - t.test('Symbols', { skip: !v.hasSymbols }, function (st) { - st.equal(ES.SymbolDescriptiveString(Symbol()), 'Symbol()', 'undefined description'); - st.equal(ES.SymbolDescriptiveString(Symbol('')), 'Symbol()', 'empty string description'); - st.equal(ES.SymbolDescriptiveString(Symbol.iterator), 'Symbol(Symbol.iterator)', 'well-known symbol'); - st.equal(ES.SymbolDescriptiveString(Symbol('foo')), 'Symbol(foo)', 'string description'); - - st.end(); - }); - - t.end(); - }); - - test('GetSubstitution', { skip: skips && skips.GetSubstitution }, function (t) { - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.GetSubstitution(nonString, '', 0, [], ''); }, - TypeError, - '`matched`: ' + debug(nonString) + ' is not a String' - ); - - t['throws']( - function () { ES.GetSubstitution('', nonString, 0, [], ''); }, - TypeError, - '`str`: ' + debug(nonString) + ' is not a String' - ); - - t['throws']( - function () { ES.GetSubstitution('', '', 0, [], nonString); }, - TypeError, - '`replacement`: ' + debug(nonString) + ' is not a String' - ); - - if (canDistinguishSparseFromUndefined || typeof nonString !== 'undefined') { - t['throws']( - function () { ES.GetSubstitution('', '', 0, [nonString], ''); }, - TypeError, - '`captures`: ' + debug([nonString]) + ' is not an Array of strings' - ); - } - }); - - forEach(v.nonIntegerNumbers.concat([-1, -42, -Infinity]), function (nonNonNegativeInteger) { - t['throws']( - function () { ES.GetSubstitution('', '', nonNonNegativeInteger, [], ''); }, - TypeError, - '`position`: ' + debug(nonNonNegativeInteger) + ' is not a non-negative integer' - ); - }); - - forEach(v.nonArrays, function (nonArray) { - t['throws']( - function () { ES.GetSubstitution('', '', 0, nonArray, ''); }, - TypeError, - '`captures`: ' + debug(nonArray) + ' is not an Array' - ); - }); - - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 3, [], '123'), - '123', - 'returns the substitution' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '$$2$'), - '$2$', - 'supports $$, and trailing $' - ); - - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$&<'), - '>abcdef<', - 'supports $&' - ); - - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$`<'), - '><', - 'supports $` at position 0' - ); - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 3, [], '>$`<'), - '>ab<', - 'supports $` at position > 0' - ); - - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 7, [], ">$'<"), - '><', - "supports $' at a position where there's less than `matched.length` chars left" - ); - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 3, [], ">$'<"), - '>ghi<', - "supports $' at a position where there's more than `matched.length` chars left" - ); - - for (var i = 0; i < 100; i += 1) { - var captures = []; - captures[i] = 'test'; - if (i > 0) { - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$' + i + '<'), - '>undefined<', - 'supports $' + i + ' with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$' + i), - '>undefined', - 'supports $' + i + ' at the end of the replacement, with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$' + i + '<'), - '><', - 'supports $' + i + ' with a capture at that index' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$' + i), - '>', - 'supports $' + i + ' at the end of the replacement, with a capture at that index' - ); - } - if (i < 10) { - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$0' + i + '<'), - i === 0 ? '><' : '>undefined<', - 'supports $0' + i + ' with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$0' + i), - i === 0 ? '>' : '>undefined', - 'supports $0' + i + ' at the end of the replacement, with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$0' + i + '<'), - '><', - 'supports $0' + i + ' with a capture at that index' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$0' + i), - '>', - 'supports $0' + i + ' at the end of the replacement, with a capture at that index' - ); - } - } - - t.end(); - }); - - test('SecFromTime', function (t) { - var now = new Date(); - t.equal(ES.SecFromTime(now.getTime()), now.getUTCSeconds(), 'second from Date timestamp matches getUTCSeconds'); - t.end(); - }); - - test('MinFromTime', function (t) { - var now = new Date(); - t.equal(ES.MinFromTime(now.getTime()), now.getUTCMinutes(), 'minute from Date timestamp matches getUTCMinutes'); - t.end(); - }); - - test('HourFromTime', function (t) { - var now = new Date(); - t.equal(ES.HourFromTime(now.getTime()), now.getUTCHours(), 'hour from Date timestamp matches getUTCHours'); - t.end(); - }); - - test('msFromTime', function (t) { - var now = new Date(); - t.equal(ES.msFromTime(now.getTime()), now.getUTCMilliseconds(), 'ms from Date timestamp matches getUTCMilliseconds'); - t.end(); - }); - - var msPerSecond = 1e3; - var msPerMinute = 60 * msPerSecond; - var msPerHour = 60 * msPerMinute; - var msPerDay = 24 * msPerHour; - - test('Day', function (t) { - var time = Date.UTC(2019, 8, 10, 2, 3, 4, 5); - var add = 2.5; - var later = new Date(time + (add * msPerDay)); - - t.equal(ES.Day(later.getTime()), ES.Day(time) + Math.floor(add), 'adding 2.5 days worth of ms, gives a Day delta of 2'); - t.end(); - }); - - test('TimeWithinDay', function (t) { - var time = Date.UTC(2019, 8, 10, 2, 3, 4, 5); - var add = 2.5; - var later = new Date(time + (add * msPerDay)); - - t.equal(ES.TimeWithinDay(later.getTime()), ES.TimeWithinDay(time) + (0.5 * msPerDay), 'adding 2.5 days worth of ms, gives a TimeWithinDay delta of +0.5'); - t.end(); - }); - - test('DayFromYear', function (t) { - t.equal(ES.DayFromYear(2021) - ES.DayFromYear(2020), 366, '2021 is a leap year, has 366 days'); - t.equal(ES.DayFromYear(2020) - ES.DayFromYear(2019), 365, '2020 is not a leap year, has 365 days'); - t.equal(ES.DayFromYear(2019) - ES.DayFromYear(2018), 365, '2019 is not a leap year, has 365 days'); - t.equal(ES.DayFromYear(2018) - ES.DayFromYear(2017), 365, '2018 is not a leap year, has 365 days'); - t.equal(ES.DayFromYear(2017) - ES.DayFromYear(2016), 366, '2017 is a leap year, has 366 days'); - - t.end(); - }); - - test('TimeFromYear', function (t) { - for (var i = 1900; i < 2100; i += 1) { - t.equal(ES.TimeFromYear(i), Date.UTC(i, 0, 1), 'TimeFromYear matches a Date object’s year: ' + i); - } - t.end(); - }); - - test('YearFromTime', function (t) { - for (var i = 1900; i < 2100; i += 1) { - t.equal(ES.YearFromTime(Date.UTC(i, 0, 1)), i, 'YearFromTime matches a Date object’s year on 1/1: ' + i); - t.equal(ES.YearFromTime(Date.UTC(i, 10, 1)), i, 'YearFromTime matches a Date object’s year on 10/1: ' + i); - } - t.end(); - }); - - test('WeekDay', function (t) { - var now = new Date(); - var today = now.getUTCDay(); - for (var i = 0; i < 7; i += 1) { - var weekDay = ES.WeekDay(now.getTime() + (i * msPerDay)); - t.equal(weekDay, (today + i) % 7, i + ' days after today (' + today + '), WeekDay is ' + weekDay); - } - t.end(); - }); - - test('DaysInYear', function (t) { - t.equal(ES.DaysInYear(2021), 365, '2021 is not a leap year'); - t.equal(ES.DaysInYear(2020), 366, '2020 is a leap year'); - t.equal(ES.DaysInYear(2019), 365, '2019 is not a leap year'); - t.equal(ES.DaysInYear(2018), 365, '2018 is not a leap year'); - t.equal(ES.DaysInYear(2017), 365, '2017 is not a leap year'); - t.equal(ES.DaysInYear(2016), 366, '2016 is a leap year'); - - t.end(); - }); - - test('InLeapYear', function (t) { - t.equal(ES.InLeapYear(Date.UTC(2021, 0, 1)), 0, '2021 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2020, 0, 1)), 1, '2020 is a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2019, 0, 1)), 0, '2019 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2018, 0, 1)), 0, '2018 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2017, 0, 1)), 0, '2017 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2016, 0, 1)), 1, '2016 is a leap year'); - - t.end(); - }); - - test('DayWithinYear', function (t) { - t.equal(ES.DayWithinYear(Date.UTC(2019, 0, 1)), 0, '1/1 is the 1st day'); - t.equal(ES.DayWithinYear(Date.UTC(2019, 11, 31)), 364, '12/31 is the 365th day in a non leap year'); - t.equal(ES.DayWithinYear(Date.UTC(2016, 11, 31)), 365, '12/31 is the 366th day in a leap year'); - - t.end(); - }); - - test('MonthFromTime', function (t) { - t.equal(ES.MonthFromTime(Date.UTC(2019, 0, 1)), 0, 'non-leap: 1/1 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 0, 31)), 0, 'non-leap: 1/31 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 1)), 1, 'non-leap: 2/1 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 28)), 1, 'non-leap: 2/28 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 29)), 2, 'non-leap: 2/29 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 2, 1)), 2, 'non-leap: 3/1 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 2, 31)), 2, 'non-leap: 3/31 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 3, 1)), 3, 'non-leap: 4/1 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 3, 30)), 3, 'non-leap: 4/30 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 4, 1)), 4, 'non-leap: 5/1 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 4, 31)), 4, 'non-leap: 5/31 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 5, 1)), 5, 'non-leap: 6/1 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 5, 30)), 5, 'non-leap: 6/30 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 6, 1)), 6, 'non-leap: 7/1 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 6, 31)), 6, 'non-leap: 7/31 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 7, 1)), 7, 'non-leap: 8/1 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 7, 30)), 7, 'non-leap: 8/30 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 8, 1)), 8, 'non-leap: 9/1 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 8, 30)), 8, 'non-leap: 9/30 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 9, 1)), 9, 'non-leap: 10/1 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 9, 31)), 9, 'non-leap: 10/31 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 10, 1)), 10, 'non-leap: 11/1 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 10, 30)), 10, 'non-leap: 11/30 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 11, 1)), 11, 'non-leap: 12/1 gives December'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 11, 31)), 11, 'non-leap: 12/31 gives December'); - - t.equal(ES.MonthFromTime(Date.UTC(2016, 0, 1)), 0, 'leap: 1/1 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 0, 31)), 0, 'leap: 1/31 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 1)), 1, 'leap: 2/1 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 28)), 1, 'leap: 2/28 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 29)), 1, 'leap: 2/29 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 2, 1)), 2, 'leap: 3/1 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 2, 31)), 2, 'leap: 3/31 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 3, 1)), 3, 'leap: 4/1 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 3, 30)), 3, 'leap: 4/30 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 4, 1)), 4, 'leap: 5/1 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 4, 31)), 4, 'leap: 5/31 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 5, 1)), 5, 'leap: 6/1 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 5, 30)), 5, 'leap: 6/30 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 6, 1)), 6, 'leap: 7/1 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 6, 31)), 6, 'leap: 7/31 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 7, 1)), 7, 'leap: 8/1 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 7, 30)), 7, 'leap: 8/30 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 8, 1)), 8, 'leap: 9/1 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 8, 30)), 8, 'leap: 9/30 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 9, 1)), 9, 'leap: 10/1 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 9, 31)), 9, 'leap: 10/31 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 10, 1)), 10, 'leap: 11/1 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 10, 30)), 10, 'leap: 11/30 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 11, 1)), 11, 'leap: 12/1 gives December'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 11, 31)), 11, 'leap: 12/31 gives December'); - t.end(); - }); - - test('DateFromTime', function (t) { - var i; - for (i = 1; i <= 28; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2019, 1, i)), i, '2019.02.' + i + ' is date ' + i); - } - for (i = 1; i <= 29; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2016, 1, i)), i, '2016.02.' + i + ' is date ' + i); - } - for (i = 1; i <= 30; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2019, 8, i)), i, '2019.09.' + i + ' is date ' + i); - } - for (i = 1; i <= 31; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2019, 9, i)), i, '2019.10.' + i + ' is date ' + i); - } - t.end(); - }); - - test('MakeDay', function (t) { - var day2015 = 16687; - t.equal(ES.MakeDay(2015, 8, 9), day2015, '2015.09.09 is day 16687'); - var day2016 = day2015 + 366; // 2016 is a leap year - t.equal(ES.MakeDay(2016, 8, 9), day2016, '2015.09.09 is day 17053'); - var day2017 = day2016 + 365; - t.equal(ES.MakeDay(2017, 8, 9), day2017, '2017.09.09 is day 17418'); - var day2018 = day2017 + 365; - t.equal(ES.MakeDay(2018, 8, 9), day2018, '2018.09.09 is day 17783'); - var day2019 = day2018 + 365; - t.equal(ES.MakeDay(2019, 8, 9), day2019, '2019.09.09 is day 18148'); - t.end(); - }); - - test('MakeDate', function (t) { - forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { - t.ok(is(ES.MakeDate(nonFiniteNumber, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `day`'); - t.ok(is(ES.MakeDate(0, nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `time`'); - }); - t.equal(ES.MakeDate(0, 0), 0, 'zero day and zero time is zero date'); - t.equal(ES.MakeDate(0, 123), 123, 'zero day and nonzero time is a date of the "time"'); - t.equal(ES.MakeDate(1, 0), msPerDay, 'day of 1 and zero time is a date of "ms per day"'); - t.equal(ES.MakeDate(3, 0), 3 * msPerDay, 'day of 3 and zero time is a date of thrice "ms per day"'); - t.equal(ES.MakeDate(1, 123), msPerDay + 123, 'day of 1 and nonzero time is a date of "ms per day" plus the "time"'); - t.equal(ES.MakeDate(3, 123), (3 * msPerDay) + 123, 'day of 3 and nonzero time is a date of thrice "ms per day" plus the "time"'); - - t.end(); - }); - - test('MakeTime', function (t) { - forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { - t.ok(is(ES.MakeTime(nonFiniteNumber, 0, 0, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `hour`'); - t.ok(is(ES.MakeTime(0, nonFiniteNumber, 0, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `min`'); - t.ok(is(ES.MakeTime(0, 0, nonFiniteNumber, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `sec`'); - t.ok(is(ES.MakeTime(0, 0, 0, nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `ms`'); - }); - - t.equal( - ES.MakeTime(1.2, 2.3, 3.4, 4.5), - (1 * msPerHour) + (2 * msPerMinute) + (3 * msPerSecond) + 4, - 'all numbers are converted to integer, multiplied by the right number of ms, and summed' - ); - - t.end(); - }); - - test('TimeClip', function (t) { - forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { - t.ok(is(ES.TimeClip(nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `time`'); - }); - t.ok(is(ES.TimeClip(8.64e15 + 1), NaN), '8.64e15 is the largest magnitude considered "finite"'); - t.ok(is(ES.TimeClip(-8.64e15 - 1), NaN), '-8.64e15 is the largest magnitude considered "finite"'); - - forEach(v.zeroes.concat([-10, 10, +new Date()]), function (time) { - t.looseEqual(ES.TimeClip(time), time, debug(time) + ' is a time of ' + debug(time)); - }); - - t.end(); - }); - - test('modulo', function (t) { - t.equal(3 % 2, 1, '+3 % 2 is +1'); - t.equal(ES.modulo(3, 2), 1, '+3 mod 2 is +1'); - - t.equal(-3 % 2, -1, '-3 % 2 is -1'); - t.equal(ES.modulo(-3, 2), 1, '-3 mod 2 is +1'); - t.end(); - }); - - test('ToDateString', function (t) { - forEach(v.nonNumbers, function (nonNumber) { - t['throws']( - function () { ES.ToDateString(nonNumber); }, - TypeError, - debug(nonNumber) + ' is not a Number' - ); - }); - - t.equal(ES.ToDateString(NaN), 'Invalid Date', 'NaN becomes "Invalid Date"'); - var now = +new Date(); - t.equal(ES.ToDateString(now), Date(now), 'any timestamp becomes `Date(timestamp)`'); - t.end(); - }); - - test('CreateListFromArrayLike', function (t) { - forEach(v.primitives, function (nonObject) { - t['throws']( - function () { ES.CreateListFromArrayLike(nonObject); }, - TypeError, - debug(nonObject) + ' is not an Object' - ); - }); - forEach(v.nonArrays, function (nonArray) { - t['throws']( - function () { ES.CreateListFromArrayLike({}, nonArray); }, - TypeError, - debug(nonArray) + ' is not an Array' - ); - }); - - t.deepEqual( - ES.CreateListFromArrayLike({ length: 2, 0: 'a', 1: 'b', 2: 'c' }), - ['a', 'b'], - 'arraylike stops at the length' - ); - - t.end(); - }); - - test('GetPrototypeFromConstructor', function (t) { - forEach(v.nonFunctions, function (nonFunction) { - t['throws']( - function () { ES.GetPrototypeFromConstructor(nonFunction, '%Array%'); }, - TypeError, - debug(nonFunction) + ' is not a constructor' - ); - }); - - forEach(arrowFns, function (arrowFn) { - t['throws']( - function () { ES.GetPrototypeFromConstructor(arrowFn, '%Array%'); }, - TypeError, - debug(arrowFn) + ' is not a constructor' - ); - }); - - var f = function () {}; - t.equal( - ES.GetPrototypeFromConstructor(f, '%Array.prototype%'), - f.prototype, - 'function with normal `prototype` property returns it' - ); - forEach([true, 'foo', 42], function (truthyPrimitive) { - f.prototype = truthyPrimitive; - t.equal( - ES.GetPrototypeFromConstructor(f, '%Array.prototype%'), - Array.prototype, - 'function with non-object `prototype` property (' + debug(truthyPrimitive) + ') returns default intrinsic' - ); - }); - - t.end(); - }); - - var getNamelessFunction = function () { - var f = Object(function () {}); - try { - delete f.name; - } catch (e) { /**/ } - return f; - }; - - test('SetFunctionName', function (t) { - t.test('non-extensible function', { skip: !Object.preventExtensions }, function (st) { - var f = getNamelessFunction(); - Object.preventExtensions(f); - st['throws']( - function () { ES.SetFunctionName(f, ''); }, - TypeError, - 'throws on a non-extensible function' - ); - st.end(); - }); - - t.test('has an own name property', { skip: !functionsHaveNames }, function (st) { - st['throws']( - function () { ES.SetFunctionName(function g() {}, ''); }, - TypeError, - 'throws if function has an own `name` property' - ); - st.end(); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.SetFunctionName(getNamelessFunction(), nonPropertyKey); }, - TypeError, - debug(nonPropertyKey) + ' is not a Symbol or String' - ); - }); - - t.test('symbols', { skip: !v.hasSymbols || has(getNamelessFunction(), 'name') }, function (st) { - var pairs = [ - [Symbol(), ''], - [Symbol(undefined), ''], - [Symbol(null), '[null]'], - [Symbol(''), getInferredName ? '[]' : ''], - [Symbol.iterator, '[Symbol.iterator]'], - [Symbol('foo'), '[foo]'] - ]; - forEach(pairs, function (pair) { - var sym = pair[0]; - var desc = pair[1]; - var f = getNamelessFunction(); - ES.SetFunctionName(f, sym); - st.equal(f.name, desc, debug(sym) + ' yields a name of ' + debug(desc)); - }); - - st.end(); - }); - - var f = getNamelessFunction(); - t.test('when names are configurable', { skip: !functionsHaveConfigurableNames || has(f, 'name') }, function (st) { - // without prefix - st.notEqual(f.name, 'foo', 'precondition'); - ES.SetFunctionName(f, 'foo'); - st.equal(f.name, 'foo', 'function name is set without a prefix'); - - // with prefix - var g = getNamelessFunction(); - st.notEqual(g.name, 'pre- foo', 'precondition'); - ES.SetFunctionName(g, 'foo', 'pre-'); - st.equal(g.name, 'pre- foo', 'function name is set with a prefix'); - - st.end(); - }); - - t.end(); - }); -}; - -var es2016 = function ES2016(ES, ops, expectedMissing, skips) { - es2015(ES, ops, expectedMissing, skips); - - test('SameValueNonNumber', function (t) { - var willThrow = [ - [3, 4], - [NaN, 4], - [4, ''], - ['abc', true], - [{}, false] - ]; - forEach(willThrow, function (nums) { - t['throws'](function () { return ES.SameValueNonNumber.apply(ES, nums); }, TypeError, 'value must be same type and non-number'); - }); - - forEach(v.objects.concat(v.nonNumberPrimitives), function (val) { - t.equal(val === val, ES.SameValueNonNumber(val, val), debug(val) + ' is SameValueNonNumber to itself'); - }); - - t.end(); - }); - - test('IterableToArrayLike', { skip: skips && skips.IterableToArrayLike }, function (t) { - t.test('custom iterables', { skip: !v.hasSymbols }, function (st) { - var O = {}; - O[Symbol.iterator] = function () { - var i = -1; - return { - next: function () { - i += 1; - return { - done: i >= 5, - value: i - }; - } - }; - }; - st.deepEqual( - ES.IterableToArrayLike(O), - [0, 1, 2, 3, 4], - 'Symbol.iterator method is called and values collected' - ); - - st.end(); - }); - - t.deepEqual(ES.IterableToArrayLike('abc'), ['a', 'b', 'c'], 'a string of code units spreads'); - t.deepEqual(ES.IterableToArrayLike('💩'), ['💩'], 'a string of code points spreads'); - t.deepEqual(ES.IterableToArrayLike('a💩c'), ['a', '💩', 'c'], 'a string of code points and units spreads'); - - var arr = [1, 2, 3]; - t.deepEqual(ES.IterableToArrayLike(arr), arr, 'an array becomes a similar array'); - t.notEqual(ES.IterableToArrayLike(arr), arr, 'an array becomes a different, but similar, array'); - - var O = {}; - t.equal(ES.IterableToArrayLike(O), O, 'a non-iterable non-array non-string object is returned directly'); - - t.end(); - }); - - test('OrdinaryGetPrototypeOf', function (t) { - t.test('values', { skip: !$getProto }, function (st) { - st.equal(ES.OrdinaryGetPrototypeOf([]), Array.prototype, 'array [[Prototype]] is Array.prototype'); - st.equal(ES.OrdinaryGetPrototypeOf({}), Object.prototype, 'object [[Prototype]] is Object.prototype'); - st.equal(ES.OrdinaryGetPrototypeOf(/a/g), RegExp.prototype, 'regex [[Prototype]] is RegExp.prototype'); - st.equal(ES.OrdinaryGetPrototypeOf(Object('')), String.prototype, 'boxed string [[Prototype]] is String.prototype'); - st.equal(ES.OrdinaryGetPrototypeOf(Object(42)), Number.prototype, 'boxed number [[Prototype]] is Number.prototype'); - st.equal(ES.OrdinaryGetPrototypeOf(Object(true)), Boolean.prototype, 'boxed boolean [[Prototype]] is Boolean.prototype'); - if (v.hasSymbols) { - st.equal(ES.OrdinaryGetPrototypeOf(Object(Symbol.iterator)), Symbol.prototype, 'boxed symbol [[Prototype]] is Symbol.prototype'); - } - st.end(); - }); - - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.OrdinaryGetPrototypeOf(primitive); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - t.end(); - }); - - test('OrdinarySetPrototypeOf', { skip: !$getProto || !$setProto }, function (t) { - var a = []; - var proto = {}; - - t.equal(ES.OrdinaryGetPrototypeOf(a), Array.prototype, 'precondition'); - t.equal(ES.OrdinarySetPrototypeOf(a, proto), true, 'setting prototype is successful'); - t.equal(ES.OrdinaryGetPrototypeOf(a), proto, 'postcondition'); - - t.end(); - }); -}; - -var es2017 = function ES2017(ES, ops, expectedMissing, skips) { - es2016(ES, ops, expectedMissing, assign({}, skips, { - EnumerableOwnNames: true, - IterableToArrayLike: true - })); - - test('ToIndex', function (t) { - t.ok(is(ES.ToIndex(), 0), 'no value gives 0'); - t.ok(is(ES.ToIndex(undefined), 0), 'undefined value gives 0'); - - t['throws'](function () { ES.ToIndex(-1); }, RangeError, 'negative numbers throw'); - - t['throws'](function () { ES.ToIndex(MAX_SAFE_INTEGER + 1); }, RangeError, 'too large numbers throw'); - - t.equal(ES.ToIndex(3), 3, 'numbers work'); - t.equal(ES.ToIndex(v.valueOfOnlyObject), 4, 'coercible objects are coerced'); - - t.end(); - }); - - test('EnumerableOwnProperties', { skip: skips && skips.EnumerableOwnProperties }, function (t) { - var obj = testEnumerableOwnNames(t, function (O) { - return ES.EnumerableOwnProperties(O, 'key'); - }); - - t.deepEqual( - ES.EnumerableOwnProperties(obj, 'value'), - [obj.own], - 'returns enumerable own values' - ); - - t.deepEqual( - ES.EnumerableOwnProperties(obj, 'key+value'), - [['own', obj.own]], - 'returns enumerable own entries' - ); - - t.end(); - }); - - test('IterableToList', function (t) { - var customIterator = function () { - var i = -1; - return { - next: function () { - i += 1; - return { - done: i >= 5, - value: i - }; - } - }; - }; - - t.deepEqual( - ES.IterableToList({}, customIterator), - [0, 1, 2, 3, 4], - 'iterator method is called and values collected' - ); - - t.test('Symbol support', { skip: !v.hasSymbols }, function (st) { - st.deepEqual(ES.IterableToList('abc', String.prototype[Symbol.iterator]), ['a', 'b', 'c'], 'a string of code units spreads'); - st.deepEqual(ES.IterableToList('☃', String.prototype[Symbol.iterator]), ['☃'], 'a string of code points spreads'); - - var arr = [1, 2, 3]; - st.deepEqual(ES.IterableToList(arr, arr[Symbol.iterator]), arr, 'an array becomes a similar array'); - st.notEqual(ES.IterableToList(arr, arr[Symbol.iterator]), arr, 'an array becomes a different, but similar, array'); - - st.end(); - }); - - t['throws']( - function () { ES.IterableToList({}, void 0); }, - TypeError, - 'non-function iterator method' - ); - - t.end(); - }); -}; - -var es2018 = function ES2018(ES, ops, expectedMissing, skips) { - es2017(ES, ops, expectedMissing, assign({}, skips, { - EnumerableOwnProperties: true, - GetSubstitution: true, - IsPropertyDescriptor: true - })); - - test('thisSymbolValue', function (t) { - forEach(v.nonSymbolPrimitives.concat(v.objects), function (nonSymbol) { - t['throws']( - function () { ES.thisSymbolValue(nonSymbol); }, - v.hasSymbols ? TypeError : SyntaxError, - debug(nonSymbol) + ' is not a Symbol' - ); - }); - - t.test('no native Symbols', { skip: v.hasSymbols }, function (st) { - forEach(v.objects.concat(v.primitives), function (value) { - st['throws']( - function () { ES.thisSymbolValue(value); }, - SyntaxError, - 'Symbols are not supported' - ); - }); - st.end(); - }); - - t.test('symbol values', { skip: !v.hasSymbols }, function (st) { - forEach(v.symbols, function (symbol) { - st.equal(ES.thisSymbolValue(symbol), symbol, 'Symbol value of ' + debug(symbol) + ' is same symbol'); - - st.equal( - ES.thisSymbolValue(Object(symbol)), - symbol, - 'Symbol value of ' + debug(Object(symbol)) + ' is ' + debug(symbol) - ); - }); - - st.end(); - }); - - t.end(); - }); - - test('IsStringPrefix', function (t) { - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.IsStringPrefix(nonString, 'a'); }, - TypeError, - 'first arg: ' + debug(nonString) + ' is not a string' - ); - t['throws']( - function () { ES.IsStringPrefix('a', nonString); }, - TypeError, - 'second arg: ' + debug(nonString) + ' is not a string' - ); - }); - - forEach(v.strings, function (string) { - t.equal(ES.IsStringPrefix(string, string), true, debug(string) + ' is a prefix of itself'); - - t.equal(ES.IsStringPrefix('', string), true, 'the empty string is a prefix of everything'); - }); - - t.equal(ES.IsStringPrefix('abc', 'abcd'), true, '"abc" is a prefix of "abcd"'); - t.equal(ES.IsStringPrefix('abcd', 'abc'), false, '"abcd" is not a prefix of "abc"'); - - t.equal(ES.IsStringPrefix('a', 'bc'), false, '"a" is not a prefix of "bc"'); - - t.end(); - }); - - test('NumberToString', function (t) { - forEach(v.nonNumbers, function (nonNumber) { - t['throws']( - function () { ES.NumberToString(nonNumber); }, - TypeError, - debug(nonNumber) + ' is not a Number' - ); - }); - - forEach(v.numbers, function (number) { - t.equal(ES.NumberToString(number), String(number), debug(number) + ' stringifies to ' + number); - }); - - t.end(); - }); - - test('CopyDataProperties', function (t) { - t.test('first argument: target', function (st) { - forEach(v.primitives, function (primitive) { - st['throws']( - function () { ES.CopyDataProperties(primitive, {}, []); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - st.end(); - }); - - t.test('second argument: source', function (st) { - var frozenTarget = Object.freeze ? Object.freeze({}) : {}; - forEach(v.nullPrimitives, function (nullish) { - st.equal( - ES.CopyDataProperties(frozenTarget, nullish, []), - frozenTarget, - debug(nullish) + ' "source" yields identical, unmodified target' - ); - }); - - forEach(v.nonNullPrimitives, function (objectCoercible) { - var target = {}; - var result = ES.CopyDataProperties(target, objectCoercible, []); - st.equal(result, target, 'result === target'); - st.deepEqual(keys(result), keys(Object(objectCoercible)), 'target ends up with keys of ' + debug(objectCoercible)); - }); - - st.test('enumerable accessor property', { skip: !defineProperty.oDP }, function (s2t) { - var target = {}; - var source = {}; - defineProperty(source, 'a', { - enumerable: true, - get: function () { return 42; } - }); - var result = ES.CopyDataProperties(target, source, []); - s2t.equal(result, target, 'result === target'); - s2t.deepEqual(result, { a: 42 }, 'target ends up with enumerable accessor of source'); - s2t.end(); - }); - - st.end(); - }); - - t.test('third argument: excludedItems', function (st) { - forEach(v.objects.concat(v.primitives), function (nonArray) { - st['throws']( - function () { ES.CopyDataProperties({}, {}, nonArray); }, - TypeError, - debug(nonArray) + ' is not an Array' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - st['throws']( - function () { ES.CopyDataProperties({}, {}, [nonPropertyKey]); }, - TypeError, - debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - var result = ES.CopyDataProperties({}, { a: 1, b: 2, c: 3 }, ['b']); - st.deepEqual(keys(result).sort(), ['a', 'c'].sort(), 'excluded string keys are excluded'); - - st.test('excluding symbols', { skip: !v.hasSymbols }, function (s2t) { - var source = {}; - forEach(v.symbols, function (symbol) { - source[symbol] = true; - }); - - var includedSymbols = v.symbols.slice(1); - var excludedSymbols = v.symbols.slice(0, 1); - var target = ES.CopyDataProperties({}, source, excludedSymbols); - - forEach(includedSymbols, function (symbol) { - s2t.equal(has(target, symbol), true, debug(symbol) + ' is included'); - }); - - forEach(excludedSymbols, function (symbol) { - s2t.equal(has(target, symbol), false, debug(symbol) + ' is excluded'); - }); - - s2t.end(); - }); - - st.end(); - }); - - t.end(); - }); - - test('PromiseResolve', function (t) { - t.test('Promises unsupported', { skip: typeof Promise === 'function' }, function (st) { - st['throws']( - function () { ES.PromiseResolve(); }, - SyntaxError, - 'Promises are not supported' - ); - st.end(); - }); - - t.test('Promises supported', { skip: typeof Promise !== 'function' }, function (st) { - st.plan(2); - - var a = {}; - var b = {}; - var fulfilled = Promise.resolve(a); - var rejected = Promise.reject(b); - - ES.PromiseResolve(Promise, fulfilled).then(function (x) { - st.equal(x, a, 'fulfilled promise resolves to fulfilled'); - }); - - ES.PromiseResolve(Promise, rejected)['catch'](function (e) { - st.equal(e, b, 'rejected promise resolves to rejected'); - }); - }); - - t.end(); - }); - - test('EnumerableOwnPropertyNames', { skip: skips && skips.EnumerableOwnPropertyNames }, function (t) { - var obj = testEnumerableOwnNames(t, function (O) { - return ES.EnumerableOwnPropertyNames(O, 'key'); - }); - - t.deepEqual( - ES.EnumerableOwnPropertyNames(obj, 'value'), - [obj.own], - 'returns enumerable own values' - ); - - t.deepEqual( - ES.EnumerableOwnPropertyNames(obj, 'key+value'), - [['own', obj.own]], - 'returns enumerable own entries' - ); - - t.end(); - }); - - test('IsPromise', { skip: typeof Promise !== 'function' }, function (t) { - forEach(v.objects.concat(v.primitives), function (nonPromise) { - t.equal(ES.IsPromise(nonPromise), false, debug(nonPromise) + ' is not a Promise'); - }); - - var thenable = { then: Promise.prototype.then }; - t.equal(ES.IsPromise(thenable), false, 'generic thenable is not a Promise'); - - t.equal(ES.IsPromise(Promise.resolve()), true, 'Promise is a Promise'); - - t.end(); - }); - - test('GetSubstitution (ES2018+)', function (t) { - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.GetSubstitution(nonString, '', 0, [], undefined, ''); }, - TypeError, - '`matched`: ' + debug(nonString) + ' is not a String' - ); - - t['throws']( - function () { ES.GetSubstitution('', nonString, 0, [], undefined, ''); }, - TypeError, - '`str`: ' + debug(nonString) + ' is not a String' - ); - - t['throws']( - function () { ES.GetSubstitution('', '', 0, [], undefined, nonString); }, - TypeError, - '`replacement`: ' + debug(nonString) + ' is not a String' - ); - - t['throws']( - function () { ES.GetSubstitution('', '', 0, [nonString], undefined, ''); }, - TypeError, - '`captures`: ' + debug([nonString]) + ' is not an Array of strings' - ); - }); - - forEach(v.nonIntegerNumbers.concat([-1, -42, -Infinity]), function (nonNonNegativeInteger) { - t['throws']( - function () { ES.GetSubstitution('', '', nonNonNegativeInteger, [], undefined, ''); }, - TypeError, - '`position`: ' + debug(nonNonNegativeInteger) + ' is not a non-negative integer' - ); - }); - - forEach(v.nonArrays, function (nonArray) { - t['throws']( - function () { ES.GetSubstitution('', '', 0, nonArray, undefined, ''); }, - TypeError, - '`captures`: ' + debug(nonArray) + ' is not an Array' - ); - }); - - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 3, [], undefined, '123'), - '123', - 'returns the substitution' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '$$2$'), - '$2$', - 'supports $$, and trailing $' - ); - - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$&<'), - '>abcdef<', - 'supports $&' - ); - - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$`<'), - '><', - 'supports $` at position 0' - ); - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 3, [], undefined, '>$`<'), - '>ab<', - 'supports $` at position > 0' - ); - - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 7, [], undefined, ">$'<"), - '><', - "supports $' at a position where there's less than `matched.length` chars left" - ); - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 3, [], undefined, ">$'<"), - '>ghi<', - "supports $' at a position where there's more than `matched.length` chars left" - ); - - for (var i = 0; i < 100; i += 1) { - var captures = []; - captures[i] = 'test'; - if (i > 0) { - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$' + i + '<'), - '>undefined<', - 'supports $' + i + ' with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$' + i), - '>undefined', - 'supports $' + i + ' at the end of the replacement, with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$' + i + '<'), - '><', - 'supports $' + i + ' with a capture at that index' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$' + i), - '>', - 'supports $' + i + ' at the end of the replacement, with a capture at that index' - ); - } - if (i < 10) { - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$0' + i + '<'), - i === 0 ? '><' : '>undefined<', - 'supports $0' + i + ' with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$0' + i), - i === 0 ? '>' : '>undefined', - 'supports $0' + i + ' at the end of the replacement, with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$0' + i + '<'), - '><', - 'supports $0' + i + ' with a capture at that index' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$0' + i), - '>', - 'supports $0' + i + ' at the end of the replacement, with a capture at that index' - ); - } - } - - t.end(); - }); - - test('DateString', function (t) { - forEach(v.nonNumbers.concat(NaN), function (nonNumberOrNaN) { - t['throws']( - function () { ES.DateString(nonNumberOrNaN); }, - TypeError, - debug(nonNumberOrNaN) + ' is not a non-NaN Number' - ); - }); - - t.equal(ES.DateString(Date.UTC(2019, 8, 10, 7, 8, 9)), 'Tue Sep 10 2019'); - t.equal(ES.DateString(Date.UTC(2016, 1, 29, 7, 8, 9)), 'Mon Feb 29 2016'); // leap day - t.end(); - }); - - test('TimeString', function (t) { - forEach(v.nonNumbers.concat(NaN), function (nonNumberOrNaN) { - t['throws']( - function () { ES.TimeString(nonNumberOrNaN); }, - TypeError, - debug(nonNumberOrNaN) + ' is not a non-NaN Number' - ); - }); - - var tv = Date.UTC(2019, 8, 10, 7, 8, 9); - t.equal(ES.TimeString(tv), '07:08:09 GMT'); - t.end(); - }); -}; - -var es2019 = function ES2018(ES, ops, expectedMissing, skips) { - es2018(ES, ops, expectedMissing, assign({}, skips, { - })); - - test('AddEntriesFromIterable', function (t) { - t['throws']( - function () { ES.AddEntriesFromIterable({}, undefined, function () {}); }, - TypeError, - 'iterable must not be undefined' - ); - t['throws']( - function () { ES.AddEntriesFromIterable({}, null, function () {}); }, - TypeError, - 'iterable must not be null' - ); - forEach(v.nonFunctions, function (nonFunction) { - t['throws']( - function () { ES.AddEntriesFromIterable({}, {}, nonFunction); }, - TypeError, - debug(nonFunction) + ' is not a function' - ); - }); - - t.test('Symbol support', { skip: !v.hasSymbols }, function (st) { - st.plan(4); - - var O = {}; - st.equal(ES.AddEntriesFromIterable(O, [], function () {}), O, 'returns the target'); - - var adder = function (key, value) { - st.equal(this, O, 'adder gets proper receiver'); - st.equal(key, 0, 'k is key'); - st.equal(value, 'a', 'v is value'); - }; - ES.AddEntriesFromIterable(O, ['a'].entries(), adder); - - st.end(); - }); - - t.end(); - }); - - test('FlattenIntoArray', function (t) { - t.test('no mapper function', function (st) { - var testDepth = function testDepth(tt, depth, expected) { - var a = []; - var o = [[1], 2, , [[3]], [], 4, [[[[5]]]]]; // eslint-disable-line no-sparse-arrays - ES.FlattenIntoArray(a, o, o.length, 0, depth); - tt.deepEqual(a, expected, 'depth: ' + depth); - }; - - testDepth(st, 1, [1, 2, [3], 4, [[[5]]]]); - testDepth(st, 2, [1, 2, 3, 4, [[5]]]); - testDepth(st, 3, [1, 2, 3, 4, [5]]); - testDepth(st, 4, [1, 2, 3, 4, 5]); - testDepth(st, Infinity, [1, 2, 3, 4, 5]); - st.end(); - }); - - t.test('mapper function', function (st) { - var testMapper = function testMapper(tt, mapper, expected, thisArg) { - var a = []; - var o = [[1], 2, , [[3]], [], 4, [[[[5]]]]]; // eslint-disable-line no-sparse-arrays - ES.FlattenIntoArray(a, o, o.length, 0, 1, mapper, thisArg); - tt.deepEqual(a, expected); - }; - - var double = function double(x) { - return typeof x === 'number' ? 2 * x : x; - }; - testMapper( - st, - double, - [1, 4, [3], 8, [[[5]]]] - ); - var receiver = hasStrictMode ? 42 : Object(42); - testMapper( - st, - function (x) { return [this, double(x)]; }, - [receiver, [1], receiver, 4, receiver, [[3]], receiver, [], receiver, 8, receiver, [[[[5]]]]], - 42 - ); - st.end(); - }); - - t.end(); - }); - - test('TrimString', function (t) { - t.test('non-object string', function (st) { - forEach(v.nullPrimitives, function (nullish) { - st['throws']( - function () { ES.TrimString(nullish); }, - debug(nullish) + ' is not an Object' - ); - }); - st.end(); - }); - - var string = ' \n abc \n '; - t.equal(ES.TrimString(string, 'start'), string.slice(string.indexOf('a'))); - t.equal(ES.TrimString(string, 'end'), string.slice(0, string.lastIndexOf('c') + 1)); - t.equal(ES.TrimString(string, 'start+end'), string.slice(string.indexOf('a'), string.lastIndexOf('c') + 1)); - - t.end(); - }); -}; - -module.exports = { - es2015: es2015, - es2016: es2016, - es2017: es2017, - es2018: es2018, - es2019: es2019 -}; diff --git a/node_modules/es-to-primitive/.eslintrc b/node_modules/es-to-primitive/.eslintrc deleted file mode 100644 index b6639b9..0000000 --- a/node_modules/es-to-primitive/.eslintrc +++ /dev/null @@ -1,22 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "complexity": [2, 14], - "func-name-matching": 0, - "id-length": [2, { "min": 1, "max": 24, "properties": "never" }], - "max-statements": [2, 20], - "new-cap": [2, { "capIsNewExceptions": ["GetMethod"] }] - }, - - "overrides": [ - { - "files": "test/**", - "rules": { - "max-lines-per-function": [2, { "max": 68 }], - }, - } - ], -} diff --git a/node_modules/es-to-primitive/.github/FUNDING.yml b/node_modules/es-to-primitive/.github/FUNDING.yml deleted file mode 100644 index 9f928ae..0000000 --- a/node_modules/es-to-primitive/.github/FUNDING.yml +++ /dev/null @@ -1,12 +0,0 @@ -# These are supported funding model platforms - -github: [ljharb] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: npm/es-to-primitive -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/es-to-primitive/.travis.yml b/node_modules/es-to-primitive/.travis.yml deleted file mode 100644 index d4c5a84..0000000 --- a/node_modules/es-to-primitive/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -version: ~> 1.0 -language: node_js -cache: - directories: - - "$(nvm cache dir)" -os: - - linux -import: - - ljharb/travis-ci:node/all.yml - - ljharb/travis-ci:node/pretest.yml - - ljharb/travis-ci:node/posttest.yml - - ljharb/travis-ci:node/coverage.yml -matrix: - allow_failures: - - env: COVERAGE=true diff --git a/node_modules/es-to-primitive/CHANGELOG.md b/node_modules/es-to-primitive/CHANGELOG.md deleted file mode 100644 index 0a5dda7..0000000 --- a/node_modules/es-to-primitive/CHANGELOG.md +++ /dev/null @@ -1,49 +0,0 @@ -1.2.1 / 2019-11-08 -================= - * [readme] remove testling URLs - * [meta] add `funding` field - * [meta] create FUNDING.yml - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `replace`, `semver`, `tape`, `function.prototype.name` - * [Tests] use shared travis-ci configs - * [Tests] Add es5 tests for `symbol` types (#45) - * [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops - * [Tests] remove `jscs` - -1.2.0 / 2018-09-27 -================= - * [New] create ES2015 entry point/property, to replace ES6 - * [Fix] Ensure optional arguments are not part of the length (#29) - * [Deps] update `is-callable` - * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`, `object-inspect`, `replace` - * [Tests] avoid util.inspect bug with `new Date(NaN)` on node v6.0 and v6.1. - * [Tests] up to `node` `v10.11`, `v9.11`, `v8.12`, `v6.14`, `v4.9` - -1.1.1 / 2016-01-03 -================= - * [Fix: ES5] fix coercion logic: ES5’s ToPrimitive does not coerce any primitive value, regardless of hint (#2) - -1.1.0 / 2015-12-27 -================= - * [New] add `Symbol.toPrimitive` support - * [Deps] update `is-callable`, `is-date-object` - * [Dev Deps] update `eslint`, `tape`, `semver`, `jscs`, `covert`, `nsp`, `@ljharb/eslint-config` - * [Dev Deps] remove unused deps - * [Tests] up to `node` `v5.3` - * [Tests] fix npm upgrades on older node versions - * [Tests] fix testling - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - -1.0.1 / 2016-01-03 -================= - * [Fix: ES5] fix coercion logic: ES5’s ToPrimitive does not coerce any primitive value, regardless of hint (#2) - * [Deps] update `is-callable`, `is-date-object` - * [Dev Deps] update `eslint`, `tape`, `semver`, `jscs`, `covert`, `nsp`, `@ljharb/eslint-config` - * [Dev Deps] remove unused deps - * [Tests] up to `node` `v5.3` - * [Tests] fix npm upgrades on older node versions - * [Tests] fix testling - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - -1.0.0 / 2015-03-19 -================= - * Initial release. diff --git a/node_modules/es-to-primitive/LICENSE b/node_modules/es-to-primitive/LICENSE deleted file mode 100644 index b43df44..0000000 --- a/node_modules/es-to-primitive/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Jordan Harband - -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/es-to-primitive/Makefile b/node_modules/es-to-primitive/Makefile deleted file mode 100644 index b9e4fe1..0000000 --- a/node_modules/es-to-primitive/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. -$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) - - # The files that need updating when incrementing the version number. -VERSIONED_FILES := *.js *.json README* - - -# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. -# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment -# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. -export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") -UTILS := semver -# Make sure that all required utilities can be located. -UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) - -# Default target (by virtue of being the first non '.'-prefixed in the file). -.PHONY: _no-target-specified -_no-target-specified: - $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) - -# Lists all targets defined in this makefile. -.PHONY: list -list: - @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort - -# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). -.PHONY: test -test: - @npm test - -.PHONY: _ensure-tag -_ensure-tag: -ifndef TAG - $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) -endif - -CHANGELOG_ERROR = $(error No CHANGELOG specified) -.PHONY: _ensure-changelog -_ensure-changelog: - @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) - -# Ensures that the git workspace is clean. -.PHONY: _ensure-clean -_ensure-clean: - @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } - -# Makes a release; invoke with `make TAG= release`. -.PHONY: release -release: _ensure-tag _ensure-changelog _ensure-clean - @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ - new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ - if printf "$$new_ver" | command grep -q '^[0-9]'; then \ - semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ - semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ - else \ - new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ - fi; \ - printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ - replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ - git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ - git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/node_modules/es-to-primitive/README.md b/node_modules/es-to-primitive/README.md deleted file mode 100644 index 5ce322b..0000000 --- a/node_modules/es-to-primitive/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# es-to-primitive [![Version Badge][npm-version-svg]][package-url] - -[![Build Status][travis-svg]][travis-url] -[![dependency status][deps-svg]][deps-url] -[![dev dependency status][dev-deps-svg]][dev-deps-url] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][npm-badge-png]][package-url] - -ECMAScript “ToPrimitive” algorithm. Provides ES5 and ES2015 versions. -When different versions of the spec conflict, the default export will be the latest version of the abstract operation. -Alternative versions will also be available under an `es5`/`es2015` exported property if you require a specific version. - -## Example - -```js -var toPrimitive = require('es-to-primitive'); -var assert = require('assert'); - -assert(toPrimitive(function () {}) === String(function () {})); - -var date = new Date(); -assert(toPrimitive(date) === String(date)); - -assert(toPrimitive({ valueOf: function () { return 3; } }) === 3); - -assert(toPrimitive(['a', 'b', 3]) === String(['a', 'b', 3])); - -var sym = Symbol(); -assert(toPrimitive(Object(sym)) === sym); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[package-url]: https://npmjs.org/package/es-to-primitive -[npm-version-svg]: http://versionbadg.es/ljharb/es-to-primitive.svg -[travis-svg]: https://travis-ci.org/ljharb/es-to-primitive.svg -[travis-url]: https://travis-ci.org/ljharb/es-to-primitive -[deps-svg]: https://david-dm.org/ljharb/es-to-primitive.svg -[deps-url]: https://david-dm.org/ljharb/es-to-primitive -[dev-deps-svg]: https://david-dm.org/ljharb/es-to-primitive/dev-status.svg -[dev-deps-url]: https://david-dm.org/ljharb/es-to-primitive#info=devDependencies -[npm-badge-png]: https://nodei.co/npm/es-to-primitive.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/es-to-primitive.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/es-to-primitive.svg -[downloads-url]: http://npm-stat.com/charts.html?package=es-to-primitive diff --git a/node_modules/es-to-primitive/es2015.js b/node_modules/es-to-primitive/es2015.js deleted file mode 100644 index 4a11a34..0000000 --- a/node_modules/es-to-primitive/es2015.js +++ /dev/null @@ -1,75 +0,0 @@ -'use strict'; - -var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'; - -var isPrimitive = require('./helpers/isPrimitive'); -var isCallable = require('is-callable'); -var isDate = require('is-date-object'); -var isSymbol = require('is-symbol'); - -var ordinaryToPrimitive = function OrdinaryToPrimitive(O, hint) { - if (typeof O === 'undefined' || O === null) { - throw new TypeError('Cannot call method on ' + O); - } - if (typeof hint !== 'string' || (hint !== 'number' && hint !== 'string')) { - throw new TypeError('hint must be "string" or "number"'); - } - var methodNames = hint === 'string' ? ['toString', 'valueOf'] : ['valueOf', 'toString']; - var method, result, i; - for (i = 0; i < methodNames.length; ++i) { - method = O[methodNames[i]]; - if (isCallable(method)) { - result = method.call(O); - if (isPrimitive(result)) { - return result; - } - } - } - throw new TypeError('No default value'); -}; - -var GetMethod = function GetMethod(O, P) { - var func = O[P]; - if (func !== null && typeof func !== 'undefined') { - if (!isCallable(func)) { - throw new TypeError(func + ' returned for property ' + P + ' of object ' + O + ' is not a function'); - } - return func; - } - return void 0; -}; - -// http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive -module.exports = function ToPrimitive(input) { - if (isPrimitive(input)) { - return input; - } - var hint = 'default'; - if (arguments.length > 1) { - if (arguments[1] === String) { - hint = 'string'; - } else if (arguments[1] === Number) { - hint = 'number'; - } - } - - var exoticToPrim; - if (hasSymbols) { - if (Symbol.toPrimitive) { - exoticToPrim = GetMethod(input, Symbol.toPrimitive); - } else if (isSymbol(input)) { - exoticToPrim = Symbol.prototype.valueOf; - } - } - if (typeof exoticToPrim !== 'undefined') { - var result = exoticToPrim.call(input, hint); - if (isPrimitive(result)) { - return result; - } - throw new TypeError('unable to convert exotic object to primitive'); - } - if (hint === 'default' && (isDate(input) || isSymbol(input))) { - hint = 'string'; - } - return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint); -}; diff --git a/node_modules/es-to-primitive/es5.js b/node_modules/es-to-primitive/es5.js deleted file mode 100644 index 602aa36..0000000 --- a/node_modules/es-to-primitive/es5.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var toStr = Object.prototype.toString; - -var isPrimitive = require('./helpers/isPrimitive'); - -var isCallable = require('is-callable'); - -// http://ecma-international.org/ecma-262/5.1/#sec-8.12.8 -var ES5internalSlots = { - '[[DefaultValue]]': function (O) { - var actualHint; - if (arguments.length > 1) { - actualHint = arguments[1]; - } else { - actualHint = toStr.call(O) === '[object Date]' ? String : Number; - } - - if (actualHint === String || actualHint === Number) { - var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString']; - var value, i; - for (i = 0; i < methods.length; ++i) { - if (isCallable(O[methods[i]])) { - value = O[methods[i]](); - if (isPrimitive(value)) { - return value; - } - } - } - throw new TypeError('No default value'); - } - throw new TypeError('invalid [[DefaultValue]] hint supplied'); - } -}; - -// http://ecma-international.org/ecma-262/5.1/#sec-9.1 -module.exports = function ToPrimitive(input) { - if (isPrimitive(input)) { - return input; - } - if (arguments.length > 1) { - return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]); - } - return ES5internalSlots['[[DefaultValue]]'](input); -}; diff --git a/node_modules/es-to-primitive/es6.js b/node_modules/es-to-primitive/es6.js deleted file mode 100644 index 2d1f4dc..0000000 --- a/node_modules/es-to-primitive/es6.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('./es2015'); diff --git a/node_modules/es-to-primitive/helpers/isPrimitive.js b/node_modules/es-to-primitive/helpers/isPrimitive.js deleted file mode 100644 index 06f0bf0..0000000 --- a/node_modules/es-to-primitive/helpers/isPrimitive.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -module.exports = function isPrimitive(value) { - return value === null || (typeof value !== 'function' && typeof value !== 'object'); -}; diff --git a/node_modules/es-to-primitive/index.js b/node_modules/es-to-primitive/index.js deleted file mode 100644 index e60d912..0000000 --- a/node_modules/es-to-primitive/index.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var ES5 = require('./es5'); -var ES6 = require('./es6'); -var ES2015 = require('./es2015'); - -if (Object.defineProperty) { - Object.defineProperty(ES2015, 'ES5', { enumerable: false, value: ES5 }); - Object.defineProperty(ES2015, 'ES6', { enumerable: false, value: ES6 }); - Object.defineProperty(ES2015, 'ES2015', { enumerable: false, value: ES2015 }); -} else { - ES6.ES5 = ES5; - ES6.ES6 = ES6; - ES6.ES2015 = ES2015; -} - -module.exports = ES2015; diff --git a/node_modules/es-to-primitive/package.json b/node_modules/es-to-primitive/package.json deleted file mode 100644 index 536bba7..0000000 --- a/node_modules/es-to-primitive/package.json +++ /dev/null @@ -1,113 +0,0 @@ -{ - "_from": "es-to-primitive@^1.2.1", - "_id": "es-to-primitive@1.2.1", - "_inBundle": false, - "_integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==", - "_location": "/es-to-primitive", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "es-to-primitive@^1.2.1", - "name": "es-to-primitive", - "escapedName": "es-to-primitive", - "rawSpec": "^1.2.1", - "saveSpec": null, - "fetchSpec": "^1.2.1" - }, - "_requiredBy": [ - "/es-abstract" - ], - "_resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz", - "_shasum": "e55cd4c9cdc188bcefb03b366c736323fc5c898a", - "_spec": "es-to-primitive@^1.2.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/es-abstract", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com" - }, - "bugs": { - "url": "https://github.com/ljharb/es-to-primitive/issues" - }, - "bundleDependencies": false, - "dependencies": { - "is-callable": "^1.1.4", - "is-date-object": "^1.0.1", - "is-symbol": "^1.0.2" - }, - "deprecated": false, - "description": "ECMAScript “ToPrimitive” algorithm. Provides ES5 and ES2015 versions.", - "devDependencies": { - "@ljharb/eslint-config": "^15.0.0", - "covert": "^1.1.1", - "eslint": "^6.6.0", - "foreach": "^2.0.5", - "function.prototype.name": "^1.1.1", - "has-symbols": "^1.0.0", - "object-inspect": "^1.6.0", - "object-is": "^1.0.1", - "replace": "^1.1.1", - "semver": "^6.3.0", - "tape": "^4.11.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "homepage": "https://github.com/ljharb/es-to-primitive#readme", - "keywords": [ - "primitive", - "abstract", - "ecmascript", - "es5", - "es6", - "es2015", - "toPrimitive", - "coerce", - "type", - "object", - "string", - "number", - "boolean", - "symbol", - "null", - "undefined" - ], - "license": "MIT", - "main": "index.js", - "name": "es-to-primitive", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/es-to-primitive.git" - }, - "scripts": { - "coverage": "covert test/*.js", - "coverage-quiet": "covert test/*.js --quiet", - "lint": "eslint .", - "posttest": "npx aud", - "pretest": "npm run --silent lint", - "test": "npm run --silent tests-only", - "tests-only": "node --es-staging test" - }, - "testling": { - "files": "test", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.2.1" -} diff --git a/node_modules/es-to-primitive/test/es2015.js b/node_modules/es-to-primitive/test/es2015.js deleted file mode 100644 index 80f4083..0000000 --- a/node_modules/es-to-primitive/test/es2015.js +++ /dev/null @@ -1,151 +0,0 @@ -'use strict'; - -var test = require('tape'); -var toPrimitive = require('../es2015'); -var is = require('object-is'); -var forEach = require('foreach'); -var functionName = require('function.prototype.name'); -var debug = require('object-inspect'); - -var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'; -var hasSymbolToPrimitive = hasSymbols && typeof Symbol.toPrimitive === 'symbol'; - -test('function properties', function (t) { - t.equal(toPrimitive.length, 1, 'length is 1'); - t.equal(functionName(toPrimitive), 'ToPrimitive', 'name is ToPrimitive'); - - t.end(); -}); - -var primitives = [null, undefined, true, false, 0, -0, 42, NaN, Infinity, -Infinity, '', 'abc']; - -test('primitives', function (t) { - forEach(primitives, function (i) { - t.ok(is(toPrimitive(i), i), 'toPrimitive(' + debug(i) + ') returns the same value'); - t.ok(is(toPrimitive(i, String), i), 'toPrimitive(' + debug(i) + ', String) returns the same value'); - t.ok(is(toPrimitive(i, Number), i), 'toPrimitive(' + debug(i) + ', Number) returns the same value'); - }); - t.end(); -}); - -test('Symbols', { skip: !hasSymbols }, function (t) { - var symbols = [ - Symbol('foo'), - Symbol.iterator, - Symbol['for']('foo') // eslint-disable-line no-restricted-properties - ]; - forEach(symbols, function (sym) { - t.equal(toPrimitive(sym), sym, 'toPrimitive(' + debug(sym) + ') returns the same value'); - t.equal(toPrimitive(sym, String), sym, 'toPrimitive(' + debug(sym) + ', String) returns the same value'); - t.equal(toPrimitive(sym, Number), sym, 'toPrimitive(' + debug(sym) + ', Number) returns the same value'); - }); - - var primitiveSym = Symbol('primitiveSym'); - var objectSym = Object(primitiveSym); - t.equal(toPrimitive(objectSym), primitiveSym, 'toPrimitive(' + debug(objectSym) + ') returns ' + debug(primitiveSym)); - t.equal(toPrimitive(objectSym, String), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', String) returns ' + debug(primitiveSym)); - t.equal(toPrimitive(objectSym, Number), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', Number) returns ' + debug(primitiveSym)); - t.end(); -}); - -test('Arrays', function (t) { - var arrays = [[], ['a', 'b'], [1, 2]]; - forEach(arrays, function (arr) { - t.equal(toPrimitive(arr), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); - t.equal(toPrimitive(arr, String), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); - t.equal(toPrimitive(arr, Number), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); - }); - t.end(); -}); - -test('Dates', function (t) { - var dates = [new Date(), new Date(0), new Date(NaN)]; - forEach(dates, function (date) { - t.equal(toPrimitive(date), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date'); - t.equal(toPrimitive(date, String), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date'); - t.ok(is(toPrimitive(date, Number), Number(date)), 'toPrimitive(' + debug(date) + ') returns the number version of the date'); - }); - t.end(); -}); - -var coercibleObject = { valueOf: function () { return 3; }, toString: function () { return 42; } }; -var valueOfOnlyObject = { valueOf: function () { return 4; }, toString: function () { return {}; } }; -var toStringOnlyObject = { valueOf: function () { return {}; }, toString: function () { return 7; } }; -var coercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return 42; } -}; -var uncoercibleObject = { valueOf: function () { return {}; }, toString: function () { return {}; } }; -var uncoercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return function toStrFn() {}; } -}; - -test('Objects', function (t) { - t.equal(toPrimitive(coercibleObject), coercibleObject.valueOf(), 'coercibleObject with no hint coerces to valueOf'); - t.equal(toPrimitive(coercibleObject, Number), coercibleObject.valueOf(), 'coercibleObject with hint Number coerces to valueOf'); - t.equal(toPrimitive(coercibleObject, String), coercibleObject.toString(), 'coercibleObject with hint String coerces to non-stringified toString'); - - t.equal(toPrimitive(coercibleFnObject), coercibleFnObject.toString(), 'coercibleFnObject coerces to non-stringified toString'); - t.equal(toPrimitive(coercibleFnObject, Number), coercibleFnObject.toString(), 'coercibleFnObject with hint Number coerces to non-stringified toString'); - t.equal(toPrimitive(coercibleFnObject, String), coercibleFnObject.toString(), 'coercibleFnObject with hint String coerces to non-stringified toString'); - - t.equal(toPrimitive({}), '[object Object]', '{} with no hint coerces to Object#toString'); - t.equal(toPrimitive({}, Number), '[object Object]', '{} with hint Number coerces to Object#toString'); - t.equal(toPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); - - t.equal(toPrimitive(toStringOnlyObject), toStringOnlyObject.toString(), 'toStringOnlyObject returns non-stringified toString'); - t.equal(toPrimitive(toStringOnlyObject, Number), toStringOnlyObject.toString(), 'toStringOnlyObject with hint Number returns non-stringified toString'); - t.equal(toPrimitive(toStringOnlyObject, String), toStringOnlyObject.toString(), 'toStringOnlyObject with hint String returns non-stringified toString'); - - t.equal(toPrimitive(valueOfOnlyObject), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject returns valueOf'); - t.equal(toPrimitive(valueOfOnlyObject, Number), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint Number returns valueOf'); - t.equal(toPrimitive(valueOfOnlyObject, String), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint String returns non-stringified valueOf'); - - t.test('Symbol.toPrimitive', { skip: !hasSymbolToPrimitive }, function (st) { - var overriddenObject = { toString: st.fail, valueOf: st.fail }; - overriddenObject[Symbol.toPrimitive] = function (hint) { return String(hint); }; - - st.equal(toPrimitive(overriddenObject), 'default', 'object with Symbol.toPrimitive + no hint invokes that'); - st.equal(toPrimitive(overriddenObject, Number), 'number', 'object with Symbol.toPrimitive + hint Number invokes that'); - st.equal(toPrimitive(overriddenObject, String), 'string', 'object with Symbol.toPrimitive + hint String invokes that'); - - var nullToPrimitive = { toString: coercibleObject.toString, valueOf: coercibleObject.valueOf }; - nullToPrimitive[Symbol.toPrimitive] = null; - st.equal(toPrimitive(nullToPrimitive), toPrimitive(coercibleObject), 'object with no hint + null Symbol.toPrimitive ignores it'); - st.equal(toPrimitive(nullToPrimitive, Number), toPrimitive(coercibleObject, Number), 'object with hint Number + null Symbol.toPrimitive ignores it'); - st.equal(toPrimitive(nullToPrimitive, String), toPrimitive(coercibleObject, String), 'object with hint String + null Symbol.toPrimitive ignores it'); - - st.test('exceptions', function (sst) { - var nonFunctionToPrimitive = { toString: sst.fail, valueOf: sst.fail }; - nonFunctionToPrimitive[Symbol.toPrimitive] = {}; - sst['throws'](toPrimitive.bind(null, nonFunctionToPrimitive), TypeError, 'Symbol.toPrimitive returning a non-function throws'); - - var uncoercibleToPrimitive = { toString: sst.fail, valueOf: sst.fail }; - uncoercibleToPrimitive[Symbol.toPrimitive] = function (hint) { - return { toString: function () { return hint; } }; - }; - sst['throws'](toPrimitive.bind(null, uncoercibleToPrimitive), TypeError, 'Symbol.toPrimitive returning an object throws'); - - var throwingToPrimitive = { toString: sst.fail, valueOf: sst.fail }; - throwingToPrimitive[Symbol.toPrimitive] = function (hint) { throw new RangeError(hint); }; - sst['throws'](toPrimitive.bind(null, throwingToPrimitive), RangeError, 'Symbol.toPrimitive throwing throws'); - - sst.end(); - }); - - st.end(); - }); - - t.test('exceptions', function (st) { - st['throws'](toPrimitive.bind(null, uncoercibleObject), TypeError, 'uncoercibleObject throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleObject, Number), TypeError, 'uncoercibleObject with hint Number throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleObject, String), TypeError, 'uncoercibleObject with hint String throws a TypeError'); - - st['throws'](toPrimitive.bind(null, uncoercibleFnObject), TypeError, 'uncoercibleFnObject throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleFnObject, Number), TypeError, 'uncoercibleFnObject with hint Number throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleFnObject, String), TypeError, 'uncoercibleFnObject with hint String throws a TypeError'); - st.end(); - }); - t.end(); -}); diff --git a/node_modules/es-to-primitive/test/es5.js b/node_modules/es-to-primitive/test/es5.js deleted file mode 100644 index 79444b0..0000000 --- a/node_modules/es-to-primitive/test/es5.js +++ /dev/null @@ -1,118 +0,0 @@ -'use strict'; - -var test = require('tape'); -var toPrimitive = require('../es5'); -var is = require('object-is'); -var forEach = require('foreach'); -var functionName = require('function.prototype.name'); -var debug = require('object-inspect'); -var hasSymbols = require('has-symbols')(); - -test('function properties', function (t) { - t.equal(toPrimitive.length, 1, 'length is 1'); - t.equal(functionName(toPrimitive), 'ToPrimitive', 'name is ToPrimitive'); - - t.end(); -}); - -var primitives = [null, undefined, true, false, 0, -0, 42, NaN, Infinity, -Infinity, '', 'abc']; - -test('primitives', function (t) { - forEach(primitives, function (i) { - t.ok(is(toPrimitive(i), i), 'toPrimitive(' + debug(i) + ') returns the same value'); - t.ok(is(toPrimitive(i, String), i), 'toPrimitive(' + debug(i) + ', String) returns the same value'); - t.ok(is(toPrimitive(i, Number), i), 'toPrimitive(' + debug(i) + ', Number) returns the same value'); - }); - t.end(); -}); - -test('Symbols', { skip: !hasSymbols }, function (t) { - var symbols = [ - Symbol('foo'), - Symbol.iterator, - Symbol['for']('foo') // eslint-disable-line no-restricted-properties - ]; - forEach(symbols, function (sym) { - t.equal(toPrimitive(sym), sym, 'toPrimitive(' + debug(sym) + ') returns the same value'); - t.equal(toPrimitive(sym, String), sym, 'toPrimitive(' + debug(sym) + ', String) returns the same value'); - t.equal(toPrimitive(sym, Number), sym, 'toPrimitive(' + debug(sym) + ', Number) returns the same value'); - }); - - var primitiveSym = Symbol('primitiveSym'); - var stringSym = Symbol.prototype.toString.call(primitiveSym); - var objectSym = Object(primitiveSym); - t.equal(toPrimitive(objectSym), primitiveSym, 'toPrimitive(' + debug(objectSym) + ') returns ' + debug(primitiveSym)); - - // This is different from ES2015, as the ES5 algorithm doesn't account for the existence of Symbols: - t.equal(toPrimitive(objectSym, String), stringSym, 'toPrimitive(' + debug(objectSym) + ', String) returns ' + debug(stringSym)); - t.equal(toPrimitive(objectSym, Number), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', Number) returns ' + debug(primitiveSym)); - t.end(); -}); - -test('Arrays', function (t) { - var arrays = [[], ['a', 'b'], [1, 2]]; - forEach(arrays, function (arr) { - t.ok(is(toPrimitive(arr), arr.toString()), 'toPrimitive(' + debug(arr) + ') returns toString of the array'); - t.equal(toPrimitive(arr, String), arr.toString(), 'toPrimitive(' + debug(arr) + ') returns toString of the array'); - t.ok(is(toPrimitive(arr, Number), arr.toString()), 'toPrimitive(' + debug(arr) + ') returns toString of the array'); - }); - t.end(); -}); - -test('Dates', function (t) { - var dates = [new Date(), new Date(0), new Date(NaN)]; - forEach(dates, function (date) { - t.equal(toPrimitive(date), date.toString(), 'toPrimitive(' + debug(date) + ') returns toString of the date'); - t.equal(toPrimitive(date, String), date.toString(), 'toPrimitive(' + debug(date) + ') returns toString of the date'); - t.ok(is(toPrimitive(date, Number), date.valueOf()), 'toPrimitive(' + debug(date) + ') returns valueOf of the date'); - }); - t.end(); -}); - -var coercibleObject = { valueOf: function () { return 3; }, toString: function () { return 42; } }; -var valueOfOnlyObject = { valueOf: function () { return 4; }, toString: function () { return {}; } }; -var toStringOnlyObject = { valueOf: function () { return {}; }, toString: function () { return 7; } }; -var coercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return 42; } -}; -var uncoercibleObject = { valueOf: function () { return {}; }, toString: function () { return {}; } }; -var uncoercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return function toStrFn() {}; } -}; - -test('Objects', function (t) { - t.equal(toPrimitive(coercibleObject), coercibleObject.valueOf(), 'coercibleObject with no hint coerces to valueOf'); - t.equal(toPrimitive(coercibleObject, String), coercibleObject.toString(), 'coercibleObject with hint String coerces to toString'); - t.equal(toPrimitive(coercibleObject, Number), coercibleObject.valueOf(), 'coercibleObject with hint Number coerces to valueOf'); - - t.equal(toPrimitive(coercibleFnObject), coercibleFnObject.toString(), 'coercibleFnObject coerces to toString'); - t.equal(toPrimitive(coercibleFnObject, String), coercibleFnObject.toString(), 'coercibleFnObject with hint String coerces to toString'); - t.equal(toPrimitive(coercibleFnObject, Number), coercibleFnObject.toString(), 'coercibleFnObject with hint Number coerces to toString'); - - t.ok(is(toPrimitive({}), '[object Object]'), '{} with no hint coerces to Object#toString'); - t.equal(toPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); - t.ok(is(toPrimitive({}, Number), '[object Object]'), '{} with hint Number coerces to Object#toString'); - - t.equal(toPrimitive(toStringOnlyObject), toStringOnlyObject.toString(), 'toStringOnlyObject returns toString'); - t.equal(toPrimitive(toStringOnlyObject, String), toStringOnlyObject.toString(), 'toStringOnlyObject with hint String returns toString'); - t.equal(toPrimitive(toStringOnlyObject, Number), toStringOnlyObject.toString(), 'toStringOnlyObject with hint Number returns toString'); - - t.equal(toPrimitive(valueOfOnlyObject), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject returns valueOf'); - t.equal(toPrimitive(valueOfOnlyObject, String), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint String returns valueOf'); - t.equal(toPrimitive(valueOfOnlyObject, Number), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint Number returns valueOf'); - - t.test('exceptions', function (st) { - st['throws'](toPrimitive.bind(null, uncoercibleObject), TypeError, 'uncoercibleObject throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleObject, String), TypeError, 'uncoercibleObject with hint String throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleObject, Number), TypeError, 'uncoercibleObject with hint Number throws a TypeError'); - - st['throws'](toPrimitive.bind(null, uncoercibleFnObject), TypeError, 'uncoercibleFnObject throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleFnObject, String), TypeError, 'uncoercibleFnObject with hint String throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleFnObject, Number), TypeError, 'uncoercibleFnObject with hint Number throws a TypeError'); - st.end(); - }); - - t.end(); -}); diff --git a/node_modules/es-to-primitive/test/es6.js b/node_modules/es-to-primitive/test/es6.js deleted file mode 100644 index 16ea0e8..0000000 --- a/node_modules/es-to-primitive/test/es6.js +++ /dev/null @@ -1,151 +0,0 @@ -'use strict'; - -var test = require('tape'); -var toPrimitive = require('../es6'); -var is = require('object-is'); -var forEach = require('foreach'); -var functionName = require('function.prototype.name'); -var debug = require('object-inspect'); - -var hasSymbols = require('has-symbols')(); -var hasSymbolToPrimitive = hasSymbols && typeof Symbol.toPrimitive === 'symbol'; - -test('function properties', function (t) { - t.equal(toPrimitive.length, 1, 'length is 1'); - t.equal(functionName(toPrimitive), 'ToPrimitive', 'name is ToPrimitive'); - - t.end(); -}); - -var primitives = [null, undefined, true, false, 0, -0, 42, NaN, Infinity, -Infinity, '', 'abc']; - -test('primitives', function (t) { - forEach(primitives, function (i) { - t.ok(is(toPrimitive(i), i), 'toPrimitive(' + debug(i) + ') returns the same value'); - t.ok(is(toPrimitive(i, String), i), 'toPrimitive(' + debug(i) + ', String) returns the same value'); - t.ok(is(toPrimitive(i, Number), i), 'toPrimitive(' + debug(i) + ', Number) returns the same value'); - }); - t.end(); -}); - -test('Symbols', { skip: !hasSymbols }, function (t) { - var symbols = [ - Symbol('foo'), - Symbol.iterator, - Symbol['for']('foo') // eslint-disable-line no-restricted-properties - ]; - forEach(symbols, function (sym) { - t.equal(toPrimitive(sym), sym, 'toPrimitive(' + debug(sym) + ') returns the same value'); - t.equal(toPrimitive(sym, String), sym, 'toPrimitive(' + debug(sym) + ', String) returns the same value'); - t.equal(toPrimitive(sym, Number), sym, 'toPrimitive(' + debug(sym) + ', Number) returns the same value'); - }); - - var primitiveSym = Symbol('primitiveSym'); - var objectSym = Object(primitiveSym); - t.equal(toPrimitive(objectSym), primitiveSym, 'toPrimitive(' + debug(objectSym) + ') returns ' + debug(primitiveSym)); - t.equal(toPrimitive(objectSym, String), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', String) returns ' + debug(primitiveSym)); - t.equal(toPrimitive(objectSym, Number), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', Number) returns ' + debug(primitiveSym)); - t.end(); -}); - -test('Arrays', function (t) { - var arrays = [[], ['a', 'b'], [1, 2]]; - forEach(arrays, function (arr) { - t.equal(toPrimitive(arr), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); - t.equal(toPrimitive(arr, String), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); - t.equal(toPrimitive(arr, Number), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); - }); - t.end(); -}); - -test('Dates', function (t) { - var dates = [new Date(), new Date(0), new Date(NaN)]; - forEach(dates, function (date) { - t.equal(toPrimitive(date), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date'); - t.equal(toPrimitive(date, String), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date'); - t.ok(is(toPrimitive(date, Number), Number(date)), 'toPrimitive(' + debug(date) + ') returns the number version of the date'); - }); - t.end(); -}); - -var coercibleObject = { valueOf: function () { return 3; }, toString: function () { return 42; } }; -var valueOfOnlyObject = { valueOf: function () { return 4; }, toString: function () { return {}; } }; -var toStringOnlyObject = { valueOf: function () { return {}; }, toString: function () { return 7; } }; -var coercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return 42; } -}; -var uncoercibleObject = { valueOf: function () { return {}; }, toString: function () { return {}; } }; -var uncoercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return function toStrFn() {}; } -}; - -test('Objects', function (t) { - t.equal(toPrimitive(coercibleObject), coercibleObject.valueOf(), 'coercibleObject with no hint coerces to valueOf'); - t.equal(toPrimitive(coercibleObject, Number), coercibleObject.valueOf(), 'coercibleObject with hint Number coerces to valueOf'); - t.equal(toPrimitive(coercibleObject, String), coercibleObject.toString(), 'coercibleObject with hint String coerces to non-stringified toString'); - - t.equal(toPrimitive(coercibleFnObject), coercibleFnObject.toString(), 'coercibleFnObject coerces to non-stringified toString'); - t.equal(toPrimitive(coercibleFnObject, Number), coercibleFnObject.toString(), 'coercibleFnObject with hint Number coerces to non-stringified toString'); - t.equal(toPrimitive(coercibleFnObject, String), coercibleFnObject.toString(), 'coercibleFnObject with hint String coerces to non-stringified toString'); - - t.equal(toPrimitive({}), '[object Object]', '{} with no hint coerces to Object#toString'); - t.equal(toPrimitive({}, Number), '[object Object]', '{} with hint Number coerces to Object#toString'); - t.equal(toPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); - - t.equal(toPrimitive(toStringOnlyObject), toStringOnlyObject.toString(), 'toStringOnlyObject returns non-stringified toString'); - t.equal(toPrimitive(toStringOnlyObject, Number), toStringOnlyObject.toString(), 'toStringOnlyObject with hint Number returns non-stringified toString'); - t.equal(toPrimitive(toStringOnlyObject, String), toStringOnlyObject.toString(), 'toStringOnlyObject with hint String returns non-stringified toString'); - - t.equal(toPrimitive(valueOfOnlyObject), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject returns valueOf'); - t.equal(toPrimitive(valueOfOnlyObject, Number), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint Number returns valueOf'); - t.equal(toPrimitive(valueOfOnlyObject, String), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint String returns non-stringified valueOf'); - - t.test('Symbol.toPrimitive', { skip: !hasSymbolToPrimitive }, function (st) { - var overriddenObject = { toString: st.fail, valueOf: st.fail }; - overriddenObject[Symbol.toPrimitive] = function (hint) { return String(hint); }; - - st.equal(toPrimitive(overriddenObject), 'default', 'object with Symbol.toPrimitive + no hint invokes that'); - st.equal(toPrimitive(overriddenObject, Number), 'number', 'object with Symbol.toPrimitive + hint Number invokes that'); - st.equal(toPrimitive(overriddenObject, String), 'string', 'object with Symbol.toPrimitive + hint String invokes that'); - - var nullToPrimitive = { toString: coercibleObject.toString, valueOf: coercibleObject.valueOf }; - nullToPrimitive[Symbol.toPrimitive] = null; - st.equal(toPrimitive(nullToPrimitive), toPrimitive(coercibleObject), 'object with no hint + null Symbol.toPrimitive ignores it'); - st.equal(toPrimitive(nullToPrimitive, Number), toPrimitive(coercibleObject, Number), 'object with hint Number + null Symbol.toPrimitive ignores it'); - st.equal(toPrimitive(nullToPrimitive, String), toPrimitive(coercibleObject, String), 'object with hint String + null Symbol.toPrimitive ignores it'); - - st.test('exceptions', function (sst) { - var nonFunctionToPrimitive = { toString: sst.fail, valueOf: sst.fail }; - nonFunctionToPrimitive[Symbol.toPrimitive] = {}; - sst['throws'](toPrimitive.bind(null, nonFunctionToPrimitive), TypeError, 'Symbol.toPrimitive returning a non-function throws'); - - var uncoercibleToPrimitive = { toString: sst.fail, valueOf: sst.fail }; - uncoercibleToPrimitive[Symbol.toPrimitive] = function (hint) { - return { toString: function () { return hint; } }; - }; - sst['throws'](toPrimitive.bind(null, uncoercibleToPrimitive), TypeError, 'Symbol.toPrimitive returning an object throws'); - - var throwingToPrimitive = { toString: sst.fail, valueOf: sst.fail }; - throwingToPrimitive[Symbol.toPrimitive] = function (hint) { throw new RangeError(hint); }; - sst['throws'](toPrimitive.bind(null, throwingToPrimitive), RangeError, 'Symbol.toPrimitive throwing throws'); - - sst.end(); - }); - - st.end(); - }); - - t.test('exceptions', function (st) { - st['throws'](toPrimitive.bind(null, uncoercibleObject), TypeError, 'uncoercibleObject throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleObject, Number), TypeError, 'uncoercibleObject with hint Number throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleObject, String), TypeError, 'uncoercibleObject with hint String throws a TypeError'); - - st['throws'](toPrimitive.bind(null, uncoercibleFnObject), TypeError, 'uncoercibleFnObject throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleFnObject, Number), TypeError, 'uncoercibleFnObject with hint Number throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleFnObject, String), TypeError, 'uncoercibleFnObject with hint String throws a TypeError'); - st.end(); - }); - t.end(); -}); diff --git a/node_modules/es-to-primitive/test/index.js b/node_modules/es-to-primitive/test/index.js deleted file mode 100644 index ad71f39..0000000 --- a/node_modules/es-to-primitive/test/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var toPrimitive = require('../'); -var ES5 = require('../es5'); -var ES6 = require('../es6'); -var ES2015 = require('../es2015'); - -var test = require('tape'); - -test('default export', function (t) { - t.equal(toPrimitive, ES2015, 'default export is ES2015'); - t.equal(toPrimitive.ES5, ES5, 'ES5 property has ES5 method'); - t.equal(toPrimitive.ES6, ES6, 'ES6 property has ES6 method'); - t.equal(toPrimitive.ES2015, ES2015, 'ES2015 property has ES2015 method'); - t.end(); -}); - -require('./es5'); -require('./es6'); -require('./es2015'); diff --git a/node_modules/es6-object-assign/LICENSE b/node_modules/es6-object-assign/LICENSE deleted file mode 100644 index 3fef2a2..0000000 --- a/node_modules/es6-object-assign/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2015-2017 Rubén Norte - -MIT License - -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/es6-object-assign/README.md b/node_modules/es6-object-assign/README.md deleted file mode 100644 index 3917299..0000000 --- a/node_modules/es6-object-assign/README.md +++ /dev/null @@ -1,96 +0,0 @@ -[![npm](https://img.shields.io/npm/l/es6-object-assign.svg)](https://www.npmjs.org/package/es6-object-assign) -[![npm](https://img.shields.io/npm/v/es6-object-assign.svg)](https://www.npmjs.org/package/es6-object-assign) - -# ES6 Object.assign() - -ECMAScript 2015 (ES2015/ES6) [Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) polyfill and [ponyfill](https://ponyfill.com) for ECMAScript 5 environments. - -The main definition of this package has been copied from the polyfill defined in the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign). - -## Installation - -### NPM - -```bash -npm install es6-object-assign -``` - -### Manual download and import - -The package is also available as a UMD module (compatible with AMD, CommonJS and exposing a global variable `ObjectAssign`) in `dist/object-assign.js` and `dist/object-assign.min.js` (833 bytes minified and gzipped). - -The versions with automatic polyfilling are `dist/object-assign-auto.js` and `dist/object-assign-auto.min.js`. - -## Usage - -**CommonJS**: - -```javascript -// Polyfill, modifying the global Object -require('es6-object-assign').polyfill(); -var obj = Object.assign({}, { foo: 'bar' }); - -// Same version with automatic polyfilling -require('es6-object-assign/auto'); -var obj = Object.assign({}, { foo: 'bar' }); - -// Or ponyfill, using a reference to the function without modifying globals -var assign = require('es6-object-assign').assign; -var obj = assign({}, { foo: 'bar' }); -``` - -**Globals**: - -Manual polyfill: - -```html - - -``` - -Automatic polyfill: - -```html - - -``` - -Ponyfill, without modifying globals: - -```html - - -``` - -## License - -The MIT License (MIT) - -Copyright (c) 2017 Rubén Norte - -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/es6-object-assign/auto.js b/node_modules/es6-object-assign/auto.js deleted file mode 100644 index 43b68da..0000000 --- a/node_modules/es6-object-assign/auto.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -require('./index').polyfill(); diff --git a/node_modules/es6-object-assign/dist/object-assign-auto.js b/node_modules/es6-object-assign/dist/object-assign-auto.js deleted file mode 100644 index 12d22b6..0000000 --- a/node_modules/es6-object-assign/dist/object-assign-auto.js +++ /dev/null @@ -1,54 +0,0 @@ -(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;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 require=="function"&&require;for(var o=0;o dist/object-assign-auto.min.js", - "compress:manual": "uglifyjs dist/object-assign.js --compress --mangle > dist/object-assign.min.js" - }, - "version": "1.1.0" -} diff --git a/node_modules/escape-html/LICENSE b/node_modules/escape-html/LICENSE deleted file mode 100644 index 2e70de9..0000000 --- a/node_modules/escape-html/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2012-2013 TJ Holowaychuk -Copyright (c) 2015 Andreas Lubbe -Copyright (c) 2015 Tiancheng "Timothy" Gu - -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/escape-html/Readme.md b/node_modules/escape-html/Readme.md deleted file mode 100644 index 653d9ea..0000000 --- a/node_modules/escape-html/Readme.md +++ /dev/null @@ -1,43 +0,0 @@ - -# escape-html - - Escape string for use in HTML - -## Example - -```js -var escape = require('escape-html'); -var html = escape('foo & bar'); -// -> foo & bar -``` - -## Benchmark - -``` -$ npm run-script bench - -> escape-html@1.0.3 bench nodejs-escape-html -> node benchmark/index.js - - - http_parser@1.0 - node@0.10.33 - v8@3.14.5.9 - ares@1.9.0-DEV - uv@0.10.29 - zlib@1.2.3 - modules@11 - openssl@1.0.1j - - 1 test completed. - 2 tests completed. - 3 tests completed. - - no special characters x 19,435,271 ops/sec ±0.85% (187 runs sampled) - single special character x 6,132,421 ops/sec ±0.67% (194 runs sampled) - many special characters x 3,175,826 ops/sec ±0.65% (193 runs sampled) -``` - -## License - - MIT \ No newline at end of file diff --git a/node_modules/escape-html/index.js b/node_modules/escape-html/index.js deleted file mode 100644 index bf9e226..0000000 --- a/node_modules/escape-html/index.js +++ /dev/null @@ -1,78 +0,0 @@ -/*! - * escape-html - * Copyright(c) 2012-2013 TJ Holowaychuk - * Copyright(c) 2015 Andreas Lubbe - * Copyright(c) 2015 Tiancheng "Timothy" Gu - * MIT Licensed - */ - -'use strict'; - -/** - * Module variables. - * @private - */ - -var matchHtmlRegExp = /["'&<>]/; - -/** - * Module exports. - * @public - */ - -module.exports = escapeHtml; - -/** - * Escape special characters in the given string of html. - * - * @param {string} string The string to escape for inserting into HTML - * @return {string} - * @public - */ - -function escapeHtml(string) { - var str = '' + string; - var match = matchHtmlRegExp.exec(str); - - if (!match) { - return str; - } - - var escape; - var html = ''; - var index = 0; - var lastIndex = 0; - - for (index = match.index; index < str.length; index++) { - switch (str.charCodeAt(index)) { - case 34: // " - escape = '"'; - break; - case 38: // & - escape = '&'; - break; - case 39: // ' - escape = '''; - break; - case 60: // < - escape = '<'; - break; - case 62: // > - escape = '>'; - break; - default: - continue; - } - - if (lastIndex !== index) { - html += str.substring(lastIndex, index); - } - - lastIndex = index + 1; - html += escape; - } - - return lastIndex !== index - ? html + str.substring(lastIndex, index) - : html; -} diff --git a/node_modules/escape-html/package.json b/node_modules/escape-html/package.json deleted file mode 100644 index 09f4f2a..0000000 --- a/node_modules/escape-html/package.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "_from": "escape-html@~1.0.3", - "_id": "escape-html@1.0.3", - "_inBundle": false, - "_integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", - "_location": "/escape-html", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "escape-html@~1.0.3", - "name": "escape-html", - "escapedName": "escape-html", - "rawSpec": "~1.0.3", - "saveSpec": null, - "fetchSpec": "~1.0.3" - }, - "_requiredBy": [ - "/express", - "/finalhandler", - "/send", - "/serve-static" - ], - "_resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "_shasum": "0258eae4d3d0c0974de1c169188ef0051d1d1988", - "_spec": "escape-html@~1.0.3", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "bugs": { - "url": "https://github.com/component/escape-html/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Escape string for use in HTML", - "devDependencies": { - "beautify-benchmark": "0.2.4", - "benchmark": "1.0.0" - }, - "files": [ - "LICENSE", - "Readme.md", - "index.js" - ], - "homepage": "https://github.com/component/escape-html#readme", - "keywords": [ - "escape", - "html", - "utility" - ], - "license": "MIT", - "name": "escape-html", - "repository": { - "type": "git", - "url": "git+https://github.com/component/escape-html.git" - }, - "scripts": { - "bench": "node benchmark/index.js" - }, - "version": "1.0.3" -} diff --git a/node_modules/etag/HISTORY.md b/node_modules/etag/HISTORY.md deleted file mode 100644 index 222b293..0000000 --- a/node_modules/etag/HISTORY.md +++ /dev/null @@ -1,83 +0,0 @@ -1.8.1 / 2017-09-12 -================== - - * perf: replace regular expression with substring - -1.8.0 / 2017-02-18 -================== - - * Use SHA1 instead of MD5 for ETag hashing - - Improves performance for larger entities - - Works with FIPS 140-2 OpenSSL configuration - -1.7.0 / 2015-06-08 -================== - - * Always include entity length in ETags for hash length extensions - * Generate non-Stats ETags using MD5 only (no longer CRC32) - * Improve stat performance by removing hashing - * Remove base64 padding in ETags to shorten - * Use MD5 instead of MD4 in weak ETags over 1KB - -1.6.0 / 2015-05-10 -================== - - * Improve support for JXcore - * Remove requirement of `atime` in the stats object - * Support "fake" stats objects in environments without `fs` - -1.5.1 / 2014-11-19 -================== - - * deps: crc@3.2.1 - - Minor fixes - -1.5.0 / 2014-10-14 -================== - - * Improve string performance - * Slightly improve speed for weak ETags over 1KB - -1.4.0 / 2014-09-21 -================== - - * Support "fake" stats objects - * Support Node.js 0.6 - -1.3.1 / 2014-09-14 -================== - - * Use the (new and improved) `crc` for crc32 - -1.3.0 / 2014-08-29 -================== - - * Default strings to strong ETags - * Improve speed for weak ETags over 1KB - -1.2.1 / 2014-08-29 -================== - - * Use the (much faster) `buffer-crc32` for crc32 - -1.2.0 / 2014-08-24 -================== - - * Add support for file stat objects - -1.1.0 / 2014-08-24 -================== - - * Add fast-path for empty entity - * Add weak ETag generation - * Shrink size of generated ETags - -1.0.1 / 2014-08-24 -================== - - * Fix behavior of string containing Unicode - -1.0.0 / 2014-05-18 -================== - - * Initial release diff --git a/node_modules/etag/LICENSE b/node_modules/etag/LICENSE deleted file mode 100644 index cab251c..0000000 --- a/node_modules/etag/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2014-2016 Douglas Christopher Wilson - -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/etag/README.md b/node_modules/etag/README.md deleted file mode 100644 index 09c2169..0000000 --- a/node_modules/etag/README.md +++ /dev/null @@ -1,159 +0,0 @@ -# etag - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Create simple HTTP ETags - -This module generates HTTP ETags (as defined in RFC 7232) for use in -HTTP responses. - -## Installation - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install etag -``` - -## API - - - -```js -var etag = require('etag') -``` - -### etag(entity, [options]) - -Generate a strong ETag for the given entity. This should be the complete -body of the entity. Strings, `Buffer`s, and `fs.Stats` are accepted. By -default, a strong ETag is generated except for `fs.Stats`, which will -generate a weak ETag (this can be overwritten by `options.weak`). - - - -```js -res.setHeader('ETag', etag(body)) -``` - -#### Options - -`etag` accepts these properties in the options object. - -##### weak - -Specifies if the generated ETag will include the weak validator mark (that -is, the leading `W/`). The actual entity tag is the same. The default value -is `false`, unless the `entity` is `fs.Stats`, in which case it is `true`. - -## Testing - -```sh -$ npm test -``` - -## Benchmark - -```bash -$ npm run-script bench - -> etag@1.8.1 bench nodejs-etag -> node benchmark/index.js - - http_parser@2.7.0 - node@6.11.1 - v8@5.1.281.103 - uv@1.11.0 - zlib@1.2.11 - ares@1.10.1-DEV - icu@58.2 - modules@48 - openssl@1.0.2k - -> node benchmark/body0-100b.js - - 100B body - - 4 tests completed. - - buffer - strong x 258,647 ops/sec ±1.07% (180 runs sampled) - buffer - weak x 263,812 ops/sec ±0.61% (184 runs sampled) - string - strong x 259,955 ops/sec ±1.19% (185 runs sampled) - string - weak x 264,356 ops/sec ±1.09% (184 runs sampled) - -> node benchmark/body1-1kb.js - - 1KB body - - 4 tests completed. - - buffer - strong x 189,018 ops/sec ±1.12% (182 runs sampled) - buffer - weak x 190,586 ops/sec ±0.81% (186 runs sampled) - string - strong x 144,272 ops/sec ±0.96% (188 runs sampled) - string - weak x 145,380 ops/sec ±1.43% (187 runs sampled) - -> node benchmark/body2-5kb.js - - 5KB body - - 4 tests completed. - - buffer - strong x 92,435 ops/sec ±0.42% (188 runs sampled) - buffer - weak x 92,373 ops/sec ±0.58% (189 runs sampled) - string - strong x 48,850 ops/sec ±0.56% (186 runs sampled) - string - weak x 49,380 ops/sec ±0.56% (190 runs sampled) - -> node benchmark/body3-10kb.js - - 10KB body - - 4 tests completed. - - buffer - strong x 55,989 ops/sec ±0.93% (188 runs sampled) - buffer - weak x 56,148 ops/sec ±0.55% (190 runs sampled) - string - strong x 27,345 ops/sec ±0.43% (188 runs sampled) - string - weak x 27,496 ops/sec ±0.45% (190 runs sampled) - -> node benchmark/body4-100kb.js - - 100KB body - - 4 tests completed. - - buffer - strong x 7,083 ops/sec ±0.22% (190 runs sampled) - buffer - weak x 7,115 ops/sec ±0.26% (191 runs sampled) - string - strong x 3,068 ops/sec ±0.34% (190 runs sampled) - string - weak x 3,096 ops/sec ±0.35% (190 runs sampled) - -> node benchmark/stats.js - - stat - - 4 tests completed. - - real - strong x 871,642 ops/sec ±0.34% (189 runs sampled) - real - weak x 867,613 ops/sec ±0.39% (190 runs sampled) - fake - strong x 401,051 ops/sec ±0.40% (189 runs sampled) - fake - weak x 400,100 ops/sec ±0.47% (188 runs sampled) -``` - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/etag.svg -[npm-url]: https://npmjs.org/package/etag -[node-version-image]: https://img.shields.io/node/v/etag.svg -[node-version-url]: https://nodejs.org/en/download/ -[travis-image]: https://img.shields.io/travis/jshttp/etag/master.svg -[travis-url]: https://travis-ci.org/jshttp/etag -[coveralls-image]: https://img.shields.io/coveralls/jshttp/etag/master.svg -[coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master -[downloads-image]: https://img.shields.io/npm/dm/etag.svg -[downloads-url]: https://npmjs.org/package/etag diff --git a/node_modules/etag/index.js b/node_modules/etag/index.js deleted file mode 100644 index 2a585c9..0000000 --- a/node_modules/etag/index.js +++ /dev/null @@ -1,131 +0,0 @@ -/*! - * etag - * Copyright(c) 2014-2016 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module exports. - * @public - */ - -module.exports = etag - -/** - * Module dependencies. - * @private - */ - -var crypto = require('crypto') -var Stats = require('fs').Stats - -/** - * Module variables. - * @private - */ - -var toString = Object.prototype.toString - -/** - * Generate an entity tag. - * - * @param {Buffer|string} entity - * @return {string} - * @private - */ - -function entitytag (entity) { - if (entity.length === 0) { - // fast-path empty - return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' - } - - // compute hash of entity - var hash = crypto - .createHash('sha1') - .update(entity, 'utf8') - .digest('base64') - .substring(0, 27) - - // compute length of entity - var len = typeof entity === 'string' - ? Buffer.byteLength(entity, 'utf8') - : entity.length - - return '"' + len.toString(16) + '-' + hash + '"' -} - -/** - * Create a simple ETag. - * - * @param {string|Buffer|Stats} entity - * @param {object} [options] - * @param {boolean} [options.weak] - * @return {String} - * @public - */ - -function etag (entity, options) { - if (entity == null) { - throw new TypeError('argument entity is required') - } - - // support fs.Stats object - var isStats = isstats(entity) - var weak = options && typeof options.weak === 'boolean' - ? options.weak - : isStats - - // validate argument - if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { - throw new TypeError('argument entity must be string, Buffer, or fs.Stats') - } - - // generate entity tag - var tag = isStats - ? stattag(entity) - : entitytag(entity) - - return weak - ? 'W/' + tag - : tag -} - -/** - * Determine if object is a Stats object. - * - * @param {object} obj - * @return {boolean} - * @api private - */ - -function isstats (obj) { - // genuine fs.Stats - if (typeof Stats === 'function' && obj instanceof Stats) { - return true - } - - // quack quack - return obj && typeof obj === 'object' && - 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && - 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && - 'ino' in obj && typeof obj.ino === 'number' && - 'size' in obj && typeof obj.size === 'number' -} - -/** - * Generate a tag for a stat. - * - * @param {object} stat - * @return {string} - * @private - */ - -function stattag (stat) { - var mtime = stat.mtime.getTime().toString(16) - var size = stat.size.toString(16) - - return '"' + size + '-' + mtime + '"' -} diff --git a/node_modules/etag/package.json b/node_modules/etag/package.json deleted file mode 100644 index be69fec..0000000 --- a/node_modules/etag/package.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "_from": "etag@~1.8.1", - "_id": "etag@1.8.1", - "_inBundle": false, - "_integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=", - "_location": "/etag", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "etag@~1.8.1", - "name": "etag", - "escapedName": "etag", - "rawSpec": "~1.8.1", - "saveSpec": null, - "fetchSpec": "~1.8.1" - }, - "_requiredBy": [ - "/express", - "/send" - ], - "_resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "_shasum": "41ae2eeb65efa62268aebfea83ac7d79299b0887", - "_spec": "etag@~1.8.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "bugs": { - "url": "https://github.com/jshttp/etag/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "David Björklund", - "email": "david.bjorklund@gmail.com" - } - ], - "deprecated": false, - "description": "Create simple HTTP ETags", - "devDependencies": { - "beautify-benchmark": "0.2.4", - "benchmark": "2.1.4", - "eslint": "3.19.0", - "eslint-config-standard": "10.2.1", - "eslint-plugin-import": "2.7.0", - "eslint-plugin-markdown": "1.0.0-beta.6", - "eslint-plugin-node": "5.1.1", - "eslint-plugin-promise": "3.5.0", - "eslint-plugin-standard": "3.0.1", - "istanbul": "0.4.5", - "mocha": "1.21.5", - "safe-buffer": "5.1.1", - "seedrandom": "2.4.3" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "LICENSE", - "HISTORY.md", - "README.md", - "index.js" - ], - "homepage": "https://github.com/jshttp/etag#readme", - "keywords": [ - "etag", - "http", - "res" - ], - "license": "MIT", - "name": "etag", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/etag.git" - }, - "scripts": { - "bench": "node benchmark/index.js", - "lint": "eslint --plugin markdown --ext js,md .", - "test": "mocha --reporter spec --bail --check-leaks test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" - }, - "version": "1.8.1" -} diff --git a/node_modules/expand-template/.travis.yml b/node_modules/expand-template/.travis.yml deleted file mode 100644 index 1335a77..0000000 --- a/node_modules/expand-template/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js - -node_js: - - 6 - - 8 - - 10 diff --git a/node_modules/expand-template/LICENSE b/node_modules/expand-template/LICENSE deleted file mode 100644 index 814aef4..0000000 --- a/node_modules/expand-template/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2018 Lars-Magnus Skog - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/expand-template/README.md b/node_modules/expand-template/README.md deleted file mode 100644 index b98aa48..0000000 --- a/node_modules/expand-template/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# expand-template - -> Expand placeholders in a template string. - -[![npm](https://img.shields.io/npm/v/expand-template.svg)](https://www.npmjs.com/package/expand-template) -![Node version](https://img.shields.io/node/v/expand-template.svg) -[![Build Status](https://travis-ci.org/ralphtheninja/expand-template.svg?branch=master)](https://travis-ci.org/ralphtheninja/expand-template) -[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) - -## Install - -``` -$ npm i expand-template -S -``` - -## Usage - -Default functionality expands templates using `{}` as separators for string placeholders. - -```js -var expand = require('expand-template')() -var template = '{foo}/{foo}/{bar}/{bar}' -console.log(expand(template, { - foo: 'BAR', - bar: 'FOO' -})) -// -> BAR/BAR/FOO/FOO -``` - -Custom separators: - -```js -var expand = require('expand-template')({ sep: '[]' }) -var template = '[foo]/[foo]/[bar]/[bar]' -console.log(expand(template, { - foo: 'BAR', - bar: 'FOO' -})) -// -> BAR/BAR/FOO/FOO -``` - -## License -All code, unless stated otherwise, is dual-licensed under [`WTFPL`](http://www.wtfpl.net/txt/copying/) and [`MIT`](https://opensource.org/licenses/MIT). diff --git a/node_modules/expand-template/index.js b/node_modules/expand-template/index.js deleted file mode 100644 index e182837..0000000 --- a/node_modules/expand-template/index.js +++ /dev/null @@ -1,26 +0,0 @@ -module.exports = function (opts) { - var sep = opts ? opts.sep : '{}' - var len = sep.length - - var whitespace = '\\s*' - var left = escape(sep.substring(0, len / 2)) + whitespace - var right = whitespace + escape(sep.substring(len / 2, len)) - - return function (template, values) { - Object.keys(values).forEach(function (key) { - var value = String(values[key]).replace(/\$/g, '$$$$') - template = template.replace(regExp(key), value) - }) - return template - } - - function escape (s) { - return [].map.call(s, function (char) { - return '\\' + char - }).join('') - } - - function regExp (key) { - return new RegExp(left + key + right, 'g') - } -} diff --git a/node_modules/expand-template/package.json b/node_modules/expand-template/package.json deleted file mode 100644 index 724c2d7..0000000 --- a/node_modules/expand-template/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "_from": "expand-template@^2.0.3", - "_id": "expand-template@2.0.3", - "_inBundle": false, - "_integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", - "_location": "/expand-template", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "expand-template@^2.0.3", - "name": "expand-template", - "escapedName": "expand-template", - "rawSpec": "^2.0.3", - "saveSpec": null, - "fetchSpec": "^2.0.3" - }, - "_requiredBy": [ - "/prebuild-install" - ], - "_resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", - "_shasum": "6e14b3fcee0f3a6340ecb57d2e8918692052a47c", - "_spec": "expand-template@^2.0.3", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/prebuild-install", - "author": { - "name": "LM", - "email": "ralphtheninja@riseup.net" - }, - "bugs": { - "url": "https://github.com/ralphtheninja/expand-template/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Expand placeholders in a template string", - "devDependencies": { - "standard": "^12.0.0", - "tape": "^4.2.2" - }, - "engines": { - "node": ">=6" - }, - "homepage": "https://github.com/ralphtheninja/expand-template", - "keywords": [ - "template", - "expand", - "replace" - ], - "license": "(MIT OR WTFPL)", - "main": "index.js", - "name": "expand-template", - "repository": { - "type": "git", - "url": "git+https://github.com/ralphtheninja/expand-template.git" - }, - "scripts": { - "test": "tape test.js && standard" - }, - "version": "2.0.3" -} diff --git a/node_modules/expand-template/test.js b/node_modules/expand-template/test.js deleted file mode 100644 index ba6ed87..0000000 --- a/node_modules/expand-template/test.js +++ /dev/null @@ -1,67 +0,0 @@ -var test = require('tape') -var Expand = require('./') - -test('default expands {} placeholders', function (t) { - var expand = Expand() - t.equal(typeof expand, 'function', 'is a function') - t.equal(expand('{foo}/{bar}', { - foo: 'BAR', bar: 'FOO' - }), 'BAR/FOO') - t.equal(expand('{foo}{foo}{foo}', { - foo: 'FOO' - }), 'FOOFOOFOO', 'expands one placeholder many times') - t.end() -}) - -test('support for custom separators', function (t) { - var expand = Expand({ sep: '[]' }) - t.equal(expand('[foo]/[bar]', { - foo: 'BAR', bar: 'FOO' - }), 'BAR/FOO') - t.equal(expand('[foo][foo][foo]', { - foo: 'FOO' - }), 'FOOFOOFOO', 'expands one placeholder many times') - t.end() -}) - -test('support for longer custom separators', function (t) { - var expand = Expand({ sep: '[[]]' }) - t.equal(expand('[[foo]]/[[bar]]', { - foo: 'BAR', bar: 'FOO' - }), 'BAR/FOO') - t.equal(expand('[[foo]][[foo]][[foo]]', { - foo: 'FOO' - }), 'FOOFOOFOO', 'expands one placeholder many times') - t.end() -}) - -test('whitespace-insensitive', function (t) { - var expand = Expand({ sep: '[]' }) - t.equal(expand('[ foo ]/[ bar ]', { - foo: 'BAR', bar: 'FOO' - }), 'BAR/FOO') - t.equal(expand('[ foo ][ foo ][ foo]', { - foo: 'FOO' - }), 'FOOFOOFOO', 'expands one placeholder many times') - t.end() -}) - -test('dollar escape', function (t) { - var expand = Expand() - t.equal(expand('before {foo} after', { - foo: '$' - }), 'before $ after') - t.equal(expand('before {foo} after', { - foo: '$&' - }), 'before $& after') - t.equal(expand('before {foo} after', { - foo: '$`' - }), 'before $` after') - t.equal(expand('before {foo} after', { - foo: '$\'' - }), 'before $\' after') - t.equal(expand('before {foo} after', { - foo: '$0' - }), 'before $0 after') - t.end() -}) diff --git a/node_modules/express/History.md b/node_modules/express/History.md deleted file mode 100644 index 6e62a6d..0000000 --- a/node_modules/express/History.md +++ /dev/null @@ -1,3477 +0,0 @@ -4.17.1 / 2019-05-25 -=================== - - * Revert "Improve error message for `null`/`undefined` to `res.status`" - -4.17.0 / 2019-05-16 -=================== - - * Add `express.raw` to parse bodies into `Buffer` - * Add `express.text` to parse bodies into string - * Improve error message for non-strings to `res.sendFile` - * Improve error message for `null`/`undefined` to `res.status` - * Support multiple hosts in `X-Forwarded-Host` - * deps: accepts@~1.3.7 - * deps: body-parser@1.19.0 - - Add encoding MIK - - Add petabyte (`pb`) support - - Fix parsing array brackets after index - - deps: bytes@3.1.0 - - deps: http-errors@1.7.2 - - deps: iconv-lite@0.4.24 - - deps: qs@6.7.0 - - deps: raw-body@2.4.0 - - deps: type-is@~1.6.17 - * deps: content-disposition@0.5.3 - * deps: cookie@0.4.0 - - Add `SameSite=None` support - * deps: finalhandler@~1.1.2 - - Set stricter `Content-Security-Policy` header - - deps: parseurl@~1.3.3 - - deps: statuses@~1.5.0 - * deps: parseurl@~1.3.3 - * deps: proxy-addr@~2.0.5 - - deps: ipaddr.js@1.9.0 - * deps: qs@6.7.0 - - Fix parsing array brackets after index - * deps: range-parser@~1.2.1 - * deps: send@0.17.1 - - Set stricter CSP header in redirect & error responses - - deps: http-errors@~1.7.2 - - deps: mime@1.6.0 - - deps: ms@2.1.1 - - deps: range-parser@~1.2.1 - - deps: statuses@~1.5.0 - - perf: remove redundant `path.normalize` call - * deps: serve-static@1.14.1 - - Set stricter CSP header in redirect response - - deps: parseurl@~1.3.3 - - deps: send@0.17.1 - * deps: setprototypeof@1.1.1 - * deps: statuses@~1.5.0 - - Add `103 Early Hints` - * deps: type-is@~1.6.18 - - deps: mime-types@~2.1.24 - - perf: prevent internal `throw` on invalid type - -4.16.4 / 2018-10-10 -=================== - - * Fix issue where `"Request aborted"` may be logged in `res.sendfile` - * Fix JSDoc for `Router` constructor - * deps: body-parser@1.18.3 - - Fix deprecation warnings on Node.js 10+ - - Fix stack trace for strict json parse error - - deps: depd@~1.1.2 - - deps: http-errors@~1.6.3 - - deps: iconv-lite@0.4.23 - - deps: qs@6.5.2 - - deps: raw-body@2.3.3 - - deps: type-is@~1.6.16 - * deps: proxy-addr@~2.0.4 - - deps: ipaddr.js@1.8.0 - * deps: qs@6.5.2 - * deps: safe-buffer@5.1.2 - -4.16.3 / 2018-03-12 -=================== - - * deps: accepts@~1.3.5 - - deps: mime-types@~2.1.18 - * deps: depd@~1.1.2 - - perf: remove argument reassignment - * deps: encodeurl@~1.0.2 - - Fix encoding `%` as last character - * deps: finalhandler@1.1.1 - - Fix 404 output for bad / missing pathnames - - deps: encodeurl@~1.0.2 - - deps: statuses@~1.4.0 - * deps: proxy-addr@~2.0.3 - - deps: ipaddr.js@1.6.0 - * deps: send@0.16.2 - - Fix incorrect end tag in default error & redirects - - deps: depd@~1.1.2 - - deps: encodeurl@~1.0.2 - - deps: statuses@~1.4.0 - * deps: serve-static@1.13.2 - - Fix incorrect end tag in redirects - - deps: encodeurl@~1.0.2 - - deps: send@0.16.2 - * deps: statuses@~1.4.0 - * deps: type-is@~1.6.16 - - deps: mime-types@~2.1.18 - -4.16.2 / 2017-10-09 -=================== - - * Fix `TypeError` in `res.send` when given `Buffer` and `ETag` header set - * perf: skip parsing of entire `X-Forwarded-Proto` header - -4.16.1 / 2017-09-29 -=================== - - * deps: send@0.16.1 - * deps: serve-static@1.13.1 - - Fix regression when `root` is incorrectly set to a file - - deps: send@0.16.1 - -4.16.0 / 2017-09-28 -=================== - - * Add `"json escape"` setting for `res.json` and `res.jsonp` - * Add `express.json` and `express.urlencoded` to parse bodies - * Add `options` argument to `res.download` - * Improve error message when autoloading invalid view engine - * Improve error messages when non-function provided as middleware - * Skip `Buffer` encoding when not generating ETag for small response - * Use `safe-buffer` for improved Buffer API - * deps: accepts@~1.3.4 - - deps: mime-types@~2.1.16 - * deps: content-type@~1.0.4 - - perf: remove argument reassignment - - perf: skip parameter parsing when no parameters - * deps: etag@~1.8.1 - - perf: replace regular expression with substring - * deps: finalhandler@1.1.0 - - Use `res.headersSent` when available - * deps: parseurl@~1.3.2 - - perf: reduce overhead for full URLs - - perf: unroll the "fast-path" `RegExp` - * deps: proxy-addr@~2.0.2 - - Fix trimming leading / trailing OWS in `X-Forwarded-For` - - deps: forwarded@~0.1.2 - - deps: ipaddr.js@1.5.2 - - perf: reduce overhead when no `X-Forwarded-For` header - * deps: qs@6.5.1 - - Fix parsing & compacting very deep objects - * deps: send@0.16.0 - - Add 70 new types for file extensions - - Add `immutable` option - - Fix missing `` in default error & redirects - - Set charset as "UTF-8" for .js and .json - - Use instance methods on steam to check for listeners - - deps: mime@1.4.1 - - perf: improve path validation speed - * deps: serve-static@1.13.0 - - Add 70 new types for file extensions - - Add `immutable` option - - Set charset as "UTF-8" for .js and .json - - deps: send@0.16.0 - * deps: setprototypeof@1.1.0 - * deps: utils-merge@1.0.1 - * deps: vary@~1.1.2 - - perf: improve header token parsing speed - * perf: re-use options object when generating ETags - * perf: remove dead `.charset` set in `res.jsonp` - -4.15.5 / 2017-09-24 -=================== - - * deps: debug@2.6.9 - * deps: finalhandler@~1.0.6 - - deps: debug@2.6.9 - - deps: parseurl@~1.3.2 - * deps: fresh@0.5.2 - - Fix handling of modified headers with invalid dates - - perf: improve ETag match loop - - perf: improve `If-None-Match` token parsing - * deps: send@0.15.6 - - Fix handling of modified headers with invalid dates - - deps: debug@2.6.9 - - deps: etag@~1.8.1 - - deps: fresh@0.5.2 - - perf: improve `If-Match` token parsing - * deps: serve-static@1.12.6 - - deps: parseurl@~1.3.2 - - deps: send@0.15.6 - - perf: improve slash collapsing - -4.15.4 / 2017-08-06 -=================== - - * deps: debug@2.6.8 - * deps: depd@~1.1.1 - - Remove unnecessary `Buffer` loading - * deps: finalhandler@~1.0.4 - - deps: debug@2.6.8 - * deps: proxy-addr@~1.1.5 - - Fix array argument being altered - - deps: ipaddr.js@1.4.0 - * deps: qs@6.5.0 - * deps: send@0.15.4 - - deps: debug@2.6.8 - - deps: depd@~1.1.1 - - deps: http-errors@~1.6.2 - * deps: serve-static@1.12.4 - - deps: send@0.15.4 - -4.15.3 / 2017-05-16 -=================== - - * Fix error when `res.set` cannot add charset to `Content-Type` - * deps: debug@2.6.7 - - Fix `DEBUG_MAX_ARRAY_LENGTH` - - deps: ms@2.0.0 - * deps: finalhandler@~1.0.3 - - Fix missing `` in HTML document - - deps: debug@2.6.7 - * deps: proxy-addr@~1.1.4 - - deps: ipaddr.js@1.3.0 - * deps: send@0.15.3 - - deps: debug@2.6.7 - - deps: ms@2.0.0 - * deps: serve-static@1.12.3 - - deps: send@0.15.3 - * deps: type-is@~1.6.15 - - deps: mime-types@~2.1.15 - * deps: vary@~1.1.1 - - perf: hoist regular expression - -4.15.2 / 2017-03-06 -=================== - - * deps: qs@6.4.0 - - Fix regression parsing keys starting with `[` - -4.15.1 / 2017-03-05 -=================== - - * deps: send@0.15.1 - - Fix issue when `Date.parse` does not return `NaN` on invalid date - - Fix strict violation in broken environments - * deps: serve-static@1.12.1 - - Fix issue when `Date.parse` does not return `NaN` on invalid date - - deps: send@0.15.1 - -4.15.0 / 2017-03-01 -=================== - - * Add debug message when loading view engine - * Add `next("router")` to exit from router - * Fix case where `router.use` skipped requests routes did not - * Remove usage of `res._headers` private field - - Improves compatibility with Node.js 8 nightly - * Skip routing when `req.url` is not set - * Use `%o` in path debug to tell types apart - * Use `Object.create` to setup request & response prototypes - * Use `setprototypeof` module to replace `__proto__` setting - * Use `statuses` instead of `http` module for status messages - * deps: debug@2.6.1 - - Allow colors in workers - - Deprecated `DEBUG_FD` environment variable set to `3` or higher - - Fix error when running under React Native - - Use same color for same namespace - - deps: ms@0.7.2 - * deps: etag@~1.8.0 - - Use SHA1 instead of MD5 for ETag hashing - - Works with FIPS 140-2 OpenSSL configuration - * deps: finalhandler@~1.0.0 - - Fix exception when `err` cannot be converted to a string - - Fully URL-encode the pathname in the 404 - - Only include the pathname in the 404 message - - Send complete HTML document - - Set `Content-Security-Policy: default-src 'self'` header - - deps: debug@2.6.1 - * deps: fresh@0.5.0 - - Fix false detection of `no-cache` request directive - - Fix incorrect result when `If-None-Match` has both `*` and ETags - - Fix weak `ETag` matching to match spec - - perf: delay reading header values until needed - - perf: enable strict mode - - perf: hoist regular expressions - - perf: remove duplicate conditional - - perf: remove unnecessary boolean coercions - - perf: skip checking modified time if ETag check failed - - perf: skip parsing `If-None-Match` when no `ETag` header - - perf: use `Date.parse` instead of `new Date` - * deps: qs@6.3.1 - - Fix array parsing from skipping empty values - - Fix compacting nested arrays - * deps: send@0.15.0 - - Fix false detection of `no-cache` request directive - - Fix incorrect result when `If-None-Match` has both `*` and ETags - - Fix weak `ETag` matching to match spec - - Remove usage of `res._headers` private field - - Support `If-Match` and `If-Unmodified-Since` headers - - Use `res.getHeaderNames()` when available - - Use `res.headersSent` when available - - deps: debug@2.6.1 - - deps: etag@~1.8.0 - - deps: fresh@0.5.0 - - deps: http-errors@~1.6.1 - * deps: serve-static@1.12.0 - - Fix false detection of `no-cache` request directive - - Fix incorrect result when `If-None-Match` has both `*` and ETags - - Fix weak `ETag` matching to match spec - - Remove usage of `res._headers` private field - - Send complete HTML document in redirect response - - Set default CSP header in redirect response - - Support `If-Match` and `If-Unmodified-Since` headers - - Use `res.getHeaderNames()` when available - - Use `res.headersSent` when available - - deps: send@0.15.0 - * perf: add fast match path for `*` route - * perf: improve `req.ips` performance - -4.14.1 / 2017-01-28 -=================== - - * deps: content-disposition@0.5.2 - * deps: finalhandler@0.5.1 - - Fix exception when `err.headers` is not an object - - deps: statuses@~1.3.1 - - perf: hoist regular expressions - - perf: remove duplicate validation path - * deps: proxy-addr@~1.1.3 - - deps: ipaddr.js@1.2.0 - * deps: send@0.14.2 - - deps: http-errors@~1.5.1 - - deps: ms@0.7.2 - - deps: statuses@~1.3.1 - * deps: serve-static@~1.11.2 - - deps: send@0.14.2 - * deps: type-is@~1.6.14 - - deps: mime-types@~2.1.13 - -4.14.0 / 2016-06-16 -=================== - - * Add `acceptRanges` option to `res.sendFile`/`res.sendfile` - * Add `cacheControl` option to `res.sendFile`/`res.sendfile` - * Add `options` argument to `req.range` - - Includes the `combine` option - * Encode URL in `res.location`/`res.redirect` if not already encoded - * Fix some redirect handling in `res.sendFile`/`res.sendfile` - * Fix Windows absolute path check using forward slashes - * Improve error with invalid arguments to `req.get()` - * Improve performance for `res.json`/`res.jsonp` in most cases - * Improve `Range` header handling in `res.sendFile`/`res.sendfile` - * deps: accepts@~1.3.3 - - Fix including type extensions in parameters in `Accept` parsing - - Fix parsing `Accept` parameters with quoted equals - - Fix parsing `Accept` parameters with quoted semicolons - - Many performance improvements - - deps: mime-types@~2.1.11 - - deps: negotiator@0.6.1 - * deps: content-type@~1.0.2 - - perf: enable strict mode - * deps: cookie@0.3.1 - - Add `sameSite` option - - Fix cookie `Max-Age` to never be a floating point number - - Improve error message when `encode` is not a function - - Improve error message when `expires` is not a `Date` - - Throw better error for invalid argument to parse - - Throw on invalid values provided to `serialize` - - perf: enable strict mode - - perf: hoist regular expression - - perf: use for loop in parse - - perf: use string concatenation for serialization - * deps: finalhandler@0.5.0 - - Change invalid or non-numeric status code to 500 - - Overwrite status message to match set status code - - Prefer `err.statusCode` if `err.status` is invalid - - Set response headers from `err.headers` object - - Use `statuses` instead of `http` module for status messages - * deps: proxy-addr@~1.1.2 - - Fix accepting various invalid netmasks - - Fix IPv6-mapped IPv4 validation edge cases - - IPv4 netmasks must be contiguous - - IPv6 addresses cannot be used as a netmask - - deps: ipaddr.js@1.1.1 - * deps: qs@6.2.0 - - Add `decoder` option in `parse` function - * deps: range-parser@~1.2.0 - - Add `combine` option to combine overlapping ranges - - Fix incorrectly returning -1 when there is at least one valid range - - perf: remove internal function - * deps: send@0.14.1 - - Add `acceptRanges` option - - Add `cacheControl` option - - Attempt to combine multiple ranges into single range - - Correctly inherit from `Stream` class - - Fix `Content-Range` header in 416 responses when using `start`/`end` options - - Fix `Content-Range` header missing from default 416 responses - - Fix redirect error when `path` contains raw non-URL characters - - Fix redirect when `path` starts with multiple forward slashes - - Ignore non-byte `Range` headers - - deps: http-errors@~1.5.0 - - deps: range-parser@~1.2.0 - - deps: statuses@~1.3.0 - - perf: remove argument reassignment - * deps: serve-static@~1.11.1 - - Add `acceptRanges` option - - Add `cacheControl` option - - Attempt to combine multiple ranges into single range - - Fix redirect error when `req.url` contains raw non-URL characters - - Ignore non-byte `Range` headers - - Use status code 301 for redirects - - deps: send@0.14.1 - * deps: type-is@~1.6.13 - - Fix type error when given invalid type to match against - - deps: mime-types@~2.1.11 - * deps: vary@~1.1.0 - - Only accept valid field names in the `field` argument - * perf: use strict equality when possible - -4.13.4 / 2016-01-21 -=================== - - * deps: content-disposition@0.5.1 - - perf: enable strict mode - * deps: cookie@0.1.5 - - Throw on invalid values provided to `serialize` - * deps: depd@~1.1.0 - - Support web browser loading - - perf: enable strict mode - * deps: escape-html@~1.0.3 - - perf: enable strict mode - - perf: optimize string replacement - - perf: use faster string coercion - * deps: finalhandler@0.4.1 - - deps: escape-html@~1.0.3 - * deps: merge-descriptors@1.0.1 - - perf: enable strict mode - * deps: methods@~1.1.2 - - perf: enable strict mode - * deps: parseurl@~1.3.1 - - perf: enable strict mode - * deps: proxy-addr@~1.0.10 - - deps: ipaddr.js@1.0.5 - - perf: enable strict mode - * deps: range-parser@~1.0.3 - - perf: enable strict mode - * deps: send@0.13.1 - - deps: depd@~1.1.0 - - deps: destroy@~1.0.4 - - deps: escape-html@~1.0.3 - - deps: range-parser@~1.0.3 - * deps: serve-static@~1.10.2 - - deps: escape-html@~1.0.3 - - deps: parseurl@~1.3.0 - - deps: send@0.13.1 - -4.13.3 / 2015-08-02 -=================== - - * Fix infinite loop condition using `mergeParams: true` - * Fix inner numeric indices incorrectly altering parent `req.params` - -4.13.2 / 2015-07-31 -=================== - - * deps: accepts@~1.2.12 - - deps: mime-types@~2.1.4 - * deps: array-flatten@1.1.1 - - perf: enable strict mode - * deps: path-to-regexp@0.1.7 - - Fix regression with escaped round brackets and matching groups - * deps: type-is@~1.6.6 - - deps: mime-types@~2.1.4 - -4.13.1 / 2015-07-05 -=================== - - * deps: accepts@~1.2.10 - - deps: mime-types@~2.1.2 - * deps: qs@4.0.0 - - Fix dropping parameters like `hasOwnProperty` - - Fix various parsing edge cases - * deps: type-is@~1.6.4 - - deps: mime-types@~2.1.2 - - perf: enable strict mode - - perf: remove argument reassignment - -4.13.0 / 2015-06-20 -=================== - - * Add settings to debug output - * Fix `res.format` error when only `default` provided - * Fix issue where `next('route')` in `app.param` would incorrectly skip values - * Fix hiding platform issues with `decodeURIComponent` - - Only `URIError`s are a 400 - * Fix using `*` before params in routes - * Fix using capture groups before params in routes - * Simplify `res.cookie` to call `res.append` - * Use `array-flatten` module for flattening arrays - * deps: accepts@~1.2.9 - - deps: mime-types@~2.1.1 - - perf: avoid argument reassignment & argument slice - - perf: avoid negotiator recursive construction - - perf: enable strict mode - - perf: remove unnecessary bitwise operator - * deps: cookie@0.1.3 - - perf: deduce the scope of try-catch deopt - - perf: remove argument reassignments - * deps: escape-html@1.0.2 - * deps: etag@~1.7.0 - - Always include entity length in ETags for hash length extensions - - Generate non-Stats ETags using MD5 only (no longer CRC32) - - Improve stat performance by removing hashing - - Improve support for JXcore - - Remove base64 padding in ETags to shorten - - Support "fake" stats objects in environments without fs - - Use MD5 instead of MD4 in weak ETags over 1KB - * deps: finalhandler@0.4.0 - - Fix a false-positive when unpiping in Node.js 0.8 - - Support `statusCode` property on `Error` objects - - Use `unpipe` module for unpiping requests - - deps: escape-html@1.0.2 - - deps: on-finished@~2.3.0 - - perf: enable strict mode - - perf: remove argument reassignment - * deps: fresh@0.3.0 - - Add weak `ETag` matching support - * deps: on-finished@~2.3.0 - - Add defined behavior for HTTP `CONNECT` requests - - Add defined behavior for HTTP `Upgrade` requests - - deps: ee-first@1.1.1 - * deps: path-to-regexp@0.1.6 - * deps: send@0.13.0 - - Allow Node.js HTTP server to set `Date` response header - - Fix incorrectly removing `Content-Location` on 304 response - - Improve the default redirect response headers - - Send appropriate headers on default error response - - Use `http-errors` for standard emitted errors - - Use `statuses` instead of `http` module for status messages - - deps: escape-html@1.0.2 - - deps: etag@~1.7.0 - - deps: fresh@0.3.0 - - deps: on-finished@~2.3.0 - - perf: enable strict mode - - perf: remove unnecessary array allocations - * deps: serve-static@~1.10.0 - - Add `fallthrough` option - - Fix reading options from options prototype - - Improve the default redirect response headers - - Malformed URLs now `next()` instead of 400 - - deps: escape-html@1.0.2 - - deps: send@0.13.0 - - perf: enable strict mode - - perf: remove argument reassignment - * deps: type-is@~1.6.3 - - deps: mime-types@~2.1.1 - - perf: reduce try block size - - perf: remove bitwise operations - * perf: enable strict mode - * perf: isolate `app.render` try block - * perf: remove argument reassignments in application - * perf: remove argument reassignments in request prototype - * perf: remove argument reassignments in response prototype - * perf: remove argument reassignments in routing - * perf: remove argument reassignments in `View` - * perf: skip attempting to decode zero length string - * perf: use saved reference to `http.STATUS_CODES` - -4.12.4 / 2015-05-17 -=================== - - * deps: accepts@~1.2.7 - - deps: mime-types@~2.0.11 - - deps: negotiator@0.5.3 - * deps: debug@~2.2.0 - - deps: ms@0.7.1 - * deps: depd@~1.0.1 - * deps: etag@~1.6.0 - - Improve support for JXcore - - Support "fake" stats objects in environments without `fs` - * deps: finalhandler@0.3.6 - - deps: debug@~2.2.0 - - deps: on-finished@~2.2.1 - * deps: on-finished@~2.2.1 - - Fix `isFinished(req)` when data buffered - * deps: proxy-addr@~1.0.8 - - deps: ipaddr.js@1.0.1 - * deps: qs@2.4.2 - - Fix allowing parameters like `constructor` - * deps: send@0.12.3 - - deps: debug@~2.2.0 - - deps: depd@~1.0.1 - - deps: etag@~1.6.0 - - deps: ms@0.7.1 - - deps: on-finished@~2.2.1 - * deps: serve-static@~1.9.3 - - deps: send@0.12.3 - * deps: type-is@~1.6.2 - - deps: mime-types@~2.0.11 - -4.12.3 / 2015-03-17 -=================== - - * deps: accepts@~1.2.5 - - deps: mime-types@~2.0.10 - * deps: debug@~2.1.3 - - Fix high intensity foreground color for bold - - deps: ms@0.7.0 - * deps: finalhandler@0.3.4 - - deps: debug@~2.1.3 - * deps: proxy-addr@~1.0.7 - - deps: ipaddr.js@0.1.9 - * deps: qs@2.4.1 - - Fix error when parameter `hasOwnProperty` is present - * deps: send@0.12.2 - - Throw errors early for invalid `extensions` or `index` options - - deps: debug@~2.1.3 - * deps: serve-static@~1.9.2 - - deps: send@0.12.2 - * deps: type-is@~1.6.1 - - deps: mime-types@~2.0.10 - -4.12.2 / 2015-03-02 -=================== - - * Fix regression where `"Request aborted"` is logged using `res.sendFile` - -4.12.1 / 2015-03-01 -=================== - - * Fix constructing application with non-configurable prototype properties - * Fix `ECONNRESET` errors from `res.sendFile` usage - * Fix `req.host` when using "trust proxy" hops count - * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count - * Fix wrong `code` on aborted connections from `res.sendFile` - * deps: merge-descriptors@1.0.0 - -4.12.0 / 2015-02-23 -=================== - - * Fix `"trust proxy"` setting to inherit when app is mounted - * Generate `ETag`s for all request responses - - No longer restricted to only responses for `GET` and `HEAD` requests - * Use `content-type` to parse `Content-Type` headers - * deps: accepts@~1.2.4 - - Fix preference sorting to be stable for long acceptable lists - - deps: mime-types@~2.0.9 - - deps: negotiator@0.5.1 - * deps: cookie-signature@1.0.6 - * deps: send@0.12.1 - - Always read the stat size from the file - - Fix mutating passed-in `options` - - deps: mime@1.3.4 - * deps: serve-static@~1.9.1 - - deps: send@0.12.1 - * deps: type-is@~1.6.0 - - fix argument reassignment - - fix false-positives in `hasBody` `Transfer-Encoding` check - - support wildcard for both type and subtype (`*/*`) - - deps: mime-types@~2.0.9 - -4.11.2 / 2015-02-01 -=================== - - * Fix `res.redirect` double-calling `res.end` for `HEAD` requests - * deps: accepts@~1.2.3 - - deps: mime-types@~2.0.8 - * deps: proxy-addr@~1.0.6 - - deps: ipaddr.js@0.1.8 - * deps: type-is@~1.5.6 - - deps: mime-types@~2.0.8 - -4.11.1 / 2015-01-20 -=================== - - * deps: send@0.11.1 - - Fix root path disclosure - * deps: serve-static@~1.8.1 - - Fix redirect loop in Node.js 0.11.14 - - Fix root path disclosure - - deps: send@0.11.1 - -4.11.0 / 2015-01-13 -=================== - - * Add `res.append(field, val)` to append headers - * Deprecate leading `:` in `name` for `app.param(name, fn)` - * Deprecate `req.param()` -- use `req.params`, `req.body`, or `req.query` instead - * Deprecate `app.param(fn)` - * Fix `OPTIONS` responses to include the `HEAD` method properly - * Fix `res.sendFile` not always detecting aborted connection - * Match routes iteratively to prevent stack overflows - * deps: accepts@~1.2.2 - - deps: mime-types@~2.0.7 - - deps: negotiator@0.5.0 - * deps: send@0.11.0 - - deps: debug@~2.1.1 - - deps: etag@~1.5.1 - - deps: ms@0.7.0 - - deps: on-finished@~2.2.0 - * deps: serve-static@~1.8.0 - - deps: send@0.11.0 - -4.10.8 / 2015-01-13 -=================== - - * Fix crash from error within `OPTIONS` response handler - * deps: proxy-addr@~1.0.5 - - deps: ipaddr.js@0.1.6 - -4.10.7 / 2015-01-04 -=================== - - * Fix `Allow` header for `OPTIONS` to not contain duplicate methods - * Fix incorrect "Request aborted" for `res.sendFile` when `HEAD` or 304 - * deps: debug@~2.1.1 - * deps: finalhandler@0.3.3 - - deps: debug@~2.1.1 - - deps: on-finished@~2.2.0 - * deps: methods@~1.1.1 - * deps: on-finished@~2.2.0 - * deps: serve-static@~1.7.2 - - Fix potential open redirect when mounted at root - * deps: type-is@~1.5.5 - - deps: mime-types@~2.0.7 - -4.10.6 / 2014-12-12 -=================== - - * Fix exception in `req.fresh`/`req.stale` without response headers - -4.10.5 / 2014-12-10 -=================== - - * Fix `res.send` double-calling `res.end` for `HEAD` requests - * deps: accepts@~1.1.4 - - deps: mime-types@~2.0.4 - * deps: type-is@~1.5.4 - - deps: mime-types@~2.0.4 - -4.10.4 / 2014-11-24 -=================== - - * Fix `res.sendfile` logging standard write errors - -4.10.3 / 2014-11-23 -=================== - - * Fix `res.sendFile` logging standard write errors - * deps: etag@~1.5.1 - * deps: proxy-addr@~1.0.4 - - deps: ipaddr.js@0.1.5 - * deps: qs@2.3.3 - - Fix `arrayLimit` behavior - -4.10.2 / 2014-11-09 -=================== - - * Correctly invoke async router callback asynchronously - * deps: accepts@~1.1.3 - - deps: mime-types@~2.0.3 - * deps: type-is@~1.5.3 - - deps: mime-types@~2.0.3 - -4.10.1 / 2014-10-28 -=================== - - * Fix handling of URLs containing `://` in the path - * deps: qs@2.3.2 - - Fix parsing of mixed objects and values - -4.10.0 / 2014-10-23 -=================== - - * Add support for `app.set('views', array)` - - Views are looked up in sequence in array of directories - * Fix `res.send(status)` to mention `res.sendStatus(status)` - * Fix handling of invalid empty URLs - * Use `content-disposition` module for `res.attachment`/`res.download` - - Sends standards-compliant `Content-Disposition` header - - Full Unicode support - * Use `path.resolve` in view lookup - * deps: debug@~2.1.0 - - Implement `DEBUG_FD` env variable support - * deps: depd@~1.0.0 - * deps: etag@~1.5.0 - - Improve string performance - - Slightly improve speed for weak ETags over 1KB - * deps: finalhandler@0.3.2 - - Terminate in progress response only on error - - Use `on-finished` to determine request status - - deps: debug@~2.1.0 - - deps: on-finished@~2.1.1 - * deps: on-finished@~2.1.1 - - Fix handling of pipelined requests - * deps: qs@2.3.0 - - Fix parsing of mixed implicit and explicit arrays - * deps: send@0.10.1 - - deps: debug@~2.1.0 - - deps: depd@~1.0.0 - - deps: etag@~1.5.0 - - deps: on-finished@~2.1.1 - * deps: serve-static@~1.7.1 - - deps: send@0.10.1 - -4.9.8 / 2014-10-17 -================== - - * Fix `res.redirect` body when redirect status specified - * deps: accepts@~1.1.2 - - Fix error when media type has invalid parameter - - deps: negotiator@0.4.9 - -4.9.7 / 2014-10-10 -================== - - * Fix using same param name in array of paths - -4.9.6 / 2014-10-08 -================== - - * deps: accepts@~1.1.1 - - deps: mime-types@~2.0.2 - - deps: negotiator@0.4.8 - * deps: serve-static@~1.6.4 - - Fix redirect loop when index file serving disabled - * deps: type-is@~1.5.2 - - deps: mime-types@~2.0.2 - -4.9.5 / 2014-09-24 -================== - - * deps: etag@~1.4.0 - * deps: proxy-addr@~1.0.3 - - Use `forwarded` npm module - * deps: send@0.9.3 - - deps: etag@~1.4.0 - * deps: serve-static@~1.6.3 - - deps: send@0.9.3 - -4.9.4 / 2014-09-19 -================== - - * deps: qs@2.2.4 - - Fix issue with object keys starting with numbers truncated - -4.9.3 / 2014-09-18 -================== - - * deps: proxy-addr@~1.0.2 - - Fix a global leak when multiple subnets are trusted - - deps: ipaddr.js@0.1.3 - -4.9.2 / 2014-09-17 -================== - - * Fix regression for empty string `path` in `app.use` - * Fix `router.use` to accept array of middleware without path - * Improve error message for bad `app.use` arguments - -4.9.1 / 2014-09-16 -================== - - * Fix `app.use` to accept array of middleware without path - * deps: depd@0.4.5 - * deps: etag@~1.3.1 - * deps: send@0.9.2 - - deps: depd@0.4.5 - - deps: etag@~1.3.1 - - deps: range-parser@~1.0.2 - * deps: serve-static@~1.6.2 - - deps: send@0.9.2 - -4.9.0 / 2014-09-08 -================== - - * Add `res.sendStatus` - * Invoke callback for sendfile when client aborts - - Applies to `res.sendFile`, `res.sendfile`, and `res.download` - - `err` will be populated with request aborted error - * Support IP address host in `req.subdomains` - * Use `etag` to generate `ETag` headers - * deps: accepts@~1.1.0 - - update `mime-types` - * deps: cookie-signature@1.0.5 - * deps: debug@~2.0.0 - * deps: finalhandler@0.2.0 - - Set `X-Content-Type-Options: nosniff` header - - deps: debug@~2.0.0 - * deps: fresh@0.2.4 - * deps: media-typer@0.3.0 - - Throw error when parameter format invalid on parse - * deps: qs@2.2.3 - - Fix issue where first empty value in array is discarded - * deps: range-parser@~1.0.2 - * deps: send@0.9.1 - - Add `lastModified` option - - Use `etag` to generate `ETag` header - - deps: debug@~2.0.0 - - deps: fresh@0.2.4 - * deps: serve-static@~1.6.1 - - Add `lastModified` option - - deps: send@0.9.1 - * deps: type-is@~1.5.1 - - fix `hasbody` to be true for `content-length: 0` - - deps: media-typer@0.3.0 - - deps: mime-types@~2.0.1 - * deps: vary@~1.0.0 - - Accept valid `Vary` header string as `field` - -4.8.8 / 2014-09-04 -================== - - * deps: send@0.8.5 - - Fix a path traversal issue when using `root` - - Fix malicious path detection for empty string path - * deps: serve-static@~1.5.4 - - deps: send@0.8.5 - -4.8.7 / 2014-08-29 -================== - - * deps: qs@2.2.2 - - Remove unnecessary cloning - -4.8.6 / 2014-08-27 -================== - - * deps: qs@2.2.0 - - Array parsing fix - - Performance improvements - -4.8.5 / 2014-08-18 -================== - - * deps: send@0.8.3 - - deps: destroy@1.0.3 - - deps: on-finished@2.1.0 - * deps: serve-static@~1.5.3 - - deps: send@0.8.3 - -4.8.4 / 2014-08-14 -================== - - * deps: qs@1.2.2 - * deps: send@0.8.2 - - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` - * deps: serve-static@~1.5.2 - - deps: send@0.8.2 - -4.8.3 / 2014-08-10 -================== - - * deps: parseurl@~1.3.0 - * deps: qs@1.2.1 - * deps: serve-static@~1.5.1 - - Fix parsing of weird `req.originalUrl` values - - deps: parseurl@~1.3.0 - - deps: utils-merge@1.0.0 - -4.8.2 / 2014-08-07 -================== - - * deps: qs@1.2.0 - - Fix parsing array of objects - -4.8.1 / 2014-08-06 -================== - - * fix incorrect deprecation warnings on `res.download` - * deps: qs@1.1.0 - - Accept urlencoded square brackets - - Accept empty values in implicit array notation - -4.8.0 / 2014-08-05 -================== - - * add `res.sendFile` - - accepts a file system path instead of a URL - - requires an absolute path or `root` option specified - * deprecate `res.sendfile` -- use `res.sendFile` instead - * support mounted app as any argument to `app.use()` - * deps: qs@1.0.2 - - Complete rewrite - - Limits array length to 20 - - Limits object depth to 5 - - Limits parameters to 1,000 - * deps: send@0.8.1 - - Add `extensions` option - * deps: serve-static@~1.5.0 - - Add `extensions` option - - deps: send@0.8.1 - -4.7.4 / 2014-08-04 -================== - - * fix `res.sendfile` regression for serving directory index files - * deps: send@0.7.4 - - Fix incorrect 403 on Windows and Node.js 0.11 - - Fix serving index files without root dir - * deps: serve-static@~1.4.4 - - deps: send@0.7.4 - -4.7.3 / 2014-08-04 -================== - - * deps: send@0.7.3 - - Fix incorrect 403 on Windows and Node.js 0.11 - * deps: serve-static@~1.4.3 - - Fix incorrect 403 on Windows and Node.js 0.11 - - deps: send@0.7.3 - -4.7.2 / 2014-07-27 -================== - - * deps: depd@0.4.4 - - Work-around v8 generating empty stack traces - * deps: send@0.7.2 - - deps: depd@0.4.4 - * deps: serve-static@~1.4.2 - -4.7.1 / 2014-07-26 -================== - - * deps: depd@0.4.3 - - Fix exception when global `Error.stackTraceLimit` is too low - * deps: send@0.7.1 - - deps: depd@0.4.3 - * deps: serve-static@~1.4.1 - -4.7.0 / 2014-07-25 -================== - - * fix `req.protocol` for proxy-direct connections - * configurable query parser with `app.set('query parser', parser)` - - `app.set('query parser', 'extended')` parse with "qs" module - - `app.set('query parser', 'simple')` parse with "querystring" core module - - `app.set('query parser', false)` disable query string parsing - - `app.set('query parser', true)` enable simple parsing - * deprecate `res.json(status, obj)` -- use `res.status(status).json(obj)` instead - * deprecate `res.jsonp(status, obj)` -- use `res.status(status).jsonp(obj)` instead - * deprecate `res.send(status, body)` -- use `res.status(status).send(body)` instead - * deps: debug@1.0.4 - * deps: depd@0.4.2 - - Add `TRACE_DEPRECATION` environment variable - - Remove non-standard grey color from color output - - Support `--no-deprecation` argument - - Support `--trace-deprecation` argument - * deps: finalhandler@0.1.0 - - Respond after request fully read - - deps: debug@1.0.4 - * deps: parseurl@~1.2.0 - - Cache URLs based on original value - - Remove no-longer-needed URL mis-parse work-around - - Simplify the "fast-path" `RegExp` - * deps: send@0.7.0 - - Add `dotfiles` option - - Cap `maxAge` value to 1 year - - deps: debug@1.0.4 - - deps: depd@0.4.2 - * deps: serve-static@~1.4.0 - - deps: parseurl@~1.2.0 - - deps: send@0.7.0 - * perf: prevent multiple `Buffer` creation in `res.send` - -4.6.1 / 2014-07-12 -================== - - * fix `subapp.mountpath` regression for `app.use(subapp)` - -4.6.0 / 2014-07-11 -================== - - * accept multiple callbacks to `app.use()` - * add explicit "Rosetta Flash JSONP abuse" protection - - previous versions are not vulnerable; this is just explicit protection - * catch errors in multiple `req.param(name, fn)` handlers - * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead - * fix `res.send(status, num)` to send `num` as json (not error) - * remove unnecessary escaping when `res.jsonp` returns JSON response - * support non-string `path` in `app.use(path, fn)` - - supports array of paths - - supports `RegExp` - * router: fix optimization on router exit - * router: refactor location of `try` blocks - * router: speed up standard `app.use(fn)` - * deps: debug@1.0.3 - - Add support for multiple wildcards in namespaces - * deps: finalhandler@0.0.3 - - deps: debug@1.0.3 - * deps: methods@1.1.0 - - add `CONNECT` - * deps: parseurl@~1.1.3 - - faster parsing of href-only URLs - * deps: path-to-regexp@0.1.3 - * deps: send@0.6.0 - - deps: debug@1.0.3 - * deps: serve-static@~1.3.2 - - deps: parseurl@~1.1.3 - - deps: send@0.6.0 - * perf: fix arguments reassign deopt in some `res` methods - -4.5.1 / 2014-07-06 -================== - - * fix routing regression when altering `req.method` - -4.5.0 / 2014-07-04 -================== - - * add deprecation message to non-plural `req.accepts*` - * add deprecation message to `res.send(body, status)` - * add deprecation message to `res.vary()` - * add `headers` option to `res.sendfile` - - use to set headers on successful file transfer - * add `mergeParams` option to `Router` - - merges `req.params` from parent routes - * add `req.hostname` -- correct name for what `req.host` returns - * deprecate things with `depd` module - * deprecate `req.host` -- use `req.hostname` instead - * fix behavior when handling request without routes - * fix handling when `route.all` is only route - * invoke `router.param()` only when route matches - * restore `req.params` after invoking router - * use `finalhandler` for final response handling - * use `media-typer` to alter content-type charset - * deps: accepts@~1.0.7 - * deps: send@0.5.0 - - Accept string for `maxage` (converted by `ms`) - - Include link in default redirect response - * deps: serve-static@~1.3.0 - - Accept string for `maxAge` (converted by `ms`) - - Add `setHeaders` option - - Include HTML link in redirect response - - deps: send@0.5.0 - * deps: type-is@~1.3.2 - -4.4.5 / 2014-06-26 -================== - - * deps: cookie-signature@1.0.4 - - fix for timing attacks - -4.4.4 / 2014-06-20 -================== - - * fix `res.attachment` Unicode filenames in Safari - * fix "trim prefix" debug message in `express:router` - * deps: accepts@~1.0.5 - * deps: buffer-crc32@0.2.3 - -4.4.3 / 2014-06-11 -================== - - * fix persistence of modified `req.params[name]` from `app.param()` - * deps: accepts@1.0.3 - - deps: negotiator@0.4.6 - * deps: debug@1.0.2 - * deps: send@0.4.3 - - Do not throw uncatchable error on file open race condition - - Use `escape-html` for HTML escaping - - deps: debug@1.0.2 - - deps: finished@1.2.2 - - deps: fresh@0.2.2 - * deps: serve-static@1.2.3 - - Do not throw uncatchable error on file open race condition - - deps: send@0.4.3 - -4.4.2 / 2014-06-09 -================== - - * fix catching errors from top-level handlers - * use `vary` module for `res.vary` - * deps: debug@1.0.1 - * deps: proxy-addr@1.0.1 - * deps: send@0.4.2 - - fix "event emitter leak" warnings - - deps: debug@1.0.1 - - deps: finished@1.2.1 - * deps: serve-static@1.2.2 - - fix "event emitter leak" warnings - - deps: send@0.4.2 - * deps: type-is@1.2.1 - -4.4.1 / 2014-06-02 -================== - - * deps: methods@1.0.1 - * deps: send@0.4.1 - - Send `max-age` in `Cache-Control` in correct format - * deps: serve-static@1.2.1 - - use `escape-html` for escaping - - deps: send@0.4.1 - -4.4.0 / 2014-05-30 -================== - - * custom etag control with `app.set('etag', val)` - - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation - - `app.set('etag', 'weak')` weak tag - - `app.set('etag', 'strong')` strong etag - - `app.set('etag', false)` turn off - - `app.set('etag', true)` standard etag - * mark `res.send` ETag as weak and reduce collisions - * update accepts to 1.0.2 - - Fix interpretation when header not in request - * update send to 0.4.0 - - Calculate ETag with md5 for reduced collisions - - Ignore stream errors after request ends - - deps: debug@0.8.1 - * update serve-static to 1.2.0 - - Calculate ETag with md5 for reduced collisions - - Ignore stream errors after request ends - - deps: send@0.4.0 - -4.3.2 / 2014-05-28 -================== - - * fix handling of errors from `router.param()` callbacks - -4.3.1 / 2014-05-23 -================== - - * revert "fix behavior of multiple `app.VERB` for the same path" - - this caused a regression in the order of route execution - -4.3.0 / 2014-05-21 -================== - - * add `req.baseUrl` to access the path stripped from `req.url` in routes - * fix behavior of multiple `app.VERB` for the same path - * fix issue routing requests among sub routers - * invoke `router.param()` only when necessary instead of every match - * proper proxy trust with `app.set('trust proxy', trust)` - - `app.set('trust proxy', 1)` trust first hop - - `app.set('trust proxy', 'loopback')` trust loopback addresses - - `app.set('trust proxy', '10.0.0.1')` trust single IP - - `app.set('trust proxy', '10.0.0.1/16')` trust subnet - - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list - - `app.set('trust proxy', false)` turn off - - `app.set('trust proxy', true)` trust everything - * set proper `charset` in `Content-Type` for `res.send` - * update type-is to 1.2.0 - - support suffix matching - -4.2.0 / 2014-05-11 -================== - - * deprecate `app.del()` -- use `app.delete()` instead - * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead - - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` - * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead - - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` - * fix `req.next` when inside router instance - * include `ETag` header in `HEAD` requests - * keep previous `Content-Type` for `res.jsonp` - * support PURGE method - - add `app.purge` - - add `router.purge` - - include PURGE in `app.all` - * update debug to 0.8.0 - - add `enable()` method - - change from stderr to stdout - * update methods to 1.0.0 - - add PURGE - -4.1.2 / 2014-05-08 -================== - - * fix `req.host` for IPv6 literals - * fix `res.jsonp` error if callback param is object - -4.1.1 / 2014-04-27 -================== - - * fix package.json to reflect supported node version - -4.1.0 / 2014-04-24 -================== - - * pass options from `res.sendfile` to `send` - * preserve casing of headers in `res.header` and `res.set` - * support unicode file names in `res.attachment` and `res.download` - * update accepts to 1.0.1 - - deps: negotiator@0.4.0 - * update cookie to 0.1.2 - - Fix for maxAge == 0 - - made compat with expires field - * update send to 0.3.0 - - Accept API options in options object - - Coerce option types - - Control whether to generate etags - - Default directory access to 403 when index disabled - - Fix sending files with dots without root set - - Include file path in etag - - Make "Can't set headers after they are sent." catchable - - Send full entity-body for multi range requests - - Set etags to "weak" - - Support "If-Range" header - - Support multiple index paths - - deps: mime@1.2.11 - * update serve-static to 1.1.0 - - Accept options directly to `send` module - - Resolve relative paths at middleware setup - - Use parseurl to parse the URL from request - - deps: send@0.3.0 - * update type-is to 1.1.0 - - add non-array values support - - add `multipart` as a shorthand - -4.0.0 / 2014-04-09 -================== - - * remove: - - node 0.8 support - - connect and connect's patches except for charset handling - - express(1) - moved to [express-generator](https://github.com/expressjs/generator) - - `express.createServer()` - it has been deprecated for a long time. Use `express()` - - `app.configure` - use logic in your own app code - - `app.router` - is removed - - `req.auth` - use `basic-auth` instead - - `req.accepted*` - use `req.accepts*()` instead - - `res.location` - relative URL resolution is removed - - `res.charset` - include the charset in the content type when using `res.set()` - - all bundled middleware except `static` - * change: - - `app.route` -> `app.mountpath` when mounting an express app in another express app - - `json spaces` no longer enabled by default in development - - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` - - `req.params` is now an object instead of an array - - `res.locals` is no longer a function. It is a plain js object. Treat it as such. - - `res.headerSent` -> `res.headersSent` to match node.js ServerResponse object - * refactor: - - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) - - `req.is` with [type-is](https://github.com/expressjs/type-is) - - [path-to-regexp](https://github.com/component/path-to-regexp) - * add: - - `app.router()` - returns the app Router instance - - `app.route()` - Proxy to the app's `Router#route()` method to create a new route - - Router & Route - public API - -3.21.2 / 2015-07-31 -=================== - - * deps: connect@2.30.2 - - deps: body-parser@~1.13.3 - - deps: compression@~1.5.2 - - deps: errorhandler@~1.4.2 - - deps: method-override@~2.3.5 - - deps: serve-index@~1.7.2 - - deps: type-is@~1.6.6 - - deps: vhost@~3.0.1 - * deps: vary@~1.0.1 - - Fix setting empty header from empty `field` - - perf: enable strict mode - - perf: remove argument reassignments - -3.21.1 / 2015-07-05 -=================== - - * deps: basic-auth@~1.0.3 - * deps: connect@2.30.1 - - deps: body-parser@~1.13.2 - - deps: compression@~1.5.1 - - deps: errorhandler@~1.4.1 - - deps: morgan@~1.6.1 - - deps: pause@0.1.0 - - deps: qs@4.0.0 - - deps: serve-index@~1.7.1 - - deps: type-is@~1.6.4 - -3.21.0 / 2015-06-18 -=================== - - * deps: basic-auth@1.0.2 - - perf: enable strict mode - - perf: hoist regular expression - - perf: parse with regular expressions - - perf: remove argument reassignment - * deps: connect@2.30.0 - - deps: body-parser@~1.13.1 - - deps: bytes@2.1.0 - - deps: compression@~1.5.0 - - deps: cookie@0.1.3 - - deps: cookie-parser@~1.3.5 - - deps: csurf@~1.8.3 - - deps: errorhandler@~1.4.0 - - deps: express-session@~1.11.3 - - deps: finalhandler@0.4.0 - - deps: fresh@0.3.0 - - deps: morgan@~1.6.0 - - deps: serve-favicon@~2.3.0 - - deps: serve-index@~1.7.0 - - deps: serve-static@~1.10.0 - - deps: type-is@~1.6.3 - * deps: cookie@0.1.3 - - perf: deduce the scope of try-catch deopt - - perf: remove argument reassignments - * deps: escape-html@1.0.2 - * deps: etag@~1.7.0 - - Always include entity length in ETags for hash length extensions - - Generate non-Stats ETags using MD5 only (no longer CRC32) - - Improve stat performance by removing hashing - - Improve support for JXcore - - Remove base64 padding in ETags to shorten - - Support "fake" stats objects in environments without fs - - Use MD5 instead of MD4 in weak ETags over 1KB - * deps: fresh@0.3.0 - - Add weak `ETag` matching support - * deps: mkdirp@0.5.1 - - Work in global strict mode - * deps: send@0.13.0 - - Allow Node.js HTTP server to set `Date` response header - - Fix incorrectly removing `Content-Location` on 304 response - - Improve the default redirect response headers - - Send appropriate headers on default error response - - Use `http-errors` for standard emitted errors - - Use `statuses` instead of `http` module for status messages - - deps: escape-html@1.0.2 - - deps: etag@~1.7.0 - - deps: fresh@0.3.0 - - deps: on-finished@~2.3.0 - - perf: enable strict mode - - perf: remove unnecessary array allocations - -3.20.3 / 2015-05-17 -=================== - - * deps: connect@2.29.2 - - deps: body-parser@~1.12.4 - - deps: compression@~1.4.4 - - deps: connect-timeout@~1.6.2 - - deps: debug@~2.2.0 - - deps: depd@~1.0.1 - - deps: errorhandler@~1.3.6 - - deps: finalhandler@0.3.6 - - deps: method-override@~2.3.3 - - deps: morgan@~1.5.3 - - deps: qs@2.4.2 - - deps: response-time@~2.3.1 - - deps: serve-favicon@~2.2.1 - - deps: serve-index@~1.6.4 - - deps: serve-static@~1.9.3 - - deps: type-is@~1.6.2 - * deps: debug@~2.2.0 - - deps: ms@0.7.1 - * deps: depd@~1.0.1 - * deps: proxy-addr@~1.0.8 - - deps: ipaddr.js@1.0.1 - * deps: send@0.12.3 - - deps: debug@~2.2.0 - - deps: depd@~1.0.1 - - deps: etag@~1.6.0 - - deps: ms@0.7.1 - - deps: on-finished@~2.2.1 - -3.20.2 / 2015-03-16 -=================== - - * deps: connect@2.29.1 - - deps: body-parser@~1.12.2 - - deps: compression@~1.4.3 - - deps: connect-timeout@~1.6.1 - - deps: debug@~2.1.3 - - deps: errorhandler@~1.3.5 - - deps: express-session@~1.10.4 - - deps: finalhandler@0.3.4 - - deps: method-override@~2.3.2 - - deps: morgan@~1.5.2 - - deps: qs@2.4.1 - - deps: serve-index@~1.6.3 - - deps: serve-static@~1.9.2 - - deps: type-is@~1.6.1 - * deps: debug@~2.1.3 - - Fix high intensity foreground color for bold - - deps: ms@0.7.0 - * deps: merge-descriptors@1.0.0 - * deps: proxy-addr@~1.0.7 - - deps: ipaddr.js@0.1.9 - * deps: send@0.12.2 - - Throw errors early for invalid `extensions` or `index` options - - deps: debug@~2.1.3 - -3.20.1 / 2015-02-28 -=================== - - * Fix `req.host` when using "trust proxy" hops count - * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count - -3.20.0 / 2015-02-18 -=================== - - * Fix `"trust proxy"` setting to inherit when app is mounted - * Generate `ETag`s for all request responses - - No longer restricted to only responses for `GET` and `HEAD` requests - * Use `content-type` to parse `Content-Type` headers - * deps: connect@2.29.0 - - Use `content-type` to parse `Content-Type` headers - - deps: body-parser@~1.12.0 - - deps: compression@~1.4.1 - - deps: connect-timeout@~1.6.0 - - deps: cookie-parser@~1.3.4 - - deps: cookie-signature@1.0.6 - - deps: csurf@~1.7.0 - - deps: errorhandler@~1.3.4 - - deps: express-session@~1.10.3 - - deps: http-errors@~1.3.1 - - deps: response-time@~2.3.0 - - deps: serve-index@~1.6.2 - - deps: serve-static@~1.9.1 - - deps: type-is@~1.6.0 - * deps: cookie-signature@1.0.6 - * deps: send@0.12.1 - - Always read the stat size from the file - - Fix mutating passed-in `options` - - deps: mime@1.3.4 - -3.19.2 / 2015-02-01 -=================== - - * deps: connect@2.28.3 - - deps: compression@~1.3.1 - - deps: csurf@~1.6.6 - - deps: errorhandler@~1.3.3 - - deps: express-session@~1.10.2 - - deps: serve-index@~1.6.1 - - deps: type-is@~1.5.6 - * deps: proxy-addr@~1.0.6 - - deps: ipaddr.js@0.1.8 - -3.19.1 / 2015-01-20 -=================== - - * deps: connect@2.28.2 - - deps: body-parser@~1.10.2 - - deps: serve-static@~1.8.1 - * deps: send@0.11.1 - - Fix root path disclosure - -3.19.0 / 2015-01-09 -=================== - - * Fix `OPTIONS` responses to include the `HEAD` method property - * Use `readline` for prompt in `express(1)` - * deps: commander@2.6.0 - * deps: connect@2.28.1 - - deps: body-parser@~1.10.1 - - deps: compression@~1.3.0 - - deps: connect-timeout@~1.5.0 - - deps: csurf@~1.6.4 - - deps: debug@~2.1.1 - - deps: errorhandler@~1.3.2 - - deps: express-session@~1.10.1 - - deps: finalhandler@0.3.3 - - deps: method-override@~2.3.1 - - deps: morgan@~1.5.1 - - deps: serve-favicon@~2.2.0 - - deps: serve-index@~1.6.0 - - deps: serve-static@~1.8.0 - - deps: type-is@~1.5.5 - * deps: debug@~2.1.1 - * deps: methods@~1.1.1 - * deps: proxy-addr@~1.0.5 - - deps: ipaddr.js@0.1.6 - * deps: send@0.11.0 - - deps: debug@~2.1.1 - - deps: etag@~1.5.1 - - deps: ms@0.7.0 - - deps: on-finished@~2.2.0 - -3.18.6 / 2014-12-12 -=================== - - * Fix exception in `req.fresh`/`req.stale` without response headers - -3.18.5 / 2014-12-11 -=================== - - * deps: connect@2.27.6 - - deps: compression@~1.2.2 - - deps: express-session@~1.9.3 - - deps: http-errors@~1.2.8 - - deps: serve-index@~1.5.3 - - deps: type-is@~1.5.4 - -3.18.4 / 2014-11-23 -=================== - - * deps: connect@2.27.4 - - deps: body-parser@~1.9.3 - - deps: compression@~1.2.1 - - deps: errorhandler@~1.2.3 - - deps: express-session@~1.9.2 - - deps: qs@2.3.3 - - deps: serve-favicon@~2.1.7 - - deps: serve-static@~1.5.1 - - deps: type-is@~1.5.3 - * deps: etag@~1.5.1 - * deps: proxy-addr@~1.0.4 - - deps: ipaddr.js@0.1.5 - -3.18.3 / 2014-11-09 -=================== - - * deps: connect@2.27.3 - - Correctly invoke async callback asynchronously - - deps: csurf@~1.6.3 - -3.18.2 / 2014-10-28 -=================== - - * deps: connect@2.27.2 - - Fix handling of URLs containing `://` in the path - - deps: body-parser@~1.9.2 - - deps: qs@2.3.2 - -3.18.1 / 2014-10-22 -=================== - - * Fix internal `utils.merge` deprecation warnings - * deps: connect@2.27.1 - - deps: body-parser@~1.9.1 - - deps: express-session@~1.9.1 - - deps: finalhandler@0.3.2 - - deps: morgan@~1.4.1 - - deps: qs@2.3.0 - - deps: serve-static@~1.7.1 - * deps: send@0.10.1 - - deps: on-finished@~2.1.1 - -3.18.0 / 2014-10-17 -=================== - - * Use `content-disposition` module for `res.attachment`/`res.download` - - Sends standards-compliant `Content-Disposition` header - - Full Unicode support - * Use `etag` module to generate `ETag` headers - * deps: connect@2.27.0 - - Use `http-errors` module for creating errors - - Use `utils-merge` module for merging objects - - deps: body-parser@~1.9.0 - - deps: compression@~1.2.0 - - deps: connect-timeout@~1.4.0 - - deps: debug@~2.1.0 - - deps: depd@~1.0.0 - - deps: express-session@~1.9.0 - - deps: finalhandler@0.3.1 - - deps: method-override@~2.3.0 - - deps: morgan@~1.4.0 - - deps: response-time@~2.2.0 - - deps: serve-favicon@~2.1.6 - - deps: serve-index@~1.5.0 - - deps: serve-static@~1.7.0 - * deps: debug@~2.1.0 - - Implement `DEBUG_FD` env variable support - * deps: depd@~1.0.0 - * deps: send@0.10.0 - - deps: debug@~2.1.0 - - deps: depd@~1.0.0 - - deps: etag@~1.5.0 - -3.17.8 / 2014-10-15 -=================== - - * deps: connect@2.26.6 - - deps: compression@~1.1.2 - - deps: csurf@~1.6.2 - - deps: errorhandler@~1.2.2 - -3.17.7 / 2014-10-08 -=================== - - * deps: connect@2.26.5 - - Fix accepting non-object arguments to `logger` - - deps: serve-static@~1.6.4 - -3.17.6 / 2014-10-02 -=================== - - * deps: connect@2.26.4 - - deps: morgan@~1.3.2 - - deps: type-is@~1.5.2 - -3.17.5 / 2014-09-24 -=================== - - * deps: connect@2.26.3 - - deps: body-parser@~1.8.4 - - deps: serve-favicon@~2.1.5 - - deps: serve-static@~1.6.3 - * deps: proxy-addr@~1.0.3 - - Use `forwarded` npm module - * deps: send@0.9.3 - - deps: etag@~1.4.0 - -3.17.4 / 2014-09-19 -=================== - - * deps: connect@2.26.2 - - deps: body-parser@~1.8.3 - - deps: qs@2.2.4 - -3.17.3 / 2014-09-18 -=================== - - * deps: proxy-addr@~1.0.2 - - Fix a global leak when multiple subnets are trusted - - deps: ipaddr.js@0.1.3 - -3.17.2 / 2014-09-15 -=================== - - * Use `crc` instead of `buffer-crc32` for speed - * deps: connect@2.26.1 - - deps: body-parser@~1.8.2 - - deps: depd@0.4.5 - - deps: express-session@~1.8.2 - - deps: morgan@~1.3.1 - - deps: serve-favicon@~2.1.3 - - deps: serve-static@~1.6.2 - * deps: depd@0.4.5 - * deps: send@0.9.2 - - deps: depd@0.4.5 - - deps: etag@~1.3.1 - - deps: range-parser@~1.0.2 - -3.17.1 / 2014-09-08 -=================== - - * Fix error in `req.subdomains` on empty host - -3.17.0 / 2014-09-08 -=================== - - * Support `X-Forwarded-Host` in `req.subdomains` - * Support IP address host in `req.subdomains` - * deps: connect@2.26.0 - - deps: body-parser@~1.8.1 - - deps: compression@~1.1.0 - - deps: connect-timeout@~1.3.0 - - deps: cookie-parser@~1.3.3 - - deps: cookie-signature@1.0.5 - - deps: csurf@~1.6.1 - - deps: debug@~2.0.0 - - deps: errorhandler@~1.2.0 - - deps: express-session@~1.8.1 - - deps: finalhandler@0.2.0 - - deps: fresh@0.2.4 - - deps: media-typer@0.3.0 - - deps: method-override@~2.2.0 - - deps: morgan@~1.3.0 - - deps: qs@2.2.3 - - deps: serve-favicon@~2.1.3 - - deps: serve-index@~1.2.1 - - deps: serve-static@~1.6.1 - - deps: type-is@~1.5.1 - - deps: vhost@~3.0.0 - * deps: cookie-signature@1.0.5 - * deps: debug@~2.0.0 - * deps: fresh@0.2.4 - * deps: media-typer@0.3.0 - - Throw error when parameter format invalid on parse - * deps: range-parser@~1.0.2 - * deps: send@0.9.1 - - Add `lastModified` option - - Use `etag` to generate `ETag` header - - deps: debug@~2.0.0 - - deps: fresh@0.2.4 - * deps: vary@~1.0.0 - - Accept valid `Vary` header string as `field` - -3.16.10 / 2014-09-04 -==================== - - * deps: connect@2.25.10 - - deps: serve-static@~1.5.4 - * deps: send@0.8.5 - - Fix a path traversal issue when using `root` - - Fix malicious path detection for empty string path - -3.16.9 / 2014-08-29 -=================== - - * deps: connect@2.25.9 - - deps: body-parser@~1.6.7 - - deps: qs@2.2.2 - -3.16.8 / 2014-08-27 -=================== - - * deps: connect@2.25.8 - - deps: body-parser@~1.6.6 - - deps: csurf@~1.4.1 - - deps: qs@2.2.0 - -3.16.7 / 2014-08-18 -=================== - - * deps: connect@2.25.7 - - deps: body-parser@~1.6.5 - - deps: express-session@~1.7.6 - - deps: morgan@~1.2.3 - - deps: serve-static@~1.5.3 - * deps: send@0.8.3 - - deps: destroy@1.0.3 - - deps: on-finished@2.1.0 - -3.16.6 / 2014-08-14 -=================== - - * deps: connect@2.25.6 - - deps: body-parser@~1.6.4 - - deps: qs@1.2.2 - - deps: serve-static@~1.5.2 - * deps: send@0.8.2 - - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` - -3.16.5 / 2014-08-11 -=================== - - * deps: connect@2.25.5 - - Fix backwards compatibility in `logger` - -3.16.4 / 2014-08-10 -=================== - - * Fix original URL parsing in `res.location` - * deps: connect@2.25.4 - - Fix `query` middleware breaking with argument - - deps: body-parser@~1.6.3 - - deps: compression@~1.0.11 - - deps: connect-timeout@~1.2.2 - - deps: express-session@~1.7.5 - - deps: method-override@~2.1.3 - - deps: on-headers@~1.0.0 - - deps: parseurl@~1.3.0 - - deps: qs@1.2.1 - - deps: response-time@~2.0.1 - - deps: serve-index@~1.1.6 - - deps: serve-static@~1.5.1 - * deps: parseurl@~1.3.0 - -3.16.3 / 2014-08-07 -=================== - - * deps: connect@2.25.3 - - deps: multiparty@3.3.2 - -3.16.2 / 2014-08-07 -=================== - - * deps: connect@2.25.2 - - deps: body-parser@~1.6.2 - - deps: qs@1.2.0 - -3.16.1 / 2014-08-06 -=================== - - * deps: connect@2.25.1 - - deps: body-parser@~1.6.1 - - deps: qs@1.1.0 - -3.16.0 / 2014-08-05 -=================== - - * deps: connect@2.25.0 - - deps: body-parser@~1.6.0 - - deps: compression@~1.0.10 - - deps: csurf@~1.4.0 - - deps: express-session@~1.7.4 - - deps: qs@1.0.2 - - deps: serve-static@~1.5.0 - * deps: send@0.8.1 - - Add `extensions` option - -3.15.3 / 2014-08-04 -=================== - - * fix `res.sendfile` regression for serving directory index files - * deps: connect@2.24.3 - - deps: serve-index@~1.1.5 - - deps: serve-static@~1.4.4 - * deps: send@0.7.4 - - Fix incorrect 403 on Windows and Node.js 0.11 - - Fix serving index files without root dir - -3.15.2 / 2014-07-27 -=================== - - * deps: connect@2.24.2 - - deps: body-parser@~1.5.2 - - deps: depd@0.4.4 - - deps: express-session@~1.7.2 - - deps: morgan@~1.2.2 - - deps: serve-static@~1.4.2 - * deps: depd@0.4.4 - - Work-around v8 generating empty stack traces - * deps: send@0.7.2 - - deps: depd@0.4.4 - -3.15.1 / 2014-07-26 -=================== - - * deps: connect@2.24.1 - - deps: body-parser@~1.5.1 - - deps: depd@0.4.3 - - deps: express-session@~1.7.1 - - deps: morgan@~1.2.1 - - deps: serve-index@~1.1.4 - - deps: serve-static@~1.4.1 - * deps: depd@0.4.3 - - Fix exception when global `Error.stackTraceLimit` is too low - * deps: send@0.7.1 - - deps: depd@0.4.3 - -3.15.0 / 2014-07-22 -=================== - - * Fix `req.protocol` for proxy-direct connections - * Pass options from `res.sendfile` to `send` - * deps: connect@2.24.0 - - deps: body-parser@~1.5.0 - - deps: compression@~1.0.9 - - deps: connect-timeout@~1.2.1 - - deps: debug@1.0.4 - - deps: depd@0.4.2 - - deps: express-session@~1.7.0 - - deps: finalhandler@0.1.0 - - deps: method-override@~2.1.2 - - deps: morgan@~1.2.0 - - deps: multiparty@3.3.1 - - deps: parseurl@~1.2.0 - - deps: serve-static@~1.4.0 - * deps: debug@1.0.4 - * deps: depd@0.4.2 - - Add `TRACE_DEPRECATION` environment variable - - Remove non-standard grey color from color output - - Support `--no-deprecation` argument - - Support `--trace-deprecation` argument - * deps: parseurl@~1.2.0 - - Cache URLs based on original value - - Remove no-longer-needed URL mis-parse work-around - - Simplify the "fast-path" `RegExp` - * deps: send@0.7.0 - - Add `dotfiles` option - - Cap `maxAge` value to 1 year - - deps: debug@1.0.4 - - deps: depd@0.4.2 - -3.14.0 / 2014-07-11 -=================== - - * add explicit "Rosetta Flash JSONP abuse" protection - - previous versions are not vulnerable; this is just explicit protection - * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead - * fix `res.send(status, num)` to send `num` as json (not error) - * remove unnecessary escaping when `res.jsonp` returns JSON response - * deps: basic-auth@1.0.0 - - support empty password - - support empty username - * deps: connect@2.23.0 - - deps: debug@1.0.3 - - deps: express-session@~1.6.4 - - deps: method-override@~2.1.0 - - deps: parseurl@~1.1.3 - - deps: serve-static@~1.3.1 - * deps: debug@1.0.3 - - Add support for multiple wildcards in namespaces - * deps: methods@1.1.0 - - add `CONNECT` - * deps: parseurl@~1.1.3 - - faster parsing of href-only URLs - -3.13.0 / 2014-07-03 -=================== - - * add deprecation message to `app.configure` - * add deprecation message to `req.auth` - * use `basic-auth` to parse `Authorization` header - * deps: connect@2.22.0 - - deps: csurf@~1.3.0 - - deps: express-session@~1.6.1 - - deps: multiparty@3.3.0 - - deps: serve-static@~1.3.0 - * deps: send@0.5.0 - - Accept string for `maxage` (converted by `ms`) - - Include link in default redirect response - -3.12.1 / 2014-06-26 -=================== - - * deps: connect@2.21.1 - - deps: cookie-parser@1.3.2 - - deps: cookie-signature@1.0.4 - - deps: express-session@~1.5.2 - - deps: type-is@~1.3.2 - * deps: cookie-signature@1.0.4 - - fix for timing attacks - -3.12.0 / 2014-06-21 -=================== - - * use `media-typer` to alter content-type charset - * deps: connect@2.21.0 - - deprecate `connect(middleware)` -- use `app.use(middleware)` instead - - deprecate `connect.createServer()` -- use `connect()` instead - - fix `res.setHeader()` patch to work with with get -> append -> set pattern - - deps: compression@~1.0.8 - - deps: errorhandler@~1.1.1 - - deps: express-session@~1.5.0 - - deps: serve-index@~1.1.3 - -3.11.0 / 2014-06-19 -=================== - - * deprecate things with `depd` module - * deps: buffer-crc32@0.2.3 - * deps: connect@2.20.2 - - deprecate `verify` option to `json` -- use `body-parser` npm module instead - - deprecate `verify` option to `urlencoded` -- use `body-parser` npm module instead - - deprecate things with `depd` module - - use `finalhandler` for final response handling - - use `media-typer` to parse `content-type` for charset - - deps: body-parser@1.4.3 - - deps: connect-timeout@1.1.1 - - deps: cookie-parser@1.3.1 - - deps: csurf@1.2.2 - - deps: errorhandler@1.1.0 - - deps: express-session@1.4.0 - - deps: multiparty@3.2.9 - - deps: serve-index@1.1.2 - - deps: type-is@1.3.1 - - deps: vhost@2.0.0 - -3.10.5 / 2014-06-11 -=================== - - * deps: connect@2.19.6 - - deps: body-parser@1.3.1 - - deps: compression@1.0.7 - - deps: debug@1.0.2 - - deps: serve-index@1.1.1 - - deps: serve-static@1.2.3 - * deps: debug@1.0.2 - * deps: send@0.4.3 - - Do not throw uncatchable error on file open race condition - - Use `escape-html` for HTML escaping - - deps: debug@1.0.2 - - deps: finished@1.2.2 - - deps: fresh@0.2.2 - -3.10.4 / 2014-06-09 -=================== - - * deps: connect@2.19.5 - - fix "event emitter leak" warnings - - deps: csurf@1.2.1 - - deps: debug@1.0.1 - - deps: serve-static@1.2.2 - - deps: type-is@1.2.1 - * deps: debug@1.0.1 - * deps: send@0.4.2 - - fix "event emitter leak" warnings - - deps: finished@1.2.1 - - deps: debug@1.0.1 - -3.10.3 / 2014-06-05 -=================== - - * use `vary` module for `res.vary` - * deps: connect@2.19.4 - - deps: errorhandler@1.0.2 - - deps: method-override@2.0.2 - - deps: serve-favicon@2.0.1 - * deps: debug@1.0.0 - -3.10.2 / 2014-06-03 -=================== - - * deps: connect@2.19.3 - - deps: compression@1.0.6 - -3.10.1 / 2014-06-03 -=================== - - * deps: connect@2.19.2 - - deps: compression@1.0.4 - * deps: proxy-addr@1.0.1 - -3.10.0 / 2014-06-02 -=================== - - * deps: connect@2.19.1 - - deprecate `methodOverride()` -- use `method-override` npm module instead - - deps: body-parser@1.3.0 - - deps: method-override@2.0.1 - - deps: multiparty@3.2.8 - - deps: response-time@2.0.0 - - deps: serve-static@1.2.1 - * deps: methods@1.0.1 - * deps: send@0.4.1 - - Send `max-age` in `Cache-Control` in correct format - -3.9.0 / 2014-05-30 -================== - - * custom etag control with `app.set('etag', val)` - - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation - - `app.set('etag', 'weak')` weak tag - - `app.set('etag', 'strong')` strong etag - - `app.set('etag', false)` turn off - - `app.set('etag', true)` standard etag - * Include ETag in HEAD requests - * mark `res.send` ETag as weak and reduce collisions - * update connect to 2.18.0 - - deps: compression@1.0.3 - - deps: serve-index@1.1.0 - - deps: serve-static@1.2.0 - * update send to 0.4.0 - - Calculate ETag with md5 for reduced collisions - - Ignore stream errors after request ends - - deps: debug@0.8.1 - -3.8.1 / 2014-05-27 -================== - - * update connect to 2.17.3 - - deps: body-parser@1.2.2 - - deps: express-session@1.2.1 - - deps: method-override@1.0.2 - -3.8.0 / 2014-05-21 -================== - - * keep previous `Content-Type` for `res.jsonp` - * set proper `charset` in `Content-Type` for `res.send` - * update connect to 2.17.1 - - fix `res.charset` appending charset when `content-type` has one - - deps: express-session@1.2.0 - - deps: morgan@1.1.1 - - deps: serve-index@1.0.3 - -3.7.0 / 2014-05-18 -================== - - * proper proxy trust with `app.set('trust proxy', trust)` - - `app.set('trust proxy', 1)` trust first hop - - `app.set('trust proxy', 'loopback')` trust loopback addresses - - `app.set('trust proxy', '10.0.0.1')` trust single IP - - `app.set('trust proxy', '10.0.0.1/16')` trust subnet - - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list - - `app.set('trust proxy', false)` turn off - - `app.set('trust proxy', true)` trust everything - * update connect to 2.16.2 - - deprecate `res.headerSent` -- use `res.headersSent` - - deprecate `res.on("header")` -- use on-headers module instead - - fix edge-case in `res.appendHeader` that would append in wrong order - - json: use body-parser - - urlencoded: use body-parser - - dep: bytes@1.0.0 - - dep: cookie-parser@1.1.0 - - dep: csurf@1.2.0 - - dep: express-session@1.1.0 - - dep: method-override@1.0.1 - -3.6.0 / 2014-05-09 -================== - - * deprecate `app.del()` -- use `app.delete()` instead - * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead - - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` - * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead - - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` - * support PURGE method - - add `app.purge` - - add `router.purge` - - include PURGE in `app.all` - * update connect to 2.15.0 - * Add `res.appendHeader` - * Call error stack even when response has been sent - * Patch `res.headerSent` to return Boolean - * Patch `res.headersSent` for node.js 0.8 - * Prevent default 404 handler after response sent - * dep: compression@1.0.2 - * dep: connect-timeout@1.1.0 - * dep: debug@^0.8.0 - * dep: errorhandler@1.0.1 - * dep: express-session@1.0.4 - * dep: morgan@1.0.1 - * dep: serve-favicon@2.0.0 - * dep: serve-index@1.0.2 - * update debug to 0.8.0 - * add `enable()` method - * change from stderr to stdout - * update methods to 1.0.0 - - add PURGE - * update mkdirp to 0.5.0 - -3.5.3 / 2014-05-08 -================== - - * fix `req.host` for IPv6 literals - * fix `res.jsonp` error if callback param is object - -3.5.2 / 2014-04-24 -================== - - * update connect to 2.14.5 - * update cookie to 0.1.2 - * update mkdirp to 0.4.0 - * update send to 0.3.0 - -3.5.1 / 2014-03-25 -================== - - * pin less-middleware in generated app - -3.5.0 / 2014-03-06 -================== - - * bump deps - -3.4.8 / 2014-01-13 -================== - - * prevent incorrect automatic OPTIONS responses #1868 @dpatti - * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi - * throw 400 in case of malformed paths @rlidwka - -3.4.7 / 2013-12-10 -================== - - * update connect - -3.4.6 / 2013-12-01 -================== - - * update connect (raw-body) - -3.4.5 / 2013-11-27 -================== - - * update connect - * res.location: remove leading ./ #1802 @kapouer - * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra - * res.send: always send ETag when content-length > 0 - * router: add Router.all() method - -3.4.4 / 2013-10-29 -================== - - * update connect - * update supertest - * update methods - * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 - -3.4.3 / 2013-10-23 -================== - - * update connect - -3.4.2 / 2013-10-18 -================== - - * update connect - * downgrade commander - -3.4.1 / 2013-10-15 -================== - - * update connect - * update commander - * jsonp: check if callback is a function - * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) - * res.format: now includes charset @1747 (@sorribas) - * res.links: allow multiple calls @1746 (@sorribas) - -3.4.0 / 2013-09-07 -================== - - * add res.vary(). Closes #1682 - * update connect - -3.3.8 / 2013-09-02 -================== - - * update connect - -3.3.7 / 2013-08-28 -================== - - * update connect - -3.3.6 / 2013-08-27 -================== - - * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) - * add: req.accepts take an argument list - -3.3.4 / 2013-07-08 -================== - - * update send and connect - -3.3.3 / 2013-07-04 -================== - - * update connect - -3.3.2 / 2013-07-03 -================== - - * update connect - * update send - * remove .version export - -3.3.1 / 2013-06-27 -================== - - * update connect - -3.3.0 / 2013-06-26 -================== - - * update connect - * add support for multiple X-Forwarded-Proto values. Closes #1646 - * change: remove charset from json responses. Closes #1631 - * change: return actual booleans from req.accept* functions - * fix jsonp callback array throw - -3.2.6 / 2013-06-02 -================== - - * update connect - -3.2.5 / 2013-05-21 -================== - - * update connect - * update node-cookie - * add: throw a meaningful error when there is no default engine - * change generation of ETags with res.send() to GET requests only. Closes #1619 - -3.2.4 / 2013-05-09 -================== - - * fix `req.subdomains` when no Host is present - * fix `req.host` when no Host is present, return undefined - -3.2.3 / 2013-05-07 -================== - - * update connect / qs - -3.2.2 / 2013-05-03 -================== - - * update qs - -3.2.1 / 2013-04-29 -================== - - * add app.VERB() paths array deprecation warning - * update connect - * update qs and remove all ~ semver crap - * fix: accept number as value of Signed Cookie - -3.2.0 / 2013-04-15 -================== - - * add "view" constructor setting to override view behaviour - * add req.acceptsEncoding(name) - * add req.acceptedEncodings - * revert cookie signature change causing session race conditions - * fix sorting of Accept values of the same quality - -3.1.2 / 2013-04-12 -================== - - * add support for custom Accept parameters - * update cookie-signature - -3.1.1 / 2013-04-01 -================== - - * add X-Forwarded-Host support to `req.host` - * fix relative redirects - * update mkdirp - * update buffer-crc32 - * remove legacy app.configure() method from app template. - -3.1.0 / 2013-01-25 -================== - - * add support for leading "." in "view engine" setting - * add array support to `res.set()` - * add node 0.8.x to travis.yml - * add "subdomain offset" setting for tweaking `req.subdomains` - * add `res.location(url)` implementing `res.redirect()`-like setting of Location - * use app.get() for x-powered-by setting for inheritance - * fix colons in passwords for `req.auth` - -3.0.6 / 2013-01-04 -================== - - * add http verb methods to Router - * update connect - * fix mangling of the `res.cookie()` options object - * fix jsonp whitespace escape. Closes #1132 - -3.0.5 / 2012-12-19 -================== - - * add throwing when a non-function is passed to a route - * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses - * revert "add 'etag' option" - -3.0.4 / 2012-12-05 -================== - - * add 'etag' option to disable `res.send()` Etags - * add escaping of urls in text/plain in `res.redirect()` - for old browsers interpreting as html - * change crc32 module for a more liberal license - * update connect - -3.0.3 / 2012-11-13 -================== - - * update connect - * update cookie module - * fix cookie max-age - -3.0.2 / 2012-11-08 -================== - - * add OPTIONS to cors example. Closes #1398 - * fix route chaining regression. Closes #1397 - -3.0.1 / 2012-11-01 -================== - - * update connect - -3.0.0 / 2012-10-23 -================== - - * add `make clean` - * add "Basic" check to req.auth - * add `req.auth` test coverage - * add cb && cb(payload) to `res.jsonp()`. Closes #1374 - * add backwards compat for `res.redirect()` status. Closes #1336 - * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 - * update connect - * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 - * remove non-primitive string support for `res.send()` - * fix view-locals example. Closes #1370 - * fix route-separation example - -3.0.0rc5 / 2012-09-18 -================== - - * update connect - * add redis search example - * add static-files example - * add "x-powered-by" setting (`app.disable('x-powered-by')`) - * add "application/octet-stream" redirect Accept test case. Closes #1317 - -3.0.0rc4 / 2012-08-30 -================== - - * add `res.jsonp()`. Closes #1307 - * add "verbose errors" option to error-pages example - * add another route example to express(1) so people are not so confused - * add redis online user activity tracking example - * update connect dep - * fix etag quoting. Closes #1310 - * fix error-pages 404 status - * fix jsonp callback char restrictions - * remove old OPTIONS default response - -3.0.0rc3 / 2012-08-13 -================== - - * update connect dep - * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] - * fix `res.render()` clobbering of "locals" - -3.0.0rc2 / 2012-08-03 -================== - - * add CORS example - * update connect dep - * deprecate `.createServer()` & remove old stale examples - * fix: escape `res.redirect()` link - * fix vhost example - -3.0.0rc1 / 2012-07-24 -================== - - * add more examples to view-locals - * add scheme-relative redirects (`res.redirect("//foo.com")`) support - * update cookie dep - * update connect dep - * update send dep - * fix `express(1)` -h flag, use -H for hogan. Closes #1245 - * fix `res.sendfile()` socket error handling regression - -3.0.0beta7 / 2012-07-16 -================== - - * update connect dep for `send()` root normalization regression - -3.0.0beta6 / 2012-07-13 -================== - - * add `err.view` property for view errors. Closes #1226 - * add "jsonp callback name" setting - * add support for "/foo/:bar*" non-greedy matches - * change `res.sendfile()` to use `send()` module - * change `res.send` to use "response-send" module - * remove `app.locals.use` and `res.locals.use`, use regular middleware - -3.0.0beta5 / 2012-07-03 -================== - - * add "make check" support - * add route-map example - * add `res.json(obj, status)` support back for BC - * add "methods" dep, remove internal methods module - * update connect dep - * update auth example to utilize cores pbkdf2 - * updated tests to use "supertest" - -3.0.0beta4 / 2012-06-25 -================== - - * Added `req.auth` - * Added `req.range(size)` - * Added `res.links(obj)` - * Added `res.send(body, status)` support back for backwards compat - * Added `.default()` support to `res.format()` - * Added 2xx / 304 check to `req.fresh` - * Revert "Added + support to the router" - * Fixed `res.send()` freshness check, respect res.statusCode - -3.0.0beta3 / 2012-06-15 -================== - - * Added hogan `--hjs` to express(1) [nullfirm] - * Added another example to content-negotiation - * Added `fresh` dep - * Changed: `res.send()` always checks freshness - * Fixed: expose connects mime module. Closes #1165 - -3.0.0beta2 / 2012-06-06 -================== - - * Added `+` support to the router - * Added `req.host` - * Changed `req.param()` to check route first - * Update connect dep - -3.0.0beta1 / 2012-06-01 -================== - - * Added `res.format()` callback to override default 406 behaviour - * Fixed `res.redirect()` 406. Closes #1154 - -3.0.0alpha5 / 2012-05-30 -================== - - * Added `req.ip` - * Added `{ signed: true }` option to `res.cookie()` - * Removed `res.signedCookie()` - * Changed: dont reverse `req.ips` - * Fixed "trust proxy" setting check for `req.ips` - -3.0.0alpha4 / 2012-05-09 -================== - - * Added: allow `[]` in jsonp callback. Closes #1128 - * Added `PORT` env var support in generated template. Closes #1118 [benatkin] - * Updated: connect 2.2.2 - -3.0.0alpha3 / 2012-05-04 -================== - - * Added public `app.routes`. Closes #887 - * Added _view-locals_ example - * Added _mvc_ example - * Added `res.locals.use()`. Closes #1120 - * Added conditional-GET support to `res.send()` - * Added: coerce `res.set()` values to strings - * Changed: moved `static()` in generated apps below router - * Changed: `res.send()` only set ETag when not previously set - * Changed connect 2.2.1 dep - * Changed: `make test` now runs unit / acceptance tests - * Fixed req/res proto inheritance - -3.0.0alpha2 / 2012-04-26 -================== - - * Added `make benchmark` back - * Added `res.send()` support for `String` objects - * Added client-side data exposing example - * Added `res.header()` and `req.header()` aliases for BC - * Added `express.createServer()` for BC - * Perf: memoize parsed urls - * Perf: connect 2.2.0 dep - * Changed: make `expressInit()` middleware self-aware - * Fixed: use app.get() for all core settings - * Fixed redis session example - * Fixed session example. Closes #1105 - * Fixed generated express dep. Closes #1078 - -3.0.0alpha1 / 2012-04-15 -================== - - * Added `app.locals.use(callback)` - * Added `app.locals` object - * Added `app.locals(obj)` - * Added `res.locals` object - * Added `res.locals(obj)` - * Added `res.format()` for content-negotiation - * Added `app.engine()` - * Added `res.cookie()` JSON cookie support - * Added "trust proxy" setting - * Added `req.subdomains` - * Added `req.protocol` - * Added `req.secure` - * Added `req.path` - * Added `req.ips` - * Added `req.fresh` - * Added `req.stale` - * Added comma-delimited / array support for `req.accepts()` - * Added debug instrumentation - * Added `res.set(obj)` - * Added `res.set(field, value)` - * Added `res.get(field)` - * Added `app.get(setting)`. Closes #842 - * Added `req.acceptsLanguage()` - * Added `req.acceptsCharset()` - * Added `req.accepted` - * Added `req.acceptedLanguages` - * Added `req.acceptedCharsets` - * Added "json replacer" setting - * Added "json spaces" setting - * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 - * Added `--less` support to express(1) - * Added `express.response` prototype - * Added `express.request` prototype - * Added `express.application` prototype - * Added `app.path()` - * Added `app.render()` - * Added `res.type()` to replace `res.contentType()` - * Changed: `res.redirect()` to add relative support - * Changed: enable "jsonp callback" by default - * Changed: renamed "case sensitive routes" to "case sensitive routing" - * Rewrite of all tests with mocha - * Removed "root" setting - * Removed `res.redirect('home')` support - * Removed `req.notify()` - * Removed `app.register()` - * Removed `app.redirect()` - * Removed `app.is()` - * Removed `app.helpers()` - * Removed `app.dynamicHelpers()` - * Fixed `res.sendfile()` with non-GET. Closes #723 - * Fixed express(1) public dir for windows. Closes #866 - -2.5.9/ 2012-04-02 -================== - - * Added support for PURGE request method [pbuyle] - * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] - -2.5.8 / 2012-02-08 -================== - - * Update mkdirp dep. Closes #991 - -2.5.7 / 2012-02-06 -================== - - * Fixed `app.all` duplicate DELETE requests [mscdex] - -2.5.6 / 2012-01-13 -================== - - * Updated hamljs dev dep. Closes #953 - -2.5.5 / 2012-01-08 -================== - - * Fixed: set `filename` on cached templates [matthewleon] - -2.5.4 / 2012-01-02 -================== - - * Fixed `express(1)` eol on 0.4.x. Closes #947 - -2.5.3 / 2011-12-30 -================== - - * Fixed `req.is()` when a charset is present - -2.5.2 / 2011-12-10 -================== - - * Fixed: express(1) LF -> CRLF for windows - -2.5.1 / 2011-11-17 -================== - - * Changed: updated connect to 1.8.x - * Removed sass.js support from express(1) - -2.5.0 / 2011-10-24 -================== - - * Added ./routes dir for generated app by default - * Added npm install reminder to express(1) app gen - * Added 0.5.x support - * Removed `make test-cov` since it wont work with node 0.5.x - * Fixed express(1) public dir for windows. Closes #866 - -2.4.7 / 2011-10-05 -================== - - * Added mkdirp to express(1). Closes #795 - * Added simple _json-config_ example - * Added shorthand for the parsed request's pathname via `req.path` - * Changed connect dep to 1.7.x to fix npm issue... - * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] - * Fixed `req.flash()`, only escape args - * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] - -2.4.6 / 2011-08-22 -================== - - * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] - -2.4.5 / 2011-08-19 -================== - - * Added support for routes to handle errors. Closes #809 - * Added `app.routes.all()`. Closes #803 - * Added "basepath" setting to work in conjunction with reverse proxies etc. - * Refactored `Route` to use a single array of callbacks - * Added support for multiple callbacks for `app.param()`. Closes #801 -Closes #805 - * Changed: removed .call(self) for route callbacks - * Dependency: `qs >= 0.3.1` - * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 - -2.4.4 / 2011-08-05 -================== - - * Fixed `res.header()` intention of a set, even when `undefined` - * Fixed `*`, value no longer required - * Fixed `res.send(204)` support. Closes #771 - -2.4.3 / 2011-07-14 -================== - - * Added docs for `status` option special-case. Closes #739 - * Fixed `options.filename`, exposing the view path to template engines - -2.4.2. / 2011-07-06 -================== - - * Revert "removed jsonp stripping" for XSS - -2.4.1 / 2011-07-06 -================== - - * Added `res.json()` JSONP support. Closes #737 - * Added _extending-templates_ example. Closes #730 - * Added "strict routing" setting for trailing slashes - * Added support for multiple envs in `app.configure()` calls. Closes #735 - * Changed: `res.send()` using `res.json()` - * Changed: when cookie `path === null` don't default it - * Changed; default cookie path to "home" setting. Closes #731 - * Removed _pids/logs_ creation from express(1) - -2.4.0 / 2011-06-28 -================== - - * Added chainable `res.status(code)` - * Added `res.json()`, an explicit version of `res.send(obj)` - * Added simple web-service example - -2.3.12 / 2011-06-22 -================== - - * \#express is now on freenode! come join! - * Added `req.get(field, param)` - * Added links to Japanese documentation, thanks @hideyukisaito! - * Added; the `express(1)` generated app outputs the env - * Added `content-negotiation` example - * Dependency: connect >= 1.5.1 < 2.0.0 - * Fixed view layout bug. Closes #720 - * Fixed; ignore body on 304. Closes #701 - -2.3.11 / 2011-06-04 -================== - - * Added `npm test` - * Removed generation of dummy test file from `express(1)` - * Fixed; `express(1)` adds express as a dep - * Fixed; prune on `prepublish` - -2.3.10 / 2011-05-27 -================== - - * Added `req.route`, exposing the current route - * Added _package.json_ generation support to `express(1)` - * Fixed call to `app.param()` function for optional params. Closes #682 - -2.3.9 / 2011-05-25 -================== - - * Fixed bug-ish with `../' in `res.partial()` calls - -2.3.8 / 2011-05-24 -================== - - * Fixed `app.options()` - -2.3.7 / 2011-05-23 -================== - - * Added route `Collection`, ex: `app.get('/user/:id').remove();` - * Added support for `app.param(fn)` to define param logic - * Removed `app.param()` support for callback with return value - * Removed module.parent check from express(1) generated app. Closes #670 - * Refactored router. Closes #639 - -2.3.6 / 2011-05-20 -================== - - * Changed; using devDependencies instead of git submodules - * Fixed redis session example - * Fixed markdown example - * Fixed view caching, should not be enabled in development - -2.3.5 / 2011-05-20 -================== - - * Added export `.view` as alias for `.View` - -2.3.4 / 2011-05-08 -================== - - * Added `./examples/say` - * Fixed `res.sendfile()` bug preventing the transfer of files with spaces - -2.3.3 / 2011-05-03 -================== - - * Added "case sensitive routes" option. - * Changed; split methods supported per rfc [slaskis] - * Fixed route-specific middleware when using the same callback function several times - -2.3.2 / 2011-04-27 -================== - - * Fixed view hints - -2.3.1 / 2011-04-26 -================== - - * Added `app.match()` as `app.match.all()` - * Added `app.lookup()` as `app.lookup.all()` - * Added `app.remove()` for `app.remove.all()` - * Added `app.remove.VERB()` - * Fixed template caching collision issue. Closes #644 - * Moved router over from connect and started refactor - -2.3.0 / 2011-04-25 -================== - - * Added options support to `res.clearCookie()` - * Added `res.helpers()` as alias of `res.locals()` - * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` - * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] - * Renamed "cache views" to "view cache". Closes #628 - * Fixed caching of views when using several apps. Closes #637 - * Fixed gotcha invoking `app.param()` callbacks once per route middleware. -Closes #638 - * Fixed partial lookup precedence. Closes #631 -Shaw] - -2.2.2 / 2011-04-12 -================== - - * Added second callback support for `res.download()` connection errors - * Fixed `filename` option passing to template engine - -2.2.1 / 2011-04-04 -================== - - * Added `layout(path)` helper to change the layout within a view. Closes #610 - * Fixed `partial()` collection object support. - Previously only anything with `.length` would work. - When `.length` is present one must still be aware of holes, - however now `{ collection: {foo: 'bar'}}` is valid, exposes - `keyInCollection` and `keysInCollection`. - - * Performance improved with better view caching - * Removed `request` and `response` locals - * Changed; errorHandler page title is now `Express` instead of `Connect` - -2.2.0 / 2011-03-30 -================== - - * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 - * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 - * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. - * Dependency `connect >= 1.2.0` - -2.1.1 / 2011-03-29 -================== - - * Added; expose `err.view` object when failing to locate a view - * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] - * Fixed; `res.send(undefined)` responds with 204 [aheckmann] - -2.1.0 / 2011-03-24 -================== - - * Added `/_?` partial lookup support. Closes #447 - * Added `request`, `response`, and `app` local variables - * Added `settings` local variable, containing the app's settings - * Added `req.flash()` exception if `req.session` is not available - * Added `res.send(bool)` support (json response) - * Fixed stylus example for latest version - * Fixed; wrap try/catch around `res.render()` - -2.0.0 / 2011-03-17 -================== - - * Fixed up index view path alternative. - * Changed; `res.locals()` without object returns the locals - -2.0.0rc3 / 2011-03-17 -================== - - * Added `res.locals(obj)` to compliment `res.local(key, val)` - * Added `res.partial()` callback support - * Fixed recursive error reporting issue in `res.render()` - -2.0.0rc2 / 2011-03-17 -================== - - * Changed; `partial()` "locals" are now optional - * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] - * Fixed .filename view engine option [reported by drudge] - * Fixed blog example - * Fixed `{req,res}.app` reference when mounting [Ben Weaver] - -2.0.0rc / 2011-03-14 -================== - - * Fixed; expose `HTTPSServer` constructor - * Fixed express(1) default test charset. Closes #579 [reported by secoif] - * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] - -2.0.0beta3 / 2011-03-09 -================== - - * Added support for `res.contentType()` literal - The original `res.contentType('.json')`, - `res.contentType('application/json')`, and `res.contentType('json')` - will work now. - * Added `res.render()` status option support back - * Added charset option for `res.render()` - * Added `.charset` support (via connect 1.0.4) - * Added view resolution hints when in development and a lookup fails - * Added layout lookup support relative to the page view. - For example while rendering `./views/user/index.jade` if you create - `./views/user/layout.jade` it will be used in favour of the root layout. - * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] - * Fixed; default `res.send()` string charset to utf8 - * Removed `Partial` constructor (not currently used) - -2.0.0beta2 / 2011-03-07 -================== - - * Added res.render() `.locals` support back to aid in migration process - * Fixed flash example - -2.0.0beta / 2011-03-03 -================== - - * Added HTTPS support - * Added `res.cookie()` maxAge support - * Added `req.header()` _Referrer_ / _Referer_ special-case, either works - * Added mount support for `res.redirect()`, now respects the mount-point - * Added `union()` util, taking place of `merge(clone())` combo - * Added stylus support to express(1) generated app - * Added secret to session middleware used in examples and generated app - * Added `res.local(name, val)` for progressive view locals - * Added default param support to `req.param(name, default)` - * Added `app.disabled()` and `app.enabled()` - * Added `app.register()` support for omitting leading ".", either works - * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 - * Added `app.param()` to map route params to async/sync logic - * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 - * Added extname with no leading "." support to `res.contentType()` - * Added `cache views` setting, defaulting to enabled in "production" env - * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. - * Added `req.accepts()` support for extensions - * Changed; `res.download()` and `res.sendfile()` now utilize Connect's - static file server `connect.static.send()`. - * Changed; replaced `connect.utils.mime()` with npm _mime_ module - * Changed; allow `req.query` to be pre-defined (via middleware or other parent - * Changed view partial resolution, now relative to parent view - * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. - * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 - * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` - * Fixed; using _qs_ module instead of _querystring_ - * Fixed; strip unsafe chars from jsonp callbacks - * Removed "stream threshold" setting - -1.0.8 / 2011-03-01 -================== - - * Allow `req.query` to be pre-defined (via middleware or other parent app) - * "connect": ">= 0.5.0 < 1.0.0". Closes #547 - * Removed the long deprecated __EXPRESS_ENV__ support - -1.0.7 / 2011-02-07 -================== - - * Fixed `render()` setting inheritance. - Mounted apps would not inherit "view engine" - -1.0.6 / 2011-02-07 -================== - - * Fixed `view engine` setting bug when period is in dirname - -1.0.5 / 2011-02-05 -================== - - * Added secret to generated app `session()` call - -1.0.4 / 2011-02-05 -================== - - * Added `qs` dependency to _package.json_ - * Fixed namespaced `require()`s for latest connect support - -1.0.3 / 2011-01-13 -================== - - * Remove unsafe characters from JSONP callback names [Ryan Grove] - -1.0.2 / 2011-01-10 -================== - - * Removed nested require, using `connect.router` - -1.0.1 / 2010-12-29 -================== - - * Fixed for middleware stacked via `createServer()` - previously the `foo` middleware passed to `createServer(foo)` - would not have access to Express methods such as `res.send()` - or props like `req.query` etc. - -1.0.0 / 2010-11-16 -================== - - * Added; deduce partial object names from the last segment. - For example by default `partial('forum/post', postObject)` will - give you the _post_ object, providing a meaningful default. - * Added http status code string representation to `res.redirect()` body - * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. - * Added `req.is()` to aid in content negotiation - * Added partial local inheritance [suggested by masylum]. Closes #102 - providing access to parent template locals. - * Added _-s, --session[s]_ flag to express(1) to add session related middleware - * Added _--template_ flag to express(1) to specify the - template engine to use. - * Added _--css_ flag to express(1) to specify the - stylesheet engine to use (or just plain css by default). - * Added `app.all()` support [thanks aheckmann] - * Added partial direct object support. - You may now `partial('user', user)` providing the "user" local, - vs previously `partial('user', { object: user })`. - * Added _route-separation_ example since many people question ways - to do this with CommonJS modules. Also view the _blog_ example for - an alternative. - * Performance; caching view path derived partial object names - * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 - * Fixed jsonp support; _text/javascript_ as per mailinglist discussion - -1.0.0rc4 / 2010-10-14 -================== - - * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 - * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) - * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] - * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] - * Added `partial()` support for array-like collections. Closes #434 - * Added support for swappable querystring parsers - * Added session usage docs. Closes #443 - * Added dynamic helper caching. Closes #439 [suggested by maritz] - * Added authentication example - * Added basic Range support to `res.sendfile()` (and `res.download()` etc) - * Changed; `express(1)` generated app using 2 spaces instead of 4 - * Default env to "development" again [aheckmann] - * Removed _context_ option is no more, use "scope" - * Fixed; exposing _./support_ libs to examples so they can run without installs - * Fixed mvc example - -1.0.0rc3 / 2010-09-20 -================== - - * Added confirmation for `express(1)` app generation. Closes #391 - * Added extending of flash formatters via `app.flashFormatters` - * Added flash formatter support. Closes #411 - * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" - * Added _stream threshold_ setting for `res.sendfile()` - * Added `res.send()` __HEAD__ support - * Added `res.clearCookie()` - * Added `res.cookie()` - * Added `res.render()` headers option - * Added `res.redirect()` response bodies - * Added `res.render()` status option support. Closes #425 [thanks aheckmann] - * Fixed `res.sendfile()` responding with 403 on malicious path - * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ - * Fixed; mounted apps settings now inherit from parent app [aheckmann] - * Fixed; stripping Content-Length / Content-Type when 204 - * Fixed `res.send()` 204. Closes #419 - * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 - * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] - - -1.0.0rc2 / 2010-08-17 -================== - - * Added `app.register()` for template engine mapping. Closes #390 - * Added `res.render()` callback support as second argument (no options) - * Added callback support to `res.download()` - * Added callback support for `res.sendfile()` - * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` - * Added "partials" setting to docs - * Added default expresso tests to `express(1)` generated app. Closes #384 - * Fixed `res.sendfile()` error handling, defer via `next()` - * Fixed `res.render()` callback when a layout is used [thanks guillermo] - * Fixed; `make install` creating ~/.node_libraries when not present - * Fixed issue preventing error handlers from being defined anywhere. Closes #387 - -1.0.0rc / 2010-07-28 -================== - - * Added mounted hook. Closes #369 - * Added connect dependency to _package.json_ - - * Removed "reload views" setting and support code - development env never caches, production always caches. - - * Removed _param_ in route callbacks, signature is now - simply (req, res, next), previously (req, res, params, next). - Use _req.params_ for path captures, _req.query_ for GET params. - - * Fixed "home" setting - * Fixed middleware/router precedence issue. Closes #366 - * Fixed; _configure()_ callbacks called immediately. Closes #368 - -1.0.0beta2 / 2010-07-23 -================== - - * Added more examples - * Added; exporting `Server` constructor - * Added `Server#helpers()` for view locals - * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 - * Added support for absolute view paths - * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 - * Added Guillermo Rauch to the contributor list - * Added support for "as" for non-collection partials. Closes #341 - * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] - * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] - * Fixed instanceof `Array` checks, now `Array.isArray()` - * Fixed express(1) expansion of public dirs. Closes #348 - * Fixed middleware precedence. Closes #345 - * Fixed view watcher, now async [thanks aheckmann] - -1.0.0beta / 2010-07-15 -================== - - * Re-write - - much faster - - much lighter - - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs - -0.14.0 / 2010-06-15 -================== - - * Utilize relative requires - * Added Static bufferSize option [aheckmann] - * Fixed caching of view and partial subdirectories [aheckmann] - * Fixed mime.type() comments now that ".ext" is not supported - * Updated haml submodule - * Updated class submodule - * Removed bin/express - -0.13.0 / 2010-06-01 -================== - - * Added node v0.1.97 compatibility - * Added support for deleting cookies via Request#cookie('key', null) - * Updated haml submodule - * Fixed not-found page, now using using charset utf-8 - * Fixed show-exceptions page, now using using charset utf-8 - * Fixed view support due to fs.readFile Buffers - * Changed; mime.type() no longer accepts ".type" due to node extname() changes - -0.12.0 / 2010-05-22 -================== - - * Added node v0.1.96 compatibility - * Added view `helpers` export which act as additional local variables - * Updated haml submodule - * Changed ETag; removed inode, modified time only - * Fixed LF to CRLF for setting multiple cookies - * Fixed cookie compilation; values are now urlencoded - * Fixed cookies parsing; accepts quoted values and url escaped cookies - -0.11.0 / 2010-05-06 -================== - - * Added support for layouts using different engines - - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) - - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' - - this.render('page.html.haml', { layout: false }) // no layout - * Updated ext submodule - * Updated haml submodule - * Fixed EJS partial support by passing along the context. Issue #307 - -0.10.1 / 2010-05-03 -================== - - * Fixed binary uploads. - -0.10.0 / 2010-04-30 -================== - - * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s - encoding is set to 'utf8' or 'utf-8'. - * Added "encoding" option to Request#render(). Closes #299 - * Added "dump exceptions" setting, which is enabled by default. - * Added simple ejs template engine support - * Added error response support for text/plain, application/json. Closes #297 - * Added callback function param to Request#error() - * Added Request#sendHead() - * Added Request#stream() - * Added support for Request#respond(304, null) for empty response bodies - * Added ETag support to Request#sendfile() - * Added options to Request#sendfile(), passed to fs.createReadStream() - * Added filename arg to Request#download() - * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request - * Performance enhanced by preventing several calls to toLowerCase() in Router#match() - * Changed; Request#sendfile() now streams - * Changed; Renamed Request#halt() to Request#respond(). Closes #289 - * Changed; Using sys.inspect() instead of JSON.encode() for error output - * Changed; run() returns the http.Server instance. Closes #298 - * Changed; Defaulting Server#host to null (INADDR_ANY) - * Changed; Logger "common" format scale of 0.4f - * Removed Logger "request" format - * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found - * Fixed several issues with http client - * Fixed Logger Content-Length output - * Fixed bug preventing Opera from retaining the generated session id. Closes #292 - -0.9.0 / 2010-04-14 -================== - - * Added DSL level error() route support - * Added DSL level notFound() route support - * Added Request#error() - * Added Request#notFound() - * Added Request#render() callback function. Closes #258 - * Added "max upload size" setting - * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 - * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js - * Added callback function support to Request#halt() as 3rd/4th arg - * Added preprocessing of route param wildcards using param(). Closes #251 - * Added view partial support (with collections etc) - * Fixed bug preventing falsey params (such as ?page=0). Closes #286 - * Fixed setting of multiple cookies. Closes #199 - * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) - * Changed; session cookie is now httpOnly - * Changed; Request is no longer global - * Changed; Event is no longer global - * Changed; "sys" module is no longer global - * Changed; moved Request#download to Static plugin where it belongs - * Changed; Request instance created before body parsing. Closes #262 - * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 - * Changed; Pre-caching view partials in memory when "cache view partials" is enabled - * Updated support to node --version 0.1.90 - * Updated dependencies - * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) - * Removed utils.mixin(); use Object#mergeDeep() - -0.8.0 / 2010-03-19 -================== - - * Added coffeescript example app. Closes #242 - * Changed; cache api now async friendly. Closes #240 - * Removed deprecated 'express/static' support. Use 'express/plugins/static' - -0.7.6 / 2010-03-19 -================== - - * Added Request#isXHR. Closes #229 - * Added `make install` (for the executable) - * Added `express` executable for setting up simple app templates - * Added "GET /public/*" to Static plugin, defaulting to /public - * Added Static plugin - * Fixed; Request#render() only calls cache.get() once - * Fixed; Namespacing View caches with "view:" - * Fixed; Namespacing Static caches with "static:" - * Fixed; Both example apps now use the Static plugin - * Fixed set("views"). Closes #239 - * Fixed missing space for combined log format - * Deprecated Request#sendfile() and 'express/static' - * Removed Server#running - -0.7.5 / 2010-03-16 -================== - - * Added Request#flash() support without args, now returns all flashes - * Updated ext submodule - -0.7.4 / 2010-03-16 -================== - - * Fixed session reaper - * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) - -0.7.3 / 2010-03-16 -================== - - * Added package.json - * Fixed requiring of haml / sass due to kiwi removal - -0.7.2 / 2010-03-16 -================== - - * Fixed GIT submodules (HAH!) - -0.7.1 / 2010-03-16 -================== - - * Changed; Express now using submodules again until a PM is adopted - * Changed; chat example using millisecond conversions from ext - -0.7.0 / 2010-03-15 -================== - - * Added Request#pass() support (finds the next matching route, or the given path) - * Added Logger plugin (default "common" format replaces CommonLogger) - * Removed Profiler plugin - * Removed CommonLogger plugin - -0.6.0 / 2010-03-11 -================== - - * Added seed.yml for kiwi package management support - * Added HTTP client query string support when method is GET. Closes #205 - - * Added support for arbitrary view engines. - For example "foo.engine.html" will now require('engine'), - the exports from this module are cached after the first require(). - - * Added async plugin support - - * Removed usage of RESTful route funcs as http client - get() etc, use http.get() and friends - - * Removed custom exceptions - -0.5.0 / 2010-03-10 -================== - - * Added ext dependency (library of js extensions) - * Removed extname() / basename() utils. Use path module - * Removed toArray() util. Use arguments.values - * Removed escapeRegexp() util. Use RegExp.escape() - * Removed process.mixin() dependency. Use utils.mixin() - * Removed Collection - * Removed ElementCollection - * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) - -0.4.0 / 2010-02-11 -================== - - * Added flash() example to sample upload app - * Added high level restful http client module (express/http) - * Changed; RESTful route functions double as HTTP clients. Closes #69 - * Changed; throwing error when routes are added at runtime - * Changed; defaulting render() context to the current Request. Closes #197 - * Updated haml submodule - -0.3.0 / 2010-02-11 -================== - - * Updated haml / sass submodules. Closes #200 - * Added flash message support. Closes #64 - * Added accepts() now allows multiple args. fixes #117 - * Added support for plugins to halt. Closes #189 - * Added alternate layout support. Closes #119 - * Removed Route#run(). Closes #188 - * Fixed broken specs due to use(Cookie) missing - -0.2.1 / 2010-02-05 -================== - - * Added "plot" format option for Profiler (for gnuplot processing) - * Added request number to Profiler plugin - * Fixed binary encoding for multipart file uploads, was previously defaulting to UTF8 - * Fixed issue with routes not firing when not files are present. Closes #184 - * Fixed process.Promise -> events.Promise - -0.2.0 / 2010-02-03 -================== - - * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 - * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 - * Added expiration support to cache api with reaper. Closes #133 - * Added cache Store.Memory#reap() - * Added Cache; cache api now uses first class Cache instances - * Added abstract session Store. Closes #172 - * Changed; cache Memory.Store#get() utilizing Collection - * Renamed MemoryStore -> Store.Memory - * Fixed use() of the same plugin several time will always use latest options. Closes #176 - -0.1.0 / 2010-02-03 -================== - - * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context - * Updated node support to 0.1.27 Closes #169 - * Updated dirname(__filename) -> __dirname - * Updated libxmljs support to v0.2.0 - * Added session support with memory store / reaping - * Added quick uid() helper - * Added multi-part upload support - * Added Sass.js support / submodule - * Added production env caching view contents and static files - * Added static file caching. Closes #136 - * Added cache plugin with memory stores - * Added support to StaticFile so that it works with non-textual files. - * Removed dirname() helper - * Removed several globals (now their modules must be required) - -0.0.2 / 2010-01-10 -================== - - * Added view benchmarks; currently haml vs ejs - * Added Request#attachment() specs. Closes #116 - * Added use of node's parseQuery() util. Closes #123 - * Added `make init` for submodules - * Updated Haml - * Updated sample chat app to show messages on load - * Updated libxmljs parseString -> parseHtmlString - * Fixed `make init` to work with older versions of git - * Fixed specs can now run independent specs for those who can't build deps. Closes #127 - * Fixed issues introduced by the node url module changes. Closes 126. - * Fixed two assertions failing due to Collection#keys() returning strings - * Fixed faulty Collection#toArray() spec due to keys() returning strings - * Fixed `make test` now builds libxmljs.node before testing - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/express/LICENSE b/node_modules/express/LICENSE deleted file mode 100644 index aa927e4..0000000 --- a/node_modules/express/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2009-2014 TJ Holowaychuk -Copyright (c) 2013-2014 Roman Shtylman -Copyright (c) 2014-2015 Douglas Christopher Wilson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/Readme.md b/node_modules/express/Readme.md deleted file mode 100644 index 1f91297..0000000 --- a/node_modules/express/Readme.md +++ /dev/null @@ -1,155 +0,0 @@ -[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/) - - Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). - - [![NPM Version][npm-image]][npm-url] - [![NPM Downloads][downloads-image]][downloads-url] - [![Linux Build][travis-image]][travis-url] - [![Windows Build][appveyor-image]][appveyor-url] - [![Test Coverage][coveralls-image]][coveralls-url] - -```js -const express = require('express') -const app = express() - -app.get('/', function (req, res) { - res.send('Hello World') -}) - -app.listen(3000) -``` - -## Installation - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). - -Before installing, [download and install Node.js](https://nodejs.org/en/download/). -Node.js 0.10 or higher is required. - -Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```bash -$ npm install express -``` - -Follow [our installing guide](http://expressjs.com/en/starter/installing.html) -for more information. - -## Features - - * Robust routing - * Focus on high performance - * Super-high test coverage - * HTTP helpers (redirection, caching, etc) - * View system supporting 14+ template engines - * Content negotiation - * Executable for generating applications quickly - -## Docs & Community - - * [Website and Documentation](http://expressjs.com/) - [[website repo](https://github.com/expressjs/expressjs.com)] - * [#express](https://webchat.freenode.net/?channels=express) on freenode IRC - * [GitHub Organization](https://github.com/expressjs) for Official Middleware & Modules - * Visit the [Wiki](https://github.com/expressjs/express/wiki) - * [Google Group](https://groups.google.com/group/express-js) for discussion - * [Gitter](https://gitter.im/expressjs/express) for support and discussion - -**PROTIP** Be sure to read [Migrating from 3.x to 4.x](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x) as well as [New features in 4.x](https://github.com/expressjs/express/wiki/New-features-in-4.x). - -### Security Issues - -If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md). - -## Quick Start - - The quickest way to get started with express is to utilize the executable [`express(1)`](https://github.com/expressjs/generator) to generate an application as shown below: - - Install the executable. The executable's major version will match Express's: - -```bash -$ npm install -g express-generator@4 -``` - - Create the app: - -```bash -$ express /tmp/foo && cd /tmp/foo -``` - - Install dependencies: - -```bash -$ npm install -``` - - Start the server: - -```bash -$ npm start -``` - - View the website at: http://localhost:3000 - -## Philosophy - - The Express philosophy is to provide small, robust tooling for HTTP servers, making - it a great solution for single page applications, web sites, hybrids, or public - HTTP APIs. - - Express does not force you to use any specific ORM or template engine. With support for over - 14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js), - you can quickly craft your perfect framework. - -## Examples - - To view the examples, clone the Express repo and install the dependencies: - -```bash -$ git clone git://github.com/expressjs/express.git --depth 1 -$ cd express -$ npm install -``` - - Then run whichever example you want: - -```bash -$ node examples/content-negotiation -``` - -## Tests - - To run the test suite, first install the dependencies, then run `npm test`: - -```bash -$ npm install -$ npm test -``` - -## Contributing - -[Contributing Guide](Contributing.md) - -## People - -The original author of Express is [TJ Holowaychuk](https://github.com/tj) - -The current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson) - -[List of all contributors](https://github.com/expressjs/express/graphs/contributors) - -## License - - [MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/express.svg -[npm-url]: https://npmjs.org/package/express -[downloads-image]: https://img.shields.io/npm/dm/express.svg -[downloads-url]: https://npmjs.org/package/express -[travis-image]: https://img.shields.io/travis/expressjs/express/master.svg?label=linux -[travis-url]: https://travis-ci.org/expressjs/express -[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/express/master.svg?label=windows -[appveyor-url]: https://ci.appveyor.com/project/dougwilson/express -[coveralls-image]: https://img.shields.io/coveralls/expressjs/express/master.svg -[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master diff --git a/node_modules/express/index.js b/node_modules/express/index.js deleted file mode 100644 index d219b0c..0000000 --- a/node_modules/express/index.js +++ /dev/null @@ -1,11 +0,0 @@ -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -module.exports = require('./lib/express'); diff --git a/node_modules/express/lib/application.js b/node_modules/express/lib/application.js deleted file mode 100644 index 91f77d2..0000000 --- a/node_modules/express/lib/application.js +++ /dev/null @@ -1,644 +0,0 @@ -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module dependencies. - * @private - */ - -var finalhandler = require('finalhandler'); -var Router = require('./router'); -var methods = require('methods'); -var middleware = require('./middleware/init'); -var query = require('./middleware/query'); -var debug = require('debug')('express:application'); -var View = require('./view'); -var http = require('http'); -var compileETag = require('./utils').compileETag; -var compileQueryParser = require('./utils').compileQueryParser; -var compileTrust = require('./utils').compileTrust; -var deprecate = require('depd')('express'); -var flatten = require('array-flatten'); -var merge = require('utils-merge'); -var resolve = require('path').resolve; -var setPrototypeOf = require('setprototypeof') -var slice = Array.prototype.slice; - -/** - * Application prototype. - */ - -var app = exports = module.exports = {}; - -/** - * Variable for trust proxy inheritance back-compat - * @private - */ - -var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; - -/** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - * - * @private - */ - -app.init = function init() { - this.cache = {}; - this.engines = {}; - this.settings = {}; - - this.defaultConfiguration(); -}; - -/** - * Initialize application configuration. - * @private - */ - -app.defaultConfiguration = function defaultConfiguration() { - var env = process.env.NODE_ENV || 'development'; - - // default settings - this.enable('x-powered-by'); - this.set('etag', 'weak'); - this.set('env', env); - this.set('query parser', 'extended'); - this.set('subdomain offset', 2); - this.set('trust proxy', false); - - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: true - }); - - debug('booting in %s mode', env); - - this.on('mount', function onmount(parent) { - // inherit trust proxy - if (this.settings[trustProxyDefaultSymbol] === true - && typeof parent.settings['trust proxy fn'] === 'function') { - delete this.settings['trust proxy']; - delete this.settings['trust proxy fn']; - } - - // inherit protos - setPrototypeOf(this.request, parent.request) - setPrototypeOf(this.response, parent.response) - setPrototypeOf(this.engines, parent.engines) - setPrototypeOf(this.settings, parent.settings) - }); - - // setup locals - this.locals = Object.create(null); - - // top-most app is mounted at / - this.mountpath = '/'; - - // default locals - this.locals.settings = this.settings; - - // default configuration - this.set('view', View); - this.set('views', resolve('views')); - this.set('jsonp callback name', 'callback'); - - if (env === 'production') { - this.enable('view cache'); - } - - Object.defineProperty(this, 'router', { - get: function() { - throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); - } - }); -}; - -/** - * lazily adds the base router if it has not yet been added. - * - * We cannot add the base router in the defaultConfiguration because - * it reads app settings which might be set after that has run. - * - * @private - */ -app.lazyrouter = function lazyrouter() { - if (!this._router) { - this._router = new Router({ - caseSensitive: this.enabled('case sensitive routing'), - strict: this.enabled('strict routing') - }); - - this._router.use(query(this.get('query parser fn'))); - this._router.use(middleware.init(this)); - } -}; - -/** - * Dispatch a req, res pair into the application. Starts pipeline processing. - * - * If no callback is provided, then default error handlers will respond - * in the event of an error bubbling through the stack. - * - * @private - */ - -app.handle = function handle(req, res, callback) { - var router = this._router; - - // final handler - var done = callback || finalhandler(req, res, { - env: this.get('env'), - onerror: logerror.bind(this) - }); - - // no routes - if (!router) { - debug('no routes defined on app'); - done(); - return; - } - - router.handle(req, res, done); -}; - -/** - * Proxy `Router#use()` to add middleware to the app router. - * See Router#use() documentation for details. - * - * If the _fn_ parameter is an express app, then it will be - * mounted at the _route_ specified. - * - * @public - */ - -app.use = function use(fn) { - var offset = 0; - var path = '/'; - - // default path to '/' - // disambiguate app.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; - - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } - - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } - } - - var fns = flatten(slice.call(arguments, offset)); - - if (fns.length === 0) { - throw new TypeError('app.use() requires a middleware function') - } - - // setup router - this.lazyrouter(); - var router = this._router; - - fns.forEach(function (fn) { - // non-express app - if (!fn || !fn.handle || !fn.set) { - return router.use(path, fn); - } - - debug('.use app under %s', path); - fn.mountpath = path; - fn.parent = this; - - // restore .app property on req and res - router.use(path, function mounted_app(req, res, next) { - var orig = req.app; - fn.handle(req, res, function (err) { - setPrototypeOf(req, orig.request) - setPrototypeOf(res, orig.response) - next(err); - }); - }); - - // mounted an app - fn.emit('mount', this); - }, this); - - return this; -}; - -/** - * Proxy to the app `Router#route()` - * Returns a new `Route` instance for the _path_. - * - * Routes are isolated middleware stacks for specific paths. - * See the Route api docs for details. - * - * @public - */ - -app.route = function route(path) { - this.lazyrouter(); - return this._router.route(path); -}; - -/** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.ejs" file Express will invoke the following internally: - * - * app.engine('ejs', require('ejs').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/tj/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - * - * @param {String} ext - * @param {Function} fn - * @return {app} for chaining - * @public - */ - -app.engine = function engine(ext, fn) { - if (typeof fn !== 'function') { - throw new Error('callback function required'); - } - - // get file extension - var extension = ext[0] !== '.' - ? '.' + ext - : ext; - - // store engine - this.engines[extension] = fn; - - return this; -}; - -/** - * Proxy to `Router#param()` with one added api feature. The _name_ parameter - * can be an array of names. - * - * See the Router#param() docs for more details. - * - * @param {String|Array} name - * @param {Function} fn - * @return {app} for chaining - * @public - */ - -app.param = function param(name, fn) { - this.lazyrouter(); - - if (Array.isArray(name)) { - for (var i = 0; i < name.length; i++) { - this.param(name[i], fn); - } - - return this; - } - - this._router.param(name, fn); - - return this; -}; - -/** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.set('foo'); - * // => "bar" - * - * Mounted servers inherit their parent server's settings. - * - * @param {String} setting - * @param {*} [val] - * @return {Server} for chaining - * @public - */ - -app.set = function set(setting, val) { - if (arguments.length === 1) { - // app.get(setting) - return this.settings[setting]; - } - - debug('set "%s" to %o', setting, val); - - // set value - this.settings[setting] = val; - - // trigger matched settings - switch (setting) { - case 'etag': - this.set('etag fn', compileETag(val)); - break; - case 'query parser': - this.set('query parser fn', compileQueryParser(val)); - break; - case 'trust proxy': - this.set('trust proxy fn', compileTrust(val)); - - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: false - }); - - break; - } - - return this; -}; - -/** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - * - * @return {String} - * @private - */ - -app.path = function path() { - return this.parent - ? this.parent.path() + this.mountpath - : ''; -}; - -/** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - * - * @param {String} setting - * @return {Boolean} - * @public - */ - -app.enabled = function enabled(setting) { - return Boolean(this.set(setting)); -}; - -/** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param {String} setting - * @return {Boolean} - * @public - */ - -app.disabled = function disabled(setting) { - return !this.set(setting); -}; - -/** - * Enable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public - */ - -app.enable = function enable(setting) { - return this.set(setting, true); -}; - -/** - * Disable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public - */ - -app.disable = function disable(setting) { - return this.set(setting, false); -}; - -/** - * Delegate `.VERB(...)` calls to `router.VERB(...)`. - */ - -methods.forEach(function(method){ - app[method] = function(path){ - if (method === 'get' && arguments.length === 1) { - // app.get(setting) - return this.set(path); - } - - this.lazyrouter(); - - var route = this._router.route(path); - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; -}); - -/** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param {String} path - * @param {Function} ... - * @return {app} for chaining - * @public - */ - -app.all = function all(path) { - this.lazyrouter(); - - var route = this._router.route(path); - var args = slice.call(arguments, 1); - - for (var i = 0; i < methods.length; i++) { - route[methods[i]].apply(route, args); - } - - return this; -}; - -// del -> delete alias - -app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); - -/** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param {String} name - * @param {Object|Function} options or fn - * @param {Function} callback - * @public - */ - -app.render = function render(name, options, callback) { - var cache = this.cache; - var done = callback; - var engines = this.engines; - var opts = options; - var renderOptions = {}; - var view; - - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } - - // merge app.locals - merge(renderOptions, this.locals); - - // merge options._locals - if (opts._locals) { - merge(renderOptions, opts._locals); - } - - // merge options - merge(renderOptions, opts); - - // set .cache unless explicitly provided - if (renderOptions.cache == null) { - renderOptions.cache = this.enabled('view cache'); - } - - // primed cache - if (renderOptions.cache) { - view = cache[name]; - } - - // view - if (!view) { - var View = this.get('view'); - - view = new View(name, { - defaultEngine: this.get('view engine'), - root: this.get('views'), - engines: engines - }); - - if (!view.path) { - var dirs = Array.isArray(view.root) && view.root.length > 1 - ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' - : 'directory "' + view.root + '"' - var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); - err.view = view; - return done(err); - } - - // prime the cache - if (renderOptions.cache) { - cache[name] = view; - } - } - - // render - tryRender(view, renderOptions, done); -}; - -/** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - * - * @return {http.Server} - * @public - */ - -app.listen = function listen() { - var server = http.createServer(this); - return server.listen.apply(server, arguments); -}; - -/** - * Log error using console.error. - * - * @param {Error} err - * @private - */ - -function logerror(err) { - /* istanbul ignore next */ - if (this.get('env') !== 'test') console.error(err.stack || err.toString()); -} - -/** - * Try rendering a view. - * @private - */ - -function tryRender(view, options, callback) { - try { - view.render(options, callback); - } catch (err) { - callback(err); - } -} diff --git a/node_modules/express/lib/express.js b/node_modules/express/lib/express.js deleted file mode 100644 index d188a16..0000000 --- a/node_modules/express/lib/express.js +++ /dev/null @@ -1,116 +0,0 @@ -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module dependencies. - */ - -var bodyParser = require('body-parser') -var EventEmitter = require('events').EventEmitter; -var mixin = require('merge-descriptors'); -var proto = require('./application'); -var Route = require('./router/route'); -var Router = require('./router'); -var req = require('./request'); -var res = require('./response'); - -/** - * Expose `createApplication()`. - */ - -exports = module.exports = createApplication; - -/** - * Create an express application. - * - * @return {Function} - * @api public - */ - -function createApplication() { - var app = function(req, res, next) { - app.handle(req, res, next); - }; - - mixin(app, EventEmitter.prototype, false); - mixin(app, proto, false); - - // expose the prototype that will get set on requests - app.request = Object.create(req, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) - - // expose the prototype that will get set on responses - app.response = Object.create(res, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) - - app.init(); - return app; -} - -/** - * Expose the prototypes. - */ - -exports.application = proto; -exports.request = req; -exports.response = res; - -/** - * Expose constructors. - */ - -exports.Route = Route; -exports.Router = Router; - -/** - * Expose middleware - */ - -exports.json = bodyParser.json -exports.query = require('./middleware/query'); -exports.raw = bodyParser.raw -exports.static = require('serve-static'); -exports.text = bodyParser.text -exports.urlencoded = bodyParser.urlencoded - -/** - * Replace removed middleware with an appropriate error message. - */ - -var removedMiddlewares = [ - 'bodyParser', - 'compress', - 'cookieSession', - 'session', - 'logger', - 'cookieParser', - 'favicon', - 'responseTime', - 'errorHandler', - 'timeout', - 'methodOverride', - 'vhost', - 'csrf', - 'directory', - 'limit', - 'multipart', - 'staticCache' -] - -removedMiddlewares.forEach(function (name) { - Object.defineProperty(exports, name, { - get: function () { - throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); - }, - configurable: true - }); -}); diff --git a/node_modules/express/lib/middleware/init.js b/node_modules/express/lib/middleware/init.js deleted file mode 100644 index dfd0427..0000000 --- a/node_modules/express/lib/middleware/init.js +++ /dev/null @@ -1,43 +0,0 @@ -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module dependencies. - * @private - */ - -var setPrototypeOf = require('setprototypeof') - -/** - * Initialization middleware, exposing the - * request and response to each other, as well - * as defaulting the X-Powered-By header field. - * - * @param {Function} app - * @return {Function} - * @api private - */ - -exports.init = function(app){ - return function expressInit(req, res, next){ - if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); - req.res = res; - res.req = req; - req.next = next; - - setPrototypeOf(req, app.request) - setPrototypeOf(res, app.response) - - res.locals = res.locals || Object.create(null); - - next(); - }; -}; - diff --git a/node_modules/express/lib/middleware/query.js b/node_modules/express/lib/middleware/query.js deleted file mode 100644 index 7e91669..0000000 --- a/node_modules/express/lib/middleware/query.js +++ /dev/null @@ -1,47 +0,0 @@ -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module dependencies. - */ - -var merge = require('utils-merge') -var parseUrl = require('parseurl'); -var qs = require('qs'); - -/** - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function query(options) { - var opts = merge({}, options) - var queryparse = qs.parse; - - if (typeof options === 'function') { - queryparse = options; - opts = undefined; - } - - if (opts !== undefined && opts.allowPrototypes === undefined) { - // back-compat for qs module - opts.allowPrototypes = true; - } - - return function query(req, res, next){ - if (!req.query) { - var val = parseUrl(req).query; - req.query = queryparse(val, opts); - } - - next(); - }; -}; diff --git a/node_modules/express/lib/request.js b/node_modules/express/lib/request.js deleted file mode 100644 index a9400ef..0000000 --- a/node_modules/express/lib/request.js +++ /dev/null @@ -1,525 +0,0 @@ -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module dependencies. - * @private - */ - -var accepts = require('accepts'); -var deprecate = require('depd')('express'); -var isIP = require('net').isIP; -var typeis = require('type-is'); -var http = require('http'); -var fresh = require('fresh'); -var parseRange = require('range-parser'); -var parse = require('parseurl'); -var proxyaddr = require('proxy-addr'); - -/** - * Request prototype. - * @public - */ - -var req = Object.create(http.IncomingMessage.prototype) - -/** - * Module exports. - * @public - */ - -module.exports = req - -/** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. - * - * @param {String} name - * @return {String} - * @public - */ - -req.get = -req.header = function header(name) { - if (!name) { - throw new TypeError('name argument is required to req.get'); - } - - if (typeof name !== 'string') { - throw new TypeError('name must be a string to req.get'); - } - - var lc = name.toLowerCase(); - - switch (lc) { - case 'referer': - case 'referrer': - return this.headers.referrer - || this.headers.referer; - default: - return this.headers[lc]; - } -}; - -/** - * To do: update docs. - * - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single MIME type string - * such as "application/json", an extension name - * such as "json", a comma-delimited list such as "json, html, text/plain", - * an argument list such as `"json", "html", "text/plain"`, - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given, the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html', 'json'); - * req.accepts('html, json'); - * // => "json" - * - * @param {String|Array} type(s) - * @return {String|Array|Boolean} - * @public - */ - -req.accepts = function(){ - var accept = accepts(this); - return accept.types.apply(accept, arguments); -}; - -/** - * Check if the given `encoding`s are accepted. - * - * @param {String} ...encoding - * @return {String|Array} - * @public - */ - -req.acceptsEncodings = function(){ - var accept = accepts(this); - return accept.encodings.apply(accept, arguments); -}; - -req.acceptsEncoding = deprecate.function(req.acceptsEncodings, - 'req.acceptsEncoding: Use acceptsEncodings instead'); - -/** - * Check if the given `charset`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...charset - * @return {String|Array} - * @public - */ - -req.acceptsCharsets = function(){ - var accept = accepts(this); - return accept.charsets.apply(accept, arguments); -}; - -req.acceptsCharset = deprecate.function(req.acceptsCharsets, - 'req.acceptsCharset: Use acceptsCharsets instead'); - -/** - * Check if the given `lang`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...lang - * @return {String|Array} - * @public - */ - -req.acceptsLanguages = function(){ - var accept = accepts(this); - return accept.languages.apply(accept, arguments); -}; - -req.acceptsLanguage = deprecate.function(req.acceptsLanguages, - 'req.acceptsLanguage: Use acceptsLanguages instead'); - -/** - * Parse Range header field, capping to the given `size`. - * - * Unspecified ranges such as "0-" require knowledge of your resource length. In - * the case of a byte range this is of course the total number of bytes. If the - * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, - * and `-2` when syntactically invalid. - * - * When ranges are returned, the array has a "type" property which is the type of - * range that is required (most commonly, "bytes"). Each array element is an object - * with a "start" and "end" property for the portion of the range. - * - * The "combine" option can be set to `true` and overlapping & adjacent ranges - * will be combined into a single range. - * - * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" - * should respond with 4 users when available, not 3. - * - * @param {number} size - * @param {object} [options] - * @param {boolean} [options.combine=false] - * @return {number|array} - * @public - */ - -req.range = function range(size, options) { - var range = this.get('Range'); - if (!range) return; - return parseRange(size, range, options); -}; - -/** - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `bodyParser()` middleware. - * - * @param {String} name - * @param {Mixed} [defaultValue] - * @return {String} - * @public - */ - -req.param = function param(name, defaultValue) { - var params = this.params || {}; - var body = this.body || {}; - var query = this.query || {}; - - var args = arguments.length === 1 - ? 'name' - : 'name, default'; - deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); - - if (null != params[name] && params.hasOwnProperty(name)) return params[name]; - if (null != body[name]) return body[name]; - if (null != query[name]) return query[name]; - - return defaultValue; -}; - -/** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param {String|Array} types... - * @return {String|false|null} - * @public - */ - -req.is = function is(types) { - var arr = types; - - // support flattened arguments - if (!Array.isArray(types)) { - arr = new Array(arguments.length); - for (var i = 0; i < arr.length; i++) { - arr[i] = arguments[i]; - } - } - - return typeis(this, arr); -}; - -/** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting trusts the socket address, the - * "X-Forwarded-Proto" header field will be trusted - * and used if present. - * - * If you're running behind a reverse proxy that - * supplies https for you this may be enabled. - * - * @return {String} - * @public - */ - -defineGetter(req, 'protocol', function protocol(){ - var proto = this.connection.encrypted - ? 'https' - : 'http'; - var trust = this.app.get('trust proxy fn'); - - if (!trust(this.connection.remoteAddress, 0)) { - return proto; - } - - // Note: X-Forwarded-Proto is normally only ever a - // single value, but this is to be safe. - var header = this.get('X-Forwarded-Proto') || proto - var index = header.indexOf(',') - - return index !== -1 - ? header.substring(0, index).trim() - : header.trim() -}); - -/** - * Short-hand for: - * - * req.protocol === 'https' - * - * @return {Boolean} - * @public - */ - -defineGetter(req, 'secure', function secure(){ - return this.protocol === 'https'; -}); - -/** - * Return the remote address from the trusted proxy. - * - * The is the remote address on the socket unless - * "trust proxy" is set. - * - * @return {String} - * @public - */ - -defineGetter(req, 'ip', function ip(){ - var trust = this.app.get('trust proxy fn'); - return proxyaddr(this, trust); -}); - -/** - * When "trust proxy" is set, trusted proxy addresses + client. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream and "proxy1" and - * "proxy2" were trusted. - * - * @return {Array} - * @public - */ - -defineGetter(req, 'ips', function ips() { - var trust = this.app.get('trust proxy fn'); - var addrs = proxyaddr.all(this, trust); - - // reverse the order (to farthest -> closest) - // and remove socket address - addrs.reverse().pop() - - return addrs -}); - -/** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - * - * @return {Array} - * @public - */ - -defineGetter(req, 'subdomains', function subdomains() { - var hostname = this.hostname; - - if (!hostname) return []; - - var offset = this.app.get('subdomain offset'); - var subdomains = !isIP(hostname) - ? hostname.split('.').reverse() - : [hostname]; - - return subdomains.slice(offset); -}); - -/** - * Short-hand for `url.parse(req.url).pathname`. - * - * @return {String} - * @public - */ - -defineGetter(req, 'path', function path() { - return parse(this).pathname; -}); - -/** - * Parse the "Host" header field to a hostname. - * - * When the "trust proxy" setting trusts the socket - * address, the "X-Forwarded-Host" header field will - * be trusted. - * - * @return {String} - * @public - */ - -defineGetter(req, 'hostname', function hostname(){ - var trust = this.app.get('trust proxy fn'); - var host = this.get('X-Forwarded-Host'); - - if (!host || !trust(this.connection.remoteAddress, 0)) { - host = this.get('Host'); - } else if (host.indexOf(',') !== -1) { - // Note: X-Forwarded-Host is normally only ever a - // single value, but this is to be safe. - host = host.substring(0, host.indexOf(',')).trimRight() - } - - if (!host) return; - - // IPv6 literal support - var offset = host[0] === '[' - ? host.indexOf(']') + 1 - : 0; - var index = host.indexOf(':', offset); - - return index !== -1 - ? host.substring(0, index) - : host; -}); - -// TODO: change req.host to return host in next major - -defineGetter(req, 'host', deprecate.function(function host(){ - return this.hostname; -}, 'req.host: Use req.hostname instead')); - -/** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - * - * @return {Boolean} - * @public - */ - -defineGetter(req, 'fresh', function(){ - var method = this.method; - var res = this.res - var status = res.statusCode - - // GET or HEAD for weak freshness validation only - if ('GET' !== method && 'HEAD' !== method) return false; - - // 2xx or 304 as per rfc2616 14.26 - if ((status >= 200 && status < 300) || 304 === status) { - return fresh(this.headers, { - 'etag': res.get('ETag'), - 'last-modified': res.get('Last-Modified') - }) - } - - return false; -}); - -/** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - * - * @return {Boolean} - * @public - */ - -defineGetter(req, 'stale', function stale(){ - return !this.fresh; -}); - -/** - * Check if the request was an _XMLHttpRequest_. - * - * @return {Boolean} - * @public - */ - -defineGetter(req, 'xhr', function xhr(){ - var val = this.get('X-Requested-With') || ''; - return val.toLowerCase() === 'xmlhttprequest'; -}); - -/** - * Helper function for creating a getter on an object. - * - * @param {Object} obj - * @param {String} name - * @param {Function} getter - * @private - */ -function defineGetter(obj, name, getter) { - Object.defineProperty(obj, name, { - configurable: true, - enumerable: true, - get: getter - }); -} diff --git a/node_modules/express/lib/response.js b/node_modules/express/lib/response.js deleted file mode 100644 index c9f08cd..0000000 --- a/node_modules/express/lib/response.js +++ /dev/null @@ -1,1142 +0,0 @@ -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module dependencies. - * @private - */ - -var Buffer = require('safe-buffer').Buffer -var contentDisposition = require('content-disposition'); -var deprecate = require('depd')('express'); -var encodeUrl = require('encodeurl'); -var escapeHtml = require('escape-html'); -var http = require('http'); -var isAbsolute = require('./utils').isAbsolute; -var onFinished = require('on-finished'); -var path = require('path'); -var statuses = require('statuses') -var merge = require('utils-merge'); -var sign = require('cookie-signature').sign; -var normalizeType = require('./utils').normalizeType; -var normalizeTypes = require('./utils').normalizeTypes; -var setCharset = require('./utils').setCharset; -var cookie = require('cookie'); -var send = require('send'); -var extname = path.extname; -var mime = send.mime; -var resolve = path.resolve; -var vary = require('vary'); - -/** - * Response prototype. - * @public - */ - -var res = Object.create(http.ServerResponse.prototype) - -/** - * Module exports. - * @public - */ - -module.exports = res - -/** - * Module variables. - * @private - */ - -var charsetRegExp = /;\s*charset\s*=/; - -/** - * Set status `code`. - * - * @param {Number} code - * @return {ServerResponse} - * @public - */ - -res.status = function status(code) { - this.statusCode = code; - return this; -}; - -/** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param {Object} links - * @return {ServerResponse} - * @public - */ - -res.links = function(links){ - var link = this.get('Link') || ''; - if (link) link += ', '; - return this.set('Link', link + Object.keys(links).map(function(rel){ - return '<' + links[rel] + '>; rel="' + rel + '"'; - }).join(', ')); -}; - -/** - * Send a response. - * - * Examples: - * - * res.send(Buffer.from('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * - * @param {string|number|boolean|object|Buffer} body - * @public - */ - -res.send = function send(body) { - var chunk = body; - var encoding; - var req = this.req; - var type; - - // settings - var app = this.app; - - // allow status / body - if (arguments.length === 2) { - // res.send(body, status) backwards compat - if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { - deprecate('res.send(body, status): Use res.status(status).send(body) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.send(status, body): Use res.status(status).send(body) instead'); - this.statusCode = arguments[0]; - chunk = arguments[1]; - } - } - - // disambiguate res.send(status) and res.send(status, num) - if (typeof chunk === 'number' && arguments.length === 1) { - // res.send(status) will set status message as text string - if (!this.get('Content-Type')) { - this.type('txt'); - } - - deprecate('res.send(status): Use res.sendStatus(status) instead'); - this.statusCode = chunk; - chunk = statuses[chunk] - } - - switch (typeof chunk) { - // string defaulting to html - case 'string': - if (!this.get('Content-Type')) { - this.type('html'); - } - break; - case 'boolean': - case 'number': - case 'object': - if (chunk === null) { - chunk = ''; - } else if (Buffer.isBuffer(chunk)) { - if (!this.get('Content-Type')) { - this.type('bin'); - } - } else { - return this.json(chunk); - } - break; - } - - // write strings in utf-8 - if (typeof chunk === 'string') { - encoding = 'utf8'; - type = this.get('Content-Type'); - - // reflect this in content-type - if (typeof type === 'string') { - this.set('Content-Type', setCharset(type, 'utf-8')); - } - } - - // determine if ETag should be generated - var etagFn = app.get('etag fn') - var generateETag = !this.get('ETag') && typeof etagFn === 'function' - - // populate Content-Length - var len - if (chunk !== undefined) { - if (Buffer.isBuffer(chunk)) { - // get length of Buffer - len = chunk.length - } else if (!generateETag && chunk.length < 1000) { - // just calculate length when no ETag + small chunk - len = Buffer.byteLength(chunk, encoding) - } else { - // convert chunk to Buffer and calculate - chunk = Buffer.from(chunk, encoding) - encoding = undefined; - len = chunk.length - } - - this.set('Content-Length', len); - } - - // populate ETag - var etag; - if (generateETag && len !== undefined) { - if ((etag = etagFn(chunk, encoding))) { - this.set('ETag', etag); - } - } - - // freshness - if (req.fresh) this.statusCode = 304; - - // strip irrelevant headers - if (204 === this.statusCode || 304 === this.statusCode) { - this.removeHeader('Content-Type'); - this.removeHeader('Content-Length'); - this.removeHeader('Transfer-Encoding'); - chunk = ''; - } - - if (req.method === 'HEAD') { - // skip body for HEAD - this.end(); - } else { - // respond - this.end(chunk, encoding); - } - - return this; -}; - -/** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @public - */ - -res.json = function json(obj) { - var val = obj; - - // allow status / body - if (arguments.length === 2) { - // res.json(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; - } - } - - // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(val, replacer, spaces, escape) - - // content-type - if (!this.get('Content-Type')) { - this.set('Content-Type', 'application/json'); - } - - return this.send(body); -}; - -/** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @public - */ - -res.jsonp = function jsonp(obj) { - var val = obj; - - // allow status / body - if (arguments.length === 2) { - // res.json(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; - } - } - - // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(val, replacer, spaces, escape) - var callback = this.req.query[app.get('jsonp callback name')]; - - // content-type - if (!this.get('Content-Type')) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'application/json'); - } - - // fixup callback - if (Array.isArray(callback)) { - callback = callback[0]; - } - - // jsonp - if (typeof callback === 'string' && callback.length !== 0) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'text/javascript'); - - // restrict callback charset - callback = callback.replace(/[^\[\]\w$.]/g, ''); - - // replace chars not allowed in JavaScript that are in JSON - body = body - .replace(/\u2028/g, '\\u2028') - .replace(/\u2029/g, '\\u2029'); - - // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" - // the typeof check is just to reduce client error noise - body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; - } - - return this.send(body); -}; - -/** - * Send given HTTP status code. - * - * Sets the response status to `statusCode` and the body of the - * response to the standard description from node's http.STATUS_CODES - * or the statusCode number if no description. - * - * Examples: - * - * res.sendStatus(200); - * - * @param {number} statusCode - * @public - */ - -res.sendStatus = function sendStatus(statusCode) { - var body = statuses[statusCode] || String(statusCode) - - this.statusCode = statusCode; - this.type('txt'); - - return this.send(body); -}; - -/** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `callback(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @public - */ - -res.sendFile = function sendFile(path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; - - if (!path) { - throw new TypeError('path argument is required to res.sendFile'); - } - - if (typeof path !== 'string') { - throw new TypeError('path must be a string to res.sendFile') - } - - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } - - if (!opts.root && !isAbsolute(path)) { - throw new TypeError('path must be absolute or specify root to res.sendFile'); - } - - // create file stream - var pathname = encodeURI(path); - var file = send(req, pathname, opts); - - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); - - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); -}; - -/** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `callback(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendfile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendfile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendfile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @public - */ - -res.sendfile = function (path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; - - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } - - // create file stream - var file = send(req, path, opts); - - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); - - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); -}; - -res.sendfile = deprecate.function(res.sendfile, - 'res.sendfile: Use res.sendFile instead'); - -/** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `callback(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headersSent` if you plan to respond. - * - * Optionally providing an `options` object to use with `res.sendFile()`. - * This function will set the `Content-Disposition` header, overriding - * any `Content-Disposition` header passed as header options in order - * to set the attachment and filename. - * - * This method uses `res.sendFile()`. - * - * @public - */ - -res.download = function download (path, filename, options, callback) { - var done = callback; - var name = filename; - var opts = options || null - - // support function as second or third arg - if (typeof filename === 'function') { - done = filename; - name = null; - opts = null - } else if (typeof options === 'function') { - done = options - opts = null - } - - // set Content-Disposition when file is sent - var headers = { - 'Content-Disposition': contentDisposition(name || path) - }; - - // merge user-provided headers - if (opts && opts.headers) { - var keys = Object.keys(opts.headers) - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - if (key.toLowerCase() !== 'content-disposition') { - headers[key] = opts.headers[key] - } - } - } - - // merge user-provided options - opts = Object.create(opts) - opts.headers = headers - - // Resolve the full path for sendFile - var fullPath = resolve(path); - - // send file - return this.sendFile(fullPath, opts, done) -}; - -/** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param {String} type - * @return {ServerResponse} for chaining - * @public - */ - -res.contentType = -res.type = function contentType(type) { - var ct = type.indexOf('/') === -1 - ? mime.lookup(type) - : type; - - return this.set('Content-Type', ct); -}; - -/** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'appliation/json': function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param {Object} obj - * @return {ServerResponse} for chaining - * @public - */ - -res.format = function(obj){ - var req = this.req; - var next = req.next; - - var fn = obj.default; - if (fn) delete obj.default; - var keys = Object.keys(obj); - - var key = keys.length > 0 - ? req.accepts(keys) - : false; - - this.vary("Accept"); - - if (key) { - this.set('Content-Type', normalizeType(key).value); - obj[key](req, this, next); - } else if (fn) { - fn(); - } else { - var err = new Error('Not Acceptable'); - err.status = err.statusCode = 406; - err.types = normalizeTypes(keys).map(function(o){ return o.value }); - next(err); - } - - return this; -}; - -/** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param {String} filename - * @return {ServerResponse} - * @public - */ - -res.attachment = function attachment(filename) { - if (filename) { - this.type(extname(filename)); - } - - this.set('Content-Disposition', contentDisposition(filename)); - - return this; -}; - -/** - * Append additional header `field` with value `val`. - * - * Example: - * - * res.append('Link', ['', '']); - * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); - * res.append('Warning', '199 Miscellaneous warning'); - * - * @param {String} field - * @param {String|Array} val - * @return {ServerResponse} for chaining - * @public - */ - -res.append = function append(field, val) { - var prev = this.get(field); - var value = val; - - if (prev) { - // concat the new and prev vals - value = Array.isArray(prev) ? prev.concat(val) - : Array.isArray(val) ? [prev].concat(val) - : [prev, val]; - } - - return this.set(field, value); -}; - -/** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - * - * @param {String|Object} field - * @param {String|Array} val - * @return {ServerResponse} for chaining - * @public - */ - -res.set = -res.header = function header(field, val) { - if (arguments.length === 2) { - var value = Array.isArray(val) - ? val.map(String) - : String(val); - - // add charset to content-type - if (field.toLowerCase() === 'content-type') { - if (Array.isArray(value)) { - throw new TypeError('Content-Type cannot be set to an Array'); - } - if (!charsetRegExp.test(value)) { - var charset = mime.charsets.lookup(value.split(';')[0]); - if (charset) value += '; charset=' + charset.toLowerCase(); - } - } - - this.setHeader(field, value); - } else { - for (var key in field) { - this.set(key, field[key]); - } - } - return this; -}; - -/** - * Get value for header `field`. - * - * @param {String} field - * @return {String} - * @public - */ - -res.get = function(field){ - return this.getHeader(field); -}; - -/** - * Clear cookie `name`. - * - * @param {String} name - * @param {Object} [options] - * @return {ServerResponse} for chaining - * @public - */ - -res.clearCookie = function clearCookie(name, options) { - var opts = merge({ expires: new Date(1), path: '/' }, options); - - return this.cookie(name, '', opts); -}; - -/** - * Set cookie `name` to `value`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // same as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - * - * @param {String} name - * @param {String|Object} value - * @param {Object} [options] - * @return {ServerResponse} for chaining - * @public - */ - -res.cookie = function (name, value, options) { - var opts = merge({}, options); - var secret = this.req.secret; - var signed = opts.signed; - - if (signed && !secret) { - throw new Error('cookieParser("secret") required for signed cookies'); - } - - var val = typeof value === 'object' - ? 'j:' + JSON.stringify(value) - : String(value); - - if (signed) { - val = 's:' + sign(val, secret); - } - - if ('maxAge' in opts) { - opts.expires = new Date(Date.now() + opts.maxAge); - opts.maxAge /= 1000; - } - - if (opts.path == null) { - opts.path = '/'; - } - - this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); - - return this; -}; - -/** - * Set the location header to `url`. - * - * The given `url` can also be "back", which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); - * - * @param {String} url - * @return {ServerResponse} for chaining - * @public - */ - -res.location = function location(url) { - var loc = url; - - // "back" is an alias for the referrer - if (url === 'back') { - loc = this.req.get('Referrer') || '/'; - } - - // set location - return this.set('Location', encodeUrl(loc)); -}; - -/** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - * - * @public - */ - -res.redirect = function redirect(url) { - var address = url; - var body; - var status = 302; - - // allow status / url - if (arguments.length === 2) { - if (typeof arguments[0] === 'number') { - status = arguments[0]; - address = arguments[1]; - } else { - deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); - status = arguments[1]; - } - } - - // Set location header - address = this.location(address).get('Location'); - - // Support text/{plain,html} by default - this.format({ - text: function(){ - body = statuses[status] + '. Redirecting to ' + address - }, - - html: function(){ - var u = escapeHtml(address); - body = '

' + statuses[status] + '. Redirecting to ' + u + '

' - }, - - default: function(){ - body = ''; - } - }); - - // Respond - this.statusCode = status; - this.set('Content-Length', Buffer.byteLength(body)); - - if (this.req.method === 'HEAD') { - this.end(); - } else { - this.end(body); - } -}; - -/** - * Add `field` to Vary. If already present in the Vary set, then - * this call is simply ignored. - * - * @param {Array|String} field - * @return {ServerResponse} for chaining - * @public - */ - -res.vary = function(field){ - // checks for back-compat - if (!field || (Array.isArray(field) && !field.length)) { - deprecate('res.vary(): Provide a field name'); - return this; - } - - vary(this, field); - - return this; -}; - -/** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - * - * @public - */ - -res.render = function render(view, options, callback) { - var app = this.req.app; - var done = callback; - var opts = options || {}; - var req = this.req; - var self = this; - - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } - - // merge res.locals - opts._locals = self.locals; - - // default callback to respond - done = done || function (err, str) { - if (err) return req.next(err); - self.send(str); - }; - - // render - app.render(view, opts, done); -}; - -// pipe the send file stream -function sendfile(res, file, options, callback) { - var done = false; - var streaming; - - // request aborted - function onaborted() { - if (done) return; - done = true; - - var err = new Error('Request aborted'); - err.code = 'ECONNABORTED'; - callback(err); - } - - // directory - function ondirectory() { - if (done) return; - done = true; - - var err = new Error('EISDIR, read'); - err.code = 'EISDIR'; - callback(err); - } - - // errors - function onerror(err) { - if (done) return; - done = true; - callback(err); - } - - // ended - function onend() { - if (done) return; - done = true; - callback(); - } - - // file - function onfile() { - streaming = false; - } - - // finished - function onfinish(err) { - if (err && err.code === 'ECONNRESET') return onaborted(); - if (err) return onerror(err); - if (done) return; - - setImmediate(function () { - if (streaming !== false && !done) { - onaborted(); - return; - } - - if (done) return; - done = true; - callback(); - }); - } - - // streaming - function onstream() { - streaming = true; - } - - file.on('directory', ondirectory); - file.on('end', onend); - file.on('error', onerror); - file.on('file', onfile); - file.on('stream', onstream); - onFinished(res, onfinish); - - if (options.headers) { - // set headers on successful transfer - file.on('headers', function headers(res) { - var obj = options.headers; - var keys = Object.keys(obj); - - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - res.setHeader(k, obj[k]); - } - }); - } - - // pipe - file.pipe(res); -} - -/** - * Stringify JSON, like JSON.stringify, but v8 optimized, with the - * ability to escape characters that can trigger HTML sniffing. - * - * @param {*} value - * @param {function} replaces - * @param {number} spaces - * @param {boolean} escape - * @returns {string} - * @private - */ - -function stringify (value, replacer, spaces, escape) { - // v8 checks arguments.length for optimizing simple call - // https://bugs.chromium.org/p/v8/issues/detail?id=4730 - var json = replacer || spaces - ? JSON.stringify(value, replacer, spaces) - : JSON.stringify(value); - - if (escape) { - json = json.replace(/[<>&]/g, function (c) { - switch (c.charCodeAt(0)) { - case 0x3c: - return '\\u003c' - case 0x3e: - return '\\u003e' - case 0x26: - return '\\u0026' - /* istanbul ignore next: unreachable default */ - default: - return c - } - }) - } - - return json -} diff --git a/node_modules/express/lib/router/index.js b/node_modules/express/lib/router/index.js deleted file mode 100644 index 69e6d38..0000000 --- a/node_modules/express/lib/router/index.js +++ /dev/null @@ -1,662 +0,0 @@ -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module dependencies. - * @private - */ - -var Route = require('./route'); -var Layer = require('./layer'); -var methods = require('methods'); -var mixin = require('utils-merge'); -var debug = require('debug')('express:router'); -var deprecate = require('depd')('express'); -var flatten = require('array-flatten'); -var parseUrl = require('parseurl'); -var setPrototypeOf = require('setprototypeof') - -/** - * Module variables. - * @private - */ - -var objectRegExp = /^\[object (\S+)\]$/; -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; - -/** - * Initialize a new `Router` with the given `options`. - * - * @param {Object} [options] - * @return {Router} which is an callable function - * @public - */ - -var proto = module.exports = function(options) { - var opts = options || {}; - - function router(req, res, next) { - router.handle(req, res, next); - } - - // mixin Router class functions - setPrototypeOf(router, proto) - - router.params = {}; - router._params = []; - router.caseSensitive = opts.caseSensitive; - router.mergeParams = opts.mergeParams; - router.strict = opts.strict; - router.stack = []; - - return router; -}; - -/** - * Map the given param placeholder `name`(s) to the given callback. - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the same signature as middleware, the only difference - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * Just like in middleware, you must either respond to the request or call next - * to avoid stalling the request. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * return next(err); - * } else if (!user) { - * return next(new Error('failed to load user')); - * } - * req.user = user; - * next(); - * }); - * }); - * - * @param {String} name - * @param {Function} fn - * @return {app} for chaining - * @public - */ - -proto.param = function param(name, fn) { - // param logic - if (typeof name === 'function') { - deprecate('router.param(fn): Refactor to use path params'); - this._params.push(name); - return; - } - - // apply param functions - var params = this._params; - var len = params.length; - var ret; - - if (name[0] === ':') { - deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); - name = name.substr(1); - } - - for (var i = 0; i < len; ++i) { - if (ret = params[i](name, fn)) { - fn = ret; - } - } - - // ensure we end up with a - // middleware function - if ('function' !== typeof fn) { - throw new Error('invalid param() call for ' + name + ', got ' + fn); - } - - (this.params[name] = this.params[name] || []).push(fn); - return this; -}; - -/** - * Dispatch a req, res into the router. - * @private - */ - -proto.handle = function handle(req, res, out) { - var self = this; - - debug('dispatching %s %s', req.method, req.url); - - var idx = 0; - var protohost = getProtohost(req.url) || '' - var removed = ''; - var slashAdded = false; - var paramcalled = {}; - - // store options for OPTIONS request - // only used if OPTIONS request - var options = []; - - // middleware and routes - var stack = self.stack; - - // manage inter-router variables - var parentParams = req.params; - var parentUrl = req.baseUrl || ''; - var done = restore(out, req, 'baseUrl', 'next', 'params'); - - // setup next layer - req.next = next; - - // for options requests, respond with a default if nothing else responds - if (req.method === 'OPTIONS') { - done = wrap(done, function(old, err) { - if (err || options.length === 0) return old(err); - sendOptionsResponse(res, options, old); - }); - } - - // setup basic req values - req.baseUrl = parentUrl; - req.originalUrl = req.originalUrl || req.url; - - next(); - - function next(err) { - var layerError = err === 'route' - ? null - : err; - - // remove added slash - if (slashAdded) { - req.url = req.url.substr(1); - slashAdded = false; - } - - // restore altered req.url - if (removed.length !== 0) { - req.baseUrl = parentUrl; - req.url = protohost + removed + req.url.substr(protohost.length); - removed = ''; - } - - // signal to exit router - if (layerError === 'router') { - setImmediate(done, null) - return - } - - // no more matching layers - if (idx >= stack.length) { - setImmediate(done, layerError); - return; - } - - // get pathname of request - var path = getPathname(req); - - if (path == null) { - return done(layerError); - } - - // find next matching layer - var layer; - var match; - var route; - - while (match !== true && idx < stack.length) { - layer = stack[idx++]; - match = matchLayer(layer, path); - route = layer.route; - - if (typeof match !== 'boolean') { - // hold on to layerError - layerError = layerError || match; - } - - if (match !== true) { - continue; - } - - if (!route) { - // process non-route handlers normally - continue; - } - - if (layerError) { - // routes do not match with a pending error - match = false; - continue; - } - - var method = req.method; - var has_method = route._handles_method(method); - - // build up automatic options response - if (!has_method && method === 'OPTIONS') { - appendMethods(options, route._options()); - } - - // don't even bother matching route - if (!has_method && method !== 'HEAD') { - match = false; - continue; - } - } - - // no match - if (match !== true) { - return done(layerError); - } - - // store route for dispatch on change - if (route) { - req.route = route; - } - - // Capture one-time layer values - req.params = self.mergeParams - ? mergeParams(layer.params, parentParams) - : layer.params; - var layerPath = layer.path; - - // this should be done for the layer - self.process_params(layer, paramcalled, req, res, function (err) { - if (err) { - return next(layerError || err); - } - - if (route) { - return layer.handle_request(req, res, next); - } - - trim_prefix(layer, layerError, layerPath, path); - }); - } - - function trim_prefix(layer, layerError, layerPath, path) { - if (layerPath.length !== 0) { - // Validate path breaks on a path separator - var c = path[layerPath.length] - if (c && c !== '/' && c !== '.') return next(layerError) - - // Trim off the part of the url that matches the route - // middleware (.use stuff) needs to have the path stripped - debug('trim prefix (%s) from url %s', layerPath, req.url); - removed = layerPath; - req.url = protohost + req.url.substr(protohost.length + removed.length); - - // Ensure leading slash - if (!protohost && req.url[0] !== '/') { - req.url = '/' + req.url; - slashAdded = true; - } - - // Setup base URL (no trailing slash) - req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' - ? removed.substring(0, removed.length - 1) - : removed); - } - - debug('%s %s : %s', layer.name, layerPath, req.originalUrl); - - if (layerError) { - layer.handle_error(layerError, req, res, next); - } else { - layer.handle_request(req, res, next); - } - } -}; - -/** - * Process any parameters for the layer. - * @private - */ - -proto.process_params = function process_params(layer, called, req, res, done) { - var params = this.params; - - // captured parameters from the layer, keys and values - var keys = layer.keys; - - // fast track - if (!keys || keys.length === 0) { - return done(); - } - - var i = 0; - var name; - var paramIndex = 0; - var key; - var paramVal; - var paramCallbacks; - var paramCalled; - - // process params in order - // param callbacks can be async - function param(err) { - if (err) { - return done(err); - } - - if (i >= keys.length ) { - return done(); - } - - paramIndex = 0; - key = keys[i++]; - name = key.name; - paramVal = req.params[name]; - paramCallbacks = params[name]; - paramCalled = called[name]; - - if (paramVal === undefined || !paramCallbacks) { - return param(); - } - - // param previously called with same value or error occurred - if (paramCalled && (paramCalled.match === paramVal - || (paramCalled.error && paramCalled.error !== 'route'))) { - // restore value - req.params[name] = paramCalled.value; - - // next param - return param(paramCalled.error); - } - - called[name] = paramCalled = { - error: null, - match: paramVal, - value: paramVal - }; - - paramCallback(); - } - - // single param callbacks - function paramCallback(err) { - var fn = paramCallbacks[paramIndex++]; - - // store updated value - paramCalled.value = req.params[key.name]; - - if (err) { - // store error - paramCalled.error = err; - param(err); - return; - } - - if (!fn) return param(); - - try { - fn(req, res, paramCallback, paramVal, key.name); - } catch (e) { - paramCallback(e); - } - } - - param(); -}; - -/** - * Use the given middleware function, with optional path, defaulting to "/". - * - * Use (like `.all`) will run for any http METHOD, but it will not add - * handlers for those methods so OPTIONS requests will not consider `.use` - * functions even if they could respond. - * - * The other difference is that _route_ path is stripped and not visible - * to the handler function. The main effect of this feature is that mounted - * handlers can operate without any code changes regardless of the "prefix" - * pathname. - * - * @public - */ - -proto.use = function use(fn) { - var offset = 0; - var path = '/'; - - // default path to '/' - // disambiguate router.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; - - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } - - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } - } - - var callbacks = flatten(slice.call(arguments, offset)); - - if (callbacks.length === 0) { - throw new TypeError('Router.use() requires a middleware function') - } - - for (var i = 0; i < callbacks.length; i++) { - var fn = callbacks[i]; - - if (typeof fn !== 'function') { - throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) - } - - // add the middleware - debug('use %o %s', path, fn.name || '') - - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: false, - end: false - }, fn); - - layer.route = undefined; - - this.stack.push(layer); - } - - return this; -}; - -/** - * Create a new Route for the given path. - * - * Each route contains a separate middleware stack and VERB handlers. - * - * See the Route api documentation for details on adding handlers - * and middleware to routes. - * - * @param {String} path - * @return {Route} - * @public - */ - -proto.route = function route(path) { - var route = new Route(path); - - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: this.strict, - end: true - }, route.dispatch.bind(route)); - - layer.route = route; - - this.stack.push(layer); - return route; -}; - -// create Router#VERB functions -methods.concat('all').forEach(function(method){ - proto[method] = function(path){ - var route = this.route(path) - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; -}); - -// append methods to a list of methods -function appendMethods(list, addition) { - for (var i = 0; i < addition.length; i++) { - var method = addition[i]; - if (list.indexOf(method) === -1) { - list.push(method); - } - } -} - -// get pathname of request -function getPathname(req) { - try { - return parseUrl(req).pathname; - } catch (err) { - return undefined; - } -} - -// Get get protocol + host for a URL -function getProtohost(url) { - if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { - return undefined - } - - var searchIndex = url.indexOf('?') - var pathLength = searchIndex !== -1 - ? searchIndex - : url.length - var fqdnIndex = url.substr(0, pathLength).indexOf('://') - - return fqdnIndex !== -1 - ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) - : undefined -} - -// get type for error message -function gettype(obj) { - var type = typeof obj; - - if (type !== 'object') { - return type; - } - - // inspect [[Class]] for objects - return toString.call(obj) - .replace(objectRegExp, '$1'); -} - -/** - * Match path to a layer. - * - * @param {Layer} layer - * @param {string} path - * @private - */ - -function matchLayer(layer, path) { - try { - return layer.match(path); - } catch (err) { - return err; - } -} - -// merge params with parent params -function mergeParams(params, parent) { - if (typeof parent !== 'object' || !parent) { - return params; - } - - // make copy of parent for base - var obj = mixin({}, parent); - - // simple non-numeric merging - if (!(0 in params) || !(0 in parent)) { - return mixin(obj, params); - } - - var i = 0; - var o = 0; - - // determine numeric gaps - while (i in params) { - i++; - } - - while (o in parent) { - o++; - } - - // offset numeric indices in params before merge - for (i--; i >= 0; i--) { - params[i + o] = params[i]; - - // create holes for the merge when necessary - if (i < o) { - delete params[i]; - } - } - - return mixin(obj, params); -} - -// restore obj props after function -function restore(fn, obj) { - var props = new Array(arguments.length - 2); - var vals = new Array(arguments.length - 2); - - for (var i = 0; i < props.length; i++) { - props[i] = arguments[i + 2]; - vals[i] = obj[props[i]]; - } - - return function () { - // restore vals - for (var i = 0; i < props.length; i++) { - obj[props[i]] = vals[i]; - } - - return fn.apply(this, arguments); - }; -} - -// send an OPTIONS response -function sendOptionsResponse(res, options, next) { - try { - var body = options.join(','); - res.set('Allow', body); - res.send(body); - } catch (err) { - next(err); - } -} - -// wrap a function -function wrap(old, fn) { - return function proxy() { - var args = new Array(arguments.length + 1); - - args[0] = old; - for (var i = 0, len = arguments.length; i < len; i++) { - args[i + 1] = arguments[i]; - } - - fn.apply(this, args); - }; -} diff --git a/node_modules/express/lib/router/layer.js b/node_modules/express/lib/router/layer.js deleted file mode 100644 index 4dc8e86..0000000 --- a/node_modules/express/lib/router/layer.js +++ /dev/null @@ -1,181 +0,0 @@ -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module dependencies. - * @private - */ - -var pathRegexp = require('path-to-regexp'); -var debug = require('debug')('express:router:layer'); - -/** - * Module variables. - * @private - */ - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -/** - * Module exports. - * @public - */ - -module.exports = Layer; - -function Layer(path, options, fn) { - if (!(this instanceof Layer)) { - return new Layer(path, options, fn); - } - - debug('new %o', path) - var opts = options || {}; - - this.handle = fn; - this.name = fn.name || ''; - this.params = undefined; - this.path = undefined; - this.regexp = pathRegexp(path, this.keys = [], opts); - - // set fast path flags - this.regexp.fast_star = path === '*' - this.regexp.fast_slash = path === '/' && opts.end === false -} - -/** - * Handle the error for the layer. - * - * @param {Error} error - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private - */ - -Layer.prototype.handle_error = function handle_error(error, req, res, next) { - var fn = this.handle; - - if (fn.length !== 4) { - // not a standard error handler - return next(error); - } - - try { - fn(error, req, res, next); - } catch (err) { - next(err); - } -}; - -/** - * Handle the request for the layer. - * - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private - */ - -Layer.prototype.handle_request = function handle(req, res, next) { - var fn = this.handle; - - if (fn.length > 3) { - // not a standard request handler - return next(); - } - - try { - fn(req, res, next); - } catch (err) { - next(err); - } -}; - -/** - * Check if this route matches `path`, if so - * populate `.params`. - * - * @param {String} path - * @return {Boolean} - * @api private - */ - -Layer.prototype.match = function match(path) { - var match - - if (path != null) { - // fast path non-ending match for / (any path matches) - if (this.regexp.fast_slash) { - this.params = {} - this.path = '' - return true - } - - // fast path for * (everything matched in a param) - if (this.regexp.fast_star) { - this.params = {'0': decode_param(path)} - this.path = path - return true - } - - // match the path - match = this.regexp.exec(path) - } - - if (!match) { - this.params = undefined; - this.path = undefined; - return false; - } - - // store values - this.params = {}; - this.path = match[0] - - var keys = this.keys; - var params = this.params; - - for (var i = 1; i < match.length; i++) { - var key = keys[i - 1]; - var prop = key.name; - var val = decode_param(match[i]) - - if (val !== undefined || !(hasOwnProperty.call(params, prop))) { - params[prop] = val; - } - } - - return true; -}; - -/** - * Decode param value. - * - * @param {string} val - * @return {string} - * @private - */ - -function decode_param(val) { - if (typeof val !== 'string' || val.length === 0) { - return val; - } - - try { - return decodeURIComponent(val); - } catch (err) { - if (err instanceof URIError) { - err.message = 'Failed to decode param \'' + val + '\''; - err.status = err.statusCode = 400; - } - - throw err; - } -} diff --git a/node_modules/express/lib/router/route.js b/node_modules/express/lib/router/route.js deleted file mode 100644 index 178df0d..0000000 --- a/node_modules/express/lib/router/route.js +++ /dev/null @@ -1,216 +0,0 @@ -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module dependencies. - * @private - */ - -var debug = require('debug')('express:router:route'); -var flatten = require('array-flatten'); -var Layer = require('./layer'); -var methods = require('methods'); - -/** - * Module variables. - * @private - */ - -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; - -/** - * Module exports. - * @public - */ - -module.exports = Route; - -/** - * Initialize `Route` with the given `path`, - * - * @param {String} path - * @public - */ - -function Route(path) { - this.path = path; - this.stack = []; - - debug('new %o', path) - - // route handlers for various http methods - this.methods = {}; -} - -/** - * Determine if the route handles a given method. - * @private - */ - -Route.prototype._handles_method = function _handles_method(method) { - if (this.methods._all) { - return true; - } - - var name = method.toLowerCase(); - - if (name === 'head' && !this.methods['head']) { - name = 'get'; - } - - return Boolean(this.methods[name]); -}; - -/** - * @return {Array} supported HTTP methods - * @private - */ - -Route.prototype._options = function _options() { - var methods = Object.keys(this.methods); - - // append automatic head - if (this.methods.get && !this.methods.head) { - methods.push('head'); - } - - for (var i = 0; i < methods.length; i++) { - // make upper case - methods[i] = methods[i].toUpperCase(); - } - - return methods; -}; - -/** - * dispatch req, res into this route - * @private - */ - -Route.prototype.dispatch = function dispatch(req, res, done) { - var idx = 0; - var stack = this.stack; - if (stack.length === 0) { - return done(); - } - - var method = req.method.toLowerCase(); - if (method === 'head' && !this.methods['head']) { - method = 'get'; - } - - req.route = this; - - next(); - - function next(err) { - // signal to exit route - if (err && err === 'route') { - return done(); - } - - // signal to exit router - if (err && err === 'router') { - return done(err) - } - - var layer = stack[idx++]; - if (!layer) { - return done(err); - } - - if (layer.method && layer.method !== method) { - return next(err); - } - - if (err) { - layer.handle_error(err, req, res, next); - } else { - layer.handle_request(req, res, next); - } - } -}; - -/** - * Add a handler for all HTTP verbs to this route. - * - * Behaves just like middleware and can respond or call `next` - * to continue processing. - * - * You can use multiple `.all` call to add multiple handlers. - * - * function check_something(req, res, next){ - * next(); - * }; - * - * function validate_user(req, res, next){ - * next(); - * }; - * - * route - * .all(validate_user) - * .all(check_something) - * .get(function(req, res, next){ - * res.send('hello world'); - * }); - * - * @param {function} handler - * @return {Route} for chaining - * @api public - */ - -Route.prototype.all = function all() { - var handles = flatten(slice.call(arguments)); - - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; - - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.all() requires a callback function but got a ' + type - throw new TypeError(msg); - } - - var layer = Layer('/', {}, handle); - layer.method = undefined; - - this.methods._all = true; - this.stack.push(layer); - } - - return this; -}; - -methods.forEach(function(method){ - Route.prototype[method] = function(){ - var handles = flatten(slice.call(arguments)); - - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; - - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.' + method + '() requires a callback function but got a ' + type - throw new Error(msg); - } - - debug('%s %o', method, this.path) - - var layer = Layer('/', {}, handle); - layer.method = method; - - this.methods[method] = true; - this.stack.push(layer); - } - - return this; - }; -}); diff --git a/node_modules/express/lib/utils.js b/node_modules/express/lib/utils.js deleted file mode 100644 index bd81ac7..0000000 --- a/node_modules/express/lib/utils.js +++ /dev/null @@ -1,306 +0,0 @@ -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module dependencies. - * @api private - */ - -var Buffer = require('safe-buffer').Buffer -var contentDisposition = require('content-disposition'); -var contentType = require('content-type'); -var deprecate = require('depd')('express'); -var flatten = require('array-flatten'); -var mime = require('send').mime; -var etag = require('etag'); -var proxyaddr = require('proxy-addr'); -var qs = require('qs'); -var querystring = require('querystring'); - -/** - * Return strong ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ - -exports.etag = createETagGenerator({ weak: false }) - -/** - * Return weak ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ - -exports.wetag = createETagGenerator({ weak: true }) - -/** - * Check if `path` looks absolute. - * - * @param {String} path - * @return {Boolean} - * @api private - */ - -exports.isAbsolute = function(path){ - if ('/' === path[0]) return true; - if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path - if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path -}; - -/** - * Flatten the given `arr`. - * - * @param {Array} arr - * @return {Array} - * @api private - */ - -exports.flatten = deprecate.function(flatten, - 'utils.flatten: use array-flatten npm module instead'); - -/** - * Normalize the given `type`, for example "html" becomes "text/html". - * - * @param {String} type - * @return {Object} - * @api private - */ - -exports.normalizeType = function(type){ - return ~type.indexOf('/') - ? acceptParams(type) - : { value: mime.lookup(type), params: {} }; -}; - -/** - * Normalize `types`, for example "html" becomes "text/html". - * - * @param {Array} types - * @return {Array} - * @api private - */ - -exports.normalizeTypes = function(types){ - var ret = []; - - for (var i = 0; i < types.length; ++i) { - ret.push(exports.normalizeType(types[i])); - } - - return ret; -}; - -/** - * Generate Content-Disposition header appropriate for the filename. - * non-ascii filenames are urlencoded and a filename* parameter is added - * - * @param {String} filename - * @return {String} - * @api private - */ - -exports.contentDisposition = deprecate.function(contentDisposition, - 'utils.contentDisposition: use content-disposition npm module instead'); - -/** - * Parse accept params `str` returning an - * object with `.value`, `.quality` and `.params`. - * also includes `.originalIndex` for stable sorting - * - * @param {String} str - * @return {Object} - * @api private - */ - -function acceptParams(str, index) { - var parts = str.split(/ *; */); - var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; - - for (var i = 1; i < parts.length; ++i) { - var pms = parts[i].split(/ *= */); - if ('q' === pms[0]) { - ret.quality = parseFloat(pms[1]); - } else { - ret.params[pms[0]] = pms[1]; - } - } - - return ret; -} - -/** - * Compile "etag" value to function. - * - * @param {Boolean|String|Function} val - * @return {Function} - * @api private - */ - -exports.compileETag = function(val) { - var fn; - - if (typeof val === 'function') { - return val; - } - - switch (val) { - case true: - fn = exports.wetag; - break; - case false: - break; - case 'strong': - fn = exports.etag; - break; - case 'weak': - fn = exports.wetag; - break; - default: - throw new TypeError('unknown value for etag function: ' + val); - } - - return fn; -} - -/** - * Compile "query parser" value to function. - * - * @param {String|Function} val - * @return {Function} - * @api private - */ - -exports.compileQueryParser = function compileQueryParser(val) { - var fn; - - if (typeof val === 'function') { - return val; - } - - switch (val) { - case true: - fn = querystring.parse; - break; - case false: - fn = newObject; - break; - case 'extended': - fn = parseExtendedQueryString; - break; - case 'simple': - fn = querystring.parse; - break; - default: - throw new TypeError('unknown value for query parser function: ' + val); - } - - return fn; -} - -/** - * Compile "proxy trust" value to function. - * - * @param {Boolean|String|Number|Array|Function} val - * @return {Function} - * @api private - */ - -exports.compileTrust = function(val) { - if (typeof val === 'function') return val; - - if (val === true) { - // Support plain true/false - return function(){ return true }; - } - - if (typeof val === 'number') { - // Support trusting hop count - return function(a, i){ return i < val }; - } - - if (typeof val === 'string') { - // Support comma-separated values - val = val.split(/ *, */); - } - - return proxyaddr.compile(val || []); -} - -/** - * Set the charset in a given Content-Type string. - * - * @param {String} type - * @param {String} charset - * @return {String} - * @api private - */ - -exports.setCharset = function setCharset(type, charset) { - if (!type || !charset) { - return type; - } - - // parse type - var parsed = contentType.parse(type); - - // set charset - parsed.parameters.charset = charset; - - // format type - return contentType.format(parsed); -}; - -/** - * Create an ETag generator function, generating ETags with - * the given options. - * - * @param {object} options - * @return {function} - * @private - */ - -function createETagGenerator (options) { - return function generateETag (body, encoding) { - var buf = !Buffer.isBuffer(body) - ? Buffer.from(body, encoding) - : body - - return etag(buf, options) - } -} - -/** - * Parse an extended query string with qs. - * - * @return {Object} - * @private - */ - -function parseExtendedQueryString(str) { - return qs.parse(str, { - allowPrototypes: true - }); -} - -/** - * Return new empty object. - * - * @return {Object} - * @api private - */ - -function newObject() { - return {}; -} diff --git a/node_modules/express/lib/view.js b/node_modules/express/lib/view.js deleted file mode 100644 index cf101ca..0000000 --- a/node_modules/express/lib/view.js +++ /dev/null @@ -1,182 +0,0 @@ -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module dependencies. - * @private - */ - -var debug = require('debug')('express:view'); -var path = require('path'); -var fs = require('fs'); - -/** - * Module variables. - * @private - */ - -var dirname = path.dirname; -var basename = path.basename; -var extname = path.extname; -var join = path.join; -var resolve = path.resolve; - -/** - * Module exports. - * @public - */ - -module.exports = View; - -/** - * Initialize a new `View` with the given `name`. - * - * Options: - * - * - `defaultEngine` the default template engine name - * - `engines` template engine require() cache - * - `root` root path for view lookup - * - * @param {string} name - * @param {object} options - * @public - */ - -function View(name, options) { - var opts = options || {}; - - this.defaultEngine = opts.defaultEngine; - this.ext = extname(name); - this.name = name; - this.root = opts.root; - - if (!this.ext && !this.defaultEngine) { - throw new Error('No default engine was specified and no extension was provided.'); - } - - var fileName = name; - - if (!this.ext) { - // get extension from default engine name - this.ext = this.defaultEngine[0] !== '.' - ? '.' + this.defaultEngine - : this.defaultEngine; - - fileName += this.ext; - } - - if (!opts.engines[this.ext]) { - // load engine - var mod = this.ext.substr(1) - debug('require "%s"', mod) - - // default engine export - var fn = require(mod).__express - - if (typeof fn !== 'function') { - throw new Error('Module "' + mod + '" does not provide a view engine.') - } - - opts.engines[this.ext] = fn - } - - // store loaded engine - this.engine = opts.engines[this.ext]; - - // lookup path - this.path = this.lookup(fileName); -} - -/** - * Lookup view by the given `name` - * - * @param {string} name - * @private - */ - -View.prototype.lookup = function lookup(name) { - var path; - var roots = [].concat(this.root); - - debug('lookup "%s"', name); - - for (var i = 0; i < roots.length && !path; i++) { - var root = roots[i]; - - // resolve the path - var loc = resolve(root, name); - var dir = dirname(loc); - var file = basename(loc); - - // resolve the file - path = this.resolve(dir, file); - } - - return path; -}; - -/** - * Render with the given options. - * - * @param {object} options - * @param {function} callback - * @private - */ - -View.prototype.render = function render(options, callback) { - debug('render "%s"', this.path); - this.engine(this.path, options, callback); -}; - -/** - * Resolve the file within the given directory. - * - * @param {string} dir - * @param {string} file - * @private - */ - -View.prototype.resolve = function resolve(dir, file) { - var ext = this.ext; - - // . - var path = join(dir, file); - var stat = tryStat(path); - - if (stat && stat.isFile()) { - return path; - } - - // /index. - path = join(dir, basename(file, ext), 'index' + ext); - stat = tryStat(path); - - if (stat && stat.isFile()) { - return path; - } -}; - -/** - * Return a stat, maybe. - * - * @param {string} path - * @return {fs.Stats} - * @private - */ - -function tryStat(path) { - debug('stat "%s"', path); - - try { - return fs.statSync(path); - } catch (e) { - return undefined; - } -} diff --git a/node_modules/express/node_modules/debug/.coveralls.yml b/node_modules/express/node_modules/debug/.coveralls.yml deleted file mode 100644 index 20a7068..0000000 --- a/node_modules/express/node_modules/debug/.coveralls.yml +++ /dev/null @@ -1 +0,0 @@ -repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/express/node_modules/debug/.eslintrc b/node_modules/express/node_modules/debug/.eslintrc deleted file mode 100644 index 8a37ae2..0000000 --- a/node_modules/express/node_modules/debug/.eslintrc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "env": { - "browser": true, - "node": true - }, - "rules": { - "no-console": 0, - "no-empty": [1, { "allowEmptyCatch": true }] - }, - "extends": "eslint:recommended" -} diff --git a/node_modules/express/node_modules/debug/.npmignore b/node_modules/express/node_modules/debug/.npmignore deleted file mode 100644 index 5f60eec..0000000 --- a/node_modules/express/node_modules/debug/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -support -test -examples -example -*.sock -dist -yarn.lock -coverage -bower.json diff --git a/node_modules/express/node_modules/debug/.travis.yml b/node_modules/express/node_modules/debug/.travis.yml deleted file mode 100644 index 6c6090c..0000000 --- a/node_modules/express/node_modules/debug/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ - -language: node_js -node_js: - - "6" - - "5" - - "4" - -install: - - make node_modules - -script: - - make lint - - make test - - make coveralls diff --git a/node_modules/express/node_modules/debug/CHANGELOG.md b/node_modules/express/node_modules/debug/CHANGELOG.md deleted file mode 100644 index eadaa18..0000000 --- a/node_modules/express/node_modules/debug/CHANGELOG.md +++ /dev/null @@ -1,362 +0,0 @@ - -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/express/node_modules/debug/LICENSE b/node_modules/express/node_modules/debug/LICENSE deleted file mode 100644 index 658c933..0000000 --- a/node_modules/express/node_modules/debug/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -(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/express/node_modules/debug/Makefile b/node_modules/express/node_modules/debug/Makefile deleted file mode 100644 index 584da8b..0000000 --- a/node_modules/express/node_modules/debug/Makefile +++ /dev/null @@ -1,50 +0,0 @@ -# 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/express/node_modules/debug/README.md b/node_modules/express/node_modules/debug/README.md deleted file mode 100644 index f67be6b..0000000 --- a/node_modules/express/node_modules/debug/README.md +++ /dev/null @@ -1,312 +0,0 @@ -# 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/express/node_modules/debug/component.json b/node_modules/express/node_modules/debug/component.json deleted file mode 100644 index 9de2641..0000000 --- a/node_modules/express/node_modules/debug/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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/express/node_modules/debug/karma.conf.js b/node_modules/express/node_modules/debug/karma.conf.js deleted file mode 100644 index 103a82d..0000000 --- a/node_modules/express/node_modules/debug/karma.conf.js +++ /dev/null @@ -1,70 +0,0 @@ -// 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/express/node_modules/debug/node.js b/node_modules/express/node_modules/debug/node.js deleted file mode 100644 index 7fc36fe..0000000 --- a/node_modules/express/node_modules/debug/node.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./src/node'); diff --git a/node_modules/express/node_modules/debug/package.json b/node_modules/express/node_modules/debug/package.json deleted file mode 100644 index c676a0b..0000000 --- a/node_modules/express/node_modules/debug/package.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "_from": "debug@2.6.9", - "_id": "debug@2.6.9", - "_inBundle": false, - "_integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "_location": "/express/debug", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "debug@2.6.9", - "name": "debug", - "escapedName": "debug", - "rawSpec": "2.6.9", - "saveSpec": null, - "fetchSpec": "2.6.9" - }, - "_requiredBy": [ - "/express" - ], - "_resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "_shasum": "5d128515df134ff327e90a4c93f4e077a536341f", - "_spec": "debug@2.6.9", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "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/express/node_modules/debug/src/browser.js b/node_modules/express/node_modules/debug/src/browser.js deleted file mode 100644 index 7106924..0000000 --- a/node_modules/express/node_modules/debug/src/browser.js +++ /dev/null @@ -1,185 +0,0 @@ -/** - * 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/express/node_modules/debug/src/debug.js b/node_modules/express/node_modules/debug/src/debug.js deleted file mode 100644 index 6a5e3fc..0000000 --- a/node_modules/express/node_modules/debug/src/debug.js +++ /dev/null @@ -1,202 +0,0 @@ - -/** - * 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/express/node_modules/debug/src/index.js b/node_modules/express/node_modules/debug/src/index.js deleted file mode 100644 index e12cf4d..0000000 --- a/node_modules/express/node_modules/debug/src/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/** - * 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/express/node_modules/debug/src/inspector-log.js b/node_modules/express/node_modules/debug/src/inspector-log.js deleted file mode 100644 index 60ea6c0..0000000 --- a/node_modules/express/node_modules/debug/src/inspector-log.js +++ /dev/null @@ -1,15 +0,0 @@ -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/express/node_modules/debug/src/node.js b/node_modules/express/node_modules/debug/src/node.js deleted file mode 100644 index b15109c..0000000 --- a/node_modules/express/node_modules/debug/src/node.js +++ /dev/null @@ -1,248 +0,0 @@ -/** - * 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/express/node_modules/ms/index.js b/node_modules/express/node_modules/ms/index.js deleted file mode 100644 index 6a522b1..0000000 --- a/node_modules/express/node_modules/ms/index.js +++ /dev/null @@ -1,152 +0,0 @@ -/** - * 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/express/node_modules/ms/license.md b/node_modules/express/node_modules/ms/license.md deleted file mode 100644 index 69b6125..0000000 --- a/node_modules/express/node_modules/ms/license.md +++ /dev/null @@ -1,21 +0,0 @@ -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/express/node_modules/ms/package.json b/node_modules/express/node_modules/ms/package.json deleted file mode 100644 index 4066597..0000000 --- a/node_modules/express/node_modules/ms/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "ms@2.0.0", - "_id": "ms@2.0.0", - "_inBundle": false, - "_integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "_location": "/express/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": [ - "/express/debug" - ], - "_resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "_shasum": "5608aeadfc00be6c2901df5f9861788de0d597c8", - "_spec": "ms@2.0.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express/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/express/node_modules/ms/readme.md b/node_modules/express/node_modules/ms/readme.md deleted file mode 100644 index 84a9974..0000000 --- a/node_modules/express/node_modules/ms/readme.md +++ /dev/null @@ -1,51 +0,0 @@ -# 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/express/node_modules/safe-buffer/LICENSE b/node_modules/express/node_modules/safe-buffer/LICENSE deleted file mode 100644 index 0c068ce..0000000 --- a/node_modules/express/node_modules/safe-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -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/express/node_modules/safe-buffer/README.md b/node_modules/express/node_modules/safe-buffer/README.md deleted file mode 100644 index e9a81af..0000000 --- a/node_modules/express/node_modules/safe-buffer/README.md +++ /dev/null @@ -1,584 +0,0 @@ -# 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/express/node_modules/safe-buffer/index.d.ts b/node_modules/express/node_modules/safe-buffer/index.d.ts deleted file mode 100644 index e9fed80..0000000 --- a/node_modules/express/node_modules/safe-buffer/index.d.ts +++ /dev/null @@ -1,187 +0,0 @@ -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/express/node_modules/safe-buffer/index.js b/node_modules/express/node_modules/safe-buffer/index.js deleted file mode 100644 index 22438da..0000000 --- a/node_modules/express/node_modules/safe-buffer/index.js +++ /dev/null @@ -1,62 +0,0 @@ -/* 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/express/node_modules/safe-buffer/package.json b/node_modules/express/node_modules/safe-buffer/package.json deleted file mode 100644 index ae939e6..0000000 --- a/node_modules/express/node_modules/safe-buffer/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "_from": "safe-buffer@5.1.2", - "_id": "safe-buffer@5.1.2", - "_inBundle": false, - "_integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "_location": "/express/safe-buffer", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "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": [ - "/express" - ], - "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "_shasum": "991ec69d296e0313747d59bdfd2b745c35f8828d", - "_spec": "safe-buffer@5.1.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "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/express/package.json b/node_modules/express/package.json deleted file mode 100644 index 59a425c..0000000 --- a/node_modules/express/package.json +++ /dev/null @@ -1,154 +0,0 @@ -{ - "_from": "express@^4.17.1", - "_id": "express@4.17.1", - "_inBundle": false, - "_integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==", - "_location": "/express", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "express@^4.17.1", - "name": "express", - "escapedName": "express", - "rawSpec": "^4.17.1", - "saveSpec": null, - "fetchSpec": "^4.17.1" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz", - "_shasum": "4491fc38605cf51f8629d39c2b5d026f98a4c134", - "_spec": "express@^4.17.1", - "_where": "/Users/kai/Desktop/node-course/dbproject", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "bugs": { - "url": "https://github.com/expressjs/express/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - { - "name": "Ciaran Jessup", - "email": "ciaranj@gmail.com" - }, - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "Guillermo Rauch", - "email": "rauchg@gmail.com" - }, - { - "name": "Jonathan Ong", - "email": "me@jongleberry.com" - }, - { - "name": "Roman Shtylman", - "email": "shtylman+expressjs@gmail.com" - }, - { - "name": "Young Jae Sim", - "email": "hanul@hanul.me" - } - ], - "dependencies": { - "accepts": "~1.3.7", - "array-flatten": "1.1.1", - "body-parser": "1.19.0", - "content-disposition": "0.5.3", - "content-type": "~1.0.4", - "cookie": "0.4.0", - "cookie-signature": "1.0.6", - "debug": "2.6.9", - "depd": "~1.1.2", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "~1.1.2", - "fresh": "0.5.2", - "merge-descriptors": "1.0.1", - "methods": "~1.1.2", - "on-finished": "~2.3.0", - "parseurl": "~1.3.3", - "path-to-regexp": "0.1.7", - "proxy-addr": "~2.0.5", - "qs": "6.7.0", - "range-parser": "~1.2.1", - "safe-buffer": "5.1.2", - "send": "0.17.1", - "serve-static": "1.14.1", - "setprototypeof": "1.1.1", - "statuses": "~1.5.0", - "type-is": "~1.6.18", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - }, - "deprecated": false, - "description": "Fast, unopinionated, minimalist web framework", - "devDependencies": { - "after": "0.8.2", - "connect-redis": "3.4.1", - "cookie-parser": "~1.4.4", - "cookie-session": "1.3.3", - "ejs": "2.6.1", - "eslint": "2.13.1", - "express-session": "1.16.1", - "hbs": "4.0.4", - "istanbul": "0.4.5", - "marked": "0.6.2", - "method-override": "3.0.0", - "mocha": "5.2.0", - "morgan": "1.9.1", - "multiparty": "4.2.1", - "pbkdf2-password": "1.2.1", - "should": "13.2.3", - "supertest": "3.3.0", - "vhost": "~3.0.2" - }, - "engines": { - "node": ">= 0.10.0" - }, - "files": [ - "LICENSE", - "History.md", - "Readme.md", - "index.js", - "lib/" - ], - "homepage": "http://expressjs.com/", - "keywords": [ - "express", - "framework", - "sinatra", - "web", - "rest", - "restful", - "router", - "app", - "api" - ], - "license": "MIT", - "name": "express", - "repository": { - "type": "git", - "url": "git+https://github.com/expressjs/express.git" - }, - "scripts": { - "lint": "eslint .", - "test": "mocha --require test/support/env --reporter spec --bail --check-leaks test/ test/acceptance/", - "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/ test/acceptance/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/ test/acceptance/", - "test-tap": "mocha --require test/support/env --reporter tap --check-leaks test/ test/acceptance/" - }, - "version": "4.17.1" -} diff --git a/node_modules/file-uri-to-path/.npmignore b/node_modules/file-uri-to-path/.npmignore deleted file mode 100644 index 07e6e47..0000000 --- a/node_modules/file-uri-to-path/.npmignore +++ /dev/null @@ -1 +0,0 @@ -/node_modules diff --git a/node_modules/file-uri-to-path/.travis.yml b/node_modules/file-uri-to-path/.travis.yml deleted file mode 100644 index 016bb6e..0000000 --- a/node_modules/file-uri-to-path/.travis.yml +++ /dev/null @@ -1,30 +0,0 @@ -sudo: false - -language: node_js - -node_js: - - "0.8" - - "0.10" - - "0.12" - - "1" - - "2" - - "3" - - "4" - - "5" - - "6" - - "7" - - "8" - -install: - - PATH="`npm bin`:`npm bin -g`:$PATH" - # Node 0.8 comes with a too obsolete npm - - if [[ "`node --version`" =~ ^v0\.8\. ]]; then npm install -g npm@1.4.28 ; fi - # Install dependencies and build - - npm install - -script: - # Output useful info for debugging - - node --version - - npm --version - # Run tests - - npm test diff --git a/node_modules/file-uri-to-path/History.md b/node_modules/file-uri-to-path/History.md deleted file mode 100644 index c8682be..0000000 --- a/node_modules/file-uri-to-path/History.md +++ /dev/null @@ -1,21 +0,0 @@ - -1.0.0 / 2017-07-06 -================== - - * update "mocha" to v3 - * fixed unicode URI decoding (#6) - * add typings for Typescript - * README: use SVG Travis-CI badge - * add LICENSE file (MIT) - * add .travis.yml file (testing Node.js 0.8 through 8 currently) - * add README.md file - -0.0.2 / 2014-01-27 -================== - - * index: invert the path separators on Windows - -0.0.1 / 2014-01-27 -================== - - * initial commit diff --git a/node_modules/file-uri-to-path/LICENSE b/node_modules/file-uri-to-path/LICENSE deleted file mode 100644 index e1af783..0000000 --- a/node_modules/file-uri-to-path/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2014 Nathan Rajlich - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/file-uri-to-path/README.md b/node_modules/file-uri-to-path/README.md deleted file mode 100644 index ab30be8..0000000 --- a/node_modules/file-uri-to-path/README.md +++ /dev/null @@ -1,74 +0,0 @@ -file-uri-to-path -================ -### Convert a `file:` URI to a file path -[![Build Status](https://travis-ci.org/TooTallNate/file-uri-to-path.svg?branch=master)](https://travis-ci.org/TooTallNate/file-uri-to-path) - -Accepts a `file:` URI and returns a regular file path suitable for use with the -`fs` module functions. - - -Installation ------------- - -Install with `npm`: - -``` bash -$ npm install file-uri-to-path -``` - - -Example -------- - -``` js -var uri2path = require('file-uri-to-path'); - -uri2path('file://localhost/c|/WINDOWS/clock.avi'); -// "c:\\WINDOWS\\clock.avi" - -uri2path('file:///c|/WINDOWS/clock.avi'); -// "c:\\WINDOWS\\clock.avi" - -uri2path('file://localhost/c:/WINDOWS/clock.avi'); -// "c:\\WINDOWS\\clock.avi" - -uri2path('file://hostname/path/to/the%20file.txt'); -// "\\\\hostname\\path\\to\\the file.txt" - -uri2path('file:///c:/path/to/the%20file.txt'); -// "c:\\path\\to\\the file.txt" -``` - - -API ---- - -### fileUriToPath(String uri) → String - - - -License -------- - -(The MIT License) - -Copyright (c) 2014 Nathan Rajlich <nathan@tootallnate.net> - -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/file-uri-to-path/index.d.ts b/node_modules/file-uri-to-path/index.d.ts deleted file mode 100644 index 99dc3f9..0000000 --- a/node_modules/file-uri-to-path/index.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare function fileUriToPath(uri: string): string; -export = fileUriToPath; diff --git a/node_modules/file-uri-to-path/index.js b/node_modules/file-uri-to-path/index.js deleted file mode 100644 index 48cb280..0000000 --- a/node_modules/file-uri-to-path/index.js +++ /dev/null @@ -1,66 +0,0 @@ - -/** - * Module dependencies. - */ - -var sep = require('path').sep || '/'; - -/** - * Module exports. - */ - -module.exports = fileUriToPath; - -/** - * File URI to Path function. - * - * @param {String} uri - * @return {String} path - * @api public - */ - -function fileUriToPath (uri) { - if ('string' != typeof uri || - uri.length <= 7 || - 'file://' != uri.substring(0, 7)) { - throw new TypeError('must pass in a file:// URI to convert to a file path'); - } - - var rest = decodeURI(uri.substring(7)); - var firstSlash = rest.indexOf('/'); - var host = rest.substring(0, firstSlash); - var path = rest.substring(firstSlash + 1); - - // 2. Scheme Definition - // As a special case, can be the string "localhost" or the empty - // string; this is interpreted as "the machine from which the URL is - // being interpreted". - if ('localhost' == host) host = ''; - - if (host) { - host = sep + sep + host; - } - - // 3.2 Drives, drive letters, mount points, file system root - // Drive letters are mapped into the top of a file URI in various ways, - // depending on the implementation; some applications substitute - // vertical bar ("|") for the colon after the drive letter, yielding - // "file:///c|/tmp/test.txt". In some cases, the colon is left - // unchanged, as in "file:///c:/tmp/test.txt". In other cases, the - // colon is simply omitted, as in "file:///c/tmp/test.txt". - path = path.replace(/^(.+)\|/, '$1:'); - - // for Windows, we need to invert the path separators from what a URI uses - if (sep == '\\') { - path = path.replace(/\//g, '\\'); - } - - if (/^.+\:/.test(path)) { - // has Windows drive at beginning of path - } else { - // unix path… - path = sep + path; - } - - return host + path; -} diff --git a/node_modules/file-uri-to-path/package.json b/node_modules/file-uri-to-path/package.json deleted file mode 100644 index 9816bf0..0000000 --- a/node_modules/file-uri-to-path/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "_from": "file-uri-to-path@1.0.0", - "_id": "file-uri-to-path@1.0.0", - "_inBundle": false, - "_integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", - "_location": "/file-uri-to-path", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "file-uri-to-path@1.0.0", - "name": "file-uri-to-path", - "escapedName": "file-uri-to-path", - "rawSpec": "1.0.0", - "saveSpec": null, - "fetchSpec": "1.0.0" - }, - "_requiredBy": [ - "/bindings" - ], - "_resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", - "_shasum": "553a7b8446ff6f684359c445f1e37a05dacc33dd", - "_spec": "file-uri-to-path@1.0.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/bindings", - "author": { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net", - "url": "http://n8.io/" - }, - "bugs": { - "url": "https://github.com/TooTallNate/file-uri-to-path/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Convert a file: URI to a file path", - "devDependencies": { - "mocha": "3" - }, - "directories": { - "test": "test" - }, - "homepage": "https://github.com/TooTallNate/file-uri-to-path", - "keywords": [ - "file", - "uri", - "convert", - "path" - ], - "license": "MIT", - "main": "index.js", - "name": "file-uri-to-path", - "repository": { - "type": "git", - "url": "git://github.com/TooTallNate/file-uri-to-path.git" - }, - "scripts": { - "test": "mocha --reporter spec" - }, - "types": "index.d.ts", - "version": "1.0.0" -} diff --git a/node_modules/file-uri-to-path/test/test.js b/node_modules/file-uri-to-path/test/test.js deleted file mode 100644 index 79305dc..0000000 --- a/node_modules/file-uri-to-path/test/test.js +++ /dev/null @@ -1,24 +0,0 @@ - -var sep = require('path').sep || '/'; -var assert = require('assert'); -var uri2path = require('../'); -var tests = require('./tests.json'); - -describe('file-uri-to-path', function () { - - Object.keys(tests).forEach(function (uri) { - - // the test cases were generated from Windows' PathCreateFromUrlA() function. - // On Unix, we have to replace the path separator with the Unix one instead of - // the Windows one. - var expected = tests[uri].replace(/\\/g, sep); - - it('should convert ' + JSON.stringify(uri) + ' to ' + JSON.stringify(expected), - function () { - var actual = uri2path(uri); - assert.equal(actual, expected); - }); - - }); - -}); diff --git a/node_modules/file-uri-to-path/test/tests.json b/node_modules/file-uri-to-path/test/tests.json deleted file mode 100644 index b935a63..0000000 --- a/node_modules/file-uri-to-path/test/tests.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "file://host/path": "\\\\host\\path", - "file://localhost/etc/fstab": "\\etc\\fstab", - "file:///etc/fstab": "\\etc\\fstab", - "file:///c:/WINDOWS/clock.avi": "c:\\WINDOWS\\clock.avi", - "file://localhost/c|/WINDOWS/clock.avi": "c:\\WINDOWS\\clock.avi", - "file:///c|/WINDOWS/clock.avi": "c:\\WINDOWS\\clock.avi", - "file://localhost/c:/WINDOWS/clock.avi": "c:\\WINDOWS\\clock.avi", - "file://hostname/path/to/the%20file.txt": "\\\\hostname\\path\\to\\the file.txt", - "file:///c:/path/to/the%20file.txt": "c:\\path\\to\\the file.txt", - "file:///C:/Documents%20and%20Settings/davris/FileSchemeURIs.doc": "C:\\Documents and Settings\\davris\\FileSchemeURIs.doc", - "file:///C:/caf%C3%A9/%C3%A5r/d%C3%BCnn/%E7%89%9B%E9%93%83/Ph%E1%BB%9F/%F0%9F%98%B5.exe": "C:\\café\\år\\dünn\\牛铃\\Phở\\😵.exe" -} diff --git a/node_modules/finalhandler/HISTORY.md b/node_modules/finalhandler/HISTORY.md deleted file mode 100644 index 920c35e..0000000 --- a/node_modules/finalhandler/HISTORY.md +++ /dev/null @@ -1,187 +0,0 @@ -1.1.2 / 2019-05-09 -================== - - * Set stricter `Content-Security-Policy` header - * deps: parseurl@~1.3.3 - * deps: statuses@~1.5.0 - -1.1.1 / 2018-03-06 -================== - - * Fix 404 output for bad / missing pathnames - * deps: encodeurl@~1.0.2 - - Fix encoding `%` as last character - * deps: statuses@~1.4.0 - -1.1.0 / 2017-09-24 -================== - - * Use `res.headersSent` when available - -1.0.6 / 2017-09-22 -================== - - * deps: debug@2.6.9 - -1.0.5 / 2017-09-15 -================== - - * deps: parseurl@~1.3.2 - - perf: reduce overhead for full URLs - - perf: unroll the "fast-path" `RegExp` - -1.0.4 / 2017-08-03 -================== - - * deps: debug@2.6.8 - -1.0.3 / 2017-05-16 -================== - - * deps: debug@2.6.7 - - deps: ms@2.0.0 - -1.0.2 / 2017-04-22 -================== - - * deps: debug@2.6.4 - - deps: ms@0.7.3 - -1.0.1 / 2017-03-21 -================== - - * Fix missing `` in HTML document - * deps: debug@2.6.3 - - Fix: `DEBUG_MAX_ARRAY_LENGTH` - -1.0.0 / 2017-02-15 -================== - - * Fix exception when `err` cannot be converted to a string - * Fully URL-encode the pathname in the 404 message - * Only include the pathname in the 404 message - * Send complete HTML document - * Set `Content-Security-Policy: default-src 'self'` header - * deps: debug@2.6.1 - - Allow colors in workers - - Deprecated `DEBUG_FD` environment variable set to `3` or higher - - Fix error when running under React Native - - Use same color for same namespace - - deps: ms@0.7.2 - -0.5.1 / 2016-11-12 -================== - - * Fix exception when `err.headers` is not an object - * deps: statuses@~1.3.1 - * perf: hoist regular expressions - * perf: remove duplicate validation path - -0.5.0 / 2016-06-15 -================== - - * Change invalid or non-numeric status code to 500 - * Overwrite status message to match set status code - * Prefer `err.statusCode` if `err.status` is invalid - * Set response headers from `err.headers` object - * Use `statuses` instead of `http` module for status messages - - Includes all defined status messages - -0.4.1 / 2015-12-02 -================== - - * deps: escape-html@~1.0.3 - - perf: enable strict mode - - perf: optimize string replacement - - perf: use faster string coercion - -0.4.0 / 2015-06-14 -================== - - * Fix a false-positive when unpiping in Node.js 0.8 - * Support `statusCode` property on `Error` objects - * Use `unpipe` module for unpiping requests - * deps: escape-html@1.0.2 - * deps: on-finished@~2.3.0 - - Add defined behavior for HTTP `CONNECT` requests - - Add defined behavior for HTTP `Upgrade` requests - - deps: ee-first@1.1.1 - * perf: enable strict mode - * perf: remove argument reassignment - -0.3.6 / 2015-05-11 -================== - - * deps: debug@~2.2.0 - - deps: ms@0.7.1 - -0.3.5 / 2015-04-22 -================== - - * deps: on-finished@~2.2.1 - - Fix `isFinished(req)` when data buffered - -0.3.4 / 2015-03-15 -================== - - * deps: debug@~2.1.3 - - Fix high intensity foreground color for bold - - deps: ms@0.7.0 - -0.3.3 / 2015-01-01 -================== - - * deps: debug@~2.1.1 - * deps: on-finished@~2.2.0 - -0.3.2 / 2014-10-22 -================== - - * deps: on-finished@~2.1.1 - - Fix handling of pipelined requests - -0.3.1 / 2014-10-16 -================== - - * deps: debug@~2.1.0 - - Implement `DEBUG_FD` env variable support - -0.3.0 / 2014-09-17 -================== - - * Terminate in progress response only on error - * Use `on-finished` to determine request status - -0.2.0 / 2014-09-03 -================== - - * Set `X-Content-Type-Options: nosniff` header - * deps: debug@~2.0.0 - -0.1.0 / 2014-07-16 -================== - - * Respond after request fully read - - prevents hung responses and socket hang ups - * deps: debug@1.0.4 - -0.0.3 / 2014-07-11 -================== - - * deps: debug@1.0.3 - - Add support for multiple wildcards in namespaces - -0.0.2 / 2014-06-19 -================== - - * Handle invalid status codes - -0.0.1 / 2014-06-05 -================== - - * deps: debug@1.0.2 - -0.0.0 / 2014-06-05 -================== - - * Extracted from connect/express diff --git a/node_modules/finalhandler/LICENSE b/node_modules/finalhandler/LICENSE deleted file mode 100644 index fb30982..0000000 --- a/node_modules/finalhandler/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2014-2017 Douglas Christopher Wilson - -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/finalhandler/README.md b/node_modules/finalhandler/README.md deleted file mode 100644 index 96327f0..0000000 --- a/node_modules/finalhandler/README.md +++ /dev/null @@ -1,148 +0,0 @@ -# finalhandler - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Node.js Version][node-image]][node-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Node.js function to invoke as the final step to respond to HTTP request. - -## Installation - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install finalhandler -``` - -## API - - - -```js -var finalhandler = require('finalhandler') -``` - -### finalhandler(req, res, [options]) - -Returns function to be invoked as the final step for the given `req` and `res`. -This function is to be invoked as `fn(err)`. If `err` is falsy, the handler will -write out a 404 response to the `res`. If it is truthy, an error response will -be written out to the `res`. - -When an error is written, the following information is added to the response: - - * The `res.statusCode` is set from `err.status` (or `err.statusCode`). If - this value is outside the 4xx or 5xx range, it will be set to 500. - * The `res.statusMessage` is set according to the status code. - * The body will be the HTML of the status code message if `env` is - `'production'`, otherwise will be `err.stack`. - * Any headers specified in an `err.headers` object. - -The final handler will also unpipe anything from `req` when it is invoked. - -#### options.env - -By default, the environment is determined by `NODE_ENV` variable, but it can be -overridden by this option. - -#### options.onerror - -Provide a function to be called with the `err` when it exists. Can be used for -writing errors to a central location without excessive function generation. Called -as `onerror(err, req, res)`. - -## Examples - -### always 404 - -```js -var finalhandler = require('finalhandler') -var http = require('http') - -var server = http.createServer(function (req, res) { - var done = finalhandler(req, res) - done() -}) - -server.listen(3000) -``` - -### perform simple action - -```js -var finalhandler = require('finalhandler') -var fs = require('fs') -var http = require('http') - -var server = http.createServer(function (req, res) { - var done = finalhandler(req, res) - - fs.readFile('index.html', function (err, buf) { - if (err) return done(err) - res.setHeader('Content-Type', 'text/html') - res.end(buf) - }) -}) - -server.listen(3000) -``` - -### use with middleware-style functions - -```js -var finalhandler = require('finalhandler') -var http = require('http') -var serveStatic = require('serve-static') - -var serve = serveStatic('public') - -var server = http.createServer(function (req, res) { - var done = finalhandler(req, res) - serve(req, res, done) -}) - -server.listen(3000) -``` - -### keep log of all errors - -```js -var finalhandler = require('finalhandler') -var fs = require('fs') -var http = require('http') - -var server = http.createServer(function (req, res) { - var done = finalhandler(req, res, { onerror: logerror }) - - fs.readFile('index.html', function (err, buf) { - if (err) return done(err) - res.setHeader('Content-Type', 'text/html') - res.end(buf) - }) -}) - -server.listen(3000) - -function logerror (err) { - console.error(err.stack || err.toString()) -} -``` - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/finalhandler.svg -[npm-url]: https://npmjs.org/package/finalhandler -[node-image]: https://img.shields.io/node/v/finalhandler.svg -[node-url]: https://nodejs.org/en/download -[travis-image]: https://img.shields.io/travis/pillarjs/finalhandler.svg -[travis-url]: https://travis-ci.org/pillarjs/finalhandler -[coveralls-image]: https://img.shields.io/coveralls/pillarjs/finalhandler.svg -[coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master -[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg -[downloads-url]: https://npmjs.org/package/finalhandler diff --git a/node_modules/finalhandler/index.js b/node_modules/finalhandler/index.js deleted file mode 100644 index 5673507..0000000 --- a/node_modules/finalhandler/index.js +++ /dev/null @@ -1,331 +0,0 @@ -/*! - * finalhandler - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var debug = require('debug')('finalhandler') -var encodeUrl = require('encodeurl') -var escapeHtml = require('escape-html') -var onFinished = require('on-finished') -var parseUrl = require('parseurl') -var statuses = require('statuses') -var unpipe = require('unpipe') - -/** - * Module variables. - * @private - */ - -var DOUBLE_SPACE_REGEXP = /\x20{2}/g -var NEWLINE_REGEXP = /\n/g - -/* istanbul ignore next */ -var defer = typeof setImmediate === 'function' - ? setImmediate - : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } -var isFinished = onFinished.isFinished - -/** - * Create a minimal HTML document. - * - * @param {string} message - * @private - */ - -function createHtmlDocument (message) { - var body = escapeHtml(message) - .replace(NEWLINE_REGEXP, '
') - .replace(DOUBLE_SPACE_REGEXP, '  ') - - return '\n' + - '\n' + - '\n' + - '\n' + - 'Error\n' + - '\n' + - '\n' + - '
' + body + '
\n' + - '\n' + - '\n' -} - -/** - * Module exports. - * @public - */ - -module.exports = finalhandler - -/** - * Create a function to handle the final response. - * - * @param {Request} req - * @param {Response} res - * @param {Object} [options] - * @return {Function} - * @public - */ - -function finalhandler (req, res, options) { - var opts = options || {} - - // get environment - var env = opts.env || process.env.NODE_ENV || 'development' - - // get error callback - var onerror = opts.onerror - - return function (err) { - var headers - var msg - var status - - // ignore 404 on in-flight response - if (!err && headersSent(res)) { - debug('cannot 404 after headers sent') - return - } - - // unhandled error - if (err) { - // respect status code from error - status = getErrorStatusCode(err) - - if (status === undefined) { - // fallback to status code on response - status = getResponseStatusCode(res) - } else { - // respect headers from error - headers = getErrorHeaders(err) - } - - // get error message - msg = getErrorMessage(err, status, env) - } else { - // not found - status = 404 - msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) - } - - debug('default %s', status) - - // schedule onerror callback - if (err && onerror) { - defer(onerror, err, req, res) - } - - // cannot actually respond - if (headersSent(res)) { - debug('cannot %d after headers sent', status) - req.socket.destroy() - return - } - - // send response - send(req, res, status, headers, msg) - } -} - -/** - * Get headers from Error object. - * - * @param {Error} err - * @return {object} - * @private - */ - -function getErrorHeaders (err) { - if (!err.headers || typeof err.headers !== 'object') { - return undefined - } - - var headers = Object.create(null) - var keys = Object.keys(err.headers) - - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - headers[key] = err.headers[key] - } - - return headers -} - -/** - * Get message from Error object, fallback to status message. - * - * @param {Error} err - * @param {number} status - * @param {string} env - * @return {string} - * @private - */ - -function getErrorMessage (err, status, env) { - var msg - - if (env !== 'production') { - // use err.stack, which typically includes err.message - msg = err.stack - - // fallback to err.toString() when possible - if (!msg && typeof err.toString === 'function') { - msg = err.toString() - } - } - - return msg || statuses[status] -} - -/** - * Get status code from Error object. - * - * @param {Error} err - * @return {number} - * @private - */ - -function getErrorStatusCode (err) { - // check err.status - if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { - return err.status - } - - // check err.statusCode - if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { - return err.statusCode - } - - return undefined -} - -/** - * Get resource name for the request. - * - * This is typically just the original pathname of the request - * but will fallback to "resource" is that cannot be determined. - * - * @param {IncomingMessage} req - * @return {string} - * @private - */ - -function getResourceName (req) { - try { - return parseUrl.original(req).pathname - } catch (e) { - return 'resource' - } -} - -/** - * Get status code from response. - * - * @param {OutgoingMessage} res - * @return {number} - * @private - */ - -function getResponseStatusCode (res) { - var status = res.statusCode - - // default status code to 500 if outside valid range - if (typeof status !== 'number' || status < 400 || status > 599) { - status = 500 - } - - return status -} - -/** - * Determine if the response headers have been sent. - * - * @param {object} res - * @returns {boolean} - * @private - */ - -function headersSent (res) { - return typeof res.headersSent !== 'boolean' - ? Boolean(res._header) - : res.headersSent -} - -/** - * Send response. - * - * @param {IncomingMessage} req - * @param {OutgoingMessage} res - * @param {number} status - * @param {object} headers - * @param {string} message - * @private - */ - -function send (req, res, status, headers, message) { - function write () { - // response body - var body = createHtmlDocument(message) - - // response status - res.statusCode = status - res.statusMessage = statuses[status] - - // response headers - setHeaders(res, headers) - - // security headers - res.setHeader('Content-Security-Policy', "default-src 'none'") - res.setHeader('X-Content-Type-Options', 'nosniff') - - // standard headers - res.setHeader('Content-Type', 'text/html; charset=utf-8') - res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) - - if (req.method === 'HEAD') { - res.end() - return - } - - res.end(body, 'utf8') - } - - if (isFinished(req)) { - write() - return - } - - // unpipe everything from the request - unpipe(req) - - // flush the request - onFinished(req, write) - req.resume() -} - -/** - * Set response headers from an object. - * - * @param {OutgoingMessage} res - * @param {object} headers - * @private - */ - -function setHeaders (res, headers) { - if (!headers) { - return - } - - var keys = Object.keys(headers) - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - res.setHeader(key, headers[key]) - } -} diff --git a/node_modules/finalhandler/node_modules/debug/.coveralls.yml b/node_modules/finalhandler/node_modules/debug/.coveralls.yml deleted file mode 100644 index 20a7068..0000000 --- a/node_modules/finalhandler/node_modules/debug/.coveralls.yml +++ /dev/null @@ -1 +0,0 @@ -repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/finalhandler/node_modules/debug/.eslintrc b/node_modules/finalhandler/node_modules/debug/.eslintrc deleted file mode 100644 index 8a37ae2..0000000 --- a/node_modules/finalhandler/node_modules/debug/.eslintrc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "env": { - "browser": true, - "node": true - }, - "rules": { - "no-console": 0, - "no-empty": [1, { "allowEmptyCatch": true }] - }, - "extends": "eslint:recommended" -} diff --git a/node_modules/finalhandler/node_modules/debug/.npmignore b/node_modules/finalhandler/node_modules/debug/.npmignore deleted file mode 100644 index 5f60eec..0000000 --- a/node_modules/finalhandler/node_modules/debug/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -support -test -examples -example -*.sock -dist -yarn.lock -coverage -bower.json diff --git a/node_modules/finalhandler/node_modules/debug/.travis.yml b/node_modules/finalhandler/node_modules/debug/.travis.yml deleted file mode 100644 index 6c6090c..0000000 --- a/node_modules/finalhandler/node_modules/debug/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ - -language: node_js -node_js: - - "6" - - "5" - - "4" - -install: - - make node_modules - -script: - - make lint - - make test - - make coveralls diff --git a/node_modules/finalhandler/node_modules/debug/CHANGELOG.md b/node_modules/finalhandler/node_modules/debug/CHANGELOG.md deleted file mode 100644 index eadaa18..0000000 --- a/node_modules/finalhandler/node_modules/debug/CHANGELOG.md +++ /dev/null @@ -1,362 +0,0 @@ - -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/finalhandler/node_modules/debug/LICENSE b/node_modules/finalhandler/node_modules/debug/LICENSE deleted file mode 100644 index 658c933..0000000 --- a/node_modules/finalhandler/node_modules/debug/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -(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/finalhandler/node_modules/debug/Makefile b/node_modules/finalhandler/node_modules/debug/Makefile deleted file mode 100644 index 584da8b..0000000 --- a/node_modules/finalhandler/node_modules/debug/Makefile +++ /dev/null @@ -1,50 +0,0 @@ -# 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/finalhandler/node_modules/debug/README.md b/node_modules/finalhandler/node_modules/debug/README.md deleted file mode 100644 index f67be6b..0000000 --- a/node_modules/finalhandler/node_modules/debug/README.md +++ /dev/null @@ -1,312 +0,0 @@ -# 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/finalhandler/node_modules/debug/component.json b/node_modules/finalhandler/node_modules/debug/component.json deleted file mode 100644 index 9de2641..0000000 --- a/node_modules/finalhandler/node_modules/debug/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "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/finalhandler/node_modules/debug/karma.conf.js b/node_modules/finalhandler/node_modules/debug/karma.conf.js deleted file mode 100644 index 103a82d..0000000 --- a/node_modules/finalhandler/node_modules/debug/karma.conf.js +++ /dev/null @@ -1,70 +0,0 @@ -// 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/finalhandler/node_modules/debug/node.js b/node_modules/finalhandler/node_modules/debug/node.js deleted file mode 100644 index 7fc36fe..0000000 --- a/node_modules/finalhandler/node_modules/debug/node.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./src/node'); diff --git a/node_modules/finalhandler/node_modules/debug/package.json b/node_modules/finalhandler/node_modules/debug/package.json deleted file mode 100644 index 2ab425d..0000000 --- a/node_modules/finalhandler/node_modules/debug/package.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "_from": "debug@2.6.9", - "_id": "debug@2.6.9", - "_inBundle": false, - "_integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "_location": "/finalhandler/debug", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "debug@2.6.9", - "name": "debug", - "escapedName": "debug", - "rawSpec": "2.6.9", - "saveSpec": null, - "fetchSpec": "2.6.9" - }, - "_requiredBy": [ - "/finalhandler" - ], - "_resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "_shasum": "5d128515df134ff327e90a4c93f4e077a536341f", - "_spec": "debug@2.6.9", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/finalhandler", - "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/finalhandler/node_modules/debug/src/browser.js b/node_modules/finalhandler/node_modules/debug/src/browser.js deleted file mode 100644 index 7106924..0000000 --- a/node_modules/finalhandler/node_modules/debug/src/browser.js +++ /dev/null @@ -1,185 +0,0 @@ -/** - * 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/finalhandler/node_modules/debug/src/debug.js b/node_modules/finalhandler/node_modules/debug/src/debug.js deleted file mode 100644 index 6a5e3fc..0000000 --- a/node_modules/finalhandler/node_modules/debug/src/debug.js +++ /dev/null @@ -1,202 +0,0 @@ - -/** - * 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/finalhandler/node_modules/debug/src/index.js b/node_modules/finalhandler/node_modules/debug/src/index.js deleted file mode 100644 index e12cf4d..0000000 --- a/node_modules/finalhandler/node_modules/debug/src/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/** - * 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/finalhandler/node_modules/debug/src/inspector-log.js b/node_modules/finalhandler/node_modules/debug/src/inspector-log.js deleted file mode 100644 index 60ea6c0..0000000 --- a/node_modules/finalhandler/node_modules/debug/src/inspector-log.js +++ /dev/null @@ -1,15 +0,0 @@ -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/finalhandler/node_modules/debug/src/node.js b/node_modules/finalhandler/node_modules/debug/src/node.js deleted file mode 100644 index b15109c..0000000 --- a/node_modules/finalhandler/node_modules/debug/src/node.js +++ /dev/null @@ -1,248 +0,0 @@ -/** - * 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/finalhandler/node_modules/ms/index.js b/node_modules/finalhandler/node_modules/ms/index.js deleted file mode 100644 index 6a522b1..0000000 --- a/node_modules/finalhandler/node_modules/ms/index.js +++ /dev/null @@ -1,152 +0,0 @@ -/** - * 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/finalhandler/node_modules/ms/license.md b/node_modules/finalhandler/node_modules/ms/license.md deleted file mode 100644 index 69b6125..0000000 --- a/node_modules/finalhandler/node_modules/ms/license.md +++ /dev/null @@ -1,21 +0,0 @@ -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/finalhandler/node_modules/ms/package.json b/node_modules/finalhandler/node_modules/ms/package.json deleted file mode 100644 index 1b94bee..0000000 --- a/node_modules/finalhandler/node_modules/ms/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "ms@2.0.0", - "_id": "ms@2.0.0", - "_inBundle": false, - "_integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", - "_location": "/finalhandler/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": [ - "/finalhandler/debug" - ], - "_resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "_shasum": "5608aeadfc00be6c2901df5f9861788de0d597c8", - "_spec": "ms@2.0.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/finalhandler/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/finalhandler/node_modules/ms/readme.md b/node_modules/finalhandler/node_modules/ms/readme.md deleted file mode 100644 index 84a9974..0000000 --- a/node_modules/finalhandler/node_modules/ms/readme.md +++ /dev/null @@ -1,51 +0,0 @@ -# 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/finalhandler/package.json b/node_modules/finalhandler/package.json deleted file mode 100644 index fa077cc..0000000 --- a/node_modules/finalhandler/package.json +++ /dev/null @@ -1,80 +0,0 @@ -{ - "_from": "finalhandler@~1.1.2", - "_id": "finalhandler@1.1.2", - "_inBundle": false, - "_integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", - "_location": "/finalhandler", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "finalhandler@~1.1.2", - "name": "finalhandler", - "escapedName": "finalhandler", - "rawSpec": "~1.1.2", - "saveSpec": null, - "fetchSpec": "~1.1.2" - }, - "_requiredBy": [ - "/express" - ], - "_resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", - "_shasum": "b7e7d000ffd11938d0fdb053506f6ebabe9f587d", - "_spec": "finalhandler@~1.1.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "author": { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - "bugs": { - "url": "https://github.com/pillarjs/finalhandler/issues" - }, - "bundleDependencies": false, - "dependencies": { - "debug": "2.6.9", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "on-finished": "~2.3.0", - "parseurl": "~1.3.3", - "statuses": "~1.5.0", - "unpipe": "~1.0.0" - }, - "deprecated": false, - "description": "Node.js final http responder", - "devDependencies": { - "eslint": "5.16.0", - "eslint-config-standard": "12.0.0", - "eslint-plugin-import": "2.17.2", - "eslint-plugin-markdown": "1.0.0", - "eslint-plugin-node": "8.0.1", - "eslint-plugin-promise": "4.1.1", - "eslint-plugin-standard": "4.0.0", - "istanbul": "0.4.5", - "mocha": "6.1.4", - "readable-stream": "2.3.6", - "safe-buffer": "5.1.2", - "supertest": "4.0.2" - }, - "engines": { - "node": ">= 0.8" - }, - "files": [ - "LICENSE", - "HISTORY.md", - "index.js" - ], - "homepage": "https://github.com/pillarjs/finalhandler#readme", - "license": "MIT", - "name": "finalhandler", - "repository": { - "type": "git", - "url": "git+https://github.com/pillarjs/finalhandler.git" - }, - "scripts": { - "lint": "eslint --plugin markdown --ext js,md .", - "test": "mocha --reporter spec --bail --check-leaks test/", - "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" - }, - "version": "1.1.2" -} diff --git a/node_modules/foreach/.npmignore b/node_modules/foreach/.npmignore deleted file mode 100644 index d135df6..0000000 --- a/node_modules/foreach/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules -components -build \ No newline at end of file diff --git a/node_modules/foreach/LICENSE b/node_modules/foreach/LICENSE deleted file mode 100644 index 3032d6e..0000000 --- a/node_modules/foreach/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -The MIT License - -Copyright (c) 2013 Manuel Stofer - -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/foreach/Makefile b/node_modules/foreach/Makefile deleted file mode 100644 index eae4117..0000000 --- a/node_modules/foreach/Makefile +++ /dev/null @@ -1,11 +0,0 @@ - -build: components - @component build - -components: component.json - @component install --dev - -clean: - rm -fr build components template.js - -.PHONY: clean diff --git a/node_modules/foreach/Readme.md b/node_modules/foreach/Readme.md deleted file mode 100644 index 2752b57..0000000 --- a/node_modules/foreach/Readme.md +++ /dev/null @@ -1,30 +0,0 @@ - -# foreach - -Iterate over the key value pairs of either an array-like object or a dictionary like object. - -[![browser support][1]][2] - -## API - -### foreach(object, function, [context]) - -```js -var each = require('foreach'); - -each([1,2,3], function (value, key, array) { - // value === 1, 2, 3 - // key === 0, 1, 2 - // array === [1, 2, 3] -}); - -each({0:1,1:2,2:3}, function (value, key, object) { - // value === 1, 2, 3 - // key === 0, 1, 2 - // object === {0:1,1:2,2:3} -}); -``` - -[1]: https://ci.testling.com/manuelstofer/foreach.png -[2]: https://ci.testling.com/manuelstofer/foreach - diff --git a/node_modules/foreach/component.json b/node_modules/foreach/component.json deleted file mode 100644 index 0eeecb5..0000000 --- a/node_modules/foreach/component.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "foreach", - "description": "foreach component + npm package", - "version": "2.0.5", - "keywords": [], - "dependencies": {}, - "scripts": [ - "index.js" - ], - "repo": "manuelstofer/foreach" -} diff --git a/node_modules/foreach/index.js b/node_modules/foreach/index.js deleted file mode 100644 index a961e4e..0000000 --- a/node_modules/foreach/index.js +++ /dev/null @@ -1,22 +0,0 @@ - -var hasOwn = Object.prototype.hasOwnProperty; -var toString = Object.prototype.toString; - -module.exports = function forEach (obj, fn, ctx) { - if (toString.call(fn) !== '[object Function]') { - throw new TypeError('iterator must be a function'); - } - var l = obj.length; - if (l === +l) { - for (var i = 0; i < l; i++) { - fn.call(ctx, obj[i], i, obj); - } - } else { - for (var k in obj) { - if (hasOwn.call(obj, k)) { - fn.call(ctx, obj[k], k, obj); - } - } - } -}; - diff --git a/node_modules/foreach/package.json b/node_modules/foreach/package.json deleted file mode 100644 index 5201601..0000000 --- a/node_modules/foreach/package.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "_from": "foreach@^2.0.5", - "_id": "foreach@2.0.5", - "_inBundle": false, - "_integrity": "sha1-C+4AUBiusmDQo6865ljdATbsG5k=", - "_location": "/foreach", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "foreach@^2.0.5", - "name": "foreach", - "escapedName": "foreach", - "rawSpec": "^2.0.5", - "saveSpec": null, - "fetchSpec": "^2.0.5" - }, - "_requiredBy": [ - "/is-typed-array", - "/which-typed-array" - ], - "_resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz", - "_shasum": "0bee005018aeb260d0a3af3ae658dd0136ec1b99", - "_spec": "foreach@^2.0.5", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/is-typed-array", - "author": { - "name": "Manuel Stofer", - "email": "manuel@takimata.ch" - }, - "bugs": { - "url": "https://github.com/manuelstofer/foreach/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Manuel Stofer" - }, - { - "name": "Jordan Harband", - "url": "https://github.com/ljharb" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "foreach component + npm package", - "devDependencies": { - "covert": "*", - "tape": "*" - }, - "homepage": "https://github.com/manuelstofer/foreach#readme", - "keywords": [ - "shim", - "Array.prototype.forEach", - "forEach", - "Array#forEach", - "each" - ], - "license": "MIT", - "main": "index.js", - "name": "foreach", - "repository": { - "type": "git", - "url": "git://github.com/manuelstofer/foreach.git" - }, - "scripts": { - "coverage": "covert test.js", - "coverage-quiet": "covert --quiet test.js", - "test": "node test.js" - }, - "testling": { - "files": "test.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0", - "chrome/22.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/5.0.5..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "2.0.5" -} diff --git a/node_modules/foreach/test.js b/node_modules/foreach/test.js deleted file mode 100644 index c6283c3..0000000 --- a/node_modules/foreach/test.js +++ /dev/null @@ -1,153 +0,0 @@ -var test = require('tape'); -var forEach = require('./index.js'); - - -test('second argument: iterator', function (t) { - var arr = []; - t.throws(function () { forEach(arr); }, TypeError, 'undefined is not a function'); - t.throws(function () { forEach(arr, null); }, TypeError, 'null is not a function'); - t.throws(function () { forEach(arr, ''); }, TypeError, 'string is not a function'); - t.throws(function () { forEach(arr, /a/); }, TypeError, 'regex is not a function'); - t.throws(function () { forEach(arr, true); }, TypeError, 'true is not a function'); - t.throws(function () { forEach(arr, false); }, TypeError, 'false is not a function'); - t.throws(function () { forEach(arr, NaN); }, TypeError, 'NaN is not a function'); - t.throws(function () { forEach(arr, 42); }, TypeError, '42 is not a function'); - t.doesNotThrow(function () { forEach(arr, function () {}); }, 'function is a function'); - t.end(); -}); - -test('array', function (t) { - var arr = [1, 2, 3]; - - t.test('iterates over every item', function (st) { - var index = 0; - forEach(arr, function () { index += 1; }); - st.equal(index, arr.length, 'iterates ' + arr.length + ' times'); - st.end(); - }); - - t.test('first iterator argument', function (st) { - var index = 0; - st.plan(arr.length); - forEach(arr, function (item) { - st.equal(arr[index], item, 'item ' + index + ' is passed as first argument'); - index += 1; - }); - st.end(); - }); - - t.test('second iterator argument', function (st) { - var counter = 0; - st.plan(arr.length); - forEach(arr, function (item, index) { - st.equal(counter, index, 'index ' + index + ' is passed as second argument'); - counter += 1; - }); - st.end(); - }); - - t.test('third iterator argument', function (st) { - st.plan(arr.length); - forEach(arr, function (item, index, array) { - st.deepEqual(arr, array, 'array is passed as third argument'); - }); - st.end(); - }); - - t.test('context argument', function (st) { - var context = {}; - st.plan(1); - forEach([1], function () { - st.equal(this, context, '"this" is the passed context'); - }, context); - st.end(); - }); - - t.end(); -}); - -test('object', function (t) { - var obj = { - a: 1, - b: 2, - c: 3 - }; - var keys = ['a', 'b', 'c']; - - var F = function () { - this.a = 1; - this.b = 2; - }; - F.prototype.c = 3; - var fKeys = ['a', 'b']; - - t.test('iterates over every object literal key', function (st) { - var counter = 0; - forEach(obj, function () { counter += 1; }); - st.equal(counter, keys.length, 'iterated ' + counter + ' times'); - st.end(); - }); - - t.test('iterates only over own keys', function (st) { - var counter = 0; - forEach(new F(), function () { counter += 1; }); - st.equal(counter, fKeys.length, 'iterated ' + fKeys.length + ' times'); - st.end(); - }); - - t.test('first iterator argument', function (st) { - var index = 0; - st.plan(keys.length); - forEach(obj, function (item) { - st.equal(obj[keys[index]], item, 'item at key ' + keys[index] + ' is passed as first argument'); - index += 1; - }); - st.end(); - }); - - t.test('second iterator argument', function (st) { - var counter = 0; - st.plan(keys.length); - forEach(obj, function (item, key) { - st.equal(keys[counter], key, 'key ' + key + ' is passed as second argument'); - counter += 1; - }); - st.end(); - }); - - t.test('third iterator argument', function (st) { - st.plan(keys.length); - forEach(obj, function (item, key, object) { - st.deepEqual(obj, object, 'object is passed as third argument'); - }); - st.end(); - }); - - t.test('context argument', function (st) { - var context = {}; - st.plan(1); - forEach({ a: 1 }, function () { - st.equal(this, context, '"this" is the passed context'); - }, context); - st.end(); - }); - - t.end(); -}); - - -test('string', function (t) { - var str = 'str'; - t.test('second iterator argument', function (st) { - var counter = 0; - st.plan(str.length * 2 + 1); - forEach(str, function (item, index) { - st.equal(counter, index, 'index ' + index + ' is passed as second argument'); - st.equal(str.charAt(index), item); - counter += 1; - }); - st.equal(counter, str.length, 'iterates ' + str.length + ' times'); - }); - t.end(); -}); - diff --git a/node_modules/forwarded/HISTORY.md b/node_modules/forwarded/HISTORY.md deleted file mode 100644 index 2599a55..0000000 --- a/node_modules/forwarded/HISTORY.md +++ /dev/null @@ -1,16 +0,0 @@ -0.1.2 / 2017-09-14 -================== - - * perf: improve header parsing - * perf: reduce overhead when no `X-Forwarded-For` header - -0.1.1 / 2017-09-10 -================== - - * Fix trimming leading / trailing OWS - * perf: hoist regular expression - -0.1.0 / 2014-09-21 -================== - - * Initial release diff --git a/node_modules/forwarded/LICENSE b/node_modules/forwarded/LICENSE deleted file mode 100644 index 84441fb..0000000 --- a/node_modules/forwarded/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2014-2017 Douglas Christopher Wilson - -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/forwarded/README.md b/node_modules/forwarded/README.md deleted file mode 100644 index c776ee5..0000000 --- a/node_modules/forwarded/README.md +++ /dev/null @@ -1,57 +0,0 @@ -# forwarded - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Parse HTTP X-Forwarded-For header - -## Installation - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install forwarded -``` - -## API - -```js -var forwarded = require('forwarded') -``` - -### forwarded(req) - -```js -var addresses = forwarded(req) -``` - -Parse the `X-Forwarded-For` header from the request. Returns an array -of the addresses, including the socket address for the `req`, in reverse -order (i.e. index `0` is the socket address and the last index is the -furthest address, typically the end-user). - -## Testing - -```sh -$ npm test -``` - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/forwarded.svg -[npm-url]: https://npmjs.org/package/forwarded -[node-version-image]: https://img.shields.io/node/v/forwarded.svg -[node-version-url]: https://nodejs.org/en/download/ -[travis-image]: https://img.shields.io/travis/jshttp/forwarded/master.svg -[travis-url]: https://travis-ci.org/jshttp/forwarded -[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded/master.svg -[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master -[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg -[downloads-url]: https://npmjs.org/package/forwarded diff --git a/node_modules/forwarded/index.js b/node_modules/forwarded/index.js deleted file mode 100644 index 7833b3d..0000000 --- a/node_modules/forwarded/index.js +++ /dev/null @@ -1,76 +0,0 @@ -/*! - * forwarded - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module exports. - * @public - */ - -module.exports = forwarded - -/** - * Get all addresses in the request, using the `X-Forwarded-For` header. - * - * @param {object} req - * @return {array} - * @public - */ - -function forwarded (req) { - if (!req) { - throw new TypeError('argument req is required') - } - - // simple header parsing - var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') - var socketAddr = req.connection.remoteAddress - var addrs = [socketAddr].concat(proxyAddrs) - - // return all addresses - return addrs -} - -/** - * Parse the X-Forwarded-For header. - * - * @param {string} header - * @private - */ - -function parse (header) { - var end = header.length - var list = [] - var start = header.length - - // gather addresses, backwards - for (var i = header.length - 1; i >= 0; i--) { - switch (header.charCodeAt(i)) { - case 0x20: /* */ - if (start === end) { - start = end = i - } - break - case 0x2c: /* , */ - if (start !== end) { - list.push(header.substring(start, end)) - } - start = end = i - break - default: - start = i - break - } - } - - // final address - if (start !== end) { - list.push(header.substring(start, end)) - } - - return list -} diff --git a/node_modules/forwarded/package.json b/node_modules/forwarded/package.json deleted file mode 100644 index 922e506..0000000 --- a/node_modules/forwarded/package.json +++ /dev/null @@ -1,78 +0,0 @@ -{ - "_from": "forwarded@~0.1.2", - "_id": "forwarded@0.1.2", - "_inBundle": false, - "_integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=", - "_location": "/forwarded", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "forwarded@~0.1.2", - "name": "forwarded", - "escapedName": "forwarded", - "rawSpec": "~0.1.2", - "saveSpec": null, - "fetchSpec": "~0.1.2" - }, - "_requiredBy": [ - "/proxy-addr" - ], - "_resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", - "_shasum": "98c23dab1175657b8c0573e8ceccd91b0ff18c84", - "_spec": "forwarded@~0.1.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/proxy-addr", - "bugs": { - "url": "https://github.com/jshttp/forwarded/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - } - ], - "deprecated": false, - "description": "Parse HTTP X-Forwarded-For header", - "devDependencies": { - "beautify-benchmark": "0.2.4", - "benchmark": "2.1.4", - "eslint": "3.19.0", - "eslint-config-standard": "10.2.1", - "eslint-plugin-import": "2.7.0", - "eslint-plugin-node": "5.1.1", - "eslint-plugin-promise": "3.5.0", - "eslint-plugin-standard": "3.0.1", - "istanbul": "0.4.5", - "mocha": "1.21.5" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "LICENSE", - "HISTORY.md", - "README.md", - "index.js" - ], - "homepage": "https://github.com/jshttp/forwarded#readme", - "keywords": [ - "x-forwarded-for", - "http", - "req" - ], - "license": "MIT", - "name": "forwarded", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/forwarded.git" - }, - "scripts": { - "bench": "node benchmark/index.js", - "lint": "eslint .", - "test": "mocha --reporter spec --bail --check-leaks test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" - }, - "version": "0.1.2" -} diff --git a/node_modules/fresh/HISTORY.md b/node_modules/fresh/HISTORY.md deleted file mode 100644 index 4586996..0000000 --- a/node_modules/fresh/HISTORY.md +++ /dev/null @@ -1,70 +0,0 @@ -0.5.2 / 2017-09-13 -================== - - * Fix regression matching multiple ETags in `If-None-Match` - * perf: improve `If-None-Match` token parsing - -0.5.1 / 2017-09-11 -================== - - * Fix handling of modified headers with invalid dates - * perf: improve ETag match loop - -0.5.0 / 2017-02-21 -================== - - * Fix incorrect result when `If-None-Match` has both `*` and ETags - * Fix weak `ETag` matching to match spec - * perf: delay reading header values until needed - * perf: skip checking modified time if ETag check failed - * perf: skip parsing `If-None-Match` when no `ETag` header - * perf: use `Date.parse` instead of `new Date` - -0.4.0 / 2017-02-05 -================== - - * Fix false detection of `no-cache` request directive - * perf: enable strict mode - * perf: hoist regular expressions - * perf: remove duplicate conditional - * perf: remove unnecessary boolean coercions - -0.3.0 / 2015-05-12 -================== - - * Add weak `ETag` matching support - -0.2.4 / 2014-09-07 -================== - - * Support Node.js 0.6 - -0.2.3 / 2014-09-07 -================== - - * Move repository to jshttp - -0.2.2 / 2014-02-19 -================== - - * Revert "Fix for blank page on Safari reload" - -0.2.1 / 2014-01-29 -================== - - * Fix for blank page on Safari reload - -0.2.0 / 2013-08-11 -================== - - * Return stale for `Cache-Control: no-cache` - -0.1.0 / 2012-06-15 -================== - - * Add `If-None-Match: *` support - -0.0.1 / 2012-06-10 -================== - - * Initial release diff --git a/node_modules/fresh/LICENSE b/node_modules/fresh/LICENSE deleted file mode 100644 index 1434ade..0000000 --- a/node_modules/fresh/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 TJ Holowaychuk -Copyright (c) 2016-2017 Douglas Christopher Wilson - -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/fresh/README.md b/node_modules/fresh/README.md deleted file mode 100644 index 1c1c680..0000000 --- a/node_modules/fresh/README.md +++ /dev/null @@ -1,119 +0,0 @@ -# fresh - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -HTTP response freshness testing - -## Installation - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -``` -$ npm install fresh -``` - -## API - - - -```js -var fresh = require('fresh') -``` - -### fresh(reqHeaders, resHeaders) - -Check freshness of the response using request and response headers. - -When the response is still "fresh" in the client's cache `true` is -returned, otherwise `false` is returned to indicate that the client -cache is now stale and the full response should be sent. - -When a client sends the `Cache-Control: no-cache` request header to -indicate an end-to-end reload request, this module will return `false` -to make handling these requests transparent. - -## Known Issues - -This module is designed to only follow the HTTP specifications, not -to work-around all kinda of client bugs (especially since this module -typically does not recieve enough information to understand what the -client actually is). - -There is a known issue that in certain versions of Safari, Safari -will incorrectly make a request that allows this module to validate -freshness of the resource even when Safari does not have a -representation of the resource in the cache. The module -[jumanji](https://www.npmjs.com/package/jumanji) can be used in -an Express application to work-around this issue and also provides -links to further reading on this Safari bug. - -## Example - -### API usage - - - -```js -var reqHeaders = { 'if-none-match': '"foo"' } -var resHeaders = { 'etag': '"bar"' } -fresh(reqHeaders, resHeaders) -// => false - -var reqHeaders = { 'if-none-match': '"foo"' } -var resHeaders = { 'etag': '"foo"' } -fresh(reqHeaders, resHeaders) -// => true -``` - -### Using with Node.js http server - -```js -var fresh = require('fresh') -var http = require('http') - -var server = http.createServer(function (req, res) { - // perform server logic - // ... including adding ETag / Last-Modified response headers - - if (isFresh(req, res)) { - // client has a fresh copy of resource - res.statusCode = 304 - res.end() - return - } - - // send the resource - res.statusCode = 200 - res.end('hello, world!') -}) - -function isFresh (req, res) { - return fresh(req.headers, { - 'etag': res.getHeader('ETag'), - 'last-modified': res.getHeader('Last-Modified') - }) -} - -server.listen(3000) -``` - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/fresh.svg -[npm-url]: https://npmjs.org/package/fresh -[node-version-image]: https://img.shields.io/node/v/fresh.svg -[node-version-url]: https://nodejs.org/en/ -[travis-image]: https://img.shields.io/travis/jshttp/fresh/master.svg -[travis-url]: https://travis-ci.org/jshttp/fresh -[coveralls-image]: https://img.shields.io/coveralls/jshttp/fresh/master.svg -[coveralls-url]: https://coveralls.io/r/jshttp/fresh?branch=master -[downloads-image]: https://img.shields.io/npm/dm/fresh.svg -[downloads-url]: https://npmjs.org/package/fresh diff --git a/node_modules/fresh/index.js b/node_modules/fresh/index.js deleted file mode 100644 index d154f5a..0000000 --- a/node_modules/fresh/index.js +++ /dev/null @@ -1,137 +0,0 @@ -/*! - * fresh - * Copyright(c) 2012 TJ Holowaychuk - * Copyright(c) 2016-2017 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * RegExp to check for no-cache token in Cache-Control. - * @private - */ - -var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ - -/** - * Module exports. - * @public - */ - -module.exports = fresh - -/** - * Check freshness of the response using request and response headers. - * - * @param {Object} reqHeaders - * @param {Object} resHeaders - * @return {Boolean} - * @public - */ - -function fresh (reqHeaders, resHeaders) { - // fields - var modifiedSince = reqHeaders['if-modified-since'] - var noneMatch = reqHeaders['if-none-match'] - - // unconditional request - if (!modifiedSince && !noneMatch) { - return false - } - - // Always return stale when Cache-Control: no-cache - // to support end-to-end reload requests - // https://tools.ietf.org/html/rfc2616#section-14.9.4 - var cacheControl = reqHeaders['cache-control'] - if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { - return false - } - - // if-none-match - if (noneMatch && noneMatch !== '*') { - var etag = resHeaders['etag'] - - if (!etag) { - return false - } - - var etagStale = true - var matches = parseTokenList(noneMatch) - for (var i = 0; i < matches.length; i++) { - var match = matches[i] - if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { - etagStale = false - break - } - } - - if (etagStale) { - return false - } - } - - // if-modified-since - if (modifiedSince) { - var lastModified = resHeaders['last-modified'] - var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) - - if (modifiedStale) { - return false - } - } - - return true -} - -/** - * Parse an HTTP Date into a number. - * - * @param {string} date - * @private - */ - -function parseHttpDate (date) { - var timestamp = date && Date.parse(date) - - // istanbul ignore next: guard against date.js Date.parse patching - return typeof timestamp === 'number' - ? timestamp - : NaN -} - -/** - * Parse a HTTP token list. - * - * @param {string} str - * @private - */ - -function parseTokenList (str) { - var end = 0 - var list = [] - var start = 0 - - // gather tokens - for (var i = 0, len = str.length; i < len; i++) { - switch (str.charCodeAt(i)) { - case 0x20: /* */ - if (start === end) { - start = end = i + 1 - } - break - case 0x2c: /* , */ - list.push(str.substring(start, end)) - start = end = i + 1 - break - default: - end = i + 1 - break - } - } - - // final token - list.push(str.substring(start, end)) - - return list -} diff --git a/node_modules/fresh/package.json b/node_modules/fresh/package.json deleted file mode 100644 index 822b282..0000000 --- a/node_modules/fresh/package.json +++ /dev/null @@ -1,90 +0,0 @@ -{ - "_from": "fresh@0.5.2", - "_id": "fresh@0.5.2", - "_inBundle": false, - "_integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", - "_location": "/fresh", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "fresh@0.5.2", - "name": "fresh", - "escapedName": "fresh", - "rawSpec": "0.5.2", - "saveSpec": null, - "fetchSpec": "0.5.2" - }, - "_requiredBy": [ - "/express", - "/send" - ], - "_resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "_shasum": "3d8cadd90d976569fa835ab1f8e4b23a105605a7", - "_spec": "fresh@0.5.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "bugs": { - "url": "https://github.com/jshttp/fresh/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - } - ], - "deprecated": false, - "description": "HTTP response freshness testing", - "devDependencies": { - "beautify-benchmark": "0.2.4", - "benchmark": "2.1.4", - "eslint": "3.19.0", - "eslint-config-standard": "10.2.1", - "eslint-plugin-import": "2.7.0", - "eslint-plugin-markdown": "1.0.0-beta.6", - "eslint-plugin-node": "5.1.1", - "eslint-plugin-promise": "3.5.0", - "eslint-plugin-standard": "3.0.1", - "istanbul": "0.4.5", - "mocha": "1.21.5" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "HISTORY.md", - "LICENSE", - "index.js" - ], - "homepage": "https://github.com/jshttp/fresh#readme", - "keywords": [ - "fresh", - "http", - "conditional", - "cache" - ], - "license": "MIT", - "name": "fresh", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/fresh.git" - }, - "scripts": { - "bench": "node benchmark/index.js", - "lint": "eslint --plugin markdown --ext js,md .", - "test": "mocha --reporter spec --bail --check-leaks test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" - }, - "version": "0.5.2" -} diff --git a/node_modules/fs-constants/LICENSE b/node_modules/fs-constants/LICENSE deleted file mode 100644 index cb757e5..0000000 --- a/node_modules/fs-constants/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2018 Mathias Buus - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -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/fs-constants/README.md b/node_modules/fs-constants/README.md deleted file mode 100644 index 62b3374..0000000 --- a/node_modules/fs-constants/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# fs-constants - -Small module that allows you to get the fs constants across -Node and the browser. - -``` -npm install fs-constants -``` - -Previously you would use `require('constants')` for this in node but that has been -deprecated and changed to `require('fs').constants` which does not browserify. - -This module uses `require('constants')` in the browser and `require('fs').constants` in node to work around this - - -## Usage - -``` js -var constants = require('fs-constants') - -console.log('constants:', constants) -``` - -## License - -MIT diff --git a/node_modules/fs-constants/browser.js b/node_modules/fs-constants/browser.js deleted file mode 100644 index 3c87638..0000000 --- a/node_modules/fs-constants/browser.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('constants') diff --git a/node_modules/fs-constants/index.js b/node_modules/fs-constants/index.js deleted file mode 100644 index 2a3aadf..0000000 --- a/node_modules/fs-constants/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('fs').constants || require('constants') diff --git a/node_modules/fs-constants/package.json b/node_modules/fs-constants/package.json deleted file mode 100644 index a3a3683..0000000 --- a/node_modules/fs-constants/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "_from": "fs-constants@^1.0.0", - "_id": "fs-constants@1.0.0", - "_inBundle": false, - "_integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", - "_location": "/fs-constants", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "fs-constants@^1.0.0", - "name": "fs-constants", - "escapedName": "fs-constants", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/tar-stream" - ], - "_resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "_shasum": "6be0de9be998ce16af8afc24497b9ee9b7ccd9ad", - "_spec": "fs-constants@^1.0.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/tar-stream", - "author": { - "name": "Mathias Buus", - "url": "@mafintosh" - }, - "browser": "browser.js", - "bugs": { - "url": "https://github.com/mafintosh/fs-constants/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Require constants across node and the browser", - "devDependencies": {}, - "homepage": "https://github.com/mafintosh/fs-constants", - "license": "MIT", - "main": "index.js", - "name": "fs-constants", - "repository": { - "type": "git", - "url": "git+https://github.com/mafintosh/fs-constants.git" - }, - "version": "1.0.0" -} diff --git a/node_modules/function-bind/.editorconfig b/node_modules/function-bind/.editorconfig deleted file mode 100644 index ac29ade..0000000 --- a/node_modules/function-bind/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -max_line_length = 120 - -[CHANGELOG.md] -indent_style = space -indent_size = 2 - -[*.json] -max_line_length = off - -[Makefile] -max_line_length = off diff --git a/node_modules/function-bind/.eslintrc b/node_modules/function-bind/.eslintrc deleted file mode 100644 index 9b33d8e..0000000 --- a/node_modules/function-bind/.eslintrc +++ /dev/null @@ -1,15 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "func-name-matching": 0, - "indent": [2, 4], - "max-nested-callbacks": [2, 3], - "max-params": [2, 3], - "max-statements": [2, 20], - "no-new-func": [1], - "strict": [0] - } -} diff --git a/node_modules/function-bind/.jscs.json b/node_modules/function-bind/.jscs.json deleted file mode 100644 index 8c44794..0000000 --- a/node_modules/function-bind/.jscs.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 8 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": "asc-insensitive", - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/node_modules/function-bind/.npmignore b/node_modules/function-bind/.npmignore deleted file mode 100644 index dbb555f..0000000 --- a/node_modules/function-bind/.npmignore +++ /dev/null @@ -1,22 +0,0 @@ -# gitignore -.DS_Store -.monitor -.*.swp -.nodemonignore -releases -*.log -*.err -fleet.json -public/browserify -bin/*.json -.bin -build -compile -.lock-wscript -coverage -node_modules - -# Only apps should have lockfiles -npm-shrinkwrap.json -package-lock.json -yarn.lock diff --git a/node_modules/function-bind/.travis.yml b/node_modules/function-bind/.travis.yml deleted file mode 100644 index 85f70d2..0000000 --- a/node_modules/function-bind/.travis.yml +++ /dev/null @@ -1,168 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "8.4" - - "7.10" - - "6.11" - - "5.12" - - "4.8" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then npm install -g npm@1.3 ; elif [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi' - - 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then if [ "${TRAVIS_NODE_VERSION%${TRAVIS_NODE_VERSION#[0-9]}}" = "0" ] || [ "${TRAVIS_NODE_VERSION:0:4}" = "iojs" ]; then npm install -g npm@4.5 ; else npm install -g npm; fi; fi' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then nvm install 0.8 && npm install -g npm@1.3 && npm install -g npm@1.4.28 && npm install -g npm@2 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "node" - env: PRETEST=true - - node_js: "4" - env: COVERAGE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true diff --git a/node_modules/function-bind/LICENSE b/node_modules/function-bind/LICENSE deleted file mode 100644 index 62d6d23..0000000 --- a/node_modules/function-bind/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2013 Raynos. - -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/function-bind/README.md b/node_modules/function-bind/README.md deleted file mode 100644 index 81862a0..0000000 --- a/node_modules/function-bind/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# function-bind - - - - - -Implementation of function.prototype.bind - -## Example - -I mainly do this for unit tests I run on phantomjs. -PhantomJS does not have Function.prototype.bind :( - -```js -Function.prototype.bind = require("function-bind") -``` - -## Installation - -`npm install function-bind` - -## Contributors - - - Raynos - -## MIT Licenced - - [travis-svg]: https://travis-ci.org/Raynos/function-bind.svg - [travis-url]: https://travis-ci.org/Raynos/function-bind - [npm-badge-svg]: https://badge.fury.io/js/function-bind.svg - [npm-url]: https://npmjs.org/package/function-bind - [5]: https://coveralls.io/repos/Raynos/function-bind/badge.png - [6]: https://coveralls.io/r/Raynos/function-bind - [7]: https://gemnasium.com/Raynos/function-bind.png - [8]: https://gemnasium.com/Raynos/function-bind - [deps-svg]: https://david-dm.org/Raynos/function-bind.svg - [deps-url]: https://david-dm.org/Raynos/function-bind - [dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg - [dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies - [11]: https://ci.testling.com/Raynos/function-bind.png - [12]: https://ci.testling.com/Raynos/function-bind diff --git a/node_modules/function-bind/implementation.js b/node_modules/function-bind/implementation.js deleted file mode 100644 index cc4daec..0000000 --- a/node_modules/function-bind/implementation.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; - - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } - - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; diff --git a/node_modules/function-bind/index.js b/node_modules/function-bind/index.js deleted file mode 100644 index 3bb6b96..0000000 --- a/node_modules/function-bind/index.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = Function.prototype.bind || implementation; diff --git a/node_modules/function-bind/package.json b/node_modules/function-bind/package.json deleted file mode 100644 index 3841888..0000000 --- a/node_modules/function-bind/package.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "_from": "function-bind@^1.1.1", - "_id": "function-bind@1.1.1", - "_inBundle": false, - "_integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "_location": "/function-bind", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "function-bind@^1.1.1", - "name": "function-bind", - "escapedName": "function-bind", - "rawSpec": "^1.1.1", - "saveSpec": null, - "fetchSpec": "^1.1.1" - }, - "_requiredBy": [ - "/es-abstract", - "/has", - "/object.assign", - "/which-typed-array" - ], - "_resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "_shasum": "a56899d3ea3c9bab874bb9773b7c5ede92f4895d", - "_spec": "function-bind@^1.1.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/es-abstract", - "author": { - "name": "Raynos", - "email": "raynos2@gmail.com" - }, - "bugs": { - "url": "https://github.com/Raynos/function-bind/issues", - "email": "raynos2@gmail.com" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Raynos" - }, - { - "name": "Jordan Harband", - "url": "https://github.com/ljharb" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "Implementation of Function.prototype.bind", - "devDependencies": { - "@ljharb/eslint-config": "^12.2.1", - "covert": "^1.1.0", - "eslint": "^4.5.0", - "jscs": "^3.0.7", - "tape": "^4.8.0" - }, - "homepage": "https://github.com/Raynos/function-bind", - "keywords": [ - "function", - "bind", - "shim", - "es5" - ], - "license": "MIT", - "main": "index", - "name": "function-bind", - "repository": { - "type": "git", - "url": "git://github.com/Raynos/function-bind.git" - }, - "scripts": { - "coverage": "covert test/*.js", - "eslint": "eslint *.js */*.js", - "jscs": "jscs *.js */*.js", - "lint": "npm run jscs && npm run eslint", - "posttest": "npm run coverage -- --quiet", - "pretest": "npm run lint", - "test": "npm run tests-only", - "tests-only": "node test" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "ie/8..latest", - "firefox/16..latest", - "firefox/nightly", - "chrome/22..latest", - "chrome/canary", - "opera/12..latest", - "opera/next", - "safari/5.1..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2..latest" - ] - }, - "version": "1.1.1" -} diff --git a/node_modules/function-bind/test/.eslintrc b/node_modules/function-bind/test/.eslintrc deleted file mode 100644 index 8a56d5b..0000000 --- a/node_modules/function-bind/test/.eslintrc +++ /dev/null @@ -1,9 +0,0 @@ -{ - "rules": { - "array-bracket-newline": 0, - "array-element-newline": 0, - "max-statements-per-line": [2, { "max": 2 }], - "no-invalid-this": 0, - "no-magic-numbers": 0, - } -} diff --git a/node_modules/function-bind/test/index.js b/node_modules/function-bind/test/index.js deleted file mode 100644 index 2edecce..0000000 --- a/node_modules/function-bind/test/index.js +++ /dev/null @@ -1,252 +0,0 @@ -// jscs:disable requireUseStrict - -var test = require('tape'); - -var functionBind = require('../implementation'); -var getCurrentContext = function () { return this; }; - -test('functionBind is a function', function (t) { - t.equal(typeof functionBind, 'function'); - t.end(); -}); - -test('non-functions', function (t) { - var nonFunctions = [true, false, [], {}, 42, 'foo', NaN, /a/g]; - t.plan(nonFunctions.length); - for (var i = 0; i < nonFunctions.length; ++i) { - try { functionBind.call(nonFunctions[i]); } catch (ex) { - t.ok(ex instanceof TypeError, 'throws when given ' + String(nonFunctions[i])); - } - } - t.end(); -}); - -test('without a context', function (t) { - t.test('binds properly', function (st) { - var args, context; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - context = this; - }) - }; - namespace.func(1, 2, 3); - st.deepEqual(args, [1, 2, 3]); - st.equal(context, getCurrentContext.call()); - st.end(); - }); - - t.test('binds properly, and still supplies bound arguments', function (st) { - var args, context; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - context = this; - }, undefined, 1, 2, 3) - }; - namespace.func(4, 5, 6); - st.deepEqual(args, [1, 2, 3, 4, 5, 6]); - st.equal(context, getCurrentContext.call()); - st.end(); - }); - - t.test('returns properly', function (st) { - var args; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - return this; - }, null) - }; - var context = namespace.func(1, 2, 3); - st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); - st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); - st.end(); - }); - - t.test('returns properly with bound arguments', function (st) { - var args; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - return this; - }, null, 1, 2, 3) - }; - var context = namespace.func(4, 5, 6); - st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); - st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); - st.end(); - }); - - t.test('called as a constructor', function (st) { - var thunkify = function (value) { - return function () { return value; }; - }; - st.test('returns object value', function (sst) { - var expectedReturnValue = [1, 2, 3]; - var Constructor = functionBind.call(thunkify(expectedReturnValue), null); - var result = new Constructor(); - sst.equal(result, expectedReturnValue); - sst.end(); - }); - - st.test('does not return primitive value', function (sst) { - var Constructor = functionBind.call(thunkify(42), null); - var result = new Constructor(); - sst.notEqual(result, 42); - sst.end(); - }); - - st.test('object from bound constructor is instance of original and bound constructor', function (sst) { - var A = function (x) { - this.name = x || 'A'; - }; - var B = functionBind.call(A, null, 'B'); - - var result = new B(); - sst.ok(result instanceof B, 'result is instance of bound constructor'); - sst.ok(result instanceof A, 'result is instance of original constructor'); - sst.end(); - }); - - st.end(); - }); - - t.end(); -}); - -test('with a context', function (t) { - t.test('with no bound arguments', function (st) { - var args, context; - var boundContext = {}; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - context = this; - }, boundContext) - }; - namespace.func(1, 2, 3); - st.equal(context, boundContext, 'binds a context properly'); - st.deepEqual(args, [1, 2, 3], 'supplies passed arguments'); - st.end(); - }); - - t.test('with bound arguments', function (st) { - var args, context; - var boundContext = {}; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - context = this; - }, boundContext, 1, 2, 3) - }; - namespace.func(4, 5, 6); - st.equal(context, boundContext, 'binds a context properly'); - st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'supplies bound and passed arguments'); - st.end(); - }); - - t.test('returns properly', function (st) { - var boundContext = {}; - var args; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - return this; - }, boundContext) - }; - var context = namespace.func(1, 2, 3); - st.equal(context, boundContext, 'returned context is bound context'); - st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); - st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); - st.end(); - }); - - t.test('returns properly with bound arguments', function (st) { - var boundContext = {}; - var args; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - return this; - }, boundContext, 1, 2, 3) - }; - var context = namespace.func(4, 5, 6); - st.equal(context, boundContext, 'returned context is bound context'); - st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); - st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); - st.end(); - }); - - t.test('passes the correct arguments when called as a constructor', function (st) { - var expected = { name: 'Correct' }; - var namespace = { - Func: functionBind.call(function (arg) { - return arg; - }, { name: 'Incorrect' }) - }; - var returned = new namespace.Func(expected); - st.equal(returned, expected, 'returns the right arg when called as a constructor'); - st.end(); - }); - - t.test('has the new instance\'s context when called as a constructor', function (st) { - var actualContext; - var expectedContext = { foo: 'bar' }; - var namespace = { - Func: functionBind.call(function () { - actualContext = this; - }, expectedContext) - }; - var result = new namespace.Func(); - st.equal(result instanceof namespace.Func, true); - st.notEqual(actualContext, expectedContext); - st.end(); - }); - - t.end(); -}); - -test('bound function length', function (t) { - t.test('sets a correct length without thisArg', function (st) { - var subject = functionBind.call(function (a, b, c) { return a + b + c; }); - st.equal(subject.length, 3); - st.equal(subject(1, 2, 3), 6); - st.end(); - }); - - t.test('sets a correct length with thisArg', function (st) { - var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}); - st.equal(subject.length, 3); - st.equal(subject(1, 2, 3), 6); - st.end(); - }); - - t.test('sets a correct length without thisArg and first argument', function (st) { - var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1); - st.equal(subject.length, 2); - st.equal(subject(2, 3), 6); - st.end(); - }); - - t.test('sets a correct length with thisArg and first argument', function (st) { - var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1); - st.equal(subject.length, 2); - st.equal(subject(2, 3), 6); - st.end(); - }); - - t.test('sets a correct length without thisArg and too many arguments', function (st) { - var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1, 2, 3, 4); - st.equal(subject.length, 0); - st.equal(subject(), 6); - st.end(); - }); - - t.test('sets a correct length with thisArg and too many arguments', function (st) { - var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1, 2, 3, 4); - st.equal(subject.length, 0); - st.equal(subject(), 6); - st.end(); - }); -}); diff --git a/node_modules/gauge/CHANGELOG.md b/node_modules/gauge/CHANGELOG.md deleted file mode 100644 index 407bc19..0000000 --- a/node_modules/gauge/CHANGELOG.md +++ /dev/null @@ -1,160 +0,0 @@ -### v2.7.4 - -* Reset colors prior to ending a line, to eliminate flicker when a line - is trucated between start and end color sequences. - -### v2.7.3 - -* Only create our onExit handler when we're enabled and remove it when we're - disabled. This stops us from creating multiple onExit handlers when - multiple gauge objects are being used. -* Fix bug where if a theme name were given instead of a theme object, it - would crash. -* Remove supports-color because it's not actually used. Uhm. Yes, I just - updated it. >.> - -### v2.7.2 - -* Use supports-color instead of has-color (as the module has been renamed) - -### v2.7.1 - -* Bug fix: Calls to show/pulse while the progress bar is disabled should still - update our internal representation of what would be shown should it be enabled. - -### v2.7.0 - -* New feature: Add new `isEnabled` method to allow introspection of the gauge's - "enabledness" as controlled by `.enable()` and `.disable()`. - -### v2.6.0 - -* Bug fix: Don't run the code associated with `enable`/`disable` if the gauge - is already enabled or disabled respectively. This prevents leaking event - listeners, amongst other weirdness. -* New feature: Template items can have default values that will be used if no - value was otherwise passed in. - -### v2.5.3 - -* Default to `enabled` only if we have a tty. Users can always override - this by passing in the `enabled` option explicitly or by calling calling - `gauge.enable()`. - -### v2.5.2 - -* Externalized `./console-strings.js` into `console-control-strings`. - -### v2.5.1 - -* Update to `signal-exit@3.0.0`, which fixes a compatibility bug with the - node profiler. -* [#39](https://github.com/iarna/gauge/pull/39) Fix tests on 0.10 and add - a missing devDependency. ([@helloyou2012](https://github.com/helloyou2012)) - -### v2.5.0 - -* Add way to programmatically fetch a list of theme names in a themeset - (`Themeset.getThemeNames`). - -### v2.4.0 - -* Add support for setting themesets on existing gauge objects. -* Add post-IO callback to `gauge.hide()` as it is somtetimes necessary when - your terminal is interleaving output from multiple filehandles (ie, stdout - & stderr). - -### v2.3.1 - -* Fix a refactor bug in setTheme where it wasn't accepting the various types - of args it should. - -### v2.3.0 - -#### FEATURES - -* Add setTemplate & setTheme back in. -* Add support for named themes, you can now ask for things like 'colorASCII' - and 'brailleSpinner'. Of course, you can still pass in theme objects. - Additionally you can now pass in an object with `hasUnicode`, `hasColor` and - `platform` keys in order to override our guesses as to those values when - selecting a default theme from the themeset. -* Make the output stream optional (it defaults to `process.stderr` now). -* Add `setWriteTo(stream[, tty])` to change the output stream and, - optionally, tty. - -#### BUG FIXES & REFACTORING - -* Abort the display phase early if we're supposed to be hidden and we are. -* Stop printing a bunch of spaces at the end of lines, since we're already - using an erase-to-end-of-line code anyway. -* The unicode themes were missing the subsection separator. - -### v2.2.1 - -* Fix image in readme - -### v2.2.0 - -* All new themes API– reference themes by name and pass in custom themes and - themesets (themesets get platform support autodetection done on them to - select the best theme). Theme mixins let you add features to all existing - themes. -* Much, much improved test coverage. - -### v2.1.0 - -* Got rid of ░ in the default platform, noUnicode, hasColor theme. Thanks - to @yongtw123 for pointing out this had snuck in. -* Fiddled with the demo output to make it easier to see the spinner spin. Also - added prints before each platforms test output. -* I forgot to include `signal-exit` in our deps. <.< Thank you @KenanY for - finding this. Then I was lazy and made a new commit instead of using his - PR. Again, thank you for your patience @KenenY. -* Drastically speed up travis testing. -* Add a small javascript demo (demo.js) for showing off the various themes - (and testing them on diff platforms). -* Change: The subsection separator from ⁄ and / (different chars) to >. -* Fix crasher: A show or pulse without a label would cause the template renderer - to complain about a missing value. -* New feature: Add the ability to disable the clean-up-on-exit behavior. - Not something I expect to be widely desirable, but important if you have - multiple distinct gauge instances in your app. -* Use our own color support detection. - The `has-color` module proved too magic for my needs, making assumptions - as to which stream we write to and reading command line arguments. - -### v2.0.0 - -This is a major rewrite of the internals. Externally there are fewer -changes: - -* On node>0.8 gauge object now prints updates at a fixed rate. This means - that when you call `show` it may wate up to `updateInterval` ms before it - actually prints an update. You override this behavior with the - `fixedFramerate` option. -* The gauge object now keeps the cursor hidden as long as it's enabled and - shown. -* The constructor's arguments have changed, now it takes a mandatory output - stream and an optional options object. The stream no longer needs to be - an `ansi`ified stream, although it can be if you want (but we won't make - use of its special features). -* Previously the gauge was disabled by default if `process.stdout` wasn't a - tty. Now it always defaults to enabled. If you want the previous - behavior set the `enabled` option to `process.stdout.isTTY`. -* The constructor's options have changed– see the docs for details. -* Themes are entirely different. If you were using a custom theme, or - referring to one directly (eg via `Gauge.unicode` or `Gauge.ascii`) then - you'll need to change your code. You can get the equivalent of the latter - with: - ``` - var themes = require('gauge/themes') - var unicodeTheme = themes(true, true) // returns the color unicode theme for your platform - ``` - The default themes no longer use any ambiguous width characters, so even - if you choose to display those as wide your progress bar should still - display correctly. -* Templates are entirely different and if you were using a custom one, you - should consult the documentation to learn how to recreate it. If you were - using the default, be aware that it has changed and the result looks quite - a bit different. diff --git a/node_modules/gauge/LICENSE b/node_modules/gauge/LICENSE deleted file mode 100644 index e756052..0000000 --- a/node_modules/gauge/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2014, Rebecca Turner - -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/gauge/README.md b/node_modules/gauge/README.md deleted file mode 100644 index bdd60e3..0000000 --- a/node_modules/gauge/README.md +++ /dev/null @@ -1,399 +0,0 @@ -gauge -===== - -A nearly stateless terminal based horizontal gauge / progress bar. - -```javascript -var Gauge = require("gauge") - -var gauge = new Gauge() - -gauge.show("test", 0.20) - -gauge.pulse("this") - -gauge.hide() -``` - -![](gauge-demo.gif) - - -### CHANGES FROM 1.x - -Gauge 2.x is breaking release, please see the [changelog] for details on -what's changed if you were previously a user of this module. - -[changelog]: CHANGELOG.md - -### THE GAUGE CLASS - -This is the typical interface to the module– it provides a pretty -fire-and-forget interface to displaying your status information. - -``` -var Gauge = require("gauge") - -var gauge = new Gauge([stream], [options]) -``` - -* **stream** – *(optional, default STDERR)* A stream that progress bar - updates are to be written to. Gauge honors backpressure and will pause - most writing if it is indicated. -* **options** – *(optional)* An option object. - -Constructs a new gauge. Gauges are drawn on a single line, and are not drawn -if **stream** isn't a tty and a tty isn't explicitly provided. - -If **stream** is a terminal or if you pass in **tty** to **options** then we -will detect terminal resizes and redraw to fit. We do this by watching for -`resize` events on the tty. (To work around a bug in verisons of Node prior -to 2.5.0, we watch for them on stdout if the tty is stderr.) Resizes to -larger window sizes will be clean, but shrinking the window will always -result in some cruft. - -**IMPORTANT:** If you prevously were passing in a non-tty stream but you still -want output (for example, a stream wrapped by the `ansi` module) then you -need to pass in the **tty** option below, as `gauge` needs access to -the underlying tty in order to do things like terminal resizes and terminal -width detection. - -The **options** object can have the following properties, all of which are -optional: - -* **updateInterval**: How often gauge updates should be drawn, in miliseconds. -* **fixedFramerate**: Defaults to false on node 0.8, true on everything - else. When this is true a timer is created to trigger once every - `updateInterval` ms, when false, updates are printed as soon as they come - in but updates more often than `updateInterval` are ignored. The reason - 0.8 doesn't have this set to true is that it can't `unref` its timer and - so it would stop your program from exiting– if you want to use this - feature with 0.8 just make sure you call `gauge.disable()` before you - expect your program to exit. -* **themes**: A themeset to use when selecting the theme to use. Defaults - to `gauge/themes`, see the [themes] documentation for details. -* **theme**: Select a theme for use, it can be a: - * Theme object, in which case the **themes** is not used. - * The name of a theme, which will be looked up in the current *themes* - object. - * A configuration object with any of `hasUnicode`, `hasColor` or - `platform` keys, which if wlll be used to override our guesses when making - a default theme selection. - - If no theme is selected then a default is picked using a combination of our - best guesses at your OS, color support and unicode support. -* **template**: Describes what you want your gauge to look like. The - default is what npm uses. Detailed [documentation] is later in this - document. -* **hideCursor**: Defaults to true. If true, then the cursor will be hidden - while the gauge is displayed. -* **tty**: The tty that you're ultimately writing to. Defaults to the same - as **stream**. This is used for detecting the width of the terminal and - resizes. The width used is `tty.columns - 1`. If no tty is available then - a width of `79` is assumed. -* **enabled**: Defaults to true if `tty` is a TTY, false otherwise. If true - the gauge starts enabled. If disabled then all update commands are - ignored and no gauge will be printed until you call `.enable()`. -* **Plumbing**: The class to use to actually generate the gauge for - printing. This defaults to `require('gauge/plumbing')` and ordinarly you - shouldn't need to override this. -* **cleanupOnExit**: Defaults to true. Ordinarily we register an exit - handler to make sure your cursor is turned back on and the progress bar - erased when your process exits, even if you Ctrl-C out or otherwise exit - unexpectedly. You can disable this and it won't register the exit handler. - -[has-unicode]: https://www.npmjs.com/package/has-unicode -[themes]: #themes -[documentation]: #templates - -#### `gauge.show(section | status, [completed])` - -The first argument is either the section, the name of the current thing -contributing to progress, or an object with keys like **section**, -**subsection** & **completed** (or any others you have types for in a custom -template). If you don't want to update or set any of these you can pass -`null` and it will be ignored. - -The second argument is the percent completed as a value between 0 and 1. -Without it, completion is just not updated. You'll also note that completion -can be passed in as part of a status object as the first argument. If both -it and the completed argument are passed in, the completed argument wins. - -#### `gauge.hide([cb])` - -Removes the gauge from the terminal. Optionally, callback `cb` after IO has -had an opportunity to happen (currently this just means after `setImmediate` -has called back.) - -It turns out this is important when you're pausing the progress bar on one -filehandle and printing to another– otherwise (with a big enough print) node -can end up printing the "end progress bar" bits to the progress bar filehandle -while other stuff is printing to another filehandle. These getting interleaved -can cause corruption in some terminals. - -#### `gauge.pulse([subsection])` - -* **subsection** – *(optional)* The specific thing that triggered this pulse - -Spins the spinner in the gauge to show output. If **subsection** is -included then it will be combined with the last name passed to `gauge.show`. - -#### `gauge.disable()` - -Hides the gauge and ignores further calls to `show` or `pulse`. - -#### `gauge.enable()` - -Shows the gauge and resumes updating when `show` or `pulse` is called. - -#### `gauge.isEnabled()` - -Returns true if the gauge is enabled. - -#### `gauge.setThemeset(themes)` - -Change the themeset to select a theme from. The same as the `themes` option -used in the constructor. The theme will be reselected from this themeset. - -#### `gauge.setTheme(theme)` - -Change the active theme, will be displayed with the next show or pulse. This can be: - -* Theme object, in which case the **themes** is not used. -* The name of a theme, which will be looked up in the current *themes* - object. -* A configuration object with any of `hasUnicode`, `hasColor` or - `platform` keys, which if wlll be used to override our guesses when making - a default theme selection. - -If no theme is selected then a default is picked using a combination of our -best guesses at your OS, color support and unicode support. - -#### `gauge.setTemplate(template)` - -Change the active template, will be displayed with the next show or pulse - -### Tracking Completion - -If you have more than one thing going on that you want to track completion -of, you may find the related [are-we-there-yet] helpful. It's `change` -event can be wired up to the `show` method to get a more traditional -progress bar interface. - -[are-we-there-yet]: https://www.npmjs.com/package/are-we-there-yet - -### THEMES - -``` -var themes = require('gauge/themes') - -// fetch the default color unicode theme for this platform -var ourTheme = themes({hasUnicode: true, hasColor: true}) - -// fetch the default non-color unicode theme for osx -var ourTheme = themes({hasUnicode: true, hasColor: false, platform: 'darwin'}) - -// create a new theme based on the color ascii theme for this platform -// that brackets the progress bar with arrows -var ourTheme = themes.newTheme(theme(hasUnicode: false, hasColor: true}), { - preProgressbar: '→', - postProgressbar: '←' -}) -``` - -The object returned by `gauge/themes` is an instance of the `ThemeSet` class. - -``` -var ThemeSet = require('gauge/theme-set') -var themes = new ThemeSet() -// or -var themes = require('gauge/themes') -var mythemes = themes.newThemeset() // creates a new themeset based on the default themes -``` - -#### themes(opts) -#### themes.getDefault(opts) - -Theme objects are a function that fetches the default theme based on -platform, unicode and color support. - -Options is an object with the following properties: - -* **hasUnicode** - If true, fetch a unicode theme, if no unicode theme is - available then a non-unicode theme will be used. -* **hasColor** - If true, fetch a color theme, if no color theme is - available a non-color theme will be used. -* **platform** (optional) - Defaults to `process.platform`. If no - platform match is available then `fallback` is used instead. - -If no compatible theme can be found then an error will be thrown with a -`code` of `EMISSINGTHEME`. - -#### themes.addTheme(themeName, themeObj) -#### themes.addTheme(themeName, [parentTheme], newTheme) - -Adds a named theme to the themeset. You can pass in either a theme object, -as returned by `themes.newTheme` or the arguments you'd pass to -`themes.newTheme`. - -#### themes.getThemeNames() - -Return a list of all of the names of the themes in this themeset. Suitable -for use in `themes.getTheme(…)`. - -#### themes.getTheme(name) - -Returns the theme object from this theme set named `name`. - -If `name` does not exist in this themeset an error will be thrown with -a `code` of `EMISSINGTHEME`. - -#### themes.setDefault([opts], themeName) - -`opts` is an object with the following properties. - -* **platform** - Defaults to `'fallback'`. If your theme is platform - specific, specify that here with the platform from `process.platform`, eg, - `win32`, `darwin`, etc. -* **hasUnicode** - Defaults to `false`. If your theme uses unicode you - should set this to true. -* **hasColor** - Defaults to `false`. If your theme uses color you should - set this to true. - -`themeName` is the name of the theme (as given to `addTheme`) to use for -this set of `opts`. - -#### themes.newTheme([parentTheme,] newTheme) - -Create a new theme object based on `parentTheme`. If no `parentTheme` is -provided then a minimal parentTheme that defines functions for rendering the -activity indicator (spinner) and progress bar will be defined. (This -fallback parent is defined in `gauge/base-theme`.) - -newTheme should be a bare object– we'll start by discussing the properties -defined by the default themes: - -* **preProgressbar** - displayed prior to the progress bar, if the progress - bar is displayed. -* **postProgressbar** - displayed after the progress bar, if the progress bar - is displayed. -* **progressBarTheme** - The subtheme passed through to the progress bar - renderer, it's an object with `complete` and `remaining` properties - that are the strings you want repeated for those sections of the progress - bar. -* **activityIndicatorTheme** - The theme for the activity indicator (spinner), - this can either be a string, in which each character is a different step, or - an array of strings. -* **preSubsection** - Displayed as a separator between the `section` and - `subsection` when the latter is printed. - -More generally, themes can have any value that would be a valid value when rendering -templates. The properties in the theme are used when their name matches a type in -the template. Their values can be: - -* **strings & numbers** - They'll be included as is -* **function (values, theme, width)** - Should return what you want in your output. - *values* is an object with values provided via `gauge.show`, - *theme* is the theme specific to this item (see below) or this theme object, - and *width* is the number of characters wide your result should be. - -There are a couple of special prefixes: - -* **pre** - Is shown prior to the property, if its displayed. -* **post** - Is shown after the property, if its displayed. - -And one special suffix: - -* **Theme** - Its value is passed to a function-type item as the theme. - -#### themes.addToAllThemes(theme) - -This *mixes-in* `theme` into all themes currently defined. It also adds it -to the default parent theme for this themeset, so future themes added to -this themeset will get the values from `theme` by default. - -#### themes.newThemeset() - -Copy the current themeset into a new one. This allows you to easily inherit -one themeset from another. - -### TEMPLATES - -A template is an array of objects and strings that, after being evaluated, -will be turned into the gauge line. The default template is: - -```javascript -[ - {type: 'progressbar', length: 20}, - {type: 'activityIndicator', kerning: 1, length: 1}, - {type: 'section', kerning: 1, default: ''}, - {type: 'subsection', kerning: 1, default: ''} -] -``` - -The various template elements can either be **plain strings**, in which case they will -be be included verbatum in the output, or objects with the following properties: - -* *type* can be any of the following plus any keys you pass into `gauge.show` plus - any keys you have on a custom theme. - * `section` – What big thing you're working on now. - * `subsection` – What component of that thing is currently working. - * `activityIndicator` – Shows a spinner using the `activityIndicatorTheme` - from your active theme. - * `progressbar` – A progress bar representing your current `completed` - using the `progressbarTheme` from your active theme. -* *kerning* – Number of spaces that must be between this item and other - items, if this item is displayed at all. -* *maxLength* – The maximum length for this element. If its value is longer it - will be truncated. -* *minLength* – The minimum length for this element. If its value is shorter it - will be padded according to the *align* value. -* *align* – (Default: left) Possible values "left", "right" and "center". Works - as you'd expect from word processors. -* *length* – Provides a single value for both *minLength* and *maxLength*. If both - *length* and *minLength or *maxLength* are specifed then the latter take precedence. -* *value* – A literal value to use for this template item. -* *default* – A default value to use for this template item if a value - wasn't otherwise passed in. - -### PLUMBING - -This is the super simple, assume nothing, do no magic internals used by gauge to -implement its ordinary interface. - -``` -var Plumbing = require('gauge/plumbing') -var gauge = new Plumbing(theme, template, width) -``` - -* **theme**: The theme to use. -* **template**: The template to use. -* **width**: How wide your gauge should be - -#### `gauge.setTheme(theme)` - -Change the active theme. - -#### `gauge.setTemplate(template)` - -Change the active template. - -#### `gauge.setWidth(width)` - -Change the width to render at. - -#### `gauge.hide()` - -Return the string necessary to hide the progress bar - -#### `gauge.hideCursor()` - -Return a string to hide the cursor. - -#### `gauge.showCursor()` - -Return a string to show the cursor. - -#### `gauge.show(status)` - -Using `status` for values, render the provided template with the theme and return -a string that is suitable for printing to update the gauge. diff --git a/node_modules/gauge/base-theme.js b/node_modules/gauge/base-theme.js deleted file mode 100644 index 0b67638..0000000 --- a/node_modules/gauge/base-theme.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict' -var spin = require('./spin.js') -var progressBar = require('./progress-bar.js') - -module.exports = { - activityIndicator: function (values, theme, width) { - if (values.spun == null) return - return spin(theme, values.spun) - }, - progressbar: function (values, theme, width) { - if (values.completed == null) return - return progressBar(theme, width, values.completed) - } -} diff --git a/node_modules/gauge/error.js b/node_modules/gauge/error.js deleted file mode 100644 index d9914ba..0000000 --- a/node_modules/gauge/error.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict' -var util = require('util') - -var User = exports.User = function User (msg) { - var err = new Error(msg) - Error.captureStackTrace(err, User) - err.code = 'EGAUGE' - return err -} - -exports.MissingTemplateValue = function MissingTemplateValue (item, values) { - var err = new User(util.format('Missing template value "%s"', item.type)) - Error.captureStackTrace(err, MissingTemplateValue) - err.template = item - err.values = values - return err -} - -exports.Internal = function Internal (msg) { - var err = new Error(msg) - Error.captureStackTrace(err, Internal) - err.code = 'EGAUGEINTERNAL' - return err -} diff --git a/node_modules/gauge/has-color.js b/node_modules/gauge/has-color.js deleted file mode 100644 index e283a25..0000000 --- a/node_modules/gauge/has-color.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -module.exports = isWin32() || isColorTerm() - -function isWin32 () { - return process.platform === 'win32' -} - -function isColorTerm () { - var termHasColor = /^screen|^xterm|^vt100|color|ansi|cygwin|linux/i - return !!process.env.COLORTERM || termHasColor.test(process.env.TERM) -} diff --git a/node_modules/gauge/index.js b/node_modules/gauge/index.js deleted file mode 100644 index c553240..0000000 --- a/node_modules/gauge/index.js +++ /dev/null @@ -1,233 +0,0 @@ -'use strict' -var Plumbing = require('./plumbing.js') -var hasUnicode = require('has-unicode') -var hasColor = require('./has-color.js') -var onExit = require('signal-exit') -var defaultThemes = require('./themes') -var setInterval = require('./set-interval.js') -var process = require('./process.js') -var setImmediate = require('./set-immediate') - -module.exports = Gauge - -function callWith (obj, method) { - return function () { - return method.call(obj) - } -} - -function Gauge (arg1, arg2) { - var options, writeTo - if (arg1 && arg1.write) { - writeTo = arg1 - options = arg2 || {} - } else if (arg2 && arg2.write) { - writeTo = arg2 - options = arg1 || {} - } else { - writeTo = process.stderr - options = arg1 || arg2 || {} - } - - this._status = { - spun: 0, - section: '', - subsection: '' - } - this._paused = false // are we paused for back pressure? - this._disabled = true // are all progress bar updates disabled? - this._showing = false // do we WANT the progress bar on screen - this._onScreen = false // IS the progress bar on screen - this._needsRedraw = false // should we print something at next tick? - this._hideCursor = options.hideCursor == null ? true : options.hideCursor - this._fixedFramerate = options.fixedFramerate == null - ? !(/^v0\.8\./.test(process.version)) - : options.fixedFramerate - this._lastUpdateAt = null - this._updateInterval = options.updateInterval == null ? 50 : options.updateInterval - - this._themes = options.themes || defaultThemes - this._theme = options.theme - var theme = this._computeTheme(options.theme) - var template = options.template || [ - {type: 'progressbar', length: 20}, - {type: 'activityIndicator', kerning: 1, length: 1}, - {type: 'section', kerning: 1, default: ''}, - {type: 'subsection', kerning: 1, default: ''} - ] - this.setWriteTo(writeTo, options.tty) - var PlumbingClass = options.Plumbing || Plumbing - this._gauge = new PlumbingClass(theme, template, this.getWidth()) - - this._$$doRedraw = callWith(this, this._doRedraw) - this._$$handleSizeChange = callWith(this, this._handleSizeChange) - - this._cleanupOnExit = options.cleanupOnExit == null || options.cleanupOnExit - this._removeOnExit = null - - if (options.enabled || (options.enabled == null && this._tty && this._tty.isTTY)) { - this.enable() - } else { - this.disable() - } -} -Gauge.prototype = {} - -Gauge.prototype.isEnabled = function () { - return !this._disabled -} - -Gauge.prototype.setTemplate = function (template) { - this._gauge.setTemplate(template) - if (this._showing) this._requestRedraw() -} - -Gauge.prototype._computeTheme = function (theme) { - if (!theme) theme = {} - if (typeof theme === 'string') { - theme = this._themes.getTheme(theme) - } else if (theme && (Object.keys(theme).length === 0 || theme.hasUnicode != null || theme.hasColor != null)) { - var useUnicode = theme.hasUnicode == null ? hasUnicode() : theme.hasUnicode - var useColor = theme.hasColor == null ? hasColor : theme.hasColor - theme = this._themes.getDefault({hasUnicode: useUnicode, hasColor: useColor, platform: theme.platform}) - } - return theme -} - -Gauge.prototype.setThemeset = function (themes) { - this._themes = themes - this.setTheme(this._theme) -} - -Gauge.prototype.setTheme = function (theme) { - this._gauge.setTheme(this._computeTheme(theme)) - if (this._showing) this._requestRedraw() - this._theme = theme -} - -Gauge.prototype._requestRedraw = function () { - this._needsRedraw = true - if (!this._fixedFramerate) this._doRedraw() -} - -Gauge.prototype.getWidth = function () { - return ((this._tty && this._tty.columns) || 80) - 1 -} - -Gauge.prototype.setWriteTo = function (writeTo, tty) { - var enabled = !this._disabled - if (enabled) this.disable() - this._writeTo = writeTo - this._tty = tty || - (writeTo === process.stderr && process.stdout.isTTY && process.stdout) || - (writeTo.isTTY && writeTo) || - this._tty - if (this._gauge) this._gauge.setWidth(this.getWidth()) - if (enabled) this.enable() -} - -Gauge.prototype.enable = function () { - if (!this._disabled) return - this._disabled = false - if (this._tty) this._enableEvents() - if (this._showing) this.show() -} - -Gauge.prototype.disable = function () { - if (this._disabled) return - if (this._showing) { - this._lastUpdateAt = null - this._showing = false - this._doRedraw() - this._showing = true - } - this._disabled = true - if (this._tty) this._disableEvents() -} - -Gauge.prototype._enableEvents = function () { - if (this._cleanupOnExit) { - this._removeOnExit = onExit(callWith(this, this.disable)) - } - this._tty.on('resize', this._$$handleSizeChange) - if (this._fixedFramerate) { - this.redrawTracker = setInterval(this._$$doRedraw, this._updateInterval) - if (this.redrawTracker.unref) this.redrawTracker.unref() - } -} - -Gauge.prototype._disableEvents = function () { - this._tty.removeListener('resize', this._$$handleSizeChange) - if (this._fixedFramerate) clearInterval(this.redrawTracker) - if (this._removeOnExit) this._removeOnExit() -} - -Gauge.prototype.hide = function (cb) { - if (this._disabled) return cb && process.nextTick(cb) - if (!this._showing) return cb && process.nextTick(cb) - this._showing = false - this._doRedraw() - cb && setImmediate(cb) -} - -Gauge.prototype.show = function (section, completed) { - this._showing = true - if (typeof section === 'string') { - this._status.section = section - } else if (typeof section === 'object') { - var sectionKeys = Object.keys(section) - for (var ii = 0; ii < sectionKeys.length; ++ii) { - var key = sectionKeys[ii] - this._status[key] = section[key] - } - } - if (completed != null) this._status.completed = completed - if (this._disabled) return - this._requestRedraw() -} - -Gauge.prototype.pulse = function (subsection) { - this._status.subsection = subsection || '' - this._status.spun ++ - if (this._disabled) return - if (!this._showing) return - this._requestRedraw() -} - -Gauge.prototype._handleSizeChange = function () { - this._gauge.setWidth(this._tty.columns - 1) - this._requestRedraw() -} - -Gauge.prototype._doRedraw = function () { - if (this._disabled || this._paused) return - if (!this._fixedFramerate) { - var now = Date.now() - if (this._lastUpdateAt && now - this._lastUpdateAt < this._updateInterval) return - this._lastUpdateAt = now - } - if (!this._showing && this._onScreen) { - this._onScreen = false - var result = this._gauge.hide() - if (this._hideCursor) { - result += this._gauge.showCursor() - } - return this._writeTo.write(result) - } - if (!this._showing && !this._onScreen) return - if (this._showing && !this._onScreen) { - this._onScreen = true - this._needsRedraw = true - if (this._hideCursor) { - this._writeTo.write(this._gauge.hideCursor()) - } - } - if (!this._needsRedraw) return - if (!this._writeTo.write(this._gauge.show(this._status))) { - this._paused = true - this._writeTo.on('drain', callWith(this, function () { - this._paused = false - this._doRedraw() - })) - } -} diff --git a/node_modules/gauge/package.json b/node_modules/gauge/package.json deleted file mode 100644 index a6379b9..0000000 --- a/node_modules/gauge/package.json +++ /dev/null @@ -1,91 +0,0 @@ -{ - "_from": "gauge@~2.7.3", - "_id": "gauge@2.7.4", - "_inBundle": false, - "_integrity": "sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=", - "_location": "/gauge", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "gauge@~2.7.3", - "name": "gauge", - "escapedName": "gauge", - "rawSpec": "~2.7.3", - "saveSpec": null, - "fetchSpec": "~2.7.3" - }, - "_requiredBy": [ - "/npmlog" - ], - "_resolved": "https://registry.npmjs.org/gauge/-/gauge-2.7.4.tgz", - "_shasum": "2c03405c7538c39d7eb37b317022e325fb018bf7", - "_spec": "gauge@~2.7.3", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/npmlog", - "author": { - "name": "Rebecca Turner", - "email": "me@re-becca.org" - }, - "bugs": { - "url": "https://github.com/iarna/gauge/issues" - }, - "bundleDependencies": false, - "dependencies": { - "aproba": "^1.0.3", - "console-control-strings": "^1.0.0", - "has-unicode": "^2.0.0", - "object-assign": "^4.1.0", - "signal-exit": "^3.0.0", - "string-width": "^1.0.1", - "strip-ansi": "^3.0.1", - "wide-align": "^1.1.0" - }, - "deprecated": false, - "description": "A terminal based horizontal guage", - "devDependencies": { - "readable-stream": "^2.0.6", - "require-inject": "^1.4.0", - "standard": "^7.1.2", - "tap": "^5.7.2", - "through2": "^2.0.0" - }, - "files": [ - "base-theme.js", - "CHANGELOG.md", - "error.js", - "has-color.js", - "index.js", - "LICENSE", - "package.json", - "plumbing.js", - "process.js", - "progress-bar.js", - "README.md", - "render-template.js", - "set-immediate.js", - "set-interval.js", - "spin.js", - "template-item.js", - "theme-set.js", - "themes.js", - "wide-truncate.js" - ], - "homepage": "https://github.com/iarna/gauge", - "keywords": [ - "progressbar", - "progress", - "gauge" - ], - "license": "ISC", - "main": "index.js", - "name": "gauge", - "repository": { - "type": "git", - "url": "git+https://github.com/iarna/gauge.git" - }, - "scripts": { - "prepublish": "rm -f *~", - "test": "standard && tap test/*.js --coverage" - }, - "version": "2.7.4" -} diff --git a/node_modules/gauge/plumbing.js b/node_modules/gauge/plumbing.js deleted file mode 100644 index 1afb4af..0000000 --- a/node_modules/gauge/plumbing.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict' -var consoleControl = require('console-control-strings') -var renderTemplate = require('./render-template.js') -var validate = require('aproba') - -var Plumbing = module.exports = function (theme, template, width) { - if (!width) width = 80 - validate('OAN', [theme, template, width]) - this.showing = false - this.theme = theme - this.width = width - this.template = template -} -Plumbing.prototype = {} - -Plumbing.prototype.setTheme = function (theme) { - validate('O', [theme]) - this.theme = theme -} - -Plumbing.prototype.setTemplate = function (template) { - validate('A', [template]) - this.template = template -} - -Plumbing.prototype.setWidth = function (width) { - validate('N', [width]) - this.width = width -} - -Plumbing.prototype.hide = function () { - return consoleControl.gotoSOL() + consoleControl.eraseLine() -} - -Plumbing.prototype.hideCursor = consoleControl.hideCursor - -Plumbing.prototype.showCursor = consoleControl.showCursor - -Plumbing.prototype.show = function (status) { - var values = Object.create(this.theme) - for (var key in status) { - values[key] = status[key] - } - - return renderTemplate(this.width, this.template, values).trim() + - consoleControl.color('reset') + - consoleControl.eraseLine() + consoleControl.gotoSOL() -} diff --git a/node_modules/gauge/process.js b/node_modules/gauge/process.js deleted file mode 100644 index 05e8569..0000000 --- a/node_modules/gauge/process.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict' -// this exists so we can replace it during testing -module.exports = process diff --git a/node_modules/gauge/progress-bar.js b/node_modules/gauge/progress-bar.js deleted file mode 100644 index 7f8dd68..0000000 --- a/node_modules/gauge/progress-bar.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict' -var validate = require('aproba') -var renderTemplate = require('./render-template.js') -var wideTruncate = require('./wide-truncate') -var stringWidth = require('string-width') - -module.exports = function (theme, width, completed) { - validate('ONN', [theme, width, completed]) - if (completed < 0) completed = 0 - if (completed > 1) completed = 1 - if (width <= 0) return '' - var sofar = Math.round(width * completed) - var rest = width - sofar - var template = [ - {type: 'complete', value: repeat(theme.complete, sofar), length: sofar}, - {type: 'remaining', value: repeat(theme.remaining, rest), length: rest} - ] - return renderTemplate(width, template, theme) -} - -// lodash's way of repeating -function repeat (string, width) { - var result = '' - var n = width - do { - if (n % 2) { - result += string - } - n = Math.floor(n / 2) - /*eslint no-self-assign: 0*/ - string += string - } while (n && stringWidth(result) < width) - - return wideTruncate(result, width) -} diff --git a/node_modules/gauge/render-template.js b/node_modules/gauge/render-template.js deleted file mode 100644 index 3261bfb..0000000 --- a/node_modules/gauge/render-template.js +++ /dev/null @@ -1,181 +0,0 @@ -'use strict' -var align = require('wide-align') -var validate = require('aproba') -var objectAssign = require('object-assign') -var wideTruncate = require('./wide-truncate') -var error = require('./error') -var TemplateItem = require('./template-item') - -function renderValueWithValues (values) { - return function (item) { - return renderValue(item, values) - } -} - -var renderTemplate = module.exports = function (width, template, values) { - var items = prepareItems(width, template, values) - var rendered = items.map(renderValueWithValues(values)).join('') - return align.left(wideTruncate(rendered, width), width) -} - -function preType (item) { - var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1) - return 'pre' + cappedTypeName -} - -function postType (item) { - var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1) - return 'post' + cappedTypeName -} - -function hasPreOrPost (item, values) { - if (!item.type) return - return values[preType(item)] || values[postType(item)] -} - -function generatePreAndPost (baseItem, parentValues) { - var item = objectAssign({}, baseItem) - var values = Object.create(parentValues) - var template = [] - var pre = preType(item) - var post = postType(item) - if (values[pre]) { - template.push({value: values[pre]}) - values[pre] = null - } - item.minLength = null - item.length = null - item.maxLength = null - template.push(item) - values[item.type] = values[item.type] - if (values[post]) { - template.push({value: values[post]}) - values[post] = null - } - return function ($1, $2, length) { - return renderTemplate(length, template, values) - } -} - -function prepareItems (width, template, values) { - function cloneAndObjectify (item, index, arr) { - var cloned = new TemplateItem(item, width) - var type = cloned.type - if (cloned.value == null) { - if (!(type in values)) { - if (cloned.default == null) { - throw new error.MissingTemplateValue(cloned, values) - } else { - cloned.value = cloned.default - } - } else { - cloned.value = values[type] - } - } - if (cloned.value == null || cloned.value === '') return null - cloned.index = index - cloned.first = index === 0 - cloned.last = index === arr.length - 1 - if (hasPreOrPost(cloned, values)) cloned.value = generatePreAndPost(cloned, values) - return cloned - } - - var output = template.map(cloneAndObjectify).filter(function (item) { return item != null }) - - var outputLength = 0 - var remainingSpace = width - var variableCount = output.length - - function consumeSpace (length) { - if (length > remainingSpace) length = remainingSpace - outputLength += length - remainingSpace -= length - } - - function finishSizing (item, length) { - if (item.finished) throw new error.Internal('Tried to finish template item that was already finished') - if (length === Infinity) throw new error.Internal('Length of template item cannot be infinity') - if (length != null) item.length = length - item.minLength = null - item.maxLength = null - --variableCount - item.finished = true - if (item.length == null) item.length = item.getBaseLength() - if (item.length == null) throw new error.Internal('Finished template items must have a length') - consumeSpace(item.getLength()) - } - - output.forEach(function (item) { - if (!item.kerning) return - var prevPadRight = item.first ? 0 : output[item.index - 1].padRight - if (!item.first && prevPadRight < item.kerning) item.padLeft = item.kerning - prevPadRight - if (!item.last) item.padRight = item.kerning - }) - - // Finish any that have a fixed (literal or intuited) length - output.forEach(function (item) { - if (item.getBaseLength() == null) return - finishSizing(item) - }) - - var resized = 0 - var resizing - var hunkSize - do { - resizing = false - hunkSize = Math.round(remainingSpace / variableCount) - output.forEach(function (item) { - if (item.finished) return - if (!item.maxLength) return - if (item.getMaxLength() < hunkSize) { - finishSizing(item, item.maxLength) - resizing = true - } - }) - } while (resizing && resized++ < output.length) - if (resizing) throw new error.Internal('Resize loop iterated too many times while determining maxLength') - - resized = 0 - do { - resizing = false - hunkSize = Math.round(remainingSpace / variableCount) - output.forEach(function (item) { - if (item.finished) return - if (!item.minLength) return - if (item.getMinLength() >= hunkSize) { - finishSizing(item, item.minLength) - resizing = true - } - }) - } while (resizing && resized++ < output.length) - if (resizing) throw new error.Internal('Resize loop iterated too many times while determining minLength') - - hunkSize = Math.round(remainingSpace / variableCount) - output.forEach(function (item) { - if (item.finished) return - finishSizing(item, hunkSize) - }) - - return output -} - -function renderFunction (item, values, length) { - validate('OON', arguments) - if (item.type) { - return item.value(values, values[item.type + 'Theme'] || {}, length) - } else { - return item.value(values, {}, length) - } -} - -function renderValue (item, values) { - var length = item.getBaseLength() - var value = typeof item.value === 'function' ? renderFunction(item, values, length) : item.value - if (value == null || value === '') return '' - var alignWith = align[item.align] || align.left - var leftPadding = item.padLeft ? align.left('', item.padLeft) : '' - var rightPadding = item.padRight ? align.right('', item.padRight) : '' - var truncated = wideTruncate(String(value), length) - var aligned = alignWith(truncated, length) - return leftPadding + aligned + rightPadding -} diff --git a/node_modules/gauge/set-immediate.js b/node_modules/gauge/set-immediate.js deleted file mode 100644 index 6650a48..0000000 --- a/node_modules/gauge/set-immediate.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict' -var process = require('./process') -try { - module.exports = setImmediate -} catch (ex) { - module.exports = process.nextTick -} diff --git a/node_modules/gauge/set-interval.js b/node_modules/gauge/set-interval.js deleted file mode 100644 index 5761987..0000000 --- a/node_modules/gauge/set-interval.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict' -// this exists so we can replace it during testing -module.exports = setInterval diff --git a/node_modules/gauge/spin.js b/node_modules/gauge/spin.js deleted file mode 100644 index 34142ee..0000000 --- a/node_modules/gauge/spin.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict' - -module.exports = function spin (spinstr, spun) { - return spinstr[spun % spinstr.length] -} diff --git a/node_modules/gauge/template-item.js b/node_modules/gauge/template-item.js deleted file mode 100644 index e46f447..0000000 --- a/node_modules/gauge/template-item.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict' -var stringWidth = require('string-width') - -module.exports = TemplateItem - -function isPercent (num) { - if (typeof num !== 'string') return false - return num.slice(-1) === '%' -} - -function percent (num) { - return Number(num.slice(0, -1)) / 100 -} - -function TemplateItem (values, outputLength) { - this.overallOutputLength = outputLength - this.finished = false - this.type = null - this.value = null - this.length = null - this.maxLength = null - this.minLength = null - this.kerning = null - this.align = 'left' - this.padLeft = 0 - this.padRight = 0 - this.index = null - this.first = null - this.last = null - if (typeof values === 'string') { - this.value = values - } else { - for (var prop in values) this[prop] = values[prop] - } - // Realize percents - if (isPercent(this.length)) { - this.length = Math.round(this.overallOutputLength * percent(this.length)) - } - if (isPercent(this.minLength)) { - this.minLength = Math.round(this.overallOutputLength * percent(this.minLength)) - } - if (isPercent(this.maxLength)) { - this.maxLength = Math.round(this.overallOutputLength * percent(this.maxLength)) - } - return this -} - -TemplateItem.prototype = {} - -TemplateItem.prototype.getBaseLength = function () { - var length = this.length - if (length == null && typeof this.value === 'string' && this.maxLength == null && this.minLength == null) { - length = stringWidth(this.value) - } - return length -} - -TemplateItem.prototype.getLength = function () { - var length = this.getBaseLength() - if (length == null) return null - return length + this.padLeft + this.padRight -} - -TemplateItem.prototype.getMaxLength = function () { - if (this.maxLength == null) return null - return this.maxLength + this.padLeft + this.padRight -} - -TemplateItem.prototype.getMinLength = function () { - if (this.minLength == null) return null - return this.minLength + this.padLeft + this.padRight -} - diff --git a/node_modules/gauge/theme-set.js b/node_modules/gauge/theme-set.js deleted file mode 100644 index 68971d5..0000000 --- a/node_modules/gauge/theme-set.js +++ /dev/null @@ -1,115 +0,0 @@ -'use strict' -var objectAssign = require('object-assign') - -module.exports = function () { - return ThemeSetProto.newThemeSet() -} - -var ThemeSetProto = {} - -ThemeSetProto.baseTheme = require('./base-theme.js') - -ThemeSetProto.newTheme = function (parent, theme) { - if (!theme) { - theme = parent - parent = this.baseTheme - } - return objectAssign({}, parent, theme) -} - -ThemeSetProto.getThemeNames = function () { - return Object.keys(this.themes) -} - -ThemeSetProto.addTheme = function (name, parent, theme) { - this.themes[name] = this.newTheme(parent, theme) -} - -ThemeSetProto.addToAllThemes = function (theme) { - var themes = this.themes - Object.keys(themes).forEach(function (name) { - objectAssign(themes[name], theme) - }) - objectAssign(this.baseTheme, theme) -} - -ThemeSetProto.getTheme = function (name) { - if (!this.themes[name]) throw this.newMissingThemeError(name) - return this.themes[name] -} - -ThemeSetProto.setDefault = function (opts, name) { - if (name == null) { - name = opts - opts = {} - } - var platform = opts.platform == null ? 'fallback' : opts.platform - var hasUnicode = !!opts.hasUnicode - var hasColor = !!opts.hasColor - if (!this.defaults[platform]) this.defaults[platform] = {true: {}, false: {}} - this.defaults[platform][hasUnicode][hasColor] = name -} - -ThemeSetProto.getDefault = function (opts) { - if (!opts) opts = {} - var platformName = opts.platform || process.platform - var platform = this.defaults[platformName] || this.defaults.fallback - var hasUnicode = !!opts.hasUnicode - var hasColor = !!opts.hasColor - if (!platform) throw this.newMissingDefaultThemeError(platformName, hasUnicode, hasColor) - if (!platform[hasUnicode][hasColor]) { - if (hasUnicode && hasColor && platform[!hasUnicode][hasColor]) { - hasUnicode = false - } else if (hasUnicode && hasColor && platform[hasUnicode][!hasColor]) { - hasColor = false - } else if (hasUnicode && hasColor && platform[!hasUnicode][!hasColor]) { - hasUnicode = false - hasColor = false - } else if (hasUnicode && !hasColor && platform[!hasUnicode][hasColor]) { - hasUnicode = false - } else if (!hasUnicode && hasColor && platform[hasUnicode][!hasColor]) { - hasColor = false - } else if (platform === this.defaults.fallback) { - throw this.newMissingDefaultThemeError(platformName, hasUnicode, hasColor) - } - } - if (platform[hasUnicode][hasColor]) { - return this.getTheme(platform[hasUnicode][hasColor]) - } else { - return this.getDefault(objectAssign({}, opts, {platform: 'fallback'})) - } -} - -ThemeSetProto.newMissingThemeError = function newMissingThemeError (name) { - var err = new Error('Could not find a gauge theme named "' + name + '"') - Error.captureStackTrace.call(err, newMissingThemeError) - err.theme = name - err.code = 'EMISSINGTHEME' - return err -} - -ThemeSetProto.newMissingDefaultThemeError = function newMissingDefaultThemeError (platformName, hasUnicode, hasColor) { - var err = new Error( - 'Could not find a gauge theme for your platform/unicode/color use combo:\n' + - ' platform = ' + platformName + '\n' + - ' hasUnicode = ' + hasUnicode + '\n' + - ' hasColor = ' + hasColor) - Error.captureStackTrace.call(err, newMissingDefaultThemeError) - err.platform = platformName - err.hasUnicode = hasUnicode - err.hasColor = hasColor - err.code = 'EMISSINGTHEME' - return err -} - -ThemeSetProto.newThemeSet = function () { - var themeset = function (opts) { - return themeset.getDefault(opts) - } - return objectAssign(themeset, ThemeSetProto, { - themes: objectAssign({}, this.themes), - baseTheme: objectAssign({}, this.baseTheme), - defaults: JSON.parse(JSON.stringify(this.defaults || {})) - }) -} - diff --git a/node_modules/gauge/themes.js b/node_modules/gauge/themes.js deleted file mode 100644 index eb5a4f5..0000000 --- a/node_modules/gauge/themes.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict' -var consoleControl = require('console-control-strings') -var ThemeSet = require('./theme-set.js') - -var themes = module.exports = new ThemeSet() - -themes.addTheme('ASCII', { - preProgressbar: '[', - postProgressbar: ']', - progressbarTheme: { - complete: '#', - remaining: '.' - }, - activityIndicatorTheme: '-\\|/', - preSubsection: '>' -}) - -themes.addTheme('colorASCII', themes.getTheme('ASCII'), { - progressbarTheme: { - preComplete: consoleControl.color('inverse'), - complete: ' ', - postComplete: consoleControl.color('stopInverse'), - preRemaining: consoleControl.color('brightBlack'), - remaining: '.', - postRemaining: consoleControl.color('reset') - } -}) - -themes.addTheme('brailleSpinner', { - preProgressbar: '⸨', - postProgressbar: '⸩', - progressbarTheme: { - complete: '░', - remaining: '⠂' - }, - activityIndicatorTheme: '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏', - preSubsection: '>' -}) - -themes.addTheme('colorBrailleSpinner', themes.getTheme('brailleSpinner'), { - progressbarTheme: { - preComplete: consoleControl.color('inverse'), - complete: ' ', - postComplete: consoleControl.color('stopInverse'), - preRemaining: consoleControl.color('brightBlack'), - remaining: '░', - postRemaining: consoleControl.color('reset') - } -}) - -themes.setDefault({}, 'ASCII') -themes.setDefault({hasColor: true}, 'colorASCII') -themes.setDefault({platform: 'darwin', hasUnicode: true}, 'brailleSpinner') -themes.setDefault({platform: 'darwin', hasUnicode: true, hasColor: true}, 'colorBrailleSpinner') diff --git a/node_modules/gauge/wide-truncate.js b/node_modules/gauge/wide-truncate.js deleted file mode 100644 index c531bc4..0000000 --- a/node_modules/gauge/wide-truncate.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict' -var stringWidth = require('string-width') -var stripAnsi = require('strip-ansi') - -module.exports = wideTruncate - -function wideTruncate (str, target) { - if (stringWidth(str) === 0) return str - if (target <= 0) return '' - if (stringWidth(str) <= target) return str - - // We compute the number of bytes of ansi sequences here and add - // that to our initial truncation to ensure that we don't slice one - // that we want to keep in half. - var noAnsi = stripAnsi(str) - var ansiSize = str.length + noAnsi.length - var truncated = str.slice(0, target + ansiSize) - - // we have to shrink the result to account for our ansi sequence buffer - // (if an ansi sequence was truncated) and double width characters. - while (stringWidth(truncated) > target) { - truncated = truncated.slice(0, -1) - } - return truncated -} diff --git a/node_modules/github-from-package/.travis.yml b/node_modules/github-from-package/.travis.yml deleted file mode 100644 index 895dbd3..0000000 --- a/node_modules/github-from-package/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 diff --git a/node_modules/github-from-package/LICENSE b/node_modules/github-from-package/LICENSE deleted file mode 100644 index ee27ba4..0000000 --- a/node_modules/github-from-package/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -This software is released under the MIT license: - -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/github-from-package/example/package.json b/node_modules/github-from-package/example/package.json deleted file mode 100644 index 03494f4..0000000 --- a/node_modules/github-from-package/example/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "beep-boop", - "version": "1.2.3", - "repository" : { - "type" : "git", - "url": "git@github.com:substack/beep-boop.git" - } -} diff --git a/node_modules/github-from-package/example/url.js b/node_modules/github-from-package/example/url.js deleted file mode 100644 index 138fb8a..0000000 --- a/node_modules/github-from-package/example/url.js +++ /dev/null @@ -1,3 +0,0 @@ -var github = require('../'); -var url = github(require('./package.json')); -console.log(url); diff --git a/node_modules/github-from-package/index.js b/node_modules/github-from-package/index.js deleted file mode 100644 index 3d1d657..0000000 --- a/node_modules/github-from-package/index.js +++ /dev/null @@ -1,17 +0,0 @@ -module.exports = function (pkg) { - var m; - if (m = match(JSON.stringify(pkg.repository))) { - return m; - } - else if (m = match(JSON.stringify(pkg))) { - return m; - } - return undefined; -}; - -function match (str) { - var m = /\bgithub.com[:\/]([^\/"]+)\/([^\/"]+)/.exec(str); - if (m) { - return 'https://github.com/' + m[1] + '/' + m[2].replace(/\.git$/, ''); - } -} diff --git a/node_modules/github-from-package/package.json b/node_modules/github-from-package/package.json deleted file mode 100644 index d19d44a..0000000 --- a/node_modules/github-from-package/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "_from": "github-from-package@0.0.0", - "_id": "github-from-package@0.0.0", - "_inBundle": false, - "_integrity": "sha1-l/tdlr/eiXMxPyDoKI75oWf6ZM4=", - "_location": "/github-from-package", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "github-from-package@0.0.0", - "name": "github-from-package", - "escapedName": "github-from-package", - "rawSpec": "0.0.0", - "saveSpec": null, - "fetchSpec": "0.0.0" - }, - "_requiredBy": [ - "/prebuild-install" - ], - "_resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", - "_shasum": "97fb5d96bfde8973313f20e8288ef9a167fa64ce", - "_spec": "github-from-package@0.0.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/prebuild-install", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "bugs": { - "url": "https://github.com/substack/github-from-package/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "return the github url from a package.json file", - "devDependencies": { - "tap": "~0.3.0", - "tape": "~0.1.5" - }, - "homepage": "https://github.com/substack/github-from-package", - "keywords": [ - "github", - "package.json", - "npm", - "repository" - ], - "license": "MIT", - "main": "index.js", - "name": "github-from-package", - "repository": { - "type": "git", - "url": "git://github.com/substack/github-from-package.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "version": "0.0.0" -} diff --git a/node_modules/github-from-package/readme.markdown b/node_modules/github-from-package/readme.markdown deleted file mode 100644 index 5ba397d..0000000 --- a/node_modules/github-from-package/readme.markdown +++ /dev/null @@ -1,53 +0,0 @@ -# github-from-package - -return the github url from a package.json file - -[![build status](https://secure.travis-ci.org/substack/github-from-package.png)](http://travis-ci.org/substack/github-from-package) - -# example - -For the `./package.json` file: - -``` json -{ - "name": "beep-boop", - "version": "1.2.3", - "repository" : { - "type" : "git", - "url": "git@github.com:substack/beep-boop.git" - } -} -``` - -``` js -var github = require('github-from-package'); -var url = github(require('./package.json')); -console.log(url); -``` - -``` -https://github.com/substack/beep-boop -``` - -# methods - -``` js -var github = require('github-from-package') -``` - -## var url = github(pkg) - -Return the most likely github url from the package.json contents `pkg`. If no -github url can be determined, return `undefined`. - -# install - -With [npm](https://npmjs.org) do: - -``` -npm install github-from-package -``` - -# license - -MIT diff --git a/node_modules/github-from-package/test/a.json b/node_modules/github-from-package/test/a.json deleted file mode 100644 index 03494f4..0000000 --- a/node_modules/github-from-package/test/a.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "beep-boop", - "version": "1.2.3", - "repository" : { - "type" : "git", - "url": "git@github.com:substack/beep-boop.git" - } -} diff --git a/node_modules/github-from-package/test/b.json b/node_modules/github-from-package/test/b.json deleted file mode 100644 index 0209325..0000000 --- a/node_modules/github-from-package/test/b.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "beep-boop", - "version": "1.2.3", - "repository" : "git@github.com:substack/beep-boop.git" -} diff --git a/node_modules/github-from-package/test/c.json b/node_modules/github-from-package/test/c.json deleted file mode 100644 index 65f6dda..0000000 --- a/node_modules/github-from-package/test/c.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "beep-boop", - "version": "1.2.3", - "repository" : "https://github.com/substack/beep-boop.git" -} diff --git a/node_modules/github-from-package/test/d.json b/node_modules/github-from-package/test/d.json deleted file mode 100644 index c61f3cd..0000000 --- a/node_modules/github-from-package/test/d.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "beep-boop", - "version": "1.2.3", - "repository" : { - "url": "https://github.com/substack/beep-boop" - } -} diff --git a/node_modules/github-from-package/test/e.json b/node_modules/github-from-package/test/e.json deleted file mode 100644 index 770b438..0000000 --- a/node_modules/github-from-package/test/e.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "beep-boop", - "version": "1.2.3", - "homepage": "https://github.com/substack/beep-boop/issues" -} diff --git a/node_modules/github-from-package/test/url.js b/node_modules/github-from-package/test/url.js deleted file mode 100644 index d5a0a66..0000000 --- a/node_modules/github-from-package/test/url.js +++ /dev/null @@ -1,19 +0,0 @@ -var test = require('tape'); -var github = require('../'); -var packages = { - a : require('./a.json'), - b : require('./b.json'), - c : require('./c.json'), - d : require('./d.json'), - e : require('./e.json') -}; - -test(function (t) { - t.plan(5); - var url = 'https://github.com/substack/beep-boop'; - t.equal(url, github(packages.a), 'a.json comparison'); - t.equal(url, github(packages.b), 'b.json comparison'); - t.equal(url, github(packages.c), 'c.json comparison'); - t.equal(url, github(packages.d), 'd.json comparison'); - t.equal(url, github(packages.e), 'e.json comparison'); -}); diff --git a/node_modules/has-symbols/.eslintrc b/node_modules/has-symbols/.eslintrc deleted file mode 100644 index 2d9a66a..0000000 --- a/node_modules/has-symbols/.eslintrc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "max-statements-per-line": [2, { "max": 2 }], - "no-magic-numbers": 0, - "multiline-comment-style": 0, - } -} diff --git a/node_modules/has-symbols/.github/FUNDING.yml b/node_modules/has-symbols/.github/FUNDING.yml deleted file mode 100644 index 04cf87e..0000000 --- a/node_modules/has-symbols/.github/FUNDING.yml +++ /dev/null @@ -1,12 +0,0 @@ -# These are supported funding model platforms - -github: [ljharb] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: npm/has-symbols -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-symbols/.github/workflows/rebase.yml b/node_modules/has-symbols/.github/workflows/rebase.yml deleted file mode 100644 index 436cb79..0000000 --- a/node_modules/has-symbols/.github/workflows/rebase.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Automatic Rebase - -on: [pull_request] - -jobs: - _: - name: "Automatic Rebase" - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v1 - - uses: ljharb/rebase@master - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/node_modules/has-symbols/.travis.yml b/node_modules/has-symbols/.travis.yml deleted file mode 100644 index 2d1c1d2..0000000 --- a/node_modules/has-symbols/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -version: ~> 1.0 -language: node_js -os: - - linux -import: - - ljharb/travis-ci:node/all.yml - - ljharb/travis-ci:node/pretest.yml - - ljharb/travis-ci:node/posttest.yml - - ljharb/travis-ci:node/coverage.yml -matrix: - allow_failures: - - env: COVERAGE=true diff --git a/node_modules/has-symbols/CHANGELOG.md b/node_modules/has-symbols/CHANGELOG.md deleted file mode 100644 index 4dcac04..0000000 --- a/node_modules/has-symbols/CHANGELOG.md +++ /dev/null @@ -1,34 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). - -## [v1.0.1](https://github.com/inspect-js/has-symbols/compare/v1.0.0...v1.0.1) - 2019-11-17 - -### Commits - -- [Tests] use shared travis-ci configs [`ce396c9`](https://github.com/inspect-js/has-symbols/commit/ce396c9419ff11c43d0da5d05cdbb79f7fb42229) -- [Tests] up to `node` `v12.4`, `v11.15`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.17`, `v4.9`; use `nvm install-latest-npm` [`0690732`](https://github.com/inspect-js/has-symbols/commit/0690732801f47ab429f39ba1962f522d5c462d6b) -- [meta] add `auto-changelog` [`2163d0b`](https://github.com/inspect-js/has-symbols/commit/2163d0b7f36343076b8f947cd1667dd1750f26fc) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `safe-publish-latest`, `tape` [`8e0951f`](https://github.com/inspect-js/has-symbols/commit/8e0951f1a7a2e52068222b7bb73511761e6e4d9c) -- [actions] add automatic rebasing / merge commit blocking [`b09cdb7`](https://github.com/inspect-js/has-symbols/commit/b09cdb7cd7ee39e7a769878f56e2d6066f5ccd1d) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `core-js`, `get-own-property-symbols`, `tape` [`1dd42cd`](https://github.com/inspect-js/has-symbols/commit/1dd42cd86183ed0c50f99b1062345c458babca91) -- [meta] create FUNDING.yml [`aa57a17`](https://github.com/inspect-js/has-symbols/commit/aa57a17b19708906d1927f821ea8e73394d84ca4) -- Only apps should have lockfiles [`a2d8bea`](https://github.com/inspect-js/has-symbols/commit/a2d8bea23a97d15c09eaf60f5b107fcf9a4d57aa) -- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`9e96cb7`](https://github.com/inspect-js/has-symbols/commit/9e96cb783746cbed0c10ef78e599a8eaa7ebe193) -- [meta] add `funding` field [`a0b32cf`](https://github.com/inspect-js/has-symbols/commit/a0b32cf68e803f963c1639b6d47b0a9d6440bab0) -- [Dev Deps] update `safe-publish-latest` [`cb9f0a5`](https://github.com/inspect-js/has-symbols/commit/cb9f0a521a3a1790f1064d437edd33bb6c3d6af0) - -## v1.0.0 - 2016-09-19 - -### Commits - -- Tests. [`ecb6eb9`](https://github.com/inspect-js/has-symbols/commit/ecb6eb934e4883137f3f93b965ba5e0a98df430d) -- package.json [`88a337c`](https://github.com/inspect-js/has-symbols/commit/88a337cee0864a0da35f5d19e69ff0ef0150e46a) -- Initial commit [`42e1e55`](https://github.com/inspect-js/has-symbols/commit/42e1e5502536a2b8ac529c9443984acd14836b1c) -- Initial implementation. [`33f5cc6`](https://github.com/inspect-js/has-symbols/commit/33f5cc6cdff86e2194b081ee842bfdc63caf43fb) -- read me [`01f1170`](https://github.com/inspect-js/has-symbols/commit/01f1170188ff7cb1558aa297f6ba5b516c6d7b0c) diff --git a/node_modules/has-symbols/LICENSE b/node_modules/has-symbols/LICENSE deleted file mode 100644 index df31cbf..0000000 --- a/node_modules/has-symbols/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016 Jordan Harband - -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/has-symbols/README.md b/node_modules/has-symbols/README.md deleted file mode 100644 index b27b31a..0000000 --- a/node_modules/has-symbols/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# has-symbols [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -Determine if the JS environment has Symbol support. Supports spec, or shams. - -## Example - -```js -var hasSymbols = require('has-symbols'); - -hasSymbols() === true; // if the environment has native Symbol support. Not polyfillable, not forgeable. - -var hasSymbolsKinda = require('has-symbols/shams'); -hasSymbolsKinda() === true; // if the environment has a Symbol sham that mostly follows the spec. -``` - -## Supported Symbol shams - - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) - - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/has-symbols -[2]: http://versionbadg.es/ljharb/has-symbols.svg -[3]: https://travis-ci.org/ljharb/has-symbols.svg -[4]: https://travis-ci.org/ljharb/has-symbols -[5]: https://david-dm.org/ljharb/has-symbols.svg -[6]: https://david-dm.org/ljharb/has-symbols -[7]: https://david-dm.org/ljharb/has-symbols/dev-status.svg -[8]: https://david-dm.org/ljharb/has-symbols#info=devDependencies -[9]: https://ci.testling.com/ljharb/has-symbols.png -[10]: https://ci.testling.com/ljharb/has-symbols -[11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/has-symbols.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/has-symbols.svg -[downloads-url]: http://npm-stat.com/charts.html?package=has-symbols diff --git a/node_modules/has-symbols/index.js b/node_modules/has-symbols/index.js deleted file mode 100644 index f72159e..0000000 --- a/node_modules/has-symbols/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var origSymbol = global.Symbol; -var hasSymbolSham = require('./shams'); - -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; diff --git a/node_modules/has-symbols/package.json b/node_modules/has-symbols/package.json deleted file mode 100644 index 0268bc0..0000000 --- a/node_modules/has-symbols/package.json +++ /dev/null @@ -1,122 +0,0 @@ -{ - "_from": "has-symbols@^1.0.1", - "_id": "has-symbols@1.0.1", - "_inBundle": false, - "_integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==", - "_location": "/has-symbols", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "has-symbols@^1.0.1", - "name": "has-symbols", - "escapedName": "has-symbols", - "rawSpec": "^1.0.1", - "saveSpec": null, - "fetchSpec": "^1.0.1" - }, - "_requiredBy": [ - "/es-abstract", - "/is-symbol", - "/is-typed-array", - "/object.assign", - "/which-typed-array" - ], - "_resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", - "_shasum": "9f5214758a44196c406d9bd76cebf81ec2dd31e8", - "_spec": "has-symbols@^1.0.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/es-abstract", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - }, - "auto-changelog": { - "output": "CHANGELOG.md", - "template": "keepachangelog", - "unreleased": false, - "commitLimit": false, - "backfillLimit": false - }, - "bugs": { - "url": "https://github.com/ljharb/has-symbols/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "Determine if the JS environment has Symbol support. Supports spec, or shams.", - "devDependencies": { - "@ljharb/eslint-config": "^15.0.1", - "auto-changelog": "^1.16.2", - "core-js": "^2.6.10", - "eslint": "^6.6.0", - "get-own-property-symbols": "^0.9.4", - "safe-publish-latest": "^1.1.4", - "tape": "^4.11.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "homepage": "https://github.com/ljharb/has-symbols#readme", - "keywords": [ - "Symbol", - "symbols", - "typeof", - "sham", - "polyfill", - "native", - "core-js", - "ES6" - ], - "license": "MIT", - "main": "index.js", - "name": "has-symbols", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/has-symbols.git" - }, - "scripts": { - "lint": "eslint *.js", - "posttest": "npx aud", - "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", - "prepublish": "safe-publish-latest", - "pretest": "npm run --silent lint", - "test": "npm run --silent tests-only", - "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", - "test:shams:corejs": "node test/shams/core-js.js", - "test:shams:getownpropertysymbols": "node test/shams/get-own-property-symbols.js", - "test:staging": "node --harmony --es-staging test", - "test:stock": "node test", - "tests-only": "npm run --silent test:stock && npm run --silent test:staging && npm run --silent test:shams", - "version": "auto-changelog && git add CHANGELOG.md" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.1" -} diff --git a/node_modules/has-symbols/shams.js b/node_modules/has-symbols/shams.js deleted file mode 100644 index 9f80f79..0000000 --- a/node_modules/has-symbols/shams.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; diff --git a/node_modules/has-symbols/test/index.js b/node_modules/has-symbols/test/index.js deleted file mode 100644 index fc32aff..0000000 --- a/node_modules/has-symbols/test/index.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var test = require('tape'); -var hasSymbols = require('../'); -var runSymbolTests = require('./tests'); - -test('interface', function (t) { - t.equal(typeof hasSymbols, 'function', 'is a function'); - t.equal(typeof hasSymbols(), 'boolean', 'returns a boolean'); - t.end(); -}); - -test('Symbols are supported', { skip: !hasSymbols() }, function (t) { - runSymbolTests(t); - t.end(); -}); - -test('Symbols are not supported', { skip: hasSymbols() }, function (t) { - t.equal(typeof Symbol, 'undefined', 'global Symbol is undefined'); - t.equal(typeof Object.getOwnPropertySymbols, 'undefined', 'Object.getOwnPropertySymbols does not exist'); - t.end(); -}); diff --git a/node_modules/has-symbols/test/shams/core-js.js b/node_modules/has-symbols/test/shams/core-js.js deleted file mode 100644 index df5365c..0000000 --- a/node_modules/has-symbols/test/shams/core-js.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var test = require('tape'); - -if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { - test('has native Symbol support', function (t) { - t.equal(typeof Symbol, 'function'); - t.equal(typeof Symbol(), 'symbol'); - t.end(); - }); - return; -} - -var hasSymbols = require('../../shams'); - -test('polyfilled Symbols', function (t) { - /* eslint-disable global-require */ - t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); - require('core-js/fn/symbol'); - require('core-js/fn/symbol/to-string-tag'); - - require('../tests')(t); - - var hasSymbolsAfter = hasSymbols(); - t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); - /* eslint-enable global-require */ - t.end(); -}); diff --git a/node_modules/has-symbols/test/shams/get-own-property-symbols.js b/node_modules/has-symbols/test/shams/get-own-property-symbols.js deleted file mode 100644 index 9191b24..0000000 --- a/node_modules/has-symbols/test/shams/get-own-property-symbols.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var test = require('tape'); - -if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { - test('has native Symbol support', function (t) { - t.equal(typeof Symbol, 'function'); - t.equal(typeof Symbol(), 'symbol'); - t.end(); - }); - return; -} - -var hasSymbols = require('../../shams'); - -test('polyfilled Symbols', function (t) { - /* eslint-disable global-require */ - t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); - - require('get-own-property-symbols'); - - require('../tests')(t); - - var hasSymbolsAfter = hasSymbols(); - t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); - /* eslint-enable global-require */ - t.end(); -}); diff --git a/node_modules/has-symbols/test/tests.js b/node_modules/has-symbols/test/tests.js deleted file mode 100644 index 93ff0ea..0000000 --- a/node_modules/has-symbols/test/tests.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -module.exports = function runSymbolTests(t) { - t.equal(typeof Symbol, 'function', 'global Symbol is a function'); - - if (typeof Symbol !== 'function') { return false }; - - t.notEqual(Symbol(), Symbol(), 'two symbols are not equal'); - - /* - t.equal( - Symbol.prototype.toString.call(Symbol('foo')), - Symbol.prototype.toString.call(Symbol('foo')), - 'two symbols with the same description stringify the same' - ); - */ - - var foo = Symbol('foo'); - - /* - t.notEqual( - String(foo), - String(Symbol('bar')), - 'two symbols with different descriptions do not stringify the same' - ); - */ - - t.equal(typeof Symbol.prototype.toString, 'function', 'Symbol#toString is a function'); - // t.equal(String(foo), Symbol.prototype.toString.call(foo), 'Symbol#toString equals String of the same symbol'); - - t.equal(typeof Object.getOwnPropertySymbols, 'function', 'Object.getOwnPropertySymbols is a function'); - - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - t.notEqual(typeof sym, 'string', 'Symbol is not a string'); - t.equal(Object.prototype.toString.call(sym), '[object Symbol]', 'symbol primitive Object#toStrings properly'); - t.equal(Object.prototype.toString.call(symObj), '[object Symbol]', 'symbol primitive Object#toStrings properly'); - - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { t.fail('symbol property key was found in for..in of object'); } - - t.deepEqual(Object.keys(obj), [], 'no enumerable own keys on symbol-valued object'); - t.deepEqual(Object.getOwnPropertyNames(obj), [], 'no own names on symbol-valued object'); - t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'one own symbol on symbol-valued object'); - t.equal(Object.prototype.propertyIsEnumerable.call(obj, sym), true, 'symbol is enumerable'); - t.deepEqual(Object.getOwnPropertyDescriptor(obj, sym), { - configurable: true, - enumerable: true, - value: 42, - writable: true - }, 'property descriptor is correct'); -}; diff --git a/node_modules/has-unicode/LICENSE b/node_modules/has-unicode/LICENSE deleted file mode 100644 index d42e25e..0000000 --- a/node_modules/has-unicode/LICENSE +++ /dev/null @@ -1,14 +0,0 @@ -Copyright (c) 2014, Rebecca Turner - -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/has-unicode/README.md b/node_modules/has-unicode/README.md deleted file mode 100644 index 5a03e59..0000000 --- a/node_modules/has-unicode/README.md +++ /dev/null @@ -1,43 +0,0 @@ -has-unicode -=========== - -Try to guess if your terminal supports unicode - -```javascript -var hasUnicode = require("has-unicode") - -if (hasUnicode()) { - // the terminal probably has unicode support -} -``` -```javascript -var hasUnicode = require("has-unicode").tryHarder -hasUnicode(function(unicodeSupported) { - if (unicodeSupported) { - // the terminal probably has unicode support - } -}) -``` - -## Detecting Unicode - -What we actually detect is UTF-8 support, as that's what Node itself supports. -If you have a UTF-16 locale then you won't be detected as unicode capable. - -### Windows - -Since at least Windows 7, `cmd` and `powershell` have been unicode capable, -but unfortunately even then it's not guaranteed. In many localizations it -still uses legacy code pages and there's no facility short of running -programs or linking C++ that will let us detect this. As such, we -report any Windows installation as NOT unicode capable, and recommend -that you encourage your users to override this via config. - -### Unix Like Operating Systems - -We look at the environment variables `LC_ALL`, `LC_CTYPE`, and `LANG` in -that order. For `LC_ALL` and `LANG`, it looks for `.UTF-8` in the value. -For `LC_CTYPE` it looks to see if the value is `UTF-8`. This is sufficient -for most POSIX systems. While locale data can be put in `/etc/locale.conf` -as well, AFAIK it's always copied into the environment. - diff --git a/node_modules/has-unicode/index.js b/node_modules/has-unicode/index.js deleted file mode 100644 index 9b0fe44..0000000 --- a/node_modules/has-unicode/index.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict" -var os = require("os") - -var hasUnicode = module.exports = function () { - // Recent Win32 platforms (>XP) CAN support unicode in the console but - // don't have to, and in non-english locales often use traditional local - // code pages. There's no way, short of windows system calls or execing - // the chcp command line program to figure this out. As such, we default - // this to false and encourage your users to override it via config if - // appropriate. - if (os.type() == "Windows_NT") { return false } - - var isUTF8 = /UTF-?8$/i - var ctype = process.env.LC_ALL || process.env.LC_CTYPE || process.env.LANG - return isUTF8.test(ctype) -} diff --git a/node_modules/has-unicode/package.json b/node_modules/has-unicode/package.json deleted file mode 100644 index a237ac9..0000000 --- a/node_modules/has-unicode/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "_from": "has-unicode@^2.0.0", - "_id": "has-unicode@2.0.1", - "_inBundle": false, - "_integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=", - "_location": "/has-unicode", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "has-unicode@^2.0.0", - "name": "has-unicode", - "escapedName": "has-unicode", - "rawSpec": "^2.0.0", - "saveSpec": null, - "fetchSpec": "^2.0.0" - }, - "_requiredBy": [ - "/gauge" - ], - "_resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", - "_shasum": "e0e6fe6a28cf51138855e086d1691e771de2a8b9", - "_spec": "has-unicode@^2.0.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/gauge", - "author": { - "name": "Rebecca Turner", - "email": "me@re-becca.org" - }, - "bugs": { - "url": "https://github.com/iarna/has-unicode/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Try to guess if your terminal supports unicode", - "devDependencies": { - "require-inject": "^1.3.0", - "tap": "^2.3.1" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/iarna/has-unicode", - "keywords": [ - "unicode", - "terminal" - ], - "license": "ISC", - "main": "index.js", - "name": "has-unicode", - "repository": { - "type": "git", - "url": "git+https://github.com/iarna/has-unicode.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "version": "2.0.1" -} diff --git a/node_modules/has/LICENSE-MIT b/node_modules/has/LICENSE-MIT deleted file mode 100644 index ae7014d..0000000 --- a/node_modules/has/LICENSE-MIT +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2013 Thiago de Arruda - -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/has/README.md b/node_modules/has/README.md deleted file mode 100644 index 635e3a4..0000000 --- a/node_modules/has/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# has - -> Object.prototype.hasOwnProperty.call shortcut - -## Installation - -```sh -npm install --save has -``` - -## Usage - -```js -var has = require('has'); - -has({}, 'hasOwnProperty'); // false -has(Object.prototype, 'hasOwnProperty'); // true -``` diff --git a/node_modules/has/package.json b/node_modules/has/package.json deleted file mode 100644 index 3e44a23..0000000 --- a/node_modules/has/package.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "_from": "has@^1.0.3", - "_id": "has@1.0.3", - "_inBundle": false, - "_integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "_location": "/has", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "has@^1.0.3", - "name": "has", - "escapedName": "has", - "rawSpec": "^1.0.3", - "saveSpec": null, - "fetchSpec": "^1.0.3" - }, - "_requiredBy": [ - "/es-abstract", - "/is-regex" - ], - "_resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "_shasum": "722d7cbfc1f6aa8241f16dd814e011e1f41e8796", - "_spec": "has@^1.0.3", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/es-abstract", - "author": { - "name": "Thiago de Arruda", - "email": "tpadilha84@gmail.com" - }, - "bugs": { - "url": "https://github.com/tarruda/has/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - } - ], - "dependencies": { - "function-bind": "^1.1.1" - }, - "deprecated": false, - "description": "Object.prototype.hasOwnProperty.call shortcut", - "devDependencies": { - "@ljharb/eslint-config": "^12.2.1", - "eslint": "^4.19.1", - "tape": "^4.9.0" - }, - "engines": { - "node": ">= 0.4.0" - }, - "homepage": "https://github.com/tarruda/has", - "license": "MIT", - "licenses": [ - { - "type": "MIT", - "url": "https://github.com/tarruda/has/blob/master/LICENSE-MIT" - } - ], - "main": "./src", - "name": "has", - "repository": { - "type": "git", - "url": "git://github.com/tarruda/has.git" - }, - "scripts": { - "lint": "eslint .", - "pretest": "npm run lint", - "test": "tape test" - }, - "version": "1.0.3" -} diff --git a/node_modules/has/src/index.js b/node_modules/has/src/index.js deleted file mode 100644 index dd92dd9..0000000 --- a/node_modules/has/src/index.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -var bind = require('function-bind'); - -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); diff --git a/node_modules/has/test/index.js b/node_modules/has/test/index.js deleted file mode 100644 index 43d480b..0000000 --- a/node_modules/has/test/index.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var test = require('tape'); -var has = require('../'); - -test('has', function (t) { - t.equal(has({}, 'hasOwnProperty'), false, 'object literal does not have own property "hasOwnProperty"'); - t.equal(has(Object.prototype, 'hasOwnProperty'), true, 'Object.prototype has own property "hasOwnProperty"'); - t.end(); -}); diff --git a/node_modules/http-errors/HISTORY.md b/node_modules/http-errors/HISTORY.md deleted file mode 100644 index efc2d4c..0000000 --- a/node_modules/http-errors/HISTORY.md +++ /dev/null @@ -1,149 +0,0 @@ -2019-02-18 / 1.7.2 -================== - - * deps: setprototypeof@1.1.1 - -2018-09-08 / 1.7.1 -================== - - * Fix error creating objects in some environments - -2018-07-30 / 1.7.0 -================== - - * Set constructor name when possible - * Use `toidentifier` module to make class names - * deps: statuses@'>= 1.5.0 < 2' - -2018-03-29 / 1.6.3 -================== - - * deps: depd@~1.1.2 - - perf: remove argument reassignment - * deps: setprototypeof@1.1.0 - * deps: statuses@'>= 1.4.0 < 2' - -2017-08-04 / 1.6.2 -================== - - * deps: depd@1.1.1 - - Remove unnecessary `Buffer` loading - -2017-02-20 / 1.6.1 -================== - - * deps: setprototypeof@1.0.3 - - Fix shim for old browsers - -2017-02-14 / 1.6.0 -================== - - * Accept custom 4xx and 5xx status codes in factory - * Add deprecation message to `"I'mateapot"` export - * Deprecate passing status code as anything except first argument in factory - * Deprecate using non-error status codes - * Make `message` property enumerable for `HttpError`s - -2016-11-16 / 1.5.1 -================== - - * deps: inherits@2.0.3 - - Fix issue loading in browser - * deps: setprototypeof@1.0.2 - * deps: statuses@'>= 1.3.1 < 2' - -2016-05-18 / 1.5.0 -================== - - * Support new code `421 Misdirected Request` - * Use `setprototypeof` module to replace `__proto__` setting - * deps: statuses@'>= 1.3.0 < 2' - - Add `421 Misdirected Request` - - perf: enable strict mode - * perf: enable strict mode - -2016-01-28 / 1.4.0 -================== - - * Add `HttpError` export, for `err instanceof createError.HttpError` - * deps: inherits@2.0.1 - * deps: statuses@'>= 1.2.1 < 2' - - Fix message for status 451 - - Remove incorrect nginx status code - -2015-02-02 / 1.3.1 -================== - - * Fix regression where status can be overwritten in `createError` `props` - -2015-02-01 / 1.3.0 -================== - - * Construct errors using defined constructors from `createError` - * Fix error names that are not identifiers - - `createError["I'mateapot"]` is now `createError.ImATeapot` - * Set a meaningful `name` property on constructed errors - -2014-12-09 / 1.2.8 -================== - - * Fix stack trace from exported function - * Remove `arguments.callee` usage - -2014-10-14 / 1.2.7 -================== - - * Remove duplicate line - -2014-10-02 / 1.2.6 -================== - - * Fix `expose` to be `true` for `ClientError` constructor - -2014-09-28 / 1.2.5 -================== - - * deps: statuses@1 - -2014-09-21 / 1.2.4 -================== - - * Fix dependency version to work with old `npm`s - -2014-09-21 / 1.2.3 -================== - - * deps: statuses@~1.1.0 - -2014-09-21 / 1.2.2 -================== - - * Fix publish error - -2014-09-21 / 1.2.1 -================== - - * Support Node.js 0.6 - * Use `inherits` instead of `util` - -2014-09-09 / 1.2.0 -================== - - * Fix the way inheriting functions - * Support `expose` being provided in properties argument - -2014-09-08 / 1.1.0 -================== - - * Default status to 500 - * Support provided `error` to extend - -2014-09-08 / 1.0.1 -================== - - * Fix accepting string message - -2014-09-08 / 1.0.0 -================== - - * Initial release diff --git a/node_modules/http-errors/LICENSE b/node_modules/http-errors/LICENSE deleted file mode 100644 index 82af4df..0000000 --- a/node_modules/http-errors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ - -The MIT License (MIT) - -Copyright (c) 2014 Jonathan Ong me@jongleberry.com -Copyright (c) 2016 Douglas Christopher Wilson doug@somethingdoug.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/http-errors/README.md b/node_modules/http-errors/README.md deleted file mode 100644 index 3b25481..0000000 --- a/node_modules/http-errors/README.md +++ /dev/null @@ -1,163 +0,0 @@ -# http-errors - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][node-url] -[![Node.js Version][node-image]][node-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Create HTTP errors for Express, Koa, Connect, etc. with ease. - -## Install - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```bash -$ npm install http-errors -``` - -## Example - -```js -var createError = require('http-errors') -var express = require('express') -var app = express() - -app.use(function (req, res, next) { - if (!req.user) return next(createError(401, 'Please login to view this page.')) - next() -}) -``` - -## API - -This is the current API, currently extracted from Koa and subject to change. - -### Error Properties - -- `expose` - can be used to signal if `message` should be sent to the client, - defaulting to `false` when `status` >= 500 -- `headers` - can be an object of header names to values to be sent to the - client, defaulting to `undefined`. When defined, the key names should all - be lower-cased -- `message` - the traditional error message, which should be kept short and all - single line -- `status` - the status code of the error, mirroring `statusCode` for general - compatibility -- `statusCode` - the status code of the error, defaulting to `500` - -### createError([status], [message], [properties]) - -Create a new error object with the given message `msg`. -The error object inherits from `createError.HttpError`. - - - -```js -var err = createError(404, 'This video does not exist!') -``` - -- `status: 500` - the status code as a number -- `message` - the message of the error, defaulting to node's text for that status code. -- `properties` - custom properties to attach to the object - -### createError([status], [error], [properties]) - -Extend the given `error` object with `createError.HttpError` -properties. This will not alter the inheritance of the given -`error` object, and the modified `error` object is the -return value. - - - -```js -fs.readFile('foo.txt', function (err, buf) { - if (err) { - if (err.code === 'ENOENT') { - var httpError = createError(404, err, { expose: false }) - } else { - var httpError = createError(500, err) - } - } -}) -``` - -- `status` - the status code as a number -- `error` - the error object to extend -- `properties` - custom properties to attach to the object - -### new createError\[code || name\](\[msg]\)) - -Create a new error object with the given message `msg`. -The error object inherits from `createError.HttpError`. - - - -```js -var err = new createError.NotFound() -``` - -- `code` - the status code as a number -- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. - -#### List of all constructors - -|Status Code|Constructor Name | -|-----------|-----------------------------| -|400 |BadRequest | -|401 |Unauthorized | -|402 |PaymentRequired | -|403 |Forbidden | -|404 |NotFound | -|405 |MethodNotAllowed | -|406 |NotAcceptable | -|407 |ProxyAuthenticationRequired | -|408 |RequestTimeout | -|409 |Conflict | -|410 |Gone | -|411 |LengthRequired | -|412 |PreconditionFailed | -|413 |PayloadTooLarge | -|414 |URITooLong | -|415 |UnsupportedMediaType | -|416 |RangeNotSatisfiable | -|417 |ExpectationFailed | -|418 |ImATeapot | -|421 |MisdirectedRequest | -|422 |UnprocessableEntity | -|423 |Locked | -|424 |FailedDependency | -|425 |UnorderedCollection | -|426 |UpgradeRequired | -|428 |PreconditionRequired | -|429 |TooManyRequests | -|431 |RequestHeaderFieldsTooLarge | -|451 |UnavailableForLegalReasons | -|500 |InternalServerError | -|501 |NotImplemented | -|502 |BadGateway | -|503 |ServiceUnavailable | -|504 |GatewayTimeout | -|505 |HTTPVersionNotSupported | -|506 |VariantAlsoNegotiates | -|507 |InsufficientStorage | -|508 |LoopDetected | -|509 |BandwidthLimitExceeded | -|510 |NotExtended | -|511 |NetworkAuthenticationRequired| - -## License - -[MIT](LICENSE) - -[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/http-errors/master -[coveralls-url]: https://coveralls.io/r/jshttp/http-errors?branch=master -[node-image]: https://badgen.net/npm/node/http-errors -[node-url]: https://nodejs.org/en/download -[npm-downloads-image]: https://badgen.net/npm/dm/http-errors -[npm-url]: https://npmjs.org/package/http-errors -[npm-version-image]: https://badgen.net/npm/v/http-errors -[travis-image]: https://badgen.net/travis/jshttp/http-errors/master -[travis-url]: https://travis-ci.org/jshttp/http-errors diff --git a/node_modules/http-errors/index.js b/node_modules/http-errors/index.js deleted file mode 100644 index 10ca4ad..0000000 --- a/node_modules/http-errors/index.js +++ /dev/null @@ -1,266 +0,0 @@ -/*! - * http-errors - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2016 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var deprecate = require('depd')('http-errors') -var setPrototypeOf = require('setprototypeof') -var statuses = require('statuses') -var inherits = require('inherits') -var toIdentifier = require('toidentifier') - -/** - * Module exports. - * @public - */ - -module.exports = createError -module.exports.HttpError = createHttpErrorConstructor() - -// Populate exports for all constructors -populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) - -/** - * Get the code class of a status code. - * @private - */ - -function codeClass (status) { - return Number(String(status).charAt(0) + '00') -} - -/** - * Create a new HTTP Error. - * - * @returns {Error} - * @public - */ - -function createError () { - // so much arity going on ~_~ - var err - var msg - var status = 500 - var props = {} - for (var i = 0; i < arguments.length; i++) { - var arg = arguments[i] - if (arg instanceof Error) { - err = arg - status = err.status || err.statusCode || status - continue - } - switch (typeof arg) { - case 'string': - msg = arg - break - case 'number': - status = arg - if (i !== 0) { - deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)') - } - break - case 'object': - props = arg - break - } - } - - if (typeof status === 'number' && (status < 400 || status >= 600)) { - deprecate('non-error status code; use only 4xx or 5xx status codes') - } - - if (typeof status !== 'number' || - (!statuses[status] && (status < 400 || status >= 600))) { - status = 500 - } - - // constructor - var HttpError = createError[status] || createError[codeClass(status)] - - if (!err) { - // create error - err = HttpError - ? new HttpError(msg) - : new Error(msg || statuses[status]) - Error.captureStackTrace(err, createError) - } - - if (!HttpError || !(err instanceof HttpError) || err.status !== status) { - // add properties to generic error - err.expose = status < 500 - err.status = err.statusCode = status - } - - for (var key in props) { - if (key !== 'status' && key !== 'statusCode') { - err[key] = props[key] - } - } - - return err -} - -/** - * Create HTTP error abstract base class. - * @private - */ - -function createHttpErrorConstructor () { - function HttpError () { - throw new TypeError('cannot construct abstract class') - } - - inherits(HttpError, Error) - - return HttpError -} - -/** - * Create a constructor for a client error. - * @private - */ - -function createClientErrorConstructor (HttpError, name, code) { - var className = name.match(/Error$/) ? name : name + 'Error' - - function ClientError (message) { - // create the error object - var msg = message != null ? message : statuses[code] - var err = new Error(msg) - - // capture a stack trace to the construction point - Error.captureStackTrace(err, ClientError) - - // adjust the [[Prototype]] - setPrototypeOf(err, ClientError.prototype) - - // redefine the error message - Object.defineProperty(err, 'message', { - enumerable: true, - configurable: true, - value: msg, - writable: true - }) - - // redefine the error name - Object.defineProperty(err, 'name', { - enumerable: false, - configurable: true, - value: className, - writable: true - }) - - return err - } - - inherits(ClientError, HttpError) - nameFunc(ClientError, className) - - ClientError.prototype.status = code - ClientError.prototype.statusCode = code - ClientError.prototype.expose = true - - return ClientError -} - -/** - * Create a constructor for a server error. - * @private - */ - -function createServerErrorConstructor (HttpError, name, code) { - var className = name.match(/Error$/) ? name : name + 'Error' - - function ServerError (message) { - // create the error object - var msg = message != null ? message : statuses[code] - var err = new Error(msg) - - // capture a stack trace to the construction point - Error.captureStackTrace(err, ServerError) - - // adjust the [[Prototype]] - setPrototypeOf(err, ServerError.prototype) - - // redefine the error message - Object.defineProperty(err, 'message', { - enumerable: true, - configurable: true, - value: msg, - writable: true - }) - - // redefine the error name - Object.defineProperty(err, 'name', { - enumerable: false, - configurable: true, - value: className, - writable: true - }) - - return err - } - - inherits(ServerError, HttpError) - nameFunc(ServerError, className) - - ServerError.prototype.status = code - ServerError.prototype.statusCode = code - ServerError.prototype.expose = false - - return ServerError -} - -/** - * Set the name of a function, if possible. - * @private - */ - -function nameFunc (func, name) { - var desc = Object.getOwnPropertyDescriptor(func, 'name') - - if (desc && desc.configurable) { - desc.value = name - Object.defineProperty(func, 'name', desc) - } -} - -/** - * Populate the exports object with constructors for every error class. - * @private - */ - -function populateConstructorExports (exports, codes, HttpError) { - codes.forEach(function forEachCode (code) { - var CodeError - var name = toIdentifier(statuses[code]) - - switch (codeClass(code)) { - case 400: - CodeError = createClientErrorConstructor(HttpError, name, code) - break - case 500: - CodeError = createServerErrorConstructor(HttpError, name, code) - break - } - - if (CodeError) { - // export the constructor - exports[code] = CodeError - exports[name] = CodeError - } - }) - - // backwards-compatibility - exports["I'mateapot"] = deprecate.function(exports.ImATeapot, - '"I\'mateapot"; use "ImATeapot" instead') -} diff --git a/node_modules/http-errors/node_modules/inherits/LICENSE b/node_modules/http-errors/node_modules/inherits/LICENSE deleted file mode 100644 index dea3013..0000000 --- a/node_modules/http-errors/node_modules/inherits/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -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/http-errors/node_modules/inherits/README.md b/node_modules/http-errors/node_modules/inherits/README.md deleted file mode 100644 index b1c5665..0000000 --- a/node_modules/http-errors/node_modules/inherits/README.md +++ /dev/null @@ -1,42 +0,0 @@ -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/http-errors/node_modules/inherits/inherits.js b/node_modules/http-errors/node_modules/inherits/inherits.js deleted file mode 100644 index 3b94763..0000000 --- a/node_modules/http-errors/node_modules/inherits/inherits.js +++ /dev/null @@ -1,7 +0,0 @@ -try { - var util = require('util'); - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - module.exports = require('./inherits_browser.js'); -} diff --git a/node_modules/http-errors/node_modules/inherits/inherits_browser.js b/node_modules/http-errors/node_modules/inherits/inherits_browser.js deleted file mode 100644 index c1e78a7..0000000 --- a/node_modules/http-errors/node_modules/inherits/inherits_browser.js +++ /dev/null @@ -1,23 +0,0 @@ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} diff --git a/node_modules/http-errors/node_modules/inherits/package.json b/node_modules/http-errors/node_modules/inherits/package.json deleted file mode 100644 index 8883c6f..0000000 --- a/node_modules/http-errors/node_modules/inherits/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "_from": "inherits@2.0.3", - "_id": "inherits@2.0.3", - "_inBundle": false, - "_integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", - "_location": "/http-errors/inherits", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "inherits@2.0.3", - "name": "inherits", - "escapedName": "inherits", - "rawSpec": "2.0.3", - "saveSpec": null, - "fetchSpec": "2.0.3" - }, - "_requiredBy": [ - "/http-errors" - ], - "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "_shasum": "633c2c83e3da42a502f52466022480f4208261de", - "_spec": "inherits@2.0.3", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/http-errors", - "browser": "./inherits_browser.js", - "bugs": { - "url": "https://github.com/isaacs/inherits/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", - "devDependencies": { - "tap": "^7.1.0" - }, - "files": [ - "inherits.js", - "inherits_browser.js" - ], - "homepage": "https://github.com/isaacs/inherits#readme", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented", - "inherits", - "browser", - "browserify" - ], - "license": "ISC", - "main": "./inherits.js", - "name": "inherits", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/inherits.git" - }, - "scripts": { - "test": "node test" - }, - "version": "2.0.3" -} diff --git a/node_modules/http-errors/package.json b/node_modules/http-errors/package.json deleted file mode 100644 index a79a42b..0000000 --- a/node_modules/http-errors/package.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "_from": "http-errors@1.7.2", - "_id": "http-errors@1.7.2", - "_inBundle": false, - "_integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", - "_location": "/http-errors", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "http-errors@1.7.2", - "name": "http-errors", - "escapedName": "http-errors", - "rawSpec": "1.7.2", - "saveSpec": null, - "fetchSpec": "1.7.2" - }, - "_requiredBy": [ - "/body-parser", - "/raw-body", - "/send" - ], - "_resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", - "_shasum": "4f5029cf13239f31036e5b2e55292bcfbcc85c8f", - "_spec": "http-errors@1.7.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/body-parser", - "author": { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - }, - "bugs": { - "url": "https://github.com/jshttp/http-errors/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Alan Plum", - "email": "me@pluma.io" - }, - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - } - ], - "dependencies": { - "depd": "~1.1.2", - "inherits": "2.0.3", - "setprototypeof": "1.1.1", - "statuses": ">= 1.5.0 < 2", - "toidentifier": "1.0.0" - }, - "deprecated": false, - "description": "Create HTTP error objects", - "devDependencies": { - "eslint": "5.13.0", - "eslint-config-standard": "12.0.0", - "eslint-plugin-import": "2.16.0", - "eslint-plugin-markdown": "1.0.0", - "eslint-plugin-node": "7.0.1", - "eslint-plugin-promise": "4.0.1", - "eslint-plugin-standard": "4.0.0", - "istanbul": "0.4.5", - "mocha": "5.2.0" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "index.js", - "HISTORY.md", - "LICENSE", - "README.md" - ], - "homepage": "https://github.com/jshttp/http-errors#readme", - "keywords": [ - "http", - "error" - ], - "license": "MIT", - "name": "http-errors", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/http-errors.git" - }, - "scripts": { - "lint": "eslint --plugin markdown --ext js,md . && node ./scripts/lint-readme-list.js", - "test": "mocha --reporter spec --bail", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" - }, - "version": "1.7.2" -} diff --git a/node_modules/iconv-lite/Changelog.md b/node_modules/iconv-lite/Changelog.md deleted file mode 100644 index f252313..0000000 --- a/node_modules/iconv-lite/Changelog.md +++ /dev/null @@ -1,162 +0,0 @@ -# 0.4.24 / 2018-08-22 - - * Added MIK encoding (#196, by @Ivan-Kalatchev) - - -# 0.4.23 / 2018-05-07 - - * Fix deprecation warning in Node v10 due to the last usage of `new Buffer` (#185, by @felixbuenemann) - * Switched from NodeBuffer to Buffer in typings (#155 by @felixfbecker, #186 by @larssn) - - -# 0.4.22 / 2018-05-05 - - * Use older semver style for dependencies to be compatible with Node version 0.10 (#182, by @dougwilson) - * Fix tests to accomodate fixes in Node v10 (#182, by @dougwilson) - - -# 0.4.21 / 2018-04-06 - - * Fix encoding canonicalization (#156) - * Fix the paths in the "browser" field in package.json (#174 by @LMLB) - * Removed "contributors" section in package.json - see Git history instead. - - -# 0.4.20 / 2018-04-06 - - * Updated `new Buffer()` usages with recommended replacements as it's being deprecated in Node v10 (#176, #178 by @ChALkeR) - - -# 0.4.19 / 2017-09-09 - - * Fixed iso8859-1 codec regression in handling untranslatable characters (#162, caused by #147) - * Re-generated windows1255 codec, because it was updated in iconv project - * Fixed grammar in error message when iconv-lite is loaded with encoding other than utf8 - - -# 0.4.18 / 2017-06-13 - - * Fixed CESU-8 regression in Node v8. - - -# 0.4.17 / 2017-04-22 - - * Updated typescript definition file to support Angular 2 AoT mode (#153 by @larssn) - - -# 0.4.16 / 2017-04-22 - - * Added support for React Native (#150) - * Changed iso8859-1 encoding to usine internal 'binary' encoding, as it's the same thing (#147 by @mscdex) - * Fixed typo in Readme (#138 by @jiangzhuo) - * Fixed build for Node v6.10+ by making correct version comparison - * Added a warning if iconv-lite is loaded not as utf-8 (see #142) - - -# 0.4.15 / 2016-11-21 - - * Fixed typescript type definition (#137) - - -# 0.4.14 / 2016-11-20 - - * Preparation for v1.0 - * Added Node v6 and latest Node versions to Travis CI test rig - * Deprecated Node v0.8 support - * Typescript typings (@larssn) - * Fix encoding of Euro character in GB 18030 (inspired by @lygstate) - * Add ms prefix to dbcs windows encodings (@rokoroku) - - -# 0.4.13 / 2015-10-01 - - * Fix silly mistake in deprecation notice. - - -# 0.4.12 / 2015-09-26 - - * Node v4 support: - * Added CESU-8 decoding (#106) - * Added deprecation notice for `extendNodeEncodings` - * Added Travis tests for Node v4 and io.js latest (#105 by @Mithgol) - - -# 0.4.11 / 2015-07-03 - - * Added CESU-8 encoding. - - -# 0.4.10 / 2015-05-26 - - * Changed UTF-16 endianness heuristic to take into account any ASCII chars, not - just spaces. This should minimize the importance of "default" endianness. - - -# 0.4.9 / 2015-05-24 - - * Streamlined BOM handling: strip BOM by default, add BOM when encoding if - addBOM: true. Added docs to Readme. - * UTF16 now uses UTF16-LE by default. - * Fixed minor issue with big5 encoding. - * Added io.js testing on Travis; updated node-iconv version to test against. - Now we just skip testing SBCS encodings that node-iconv doesn't support. - * (internal refactoring) Updated codec interface to use classes. - * Use strict mode in all files. - - -# 0.4.8 / 2015-04-14 - - * added alias UNICODE-1-1-UTF-7 for UTF-7 encoding (#94) - - -# 0.4.7 / 2015-02-05 - - * stop official support of Node.js v0.8. Should still work, but no guarantees. - reason: Packages needed for testing are hard to get on Travis CI. - * work in environment where Object.prototype is monkey patched with enumerable - props (#89). - - -# 0.4.6 / 2015-01-12 - - * fix rare aliases of single-byte encodings (thanks @mscdex) - * double the timeout for dbcs tests to make them less flaky on travis - - -# 0.4.5 / 2014-11-20 - - * fix windows-31j and x-sjis encoding support (@nleush) - * minor fix: undefined variable reference when internal error happens - - -# 0.4.4 / 2014-07-16 - - * added encodings UTF-7 (RFC2152) and UTF-7-IMAP (RFC3501 Section 5.1.3) - * fixed streaming base64 encoding - - -# 0.4.3 / 2014-06-14 - - * added encodings UTF-16BE and UTF-16 with BOM - - -# 0.4.2 / 2014-06-12 - - * don't throw exception if `extendNodeEncodings()` is called more than once - - -# 0.4.1 / 2014-06-11 - - * codepage 808 added - - -# 0.4.0 / 2014-06-10 - - * code is rewritten from scratch - * all widespread encodings are supported - * streaming interface added - * browserify compatibility added - * (optional) extend core primitive encodings to make usage even simpler - * moved from vows to mocha as the testing framework - - diff --git a/node_modules/iconv-lite/LICENSE b/node_modules/iconv-lite/LICENSE deleted file mode 100644 index d518d83..0000000 --- a/node_modules/iconv-lite/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2011 Alexander Shtuchkin - -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/iconv-lite/README.md b/node_modules/iconv-lite/README.md deleted file mode 100644 index c981c37..0000000 --- a/node_modules/iconv-lite/README.md +++ /dev/null @@ -1,156 +0,0 @@ -## Pure JS character encoding conversion [![Build Status](https://travis-ci.org/ashtuchkin/iconv-lite.svg?branch=master)](https://travis-ci.org/ashtuchkin/iconv-lite) - - * Doesn't need native code compilation. Works on Windows and in sandboxed environments like [Cloud9](http://c9.io). - * Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser), - [Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others. - * Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison). - * Intuitive encode/decode API - * Streaming support for Node v0.10+ - * [Deprecated] Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings. - * In-browser usage via [Browserify](https://github.com/substack/node-browserify) (~180k gzip compressed with Buffer shim included). - * Typescript [type definition file](https://github.com/ashtuchkin/iconv-lite/blob/master/lib/index.d.ts) included. - * React Native is supported (need to explicitly `npm install` two more modules: `buffer` and `stream`). - * License: MIT. - -[![NPM Stats](https://nodei.co/npm/iconv-lite.png?downloads=true&downloadRank=true)](https://npmjs.org/packages/iconv-lite/) - -## Usage -### Basic API -```javascript -var iconv = require('iconv-lite'); - -// Convert from an encoded buffer to js string. -str = iconv.decode(Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); - -// Convert from js string to an encoded buffer. -buf = iconv.encode("Sample input string", 'win1251'); - -// Check if encoding is supported -iconv.encodingExists("us-ascii") -``` - -### Streaming API (Node v0.10+) -```javascript - -// Decode stream (from binary stream to js strings) -http.createServer(function(req, res) { - var converterStream = iconv.decodeStream('win1251'); - req.pipe(converterStream); - - converterStream.on('data', function(str) { - console.log(str); // Do something with decoded strings, chunk-by-chunk. - }); -}); - -// Convert encoding streaming example -fs.createReadStream('file-in-win1251.txt') - .pipe(iconv.decodeStream('win1251')) - .pipe(iconv.encodeStream('ucs2')) - .pipe(fs.createWriteStream('file-in-ucs2.txt')); - -// Sugar: all encode/decode streams have .collect(cb) method to accumulate data. -http.createServer(function(req, res) { - req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) { - assert(typeof body == 'string'); - console.log(body); // full request body string - }); -}); -``` - -### [Deprecated] Extend Node.js own encodings -> NOTE: This doesn't work on latest Node versions. See [details](https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility). - -```javascript -// After this call all Node basic primitives will understand iconv-lite encodings. -iconv.extendNodeEncodings(); - -// Examples: -buf = new Buffer(str, 'win1251'); -buf.write(str, 'gbk'); -str = buf.toString('latin1'); -assert(Buffer.isEncoding('iso-8859-15')); -Buffer.byteLength(str, 'us-ascii'); - -http.createServer(function(req, res) { - req.setEncoding('big5'); - req.collect(function(err, body) { - console.log(body); - }); -}); - -fs.createReadStream("file.txt", "shift_jis"); - -// External modules are also supported (if they use Node primitives, which they probably do). -request = require('request'); -request({ - url: "http://github.com/", - encoding: "cp932" -}); - -// To remove extensions -iconv.undoExtendNodeEncodings(); -``` - -## Supported encodings - - * All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex. - * Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap. - * All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, - IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. - Aliases like 'latin1', 'us-ascii' also supported. - * All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP. - -See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings). - -Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors! - -Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors! - - -## Encoding/decoding speed - -Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). -Note: your results may vary, so please always check on your hardware. - - operation iconv@2.1.4 iconv-lite@0.4.7 - ---------------------------------------------------------- - encode('win1251') ~96 Mb/s ~320 Mb/s - decode('win1251') ~95 Mb/s ~246 Mb/s - -## BOM handling - - * Decoding: BOM is stripped by default, unless overridden by passing `stripBOM: false` in options - (f.ex. `iconv.decode(buf, enc, {stripBOM: false})`). - A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found. - * If you want to detect UTF-8 BOM when decoding other encodings, use [node-autodetect-decoder-stream](https://github.com/danielgindi/node-autodetect-decoder-stream) module. - * Encoding: No BOM added, unless overridden by `addBOM: true` option. - -## UTF-16 Encodings - -This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be -smart about endianness in the following ways: - * Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be - overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`. - * Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override. - -## Other notes - -When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding). -Untranslatable characters are set to � or ?. No transliteration is currently supported. -Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see #65, #77). - -## Testing - -```bash -$ git clone git@github.com:ashtuchkin/iconv-lite.git -$ cd iconv-lite -$ npm install -$ npm test - -$ # To view performance: -$ node test/performance.js - -$ # To view test coverage: -$ npm run coverage -$ open coverage/lcov-report/index.html -``` diff --git a/node_modules/iconv-lite/encodings/dbcs-codec.js b/node_modules/iconv-lite/encodings/dbcs-codec.js deleted file mode 100644 index 1fe3e16..0000000 --- a/node_modules/iconv-lite/encodings/dbcs-codec.js +++ /dev/null @@ -1,555 +0,0 @@ -"use strict"; -var Buffer = require("safer-buffer").Buffer; - -// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. -// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. -// To save memory and loading time, we read table files only when requested. - -exports._dbcs = DBCSCodec; - -var UNASSIGNED = -1, - GB18030_CODE = -2, - SEQ_START = -10, - NODE_START = -1000, - UNASSIGNED_NODE = new Array(0x100), - DEF_CHAR = -1; - -for (var i = 0; i < 0x100; i++) - UNASSIGNED_NODE[i] = UNASSIGNED; - - -// Class DBCSCodec reads and initializes mapping tables. -function DBCSCodec(codecOptions, iconv) { - this.encodingName = codecOptions.encodingName; - if (!codecOptions) - throw new Error("DBCS codec is called without the data.") - if (!codecOptions.table) - throw new Error("Encoding '" + this.encodingName + "' has no data."); - - // Load tables. - var mappingTable = codecOptions.table(); - - - // Decode tables: MBCS -> Unicode. - - // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. - // Trie root is decodeTables[0]. - // Values: >= 0 -> unicode character code. can be > 0xFFFF - // == UNASSIGNED -> unknown/unassigned sequence. - // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. - // <= NODE_START -> index of the next node in our trie to process next byte. - // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. - this.decodeTables = []; - this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. - - // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. - this.decodeTableSeq = []; - - // Actual mapping tables consist of chunks. Use them to fill up decode tables. - for (var i = 0; i < mappingTable.length; i++) - this._addDecodeChunk(mappingTable[i]); - - this.defaultCharUnicode = iconv.defaultCharUnicode; - - - // Encode tables: Unicode -> DBCS. - - // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. - // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. - // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). - // == UNASSIGNED -> no conversion found. Output a default char. - // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. - this.encodeTable = []; - - // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of - // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key - // means end of sequence (needed when one sequence is a strict subsequence of another). - // Objects are kept separately from encodeTable to increase performance. - this.encodeTableSeq = []; - - // Some chars can be decoded, but need not be encoded. - var skipEncodeChars = {}; - if (codecOptions.encodeSkipVals) - for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { - var val = codecOptions.encodeSkipVals[i]; - if (typeof val === 'number') - skipEncodeChars[val] = true; - else - for (var j = val.from; j <= val.to; j++) - skipEncodeChars[j] = true; - } - - // Use decode trie to recursively fill out encode tables. - this._fillEncodeTable(0, 0, skipEncodeChars); - - // Add more encoding pairs when needed. - if (codecOptions.encodeAdd) { - for (var uChar in codecOptions.encodeAdd) - if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) - this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); - } - - this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; - if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; - if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); - - - // Load & create GB18030 tables when needed. - if (typeof codecOptions.gb18030 === 'function') { - this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. - - // Add GB18030 decode tables. - var thirdByteNodeIdx = this.decodeTables.length; - var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); - - var fourthByteNodeIdx = this.decodeTables.length; - var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); - - for (var i = 0x81; i <= 0xFE; i++) { - var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; - var secondByteNode = this.decodeTables[secondByteNodeIdx]; - for (var j = 0x30; j <= 0x39; j++) - secondByteNode[j] = NODE_START - thirdByteNodeIdx; - } - for (var i = 0x81; i <= 0xFE; i++) - thirdByteNode[i] = NODE_START - fourthByteNodeIdx; - for (var i = 0x30; i <= 0x39; i++) - fourthByteNode[i] = GB18030_CODE - } -} - -DBCSCodec.prototype.encoder = DBCSEncoder; -DBCSCodec.prototype.decoder = DBCSDecoder; - -// Decoder helpers -DBCSCodec.prototype._getDecodeTrieNode = function(addr) { - var bytes = []; - for (; addr > 0; addr >>= 8) - bytes.push(addr & 0xFF); - if (bytes.length == 0) - bytes.push(0); - - var node = this.decodeTables[0]; - for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. - var val = node[bytes[i]]; - - if (val == UNASSIGNED) { // Create new node. - node[bytes[i]] = NODE_START - this.decodeTables.length; - this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); - } - else if (val <= NODE_START) { // Existing node. - node = this.decodeTables[NODE_START - val]; - } - else - throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); - } - return node; -} - - -DBCSCodec.prototype._addDecodeChunk = function(chunk) { - // First element of chunk is the hex mbcs code where we start. - var curAddr = parseInt(chunk[0], 16); - - // Choose the decoding node where we'll write our chars. - var writeTable = this._getDecodeTrieNode(curAddr); - curAddr = curAddr & 0xFF; - - // Write all other elements of the chunk to the table. - for (var k = 1; k < chunk.length; k++) { - var part = chunk[k]; - if (typeof part === "string") { // String, write as-is. - for (var l = 0; l < part.length;) { - var code = part.charCodeAt(l++); - if (0xD800 <= code && code < 0xDC00) { // Decode surrogate - var codeTrail = part.charCodeAt(l++); - if (0xDC00 <= codeTrail && codeTrail < 0xE000) - writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); - else - throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); - } - else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) - var len = 0xFFF - code + 2; - var seq = []; - for (var m = 0; m < len; m++) - seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. - - writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; - this.decodeTableSeq.push(seq); - } - else - writeTable[curAddr++] = code; // Basic char - } - } - else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. - var charCode = writeTable[curAddr - 1] + 1; - for (var l = 0; l < part; l++) - writeTable[curAddr++] = charCode++; - } - else - throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); - } - if (curAddr > 0xFF) - throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); -} - -// Encoder helpers -DBCSCodec.prototype._getEncodeBucket = function(uCode) { - var high = uCode >> 8; // This could be > 0xFF because of astral characters. - if (this.encodeTable[high] === undefined) - this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. - return this.encodeTable[high]; -} - -DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - if (bucket[low] <= SEQ_START) - this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. - else if (bucket[low] == UNASSIGNED) - bucket[low] = dbcsCode; -} - -DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { - - // Get the root of character tree according to first character of the sequence. - var uCode = seq[0]; - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - - var node; - if (bucket[low] <= SEQ_START) { - // There's already a sequence with - use it. - node = this.encodeTableSeq[SEQ_START-bucket[low]]; - } - else { - // There was no sequence object - allocate a new one. - node = {}; - if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. - bucket[low] = SEQ_START - this.encodeTableSeq.length; - this.encodeTableSeq.push(node); - } - - // Traverse the character tree, allocating new nodes as needed. - for (var j = 1; j < seq.length-1; j++) { - var oldVal = node[uCode]; - if (typeof oldVal === 'object') - node = oldVal; - else { - node = node[uCode] = {} - if (oldVal !== undefined) - node[DEF_CHAR] = oldVal - } - } - - // Set the leaf to given dbcsCode. - uCode = seq[seq.length-1]; - node[uCode] = dbcsCode; -} - -DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { - var node = this.decodeTables[nodeIdx]; - for (var i = 0; i < 0x100; i++) { - var uCode = node[i]; - var mbCode = prefix + i; - if (skipEncodeChars[mbCode]) - continue; - - if (uCode >= 0) - this._setEncodeChar(uCode, mbCode); - else if (uCode <= NODE_START) - this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); - else if (uCode <= SEQ_START) - this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); - } -} - - - -// == Encoder ================================================================== - -function DBCSEncoder(options, codec) { - // Encoder state - this.leadSurrogate = -1; - this.seqObj = undefined; - - // Static data - this.encodeTable = codec.encodeTable; - this.encodeTableSeq = codec.encodeTableSeq; - this.defaultCharSingleByte = codec.defCharSB; - this.gb18030 = codec.gb18030; -} - -DBCSEncoder.prototype.write = function(str) { - var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), - leadSurrogate = this.leadSurrogate, - seqObj = this.seqObj, nextChar = -1, - i = 0, j = 0; - - while (true) { - // 0. Get next character. - if (nextChar === -1) { - if (i == str.length) break; - var uCode = str.charCodeAt(i++); - } - else { - var uCode = nextChar; - nextChar = -1; - } - - // 1. Handle surrogates. - if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. - if (uCode < 0xDC00) { // We've got lead surrogate. - if (leadSurrogate === -1) { - leadSurrogate = uCode; - continue; - } else { - leadSurrogate = uCode; - // Double lead surrogate found. - uCode = UNASSIGNED; - } - } else { // We've got trail surrogate. - if (leadSurrogate !== -1) { - uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); - leadSurrogate = -1; - } else { - // Incomplete surrogate pair - only trail surrogate found. - uCode = UNASSIGNED; - } - - } - } - else if (leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. - leadSurrogate = -1; - } - - // 2. Convert uCode character. - var dbcsCode = UNASSIGNED; - if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence - var resCode = seqObj[uCode]; - if (typeof resCode === 'object') { // Sequence continues. - seqObj = resCode; - continue; - - } else if (typeof resCode == 'number') { // Sequence finished. Write it. - dbcsCode = resCode; - - } else if (resCode == undefined) { // Current character is not part of the sequence. - - // Try default character for this sequence - resCode = seqObj[DEF_CHAR]; - if (resCode !== undefined) { - dbcsCode = resCode; // Found. Write it. - nextChar = uCode; // Current character will be written too in the next iteration. - - } else { - // TODO: What if we have no default? (resCode == undefined) - // Then, we should write first char of the sequence as-is and try the rest recursively. - // Didn't do it for now because no encoding has this situation yet. - // Currently, just skip the sequence and write current char. - } - } - seqObj = undefined; - } - else if (uCode >= 0) { // Regular character - var subtable = this.encodeTable[uCode >> 8]; - if (subtable !== undefined) - dbcsCode = subtable[uCode & 0xFF]; - - if (dbcsCode <= SEQ_START) { // Sequence start - seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; - continue; - } - - if (dbcsCode == UNASSIGNED && this.gb18030) { - // Use GB18030 algorithm to find character(s) to write. - var idx = findIdx(this.gb18030.uChars, uCode); - if (idx != -1) { - var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; - newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; - newBuf[j++] = 0x30 + dbcsCode; - continue; - } - } - } - - // 3. Write dbcsCode character. - if (dbcsCode === UNASSIGNED) - dbcsCode = this.defaultCharSingleByte; - - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else if (dbcsCode < 0x10000) { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - else { - newBuf[j++] = dbcsCode >> 16; - newBuf[j++] = (dbcsCode >> 8) & 0xFF; - newBuf[j++] = dbcsCode & 0xFF; - } - } - - this.seqObj = seqObj; - this.leadSurrogate = leadSurrogate; - return newBuf.slice(0, j); -} - -DBCSEncoder.prototype.end = function() { - if (this.leadSurrogate === -1 && this.seqObj === undefined) - return; // All clean. Most often case. - - var newBuf = Buffer.alloc(10), j = 0; - - if (this.seqObj) { // We're in the sequence. - var dbcsCode = this.seqObj[DEF_CHAR]; - if (dbcsCode !== undefined) { // Write beginning of the sequence. - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - } else { - // See todo above. - } - this.seqObj = undefined; - } - - if (this.leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - newBuf[j++] = this.defaultCharSingleByte; - this.leadSurrogate = -1; - } - - return newBuf.slice(0, j); -} - -// Export for testing -DBCSEncoder.prototype.findIdx = findIdx; - - -// == Decoder ================================================================== - -function DBCSDecoder(options, codec) { - // Decoder state - this.nodeIdx = 0; - this.prevBuf = Buffer.alloc(0); - - // Static data - this.decodeTables = codec.decodeTables; - this.decodeTableSeq = codec.decodeTableSeq; - this.defaultCharUnicode = codec.defaultCharUnicode; - this.gb18030 = codec.gb18030; -} - -DBCSDecoder.prototype.write = function(buf) { - var newBuf = Buffer.alloc(buf.length*2), - nodeIdx = this.nodeIdx, - prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, - seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. - uCode; - - if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. - prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); - - for (var i = 0, j = 0; i < buf.length; i++) { - var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; - - // Lookup in current trie node. - var uCode = this.decodeTables[nodeIdx][curByte]; - - if (uCode >= 0) { - // Normal character, just use it. - } - else if (uCode === UNASSIGNED) { // Unknown char. - // TODO: Callback with seq. - //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). - uCode = this.defaultCharUnicode.charCodeAt(0); - } - else if (uCode === GB18030_CODE) { - var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); - var idx = findIdx(this.gb18030.gbChars, ptr); - uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; - } - else if (uCode <= NODE_START) { // Go to next trie node. - nodeIdx = NODE_START - uCode; - continue; - } - else if (uCode <= SEQ_START) { // Output a sequence of chars. - var seq = this.decodeTableSeq[SEQ_START - uCode]; - for (var k = 0; k < seq.length - 1; k++) { - uCode = seq[k]; - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - } - uCode = seq[seq.length-1]; - } - else - throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); - - // Write the character to buffer, handling higher planes using surrogate pair. - if (uCode > 0xFFFF) { - uCode -= 0x10000; - var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); - newBuf[j++] = uCodeLead & 0xFF; - newBuf[j++] = uCodeLead >> 8; - - uCode = 0xDC00 + uCode % 0x400; - } - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - - // Reset trie node. - nodeIdx = 0; seqStart = i+1; - } - - this.nodeIdx = nodeIdx; - this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); - return newBuf.slice(0, j).toString('ucs2'); -} - -DBCSDecoder.prototype.end = function() { - var ret = ''; - - // Try to parse all remaining chars. - while (this.prevBuf.length > 0) { - // Skip 1 character in the buffer. - ret += this.defaultCharUnicode; - var buf = this.prevBuf.slice(1); - - // Parse remaining as usual. - this.prevBuf = Buffer.alloc(0); - this.nodeIdx = 0; - if (buf.length > 0) - ret += this.write(buf); - } - - this.nodeIdx = 0; - return ret; -} - -// Binary search for GB18030. Returns largest i such that table[i] <= val. -function findIdx(table, val) { - if (table[0] > val) - return -1; - - var l = 0, r = table.length; - while (l < r-1) { // always table[l] <= val < table[r] - var mid = l + Math.floor((r-l+1)/2); - if (table[mid] <= val) - l = mid; - else - r = mid; - } - return l; -} - diff --git a/node_modules/iconv-lite/encodings/dbcs-data.js b/node_modules/iconv-lite/encodings/dbcs-data.js deleted file mode 100644 index 4b61914..0000000 --- a/node_modules/iconv-lite/encodings/dbcs-data.js +++ /dev/null @@ -1,176 +0,0 @@ -"use strict"; - -// Description of supported double byte encodings and aliases. -// Tables are not require()-d until they are needed to speed up library load. -// require()-s are direct to support Browserify. - -module.exports = { - - // == Japanese/ShiftJIS ==================================================== - // All japanese encodings are based on JIS X set of standards: - // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. - // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. - // Has several variations in 1978, 1983, 1990 and 1997. - // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. - // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. - // 2 planes, first is superset of 0208, second - revised 0212. - // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) - - // Byte encodings are: - // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte - // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. - // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. - // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. - // 0x00-0x7F - lower part of 0201 - // 0x8E, 0xA1-0xDF - upper part of 0201 - // (0xA1-0xFE)x2 - 0208 plane (94x94). - // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). - // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. - // Used as-is in ISO2022 family. - // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, - // 0201-1976 Roman, 0208-1978, 0208-1983. - // * ISO2022-JP-1: Adds esc seq for 0212-1990. - // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. - // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. - // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. - // - // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. - // - // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html - - 'shiftjis': { - type: '_dbcs', - table: function() { return require('./tables/shiftjis.json') }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - encodeSkipVals: [{from: 0xED40, to: 0xF940}], - }, - 'csshiftjis': 'shiftjis', - 'mskanji': 'shiftjis', - 'sjis': 'shiftjis', - 'windows31j': 'shiftjis', - 'ms31j': 'shiftjis', - 'xsjis': 'shiftjis', - 'windows932': 'shiftjis', - 'ms932': 'shiftjis', - '932': 'shiftjis', - 'cp932': 'shiftjis', - - 'eucjp': { - type: '_dbcs', - table: function() { return require('./tables/eucjp.json') }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - }, - - // TODO: KDDI extension to Shift_JIS - // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. - // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. - - - // == Chinese/GBK ========================================================== - // http://en.wikipedia.org/wiki/GBK - // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder - - // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 - 'gb2312': 'cp936', - 'gb231280': 'cp936', - 'gb23121980': 'cp936', - 'csgb2312': 'cp936', - 'csiso58gb231280': 'cp936', - 'euccn': 'cp936', - - // Microsoft's CP936 is a subset and approximation of GBK. - 'windows936': 'cp936', - 'ms936': 'cp936', - '936': 'cp936', - 'cp936': { - type: '_dbcs', - table: function() { return require('./tables/cp936.json') }, - }, - - // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. - 'gbk': { - type: '_dbcs', - table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, - }, - 'xgbk': 'gbk', - 'isoir58': 'gbk', - - // GB18030 is an algorithmic extension of GBK. - // Main source: https://www.w3.org/TR/encoding/#gbk-encoder - // http://icu-project.org/docs/papers/gb18030.html - // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml - // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 - 'gb18030': { - type: '_dbcs', - table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, - gb18030: function() { return require('./tables/gb18030-ranges.json') }, - encodeSkipVals: [0x80], - encodeAdd: {'€': 0xA2E3}, - }, - - 'chinese': 'gb18030', - - - // == Korean =============================================================== - // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. - 'windows949': 'cp949', - 'ms949': 'cp949', - '949': 'cp949', - 'cp949': { - type: '_dbcs', - table: function() { return require('./tables/cp949.json') }, - }, - - 'cseuckr': 'cp949', - 'csksc56011987': 'cp949', - 'euckr': 'cp949', - 'isoir149': 'cp949', - 'korean': 'cp949', - 'ksc56011987': 'cp949', - 'ksc56011989': 'cp949', - 'ksc5601': 'cp949', - - - // == Big5/Taiwan/Hong Kong ================================================ - // There are lots of tables for Big5 and cp950. Please see the following links for history: - // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html - // Variations, in roughly number of defined chars: - // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT - // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ - // * Big5-2003 (Taiwan standard) almost superset of cp950. - // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. - // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. - // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. - // Plus, it has 4 combining sequences. - // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 - // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. - // Implementations are not consistent within browsers; sometimes labeled as just big5. - // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. - // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 - // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. - // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt - // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt - // - // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder - // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. - - 'windows950': 'cp950', - 'ms950': 'cp950', - '950': 'cp950', - 'cp950': { - type: '_dbcs', - table: function() { return require('./tables/cp950.json') }, - }, - - // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. - 'big5': 'big5hkscs', - 'big5hkscs': { - type: '_dbcs', - table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) }, - encodeSkipVals: [0xa2cc], - }, - - 'cnbig5': 'big5hkscs', - 'csbig5': 'big5hkscs', - 'xxbig5': 'big5hkscs', -}; diff --git a/node_modules/iconv-lite/encodings/index.js b/node_modules/iconv-lite/encodings/index.js deleted file mode 100644 index e304003..0000000 --- a/node_modules/iconv-lite/encodings/index.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; - -// Update this array if you add/rename/remove files in this directory. -// We support Browserify by skipping automatic module discovery and requiring modules directly. -var modules = [ - require("./internal"), - require("./utf16"), - require("./utf7"), - require("./sbcs-codec"), - require("./sbcs-data"), - require("./sbcs-data-generated"), - require("./dbcs-codec"), - require("./dbcs-data"), -]; - -// Put all encoding/alias/codec definitions to single object and export it. -for (var i = 0; i < modules.length; i++) { - var module = modules[i]; - for (var enc in module) - if (Object.prototype.hasOwnProperty.call(module, enc)) - exports[enc] = module[enc]; -} diff --git a/node_modules/iconv-lite/encodings/internal.js b/node_modules/iconv-lite/encodings/internal.js deleted file mode 100644 index 05ce38b..0000000 --- a/node_modules/iconv-lite/encodings/internal.js +++ /dev/null @@ -1,188 +0,0 @@ -"use strict"; -var Buffer = require("safer-buffer").Buffer; - -// Export Node.js internal encodings. - -module.exports = { - // Encodings - utf8: { type: "_internal", bomAware: true}, - cesu8: { type: "_internal", bomAware: true}, - unicode11utf8: "utf8", - - ucs2: { type: "_internal", bomAware: true}, - utf16le: "ucs2", - - binary: { type: "_internal" }, - base64: { type: "_internal" }, - hex: { type: "_internal" }, - - // Codec. - _internal: InternalCodec, -}; - -//------------------------------------------------------------------------------ - -function InternalCodec(codecOptions, iconv) { - this.enc = codecOptions.encodingName; - this.bomAware = codecOptions.bomAware; - - if (this.enc === "base64") - this.encoder = InternalEncoderBase64; - else if (this.enc === "cesu8") { - this.enc = "utf8"; // Use utf8 for decoding. - this.encoder = InternalEncoderCesu8; - - // Add decoder for versions of Node not supporting CESU-8 - if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { - this.decoder = InternalDecoderCesu8; - this.defaultCharUnicode = iconv.defaultCharUnicode; - } - } -} - -InternalCodec.prototype.encoder = InternalEncoder; -InternalCodec.prototype.decoder = InternalDecoder; - -//------------------------------------------------------------------------------ - -// We use node.js internal decoder. Its signature is the same as ours. -var StringDecoder = require('string_decoder').StringDecoder; - -if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. - StringDecoder.prototype.end = function() {}; - - -function InternalDecoder(options, codec) { - StringDecoder.call(this, codec.enc); -} - -InternalDecoder.prototype = StringDecoder.prototype; - - -//------------------------------------------------------------------------------ -// Encoder is mostly trivial - -function InternalEncoder(options, codec) { - this.enc = codec.enc; -} - -InternalEncoder.prototype.write = function(str) { - return Buffer.from(str, this.enc); -} - -InternalEncoder.prototype.end = function() { -} - - -//------------------------------------------------------------------------------ -// Except base64 encoder, which must keep its state. - -function InternalEncoderBase64(options, codec) { - this.prevStr = ''; -} - -InternalEncoderBase64.prototype.write = function(str) { - str = this.prevStr + str; - var completeQuads = str.length - (str.length % 4); - this.prevStr = str.slice(completeQuads); - str = str.slice(0, completeQuads); - - return Buffer.from(str, "base64"); -} - -InternalEncoderBase64.prototype.end = function() { - return Buffer.from(this.prevStr, "base64"); -} - - -//------------------------------------------------------------------------------ -// CESU-8 encoder is also special. - -function InternalEncoderCesu8(options, codec) { -} - -InternalEncoderCesu8.prototype.write = function(str) { - var buf = Buffer.alloc(str.length * 3), bufIdx = 0; - for (var i = 0; i < str.length; i++) { - var charCode = str.charCodeAt(i); - // Naive implementation, but it works because CESU-8 is especially easy - // to convert from UTF-16 (which all JS strings are encoded in). - if (charCode < 0x80) - buf[bufIdx++] = charCode; - else if (charCode < 0x800) { - buf[bufIdx++] = 0xC0 + (charCode >>> 6); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - else { // charCode will always be < 0x10000 in javascript. - buf[bufIdx++] = 0xE0 + (charCode >>> 12); - buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - } - return buf.slice(0, bufIdx); -} - -InternalEncoderCesu8.prototype.end = function() { -} - -//------------------------------------------------------------------------------ -// CESU-8 decoder is not implemented in Node v4.0+ - -function InternalDecoderCesu8(options, codec) { - this.acc = 0; - this.contBytes = 0; - this.accBytes = 0; - this.defaultCharUnicode = codec.defaultCharUnicode; -} - -InternalDecoderCesu8.prototype.write = function(buf) { - var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, - res = ''; - for (var i = 0; i < buf.length; i++) { - var curByte = buf[i]; - if ((curByte & 0xC0) !== 0x80) { // Leading byte - if (contBytes > 0) { // Previous code is invalid - res += this.defaultCharUnicode; - contBytes = 0; - } - - if (curByte < 0x80) { // Single-byte code - res += String.fromCharCode(curByte); - } else if (curByte < 0xE0) { // Two-byte code - acc = curByte & 0x1F; - contBytes = 1; accBytes = 1; - } else if (curByte < 0xF0) { // Three-byte code - acc = curByte & 0x0F; - contBytes = 2; accBytes = 1; - } else { // Four or more are not supported for CESU-8. - res += this.defaultCharUnicode; - } - } else { // Continuation byte - if (contBytes > 0) { // We're waiting for it. - acc = (acc << 6) | (curByte & 0x3f); - contBytes--; accBytes++; - if (contBytes === 0) { - // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) - if (accBytes === 2 && acc < 0x80 && acc > 0) - res += this.defaultCharUnicode; - else if (accBytes === 3 && acc < 0x800) - res += this.defaultCharUnicode; - else - // Actually add character. - res += String.fromCharCode(acc); - } - } else { // Unexpected continuation byte - res += this.defaultCharUnicode; - } - } - } - this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; - return res; -} - -InternalDecoderCesu8.prototype.end = function() { - var res = 0; - if (this.contBytes > 0) - res += this.defaultCharUnicode; - return res; -} diff --git a/node_modules/iconv-lite/encodings/sbcs-codec.js b/node_modules/iconv-lite/encodings/sbcs-codec.js deleted file mode 100644 index abac5ff..0000000 --- a/node_modules/iconv-lite/encodings/sbcs-codec.js +++ /dev/null @@ -1,72 +0,0 @@ -"use strict"; -var Buffer = require("safer-buffer").Buffer; - -// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that -// correspond to encoded bytes (if 128 - then lower half is ASCII). - -exports._sbcs = SBCSCodec; -function SBCSCodec(codecOptions, iconv) { - if (!codecOptions) - throw new Error("SBCS codec is called without the data.") - - // Prepare char buffer for decoding. - if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) - throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); - - if (codecOptions.chars.length === 128) { - var asciiString = ""; - for (var i = 0; i < 128; i++) - asciiString += String.fromCharCode(i); - codecOptions.chars = asciiString + codecOptions.chars; - } - - this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); - - // Encoding buffer. - var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); - - for (var i = 0; i < codecOptions.chars.length; i++) - encodeBuf[codecOptions.chars.charCodeAt(i)] = i; - - this.encodeBuf = encodeBuf; -} - -SBCSCodec.prototype.encoder = SBCSEncoder; -SBCSCodec.prototype.decoder = SBCSDecoder; - - -function SBCSEncoder(options, codec) { - this.encodeBuf = codec.encodeBuf; -} - -SBCSEncoder.prototype.write = function(str) { - var buf = Buffer.alloc(str.length); - for (var i = 0; i < str.length; i++) - buf[i] = this.encodeBuf[str.charCodeAt(i)]; - - return buf; -} - -SBCSEncoder.prototype.end = function() { -} - - -function SBCSDecoder(options, codec) { - this.decodeBuf = codec.decodeBuf; -} - -SBCSDecoder.prototype.write = function(buf) { - // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. - var decodeBuf = this.decodeBuf; - var newBuf = Buffer.alloc(buf.length*2); - var idx1 = 0, idx2 = 0; - for (var i = 0; i < buf.length; i++) { - idx1 = buf[i]*2; idx2 = i*2; - newBuf[idx2] = decodeBuf[idx1]; - newBuf[idx2+1] = decodeBuf[idx1+1]; - } - return newBuf.toString('ucs2'); -} - -SBCSDecoder.prototype.end = function() { -} diff --git a/node_modules/iconv-lite/encodings/sbcs-data-generated.js b/node_modules/iconv-lite/encodings/sbcs-data-generated.js deleted file mode 100644 index 9b48236..0000000 --- a/node_modules/iconv-lite/encodings/sbcs-data-generated.js +++ /dev/null @@ -1,451 +0,0 @@ -"use strict"; - -// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. -module.exports = { - "437": "cp437", - "737": "cp737", - "775": "cp775", - "850": "cp850", - "852": "cp852", - "855": "cp855", - "856": "cp856", - "857": "cp857", - "858": "cp858", - "860": "cp860", - "861": "cp861", - "862": "cp862", - "863": "cp863", - "864": "cp864", - "865": "cp865", - "866": "cp866", - "869": "cp869", - "874": "windows874", - "922": "cp922", - "1046": "cp1046", - "1124": "cp1124", - "1125": "cp1125", - "1129": "cp1129", - "1133": "cp1133", - "1161": "cp1161", - "1162": "cp1162", - "1163": "cp1163", - "1250": "windows1250", - "1251": "windows1251", - "1252": "windows1252", - "1253": "windows1253", - "1254": "windows1254", - "1255": "windows1255", - "1256": "windows1256", - "1257": "windows1257", - "1258": "windows1258", - "28591": "iso88591", - "28592": "iso88592", - "28593": "iso88593", - "28594": "iso88594", - "28595": "iso88595", - "28596": "iso88596", - "28597": "iso88597", - "28598": "iso88598", - "28599": "iso88599", - "28600": "iso885910", - "28601": "iso885911", - "28603": "iso885913", - "28604": "iso885914", - "28605": "iso885915", - "28606": "iso885916", - "windows874": { - "type": "_sbcs", - "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "win874": "windows874", - "cp874": "windows874", - "windows1250": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "win1250": "windows1250", - "cp1250": "windows1250", - "windows1251": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "win1251": "windows1251", - "cp1251": "windows1251", - "windows1252": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "win1252": "windows1252", - "cp1252": "windows1252", - "windows1253": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "win1253": "windows1253", - "cp1253": "windows1253", - "windows1254": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "win1254": "windows1254", - "cp1254": "windows1254", - "windows1255": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "win1255": "windows1255", - "cp1255": "windows1255", - "windows1256": { - "type": "_sbcs", - "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" - }, - "win1256": "windows1256", - "cp1256": "windows1256", - "windows1257": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" - }, - "win1257": "windows1257", - "cp1257": "windows1257", - "windows1258": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "win1258": "windows1258", - "cp1258": "windows1258", - "iso88591": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28591": "iso88591", - "iso88592": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "cp28592": "iso88592", - "iso88593": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" - }, - "cp28593": "iso88593", - "iso88594": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" - }, - "cp28594": "iso88594", - "iso88595": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" - }, - "cp28595": "iso88595", - "iso88596": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" - }, - "cp28596": "iso88596", - "iso88597": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "cp28597": "iso88597", - "iso88598": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "cp28598": "iso88598", - "iso88599": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "cp28599": "iso88599", - "iso885910": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" - }, - "cp28600": "iso885910", - "iso885911": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "cp28601": "iso885911", - "iso885913": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" - }, - "cp28603": "iso885913", - "iso885914": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" - }, - "cp28604": "iso885914", - "iso885915": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28605": "iso885915", - "iso885916": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" - }, - "cp28606": "iso885916", - "cp437": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm437": "cp437", - "csibm437": "cp437", - "cp737": { - "type": "_sbcs", - "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " - }, - "ibm737": "cp737", - "csibm737": "cp737", - "cp775": { - "type": "_sbcs", - "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " - }, - "ibm775": "cp775", - "csibm775": "cp775", - "cp850": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm850": "cp850", - "csibm850": "cp850", - "cp852": { - "type": "_sbcs", - "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " - }, - "ibm852": "cp852", - "csibm852": "cp852", - "cp855": { - "type": "_sbcs", - "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " - }, - "ibm855": "cp855", - "csibm855": "cp855", - "cp856": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm856": "cp856", - "csibm856": "cp856", - "cp857": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " - }, - "ibm857": "cp857", - "csibm857": "cp857", - "cp858": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm858": "cp858", - "csibm858": "cp858", - "cp860": { - "type": "_sbcs", - "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm860": "cp860", - "csibm860": "cp860", - "cp861": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm861": "cp861", - "csibm861": "cp861", - "cp862": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm862": "cp862", - "csibm862": "cp862", - "cp863": { - "type": "_sbcs", - "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm863": "cp863", - "csibm863": "cp863", - "cp864": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" - }, - "ibm864": "cp864", - "csibm864": "cp864", - "cp865": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm865": "cp865", - "csibm865": "cp865", - "cp866": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " - }, - "ibm866": "cp866", - "csibm866": "cp866", - "cp869": { - "type": "_sbcs", - "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " - }, - "ibm869": "cp869", - "csibm869": "cp869", - "cp922": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" - }, - "ibm922": "cp922", - "csibm922": "cp922", - "cp1046": { - "type": "_sbcs", - "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" - }, - "ibm1046": "cp1046", - "csibm1046": "cp1046", - "cp1124": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" - }, - "ibm1124": "cp1124", - "csibm1124": "cp1124", - "cp1125": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " - }, - "ibm1125": "cp1125", - "csibm1125": "cp1125", - "cp1129": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1129": "cp1129", - "csibm1129": "cp1129", - "cp1133": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" - }, - "ibm1133": "cp1133", - "csibm1133": "cp1133", - "cp1161": { - "type": "_sbcs", - "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " - }, - "ibm1161": "cp1161", - "csibm1161": "cp1161", - "cp1162": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "ibm1162": "cp1162", - "csibm1162": "cp1162", - "cp1163": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1163": "cp1163", - "csibm1163": "cp1163", - "maccroatian": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" - }, - "maccyrillic": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "macgreek": { - "type": "_sbcs", - "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" - }, - "maciceland": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macroman": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macromania": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macthai": { - "type": "_sbcs", - "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" - }, - "macturkish": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macukraine": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "koi8r": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8u": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8ru": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8t": { - "type": "_sbcs", - "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "armscii8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" - }, - "rk1048": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "tcvn": { - "type": "_sbcs", - "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" - }, - "georgianacademy": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "georgianps": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "pt154": { - "type": "_sbcs", - "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "viscii": { - "type": "_sbcs", - "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" - }, - "iso646cn": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "iso646jp": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "hproman8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" - }, - "macintosh": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "ascii": { - "type": "_sbcs", - "chars": "��������������������������������������������������������������������������������������������������������������������������������" - }, - "tis620": { - "type": "_sbcs", - "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - } -} \ No newline at end of file diff --git a/node_modules/iconv-lite/encodings/sbcs-data.js b/node_modules/iconv-lite/encodings/sbcs-data.js deleted file mode 100644 index fdb81a3..0000000 --- a/node_modules/iconv-lite/encodings/sbcs-data.js +++ /dev/null @@ -1,174 +0,0 @@ -"use strict"; - -// Manually added data to be used by sbcs codec in addition to generated one. - -module.exports = { - // Not supported by iconv, not sure why. - "10029": "maccenteuro", - "maccenteuro": { - "type": "_sbcs", - "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" - }, - - "808": "cp808", - "ibm808": "cp808", - "cp808": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " - }, - - "mik": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - - // Aliases of generated encodings. - "ascii8bit": "ascii", - "usascii": "ascii", - "ansix34": "ascii", - "ansix341968": "ascii", - "ansix341986": "ascii", - "csascii": "ascii", - "cp367": "ascii", - "ibm367": "ascii", - "isoir6": "ascii", - "iso646us": "ascii", - "iso646irv": "ascii", - "us": "ascii", - - "latin1": "iso88591", - "latin2": "iso88592", - "latin3": "iso88593", - "latin4": "iso88594", - "latin5": "iso88599", - "latin6": "iso885910", - "latin7": "iso885913", - "latin8": "iso885914", - "latin9": "iso885915", - "latin10": "iso885916", - - "csisolatin1": "iso88591", - "csisolatin2": "iso88592", - "csisolatin3": "iso88593", - "csisolatin4": "iso88594", - "csisolatincyrillic": "iso88595", - "csisolatinarabic": "iso88596", - "csisolatingreek" : "iso88597", - "csisolatinhebrew": "iso88598", - "csisolatin5": "iso88599", - "csisolatin6": "iso885910", - - "l1": "iso88591", - "l2": "iso88592", - "l3": "iso88593", - "l4": "iso88594", - "l5": "iso88599", - "l6": "iso885910", - "l7": "iso885913", - "l8": "iso885914", - "l9": "iso885915", - "l10": "iso885916", - - "isoir14": "iso646jp", - "isoir57": "iso646cn", - "isoir100": "iso88591", - "isoir101": "iso88592", - "isoir109": "iso88593", - "isoir110": "iso88594", - "isoir144": "iso88595", - "isoir127": "iso88596", - "isoir126": "iso88597", - "isoir138": "iso88598", - "isoir148": "iso88599", - "isoir157": "iso885910", - "isoir166": "tis620", - "isoir179": "iso885913", - "isoir199": "iso885914", - "isoir203": "iso885915", - "isoir226": "iso885916", - - "cp819": "iso88591", - "ibm819": "iso88591", - - "cyrillic": "iso88595", - - "arabic": "iso88596", - "arabic8": "iso88596", - "ecma114": "iso88596", - "asmo708": "iso88596", - - "greek" : "iso88597", - "greek8" : "iso88597", - "ecma118" : "iso88597", - "elot928" : "iso88597", - - "hebrew": "iso88598", - "hebrew8": "iso88598", - - "turkish": "iso88599", - "turkish8": "iso88599", - - "thai": "iso885911", - "thai8": "iso885911", - - "celtic": "iso885914", - "celtic8": "iso885914", - "isoceltic": "iso885914", - - "tis6200": "tis620", - "tis62025291": "tis620", - "tis62025330": "tis620", - - "10000": "macroman", - "10006": "macgreek", - "10007": "maccyrillic", - "10079": "maciceland", - "10081": "macturkish", - - "cspc8codepage437": "cp437", - "cspc775baltic": "cp775", - "cspc850multilingual": "cp850", - "cspcp852": "cp852", - "cspc862latinhebrew": "cp862", - "cpgr": "cp869", - - "msee": "cp1250", - "mscyrl": "cp1251", - "msansi": "cp1252", - "msgreek": "cp1253", - "msturk": "cp1254", - "mshebr": "cp1255", - "msarab": "cp1256", - "winbaltrim": "cp1257", - - "cp20866": "koi8r", - "20866": "koi8r", - "ibm878": "koi8r", - "cskoi8r": "koi8r", - - "cp21866": "koi8u", - "21866": "koi8u", - "ibm1168": "koi8u", - - "strk10482002": "rk1048", - - "tcvn5712": "tcvn", - "tcvn57121": "tcvn", - - "gb198880": "iso646cn", - "cn": "iso646cn", - - "csiso14jisc6220ro": "iso646jp", - "jisc62201969ro": "iso646jp", - "jp": "iso646jp", - - "cshproman8": "hproman8", - "r8": "hproman8", - "roman8": "hproman8", - "xroman8": "hproman8", - "ibm1051": "hproman8", - - "mac": "macintosh", - "csmacintosh": "macintosh", -}; - diff --git a/node_modules/iconv-lite/encodings/tables/big5-added.json b/node_modules/iconv-lite/encodings/tables/big5-added.json deleted file mode 100644 index 3c3d3c2..0000000 --- a/node_modules/iconv-lite/encodings/tables/big5-added.json +++ /dev/null @@ -1,122 +0,0 @@ -[ -["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"], -["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"], -["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"], -["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"], -["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"], -["8940","𪎩𡅅"], -["8943","攊"], -["8946","丽滝鵎釟"], -["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"], -["89a1","琑糼緍楆竉刧"], -["89ab","醌碸酞肼"], -["89b0","贋胶𠧧"], -["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"], -["89c1","溚舾甙"], -["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"], -["8a40","𧶄唥"], -["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"], -["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"], -["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"], -["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"], -["8aac","䠋𠆩㿺塳𢶍"], -["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"], -["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"], -["8ac9","𪘁𠸉𢫏𢳉"], -["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"], -["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"], -["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"], -["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"], -["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"], -["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"], -["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"], -["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"], -["8ca1","𣏹椙橃𣱣泿"], -["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"], -["8cc9","顨杫䉶圽"], -["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"], -["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"], -["8d40","𠮟"], -["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"], -["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"], -["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"], -["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"], -["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"], -["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"], -["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"], -["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"], -["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"], -["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"], -["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"], -["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"], -["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"], -["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"], -["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"], -["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"], -["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"], -["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"], -["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"], -["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"], -["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"], -["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"], -["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"], -["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"], -["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"], -["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"], -["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"], -["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"], -["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"], -["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"], -["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"], -["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"], -["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"], -["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"], -["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"], -["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"], -["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"], -["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"], -["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"], -["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"], -["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"], -["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"], -["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"], -["9fae","酙隁酜"], -["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"], -["9fc1","𤤙盖鮝个𠳔莾衂"], -["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"], -["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"], -["9fe7","毺蠘罸"], -["9feb","嘠𪙊蹷齓"], -["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"], -["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"], -["a055","𡠻𦸅"], -["a058","詾𢔛"], -["a05b","惽癧髗鵄鍮鮏蟵"], -["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"], -["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"], -["a0a1","嵗𨯂迚𨸹"], -["a0a6","僙𡵆礆匲阸𠼻䁥"], -["a0ae","矾"], -["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"], -["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"], -["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"], -["a3c0","␀",31,"␡"], -["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23], -["c740","す",58,"ァアィイ"], -["c7a1","ゥ",81,"А",5,"ЁЖ",4], -["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"], -["c8a1","龰冈龱𧘇"], -["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"], -["c8f5","ʃɐɛɔɵœøŋʊɪ"], -["f9fe","■"], -["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"], -["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"], -["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"], -["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"], -["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"], -["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"], -["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"], -["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"], -["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"], -["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"] -] diff --git a/node_modules/iconv-lite/encodings/tables/cp936.json b/node_modules/iconv-lite/encodings/tables/cp936.json deleted file mode 100644 index 49ddb9a..0000000 --- a/node_modules/iconv-lite/encodings/tables/cp936.json +++ /dev/null @@ -1,264 +0,0 @@ -[ -["0","\u0000",127,"€"], -["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"], -["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"], -["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11], -["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"], -["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"], -["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5], -["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"], -["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"], -["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"], -["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"], -["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"], -["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"], -["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4], -["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6], -["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"], -["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7], -["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"], -["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"], -["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"], -["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5], -["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"], -["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6], -["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"], -["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4], -["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4], -["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"], -["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"], -["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6], -["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"], -["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"], -["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"], -["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6], -["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"], -["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"], -["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"], -["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"], -["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"], -["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"], -["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8], -["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"], -["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"], -["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"], -["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"], -["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5], -["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"], -["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"], -["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"], -["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"], -["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5], -["9980","檧檨檪檭",114,"欥欦欨",6], -["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"], -["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"], -["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"], -["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"], -["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"], -["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5], -["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"], -["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"], -["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6], -["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"], -["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"], -["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4], -["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19], -["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"], -["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"], -["a2a1","ⅰ",9], -["a2b1","⒈",19,"⑴",19,"①",9], -["a2e5","㈠",9], -["a2f1","Ⅰ",11], -["a3a1","!"#¥%",88," ̄"], -["a4a1","ぁ",82], -["a5a1","ァ",85], -["a6a1","Α",16,"Σ",6], -["a6c1","α",16,"σ",6], -["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"], -["a6ee","︻︼︷︸︱"], -["a6f4","︳︴"], -["a7a1","А",5,"ЁЖ",25], -["a7d1","а",5,"ёж",25], -["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6], -["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"], -["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"], -["a8bd","ńň"], -["a8c0","ɡ"], -["a8c5","ㄅ",36], -["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"], -["a959","℡㈱"], -["a95c","‐"], -["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8], -["a980","﹢",4,"﹨﹩﹪﹫"], -["a996","〇"], -["a9a4","─",75], -["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8], -["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"], -["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4], -["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4], -["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11], -["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"], -["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12], -["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"], -["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"], -["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"], -["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"], -["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"], -["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"], -["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"], -["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"], -["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"], -["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4], -["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"], -["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"], -["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"], -["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9], -["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"], -["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"], -["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"], -["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"], -["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"], -["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16], -["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"], -["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"], -["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"], -["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"], -["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"], -["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"], -["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"], -["bb40","籃",9,"籎",36,"籵",5,"籾",9], -["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"], -["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5], -["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"], -["bd40","紷",54,"絯",7], -["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"], -["be40","継",12,"綧",6,"綯",42], -["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"], -["bf40","緻",62], -["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"], -["c040","繞",35,"纃",23,"纜纝纞"], -["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"], -["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"], -["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"], -["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"], -["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"], -["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"], -["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"], -["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"], -["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"], -["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"], -["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"], -["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"], -["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"], -["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"], -["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"], -["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"], -["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"], -["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"], -["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"], -["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10], -["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"], -["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"], -["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"], -["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"], -["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"], -["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"], -["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"], -["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"], -["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"], -["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9], -["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"], -["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"], -["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"], -["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5], -["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"], -["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"], -["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"], -["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6], -["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"], -["d440","訞",31,"訿",8,"詉",21], -["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"], -["d540","誁",7,"誋",7,"誔",46], -["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"], -["d640","諤",34,"謈",27], -["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"], -["d740","譆",31,"譧",4,"譭",25], -["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"], -["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"], -["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"], -["d940","貮",62], -["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"], -["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"], -["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"], -["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"], -["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"], -["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7], -["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"], -["dd40","軥",62], -["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"], -["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"], -["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"], -["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"], -["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"], -["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"], -["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"], -["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"], -["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"], -["e240","釦",62], -["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"], -["e340","鉆",45,"鉵",16], -["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"], -["e440","銨",5,"銯",24,"鋉",31], -["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"], -["e540","錊",51,"錿",10], -["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"], -["e640","鍬",34,"鎐",27], -["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"], -["e740","鏎",7,"鏗",54], -["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"], -["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"], -["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"], -["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42], -["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"], -["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"], -["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"], -["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"], -["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"], -["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7], -["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"], -["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46], -["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"], -["ee40","頏",62], -["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"], -["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4], -["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"], -["f040","餈",4,"餎餏餑",28,"餯",26], -["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"], -["f140","馌馎馚",10,"馦馧馩",47], -["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"], -["f240","駺",62], -["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"], -["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"], -["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"], -["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5], -["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"], -["f540","魼",62], -["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"], -["f640","鯜",62], -["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"], -["f740","鰼",62], -["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"], -["f840","鳣",62], -["f880","鴢",32], -["f940","鵃",62], -["f980","鶂",32], -["fa40","鶣",62], -["fa80","鷢",32], -["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"], -["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"], -["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6], -["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"], -["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38], -["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"], -["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"] -] diff --git a/node_modules/iconv-lite/encodings/tables/cp949.json b/node_modules/iconv-lite/encodings/tables/cp949.json deleted file mode 100644 index 2022a00..0000000 --- a/node_modules/iconv-lite/encodings/tables/cp949.json +++ /dev/null @@ -1,273 +0,0 @@ -[ -["0","\u0000",127], -["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"], -["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"], -["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"], -["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5], -["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"], -["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18], -["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7], -["8361","긝",18,"긲긳긵긶긹긻긼"], -["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8], -["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8], -["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18], -["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"], -["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4], -["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"], -["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"], -["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"], -["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10], -["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"], -["8741","놞",9,"놩",15], -["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"], -["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4], -["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4], -["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"], -["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"], -["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"], -["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"], -["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15], -["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"], -["8a61","둧",4,"둭",18,"뒁뒂"], -["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"], -["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"], -["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8], -["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18], -["8c41","똀",15,"똒똓똕똖똗똙",4], -["8c61","똞",6,"똦",5,"똭",6,"똵",5], -["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16], -["8d41","뛃",16,"뛕",8], -["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"], -["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"], -["8e41","랟랡",6,"랪랮",5,"랶랷랹",8], -["8e61","럂",4,"럈럊",19], -["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7], -["8f41","뢅",7,"뢎",17], -["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4], -["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5], -["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"], -["9061","륾",5,"릆릈릋릌릏",15], -["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"], -["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5], -["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5], -["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6], -["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"], -["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4], -["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"], -["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"], -["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8], -["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"], -["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8], -["9461","봞",5,"봥",6,"봭",12], -["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24], -["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"], -["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"], -["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14], -["9641","뺸",23,"뻒뻓"], -["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8], -["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44], -["9741","뾃",16,"뾕",8], -["9761","뾞",17,"뾱",7], -["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"], -["9841","쁀",16,"쁒",5,"쁙쁚쁛"], -["9861","쁝쁞쁟쁡",6,"쁪",15], -["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"], -["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"], -["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"], -["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"], -["9a41","숤숥숦숧숪숬숮숰숳숵",16], -["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"], -["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"], -["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8], -["9b61","쌳",17,"썆",7], -["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"], -["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5], -["9c61","쏿",8,"쐉",6,"쐑",9], -["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12], -["9d41","쒪",13,"쒹쒺쒻쒽",8], -["9d61","쓆",25], -["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"], -["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"], -["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"], -["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"], -["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"], -["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"], -["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"], -["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"], -["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13], -["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"], -["a141","좥좦좧좩",18,"좾좿죀죁"], -["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"], -["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"], -["a241","줐줒",5,"줙",18], -["a261","줭",6,"줵",18], -["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"], -["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"], -["a361","즑",6,"즚즜즞",16], -["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"], -["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"], -["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12], -["a481","쨦쨧쨨쨪",28,"ㄱ",93], -["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"], -["a561","쩫",17,"쩾",5,"쪅쪆"], -["a581","쪇",16,"쪙",14,"ⅰ",9], -["a5b0","Ⅰ",9], -["a5c1","Α",16,"Σ",6], -["a5e1","α",16,"σ",6], -["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"], -["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6], -["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7], -["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7], -["a761","쬪",22,"쭂쭃쭄"], -["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"], -["a841","쭭",10,"쭺",14], -["a861","쮉",18,"쮝",6], -["a881","쮤",19,"쮹",11,"ÆÐªĦ"], -["a8a6","IJ"], -["a8a8","ĿŁØŒºÞŦŊ"], -["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"], -["a941","쯅",14,"쯕",10], -["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18], -["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"], -["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"], -["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"], -["aa81","챳챴챶",29,"ぁ",82], -["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"], -["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5], -["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85], -["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"], -["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4], -["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25], -["acd1","а",5,"ёж",25], -["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7], -["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"], -["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"], -["ae41","췆",5,"췍췎췏췑",16], -["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4], -["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"], -["af41","츬츭츮츯츲츴츶",19], -["af61","칊",13,"칚칛칝칞칢",5,"칪칬"], -["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"], -["b041","캚",5,"캢캦",5,"캮",12], -["b061","캻",5,"컂",19], -["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"], -["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"], -["b161","켥",6,"켮켲",5,"켹",11], -["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"], -["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"], -["b261","쾎",18,"쾢",5,"쾩"], -["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"], -["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"], -["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5], -["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"], -["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5], -["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"], -["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"], -["b541","킕",14,"킦킧킩킪킫킭",5], -["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4], -["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"], -["b641","턅",7,"턎",17], -["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"], -["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"], -["b741","텮",13,"텽",6,"톅톆톇톉톊"], -["b761","톋",20,"톢톣톥톦톧"], -["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"], -["b841","퇐",7,"퇙",17], -["b861","퇫",8,"퇵퇶퇷퇹",13], -["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"], -["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"], -["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"], -["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"], -["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"], -["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5], -["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"], -["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"], -["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"], -["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"], -["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"], -["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"], -["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"], -["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"], -["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13], -["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"], -["be41","퐸",7,"푁푂푃푅",14], -["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"], -["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"], -["bf41","풞",10,"풪",14], -["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"], -["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"], -["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5], -["c061","픞",25], -["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"], -["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"], -["c161","햌햍햎햏햑",19,"햦햧"], -["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"], -["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"], -["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"], -["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"], -["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4], -["c361","홢",4,"홨홪",5,"홲홳홵",11], -["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"], -["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"], -["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4], -["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"], -["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"], -["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4], -["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"], -["c641","힍힎힏힑",6,"힚힜힞",5], -["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"], -["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"], -["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"], -["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"], -["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"], -["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"], -["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"], -["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"], -["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"], -["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"], -["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"], -["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"], -["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"], -["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"], -["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"], -["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"], -["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"], -["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"], -["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"], -["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"], -["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"], -["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"], -["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"], -["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"], -["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"], -["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"], -["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"], -["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"], -["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"], -["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"], -["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"], -["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"], -["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"], -["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"], -["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"], -["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"], -["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"], -["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"], -["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"], -["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"], -["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"], -["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"], -["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"], -["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"], -["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"], -["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"], -["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"], -["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"], -["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"], -["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"], -["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"], -["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"], -["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"], -["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"], -["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"] -] diff --git a/node_modules/iconv-lite/encodings/tables/cp950.json b/node_modules/iconv-lite/encodings/tables/cp950.json deleted file mode 100644 index d8bc871..0000000 --- a/node_modules/iconv-lite/encodings/tables/cp950.json +++ /dev/null @@ -1,177 +0,0 @@ -[ -["0","\u0000",127], -["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"], -["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"], -["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"], -["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21], -["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10], -["a3a1","ㄐ",25,"˙ˉˊˇˋ"], -["a3e1","€"], -["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"], -["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"], -["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"], -["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"], -["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"], -["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"], -["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"], -["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"], -["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"], -["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"], -["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"], -["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"], -["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"], -["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"], -["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"], -["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"], -["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"], -["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"], -["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"], -["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"], -["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"], -["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"], -["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"], -["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"], -["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"], -["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"], -["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"], -["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"], -["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"], -["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"], -["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"], -["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"], -["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"], -["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"], -["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"], -["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"], -["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"], -["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"], -["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"], -["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"], -["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"], -["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"], -["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"], -["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"], -["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"], -["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"], -["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"], -["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"], -["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"], -["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"], -["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"], -["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"], -["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"], -["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"], -["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"], -["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"], -["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"], -["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"], -["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"], -["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"], -["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"], -["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"], -["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"], -["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"], -["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"], -["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"], -["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"], -["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"], -["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"], -["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"], -["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"], -["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"], -["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"], -["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"], -["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"], -["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"], -["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"], -["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"], -["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"], -["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"], -["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"], -["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"], -["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"], -["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"], -["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"], -["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"], -["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"], -["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"], -["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"], -["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"], -["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"], -["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"], -["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"], -["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"], -["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"], -["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"], -["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"], -["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"], -["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"], -["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"], -["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"], -["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"], -["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"], -["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"], -["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"], -["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"], -["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"], -["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"], -["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"], -["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"], -["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"], -["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"], -["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"], -["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"], -["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"], -["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"], -["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"], -["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"], -["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"], -["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"], -["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"], -["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"], -["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"], -["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"], -["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"], -["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"], -["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"], -["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"], -["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"], -["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"], -["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"], -["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"], -["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"], -["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"], -["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"], -["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"], -["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"], -["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"], -["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"], -["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"], -["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"], -["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"], -["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"], -["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"], -["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"], -["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"], -["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"], -["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"], -["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"], -["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"], -["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"], -["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"], -["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"], -["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"], -["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"], -["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"], -["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"], -["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"], -["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"], -["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"], -["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"], -["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"], -["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"], -["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"], -["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"], -["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"], -["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"] -] diff --git a/node_modules/iconv-lite/encodings/tables/eucjp.json b/node_modules/iconv-lite/encodings/tables/eucjp.json deleted file mode 100644 index 4fa61ca..0000000 --- a/node_modules/iconv-lite/encodings/tables/eucjp.json +++ /dev/null @@ -1,182 +0,0 @@ -[ -["0","\u0000",127], -["8ea1","。",62], -["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"], -["a2a1","◆□■△▲▽▼※〒→←↑↓〓"], -["a2ba","∈∋⊆⊇⊂⊃∪∩"], -["a2ca","∧∨¬⇒⇔∀∃"], -["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], -["a2f2","ʼn♯♭♪†‡¶"], -["a2fe","◯"], -["a3b0","0",9], -["a3c1","A",25], -["a3e1","a",25], -["a4a1","ぁ",82], -["a5a1","ァ",85], -["a6a1","Α",16,"Σ",6], -["a6c1","α",16,"σ",6], -["a7a1","А",5,"ЁЖ",25], -["a7d1","а",5,"ёж",25], -["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], -["ada1","①",19,"Ⅰ",9], -["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], -["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], -["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], -["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"], -["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], -["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"], -["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], -["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"], -["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], -["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"], -["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], -["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"], -["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], -["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"], -["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], -["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"], -["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], -["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"], -["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], -["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"], -["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], -["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"], -["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], -["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"], -["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], -["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"], -["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], -["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"], -["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], -["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"], -["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], -["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"], -["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], -["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], -["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], -["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"], -["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], -["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"], -["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], -["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"], -["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], -["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"], -["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], -["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"], -["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], -["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"], -["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], -["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"], -["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], -["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"], -["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], -["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"], -["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], -["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"], -["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], -["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"], -["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], -["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"], -["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], -["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"], -["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], -["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"], -["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], -["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"], -["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], -["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"], -["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], -["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"], -["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], -["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"], -["f4a1","堯槇遙瑤凜熙"], -["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"], -["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], -["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"], -["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], -["fcf1","ⅰ",9,"¬¦'""], -["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"], -["8fa2c2","¡¦¿"], -["8fa2eb","ºª©®™¤№"], -["8fa6e1","ΆΈΉΊΪ"], -["8fa6e7","Ό"], -["8fa6e9","ΎΫ"], -["8fa6ec","Ώ"], -["8fa6f1","άέήίϊΐόςύϋΰώ"], -["8fa7c2","Ђ",10,"ЎЏ"], -["8fa7f2","ђ",10,"ўџ"], -["8fa9a1","ÆĐ"], -["8fa9a4","Ħ"], -["8fa9a6","IJ"], -["8fa9a8","ŁĿ"], -["8fa9ab","ŊØŒ"], -["8fa9af","ŦÞ"], -["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"], -["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"], -["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"], -["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"], -["8fabbd","ġĥíìïîǐ"], -["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"], -["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"], -["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"], -["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"], -["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"], -["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"], -["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"], -["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"], -["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"], -["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"], -["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"], -["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"], -["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"], -["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"], -["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"], -["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"], -["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"], -["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"], -["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"], -["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"], -["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"], -["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"], -["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"], -["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"], -["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"], -["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"], -["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"], -["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"], -["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"], -["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"], -["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"], -["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"], -["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"], -["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"], -["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"], -["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5], -["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"], -["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"], -["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"], -["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"], -["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"], -["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"], -["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"], -["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"], -["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"], -["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"], -["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"], -["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"], -["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"], -["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"], -["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"], -["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"], -["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"], -["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"], -["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"], -["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"], -["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"], -["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"], -["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4], -["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"], -["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"], -["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"], -["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"] -] diff --git a/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json b/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json deleted file mode 100644 index 85c6934..0000000 --- a/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json +++ /dev/null @@ -1 +0,0 @@ -{"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]} \ No newline at end of file diff --git a/node_modules/iconv-lite/encodings/tables/gbk-added.json b/node_modules/iconv-lite/encodings/tables/gbk-added.json deleted file mode 100644 index 8abfa9f..0000000 --- a/node_modules/iconv-lite/encodings/tables/gbk-added.json +++ /dev/null @@ -1,55 +0,0 @@ -[ -["a140","",62], -["a180","",32], -["a240","",62], -["a280","",32], -["a2ab","",5], -["a2e3","€"], -["a2ef",""], -["a2fd",""], -["a340","",62], -["a380","",31," "], -["a440","",62], -["a480","",32], -["a4f4","",10], -["a540","",62], -["a580","",32], -["a5f7","",7], -["a640","",62], -["a680","",32], -["a6b9","",7], -["a6d9","",6], -["a6ec",""], -["a6f3",""], -["a6f6","",8], -["a740","",62], -["a780","",32], -["a7c2","",14], -["a7f2","",12], -["a896","",10], -["a8bc",""], -["a8bf","ǹ"], -["a8c1",""], -["a8ea","",20], -["a958",""], -["a95b",""], -["a95d",""], -["a989","〾⿰",11], -["a997","",12], -["a9f0","",14], -["aaa1","",93], -["aba1","",93], -["aca1","",93], -["ada1","",93], -["aea1","",93], -["afa1","",93], -["d7fa","",4], -["f8a1","",93], -["f9a1","",93], -["faa1","",93], -["fba1","",93], -["fca1","",93], -["fda1","",93], -["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"], -["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93] -] diff --git a/node_modules/iconv-lite/encodings/tables/shiftjis.json b/node_modules/iconv-lite/encodings/tables/shiftjis.json deleted file mode 100644 index 5a3a43c..0000000 --- a/node_modules/iconv-lite/encodings/tables/shiftjis.json +++ /dev/null @@ -1,125 +0,0 @@ -[ -["0","\u0000",128], -["a1","。",62], -["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"], -["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"], -["81b8","∈∋⊆⊇⊂⊃∪∩"], -["81c8","∧∨¬⇒⇔∀∃"], -["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], -["81f0","ʼn♯♭♪†‡¶"], -["81fc","◯"], -["824f","0",9], -["8260","A",25], -["8281","a",25], -["829f","ぁ",82], -["8340","ァ",62], -["8380","ム",22], -["839f","Α",16,"Σ",6], -["83bf","α",16,"σ",6], -["8440","А",5,"ЁЖ",25], -["8470","а",5,"ёж",7], -["8480","о",17], -["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], -["8740","①",19,"Ⅰ",9], -["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], -["877e","㍻"], -["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], -["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], -["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"], -["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], -["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"], -["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], -["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"], -["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], -["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"], -["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], -["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"], -["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], -["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"], -["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], -["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"], -["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], -["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"], -["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], -["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"], -["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], -["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"], -["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], -["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"], -["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], -["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"], -["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], -["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"], -["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], -["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"], -["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], -["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"], -["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], -["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], -["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], -["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"], -["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], -["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"], -["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], -["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"], -["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], -["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"], -["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], -["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"], -["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], -["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"], -["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], -["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"], -["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], -["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"], -["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], -["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"], -["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], -["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"], -["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], -["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"], -["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], -["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"], -["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], -["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"], -["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], -["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"], -["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], -["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"], -["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], -["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"], -["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], -["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"], -["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], -["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"], -["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"], -["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"], -["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], -["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"], -["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], -["eeef","ⅰ",9,"¬¦'""], -["f040","",62], -["f080","",124], -["f140","",62], -["f180","",124], -["f240","",62], -["f280","",124], -["f340","",62], -["f380","",124], -["f440","",62], -["f480","",124], -["f540","",62], -["f580","",124], -["f640","",62], -["f680","",124], -["f740","",62], -["f780","",124], -["f840","",62], -["f880","",124], -["f940",""], -["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"], -["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"], -["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"], -["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"], -["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"] -] diff --git a/node_modules/iconv-lite/encodings/utf16.js b/node_modules/iconv-lite/encodings/utf16.js deleted file mode 100644 index 54765ae..0000000 --- a/node_modules/iconv-lite/encodings/utf16.js +++ /dev/null @@ -1,177 +0,0 @@ -"use strict"; -var Buffer = require("safer-buffer").Buffer; - -// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js - -// == UTF16-BE codec. ========================================================== - -exports.utf16be = Utf16BECodec; -function Utf16BECodec() { -} - -Utf16BECodec.prototype.encoder = Utf16BEEncoder; -Utf16BECodec.prototype.decoder = Utf16BEDecoder; -Utf16BECodec.prototype.bomAware = true; - - -// -- Encoding - -function Utf16BEEncoder() { -} - -Utf16BEEncoder.prototype.write = function(str) { - var buf = Buffer.from(str, 'ucs2'); - for (var i = 0; i < buf.length; i += 2) { - var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; - } - return buf; -} - -Utf16BEEncoder.prototype.end = function() { -} - - -// -- Decoding - -function Utf16BEDecoder() { - this.overflowByte = -1; -} - -Utf16BEDecoder.prototype.write = function(buf) { - if (buf.length == 0) - return ''; - - var buf2 = Buffer.alloc(buf.length + 1), - i = 0, j = 0; - - if (this.overflowByte !== -1) { - buf2[0] = buf[0]; - buf2[1] = this.overflowByte; - i = 1; j = 2; - } - - for (; i < buf.length-1; i += 2, j+= 2) { - buf2[j] = buf[i+1]; - buf2[j+1] = buf[i]; - } - - this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; - - return buf2.slice(0, j).toString('ucs2'); -} - -Utf16BEDecoder.prototype.end = function() { -} - - -// == UTF-16 codec ============================================================= -// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. -// Defaults to UTF-16LE, as it's prevalent and default in Node. -// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le -// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); - -// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). - -exports.utf16 = Utf16Codec; -function Utf16Codec(codecOptions, iconv) { - this.iconv = iconv; -} - -Utf16Codec.prototype.encoder = Utf16Encoder; -Utf16Codec.prototype.decoder = Utf16Decoder; - - -// -- Encoding (pass-through) - -function Utf16Encoder(options, codec) { - options = options || {}; - if (options.addBOM === undefined) - options.addBOM = true; - this.encoder = codec.iconv.getEncoder('utf-16le', options); -} - -Utf16Encoder.prototype.write = function(str) { - return this.encoder.write(str); -} - -Utf16Encoder.prototype.end = function() { - return this.encoder.end(); -} - - -// -- Decoding - -function Utf16Decoder(options, codec) { - this.decoder = null; - this.initialBytes = []; - this.initialBytesLen = 0; - - this.options = options || {}; - this.iconv = codec.iconv; -} - -Utf16Decoder.prototype.write = function(buf) { - if (!this.decoder) { - // Codec is not chosen yet. Accumulate initial bytes. - this.initialBytes.push(buf); - this.initialBytesLen += buf.length; - - if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) - return ''; - - // We have enough bytes -> detect endianness. - var buf = Buffer.concat(this.initialBytes), - encoding = detectEncoding(buf, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - this.initialBytes.length = this.initialBytesLen = 0; - } - - return this.decoder.write(buf); -} - -Utf16Decoder.prototype.end = function() { - if (!this.decoder) { - var buf = Buffer.concat(this.initialBytes), - encoding = detectEncoding(buf, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - - var res = this.decoder.write(buf), - trail = this.decoder.end(); - - return trail ? (res + trail) : res; - } - return this.decoder.end(); -} - -function detectEncoding(buf, defaultEncoding) { - var enc = defaultEncoding || 'utf-16le'; - - if (buf.length >= 2) { - // Check BOM. - if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM - enc = 'utf-16be'; - else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM - enc = 'utf-16le'; - else { - // No BOM found. Try to deduce encoding from initial content. - // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. - // So, we count ASCII as if it was LE or BE, and decide from that. - var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions - _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. - - for (var i = 0; i < _len; i += 2) { - if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; - if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; - } - - if (asciiCharsBE > asciiCharsLE) - enc = 'utf-16be'; - else if (asciiCharsBE < asciiCharsLE) - enc = 'utf-16le'; - } - } - - return enc; -} - - diff --git a/node_modules/iconv-lite/encodings/utf7.js b/node_modules/iconv-lite/encodings/utf7.js deleted file mode 100644 index b7631c2..0000000 --- a/node_modules/iconv-lite/encodings/utf7.js +++ /dev/null @@ -1,290 +0,0 @@ -"use strict"; -var Buffer = require("safer-buffer").Buffer; - -// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 -// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 - -exports.utf7 = Utf7Codec; -exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 -function Utf7Codec(codecOptions, iconv) { - this.iconv = iconv; -}; - -Utf7Codec.prototype.encoder = Utf7Encoder; -Utf7Codec.prototype.decoder = Utf7Decoder; -Utf7Codec.prototype.bomAware = true; - - -// -- Encoding - -var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; - -function Utf7Encoder(options, codec) { - this.iconv = codec.iconv; -} - -Utf7Encoder.prototype.write = function(str) { - // Naive implementation. - // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". - return Buffer.from(str.replace(nonDirectChars, function(chunk) { - return "+" + (chunk === '+' ? '' : - this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) - + "-"; - }.bind(this))); -} - -Utf7Encoder.prototype.end = function() { -} - - -// -- Decoding - -function Utf7Decoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} - -var base64Regex = /[A-Za-z0-9\/+]/; -var base64Chars = []; -for (var i = 0; i < 256; i++) - base64Chars[i] = base64Regex.test(String.fromCharCode(i)); - -var plusChar = '+'.charCodeAt(0), - minusChar = '-'.charCodeAt(0), - andChar = '&'.charCodeAt(0); - -Utf7Decoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; - - // The decoder is more involved as we must handle chunks in stream. - - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '+' - if (buf[i] == plusChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64Chars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" - res += "+"; - } else { - var b64str = base64Accum + buf.slice(lastI, i).toString(); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } - - if (buf[i] != minusChar) // Minus is absorbed after base64. - i--; - - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } - } - } - - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString(); - - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); - - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } - - this.inBase64 = inBase64; - this.base64Accum = base64Accum; - - return res; -} - -Utf7Decoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); - - this.inBase64 = false; - this.base64Accum = ''; - return res; -} - - -// UTF-7-IMAP codec. -// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) -// Differences: -// * Base64 part is started by "&" instead of "+" -// * Direct characters are 0x20-0x7E, except "&" (0x26) -// * In Base64, "," is used instead of "/" -// * Base64 must not be used to represent direct characters. -// * No implicit shift back from Base64 (should always end with '-') -// * String must end in non-shifted position. -// * "-&" while in base64 is not allowed. - - -exports.utf7imap = Utf7IMAPCodec; -function Utf7IMAPCodec(codecOptions, iconv) { - this.iconv = iconv; -}; - -Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; -Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; -Utf7IMAPCodec.prototype.bomAware = true; - - -// -- Encoding - -function Utf7IMAPEncoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = Buffer.alloc(6); - this.base64AccumIdx = 0; -} - -Utf7IMAPEncoder.prototype.write = function(str) { - var inBase64 = this.inBase64, - base64Accum = this.base64Accum, - base64AccumIdx = this.base64AccumIdx, - buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; - - for (var i = 0; i < str.length; i++) { - var uChar = str.charCodeAt(i); - if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. - if (inBase64) { - if (base64AccumIdx > 0) { - bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - base64AccumIdx = 0; - } - - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - inBase64 = false; - } - - if (!inBase64) { - buf[bufIdx++] = uChar; // Write direct character - - if (uChar === andChar) // Ampersand -> '&-' - buf[bufIdx++] = minusChar; - } - - } else { // Non-direct character - if (!inBase64) { - buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. - inBase64 = true; - } - if (inBase64) { - base64Accum[base64AccumIdx++] = uChar >> 8; - base64Accum[base64AccumIdx++] = uChar & 0xFF; - - if (base64AccumIdx == base64Accum.length) { - bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); - base64AccumIdx = 0; - } - } - } - } - - this.inBase64 = inBase64; - this.base64AccumIdx = base64AccumIdx; - - return buf.slice(0, bufIdx); -} - -Utf7IMAPEncoder.prototype.end = function() { - var buf = Buffer.alloc(10), bufIdx = 0; - if (this.inBase64) { - if (this.base64AccumIdx > 0) { - bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - this.base64AccumIdx = 0; - } - - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - this.inBase64 = false; - } - - return buf.slice(0, bufIdx); -} - - -// -- Decoding - -function Utf7IMAPDecoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} - -var base64IMAPChars = base64Chars.slice(); -base64IMAPChars[','.charCodeAt(0)] = true; - -Utf7IMAPDecoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; - - // The decoder is more involved as we must handle chunks in stream. - // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). - - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '&' - if (buf[i] == andChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64IMAPChars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" - res += "&"; - } else { - var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } - - if (buf[i] != minusChar) // Minus may be absorbed after base64. - i--; - - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } - } - } - - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); - - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); - - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } - - this.inBase64 = inBase64; - this.base64Accum = base64Accum; - - return res; -} - -Utf7IMAPDecoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); - - this.inBase64 = false; - this.base64Accum = ''; - return res; -} - - diff --git a/node_modules/iconv-lite/lib/bom-handling.js b/node_modules/iconv-lite/lib/bom-handling.js deleted file mode 100644 index 1050872..0000000 --- a/node_modules/iconv-lite/lib/bom-handling.js +++ /dev/null @@ -1,52 +0,0 @@ -"use strict"; - -var BOMChar = '\uFEFF'; - -exports.PrependBOM = PrependBOMWrapper -function PrependBOMWrapper(encoder, options) { - this.encoder = encoder; - this.addBOM = true; -} - -PrependBOMWrapper.prototype.write = function(str) { - if (this.addBOM) { - str = BOMChar + str; - this.addBOM = false; - } - - return this.encoder.write(str); -} - -PrependBOMWrapper.prototype.end = function() { - return this.encoder.end(); -} - - -//------------------------------------------------------------------------------ - -exports.StripBOM = StripBOMWrapper; -function StripBOMWrapper(decoder, options) { - this.decoder = decoder; - this.pass = false; - this.options = options || {}; -} - -StripBOMWrapper.prototype.write = function(buf) { - var res = this.decoder.write(buf); - if (this.pass || !res) - return res; - - if (res[0] === BOMChar) { - res = res.slice(1); - if (typeof this.options.stripBOM === 'function') - this.options.stripBOM(); - } - - this.pass = true; - return res; -} - -StripBOMWrapper.prototype.end = function() { - return this.decoder.end(); -} - diff --git a/node_modules/iconv-lite/lib/extend-node.js b/node_modules/iconv-lite/lib/extend-node.js deleted file mode 100644 index 87f5394..0000000 --- a/node_modules/iconv-lite/lib/extend-node.js +++ /dev/null @@ -1,217 +0,0 @@ -"use strict"; -var Buffer = require("buffer").Buffer; -// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer - -// == Extend Node primitives to use iconv-lite ================================= - -module.exports = function (iconv) { - var original = undefined; // Place to keep original methods. - - // Node authors rewrote Buffer internals to make it compatible with - // Uint8Array and we cannot patch key functions since then. - // Note: this does use older Buffer API on a purpose - iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); - - iconv.extendNodeEncodings = function extendNodeEncodings() { - if (original) return; - original = {}; - - if (!iconv.supportsNodeEncodingsExtension) { - console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); - console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); - return; - } - - var nodeNativeEncodings = { - 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, - 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, - }; - - Buffer.isNativeEncoding = function(enc) { - return enc && nodeNativeEncodings[enc.toLowerCase()]; - } - - // -- SlowBuffer ----------------------------------------------------------- - var SlowBuffer = require('buffer').SlowBuffer; - - original.SlowBufferToString = SlowBuffer.prototype.toString; - SlowBuffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferToString.call(this, encoding, start, end); - - // Otherwise, use our decoding method. - if (typeof start == 'undefined') start = 0; - if (typeof end == 'undefined') end = this.length; - return iconv.decode(this.slice(start, end), encoding); - } - - original.SlowBufferWrite = SlowBuffer.prototype.write; - SlowBuffer.prototype.write = function(string, offset, length, encoding) { - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; - } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; - } - - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferWrite.call(this, string, offset, length, encoding); - - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); - - // Otherwise, use our encoding method. - var buf = iconv.encode(string, encoding); - if (buf.length < length) length = buf.length; - buf.copy(this, offset, 0, length); - return length; - } - - // -- Buffer --------------------------------------------------------------- - - original.BufferIsEncoding = Buffer.isEncoding; - Buffer.isEncoding = function(encoding) { - return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); - } - - original.BufferByteLength = Buffer.byteLength; - Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferByteLength.call(this, str, encoding); - - // Slow, I know, but we don't have a better way yet. - return iconv.encode(str, encoding).length; - } - - original.BufferToString = Buffer.prototype.toString; - Buffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferToString.call(this, encoding, start, end); - - // Otherwise, use our decoding method. - if (typeof start == 'undefined') start = 0; - if (typeof end == 'undefined') end = this.length; - return iconv.decode(this.slice(start, end), encoding); - } - - original.BufferWrite = Buffer.prototype.write; - Buffer.prototype.write = function(string, offset, length, encoding) { - var _offset = offset, _length = length, _encoding = encoding; - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; - } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; - } - - encoding = String(encoding || 'utf8').toLowerCase(); - - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferWrite.call(this, string, _offset, _length, _encoding); - - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } - - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); - - // Otherwise, use our encoding method. - var buf = iconv.encode(string, encoding); - if (buf.length < length) length = buf.length; - buf.copy(this, offset, 0, length); - return length; - - // TODO: Set _charsWritten. - } - - - // -- Readable ------------------------------------------------------------- - if (iconv.supportsStreams) { - var Readable = require('stream').Readable; - - original.ReadableSetEncoding = Readable.prototype.setEncoding; - Readable.prototype.setEncoding = function setEncoding(enc, options) { - // Use our own decoder, it has the same interface. - // We cannot use original function as it doesn't handle BOM-s. - this._readableState.decoder = iconv.getDecoder(enc, options); - this._readableState.encoding = enc; - } - - Readable.prototype.collect = iconv._collect; - } - } - - // Remove iconv-lite Node primitive extensions. - iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { - if (!iconv.supportsNodeEncodingsExtension) - return; - if (!original) - throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") - - delete Buffer.isNativeEncoding; - - var SlowBuffer = require('buffer').SlowBuffer; - - SlowBuffer.prototype.toString = original.SlowBufferToString; - SlowBuffer.prototype.write = original.SlowBufferWrite; - - Buffer.isEncoding = original.BufferIsEncoding; - Buffer.byteLength = original.BufferByteLength; - Buffer.prototype.toString = original.BufferToString; - Buffer.prototype.write = original.BufferWrite; - - if (iconv.supportsStreams) { - var Readable = require('stream').Readable; - - Readable.prototype.setEncoding = original.ReadableSetEncoding; - delete Readable.prototype.collect; - } - - original = undefined; - } -} diff --git a/node_modules/iconv-lite/lib/index.d.ts b/node_modules/iconv-lite/lib/index.d.ts deleted file mode 100644 index 0547eb3..0000000 --- a/node_modules/iconv-lite/lib/index.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - * REQUIREMENT: This definition is dependent on the @types/node definition. - * Install with `npm install @types/node --save-dev` - *--------------------------------------------------------------------------------------------*/ - -declare module 'iconv-lite' { - export function decode(buffer: Buffer, encoding: string, options?: Options): string; - - export function encode(content: string, encoding: string, options?: Options): Buffer; - - export function encodingExists(encoding: string): boolean; - - export function decodeStream(encoding: string, options?: Options): NodeJS.ReadWriteStream; - - export function encodeStream(encoding: string, options?: Options): NodeJS.ReadWriteStream; -} - -export interface Options { - stripBOM?: boolean; - addBOM?: boolean; - defaultEncoding?: string; -} diff --git a/node_modules/iconv-lite/lib/index.js b/node_modules/iconv-lite/lib/index.js deleted file mode 100644 index 5391919..0000000 --- a/node_modules/iconv-lite/lib/index.js +++ /dev/null @@ -1,153 +0,0 @@ -"use strict"; - -// Some environments don't have global Buffer (e.g. React Native). -// Solution would be installing npm modules "buffer" and "stream" explicitly. -var Buffer = require("safer-buffer").Buffer; - -var bomHandling = require("./bom-handling"), - iconv = module.exports; - -// All codecs and aliases are kept here, keyed by encoding name/alias. -// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. -iconv.encodings = null; - -// Characters emitted in case of error. -iconv.defaultCharUnicode = '�'; -iconv.defaultCharSingleByte = '?'; - -// Public API. -iconv.encode = function encode(str, encoding, options) { - str = "" + (str || ""); // Ensure string. - - var encoder = iconv.getEncoder(encoding, options); - - var res = encoder.write(str); - var trail = encoder.end(); - - return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; -} - -iconv.decode = function decode(buf, encoding, options) { - if (typeof buf === 'string') { - if (!iconv.skipDecodeWarning) { - console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); - iconv.skipDecodeWarning = true; - } - - buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. - } - - var decoder = iconv.getDecoder(encoding, options); - - var res = decoder.write(buf); - var trail = decoder.end(); - - return trail ? (res + trail) : res; -} - -iconv.encodingExists = function encodingExists(enc) { - try { - iconv.getCodec(enc); - return true; - } catch (e) { - return false; - } -} - -// Legacy aliases to convert functions -iconv.toEncoding = iconv.encode; -iconv.fromEncoding = iconv.decode; - -// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. -iconv._codecDataCache = {}; -iconv.getCodec = function getCodec(encoding) { - if (!iconv.encodings) - iconv.encodings = require("../encodings"); // Lazy load all encoding definitions. - - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - var enc = iconv._canonicalizeEncoding(encoding); - - // Traverse iconv.encodings to find actual codec. - var codecOptions = {}; - while (true) { - var codec = iconv._codecDataCache[enc]; - if (codec) - return codec; - - var codecDef = iconv.encodings[enc]; - - switch (typeof codecDef) { - case "string": // Direct alias to other encoding. - enc = codecDef; - break; - - case "object": // Alias with options. Can be layered. - for (var key in codecDef) - codecOptions[key] = codecDef[key]; - - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - - enc = codecDef.type; - break; - - case "function": // Codec itself. - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - - // The codec function must load all tables and return object with .encoder and .decoder methods. - // It'll be called only once (for each different options object). - codec = new codecDef(codecOptions, iconv); - - iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. - return codec; - - default: - throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); - } - } -} - -iconv._canonicalizeEncoding = function(encoding) { - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); -} - -iconv.getEncoder = function getEncoder(encoding, options) { - var codec = iconv.getCodec(encoding), - encoder = new codec.encoder(options, codec); - - if (codec.bomAware && options && options.addBOM) - encoder = new bomHandling.PrependBOM(encoder, options); - - return encoder; -} - -iconv.getDecoder = function getDecoder(encoding, options) { - var codec = iconv.getCodec(encoding), - decoder = new codec.decoder(options, codec); - - if (codec.bomAware && !(options && options.stripBOM === false)) - decoder = new bomHandling.StripBOM(decoder, options); - - return decoder; -} - - -// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. -var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; -if (nodeVer) { - - // Load streaming support in Node v0.10+ - var nodeVerArr = nodeVer.split(".").map(Number); - if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { - require("./streams")(iconv); - } - - // Load Node primitive extensions. - require("./extend-node")(iconv); -} - -if ("Ā" != "\u0100") { - console.error("iconv-lite warning: javascript files use encoding different from utf-8. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info."); -} diff --git a/node_modules/iconv-lite/lib/streams.js b/node_modules/iconv-lite/lib/streams.js deleted file mode 100644 index 4409552..0000000 --- a/node_modules/iconv-lite/lib/streams.js +++ /dev/null @@ -1,121 +0,0 @@ -"use strict"; - -var Buffer = require("buffer").Buffer, - Transform = require("stream").Transform; - - -// == Exports ================================================================== -module.exports = function(iconv) { - - // Additional Public API. - iconv.encodeStream = function encodeStream(encoding, options) { - return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); - } - - iconv.decodeStream = function decodeStream(encoding, options) { - return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); - } - - iconv.supportsStreams = true; - - - // Not published yet. - iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; - iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; - iconv._collect = IconvLiteDecoderStream.prototype.collect; -}; - - -// == Encoder stream ======================================================= -function IconvLiteEncoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.decodeStrings = false; // We accept only strings, so we don't need to decode them. - Transform.call(this, options); -} - -IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } -}); - -IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { - if (typeof chunk != 'string') - return done(new Error("Iconv encoding stream needs strings as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } -} - -IconvLiteEncoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); - } - catch (e) { - done(e); - } -} - -IconvLiteEncoderStream.prototype.collect = function(cb) { - var chunks = []; - this.on('error', cb); - this.on('data', function(chunk) { chunks.push(chunk); }); - this.on('end', function() { - cb(null, Buffer.concat(chunks)); - }); - return this; -} - - -// == Decoder stream ======================================================= -function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = 'utf8'; // We output strings. - Transform.call(this, options); -} - -IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } -}); - -IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { - if (!Buffer.isBuffer(chunk)) - return done(new Error("Iconv decoding stream needs buffers as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } -} - -IconvLiteDecoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } -} - -IconvLiteDecoderStream.prototype.collect = function(cb) { - var res = ''; - this.on('error', cb); - this.on('data', function(chunk) { res += chunk; }); - this.on('end', function() { - cb(null, res); - }); - return this; -} - diff --git a/node_modules/iconv-lite/package.json b/node_modules/iconv-lite/package.json deleted file mode 100644 index fc4384d..0000000 --- a/node_modules/iconv-lite/package.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "_from": "iconv-lite@0.4.24", - "_id": "iconv-lite@0.4.24", - "_inBundle": false, - "_integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", - "_location": "/iconv-lite", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "iconv-lite@0.4.24", - "name": "iconv-lite", - "escapedName": "iconv-lite", - "rawSpec": "0.4.24", - "saveSpec": null, - "fetchSpec": "0.4.24" - }, - "_requiredBy": [ - "/body-parser", - "/raw-body" - ], - "_resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "_shasum": "2022b4b25fbddc21d2f524974a474aafe733908b", - "_spec": "iconv-lite@0.4.24", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/body-parser", - "author": { - "name": "Alexander Shtuchkin", - "email": "ashtuchkin@gmail.com" - }, - "browser": { - "./lib/extend-node": false, - "./lib/streams": false - }, - "bugs": { - "url": "https://github.com/ashtuchkin/iconv-lite/issues" - }, - "bundleDependencies": false, - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" - }, - "deprecated": false, - "description": "Convert character encodings in pure javascript.", - "devDependencies": { - "async": "*", - "errto": "*", - "iconv": "*", - "istanbul": "*", - "mocha": "^3.1.0", - "request": "~2.87.0", - "semver": "*", - "unorm": "*" - }, - "engines": { - "node": ">=0.10.0" - }, - "homepage": "https://github.com/ashtuchkin/iconv-lite", - "keywords": [ - "iconv", - "convert", - "charset", - "icu" - ], - "license": "MIT", - "main": "./lib/index.js", - "name": "iconv-lite", - "repository": { - "type": "git", - "url": "git://github.com/ashtuchkin/iconv-lite.git" - }, - "scripts": { - "coverage": "istanbul cover _mocha -- --grep .", - "coverage-open": "open coverage/lcov-report/index.html", - "test": "mocha --reporter spec --grep ." - }, - "typings": "./lib/index.d.ts", - "version": "0.4.24" -} diff --git a/node_modules/ieee754/LICENSE b/node_modules/ieee754/LICENSE deleted file mode 100644 index 5aac82c..0000000 --- a/node_modules/ieee754/LICENSE +++ /dev/null @@ -1,11 +0,0 @@ -Copyright 2008 Fair Oaks Labs, Inc. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/ieee754/README.md b/node_modules/ieee754/README.md deleted file mode 100644 index c5291d2..0000000 --- a/node_modules/ieee754/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# ieee754 [![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/ieee754/master.svg -[travis-url]: https://travis-ci.org/feross/ieee754 -[npm-image]: https://img.shields.io/npm/v/ieee754.svg -[npm-url]: https://npmjs.org/package/ieee754 -[downloads-image]: https://img.shields.io/npm/dm/ieee754.svg -[downloads-url]: https://npmjs.org/package/ieee754 -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com - -[![saucelabs][saucelabs-image]][saucelabs-url] - -[saucelabs-image]: https://saucelabs.com/browser-matrix/ieee754.svg -[saucelabs-url]: https://saucelabs.com/u/ieee754 - -### Read/write IEEE754 floating point numbers from/to a Buffer or array-like object. - -## install - -``` -npm install ieee754 -``` - -[Get supported ieee754 with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-ieee754?utm_source=npm-ieee754&utm_medium=referral&utm_campaign=readme) - -## methods - -`var ieee754 = require('ieee754')` - -The `ieee754` object has the following functions: - -``` -ieee754.read = function (buffer, offset, isLE, mLen, nBytes) -ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) -``` - -The arguments mean the following: - -- buffer = the buffer -- offset = offset into the buffer -- value = value to set (only for `write`) -- isLe = is little endian? -- mLen = mantissa length -- nBytes = number of bytes - -## what is ieee754? - -The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation. [Read more](http://en.wikipedia.org/wiki/IEEE_floating_point). - -## license - -BSD 3 Clause. Copyright (c) 2008, Fair Oaks Labs, Inc. diff --git a/node_modules/ieee754/index.js b/node_modules/ieee754/index.js deleted file mode 100644 index e87e6ff..0000000 --- a/node_modules/ieee754/index.js +++ /dev/null @@ -1,84 +0,0 @@ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} diff --git a/node_modules/ieee754/package.json b/node_modules/ieee754/package.json deleted file mode 100644 index 7191dd0..0000000 --- a/node_modules/ieee754/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "ieee754@^1.1.4", - "_id": "ieee754@1.1.13", - "_inBundle": false, - "_integrity": "sha512-4vf7I2LYV/HaWerSo3XmlMkp5eZ83i+/CDluXi/IGTs/O1sejBNhTtnxzmRZfvOUqj7lZjqHkeTvpgSFDlWZTg==", - "_location": "/ieee754", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "ieee754@^1.1.4", - "name": "ieee754", - "escapedName": "ieee754", - "rawSpec": "^1.1.4", - "saveSpec": null, - "fetchSpec": "^1.1.4" - }, - "_requiredBy": [ - "/buffer" - ], - "_resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.13.tgz", - "_shasum": "ec168558e95aa181fd87d37f55c32bbcb6708b84", - "_spec": "ieee754@^1.1.4", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/buffer", - "author": { - "name": "Feross Aboukhadijeh", - "email": "feross@feross.org", - "url": "http://feross.org" - }, - "bugs": { - "url": "https://github.com/feross/ieee754/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Romain Beauxis", - "email": "toots@rastageeks.org" - } - ], - "deprecated": false, - "description": "Read/write IEEE754 floating point numbers from/to a Buffer or array-like object", - "devDependencies": { - "airtap": "0.1.0", - "standard": "*", - "tape": "^4.0.0" - }, - "homepage": "https://github.com/feross/ieee754#readme", - "keywords": [ - "IEEE 754", - "buffer", - "convert", - "floating point", - "ieee754" - ], - "license": "BSD-3-Clause", - "main": "index.js", - "name": "ieee754", - "repository": { - "type": "git", - "url": "git://github.com/feross/ieee754.git" - }, - "scripts": { - "test": "standard && npm run test-node && npm run test-browser", - "test-browser": "airtap -- test/*.js", - "test-browser-local": "airtap --local -- test/*.js", - "test-node": "tape test/*.js" - }, - "version": "1.1.13" -} diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE deleted file mode 100644 index dea3013..0000000 --- a/node_modules/inherits/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index b1c5665..0000000 --- a/node_modules/inherits/README.md +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index f71f2d9..0000000 --- a/node_modules/inherits/inherits.js +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index 86bbb3d..0000000 --- a/node_modules/inherits/inherits_browser.js +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index dc91c0d..0000000 --- a/node_modules/inherits/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "_from": "inherits@~2.0.3", - "_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.3", - "name": "inherits", - "escapedName": "inherits", - "rawSpec": "~2.0.3", - "saveSpec": null, - "fetchSpec": "~2.0.3" - }, - "_requiredBy": [ - "/readable-stream" - ], - "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "_shasum": "0fa2c64f932917c3433a0ded55363aae37416b7c", - "_spec": "inherits@~2.0.3", - "_where": "/Users/kai/Desktop/node-course/dbproject/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/ini/LICENSE b/node_modules/ini/LICENSE deleted file mode 100644 index 19129e3..0000000 --- a/node_modules/ini/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/ini/README.md b/node_modules/ini/README.md deleted file mode 100644 index 33df258..0000000 --- a/node_modules/ini/README.md +++ /dev/null @@ -1,102 +0,0 @@ -An ini format parser and serializer for node. - -Sections are treated as nested objects. Items before the first -heading are saved on the object directly. - -## Usage - -Consider an ini-file `config.ini` that looks like this: - - ; this comment is being ignored - scope = global - - [database] - user = dbuser - password = dbpassword - database = use_this_database - - [paths.default] - datadir = /var/lib/data - array[] = first value - array[] = second value - array[] = third value - -You can read, manipulate and write the ini-file like so: - - var fs = require('fs') - , ini = require('ini') - - var config = ini.parse(fs.readFileSync('./config.ini', 'utf-8')) - - config.scope = 'local' - config.database.database = 'use_another_database' - config.paths.default.tmpdir = '/tmp' - delete config.paths.default.datadir - config.paths.default.array.push('fourth value') - - fs.writeFileSync('./config_modified.ini', ini.stringify(config, { section: 'section' })) - -This will result in a file called `config_modified.ini` being written -to the filesystem with the following content: - - [section] - scope=local - [section.database] - user=dbuser - password=dbpassword - database=use_another_database - [section.paths.default] - tmpdir=/tmp - array[]=first value - array[]=second value - array[]=third value - array[]=fourth value - - -## API - -### decode(inistring) - -Decode the ini-style formatted `inistring` into a nested object. - -### parse(inistring) - -Alias for `decode(inistring)` - -### encode(object, [options]) - -Encode the object `object` into an ini-style formatted string. If the -optional parameter `section` is given, then all top-level properties -of the object are put into this section and the `section`-string is -prepended to all sub-sections, see the usage example above. - -The `options` object may contain the following: - -* `section` A string which will be the first `section` in the encoded - ini data. Defaults to none. -* `whitespace` Boolean to specify whether to put whitespace around the - `=` character. By default, whitespace is omitted, to be friendly to - some persnickety old parsers that don't tolerate it well. But some - find that it's more human-readable and pretty with the whitespace. - -For backwards compatibility reasons, if a `string` options is passed -in, then it is assumed to be the `section` value. - -### stringify(object, [options]) - -Alias for `encode(object, [options])` - -### safe(val) - -Escapes the string `val` such that it is safe to be used as a key or -value in an ini-file. Basically escapes quotes. For example - - ini.safe('"unsafe string"') - -would result in - - "\"unsafe string\"" - -### unsafe(val) - -Unescapes the string `val` diff --git a/node_modules/ini/ini.js b/node_modules/ini/ini.js deleted file mode 100644 index 590195d..0000000 --- a/node_modules/ini/ini.js +++ /dev/null @@ -1,194 +0,0 @@ -exports.parse = exports.decode = decode - -exports.stringify = exports.encode = encode - -exports.safe = safe -exports.unsafe = unsafe - -var eol = typeof process !== 'undefined' && - process.platform === 'win32' ? '\r\n' : '\n' - -function encode (obj, opt) { - var children = [] - var out = '' - - if (typeof opt === 'string') { - opt = { - section: opt, - whitespace: false - } - } else { - opt = opt || {} - opt.whitespace = opt.whitespace === true - } - - var separator = opt.whitespace ? ' = ' : '=' - - Object.keys(obj).forEach(function (k, _, __) { - var val = obj[k] - if (val && Array.isArray(val)) { - val.forEach(function (item) { - out += safe(k + '[]') + separator + safe(item) + '\n' - }) - } else if (val && typeof val === 'object') { - children.push(k) - } else { - out += safe(k) + separator + safe(val) + eol - } - }) - - if (opt.section && out.length) { - out = '[' + safe(opt.section) + ']' + eol + out - } - - children.forEach(function (k, _, __) { - var nk = dotSplit(k).join('\\.') - var section = (opt.section ? opt.section + '.' : '') + nk - var child = encode(obj[k], { - section: section, - whitespace: opt.whitespace - }) - if (out.length && child.length) { - out += eol - } - out += child - }) - - return out -} - -function dotSplit (str) { - return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002') - .replace(/\\\./g, '\u0001') - .split(/\./).map(function (part) { - return part.replace(/\1/g, '\\.') - .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001') - }) -} - -function decode (str) { - var out = {} - var p = out - var section = null - // section |key = value - var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i - var lines = str.split(/[\r\n]+/g) - - lines.forEach(function (line, _, __) { - if (!line || line.match(/^\s*[;#]/)) return - var match = line.match(re) - if (!match) return - if (match[1] !== undefined) { - section = unsafe(match[1]) - p = out[section] = out[section] || {} - return - } - var key = unsafe(match[2]) - var value = match[3] ? unsafe(match[4]) : true - switch (value) { - case 'true': - case 'false': - case 'null': value = JSON.parse(value) - } - - // Convert keys with '[]' suffix to an array - if (key.length > 2 && key.slice(-2) === '[]') { - key = key.substring(0, key.length - 2) - if (!p[key]) { - p[key] = [] - } else if (!Array.isArray(p[key])) { - p[key] = [p[key]] - } - } - - // safeguard against resetting a previously defined - // array by accidentally forgetting the brackets - if (Array.isArray(p[key])) { - p[key].push(value) - } else { - p[key] = value - } - }) - - // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}} - // use a filter to return the keys that have to be deleted. - Object.keys(out).filter(function (k, _, __) { - if (!out[k] || - typeof out[k] !== 'object' || - Array.isArray(out[k])) { - return false - } - // see if the parent section is also an object. - // if so, add it to that, and mark this one for deletion - var parts = dotSplit(k) - var p = out - var l = parts.pop() - var nl = l.replace(/\\\./g, '.') - parts.forEach(function (part, _, __) { - if (!p[part] || typeof p[part] !== 'object') p[part] = {} - p = p[part] - }) - if (p === out && nl === l) { - return false - } - p[nl] = out[k] - return true - }).forEach(function (del, _, __) { - delete out[del] - }) - - return out -} - -function isQuoted (val) { - return (val.charAt(0) === '"' && val.slice(-1) === '"') || - (val.charAt(0) === "'" && val.slice(-1) === "'") -} - -function safe (val) { - return (typeof val !== 'string' || - val.match(/[=\r\n]/) || - val.match(/^\[/) || - (val.length > 1 && - isQuoted(val)) || - val !== val.trim()) - ? JSON.stringify(val) - : val.replace(/;/g, '\\;').replace(/#/g, '\\#') -} - -function unsafe (val, doUnesc) { - val = (val || '').trim() - if (isQuoted(val)) { - // remove the single quotes before calling JSON.parse - if (val.charAt(0) === "'") { - val = val.substr(1, val.length - 2) - } - try { val = JSON.parse(val) } catch (_) {} - } else { - // walk the val to find the first not-escaped ; character - var esc = false - var unesc = '' - for (var i = 0, l = val.length; i < l; i++) { - var c = val.charAt(i) - if (esc) { - if ('\\;#'.indexOf(c) !== -1) { - unesc += c - } else { - unesc += '\\' + c - } - esc = false - } else if (';#'.indexOf(c) !== -1) { - break - } else if (c === '\\') { - esc = true - } else { - unesc += c - } - } - if (esc) { - unesc += '\\' - } - return unesc.trim() - } - return val -} diff --git a/node_modules/ini/package.json b/node_modules/ini/package.json deleted file mode 100644 index 2329d38..0000000 --- a/node_modules/ini/package.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "_from": "ini@~1.3.0", - "_id": "ini@1.3.5", - "_inBundle": false, - "_integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==", - "_location": "/ini", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "ini@~1.3.0", - "name": "ini", - "escapedName": "ini", - "rawSpec": "~1.3.0", - "saveSpec": null, - "fetchSpec": "~1.3.0" - }, - "_requiredBy": [ - "/rc" - ], - "_resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", - "_shasum": "eee25f56db1c9ec6085e0c22778083f596abf927", - "_spec": "ini@~1.3.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/rc", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "bugs": { - "url": "https://github.com/isaacs/ini/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "An ini encoder/decoder for node", - "devDependencies": { - "standard": "^10.0.3", - "tap": "^10.7.3 || 11" - }, - "engines": { - "node": "*" - }, - "files": [ - "ini.js" - ], - "homepage": "https://github.com/isaacs/ini#readme", - "license": "ISC", - "main": "ini.js", - "name": "ini", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/ini.git" - }, - "scripts": { - "postpublish": "git push origin --all; git push origin --tags", - "postversion": "npm publish", - "pretest": "standard ini.js", - "preversion": "npm test", - "test": "tap test/*.js --100 -J" - }, - "version": "1.3.5" -} diff --git a/node_modules/ipaddr.js/LICENSE b/node_modules/ipaddr.js/LICENSE deleted file mode 100644 index f6b37b5..0000000 --- a/node_modules/ipaddr.js/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2011-2017 whitequark - -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/ipaddr.js/README.md b/node_modules/ipaddr.js/README.md deleted file mode 100644 index f57725b..0000000 --- a/node_modules/ipaddr.js/README.md +++ /dev/null @@ -1,233 +0,0 @@ -# ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js) - -ipaddr.js is a small (1.9K minified and gzipped) library for manipulating -IP addresses in JavaScript environments. It runs on both CommonJS runtimes -(e.g. [nodejs]) and in a web browser. - -ipaddr.js allows you to verify and parse string representation of an IP -address, match it against a CIDR range or range list, determine if it falls -into some reserved ranges (examples include loopback and private ranges), -and convert between IPv4 and IPv4-mapped IPv6 addresses. - -[nodejs]: http://nodejs.org - -## Installation - -`npm install ipaddr.js` - -or - -`bower install ipaddr.js` - -## API - -ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, -it is exported from the module: - -```js -var ipaddr = require('ipaddr.js'); -``` - -The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. - -### Global methods - -There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and -`ipaddr.process`. All of them receive a string as a single parameter. - -The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or -IPv6 address, and `false` otherwise. It does not throw any exceptions. - -The `ipaddr.parse` method returns an object representing the IP address, -or throws an `Error` if the passed string is not a valid representation of an -IP address. - -The `ipaddr.process` method works just like the `ipaddr.parse` one, but it -automatically converts IPv4-mapped IPv6 addresses to their IPv4 counterparts -before returning. It is useful when you have a Node.js instance listening -on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its -equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 -connections on your IPv6-only socket, but the remote address will be mangled. -Use `ipaddr.process` method to automatically demangle it. - -### Object representation - -Parsing methods return an object which descends from `ipaddr.IPv6` or -`ipaddr.IPv4`. These objects share some properties, but most of them differ. - -#### Shared properties - -One can determine the type of address by calling `addr.kind()`. It will return -either `"ipv6"` or `"ipv4"`. - -An address can be converted back to its string representation with `addr.toString()`. -Note that this method: - * does not return the original string used to create the object (in fact, there is - no way of getting that string) - * returns a compact representation (when it is applicable) - -A `match(range, bits)` method can be used to check if the address falls into a -certain CIDR range. -Note that an address can be (obviously) matched only against an address of the same type. - -For example: - -```js -var addr = ipaddr.parse("2001:db8:1234::1"); -var range = ipaddr.parse("2001:db8::"); - -addr.match(range, 32); // => true -``` - -Alternatively, `match` can also be called as `match([range, bits])`. In this way, -it can be used together with the `parseCIDR(string)` method, which parses an IP -address together with a CIDR range. - -For example: - -```js -var addr = ipaddr.parse("2001:db8:1234::1"); - -addr.match(ipaddr.parseCIDR("2001:db8::/32")); // => true -``` - -A `range()` method returns one of predefined names for several special ranges defined -by IP protocols. The exact names (and their respective CIDR ranges) can be looked up -in the source: [IPv6 ranges] and [IPv4 ranges]. Some common ones include `"unicast"` -(the default one) and `"reserved"`. - -You can match against your own range list by using -`ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with a mix of IPv6 or IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: - -```js -var rangeList = { - documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], - tunnelProviders: [ - [ ipaddr.parse('2001:470::'), 32 ], // he.net - [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 - ] -}; -ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "tunnelProviders" -``` - -The addresses can be converted to their byte representation with `toByteArray()`. -(Actually, JavaScript mostly does not know about byte buffers. They are emulated with -arrays of numbers, each in range of 0..255.) - -```js -var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com -bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, , 0x00, 0x68 ] -``` - -The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them -have the same interface for both protocols, and are similar to global methods. - -`ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address -for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. - -`ipaddr.IPvX.isValid(string)` uses the same format for parsing as the POSIX `inet_ntoa` function, which accepts unusual formats like `0xc0.168.1.1` or `0x10000000`. The function `ipaddr.IPv4.isValidFourPartDecimal(string)` validates the IPv4 address and also ensures that it is written in four-part decimal format. - -[IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186 -[IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71 - -#### IPv6 properties - -Sometimes you will want to convert IPv6 not to a compact string representation (with -the `::` substitution); the `toNormalizedString()` method will return an address where -all zeroes are explicit. - -For example: - -```js -var addr = ipaddr.parse("2001:0db8::0001"); -addr.toString(); // => "2001:db8::1" -addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1" -``` - -The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped -one, and `toIPv4Address()` will return an IPv4 object address. - -To access the underlying binary representation of the address, use `addr.parts`. - -```js -var addr = ipaddr.parse("2001:db8:10::1234:DEAD"); -addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] -``` - -A IPv6 zone index can be accessed via `addr.zoneId`: - -```js -var addr = ipaddr.parse("2001:db8::%eth0"); -addr.zoneId // => 'eth0' -``` - -#### IPv4 properties - -`toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. - -To access the underlying representation of the address, use `addr.octets`. - -```js -var addr = ipaddr.parse("192.168.1.1"); -addr.octets // => [192, 168, 1, 1] -``` - -`prefixLengthFromSubnetMask()` will return a CIDR prefix length for a valid IPv4 netmask or -null if the netmask is not valid. - -```js -ipaddr.IPv4.parse('255.255.255.240').prefixLengthFromSubnetMask() == 28 -ipaddr.IPv4.parse('255.192.164.0').prefixLengthFromSubnetMask() == null -``` - -`subnetMaskFromPrefixLength()` will return an IPv4 netmask for a valid CIDR prefix length. - -```js -ipaddr.IPv4.subnetMaskFromPrefixLength(24) == "255.255.255.0" -ipaddr.IPv4.subnetMaskFromPrefixLength(29) == "255.255.255.248" -``` - -`broadcastAddressFromCIDR()` will return the broadcast address for a given IPv4 interface and netmask in CIDR notation. -```js -ipaddr.IPv4.broadcastAddressFromCIDR("172.0.0.1/24") == "172.0.0.255" -``` -`networkAddressFromCIDR()` will return the network address for a given IPv4 interface and netmask in CIDR notation. -```js -ipaddr.IPv4.networkAddressFromCIDR("172.0.0.1/24") == "172.0.0.0" -``` - -#### Conversion - -IPv4 and IPv6 can be converted bidirectionally to and from network byte order (MSB) byte arrays. - -The `fromByteArray()` method will take an array and create an appropriate IPv4 or IPv6 object -if the input satisfies the requirements. For IPv4 it has to be an array of four 8-bit values, -while for IPv6 it has to be an array of sixteen 8-bit values. - -For example: -```js -var addr = ipaddr.fromByteArray([0x7f, 0, 0, 1]); -addr.toString(); // => "127.0.0.1" -``` - -or - -```js -var addr = ipaddr.fromByteArray([0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) -addr.toString(); // => "2001:db8::1" -``` - -Both objects also offer a `toByteArray()` method, which returns an array in network byte order (MSB). - -For example: -```js -var addr = ipaddr.parse("127.0.0.1"); -addr.toByteArray(); // => [0x7f, 0, 0, 1] -``` - -or - -```js -var addr = ipaddr.parse("2001:db8::1"); -addr.toByteArray(); // => [0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] -``` diff --git a/node_modules/ipaddr.js/ipaddr.min.js b/node_modules/ipaddr.js/ipaddr.min.js deleted file mode 100644 index b54a7cc..0000000 --- a/node_modules/ipaddr.js/ipaddr.min.js +++ /dev/null @@ -1 +0,0 @@ -(function(){var r,t,n,e,i,o,a,s;t={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:s.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;e>0;){if((o=n-e)<0&&(o=0),r[i]>>o!=t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;null==n&&(n="unicast");for(o in t)for(!(a=t[o])[0]||a[0]instanceof Array||(a=[a]),e=0,i=a.length;e=0;t=n+=-1){if(!((e=this.octets[t])in a))return null;if(o=a[e],i&&0!==o)return null;8!==o&&(i=!0),r+=o}return 32-r},r}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(a=[],r=0,e=(o=t.slice(1,6)).length;r4294967295||a<0)throw new Error("ipaddr: address outside defined range");return function(){var r,t;for(t=[],o=r=0;r<=24;o=r+=8)t.push(a>>o&255);return t}().reverse()}return null},t.IPv6=function(){function r(r,t){var n,e,i,o,a,s;if(16===r.length)for(this.parts=[],n=e=0;e<=14;n=e+=2)this.parts.push(r[n]<<8|r[n+1]);else{if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=r}for(i=0,o=(s=this.parts).length;it&&(r=n.index,t=n[0].length);return t<0?i:i.substring(0,r)+"::"+i.substring(r+t)},r.prototype.toByteArray=function(){var r,t,n,e,i;for(r=[],t=0,n=(i=this.parts).length;t>8),r.push(255&e);return r},r.prototype.toNormalizedString=function(){var r,t,n;return r=function(){var r,n,e,i;for(i=[],r=0,n=(e=this.parts).length;r>8,255&r,n>>8,255&n])},r.prototype.prefixLengthFromSubnetMask=function(){var r,t,n,e,i,o,a;for(a={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r=0,i=!1,t=n=7;n>=0;t=n+=-1){if(!((e=this.parts[t])in a))return null;if(o=a[e],i&&0!==o)return null;16!==o&&(i=!0),r+=o}return 128-r},r}(),i="(?:[0-9a-f]+::?)+",o={zoneIndex:new RegExp("%[0-9a-z]{1,}","i"),native:new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?(%[0-9a-z]{1,})?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"(%[0-9a-z]{1,})?$","i")},r=function(r,t){var n,e,i,a,s,p;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for((p=(r.match(o.zoneIndex)||[])[0])&&(p=p.substring(1),r=r.replace(/%.+$/,"")),n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(s=t-n,a=":";s--;)a+="0:";return":"===(r=r.replace("::",a))[0]&&(r=r.slice(1)),":"===r[r.length-1]&&(r=r.slice(0,-1)),t=function(){var t,n,e,o;for(o=[],t=0,n=(e=r.split(":")).length;t=0&&t<=32)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv4.subnetMaskFromPrefixLength=function(r){var t,n,e;if((r=parseInt(r))<0||r>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(e=[0,0,0,0],n=0,t=Math.floor(r/8);n=0&&t<=128)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},t.isValid=function(r){return t.IPv6.isValid(r)||t.IPv4.isValid(r)},t.parse=function(r){if(t.IPv6.isValid(r))return t.IPv6.parse(r);if(t.IPv4.isValid(r))return t.IPv4.parse(r);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},t.parseCIDR=function(r){try{return t.IPv6.parseCIDR(r)}catch(n){n;try{return t.IPv4.parseCIDR(r)}catch(r){throw r,new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},t.fromByteArray=function(r){var n;if(4===(n=r.length))return new t.IPv4(r);if(16===n)return new t.IPv6(r);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},t.process=function(r){var t;return t=this.parse(r),"ipv6"===t.kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(this); \ No newline at end of file diff --git a/node_modules/ipaddr.js/lib/ipaddr.js b/node_modules/ipaddr.js/lib/ipaddr.js deleted file mode 100644 index 18bd93b..0000000 --- a/node_modules/ipaddr.js/lib/ipaddr.js +++ /dev/null @@ -1,673 +0,0 @@ -(function() { - var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; - - ipaddr = {}; - - root = this; - - if ((typeof module !== "undefined" && module !== null) && module.exports) { - module.exports = ipaddr; - } else { - root['ipaddr'] = ipaddr; - } - - matchCIDR = function(first, second, partSize, cidrBits) { - var part, shift; - if (first.length !== second.length) { - throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); - } - part = 0; - while (cidrBits > 0) { - shift = partSize - cidrBits; - if (shift < 0) { - shift = 0; - } - if (first[part] >> shift !== second[part] >> shift) { - return false; - } - cidrBits -= partSize; - part += 1; - } - return true; - }; - - ipaddr.subnetMatch = function(address, rangeList, defaultName) { - var k, len, rangeName, rangeSubnets, subnet; - if (defaultName == null) { - defaultName = 'unicast'; - } - for (rangeName in rangeList) { - rangeSubnets = rangeList[rangeName]; - if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { - rangeSubnets = [rangeSubnets]; - } - for (k = 0, len = rangeSubnets.length; k < len; k++) { - subnet = rangeSubnets[k]; - if (address.kind() === subnet[0].kind()) { - if (address.match.apply(address, subnet)) { - return rangeName; - } - } - } - } - return defaultName; - }; - - ipaddr.IPv4 = (function() { - function IPv4(octets) { - var k, len, octet; - if (octets.length !== 4) { - throw new Error("ipaddr: ipv4 octet count should be 4"); - } - for (k = 0, len = octets.length; k < len; k++) { - octet = octets[k]; - if (!((0 <= octet && octet <= 255))) { - throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); - } - } - this.octets = octets; - } - - IPv4.prototype.kind = function() { - return 'ipv4'; - }; - - IPv4.prototype.toString = function() { - return this.octets.join("."); - }; - - IPv4.prototype.toNormalizedString = function() { - return this.toString(); - }; - - IPv4.prototype.toByteArray = function() { - return this.octets.slice(0); - }; - - IPv4.prototype.match = function(other, cidrRange) { - var ref; - if (cidrRange === void 0) { - ref = other, other = ref[0], cidrRange = ref[1]; - } - if (other.kind() !== 'ipv4') { - throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); - } - return matchCIDR(this.octets, other.octets, 8, cidrRange); - }; - - IPv4.prototype.SpecialRanges = { - unspecified: [[new IPv4([0, 0, 0, 0]), 8]], - broadcast: [[new IPv4([255, 255, 255, 255]), 32]], - multicast: [[new IPv4([224, 0, 0, 0]), 4]], - linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], - loopback: [[new IPv4([127, 0, 0, 0]), 8]], - carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], - "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], - reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] - }; - - IPv4.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; - - IPv4.prototype.toIPv4MappedAddress = function() { - return ipaddr.IPv6.parse("::ffff:" + (this.toString())); - }; - - IPv4.prototype.prefixLengthFromSubnetMask = function() { - var cidr, i, k, octet, stop, zeros, zerotable; - zerotable = { - 0: 8, - 128: 7, - 192: 6, - 224: 5, - 240: 4, - 248: 3, - 252: 2, - 254: 1, - 255: 0 - }; - cidr = 0; - stop = false; - for (i = k = 3; k >= 0; i = k += -1) { - octet = this.octets[i]; - if (octet in zerotable) { - zeros = zerotable[octet]; - if (stop && zeros !== 0) { - return null; - } - if (zeros !== 8) { - stop = true; - } - cidr += zeros; - } else { - return null; - } - } - return 32 - cidr; - }; - - return IPv4; - - })(); - - ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; - - ipv4Regexes = { - fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), - longValue: new RegExp("^" + ipv4Part + "$", 'i') - }; - - ipaddr.IPv4.parser = function(string) { - var match, parseIntAuto, part, shift, value; - parseIntAuto = function(string) { - if (string[0] === "0" && string[1] !== "x") { - return parseInt(string, 8); - } else { - return parseInt(string); - } - }; - if (match = string.match(ipv4Regexes.fourOctet)) { - return (function() { - var k, len, ref, results; - ref = match.slice(1, 6); - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(parseIntAuto(part)); - } - return results; - })(); - } else if (match = string.match(ipv4Regexes.longValue)) { - value = parseIntAuto(match[1]); - if (value > 0xffffffff || value < 0) { - throw new Error("ipaddr: address outside defined range"); - } - return ((function() { - var k, results; - results = []; - for (shift = k = 0; k <= 24; shift = k += 8) { - results.push((value >> shift) & 0xff); - } - return results; - })()).reverse(); - } else { - return null; - } - }; - - ipaddr.IPv6 = (function() { - function IPv6(parts, zoneId) { - var i, k, l, len, part, ref; - if (parts.length === 16) { - this.parts = []; - for (i = k = 0; k <= 14; i = k += 2) { - this.parts.push((parts[i] << 8) | parts[i + 1]); - } - } else if (parts.length === 8) { - this.parts = parts; - } else { - throw new Error("ipaddr: ipv6 part count should be 8 or 16"); - } - ref = this.parts; - for (l = 0, len = ref.length; l < len; l++) { - part = ref[l]; - if (!((0 <= part && part <= 0xffff))) { - throw new Error("ipaddr: ipv6 part should fit in 16 bits"); - } - } - if (zoneId) { - this.zoneId = zoneId; - } - } - - IPv6.prototype.kind = function() { - return 'ipv6'; - }; - - IPv6.prototype.toString = function() { - return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); - }; - - IPv6.prototype.toRFC5952String = function() { - var bestMatchIndex, bestMatchLength, match, regex, string; - regex = /((^|:)(0(:|$)){2,})/g; - string = this.toNormalizedString(); - bestMatchIndex = 0; - bestMatchLength = -1; - while ((match = regex.exec(string))) { - if (match[0].length > bestMatchLength) { - bestMatchIndex = match.index; - bestMatchLength = match[0].length; - } - } - if (bestMatchLength < 0) { - return string; - } - return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength); - }; - - IPv6.prototype.toByteArray = function() { - var bytes, k, len, part, ref; - bytes = []; - ref = this.parts; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - bytes.push(part >> 8); - bytes.push(part & 0xff); - } - return bytes; - }; - - IPv6.prototype.toNormalizedString = function() { - var addr, part, suffix; - addr = ((function() { - var k, len, ref, results; - ref = this.parts; - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(part.toString(16)); - } - return results; - }).call(this)).join(":"); - suffix = ''; - if (this.zoneId) { - suffix = '%' + this.zoneId; - } - return addr + suffix; - }; - - IPv6.prototype.toFixedLengthString = function() { - var addr, part, suffix; - addr = ((function() { - var k, len, ref, results; - ref = this.parts; - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(part.toString(16).padStart(4, '0')); - } - return results; - }).call(this)).join(":"); - suffix = ''; - if (this.zoneId) { - suffix = '%' + this.zoneId; - } - return addr + suffix; - }; - - IPv6.prototype.match = function(other, cidrRange) { - var ref; - if (cidrRange === void 0) { - ref = other, other = ref[0], cidrRange = ref[1]; - } - if (other.kind() !== 'ipv6') { - throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); - } - return matchCIDR(this.parts, other.parts, 16, cidrRange); - }; - - IPv6.prototype.SpecialRanges = { - unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], - linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], - multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], - loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], - uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], - ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], - rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], - rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], - '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], - teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], - reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] - }; - - IPv6.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; - - IPv6.prototype.isIPv4MappedAddress = function() { - return this.range() === 'ipv4Mapped'; - }; - - IPv6.prototype.toIPv4Address = function() { - var high, low, ref; - if (!this.isIPv4MappedAddress()) { - throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); - } - ref = this.parts.slice(-2), high = ref[0], low = ref[1]; - return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); - }; - - IPv6.prototype.prefixLengthFromSubnetMask = function() { - var cidr, i, k, part, stop, zeros, zerotable; - zerotable = { - 0: 16, - 32768: 15, - 49152: 14, - 57344: 13, - 61440: 12, - 63488: 11, - 64512: 10, - 65024: 9, - 65280: 8, - 65408: 7, - 65472: 6, - 65504: 5, - 65520: 4, - 65528: 3, - 65532: 2, - 65534: 1, - 65535: 0 - }; - cidr = 0; - stop = false; - for (i = k = 7; k >= 0; i = k += -1) { - part = this.parts[i]; - if (part in zerotable) { - zeros = zerotable[part]; - if (stop && zeros !== 0) { - return null; - } - if (zeros !== 16) { - stop = true; - } - cidr += zeros; - } else { - return null; - } - } - return 128 - cidr; - }; - - return IPv6; - - })(); - - ipv6Part = "(?:[0-9a-f]+::?)+"; - - zoneIndex = "%[0-9a-z]{1,}"; - - ipv6Regexes = { - zoneIndex: new RegExp(zoneIndex, 'i'), - "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'), - transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i') - }; - - expandIPv6 = function(string, parts) { - var colonCount, lastColon, part, replacement, replacementCount, zoneId; - if (string.indexOf('::') !== string.lastIndexOf('::')) { - return null; - } - zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; - if (zoneId) { - zoneId = zoneId.substring(1); - string = string.replace(/%.+$/, ''); - } - colonCount = 0; - lastColon = -1; - while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { - colonCount++; - } - if (string.substr(0, 2) === '::') { - colonCount--; - } - if (string.substr(-2, 2) === '::') { - colonCount--; - } - if (colonCount > parts) { - return null; - } - replacementCount = parts - colonCount; - replacement = ':'; - while (replacementCount--) { - replacement += '0:'; - } - string = string.replace('::', replacement); - if (string[0] === ':') { - string = string.slice(1); - } - if (string[string.length - 1] === ':') { - string = string.slice(0, -1); - } - parts = (function() { - var k, len, ref, results; - ref = string.split(":"); - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(parseInt(part, 16)); - } - return results; - })(); - return { - parts: parts, - zoneId: zoneId - }; - }; - - ipaddr.IPv6.parser = function(string) { - var addr, k, len, match, octet, octets, zoneId; - if (ipv6Regexes['native'].test(string)) { - return expandIPv6(string, 8); - } else if (match = string.match(ipv6Regexes['transitional'])) { - zoneId = match[6] || ''; - addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); - if (addr.parts) { - octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; - for (k = 0, len = octets.length; k < len; k++) { - octet = octets[k]; - if (!((0 <= octet && octet <= 255))) { - return null; - } - } - addr.parts.push(octets[0] << 8 | octets[1]); - addr.parts.push(octets[2] << 8 | octets[3]); - return { - parts: addr.parts, - zoneId: addr.zoneId - }; - } - } - return null; - }; - - ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { - return this.parser(string) !== null; - }; - - ipaddr.IPv4.isValid = function(string) { - var e; - try { - new this(this.parser(string)); - return true; - } catch (error1) { - e = error1; - return false; - } - }; - - ipaddr.IPv4.isValidFourPartDecimal = function(string) { - if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { - return true; - } else { - return false; - } - }; - - ipaddr.IPv6.isValid = function(string) { - var addr, e; - if (typeof string === "string" && string.indexOf(":") === -1) { - return false; - } - try { - addr = this.parser(string); - new this(addr.parts, addr.zoneId); - return true; - } catch (error1) { - e = error1; - return false; - } - }; - - ipaddr.IPv4.parse = function(string) { - var parts; - parts = this.parser(string); - if (parts === null) { - throw new Error("ipaddr: string is not formatted like ip address"); - } - return new this(parts); - }; - - ipaddr.IPv6.parse = function(string) { - var addr; - addr = this.parser(string); - if (addr.parts === null) { - throw new Error("ipaddr: string is not formatted like ip address"); - } - return new this(addr.parts, addr.zoneId); - }; - - ipaddr.IPv4.parseCIDR = function(string) { - var maskLength, match, parsed; - if (match = string.match(/^(.+)\/(\d+)$/)) { - maskLength = parseInt(match[2]); - if (maskLength >= 0 && maskLength <= 32) { - parsed = [this.parse(match[1]), maskLength]; - Object.defineProperty(parsed, 'toString', { - value: function() { - return this.join('/'); - } - }); - return parsed; - } - } - throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); - }; - - ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { - var filledOctetCount, j, octets; - prefix = parseInt(prefix); - if (prefix < 0 || prefix > 32) { - throw new Error('ipaddr: invalid IPv4 prefix length'); - } - octets = [0, 0, 0, 0]; - j = 0; - filledOctetCount = Math.floor(prefix / 8); - while (j < filledOctetCount) { - octets[j] = 255; - j++; - } - if (filledOctetCount < 4) { - octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); - } - return new this(octets); - }; - - ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { - var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; - try { - cidr = this.parseCIDR(string); - ipInterfaceOctets = cidr[0].toByteArray(); - subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); - octets = []; - i = 0; - while (i < 4) { - octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); - i++; - } - return new this(octets); - } catch (error1) { - error = error1; - throw new Error('ipaddr: the address does not have IPv4 CIDR format'); - } - }; - - ipaddr.IPv4.networkAddressFromCIDR = function(string) { - var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; - try { - cidr = this.parseCIDR(string); - ipInterfaceOctets = cidr[0].toByteArray(); - subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); - octets = []; - i = 0; - while (i < 4) { - octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); - i++; - } - return new this(octets); - } catch (error1) { - error = error1; - throw new Error('ipaddr: the address does not have IPv4 CIDR format'); - } - }; - - ipaddr.IPv6.parseCIDR = function(string) { - var maskLength, match, parsed; - if (match = string.match(/^(.+)\/(\d+)$/)) { - maskLength = parseInt(match[2]); - if (maskLength >= 0 && maskLength <= 128) { - parsed = [this.parse(match[1]), maskLength]; - Object.defineProperty(parsed, 'toString', { - value: function() { - return this.join('/'); - } - }); - return parsed; - } - } - throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); - }; - - ipaddr.isValid = function(string) { - return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); - }; - - ipaddr.parse = function(string) { - if (ipaddr.IPv6.isValid(string)) { - return ipaddr.IPv6.parse(string); - } else if (ipaddr.IPv4.isValid(string)) { - return ipaddr.IPv4.parse(string); - } else { - throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); - } - }; - - ipaddr.parseCIDR = function(string) { - var e; - try { - return ipaddr.IPv6.parseCIDR(string); - } catch (error1) { - e = error1; - try { - return ipaddr.IPv4.parseCIDR(string); - } catch (error1) { - e = error1; - throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); - } - } - }; - - ipaddr.fromByteArray = function(bytes) { - var length; - length = bytes.length; - if (length === 4) { - return new ipaddr.IPv4(bytes); - } else if (length === 16) { - return new ipaddr.IPv6(bytes); - } else { - throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); - } - }; - - ipaddr.process = function(string) { - var addr; - addr = this.parse(string); - if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { - return addr.toIPv4Address(); - } else { - return addr; - } - }; - -}).call(this); diff --git a/node_modules/ipaddr.js/lib/ipaddr.js.d.ts b/node_modules/ipaddr.js/lib/ipaddr.js.d.ts deleted file mode 100644 index 52174b6..0000000 --- a/node_modules/ipaddr.js/lib/ipaddr.js.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -declare module "ipaddr.js" { - type IPv4Range = 'unicast' | 'unspecified' | 'broadcast' | 'multicast' | 'linkLocal' | 'loopback' | 'carrierGradeNat' | 'private' | 'reserved'; - type IPv6Range = 'unicast' | 'unspecified' | 'linkLocal' | 'multicast' | 'loopback' | 'uniqueLocal' | 'ipv4Mapped' | 'rfc6145' | 'rfc6052' | '6to4' | 'teredo' | 'reserved'; - - interface RangeList { - [name: string]: [T, number] | [T, number][]; - } - - // Common methods/properties for IPv4 and IPv6 classes. - class IP { - prefixLengthFromSubnetMask(): number | null; - toByteArray(): number[]; - toNormalizedString(): string; - toString(): string; - } - - namespace Address { - export function isValid(addr: string): boolean; - export function fromByteArray(bytes: number[]): IPv4 | IPv6; - export function parse(addr: string): IPv4 | IPv6; - export function parseCIDR(mask: string): [IPv4 | IPv6, number]; - export function process(addr: string): IPv4 | IPv6; - export function subnetMatch(addr: IPv4, rangeList: RangeList, defaultName?: string): string; - export function subnetMatch(addr: IPv6, rangeList: RangeList, defaultName?: string): string; - - export class IPv4 extends IP { - static broadcastAddressFromCIDR(addr: string): IPv4; - static isIPv4(addr: string): boolean; - static isValidFourPartDecimal(addr: string): boolean; - static isValid(addr: string): boolean; - static networkAddressFromCIDR(addr: string): IPv4; - static parse(addr: string): IPv4; - static parseCIDR(addr: string): [IPv4, number]; - static subnetMaskFromPrefixLength(prefix: number): IPv4; - constructor(octets: number[]); - octets: number[] - - kind(): 'ipv4'; - match(addr: IPv4, bits: number): boolean; - match(mask: [IPv4, number]): boolean; - range(): IPv4Range; - subnetMatch(rangeList: RangeList, defaultName?: string): string; - toIPv4MappedAddress(): IPv6; - } - - export class IPv6 extends IP { - static broadcastAddressFromCIDR(addr: string): IPv6; - static isIPv6(addr: string): boolean; - static isValid(addr: string): boolean; - static parse(addr: string): IPv6; - static parseCIDR(addr: string): [IPv6, number]; - static subnetMaskFromPrefixLength(prefix: number): IPv6; - constructor(parts: number[]); - parts: number[] - zoneId?: string - - isIPv4MappedAddress(): boolean; - kind(): 'ipv6'; - match(addr: IPv6, bits: number): boolean; - match(mask: [IPv6, number]): boolean; - range(): IPv6Range; - subnetMatch(rangeList: RangeList, defaultName?: string): string; - toIPv4Address(): IPv4; - } - } - - export = Address; -} diff --git a/node_modules/ipaddr.js/package.json b/node_modules/ipaddr.js/package.json deleted file mode 100644 index a9916c9..0000000 --- a/node_modules/ipaddr.js/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "_from": "ipaddr.js@1.9.1", - "_id": "ipaddr.js@1.9.1", - "_inBundle": false, - "_integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "_location": "/ipaddr.js", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "ipaddr.js@1.9.1", - "name": "ipaddr.js", - "escapedName": "ipaddr.js", - "rawSpec": "1.9.1", - "saveSpec": null, - "fetchSpec": "1.9.1" - }, - "_requiredBy": [ - "/proxy-addr" - ], - "_resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "_shasum": "bff38543eeb8984825079ff3a2a8e6cbd46781b3", - "_spec": "ipaddr.js@1.9.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/proxy-addr", - "author": { - "name": "whitequark", - "email": "whitequark@whitequark.org" - }, - "bugs": { - "url": "https://github.com/whitequark/ipaddr.js/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", - "devDependencies": { - "coffee-script": "~1.12.6", - "nodeunit": "^0.11.3", - "uglify-js": "~3.0.19" - }, - "directories": { - "lib": "./lib" - }, - "engines": { - "node": ">= 0.10" - }, - "files": [ - "lib/", - "LICENSE", - "ipaddr.min.js" - ], - "homepage": "https://github.com/whitequark/ipaddr.js#readme", - "keywords": [ - "ip", - "ipv4", - "ipv6" - ], - "license": "MIT", - "main": "./lib/ipaddr.js", - "name": "ipaddr.js", - "repository": { - "type": "git", - "url": "git://github.com/whitequark/ipaddr.js.git" - }, - "scripts": { - "test": "cake build test" - }, - "types": "./lib/ipaddr.js.d.ts", - "version": "1.9.1" -} diff --git a/node_modules/is-arguments/.editorconfig b/node_modules/is-arguments/.editorconfig deleted file mode 100644 index bc228f8..0000000 --- a/node_modules/is-arguments/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -max_line_length = 150 - -[CHANGELOG.md] -indent_style = space -indent_size = 2 - -[*.json] -max_line_length = off - -[Makefile] -max_line_length = off diff --git a/node_modules/is-arguments/.eslintrc b/node_modules/is-arguments/.eslintrc deleted file mode 100644 index 6d42c6e..0000000 --- a/node_modules/is-arguments/.eslintrc +++ /dev/null @@ -1,10 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "id-length": [2, { "min": 1, "max": 25 }], - "operator-linebreak": [2, "after"] - } -} diff --git a/node_modules/is-arguments/.jscs.json b/node_modules/is-arguments/.jscs.json deleted file mode 100644 index b4d9b8b..0000000 --- a/node_modules/is-arguments/.jscs.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 1 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": "asc-insensitive", - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/node_modules/is-arguments/.travis.yml b/node_modules/is-arguments/.travis.yml deleted file mode 100644 index db51785..0000000 --- a/node_modules/is-arguments/.travis.yml +++ /dev/null @@ -1,248 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "11.1" - - "10.13" - - "9.11" - - "8.12" - - "7.10" - - "6.14" - - "5.12" - - "4.9" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "4" - env: COVERAGE=true - - node_js: "11.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true - - env: COVERAGE=true diff --git a/node_modules/is-arguments/CHANGELOG.md b/node_modules/is-arguments/CHANGELOG.md deleted file mode 100644 index 8e2a361..0000000 --- a/node_modules/is-arguments/CHANGELOG.md +++ /dev/null @@ -1,32 +0,0 @@ -1.0.4 / 2018-11-05 -================== - * [Fix] Fix errors about `in` operator (#22) - -1.0.3 / 2018-11-02 -================== - * [Fix] add awareness of Symbol.toStringTag (#20) - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `jscs`, `nsp` - * [Tests] up to `node` `v11.1`, `v10.13`, `v9.11`, `v8.12`, `v7.10`, `v6.14`, `v5.11`, `v4.8`; use `nvm install-latest-npm`; pin included builds to LTS. - -1.0.2 / 2015-09-21 -================== - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. - * [Enhancement] In modern engines, only export the "is standard arguments" check. - * [Fix] `toString` as a variable name breaks in some older browsers. - * [Dev Deps] update `covert`, `jscs`, `eslint` - * [Tests] up to `io.js` `v3.3`, `node` `v4.1` - -1.0.1 / 2015-04-29 -================== - * [Docs] clean up README; add badges - * [Dev Deps] update `tape`, `covert` - * [Tests] add `npm run lint` - -1.0.0 / 2014-01-14 -================== - * Bump to v1.0 - -0.1.0 / 2014-01-14 -================== - * Initial release. - diff --git a/node_modules/is-arguments/LICENSE b/node_modules/is-arguments/LICENSE deleted file mode 100644 index 47b7b50..0000000 --- a/node_modules/is-arguments/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Jordan Harband - -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/is-arguments/README.md b/node_modules/is-arguments/README.md deleted file mode 100644 index b5353bc..0000000 --- a/node_modules/is-arguments/README.md +++ /dev/null @@ -1,49 +0,0 @@ -#is-arguments [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -Is this an arguments object? It's a harder question than you think. - -## Example - -```js -var isArguments = require('is-arguments'); -var assert = require('assert'); - -assert.equal(isArguments({}), false); -assert.equal(isArguments([]), false); -(function () { - assert.equal(isArguments(arguments), true); -}()) -``` - -## Caveats -If you have modified an actual `arguments` object by giving it a `Symbol.toStringTag` property, then this package will return `false`. - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-arguments -[2]: http://versionbadg.es/ljharb/is-arguments.svg -[3]: https://travis-ci.org/ljharb/is-arguments.svg -[4]: https://travis-ci.org/ljharb/is-arguments -[5]: https://david-dm.org/ljharb/is-arguments.svg -[6]: https://david-dm.org/ljharb/is-arguments -[7]: https://david-dm.org/ljharb/is-arguments/dev-status.svg -[8]: https://david-dm.org/ljharb/is-arguments#info=devDependencies -[9]: https://ci.testling.com/ljharb/is-arguments.png -[10]: https://ci.testling.com/ljharb/is-arguments -[11]: https://nodei.co/npm/is-arguments.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-arguments.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-arguments.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-arguments - diff --git a/node_modules/is-arguments/index.js b/node_modules/is-arguments/index.js deleted file mode 100644 index 84cc200..0000000 --- a/node_modules/is-arguments/index.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var toStr = Object.prototype.toString; - -var isStandardArguments = function isArguments(value) { - if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { - return false; - } - return toStr.call(value) === '[object Arguments]'; -}; - -var isLegacyArguments = function isArguments(value) { - if (isStandardArguments(value)) { - return true; - } - return value !== null && - typeof value === 'object' && - typeof value.length === 'number' && - value.length >= 0 && - toStr.call(value) !== '[object Array]' && - toStr.call(value.callee) === '[object Function]'; -}; - -var supportsStandardArguments = (function () { - return isStandardArguments(arguments); -}()); - -isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests - -module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; diff --git a/node_modules/is-arguments/package.json b/node_modules/is-arguments/package.json deleted file mode 100644 index 5995660..0000000 --- a/node_modules/is-arguments/package.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "_from": "is-arguments@^1.0.4", - "_id": "is-arguments@1.0.4", - "_inBundle": false, - "_integrity": "sha512-xPh0Rmt8NE65sNzvyUmWgI1tz3mKq74lGA0mL8LYZcoIzKOzDh6HmrYm3d18k60nHerC8A9Km8kYu87zfSFnLA==", - "_location": "/is-arguments", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-arguments@^1.0.4", - "name": "is-arguments", - "escapedName": "is-arguments", - "rawSpec": "^1.0.4", - "saveSpec": null, - "fetchSpec": "^1.0.4" - }, - "_requiredBy": [ - "/util" - ], - "_resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.0.4.tgz", - "_shasum": "3faf966c7cba0ff437fb31f6250082fcf0448cf3", - "_spec": "is-arguments@^1.0.4", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/util", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - }, - "bugs": { - "url": "https://github.com/ljharb/is-arguments/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "Is this an arguments object? It's a harder question than you think.", - "devDependencies": { - "@ljharb/eslint-config": "^13.0.0", - "covert": "^1.1.0", - "eslint": "^5.8.0", - "jscs": "^3.0.7", - "nsp": "^3.2.1", - "tape": "^4.9.1" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/is-arguments", - "keywords": [ - "arguments", - "js", - "javascript", - "is-arguments", - "is", - "object" - ], - "license": "MIT", - "main": "index.js", - "name": "is-arguments", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/is-arguments.git" - }, - "scripts": { - "coverage": "covert test.js", - "eslint": "eslint *.js", - "jscs": "jscs *.js", - "lint": "npm run --silent jscs && npm run --silent eslint", - "posttest": "npm run --silent security", - "pretest": "npm run --silent lint", - "security": "nsp check", - "test": "npm run --silent tests-only", - "tests-only": "node test.js" - }, - "testling": { - "files": "test.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.4" -} diff --git a/node_modules/is-arguments/test.js b/node_modules/is-arguments/test.js deleted file mode 100644 index fca78d8..0000000 --- a/node_modules/is-arguments/test.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -var test = require('tape'); -var isArguments = require('./'); -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -test('primitives', function (t) { - t.notOk(isArguments([]), 'array is not arguments'); - t.notOk(isArguments({}), 'object is not arguments'); - t.notOk(isArguments(''), 'empty string is not arguments'); - t.notOk(isArguments('foo'), 'string is not arguments'); - t.notOk(isArguments({ length: 2 }), 'naive array-like is not arguments'); - t.end(); -}); - -test('arguments object', function (t) { - t.ok(isArguments(arguments), 'arguments is arguments'); - t.notOk(isArguments(Array.prototype.slice.call(arguments)), 'sliced arguments is not arguments'); - t.end(); -}); - -test('old-style arguments object', function (t) { - var isLegacyArguments = isArguments.isLegacyArguments || isArguments; - var fakeOldArguments = { - callee: function () {}, - length: 3 - }; - t.ok(isLegacyArguments(fakeOldArguments), 'old-style arguments is arguments'); - t.end(); -}); - -test('Symbol.toStringTag', { skip: !hasToStringTag }, function (t) { - var obj = {}; - obj[Symbol.toStringTag] = 'Arguments'; - t.notOk(isArguments(obj), 'object with faked toStringTag is not arguments'); - - var args = (function () { - return arguments; - }()); - args[Symbol.toStringTag] = 'Arguments'; - t.notOk(isArguments(obj), 'real arguments with faked toStringTag is not arguments'); - - t.end(); -}); diff --git a/node_modules/is-callable/.editorconfig b/node_modules/is-callable/.editorconfig deleted file mode 100644 index bc228f8..0000000 --- a/node_modules/is-callable/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -max_line_length = 150 - -[CHANGELOG.md] -indent_style = space -indent_size = 2 - -[*.json] -max_line_length = off - -[Makefile] -max_line_length = off diff --git a/node_modules/is-callable/.eslintrc b/node_modules/is-callable/.eslintrc deleted file mode 100644 index db619b5..0000000 --- a/node_modules/is-callable/.eslintrc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "id-length": 0, - "max-statements": [2, 12], - "max-statements-per-line": [2, { "max": 2 }] - } -} diff --git a/node_modules/is-callable/.github/FUNDING.yml b/node_modules/is-callable/.github/FUNDING.yml deleted file mode 100644 index 0fdebd0..0000000 --- a/node_modules/is-callable/.github/FUNDING.yml +++ /dev/null @@ -1,12 +0,0 @@ -# These are supported funding model platforms - -github: [ljharb] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: npm/is-callable -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-callable/.github/main.workflow b/node_modules/is-callable/.github/main.workflow deleted file mode 100644 index 0494481..0000000 --- a/node_modules/is-callable/.github/main.workflow +++ /dev/null @@ -1,14 +0,0 @@ -workflow "Autorebase branch on merge commits" { - on = "push" - resolves = ["rebase"] -} - -workflow "Autorebase PR on merge commits" { - on = "pull_request" - resolves = ["rebase"] -} - - action "rebase" { - uses = "ljharb/rebase@latest" - secrets = ["GITHUB_TOKEN"] -} diff --git a/node_modules/is-callable/.github/workflows/rebase.yml b/node_modules/is-callable/.github/workflows/rebase.yml deleted file mode 100644 index 436cb79..0000000 --- a/node_modules/is-callable/.github/workflows/rebase.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Automatic Rebase - -on: [pull_request] - -jobs: - _: - name: "Automatic Rebase" - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v1 - - uses: ljharb/rebase@master - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/node_modules/is-callable/.istanbul.yml b/node_modules/is-callable/.istanbul.yml deleted file mode 100644 index 9affe0b..0000000 --- a/node_modules/is-callable/.istanbul.yml +++ /dev/null @@ -1,47 +0,0 @@ -verbose: false -instrumentation: - root: . - extensions: - - .js - - .jsx - default-excludes: true - excludes: [] - variable: __coverage__ - compact: true - preserve-comments: false - complete-copy: false - save-baseline: false - baseline-file: ./coverage/coverage-baseline.raw.json - include-all-sources: false - include-pid: false - es-modules: false - auto-wrap: false -reporting: - print: summary - reports: - - html - dir: ./coverage - summarizer: pkg - report-config: {} - watermarks: - statements: [50, 80] - functions: [50, 80] - branches: [50, 80] - lines: [50, 80] -hooks: - hook-run-in-context: false - post-require-hook: null - handle-sigint: false -check: - global: - statements: 100 - lines: 100 - branches: 100 - functions: 100 - excludes: [] - each: - statements: 100 - lines: 100 - branches: 100 - functions: 100 - excludes: [] diff --git a/node_modules/is-callable/.travis.yml b/node_modules/is-callable/.travis.yml deleted file mode 100644 index 2d1c1d2..0000000 --- a/node_modules/is-callable/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -version: ~> 1.0 -language: node_js -os: - - linux -import: - - ljharb/travis-ci:node/all.yml - - ljharb/travis-ci:node/pretest.yml - - ljharb/travis-ci:node/posttest.yml - - ljharb/travis-ci:node/coverage.yml -matrix: - allow_failures: - - env: COVERAGE=true diff --git a/node_modules/is-callable/CHANGELOG.md b/node_modules/is-callable/CHANGELOG.md deleted file mode 100644 index 36b77fb..0000000 --- a/node_modules/is-callable/CHANGELOG.md +++ /dev/null @@ -1,67 +0,0 @@ -1.1.5 / 2019-12-18 -================= - * [meta] remove unused Makefile and associated utilities - * [meta] add `funding` field; add FUNDING.yml - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `semver`, `tape`, `covert`, `rimraf` - * [Tests] use shared travis configs - * [Tests] use `eccheck` over `editorconfig-tools` - * [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops - * [Tests] remove `jscs` - * [actions] add automatic rebasing / merge commit blocking - -1.1.4 / 2018-07-02 -================= - * [Fix] improve `class` and arrow function detection (#30, #31) - * [Tests] on all latest node minors; improve matrix - * [Dev Deps] update all dev deps - -1.1.3 / 2016-02-27 -================= - * [Fix] ensure “class “ doesn’t screw up “class” detection - * [Tests] up to `node` `v5.7`, `v4.3` - * [Dev Deps] update to `eslint` v2, `@ljharb/eslint-config`, `jscs` - -1.1.2 / 2016-01-15 -================= - * [Fix] Make sure comments don’t screw up “class” detection (#4) - * [Tests] up to `node` `v5.3` - * [Tests] Add `parallelshell`, run both `--es-staging` and stock tests at once - * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` - * [Refactor] convert `isNonES6ClassFn` into `isES6ClassFn` - -1.1.1 / 2015-11-30 -================= - * [Fix] do not throw when a non-function has a function in its [[Prototype]] (#2) - * [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`, `jscs`, `nsp`, `semver` - * [Tests] up to `node` `v5.1` - * [Tests] no longer allow node 0.8 to fail. - * [Tests] fix npm upgrades in older nodes - -1.1.0 / 2015-10-02 -================= - * [Fix] Some browsers report TypedArray constructors as `typeof object` - * [New] return false for "class" constructors, when possible. - * [Tests] up to `io.js` `v3.3`, `node` `v4.1` - * [Dev Deps] update `eslint`, `editorconfig-tools`, `nsp`, `tape`, `semver`, `jscs`, `covert`, `make-arrow-function` - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - -1.0.4 / 2015-01-30 -================= - * If @@toStringTag is not present, use the old-school Object#toString test. - -1.0.3 / 2015-01-29 -================= - * Add tests to ensure arrow functions are callable. - * Refactor to aid optimization of non-try/catch code. - -1.0.2 / 2015-01-29 -================= - * Fix broken package.json - -1.0.1 / 2015-01-29 -================= - * Add early exit for typeof not "function" - -1.0.0 / 2015-01-29 -================= - * Initial release. diff --git a/node_modules/is-callable/LICENSE b/node_modules/is-callable/LICENSE deleted file mode 100644 index b43df44..0000000 --- a/node_modules/is-callable/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Jordan Harband - -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/is-callable/README.md b/node_modules/is-callable/README.md deleted file mode 100644 index 0cb6587..0000000 --- a/node_modules/is-callable/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# is-callable [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -Is this JS value callable? Works with Functions and GeneratorFunctions, despite ES6 @@toStringTag. - -## Example - -```js -var isCallable = require('is-callable'); -var assert = require('assert'); - -assert.notOk(isCallable(undefined)); -assert.notOk(isCallable(null)); -assert.notOk(isCallable(false)); -assert.notOk(isCallable(true)); -assert.notOk(isCallable([])); -assert.notOk(isCallable({})); -assert.notOk(isCallable(/a/g)); -assert.notOk(isCallable(new RegExp('a', 'g'))); -assert.notOk(isCallable(new Date())); -assert.notOk(isCallable(42)); -assert.notOk(isCallable(NaN)); -assert.notOk(isCallable(Infinity)); -assert.notOk(isCallable(new Number(42))); -assert.notOk(isCallable('foo')); -assert.notOk(isCallable(Object('foo'))); - -assert.ok(isCallable(function () {})); -assert.ok(isCallable(function* () {})); -assert.ok(isCallable(x => x * x)); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-callable -[2]: http://versionbadg.es/ljharb/is-callable.svg -[3]: https://travis-ci.org/ljharb/is-callable.svg -[4]: https://travis-ci.org/ljharb/is-callable -[5]: https://david-dm.org/ljharb/is-callable.svg -[6]: https://david-dm.org/ljharb/is-callable -[7]: https://david-dm.org/ljharb/is-callable/dev-status.svg -[8]: https://david-dm.org/ljharb/is-callable#info=devDependencies -[9]: https://ci.testling.com/ljharb/is-callable.png -[10]: https://ci.testling.com/ljharb/is-callable -[11]: https://nodei.co/npm/is-callable.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-callable.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-callable.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-callable diff --git a/node_modules/is-callable/index.js b/node_modules/is-callable/index.js deleted file mode 100644 index d9820b5..0000000 --- a/node_modules/is-callable/index.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var fnToStr = Function.prototype.toString; - -var constructorRegex = /^\s*class\b/; -var isES6ClassFn = function isES6ClassFunction(value) { - try { - var fnStr = fnToStr.call(value); - return constructorRegex.test(fnStr); - } catch (e) { - return false; // not a function - } -}; - -var tryFunctionObject = function tryFunctionToStr(value) { - try { - if (isES6ClassFn(value)) { return false; } - fnToStr.call(value); - return true; - } catch (e) { - return false; - } -}; -var toStr = Object.prototype.toString; -var fnClass = '[object Function]'; -var genClass = '[object GeneratorFunction]'; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -module.exports = function isCallable(value) { - if (!value) { return false; } - if (typeof value !== 'function' && typeof value !== 'object') { return false; } - if (typeof value === 'function' && !value.prototype) { return true; } - if (hasToStringTag) { return tryFunctionObject(value); } - if (isES6ClassFn(value)) { return false; } - var strClass = toStr.call(value); - return strClass === fnClass || strClass === genClass; -}; diff --git a/node_modules/is-callable/package.json b/node_modules/is-callable/package.json deleted file mode 100644 index 3cd3ece..0000000 --- a/node_modules/is-callable/package.json +++ /dev/null @@ -1,121 +0,0 @@ -{ - "_from": "is-callable@^1.1.5", - "_id": "is-callable@1.1.5", - "_inBundle": false, - "_integrity": "sha512-ESKv5sMCJB2jnHTWZ3O5itG+O128Hsus4K4Qh1h2/cgn2vbgnLSVqfV46AeJA9D5EeeLa9w81KUXMtn34zhX+Q==", - "_location": "/is-callable", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-callable@^1.1.5", - "name": "is-callable", - "escapedName": "is-callable", - "rawSpec": "^1.1.5", - "saveSpec": null, - "fetchSpec": "^1.1.5" - }, - "_requiredBy": [ - "/es-abstract", - "/es-to-primitive" - ], - "_resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.5.tgz", - "_shasum": "f7e46b596890456db74e7f6e976cb3273d06faab", - "_spec": "is-callable@^1.1.5", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/es-abstract", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - }, - "bugs": { - "url": "https://github.com/ljharb/is-callable/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "Is this JS value callable? Works with Functions and GeneratorFunctions, despite ES6 @@toStringTag.", - "devDependencies": { - "@ljharb/eslint-config": "^15.0.2", - "covert": "^1.1.1", - "eclint": "^2.8.1", - "eslint": "^6.7.2", - "foreach": "^2.0.5", - "istanbul": "1.1.0-alpha.1", - "istanbul-merge": "^1.1.1", - "make-arrow-function": "^1.1.0", - "make-generator-function": "^1.1.0", - "rimraf": "^2.7.1", - "tape": "^4.12.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "homepage": "https://github.com/ljharb/is-callable#readme", - "keywords": [ - "Function", - "function", - "callable", - "generator", - "generator function", - "arrow", - "arrow function", - "ES6", - "toStringTag", - "@@toStringTag" - ], - "license": "MIT", - "main": "index.js", - "name": "is-callable", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/is-callable.git" - }, - "scripts": { - "coverage": "npm run --silent istanbul", - "covert": "covert test", - "covert:quiet": "covert test --quiet", - "istanbul": "npm run --silent istanbul:clean && npm run --silent istanbul:std && npm run --silent istanbul:harmony && npm run --silent istanbul:merge && istanbul check", - "istanbul:clean": "rimraf coverage coverage-std coverage-harmony", - "istanbul:harmony": "node --harmony ./node_modules/istanbul/lib/cli.js cover test --dir coverage-harmony", - "istanbul:merge": "istanbul-merge --out coverage/coverage.raw.json coverage-harmony/coverage.raw.json coverage-std/coverage.raw.json && istanbul report html", - "istanbul:std": "istanbul cover test --report html --dir coverage-std", - "lint": "eslint .", - "posttest": "npx aud", - "prelint": "eclint check *", - "pretest": "npm run --silent lint", - "test": "npm run --silent tests-only", - "test:staging": "node --es-staging test", - "test:stock": "node test", - "tests-only": "npm run --silent test:stock && npm run --silent test:staging" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.1.5" -} diff --git a/node_modules/is-callable/test/index.js b/node_modules/is-callable/test/index.js deleted file mode 100644 index 2e4c362..0000000 --- a/node_modules/is-callable/test/index.js +++ /dev/null @@ -1,159 +0,0 @@ -'use strict'; - -/* eslint no-magic-numbers: 1 */ - -var test = require('tape'); -var isCallable = require('../'); -var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; -var genFn = require('make-generator-function'); -var arrowFn = require('make-arrow-function')(); -var weirdlyCommentedArrowFn; -var asyncFn; -var asyncArrowFn; -try { - /* eslint-disable no-new-func */ - weirdlyCommentedArrowFn = Function('return cl/*/**/=>/**/ass - 1;')(); - asyncFn = Function('return async function foo() {};')(); - asyncArrowFn = Function('return async () => {};')(); - /* eslint-enable no-new-func */ -} catch (e) { /**/ } -var forEach = require('foreach'); - -var noop = function () {}; -var classFake = function classFake() { }; // eslint-disable-line func-name-matching -var returnClass = function () { return ' class '; }; -var return3 = function () { return 3; }; -/* for coverage */ -noop(); -classFake(); -returnClass(); -return3(); -/* end for coverage */ - -var invokeFunction = function invokeFunctionString(str) { - var result; - try { - /* eslint-disable no-new-func */ - var fn = Function(str); - /* eslint-enable no-new-func */ - result = fn(); - } catch (e) {} - return result; -}; - -var classConstructor = invokeFunction('"use strict"; return class Foo {}'); - -var commentedClass = invokeFunction('"use strict"; return class/*kkk*/\n//blah\n Bar\n//blah\n {}'); -var commentedClassOneLine = invokeFunction('"use strict"; return class/**/A{}'); -var classAnonymous = invokeFunction('"use strict"; return class{}'); -var classAnonymousCommentedOneLine = invokeFunction('"use strict"; return class/*/*/{}'); - -test('not callables', function (t) { - t.test('non-number/string primitives', function (st) { - st.notOk(isCallable(), 'undefined is not callable'); - st.notOk(isCallable(null), 'null is not callable'); - st.notOk(isCallable(false), 'false is not callable'); - st.notOk(isCallable(true), 'true is not callable'); - st.end(); - }); - - t.notOk(isCallable([]), 'array is not callable'); - t.notOk(isCallable({}), 'object is not callable'); - t.notOk(isCallable(/a/g), 'regex literal is not callable'); - t.notOk(isCallable(new RegExp('a', 'g')), 'regex object is not callable'); - t.notOk(isCallable(new Date()), 'new Date() is not callable'); - - t.test('numbers', function (st) { - st.notOk(isCallable(42), 'number is not callable'); - st.notOk(isCallable(Object(42)), 'number object is not callable'); - st.notOk(isCallable(NaN), 'NaN is not callable'); - st.notOk(isCallable(Infinity), 'Infinity is not callable'); - st.end(); - }); - - t.test('strings', function (st) { - st.notOk(isCallable('foo'), 'string primitive is not callable'); - st.notOk(isCallable(Object('foo')), 'string object is not callable'); - st.end(); - }); - - t.test('non-function with function in its [[Prototype]] chain', function (st) { - var Foo = function Bar() {}; - Foo.prototype = noop; - st.equal(true, isCallable(Foo), 'sanity check: Foo is callable'); - st.equal(false, isCallable(new Foo()), 'instance of Foo is not callable'); - st.end(); - }); - - t.end(); -}); - -test('@@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (t) { - var fakeFunction = { - toString: function () { return String(return3); }, - valueOf: return3 - }; - fakeFunction[Symbol.toStringTag] = 'Function'; - t.equal(String(fakeFunction), String(return3)); - t.equal(Number(fakeFunction), return3()); - t.notOk(isCallable(fakeFunction), 'fake Function with @@toStringTag "Function" is not callable'); - t.end(); -}); - -var typedArrayNames = [ - 'Int8Array', - 'Uint8Array', - 'Uint8ClampedArray', - 'Int16Array', - 'Uint16Array', - 'Int32Array', - 'Uint32Array', - 'Float32Array', - 'Float64Array' -]; - -test('Functions', function (t) { - t.ok(isCallable(noop), 'function is callable'); - t.ok(isCallable(classFake), 'function with name containing "class" is callable'); - t.ok(isCallable(returnClass), 'function with string " class " is callable'); - t.ok(isCallable(isCallable), 'isCallable is callable'); - t.end(); -}); - -test('Typed Arrays', function (st) { - forEach(typedArrayNames, function (typedArray) { - /* istanbul ignore if : covered in node 0.6 */ - if (typeof global[typedArray] === 'undefined') { - st.comment('# SKIP typed array "' + typedArray + '" not supported'); - } else { - st.ok(isCallable(global[typedArray]), typedArray + ' is callable'); - } - }); - st.end(); -}); - -test('Generators', { skip: !genFn }, function (t) { - t.ok(isCallable(genFn), 'generator function is callable'); - t.end(); -}); - -test('Arrow functions', { skip: !arrowFn }, function (t) { - t.ok(isCallable(arrowFn), 'arrow function is callable'); - t.ok(isCallable(weirdlyCommentedArrowFn), 'weirdly commented arrow functions are callable'); - t.end(); -}); - -test('"Class" constructors', { skip: !classConstructor || !commentedClass || !commentedClassOneLine || !classAnonymous }, function (t) { - t.notOk(isCallable(classConstructor), 'class constructors are not callable'); - t.notOk(isCallable(commentedClass), 'class constructors with comments in the signature are not callable'); - t.notOk(isCallable(commentedClassOneLine), 'one-line class constructors with comments in the signature are not callable'); - t.notOk(isCallable(classAnonymous), 'anonymous class constructors are not callable'); - t.notOk(isCallable(classAnonymousCommentedOneLine), 'anonymous one-line class constructors with comments in the signature are not callable'); - t.end(); -}); - -test('`async function`s', { skip: !asyncFn }, function (t) { - t.ok(isCallable(asyncFn), '`async function`s are callable'); - t.ok(isCallable(asyncArrowFn), '`async` arrow functions are callable'); - t.end(); -}); diff --git a/node_modules/is-date-object/.eslintrc b/node_modules/is-date-object/.eslintrc deleted file mode 100644 index 1228f97..0000000 --- a/node_modules/is-date-object/.eslintrc +++ /dev/null @@ -1,9 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "max-statements": [2, 12] - } -} diff --git a/node_modules/is-date-object/.github/FUNDING.yml b/node_modules/is-date-object/.github/FUNDING.yml deleted file mode 100644 index 9cfa9fd..0000000 --- a/node_modules/is-date-object/.github/FUNDING.yml +++ /dev/null @@ -1,12 +0,0 @@ -# These are supported funding model platforms - -github: [ljharb] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: npm/is-date-object -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-date-object/.github/workflows/rebase.yml b/node_modules/is-date-object/.github/workflows/rebase.yml deleted file mode 100644 index 436cb79..0000000 --- a/node_modules/is-date-object/.github/workflows/rebase.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Automatic Rebase - -on: [pull_request] - -jobs: - _: - name: "Automatic Rebase" - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v1 - - uses: ljharb/rebase@master - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/node_modules/is-date-object/.jscs.json b/node_modules/is-date-object/.jscs.json deleted file mode 100644 index b4d9b8b..0000000 --- a/node_modules/is-date-object/.jscs.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 1 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": "asc-insensitive", - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/node_modules/is-date-object/.travis.yml b/node_modules/is-date-object/.travis.yml deleted file mode 100644 index 2d1c1d2..0000000 --- a/node_modules/is-date-object/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -version: ~> 1.0 -language: node_js -os: - - linux -import: - - ljharb/travis-ci:node/all.yml - - ljharb/travis-ci:node/pretest.yml - - ljharb/travis-ci:node/posttest.yml - - ljharb/travis-ci:node/coverage.yml -matrix: - allow_failures: - - env: COVERAGE=true diff --git a/node_modules/is-date-object/CHANGELOG.md b/node_modules/is-date-object/CHANGELOG.md deleted file mode 100644 index ff802bb..0000000 --- a/node_modules/is-date-object/CHANGELOG.md +++ /dev/null @@ -1,76 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). - -## [v1.0.2](https://github.com/inspect-js/is-date-object/compare/v1.0.1...v1.0.2) - 2019-12-19 - -### Commits - -- [Tests] use shared travis-ci configs [`8a378b8`](https://github.com/inspect-js/is-date-object/commit/8a378b8fd6a4202fffc9ec193aca02efe937bc35) -- [Tests] on all node minors; use `nvm install-latest-npm`; fix scripts; improve matrix [`6e97a21`](https://github.com/inspect-js/is-date-object/commit/6e97a21276cf448ce424fb9ea13edd4587f289f1) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `is`, `jscs`, `nsp`, `semver`, `tape` [`8472b90`](https://github.com/inspect-js/is-date-object/commit/8472b90f82e5153c22e7a8a7726a5cc6110e93d7) -- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`ae73e38`](https://github.com/inspect-js/is-date-object/commit/ae73e3890df7da0bc4449088e30340cb4df3294d) -- [meta] add `auto-changelog` [`82f8f47`](https://github.com/inspect-js/is-date-object/commit/82f8f473a6ee45e2b66810cb743e0122c18381c5) -- [meta] remove unused Makefile and associated utilities [`788a2cd`](https://github.com/inspect-js/is-date-object/commit/788a2cdfd0bc8f1903967219897f6d00c4c6a26b) -- [Tests] up to `node` `v11.4`, `v10.14`, `v8.14`, `v6.15` [`b9caf7c`](https://github.com/inspect-js/is-date-object/commit/b9caf7c814e5e2549454cb444f8b739f9ce1a388) -- [Tests] up to `node` `v12.4`, `v11.15`, `v10.15`, `v8.15`, `v6.17`; use `nvm install-latest-npm` [`cda0abc`](https://github.com/inspect-js/is-date-object/commit/cda0abc04a21c9b5ec72eabd010155c988032056) -- [Tests] up to `node` `v12.10`, `v10.16`, `v8.16` [`49bc482`](https://github.com/inspect-js/is-date-object/commit/49bc482fd9f71436b663c07144083a8423697299) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `semver`, `tape`; add `safe-publish-latest` [`f77fec4`](https://github.com/inspect-js/is-date-object/commit/f77fec48057e156b2276b4c14cf303306116b9f6) -- [actions] add automatic rebasing / merge commit blocking [`68605fc`](https://github.com/inspect-js/is-date-object/commit/68605fcb6bc0341ff0aae14a94bf5d18e1bc73be) -- [meta] create FUNDING.yml [`4f82d88`](https://github.com/inspect-js/is-date-object/commit/4f82d88e1e6ac1b97f0ce96aa0aa057ad758a581) -- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`3cbf28a`](https://github.com/inspect-js/is-date-object/commit/3cbf28a185ced940cfce8a09fa8479cc83575876) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config@`, `is`, `semver`, `tape` [`abf9fb0`](https://github.com/inspect-js/is-date-object/commit/abf9fb0d55ef0697e64e888d74f2e5fe53d7cdcb) -- [Tests] switch from `nsp` to `npm audit` [`6543c7d`](https://github.com/inspect-js/is-date-object/commit/6543c7d559d1fb79215b46c8b79e0e3e2a83f5de) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`ba5d2d7`](https://github.com/inspect-js/is-date-object/commit/ba5d2d7fc0975d7c03b8f2b7f43a09af93e365ba) -- [Dev Deps] update `eslint`, `nsp`, `semver`, `tape` [`c1e3525`](https://github.com/inspect-js/is-date-object/commit/c1e3525afa76a696f7cf1b58aab7f55d220b2c20) -- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`14e4824`](https://github.com/inspect-js/is-date-object/commit/14e4824188c85207ed3b86627b09e9f64b135db7) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest` [`68ead64`](https://github.com/inspect-js/is-date-object/commit/68ead64a07e0de282ea3cd38e12cc8b0e0f6d3cd) -- [Dev Deps] update `eslint`, semver`, `tape`, `semver` [`f55453f`](https://github.com/inspect-js/is-date-object/commit/f55453f200903277465d7e9307a9c49120a4f419) -- Only apps should have lockfiles [`6c848eb`](https://github.com/inspect-js/is-date-object/commit/6c848eba982cc58053d4cca08c01f12a433f3695) -- [Tests] remove `jscs` [`3fd3a62`](https://github.com/inspect-js/is-date-object/commit/3fd3a62121607ad074b7fc977f3fc6575b66f755) -- [Dev Deps] update `eslint`, `tape` [`77d3130`](https://github.com/inspect-js/is-date-object/commit/77d3130a0039e5dae24c17de790dd510c265edc6) -- [meta] add `funding` field [`9ef6d58`](https://github.com/inspect-js/is-date-object/commit/9ef6d5888bf829a5812b3b091dc99839d48c355e) - -## [v1.0.1](https://github.com/inspect-js/is-date-object/compare/v1.0.0...v1.0.1) - 2015-09-27 - -### Commits - -- Update `tape`, `semver`, `eslint`; use my personal shared `eslint` config. [`731aa13`](https://github.com/inspect-js/is-date-object/commit/731aa134b0b8dc84e302d0b2264a415cb456ccab) -- Update `is`, `tape`, `covert`, `jscs`, `editorconfig-tools`, `nsp`, `eslint`, `semver` [`53e43a6`](https://github.com/inspect-js/is-date-object/commit/53e43a627dd01757cf3d469599f3dffd9d72b150) -- Update `eslint` [`d2fc304`](https://github.com/inspect-js/is-date-object/commit/d2fc3046f087b0026448ffde0cf46b1f741cbd4e) -- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`c9568df`](https://github.com/inspect-js/is-date-object/commit/c9568df228fa698dc6fcc9553b5d612e7ee427aa) -- Test on latest `node` and `io.js` versions. [`a21d537`](https://github.com/inspect-js/is-date-object/commit/a21d537562166ebd18bde3a262fd157dd774ae17) -- Update `nsp`, `eslint`, `semver` [`9e1d908`](https://github.com/inspect-js/is-date-object/commit/9e1d9087c0c79c34fcb2abfc701cdfa1efcb327c) -- Update `covert`, `jscs`, `eslint`, `semver` [`f198f6b`](https://github.com/inspect-js/is-date-object/commit/f198f6b997912da10a3d821a089e1581edc730a0) -- [Dev Deps] update `tape`, `jscs`, `eslint` [`ab9bdbb`](https://github.com/inspect-js/is-date-object/commit/ab9bdbbc189cef033346508db47cd1feb04a69d3) -- If `@@toStringTag` is not present, use the old-school `Object#toString` test. [`c03afce`](https://github.com/inspect-js/is-date-object/commit/c03afce001368b29eb929900075749b113a252c8) -- [Dev Deps] update `jscs`, `nsp`, `tape`, `eslint`, `@ljharb/eslint-config` [`9d94ccb`](https://github.com/inspect-js/is-date-object/commit/9d94ccbab4160d2fa649123e37951d86b69a8b15) -- [Dev Deps] update `is`, `eslint`, `@ljharb/eslint-config`, `semver` [`35cbff7`](https://github.com/inspect-js/is-date-object/commit/35cbff7f7c8216fbb79c799f74b2336eaf0d726a) -- Test up to `io.js` `v2.3` [`be5d11e`](https://github.com/inspect-js/is-date-object/commit/be5d11e7ebd9473d7ae554179b3769082485f6f4) -- [Tests] on `io.js` `v3.3`, up to `node` `v4.1` [`20221a3`](https://github.com/inspect-js/is-date-object/commit/20221a34858d2b21e23bdc2c08df23f0bc08d11e) -- [Tests] up to `io.js` `v3.2 ` [`7009b4a`](https://github.com/inspect-js/is-date-object/commit/7009b4a9999e14eacbdf6068afd82f478473f007) -- Test on `io.js` `v2.1` [`68b29b1`](https://github.com/inspect-js/is-date-object/commit/68b29b19a07e6589a7ca37ab764be28f144ac88e) -- Remove `editorconfig-tools` [`8d3972c`](https://github.com/inspect-js/is-date-object/commit/8d3972c1795fdcfd337680e11ab610e4885fb079) -- [Dev Deps] update `tape` [`204945d`](https://github.com/inspect-js/is-date-object/commit/204945d8658a3513ca6315ddf795e4034adb4545) -- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`7bff214`](https://github.com/inspect-js/is-date-object/commit/7bff214dcb2317b96219921476f990814afbb401) -- Test on `io.js` `v2.5` [`92f7bd6`](https://github.com/inspect-js/is-date-object/commit/92f7bd6747e3259b0ddc9c287876f46a9cd4c270) -- Test on `io.js` `v2.4` [`ebb34bf`](https://github.com/inspect-js/is-date-object/commit/ebb34bf1f58949768063f86ac012f1ca5d7cf6d9) -- Fix tests for faked @@toStringTag [`3b9c26c`](https://github.com/inspect-js/is-date-object/commit/3b9c26c15040af6a87f8d77ce6c85a7bef7a4304) -- Test on `io.js` `v3.0` [`5eedf4b`](https://github.com/inspect-js/is-date-object/commit/5eedf4bea76380a08813fd0977469c2480302a82) - -## v1.0.0 - 2015-01-28 - -### Commits - -- Dotfiles. [`5b6a929`](https://github.com/inspect-js/is-date-object/commit/5b6a9298c6f70882e78e66d64c9c019f85790f52) -- `make release` [`e8d40ce`](https://github.com/inspect-js/is-date-object/commit/e8d40ceca85acd0aa4b2753faa6e41c0c54cf6c3) -- package.json [`a107259`](https://github.com/inspect-js/is-date-object/commit/a1072591ea510a2998298be6cef827b123f4643f) -- Read me [`eb92695`](https://github.com/inspect-js/is-date-object/commit/eb92695664bdee8fc49891cd73aa2f41075f53cb) -- Initial commit [`4fc7755`](https://github.com/inspect-js/is-date-object/commit/4fc7755ff12f1d7a55cf841d486bf6b2350fe5a0) -- Tests. [`b6f432f`](https://github.com/inspect-js/is-date-object/commit/b6f432fb6801c5ff8d89cfec7601d59478e23dd1) -- Implementation. [`dd0fd96`](https://github.com/inspect-js/is-date-object/commit/dd0fd96c4016a66cec7cd59db0fde37c2ef3cdb5) diff --git a/node_modules/is-date-object/LICENSE b/node_modules/is-date-object/LICENSE deleted file mode 100644 index b43df44..0000000 --- a/node_modules/is-date-object/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Jordan Harband - -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/is-date-object/README.md b/node_modules/is-date-object/README.md deleted file mode 100644 index 55b0c59..0000000 --- a/node_modules/is-date-object/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# is-date-object [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -Is this value a JS Date object? This module works cross-realm/iframe, and despite ES6 @@toStringTag. - -## Example - -```js -var isDate = require('is-date-object'); -var assert = require('assert'); - -assert.notOk(isDate(undefined)); -assert.notOk(isDate(null)); -assert.notOk(isDate(false)); -assert.notOk(isDate(true)); -assert.notOk(isDate(42)); -assert.notOk(isDate('foo')); -assert.notOk(isDate(function () {})); -assert.notOk(isDate([])); -assert.notOk(isDate({})); -assert.notOk(isDate(/a/g)); -assert.notOk(isDate(new RegExp('a', 'g'))); - -assert.ok(isDate(new Date())); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-date-object -[2]: http://versionbadg.es/ljharb/is-date-object.svg -[3]: https://travis-ci.org/ljharb/is-date-object.svg -[4]: https://travis-ci.org/ljharb/is-date-object -[5]: https://david-dm.org/ljharb/is-date-object.svg -[6]: https://david-dm.org/ljharb/is-date-object -[7]: https://david-dm.org/ljharb/is-date-object/dev-status.svg -[8]: https://david-dm.org/ljharb/is-date-object#info=devDependencies -[9]: https://ci.testling.com/ljharb/is-date-object.png -[10]: https://ci.testling.com/ljharb/is-date-object -[11]: https://nodei.co/npm/is-date-object.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-date-object.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-date-object.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-date-object diff --git a/node_modules/is-date-object/index.js b/node_modules/is-date-object/index.js deleted file mode 100644 index 285ec4c..0000000 --- a/node_modules/is-date-object/index.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var getDay = Date.prototype.getDay; -var tryDateObject = function tryDateGetDayCall(value) { - try { - getDay.call(value); - return true; - } catch (e) { - return false; - } -}; - -var toStr = Object.prototype.toString; -var dateClass = '[object Date]'; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -module.exports = function isDateObject(value) { - if (typeof value !== 'object' || value === null) { - return false; - } - return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass; -}; diff --git a/node_modules/is-date-object/package.json b/node_modules/is-date-object/package.json deleted file mode 100644 index e4ff45e..0000000 --- a/node_modules/is-date-object/package.json +++ /dev/null @@ -1,104 +0,0 @@ -{ - "_from": "is-date-object@^1.0.1", - "_id": "is-date-object@1.0.2", - "_inBundle": false, - "_integrity": "sha512-USlDT524woQ08aoZFzh3/Z6ch9Y/EWXEHQ/AaRN0SkKq4t2Jw2R2339tSXmwuVoY7LLlBCbOIlx2myP/L5zk0g==", - "_location": "/is-date-object", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-date-object@^1.0.1", - "name": "is-date-object", - "escapedName": "is-date-object", - "rawSpec": "^1.0.1", - "saveSpec": null, - "fetchSpec": "^1.0.1" - }, - "_requiredBy": [ - "/es-to-primitive" - ], - "_resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.2.tgz", - "_shasum": "bda736f2cd8fd06d32844e7743bfa7494c3bfd7e", - "_spec": "is-date-object@^1.0.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/es-to-primitive", - "author": { - "name": "Jordan Harband" - }, - "auto-changelog": { - "output": "CHANGELOG.md", - "template": "keepachangelog", - "unreleased": false, - "commitLimit": false, - "backfillLimit": false - }, - "bugs": { - "url": "https://github.com/ljharb/is-date-object/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Is this value a JS Date object? This module works cross-realm/iframe, and despite ES6 @@toStringTag.", - "devDependencies": { - "@ljharb/eslint-config": "^15.0.2", - "auto-changelog": "^1.16.2", - "covert": "^1.1.1", - "eslint": "^6.7.2", - "foreach": "^2.0.5", - "indexof": "^0.0.1", - "is": "^3.3.0", - "safe-publish-latest": "^1.1.4", - "tape": "^4.12.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "homepage": "https://github.com/ljharb/is-date-object#readme", - "keywords": [ - "Date", - "ES6", - "toStringTag", - "@@toStringTag", - "Date object" - ], - "license": "MIT", - "main": "index.js", - "name": "is-date-object", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/is-date-object.git" - }, - "scripts": { - "coverage": "covert test/index.js", - "lint": "eslint .", - "posttest": "npx aud", - "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", - "prepublish": "safe-publish-latest", - "pretest": "npm run lint", - "test": "npm run tests-only", - "tests-only": "node --harmony --es-staging test", - "version": "auto-changelog && git add CHANGELOG.md" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.2" -} diff --git a/node_modules/is-date-object/test/index.js b/node_modules/is-date-object/test/index.js deleted file mode 100644 index b9d27c5..0000000 --- a/node_modules/is-date-object/test/index.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -var test = require('tape'); -var isDate = require('../'); -var hasSymbols = typeof Symbol === 'function' && typeof Symbol('') === 'symbol'; - -test('not Dates', function (t) { - t.notOk(isDate(), 'undefined is not Date'); - t.notOk(isDate(null), 'null is not Date'); - t.notOk(isDate(false), 'false is not Date'); - t.notOk(isDate(true), 'true is not Date'); - t.notOk(isDate(42), 'number is not Date'); - t.notOk(isDate('foo'), 'string is not Date'); - t.notOk(isDate([]), 'array is not Date'); - t.notOk(isDate({}), 'object is not Date'); - t.notOk(isDate(function () {}), 'function is not Date'); - t.notOk(isDate(/a/g), 'regex literal is not Date'); - t.notOk(isDate(new RegExp('a', 'g')), 'regex object is not Date'); - t.end(); -}); - -test('@@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (t) { - var realDate = new Date(); - var fakeDate = { - toString: function () { return String(realDate); }, - valueOf: function () { return realDate.getTime(); } - }; - fakeDate[Symbol.toStringTag] = 'Date'; - t.notOk(isDate(fakeDate), 'fake Date with @@toStringTag "Date" is not Date'); - t.end(); -}); - -test('Dates', function (t) { - t.ok(isDate(new Date()), 'new Date() is Date'); - t.end(); -}); diff --git a/node_modules/is-fullwidth-code-point/index.js b/node_modules/is-fullwidth-code-point/index.js deleted file mode 100644 index a7d3e38..0000000 --- a/node_modules/is-fullwidth-code-point/index.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; -var numberIsNan = require('number-is-nan'); - -module.exports = function (x) { - if (numberIsNan(x)) { - return false; - } - - // https://github.com/nodejs/io.js/blob/cff7300a578be1b10001f2d967aaedc88aee6402/lib/readline.js#L1369 - - // code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - if (x >= 0x1100 && ( - x <= 0x115f || // Hangul Jamo - 0x2329 === x || // LEFT-POINTING ANGLE BRACKET - 0x232a === x || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - 0x3250 <= x && x <= 0x4dbf || - // CJK Unified Ideographs .. Yi Radicals - 0x4e00 <= x && x <= 0xa4c6 || - // Hangul Jamo Extended-A - 0xa960 <= x && x <= 0xa97c || - // Hangul Syllables - 0xac00 <= x && x <= 0xd7a3 || - // CJK Compatibility Ideographs - 0xf900 <= x && x <= 0xfaff || - // Vertical Forms - 0xfe10 <= x && x <= 0xfe19 || - // CJK Compatibility Forms .. Small Form Variants - 0xfe30 <= x && x <= 0xfe6b || - // Halfwidth and Fullwidth Forms - 0xff01 <= x && x <= 0xff60 || - 0xffe0 <= x && x <= 0xffe6 || - // Kana Supplement - 0x1b000 <= x && x <= 0x1b001 || - // Enclosed Ideographic Supplement - 0x1f200 <= x && x <= 0x1f251 || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - 0x20000 <= x && x <= 0x3fffd)) { - return true; - } - - return false; -} diff --git a/node_modules/is-fullwidth-code-point/license b/node_modules/is-fullwidth-code-point/license deleted file mode 100644 index 654d0bf..0000000 --- a/node_modules/is-fullwidth-code-point/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/is-fullwidth-code-point/package.json b/node_modules/is-fullwidth-code-point/package.json deleted file mode 100644 index 91cb461..0000000 --- a/node_modules/is-fullwidth-code-point/package.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "_from": "is-fullwidth-code-point@^1.0.0", - "_id": "is-fullwidth-code-point@1.0.0", - "_inBundle": false, - "_integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", - "_location": "/is-fullwidth-code-point", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-fullwidth-code-point@^1.0.0", - "name": "is-fullwidth-code-point", - "escapedName": "is-fullwidth-code-point", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/string-width" - ], - "_resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", - "_shasum": "ef9e31386f031a7f0d643af82fde50c457ef00cb", - "_spec": "is-fullwidth-code-point@^1.0.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/string-width", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "bugs": { - "url": "https://github.com/sindresorhus/is-fullwidth-code-point/issues" - }, - "bundleDependencies": false, - "dependencies": { - "number-is-nan": "^1.0.0" - }, - "deprecated": false, - "description": "Check if the character represented by a given Unicode code point is fullwidth", - "devDependencies": { - "ava": "0.0.4", - "code-point-at": "^1.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/sindresorhus/is-fullwidth-code-point#readme", - "keywords": [ - "fullwidth", - "full-width", - "full", - "width", - "unicode", - "character", - "char", - "string", - "str", - "codepoint", - "code", - "point", - "is", - "detect", - "check" - ], - "license": "MIT", - "name": "is-fullwidth-code-point", - "repository": { - "type": "git", - "url": "git+https://github.com/sindresorhus/is-fullwidth-code-point.git" - }, - "scripts": { - "test": "node test.js" - }, - "version": "1.0.0" -} diff --git a/node_modules/is-fullwidth-code-point/readme.md b/node_modules/is-fullwidth-code-point/readme.md deleted file mode 100644 index 4936464..0000000 --- a/node_modules/is-fullwidth-code-point/readme.md +++ /dev/null @@ -1,39 +0,0 @@ -# is-fullwidth-code-point [![Build Status](https://travis-ci.org/sindresorhus/is-fullwidth-code-point.svg?branch=master)](https://travis-ci.org/sindresorhus/is-fullwidth-code-point) - -> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) - - -## Install - -``` -$ npm install --save is-fullwidth-code-point -``` - - -## Usage - -```js -var isFullwidthCodePoint = require('is-fullwidth-code-point'); - -isFullwidthCodePoint('谢'.codePointAt()); -//=> true - -isFullwidthCodePoint('a'.codePointAt()); -//=> false -``` - - -## API - -### isFullwidthCodePoint(input) - -#### input - -Type: `number` - -[Code point](https://en.wikipedia.org/wiki/Code_point) of a character. - - -## License - -MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/is-generator-function/.editorconfig b/node_modules/is-generator-function/.editorconfig deleted file mode 100644 index ac29ade..0000000 --- a/node_modules/is-generator-function/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -max_line_length = 120 - -[CHANGELOG.md] -indent_style = space -indent_size = 2 - -[*.json] -max_line_length = off - -[Makefile] -max_line_length = off diff --git a/node_modules/is-generator-function/.eslintrc b/node_modules/is-generator-function/.eslintrc deleted file mode 100644 index 484e4d7..0000000 --- a/node_modules/is-generator-function/.eslintrc +++ /dev/null @@ -1,9 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "no-new-func": [1] - } -} diff --git a/node_modules/is-generator-function/.jscs.json b/node_modules/is-generator-function/.jscs.json deleted file mode 100644 index c62f2c1..0000000 --- a/node_modules/is-generator-function/.jscs.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 2 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": "asc-insensitive", - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/node_modules/is-generator-function/.nvmrc b/node_modules/is-generator-function/.nvmrc deleted file mode 100644 index 64f5a0a..0000000 --- a/node_modules/is-generator-function/.nvmrc +++ /dev/null @@ -1 +0,0 @@ -node diff --git a/node_modules/is-generator-function/.travis.yml b/node_modules/is-generator-function/.travis.yml deleted file mode 100644 index 7ead9e9..0000000 --- a/node_modules/is-generator-function/.travis.yml +++ /dev/null @@ -1,191 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "9.3" - - "8.9" - - "7.10" - - "6.12" - - "5.12" - - "4.8" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "8" - env: COVERAGE=true - - node_js: "4" - env: COVERAGE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true - - env: COVERAGE=true diff --git a/node_modules/is-generator-function/CHANGELOG.md b/node_modules/is-generator-function/CHANGELOG.md deleted file mode 100644 index 983f518..0000000 --- a/node_modules/is-generator-function/CHANGELOG.md +++ /dev/null @@ -1,44 +0,0 @@ -1.0.7 / 2017-12-27 -================= - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `nsp`, `semver`, `tape` - * [Tests] up to `node` `v9.3`, `v8.9`, `v6.12`; pin included builds to LTS; use `nvm install-latest-npm` - * [Tests] run tests with uglify-register - -1.0.6 / 2016-12-20 -================= - * [Fix] fix `is-generator-function` in an env without native generators, with core-js (https://github.com/ljharb/is-equal/issues/33) - -1.0.5 / 2016-12-19 -================= - * [Fix] account for Safari 10 which reports the wrong toString on generator functions - * [Refactor] remove useless `Object#toString` check - * [Dev Deps] update everything; add linting - * [Tests] use pretest/posttest for linting/security - * [Tests] on all minors of node and io.js - -1.0.4 / 2015-03-03 -================= - * Add support for concise generator methods (#2) This is a patch change since concise methods are not in any actual released engines yet. - * Test on latest `io.js` - * Update `semver` - -1.0.3 / 2015-01-31 -================= - * Speed up travis-ci tests - * Run tests against a faked @@toStringTag - * Bail out early when typeof is not "function" - -1.0.2 / 2015-01-20 -================= - * Update `jscs`, `tape` - * Fix tests in newer v8 (and io.js) where Object#toString.call of a generator is GeneratorFunction, not Function - -1.0.1 / 2014-12-14 -================= - * Update `jscs`, `tape` - * Tweaks to README - * Use `make-generator-function` in tests - -1.0.0 / 2014-08-09 -================= - * Initial release. diff --git a/node_modules/is-generator-function/LICENSE b/node_modules/is-generator-function/LICENSE deleted file mode 100644 index 47b7b50..0000000 --- a/node_modules/is-generator-function/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Jordan Harband - -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/is-generator-function/Makefile b/node_modules/is-generator-function/Makefile deleted file mode 100644 index ccca6f1..0000000 --- a/node_modules/is-generator-function/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. -$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) - - # The files that need updating when incrementing the version number. -VERSIONED_FILES := *.js */*.js *.json README* - - -# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. -# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment -# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. -export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") -UTILS := semver replace -# Make sure that all required utilities can be located. -UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) - -# Default target (by virtue of being the first non '.'-prefixed in the file). -.PHONY: _no-target-specified -_no-target-specified: - $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) - -# Lists all targets defined in this makefile. -.PHONY: list -list: - @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort - -# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). -.PHONY: test -test: - @npm test - -.PHONY: _ensure-tag -_ensure-tag: -ifndef TAG - $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) -endif - -CHANGELOG_ERROR = $(error No CHANGELOG specified) -.PHONY: _ensure-changelog -_ensure-changelog: - @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) - -# Ensures that the git workspace is clean. -.PHONY: _ensure-clean -_ensure-clean: - @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } - -# Makes a release; invoke with `make TAG= release`. -.PHONY: release -release: _ensure-tag _ensure-changelog _ensure-clean - @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ - new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ - if printf "$$new_ver" | command grep -q '^[0-9]'; then \ - semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ - semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ - else \ - new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ - fi; \ - printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ - replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ - git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ - git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/node_modules/is-generator-function/README.md b/node_modules/is-generator-function/README.md deleted file mode 100644 index 027facf..0000000 --- a/node_modules/is-generator-function/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# is-generator-function [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -Is this a native generator function? - -## Example - -```js -var isGeneratorFunction = require('is-generator-function'); -assert(!isGeneratorFunction(function () {})); -assert(!isGeneratorFunction(null)); -assert(isGeneratorFunction(function* () { yield 42; return Infinity; })); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-generator-function -[2]: http://versionbadg.es/ljharb/is-generator-function.svg -[3]: https://travis-ci.org/ljharb/is-generator-function.svg -[4]: https://travis-ci.org/ljharb/is-generator-function -[5]: https://david-dm.org/ljharb/is-generator-function.svg -[6]: https://david-dm.org/ljharb/is-generator-function -[7]: https://david-dm.org/ljharb/is-generator-function/dev-status.svg -[8]: https://david-dm.org/ljharb/is-generator-function#info=devDependencies -[9]: https://ci.testling.com/ljharb/is-generator-function.png -[10]: https://ci.testling.com/ljharb/is-generator-function -[11]: https://nodei.co/npm/is-generator-function.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-generator-function.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-generator-function.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-generator-function - diff --git a/node_modules/is-generator-function/index.js b/node_modules/is-generator-function/index.js deleted file mode 100644 index 306a299..0000000 --- a/node_modules/is-generator-function/index.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var toStr = Object.prototype.toString; -var fnToStr = Function.prototype.toString; -var isFnRegex = /^\s*(?:function)?\*/; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var getProto = Object.getPrototypeOf; -var getGeneratorFunc = function () { // eslint-disable-line consistent-return - if (!hasToStringTag) { - return false; - } - try { - return Function('return function*() {}')(); - } catch (e) { - } -}; -var generatorFunc = getGeneratorFunc(); -var GeneratorFunction = generatorFunc ? getProto(generatorFunc) : {}; - -module.exports = function isGeneratorFunction(fn) { - if (typeof fn !== 'function') { - return false; - } - if (isFnRegex.test(fnToStr.call(fn))) { - return true; - } - if (!hasToStringTag) { - var str = toStr.call(fn); - return str === '[object GeneratorFunction]'; - } - return getProto(fn) === GeneratorFunction; -}; diff --git a/node_modules/is-generator-function/package.json b/node_modules/is-generator-function/package.json deleted file mode 100644 index 3dea9b2..0000000 --- a/node_modules/is-generator-function/package.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "_from": "is-generator-function@^1.0.7", - "_id": "is-generator-function@1.0.7", - "_inBundle": false, - "_integrity": "sha512-YZc5EwyO4f2kWCax7oegfuSr9mFz1ZvieNYBEjmukLxgXfBUbxAWGVF7GZf0zidYtoBl3WvC07YK0wT76a+Rtw==", - "_location": "/is-generator-function", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-generator-function@^1.0.7", - "name": "is-generator-function", - "escapedName": "is-generator-function", - "rawSpec": "^1.0.7", - "saveSpec": null, - "fetchSpec": "^1.0.7" - }, - "_requiredBy": [ - "/util" - ], - "_resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.7.tgz", - "_shasum": "d2132e529bb0000a7f80794d4bdf5cd5e5813522", - "_spec": "is-generator-function@^1.0.7", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/util", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/ljharb/is-generator-function/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Determine if a function is a native generator function.", - "devDependencies": { - "@ljharb/eslint-config": "^12.2.1", - "core-js": "^2.5.3", - "covert": "^1.1.0", - "eslint": "^4.14.0", - "jscs": "^3.0.7", - "make-generator-function": "^1.1.0", - "nsp": "^3.1.0", - "replace": "^0.3.0", - "semver": "^5.4.1", - "tape": "^4.8.0", - "uglify-register": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/is-generator-function#readme", - "keywords": [ - "generator", - "generator function", - "es6", - "es2015", - "yield", - "function", - "function*" - ], - "license": "MIT", - "main": "index.js", - "name": "is-generator-function", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/is-generator-function.git" - }, - "scripts": { - "coverage": "covert test", - "eslint": "eslint *.js */*.js", - "jscs": "jscs *.js */*.js", - "lint": "npm run jscs && npm run eslint", - "posttest": "npm run security", - "posttests-only": "npm run test:corejs && npm run test:uglified", - "pretest": "npm run lint", - "security": "nsp check", - "test": "npm run tests-only", - "test:corejs": "node test/corejs", - "test:uglified": "node test/uglified", - "tests-only": "node --es-staging --harmony test" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.7" -} diff --git a/node_modules/is-generator-function/test/.eslintrc b/node_modules/is-generator-function/test/.eslintrc deleted file mode 100644 index 168cdf8..0000000 --- a/node_modules/is-generator-function/test/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "rules": { - "max-statements-per-line": [2, { "max": 2 }] - } -} diff --git a/node_modules/is-generator-function/test/corejs.js b/node_modules/is-generator-function/test/corejs.js deleted file mode 100644 index 73f0c89..0000000 --- a/node_modules/is-generator-function/test/corejs.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -require('core-js'); - -require('./'); diff --git a/node_modules/is-generator-function/test/index.js b/node_modules/is-generator-function/test/index.js deleted file mode 100644 index a33cc2b..0000000 --- a/node_modules/is-generator-function/test/index.js +++ /dev/null @@ -1,94 +0,0 @@ -'use strict'; - -/* globals window */ - -var test = require('tape'); -var isGeneratorFunction = require('../index'); -var generatorFunc = require('make-generator-function'); -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -var forEach = function (arr, func) { - var i; - for (i = 0; i < arr.length; ++i) { - func(arr[i], i, arr); - } -}; - -test('returns false for non-functions', function (t) { - var nonFuncs = [ - true, - false, - null, - undefined, - {}, - [], - /a/g, - 'string', - 42, - new Date() - ]; - t.plan(nonFuncs.length); - forEach(nonFuncs, function (nonFunc) { - t.notOk(isGeneratorFunction(nonFunc), nonFunc + ' is not a function'); - }); - t.end(); -}); - -test('returns false for non-generator functions', function (t) { - var func = function () {}; - t.notOk(isGeneratorFunction(func), 'anonymous function is not an generator function'); - - var namedFunc = function foo() {}; - t.notOk(isGeneratorFunction(namedFunc), 'named function is not an generator function'); - - if (typeof window === 'undefined') { - t.skip('window.alert is not an generator function'); - } else { - t.notOk(isGeneratorFunction(window.alert), 'window.alert is not an generator function'); - } - t.end(); -}); - -test('returns false for non-generator function with faked toString', function (t) { - var func = function () {}; - func.toString = function () { return 'function* () { return "TOTALLY REAL I SWEAR!"; }'; }; - - t.notEqual(String(func), Function.prototype.toString.apply(func), 'faked toString is not real toString'); - t.notOk(isGeneratorFunction(func), 'anonymous function with faked toString is not a generator function'); - t.end(); -}); - -test('returns false for non-generator function with faked @@toStringTag', { skip: !hasToStringTag }, function (t) { - var fakeGenFunction = { - toString: function () { return String(generatorFunc); }, - valueOf: function () { return generatorFunc; } - }; - fakeGenFunction[Symbol.toStringTag] = 'GeneratorFunction'; - t.notOk(isGeneratorFunction(fakeGenFunction), 'fake GeneratorFunction with @@toStringTag "GeneratorFunction" is not a generator function'); - t.end(); -}); - -test('returns true for generator functions', function (t) { - if (generatorFunc) { - t.ok(isGeneratorFunction(generatorFunc), 'generator function is generator function'); - } else { - t.skip('generator function is generator function - this environment does not support ES6 generator functions. Please run `node --harmony`, or use a supporting browser.'); - } - t.end(); -}); - -test('concise methods', { skip: !generatorFunc || !generatorFunc.concise }, function (t) { - t.test('returns true for concise generator methods', function (st) { - st.ok(isGeneratorFunction(generatorFunc.concise), 'concise generator method is generator function'); - st.end(); - }); - - t.test('returns false for concise non-generator methods', function (st) { - var conciseMethod = Function('return { concise() {} }.concise;')(); - st.equal(typeof conciseMethod, 'function', 'assert: concise method exists'); - st.notOk(isGeneratorFunction(conciseMethod), 'concise non-generator method is not generator function'); - st.end(); - }); - - t.end(); -}); diff --git a/node_modules/is-generator-function/test/uglified.js b/node_modules/is-generator-function/test/uglified.js deleted file mode 100644 index fd82b55..0000000 --- a/node_modules/is-generator-function/test/uglified.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -require('uglify-register/api').register({ - exclude: [/\/node_modules\//, /\/test\//], - uglify: { mangle: true } -}); - -require('./'); diff --git a/node_modules/is-nan/.eslintrc b/node_modules/is-nan/.eslintrc deleted file mode 100644 index 3b5d9e9..0000000 --- a/node_modules/is-nan/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", -} diff --git a/node_modules/is-nan/.github/FUNDING.yml b/node_modules/is-nan/.github/FUNDING.yml deleted file mode 100644 index 0b42d4a..0000000 --- a/node_modules/is-nan/.github/FUNDING.yml +++ /dev/null @@ -1,12 +0,0 @@ -# These are supported funding model platforms - -github: [ljharb] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: npm/is-nan -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-nan/.github/workflows/rebase.yml b/node_modules/is-nan/.github/workflows/rebase.yml deleted file mode 100644 index 436cb79..0000000 --- a/node_modules/is-nan/.github/workflows/rebase.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Automatic Rebase - -on: [pull_request] - -jobs: - _: - name: "Automatic Rebase" - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v1 - - uses: ljharb/rebase@master - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/node_modules/is-nan/.travis.yml b/node_modules/is-nan/.travis.yml deleted file mode 100644 index 2d1c1d2..0000000 --- a/node_modules/is-nan/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -version: ~> 1.0 -language: node_js -os: - - linux -import: - - ljharb/travis-ci:node/all.yml - - ljharb/travis-ci:node/pretest.yml - - ljharb/travis-ci:node/posttest.yml - - ljharb/travis-ci:node/coverage.yml -matrix: - allow_failures: - - env: COVERAGE=true diff --git a/node_modules/is-nan/CHANGELOG.md b/node_modules/is-nan/CHANGELOG.md deleted file mode 100644 index c906867..0000000 --- a/node_modules/is-nan/CHANGELOG.md +++ /dev/null @@ -1,42 +0,0 @@ -1.3.0 / 2019-12-15 -================= - * [New] add "auto" entry point - * [readme] fix repo URLs - * [docs] clean up README links/formatting - * [Deps] update `define-properties` - * [meta] add `funding` field; FUNDING.yml - * [meta] Only apps should have lockfiles - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `es5-shim`, `tape`, `@es-shims/api` - * [Tests] use shared travis-ci configs - * [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops - * [Tests] use `functions-have-names` - * [Tests] remove `jscs` - * [actions] add automatic rebasing / merge commit blocking - -1.2.1 / 2015-08-16 -================= - * [Docs] Update readme - -1.2.0 / 2015-08-16 -================= - * [New] Implement the [es-shim API](es-shims/api) interface - * [Dev Deps] update `eslint`, `tape`, `es5-shim`, `@ljharb/eslint-config` - * [Tests] up to `io.js` `v3.0` - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - * [Security] Add `npm run security` - -1.1.0 / 2015-06-24 -================= - * Add a "shim" method - * Add `npm run eslint` - * Test latest `node` and `io.js` on `travis-ci` - * Add license and download badges to README - * Update `tape`, `covert`, `jscs` - -1.0.1 / 2014-07-05 -================= - * Oops, jscs should be a devDependency - -1.0.0 / 2014-07-05 -================= - * Initial release. diff --git a/node_modules/is-nan/LICENSE b/node_modules/is-nan/LICENSE deleted file mode 100644 index 47b7b50..0000000 --- a/node_modules/is-nan/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Jordan Harband - -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/is-nan/README.md b/node_modules/is-nan/README.md deleted file mode 100644 index d53b67e..0000000 --- a/node_modules/is-nan/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# is-nan [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -ES2015-compliant shim for Number.isNaN - the global isNaN returns false positives. - -This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan). - -## Example - -```js -Number.isNaN = require('is-nan'); -var assert = require('assert'); - -assert.notOk(Number.isNaN(undefined)); -assert.notOk(Number.isNaN(null)); -assert.notOk(Number.isNaN(false)); -assert.notOk(Number.isNaN(true)); -assert.notOk(Number.isNaN(0)); -assert.notOk(Number.isNaN(42)); -assert.notOk(Number.isNaN(Infinity)); -assert.notOk(Number.isNaN(-Infinity)); -assert.notOk(Number.isNaN('foo')); -assert.notOk(Number.isNaN(function () {})); -assert.notOk(Number.isNaN([])); -assert.notOk(Number.isNaN({})); - -assert.ok(Number.isNaN(NaN)); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-nan -[2]: http://versionbadg.es/es-shims/is-nan.svg -[3]: https://travis-ci.org/es-shims/is-nan.svg -[4]: https://travis-ci.org/es-shims/is-nan -[5]: https://david-dm.org/es-shims/is-nan.svg -[6]: https://david-dm.org/es-shims/is-nan -[7]: https://david-dm.org/es-shims/is-nan/dev-status.svg -[8]: https://david-dm.org/es-shims/is-nan#info=devDependencies -[11]: https://nodei.co/npm/is-nan.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-nan.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-nan.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-nan diff --git a/node_modules/is-nan/auto.js b/node_modules/is-nan/auto.js deleted file mode 100644 index 8ebf606..0000000 --- a/node_modules/is-nan/auto.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -require('./shim')(); diff --git a/node_modules/is-nan/implementation.js b/node_modules/is-nan/implementation.js deleted file mode 100644 index 6200b6b..0000000 --- a/node_modules/is-nan/implementation.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ - -module.exports = function isNaN(value) { - return value !== value; -}; diff --git a/node_modules/is-nan/index.js b/node_modules/is-nan/index.js deleted file mode 100644 index 709ed0d..0000000 --- a/node_modules/is-nan/index.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var define = require('define-properties'); - -var implementation = require('./implementation'); -var getPolyfill = require('./polyfill'); -var shim = require('./shim'); - -var polyfill = getPolyfill(); - -/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ - -define(polyfill, { - getPolyfill: getPolyfill, - implementation: implementation, - shim: shim -}); - -module.exports = polyfill; diff --git a/node_modules/is-nan/package.json b/node_modules/is-nan/package.json deleted file mode 100644 index e09814c..0000000 --- a/node_modules/is-nan/package.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "_from": "is-nan@^1.2.1", - "_id": "is-nan@1.3.0", - "_inBundle": false, - "_integrity": "sha512-z7bbREymOqt2CCaZVly8aC4ML3Xhfi0ekuOnjO2L8vKdl+CttdVoGZQhd4adMFAsxQ5VeRVwORs4tU8RH+HFtQ==", - "_location": "/is-nan", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-nan@^1.2.1", - "name": "is-nan", - "escapedName": "is-nan", - "rawSpec": "^1.2.1", - "saveSpec": null, - "fetchSpec": "^1.2.1" - }, - "_requiredBy": [ - "/assert" - ], - "_resolved": "https://registry.npmjs.org/is-nan/-/is-nan-1.3.0.tgz", - "_shasum": "85d1f5482f7051c2019f5673ccebdb06f3b0db03", - "_spec": "is-nan@^1.2.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/assert", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/es-shims/is-nan/issues" - }, - "bundleDependencies": false, - "dependencies": { - "define-properties": "^1.1.3" - }, - "deprecated": false, - "description": "ES2015-compliant shim for Number.isNaN - the global isNaN returns false positives.", - "devDependencies": { - "@es-shims/api": "^2.1.2", - "@ljharb/eslint-config": "^15.0.2", - "covert": "^1.1.1", - "es5-shim": "^4.5.13", - "eslint": "^6.7.2", - "functions-have-names": "^1.2.0", - "tape": "^4.11.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "homepage": "https://github.com/es-shims/is-nan", - "keywords": [ - "is", - "NaN", - "not a number", - "number", - "isNaN", - "ES6", - "ES2015", - "shim", - "polyfill", - "es-shim API" - ], - "license": "MIT", - "main": "index.js", - "name": "is-nan", - "repository": { - "type": "git", - "url": "git://github.com/es-shims/is-nan.git" - }, - "scripts": { - "coverage": "covert test/*.js", - "lint": "eslint .", - "posttest": "npx aud", - "pretest": "npm run lint && es-shim-api", - "test": "npm run tests-only", - "test:function": "node test/index", - "test:shimmed": "node test/shimmed", - "tests-only": "npm run test:function && npm run --silent test:shimmed" - }, - "testling": { - "files": "test.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..12.0", - "opera/15.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.3.0" -} diff --git a/node_modules/is-nan/polyfill.js b/node_modules/is-nan/polyfill.js deleted file mode 100644 index 2fa5886..0000000 --- a/node_modules/is-nan/polyfill.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = function getPolyfill() { - if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN('a')) { - return Number.isNaN; - } - return implementation; -}; diff --git a/node_modules/is-nan/shim.js b/node_modules/is-nan/shim.js deleted file mode 100644 index 05dbaf9..0000000 --- a/node_modules/is-nan/shim.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var define = require('define-properties'); -var getPolyfill = require('./polyfill'); - -/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ - -module.exports = function shimNumberIsNaN() { - var polyfill = getPolyfill(); - define(Number, { isNaN: polyfill }, { - isNaN: function testIsNaN() { - return Number.isNaN !== polyfill; - } - }); - return polyfill; -}; diff --git a/node_modules/is-nan/test/index.js b/node_modules/is-nan/test/index.js deleted file mode 100644 index f55aba9..0000000 --- a/node_modules/is-nan/test/index.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var numberIsNaN = require('../'); -var test = require('tape'); -var runTests = require('./tests'); - -test('as a function', function (t) { - runTests(numberIsNaN, t); - - t.end(); -}); diff --git a/node_modules/is-nan/test/shimmed.js b/node_modules/is-nan/test/shimmed.js deleted file mode 100644 index 66a5400..0000000 --- a/node_modules/is-nan/test/shimmed.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -require('es5-shim'); - -var numberIsNaN = require('../'); -numberIsNaN.shim(); - -var test = require('tape'); -var defineProperties = require('define-properties'); -var isEnumerable = Object.prototype.propertyIsEnumerable; -var functionsHaveNames = require('functions-have-names')(); - -var runTests = require('./tests'); - -test('shimmed', function (t) { - t.equal(Number.isNaN.length, 1, 'Number.isNaN has a length of 1'); - t.test('Function name', { skip: !functionsHaveNames }, function (st) { - st.equal(Number.isNaN.name, 'isNaN', 'Number.isNaN has name "isNaN"'); - st.end(); - }); - - t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { - et.equal(false, isEnumerable.call(Number, 'isNaN'), 'Number.isNaN is not enumerable'); - et.end(); - }); - - runTests(Number.isNaN, t); - - t.end(); -}); diff --git a/node_modules/is-nan/test/tests.js b/node_modules/is-nan/test/tests.js deleted file mode 100644 index cd6a500..0000000 --- a/node_modules/is-nan/test/tests.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -module.exports = function (numberIsNaN, t) { - t.test('not NaN', function (st) { - st.test('primitives', function (sst) { - sst.notOk(numberIsNaN(), 'undefined is not NaN'); - sst.notOk(numberIsNaN(null), 'null is not NaN'); - sst.notOk(numberIsNaN(false), 'false is not NaN'); - sst.notOk(numberIsNaN(true), 'true is not NaN'); - sst.notOk(numberIsNaN(0), 'positive zero is not NaN'); - sst.notOk(numberIsNaN(Infinity), 'Infinity is not NaN'); - sst.notOk(numberIsNaN(-Infinity), '-Infinity is not NaN'); - sst.notOk(numberIsNaN('foo'), 'string is not NaN'); - sst.notOk(numberIsNaN('NaN'), 'string NaN is not NaN'); - sst.end(); - }); - - st.notOk(numberIsNaN([]), 'array is not NaN'); - st.notOk(numberIsNaN({}), 'object is not NaN'); - st.notOk(numberIsNaN(function () {}), 'function is not NaN'); - - st.test('valueOf', function (vt) { - var obj = { - valueOf: function () { - return NaN; - } - }; - vt.ok(numberIsNaN(Number(obj)), 'object with valueOf of NaN, converted to Number, is NaN'); - vt.notOk(numberIsNaN(obj), 'object with valueOf of NaN is not NaN'); - vt.end(); - }); - - st.end(); - }); - - t.test('NaN literal', function (st) { - st.ok(numberIsNaN(NaN), 'NaN is NaN'); - st.end(); - }); -}; diff --git a/node_modules/is-regex/.eslintrc b/node_modules/is-regex/.eslintrc deleted file mode 100644 index fbb8e9d..0000000 --- a/node_modules/is-regex/.eslintrc +++ /dev/null @@ -1,9 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "id-length": [1] - } -} diff --git a/node_modules/is-regex/.github/workflows/rebase.yml b/node_modules/is-regex/.github/workflows/rebase.yml deleted file mode 100644 index 436cb79..0000000 --- a/node_modules/is-regex/.github/workflows/rebase.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Automatic Rebase - -on: [pull_request] - -jobs: - _: - name: "Automatic Rebase" - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v1 - - uses: ljharb/rebase@master - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/node_modules/is-regex/.travis.yml b/node_modules/is-regex/.travis.yml deleted file mode 100644 index 2d1c1d2..0000000 --- a/node_modules/is-regex/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -version: ~> 1.0 -language: node_js -os: - - linux -import: - - ljharb/travis-ci:node/all.yml - - ljharb/travis-ci:node/pretest.yml - - ljharb/travis-ci:node/posttest.yml - - ljharb/travis-ci:node/coverage.yml -matrix: - allow_failures: - - env: COVERAGE=true diff --git a/node_modules/is-regex/CHANGELOG.md b/node_modules/is-regex/CHANGELOG.md deleted file mode 100644 index c82d889..0000000 --- a/node_modules/is-regex/CHANGELOG.md +++ /dev/null @@ -1,148 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). - -## [v1.0.5](https://github.com/inspect-js/is-regex/compare/v1.0.4...v1.0.5) - 2019-12-15 - -### Commits - -- [Tests] use shared travis-ci configs [`af728b2`](https://github.com/inspect-js/is-regex/commit/af728b21c5cc9e41234fb4015594bffdcfff597c) -- [Tests] remove `jscs` [`1b8cfe8`](https://github.com/inspect-js/is-regex/commit/1b8cfe8cfb14820c196775f19d370276e4034791) -- [meta] add `auto-changelog` [`c3131d8`](https://github.com/inspect-js/is-regex/commit/c3131d8ab5d06ea5fa05a4bb2ad28bbfb81668ad) -- [Tests] up to `node` `v8.1`, `v7.10`, `v6.11`, `v4.8`; newer npm fails on older nodes [`660b658`](https://github.com/inspect-js/is-regex/commit/660b6585d1a9607dbdae879b70ce2f6a5684616c) -- [Tests] up to `node` `v9.3`, `v8.9`, `v6.12`; use `nvm install-latest-npm`; pin included builds to LTS [`7c25218`](https://github.com/inspect-js/is-regex/commit/7c25218d540ab17c18e4ae333677c5725806a778) -- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`fa95547`](https://github.com/inspect-js/is-regex/commit/fa955478950a5ba0a920010d5daaa29487500b30) -- [meta] remove unused Makefile and associated utilities [`9fd2a29`](https://github.com/inspect-js/is-regex/commit/9fd2a29dc57ed125f3d61e94f6254a9dd8ee0044) -- [Tests] up to `node` `v11.3`, `v10.14`, `v8.14`, `v6.15` [`7f2ac41`](https://github.com/inspect-js/is-regex/commit/7f2ac41ef5dc4d53bfe2fb1c24486c688a2537bd) -- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9` [`6fa2b0f`](https://github.com/inspect-js/is-regex/commit/6fa2b0fe171a5b02086a06679a92d989e83a8b8e) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`697e1de`](https://github.com/inspect-js/is-regex/commit/697e1de1c9e69f08e591cc0040d81fdbbde6fe4e) -- [actions] add automatic rebasing / merge commit blocking [`ad86dc9`](https://github.com/inspect-js/is-regex/commit/ad86dc97a52e4f66fbfb3b8c9c78da3963588b54) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `jscs`, `nsp`, `replace`, `semver`, `tape` [`5c99c8e`](https://github.com/inspect-js/is-regex/commit/5c99c8e384d5ce2ef434be5853c301477cf35456) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `replace`, `semver`, `tape` [`bb63686`](https://github.com/inspect-js/is-regex/commit/bb63686a9d0fc586d121549cf484da95edec3b0a) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config@`, `replace`, `semver`, `tape` [`ddf3670`](https://github.com/inspect-js/is-regex/commit/ddf36705e5f7bd29832721e4a23abf06195032c6) -- [Dev Deps] update `tape`, `nsp`, `eslint`, `@ljharb/eslint-config` [`e7b5a62`](https://github.com/inspect-js/is-regex/commit/e7b5a626eef3b9648c7d52d4620ce2e2a98a9ab8) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` [`c803db5`](https://github.com/inspect-js/is-regex/commit/c803db5cd94cf9e0a559617adbc1e4c9d22007ff) -- [Tests] switch from `nsp` to `npm audit` [`b7239be`](https://github.com/inspect-js/is-regex/commit/b7239be9da263a0f7066f79d087eaf700a9613e9) -- [Dev Deps] update `eslint`, `nsp`, `semver`, `tape` [`347ee6c`](https://github.com/inspect-js/is-regex/commit/347ee6c67ba0f56b03f21a5abe743658f6515963) -- Only apps should have lockfiles. [`3866575`](https://github.com/inspect-js/is-regex/commit/38665755ecf028061f15816059e26023890a0dc7) -- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`d099a39`](https://github.com/inspect-js/is-regex/commit/d099a3943eb7e156a3e64fb8b74e11d7c83a4bec) -- [meta] add `funding` field [`741aecd`](https://github.com/inspect-js/is-regex/commit/741aecd92cd49868b3606c8cc99ce299e5f3c7d5) -- [Tests] use `eclint` instead of `editorconfig-tools` [`bc6aa75`](https://github.com/inspect-js/is-regex/commit/bc6aa7539e506788709b96f7bf3d7549850a81c3) -- [Tests] on `node` `v10.1` [`262226f`](https://github.com/inspect-js/is-regex/commit/262226f08fa34dff9a8dffd16daabb3dc6e262eb) -- [Dev Deps] update `eslint` [`31fd719`](https://github.com/inspect-js/is-regex/commit/31fd719dd59a6111ca710cdb0d19a8adadf9b8c6) -- [Deps] update `has` [`e9e25a3`](https://github.com/inspect-js/is-regex/commit/e9e25a3de7e89faaa6aadf5010477074140e8218) -- [Dev Deps] update `replace` [`aeeb968`](https://github.com/inspect-js/is-regex/commit/aeeb968bf5a4fc07f0fa6905f2c699fc563b6c32) -- [Tests] set audit level [`2a6290e`](https://github.com/inspect-js/is-regex/commit/2a6290e78b58bf14b734d7998fe53b4a84db5e44) -- [Tests] remove `nsp` [`fc74c2b`](https://github.com/inspect-js/is-regex/commit/fc74c2bb6970a7f3280abe6eff3b492d77d89c9f) - -## [v1.0.4](https://github.com/inspect-js/is-regex/compare/v1.0.3...v1.0.4) - 2017-02-18 - -### Fixed - -- [Fix] ensure that `lastIndex` is not mutated [`#3`](https://github.com/inspect-js/is-regex/issues/3) - -### Commits - -- Update `eslint`, `tape`, `semver`; use my personal shared `eslint` config [`c4a41c3`](https://github.com/inspect-js/is-regex/commit/c4a41c3a8203a3919b01cd0d1b577daadf30a452) -- [Tests] on all node minors; improve test matrix [`58d7508`](https://github.com/inspect-js/is-regex/commit/58d7508a36eb92bd76717486b9e78bde502ffe3e) -- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` [`7290076`](https://github.com/inspect-js/is-regex/commit/729007606e9ed162953d1f5812c37eb06c554ec2) -- Update `covert`, `jscs`, `eslint`, `semver` [`dabc729`](https://github.com/inspect-js/is-regex/commit/dabc729cfc4458264c6f7642004d41dd5c214bfd) -- Update `eslint` [`a946b05`](https://github.com/inspect-js/is-regex/commit/a946b051159396b4311c564880f96e3d00e8b8e2) -- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`1744dde`](https://github.com/inspect-js/is-regex/commit/1744dde77526841f216fa2c1c866c5a82b1638c0) -- [Refactor] when try/catch is needed, bail early if the value lacks an own `lastIndex` data property. [`288ad93`](https://github.com/inspect-js/is-regex/commit/288ad93dbfed9f6828de20de67105ee6d6504425) -- Update `editorconfig-tools`, `eslint`, `semver`, `replace` [`4d895c6`](https://github.com/inspect-js/is-regex/commit/4d895c68a0cdbb5803185928963c15147aad0404) -- Update `eslint`, `tape`, `semver` [`f387f03`](https://github.com/inspect-js/is-regex/commit/f387f03b260b56372bfca301d4e79c4067633854) -- All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. [`55e480f`](https://github.com/inspect-js/is-regex/commit/55e480f407cafb6c21a6c32aef04ccaa3ba4216c) -- [Dev Deps] update `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` [`89d9528`](https://github.com/inspect-js/is-regex/commit/89d95285b364913ebcd8ac7e0872570fe009a5d3) -- [Dev Deps] update `jscs` [`eb222a8`](https://github.com/inspect-js/is-regex/commit/eb222a8435e59909354f3700fd4880e4ce1cb13e) -- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`c65429c`](https://github.com/inspect-js/is-regex/commit/c65429cea0366508c10ad2ab773af7b83a34fc81) -- Update `nsp`, `eslint` [`c60fbd8`](https://github.com/inspect-js/is-regex/commit/c60fbd8680f7fb3508ec3c5be8ebb788672516c8) -- Update `eslint`, `semver` [`6a62116`](https://github.com/inspect-js/is-regex/commit/6a621168c63616bf004ca8b1f885b4eb8a58a3e5) -- [Tests] on `node` `v7.5`, `v4.7` [`e764651`](https://github.com/inspect-js/is-regex/commit/e764651336f5da5e239e9fe8869f3a3201c19d2b) -- Test up to `io.js` `v2.1` [`3bf326a`](https://github.com/inspect-js/is-regex/commit/3bf326a9bcd530fd16c9fc806e249a68e25ab7e3) -- Test on the latest `io.js` versions. [`693d047`](https://github.com/inspect-js/is-regex/commit/693d0477631c5d7671f6c99eca5594ffffa75771) -- [Refactor] use an early return instead of a ternary. [`31eaca2`](https://github.com/inspect-js/is-regex/commit/31eaca28b7d0aaac0599fe7a569b93b842f8ab16) -- Test on `io.js` `v2.2` [`c18c55a`](https://github.com/inspect-js/is-regex/commit/c18c55aee6358d70531f935e98851e42b698d93c) -- Run `travis-ci` tests on `iojs` and `node` v0.12; speed up builds; allow 0.8 failures. [`a1c237d`](https://github.com/inspect-js/is-regex/commit/a1c237d35f880fe0bcbc9275254611a6a2300aaf) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`aa3ea0f`](https://github.com/inspect-js/is-regex/commit/aa3ea0f148af31d75f7ef8a800412729d82def04) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config` [`d97831d`](https://github.com/inspect-js/is-regex/commit/d97831d0e2ccd3d00d1f7354b7f81e2575f90953) -- [Dev Deps] Update `tape`, `eslint` [`95e6def`](https://github.com/inspect-js/is-regex/commit/95e6defe3178c45dc9df16e474e558979d5f5c05) -- Update `eslint`, `nsp` [`3844c93`](https://github.com/inspect-js/is-regex/commit/3844c935cfe7c52fae0dc74d27e884c417cb4616) -- Update `tape`, `jscs` [`0d6dac8`](https://github.com/inspect-js/is-regex/commit/0d6dac818ed251910171965932f021291919e770) -- Fix tests for faked @@toStringTag [`2ebef9f`](https://github.com/inspect-js/is-regex/commit/2ebef9f0759843e9a063de7a512b46e3e7daea7e) -- Test up to `io.js` `v3.0` [`ec1d2d4`](https://github.com/inspect-js/is-regex/commit/ec1d2d44481fa0fa11448527da8030c99fe47a12) -- [Refactor] bail earlier when the value is falsy. [`a9e333e`](https://github.com/inspect-js/is-regex/commit/a9e333e2ac8912ca05b7e31d30e4eea683c0da4b) -- [Dev Deps] update `tape` [`8cdcaae`](https://github.com/inspect-js/is-regex/commit/8cdcaae07be8c790cdb99849e6076ea7702a4c84) -- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`281c4ef`](https://github.com/inspect-js/is-regex/commit/281c4efeb71c86dd380e741bcaee3f7dbf956151) -- Test on `io.js` `v2.4` [`4d54c68`](https://github.com/inspect-js/is-regex/commit/4d54c68a81b5332a3b76259d8aa8f514be5efd13) -- Test on `io.js` `v2.3` [`23170f5`](https://github.com/inspect-js/is-regex/commit/23170f5cae632d0377de73bd2febc53db8aebbc9) -- Test on `iojs-v1.6` [`4487ad0`](https://github.com/inspect-js/is-regex/commit/4487ad0194a5684223bfa2690da4e0a441f7132a) - -## [v1.0.3](https://github.com/inspect-js/is-regex/compare/v1.0.2...v1.0.3) - 2015-01-30 - -### Commits - -- Update npm run scripts. [`dc528dd`](https://github.com/inspect-js/is-regex/commit/dc528dd25e775089bc0a3f5a8f7ae7ffc4cdf52a) -- Add toStringTag tests. [`f48a83a`](https://github.com/inspect-js/is-regex/commit/f48a83a78720b78ab60ca586c16f6f3dbcfec825) -- If @@toStringTag is not present, use the old-school Object#toString test. [`50b0ffd`](https://github.com/inspect-js/is-regex/commit/50b0ffd9c7fdbd54aee8cde1b07e680ae84f6a0d) - -## [v1.0.2](https://github.com/inspect-js/is-regex/compare/v1.0.1...v1.0.2) - 2015-01-29 - -### Commits - -- `make release` [`a1de7ec`](https://github.com/inspect-js/is-regex/commit/a1de7eca4cecc8015fd27804669f8fc61bd16a68) -- Improve optimization by separating the try/catch, and bailing out early when not typeof "object". [`5ab7632`](https://github.com/inspect-js/is-regex/commit/5ab76322a348487fa8b16761e83f6824c3c27d11) - -## [v1.0.1](https://github.com/inspect-js/is-regex/compare/v1.0.0...v1.0.1) - 2015-01-28 - -### Commits - -- Using my standard jscs.json file [`1f1733a`](https://github.com/inspect-js/is-regex/commit/1f1733ac8433cdcceb25356f86b74136a4477cb9) -- Adding `npm run lint` [`51ea70f`](https://github.com/inspect-js/is-regex/commit/51ea70fa7e461d022f611c195f343ea8d0333d71) -- Use RegExp#exec to test if something is a regex, which works even with ES6 @@toStringTag. [`042c8c7`](https://github.com/inspect-js/is-regex/commit/042c8c734faade9015932b61f1e8ea4f3a93b1b3) -- Adding license and downloads badges [`366d619`](https://github.com/inspect-js/is-regex/commit/366d61965d3a4119126e78e09b2166bbcddd0c5a) -- Use SVG badges instead of PNG [`6a32e4f`](https://github.com/inspect-js/is-regex/commit/6a32e4fc87d7d3a3787b800dd033c9293aead6df) -- Update `tape`, `jscs` [`f1b9462`](https://github.com/inspect-js/is-regex/commit/f1b9462f86d1b69de07176e7f277f668757ba964) -- Update `jscs` [`1bff23f`](https://github.com/inspect-js/is-regex/commit/1bff23ff0fe88c8263e8bf04cf99e290af96d5b0) -- Update `tape`, `jscs` [`c22ea2e`](https://github.com/inspect-js/is-regex/commit/c22ea2e7967f45618deed01ff5ea483f918be216) -- Update `tape`, `jscs` [`b0479db`](https://github.com/inspect-js/is-regex/commit/b0479db99a1b1b872d1618fb0a71f0c74a78b29b) -- Use consistent quotes [`1a6e347`](https://github.com/inspect-js/is-regex/commit/1a6e34730d9270f3f20519139faa4c4e6ec2e1f5) -- Make travis builds faster. [`090a4ea`](https://github.com/inspect-js/is-regex/commit/090a4ea7c5fa709d108d596e3bc304e6ce973dec) -- Update `tape` [`7d76129`](https://github.com/inspect-js/is-regex/commit/7d7612928bdd43230fbd835db71797249ca24f35) -- Lock covert to v1.0.0. [`9a90b03`](https://github.com/inspect-js/is-regex/commit/9a90b03fb390e66f874223a34c58ba2bb109edd3) -- Updating tape [`bfbc7f5`](https://github.com/inspect-js/is-regex/commit/bfbc7f593a007acd0411152bbb55f724dc4ca935) -- Updating jscs [`13ad511`](https://github.com/inspect-js/is-regex/commit/13ad511d80cd67300c2c0c5387fc4b3b423e2768) -- Updating jscs [`cda1945`](https://github.com/inspect-js/is-regex/commit/cda1945d603dfe99e24d5a909a931d366451bc4d) -- Updating jscs [`de96c99`](https://github.com/inspect-js/is-regex/commit/de96c99d4bf5787df671de6df9138b6547a6545b) -- Running linter as part of tests [`2cb6567`](https://github.com/inspect-js/is-regex/commit/2cb656733b1ed0af14ad11fb584006d22de0c69d) -- Updating covert [`a56ae74`](https://github.com/inspect-js/is-regex/commit/a56ae74ec8d5f0473295a8b10519a18580f16624) -- Updating tape [`ffe47f7`](https://github.com/inspect-js/is-regex/commit/ffe47f7fe9cf6d16896b4bdc286bd1d0805d5c49) - -## [v1.0.0](https://github.com/inspect-js/is-regex/compare/v0.0.0...v1.0.0) - 2014-05-19 - -### Commits - -- Make sure old and unstable nodes don't break Travis [`05da747`](https://github.com/inspect-js/is-regex/commit/05da7478f960dc131ec3ad864e27e8c6b7d74a80) -- toString is a reserved var name in old Opera [`885c48c`](https://github.com/inspect-js/is-regex/commit/885c48c120f921a55f1842b0607d3e7875379821) -- Updating deps [`2ca0e79`](https://github.com/inspect-js/is-regex/commit/2ca0e79a2443ca34d85e8b2ea2e26f55855b74a7) -- Updating tape. [`9678435`](https://github.com/inspect-js/is-regex/commit/96784355611deb0c23b9064be774216d76e3e457) -- Updating covert [`c3bb898`](https://github.com/inspect-js/is-regex/commit/c3bb8985a422e3e0c81f9c43899b6c19a72c755f) -- Updating tape [`7811708`](https://github.com/inspect-js/is-regex/commit/78117089688258b8f939b397b37897b5b3e30f74) -- Testing on node 0.6 again [`dec36ae`](https://github.com/inspect-js/is-regex/commit/dec36ae58a39a3f80e832b702c3e19406363c160) -- Run code coverage as part of tests [`e6f4ebe`](https://github.com/inspect-js/is-regex/commit/e6f4ebec26894543747603f2cb360e839f2ca290) - -## v0.0.0 - 2014-01-15 - -### Commits - -- package.json [`aa60d43`](https://github.com/inspect-js/is-regex/commit/aa60d43d2c8adb9fdd47f5898e5e1e570bd238d8) -- read me [`861e944`](https://github.com/inspect-js/is-regex/commit/861e944de88e84010eaa662ea9ea9f17c90cff8c) -- Initial commit [`d0cdd71`](https://github.com/inspect-js/is-regex/commit/d0cdd71a637d8490b7ee3eaaf75c7e31d0f9242f) -- Tests. [`b533f74`](https://github.com/inspect-js/is-regex/commit/b533f741a88dff002790fb7af054b2a74e72d4da) -- Implementation. [`3c9a8c0`](https://github.com/inspect-js/is-regex/commit/3c9a8c06994003cdfffeb3620f251f4c4cae7755) -- Travis CI [`742c440`](https://github.com/inspect-js/is-regex/commit/742c4407015f9108875fd108fde137f5245e9e7a) diff --git a/node_modules/is-regex/LICENSE b/node_modules/is-regex/LICENSE deleted file mode 100644 index 47b7b50..0000000 --- a/node_modules/is-regex/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Jordan Harband - -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/is-regex/README.md b/node_modules/is-regex/README.md deleted file mode 100644 index 05baa0e..0000000 --- a/node_modules/is-regex/README.md +++ /dev/null @@ -1,54 +0,0 @@ -#is-regex [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -Is this value a JS regex? -This module works cross-realm/iframe, and despite ES6 @@toStringTag. - -## Example - -```js -var isRegex = require('is-regex'); -var assert = require('assert'); - -assert.notOk(isRegex(undefined)); -assert.notOk(isRegex(null)); -assert.notOk(isRegex(false)); -assert.notOk(isRegex(true)); -assert.notOk(isRegex(42)); -assert.notOk(isRegex('foo')); -assert.notOk(isRegex(function () {})); -assert.notOk(isRegex([])); -assert.notOk(isRegex({})); - -assert.ok(isRegex(/a/g)); -assert.ok(isRegex(new RegExp('a', 'g'))); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-regex -[2]: http://versionbadg.es/ljharb/is-regex.svg -[3]: https://travis-ci.org/ljharb/is-regex.svg -[4]: https://travis-ci.org/ljharb/is-regex -[5]: https://david-dm.org/ljharb/is-regex.svg -[6]: https://david-dm.org/ljharb/is-regex -[7]: https://david-dm.org/ljharb/is-regex/dev-status.svg -[8]: https://david-dm.org/ljharb/is-regex#info=devDependencies -[9]: https://ci.testling.com/ljharb/is-regex.png -[10]: https://ci.testling.com/ljharb/is-regex -[11]: https://nodei.co/npm/is-regex.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-regex.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-regex.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-regex - diff --git a/node_modules/is-regex/index.js b/node_modules/is-regex/index.js deleted file mode 100644 index 93a5b4e..0000000 --- a/node_modules/is-regex/index.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -var has = require('has'); -var regexExec = RegExp.prototype.exec; -var gOPD = Object.getOwnPropertyDescriptor; - -var tryRegexExecCall = function tryRegexExec(value) { - try { - var lastIndex = value.lastIndex; - value.lastIndex = 0; // eslint-disable-line no-param-reassign - - regexExec.call(value); - return true; - } catch (e) { - return false; - } finally { - value.lastIndex = lastIndex; // eslint-disable-line no-param-reassign - } -}; -var toStr = Object.prototype.toString; -var regexClass = '[object RegExp]'; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -module.exports = function isRegex(value) { - if (!value || typeof value !== 'object') { - return false; - } - if (!hasToStringTag) { - return toStr.call(value) === regexClass; - } - - var descriptor = gOPD(value, 'lastIndex'); - var hasLastIndexDataProperty = descriptor && has(descriptor, 'value'); - if (!hasLastIndexDataProperty) { - return false; - } - - return tryRegexExecCall(value); -}; diff --git a/node_modules/is-regex/package.json b/node_modules/is-regex/package.json deleted file mode 100644 index 041f1ee..0000000 --- a/node_modules/is-regex/package.json +++ /dev/null @@ -1,106 +0,0 @@ -{ - "_from": "is-regex@^1.0.5", - "_id": "is-regex@1.0.5", - "_inBundle": false, - "_integrity": "sha512-vlKW17SNq44owv5AQR3Cq0bQPEb8+kF3UKZ2fiZNOWtztYE5i0CzCZxFDwO58qAOWtxdBRVO/V5Qin1wjCqFYQ==", - "_location": "/is-regex", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-regex@^1.0.5", - "name": "is-regex", - "escapedName": "is-regex", - "rawSpec": "^1.0.5", - "saveSpec": null, - "fetchSpec": "^1.0.5" - }, - "_requiredBy": [ - "/es-abstract" - ], - "_resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.5.tgz", - "_shasum": "39d589a358bf18967f726967120b8fc1aed74eae", - "_spec": "is-regex@^1.0.5", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/es-abstract", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com" - }, - "auto-changelog": { - "output": "CHANGELOG.md", - "template": "keepachangelog", - "unreleased": false, - "commitLimit": false, - "backfillLimit": false - }, - "bugs": { - "url": "https://github.com/ljharb/is-regex/issues" - }, - "bundleDependencies": false, - "dependencies": { - "has": "^1.0.3" - }, - "deprecated": false, - "description": "Is this value a JS regex? Works cross-realm/iframe, and despite ES6 @@toStringTag", - "devDependencies": { - "@ljharb/eslint-config": "^15.0.2", - "auto-changelog": "^1.16.2", - "covert": "^1.1.1", - "eclint": "^2.8.1", - "eslint": "^6.7.2", - "tape": "^4.11.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "homepage": "https://github.com/ljharb/is-regex", - "keywords": [ - "regex", - "regexp", - "is", - "regular expression", - "regular", - "expression" - ], - "license": "MIT", - "main": "index.js", - "name": "is-regex", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/is-regex.git" - }, - "scripts": { - "coverage": "covert test/index.js", - "eccheck": "eclint check *.js **/*.js > /dev/null", - "lint": "eslint .", - "posttest": "npx aud", - "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", - "pretest": "npm run lint", - "test": "npm run tests-only", - "tests-only": "node --harmony --es-staging test", - "version": "auto-changelog && git add CHANGELOG.md" - }, - "testling": { - "files": "test.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..12.0", - "opera/15.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.5" -} diff --git a/node_modules/is-regex/test/index.js b/node_modules/is-regex/test/index.js deleted file mode 100644 index 731c789..0000000 --- a/node_modules/is-regex/test/index.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -var test = require('tape'); -var isRegex = require('..'); -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -test('not regexes', function (t) { - t.notOk(isRegex(), 'undefined is not regex'); - t.notOk(isRegex(null), 'null is not regex'); - t.notOk(isRegex(false), 'false is not regex'); - t.notOk(isRegex(true), 'true is not regex'); - t.notOk(isRegex(42), 'number is not regex'); - t.notOk(isRegex('foo'), 'string is not regex'); - t.notOk(isRegex([]), 'array is not regex'); - t.notOk(isRegex({}), 'object is not regex'); - t.notOk(isRegex(function () {}), 'function is not regex'); - t.end(); -}); - -test('@@toStringTag', { skip: !hasToStringTag }, function (t) { - var regex = /a/g; - var fakeRegex = { - toString: function () { return String(regex); }, - valueOf: function () { return regex; } - }; - fakeRegex[Symbol.toStringTag] = 'RegExp'; - t.notOk(isRegex(fakeRegex), 'fake RegExp with @@toStringTag "RegExp" is not regex'); - t.end(); -}); - -test('regexes', function (t) { - t.ok(isRegex(/a/g), 'regex literal is regex'); - t.ok(isRegex(new RegExp('a', 'g')), 'regex object is regex'); - t.end(); -}); - -test('does not mutate regexes', function (t) { - t.test('lastIndex is a marker object', function (st) { - var regex = /a/; - var marker = {}; - regex.lastIndex = marker; - st.equal(regex.lastIndex, marker, 'lastIndex is the marker object'); - st.ok(isRegex(regex), 'is regex'); - st.equal(regex.lastIndex, marker, 'lastIndex is the marker object after isRegex'); - st.end(); - }); - - t.test('lastIndex is nonzero', function (st) { - var regex = /a/; - regex.lastIndex = 3; - st.equal(regex.lastIndex, 3, 'lastIndex is 3'); - st.ok(isRegex(regex), 'is regex'); - st.equal(regex.lastIndex, 3, 'lastIndex is 3 after isRegex'); - st.end(); - }); - - t.end(); -}); diff --git a/node_modules/is-symbol/.editorconfig b/node_modules/is-symbol/.editorconfig deleted file mode 100644 index eaa2141..0000000 --- a/node_modules/is-symbol/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -root = true - -[*] -indent_style = tab; -insert_final_newline = true; -quote_type = auto; -space_after_anonymous_functions = true; -space_after_control_statements = true; -spaces_around_operators = true; -trim_trailing_whitespace = true; -spaces_in_brackets = false; -end_of_line = lf; - diff --git a/node_modules/is-symbol/.eslintrc b/node_modules/is-symbol/.eslintrc deleted file mode 100644 index 046dd07..0000000 --- a/node_modules/is-symbol/.eslintrc +++ /dev/null @@ -1,14 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "overrides": [ - { - "files": "test/**", - "rules": { - "no-restricted-properties": 0, - }, - }, - ], -} diff --git a/node_modules/is-symbol/.github/FUNDING.yml b/node_modules/is-symbol/.github/FUNDING.yml deleted file mode 100644 index a65600e..0000000 --- a/node_modules/is-symbol/.github/FUNDING.yml +++ /dev/null @@ -1,12 +0,0 @@ -# These are supported funding model platforms - -github: [ljharb] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: npm/is-symbol -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-symbol/.github/workflows/rebase.yml b/node_modules/is-symbol/.github/workflows/rebase.yml deleted file mode 100644 index 436cb79..0000000 --- a/node_modules/is-symbol/.github/workflows/rebase.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Automatic Rebase - -on: [pull_request] - -jobs: - _: - name: "Automatic Rebase" - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v1 - - uses: ljharb/rebase@master - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/node_modules/is-symbol/.nvmrc b/node_modules/is-symbol/.nvmrc deleted file mode 100644 index 64f5a0a..0000000 --- a/node_modules/is-symbol/.nvmrc +++ /dev/null @@ -1 +0,0 @@ -node diff --git a/node_modules/is-symbol/.travis.yml b/node_modules/is-symbol/.travis.yml deleted file mode 100644 index 2d1c1d2..0000000 --- a/node_modules/is-symbol/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -version: ~> 1.0 -language: node_js -os: - - linux -import: - - ljharb/travis-ci:node/all.yml - - ljharb/travis-ci:node/pretest.yml - - ljharb/travis-ci:node/posttest.yml - - ljharb/travis-ci:node/coverage.yml -matrix: - allow_failures: - - env: COVERAGE=true diff --git a/node_modules/is-symbol/CHANGELOG.md b/node_modules/is-symbol/CHANGELOG.md deleted file mode 100644 index 6c68c59..0000000 --- a/node_modules/is-symbol/CHANGELOG.md +++ /dev/null @@ -1,86 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). - -## [v1.0.3](https://github.com/inspect-js/is-symbol/compare/v1.0.2...v1.0.3) - 2019-11-21 - -### Commits - -- [Tests] use shared travis-ci configs [`034afdd`](https://github.com/inspect-js/is-symbol/commit/034afdd677c1b72b76751f3e5131acc927a32916) -- [Tests] remove `jscs` [`0c026a0`](https://github.com/inspect-js/is-symbol/commit/0c026a06815e46a33a8a5b4b1be8965d32d38e5c) -- [meta] add `auto-changelog` [`9a1776b`](https://github.com/inspect-js/is-symbol/commit/9a1776bb49f3e6ac12a5b3a447edcc651216891b) -- [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v8.16`, `v6.17` [`23a6db4`](https://github.com/inspect-js/is-symbol/commit/23a6db49a338d19eab19d876745513820bb6a9dc) -- [Tests] up to `node` `v11.7`, `v10.15`, `v8.15`, `v6.16` [`892d92e`](https://github.com/inspect-js/is-symbol/commit/892d92e7c40f3c0577583a98134106181c38bb7e) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `semver`, `tape` [`c2e6d6a`](https://github.com/inspect-js/is-symbol/commit/c2e6d6a71f839522bbd124b7419f5fc42ffff6d3) -- [readme] fix repo URLs [`655c288`](https://github.com/inspect-js/is-symbol/commit/655c288a815856e647dba4b6049b1743cec3533c) -- [actions] add automatic rebasing / merge commit blocking [`97b1229`](https://github.com/inspect-js/is-symbol/commit/97b12296bf8fa1ce0c6121bf3de56c413da10aae) -- [meta] add FUNDING.yml [`94c64a3`](https://github.com/inspect-js/is-symbol/commit/94c64a367a1c34f960cf6007fc65cfbbcba34ba3) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape`, `semver` [`71ab543`](https://github.com/inspect-js/is-symbol/commit/71ab543e09b820378362f4f66248addd410c6388) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `semver`, `tape` [`c6212f9`](https://github.com/inspect-js/is-symbol/commit/c6212f94e28622c94bb37189ffc241ee88b5b1dd) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `object-inspect` [`91bc802`](https://github.com/inspect-js/is-symbol/commit/91bc802e18e63f4e8230ee0148302ce849e2f733) -- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`8cbe69c`](https://github.com/inspect-js/is-symbol/commit/8cbe69c3fafe9cfbe7d27f710c88d02d2d2c6a00) -- [Tests] use `npm audit` instead of `nsp` [`741b51d`](https://github.com/inspect-js/is-symbol/commit/741b51dac868f6b22736c204910d257bcf4d5044) -- [meta] add `funding` field [`65b58d1`](https://github.com/inspect-js/is-symbol/commit/65b58d1e9fc572712d462d615e6b2418627d8fb9) -- [Deps] update `has-symbols` [`9cb5b2a`](https://github.com/inspect-js/is-symbol/commit/9cb5b2a9a3b89e8e0246be8df4fff3f5ceac7309) - -## [v1.0.2](https://github.com/inspect-js/is-symbol/compare/v1.0.1...v1.0.2) - 2018-09-20 - -### Commits - -- Update `eslint`, `tape`, `semver`; use my personal shared `eslint` config [`e86aaea`](https://github.com/inspect-js/is-symbol/commit/e86aaea8d81356801ecfc60540523e9b809a55f4) -- [Tests] on all node minors; improve test matrix [`50bc07f`](https://github.com/inspect-js/is-symbol/commit/50bc07f2ff73e5499b02a61f0a00ea48a84ae213) -- [Dev Deps] update `tape`, `jscs`, `nsp`, `semver`, `eslint`, `@ljharb/eslint-config` [`45e17bd`](https://github.com/inspect-js/is-symbol/commit/45e17bdf145846f30122348a94c5e506b90836ba) -- [Tests] up to `node` `v10.0`, `v9.11`, `v8.11`, `v6.14`, `v4.9`; use `nvm install-latest-npm` [`44402cb`](https://github.com/inspect-js/is-symbol/commit/44402cb82d4499e947b48b31b14667d1ebe7e2b4) -- [Tests] up to `node` `v8.1`, `v7.10`, `v6.11`, `v4.8`; improve matrix; old npm breaks on newer nodes [`9047c23`](https://github.com/inspect-js/is-symbol/commit/9047c232857ecb80551a21cc0b1cc4c91d28da1f) -- Update `tape`, `covert`, `jscs`, `semver` [`d57d1ce`](https://github.com/inspect-js/is-symbol/commit/d57d1ce3fc0b740885a1ed5c0738d4a27b29ab07) -- Add `npm run eslint` [`0d75a66`](https://github.com/inspect-js/is-symbol/commit/0d75a6638ad6f7ff7d5bc958531a6328fb13e3fe) -- Update `eslint` [`042fb3a`](https://github.com/inspect-js/is-symbol/commit/042fb3aec590f0c0d205b15812b285ad95cfff6b) -- [Refactor] use `has-symbols` and `object-inspect` [`129bc68`](https://github.com/inspect-js/is-symbol/commit/129bc68dd619b789b9956ac9b63b46257ee1060c) -- [Tests] up to `node` `v10.11`, `v8.12` [`c1822e8`](https://github.com/inspect-js/is-symbol/commit/c1822e84d6cc0cee9f1c2893e91b1aa999ad41db) -- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`089d2cf`](https://github.com/inspect-js/is-symbol/commit/089d2cf7cad87b75aa534769af11524ad2e79080) -- [Tests] up to `node` `v8.4`; newer npm breaks on older node [`05ce701`](https://github.com/inspect-js/is-symbol/commit/05ce701e3c1be8b3266ffac49806832e410491c1) -- All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. [`241e6a6`](https://github.com/inspect-js/is-symbol/commit/241e6a655c0e19e9dcf0ae88e7fddd4cde394c5c) -- Test on latest `node` and `io.js` versions. [`5c8d5de`](https://github.com/inspect-js/is-symbol/commit/5c8d5deb9b7c01a8cdf959082a3d619c19751b0a) -- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `nsp`, `semver`, `tape` [`06047bf`](https://github.com/inspect-js/is-symbol/commit/06047bf72b20a66c0b455e80856b2d00b1910391) -- [Dev Deps] update `jscs`, `nsp`, `semver`, `eslint`, `@ljharb/eslint-config` [`9d25dd7`](https://github.com/inspect-js/is-symbol/commit/9d25dd79347c89f98207a3bad39f667f1f8a410e) -- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`ce173bd`](https://github.com/inspect-js/is-symbol/commit/ce173bda6e146907e3061a0e70463107d955de35) -- Update `nsp`, `eslint` [`29e5214`](https://github.com/inspect-js/is-symbol/commit/29e52140fac2049b4a32e175787bb3b184a1dd72) -- Update `semver`, `eslint` [`53be884`](https://github.com/inspect-js/is-symbol/commit/53be884c2811f7a4452581003d9cdaf6f9bddd3c) -- [Dev Deps] update `eslint`, `nsp`, `semver`, `tape` [`3bd149c`](https://github.com/inspect-js/is-symbol/commit/3bd149c869c099b07104b06c0692755a01f8298c) -- [Dev Deps] update `jscs` [`69b4231`](https://github.com/inspect-js/is-symbol/commit/69b4231632b170e5ddb350db2f0c59e6cad6f548) -- Test up to `io.js` `v2.1` [`0b61ac7`](https://github.com/inspect-js/is-symbol/commit/0b61ac7ac4de390296aeefb9395549592ea87da4) -- [Dev Deps] update `tape` [`5e1b200`](https://github.com/inspect-js/is-symbol/commit/5e1b2008c910bcdabee299a1ac599143ea07c3f9) -- Only apps should have lockfiles. [`a191ff5`](https://github.com/inspect-js/is-symbol/commit/a191ff5f0320fc16db42fdaa40f0c21d4326255e) -- [Dev Deps] update `nsp`, `eslint`, `@ljharb/eslint-config` [`97c87ef`](https://github.com/inspect-js/is-symbol/commit/97c87ef52b966f211e231092a54ef6ed05c99a26) -- Test on `io.js` `v2.2` [`42560e4`](https://github.com/inspect-js/is-symbol/commit/42560e466e17cbbb9fa71c0121f4bbbcf266c887) -- [Dev Deps] Update `tape`, `eslint` [`149b2f2`](https://github.com/inspect-js/is-symbol/commit/149b2f20bde92b2da12ccfeb8988beb2dc95c37c) -- [Tests] fix test messages [`28bd1ed`](https://github.com/inspect-js/is-symbol/commit/28bd1eda310590e13ada19cbd718c85c25d8a0c5) -- Test up to `io.js` `v3.0` [`c0dcc98`](https://github.com/inspect-js/is-symbol/commit/c0dcc98313d17151ec043e5452df306618be865e) -- `node` now supports Symbols now. [`d1853ad`](https://github.com/inspect-js/is-symbol/commit/d1853adf6369ab9d4c4516bdb032c2e42f52f90a) -- [Dev Deps] update `tape` [`f7a6575`](https://github.com/inspect-js/is-symbol/commit/f7a6575fbdef13abcc412c63d22b56943ed85969) -- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`aae9c6a`](https://github.com/inspect-js/is-symbol/commit/aae9c6a724578659976ea74e11ec9fe35608607b) -- Test on `io.js` `v2.4` [`ab8f449`](https://github.com/inspect-js/is-symbol/commit/ab8f4492115270cc00a479915b02ac1bac75dfed) -- Test on `io.js` `v2.3` [`58ce871`](https://github.com/inspect-js/is-symbol/commit/58ce871674e857955b333aa057eeecd68b40e988) - -## [v1.0.1](https://github.com/inspect-js/is-symbol/compare/v1.0.0...v1.0.1) - 2015-01-26 - -### Commits - -- Correct package description. [`f4d15b9`](https://github.com/inspect-js/is-symbol/commit/f4d15b928b4b754b097a84f7c3ceac73c486aceb) - -## v1.0.0 - 2015-01-24 - -### Commits - -- Dotfiles. [`5d9a744`](https://github.com/inspect-js/is-symbol/commit/5d9a7441f724630070e9bd74a995191cafa1064b) -- Tests. [`8af5663`](https://github.com/inspect-js/is-symbol/commit/8af56631950dcee48b36f517837273193a6ba119) -- `make release` [`6293446`](https://github.com/inspect-js/is-symbol/commit/629344654a72e7fc8059607d6a86c64b002c3e5d) -- package.json [`7d4082c`](https://github.com/inspect-js/is-symbol/commit/7d4082ca9502118e70d24f526704d45a1a7f2067) -- Initial commit [`cbb179f`](https://github.com/inspect-js/is-symbol/commit/cbb179f677bd3dcb56ac5e3f0a7a9af503fd8952) -- Read me. [`099a775`](https://github.com/inspect-js/is-symbol/commit/099a775e7e751706283ae1cab7a8635c094773a9) -- Implementation. [`cb51248`](https://github.com/inspect-js/is-symbol/commit/cb51248eedaf55e0b8ad7dacdab179db2d76e96e) diff --git a/node_modules/is-symbol/LICENSE b/node_modules/is-symbol/LICENSE deleted file mode 100644 index b43df44..0000000 --- a/node_modules/is-symbol/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Jordan Harband - -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/is-symbol/Makefile b/node_modules/is-symbol/Makefile deleted file mode 100644 index b9e4fe1..0000000 --- a/node_modules/is-symbol/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. -$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) - - # The files that need updating when incrementing the version number. -VERSIONED_FILES := *.js *.json README* - - -# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. -# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment -# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. -export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") -UTILS := semver -# Make sure that all required utilities can be located. -UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) - -# Default target (by virtue of being the first non '.'-prefixed in the file). -.PHONY: _no-target-specified -_no-target-specified: - $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) - -# Lists all targets defined in this makefile. -.PHONY: list -list: - @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort - -# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). -.PHONY: test -test: - @npm test - -.PHONY: _ensure-tag -_ensure-tag: -ifndef TAG - $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) -endif - -CHANGELOG_ERROR = $(error No CHANGELOG specified) -.PHONY: _ensure-changelog -_ensure-changelog: - @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) - -# Ensures that the git workspace is clean. -.PHONY: _ensure-clean -_ensure-clean: - @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } - -# Makes a release; invoke with `make TAG= release`. -.PHONY: release -release: _ensure-tag _ensure-changelog _ensure-clean - @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ - new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ - if printf "$$new_ver" | command grep -q '^[0-9]'; then \ - semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ - semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ - else \ - new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ - fi; \ - printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ - replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ - git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ - git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/node_modules/is-symbol/README.md b/node_modules/is-symbol/README.md deleted file mode 100644 index e59d1ce..0000000 --- a/node_modules/is-symbol/README.md +++ /dev/null @@ -1,44 +0,0 @@ -#is-symbol [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -Is this an ES6 Symbol value? - -## Example - -```js -var isSymbol = require('is-symbol'); -assert(!isSymbol(function () {})); -assert(!isSymbol(null)); -assert(!isSymbol(function* () { yield 42; return Infinity; }); - -assert(isSymbol(Symbol.iterator)); -assert(isSymbol(Symbol('foo'))); -assert(isSymbol(Symbol.for('foo'))); -assert(isSymbol(Object(Symbol('foo')))); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-symbol -[2]: http://versionbadg.es/inspect-js/is-symbol.svg -[3]: https://travis-ci.org/inspect-js/is-symbol.svg -[4]: https://travis-ci.org/inspect-js/is-symbol -[5]: https://david-dm.org/inspect-js/is-symbol.svg -[6]: https://david-dm.org/inspect-js/is-symbol -[7]: https://david-dm.org/inspect-js/is-symbol/dev-status.svg -[8]: https://david-dm.org/inspect-js/is-symbol#info=devDependencies -[11]: https://nodei.co/npm/is-symbol.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-symbol.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-symbol.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-symbol diff --git a/node_modules/is-symbol/index.js b/node_modules/is-symbol/index.js deleted file mode 100644 index 3d653e2..0000000 --- a/node_modules/is-symbol/index.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -var toStr = Object.prototype.toString; -var hasSymbols = require('has-symbols')(); - -if (hasSymbols) { - var symToStr = Symbol.prototype.toString; - var symStringRegex = /^Symbol\(.*\)$/; - var isSymbolObject = function isRealSymbolObject(value) { - if (typeof value.valueOf() !== 'symbol') { - return false; - } - return symStringRegex.test(symToStr.call(value)); - }; - - module.exports = function isSymbol(value) { - if (typeof value === 'symbol') { - return true; - } - if (toStr.call(value) !== '[object Symbol]') { - return false; - } - try { - return isSymbolObject(value); - } catch (e) { - return false; - } - }; -} else { - - module.exports = function isSymbol(value) { - // this environment does not support Symbols. - return false && value; - }; -} diff --git a/node_modules/is-symbol/package.json b/node_modules/is-symbol/package.json deleted file mode 100644 index b12d9a6..0000000 --- a/node_modules/is-symbol/package.json +++ /dev/null @@ -1,105 +0,0 @@ -{ - "_from": "is-symbol@^1.0.2", - "_id": "is-symbol@1.0.3", - "_inBundle": false, - "_integrity": "sha512-OwijhaRSgqvhm/0ZdAcXNZt9lYdKFpcRDT5ULUuYXPoT794UNOdU+gpT6Rzo7b4V2HUl/op6GqY894AZwv9faQ==", - "_location": "/is-symbol", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-symbol@^1.0.2", - "name": "is-symbol", - "escapedName": "is-symbol", - "rawSpec": "^1.0.2", - "saveSpec": null, - "fetchSpec": "^1.0.2" - }, - "_requiredBy": [ - "/es-to-primitive" - ], - "_resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.3.tgz", - "_shasum": "38e1014b9e6329be0de9d24a414fd7441ec61937", - "_spec": "is-symbol@^1.0.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/es-to-primitive", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com" - }, - "auto-changelog": { - "output": "CHANGELOG.md", - "template": "keepachangelog", - "unreleased": false, - "commitLimit": false, - "backfillLimit": false - }, - "bugs": { - "url": "https://github.com/inspect-js/is-symbol/issues" - }, - "bundleDependencies": false, - "dependencies": { - "has-symbols": "^1.0.1" - }, - "deprecated": false, - "description": "Determine if a value is an ES6 Symbol or not.", - "devDependencies": { - "@ljharb/eslint-config": "^15.0.2", - "auto-changelog": "^1.16.2", - "covert": "^1.1.1", - "eslint": "^6.6.0", - "object-inspect": "^1.7.0", - "safe-publish-latest": "^1.1.4", - "semver": "^6.3.0", - "tape": "^4.11.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "homepage": "https://github.com/inspect-js/is-symbol#readme", - "keywords": [ - "symbol", - "es6", - "is", - "Symbol" - ], - "license": "MIT", - "main": "index.js", - "name": "is-symbol", - "repository": { - "type": "git", - "url": "git://github.com/inspect-js/is-symbol.git" - }, - "scripts": { - "coverage": "covert test", - "lint": "eslint .", - "posttest": "npx aud", - "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", - "prepublish": "safe-publish-latest", - "pretest": "npm run lint", - "test": "npm run tests-only", - "tests-only": "node --es-staging --harmony test", - "version": "auto-changelog && git add CHANGELOG.md" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.3" -} diff --git a/node_modules/is-symbol/test/index.js b/node_modules/is-symbol/test/index.js deleted file mode 100644 index e01f035..0000000 --- a/node_modules/is-symbol/test/index.js +++ /dev/null @@ -1,92 +0,0 @@ -'use strict'; - -var test = require('tape'); -var isSymbol = require('../index'); - -var forEach = function (arr, func) { - var i; - for (i = 0; i < arr.length; ++i) { - func(arr[i], i, arr); - } -}; - -var hasSymbols = require('has-symbols')(); -var inspect = require('object-inspect'); -var debug = function (v, m) { return inspect(v) + ' ' + m; }; - -test('non-symbol values', function (t) { - var nonSymbols = [ - true, - false, - Object(true), - Object(false), - null, - undefined, - {}, - [], - /a/g, - 'string', - 42, - new Date(), - function () {}, - NaN - ]; - t.plan(nonSymbols.length); - forEach(nonSymbols, function (nonSymbol) { - t.equal(false, isSymbol(nonSymbol), debug(nonSymbol, 'is not a symbol')); - }); - t.end(); -}); - -test('faked symbol values', function (t) { - t.test('real symbol valueOf', { skip: !hasSymbols }, function (st) { - var fakeSymbol = { valueOf: function () { return Symbol('foo'); } }; - st.equal(false, isSymbol(fakeSymbol), 'object with valueOf returning a symbol is not a symbol'); - st.end(); - }); - - t.test('faked @@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (st) { - var fakeSymbol = { valueOf: function () { return Symbol('foo'); } }; - fakeSymbol[Symbol.toStringTag] = 'Symbol'; - st.equal(false, isSymbol(fakeSymbol), 'object with fake Symbol @@toStringTag and valueOf returning a symbol is not a symbol'); - var notSoFakeSymbol = { valueOf: function () { return 42; } }; - notSoFakeSymbol[Symbol.toStringTag] = 'Symbol'; - st.equal(false, isSymbol(notSoFakeSymbol), 'object with fake Symbol @@toStringTag and valueOf not returning a symbol is not a symbol'); - st.end(); - }); - - var fakeSymbolString = { toString: function () { return 'Symbol(foo)'; } }; - t.equal(false, isSymbol(fakeSymbolString), 'object with toString returning Symbol(foo) is not a symbol'); - - t.end(); -}); - -test('Symbol support', { skip: !hasSymbols }, function (t) { - t.test('well-known Symbols', function (st) { - var isWellKnown = function filterer(name) { - return name !== 'for' && name !== 'keyFor' && !(name in filterer); - }; - var wellKnownSymbols = Object.getOwnPropertyNames(Symbol).filter(isWellKnown); - wellKnownSymbols.forEach(function (name) { - var sym = Symbol[name]; - st.equal(true, isSymbol(sym), debug(sym, ' is a symbol')); - }); - st.end(); - }); - - t.test('user-created symbols', function (st) { - var symbols = [ - Symbol(), - Symbol('foo'), - Symbol['for']('foo'), - Object(Symbol('object')) - ]; - symbols.forEach(function (sym) { - st.equal(true, isSymbol(sym), debug(sym, ' is a symbol')); - }); - st.end(); - }); - - t.end(); -}); - diff --git a/node_modules/is-typed-array/.eslintrc b/node_modules/is-typed-array/.eslintrc deleted file mode 100644 index 344c5b6..0000000 --- a/node_modules/is-typed-array/.eslintrc +++ /dev/null @@ -1,9 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "max-statements-per-line": [2, { "max": 2 }] - }, -} diff --git a/node_modules/is-typed-array/.github/FUNDING.yml b/node_modules/is-typed-array/.github/FUNDING.yml deleted file mode 100644 index 7dd24b9..0000000 --- a/node_modules/is-typed-array/.github/FUNDING.yml +++ /dev/null @@ -1,12 +0,0 @@ -# These are supported funding model platforms - -github: [ljharb] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: npm/is-typed-array -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/is-typed-array/.github/workflows/rebase.yml b/node_modules/is-typed-array/.github/workflows/rebase.yml deleted file mode 100644 index 436cb79..0000000 --- a/node_modules/is-typed-array/.github/workflows/rebase.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Automatic Rebase - -on: [pull_request] - -jobs: - _: - name: "Automatic Rebase" - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v1 - - uses: ljharb/rebase@master - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/node_modules/is-typed-array/.travis.yml b/node_modules/is-typed-array/.travis.yml deleted file mode 100644 index 2d1c1d2..0000000 --- a/node_modules/is-typed-array/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -version: ~> 1.0 -language: node_js -os: - - linux -import: - - ljharb/travis-ci:node/all.yml - - ljharb/travis-ci:node/pretest.yml - - ljharb/travis-ci:node/posttest.yml - - ljharb/travis-ci:node/coverage.yml -matrix: - allow_failures: - - env: COVERAGE=true diff --git a/node_modules/is-typed-array/CHANGELOG.md b/node_modules/is-typed-array/CHANGELOG.md deleted file mode 100644 index 71e7331..0000000 --- a/node_modules/is-typed-array/CHANGELOG.md +++ /dev/null @@ -1,53 +0,0 @@ -1.1.3 / 2020-01-24 -================= - * [Refactor] use `es-abstract`’s `callBound`, `available-typed-arrays`, `has-symbols` - -1.1.2 / 2020-01-20 -================= - * [Fix] in envs without Symbol.toStringTag, dc8a8cc made arrays return `true` - * [Tests] add `evalmd` to `prelint` - -1.1.1 / 2020-01-18 -================= - * [Robustness] don’t rely on Array.prototype.indexOf existing - * [meta] remove unused Makefile and associated utilities - * [meta] add `funding` field; create FUNDING.yml - * [actions] add automatic rebasing / merge commit blocking - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `is-callable`, `replace`, `semver`, `tape`; add `safe-publish-latest` - * [Tests] use shared travis-ci configs - * [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops - -1.1.0 / 2019-02-16 -================= - * [New] add `BigInt64Array` and `BigUint64Array` - * [Refactor] use an array instead of an object for storing Typed Array names - * [meta] ignore `test.html` - * [Tests] up to `node` `v11.10`, `v10.15`, `v8.15`, `v7.10`, `v6.16`, `v5.10`, `v4.9` - * [Tests] remove `jscs` - * [Tests] use `npm audit` instead of `nsp` - * [Dev Deps] update `eslint`,` @ljharb/eslint-config`, `is-callable`, `tape`, `replace`, `semver` - * [Dev Deps] remove unused eccheck script + dep - -1.0.4 / 2016-03-19 -================= - * [Fix] `Symbol.toStringTag` is on the super-`[[Prototype]]` of Float32Array, not the `[[Prototype]]` (#3) - * [Tests] up to `node` `v5.9`, `v4.4` - * [Tests] use pretest/posttest for linting/security - * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`, `is-callable` - -1.0.3 / 2015-10-13 -================= - * [Deps] Add missing `foreach` dependency (#1) - -1.0.2 / 2015-10-05 -================= - * [Deps] Remove unneeded "isarray" dependency - * [Dev Deps] update `eslint`, `@ljharb/eslint-config` - -1.0.1 / 2015-10-02 -================= - * Rerelease: avoid instanceof and the constructor property; work cross-realm; work with Symbol.toStringTag. - -1.0.0 / 2015-05-06 -================= - * Initial release. diff --git a/node_modules/is-typed-array/LICENSE b/node_modules/is-typed-array/LICENSE deleted file mode 100644 index b43df44..0000000 --- a/node_modules/is-typed-array/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Jordan Harband - -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/is-typed-array/README.md b/node_modules/is-typed-array/README.md deleted file mode 100644 index a2bd8d8..0000000 --- a/node_modules/is-typed-array/README.md +++ /dev/null @@ -1,71 +0,0 @@ -# is-typed-array [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -Is this value a JS Typed Array? This module works cross-realm/iframe, does not depend on `instanceof` or mutable properties, and despite ES6 Symbol.toStringTag. - -## Example - -```js -var isTypedArray = require('is-typed-array'); -var assert = require('assert'); - -assert.equal(false, isTypedArray(undefined)); -assert.equal(false, isTypedArray(null)); -assert.equal(false, isTypedArray(false)); -assert.equal(false, isTypedArray(true)); -assert.equal(false, isTypedArray([])); -assert.equal(false, isTypedArray({})); -assert.equal(false, isTypedArray(/a/g)); -assert.equal(false, isTypedArray(new RegExp('a', 'g'))); -assert.equal(false, isTypedArray(new Date())); -assert.equal(false, isTypedArray(42)); -assert.equal(false, isTypedArray(NaN)); -assert.equal(false, isTypedArray(Infinity)); -assert.equal(false, isTypedArray(new Number(42))); -assert.equal(false, isTypedArray('foo')); -assert.equal(false, isTypedArray(Object('foo'))); -assert.equal(false, isTypedArray(function () {})); -assert.equal(false, isTypedArray(function* () {})); -assert.equal(false, isTypedArray(x => x * x)); -assert.equal(false, isTypedArray([])); - -assert.ok(isTypedArray(new Int8Array())); -assert.ok(isTypedArray(new Uint8Array())); -assert.ok(isTypedArray(new Uint8ClampedArray())); -assert.ok(isTypedArray(new Int16Array())); -assert.ok(isTypedArray(new Uint16Array())); -assert.ok(isTypedArray(new Int32Array())); -assert.ok(isTypedArray(new Uint32Array())); -assert.ok(isTypedArray(new Float32Array())); -assert.ok(isTypedArray(new Float64Array())); -assert.ok(isTypedArray(new BigInt64Array())); -assert.ok(isTypedArray(new BigUint64Array())); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-typed-array -[2]: http://versionbadg.es/ljharb/is-typed-array.svg -[3]: https://travis-ci.org/ljharb/is-typed-array.svg -[4]: https://travis-ci.org/ljharb/is-typed-array -[5]: https://david-dm.org/ljharb/is-typed-array.svg -[6]: https://david-dm.org/ljharb/is-typed-array -[7]: https://david-dm.org/ljharb/is-typed-array/dev-status.svg -[8]: https://david-dm.org/ljharb/is-typed-array#info=devDependencies -[9]: https://ci.testling.com/ljharb/is-typed-array.png -[10]: https://ci.testling.com/ljharb/is-typed-array -[11]: https://nodei.co/npm/is-typed-array.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-typed-array.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-typed-array.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-typed-array diff --git a/node_modules/is-typed-array/index.js b/node_modules/is-typed-array/index.js deleted file mode 100644 index 213e904..0000000 --- a/node_modules/is-typed-array/index.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -var forEach = require('foreach'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('es-abstract/helpers/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasSymbols = require('has-symbols')(); -var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; - -var typedArrays = availableTypedArrays(); - -var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { - for (var i = 0; i < array.length; i += 1) { - if (array[i] === value) { - return i; - } - } - return -1; -}; -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - var arr = new global[typedArray](); - if (!(Symbol.toStringTag in arr)) { - throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); - } - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var anyTrue = false; - forEach(toStrTags, function (getter, typedArray) { - if (!anyTrue) { - try { - anyTrue = getter.call(value) === typedArray; - } catch (e) { /**/ } - } - }); - return anyTrue; -}; - -module.exports = function isTypedArray(value) { - if (!value || typeof value !== 'object') { return false; } - if (!hasToStringTag) { - var tag = $slice($toString(value), 8, -1); - return $indexOf(typedArrays, tag) > -1; - } - if (!gOPD) { return false; } - return tryTypedArrays(value); -}; diff --git a/node_modules/is-typed-array/package.json b/node_modules/is-typed-array/package.json deleted file mode 100644 index 6bf2121..0000000 --- a/node_modules/is-typed-array/package.json +++ /dev/null @@ -1,124 +0,0 @@ -{ - "_from": "is-typed-array@^1.1.3", - "_id": "is-typed-array@1.1.3", - "_inBundle": false, - "_integrity": "sha512-BSYUBOK/HJibQ30wWkWold5txYwMUXQct9YHAQJr8fSwvZoiglcqB0pd7vEN23+Tsi9IUEjztdOSzl4qLVYGTQ==", - "_location": "/is-typed-array", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-typed-array@^1.1.3", - "name": "is-typed-array", - "escapedName": "is-typed-array", - "rawSpec": "^1.1.3", - "saveSpec": null, - "fetchSpec": "^1.1.3" - }, - "_requiredBy": [ - "/util", - "/which-typed-array" - ], - "_resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.3.tgz", - "_shasum": "a4ff5a5e672e1a55f99c7f54e59597af5c1df04d", - "_spec": "is-typed-array@^1.1.3", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/util", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - }, - "bugs": { - "url": "https://github.com/ljharb/is-typed-array/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - } - ], - "dependencies": { - "available-typed-arrays": "^1.0.0", - "es-abstract": "^1.17.4", - "foreach": "^2.0.5", - "has-symbols": "^1.0.1" - }, - "deprecated": false, - "description": "Is this value a JS Typed Array? This module works cross-realm/iframe, does not depend on `instanceof` or mutable properties, and despite ES6 Symbol.toStringTag.", - "devDependencies": { - "@ljharb/eslint-config": "^15.1.0", - "covert": "^1.1.1", - "eslint": "^6.8.0", - "evalmd": "^0.0.19", - "is-callable": "^1.1.5", - "make-arrow-function": "^1.1.0", - "make-generator-function": "^1.1.0", - "safe-publish-latest": "^1.1.4", - "tape": "^5.0.0-next.4" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "homepage": "https://github.com/ljharb/is-typed-array#readme", - "keywords": [ - "array", - "TypedArray", - "typed array", - "is", - "typed", - "Int8Array", - "Uint8Array", - "Uint8ClampedArray", - "Int16Array", - "Uint16Array", - "Int32Array", - "Uint32Array", - "Float32Array", - "Float64Array", - "ES6", - "toStringTag", - "Symbol.toStringTag", - "@@toStringTag" - ], - "license": "MIT", - "main": "index.js", - "name": "is-typed-array", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/is-typed-array.git" - }, - "scripts": { - "coverage": "covert test/index.js", - "lint": "eslint .", - "posttest": "npx aud", - "prelint": "evalmd README.md", - "prepublish": "safe-publish-latest", - "pretest": "npm run --silent lint", - "test": "npm run tests-only", - "tests-only": "node --es-staging test" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.1.3" -} diff --git a/node_modules/is-typed-array/test/index.js b/node_modules/is-typed-array/test/index.js deleted file mode 100644 index 808776f..0000000 --- a/node_modules/is-typed-array/test/index.js +++ /dev/null @@ -1,101 +0,0 @@ -'use strict'; - -var test = require('tape'); -var isTypedArray = require('../'); -var isCallable = require('is-callable'); -var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; -var genFn = require('make-generator-function'); -var arrowFn = require('make-arrow-function')(); -var forEach = require('foreach'); - -var typedArrayNames = [ - 'Int8Array', - 'Uint8Array', - 'Uint8ClampedArray', - 'Int16Array', - 'Uint16Array', - 'Int32Array', - 'Uint32Array', - 'Float32Array', - 'Float64Array', - 'BigInt64Array', - 'BigUint64Array' -]; - -test('not arrays', function (t) { - t.test('non-number/string primitives', function (st) { - st.notOk(isTypedArray(), 'undefined is not typed array'); - st.notOk(isTypedArray(null), 'null is not typed array'); - st.notOk(isTypedArray(false), 'false is not typed array'); - st.notOk(isTypedArray(true), 'true is not typed array'); - st.end(); - }); - - t.notOk(isTypedArray({}), 'object is not typed array'); - t.notOk(isTypedArray(/a/g), 'regex literal is not typed array'); - // eslint-disable-next-line prefer-regex-literals - t.notOk(isTypedArray(new RegExp('a', 'g')), 'regex object is not typed array'); - t.notOk(isTypedArray(new Date()), 'new Date() is not typed array'); - - t.test('numbers', function (st) { - st.notOk(isTypedArray(42), 'number is not typed array'); - st.notOk(isTypedArray(Object(42)), 'number object is not typed array'); - st.notOk(isTypedArray(NaN), 'NaN is not typed array'); - st.notOk(isTypedArray(Infinity), 'Infinity is not typed array'); - st.end(); - }); - - t.test('strings', function (st) { - st.notOk(isTypedArray('foo'), 'string primitive is not typed array'); - st.notOk(isTypedArray(Object('foo')), 'string object is not typed array'); - st.end(); - }); - - t.end(); -}); - -test('Functions', function (t) { - t.notOk(isTypedArray(function () {}), 'function is not typed array'); - t.end(); -}); - -test('Generators', { skip: !genFn }, function (t) { - t.notOk(isTypedArray(genFn), 'generator function is not typed array'); - t.end(); -}); - -test('Arrow functions', { skip: !arrowFn }, function (t) { - t.notOk(isTypedArray(arrowFn), 'arrow function is not typed array'); - t.end(); -}); - -test('@@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (t) { - forEach(typedArrayNames, function (typedArray) { - if (typeof global[typedArray] === 'function') { - var fakeTypedArray = []; - fakeTypedArray[Symbol.toStringTag] = typedArray; - t.notOk(isTypedArray(fakeTypedArray), 'faked ' + typedArray + ' is not typed array'); - } else { - t.comment('# SKIP ' + typedArray + ' is not supported'); - } - }); - t.end(); -}); - -test('non-Typed Arrays', function (t) { - t.notOk(isTypedArray([]), '[] is not typed array'); - t.end(); -}); - -test('Typed Arrays', function (t) { - forEach(typedArrayNames, function (typedArray) { - var TypedArray = global[typedArray]; - if (isCallable(TypedArray)) { - var arr = new TypedArray(10); - t.ok(isTypedArray(arr), 'new ' + typedArray + '(10) is typed array'); - } else { - t.comment('# SKIP ' + typedArray + ' is not supported'); - } - }); - t.end(); -}); diff --git a/node_modules/isarray/.npmignore b/node_modules/isarray/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/node_modules/isarray/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/isarray/.travis.yml b/node_modules/isarray/.travis.yml deleted file mode 100644 index cc4dba2..0000000 --- a/node_modules/isarray/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" diff --git a/node_modules/isarray/Makefile b/node_modules/isarray/Makefile deleted file mode 100644 index 787d56e..0000000 --- a/node_modules/isarray/Makefile +++ /dev/null @@ -1,6 +0,0 @@ - -test: - @node_modules/.bin/tape test.js - -.PHONY: test - diff --git a/node_modules/isarray/README.md b/node_modules/isarray/README.md deleted file mode 100644 index 16d2c59..0000000 --- a/node_modules/isarray/README.md +++ /dev/null @@ -1,60 +0,0 @@ - -# isarray - -`Array#isArray` for older browsers. - -[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) -[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) - -[![browser support](https://ci.testling.com/juliangruber/isarray.png) -](https://ci.testling.com/juliangruber/isarray) - -## 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/component.json b/node_modules/isarray/component.json deleted file mode 100644 index 9e31b68..0000000 --- a/node_modules/isarray/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name" : "isarray", - "description" : "Array#isArray for older browsers", - "version" : "0.0.1", - "repository" : "juliangruber/isarray", - "homepage": "https://github.com/juliangruber/isarray", - "main" : "index.js", - "scripts" : [ - "index.js" - ], - "dependencies" : {}, - "keywords": ["browser","isarray","array"], - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "license": "MIT" -} diff --git a/node_modules/isarray/index.js b/node_modules/isarray/index.js deleted file mode 100644 index a57f634..0000000 --- a/node_modules/isarray/index.js +++ /dev/null @@ -1,5 +0,0 @@ -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; diff --git a/node_modules/isarray/package.json b/node_modules/isarray/package.json deleted file mode 100644 index a6d3856..0000000 --- a/node_modules/isarray/package.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "_from": "isarray@~1.0.0", - "_id": "isarray@1.0.0", - "_inBundle": false, - "_integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", - "_location": "/isarray", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "isarray@~1.0.0", - "name": "isarray", - "escapedName": "isarray", - "rawSpec": "~1.0.0", - "saveSpec": null, - "fetchSpec": "~1.0.0" - }, - "_requiredBy": [ - "/readable-stream" - ], - "_resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "_shasum": "bb935d48582cba168c06834957a54a3e07124f11", - "_spec": "isarray@~1.0.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/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": { - "tape": "~2.13.4" - }, - "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": "tape test.js" - }, - "testling": { - "files": "test.js", - "browsers": [ - "ie/8..latest", - "firefox/17..latest", - "firefox/nightly", - "chrome/22..latest", - "chrome/canary", - "opera/12..latest", - "opera/next", - "safari/5.1..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2..latest" - ] - }, - "version": "1.0.0" -} diff --git a/node_modules/isarray/test.js b/node_modules/isarray/test.js deleted file mode 100644 index e0c3444..0000000 --- a/node_modules/isarray/test.js +++ /dev/null @@ -1,20 +0,0 @@ -var isArray = require('./'); -var test = require('tape'); - -test('is array', function(t){ - t.ok(isArray([])); - t.notOk(isArray({})); - t.notOk(isArray(null)); - t.notOk(isArray(false)); - - var obj = {}; - obj[0] = true; - t.notOk(isArray(obj)); - - var arr = []; - arr.foo = 'bar'; - t.ok(isArray(arr)); - - t.end(); -}); - diff --git a/node_modules/kareem/.travis.yml b/node_modules/kareem/.travis.yml deleted file mode 100644 index 0a388b9..0000000 --- a/node_modules/kareem/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: node_js -node_js: - - "12" - - "10" - - "9" - - "8" - - "7" - - "6" - - "5" - - "4" -script: "npm run-script test-travis" -after_script: "npm install coveralls@2.10.0 && cat ./coverage/lcov.info | coveralls" diff --git a/node_modules/kareem/CHANGELOG.md b/node_modules/kareem/CHANGELOG.md deleted file mode 100644 index aa011f4..0000000 --- a/node_modules/kareem/CHANGELOG.md +++ /dev/null @@ -1,790 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - - -## 2.3.0 (2018-09-24) - -* chore(release): 2.2.3 ([c8f2695](https://github.com/vkarpov15/kareem/commit/c8f2695)) -* chore(release): 2.2.4 ([a377a4f](https://github.com/vkarpov15/kareem/commit/a377a4f)) -* chore(release): 2.2.5 ([5a495e3](https://github.com/vkarpov15/kareem/commit/5a495e3)) -* fix(filter): copy async pres correctly with `filter()` ([1b1ed8a](https://github.com/vkarpov15/kareem/commit/1b1ed8a)), closes [Automattic/mongoose#3054](https://github.com/Automattic/mongoose/issues/3054) -* feat: add filter() function ([1f641f4](https://github.com/vkarpov15/kareem/commit/1f641f4)) -* feat: support storing options on pre and post hooks ([59220b9](https://github.com/vkarpov15/kareem/commit/59220b9)) - - - - -## 2.2.3 (2018-09-10) - -* chore: release 2.2.3 ([af653a3](https://github.com/vkarpov15/kareem/commit/af653a3)) - - - - -## 2.2.2 (2018-09-10) - -* chore: release 2.2.2 ([3f0144d](https://github.com/vkarpov15/kareem/commit/3f0144d)) -* fix: allow merge() to not clone ([e628d65](https://github.com/vkarpov15/kareem/commit/e628d65)) - - - - -## 2.2.1 (2018-06-05) - -* chore: release 2.2.1 ([4625a64](https://github.com/vkarpov15/kareem/commit/4625a64)) -* chore: remove lockfile from git ([7f3e4e6](https://github.com/vkarpov15/kareem/commit/7f3e4e6)) -* fix: handle numAsync correctly when merging ([fef8e7e](https://github.com/vkarpov15/kareem/commit/fef8e7e)) -* test: repro issue with not copying numAsync ([952d9db](https://github.com/vkarpov15/kareem/commit/952d9db)) - - - - -## 2.2.0 (2018-06-05) - -* chore: release 2.2.0 ([ff9ad03](https://github.com/vkarpov15/kareem/commit/ff9ad03)) -* fix: use maps instead of objects for _pres and _posts so `toString()` doesn't get reported as having ([55df303](https://github.com/vkarpov15/kareem/commit/55df303)), closes [Automattic/mongoose#6538](https://github.com/Automattic/mongoose/issues/6538) - - - - -## 2.1.0 (2018-05-16) - -* chore: release 2.1.0 ([ba5f1bc](https://github.com/vkarpov15/kareem/commit/ba5f1bc)) -* feat: add option to check wrapped function return value for promises ([c9d7dd1](https://github.com/vkarpov15/kareem/commit/c9d7dd1)) -* refactor: use const in wrap() ([0fc21f9](https://github.com/vkarpov15/kareem/commit/0fc21f9)) - - - - -## 2.0.7 (2018-04-28) - -* chore: release 2.0.7 ([0bf91e6](https://github.com/vkarpov15/kareem/commit/0bf91e6)) -* feat: add `hasHooks()` ([225f18d](https://github.com/vkarpov15/kareem/commit/225f18d)), closes [Automattic/mongoose#6385](https://github.com/Automattic/mongoose/issues/6385) - - - - -## 2.0.6 (2018-03-22) - -* chore: release 2.0.6 ([f3d406b](https://github.com/vkarpov15/kareem/commit/f3d406b)) -* fix(wrap): ensure fast path still wraps function in `nextTick()` for chaining ([7000494](https://github.com/vkarpov15/kareem/commit/7000494)), closes [Automattic/mongoose#6250](https://github.com/Automattic/mongoose/issues/6250) [dsanel/mongoose-delete#36](https://github.com/dsanel/mongoose-delete/issues/36) - - - - -## 2.0.5 (2018-02-22) - -* chore: release 2.0.5 ([3286612](https://github.com/vkarpov15/kareem/commit/3286612)) -* perf(createWrapper): don't create wrapper if there are no hooks ([5afc5b9](https://github.com/vkarpov15/kareem/commit/5afc5b9)), closes [Automattic/mongoose#6126](https://github.com/Automattic/mongoose/issues/6126) - - - - -## 2.0.4 (2018-02-08) - -* chore: release 2.0.4 ([2ab0293](https://github.com/vkarpov15/kareem/commit/2ab0293)) - - - - -## 2.0.3 (2018-02-01) - -* chore: release 2.0.3 ([3c1abe5](https://github.com/vkarpov15/kareem/commit/3c1abe5)) -* fix: use process.nextTick() re: Automattic/mongoose#6074 ([e5bfe33](https://github.com/vkarpov15/kareem/commit/e5bfe33)), closes [Automattic/mongoose#6074](https://github.com/Automattic/mongoose/issues/6074) - - - - -## 2.0.2 (2018-01-24) - -* chore: fix license ([a9d755c](https://github.com/vkarpov15/kareem/commit/a9d755c)), closes [#10](https://github.com/vkarpov15/kareem/issues/10) -* chore: release 2.0.2 ([fe87ab6](https://github.com/vkarpov15/kareem/commit/fe87ab6)) - - - - -## 2.0.1 (2018-01-09) - -* chore: release 2.0.1 with lockfile bump ([09c44fb](https://github.com/vkarpov15/kareem/commit/09c44fb)) - - - - -## 2.0.0 (2018-01-09) - -* chore: bump marked re: security ([cc564a9](https://github.com/vkarpov15/kareem/commit/cc564a9)) -* chore: release 2.0.0 ([f511d1c](https://github.com/vkarpov15/kareem/commit/f511d1c)) - - - - -## 2.0.0-rc5 (2017-12-23) - -* chore: fix build on node 4+5 ([6dac5a4](https://github.com/vkarpov15/kareem/commit/6dac5a4)) -* chore: fix built on node 4 + 5 again ([434ef0a](https://github.com/vkarpov15/kareem/commit/434ef0a)) -* chore: release 2.0.0-rc5 ([25a32ee](https://github.com/vkarpov15/kareem/commit/25a32ee)) - - - - -## 2.0.0-rc4 (2017-12-22) - -* chore: release 2.0.0-rc4 ([49fc083](https://github.com/vkarpov15/kareem/commit/49fc083)) -* BREAKING CHANGE: deduplicate when merging hooks re: Automattic/mongoose#2945 ([d458573](https://github.com/vkarpov15/kareem/commit/d458573)), closes [Automattic/mongoose#2945](https://github.com/Automattic/mongoose/issues/2945) - - - - -## 2.0.0-rc3 (2017-12-22) - -* chore: release 2.0.0-rc3 ([adaaa00](https://github.com/vkarpov15/kareem/commit/adaaa00)) -* feat: support returning promises from middleware functions ([05b4480](https://github.com/vkarpov15/kareem/commit/05b4480)), closes [Automattic/mongoose#3779](https://github.com/Automattic/mongoose/issues/3779) - - - - -## 2.0.0-rc2 (2017-12-21) - -* chore: release 2.0.0-rc2 ([76325fa](https://github.com/vkarpov15/kareem/commit/76325fa)) -* fix: ensure next() and done() run in next tick ([6c20684](https://github.com/vkarpov15/kareem/commit/6c20684)) - - - - -## 2.0.0-rc1 (2017-12-21) - -* chore: improve test coverage re: Automattic/mongoose#3232 ([7b45cf0](https://github.com/vkarpov15/kareem/commit/7b45cf0)), closes [Automattic/mongoose#3232](https://github.com/Automattic/mongoose/issues/3232) -* chore: release 2.0.0-rc1 ([9b83f52](https://github.com/vkarpov15/kareem/commit/9b83f52)) -* BREAKING CHANGE: report sync exceptions as errors, only allow calling next() and done() once ([674adcc](https://github.com/vkarpov15/kareem/commit/674adcc)), closes [Automattic/mongoose#3483](https://github.com/Automattic/mongoose/issues/3483) - - - - -## 2.0.0-rc0 (2017-12-17) - -* chore: release 2.0.0-rc0 ([16b44b5](https://github.com/vkarpov15/kareem/commit/16b44b5)) -* BREAKING CHANGE: drop support for node < 4 ([9cbb8c7](https://github.com/vkarpov15/kareem/commit/9cbb8c7)) -* BREAKING CHANGE: remove useLegacyPost and add several new features ([6dd8531](https://github.com/vkarpov15/kareem/commit/6dd8531)), closes [Automattic/mongoose#3232](https://github.com/Automattic/mongoose/issues/3232) - - - - -## 1.5.0 (2017-07-20) - -* chore: release 1.5.0 ([9c491a0](https://github.com/vkarpov15/kareem/commit/9c491a0)) -* fix: improve post error handlers results ([9928dd5](https://github.com/vkarpov15/kareem/commit/9928dd5)), closes [Automattic/mongoose#5466](https://github.com/Automattic/mongoose/issues/5466) - - - - -## 1.4.2 (2017-07-06) - -* chore: release 1.4.2 ([8d14ac5](https://github.com/vkarpov15/kareem/commit/8d14ac5)) -* fix: correct args re: Automattic/mongoose#5405 ([3f28ae6](https://github.com/vkarpov15/kareem/commit/3f28ae6)), closes [Automattic/mongoose#5405](https://github.com/Automattic/mongoose/issues/5405) - - - - -## 1.4.1 (2017-04-25) - -* chore: release 1.4.1 ([5ecf0c2](https://github.com/vkarpov15/kareem/commit/5ecf0c2)) -* fix: handle numAsyncPres with clone() ([c72e857](https://github.com/vkarpov15/kareem/commit/c72e857)), closes [#8](https://github.com/vkarpov15/kareem/issues/8) -* test: repro #8 ([9b4d6b2](https://github.com/vkarpov15/kareem/commit/9b4d6b2)), closes [#8](https://github.com/vkarpov15/kareem/issues/8) - - - - -## 1.4.0 (2017-04-19) - -* chore: release 1.4.0 ([101c5f5](https://github.com/vkarpov15/kareem/commit/101c5f5)) -* feat: add merge() function ([285325e](https://github.com/vkarpov15/kareem/commit/285325e)) - - - - -## 1.3.0 (2017-03-26) - -* chore: release 1.3.0 ([f3a9e50](https://github.com/vkarpov15/kareem/commit/f3a9e50)) -* feat: pass function args to execPre ([4dd466d](https://github.com/vkarpov15/kareem/commit/4dd466d)) - - - - -## 1.2.1 (2017-02-03) - -* chore: release 1.2.1 ([d97081f](https://github.com/vkarpov15/kareem/commit/d97081f)) -* fix: filter out _kareemIgnored args for error handlers re: Automattic/mongoose#4925 ([ddc7aeb](https://github.com/vkarpov15/kareem/commit/ddc7aeb)), closes [Automattic/mongoose#4925](https://github.com/Automattic/mongoose/issues/4925) -* fix: make error handlers handle errors in pre hooks ([af38033](https://github.com/vkarpov15/kareem/commit/af38033)), closes [Automattic/mongoose#4927](https://github.com/Automattic/mongoose/issues/4927) - - - - -## 1.2.0 (2017-01-02) - -* chore: release 1.2.0 ([033225c](https://github.com/vkarpov15/kareem/commit/033225c)) -* chore: upgrade deps ([f9e9a09](https://github.com/vkarpov15/kareem/commit/f9e9a09)) -* feat: add _kareemIgnore re: Automattic/mongoose#4836 ([7957771](https://github.com/vkarpov15/kareem/commit/7957771)), closes [Automattic/mongoose#4836](https://github.com/Automattic/mongoose/issues/4836) - - - - -## 1.1.5 (2016-12-13) - -* chore: release 1.1.5 ([1a9f684](https://github.com/vkarpov15/kareem/commit/1a9f684)) -* fix: correct field name ([04a0e9d](https://github.com/vkarpov15/kareem/commit/04a0e9d)) - - - - -## 1.1.4 (2016-12-09) - -* chore: release 1.1.4 ([ece401c](https://github.com/vkarpov15/kareem/commit/ece401c)) -* chore: run tests on node 6 ([e0cb1cb](https://github.com/vkarpov15/kareem/commit/e0cb1cb)) -* fix: only copy own properties in clone() ([dfe28ce](https://github.com/vkarpov15/kareem/commit/dfe28ce)), closes [#7](https://github.com/vkarpov15/kareem/issues/7) - - - - -## 1.1.3 (2016-06-27) - -* chore: release 1.1.3 ([87171c8](https://github.com/vkarpov15/kareem/commit/87171c8)) -* fix: couple more issues with arg processing ([c65f523](https://github.com/vkarpov15/kareem/commit/c65f523)) - - - - -## 1.1.2 (2016-06-27) - -* chore: release 1.1.2 ([8e102b6](https://github.com/vkarpov15/kareem/commit/8e102b6)) -* fix: add early return ([4feda4e](https://github.com/vkarpov15/kareem/commit/4feda4e)) - - - - -## 1.1.1 (2016-06-27) - -* chore: release 1.1.1 ([8bb3050](https://github.com/vkarpov15/kareem/commit/8bb3050)) -* fix: skip error handlers if no error ([0eb3a44](https://github.com/vkarpov15/kareem/commit/0eb3a44)) - - - - -## 1.1.0 (2016-05-11) - -* chore: release 1.1.0 ([85332d9](https://github.com/vkarpov15/kareem/commit/85332d9)) -* chore: test on node 4 and node 5 ([1faefa1](https://github.com/vkarpov15/kareem/commit/1faefa1)) -* 100% coverage again ([c9aee4e](https://github.com/vkarpov15/kareem/commit/c9aee4e)) -* add support for error post hooks ([d378113](https://github.com/vkarpov15/kareem/commit/d378113)) -* basic setup for sync hooks #4 ([55aa081](https://github.com/vkarpov15/kareem/commit/55aa081)), closes [#4](https://github.com/vkarpov15/kareem/issues/4) -* proof of concept for error handlers ([e4a07d9](https://github.com/vkarpov15/kareem/commit/e4a07d9)) -* refactor out handleWrapError helper ([b19af38](https://github.com/vkarpov15/kareem/commit/b19af38)) - - - - -## 1.0.1 (2015-05-10) - -* Fix #1 ([de60dc6](https://github.com/vkarpov15/kareem/commit/de60dc6)), closes [#1](https://github.com/vkarpov15/kareem/issues/1) -* release 1.0.1 ([6971088](https://github.com/vkarpov15/kareem/commit/6971088)) -* Run tests on iojs in travis ([adcd201](https://github.com/vkarpov15/kareem/commit/adcd201)) -* support legacy post hook behavior in wrap() ([23fa74c](https://github.com/vkarpov15/kareem/commit/23fa74c)) -* Use node 0.12 in travis ([834689d](https://github.com/vkarpov15/kareem/commit/834689d)) - - - - -## 1.0.0 (2015-01-28) - -* Tag 1.0.0 ([4c5a35a](https://github.com/vkarpov15/kareem/commit/4c5a35a)) - - - - -## 0.0.8 (2015-01-27) - -* Add clone function ([688bba7](https://github.com/vkarpov15/kareem/commit/688bba7)) -* Add jscs for style checking ([5c93149](https://github.com/vkarpov15/kareem/commit/5c93149)) -* Bump 0.0.8 ([03c0d2f](https://github.com/vkarpov15/kareem/commit/03c0d2f)) -* Fix jscs config, add gulp rules ([9989abf](https://github.com/vkarpov15/kareem/commit/9989abf)) -* fix Makefile typo ([1f7e61a](https://github.com/vkarpov15/kareem/commit/1f7e61a)) - - - - -## 0.0.7 (2015-01-04) - -* Bump 0.0.7 ([98ef173](https://github.com/vkarpov15/kareem/commit/98ef173)) -* fix LearnBoost/mongoose#2553 - use null instead of undefined for err ([9157b48](https://github.com/vkarpov15/kareem/commit/9157b48)), closes [LearnBoost/mongoose#2553](https://github.com/LearnBoost/mongoose/issues/2553) -* Regenerate docs ([2331cdf](https://github.com/vkarpov15/kareem/commit/2331cdf)) - - - - -## 0.0.6 (2015-01-01) - -* Update docs and bump 0.0.6 ([92c12a7](https://github.com/vkarpov15/kareem/commit/92c12a7)) - - - - -## 0.0.5 (2015-01-01) - -* Add coverage rule to Makefile ([825a91c](https://github.com/vkarpov15/kareem/commit/825a91c)) -* Add coveralls to README ([fb52369](https://github.com/vkarpov15/kareem/commit/fb52369)) -* Add coveralls to travis ([93f6f15](https://github.com/vkarpov15/kareem/commit/93f6f15)) -* Add createWrapper() function ([ea77741](https://github.com/vkarpov15/kareem/commit/ea77741)) -* Add istanbul code coverage ([6eceeef](https://github.com/vkarpov15/kareem/commit/6eceeef)) -* Add some more comments for examples ([c5b0c6f](https://github.com/vkarpov15/kareem/commit/c5b0c6f)) -* Add travis ([e6dcb06](https://github.com/vkarpov15/kareem/commit/e6dcb06)) -* Add travis badge to docs ([ad8c9b3](https://github.com/vkarpov15/kareem/commit/ad8c9b3)) -* Add wrap() tests, 100% coverage ([6945be4](https://github.com/vkarpov15/kareem/commit/6945be4)) -* Better test coverage for execPost ([d9ad539](https://github.com/vkarpov15/kareem/commit/d9ad539)) -* Bump 0.0.5 ([69875b1](https://github.com/vkarpov15/kareem/commit/69875b1)) -* Docs fix ([15b7098](https://github.com/vkarpov15/kareem/commit/15b7098)) -* Fix silly mistake in docs generation ([50373eb](https://github.com/vkarpov15/kareem/commit/50373eb)) -* Fix typo in readme ([fec4925](https://github.com/vkarpov15/kareem/commit/fec4925)) -* Linkify travis badge ([92b25fe](https://github.com/vkarpov15/kareem/commit/92b25fe)) -* Make travis run coverage ([747157b](https://github.com/vkarpov15/kareem/commit/747157b)) -* Move travis status badge ([d52e89b](https://github.com/vkarpov15/kareem/commit/d52e89b)) -* Quick fix for coverage ([50bbddb](https://github.com/vkarpov15/kareem/commit/50bbddb)) -* Typo fix ([adea794](https://github.com/vkarpov15/kareem/commit/adea794)) - - - - -## 0.0.4 (2014-12-13) - -* Bump 0.0.4, run docs generation ([51a15fe](https://github.com/vkarpov15/kareem/commit/51a15fe)) -* Use correct post parameters in wrap() ([9bb5da3](https://github.com/vkarpov15/kareem/commit/9bb5da3)) - - - - -## 0.0.3 (2014-12-12) - -* Add npm test script, fix small bug with args not getting passed through post ([49e3e68](https://github.com/vkarpov15/kareem/commit/49e3e68)) -* Bump 0.0.3 ([65621d8](https://github.com/vkarpov15/kareem/commit/65621d8)) -* Update readme ([901388b](https://github.com/vkarpov15/kareem/commit/901388b)) - - - - -## 0.0.2 (2014-12-12) - -* Add github repo and bump 0.0.2 ([59db8be](https://github.com/vkarpov15/kareem/commit/59db8be)) - - - - -## 0.0.1 (2014-12-12) - -* Add basic docs ([ad29ea4](https://github.com/vkarpov15/kareem/commit/ad29ea4)) -* Add pre hooks ([2ffc356](https://github.com/vkarpov15/kareem/commit/2ffc356)) -* Add wrap function ([68c540c](https://github.com/vkarpov15/kareem/commit/68c540c)) -* Bump to version 0.0.1 ([a4bfd68](https://github.com/vkarpov15/kareem/commit/a4bfd68)) -* Initial commit ([4002458](https://github.com/vkarpov15/kareem/commit/4002458)) -* Initial deposit ([98fc489](https://github.com/vkarpov15/kareem/commit/98fc489)) -* Post hooks ([395b67c](https://github.com/vkarpov15/kareem/commit/395b67c)) -* Some basic setup work ([82df75e](https://github.com/vkarpov15/kareem/commit/82df75e)) -* Support sync pre hooks ([1cc1b9f](https://github.com/vkarpov15/kareem/commit/1cc1b9f)) -* Update package.json description ([978da18](https://github.com/vkarpov15/kareem/commit/978da18)) - - - - -## 2.2.5 (2018-09-24) - - - - - -## 2.2.4 (2018-09-24) - - - - - -## 2.2.3 (2018-09-24) - -* fix(filter): copy async pres correctly with `filter()` ([1b1ed8a](https://github.com/vkarpov15/kareem/commit/1b1ed8a)), closes [Automattic/mongoose#3054](https://github.com/Automattic/mongoose/issues/3054) -* feat: add filter() function ([1f641f4](https://github.com/vkarpov15/kareem/commit/1f641f4)) -* feat: support storing options on pre and post hooks ([59220b9](https://github.com/vkarpov15/kareem/commit/59220b9)) - - - - -## 2.2.3 (2018-09-10) - -* chore: release 2.2.3 ([af653a3](https://github.com/vkarpov15/kareem/commit/af653a3)) - - - - -## 2.2.2 (2018-09-10) - -* chore: release 2.2.2 ([3f0144d](https://github.com/vkarpov15/kareem/commit/3f0144d)) -* fix: allow merge() to not clone ([e628d65](https://github.com/vkarpov15/kareem/commit/e628d65)) - - - - -## 2.2.1 (2018-06-05) - -* chore: release 2.2.1 ([4625a64](https://github.com/vkarpov15/kareem/commit/4625a64)) -* chore: remove lockfile from git ([7f3e4e6](https://github.com/vkarpov15/kareem/commit/7f3e4e6)) -* fix: handle numAsync correctly when merging ([fef8e7e](https://github.com/vkarpov15/kareem/commit/fef8e7e)) -* test: repro issue with not copying numAsync ([952d9db](https://github.com/vkarpov15/kareem/commit/952d9db)) - - - - -## 2.2.0 (2018-06-05) - -* chore: release 2.2.0 ([ff9ad03](https://github.com/vkarpov15/kareem/commit/ff9ad03)) -* fix: use maps instead of objects for _pres and _posts so `toString()` doesn't get reported as having ([55df303](https://github.com/vkarpov15/kareem/commit/55df303)), closes [Automattic/mongoose#6538](https://github.com/Automattic/mongoose/issues/6538) - - - - -## 2.1.0 (2018-05-16) - -* chore: release 2.1.0 ([ba5f1bc](https://github.com/vkarpov15/kareem/commit/ba5f1bc)) -* feat: add option to check wrapped function return value for promises ([c9d7dd1](https://github.com/vkarpov15/kareem/commit/c9d7dd1)) -* refactor: use const in wrap() ([0fc21f9](https://github.com/vkarpov15/kareem/commit/0fc21f9)) - - - - -## 2.0.7 (2018-04-28) - -* chore: release 2.0.7 ([0bf91e6](https://github.com/vkarpov15/kareem/commit/0bf91e6)) -* feat: add `hasHooks()` ([225f18d](https://github.com/vkarpov15/kareem/commit/225f18d)), closes [Automattic/mongoose#6385](https://github.com/Automattic/mongoose/issues/6385) - - - - -## 2.0.6 (2018-03-22) - -* chore: release 2.0.6 ([f3d406b](https://github.com/vkarpov15/kareem/commit/f3d406b)) -* fix(wrap): ensure fast path still wraps function in `nextTick()` for chaining ([7000494](https://github.com/vkarpov15/kareem/commit/7000494)), closes [Automattic/mongoose#6250](https://github.com/Automattic/mongoose/issues/6250) [dsanel/mongoose-delete#36](https://github.com/dsanel/mongoose-delete/issues/36) - - - - -## 2.0.5 (2018-02-22) - -* chore: release 2.0.5 ([3286612](https://github.com/vkarpov15/kareem/commit/3286612)) -* perf(createWrapper): don't create wrapper if there are no hooks ([5afc5b9](https://github.com/vkarpov15/kareem/commit/5afc5b9)), closes [Automattic/mongoose#6126](https://github.com/Automattic/mongoose/issues/6126) - - - - -## 2.0.4 (2018-02-08) - -* chore: release 2.0.4 ([2ab0293](https://github.com/vkarpov15/kareem/commit/2ab0293)) - - - - -## 2.0.3 (2018-02-01) - -* chore: release 2.0.3 ([3c1abe5](https://github.com/vkarpov15/kareem/commit/3c1abe5)) -* fix: use process.nextTick() re: Automattic/mongoose#6074 ([e5bfe33](https://github.com/vkarpov15/kareem/commit/e5bfe33)), closes [Automattic/mongoose#6074](https://github.com/Automattic/mongoose/issues/6074) - - - - -## 2.0.2 (2018-01-24) - -* chore: fix license ([a9d755c](https://github.com/vkarpov15/kareem/commit/a9d755c)), closes [#10](https://github.com/vkarpov15/kareem/issues/10) -* chore: release 2.0.2 ([fe87ab6](https://github.com/vkarpov15/kareem/commit/fe87ab6)) - - - - -## 2.0.1 (2018-01-09) - -* chore: release 2.0.1 with lockfile bump ([09c44fb](https://github.com/vkarpov15/kareem/commit/09c44fb)) - - - - -## 2.0.0 (2018-01-09) - -* chore: bump marked re: security ([cc564a9](https://github.com/vkarpov15/kareem/commit/cc564a9)) -* chore: release 2.0.0 ([f511d1c](https://github.com/vkarpov15/kareem/commit/f511d1c)) - - - - -## 2.0.0-rc5 (2017-12-23) - -* chore: fix build on node 4+5 ([6dac5a4](https://github.com/vkarpov15/kareem/commit/6dac5a4)) -* chore: fix built on node 4 + 5 again ([434ef0a](https://github.com/vkarpov15/kareem/commit/434ef0a)) -* chore: release 2.0.0-rc5 ([25a32ee](https://github.com/vkarpov15/kareem/commit/25a32ee)) - - - - -## 2.0.0-rc4 (2017-12-22) - -* chore: release 2.0.0-rc4 ([49fc083](https://github.com/vkarpov15/kareem/commit/49fc083)) -* BREAKING CHANGE: deduplicate when merging hooks re: Automattic/mongoose#2945 ([d458573](https://github.com/vkarpov15/kareem/commit/d458573)), closes [Automattic/mongoose#2945](https://github.com/Automattic/mongoose/issues/2945) - - - - -## 2.0.0-rc3 (2017-12-22) - -* chore: release 2.0.0-rc3 ([adaaa00](https://github.com/vkarpov15/kareem/commit/adaaa00)) -* feat: support returning promises from middleware functions ([05b4480](https://github.com/vkarpov15/kareem/commit/05b4480)), closes [Automattic/mongoose#3779](https://github.com/Automattic/mongoose/issues/3779) - - - - -## 2.0.0-rc2 (2017-12-21) - -* chore: release 2.0.0-rc2 ([76325fa](https://github.com/vkarpov15/kareem/commit/76325fa)) -* fix: ensure next() and done() run in next tick ([6c20684](https://github.com/vkarpov15/kareem/commit/6c20684)) - - - - -## 2.0.0-rc1 (2017-12-21) - -* chore: improve test coverage re: Automattic/mongoose#3232 ([7b45cf0](https://github.com/vkarpov15/kareem/commit/7b45cf0)), closes [Automattic/mongoose#3232](https://github.com/Automattic/mongoose/issues/3232) -* chore: release 2.0.0-rc1 ([9b83f52](https://github.com/vkarpov15/kareem/commit/9b83f52)) -* BREAKING CHANGE: report sync exceptions as errors, only allow calling next() and done() once ([674adcc](https://github.com/vkarpov15/kareem/commit/674adcc)), closes [Automattic/mongoose#3483](https://github.com/Automattic/mongoose/issues/3483) - - - - -## 2.0.0-rc0 (2017-12-17) - -* chore: release 2.0.0-rc0 ([16b44b5](https://github.com/vkarpov15/kareem/commit/16b44b5)) -* BREAKING CHANGE: drop support for node < 4 ([9cbb8c7](https://github.com/vkarpov15/kareem/commit/9cbb8c7)) -* BREAKING CHANGE: remove useLegacyPost and add several new features ([6dd8531](https://github.com/vkarpov15/kareem/commit/6dd8531)), closes [Automattic/mongoose#3232](https://github.com/Automattic/mongoose/issues/3232) - - - - -## 1.5.0 (2017-07-20) - -* chore: release 1.5.0 ([9c491a0](https://github.com/vkarpov15/kareem/commit/9c491a0)) -* fix: improve post error handlers results ([9928dd5](https://github.com/vkarpov15/kareem/commit/9928dd5)), closes [Automattic/mongoose#5466](https://github.com/Automattic/mongoose/issues/5466) - - - - -## 1.4.2 (2017-07-06) - -* chore: release 1.4.2 ([8d14ac5](https://github.com/vkarpov15/kareem/commit/8d14ac5)) -* fix: correct args re: Automattic/mongoose#5405 ([3f28ae6](https://github.com/vkarpov15/kareem/commit/3f28ae6)), closes [Automattic/mongoose#5405](https://github.com/Automattic/mongoose/issues/5405) - - - - -## 1.4.1 (2017-04-25) - -* chore: release 1.4.1 ([5ecf0c2](https://github.com/vkarpov15/kareem/commit/5ecf0c2)) -* fix: handle numAsyncPres with clone() ([c72e857](https://github.com/vkarpov15/kareem/commit/c72e857)), closes [#8](https://github.com/vkarpov15/kareem/issues/8) -* test: repro #8 ([9b4d6b2](https://github.com/vkarpov15/kareem/commit/9b4d6b2)), closes [#8](https://github.com/vkarpov15/kareem/issues/8) - - - - -## 1.4.0 (2017-04-19) - -* chore: release 1.4.0 ([101c5f5](https://github.com/vkarpov15/kareem/commit/101c5f5)) -* feat: add merge() function ([285325e](https://github.com/vkarpov15/kareem/commit/285325e)) - - - - -## 1.3.0 (2017-03-26) - -* chore: release 1.3.0 ([f3a9e50](https://github.com/vkarpov15/kareem/commit/f3a9e50)) -* feat: pass function args to execPre ([4dd466d](https://github.com/vkarpov15/kareem/commit/4dd466d)) - - - - -## 1.2.1 (2017-02-03) - -* chore: release 1.2.1 ([d97081f](https://github.com/vkarpov15/kareem/commit/d97081f)) -* fix: filter out _kareemIgnored args for error handlers re: Automattic/mongoose#4925 ([ddc7aeb](https://github.com/vkarpov15/kareem/commit/ddc7aeb)), closes [Automattic/mongoose#4925](https://github.com/Automattic/mongoose/issues/4925) -* fix: make error handlers handle errors in pre hooks ([af38033](https://github.com/vkarpov15/kareem/commit/af38033)), closes [Automattic/mongoose#4927](https://github.com/Automattic/mongoose/issues/4927) - - - - -## 1.2.0 (2017-01-02) - -* chore: release 1.2.0 ([033225c](https://github.com/vkarpov15/kareem/commit/033225c)) -* chore: upgrade deps ([f9e9a09](https://github.com/vkarpov15/kareem/commit/f9e9a09)) -* feat: add _kareemIgnore re: Automattic/mongoose#4836 ([7957771](https://github.com/vkarpov15/kareem/commit/7957771)), closes [Automattic/mongoose#4836](https://github.com/Automattic/mongoose/issues/4836) - - - - -## 1.1.5 (2016-12-13) - -* chore: release 1.1.5 ([1a9f684](https://github.com/vkarpov15/kareem/commit/1a9f684)) -* fix: correct field name ([04a0e9d](https://github.com/vkarpov15/kareem/commit/04a0e9d)) - - - - -## 1.1.4 (2016-12-09) - -* chore: release 1.1.4 ([ece401c](https://github.com/vkarpov15/kareem/commit/ece401c)) -* chore: run tests on node 6 ([e0cb1cb](https://github.com/vkarpov15/kareem/commit/e0cb1cb)) -* fix: only copy own properties in clone() ([dfe28ce](https://github.com/vkarpov15/kareem/commit/dfe28ce)), closes [#7](https://github.com/vkarpov15/kareem/issues/7) - - - - -## 1.1.3 (2016-06-27) - -* chore: release 1.1.3 ([87171c8](https://github.com/vkarpov15/kareem/commit/87171c8)) -* fix: couple more issues with arg processing ([c65f523](https://github.com/vkarpov15/kareem/commit/c65f523)) - - - - -## 1.1.2 (2016-06-27) - -* chore: release 1.1.2 ([8e102b6](https://github.com/vkarpov15/kareem/commit/8e102b6)) -* fix: add early return ([4feda4e](https://github.com/vkarpov15/kareem/commit/4feda4e)) - - - - -## 1.1.1 (2016-06-27) - -* chore: release 1.1.1 ([8bb3050](https://github.com/vkarpov15/kareem/commit/8bb3050)) -* fix: skip error handlers if no error ([0eb3a44](https://github.com/vkarpov15/kareem/commit/0eb3a44)) - - - - -## 1.1.0 (2016-05-11) - -* chore: release 1.1.0 ([85332d9](https://github.com/vkarpov15/kareem/commit/85332d9)) -* chore: test on node 4 and node 5 ([1faefa1](https://github.com/vkarpov15/kareem/commit/1faefa1)) -* 100% coverage again ([c9aee4e](https://github.com/vkarpov15/kareem/commit/c9aee4e)) -* add support for error post hooks ([d378113](https://github.com/vkarpov15/kareem/commit/d378113)) -* basic setup for sync hooks #4 ([55aa081](https://github.com/vkarpov15/kareem/commit/55aa081)), closes [#4](https://github.com/vkarpov15/kareem/issues/4) -* proof of concept for error handlers ([e4a07d9](https://github.com/vkarpov15/kareem/commit/e4a07d9)) -* refactor out handleWrapError helper ([b19af38](https://github.com/vkarpov15/kareem/commit/b19af38)) - - - - -## 1.0.1 (2015-05-10) - -* Fix #1 ([de60dc6](https://github.com/vkarpov15/kareem/commit/de60dc6)), closes [#1](https://github.com/vkarpov15/kareem/issues/1) -* release 1.0.1 ([6971088](https://github.com/vkarpov15/kareem/commit/6971088)) -* Run tests on iojs in travis ([adcd201](https://github.com/vkarpov15/kareem/commit/adcd201)) -* support legacy post hook behavior in wrap() ([23fa74c](https://github.com/vkarpov15/kareem/commit/23fa74c)) -* Use node 0.12 in travis ([834689d](https://github.com/vkarpov15/kareem/commit/834689d)) - - - - -## 1.0.0 (2015-01-28) - -* Tag 1.0.0 ([4c5a35a](https://github.com/vkarpov15/kareem/commit/4c5a35a)) - - - - -## 0.0.8 (2015-01-27) - -* Add clone function ([688bba7](https://github.com/vkarpov15/kareem/commit/688bba7)) -* Add jscs for style checking ([5c93149](https://github.com/vkarpov15/kareem/commit/5c93149)) -* Bump 0.0.8 ([03c0d2f](https://github.com/vkarpov15/kareem/commit/03c0d2f)) -* Fix jscs config, add gulp rules ([9989abf](https://github.com/vkarpov15/kareem/commit/9989abf)) -* fix Makefile typo ([1f7e61a](https://github.com/vkarpov15/kareem/commit/1f7e61a)) - - - - -## 0.0.7 (2015-01-04) - -* Bump 0.0.7 ([98ef173](https://github.com/vkarpov15/kareem/commit/98ef173)) -* fix LearnBoost/mongoose#2553 - use null instead of undefined for err ([9157b48](https://github.com/vkarpov15/kareem/commit/9157b48)), closes [LearnBoost/mongoose#2553](https://github.com/LearnBoost/mongoose/issues/2553) -* Regenerate docs ([2331cdf](https://github.com/vkarpov15/kareem/commit/2331cdf)) - - - - -## 0.0.6 (2015-01-01) - -* Update docs and bump 0.0.6 ([92c12a7](https://github.com/vkarpov15/kareem/commit/92c12a7)) - - - - -## 0.0.5 (2015-01-01) - -* Add coverage rule to Makefile ([825a91c](https://github.com/vkarpov15/kareem/commit/825a91c)) -* Add coveralls to README ([fb52369](https://github.com/vkarpov15/kareem/commit/fb52369)) -* Add coveralls to travis ([93f6f15](https://github.com/vkarpov15/kareem/commit/93f6f15)) -* Add createWrapper() function ([ea77741](https://github.com/vkarpov15/kareem/commit/ea77741)) -* Add istanbul code coverage ([6eceeef](https://github.com/vkarpov15/kareem/commit/6eceeef)) -* Add some more comments for examples ([c5b0c6f](https://github.com/vkarpov15/kareem/commit/c5b0c6f)) -* Add travis ([e6dcb06](https://github.com/vkarpov15/kareem/commit/e6dcb06)) -* Add travis badge to docs ([ad8c9b3](https://github.com/vkarpov15/kareem/commit/ad8c9b3)) -* Add wrap() tests, 100% coverage ([6945be4](https://github.com/vkarpov15/kareem/commit/6945be4)) -* Better test coverage for execPost ([d9ad539](https://github.com/vkarpov15/kareem/commit/d9ad539)) -* Bump 0.0.5 ([69875b1](https://github.com/vkarpov15/kareem/commit/69875b1)) -* Docs fix ([15b7098](https://github.com/vkarpov15/kareem/commit/15b7098)) -* Fix silly mistake in docs generation ([50373eb](https://github.com/vkarpov15/kareem/commit/50373eb)) -* Fix typo in readme ([fec4925](https://github.com/vkarpov15/kareem/commit/fec4925)) -* Linkify travis badge ([92b25fe](https://github.com/vkarpov15/kareem/commit/92b25fe)) -* Make travis run coverage ([747157b](https://github.com/vkarpov15/kareem/commit/747157b)) -* Move travis status badge ([d52e89b](https://github.com/vkarpov15/kareem/commit/d52e89b)) -* Quick fix for coverage ([50bbddb](https://github.com/vkarpov15/kareem/commit/50bbddb)) -* Typo fix ([adea794](https://github.com/vkarpov15/kareem/commit/adea794)) - - - - -## 0.0.4 (2014-12-13) - -* Bump 0.0.4, run docs generation ([51a15fe](https://github.com/vkarpov15/kareem/commit/51a15fe)) -* Use correct post parameters in wrap() ([9bb5da3](https://github.com/vkarpov15/kareem/commit/9bb5da3)) - - - - -## 0.0.3 (2014-12-12) - -* Add npm test script, fix small bug with args not getting passed through post ([49e3e68](https://github.com/vkarpov15/kareem/commit/49e3e68)) -* Bump 0.0.3 ([65621d8](https://github.com/vkarpov15/kareem/commit/65621d8)) -* Update readme ([901388b](https://github.com/vkarpov15/kareem/commit/901388b)) - - - - -## 0.0.2 (2014-12-12) - -* Add github repo and bump 0.0.2 ([59db8be](https://github.com/vkarpov15/kareem/commit/59db8be)) - - - - -## 0.0.1 (2014-12-12) - -* Add basic docs ([ad29ea4](https://github.com/vkarpov15/kareem/commit/ad29ea4)) -* Add pre hooks ([2ffc356](https://github.com/vkarpov15/kareem/commit/2ffc356)) -* Add wrap function ([68c540c](https://github.com/vkarpov15/kareem/commit/68c540c)) -* Bump to version 0.0.1 ([a4bfd68](https://github.com/vkarpov15/kareem/commit/a4bfd68)) -* Initial commit ([4002458](https://github.com/vkarpov15/kareem/commit/4002458)) -* Initial deposit ([98fc489](https://github.com/vkarpov15/kareem/commit/98fc489)) -* Post hooks ([395b67c](https://github.com/vkarpov15/kareem/commit/395b67c)) -* Some basic setup work ([82df75e](https://github.com/vkarpov15/kareem/commit/82df75e)) -* Support sync pre hooks ([1cc1b9f](https://github.com/vkarpov15/kareem/commit/1cc1b9f)) -* Update package.json description ([978da18](https://github.com/vkarpov15/kareem/commit/978da18)) diff --git a/node_modules/kareem/LICENSE b/node_modules/kareem/LICENSE deleted file mode 100644 index e06d208..0000000 --- a/node_modules/kareem/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/node_modules/kareem/Makefile b/node_modules/kareem/Makefile deleted file mode 100644 index f71ba90..0000000 --- a/node_modules/kareem/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -docs: - node ./docs.js - -coverage: - ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- -R spec ./test/* diff --git a/node_modules/kareem/README.md b/node_modules/kareem/README.md deleted file mode 100644 index 49a4abc..0000000 --- a/node_modules/kareem/README.md +++ /dev/null @@ -1,428 +0,0 @@ -# kareem - - [![Build Status](https://travis-ci.org/vkarpov15/kareem.svg?branch=master)](https://travis-ci.org/vkarpov15/kareem) - [![Coverage Status](https://img.shields.io/coveralls/vkarpov15/kareem.svg)](https://coveralls.io/r/vkarpov15/kareem) - -Re-imagined take on the [hooks](http://npmjs.org/package/hooks) module, meant to offer additional flexibility in allowing you to execute hooks whenever necessary, as opposed to simply wrapping a single function. - -Named for the NBA's all-time leading scorer Kareem Abdul-Jabbar, known for his mastery of the [hook shot](http://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar#Skyhook) - - - -# API - -## pre hooks - -Much like [hooks](https://npmjs.org/package/hooks), kareem lets you define -pre and post hooks: pre hooks are called before a given function executes. -Unlike hooks, kareem stores hooks and other internal state in a separate -object, rather than relying on inheritance. Furthermore, kareem exposes -an `execPre()` function that allows you to execute your pre hooks when -appropriate, giving you more fine-grained control over your function hooks. - - -#### It runs without any hooks specified - -```javascript - - hooks.execPre('cook', null, function() { - done(); - }); - -``` - -#### It runs basic serial pre hooks - -pre hook functions take one parameter, a "done" function that you execute -when your pre hook is finished. - - -```javascript - - var count = 0; - - hooks.pre('cook', function(done) { - ++count; - done(); - }); - - hooks.execPre('cook', null, function() { - assert.equal(1, count); - done(); - }); - -``` - -#### It can run multipe pre hooks - -```javascript - - var count1 = 0; - var count2 = 0; - - hooks.pre('cook', function(done) { - ++count1; - done(); - }); - - hooks.pre('cook', function(done) { - ++count2; - done(); - }); - - hooks.execPre('cook', null, function() { - assert.equal(1, count1); - assert.equal(1, count2); - done(); - }); - -``` - -#### It can run fully synchronous pre hooks - -If your pre hook function takes no parameters, its assumed to be -fully synchronous. - - -```javascript - - var count1 = 0; - var count2 = 0; - - hooks.pre('cook', function() { - ++count1; - }); - - hooks.pre('cook', function() { - ++count2; - }); - - hooks.execPre('cook', null, function(error) { - assert.equal(null, error); - assert.equal(1, count1); - assert.equal(1, count2); - done(); - }); - -``` - -#### It properly attaches context to pre hooks - -Pre save hook functions are bound to the second parameter to `execPre()` - - -```javascript - - hooks.pre('cook', function(done) { - this.bacon = 3; - done(); - }); - - hooks.pre('cook', function(done) { - this.eggs = 4; - done(); - }); - - var obj = { bacon: 0, eggs: 0 }; - - // In the pre hooks, `this` will refer to `obj` - hooks.execPre('cook', obj, function(error) { - assert.equal(null, error); - assert.equal(3, obj.bacon); - assert.equal(4, obj.eggs); - done(); - }); - -``` - -#### It can execute parallel (async) pre hooks - -Like the hooks module, you can declare "async" pre hooks - these take two -parameters, the functions `next()` and `done()`. `next()` passes control to -the next pre hook, but the underlying function won't be called until all -async pre hooks have called `done()`. - - -```javascript - - hooks.pre('cook', true, function(next, done) { - this.bacon = 3; - next(); - setTimeout(function() { - done(); - }, 5); - }); - - hooks.pre('cook', true, function(next, done) { - next(); - var _this = this; - setTimeout(function() { - _this.eggs = 4; - done(); - }, 10); - }); - - hooks.pre('cook', function(next) { - this.waffles = false; - next(); - }); - - var obj = { bacon: 0, eggs: 0 }; - - hooks.execPre('cook', obj, function() { - assert.equal(3, obj.bacon); - assert.equal(4, obj.eggs); - assert.equal(false, obj.waffles); - done(); - }); - -``` - -#### It supports returning a promise - -You can also return a promise from your pre hooks instead of calling -`next()`. When the returned promise resolves, kareem will kick off the -next middleware. - - -```javascript - - hooks.pre('cook', function() { - return new Promise(resolve => { - setTimeout(() => { - this.bacon = 3; - resolve(); - }, 100); - }); - }); - - var obj = { bacon: 0 }; - - hooks.execPre('cook', obj, function() { - assert.equal(3, obj.bacon); - done(); - }); - -``` - -## post hooks - -#### It runs without any hooks specified - -```javascript - - hooks.execPost('cook', null, [1], function(error, eggs) { - assert.ifError(error); - assert.equal(1, eggs); - done(); - }); - -``` - -#### It executes with parameters passed in - -```javascript - - hooks.post('cook', function(eggs, bacon, callback) { - assert.equal(1, eggs); - assert.equal(2, bacon); - callback(); - }); - - hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { - assert.ifError(error); - assert.equal(1, eggs); - assert.equal(2, bacon); - done(); - }); - -``` - -#### It can use synchronous post hooks - -```javascript - - var execed = {}; - - hooks.post('cook', function(eggs, bacon) { - execed.first = true; - assert.equal(1, eggs); - assert.equal(2, bacon); - }); - - hooks.post('cook', function(eggs, bacon, callback) { - execed.second = true; - assert.equal(1, eggs); - assert.equal(2, bacon); - callback(); - }); - - hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { - assert.ifError(error); - assert.equal(2, Object.keys(execed).length); - assert.ok(execed.first); - assert.ok(execed.second); - assert.equal(1, eggs); - assert.equal(2, bacon); - done(); - }); - -``` - -## wrap() - -#### It wraps pre and post calls into one call - -```javascript - - hooks.pre('cook', true, function(next, done) { - this.bacon = 3; - next(); - setTimeout(function() { - done(); - }, 5); - }); - - hooks.pre('cook', true, function(next, done) { - next(); - var _this = this; - setTimeout(function() { - _this.eggs = 4; - done(); - }, 10); - }); - - hooks.pre('cook', function(next) { - this.waffles = false; - next(); - }); - - hooks.post('cook', function(obj) { - obj.tofu = 'no'; - }); - - var obj = { bacon: 0, eggs: 0 }; - - var args = [obj]; - args.push(function(error, result) { - assert.ifError(error); - assert.equal(null, error); - assert.equal(3, obj.bacon); - assert.equal(4, obj.eggs); - assert.equal(false, obj.waffles); - assert.equal('no', obj.tofu); - - assert.equal(obj, result); - done(); - }); - - hooks.wrap( - 'cook', - function(o, callback) { - assert.equal(3, obj.bacon); - assert.equal(4, obj.eggs); - assert.equal(false, obj.waffles); - assert.equal(undefined, obj.tofu); - callback(null, o); - }, - obj, - args); - -``` - -## createWrapper() - -#### It wraps wrap() into a callable function - -```javascript - - hooks.pre('cook', true, function(next, done) { - this.bacon = 3; - next(); - setTimeout(function() { - done(); - }, 5); - }); - - hooks.pre('cook', true, function(next, done) { - next(); - var _this = this; - setTimeout(function() { - _this.eggs = 4; - done(); - }, 10); - }); - - hooks.pre('cook', function(next) { - this.waffles = false; - next(); - }); - - hooks.post('cook', function(obj) { - obj.tofu = 'no'; - }); - - var obj = { bacon: 0, eggs: 0 }; - - var cook = hooks.createWrapper( - 'cook', - function(o, callback) { - assert.equal(3, obj.bacon); - assert.equal(4, obj.eggs); - assert.equal(false, obj.waffles); - assert.equal(undefined, obj.tofu); - callback(null, o); - }, - obj); - - cook(obj, function(error, result) { - assert.ifError(error); - assert.equal(3, obj.bacon); - assert.equal(4, obj.eggs); - assert.equal(false, obj.waffles); - assert.equal('no', obj.tofu); - - assert.equal(obj, result); - done(); - }); - -``` - -## clone() - -#### It clones a Kareem object - -```javascript - - var k1 = new Kareem(); - k1.pre('cook', function() {}); - k1.post('cook', function() {}); - - var k2 = k1.clone(); - assert.deepEqual(['cook'], Object.keys(k2._pres)); - assert.deepEqual(['cook'], Object.keys(k2._posts)); - -``` - -## merge() - -#### It pulls hooks from another Kareem object - -```javascript - - var k1 = new Kareem(); - var test1 = function() {}; - k1.pre('cook', test1); - k1.post('cook', function() {}); - - var k2 = new Kareem(); - var test2 = function() {}; - k2.pre('cook', test2); - var k3 = k2.merge(k1); - assert.equal(k3._pres['cook'].length, 2); - assert.equal(k3._pres['cook'][0].fn, test2); - assert.equal(k3._pres['cook'][1].fn, test1); - assert.equal(k3._posts['cook'].length, 1); - -``` - diff --git a/node_modules/kareem/docs.js b/node_modules/kareem/docs.js deleted file mode 100644 index 4a8d4c8..0000000 --- a/node_modules/kareem/docs.js +++ /dev/null @@ -1,37 +0,0 @@ -var acquit = require('acquit'); - -var content = require('fs').readFileSync('./test/examples.test.js').toString(); -var blocks = acquit.parse(content); - -var mdOutput = - '# kareem\n\n' + - ' [![Build Status](https://travis-ci.org/vkarpov15/kareem.svg?branch=master)](https://travis-ci.org/vkarpov15/kareem)\n' + - ' [![Coverage Status](https://img.shields.io/coveralls/vkarpov15/kareem.svg)](https://coveralls.io/r/vkarpov15/kareem)\n\n' + - 'Re-imagined take on the [hooks](http://npmjs.org/package/hooks) module, ' + - 'meant to offer additional flexibility in allowing you to execute hooks ' + - 'whenever necessary, as opposed to simply wrapping a single function.\n\n' + - 'Named for the NBA\'s all-time leading scorer Kareem Abdul-Jabbar, known ' + - 'for his mastery of the [hook shot](http://en.wikipedia.org/wiki/Kareem_Abdul-Jabbar#Skyhook)\n\n' + - '\n\n' + - '# API\n\n'; - -for (var i = 0; i < blocks.length; ++i) { - var describe = blocks[i]; - mdOutput += '## ' + describe.contents + '\n\n'; - mdOutput += describe.comments[0] ? - acquit.trimEachLine(describe.comments[0]) + '\n\n' : - ''; - - for (var j = 0; j < describe.blocks.length; ++j) { - var it = describe.blocks[j]; - mdOutput += '#### It ' + it.contents + '\n\n'; - mdOutput += it.comments[0] ? - acquit.trimEachLine(it.comments[0]) + '\n\n' : - ''; - mdOutput += '```javascript\n'; - mdOutput += ' ' + it.code + '\n'; - mdOutput += '```\n\n'; - } -} - -require('fs').writeFileSync('README.md', mdOutput); diff --git a/node_modules/kareem/gulpfile.js b/node_modules/kareem/gulpfile.js deleted file mode 100644 index 635bfc7..0000000 --- a/node_modules/kareem/gulpfile.js +++ /dev/null @@ -1,18 +0,0 @@ -var gulp = require('gulp'); -var mocha = require('gulp-mocha'); -var config = require('./package.json'); -var jscs = require('gulp-jscs'); - -gulp.task('mocha', function() { - return gulp.src('./test/*'). - pipe(mocha({ reporter: 'dot' })); -}); - -gulp.task('jscs', function() { - return gulp.src('./index.js'). - pipe(jscs(config.jscsConfig)); -}); - -gulp.task('watch', function() { - gulp.watch('./index.js', ['jscs', 'mocha']); -}); diff --git a/node_modules/kareem/index.js b/node_modules/kareem/index.js deleted file mode 100644 index 31ccb41..0000000 --- a/node_modules/kareem/index.js +++ /dev/null @@ -1,511 +0,0 @@ -'use strict'; - -function Kareem() { - this._pres = new Map(); - this._posts = new Map(); -} - -Kareem.prototype.execPre = function(name, context, args, callback) { - if (arguments.length === 3) { - callback = args; - args = []; - } - var pres = get(this._pres, name, []); - var numPres = pres.length; - var numAsyncPres = pres.numAsync || 0; - var currentPre = 0; - var asyncPresLeft = numAsyncPres; - var done = false; - var $args = args; - - if (!numPres) { - return process.nextTick(function() { - callback(null); - }); - } - - var next = function() { - if (currentPre >= numPres) { - return; - } - var pre = pres[currentPre]; - - if (pre.isAsync) { - var args = [ - decorateNextFn(_next), - decorateNextFn(function(error) { - if (error) { - if (done) { - return; - } - done = true; - return callback(error); - } - if (--asyncPresLeft === 0 && currentPre >= numPres) { - return callback(null); - } - }) - ]; - - callMiddlewareFunction(pre.fn, context, args, args[0]); - } else if (pre.fn.length > 0) { - var args = [decorateNextFn(_next)]; - var _args = arguments.length >= 2 ? arguments : [null].concat($args); - for (var i = 1; i < _args.length; ++i) { - args.push(_args[i]); - } - - callMiddlewareFunction(pre.fn, context, args, args[0]); - } else { - let error = null; - let maybePromise = null; - try { - maybePromise = pre.fn.call(context); - } catch (err) { - error = err; - } - - if (isPromise(maybePromise)) { - maybePromise.then(() => _next(), err => _next(err)); - } else { - if (++currentPre >= numPres) { - if (asyncPresLeft > 0) { - // Leave parallel hooks to run - return; - } else { - return process.nextTick(function() { - callback(error); - }); - } - } - next(error); - } - } - }; - - next.apply(null, [null].concat(args)); - - function _next(error) { - if (error) { - if (done) { - return; - } - done = true; - return callback(error); - } - - if (++currentPre >= numPres) { - if (asyncPresLeft > 0) { - // Leave parallel hooks to run - return; - } else { - return callback(null); - } - } - - next.apply(context, arguments); - } -}; - -Kareem.prototype.execPreSync = function(name, context, args) { - var pres = get(this._pres, name, []); - var numPres = pres.length; - - for (var i = 0; i < numPres; ++i) { - pres[i].fn.apply(context, args || []); - } -}; - -Kareem.prototype.execPost = function(name, context, args, options, callback) { - if (arguments.length < 5) { - callback = options; - options = null; - } - var posts = get(this._posts, name, []); - var numPosts = posts.length; - var currentPost = 0; - - var firstError = null; - if (options && options.error) { - firstError = options.error; - } - - if (!numPosts) { - return process.nextTick(function() { - callback.apply(null, [firstError].concat(args)); - }); - } - - var next = function() { - var post = posts[currentPost].fn; - var numArgs = 0; - var argLength = args.length; - var newArgs = []; - for (var i = 0; i < argLength; ++i) { - numArgs += args[i] && args[i]._kareemIgnore ? 0 : 1; - if (!args[i] || !args[i]._kareemIgnore) { - newArgs.push(args[i]); - } - } - - if (firstError) { - if (post.length === numArgs + 2) { - var _cb = decorateNextFn(function(error) { - if (error) { - firstError = error; - } - if (++currentPost >= numPosts) { - return callback.call(null, firstError); - } - next(); - }); - - callMiddlewareFunction(post, context, - [firstError].concat(newArgs).concat([_cb]), _cb); - } else { - if (++currentPost >= numPosts) { - return callback.call(null, firstError); - } - next(); - } - } else { - const _cb = decorateNextFn(function(error) { - if (error) { - firstError = error; - return next(); - } - - if (++currentPost >= numPosts) { - return callback.apply(null, [null].concat(args)); - } - - next(); - }); - - if (post.length === numArgs + 2) { - // Skip error handlers if no error - if (++currentPost >= numPosts) { - return callback.apply(null, [null].concat(args)); - } - return next(); - } - if (post.length === numArgs + 1) { - callMiddlewareFunction(post, context, newArgs.concat([_cb]), _cb); - } else { - let error; - let maybePromise; - try { - maybePromise = post.apply(context, newArgs); - } catch (err) { - error = err; - firstError = err; - } - - if (isPromise(maybePromise)) { - return maybePromise.then(() => _cb(), err => _cb(err)); - } - - if (++currentPost >= numPosts) { - return callback.apply(null, [error].concat(args)); - } - - next(error); - } - } - }; - - next(); -}; - -Kareem.prototype.execPostSync = function(name, context, args) { - const posts = get(this._posts, name, []); - const numPosts = posts.length; - - for (let i = 0; i < numPosts; ++i) { - posts[i].fn.apply(context, args || []); - } -}; - -Kareem.prototype.createWrapperSync = function(name, fn) { - var kareem = this; - return function syncWrapper() { - kareem.execPreSync(name, this, arguments); - - var toReturn = fn.apply(this, arguments); - - kareem.execPostSync(name, this, [toReturn]); - - return toReturn; - }; -} - -function _handleWrapError(instance, error, name, context, args, options, callback) { - if (options.useErrorHandlers) { - var _options = { error: error }; - return instance.execPost(name, context, args, _options, function(error) { - return typeof callback === 'function' && callback(error); - }); - } else { - return typeof callback === 'function' ? - callback(error) : - undefined; - } -} - -Kareem.prototype.wrap = function(name, fn, context, args, options) { - const lastArg = (args.length > 0 ? args[args.length - 1] : null); - const argsWithoutCb = typeof lastArg === 'function' ? - args.slice(0, args.length - 1) : - args; - const _this = this; - - options = options || {}; - const checkForPromise = options.checkForPromise; - - this.execPre(name, context, args, function(error) { - if (error) { - const numCallbackParams = options.numCallbackParams || 0; - const errorArgs = options.contextParameter ? [context] : []; - for (var i = errorArgs.length; i < numCallbackParams; ++i) { - errorArgs.push(null); - } - return _handleWrapError(_this, error, name, context, errorArgs, - options, lastArg); - } - - const end = (typeof lastArg === 'function' ? args.length - 1 : args.length); - const numParameters = fn.length; - const ret = fn.apply(context, args.slice(0, end).concat(_cb)); - - if (checkForPromise) { - if (ret != null && typeof ret.then === 'function') { - // Thenable, use it - return ret.then( - res => _cb(null, res), - err => _cb(err) - ); - } - - // If `fn()` doesn't have a callback argument and doesn't return a - // promise, assume it is sync - if (numParameters < end + 1) { - return _cb(null, ret); - } - } - - function _cb() { - const args = arguments; - const argsWithoutError = Array.prototype.slice.call(arguments, 1); - if (options.nullResultByDefault && argsWithoutError.length === 0) { - argsWithoutError.push(null); - } - if (arguments[0]) { - // Assume error - return _handleWrapError(_this, arguments[0], name, context, - argsWithoutError, options, lastArg); - } else { - _this.execPost(name, context, argsWithoutError, function() { - if (arguments[0]) { - return typeof lastArg === 'function' ? - lastArg(arguments[0]) : - undefined; - } - - return typeof lastArg === 'function' ? - lastArg.apply(context, arguments) : - undefined; - }); - } - } - }); -}; - -Kareem.prototype.filter = function(fn) { - const clone = this.clone(); - - const pres = Array.from(clone._pres.keys()); - for (const name of pres) { - const hooks = this._pres.get(name). - map(h => Object.assign({}, h, { name: name })). - filter(fn); - - if (hooks.length === 0) { - clone._pres.delete(name); - continue; - } - - hooks.numAsync = hooks.filter(h => h.isAsync).length; - - clone._pres.set(name, hooks); - } - - const posts = Array.from(clone._posts.keys()); - for (const name of posts) { - const hooks = this._posts.get(name). - map(h => Object.assign({}, h, { name: name })). - filter(fn); - - if (hooks.length === 0) { - clone._posts.delete(name); - continue; - } - - clone._posts.set(name, hooks); - } - - return clone; -}; - -Kareem.prototype.hasHooks = function(name) { - return this._pres.has(name) || this._posts.has(name); -}; - -Kareem.prototype.createWrapper = function(name, fn, context, options) { - var _this = this; - if (!this.hasHooks(name)) { - // Fast path: if there's no hooks for this function, just return the - // function wrapped in a nextTick() - return function() { - process.nextTick(() => fn.apply(this, arguments)); - }; - } - return function() { - var _context = context || this; - var args = Array.prototype.slice.call(arguments); - _this.wrap(name, fn, _context, args, options); - }; -}; - -Kareem.prototype.pre = function(name, isAsync, fn, error, unshift) { - let options = {}; - if (typeof isAsync === 'object' && isAsync != null) { - options = isAsync; - isAsync = options.isAsync; - } else if (typeof arguments[1] !== 'boolean') { - error = fn; - fn = isAsync; - isAsync = false; - } - - const pres = get(this._pres, name, []); - this._pres.set(name, pres); - - if (isAsync) { - pres.numAsync = pres.numAsync || 0; - ++pres.numAsync; - } - - if (typeof fn !== 'function') { - throw new Error('pre() requires a function, got "' + typeof fn + '"'); - } - - if (unshift) { - pres.unshift(Object.assign({}, options, { fn: fn, isAsync: isAsync })); - } else { - pres.push(Object.assign({}, options, { fn: fn, isAsync: isAsync })); - } - - return this; -}; - -Kareem.prototype.post = function(name, options, fn, unshift) { - const hooks = get(this._posts, name, []); - - if (typeof options === 'function') { - unshift = !!fn; - fn = options; - options = {}; - } - - if (typeof fn !== 'function') { - throw new Error('post() requires a function, got "' + typeof fn + '"'); - } - - if (unshift) { - hooks.unshift(Object.assign({}, options, { fn: fn })); - } else { - hooks.push(Object.assign({}, options, { fn: fn })); - } - this._posts.set(name, hooks); - return this; -}; - -Kareem.prototype.clone = function() { - const n = new Kareem(); - - for (let key of this._pres.keys()) { - const clone = this._pres.get(key).slice(); - clone.numAsync = this._pres.get(key).numAsync; - n._pres.set(key, clone); - } - for (let key of this._posts.keys()) { - n._posts.set(key, this._posts.get(key).slice()); - } - - return n; -}; - -Kareem.prototype.merge = function(other, clone) { - clone = arguments.length === 1 ? true : clone; - var ret = clone ? this.clone() : this; - - for (let key of other._pres.keys()) { - const sourcePres = get(ret._pres, key, []); - const deduplicated = other._pres.get(key). - // Deduplicate based on `fn` - filter(p => sourcePres.map(_p => _p.fn).indexOf(p.fn) === -1); - const combined = sourcePres.concat(deduplicated); - combined.numAsync = sourcePres.numAsync || 0; - combined.numAsync += deduplicated.filter(p => p.isAsync).length; - ret._pres.set(key, combined); - } - for (let key of other._posts.keys()) { - const sourcePosts = get(ret._posts, key, []); - const deduplicated = other._posts.get(key). - filter(p => sourcePosts.indexOf(p) === -1); - ret._posts.set(key, sourcePosts.concat(deduplicated)); - } - - return ret; -}; - -function get(map, key, def) { - if (map.has(key)) { - return map.get(key); - } - return def; -} - -function callMiddlewareFunction(fn, context, args, next) { - let maybePromise; - try { - maybePromise = fn.apply(context, args); - } catch (error) { - return next(error); - } - - if (isPromise(maybePromise)) { - maybePromise.then(() => next(), err => next(err)); - } -} - -function isPromise(v) { - return v != null && typeof v.then === 'function'; -} - -function decorateNextFn(fn) { - var called = false; - var _this = this; - return function() { - // Ensure this function can only be called once - if (called) { - return; - } - called = true; - // Make sure to clear the stack so try/catch doesn't catch errors - // in subsequent middleware - return process.nextTick(() => fn.apply(_this, arguments)); - }; -} - -module.exports = Kareem; diff --git a/node_modules/kareem/package.json b/node_modules/kareem/package.json deleted file mode 100644 index d130098..0000000 --- a/node_modules/kareem/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "_from": "kareem@2.3.1", - "_id": "kareem@2.3.1", - "_inBundle": false, - "_integrity": "sha512-l3hLhffs9zqoDe8zjmb/mAN4B8VT3L56EUvKNqLFVs9YlFA+zx7ke1DO8STAdDyYNkeSo1nKmjuvQeI12So8Xw==", - "_location": "/kareem", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "kareem@2.3.1", - "name": "kareem", - "escapedName": "kareem", - "rawSpec": "2.3.1", - "saveSpec": null, - "fetchSpec": "2.3.1" - }, - "_requiredBy": [ - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/kareem/-/kareem-2.3.1.tgz", - "_shasum": "def12d9c941017fabfb00f873af95e9c99e1be87", - "_spec": "kareem@2.3.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mongoose", - "author": { - "name": "Valeri Karpov", - "email": "val@karpov.io" - }, - "bugs": { - "url": "https://github.com/vkarpov15/kareem/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Next-generation take on pre/post function hooks", - "devDependencies": { - "mocha": "5.x", - "nyc": "11.x", - "standard-version": "4.4.0" - }, - "homepage": "https://github.com/vkarpov15/kareem#readme", - "license": "Apache-2.0", - "main": "index.js", - "name": "kareem", - "repository": { - "type": "git", - "url": "git://github.com/vkarpov15/kareem.git" - }, - "scripts": { - "test": "mocha ./test/*", - "test-travis": "nyc mocha ./test/*" - }, - "version": "2.3.1" -} diff --git a/node_modules/kareem/test/examples.test.js b/node_modules/kareem/test/examples.test.js deleted file mode 100644 index f120723..0000000 --- a/node_modules/kareem/test/examples.test.js +++ /dev/null @@ -1,379 +0,0 @@ -var assert = require('assert'); -var Kareem = require('../'); - -/* Much like [hooks](https://npmjs.org/package/hooks), kareem lets you define - * pre and post hooks: pre hooks are called before a given function executes. - * Unlike hooks, kareem stores hooks and other internal state in a separate - * object, rather than relying on inheritance. Furthermore, kareem exposes - * an `execPre()` function that allows you to execute your pre hooks when - * appropriate, giving you more fine-grained control over your function hooks. - */ -describe('pre hooks', function() { - var hooks; - - beforeEach(function() { - hooks = new Kareem(); - }); - - it('runs without any hooks specified', function(done) { - hooks.execPre('cook', null, function() { - done(); - }); - }); - - /* pre hook functions take one parameter, a "done" function that you execute - * when your pre hook is finished. - */ - it('runs basic serial pre hooks', function(done) { - var count = 0; - - hooks.pre('cook', function(done) { - ++count; - done(); - }); - - hooks.execPre('cook', null, function() { - assert.equal(1, count); - done(); - }); - }); - - it('can run multipe pre hooks', function(done) { - var count1 = 0; - var count2 = 0; - - hooks.pre('cook', function(done) { - ++count1; - done(); - }); - - hooks.pre('cook', function(done) { - ++count2; - done(); - }); - - hooks.execPre('cook', null, function() { - assert.equal(1, count1); - assert.equal(1, count2); - done(); - }); - }); - - /* If your pre hook function takes no parameters, its assumed to be - * fully synchronous. - */ - it('can run fully synchronous pre hooks', function(done) { - var count1 = 0; - var count2 = 0; - - hooks.pre('cook', function() { - ++count1; - }); - - hooks.pre('cook', function() { - ++count2; - }); - - hooks.execPre('cook', null, function(error) { - assert.equal(null, error); - assert.equal(1, count1); - assert.equal(1, count2); - done(); - }); - }); - - /* Pre save hook functions are bound to the second parameter to `execPre()` - */ - it('properly attaches context to pre hooks', function(done) { - hooks.pre('cook', function(done) { - this.bacon = 3; - done(); - }); - - hooks.pre('cook', function(done) { - this.eggs = 4; - done(); - }); - - var obj = { bacon: 0, eggs: 0 }; - - // In the pre hooks, `this` will refer to `obj` - hooks.execPre('cook', obj, function(error) { - assert.equal(null, error); - assert.equal(3, obj.bacon); - assert.equal(4, obj.eggs); - done(); - }); - }); - - /* Like the hooks module, you can declare "async" pre hooks - these take two - * parameters, the functions `next()` and `done()`. `next()` passes control to - * the next pre hook, but the underlying function won't be called until all - * async pre hooks have called `done()`. - */ - it('can execute parallel (async) pre hooks', function(done) { - hooks.pre('cook', true, function(next, done) { - this.bacon = 3; - next(); - setTimeout(function() { - done(); - }, 5); - }); - - hooks.pre('cook', true, function(next, done) { - next(); - var _this = this; - setTimeout(function() { - _this.eggs = 4; - done(); - }, 10); - }); - - hooks.pre('cook', function(next) { - this.waffles = false; - next(); - }); - - var obj = { bacon: 0, eggs: 0 }; - - hooks.execPre('cook', obj, function() { - assert.equal(3, obj.bacon); - assert.equal(4, obj.eggs); - assert.equal(false, obj.waffles); - done(); - }); - }); - - /* You can also return a promise from your pre hooks instead of calling - * `next()`. When the returned promise resolves, kareem will kick off the - * next middleware. - */ - it('supports returning a promise', function(done) { - hooks.pre('cook', function() { - return new Promise(resolve => { - setTimeout(() => { - this.bacon = 3; - resolve(); - }, 100); - }); - }); - - var obj = { bacon: 0 }; - - hooks.execPre('cook', obj, function() { - assert.equal(3, obj.bacon); - done(); - }); - }); -}); - -describe('post hooks', function() { - var hooks; - - beforeEach(function() { - hooks = new Kareem(); - }); - - it('runs without any hooks specified', function(done) { - hooks.execPost('cook', null, [1], function(error, eggs) { - assert.ifError(error); - assert.equal(1, eggs); - done(); - }); - }); - - it('executes with parameters passed in', function(done) { - hooks.post('cook', function(eggs, bacon, callback) { - assert.equal(1, eggs); - assert.equal(2, bacon); - callback(); - }); - - hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { - assert.ifError(error); - assert.equal(1, eggs); - assert.equal(2, bacon); - done(); - }); - }); - - it('can use synchronous post hooks', function(done) { - var execed = {}; - - hooks.post('cook', function(eggs, bacon) { - execed.first = true; - assert.equal(1, eggs); - assert.equal(2, bacon); - }); - - hooks.post('cook', function(eggs, bacon, callback) { - execed.second = true; - assert.equal(1, eggs); - assert.equal(2, bacon); - callback(); - }); - - hooks.execPost('cook', null, [1, 2], function(error, eggs, bacon) { - assert.ifError(error); - assert.equal(2, Object.keys(execed).length); - assert.ok(execed.first); - assert.ok(execed.second); - assert.equal(1, eggs); - assert.equal(2, bacon); - done(); - }); - }); -}); - -describe('wrap()', function() { - var hooks; - - beforeEach(function() { - hooks = new Kareem(); - }); - - it('wraps pre and post calls into one call', function(done) { - hooks.pre('cook', true, function(next, done) { - this.bacon = 3; - next(); - setTimeout(function() { - done(); - }, 5); - }); - - hooks.pre('cook', true, function(next, done) { - next(); - var _this = this; - setTimeout(function() { - _this.eggs = 4; - done(); - }, 10); - }); - - hooks.pre('cook', function(next) { - this.waffles = false; - next(); - }); - - hooks.post('cook', function(obj) { - obj.tofu = 'no'; - }); - - var obj = { bacon: 0, eggs: 0 }; - - var args = [obj]; - args.push(function(error, result) { - assert.ifError(error); - assert.equal(null, error); - assert.equal(3, obj.bacon); - assert.equal(4, obj.eggs); - assert.equal(false, obj.waffles); - assert.equal('no', obj.tofu); - - assert.equal(obj, result); - done(); - }); - - hooks.wrap( - 'cook', - function(o, callback) { - assert.equal(3, obj.bacon); - assert.equal(4, obj.eggs); - assert.equal(false, obj.waffles); - assert.equal(undefined, obj.tofu); - callback(null, o); - }, - obj, - args); - }); -}); - -describe('createWrapper()', function() { - var hooks; - - beforeEach(function() { - hooks = new Kareem(); - }); - - it('wraps wrap() into a callable function', function(done) { - hooks.pre('cook', true, function(next, done) { - this.bacon = 3; - next(); - setTimeout(function() { - done(); - }, 5); - }); - - hooks.pre('cook', true, function(next, done) { - next(); - var _this = this; - setTimeout(function() { - _this.eggs = 4; - done(); - }, 10); - }); - - hooks.pre('cook', function(next) { - this.waffles = false; - next(); - }); - - hooks.post('cook', function(obj) { - obj.tofu = 'no'; - }); - - var obj = { bacon: 0, eggs: 0 }; - - var cook = hooks.createWrapper( - 'cook', - function(o, callback) { - assert.equal(3, obj.bacon); - assert.equal(4, obj.eggs); - assert.equal(false, obj.waffles); - assert.equal(undefined, obj.tofu); - callback(null, o); - }, - obj); - - cook(obj, function(error, result) { - assert.ifError(error); - assert.equal(3, obj.bacon); - assert.equal(4, obj.eggs); - assert.equal(false, obj.waffles); - assert.equal('no', obj.tofu); - - assert.equal(obj, result); - done(); - }); - }); -}); - -describe('clone()', function() { - it('clones a Kareem object', function() { - var k1 = new Kareem(); - k1.pre('cook', function() {}); - k1.post('cook', function() {}); - - var k2 = k1.clone(); - assert.deepEqual(Array.from(k2._pres.keys()), ['cook']); - assert.deepEqual(Array.from(k2._posts.keys()), ['cook']); - }); -}); - -describe('merge()', function() { - it('pulls hooks from another Kareem object', function() { - var k1 = new Kareem(); - var test1 = function() {}; - k1.pre('cook', test1); - k1.post('cook', function() {}); - - var k2 = new Kareem(); - var test2 = function() {}; - k2.pre('cook', test2); - var k3 = k2.merge(k1); - assert.equal(k3._pres.get('cook').length, 2); - assert.equal(k3._pres.get('cook')[0].fn, test2); - assert.equal(k3._pres.get('cook')[1].fn, test1); - assert.equal(k3._posts.get('cook').length, 1); - }); -}); diff --git a/node_modules/kareem/test/misc.test.js b/node_modules/kareem/test/misc.test.js deleted file mode 100644 index 531b1d4..0000000 --- a/node_modules/kareem/test/misc.test.js +++ /dev/null @@ -1,71 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const Kareem = require('../'); - -describe('hasHooks', function() { - it('returns false for toString (Automattic/mongoose#6538)', function() { - const k = new Kareem(); - assert.ok(!k.hasHooks('toString')); - }); -}); - -describe('merge', function() { - it('handles async pres if source doesnt have them', function() { - const k1 = new Kareem(); - k1.pre('cook', true, function(next, done) { - execed.first = true; - setTimeout( - function() { - done('error!'); - }, - 5); - - next(); - }); - - assert.equal(k1._pres.get('cook').numAsync, 1); - - const k2 = new Kareem(); - const k3 = k2.merge(k1); - assert.equal(k3._pres.get('cook').numAsync, 1); - }); -}); - -describe('filter', function() { - it('returns clone with only hooks that match `fn()`', function() { - const k1 = new Kareem(); - - k1.pre('update', { document: true }, f1); - k1.pre('update', { query: true }, f2); - k1.pre('remove', { document: true }, f3); - - k1.post('update', { document: true }, f1); - k1.post('update', { query: true }, f2); - k1.post('remove', { document: true }, f3); - - const k2 = k1.filter(hook => hook.document); - assert.equal(k2._pres.get('update').length, 1); - assert.equal(k2._pres.get('update')[0].fn, f1); - assert.equal(k2._pres.get('remove').length, 1); - assert.equal(k2._pres.get('remove')[0].fn, f3); - - assert.equal(k2._posts.get('update').length, 1); - assert.equal(k2._posts.get('update')[0].fn, f1); - assert.equal(k2._posts.get('remove').length, 1); - assert.equal(k2._posts.get('remove')[0].fn, f3); - - const k3 = k1.filter(hook => hook.query); - assert.equal(k3._pres.get('update').length, 1); - assert.equal(k3._pres.get('update')[0].fn, f2); - assert.ok(!k3._pres.has('remove')); - - assert.equal(k3._posts.get('update').length, 1); - assert.equal(k3._posts.get('update')[0].fn, f2); - assert.ok(!k3._posts.has('remove')); - - function f1() {} - function f2() {} - function f3() {} - }); -}); diff --git a/node_modules/kareem/test/post.test.js b/node_modules/kareem/test/post.test.js deleted file mode 100644 index b9a776d..0000000 --- a/node_modules/kareem/test/post.test.js +++ /dev/null @@ -1,198 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const Kareem = require('../'); - -describe('execPost', function() { - var hooks; - - beforeEach(function() { - hooks = new Kareem(); - }); - - it('handles errors', function(done) { - hooks.post('cook', function(eggs, callback) { - callback('error!'); - }); - - hooks.execPost('cook', null, [4], function(error, eggs) { - assert.equal('error!', error); - assert.ok(!eggs); - done(); - }); - }); - - it('unshift', function() { - var f1 = function() {}; - var f2 = function() {}; - hooks.post('cook', f1); - hooks.post('cook', f2, true); - assert.strictEqual(hooks._posts.get('cook')[0].fn, f2); - assert.strictEqual(hooks._posts.get('cook')[1].fn, f1); - }); - - it('arbitrary options', function() { - const f1 = function() {}; - const f2 = function() {}; - hooks.post('cook', { foo: 'bar' }, f1); - hooks.post('cook', { bar: 'baz' }, f2, true); - assert.equal(hooks._posts.get('cook')[1].foo, 'bar'); - assert.equal(hooks._posts.get('cook')[0].bar, 'baz'); - }); - - it('throws error if no function', function() { - assert.throws(() => hooks.post('test'), /got "undefined"/); - }); - - it('multiple posts', function(done) { - hooks.post('cook', function(eggs, callback) { - setTimeout( - function() { - callback(); - }, - 5); - }); - - hooks.post('cook', function(eggs, callback) { - setTimeout( - function() { - callback(); - }, - 5); - }); - - hooks.execPost('cook', null, [4], function(error, eggs) { - assert.ifError(error); - assert.equal(4, eggs); - done(); - }); - }); - - it('error posts', function(done) { - var called = {}; - hooks.post('cook', function(eggs, callback) { - called.first = true; - callback(); - }); - - hooks.post('cook', function(eggs, callback) { - called.second = true; - callback(new Error('fail')); - }); - - hooks.post('cook', function(eggs, callback) { - assert.ok(false); - }); - - hooks.post('cook', function(error, eggs, callback) { - called.fourth = true; - assert.equal(error.message, 'fail'); - callback(new Error('fourth')); - }); - - hooks.post('cook', function(error, eggs, callback) { - called.fifth = true; - assert.equal(error.message, 'fourth'); - callback(new Error('fifth')); - }); - - hooks.execPost('cook', null, [4], function(error, eggs) { - assert.ok(error); - assert.equal(error.message, 'fifth'); - assert.deepEqual(called, { - first: true, - second: true, - fourth: true, - fifth: true - }); - done(); - }); - }); - - it('error posts with initial error', function(done) { - var called = {}; - - hooks.post('cook', function(eggs, callback) { - assert.ok(false); - }); - - hooks.post('cook', function(error, eggs, callback) { - called.second = true; - assert.equal(error.message, 'fail'); - callback(new Error('second')); - }); - - hooks.post('cook', function(error, eggs, callback) { - called.third = true; - assert.equal(error.message, 'second'); - callback(new Error('third')); - }); - - hooks.post('cook', function(error, eggs, callback) { - called.fourth = true; - assert.equal(error.message, 'third'); - callback(); - }); - - var options = { error: new Error('fail') }; - hooks.execPost('cook', null, [4], options, function(error, eggs) { - assert.ok(error); - assert.equal(error.message, 'third'); - assert.deepEqual(called, { - second: true, - third: true, - fourth: true - }); - done(); - }); - }); - - it('supports returning a promise', function(done) { - var calledPost = 0; - - hooks.post('cook', function() { - return new Promise(resolve => { - setTimeout(() => { - ++calledPost; - resolve(); - }, 100); - }); - }); - - hooks.execPost('cook', null, [], {}, function(error) { - assert.ifError(error); - assert.equal(calledPost, 1); - done(); - }); - }); -}); - -describe('execPostSync', function() { - var hooks; - - beforeEach(function() { - hooks = new Kareem(); - }); - - it('executes hooks synchronously', function() { - var execed = {}; - - hooks.post('cook', function() { - execed.first = true; - }); - - hooks.post('cook', function() { - execed.second = true; - }); - - hooks.execPostSync('cook', null); - assert.ok(execed.first); - assert.ok(execed.second); - }); - - it('works with no hooks specified', function() { - assert.doesNotThrow(function() { - hooks.execPostSync('cook', null); - }); - }); -}); diff --git a/node_modules/kareem/test/pre.test.js b/node_modules/kareem/test/pre.test.js deleted file mode 100644 index d908d67..0000000 --- a/node_modules/kareem/test/pre.test.js +++ /dev/null @@ -1,320 +0,0 @@ -'use strict'; - -const assert = require('assert'); -const Kareem = require('../'); - -describe('execPre', function() { - var hooks; - - beforeEach(function() { - hooks = new Kareem(); - }); - - it('handles errors with multiple pres', function(done) { - var execed = {}; - - hooks.pre('cook', function(done) { - execed.first = true; - done(); - }); - - hooks.pre('cook', function(done) { - execed.second = true; - done('error!'); - }); - - hooks.pre('cook', function(done) { - execed.third = true; - done(); - }); - - hooks.execPre('cook', null, function(err) { - assert.equal('error!', err); - assert.equal(2, Object.keys(execed).length); - assert.ok(execed.first); - assert.ok(execed.second); - done(); - }); - }); - - it('sync errors', function(done) { - var called = 0; - - hooks.pre('cook', function(next) { - throw new Error('woops!'); - }); - - hooks.pre('cook', function(next) { - ++called; - next(); - }); - - hooks.execPre('cook', null, function(err) { - assert.equal(err.message, 'woops!'); - assert.equal(called, 0); - done(); - }); - }); - - it('unshift', function() { - var f1 = function() {}; - var f2 = function() {}; - hooks.pre('cook', false, f1); - hooks.pre('cook', false, f2, null, true); - assert.strictEqual(hooks._pres.get('cook')[0].fn, f2); - assert.strictEqual(hooks._pres.get('cook')[1].fn, f1); - }); - - it('throws error if no function', function() { - assert.throws(() => hooks.pre('test'), /got "undefined"/); - }); - - it('arbitrary options', function() { - const f1 = function() {}; - const f2 = function() {}; - hooks.pre('cook', { foo: 'bar' }, f1); - hooks.pre('cook', { bar: 'baz' }, f2, null, true); - assert.equal(hooks._pres.get('cook')[1].foo, 'bar'); - assert.equal(hooks._pres.get('cook')[0].bar, 'baz'); - }); - - it('handles async errors', function(done) { - var execed = {}; - - hooks.pre('cook', true, function(next, done) { - execed.first = true; - setTimeout( - function() { - done('error!'); - }, - 5); - - next(); - }); - - hooks.pre('cook', true, function(next, done) { - execed.second = true; - setTimeout( - function() { - done('other error!'); - }, - 10); - - next(); - }); - - hooks.execPre('cook', null, function(err) { - assert.equal('error!', err); - assert.equal(2, Object.keys(execed).length); - assert.ok(execed.first); - assert.ok(execed.second); - done(); - }); - }); - - it('handles async errors in next()', function(done) { - var execed = {}; - - hooks.pre('cook', true, function(next, done) { - execed.first = true; - setTimeout( - function() { - done('other error!'); - }, - 15); - - next(); - }); - - hooks.pre('cook', true, function(next, done) { - execed.second = true; - setTimeout( - function() { - next('error!'); - done('another error!'); - }, - 5); - }); - - hooks.execPre('cook', null, function(err) { - assert.equal('error!', err); - assert.equal(2, Object.keys(execed).length); - assert.ok(execed.first); - assert.ok(execed.second); - done(); - }); - }); - - it('handles async errors in next() when already done', function(done) { - var execed = {}; - - hooks.pre('cook', true, function(next, done) { - execed.first = true; - setTimeout( - function() { - done('other error!'); - }, - 5); - - next(); - }); - - hooks.pre('cook', true, function(next, done) { - execed.second = true; - setTimeout( - function() { - next('error!'); - done('another error!'); - }, - 25); - }); - - hooks.execPre('cook', null, function(err) { - assert.equal('other error!', err); - assert.equal(2, Object.keys(execed).length); - assert.ok(execed.first); - assert.ok(execed.second); - done(); - }); - }); - - it('async pres with clone()', function(done) { - var execed = false; - - hooks.pre('cook', true, function(next, done) { - execed = true; - setTimeout( - function() { - done(); - }, - 5); - - next(); - }); - - hooks.clone().execPre('cook', null, function(err) { - assert.ifError(err); - assert.ok(execed); - done(); - }); - }); - - it('returns correct error when async pre errors', function(done) { - var execed = {}; - - hooks.pre('cook', true, function(next, done) { - execed.first = true; - setTimeout( - function() { - done('other error!'); - }, - 5); - - next(); - }); - - hooks.pre('cook', function(next) { - execed.second = true; - setTimeout( - function() { - next('error!'); - }, - 15); - }); - - hooks.execPre('cook', null, function(err) { - assert.equal('other error!', err); - assert.equal(2, Object.keys(execed).length); - assert.ok(execed.first); - assert.ok(execed.second); - done(); - }); - }); - - it('lets async pres run when fully sync pres are done', function(done) { - var execed = {}; - - hooks.pre('cook', true, function(next, done) { - execed.first = true; - setTimeout( - function() { - done(); - }, - 5); - - next(); - }); - - hooks.pre('cook', function() { - execed.second = true; - }); - - hooks.execPre('cook', null, function(err) { - assert.ifError(err); - assert.equal(2, Object.keys(execed).length); - assert.ok(execed.first); - assert.ok(execed.second); - done(); - }); - }); - - it('allows passing arguments to the next pre', function(done) { - var execed = {}; - - hooks.pre('cook', function(next) { - execed.first = true; - next(null, 'test'); - }); - - hooks.pre('cook', function(next, p) { - execed.second = true; - assert.equal(p, 'test'); - next(); - }); - - hooks.pre('cook', function(next, p) { - execed.third = true; - assert.ok(!p); - next(); - }); - - hooks.execPre('cook', null, function(err) { - assert.ifError(err); - assert.equal(3, Object.keys(execed).length); - assert.ok(execed.first); - assert.ok(execed.second); - assert.ok(execed.third); - done(); - }); - }); -}); - -describe('execPreSync', function() { - var hooks; - - beforeEach(function() { - hooks = new Kareem(); - }); - - it('executes hooks synchronously', function() { - var execed = {}; - - hooks.pre('cook', function() { - execed.first = true; - }); - - hooks.pre('cook', function() { - execed.second = true; - }); - - hooks.execPreSync('cook', null); - assert.ok(execed.first); - assert.ok(execed.second); - }); - - it('works with no hooks specified', function() { - assert.doesNotThrow(function() { - hooks.execPreSync('cook', null); - }); - }); -}); diff --git a/node_modules/kareem/test/wrap.test.js b/node_modules/kareem/test/wrap.test.js deleted file mode 100644 index dd9196e..0000000 --- a/node_modules/kareem/test/wrap.test.js +++ /dev/null @@ -1,342 +0,0 @@ -var assert = require('assert'); -var Kareem = require('../'); - -describe('wrap()', function() { - var hooks; - - beforeEach(function() { - hooks = new Kareem(); - }); - - it('handles pre errors', function(done) { - hooks.pre('cook', function(done) { - done('error!'); - }); - - hooks.post('cook', function(obj) { - obj.tofu = 'no'; - }); - - var obj = { bacon: 0, eggs: 0 }; - - var args = [obj]; - args.push(function(error, result) { - assert.equal('error!', error); - assert.ok(!result); - assert.equal(undefined, obj.tofu); - done(); - }); - - hooks.wrap( - 'cook', - function(o, callback) { - // Should never get called - assert.ok(false); - callback(null, o); - }, - obj, - args); - }); - - it('handles pre errors when no callback defined', function(done) { - hooks.pre('cook', function(done) { - done('error!'); - }); - - hooks.post('cook', function(obj) { - obj.tofu = 'no'; - }); - - var obj = { bacon: 0, eggs: 0 }; - - var args = [obj]; - - hooks.wrap( - 'cook', - function(o, callback) { - // Should never get called - assert.ok(false); - callback(null, o); - }, - obj, - args); - - setTimeout( - function() { - done(); - }, - 25); - }); - - it('handles errors in wrapped function', function(done) { - hooks.pre('cook', function(done) { - done(); - }); - - hooks.post('cook', function(obj) { - obj.tofu = 'no'; - }); - - var obj = { bacon: 0, eggs: 0 }; - - var args = [obj]; - args.push(function(error, result) { - assert.equal('error!', error); - assert.ok(!result); - assert.equal(undefined, obj.tofu); - done(); - }); - - hooks.wrap( - 'cook', - function(o, callback) { - callback('error!'); - }, - obj, - args); - }); - - it('handles errors in post', function(done) { - hooks.pre('cook', function(done) { - done(); - }); - - hooks.post('cook', function(obj, callback) { - obj.tofu = 'no'; - callback('error!'); - }); - - var obj = { bacon: 0, eggs: 0 }; - - var args = [obj]; - args.push(function(error, result) { - assert.equal('error!', error); - assert.ok(!result); - assert.equal('no', obj.tofu); - done(); - }); - - hooks.wrap( - 'cook', - function(o, callback) { - callback(null, o); - }, - obj, - args); - }); - - it('defers errors to post hooks if enabled', function(done) { - hooks.pre('cook', function(done) { - done(new Error('fail')); - }); - - hooks.post('cook', function(error, res, callback) { - callback(new Error('another error occurred')); - }); - - var args = []; - args.push(function(error) { - assert.equal(error.message, 'another error occurred'); - done(); - }); - - hooks.wrap( - 'cook', - function(callback) { - assert.ok(false); - callback(); - }, - null, - args, - { useErrorHandlers: true, numCallbackParams: 1 }); - }); - - it('error handlers with no callback', function(done) { - hooks.pre('cook', function(done) { - done(new Error('fail')); - }); - - hooks.post('cook', function(error, callback) { - assert.equal(error.message, 'fail'); - done(); - }); - - var args = []; - - hooks.wrap( - 'cook', - function(callback) { - assert.ok(false); - callback(); - }, - null, - args, - { useErrorHandlers: true }); - }); - - it('error handlers with no error', function(done) { - hooks.post('cook', function(error, callback) { - callback(new Error('another error occurred')); - }); - - var args = []; - args.push(function(error) { - assert.ifError(error); - done(); - }); - - hooks.wrap( - 'cook', - function(callback) { - callback(); - }, - null, - args, - { useErrorHandlers: true }); - }); - - it('works with no args', function(done) { - hooks.pre('cook', function(done) { - done(); - }); - - hooks.post('cook', function(callback) { - obj.tofu = 'no'; - callback(); - }); - - var obj = { bacon: 0, eggs: 0 }; - - var args = []; - - hooks.wrap( - 'cook', - function(callback) { - callback(null); - }, - obj, - args); - - setTimeout( - function() { - assert.equal('no', obj.tofu); - done(); - }, - 25); - }); - - it('handles pre errors with no args', function(done) { - hooks.pre('cook', function(done) { - done('error!'); - }); - - hooks.post('cook', function(callback) { - obj.tofu = 'no'; - callback(); - }); - - var obj = { bacon: 0, eggs: 0 }; - - var args = []; - - hooks.wrap( - 'cook', - function(callback) { - callback(null); - }, - obj, - args); - - setTimeout( - function() { - assert.equal(undefined, obj.tofu); - done(); - }, - 25); - }); - - it('handles wrapped function errors with no args', function(done) { - hooks.pre('cook', function(done) { - obj.waffles = false; - done(); - }); - - hooks.post('cook', function(callback) { - obj.tofu = 'no'; - callback(); - }); - - var obj = { bacon: 0, eggs: 0 }; - - var args = []; - - hooks.wrap( - 'cook', - function(callback) { - callback('error!'); - }, - obj, - args); - - setTimeout( - function() { - assert.equal(false, obj.waffles); - assert.equal(undefined, obj.tofu); - done(); - }, - 25); - }); - - it('handles post errors with no args', function(done) { - hooks.pre('cook', function(done) { - obj.waffles = false; - done(); - }); - - hooks.post('cook', function(callback) { - obj.tofu = 'no'; - callback('error!'); - }); - - var obj = { bacon: 0, eggs: 0 }; - - var args = []; - - hooks.wrap( - 'cook', - function(callback) { - callback(); - }, - obj, - args); - - setTimeout( - function() { - assert.equal(false, obj.waffles); - assert.equal('no', obj.tofu); - done(); - }, - 25); - }); - - it('sync wrappers', function() { - var calledPre = 0; - var calledFn = 0; - var calledPost = 0; - hooks.pre('cook', function() { - ++calledPre; - }); - - hooks.post('cook', function() { - ++calledPost; - }); - - var wrapper = hooks.createWrapperSync('cook', function() { ++calledFn; }); - - wrapper(); - - assert.equal(calledPre, 1); - assert.equal(calledFn, 1); - assert.equal(calledPost, 1); - }); -}); diff --git a/node_modules/kerberos/.clang-format b/node_modules/kerberos/.clang-format deleted file mode 100644 index 5b30f57..0000000 --- a/node_modules/kerberos/.clang-format +++ /dev/null @@ -1,15 +0,0 @@ -BasedOnStyle: Google -AllowShortFunctionsOnASingleLine: Empty -AllowShortIfStatementsOnASingleLine: false -AllowShortLoopsOnASingleLine: false -BinPackArguments: false -BinPackParameters: false -ColumnLimit: 100 -Cpp11BracedListStyle: true -DerivePointerAlignment: false -IndentWidth: 4 -MaxEmptyLinesToKeep: 1 -NamespaceIndentation: None -SpaceBeforeAssignmentOperators: true -Standard: Cpp11 -UseTab: Never diff --git a/node_modules/kerberos/.eslintrc b/node_modules/kerberos/.eslintrc deleted file mode 100644 index cd93e8b..0000000 --- a/node_modules/kerberos/.eslintrc +++ /dev/null @@ -1,30 +0,0 @@ -{ - "extends": [ - "eslint:recommended" - ], - "env": { - "node": true, - "mocha": true, - "es6": true - }, - "globals": { - "Promise": true - }, - "parserOptions": { - "ecmaVersion": 2017 - }, - "plugins": [ - "prettier" - ], - "rules": { - "prettier/prettier": ["error", { - "singleQuote": true, - "tabWidth": 2, - "printWidth": 100 - }], - - "no-console": 0, - "eqeqeq": ["error", "always", {"null": "ignore"}], - "strict": ["error", "global"] - } -} diff --git a/node_modules/kerberos/.travis.yml b/node_modules/kerberos/.travis.yml deleted file mode 100644 index c5cbe86..0000000 --- a/node_modules/kerberos/.travis.yml +++ /dev/null @@ -1,28 +0,0 @@ -sudo: required - -language: generic - -services: - - docker - -matrix: - include: - - env: NODE_VERSION=4 - - env: NODE_VERSION=6 - - env: NODE_VERSION=8 - - env: NODE_VERSION=10 - - env: NODE_VERSION=12 - -script: -- > - docker run - -i - -v $(pwd):/app - -w /app - -e NODE_VERSION=$NODE_VERSION - -e KERBEROS_USERNAME=administrator - -e KERBEROS_PASSWORD=Password01 - -e KERBEROS_REALM=example.com - -e KERBEROS_PORT=80 - ubuntu:16.04 - /bin/bash ./test/scripts/travis.sh diff --git a/node_modules/kerberos/CHANGELOG.md b/node_modules/kerberos/CHANGELOG.md deleted file mode 100644 index e01725d..0000000 --- a/node_modules/kerberos/CHANGELOG.md +++ /dev/null @@ -1,44 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - - -# [1.0.0](https://github.com/christkv/kerberos/compare/v0.0.24...v1.0.0) (2018-08-15) - - -### Bug Fixes - -* **check-password:** correctly validate parameters, fix test ([b772dde](https://github.com/christkv/kerberos/commit/b772dde)) -* **common:** ensure nan is being included everywhere appropriately ([7bddb24](https://github.com/christkv/kerberos/commit/7bddb24)) -* **context:** add `NewInstance` methods, and make getters safer ([fd4b852](https://github.com/christkv/kerberos/commit/fd4b852)) -* **gss:** fix issue with memory corruption ([ff4167e](https://github.com/christkv/kerberos/commit/ff4167e)) -* **kerberos:** provide default gss flags ([b365934](https://github.com/christkv/kerberos/commit/b365934)) -* **legacy:** support legacy import expectations ([615b23f](https://github.com/christkv/kerberos/commit/615b23f)) -* **response:** ensure null or client/server response is returned ([083518f](https://github.com/christkv/kerberos/commit/083518f)) -* **server:** use the correct internal method name for server init ([8c8dd35](https://github.com/christkv/kerberos/commit/8c8dd35)) -* **this:** use the correct reference to `this` for object unwrapping ([1acfb20](https://github.com/christkv/kerberos/commit/1acfb20)) -* **unique_ptr:** ensure we include where required ([e3d9afb](https://github.com/christkv/kerberos/commit/e3d9afb)) -* **warnings:** set clang compiler pragmas only when clang is detected ([048479d](https://github.com/christkv/kerberos/commit/048479d)) -* **win32:** `windows` -> `win32` in bindings.gyp ([0221c06](https://github.com/christkv/kerberos/commit/0221c06)) -* **win32:** cleanup client state in addon destructor ([5394561](https://github.com/christkv/kerberos/commit/5394561)) -* **win32:** initialize with a domain, if one is provided ([309ba61](https://github.com/christkv/kerberos/commit/309ba61)) - - -### Features - -* **async-worker:** introduce a `KerberosWorker` using lambdas ([1239ef7](https://github.com/christkv/kerberos/commit/1239ef7)) -* **checkPassword:** add implementation for checking krb5 passwords ([60f476e](https://github.com/christkv/kerberos/commit/60f476e)) -* **clean:** provide implementations for the clean methods ([77a77ce](https://github.com/christkv/kerberos/commit/77a77ce)) -* **client:** add final wrap/unwrap api endpoints ([016222f](https://github.com/christkv/kerberos/commit/016222f)) -* **client:** add implementation for client wrap/unwrap to win32 ([994604c](https://github.com/christkv/kerberos/commit/994604c)) -* **gss:** add `new` methods for constructing state tracking types ([274cad6](https://github.com/christkv/kerberos/commit/274cad6)) -* **jsdoc2md:** add jsdoc2md support, and README template ([60e1ee5](https://github.com/christkv/kerberos/commit/60e1ee5)) -* **kerberos:** add getters to check for context completeness ([6a9a01d](https://github.com/christkv/kerberos/commit/6a9a01d)) -* **kerberos:** implement client/server init, move to worker file ([1c857ea](https://github.com/christkv/kerberos/commit/1c857ea)) -* **kerberos:** return value for `step` is the challenge response ([e153d24](https://github.com/christkv/kerberos/commit/e153d24)) -* **promises:** allow to access all API by promise or callback ([3b77430](https://github.com/christkv/kerberos/commit/3b77430)) -* **serverPrincipalDetails:** add server pricipal details method ([385fcd1](https://github.com/christkv/kerberos/commit/385fcd1)) -* **src:** begin to develop the new version of the module in `src` ([f45da50](https://github.com/christkv/kerberos/commit/f45da50)) -* **sspi:** introduce client initialization for SSPI ([6a40301](https://github.com/christkv/kerberos/commit/6a40301)) -* **sspi:** provide implementation for `initializeClient` ([5943f1c](https://github.com/christkv/kerberos/commit/5943f1c)) -* **step:** implement client and server step methods ([5a4327c](https://github.com/christkv/kerberos/commit/5a4327c)) diff --git a/node_modules/kerberos/HISTORY.md b/node_modules/kerberos/HISTORY.md deleted file mode 100644 index 1e27e77..0000000 --- a/node_modules/kerberos/HISTORY.md +++ /dev/null @@ -1,85 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - - -## [1.1.3](https://github.com/mongodb-js/kerberos/compare/v1.2.0...v1.1.3) (2019-08-27) - - -### Bug Fixes - -* add support for node 12 ([ae6755d](https://github.com/mongodb-js/kerberos/commit/ae6755d)) - - - - -## [1.1.2](https://github.com/mongodb-js/kerberos/compare/v1.1.1...v1.1.2) (2018-11-01) - - -### Bug Fixes - -* **auth-process:** only send username/password if provided ([334ca9c](https://github.com/mongodb-js/kerberos/commit/334ca9c)) -* **auth-process:** use canonicalized hostname in client init ([b1802d1](https://github.com/mongodb-js/kerberos/commit/b1802d1)) - - - - -## [1.1.1](https://github.com/mongodb-js/kerberos/compare/v1.1.0...v1.1.1) (2018-10-30) - - -### Bug Fixes - -* **sspi:** only add password and domain if they are provided ([bc48814](https://github.com/mongodb-js/kerberos/commit/bc48814)) - - - - -# [1.1.0](https://github.com/mongodb-js/kerberos/compare/v1.0.0...v1.1.0) (2018-10-26) - - -### Bug Fixes - -* **sspi:** correct invalid null checks for user data ([163bdb9](https://github.com/mongodb-js/kerberos/commit/163bdb9)) - - -### Features - -* **package:** export the package version ([5be618f](https://github.com/mongodb-js/kerberos/commit/5be618f)) - - - -0.0.23 07-03-2017 ------------------ -- SSPI implemented missing _sspi_FreeCredentialsHandle to correctly cleanup credentials allocation on call to destructor of the C++ instance. -- Updated nan.h dependency to 2.5.x series for Node 7.6.x or higher. - -0.0.22 10-11-2016 ------------------ -- Updated nan.h dependency to 2.4.x series for Node 6.8.x or higher. -- The length calculations are off by one meaning it impossible to not set the password (Issue #54, http://www.github.com/tlbdk). - -0.0.21 04-28-2016 ------------------ -- Updated nan.h dependency to 2.3.x series for Node 6.0. - -0.0.20 04-26-2016 ------------------ -- Updated nan.h dependency to 2.2.x series. -- Fixed minor compilation warnings due to v8 C++ ABI changes. - -0.0.19 03-07-2016 ------------------ -- Fix installation error (Issue #1). -- Allow passing down off CANONICALIZE_HOST_NAME and SERVICE_REALM options. - -0.0.18 01-19-2016 ------------------ -- remove builderror.log. - -0.0.17 10-30-2015 ------------------ -- Reverted changes in package.json from 0.0.16. - -0.0.16 10-26-2015 ------------------ -- Removed (exit 0) on build to let correct failure happen. diff --git a/node_modules/kerberos/LICENSE b/node_modules/kerberos/LICENSE deleted file mode 100644 index 261eeb9..0000000 --- a/node_modules/kerberos/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/node_modules/kerberos/README.md b/node_modules/kerberos/README.md deleted file mode 100644 index ca2e365..0000000 --- a/node_modules/kerberos/README.md +++ /dev/null @@ -1,245 +0,0 @@ -Kerberos -======== -[![Build Status](https://travis-ci.org/mongodb-js/kerberos.svg?branch=master)](https://travis-ci.org/mongodb-js/kerberos) - -The `kerberos` package is a C++ extension for Node.js that provides cross-platform support for kerberos authentication using GSSAPI on linux/osx, and SSPI on windows. Much of the code in this module is adapted from [ccs-kerberos](https://github.com/apple/ccs-pykerberos) and [winkerberos](https://github.com/mongodb-labs/winkerberos). - -### Requirements - -**Linux** -- `python` v2.7 -- `make` -- A proper C/C++ compiler toolchain, like [GCC](https://gcc.gnu.org/) -- Distribution-specific kerberos packages (e.g. `krb5-dev` on Ubuntu) - -**macOS** -- `Xcode Command Line Tools`: Can be installed with `xcode-select --install` -- Distribution-specific kerberos packages (e.g. `krb5` on Homebrew) - -**Windows** -- **Option 1:** Install all the required tools and configurations using Microsoft's [windows-build-tools](https://github.com/felixrieseberg/windows-build-tools) by running `npm install -g windows-build-tools` from an elevated PowerShell (run as Administrator). -- **Option 2:** Install dependencies and configuration manually - 1. Visual C++ Build Environment: - * **Option 1:** Install [Visual C++ Build Tools](http://go.microsoft.com/fwlink/?LinkId=691126) using the *Default Install* option. - * **Option 2:** Install [Visual Studio 2015](https://www.visualstudio.com/products/visual-studio-community-vs) (or modify an existing installation) and select *Common Tools for Visual C++* during setup. - - > :bulb: [Windows Vista / 7 only] requires [.NET Framework 4.5.1](http://www.microsoft.com/en-us/download/details.aspx?id=40773) - - 2. Install [Python 2.7](https://www.python.org/downloads/) or [Miniconda 2.7](http://conda.pydata.org/miniconda.html) (`v3.x.x` is not supported), and run `npm config set python python2.7` - 3. Launch cmd, `npm config set msvs_version 2015` - -### Installation - -Now you can install `kerberos` with the following: - -```bash -npm install kerberos -``` - -### Testing - -Run the test suite using: - -```bash -npm test -``` - -NOTE: The test suite requires an active kerberos deployment, see `test/scripts/travis.sh` to better understand these requirements. - -# Documentation - -## Classes - -
-
KerberosClient
-
-
KerberosServer
-
-
- -## Functions - -
-
checkPassword(username, password, service, [defaultRealm], [callback])Promise
-

This function provides a simple way to verify that a user name and password -match those normally used for Kerberos authentication. -It does this by checking that the supplied user name and password can be -used to get a ticket for the supplied service. -If the user name does not contain a realm, then the default realm supplied -is used.

-

For this to work properly the Kerberos must be configured properly on this -machine. -That will likely mean ensuring that the edu.mit.Kerberos preference file -has the correct realms and KDCs listed.

-

IMPORTANT: This method is vulnerable to KDC spoofing attacks and it should -only be used for testing. Do not use this in any production system - your -security could be compromised if you do.

-
-
principalDetails(service, hostname, [callback])Promise
-

This function returns the service principal for the server given a service type and hostname.

-

Details are looked up via the /etc/keytab file.

-
-
initializeClient(service, [options], [callback])Promise
-

Initializes a context for client-side authentication with the given service principal.

-
-
initializeServer(service, [callback])Promise
-

Initializes a context for server-side authentication with the given service principal.

-
-
- - - -## KerberosClient -**Properties** - -| Name | Type | Description | -| --- | --- | --- | -| username | string | The username used for authentication | -| response | string | The last response received during authentication steps | -| responseConf | string | Indicates whether confidentiality was applied or not (GSSAPI only) | -| contextComplete | boolean | Indicates that authentication has successfully completed or not | - - -* [KerberosClient](#KerberosClient) - - * [.step(challenge, [callback])](#KerberosClient+step) - - * [.wrap(challenge, [options], [callback])](#KerberosClient+wrap) - - * [.unwrap(challenge, [callback])](#KerberosClient+unwrap) - - - - -### *kerberosClient*.step(challenge, [callback]) - -| Param | Type | Description | -| --- | --- | --- | -| challenge | string | A string containing the base64-encoded server data (which may be empty for the first step) | -| [callback] | function | | - -Processes a single kerberos client-side step using the supplied server challenge. - -**Returns**: Promise - returns Promise if no callback passed - - -### *kerberosClient*.wrap(challenge, [options], [callback]) - -| Param | Type | Description | -| --- | --- | --- | -| challenge | string | The response returned after calling `unwrap` | -| [options] | object | Optional settings | -| [options.user] | string | The user to authorize | -| [callback] | function | | - -Perform the client side kerberos wrap step. - -**Returns**: Promise - returns Promise if no callback passed - - -### *kerberosClient*.unwrap(challenge, [callback]) - -| Param | Type | Description | -| --- | --- | --- | -| challenge | string | A string containing the base64-encoded server data | -| [callback] | function | | - -Perform the client side kerberos unwrap step - -**Returns**: Promise - returns Promise if no callback passed - - -## KerberosServer -**Properties** - -| Name | Type | Description | -| --- | --- | --- | -| username | string | The username used for authentication | -| response | string | The last response received during authentication steps | -| targetName | string | The target used for authentication | -| contextComplete | boolean | Indicates that authentication has successfully completed or not | - - - -### *kerberosServer*.step(challenge, [callback]) - -| Param | Type | Description | -| --- | --- | --- | -| challenge | string | A string containing the base64-encoded client data | -| [callback] | function | | - -Processes a single kerberos server-side step using the supplied client data. - -**Returns**: Promise - returns Promise if no callback passed - - -## checkPassword(username, password, service, [defaultRealm], [callback]) - -| Param | Type | Description | -| --- | --- | --- | -| username | string | The Kerberos user name. If no realm is supplied, then the `defaultRealm` will be used. | -| password | string | The password for the user. | -| service | string | The Kerberos service to check access for. | -| [defaultRealm] | string | The default realm to use if one is not supplied in the user argument. | -| [callback] | function | | - -This function provides a simple way to verify that a user name and password -match those normally used for Kerberos authentication. -It does this by checking that the supplied user name and password can be -used to get a ticket for the supplied service. -If the user name does not contain a realm, then the default realm supplied -is used. - -For this to work properly the Kerberos must be configured properly on this -machine. -That will likely mean ensuring that the edu.mit.Kerberos preference file -has the correct realms and KDCs listed. - -IMPORTANT: This method is vulnerable to KDC spoofing attacks and it should -only be used for testing. Do not use this in any production system - your -security could be compromised if you do. - -**Returns**: Promise - returns Promise if no callback passed - - -## principalDetails(service, hostname, [callback]) - -| Param | Type | Description | -| --- | --- | --- | -| service | string | The Kerberos service type for the server. | -| hostname | string | The hostname of the server. | -| [callback] | function | | - -This function returns the service principal for the server given a service type and hostname. - -Details are looked up via the `/etc/keytab` file. - -**Returns**: Promise - returns Promise if no callback passed - - -## initializeClient(service, [options], [callback]) - -| Param | Type | Description | -| --- | --- | --- | -| service | string | A string containing the service principal in the form 'type@fqdn' (e.g. 'imap@mail.apple.com'). | -| [options] | object | Optional settings | -| [options.principal] | string | Optional string containing the client principal in the form 'user@realm' (e.g. 'jdoe@example.com'). | -| [options.gssFlags] | number | Optional integer used to set GSS flags. (e.g. GSS_C_DELEG_FLAG|GSS_C_MUTUAL_FLAG|GSS_C_SEQUENCE_FLAG will allow for forwarding credentials to the remote host) | -| [options.mechOID] | number | Optional GSS mech OID. Defaults to None (GSS_C_NO_OID). Other possible values are `GSS_MECH_OID_KRB5`, `GSS_MECH_OID_SPNEGO`. | -| [callback] | function | | - -Initializes a context for client-side authentication with the given service principal. - -**Returns**: Promise - returns Promise if no callback passed - - -## initializeServer(service, [callback]) - -| Param | Type | Description | -| --- | --- | --- | -| service | string | A string containing the service principal in the form 'type@fqdn' (e.g. 'imap@mail.apple.com'). | -| [callback] | function | | - -Initializes a context for server-side authentication with the given service principal. - -**Returns**: Promise - returns Promise if no callback passed diff --git a/node_modules/kerberos/appveyor.yml b/node_modules/kerberos/appveyor.yml deleted file mode 100644 index 7580084..0000000 --- a/node_modules/kerberos/appveyor.yml +++ /dev/null @@ -1,21 +0,0 @@ -version: "{build}" -build: off -skip_tags: true - -environment: - matrix: - - nodejs_version: "6" - - nodejs_version: "8" - - nodejs_version: "10" - -platform: - - x86 - - x64 - -install: - - ps: Install-Product node $env:nodejs_version $env:platform - - set PATH=%APPDATA%\npm;%APPVEYOR_BUILD_FOLDER%\node_modules\.bin;%PATH% - - npm i - -test_script: - - npm test diff --git a/node_modules/kerberos/binding.gyp b/node_modules/kerberos/binding.gyp deleted file mode 100644 index 43c7d9a..0000000 --- a/node_modules/kerberos/binding.gyp +++ /dev/null @@ -1,49 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'kerberos', - 'include_dirs': [ '> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_objc = CXX($(TOOLSET)) $@ -cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< - -quiet_cmd_objcxx = CXX($(TOOLSET)) $@ -cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< - -# Commands for precompiled header files. -quiet_cmd_pch_c = CXX($(TOOLSET)) $@ -cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< -quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ -cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< -quiet_cmd_pch_m = CXX($(TOOLSET)) $@ -cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< -quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ -cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< - -# gyp-mac-tool is written next to the root Makefile by gyp. -# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd -# already. -quiet_cmd_mac_tool = MACTOOL $(4) $< -cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" - -quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ -cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) - -quiet_cmd_infoplist = INFOPLIST $@ -cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = LIBTOOL-STATIC $@ -cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) - -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) - -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) - -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 2,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD - @$(call do_cmd,objc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD - @$(call do_cmd,objcxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,kerberos.target.mk)))),) - include kerberos.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/Users/kai/Desktop/node-course/dbproject/node_modules/kerberos/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/kai/Library/Caches/node-gyp/12.16.3" "-Dnode_gyp_dir=/usr/local/lib/node_modules/npm/node_modules/node-gyp" "-Dnode_lib_file=/Users/kai/Library/Caches/node-gyp/12.16.3/<(target_arch)/node.lib" "-Dmodule_root_dir=/Users/kai/Desktop/node-course/dbproject/node_modules/kerberos" "-Dnode_engine=v8" binding.gyp -Makefile: $(srcdir)/../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../Library/Caches/node-gyp/12.16.3/include/node/common.gypi - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d b/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d deleted file mode 100644 index ee7ca53..0000000 --- a/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/kerberos.node := c++ -bundle -stdlib=libc++ -undefined dynamic_lookup -Wl,-no_pie -Wl,-search_paths_first -mmacosx-version-min=10.7 -arch x86_64 -L./Release -stdlib=libc++ -o Release/kerberos.node Release/obj.target/kerberos/src/kerberos.o Release/obj.target/kerberos/src/unix/base64.o Release/obj.target/kerberos/src/unix/kerberos_gss.o Release/obj.target/kerberos/src/unix/kerberos_unix.o -lkrb5 -lgssapi_krb5 diff --git a/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/src/kerberos.o.d b/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/src/kerberos.o.d deleted file mode 100644 index 53a8c4b..0000000 --- a/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/src/kerberos.o.d +++ /dev/null @@ -1,61 +0,0 @@ -cmd_Release/obj.target/kerberos/src/kerberos.o := c++ '-DNODE_GYP_MODULE_NAME=kerberos' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-DBUILDING_NODE_EXTENSION' -I/Users/kai/Library/Caches/node-gyp/12.16.3/include/node -I/Users/kai/Library/Caches/node-gyp/12.16.3/src -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/openssl/config -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/openssl/openssl/include -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/uv/include -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/zlib -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/v8/include -I../../nan -Os -gdwarf-2 -mmacosx-version-min=10.7 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=gnu++1y -stdlib=libc++ -fno-exceptions -std=c++11 -stdlib=libc++ -MMD -MF ./Release/.deps/Release/obj.target/kerberos/src/kerberos.o.d.raw -c -o Release/obj.target/kerberos/src/kerberos.o ../src/kerberos.cc -Release/obj.target/kerberos/src/kerberos.o: ../src/kerberos.cc \ - ../src/kerberos.h ../../nan/nan.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node_version.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/errno.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/version.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/unix.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/threadpool.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/darwin.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8-internal.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8-version.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8config.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8-platform.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node_buffer.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node_object_wrap.h \ - ../../nan/nan_callbacks.h ../../nan/nan_callbacks_12_inl.h \ - ../../nan/nan_maybe_43_inl.h ../../nan/nan_converters.h \ - ../../nan/nan_converters_43_inl.h ../../nan/nan_new.h \ - ../../nan/nan_implementation_12_inl.h \ - ../../nan/nan_persistent_12_inl.h ../../nan/nan_weak.h \ - ../../nan/nan_object_wrap.h ../../nan/nan_private.h \ - ../../nan/nan_typedarray_contents.h ../../nan/nan_json.h \ - ../src/kerberos_common.h ../src/unix/kerberos_gss.h \ - ../src/kerberos_worker.h -../src/kerberos.cc: -../src/kerberos.h: -../../nan/nan.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node_version.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/errno.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/version.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/unix.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/threadpool.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/darwin.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8-internal.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8-version.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8config.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8-platform.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node_buffer.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node_object_wrap.h: -../../nan/nan_callbacks.h: -../../nan/nan_callbacks_12_inl.h: -../../nan/nan_maybe_43_inl.h: -../../nan/nan_converters.h: -../../nan/nan_converters_43_inl.h: -../../nan/nan_new.h: -../../nan/nan_implementation_12_inl.h: -../../nan/nan_persistent_12_inl.h: -../../nan/nan_weak.h: -../../nan/nan_object_wrap.h: -../../nan/nan_private.h: -../../nan/nan_typedarray_contents.h: -../../nan/nan_json.h: -../src/kerberos_common.h: -../src/unix/kerberos_gss.h: -../src/kerberos_worker.h: diff --git a/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/src/unix/base64.o.d b/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/src/unix/base64.o.d deleted file mode 100644 index 5bc75d9..0000000 --- a/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/src/unix/base64.o.d +++ /dev/null @@ -1,5 +0,0 @@ -cmd_Release/obj.target/kerberos/src/unix/base64.o := c++ '-DNODE_GYP_MODULE_NAME=kerberos' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-DBUILDING_NODE_EXTENSION' -I/Users/kai/Library/Caches/node-gyp/12.16.3/include/node -I/Users/kai/Library/Caches/node-gyp/12.16.3/src -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/openssl/config -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/openssl/openssl/include -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/uv/include -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/zlib -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/v8/include -I../../nan -Os -gdwarf-2 -mmacosx-version-min=10.7 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=gnu++1y -stdlib=libc++ -fno-exceptions -std=c++11 -stdlib=libc++ -MMD -MF ./Release/.deps/Release/obj.target/kerberos/src/unix/base64.o.d.raw -c -o Release/obj.target/kerberos/src/unix/base64.o ../src/unix/base64.cc -Release/obj.target/kerberos/src/unix/base64.o: ../src/unix/base64.cc \ - ../src/unix/base64.h -../src/unix/base64.cc: -../src/unix/base64.h: diff --git a/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/src/unix/kerberos_gss.o.d b/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/src/unix/kerberos_gss.o.d deleted file mode 100644 index b8168e1..0000000 --- a/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/src/unix/kerberos_gss.o.d +++ /dev/null @@ -1,7 +0,0 @@ -cmd_Release/obj.target/kerberos/src/unix/kerberos_gss.o := c++ '-DNODE_GYP_MODULE_NAME=kerberos' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-DBUILDING_NODE_EXTENSION' -I/Users/kai/Library/Caches/node-gyp/12.16.3/include/node -I/Users/kai/Library/Caches/node-gyp/12.16.3/src -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/openssl/config -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/openssl/openssl/include -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/uv/include -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/zlib -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/v8/include -I../../nan -Os -gdwarf-2 -mmacosx-version-min=10.7 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=gnu++1y -stdlib=libc++ -fno-exceptions -std=c++11 -stdlib=libc++ -MMD -MF ./Release/.deps/Release/obj.target/kerberos/src/unix/kerberos_gss.o.d.raw -c -o Release/obj.target/kerberos/src/unix/kerberos_gss.o ../src/unix/kerberos_gss.cc -Release/obj.target/kerberos/src/unix/kerberos_gss.o: \ - ../src/unix/kerberos_gss.cc ../src/unix/kerberos_gss.h \ - ../src/unix/base64.h -../src/unix/kerberos_gss.cc: -../src/unix/kerberos_gss.h: -../src/unix/base64.h: diff --git a/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/src/unix/kerberos_unix.o.d b/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/src/unix/kerberos_unix.o.d deleted file mode 100644 index 9e0ea95..0000000 --- a/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/src/unix/kerberos_unix.o.d +++ /dev/null @@ -1,61 +0,0 @@ -cmd_Release/obj.target/kerberos/src/unix/kerberos_unix.o := c++ '-DNODE_GYP_MODULE_NAME=kerberos' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-DV8_DEPRECATION_WARNINGS' '-DV8_IMMINENT_DEPRECATION_WARNINGS' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DOPENSSL_NO_PINSHARED' '-DOPENSSL_THREADS' '-DBUILDING_NODE_EXTENSION' -I/Users/kai/Library/Caches/node-gyp/12.16.3/include/node -I/Users/kai/Library/Caches/node-gyp/12.16.3/src -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/openssl/config -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/openssl/openssl/include -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/uv/include -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/zlib -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/v8/include -I../../nan -Os -gdwarf-2 -mmacosx-version-min=10.7 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=gnu++1y -stdlib=libc++ -fno-exceptions -std=c++11 -stdlib=libc++ -MMD -MF ./Release/.deps/Release/obj.target/kerberos/src/unix/kerberos_unix.o.d.raw -c -o Release/obj.target/kerberos/src/unix/kerberos_unix.o ../src/unix/kerberos_unix.cc -Release/obj.target/kerberos/src/unix/kerberos_unix.o: \ - ../src/unix/kerberos_unix.cc ../src/unix/../kerberos.h ../../nan/nan.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node_version.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/errno.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/version.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/unix.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/threadpool.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/darwin.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8-internal.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8-version.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8config.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8-platform.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node_buffer.h \ - /Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node_object_wrap.h \ - ../../nan/nan_callbacks.h ../../nan/nan_callbacks_12_inl.h \ - ../../nan/nan_maybe_43_inl.h ../../nan/nan_converters.h \ - ../../nan/nan_converters_43_inl.h ../../nan/nan_new.h \ - ../../nan/nan_implementation_12_inl.h \ - ../../nan/nan_persistent_12_inl.h ../../nan/nan_weak.h \ - ../../nan/nan_object_wrap.h ../../nan/nan_private.h \ - ../../nan/nan_typedarray_contents.h ../../nan/nan_json.h \ - ../src/unix/../kerberos_common.h ../src/unix/../unix/kerberos_gss.h \ - ../src/unix/../kerberos_worker.h -../src/unix/kerberos_unix.cc: -../src/unix/../kerberos.h: -../../nan/nan.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node_version.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/errno.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/version.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/unix.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/threadpool.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/uv/darwin.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8-internal.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8-version.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8config.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/v8-platform.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node_buffer.h: -/Users/kai/Library/Caches/node-gyp/12.16.3/include/node/node_object_wrap.h: -../../nan/nan_callbacks.h: -../../nan/nan_callbacks_12_inl.h: -../../nan/nan_maybe_43_inl.h: -../../nan/nan_converters.h: -../../nan/nan_converters_43_inl.h: -../../nan/nan_new.h: -../../nan/nan_implementation_12_inl.h: -../../nan/nan_persistent_12_inl.h: -../../nan/nan_weak.h: -../../nan/nan_object_wrap.h: -../../nan/nan_private.h: -../../nan/nan_typedarray_contents.h: -../../nan/nan_json.h: -../src/unix/../kerberos_common.h: -../src/unix/../unix/kerberos_gss.h: -../src/unix/../kerberos_worker.h: diff --git a/node_modules/kerberos/build/Release/kerberos.node b/node_modules/kerberos/build/Release/kerberos.node deleted file mode 100755 index ba5749624bba7b3f9520f7bf27a2d93fb44cadf8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 223008 zcmeFadwf(y(msAB$v{M60)l3h)loqa5fUUA5HukdCNjauO++9B2m}a8OeWkxBtaO4 zK}1wmL6Jq5by;P-BFiNTOThJY(PfoY1XNz_7*W7uHM z3O*bQJ~iYVJPkYkh|(`N*PTDzt<(BEnBUE9b=j0fn$o$JKR9Nb@r@Y{60u0rQlyYn-WL~ic5Ja=9oH&lQ7 z>vh>AfzY{CzCcZ#BKf9FDK0YeL-{#n*2kFuP%A&HPap`{ofCh#xvs1M{WH?D22(D6 zae^Ezvp~)rcj$8(2P>~D4P#z{)LRd_9{9rmENX2tqG43a;%&yT3k^eEXERpD>bVsU z+~M9f<6D%Ue9mTce8pyvT62gGe%B$N{%%KlHs}n_ZTyh1!Df8jNYSOpqjtPE{d0e> zS8m$B^>|*t`yyIg*dBSTqvkCPbzypj?L&= zURK(*aN-#H8++Y#T@t&Dn}H$ehgrzukCkfsIvz}DiXUHV6sT( zS3Ax8T2w`Txz1mhY3Bb^vsASU4I|65bDM~!cHmr%){XQ-C5uGK7KsKh+qRG3;`>$7 z5xSQ_f_w%UCmHDA5acTsN7#5_Bz>FMkuOV3*o(ANB8$YKIaY zxm~IpSyH-)OLyQ*rBZUi2eFmy(VF@UXBZ8qx6ccT^6TAkY6>B$?T;gaegL~$YelP3 z%*VbEMY=^_QrWs7-Bb!gvZ6OpTP@%!J6ygg5cNx^XP2^Z&LMR-sEGQ;0!nh}he*Om zai$(dGJ8RNY^9GF^=`mu63VI19huPy@OF7Vc6q*2-)VO0HUd=a?08q|h}4m(qf&E6 z?ob}&)i{2vuUGd_YCWaODfKy}CR3{OX{7QfRYa*fDD@7dvMJRG^F^gmY9dnpnaK0d zk>z>Q>G@}tr!EUqWHCTa-<;jl>1~zh!VJowzMWRJdmele_kaoP9=%n`D3`(UqKKMP!zfX)(?Q+VonC>Q+A6=S;x!7= zJ=yzQo{Xw2&s$E<5Xf1+(dn79NxiK(tt7$iNM|pobNQ}+4||l^vFTrE8S2Pqv_v6I zX3Rb6n5wHlFCV1Z9*p?b=}?f2Fd=EIW`l}RZUtCM6_VgX9efhW>;*?+E7#JX_v32S zPH*{cPP5zK`md``7+L3bs4Fyz^mQeY+b~UZBd@D%06D!Q>suif_~k(lQ}Hake&>%fAo zq>+Bi1k+#8k8IMN?ni?3V-jUG>_;kRQ$Ieu_YD15$Q?-9wubxhIf(AZ0kH5}yE!vM z#^o6>r~c3lte-J1b5K3Ydx6V)1@+21ELlB<983a?gqO-NcRZYfnJ}kH4BgH-hg3PJ z%R??py}?PWwY$_u^N0i7biI0%lF&_Ch?eC^Z|?}6&^u6^0^3Uk|z0^AOJ(2pJ_`$sCy^YuvJJj!x@ARebFUj%^ zh=tXHiGLk=i^jkubnD5lAD8kB+~8I2hL3SvAXc!j*2l2HBV z?G6JiE+%f(DSVTnIwcxeq~tf>1F3i|&gqGEc}n6T15Lr6sQka)%yCM16yDoE7)P8Rd7A zukrlg^qf#1f)fUFE_pUI{l40d40RsbhgO{4S#h+q$ExKdMRgjtlvoe9PAfZHbe*cC z66!=6RND5wy?T{72zjI7I$wUVn@89k43>T?O#w#2Qenw@%t03mVf z+sLcQp%}HAQXIE#r4+}lFHnl()<05;UKci`Yl+P{)WOcc&GJ21ei4lJ5l-QEP#U(k;yP+j_w zEYZpq%4*n;2RWPi(G{t%QP;n@14(hZAH6|zKe~kJM--U;f_}U=-QN#0>N-wY4g2wT z&Zd4$Kq_oMTCD^JUy}0?A~9|d-H-8*wW;yw4W>Uc+PDx^gQJZUjyA4C{u!c;2`pmL z;}5f>Z-8h?x1g$jZQ=MZg`$mrPa~X;Hts@N?WPQG%oG0xu|ylSQ+clIXk#5=f}#xv z=NwYYKrPY6`Dj%9+DR~=I=Bk?3neie5^c1jPBn-&mi_~|4Wf;saI2PRY{!KasE@DSlh?tsm0}3oU`JSW5oUyXoBJ* z5A$?Z{N3jCtfp36o_x!?*fbWD_PAt4p?a>$8 z+!ii$A**87N$!uF3{#8CAtYJGR_d25885lH2NWK@f$~(^w5V54Ay;=c2T*i&GzfK8 z+K8Cj!s(q3HB}!Io$<*qH4{84tK3&?r?62S#2Gp!l_F-V%Ue6|-AQx9x{Z*)UD{egRla~S{NBmjtI6{0 z)7wg5c8f5>bW$AvM!!n10|7)nq47?&+mdIEucb9Ef&hy&GI!0_Dl zZ(H8VIfv9{P;uiIa+1TptC2)K+O|AYB0E@pz)LOQYS!@Y1(ehH+|9Lh`1ifb^O5SS z*{PKPsBEg|OImw>kmwzdOP-5FSMYogy+t1py{CvyQU!~CzqD8nDxweLB#S;7NfEt0 zlDzr$FnFssa2CwyWHIF&QZI9Di|7kE<4g4+0BSka^Cg|ctg>7cO+v0Ida4%vYg6>O z?8LGENj1r1`nA4KT1@8#J|p{HjV#$L-iV}#J`qV4{Yx_L*anRH2%{gkwng+eIpa%p zC8&CjP`;!A!J%Odg&A2yZ^ap3stEw7c2v)o^dvUREm}X$&1i%926Gjn55ZL;+j_K! zPErMnK1y1A3sgkEhLdbCy^s{qznLPUKMCIIcU;XneAOr?(HC%Si|9i&JGFrTA(uLz zBClq`Da_vklzNp??@;Ojy8PKqsnL|$MyZ!5^&+L3(-!?Rlo~;)HI#amQV&xql03^2 zN)17ZTnAJ!;2(xDvSuDM7wSufWqICpdcHyUqIRGXA`Bj(A4!Ftk$YX9^4*9O*OMP0IZ2B)iO6dX31ZV0YO42p& zOK4V{bSf&zCIo7}u0AA;7jYHt5d7BZO&~e?bG<5e3~wP5>J{WvN3{nVvJp%Ux`C$e z5Asxc-|5ZXt?mK}0VR4xBc%os8;Vj-sPj3wzt$m466-?hyF6d1b_A-}In27QU4p!t zRM9xyvZULU@d&n^-phH#t=QqfUJo|HQ_i;^!|E6N%I=EqT1{&o`$`pVU-FLlYh@R? zy!TwL#<385`()x|gbgvK9@G(>lET*lK@-(`(^>FzdUG#UahfNEV{M72?7BZl41II< zyF52KJ^i9n>)%7i;`L5gU{{K-9B@nZ1o!7M^rs^hxQ=Jhw#z%=Vzoj`O-t|Z@Z7oC z_Ql9{dFJeOdNTH(bx$r=nVK8*q(5;BXlEBrNjsI?sd5@zGSvDpK>lds zlAqMA;)~T*-5gDg*Cz(Lm4a-SCm(m2=px`O2k07AthrIQ+{7(LX4fJ0B~GbZeidoS{c?WcdcSB=TB{7iQP}&8@RHW_Bk@cey`}Wzo zh}b5LVG^?iWb+)%8#NEjnfelArd`h%J0l6CG`YPyI# z6;vkKhm?i6I|?@ps5k$_xvynP#doLY=BE2*r`S^Ot*4!}(pFhx>(w6CMp`u0$W_-; zT?D&47h9lx%`+XhK$oM)gPTnVd{^#@vau}c76@XoV|22PZY2AXzGo5>Nu6|~G4&X6 z_VsyB7k{9OzX91ijf!WZSoDhhXYX7G#mudoJx{wY<$xJFNOROiL%9yt3afR8({mT* zI>6rMytm@f+sh;C51abbPct~!_kyqe=FKE9UzOrcoo6BB!;rtSjLE_^Ozw$RS5Uv? zM(dCXkS~rhpv=#40)L) zWctwuPa@IH)vG?&cP>1S@{6LgP&hdOg zdiX(s8Bnw8gLA|jdvQ6P?R}aR?R}Z-Reb|KG&#N!`X19A>H|=IVn|1PxGv82oXp0$ zo=&C;AyoZXB)s;jmx<7Y+5Yl2=uU!v9Z}bTN9{Z{2947Uh&?}W4D^$&WD1aoHQ=>5 z)_5GOUEaTvoGvfVE7hOns#aM-yE5IOZUE)yn{>d$a(<+qpqen8yGX{+naFL^m2^&) z=U-W#R%Z8Q1KjDFr_pt(Gdyc6Ls*aTcTL9XG<^?MA zfOh9|+9&L25trrUK#fKU1OCd3;G-RwdWovY?5@c}+UirgQDMNRHaf#E0EPytGxv>M zgP!_rIpZ<1QQn_cw*m=ON8*q6Z>rV3#2&W&6;bjCMI-4pVSE;r)=JOY*F5kiBWzvH^B)v{iee`+{1ITS-7pNZu$dvhQ@}4BTu`3rnvZfQ{ z)-?x!QFSyHteax;iAQXDwfHM=O+!wQ_hJoCA)M*J^m2M3EvMMSf`6*cbbz^08}F>n zILxUF;7qEVo~aJ_mHM3c?Ud_`yvfNP@1RPi(=hv4kmHBvb&Els?HTBk`k=$~6zz}R z7NjRbf&WGtfPv%@Xs4)7;S&B#O)c{`rOI2nJjbAB+yuvnsa|G#^em(Hfe>x9zrp>` zL2TvgXhLpvd+)&>-68iyS>8-+IPG#LP@s|Jnd_)o4N!K^sSft-6bEAek2JvhcLe8< zWUA9kmPEe)_V_Fvi(r4x=_M|Nxyw;I6m{S^@hH&gASM}!M_it<4ynbH7_gpuM$x?y|XkCd!N1L0>^ zGf?obB3O{#vQ1~i4yVsPlWRw&F3yZzgh19eD=y17HBQ+Xus^W219}@nn=S4ay(kmN zOl;sz!*r}3S@Yf~S$%^g-H&YPtLFzQ68Wl-ACT{PL6Mc;dz6+OZRqMbJv?OS64Ux8 z;hLaHxCV8MTAGCO0+Wz>gq_#|T&0GT7I56l&aNlip2gGo><^%qrr-0~Be~BZmempb{NsfIKS*v+o1cta zGZNV})S8ncG~Q}ipCgX~AD?{<*KS~0e_}weWtB6uG0U0*H1{spvgS(5JU=a#HJ+Kv zM5-AkD1W?xP|&H@Q173$QZbS)Zx>Z`7f$g^Aq948hvPkAT${#L!T=35NEgA;?o$6k zk?PACNl)T7aUdp9mryPTe6f|+Xn(An$U{&C*Tq5A1E>uMt+ux!ndP}m)ln8641~9f z&h~EAap6lG7krLbf!iJIjZ1wo$Df^20$1~Q~t4fvOFC+RcZqs~GE9YyUMpb;8fc!gfOY%JwL^;npk-E5D z@}fI!6(7f5?J>RGH3ZUadTxaaIJ?Nxu-uHMQd_BQpx83$5BIDRa zkK(NF;&wLNZ`03;qiEV`XT|A0?v^Q)b<^kco!7fry?ZLM@4@p?^_*QleLS+8*SmA8 zK92DGyXw2B=(kfBotIVLEM*=lcCGp(igfCEyXw1$=zpg!%Cd10D*vYH<7RzZv}v9S z4P;fk7K!{?)O)QKntv?<9l-!ZLF@&z?OEGm7ev(>2+`5@6v(Yk45O$_P-?hh zD}f9*HXt?g;L2-I*(q5tZ@M+hg3jiAolfDjJr?#N{vdY25N5w0>l!J|;u#t=vk1*Q zeLfa7nMI{5sXomh<~9s%ea-DSK!>DJ+~g-!x_nP@Ex*J|DAV(`YQgo(N4mU!W;oq( zJxy1R*K5WI&RAsHHC;QD#Ff)e)xyB3^cN5Qn{ur|A% zWCZ)3)CBzD9&xHeJx_dnb#o`_iSEubvszf(auzAr(K{O zrw_MWip++}9-)^U(0NF(nbbs1&q&<_YsJw0J10k72PiZV$8yD1j01+i=*MoAVX}#> za3No7eHAi;#|qVxEfycF%zKY^#Du`GrD9F<+TUMC8o}ToVDUZmCQKq#ZvNm|7@BE_ zb!lqgy#?}Mu(x#2X}miDVb$_MP#-Ff{++yIF5#OBSiSJO5a~}$w zbh`oDyFPl7X3lZ7R_8ek_l0$7@itrl`pO(!GM`H5-Vw|yMkUi(by`R0gmM#f?v*+> zfpXaNqeHnhod^}L%5_Z507;8hiRe%O<- zl2_&Dx%~{xk&I?1u z5f(f^0%!x@sD^UiFSZ&bY!zaKph zZ6x-P-A+$LmiI>L2DKnl4edd&Jvo?bpX6`{9NGuuu@9)}MV7>lux|+e9^kL;;7r(7 z#hgt%@H{s+s@25Hi%=iKYgc#D8NUc%jY=UCt}tmH0Lr(P_a*L88Ng}@y3l$!XMKR} z8kLDc1kgPH$=CG7d8)TZ&2qTnEbl#HO`qS!11{Dyat*GxZK?uLs2Pwd_s!t3Cd&)w zMB5_otKUDLCfV;>P5iGjP*d5 z&>0UjTy7(4*S$xbapZ2XcFB_la6I`>5DV1H*vooau<=XW62ErA8W3|9U!dB8byjtH zd)5<8)v8q9{8HZ1sxTR=!J^}q}fN?Ur%k3h>8!K>HCYn6EbXb=*_ zTkKQsKZY!4uk=+td2KB?-R!_5rJPkI^H?cGE-XomezLn;X-^IjM{srZjM*8B? z;%ct{3P$S7UgJbO$?nFMW(>q7&n>|O zbvJv{W*R1~M_G&SAaQV$hcyse@jaH6Q2BeY{Nd)0WIgVm>w_D+#Am~)Wm$$Th^rCwMZ8Szuq{oqjPl1@!#9J&E7jfiBv+IjR+09b*H)+9%h6ymRWz*>iFR1Y$b za?-~}bubex_*T;_p%^9=Wg3jh%aPzqRNrrVaKD52(-M~v5C#YZbk+m2lsNIgv?T9< zOls7}_0`)btQp8Q7s%X#Os%12#4U8ys<{$)GCA#kefHU_35Dkh?upl)ZyBCvhL?=T zh@imSaHepCcdK zc=sJ|Ph4E9A6!(wL3M0f$g2xYyfea=qG+q&eHweZ*xEXsE)l14n|SoYw_ra-em$!Z zeSZLs`t1eM2_6kHUyJa+y>POTw-?$1OJSCNd*OvNobf$GH2_Jxy+Ch^s#Q3cZ!e5S zgDwxhy+E>%DmqZh9Wh+0Cvo$|ET@IugC)QJN$l+rMUe1Q-d`vi$CHzS_P72)eGhjh zh$PZ?f=ZB5&q3I_1tgo!(({PK zlz?n@Q0K;=*zY_sQ|CUn{>~~bmL^|qNw&+ z^*gb_Qr@YyhYR<{EwAku;7!pW-sAZ@_H^2{&-To2AI(o9!w>OuS=2AQuhW~I919E| zrB?TqS;F^aLag`e2O&$N*1IV67g_IJsD9Sg`^g0Ky& z_W&|sy;m(K(vs^OpzxDD{I_6t!KZ5n{2Q+KG85`v1 zM%|(<5PABm`rD=C_US>6oe%EzPJk~A^B{=IK(-iW+dt(( z3cslIRMt#142Pdgo%XT<;b~4{C1$n!g;@Gl=TNEM!*~KY8Hsi2p0ap-gJlClVut*V z^gvGdusCCK$_|_>JYajwe4C7XI{uE~5Bcn{@%W+n!dU{UbVN}c{-Rx;8`3=`DQJEf zH_xw}eL2c+^q0QDLl)-dJ&CQoGdXW{3fgG!9@=M|N%vedaxWp@;mi_$<~+*WicHvW z)cr*C#cew{_x0l3&CerE>W$zf5za?FP8EE8+K(WTbk|)(VitnvsWJn_p;ILp%s4>S z55(IaS&DOZt$WoRFvdu&hb&}c&)$Twort{PyTcjCp$Bzo|F0LumOuaWjR9;Qs*gZR zzf4IiCW8g7tkwds{vW`r5^q#IK|E`i1FZkg zq(R@e{?uT^}6d$8Zx%KKt|^GgjC zCsWFjtgnC`RNLOBc|Hv$azgFJ#W`IDT4rt=m4qH42CBk!3T|IyVu{1uURIr&O)Yxu zeSAdpFkVZKRNcFily3>`)fymcw$MmEOsP=_=hPbz-5=pOefCUR`>avsceogB7-c?& z-8POgN7if$iV-&k#fZa&dtdf`3%O86o*<6j8} za-+Nw{s(MfJo`Y@O~@wWfiGzL)-VX+f3KWY!jkXNZC}!M6l`t*EmPdP94;>v@5cL* z{z7;U-`K_Sm-r5qx=~tj65L{*S_w&GGv2B=d7jJHp#o>F*o=?hauUc}%VIi?r1GtH zQWhaAwG&T7XQL>~jl=G`*;{O@agdjP879p+d0f;{mZ$xdBkGh5?8@ zEbI^MQcJpH%=;lDc!j(QIpzv^8sp3>_6=ws zrkzVd96>%_N$;YH8BndJFg-;5eHlrbF0XyzsH`eKUmZoo+9;BPG@>eSn$FJ-Tko5x z&B(4fNvqsO!ar&%mv$(o`+dp<_dy5_L=IzzqG_M97h_Ixw&UQ8*9kH$)rod_v`;xq z5Z+6;9|G%{K0!oh))D@gx3R5+Hy~wTrWeqeUM3<*{FdtTZW#63k(QaxpQXSQ)E0h7 z9YoP~2Zl&}O?7=SkI_X5&o!D`m@4K(;;F{dEYiQ*<6FIkd&t4)_Q5oIi1_jSgY9RU zHz9^!jK=FY-qurOC246mN#wOZSxJOu!{PD^5SY*~$Q=fi1&DQs0&ah@)beDU-4M;# zO(OFUk!)%qMJ^a3Tp!R7xq6J0toE$nwzoe(0k9J!mG1{kadqa&yT1IKeQm@5suH?)R3yY!NdF_Me6A2iTzFyH=QKUVq zF~!?yU|L2f4H;3#`FZ5J8NTlpQA12$Q@Tlg(Dl&U_UGV zuuJ3LV=?XW{s1dh?CKy^=YbW^a{Vov>IKWt0hot~8tMOVjH-oafG(%g+bP3TYFBo} z4sFv<;mmK-QM1eapK_Tl;R~^0F-I|qN@wvPJgKt`h=&=) z%3R7>tK)SR2~PfhI&!xc&?H;J}GkA?bb036&%)+ zY!Gf{l zFU|W^oNX>7-owBf#Z|iaQeC`>ilQ`)?D_f^{z}D z&S0T(S4KeuzA#sHNO4bm_MWtohQ7nIP0G#tOKk!mdDCJQb;r+nso={MD_Twc6Yd4p zWzq``csvR(G~hL*R(NiWp76uB6!v4^##61Y)+exFc+X-qw*K((0I&U_S&)Hm!$rD0 zv*M9+9p&Irb9#n1fanXB zdeZ3^)k^%&0jPywqCB{k(c>F)AzcDB@xH_%EW`Q{#gR36s3&_!S0hQad3;qoN#(b@ zi=<4?$auWG=HOaRFTYjkz^$a4Vw#h9fp?8Y)*QyBiP+l@_Yyn2t4;4@Zp6j7za`l1 zK`Hd%xr-Gj3$**VaA28qfc*fnFem9d(c1OH*8TVC;4AjH?HJ5dj0~<&X;BE=OGQ&< zTrFVtcyf}T1Hw&Ys+NLk{ZK7azH+POrH5oK@=#HCrR=j$6Jxso0dIFw!`8{lm^X5~Y zcUXe@2Y|uXoqv+5u&P-q9VfMJ3KG;)NTRVSYU~=M)e0PftCkSNqrbQdt&rB$?yo$KKDNDA`^S{f+yPNVZ`Marj z1Kj%@&r$Cmuy10hhqx!z>OrA1nC?(>K=ma#F1Ymj*?35ZZN~qic+LB-`F%aUS3;pr zYja9FV_$=#h4s*92zXhuOl_T2Q;jzCZ1LGE?m=%tSAk6cSnSI_DgcsI;9(ZmTwfLm z-nt6RWCX1O4zAsB73jr?pjF^oTEzqJQ3tI8=L6ozD$r8e4qXL~wi`bq#UgWdH?Gv zC&c^T4xQ*X;2QJ(YuNjHVN#*qfA7!p{?A+m5zhSbCw*nnoHOUct_sXKvlR8!GHjTO zg~dz^GhhA}VN&4T&j~p5`{Z`AcJR2uif)xc^2r9u0%O|(E&8oh`{W<5q)x>^;_ULh-9@u@yU;sX+7c+lzj5sD@btdlb?4` zk@m^`)Ho{9?@v~-6aI0nIN@7S66{H@CaieUr(hb|2@a30oy5NQH@cB3^2Lv#5f$Bl z!x3tmIk@j8KYS4o7C)S;i^&hiBT0UECuLduu;1H$iO8S5t-2ftul&Zzbf=Qs=X8;4liW5qH$@b|)+95xsZH z-)GT|5f8$!kF42^GRxT6iyG8^T55~?djzL}q4nU5 z_(s1j_5;+EF1Db|uM3O*)=3@Fz(Y6GP)M9!g>2G z0Cu-m3dyJ4M|VQ~K5f}=Ew-{97Hp^rWTEL*T<0fy-h8h16Qkj;@szVgUPyVEpL;gf z{?FSr>Upog1+>^EdEO|XOwXHqDHWNX_j5Y4dftlF;(7O?B-rzAAZ*i~_X#SNDEJDb z)zStWCiyvN&$|le7SH>?mv95*c^^lTJnyYkqcP80PPaHI&Ml%!UVB&UD42#5)ykf-e5C<99kNl-1IxN%UPUYht{834{~T9O(K;9J2X3V@_*>iM*RjNoY|p0 zLXtM-(E6gjO2;O0a-%*m*Vp&^!H#A=26_)|G&SMx=w;xLNV6{m@N@y~(2-_>nh9QYY0*KErtJFE zjFNUtON?qzySLP4=NPZ9$7x`}y&Pvc&eGpZ;z%=&A>V0LZxW6pZf2c z<-mzU{hbu*%}mbX7^!~>d_%J7GEJWTShJ8h;h_&~Hxj3%R!;Xe!pR@8O04PEMj^mW zX(I<^7JuunlPq;a2iM{>po2?srseg24Xnh8px@m^qe*%v2~~S zPx;6R^3SQ11OJ>_aZ7zUKjfE>TDy3N;T=mc<$SFY;T|ipz~8gx9`v3=!>e@jpxkF7gvmUb|cspefP?hUkyH zQ``8r!Cpd)9YWb#NV+r4xD+Y{xQm||#(w6wdXuU$jt6|L5j5%%< z6xoH`q0;{Bo;_ToLf9s6}3*wZ@rpDS)p%Q2#CTqI5dL-sAC zHKRJ*>(GyaeM((~+I;pU%q`&Oo~05qQhbtO+Uc1*{E^{6t{I37-IkgZ1lEj22GvquI;wz}HUj5J?(_IzD_G2gdZ6Bug09}2Vo-y;2 zV9)55Lh_8AP!=%Y?r6|&5&D(rYq$?FDO@Lh=n^@RVrQ>#rp;il%KZ0!k;Hlrf#3Hz$YsRVAwNnZm%E<&|9;OA-jAe z9`YLQid_u@P;4Y<8*vEA^)_OEq_B-RA1q0mi1NnbUQScK@*m^<_F{UwqsU@knWJN- z(W*Uo)ukotQ>SXnr+(kkj87ZC=KdVQSjN=8tO4)cKv;Oc%BOzb&+w@~czX<|0fX@2 z%=D4uXJKrHn#&OUKkE2g67GMGrwZ(A)qQw!!@TI$nxUr_Vt(XnL3|ku-*%yA#&Q9( z`cS_XE(2$aq_KSJm(<|X#!bZ|^-!SxEB@EK_^wP#rf_zUldi=F^{h_Hx>}n z!;h0S!ko#=rI0+l6J-JO83-2sd8s{o2C^_6Msc09_V8U9ewH47=YdcU|2%R6QfmK%a3CJ2?QocnAM^1DA3x=z;^XIhJj%x} z_;`$uU-R)eAM5ydl8@i>@f06V^U;9R^&KMk7{$kCe2nH}3qH2w;{|+-<6~<+w&CMN ze2nMgC46khN76@q2L~Uo&V1~`#{@oh<70O|_TXbOAA9k!Hy`O6 zl=U4__}G_^>3q!Oqmz%f^3lb|0eqxyT-J9O$j8Ba9LmRGd>qcl5quoQ$I*No!^d%a z9M8uBK2G9eAs>tQSi;9rKDzlhm5I{&&L<}_%a_i z@o_UBx8O)ivr#h~^ShugrE(}$M5#)M84V zg2D=3rqtJzibcd;qbQX~se_cdlTzfh3d$+<2Blu4R28LaDfKd?l5t5@vw>27rPNwV zU5qO}{=aDpMo@}|tl$AkRZ{9DO3kFySClHD)K$1Dt{G3M;grIaA@oNnxDt#TrJR(i zrPR%oIv<-IHQgzdLa9!a%A=HnQZG;nH(ZQ@^{tUYEm+fqNMYRZbNPOIdp4fH8C2gP z6?9p_SZs~eV2h!?;66%Wsi`k`ic;@TY8$0?Q|d!X(OdHcb(DIMQmwEtSn~{}uB8-i z%GDQSQtDw!jiJ;MO3k6vd`i)FC4Z{E;5kasx0woFrxbk!xZt0Z8cwPIP%4K~G1xw> z$)r>grFv89c1m@l)ZLWoNU4V@bs44pN~t!K`WK~IP^y+v2BjiND|L9$vfy$`9i>z+ zN_|YJVU*fWsS--PMXCLy(VdiXT!7SON|jM+Bc*mw>S;=yqSPu%T|*k8@0S+zrqm)z z4WZOrO3k2@n^KFZjY*XH9i>K7>Ti@9N~w1#<)YN5l3|ysOqBQvGMlC_ETSBI2DGhxblQ(v9R?+z4tO4Do zCMONeD=g0^0dHuZn-HRfo~(tC{tXzEmP?vzyqmhGjmy`#z6M|jejY#F-=E##0sX1V zV+%7HbTBoXKtl?lfCdKRgsKLm;}FI^rT>j-E?^p*8vbi^s(}p+7?ga5j-{ewB*4#Z zo-~U3aB*k*yBWY+x+nFxF}Y{2n|k+=YKAQ$GRoepdGvWL&TkoWL2O*B))%&Ed(p-5 zztMn8E^YVQ%Px0ZaphI*J6wHD$7?%X*ZKM`T@wWrG_Z_8qCBg2+;-3cPmriZOKb@Wb(T#T>;- zpfj18%&&3(tjDK8Q;7*fil$+Xr02QweySNKhS<^1G~;mcHXN#-Eiju^Vq+`9FEp!0 z?CIAK@@JdXuc$MaRbtrr-oT!c$>IJSW9s(n7!zi|PqU|=ComgRxBr4MLHgMMP%(isHf5(gHw#4%M zN`p+i=oikO5_@D7O>|GpE1WnpUoZ7PF;wdwVoE>zs!7XwCV7YdGJ)BYx;JJ@zxb*r zAV02Oevwu!LN;PbXL}W6k>{6*gEfwJx&ptmwI@B5exf}k{Xev)pDr*DRnq^dJ^dmf ze|>xU>Eghik^;trRCs&JDVhXVIPrs6o zzm`4y5^-QpJNY#|M0}0FEAU^jlaGzVSW2m zg!;M0^GlkCvD_GBEI2WD<8}OFlwrdP|Jh((iBZm1{ziFOerZwOlzanwL?y*VWr0Lm zanX2VY%%tcrn}RMr<4@tyYv0*v}ZKjd8HHb-256|vc}4V>TgX~pFPbKLAmFz(3Dn{4i$vu>`xxio)#S+1i`ACwMp zk53-thL{tA8%KkM`9+T2eH>W>2Ipp{4uft>a~)Su9f(*~I<~8+k}hM%`qg9T9Ty|7 z$dO-KT3qTV9y_+Y6#I5EaH)OM(lavqIkRr<@5&xox>a^)IX42-U-e0#(TZE3u`7_*kW2_}*`FEG+7mdw#K+H18JHE7dN(ihZue2=R;U7u|*;5eC z?*Sbo(|G8993(Tj41_L<%iWIR@s26^Q;JJxK$@||mTu6dg{?uacG{{0*Mw{#MW*aP%k}On1x@>26lEc3-czF8B_Ad7TlJV9$*oA+0$5w zOhA7V{xOnJBv2=4Q85PQk2kJpVyX=(!o+D%O7jczP|qovaJX4+;AL}qSkEw{Z=!Su z*=E?N*p_FDv|V9D*xnvyx3xMy%62nedUK(G{x+<}0Y6IP$pWLL@tm<+-+qo-9BJ5l zL>W;l>_#M>n6!6}HX`4RHtcVmXV~h_Ga_DYVc1j)BdYHOMr3*`!`{2KVSBi>5tVwW zVH zzOKDt+t?oMbTFbuU2R0Ry~eP0xyCR?fxZqpqN5S{W=F&R?zM(-WhcXyfZOQ5Mr5z+4cpY~4P({yM%3W0hHXw)BjUA0D5skd z^=Nk^;`{DK)Ixas7Rg4`AA6x+HyKfteT;~qxP{;97Q;R^)rfjG%`kG(4cqW^!kXA@v zkPp3%H*8gS6d_@PVJn${hXW=U5jzVE+ZP4EPJ~`38Aj10BjV&_!`7?NFrFziY@dU+ zm|{fSTx8f572*GMEixkOknUcLy^Ufc;*Ao+*79z{n0>cl+X8yvZX=>gnPD4NW*G05 z8IdKpL-fAeu+N(c*{2#tw`tJ*G{aav&4_q>I%Jz}81XZV$N@79TO~dT@yrav-fNa& zn?1`gj)Hcc4ZX}ZB8JT|Z1d;9*yb9MGv^w{k-0|1;CZl}d4_Qsw8y=MG4x*8%6!B2 z?0h^EQDHNJT z)YU(eubguKEx0Pl_w&uHVC{1Mf$L6>o8T9Y-zf{OMJPWxr~b5ukGn|t4L^e&Q2T>{ zPZ_D(4>wM;fjfK_xOKqI8+B%W^uPN!ay2g8_#6jrt>DgPeA=VWlSXU4;q>V`OPt$+ z3#a#0z`3Md;>|zPE^->qzc+y?p#NtcKYDH~2p=+^*#3bZK@TY5cT-e&JdJB-U?vo3 zd@F(b?N83x{(;L8T;3VvAikBr-#bzB{d*|iEN$1scLQ+kCu!U}p}3HFMfd~2?-Klh zP<)6!NRF0v!zi7s`40}o_pRU&AY6Cg9v56xX#YfB!i@lKW})WiYJwlhSxNi^ccy+3 z-xq;TnWFh(>Cr#aE-Z2$0B*71u*5Wpi$XwjKyc-uxPAe@+8MY`^k^G?6`{C{fPMx8 zcc0)|hvMX%`Y{{062T$l&_A;ua!UGH2i#P_H5kW`aVNg}fWNX>%Za4^h43ZZDJnbz zj@qX;U=B+Av}W!lkp`x+XCDev%jH!D8w$QKSzP@eYds;S14c0 zxU|9Gjuu=v{qzPdQ*c*=;WrMr6u~({adJ-b(Yu_kM39!Cf7Sv*>RyaAtpR2_2VP1O9Y2aKlRVc!aaBb-=j< z7tX%k1g@Ll9HH{bIqCU0aGeAfPS5RH2Ka^3b2@NN;TKNNg}`MBE}WiM0M}h`P3gHa z`mqH#v%mbGjZ+`ZacjhH9tD1L*_rj-21sj2d>Pm zodL{qIR+ccctWq;z*x``0FRQ-yufkpUE#I-lTr6 z!r#Vey8Y1%#=*pk{KR)B{*>UdL-i3dPJ};>Kl=>LHzgF`h#aK5wlg)pL0ls9lK9d) z7bSvwBD8-Ya!~(f1Al0?<{J|#hb1muhq9e>G>+aZ;h(98M&#WG%$R#LzCpZai680u ztmQn7`>U|^>(|mRx;}eCa05g86|xSH9_ae)HF|9Uzp_w#h`eXAzoV6!&y7vUM|w=h z-zmZM4TCF0*+mO9Ke%rFGxaE^#BT-uP71#Uaf3xKTYxj=qj!n;XYw1+a6jTG07vfA z?LQ=NzrOo5#J9uv+`3TX&xSwQUtf>LU&mJyXvCB!MDH|CWPg3=MHBp9LYjX~;7KnV zfO*}g@!`gU?C%}Hh0`yCxK8X?KMM7cP$20^Bg+7cP!C0^Cr+(VXL- zsh1G{*&c;$a9zE2l^*ACaa(WT9u{0vaRl)j2iz>dg&XH3z>PW!9PbYZE}T8k{y=xZ z;oU9$Gy5&4Bp>Y$v=dyo{?h(H+*!y+`vYH#zVSg#{cEIM+8_8>aGgSNmia{c14jgx z83y+za1kP3w@{p%Q-A3N&6a`-cm2~2*Vkr09HIOy@}&d!xyUy#)V?h1eIamdR-f6f zRsa_*xTfri){iZ~eIflA7b;)KJ_PmqDDYPb-&;cQmj1NC^>Z)5IYM!APW*ZU*G+KY z{KGg4zi|Fx32-^W@0u{}zG%UP^A87ryIJ^M9m>zr-zd6n7F=O}_zrnyw z7hF^0NBWx$+$h0?nH$S=qH%V{XTR=^Joeo~-9zIKSV% zCH#iq!s*!sT(scA*|QtClWTOlox=2Y6>#4RE}T8@1TJ3M4QJ1^KVbGFoITV2fY}d6 z82NgWGNj#b_B;-_mTS+f=Ox5XaFpbqIlgjAe&aA4+( zrWS$=XV2-teJ|q{&YlZ_J0-Yq_PhePOQhX!_Phl+vmfY^{xxDRM}RZ?;RwZ9{6@<- z#81+0xHzUeaGlqkSPJ zEw~2bVZpV>&Ct1m3+JC*z%3SBQ~tR#vpXTW53|S*>yT_?+dPh9xdZn2;51*g|q7wz?uCBXV+VRGyCBX zHTwOarQIXI9hP=mhU(iApSQ%vCw88Np1T9L=`8d-0=UNo*FZjzm;8Apa1RSEAxu9u zSork_#aZliA8;FlA09Q+KhwVCl-fN7+&aO9^V99INw{2aP5EiEYZq|K1b2U^o*S|2 z*}xzBgSNwP@y9ygjtDNCUB3z38-fdG*T;d|EVyuX-L5UJu>=>+uG4{gUvS~>MheO7zF}vOZ-0RYAIJ-Uq+|%pNtml?6f=2}xPS4$en)?DS3G=zmS7-=HwK zfvp(iC@ zmj;fmH99?1=xCvngt~>!6}m|1a-pk)J}q>k(9J@33VloHexV-=Ju0+LsPUx1zZOE< z2)#^bN1@$>_7<8cG)L%gq2q)W37sxgns;c-R@DLbwZ7GqF)4+>R6zZQB*Xfu%`PUs~<+Y9X?G+Ah0p)R3Ag^m_F zNvK=sT%n7EE*H8==+i%0t^p5x+E|x2`cpXra(mLN^KBCUm#ZcZGf})RcR)_%~AyGyj7dl+%JfT&oy8M7pvz=v6>wNS4n8;Zr?dek77pT*z z&!v8gzWThE(CI=S7y6>m_k}J`*Z60Jn(Zz7gU&b44~sl0(w>>WHw2fnUe{}I6uVe@ zr!HA3^wv^+zF4SP&ms8d$LgFdLPPPU90`BaIP*MC&X0+_CSS8Wr-^bC-@Z)Oz`H^G z3vD-)-(Im7GvB0#r5}TZk6Y+Ep&tuv;np=ALNkTFUas>G3N_^~5&1*yA>pLP*9qR3 zs?XaA?JU$O)a2)o^PU)mcj_~}B|3ROZcnXmbF6zUW@yF%x$6l%7Y z@SM&M?f)^!H*xbeYMgmY_(7+h7Jj>g)(P!ismn(QEfu;_X!L!$yuDDfoxRddgZ@i< z-2{KDP`A*{LXQglUg#wYbvuQNG+iXrY;WFQbbe_6Q=ZrPCT_2s>s;IiIi*t%3%`9r z+jw+-fzW4#ek?S8u`b`{)%1O#W;>1-bbf>WOM6Q2#uAO|B(y~6TA>?-?iG5#r|~C+ zn(ghC_Cou=>_v??agLYtxp_?ZQKyl{&kHr%bG)qcL;HVN@=aXHD;j4W6He7FqCG9lmzqGeS@cV?G7TWt^&2PL=x6lZtH@uGHsG3q2t8l+Xdc)8%W0COoFkT|&)v z;x_C22K|@z9vA$}LJteQY?ZF(6gpJsRH5@%>+;8in(b9dd!hX=`K!j8xMOne)Y<;y zOIvj^y|X`y6T2lpI2X??-simUL~C0_gmE5<;td-Eu4`tq+as_$g0n7?7h3b&`8f@o z)4(|moYTNL4V=@!ISriCz&Q<^)4(|moYTNL4V=@!|KBvw>I%n*zN1spMtA8utna|o z!Ks5%ho_dr4NNVG28|v_XE>Hbm&6T89YSfKhV(6o8=g8abtsTTQ3^C+f7LWeaal>r z+ev4wQgZtZ8kC!si;rPCZyPkYZ|b0o^xQ!i1BYg%Wf-^L9k?E@@!_4d^ z!D~U($Yn%8MAYRp$Q3!GAa4}W^}>k0zVX6%M?{Q@z91go^VIV^J=Hz4vpqet+2;Fw z{Y%g0-_`%Br>dT+r>?F_7fjd#aU_|rOtq)t=-}qV7ntUGeNovzdA@zV&3f2Q&`jX| zosrP!)f7~4MM^JBXkCcMjeuMXQumI-0(_Y%U`c*EGH2Jn7M!~J918oux)Koj07 zjDdLXNN9BTZ^VZSLSrxR|NqlKZ=~Q2_rvu1A@?&#hPas>&ROP2GFKRmr$VEfW^FzK z(#gyh;Dj(UF}TiLGaSzight2zSHj!8U|?fv0NxnxH~W+60oamq^o4&HT_Kf?<`wE7 zp)L#eg3US334$zcR8p24z+{B=4Oa1(891EGXwx66Gs|L4cuww zk5jx@sp@UrkHU$SQ@s~vIUHSzw?P~$WgBeetsgNs`9XZ6ci(*Y_VGA&!|8p~}%2D}&+ zZWvv-x#0}7xT+F2mc-KoDJz!9WGy4ynX}>riylRKQ3cf@bg<=ido-U(fm>uKv^jL) z^%MBeX(*QcGQK-D!Mj~XWCY!}OynLW_pO?H3mppBXTe_PAdF%3SnH!{Fp03cHJ*ys z+6`xfrl7@Pw!_}%xa~Psm=MUeN}j~5!oozt%ER8+PET5JTXgUNkKJoF!R*D%a8qv% zk}6l&*y%W}6T-F+>!jCvVul%wwL+DG#1=C;0zSnS;Q@C>GlhpT<}&JxOQT)eX;iVjnbMH1#)A%l%nCu>h7R%vR2&ai$-dQ7Ze#R!60 zp(4QHK=5q7t{q8uV9W;vgDvfc6L4(qB5N={k|Yf;(HqRE7m5Ohn#S6!Kc3>C zuXn!Fz8E%pUpkyGMDsnF!XWGvPhO2VU+W-0;2KT2vvl=p?w_aLdfhXqChy&0Wp zmoToyl)b}5!V@i=wQ=vV1Zo{tEL7tul~c9)rlLPmtG01@QrWXvbH~(QW93TgC*{-i z`kT}qFq$AMI`Q}m=*%nc#>%|ZUVKUHvU+z*@!gKd20GlMG;GqMt=hX%)i#%;tC(z2 zf);g_B^AjsCKl6qo9=NA?0O+F*uKK*8_Z?aQ(5bNpmZ= zsxVJ`EI7+}g%uxIo=$CyW#b8pY5;0+?JUygM>Zs^EFP=g8o~2NoQmZ#cpA+%52Y#W zs8J@g<-6IlmULzS8jDyXije|kgdqXD-PZ#n0d^JDWO7}mYQ|=?RZV7xm^pZugq9{h zw#%$i<~SZP4+BNilEb{(;}D@aGL$T+(E~g#qiPw7Nj0E~t;6p&+wU$oP$ZYxSmHgD zwo(B{XHlW0G@4)3`^X5CknT(->+%Of-o&J3_L=WSQ#5a<5S7x>cZ`*wNX=ntcRI3A z$~iZCt}o?=7iBVFe9}b5roNqdDA8C6qrEQ!l|ysbsco)+wv^C1z$gz7!LdSAlD3w< z(3fF7uM~rA<#^n*tHj%`@i@ENy5TgM!XU{rUg|#ooLsVCm8oG9$=;-@26t#AyV_#S zRe7~je?hX*TW1B!0`wa&PST&i{Me=Y*vFOBe6V1h@!>UtT=VXprAAzPmeIIE*f32P zSxP2gL=X=@f`T+Olu1Xs`;ABhyTApk;Y>W7r!Z)$ql_p~_OL%ZJQ3DCi7GQ=z^Oht zvyh7?3;Ae5)vojTpq@+)A4J-qH4aUK2-qc*|Ajhu2{rDDWnvrmp{TNm<%X7x786cQ z2OZB_=6YDL*O=QuO(Otfi#YIkXYgpNJW}VN!Gmr1U|p`iRVA;O z3=D6(%LP)AoYU~#2e^+r-Rbl!6YA>RM#pNu?dI~{k~?rW?9 z%w<4gVyyFK2J#&t3bK2mm$IONFlw$ce~vbp4AJ7$zIA*)5_}kInVn64Uv0b+A3k70G z)g0*kHU+JrM0O*>?fZf)#kPhylo=RKSx}tU;OTHmkH+!cd>Zqiuo~aqp&k_RPK67( z#GrbAmq7A+H^YJ9ERy#ygvt=%3k=hVA>}-}9|l&)rCG8~`+;OInE{854MXh$QyRbu zHNXK&p_%4+q0^Km;+bA%COHs#X>LB7w$@~zD&QvA~U99fvkI#fJ-npp?l3411|sgAO+{sZ8`5ZCI1=Gc4E^R=oc>yf5^zqe3%_ zqt~HF8_+q!L?-5L7h?5@y{kMMO$dgzKHLo+Z5OQhju1&l*|cP5^@ zhU0J~m6&8{y{gG86&YKq(IaPu9y=8_Q)mhObyf#VnyHf&AsJTJGwyfJHbM{1ZlXiv zR8OTE89xXyUkSzuN4@GP)lIV{zV-C=_SrK-Pqo5nZ#T5V&o4XR=b1Ob?h^VCZW%oe z?Vb%C04RHE6e|+?&l}=y?0?gKTYdJiib0>mNN3=FQ9D=bOtRcbbZau2xeA z{O6$N(2a+*g&u=k{sDUS)pJoA*tpQcy!yuv3C+;v%&VK`zw(fYXZNo@Wag}A2H`ls zU2xXktmohZ$eB3D-PQtgtA{!cqpT*bA3CbS;)N@Z3e8aGiGt-D914BvP;~++nn4)O zz2(qZp+`R45SkVG$>s2w%|1F>=-sfx6@|YT0atc>M&hD=-JN0W`+K9B?|p1*g9rb z=)Z6S8R3ThA&k%mj|k1g)*uCw;#yJnuh*E55rzXsA%1z)AB5VpT=jYL;n2RymT|#! z47aOB#vq(aYo*i*6X;duv0Vhdg`Phg8{_4vv9Os8jUF*8wCx%#4hbB9C_@N6cQ{M0 zzoADcG!A|}@d-?o@f+~>cb~!E=WjyaIW5>@2kk3IXwlPMAbO!E!OySUhW=dhS^WL( z7W}>GZt!y^b_t(50%t6rKcWeK{{in_b04~2bwB=IuYMm;zkh)PRAz;4_>%B$KN5L& z9f`dAj+_eD)^xGJbop2Jutk6sUgTLcHh2L3!_yZC^mNG>`-#j)nlU99%?mC*=w)Y)NF$_I+?5tT^zX2cF&A|4c5qjci z8b=7hwp}xvi#2|Gv{pezLfe43Loso&+G?KjY%|T!zoUM?3%{YwPpRkl8``1%KlTHBvIl-0{g$!gdP0vM zH)+C5yr$=}xwb-l={Q!1U(IEO`2Ac6a`#M72v&q29!Hw-=v+_;S5DtOr{fO#>q#WynV);L+F3oX3jZyY{soK=AQV8eJ=RUjO{bt-|(4zuAK4Y%%>V2 zX?SWD^d=V_FlWoG>l(Jqx^wn}GdmExw9n6G+%oe!vo6_h!3_-u9KS#KbjndD|8vHi zgAY7l&S7&7IOf#F;X@jqf-nXaklP;kKRtZ_{&&WL6^mQiE}N-8bH9h|GZys0d$-%~ zT>;M;o7x(WI(f6>*%=GE+FIHuj5AI>r12hj@BDYRHLmEp3f}8F=2UzLWR@=kmK%t8qF9K`d$@jB==u(z^?7Xaq1A(Z=S7rw=XA9CUE zyD)}#65Mj`GU6Wi(J{(1evAq(^f%z6Jc2I-vM$fXE{y)6|925x#Si`0G5TM46}@mR zyo~+}7QUR@j2QVkM*dUB691yt5?}DI0qgSZbFve^+Jz;&ahJS0#_(=9j$T*;e3VzP zSAIXKN9cRZ7kuXHobri(`{94!!ao>)9iu#Jk5|s2IPg&(!T3I=zigL-82LIz{*iNu z{}l5D3;zXjw!_yk@(((JUfAyx3SY4B;jy|9WB58oehc%PnJ-xQ+lg+6uVdst&-^va z7c6`|ymH~sX`}$IX1-wIAK(gK#~A*}%-_meTd3xSVrg7JM+WjQAtG4geceAy?kpZS7?{|eyYC43zte{&PLznl4j zg)irc3tz{`|Fc2-8K;x{f`$Jra<;?QG4dY`(+hpf7cBgzTznlP|Egws;SuHw7XD9N zd>tcS_ESA|9?36Q_!`CtLWxvdCGheXqb$vy?j*&0>bH2!Y!NQ;I3SY;_mwi2tfO3raFW4(z_WeAK z`GST2Zddp^#_-p|><(V%Fki6nFC%AL|8e=82Pe)>!+A6Som{Xd>tcS_I-Ul)T0=_VBzcW#qf2E zeAzGd7Ul~Uz8+uX>lpd6&+O}=9>(wm3;z(8{5nRy>`yz!e8I1SdRgik^g{g8MlEA-XzTgYm%gb{Ey>9ELj?upx*uOh~kMan{pwK>L zU3?uQ|9~^-g`Y5A@Sz>$;CpW>1E6o0|O z*UKk{uVduz;`BQf>P<{P!NTY4vcuOg^5-rf0iR&LVBw$al3&Nj?_&PNQ14>+f`xyS zi?3tkpU3<+yoLCJg|CO#0}pkK{88rrg871lzX1OO7yd!Mj*&0>K5v3@f$|H+_fh}m zz>ODTkg&)XjPD~~*Ei(r82QgEgqPs@6Y~WNzfrjs!`CtLWuNJrKo2l{ z!NS+|1;f`d@@0SO*aG4U7QU`8$k#FQWnb%q77|~u@b&yczK)SE`(gi(`GSS7>kIOA zjC|Qg`>I70zF^_&;gt(t_TOI7NqoV=hiN@^;UDDd7{ix+yZ7xPzF>Uci~h)d-`{4w zVBsH3!Q1*L__9bS)W~l5XUv7a;KFZQ?0kRNg&zcb@+>&V<2Lg2+_RkT-w7DqW&iQ> zmpI)&1{mFCAM#g53Clj@=K^jduhnnbg)epCPr2}6OP&0;yYRPN_@HGF{z0M8;NK|F zdjad=&j3S$?y_(EZH#yG`>W1&zJDcPd|&o?Kck2J|2z4=o$&_7Gna!qWY*6Ako#eP z_3)crxB*@pz#qO=f%|{}_`Ai0?*okE>u-0BuRqd7q}TS6J_>#d;7c|CFsPH@ZsaiW z59+s$QNMozdW6>s_D?Xrk9@3i@WMaH7rYkUM}64L4Rmy`6u%Ad{s4N!*CxQ_;`blW zQ@k49Mqvq_1Nc&MB6s*j`R4L7kx$1MzvDr#@#bdwVwHcg@1u^E%J4Y{0`82ytXi3u<*~u|G??*?tgs)@dFM)D}*ZIsBEd0;7(oe_8 z{~eSAyzXPZVBsH(|A7ntp!_;U{_~(`cs{Ewp(9+v*D><10Ull#Fki6ndD~%|uVdsd=K-wim@ioPD_rTPW8~koio$=A`GQ{r zd?`7pU-2*R@=wQ=%J+Pbb3pTNDPSz$=ez2!Bi~LheHGlXE)o1Qz~$tDX1BUfz8?6| zF~+Z({rd;|Cm7$y{8^;f#r)AR^5vY2BUX|;f`xy8i?3tk%lR5_WWHeG>+MODU&qLQ zfaQ-cU$F2`api}Ok^j^GLjqpTe8IxM&LzK&k)J!CUicyN1q)vf59QY}@^5%2@m~Xa zhWRO2_-}BH&+8cZPsE8o#C*Y@0bEWW9z>7f!apdFj?ur163RKWo&6Jx@1s8G`h$EO zBVW!z`4RI43t!KFERm@ioPdj2C{$H?Ew@*j8(rKe!w>*vUR7cBgD;D6x4KN!A_k$>)5%ow!`CtL<@}isFki6n7ZBZ+U&qM5 zEJrVlF<-Fo_3;`EU&qKlDNp<_F<-Fob$vs=j*&0t==_lRf`zZ^8}fCG{AC>epO`OL z`1`x!uVduP`8&rzy@vIHVBt5q_&P?uoZItt<_i{nlZ&rorDz@u<#Fb@pX)RIge=@^92iEFE1Frj*%Z4p#WxIK;a7(z8+uX>lpcR{!<_G z1q=T$^4?B=9V7pZ9R7XG7c6`|ymH~oc~i&5Nq)h?*W-(P9b@=%{?vP!FIf1;xa8L{ z^5xvBH}_Ncf`xyoi?3tk%XwEXFki6nxqE1*pN^3)=VYPXMg0{l{IDy09V1`P*ZSxH z@dXQCAK&YNhdM^SoXgc`5nr(I8(rb+82NIZ*K1Z2U$F33;D6x4KN!A_kuT?f{fha5 z@qI7lSI!T+e+`8%SonH;F?=0k_z!JB>7ZVLb_Axs;4cEcl$_MB_y@^sWAsnQ=-;s$ z$^9qnpJ3rHAZI&0bc}pCzid{L@G4kacyANe4e8Ixk>p$e{82NJk-LeabFIf1CUFol52j`Hw=o48s>J{6?4jI!6AJ%)h!oe8IwR z!T-R8e=vL^ge|8wBROZYlQzMLo61a=wa7c6`|z8JoakuT>5hSn2b zu<-Trj(i;>U(Ox8pZS7?zd%V}lwZflm-7l&L%odh3l{zg7hlK7mvasqp&mrOVBzcf zhVtte`HS910sMjaf`#AW3SY;_mva?wy@~W6#mJOj~IW!@Lv^wJ-?B!W8}-ZmCrF>u<-Tz2KhQhzMOaY z^-&66u<-TtLcWfXFXv=lbusY;3%`+~XXn3;kuT?K#xEhhVBzca4Ti5{@FIe~|lX$lN=otBO9_rB_Cca?d>+Ky3U&qLob5y^fG4ka+*2R|-U$F4?`Ud$rM!uZmI`azR3l_d!-ymPd$d~h9w=-X`@E23` z?DW?$^5xvvORuEx1q)xVZ!mlvBVW#&efw3!7c6`|y^ybC-|3rU&qLob8+w7OyLU_zOFCG*D>8E4l%Xz)me~iKxEPR+YQWs(jU&qLobAF@O5MQwH zb$vs=j*&0t10Q%T@dXQCZ|@*q$H#e8IwRRIbJR*D>;UFn{i+h%Z?92jPFcP(tU$F2SK@PkSBfk*=T!@i>@>L3k4j&`F zV01_M_4W?(b&PyDFZ)sE3l_d!UXib3-}@)3l{##ie2RE82NG@_$P0n@C6HhGyVrI{Da}^82NIJ z_>xlpcR-uf4}Q22s{ucsICb&UMA z&~CtM!yUvIEc{00TFiePBmXkyFZvwu1q)xVZ!mlvBVW#i{}=NG3tw;VAYaGGm-FPu z@1*br3tx{f@^y^-?N?I-uegi&f`zZQcaX1RteIS?15&N_@e>*TX9p z{)yL+{Qt##!NS-3TgcZjhJQ7*yYNbVp28O_d|h9VuVduj!~ECZM|{D;*YySYI!6AZ z%>Oy_1q)xVZ;-EJ37J3 z#1|}lJ-l+^uV((!%oi+tJ-v{xV+_B*{2L#l@C6IMk;Jp@kB*Ul4f9t&Onkw@$9M3; zKN!A_@&8|eb}wG9-bQ@E_`VnW^)&OJWxinH>+!|#b&TOZ%lxfhpzs9?|9mA~QGOjG zf64Xq!Z}|gzF^_M)5X^@@^5GUznL#s_-!t}j*N$q1q=Tw{106Crw4v?jQl2O_v7`h z$0&Tk_`VnY>1KZGe-U4>@O6E`@O6ygpU3>&%oi+t-CiJH$H@OQ^B>qw;R_c2F&H_x z5F=m5$bX3W$uARMFusrRpRE4a#r(NnA--VY>-80euVV~|{u1VY z_Hhbdu<-Tt#_)BF;jdzT|5u4GSon=fx?=k282Ka2fBh507c6|ey@cWG82Oh#zYVWn zFki6n=a93Ve>z6~r3!!avx>7rgfCp->~c;h#|#zTSoJ0gT@xWTBmj*ZJd4 z{v9s79kBX-;dAuEcpdaDc4z!u#$(XV!YlD@a&Nka z@HWPyjMsjL-JxBC*Qrku-oyA2#-q?~!Rz4flKT$Ek1!sEb_rhVcaZx6XeZz`>wEk@ z;}wh>p&fwNOXAM>zNhH@&0y#8deip_H-g>8>-~(gjNkYJb_ctP*RL4wV!ZCZ$vq2p z6R!stZ)g0DAF}&4azFBa2seS9!s|xH+Zq3c@nK*`@Va~_y}zCDnLlFx9wGOyGTy`Z zfFC>cq0xogT)4-D2VD3f7rxqs?*xqB6K(omlIQI|A-s$6zCU%!)91oB0Y?6k7l{9k zpAjBo{Hmu3Z)1Er<8j8%Gv3Mgj-S)}O)rvv@7%@yGk*0i*nh^qX1tB@hF_BVIOFdy z-pTlVzheLYLH--RX8#%gneiCo&;N$pw=rJyTlSyvHH>$P`|sHQm&pG;jF&LJYd5)% zF&_Lq`_K4qjK>*wK11$189&Ro>7V5PwSOS@C5*eDW&at^{3H9%_;SYMjDNs*C*$`# zNAEZNi~K+NPwYSApD`X|e9a#ApYfbO6CP)5G2Y4ekiW41|0e$*X1s)P`mf|Z#`v|* zv;U0mW<1XL?~HdczVUDD|9{B;MSmx}gz?`Qk1_rn=sD`|HpcTn4-t&^9&!^e_bawxu%NzoIAg6^_k&RvXU|C=KqpV3|Rv$+H?h9~>W+{aku?Ei8i z{oIqM{Qz?N5SH)zkD5(bzSsXUIh~xpy&s9c+w;{+-A8XN*S~U%EfJ z%lGSVhK&~Refb{!4~*se@=qN|?guQQ@Rmcv4&Q$hz+di%lFeW4a-yiM(jQJtoYyFCNSug+oS5f?B{rdM9%X;(^jwN?lU;ZA( zvR?eRjAi|I^f(Gn)^pFELs-^lKh9XzTYu!D9Lfv~J^evYxMSH7o_ z+-3dodtXgh))Sv~BFQi7gFnFd*o~Cm_W(xyJCE_eYY5Bw+hb26EbD3ihq0`Wz3sK+ zF6&+6Cli+StFM0@VOfv*OUAOk^v+YrUDk^Zy`HeF|1?e|EbBS{##q*8Zhr&0r{7KS zx$%vJW&Pyp(+JND(>$^JMOjy=y9rzZ)vi|D3jAcF5EpH`vSs#@>gRrc3I^j&hvVQ4F z#x-5xBrNNNLW>B?`kyZ|mi0XOPI8y^IjvoUWxdTF#s4khAuQ`pzQ$PAlUy4mcUd2@aw%b1@A2AYgk}B4bBtv@#`WFgF6%26 zolRKQOZ=6wtbcg0humd7gSDKntWS7#FJW14@FZhdKXCcm$X(V0EL=fY=J#J@Ec5lB zkCD5~zi0ahXRjcAT(FYx&5ZxeSmwLOSCPBSU%&qx!ZIJ-b1q?-Uq1Zpgk`??QN}X= zyZStGm-*bI{|{lApZyVInQ#5@`Q$G1rxEyY63d&+hyI1J%x~WNPI8y|O3NfH^N+`0 zKv?Dz|C_PQ4_*@|_ftPg=`+wzSmy6eOc0j&xMvy5{Mu&+$X({kau#8k|7u%JSmv{K zF_!tM%hr&)%s0Jxkg&`j{fn{82i=_{cbVTwt|ctW#17R5-{yAeA@4b2>xy$(NJ1-(E z?lS)Qw)YU0@yvtXOL*0dq;KD6EaQ!rzmMEy{4h33SjGd7 zycjTy-^uOkiXa+AKciDgD8OE~z%xUi@ciE5R&5UI{@b}{WIg;~eCK@xIfp;P-jF?_G>#yzitd*`3Gxe!^JB`w~}?yNvhU#aPDsR(^!t zA0qh=+Dur+`>tUu<9$D4EaQD2{3yMj-A4SkUQJlW`<`Gd<9&yGjNE0s?*Ya#-Zyv+ z`}YX>_eaJu-q(CBxbFk{^d)j%2zc&6qoGC^*TCx>#+w*t8Sh~HE9Ap?h3qf%!RrXi zenPMRIAPgO=*Ns@|DemSXFiOJ;C1jP2+RIKy?{}k4jvC2WOo@aJn9B|U&af+3K-vi zf!}|{C&^vL2fxEu#s@!qBe~1?;8C9o)dZ+!;6V zc-{rKv;U0ee3t!Zyp!=Z#?}^cm+`^-8O!+K`FD`Jj1TVfIrjgb6rV>Kk1@{QN$%Si zzr_5N%8OAa`_#4D9J}CQZ{e`iN7asI5xy$(A3<&d3Xiv%h<8Ngw`#-!(;Zghh@=vn6 z?01FLBJyQFEtu|6SoY625ZusR_Os|_Ec;VHb*kKDzba54g=N2~#~I81QNLp>`|%tO z5kUWCf2Z|~WxpgiUPrmh{zd!GBrN+8Eo3bF18rn1`!(ImSoR)L77{2Uh zzJRgp2XiH3IbY#%#D~EAL8n z7|VV*N9;@Q%lViYT{w-klEsUFB+#j#M zF+P{wTR}JBe8A9QcaZxs#=VT=3Xg`i-b(K488@-}M;Py5_brS!-%jtp#Q1{S2zMQd z;f;nif0ppO81G^JbBr55NA7PvjNZ>OUcq=P`*$^BNQ2EB|1FHSGky#)#Q8+l&+jm9 zWBfE=P**CP5ad5x_>fm9N3PvNp{NU|UHC&TJm$hryYLf-JN^H=3okmt>3)d|f5nCO zxbO)_I{Dvl;Xk|Z39od%|0Wkc$A#Cs@VzelFBg90QBMDRTsZH-H@NV3U3kBvo&H5! z_!1Ys#f5+6!Y3W$^zW@Me1QwU*M)C!VLV3(l*`tiV_)UOtuDOEh1a?8EiU|h7k<^T zPXDiU;b&a@DE-1gt>}uzyCHD9(LjDUHHFT`1cBr+W!67gR8g_70bO!sY%h7rxSkZ*$>?UHDrr{8JbHiwp1DsN}cho8!VwF1*Nv z`&{?}7hdba?{VSlT=-!Z{Q4=ZG>%o z*zUsPg#R7l>uHz!ZWsQu3%}^X4JSJFZ+{nlg$p0+!mlB0%M*6FzZcrG?}K|3?u+5R z1n&34eJR`@fct}Re+cePaDN!?%iz8o?knKF67H+u{s`Qg;r=MxSHt}=xUYfxTDY%+ z`{Qt54>z`@Z-D!gaNh{`r{MlH+@FDa4DOrYz8UUY;Jy{^+u*((?$5%#1@1fG{v6zQ z!hILqcf)-T-1ox074FZ&eIMNS!~Fo<55oNr+z-RO4el?%{YAJRf%{RozXbP};rxPJ}zZ{Yqd+`of+H{8F6`x&_Z0Qa+S{}Jxz z;QkZbd*J>v+<$@luW&yPH(U$e4S(MQ_i1pS5BEFZeka`P;2wc{J=}1Oy6>;U^Y6p` z|MlSItp|-E(>%}cd9FKBn|+^@uGke0OIPlEBD;Q0y8c`{OdTJ$Md65XI-a`vv!z`g zRDaO4@}QP8vB86|I`ut~N?Pdx99kYPSai<1?UYyNU%Qd)7mTYw3z7mh6lMLZ+?8ZFbEl)Okh5%bL%PN z^&{o=B$$B3e(NkfIAk?9O%&E}dg7EpW($_7p72OVYj-9QPetLd=CO<;~ICW;ytEW0%VFN-bSQ`qRnW1dTDolCwlq#0wQ)Ojr zi50ADF$)*N(e;I7Chg2Z)b5H|*l|uSo~?^McN(6RxHIhe)vl(aPI0vEAzstP~iBLy-?sJq^U1(98z0fJh#RwOl{$&u=ZkcqX4TbZp^8%xREc# zLXy{-J1zz1SM5SF>8oW53Hec`kg$UklIEUx+GwJh2CD)ie2x`gCzS|RFHnUTZTdrH z9KbfPkyJi}7v?vn6Oj#8Vz>atZ2s_wxjvIyXXaJZ@Re|r{)$wrC9f`X+uT-V3%N*Z zt`ra5wJ+-CV&M8y;<%rl1Ax!Q{mHecDlg0Fg5*tQkIFGAy~;;vDz!)?t&0}LK+ha{N17U|QMp!?RW9wRDA&4N zf2%oUB?iq*av)^pvuSHhMtg8pEM|6^J$>eq<*~j+3uBQkGZtB~D%uHh+HNc1k=e8G zY$dy@$c-iO^gzmrC7``;ggbK<^v~!~q!&xCDsbs|sy&*|q`)mQgt=KlMKcDk+i#V9 z$u>S{LG*yT#Q2~?3)!AN3tHL`ptF$%VH7)O?c6A5%~V2_uwzzXVIpDW^UynTuv@St z15~U(noY24F*DpWLBFTi?cvvZVul%wwL&d{#1=C;0zSnSVZ~-NQ+Oy`E|bDQjdt;O zVF9{Y{b&-E56Vr%izU~jL5RhaHQE-l?UHN&nQXsG91R0HV8U>wa=APz<%dE1 z&Qv^~S9#(PrPw*G5I&5CQMcI^m-+~*sUm`jo63zsrT}RwkGM5a_Vv=F0*zsH5wE3r z#NA{~U5ar5Ex~+UXyUlSd_A+1@W7Z4`Xb%OhO&i?#iT)}=B^}+B)~vID$^fN>7jsQ`{Go`c)krXUErB*xrQTdPgMj z%QQi;3}R9`8mFr0*lD(^V}57Kis#rndCtQ;Mw`1BMKEuQ<-*x@26Yi)N14KB$DLma zH^ow!^-xkA?-t7_zt)U}VPOg?18bm{8$4+jrPu9ua|iqFBw~iRsIDkCgFF+KSgE5X zigxpoc-}v`qzZD22I=74cc_eQK8-N;T))Wp;!#WKpO2uSFvJtC>@avRFjtmQ_T1dsk@p> zl1VI^WM7LK&Y`kV#u7=gb@b(6yswZLY+qsZ4dycIi(=bO6IC1b3%ZTB%XM=rCkp09 zk2PZDR#@?Y<>}PMST>%pcv#D>vF1lMB&;lsUA0DXIk(*|H3-GZv^2pS#dl(}){@Q) zK>G)48mY@cW1xUbhJhl&;HQiW!A=Ut@p(NC6{Mar$O5@_#EjAN0 znn)&f*(r3-lSeZ;0n!_~w=*So;aMH@qNa0194Aj_ZVwE;Bi?6o# zWuSOAhbOEvT*7vMnHnDIhw*T?q#b=3&R&mF0)gt0$;0N1YU{SrYYKx}(Cje(oLsVC zm8r54$=)Q@G8kpMj$rjFM!{A?Z!KrkRA|d$L>=S8DiEm==0io_86RFVC{@`q>Ys)U zHMEgTz$_h3A%J2J4Q0~N?tUW@!ERRp>k%`h;%Zu|Fq5R*zYW8{h|P|wO4&$2hukijnozZtHdX)+B5lx61oIf-$tCGn`tl1Zv=z(5cCb+M?Lmk2(CUCVK~vgjG0mI> zikP=de99SDfgzn57%QsqmZ}2!R`uX`QDVb}cz<%lFxuh&*cvvmjcO)g?xoyos#}{Z z`{qEL48=f-{-)Pssb|SF2TN5hadE~OhFg;f zm~*xRk?idshCUYz|6w5VtSGcRDe`Dqk>1A%#*nG{>X;%@(K{aDXqGYnY1pDbdv~3+ zu@LV!p`y)gEc-$hidZ6<#hfaJFr3cDb9wNR1X2!btO95aqy~zeH#3kO2$|+`&4N~} z&tT3fF7YI>)T4FaQ3@LU{06`QYjqrk-ii;b^Z=yjg(mo2e3*s_Gm1{}8RQ^jn)6i^ z0bPEM6F(YKBZVQ*wV_0IW5`5PZ4PAyhEo>g&zdAmJwtBg)0jMk)i^XF|0(1WgXjc* zkqCbWh9P_4FVsltZ#pqV57O!l7^S{&*cyf+4nx49fsHAMRbjZ_>`$f#Adq=D*^-~P zE}onR_H8H=j=MwWm z^7!;bqCOt4pz3K}rho0}kjju1#h@`nJHU)GgzkZ-$>u;nZupmur}4(pm$HUHSL4`D zGmS84SnBjaJtp1B{#-n_ab9OUF=*u}rPgfB&NITN8*QgI&jV#n4G&n#VctjwkU42= zK_O+Fp$^42_FHC4GY95$gbC|BDgzX5TO4c(sS*4RXeGlS40Zd@whDup0r&K3+14R0 z#h9$Sug!{s{l|eJ9ME=(PO;MxFm0`eXSRGefFlDzC4#v|dsH`9*=&989>=j-CmF}m zC8hU^^5T$28xLf4!9Z41nUO4bR;B~N4G46UDCol*Wwp(il9d8Zg-Gz?g?v#ToG(C0 zfzoPXrCpQio(2_<8hYa#br&sTFU$w?f|My+7U4`euwT%NgGlF#r4e=69rL|7lgkNE zZcaa;Eix;sjo7W7V7-ld{;vfmMV%$o(0YUAy|-s>OC-@IFew811g4gpGz~CW9qr5l z;!I6RD<6`q$vJDv)){e}{$E~<;Ow`tUP8kI3LLaXU`oWLW0WLC6`uT6TOCVY)zp!^ z)z#7O;@Nr966k`VpA;@En+MbVLoo5wolIMO(7(^m8_wtK20`KtZq0W*C zZe{9mJpx#KnAfD~ZfI9fvqf($s;01&Bg>}h9~>65N5WiHU$@a=x5-Uu$5D?TE7E3Y zHnuO0<5I-GqjjnKUyaF0sfM{$^Eh6ZNb>fId*g4Ijij7Fo9d4F^ zDoHA=*g-dWiA%W2?aq@sMloQQk2nhkCeiJmBfSh$MrX0TWlTKfSRoi_DtZq_tq#DD z?BSh?0mB@M9jiJl18Ty7te7f@u*T1o61GGt#Bxg7gxZNs(MszZz+)J~>7e0%Wv=xF z72vAom?T&1QKMp0g-VY-a$VveD-KKihP6@9PqddVk)FHh#RW0Ngw+LXm!aA6bfb-? z!nC_Xu`!=v_8mvqMGQ@u^`w%qIj$MI!>uw@ z*&iRU*KL^zkjOdE=Uml=^>O`|K-pQt!-jh$Own;3*mW&mo0^EKVa`n2l0opj7+*VR z&>84N^8!7XoagFqZ;CR&Q!`Yo_hQIK2L}z~d1{Oe*Z1soDH5s3ax4xfkv*VVrCvvkpf1Va*t{%V2R)T8(xBlRUEXKU@!14dib9i9-h-tU3Ja>tYTcGcSEw$0cGn`!Cz(xPNwrD0*nG(E zGOL%Nm0e-=vKKox?J|0?d($nXZLFwnu2e||MpUO=UFyNEPP^!y?eKI<>d$UZx75nc zM<=)Q(=F!&?E)O|406dcCTs_kZOi-p5P+RveW1>73mB z1WRh4#wb{kC}W!XDt;)Z57nt6-Y1`Om9=HsG${?`R_?rd{04D?Aj^NrS*CZYCR3o* z&{yjxViO2LV{+5oTB?{m<M?dyF;&ZFkGE>2Vnzic))h0xcUhg1ew&wUDpzbK zFEfFR=d@SVQQygeopwz1?si_6j6iER$?7>+rUENp%5Ek_3xW*iepB^a5cf|ctDSlr#aY;Z^xChPCQ+GI#U`(@X*eckZw+kmyfY-_RC zdE@s4dpB0H{ziqY;x^Hqd$70@*ZipXIam}+qUnppid*%0*pIKfxdXqYP@n(6EEI0q zVXjXW2IcD!6P7K&`Y256g!;m1uk6a#O$$DCsn)K=JoUL*-Gn;{!jklCnboDZvOL_5 z2?HNIrPCJ7eu2)winTnhT!RvbviRT3ZsIh=<<8~hffZ8|r9WprejS2>Q`+eoF+s}l zE0s3vDD8>Gwyl%B0;afJiA;b!6kFmTBc5)D7GE1-@t~d0kM^Qn=?E?`LOm$8V)fjW(f59M zMmw#0TduxjR^L`SmP2W)p)ewP4#NL!rK2w@OFk@!srA5Ra*-WMH^XCx(p)45U%6QO zHni<4)i=A|5=m9hdYB|SENDdao@m9U{dF>T){M3qcdj*R+6lO%C^o}x7`$-9T}oS5 zrgIZI+9lP^vRCj?8LQjsHmV@1R+MrJ3UHxSnFR%1mBuVQ%@UPV2Gc066tzmzh5?ed zius`+O6{B+TIOMLC`hsJJTnv^q5Vw@1ttkU1Y)nS zOKk{{b8NGxT6kp0YTU=qwwLwsO=|bL_-4RbO!$oYBKS_6H@tK%imoy025dxYS|FwUr|O$bQL;}qyQ?Wg zKoYwOgBxJsotDD3$Wb}nF9;LofD zEE2xEdDE*jK8;qu62D3tRcdnmWrFJ6g#*#M3sMBU*snlmK^4~QCc z%T{HtZMt>EyB!Nq()+Vo0g8Z+p4xOPicgCaphU0I{^+*UZ{n-oS@Sga&VnVp7uyur zq_4tK1wRf>yH#zEEKpkI-HHV^Tm0Fyz(&VUFDy_h<K@eR1jmLjFzVzor9-CK22ByH?ppYMqWg(lkoy z#b^a1QL8Xh0TbA1n5yj~O`mdjH$}lnaDT=p7_$56BTb)X_%txVNa`w0io+^apX92q z(K_9Iq@c*{#oPoj!K*MnffnCsimL7-1w@U!8>S#;hCeeE#F+T%BLzf*e1ajn_dZe( zG{dKX2}V*^X;Q!{){^9^kJL6jeWc*Y?Zw;#F~O@aK7khBX^K4dkpibi-VIX_GsB;m z3SvyE=pzMAhkTl_AZA0A2F?E=4A|{x-)kKt-)BYCPfRc7Dgen@g>?#&v`%B>sb4hx zI^o^+1R$yXnVJ9y?zuZO{R-jJkOUx+C$<~munEV?4Q1iTxx6)CX5-162^-)K!6}Nh zC3ttTDbn5F6p3_(qf22g{SGs-w0j6}1osOJ8`-3lu+}H@76i}7DVhazYApiD#|fy;n07Pv3wJ|z;*@#%||9DYY9 zNNaD?IeGTq@LqYpCfeGv);ucj$@FVVHhu~Gjv$? z^YqXB{N|amrA?~YQgXa~Pi+1qA2lq3gMLW0>LCm2j}Jxlz56MISC>N-eCd*Jsa1~E zdn@gURjM9x)>*TBi-Z~OL&5xQ$pnGbW#?93+T~AVrCRmg$8TcQs#(Z7>yJ)}lb2>f_s#amDmsBZCy_cMqRhXJ&tDnMD zF9s+~s~3f-Wl9#psLM)8Zwgb3q)K7xz5Yg1m^#T;tHRVG24DO1%g6i>gu=!D`eK|1w}6DkWJ}c6>^EN;Q^xH#)(nRkW-h+EdMsRTKF^&y9uo zjp+m(3`uFds?yo8fgAjazO1B`w5{<}ZOSN#dR;sd$zF~Fe3B3^OWA`oI2o<$;ABOW zDyc|n8mp?`V0uMe3aZc*Q@S)yeJ8cD@KZCQS~1;UCQ&F;l*b8Sy_@I9;VW2ohIJ8vr}|rDeNgK@zlLio%yFwd_=^%IDO~%v3I)!4>V)_PHY-fS2DM{;BAgdPx z3M5U~RaBqaK0}8v+V+}-taUP~eu7p^QPAvKBvl1+YGxKEE094I8w+HeWUIA6)*=QL z7Mkm-G&xhlCqxiH9VbL9YD-|GoTMoFpP5wUaB8M)E2eDVz9!(_3lze-Bxa2z(7y~= zIHn~E1K_^_~dSpq&VfTl2f zt=J^)o$*wvKb}|@O|Q-C_a zN))spl@};bTda^vrq`epi$`LuCQAX)$XdC=#tKr<`$buh*=9yZz^ho7sUq7<5_M+M zg@!|6z`%Bv2E7$!bf$Q`RWYod!sR8;Igy)pFxDELd#bQ>LJ&RUbq7p$DQ z&dT*$xlDe7lh2~wwfI&&^Si#g!VRZ);gU+y9rR?Na@6#7hPDN?LMVqMF z@Tb?Ua;PzQfye60|+7-|#pJ#R&0_)(-*8SRzq_WoIQy%WLTSJCyBLVeWSrq`m?S`Au@Y zqhIEeVs0~qJ51OrV9z%QEQU#+WzaAQtE2`pgwIvOm`ytvrf}3 zwX$Yj&X=5KJ@9G$raO5JqY%%nu?i**15MsEKhLkcYK)RLUvM*)K zZTlr)ZDH8PQ^P)B5_>Tm!4kO&GZIk2okqpmR#84{lPOVi?4T9lI3@MrZW9UUt4O~@pzet>!n4Yjgd@u@>bCt2%^-^w!pILh9{>z z?FSq)8!rz9_ty#tknX4^z|yM5Q>R-|eA@p2C3+d-FQd4yfngpDF>cFT$eGzpG7VF& zQOA~tINcA^LayOR0|#kc=Ap(u5u-TJ z5b-$B5Ln^8v@rAu55Kk7lq7u>?Tz5a!P)u%#hP?-G`Ml{+!hIJ6#TVJ0vjFGPU)Jw zof6mx_-wTVHa_LrFz&TbEx1T0x)fI5=qr1)rD4!yf%#;|bh6P@Z2v@!CLG|Pv5<&+ z5To2)&n0H6rtJh=O{~4wW1oJhy_nVDC3Y3|G{C|;4XLkg{In~O_hJ3uWrRP|8N7J- z?%Pkh_V_fG!OMbjRT;mI6mskZp4qi-K&?8ZWp?ldx#cB5Z z^&f*(T)Z2>pl6allNj_^`R`N)OV50o%b;gZmBzEg`upF2YT7z}(=4(V(-^R1uEG)q zRdT1{^VQ#*UcK>d=K_`m{>)myBH_E6H@!;Z(`W@O@vF2^r6$*3CaB(By|>2n*SiZ+ z1iaXD$@Yi#-gIxL&MZfaI;h)&)^&r)8_M*EZd%?cI(ADCzxKtpG*9M^A0K6~(7T3Q(d~ zX@7KE>NoLK@2uXtpL?-J!4=+%Z3?XPRamOv$H8g0s_l^lsz`XZVu8&Te>N?!(ecv@ z3zSOvw0D8ckSeX8zTG;ll&^A^oEF#A+0^ZlQ}ZtQb&=GIT?l2U#hm$o*KEm zn42IbcooJc(BeByk+EWZc09HjlO;`}Kp-O|M zX9o3MtL!7S)}`km8<1D{oFE{QdNEqT5VZ<36)=IFhN;><()6jZcT*IM1ovlrf+4$~ zKGO7QhED?%jHIs8q&Tc%^+~Q8iS<4_um${AmSkNd^TBkAc)GwNTo$zjZ0+7`HOicg;_uL(teueO9NCJ?^ z6Wfh&7!GZP1H)kl+&mr$5Krbz*x!CAdR~oUcPE=7-Th5?96B5byDZjWMwWID0age9 zgpF*{N?7ZYc?*J1!!bd_2{=R#j~r+%48!r|(WSU+FTHHwY1sG>HrgLZCaipP>ACrA zUlTe{z5{p-@lZXwcF<4|OFuMwFPysPU)!ffXfO7$7L}P2sjIM-!Ij-;yjX89HgGu%flyyHW>%*#q?*(5ZC14kQ@x~0Vd}l&zpTR4BwPIy zrg||zVOqT?Of56w5Jp`Vs(MqHS|n8pQ}5+Zn!?mcwptaY7BMh0Jt&O-Avg%2F0=NY zw8g)eN>%DTuToT%x(HUIp7@sm^AMG!yQ4pzPv&J5XqEfuOQlGwdYXIUX~S5U-V~p@->f>SIoAc%YI&+1uWB0@I1yJt%oeoU{KRWeWIUb=MzgxQ%ys@ zF1@Z{jK88T1y$&ZDP5YUzLQ#&;i;LJsF?0AlPHua%JoRs*rk$pgihX0s})m{yEwByzfE zvnnc7;H0gXwtDgPo4BgzPR-m~#gq=Z?2ckvhs3R0k@YJJ6jz!ztf*48&3Hi=b(}Y> zs6Rmxv|@_F_jb{AvXG3Yk{4OkPsOV8IW-fU71KAsV#7FBy^^#{sq{QA3!_~%iGhV> z@*xvF3@ZB5H!oXJVS*&6_X1gclBxnZH514c)7PPG!4lh9AZwDXeg(36F`z)wymv+Q zsckb22&2u_9j##*dqsr_lAsk+6g0b**=JQCr)Gk_V)_PHY%GvjWG!M~Vew!g zYnzkaTct55QchA7{fnu};nb{tn4}yAQ)VcHbrGz_66jwBD1NkJqum_J3=F3%EQ{U7 i{B^nhR&&To44RqbfZ4yXVC9ud*vMzo)|!ml?f(MYE9-Fp diff --git a/node_modules/kerberos/build/Release/obj.target/kerberos/src/kerberos.o b/node_modules/kerberos/build/Release/obj.target/kerberos/src/kerberos.o deleted file mode 100644 index 3f2a00e9ea7cdc9bc2bcbd44798907686be8439f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 573256 zcmeFa4UlX}bsl&TAfABX4O&Z@)vl$+Ld&4#r*HNDF!Mye?&?>?>pyk%n;Af(qPpsK zznZSDYU-!od!TuOcuYXk(Yvg}VPkKw%dTS;3P;$>{>TzyB}N*|fY-K0SoRVoLa<)T z3m*N9<=xSMEM~uR^5+M>qT8 zxA@*JKDr%$t6xvNUHl?^M9+)=*@fW0{XYD7Mere!BmS*cTg`sdt+nRWw~g;Z5|5xR z2%et}0&1iBkJ@SeSFP4N2M3+DN~>0v7q=JHR}g$mw(H(F$-+mpn*RY`uitI9_he$V zYSZ^IN#Ea+1z!Yx=6}>=^S^4fQR~;@6qmmFP~^Q+g8UNrLhXJ29TzM*Wj6Yw-f8#Z z4sr2)NaDLG33(p)h-VibybzQW660?YpWWVIS^)o^?1aO22z&+#>u0rk&}meg?PkBa zJ80KIuiYQtm=oZte>ZFoacf0GeN*E5o!=A$ zJ_>x!e^!?$e63EM!CZWw{kFjK|9(_pdGpI$i3_~=YCAjK=!odG>H9k$7Uf&75%_-W zI3K=dd$&U+Tzo%zD$4)ePY5zT{#V5JCir)a25#V|uUl*HMZF}xXaAxo^o{$tZ1B#X z6yM^D|Mj-_pjKxRUHU#VE6S^JHF0SezS`koE2_3@2Si??z5kQM_k}G%(HnB&>+C$v z9qiIKI2QE0Q8w`RKQRJ*hqbzk@2^XI|EX;75Byj8@bzyUdfWTU9~b5S)}|ovC;##= ze9(WOt6v?oZ#3JDYISv4HjV$h?`yLBt3~Rw|NK>~S6;k%A&^x#{Tp4c?sm}|0^Zes z@B4j$Z~h*M?+*k%@f8FR^Xuw2{ng{G*=CF`|33LA0^c9MMU=Ym9r1nhgF+u5)uNC3 zjdl5}(4g17nlnjsKLq&CVMZt$G^Y$ z$l}9`*A}-cr8|FcfBE>k-y|gXeIa}y{7U%cV))eJXGsi7$Im<-$jmR?TRwh9{63xe zX-ppBS3dg^{sW9iJ$}0M%E> zm5;yh8WGrfeP2h({a6aR9simas7R? zVT4Wu+l9I*m)0uB$s5pH_2uX_mfd(T|4?yZ4myRSIrH-nStE?#Z~3muZR=lO(Z7BQd=Xfh_@zf8kHd-b@joaX|KsxU3uQe-p7@e# zG?&6qTUCSg`0K03|FU%aTbu!|@!y!4tH&?MA~Y)d3u^d;Uj`D$JzC58X6Kwf@g-5_ z&KD-A*>R(vdrH$PwZ`@3c;_@GHcKCwQ88n#5N>SgUH1+te-vomUVJvC+#HdyB2_++b0*`9o+LQm{;z$1b zxYM60oeV^?SZ#271=B!Te?ry>z6yT*2F5qk7b+1zrIW|*TRs`wTROS+RO!jD^j{sm zfLzgxr{v%*ojmcYsO2-O$KP5z{>Jjj+V5^|Ru&%?sKLt;*r7hIC*)~cNy5Vw^nK~% z`%5SHmF_$}salND@LxPhJUV%K>7?}1#a}7E=EJ}F{GYvqU%zwbJFma-7cTzFmw)YL zmGJ8yeb4<->GYw0@>8U>W?svG?wQA*Uz1@L1fCu%Ws^39&-kC`SfSsc;9nhM|XZdw}0lL`S6hG{XVFy(#7JJN+&PV@&{7i%QVjX z`%6mzR|!scG-$uIXYrbDH8Fl#*b@?t1?$Ft+7Sqs=x z4jD%Vzby!JhU~xZ^Lk8_o_QymdC$D_0;C1QSP*dMH}5SSUsydpyiX`(rf&6gfZj&e zO4|v99RI1H`}nKq#dkVt`LA;im7cjGYPce6;7Jxk7&W}AbbRB!$DS5F35l+3mhSw* zy}{u9q-&1JvZ|^{O6v3i9f$KgDipi^r8P%WdF}1`}ZiD zd=i{Z{hPO)rIRaYvX+Q(?A%|3l^$zKLFlotbAJ&t1#uPGX8zHSb349+ zKY816PS(ad^I98!$Ry6ZQBb;>q*U97|G%|?&P-Svr}d{GrCmI==7rt4k+0!KP=PmptPSQO8G~>c8Rh7XZvPqG7Vo%YXg`R*fk1 z^z+Ysz(mCSR*1aJFM;``(_bfIL^Do4cwu$nkNdCWFJEP^_<2ysm3{NMd$?Emin75@jNhx{K+5 zfu&U>lE8AJF#_IEe0K1Ir4N6B#)j)g0K*Se5!dp)UOxU^;Z`z`VK@o=r=L262Lg;% z>m19d7P$=htxtkypT8GItSHEiIjoZY7>+2J@^!eUR*(Nge9589is9v@)6abd z#aEAo3#jzW9o{5EQu*YGiSojqdwD0(N(b|ur_ocqzEF#(SPo1=jaCxNE@B~)aJ#rX z(q3>iKtuxh>(r zdI-3OA|fBa>hX70kN-~wRR~16)0z9zN&hA^-`yhpuLAeDq~HFLRIV@HMbiJ+7H+@S zc?j2k_lHwS{~JJmx42$92h!h^PWrzgeR+C!Wc|Mb?z0LE#&*(0zlZ$?M)R+$Z z%b)k@U%#w>y-K_2e^&qcJNnnlwF=cgUaE* z?C^R=4xFWv>W`?B%3Ei7-A|wR>gw@a>G;Zp#h3mM2hTlL!dm`n=_F@MG4j{aL`qHy#&%N3c=}JF3 zNLw2}I#RPbMze&OU^gqmE)y*RayIKti4M9)j;^n(9P#(`+Lth5V6}70&{KNHkJ<*0 z=}Gm%9qh^veiF@LZ>ZQNDM@cAdBI^mk-PJ;m)-~4_o1cN^H}*NtW4ONm+|#$Phi|| zb&6k7n8^$K44)JzonCCeCOWs4tviBA1=Utg{Zg$VQY0*&^nKnG)&$KtC&oWQv(w?L1v*#yJ)lV5zr%g}@; zq^%gsF&g>v+`5?$iAEmd&#(1SnI!+A$3%8bWZ$Cf8!B7!75?Xw+Y@9nzrM8a-Tr^V z1~YiDH1XU8Fn0n}VPQ#ZeY$k~UW|1BpS+59w4{6av6sG~_^J15pnHK=tQ*CuG{hdj zM?Xf$j(_D7{O6;e=0CrnnGMkr%(nOpeZb%3-8=alV=%V4?@$8$hmB_5=8iXKIqUOi zvtS36r@dQf`tLBp)#JZO)-*UPG$&da@6Z_BFQpwTqM`mcOx zbMm>DV{x^5^1o0=(#ZIs^2sFJ|o|+HU)k#fz_h75%dTmkVv1=_yFC<;z;jsoku#GW0`?#MriH%@`|l<$Mr3xI9fB!-pj1DJpNZ8eX6)AYes~ zZx=Vbau?#7N+;_;^vnfJSnm+q#21&Jk@`wvwX|2vVWq&tbow9BbP699^wTpd6Brl4 zbN7{=DSm^0y$;F*y6uSO(w8>x`#hzVUj7cD@#JP^hCfTS&ZpVp-Y1{90eM{fCh&ho zDHr_J8^?L8`sU!ZtH;lS&DaEo4%fXE>jo%fQvrep7eDe_Xq?>YKKTXs=)T_n;qu7} z98O>CPm-ZgKE6Hitxo}HZQ*EwbvxOC@c$86?7t&$Hc5_3CnQOv`+w%Xvam(q-z%LE z7J_;2#B&d$3^XT>0)5v)QVjpa>T!KSmg4EdK(Thb%f-tmEDX_2eU$n-DYE=_~IgIXZsT3s>%a z+2H$Nv4P*QWDD9Xp#BdKlZ8@H=-4QbQUnPyT(+2=ROy#5ethM^$6&~we(>J%>5#*0I7P27+g4ui7{|HX2EGSxYHFG-iCb*Mhn?!)I!FTZ^ zZ=%J7I$e26rx>+Sh3Q_|)8%6^r_#YdXuAt*C%;ZzyLR%+L+!%V)8c17`+Wd5Y_5O( ztvi}rU@RRMKl8#8h8$)~Xwg@|6Y_c{GN#$FQ*Xom`%L-x=RnB+APD*Op@c{x$o+Sm>ikSg&SDG(qrx&wu`E)ZK}? zo!(Nb8MXUCuOA%-H@daM0M{S*PcQ1yU6P<1^$u}UD*mz5Y3~NOJVp1}mT+gH74@S) zp{qpQqo^D7Yu&x5zfR@%WknBcN4@@9)W6;9TCaDb(`^K}OsA1OLgc>fZEwf_+O;kEbd)@lm z6-(Y$uWR-M*96~d?TM({?Q|zP_4=UOjT*AYO7gGz^XHT5m;Lu%d2h{5J^!zJQ&6U* zr-1)ElblBPsOjh3Ah&+^`@HLO@wxT6-wNJMcfS=}IIUF0Bb_b=f=X9^*QeHN?J!*I z-D=kbL{Vk&-}Op=s#*=h$tvHA>^D2@S@E;{o^==bT=8a9AM~T*QSn-9y;7a0tCUov zymGWzDO8L2uZr{qjPg#s*6(!7l{uuY993p16E*tl+o|;;;BZm8^%H)^5;tKek=#6+ zP(i1_;ire%Ren!68SB`stIWy5ZHSk1?Ga& zzV*sdl{n{brf8|3K0m+K(FJG2C)#`F2CrYGCf8fVL<1MI2)fn+0}=vL0;?*^_$Na? zW&3@ci$#Nfz2`g{m5`zJ%KVUqEuvvWz?rKjjv8%Qq}!+ytE&&MO~4@NVa!d0lW&`R zTR3rly@flpZw)6WLwrxqzHR!=zKQYe*I{}-2_j;$j)H%FW+i68H)ONSl?Dq`V zOB0uZqj>|*WvCJ}KRBwjs*=iphiI@&H{Yx8S-+}BZ5Wn&*V>I}7q>wh#iPLZ3U)f3 zmJK~y?yV16Erz2Xc5XN)vNyUmMuIfb>_R}f-G%m`s_BQF3ydqZR!?N}FFT(If^8@W zA|ugi+KW&JGa_=&_B&xLqi1=;8pq}-?0Ss~m5kGARYEbc}uv8gHeb``V z5NMeyFbMy$^HI??NVNnIKWzx~4dhMq4gIilNmv%UdxHa5()NOz=c#9;AVmcoJGt8HxeB1DH85}^C&8k9WOdG{e-q&fvL??9^7V5Pe6u!daUd`RxFsk-%fZ#-9$T#5+~6 z@yc%pSl~5bf!7ZTov_mC)Ko6_jG5qIR^YSKF&zvp6C7~TXsiHDcq_#z04oqtQm~caI6RCDVXa|h$n_{ZuUv_>00FOjFi@jcSu+zFl zo}p$dYOJwg#_UYZbr8|8=Tc-N^bnIHGPIF5$3`%}-4U!M^L}O(3%gbszvke$BA*ql zQxrt7R=c$mF$mjWqTHn*PLYK!1@Z?~1v5+`o4wNN?9|8(5kHKQf@q0LQ>e+Am5nNb zZ|ss{9`P?(M@+hgomqk%L7I^NW*|Kzo!Wuti!|q3FJ(YBXsTC`Kb2nf)H?LlCh@V{ z>$J#1!0IhPA}m1umPJ+e{GwP>6MFU20f9}U9f8Ho%48LbR{R?lmbwut*sLLZO0O8i zK!KS7A7mq{Mn|wjs=_?)2JdRZB}pwpVu?+5J1tena&cMwT-$h9 z{oE=V9{{PYme-5b&5cU6yuPv_z$@E}TiYUo602LqrH!rS^7<8#U0j!?oJ=O1DIsE+ zkjwAhE>?+};9ccy@q?jy@TB%dOW{=vdT^Om`$4PI-kTV-d(AzV{}WIWL9gCz9`+6C zyVl-;E3;AI^h@wA8lS=bdPiiG;YwwB4yP=L!sKPdz}fCBkqfd7o{Euk6!?;jT2*!8 zuf#nozA$81C8UnZ^-2idR;sho`Y*D$g#}T3qubnTwu=~tjKv+fs^)k=Q|+{33Mb<< zfu4C%GzXq!LKp56+f)L@o+y%Vc%F*oIm{RKFq#YC3d~ktMt?834C4^6ZutX465*MY2@G zwh=jGAlJqhwLIo!7Lr<}xOEk3Nl%au5sJ-T zYqvx}@gq?E6I#pTaSk%b_o zo88tH{8*LXFkM2ROB~pU@ zvfO`#Y15EtBUN4v6LrTEK3nwyt2Tm@1_4jlxeNjc=`jdotL*lWh{c*FoR&DWwI2M>)26HUA@;;FKbJ$fxd z9n2;R{G!4v7@-1*#i_@~iD5{sjt*y*YHgE6(2!1wTcsF_#rF@eKVYl`SSF;!EHbH} zVew2A9*(-r-CK&|0#DLH$(qekpJl=f!|0Gun9nLOOp>z7x)r6HVwF~hyoSb1Wix{E z9c)umsnBHDF~*UMJ5@)l*izOVvIh-6hV1?1(#r#*eI4m&*vpZg&8`h(gHR8Cze8gL zaPn4E!|8alkJwp;wFn23o#@U&AShAJT=>pFuGuTje^q~G7BRd?q6wMMa-ngQ3pLA+ zHL;NVQPE-Tn1jch9OsZ&`72MU1$J)9a{70kl7+%zyWQ!-cLYI$k7SDuk6|mMxOuf6 z__K0xpnwk9qa$QprGB;|`1_-F-C2MJsc?D74`u)cHQfcIKJO)B zf8RiK1gC(R;Ec~a^ogY)T%I}PKB-zZX%RWHZYkjSKs{;**Rs?sW|Bv*2z_{4DftNRFq+miJyWBynHBU5eJS= zY~cjdZ7&j1MLhoPRv4qd5PA#NaY7ZQWV|=Whs-23XU3{@>6u7UYMNBvsLc^#Go@7X zS;`CHDenf=?d#YJGdoi%{B*3Sej}b3GU4Fx6*EXSj}jAKI?}{kkjlJtg`HX?%pCpc z#gZnH9Q&z73R5uRSDF}7%@5!}6OKE|%Mr!Rqs^5gF<58G@KYIl*7&H1^-xMl>y8CM zKX}w>HZBECv87xM4rvb<7fia<0NeO{6$5@F`76LlgQ(F!<}Tgcz%k8gb#ZHJ@!i!* z`8~zz_PaNW)oP*&J$8JghLc#@s10th8yD|xvp{%Dk?WYZtBF*xKG&bw_03X!<_#3M zPTizT422N9twf~o=z5IeO_6(qGzjrNnLl*I_?7o&yktz36QyIICX&XWA8l-Zwy<8S zc6N7rQQtH}iA8%+_Yw{R@Q=VgBRMNRV0HtuE7;QxoI`n!XbPjro!fx%Nej6283iv z>ehw8p6;4LgXW|(C0o&?v)@w%Z1oDQs35}`>5ji9PhZ$h?#K1Ehs@?}XvU+rp@CQp zXoXeFE%Iik)d3Ga zig#IQ717D@2pV2TE&)Fieim`P9N##!(d6lZEA8I(DhD=vA*=u#kmD6yE6 z-`d6yO;gFK)`TpU?2#R*1Qmwd_J+imDUAwgv6wD}F^pgO;(V{v#o5WW`SeZ}{D@K} zIl$`K(mBKH$R$>1!mqTAaCewCLs-E6BX0}H+j{1wk}vywZaA-CR10bT3T5q|SCrO12<_QSF;AEeoZg2_aG z@wvE&vf0FFlt-kewgzqEPz0uXbM9rZdl-=NO`A92hJ8B7lOp*7?h@n^uU z#yi=u_Njky99?v2+RcEFT$G|#sT8bl>ii_)ko;p}bY0t86&2{ulp=HnMi0nC965GM zV${mi6a+*lDIwtp5N@^jJ1M0OGcu($0h=zh2~fZECcwN>oPf$F%{hvVDAkq{ND6oE z3Udkh_?5BD4-im5ydvL*PdT7};A-jNL3Er44%qR?PjTyC$QA4E0Oz>r|Gc9lLIZ5d zFTTBlTS4XR^2U0A3qjk(wITxl=%jXZ15eH4rjoeIBR$)+L4}%eI;G#!vm?$!>a_i} z%fUhIW)-*TnpM68SLMq;&31Kvr^;EKR>RCeOAx52+M;sH~amYqrJRDq;` zx_VDs>W2GAOM)VK7)TcBQ?o?+FbuK@!@#neGEK#A;ab|>u*PHqWj2R)l~2A*YJFn@LJUHfDy>due{fh;``(y)IenFr)jn@f=eyF? z>o}g;*~4bJ0na%lm7z=28Vv)yhX@deY@};hY&3L{3g^WIDN;pshhtq-u?H_grUmT7 z5`hHb+b?l6#bCcEx9N>ESRUM)p;0)Tq$@1qE-891{!qPU0w)dM1H%(;VD+mIPnz73dSe)q zY9O@%8K*n79s;Eq2_BdOTAiq{5FOm0=16RdTBY2Mf66tA*}n@qHx4p!;A>3`SO{gA z=vrG^4%DO2?cVfkWYa6%2nYX<4g&g-4I3`tz<^vqX|lNs5~+$5DU`uJmSqU1%SWw( zMnrLTaSUo%{Lo5SWza>~c<oD#F4XH0!U$!oovhFRWTg!6(DC2zDqyK1e6She$? zaF%cQT#XLM!mfn!`r>8m^EI_O9bzdL1Yr$7*2U0Nf76l;QJl z!+?XK0Cwx97C-@c{fW}{;Lto3d8OMK92!(ml-Sr8ZaDN+ypwP)QM`!%=-ghODtPx{ z7#)Ufl&DNi@v7^l=4H+0gG2CG9KTq;1%Fwy4(YjNv<*#j_Y&q*Jh)=&PR2Se|CXuf zv~VPEbVVI#w91lkE=)cQp@!Ko492+_E=e`xJ=qkwteK|6meeU_9k@tViRoR)ufd(6 zJwI!-TgJXoQK91gA6}Jc`cR4t84&fltt(K+Z+4?Yga^ZVrM}N6_KXI3x?61>Wp_4= z*0^tH*m_c3n_3@^-lR}sG=x!I66PCe37WkGe)ph_NKKlCd{Rf3O6JqW$9VYa<|=zb zpiNWcA~!{YD{}SO9s!-XAW%|cEV z!&6j@HeO4>$fTfc__c)iMx=0^$#14e&H?lu|8+8_i#MAT`HlWKSw=V-doBy-mInui zi|q!Pn|+LXc=}--xoHl%!UBTY)N9?w_I0=!8kNJSPE5fA4>htx2}4%CgN^Pmu!Z$F z4w%c|E(mNX0YX+4{c->bbaY>A_HFD^KJKY=Q+&xz*>Da(rKomD&4z3DBfNXTP`vLGVD}1cn;32U zQ||a6qzXJT06Ji4tp?gcR0)T;ngLJ01J>w7z3K-*?q03CQ`-YoZ4O0@GpD!>N|%VS zu>qO8*~i(^IIF=6T2vQj3b}H57S1>vfNVG^vNzn4g;@u#8uKoR#K=s+7cO}Ctr1zh zkb^<8(O+Iw`3oolZwdCndF{BSa|aq@6d$`$Acg)ZW%sRduofmT*jOI$=~EGMl;-}3gi_$}0q_{{=pCfJgWds;Sun7QY9KC zGE;VJ_(|$)u}+}V2d4P=0bG3Kq=<3Eg0a|NML@|bOFZ=zCVe1qm<=h+(j};i zG0Vr6_~-51o=dV?K1fj2(lY;>%;F6t*H3?-&Mg&f08S%H_nWRp|M%{UaqWfe`? zpV41cMO9nKG_Xz$ z148D)d=Ms_v_{CyTPJs|Cr?iWJr1c_?THu?*68;TSSa`rf|LFX$Yc`!g;7iZU z!a0}GFd)syl~`3ThSL}==$ZPy*h)h*Nm?*WsW36rY49Y&l}yXba8f|gMOY57X_VBF zWw=OiSclFGb`OJAH;4-byL4N&2a^mtg~8DQosq#(f{Sd|_JVg+f-6hG=HeE@S_TyA zk>ejPZLDpUSCOKBY;2eCS$uT6xV65x8kCn;i*ci2sET{I*bC_1avD4}x7c`m(CaTA z5D6Q*Md_tn6s~>5183v3cr(Za=U|`Kns5^lpW(t3F`jwh(yQRbxQG-OIV{jiN@)%Q zb?V@tyfmob9NI+$b9tTDOyS|9vYq0zk}2b4ar;LMT60&;2&xBuk#{SpbPfJ-%7oP*yVdz z{)=x4-c-2}MNshvu&nwj9USUL^ax9>MIbmHt8zd(OiGTwr0VLaJjj|sg19ROze7xw zOtKTuk2scym>4pgR%3(bS<+IBSye-Y5kUh>P^!;Nt>7^?^i8`n=*iKjawWBrew9j? zaMHhp=bb?EqFM=G5erlodkm?xjZiWsTm^xE>4hj7ni7pH1}Dz>$^gg3kK6AepWcE7 zJc`DZG0X>kH0NGl(ZxtUaCM}E)FOL{5o3*Juz61gDZ*qj;#!N~4KWJ24eZId?MaiX z3r~%OS@8@^#FWYKSz@YSw+_OG&Lp!QZsL3|)Nqhq*orwK5Xw@L^i-_D?ewgShNP2O znBtm~SfzNk&4F?X-8}Nu-5FB zH;kqfk1Ng~jc&4dumu9ggNWeszyk>3^S}dyh~t4w{1ig*AT9`^@VsRr&WCOm zCy<7e!DFt<1MF=a!n4TWeo`WJ6NmFMwP*%6!zu1HHOF8Qx4uUx$=k4#T$(jE9yXzX zaZ-z~cjS*PsJ?n6m14TI;dnsfs0Jg7kWh^G24*ocA(JwC2aby^!;ejdiTRybl4&mD zwHTUl6*tuP2qmF_XjhuiRR#wKweBs+5cw7Kn>hC`#Ri^B({q6ZCS`0c$nL@N-nV~ZX$Wtztcoy%dhjV=iHIq-Jz8a{MYAfLOHATuB)xu0 za+}^w8Ktsn3)$SN^&(g!q;e3boLo=`u)bl2x#^jhmLpFIVDhFDCO(g&WiFm9=j2Ti z3>Yz_=j0KM0=ajR^CjTC>2B!)X6r?9I^+=?4pAlFh`CYlp%9 zHU@lSV}PV>b-bk^-UKGIZ+~&KT*1Slcma(DWuF628=K3CmSCgVN50EKevL_|=~;*#4G-zAXx-8y zT}+$h_GP*rWc19z5ueZ*p%9P1oE11N4(GM}YVoC+QVF$AbjlTQj#TFPg<=_Zsw;}|Jp))gmJZ(R~!34RQrcsZjvYX8@z8Fxk z+rc=6{%4FC>YOJ5s6w%1jMsX+c2`vrECUBONLTJw)yg*ec|HaN1v(hj-y}wA<;jgQ7@$g}+7uEAHY@ za|Tq9THdK_DikZtRQR~QA%G6z0?bV&np_)nxYgeRYE}Y*LjWdIZFU#t1VLU5F4bNj zhhpwOnCp&bHJU1;Z?s=m$&OB-C=5HZ;bP|kD1$SC_ zNNiv92xhTe^uIA}NgNcrh>@vQ$WOf4(63*&XKl}^#CiR8EEa5B#Hd2$T?*8%V4v<* zi+Bx~N>||iRd35_Ong$vvKEYb!ArJF(_XAMRJ zcf@5(hkZP$+!M#FgZ&aNLq%N*%YGAAY{XGq`30xkpxfp`@|ZdQPUgxKayrVNIGMg( z>+X@il@K>E44ZXa9!46Ddf@1A)J3pQQX^e>6#1sFI9_~20dE1KPWEHm5%-37opmTL zUy)-jy(@W1P0BaRklNo3G0A8sQ$te7S!|^U z#hwkN)J-;&I_{Yb_4u$FX`5#qrU05Ne+?^vXfqT$r6FR+h;sUKXkoS-$XQSkFHmu{ z>^%?(gn$)T8YBJvo6ZHYYt_m!6)GfGFq?JI6IjF=Uqf3&!A4AlB?QMzF(t>VF6l;+ ztM{?eqg^1(idd@O2SUx}0me$7yFTt9XWG(`o{2~b%7`sd@}-LvNZqN1 z&}NpwHn}}!m_X<#`Sh}fCEl4j6T1{HO$=5k7>a3@MWPRyo3I_&gme+{u*Md;jVr#4 zz=Iw633kx=(KsFs{Yrp{*IwK3p2Jv=VKMLPlw=t?1+pCN4EEvz`ZEblrw!<>$yV)_ z0UswMOK_AOKD-f!#t|b?T!e^I6J^=YB%rXoLXc9i;ck{T(-Y-Ypsof=2s9$*5UDZU zvm9~iG8vP~fD-tvqy%bawZN$(oPsrG3Y9S{f(SW}>pB2=5Akc#Jtkv3A`GbXqx=St z|1`e=0G+1PwYQe!DSh9Wegk2$fN&eTPm@5wVS(Uz?@D!;-g|LNV!Rsl2^X?x1kYsI z;7J{r4WH-P6oVQ%q`^Cy%B!k8MhFBMb$j#{RJ+gbec7!b1tOn567n+yKIi)>24!b` zLd8T8?|4afRJ`LwySO8^d9;UA3_559rQW8>-SHzmr(#r==S39*Jo{ONY#|uwT@|Cw z98aql(8&R6++E431AIF{VnFjQn%p{PvppWp^?Yxu=mMF~t0*XbVMW@o1+#Km4H&H+ z>9v#?xtb!9k8}*jtyC*(r8Cf`bT_7(vs6Fy<&@zq0187kGKm0a=0hn)Wu~|e*}mh*#kVYWd5g93~r6{dWxJ%vWW6)gRJK|4BC{0Lqc;Z4nv%je-r+e zC_Q?qGQy2ou{lrg_=v`x9Shm=HjZ!-%RI5ONT)aB4+jn#6FmgB1Bm$HWY1tn5vOxu zo$@JK={^-7`J*O-C9pC)k-%di`x@U$HEW*$PWx`9V_^3BA7<-vZzhLE@+p z{TyC`w*y2i{8LSba+eEtWd?11rGWNxtZx^3w%EqWfI*~7*q%Jg`fx#q|kf@7SR&UCQ`|%=qAP$$g&iPOl;5Lq!R_^K?g4m`W?mK zxMFmdi%qcCO?BEkH3{*GVG_IR@s4>moI!d5#~G`X2SqZ7)7L5NZkWPND>^2hQ8I4U zP*9ip{K#bkY~uLkzH7Z`iLOfF(QEjy?Yky8Y&sX`uS7L$kx9iAC#zyXW|Az7L#Q~! z*gL@C0i0Xh7bo2je{Fv?+N;%X@qP*pv%o8}OebtMu=TM^+bB3(hr=c!#-ou)0T$du zv5B#gkv~7yhZUX2wk^Xr^rI$H=b%2zj2%zVh(MCYxdYhs2~u- z{w)YJ9dLkoZDnqE2n$_&aWW9$jjj=@V%VQ*Jv_fz>-JC?eQeeUACCXg2P}VET`pZm zP;RX}7wZ&ON`GQ|iYO`d59mw^-M=Zf)tNEjUA8jKMqkFsQ8{vzTLR~@X*ZCgiZiFm z?Ks#Es^ME=#0)-NzufHhn>_3(cqIqii0GLtgx%1onsdg^m;<8rY#1~p&s$oEh@u_m zRaMbSt|Tosi@L&OGi)QI<7_ZNG;<{ot-WR6Zape?JV3ijMF z5nYn@>rggE!DhqU8LF{M92G31Ay~^oa&ba*L7!D!DSyNzxHa|8FGi0;5 zd9}_b0-Zdkc!3TpFG0xrk&e`?8bfG~fTr0z5SaX6E=ICeVby7L;!3%J6n3vTrkW1r z;^d12IN{kvluiN!VqzDyVX7(%joyY zb-GkmFfWxM1^P|j6>q}EW*l$*c=>SGE00~>ILGdsv6vt$x+3n$7=ei-pN*wNJC9is6f)&zI1B$<()3M?%^e^eKQ8zd(ZJheB#5BN5TlyY%=( zZ$IFm5oGkK3tAo3=f?Fu^s2n_r#bPSbwO7+t233XV7axR6G?K4^YSw)Zb66+R8T`7_XAT!$CBT1T7= zoIO&s$}bCpV2V|1-1vjdt4A@F^38R0v8PZt*@!gLHtPonM65p32<2e>)Sc*eeu99M zuOIsyrs#gRbE~*n2V(viRF@B(Zm8m9s*^OVXWlY_8|%@fxRK)39!MOB5q;~sNXk<6 zmI(@$t1wg-N#;ORb9a{x5yve#i^LJ*Mc>hdR^5SBilT-NH50jsboDiZ&|R7hA%vTF z#7GM+D@s|K)qxx!(>6qTvtA4*by|mnG5#Vd8@w{9wI1YZOhPoARTtgcMVzj;OfVbK zWB7nv?=;(u2f2NGi`OJ6&zQ9&kcKTup%$lnouI@JGYt@oSbA!%2Wz|zeb(k+cUT`H z5I1}`nS>OA%Y6%UT+IJg>MdF!3$Ju zbX2Q|s87oGfLGeM6V5>gVvTE>S&2D^)SR?6I4|31BkhP)wy8$tm{x`ZnG-H8RrJk) zVFBF@f+pWGp@vIUjAhUPQt>aM&oaA+FoX!jAD%$*w}E>k{7q?O#^G=4CjKEK3h&?G z-y5B716MD+O^QXJQ1C<0!Jp)Mz_%Q5t-KkgzPQ?)EUxaLicm3O^$)4dzDLl`Xc)qs9s zu@vI}g`iFEX_}f$Js}6<9PeJii6-~w`KQCAu>>YT(aMc9?DI|Y+Xr*_;IHCr|Uv+=+BuD%ytzO;)h=8!%>S@mNav^ zI9^~T$mJFpDC%JCsGT_76|~czGtoX**Tl@o+fZ)(q(QTFhDqKQ&`p9Q6wUeBm$@d)xEdEO2V zpjHk!4Asayo<+c9xb2F-A%2~ytLJC|hE1_z1x=B^$3t{*K&Z|lxtbP6fp(3B1Y0rV zAvl1q_B>FWtsT?YW^Yih9KiNI<2)d62%p`^@+As`1!wGtxcr&AVWt~1fPapI<%}$l zG@P9W27)t@A5IYys=WBZo=z+dI_X@{o{>E+b!X?357XINR$zv;aHG`bmrOYiq-W)p zP1+dDN+LR2v*rxpYU3?skAR8fb3=bt)_Eu$gMTU5&eqD=Sl|*oWT6{}g-PURZ(*txAF{l?-{+JoMDH)w>p}GXbkqgh zE&@o4Ent7`+TH*wc%n_GQ!YgSm|kN%;n7xE1{@uWh4Dun5YX=oP-!PJXgYP0i?Am% z$eSZUj4;NVf&4{rhUDH+S_g%Ney1ur6di)1=4U$HVF);dy;!GG>MN^I^nMLiY&Oxo z`ZK-M6g3H}w9YR4Tf8S~z$VVLBwZ$Oqu5?n=|d4$+oa%}70-seAvY$PO5f{kJBNna z0)5tIno@Tr9NP1w-746^z!^(+v#>AC@uiGci-nwa|9RV7RxwUrCB0r}A~Z%b4l#xY z%kfd+WPszeinrY?-Uug_h~cdk5NB#pIxWVQi&eGRErNh?c%fWs#)|Sx?Km$yv5#|X ziln1+Ts(%)a9mW{Z#XU@kN5CQy*BIfB%TRVidXS$xUj8@u9aUWiOqx} z3<2@$+z^h7Xb$wyy%ab$<*#uuhEu)kIIFr}g>|vZZ?9V4@*HdVys0*z(1uzxJHy7(Hq^%l}|=wyZOTzc6+ zc5V$lhkll1@i`r1X1|rxE*FrL4CymSJ5SMzXDSWrxYKcx6zaiq{uu+FQm+g)nGA4)-YBRpbB&s%LptKI47Ap zwlJY4-4s=m)f|~PKGV`_61P8PHS!{>xXzdnKp}BC{%kjLL#V=dbh_;q!}#17kXF~2 znhh6asR=Ie=SFrC|9AvLN8;{xhX)P)7+Zu9`>cz*^%SJF!Gm3Yjf)zj(sgt?nn9Kl zf1D@I^TIX0Pm^SmBE;?7g8!fXLu+NixI|KHI*E!cn|Pmr>R~g_mp^W`A(S-l>d<*D zB^hSI*cE_h92!a-hnL2WH2jk}cdqoSe@mma58!c8M#i#m{8DqCEwYGFF-`!TG*LxoFRA6i7a3Ie|H5>+(TdhP zeMAMXbL8b^1T<|SVqLKjq-9Y{OdKI%4vUD&CL&DD-gLLLdefaABJK3>)Tu!Xo^oCi zPr>?f9ZXZ9e(4-Bl@aESo&mM6(F55XL}QN1Z9hah#>+U3mW|O5;b1IG726c*TCl5v zr{~*y6qKD}U#8@^7^Y>kY#)lWEC&a_!@RXvUgerGUgq@&#l=-0f&Q^s+*;Y#T3cLS zDpt3OmCcRy3f}NE5*OFYYm3|Ejdd%vyu50It!^wXJG2xQ%58+|zzK>{R6FFT;piKF zv=)(k_Q03Sd>7mF7Q%v}_r*J|wU$N-L}^(Lj;TVqr;Dk|8!k~pKpdO}if;U_CZae~ zS0gaHdTxxA)qO! z3EovH(np1U6Ocn&VG=D}K`@XO$G}%zMX$Nw&Lx5@5hoJ)L7bwaN!yB&<9Kguta-5R zFis~gP~R!|3e$))y$)ZWmR1D_={eXuIym6BXVQQIZ&8;QbK;p3FRZTS0Aq_x4lk60 zacY*{p+U%dOgOF9EjcLVLl(Lvn11qrIk>0kf%!#x$(`ixN`%0xJgKeVS)~fc2mw<>3)L0&jp=BK7rkI-8ScGC=LJyTbtV-$Umk#7^pFY6FA+K5LROuG05 zvcjYaZLhNM3VSEX$|Q<_UVCZNOChSH)9?JuCzUJXMrW;EAFpy3iCYug zD<$0~EXia=g;0ZF66y@P^=Q3zK$f^SJy8SGsUOCX#q_tqRW_pdjcSf%ZZaq&Br%86 z8@pD!wG%yvcm$V%>$RQ^yDJzw!@1>VaiQG9g6F!lo7Hbcxdwyay=%Y`QpJx1z`}NC z>3US($D2Y&f&QHUn_(b;@ZUssVY^e@Y@&Q3XPzcxNrL*B09v3NZW&IsH3R*X07P63 zILz?Mp1Mi*5Z|ODKI-i$%1!oPD@`AI@r^T%7 zAs-#d2VG^1nH0K{@FTw9tmiKwHTh^7;gQ)h;rBc;J5@+d%kAq#dlYn zX7h4%$$df(o}_E-dTp?G9S;f8bCK-t*=d65;bd$pgmdw4BH%+`NE0Xd@)h63B%d^44Igq;%~_ktHj(8{S8*oTc&Xnbo&zp zjdp6US8Pw=g*LWT^%HMw5R#P_KN={$%5dJ-@S+=DbEF_H^hOK4^Cv7w0>QJ9Y$9IU zT2;yP9vI$SgyQGs_7>|jsa5cZAvF6fF}dN1unmN*;o#eNhO*D{=ZHz6@Ng5RhI$xO z8KW495D9pUv4rfl>CHG{q%trr5Cr~GyyW!22i2p)e)o+j*n-<>8A6q&k`XRgWJo83 zr9k5KlTEUKb(t~E_=MA~M;dGi5$Ss6hGNGiB3JWjNcvE1c6iDKDJ3LB(sFO7WhjQE z3@77c!+k*AJcqXdmk?H$b_Zf05ge>6BD)v+f`4(gXsyveUd263@9Vr} zf);ccNMlfXAuh(L2W*@)5~(2tp%)?Dr>lX%MM6wA`I(u(nAzmW*Q{X8k*#o+yXFx* zWh~`H4zakYBHflL1KvS6SMHVDcp@1}PyTWM_+4*y2rk0s*{t^-!K;MW)q);(Q=O7i z3(MH3qBkm`kanAUcu|xl3PdY}f8E;E63UVw--FjIp=0p&6d;R1P6R=sC=}d&^N=1l zY%n&Lv^lmphZ05`fbc8~g9~m;i^Qo$$j~I;=A$KmglgZwR)kvVO|Y={@KOTrk$#E*0n%#;H z@g9!Sza$r8E0*_N@W5pKISDuD;6OD1(P#%sR<||yx zEPh>S!C?L#-l^fVQz%DMcoSiz2^+Eb0WnL|#B;V#Val-|&eAldmR!7lafFF_cteuI zpZa%`$r{ofN{%5&xfFsSIOs^sD(PiC3^5O3AV+kY*KoFy>53zE*b+ zEu0pEcN_0#&^Zw>XdO#y!~UU!>eLjpNrd|w^iFh{9)bnySDI0)VQeoF`suYM)&zaL zSNk)A2<|LnJIEv@Xk&qa?dkzS+w$)oPkO}NH0pKmQ7KVra55?z!r(^yqfLA{<# zAWRJ81Vp;~O46j%AaOBKy5VzN$%08Siq%vCQ4)AWmzCy&kIXde_KcD;XO4)O2VX2A z)RDga5gnY>KLR47e*{2E|Ah zD1sBN*4V%+Mc|+1Sy+kJ{$=M>*my<1Q zXb+67Srk3l?sv`N^zjiR@(+?B8h10@T7#Id3~Ui46`EQi;TYs8!hzhPA9 zF~Ad<<@v;}z9lniB6Fuev7oQlv6Sj`)o8Sbkvk`bv&zA(=21+LuqsfWZ;qtoDd{E0 zXzq4e;_#7Er!n4K^p^rRMYbYINm4|Vy_o0BOU$v#G?s1al|?oJ7Akliq1LCRX0Zrg zE>1WaPSwlNbsT$z|B^DMD@_RT?k-#w?AJG1rIB0;^iSE2xPm18F-?Tu$NB`4l<^YJ zJM_6*Lo2cF{vte=h_)TCEr-=NMQ&H8wmdzH6EGt&J9{-hjLOs{{g8sf86!L&IeIfW z#*MizuUZg;JlAxb7~py9Fvv=3=&)eAQf)Cj;8Q@#%_rg zEs=B8uH$SIAXHgwZM#FcK``m^HtwL!`vB>v=1?P@ z0igRZJwAMjk(WqIFHfgQ$)P0nO!#afOV5a=1HD>Ib9I6tHu_XL=sf9a)ZWAKi6(8V zh~KH;;jC({Hpl3WiC}tz8Dsw5S^QbOUXU&z{*WnK|ontt`fN?0((}fXAqtoy7ai&Fy9>!oI zEwy}s4l-+S{5XO=-PNcttfc4(aj>#;0=ux;*%#x)FJo110;S^Ot2MN^IqWaC zardJhVZQIm4N*5a6$@XaDK#6gFm&4m4ks}k1Fp3Qmr0C(E{Hj4>E&TK(S;Ygw3U)x zHZ0X(wMdO?u~Q%24h)b~L@Dc*pl zB}Y_hYF1XGPn#beE6>Y2cS9;?xx{Sav--Ui=2#B-%8j%v@*&8zJn|LHxlHmEJ?nDG zi|ZVgO+LJ%EuXv?axbI2rAJv#`4Hq;R{6?}yu9)v8D*K}Ly%*+TVfjmOD{ZWD%TJS*xItD*^-a9VUa_} zg#pf66>z5(alvC9YpybFYgaC(yH~}|MmQ&$-0A9NEXo1D>wKjocWF{ttyw~CLhvWw$pQ0wj) z`@)kxl;%dY|CUu@XgT5e)-ISF1&GAhXEVIOY^l?Nl{!k1kgmbN!!_u(MfZFbY#O4A`?BsrN&M0~3`(>W*U4jzk4tYdz9<1BMakKhx z(oq$n-$-z_Jv{V~p`n3HoNzA5qQU-Rw_Ce~ws4d>q#_K8nYN4VR(QItwEgIo4TSqI z11iVX2je2Q6t2Wz+N01>agyjP*GZQg=J_?TbM7vC55Ql27{Yb!cdMA5@wCF=vJ%hl znR)7L^QQ{rFpD+CJXP&clc&pM4wfR171(V)hO0z0n6jcoEdD;&Z`k4-6dPcwFzqvtfvp=w2j zQkrmD74_} zWd>rK(lnrD%0c0gIzPCV3((I}R8)?tjqlP~qT+}Nbt(ZTkfw-iIL~Jx zd)Lt8beUTY`($EDc@8!!7JpWp707C8Xgwv3`pPR7gi=2BeoJMJ<aoboy~q=Qxr8#k=`r0Y4G!m7Q>hz*Do9E)F{M23p(UZkS+`_*3KpDt z>y-}<1}scawtad!!%a#nOZ)YS!ilt$(rGSrM^9_-(R@>0sKmJj4%ThECNdrR4$e#; z{qVb=$%7S6$W_+^1~YzoyTcO%4+Xxq59O16RWzu}+q!|$C`!Ww_VrO2u*6Lild^Nw zRI^iaF&MO)a4J+01cv)?Afwka7x>%0)c zA02h!tUX}y;m3Dueo>qjJD(aVPQ2@8VR|1#AwunK4ccv(MmmFbX+5cuSISG8>3l^u z<-Pr!b|sm{vpe{-nMKS`UYmBVFE5EV0eE>0gH#hfs}C6!5|`7$|zKV6cN(Y zOmfQ1ARxNhkvBLxjo9$<9S+UsNf@6>Ijd_&DzmVF%=H0cuy;3hiy{F zGvA>rq%f`~7EF6iic_M%ktr#jV()Sj!9v=5;`Fbm7}s3f45xfZ>jk?;OKz-=G~paP zQ*=shv4st6tUEe9r_sFzvxI0%HjImvefAdCa@)p<$P8$Kjn#&6aZX~Hl@T!=Yx-;e z7vD4mQA>$o&X{;!91i5*o#tDc-EOBVqYdIRZ)!dE=!=gS5pQ^dD+dmzevY!SxPwqV zA}U<*CI%EoTB2D8LZYYISYY_rwYb0ODH!;$DI*|JJLHMSQ8LhwSj?yqh`m#Er!z{( zTui1qbxh4k7+ZQga+?c|u+!8OD_uom<`IY(DE-_+4C6oS5a)YOIKY z5s4$WA|?Z7YZup>a3=ifgaY>#ulEoES~)CYX(kz0Gb>Cq z4dPzJa$WN7Y(J+^7l)eIF{sD1R`SIZ&u@3cv||r_n_vOq(koK6x85apR^lB_t%l4& ztZ-Xp5i20{DB@NUVhVxNYz;4O!r55BD>*A>bgqD~3qmYt$%%c%EW#y-%VwFJ%IDa5 zHe4(e6}}ahD;C$9?fz6Di(moa(koIg1u|EnofV(b4p8QgOpO=2GN0H76)3Zv1*rkU zCcI;O%0eDxnUGLHlXv|YAGA~LQT!2}Oh`a_MX`F)FzHHJgZOo_&i1NgotxBtK8>6K zKB7W4xMIy!Lu<&Tj?aKSsf_1%)Mbk>2E?%Ny%8W%cNRhjvOHXV9InT^?DiR>`^ zxg>UE+(~&gj0eju)*|Rk*x5jGqRR%7(^&?PF?D4?>7kYZgP?*P-oNH;hOBudhO(O; z7NiBljIg~Ffti(AEOqW?cgcf0I7Fi7TKN#hj{QW48c$rHyi<%H261!1z1XGcX6ko9 z+zfsJ1aB9}b%3hIeE!4DvtIp37S(TkxaHdFfe)1-%%xD+Zi3IL3^Ra)3VpEA8DO*3 zWnUwUeT`K1p;$Wm8pRa$HHyqWyeDC?uTe~AA1b278uJ;~VUk5t*w-kgu&)4ZK-S(6 z{+Upcf%L5X1pVXk@MabdZ>I7P#nO3rGmVEg1rKjJJiM8~LsVq)Fj+K(hd0xB7z!I; z2n!7$$-w~*5tH|5qDim**h27l784&&Wg?2DGx6~>CO$5h_;`YbbU{Q#CKHoIQ<(U8 z8WSgZS{lN`7)F!IC1#87AJkgCR81|;g!6@c0cjV<1$Z1WsP_|C-KQ)_AmH{R2QC8$c-l!miEGicWF`T^}Z z(_T6~{NyG%MM9asK4{S!M#h&7SST1-8+iL7Q3GKxGVJ2vlq@do09}*#c7SJAfXi-% zlj0P>(|%MyHX{CTzzQNq(_nrQD6R2?4U!C!Ds62X@X-5Gsj!B-LUmtU9M8EWt1=Fy zkRS+g(;H}cDgp*)tKY6BoL}ljh%;qgJ{T%=>IiufcM{nc)eWV64tpt(=ZzZ_DuSiBxTr4!PGf_%glV3zcGDq*#5 zNPZSR2bLe-Q}pWq!9!Fu(W>Pel_kr|sguI6Cosz|-}6@_=KVOByIhx~)gsJN9RW>hvjW{qHAZxN zzH6vBE44(sh+Yhin3rm!$Rwcc^0VSJ-B7Y(u@(hvEK^xjI0I`~jSe_J1+Oj&4JA`? z4;x-M`^Zj7A?aBF+nD?fT=W_nKGfkc$W~+G=g-Q3S z3J;xj$K{HD;8D8g&*#c=dO!pZ3$OZE=w5%kTjIhdgBApjiYC4%?!2wIBu`@0$aDQe zDMckJ^fiTEl3#XbW(3ZTH^r2>V<1#X@ff#^xDbyC&>18}0U8%OFFmqhV1^lBlys@( z3DOtlJCj;cjQ-}+!>DRfr8{ovic#PY))qsGX*qW1+P6O}1whT`>^!bx3FvVh+bqsc zI*HcY)d-KUw_4&ICA!N&UPyQ>s!W$`keH|4M5`n9#3@xqTwtqE>4uuoVnE*pN4rENU!v)6$cEoxld}-b0>m^%a=oAt9TZHBlXNUBsLlGTl z)_FrUO{@jXVm8Xc{7SQp2erjoy&MO*!|Pvo$r`PSHH7~>Y*u-@u5dvtTe$_QL+vUI zB_v-8v49a4aD zoBl&}7Le0mas%0XEVnKA9NE@#LrJENRb_W5W0DLTqnu4|m=~+FekhQY zg$r6O8t3{>{YW$=O52nb3bF>CYID@_I5m`zIt3iG^Cscy&>a-pXg(rU7dPLjI&-I)iQO~JI6g4p|VzO24 z*tHgBAYm*Qt9T@SaLA*dE-WG#%MrnyX1j(267&iWNKye7hys9@;HuTKe+=Qoq@9@MI{T$qL0=G%GHA@@Ay@@>_ z*DIeW?V$Ia%a<-QTD?T{3N;S;Q+S}_<_=aGW{Qm~d7x!jzSR)T6trSWybMRuUc}v3 zFzLX?m3Hh%lAeCQZ?^?rPwX^*~7saF^rq*k1yIHY1!=w`q zYZyJ7Ve64|!N_g9El8*Nl1RNOFvp3AX3=hNEDG@>ZchvoPQsFww;wR$#veXlmaZZn zgivQYL)|Ob%vO}Rgy5$9ek5P=Q9ph7aZz&@MBrav?##7zm-G3r4?@Sc&>a^y6nPt1 zwEK#M1@qBe3Q$b4oP3E_tocpY!2IB7!4Mbqwlr}=?`C??N!f}?Op7m+vn)HqYF$j= z`jQ}zqGUsSHK#Z)@?+p#6x@Zx+uxhDp7F#kg=BzvQKT>|dT7NXn+Kt~Q!F0+9yVkZ zG~IAUS9>&1yfbu8x@TmBJVJ9fBo@nhtK!Nyv3(B$*;RH^)lZI=U(+2ax-fQ_WH-i;a}nSL1r$}fp^01}zJ zZqz%3@J509fwjRd$uqSR0fWT-bn3)#`fAk0t=dj+iCHpTZqtJ^=t=Dio-|b^We1DP z%NrEF{YtsAUEHd!Tw7n-E+b`e>q@1%{q9Y^XYXRRBWZ4ivx$D7Il(P8!<`5vD>~Cd zaX5_&%-wZ#2A1r+gW?ch;YdE1)}Sa!)2Hq&Pa5YyY@ES5!qs0XZc}Twird$=)fNKokgcn(u~uVw}=s`EoTusR$Ib0MKRXDF;NW7>RRTA@#U4J{PT7>++`JEou!8aXSU4jida^QPE< z%gu{~Dj(jggfmZ!{hLO2(RCO_Vt$hQ_4LbWflHA6{eB)rAmM|mZRE2`uwkhPR zAq?yBqM(Q~7{Yd{uxZGqrnC};xk4t6l_2doHqvBaniuLAQhtISix zYi?PzkT|;)X>-em@vazJ-ink`KTmDyt7vwc*?!)}ql?v+B+;dJb>{H2b@Vwx4+lZ8 zuMy60XdWEmK!kiDmLv0UT)H?-P9LSHb|~Bk+cm`9R0l=P5~AlNJnSME_VNQ;ER|b$ zT>3!9zo|4ofJNR`bl9rZF&iD#TFu6_{_cEm*u+DSH=4bOBBaU{k|zyIIIyeIpQ={F z)o{TBf#u9Wr!i-JZGN96~ z3Mh!vS~%?kUVZ>^kRQQ`m}ujW_T_rP`bKqQla_mxpj2MpuC6Vvi?d_JO11dtW^rk| zxJ*Fn*YM027EEj9^+f{5+g`;=aqHn?bz{9)z5MR&B7+25#m&{lr6RU-9$s86FITT^ zugnM69Du-(K)KX14yF~?m+ALPg~2wq zuF_vD->`1Qk+qc#`MJKhR#cx`i|fl9Ym|YCcyWh@Jxbq-juIenI1VX`m3OZ%(T}D7 zkG(emjH{~m$M1yhWwlT$q!3mKEhUqtNm^>5v?)zn+R!9r5jswiNjo&jgqcawqAZFC z>Qiw;L}e2M;eqQzPyunl74^NR@_T=`r#=*YZakN#@9FdZ`JQvW=bn4dotZl`chaO# z$lPl0m_7$PH`;h>qW zwcBOX_HFArx&`CdU)Ql#u++1zi@6%?|Kp4-Fe>DwSwM;PRXF8>q?PG zj3g#9Sxg}$62s|{L_bZyCQ!J$Mrgvpq3R;X92jP26XGYAcgL{tCKsX=woI2Ii=GX2 z9?V2J@1m!6-CQE!YWJP0oIkVdVwh8&EKv&+{qnR=E z>Z6&dob^W|Uzin01H9}tNHcFatB^)M>9F)?L?tSWT|teN$UskH=a5yp*}Jn-RA@6w ztWfx?b4UsXPg>HzofNdtq9N1-o@f)y_yU_O*3wpfIC7q#pl!D1E1Y|=xzoVA4&^wO zciJ&#G4GXdt$?Bx%|MY zRp`&IS`{{dN3s`YvU^h5hSM9@(0}M9Faqj2B=_~Du#AD;Whya<4JwJTkz{tC28o)u z4|_C1VZ}~dFv)V2Vme4M5$GZiZCHWr%mt*f0mHK%kk`kbAA*_i#ye|s`$qbuU8%FC z&6sQoCpqWx&e%A0QTJdp#-SXAkem<~#$~bF0qbuA&QK;ZN-6Y|&?1y`lBfYNOgZk# z;X)MJOpp-gL~|Oj0qe+E4tV-AW9a(k^1wplHiu?PQzHY3!2#?l5J$YKyc5ZM|86Y& zNlfZZFqcSYBnK48IsJXa7ljcTO^u7SJoNz9tfV+0A0ryk$RIlA6IbB>1Wr=N?YuxD z0>C|*-;E8C1NuFY7)WL((1o`WGNVZ_XvZgT+y@F>CKHV$6$jA}0m;7%3YnDJgwFei zGBkP?VwquvAuKA4yv|6978j9+Zqtw`WnLYYDpcxq0E+uF`cabodk9r_fHj$ zP4UUC6BHlX97eMle1nuT-czH=tZObPV$hb-H5hWD-hTm8KGV0>zzA z<65W0ZcKGJ7;`~6Ls;3Bk-`EnuBMY%l0%8n^k@nh)SH2umvlV)O{A- zpdX3Z3=YU0Ng;&UJN%N}ISFv0eFVaC0u}*Trzj>hOibbd6T@$Ebaw^@kavc0iDhCG zC-5SyNtcMEsTLD_B#B$3QI>hqh%5wDYI10@TsW8*kfiCtut!S^&Wz!19zTlZ25}D{`yjQwL)BH( zOxQk7pHdDGJ2kHMW&GF|{ugH$!TN?q|-47`X>qTqD-MP|1T-(a>q14kNUWqFq z?H*1YNVsYlyEgZif!Lbc@e0V(J7F!rV?xV~{VBv!3t6OT6iQZIImGD%8&r>3ZJ*P_ zqqz6N2#ib^k_$)UQBxpt|6L&je&U{a6EZW6E*{6Ih>01?jT*o^hvKcK;`@Ta7FnpM zf{*||oz`SQds{&c6xVN&2B2=fDF$9DXalLXHp7br zGA6JpcZ5btxG^V{%?{^wC6xEMPz=1-#^Q0|XJjPydm@o{7{D^j*Wetjv^3w7ai{q@ zP+xt9YE}_Hcv!4HlxQ5}JaUITj>Bpk*zI`4vzetE&Pv&!S4C}9cQ7RNN=)+%-dJsE zC9_*BxT1weVr(ih3baig@=u>dsZgN4amW;=<1_mJrb2;W@mAR%*tVHle`N4S1?OBT z!Nk=CR%TCZaDH*Cg>iQRSs6{{n0FyiPT^*}8gDjXND&5_Kw|#N>_NvBn#L0tL#eKN zmeni8%sN?fLxEv;U0hZ{qr?JIm*Ywt_zaKlAyueV z#de-+=-e>AwHrs&=tmdUjrbo4?I#;pw28IU>qTz}ce&t6OF8z;Odl5S?5P>=$ed<* zkhyPcFyV;BAZP{S;cRkOYISqV(uQ~|lChD+Nvx%%B7g!A@JVbel@B#}5`=afH$t7v zz`VX1Z*nJ;T4f@X(d8GrqeB)pK76~{MX_0~(T2v+M#BpE@u3O{Q>+w=_zn+cRBnE3 z`&E^={LJxol^e5eXqYnn*wBo+Vn>o>Wip1&HE+);SF^2hw+gyW-T9R?Q;?uNua1m$ z+=zrQ0^?mw<;We>f?+qaEO3;!0S&)l;%}ib7o?BRFvqbq*uYfmHtxsqr)wB?e-lh{#fC5rT%zuniq<*ZfLI0RrnsoU7R( zhR)ZLn@D1Zqavm3wFIsH@jh)WRAi;VhdR^}YdG}&f(`G53r=L)epEVWINZvnsf#-W z46RG(1Z|TviT2XA9}1i4lSMTyT$jqj*VQdqEan8mVGQlBL!m3+!ArR7P^g6iZ;hy6 z3b=IXYpX0ItERA7n%1`!U#kW81z?0e=T~-qX~a@jwqGks8ddO67#F(Ov_Twu#axrc|R^u@wgQ4t-u-Oa}*! zeqfaNC#`91*$%!G-pbqH(3rcrCEI1R#wBrA+Afzu97zjZiil{dJ#{G(6N#qPF2%gR z^5n;Gz47YPhLXd51IdPDzG2z2GjrMgGxw;kA;iK}D!Xj=s^;cZ%_|xkPCZr3GoZ%7 znCZ^K9t>avmIStp53P3VnU0o6My_sJv$UaXLJ~7p6bDx~m6?5M!yvA7zzr?=-Dz<` znzG<#W{j|QZW(Us*k;exxRXR3y+gjrPW!5;QYW_bHF4D@dr)d1v~D97kC>d-nb$_7 z<-0KL$AfdxVT@P^CeVp7^G2HVat$a*b7WX_2uFN{hLkqdxrvGo|2CCfgg6v{ijd3C zsu#>E?W?Z%!=1l)Jfpe4BTkbF+!(nbwcs!{xr^B8yM?P4XmZpG-)#; z?w!euIHJ(p@>(I@JIgN$Rhv{%pqx?6Sc4abHVmX`D_nADwW!PH9rS`)nV!qcFK8IO zO-WQX)L2r-WF>frSUP-Yp@q}k-0JnlB?>2`W)?HqGBhKUpe9OIY6P7XI>nAQd627#F9TMW^ug;pATIQ@K)2 zs7A(j8+X%)XT!40CZ1>iXp1U^%P>2$GHRjflVRGzqi{c9R#d#gdEmf~d=eifc!#b7#{ z^L4lx#Elm_{i>f9*6Qb4yjSN{*nAxC; zTD9<$v1JNpOsVYv7~RNg=9Ky)XkSZn!kreQ4>u{wFLUmxHsw%q9jP{C%bmNb4Hy2o zt;B})Se8H6sD(xwg<2GaS%m5DZSJNHAFpamCJ!M7H8t0RZ}f9+q0vvx87VbPsyPG3 zcnSs~=P$%@7G+I~QlD7l4Kv?b4SJq*Egy&7;SQJu-M+cP2?k@G|9esyXFt9+x{=gxO+Dp?P+%d`(s} zEn0q^#cYZ>uY-`P_x?M4Wv_b1*vG{tJb(eJJ~47vD2*{XDBC3 zMPhVF%Jsz)F9u<@C!u(z*LT3xSL?J#h-biEix({iT2j?C?uNUa4j)d)l?n|B2? zdi8N3L4i_9vSqB=y;jf*kB}y}5)la#s;R&?RFSt8W=F~Gq-i%AElDqnIM9axG+-@B-R1DE@MaT$SpveonylTn#n+#OeGPY4fiv=hGodoqZiEJ9Aqz*kv}dOD%BF*MmA0r=M*a z)9X8)q?J9Hb#zuqY9J`%3Xv9+(%h4w>)B{|!Go`zK9DU)j1mRQ_}D8Tv;1I69#rK; zD?gb+N|@o)vi|;6@s<^`v}sp(Q-}#@X|E*;b6d3Vz^2gGIBJZbr*nYPZW2RkywUq{z;b zh-9c_(~F06S^Hh8F_0}4?RtrrqJLwC+#lpttMY4X<=bAW5iOd{FE!vmjUs|JYg9wc z+Xoa|6xXvug@=cep=S@_Nfg-EhgOt>c7;S(!YeCjz{2mOnKGPuciwD* z)W(2!O6oZ5PM!U&;)-_m>~E&UPM}UP>A|jLDjGp$JBRkSa^t>(KxiN?y_qrSo5Fqa z&E3=~=S>Y$ndcB=-zleO-*9?!q2ctDW4zP|eabOx4EkZva)GDtC#J?IsoW+0@{#fq zP1u~F)?l_(HAiA>oGP_oUOgS|>(!o;yWqhMUBH5T^#ZwMRKHbI39*P!UBU4xu({Ig zE|*OX`D&Kjt5SYP2b+>9KF{z+qFDGfUP3Te*~|Xq)aPK#iNk`6=~e26j6UePYuO1yid{IIw0FuLe&sfY3Q(X+Fyd&+RbrfD*yyJQmi4r7^Irc{O#&&`-xhZBQRvR4Q-NQvk^y$)=60X59C;M7(}ehX^!tId>w}B=`sj7-(yhq%N6HYl1sf{u)JJR+f}d^OQ->Y)Qzl1lTTzR$ z0M4@8j%s{P$Oa{PQA;#15fkKsgrf<+_oj7Kb6dgfq80Z-usaqzMzInK5xwW#t}M2F zt#=4tkK&^zdqZbQ!$C*4{2#?m=%gu*h>uc$xL^GIEz~C${Tg zimlR(vo%y>1zTXN=BDy3u!?k9TVQKY@L`&l%689A9cH83c*`}p@{PAO(8}5pb$1>0 z5F$CSZfY^FhDt%(P;09Lsk2(YamK>1H7_#VNVeWLd@@=$(XDbtdcVD%>tFZLwl+e zM2Um{r+6tCGfJU%Z;P>FxjP9%O(l7d@=9aaoT1hex9zXFJ7eWhei5WP#(D>{UU}TV zEOJkHN;B!MDstOD)zs*6=r89mn+I!Qq+xtCuaKHwCb?_lQ=ao}o=>W#3*%hlOr`Ux z>wfbE$`a6em9ah>)>DUCh26iR7hSL2kF2q=z&*>YMDEg0xyv@5#+K@~aa)N#-dbNu zR?PyDhY~mIRWTl}t@lov)WWHTnYvM%f8?!ZW+itWl-u@CDVEvTrWMm}%Uh&xFs0P& za$HGYq4uH_J!c3THLwUn>jCP5-SaEmUFH9TrUnDNG9=m7eIN+JHQ1Cz_bqB~IpN$R zTMpbzZNBl4i<{I6nXOpC&jF{DUc7zUDOh%FVkkXxb92bPUs&UI`&E}^-N^W-Iq^!v-Ko*IeQpl+eoSa#MZIl&Rk|F znNN`{#4dEMVuHA2jOV9@GueI2yEk@AdN`dAPFkDalEk$Y$?TqWxC}noufY__?HMq@ zS$jtYQiJJ{)WDA9&{&F+IuWzi+0(N-wJ|f4@<(rl2K{k8xaP|rw*iJ_MRp92=JzQB zaw%=i45Zc#C3Cq>Z95dTVJNvvvq=%%D65n#75&)^83~;^ z5^NOlDD>{#=|Pw{W$4VU#eD|jDHXMW?zrEYf#GM7pA6sGql{a=D6^I?o4UJ4Q~l}W z(Av?ov}=yHBFtp1bfemU8>rS3(X%_7nb_B>OFp+m?yC-VKt`UTXG9$Yh1~OxP zLn&txdpgU;YkCYhHn zLkea{y{hM!ehxX=|LVV3ODYg@J3?w_7-|{8 zZ$2~8?@aXXPG+H?iT-?MxDT;8iq7F30lYaV&~~KfL}@e-G)2W*5r=02(>XZ-pkKU6 z%bQKW))u^tX;4D!zKM+PtH|lTima4#&>%=*O^;qQIeKxaaUOwAXVPyjDV+_J$f6{F zGBlhT?jPOf;4z#TPf?N6D;^{2iS|#v;z_{6qXI}iM))-|B+O&)V0M_wu9YBnXM2+? zQzJ=~Od>tldC``>IM(gE#?!+B(eA8(B#H$f`_qCH00}5JIzk!R5FYKz?g_-*-?h1) zfC+$sOQ5G@%A(M>QZOIPIb%mU<;Z9DkRa5>r`nXtW-}sQ2go7^`-d{QlruOuG?v@# z0Jd)ol`fSZr{~}(x<+|CbN$H?M31QV96x3JIKw3p*M{YHzRNf9c5I1e}X}RZqA)vehhXYdGcPherp~@QHZhUGPWsS@6$73iT?b67K{cWExkI ziA&njx#ZBu82q~mz zyRymA-4rJRG7jaH%2J#N$T-0l#fgB56BmY290g=t4#ScZ!HIy38ykfhDNY0s*PhPp z)y&8cL85VxlvO~+soeRD%#E^wx#3WNfn*lpgnEZ-h5yfaQgjp&(cSl@aSS;q;hO|s z6I$sqB)LUcsa=LttXBL4YaWtKXw}P*g4Oa)u=WX7t6zo`tS*2FE&+noMIb{8R_LCT zJHe$uu(}vzNWtoYnBbCF30Su%R8T<+rKK+?)FMdD7mb>rCp2HWs9YWqs|!m}pmt6a z3}vPQ5{)0)V6!l&J>;l>aJ!RGv0G57@P8tg>ZiwWdW0SrEoH^)KysgWW<>NpRA+jf zP|^F;6Xu`GQ^Kxc^h*XQbY*6QJcX)zgA>aAam2Vz8ds$N->86)#+6zH$Wx)s7Z2&A z=nb`d0&f#(jOQc(#q>MEX^AcZx&i~TM=&TK==g{Z!jO8XCptbN8e>WdP_u}KXddYm z&7ydfPihY-mfAxRE#Gy!NNELHyNL;rQ#Olj04&(bO>}J*u)384aKTniq7|(iHOv4l z)VwiTYTl@!ohZ_XPfQFuDqV0*ttU`Zi$@gX8#Ryuh?GFcNOgD$?@a;GbOL@bpN1pX z0q(@*GotU7#)ukboRu9sG`phs@RVIU5h40^B1*JSq66rRD+^H%VF2X$$Jx;MxdBr< zm>*g_-o9!T-%8q(!ss2fWR0Uz&rRl11t2gdKv$YB$KHrG1>H%r1o2iswvLYFTT>Gq zT^q*5dRU=LP`jHGE97t+J*KVnwgnRrL!I5N*!w8%Vx-8GG-ycX$FeCvp*ci|1`5=x z6|oNN5dNbBMmkEpu#M=p52dATz+PhyO!>Jh3) z!TLi-yLl>FPokrpZ679tyaj5hSY$8;GD?p_^WlR1W3$lCV7j%le{1&&M9P71Hkr=nI{V3WtS~Pu zK#V*BAq@LlyO$@Ln|bz2s(=?S#5oF~k*s7SYNFqdYi*Mjo-Kh@2_=#gMJ%8Pu7Yhq zB3{}cH}#M%8ctv1U})qa&_RPnrEM`M$4b~;4bZS?SJMVC)BTj(9bwU|@CwOkx zc!dZGG0e9ErJ|~X$8^^?ff@PYT?Wo}w;=aHTCSUTRT& ziec<=;2QT#os0I;(3z9pjV{+HOSZflbA-O~YLzPmV48#jr6#vkC6(_B5*Gh05sg<-&m8P9QrRecr+{WA86WuAmZm0tN60_qV`XfdcgMz_^ zzM*F$IvE&kVva$h<_c<{BxUPb6AwmKP9B&-^#a4&2n{*$heK6e>SD=8_LGq>Ry{HP@pz2sX zSaDMdsj{6xcx~X_5T(}xU!JskYmEX4x3lDwCep=Pdc-_5%7l?#aQqI;yC&Zzntwig-TyjL493#EN586XET58=EfZM;U1Nbw%h)6f>OxHTwf2ro;L#ax;ZsZ34W-cpLyVq; zr_oxGaIL_RxmJ7gtfAgA_Ln$>k(P?EVnN#s(#j+gYR*WENSl|_@JcOJi&ZDJnB`Zx zOI0k61!YlYtcOhQ%6D8WmTgZ?2nwCUaCew166<6fxq57bhNY>223p2iN1 zK{6zC?y%u)! z)bpVCm0ejHH=}ig6^s*r9J7mV5nx0`)i6d~@Zbf%KE!b!X0lw}zzXD4TDwwN)6XJm zd9&>eRJ7p=;w|3XqQ0*XaLONeMk1xb#cC`yOWJ!VZ0RyQhoHZ-Aw41sk9M-YoSt7I^yQUz>h+4 zN2Eq!i6D0lAc?RDo6`Uanl&o#t=%ounQg`jxGZ?`I--=oR`4jm7=@U88y4ytf_S;| z*?y3XYP11k0ycgZDKPkO+V#oB=&MVn0i2t`&Z^{yZRt9}uyxPeT$_SWR^G?utIbve z^p#<_3hB~@J}~Cm9~#mQK_QIbns8w^;+M{+%%B1?vDz*~X(`xx?1?_zMF`H|9~cEg znIoiN2=7oS7{(kk6@Z|@6PtnV(r_vwF{1AgHwV<{P@wyR$_OH!5sK{L z7a3c7px2<=PlH?0Fe<)__B!1`yzG9Ekp&F1bsGC%u2^l3J=@E7UI7 zPzyO0k86hov84uMF~@xcAPlLSMc<^n?jLqyQHLfV6LVH|Df1)`%_jvk7w!}i4|Pxk zrEHpUhL||&V#6<1N7|qS+7R0*`q8HOQ16bq?KtqTl^{HW4qBjT=NOc(52gnL@($83 zWn2wgS+&X?C9H8qlUeL&z&2@D)o!vqi0Dpb(K9J;5Fzu3mdUkh8R^=8P9P4le+8-S z-w%mmTB-Ns`j%vLyenOAez09m(yohpha|={3O1Kz#QKSx=x)a8YyH@coyF)eHINuh zrn8CEP->X^;PxbV&>Xmb3LJ+{WmBU#+Pz8Mg$qTX!B{^wJdF84KdsgBHc%QI2ra7F z_kdHftK|n>GI-Zc+BSvpiD<%VOf2paGZzz9k6`T^qqKzVjTc&P2%~DqvwlR(CXo?T zg(>c0O60CYL1FNiz)Bi^b8-5?%vl0k#uBt^rz%o(u&LaIna+1^8IHHY1q{O?b>!-J zD{LXLYYZmo65A4oQ4FQ~`bS3riJg&XO=Lb_BxAy}pE&P#=lq)78e+QsxEW6lUk`3p z%Z{fQWvGs_7!-N?qu%jQUxzyiLIu{Npyhgut7kQ6Y~uEZ3yyhAEUg9>jCm9z2{B-) z$^g`4c~v;Px--}R*SI>>qe|{Gx*dD3BB_-!I%BR@-Bw;S_<9To!xTLRHKsK3QrqDh zww5)lbXj%RTfDtY*9*H4a<-52iXLx?KA>0=Lal~`)SK~6OepcJ4udNv`ZfNXY3;$1U z)^|JQ`l4Rf9hqRHg3YXQETB$+C^#INR^s@*k8O|IUB2+V^wI`glr~780n;es1*`~` zo|>ziaV2E}Tivn4&G27ZNk-g((rCLQ%y_GoQ>j2KMCwQ}B@%Q|O?4g(d#UKY+zK2S zdXes3BHMB3DUG5><@c3h;rak8F0;>}OXUEQk$aIZmSP6exzfpm9g$6?(ZJFMn%Sfl zCWpfd{I&7Gwce#-ONy3WPZdso-`ceqlg8*-VP{Z+#*XZ14>Skl8QLAlhN}92y214K zdJc#lj@)sjW_4SBw&YpNPs63qN0HNARJpFI7DmNr5Iq)}glkLF#>Q-NNQ#`q$4Y(j^pNR2 z_AOK3CJdLSzreb37BATY#GXS)OT~HsNV|L`Mv9?a)d64dQK-VOiohve*AdW+zaHfn zv*A;J?hn^!Q+LBFO3+FaiLzhCY*ydx1+3L{6kn^Mh4L-wxZFur&U(!OD6$&F1?-KR zy5qRw#ehplV8B$y9V-UufK$&}9BugWne!ALu~sDM0bQi6IOqst_7_5#dPF^-3zZM* zz93=jHgcPwc$2#aDPX;fb{~n2QN9&>eAr!NpA_xh3*COj6RmP)q`JLTTk#!hC&q;M zpp|wRh=2GHXIuAnoGRnW_`;EVz1Zr<7iApC#XOLL%fctLiJ@^idmOvjahzfb$ITa< z>94`2I5qy|2rusV7w){1t~Drk?+kCy zz{IdZoovK;IV9Vdj?1UzEQ7yT3Su{GO}4Ze3%M_Z%5Pn-bRc`WcpSSQG2<~r-^iiK zGu|8(tB=2UAr!t}ANYFUg&=nSc%K}iy#N~bwk)h2V-N_eLNAaG{0e;EiLK6E-P;n7 z9Kjce+&o;xs4cNpoQET=yppeV;?<2P)z>EqXs6eG9d%du3u9 zHl&&c;`S*c8e2!eY24(r;?JnI(sxusYH?OTm3W9J!m~EJ3tz5^3#(EH_-8TYcKlG^ zDdFP#r43ESE{TF4C{)ZkX~6hcyK~dF?)F5-rY*y?h9ah3;-hICR5+2&rQAjH1fB7d z;L8EmkJ3>(6cfiJy|{ojfrGTtIFqb%(?z*aagYZsztT+#&KSEW&?!u(PN8l}TMSh?Heq!P_*m7(185}li%X*v{zR5^-sRuf{{ zTxpd~mdAvvdee?3U>ZGo(c)2xrdhX6;SKjyJgOlMB*lWNID5USuhnsqf<(qVRnT(q zx8@Z$J>nQjbVpSWts<>>nW*e&2f@eHXc;QDAK`BmD^(&8w2Tpa{3Aa6{f z^8v(B;dVS#9+*Z?3fB?xfu0q9#NqU0aZn=eKymU}>?xv9!jY%Hr}p-zMrn6Z0vFrl za>-pOI-@V)T%Mz|K>GIxw}&%I=tdtpu@5i_Tvw66DI|Tk7FfIqx1{y& z!Ews{DbW_m0|Mbw+lciPZrYR^emtVJoiB?5sC}HtGjHs8&`ITY$TGpPWA2N^(aO#o z!;RC$doquoPMi+IStkpVnGtBcasF)0Ex6Q?1YSp%X9}xXD~$%ddYsZ-DAkV#ix}80 zqi+DvrorcjnT0jt9%HZJ+*8C%NOkzWPo?qY+i9%9#~+C@H{OK;>BI(&++&|)m7Y|; zSpvY5ZrGNU*JD&xs>hauWq2ujt;R#tG#gKX&u;w82AhE&3SCpdjt4W^BoQfHUj+>k z5Woi7MIYaPH~}bjc~5kp(~4Eo7h9Hb6UlCIQHD5$ z$s&fMkE$gGmD!32ICFtj84g&fnDicBiDO^ajb*V01hrrTo#+$W$&ead3sVbk!4g|B!hc?`92 zbQHX-K9K~YMB!a=;AuMVIU+*pPb$X%j>6QDgGNWB4~dJQlViPkAhG#f<;F z7V(ZlgaPP-Fn^0XlMLgRoSnyk?P z;yfpLeBK(Ye+(w!B5*?_b^vG=jB~gUY@w)14HFCS-K;kn+u&z4%Cy|b2^s)6n`;qBAU77q6tGMPc-+iH0mml z-{g{5Zng&8EztTjn?op+nn-<)l(}QywXuEZ!rvn#wN{S_CTgTp1Kb@FA-qAZmiW*eS8tt4C9+u&1*fanZUZ#xYnG=%<^+bQ2Xfn+9{J<4rI;Zrs-vp*bnm7Li9HXGoJn{@w%k zdE0t2vK@mn>FDUA=E>+h;6zK2D*6qgr-#c##)@AsW{hK)Nb#|Y!mAqi5`!aZc)81I zbQi^t$UO?%rzkGAfcCtw-o>m$LQX&SB?l7h-!TD-t6IUWG=eS7v>GHPDJ>|pl~>Dk zMHhZj+9Z}rIgp@b*fJf6IJL7_b>{dxF3-3`8+_u#27@2F{!4dVr3O^*#MV z{X@Czau^$31KiOzn8{8gvjd&zL=BE6I&z~0lCddca8&HfASbteRJOZ{tulta4cPDF zS~~Zu)WOW&*$_H^nLZP_q^QhWH`8>1xYXDyImz3B%UL>vE)}QpWGi(6G~J1ZsboPM zba1np+mmS4IuFW%n*gy>j5>p`sG{rz%w;T>oQaDCJI0~P9@vIJR%1N|smVY2gE664 zJoDI}7?}oro2tHd3ov>)o?Mw45zGJS!On}4$y~NMj`jcH%($`9Dvj*{WPKeg#9U-9 z8*gWrWR7kDBm|veIYvTYf~bXVEySrwD-*ab)yYjHM+<%+VthOiU|l#pN^|JFsw1%% zWkMHv7&hUtuK>l-BsUqGm^4(=S!7XS=+SJ(c66;A8yDS{M9u?Fi{G?gowGGJnb|ni zlUXu#m_RaWTcKN8D&9lm+4Wa|3739g!xN$E zL=(v)Q8h}MjBRTn#)1(_S($;9o-5w(ES4VL?r#=lmw3ADY=)cEtX5pZd26%i(V;3= ziAc11G>a7Is!I0jm-Y9rinoXl)u@Xz$y=JCgBtE>_WAB|b>VjR-0wLH&x{y~3^R_8 zu;S@G%u1V;ZDQUSel#CB?{a)YmJliLL1X#|d9SG1V26jYnhxJ`fX$V-e_ZhDcQEDF zr%I*^ytS&-OhJT&>#tPMfjDoX%=v=ODN(B;W!@Z36kS0Q^9OQ$!ye}r&&eO`@C1uz zCZU>A-sGET*osmudc;XIGY=cZ%tI%&(sDwi$cWi6`J$5!Zu3-fHbTuusBv^TQv}uM z+ER7#Z`?vpDb!9um3PH9)3^PcN3qJeL!0UF&+F}LIbr?)E&==6CHA0G!fsFukzD8%MP>KQ%5OzC zu&^g1XRsd5z&HEW2}jZ0fgioqshr~?#qRu|e*DxI&fi_Otxo$I<9O3)=i>IqwOuv# z+KyW=wYqYv))Kgr>#craLLQ)7g9=u({|D~@F9GjC_ik+>r?EkFF=~31Rt<~6?9J#R zFlzS{Yx~tDsgYf8^`d6?q_T1)SfABZ%PXg9sP6`Ja)&Y_yR;lUDzEtBiK*&aYIBuT zEsMs}WuFdiMqlw6<;_4f)v!6~82X~78d!KWeeeBwZBuOvCz=bGYRRK%KhwT5R~8A2O)zU7$=yR!MzqPkbZN>6PCJZL<4D`Da3SwxT){M5#gFJhrYR-9uGE;F zDsu7G0axY8@tS-iqXY z0Ts9BY9u~SJz#J50cYnP!CycH&c`(1hA4M+DAYX)0h>w0p$lPeXf&>Vs)3Wh7CZTo znB0$ojVWl}u;oTx5+yz#qpd19Ur}5V^#YZ>f@`72(r(I#_V|xaik{=1R1l2g_uqvu0k?)=w`OxDD1(T{d8$GOhlhrE#{JF!1me3i5j=WlH?6gVCD zrf;G&-;tE3b@)i}PgOd$LbLb?E+JI7fz-Eu*&vM&8^JrRLw&zd#sQyE)F9t>`jsW7 z>d%F;^|pC=OA)5)_x}l@##cx}f$qplkGo2K;3l@*g!xi>Kj|GkBJ;>zu}tC?!M1Mt zuA$tcN4JIl8gwd2EzT|_!;3`f{pvH+Stk3Jhtem9)S&dMXfnMAz!bjet_EC}Zrftu<7Gh7*2h$O> z9gu$d&BK7{jdUmyaqgdc2ze-y82!@mE|njO!~+Z)G5wM67?$NIZ3)A`F8{u)uNmOk7}UBFuNFO zX1b%y6Of9E9!a$?dx98eT8kNCI=y=ZXE?d9FXaqna16N<;>;*Io2STZvi}kdbGJ*F*=T=$eWH`w_vX`q3ZC}f zh)gbc?f2ODc{Zs}p3DsqA8<8Ar1E@H|3WWI`_Lk;3?YunnmPp<$$463UcIBPOYrrB z>0D7<{YW=JMtmaHWU%KS?bzm_-A|3S7funIg6o^ygRiEJ+%-KNYYK_!ZfdFY)P^!^ zq&!knoq#0|m!{Lv#lLn{ujupj^@(B3JA~R7Jni~U+IO3t(qOQ@4Wt1H58%Q=J z^9{?Eotew_pSdTM?Mr1dxv5gg^)B+-9LzO!#EkazuG+b^sL$V;A|>D%Q5-NHF5;8C zrb<~E^M>)z$93nXQH=d`j zsrFQ_DPl~fElq(=r0?*q^@%QQlty2Yw~<$To@1HjU$mpEPpiR7$$Bw`tiI8n0tzhS z0IjLUI&I7Gjv*%F2&@PVqf7xJI>ahs0km;rR;c(fR8!G@LU6B+1)6HyM{(j&90T#G z=#wHir|GJCHJuG9u&KpIw%Uj~{xG@lLUofp~EI!aXRJ<%M>3u@L-1q4~c9FJB$b9+;(DjY6v@&jpZ-B+L|bGlV9PJLj3DUV%wM5 zMWEuNHM!}t8*)v!{aa<}#GRWfxr9{ifD_jX;~)K)TcFzQEl}YZHrGwHeU!1oJYa9n zBofzce2Gmf;aNhrp|TAkk(Fh^eIMb4XehABB0L7DK`g7UadbymE~bY^p+4|XGe_3$ zfpYZ~SGFH-(i~;5|F5;Yy#QsguNU6K=PGBByIc*pwcodP-Hx^EwzAf)D<|Eq*S)a( z({4^!m0FUnoMss-&6C8DZ~YY>ILZa&$~9FcUuCWfSI3t&9Q1dKFZWJjA%X+Sc6Pa|TjVP^vFTZNsZ^I+_0SE; zG(ogus2bgE>m7Aufg1{$hVqD_&ZjW|%cq7%`^E+_tVr(~Ne$pD&rCMCE46xg zGro{%T?1*ah~P6%dA`hwRV&&XO-l%4N=8=n@k*F=S@u5J-+daAOeH1I*A8S4dLLn! zNym6oPb!x`Kb7B|8Q8vAd<)*(v_TE0={xGaWdEMdk-S&MKLeA@Bt>N|?HaKnpN)8~nLsW8IDaYI5h z>jzdZo%?;&Es`4=G8MGHmy2No)t`7QWfP}=S0#>}moX=^4<>#{athPeQ#>W*(EOS#jvh$~*$ovs2`zRWvaC7$d>U)fmF z9woDbRraE94SOG$J8}Da6@ATZbmz)kzO8{3g}FS_xANOr{>pFFAznCqYYXRG5Fi73~bmDat?C(bx;TlSohopV2I=7>entbb*&=iS6X56fRN$BD8FMUNq5*kXOj2l7&j3Qv zfaDZ`*A^xe4agIUz&8pLiUwqMom5?$dd8e?Ra*KnUnQ|&9^{Naa*a+^0nWd%FrH{Y zx)g!yG@(oVyfDb6g+bn`l5W!=mT5)>BE$V&C&iw^pN7eb%reRI%j;Nzwo1iVdcA;w%YRN6+16e?4W$kR6*u2 zz+H3FPMxcVgYTRvrGW?kh~>fUd>8oh1?j`iww<%JDst%Dyio<214Q{1Ya_at5pgci zw`%n+B__i_wp%ROq64~0k$at%?J`@o%lxw4t#Uo5%fxc357=`2`D#C&XDmEcYjUV! zY?)@z(sT%r?JD<(#$xsESmC#6kRA^HO-Jo~`79~JrRo__@b6X7oEyD24nE={@~h%b zmGlt}V%49!RnmPL#M1hwRnm_%h=nCuke|AQo>jr$x>0^1nYNM35AuY{{dtXLdj%lO z!|yc~OAnI<^52SwEYlPb=1z8v!%*UR?h$A z8%EB-Yh6VCl1rN3%$U}fI4{y_0EImX6@eqd_bowyC6?2C=Y23o_vn+NXlo zxlw-AFl{53AEaC5zEESa3_k=2^YCVk#nMAGAg@;h-m3{&?6UO~;pJwP`{NpmRkG25 zFq?O1LY7__qzEtHRk@$jSb8~l$6Q&UsLD^N;L~oDzp$SzjA)*l>lhVW>_*iL(esKU zW;)23OeW0#DSnR9vUl0)u*z_zf_8Ilw{uyB8da_^9CGm*9Qw&^n`6v)_K`tIHIGv_p0DEI;!{GD)_LDvT!>pX`Tk@;b5DN zvU)5pRY@+0g?O0)xlCiROn^aLEEdRS3ya0efC6FpV~#at^qd0utLCMbgTFb1b-MGv zRPfwGb(Fv2#pcVH3FtC>oF@ z2g?FjrJm?P`pYO9kO@WL^@RyV1M-9-@LNsDs!E?%No<&b3!$9f(FSedi3VhjB5;-_ zWX%OL$dQFX&QnP{G>BD@(STg62=r+}7Q2_Lqz5#JrMeN7RI~_gweVQ}j7j`Xld?cQ zu9BY9AQm^DR7pj-;lwT4o%L|=0UfpTKUHwvVX__t3^Y3x2za^NCeeW0rwDvR6S5>?n>=Jr~3Z~pBziODak;@OVLgikmu~-%y z0)%-;Yb=%?q5&CJ1m39$S!EIp$fzQ)R}-=%Vw?QF2I=A8S%*tK!{NS41#fku{AKWO z3IXSa1#|FE8n@Lo{*g-hjRvte{E15XnFg`6^%s@2ShHtgi5BDpm(WQnc!nG0R}IrP za`{32#=>bVmIa3ZVIJZdOP8NeG$1P!flDoGIC<1e}Jy`6{P)R3f5Ubdt z0bw2v)r2ge8Kej=Y}q?BmR=4X`Vy%`7=4Qhp5;dQ72K^5aBghM=HOn9d*_WR_$D{1 zW{47s1~VNru{)VCLyDj4wCr8BI;=9xS-G~`xhyM;Dpwc|xp-Zu1uf^=P#VnYs2;v_q zw&rQXmIRXq!on@pyjT+5tdc&hL3%m(m800HT>8%{_!BqE?+flPjOaTWw>9s;$eHyW~g_S`TxggAG!j1BCTwN|E5OWH$ zQv{?@vE_nTJ~9AggUaP9(8_g|0=YoT-R+k<8W85iRj|d&`K5VzqXK!qX4k5Q404kT za%<^a_b3p428=d1iJwJ4p4POj3iY5$`hy1P_AC4oDv6yl8rIKF_<@+j)7pdYWT(#6 zI)K67Fx4X^zJSFh25}ke`oGe-<|>5zL>JW0F(>ge0OWXurBSnI8Ofx9oTPYIu6eOc zjX_*?Es!>qdsAU74DxapX~F-K_CgWjmEXZc=RCq1m;{_Fk3rfCjOu@`Ebr@v1;RuX2B@Fct>+h6b_N4FU3f zmHV68sU&QtVinsjRjxHUm!*eE135_X(4%>=^bi7Mfy!M(q7WcUOJfNE(y6c*mFp&} zH3$WCt-^G@dImV)Xh7bj2;5qjP&6R-D*_)bOeh)4o6qf5XFTH-j8N|?zy<3nIkJ0t4 zmxKRyjKqk(?+;XP?Xfz_Pi?tEaIQwwQyY*DMPREYWSM-gO4_MGEahBmfn4BcH?2VK z*I2Bw99BuJm%yz*@3HXMlQs%u?jqK&1@bWq#Ny`RFx>n`0sT!q1A4O2fH+DPS0<~R z4p$&A)nZ%abfg7hmD9-zB&D%fnmJ7+6)mS83y)O@OyUcglm#-Zl3Wmrn=8U_^C1QF zh$dy#r)WSvZ82<>)7KQpw>2+TIepUtvC8R33Zy}uR}=7&`cD-|(Q-OW<#+K|g}_PI zXi^r)X)4JDvC3(w0x8PPfC9>CQdT)d12S$gY?agN706pPFIG9d(E_o`=~e~uJ&ncE z%xx;EsAj%u;js#VNvzUMjRo>kg~bK2xcPY)ZjM(ZmT6K}IYk2!R|H&!t#VqcKsIS! zta9qGK&*1=RUkKOES6?2R!K$6>3R!~RR~PtJDQXQa+^x}R}ErubC*gg%FTAw#Te3E zjUEoZMn`pX@XC7GU}90Ui^I37IQW+jso=*AFn=>|6TE;4Uatx6CLHJDN7S#_OKUcJICzzgvPxkxbLABqAJB4LX3J$w;&U!nh)O^{ zu4w;3tHK(Hd{QN`d7%4t<28OQ|J1@`sdSMN?<6gzHB&OIlGtVf8b9XZ^BPMp2d`W# zxeAzu{;Yy#Pz>)l_`F7BNj{mmo>FXlL$hNkFa!wac7?KhX0#yxquK49t<-;*E{1}% zja+_1`WJ=pyBe`&B_TlmsB$w;0TUz4!%WStMTnDJEEdS|D)*~37ONdQQ6+U~5KAx7 zf^2mOy+Q?F=|=e#&a{nOevngD?$b3EOAjGHI#q7wDWGyQ4;L3E#7Qm|isH))U_4o05q zW<}#RP0Mm>AwW2{%brz%q6PV?X1Dhl75u&%st znA0~aPz<~|_z4}={jdr??M6Aie~jo(4bpS33Vzs)Vnkndqa5GAZ>gkbHApW9Z#_Z6 z2ADVJTA)F!iBSe&Y-r0kc$?0()5neTBgMu~G&>h?a9!bCe^k&eJ67Qwt#aR`oKV|#We}H;)j7Dx!ea31^Pel(K_vpxhrwo>2&X?IQY%3LalL z*YgVGZUqv!%ON@-N0B*3b7a-O5Fo6WH)$+8Surd}z*x`Db*Y`pa?EQLjZRI=YO{J& zlFLrFjo6aY&J{)oJ69MXE>;|73k$&@tU%bRC1@C!k0=tK)1-Pi_*WfeDdTG@Y3V7_ ztU=xC9!CZ9ABxtgidH~_%^;_15UVx*g~IZ@7Rpi=%X_lMV#&=QMR;M5BD};Dful7c ziE7y&QZ{MS09p>RgxFh^)G|N`)F00g8ci+{yF5uvfQ`zTRa@o0hIai&|)jdN6XSq@S z@?k{Z)8wsD0fR7sn6sUOmukdTov?FV#JMifxhx&pxi02h7wKG=`GxqBV%`;^_vb3A zJZ%IZ`c+kkzN*!FF$e#kqb{?{r=V#6s&ieyK^M`bHX_SnShR0xMB6#&B1+hZtb%1k zPisUManMDy(?(>K^^X*SovL61yBm`X#HIarEnJr^iRDm#tDxOn+wEN2{Z<=Qt}q;O z$rv2^*H97S2kTFhCJ`Vv=bEKKtfup86(Qza zArMCc@(ovR4nC`+ES&`)ww&X43!JuB>!z23U(``Mzodd+ccTg+dYuNbl)OtN z6#-!aztC8EIrwKCWeIBM>fu~})VZwMn`)FYd{;futl771apI2@5JvhOoOQa)4~v_l zg2%g2e*G|_-)lrYf8n6c)x(I6aijc*PE<*a8pNteoYYhpgpqj$pqGO`&{0+`dQ>HSPlH(63IQ@}i7eiQ>KQOq$4T|I24MoHxP&;kT1Qzz zo~V)-6cTW7N#R^)s-zYTVij&QAWWc$1m`Lqk}fYCyjMqA<}px zFMreQS|vGYAfK^#u{v8JK)!Bau_Ous@@#1=AwXsKWLiwyMOl)H9&2M+36X z=H}XK{LM%xpw}u)Z!665KdPjs3WIz^C4JTf`CRE-jPUDjF24-XfG~mYxP&!nxj{lHQ_0EV-irVFE=Yc%S0oahDek z&R@nR(fuYByvvQcTLtfPqx_YXaX+PTTMg!eDycerG zo;B4O0_3YIHxoibVBhu|9niBjIeREK$v}TmJk8OjV3qTvfz&G=mS|qAp2jkjG^9bS zdc8&^ovT4CEFnNR_r-;=L<7>J2yitGSY5V3tXXtsGg+8jR+&r4Qk@NAwH`Kz#mg0z zL{Gddt9)30@G^(kUU#7;SM z!OVjWJ$%-&hyM7QgO7;4B<47EEzWrh>gL^W&Y_NTP+e^Cg4X#59Xfyhs`+QlcbpmZ zPUnL5dCdsUJj6NZ(9Q)EfA+zv4|becZbbV$$C1{?<+N&u@5KKo!0plowy0)yks zHBvhl80qsUy#?sz2SGT_!OLPEoc#bjgyXi%KYyOWwHQPWT?tsnIZQIvK9A5IZgNQs z9l@CmCSJmE2Eyj~gmQtwm6dp;k*Kga&QXj@$1FS(A`)Xq*TqcbE?Ow!rKVrH5b8y6 zrsEu=5_4r6Ajrq7l`6)fc8$BDcPJ)g?jQbnAA&R=aBKpLPDWC&M7mUx>@p_piU(|NJx5l zS&Jv_w8gRbg5Fsd&A%A98!2BLK&Q`i>JOp75`w0{Qi3B|fP_-cFkX>yS&KtJXU-Sw zI8IZG${$w>pD7jFtaUk)EOxol;!JG`q{S9j@R?d4WH>7{`1DoV4Yaz=kVebW6?3e**h2zA_g{J|Gs_I3DARCzKX^Vd zKX9s0K!(B`G`hgiUJ{zT!sX@0*kQy-)}teB=47rpvN)+VZFS_v^JY;2jpK~n@Y)z)9cP>Z zjx&J=^x`;sJx1#|xS^Sx7acNvrArvj48D#$;;Y=qnJVhl%N(y?q=XwtLsuEV8pGA+ z3I$ygi;AMsFvRhiDl^B$i%IS zcEGp9mVq;p%aQ9XBrtEfGS)*{t*C@`hyZw@JDnWQtw9A45=>rRd6pr(0BTDh&IG-^hNel)1m_Xz5wC0RfG>IwP%~bS_l8Bs z&!CsOlbqPhHSdf$e>li-7QHMMoAtMM#hf496>}D~)}6Fy_VMq=Hc0#}Iw6LCb8eeK zIQJpqrPl%e#5=ZtFeOk9XYNBt_!>c)>L|rvVZr4{c|E1>LFz%i)Fb}^Dc{6x4zY2hC|a)p zL(Wk`%#yLMC)gwJ3&0{%K97_c?*R2z0sovg5%k=eKBv zrJQsBdSjil;SB_FKSPY5TwMs~=o!x-%bcSRp7D$-v?H!v5Oa<`jL^;7Nh)<_|MsSs zvjOJ~9Q{%wcK$ig??dp!M=$OF69fl%zW`tOgXNNmg}?d*x_L(e!P{=AbN-CKqw5KQ z0N6BE=Sci>9-U2f{pcB+P&tW{ng1!x$K>Q2l9NkNWerYb?ED82D>=FSW}%3A|0+3Y zg7Qh&g+B&L!O0eo{U`h>P6$A7A~4Na{|V^zi1Xfx^dkhPzVw;5fKg`=8PSEP=JoG+ zX(wuW{U2r?a}?D2N(%pe=Fu~Mv?}HtzW9b&V~BXgZ82x@jc`7*zJI>s{NI0Lp!o(= zhGWma%5lC4y)Aw(?94g#5`KLjUSr4Z=GXV*weHy0^XqMRJ?Pk5`1N+Y&Nz0_S+G4q zbq8K&9=n!P@5Jk@`s-JNfqx)rV)Kp{m6}+ZL!3BsUj+`IIvrWx{&rc0v3VyGj5GJ2 zkg^5ZSp1HouMnlHQ=UW08?Q#nJ9S-Dd5(Qg%=sLpyvv``g_Qrj1}Qi9poI~<$UH|r zf2*uGi|=+BBxO2B3C2stwiE1;C&P78^)s=El!g6kqzO1j&zyHHEPe4IvrfQs)&~H5 zD2iqFTfo{NEOzlS!B(SC(J-{(%zl`Yq)U`Z^H39=*+1l@b|cqDku(bu34|{*H)EBRFlbqR?Aoj%9Aadx@O1v8O4|iwU z|Euw8*#A{{opJ0Y&=vN7HC|^Pdm+DKNKiM+tq#}Xb#{H%YoXFU(oAgLd7`X|!#QN+ z&fGMz3NziU&2)>c(}h%v4;? zQ9>6bV=o}sBfA5zh!kyj&Y_tPpsaKFq0%^Rb=~3{IDA%YF*~i}RyvFC;rMe7TKp)7 z*Tfb-#o@E-j{60|Kf4nabysZ8@iQ+UK`YjMX~X##7QmS1-;ej7qw(oZBoG6^=4^f` zwPPs8IXz#5suuqAbE@JWKl4VB`BWXX=#eKe-<7Fzx?koTKeH=KsBdpL2IzqLgxBC* zpuS@%Vt{)7hdAa=6*K21cu!d*^S{lBcX8sdoA`H5`~WBZ677aFe|JvNxQFBW$sf;u zkmEnd@wfjB@C(0{(!vY?Wvu&j9ku8)Cn;f;K$ycPDD^!J<5HOU=i*%m^WGb!FmsZ4 zIzj_CA+7t?h1Wc#alcIDK2=98B2{WdeR&_@zMiAa?s%;G~Ian6wHoOZqyG}+773U|(11~(`R~q38k>yk!wdgjaY2F&I zA%vNR*DHjV;9VfR;$nqRIOj#T;7w#2o&N>~$ufv=(hJEMQl|mhTqm%es-qS?hcr#| zsB1xU$7v1ED4Of=egpn?oc0SvQ+O4f8wgJqSq{-ri@vZ#BE(hgC;l3VKf+)4u|x(+ z&|oK>0bkvH?3X44SBqXtvbHsB!}Jf;g$;NYvbJMRN+?e>Ukk}&D?!c>Sx(hai@M;K zv>;30OoB8w+@TP5<6Q{S{4s@43PNZV!qpqIW5?hGtIY12(T-3mpzFuc7C++AZPK1AH(qIw7;#cbG`)* z7vJBw0Vw9Z9No~<7Sb=6T>N0;bBH_%ucybB;djZqw_)lTfu$$>F6Quwm3$;*-LD%P z^8h#vX-gJ>>~aLoh#8Q4Lgb-8ZoB}1bC7hpb0mJ3e*L#DJ`L3pYg`7f?<4JW=Q;c? z`vZP3dA|i&7>cPM`jf`r0r*nFdGK!hF3aNw1;S@;@@bJx4Lu}ED;Rtw1ujNlhyt%h zU@r+r%y2F~v9j*J8XKQxW*Q7;oHIyWeBNYAmCoW1H_ivNP@N-Gx8wptbtft?KDm)p zHwOShb@w8mRmYHgkRw$0Eco=P&VqvKJ_oR1)iExn4%NL5G;P)K(U^RwW78s`x~~FQ zsP5MY2-O`9tJ13DTzs%3sV)gf!OS9$>OKS2@tKdKuIk&z_u;$DUWMnrlb|9(o-N2hf;EY*8fHyVX0Kf(U%mZ)<0&o;mH5pg)abyc9jwc%bor^v;X}J(J2wBnI%fs` z7Jo@qnlFn=lLdueoeIT%g<7;z?!&97LtnjK*P*Y8I`o@Ys5?W!%Uu*m!P+UnRDC*E>De~#YYca!V)S)vkHVTao%Hvb;sL&1ufGD&F5YUCj zkbEc}3hfs_>?<@23WfF*z=8{naWQoi+Kr%T7aAWk$Oq)9I`j9sL)b?6wG+*(34OapP%6L~(o#0bPeU7azVy z#ZeCc!OUr9^M)?nNB)iasjqE#{%AR{`aa%8KlQqU7RmlC&lCdq3j+95J$Wc5*;Eg8 z(TU##4``{5Yg_aT>ecJ0(fanHrx3i2f}eNdGhTKt=G*32OTm7yX=#s`_^OA^HUDKAck?{T_k?rOgdW=3u z=}yaKNTTV+`deoZVmGVPGR8^ook2rHktB1icneW_zn~-uIjy%Mibm%3cT=B>)nW8ZY;W`c3%{v0X3=}MJy_(RrorAk?e6yJ2EN*O?koUZ)) zF{%`0%8|Dq#hqxB46X(X=5%GT*e-%S^2q=!BBfmnuU6joatO6*=CN49y8fdmsQN2r zANDo`cwyzN58&nY`(aRz&4y9O&U*Ucm{?h<|HABpPP#ExcNUF$R$(@~{)>pfn(|q1 z`Ap2Yh$5as#4WM9=Jz8))Qe{kaYt-95vtG4CXB|kw55H;LTz{~#`N&iF1U#8@l;0}|NuKMOb5p&w`SN{!4 zp5;qkvl&Tal>7_{UuUS#X}KQp4^Y~VW-D(~H&4jzv_67p;adKKvZ-8eC28A4L5GNb zCqcJr0gQ5T9R6(?6) zR{RjATYs?$+wvTuI_4nyvRQiOw3E=x=_a09>OL8B(v+SIPOnG0aL|LZXvIdbA@Vyd z%}C1QuYUI|Z7LEq_0q(Y-kkHWoaD4z!;n|{A*nr3Ko2p{TW3AhU{abxbC$IW6x)^tLmA?g2|9k0EIV zwPqjoDbs2BHzeKlIwU>fSAmb+mg7FHAiv>7}k&T07&ga4NwT;r6G zt-l4NF!nlO?84%tsk8~R3lV(<8CL5Y_$mvLNIIthNjH+0n>AaN^gL-dG~F(iTiw!@ zY&nZ&yawxpXJJ5g$k{WVhou}|zoM@B)SF|@3Dg&OeH~R5imz`IUUS}M!p6mR0n&&{ z>@X9B-;{|jdjvUqjYOxV6;XFm^rdy$93@hrVX6!+mrlz^89W^bE*R0ec3O^s2@CAw zf#8BQ7rZqGaG}iC5syl^KGJiW5IRKkkSLY62O$zkSkyazPt2*S|6cQw*)fNlMLoPI zdVRFUCtl~^H8%H+e@3ql5cNOM4&@WTijKp5NSUCNANo^1kCgXP%D?+kX8#x|k5kHz zg=+z&RP*8oQ8^$gudO(X{xXD}ISUDFQCHe={!E?dCr|ti_c zWkWAuEF{DE3zAQ|NTk!NbM9pb%Sr8+%CL^c+1>3ik$&PZ(#fMOIhQ7iA;(GgB4)|D zN1nu<=|yWnem&L9Q_saR&ytR(ehZu@o;qG9R%VxMqSfL)7osemh|$sr(&s#ar_=g*B;+XJ zvy?}yo5+-oYeAIam=ov3_hWtM@A&KfrdkcsD?JNIZ$=@|t8-%8Ud)i=ultYwVqQoq zLoG-;iF%sdf28^KlXj!1yZOV0z z7F+j9jN$74X)cjGZ_P~X5j+R#e0VOE^LaPmoha0QaxRfL?~lMiWa=N8OLR6qkBNLL zg8E12-f=SC+pz`gBEt9hTykHXWEAzE61bNx{7uZcNAdEodLm!r)4*{G(w6=Sg zJL7JwBlYtiR)Xy710SIgSlCY-pK8W|nHURR=b7?00ydU8G=k)%SxiqV{PFUvu z&)j*(M^S|Te|B;)dq+Y-3*iz%06|n#JT`#nZ29ajo;t*&u?C@o$NgC=b4$EwllLkd#`iN z?AAOi#7L@%Z-h^J6R+0Gc{yXr`(}9Ei|oy7OZE1xa5ff0x<3GIuE#r6J$@7ZNu<6z z90fmf9-Y6(sXCK7t%5ya>b1JB$J6hH#CC<7L67VBdAf`)^U7*R_{3=lFHy$>3aH~l zprGsct`pFKYuhgVB!$IrQ> zU^FDw@05W@)qIDpYiR>@hpua>N9~!Pp@ob>S!Okvqn~V7mFXwriJ+SvLS?QhqrO}; zxeQOKAHmUgr+$!~cwWt;5F-UN)DfMwdJn#9TG~LRpr*yVJk%X6tf=4>b(f}|qu^b> zOOw3dHFa;?E^wC=T`s|!PJEYsJ$aXAweR>2%3Agg=!%kipvrgY@BOG^D-hqM_xtYB zUjy)6`T*G&cWGzcO;Ti{2P)WUQJD}Rs5|8oQaa@m$Xs>G zEs~w`iQFmoYL7QOC*UY3OhXK+qBSxqS`k+?E~0|QTpvY~*?5oO9UN6<`c;F(cr&GD ze2KRMO6HK7et{s7ep9VH)c-9!i!AuriVed_)h{UUU%0?YUhpU7kQMph6e@7%&RtT} z-U0DZt}To{R_F5}gafivqeIiSSrmB+i zP)ndW=|BzSs7F&!ygLxj^Bby3o=SLp7{uLoBA!Nu*yb7^p8~d=SmOXY;{fu&%mLB6 z^*g8%I0|OUl7}%?wX9wj!g~ja4%_f{Uad~2(@dkud+_j}|Db;~s0M)tlY_uRT=9B8 zg9l~{N1+tzrrq3~FRn@GLn+E|^xYnK2+-C0Vx9NRIjicfLsHDbQSc3t)9wE8co04f zH@k1_C)Zn|`*!#_h2Pqo!mgfS~W!U*w<)zW+nS6)7Agyalgx&j3fQ)X?{aj|@jXh+SsC*tBWuI+uo`ObS z>L+;!oF1xKfE+AWFI&r{GBo>iekNiS)7#c^r7Ep6_^o9ndd?8pX8{PO!CW<=mRn^% z(!^hcO%yNwfP#A4uoE3Q^n-@TrgybP#V7#y;^8{$(hISA)Zh-pPhex7VT6^!C1%(lc?wSc}zvFHo& zCs@&vUnTm$2wT|H$%yz&@EknSlh^~Cj3~Yl;_f8Y4MfEs{|@5$ByMJCt99&ni`y;n z2eFolnXz0A)*TP|WQk!X;%gzEN#f3?*!dLVH%NSjOia8vG~v{ngLmGGfV%rpyfaWY zLT4L+*)?d&>r4WhORTRX0bi*Kv3NO&^;!>KrM+V*$|AlVCUh&3Rc3I^I>wjAY^J?FBj8Hrm@Jc7Lg^v=HgfQyO&zyGV^r-D&$?#Bm0b1x2=$&ux*Maufa zuj+%n07Y+i+Yj~hA8?tdPvuasYZu%P*x%{|H49rdK#zR7IVJ$ zlpfD&^o7nJr9_>JdiRt29jC>WI=J=z;P|P5QtIO=JymURhUOe-9>5`AtX7j=1kg$R z*VEimt)>xXkMWjx9*2ChTFpe5Hq91h$nz5H0%4(bDfn1*UH>+_*j)?cV4o_j5A)JP4FO(_^Hs|$PcBm4txp1~a z{|R)&vibieUaA8AD4qEev0C2=L6rP|f~eN|j7gT5g+q3(*7_Z;uM45Dp)r)Y{HKy` zG6$hqay>M={->sJxucXfUbNB!W>kcjd1e8n2)HAtKd{f)1bM6Lb|kOYP%H9T8MukG``v_Aa&u0 zsd$8gLr$#e%@cIH=CwNK60kMIr`4ntSiXBC+qH0>1N)5lEj4LnEXjrQ3&b6#0nM&9 z{`Wa2#zEn5KPb(uN#h#RexZl%NFa58a^CgG;w1TCDRomh(=9>Y7?sO>*})GeL_7vQ z28Uc}HVcYb*PDrekCDQfntE#M^>aKub#{CF;RNSIsqme~Gqm}-B&L+<=*I%zi$gve zh@O{`;#&calEQNVg$mrf?W6PPDjVKti4i#D%hl$r>fNsNl(to?r23?Xq4Xz(^j@_} zDx|ENEO9mtxu;qs719VOJVQ!*t5s4Vy$^-fH$&;OY8#wV>JNn%N$LBV)phVn=@1m! z-vXt>|3gTFqtHr7#!}>c!iicmp0WpT13M`%U>Jp=J>LbnFcM-cx? z==K2m2jco^Kz9UCV~E=kx+{P>Lp+qwJpn`;#xds?^4TK)jXEBLVa} z#0Lqj3!q~VH^OSLd^&(mg}4`?X9H*`#5WMy96+~2{3xMU0*Kz7|CrG00rUgJHL&C> zcLq=ch+~A_4IujX)nGz<1LzWn=MnlOfbN6%H9}to(1#HJO6a=)`WNE5c=jX@22d2@ zR)l^Ipc07b3ls8>02&VQG(vv|&|HWgB7}YQUSFkK<&zN8BQSYf0DS=QAB1WIPsyh z;>QWO0rWD&`v?sVpsygVg~ulHyZ|}{;wnPJ186M7%Lt8(Ozp03aa?Wq-YJ~v!z}S6 z4mm3F)V^wX@dda);gDk@jX$o2e*so|IQS)z#CY2bKOd|Q@v+tOVPNx!Uml^SnS2X2 z?U#VPL3~_fc6IUh9ASw`IOO=qk?MHPC`**%kXJ`CKdUDE&7<}8UmKy#fJXeh=H`3@ z&euO7a@uv(@ET+E^-qi><`XLY%DxpiU*GkS#Nf*0=YsR~-4LODje+e8ntL35z+ zEGaGVU!|9`1?K2hej^_0wO#KU;3%h40BgvVtBb)r!#a>2q9V z=dVC+iST4%RMs{C)3;~ z&eS`C%hTVc9FvbUbN1roFb=t?S)$=*V~}i#c%%TYdgG9rn{h-+?36&nalG3s^}_1H z%$~3jWe}PQ=h%mEE~Vr;*AK8nidamY5l==C~Bd$1A2%bWX4 zV>~h9aDU zM$Qkzk{!b>Oft$qjE+I;kAzfp4Bo6bqV&UaKvc)zBhE$;-7$D&tZFv*&(5^^x_K2O zo~|j(&xxGv9xn7@UZ_jy7&wjk5#opWiH<=>ssg3NiNs?hbh8JLI!o3m?D7jvvNBQc zdp7bacsv*W9we)5M73H4v50~=H@yn-i)3D5jJ{1-HWW%N3eo$ivB>J0y?F4W4*t_tyz7w|H;q4ux zo!X1Z+Z*2gvBmIG-IP`Eo*#R}^A3V{SQ|>7Y*0uwYcp)9SK1B@E{MU2E42Ayy8H~1 zjSbdvM1sVl@RyP7a=!M+D;!Gv9EfI-c#7RuVd~YJ z3BCAQ$b0kyn`N>Sn7syhXKcci^G#OH?0(3bSAi`yStYaQ`$JCM)=HCgyN%-O0Xg?{ zYYisi7eUND-P0-J=@4htK}gS~h?hdV8He1GBHm3RYH$Bn#BHBS34KOotDGtlu^wGvJQHSjd5g+Df;K7^{P zE;6SR#5WT9t5KpaQ&CM$E_jsmv={VhrR*l@g-heOu$E6u0$ z#s5VA*l8qq)1qYB?4=X{Ek^UQoBc4UI^RRB@r6)zibi_(6O~@_3a1;`G~(?7NqrdN zw+K}fJ&v%FF^Twoh|@*^ona<`E(i;>kQWo{UPSH9Fmuj^_##3*eAgwMaS+q{BeJr{ z8yI+5z6Rnq3H1x0Paw{^2xv$Eodj`jLc;@S1jI`SU0js7kE=Z4p>+H~Ffkf@qIq@C zpb@IKxt7iYk3NMw$tA7JisEa>Xp8Gji*Lw6Der>vF(}DPi{g=svBMvSoM9>_f*0}Y zJcS!g1qux>Vt{2{0^^w}jLZ6xD}}fdhn!RNjjzBSg18v3#K=!fGy0Z*YC_RExO4U- zg|~~U&d2|dytBx?0w=D8*(3qn~q+85B^*7fui_9oJ8@SjohFj z=|p#9q`47fSCjmEGxEd*t1OD&=4l-;wUT)l{{#xfS0k98O@%}-B7P1aEBtCIsC-)i z_B9#*YqIJ6s3f}~opmuWmA@CoEAW3Lo!gDgntLroD@k0tacZ*_@r@9FNvMfw5&s*a zldpxir6IN(E%0(Yeh%O=QfO-`)H@d`s(K0Xkla=1?!k$055dKl`nU=BggXvdW?Gz# zAaU)G&meY&$=Wb`7V=+-ofTwtuM?sx4%ydao!Rax$R8rsKghO0-eMxyc_!<{b`uw3 zMHYt~VY2TZrgXNuONfCuPyvepalE}%!P-wXr#uH41 z9Z(R?XvpUho7|WL7XBhHETVcDUk&j-LbFY?{bUxezeKaSCi^`Z=e1B+k3%jr6_oLN z9$RcO!?+%{*9^uXmzxSXE@F6QgBHV~u47Y~c2X3Z&G2AToR=73Yg>bXoRd93M zb#QCBFT$djxJh_qcm7*mF;ZTi@*rH_sgiw}E>(+^Bm8+|;I?r4 z!#&ZR2KOX)9^8}N2jRAKUxIszy9e&6?qRs6xj8Ga676Zi)LS+&1oWaND|X!Yy_8!fodsgxlWz4Q>b5T8Yt`n+Z4WHild7wu8G_xP9^O zCE?o;^pmT=#}za7H;9shPB-kPhBC>-)Wvxd-MSH#bTdhL1(K96eB1OCxqO_wBf1e`Gho~!w52c8QLUb#M|1iXM zE4rNc0m$?J2K&cgB3=s72olRC7XG{e#`O?APGY->zjJ>Z;*Azw*sl*uyi zHnWKT4EZ${*l3g0VfH%YcnuTtACom=b{XVbh+Si{lbP*@ygUu;+8}cwUrX#dleJ;H zeUP6J0-I#A&dkn-{4rvaP1cK;^9|(x5}V<#2~K*tB?jP-b9~4i1XI0?@>wRH{bxbx zo@$l&vAh~%j)2xPq`BHm1qCJIyCCmW6YK$#HC#{ZRme}s23u<~sMX*H$r z)Z{=lqUjLdMF?AxQ&Gi35c6`C-PBvIQj-t1EcpSrDb{IZm@IV{Rni@ju_TQcQW0H= za=$tg`4VY(Zu(4|beGEuVvBHc!B9vy7GM#jYAL)SxuU?mA1A_H2iJ0+gDc(baMRq+ z;D+2|aMMMMev4%}89xK#P*rnyL-MHt_cWXcw-hd3_3VUylo|3_DA}>I;ic5e=i$wX zT}JeLcwdA!FLp@yfze{g&9sbX!}56U%@1!s6$F&YyD1; zs=}sVsoWw;KRgUXtpWRpGX+E!wwG%vk@ly&v?6;c zSMde_MBE04Cikg)qR^v2pOM97-i3Kq$*ZcLei#~F1^AAl3bghuxFEE4{1BkOwZFyaW;Cmz)Hn$bDr02oTvb) z_-n!`6@b%dQ}lTB>zS2%p{h8UCcf~1VoA%!b;v`J(9M@1pRna);6g~a+5Z&51%7+% z*s(NcC1mtnboqBA(Z2syC9)af?+M8osfZ&K&aYtEIpC2RiQ&37Z2)mOp;`gd7vhP8 z+Ey2;eH<=cji7jtMvib6Lw`Hjw6E5tVRbe?K)*pP*u<-~q3>|1c=+966;BK3^IoYg zHByQMFS3L1+j3_HF6dIAc@)t(0kjI@&k4Oy;|#>dwTg4dJ`Y}eoCC|Ip<__6W$zl< z(b~9i;(Dp9I<$vJ_NjsIQ?VIoM$V!z#2^=F9^nBhLj46WR_Vnm#T2F-T!SNID|-M% z7{3Q*ym@IzfGL~vNiKCvWqYB{PYo`jgrpHN5>i&L4qlDKA+I7#5AzjPi74v{G==bW zgy~LWVo`N7SV;aFap&U1a#z9??s~Yka9+W`!#LzCHRv<#u(cwpZmCSGQI|69mKq^S z4`)~tNaUPEhSAz_B=qluK3qsDOpD8nQhkf1}3K>XJ!cVzK3eMly5jLHqGUGU;dpf)Z9jYqXhi)Z6pznCh(~-OQWNK2iW1Jr;1ftEl$m-R z{2KwzZ9uOQ&dE&lbQ_T#%U1kduqF+_qnRoFhW$L0@B^Jd(+L;)LRWYp5Qlz}KXk=E z06#+Jr}?;W!cpAia7f38)OD3~0$WY|!c5d=)q-s5itKUpY^CHCuv+=x7a5$dsp3?K z&m%NCQ@23f04pXz`T~(LnYvfg0duET@);1nIesaHsp?r(xBF;@*|LV)4=2JM3fFQc zz?JT7Lhfp~HjO4CxT{!lTO{kh;f`|ZfjBuPYAG6sZG z@h;u#R4Nd9Hiy10lGq0c8GSh^F@B-;QO)>eIh8hcutU{9ep#*1i$Hq(;?;qOvP#^P zo%gXhJ8v(xZC>r&yDf&i$&BlgnNNfw{q^fPf(S}%> z!{KcU{z#>%Cq$fFV_WcNjN%i4%x%Hi;sJ18PFtjga0JtkOoifQ2&v^0~x}ZNbVcWm~W^;n7_DQK*~Sf(@3kEm+BUuvYOQ zYwU8Q68lmyA`R=(*e@8 zDKh2IYpm*w0eh1Ug@k!fDOO)`$c*HK?;HvY>#h*jYzJhgQI4D?-ROyFfAZo_pBTjD+J>#GZCnHs5$S0i19xh0H zDnsG4KMChIPs})c)`U}L9GphI>qnq|airy5s47rOoJjl@QLQnpkvaSowd4wg)^PxNk_*Q$5>1ah-?%R+Kdd%{?T^7n4F8O7TGnZ28~ zxBz0^yLlN9VGF(>5x)!E?A?@E{1u4J-c5^th1l%fSgd=u*2kyzZe}b~z|7uF2lq6@ zX78rN&bJWzdpC8JPC>I^@1`^0Odzv&Q)yGZ+f=Z*MJNoTcT;95y_+)OniJmu6SH?S zSW54vXsJcJsW*{Z}T(B(@7p-v8V{2fO>#K9v9MSh%6%mQ85%!ZetmKvJ`|@0&G9o z3&Ob&4y~b3ym;)j@QI2BEi}&ZVa^Xxd;z!|Mzbg@@&u*vaTGdMSyb!mx#>`R=K_zytb$Tk?!;=>vz>L#<*`#g&k zVGG@4&IIp9m1)0WroXOn0~lAdpVFx2@rCQy)&pgq1hc@3^~M8(RJb?vF+ zl|r)is3&L@A3}wTu%4%)QkLwK(5IY$NLt86RxFMaUN~Myi&L>~@KSX033%;TA9%MR zBjkE`bE0qHl)hst7hAEB_)kA~DxU<(E1pSW{DLHv;_sAoDqWm(exyjj21Uv~ z_U>2dh)@RZSNxNzB0TT3!2N0#Cop3Jh;hHt`X557R>&w=zJ8@2{tHCiuYAObVmU+K zue=+)$}aK==PVBwSgCjcVi3-w9xn9Z<%Co2SDZ$hq8Al4Pfy&hbf_v$rnx^~n^+?4 zkF2ufzRb{y3CL2cx;V>E)ux|hrY4BLujXtA{u77%)Q8nJ??U7QZE=;KWsdZ+=o&f^ zPER17sC=I3<&nC(wxLAGFM0Ykm32!lfi6#7zDiD@P?OK+)b7YkPK-uD!tw3Oq{qTs zB(+q0Hv)0Szn$rAB~qEd&yStKxClxLL9~LUw#`vjUhgh(02jU2jXi8?N9z@hl&eB=SKm&DzXs? zkb$n~S58*=;^IIRIl?4kF^Ew`wEoMGswzUka=lmj;U7R$SL7p3-I7EV@y7qExYR7A zr-uuyRGfyXif~@^aG?)p5l*QhoJO0X7Zsas$&_a}s&(In z;H}c1*nb zRQlmDASw%e#F+`AJ4l+Jlaaa{@(E{?hYPG!+zv4a2R|UItP6d(3*nS3fYsS0^y5% zF0sE>MM&MCDA@SEfG zmT;y*zKPgbQA)gN_723^oq^6a%}7f)Eg`>@SpR_8?GW!KG$?5H2juO#fQ<;44S{$S zp^-te*CEe718h{l%z=0kp)om3U>53*+`=Jm3z}6zK7-iYfY~C5-y(Epzzog) zXOJA3)wDf5_2NffxlL&p-u_8=D8=nHvJtV%w6g#USdX>c2*2%m{ zH#cQbp8gKxZDq|mv3)q!Xt)RTMxFI|B=1ztP$qeoALHzy{}(eyNU^I~=2?S~AK zt>7(+_3kCa<%me04sVO-cqDEBL^7vNY&8CJEHR)~#T2`&tr9y^<@q(xc!0F?>yRQ} z-W-LVhWI-|1<8`q=m^9Pp@wxRA*R)dy#@bznQR;g@Ejm6`X+$@uLHUlhiqDhF2xM+ zA&B=7I^G{(8@`?s=z1c2Ims6kjWbH1O@XS_4bg7i&6ph=k36*Hr?sNJ1Nb817( zH}@HJI?)B;Pftv#3Co$BiK>>Cw1F<)&u5WTsbT0k9?jDmcTpHJFze{XSrwiIMc>f1 zCzFh)L5y*i*8c=jHSY3~7E$`)v>x8L%SW6RAbQ-D+E0xK0)AtCs_riTlC z_r)?N=(?wP6niD~Y>8Q#S7Ap~!g)`PZH^%&fce62P=Y839PBoxt) z5Z=Xok@3GrOXuRh75xE{as434$}e4r|5oXv4aDkPI&qoaSJ+uDWy3mKm5Kbu+PNPlHi;CMlvvSW&#mO}H zmRX6Z;80d+7a#WUBp)`u3ikzc zxXDe<_A*L0IZBC~!e52!$~h@U!@@q*Y9obY|5AHNA48Kk}E@|(cTJ#Q7g2^?$hd0lw(VwIk^KfFb; zVV-vYye(qmJnukwTg9e(-a+uTjos;a2g6$tdk9{-^~xdec8@*h(evQ#9oyr1hr-*x zm=Z553b=|*P`UprGztep+_8YJ#zdz=Je*Lc0GbT(BZN8!&}N8#B-AB?>KmKVtYOBmGI`pe)PQK;Vmkr zFy%$6u%@fR3Z0LAYB=QR0*ZtSOQTYVhZ7o;OrAz#A-;#u#R0Sy;?D_P58cl)taYB;=XfwnI3EhxPsSa1#}g~WF=>-WG_<5mLsqe5Qn@y8H+~eKzuWyIRSJp#QO-%^&{*!s2oW- z+|rH>#R(6CPPHkAFYvsl!E47xdfry>=EN@Yyr;vP*M2mCg?9Bo?)SXA8xe@Hg6-32%i?p<&#_inh-y%%np`y||u z`#juqcPrfE+&AH7h|-TQglg4^qscy8;I_hv9+#+`d+|5F?JA!nFnp{FtvC@Xw#W?ZCne7wL%sy|3 z{E{8c0hAXs^v0cJ89Bgt6TblHS;7}JG8X%Nj*`P4cwko?xaNUd#NTq)58l0Q++jK z2`xkxoSS|NlyYRhhOq@Wp_t_W6sd?UftTy?P%2?j_8|N};*fV!e&WZuQUW{aPP*V@ z;33(up*{~_5f-|dSN;SPXnxfc+0$G}a)q~!|y_r}KyU@8OS<1yHej`8v3^8(}J%a~*= z1Tn_PTK^eH)%ci#rA&_~{qSB8H9qzchq7FckFQ^VwBk>VRmmru6X$DOV5Q;-NQiLu zLy4^meRwwEl<_gA(WdA{#aRorS-EGX;$)h;29(#^%hP92_Q}jziScoA?Pg#tBvm-K zL1PCF*|t_|jOZ!-ktKBXYTpZg&A|C;4mP{bg;M+fLFptYuu}X#mDI-(oUzcHMZtBg zl~~N-IEAwi;ztSftd&>}*61mS-y~F7YwjX5rJ`y##35O`misAAg!>&_%l(CPMf@N9 zYluRURdm7n;)HWDL_Cu3U&|{}J(8z9lS4>ZWrQf{0bL%+pGVTfJZ z)x+eQguR=;Qbyh z@P1-T<3?N$CtymY>tU*O>p(r^G};ussCWYPg3ZdkP*t2v6Tg9l0nm5IDod`-Nz}vh z4nx9givQ#wsZRPN9n$(7`W;tJK7CWi-VYydR8|{McCCh&f0@GBISm8v=_spba=Z`b zMJ&ozRde5H1x=c|VM`3OSo68+G=;MZykZ7I+EyJ`5%VNaMSLDq?Ep(SLY+jDp_-*>!F)-J<@f5PI-D`oaD*0oPiy2!j-o%73pyU&-VN$ zz%RwXfu6qw`K^H$dHxg0F9+V_`A;H$+Q7R!|HI%Q{HcYg4W%hw{gG+pXpnc=w+Ct4+u^nI3q9`~c=PgOo_8+WcK5vV*gMkm&S%?+p7#!T+vYFzym!Kz zoxjQRE@0&yo_8UG_{{-Ur}4F8^oGy9VBj{Nsk` zWIPD3ouBV{AA&cWf4b*=glQMgyB6LW`R96Gdh;(Me}w0K3|^Uko#%ZV-n9HXJnuU8 zKJ0m)fH#!?g6Dk_-pwL^x95Kf{;eYaQ_uf2{I81qA3XmC_~+XBq4V@*Y=nP>onO!M zKLh_tJHM&te-{4q{8G>R9K31yXL;Vu@QVEYp7$kqt^DDhcME(ne}d=T2Je(9Q;ISc zLh>$-ny-;Q-oe*tr}czT5U>v>D-m1^!79<>P$~6O+=pX zYcoozm|i9kRU?t0kX)1FPQZz9r@*za=a{88X1NPldLK#Mr{U7$3Ho{S#2Ab|s$0z% z>}QpI9iZwTgZ-h~-Psp4#h@iRXgmUY8ST5H6f{5OaLS zPQFta#V-aj_qu3{#Sn7=f91_%tO#4EJ~O@>+}!J;%;NIa)V(fR>_BYpbz!mI>vA=i zxs%U~Wg7+82sv583wRM79K8Tx?sZXOhi2>ky)No1or{4oiV%>olTT;B-9X(4>79Hk zZECN}`(Sg48GBunS;}4)Wy15ucsAyZ=3Wl`6T4z&{fSGcZdVM~oZzmQGM>6|+RR-sEEW~c zZ9-g&1G{2$Y9pPvE>+Bhl;`3ZezFUM=kK*vb;2XJm&#;%x= zoRoO}?YcSYT`?+!PB)0TacxaY%(K`+H?GOxTqX6c7?m1TB{zU^l{9w6=-3VcnY&_? z8QrP$u9&mE#fdszDJ1Ke-W78zRJaK1c`6YVdU6I>o_+)yv(BaE-iqresn`8ftzep5IxTIr5O=%iA{5*{oJlty zui)V%Pj<_XWh}y{t`UyxlaJv}EC=2dkHFg(UYiF)w3s9N!JAV|R`Sez9tf?XdSH{O zO$Pb{e9K|~1`c_4exm%>sLJ#{#K#DolTQX5h(3A#VQO%qiMj*`ayf+5RrB8IGo zYYo{BR}T3QE;Ks+LmK}UxaZNT zApd~Q59ae?(zZ05|B)a49P%^htBrrDUR!Tp7H;7tc_7Ue<5WT`Y z>QNLA{#4T;A3m$<;Q}iapNE9t%|d)-Qm-(l;)@8UJn7&x+7!L0c+4{^_d->1GR>X; zSmH^?9AuRxD>DWz!U?a_r85IXib*$qL4C0I3EM? zl%Rh`Vi8KCqd={XLx~K`@IHbPVWd9-))9;sK!;@{7C^P>2%yT21MDv&7Mjf}%?g`x~E z{1JbMP8!Oq36kPBSlSxR)GA#-ZgdM@*$;f$9H-THID^u-WZ61993U89qtH}z+O2YXNVywao zxhv6xlqDtB<}b}wm4b)lx(v4mPAu1jo92!rp?d{f+r0s9j(aoQB6lI&&G=L{{!Ovm z4fIdCAL3uO`xRW=3PkBVL~6CmMS4R$YEeC_-!OYPP7<$fOoc}_py%}5!H{NT5nYui zTLSbg;V5CA`6aRb#7(;^DCohpDd@%xv&Z8k5%hd`WYa{@q#0SMf_@kXuTtYR>qO8= zY~K$hwfP(~s4}S8a;XeW8;7=l_oj=dkl{)-6MdM&Q=;b#k^MLTUaW*FkHfagO{7Ux zhfNeO{(ypd+prTIIrM{uNIe6p_zJ3g`#B{4KqIA)UgXFVyMc0VehM#X)J43dr^2<$ zLpAd#?fRPtt(zjQ>SlkuMiHF-eLYp+r*P=7%BP5m{&)C9#XJvZ`7lM`P3iPE5sq>yQf7ZFvc)|JDrNSk zbx^d{mD!jM-m=0uu2`Af68C*`G?GGZA7v`%A3w zum!hD5q})qoc*cPs42m>VE);kj;#Pc?_|#Yl$kO6o8bNaQys4qR5w6*sb_!dp`vGh zUJt9W!#8dC*!T6RH}VZl$?M*dfVjWpTNy$JPUa;_m~IyrO5p_oMcIT&z&*O^8~mQ#S2_p!vsIOH^wCEj`v z@!tWP_JzW1LqWt#AX-D>MTXe^<-@1-cZQqSq79m!Wo;R3B=P7`|}k zi+Jc<)Fd48aWfRs!WStZzlzvX4H9D|ZFUpHPY`<6FcZ$p5b?AB=NnMnXJm z)LgDqF+^wCTp_M|0hvX$NW=##n38j zhOit{i({m;^988NOVt=($1g=*wS#_@sb5{SPu6&D07kX{yh4XD)C{A#YX9G1h)$Tn z;*ghC9|pG?Ha8-E8V31j_VSv5(bv?}ID6YrvB-&}5#jt7c#H2_$h^7j&*&dyU~b!n zib{n4fFduby^*M89hhW93sdH{TE88nYHmxxa-l2zunVH*wm#yF2hnp|$}}=kJs0`# zO;8UPSgE)x5+a;q9xn9Z-h@-;wwy+rq8Akd8tF*OJu?+2(_H!zu^L=|gW#>wPSD0q z`J3_2%QmX@!E77KnG;?FMPIg!V3M&3#8?v0`X557vWM7VLdmfMXQyxW@)>f;vt_cC@G5)jPTg_JKMysk+gWAA2?u?NJ+ zSgnuWde9k5!E(kb{csdxRh6+m;w5Cgu^;^9IcevEKR z#&Q~MiXI=}K*z9p^uTu$101+ILAAQLf-h2S;*uQ&Uqd#uu^eLBm_I}+G^`UAFd#rQplV}o1zyLXW(w5 z3t5M%3Ylr{ms=8rd=9e8lJD0~j{b&1!lrxcrzR*dTCw}RfNP39tgH^g;M1v*xri%OX#FM}h9H-$!b(hB7nT59am2l5+;W#oAyVHLTE-`~m- zdvHk1OYx`EL^&p$Pa)4b9jtD^tP#W)5-JFo#iv8Qg;-OQ@hhb9osf$d*hwa%TcwEC zgS-o|wn64Xej~ARgNgVeh_;gW3{&j915plYvh0zUxC^UX;~}n70LJa~>^!fU>vl@@ zNcN_{bOx220bOpVeMqXuZuQgc=E=7CLbYx4H7Z>ZUJpgzo$W0q86SZdZBy%u6TG%b z!E%`>{csZy)i!;^=>o!aJ>Q~wM@Fj7l215Sd$_=d_aFx03_^`(>p~wsKscpsavE)l zUR1p3nU#BHDo&=kH*8C^P5fXt+UCv%$qx7gNI1r~8>FUJ)w@f8xp>}d;9aRM9tui+ zzyt5ClslqiHY8j;AEpegH{+5Mk3lIA{TTEU$h$T~*T0)G$%=f=p*UGBbRiipVSK|V zUJhhF2Gtg0A=ZyUy-SF&1!sbYuK_n7gDSK5UWm=dpjw=HqLuO(l*RfnXfH7HF{l~K z3NZ6As1EK!h|R~KO6+8xgeO3aaPeozM6*y=>2wFmC;~EG!q6Eo0f^T;^h+2jZEDTq zDKK91FkZq?W+{(Bl?m6j_>V9#AA=e!TInk2S*6A3qH*_} ziw@7bd-B>tV95R#mvHzYDEeCHF(w%wfEX=Q>!+ROwNP(b7*YD+lR;Dq^%18ph;E@? z53DYMd{~q8aDkPI!^^0J{_EjFAFe|vxdv4w6q zFM^vbN14U{gxG93THLxMwdJr_x17mfX3H^S*#l;_935PPHmNN~iJdBl{VhjbrLzdg z-*R*Y>;f`dj!K(qIdw50^0ypimeO*R36G)TRWLDIj=@q|j*_bZ)NF6uHA?C`ovH#% zlLM&ICKza0Ra4-GG;7WHLArUe% z&7Lvv7yz$6E`}dF3=%sImXO~{?l`!c{4%-YU@7_2k~aN1+wT_wh%n`Z^4#CoWEQOTNXg(R?7@OfW9FV?d*=K)jjY z`T+VJh+pu(Ir)OWwu*JY7d3Fmxyj803Kic-;+04}-u)j#Df7KlDWaD_x`edOMNY57 z$^XfmeiI4v=ky$v(?@~)IjvFCvS3bY)C0($(;8g`q;t9e3#okn)@T!uKc^K+$>}?j zIjugbTe=2@xK|v;Kkr_#7)mm5uUN$w6@E1yxL2%UlJO^qaj($&&C9)e1qI7VR{G&e z5OuHc5oZ#JzE{wKF&U{wOFrRj@Nj{Zil0CX!f92ZtqXnlIl?LT3QnU<(Tj@vJhO7o zOvTAG_iU_=@$yc2dd)blLw;e5=87QU^nTSKH9;F+qV$dh=F!}D4ZJJWqd5vn9^ld3 zvSkQWl-vagkLC^u9-Mzo=L52;oX*sBMRVOaPK4VB zE?y#nE8T10rnxiWhTJ7^)A1(F-CfcB%WLyu&*P-;ZuAH1^XNgzx9|=n@00M_v0B~m zl^pUu1#eDldv`nse+S;D;mwQPc$Ou4ya(?Fc#C3fP}`qt!635{kSaud95V}F6RA^I%56>TUzastmg9$t>5+mt4oQesp5HpOaFTsFmEQ@CoL zNnr?OKKp-T&g-Iv(TZw~IDB86NlU?{@G>QNO>XpWl)@o8-<%t*jkMQCp2@wr<>{q3 z`9Ild4MM{Foz^Lo>%v(8S=?zG-R8FCMx(ak{qPD`Pb zPAkUsfo^Xi`HAb&u`srxZNT2fnLLdA{tYMpC-b}hnZf+-qw>2F$e-UD%>eS}w?-R) z{Q0fX4?sG<&p>nG{MM*5nyWv*6-vo(*U0aQQ*^&qdJ>GS=wPt9IFo-Nzc=9I|73pe zLBjm?dz{Me>>k1V)~Eu=pWhl?0p!nbjaCEc{C)~O6X&-^e*pROTcMQvzQ)M!#K*Eq zKZCIqodi~n`XOu8FAojJi7l_M6}uWIOF`rVwa{mue*?T$F;O{%cHUZ%m3*Qq9|5?Z6X0wGIzSe;CqEsa z(QgpfKO1Onz$zc&j)dj~tj>h^VnXu+R+mA%fY2R&tN1+-zfNd@k#P0<@y=ez)6M}~ z=r?m}LfnDSB0q}vfcQE>i-RG~f_ww9C4MvKWr%+zbaw!y<9^r@hrB0%iXk3GXjuS_ zg?KTcm9?lsaN(;AR>io=Ox}EGi1>X_=ULS108{t1cPP9T^{Yg08c__&)89L*2e0Ke zhAZ7u2)VSy$QIGZ5p0u6h)=B_eF^6kbY5IPx(Day(Ro?@=yy1uNatPZb04yV&d;fT zZhDPAG!A)DjYH_cygY*OfEtI;BYOE4ylNam59{Soc-1(B9^1>m;Z@@hdVnwgfme+~ zKEk7Q`7gX`9P%xBkHKq27iu0RljX3<|3kn=((o#gzkjB#}$^GhcIh;f1gX%{MA%C$i&c`B;KdhpcVvaS8 z{f(2eL1cO%lX){-lv#amyoKn#(Goy>BssT};{`Y8!_3?@7hwP+Y$Ripxone$Deg z6n}zZivhTf`$+LPpW=MVsX^_)N0ZJ&`P7|4k6&`-n6KgMZ9`cnAEiA8ItN5);Xvd> z>HFuC+jbb-^7I$*FY)eB!5uIO{`T-w9H8?)RCxi5S)5-kvZHC3VmXOFW9s{Sg`QK7GZ^ecJaeWt5~vdX;{ zeqAMoK+BQ`j4Cl4lCD%G4rbCuX)5=~DJsYbKwKpbWm2*T=_*0N$irME+OTfPB1pJO z{LIhJ>D^mQuG8yXl&lhbX@M%ygYCo3q3Ej;y_sa31!7bQt$#73s!DiCizxl@tstsO z_=xiWh^`V|7OCPPA3hQ8;Q}ia4@5$QQ#@K*7y9rB!YNgP(`Zxlcq!L2EBDM)oJ^BN zQ<@Jwt8@an<>_Z%jQstN%?8|u(`Ez982~l^W`nVuYtGd`{>=s&%>~k%4HD0s6pF6} zGB+D&i)|45HybdrujQ=y7+h~Q@P+6c0n(cdQjvW`UC0OOJQ;LDips8$jn}C zaXZBR>}6!{<2<+zTxYK@MCT7 zn7xebnurZQpA4?E*B7EQ3rJ^gDzfXa=@xK*_Nt&8GCvIN&t8L@+1rG#JSBTsq+-gY z=ympfdc85)p>Lp9Guk_LW0za#$ST>O{g<*3kO=x`y^G33Hc7EzG9=>z6YZ z;F67B&RjxX^~;&dar(db<;;hnrk__)ST_H1CIus$)`*waC5>Ose4Nzr^QS=imov$V ztExt8f&9Om$w+;1DE=e3`OBG#b=!|oR_4_1g-)L#;p?x;xsR&L^H{;ciEvxO zwcHMH>GL>mKS1{3+|cm2${XiHNO<&GBX`*ks_RfANnQ_e+8|?ju%4NF;~G_5YOwC~ z2jLNZRxYV>L2e)wQE~+kkJ_{8-Fl^uQTxA$%A3ehU@|ajpUL*&+W6-iwa;OaQHp=Y zs9oz1fmDs!y);IYet0s78nyd~vm8W^+EcHaeE9aJhYPG!ycj?@s~$;=+Eejb!YQM6 zPNPlHi;8q)3`bh-g{tzJX>Mc0th=)Y4^mdWY4PtV6V>nLlt6C2o3jcCjcNqMoMFaW zZEG0C7XX>>=4gwp5bJkyybFl11t$n!S_U`Y%~59YmJeAe@8)Rnc@Uc)_h7MpH)jQy z`EHIG%TE+sBh*CwX(1ili4Wre1&KRzi-;((GX!G)yE*DAodrPtcXM26Myk|`e}kU9h=G!eV%ELR z5ZMc0AmTNyz!v~(Bm9X0R?!OVv|L0tC8V3S`hlQ|N`PJjrlx|DaR65mm`0)TTBk8C$%Qleb15Fi z0YzG@#wA#Z4Z&KGpC(}^^AMC-o;*FoKVnTg#$;cVrHGA&oQt*}ymoB7=RFtRoYrI| zTXP9nkx52LPa#mOijL*NnGMlq61NL^+vQZXaCSk;x8n{Ws&|yk$W#hU6mtX>MmY8? zt{%U@gsVr#08=(yNG?^HL_8Z6uSX_oQ&&T*V=n`{hAL)vubidYGN-;rHv@<(+c~Lq zs$wYsSGHcMpyWvau57(2GPAPn0O873=_8`kx?82#g+tmc^>2Z8&g+N-+btE;ACfaKo8wW2n7kM+h zIkD?K?=A4=#b$cmTj4Dl{s6qRbRcJ9CvFCw-V9&wNoGNE97$gCB)375PLkc8WHuzI zAT5S}&l1Rt(62$bS1=+4yXsWKCjP#a?Kfvdt zgLi4>eWWF#Oyjk8N_9i*ZC+UXB#67?kOK{|eh}Ih^2>=0^(Q}m9mLBCT^KZ52l;2j zu59LwcWf$sQOr4ht!eQN$>T?$&24BxfK}AmrEC3UFEri7HUr>Ve?uxLDFxtKKZQaw zYke;euJu#>WF*Kf&h?X_^BPSP`n3Nb2g zD^9Dj@WG{czajXSVOM@J43K)U%ALdElwwa-<(Fi@XS+tiOB)fD!?9cVKFJ6MbZgI} zPl!&{3wLWPCuX# zbT*RCD#u*}=fQ+Cjwr=dIf>2~+(c)+M?=QW0`gJ>l>{p3i#(MNl8n#R(;20zl9SCA zw0EZRO#*Z_@_jm6eJNz@kay&MlHGk7Wb_4}N@`}6|B{T(M%sVkj6Rl8$qso(7LaVh zcziwj8oa%5(L^}bx#>61zvI?eqp9WZCQt5s==5)a+0-8p4aP~7B#SbUIT*H-#>TSY zNBF9t&v4BH+K^^GY)BH%FmDwSPy>^(x?9RawedeMdreN!JJjHtiowUs%MnQ?R{%J>`FG)BcJr5_b zS3ug5Fhs)GxA0CPZ#sMbgm*W2k0UQ;VCmaAq`fk>3nwolwb>s@GTh^N_rYt&K85#k zGW;0c91(4Yv_3{@y;q)_et^R`Ap6fFje}%AAla*x9>CN6Djpxe7qRLKA+NG-~dbn?`L- z$lKH@-*t5Ds)hElWY`@{4YIT;+q8Kn6Vg@Ktig^E#u?SC85%=OjV*H$*)h~F*Gbz) zd4GWc@lz@g^~9%PvPY&pb`%W$}$8Ywx}Ggq`Kquip^JOnP(HpD_*Mj{@$lZ`C|4BRyh+l}vTp#-LFK=sz zl~$}f{P_CCz#k1JzBID0h4TOQdaIW00ofLmeI%G@ywkEav&h#g%r`OA;BQozSK@i# zzvDmiP5;P|`7;sOrSTnpT#dZ*4ZhQltC2U`;P3cxJ+gtf#*^cj@B498elak?KdT5& z&5XE!G?EAXlC)GcUE%{H^j$?lR-z%EeU{=5`Ei+kRh@f#qtZnhqHwY{kG`F>n7Q58QC0wOfvxI$is8)(F@s8HNf#pjIVmB*E| z5`P+@t11-oRJO|p+RlL)>8qK|Rm)aRy4VN}s!+(2T_rpmDb=1(p`>cSn;`Ti{xc^X z*E%b)%?RCGQBGE(F`g!rOm3|R7wfIWbO`Omf9AB~mZWzTpBc&7|19b4wD>-q`+djP z@$}ryM*RMN7Pk^RjN}8ym-IAxosYF03;p8KhY~2Sywyl9J-(#J;%|-kQ~xY(CAxp2 zO;~<>Nsq-Vjrf}5iz{Dg`YB!j{xW)ST?X}2E5F^x%*1*+9s|jvlzcUVS6LoODVTv( zya7UdYh~sJ&y;C%=Cu-4KEw4d{xi2`unkffScyx)=A*NjZHwPjnHR)A-5xR1s^byUmRD`N_=gE_WOl6lyy$czQASQt1#?q zzmUhUiALxLzmVUstw!?baV0VJ?$>4h=oj)BHUL7Ot%qSh`-MD)tu{hd*yj>{!>WC$ zvkM+q(n?%ugfjd>9>ZRMP}T+*R>?2qF|5j0TBy2T$ZyyHBU$6Pl2&4s5vu7I@)#ER z8aLTqhhe#XA&+5K7@-D!A-`cS8_9;pm9!Ekexu7g%`fCJY%qkTz5&DX{X!nY-ZVlj z{X%}jPC1~nYjs>ny!68ewe|~n40{Vg?bgAtc42dKKwXCFmEfdrHGZKVcjpl;ImAd_ z^v{ysHDkTexzw-28spspxQ8#+_4VVa(v@UiBiZktCH0tp3gUm@KXY8zcRf*D`8#~$ z691VuhGo)ISCWa5V67*6qF2h9j zEee)Q`~mv-&wR(Pf50HSeflLO|HY>p@t?WZuk)}$KJw`l{TE2PqtN*@RRyc$OmJqC zd&pE-IZM%lV17&B=ajhZ8e6=oH!1^dMR0m}72oTRLx#$XF{vJbL5 z;Pllhdeq=We*8hfV?X2bnE1~;!-I3TVJrN8gBSa8m4DS=aF+o8nO%IiRdl0)F7iRz zw4(+u_2a7O>#!f%jQ`BODcmaB4^AiaPG-LpSNTK^PZh`GQZL7@AFzJg1cGO#mqGZt zjLhGHrIqkZONjJ=U}<&GwMZWfm!1SV%W5@oX3)xPDn}fHe_e%_(W#>mo_FGN$+Lpi zBlyoeU>xyU-U;apR+cIrPwZUw1O`}UGFW^gh?nr6*@K7S!RSvoGspXlcaZfY{(E}a zLu9tY$@Uq50$JaLORfR&B>uB1M|fob_!uc56*_ z8lQDET=F3fl_ZC%<#VuamTXo+{G_GG=KF9_on@Bw0S0_lbvCLhj3uiQOD+e@W2&s; z2u+|!TY6u~LIA(vKkKYWXD^Vb`xI{J;6H1rDL<5|f*7EjAo05qTz*_Z@rJ~6Pb0VG z_}^n}2uT*olEg`b`2S%FrlN*#1oSiEPmQ5z+NZ40@ctB>(iS(`g8IiSocVKN%sR~1 z6|9#2%E%DMJAi};wxeM88UeYbk`>{b=?{tEPmxxCu-n4&+pB1Zi;tCvAiI2KS*23r zY-!s-)FxynkhEe6xS#a)Z;@Cw_&f^B`aP03!{}A3G$37Xi0IL6#nfYwSS{%BxGn3C zNMa&l@rz4@H=P~3K$l4Ta!$yqpTPtGuR(xr&7&-L{I|u_=KZo25+?G~@ zCq~nF3oGl_5X7Heh}+^6|D|cbl8!m;oPfoS(c)JjnG%0~ofcoySc|v8L)#wlCy-2u z&$L4-_qByuJik|(_#h-x;-{RZ#qT{;i=T;yYCXBHKr$u%VGk|ds)-gq(mGANX&bNj z^r3$7g?Pr*lRKYvP38XLSS|j>3p)1|MQP&SA(;{n&(h*ya61WSjU6*~_z+bqnS zkvh2TcrS=RBqP}G&}o)DTpWpTc_~>1{wEZQ25*8qhiDg$RV&5?hj%R_m4fn{7!DD+ zwfqaSvSLdh-XHUA&<`$Vu{av-`~GEMXaTc87WI|Hp$&?Z1Fo`=?9dy#>(RvWMdI%;n* zkkTrCoEod}|BIa}$6kjl(frtC)C49jP#Z+6skdXHe^Df*rOJ>FT(6BoAGUsmRqAD* z@gfMSXN~4ZphB&q&w}nt#poC@x1>He_mDf>R8k|c2@sI^z0@vwz(|cW^^M*x`mxD~ zWH#?(i=phjp}bJcLhGr1tVs%1or*Y+HQvtPMkr;@WHIM%WzGP|h&lI~){816cAqh4 zf?e{2ky>CHGP+2a!&|Uo&P}#7SDHD>r)dthTj3jCfRWj+U(WmCN1&Fy3(aEghW{Oi zF9rS=`Tcm`JeMv{H_hG@e-_A(MEV1JY6dBHrTwmiTg2rs3zFFxtU$59MlJF-rUTt5@6d%o2W`B?gqr0o7pFngWdte zJwkT%a!~eKb?Y$u#DIILuQTigh_?>2bMf_WZ&|ixI=fkbU31IVHQg(hh=t8i0lA7Htz#jEfwsoz!Ycu5l%?tN0V}^KiJEeMWh# z1^Aq5vO9S(dL({h0gT7T+1&&2I^N=Ju0v93U30T%%HEN99tu23&h8W7g9&1cw4X;l z@f!qqP?LRmz&%FNLeQ}ioq!2`Z8;pBtaB2{sYY_xKTCQ`-)eNm_;olqaF&f@XDR(A zKhE}4IVs8RM)H<_mJ}T;F&E-I)6SmZZ%{Us7JA^wW^5f%5T8YgN%GvX90pMBO@QxK z0A>N;bW>xGo(t{fEI|T!hkTWGkl;#I;{&E?13|0G<=}G`sPPfghA&S5D+8Z^t5j>)m-19Z7?VFp?LTwvt zVVJj-;X@32g^PbclvUkxBvSF!R3OGf3%Q!A!K-F*Bq=i3zlt9fA}l5sk&yRn@NWIT?` zdlDn^HsIH}Edy3z+X!Dx8}H6EeneH+4$tz}EBO}Jmmh3IvVDYHwj-Y+w_5Ed^AaAB z1)_s+0gc~e2ultqHOszZ4w_c+<%rVo2SY*g`+KsmN0Xmu`Ih>rQsMB(jm+6C!WO;6 zID?Py<4S*>!AJUWWzYOKVfq+PxmNLCP~onmaJ+|Yvvh0ZIot7*Gi<#Jr$o#KEfAeV z!>r=zz(%b`cK8A*%@nqMPcv5IEnxH5N^>F~;s`Z`TRE3Q`(Z#ap0e~nix;+uw5mTR zXcb;A`Q-4>fCAU6wzZkYbI@l#!>{rsn%lhOLC)NHLGT? zLx{^@$nXlI@a6C(RpY1!ZY5f;P%EJLR{Pgkcii~VA97@o8tS{1CBF`MeRvx(!+V-| zB_9xxoy^_pkOf#oUJC=3)9Ms#Q_Je$K!!(fg&Qa%&k=Y^>2N3DJuKyQ!eW~jJ_tzq z_YK0*H!0ZO%@X=Hd?R2D#ed$$*?(LZ{?Zhp^kx zkwZ4=4skoMU86?mkd5H~V~6C?GwsF*t&+bXtUDx5HX7aor*(+%%XJ8gR4P{A^Z(;^ zNNZ#U`=vufq&;)DIy`7ZQXP_lZE9H^zK4vjLp-H)DBfJIL%i^PfPEd3f^C~6^!*Al z6?BNl64fDRZmFGnUmS@<}vuJ_U;q=e7$XA^DWa3J}dYr6M5q?$3bLm_5jp+k>4uSKNc` zwz3C1BJ}m30=~zHwrizO(}N!L>=bHxFqNq-Xy3O(LDPdABCuX&Iv)H-&!YuahjAHN zB-Mi{SP!h0;h?_N&?TwM1?)*u|)M?X{!o*FePW@@K%uYAa4ap4|0E3z6Vn_U`yF6 z{OU7kj=Hafa=2^V{aV0k^C1HKeE1}6CFP=_tM1o~8hVng@S@=qxQn`Ih;cI3yV{a_ zF(mZ`1SPQIRd4}uCXw_D2w_!l0ipPvp^$z7q4=`iB;H4vvdRvR^ipL8q8`0Ob&O%b zNBD82-_777{doBc2+7wfz7;Co3kX#lOSeY82CUo##HCW@;@^OYkLU{sVcTP|dB=4S zI#foj=K?~hx%-k<6ZfSq8aN57iw0FX)9m4A(2>%^%+}k(|1~{~pAE~%&A3Gq754B- zxRdT-4t3MRi?CtUJxqy;d-z8p={+p03VK-a|AIn#4=cWG@e=l%ZVy*uLvkbK(Mz;7 z_=t!PSNhi)e54;Q-@}rxRs1MaygjUnWA4_-_kfk_;cOaa6^F0~_x7-`?VFZL4+Hb} zuu_xjFm`6EDu1PVm_uCkuqvHt_V9(gvf~(Lwy7TO6>frys6gb)h&-Uv35i^x&IOe< zD$E0fdO)+{{B7qGXmKPkgJblEd+)+T+#F|@GeJC!3&!Rj1OUY@Przibn(qnpyMDKN zgHv8ukrGike^rpc@D$oSBI8UoSmrjRti4meT@(E z<2#8L?*z^sX+BkUP+FH+S)+O9ZLsY0&^-4`U4{he)omqy-uk0=Vd-!wa577_6lZmc zV^3u^ioM3ezKiUV1JD=C*9GpTJ`9(9lvc?V?`e3W4;JmB4*-kZ+dLUFA1fyV+o!A1 zEMEI-g?|$JmqmC#m33+$9HrotNUvku4HUq&77(~3bgrJDL~ko^K**h75v4+ z9zp%Y3h0ZGq12rQl|M_f64_`1z8=1L<-iygi@&HUC^6DN(G)a+GL|^syMV16)?*JS z^+17DH{27|4z##*%n&|HCSLs`IqA;=%xkHi1vn24B?n<7%(DQ!!t!iEo#@>K= zgvl*WOz}R#G!#PKN0^iV<@F;>+ach8gh{NnickAMU51!Pm{PiG*Uy3GeT1o3_{W?1 zY)Y_F4mbPXBN5|MJ6rHt5-{0*laXb)_WKc)!Xsc^aY3isj}P}q`(3aGgxwlREA}hI zO#79BZ`!XNE;U52TBWPf^@fRFKggQ)y8^UnzxB}5kAS)5i7DRpJL{|T_EQ3s*X_3r z0{-?BtF7V-zD{qyl&&QW4RpZXWuPVs>h&p_Nj(y>3>kT~{$rq{_D%ySt>Si{sqt?f36XN_1hQ29 zE{}xpYEK>s8T1Kycbi-mj-ItSsHfhs^FT(GX74;yio@4FHUfFHy6r2U2EE!EO^v~F z9qrXS2IK69im5mH!149u+P$1!r!%34Rp953*sS`o6z+{Gcr4{l@xqd`_Tf_%c<2O= zrRau^DkSEPSv;1q!bpuYZ5|CulgHcjD8G8 zdrVXzvFZ?zA&19cel}7IjPpcKQq^Zan8#pPOj`B5kHK^d@5JzMw;46sV?9yZj7=c_ z#WrIh3$!0Yn7++W{HMuJtT?FG$*V)pQ5=6!g}*5H4c}>em>++Qc=6l7z1s|>%dGS= zEsc++jef(rV4E?mL%D6n6qcN}%@B?~gV}hu8HzoR?2?Y(YRlFI7Em9Cd$dZ{8hE1* z7VV-q>h0NPC{5<$-)1QLYlW{B`_(psJhjbO1+MIMRu9rP3}$Q(XHMR2hOpDN8RZ1k zHbb#*q<*5-0d1sbo1t))W+iR{uD2O9Njgszl=#>{(SQq0qG{f31`*FT1D%B4^ld6Q zKIHCNg`0|w;ZqNJd~`KtA?>5rb^KR8`Uh>Y1H6Nyw#a%btoT*PPdxa8>!VpMmriF7pueQ~sN!Eo ze&X$)T^}7radx%BM+v^>7uQF9cp35HykFCOROwPw`=~76@X^^)7x?JgFdj>kay@mq z)`=yj&7;Dx&t*1VA60CJ?2=~xbA7Zo^I7s^M;Q$9KnTs4n2)HdWZwohkHULO^9nva$fR6eTMZK$8vgWUZ-s&JNOCC>lJ z^--E6ou>*)ykekez=b-{G_Q{mN%PTm=xyIT+6iu#?xWs|vyR~@zd^-+-LzRsO1uC} z@B8^+yx8~A77%tbB(2zXh?#x=SKym{f9GTFzQ1p}-qoUa5VB_9&$|O=-@gQUdf)Gs zC#HD!{gr=D-}fs4%IkgqPzd<<{bIFMyd4m4-xU(*G)WPm+L0} zQp0oIRQN{)?e`NK2`>cs(``TgphMcP2hJ7)_An%^*l!Rs?bjcC(|!-yL37>oK)T*y z(Yq3|rv0u4ZQ9SN95n6cmM5lo+b74pM;HH|V9<46eL2PFQ!2Qe`U^$`tdf?0yO&eC{i6zrxkDM3Q;!>|k)|u6A?b;j zJ8*G1#gfvlC%l(aH{!y{dpV_A(|cJY<*LgmX->H;8u#G$syVe;t-Jh`o{wtG=$!+#bVN$ zBmMHKK~>!3GN-sB;Xis?aBA0owJli00_`OT)3*hRzmoh!I7_`P6sNeWDUQFW!q*A@ zroo5#@lC{wPpyu&_MGA>U1p`X1=5Mw7F;ZK!M5P5uI07`w?jOATOb_!E@tE17AW?8 zWS87_g0_5J;34Y6aF13=BvZp1eXwX3O#$rL7AQ^T*Oyluiqd(iphP{i zjzH0X3r(eI-faQvk+v-ugx>aT3pmdHXOtJ9MO;Q*5=nNc<`?jv% zO5-VKTrDOD$3DWI@cO7?|4MdA@5A@fULUZ(SA6(yYX| z8m^CWew3C|1tpFcC>n5~FDc{oQPv~PM<=4UeV12URnvWxoYdvjn{WWvM_#r7s&px; zeN+}P_~v@zWN$07861xo)4Y<%*G|lUyMACe;9(vO^k8+=p?xX3KSDjAw z_$a^Yt9`Wk#sA7jU!zU-o2*Wnk1GBSspi4@u8+P)adx%BKM;I(1J_4=_1R=;iI#pF7VM^Fy7~*i&=7-j|#_rn%Q`LRIy(qyQFPB*GFHbJ`DG0m25Ha z#y~nO+C_a(Z;y{EO$z#bRM}rE{JYq%=27yLkM=&r_~;C6!<~%ndCbY{qry(}(Q<;y zM-_V^^%FagyMG>4I7`E=wYsj4(j@6TRZwDsfuaEydW@!deUwO=kM=`v`+Sra2mj=w z&%*)A9RVDWk`iA6(?@BuW97!v77-HrUc0Bmz5_U4aeV}jsU6!tQo#>T8 z)?C8!@iKD>d-AF7C9GSXnBu*JT?--aty3jHd3_0c$!X;;VZ~~z_(wqABY>2ydRWVU z3EL~&Y=b@m;4@ls1i;rRc#Z(>Y*az}O=lzFaiPX;`wfDYwBI*`?2$-Xu{%JU_WLhr z(|#uwx$XB*y52I;`x&yP{eA~++HVi^^bv|%o|xiozx!IJx1SQAyl%hC+mvrVvDzxG z+cv%ZQo2?S8_3^&I06`#A5=#Gt4n3xsJFe3#EF6UvVp#J`X?Z1oR?4;v|G;U8aiO- zL0X{o3fcll-#V>&NxIfe&Dbar5SCAetipDaYP|ELFeD5da_3lOurX@lg5^ zfIJ(ijsWCg#;DSlBY=J=%C`C;C(jXpszt02UW$sRg$7vFNj^IoL1e2!O?;HAngp zz-Jgm?$&iQ{6}vK8ejUawgs)X!|(0(2-CL(ir<<1#DI?OwxAou@fTJ2MS}M&akm9N z{8Hk@KLht}U6n3H^|nAd5!-^ScB~7w1qWcfZ(DE*OHSJs2*=K2Hr{Q4Vi%HK(xQXA zEr?SehI_P1zBBN~KsqeiMUNM!Z3~np1^wFsWq+-3QtVgT0`k?CP)<;73l#fA>L<=Sqx`l&;VjKc909Jkt{jTed8(kqUF|g#4Y*Kkn&#aW zupVjKfnuZ!!WK71|l;&JDt`>4{TsP<8rV&S9jNL}Egv-+3w(TOZM%}0e}-@@1qK5X;$JGaP6ahf|IsG<7^{=! zql%yLHmmuM|(^#X0#y1)D*J1NSBU+}N6Aw@`V+XyM_<)8yusMs%$&SFD(o~LEhngaRI%Toequql@;<6? zmS!c2&v$*4CP~Ywf)bw@C>n5~Jv7bhqeRkt^kVe3Zyx17Bi%>Sj{pwB0o=9z3hdIf zkDhqtzw*(ZbUOPI`b(ORD*jdECz|!qjeK?J8j7>46@ICjEZRj^mZtfr(qukU*|BsW$T4ZwHhd?R>@~1HRxlBuBozv*mZ3s8r)r?Ay-K>beu%P z?~rK3GZKw_SE3sZOEkLbPO6V>D$)3^5>2>PqMOD^G;z8_WsgZTX{AJy|0B`OpG$Ph zVTo=H?qX(BPLyccX%gLbhD0-ZNOb#LiDo`0(X1^J-T8?`vwxImPS!ijWnL4B?m1hc zdoPn{{tSs0ERyKH*BQ0D?>mX^|5Ks|y38f>!K6eF@f&R8+da&0xs7l4NDpB?x@jIo z7TNDIdc1~2Pn;srllc-YNl3J`qeRQPO7v7OiIxwLXvJWOo*5(2vo}k$a+XBT&zES` zV-mfvT%y&B?q+#w-oBU7OKXJr@*9jgo+EwRvGd!KI`^Uxeu-7c5t z{4$9ySSV5V)e>F!zC;)OAd!=~o9Y+0kf=v@iF#fmQLm{I^?ppE(sdGD@_|Hs`J00A z9s6a!&!~SBMxBOqzMs+cM;>4_RLt!(yrW7FOcZwt0lT+ibS{GC()GWC7Q~| z^v8Fa_Fsu^%l&|<>8&N2(OaV1ZV-%^xJu0}~`#c)LUoKP=HBFG}?IE{UEvAkmY5O0*cSqqD}Jb4`In*PboW zb^Rn7JW8S=vn0CyafybmlW5p`5)D5j(TMOq<}&gWiEd~u(Wr|g8htIJb35K5QON>{ z&gAphy-T8QizPaLy+jx6 zk*NFk5?xsJ6XtSJeTkg55?$;_)MGHC?xQA4G+Laf` z(F0p0dhlC`7Do0{{h>UG9xjpSk^T}rI!U6(?vrTI3W*-yEYTC+Nc3dnOR6tERiY(l zOSJSViI&|h(Njw$diqs~mVYeKiojRYd*)P$o;_Ql=dO`x)f|alctoNXUy|shT@tRCZ+FaAppsc)s`@nwsphuE8W2Zc`(2aR9O!Do@P`d5w*ng{72IQqJ} zGBzo#E`AX!@Jp3tWzB7Z#nC<)p_S+lKG*%MU6mV*_l@rCUsx?2W zy34} zN84BTb*R6A{|izDOKVugxnM^(0_y2$44bvU>y*jovsL}P7#qjR;p+o<3YJ6j_|9Ma zkmh>yjl5g6>h-dPtoNA2c4GZ=?rHGFV2Rlos_B-jbWelF8K|;?=05M91|Kkx*1Bnx zdm4NK%9jk4R`Jy@XruMJRYk+DAx875JUI=f(L4>tzPIl^*!P;BsZgMTL)B$Ccnw%3 z-S2e|RdqF@3W+@f0Xap)p=zD^T56=NYZQG|^kb_K$tfZZRasKnDWd046;^$ROtOqs zw6+4PzE)O!_>60nZl90Mq#`Tk^^YuEF|sN?;zz3+cT=R`gH}Q?yM?3^f?Q(sb^Cfp96>K{H<=* zT(1CMd2Pk^Bb0$Ny=sm;m`NY&6|Rq>Ce zgeK6QJ+KG2LYD;1i|W7k0*Qu8gXTr`x(1%isLoe96a)xY@?@Nlid)L zEl-fLt{!QiU(G4rt19^KI;D zPg73V{T7@I|D|-iv#M41Osn`AU~(+< zpoeY056~LRNx{0QW+R07J4MHV-h;ouC)x2|I03K3nefg*jOXuyR^(__Adth~?(x_2 z>Zf+{j)k*6z&Z|;&{bIEee4Y!%sG6m2^-<8?ni{Z=!&3q*2O9Myxyc2RF}7)^$NE^DiB!}P@O6t7pN`0 zifks-`8{YI!M|!IT9|4kvD!2fA=6Cqs*H{qTmSNGga(Yp+*y7jbp8kwZaWCA#He~9 zvk~e|HvXa>JZ&Q+d@C`$zE&xW`c%|L=(+|Wvk{tnqh5UbGH)vpZ5T2eq0yt#px6$G znvGD0Mj<);z(&X?mT22JWHv&{G<&TW-_UP1LLKt8*xAwRjF_@vWTz&f@*5#-Ux%i+ z%cwR&Zo#V7#qA41X&WKcNR+aQ+ZRI3vk_7l8^_Awt2yWxIW$jigg*OQZ-i=&Q5&JB zB(@U|oP?L|t6voN1xtFPjcU5Nbu@IqzS%$>6m&zXsA;x16G(qjoKnFBvMW z;t6%N(Rw2!8uqzjG@nh7jS!928=)%$q0~l*0u^jIJ{it#E~y&~ncwT`YD5(h+YbS= z5&GRojWjii9u@uA0Yqja#FEms9O)aOy&=@XY=mfS1y;qRnM&@j?OLUqDXNfIT?iPf z?vH7yk*39>r;C29AtGZHOG>jUeIxW%2CdQ?p+8U?&qnB48mTry8RIJ62-RePHuY>u zTg4l4Lunf!CBUz9Sg}J0%|=KbPf;78yTg2T1z+sx9SN!DLMlfn3Ky^g$lqq+R&2`n z)JBNfW+U`G_+}%tGOBZ^T0RH6rDXF3#LY%%e`ZKMqoX!LQW#5CC6>II6;eMkDUQ$t z+EWGgSS62C51Eb7ui8)n68B|?%tlDpAe5?t7@#*o3u7y2v*hg5s*B0tY zf}m`KKJu*Iy}}18QxF>=qwL=ZweRiS2+giSacqP*cw{4F^z=rk5R+|cBlK%kien?R zs9MNugtFDlZAaKOsb`hkjgZONw-Fk50dInIIicm*Au9(9y;@tjrl;0c zS?A5#O319O@?z1B8Gm&Nr4AX^-BjV)8ko(Y8$oC#oNL^*wF=qzi+b?1wN?05B5?Q3`g29;V{-GWuEi}wKX9x|v#qLfuUa}?A( zYpcT8IH?zQLq*Z!teGYn_we?LJ zsn*s3lPX?Yx3WN+dN!r4;ybTQUt5&`zfEPux*#-b>yg&#HGaG{yNHtw*4FzRcWtF8 zyu*HxIkRvp_Sxjr+DdJ+wq|1FnzeO!Z+C4imxFzmWK#@rv$lTHH*IZ|!l8Z9Sf#T3h>Fj{Z?=tF}R} zj$%n7HbBE4MqF4{M+NT%tiOh*4NcR2{t9<(b>WnDj;D``F4hY|t0sDFB`9laThD^f zD|~A&3Swa>$TXN^z{M96YkN8a=(X&Ompi*4EeiP#kOP+)LcGb*P%T z?U&g#saGhuYpcoGx3=bAimcMt)*F$NtgWo1tgR$cYis}OsDicCG(s$hr9f~wWQY$Y zj}~a|KF~uUs09SjH6HD&IvgfJTm? zAO_HzAmpLt%8?n+p~L25YPTOn!ip6_NroRz>GF>L@zVboJ4mK0BL2M|r5JuSJ^l&l1xKPP#Q7f76alRJQP`Jq%5!~i{j_8GzD zrmE!x)c_hb(H%hA20aACl0@Y)cL2Gt3;_i{1XvFsZD^YIMU&hC!HdC=` zPDV+8@pF=G<=cGNU75EhiJ%Oo`Dq@|2E8GJiQOeHJ@tLqZUY9Pj1C!0_IQe8F!4QX zGMJ2>9!&2Ww~-UOc_NO%v=f9rv3nU3?55M%O{w>}xr52%>>Et2;0M0J^dICTgNc=t z!9*f8n0BB!0$G1&NZq+Wxo=d{qvkVHw*cF0%PlOy^RCBw|MFdr8DBy3|GSyh0o4uI zomlC_)+z2j^IWp=7xmz2`%K|miDgsWeWp)E?K7uObN898Z<7Ybu@LjdgH;DeV?fsiBeW^*LhI$>@yX{#!0>4AaygVS9s8E>|RW*<`6s9AGJ?St>;fC zj;Yn)+DZ7fht$+s=XUxO29}X>i->JX8(4*RQxH?@I+P+)tI>#EK0^;FnOd*Ehk}?| zUk0J4)-P2T+DX*L{sRdsHXTZ4YUPjC&D6RYd^5Fe>L)=WQ_uZE^ zwMt>sQze$f?sunFn!qtTjICR8Hvm1g{@?`?1rNAWt1ds3s)87xr`D}TaCzi-f@*5L z=0QDo?ulp{^yDa(Bti={{9y`~$x*=%0oGHiHZ)DU_e1W~>cT1Q9JVrN#Mr#s1J(%- zqa>MHTivTYz`RL81Z8UdUz!KhLvP5`YBKWgQ+_*J`+-cY{}pjet$bCBOsz&wPpvIr zhRnq3o1qJsJEqoUAoSFl0||E1b?m0pD_`8H)#U7(T5G}&d{b)!CD?oJh0fEATOPn2E`Ub)J%}mo^mHhpIBnl z)9wU0H_hJkL+`A%-CP;I*6)QvSrO##W`KjQTAPug&n!kk;DY?OQ+Y)+) z_lV4#qsJQ7)IK5i3LC7XASTFN9(>CZS zPAp06UZ>#?jfwhTRKZWZ;!cp-&@}CbUUer(7nTW9v~$?XGC{6Fo6T8|l4OExCf`cNhTf0~(q!bHAphv8{Xizj(_W-FCP@B}RVGNIrzgmZVTQ~(GC?jD z@ok}!PeJGjvNa^wO;56$Qa^}wCrFdCZ-Sh<8YQP+$eo3pWP)TRWr8Fj!(bWj7Pozk z#$xYD8)br|cY7wtlX_`mF+t*Uw#_(DtDh0+jF=zAtKK1)XGQklh1I;#TfGhw##TqUg@ z{g$yU-(#rB98SNK_IkK=ggXx0py4w^D|;oS%gk3$Xo6C+D!&3`VF^lE{J@s36LK%D(~1*~mjuw|%r?J#f#lfo!Z$u?^sB32&_kwsL<(@rNMOtgYqD z9c5Y0qB#L;AgQDTOgiI{EMt&l;MDmQLA9|6b^;w_??GrK_fhfvF_txnH~uFFjv$Q( zM*?G-;6r|u93l=8hl0-0ahBDytiZA|Y$pfLG7o%YJRk|0-3Y1)d8CpFQkPBuRZMCC zD3O!T|7|!OU)nt-_c9=MGn7-eXLUrCGIEE5Qv|Z|DLso3g>C01YO`1=+xZXepG_XA zisbWyh#Wx}N zi%C*RdmgB>DUwa9D@7h1hG4>E1gDWF)I|hZF-a=fk<_mcNuEdQFADb{CAt|mBY7p0 zLhZN;$;YomForx*$;qVdgIw}@<=6@ka~i0D@i>CN}kzw_}IDg z9Fn=a0DOCb8iekqxKIy~;-l@kD-eu!EURk0Tplo#fvnP^=WIl9q>S#++I9hg9l&mp?>O6Y zk*no=2F4)!wk{~4{_SM^S0q}3R@}Cvo)}1|>OHP(H*z02pWFuE-V$I3Dur4jK=qfr zrq2Z43HU&vh&VzKcKQ+^l}wU4V-~1kq|OB8T;&Gi??h69YwrRjL9^MQ7$hI1#x^D; zXgCMdy$oIgFi2`?KZvxwkpX+qa&}h$Sx3Q5o~1gyXvs68W#A0q>}vjZt@-k-cJiS zg}`qOBs*t8qInL2Vk$5>kZYN90h8wea7sxn0X1pUZ)WMKWldsHY8?t$&fB$+!x3)2~K-;zga zAU~6xOE=}NK6{4~x)02}+K~A%7a3+VDHH>T$z+rI2$~Wg<&biOVo6CUsS z(N@n1<_(WjN2(REyMuY7BDIj}#MC{(ys?p!k&;{%1oOs4>KnZWLV42zktRs;7fv-F z4CP@1>J(yh^_+>4!oj-X2M}k~>=$_qv9wozw$~D*q`fXfds)uY&{p4_*R$#?=?t6S zH`ep(UV&Ji@+6^{mzDb)nC~Fxnoe#8O#c96&bhKZI{>oE>CTDZddf-d2(Tmp8jyjS z1SZjbGnPFG)Qk?~Tms2~q>@*Ws*Vp}B(En`3zRb!)F4@4?R=!QyWK(DA)d3!1S3dE zu!|If+zg)R{!A+4A@E2gPasu)E2vyjjX*hTSWqJ-NhMp5DkLBQlgV?) zYxov;7lIlj+bO#*NGmyjP#;319HB;~ggDLEQ$_N2O1{1wlB67=F4&2r1Pyk8T22vC z$xq}{22RQm>Sn>k>bW3wv(2aEf8K}W zXAFcQ&k>tn5FPIPbxk*=7@kV(OL3(V&fye88T=O*10VPRCD@O!86?Y;8IC}Cfb^bP z_R-uH>jC@TLa2^MgF0OxG*GCEB_|P*3kY6t==tjJ4k~ug zLE@y6Pm)@?57e`yo&n{&z+gR-Le>8m$+wvl>JBD9W>To+CrBP*QYZ<2qlon=ctY)_ zNG6k{lC?=$pMlCF6#?apV-ROjC<&^P*O@$_4lvn^Nm9wnN!9oQ)U~8)gK};lRhJZ3 z^W<6FLXhVOZw}G2{Xn_VPCmkoX> z6pDZ&z*WUSKW+&N#Jeg#29XE80q;4^Hn~g+MZgi@*a4s|2nZ$9ALm(zGp@4-i%arC zqCzonm~`++g5_L8K&a&yPR>{+NhQfkGFc|c*#xosi4eqwoh2?+HCsNBN{GVaC6Y~|cvLDmErYcVAdE{QdYoQA~2MPM}MntK6K z^O(x#9%U3#OPOlIUCC;sc=Z`;%6-TNr2a>&AedJ#@;y>qe`AH*mHcW_r*l^lz}m#I z5NpO=$q7iY=VQ%-dF`#->B!=Ah}RzM+yQdH8K48X4}rXd+@!OJ+=0Sf1#%*}w>oP< z)(uZZqH68Qk%cE()~Ddq#$L*b@G^;eqT1L?Wmvff0o+HevRn@EMI=Y$T8{^;w@F^( zgh3A22Rh(nfgIS$Les`by^?{plz>U6X9UTX1W1(;NOlsrN|a;3WSOFnOK=L3l|!@Z z+DKT|1+XNGXsIhpSUc2{0a119W->M7a)5v8ZB3T z)@eV4Qmx7dz^r{MW8TJbW9at1?X>diIkbtSaq*w8Lo2t-cglP(wDr z&oRF$ivX_2&L}s#0sW zw!EoY#jdyNy(}$ zlFj3PAUU1F?T~C^#Y#ax0$#la!Pxbnx07xZ>=pidHTLKAb_C zL>MaFk1(V3dxYWA-w{Si1JJ2dS{b2Tnv1YI@&Is#!v=}id3rPB~bO7BEisq{gFcIo2?E0;clFk1Q&!YZX35mqhThOk=cdk9Y` z{Rm-Z=@$sIN)I8dUiuTlY-T<2iYCaaX9_}ePxV?Lh~`t z1P|m}&JWbd;kN!5DV`NM8B3{slw_ummtw#=F_3yITT^mtnqo+Iwny4Zo{4baklN6d zfXOnUE(J9`@Gxf87*FQ=HNiypLnCK|up2*$5{@-Qa5K^~0^yS|FvdKGW(*Wm%3z9< zV&uQ;1J)7<6cmK=o(<#a%PKgDS(H;=4)_?A8$lVr@e2e! z%DMctT8m>qqc^oY&5ZapSn)V&8subfAo9-HDNjL$Njts`V)-VS6@L%OA|`7A zEs0NhF(L zevUWUC*A|e|6+WI@HO!Vkd%@rJUsq{H#sW4%&R*tz8uM?R){VSIpWpPZhxEf=0N-* zq`!PtrHRYhBx8w@}^>8S#-w>xRLI3de6kI%@DW;h6z6{@zIZHn7FH*alX7 zCX#NG*j9WF(tOX4l(IP-zh}6WO79HE9|qphSg|)8UyihE#b@F8dZf=c_#=^cpBFq< zt*I2h66w`wS;_ykO7ZWQR=pd_+gvIBt2e!~Qak{Ub$elNrFazSOVQGzk9U`jLfUQR zM{tt#Gpg*+BAlk-_A`pg>sL3NL|l@0S!5{U$>8T*j><=j^W+VH>qd<4P5fRY#mSi*XXSo`39LDI4K~Jph8bN*whuVJgC1nF5ZwPmn468D zC&71mg$E!W&|qyK)ebKO(%OMZPdhN_X$K}f?ZBjJhcUF8Noj|d0;zT&)6));^t1!h zo_1iekN3uQh824kc~7DJ9Rto@(1Ywx5n2u>q}=a8J_RsudhRiht3jStH#dw?xEW-_ zQFX&#Al}@tf68%i>Z%;4DWn==Fr+!oYq>BL*YtacZL7dOjb?5`j z$pu+Ayc#084ckWEL%b5#lnrqmWJNwfiqmmJTnE{aFHJVM4$AUwe1E8G27PK2!B*J?AyfwoU58 z`iNQGn>1iYIVVGGklhfW<#0#jobEDoXFPc_AO=a^E_J#CA1Fyu&aQeu86>YJK&ngv zQR6N*`4_h0$+x&4znvn&BUMI9Hphc(`I)BY7DGK8(YHYM{N-nI1J#6LAUub>GHNA1 zCCcZ0k_;RP$aA=1zBBOiMj-U?flQY%NHTE98)TEjBQ?#yXw(Q$Ati-kAUuaWhuhv{ zH=?A0wT-=m_l17W)$C(`bnfW>+j)Iv{J=bLm2a=6Kk_5c~MdBI>=a{}*QX<0@zPX7GLo&b6~QBq}+WZ=we31ATcQe~2qU^RK| ziy*=m&?YxADHMY;0r!zl%vR`=lfZBqiWixg7?{(G($7COjq`esDZ_CjnAr zl4RiU>(I%?1W1)hQi7Msn^O!PgCsww>@Y~aM}SnB@R)S2>j>a50a9g>WZ*nR-N;%1 zq{<{IL5#dsXM)Ed$#3C043aGgkSY@%lgsOp*+oPSi~jAXO$w3C5H6!CBxj zaAdmcM9-NAz;kGk(Zq6|pe$D$Ia_mhpTt>9UVa12o}?U74j-m>_@MpVz`b~Kl7C;+ zRB@p9DR>7^4gA-iqD~@b2Quo_pA*T!)jCh3>*Id56={GJ9}lUIJJ_~NAob_S1hQ)j zCy=gKbgX$~U{3j_2`=z$eu2(9=e)N-r?@^DeqG73PJI+7fH&->1v~?7G@~^hBu9Dm zr?LD-HQV8OmC5NepwTBdg7~91k~4UGaat8Tep7!ck-}+tLF;8*z1=#lKQ;d#a-RdJ ziS;1D!sQ5F^+}z4L;kOE%X&$q-b7fi2fOkxa5CuO#wwzSef^NTn-y|c{FlaR$1=&mx{41;vVxKPWOC8srdVXlmYh#-O z%Ae1SDO`8~LL+e?U9t}a8b|PjoO+enI{7a_>r^DW?gnxZc$rN@`9Fa96Ve6GATT-n zsdIur!ITR4Sufgm2L@IQpt^AsVzLO=kSbZ3g`xcO5|-5#nAP>{dffeSl_uz}ih*;RIkT-=~UBS zk^Fv;SSJ!&5E{g^N9GTa{NGXQPbpz_-G(ZE#@0O=$sY?V-a$J5G~geT=n2jN5NPj1 zkiTA+GSZaxBX03ng{L+OT81@EL-nWL9f(%Iud^^i4NoKZgi)B5UoWnQXTTkvw`jj9G;IsEHyk0V)Ai^=U#}p!?T=J`tbZ6vhMKww$QRnZo5-; zI0Z9S#_4F35>(!g_b%>s9@tIKgiucs13_F40`lt-nS2hK{H7N?RslP6MWkSGMf{bK zX8tVh#imdSKoOi3P1co9M4|Yre|vs!)9gXF*^g)gj1-!EJxrBm54z3%mzE0ayx8nt zKrGel1~K`#&7RxF)9mG>(wqGZ$eLzv%sOO6VfV}?Vs2wj;w50f#Dfs@nfQn{ZL!D1 zYHhWNXp$^+mBC&xO)@jTDpr=J?8U#)c77ba7-@{<E7zm;;y8_8t+4=v0U=s>9gJ3HV{1XRhsV%$MSa?VNtnv=h+9!q9Z;od5wf?zU zs=JQqAU#a$%d%+@Q=01_Ga%-U%W_ib4)Qc)jf2Rtd5JFX3LV$SyHw1wxq}&F)l$o* zkrq{!wIgl!HrVKqE29EBV^k1Oy5=6Z&z?gkn`~=Ahbs zmR2=hTmR1d*G=1p+`&29Cxy2E78@gJ`w#~wR($%}BXqty^Ve1Rh?w5Zw+VD2N@vtp;u7 zP8|oA2J>HrR35OVqd}Yj0_)1(P%xw6)08az(JJhY{o`+%*{P=Rton2E=Xby+0Z>6{ zetDdiniC7p#IE z1}`?*U=@C(y=A=ttlNh)^yZ4B_J{M|fYfYCEvD3`O@mf7orjy(7vXLh1pud30PQpz2!kmiPzd@7AN!j{!Q_Qa_V61+adDE2y7ej`iyT zIe-1i$)SFyLe5`5shuhGne^KE*>3F&@TjSTsof&YSY`lSJCimAuy*fNP&>aIYxi6Q zwJRrw+TB?}?QmF&3+{nD2yi|l#dCqABnc!LIDAvG!ynx{tIkDWZ-tytTf0C+G^p#; zCqSOlxif<1Op;1Uk{OgS=Q25a=uT8J?L&%XBqd28DZy7=kqd+51d5O<6CRV!sRZsO zK&niV3><#MKDnF#sWM4Quz|cEx`D?aIpYEdGe~|&fK-|Am~^(B58y`vq{<}8z~R@% zlU26?AXO$w3F?t|cX#j@B>Bm1he5I}0a9hcW76T*$deZnAXO$w2F|0@9ZY~!nIt8c zL|z*QJO)XAZP{UvTtI+Snedo&suOsQ0I4!bGI03S-{e*Tq{<{I!6)SH>j54EhrcCu z_&eh(%af>q?rzYIJENq$4l zVUXNTfK-|Am~{AgyyVveNR>&Ffx~Z^CI2Qss!Wm+)OZ`bGp+!SL6V>Uau_5F2#_ih z9+S?A1kNEqs!Wm$oG#S8i~y-JNlGx1yiczJkHJ7bkvfo%XgT}^$M|@HuiKE{c>Z=J zHeW4smq0#rRnSV*>zRotBP;hMa83eQ)EkdJ+C@Dg^^xEW#-g4)!#vHTddbtT2O!;q z(tRPFRn$kM`CvfNB}Q6Om*T_|k7@3}15A{@LZmMfX+B(CBo9L{Z%OfC2y1?zEk&pC zsXq)9dBzINVlr=|K_2E=WKL&E9%dIZXEH;VS*1I8y~%&Vo2|VJhFK0D#;npGXp$07 zz6GYyR1!Uh0LaLg9~eo2rEI)(f%$lm^cr{0yHpO3T-1 z&mp{$KSizpUJ$sS@MF4ZYCg==;}n#~Jmv?U0Hbw2PrAwE58ouPYCcV%37G`Z#?O(_ z*eeO<8Zw(2CS#?3U*I($MYlp9k792kJ=Js%pBDN*_TB?HilbW_o?etdAcRQ*1ZWXR z8flkcvPlBjfLM|UB4-Iq&N=5~g2*`;B#{g@(SQMi4F(hRVlcsEOg1@VY`*98bkEMt zuC8(2x9YFI>P}Tp_nh2SJxdOD4=h#e;)AL`apvWT4`$|3S1({_$1vq=R+A3}*l|$yUMA*?aWzpjWNH2QG$!^4sO_$w|*!5&7=Q$~g^ibk7cH>Aj zk0rLljg1he5T~IVM|zw^>>5((dM%Lbg~YBS*}UY42(2JaBR7upm`d!rZfrzoGjUqD zlon@+T+DWY{Tocx4q7g0m5>B!q8GF4;CgigqOO)I!`93B%pZ*C`ck?x!i!mUaLSQ4 zk&Bu)o|?rh8jKFaZ0SK}S1_WRdXm`(oO$G}i_x3Np{3-lxm(U73sw`SmP;vcCeVL9 zxZ4Q9-#CUga4!)X7~=t1KY|!DLuPc<65Kle4Um)rhBhs0j zQkT~Wv)BbgNnC;GPgr%${@#A&A9y>oCgQYBi_>FbGYtl8)eAa_N`(+9_#+i!wY#^~`OSaJL za3aoiDO7~uI)ysM5?g-}I63~4!I(+RrBWadN=ThYoMg!n#KlBhFNscB^VtgGeCLUi zLY!r?h*IWi8YhYtNB@n0Y$Mnj3DX-$4J(4*Lzp=-5F+}0e4f-x+o|WXABZh`Gg^`6 z?@ICj_EBPg>EgQ=_uU`&1Wm*#!mK7=vQ{WL&k=32^Z5!rPuHL4vpYnXX%vjm9uP6f zg_!d>(bker%4x;_Pdr;b2W=sxMbZV+4~%TYT<*q{s?9^}uVffp=6n`H#7#z`CU5}@ zC(d>uZ9XeTk9&;eMp?kh5HUsgM&FqpQ(Z9gSqu@sHim$jyOhNexshJLjpepJvDTS< z%x6uAyg`!5M#i-v;zmgniAo^iJ|j`9G5+1a7zFd_Y02bb{6~TI1<^0K(&vD-g6LOW z>8YS?CHgH_`X11JBKiYYdKzdKiT=!${yS)oiT=iw{u(r|&Y-_{p+{#1Er{sedd3kz zi4FnLMht%wqZEkI#K>l1)C93HF@j8t)*yBvMqv}94~Qd(5$VbZnsyO8pTMXd!Vi&} z2B&|opf5pP3TLcFO@Xtf8uTrwyWp%967&O{2ZB*pNA$n(5`X11Z5WS}>{S;_diQeCpeh;+QME}f4_oLspqB^jy z;4GyF**+-#exT(f`cTSAqH8%?0JJEgk9MKYXQe=_J=jR}qo2e=d}ZPcr3YPn(A3LJ zsSbLbkf3>R)`!zSE@&m39mrX41@j)|U)!fA9)1APzYcx455W_Cv-sD=lW|4=C@kC^ z2WGi?wR|SRrbO0rkeBK5sWwIieCEn0i1YJVDxV-Ov(Fm&gv|qiJ{#l{HV@?R*(#sn zut?Ttk9=xi2@Ur7K|VFKU{COIJW=T)}hwPErN@tr3rXFBKDR9e+}u0qXf)n z3B=wchiIJa`K&8(zLsM%MowSi%$D5&og+seh7fzJ{E~NLk0JJ4IX2_QoGiyK$t)uZcZE>WD{3gt(J9d}9R_2qR}d zaVEI=ks^O0_H@~+qmVVO zoV~>-o&3m0^b1dZZ?vJktg z43_s2>A~+E2Wprcgy|+RJZdK3d=^ZYp%OzaIUk$SMr9R2HBNLk4m476f32@9olxD5t6@?e1nZM$tSi1t5+mg{Lz8VshBhQflX zf;xoOC9h&()rdaq5O!#X-NMhr8VskSg~INUb0nSB5cZIq<46WHzW51l6K+9U{kRx@Xo;BSr#FSA9cGx!n$al~Q$XPnss%9`XeEI{kKj3X@TXfT z4sb)ZyJ|QEL_dbg(swd`w}!$SR58Z`m>y4 zq`(*o7j7PKDq9;~iF|5^P8N^ zSdk-l@qm2IAZa>6oxf>jx4y@4uDZ#L=t@>epxQy4B%t~qq$_Hg=>of>Bo_D4U>$E;c73) zrA2|NFC4|-h>C=RuMQN|WvoE26t*>wdL9tH;F$TOJsimH)Seq4O~s#GJZNtwB|VQp zd+S7y_his{HSHDj656WwUH z3>yig%NpeP9Axz!p8Jwx3gR#Vj;M`rOeRMf9CP5nTVw^S#3!hA3FJy)m(g~A3m5Z# zDBn-n;KKV!el9wlES>i>btGKg)AX{9rB~o7UGinPkQh4Q7k!z!k4bze z?>*F|QDMAMtD+CWXic~F;>`*dJkXxhWVXZ`yn;F}O5@QnSgYBCsEFg>R?@k#8kf#E z+`x)J8!T5fgg}uG4H}NFLjm6NDM-%3b5}7XtS~u4c|2A#OJpb(+p=l8ybg#Ti-`cn zVu_^QO)T}FEIyI6J1n*+(KB-TDi(V<8ZYlG{0Rs1voBUr==2dtp~qYVHXxYM3X2#* z2IS|xrPx1+UVzi#sV;fautg2nqFT>t11r4}{7{NRz?IP_5dA0Q{aW;6l+gA;@`Rm$ zs}Qx7hfhcB{EP4}a!-^SAM9x(vqm6R3Ok5MX!<(|7xYJGm?g6`(%%)Gr|EAsdlS`~ zRQFnEXsSzQWk-OV^@)^~4=%`}L*!Sp^AT-VgIfl)Ty(&^v#(Z{U@<$BFt>9)D}lB1 zrW47T%qn7^8|&uoYb^N+C13gTHH2F`S#32ds}`Yf=7OZ9h>KU&vN=c$T`g%(4lZ=8 zY`bBHuBYykjm|ME@+*4Be0!aZPBaTYlvz=>64yQnWyYQZWowy`k}7PgT`h=8L5192 z9JiGwe*QUXWALe%<9$*W7QGd$c1LSCqwXSr&g96PMN#^}VXqm5-%SV^kA%%a9W6kP zR65~q8wHpd5u7iBItal~>5o(vkVG$tUJZxM3N`H(k`4+RC11S;d<1w=qkt?4hn*Ra z`vfxJnz|Q2Kd>T|9Jt$#L8z3cqe?M#F<=*Y_;+wG`W!dBpK8O4M9I(tuB)vOW=oQp z`E%Th_QMS?w<{vho5C(0v=>rrqro+^ECG?~ClHcELV}i(khNS01-czBnR(BIENfBq zOW>)bEB4d4zY>hUB%ql6KFDuPQMf8xgS8qg9lEmW)Sn|cTg>JRK?Ba zg`4!Q3Ne=7A{$OHACkiBL&6fb0YKbfd5hwZ_b%T2l~0(ycWz^L7ha*3#-E;GMN*pJ4nb z0cCitIbb5A)(j7HsWm4B;+phWR?Pu~UTe&Jsx@T+&})qwAWdx!zI&~aAw1ASGSr$t zbS$i8OtmH&M7LTay+09RTx-pHLG>2(!eXd3=qV*vMO&lwlp6M?)lcX?HO{w<6KU+G zaXuQm;e$Sn^U;U^AM$COj|OY-(kqB@9Mnn*|LCbPEmKHVclJKw^__vx2l^H=tGdX?UF2fMtoNiJFn*+N8V=af=Q z@yQECwiKW6mSP1I##@R{cuUd!BhgY+&|8W!B0r;rZLOf*g(tnGC~xAUr6`!qrKO#p4Z#>%iW7L$TZ)E4QVU^IOR*jR-cr;; z*m_GLkxc{=EyW}NO)Z5R3N1wh!L+(dNE5*lI~G`0|akkB34H!$_i3oMYTP4&+fou zt$w(rfrdYqsZ~H+fai!TR7BB7YnY}6gO&@A5id}^ii6f5MNI`Q5U(ZsNr00@NVkOD zFjyTA{ynhlh2YW5#|G9YkfSaGRE8W3V`o+2u-CyYO-Q*c?8f=%&=RVwj&1}l0`MR> zv=Io2l3{CTeE`DDrcYQ%6XOp`#CQm5OUVp&P^IQqL@Hb}L9|wMP(^ke#?Af=$0rhrDA|-8~o^p$M=69WoNo4sdG?T2Hvppplrh z%qG(LtFy_e@)3M#os%lO$*Bo-@Fu4UZ*p?x5=~CDv&j*@qlImaR+He#+2ok`XmSpN zZ|I!tCuKxyO-?xkz?+;FaOh1=Z6RZvB$}M!;G3EpHx!y2+UV%H$&s>T=xB0I0_@)8^c8^)7Pg_uF|(-2 z*#IHwHaRl$CJR~Cs=UdWARZ+dP0k49y`jmGoN2m8btMp5uO`ffBZ~wB2Rri1T2;-I z8-u`L*IbGR)w1<=5%+7ZAtu+;i+Jb;5P zyB+0Q#^M`2HV&#Qj@r1{-vTKC>jePyoNAvVA8x#!OTcOY(CfLaDIk)XBDwe;pc+P3 zTy-QV@fZB$E`eMrEaNzf(grSe8#JvBK7$K&P~%5QzAtm-C(`-xsjP4KH<%9+?MJXS zKf-4}^0R`Nb^&5|xF05y1fq%oQH3A<8~Y9+SVo3B=SoItb0x`a6ZspdhdUoG7DH#z zTfPgVGodk%fFM#>nekXJRT9|sI`$yPQdi8<(LzH-n9nXj>1_w>z2d;0)v-4StDVlD z!q$V2ztSu0mCny#;e0xVKZU)P{M?{w`K9qw*k==P4h@pba74FY(Kr@UzGBv}R$vY! zW<8xrEffo-gV?QMmjL9ri4r$3eOxlTPa0bVglPbftBz0q1)pRzo<<{%KeAU4n!^q+ z$8@2Zk~ufeM8Umh;;v<~!kSNIwl9_rLKCLAB6WqK7UIHxr!qriTe++nP z4mj$;5mgJ07Ub9tM<+Na*wF|!zwq8p1{>m-4RTagqb9Z?o~iLjG|ZMCXxpgSs=>K+t;F>u%`djf{36#=B8u6iT0 zn-eh9030bLhN*b~qzYsAGw=rqJ_~SAJ+t3IzR1`}Uhb?8s-yOwJoBi2+m?9XSyoyc z)KG}aJ{-tgqplL4s;P}8xXj)KUstP{Z|Ywvo7f2v@C#wHcpQ(dkalac#-z#GtdXwA zQv&o%#x@Kf(jq{*4khTC5u|HSaxcj63>q}^j2iU7(=}-3nKYQpzC+W_QhjBsyA>`p z==9H(#A#^zli5jX(NBTQ+e>E;mN(sE9l^I?RGUdtWq!3(=#P(dvPgB-PXE0eWq@tRBFuO87=XFQGVWL^W+X zNeb2C@D$IM%ocj>#L$uyOBM_LA0~#*ezyczy#GLU6l+>8!m-+XO(|;3?MsnQZ-qy1>9Mqfl%d$Sq20?Ph+&dh*6{<# zkxClwYV%-pLE%vBd*MT3T1jj<2Pw^Q2{*e1ktr$|5|BH;gY=;ehZy`3S#cD@&2|@X ziL5SsU~<+$I<--RC9||-riE)UR%{g^K>CT5?BBv2q&~&gl)@0yW|E6Z+!YAF9e8SC zIJ(0Tbr6ohknqLI+b4J;N2|Bsa|>9J%0A8iCMGpl%XoMFjao23=3xYz*4Wr=X`9gLVU? zsa-q7gJv&=<8x=x&`ZE;zLkbUDn0; zW#Rf%3JY6b7b6)TNrqe(qY6SP$v~4j7;^c#m_RuAx|ou17}v#A5a?#Ywl-0(1ESYd zGoQ4#4**?zZh$m(3Ha{X+e}GsV$fcD5#%ZvbW=@x5muo+2OPTgz7VKI!gkYMFQA>; zlQ1dVtUWW|llHDsjGG$P#jF=$-;gnm*Ve^&BWS)ZW;PsrUCeek__~<$aA@mdHZc5* z21_RBzg09_@y`o3)-u_UXTtmvU1-p|+=hQ`@U9CVy!)F1KZ6g$E`0Fr=TJpCNgsw? z*U9<#+TwK(FKla9wMHSs;9WfvAA@(p!54#f@3Fux5MzO}8){$? zIQV>gM$Y^WdG7B}2#H-FSrQK6p1x1Ug&ThQT{Ciw5u7LrA)VcWZ=<^}@Dx z=Yw~tCNc)^mLl&B)9u>?;;{7CL!||RdM!5dsTMZ@K(EDafHZXo_%5}WPq)hue$hkH zYBZm2rwJ)*chkgSFA&`(4yE_ALX7Lg;Y~rkFS&+^!?jFShEvW;(VPDErd5jGyi)8( zH^ zm7=JSLG$3e`noMrF(ar_v_~+8O7RendZj2KB$XF7Rf?Yh;FY2a!qzK=M3xpvREksp zO_jn8g-S6VFwd1j%95d@Qq(}0?v4@Bsd!VQ3q3Ha`nLWZzd56Ms|XfDj!&r~TC zjHtO)3h8~h5aU`YHVWz%$#tm|vN9~fL@+OE@zz0By;2O~m0}Dc&nv|sUMcFSqEZaj zE5$`2`@{8!<_bvP~R0=bTD#a~?m~N#gEo4*>wsk146y;20R0?aPOQrZsAeu;z z!_=LKtzIe2e5w?`0iah3H$a;DH~8+ALWa;m56Ms|+WMiG3^i4XnIO7V3hBL*5aU`Y z`U~n%$#tm|vNC*{P0Mj~pGH>JE5%4&DLzI1@Jca~SBh*lQ7K00m14D!{gtq-qtt2e zq*sa*6Cai0Aozwi#ePcdD6LYILIAu{G=W2}6uX3sC&G5`KA90zDQ+PcL#5~wWvCS2 z2}wT+n<_;;0C=T%2!~!NB=UQKM5VBSZ>kh-C{&7!fO)PIQkD!ImEvcB-7Cd45$J7U z8!CmFMU^5ILei}iGV@*uS=Q0KQal%rl8j0*1bHvIPhoI+iSiL3Z0l(C2FUu0=jDn<^YGQ=2jtA$n{~Q=1ZyM*!TWHYMOA0dSq# zl+>J(Yna-^EL%dW$rhzAY6;txUyg24T@bTu39G@PS+<0U5_c(m+*&5&wjNaiQ%)0irKH0eD>>`Vq*5I6`%cDSX|70wWa~n@D?S+>{lCJOKJ8i zUZkdzu&piCo)GCvGZ-}cW#-fDmjeL9?3eUPi;d{Aw&Js2-Nd6L)9lv{_|#{=`kDYV z`_&Bb=d)iAfaJ4Zp`h^DuNiQ3(&kS1?AKJ`{iF=GwKn^82RJ_a<&VVcvtR23>RVxB z_NyWIeDvyy*H@Qt%y zW}b0u)&ox;n>F)X$7U5i`xPL{cd)Rn?ey8NlZc-_`(?(_>{mF-h;#O91k!Do{gMI; zOTq13X1~mA^XykTe0}!I%qO)PR###6tD*?FgRoirDXT>x?PBDaG>M5VU60WM)K11W z0U**MK)MbksGbp|Yfy4)%J2-M>t>!&gC2Og2F*N^1~;(;5!h52X#9>s7KKWthxmUk zKm&zsr9|rSm)u@blp+3Ro-zI&czXQJJlFVdW?zV~{e1mgbHF#RhV$|JB0Hj|6Xuwkhj3J=KFHl4N zfORCRS$nnpQXuJ<9R?)!=oDK8GM|+T$f2!Sp{+)6^Q}gFYfw&YYfxP5Gg=sO0k4$K zm`U-B5q}w|ooRXA2vAseP0BhA`e!bJ22K^wBk4m^*j%7yWre`IKy`hMjntYbR)ivc zdlUXE5tV@-_Z0W#Yf9u5=^-x=|D%TuEXhhQUJ{c1eDQ^N@vdf9eG;;O*Z`j00($NJ zDL^sm7ZxS!YwsTrTx?Nt|L)W44Q-l_{g|Hq@F5OOV$Sx5q$QptC3D|^q-F+WpDP5a zeZV7D4&t(3E{!llD{&{qF|-?v-{1u}nx4UtH#;&W?tV7f6c-#w0(npweTo60p)>k4 z00YUXL&=%03)Gav^XP~-yah(O9% z`U`@gjKos5WWDCS6l9cziwG#|b#Hzqu9Dapd9{UY@VN@A_gjRr#nm%s7M?DcX(nbe z%l8g`=$9sj05!$-%Rq$^x;d#wK0X(($tkQY+N9xL@JW9KF`XHpolijP;Bsf9P9U=F zfP~YJMgAFHc&0@;g=s@Ze<;!7MSpo?F^$2%-%I%611YSjgeCuvu*rb!x({jew-Qs} zZ$V<(`h!%%=>@449`QJDcuQf=A)rVK1O%uuI@-AiVu>BC-h=A4e1<5N&>;=rO0Ue* z$@g2>6`v+aIAgX5ywML!a?wHg%YVTC_Ov9g;R4PBVsGO^Jm~%sJw5dKrVF-tQmL^2 z;Zrrzf;{HG4~@&*9jiXx9Kr2dcupW!+(B}220w5AQ4esN^v3NXG3YU_9NkutUveeB zAO@$sCl@i|nsmc006`^?E0I4^EJn~Rk#2D|;_}C@x`I}L9?8`{F9pngL~QT-@ML?# z&67<(a{0$(Ljx1xp^pth=zl3%?oirT49}fw-t?D2-gwxrd4CEwyp%X3ywHzWKEwmh%V}n^cET`sqvm zFMt$6XOoksT8qjBk{Oc*c;L^P*fW}&#Kv4F_c1^Edx7@Ph7|T#N~V9!{C6a8VdZ?+ zAB6^}MWWxoXi?Le?WbU5Es)^?S}qiaa=x!6kp3oQJPA;!`BiYGpA@O2$p5|o>Ti}xhc~?;E zSx22|X!Bb7blt{la?Vp0<@j2_rs**H*MxTNkSz08ICJ(a3S~Lu#dpa&1-;~w;IM@$ww#nSU`?9aC`{|_xcqaJbuGP zXyaw50cs_9{!9XE4(n(Dd@BIK&-}1-9I?102v4QY!dyvI zE^Q?|@KLlmfQmJ)ZA_Nas#qmS7mIIF8-g2RW3#0;HzBX;NYuVxL%}31s^zcSyRn&`!Nbm=tc-i<$39FCm$cwzUSmB#N+U;Dcvtil&z<$QrJf zErR+${yHR}-om^kU|dUaA71>%|R_rWOF-T`%=1?&}SD`9TDE zRtCL6T?e1Mz8r_csTYaJjXfefl^Zm@JO+yEC3_8nUYI~-6}FpR$^q@vi-bwxX1$pC zp7cUTfmk;f^b#V%ZYpEEPSeXo#F*=)1>(TPFK&P|^$_^(df7~I|H`13ks`=hGU!ce0|d?W(jN||UL@j_j@0zB04T1P-Eipj zWsg7|6}FpRt^)1Ui-bwxX1$pCp7e5+(zeN36af$i8n`hNRSy zb%7|_jBW{Z>xrBFk8njvb;F#?V;aO8l4?}p7Aqj|-wkK{GvM;;HhfrZR7^mhzs3~Bn zRgv;7aM%(&04+Vk)rvrNC*(jN2g4Dy5svZXI0{x097yWxhxnQk;=^Px6SN;|+xG+0 zMi9G8<`g6>btGxmafO6EfUx_TFxo{Xas4HJI>+l7VdiTYkt#D{HEXHXpjnbkmE=bt zpHIPn{w?)-c`!nC2JKlAr?TBr`BVu%mF=E-IaQv@_JGqdkasv5o06VrD1PL?Qw_z7 z|7*4U3i!y3)xnmx>N)tPZ`tg4Z0?63=ISBtfQyCFGMM}w_F)u~pTCZaAYZH5?Wior5y)E|9*c9T=zF*7ugGF=uyR(GSy2`)5&pCmINVMPe>$Czr^J2d zMd7cMz8oLqi^3mx0)Y(C;S(qjC2k7jr?BB?F$#tk1Y4x@_YhypglXf=k?00&3Og@- zrG1dEWVZSqg7`}ZXT%|!h{8;4ElXz8Gk})|6m1AZ+X20m*{}DD+7&1YU9krs9NJYuR|5$c;h^B{wAIVZ z%bmx$(@XMVgg=YE(~E|yi*!dauIkD711=9i_Vp_ z5Era5{pA<6!useQ?D@*PYog|3w&u@tHwG!)3{b}KVOn2t|nI~uF)m&{9^j1h?*m{#mBx0tpYmNq&Hv0z;@}<(s&)p0j>`Q6qB{x6- z3kn-JwH5s6CD#prl3N}CQF1S!;7Py5q>RD7b)P_kW_rV;ij8)TN?aF-AL47;I$Bn6 zBtmW-y^nxhw~k6=L*c_^>!@T_l}x=s;af+gpLof3**e-(P&-I2_BjQ#6J0 zXbDin)=}GAq1miRDo9Pe0=e;d z1*$13&{xdn`y+~LV+^}8_L(gAe9W28G+Y96*2iEL(3#r6Fik^b`b{t^n3$WGtP$A@ zA)>fgds#Bk+Exu3Sus{CPqO2FumN=WQx)FSeiaipyZw3E~ux-8$3e1+p0}o?` z4vHpTB{bA1y?Bc#z^gvYXy%buZHN({KFE`@NEy!)im3MP)AD2w%OS)~(^D1$jLo;6 z@RG!CAOTeCxeq&~IlsV;)T5&2X=lg<5Bz%I>$wmm{Ke`1ow;Dz?a_CxB<}A>;^zIHI)$7e}v!5QpOBl zHN3r|P+V<=JOP^dsI>r~blUtq0h;@$-2tFHvL8SP+#E#iJnBsF=~o0cIxt-F&lb`$ z0lgG;3jp*d1Ag&$;tRojE9~GTs?tsMD(%MSRl2FD(kUznT4)i8I(w?7)ZObHc+_T) zfALftNhxf^6(O@OeEx4`u4esxchQ{hR0z`| z^d*nbW#p@Unh#|xeq)XYYJH1cwJ4j51O2Uz=E~sAj*|JSi8+H!5;bs+gGsn*KZv8JiMtu^15>YTlH%42aDPCS}q8N$6tn4FI*_t&+sjIvAS6 zh|HjGMxWFc;UKx{GjI#TL0$1MYE>rUK}-8=xaeaDeWhgP6$0LuI`0bcVwNJ6!B2hY z`!i;h=B_apisHSrr#{qui>0s3;O9QH{78wb%VnJ@2w9IzvS{Ka__`1EZZx?!403<> zamu}Ekb7H`JA?fs622N8CAwIA!`f&jk*P^665VXQdHar``^w|`AKwWx@V~xi;PPJ9 zNoR9+M@V}k?BJ8W>IvZV=FSa(=58$jqPZJ}v`N28VJ$|%r+n4EfKdKwfBul1yaq&t zM8nvi8Gu6?gTObA4c4ObjjuwV5U-65+7=*yibCW7Df+apItN}!fsyPh+|_S7q6bZm z)}SAPBkCv|r{J*tj$0$Mgcm+)Gk77jsSkjB3r8gLK`yJmg8mUXLg6R?N7M{BBH<97 zBpHpVGCF5`F*34qq~4^u0nnrpK(wj5nAGb!A%Vr0t!q(IQ09{G3UjSEyO>06*3pST z@ArtF!6eF7MAHyiw`v)P_y^awXw{P1SNf)5 zx9iLHRr|W-?OrSXMH`d#8rsv=d_kbr2DY&{+t#)gY6Bsr_-KeJ8Yjhk0vDR;_Oq#( z?n%6cpycXM**KcQK{1JtZ|TT{oZd84JyK%RIUSkC_gsdmF`8qCza8%WTn@$K1R2RwNn}@E$3*S5x1Pb3gG!BkV z@P^BF5v9#X#2`w>B#W>59P+6os+GDa%2RS&g0H{HF#(iJP?CBQj$Cjkwko(w-$kXA ztiBE^XpYvn*+M-aES;ExiYWwq39FRwSXBxL)LsHqlGN-y73BaNwyvI#*#8oQWKvmm zOu;QG7Vvp+Ks25HMmx;usx3ul(?sj%zqtW${u{kt^aJ411L$M-W`JoLi$;De*DXq6 zE9%D4MzU`5Dvlv|Ua*_+7L1VjCGxo|5<^36P_G1^x<$;(Eg z#`6U=MRLdZI){zTOfhT>)zMes7U5;T^g7m84d`X~Ds%(jtFQzB`d6VF0AGcT0MNe* z%>aBA4g_ESDwOWulgNOq(a+nPk_c2^(p{V8j6{H zM`b`;a~2%B_*bW|P+?|a2TySQ>U86~e0A<+1%$uC!e;R;o8YtfsP|%&ol8;9JwE(f zRN2cUu&C}~n&u(kh9?inY-l-rj3fi2eI6W!E4@YM56jZW*=PuwMIXYy>7EQ9!WX?C z;;UF&N`2A0@=iuIEAQMx8T3J(sbs!Ld#0f*nv5H z=d!@X;NZQR3=1XrJ;2g?6Dj7kcWqXm6zRxAw<5UNj(GxJCLk3O$1S=&#m#mW=z2nu zF7cALgEG*O9qF`<@qh?S^K+2i9DC_@6gS()o?yrQ98_E!-EiYq-bQ1PO+TW>JoiR9 z9DduP^g}kXdB`M9-G*{_)=+fMdgs!L?i=al$On7zx{LUIf>1tc;i0H;x&NZ5RjbO2 z+HNVd(|=9qJ|>IU5TOwkzYWs=_I`pql3!oEpw(fGXmz;#rgzzG7^Rh&GrB=GlEJ3WvxS{TWNw( zX>fzNl?G)WlPMjgr#Pi0b~gFsbZbhJ*$QeI_k(S08O3V)DDa%C>Gv@yZ;CGWJv?Ui zDP@+cZMq5c>DUU<-UiG#;Y0ege}sH&{4+SHhi75ge!<9?85J1h3)D4mfO)kXmH2hUdA1Hk^Rk2(;5+TcMA zV_@YJe(7`|x=6+%Kqz%;8XQXqYop0736T*46a)X!`h=I6kNFznYja+r>p`jRN}Dz) z&lmVuAK;7oW8~iDwjPwz(&uj~y8D>S#bY9pEIvm&tby|V7+#aubHtL~HI6T-SFEkMURp>5TEWGRA{_vQR@%s4r7834ghTZSUpls06wr7Pq2}aZ`%5 z7QD^EuK5Up;veGe(%APK#3FVdRl`QU9mZ33?`ASCg(78~TDPag2+iSzl#s-7^fSh* z6`sUm1g?j54Bh27057*gV>97bt4@6XA5QoWZ0xu75%y@&cDt{1?x-kgV!&PQSL!jk zqBX!hrgQlYIgOhlx%W)mO^lW$(A7te`9~crN@4=E_i=xm1P@285%5JnenK48#voGs zYMsL^O(Qx;Y^`0mDcP_VXRbprk!ZDF5>wyp0if+bI`su+kV{IikKz{J8M-x$IqZEw)*h%xuABF+-iOf z+JvUqX5%iYGPPN&`KkXwiju*bi?<~#TPF{=z>j>?uYen_;U*J~UU_DDc;%^6fpdB3 zX&Fp+uI9W?gqkUDjcVS@WVBX^$g}ulV36(K2|uWjkWS^Bmkb-}X{Z3t5jJTla)72f z8>!9{pe+ETMjNSdyt@RhQX8q%%#`Z2k$OEbN!2z|wHs5Y-A-yZGer@wQxWjMqvBwr z;$Y^v6b;FoEE42eG^Psb49RsV8j>ork&4De!HVw}^V(Z&IuJib z0?%=RZWnN~jrIh+?5&mtbS9w|(=COdX~--(AdW6wDn5QG6CIh6R@+by2>RS1-8pv9 z?I3QpC{Hka?og3&BoZQ{Cq!pI2NgO;5!~#z5hHVC&`?mhbz}fQTzNN5M1JdE&~dLU zN*St0=aAcm23D&_XASk}taol`3RUkf>BYaxhk7ac1}!U<*+%fD@<@I`^AhX)f?hzKrFY1_-%Wn){0o|L z$&m{;+YwI~{sm2$@3?`RZ5)6P&2sPsO=)!OCn?1|AgD-D);hWpf=ZKFMxa}1aznV4 zCNsiAX+js%N90tno?~h^`T{@8Yxz*r8vPZ_`#~Wep>yQx<0yA=g)dSC>qZ$FS|@4ask42ec62^sJSH9yUV(!ogyNJEjoZ_9JY{gtR_;z;w2QdP|v1_@KZ|I_H3Gxc+bYnlnUcL8&6EVXXC~+_H4{dW6#C|Pw&~7 zc`nM9OjWAWrPCWFsKq4LMcI-nGl7)-Ewat5Y%`9OJr6juvfXe{c3HrQB||CBwf56bn`U z#yCz=t#t@KnQdI;5lH?*rT-*M*Rij68CGtm#zzDh}(k-qnarxtpexUWFM{>2#O930t%&AZ`gO=i@ z!2Dy1@#6jg9!eF3kRRYd(>7bc`E?!>l|A)Gj^Qgb~K^M zt_&qJD1XI6=w%Yhd(WCs-h1Y$)^aAGFO@kDYaB_e>^&5?jJ|-KQ(O7>$ z7mL3KOm3f?7+yg)9Zib<0GZgnU)U%_F!iUy^fXnf}in}++A0q~AqMmszJXvpw;0Db`vD`v_gh%`utKL@oW z_Aw}*-w0vPg>9W>n+cwoY`^AH%uFl#1As--aI>{Bc-bQ);eahnwe=@9O|?nilI`h> z;|?Mu`H!WTM?Pw=A&Nqk$q|48Xxruqb;Dbo4HVT<$8WgVvO^z-gbZEQb#DiiG~2h3 zV`fr+kP5it1>G3I5TY{4zJobL6G!XK^I}4 z<(W+5H125ica&$nM`PxrN2B^8)%sAL1lUDz=)$Uz062&9iV02`i9p|_4iL^EJ;{+# zrrym)f&>hL-D>&7hRVYlwZO zbNOpVcRi_dX{1}c}uMq3DlsXJ)wgr*mS1S&;nHteS zVr!MeZ9fRqf2UZ~%8A=!L7+(2qM{v=Q~Themqi2>>iQs{O4FN#4?K_3p7jr|&3Ja{ zgYObC-79R@53U1(dPs6z`rwi(Q_Dveks@;`HRJf`B5>wX>V`upod=wUQc4Ai4?J%u zC)7-NYv?OsMUITtI}v#nUvMZ|!K2=-%4>e`(u8z+Y4Yxsjr4RzfFBB*v{ZVyraBv` z&J&<30Hj76squ=t1g=sWsnpDr>a~%2JuykuHd3`46Q5_KcHWkmnW6~rfoBgqy)iTM zT#ANd-Vh0LEgClk^{(W)6b(t0*+@m>Hgd^aG|V_E8b1JME*fq)6pfX@rBgJ}%?tP> z1I|RF`aj&IV90^zv1knBYAMl)J}kXd{6H_%e;!pKgHoRwmfpH2t^Z5`@GhNSMS+;@ z34s}6@aIrlbQFB8|IGbePDW86i8kn!FG0I+H|~u5$`& zSVai!@m~|VkI9-@9*cPCV)1(*{fT!2=q-t58lhFrmz2A5;CaOq`5E}ayYwj34eAEc zpB?DRE^KY!S?>m#*`B(AcI3VEUP6k&z;g#gf{KHq2HhIsW_vr#0~7<#(STB6bL5~~ z2ti|!ocuzXE)@gMl!=b^VtdUV!%Jr(&B=2caA z8TY|nVyb0OMo^hO4lmkAnW4;bx&QFFXDqWd+wpi*h!H{yjs9;5-N!x=>TDxy7T*if z|Mu>WGAp|wyu>;Oo@t8T)*lJ0Z1SrOJX03fr3oFkwj#Cz^c-6?h6bJ&@>)JY z)N=j`=KY|n=%diUv)&I1%w_5aMGJ!759&n(@j~SNpcNn(`$1{iv)&I1Fo_$uhs}%s6`49Rtq%vU9`XWw#bM&o8@V_8Sd2JsvBo zr#1>F2A(^DXB>EzaaNlCnC zV`jSaY&kxh~3>rSA zW@Vdkr0kWznU(E^gR(~e=TX_Vo6xchS*nl*o@>I#pWw}9iZArZ2cFG18hE~Kmh5cp zG4Q;By>bo{4@P6&mG6p`L&HRo?lWl9(9}1soXrv>~;8AEj3Xq%bQs zR&n^P4}kAuvVhQG#&ogxe3NLv@T}Io8fB>KH9F!+3>cDXYZXU^7e^yW1BNx=Rwo0{ z5RO_GF`C{M92zkE8*X(2IGL~zzE)eXXM#h6eN-OQli&=2BWmtwtYd`3PDccNFY47P zVOwXby};M^&zSka*gxX{K-)jFlZ6Cn=d*1dISV2q20=CZ5vp~rx?_x@OvPiA3dejn z`1Z4lBAf@p4sM@8^#VZOe&z2GGfby#dg- zIl2MT)Vkmsw>c_&`|)F>1>(i_W7_H!A_6Vy44jW~@vUALAVlBl<%YyouU$xqbF0^1 zfE%`YNs(ntqV=s_ZUDa3YqN8!S9$<_tCty|ZS~qLk7+{@TMbQ>7ZIo?Z0lTG1e$=# zCUWpCiyAW)2P}aXH5rZ?aM&J)qHkqFT5{Ud5CC3*7wMCsFiPPDJZ6Ohm;E7%jtr~1 z9;Vt6kZh=2_I)1smVJ)vAj5ZlK%}p!()T>o8(B^5Nu(tPclC#Hic*(^(Wc}^0w&?M zkJP6KjPFUd@IA?Q0q0xDPlC?(BrpRTb5HbRUUL|&y_9m62sv3V zdXtW++NTQA0X+!yIwGjodNZGDz4rt|t#<>YsS)72)Ovp2b$w{WxeX zCjrijX%EnOG2IG>UQAz@1W+-}4==o!o(0lSOgn(ix6i)?ofp$+P-HQ+(}`+&JY@72 zqv>1VJnF#A59UW5ERaVXAQ$#A`TpyvzXwBS&`9*3{5^OILDCqY{Ae?8M%WC^xQ;~k z5^{#?^7=wvq)#Y@n_WHuG3A)dj2#=y8}}ZL*<#wyk+=$;637*|fn1zHJN*(Hjl^xw zXxx4z20g|t9f6xKZi(bdyi5#EyF)Hw#O)b|+ben`S0aC;4QeCkmPog_oHN1YkJ$-A zf9px$uDRH*m6#EW`Vz|#jUMA@jo%2mCDJV}ju`xL=mgN((j#|0#zM8k1dPih_9GfS z#?dg%2)ZTGEp8ey_~VkPpe>mbfYD;GYQkOJNuD(xP2P z*ycoB5%fF4o~zUn#TZuez`$E^j*c$pSY^*b-Mb9sDbSQ$+d-3p-ps z3x7q^@t>Z*3hCsRpOk9~Cp~;Kfom^p8IN-5#AlVjtrxb$RZ9mSFX&5!eP7s_vU=9v zFM@ww*f&l7%)b6DzJLffQP^9AeJY*!EEe>Y!rmxs>CYUWe~Z5*CI8>8Jvr}p1iuf~ zRnc_`Df?xJ|U^8XY3!G9Tl`Liea2c}DTwS2fO zY;*p|Un9xC8cE!fbnx=0MeN!OLIO z$iK`;T%L6B@+UI#&n^-dnhsw6az*|vMdIw~;N{OySqX6YxkUE=@aCM+p8swB$fY)2?3#bMxJE8bF^BSh zcr8cL%b&d>A8o}nTm@m*6Sg@&|1Dn5$A74NIh`)&lx2KAOD8`5MYR~_5cWUerF=PK z`A>K`d3RXIm+?q1f23SFwe(N;rXpQ!gqiLzqV5nP^Sm zZVJ;3ra4Rt7^1g?-5RD1Ob0>h1iK4N4;ZZfQTo9UcA&7yJqT`W!Qu2_utx|t)-oxh zVaC9W6}0iNC%{aFnJ#EEV9$g}f|&=i0A?W!$zCDsm9SUAd8JM#$=U^_vketh~Z@~Nxa}(wk z%x#!^F!y2pfO!b>80IO=YnV4M?_d~18G-SG!D=KW3rsec>@Xxd2khK1K`?m)EideR zFu^eSVXQDkU{sh$7_9VFFpbImmxhh`NTmWyML{FEmEf)dLlbD9!c>Q$0v!ue3x+Ut zVAqAI2NMU=5C+>X6|8eturU)yE2AvHw1r88`5dMTOgESwFuh^02~p_}GY|#~jTB5- zDwsW0Ff*!Pf>Id=Lz8ouj#Mz|$itlsn4 zKdWGonzA0|E11nNTVS@s?1cFi<~x}EF!-f{atMafcLX-J$towr^M7EU74Gw}Y4Yzk zn9DHNV6Ma5fVl~C3+4_C$+-*r512yg+7HJq0RtwNsa)h}!__%cTR;w*vzk1w%Rg3js{8e-2_a7Izu%Kj?khBZe zU$)Ge>HL_2g=VCV3y0sBb|cR&OG?{vG;qk3>R+^fHM``%yf@aD`Q&*B^9wmMdDxw( z)YT96-cim!c(Cn4o1TYuH%QI5`&ExG&Sp6OxMsfv#h2P&maB`nOusmDMD{~{pKg8l zFz{}f))7{AplH>cuX}HQw9e8oPkH;_MT+&!w655t%eI0ybB`MxakgXOl8yWqe%37} z$CRdj54!%M!1NN^ayRQaq(VuZwf9tsK zUP$JfC6_FJT=t#+p#4q1`On2VFK>E%7P7Z=(y%TED%I}(rfiRb>b`l)s}~&AZd1fZ zeZBhG>bI=_d(+cmOso3cf#mtJa(b9alD(*R$HsC-+~h zIj7*_#$VU|w!&veHq9@#c43`yN4Do$qTE~K*Zj$b=nAE-e^F}bqv0i|^xrtK>vzLz zmOMFT#;HcnXOAye}hn$_(E3~t?anB)aH{HR)kGe*L7SFlK-3I zJNkR|j+>A@&zlLu&QHBNGuw!JdxnQCJ-DXCtP5?nPak$hIanm`vo~u`HY?es;Msk% z5?*F0y}51WN0t1PB31wDIC1;P8}`}i=ik>XGrQjY3UOO|TPOK{W-A=m=h!{pfE?Yv z+p#=k(E9J++**0CbDIli&Sh$_uEqGGCA!X-zB|{w5rvok-6;6GFWx-r^NszNYmdVk zuBo^~9TJxPqFT)nTcE+jCbRpVy;>%1&bs#VYF|6D=!@8FTc6}U)?oazj>9@1>v`a1 zwF+&bs^pk5^~AHUXaAJz*PlLJR;JOfeFocp&G+?!WB0##a&5csZbaS4^O(DGcr%w zvJ0JWOzl>AN4^ZdUuaoAerj6D=9{g%*ED%iro+4uZU6fC1PkhT`K!nwk%eAuIrPnt zU#br*eR=Wh(y1Y<{_ayQceh=c&n?`&aODN--2v9Py93JhDBtc{N*%}M?=KH+x9L#5 zoI9(hoH!8w{myH%ee!t~j9go7dBz>7o6iOHS-pAJ{*cXO4xL`n{e{}{+L6k8-r6hQ zeXt`S{L%AUZO6YmnJpwsz1*!lb~i3@P|Cd$?>yaHbvmlFr{wtG(0r z_m{txJ3S#T^|AksJ4YTgE8Ao6!$sG>{yAk)k6D{LZQE0K%SWSAHV+%(*Jwl5?iGWk zO!8`Ye^IxwUB9zUpME*l=J{%_d-+R;ZpRM+o(##jyylJ&ipkkR%WQWq1eaGdKNCZXzR&l-@Mp1a>g&?rVPvOz8_r2QLgam9SK98l+NBD_1>hXWA+Vc8Z~iUOoKm2j0K$|8elatqqgg z&zo`e?DcX_a%SxI*UbE*u5BB!w%D@6%?ji{ccM$(k+qIK`?}$u#aH@=IWD!03mMe( zr~X4Wln?vsiGPa)50>@&dAoO`J6}G#A24=Ln$=PD;f`V#hCW|%yj-2R59UXfu6JX| z)2@>&6SuFed@-))(S_?is(NkU*kQ#oPx3z)^i}i2`EJk89=&y0(}veOg+$LC_TB9- zhIRh2_~YpX$1QQpI@Rc8m&|Q$^u9Of^pM>FTR-kF??{g|qlahDeZGBoc#$x#_OGg3 zD&rk9cF2!y`#sIvwn*E;sq3fBSyO9XuS%=yP4C{X(5}|2BX-o?RPF4A3@x6opOJfP zhvpfU{Hfet)^vG&HK=f%O@HlpYkzb0$oFenj(@l7(c-<4HM^XevAU99leLGN^nAJI z(VcRQMlG2=YRc=~Pu~x}c{Z%`>vh%s-t~0R*)Bg>Vn%pxU;lo{iS<=i-F(b;_8WGo z?~+L)i=Av-wndJW;|e!_;+^|vOOtT_)_Hzhaw~kz`m&e9d|s_Noj+#dXSTaHM}Lvz z7`m+e?p^AsPN(C$l)Jm9L(U9CW{-(Woj9}oEAL-U2DGaFUAgidf3JF`&Hp3rEugDN zwm|KZ5Zv9}HArxG3lJcBZ}+a#XD%{x-@5-> zuNEJbuHIE$waevnm+1FLr!-SOoVdAiO!ErSdu<*#uuRcPeq|5NJ{qG?v#5>Be99iB zs@K3gh4yEOTFC{S}txSr#q4t^Z?ZTj1_bFR;Jv?U1XfR`jp6diSE;-6DDW2VC_%)bPgj5;sRytQURrhgG!>oY;IP^kR&vey?NH zSoVDA;!E}B{O*`uXy3*9(LR>S*S&PTF|G6W+I}E<@W3y{&d1#9-MzuEHj9?tI=X0H z>}P(_9xgq%c=+YIMSZ;&=EyzPt#x3&BDW{5@#$A;^1gC8n;mU&u1DCcwnMsxEZfqv zLh(4abAG$~IeL`q6R%|HyKjEzo%8LR9~jd9$+H`_p5paj`13WxX5Njk=xnpUlC|mOQNppHY^sijA7_u+KQN@x z%6RLVmB=v1|MjCbL$)UE`OIy?nbx-o?0+=>{E0VFV&^YBCEl=_Z^M4OvSZ8Ek)=0X zn|G;uspFq=A2?OEPW(Ze#!eYoutDr`kFzF>+C0PY)=M(I>7Qd*joCNC_Ro*7=j{1~ zZ)YTWkg#mq=Lr~tCuB?wa%O%6OoLzu1v$~3EfHgA@P=uy5rQEEo`WMXzhDB{bjk@0 zp$i1SBv=Gn;Rr-a!m}V7)CE8AhjB0uc0w?O!gFx2VUrFjKwW4H{tyJq;5o!gh75Q? z8Q2M@;V!&}NNkQ&fV$8Y`oJRC3m!~5<3Sl{2|ZvO%!9RX0M5f}@L;ne9>}MYOF$Qx z2FqY89D&R59wMc3I5I&?=mR5Q8Z3ig2!ZF|of>^X510gt;53B7bBL7&y+Q@33vD3? zR>59~mzK1H7nA{CXbAx@4uT;R%CJGv6uLkFOoF{2UyF*Co;(3BCIwXhd*<|iKD3vHnfjDT728R{0` z888m!!A3X$q3|3W1&J5rgc9Hbe&7$|U>>Z60}u*{3ZY-90Ck})^nnpD4OYQUcn^^Z zBM;f22zWzN=mG&S4z|J(2!+>Bp$OrEANa#KSOgp42wa9pMF|(Yz#AHZ9|XZX*a^W9 z0`DPGG2|f=w1mBI9v(uG;)DTBp$i1SIG6_;;Q%~`G9}S5w1hq|0;a)TSXPR3z-f30 z?;%oY@(g^SCG>zmm<9*nJcPk#h*pL?fNW3%yrCg z@PVe#1p;6etb&~o3?c9u;#DM_;0-OI2L!?@*a?nG#2307`HyrCiZfj0nIqN5y+a0H+I zfSaQfi(U0&x^qR5;%DIU*Qal8j*H3E?I^!sm%sczyEz7dm`FW&;R1HnEDp!|CvJ`| zf4MpGaBn9IViO~{JC3m!HX@e0V|z;8;GEjs(TT;Z2zlKdb6C*ISHRtIl0~i4h52k^ z5q==cN1_5o>a%v7kyp)AA3XIsm^Up%;kpwGa6@3xJ2%HRxX$9*OM!*8hzTJH-@OAd zXG|K}5$iI^)ve)m4fmWZB4WxVCvUN1k@i1Wz{^DX{WD7_)zEV&y1juuU!ylM6UjTtLyso>G>O;X)EcYq zC11*(1;4V{scDV+Rr7BGKbu_+V(O3=a@Xl++;@KD%gS>9>n07O?Gg>sLl#~!Zi6WU z*qh0dF!Eyoc|Q_;r)R;l5cyG!yl7=~FNd7vsk3&tInM1@|Ah`}c)3g*|1^2F9lcC8 zX_t2biS*}w8s}=fDoFksgf5(KYd(Bm;~AyC%D6Xmcf>$O4(48tNjn~!HERlLruYuW zmIMyRjF)bX({J1yA3wM`I(~I?WQoI@wc_(rz(nqjc1bmiLi71yFk$49#av82^eWev z_G;XHShSY3Oa4mUO1?^-N`6XSNL`c}Pgb4{CT%PH4KW zvUAZAJ%)z8Zkdc7RoNjWH8g)(2&-7$O=@7x=s_rg=|B&52X_4?U3`MEaj9c5X{ zub7BDUu4Qt{=~?OsO7IX9rS+LVbo8qONXZ}MdZ7)gjq5buY^eB?l=fyhRo5Ou+`h$ z994F^IS%Y`bBx&Q=D4@d&CyI2;xT*AX}FRWF|&xH+1-W+}SdkZ=ZmeWO-C3 zcA#EIxO#0hw_z_`~5T0{<4X%0dhQcb1a8+w2`-IYpPRUhErdB zqETm|Ty%HGJ}5$a`7tK%7o!YapbR~x3~kQM=SIBT9rvlL1M~A^^n#?bio4?ozZP2i zySrn_XnpR05G_AaS2LRSZ8-TUcVCdUt)xxN$#5F~^lkO}R2%TO=3u))%Uy7xP6$sF2}4M{X^W0qit>j z{R30)<%O*htF%4!dD2!!=DG!Wmzw^qKY3J;J}o8Xbqo1YEgyc#m*2=2F~e#1!()G> zeoQBRvG!61AeU+LIy}=l-PN?Ar^!Pp=gFwsJCM(fY)vCu?V9Q>bvX^Y{&#)M=OE2r z(SuV53;0{&ztptZBhZP&NBT|aGo`B ze@Fc)K>nZUsP}Ht{)pdQ#9hqO|3h8n>qcDgH=Iqkxl!F6hbik#(CItM`dD&|VSF@W|^%=)D|ZrDZrm`(lYPyL9DZql`Ocf>|FU#TA< zz1H$hR)%sOo^n3I=x9FuiuhS((lmg)65odYpPA3E%VKMB((9^*#B4NtfcsY8?CG5u#M>QN=?(XOvt z9?3hNP4v3mXT6S0ITbT5Sf73Skej0g z<-02FTL;Q_Ch|{Ajql3EO7c+3>u;2alH|!P@@GIQ#t!t2-(b2aZ@K=`{M_WM>)3yJLQ! z-oHw_A%ArvjOC`ikp7NrbBw0%kwdcKC?~RZ~RMy?G3=YE`m_WO`8cx6? z=-ZS$hQ`fk?_qZ@^aNhyZ!J?dPo>te`aQ;{afz2-5yl-Q^!a_KsxIET>-D3Ts;int zw@s-Fa!2Zc)B!Q_jyoyu6{vFq=^K~PHzxh+=D1AX_*XpSsdEWUojXt8BJ-KaT1ey+7c&-XCYun7OCU8Ka_~3G}Hx^r`U} zC(QC-z7v75S`6v{{p$?!ttJ`+9PCbBeG2I=t=^HyFpnlMX zc+(f%<=OsuX(RLV4IQ3cmNHdjv_9|hAWf%pE_{jj$(<15afdcaOo+dp56ew{UL>uP zNb6J5w~F*lAnYuJy&r$|3Hv4K5>wseL&0vE|Dilj{^~<{7gOQ2KF6mWt8$n&GN;#GOa1ilX-pk$bg?iVC@q?Jw=QPZ@lzB1T{>SlNm4#Za8!XZ| z%BO|puWa=-{AtZ~Ty~f?!JYmk294Bg`j#5>E4QeS2PoSgDck92%coMdeQC?v#V5}x z+Y?RMKEZrILaR$Z_RZwM`*P|ga|D?mh>0~s=O_QvH=Z-`y+7OX;&7vm$rvXC@n}dq zhEc~pF#Z%HuVRpp+meSzOr4AvqUo!GzQxp_UQ6AmK)Gv5*-B2?5%adNj%#K9FLQsH z_sg7L=KC_&mwCQ(j$i*b4YLa}Vur3$ojS)b?el26l7#dZf|;auhe>nF2`YOhl0J9- zMGfn@bOx9+rrnv(_*%?S+EDrHb|sa+Ge+f|bK7(DHFCc}CXr^HBuuZDnSQhoWlH8a zxu|PTNpm~u*RK@M;h{HetdF~+HFd6`$?r?FArh~;Y}cGN zRK|DJXh&s?cgD1*9nq20$-LD2SLmY(^*$=~{sn3MowTOTM;k_3tDAbC$JEI^rcSmd zza!#*F>S^!{4LDm?kJ3Y&f%{E`Uz*+*TS<@CvKEkG3{-V@cNS?KKsu|Dw&VW$XwwmEbq%YAatQ@jfQoDY5SlO&uL?xHI5hVN~lMv3kkU= zrp+}?&wKJbMs0N)_&@Y>`TJ=6onx`6w5yVy{N5V&N^^b4T-Q3U^3FOP7u`r(QGuAs z+G5(|uJy&jw6PLazQ`I@hbwx$rlel~Y3gbE;(A?yawUCxgK&J^3+mCY_JzSU$Qy7Y z|I(N|>_Z#%-;M+NT+rvMi&&(Oj668&3$}~D%NIFkdrLV0;o|yij z24zUnF{P%)Q$DpV*NGbH^@Q){EAjJp0Wkmz7ZLJL}gA#+Ipwq zWAkY#`=!)xMh>jXUoy7ZV#=^5&yn!&oAy2mx)&K46FbMl^4dgklQv)4doeZHM-zV? zJ@s1NPiw`~gj4#SmS<_##9X|r_nq^3pTWA`BV{82^F}e%zZ=8Nysdr;*3mFVm^$Db z)2*gIk^CA>zxF5nS_Ymyoqnwd=@(NiyN*Zx+qN(MS$*F2oa(>s3Dt$H|35eBJa<}U zyo^lLP}Rc~qZgkvdL6!qh9NI57QMVN`MH0rhAHz*nPZCSZpHySq;g;iu?{7^rJr=J z`^v{qMS2MBnwZ7L&rRc}745m)52XBwsciHez`R*ZX;bH&bNPdJH6AtVGX^#FY1=K$ zv)|3Nd;~$t_HoMX3d;65!VWZT#F6lZ$x~9fu+@64S+QhUsU) z2F?F{EunRo){TB<4pxeGPTJ=GW(_5eX$PbF>GR$X)isb7xTmMhI~av>OqocVhItS8 zmr}XBj3p$V1L$wWcr4a3UU!M6b(9%Ly!F)kd3ZaR+;NsU`OcJF2bpy4nW=SC){M)= z(`S@J*HTY5$7X(uTWCUe$D1U2Z_9sCPo5vuIJPolo12td@f}Ecoo34H{PQaFyJ=Uh zn6|2LE`5%CL{s8f-}HOu$a}etP2P!F8miX`>0`w_WzHgZ?wY!_khzOof8C+-3h{+4d*KD@}^|!=h=5@@pz=qE@axB z;>T5=vL+(yA+iP{>mFjp62AQP2l-jEu)6hlqW+!hYkTf$9(S#$_aB+IGF%iZ2uB^t zyrj}u-s2iwIQLe(2LJc_iLt+ESkAS)$#3;KVmp2IA@l5ark$SXrT4?r4~VH=R^#fN z<3y%?m9iw`Fd2i%_{%x=+Hgl@WsgrAw>V&v0*a$U5CUdx9j z4mdO5>y^3unjZaJ(^G3CfD>|HOPnl@frcqx`(ylEd2F~^GN0hA+ zv}qCJG2W-nf#+e{0HNx-lx#%+wM2ke%r3f~o7#s9S`y=bHjZ8Zv>#<)AJ8#ZJ?|TmjzjuO$4$w`xjX2v&380Xy1UW)9wZ_xtHlV3+dmb9d(Ws zu3y#lXIXQUbw*iRlyyZJuZzibNcEK1v`^K^H@S0`{-S+bm64D9iSC^J!41|Vq#R!= z@9vN}(_iG5bKWGcsTNt;cNKG&v6NiPxK~WH5xT}8=ON@Qgq(fwF?oHExQdh?aqVW> zgj8leeyY0qfAw9xSb0n9)FsM|%t!bC?wXUvV-6?JcJ70{Kc?Y(p!*mm{S!`V{G4OH zIOaMo@fNfEz50>1*Wa|iLyKtoW$hy|YfQ3d)JPV6F?Y}#Rm4#X|8F2AZJe~@GCz~@ znicY(f0^4#-EC~@Z@MA+9GUaUd{4}~VVbs@5tzfL<{Rgvuh>Yv7m56mv^n=v(d<@F0?)!|RMBTZLL`5b>u!|HC>%hvQ19Uhl1@@$)B4`Af>7ltD4_ts0RIpqz+#{!-KJT>n1*-CA+Jp*q(1 zxA|2J^e*8hFyk9Edl0Lb@KAuY0ZI%*K*2*hMJ{Y4*>S9Qm!E=n`^So5dq z>l5Wv{&L2x7wdiE`!~v^a~@Rhjrx;5Ei;G-e^ApZ<3=$fa%)> zV&nsF5)WBRl653mLz49)F(+qg_|A2(Ge!s9Nt>9B&om7+s1v!U6ZNSRQK=JRu9ZIZ-Y*4D*LysdRj=EvEMltSanGt=6=|`I7ufO-5AI*@%MnIBF@56-h?axQYtL&i@a^G4ZIlDVVoE6My(_LgK0Df>$@kCZc% zvd<**N!e?XIi>73$-Gj|T*=zLoNbeHl``}>FRQ9Q4J}T!lWxq=1rLt!wb5q&3lKH9ZUCA6(&d=B~1@ zCG%I=+mbn~>~G0DR`$4LF8jU^^|%PSg22-5j#6cGe%r=J=eQ3T8^^Ax`(ZNQEi&3Q z=atV=NuD{|!flr|51nV&>QB~sEoUp`Jf)cJ-_1`~@6fixIky?fyjYep<$RC_do*%J zs1V3Gp_U+Lg)V`d7n%feW@tIcxuM-4XNS(2Hsnng(nVOZ|0w5HWe-x$uF5{7oL`l_ zNIAnQ`;l^v)r}Se3*xbH4mXN(oITM?lzD>pzvd`%}A3I`!)+1-T zST>Tj!5gUaoBOysN{m&#t{~H7m`1~Ny+_W<+(t*vb28D)`lX!TbDrIsHb9?sF0$p- zvE+=F59d0cd~{Dj{reuktY^Aj@qOFSV^6nBdR^J9p$<25vBM@^r33W7bM5N|?XNtk4|;Ttk+uh_ z-oD>cABw(2_WlkxdtKlo{h7Gst4vv}s&VdZ%0UClxR?m%^qDfQ6?6H5UdNP)CT4G_ zUY9lgi<$P=EWtQ@c%JmH(r!wdDea}Rtz0ui_cGg4|K?Hmj#2N5er4a5`W7=j^Tb5V zZIkMA6Mmt=bIHrDNzudZCRQ_DoQsh&F>($@&c29w*;V~J&+3U=sov^e`cE;tZmEpS_hhaoCLV5* z1J1pqo3x2?E$0!$$Ttb)TE@>}PW99YDa>)bznI8X1tPOj-m#aKqh z>EHJeQLgD4gq(en^Gm3z{zHUQ`C28xi+^+xJfWm-@>?T*b6t3@**w|8mCU z=_d`-Iq%MoZY1>b=%$9L2l6di(YVa}#I(MlGIF+gvuSI#hG;m>bJ)v1>a}w{p~G#x zcAoL6{!XuDUMa@wxt0UjPnW%P*+-W>bTQvdottjzT(`&SSJp1X%>M3vBg&NIgUqr1 zKELuZYi=*8Z(_m^)pW%7V2qhk-4atrr98?QNX9oZHj(j&nBXAoE97@G&fm+(Z)C*$ z#@PkgA9Sug{(YTM?w9zr>la~-lOl90HV_Pw=O#9N}T7I#=lm#zn{H& z!MH*6JB~J>8uh=PsW(xWi%Ce%HHkm=YJHUcTg*_?*E!D_#66*Dbgrj-pnVrfnODku zQcNfXoFS|A+XDG5ken;~*>4QwteO1IK+c;ve`_FT@k7bmpZ(@Q&ZNoj4&+?g-+y}` zzcZ5GAIMoX`3-`cSCii%$eA_yErOg|liwrA*){n+($9XEu=$myV^TZDhNgTMV%_Iw zI_r1Xlnc|x4Y;J&&h@*V4>c?~hv3|^SZ~IA&ND$PkEx8b#m;tk+)vJqC7-YPQ9rHf zHt%J9mUG{>!Xmxz+^;%8J(v7+*74(0^$fw!_Q0KCKEI%Toa3*`^kY&^Wqn!JmOHd! z4o2OU^<*(CuthI2=al)N%)`VKHtU7*+buDD$VZ8boLLaltgyya*1E(Dp)ZyD@>@MI zDT%B6CFj$`JoD1C#j<`aYu9)C>zcK5y}ERW%F8-}n1+-!X$NHeO3uN_8kX}c+|7ZS zCi!ii{4US>O~ALm}* zUlBD;@*6iXtwS}Rp`k-^4EB;aS>l}MEeW};79w?@((YNy~$83{6=kMA=7%L<~PS$4S43@0V z$~i1qqm{E*vQ8`Kv1F}wA;@~|ERZ!@Ih!TxwsJm8)^6pDmaN~(IW1Ykm9tv1j_W+H zRcw;BZ8D~Jp2v*E^Ci{J-vY#9-9yTm>;uXEj_mD-$@kqFoqPpT{Dq9x`!%uUTK4tD zOj)SqO%z575c~)Z<&yY}@=a!uBu+)%M zuiUm|q{WhV$T?+Xsw&97ff(`Ql#y$Z6(jCq%k!ljhyYOoMnvthazxaXrhj zkD4Q*rpfLVw4rZ3$AYLMq8?i`Ax;o-vtSkMgkT7PF!&772)MH;Lz^WcnBI(QBo73{{n2aUY%hbE07<+T_ zXGZoH#W;0Sn#*CRo~mpaNxSGqT22pZ7fI`owC6Hjl``nmrRYjbOx)st3|nLiil5Hd z?*ovjE9LZ z1*XCbm<1BHWXXK<_af}Y=5MOMVO%J7G8Mfqn2N9D*Zo9Hd-H_$RSX z!x^{;SKvB?g51B2eFyHsV|W73K<+)qehqKn9ee;Oqf$7+K_rL*Qf6a9EQkZ~AR#1% zB#<0ZLTZq3(-~Wet6XQo&J0;0J9vV)=f=)!{w{=F)cjonTgqY?s0fw88>&Ecs0;O= z0W^fh&>UJoD`*Yvpd)mKuFws7LLcZ0{oywVfWa^nhQV+c1ron8*!-l}dUq#F4c5Cm zr(@5AIY4*KhogCS1Bg7$l~u>&-JMif%Wa*pH)3xBx^C-To*Z{_NK?r4()tP9UhD%v zS75)(^E7{-g$r;AuEI6A4!7YB+=U0gQoQv%hQE%d@XTCGyjYfZFjR58fe-KzK7ri( zjQz#@&C-@NaA9cR2nP%e9N~dsh$9lvbvmK}LuSiwTx^Ct4jJ~yFee4bG)ltFh@Ba- znCq}xvn^SM+KvKH)La)gb_wiK=5Gm;Zrf27nC3XjLnWvJEZaG1LTwPa zdd8N&8}fH!Xb!ER4YY#}KsW2?2qH&!YuVkfyMuH~3_TnS6J_Y(V94iSIOSm2lqJUNbRS)2X?h1})yxp<%K#iSrNg&Y!oT-@}jT7I;Le>6y4s-mEoOE%;R7Q=@_3 z5-z)*<#GQnQ(oQ9b2I0xBKh~F@oqJD!Ko|npLCvfF-D%q?|LWfQ$FDHyo`_IUpgLd zaR2u2&c=EcJ5zSA#?!LLD;C+;2&{XUKeJM~55}D^1wCroqa7WqOpkm~>dcpF`H3o;P*F z62?+P_K(=HYx40|m)~bguxRF5uUp}}w%&Lp>C3Dc*Tvoun7M4_D**xWF4Vde28~`b zcD47Wr45r7KRhUMmcKkoweR0^RL;?xCZCB?eEXG%;cv`pGrMp21AjKiI_YlfwNGx$ z8=igMqDrqGBpzNpan!7{9#x**ZR&_8$^E{*&9OdcQ|giNXZViqn4sas;%{#yYnp!S z+;S5$ya=AtrtQU+w@#MYKIvSW3<1CUzYCvX<>J8ng-5n2+p71D<1g25Na7P`{)$N> zDQCZ={?hZan<3iZ(cUfO%T2QCC*VB33+qc<$ zXTi1yahiQe(V&6<-9=4P*Gtu)=!fWkhL4@Sd!b1)Z~2DzJQjCp%zNHjPE0Ja{!^KR z8?TNpcKFre6poLL{>VJ)TKOV9?|1FyKfg?HY|reGT9$hqd404jvtt$Ck>J@Yug1QO zd%a7s#-oJ12Xtq`i7O)Rn&V$R-r*vhk_@QPDDswug=dfJy{v!Kb=BJ+<Jsw6+`E zs|ELOop(jK3e(*}yidgP=kKT`+HRZw`D;B#y7cXK&nw*V_>LRDHJ;uktmgABVg5OK zzF&DO;j-{SyOyum-}T*r(>rP|jM#kIrW}=ao)l;1mNeAkL~SM^I+`cw4a zGj$RVni6wi!BvM-OqhG8__7US+ij@%?Lo9_x67YQo3l-^m(j=m_OSAT065ip>+=hx zT1Q_wVOr8s_wHQSk}ZDmYFSRUX|!p0`-{om3^{lu=d9~#yIdZe%V*U4=*Kc7&pWio z6rb(2vvzF~xN2zmv2Btqc^3KTj-VN{>V?bPzsUTn=bPkgv2%R=xZ~?TE;f04qIpY? zf4Deva-xcr4h$JT@7}lyQyp8}r__qw(F;D z>-vm=f8;8W_gj~DdulbSB=6U4o+ah2UH*AL9b57>MdWC0S9Ff_Tk4xPGSr&7a7a+q zQ$_1U>f3h7nqzLOCyp8w@K@@v7_YMCYw~oxug8bvbBDL;Q}#ipXugL+n~#ssCFS7g zTMHJBH#h6W2HR#`>HV&*_u%Orf(G>Q`fbekL4*GYuJeBGi6&bQK8lj|a;#{*Hr}XQ zbyW8g?Ov`=)8|T>@|9xT+ncPkyr*@h@4m8;W^eWNDC$_yox**f_T7?^ZnzE^D)IsS!`o(!Ls@H{TBcisL{PxO# zx~=ZWd!{q5IQ;4G^w-A@+${Ab*S@Ik*_VyqF7H-8+^%4Y_T@K!J)F>OMC3A~M^DfE z`=zN3d(1c$Y0JShR1cu`zG7n{|ED z!!qdu@4im^pu?jbkJB{qPkH<5=9uM{4Sg4*?VNrG%T90J>w38LO`3bvj+Z0$uJ-(eo;d(kQxGqlcBwZMq2Hy)0?xTryJ zgN?1azP|HkhR*4d<@C+{CZK-a>`CUkX|HkXgqfHlbKG;5W%8hSXR@L0!YE$<2onGFpH7R7~ z(=!okw(q&K(%ivOiWVB0De~?y51&_@8_Q?&%!uACH@Cf=zV-c~1$&>%-feqzk919k zUwQib&Qcd5H5;}3MT+M&>(`lgu5P0BU7JLETIu(Y%8mR&j#WF{=5>wZC)b5kU%Woh z|M{&@&!kJo&cCyL*R_uOt~@?d|6BCQYyL>LYe9j`{dUeizAMY%P@jEozl`tMH;>Qy zOP5C;-1;=Q!&$FJtxoN#TB&S_k0qwpUlecp_Ax_yKNxeOSc-kqE|+{VaP_{n)!KZU zd8=#8Pm_8kjkmhl(K~P2x~Cj*V&?8H$&0RV&+WBm|DP-GGY;EQbxPYlxkBcpt~qRB z&ar1p#+yGca~(I|vjcaf&sii}f^t(L93MD0{ioB7f~MtO(Cc%>V&}88i8Xjbw*51c zHgPNR=}qWwV?LEWy27nu=i0p+cJ02ieVVWs)A!uZ*YWp3!&)Y0J`W>dHmrp|;UYYO z&k!>S^AZ>glVJ_)hYRo!>%$}tqHB6F9g9{SPut5-m&@;!l#lw8|H~n45~v*=nW%bHmrp|;UYYO z&k!>;>j;n+DnJA11cM-B8rBWK7urBS7!C7a0~~@Y5C-2M4vP`#p#W5d#?Tc4VJfVE zU2q!iz*~r%4*h^9l!AuP83w~-SOz=bB;1165HUUaf$UHMYC>!13qdd!*26)#3{T)I zBx0c?D-?t3&<%#dG*}6{;SAh`cMv5bb2G>ZrJ**o1AiC`3t$r*fot#-+%hr8hm24N zsz6id4#QwNtb#po7Vd$(=QV0(=75k3%D`-pcfI}z7vT|nhL~B%FUSiOpaFCOIfK?D zD`|qEFb!71Za4$-{?~Wl#R5@zs1F?>0OUhkOJEzEgZuCSqGe}J3b~;y)P)W(5XQqI z*aFAkI=q7@EIcKLoKPBSLpzZ7!H$ImunCU9HFyecp6CoRLLsOEO`$ssgL$w44#5=& zgKrRrHM;ar04hUc=n8=_6;{A5I1P8;Ekw>mc>_-<1+}0p^oKDpA2z~axC(!Pd|)Ro zWPpO;4NagM425a15_ZEGxC`$fN*;6pIpI1)^Fp6c5Nbke=nE5J32Xy-PwY*22|4n! zehKnE*G@19Cc#pW-$|T+P3Zg$K0F|LJ zbcH~e3M*h2oQ6B_79tlyf8YtFpccq`U;D!tm=7D_FkFSdz)=|eK?W!Y^6u9r&<%#d zTv!hW;W9jduMoQk@qs{?3M*h2oQ6B_79tlVKHv$Zpcb@+{xAmS!$vp>x8OBIEJphQ zUQizDLq`aJiLeB=K``8emk_=t5g1N9B4#H)40$(9^ zX~Kv6Pzf4A7Z?IlU^(oBQ*ayJK%_G4DMJn@3BJ$<`oUsb|?Wgp*8e{Aeam5;UHXwC-4_x2!n4BrxNLf z0#F$mLstldsjvce!D+YyZy|DJ$}V_9DX0bVp4$E}2Ij*?I1E?eFObFgxR3z~g1oD? z33P*@Fb!71Za4#X;T=S&LR$nmp)}NncHj?VVF7G{BXA9#f?HMEWylDHpbE&lY)8OM zSPlE&JiGyUk8M)O0VP4+W!nb&!DyHV8{iOJ0eP40H;Chd?m*sWTNxTdR|tfuaFArX z!SS5rCpKoSmu~B1Kc?HoIGqa6-NythN5{21fa51c_aEUBSqLy=mKJq4OdJlJTYKbr^QG~|lyF?^6Jd{I1G;rVK) z(}4inY1M4qaBL9Qb}BJlpLlYW?hg{|1=f`%_yZw!BHqW-haXOBJ<+F~9hX*xRQO?i zJI2G8QT!yvA1&c>Y`2i&XPqqTeQ(S1WzPb~$!u9*Js)mau}51LULC#XYOo`^*fHI1 zq9wb$MuWAO|1g;P{Fj~CifkvvtZ<^w~DQSvDqVTIxksWji%YqiNY(({|coiq5mOcJRHjXz)+R z^D-qKg(=!sowBm=X;M7d6!Ys8bMwSOF*L=QH`r&$5^r;ZvfCq0d9&CB zq^U`L98zx*akaKeeYO!YP#HhX2-7@=c9kv zq4}C;Ms#U>i_v8wZkcFws;wSJjIxt7E~-XjFS~6<>Pkz^&|2s0Ck9;6_&=ren8GpF zNM&|O$&YvB?mRLWd*%!KDGS`xe_R>>qqsH1R20`Zm;K;jrV0#pRe|3!XpFPHx04#a zj(RM8%?>La6-2@sKiqy|xE1PDF`pfLRBE|MEpKZ}O`$G}Q!`4GN&Q9BY^8BETRkeN z)R7Uk$Eb_dX&Uh|2^#IKn(R8j4(kY8Qxg0nT4NJ@8p@eCeHd?tRfqAXsO?ZHD=d#e z_MJes0Y&(JX%aRl-WK z(k^Wy*yR(aDpBmP^0L7vPI02yP97JXNPr&Q##`DC|lYl?{X1_WOn9nmhBbCdP=-RmbFl=ca%3|@)xkIm4z&8 zMPbYGWT%{aowe=#Nc+T9WVX(+a{F3Vw_29VCMXM39FZ@?95uE!N;J4d03%43hq_yPZ(=^EXA(0cq~iDFVVz& zGX3`BRd&3NlYEi7e%Fq~YPOceDQ8pLgA) zyB${YdK!uHLAF%lg&O?*F1Az>6NzuD?M%BiC`y3-=^Mea zBP_J<%r|{;epg?dZL~hPV{|+9OK+&t$F6o#%g$G)Eq{yNbxmpqO1;t1h%OqJ>l5v; z#+fW=Mi!WoH;Pj%l8AmY?J+{_GwL)kkNw2hoZ}Fw+G*|Jo5j%J3%0Zq^qJEMB6XsH zE%lXzh|{SSw$vHM8RE3hrODN-rifDwe_QJQUX>c0-VQ61DeF_u*;ybzlNOJI=%`I8 z-q%ONieJmll_zV|$^V0`i8hP+s?V@PPD34)R5rO{ zM^?TiB2K<^kEZO&Ps+sUOe$N69crpn{E@cD43|`DHEpKRST&=>66Cju#7Np?32WdT zJFFqKG}Tsf(R>XnJl%{5tMqSLLWa?x8K?fAZrc#G{+fvTghK5gSJB67Vxv07A z)Tq72{-{g$9#b@`w>iXRS_=R0>eL2Bo7~P|!kSBCZA#(IB^p+%AUj@7DC0CZj#<&H zur|fEtftzNCy8raUDv9WHotY%LVNNCWvr{2D3v%g*4}!K_SS^w2r_+G>>Bp7J{hMo zIGIScGVM(S+8dJ*4UN+$CSE3Wo_LUazQ%09I5jrauD7e&73ia>D->vl^`xR|JtWXp zOTkzg)}9TvT4qrSB>3hoO=Taf1*Dp*t$#U1rQWQx!&?KT`ki2;bya_qWrZJYS^4Rq5fM|}RLkSz z>`JnL(juCQO2IHW_|Pj=xyThoRg$4AbX%Og5gvmded zfF>$SYC8p^lWW|j?XdIuayU)Y%3ij|%x1bU?+;r+V=`*+naNV4peFq^_|mSCguF~t z?v|rbz&`ZMe#(N4`jlK09#bDYUTIuTma>B!u}Fh-=fNhk#^q3{w@2)-PTyCjkA-cI zT}|Bzpt>24KAapBg>-PuE$X*Yj~8y(VR@RCqpYjtSZXGx3q$O%Ms(8Hmy2h|K1G-Y zKdGDTlw^}iZ60GgMe3_g?Oav2d>f7Rfvi>5iSO3m6}dz?bUAeyY0 z!1nmKx<<7^Gdl~Oo8D+1wa-Li-y)UDMO`;f+-JI;D6X((8+}i6={rhHed2IGJ3;Gx zRFkQw2PQ1v87lR5m0em6q*15A-E5ClO&j~b)yBT8pi*yF%}N?ORkee!G)WWk znvoL;3jf3o^6dfD(ff^VvJEBXENzMSA2-!*eH)k=_LH-=CR0UJkL%ajVHKst5szm! z+D`dAHLO+>Y>(b%vNODarx<<1i!{rrYiJOk24?G9uJr% ztEQ{Tit<3E4i&K#GRRDnzf`t!c-%{sia{MVxl-V%KCyXs+bQWHTjvvtys-kb10`#@1Kv^cwuueYRAPDaA!8d8Ub& zw@9TTFSVW4Z`0TZx{7QI(|Avz@irb)%vO)fX|9daOryfMXY4lfTYHVy{TjB^aFit3 z(XFjrOqOoef*p?z%Bb*LY?bQK#*Te2QhD^<&~K3)esQcA z7fNJVN7X8j)VlK2v0mo_*3}tZwK+{kg1m%+)NYfu24>dvr>m4Qxv`$ok~Y`GCDvl~ z7(UFd1XH8&RxaXFr!GwrWjP>yTP+)JjJQ zC7LzW8lu*EwQ`y^frSP{@~G82kCoIS`7For#VjjtNz1xY+OnS065?S}Rm&<+-LgVz zTGp!umNm7pWfi8QMDk_}%j)07vR0^dMXfqCIf(RDYqna4jAM7}USMC#+Mw2LwVL*` z90Sx^qSh(3LIbROF{$YUT}-W=YK5rfKG?dKRV`n&vNK-6LqoMjsTFysC=Vca0*q$#a$7FvG9DYY3c?V?qp9KM}t7svKy5jvJ@pcu~dnzK*Z z{u`~*r_3@%g&=cI)^dEyH8MD|L7hIj>cpLO>Qru}U31=EQ>RviY^V5b)#+iV9j`0K zV_`g!a4`qW+WU)yb|>R*cBnlxk3?#USJpX0#c^jdl&ov6_`_&9k685+I z^FC%xt72{2>02`OxTvG8i!|%C72HV4FcFu-WfE~urXi+bxe=!E%2L7(t6MMi*o<;* zJXVgaQVCq`UhCm1m5y?2r0P}E;JXZS>BUUCw=!%r8PdD6N)?=FH)S&!ph~>b!~l zm5u7L4rRzVoiI+`IGM0YR9C4EuHk>9HtN(T)DFIDe|_Qr=6NPwZO3SWcDs7&9cF-1 z{G1(p=r@&W+S5*uM|zFw23J(w_UaRtEw?>p+n`d{UAbN8ol0$>;WY^wVxAb+^~7`4 zR4S`0LHA0k)0NY<3U_`{r*~QHcpWse=lQhcCXJWKL-~_sDzPuox|lohzo|l={b2`L z!*qOGU2)mnOrNqT#P(S1xq7^i#!ke>aVix?X)(cPFayGSw0kD06VJF=KagIP$I?+; z#^hw-7VVN6kV3AyRkW-G-j=nUgy1NvNmxB~ppuwjG*`Q{OKL_0xe}9qjYjNbLi>?7 zVyRR1clMfU_DPy86J50=MFw?x7}xgLY_q0l{02Mtj+0etr_1A`k{bM>iMG@+lb@B& z*-k!Y=soI&?X-r$v{WzowzY}|vOm>&SVz>xUEe{u8$FQPX;q)ovLXM{bi7{arZ`GDRQ! zh{=#iOF5(C0GEz)#!)5wUd7f+F4H4MJ!LE5vne!ZKiKViT-p{%S8Eh%if+?f`owOu zA|_p)W{%aet1ZCWr zL|&mwdS7&$nT`}AoLvWJzYnsmE^5!6O9wg1XdBxt8j+g#IA=CD@qEsEJX|JY2O+KsiHkbKah{biO1*zZI4-q zyf|HQRj@Q>XjG5h%LLyhhDIX!2D@fWH%0Y;s|nrbr`n9^8rYRK1C<60RH)TrzM4Wf z$5jY7t<&IFtgvIBkzT@zYFgVVhUw4;x%!j~lx<5B*X;zwX`>0Md&%~=(gZ)3;K?>I zrE9Ausjpgk~ zyc(p+Ig#IXieb_?nx4@pdh#cYSI$3deKj@fj1z0xPSZ`>dDGQ)o}l8(6XT;@lb~M5 z)oD>C`-y?3tvc+Q3(ab&QmtGI@W;NY3U_q3)0nrP#{Q10w#(Pr<%x@1+Oa>5gE&QW z?Yv~)p<%7)YDeN*7xkEBlAWMjv_kRmct95!YQ(Y<@s-sO(vmxwW$i<8T)7prtPf=@ zt02uIj-P!kt4M9jYRW(X$4_dt>up_m^s%giG~C>4N*{$aU#Hfehg(<4M_X1hx*_hp zQj1tQuGZAlCyZw&;(}?R4UOd7A)Pqe=ChjPw0x8qgKU8PdGG!d(g7N%qjTTG^1Hd0w#Qk!X*MA0ir zzIoz@<{GaFB;PpgHzoQUBNU^FBBfL+sF59sAr&>*2LkP~>bX&!_A^W}9_O@BC(m(q zSi_fTR7bfcki+T7Bwqb?+fvPVHJdnfZEPo~Htn%EZGCG$apw_r>g6i;olI}{h2G92 zXkc}fT0O~j%4p6#^>U44{K9J_8o2azbAUR1d}zljc?Na*?U3zMoLQa3YsW=9UcQMm z_Swl#qlxV%w=a_0CWkWDS4~WDW!j%+sb*V<9o4QAH1=W3?I-pyliW{q4knFWHS~$` zC?+QOa52^6Y34X45>=^(64g8VZKut>H4;5tO6qII<6_0Z%{({r}RH*gIZmBx07d z!wM~^9vd==Hc~T~hDjPXpRkovXR12QVdP;F6h=oQQcq&r9_N?^u=I&+sk(HJB2@{! z8LfJn&GOM>Y^U9(mGk$sor>d2Jj$;CO}y^*)u`@s6}d^_Rrd$znN0AVqUaOL&9IeI z(Bx2TSC>1E=30WUe8G^O9+=7}Z0sK*)<7Tv-+OATM%M#d5+f2iEI?xU)hUxH|FspG!!c>LeQ??4Svg%tMV$XPWQ+$Q)~_x{bl3{=3z$) zsg!rH9i>?2$2^(p+bSKKRn>5!uI&`bw6nek?TGgx*Cpaxn%Yh?&S>yWyljs*r>WF_ za?a#MQZw!eay2-6YO2Rqu7d|Pd^8gAo7rK-pQ2KKEwD8)*c7f4uEG_yhDyz((>C=W z$`f_!K(RJX>DOtzS|+lc!Vaj^=<#;&Da{G{o32J;j~Tu^WmsjxdK_6x(s)-%YGNkC zeYe`mK~-u-lDB8-(!G6W#9a)Ua>S16@x%RmCSU1-f9iiyc+0zkPS}y!!Eoa{(=ft6 z-%rPOkC=$~{MqxfMbi5#uznW)MRT7a=uiEhjI91Ms`W$s-kSS+x!=r<;pKN`GnGfo zul(OI_l@;~|A*!V-TY7WS1N{v|115;NgFZ0x_|ax?$2P1E@lP%On+r!Teq#(8U9TF zMdIlFU!}k0zuXTp_kX3IDds*u+4-q{ZpYW>r$e(pE58vE>ixo$)1TchnN;taWd4vp zHOze~{7?OFV6RKearjyJ7?|9;?Kq3|GyVCb(EDsM{51S*DfK>GDh-?45Ah2y_oZh3 z?D>JI)W7#H{GT@We-*z4snvhiU-*xgM(_9i#r-kneoyZItbBQ-RsTbN;eUj=Z;HVW z>7QZlXV+kUxPQdl7ybTB|BKS8N7D@b;D5!x++S<%`~M>RZ0R-pkyt+~f1AzyWxu%J zID`7%g7q`~#WxktG*dssKZUvftMsKa_kUIYa+v!$dH&DJUt@FMRD&O$-|t_ZAMh{F zA8GEJX7Gpbr4{#p7$jek>2f6!lq ztk!d#!>AwbCo}h@82>E(rObVq4E^l+gR^P)zslb^=Kinpca^!HN`v_!e!=Gcuk`cT z-2at+3YmuISNdsc?weue56|yq?*B?Zv&{Xi`21P>;p_R&`srfsNB>3o&IUvZYQ3BzZ4ybN%KV2Rcf|h&9Z;bo2;ShC~dCFgpAgkFnt-2$A=O ztI1VJUkNuGGP6=^xGRjfoj&t?3D+076lqjW#+{b=hj0Ut zzi;GCbL7&S@ouI6Z*qH$yZ!ufLoDrD=|^s0T7CXMg~#rMEf?kc@XWQOCmj>DrY1ZY zr&`9Do}c8CFY+TZ{ImWgp7I*tEE)e@ZV__F{tLNat8T3>$7P*Wjy>J^55l?RsNA*l3nFx zeEd)Hl3&@7S(i)Y&3O5Ta%z=-Z{0yARo(14MD{>8yJCIkO?`_2F=bP{(o`Djck^8rFNw^!4ADK_Xm2tUceiF|R|Dl{nI{cB_Zsbfi_k*11 zXAyFHjoc6U_+7qBxaX1gE1>D&Pc=^cm`joS%*{&wA}7z6HHb_`PWmj%IK%ty`6BO& zd=Dc((umvnUg^hr8;JZ#BQNs+%Q(aTNjcq!e7S;}KA9K%hy362D+IXFOEQ#}$jF)T=TGIzAQ#QZnQ_)n<@}I)Y4Ta-8^;+QqFcFx5~)L{Nq35zAKla$1voF71DC!ZN%+z`L}$DN9L|Da{r{C zBFK$1a;g6zyq3s~G;*oFmowKAzaZoW8@YcfHyi&Jo{Y;a#xlUvTtoiXz^ex>JZq+=&?&h*Os$TChn|D@dvL*Aq4zw0|5N`7BN<$k5_Cq#gcJJXW5xqXTe zo&Vh=2H=(>hbR9!HS6T?tku0$x9*-Dnzi%vZr8k9vu=GoOE+uLwpDk}PMuq}%HF1L z7tdU|bL7gGBadghPA&X;wrpkHaM;piTJ>t>*SSlpZl0w(ckI}#Q%mo5om%;J?(Emy zvuF2io__6`d$#av)~StWuK%ySJAsR;>i-8mc$o_#f_s)5W~OEW1BjSpxL^W?CN5~p zFv6fDFgOgLrbxJ(m6nzDB&lVk;%*ySnr8W^nVMNorCFJ&ty4)vLGX-gD1#@44rkduAa#G(6PePUWH!Na>xFA9j;1y?;t7jKd14&%da&q%iKo(mQqxE3{nHVZU31{BikVmr#t~O)o1lCi+h)*`Ja~7^-JNQ^|Lx z|2gT6%+I&wWiiRHg50dJf3yjP6%_tCMKZ2no@KJi{J>6w3a@z7jN6Bqm7z6R3nD5HSuxH}mnEqP}vT|LPXsZiBUj}2`A-P+uE~hQa zm2bkt+lr`>5yno;sf;5Tlq0b-I;zS}24$yl-ysW3-y~w5%ULC+N4PMi6C&81xwdR~ zX`NZQBPIVFdyd07PX3jZo8`)~WoM1IJFVGS`7YU(?~-`d!Yq4{QCO?mU_^K1XBK4` zTT%Bc2NFgvS6L{`A>@3aPs&GH_FR|M5`j`m{y1x+?amQ)rz0OB48E#8;@=o>+}=*`p#CxU#adTt;oBXT?TbId}S@ z>FH9Kf{M>cDR9}x8t2_}tFs6#W^}d9(jX+7v`uTC!|8Hg zFk^%Jdg84(btB}V2UkUqy5!i#jj&szBCDT8Ymvi=S|BRQpIMNb?#goDQp>fGG_!Iu z9qQ`k7G!6mSr|JC^0Mt}tIPe*$~KGx(^WvlQ2#~=##+%pM&=sDMnjiK7+fTh`WK2I zjUWdX#F36bJ&zrTB+XRa2x#kaFv3O-koOCAsO?M&dn8-WTgfAgG~5kY{YxEH`EOPv z%c#Gk>u#p$a$;2EbmQMfF^Z6z`;w#=o!jodGEz5ecG`0DD@&xJc?DIna~}z);^>2%Ozz@-Nk6eOsFYbnTnflQPZb75)YO1?DjSLUWxJ zINDFUr`GoB(apN{1EL!d?ygm{G@uYS!WmAcG)rLIj~gM(|CJ8G|LrRH$m zW%kpxuXmba&03h*e;6Y7Dc81|Vzq&x<{&Ms+^Eo|wUb=lRYv~0R*u9jp#a7)&l$(8 zMWGw&+M6hJ^A+Y`z0~ZZ`#1D$ttCqF+iJh=HXYH+)XTTI*`#X=dzYC*0<`ZP{$;wh zcS0)aze-C)`C91O!QxU}uvFg^bD*wet3tQ&Z{S(xM4W);a$cV99cpfg{B-?W)b@nq zh}lPbxL&G}>pR`HOJ>@$yac3*?-#+CRq zd%Ld18`mM$Rpm0QuXY&*%GG)vXMxH1>)Nb_6)4O2Q(8bQ@@TG|$_`aKb?v@}<+`>w z`xMF-u4_AeDo{W_ZGMATb3mA`J(gW&#_^vu48_K+j#?dkP@8S6&C+g1(2z~qyfu@` zd|Q~K1GHnNGNco!y?4MA>+54SYipmG%nS$|~FOgnCpy;o?TNDjzc*QPx) zDb^gKYoV!TGp@lvIrIykP|3l#-9q$ObK6j<+&XDye%hQpNW(aE$;wHgXcwAA${3){ z*k?*LO8waiv|*`PL;nM+Vjum571II}jjDZo-l}!>sM@EOR<#&awY#cS?Fx6*-ZS}! zp!$F2MUx9PZ3P;I$CV1yR>_6xsx_2*>N4$fbP4rvOAVF_@Le&Qx4l$rCKng?&;ft{ z?Vge}t7uC{xpDHS(Efb^)b=4d^_+`gNx{kD3N(L?B3`&eB|HF}5+(ov%b zf!e&*rRLh&x{*gbPo^>aT&-&}*G!VTBuv}pTZSUk(U#s>iZUcVWh*XWP%NT_2WTra$xtO(A zS5NXU^MA)ESst4Cg$ssabvFkFB%$|6lp?kW#Yx8)9(6H8_-g59%_}^I?>BvF9=>H< zLdt&H8$Rb7zNOPPqU<_vlo#AlcAhs%g+!6z+xdTQ_@0G}*;d=+Ie4S}>Ds=^A?TVv ze*_BB-j@-m35G4){<_w&#v!N`h8^6Ym1EG#OY5k=Mn52f(2l*{gV0`+yQ^;VSJds} zDs{W+e0BTQvu;mcTHVgDZd?cK_{HUBH>cDzd6TGUv#*1GnSXWbTFTHStS-8NRM z+lQ5PYkYya{b{36xHf$$2G|(1QVc?v&rZ6OVW`wc4MSzd5Np!9q0Jd1(U-OU`jO~$ z_eeC|Yb1KxCorXLZbm~p=I=uH z6;bM2&)idc#V^sfp}DhmHqSrNHyBStGXpVN>xo*KGt(TTYoFGQm7qBa&t4Nl5wSz2 zxs5i|g@c-E&le_|8zGlqc}$uSkZ5kJyL^Yr-1mV(Nv(~xyLP$RqK$K58i67d%3%@O zGleb;@D91Q^|jr8smRA=t}WFFL*Evs?KjS*Q8yWMjk-ybxCGx+%OTRAr-YvG7=gkGlTP#P$KBsw|H(i zZV&m6H`2Z?N;OJlzd)%xvy|tMV>0<0f;sRm zR4qg|9#wSht~c=zEpuFXkjA91fjmb0Y5#iDgelTnt0$G?5^M9{MBT7k!(+TWQif^! zePzyjowj@e=6_!omzyzZn~$3rZ9zL?D)sGT9-w_zyUd8QvY-qX#ZOyNHxt)v$wYtI z-2e*?cmimRiPNI|L~N+9JzE#|Jcc`|XpkO`>1MDVR)RyDXwOf`#EIByc43k>`_51! zo2_VEvhOSZ)JxrmMUaV{(=YHjg}bL1MF~cB+9!1@e6PjS@&#uq&V920?Vu(P%k}gM zb7y@OcGcAuPrwOFms{&HU7L*aaIN3GU|cC``lU~K4Ha!}zFK>|FcXiYsmM?}iu+RQt84e>`j^T~^pu9IRm=Im~)shxWS#nbH$ zEVd#4+S&%pKLW$dm+!=)PI0ZPWtc<~m5+`C@#wg8Y^gbLh}p;gs8OZqn8~C6G--2D z4{WgnXzTZyPT{7#$0ruU*SE!q##8zmGLFjl(LvWZN`70GzBsZFa9hU21x|R*E?#Qmuml+LU-bo;r6R zTc7LAruC})s}7j(tXxMcogfuBizP(KaLckkUV%E=Tr8#}VGZEDeOM#q0T`(> zjirEhjm5-{+L2nB7iJnkop`^zyWYli`%zOMbJmfWD>+R1U{h)_p+K*v~oZ&9eMhkuJ@gr-;y zuB~6MYqN`t_@^;Y*416w-H3ug{S2aDDGW_2$=vof%wST@&CrtlG1BT<<4}xlncCNw z?_ua!rX`}qoiNKln^tbFN?CG>HbW}jK+ zAcwhb5|+hf$VA_9zz4(pwE@PwEKECDaLTCNeOO^?iCJL-y}%rzz39Ra=dl`&Wm&F; z8>{^Xi)BvkUZ?S1>^IhF$}ui^tkcLDYN9>92}`lvv|R<;F^5_oAa5e9a+RZM`|6}( zY&B_jkJ*lEF~^vWYzjJnLHa<|*@(Hmz4}HR>ZffUlW8^``7e&fI~>OOxhwdHtkOU2 zI$*5P<3fK>r&Lbd={#c|aBnas=v~czmLcZA8}Q&S5AYqa7U9B@A5Q+cH7g`%)?VH; z3A4w^DBz>6BdFBi&%}d4ZEc?TxS#<5iF_|(e(Y4Dlj~eMh0%$!y1j+2lq`hv+#0g0Jm-fJh(zTJ;8WyL@wX^CX6HJCUK~k6e|?P!UT1%Zz*nKEIaBekxpA}+YSt6a>7o% zjJAz6+?NaFjJ<$&lGqx{_JW+4MA`os6?GQRcpPS649+=uE`O3*%T`0F} z-2m*uC|R|?)jOLTB;i562oE9KocQ0%bra1ElQ7ge<=(8TYnP>B89?q$bSA5UO3!y6 z%QB*Ns1|PI#S9|jGlvVqBQvWq2}6i z@ef&e7>Qm3RnteC>u!(%#n>b#BM4(yu$G0P>)%GyAbl>!98`a<5w(FFos_fzl^Zih zp3_bS`J-9ihaMkAeWWhN#!DT^UiU?dk3s)d2lKEZ{A(osHCIlY_QAMQ(!z`f)b*Gv z%fqX*f+%e!9$$maS6cWCtJ+FM?My_UQ#E>(XI*u0MQv#e?GLzHt27E}t=o+U?R9w2 z#v`b9JOD$x=|MJEc}#!7*kjU82lyKg%>j6aNIH2{C?D;0RVXdq{b;R<^=s`+DN=xT zvKZGxVplB_-bgcA$qd}}Xq$_DFdw+6wu$1_*WS+0G&k#O?(?K^DvqEZJGW}kOk2fO zgL3axgL0H)x-mEzD+L^!wpVY|#@Rg2%7Iz|Fm8y~f)cAATiKo;4MclBnqMK!6T=$L z{<4Xga<{5`xRbe__F;evV>A{qyzXJl58d}L4l6?|_#bW&&9wDw5y!k*L^JJ0wutZk zvKE0`8a>DRjcZ-$gAP7K+i1h>c5YBW3&4;wvDBCrcF?u;m@BKd9x(*IC9}PAL!f-j z0|Sk&?RZ{3nNc=QCcd~JmCtysF%4cZRz{=77$J>SP;K=DS*ogy*}1I8_#sVvC__dd zUHceIF`m-`-2YA)_q1c^IU8$di~LjZyc1C+30Z2|R2vgy?T~zY;7OOfVTYprt5%t3 zQQf1p6mOHy@8*mNiJB%#C|%5j6a{W=-}@g1j5?I6CJ)Tt@_7xaaa?&(g(PtY{}3Q9SS!zu6} z!@FS-!dn<#2c;hK;aY5;MV<5(SdQ&IU=YqnCx)9a90=E8{}1?_xEz0iz6&M(c81q6 zyaeLAQY~gee7LT~M2Jt5bs7uhJl_tbJYArqx2dB_=LIPFtc2xo2$Xo;p~MTPO{ou* zc%NNk{02;mx1fYKGQ1W_dSy_KpF@keKbPTQ4Daip%J)2!d=Ir(ZiiCtl?>kv@yq9( zO5iOphuc%3#OuYd{N;;V5#HNQrLzIzBf8fwg?Heur_O_^*gp+Q`Rp(U`+L*tp_Km` z?!N-!=WaUrLurq{U9FD$9zKrnQTPCS8?J$`a{op+4dMB8IxIr?PAKsmFdO;yh0^X~ zptQSoZ~^p#67T1>_$V(H!>i#`gy+ICI2q!ztBv!av|AgLS5>99AH^uwW~ z+aAjK4`H|&lzf93J{F?dLkV1u?S;@6*U>>oQ5%%~Lm3`G6KEGG<+>6+1^uAp|090q zr2@VWm%yFyNw^uxb$9_vyp>SOwV2@vQ1Wv^DbHw{LHj_dXI=O-G{d{$8T>9yA^aTT zyK0@*L)rcew=dxKXeh^pa(^rCZ^ZovF=)tfd!eNF8kF>G+&-Aw6S=)9l=SLxzYq7H z!50MOxMfh<=|iv-j)8LjWx~mDD7W7L&FDuha3;35f|7q7hJVH&hF?YN^cj@nKY()l zUN|1U2IaiI45z?yDChTSH~~HkC&GKUKZpC1;YMul3vs?%#6T%;D7}haLF-YS{&Izi ze~KQXhv*I{?PCkP53Yey&ZSVU`@>MmITK2~ilNji9~Q$=P~xXSsaGkpd`?wjDcGCz-ykIE#`$5V7%;hS*ub|}r0hD;V;W)SzO8zfE$$tfu{Fgw<{{blR z?}n0pDa^(F>VT4e8kGEpL5VjAO8)(zl=Q|z$v+cHyi_Rp-vlN9o>1!F z1xoxdDEYU562CE&`~zVg^8fKNmH!DS`F{c>-XS;^9)ObnHYn-61dHHuDDf6R$^U*R z`A>(E{{$%UT~P8L0VV!$DEZ$E9mu~sl=_E3$-h06cx_-LYz8p}=u`_n2S071`t?Kb z5rp@_m*ML$5$SD)H^OJ(LTq0FCB3`gFgO~H#{LZ06X7A;-W#q%xHEhhwuMV!3pgLv zfs)Q|_#Lq4ar_~;4B>t7Ik=YFmqQsh9-?>A0k8|U$3v;74r`(P|JF$5dm768=m3;_ z_CmRzcfjdz6SuE{ix8d)rM!2-7hw)u4sV0k!=~IH044t3hU$901{Wi|0T#ih-~+G} zN;+9^1H1vQgFf&jc({Q|cQusykB2MaK-w8fc|+hh*ceKC&|xh6roM{*9+Y%-m50*h`H?!dba1tzp4j78_Hj3NRp~M@?a2#BZa5R+j97fwyGnDkctcRbf zhil<1_z;xiWB~W{phcC zRs3)1hfw-~ci?^SH8>B-U-XgoQw}BHGAP&c0VvmV29$naB9!Bt|&D22ZUsPHbh0>`g~(ypF?lFlOfD1CtYXEIz$@1!m`1IMSqZgT%axlS=~8f*t8 z|105aSRc-UM{2A5Ux(5j*FtG8PeZwG^P%(;rBKQ#zhSTr;oG3Z8we%djZpfD7%0~_ z98Q5Pq2ya1N7k zl;fJvVCn;~q;a$rl=3%*lFnJPO6PMZ>6AlB=WaL^ z7D4GB?tphfykQ~VBWn>4XCizJy#hXna4?i|nYsNm3L)E%L)rd5l~7JstM zsJ9NK9`c(~Ql6tw&eQvFGTZ~D-`fV|JiP>`z~xZl3Os*R^`JN}fBai5HZ z(-AL2h3~uYi&-{vwo-uS{+v{`Y7Mec(aZ0oP*( zl=Hd)N;%d;iMJd|JpBBysXgKqLy6~r5^ofgcvdL!;^EbZ7Xc++8z}LbLy3o<^ETrB zh(^#3@s2`?_YRbJd!WSI38npD&SNTp>tF(03Z3YO7DI{uFK(X;UD%F$z}Sv+V8q8c zG38@Bjxn~6hSIJELCH6s+q*-_7h{jnKVuqbgi&WXPHzg^V9Bi>!+AK5_;=7KxC*Ah zW-ygu{7|&XhHzil8pgrZFb0l-a-HP3_OLk&fq0|}Y6>rh^&s*L@`sl}xo%D14>*4) zTM&MC+tdgigAL(f7y|b|E8GrS!Oc+emEXt6gsY+Ci(m0JVagS>5C+5fur8bfF?0sa zfEcQRN?-sS3v0tXh^{nf6hs#nlm=VE0q_pk7fSkZFb&4QEEo=@93gNdYzie_J=h=m z!vW9)hr%Clo>SmA5Z5Z`7`z!Ch6CZda4_5hhrsP{1bhL;LF8q+0X_qJz=iNxI3MC# z2hD-K;0)LsmcZL#9vuZU5Ke(9f~@x$zbLK`rNPvXey)DbUjKydq+96(>Z09fBn_m#^tk#P&H6|5Rl1SR zqNOy8+GqmpK||@)v@xwqf1R!BcbXohhv;^?nLa}o(gK=8lV~p*MX#lAqa#HV(%+!- z=xl1Ix6vEv4YVC?MZcS+())t$pj+rVx}4rar_yYiL6c}NdJVmj{y0Ko`qAH}t9Uy8aG9Lnvs0Ca=mA*QS$waen@xHt#l=Qiq54osf%XQp|n43MjO&ilU2UY(}(GO)Imqm zn`r`#q#fzK>JNwM)95IgM*Gn2^eWn%)}lY%rOI`fzDqaK^>jX+LvN*n=oKX@od)y= z^*0ptZ|DKKo35fy(|hPtI)V2xHu(gfOrcBF0SIQ180^fC19u_~W8=u|q9j-bP7589R1r?u&E^+%HQkLWA(Mfx~> zm`FqR*#?WT8A^ojDrT;zsn7&6h z(--I?bS|AhU33Udrs1?b^`|C!+@eVjf_N7HngNPE%)`6~V0^d5%_ zPo;Kx8;ztLX&s8MmKpcyC%MY^={EWjeVRT_XVFrcOEc*}nn*j-PP8elM}N*y`F~3f z(F1fbeU$d0-DykOgr3P(>3v1trF&=vT}vC&y7cSO>iEy-8+038PM@GN>0NXrwbEX+ z8*N1|qo3Tt^G_FLsqiCo5-p;)(ZMvDhSEkfkRBhU())D^2%v;(b8edyBI-8EAdGr>VLc7yw+L~TYed#Y5EC+p`ZlM+Q z9y*nFr_r3FKs zvshS>dB$=25nWE7ph>hBZA)9w&u>-fd_o_fchg*&NpGY#(6+P%^`SrBqS8G`-=>S` zBQ$NeikC{eQVYF|2Gg&GsrX0fHu@4>Kp&*Vw2(&AQ0f}0(#xj3XgAu1HlrH-d5Ajh zBl;iuD&0t*p#P#1X#u^B4yLg*iZ-JS=}&`IzNhF1bU)ohpQnrHBea+n(%a}@8biZr z0IfwA4^sI*O7EiMXc|qWH_$FLi0bqR76zpqe?YglOIKiFOv<-}&ZbkSi)PbX=^)yjM$;YrReD?KGP;<~qNTJ4 z?Mi=3R>yx&KcM^R2D*+;qy@A;y^*%2ms1n{;U<;Ohx8qKKb=Jf(7v<@4Wg&}sdT=i zZ_%A}HGPKON2k*sv@4BEQt8FeFA`Pw2wl-vg_qEK=u|qATIr4S26{DZNzL@v8<`LN zfWAUsqzmbMI)VQk+z}V#H;*{(fxE6eU`4E zkI=bv934Y%rU~@D-YWflw1TdsQ|Uz7pWa9o>RM`L*&>1*_5`VhUB zj-z8}HyTMB&;WX{n@ay}`VxJX-b<&^G@43l(VwnU>GY>JQvPL6-Jjw2yQ+9^(G7GR zolU3E+vyM*MX#kl#i;a7(f`oB^hLUcj-`3D7wtyd&}Q_zE-L*m=xg+4`WT%@N6_K4 z2klB*)641MXqEoEbUA&3-c2XdTj?MgO0TBA^q0;m-5qobT}l_xne;B&m&VbCv=03? zN~QZbeU)yc57B#RHqD?B^cq^9)}|*TRr<&2YWfVlljhS~XbQcSUPaGFsPxXz{d5<7 zl-^Ir(J^!wy_vS7t*B1VT2wwq=^^?C-A2pllXND%i)K+9?Mvh6we%`li~ba@@_(If zqO<7~I)Vfz+3NbEP`|7~MyA z&?R&MokAzjQ8bPAqrGW3ZBHA}0QzNXmH(%7Gkt-U(T8X;Eu^>8A@l~?g$7Zb9t~0X z9im%k1$~N^(OI;V=F&`>O#9Hbv<3a8mCEls`a0c2pQew~u{4h+(>^qWHl-i6RO$bR zZl*8LrF0RUMvG}Cy`7$Iq0&1;=g=9{N$;RH(*zn$+f$AH++3ym34Nb#p%rv7eUz5a zu{4X?XbcUfEofuAgo^q-*GWI){#>d2|R(rZ>Gc- z+r}!t&*=`jg+4~-(L$O_`_bOCIc-FLYNXOXMW3T9=|l8hI)L`25%e0`hz8O(8mjcS z(I@F+bTYk@rqf$!589PpL$9PiHc;uGq=)DM`Yc^Rr_)K)Mu*WZG>rPu-|DM;KBWig zBKioui;kn+Xe8ZHPo=YkK1lDO1vH2Dq1|ayT8|zIR_Ps}FVSb|0{S2wNv$-Q_Mx3= zC;Cp1O8-szJY7X+&=NYF4x}NpDgCXkO7DC6A$^A~p$q5~I)P@;Tj@3QN?M!x(BpwB zzmMoD`ZT?lPNTUrlSa{NX+v6vep^SS|2f@CH_&qWB)x-LCD!;GjJM>LjLD$kbbOv?Mk+c`>Mz5wV>6iX0 zzfb8jKNT*fchC_unf9R(^cvcT2GXx}mELD`3$36F>3mv3$I>*KN_)_*v>x@R$IL3f z!}L|Ukv>Bg(%Ezh&7-5}0NR(fqpj#!UzOh(`fvIQT}l_x@zhBN(7yCadIkMNQ|Z4? zx6lf@oIXKk&=NX|rco39p_WSbS(9=FeVE=y3u!JLOmCv?X$bYF@+}})r~d3W{MBms zA$^^0qEFE>I)zT4In+*LX%uZuFQ-48Rr!5GchD{LN%|NaPn|T8_N47;2tD$vO8*1; zD&0tnX(3&OKN2kUf12J)r_neXLtE3!>9;?t<3Fd{=u317T|gsgM_QlOra%3p(mO@} zO<$oa=~Hwnok)k${?tM{P(S+Hk1C&c=$rIex`K|OS@dR_K-=}ZU zd2}`%P19*2?MbhpS5kj!q9@O&{EpK-bUS^VK1`?33G^14LOap6)Q|plTIF+)zD-xq zCG>7OnchfmpzUZY`q6hP-T%<7bOT*N7tq`35Zak`qK#-E{q9?p{ugu~-9b0db@Wks zKh2^xnoRr9wzLKP{*=n^Yr2>In?6k+r$y932h*EqeOjBIJgL$@PM6as=-MyU{$+F` zEugp2!8DX!O-=NNFH}0O(U<8Gx`0ll6KQ{XBaNn^v;}QUH+`=1d7eH_AEtS96zxf` zqyE%HKRcn)`;fj)H_?0ORGLjQXg}JUHlP9Y;HTc9s73bRXS8 zm(j(vl#Zu&&=K@znm}V{IBiWYr>9<5`JbRW=oY$|K1xgISb94hLa(QtX$#tz>h$bu zD&Mc^XLJ{Rm6p>dX(=5~Z>581G!3QoX>EFXo67e~`Yzo=pQ9`3eRMi?(mQBB+M8ZY zThgrMhTbSj-lb7>~+PNQi{+Jt`fvdaG` z-A*^tr)U{1p=0TAI*|6DU1KCMkpZB*%> zpu6a+bS+&*%jiS2JB_AS(dM)c)#$eyRDPe+rF0RUM2l#DdL!*XTT?&!TZKyZBl;h@ zfv%$;yr|;sr`JEP!kuYL+Jqi{PVIk}ZlxROQ?!hh(6Mwl9Y~|-wX_b^=$dC$eoJZQ zQ$F%LGWv)oedPOEdQYd?e;tj(7r$gaA47i&Q{nHarK1XWp!KLfJ#~%Re}e9z+vzI$ zG`*Kjqw;%Pl7A+Rq2aVCtw)b{Q1L&a6?83KOdqAQXek{@t+WsAPBZWYI4RGqv;tr9 zl<->mD7~Lr=}_98M$;CwF+Gkimr8mc(bwrF`V=jrld1e}mmD{O4yOm&s_nb!B7E6W z;ypq~({$RCUPl|zK>8KFq$$TArLWSB^g((Ly@QURJ!n_jfCkVH@a0cQe?MJE<@Zfw z`&2rSTIo>QnRcQx@g-6@?k+07QzGHPv>k0l&*ICbvi}U-L$}jqbTKWVW9iK_fnH5p z(q9{>^iR{>^ffx4&Y=!ElJ=loX*1f8p2U}4rToX~Ali?%q0Q(?d~wr=Pq)wtD!)r2 z`=`)!dJFALJJDe3M?Vc##~-BfdnA(HN;;iRqBqk7+Mb5cpYY96IsO#gPj}H}bTMs8 z>(OZSy;L2yn~@H_Lu`1swsJFFNK0rMjiVvdL=WSOuTrkfbRjLFX*7<8P!m1u$K&Zj zT0+xk91Wo+dRXW2bRjLFX*7<8P!m0jLBJ?KT}Vr48jYhN)I<;COXSA!bRjLFX*7<8 zP!m0j!N)kBE~F(ijmFUsYNChn{c+=Xx{#L8G#W=ksEHoN!N&1)AuXY4G>(Q)6Ftm! zw3#lXB{Yr3(GUtG34JHqK~igcX&M^_;7jN7lHZ?{aB&M2&Wu7B*X-R06-M(j_V>V- z^X2tD`n@1rlNgH%cg46U$FIYe@a6Rc&X z5Xx&k&Wr3X4 z7vkJWxRBvHD*x&Ne`FYFJOjtj34q#KO%A3}dGuL zO)#$cj8?!x;=WKz|eLv)S}0&a1pmo*XE;gn^D8l# zkdD0CNqz{2Fx+4AL-=rKwST{)hwy6d&y)OQKjO*jE2JyoIPU)${h5SKJYMF1!8*=A z>l0+uZ?owKhVPW)u|JOG`#97X?~t;3wekut@(QPUg+B|cdc6EzH!gYQD=NHdc#+rs zehsVce;D_r=kYJ&e(?<7<`oV?yYSqfg?`sFe8MaJVz2Tnz{yPlrmAg}!!z4D*tRlgQq`}=vd$Aez&%Z~onGrx^q<(Jw3%Y zf_d(j-wpE&kN2w2m*_7&_b&;q8m^80!gK#*uj?_)E1c$a{n~hi`J9Zc>LtGq>Y4r{ zUiF>s73R8w`*2g4S9yKC>gV(dOJ1J&weqUp46pL6@XFt0&9UdC=Z!O2t;73SVysU4 z$gF&q-Dw?dcaE?-9r=Z_CnI}+VRA%aOmzPdci7Wikr63&SC8zhk-7Ga0gkL(9Fvfn zAmrMz`()X(Gvc$PYc-8IUQF)%4PGTD|J z5#EQ25~L2DhuE?U?D2RdCq-Um4NuRGM^R$j$tLtEOit-x1p_Qm zNjwol9ZsARIR>x6*(trO@m3tv6=|cOE{8KArLQ$UKBc!czDowm;&fa@xs$!q?-D=O zo?d{{QHVUe$}}J)0vW_t%eD))_9;w>1{a_6A3b4my1c60)yUtgu*o<<7dV05C6xs%x@TuV%qR@%!^kn0htGNtfyDKUv8&oXrFYs>FtD;PP-eQc6yoe>tRb%ZTH zE8U6~kd-^qn(oNSapWfS8)1o$k3iFPNy)9*_S})KQC7Rt>2P`^uiB+0JR#rRbh%R{ z-Y=rFJAo0ljLN&fiu)w{Ts^z6=FvB1J4WCRQa4Yv6Kp{hax=2+@lpo&9m2@ot^Tm|27oB39ljwd%?U|QxTHW0OZ%kEW?^2w*H>6K8?(r&3#u6b-rzYkD(F47)RHhMk?A`}AF)4u5vf_Qy)`clUA^C^b8b{{_RD z#p1F#N7`LhY4h$I=YR6jUt<1$`$fOR^8UjnFIH=Mwj=lNxX@iLKI^~x8haJB+Bn!d z!edadsL?Ye-H~Un+;MJPQWKuu79LSOE%zSJ2}osh8Fi{;;EsKPJM^E`;wr0hffE1O z!^y?u`FFRm$}(1KD&gmCD(*cOIFR%{?jl1MdbOnUwosCwh<1eOXjhIhMa2z zY94!T4jf@THn|@h2Xrkcv=(6^Y|XEX5)tkhrE-Ss71c8jH5)cra~&CWYmOtMAlqKK zHsDL)DacVKJ$x2XU@2vbhN4}j;vjeK^j8R*&#@h$l zGwpcnPsc)%tV9?KQdo&{KhMW|92Xv+pKi;ujmWlpjLXr+MjTz4eq|bwow-KU$LYvP zw&N*rpxu_yKR0_^N}esMdnrX|* zmM!UHZPvU3r`=kZ<#ZL;unl+im;!r&-MGJvljQMO-F2ul%Vi(z%8c<^SWC|ukd@^= zrIsjFUiY(Wgazw(HLQqK9?(U0j;a;d8ykf<-+!M>UioDIHhEB59~KfI;#o zaV`N>rik#AY)26mUaFL*TC~U*MytB~C^^@3;JMC6b(}^q-4EsQ11!-a^Yby~m9+u6 z2rj#Es=SZt6>;%VEf*10b+9#-1vdrSSdC>-N1ZFn??FWj7!w^njWxV5vfTALvMIqBM^*+#H&=l(*IMMX<>g^5yD%P$%d)VRkT`Jo zCHCZzYMC}g7G~oMd*}5ZWHpK?Q+2P~&my;9kMwkVem+(LQQXQCX^l#@<=BzH0Icms zTCu2|VvPvL+7n9W!a}I$k~R*jT+vq1lT$3#gp|%GfE*ZQMSZX~-BVVqEs-ieStfKk zjFoR=P0L8PhYL$|BV+;ENI{}^aThNIr`v{;B!!Y4Q7Ks&_V~<9yc=NL&MEy=H7_vt z{JX~@EcEwJNid2zDCJLi*T8sBqUt*bF&A3+#ybZ+@Xmp>he3bN`xgIA2~vKyX;({q zK#FSJtikWy8W%i1`2tPlpY@nxG@M?Z?YrtV50`5$z2Al2^FWV;DP)XiDm5RvR}Hl?x2T)~xznnAj}o^^jS(VheE2wD>?)5EHAYhHt*hsom6*r&b2#$6nw`6Z z)!)#nKC#CXg3}FmOLVto^$xnn-RyDSzeRf;6D8_A@~9%E9XE}~2hD<^`T_Ya)lfx3l9ax+v4_wlteU= z-!1z;YwSNyP4GbvcjtA1%ka;tiYjo*|DJi5Dll#hV;))KZ0R3(hA+6b`Df4W&eJ^c zl%Z}kW*}Q_=tu_*DcSc7+$OP+QtxrG?{|2-@9NI3kE#*Mvox~-Ll8jQ*|?y<9Ey; z2bUobt+K1Hc7SA9?I9g=gUS`73m$!Ly3l2i1FKPy5f?08lq{!I852B4o^xlg>QEyK z8(2@1in&LU$QlpxIPp<(_N!iT&q2<}>fGc|EtDCBt9p#*>Wm+CAe6gNS6vvaa+F64m$`}8eECtF&|P_})#{5`+0z9wwT0 z%r-Ms-K(a67R+A2SQ?Wvb>3AqkB-eKop){#7UUuyGIYPA_Sa>o?ympA47pYw!vH z$39wKV~-J);<95s>(Wl3$AnQ;|G!OzZ8LmuuDsh}tdjikBB{h;WPb67QmSFTReeRG z$^ck>c=i~(&n-Os;Z&q?d%Z8?IoHBW*=v4iEIt_Hu;=I^Z^U%|o%d}#Mi}FLp3ZoK z#yx??CBbL<)f+dxu^stVd*=q*YFOFgq(FAo^xlopGTl>zE`4mWJUGtyUPMi2R-MM* zTM>#lH;`j?g^-$=8ed8W_g}ka30_1ae>t7I#1azJ)sL;>c4xj>LQxPKck4}xg4q~{WFSqNlnjK z_&opjto}$Nyr?8S##Hq|wa9@5_$+}jv8h}rHXgH82jzLY7~QhG+lSs6MOW{K$_>L- X^oJLu+@! diff --git a/node_modules/kerberos/build/Release/obj.target/kerberos/src/unix/base64.o b/node_modules/kerberos/build/Release/obj.target/kerberos/src/unix/base64.o deleted file mode 100644 index 8f939c32bb35e3adca8739de7c59131e0a996038..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5812 zcma)AeQ;FO6~Axa-nW}ZePpeAXfSas|;9i)zqZT-j5sZ*WeBx8j-9jDsPRBd$zsb$(CQ%4*S9h3gfd-uI0 zOPq2i=ic-AyXT&J-`o50r>`zg*%*^#h7M!}^>K7=5ZWTpm!$lb_O?qmoTL~uLk1=z z5@x2V>BwN3JoKij?b|!r4QXcFX3=>A@4y1a6jE8)kZ#d?RSl=o$!NSsD6{ce1&&YH z&m)=H%MfN05_pMtY9_&Kywf6JNJLcI=i-?_f>G7(NLQvuMUt9ERk!W)we2w7+*EM1 zr>N*?F9I*C%}LR~izULETQ=TnVsU#!R4_LSjj?(0LS0?SNI%2=%+1e5n}_yiePB=L z31()P7cUw=m>`#IypIK*Lqy%5uLGUL{)$xR#p?})HOOqdPjmEmQ9gFmIB2?>`YgOq zUtcVu#zVc46pYz;mj#~o5WxQ6P2wfG4r?271D;q^1!aQvV1Yi)>c2g|zEC(Duh5}K z)(e1N+$3K5fxdayyHnsbiUNN0fAPYJUgVWlGx33FyjxXUw#`}#J1NdblTf;g7^5S8 z9{Vd6nzi1@A@yJqyP*eUKX2~{yh8%-fWQ+XL;8kEQ<=|4G_E0L*RM{Twv3p7f2C6pZY$3}0+SyfU&&_76{51HuI=a*zmwDZK(^!{11`NvTs z#>UDQjw}*$!duGZj+K;-?2=w;xU>x3$0SOi$@R)rf6mlcc`0(B1f=1MuCbDrFz;EP z+(0v)m6(6{_x8Je_xjZDzi~r-&S}36dMU>1n`pWI>2ous`2?x>#$3nWavlFbtI|2E zs8L{a655ehq4m37e+!G0hQ6A19seb{xn95P8~+KIpMtbytXvxU8m4jGG%)2Ko@z+v zH66b?_~4eIdSyD@kBDQ_{^4m&Jw133YTI;Low#5b{b1s{)&8z;BquPfGz}rpJMj-I z)pYdTiR%{o2fmSjq?r)BXySshCAY-pLj?lElQQ&|5I1=Vm7la=A=m&b(mvsvo}Rvx zdlsqc6_`~cBxyF^maW^i@3_Ms2sXFuyz{QsU2VJD_w3!*(YZg=74D84>^T%Yd|#|L zp6I(jnM!B+2L>NFQeCt5w%Xg*t*_g#+G_#{2D9F5+YHA>9cSaF`UVlkB#Uh2ip`#r z>&VM@x(W)5ic1!hE-YK5JA7wx`I4o#xR-tR){5mTR#vY1-s&|~9xtV&*?sgDcek|c z-RbU+Bva8u++9=csrJ;kE5or+yr-(By1E8(?K)5GD(3NcQ^~M56ORshyF#hRx>`>- z%)EP22=(3s&rkZY9jNvM=c7rW9qwdXeW;H_LHeFi3%_S%d5^FWs z)26EJMZvyos#*=!7$w&BTVegs^lG~(*sC+DT#-zXnN*uFnu8H_#f)k<0nDfyZpFqb zt4)_Z2HS0_Zm8^yQSC-lllWzl*bSAf7l17$@C}tUOvY6ml{FVA7{et#gJQ4+=G>hN z1iN8Il?@~nO3R(aTy_>Hi=7`I%PW+qx|UidI|IcV9h)4M+=rT+xN1mJpcpsuWh_v< z9>2-F0v?+k4zLQb4##G&HW$o{**8csVsc6$$xcGS9dr}C@N;fwB$vS}&x6T}q$Zj` z_X-p@<{<~h@;S38h7Q+*+Bu@jp#|dpKxq;jOAtvFWZ5sRk#l&BYD zMsY2p(E7=;Fh@2%YF>aW(=oB$jn2pTPcbNx@+1bk%|gfZ2Oy~|M?NiT`!;0xA#_^E z5aW~J70E^@wx6Nne?w=N?DWf-LyyI$Aj<}pO9#{;*FK9u+{qX-&X%;d6dBV(q!kat zL6Wp<)-Fx)KKlH1(C*X33+SCOh#3-BlDqQ}bVo^CO`^+q&WtC>SpnM++1F8uNWhrb zD37#vBg|{a<&MYTfCTnK&=R=g3vl@-(VfujQ|O(zP3ZYFYx(>eqLxn!MLY9QEiIo` z5(~yCE+9i$@aPQt_ze4`$uiqV;0r0uoXg3#o=w+|e< zeD?WI4ql54d^QB1lc3We+R_QoJD~HR&p>px2-osB*v)LBsWlp zM(2=NBVOAF$cCNvlk5hbc2FQ2c*gn#oO!-TruEa>XZw(Tz8dwtFydGP8=YP9c^X8` zh^22kq7qV~Q4I-SW*q+%z|*hEdVP(0V|%n3lT7>LTQ+&-%rkYXs)t4#XO7bAP!{$UOp^4qGatP~o*-$~C6IYrqFu>Q@&R1@ z`XjMKUnJ?>n&|Bf#k*VZ;nemiVsLB1f!7b?w){NrPoL6QH$ zPC{Rb%6SyI@`v2fz@-6;14j^>*Fz_eu_g4Lw=z~$hY?@sRcG~$U9we-RT#;>L-$uU zi;>Pd{*-btz6n2)&xkRB5r;*o$B5&itQ7iN#OM|y1}*NdV!RWh69LARqKRYxofc=# z4cUc>+#qW7`Xt$Cbzo+R8b4cR^q)`qOi<_lHkqxS{W+rchGO(TPS|IC8)=gHE%iUi Cg3Yb~ diff --git a/node_modules/kerberos/build/Release/obj.target/kerberos/src/unix/kerberos_gss.o b/node_modules/kerberos/build/Release/obj.target/kerberos/src/unix/kerberos_gss.o deleted file mode 100644 index 9d43fd0237e4a6767fbe64c6621469c63b9fd1cf..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 35460 zcmb`w34D~*^*;X2ym==xKo&^Y0!Se2F`FWSf+j*_0trNtU=U>t$pj)HiOGaTRtc!n z7{#isbpcwn#ab1sSj3{KsDMkwuZsH)D&oFZE&QJ6F7Ir?+W!CVCwI<0=bn4+x#ym{ zPv(90hfj{i8-~L)@PQDA&}88w9RW{&gzrf_&hv4zOxVagcr*@~2162wcznKqe_24r zC0<@wSsuc5tamRN)ACj>GmPyd#Tjd5iv0BXs#^lhbqxy?(dUblr{x4$DLl9Ll~8{= zbwoj*uf{*Wb%75;1;yu^a&Ez_vu&AvtQK6+@{)$g%qN~8 z;pP#M!hm%tuWJ7MX8#h}Gg80P&y@Kmt6Wb_`DOCz8fqKK87*&hfz0nql`wItgu_-F z##u7jrGCv-4Ga7&vGU%ikeRkfU@V@iA|cSFyv0@3Ld9tPR?U_fRr4AN=Z6HTSd_e~ zrlxwouc2x&)r+mKl9#T0J@FUHYn*?PXy9o5Hk~K67^alTzEDL%;Q0DARaHmJdsNAr zsPfPHh4KQ+o4Ty;Q6;aDofOYi7YY#m5v5;s<6`I)@U=E9t!t?9`HCYvtZBZ?+Nm34 zpGytktxOw~Y7sCgI;^YAe|htI(W zY)Fe1ckH4mi#u)?xs*BDw_izO@Jm(I)(eW;?-K06&x(Uby}?&iLZDQYUL5>1yavU= z_rpi!QFer62iMD-wmQs9BfKHJQF2~WV$XLv#hir_-#=zIwM3uGgV&4 zvQ#DVAKu_(x3}Yz70{k8`)qOWhbh4?RO-v#w#VFaWg}_%((&6q9$y@Mswntu5exe% z>Dy=23&K+mG~sp($y2)8$A9&Sg9Fcw|8VC@-3 zV5QxMI$F1ha+XAurW;CjPk;*5+vWA$)jj#Z~Kbe2x=~=!Y4$Zh@J@AKK2#` z4`3od&y$^DBRhn*eNC8{qCHcE81IJH0wdO*ZUlzFh0qn=l0^p#Z-84Tt^cbizYqz9 z8;jbPrWdu(beFVGO)hMo+0WbdF?yJ{_S@l?!&J`aADrT4X+g>UH3Sgew!D=cZRop)efORQE)1hg#y=50qNk|L<;ns zSa`+9A?HT>P6?*#f#`4>GDIZG#>c2wj&;P5c?C~Qo#>$26??rwXHom9tOiR^T@Bfx z*uK(GUrU!`K$RE+4xiSwb3uN8$XC|GIM%jmhiG`wH>K*R9jtmRU@0yRY2Gk*f=*k! zd)N=q=B<0FRNg+pD>cZ*MBKJ&Ye?)CkyzZ(D*C@3YYN)O9sV_j;-dC7VcvuWA0;JU zu*KW4LQe-%!O|Hx12VQ0wPSE%&ye#GhPF{f?TJssxzPX@ya3lI4t^^&$6%v99 z>e}8}SWO*1f@D3yl)=mX5C7a&)IJU-dl^>ThEcV%xTEkO8d7kfiWtIQRzo;E=7<*- z?xfERL*+Wr#oV&o;MuwDg$E0QXO9=M)Zi3VK@N7>;m{&`Ws9KXRy}yE+7aE*7;?n| zLmNXc+Ps+U3OIMk9{W?|peyXOVcTcNjwOxWumwQ(;zVVpDZ}h;oJsqPz_`4hd~7bY ziomK5l%n<$jN=`Yb;Oz1iHRyu@&r9?7gO5@OLKPYdI4C__tO(oe{$^n30wM5t8b8k zg*5GK-nPy-EGsFssC_JqDYXp7A-d~nP>VZ6V%|Qq#gyO=x;c8aZ)a*)i%iE5FKQ?o zei%d z_mfU7mfLV2coM=Wgmi>{2+0WOVXn29CtBtBT->olIv#vyzgQrwj$9xdELJNZF$A=n zgq24>IJ#IO91LF~aMsCEJm)*E=I1c(IZzronCE@FjR)-4mdZbsqiU-q>@g~8AWZY;R3^>bPFFj3!XST z-*I?8=2MQ`YB9m;mh9NcW|DU7YA#M{`vKER*ZQ~aU>jf(h_G2w+g|2qkJKNl%4q#T zlKLM$3ySIPtq1Fup;l4w8E^1;vDd(25rv`Oa{lQ=*nt3p6so04C&!;jdFYyM-7EHr#>b4c0MmW-_tJNQdlWNT7`%JK+DOe~9*U66l!HMu zoT8J&mY1~%8^|b6WPF5MI#nL30Tr-WdhFqRu-n@;5GUi{;2G5EVY2hY;Dh4ezeKhp zQ=*z1Cggr}DY%u~$?n4w1+n+~Xb~mB4<(bd1=c?mayrF2aKqzb%xDaW zO^52B1^ms_rZf+j%vE#DGjyAHhb6T3Kb6OkfmgOu`E#+I# z(vn?WZRAuy_m-SRRdqR2{4I+DjZHZXjWzzP>P9q)Kc{AXQ*+}*{_23B`W83VwATB< zuB7D5Z>_7ZF(At)>x6rYs(|0nULXNQ3)WqwV|bML4%(j z5-|Mr{>5m97QtCtU$vmcsBc7TGELQ{y4hbN(-{k^hQd_YcKgGpnho1$bYya4L#-jC z%Ff~A5q3R1!;Tg0nP0-?(hE?$hlb{Vzl@@eR zR9#dpqW%;yzqPg&Eg)qmB;2Y?s_I+)A+w44iAG(BF~DE%n~x)S^ney60qK!sWgt0J z1R9%tRW&uuybFLmIC^N3zeSokOa-H=y4v5Q8AP543bXJorH-AjvB6hU6{r%ngxN9N zzz1vm1}<4zs?fznVoRXLXlSjkZwj!+7zpYqb(A8F7Ma7{*w^4+YWU7ODOc23Hi~E= zCM=0*w+Qy|29@l-^NRDvQ&LMSDh4R^tdnvgXmFtb-H6ptg6t6xEgYz-t8bxVV~>|u zI=#9q*C!V>Vycs0jR`HaqZbH9z`wW&vy)iA8Ca<| zwFXpqbq%37hBkU6*Oj#_+YlI*rU5KXg)&^_Xy+47BG*cC5!KWJA6MHD6vj4LGK1^& zCN;gP^`3#%XkG2{SzJ@qRr?y7xUf+6!@|qQ(Z?s2VoXzw&_#k=ObWBhXaGK6Usvl_ zuHdgnFTw<3g7UDXtO`c14Lv)djXxaZx1}#6pyes$M6_+8u=-YnQHG1j|W^WX8fFM4}Q* zq{lP|M9kk%BcQZTpsv2&sDmqE`zS?n(ah;v$&nUT)%CY1G8z`nf^CN=ObmUZ+es^+ z(6IhU9Rykhey&X;m;^k!GlOIE-8!eaa@4?N`wZTXxxXD!R*- zU8b09z;j|gFG;{Q-MdsH?8zP;mq9OBDT%kxIx2m{Fk^U6QsOn>b2UKjYg6NUjq62KD zO0`8F43VBx(L`Hzsa8h&d>6f2H=Hg5ol-a4uWZ?6y5Y31gUeP}Meb1CngtDbMND_l zazefzBS+^yY*(W~M^EK<;_x^OpNxb)V{?`3TqEpU^K>-RCdG_f->PCywpn5{oS>3s z+bk72x*Asmd>qF4G7|cX%~h^*t+R8*j08GYn_bp9A(1ksS+q2VF-u3++k#^ZrgMb^ z$Bew1MN4xSb9D4hTb;6dlq|AEYpGRQs(8ClNo%{^W~tE8N5ohAL_hn7iarq{MVA#Ts9X!$ zW#^g~D=5a-b*`sujdFEV7Z1BV9W$tO!4x|YcfqtbM$&t#WT&ln>2MXD5+X$#piU+I z&1NZ!t!>OGqO0_*ovT7er{b%ze7YEAUs2peiUo}ykj$Y^omOp&snF3xw`9WznyjK9 zhDae1G8QYSTnpM~%PyOvz64#XU>91)3OYv%`ob18PyEXRN}gZ~nx|#I9wKSIr`vkZ z^Qq|7A<{k-4b?8j-5ONM6P0YI(bLdzU2YfS_^(yAI~5dznMUrhYg4L4Xbrj?^t2hn zm}19;XOz$|rj0R!$8(BF+mqv>j(=}!RjzIPSG&?n%60rf+sNfQs*9wwXzw_zq<&>f zFVoUbu_cw=rlMLRMj{=3BE+Q|b&TDDr6;SXZrm>1>PJK{--vNEDd>e9V`fl;-G{ix(&S+1jBcw})7Bc|`h<|@~@R@k}9R;lQ( zLZnayWXz?K<}1iSK*w*iX-jH!{Li+in62~#l{7t+ty0Hl9zWY`m2`1fHXUDPXDior z`6i4lx-#dfG|huHi5*SmMKQre@}mV^qC{}%ac?zOxV*g!aj~Iaa#=2zZ6qQc&QeiX_pt%-x5@kW`(;IE7JXTuCiEb#S!s1;=$J@DL)ETalu2&EpG^XyFr!K@( zqvK7s=$I)xOC?RRSxV=sXed`qVLB;P)6$hHm)5b1(Ll5ODpXdqRdw!7HcN$$&QSj; z+QqEDRdJUp7T70d39QrnwwMYXy-S^nVph3VMgO4w&$f$+CRR|n7WAwwyUeQuRoJp) zTJ<)?y)&eBrH=2jCB@kOd6lG9>}s@rDT;@^dQG&gHPb|;A_P_H_+(q{@+B%7R$k1x zz^AIbBs*K_Nh%tWRH}{paEL2c*}2TNcWJGPt`3o+H9uPk&_;$!Xgl9w%P#vuMLo8l zm?qG<7KL&}mo;A{EwEW)7Cx7#q;pk4u=b8M8qw8ZPmg+jfr8rTd+j<@=;(%IDGnRA z%T-kWlXe%UVX=bBwV*az(7aedF*8=IpmVgKZ)_#YzEjbmw(K%3`|S|vM-^S$Q&%OX zg<^}FrHi}N7IcA@9WuZLQMNW7P#QgID_NnV2W?W!c>TZS(i*;P3oc!tsu)lZKC*3% zMwZ+4kMXT8MBS(A{e)frQf)|&EvPiQ{#^*_s|1{`AO--hju+a(E3|Rj!`O6uV~FjK zD*C)lI$x_b*jDR&9UWzpV!DOaRQnDW;5vS)Ej-3kbha>~A5->EQMp9N)W|?vRQX&L ztqYNUf%%FQ_qm~58LC#*3UX}L@%m7WH>&8pHtC$>mG@f6g>>{sMS}2B9gnwls7O-L zQ2i=q#b{blqe!7DS1eYfW(BdL8K4vlwN`~skwVp}xKfcq)v0(vk=|AivJR{0Hz87V zrFGMN8LG4%NJ14Xjn1Wq9nFf_K)cB*yDDXR*wH=-uKh}rL$*d`&R$Y_XdsF4vn~Wh zYxIdK_Dj3?n0~Fz7wY<@4=FXYT3sx3^gyZAgF~-f9bNiON=_J4XAILXsHmf-V|ZeU zWhN%O1|+_-rbkalFI?z2lZ>JiT(I^5FcVMfema)OaVd^*-Me>}h?QWNiA54yRnv!PEfM}D`< z^AlycMJZ?YfLi!Xl(B}>rD^z?fozB7v5Hc_k&ZHYS`Y|XpcqE4v0+Gx6_Gm?!n%co z^&aHNOJTv4-RD3|AIlh+kOvWcStcX>qVb7z6F{1bxt0 z6c8%@gzkTX*I$J(KCM>rfb z)W{)dlv5#l6kDr%_cLIE(RRy&J|?VDfo9rmZ?Wx-xvBa_-YxC|d(%ORfZsMby8HTk7u~&$Vc4oM(PZ9f!*cfLJRwjb+n_+c?=-l;%5)XS}O(eh9fvGWgQ9; zD<0u@P21g;sqNe8R@#Xw{E^ z2|Jz|Vb$>wR-Hhreg{rr9lK|8L8HHI_)~z$_*~Tc|ELSm{jmZ1n4>lDds4A^ha{G>OrD98j|kAEzN$6O0~H025qeF95)}DW4M*bj)4^GB0Z5hvk6ga3nG1 z5}dEb4=2G$)U5f$@Hl4Q2=)!klDz@8L6!`VMV1^AjO6=~_zW3db@l^rIC{P2ajqNpvy|lr$Y5_Yy5=Vrm=E7l@uNQu%#|*NNs|&eT#gz}G}iqjx0z1s_L=p1Fys zyvt=X#Gk=hBn^X_q9zlmX3}DyLvbh>f7W&|_kImDx(1)86pX*PkK+^2`~Did|3U;a zgs!%}J$KBWfy9vra9~mY{=Dd9gM+~O_dfz$=;1c0NZMEou0j!y$Y3ODS^BEgG5aQD z;g=2KS1XgAi#)=ltA$BBfbu*xevLqP1Etr;ujOaT`#>jP$d131t(!6slMct$_;sJ* zGv!R6qV3yqfF@l5bSjxIqjx9W1#}kC4eTUIyjz+}biF{!Q6J$MR|p&a3TO>eFK6BX z?+Fv(_oJXWpQL+`9$@-y9D$^fb)vqzj(=1c`3Ep7BWpwGOH{|~WK`)G4f2k3(Efwa z&OwTP$4Sll*8;yLgb#$5tyoU{kh2AADB?>mCH}s^)9wNP?})!A@~3?O{P)BUI$4*r z9WbKJj0sPr$IZ8ff3^ zaTY}n)A0t?H~zJ0(eScb3*M_=N_pXErO2_c^#t#30T!oyBzg2c2PKtE^s zCphSyY3Dx7eb>J_jxgT`KfS>y4d=XoqtoJ^{Ee z^$f}12wd2@OlUAb-(2ZisZoK1_X9_LeUI4bQwCQ(ypMyfogrx{|7B`pp#YaKe@N^l7UXqDRu)Ft)4E&;}3v~RvxUz z=RT^?6Xf`OE^uL*K@xugxG+tIC^4;~uVG}+JVTu9>;v?H{VogweA2E&0ixxzoU&7J zz|n`&`b;@K&zXJ_B#FT(36apqa}d3n&oKq#8=b2EbbwFVdf4lb`3-`58kaK;$8ZbY z;GV`B5BG>DEouzIUfIYYJ|mn@Ad+u};2WwftT$a4evoS%Li`GC>1`-p^tTnlvi<)B zJcpK8De<%VDW_Z|@q2-fW%_E_61DyDtCqyCbW)kLdx3k2UncP%fQw0fgT!x3QKEramx=zulQ$3qH|~lM#{axCqXm zk3R21*?i*faHjtNldMEqpHAa)fZmh4;B(JN&xIw*C7TaG4XpZ%Ot(?|KJ6GDtkk7r zjNtq|vX1>F&KPwWTRwjDN}xLs^)y%}_d9zSKQ{VWkl$i-x#he8an}(bj?sTcG#<0N zr`F-ThvZZsj?w=>bQH-;tTEPUh>Y?yS(%&)cw+3i*uwTClS@gqji(uCT;^V&pAl^V z+9UHFpg#}|08P&1WxoYOds=~}8YUa50yNKuW)`9sGI~g?bekCc%jhYfZeX;V!^v~j z(G~c(js&-3jK#<>kJAy-$#hVst)SltMo%2jxJ>SuJ|b!XP0i#UoTYhOKnG^-2D3op zfupdOrG1g^>O!Qpp&fJVh5uDz$&P_eG0WBxm z1~e}7agDAA>dxE`l*5Q;1JE9suWR%&pvjr<1NAZQ$2ztE{y03Ddg>+u?<27#t$ zo(1%2qQ3$^5>UPNUyeFa$GWx!g26NUyh_eA7qc6cn zGBSEfVdz1Kq)R zcK!(IP6M;`=pOhu4P|>?KsjDSQa#U_Asg)%<(vz885lj!iE`|2_J5)r+x4H9<j{!Zq9n_ris_Y|oZMfvCzy~M&ky=4Vnn8kpn7{d@? z9`TUoFtEx@6% zkzcoL$DdzZv335!o4mKZ@XFH%j=cZm^R4?2)^4tP`i&8no}BpR0}Xd&<=RYTomC?>9fXK0nR9@4cd*KL2X(y8Nx*f4Jyk$746RdN*B>Qh3{4*@qsw{@Q^> zdsE&#lsfJE^>b$Vy4~CGz~)aMOaASdpZ5RVsV|SXf6pDK^na^p(4{T+PrhdMZPm-o zpVnM~3i2p&D*_K8Uq<*4;d_LB7^?W+GUE}v2$cv65tbqF|6^`I*owe^2sw!GH9{PW zl!`D6VJyNFgmQ!$gaE>Ngl!0&2>TJZiu)Xazqgx=z||>=HeN#aOLlk!(_fTk)Th$1OhjPf+=}&Luut zIS9{jh|i%AJUkW%=jUpT__gQx6%f9xZ5Ib(y{RHJdk*+N`D3r zB8@jt?pfg70_0WL<{R+e4V$H*oRgJouFIKM>&jz1;x6RnbBapWw&pn()3xn*PDNbT zjh&Ua)}3ou;_oWk^DKh6wl&we;ptqx64$oiMw+;8+x!2Ex^ZX9yxLCOiV^3j1|M$E z!f_rk5!da`V@=}P7Cb;DuG@iUu*9|9_4q&>4@heV2~9LlR5sF@X|Q`_BS4MGcm?6jc$jk8tfj_fo?-r!*nagGLA#oEQxUl zOK}6MVPgnF2Es6ekqDy@Mk7$KEQDNylMu!tj6)cYFbRRzJ?R5JzIw}_p88k8kbmr| zPQQL-_4R)`9Cy`%66;Ubbie(bM{n_8{Pla6-QvD)RN21nqYhqr#wgFjSJmy9*Zq!_ zXOAjsoV|2kOW@`)+yA}c&QD+RJw5o*MaBQFxV`v;-|kM>ZS~CBa-is$YbX9S>#GO< z+K{$t)@NUho!2=1y?^Gey`p>ay8BN2+`9ggUUT1dD|^OIyZ)q?o_?X^2{4w>3Pn1M$+E7Uwu+Hx8=&$Cnm)Zufw>&-9zysh!aE2Y^WxDEX$V;e`3PkQwFt`*u0+_3@K=P# z5ne`MKRk-i6F$gu>r)Y?AzXmagwTfY8-zO${*Lf0!n+9HAh^-s0}!$i3J}T>8W1i; zxDMe@2s;s;L3kVCD+CuDq(8!m2s|I2h2Te6hR}|%3E^IZ#}HmZ_z2PBJ8MFQmA*${>kL5Bez{u0Tkl z|I=;pa4ks^SH6lQuHZo80h%H`50qT5ASe=-9wc$WqDb7cki?aVB5^rL64!`I30}UD z#M?N<#nmH8+;b`t_gy6MffQ(W8#ki^}A;^Jn7BrZ)A*LOfgMnFa4O&dwP)>0YA11E`VLDd}GaFE1(w#wL` zxOl0kNW3Q{7on2HjVDRmjVcnaHA&(=L5aT_C`lYul&t>BUc6&dByN?+#r=XJaalqV zZ+ew1?)pgLPEeJ|4IxQfS*wiPe4@q%x1}I)W2%^WGf8Hi1u1536-eUVL6NvUCy94e zio^{DN!*qw5;r&`aVw@s+)a|ieYGNqt74FHL02U10?EZ~p(1frP7?PLip0YJl6WPi zNa8jYr2Zl8xkV=zxBZHX2MQ$dph1y%b4wEMag`;wbtj2i9mU1FRFZhJsj_GzZ3KEkqb52gc#3ml{O+omh;u|W-m{ueCP6WLkVTFThqio060DCORa;MpY0zfdsaL-U{ACU`0LF_IM@{XjgLuOw0~`M*Y(w^_=i zUx-KZccBMIorW!vpMDa-e^#5&mvW22w@>lWUn2OT^kDt?J(lseO1bo(2>zl_{cc0r zpxY!L{V0O33w>Vz&qKFMe)?4ezmm)He*&NXkCKo6B_3^uuzK;kE8i(tP($@nKw4OrDjo1YfEzues{FKwZ@-= zUm&V#stf-qP2>L;x#9zhC9P*S z=a@7rwbkmr#IlxJJ>7>~=7VegV)byD`;36)nd8c~5?r}1^ZqsNUe*wox!#RIiz`Ro=yr>cqTnk<19UysJ<~LZ^ud@b`6@0%U(frm3xaPPv zS$#qExB`H4EDNcZufYW7GJi7M6RnY^&pl1Zz8!f|&DV?r*3?SNVzFjww#&SRij8!c zuj6jZIu%lS2dsp3*{JzgXdbY#4_FD=(0rUIVzjGGKxAlIN3m9Fz?yoH^7^=zSi?K5 zlcDAb(~z~z8h)3R1CE4%l?6S`8=*jg`93Pw({&-FKslHBNnEYfYoFD7fz`*ne#JVM zdDR-cGS6jR;i|MocKeEH!xvbmNTI#gp?=fd3-FD}Z!bAu_3q|=*y^#=>gTG3y3?)H z=~kafR_|h~|HBZxy3*=vUh9|!#U@#KB`ENKYrU(|{9rX|z1iW;hP@_QqqD7X(=5+K zVcNtEkTua7P-`Vlvxd5It#sE;YcR4G6uZoqS08}=wnAV6YEx+qca3$K&#j(jrMk?! z9ko`1dq1Qts=SxxaGr?r)?I?ugW2{tDy@Fq zu7jj$=5|)}Y3Ms}Gw@3DKH~p`VuR*bVmyKW zgN3iAz}(liTFEmbl027LDKJ@|Y~(e6y*e9qG(Sg~1JGiF(IyEs)J4 zF{PQGt`Zjht#h4~W-dWB%tX}d(5h_O`Za5!aHmOd{NZ~U?YqDlV&1TFqsu(F3f}56 zH#w(SgU_&1Pqz}BLsMagY}A=`K=!xIfXo9!_l9Vf*|~BWO!xOyDB^LH*!w)87jih} zy3FmX-07&P`6r0XZH0@hf;X63fhD+Fk?kcY)zfAE*_jRG0A<|igp0qpsuB$5U67Z( z-s-mjy=$7)lcpas#~Q!hIuq!KY1W`hBus~ZiRL~C8V|1$lId}GS);&|I}vi)4xz4( znYyxuxo_o8wpCuM<$n6yA^`bVsAn40M}p8Qq$2=6VYF1xXhbjuVnL} zb0>z1^{95XH3ljsL7m^N+Js(Ze(Xf6qm|6-Amt2~`KeNmjWxI!awkI5HfVPQHI<#* zW8Sc89gNXVV|+`4&d~<7&a-g7+q;`HyZ2@*`H~2=J=cbL*%vE?&ex!=q|UAMF7wls z8zIWP-pm$lnP;U=vOL#Vz0D*vHRu zJ@zPZbOkhOi?c_GpNMaWgMHXCmF5q`F9(iMgZTHvgCYD|;_bj=hmZkqQ8A(n=yF8a zMK3MEh%){1$i`L@rvng zka_JI43XxdO>!t2g`vn*k5V?Vl=o0d?s+crrWG7f4gnJ*3I>6T#PBc-=BNZVoz+BT z)OaA~fLk7DX&cooyg$PP^g~c(Qo+oPVaLu*4nMH7E+93th zZdjxw3SB3fuV0cK=eF`)=99+6xOkNQcHCZwn&`?yM|#n4Zwj>n$mXB092n@n7t_Qv zbHC7Po7M{A>#YoDW-5lOY33dz_B0M1GpY=G+-+rzR8ruBcqc5hXLjRrU2qxE$b)_ zW3Vdi{V5<$?XwOm{1rf!_Y5HU9#Zss0LKCUjY_`~kn$SqJ1@P-K0C z8zrGHAo+JH{1!m!cQqjSR{#zHtOjI#=K-?38Gy`xCLlHkS=oRrX8<7cbq9pWvOdBQ zF;0ZC?gWJDS?d5Pf4qW273`tlQSABBnNPt3fGqz}1@8vLw~4Zr0kZshK$d?lAZ~-R zcoR1OFbxnYOmYKG0R9Nh5PJdM444A?^?=l~MZrQq%HzLqkvr)NL`kkS0p0cu>_i*sW^cMjscN-wf`J=+G24pz_K$cSrI214+kn;Kh zGCvO~Y4>LVnZFZ|cDWyra{0AL>cbmbrq=;7Ul}0zCIgah1R&dq-xg>3$AF~20Lb=z z7LesU0!TSq0O>D$moMo)ML$cyJV55}3&?tWjjbE&@fIM?h_ZeI$a?T5gyr!@l5l{6 zJS<{+^A?4Az6HqkeH4)GwHYu4cDw=b6yR-u)T0%U`ps8xIw1AP2c#W_0OFegSsq0{ zicKl$Zvm2iDW#}@KJ^*C9-wVk4Z2@HZHGnw(nzTlx zj|8NieF3Sb2axi)L1zBXKqSsv3)b%eh2IJ|0{BM2QGmR{I2DjrKjg0kWd1pT`0HJS zj~w7UXJ@`afXvqo@HD_Lpd`nOzXO8Q`(8lu^S&Vk`Yr$*27E5yiGY&qd_ z$b2rqT;LypNc=4(;_oqX0q(*F>3;>x1b!==pF**!?-BI zHD1BK3MMJ|89Fi3KTz;71^=$#%@{YBew~6N6&$SKPw4+l|5`zgC&d4$;7JOOQSfcq z-(4>&_>hA4Dadhw`3EcLRPYB>i1gPLd_ln;3dSk;f$Zn5w-o$`f)6SXAN1!J!JWf02%jfPje# zx)l5f{exK_an70g#KT|oefaG7vk!ruTUBBJjU*#C&@JAx75PXex=0)^|d@87{5OwU&g z{B1|#`i#8~>PuYTN$_@%xV}T+YdDGPI{}V2#PuCOm6E5=^jD~KeMdn%lV9Hnj8y#k z4&o=^NVcC3qj3Jdad`U3D13Gl{-JDNTOR*uD?I;WQTT7c8J?aHRsQ2q>Df{FuR`YV z{P|Jo_eAAyjKVLE;y)NA@5iY0)+n4uk>Ta{j>6YRmA5-eK7Ud=JU_qX6^`E=RoU{^teM^B588U_V{e4Kf*oPMygvj_Y{tyw>KJL4H!ro{S{;nRri{4sH4&8%){$?GlZ_-z!dF^^G4MSEVF_%;h0TVL+6?nlwfNOr zu0+$;wBl_yqKWa+4Z);efkP|H*VZ7JuNgrr=bbzs`Nxe#@q7GXw*Bgi#;nH=BR zQc60tuU_PgW0=&R}mBbtJg5m3y<3z|Ka^Qz7}c}sD&*WbnNHE z(f#CmVE(_oxrsXe5AR&+GMDOn;csdR?~k-}7xqysszP18)JOUj-%?ZGh&TU5_@{UY zilEdjZfb1C2*THh$Q-Q=;$?;5q;LZLOFLvpOhW+Ot9c1tnG>E*c)pTXqY~unX!Hxs zd}L7tN4J#pf3tI7lk;rbro+Bw$)oOGSl*QsTgtXuP_*ST&wS3q> z5#C(zF41ED>78bj{R`h!BtvTZ`iO-3S6)JR;M08Ga!V^akMVSF;P=sj35iBJNWF-<5 z%My83R$$2of+UN`cW?c?s(STa{|!J{A`ZFJuj<}gw{G3Kb?esOFaPPk{^py5;Fenh z{Dc4BhW~&5P55UD|Hps-0sg;8-zoq7-v9j$&Us$KsBh2==>Oj%@yg|Hbge5t@TXkf z&Ofvrf2&{r*QWSI^oXA?{L6O)ze>#A7JO3Vh=0rFM!g%gD~(0l7b`=u}3&Zr-Fi=glmPmAwC^yQe_rh{#JfX;44-8p8sbMy~@EsBPus5`@~+NzN?bnXTKu&dHay`T04(&1H1hF z&fgb`cbBZ*|NIZ6BI@e8?Q8INP^r4~PW^azi{atY_Fz%_MO2$7fDY0Mpw$a zZM25SbnU^Zx}f*ayF~sAEkRFw1p(Cjiuz4|b$_cjnW8JdM}ADu`;jeyHT|E6@6Ubd zoook@YVk+yb_apJ83yjVzLPWW#OLP$e~dQx^xs@K`r$hZPrcf`{p&=m@Z1XVfsEfO-1y3=k9_nS z^!4c&@92%3edC!s1nwP#`+WlU=rR7%l(>e1%(Fy65Yw~-l2s7pEkC&Y!18vf@TuSb z^ld>dCx3QRJMr=B_ecYg^IDIDEeI4Zn)`e%!8`P7$R z`m!08F)3;rH`{|$k+81wu!W2&b)IaUKY3=CXdvD$zzO2xT{jU~}ZoBKowL5|* z-c&d`ICb+a1(by!g&SXesBrw5Uj!)yTsZ2SDja|58j@6{@%_{b1hVv8_l=zR^eG65 ze--=BN!oAtq3@J@zjE_-rq7jlsQVvj(og+H_nl8Z)BSEixc^+C|C{{t=3Ds>{}Vn_ zM4KId<`ERQ*6+MhIQ|*pMbUWrZdG#O_;%64rwT_GUMcho^cRg*m?|8hekDk6^G-PD+{#qpc&_*1AXw{z_`l$?3rCMl6_)<2dpouHccCF(-MsrI zB!<6JFF!>b-O_z);pj^T_{9h>KSjKW#2;0OMst23|3dGM!l%AM4gHbjA6)*}a`~gr zilUD1`{cuD(c`&*|J;5Zf4(@SDre|PvHvo3Bz&gOKabj-M=jo5=>M@Ga^sbkIu$fQ z;l?Z9+j;wH|CQC?mE|A3?XKdhU%B|ytG##MoL@s%xbf^Ag&Y6!B_+aQfAuaT{L(GO z{`cQ?vHwGNohtUfvey5-wf@U%{Xb>GD__0s-k4$JaVqx`*4|5`zc+sWO0oZcFng~W zb?)b%mo@y%!K>VGh5lDXid1K)z}ui=l*{Sg_;FPG={um{671QvAzXYAptZE~4{G~;z^brdXmY9a7SS-h% z*%VTP8Rh!s!@#dtHu5w7yI8d z3X4acFMSTYC>>))!(aJ13^z#ACJD+_fMfL}O}8;vo__L=bVK!@h1I9pDiW$Q2sK^n z|G!ML|Lp4NpZ&T7<&@=5{W*<3r~md(gVvM3ar(*s(xAC^{67#)jBD9sEr4h7#iR>Q zfgBB#==l9F-}voY3pf7cmfl(PZ+L^lGZ<3}H?k6>^ffr1H(LAHZcZ6ZH+)3_@J(HR;?feZqrDGb5)BWuwfP@ld)cK1tEui@s3#J`Uu@{P-8tIK=#=kC5L) zOYsQ#FSx;ba(>sRY1)q)I+`&`!j%!qyZotdiV^b1K_TEh{E4$$X!rDQ9^I#K?w_952UAZz(|Zep+`NtWC_p0oxr%}A##ai7QSKEr z%H90?O1KooxyGKmZBt&%v?uuCc^xHnrLn5k7YVU}qX$|UA1ak$Rx z?{`A=U_}kAetu+ST2yS(eELL`NmraHI(qpAt(PzH%sg8!wP0;h+{>T(BsecT_tdBH z2kH?>zk}#sLp=GpuS@#;@enr;O!1UQr*HeAo(yh${pK};42Pu^86Bg3o{E(LL}@dL zlek0b8heU*qYe{7p|etjMHjpq zzhq}6!HC2=;zSalNPGpqBqRx1B)%9YlJrC(>7axpDT~BwaU!*bNPHwtq*fD&1(j%Y zWi^^mCpSkEbA{-Kc@^k1m;CAql%Cd+5Hh$gJj*kY_wk?GSMcYHw2sbzWI+o3SFjqz z*zf(ZjkkRAx8MB9KY2rU`KWN}sjofp;a9%~r?vYAP!h3dYVEIzsW52YE@=PCGS6~; z4}ZScP_&W#2b@0lk3{zGQue-){mUZz?}_Z+r0k~3CeDVRaZ}v?P6Yk2#`YZT@W7l) ztV?h$;X^&IysV2)z1)3Fr1pgiW`y<-dg*=)ei#BW408O|`)~ZoH=ii49{C$TdPdKZO1v2RDkAL;HTfo@k(o?gFl;&L`_A46ed=L_?tppM?cRL!0a6Y=D8b`K>xv~ z?|wHg{D?_bq0d=QlM|=$`_CEcLTmk>;t>)?%vJCtt%7MNN|>FF!ziVG7MAAdVk@LA6HV z#?OBi)j)M_#hBH7ZI#xJQalK1gPp)@EIL3&obr&*jRXPH#6|C`{XaP;_#X{(%y6#LaL z_1+9^U4(68KKLKzf%t|#zxkuDK62`#yz&jE&;cHYc@wP+fIFzbZD`_pa&S611WoEDFM^0N>Jm!6!XV#Y{@;kt4S*3jv(fPC@jzhyxm{V$}iLX5Ig zD2oG3PX9S*CA`nyL)&4FalP3FU>}+fkiqt@R9g^OO9Cdcf(o#Q(;->R6AE@AMy@zT=Ho-_IjImRi+h?hltwzwOQR&xRNUowd-L zU(;4j1|jag*#Bo2`(It||1y@2jh^!b)pLXhFuQ!}YotM;(ONg(5dH>dqrf}z0sVUs zS`Pd4yWj^Sz{UPc0v!s01?D)ufu<&8N)iD57tn@x8xwryQ}<`p;KG0j6tj0{*wn#2 z{D@6M-1Q4bKfyK?ncB$&Ihv4;MrlK`u}30)h=R zSfl+vOW!>Ggp&n_5q0{l?mLS|=dhjOtKDgGG>ZKvroQnR09{-rvnYHK>}M$)5fy^@$kfdTAX8Y*&m-Jw5y^+YLs3_W#lwd| z;$nZ7(J^=9=rA!LeuMr+ZYeP=v&>)U-JUd@B#D#ss0v4aON>i*O3FunU5vrxpz&ZV z6#msmrj++^R6cd%u~R|sZ$Ngw?OhfY7SQhd@8)T6o-6R5+y5c{eDQI#gzks&g4fIE z@3^JM4*d^L#l1z;SMN_Fpze22!->9aIT}(kp_RtQCzxb~eJh$7tqbq?_^~^R$A`+S zzre~y*cw##=)&yujWs+yULUKdt-r_n~jIw{sKL z`e(#uA=SO1a>B`7e)$~a^QPj_;ndCBP{X%DC&OP+rV*a5C78ATBUl!H1m?|f2yb2M zKZc$mQqXx`Dqz;ef)jB~jLDxZ_P^_5{|PLCe(VnPiaUk&KK^N#>C;d02z?BXiu4>x zjt=|yGewvx-#)RzbI;I1^Gn6kUw$(@liu56{ZrA4PnG$>!W0u$wfzJB1?ic--$-3`v69eYQQ-6^1MT$>I~ zKlxKMn(4Hoho(6*_Qzm*H7c}9%&Tv9DS#%(96yf1(U=P+QH85~`pHjGQBoIS^rcTJ zs9^m?t`8Oae_bTqcm~`2;0qjIdgkVx*xGYNCsR_P|Aw{xCrg+V8J5)s`b#hh$X%iK zuACPWW58$i7(o8rXQ4a6P4e$P8T)tX13;SXhh6HgpogQ4MzsE)_gnwZvh_a#b8C+E ze|{3{pZ_F6<-?i&7kh7ks$q|5+-JCBaW5FYzr;y9=-W6H0qvartN+;!}ZT+wJ}ymHF&G-cE$-P259v!5lyFIMnXTOr)2+oYziMDaEpNAVv&8M3-FUx z7L}{1XeNBkV}u)rqNHQF($`GX$MiM5(s=oN0%w2>;)t#r-x@cf%M!!t(FKMS7QS{H<4e`Tz{a zeWkO%b{rw*dz(7{`h$1fak1aM3vu7tT~i3}iooxGhT*x`|4nS-7qQ>p)v@1yHz@Y| zroS+;U&n*^b_5_9m3_D9&4_eTJe1C#t4J(GKGkd+hof({$C%__R>SpZ!B$nQv^4&Z z>UX=7{G0zN!;d>ldHFnSt5~tRGmhye?C~jKk9{VTO2*8Z=IT@4xw>sZjrq7S4L`=B z*6~#Y`|TB~RNjc~RD;GGy>|ADh9fdwA0cx_C&^!Z77eb}iCwcbT=-V@B zJ3cnvdeUEY%ayQ92|s6`Z=}r*Vv-5$RHLH2ItSioTxl08pMp~v+sv4OzkVz0XSEMk;8h%21$;4>z4va?sTqV}JqnX|UsxCH1iIU~3HN!qm_FNwnH@)J;L zd7i?wp(AoSPzo=fACcmKx~o;6*V_K7$@h~hi{#Fh3N#llEj_ui$=>ZFY@I(;=>IzF z$C!TYUmferb09h;!{UO1-U*eJ6Q<+Grtu-7Ss3yP2rv}HoWUODwSrH$m+CKvg^zt* zdCEaZ7PEHR^P#58*xK`#ZA$a6Ig0PJ z^4xUyTj8Jd-`A@g#dlhHZo2!e@K5^h>s5~8JFPr7-ThYhC;j*JDo631R-T*gek=Tw z{`-2BqxeoM&rNr~_oDVr)NXa|S!vXxX1COh4gx3bQuAuNauD=7QQOUWkTNuQDQX`^ zZ6T#2fCo0U%IYO7rfE_HVoOX8h|_r34^_+PWqr2oI~O3;X!Q}^CCRb1aLUtE4D zz(Wb;sdwEsH63h4yMYB<#-;cXZi=Vs1Myu4QM*&`bRnj@f8c$^PJaKOd;RVo2rf0- zz;tsTj4FG`L{_Ifbq3@qVWrY&>{P0I0g-&~8IgG(6)uG=N__8`ViS*QG%JmB^{7!> zY4xZ`rlQ(AoV_4hP6|(D$iM3|>y>6Wy}>o0X3EYz#n0ly>n`zy{I#gs>qhy*{H4Zvsl2FAisueD zOSy6$|CN!x1o5@1m2RtDEG;1Q++k^+GQpg`yq!uX0u7g>TRzceDse3bGRf7m85MjA z8h(DLURM1@cr-Ayzj z+SsX1$kNme0w4>?*0!|v7xFgSa$JG0Um%fJ8^osB>g%PmS+cm)Km#Onw}`rx^7uzr zFI#_o%@?EcuZK^#k_q)*FD(tI=vh=$b9EBzki->1zka6lr*K-B(^WhrG-|gB9X%Yg zTV?T^l+D--vs#9)fm(X>=_HsOTdht|W>BjzrN5=<(;^L^<0w<^WRwY=U^IOik6~7( z+-smr;NPQ96EiusG7&$96C%ch@z{Yf<;X^5wU1GhaJI%8?`KX-mj>}`%4S@KS(j#B z8(kv)EqyuxCMVG)=I4YOnP|~}S^5;tyHlqTUB_8Rm6rUj<4V?mZ#pjn_Gw^)FPyr&+Q4J2?+vG?LwwK9zi;*jD304{SKr@j z)~~%^#i#M&XZ_mys@35AmpY*E{=G{5{i{)DuiH9!f3sDK-dk<;+MVeAwVi`@ivqu# zTHbHfdW{I+GT!?BonF0B3-;POb7hKYms|B3MY+oeZsYOYPSyILhj@F{E=8R$cdrB+ z7t1|_z-Dp`B!7xO0xkCkE+qtdM6UEE_2O2X{c)XVcCPgo(Ccy94-bND?|`H*egVp0};yJ zu3WxY>FiM+1r$LD4@S4~l51I~G+NEeEI}KMP=dYXgL>&YV)*-;A{1G|@Q%Es1eas9l=&aX=>C$kE6%FGEd#*Cc(@OHjT+yoyiZi^ob)#+B+-GF~W z$$}0l1hKFXEPd)!+x3HPu!aD7ls%MeCdu(#e4xkWVZ z!xVuIXDo=^^jW;2yWLvpwcC*0N(<55Yu)@|;7c}&R%MF6lJ>m#T3EpYz4b;!k=8lp zwuoOy6}0n64pM|gX;pHZOr>9-s!hjf zf;?!zX2~11Qe`N6%(rlVOZ>3YSyA%JSca*Dqs#4fU1MssXMm-E*SxV^+r8-j$v zOR`FV8PZB|5TI}8qh{2mMO6zak?J6#X*GyZRVU3xLSdWj);|0L=1cyzVNipMSgof1 zfxn5oQY88g{@QsVBngBfl%DFM2&nHQFes=@1~$HJU~o-q_lhg|+Y6((BN#7-Y&FjI zc6VjxHNI_vqU*re2;c|m(N*TsK%g`SDF^!sr=`YF3?F|cL8(J8#-Q=10}26f-b$mg zZxK(VI*1r@U{#DF^p^vOwj)~Myv>dLc7Rby&@o}-PX|=eoypmB<+lSY=$f#g>j#Ai zIoD`aR4z-}OmHYG@cG%84+fVB4mepf9wkh8E5$*86-G8m(7`a0925)?^@0&eU9o5OsUT zA|Ii1fQgA=jl4NFfyM2X5N)cz3Aar^xW1%FJ!8{b0<;{!(;QeLD982KN@Tmo3mvEamT*)`DI3LF|T$^18q+yPnl7B*Uu4S#PeT2IL|U(=xPmR0nX zo~$mmn_zh1sw>gR&&6f2!-#0BpAHCoE4^_ozge0tBOZl+!`w9AH+a` znIR@>5zREqS1Qd~16!-i>1RQvRa?zYw_QP(?qFkD2a$oj|@6N4UGB{d^WPD`bK>@OrVct(pDU$RmBXmg#Yi@=Mn zZhrI8z)2!}p7r@Emz(A3v>_gdl>;qcA}uS6que4DpN5&=XYSInGg+OUlwj0 z0%KYe6w8A^vRI#)C)Nj1kX0B2mR*%uLcflf#N|Pi$p*@-4!6V*1&KBp447S|`MR(b zgIZ`9u&ip$PE#ulLq)dKFre90TT~>n8v{LNIKa&6<;?00C{VQA@P($DfpE_0lF8nm z#dNsj>Gb}-o+;_v9BHA~(1W4Wye!so%vvg{(VM-+X0jVD5?y=nk$l>TnGAA+dkDqd zGD$4GA(Xvs9ybDScr|t1JvYTFi;gdO;A3pd&6=*W1BT2t~uze>jptOO6tKCOtUIav#f zorhTeyK7k+m~#2ByVKxP2E1r~IMJo1bS|icVg9}8 z*~DhgwWBBxjSJ{UHf*?r$+?_lX|}mZ5~+$6sj{?y*WRZERLtOTI17R0Rx_w!WtoN! zv^)RMrdwr*#`3A%iN_{?ghVi?0K;jjp;$+j)fFEO!El~~NEf1mt_bvzaNHyZ zXJ)Pxb(eQq?e0eNQnOm=UB1%IU#o%y)K{s0e)HT8g>&-35WvA8YAy#$AX;d3y2NR- zcW@4p!^ubPkmuX2-hsgd9aoFTdbI+aj~Bkfg#qgzk!*CYN7u1pvRWPmMv%KOT&Z;$jQ3lIIWW}2S zv>XO-!(tc&g9mq(^4yD>328>g)i1%P3w3y7hb;5 zdNaiYPwU`JE2U#&&FY#kuSAJ#qZHG;HoD$yobf%`;8o?X-2 zd^#xYY*~S)9BIc_e^Je2tGQ!+pc!F09r&2Q7AjL? zU{3LisISs+f32uaxs-04C#`bOodR+fD|?XwAs(}+nXnEW(teXnyeckeW_LM@QHQcA z0>7#-(<2lhsW|2MBr%An)zIM_g3G3e&_|pUw@A_J@*nSE=ceJevrb5lS7Z{R;d##F z9*ElY-Rnx?f=<%^$Qr9rp5>qnqUf-YTg*Zjq)A!0Zb9jeRta-zd%&>;LHQ1~nHggQ zv!TgtV~QiWZmNvf45dsXWDCY~(sY~Zfk}^tYcl>wxX!N8ltL)1hdxIbEPLsTersY$ z@DbzQLiB15oQRjhKI*dODC|Z%TKKPO&rFo$DCGv^tpbb@jYD5qz^p%(pvbkCg3V?M z^LyITh?>Y>!(c6OR7T?I-@{<$a?8zTtBcqYgpJc2TXfkIHmT+}FH{46)=m9IFX0lWH#_M$G5r^wo95m(gjE|}$Jy=V3Ckr;&QdxwD7^D>w zo-tZDKAGIeL0NlAS-{q)JeYRoP&|aBh97bV^Wqy1If+URFw^7w|-QXlzAqTH!7}Bml?fjW(<6xG{xPZynO{nl1+Ik z7cG@4ir(kMaPO$9rsVKP_j0onkZR{Z( z;v!AaN$1J6R~dZ8=%I9Ye3;htwFG_dA?`gm6V$~qigEy#42zn)ucV4aU%KTMkwN(@ zz$qWz-B;eF3vD~)1UcPLd~EUF0J+$Veui1A{K&?lkpHG)OW^6xY|MEo!rY{YkhhzZ zNg+pWcqt;|Mt2e`Ibe?gq)*m@W<<$+qM6xelNOiy+NNF|N$)Spo`C!?hMc=_>{PNt zd`9emQxz9pa=er*co(TjKI^h>Y56qjBpJi*DwAy5N`@dhZ1_q*XYT1#AQ_&poFgbx zOE$>hU*`IyE;ExtiVa_qR1$hbPgu60lqa_>k8Y{lj4+swOj`^QtnGSoH-9nOZ?&&u zR@Ld?T+w=~Ti?YF5^@eG#2hZ!`D@W()W`>RqKV{WF+8nLHKSk;^GiBphF>e#SU~$! zq@pQq=JM44VKw-#lR2BeR;Rcg{c*C4#b6<6MKD}g?d=~dH)|XW#O$?8JC_n^4!PVC zmXxcNc5V9#c52s32T_%TauKt6xh|TS?@*%=h_|0T3X>s!yCAT00)#9c{c-?uv{6f* zm*1s)#F4owzGMeCTmTSV=0ep+APzgq*xd|gokS|zP70jQF5-iY@)gjMht=GKi0>4q zJptuFFIU<-6`Z>ZntX{vxwTuyHaZ0P=+YdzKLx{MoK@ppz$h-x6nf># zESz&B0PS*8WNWyXxp@b!9Lp|A#K=sc7cP0^tqEDJkU}9hEhyNHqe?#ZDXEx_5&_dmNx{rb`?L+{zT`9-bFsQPng~Lvd1=%ZVvL0H zTJ#dRDHOwbx9@JDThk_1YNmdru z0Z2sI`#lWia(;r4q(4K-H1yG$PiGMH(lfJYE@V^;L^E~&EP4xCrn)CiBhsS} zv*&BG!y(Mz zaG&lPz*K@!a6w`4!BTL3CD>fv!lu%IHd^u}f-4&rH;ZdX(LXk}3;4`Gw4L8tUtSA} zt84kV(r{Eo6a@>&?dwj3XBL)gkM=s<<$YpdV>d5-&}DHRDuN!6Gx^Q$%KsLLF#3Wl9HuI%V*tc^fT zuXFUIx|p+=pkhyxI#pxr38TP{jG*TO8_FSqBX+gg`4u#7qjk9#kt$Ifk)mdFG6#g_ z&#&+fRO-cZ=T{U2zc7a5bhI6jVkllR=#vWm!Fu-!Pi+OcU{CxlRV%odrC8U#Y8J7f-6hoi~6CRAB?qfB5y*9;cKqiBdm#9YZF zI|1$3;dKtV38uEeqdM6xrmTt~WUPu{VoK$isUiROFf2EHb|Hr6Rw2K`E-dcbxlb|q9L?%vO18b=8x;|5})0IT|A5? z)iI0`eljOsUf!ihfn{}8o(v@~u3%>r^@v4J1{uO+GR~TafP73s9oI-^JmCWtfoe~Q zxp{G|USux&h@pamJ=mr@m&|&g-l@~IeL*_1wT>hRN-W8GD%IeL^ep8*CF_{MW^RT{ zPEwVQN9xKI3KoITj#Nl~KaTnrQJU25(%TUVRB3?R-DHDH+%~oKD+n zwYnIavGO3B2XlYl;)>-ddC{^85{uWuFczDm6~<1y4>ha6g~V8nN^WCY2B|OWfo{;a z2{7RjjzsJM#8_FSh3s`zIuV=_vOH0(MDeM8IN|Wd-1JOJtC0r-l)ULgi8mPN%EV*l zf?WPahmpTzxeIcEI!7^}=}tl0?Z%FS z#O0m&{Qk8X_fmMaKS8f&Mu!GF*bxIYJ$~hAN#Hd{gs@h`l1!+ zPZEPBAMI zAfqD~87@9{Kfpg|CB>3s9FgK-sP1{b;PtF81hnZx%L7% z9CQ1@i>KS<3%Ko$XmC`>NK>Jrcr%T4*$7^-Ha#wGc>^2U`!#j*x6nO0^uYHjwHmmc zc~7(mMzLMAzcFk{8fO#%RSTJpgO}av6?@e7-1xGnuja@6jZusuRNk3D{R;Nha9nC* zcejI`8svK7nHO2Gro`KcsQP*%kWnsV$^L2DTjWMW54_`GNQvf_b&@~b@F4M;q;x@YH>d+5V}^&FN^MX6q@1*a0k21o2e z=D6h83OxMIh_n!{gKY8Criy89>HK8J?JP zFzj~16@EgEbYJDWAc`oR+?-UKSjXf=97T&)70}cQ z&%LBygv(Qn%Dl)Q!lYckBUh;9vd zo6!HXA`@*;-^3Weu7FF37Uk%|E1Q-+B+bLFx*Utlispbe3o;_>vlm2MqSeG@b#S_3 zSSYeiNk}=QCI8iEr*}C<(4R?YT3V)SeHxYP27H{5#GpkqaV;1P!(t^=^hq~0fy?m% z0fqQTZ@-zuHq#UMivkyCZn3|UHw%cT+bp?;w7vZ-IR(l92=1(;1Zftvpef&2<7P2a zWRW5}z<|Zi7RcRB`m+I{VACTxCuPHpp@|0k@H0H)zz?~EtoWE0l8}8~-3K63lY66U z24#V%O+f7NNNi8%_rRoY1=nQ!d%<-!Or+x5LqAyu-)?YCED0_mita%~*h=_}p8IpU{II$1Q2!cGZSG>ESO;(g+vf^#J0A24SQn6kg<<_^1U`5B)x*G4DhP%F2;;n zSxb}WtZZlW14;4(iv3MYkZ5P^>u>!eoL2{uU`cuVG+`LLarGhP;Mwp+4&}{g z)tI0-r6p`-tjCJO+?I5e&zY z`$?#o#wxJHz*SuJLxOWQ>Uco&Qkxea2+!fVZ+6Q`HCT@aqnL-NyJ;M zuNcyr`VMCHb(LaPimjc^(ZP-5>I9T$o}95`%!>ENAOfQTPX_8j)C@#7Wz zSFP8JkG)M?w{ zGzLodLSqYE#8!H?*H>a7;C|9D32xU_`H$%IatvrKUL zx<{sS8?%yb&@u}d%J+;*8PfHP5ytgA4GJgVc*fL5^E(Z^q1{dcCvkZ$bSiBg5u**` zbjHxxLsDkjkK}U3C7MGxxhI)rB>S&13i#|n5@7^?)9Jj!(Ki@E59RmVbF{5b5)%em z?dg#l#B$SC?nUgXsa%dkY}U$AcxoiDsoANLN^l@{jNwig+A&zRfp`~TuxAxQi~Q>? zIe6(j`Hf9KQH?j0iL!OR_>?)Q_aO~Onl2~UnY>v@uQd2Yz`IW*5e!-gT*?m`u}Js* zXngvVx1KYOsN_Hl-hd)X;h$<$l&y%9+r6ef%1S$ktZx^3KHtRBMlaGB_ErPS32{LO z)1r-`*c^+ufi!)s8)B$Y%7-PKsH=fGn=NeNx=y@=^NCd2U+*Ty1xQ?aOjPUx!Oyl$#f-Sqzid#u;zT%!V^qPtX{%NVy|9gE@VS*KURx zocpKanHiXIwFZK^+z(G&R={SCZw9>7iB{;~KCVc|CL8;VGmcL!#QEo<3bt-Z`xGZD zv>-D{BIDE(PR(EqZ|^J)%It{~mUu#SZ!Nl9sb1#|U)VK`;LIv*<=(*FtXAjP%$&RdpLu^C^Wj$(L;frP=QI#=uMZk@Y5y{paFzeTjdic8>hs+OFwbufY?wA8C|L8p$Jv8ey9;Z{4e=fhFE zRcx9XB1*;%*@#;ak`e0xg2qN0_7e^IV5`@lyYWa}6_-Xu#Ky;{b_ttmc`*Uuhja(ec)12rvCBY+lV`T>q^5RI8VvFaV z#HrlR-KN`1@qGKil@i^6UqSC&?$G+rwmf=5eVVrqlLB`-^qFtBTQD*QWJEwu-k2}b zanmB`B-3NSwfa7v;fi)3wrGE+ab0Lqw=R`nHKIlNeVoK=W0M@+qenX0YshS^%%W%G zMaB=7I8EuG*4?=Iw&}o_SdrRpwbo!J=p=~l_p}>990pSt4NwYH0E)D6KsEsPBFLj* zd>iC-{mG}ja5F{&?2&N9CM8hc$MaQtq-u0VO?_`RdhJSM3-=a);8sLcI`L`YgCZlhY&N+Y_&uVmotqMNbSx=LdMWe6q}hO&Oltfb;g zqkLaFRZyibqXXgWE1C8-w(D+@0Qp%?-6*;@42G0Fg4Wwe8}!yf>f?B}s&u8*rBhqf zKFV}lq_YonM7bB$I{-rO_+UvG4hQ5MUYQawF#y#Nwty=137mEo3ZvvG-o2*lp7@I6 z65bBQ`9gpz8zE{&ecpwjz3OJJV2F8LZm`J$pW?-O#cMnW%Mq6ccgJxE>Fo+R>MJhb zhHTbx>WKHiI(ZIyj!wm`K*_sN0s7X09oRR?@ZqKUzM$j>b19Oy3a?I+6BisAMB(>} z^HAwfE=@kMilanrJZO6%GN1nC(>c>B13Oe{cE}ePggHC_U$5d8B^ud_cycgT4nult zwcKsv3~8rW&BKe%m5s{`kb?jCkZQ6tIxe9K(w>q^z=l|LY6D<20+6y*YV@deiEh<9 zS8sQ4Z}jCzXJh3$C1(Zd?9URF3Cx<^OI0%OP%x^vlsB?bL8}?8v$CX&5dg%&`IT06Iv1vE7h6TnMzkM-E#C~QNl#|Ehy2x zDk=&NT6OZl!IJ#N_v9s-Nf#j+iSD!5K2TIzZIK#(8)CBy%_ooIU z;pwX?9nDa@$}fw8Xe_JLxbpj(7Y<`C<^AnwVh>U{U5m8PHmmzV{F%n+;(p~CU*>>z zS3e2XLwx~5G~V^Pp5Ls3F#in7s|QXqlyL;gNgC8L@0p?(B+kT@?PK(>kq1${2qUm-;mhF2-a;!!adQ7Tp(vTVvld z#bSi8@d3TwsW)r)a{c)B7?Y)8Bxq?Mbz9Oxtxm%=f>J|_G$1e{_RK;D-gp)EtjSj| zV}2O5@$2BaXtj0^53}K7azT42*bzAhVXJi~WXlCTqF~YjSuKqJ4Z#WS;w$d3b;n71 zjS)~+5c;10zjvqAYG_s0Mn0Wz^>7E>TAcu#B6RVVit1pz)FCx)xaN&H6;?U3Zqqc@ zvp#0mNcD_CRRTRxrO`BsT0|>Vc1uW=)8J#Y{SYOQT*gxFCD_EF)O)yE4n=E35zL$b zkA{58WZs3-Q7*S(4bXY^d8Unx<$T#yY;jFDD>3GfnKR98w$nz|5wmR5jC$M&mzOfy zX5a9DUJHh%-!rAUOZkuv6O&B9D*nY=2rMoV5;o%F4-cUDTf>26{-(4mn9k#G;~M@U zC#qe+o3-Vut#%EEeZ5tRRUnu1L(m?ZFj0c6+sHFK0zYK)Bi65^+<>De=^V-dJ zu2v2(s4wC)4}M{?6ypE6pm~5BOHE6Lb9jh?R~i&NEH@C;U|S1MvAlyj0h{GSzLZlq z?;;{VFiR$iBuYUa(b>Ilb4(k6{5K17277)0hkt`|{vde5Vm&q|<5{b!@Z?OI<-Fc1(1++FcIL1FNKMH5)IKz)XbeG!NPI zcPtXKyciDajHRma2#|{^8gA6Ohcj*7H&Dj3V3#FmeG@xllkD_%Et2AU9Fl5y9n;dz zQV0W)xBY#Xl>@%_bY$(C$MYQs+vPz+{2HsJ7H9&7MX`JdRgu3ZBecIyq{h))%?p!2 zy(S`p6`jcl>?2lt5+uf}$1GOLYt$QEEI~D-{ zoP^4lB9J_cF9U znQ{_D$CZ}N+62N%5*n{s3x;wvTaLhl&WYp`BR{U_Je*D-zZ7cY)p9;oxP%N@=_V0j zlK8k1Oj4RafPP|#v0>7)9VBA2Bv|RQIU5S*@ho%wGS+XZTNrA^hs3wn`y9Mn^znSP z8blvYC!NC~BY-s61NN7${SAnM2ikN#R@jOEw~iCEkviNc8Ev7)vfz(Ppy<1}2e(3aL%1LMKHh zj&V-RkqmTBO2>#9PD)D04JRe!i5`yCpXPm$#IY!)L>0%Qg=Jm56U0GA^>b2_K98-G zv;+f3K>Ru}f|C+j06%mt1%XZZYf_5gOy>&rs_vEHUF_B=;%R+PN`9`|h$?iJo&OTG zi7cRwCr?U9MU^Kphl<8TH4;&3RA&-SPK3w-9(27xu9n&y^*8UEwDm#q1bibe~cH(1Fxmh$tT5Ls5qQ{Gn(8=_8O>0v1RJA;b9xs@Bje0z`<-pIv`mwO;;%nmCTSQNwkrllY zX=Q`hiBSpn>;7QUtp*q^j$z#<| z?r{1NOCS&8j2?up^xgsvUG`_gi!5GF()Nco9YRP zG)Z)FiP|(zLZF^qGAAWf59t#UZ3^Yd5`gep2NpiMWP~ zI8#Y$faMDI;EJ_HF2YTmSjsqLUGMN=Ur`0|ds6;!ZjukNGEM$9F{38Q357dP=jXce z8XB=?%}46Yq>1?rQ3_2B#AP>Jiad&JBuy&k5QloHDtxxxs)W+IAxJ7vXfNBeQkaHr!vxa=I(SZ&{#R5aZ8hxbtm??b$%U3yk~sY-i;)Le#c{@r3ltKE_*Fe#ICH=QKKo=v>YK;^KT=gXh8*bqjV zS9NH=meLF}Vd4THGrk&1Y=@W5k97Q#Ij>=H6j0B)A8NAxN;Wd3p6LbCB|H`$(i^IW)qs6m_?ji)&mm`pcsJpnGxEN1%Uf z=C{smY+YPlU&)uZ@}aWT7kb&QPFl9{0%pryA%aLqBUG&6I>#l>cddI82vQ%~3KnTfaq zzk)~10xL1!?Cs~T;Q}Ry+F?1I0n2=!J2wg}jP>n8=g!j|)wO7gZ}8pRJlx!;mtb^~ z3qOm@OUy|Ho8Lv@EQq;~QG^_@a5H;a3w*AeT}+NuC?JNW+Q;r>3qJ(C6$cu`$h zEQn`Lys)~Mee^AIIlNE~#hH0}hX(iNW58)NuFFm-AF|Lj!SFK-m_vJ(4BIj;;Jr$E zcRs?!t30Tk!|O^Vz9XC;Yv8TLo9A}Wy^QCgu;)tW66xk*k`Z5_oC5Owi*21SlTf=m@u` zW^j_K4BQLTQMq_ORhI{PQGp1pwJJ6JsJy{~)rI1owON`jBi5k#@S-yt{v2EF@aP|T z+vMW#4~NNc5tduN4@VD$kTs)rvUpq2&(LYB6?bo%@+E0t2<4aSRCVE|S1XNs4;Syb zN9LSSAb3NhMbE^DmqbYEDFx4<^!D-ekoXes7!_;$jSA9(Z;C5^pb~*#JC)yylb$## z@8%McXcH=$9zpXOY4R6humqJk%C5HSc%`IWhbNgVC>LrF3_`75yBe)m_Q@0XrYA~Z zKJ~*m5>0;_Qe`KKpM&PR%uNA>L?o7QW@TeAybBA>Ld@x`!q8!$e<#4^7ziNzH<6v&Zsj-Y zz)$2X((o))RN98~bU9BKZGEck%342gh^yu4+8p zjA_CS?&~Obc6#`O`$>^NE2lxZv9l|FR9mgRIufc4L^41J)*UcWv={6mwo%5lF1S6l zjY$vgdD`Vqus=Ubzpl0s(Fw|!k(3ecXjiBpV(cNLfu9~1+T?#5fZ1v6i6TL$BQL2Y z4cG3V(%|f8o%QIE@vO6kNqN>;=hxyE^6`;;MNxv8G(LUL%d<1NHH zIF}PMIN6xW-{_21vYZCGM4Yl_=s~J;74)c@cy5jd4CRg}S36Piym%@S^A_~(a9W_! z6DuCiN6gR%lzmF0rBOy6I8MF6*D8Cb`@Lb+{VpnNa1L zq9>wl5I@F*vfae%g3@JWU>qk1{8&5z^}q+^!-H=7t`us)6KNU3l%}!~E?I0~hDhEg z7>|u_Je#sv7O<``W|^J{!F9-jt>AvTPO+xM5u1GhV~fLsXABe;h7?E&z2J$o3?-11 z{9MQ!xw+h!;dGpA1QV#47w}Tx3NG2DwSpK3BM`l5C+>OAcZK}oY*8Phf;>ubu;)Ef zG`-6p8iUe%aWPHZVdJEcSf#O9UQRY!Hl;{}g&mrNGP@kZRV%pY=vFw-P4gfgHkNuK zyI9PSr6ID58SoClg<_}J#EXtFdh(Y8z^{CBcyJjJ(0aA=Alfs(Lw4Lvbued^RJ^@c4+G}V4wu-`5-TX1ZA5|SeQ-Hnw^Jo%Y_%88;^nTW(#+>4 zcFQFtb{}lle_$Cyx#eTgH{EhcKu8Nu>0;{^jbI{bPLdIJ%MQQC0)p!ClRbL6>PG5g z&~R41&dUwM?JCKO(iXQ{BJ^etp=!w-rWNrN0U_cS+{M_Ii&Vo$v)P@Obn^qb)sRCl z>l^QFX5&$w12QaAA}pMt!T2VeY6>kYIYF@84ZC;&VIv~ERitO}5M9l{lpwB{Wpb*V z7ZmBif{sClko2W`vpbW^Vpu@9{EE~wfy|ZKHZMM&K z+emOj~Mwd zq%tf+Bg8$%psvho-02s%*JZ0P`p!(w)nHCMgIyt%r<$F=9QB>!#5C;{xuYqsz!^e! z6=0_7%8IBeXw6l~8H%ew()CtB_|;bBdbL(%4yUx~&?D+>EDlR$2hktOB^a4@QeQDj zDEGt)l4up=p)4M-vw`G5mklI`vkV|(=*oc7T`dD9#PZB?yIr|nY}TS{S>s9!Wmi4S zN%;sr$u7&x%0x>Yf!TfG=V$d;E0=S2?1e7XpBSOIlaH6T+#G9N%gxlQS#AceV<7@> zEw=6C%|$FX&sw`mqUseZ7f&x!sSM#Rg~E3ea!wVP0VGW5y|q>k;RIKFwJh<~QpE=} zy%Z=sUAFB)>a~1|_-c6;pLijR`niHn7at1Ji+xzNOQNQTua-{{Uk=uQyuAVPGohpa z>8KVz_U+2>T9yp2rOFU!=`y^QCc|q&hIk&-Qo(B(Du{wi875IvWOyx2hN18Q28hrA zk`nA;FU;j;RGX^P+O=JQN3(?ZXsQr_mM+9c(}eh_5aOc=9?}&N1(`xjqNWJ((KI1W z^RP5PhB1t0l`-b?AMfEc_f$*Gd)N>-#}rXO+UQ}9hM;OUK}DdLnKt553E^*-XNjb8 z2!lGeV3d|{pPZr| zwVGc84`RwF2oyqlv!jh1F0Np8z8g`nZnI4RL|kcZm1+=Ev}SpKP`p1hW-Lj}STZB5 z*w|@5UsB6(^Cd*OmoEYQPQJ|a`uH+$I2S(^ctj6h%YkfzD~2R1Bg{xgq^!LASnEbo zhk?4afW7vxHyc-*ldBeVGF(t(mb)<8JH2j%aK2jvcDD#M)<6LkMj|Z9S85y0#`R#8 zUf68*_W8%E8ReF}Je(Co6``T~!xk~QsL)oU4lk_IqNGhwvlxQ}2krVH9i*boIrM`% zB-V*!T?|0!EcnWqJLC<`dMlw1W=U_9gI(9Zl|}Sn(0y%y#lKll3q(sm%3oQ~GaaUh zf3u*Nrhp`x5*pg-V>6sZK2A6E_OaO={yo-{?1Ze6!f6AMUaVGBGLdG9s~A=aG)^Go zG;Z;nco!!#E*oS@2+Nh=l5GXTZ|o;~DKA?y#w7L``QQVoa$ z%R6yZm)GWNfNx8KweUmX;-au5zMON=%6B3&9*@NgG{wwjO-a&F(gF@?@EOyWG?bLt zbs9L&xoJzRw4rj=od%vh1xmxPCPu>-BqmJa**PP6kXDMA&kOKa(Q>pW));EzAtP1& zTz`(#$4kNKB8AE*ItgeSe_jl_1KEnz+BZtiWO3nitU)C@;CwDrY<yZVJ0R3hrW3xF|cB=xrsdRZGLPYO7w;BS4Du4)Y_m&S8GI zMgiPVZE=_%wh6#!Qu0PS+HIIjEgeWi+WoyLJsl<4~3~c1~v?i ztuTAPLa@2v(|_yOPjxt6G~ndyUujibO``a;E0!>A7ud8VIk&6F!d|O<;`&&jju9&t zn{_hA!`kR`ToIQ?ryA23_v9SWRu#|Cgo1_h4A(G5GeR;lA3GfdAeBWPh(Z+V#|F$u zO~xot%Xo}5cD4%lSW%nDChz5gx*Y;dLlv;H@`^&diY=^+lkF^H$1v(WMni0E{#oxoEDk-WBa7u=i$GNhOQvih?l z$4l3G+_zj!>W!T3=^JT)p4}Znt5iH~c-GlkUWjn^ztIpIc5xJ)4z|FfRh2(iZ@^vU zw2-|`BVmDYoAf{~Hv2MekRXS{2UnXM3f#lBCXHSVP1x$Tx>$rakx|rXJzgITa&lS&K5-Ft%#m#bQdkaHb_U5KIsvCi#GwZbK6jWMMgtT-;P zqlF{UOKUb?E7=-D2Pt)fcU zmeYz9ycXJlZRR*YZ50vDD~D`5+Q*YW2uWkC&B8ZEUl;XE;HCtMs^oA{eJ59o@ zN*zurk7EI3i_Z9Mlbtqhe_TiW+9(1vx1ZwvoQJ7oAPhW@WNAD&cYm zOU)HQR}IIQ!FYSjXj2)7{h=ld)B&Zf^(gt-Y9 zRG_7V{T>y>1js&+U38{rl$4m*tl`=UIXi>_G-EU>89HGm8$-Or)5V_Aq;!&OOb?IA zu4HM0w+Yj!r8w=La)_Sv@~QAf0PT7{Hi z@(^H|zL5&fndidOj*6dLp*|Zqlp#>#>yx#&1L=O5O_=L+p2w~1R=r>FOyeMutoXUF`P?H5%06KWArwoHQTjIINNGQ47 za%~b_2DF#gUBz_H7sp)fORX{jc_{;j=+vn?+{DXZG;JG z(LscNuz^XJtBGqeUJ>3ecbRqVmH(5a!HgCri+OVK5Q8VTS*HY=FHRBwi@p9 zMPlltwi_>WqY~QgBu0TSw;o;P>nZ4bwq3?}10YOU9QGC?;eavGokrn)*O(<`XOf)L zEqJP;wvS>gtWY3I0i}~#K#6pXP&ZORBy`tAS~@=YPPFg5j)ov?3uv+R>jQP$;o~-v|kcB zq_X=1Z-516TIPnt-7-A>%3ze#c)CkH453s?!s$9IeN?yld`GYh6WGYFVXVXx z_V7+J28B=DPF_N+WaN6P$;XLL1-}Kgr0}4!7i=tMW+>QSQ`0V)hxtN$Z3^GtDl>wC z(6s*&4h>8ooS}Nvf_K7GopeaBX-2GYoniaBm*j^iN9{q<%Q7lKZ%V? zg@zFcnjdXLi-jrTpzLOlH#AIP!)67G|DJ#r;&zeI|)0Qto&^!H>lH9Zoa;p7n|Ra ztvXwJ@3U8u)4PLOQyyt68RV+)hHg8JFl@^ygb~_Jp$yS#Bg@C%Vl_VG;%_c-v?Ok; znm%^oZQXcVux?#(!K*V+oa0+x_i*phN~K9>XXwW3=EX{9kDkcbqvdllC%7#705{Ge z_=Y=T{R41r4mO`Alh+cX5$&0MRJyjRe8rY`$EV%UX4C#ylt28Rwi_dvJ3yUHj=|d-|te@VsPb`vkZ}!m5McD;NUE z6^5&Y4hfIe`FZBJF{!|EN6oWT4aS>4vYMzFPl9NQ%7%*^G~pAoba9+K?UGDP!RKdg z#99a6Xr*)-8ku^jztTpzX@-{xrGBd89eHd7kN0s}l;!H4o#q$u4DFckFt^;S#iE{w z&7u8I0XURWrdK`YJEb+kMYdG9Ec9GGYTzpG9>>p;i7EKJtdxWnlj3B03KdL`JH`F| z9xD?sAkg&KNlL?|C|LqIk(Pp;5{7qYlX_~sSSP~{ap_~~G!pAwHOa^lbTy^uAp`s_ zE1qeyQNA;g&1Y;tNfP#l{F89rz<&}<3r)+)7ycgxkNZL*5{V%S!nMQuyob*dkg(To z6H-dDDvBIx;r1ko%ZyH9+`fWorFm9P+@>JYm4YP$cN9Mm`?FLm2^}kumWrRFH&8S< zejMWDOk0zRRbO82kO7=p25y-^M2~LlrCD=Yu!Tn{1(ZsQU*#h6eb8NQ;@PNbgvfqd z-k$0vr&8fJxC-?e))I8x1q~-LodRCO5+|x-0`#_=la`K;B@%io%f_}+(s4uVX7>la z;vK&RNGhQ;)0oh*VGUUVG24`Rz|&VQeTFy1oO$T_4VniqX(zlUZ79qUjhb@#RPW>2 zZpwnCPa4B4bo%gyTJZEC&JD5f>BAdo0n|resD)4;;*blXKGbm+M!mF7V1d*}ceI64 zFNL8OOug8nES&lX46}gh!y9=a)k|cQ1yvt`Ar@ABXi1Y}_zH&SH-gO>%BxAUH=`D5 zaI4NdED4W^M>n-m-yZnQWknCL9J3TXdYi)7?8ANp?~8X59W7r!Ul0!~#U2fQ z8BE|SoTcfE0ZT54orH5F)z)6Nf|fz z8n0AmIBT?!g<-BR#9kN;Jk+?Lp@$g^H1J3xfW{ii>}%*DZM}vc*TBaFPQa>bVxyVz z7;R|#9ixn5v^CZ+mRbXkY@TDxQEalt8p053*i7pyp}a8^@BESbsJR!|n693oTWV_j zejHv}#JP75~=1_WUjOcWh(;Czf2DQg?dezKR62T&5aIml%iUttuDsz^vgyffrh4YlEhE+a7TY<|OGsXDjz zvQa zu}hqxUYw|G_DNT3rXUukbaM_v&E{a%%YnY=1HnBV7xbLE9hH}Kx;9riI<=pWOKS5b z)Y^w_moVckA?9zgvSK=Rsku3580*CvUS{nbut}i^GER#elHU0993l$_jU6we!L`zGIdi{gQ{f0oKM9wsFcJgbd^EpiblA zLyW|7`8WP>z%YFQff3TiRK$EcLqA|dVDwBq#uiDqXzs{mdYtj{!BSE>5;xE=VCZSpgV62=~_eO}LS zfJC0=AaOiP&xjJ9wg)DCDMFJ`bCr}*3N{bMp6RMy5zi;1ubZE;=@o2J7IaQ1m!tDTI6}$h&e*w&yulmEVKCERA4u->mVODbrZ#1vQB-I4HER4 zb?jFz$$Eh4anUDie5ntv*u(jJ6NUC7 z4Q-#QK}*FtZr%|K6lrs033WizMq6IAm%`3hTIkj^Tq<_9dd()bHpcbk0XvZ@Wv%*h z=E;%~x?ozrAVATKx7U?^wh`DBbUY}Bu5Vr6vWlL^q$>b|O03}JgLZi5W zdM0|iwHG-z?dS^9EY*T@2<2ujbt3FXq#kI&q3u#~910;#PFz$s$-$X}H-l{$%GXg6 zoy}jvo)$MXxeXeFv_i?z9ZTXiCp-YMzZ2E4AB9fP^BM}>UYeQj@WsxyNd@s5;F~E9 zMvg9D!m!h>bk5cht!-Ww0Z~z~C&R%HX}_;YpO31?M#^eP6V9PCLs7e=CuCxXx@5z+ zRQcGG6JoJx`U4>*j7xKR8PC&RUBOjlyrG^aBYfCWY>dXnnrr}<-YiWZQiw4ne#2!j zkVAKtFZyY>TkVUu1-NoK!X1mL<=C^0_(&LaKfV`X2pUfL9Ohi!!Lz>N1^N6nyb8~+ zGSjGI4jQqc;ayjJP|1fF_!8Anlqeng#QiAwD6#PKR1d`U8p4G)+nlz0CR3d%+&{Nk7Tw#Am^0dGVgbUT5rz4a?v%d@jDZ zX2hP_So96=e_kl}47>!p55@fD17u3ok>EV$Tx#yXkFLqy!G_*SA{1L6BzC4cXqa?u z&>((g(Ai#H(7D5@LI(JVnjqw)oS0Y<29_|C9*jZV(1LKrYB>?|5<_TF?UHa{LK^Ty zsT7YB!11@#7Z-^}>r$(SgE*JA)+CPlOhF+BL!ey5#S0kV9n3g2g#a3dSCRAn4xM@h!^iJYB1^TLuPI?+a!v?OgO^Dw{t>jnq{phyW< z60~P8u|$zXccanWX!HeYVo)oEo&d>wS%GpZe{S5{%%>Z-*7NJeZMA&6ahDqZDmN|4A4?j8#_$m&G@1RWP``7(=b}i}S(w>h;y|*Wvk9TwYox58!H;B{9_IO!L8S z5Y?1itkHzX2Im*?#U(yC9{e(bhkkv1PHVLe$MNvrm&3EG;Tyc^{1X&yzZ!o0b#(rk zjC1*MI39ld*D$^~AI3lb-_?-ZGWa;W{P6m02o98gz5XzI6MwpTdph{^ulUpX`}2$6 zu;%;!;@9F2lzlyiA@B;V{|+C^l zC=vViqWF6L`qv@*`tkMon~PuZ2N)>6`oGH|Aog$k&fxe3?to&naOL&*|IW|w!`Uyx zGxF}Yfcn3Hf_M==UtWCpfFJoIqvBB<@=bg>x+E`R_W@-tUw@>RK3<#+#{_VwXFGgN zK)O1+#MfPopaL%WaP@!q=hGW+|v!P89~9@|)8!F};x?WAaZ1-YL|c z2j`Pzw8!r_26n{?7i5c8{gH`{ji<;DfAY8BtE&&wNQ^x)Y|U>MVA&2nXIXqPdNa7W zTSA4N)splmc=mVhNmBjceUe@$=_>nem3~dqXFvY%3jYgKVJ|>ZO}<|z;FE$E^G0>hYo4vZSG|J) zAzvT7&b}|Fl&=c^sdyz#z&n}cgS&fNl3zi}vrid*f}g2~Ptoao4*{Z!)oP8u;9q(- z`IHSNq()WzWwM+tplBcc8x!9r`wiX(Z(V}!nL#8Oc${Hr!&@+cd4SGG@E6B7vjNt~ z0;{HY_FUMu3awD+&RA$OhAEgbP2zr*(1f8ebt9r1zwSr)I&2Fn`| zL=XRk|HY8q2hDHbCFBFVd!2uQv&mWcJqDGTK7h#D_+ho4P~UR(fo%R6CY}C_V@z;5 za18Q+!cRXEoC>lLwK`p_GH}fkw8YQs9(+sj8J-<1lW)+H4xRzp4d^TBv*l+x83lO< za4Y0=PhlpfU-4Dx1AY>)E-!4L&3~!jUH(wOQL@82U194Y;d`>4q)GW5rWnSi*kpq_ zuu%Dhg3o@U-wGz8Utq?I*(}h0fa%WX&`2=;l7Maj9RtK!05{N!gabei!PG#=R=l3C z6L_HbCcJF=Wxkk|uLcSgw~#ebe9qW&l+?vl_=2CHNoAfU2`OaxeE( zf1#g{46qXL*Xe2jMIEM-JNT^_EE~+`*_teYS$QeBy_o}n0O;vWOj#5suwYiswor+! z%CK;$GG%zv6e@r(@78FR0WWMkL}{ObG?>DV=?a`a(2)~Vc8a`>d^d;zl2S&%XLwVd zAb505;g#eTfrLN6V({-|{bdCVkPmL*h%H`&R|!6sL+`jq4y}aSNo{7B%N&QKlK_hv z1sa_f_Hl9pwh5JV#oCZAklR2?A)w?g@{Yj_8<0XYPlhD{mqnc(A*)jek)^S%P-@|9 zwf>HQ2iyY!o{D*%3HRbD67^g~d;B)6{>aW};p6_vmY2~wy+dlM98wDj!%pp9N35f_ z*mhL~iNRMAl0RC)xnxnwl$%o`T09C7{3_8d#IQVs9PLkyFv~X*+zO#tox!(-6{j|b z?C$1Se4K{tZ-fudW52{NAz{*>PVK#|2J z!w?;%cM#1=ZXHhnrnjd-8PMI~1P)=6k#T&ax89@?^U&o-p zJ$39L@zX(tJ)yk;#!5*{hVxnSH))W`mOXZ^l(|!!G(0Y1ce2ST-&2I}Z+}5S=;}i> zdZYpt_$Aq3bVn~QB{}Fx{*46NHFIRsRMoviXSo^-TQ{GZVuQZ88I-2CNEEGdT{#Jj z{C0%WGzOjnmMCLDh_GV?M5@A&aGM|uYXKu~EyNL+iA1Iik~F=|KF5Xh`Hi?f7>`8} zku&sSw2yyTtO{_3__h9tG-{H36Q|)ch@h`;baPgj*0`NffQvH+9>22gdeB)v1YW?#hRzf(DCq>39 zC+zrS&4lfXr|?J!;Wf2`RTr}~fowtJjvl-i#pXF>uW{cArV&I4!C!P9Z~8{B!QH&+9F>tmKPxnp{@V9u`|V zhywqUzv4Zmrt&*ZaAQv+@rzG{6;0nlg3@7*bf2H$zK|?p{fDE|;%V@EgJN1uu|wPa zVDlnkrU@9BRu^CVRK}2@?q4i8D1u?*#>zKTKCQ z%(rki$PMxRhxi;|52#AlkFOI5i6ncRctAgI-1GbkBx;beH+Vt$dE+*^hhjA0(9sTuZ#r@@MbyqlL) zUzglc6~i?IhV{U*e3ekIPOQ2VZahlbl%rHYb4jcDDC4bqZiRjJ4ibWHqAYQ`oA;I8 zCdy>8jGNbz-uo`c6vS;pQ0=P24HCRu^%gTj1o*L|iD?k&RMuKf(#A?*Y$fIy5|bF*bb?WL-Ja%E&TVCrz#L)7zxpRzy+$6+U!L z5^c<{vOU@;&KiHH6Okw+x3I)kthJbH*PBFH*+@f$mt07~tY+#J-m!!AcD;cyp(OYX zAW>k)U7#Ri?ph1G-m%G|!uF++*&2V?#f3^zop_0BcRzGXNV(~?wt(ODUUMC+{N_t& z`N!9!6Kb58>g8QPJJHa)1|hmyT1!rd;zn!l0=~L<@;gYHd-?apE{{x@D7SUYf2sugr@#V$-{)_#iAD;c~Z^YjK<}7f>&+z98HZtUG@f;HI zUh?%;UZy?eU+%s7>6!6>bObo#zj?W5_?n-d-Aoo)@@kNOnUgXig`K(20L8bDKHTmN zFE+h6+<7$ow5VE*BvW@dj6YoOiNHN>1McU&u1Iq_Wp>83&=b zXM``8>>!4U8s7%-aEXy1BOv^II)?%!vpXnr_8Ln%LOLEz4S7=^#)dHJG|p^zM&OlC7UK+C`tB$Tt&Y3aMYy?jq( zAr%e|ULEbtxM%nh04F6u+!6frcJd7(%Kj)Eug>5u%{hcw;4skyU|vEjOMssZ*iT%X zCHEP;2h0x)+};w~UbiKn0dAX&e_i{y1X*oXaXaF|?7pHQ=V7o`D@&7?h>R-Up3c!I!*Wn=J|z z_+h>`Bt|7Dp{fnm!dSJq2o}EOYK(q*h6Pv!UE7EgtTqclO9C;`p!hJ4fSwUVWoppV z=h%gTiQ9R3nV52n3@pfHkR(Sp^E9g%@a>J*3W~>B0#Solst49$A*>_6I7&mdf+REN zphX;22O_c#bWyQPDlCNB2$T|Xl8V>KNDHcu453+jF$+6@-4ZQ7TadpM8tnFA`5}R( zkIN4bJI|~946ExS^8-cIhZetm1IPbA3#(AjQLu{IvJc;n(LiLUCvC!@uqpCRhsy5h z=ce70cR+S+v%CW!?8ks1s6Pa>VwM}ZUC~x1?@;mUx)_Ezcg^3mX^=;y3$1kSetd7} zxDdR%sDasfb3TNq=DiKVJg(eYa!n~dLZO|@0TjHM`jb@g--;5E&ye?#FCxz*b7#u`?rJoX)70$(>ijr`OqkJOko{Vg= zfRL0}RD*I7T51pjE8fG{Op7>1PDzzO4w!RYA{tuU$SZY;+aVc?v^ppk?#^I!aW=d6va)5BY{GcC~7N)aOqR< zKwLJ5AVppeXgO`{08`Y{5-z044fId=Q@DahDkT4Pk6%3gLh@DNz=eK5e@OM7Xm4E> zoPitpm%5ut&${O1cPO-oz-|t5`s?Itf>r!r1opA+J}C2l1Gm7xb-x~cS_0niJNa98 zM;QQA0|Wd=&%B~gK}{n)IMslo4Dnv+3pU$(3H1+HYe=L9*&k!g)0)?9 z%*AlHS@B)t*?maDE(;?9nE+FbryDxXf@17qxafpfu=Zz=wVqb1b*m(uUy)QqlP*fK!}<#|4UlAjk?L-e1cG1MZB z-+nqj!(ycI>yQ5&lLDD_Z;m49&oBa?@?<$phL_PXK}RGjvPKo2BT`EX_=eWhs)0B< z`~+y9Lv|=|8n!X00zW3zGy!-}I4EfL_gH&6mh?^LXVW!>sqn@h__d zRNmBkD8deyACvqpT~aj3(pLnMicFfGto{f~Xs+^5bojAY4=y=GerGMmpR#*!`S}=| zzqfAu{Rn=?dPuBzh)WP^UtI^q;W$qqd6%udw?#DsdF=^24gC_}0kYzL9bWx%@n&Pi z6_@#nBb{XvXb3ff3YJhRg&>VZP3RSrE0l|N4qnf-s!wk&$DIS#t*xC8MMpxDJ|v{H zG{M?qB4EWOjvzH!K6u9n1%4NHS}9$L_Fj4)9H(_8M#EV99ffh;bXP zr6J@$!!{C26G>Ge&cTb+n3oSGwG?dr0j%Dw!R8Hg400|uK-JNK@hu75V|3P z6m!lFW?G&I35IUSzmQQU;Q zALA~B$(Nphui!NZnfet+#D^wFM94Vo@@<3+yWlPX=BL46dY%m3cwvjTvw$w`S15&S zNyS@i#F3D)u_JoQ?U2ksZFNu{K*cQLngC!|-aSHDK4PKb%K=paZ(V`HVo}BDBp#I4 zIwTe$Th5qpIAk0s5`{$-IUI(Z*??4K5lmAd7+9}DPlL+~Wt!+&+^Eh&1ZAbjkd4UL z9hBved~B9LPH2ZpHxTTVt`>0MIFp8Cs=>{B)$|2$pkO4r6D)%M5El}cE@jB?mY{Px zZX_TuKIs$)F73DI7q2tHAu!Q5zCdI8=dG}1;T)o(f4o9=F%A(h#?c~drGD~C4+t29 zWh5#pEJ7pd7^k9Gd~u`l@`|u*khDN#Hn%`#N=hJha}s)k9(zXWjFRWA6VMfgU|P!z zR3$AXXPDY(1wk!|NnTv&lxoTGm~3X-9hHmyX2s(eQ9h)Brf~-gQ!PVN)#4bGi*XQ; zFg6r{VRFqe#w5K(V|QaFKa{pOjxpPjc;e28X0ruCLsSP&_6L5`8yoZnY_a&bvf^-p zl%h8AWi$xdMOXH5jH*D@bCUyTx^TjpE+}t?EZ)x4nf5D6r3J}q z*wixnGQqSq=w|m4Q^e?1RGZk}Zh%F1F%u74+zoD_IxzIB#8}N`o-RO|#KqGOkUI(C zes_@3S6(Z=7QHEp8!Pv$9+r@KDvG5;`FWaaK+CzyuV9DHQRRsUicUi7(La)ORX~U7 z8kI}@%zEQ-I2wVv=i;OM>z2o0)D(z??KUW!WK{VQKF)Mg1?uOJOh^d`&y}A!F$sYg zwV1O0Ek_ za`0y{ldu?tLH797QMAXGZP62BUtCbz?!73QFczH9cq7z!I7@5a?0)0Z_LW(ZzAr5Szic`UM zkRiyvf>l6nYIshycN|JP%3#Q`b?+Gll#H!F{_E#Z(VZ%-Nkb)^7?IJvJ{D7&e<6l! zVL$~7=KC>)Ge~MG1Uq}ySt>>t6lIx-t+jq>3Th4k)?LBNA;2gEDFbtIDZyQY7CGHi zgoptXd;mS|0IGqu`g&iqG5u|o!eP#{AAiu!&h{(0R17bg*!>O+Fo@)_&DCy&#;|9r zv@=r9x^@VkebzMtMl0*uFT9dcb_vtO81R+oHA1U8yRa(ejC_m1>ZIy&=-_J?yM@OwvmwqtxRZm4SWOZ{@b zip;F6+Y#DR;MG!3%MTv~IY}Q~cB0>%Tjp?@hLwy)o_7>Bv!a@^AMB(UCGZD}4N2#x z*(XfK))jpS7Jjqj{$SCuO7-`PmEDe3JMlj}WE4DOpo%(Bk|r}#@tzt)tFMjLeIFf zukdqQpxJT>miQca14E`=thQD@hge-WQpXdVBDnF~)UF8@sf+O=!-*|?5iMr*v^xuG zvX-$H2r4jb+_lQxNKP(Jwv{Vp1*n$@t>p0Bu&0(WW5ogE#Ju1+<_d-qwVEA|%d91b zFIO^|NSbQEHj}vFse1aY^74&Uh3wl)jVc==jC)o_cS*$go8q zw#bXbd=lD^uFy!L-Llb`*VT|3J@D*?R5;DvJZiHWvU29E(GkyX+@1Lsu4j|QI9*~x zL(c8oi02Vo+Wqn9Qn1UVD3%k;rQmQ?+Tb<*u$g_~q(7e3GApd*Q$?hx42C-0L0}X5$LMmbIa;Ud5gf3mFCQ zhlhq~BfidA$1G$&ya}+1)pw0fAl>;anactT1%C!uDy@hp3oI%w678`3fY@r6*QE!u zQ5T4>TCalcqIARJEZ)w}bhTfhbaGqM8_Q~~3xR6-z4YuyW+reKWAnp8wjn9wtjk0P zFXZL}8=O+QhKNPa)OWs82srlwkla#-hX8Z}4`Wi1MC_Eu3-;u!P~${SThu6>yLmwk z1IQR=8%JjDM`Tmyr2k*xkki#A+=bBai(z~=V|tNjNX+9NreaFB9h+bBKNR({W>0M z)PP(EibUi(unqc{=|m^OP*G8~L4_TP(>n-)1f+^ob+dE4=d+_>&D)t$)CN#V_0@Im zFkWP&<5bj5$EhxXX3S*Jc&baVxw>msyrJ<2huJ_yw}gyNA*%ZF9}3DmG+gAYcP+al zC{);57AJ-o2rU8Xtu&Rk3Q;l`LZix7(;_Hf8Lt^NtfHoZdc&%YG>w>NsL{8oduVmq zS9JxgLNs7ay{@jHtwjClG_&doFlLQVJ<^P4$kQ zBrN(m6>NuU(jd#js!)+im8I>XPgbCq$oaKK?Xm*HOf}oK6+L3XY(}}ap(AD7Ln|yM zGt0{jeR8a_bX!5rZX@lWv6crmG{H&1XV*K2N5!+JozELA1Mc$w^=_sFFJYzTv+m)L zLAap#5G)8nFF=&~4xar@DG~yrHCtgrm7SdsFKE(x%Y&p-hFab+R1fKeILE-K%>xVA zj&n0zIXD*KKvxN^5JAuuHY!Sz#WvO#_UaEf!LdJ_QSb zMrH}npe)LE6*rSbmWbz9V)(qaUJ_r_l-w2^ZMMcmgas|*IVY{ViW7u3^UCXnWG0MF zBrkujl1YOzE}Wybqj6Q-CT=@;c@T{nNHAU%1IBpxTWRowJ{R1SXtsa)gM)!N)CqEW zT`I(uQJlpTtfSCz^V;OggLqJ#HYOXyiDR}?Cv&1E*O)a9B2BcR^7O98gmRly-7j+vsdAX9|wUNcyif2h}aSOgBaZAVbNoleK zj|F4izT=@{dj&rk90>#Cs~hZ8)i_j$huv*`!gpB}t8I#q8YcKTa7S-+X&6A*Ie2j`RJ z{@&ZWncGAp`%c7aA;=@1Tz&od?umKgW!fKkAYP~BI#yGH@42= z?d(Wb`xQzDw>2$t%youv(yHHp%W_y|*tR|}KL%t*>1G_gdn)r$4Gtfjg2Q5G>YLjr zoEEx=M(%*2b#&<%7{-+%aoBmB@4?rd*1p78e#@=w(DtHRjNv1y!jm-#H*$ zBW%$_-e-kFVWO9Og2(if*pG^HjEbJ}4xP__UgqW%9)2^aC=##KW8Ue~Mkg;pREtNb zP03DP1xpcID~gnsh|T61hBnC;W1Ay`Kv-Q{gb%^A8;yC@eUFkhgJdy>nnTzo8T8OH zU&v%!HpA_Y%vD3Pg7QFUKCFR8atjYrLG@i|6jYE0a2$8+GUraNWJK~Xx#t0M5)h}c zTQZX`N?Rrm*lpc2xgJjtDx%tOvfto>9v6uBE?uP^z{iypj1#03wT@5AO3*^$g5xG} zxry3{9CfG*E4!%fA>ry`o0jrEF&qpdt>qIwrp3gLQk-j)w3v7By!Pa>(Q#bMiR9y2 z&O2qyw4M{8r>F|OlVFEx^gBLNl_2T#`f#0|`0T?~^LD28ly_7NKqci?*O$a>VUbey z``t9*>I`DWMg|?YI)j<(v}V;B6kBkB4U}*jn5Y#rqS<_6*oT(74hj)Dt%15~2vbh>MGL)sltbD_{xh>mmLSBr`k@r2DF#DQ!yKy}=&=Cfyi_t96& zHG`-aYEGMKwL)i`G(s|mPWZq<8esv9RvMwJ6G6-E>wIrWJh^a?@j1z95_7S=YRrWT zMAFn`PuAw{2|j-dVPT%U=zpfwie&idrR7@GS>RIavg@+*{Lg{Prbu=T+IG=$O?ej> z^l}QM+)CzK>K7MDDD-j?*pAbrbC&Cspdy1RYuQEHtPs(VvrdhAW`%^7Y7VM@ePO|4 zMj5F=V`SVaD+j~l3}+SJ@I5vus*w6k2p#L8V` zEY~8>XcaL%dWq@aV$7cI5e^TNQx4BFAA*G>Xog}IfeA`+2@o3Tp8-{NYC?RTNlPr( zT&4`Nybq`zoC`sPA<>zi^t0{bW)g2$oWUWkl2|DMuLa_($R!p_SYOb(cbK^Df#rG; zt4#@8!Q!N_@PuF%LBTm-8u<(1FZ6~|kV065*&3w~5U7mRobniMN;20Q~R~?|Hs;>RFvg*nZ0nGgNvFZvjCJ_vqSh)sU%fvGA zM>$buicYFP9R<|j5{PHgzN)KD|=y(GbO!uiibwuE%Va3(oqQg%B@;QM1&m_;2bOWAo zp3aw_0Upo~w9nRMx>_e`{$1{~1+bTWwrW8?{Fr3x)iU!w(D4-^yK9`PZ>>XeKRR12 z^W|5z1ghLQ-~PZT>gf5Rf0K`da~Iew<}A^*^KcJ2=~3%3Pu-wAm*!uB|33C zp|fsmHdEVOC$^wx!y<{wDPHzzR3$iCc~p+pb4@Z)nZ4Yc2<2~Z_nAxudBM;(Pi1n1 zFP!YnBgi|8hC`jav&!bfFEE80qb?1^(ZDh~n@!J{E2u*dx*>v;%+e7RBpA9O1KSsB z^;)yjuwoRz*r;0;GOKog7*Ln8^40b0{n_YLOZ)81P(IIB?$p`p*l<%XrP+V zQS4x(Xi0?tO`F%VumSydC`AWI&4+B3v~ZfQ)4|MoNM@t9Iw(JDW}Ab}Yzw!PVZ3}~s!88|*ht__PlBR-0K}T~d zs3xt(V>T;@jL9aq-BG#dZ&p5ziOYvH&^GR1Vd|y6k&l9UaSV#H_GUJm$eX^1WMQJs zF~+*P976%3wAFEp+Sa{}%drHhA*uv7y96%76?|WGc3clED-SnsSJWuJ^thm5#6`wU z+j8@>k*wfI$5nPe-9o|D!8Q%#buu^zMjFW%Y)nIm{kJ%mC}}9Kpm}OtW~aZn1{2A~ zHJDe5m}xXOQcY3KdBuN++VeLyQ-dJN^m>&=(W%d7Wp%G-DouSS#6VP1Tykd@)5Sz; zy&tsQs;on383$>#DeDkkuCtoeW-zS4fi+ODzOhg%HAOvK^>tMgRBZlo1;l?vpjIs0?r zytC6-+-x-JLssZ{*f5u&{7qG^I+}%($!wM;SvLF#%^>;!rdk8Cj;N^+nij&+tAwDb zH6H7Vq`T7T0uT~HNSXVFV}%S6<+@4i0NE_SX3$5=G54&YVthGmH`WrBt#aka6uRL9 z7rAl;I9j=K-7i+NG`k?-_K~5-#DsZyQH2q>_x39Ho80MbiOpsCVkbx?yP2LP|W-5L( z?NrY2FfvW-3=b2*Cs(F<>P8BZ&G56o8N|D3AL8>dSR8;Muu8!I5Nham##A<2Lcp6| ze=zrwOc`9+q_3V@3lVyu(3c;vv)$ijrfN9cz@e>@R^cq&I~pqbjs@q{7X$AV7Vdh1 zxnHnqQ^8iNI2kM^z&p37$P}ZX07J!~7zh}E;MyG;5Xj^){&Ld%i^U2^>Afg0Uh+WD zI3{r+@q9U(Pm}EBo;0cE$AZ$B%mCrTTD@4wAgSi_`n66}92c&7f4P@^8qhNa6@#L9 zY*%Tn1WSEx4>VgZJpkUom}wU)y<$mp}P83`C;#4uqr`=gl zlUB@Z20-6U?jxTYxWj&Q+e9NSw2R4k`($H#U7&!?ZLD_<@5f?Lr?B}Bbibpp zpAQuBii_ZVlZzlw@OOC~0tH)eWR&4wnl1(@>Pq48(&qK-h*JL@N(Ye_4$Lnh9{jc7 zx8tWI<+-7=(U^7F)_D9}i&?Up(b&$A}47at6c&SnYy2TN1rB z7#O38V6YP(AMAv z!IBnZFg;`ltdib=R3Q5WBWyi(^bvJ89GlYC2ISJbS(Ug$kB?@cJDh;Ql!e%hi<=G# z%EBEK7vrvhVB99c!9psNMFl>Ix?xd77ZY+2MsqcDVSrxc> zyP|&ZVC)F`LR?T>x|FV}jo?9hWmRd@(-{C}+ zm(igdgNhCT_|K=s_~&>S3)+jG=T{|YP=GQf>H(-+CpBxt5ayo4S)F->U6Drw)RJ9j zB9$0j!0oP{z<(hHNAwGPwjRX^V0y$OZ>R{i!U7XCoq~?n7x+rs&k#tlRp)mOAY&vD z>;`9TRQ)#ORCKFf#oP(nZL&}Y;`vyo7JvZZ`?1&%GaLvN;;}lOon7|0)I)%?e`$-fa`T+99w_ z%9cwA9i(hAaI{jkI#m{C*>*K%P9?|%i)J~#B!OD>Nhf`B0z{$M*48D6b;_5r zUlS}ZaLTA=wgnA%p9n4`v@u6bFIYu_yiX)&TRqxEo6)>3i_aUEs|du(^85vsCmh@l z)pPoShF;F_1H5)+_yviLYQA5Hz#C=%g@_2r1*Fk$eOt_CnSmirf>oZNH-zlApxRl3 zLE)j`vjP=Un>HI19u?1)c1B@P$n5fe^*hx4~rv`5IR5dI}Wn(;SSoujcvop%vy|9SN0j&~L;Yivi z1FPs`7P(g6CZI0}$Q7}p>7?>*0F$5Hf}W zjpQJ+wQzN}n%P=6CNn4a>7e;}9w4J+Uf@KxaxSjoqLPwg#Sk1W?@GlOBH)ZIdk8vL z@y)hKh$QE58<-}oA+)uu8U(IFzivD&8Pe##`nvoInm$B)EE??vhYnlc;sh}}rZr&I z1S#Vs5Jh5`pog9_f+iC~QB*UQy=`ta=p;w120NpS{VGlpH|9dyX>=vq@PV2AL#=B! zXek*%8;L0$Go|2j5w}b=R#1?TGd}Gj?A)Gcwu6EsItSdq5NZ!2JxfUJ@W#1c!4e7* zA&W+Q;o-v;xj02kbG8SqhLR^hwVNKvb)1T26eQKqtYt(ik14{PXU3JFdJKFgrw6Ki zV`%#(m@%EcF-JmXLeagYP%@$iMvOSL9!9N8jNvc}C&H2;WjIXbz*enGjNw?j&Qo3B zBOG^n=n_MDSd=&B3xOpCa8sNWi*LV6jM;>C*d-?9iLgmIaEX_LlmiBiR?30Bj5W&} z@G`E4;D1U~tKffoRN*vW9t}TSM-WCH$Db3qLCQXyl}}f<>om!-WEQU{^E6Ht$?d3e zpy3UUVw+VLTWvq4jD&fY7*nY!o(XM^-a6`1Y&hGPw?}zt_|}nUHmzQl7$-At*LCGy z=m}RF7wCMQ*ug8ukZX2{>5$&4QR88d+bB*v4A2d_#B|3NX0hO55ZWsG+XV{UcZo4& z91F-5_VZwuc$4H7kXKv;+A-Z7v&=59L!eX_92w=2q;kYI-D2p*T-m&y9WUy?L+KDv z?%80re1(HQt*$K=qcQ8Ut?~Fd6|>_vgPxs{k`HEZDCPnR7KR}fQ`b7kat4I6E-_}j zHXJfW6G_1i5}aYFd&r|N3zTAbo#C_f_{GgAY+l@Si77lsx^kU+n9aS_(wI!xJ9@F2 z29UirF3t+T{k6AUhBOAm+S@dhTFm0YNOL6HpgIk$nZr}OO^G2%+@Cv zj!kK619EBJtV-NblaFSgJDh;Qltq0T1qEf{4hnZ&V$2whs{@f3Ok}ykQ+EeqC>WHs zA?~o+x({(Qj35m}0nY`r&DOv`>bo9TRt0X}uBab87(0T#5Em3TMazxBMqH!4va0M% zIs<@9_-*>c7xnq*M*77ASWMrDjZZj7DCrwtQ2FW-W2%j~J`#z=^^q?+nCT}s(n?Wj z`9gh%67w=FQ)(chs8Un*I6go0+9jsu^-MwOgIKDeEJ^Q^RKH7%{wg9}Vvbtx64MEw zjEVHR#B>5G*GbJ9vC^EOV>k_Tr$+>ID%#YS8Box&A;2%^+-eyKorBNTqc{Ofb9)5N zTR9tjfv=>=LmctjFHT`#84FuJKNvS3t=nf5n1{K?ewdd>7>>rrfn@CK&aRy zrgaDv;<4n~fUQGViMvwl64N@EyW*=lrlJr><)KRql@j7Hk%1qr5H&0zOm4vV?8hHo zVJ1(V7=lezZNQ*6>7-&nx$P3u4uNe_wp>E!AZ3ezqm{DdjbT)*Dzj{_&_J%uml6&@ zZRCQZE-@}ugIa9>7dd9$CfWjpVq066B;^fUm8B$m*(|!mxMUR=NUW%T=UFWqDe5i3tsQIm1u4OH3%(sOI~5lk*mgWR(3EA|fVTVgg|x zv&_H{C&4OD&>KQ_TTr_$F)mrm1P=wDRWDou70;G-MqyCQwafq2iy0BTWM#IYX7C(! zJcu1!+=l>fj=_%A4S_As*30s1{IE=jvFg@`DMW*5c8PH*uvE5jQs8kPU{yI$hX_n> z0!Nvs98iNJb)Oih=rI<#R$sGL;Y>XU1RQpWak(zlCV=gb#VKH?>OQHf!r%pafTCo@ zFhQEn=J|ZJoGf16Ocq%pp0J4V%i4$QN@wdq5M=A&diM}Ah5{*1C&Vg>kt+6AQkJQL z`QUs^W==SIv66X#6WvN|fr@9rS(g}>B2EKv#+G9AP>o3!BF(vqXHMgq;tc`v3WwXk zG-+)j^lGDvO-MNVC|D{X;^V7JjLRjiIz4QCixb4`nAT{oCXbla3!+H0XFPO?5wxdh zD5+*Fd)wV;&`FM14R%Hu`&FDIZp?+Y)96aJ;R7@Khq_bTprvF4ZRD|a%#?!9McguR zT_AXe0@TTjPx}Zvw1JGNP5o6yeUZpnCLU9`~aiU1BcN`Eoj6PZn>I zd@^5Tz*0J0VvdE(1nd&?WtHX2$!$^}Ukx^h!|}GYi?JR?;b_kuf_>jJnnT@1RxS2nL_ z=ZyOAP&!S-<_)%TUpN6&Xy4*wG-h44H6A~(Vs?B@#E~mf^1%wLy&Oy7Fv-P)vUm)! zs=C&RmNOtM+r`-O8n2Eil7gKmIKxu+v`1eSD4ppz!)NO`jGIve0bn0g%REQAa-Dma z&Arvqm`vC^da;@Ykay1xgqRc=D=r)^L&}(tY9yMyHY!GE4ARy3T!?Sc7`{l)2RG3m z9-v|xMeKpXxj{v(`2xymyBK?Y!!?dbs#4?lq5|ytV4?U8z7(abc+#gDeCa|o&@chS zbt68&ha}>&2_u?h;}kUWnk!l}2Gc_{xKZ2OP|`b)m}5Vq!q!8jdyDP*l(IHk8<0!$ zW>w;jntU_^-QffbrY!3FDJUolcTm{2i?L-mEP#Pu(4eppsNM zFwD*bX&?%CHx@h(H%G1)YUDLH33ENLtP0$`T~R-HFm?oeAucFxik2G_vLYPEP|-G; zjAJ?jfJ^vo`otIY`RGRa#RFJO--sPhI7cYy8(&blZ5Ly&jkrD%iN*DiFFKg%CpXec zQEB-?eTNeBGOQq?s8Unk0-X447qcI2zMd&4eGrw@5Gl@Yvv5cS`{R~6#B>ZO;~SL@ zF&%@-)ljn%3}Nm$oCfOBBLZs0RA^>YeTe}D#To+qa=xvWUC=rBY(0t-z?8K|;JlTx z(Ux-5D;$d5Yr)q3L#h>&vGTy zYHNp>E(y6Kq^e^o3ZYZ(JH!-HLOdBVIaMbc1d#eP2h2%_7(Wc5Vn8|V5YrNYt+KSp z?73k97g<^bI9gd+ovJgl1h3FQ_K_RL z21RzPX?KY6LuVI&_le+A4jXgS^nz6+$ooWcw$)SW5aWl-RisH}c^Y+y2^V@fsZXs# zOnBI+rucc2^A?O`l<*fKBI+Gtf@2`FWWW$7!74S-8$xzlQ0+v)pzu)eS%HeFO&bgf zkBVnYJBctTWGp(w_z_-4D}<@N%WItwAtQG)O`AId~sFit(p#oYZsKSx7PX<DQ7-HVAGZsZr0#WTOlD3vda;suffFqTZF{pdR6Gk(9;_IG!-I%Q#TX*s zj4gWzx{56lBFQ=22Bt}C2D7aNdp&R4KhLd3^yhZsLrjOz5T^({^ivtwGLy_z6p zRxgMm(VlVNAx6}mVjO~Ml5)oihtNrmSPgbY8T(b7ByP+F1J8-;ftme7-6?L~u4Dvl zq^@<$l!DJi+%j=pP+CDjLeBWKkFaxlVw+DUK%h_z6p_P}4{t+C~MK_QZzjJTtBY)ngC~eR%ZZIQpR} z?IJoj`;tt*UQV*?VU^ARd7bt!Ct~6RGz3`}uNlmeo5|fG|Cme`w@tlboQ=GtQH4&lEbhk47XwQS;DWH_<}h|s*~_&+ma9Vh z7pJpr)Z7E7W3gHm?eo|q?eT_o$MoaK*5s?K3Oius7;%-xF9A@R#m4RI`qDkDMiJm{ z#ikL1sP=p5p2BAF-2sr;DxBLIev6hPHf>&P`NaZkh21!a*4kk0E~#DF;A_WbcL}>` zD0Y`H3vP(=P*FJ^n(h>&2quN7DVx``148|GC>;YrqXoMqE1cWy?z7@xC}uOZG8jK# zV)ou~57keJR8Taa)LP|+D)AadEN#g<=q zA!LzArB3mJe=AK|1ZgUsxT(fJT1$Z%Yr!K`nI-~RCsyy**3Jguh8ANmO{1Bp$#ytO zngz0AEay^CB?_%l>=q;$i%n)bqj8bltSlT6kq>2{9qeIX>Y%=1fr2`41cGHV7CR2( z0$(Hp6HSgV)ZIlG3IL_8gd>!;?j>A|A*^~)guAiA4dlA(fn{Ou=Ix3az_k@4XasQ) zanrKgTx^8mS?Z$7?xLH~xftK3F}x6+4{fADT*JgPir7SibAggZ@dA?5b}P2}hHD&= zOkCr5p@5kNawC-#)sh#ycc>}%V=}b`qDZsF%HeabEmmq?&s325mW6?+q-e0Zz4>Ax z{Z&rd>95i$l#F8(nyYjQC)YL2YOeDs=Rg`LL|@RWl^=1?Q^f~=C<8C2r)sJFZVAs8 zpjZ!qsbgP|d8_%NFUytGbLVu}s>r*Aj`5FK6BVkLo3eSj)1YD^(3TD=K17bv;t)fg zD121n%VlCZ15Y8esYCNT+?gfY(c?ATK2G@f{P7GJf%betxMb zo5gb)le27Mtb=rS*D}QiE2!8PZu_NBiR+uXR=G=L>fAu+B6q0(M=N)!yTxgi_7oJn zwYft=p*I_GV4gAMheT>g({9?N_z++g@E3d3y0jrbv{tdKWS^LBgA^YWb^NG&CI zF;7eQ93p|;8)CDqn@Up@ADpcsJ1XnZq$5hGpv$RlO6^cWLxt@Fb|t>~k>?itW0VFL z92Ux5Py*u{vlO}D$ZwS}=LZ|R{iH$j6Ca#qf`o#{2~<`QSnP@r`CmoiD{x; zI2hEW-RVZA6$i!!@m8A7vS)weW3Y2=LtvE-w;{yM&rGRoc7%W{m2M|KB$P6kvWZ>n z3^sG}x~C^UI%d1Bu%WDyQYpO36Vs~bD;6A9UvIS+(A%~*@v#uqNY7TGNPKq2-RaUR zxB@H_mYE1rdp6JKtL0?z(oJI%7W$-g(%n5ZwjOnN3?AbnH!V$yvu`Qg5(R5gL( zMib3eE=CNmiL>7CV!l?(`+W&dZ@Dh`4oh~maM!^;d4jHEnOnlfWsuRN&v^X`)QfY_kYBH0V zvmkgxi^W6h5XsulZ__yAQylXsCtNTXQ6y{}^Xw6yRvNQNdW^K5O@+zJd_#*Cn1M$0@&!2_2K zzW$O-))&|RNv8R)@ZshrOY*^2_&8c-`D8gwuD-7mc6pqq^X2D{Nw&I6r{&d)+3Xq| zD(}IE!)|=LN|X8L7;=`RqrbgdEEobm>U+_)32nE~l#* zph&L`zfme(J*naitDQ_Qqe6 z+g19V!7g9@Fu$GW^*_DNKTI;1$@J?Pl&7Ce%iD?}Kdt}(_UNZ2w0)T`li9x}i@OAW z8o`xsgRfU#l3!MfqFB`%|9;}|Nb87B{W)sKYp@+3_AY`#0%8)fkB`3xUe4EUEV zj~x9of#t@nlx>D&dF0I!|Zwo0~WvU{V*XjL%E>49yunKbx)Yt{2H* zHou1}|Gfhg(&Toqpx+n8-$}l@8Nfet{AWS_Sqx&3!})49DE`o|H}vbx;AXL!e;0#vvV@z+zf*GfGq_2U1fWHE2@ui0lj~KQ!|2Jkc|IWj#6$e}ImweH z%y;%Z%K`Y}&vlke(&?AMe=~e4{{6$jD{sXY^Kaxq{*^q*zmiAs$s1un{9KNQU&`U|3m=U=Lta-tRDR<_ zm5;$l$WatN`sp^govyzR;Lq*qKEWx+ukdGC{003-zrtU<`F2fiqJNg`>uN#RQm{%{=)hr`SJ`7L?Tmz3OzBR1SQos*&9M!YFoFY$pB z_`JSOzt+Bcdij2eH{%WL<{hucpYf66^~d-zuZNty9e&3r^3_*F1WkNgO$jkB#1F`k zH_%iiO9nSLi@WU00PelMgGHC*_xSf_4W>~Jf3xXi3740}_l*6e*YDYVaeP0C7xOHS zbFh~`uj3WnVce9TU=CAQ%MbA+{S5z4Ca@Ym$JyjQq2KO{q3*Nd)#aG?Y|tB6pVI;U zn*o4#@Hxgm^h<`TcRC=K@0RpV7-a_cJf!m+5H0?|PwN#tlO@Sl{Fi>q6X26Hd4SE$ zU<#`Yi8i=NKwNU+%2Knv!W)3nD{=#UVumC!{9TdD-(fl9*N5Wr_u?C><;sZ)5(D~#K6;k*OR`&yZdziz1 zj^2P*rUN3hh=~BEz>Hc1H}nq}KEyy+6n~1pVEB;Bu&2Zis21T5QIGf))FSyx|Dry` ztEdmjW%|9;i}+iEwtILWPg1pb0yj2lxrfX5`EVE~l;_l(ilU)a+} zhwqd0I!RaA*uRK7q^t2WDJ|B-$wX;Geh+r+z)M zsVVkKLuuqaVPvxRs(Yj$b&X>sB73oqlLs=w=yo`~0#QV^VeI0|yJca^<1Xpd;0w56 zV~R|Scuc@`3fq&l@*w%vL9#EfM?XUI6vH^kvDrRhX;7 zu{Zz&As>wKe#!=)@|)8!aj%_4GRdR(h`MWrL)e?GNEhnrGmHf{t|JRxt=@va6P%_m z?@wR6cuOpg)$$d;j_aWETLISr9Na%IpC1u-8GFHScmk*DV5H{5^YMOMGADd2;Vo_e z`!2srap!wKf$b~BdH-rveIdLkt_*n<4^P?C@G}sDEdr4)SE~yAe34gvC<)H*s6c^( z?4N+Q^K7;LjyoQH=T$nH=h+Cbh278DKK&p71;7pm`4`Y14u^^AhbcxlJ%b(k^ zY<~#HDx#E#;!{3Xz&p6-BHYHGiFQ20R#~*iiGUK5zZkykAXdbPg&!mrDm+`vCLtU^ z*C3$za6t9pB}@>aLJz1vM35xDm|suVYw)iSCvP&mg;i3$2v>;z1^&Wzq*w*&wP{XY z9G(6^i^>pjK}SDjFB-kQC)HZYKbKsL|F%lMCMmEC`48~Trj9xs=gAr;16T0=9-B8d zx!~KTi=|vz!-M}9?-5}H_}sw%zpTLMxm(WvdzYY`ltPIakXVuDnk;tEWzYW3qkPy6 zM9FRWfhie^(X$_ac!mF!PbiB?Sfw$^5xzswBS2IBEL^jx8C1**$Au4|oJvLB0cg;Q zLHt#AWO?=q{|i%7X^8yz5&!Wojwmcpd7(6M1Zk1|B-lcyloINS+O*vb3*St7!s~@Z zgz?Xyo=|$nvP>VwAle&+`Ov87QeQEvO0rG9Ersu2!v7g46sS2xQn^qI{6(6=Tqv|6 zp$8apaV8WJjKR|dCbl38OR@>q9;`yJRp{KH> z2Xjn3E&+b|9(>tg|AFr~#%(ea=Z~M$rOoWq;_Je8E#-ODHhZLY7$sr$&v-6(Zs7I8W8yeGAmN}wEj-*i4=|qAl(E`KOPg-=(#Mc zg#;up?190A!ae&51WhFnytJU$PnP-Un#NNKTBqNftcm*`_zNBt?qvgy?eqQk7+wK! zob1Pi_`!4711m|mr^F5}s3PzRlcmzJG8Y>AP_wYyn+azRz4DntQD?MhWUMNO$K=Qb zu?hv_eee=v1@oGtv$xxi&M+E+wzq(JhFoEY?WBQmMZE;X@CjmH*s?XP4|=in+|HU% zx&b&GXMT8egIT50jAJNIWybrl-!?+}sZ6xgB7@aJdGs?aVf|F5npINx7z?3jT%SdI zJU|U~SS7jxL(@ncT_ptLV7ngKzWC%L(_{ z@Fz$2NfO}=2{~m;{)tTfECHPcQR?yH9;-*hX#xpx3B=ns9+h|q$s}=ybwI=$rPx@I zqqpGD;+*jJ^C!j#Yhv86gR<%gsqAg`zyh*syKZwNFl70&a7~5~*+e^9nupTz0YZt& zEzdk4F|QHpzvcxZ*GVo_47%*wKc>?c`~IS(g){UgCM!0|?mZD@8AY(`2Y<~13Q44( zH-&G5;%b?u_QY7CN*Xwleqt1u-d|JqK(T##B5UF#h2;QSA;7)(^z=3lM_7jrYW<8a z1$XFE**>yeH0&V3t38NclQcZK2;}61J=_@=d1s9|3TKhC&2Eu!R))C287JF5xZhWc zJ9o0Tu5mHL-g`@S1|$n!z>^mc#w;$Oz=4iLpk1U2o@1^cp~VT(!QCqnQhep>^m8_d zNsYt=K2&|UG)+X$?uR}lKRw$MVpkeZ16-hk1S&ImAVKrp#rSzVeD~oNPoOX>c|Tgu zlPOfY$r5^Ok3kDDWBFMzhwZgf|76!v##IzJPKP zKqp!%q)4ic%wC4_fV_+pLNHcXteS!O3yR7ch23a`j0}VsLEa!7f4UU81yn8;A<+s1 z!ZO(PLj<7=MK1k}mi~j{LQv;TNT=u5afM-hnOHDS8l^O{qtQHoEKMObUXaeXCwOyr zd;1-RuACOWq-{vbQY{4o)QB-#c!1Bb0t5zbfl);2ym%fg;)97R{pAv>8Nocnw2Fxh z%L6`dmQbSs3h#kD_yfs{byi|jQ*j1L%1+kMs4%R6InPHQZlhz6Kcr9tEsHtNUq;8E z@Z-;SP#PNt$6=?|!-DzCu)0dWpG}}-+#pXO_7FeCgJtq9kD;dJG+AR5VhnWvvuyG? z!J0Gi;6E7%MyReq7;Tc00*F|F2JVTWx>pS4Pp+XTAcR*>XmI0v2`+#5wuXWyNzC4b z1yHbVaXk1kfkJCZ3iY>OWzFD-sDugk_gI65U3d;9ea|L$pTD3Rx%`ZiAl(*4XA>w@ zvdnR0xKsGHdG7(d=c*i?zL$T;`$Y&&J|?7+GTc{u+IZvhAtM~zRDRyLE!u;kveU0n zKV_N_n~4>1iBAx8m;&I1ji*k2rBeZ~u0VG5k!%k)uERJ<{x3Qw!|MV6vhnWcP@A~8 z?;h(E)6dm$q7!(<8J$c940)}5t@_yhA=JP|gwL?nIN_Stlxbi`yB80deyzS|GR9Cj zc%Xv*@&O7RSFcSrugxH!2xYfCt+Pqp)#!lGl+|-0a}HZ@_8njH9*dLI^XJB|Rknm1 zq^AYm+IUuCs*PVIULqVI!zFW#G^ofn(hn8BsRCQi2GzU3mLlLtZ-#14JM!R?9 zfm6Z*)siwW;-y^C2ZeWG!^vYEQ%?c;b2(-Q)v)M5l#!+dkPQKa+rB_K;6(yTU9>Q0 z5evY?dN6qHCLwAZ7mSo@Hy0#Ex<}8UjM>>;3J0zrHsPNStJNB2pyn##NFF(UoqbOF%8Qq+gNq+AuuY?PRQSXsMnd#W>CMhLc1btvGK zj>QE%R~-sSj{7Y>6!J7nTid53(#yh`rC4`ZnkMKO7h+y4iVsyg34Wh6o z+HDP@kZ~1x+F5B6OBT1JoX)8a>$W5f8iQiQMDx7HE4#;hc8MLiJh4sHeC;v1ym;`>@2^r^53R@=t8yS#~DWIO6-E zpi`4A1xj;$qbH1ik4hUkpZ*!<8Nl2#srR&){|T4%3EIW1(|qWWmGudHUdluJrz$e~ zRo%zAzUXTuo4*K=oh{~&MB|(gy{hcv9DAX_&r`LadsyGcIUBHzB$oMMrwVe?o_Tp6 zD`1VP{8)`xNs7Qix@{Kw=^pkSHGhlBz7WK+^QJvF6&EZ@v30M#dFsFwVp_Nz_F zA7eC-K0<8?R++_9<)3P~3IhW1q%|H6sP~#zCPjX%2wYj-9%}tC`B~RNKul$JV$VpY z3ltf*C4C%1Oawq<)fnShrLV=r>#Nn<$uwW3-(TLJzIbtQ{U7M`^@?Bpd6Fg4FQDo$ zH~IkTP(Lr99bw&xWBTxLcmhS5ps)s3*V>PdSg8p3_%AG|jZqjGbPr1g!wl+dU`dW& zNY?t8TogaA)8sy;1wP2f#r$>-#XkNN?*VvV>?jhhMMvj%w@~!<;)Y(#An|=1pNz8A z0?XkHD!&p}*v32dAmyArLA+(vJ1WH;WC->~%XvPB!YF@0`5kHSI(YZb(gYx*(31O4 zvB_AvoGePHZwKN{2y+!6p{j%g%#v4@kgiMBCFEadg^2{`CyBGg3W;7jTNI4_y}BPO z1ggJD0J`A@4t@O%5*iJ+h!r#HZ#gCyz+~N0woH)1$msi5E1A2o{z--Vp>W(OREW7t zm!zaz#F-vGmP~)OsxBm$!L86>kA-qo33XSnP#qTPqA)AJmDM(A9M-JP!Rf(^qf>u% z4o-hdCu@@;2m4R8$N`%W8&iY6qi019LPlK51Zlg-LCA#hU*sTU?7bB^Fc+Jkbc8CC zq>yLLW`4M}axbs7x zCBO!Eov>gdIjmBSP78leLc2+O$#@TVK0Ri<2aL5&P=i)&gMe{iw%j;1>TL79ns;0Jcx`QGvi5Qls(%=EGIe z722*n&@tdU3J;h;huOjV+o}%Oyw*+00cxAtlpHX_0VxxHy#awbJR*-r>8aKmpsz8i zH(*ZP%6jg+*nne9d{-JU1DCA$#xeso?-ZN6Z%@)ES@xK6E#;z%S>zi(vh4AVA9zyu z#!sv_{pJq{s#pwRoTu~U=U0PYC*QA=;)k*x0{gK@6UU73lj0tlFHUb54iC3v zN8EAW<@@QJWuEW6HCMeAy2BUl^L=np%%^ciFdI$JA&WeUre7v$OgpKLrbEaxKN1hL z;0o=Vp#uK-_yEqahTmxM0!o69Nw&I6r%-r7jaHBa2rqfgUUIQae*T^()pxz#D_;i$ zmPignL@Y>_emN&nj{enNJb>@hE$Dm*sUoLCuY` zFUj<4GOPRbi2PRf3zRV!US1;xG9agK)75R`VE7{e8M=qmJe>R&yNX1l{+0aNC1g2~ zU%n>a2eag6a<|Cido2IKh***W)+6vIQj-y#X6s_ zmIN7?pXg-cs>JOAvlpu(I((m`P;q6Ijgu5gzpybkt`|UVT;HQSOJLlib!4#Y!||u( z1N<3P?;j2?uVM+NBLS!Zed?tQ)2jiCXL+e=|3uNDr_vUbOo!tF>KjwDh0uY?lEyZ4|f&ob!KrwpcAcmlS!NqTFwJi?C-{ z+SKx+GcJ*MeiUZRKOXspPg$&cq4`=fUkW2k}f z?!zq}o#7eMezcw^)8t{ECH#DeG#-zS^1JmS8NGY6##~i$-~>r3B? zwuby?d>Qm0oUU%yX_95hEM8CMscwiaAq|g-<8gADDVCZwCTwV1S-u_CmvD}SzuFR} zppw;CQ&+<7eV9e8pUiu7_~Q7`S)cmoc(k17^T}fVM{>5nx@MYryoXOVkC#n^mE52& z>02Ie(5Oox&#mY222Gk4@_2*B-&G#3z0|CzZzJp5ad-M~k*b<^F~lj|zT|TEuSNbf z38pQ56to0rw=sSAw6M?Kbs;t|;=G}X0i0aFy}#re>fcr=FgtGh*nh;t-CyHdFCFQF zo=BgmoWU>VI4*nmeqSe&Qeb;4{lvDAv3|OrdlDHc(54i75ADR^RoUwbs_kU}y8&*Ex1S-d2P*rMVpb#^+L z=h+j`+E9$uak_5M%q;S|2B!=sydT6T_jV)#A*bfs)l zmSCcjLf$uimJogd6U-v3|5wmZQAim?E*J=tYJUZJMT8+ajf5^w7vo^FiM`<*Za%Fa zlxIoNo2XdHkDsxhau#jaj@GA~MH~9eln2&fws!X;9D`1v^@DOxa%cZS-YU`Ie7tG! zg`6?#XS#z=mi2>nnJ0Vkw01OXBPVWZPFeH`DfqC5?mKK0x-CxgEE@f8KQSuVvG${Y zlS)jC#mu@IujScxd@&jHd3*s;t=vWH&6Df^Ud%Kt;kBG9%$7SO>9EI$y_2^geE7Cn zAGdnCC$$(gGGXo6sgeYH8ekHvKouTj#sklklVIt4RFYur$y!;ZK-S@qrWqrJFQ`uj z{mmL_#{Y~-&N0a<7M5*|W73kRae>q#KvG|wAz%q5S;s8v)o#Yq-h~VH)#BQr0AMS&5D9HJMk{9Kb^>h zOBj0RW+5!3>g{qacmG=CA*JXBEdg3i(G8v!Wr&w?hY``hHWeFIk@T&k=!QIzV(tsy zSc~G3`PB52RYS&G=X4S&pzg^D8SAGz+vSO8D=E4m^MKzJ-4LX>=M>$bCs*3QJ}rUn zx2hbg*$A)o3dI`lb3*WGmYDn-{F+Wkt=b%!_G z$T?2YH3LvLMb~VUN@#wIDY_lP+nl1S4;1F(9W|urn!e3ZiY~Pn4O4XWVMjugNg6zX zG_*do0#$g_aOtGg4V%?X(KRD$WtDcBqU#U=k14wPP?B|Am!fO>Dmg`$zNM0)tNm*I z4BGw3aR%*WI$uub>&fCxl27J~Ow+JDeySO?S%(@KwD#-PL1=Uc8ML8K zuiFgTu(1_+xwjh&j~TS~i`H(-R3_tnd=I&ok6{>j+c8<%&7ieM zwx=1iK_YIHfoG42xGutPa@${gpTP7=38iKkwEdc23E?L&!7T7P;0#)O2I^l1ttXsA z&Y<;ya@ZNPJ}`d58MJ{rT6GS=A6W)%@H0~$ScjTH>qArooD+dpxuWIS|50`jhvGVT3Z0sGH7i_sf6Zx&!7zg-f9M|4N#bQcPwSl+P}?B z25n(6YGu&cz>b6{lQe?OpcSdYlc0FunQD{U;yr2^w6-r_IFK;A!EY^{lPTunPe%_IE}1ok1LzDL3EOiKF!AkY~|n9%aaQ z>l_&BWzB|+_0yg0@({9>tl5xxz(dw-NFv;G%52axD{Wf2=aTytY>IdUjXC%}ZYGN? zc{M2YceSX=qs9G4!Fv~}r_9=P?xgc_y5_GxA%Y#;m7 zvY6>`lV5FFr+1mJUJwpA?bSWLLFc@>NB1cwyoT*5)j7X@YzeQS&rEsN9B9I;dpQwy zwyS%5`;zMV7v^T^2)#>kbwAPJXSlk@xd-X3?vZBuG#9z8cF-v$w%QF*37Yqv)fxb> zm6TR3ftiS?y?AS(dG* zv3h{sbq=dJh-BfG39Pp7!R%Ej)e}=!jbDm2*Z1#Fqr=N2&E{F2Ec2fySuz5KIKH_4 zPcqGi!;^86|CUU?j?NFxC(CG$UjHqftcSzl{pD2*H%G^K#~JYW^esS zlwBEa+;au-{lh`=>X-217ccmWA&hX6PHvMtNfE;8xNndMb=UXk_4kO<-mjDI*U5*~ zbh04mjB{u)`*}Eg{x)6RlHW$-C>|nYNA#{M_y$l9${SwZpT2lOpCh4B6pl~%%_+SI z(io{%Jbn(ZJNnmTahCvH5IpK(HcIFnLiy}dQW1aG>;MdxFfg0QJwB1*Bm$EAC+Dl> z*=qfLa=l3ST~{PdlagWxFB1sMZyF(*j3E%u9WUDlN;-ZSPWju(G+(9P$+S>rdBv_F z*Gkt5_Bfc|u1|{RBrJvp=g9-d7Qe~ABV$NU1ACmNNq(0u;~XA@2kHilq!}UN!jheUe@$=_;f5 z;Dgbje65h2HLK~edh2kgcXJ^|s;^<igo`Ty}iFA+%O!XsC`}<5~J}6%;ej9l(e|oF5o+tJGB+VosWt}B#g>n zZR&IXkAM6RumG9q80r(i=YM>8vA_Rf|469r+`947x2yYnaQLQ-+Hh7^Pw*1Bbl(aErkaeYHo%frP#3>UIqa zKTBrudNNN9H~@(8YCwi~DMTPMNQOhUL#A4;`P_C>c1WB7xQL8^S`+C}T~oN2U^R{2 zUEsQUM~R?AF*ue)@(}_F%kgA`RKROhE;I+2*t;$P7HPG0(J%?vXztXnH6mpv>F4PH z{^3@Ks4|!!CU%$fgCL2cijD#`vrR`8nr(k?m`x{Zw1s||EN6>kJYB7m=;-|J7Npe0 z4ZWCg1EKzb$rvrQJtB4y%KE#O55rrg6YKAoEryr(JMIyUv--Dyel7`F8Z@VG@0Qbi zzFNX!Rx{klje^ZVtOLoeft5k{yEKB>7*NgzOy(_yCb3-D-H_@&$iGbTc%7$2g&>jY zjCW>MpIoh|DMZ%pHQEyboP*+5G6pfkUkz4w`F6@56Fz_)4_HrZ7$CsD_+s1?Y~>ra z1e#euVr7|Q#fK}*EIlPH0Ai@e`ImI{5MNJbF;l=XY_JFv=xp{p7?P8P}SOQQFmnOH7AJ=+u1GzJh> zOaL-~sdAGH7r>%L%f*Hy8h*YlW}%9!&!No#MovND3-C7RTRLyMvUGev-O?tFEKK;P zGoet7U0t+R0)eg^XKO$ZFOg@nnJ)pLi^&@JXUA*6DcGXTUt_fsAH$)b&34_7-U0Fc z52rEgBJWpUlhH@R&Ck2>5lX5zSJTCGk);Q~bO&)94Nq=X>BA(QjbPt;vyO+^y5VQo zm))$%<_v}2n>E$X1z1MASFx%Gv%_9uS;uF8mt9%Ue*6JV-uU;exSzjA|4)usN%S4l z?J8uL5SkVc$2d@2_$42}DZfrqGB}L$F(Jk;eb;_T`?^O)_rqgQ&Wjhsqp&M{XP*-Q%G^mPV)S9;nhe|4d#m0!6^?0MFlHj>jS&;o|r# z9%K)bbz==AA*!&3%b+Mh3E@ld?<8fR(fAw8&3E{}z#9^u)ew%DvOqZE&Mo|uY)2IB zi&ux2&+qPui!aWk+t0vFw15L0_SpWO_!#?Ddc54lROSZPm}Fj_E#`1=bvVwGHM+9t zE{tt5*%1^ul#+INSow4h=Th*f8kO-QJ2==&)!D&(Z>3}@+n`dK&JFNzP#k`__vEi(PY%+xH{ylrtrBWcJDU;|V-oh5hXN?! z?wv%(;yF~UG~B++D36Hlmh*4_m`-2ppT0Oc{o&c)3|tPTltIFjf)tMd$bPA{)03?} zh%NNd*n2g+Mbr0SL*F_TA&~lF{4**IxJ&2QWn{DwbB+d_!xS9j6pbC;35RGHDJ>>g z0rfsg)&lIR$TF5z+WwH{HL2kXamWP3Y7>?u5XfXrz6)(lI>kfWHElg1h1G$F$=u>l zf0701mIpfJE?)Ma*v$PqkhC&Hkow;gA_0Qgk@ICloGbgCTBsz;y|;2tG$Zj zrSXUNQos>1IkFF$7)IK{HNMNS0ws4=eI5%+fQcol0G%)p-&ZdFiMTo+KXC4b9Exa$_SRJli}f6g1_pP#%^Z zt?~zr$KEUJsT#fl=w0WHs^BgR!zQxPOLZyobh$%<@Pf|?hQk6I7WG4n-%t;66IVo> zM7v=}aVjp!5A$gF;Tq!MwBT2IOA%sFb8aPp0OEiIbspW!(@Z8{oqufSvzo(7rBJpN zei6yWV3r=%9GC_39SNedkz+tcDiMPmKp63)?FjWe%Oyaq==kXwFfTggU-4!Z!pbBj ze=#S5Z(5v*;mKq+!>CI*E1+SK%J;u79-#Bq^#0QV@ML&PDtfae)^xvAcop>=31-^? z6fbK^NN1bY}zlQx+$!izz7a=K~2Up z2)%-wCOn4BpW{&XLJtrWpkvrQ@)Xf)hG9Aj1kJz2jS#GfMg|32rO zx|eFMF&yM5CWrVi%mr*wU{&NWPMkX)2(}~DftY^zaBvvMi~03*y^bgO>UKWG?E~3O zz*?E6$t|4pjuyk=RZKPC&YNE@R?E-A)NI)%kz?+C!7$l!FFEIs@8um1U>(v!YRCIy z9XHLV#rO@R!c@f32=VTB?Hya+Msj*KU}$EC}>*%IkqEOxaojkzCyB8i9?VsqOxw z;Wb(EbxwLog5_jS!-Gjitx#8rf!!IjSPCUT<;c;VL+TxhS`Bc>HiN{-yKG zwFVhNvevlst!BUPnwJcSS&{xgOqSb*bk#p(y-+{U>7J8nktca_E|K46vCI+;i>16- z-C|*>L&c7$(F08~Zaxxs_#3(f0Z|tnNLQr23}yy#@y-0T+}yM@%4N81UnT`i*}e?p znaW+h6nwc!52ek4f+Ly41T*)ku=@uFRz(LqV8q-Yyv`TldafPWLj46?Vv?RM|31UMJKovvy0j3xu*(I<^9Z7!-wQgsU%W$O zp-UWGixpE9LP;B%2LWcg*@d7NX-xfQ>XF!f7lD>?LO%jfqD4o7DQWADjrBY|DnZ=c zPYu|=!cGBahI%E6S-Kd%!z*YdYZNN_-^bvZ@IisP&~d*!;6O(KA^NYR3M8s7T+Og@ zE_&_5%IUj6N{9zy{c>FvO9cLyNQsY+NJ=;*fs~r>S3Ia_?{|0>;40Gm9f>qYd7>L> z&evWwZd_PEIw9kJDSNi#d<71EV?6zZ`kyLU`i&N9V>k6iy(=c~~OhXR^h? zRPe*|yTt;$y7&iOm3ZxFn5L@~E5!}Sr@?LZ8GnN!VDxq@2~d_tEq*EM{FY^Y!L&qM z<}#h%&hz5y%^lpAB6w+m=vO9=0(CQq$vDL~*!ELRD< zLt%nx_7SBGIjwR2YNy%uN5?OY_iVE5t)xyVbPInCh@G}d7VG(IIGJqxHS{ei{u-|f zrkd#MG-MSdfFuF*91GJ_hT}bVsSL);@SHQ>?(6|^u_|XY zcm}P;Y3X7_i$DSz_g|NZ&?#VU5)vrWS|ud7ph86mshmhi`_mxv5=z?cGErL*>?$;^ zY|s)Ea4ED}fs5to8kZgRr)#AI>AmX$ zXp8Fx{<8hwOm!CDFjT@d|bwg@Oe{CF?pZ;bT2)thr5Jq7wvXiCR zz2y*W9S4=eVJp<4(YK`CGpmuO7KiL?z9ncU^A0`TF&^> zh&y)n)G`AP1Ag}@RT=_*ZQe`FcYJTva#v{Sy^+gvdSKaG%M24FP$^kM5B23VvT={l zx2U*B{4MY9<9yB8rA{NB@t{GcA@~-scTv530dVycL{zW&9DuABqXf^P zhIMoQCz|-WyW98{+s7f{Hr-KXWFR4x`>n+DS_4>_EF0f6){izQNFEXjrjfj-C+;G7 zt?A(@jMpbzHBLP1;fznfk&l~>=DUN+P4q5hRIBJ+YZ6pMj*5R?+HVFKx?2)I z$ruo{vLov@Znq1LswF^ILA$OAV4=mEV`Hs>G!@7pf+V@7n-4R>SnQ?rl+R#lcgJBs zT(>&=4ZOrKiXpnzE3Tp#Y{Wv};op5S8UcEO~zROmDg*EJO!=r35j20^$XA>uRw zmy2Tu2Vg|@fYj)>2ci(~@Tc|gTi0x6EIYZ>a7u<9vA12IA4uRWUx(fTZ(UQ@chv26 zk_6$f-we4`3x^#i>3xzOj`L)#TNC%7qUDW(C}dAYv-d~{Td@II$Nl4I$O@GVLSStW zt{r{11H%vQW*pKlXm>kT0-~*1$g4wsG~$RY;jX5jVW{gtL#V6WJDrBPM$w^hoU17s zNSRV>3K3mFIvoT8@n9HzuS4+~6}N+*)!b!-s|};nshf_XTOFcdCZ)_GTRR8aX;iDQ z9_@Gad{yq+*0-}LVME$pOshk_=p>%i2L9f~vI=a^)lkR5tTqz>V!eexRzFk|&jn0r zK%!U=JV&uQ0Io7ic1~)|2-dK`H;rD6qEi>)s}6|aJapABOp+JO!B7@Q*L5MQT|(q0 zT(#g#!+2E(_*aCBibr4CHwGE2%Bi}`rgW@F45(SzTy+(w+6^n!BHw=}NRH#?qlNAlb}1(1(~zA(sSf7akr?VP;1ZMU3`TWNahv7eXV`b2llWbi z7IZfZKn;p_wgsO$0Mt~4GzFe^36j&G)6(8Fi8^&a1p|3sY9}F%G0?*wvUj%)IW4A0 zwwdDG3^*OS_r59C(Hcf`}2eI$#Q@1?cH*k&sWPc2*kObOuvqnH>=S( zmW2J+WO0{Zwh;sw9ac;kJf(hn4;ST=$E}kxl>HFRJ|BB%ORHEOvR3%nk5-}0DW+(3 zH}G!1gL90{xS=wK_O1lJit6gm%K`|9VGX!OMN~vcfUt?U5d=jHgt*HyBtfGw!6cwm>sq(A*0pNY zD(?GQYqhOQwbpLhR;#vJTbH_4+iI;=ziPj8XU;h@Z|=-{v)q|C^8)_jyYHU=J@=e* z_j}K~cmF2go7e!u!_>Of9qp~{$9MF$Lp|#1?dw_7+L!GUqvK_4lxpC#K3A?mprMF5PTgnFV)Fz`j6EkxZ10?W{u% z`5E5!K9^n%Yr$sA^=S-@sYNze*om2V2!6Vozvrwxx40JQ+SSQrTNdYS7R{Y-xpqU= zwult|LvSN)0}M@~#-~wo;aLZgbNlk#N@vsu_VNtZuyjviqh_gb@Qg#8(CeJQ&8cAt z)Lj^0vw9_6ps%^qwIPR7>U?e66h_oLA&h-eWUSbH)xQqL@3FurCBuUPWt^2N3Waa6rBlNHXUsOSzI+|3* z7~|ACuvyLBuK*`3#`4_D2}@DS#c6!C6p`3L^gpX@O!;gcTB)d?N|jH`l%B>QutBN^ zA(Y>~z2W!F$7sglELy>t5BCYFT-#%-fR7-3!qU>{6O?M7bJA4QVPGHQ8W=T4PmA=U zC((QOK6)~nn=1Fps1{XT9KyxXL_^R+rTnHS=Hyy9Rf-L5I9!5Hap)o(As2VIwsbCn z`2@K{!ZZTD&DekC(e15$`XmC53xxZIdy2X|De_zfYAs{Kht{X#X1#416v#g!cU!`J z<0rhdyp5fkWkL4=CAJCTxT!GX!W$Cd?W?3Vq(;!fdnL)Rs4+8TKgcDC?+}b1sItI0 z1HAthAsjdB4I9Xgn?c#Bb=-vaZv#7S`qx0%gL^_;vnJPZ)3i;fZ3Tmkmu&^*jkc(c zo58Awts^%yD3ar*5)A@POsM08wTmy8_aaKH)^XEpdkPlu+yVP@XY5ZYrq_ z_7p2UX7)SPn|`p`K;iS?P>2@ z)6h_*RYa3>OD-rCIFWP5W$cc^^*P-L~^P9P#YwSo27E*oPy{&%Y{H#*`gPn)isXSEH)l^*;g4(c5@qY@`~qbpP{fqf-~cd^4Ea&d%FDjyrPd#)klgw5^DW=C~Pm1#;B82#%X7^$s!a;>K|T zI@bhAlCxv$zJFiT_RAYy9=86ADyUO~OQp;?wW6@&W>Ok>O2saG7!g^m4$+;G(~Muo z&4g4IAyfa-Ax}vs3C+IknEWQ)L(pggv+?OuAF0#WrD<{K&@3l3#hF zErL^J*y>?x#depj7;eKp%#7dniEp0FS0^4kXmeoRxGcQX= z2jv;LQ>EhCU~hp+RmfTDhVTAT=TvE_=jIqw9H&YJ)g}g~%4iG*+W}$J*PRzFA)G1|*+G?4W%S~RO(;dVggD`~I8_!~7&T6nSPT6* zRVq^5)_r){G0$1&CDN(VG-#oDp}Gnkz>u~TQOr)2#j8M$ddKEe8I9f{#$DXMO+e?G zAW3p|Y~Ad&b%ah1iv zsZx=QA*S50HN;Mp#g<0jj#PCUCeIXoI8`b#K!6D&4>%T&y+k@yTFh$he))H*L^fVd zSR(6*ysU_v##c)b#o<(0yh`b)yy-xtRC$-%Fr!gk!59SnrWdEmKmC;nIz#XF5Cx8*uxs>LdG!=CiNQhIVrMands*I*CMeS5sz!b&Y za`ER>Ic=|_+FOrlZ0YSizPqQ*r$^;X+YlYdaUplVzsz3b&vl**`4gL|)9dHVsMFu+4z)Hk z*mzkRsx9yMUGJ1u0K3;u^nQ0r#Sd10{W#qvKwPyRcV>H2u=?UwS7`MWZKHz~MAYtf zO6!5W)hU%fX9X0}?&)*1Gpn~boD{{;E_8*7!^K zHIaD1!oK|wJ+1h7_DG_e+7JC3p ziWoT?tnQUDnqu@dSb5l;FP@Z6{bKqA&Z!J8zK$U})kvCi8f7kgUJy-94$*D;a&b&p z9g+PTl?WJO?E`yp}JzSg6(?$v!A-Cey}_L%l{+Oh4eM`gvkZyjBI zT3h=nt*hnO_H1t-ToHMsc5KVKmF-%mcmP~m)75d@n)dAKzMi?})GC{$gWNfDjPTqY zI$Mri+166i(pNKi@|515)+vzkgeed{roCrndrx<77Ca;&Jo%_OQ>V_ETEF9@8k1qc zxmq4R^Cr~}lyVRA}kyTeNcV$~ssRCCm0c6{t<50$jQCTRwqRUzp#6^up{3lz!T5SVMSfx~VG| z6{8%z4X#T|7G zi&uha{p?n!Km~jx&%wDVzUgy*Gl2sLR2aPw>Q{C2^yZ!vIJsjaT=GgZN#b*{>&G-uYcZT0C(~ zxVUX_%&N7twPickwse9EN>BT$_MY~x))G6+&>b+G)Xa7qySlTqHXQ|?2{kfP^*8xpqHzAzOC3{L#R|oRKV!N{)JP&dw&>IBT zw^kP|SnI`8%=09)b?r*S&Z(#$Gkc(FwDgLZow+Zb?3z*E)7}fNdbv9|373(FqW-nqKn(X|;pmn=iOIo$hq?gsy;(mM-dgDAI^r8N{fW;?{ESL#$_ ziw`!FtS(}+WEV02g={ThwoQOv0_e_kxs&W73d3`R0!};rMT901%rQn;nY;SC_*W*^ ztv*!ovlp$+Ng#+&))Q;VJHoFW>#*(Ed>!Dn8$Z4dfz)7!0{^M4CWx*#v7N=w$~Jb^H{haE*T>0uOcL47lc7gfc_1FVbbQL?^PD@JTwHO)ZnC@M zKz!B8->Gy=HA}^btnj~x&x|T0#xrEFv3165nGcu5Ru?P?c&x^0EUpkNnld8DWX?J( zECG|zbkL|279*8_Zu;3nUkB8QzV>5RuUxYVe#+BvWLJ9|{1Ujkr{&1@xznb?ubgJg zgC=oY*q;LP?|{V*gD1DP&Y3!EPW>!@KLd8*QTQjo<_{d{m&_BT+|tMY4o{uvsY(FdspA|roMJK z>fLwAv?VQFQ)?Hj>C$(`_5w9mwzM9z2!6G`Xvx&Iv+55J=YBAbG{6mqwJ>7OWIL*H&limn$n8O(4YFjuqWr~>G9Pax^K`q$!n63NB!w3Toqmd>Cu)Q z4EF06%T4l45R2;weG^<}Eczf=>N6nNqT!vA0Imw|rnBt)_&I3{(-vXd#_G4Qr)R$f z7cH!_LpGAzHn$58eGe>mQtfYJPKgjanG5Ep;HH}j9|g4q?$>F-MKhlc3ocw>4()u) zgufb4lm8kA>nUd_W7<3yW-IYra4`+&RLE<=C8c#sImV8~=EATixG?My*o7ffF+nHC zN7Ha>x~Fv}5TikSI5`wcM4NX3j0aJ9J%lV!pMr*PgHRwSSH6ON5ydQb4^rYGezBxf z;fH{p6KPh#EQQdn6fPr%q8U_yi=)kj0&SG$JvBCd%GW6_&W7Xj;NBH3I@?aANu<)+ zyEQJ%3*l_xV!WhQm}7cY!Ya6TO=q8WWN$A8vwL*{(3OV;A_N!8o@AVEmyu?;iO73`9vC`IG zrLT2*f)zZ9+})9yJHcH^x-Whoa6p20?^ItFpDI1!CbyhEM6R8@br*|EUOZJ=A5vqx zQeK)T#ipdU&1rM)o%mrx-w$S=$U^%yVu|heyqx8SeL?mf}`0zDD*IPh|XxLAH) z(E;fXwdZcVFOj$2(^E#)=@<7MDVjbSez!D(x8Ee5^cIqS>w7(HNl%Lq-ax^Ajhf;P z%=IWKMdg;WNJ(d3=5~gbrc$t;SxG-ME>05(v)ZuV=MK&&etzSes*>YV$`na$t!||> z!?c~jE`c-H{d}Fl7N@BNoKEuz798>}@pH(VCM|uOBA2WUY^T4lc2apvou=C0(-J<< z!P905?f`_~c`qO+>89bq40wiIvSv`|DzL#u4erg!p&o_2V?Wxh^k6d!{fz;u19^mR z3`DDc-d}LTkqPWf!bYWduVAs*s9XsD6aR|zSV4Mh5#ToXXq5}IT7~AGrxEXK{*FKF z^9dzpg8o?va$ZHCi^u&u|4{<9Ajby%vl`GZkCs^%-d?WtD1qV+cArUUDDMAulM>Lo zE!w+IVsaLU{??LM6yeiDe{ZjpKsAi)HjXKkhBbEJE%^Ub^KRtI}ur#S9J zR>y*p_1Emby+@!sJW8O~40)r+1`Cvc1%ll6Q37fQzWbvDbPs+LNC_xUtMj<;1u-U) zy6?4hvX}6mKPbN8gN@+lhL30~-JS&;mgmDc0POo)F9+F2_E7fs`z`Bql4tv#F9)$0 zG1pPI2tx3jQPJffs9R8%(L<70S6rPz{gqePdqvo^;qDbN*c7@~B-(P=qd=R5H?6aF zM?-k<*N>y2-?H(4B?*>C>Uu((C*3~aNw>(CCtX4sDf@HM5stF5CpkDL(C^(ZVi z*~8tRMXg(w{@sGGRCp4o$Rmf@2D`*fb_5AE?8@aH+PlV3FsyeCn<<=k4GCkthDo~h zOSMhodAx^J<7=_}wGOLE3c6@0?`>>eFDl;f3EdF*+&TPHK4E3?;f)gV!I7|%+Pp3z zf7mBxdHs5cM9@&OS+1A`Jw6gp89WG!C-_AcR-q?G320)LiF&UJW2jOz9ZSjEKRkgc z{S9RGZ~r8_!l-`8W=3uJhinWU?DZl0a9CSk+=o7~D9Fb*wnr$`+!h~?3ORQ~_p4Hp zp9%?l*cMw+Mf8wO;2Ey|ibP%7-m^)*x=DN1CY}neZ{-&6S)16D^tP9)WEK~nPT;|V zmxUGD+7U}iZ_nC9&`^V2nrZ#*XjHG;#8On&IhnaZowlkLfxpZK>$idtK`+KzH*pmp zAL^y3@%uSZENUeTHtn<>Sw{KfO>(B%e3}#8%QuNp*2kf1L{B#)#uTNwhpeS;4TUG`8%))+rnRr5yQ|1gwiuH_6DOjRkSBablWz;;Xlh!(sV~T!VDdT8^lX$j`VFNbX($<#kT-(yQrajx!zN)>ay{ol7+i~pb z&J_8<@o%oezPppw#u(YHB(c;(t6M{9J29$%erH1gwYAi=^wmtBJf*j%bqcszJKP&$ z7%8u7gvB|czjh*l?(!&|5k2J19vcji6&~1&9PT|%>!=#!){oMu27&JYDIF68zY(N# zY(Pu>xZmr+F9C5wg(17(Ms4r|hV|K7A*T0Q`j+9^o^|#d+vlr_!HSj{O2yX!K#5O&vY+603 zd;=)1LR5Vh%&cj1>Su*~0m$IN$0KG%per@f_X1FY%|iFi@GtHIy#O@pz<|&HOoibx zeb4`-NL~M4G147?Y0)-fCzwPx;^?RsNq7uNNLZ4}P+hJ>*?i+Fh2C-}t0e*M_&tk&Ay)z%?yXK3l1 zt7~IjS8)R~{099sF>opJ?L32qEnX*MbAM6ss85LEYG}xDU-OikO%Jqgz} zY0vh=Q?-lyY)@=TdfTB@Gk=S#Z}qWrBb?;DJ=>$Yl?J;!J&refVyS!16QQ)#v)tYP z^hlq6>(h!WTj0bYJ!K+((%;$LbtG%Xp3v&v9!q2==6arzqO!|bw3r(^DbfIHpYuUd zigcKm_YkXiV||!QitWc`#dxhJmKlNds4hiy&RXS4t)sRbL`L~kPeMi}KC+4Kot|W9 z>f9tIb001md;_IKJ`^38<%Mp2H%c$g;{ZA9UDc}Z6p z6?Vb{d8?iByx3v=0dLy+n&Q64qq=3K{V|>-+e66<8>$ryv%-a@nx|3kn_bkjUlts? z8XD?Xb@cT1HLMl;`)ZzCNxd2RZ)M1Nb*3NJh8#Qe-|9d==TY$VPAWSERqyVkReAr{ zi^%r@r&9N}b{G(yUaPU(uxvP5iXT|`ce;${&_0H1L*h`xa&|{Ul9y|YN~9`AcO6JP zWoJEg;4{2zTYGPxcs#bd$I_yhY>7*LD-(`~_Ma?Tl@9Kjy`g{#KeuC?qUCW<7RA%Q zdyqhvXp~6r8S+Yv4OVb|Wha%Bx**qWlt={#eECL+=pXzljuJ5dt>oi=SqFz_WiRW* z<20lCiVb}tr%w|-yB|7S^{%?p_4?8RPRrXHmNmiE{r0J@=c@zM&1U8Kb`gZ&Ib{J~ zS%0Dhc2`YoeQ|X}^=FvS7ke0O(9IvyuP{~zHThzX=m(7iJ*Z=J$yP^0f5x<$vXHM| za%#EFi%-dGI>qYX*#||zQ#wV`!H4Hv*vBb~q@m5HF8W7w(xInMZ@DCOAbxILNpYp+ z-ld?2TS}Ew;gf}z>-1v_pjR4LAcAXR)U7>=@M;ckai{520ZwNrPJeF;ll z-SqI!<{%S3=P;`R9WSNt-JC=lhOQIg4I3{<&X#-Gn%aBTw)aeL>T6#Ox27$bwxp$N zYV88JnMpVd>;+pYD_dHRS=6k8G$A z$FwVcH77k&oIuV#shr}3bnV%ob4u1HLELsyS-63nbW*8paF?7^s#`1v9Gtc2PO#QF zBW)Y`{_R4dr$MS8$1$zv3^7s1MCJ_ZzhBn4}$vMC@r(#-Zx6c;6<(?{~Idm zp!dZ^SL&fXXi&AVE;OcvobNRA>h{6nSUo>vCmKcFy#1=Lh+f7qmGb>G4%xLhU5w3< zCEU9>VY@p%D-QF}NJt@kxRL~Znj@r$HeZkk-@=JkP`}O`s=9~<=p_7jV-&O8xrr2X zrzn<`3jHC{tO7bTfC}mz8gR(4?)sTOp7c2mD?d}#Cx|Q#zEPQ#UU6ZB=eKHTptPzT z;`gD6HX==LC9{>P!cc3}dtS^6|Nc!~oz8??NwOZmLFue5B1pR`q#_@yMDheqTuS8J zCmsJONi3Dot)vt_gA-$MDSrqj=zLax1ZP@$9>Gbxo=JNEC$37ZZ^YK|&yY&E7mD!_ zoEQtw$0m(fpcQ%sM}0dDb}O%SqZzJiwr?~mIys1C1azJYrAY%ZhHof=u8tF?fFsAs z_MYzEEG!L9nB3YrC$^SO>#taz!iiC<=pMsKXjkTXdXlOhA!q4guJBT&11zDP4~|l$ zMfm4%)Hjqc7X{nT$BOY3PF(%p#Cd!;m#R8vJt!^o6ZtgFI&Ei<(L9BtzPSaQV)MyO z6wlx!MN1#2r`87u>Po9x^RixCnp1@5Z<10QYzNhaEaCI~H(gzwp9AKSZW`PVit>y1 z$(y9K3x!AIC0kWg*a*+ytv1T@Du(q}w`uBIiuKHm`qq@*CvK8$i;z!Ps8=q`iWQn> zo<5hwg8o?va-MRb_XB2T?dOk+8jI88$I=jTY|uZe0sa0a)KfMo?F7OQetq^sI{+PhlYvmM8-?o@NBR7^Y1 ze46O*MvfAwiV@z=5lbbsdK2)jUUyF{57@+1IoV}!b$3TsUwcosZ{6zllr=BwaSk7k zmRce8-(DoptrjKFdxpH@VuJ-rzyd+;zbFB<1K);G0=fsk8>0l2rnrpB6)~L>B^!APtnjUDECw(#9fj~ zS2%0CJKAb?aJryF{cAMwm89}pQR=79nK6AwYY_(6BrurpttjUC3sr^`zDJW}!_Xle z@5p$0(V=d}qOOjoe#UMXoS%BWpXlHFEgcz`C!1_*diowhn2oo`FB z3)dX%WA}(jvSDb5j^gc^B_M}*)K`<_E+dxBc*$~B-_OY&)!waB6)WcF{UI6-DQ$I z$5HNN!`8EGb`*573Ev7~lf`<~-yZT+f1Z5{R2EkVCmEGu@VZsin=)9+ft_TcDDd!3 zE{0a2om|*B&bNa3tcc*$VQEUTlZygV*46SaB)Z{Vmswe@wY#egHdwp6S~}G659%Ew`NI$??$=B<<@80KBvKUspgnbo^y5qQBgHNgKCchoj4UI}xA z`fT>d_P&O-Vjhln7m2H{oQf~c1x6`R(NV3Op0H%Q&q*~!d=e(67AtxlvjFq_P|-SI z(qz;BGvzUA<$aq&EXEw4go&z&db?h%4qWi|5uMKh!w=88MZBN9MVzJrvTn$6?aS#@ z(ow~ta4LzXiIhSK(1NSbuV>TLGHL?B>?!F-^cP*MuFI~w{-97&RnPmY;O0)T*_d6@G!^z9_Z54OdmDR? zaQIQ@|L~)qm?6m94N+|^hgopuFRp#eUxe4M>gegsJpilo^>|0gXy5OOKIhSrKo7U1 zy6kh*?{|eyziJVez_Jsum&+gyNp+zIy8t8gI{Uv4Bi$-TeK|%v2YZGqXTxEOQITCM`L{&so@R+h1MBI3342xc%MK*ar4Q*I zxkFw7u|fIZ*U?4eYU_C?BFOa+=`QZTmqnyo?ci5Oq+4%Va>ss=gfS6Oc#%XrGaIk& z%$|R|&33SCc@*;WI3%(<=jqvo+}k7;$*#gamAB3oc|z~~N)n3&bNywDA_mV1Roy0m z>IJ?{B4KsK)gjYoX@$Osg6$geA_{{~p^GRYD}~uvxQw^4ZhG#I5aCz+;vby1?Fr{? zc2B>({dxNNE}41kZ09qnA9uH+cY-!YwngB`w$PU&ThTShaZy`j-E>d<2;{^0EM1D( zJgQ)HRq0k%^eX35J)aI^iBQjjBNV!VrLSgs&<&lu(xsb1_pSb?xLM*6Tx()Xuhc9N zit%;|PcyB@7D@m0AuVE*UNsV1Nh-fIWY#nVZ>Jbc_|g!wI#6W@cD0VRWyF5el4Qfs zDVi@w600AH@t&2>w^Qn2YuS3cL*m~~Nr{&Jokh}Clx^*B<422wV}+vMttY#!#_)DZ zk_|uuu6g5&Cs&lT)$!<@Pm*1@=3u{Jh_*eIq5G3X;OMfULclcmgehR{mF+#X za%=0Hx+EJ$%-Q-$R~X2RCT;zFNXMBC>iT;-CFaFP5a*b*6=`61n6xPx+yN$SnikFF z#Ta=Ny1XQNDED^npXU=|ww@nHnecTJPSLFw1@slQNEoLmyCWLDwOo6 z!j4?g;DDsg`GSwok9&kNq6Y!-pt}e)QK5fAN~Je#AAysBF$$=f5~bzs6de1kYKM7u zBFRRinWR#Oh9oNt>jUL(5VNN%css>l!fp_`Zp$?jcLYiiPfOxakz5n(ZyzW+>5WN= zoJ)ygKi7&$N!YE?m)cH`Z=|lc)W4nLf5xT%ptC+jZ>Jf0&tsp)MG)jD93H=+NxQ)1N0yxpnLhMrh07JNHJWfKi{skL>BII_1>;wd2O{ENGf zbPaXJkR5?j$%YcpT}TWw15boOGd=N_plw47y1T0698-%g3A zTPyGr>Db#yn5%5JQ$lKV7*&y(BOhtpsSXMab-rP>y_yA!46d^nEhpQUI4g@@Z4 z%;UNCsC+=A_?>Cd-cC`edWzppNvavbzM-H}uP_Tv7#Q+2*r?u4NwxO(w#pVw++vuTGW?g#I%(PTasC)D?YLv z$FA;7)fp=}RQkNIBHgtxy6Y?Asejg^{Ze<>D~Z$p5-y~E*?|PQ^da4SX2>fbHYiVT zr=)J08svJ2bQgEv%OcXPcJQks(yccwxnqAj#h5KByhtLR=_mYRilkr>HEm5VuLF6oco41)N4bUv+^MB&geF?sf7i2jF0J#nmCx zr$ItrM8S3qc@c%dr+{N%bfu7_w^P^@>}=<=Q2n^OMQ2iv72D>>7WVCwVl++m*#H-{ z5O@9;L3AI^XX#SR=1~>t+bKmTH=pYHbQnuOpWx?~ko46|?l1~Ed8JD?h3;GZPjPhX z1H~h_*2I`oSa9v_H=Z$cC2pcoZsHp($U%L^X-%wz&QnPr=(6x z|IQ+5E6Rx7LlWLrqjxGvv;kky8hlyiFxr6#5pEyMH<*0CT)racYsNo zrp0o3!6}J4mzPA(aa23XnAY>-C=kSjc2Oz@Pu3K9yHF_y_I8P)z(c#N zpjKgBR!rlBb6H_=tnL<0Z>NOaCA8l#717%%rar#?PROLO_bE2#kw9;!gf5K28 z--jEA-!~r=NN00aQ2%yH{4)A=s8G_M3Ojo690>S!iXtO=5D*W#i%=64`X{7Rdeipm zoeXdkux`uwcQT-%gq#e_ZA{w440gb)&-7Rv^f}K;C-aQ(?0RkrY>FD;tA z*-BMms5Rzsx8)ZKq4b>@{_T{hbvhGvgGkofDJWgoj-Zf=eC}a;kt0>*l)IXV{}>~d z%IH>7@+%e8$p<*8iboT;Lt53_DPd+@`XwAQ690BeDpX9`+bJ=2pT>B}O&9{n${^ z{4Jh-NPpOZo$^B5g&a*24R!@=9B-$@RPCH6Kk2JtkvNsa(nLz31ZcsPEpRZ9u6h;p zSi;TS7=Fi{;9ku2+#^+m7UkP1F?Gq}DI(`1pLCT(-t(r|+enzJZ0#po#dtdyE{>8o?pKR^N>`M8iK;Z?NY2DD$IkY=T`INd5XdM3)YnMBQd|7 z5>4|--P z?UWQ3df>NH(yg=q>o6iaYKUc2i~MqoSPu3KSI)M!Z0FjR&Nc1e#JQ@yr@gDSUE$j) zG3^TT`Q9N*Xr%FSzfQVqVT9LL#8UsP2g{}Iu&4g*l-OF9^^}F(y0dNVy?s4vTKl?t zEN-Gqw!|gh#aDP$_R9_=(4`OQ?lVJP0kJ{(;MdVb<7(@9CnCu85a}-Nz?Vg&TkYUi zN2FVCT5`wzb_z~JR9++z%k&eLKRjPi@pg)72R}dGj;zjkd^W)9Dh#)~!^MX=Q&q1o zCMcba>I>82i@|fk0#2hoZ3J`8&hD-wnY(A_b8($~H2Xxs>WZsFrcZ<9{&b7mq>o>Y z>ivbQSE6rmtgc$}MHG>hLW15-!R8Fl$gs1WPb*q&SjgS2=oQ=M$QJDFl;So`_Sp#X zc1lr2_u+iz`!R!}DrR#li{R~)G^yv)VJrcCf}dML(pNLN!zk$Fl`h>>_$T4jFa1w( zbj$+9qqx>2u4SF|Fu`~fQ_Te>G|jZ`h$sDr_O#4Ud(}u>C8_+bvX4LIyJ$VYS z-Y}TJdSh*OM_bJfW_6&-5bSClt5nu19LrHlk_|)GUhqoU%h_(-w7rgMZ#|~5rMLI^ z?w&TE52wt8Q8D=sr=(0p|863wD#WP0LXzD?V|X$p$p)Zt*6))kX==jJIh-WBWX%D7 z!?0|79z))$w;GG)L;i1}+E5{2>U+Wzu=dLKp6=eP_%^wTvDZG(L7p=K~|whOR`68#eOhsJwJXhAuA^IrdCfDxEnvPCyUCm zlBdU>kI_|%!HZK>o-A0zfjwE2mv(qx6ho!Zz9?)N=Nqzo7C$&(SQ?S+ixSq3b+znf z)!neHDXJGy$hHBzNzk4aD-`r532T%FxK69B9nS^Y!7M?ZLkYL9Bf2v_paqW(pRXi@ z&fJGjM%<#=yegExf)d(xJ_Ypa7onnd`|)fjM)`8pFX)>Pw{!}<3(_b$`UimM5%>of zUA^@bG&yIp`b3V!QTgl%PZ;{c#wq+{uzeoZ9YwzpOn9wP@4+xz!LujRbtde=kg#V@ z4C%sl1cg*2uLAqC1*+<0EajBDUWxyBDjp?aCr0mpZ4cC_eD)-!I;Za0li>4I{fC${ zlm6yO3iPx09CCd$XAJQ;amCggi~8V6Ol?*4Ic5PGj--~sfk~FQFqa*~s1-P=;Ehy; zHdDj`44%uRgZvpra1nUtN6|imUD|5h_=UTB?Hj*}=GCz@E$2B;nl!+Xnzt3#t!__M z`zVDH@Vecfu6h;pupxzAnCodqs!A-2<1Fz4gGd6lRyUvp|)PoFr%p%_lDEUN}jPc0Nustyj{Ac+em@y4y}8V|&{qwHEMs z9vkoA8Ek

Hs%zA+YnC9{8*0l57GV)W@^Ul2c#dk@W`K^tB(^)6xkWzg@k3EnR(! zRxV!YP;c_QjbQy%X&U;DcwaJ!V$?|6GbTy5L7=w`qEIT#N)no0o<^$l0h5wYy?+&Y z&f6Vyq5RCO{k(5cW4t|hEEPUS_x@Gv^m~&4kCvpikq3RTB+Ux@zlS24%%NhQc4qB*ut0bPCT|S-j`&LP6n_PtVM#O$9U+OM)C2??H!iCiTdXGT2 zEu?tB4te*&2F-(9`4){&tmj>ZAont)xS#{y(vV`EgWuVZVx?(C9s8Rk##CPA4Gyu) zG`)Hpd;b}^F1G&b3C}*i5jpn;dt}1y&FfQhXLnAYOpG6&Ir7tOu?(mjJS+;*bNx`xfz9c{D(hP&m~zgwSV3TW%MRNc5QpvL}ltaoG<^ z)DFtEwf|Xb&#DhWCo`XHi9oL78j_VOjilrWsQ)+E4pMOw#57goIfYZ5kC2O*vDCJ| zjid*ohTL8_BZ54@vPgFD0Qo7Ve$AcBvq;*3i%GIeY>>a9Eb~|vNofy|FA8hq0Wt<< z$YU1|kZH)p()KSn-rlf1fsRH_-E5m?J0CTWQ!sJ4?@4d5-z78HSUZimHnrPZsO)D%@qh@s-7i=W^bW56=jgoTp8zqkZnzf zR52VN0FX4sBphwM%fFOQdLw^m5>^>2gsM0_r}ac zGB`oZj2Z_cI!~(62%%4h9UUUkXCBCS7EjvrnSvy02acOQ2O#JO<|FmVDTREEYe-hE zG?J2sp#I0Q9i-wWh-s?EqYI}x4k2rpvDCJYN75BhL(VIl5kW3zStL7nfZT+spK#}L zKavJ>F-dlb4e~U~Qp2)HN_&9(rLaaGApa@M#RFtCYGP^o@}`d`&|>7Ylx-u8-D)5$ zn87OdjMPBLCciN=qTsc7HkQ#2zZrwin^E?G<`HB-sbLmD!S|T=;clsZ!jNVPDo^z+ z=J7h`B~|Pfkn|Emq;~iLl7K|UI?L2hv@~8=ra#w8Rsp{Kn_Qe#bE!G zj-5_K(6^Y6RJ#arnhE(v;Z&C*ggzbiONd0Dc_6QI-qPIRY9yHusR`YP5Q`-qld8_| zBtFs-gdo>&uXGr7R1cU@_Uiu+Wc(R^I;fda$c?OY_FfE{c906{U#S0pL9QJcK}=IM zmLob(s=){u#*C#JP=%yvQ9~va&WIp&EQ{3SJV18C)Q7rrX+%=qYES72RHhBLS77Z} zWVDX+l4c?O5^^fq<9}=ysp7>3xe8?%&23VuRURPE7S_lEqss5^g9Do@d>YkAr$T66~YWIxPKu*OB&UDX64TMTr8%(3aQVLGss3r>T z#8J|;=UtSvk|9e+VUSX1v~)B2$Se#B&SY(+?KUz9L1Cdp!Gxq5io$<=h*9>?(r=OG zXX-$cF}n`T4tA}N!yrlEa9%~JOq)sb!-dGWn+ro45B8T;m8YUv1bvhFNLgKlq-Pl- zWpzE0NGGtWoE4>i!<|oTkhf5V4_Ovz2qVb9696F@K697F1B6QFVy=wM6#NlKNoD(M zBt6fNW(vN}QBtaB1EqQgQw4tpPiRl_*S2$=u>+?~+`<}KB9O7#Wn z)l9)WsfHoLEt#=Ymqs9I3_~P??TDoP7$R{|3pu=SMosRJosm?>5NV^u1LO!y{SFuI z3M$+W%_y^2jS!_en)8+hA`g%@Ox?>|B!d&g%&2j7;Z!Fgggza%RER{Mc_3eB@uca; zw~<8c0D4{7+4si?`Wf?)R?8`cyvH>pD_0sx$;VLt=hzNXaTCNeRpW09r+N_~FEeAQ zZNGvfjU|o<@~^@f5#&o2SF(c#$WYW|N7hKp63V66g*@TLpRtM z{cn{K9Dtip4tu5JkpZO!(@=1K<}LL!lxlm1G*fUMM@gw>A!%=hNL7>|CYQ$fg;SBF z^yx6x5Q#qXKvuAL(s0y)q#?vafU^+v9p)pcNsw=vkV^}vx)vey>EPx`B>Kz) z`GE75rWUs%$%IJ#+C2!dSVCS7{Yl~@%|{7xH`m(3@%n7ZAa z3w5uSQjshENtphVD(Z_5r#_g{!Lhu347v6X;UpbR~W|OkLDK zZpRGnanDE%VSKYL>YmqmrJUiiJ-ff&tbDr*14w4b^|?*=znu6 zDfgctDR1tSzKpYy_)z+D8PZI_icyAKur3*Z!69apUFH*z0i}knkb>7UZ)wr-O(b2( zkVZRWf?Q-mE-##l@}y6P6$O##GY{lG&Rgmg9!3(G2C9KP5Bw{FK43o5j5wu`GOiIT zAFym%P_U2j<1)_EIomqK~B%HJknl|8ps=%!8`65sezD9CUHY(rr^>sR2j2P z7(B>~viEbFAp=Sc9Vi7CFmI^?rBquoq?v;C93`cif~0v2k?J2oOfHSP6i!8w(x*e8 zN+kNs18HXQmfNj$1d_<0(Cx~5Jzqu817WCV=ra%GX3l%L zUCsNDWKmNdU7khI%gjgWcvA}5pPS1Hxdll|K9Bmp!*-C0n;@pC8s99O>V1U#lNmSJ z3+f{zjUH`KU;-ZvWDsVMCnJK4WLYFTcz|q;sb{)#nTMpi86qhi8{|Ng;YpT7QrZLL ztil?3fPA+w7Y~phA{R^Bmq%SspbwGLC-~{GO`!%d0Nd*jZnw?$R-gv58D>!9o{<_z zEoM;fo{<^|mGU|>BML6tl=_tHatt19M%fK~6f&UHP}mf_n0ZSx0!noZLz*dgI!E=J zR41Xz-(c0H&V(SQbsEnpoQg_-J{@KSM550;kn32y<@Q=|Cz7b5h>e)FcF->o^a}Hl z)FjAnO~^}yQ@x20`gG8NNc5Qp@-gQvsrf%7S=9XPTDzK~tBsf)@YCTMLxOB(LbfZM zsum&i>7WCV=ra#wH_ls9a~~vG)O<%$a}9#dVLno6668b^a%SOF7a)W_9fl7g(We9C zCggHA=Pga(VuRd@GCahxNTwo)DXs+hF{b{FI~RgHZbE)tIMs^?p-+cOLnQjl19^+{ zmg?1eNczMb@*$EeRqxc}?JaEhSR-ar{B+p#P7-7kiaDOemCAM}Bu!z6G_|cm(w?Cp zdt>V5?pz46j3JV^9w0|x>PDVAtdM6DQj`2DraG7NmS%MQ5^@3B<0^N%^h?O~Xph6j z89jo-Iyg4Sk5QH$mPKke9w5^&bsmj8K=vuj#RKF>1m zhZ#KRo{<{J&oP6i-7``Hc?C0g-8~~UkdH8fPu(+80~v@z!cZO>q)uK9WOK}5Yxj)Q zK18(>c6f=G(n*mQ}8xs zq$t&|k>QKXc&S~9c_``LEO9dhmvfXfk(wVU)ghSbSZ3Tz!A&_0G5@f2xMUrJH zLe{!xL{>YKA)e;dCSs6#6&{=1KK;O!X-VVC<v(?Fk}d(ZoyA5 z@a}f4L5Nn>{@kTxUiZ zH1q%WB7>()M$cjJGmes~*RPOtGBOt1*r%9GjgUIfOPJlq_~|fad4P~%+EHjQ5E+K_ zaM&P|QynI!k~-$iFpq6HFKNu0j3iT>CYiC+&&a8~C?TivqQo?maIw1*1R(=LU6mB| zg84dTaTRCPOu-j8N;1ZcNE)!UrvHQ7rD0zc<`K+G!@L|ESP4?WkgOq>`Tr-7%dha$ z;mm{d{gNS)-UP`b3qkV8@-k-dA!j5N-K!GhAkFrVY`+C7-Auu=IVyWD1}`w9YW* zm1Jg;jGzt^Myg8-m~k@&f5=f%AAC5H{(+w`9weRY4!H_R510@Ne!@{w z-jwQ9hDbx_je!_bDi4g+KyG0Tnko1wM@f2;_e#5Dx*1Owwh7R}OCk$)%oMKmt zhz}tM>_fp!K2J5yLeNPG}j$614)N7q=^`xYDU=^6X^l z3J%@gu)f27(c6d~%n-?19w0L?^#bN1DM_ToQ9~$$W-}uSc5;-YB)!!@D1$s2^q>qEnX*uD_71M)PpKZ|RMIeX8j_L#`4`G^Fl!_&<2*n#Ol@+J z>O&DBl13!U7b@rJXqdJh zKcQcw;GP^MwVtUlrdo)3?a$&gQ}95Jl3K$-NNQt&W17sGa-krHfrXtb;cLcd%W?|t%&D>zT)I1huTM#6VECk6T%hs5ISqzdaMCxN% zq}tqwq$3&9)P=!Q%qaUj!UNU*9Y`W5%)%)6bJeMyK!zq`$;N6RFJMNmvIfl*9I-R?l+t|a14LIbM6#9#$Xral zn7K$w5@}h~5X#_CGb0N2aFnFvK}aGfR0#^UxTk7I($Nf&^i~6*4Dx7j0?KfyDGLQ> zPIfJSO7$40lBWA-A}I-wf1oS}vPRMlo(IT(B`#8Z__BBqNh6YFl)KVfA!!mrq=7~a zWLwO@EC9)L9v~#z?ESgb>v6{4{3J3NJEUh@k86(_w{v zo6P4_X$kBJ^bT_RlrxjMuMty>u46oYI&4^sDGZ_16WzHGX_^V4;1Z6K>RK(52nym+ zPk!0}z z`8B5gJ#&#vMWmP9Aw+t^gi!Efj*_hTDw5u2Nb~y`%#(`H1a+wAM9RbEbIfRLEe*KM z6x^Sqnoh#tsb-V`H~&wJY8WC7%L9=V4zd|?8CpjYuc*f0&SsP;m=PL}sR-h@3#Se= z2eX@ppAN3^9w3x@Uw1BQAXL;HoRL&X)j%kN9`}r>j@|AKITuM(m`+Kq$4Dk;Fv}WHPquUAc8jUGqUmYB3=c zJd>lE&c@&cW|Up;6-c7g(5X`JR5O(aMr#oL6;34ytp@T9%-~Y@jMP9VgKNx;DEJ$W zlIq%3NFpd0l!8yGPW3%x_#iWuY_10KIA&mKAZ4Tm@&ab`s;LnLCrmZ!u7lUs2Z$ce z5UE%^Kz6{?^~|N2g2!-_v^yiGT284tIF%&M6e+LhQgvZo$Fn%i6ugk5nl8rRRc4gE zuQ&}!XE8*o1!^FdVFuT^XQT!~8QgAWM8V&2lvH@PAc>&R#3^{Md#djv>4yxFtfvO@ zQ_SEO?is0pPzHHS^#_#U6H^un-Z#y)JyWV0hDcNEH<4iyAoEbnJ>11j8Dtr1(##qy zwRZ+7gB*>TJj)tMdw3oo$4gwA>~>jKJcy(b$#TBC(pMnqW`;Oa=KAk8)>e)l0QMl1a;h%j2ZMtFER~9-L}9_hh53-kYv$K-j(zO zA`ZuKX3|*pO(b3I4!NK(gi_z&&V@*Knh*;9oTHlT&Ga@T5fsL73Mx#4F0ezyAXpnn^E?>uf|jaaom+u2f81#dk{Yzb|pPP zDD{)>T+~3QsNdj>q)Ms=LK(d8o)Oit?YJ-{S;}qY?X)WyCuRuBlSgDVkg1r_9&8(_ zubYpgBN!r?Z#j|>}Rs*37{?E*af}78zj!r7c{~(&6Fa}U?l9C6YMCK!J3wQ!eM?>y~pAKuG6-Zj`4p~_kLaEofb0N|xCWL}l zaFo zBIV(-05fVc^QPc!9M$w&4F2AX+I<(JOPi0M4$Yo;cXBFeq;5h|ILML6g=B)Af^$)< zi&;ErBC#4%U5*gPodR_rGUqSY8d6121EE6tpL<5H*i?5~SI3EY6XnSxvKmMgmi1O# zEu@ZX8zh;PNh+tQ2$|u|#RG&=n;A*6sDUg(G52#9*8_x7ALP!(17sA2%KJ))SM-rum&X|JlnW;Q5`U|4}%Bduw z)jNhK zse$Z{8SP_gM8OL=N*WLkMAG>Tk&49w%6wXFT3C;ZBebb zco0R=Cv8z#NMvH#q5_iL)b?EAW`Ft6Y)wwOT&qfE!JeOB13mIugTUNk!&LF+jyspGs|<|AMD<_SbL{){t|dZ$sl z8JbSOPlt*4*uoG>J;|L5k?Ktd1sgd^vc*&+5fsFupz>6EVO|Sa9LZV-ASr7?D0l@& zNlJ7e=_-auZOa4X6ij^{bCLEdJwP77)IVh|k}Mt|&tU2on2Tg8BK^r7LZmlM2n9dk zD9M_yBk5g+H2)ogc~TLYpbqt%NO`#Y7c<&)ccaw+7Yep>lq4~w+J+(0OlTt{g@bH? zTt4KCR{R%(gZ9w$e-6JcnP7uB?nJ5s&Bg3?$4`eHa}N+o-RRE617tp?&clUBE$$gD zM-tiCY0Jn9hN{p7oRw6Sx;$hRCuS|mlSgDVkndtfcd%`we(P=|J;xBqe2*gO35G~q zJU}S5nUTar4TLIGH8)(=nrOvIfl*e1M}?*h)eB4wCL?h-57fkUwDRcbJQ$ zB$56eHH0$w)Xa#2!}c`PcUZT5jA(*Fm7w4k%t$g#1{n@u#**G@Ae2EK4Mw31(@j|@ z_*IT-It7Dgm{ImBL5x}$BF#9qMN$$Vy(r7Dy{K?kT#do&%_zH)r2kp0q*S=22e|~5 zeFi`Ey_c8q%g6X>*?XZV`n2r5P!yRs&)&-=wp<$GbOl50KHe?!r;Cg$O#Bvy$pxo6JYv zd+`Li0Xcn-Gn2-ZXOQ%&JLK8I5K8@)I~OAT!-P<9@OhbXGrrc7|fH3&;*5wWVarX@^EQ9_Xnh8CDq;QZIk<0BY%Zdju__!Hm*ZWmWMG(im7j>XdFuTw3(_!z$1B6l!X1%0( z>;dv6%8-W(kv4PBXqe5$PJ1t2FjR&1;jE;}zk`RY;>6UVJb6S`133^gTE(`J%DV$e z=P^Vw-#R3Hl_3%r4-iUiW+ZV@1ECiAI~G^!wBAS3zfA}Q$1UI2#mz(?+k zMwzKRFxm*w!#I^Bv>M1(n88H%jMP9VgK1_)6l~=vsjk%`iJ&mzQ1DRIsrE*Oi0+kSr)0fsew=i zTbmhCaBq&13U5m!5fqv@1-ExkwG)zR86qjA1~LaT*v&m7H4w@mkExcR44tMd6nvPY znjXdA6K0gXViBWD86r)l4@FWEAorpy_p`WCVV54{8B})iLh4ndEh!I>mnAMz1AL`; z5J@AF;pUkB1^r^?gZBO+55yl%= zK-rtH9R~|e`Bm?jLG>sz$?hoAQ3zUxpAH8=r^$TeA9{KMkt9!ZW>U}b4w621hrC}H zLaDVy)LNyCh_sOjq2PFqlB(DMBoP#bM+z!WRgHOV&f-W)OhnQ&6GFjN93?5SE0T_4 zh}331K$sY?sj)Ig}HCvrwoB~=5V45qnf zM0Kpw9kLISs4$)O7URS$LwWLutOl|UGdhQDBUP(!An9g?NJV)ilCEKh#Ki-IQkxk` zT+~3Ql)qqcrLKAGzD9fB8b8IF6N9ZB)zpr`E;GvBO>BuIN^N1Z!c66XQ9YvPa4Jb? zHIVt3!6NsJ)IgdrgM-{NQUmG04Eo$NQUjq3zG`Mf!C!Hd)Ox;xB!WT}q2Lp$Q(cG* zFJ;D3Em8wnj~U$Po{<{J-I&4s?is0pJc1dRWg?kQ4dhwO=uf6b6dbVF=wBRsyFWm* z#t><`Y+9Jh4hX5^jG8If!BI`e zV6e}OvUm2oAZd4oNJ^=J?1LHX@1Btw$ibMw3ipiEK)Nx5uefKV20|H}VP-_Zr#MQg z^rs?;pwLHC@Lcy)=OO7LhDh~64dg1!;9B>L)Ie^>4DNByNDbtNn8Bm&8L5F#26+nq z8I<9DQx*yyx*v7OO^0K!#f-A|55#B;L!>_XWy~W9kUA7|I*Th+-_nD0qO!kcrKJsK z50G^d7pY4*v3L+kBa-DpccrgF(j5$uMq@RQ^@Z)?0dga9`4N87t~!0EPuf+d?}sfh z8tnjlSi#aX5xElX{M`kaV#L zq2L1?B{iD!6s1~DdHs;{l3Weq%O`a?nGsXoKJzBDDYi!&4@9nBIqQ*a?iNp)u{B<;fxsR#1_smIiNF&F8K!2_fX zQ}-|zNfr-~K1_WQbCGHdkxqAq5a}Bxgo0Oblw{3wkaRvnnlHg%o>YV;C{!eS;Swni zm+LU2$IQGb_#Q_!4MdX;!B2-Cj~M-&Q%MuDyO9(Q@&t0ZjAdDI9R}|*qwJ>mHKrnn z;~9fG(Ce7pTlneVGwcCEsXub(;sHYCn1>6I$U0@(@BwxU66OECL zj$)cBt=-+Ok{1kB`59cdr1m??R{flgJmSP`j`HLYSq)?_%xD?g1_P#{n=xh`LnQOH zBdLQS7%;hbfKX~PBZ-R|2vw+uSzM{#%?!_MH*92O`LL=1n+<#Il%c~jBQly+HeD+p zwrJ#TL+1?HWk}gzO)DRxEgD%qOnlX}ijkQaL&}E@8De~`+*k*TFS7tTU_5-CH)IF^ z2W|p(8D#J>IGw%wFiqPilUX!U(*|!1JZA!Ih)6MH$UF!Rot-HM#KxSaa&zD@Y;!;g z-kVI$00%>kMI+}9-EAm{tZ7x1K-aY4Q*COsnoPlEO({gJ$f=^ zEhxx#>X24oJw~ve4uNVj>q^dgDu_H*N~dY#EMS&$QyWmzHY>|)F_KLQB5iJnG;6TP zaSN+_BBw2h!QvtN4Q45~0L{0u!q*r6m1CljV>cyYFNnNU0`Sh+F_WQzjfUc?{G% zqc%+88V-8Yn)2;7bneipL!e-^I$Lt1f=n#~7IUGvrkPoS?t0Cv0nMgYViux?)|(hm zhA}e`196%*Q)DxD=yaoU3**c(tFx8!Y?E0fvzn8GwG`kkqDhHHDDs$#s!&}QHGS8~ z&=-uz>^_*9j=@yZ=2dEC0}L~Xw7X5u`MNvu1<5pRj|qB1+*7pTb2GqnFS8-*O@IDK z&060ZEIkRBeL=0>fJKwvn@a%1m^)NNE!-HWqOe43T~rNiS?_@$-9EWsC@z5STah99 z;vGPDQH1-69zxTWhNugsoPO)@jG>seklL0L%1ZwE#`~^Z^L!&zgFjzLvWwF+u>~cq|1RFisF(Ns)D< zf!S9q0KlKPi(VopQA=tYxi?t(tD=w8lL6#pqcIs{$|+l9>P8C79yH`&pq-i##5zcF zTE;>F0Z#{th(AM*ZysRazb5d5Mf{l=HjrLXHSMenHgW2$MP)pjBW-o!oD8c5a-0h= zqr8O~gbH7Wn4B)@8@i}whw{w~_X>IkbDsWPi1sZ&ZoaVyoey#1^McF}oxP@A2r&lj zB2zI?_hOM|6M?-%AoS3;Gh0AvG!|ekWg)4*f{bxKaGA(mH_YX%F}F)i`%Y#ul#|fS z5_ttjVyCIs?<+aIHTEiqwd6Y2n1y_ou-2jPYTdG;{%hJbSW2SHSfAkz3@Fz^Qp4hH zqK6v-%!S#ngXq0S)(mNb@bzF5F((r#Ona^ZvahIoS5LArN0onXIE=a?%`l)&c}_6gZrClzFbm&xhTHuxhv6lwnPG#T zWaHr!Ro)FH&kW~{8lYtkxMtWI5CbF}(GB0TFc=-M{%nW=2{*ZnVy?xQs+O(GwW`Z% z%3(?JI1#TS;)mNX@dF}WPsI1O7l{rSjd|Qi@oz&SZIdf0{w9jA-x!QC{JYn&GRuHv z=75PDResPYLzx410_*fP3+Cdof9LSq;2*Y04io(lF@Fd zIBwwP^C9pFNCuY4Y;gd5d2Tw`;^Bc{n#>lbekY?{0XRE`;t@|cKtj~-V8CCQS6pClYOxz7jP$d}Xbx_;# zB|ul4JTOyMrJF{GW`MM<-Uiap>w$cZAeV{s7IMuvAgvJOi*??}TCdqtAQ!Esn*iUj z0;U74$^iU~0M}RnqE|8i)f?TA(PqG3#f<|+E7vuct!p5%(W(~`{Z2bw8GeE`vV1^uf?hN<=v z+HR^Bw1?=00zGcu-6x$QI<)3@COa?Ff52`W!U8-K?Y z8SUYznzrpYOYA0JK&)tp+fI7kXrg0I)8X7l46h$st_>Or45}6k)Q*S0Z8sMTbigst za~u4tE}twq^X)3WzXyyV6-@(1?R#ZLn-4ReigIWf+E@`^(JZW*8S|i?#b`b1Ks^fM zsvZW4Hg>>w!ITGEvDH-&^`HL%i^B&zN`1-Wf=$)0MUv`?K;InHtY~qj&j-5R;j9{P z=1;I@>gl!WLx6M@{8bz^fGe%RT6B+kuV1zIc#+A?g#3yfDf%}Ay+EMz2mBJ$*A+I{ ziB@lA_vSU2@uiMPTkbWxtj}o2!(YWU7RwkGt2qPWMd4OlFVh|*+RYZ4R{cAOZrBgl z-7Z<=BOsj##aVH;&6ryCuxm5gP2E6x&~5^oxYbRBe8!Hn80$;|y>2%_F1spWJFWW9 z1pmkmXPyRf+<52<^=4P5H#@z?8C7Ldz1n$*-cE0JyE-w_NfVlZ^f3HY3>b(dJ;o^L zp<=e+qyV(kCTJF-r5+5;N{k@ZmU^qG(AxOct8!YZ5xdC)5Nov52e$(lG^4w8I8U2~ z*N-z=>b6h9+-ck4qUPyDy_M=*szlv~iQNfzlxcU((zNj#Z&xwyYBB29myOyU0xtv0 zinGc@gB9@=Gxbqq%y2M8rmE*!XbwUxBsN%yqTfT}VIpO-g{V~@15q!C=)=mmQ5Z~h zGYPS*E#obMcR0dzLAb=V>iwZ1>D<>k!gbM1__$jDuGfvP2^mqjF?yG*EA1h=Mz0%B zIWf{n+V(rcx~<~ezhtzrlZI}734GF&VTT*xi;!kgFU%OqDn&mjW(<=qhso5oBE_U( zqUgq4Ghft(9d8#gBVk0+yAr_`DHDGHl;;I?M`1)g%?)~*iGPCFF9l`tT_VEdHh!a5 zGumAEn=~CF%M4CNv5nsYqK^=y-At0UQwPMHAz}{$5rn$AQNmW&QcI6!qao*%|t@a#fF_n*O0qfgs;oG@Tu(jtNt!WoQG1p!R zR?%uNrLR}P*G%mV^!2;&wXF7W`g%2dEwBAOeZ2<0R@AmYb~>x|@U^n`t37rbC> zqrgu3j{_H-GJMk$aj7(QSI9pz`J=a?kUp%O(hTV~dI!S)gaSJpOjcEUxL#m?fbO$) zMNWZba|&!7nAK8XUxBZd0)x6{EwGc|tEIrc3STQ~w}gE40y`PLR@UxBUr&Lr1I+R} z6}}FvTQ1DDQkX0=CM(LON=RrdlPB&9Np-s(#dd8I7;WN-f+EVVo68R=cL7B&rPW+Y zNO=P&>pCILaXg7a$~Nz2v;(&TN{{H8bXkycAW%*dW!{^ckFgw{cs7vr%F<`g?1wimqWsIBmTAv+h=Fd}KcG|C zX;GzCF}7Unu0YPypMt20ae8Z?{-OwPS}wHL>RVs{yIKmrUHtqy87Zu?b{bX^#5hp_7e6!1^*1gPBfTyLlI{l5^e*XQhEABR=`P)!Y9&;`pIY8Uy_Yi$g zhHCt#I_zQHTso@ipMcfI{Rp7?eBlv0X~G|X^!mnN=|?kIsj99PmKpaU5GD)*!eb&$ zl^`0FnXiK^A}%w=kVGrL@76MH@FbyV`4%^oX=hG^;`vGad$2XM!IKR zE+#Z@19`>*oi4s=)Aoh1zVkCHg9)ZL%!6I6Ss9&Pe<;vTm;}?y^5O&nIuKd}!j8<0h@~A(5scEA0p@KnG zAGPcG_;nC`%}l%mav31jX|HfCzYKP?puf5gC=&(c&vwewKv^Ovui7Z%{|1!f1m!i5 zH!}t~Rf4eJ60vXO;;Sy*86=&!1(5F)6J|OE$%>Ou%x7{9;gk~z_yh&(WwO%mYRF4*W4H&J>)noLf7$NoShYPOyj%fWm zkW=$CD2B6evTPL9*=A9lBbvNXROgyS_4PxxfGlV2c;Nu;32!&jtEmNo-fI3P(pXwe^=<}Et`&bj_KNPK%`*K%#QHSk^Uy51h7cU`+u!kw7GEMTxL z{8ju-Fu0r;{LNtSBVzEr!C=;PR}R$fg};i|%5M0LUWC&gfUiFnQ7g-_zn}h$@l~|% z-9=jk(u-q+$a{$6fuXPwq3sDPW-YVVjqv}gjwsVAch39*{skr{r=J!RUxyTLZ}e<14n5SSujI$+2XyYN%9hXSafa@`qH!cU=g=?TRW zRZl2lC}H{Hahi6|Rj`hKe7lMtz~|Tzw^R)~saD^H-}@Ke)wD0SFV{x=Rg5K5{tu#G zfT$5ym+igVO-OoEkVfqbU;B0k(%^FFff_2?ZWgSx@`ZN*{}E*(a#7`22#h)!D6fgg z3K2Q#oA7nJP2p>${`I@?^+fS?fcOfBCzV|~r$3gBS_6S&MZ%ZGT6ok+^z~2hbnla)5`(a zEinHSUp1ZUp*sNiBlr$Gl`nxv7hVtaD}n2^I@kXz8+9`Tjufab^i=yiemmM`W3l}D zAN|XWeF_L8HW87TF^@okj5b=28lgvFT-6gm(WYDiTSt@D1OBQqBi%Slx~iuI#)#k4 z9&a!(h+A5TFPe!a*yF8iLFLjjN}>AiMDMoKb%R&eKZ@yl>~vl1>hp=-XQ%H0 z*=g0!6Mc=HE~=_lJ?=5^nh|Q8Rle00sD@Fyrp#Cj&Llt{ac^1m$pkyMd;!5w+qnRH zTWEVW!X&#w$3im&9uV(tUz-y+pcF zkVIZLNetft(x-xSt3;aeQ}Cb@R=T5H)No7HsXiV^P-5DMyCl+2fON+-K)PEZZTuwo z7s20%d+el|l@NW0Al+}Ny+(`CD?rWn2=IM7K&$yL&=&j*68}J^ErIxJ1nnUUO{=*R zqW&$Se`JlW{y&KN_#TLUxSS_jM%h)*e+v9%U_CnG(ej(NvRcFFIHv3i^>~EP``WVV za|!!c`Ll%8YYJi;0sDgJxYw6eKMmMp?}hN=j(n>}{v7E~IP$7K2Yg{`;Kb*kwB`Xlf+!Z^$`#<41+ zBK{oWNB$aUBlLql9OJ4thp0P6F^;UrEpn~8jYy*^a%+xOeJ7CqAySQ&QhiLMF;c3z zPlM;(k0I68cJU39pG)-dcDm77KTq@>?DX8hN~<3K4CYj4M_P(xHG!r&fwbx$5q+AS zZYh$=-(XG)?I5F?wE_J;_#3g5&v2sa(reW_KL^f;@HgTt*PL)xaV8-z$d9xZ+KZItJML*LB{$*sD9jc4 z;aYVcA+K~tT8#b^f`8Wz*UM13I4c3q&G+Ys%Gkmu{+-EMex`W$VV!~D$9b@GZz2TYE}X0`?mw= zCzdX=O7y&1^*uoQ4E{#^vO?IvWS~|552BwQ3#4C5q`m(D?v?O2;<<{KV18&#bu&b- z{XURhu*=S!n^yfXfnK$PxFAr$-T#Q}UUx-m)!!h{8+MQwGmz8o0d)KWAlO@WkVUX< zU>Tu<{%Hr<1?wi{N3KZddI|I|JIEqfB{=k*`2!H_6FbNv*kJ_HDs5H5F4%p9EOSL_ z)dT;8c~;m#7Qqey(Dxq%!3Nqv7QyZz&~Q7*E?DI&$Zn)7Qma0gK%?y-i(t0{=&gr9 zu(5WKMX&*XM$k5PkX^7N2sz#rsZ~Ejpb2)6MX;*Bz=q+EK(HO{Ad6r}6KI+pWEboS zLe{$?wd&1Y#XM))K^DP|1JGYYKQX70w!MvID2@b=5q*CKnKo@OyR^ni zvbq|g+C=nM?I|X7LG*)y^o`0xjII(VpA#M<%C{=T#tL+YxW*qh39wk=XsxCTt7Q>jdf7l_G)_(r#=DT_5B43Hd56Cy9pH*e1J)3*y*Ep7xYJgUiWuky^Dn|W*b!oeK(-#^m%r=!T(;M z5BUeAUudIizIkevk4Y%GgnSw*o|1S_Ig0K2Fdd$2cbpZeJg>TfTg@_{IJMfsv4M(n+! zqJH*<1v|F?eb2df=H8i*Cp-_?-SeJv@0oMnJ9F;6v$OdT@8f+KG~9A=KIprOEOBgq zJMJAa9?8yJsXum$C*XhIFDwzaybTNQ7oC+4LhU|SF<*HDhEd<~6~!jJ*$4mo?##vT zio#D=GtULZV<5Vp;$2+vNIBbKW&1-wxw_BurQSEfW&E$}(T&U2Xd+ylE2CU*56b7@ zptzD<_f0-t6t4R+U;c9wU5&3>lrNn&*|g9r+d?>KO*XR%_%R1+b>HP1AD@D6L1Dnx z)iS8s8GF_qOI0`PGF9Cs-RJ^U)+75$Ljl}~|8-k*`_2WTb_h$i0JzQeUzr?&IG`km zCPPUSXD(4uh!~B&6$J_Y*S%$ZsFWtulW2~G-$`H^8n|g{5L}1Z+=Qco*S=D1LxAmVaFf-;%39f8DCUi%FvRQ@4gG zcvF|>-Hy3JB`-cfbUQ>ZQoL06SCCkNstJV)@G&U!u5-!u@7>CMA?H$9-5=ee53ODA z?mf_%V^@!lL7BAWIlOLhw{iqKF1OYF*)3WQufnY`=}%k<2S6))g2u%$P!c{wj;|s8 z6RjXR4+>nktZVE}v!wT+_yELj5gMDe4dOtRxdG3eqq<+aAwF9{Jy$ocVh0AXyb>A| z&!4RbdVLINc>Whr_@y##Ada*So-$pNc>h)j_09Ic{$d@}hmFP+7;V=6buO+hXvC;* zaGtCF*~vydzq3()=E|I_zRp!Sr}YPKG3rn6X4D^<>9xKX9}{ODc_Q6e=sEhG2X??YSrCY!GUQfNxeXja*HyZV~TWssA zdFqStF=_qfN7AjIf(=#2nXm9MQSbeZQQz}W+xqsN`eJ-c)cgLPZhh<=PyI=JOw_li z@2+Y3@Ce)b;hy?pd`#3U*EZ^LR@ZvUQ=g2Fj`~a0+WNn6M}hGD$&?ZXQY==Vv{Z$groZtqQGa%zQUCFHd#E3Ht&hXUME%Q6je2~J z?DV9!^>#*m(nNcx-*~Oh#>b@fJN7f`m+fZ{6=i@!u_^eNs4sJ7TK&WR-l1;4w0o$> zUu@J@KF=QNKb|w=@G)t9{C|vke8TSZ41E1PM*Wiu?4jaIM~?5a@iA$A_R~haaG*WZ zqNhFu9~1S5zDTQ=2YH8jJw7JtU;Sv*$6RL*waIIJ96l!MQ}AtXxlqPek4`TKZx@Vu zbfZ1gRlU|{<73kLFRK~#YY(=Ex|ydw1s@ajpSDk{pSr$xs9)n_qF%z22*meSr`to_ z)N6elJ|^l5CK&bjQr79UsozASe%bBzP)B&J&&J23^}&}L^<@vYhq|w)J_R2W^)>EG ztG}?dcc>d|;~wgMj~ey8XWK*F$7_8YJ|?aAe$%MO*VRrhl&k*Fs4w-1J=DXz)@S2m z(t7bXqki)Qd#I;->QnGBQJ)|6(lo{D1IBuXdLBL|>OU@L)EnQlhkBaV`Z#>F>Zocr zoXjfu(yDkmQhNca=wl%@RqZs??xKHL71Uo7_2E^uoI&)(1TVG|^`Ly*rbc~hsz=bs z)jd~PS{-lp!2h~;EBAl~O8amvROHS~+E;59K5tQmmYs5Zo#TuoKQR=hQKD7voc#_4itH^|SVQqPK? z)v>}>Kw-`aH1EQy>0TjsXtIouTjj22Q$e|TGu*z031ZDMXudbzWSb94t3qy?-v#>U zu`sF&&Esyh{Eq*@%|>-MRo85_x!fmLvp`>?OK%H;#rR+MarH$I$uwz(G#Ujn4D?0y zeHOY)p+f<^iT`yAs|O7Atrl2lQT0#@sa0{C+Ywp(ulp5uFT#20Cwv%92DMjV5py;$ zp}?bf({TGm`JnDW(UeHtiqE-GYQ!1WdvZv-Rxh*1G;CVIyzbcQiskX0oV)P3ZVwt3 zjuv-I^B~z^I;0cqK^mld0u*GvI;Og`88k%eD0{qxbHu)U3SMM(I<{IIW%hRB!uJC( z(LB!PJ9zahUUPLPRxiheoy48f#hpp&P9E`=j;^%PD=1RF(zxP+_5ZBM$nfLd74YT@J5EgrP-#@v2BZ2=x`JTKFu#%J~ zP3!0N+ZD+7MD_wwz5Jf|SpP1JbA>!ts{@t1pGd-cs{MtJNot zSZ>y1N2bMvDJ&Q?11<7qvHC^ZZDF|9C@xfv#%JCHR{vb3T}-HddeASB@OH5JpHupS z*1S`1x2pdwjT{GrcU#r}kw#`g%G<>1|9&Rb`^nqt?O*jTM1$|ryT9slxs+CPG$7ur zRbQ2XW<$)Iwd%WPpuZsI&06(KX+_NHJSjNx6RZqpTdLaK8Sg5 zO#R9k=qHG|GhAQJF{94G7T35J&soC%`n4!E+*7}bXF~oou?@4>n~?KVQ$N(j$jBh- zcb{&D*N@EIKHTjt@qO(D zRiaH0eQxoC(>NooEve?9`%O!&ool+iw_2Oy(l#6%*qgWb#5A7tu9`nu&3|>SsbPxN z#r{0^=~B_c@)9+JXx#^O`@R0Qw36f4 zDOTy8w36f4f34C(X{EGde_G8sOVkXajb`b7dHpkKCC9PLt1g2Cd`RZ&qokw36f47PC!DebY*5$0k|L{!7%v!vvtjJ^K3P(@KtG8$v;pR!J*4 zj-73l2B($Mj=gF%H&~*ku4H?AO~K$gTvc*a`4zDPl`A~8>biL4jfaJoaXJf^#mO;T zo@YoY1I810rcWzgF5%l(%w;3I1(!Yf6ZE+Zz`X=t>i~QJ08fU6x6Ca9;cDzb{>Zo6 z`g{P5$1wN{^ZA)R5DfZMJ)-B6!n^!z?EAm8qMiSlRryp5NNNAdOxn$T5I>C*?Y z^(gOn2W!|^B;eX zm%3VKi>Kq+RIbcT7@2(4aW-}K5xMjicINi2)F}`j;v!QZN@NPeFYFA(WG}a3)%AG9 z(HaBS?zY^?J4l6_TkeOQ^vy0~r{#i?$KzW}>vs!LPWC$!pYOnPkp^zitz!9NX<4kD z*I;#i;6~jjWwdTYJcEV?3eA&R8a4xBM6#`#D~Kq(6kj|ta@kn5@?~IP%(8>o= z9vy@}S&j~z&}~(=oZw;?&9wNDXW{Tt{><08x+^Vo&al)fhRiRki7@H zo&=0jxPfPNvt?MWuqGV~ijM%}6J!Qnq;?_>Pdy3|igNeof~PSL9XP4mMcDY2!%(x@ zT3El%DJoau&qc%suGg*MQ+yF^;6Bn$EtjpSFv!#E;A*d{!Oua%W^W}L zTqJch_&I3kkLMrQHn_IvYVdQ=@cFKZ2AAYq4So(9&d1jbZ5v$4ay9rlXn6klM1u=J zt_D8`4K>x><2JZ%;%e|Sz8LcpSUWub5B}x`UXrgFkEnv761)g81Gd!V2HWZw#hyW+ z4K~kW5!g+;of2$mnCAxmUp|p7{V_&H)g_Qu4}2&;;4ZwekL~C$37Rc8a~#4%hOPJ; zl-i&pH2rV>M2f*;2W}9nM`&f_!Lq-?VjynLF;DbhmueD>{s+*;7_kE%%b$wI@Qf?2 zPUJ-8Otv004F@bLbMp2PSP2}`DrovQbhu4A@Nw$My`D}lO-}&sbsKt_OIUn!;U+-B z<|haX6B9T*mpzQ$4LY~5i6`^iQiYyu$U2^o?7`@>!CqniygUWalVyQKPZPqlBau_? zFbRnhxb!ijkdWUY?=&HApzU1v4!bO^Ju^D498WYM z$3d@ygd}=FErV|oa{E0dAv{&dh+3NGs;ZGVsdbu=b$DV7H^kqdbSsq22pLW>65_yK zLPVZP2)k61VDuko%p_!6GzLORLPTW;wjMO?`aoucBydQppy^)dq(+F-OVd&hW)kAU z69A_YlE7gFdl)?rIvtD<#}iG+stM#W7 zG2UO!W5uU_+ov!vUz2g2E7WblOdLd?6nM)6o*s(o>wEk$=zCeT0WBExe;&$4LqSK6 zLYI=3Px53u&TWzw?im-Bp$9?Jb5`Y3p8Digs023SWc1S}EuT?GPF$iR2N5*A1X#w& z=Y+)<7vAL=la?$@J28Vd z<8La13hV?RJSjnK1|4)-g4zrwjfR4b-uag}gB&98UNXqLTncx<9vQ6u)u<#HOkgvx zUWASetR#b?BmD(U|N1SHK^GqSdnSVkYzEek(CHw9jwhPI`xkeZ!9*{R`bsj$+X5tm zJkMn_nD~GU^4e9k%W4%tks0KtID=B)l?UKo$0x#`~4E~BgsWIrFO=uxC z29riZK}Wwgq{5CtmH{?{yqTe}0zC+tZd%8vBpFO#Q#>5KZbdqSq9gqUO+(hhom0H> zCu7isE3vsKr^aLqCa@_U=0c}~3_6}@1}AM$q1P&Z3?_O(E$^j}4DwzI$sp^yYz7k_ z>==9r-{Q`W!39_^?&vIf*nZ65k@%Y$g90Ee65PihQ0 z=s^i;Gnh0Q3Of3)$#DkVG03}Y3Ww8!py??*WJfNQ$rwyvGX`(QrFwqNYd6SQhK`aS%G6oYL>=>+ht|Hhv za~)jpV#gWW^f+d482+X*sK8IhB7*}G)Q&+1-6lb829riZK}RomCC;Eb26<~zVI(~W zny$n%O;Q<5U^52yeJztg(UJawriRxu8FbVaP*rUW-!qU zYPlw$WAOP-$6(@v9fKECR(5n9{9nfzT<1h)a3SuLN@Y-iuTMY*>!6bwgATf3g4zrw zjfR4bUbk0eN7q5#&sErr9t2H)Ta{!CCa@WUZ}zTCk3rFq{(`3KYbw)cQ5Qa}!#i4S%RUcFvrN7un`JI>&-=P-jO z;cqH~3Jd}e?v$W*3_9p(32HN#G#UyzdK+BB&1}LQgD>xk44wshX3(l68BAa^2HR20 zrOu+FBmD(UCv2X{pbM`zG?T#uHe>Kh=yY%$bUe`v&cGC?gR^L&7u0gqO~>FjosPl8 z2RjBAw{|!NbEwfem=7LyJ~O!dd6^6<&*P!Z6WENwBM|luGU#}s z8Ql1k4l|hO1+}~_QpeywosPl82RjD0o>JM-b+D%64Bm1LGdLZ8Q)5tpu>iu;6V#4D z2c4OqHiJo{p`fFmpB87(9fQ1?vv4o$k->@6GZ{=^GX^)lEt5gfk^X|FZvdw<=)%)x zWHOk*W(@9(h2#!0=y;+T>~lwl8BFwoTCQvB80?kntQJjtuw!t|w>lhy%^hd(rt6u( zQMk7>l|cn|0US=mpVSz1&|4GKW-w_q6m;}uAH*4S#~^Q*E!;*Af~Flm%w#Zu?HK%D zCWE3Q{RK_$0ZwJmg{OX$$zTGTF}Tmi9cIw+L^HVZCmm)m(FOA=Yxq4 zb_^cTy-F(?Z%t;w>K$irS&R;xMe#S4K?Pp>4>I@%{-iSKperS|HiJo{p`fD|;W?5W zTnBlVabY!j5H#IfV^ossU;>*lxPPCj^jTDNq`#mE57$X&(1l+BoT^0=*o?swYpXgM zgN`Sf!6ALCI=T)fdO(N2DKSX8Vv;<{m}3@gYFpQo!o^L=t0nQ+?JUPCa@WU!?((0P;{if zps50P*`~&z3qJ=qmB9oyWAN;4I?SNsiDqzzZ9B|hq8HTiMsgj4n|3+|6Cdmtyy5Vw zV7=^oaAe0BobeDdco+VrGN`~l0K#(;)LsW2^!^038B7`t1s&adOq@aYI>_7K3lGB{ z8GOa6Bx5jv%^1Aw*h~gRNBRqzHa{+tK^OiLa4LfdY{ua9<2%ft4435R!_^Avkur=Ut0{*1Npo3nWpf-a^ zqoJUq-?=@`pgRWn6@$VJ^dM-u`i{&POkgtxTV`f5C_2&~xA-y{bm4`7QyENPGX|&K z)nNu5Pc(x^-rZpa6TP68-*C_|xKF2JF!8~T!C80&@j=-!ctpn;9RE5qcnJQcGN?d* z0O8OCwPVmhTNBh~FljUtbae5ZID_sOx`Ms%dVplOY|eEK@*!oL7cWiWxw7@XNJ-%%ywc%m6Rras?MC6nj{ zwfyRhjzQdh)ycYO;sb7X8J<7#GVHnM=Tz46{-K_@A!LU>_=6uCcoBfyzIBz^b6Rd+ zvjN=U?OQKng+y=PDs!XQ++S3B4mSXpTe+x#-S`e}<@%9`e=C=WI=Gcf<-ftezm-en zvKJmLb$5I#S9k6$@)iKcF51%KM|Ml$YJa-Lk4od&Te+m&p!g6>+*`S{JGLI|`ZKUI zZ@~hWdn;EjIu;aH#~lyC5pye-h{JtxV-fC11176D&aGT(7T+_`(0iNYh9+(h>kUoX zJ3lkS`|+M6W|+;o8NL;OWcWUt;g`&t4l_JH$uLV^o8h-{GmXhGH9F4lf3g`CQ3n}T z`Q4cet6XkBi8jW~bmnHg$Fxs8+n#Siv5Std_>tXGxZ2-n@uSjsHp9|xP<#_6Ziclx zwjS)-!XmIJ))!^r#;q9vG_{KOcEV&x|95g(-dZNK;udBh&LBsK56Ac#S zt_DBj2E8*94VDb920sT4E8muA@Py`S@H6>bafRVCgP8Dnczz$8xN)xRG{7HiHIw#;4 za3LD>R&J}=|INu)_y+N-OhLm3_&BIVZdxcDjdj^vcmnuFc@BX?zCp;);(b{|23{PcBwlHWlo~?{#g@+hZ7>x8zt3%hmh>=W!7I zSHh2&44NPv?#`Z#WL6>x_hB=t_>dz$nBvk9*o)_Fxg%%~$E6*$D&1+}_7p7EjU^m6 z$IYPUoQBy>Q2XwQc!m&Q*Z=1H`VTP|GxGel9*=3z9XNb*^binHzG+%K z315-e6yICr8@bIIXNKW<`Q~cPN!|MMP0cC11F3MObghz86G?a-kE3*lAz967-KOes zsDZ-$+X2^{o>*~coDAOO>QWEYE4t40;SV zo8N>lc{&gL5wC;dnSi(fU?2FC*y{aP9BA$XfAI4QfAfhV72Ruj+tt>^ilEHrm7Is) zK7o+&TYx4r@p}OWg$E|hniI#5k2R6_4cvn9tHH;h{3_IJ{MLlr#_uiM^d)ic-F*Y! zZcDLS2f8+X8{)l<-=5FK@r(NtSKRo02qiausz7}czk{C7#!tKsieCY8ch` zj=!8!fh%I~rZPSKwTD?7u*OhDS#)*-q}F%-A)a z4Lh70&Ya7znlC-G671kh&u>XIOK(F}zGXb2+620wNI4#}_|o$hPZ+JEY|IPqiG4X9 zq4?4>dt#D1`qFd%pHQsUwJ>hG4L-+)ZMXIC)|>{l-!O?DuMk21={xy$8oVXgN%X`H zQMe0E%a^SAn4gOHJKy>x>(BJ?8`{l*U0H1yQ&6P*H56pX;Y-$+Tdk`tc?v)4;WH2R zOV;ehJAC&`)+^=@f59m;zCxN!nQ_DET`DtUTm z87e-U;?hqq#bw4(w1?x4Rq2SA4cwmdVXGExa9g(ImKh@U%8ZPnmKiGEh4#_&XgytKD9+x3XibE`lo@nMlBXR-mszN1 zE{1laYi^lA#3?g|=N|(bQbh&F$C8VR74si~0C6dNG0sAUqnn@EC62yHpTc)}I37n; z{;3@1k#CtGw^V*bb*5VJ?*!lVZG*R_@!yFT9|G=jRBhRm;i#Na!O^u}~8c-EGCh4ygVu`2ETrh(g2uvj;K2H4@KTC$xqN7eu4 z{O#humco=NM{8a;z0A7F_;4#yM^$_u?W5DtdYYq(vo}0K9k}5r z&ySKk?I=0`(GjR;E`}bWYc5B593DsC02@+22*!(_&rwS3_X}6dFFW7i=wMv&3`al3 z+b&Gkh74o4Ho#w>qbeUpdGy2r6Xcf4ZK%#vD?U>22i`Y$YZ@O*yjc9e=cwAUDZ^2@ ze1oIM%CUf>Q~#ae=m7TYaa1H>Gn;Was^V2BF0JsM@vJSk2JPXvV^zA-!tE(otQ*(G zaXTDUOSY5dsQTZW|3Um$j#8!^-R&LA(Z5Lm_)tk-!fLkUa#X|~M>C4bQ5E;4ee^t9 zPjggp_7+5&zZ-LuE=lsVqv&1>^~}XkMAux767e`%Mz&MuQ5IT0N8QQUiut}@v-C*K zoBnSr_7sf(X68+NB%t`W3BU9Zb~_gZPx)G?*}8vg$Zg&KzP0P!eJ~UqyG_Jyd+6G_ zpWoB4b^mtX#C3n%pSa@I{j;Ft*8QqLeN*=jT$ru<#p|Fr36NX&C${>nhjiUPJpWe{ zACrf96Tj>r^Cmvm)R{N^i6%4g8^a(4(U;%G@#Eu9B@Pb~3b(|^pu8vE+xX4FdmFza z{)p#INBMTAirtgYwefov?``~6|1*wX+@HAO#&02%-1w;i^-cWl{wo_l@j56T{@hy&5io1~xcYBZ^Nmw6Mv?IQE0V=>+F=1uY? zBb^1ww}J|4FZKT#=qh~u5~Oq8$$R7LO^!zm!wyJIi%51eoys(H!ezFhhF4pbY$so7 zavc!60sjXFg5gzvNVLs#>R}Ae4yIG%B$A~OKbZN%glZH2f+FR3C}TSHwADJwrlN45 z*q7shi|G`5^5zrHGo<=&j){{yoziH!(<13tr&AJ6nHKFCns6Go`Zw+GPp>qXOK3-; zVy9Qb7jcZ@8CFbjMQVCALBlZvI_4QxhFAqf%Ev;%POsJhX+`VmYQwR@X&MgZ#ZIr- zjTa7odbP?wPFb)G_+!d~Kk>E;WkI){c?MYufBmvR<@JEED*6*7GxB)EKu>sw2w|h>*=yUarTDN6}Tx~ITR&w+EFwf(J`fK z41GZzw=CdscxAyyU_+`b;5h57EEtflNTyc{ae6ZxoqTDRI69uG3lCx7z3G+8kD)v& z^fW)0l$AMdYZ^b7c=2T5E=SdtO&N~LDHa?(M2-a<-FH%kqa)a} zSGtNM9K~kb(pANKP+Z!o+IZHM+n4rm+_5VC&%*5~SgadQ>fv!zE!j?*qw0Tieu4O} z9HmS-x=}aF(bbI)Yw#Y1TyJ%-lP995jX1<|nXF-LiRl;mkg z(UTVHnTw&V=$gw>9*4)#3&4id^omzipQDr{)2l@wK)eJn371d9(P5W&iKFfGDSU>9 z<8f5wugPKV9L5}do9axp;tK>{tv2Rp3jdsV@fzSRN7a_9hNE&314q~B#bW_StFFj! z^mg{_aa1JX-E79?sETJ(T)L+w=ICRzhvSY_X`?;{ZqNC!SU1iCEPm^5m|9XX%~AEg zIe)qMuNMQhF7sAm!l%~IGRyZj;eSH?W57Xvm8~Nyokv+`_#E}8SGm3pM~9$FGaUT_Z@X} zxo{=fKbM_cvy`gx!IVd}kqL53<+@a7sukZz@UX$)t!aEq;>8PryBt+pHf1;}B_}w# ziyR9$I{nHFM|-kokE0?9`>+|8qbhEsxU^}#@vJSkEbZaAV^w;`!tE(otQ(IhcpOzr zwv*%Ql=bTqt0^l8xjCM{J_`n7jnqusE9p|W)zj9Dh}vLbU#{8pGOsE zZ$Y#{znG(RNs^}>MQs-9nTw%3!{l<5h{w^3!G;t^IXUQzqg9O#N9SJ^bM(TiyTs9p z@fH1CcsakQ@0~|gegoyv&MU?oy_xC^v*ObP->(#NG=<+oyjVTZ=cw9J)o@gvA^?tV zEXM+lj<_bn(PP=O$5D}lC$Slqqbfd&;!@@EF-Om%JsfweN>5w3J?Fz>-FV>&9!J%Z zifN9j|IPX9#DC=|Wy;YJ*s#^}=uXCmF?v1jQ*-vj!(51`#MR*g*+!D;xVg1SBX zT!5Q5T&ryXoq+#!d-t&qZ7XPByPgIyZvw2_H->Tsi*5t<19&g>py(^Xv>xtKW-kV3CD-;;d zkZ7>%O$^P~z0KojDo(f_x7-RI6z>Pri}254XT={w6b^v+cTc=DL|ak&FHbxY;?t;I zq0G{@ql+n~c2!NBm8CV!vjKfbi+l}r;bAK=DCA&T*NDZG?z~br1C(upQpm$G9!CFFr`v9!1!yEBaHbZZ?mo@E4s4 zD@fkbkr2zk_;2rC^xB7)y_{B$#X)6G)I8Yx7C^5Me!RDNI+cUgOLtF70Bwhors791 zkzBl}(G_Qcs1YHQpugHXX0UPaKk+&!Ub=}Nzr;4EWq{K0!!rAqc=D3` z9>O;_%XzSdKfZwTVYK4l3VVCfV4T+_INcbWAo|EcUsR8^&{7IbUaP_`vu}=uT&um; zHqfH#77M9WaTz>nNiKWl_YkC?upUin-esA61yD$q+2@>*TIH4+NN-P4OIcv&$kN-B zoCS70f`%TKrJ5kk%>uhT{i)zIGzs2@L#72N1y;Ut$#%c8iHzO++hB(U_9ItkoXr9| z?`!U0f&G1amzSo*Y>uSrc!k-!r=EW|svl}lQ{sQ}+n>rJk z8A!XCbni8_OB0$?IR?TrNn3A1qw1x2Ewa#EXTk zOwDZ;*wvOznF);qAJ>{|&DB58NYR5NG;h;dP1ZAH|PHn|8+t`nVHaRW}KL{mGNN& zU&B#s$(_)M*qhK~6m>$Q;yq{|{ejlg6B@F96I4c>B<}jqYurRcMK7}9ga6FEx{2MvU9Y@9- z{ekLCwc@`BK5>VbqbWQXgLaFn?C5h;ZK-NFDyLX*wENaP7I5@&IG^HZJA3vxDw6OS zHsf+s#jjCZdU?B;qi@q5jyqPRsUr;Bp7UX`Zai^&kE3cy#WY9N|K|Kj;=gi~GUe!e zNOjWvALGOAd=2krOD;!6>~S=ss2o-CY}!XxZIk7w;_NMm#%vpNl;=lDo^}+~Av$L9 zGKLo-D993I3WjHFAb8vKxQHG=A zF)vSXbb0pdaa1JXN^HjEsEP+uT=JV{hL)vkE=P%Y936^mr_Q4+ynK%O3+$`!&e9`w|Iz`{Q*;n8GqK|D ze2Ra)_hWqK;bTxf7;1K65J7Gy2Jc$C-rX1Zc7KcA0O;C@0iSVcCk8w05l;-_{=^k` zVlWp+hMJ7>L(FaRwmw{-wlLpBR~*7!1$alkmKmNe7#P4iEVYfROzg6(w#_tlmxADs#8c(bSL(#F@MC`7Bu8rR{ zcyHtPJnYQ(X5#+D6*qpD9p=YR6{v6Gx98#6_=(rJ+wllLeu-^R%K)Y0hl$m-``~e! zynkuCyXCx5GwvRFjk@h0Ppl>Zl7k$JgF)ObvCtRQ{Fy3&_EMO-oJDl-xkzfrdQvitMH2Z zkxplNrN`0m@GYrn63M=#hSr;98*12p+LG!6$FuhuCUq;)09R$O(gXz^8 zXdxGrj)tn4UYYn86e-6;8Pls@tkzLB6@?*UUycVZzYc<)y!nJXy;}Pv|NbS7raLW? zesy{!;Y>}h)UEy(-Rw`VG?+_hN1|eEGQ=t`;b30u^oreh;qa$dpJEinWkHX7KLHsh8BDt?aQ(##{{vfyRf!*R!|w8>EhZqNC!SU0{1Sp3%Mm0D6UT^6YS z&H0Jqzm^4*X<0B2QY~F?G(OzI*Kj&pa?1h{du2gJQOg1q-%I;wvkBR21gH( zW5M*Qh@WDs@RtCVhPuyDk%UDy<8oBRgD5WTe}eI>Emx*J9CxfrRVNy_Jq3$(F$Nfv*GonOjy?f4q^4KAs`?zIB$-~VH__qf zC|o`bN2?y{5=SqWa9z#A^`=)UzgfcY?CB=REtS)#&QvRYhv2uLVer;8{vh$sz)pHZb5j!vK5C5|qlPvNgT9FL-8cxx?Qm2rshH-d`rn)%dnR+C9HmS-+6Jj!>;G$fn8VlbNw(y2 zRKy-fGm6Sl6~9FLXsffb995jX1<~uk&9$B`N#wMnXfH&^T#p@jH7RY05M0eX^S~J;*l zThsVr;>CM`ORh~lsVI?oaPeO`N||zW7NpA2>x>VR z`5I1TOD;!6>~S=ss2o-CU9^u5yCBO^#o1dBEq`Im(fipgW1t;HZ(68lE`}baj>}OV zhsV(yF3oWCbkMFdj_z?8Ow!9#|42{K{{gf6|Bsn9fgb!-jPP)L49Zn_Z>z&2Fi1hP-&Jw^roc+_dpx0V zCO!t`? zeyiS=jh}dp_yKa`m)Hii3{X0LSf+aJYP z`Om-(3sgH_?zryYr=U7%{dj-!+N z|442{YX5&74adKsWB31+Hw8t?8$!V@Q0;Pkyg=1rw1#Uqm>0W1#csTC_zP68%y0^V z8ED27t$RJ$rGnrob{Ia7zkWfW@;51uf_uyrt)=o^s`Hwn_=kcIxYyvVY5XhV#b<%L z1%cYKDN_(g@L3StZVG~B=4A?kJK3{W5QrqakIlFRfr=lYxODZM#8u)e2%Iun=%}gQ!F?-SB?cm>*H`9!(XYV_o(z{&mKob682>?E=N^7fa21$S;n)r zTr=(AxMNj1^C1Jbr(m&e-1}jVqiV@^(i~O)oAX2NXD*bZlqpBAfK)m9osy*R6JNvM z@z>+1h&_&G6qTbYuB0c?ZVzNRsyKVYP)rbHwyk&yTM!2_;ljM|32w+RBhRm;iz2B!O=AzG3U|o&t*7z7<=|ODw6O>Hsf+s z#V1o-TH$fySzGRO+QV_js+5~+;Pw)L)=Fb{-c+$49?SU5!^fa} zFVyVB;48@O#9-B@;)%f`-|la*`wqHxV(=5*+lj#qurm{@+15^6aVG}7pY|sPsz7}+ zF*pMX>E}L**Fo_+K<>mKvDIIzOHT}j=O6seOsq!iW%vJI@FrG!Khr_{erJ$^XuD_Q z_$`K&bVFCSunDT^ql{@ZQGnZP?lUf7_q9 z;>Pc~xBd930{t`b+i!k0e&TgdT>c$Deu-^R%K)Y0hl$nv=PH8DWdHwVId9aAdqrNO z^bq@QpD zG^u&l{eMtMCRWde-Tdd545Om%|I4pA7Svw%|It-=#p_6?v;VKh(QxZasc90)zNCiM zd&@S|F!Z%0+YO*Et^;EC-h4QK>D9RB8Ev!w&);9{V0u+4ku2Q{RlEPMK`tm#j)yX) zSA$=Or&lHwg=(=c#{(DBEB55gC*0}Pv_1%@b9=Q$)14Mczh?iR;Y>}h)UEy}zvxe| zG?+_hN1|eJbz@TXUwVid(?L62ACvY-ubyRiR1ogIcV@z*a4R6dLHXv7ERy4F(JMs@rvDE_$M zD|~41)-?Vc@#5vc-RYIuvMEy*ND@&NEc>o03nspnDGM%P&t6#|lJE*P%MPviKE?*XSjOdug_7H7buVVeP)8( zQn@tMnQFz0g7^5`;H_zV5b@#}z+H~2Et@hNm2)*XI^utZqs2Ef9Q{^;r(~QZE{G)j zk(qEgs^Y&WF0KEG@vJRZp`I5UtI}H*Zco8t-FVEW9!J%Z?W8%X{x|0z6aST?lqpA- z{m63kWgY{9_Xc0Xcj%(aQ4xC_%_u5IRs0FdYI?=1s?SkMlIhi-AVAE~QMh~>j#jINHN;$EvjZ*9LCS`LI|wegW7ykE$gV(;QX*oAWn_ z|H@Iyl%wB3s^`(N@nLPghU>E>m!l%~IGRyZj;eSI+D8X`ndPYB>@A4i2X4-zbV-t@ z9Ywn!I_5kYLtE1|m!m{Hj(!C;q|T$PGklKv)2p?F;!jqfgSO@L3*? z$5EBPE{D0#k0!`1mGi02R4e|z;QRe#@YXc`1@YoXz+H~2Et@hNm68)2{kI$o_y6C` zaP$uL>~T~i;XQ1|<*17POL6IpAB<;hxjD3lMT;%eGZ#bC=$gw>A|6LS1RGKu<>a6;{=B5 zF8uX5s`7^^kM{e+1i7X1QK~c5ia#Ovv40x8HI2VOyx8=Y&r!8yQ--4p8BK8XDmfPJ z|G%H%=p^>+aa1JXm2Af4sEQ|3TSJ1jsB?y(&FL{{XZ5{~wq& zf%gc7hvQ>VehcsIG7G)5%Pcegj+a@k@$IIH-Dl9X%Pe2xye z54~lo$_m6Iz0CJL4hqXHvw@lTO@Wovbi?6%-EGzs2@Lp}#18n*a$$#!)e+RgtGc37aAE^#&sROE683sj4R zmZjgJYWM#&yah$d@gT+m)%|&+h5dh{^^e$>;~|R$Dm!XA{JoL~-t!lhB#z$xzw~SN z{~6BI0+qVe|E@3mb~Kpo0+rK_MAI%%P3Xqa$^CyMH@!gBLnu{x13Gs9UwKndq+A09 z8I$<^lF8kT7QX*)v>L>|%)HnIDt6P!0@ddjKk>wB2AVNN>t3IBsUWzP9fmjIuU`vD=HH|+)y!a$=w`f&cHf0I|2|fyf6$?BT6a>qB zmMI9%V9#DbAd>LkY{o4JRD3DLrJEa#XKlIvqdgpVtV)OVH*k9j7VE|#OB=uS3o2^K zcG3lb`rn*CSNzw4fHExz-hxyoR{I+t4&rNgI9qZH0ug%!K}Jyv0u>)m`{?}0IO!Cv zinF&M+O(n4PORvXBu_hvzPAv58^S^p>6%**5b+9vnP5YzAmI4utROgSS%;$|aaJ-M z&3(}&j{Z)c!oPVq-o#4f)hF>Vn^rVIZmH}IfgGmdeFfj4WboEBK7e?!VxZ4awPjO= zqjHJ`M`z2iaQ`39rzZa&O7N77v&03FgrCxNm!m5Fj^fhg%NftwazD`?9CfTphb?d5 z_7p7Ejl)*(II5OxC(Tjyzd65J6LX;)rA#?`A*9ODxyFa5_!>UXmRydC*yCtMQ8}vO zH)$V@#8b%9MXTcMEr|Ly#~kJPQ6i@uMXy?@XD)``rH;!{9*4)#*T9C<0u?WYK1V4@ z7N{Nq0pj!MB3uCtN2h+(C610I>B7Cp7muSVZ=pOoV|5ecmdeAZ&QvRYq~MR04c?l@ zPbOYGX$_yFYRje!N9A%3jxL4grpbA9{MQ+dZpxm$^QcI|VQj|bsES8YTw1h>@vJSk zGwtEHV^w;7RRg!DV6kqTx|+vPwPZVKj;jC7`7_0T)L)=lc5RrXCkBU4WKYpQd$oC7GFhmS$|D5%+qK@oC0F?inE;rsu- z-QQxjB6RJcc8W@7d7zIOkAp*OMm3QcC>S7wlcX#To!{1(GX@_R9%u-mtc-`aR@ z<99XQ+xQ(YES^{mhN5G)iP+r$T^qlf@!rO7h2e4h;{L=HH+~;O$&H^XP~XJwKU-$w zCte4|{kQVtm)Hii3{X0Lm{^TpztVjF|9d%a)QtNT-RDE7f~Jm3X1Rve0wJnbmj8__XkK@82Ij$0P+IJ~mpU9cfl7JLu( zc2*V?MmijwiPM`YUHARDOB~%8EXsvL$tACJRrv_YqdGjmU23nE%28BjsudqCIG@!n zcxxKpmw53+;4VkimQ5Ls%DEaG9WTcMjuwB(aC8Os>~T~i;mT~r<*16+qPR3{l<}-B zw;t``xMNj%-@@%FSgae5$0O$*j;bZwNpn>F$9Jp6f8{7;%F*?AupI4Xd{~OFVaS$T zj*8ghXhu;vs^b2%kJ`|Bnxl%dH~jS8jxk4hew5^CN6}mh^~}Xk6J2vT%H!}j%HO0( zO|N)W^*KsOGQIj91c;|sqj32&9Ig7TOB}tPK7~_wI37n;e!CpzF1y7Xy_@Pxwc-y5 zUfw9EvcC1sQQoJFA@Khqm(H}`6O1IUX3?C9KzSI zl`Xj(6|u+BjG}T>#V67}8Z$b}QN`I?5WN80oJZ-BBu_hvHbr#Ic{GMjrE4xniFh1+ z9BfFPM_Fh19QCJHm3ufG{TWr7;pp_mUE=5;^eGI^!{K-wRe4X!qr$!>$Ssw9AdtgU zyr1IZ4Bnc?mnB}j47kftwPjO=qf&B$qhsV)a2`GAj|@jYlHe&BXNe0U2|s5hT#l;v z2Z~F>_BNii<$j?(IOGP=K>p zxE$qicpSa{AZXOg(7U2n*#wEJJsq^`jHBBh0+aMIRW-PQ<$`m8+5P{2%$h)7LgC@~ z7?gYCyJN4 z&^OC0D<7U+W)ZK0;){UXWvawBs9hNckX~jPp8w}MvrKi_es=#Kk#QbVdCU*h9AGgHmGHQ((%JG)uah_|Gy%~`m3g*N?xN^ zj)|A423MNkjK#qqZWkXLFH?=R&|V6SIL@p^Ev()g4M|9iRnOxMg#CXDsa5eAKs;O6 zWh$`1^Knqx)IvlEY|6jvfP^26W zVk}UtaFo%){=d;0BKGBY$YO!Yj+zb^s1E3kqjA2VB60Ng|D|8E|Icuy7O2#%{wvh^ z?PxIF1uCZnxg45Zx@t$XEjU0I-dnH`32;ICg0sQd%UqaG+^%;f(Qs`Hwn z_?Ln=ff{D=pTd76UYrNqEeO<>s-_^2;G-beN{$6Z>oVPBK&DGduQ>&QTC$yVL7@IO=WiGPwP>YG z3xYo&)q>y}A_ zjp&$(RSexr9k(DL;uQqgqaq2HW-~5FRlFj_r86%!p0(u$(H@RFR;96*7`QzJi*@6wmwFskOSY5dsQTZW zUlo`wS}9YGUI?jj^f$=p!(V(2E7+3DQ4xC_%_u5IRosjA(Y6<6IjT5&3!_d69Q{;| z1sol}REDF+vS*K@A_-4oGcHF}d=|x}N3SxTwdKyEJsfweN>^NMVEizo2a9#%!Pj^k zRZA+SIja6Q=l8xM;V5Ow(I+5Pj*c;%?8(<~99wcZDq@eL8Aau&iVvlI^soQRa#V5l z7DQWI8FQ2_N%FL#C_r?~c{GM5&^7lwO2p&n?_fjfJj%k$=cvCx^%)3|nOHq2Jw?qo z#1n(ry-XE541ve~KR)7z)u3i41|uQ26N7859rpiyyT8S5XXx6A!C1Vv6N8Eyq3=W2pyML_;)Hf4@*P)QUv0A(iitFFxPYe>G)w{Rey7( z`Tl<>=Z%_iwelM6IyIhHO#&nbc?k{%aeLK5`2N3zu25*l|Crg+!s^Lr$hCUWLfHSe zkXjYDpQZ!RPOPM#@J2MLdDs1aP)H_LYhIk%|DR4p-T$A-w*|G={eN^7UeOQfboT%C zI2xv|keViu>`Q8By~sAy(7e);?M_cSAa?IH>h$U+iME+ukD^lSG28P3%7O5N&z z*7E-JN`twCb|flxdi5a=LihiXV$@gO&#N7$;n?!lczR`sRZygSG8F9e>IJKX{eR_H z;cN{D^J1r0r=XiordJ2u?UV&Q`o?8J8{T$d|GyVc@?kCh`elL2m!>?r{C;y?YpEDsOj#gFL|JgN91F^ViFKK>;75s!UjJu_3nB@B zgWM|%R9wN6U=k{vF*;^0|x;HKhI20vv z+EH|+g?i><=v(TzWdV=FD+?AQDyg#Id$6~&vS5`59gfb#>CKd``_^}fqlYqe;RFWW zD_vE766I0;zcEKoqdLQ^_*sH4vUqD{3cr|maa^0vQMIM2;i#Oe!O@fCSisR@A;Zy~ z*t1ujvk9_r>0lDs`?zIB$-~l1_H!O0HbjEG#ssJ=n_YtrBC5Y zJRFasDxWWh+3)d~qwiClsaE`B!N0P2Yh?;wNW3^|uFp}mrK;hmT*Sc9zK`%&z|nR% zpIQRAhdp~76-oFYn{hd+;yDzT&Uh^5=##XE~S=ss2o-CG}=c)9?f!8arPEO{{e3H z|LKw>Pdke05FInUilIB`n#)ll9!Do4+o|&?>kOZx{`Bg85FqC0N2N2mAi5=U3Y z^gS1@j=w%fRlXkO(XCI#9Nn1eOts=e1;6QOgSS?u@Dap|g=c(@sx4IwN2TNhN2{MO z96f013`axu>~T~iVLh91IjZ6&ic9}{(sg)+_5ShKhMDJDOjuFZ_b|~{wqf*Q;vQHsd97?2>>5{cpM#oY^ONN$w6lvJr4wkIeN{2n4=?>=@Lil zxPlNi;IGe7l`ltmwD(IU$Ssuvsm{Yxd{w~@e%auyX?z{x#h$PD993I3WjH#D(FRAK zkYmAlwAZp3jxLtqx%H?>!hdM%a#Y1V*m`N17mR0Zxf%%QxMNjXVBz)@EY^+JzvyvP zE!j?*qw0Tiez|9v3*{(f%F&Y`RgS*JV}K9u@iqJ(J$E@OVvnO4Mdhf9zovb({Bv23 zD$d^U10%o0Hx!HWvZv& zvitwb$$6uuVg-4PetI`vrW(Aw3C;yL7{u+4_mcg83tg(v_yzGY)#hkOLTap*ecwRX z|F@7@72gKLE1F%V5{vL!G^u&l{eMtMmZ>froLVK4bBON$tEKM$V`OFa|J9d2QH+oi+W1C5fZA|1bTT{eOltwLqnA z^}l^1za0&xyFlf%Bhj=AR6X9o5zF`gkz7>&-U8K88je=zNI0&nHk2wTQa&CEc7bY5 z(ADn$E4vD3XgHV`yFj%9y6I$r>P?KFxFDE;W=zq#*NR;#2r6&jxuY6?{enQ{eJPLb z|28fNBC7M6qWA#8pZqQ^2vT^7c(LVszaUUss+xj8f{%ir{!3G|E>p@B1Yb#H+=4(P z;dhXG1%Zlxr?@oXo46qOoAz+ru_~>((7^3E9~SGz9{@W=t6EYqT@a}M&G{3>e=P_o z(}Lg`NVOn%-uUneU&A-ql3Ngn*eeJ!idqn;_(R%9M}L(q2oz^;_+tFmaX~bL~~5w9Q^gKVb?0*;T)3WEF(4o64gtYkQvTd7MN-H)UTTgVr0@~`qE zDUT-pYJ%KSc^uW5YQ;|${MO$L-kQeGCSDx*yU$UzWmATua*72OCskuxBHgB`%009LZ+fqE*FXDK0Jbv+=Agw-@cqpKJn*5GS6ge|!o6|u+BjG}T>#hcPT`X5@Cf#fWrD$d?; zQ|pg0M|pmf$Z1E>&OgOPYYYveYc5B593DppBHO72DqakIj#82=Q2hY{#OKjPxB?oE zP94-Gjy_JG!g)L#kE1GoSq}5uph`~!EtPLjovBv*9l;;X8N4-(e?q)Cp`uE|Xnt5t zZP}FJs9es$(H$0>^XT|hG8~=Go;{9=B%H}+T#l-E7R9B0f5#kcqdgpVtV*9+xIO2? zV%_+_KORTbl8R}Ls{i1q_^%wLOgXyRAC{x%8y_y=Yj_1)aycqukE0ny<*15pq3RTC|#1|X-Cl>f5jY)p<7_&ag>P1(G8L9)OnPJm(Njufoj=Gn51v4 z{!)61b^~U=|G%oKVjsgUD@citLHS##*@?k3+lyYbUO_6N5{j-ESZ!Ecr4LryZVfqa)QnqGUZazjsM>vL}NRM88=G`~Mc|qtJ1^ zs^aheqaoMoCktW!-$H6tJi51@SK$?FBc0CvzaB@!-Xl}fB$9ne4XwAXZK&a$QA@V_gH5;&h~0bZ>-6eLiMHAQ zC!;%ta z(R8Op(y!V7XE;;SD|M^?#@qYTD-Grn+L5T(=~cI$9HV%=+9^nJdV2MPhT|~knCaDI zWluqo@-I-Z)2kn?7WV&*Rv^SIGcR^}#cn#8UR_+MO3H#BgX6NG4R5=!|9=iU3@;=R zy|O^%S5h85+&?Z0uA@5s6%?N=_<2jmWkCv`LA>}KaJh1svOsOAYRUphBFciNdfr<~Hee@w(PnQLX zv$r7Hv7ySYw{j>-^0cF<%|bnMF?29pb4ynqhgTL9kAUf;^=4eDg2s;<8f5wKT{s9(j0SiG1ZxB#s3k!VY!&2DZIyY*cZpesJ&tA+m7^+tg7(oOw4Uau z;_NMmj#@V6D9?|QJnbm@)&1UPk5Z-_{RUFyXpQlqj;~<@TXH!nVvnO4Mdhf9 zm!o~O#|l}FD$d?;4-0U!Z$+0RdD>C5KB8mxR%2)&U2{1~#N+7AU_n?9*)ORmER|a`Rr;Y$Ssu*QJtw){1L&QT;1TUY5XbT z#f{27N7a^18IDTH368G5vf=1K8)i6q0ekj1Dw6P0Hsf+s#n)0?>b|P+tSxsF?cum% zRl32#?I~ES8wcaK9geCc+evd&{cp}s6aST?lqpAh4YC|P-1u-5U&G_slFLyMdmPOu zDo0g(2JNE@(0ckjsyKTKqF$@S9HmQ=Jnbkt&q6(OG4yY`=5myX$I+q4c8a5%9CXIf zyFh@Lqt|Q{b9BVUUE=7)w=rColVqc>BXsaAZN;Fqiub2NqDL%g`g zx;{tMma2xM&oi3f=$CRVIFI()B*W2T*|Wz{k%T9)8JD9fK8xbg7Hh>EJ&*Qq+_5TE zu5Dm^O~r%7x^XUGhofpq#WY9N|K|MGYcLneQOcB~lOfgf=uW1SF?y6kRtsK99!G1nRgP<#Bi%Eg{<}j-C$M zb;i*bK!D6L%Y)KWRJ~rj%rb6MvnDWyPBI-v-%b7V$bL4%yIOW=U*=+E)?G z^fJrv{P72xWvXirw)_8^dCOF9qRCABUdKUUx#g0L;`mL0mE?Ez8I0ddd<@F-p=RT^ z9^^KDeYcC3spk83pNiea(6#X!iuX2t@50W0|KHk)D{lO58R5rI73iOdU+ebS_=(qu z-$*}xiEU8J0Hx!H{r_(_Hp^7s43+anO~o*IjrtFbm#GGCVS>|*!NJ#5EQII(TWBeT zF4!VorrI10Nl1;=uwe$m{=bFPs`xh`o-OP$l~{!JXj1d8`~RSjEK?2NGqp-2=Mdfh zS4-Xh$H>a;|En(zb6QeOkmhEAs)^keoQ5XB+i=KMU_`@L~9 zyT7m`arE~8rC+oE&v2#|sMM|g2OQ|Pqrr3+sGN2rns$MzyctI)pZ|~KrWdFdYB>H6 zI(GkGc~elNya)<*foja=MhnmXH(GycIG7i^K*er4S)lq8<0mc%W}q2UwC**$O9jEH z90TE*OSG1PO%c#z4isDxZ{`IZ~Z%yM_!x>ySMFpyYs;NTdpPb`mB#FB;Pw;Hd~{Y2tTM*o=t!KE z3`cWYcZs75=u`L+569!E%D<7rym>DZE=N^7nBvj~2N=)Va_iC_ zjyqPRrN$e$Jq3$(F2S>$!vIjT5&3!-O$8;;T?NuG8Tow0w+(HL5muDKi~;&F5wvYk4Qvheab z>Mu|YJD8=%Pu&`(aPvOjU7R>TdWud1X7~R`m@0O=hZvuE_!yKAhMJui>bGd{VjI?&)AiK+f;q=^E_|xNav;QAq`jMD&l0QG)YCHIb+CF87hQGGD`|YlX)I8 zgeWtGNHqL4OEW4(k>*MN^;>)GefB>0>Z|YT?PITDuf6x$>$lcE_uY33@#?~$9X;#9 zphY)R7_8HBY>HhNyhu!TVWk+rFNMK*ccvExY_*qslt}jb>qwTq7>p(pFAVDDT>p?1 zR&DOo@BiyNh1E}_GJXB9NM5k-F0+1rkQ6WN%OLr=4S4m4e(#c;6jo-u+lZcJuivBh$JUP-z%T1pZ$SF`vDNfmq0b8{^b!)i|JS4`iZqW% z`uqP$ku7z0Z&O&kqDe|BIh#m!Va4P4^GK!IclG|CT!;&+L{9AM_m_cDz5jm!j|nBO z-v853{*z52C&@6tyFpS6R)84?@1_1 zIE)x{d36>!EpyTPf8iRVmIM2u%PS1?FXh!nIz^_uD%QlL1smw`KfM1hwH7D3H2rkb z0@Z&O`hx>Q1lQ>It-wzIB^3R9rmq<)bozZOmwplG$uowzX@QajtE2_IiIf)n%5$N# z;DMXd(tEhV1!;^bEl}M@ zARnAKC_ODubd2T&gNZI_0gfWCoEj)Ns7VD`hV(Od?6d&$aMFT?wA-6?Sa>IORsBQJAKdbg@zIfB$1*GWXr^B`%J^uE{uJoR zRYd2#md~gtS+I(aa;zpF{U6VTd^FiS%|}~dWG8jy9{*OTu~S#o-38sL$qyPIy&Ljm zxFwYeM+$jsmP=;oGA|R^@=+xT#<-6v`^)8AGd%K9^eG>mL%qsJFB2PTqxJFS1dfk# zx8tK}jLJta5}9HlM1p7sVPjeeH8O>d~_#y zL#(_4s=7Xko~XP!_hHLN8xwqrj}~qDpM3N!*yO*D={P>B`akDsb{#8=+&TM8uw$zg z{adDA`KZu)#OXhQo}5o~+eeiwREdu=h>?$W=DCoMZYASmR{(1;vg4!N<8Oo-+ecOR zc66uSA1#(`$a)>}WVj`jYBNU2TVrIFF7pMEEgw~q&=dDjWq-Mx*Vuj)N71KzwCp1? z%Ie8t!wj_kTxhc6D0e$Pn#QPnRCO|<^_KeU3?TK@#d+4f-bZ= z;-iN2JWR8F6coot-y&~_#ZlxLu8+FqRk6n`AN`rKH1W{|xBMp`yq7eJ`l#x^ z68*vNPsk#7&aMM?Y_+1_!1SM<6nc+1{btaUcRuC%sFH;$@lj4W$w%ArT*ybev`+KU z03$m-%02#RP-FY3>Q13MbDj!wdCqO<}N7~~)s^}Qa3oaXP zd=w_}=Ba^#HJVhAWk@GsnQR{g#qrU5Xt!fNisInkeDqUt0E6|D+87_L*Y-d8Xx@4( zR|)#*`l#wppg)*D#rSAhuw$7OJ<0UtQ;mO@J^qi7wS81||Bdd{?URg;7EzWbEU8ra$wJU&9<|@phs0--C&^k8-!;qiKxFM^*P{kPq&hknW?3 zj?w53j7&5>x*x-u@x5T9CKY5E(l_9-eH8O>eDr$S?U;`aA-DTCA3aPCkao=yVngWr zvZkABmJaRYPT&%d{JZI&^k)|7SzoijN`1}px|XB&|E}CTmb-@J^fk-%^sKL0ddx7_ zEM`15#lB`KoatV(CQknuY#M!%oCpRC{b=hN4Zt)}&R!Ck*d)+@vU#n+Fn zsrDdHs+ zsXG>#YpTwgq@WpwNmUtbV_y0Vu zy#L2?#xAIoS*Naj%+;e7)4rgx^zdrx3#!KRaXRt-pEfssL3M{(j@87Y-~TJWNhnHq zCo$*?s{YTI3o7xh1b?%d7h+%Z1r>(*mkX*hR$2+cA{tDR*0#6*r-a~F80`N=Kiz~t z_2+J&{@|~5f@qzyi&F<55JmTye!>Q!_lVO^1wFZp=nSk<{3}_gl7xU4A4x0Eg%X0( z??_7sK82x9(#k#lKA3JN1giTxbf?y=5z97Y;TsA8hL%*S|5_n$jgeWp%q28$DOy$HnaUIAwZu>2ntupD62P#4cpNAJE6%=2)Nrx2+|l;LZG_eg?zA{w8xWH zMaO7f(0R2<2w)O#o*F1Pkyb|vD?|DaJa$3=ijxq`Sf7><;C%dBLQsFB<)aNKDv6I~ zb@@*|+8j>jw}!ts#lPym9sR-9mt~PVXLkcTwp!79F#XV0q4$W>`-7f*dYkK`N*1cb zM>)ijk51*ekdJOA<737D6&Ts^QSR}th8o*PRd+pfr*7UXmTkyt40$r#l1iPuMaWxY zWR@;-l*pEkDoN;x`>3+NT#o-D_Con6`jn6Mq+XS@o+&n*gVsL}nrt8CZpTN{7?qEz z?&^>a&U-1{M-?5TdBJ|7OYx8R$eX7I3Z`r_K59rcVVdoun1|z|J!rRM7gPX4*GJJ4 zT~J-~ishq62?51N=XLu}KDrV%`Rgzp$46EFR-Wdr*JY7AXYT+zwp!8OWP0wKLhli$ z?*=`&hUj)2RkBbeKFV-TK01NtLOy!?ooPNg6(c)7%02!psIh%ibuUJDs?AQZY(v&_ zkSD_}sZ{0HguFFIX6Z726WQ`nB?&!oA652~k8Y2A6n)A^@1FlUGHQA3&l(`+9F#qrVMZ=}Uh zBwntMx))S;{12%|?EU{IJW?==X!`yCU6RG-($|*J`+xeU7w#oCT^RV(uM2~+yG&tl z)RjBNa;FflE(}hkXI&T!Avq}w)@eC5#V!o?6O;Y^Uon7R3WIuYr56TlwU=BVk; zB!B3Z8x3zVU-8u4yXuRXv2@5ynaWQTjW4c2^M3ajx%;z>59$x*qlM8WS_4$>t_y66% zsNVnMTl>6(l2`BlX(<26KD3?I`+qf$(p6`~$|N}Z@f6kUrxlf+HT(E-SH}%txsUs+ z@~Y%}SZyh<;L#b%tMf<$l~?VFRmv+_|AeB1<|tEn^{(ck_y1}u5>;3}GzXW;D}8n{ zmRGOVa^L@})wIhZ9#`J~V>x5xl``wp=a#wUm0HZ>=;2k-<<$-Er>3>81s${}c2FOTQ9a>zut8?DStk(Z6Q;fUkw#BToMT^yH^Rx6=Y83ssU9 z@Fr4P@HWqd(t-zir=iUXF9E}`%yscZXt|C5ha#@CJd)##_|qpJUM^an-0Gd_A1*s;}$el61vX?l;TvroAH_TzAMHWA z9V@SZs;-ZsCn~SDlLMIdR*eZh#YcYd_~=ZqW2+T? z9@Ag>QRqFgWAtU9CoBHs`lylxtN18`82M=KVa$bmbSoJjy8`HqksTl99{)b5v3*o^ z4?}mV>kr09AA&p?Zb_vMY4X-Am(0>-y3@R^II1MU823?Sf4Q7)Y`?k!K%er_b=0eT zw3*m&3tGP&G}%7N-Hwl@F)ANb-CZFcq>iNfsG?&uFL;vZQeMF%-aIu>a7>d5vJ9y^ zOta%CD2|V|q}`6iQREq}kGkd6BjfCU=<(bl#_h)Q=SX?XqN$LKKeFB zc6^k3{12eU_EFXS1-esFb(739fqODa|CHz9A$a>*=RW*3nyA61fIjQgmvzg$j> zpQAX6KINkus8{*u3u41swEm0GWcw(0J3gAmsC-m)zY6)F<}c|!s^}Qa3sw$wJs{bwa!JoVwwaA^b-v>LkTG2mZ`d?W>?-8ee33_sJksQZIl`K?=kCwtC`RD+i z3;Ae?L1{j^ka%1lC5IqEGo~`McmaU$fND$#Jf!6a)C>n&k*F#NYq3)%44)xjD`?OC;+RmLa3!*DQ5&&c2`o zEf0PF|LmUn{r?c>nyOM>hV{#*Nzrx7exk|x%_1q@-;N;pOX#0ocmh4^^}CCn_4?IF znDzV6mHU$A?jc^ietqd#uiqaer{Di;IX1;!zn21c{S*W2ll2=_I(_}vYA<Me-O;S?Hn!bt_`kIO*{2NH6+IRK-pInHqsSZ3FyCvcnqTc^2 zN%j7pPFC9ce`QPQLu+Fy;O25cbu%6lmZI@wt$*P|h6}2bNCRC^omP;eFQ{bY6N(a=LrfP`uW2rN|F1S75wLt{jx1eJ=~I*Og6gTo z?!^+Xqx1fs$Cda0SkBl5l``wpC)T)n)MDBfRF)oIO?^Q%pg2w^-v86)#xJPKspa^B zc;tdgTq>a`VTu^^1=Y+F!bQLTue>X9fm#mii@u=3F#mEvb>gWxQPR4I)JW3W_QC&@ z5Ujv}{%ZQ^CIqT~Gx~$wXPSiI6|e(S6#X@(f0Z-|L5%($=*b7EEVh$YB@0$b2zc=+ zA!xvJp@iV{k!cCRB#i7Nt=!{JhZ;K}P~8jAotk#KShgW+3FOIeODfg+3?Xlgky*M- zX_~i{5GYCLi6;cg{&G1h*nX7|pidCc=e^d50~4bYPf zD!M+ZWT8rYltV1}Xb+wX`RHacK34qy#*3$%aW$L3J^tU+@A#)@>T6Bj8Y8oGndd7wKB^?4C+?%l{&G3{*nZ`s=uuXDsOtV6^1<(h&HjsQEB zSb1*`Zd!#VkAy-Ju1`RMJV(|oiAMt0&T_xNp~#*U+^ z`wn!cazf*ycS4>Fx1>_-W?taH`PxS> z5gTfu^{;^@+ef+E@zFF!<)f;*KIDThNPFBz6&<5_!Q{%uM`03go*F1nT) zIX()CZ(YSm{*YrCq|rYF%{yaNBKejER*`t4i!Uw0hkrc3fe z(7H9?=FU#s+;tx}-N$m%b2c~kY~`lc0d9I1*#o(I%W>1MHaGp-aWh~LHxG>EX5ch# z2Ce31@OEy7e9X9&j__JZ?r_#?3>GxOun>H;>HcX7o00#(cufqerywwKf%AIG*6+K`rJ8armr{) z&5SAB%p6145$$Tus$CA9b53J{xfQsXSB;zbS8%i7dTtip%*~=(xmnzmn}Jh1UzbO-?se{5{{fmS>hj)RaqV9I*L7K+ zqVxJBH#c0$&5f_yv9w#Z@Fny^fQPzKAW2+b-B5@BR5SS;HKFm zZkn&+ro}F9T7Ab&>%7k)-X_IO+gfO@y6cLHXzt!y2~Br4_o|+^Fzucm-1Hj3P47wE z^x4SGy}P;T`y)5~PW}So_l4Z_zmc2!7jrYM6>dh==jP$NxOrq8H>2lqGiD_>W4Ceh=pJq!JIu}F z|8VofY5Sq<$y(ezbu%|l-_6a02e_Fso||bixtXz&o0+e1GxsZQ=KaOZ{6hLed+n}z zCWWR>m)hKPZOKiyp4{9yikrJ;a&z|@Zo2Q{rpEzpdU{_${GKx0^s2^9@0+;ka~n7J z;*a&UyY|YbxvBjuH&<=p=IVXiT=OS4bxM5=&bpPjx%L`vu4~QB^}V^dVKg^4&f(^! z_1x5ZhnxBbxoMDn09qO*xoLDEH;wCa)8uw;ZXS%LexE0~xtE=&e&7B4uYPQ2{rlL@ z>h~Y@4LI+g!_9yfxq0AIZU+9%&7gAMf@SdK+ze^W&CvU~8TJ@A!b!CbbW3n zbmnH_NNy(0H20vgBci_n^uTC` z-6YyS$2)i;k!lwF{e(jbTM#SXt#v3C3?Ha4ztrV%w%~z5Io`m*WK->e`HsC_xZ`QM z=mV*JvEXTHnXOL2V$G&(Xf|<3jyHS`*>HWqOSEQ~8GYbV**9)zjyGl)si+?f%&Xxg zpQP^V&M4xQYHBTpk6C!h@xxVmQ>u+k!{T^_IXA0MgB8NO&t}l>mCtF^2%AK|V>9h3 zP9aNHCt8uS^Mips%^ll5BC%=xm1+0fWA50B5jT?tDbgLi%pF^QO%kcrz0Dol3{6r} z$;N%e=wI`rar{wibeksG9^bLSXxy<;-rKPW<-Ph7Rba?)VRa@OleObqu9RyuSewDB z*2=13-HlbUObJB^+gnx*?qRHw6-)F`R^4t{g^?VqvMj60=QM8)t45SK`HmJj-W4QQ zYIF%Yg(vr*fBpa?$Iw6X!!Z-Gy!WS(D?VJJ^iy|}+dW!>x1u=)^daYi+eGMgt)HgZdWz^569nDEyd8=qBk*>jC&uY36`zDAU&MEWuZE|5^Z$ZEvY z^4sOQx>hbs082fx$4fnYM~*jrHtDz~cZf|026xW!QaG^-_4wJ*6xaZN)s-~qU_cjP zTyk8-Q)+{;Usv+|xuo#}Z9_JzP?iKey9s$uM24V{yWW}OO_@j1pJ_uK>A`mid0#}1 zr0qRw-U@qEv}j?S<`N{Z1qc#hs)on)bE({-Z9z*#DT53 z4qFrA5VDWGk=i>n==kCGAs)2fiCvltm(S z?}JFYq9#&?RR{{0-X7My%JjAoU8Y>OcDCYb3$6zDV-B>GY4J8}W-Vohqhko1#uAWX zb~P%hCtzv~hEXpIkV-gOX@Z5L7fj8FqrGWwvi$q#C;bhV7Y&XML^u7Hu;>nsazBZ@ zWNftuaNZ|64_q^ufsG?zUEF6V-f}<}@ z6de7MHi+VD$pI82fupt78XT=eUA!CZ)Y4tD&fsWcO}b5yE?jSLbh9RjRMiazN59r2 zC6%nQ(Zx}g@Vm3ol{yNJ!f3(Kw)#CY7k3i zlqkdU;fd5}9K}cuV!1dvVVZ@bur`BLS1GG5Ty3n9WlAVYc&%mCC2NdTvSNv5%Bq_z zt1yydm5ZbAOt*0KY?8BZ^b#1UaP(bz%!H$tV?ZBrKDgPQ(rZ!H4- zhW~C0+KSJ~2yIUl;N(oEpI-3hF#~Ng&`tj(EV=`2+)p2*`Nu$8OhiH3D_(9|i8vR! zyld8MnX}-^NB%2+r&={h{%i* zm$7_Ul^P9g7|8(<7ux!MYC#*U&0tk0Wz~1T8mnZP5{eRbv8?+3H)EBoSfZb@>Tb&_ zjO1A5LfeYZENH7sau&3mJkLPeGJ4DeZMR}TA96mpy<{me-7XOoLo3k23G~xI+ZzVj zwtS9=LD2U47Y5qEig<|0$~(OY9oj&i~$l zHXaOeYQ)ruhYhsB1lZG*?D0|ui6AB79Geh)dBi}QjGrA%fejF7`|<|^ZO3C&(Dvm~ z18ri1fD>C1?ETR|n;|neDe`AO8E6wj9qHeHHqd6sk#yn4Xpa``m8f2?t%f!tGPLcr zqI%t&pXa>!tIMAXd7~)fwq2{O%2p+*i9Lr zP3*hBo`E(qu$pzUZ+#cq)FOe)OZINyLYtytaV%(qc>-+%Ps1kB?dKG#{{d}Pi3Vt! zcX_Vbq;U1p zGfMo!^5M_aXlTPo4v4tWR=-?sbo&WwGgwuDmnpUAQe%}YQ$kU~^NB%Q^~`0)Dp|3_ zWh@_7rAAwYksPaBXd8VNtdiT$VkBol+hG`~s1YR#-JxecV~ye)3=#S&f)FLS+81bFEyM0DDT4Jznb7YPlNP2HAw* z#p=2G_ETn%9Zi7^5NKOhLl~E6L(>=)w5__3e19%o*?pjG5O88kf@K#8c~3-Ua8l$2 z7w78RPchVyezB&I_vIRLBwe^M+M}W6C93aguc3{I9Mx-EQJvmAoCiign+T^t+xIrK zHLL`7f;Jo;1#KcH(DpoSR|IW0RR%jjTkR^j`u1}oabRmoVQWI@aiL9XjzQZ=A*phq zZ7ykIXu~8K+VBuTTm8Bi-G(+CE?$Hl)*_TIx~#bcZJVFV2yIi#;N;ArpY$g+9x%{0 zAKmm{!lFCS#{Kjih64?>#Y7aeEgO^$ZHu9sz6E)(fwuPv%6K$I3cp<$LEG!Y4YbAB zf=wd~w5@dP^}^XJB52$2pnb4YU>$_Y*TM428+DhMNplt(@czs5xrOWGYplz=vja8&yi6kGM zZ$gS}sju%h&~~3DDXHY{0WP%hIQ|4Sy5l5)HW)3?*7_C;+Q5(jM5?essgA7;h{!Y& ziV{{Q1`Q$?wJ{(fGfG^|@?lMCG>Bj%2Si+GE8fXDoUZ98G4g0|bA&kSw1V?ZBrKDfPP^Lt%r zQw%4PxEI!^p9b1a$kG>*t=l1D5VUn}Z=emV0w2`!iwv*{NYG|u` zhk>><4gQm?<{Dzx(6;F=2ikZr$f*%ilkYar1`}XUYqG~n-QC?lTPvFo+}guHn~a|w zO@R#%XlvHfK-=*c6|~j6$3UCdAmGH71hsn^XftF6Cq=H&+d!Kb>PXk^W1!8DBk978 z(H>peL85xo+cdNhk)!%_E2`JcDSJB@0c|3j25lt;tN6uUc4x2?wBhh5XcIYswnu5Z zB53=k3)l(Te(GwVtv7LCYno$gLg;a!O>2%p+vaYh%7wPUq=}&olVoVaLj-M448iC& zwCPA0zF{pw`Jzo8x1eq6>Wt9VDv6VGEB*9>yVe+J>x6FlFJaLgXybk_XusA#TTDbj zTa$I^(AEXIy`au|18vJ!Nf1_~aNC9m+IqZXpe@E0blPN~t(Rl37Y+XU+3-KeXUZqW+{+BRy^jfymRrGd7}G>9$r$SMPEH*1oTN)A}@=qXpWIJ!L@~7&3s!!85VVshkN0L}VHXMG21(gNC*bHCL~EnNi{&mJffX zMnfA$azMm|wxts-XoIyGtg67vl-jx6SS8DpP?Yd|V$fD?Sz(|}RxEKD%ZF8|(N{E;F>9g#mrY`QY}Fzdz?fn_~DDwD4R~VxXNBY1r18s&JNf&O6_UIGZ8jk9_J8NhoB179> zR#dN>^Wsb}0@_444ce;M&^CWI*a_NjcoejWoIqPw+O7!NX3qsXLED6R2HF}B2ezgZ z79@lo7uvMu7_{9spH#Wfb_;1@Xu~8K+VBuT+eI5Nx(#hQQihc-l3J86B%gf4g0_Ay zW`wq>XXE6|qM!72RX-YNn~!e#FJaLgXybk_nEjK1wwQ>5wkLm1hqlGg?FA!$G0-+< zqXc0^3TM6?LEG{_47A1Af_Z-$Xj|#n>xC^hMbI|uF9U7sG@BZz+4R3NK%3Y%{+NL_ zGq9R@9-N# zGY0pno+ex1oXiL-J-^glyCw2{O^Y%H=#)CmljhGs|-#{BofIY3r z9xv78O9O2u+JxYmuMD)w_*Av&DX;+oZI^y+sEz(AYWpzAJJ5|sbOK${^m zII*EYnQslWiJ^{k#e)Xg3^|f6+!*cAnY$&bx4Bb88xa}WZn2_z-5l>@Fap{{I1Snw z*wA)>HjJSShetu1$O*L7pUeT<|Ky1n53s(JcjB%QZP5LTpcz|IKT zW?z`6KSmN`3!bc zUA!CLr+Ddp)}#aZy*24aMcP{_PhUvx(SLDp|3_er44j%PNfI zSmi=nXCGF{yS5c1XF*$Q7^$G`7kXs;i2bI)YZ%anoDXg<*{DLE^R7)X%mgj`lztj$ zyW2op|H3?q7zAw(o|LEGwSkpfz+Vl`7~Bi{?y#VZq&2k7qkau-*OwLzC34d=_~l=P znsIO z33*?xAxF}M8>2mHRtkGWQC)vIH4_=y)>u)!Zq7vk7y)e}oCa;(ZD=c72JBR|;qWME z6FGslGbz|c&=!;hJ3(8C)AIDYwxYy=t=WLBiM|Qk{HB4{9D}y^Nka_UeA2|whDkEC z;UR*yuGKKQ4Q)D7hF@EYP(G*OO~hF7k!QmZ`g4f?<2Q9moIu+i1o-n)ykyjIm7 z%JJ&A??Zw$meVis5f!8w?MLzRx-03|66)p*zJ)An(K4&yYb)MIv4J=d| zAf(i=yw8GV-n=u<8+w<^c|HA7NBu#)Xh0v2ei8bG3a?Do_B^QFIPFE#JHLbeD7E!$v0_Md!3i z`QA02iqVNj(b>FNzE`xl%ejLtF+?XGMd#!m`ChA@ zF6W&KjZQp@&c%a>bFj;azn3gJ@hCbEPt5n0PI5W%=cQ!d@hCb^o}cf%ME~0>kMCd> zop=` zq zS>)`}rQhsFUjSdGB!`n1I|6xYbs&7Kh93*wA#`iLk2uagoqo&o^pg0+s;nYDN164s zB#D<WTEs^@b~MuOtd60{@!y3TvP)%>Wk`r78JyYIWRkBC36hCLFx3nCXwrfF zLz=Wqk#-VEUTwD|MYdFu)__Sz^9N~?l1la?5`wS(UN|1dUrQ>z!kTYosZ0{HK_*!m zCYO4Jf4h~b1MkmMa~(<#%0|CYCtCZ_^aIf~yQh`nL0^UxuN~W;y1KVX@nqHsMG0>q z2Az1$(OkXs0wlV!e0Uo*I`PCv*pN)$$#(e*{b>>%qe)z!EaEj*W3lo0ed5k+H)Z+X zktTeiZur}1^Mg}*nZ2n_UA)RSu>nCNO*)X@N|PEX(ikGi-t5pMk$P2=j^-cMBqf#1 zp}E?7!xBDL!(*4@EFUf>S^f+%+WbB-d@{pgpU4KK-XvDO1nQYD(?}>vcrr2Q#Xj*K zlTXWx5@)k~ScV$C*xLIuEjGD8V^U(Qg0&f}s;sPfM32`qUzRDMC}B0rs{d)OUV6n6 zS1GG5wyeTPjtkgXe%+j$K6EbewRrGt+TiR{mr-OXH3V*v7_ZD3bgxYR>3lg+LJ6PN z<_ySBy{Wk->cf?osmz(8&3Pc71Hy64$s&Kdmd%O%shr-dCTK%6`3}u5_36D2B>xBc zrx#-Vxrq2ZH@t?D3EsUwbAvHj?u5M4-xXI?a_7-My>J-m(BGjsMw|LqZm^N$J2cDDvc$iGlt=fH4T)s`sh3FBE8N~xVN~6mMdgao4$=3H zA`at>hUdRWmju_+;VqKqd7bJH$n!?h|E0#AfM4Aud_#jZt^pjQ?lW(rlhWy*;dx$7 zio&I)WagWq_{!&e^dMX!wg>O^tq(zasMxsuF0FoBv z1fj!S+wy2=Es9(=5_LueNsFpc?|CoJYeE^XN=uO3MxxHBAZbxG>VYG9-ku+{D6-v1 z)EN~dEviPn%FFl8pqyBZiu5-Ubw&kAi>gttEt~Jvpd?v|A|H-Kol!y3qH5II74yB) zlr<|+B*>AdGb%`0RE@f*PQLd9rO`?h8FM7+j0%z#RiplXbH4XhQ!R=VIudn81xbsl zQ9E_d_v%ritwu#o9f>-lf}};&s0{|@dnwAil_-+zNYoh>BrU2&T{9uyn? zi8`Z#q(#-J>*nTrkImDfNW&vhXH<~1s2X+PrhKmxCF^QbqJ0Jf2^wSIe*q5*Gfd``-5N6SxdtmPOf<^m9q;f$_MBM|o z{4!tP1KkxjJkL?I;f@dzYx-a`~jMD zha&AHl4OVnHA$pK>=n|{{6ZR^6)LIZm9+DAhR70rPd57PtK}XTMoWg+e0zSBi-93S zE|$jzrLKQ9UuTFijfA3vC5S<1h+k>0UV27}vMe7KQlm3OjN~Lg?mh5>JMyD@U|5^M zs%w;0Z+~j6l4VLLN_f3x)svqIS1-L{i5AML`j%A~$+61L5XhZIqDX;-@4_s%D zFfKVRqq+yq`G|afE@}KAS8R}*T(%^5S(EofWWLE&w91^)RAuUiIDf@8ge9E zXzkIJZ(xt;3e*G%5cwWBadGs)mAW~v?*b#;18d>*W_58nf8 zIk^X}K*2V;2fplGu+u$o+4u7GJ#Y!)z}AG=nh<)}$ILyj)*QPBUO^gS_rRq|6W;@4 zl6()0hv*(S_bZ6dH_qrq2xp3QCEMe>WDYW&zHvs=)typU^&0ydXC66#IoM07<84^i zS<35v0ONt&!hdL#=`UIlI-I>%R)yYC*Ufq2C>ZGgeNPW^fGT{UR%IFv(3SKLFMN%J zcxmV>n;yJBIzWF=zdk^Fe=-LsO@rT^)tt94IzX5I>Kq^*403A3)M_HjFD=0Y?9wxQ zfGYiF4p4QQ5NsrZ93UA#+c#5S1LOeF@7gQICAr6AgeQB!cf=?MNNkWJz?KBV{t)t> zTtns~pvb|W<^YMIj`R*q-j{30k#r$e8TVu1`?O{Q{-Q6pr>{hy-%I*YJYW>voFg_f zBOj(djt2~--QdHd6~zzJL^_0gI`}ZP`WftWm|oC_Nz2J$>O*Ekhv_F~r^9r~FXk|{ zA`WcRY(7lT;~plhId+()lZMz~x}7xfVZtQ&FySFOOfCP0vHuk1x$`36)Sv>EQ?pvn zEemVb_aBU~Klj>&RQ~pRCd*6m(*yM6x6FasBvJj7C(`{!E4u2Wf6#pgzLDv1k~Ded zalYAbIZZdqUxi5rQ?iQbJaav|>A!?Uck)c`r_aL`5s}ITF%gw#_Q)=#^UU|YvDf`(!%I&PwmJp>(`?Fy zW>rcSOV2aKzS1Wa(|M*DSj{?_>lbtKOtnbh@{&IjjZ-%HWD${$%TC%9Oovt(KRcQN8z77wet3vCkCyNKHy-q?a7&)}Q?Rda> zv>WPuwJ3^*)?M_Cdho1L99l~zz)qocGU-+Ct3^&i>;Gu$n4P~FZx*vtXx&Q>t!I&z zkFsAN4s6q>*rpJA+|a5u$3kmM@`G4t-9(x=v|^GRTJgZgfL;jK%~^E@jHS?uxpQcR zcUz(Lu$~)-)-1k)Bz9a9GrPWvltcC=U8M5dh`oH#Q_m_E#nY1xW~|%$zJqu=fPT_n z&%4&d(;?`l{}LA6iKpC8UwCkxiKj6U6;JD5Z{lgSBN8+pgl;c*_eK*>D}3va!lA^< zOHOtBNexXrjj;vA8<}|em}9RO{&*;=+e?9Y6eYaDvg)eZ#wuB{L`!8=1IsFm zN5ZjXgtyjcFSEFIml# z#J-8dfsKV1I@rjAK~9aBI!0tEJ75CrxsdGfQu{A5*tp0h1P3lQ*eK&?M^j(}1RIam zG}w4NMum-kU1G3NY!Gx~OM>jn3^p1vqnjcZTyC&Y40WWdTw$=$kRxe(kDjW8J)(@r z1PN>b<6%}!0k~Y$u1{A1Bh~GCgX4JEZ8QBBcIUaB=?FJtvttft&E~Z1sr-PHrJ8l6x9j5jAFljkCOy`ps z(P8?X+37G{+S(kZLgK(S&EdlYJ?>%Bnq!CQAZdslrqf9iA0|wa4-+1u!<4!m#!|Kj z8#!BqcU#G2b3HfC7Qeg0$`+6FeaI`wX!^)6Ob>qPVzR{z=%)V?7Tw7fx!(&8bT!#x zOhjdiyStfe@#dd-nX(d_q1y|#-fgnQW8dA3SPA`)!#@K>wy-l|Gnq#l~ zeaJ8MG1=lS&8BQkeaJd4-r1< z9FNic!AJpeH;uvpQcHvbezgPSSNDUF0^}6~On~%$QJ%hsX5*Kpe|X_s64C*3;ImPH ze24mVfV^;^36N8>Kxp=S>AbBvzsS#7PhL`{e6L9kOV|7zIi6GT?37Zh~ z8EOKgjGyhBDX;+&AkP_Q0_5=+Re*e#7^V6a8zjWBCBe|)CO{f8hd4#9GQtE%G1QU% zO_TTK8ge9Eh*jnQxs29q%Y!;V?x1aA4;a-#s&6oIfZXVK!0rdYNZE!~6c3Q&me>Ju zD{USJ$gZT9vkfgL0kS@s5e3K=gTPJ!aw0uQ^<9lPuuY#~n?mSu1Ekg*3y`OfAH)J= zEz+beHc5%P*rbOjK&}{x(J4T}Mh=khZYw}8({tkhxo?yeAUph#v7B!6E&^l+`soFm zmY4u}2f7g;ExHpRxt~OqngAISQ33MBWhOul{YRqUozU$C^;Vbw+4pyc6z(Ec9U#ZA zG66Ei7K~qQ0_44pytTFPmb@LRCaXWcI4G>n#VIyJ^B zr@@e+aQ&W+1AU3b&%`Ppl$2>C6eawT7<4(kZ>%X?Wk!i2JfZM6;?m_bMsf;Q_ci$2 zk6Pt4tj%CmMb?_?GT&Gw%al-*FeC6 zIjfxR1|!vL@SMLhm(%4jpbt48++K3vJhz-y49h?ZzoVaga8OQfGUfD&afllPb|c3d zumdZ(fL{pB7~BgVJQjf+q;)m$0`+UKYw)xIyEF}c4OX*{*f&w8hI0DvDGu22V31QI zrhb@ezz!zBp0Z?*m-=*?0lVMDP$mT5OgCUB<7Y=xU;_l~{+MCF?s$v}?26AaU?(;R zT&V%e%r;b z&<=Be44IFBBHyvo93U~&k-qaabASvvk}kw5bGG;ity$04b+-6DZ4-Myl0M+di4qw3 zFx}{Qz~7s|NQX%)iXWzn>5%d1;Bxw$Enug^R8$`(EhmR*0GSaTrq#?&hv_$ZkZiF% zabTMs=EDR%?qSlJV~6RvmuY18Fx^F(_%LCTe3!Svv_T_#(cjc)ocVbPszk^8;i>$gm{7!y(1;=6B~Y;kr` zUZ$+XGtf<61p1!I7UyO=r0@q~bI1fpLyn{i zvC14EkI|Y9{!RzTXK0()1Kzqrm(#?^0dj%k0ju_d5#_WfiU-JXZ`c8H25lY($Q7hl zmD3_80dgvt5e3LrO(FES0a9y@1<3E9$_sJ_?t-bcT8J5_Ily?;zi8gF)fl5wmJpvHJh@bS$?^K^iTVUeMQeI(4Y1( z1FKmli=JKJeA-7X61co%&N&56fK)Urj#pT+oopM-lXCisqf$=aUQmSJPXEbmeh~Nt z`t9^$>f+s~qL%LTLLnW5g{w>>p(x>p#Gnh;X+N97Rc4ep z!1Cdz)ab$$BRPeuTTVaxi&aj;+6-3tyiBRzPAJetzARHhQNmM*L0gq~qHy)nE0#Ei z<-=2{(NY$UR`L%2S7^rI^tB)-L|_MLT~24y$<^g_kz)qz z(lq$PSxq%!-!xN|(~GkU>`!j-V31QIrluAx&~K+<0_@46`Fg35IRzT*uD1!nqqzn8 z<(iD29Zi7^5U`t?CyYySkH@IMZc#q@zWP+T*dTDlmINz{33*ShAv0Vl@}`0U4R&Iv zBYmK_koV;pawKiL1QTFSA3i{-%H{w)Y!ia~D&_#m z_}S4E*Z`d^YQ`nn&@@JMfOd!G0ErE91lW>b;|1mb88ROMMV?*N93U~&k)B)493VrE zqzkdioGqSzQW0-{^#b|mW8Dhk0YCQB~xsw(Su}*%ZLNp)C1cTLXUfxwC31h$|66A9j5i9 zi4PMd$%hFK(P3&|1EZsyrnzyp2=BJC#pZf$oGq5Ws37_*<8l7((;zZB%O4KYgK9NR zwm1si^k2fFJJ}-ld%@|Km~1g7qO!%@OHH=;Ln&USti)L8_JYHgn{4q%+G-w6k;2+1 zN7>>(SD9=v#uj{gwaFGIIQF`K_vw>sOtv^xv#Eiay;UbewkYzNnNT@>m{y1bq$Y*|&7Sw1%js_}1Dyh-rb~dF z_>dhScV7X|pa7}43iS}-ZO-u+c|8~@K=!3kI6!KNuuQ@Zko#`{BL&FIZ!`gNI?2G( z=hJNbRrC*f%SA%$?sVTc@K6*W@1cGjAgk3g0WwX4|0S!LN$fg6&S>BSNFEGwYQ$8f zh9*G51laQ&RyXw=5u}`6WD|m$8<_wp<7Y=xU;`vT{-qh0uB>hK=vZNs+<-%36KZ1+wf<@8`cLq1<3LAAOUh0 zabTMkW1B+gaRa2*91Dv4KU$=6K}g)q*^3!dC3fNU0ga0uIpj|ZaHyaYxZJmLg;Y;PHT<k<@1+2ZoSpi{P}>5?rzLN+lMzn#8sDCS@fJET`<-hpw|_i`Hd(P`1|P}Uf7d_^Z`2O zpD0_LLH+swb$HAipfnABsWYMGO=8yvsLtcg0ph_Rr$$T_f5IFfn1Efn1yMWo8WE*?smIO^Em;+?Ud;}D^ z`b2Yp#85}N>Lhc33^|f6#42;PIG`MT`_^QgEgqq5Vh=cvzLJO&B`~rFBrmfsRI+I| zR5>k*;)m&CIxKuT_%NL_4(wD;pP&zuHb4$j88U;}Ia^%I>~xs^qzB0skJ090o0?&p zLg;Z1lhzzNOwW#|k=?^oKx6S?!X)`H;en3<|0dxojhO1W(gaADfRpz$RyTEo2ofNF7ekp4Ji5vRNEtsnngSaj z0kYa^6CjVrr~>5s#3&c`VuOS@HDJFrCO{f8hd4zpz19RsG1QTMUz7Lc8ge9Eh*jnQ zIW<+pdvcu)kf$sc57<9im(#?^0dkPz0q4?gsB&5q#RKHH6YKz4?0K+LfLu>{RXHtk z5+E-nGok=Fo!KcseohY(AkQQYY}0sbQwTk7fYh2}0kSdqK`cO4B2641F-Z=Pc!&bz z$n`K5xE&(sGM$c$OOpqHJh@bS;Ox#1W2*(>hDc}Gy|(yCoehd21vC?;PR4HkGKI+(XcpP zVd4%6kT4IvOCR=b`;wH?+2^TpdJ?z!!HXZ8a{319;@$XzT#S}({U@fJ?x9KlDAL+b zO*#FUCW+MQ&rCU;L*uhTC6!$Dxfm_wG)wr!*yvlQN;wUqrJT;&Y?aes$WXY>WP?(> ziB&%AEz?LSN;r=gbUD3liz!@XMu`_#K3qhNE?hAZ-2OPfJ3Z}XtDJ_l8LawPS+#tR zu}YRHp(x=OmQ|}iGFHioC5|YozOt;sNRCx*IX!QyRZhQ1a#lIr0!FI0(?{tsQ#t(s z2J|84gWF5K{h?b>~C}0(LL%a=?xUgPa;MHUBLGb}#|3_9BXses%hX7rsP7yfpZ* z_nFZF`kwmr0ebf*bAZw`_#Iiz=@&!?Xvwe60ph_Rr$$Wm_{|(3n1BOR8&Nw|@pp58 zD%gY|`ww$~Wc+O3Oo0uM1GHB&F3CL}qdGvF|1<|kY>*?smITxOG6%?z`3NX-|G&)v z5(4SiR*jd5{$w_E zd%?5$#r0Jy6V&oai?f@vj->(4TFa_se-zi&PIL}9B_&_%N; z8=Bqk7f=5zquAH3u( zDL_7(OM8j{sfpoAnmzA1m(%m}K&Jqy=@KBXdd3crb@kOR+;0_2GoMgek5 zAR0>KrfKkpvzl7OzDY8S@~0NJKmW#qK~9aBdX~uY?JO_>_B?>qO`Tu1xGtx!w+X>c zBFL9Z$oSdO6xaX>kljxcM*94l(vZfe0^~`j(B@G6%?mv}U`ASABC?=YospQg)ck&^)VFqshr$UV$X0rIpm#dUz}P8`^#e%PiE zdfWi1HOB(vSke#+koS`&4v?562S_|b0dh+c#-f}i8#zG2yR87ZOwWx2Z`0n!YtW}UpZsT&~GB7w_G-rdX%kcx)I@d_t*l>iCzq@12~4mOG2PB*Ek%IO2# z<_CXVRa}4Adm?r5>^{e~c)_n%3+X`qi<?#as6TMDl~{K^K*zw|Mk+8rEj8YKyY!yDN=VvP=m@3AbBT{a9PL zdg&EQysxZ!-LeWJIaayl^cUyBDtS9Sm*lK+dOnO)<@8mTW-g~UVn82qKDg<7T*-9% z!`_PFAZX!vq=bVH%IVssoZeUwaf86_iAo0Sz)IfXFN9_c?uDB#i@*-jx|}{j{kj@x zb%6o9G!1@FR&ypD^i2YGe_ZH*9S;UMHDYS-MF#9(0_=I7?D0}BUu?kcLYok5scFDY z#?OwXzy=7|ZNJ2T-SHR|*u8$K0Xwll;EF8?-n>l6dvXn#!A_BPU2ecm40WUrUtz$` zkRxe(kNTXCJ)#uH1PN>b1KdOh;0A_ZL^&-R90$05SJ?n}MOCm9z~S(ya$4jB;JVRv zMF96kHLw%Fjj3(`uAz$D{!(mB2t6*qY0WW!>s*6Wx#e_g(!>CVNix9UAp*D^H$a54 zMZE~&KCw=f(_?Q0ow7wumu#`-B0F1bSPyfsmr}>uaJ#dVw>1YNWs6r6;BYyu^@d;8 zva`i8Exfc#s`0ZP;0FK0D( z5xYJ>-?VWK5Dx}9HDYRUTXTS50_;hVJznaLTg?ILYZHPi+nEC-<7Y=xU<2d;ozdPL zpyM&B1N1jBO13CA$Pr*mf)6{G17yg21QdB?M{|J0P)B-cCv$)dIg&2KDs#42rgjnU zncH->IHRR_z}pLSIZcdwn0|3QU_~o1(qYny;)m&CIxKuTxSW2IHjfX}dVQF*oE)ar zv~|&8>eL$SbeQJRgOt-#i38hI4%-w$k9(N3=Gb9sOnwkMObbX8A0|wa4-+1u!_?_^ zjE-`e=FZt7yxYnao9nr8wph8dl`ZyrG2=JwT!8$^zYwMemv%MT;-%=O{}LA6$rica z3zFSTwipvp*<#TQds%wC|mrom&q1mY{7@U zO}2Q0W3LzDPqFLIGH&lHDif=lVlhj20HEv?z)P$Z_@U06BCZ*eToSN_y4XX_1ovxm&vpU*0DMft>MDFA@sNbQfrO{$Q@ASW*a+569-64k^>|jq5ye}mP3`(WFrSic()ZGm+852fUGgf z3Xq4c%~($FA*1PA)L?p0`B@Vn_oJKsOIUO#Kyp95VqRhbWK2W_$Wlv9fGkl@qTn~s z?FEybGXXM-Y~#@sDQr!wyoPk&xaS2EAY*L7n=4I#{L!)33*WdtDyMg@G6C{8&87xw zwtaPm04esZTVn#G8CcCaxqPh~Ak`v)%S$d?=LSec!{T^_XWT6T66Q%c{ocb;PS3io z2>DW?Z&l1PP%OgTMAlay4l z%3?8E%4wGH-(#bjte0{cM!!g*pQ8HU(N;MPh75)4U2IUQ(HK*>$}|#+65c}$x}2^y z))cNXqr?!F5BpN1%V~_{6s~SLeafR&ISp$wShYY|b>2KHwoBXG{pfs9t?77#MBv64cNg1*fWXjp}%@T1oPT0bW5CXkBWZh&o*R!n zq7=sj32Xra+;9ir);BNDpc@kR_LXQh@T5}BG=1d}0F2F4!O$>0DBm*2CFuHm>owE!gR8H$f z2&)kkFrBl-9ZaWeQPU+`TuwGI7r&hzy&Q9}ml8*mmvV)(lrz_Zk+Q|{Gzw>nT5njR zft@YBx&e%oEhaab1GHA*nP22XIzVsHKfJIl3Gve4?R2~70F9x3eSqq{WDZc82H&d> zHS398AE5GEoCCyzK~9aB`kKg+Ey4usQVFuhOU-`S9H4DBAsDdL93UA#JDLI;AP4A{ zZRP+Sk5L_P?a1s0k_g$N99BbjO+nlI3Do*i(o`KEsElY>0&x8d^)(CF4zQiI!rb6 zVbXGPm~zPsX6I~i2D8&)`hp(hFdd}L#Wv+(n?mSu50lm$J4|CY)5z{&`js^CVZtQ& zFyVoZ0e{qE#!eWEa+>DGivaJovc=|lZk#Q4ecj3yn{3NiPAAA{`nE`z9`t?FWQ$33 z(|-wz?qrMH?**;?XR^hZh{_f(-DR@H%8hxMvJ&N?+Y8FRW3t7tkwXd}AXZ+(|1ZK|n;MsHoUbQLLySii!n$ zK}9TB9#QeJR}``LiWMyUzUR!$-YxO{y??&<^Vzv`&i9-tXZq~yE@q1z-|=UQ5iuw4 zU4OP%7fP?F>#;Groc_s(4KD0y#8etaZ`s_;Y*DB0iTC{3q93u!wY&QL@N7{TiKK*k z;TALw%&E+BT47`yQT*WyJzJ#Y@oaHOZuzTJ4bVXvux=!B&t=XXWZTyWM+a$e-9es* zPyMnKcaVRhgi6SG#YiIM+Q5{SGJNMI>^o+`W@tE zRfKjww?Bk}c^~2%^bF&KPeUCfM@D)o z#?0@4bq7gFpq4j`tecthncqQv9t51$pZgu8jz1@x1x|qOAn!4Pcjo<@pz0t;eBpPH zIt{vu& z(Bd((oQ5EGko`k7;Ng!*5FMlmDB3|TJucWmUWvlv4)Wti&2m~NKzERxkc?~xx$7q+ zjt=rTcytF@1PLmpeW;k~D4cKyX+n;4knd4Y;SRC{A#n#undA@_C-nfI@^}9d^*=J0%%jpeBG~S{{Nq0WBi_Gzz7l=(AWB?C!kjxj(>&057 zTVX^+b&yZ(Qe=+rj32Li!Ivp);S6b8WRC9)A02|~)q!enY+__fW@V8hcewS zMH>3D;BW)otDqlR7MZ)#FB(W|eceh!+X}WBNNKsBx7LZ)%W2lI*K?v66}y2J5jmeUkdXyF=O zPUrm`SWZ)Fn@QD0DpfzrB6H7Nn<=f3y2}Eo`mIn)%{CTG-=I=;RUlOqQz%v8<#elG z0?X-H&{f?SFpoiegC6WE zMN#l57Dq;UD#lEXRb&P`N&=;4A<`o<9|6$I>DPmRvn5evj$-NfbFx|B1n9wTYmOGY zGw!NgalRUtYCp*C1 z+onj(7L5_=&d{k-cc)KG5sulS!S!r$I?}|U@NBVX8d4!sn*O%#+K?%Gx+I9%;)jTZ zXNxA>xXN!loCqc{>AAm>Soh~?BS>;P=KrRSTcL$W%G_;&vm~BAsfo~enmX11v zqP$oL_Q4!X;gQ(}bWbMKfH*SJQ!!>{cJdn#C4ow58#ka%o&5%s3IfjG0Q6Z#9eI5{08)If~oEZjPHIek?% ziK8+7fN;4nnFQ#@G#bgsHl}VhB#y>36COQV>*HP@WoJQVwwn()*Fk2jB@`l->XrKEAmUVWjPwqGPKdOC>NcF{Z zB=?kCgjk7BUZ?tDkH6b5z*2*d{`C8ub1*KEoK3Lk$j}Ht8WXj-cL>oLS86m#F!B*; ziP~=9jv(YP3LuCa3hq2Yj))+|o3W8kU$haOW==?mz%kV{RO4$nfx0k>b-6(|4<09PMm^&BTgpsBIMVBu~`ZOzH zb8;yODlk#I4anGwfIjRec@;$?Y74Qg(Fs@QN1reTU_>RLwmYB$2;Sh^M=Op7_YXYr z-uank6^{d4fe1Rk&>SpsZb$U(Z?{C3y~MyxB|;S8Q+c8Y->n@RJxkDWUL06tS>j@%^-8@8w`01$h`WYhP)MIe*HK@ z-UhOuex@PUfRy!T8}bfDuQKGFAY0VmX2`oh=GQ-L$h$!%>R&SCJs@-HzcA#zOzt$~ zeIS$dyX>j6@BqjSqCR8jwVgkQ+dX`a2ByBuK0NAwxa|DpCJmLp}@g^wUpwtG@=PbFW-c z@Epn8MbwI``+{*YF`v&eYtIAYL1Mmanv;Dks)VTB2o*&eS42%JD5dm8xL0tys69jw~0bT+#r#FDF{Ge1Ev9U)~={T!IT6R;Kw{=QqGIyAo<#Bj!Q2X&ca+@C+Gxe(iOT&7nauti zp2!{l`pDH?HGPEH8{jfn?M#o@FXxwZpzp#Z+vgsPO3N{v&bD!;USNrH zaLJCjrW;CY=t8jXC#X8N<(*-zC&B)Lpe`}!7qHvIfU;W*+MUYbA0(qkBretDQP@u- zk*2WMQU+p$eFP`F_L;@8!akaj>aTzV3R}y!INuaD1B82bsyG=fo^C88;jIkL z`|#9Ly?;OVQ^1rrdw3K2(b=oujO4@|4WlfIZs0o%FOp%VI_^k9JWL4pe1B=_>1j}!P&ngJZDDezw%=GP{ zwX(TtpZg{xOa*v_qKZ|3dP=saec;?!1=yXD>dim`6+p}X4X$eK6fCD%$=9|!&s2a2 z;`9ZgD*zdklvH65C7k07Tw#Ub{%rGC4O|(4_ait|0XU5|MK3bDp%`=p(4ne087*Eg z-LC*&!c>;LqsIA>Y=(uLe5B^snYwWQyBk@_oph=t7U7Z`YBf4cY@HDVAG^W?iq<*&s)lX?L&C~Otdt{ zflc!%IW&+CR#Q24ZUFce2^^H6fjk?n3fuhySl6?GkB$XE^1}51o=O6ff&$bOg|h`bI|tD5K{e_>ggXcP#|S$!i0!1wPF)qM#+!tlp2=*(|GBN;e>kIO zdua|`Z4zWE(EbMDlIx7wG|ZF1%osoy5&VeBc@W0P&>9uobPR7IKk<&?ajx>UzbuG# z3{NvsU3yBWW6<(_z*QXs1qXUu)^>RBm^&4 zH*jSHK9k^3$G~Z{DSDCVX&P;Rqo(3ywD|H_e#g)rrn2O%EjyGg;2TSpvqyX6d@gGG znwEaix9N`Da=p`)?`R`*Ps`6g)7^*?qCO%hxynf19}SKd2i$s{O-5*Kv%v)<3p!Y0 z5-#~fvyw-DqhlA2Q>`VRYF083<|IhIg-gEJtfU{Nef76gVih%(I0cv7^6%n(U@+nQ z*x3@Jd%%<*we)+RtSN<4+C}3ZxAaHah!ur1+6a9X4TQ2FoMR3Cd9#5ip(`NtDK7ba z%c>umFE8P|wyPyNc7@O{&4xsF5YFBZm`g%=t^Td#g>wo7){~I@AB3JVAr&<%q!RwU z38~fpAk?lKmIK`pU8-3jF2K`%M9ui}CpbLnjQSZqDo=YNh8uQ-d-iUY*ojNFYsGC_ zl?AJx{UoH=VI@)*PMZcxypKy}{x|Vb6^KUZY=iph9tdKO|4$IjYOjOlPSW0|S?!ZJ zmAC9+iGOg(!T&0xTeaNN5{KZDL;qD$I1?doGYRe6s<}$5;=C6EUz5>nn#1jl(6P6W)8aQc?cv~yk9(nd_C}cFo6`}_p1>HN)EusYQz5N{a& zpw;iq!jv){{gr@Uz$MqmqE{1{Zvb|j1A#|l0%v2cW_Pb9qYZ(?g(US%vzAr8+j1lH zY_meDPkJ3f?uiKL&1QvENV`MeL=t+tSs@kDg%J3Ngx+mdNQLwd1je5Pp%0sFa7yTO z2z)_8U$ttkgI7Z7lPz%!F8R~{5Yk)-yi7vd|A&yihd}9E2>snEJV_8v53nZ^Bw9zI zQ^5YL8Wl~pj@H|20o_kpcI$AH63#lXHxtyhwON3u)+U^<4OHSoy0+KMv&2ALvO_Et z9@tF;b&5grz+OgBeGIw@?4JnQqjhuL9(T{&B=+UnCgxk>KwNS_v*H2C36SEI#n9IN z%0f5h1%OsiAR}5wdeJMpQI)kd`-hur=%R{;7i z!Bbl6{vils*Pt`cLOt1`{A@i7#jPYUoFYF&`n6~)&AEkhIM^o;G&Tm!2m4xrCd8n- z!G4yYNipcZV1Gu?u`%d7u#;pv_?aLeOO~=pV41d_Y&lAQ$Yt3A#20?F;qDXm79&CulaJq8T`djdg!#h~NB#)o8tvJ@_)f_)u9ePhsFV82Ar zpcu3T?0*Q_HwLw8i9KCh(u+X@!9IeZ5iw{g*h>gHGzP5#dmTZC$Dk*{{+^&CV^Co$ zA$s7F$Hbrmz+OO5V_`3J@I2q;&Rp*(F9-G_;Zq9xHHY72TjB#;a$4b+A2y>uzSt5M z;F8k|{rPq<{L6uDB78>k_-0^*y8xe6Xf_|yLH#zs1`|HJaMVZ5#Qz^)zY;#Da6@zW z;(y#Py z1J3z7wa}kj1@V`FbN&_<9{GGT;r{}h(|<{x#3e5&yy?qk@S*K2F&~$_tT5;6 zX7CFtE%7)mc}1bMr5XHrU{)3ItC~xnUIZ0DpeG4k6V0SrG!6uIEaA(W$4>xu1>x6a z3$YdNyQxB40qjGAkfl<&`l;1Rgp!e65Kw7td1i4f;*Fto1@4% z;I1a*mMC&RxNi`0YZUnuT!HO8d0P}|0d5yU)QK4dgu;5lJh-9 zDIYHE&{i#`oS52EAQ-u^ouK;_qWT6P zfm>Z#eiOKAN86-5t>kNe1EO}cBZ%YTcDLTqHa1k*B1$;Bx7MqY3M&jhfg->Q5)51! zfuAQhw4=>wv?+R#*>2SO8#NUtqrtM{!)UTiW$&>_=4`q%?^T(FmAe4+J;WPP#pOhR zT?_|D6V`)2RhCqyo`dI|t8niR)8D?a#-qCkdKh=Fp$GjjaWzZ!1)q69OT&4Jdji~ zQx_U?JjkQUD0#B963I^YqQfaL)3@xnbD967CZ4ccq2>1wm{aW2Jiv zaXBt|X$ZqDL*f1o{>i<7T^+=xGxo+1G?AgeRt2$*Yf0~D@cG`|odHa^3&G}lcMpcx z*MNOOyofRQ=qCK>t9zuY-Zk;T?qb9%h%gf{&`vb{f495aLKk&p-U-!ZtFvYI1HEU=mrw7 zf&!ooH{M#XZzoYlj6@HKOZIf{0V5zzq;Tc{yPNRdv828O_6~vuxKD*t@rcVP%zJUk zA;AQ2*Xr~F|7gO7xzygWF$!ls*jEsAKqOznxen~72^!)0J5Ac;Z-Tv@piwcX#b_aV zM}N73NdhA z`;gR3*WG-m);Kk&aRzB9;g2EQbu5IBbKO1he-Zi53JUwd3-=ZyaCT6DLKE(GV0#?~ z<@1BsA6%BVP88x5T=HU<7y-+>pM!n;QGh-Os&!bRvn1-e;^g0XB=D-+xB~x4dAaM| z36Jm|hHH6G!cBOa;O2NA!cBVL!p+5?+2&{(v2StRF7S-OB_C3ejHlCtNb`8`?j!zJ z!N~m#D-*fT8L4lAQdt|iWyc^7xa78=fFF!-&o=_U1O=4c-Urrx5|sZ5VwH64uWlmJ zIh?THT=x|GuOfdz`+)tN2f*4w>|NT2o2_tv0lTUZP=}y~+Y78I#O@kk+t)pAEbg8U za5D+?3JTmqDQf&1{G@!P(rYuBN}v`l_Pqz;ZyGMyH>hztf<)fI-$2-qAodVrzk^>t z1=#*^Y&iI55;ii3Ji3@85B^;^9^=&5DO?j0s-qX zC|?&8xP2*Nu6quNa|r8G)mV%Fq}*KT?G2Cc2E(9%d2n;RYvJa3 zcfif}9)w%qJq1^KFTpMJHp6Y<{SLRtvoFWql-C_@E3XgS*4{9v&(nE%A23E%n-7fn6G}7u<4h6x<5$B)ILoOW;;|cfqal zUWDshGW~_9&mT{ z4uad&n+&&`cM9C@-j#6cytQ!ay^rAT<`rCp?KQ6qZV#^;+@9XvaCi6igS&?}67HVf zQE+>C$HU#rI}L7c?^3vZyldd@?cEHwuXiupe%`Zi`+HmAZV=ud_`Bnp9J>H1i1kXdlmHqv`i6hmtTe050~s36rcxm zgnKCX^9k!4#CV1_p$i0@a{=B;0)sj{gdhWHay$Me#7JCnNKm)oU5ax7__q)?EQs}E zY!mq6cVGtxvHgLmhXLF=fQ=+DHZDM`J@*WN50k)AK><|_wtzqM4`5S**cgs^8Tb|3 zfgKyfj%I8o_^%Q+D~QctEVTmzB`$e#5S!1~#o&KR*xWew7x;(#32c54JBRho0RKh8 zP6=X{GM4+75TkI((}LJa!ki1hzmc%BqBX%;1NJ`zT^xbzHBi+XQI{q0tQ#(QZL>mr z>ru@yom@*y$0ctHrhUl_({37gEtT!;q40-{s~WKSzoqq>tc+9wAFD<89iz>Ak_v83SC}XM!PEA4S7Atg47_8dyx1l zkap@|gWdqLBsI~HH-dCaC=%I#aFMn?w7kQ~Q%Ky5OZE-0?EwJU5zadRle<7*pE8Pv zbq`UxHrN9Q8XVLmDd7wUe=%YEm-(w`t#$+09}sk4P>l`f{0aWvZGer9sT~3KDuTwx z)t)7O3fH8VT34`V6Vw=2yBhot2%8d9%V{gb0l4I}xY``>*Aq4)ruH$|UDJS$kEmQD+szgriO*&lR#|QvSYjd!oyE8r909NaJ$z)Q{RcVaiPLm&U>J(QUsIg=nvRU zT%knWiTLkC*c)Ya=fi&}`QIw5yAA#&JTQv=| zTjx9kLB9Jxrj4H~9mQrqJ8{YJF{r2=8apm|WE67yfjyp}V<`_-`X^4Wdo)-Ji9J2Y zcFqCoHe%0h)BjpM8BrQFxog4iC0n&gJq{1`g0gEH>Pemd@>6Fu56m$>R9}`rOEh!EC40eW~c5NsjY!nT3bTOOE1=Kzk;4na3^c`XW z&H=Onm+aVvvJwpNCa_;6s5%;88Rw@H!ULgq@&NW<}H}H)ay#mQyg_ z8M&P1|HdROt>kOp2BPlYL=fjMAo~7IxUV2e zIJ=c=xWWpI__Ah2aB`5UdLJ(At#|cmly8vvV44ie6;CGHU&enu?Rr;%jg4Z+SjK z7L(r>b{K^d%Lz2-$vtcIX!Il9p8R6x&Yd|`uZ9Tlgc3R(%NUEd&+Epr61l%>e4vT&VVyh+C~Wcv(XZ4uV5|3hDG|R_D&< zbk2wTL!{HMS)FHm9X?U4;&~GCpODVr7NHUo&R5{_D7s%PLwTLBlY~ni6od8#dp<#r zw|JgxO0|kDWPc1&ln=ZKo$pl;D3HTjRNN1b-}$~lYKOEioi9nIU!pL?m>&Vv(xT%q z6`}5YS>$yVDWNds;Vn2q*0Q%ygzg?t|159*8$PwPhQ^QCvY&r3jTSw!0b0Y)z_S%u|3knfJAzX{t#ki=>pu?-1c+J`hS~K%|7Cln<(8s(^*leOEo+ z{kMhb!}NiM1A$zGOTHDZ@#+mf-y(JD%zooF5W>BK7T&G!2=76-=ptUgAFF@R!kp7m zy%A-=-gk{rcTVeyJx*Nm(}-YaWGpE73WQSKAox`zK~!>fHbG8D2(jQ#kq}uh5cOmT zE~gN;M?$0~&W}k8=LXjF7kW21}YI-;RgV_n((rsP`_dC z2_fOE2DF3V%1G!6Zds>8uZ@PT@PmQR!X@h>I3Dc>`woJ7Mj(~1(sjVf>w!-$@~fsz zU6I`%?L(CA4eUI^rv`A&Q)V^TZxVEDk#2#yW@ml|cXtema$1q@)q7jsl!gL&k zsp?td>le|UOxG6PhwupR8@QI2dolJvyi&MHuO4mzoz!`fhplG=Cv~0$haWO{IXgt1 z$<5aJ6%bG4UM)PAIDUksyI`2%RJ;*7ic^T{<)1mCw$RL(qf%~bPJ4((&m2`M$OEL$ z9GUV?D=mKjcCOkdUu?!DPcq}Q#b6U&Gm_?TR2d1~w6+xL`72G0EEwV>Odks5i|WC9 zPU^9VL`OU{4gO=e1nVyxgS}69UaGzyA2QzYafR+Dtlmq8khXkPhpxh z)cEcm2JBqI9iH6lh}?_8dV<*PLhR>>)e~1ufX&^Aa9!|c5Y|;;!C1}%{|UnO2!QLmxc8b6nMC>7nNG_e>V4p_Nuqfo74ff*%9T*7AUXJ1y&MV;OV@@SUCWyf% zRdy>$6MJ+}g=cPV4fs5Yj)`G=v(DropNdXoMwn^al!Wero1L~byaG9^?pPGu<9j0Z z^74ky@Nd;E1n2Tz;AF~ca_@r2uf_CSM>DnfYE>%JO|cVgw{pC-^$?7#i0)*hdK8er z)LhG-2(Fr%Q?Oh>O1}0oAZltJL7aPm=oOL4o3c0WlRH}tTw#Ubhma6F?b_F$nup;{ z1c#>PoJQ5jWrpmd)%u%IRh*PK;oG$1^K(&*k5fL1=`9W}iJT?dzi>N@&^AM84wWV1Wdz>anu&obm*1t{2cXpN`A z)?J4&P?|M#*RdUVu(K1cUqmfqCNoy@@ZA zyxo$1lL}l_ZpG$nj7MY{LxskYeNu7rDX09Qbhr#7Gm>)%c1;XvNAc{2f*H)0p zPbm}=kNp)Wk(q7amJyikAxhQ*mq+nVQu=#Ng<{PPu=q7V-jz13l%}H^G0OCgWP#{|2%mAC4%+oo3lVJ_rWNrY? z747SQnjWLx0mc>W#~go*(yeIN@`w}VXJn3%jDq+OQ} z?^>|r)mG|p{I?_M0YD`sFB6;Iw}{g3LI=xKx;W{4H=BYH&W8}=rzvl;%%R_O4-ywn z8d=*1mt1X;7Kfyv;b8L<&^JdQwVZJ;1^x=D-lY=2YRX~<^R`v{+&Qp{8P9rAvSZ`f z2u?P0Yz!mSM*<0qXIg$CxN1D3U^&%FzV=!mYCMY|&UzqvJlld|B_(ApqOd(- z;0h}YPecsD*>8wHo`vCQ1c$~mPNPlHi_B`H*58Dx;$*bA00(#3R5iJ0!&H`>(b~W9 z;amU?Z!67eeW59uzLZ<6wE%HePHG)ajM{^F%D|^Y;K1Xp+abf#{?l3;L+PH2QX)_1 z$6Gy)uGE2Pcp-2`_VHHHP=~Bp4NJ&v>^YQ{w)O42Vekm=Ah?z{7H$I7-Wn#vMA@$* zWy8ZaB}P?HwQq08(I5*_eGNGVq@6m%kcWaSNli86SdeaNt|1Qt**Ue?kmEqsr>-&N zc#yqPw;S?skONXrf}|ct9szP#>UD!2337PqdqYkDIktonF9%d`6`QB5-(o*3-f+o* z6_lGGGz9GV1PzKoSAhLALHop@x53WaAJE_!R1WrFf`-JPkzk)n(9jsP1nh?h+BXJm z1p6m~hQ%Q303qse$^Bx`5U}SFw0{h`4D9C#Iv@sp2Da@18WDw1EA9u-Sx&AT-vdJJlL5bl}dlE+0MAzV4XB9(!M z^ScOX7O5VFJPTw&YA{I7{@EbW3JiG;$dVEYM4qBDxI|@e0$3Li`_ya(HM9)ujRc(* zgWd)^IULZ!Y*MvWG1z?xIz0*@7i$5O$O|e`&%wj#yo_`4p&>8lT>NFoD<~Hwq$QWA zWG_?6E*&AnLAc~a*;q8x2=+>XE{;L#!2X$_rBMjas!TnEEZnsqbrL*0o^~%F3(qrT z9ms;zDTb^EX{Qz%ayO7AWfX|)R)BhvzL`^sfX@W4MDC6^aFQ(b9D8uU*MNNg5!@)< zlLP*eP#VU2QNW_{M$k!FRp8wLkMQn>YkBvcWiwW2A)SS&+W6Yz3x#=7aDJZOo8mvZpz*8h$#=l#s2fN`1=``Ji8r@FvtPz*;@f^ zKCU-L9)TeQm%PBp@pgJvPE_p!cqWNlPKn^H^dNkyfv+H#>T58Tc4UGfxsO7~mZRFG zo`;8GmWQE8Md~GxT#qME35%*NpgSIkxR#SWWhAgQk5Ptu08h$+?YyDz2=8FHmUkH3 zgm5R~?;>3C=76omn3Z7tMC^5(OQe%F5`*bf#gRV&r%rLnjg%L@t&+{EDsy)(@E1tt zZUOxBCd0qBtnNbiw~+r!;nf zR>DnqH^a@re$SowH}m7Wpce+=^|rI5t0?$w+liAc6U@mOm6+H9w|c$>?b% zUwbkTH9w9Z&N3i+e*8C{79b@xS0zd~8x34xh2eQfh;YtZ;?Ix6@DhSU^J7k301|(XmRHa{``0YnNJoK`}5=ML7;KPNUCt2gGAx6uzj!M$=Kwf^r!Eq+^d(l z(tFB;bLP32h2fHY{s*Dwj8MOS6;e+?I7R0P(FKHIR zKA`rujifpQL2^j<+y6YHlg|&MPx}w< zl~GmT^|QUd|B5~5_2aOrpMkPkXZx>OXp!-2F5ktcrJHcBg%nFZ+MJ|t-T*#$CPI3) zIb21|i$Hq8pKy+b=*=Yl0>1!Il}|R}Y+^Zf_jZWBN8&G0POWrX7UdmP=M(V%A?#(& zBjcP0;pEN2&30V!?HJS>?C}I`i9u7rzJQ=lV$d~UKSj`2oTFe|Z-Fh22lRamN`u`% z(9bcb57-k4+8&GRc(AV^=ui7g*en=Ve^g;^cz0F2rNha)k2@M5A{ho>EZBH2*Gysq<;2m94pTFGALXpuE|x$vpy| z5}9L9J{2CWyzQw-^CmAgbSKaWG5JbEcP84Je3PNO5S^I(l%et5zLm(C{Dz@-B|15I ztD(CRo!jmQ&>vGi>upR#67B3JP45P}AknS_G}U+60NPGCE@<8a$;%enHkIp_M^LHlclJ8K#bEOx z#qyZeBY=4GtsVC$T!FOKHqt`dmsR#)Q@0dUGK$#UVKba0`JM8sK2$-bQ`yVzD>n3n ztkrld+@!qK_D+RIcxMq)G+w~mvs-%CF!wg%dXK=RjhQa!E&SR?FF9+b_Wh-dJpiK7 z+GkPo7fur(eGkmHv(gH_Q+GAmP%pVXnYs@i>R6V z7?h7YIwrFYg(RG3PZ8oNP91ht68^$yrcbRn`Rm(sfnu?Rr;>9oc1N+x7l_lRV>aZu?CWM-4Ikm6} z$M``}I6-4LL8AaK!X>vx;0w|I@T4dpemTmAMgH^sM?n!S=5|0laC}r`Y@`PcN`(A` z50W&oZ0RP*^1$(F_9zIN?lw;COGVk2v1|v2<9nruR(f0{RVqGvw$8|_MdnpW$_Ts| zb-p-3C+D@IE~J2;P7cK)-{9noP|3+N$$2x7oc6i9AqG>=D2#YL>(2VM`#>;q)?u&%r!{xAsu4iF* zUxGvRjMHdS^dj?+QR{C)RVHS%nCcX7^f&Z_oYkc%c3Q}N&vakSXhpqRQBuo>#D&@swSlK!A|6$K-l4q)$3(C0B| zB-rx^`XUCM4)(1CeHnx91^X?6zD`o)Tm@BJ=!#n6mc6MWHy{D=D)Ip*tM-NYu`2Qj zBh`NZ2~-g+-*JJdA`~n~s^n`A0HUf$1aVFPqN|AMPgQZLUjKFjS6E^AJH#NIO7#4? ziiF|c2@X{ePNPlHi_8+E*58Dx;$*Zqg@X(FUQj2P%91Z8oju^;h+ayDBT{8M5in1V zUe4P47P0}J6$QjEtbavSiF=8yq9a|Kk4ZS!!=QXa_0=RX*me;~fuf_+7N+PPL_qPP zThFo9egMHp>)yafb>6&C(P{Zz!BwrBg5~IyeC>fiRMABcXC@F`bSBLzUn)zh3|wJ_ z;TI5ta3pf9i!KbmL2#((IE^+%k5R;^^*5oaI2q+5D5`aTgV?Qx5sg7=`q zwP;F$7^t|aIxw1DbJZk|TtvmLkCXH)g;AS3PQvveew?H)Pg*(5;BgXWi_B{XI(-&G z%uDJtqz7>g$#e&o+fIHInE`~`TR{}L3kX|5COrxTt9upw2v8#PlYv`CU`}25ILR1J zMd&yQv+VH{ROmQ~;`7do)8lNNg3EIzsuWo1fSz-t!EcD-O8T)I=y4Jq+l7FF$4QjhN`b9-b)4iI2ypFb zV@e@gd-QRVPS}p(B5Z3!(kk>o<;rb+exOgGtv{*ylwH9O_9=_l3eH%tqkYPG%0TA< z3La6@8f(GUeTv!BO|ynJ(09OteTq_ZD=rB4DVlvC*ug%9*}6};2w3olS}>L^6kJc} z>eH<{xVD&P2m2Joc7}l+?Nd}PorQp+N7S?d?gA9-Q&ieiQGW?6+NUVBP@keycr)B} zmxTM202b;~6kqLx9|#@Yr|4~5RVx_H?u0kI1Uaj2847OxMKH>tILo>eo)Wold1^I0 zR8sPga#~y81@Z^H+((WCi31iF>*ew&kah`a$^FWC)V-1FflaD5Dey{JID?@u3zs~w z+%NxIRb^TL_DuvGR89&Uh=%S2`z?YFE~j;M01}OB5ob~kDEFR&M|hvYwY(&R6P^n< zN7UVi@XuNb?Ze9(Kf`}gPA>O;gGYGc5|S=}n-F{l=6ZPLxN^Qrvz`3o%j@2Sezz6y ze^%Bw5dTT}L7C^lBfP`mTHXS<3GWKHIij)m&m{46#gu*E5mUy(wWiE~o0zf?E+jtx zg(Uu|@OHo>yw<-$0(aIP!hgLSQjmHYo*(dv5IK}@3IAxwed!)>D)}2q2Ct5g!$7*w zdkMHL_by0nhNm+==`8!Q-iILhj$A*G^i9ZJplQp21*uASID$bWDC#ER1tn9#lWWTA zPK5sv^50QbcMklezr(+KMcwuA&-w%YFUsrI!oTl!_`fP={x9VJp}g(|@K4VG};tBPIDTy{zgs3$!PIMoBhdrPngP*Bl0Kj4G*vD zR?^K}G5H`vU#IB94ShY+&UDb+`;N@_pO9!vM!{VyKrIHLEXL;hH!d}FJ)n1R$#MDS zF`P6*`nA%Z1LOVdqw@XzY^^H)!PX}(IVIn3xEdM;_OS%b$p7W0%fP;uptEAoqhNnP(D^awI|E(Nd|L1UHZc^J zyd*%YakozK_LNo!nf^XofD$xuJ+@vQnkSbyOyA(F=#ii4qOYol-hI;&N-e91?L%+erBndiYc#ZLH0Qsztu1d zjTKKsqd}L^8+x{sH}=GTQXb`a{oxVb{%|dCG~9$Y5pIq*18x!XUy=DkyiArWw_N4a>mC~^b?l(y?eIDgXR2>ND8iLCR=94&CSU-4G zzJY>nT}VN=t89?m>9%z8@FuFgFv|Pb$F4 z5RJz5n}RL{q~kK%-)W^4+&2Fw7?;2oc$$eT1vW;lliI}NDpk-bKsv4!AM3`Yw2Hfe z*85^@A!W(!MIC6{o~o}?0S<3^|5-#0kPA3h1=$0Tx;tA$$s$PaYEv+BC+}*vX4%q1 zz~N1H(b5;gzSrwun^_KLEp~jpBkR|G20^ysCckg)%t&=%Dm2T{@?F7IvmBGOw34qq z0En99L=a~h5IxH=CQ|(eQFw#6fh(*q+<=4#=T8GyM&P{(4$X2njW$IuGKaO*k@h!g zDo#eTMbq#hg0~t5KpItj1OEK#Hx%JCQzgcMjVjS29j_7-6m$e2T_ybQD=4kv{-63) z;w_3&eiNt??}Nit;=7_TsQO$b4p2dE1H@J0`yxtKph{3M@+Ynmqgl4pM)X`IwuNqV zTm-hM5}dVIl{l95Yp*jo%T|dQj8s1jB(RIEzSDM<+P}JUGc&%{dQEa+sxJ zDyHal$Cy)&X~Dmkmydmtc?+Ckh(*o2Mwz!eps0B@Gz^fQL;5!s734Mo3Yu4IoCbE( zybRe7unn#NuFV?>(YY6pHg6cR*Rkp=z@z3>K|js-SHPp@4d6lZKF2u^nU`5Areca- zn|Cliqw;U&U5|5FJVh^XMnf!W-v4qW&TK$Y^J?fqK-#<%7WY>Qa&H3^G_Tfp3hbzP z8M5DI8@vl#n>P}o^D7{2-Y{gp&#EbW5GHC~74+wfcLN?ZZvYRP_Z!Z6$h^!_F%?tv z+Pvo=(0^S4VN};Eplcu&HSdociSrPksChN?Dj;p%WoCw;AoqJfLGx;je0uy z9c+V2;ARCB4$nHMw_C?`<{$if1{>`EJlmz z-A-((hLa#?HM~Y{FFD@hK z(wNpVupcAnvZ$8(AF#I(bVVTHe4;@(RwqmBic4M@RdeQHBmL^Td*rS16m$~x`924plf5$5nwMSXk`q#66_}lT2)LHB4A)uj5h|8HwqHM z{V&9Mje1iI!}i0DF8|&)(nq&--{{oF`^LjmnePuM+Ba%wJ|NvUQdpc?1-W+u3igd! z<9)EBeIrBmF_amn#jbwe7zxqo3rP2kVaT4!s&jxx`$iS?Y{qW{9_ZW8H)v;?x+_9}pi&JvVzKRckE(v>umS z%1t#8SIJAnUWL@-wCV~<8J||ozOO^ntpfKGk~$2Q{s*4_la?;6k6ZdlW$9snqL$Xs zEI?69Yv?LKQA=y+DGKm76vDaoLHHy+n^QyiyTvW7ppd1X&01PLaNqDN!n7LuK|Lv_ zw)8xBgf|MVPsRY!EW;P+1_?+NV&UWo~2u9`vUolc$wR>nzpydaF ztL6k0EN4o|*B%W-%?Toib0!eIj6F$PLXFQv3FkfoS6E^AXT*Rv80?|7D)Bryl@-MHk2X5j|`@&3e9MaD+vvGrm0%v61&DSWGnR zfUT^C!;v>Ey8qmh3VDor`xQOp-^@NtejTT~xL151rbt130O@@g^R9uk(#pQRpz#j~ zCFP|py~4ey%C&)u!{-_NCFSgv-tNpDOkD2}xC!rQg1k9!3%oPn;&IuFh$XMWQFVBP zw+1f4c!;?xTYAqkcQbR_=bqOmTY=L^XuJXs#P_^0@{K$uR)L2yQoRUBU{b5)?*Ug; zU<#Hiu#&Ic3`AAn2;w9s`4xE2--44`qOc2X;0h}Y4@W{!zo+^YI1EoBI8=c-jW$Iu zGBw9)wf-hlRe>2TKKggR0^bBvS@JEX!|U7iuIcC@TJ>Eg9AoworJMi3DFD7R5qM7N z%L6QYI0iNGBWF-T8Arv*k6Jn&pzQ>I(Oj_99@Mlp8@751Depi`SaHek9rMIg`Xw^H zzGXQA*h0epaQw%k7{`m;z%D!p&`yVoN~vYD!4bHnkmyHJ$&!E+PE8wl$d#JF>C?*{)v!fJyU zuL0a&!LL3VSg$y?C-{wo^$%deJsGSUi9IC9cJ2r3M`9mP;_qK6tMP)u`3o5LK?jzY zYOebrsz-7-1*Q#DT7wqBeb6DqRbrU4uH_2XDed=|?&IL_Y1Hm%E`V|_U0UJUr~L_s zW@N&>yRRkwLDwbggHl{?0#Ysd>987tQoM$ww<>Ue!W{ysofzz7&!7~?NCjxKL($r! zXpnJVfc*OnkRKD2r-HH9{srera>zoQR{Ot1lBP{Hj2+>=K1hc#AsB|r<&Tj1@+Ua| zpD-TX#}cc1ARWgwA4XO^5b=?NE%7uid2&o?F12GeZy6PfTtE_Ow!gqUp!MF_Zj^?Q zcsJ@&QHk0r2u9`sHH=gb0uty(wfxcGs&15msqTd+ zJm+fQ3M&lPAtA!)gxbT}l@WL^f6v65QF=Z&+%bJeT-`A>{DmA_4JROlR^$6q48fs-9Do#d= zU)|{!Y#Zdrk}n4ewjDSe{(W0$ZPiHCafr1{(n% zlLa0;39HoHm%$F6uGj3ue#jS{Xw~m|Wwt&EI|NwpBy2F2D}e=1!s_5&0XujSRhFpxkC z)$*T!t6C@p%PmyN*S45oT4)4udH~Ta)J!T>7Kp+Vvj(oP!f-cU5PV?Z$_Tt?Y(cetz-ruG)lc#K; zf>!hXM-R5tO9`A(e}4W2*-Fjd-R;1w?x^y6P@}cd3Ttj|#WO0NmC*tR*@f2COlN%`d`)@*Hw5C1)i$Yslfbvilws zIKcTqrOove;Kk!C@fR+6W)SmNCcvrmoqgsMkCr7o|r6TEoA%81_qG)C-;~lDU!Z{G4JW~yvp4y_IGXUwW3{%b1N-NtuhU8YEiVTx;OHu>j zc`YAt-Cu&+I;kd*9}xKf$b!@rAipMZEl4|c;3!LslOP`iS(3uGi+G_BI;xViChP=K1E+Fpc*9~0of~6in@3Rq3b~oD5LbqdA#nr5M^uGlqQ=} zVpIG!#cESrHpO65xN4O_VF;zZnlXnu7P#hf$JmP1pSfyU!;7 zhICyK(!QMh@1|>VAA{%r`at&zMD|Qx!#0F#)$ImsG=h;o!QS)W`9Epz9k;iJ`T&aBTSKz|X?s6|=EC;Y&_+N}dn+hp?-2oeukn|LcR|^z z8v`tbRxfwJ-hJTtKWXprNLbX~)0Mq10~EElhMoZwt=}5@6;RaP8tRN*PTRXDx+1o> zh86&d+FL;(dmkULxBsr(hDlJi>P`aoG<>qy;XY>@`8zv}Rp>pFa(sz?6>U$DmNx)y z!t)67=p85pqV5vt52O*lyHj@q{1eE(yHoct{HKz?uT%Ft{MV3wu*2oMj{FBXLvm{| zvJaC_s4;?O335C7YBfgCd_nF2sm2JJImkajsxgA*5b`gOYK)-Sg!~(%8Y6yd3GyG1 zYK%x=*q1v&2F3_c8X6-kkORsnJ#qv0*E^7A%l_Ay3&mhlxWO@k)nEVLsAqe673b&8 zDslMP*%HT@)f9D~B8>-8l1DjQ4#$yyyi>Om{10gIGs9_Ek6EzQ&~+kQJmEHp+LQi} z2klGh1>RclgA2TIJd=061)Jvpfd$?KhTKeJc!8%ijsROP@MzA6{EG zy1>&0xCc;hfv3`@7I?n^i!Sh#T4;f%RQT?NyT{b<0xy7t7I=!!HzzX3L5HV+QxbZQ zSuH0R&EC3bNF0lNH|{%)8uX1Vy)p0z??|{7cA1~Uzh5Qzu zv6l{&;F>>xg{p+&Q_+dcZ_v?If*5Fjs!A~Gzemb>XWv}WYFI9wNlC2K2kZ`h3%oRk zCERBR<%=Qo#h@a7f}^-w5uQc$ar>IV==YYE!a2sFlwLeEU!06fzC#V(;&}L5AS!8m zQ{k%aNyJo>oIZo5C^f2i z`ceM3A;8tPjVXm}wY5o3WQu3&B5Z3!(kgVnR--c;cp9BBzNRKM79KupbW;t@CnkY> z8#$M&K^Bydm|RiA27R9mqFC1kSn94VDPf}t@+0m*`me7c2J3yqdd_8l<`J|i3gO}7 zbpUO-vt8;vc)o#x%&ny4&_b1RCG$ZRl#!TBR8sNgHBbeAw=J3$XStAUB~g`Guy{)t_#OGw3<;t4TUZX$eRV$qJqZ!LgS@ z@H!IA{dd8aA((##^0Ar(`5n)J5UGC=V@iP!BbhbjwA}(ZepZy_+H!u&$aL~9dQ@Lq zKs5Xf4Xa`8dE`2a$$jE{a;q*N_uM7q{zh)&WlL%Ne9ZE0f(Nf5hiiFHz{M*7lb2jg zg@VWH_OjIzfuYCij_F6{4n1DSEPE;d;k*T9?rEM*%qB@nUjPq1UZ;WzJzl3ox!cK9 zU!z;e_X*Plp3ISRE13zjc=wVV^>|%P?(v{4IVZ9I)$k0Wr|3_n{$2!{RC45UowF}q zY39MfrSY6G%f5nhwgSpJXV;mW1@KVLR8XOuDN%kmO6FSx#a;OK=3O!An^ex|t+Fa- z7?J3~!IJ+RfT8VHHFOcmW04As$0DxO=q~nJ@h|xgyr{POM|ckEUp_WN<6z)pGaHFi zADej*-nG=@{m&npc?V*8gyu1oKQ=?b2xmCr4Sw9BpcbX+LAS&}1P<-Lc1?vi8x2W;Ab9W&X;ao=n6Vx^a zZ36o{f;z^aKf!K$381buw5ZFbK{)Ne?oCk7ETrQa3^qMXEqm9@y+dm;q)++G2Tt!w zkb`T?TO86#)x81`5BkG{8FTLhdlN1>F2L5u$ln70XTl~#lkffwc85y=O^&Pe1pgSq zPN<<$rmW%J`j`Ngu*K&FH7bbjo&ss^Ddxqn%;ms7Ziy_PWmZ?u9e=mC5IVfC)C{= z>P+#WG(cS92ZakZ^A7+n@q@!aY1)+daEdHg;`OG)M??_O`INZ$_2fF#T zT?Z{h1r2obyL1&|;ECvtb54iT8tKhb?`O0@EvD&f-9Q368D$JgcwM-T$?ULHEjCys)Wcn z0Kmh=cpFSr-jn!43J)bw!kShuhclVT%_KjIe9W5<-wgg{JDr#lO_b%Pi-}3?ls6^R zDuMvjW}EH;e4HvD;)7Q4Olu7$|pxBn)+W0z3zYpvTqipmMugEYuXpU3>w%}6>U0{!{9gW zk3xi^X(|a!hL;B#dph~}#AOqI8k8RYYGUUSih_BxFwD6bPE|&TqN=>k_{&c;-AC-l z;LHKtvMTQs{1sSDY+d?@dJ{YEKwu#GrjxIUz7pL;-$_@_Z-i3#O`;=w3>1=&K0w~Y z4v|gt@}8!S1hB6g`$&xw$a0j4rlACoZ~AcZ9kB*Hc8HuliFl(h+&0aC?>J?F$)Nec z57BfMxHD)tRtWFW(kXAzM9iieNu7O!G~Gue`KCWgK6)cZ6FWpse}#A#-vi#QvWd{+$(hb_q|rq0#A_<5rqs28E2fvg9r*2ixE)HhvG5}}kRV1AF`5W(qPqc2 zgGiEnoILhX>YK(BK)&gX)<12`YO^m0N;0N zV&^9Ka_F(uBS#9+x-xGv{&EYN((57cBG|{Ng=Yn5doVeaTG8}HGmvPa@7pMczHZb+ z&h%moUjqy9lE}Qo5&w_1_W+ZkYNCewZtpBnSYQdRfQukGNfHr}MUt?97(f&h6a~DE z(uk;t?(Bk+B?!7As4s$om?LHksIMYPQ4FZ)t6;`}IsE5T-#gvYGk)LyKhM7pR9DqG zw{Ga3p04Vi8GPwjWjzKzyrWytEA(TaP0nw>2%&F&mhpMe^Sh<<`B~-s5fnk6qruT4 zE`W22oHH(w)_l(}q@+0Hnc3hKy)?zZQ6~EP>_)y7jtlH){vJypBs<~L+WHkRi$&Wh zZT3Jq-d=jAZvoDC204-D;S)#sjWrQ12p<;FdH9ZoV$t%cNn8>9jt||8K7M(!7Qyd4 z(cS5z=JlcW{Z?ot)P8{`JeTt+nTFJ$vA&Rq#1g@8GSM^Wqvp+~_7@{uPtAP;Xcdap zG)3e0^6GnNiY7vSbC?;1-a>$yx1HMd9njvTwi}w}m-gxdG^u$%PO*mi*@FY< zOQ??b9l6Cgy7h0=W_HB8@no9IJ3$AjPqza;)%y;O zybUKpoIpO!VxIbS3C$M(=n>SK^v31OC57hfQ6EoJqa!(!fI9%`t#=a~UOBnc^g?O` z^j@Me5DrPNBS4>?hM4*hn$$coOBm%<`rbol-Y#nN`4oD~Ias*Q>7!PB5SnY}RCl{} z@P&HCtNMWGL3lN3ibkPndUp&0(2@W(O-+l&o;>NKKT%HAqvlc5Vsb=UUip&%Ob*`F zgZKLxp@XaE=ml_GOsnOcw|ZQi}Q3Lyv3q5qsFh5^H>!1Xlk1J1ZeI+h$cC>@?D*q zXpU_~gKHA)vGv;EqOLTjsgpPc7EcBZlDHsGbg@=hPSfg%V`2GZmgDL?(brnDa+=mo z41#q9vDrwJ660*UYms{=E`r6wzrkGGmrYEiMdm!*mQ7p<>poiZaaT4`3hPx`3-CLm ziFL5twy+lBXGRnEz>*#o<5xx#55Q_fY)MYjiHXgyWYkM@nodc)1gj;nKo zh1QCkrk5vnz>+8xIZdxfyk*PuFrGfq_zgh%QkvAftEs*B8MHanK8B{3Qu~}5U+^C5 zsvdn>eD@RWw;w34HoRwPibg;Su#3L62SDLvlDChhXauwXhv;*^1cl#F;cdhX1&=;0 zKFNwCd*YLw`Y3#Kq?nr5mfE7Pp>?Bn1GT3h^jj374I@C!qo&WHdE|FM`8=sNnWkt2 zv;bw$Cd(I30S_zYHYmMdPRUG(WDVulWO_H34c~7it^uY^>Ld+WpY< zKxmUCqY0*=M}>}X$eN$M2n3(4)z`2+HE%98?{8?!s7-~Y`8aKYzEEbRl!vRrS3tTn%9@wiMW^V4W-r(T5v@zC7NNAK%PK=n&(p+O!8IKhLbGy zobx7tx0pU^-p$lTl6MESG0-l}EquA8-(rRPXQxA|lCvRmN-l(SOD=)TEx8IZQ8EWI zuVfKqrIHnpl}pw_Rw;QHvTDgQkkuIMnUXi4Iwc=Ls*(ecIVImix+Q->=9W~(`*otE zHe_B&A!MbJmXMW8Izm<{IUcfVNq@*{C8t1EFBu7WSjkw(8YL4TYnEILnO|}RWUZ1U zWNoL)dpM}4?SsHq0BF3`IeJ!S%#WH!&8OzBhPHeu1~f~b0;;|X_GP@4rAG~g`54UU zzv0!H+iE#_P|YhHMGF@XD$)E-d;k)7^R{l&2bB99?&o%ct9i9VKWu&`(#~!Av2w>E zHycHy$}x=6oZq^LI_8iQQP9j^fV*SCRRCi-Z8V7QtOctsZUxINT#g|iJI&?+U4;9e z&E<>CGa7#axWhWYEzmfDPI4lR-D~huK>z&;Xw{MZ22^tFt!5SBG#jz1l5+$8H5l#W0nJ29FF^87nBGvtHN*alhoKI3+v{l?wl9alS(lTN9WY8_&Qpe zl?$!`ZHzVZ3+BL_M6*87-UXd-n{~?xFdM)eSkMpVCp7u|$teZnVg5t25ayYVyB^2v zRCfPHSU<@_{Ri>fDc3q@04=0r1Vaa0krF1^2^jgtzm; zoiOtYo`$)ZW7`e0=;TCx;jX-bS1spFiLl*9c#Eb}u-n@2!0sr|x3jWZxCdtUf{%z= zvv_qwy3>6x8TF5y(zcg z>!|%|ZozL+drxjbrJL|A;I_X5xdjEV+uHFR%q=(?wpkdwo)QHeVD~)MjAv8g3atH} zyn-I^G98iCbP9U0ku@tj1$|-n#@QG!CYg|5f=<~x5(TFM_v|3{BnrmDP7UJYM8Q

KkwI;$R8SZ8Cp}I4&6Nsng>8m|{wfu0jM_UY6+8kvwG;MKDtHF=EFQib zUq$7D7C4+!i+nqBkQP`G%@MiBLe#`QJ7RQhq5-zOk2ojM1ltGUKjK^*X$gDm95I&Z zo;`Gq7{?^8J(ygWBhF(I*Uehz=QM4bIDr-p!6U{qrR#023v!xvNeqZs-5vL7bk+>6 zBSz`xp-#@<1)2X21*4;=hZl$DP~H6ylSrN8{s46v)J8|Te?grMwV|JzSdDG(hC>sN zV#_-b4To_SPr+)6p~C3w~g0Yc>d9-9(EDj>I8)D_;^cJD!{K~tN1TqFtiH4n@ak@YHu5rI zn^WY~Ee9aYGYi@S{h90@Fvk|0WM2a`Cl;IxQx0*OS2*q=oV-5e2w&>Z9F6{<+EeK^ z&?o1!6D%#H+Xtc&+7|BWm#Bm7*up1NxDHRMv~{2vSqGYtb)Xqp2b#e;+=)I4Y05f0 zsls)jGqMh1M%ICLWF2Up87XGxIvsNGf;yJNKT+vQ&?o2DfOIs^Ms8!M=KwrnuG2`s771V~)auX}CeYN43@UTI)9vn7jfz=Q%h3H|k+0h#AE30s!O*!421y2$$ z?ZQv`B^F{^QTTTvT)=-4X$wd*vVb%r3rI7vfHZ>z+>bsAY03irlL!}(&d36a8CgKu zkp-lAWlDM-t898^IMgaC7nso`-XD;yU+NsBNGgd8F&&l-Ct%!|A#*)ES9^Fr1=>6T+Q3kvsJ)xK99~;Uw$= zIWtVBbrJRe?tehdO)f?a--TM#$-N)yXHXCC=ROJbcdC6|u1x_>)_I*e?1Z-m)WZHs zzYTqI{$5CAu(%TH@GaES2o6yC#}pVWQ*L51kd{X^PE5zP7#Ds=9m&C81?yB=MI1aY zhj^AfstE?4uy5)|9mUFH$A0{9g$sX(U`W5=bq^5U+SG~in_(q#V7s&jhx91e}fs%`B z+oN~n@VFmr&7CmuNfcI5NI7~N(h#=yjsUrsnlC~|_8VsC@eZ8FTYkD1DdMB%QAATyE=6hoSv6wi1m(e40L=jl5+&pXT-YRc$unO5ssb zX!;Z$g{E(EK2=9Qfh%e~Z8)Hh$P|r2e40MZi*D~PqSSmbDKveP^Qoc&h1|hAsy9f~ zd@(6BeL8_#Z(eVrqEU!X)2By4T*jve_4(9(h33zNHuJ;A2#vpSM+RFp;$gU(;wZg3 zQMq}&#GFmIn7~3buaDi-bk%Ak2EiAqwClsfgb56OL8|;h{OXlqs?uM&J~r1$s&(Kuf>x%U%ffB3FE6R`L4FTlx%v#UOjSgP)lAS9`$7B~vF;M$ zLqhbk5qBq&>QxYvLR=uky%<0x6Dbw(twg!1)14j8%L3QgQMp__Cj)Pt4SoagcmU>a zmTHSo$;0p%NWF4(9CdXj=G7OPQ+g?6Gt+f%`dULiou7n4F?#w$S|ONFX*4r|I#1!lUVn`2vAaha&_ZMAbWCPR@S@ z66YW~i0l0jElAHj`xCsKwmb4D8ab$!T&pgEhi@nCTHx8w=`c>|k6$nAhBvlmBR<8K z%;JB$CMa5{{4epka#}wCN280uKZ^A>0oVdRvjrgMe_%JGO`u+<0Z^QpmErY?v^s*(c0BY_B*d_~j6o6#}+hzgR1Nequ`#Wm}ecp$yQ*+dp z%2|j1?K-6UAAs*S`a7oiuTxyHcAaH97jruKGTS*S2Q`~^T}-)#3tUfNtos?5zB?A; zYBcRo#nn)+huZ!a+z{*CzD1%1-e?cP*}f%qLE>3Jd5GM;6)!YCgS8AN`Sz`Oq46!O z1voz1x555M{0gffnQd`-n`n;p=H0LM?U+ntScg$(p z({cYm*S8^5j@AyMopKL!<<^4w8od|jdi3rVZwsgiG|!o++tOPHy3)r&E#{oPVro@t zVAdjN`qaF$2t0`;*CJ^8qOqC25@zJJkc-#C0yf~)qUIfZ{S03`Prx@%-3}-JUd;)% zYJ^*VcRws|ZjswCu?hR(6U1~Ib1|QT#T)#zD$Coa+fephms7d#uEG1PgP+k7*XUpA zS_8m2_LPMQIb>Bm@y0l(lH)8;dmvAGv9jaV=fSj4aYXFjZNL#MRC&4h`7GLpa|{dB zU$FV{6}OND#nKT!;N!x<9Gq=t>o!QLCJNUBz)Gh=yc{ERoR(CJKqv*~IJ49e*xQ*R{AWS!~4(#YJkT4YumJ3?S%h&BqZ3BsTaVElX8!6lj;Gq z*bWfP_atsl^zb>fGIjosuCp(Q=X_zdRjRa3;v>M0a}mHrY8|x8pp~8!;eKYgmG>pp z&j>#V7{ZUhrcBkyM(m=J>P;{k2h7&kELPnhu@u*1VG83(J>zAVT>dez_~Y!<7pAmy+0S7>%oJDY&+;Yl?T zy8DyNs|Gfug%Ax5Zh0LqO)4BJPK$uo37ax?B4kTL>|nN4`nF1{31F501ZQX=-Wy`U zz$sVb04!3gL7EJ$Oq~gS2C;hEa&<0%>s7ACW|7(q{^g8}ztVY7dYIUK%+@`8wsM!g zdU*w~r1})hJ4i2m6w-2r#JHP+7`dx+gAU(k5JwhynrV&O z5%T92UawSYX|IT(T-weFyR<4?T6{i9{%jao+7V#N(xR^~@p7;rF1Sr!NriKQlc)_s z<3l_G0>Bc6_bOLM!(W;c0dFv*;q}YaVesQ`mO2Iso)W@Ypj`E$bC!A+o3Y|bsx~-D z9DrS}euP}69)er~EO#U>wub_IUcjva&Vt-*K_B2Pa3s|sjPy=uv(zxigCI1mom9(# zPY`?;@Tr2g|JiklFiPT&1Md$zsgB1*#c*ilY7Ar<%4M#z(aZ&DhWu68kdsvBfLKME z+>elTp)FE)VBKi~4ec($<|V^_CED&ibajoiD+7BT+45KV;x9O%7-n0%=J@9}OsW=@ zaRvj1qXpzRLo${eQ1$~{qT(?26`C$q)g{0!kpMV3%U_Fc^KMY;K_F%72<$Z*!Qyr5 zR=Pp8YzqYcj+Nb7rdr_*!xCDWv9|aQd#Ph3$LS8RTn&RPQ$M5M4C1FqiB1DCA;gA4 zJRO&Zhs=;t5kEmnbR~c?^*cy$SW==R0hg<8BKrt+T{bGyqt~UokEFX<*+`Q>S`MIe zTo%-ASgxiLd7KYmkD`R>R94wWy$3i04r0+W?@K%N6J8n zSo%L~Y-?QM%Aeb?^p))HyR*8JYAp`)r+}5IMOhfNPpF(!uYhu^Q2YpGoawT5F(_Yx zG7})es6Slie1qXBfBCE32b{yOO4R{^b22s-vqKloGQ3nq1H^$m5t}mAAPcijZ5+y% zfZ0A^_7LWHe7rFpvrYr-rxGxy0z}MfurYt7ToBv$Y`c8N1j`WjV;NQ`PTm63?Zk=! zaK={{N2vw+R1T(T9kvUZ<{#On8E48g_hg%929wi#G}|=wai`*Hm6xabBx<}`^~5CL zQRu(s;tIC!2#5vv^>D4p6YW0>L6#P5t7j9SPdAzmaRW_io|p{aGqNvN#19gcpifa_ zAD);5JP}V{k0=!0hon&R#Ya>Bxd^~71gQC9Qs|BZ@=pUm%@u&^^!ux{&HD7!*^#M`}P6t5E7n4FaB+!lk zHD62-#q>RlIPY*&r$SoVRZ<63obxY!BJ!0(UiyYX7MWfI(1GI>M@HiE(15Ikam=u~m?-dMI4C?0S1CdXYnkOa$_!7Al0g2a{8pC^H67WPcx)T8? zyb+{O^TkI~k68!c5(3nGF)8#?4rnd`YQC5vR?*k;F8C`w39<#T4-eeOoucN8w$t5o8LlU?c!)zW8YBb$0`3M}V3yCWU^NZTl0T z=8GxfEc&M010RLHnqn?|^Hg~*k6FjL8}DuW!!GFjjY;Rbhc6VlgOp0=VVQKkyS!}N z^Z2q!OXvGk;>*Sd5PjK*H}$d!I8DewI{!v(lg@Vz()ni!Ogi5sNaz2kYts3yK|23K zJ(JFNOQrMc%w!%gTenM6)vFUp=hw#wOy|o%h^F%&E1V{}*mV9!j3P+q>!JTtI=|Tj z`rT}^rt@)&V*UeVa`5K^H^dm3ARzgdq^OpOH;WC~73gHKV znwHLI5Sh-u3g*A1^ERR#1=IP<(RJ2ze!uDd8?#MI=i{KH^QR-!{~?{Xi&_^+4gcJ( zNmYW;#?$$~O^24pobx#BrHpjGstHufY$fL$4Q3>rx0nqUN#~b=8K(0Y#Ef+QQSj5! z`G%(7W~m89)A>E1hv~fKbck`obiRv0PL46cbUx0=md-Qf=AUn)bc?3*XT?x1ZOi(0 zX(Q?UMKPi*?O-sY>AdZuG}Tv9m4TB==i`L5bl!rOnbsNUd_FEm-EL{=d~b0jRS`}S z@pOI)FiGc60vJ!{Z@1uu0E2Y?ON=y3=XZd>bbTK1Af0~&c$m&RIGYi_2Y8UqcWjWE z&Mz`^S!uSC&YuQikj}3~$RM3R48BM@f2ZMZh_>5~u7Y%aI@pnPegjINFB)bIbAorf zCso5jTzUX2Q;#Py8IsQbf|BVjfJ;<70E%z$FIK-mmZ|F^0p2iO1?l`M!I{q62o}$p z&eyDz>sUfnGge9GkH$zE11wivAHI(tzXDjUa)j6eAA*0!3@H_n>HN6> z%GAdo#bHV36M)NALy;|ox*!{s>HLEL%GDO>Zc;W9)A<?-R|Y;OoB}3KZ=c% zV35vh%qvXiL`f84?y%FPqc9lf-EiAR-ZLUWwd@)7*NZ*`C;G^)09s`-e ztA0KJYQFer>amXkIGO-8UrY+UoNap%pyrDy;#B(DJPsd)_tGYiDLhSpnlC<@I+ws~ z0@QplDRg(XT}^D&GUd=%cqr$DCgUL!!w7avW%{z(9z5}@XbNufVr+dm0V z^TiaAKOVkIpN3CF5ll(vdxq(JubgN)-#3-c_msS3DO$wR`Eze%UQ!4knwN+-m6rsZ z1{W|d!RKE%3ij<)e-nGCov6g9|3BmXBjV+c_5 z#Ya=Gdkw&J0@QplDfGK+yO;nqUrZ5q&^Ki(d=&a>ik6Tm7L%%Ijo{YGgvGcxv;tiwW-tOV1E0uj3j$}H6F};r>7sx z;!PdQ0p}+)W|Cd!2$N(F3X<%SMkdJ~933Dl$#cfh~gV~>+0DR0s+mXzNMN0^jqctQy8b^TX@NWB62Ddye@*0ddSma20zQ7QdnXN4H7BC}=Y%v=w zvdDjc87^`LF=LS%<8+Z) zrS^BMplvr+~mB$;H5fBFa6$!y-!3;7frAMU=XDV~IZ#(cH|Xv)M`! zr8|g05oI1i21S$~phb!(CmMdAXuC(yRZv7Z8xbN!l-H}~I=o}cKi9muyQd}9c}L?d z0$7=P7so@KAw`rEK=}#a5*3FRtHaQAu{vA=td9g(Wx5KAD9-{3o{6v#EG|Wqfw5;I zj==?iCH!LpeTN&#x|!qj23W2}LYAq&(QgKkMU?A7JWPnqggCl-u5+h}l#0kAN*RDM zm6HXQB1#JYIG98Z66(E(7mrkjMU*$CyZzGLf@~xfQC0ycosrDNJ>I}dW|Vj0OsRX^4Q57pCxgkl#~d)@qymB)rk>wa>uo0HS<#-yL$Z}ZB4n~%vTk|Z-5ogMB)B!VNIWm}B zj)Pg21IHwf58L+?GfwyXpxPDpr>b2RIL}VZR=dU{fJcoh1XH;_x0jDZ-u1L81bwZ)>1+X=F?U|Zds z0DXGzHi)h?sd-{DfX~Rj0JPBCP2*> zlR_Wls2(Cf%@crWb%nZoNufSNBpnmU)jNCMP+F)4I+ww*$NnlGk^+4OCH7d{Ga;`<;| zc&iCe^TkI~uYV7~V+5%AVp8Z2*mgSsYQC5vKBe!{58xB=BTOmjjSNeAqtZ%x_~^2E zLT98@LB?O<#!Gs&US<{K8-$9M^u(L0f&`qe&=`Mu61K(c+pGQ|ObYL6`l$J064mtS zlD$B0Axg~`lR_sk4et>G)O;~Tyh>mFkKm)w%_t<^J_2HL1RjMR|1r=S=R$n_2}JId zpoo_9KZGaQV>8`|0DXG)K8Ut7sd-{DfG?5z5s-Mps4=`JCIL@Gqt6k5!kbD8HD7!* z^_b59EFeJ57n4FS<$%@_pyrDyViSEW_rpiwJ%0dX3U4O?YQFerYDM5n0@QplDRfu1 zb!Pye=8Gw!K7CuifRDnv;46?Ryp9B@`QoFg*L?}#WCGNDF)8%BY+zpU$e9 z`g9gsIIX`0AfL{vPFoJ_b7n$uYF6unQx`v-RV&NKsHOpwPiNK60`3JkurtO}Ckr?V zfP6ZuAPe|kfb!|Ada+MiaRu51zw0`Y!^@Y^&rvnHz+Y%SZN&wvCoop;MNG%t2GJW$ zJ5+Vwg*qH+`xEd)+`#so!%tgv;mbVrX{)X*gq{bYeD(^Tcgs)kr=#TaRmY}%+Nyin zr>&0Tr>(96Q=X*5b4eY;&tBnk?vYPh;dAc2@%dj&10T}Ffg<8+?(wDY%~J=e@zj7X z`Kl3Y@gUUXOEG$Wu4!sw3uc@|Gk02A{T7ya5NfLI#OianN@)*5wXDyx(+mL7vy*sJ zXQzPEnjF+yx^dB;n%Sn+T;rhBTuTt@|4?(ai+Ys_=w5;fF-9A& zxsEru<+0Fo4E9n+&2@?)UT(HhXgVFtNIB4AHdv$_I3LWg9GF4OCWT4&VocJLKDC9Q_% z4RDf(KM2(kn3U;`2NUrKvDyj$Vzn2tOnH$2olO@(4X<2q zJ_uzaSUl^4P=_!cOPFESaWW!&1ZhN;=B{sa(|%s-KO@8s1Gp-3VExhGiqMhBp>KX}c__I~B() zLDum4#YRdnsNtQDd4-j-I4@EuyAH&#Qg%)(pj65>fD%;7wn7UkWpU!aSIVw4A=j9# zJ2hS@i!NSmMx`vylybsoFf(c<8O#Qi@H{V=@tTP#4cWf8 z+U1)Ql!oH|RMo@+&)SLEs>x>Kc*O#?YGNI>3z_DDY}1T0Wtv;EO*4bZX|BmOOu=#$kKvs^=Jb0>Al}VXqwbK zF&V&TWS=ecJfafx25RiX6O(`^V&;$FQFxD$Ld_Q+P5tx_0JamL=8H+84{}ro2vGCI z6!9m0bAE!4!Yle2WD2kDTmaO3@zK;{4*_UTfSNBRgZX#}YG;-jf^2`nN&%@>nGcW2u>2~hLJ6!9c|+kbb z4&ZA7)O;~1^apI4mAUn#_(ZgVDOHo{Vb$ac<|U~tr8HGFnJ#(BO0VLze@E)d*nlC0%O`k6L3+PUw)O;~1 zbQ06>z9c}+7gNOF^ws|dJ__B8LgLj&|HWc*1RjMRk6c+VI}envbD;GgMYNn;d?yvj z9-HaY2+*fzD~R)GQuD-Q0AC_sML^M{7<0`GYO z)O;~1^imG!Jp$BxF-3e!U&~7HQFzZ+2ARUEv;Y7#UwkyRB2YwtnlC1W?#i~u5uoOa zDPjnHTdTlF;ayM-WD4&>0@Qr*(bVgz0w^Uw%@>nGzst521gQC9inxcqDfo#>pF&?v z@jv)(R5pRGR*OdsAB6e>mx_Dv-<==S7x+lj%EVlJO9B&EcQp^)B@wHEeACK8v?bOt z^(`#4%p*}N<*@E?b4I$Y3wcg!$9POeHiMUu=k+zj!DcJT$fsaN@;r;# zP9u5V;aGw&&&wcY5#2L@l+-Qia%~lrqH83NKY%v=wvd9jO zt8kGsh#8CA6#Ud8=#Hs=2#6Y39A>e-q&A$+!G5@^A*H4CAoo~_wtB7I=C_DPxO zvo#N*LHKNqW!f>=7U8osamK$qTXPWEqPsBqY|Zax5Ct`Z7l*qj`fSZ#F_e3$;5fUN zBG1+wW}4eDvX_npGn$uM@TgQ@Ni`XqR9+q@q~+xnY+zbv0(tR0q&0k_|kM0HfUw4N*1DI?d<^|wHG;DsE;6WJf=K(^PY74t#rIB8;M!_ z9RPxk?}Ju4B@548iRXb*w1uQGlec}=Pwm+tlMkYWnS7j=%H#uLn8{Z+fowoz@&SdJ z{7tg_K_(w3MlyLBnGJAUY-CB*7>89jvN$g_GJHY@#BgNoO&}XkY7FB+32F>;pamm~ z6C)!F4u48{8s{Pt^19R*IoIfSr^FfY8pCevecPJ9-^xFCW$C8uZq^tq`<4_tsY-CH zhBbybLuw3{fD+aiEM<`iA~l9(phRj6iw$<8<*>%^C^(TCgT?G%B>C=fLY5jsoGHn7 zeK0d>3>i!&-#=mR#A^)l@QLj?T)d#d5cj7l3>H{pr)4V)YmH;01#E@EI&2p*$vd)5 zGR~AqCbLa4gULyb0W&^HQ%JFWZ!v>&9}K1$_ot?5fyeD^>@=S+j?EUZ)3grTg-o-0 zuPpmA&Xj3>k!_k8OiuIVEYp;IX?uPzHp#d@HAxF>wR5qP+-4lREnp{U9kvUZUeDXva zR|{lm!M1un0s8db8W1ceZ_t05xAs5eMko zemHy--ozt7rts7)0I2!mqp8;y0w^Rv%@>nGf55h#2~hLJ6fuClOYvQYzKD@9rCPKu ztQOtHlzZ}PuJbBD_uf>sXq}|hZ@?L=7TwV#0oQN<(X?8;skA!aoW3fk7V#@r^)56h z<^a6vjWJ{j?{oU7`C<~)^y!jDKy%T&n3^vpg-&8FULyk3d@)5FLtp(P;iJ&aC?wt> z0%CFm9)%uX1hn3TEEydIZ89mM}c z?}iOQco(z*nZmo705xBHH1)dH03ISh z%@>nGzst6-6QJgcDdHpgrnH5RLSIc$|5lcaCe{uvPO23ITQy?g);#Ab{C6L=C8GxJ z<6+6@NgThyXX751BlgiddBmnachN-Zn|Gxju`TI!>~}kfmH#Fhvk>%Hu_**S92A0n z>0=5(j|7FCZ%;CXpGW063x4tFJTve+%+`G*ss2Hjc;RMYjK^%XE5c_KZYm7%HnWv% z^-M4$H3f^=P9rsi>%k0b3K_(Vn!kLN(6I_brWFFliVNS#fuk#42v`D43IQhq zj28knTkt%9K_TFCj5I6+90Y-dfNOyVg@6}aP-y1T!fd4w zFbu??5O6y}28Dns@I?v%oejTlwB76IDkua@1v^p*Sd5Ph@hg7#x5RAS$CJwGj~n#B zaD)EHOokK!-bbWO0GG&j1Vsbj20i?^K@W)=^pOA~Oc&+`z2Lk-Z--!UDFhV7K4fzU zGtjRt4fz)jcw~UQ&CDU%kE~noyiUoued*zlUQJj36In| z_-4*mjANSxY))bwc0iJoXuPU2Zq&z_l9LPsGb1O-U@|8;8qAEGB=`)6?fZaTlx@K@ z@=;zb|KSzE88^VOqu3`*`}GneUh2*W`&d?ii4z1>5Qbu2_oc(|g-P6wsvRiOB#yBl~js z)QPAB?MaP&cw!RpM9l1rC=}kgq)_w4M^iuD3BVNusQF@2=z|>9QUcU`F-5GSZ%!BZ zD7>O>AX9kH5}@XbkER~m6~H?LsQF@2=;dsCkN`DbOcA;3;cIg&d=%bG-9e`C8WEu8 zi;t$xCD4rkHD62$-JNZR5uoOaDdK$kwjT!{g*WkdkSV;G1gQDqqp8>T0I-4pHD62$ z{Q=wFM}V3yrid5lyR;{KB6h)))a!*X^?He^*9{$Wos%{o^?EIpdc7bQvIF6arCy_l zF!kDsP|?&&yr~P>fU_Nq@u&IxwH^Yam;>;t_rj1Vym9nV^Ti~p>C+`A04*g-%@>nG zCovbVf&evNOcD3cSN}x#D0DLliMNG-m>hvep~v?Ix^fazuRhQYkRn=6UxX*wV>7Mp z20)*lT?~;=lbR_7z{FnSFjNPHD7!*^}0a-+7Y1Ui%Fs1W!wG)sQF@wIE%h1CGb(`t0|VjccZc? z*O~Qr=bWh7#{856Pl z0Yr~q@urU7fO9T6NW^}@IaYqyV@HsPT|CevVmpIG?2MD~pg2b0?h5RZK_)SKGnJUN zHJN08vvqgkvB&|LiCKpjkJ-aL;AJFc#~WfFvz6>&JD8Eg%wo3FNMe@26vD(TgP4(+ zwFEycF&kp~J;Q9>oxD7;iP>P#!^F&T#>Ti|Vs?Q+X2cj_Visp)OU!KR3L9k?zI#5k z$l)FJs|{{>T;v-t;*2}$iwtqO*~%h624-ZDEoOs77Wr#1!$r;@W-M||97k!3e4FX_ zF0*xaMHjgf=;0z;&O^N z-v@w6_PZKjJp29Ff|~&b*>B&$(d;)LpXXur`zi1s`)vX|%zk?tJa3TAe&+*^-v+N- zSI&w~U9*+!_g)Z#?Duap4zk|~@I|uUCWhZB+O8GYLH4@?>`3;zt7)z?#4sN=TX#2J zOha%R92jncBZ-JJB>No>${zris5p$<;Ao25;1b~eNPv;13v(MBNN^k6MzFYKzujZm zZ+D!|E#ZC}h}myx32uV}~{^C6r`FQDNWi)lk<9WTp9lH1?_f{yQlRyrjM z&)tpN;3?Wd(wP0)KCesd*)aRvJUz^QjA4Q_+ChZf}Jabjd-!3&O3 zZi8BDcZ6G}!l+!`tAa!HL`kx0oG_q_+F8k{KC%oGGd8vtVXq z@EJ^|wzq&8&*0_OsqHyjydZy%`&0S51^%+rvibWz#*t@s1LhL^fQWV2E@YB}hGv;$ zoGFuR0cOS|GnkxYE|~F2n%m&EZ+>Sq|J=`lX~zAjX(-I8&y%B-=DIn4IS1EYp;IX?yM(n`GRdnxq9<*tytAwla>67O<1F4%>xHvf;2S z`!ddyN&c2?k{L`+^6e~>#BaTBLaxK)MxR2BxsE3$0gpmIGX(k1Xw6#8DbTJUPqcBv zL6#P5tCtd>PwyQHaXU?Fo|p{aGqNxF)U!k-=&RJ&hbJZhPsGgA5QW0~iWF+T_-N{< zPX&Vp8bk zY&(+xHD62-OXzDe5K**&tJRm7fGa%@-d{z5Xl!O$bo)#iY<5ux$?l)O;~T45jbV(eQ~l2PSGU`R==6 zE$02yZNzsadwm|9SoP)PnXJB?2_TxiiZ_+L2AqLU1=W|A*)MzZs-J`LQF!msN6iO_K;qp)jp02p33wtJU5Ee_-gZ)` z`QoFg$6Ns500C;gm=t;`2c(_`K+P9ZL|yt?PJoZXdwwFw6kdA*)O_*L)QZ3W0@Qpl zDRfu19ZP_kFQ$lT^lhC4ABA^;2ARTJM1YzvKAL*nMF8$3K+PAELchzl&k>;Jiz(tw z`lfjBQRu5Fsy)NPi!Hc}Dh%Fj)QEX~Dmho-zq{WSUdFnI68vFVmO0#CSa?b7FohRb z4Z@-ftd5Bq5o};klsP1a^`CF@uui)>zOx03G8es-eprh)byx?SLUK@)IT0stDaz~* ziZa&^cN~t*JrEROE;|)@B1YhT5!jsk{mFAt~ z2D5b!B-LDW8^4=AGsa`myY&>C^g7}9D$X^;#bzr>?{{EE>IoLJokr>jM`Ma%Jt2db zQBN2Mep)?YrRjH#*}4aK?P`lQ8uYN9U^(~3xM4lvA%naUV}$jDI3rs``roQa;GJ{(lcV!vYCD@g2cv8C75Eq)Q?8>!Z zMs}seY_Q0#d=JcUS7s11cI98-+g&+JaYj?BVf5c!uVn1A6n_}`cDOj;drr?X;ARbi zmqZ)0l>u)DQwEIWiNDxu!Q%|c{Vu7tjfj*E z4F)qjhBAm5$I!*#+ha(6pZY`7@8@Rgejhy@ECoG09azryF>Y`=_yJWIi~O9%NM8OI zu%vnf(JD93#ZvCak!m@)cDI|J!&66`5kGbCB~Z(>wuiR+LsH$C+9A2A7j;35#~rc} zdpFo2xqMOEACPvc<5h()e`2`dF&O-SbVp!v+#QLw;c>T2jyrzIkAQsu@>mOgHhKx% zJghE&mxt9X#UG32*U`{B7vA8Rt+PgER;>q^VV`ccQnkJsL{_aAsbir@t$Kz0M6`Vc z`5`+vbi3ms@gd_Ji%U@cxrcD1pY1rO0V`Aev0vg0DNBzBWgNgIDh@AJGvHsWu7fO7 zbt3`zlRf+k%F=BF=R;XGg2kmQJuz06z7^xKgwbZK^69K)XF1Nj0ObI^Y!kF{^^y!; zXKTW;^rL7pBh}#a|olD>EO`>_b^Q zE(?plabBwU8^jBXzaN`GHlQg>@3_o9l(plsp!gdnM&EK-Ft-6}rj9vVmVO&YZaA_y zFEz5H`VGWzWUdKh14>!C;hDB9eIm4AWN~7AWHvzOjFEkd7~#m`yvWFEjf#$}g$ZN> z%E-Ea5){lwLJLL~C&ou+1K6X|?#-mygQGbdS)3Oc*&iT=Yc|M?%m$Q^HO9+27+Ep2 zU}SM(WMskXnNmvmQ%y+zP8t8)Lp+3{rTjP}UdlfnFD~2qlT?(_#@XF>V>Kw@a#+gUcB=e- z>CK=-mg63SJ#0B#j!(gfEQiJHU}QPQjLxzgai%Os4=^*9BZJB1s1Ih=<*+@!VMfV! zxAX8y4v&sFLzd%OP{QS~l;`YJxg6_3i7dzS27A?VxE!y86Il+6*}=$iyqs-0;!IhN zJF+cD29wK?{I}(>J%=x?;0{RKpSn3<0sfdE|5DGRzHJm~EOFOiuHuf1Rf7x=DPRaUeBK3)Hc*vD2(;9Q=V){-vgA9kvgd z=0(}28E48g2Y{Jz*k&*}&1PU`-Ae?2oK2IOCnf{}3EN6QJgcNuigs z?Xd)?`C^I~OkbPJ;iK?gx&mYhZ#)5NzW8YBTmn}UpyrE7p}Vu~jRdIqVv4w%zU^1S zN8wGp3SncdF!qYfat9|@uu!^1RVDrDc0yR_RHS9>epa=6y6H@sQF?N z)%59-tARdDl$tLlg-&AN-c|zCd@)6QOke#{_$YKU3W@g{0WmoOk3x@60$nqOx9-ZJ zHN+5$Ma!9u@FaU|rn?fLPtQh`Q}?Aw%@dOWe2F}UfW(_Xjp02p33wtJU55Y^-h5K1 z`QoFg$6O2G4g%DCF)8#?4(MqD)O;~T?4YmZ9QY`_=jVb<;eA1XnlC<@S`o@TpdA^U8w^ShiWY{u^*KZQWHSZCqO#vQlK zyRLIB+2e$Ljm%BsAY7{;eaB}o9LX& zo+8dwbS_}Pl(Xg<`0l2ET{LX|a~K#-GDo>i%?E)#LB^f?;Iu6RM&4!sxw#eUWfC@U z@zMzuY8#Qeq9c)}`5Z7tznkzq(J`gLdkNpaAu^9N_%p%}4aP#GbsGe~S$#`*jaiy@ zKhj!D;!V69s8GMb(Y4jB(CNGtorrMSIVS*UEzW?Mprd7!iRRVmY?E?=88lz13V?K( zh4!jK6;i*}?w$*e$E4m}mBEj>4I7my}9yJlzjj;H@w8_*mC zedt_d$I`MTrXnIWsr;qybC2E#c`@4tFgZ@UL2P_GdtrcZA%Zrm)G5G6;eR(j*iZS~ zU;)Ok-EzBYxrOsQIxFlB73L~65zeWMFuh2QA&FqaOlOM~KbT{OVe(C^tBBkjG*M}7 z%80CrE<&*O6>1KVTP?Em14QE*1+cymcHZ@%ByiB)Na~B0%9YM1j!CR0vYLy>Rfz?u zPZCrNaVB(#5Vk# z@Bq8h(_blQ{SDzE7M3H&4Cp5!r)MBG?w^E*X21xUdm@mt(~g$#h+L(r1MYzTC!Qay zQt%>Vpdj=r)eY#GWDE^vmCubmfu0MX*C{r7IN()k0+5AlW>zt1CbL+J1YQGq_+z7E0IBIM?pBjn*RW;(i@E7wk<)dTx~i} zjgG@Pw|AE%c;Bv2hXd=g*sgc?*3zJe&Sh!Nb}i_8h_7RkWLRk4p5BL}%y3ohF6~Cn zEomIibPSsJBJ`gu&}!9>(5cE|oRS2T(-7MZCE<}Y+=d-N=ur#Nn`$+NQ0lZVQxSa9 zKAv+fhP+iJE(EE;ZE6}ee2>F5#BJ)Dl#zRznhS%w0oN0^sg)@s-&w8J!|HQdYTU6N zR;veyk4WLE!R5;cR;x|K&q(3v^A1QA>IITE+X)IMoJECto$w77Ham4Eoh$62A#KQz z-HGLVhj8kxAVg~J1@J$Dt8GB(%0&H=$ek83&hO~lXq{oK3iT6_XR;xG5V_SJq+Hx! zcheJ$v8F1<0gnHD)>&HW6d7<$_xa>3x1G?LKk!rT-cRthQK1?TwwE)((Jb$lYyh}1 z;XBe=Uni{>Ko$ofnv=7Zt?UcJY1fv%2SU3uZG0<7@Pa|$o^&jU28Oek&ZTM2b_40# zz?NKTr{*x&Bj~%CbFqE{js|c6!P_!GyK5&CzR&g{F)P$GI`5AiqE)C_ zG@p(hH_pv!KAm@&*0^}4xjv0kp>Cq{!DtU-@cLLy@9C-IJ9^lzC3JUsg9^2g-g~T< zTP)kdblz*7W=fmrd@kw?UN1E_1K5iHC%t7s2~+be_&%opy>$Np_u z|L5uceE1sD|4q8T8GIe-|1sU)9lpNw|Ca7Af$vQE|4H*V9}AyHemb zEe6bmb2))pF<=#(8wfOr0T03XEP-Y*;AJ>>5onzbxc~Xwb>0KeugK+S_Cd{?;yw=V z_fQ80-anuYXyv{EZ;g`@&dEjY9;o%94rt@@L7nZ?Zv@Y&IS9Uy z^dFb*9}C}P{2$yY-9H_^S>&IX?q3Ms&GZjW_pgEPe)@-}`!~V2h5nK0{%!ERPyd*7 z|Nr3op8oUG{lCLksW1GK(*61HHKPBLbboXBy3l`Fy1y5ECG_`;`tx7lB2}m}h^(ez z&kjz_(eO>8|0=E|{lSV(g|C$UvNV5%nhWRPE2GZ*dxG%Gh+IV@72dt=fa|P;zof{$ z8|qr9dBfdDp*~J^*zGEj%qvN}2xAYNc|-6nn%D-5xlGY&>gGf5Li9Nu& z4;_?vA6w3G=wP<^#9Ae&3nad<7NS*7d~Yp8tDgAHTEp=D0XQm6lv8q=79=WLYd9Yf z&bQX7IZYcT8d&Qz{)$=?SUj%}MOC6@q7AH5ES%ola>kJ}&2l7*ve73IN}W|RqE989 zI=!Y^+Q3&4KF=N$Y>l~=(|JBe!s9_k#IEi8%{;>6Z5yU=7Fj~%g0x|pkT(&z&>}KQ z8t7~_kx4e1q2EELZ=KODHW0Zih2WUAoj*uqiLKAbOwauaU1(0A0$)1>_L$ z9FYfYRVIqOLgWT}9gsq7Qn8KjBQ}Z8fZry(!d7K6;13BuW~(w8@P5L{w4Fc>X7VkO zIT?t(9{-u}%nTR}{~~g224Wi~`UAek?jsqH>9IPI(ricpk?S%L8?qtc>+R(nd(M}* z^f;?jGr;}v|CB|+pn_vfstc>s5CBsNE{}pTqE%`JfYk(ViGrr(IspGAxF!mkmOB9a zL~uhCltWBLRiXX_I;_kNTE;7Fk)sX(GCPW3RjbjtFzS>!0;x@8Y0!;%9Z57fERmZL zzUg1rt_k6a%+_XAE7Ra`jx~D#?Mp_v9XFZ5RkjTA=5P7RxfQbbe>lBY zs3ByJv#&c28qU+`Ol6k@;T%P$RL^+!_(THjXQ1U0XdGc}yOrxh8u`_}V~+u6A~~Mr z$k1ZM3N?kCt1O3SaVbj$aVpdmgfFqMgm?$PnHfw``oejRocWd`A#TAaA{@=dxLGYE z@gg(%3ble}>VjL=OR_th%!s72EFygGSWE9zyLNJrR;YXFoRPNoO_0Zkq!Q{N$bS^x zM&<8VvsEMdA4Ksi|5>oR_D4CL{yCeJ^GRQvx1BX=Qa-k0!MQ`x?LkBB|57Z%TJ>j( z4z*#)@~_xsS$-AZ`Z zsqSXXGg4!BzIUC*0~5}4JluIrH#72;9QmE<3^c_D2jmaWe9B+jg3{%1*II{BD>r_m!e2Sl3{0{YTlBx2GZ;{R4OJP}AfZ z4?t@7mNN7rLtSRJZa%(V0J?OCJy;jdsH<^^67)0~8urLp19$)oYIXL@Iga9Qp9biH z0NsnbCL7ec!_czUe(a7na~-GKD;PuD#{4OmOyAaMv|!XzK#CI;zy&NY!q5n_J~>Kf_)PMlHxKlJ~aG~#OfzizZf{hW_==BFwmd#Ky-gOF9q{3-QVIXsb2qSOivw9kTAjq2XA4s40)et~mFpZes=~oZ0Ptx0GcXYKeM{rx@&87d$2G2Uq4eqK{X257m*>yJB=1b|UJ>3t1gMi=sbNdkxmQ7Xu``Z){nuQ_ zxletR*K8u%)?4>~IRg#&yLlosda5yR{MQCi>TorDM9doP*| z{p-BPKtssqN+4FRz`NJzQ*q0_J-o%#@UwK#1YoaT@+MFY+zc_C08Rbh8zDMFc+|X$ z2#9YQH3Is;a)?!<}l!@ z%d4Q*c|8dGMxZlnm-nb|t^C$vMs9?78`S|D`O5#_BHyRFSGsS0!a3py4ERZe4TiQ$ zhIR-*?Z)mqcun9z89Yo#_8*qbPZ|6hdyRUc9Rl(p^9V&=3AOhnI>C+CNS_4=|4Bmb z$vfTz^m3o-Td6<1+lHX=z*J*-feARrf)~WVHR_u-Xv1f9gAV6H!?C_gqV}x(DjK$K z2nHYcjSLASWsumZ3&jm*Vu2KDQ zUQta`?!M4emyV0Duj^OZ*+~wk`f?UR;sA4l>UIno$ZMuft-SV_PQb2}_i0BQC34!T zmG=j993Wi~XIwG(vr`=`VF!*L0PjZiU*Ii?-w$v9=Wu+lg-4n5*i!*@T5nRjU2mxG z{X2D|dI~K5?6mqFtRWjuOq*?&g?HiE%Qmjmx;Ln*gTd=YU%hwRwZb8_R(+gzSbI1- z{h6iRuZd!ix+E6kAo(>h8Ao4lE>rFQP-Uvqid7T7xp2 zyX3ZX3Rd_+8CX8T)%&m$`s`L$RF1J5*SFq>%%?y+lQZql(*jRn`N8}S1kpFB?TjAy zz7ED)$`O8NdvC%$-{>zp)nLzOecRcfwy>vQr&kGfx)7@bI~rG6ob04jtl;G;%k$p^ zmj{!5o|J_#itLdW?1+3)?$1WqWG6L$5GdW|a6xu7=7KB~wJB62L9gOsgMVXS@lTCN z{OvkRLE%AhP2(!T^}P(Q*9=&ZBVw8Q9LEg4xP^yEQoRV22T@WTiHny6c2b$z4Euf4 z#ph-#nY!%XC~twn7YhE$RBiNV`}o%O)eZxzTFr3| z2k0zQM`M%Zfa&Kq&+))bs#VZV5UuB7j&m}!MXE~;$2kKUvN*`UOu$NJooesT!zaY6 z~%Do0}bru*jQFo%Rcb`u=XZ!K2`t!_JyXb_>_uc`X_O^N4DDJ_jHRqe z^d2FiqM7&mO_uD_!lxpJLQ^3vMhT^b7NpWbrClpU(xU(K^*ZO=d*A2Y`Fwr;Kl6CZ zz2|*i&)4gm^E$7y-q*PoX#Oxgn=a1cW$F0y^nEtn079I8#nsSi8{Qwm+aL0efH<4d zP}y;MFAVq#&cA&P0_UPVU`9d%Bk3nddIiPmCNe6AK&qSo$Ra=*38WS#8@3dj`opXE z0ZBUeha~%f#U#bX#ebE5hP z^itdm$|$Y!exSPn&GwI%zC%Up7>#N!ffiPAHUA1o77~3L5jbxI$a)F=jL;hhIrr1+ z;K7_j{;o6``3*Y+(iu9@sWmaPlS?(iJ3ly-&!K2mWsIp!IF3Ulbmn~+gAk$)h*Lwx z6$qj0R`m9U-ru4Z(*?{n){RamHkMsXqnTFZ(v--jXny*&kk|ey5LdcH-#qsE^g6jH zO$p5hj9Ov{`M`y(Zh@bzKY=f8!wUS;kJi5c)35^f@~!`o;BFwmn|8nEtz6C&>6m%1 z2k*u)$lld1Zy$u9jsb`*p=pMGi$zCqexNOR7r0`3_uRh3+*7aHp07IhW%(^Z(j zDxLo*uOkYN*QUUjq{Owj#M5aieoL`yaj~b<4*Zs~*W$9zp!cv(aoH;wPQ%(o-o#LlCKd5WaN^2%8A@f1VP706~|}@uyrK#2SSYyQj%IARQNiC1lTL$q!!rOx=?&D?UhhRl=4S}6#HR>B&V2h z${&8qUqi6p4R)2&h*lbr`dfxmI3HQ;ts`zRtPNDf zvDL=u&JYAFUqRUH@mEZppMnj~O*75!X@p4483Rk*^-rp$?mU?3l&it^F2Gq+dzQV_ zWtz9to&KP=)O|Re(~o}rFqW512BFKViinOJik`|LA#j5EZ!83)IktlH&t(GtjArp= z`~t*rD8DNcB(4vKm=J9a$pVJmd%Fc)X1^1L|MC7f3%6c zgPss!>g93{G00jm--bm_Roj2>wUo^l$khiqXU%HcH`_w^I zM4veo_I(rrI&vtVLs6#WSI$Hnhl*(+D8wIP&bn`8IoVfLS?Pi(YI$*cY?h5k!Z9es zqK9|~gJ;d9phbTl^E4YU^2yoVpA!YXvO!In(A!z1iGwh`kq=(qJ1Wohk zZO~C`M0Dg(G?zm{SdRqrmplr{iOX^6%>@1#{c$NSdAQ_rDF0R_NZbStF(G;)BuA(7 zPY&hFPtL$7zU1>Ix`L_lb5Jqj*78pdp@%@i{vP7@^69F?-vIM}mKfDBr9!&%Iv%i4 zg%eG6aM|1*;-ax$4{36!EPlH62I2A#3JxL=T z4nvgCLC`{VopW~2B+v}82Xtu{f4SoYfz6Gw2yln=?(CMXP7NFp!5jK zLuzi)M^>Oo-|Pw)s}gt`vBh*Rx(}M{(ux%A4Xl8o4)G03Y5vHnVb+Z}| z$8$a>`W5zYmeRz=+mJ4;PDWy*XTuGMZq2=M#x{PkhF!uZ(#KTCra1OiXs?TxjSV5L zHN>M95mVF0>2FZ^a}rpT8g(d>5bDV_G_|coeSqG_t_c6#gGDg^QC=>7mCcl7@ zsC73iGjeM3kTIQ_WIIl8`OQW%gGQZ+T{etRIknjIX3zupJquNnQ~TD%7{|DPIrUh< zg*8!;4)#O%ud2T1)QZuS;9xtA)1R<#8@(DsS=@*2)kx=Evj&lH^iF6c_KSx>(9!(Hi zb%LtnT0}b$59d86l_()CBSAkQ3fl;{!b4mUxOwqkA;0pjm99Ae2fIF8$Nf-b~$CKZFB3qnre z2uv3Y(j?YkrsCjfOPsogATo!hDhN+{@HdgJhqRGUYz{KYeSlNA6xT0x9{$$%9IQ-V zMcUlDv0Ms4WKL;}H{S!oUByi5)&v$P;PtqEqs9E9@0qg!J`0e|AVS~`zrkr((~cO- z9AL%(b2ErD$!Y31w;@z`p$~gVV>9-~Xda-QL4yZC9&T}}7zS*K*0B!AQx&o?ZnLR1 zt|<5{+>At%i;OQ~vA9n z)xz>qa`i5^+M3eBLU`|Tvl04TZX3<#K^vjpyHs;uZ=_^%o|cc}J~2)wgdotbDhPL~ z_*+b-m)xXfP~HPoaWZ$vDD;<0#>1beK5B#=PGWar;DL|J%NqEW%diOyTk$^$J}#f& z&SU?OX_}unMvZ1l!eTO<-??`!DC`kpc*MzevE+dLRgOk^9!B;R8GXG3m$Pxn=TLrY zCP-W^hnNukW(6)?_$P<*4Q zG3GFTgW-ySP|*%BD9v)&+&TQ6_+eK0g$RRXbyv-jTJ6|aqO4t**sVjlr8`>?ruHu9 zt^BhRry___gBTEoD4{;rU=F_@*_{Wvn!^ika1Or-017&RS6;tJBb%t!5tn$VL7gJr8>x%3!WqO4t1{eySTzzS^!q{m&( z7eJy)oQfdcFo-2#h!Pq+6HTZR4B=zYRTC24U=vEM721Td$nOqv1w@t5##u1*lOXgg z@F+u9LZt~wsg<4fW0|2%2x8qPR256Z=pI-rn$T=5dFpYK%zErJ2b~z}aSOz%tce~) zg)mOG;XahE#*1eQB50uZ*` z$<4sTx0!#r(_5!}y~)8@{^iaP9lP8|Rm+{nQ4qDc3;hd>d%@r> zFbvWprWP3U3%vz~jnE5>`GrXf3?~zMMn+|U@fa;fIV$404gb~B_ndPJE5f9k>7Q-f z=!BR$9>}9H7;28DWiCNdcN?D6t}XQDy*5J6d)F4~c`pX9v(UYa z!{^Uc>za>HnS)m|HF#}B8#}2BS{Q$GJ&Qj@T$V#4)4aj!Fh(GE{#RE9uWsy#zvnTY z|3Owq4nL>*Hm~qQ>fIR#nE_Il|Kcjb*;_@x?awxww6C^H|LrjQ1{5&pQ_$P<* zTpCv~3x*iPI4uy*N%kE0E zTsC*`s=v$|yc!`4mf^2!7XE(xv9Ls0yXbVEuk%K_(-C3$?z-aqc>xbzoQfc#1~I^u z?L(AMWD5qb<}ieLpsT@4c!Pu2CICX_e`hBTUJzA6H*CcalLMhYuuz%*DWNiWNvTz4 zYn@)!;03Yn;MJ0N@Pf6LP=hzM(isCu=!h>xWpo&30;js zu5+V5L8#0obd_pC<=;+s&gLfc7rSN27%VHxX%_wn<*~5H7m!i)@AprMI9s7<;*U3KPX4JrTFi(i4Pr?cqJ%C_ zjX0log&}+lx@to5!Q)^PN z`5(l(O{lvxAy{h(4N2FMrye)Stfg#xHF^&#ZVSZv^vF%<{aX$38;e*>o7ugVU-qwf zlux2K{EbOrS58a=JKq95)NN=W9T6(Cl?_*|?COk&b1km~1l|6~3 zVp>^~Y-weY*I?ca-a{)}0$Ck76n&CILXg)*e*Zck*KEb*H74-SXbZk9U|tU8f5rrf z+s7d$M6Y=jmp}L?hw|koXJ8ax^7#@y1$pQwKUZu<+!_3nLuh3vslSz7+fJ95U(Wx3 zmKb*MAsDV30TuDv?v?VnY;G&#??ahZHUeR=+yvVIgzCy)_y9|O~Y9Bz9&?z0z%0|Kv_|5pLl?iXKmE8Y(OQ`YF3hWe}Qxkkt%%w$5p`>~~?r$t+)vOVEfr!yw zggPNKi=3-*!{0J8} z!&@yiKecNV53E-`j3x5$R4&^6vUr@UITsoU`KfVAM*&yph$jr;7Kmn*#p!z})h1_- zql9RilirUi?r<5BuF(rg-;r8`$J)6=VJ)enQ{~J8>w#C9m9$Pz*7wx=QYTTlxm~?g zW&puYSAfuq%xB0{%j0hK{MIbhnV){zMGYZh5Qch>L)JOFAcr8qKHef}lak|Wfbw>y$RfyOU`UvzV_+a)>m#z+Gmr%otHEE(n zdX{=@SPCPfeD;DUrhl1#H9+Ep<(;GyL9M4<5^?I+o)0qmvJbNhxXb!92v(V2#Fp}* zI*H1R2n#2lfXradmV!t=0m((RPC)Jf?}>OKL>+RBc6PL9_Fi0_my{DPkSdo(oYYIp z@opFzjH!tUbsYJlyoung4a`l*dci-sKKi0JrS>fbLAf1al%pf;!rVR&zuAL1bxeds z$7u{oxJ}pX2gXcBM{wF4gu>n-)cPkSq!J3xD}%^2h?5l|)Xc>=#?E#SqnDA9rU>!h z9QsP9e6uc7hh{hEW_^2vo3*%cq}~x>6{sfuo#r@V@_c(FMw#I9ns@-hP5f)5Ynu2A z*xfPwnL1@8@)*rV#%w~~R;0WD1cSWDaNG%Pu~jALMO+Ktz$Hu545mJO5!jaS@E2L! zC*VW4#)%K?8+0?xmH9D-7VpHqA=ffw@5Fwb*z>{gH8+4yz|WpQkY5hAagL6^z|ePR z>gj4lA zrXoie#t9MbS1$8@4&wOR&~ol@ ziG9kYqQhX~gNFEkMO;Rv+5Dt)MtLs*b5je}M17R(c7zJAK-AqDV1Nx#^xgn)W(x1d zgMD2lwnhol!1P|+73)NVl9mxW*~%dqd_)1du_{hn7YuV%K30G@nJH0 z){U0a^cZIjLrKFTAZ>R^+;Q@fp!{W;^n*p3FjQxIkG@l0cTT@-xSj{y>-$9JgbRfO1ECAuI>?S}=SGF5jD$)FFjhxw#vlAfBZ=5!T zL3*dh=yyQ4wD|5w7^Dv%HHJ72>#A^W2%>(C7_|d{b&PX&KE!IB6TD+2M*RWdN|Ha- zOKj8h_e_rGN-xpN>m>pR)l2l!y#$;>Q7Oy2qrPITP5r;y3H7B8=I=}!nw!GYi+KjN z?7zVH@ov}4BTj=ckoPfwSyRF7+j#gDaawZ!bf!7cf?JhmMX}+leD1OE;WZ7NBhHQj zB-9lQYCSA@4X%gp1R%H`zIj~IgZp+66`jgk7|G5j|m$P`;!WHq?@yb~B z7ay|Rur)D@Hfv&*h9eylScwg<)H44*4lh!wBW#7P!$!l2WXxsB0x$}0h6ahl^ihgB2zfzmF~Puv!H zjR%w0TnV2dKExeolO$O?5tlQVTxN8W62M&kG63>5j->INj0V5j<9r-fx?)_j_4O+o|uV+t6#> z38dHi1t8q}^#H{5evMH)!~e07^Dg9^1`z8Q{Sv#N8rnfW=38LgXRJL>O9YFJ1tHLv8R1v|s>IWF^b`v;7MEDq{`0 z28UL#0_Zo~aiqVwTwc%9;XeEx0k@3QF6DUtLoH3t&}lW&_tYz}0@O`rtCK7Gllmeg&;Za92y_f`4@%#Sk5d0_D&6*UX5q!MaRi#owrZ=2H{ z`J=o7Kq{R83wCZ%7A)gs`^)i5>@z*W<6--)Fagm{M79yy=YuX|YDR>$(!LnKWwgqS zaEaP~h~F}{o)BTxc4#q5cRMFWxb8b#iwTNoxO{|PNtHXEZNEZx6eIp%*O^-YA=bv&~6apR0&n} znkE@YkH;XV7m}(0VvKqMdFS0cGAq39(?7@)rOVHFqr|rIH@%*gRvj0r{wjP@MQQLjb%T`r3?a`Mr$} zfknKHz;rQK>uJdiO$u2$1-92XWrsmt#nvj1w`}nE$aH3i6a(?xmh6PI+tOO&w#1!O z3pAES+!;)|&@?6K4DeV~8bD9!pc#3!K|Ym?gxAe`0P)t%0SK>~ z9jqkXb+e7&b#r|Hymhld+^cgU>*h-U@vWO5L9J}i^!H7U??#S?0ms#fC3qO52ZqTR zfUu3sAzQ*sS_#@*&{VtT3FBTZ{Tq|YWSMgKR_6gk^6Gpo{h?Wp>O19~b4jX`y*2GE z*j3{^Z^kHVc4sXaU`Bn(2==aSPz)Wqg)tPPr$ zm{z+?z72!jX>VZnKs`3!omTxqm>8Y~U!z&RI%bxmV96{*Dra44R`)E}Io8$v4)A)f zn1h>t_lWZ*FX!)Kd9s{W^5j9ciJ%63}i5RqCOIzI)t+mXfKtHf{~p zy)4x^kXEY)dXaZwWZa9ihGO;G5)Y?6`w?lMjYDZST+RkO3VP1c{I&Ew`*7O5L{mVC z6Tf1}rsEYu_fn;#_Y1}8eZY-?vyGrX(k2mg<+@DJFLM1$q!x#PKNT?B3byy<`i6j? zgv!p;5?#rA@G>RVWrFtM8mC?%peoxl5>kr^x=)~s1ey^BeH&0VpagZoRsM2*{apKv z985zMzJ@B?#MWF0#VHH$S@SNRHSbE>&jwgRo$@rx)5pxxw`asj;k~NAz!I=Nk^4Vb zUyZxP`l|NQLc4Z8UP4RBSY3BrHI%my(vPOKhxM7&sTkinqVD|WwCu0b_F>N@PD@a< zcAD!Neb08%VJh8OQ3+a)Yn(=g!9HRm>CRPS>p=GRp8BFh zq+d%|N=DvbSMCuomQRn{a+Uv8rS!p9av@g&)K9Y**6hlx*B-BegqFMmw>S;P+gog0 zmFgIAs7KN#mAwXVQaV;IL)k1RASG1-*(*i#zg)0;-Dv3*p&OHdTir6O2c}y3BJP|r zZd09;D2MGsb|Sw^TPOB06~LjIEnnZWYvT1moC>c)PGe zm3=5M=N*5gG)pr*{Vktsly3 z+!d}_ky=np!6IaoX97~k?f2oAxQ&by<~V%`$$6TupT1|GjI5>1T~)}*#;E)_tez3l zMIEM5ciU*MtN{p@l?Cd;<`*F2rDXEE>I^P0+r$^h_tlYEobMc@>gD@J{E~d%k-h=E zar*mha=y|zIAC%z604DF?-085`nb-f99%I6Z=>bkqwgIag0v0SN1W^)ksBc`H=i46 z_XvFjxbqB|{QT|atDqaZ;=BSDu8x9@NqNh>-F3y03cyA1okW|TmTu(HA`!KZ#p4H zRRQCa)aMG?Y05PQQQ%vi*+jEEi_7N<4D~|In)JDXm4v0lpuQ33$DXLB#5Ja5^73hH zBvt8=(Wqa<=`{n?MJ`od>de$fGS+~aIUUrOT&ldDSy9jKuc^B&>M}BFTBNf@d8yZ? zI=6Ob!yJyXPeQ1OMuLxDjEP*vXbz$|i$$~**X=4gK`gt7p1{>P2^&t2paHzkvZ9)dMJg_wYn|9oIRCO2NA@_*KOd>2X{)>KJ~raS_eLbw6S%UjR0K z6EcP?TxaRL7wLQDjv(`^ltHJzQk(~L{DX$x33Pt7G3b}$X5x(wDtE#QSj*oD4+#)4 zt`Eg6PSrz@RVt%r+XsD|rI2j}$uj_3CT0LJdJV{=Ie;=%zKR8`L_LWGu-27rD+^dl zCU4ty87OZJFsP5d0~Aj|4l>LQS~%jwRk%WfU)Fc2z8isK`IrKtE0m3yLml|FZ zl%i@oF12lw-I|X}&4-fN3gTh~0kW}(LN*ASYK)_hZ6l1xb`lpmv8k5L81nPFaJJ2q z>iG4BZrO~9H>wqzsfLAlz-DZu*vvs_IAAjYB-_jmAj_~BtbtA(7;zToq1`{1mt-+& zvavhunrpmG0R6)HO@?LPF|xp;yY{$25$9xni}s=vJ`c_ZP2!4an>_js?dJlRN4@?<07SYA`l63s?}yr#Z{ z7TlG;K^^wR3TSS5m%GH5d5fF0@uO{AsFsV*qjq|Ca(G~=c;e~+Y*C^M4XA-zE0_5>|Xj; z)xLK5+SjhMJGm*8P_3IZ%jL(+GHhtXxrS}I2rL0x7P)FPDD#sGep{}6Kgv=9Tm{<5Re!et2sd{1jHt0OR5rPVgXQyiP@M?6XO+y z&ia+E8Yf)OTN@3a#)9W`mmr3wCRueWVeS>dlGU4Jbw!jr)T&8V%tU#UtW_LkhEz4l z`W#Va995I7N?9t#n`Gr8#u_l&>a4cccYDC>q~k9!bZfvg@utW!V4jBEjlh6uBW1w+ z8%hZbm;odYm>&TdK42Ep%4uk1d;6NEtUjHiw~5+<=HDhV8NF2(i1O<8<87h~xsEy^ z=QK`z!uDt;vSl3u)b$!>AF)>CY$Wmqna{>lD#QYfNbhlrc5@~RJBZ*!ie6K z$);KsV932q4O`Rf>vVj7L$@rz#2clE1sn{s02?V5umi||1q6_60Z#!LY5~}(MBSV8 zO~qmpFGjb6=SL7R-TwnOwT)*ZWfETvdsj))y&(e|dAtL31U+v(JX519U=XU~_BmYk zO)rNIQGhLO*1$3U1-OE)!{!UADbr;bW3Cd9LivUdwsknhghg-(r3{ZaA76_3#G9_z zt9W|RdJ+gJwF}_lcmCHk$~h@@&VCR>MKL|n44M7I1*>n*6w@CV$?2qlrVJ)}4@Wn& zqNC>`VtA$YxWZwtJ3Bk>J1KHY#5wa}pobtji(_Xa2U+Lf*JqCyw~Bl5OMgPM%QO+w1ooa->0Q&!S(KB;9R5UPAz zVR~KERrIGF@JHpm<)1nz)#=EgXd@0WAv*D0P&v2x?KqA@(MveQglHRv^x&Ty%9o$9 z?FeyP^cE)Y&*<`bPcg0UyZCLL@OcoR4 z2&fFbFCxBT5wD4emittAx`<=ll+e$J5=npk|CW@`R#8lS7s76G1{-ypj}Y|!_yTTH zJJ_bKaA{&wFyB6vR*sK2b70Ce)FrAGuwWU6>gOvq?jfB+pGuz?;N1TL#CtO)M4YC* zAaAV;`v@Xjzws+zLMZiX2KL#1fwABC=DQ+JI(9Ls@{OpYZs7L$jr%sT`=>JvMfxng zSAk}^_!wD6SNahw%UKJzfJIfFPYW9=wp3aeU8!232G090z$j-0i_p5AfS!ghz3QT0 zU}aPiEimFegZMTKQ9^5C5huO`89Q}|S*8kaaG81;06}l|jr07=)aZ}Jto*b@#A$;N z<+D&(tBO#c5BtL`EzF0V1)5c=@?oE}m}QomsAXzo{3{-@{(&%69Vg$!8PY!N zvSl9q2Yb22G={DI3{VwLSv?+9vB9@}?`pXp>3hnlaY_w|ue=p!Y<~im%~1KR)ca-U(-3xPNtJh} zA@#!f5cZpnIzy{31t<4-#EelVJeYe;LU+NH;$4L9CFfJz;&dUdHe;0^aZZv4aCo7E zbCiVofb%Ydz&Q=KIAw7UtCKQGR{8BDoCXIE4;e8!fKU?&oeS=B5sK5>7?1*NHSt-L zsQ~k6g&lZ+zeOlPzu_9E?~tBh$qDkSJI2=Z6h7+v96 zI;U5f9M?swh{3TGv^X7xC>xQz7t`jsfbc+puUjF-Is)GA17D`aWq%8BKEOQuBvjn{&z{Tj5+G$Cy#P_h;-vvUPt_mT`I)9>&|3I#6Zdu`CSULS5osGSI5UKYg?2yS-wfcB+J z`$f_21+A3KNRxS{l7!Qbx1_@JU^0(5!;yx&QOmnq0ndZxsKI2&`ku|6 z2b_U8y%<6k&jZdo{z~Ztos(*Aj+P=vjnkh(j*_<9oEOMo>bckr7+hE5Kj&nk7vX-w zYrdS5f5Nw7__1J>iU&bUU`|ZGL8uzdWm$l?beyh*G1G?FCmu z3kRtTV1YW3j(6)sn8}~WS~9{fa}${Y3`ES*JOy*K(j{9snFMkx4Q{LNfaAd$a9*ZD zA%6p+vIV`G6nnZU{|(XSRBQrm6r2O6Lau40i(+~ot2jDkq{;p12*I3qfmcjRcr|m5 zOKY!ays|5$URwBQH<5uLpII@56B()#*~c7gPW-&QN}Yn<1v(YB&{9p27FKC*qXy;-G;`l~n*Yr$;ifrbnEcd6wVFrOK>cQMVfE0E@be zjQ;rZ7W_wfQ-K*bI@O8MblAx>gyOUg*-dDKLCOQ&rvTxC#_4LX%?Lu^Vh#dcgb+fO ztw+ux!Th zzglgwrPffgr`7EM?0WG1w zpwSz6Tj8YJ43lqLVRza#EUS%o`DuA6%(7vYX6bZ{EW93{I6LAz$*pmm%cNH9oPadR zQ|4&If5H&RDd=04Ag9|wSG%Obd#o$=xl8>k_7Zxi2=C)4hP>0pn#H=3Cl8jTtja3O zT(Yx7vt)0z4EBl#%lB%bV~(59QZmgTy)n|jALYFa=?BstLA@1}!U(t}T!6}PA1n_? zPiY=3r`^G=dK)ZZi?*SiriF-y`q!YS2g^2H9xT_j9xS(j_Kkplji5i$V)P3#!WIFC zO1bvNHBL?#oF6P#o&^6P0oIgjLxFce!S-mWu5^B|%=*NGU|jKuA3$x8tOK|v6VzI+ zodo)L7?hv-u@NQcD@k-}7>HK}Y>5e4ifiGJ5DYg^Hs=H-7{UueldZ$L3=FXsgf=F0 zLHMf{U<6g+1z{`b%v%r!AirZa-U|?KK^TA}EeMr0IXRE-_dg1Mh z**psOdW2nRhq>|Mh4lApmhQ*Qvhjh4vxZyW0&v~9ABDdR9hupWG(O*>aQ4f@xjW?I1kKf2-}R$#R#bxewwp!(6w)+o zOi0r(kh63d!kUJS32ho@Y5_)&G>!2|O(Ou|rm--oX#^l)O#`!gQ|*`NR4K2+1b&47 z4R^kqAksGt;dxm*jWc+8obS!cY_c_h2qk+HhyXch0%22G!|uE+*UA@9AihHOeG`ac zI%P3hWR1H_yI0c({oH)_Qaq(u&B9dmG1!!P{F=J+bG{@er4b+dew-AfK1294E8Hbw;?eumIIK9lf0 z0yF6-q7ET6n;hgxK2SJCXLr87r__VD3SizLVjCe}?05zcb%?mIAw(JOhm92MEprv% zeVQ>;on)Z`eov%=>W)(vQ7QOn_lzkhKYq`oT2t}v4usTs{)1XdnpR=zpcK5`17Pnw ze*nVg`F8?h&hztU6Ak}qemNbGl=t048zLVP83c&?!ixX`FTA)LfQu^duD7Hb>CXU$K_k<#5;MJkTW3awES{N@=nVKuzXs6B}(N#E&nE1{HNuO;LcV8-eLIw zf=|N3D7>@sWg)zy@-{+_%0q_!zz4R5qo}{DbRP2bJ*9q}TA|ThW5uU_g9Fo9(;Pf& z=db$pM5sGLIMjJC2+lkiUy=D4rS1>nEJ}~!Hk0lI&p3qeS2z}?Ws)4=CLN=e!2Aca z!b?K{nHx|~h{xY!#F<~L&2EJ;;zsiE&8_<9S0)-CBpil1@r=kuh!I@^h-*Xv1dOOY z0LeyF$lu;H$?SKN)8-@!9;{0@%9OI1Qt&Vd-CRbE3m(!g>BJy*<9xg#HmIISvJ=>@AxaF_cYU9H%By?H`hlZ zM@bWSXTld6a!FHWMIrMV16te??@D`KXI*J)}@G3uV|_boO(smAcWK_ntJbqZm!~-UnMWY!IJ=!%e!@2ly}CI zREM7%p>GBwKh-ai2SuNwimLF#q2-9?heJj3aHtYS2YDd$DWbgxLf30~gY>>?znCKycyVamY!sXa1oUJ!AruLgCMOZ_CmwkUhC`#{~Y64ZBGYO4&F zddosh{n4T>qsclukGaLIIu#9R8W)#l;cK%96;TX)xhR+HB{o1bXR(Mr#&x8MP7uq6 z9{{e4SOa_>iZfG03vu0UqB!?BHHEx6Cj-S(()IW;k!IuC98oE460}HS_{_@y9pky` z&OwajsCl2x`+R-3U3DMU@rw-Ia?~{OMhD`kxd^2Uxa!(San!sE$bh3}0LhM;eSl1w z@2b|tSFwQKP)}k3taZNytR<7T4|EwY^#ca=vHTImQ}7CebDttM6DO|1l^XnpzDxBT z0gmOzrB*{BIkQy_!=nJzRT`9{Y8y}VLdb5-$ED_NZXvT3z%>}v93UHuC}e}Msm3_O zxi^gHIrrLB%VrFDy)K+>GaGdLD~4{_jEOg@6`Lu6-U2pbBgJN>0vWKG0FrIyMj*?u z87v_BE{Zs3^g+9SZF-W$nDbEe(1Dn3>#+!frRHMIa^x6Uux;ID7nr{4iO%S(877@! z{Ie1#z}wbs&MDT2u3?B0`V90&+<#30U2R(nZ*bdMx-~p}yD8&M%$#J2hj5$cleev} zSPG}#m5}!V%M%|nB~P}krL3w2Nk16oX~q)Gw)K6_pbeH#jYqZ6CNqzh&{8r@wrVrg z+$rx4NI#G^5cO8@4yu=1?S0(S=RSKiUTkqV?V;biZR-SUQ5bw>g zB_`-PTnp=jV7N13b578Cxaz;0HxKzYfxm@8M7Vu5L^b$&WU~qEwXa=im#g;m=wq6t z_c62lxh&#TUWHVO!4j}#k^4W`^6pZx8bZo4{Py1XV<);&fLC zNDPhDoS;%%YtFwBM zzS{%lWjg*!L$?M@6K{$v1LhhOH85b>NEtBa02vrC14te)hXWZtU>4Jer_jg_6q%;{ zH2O~0<>SvMllOH^MsL>zqP*t!^1kltTt^@H>&WcuUT{Af6i=D1(>yopyX@<7-Ki;) zO?K;1O_@T;-jpdoHuWo0CYx%iTBb~4L~qJuQ!NWH!)wgn8-@i!W}WdSDMC`Bw_ z>f8_uu#sW`Hv$>3fB=#$pc9ax77(XzQ1>Q%Q?asXT^>AtgNRM*3{A5Xw>$i6A(<3 z6A+D8YL-ini6zR6m?XA)6@0xArrW@$%9_equOxY9M88!UF)s{JLKm&Zd4*Sy*>^x! z(@5bBP9y&SfCAIV*o*#YWc0_EdD^$&X`C%Uh-%L>U6*Zx;byvcX3i34v2R;z=p`_fH{De(*buP zsgX!T9wD%u&!$IkmD2$`wcL;OJ*BNW9bm`1rvm~6b2`8fKGc$YrvrY`QT4U@QqD7{ z13o}D)#-q&`$A3!*o?l@0c*giP6zyaZ^-F@qgIk~I$#ix>U6-}2&vNnZzANK4hXRE z>3|M^sM7(<5wcGQ7?yNhI5{0q8^GY{fT|i|^iU=2bU*+Ub~+#w6n;9uB-Y3%zkSdd z#Kwd^@eY948Kfnu&2t6`K=_GwPe43pkN_m`#@WL{EzA=#ZAM&_ArF$jf&L#Qe35)@-1pAIky zcXAa6PQ5XsOguBEXzpSo zCY0Gn!^4hWEW1NaDf0`GKyfjp??%VzL>D2TTiY#=iX#J?HLk1F|ez+;;Dvc5~l zyBl)6(*ZU_P6s>>i0^d3f>jvUzFuI)+XD#U0Y+O)F^Z`&Z=ldZL#u!gXoEm2rSEjI zDLH1uX%2F|^b;`kD4+*?+ZLe@Ft+o6lk{G~-;wffTIdmdmj@V}0nD32$npS#^Nzn# zO4T{Za&z=DI2)&*gB&F-KGkmOqt8T~bNZryUjU^h8!}IlnaI#*BTkfOBLBKXnTZJT zs3F#V#BeI2?8M*q9K51=3ewi4%3MS3#9#e9yrOw7(aWXE+(A(*uGQ4B7Ihg_)}?Cf zmTn<1GZ%4p(g5my1R=a|9@#y`Ldv%8rGRijF>?i5-5>-;4gwApgpg$c!WqUFN6I2| zY2kDqM&<l+Ft$(6t%r<(?h+YFNgMxfP0OgKQM`zij1&DBZ(o$XNyuHl&OweLn@hOcEkj#I$CKGg}Tzd(0Bc$5$ zWbcoSC_#Tpq6@=7JR@RDOwc-93nzqNxPh`cCulxH*elwkHC>m1A+}evjR~CyPu2pA zAaVVC2Rid6!T|_Rgbx7XO@srGq=_&rmj7~&{OjKkKXVh>8TSb1!f*mT!mc#0N7$8? zt9pb(hUMmCX6f|`9GJQFtpSVL5cjn{k^4WizK^z`93?bpvlg1M?05++CDZEO(ltVP zd60fI?Gm&;GbfS8=i3lhUeVW~XbUyhR(;nS;;g6y-G(d1<1m=o5a%kuLluF2iR*G( z8gGbmVR7;lSG;T~1SCy^)tsQMa{U0;IC0ak<%Kql04Sts*qD%}VIVK-GK4h^8xz_z z)@uPqkTi{|^ZiXD0O6)_E+Agh2tdM`2BxH@+CSE*QeKZ0ypex1cfNffk~?2L4dHp& zc8xQ5+0^&uWj5KGK!lRL2}FRLG=Z?GtYLRv_MVk5obvZodrGp&mXboro{|FO zBqiC@Bqe=o<%^Y6{y%;t;SB{SrOCG`yKFFjfHJoQ5gW{x;HEa1ZKP~4=RjoA_O;gq z%LemD-UjnCm@_4NMRSbVVAfvIn_rJO9eHx~Jv6Mk%_=+{P+rmPJg?}BJg?{r*elw& zLU&NE(C{{RBjWUA@8%1hz)tak;q5PsxAj;MxYbZvk55kohA#p8skcXKx2~j5^B!11cnyU;p)%TPOV$>f1&#&1=h+lJC zKzx49hP%0uf?ct*3sH*AA#H%Ao<<~q1Q7Ij8RN*1x*F5@Rzh84qOPQaJ?g1d#B~|$~Z$!atzvdTp z;#<8;`23ok1%AKg0G9olBS_5e*IXYge!pfT_+2Xj&#yUv2>3OZh4B2EZA7?V^ZPmv zpXz%`2jzDAu@x_Fx5H2n<=4CtAKr-kV2dou!k#-0ixr2f1GQTi0W>KLm?%*Px+$g=km}@mETnHB(PFM?ZtqIQ<}Ulr%3_dxe`YR2}Sx z0#;mO3V-xAjFG%+*CS)}7Wm%o0JW)0{pUnhjriXF0_v7+pmuhtJ#9laPv3^n17yS6R5rr$AX{Z(d%#IJH`s)ZxIYcG-t60@59H(DOEIHqa;ynaQz%n zG9lv3z#$peN;P#9=e~&ELEdsXiYGpw;m1T;jq6B6rCgh!mk}0UfvC>ao%+s1&sV^v zTD}5?JVG__1P-Xb$_O*)4;KOd~O9s9SZpl5H@hU{Rr0;K`F}E@!_2ivTOKwO;cH9ZUk{@1h#OuK@@U( zu&GIH!w}c%{3W*yn`+sNAwQ{^?Y6N}$FDJT%VtcxNnC7Z@S+f#v5{gk9f1tkOaRF? zb1IOw%}Cc^QZ|*FTzs2q72l9wG{v);%u71{Wka`$Z{khjQvA2Wif<#O_>YGbKY--o zPYEf$qyI{%=UZ^w>5E=Jw=}82n62@H7(UF__~m0|Ydq_1%`*BJS+F&J?VDh_{H7Fq z|Hox|dI)}2;skhW{M!2OXvEeqL+Nuo z=JBp8%M;IQB~P}-rL3w0kx?+z^BNM(*7$wzL8T=`JG9V8kDE|o`<@$bu(bIc1vCcVf##qvxHs#?xZ`mVOdUjjvYUR!k88o$hX zVaQ)G(=z(Omh)i~JOGO= zw=c#o-j>5BGL`T3X6U1p<{N5E&%xQb4}oN5CFoOJ<1{x6_z{e*VllqSF2E82UWv3j z*b;fWnTwpDskq`Tnt<9MF*jCrf?CM6gFxBb0#No!vCS<23Nbeu6KZZ)Biy13P^|BG z|KSGSylu)Vy$B_C=QL`%?bO07oWDxpO}CpP%AIwn>Gl8<if((!Rax5iWxZxWX=btg0sm~Puh8BTsOk28tq^azUAJ~%x^41zk12;Wceq!_&ogwZoF?AXxRkTql8|!RNGWFxAOqzL zAi12shm=$Gb8td`2mQ_1O{Q0S55tJ(g#LE&HoD2^E?pqXdlro4)30C??T_rZCTh0P zH*Myo$CKw0&9g<{WgDGMS52O6vTMd_@*GO`CeHz~F>jeX+tegWH^g;1U&)qkQ!Pt3 zjT8&`Im`kANVb4CfwV1MCeJ2iQ!UBGx2aa~ z4f!QgJgWh0)bX1Q-73C`H;GH}?+h!xjg;c|1TxS70!S`?OCasyO9O~g6c%jKH+C(L zNbZNq;vnJ?$xPhTBN7`ak4P5S(!I%pJR(VXi_8~9zQ;5<*$1Cv%p;O=aFE7`ebR>! zry@_XE4*r&KAN*@QAN=n63nEcC_flIIY(5pzgrmDz(Is>r#JB7ZQoc(%bUVZw zkNuy>n^JM~;al%8XcC^qlrd z#A(8L&3?^jW*7ggBzb1UX}dMz@-PHm+`k7N`(GlnG0>G~j_?MTACChN;<3Nmzx;^) z_yt#3uTSA!j}X1XLS+piLVX_lM_F3f>LUh$X7!;x_V=>P-k)iir@#LHF0+(A)JJobOrDK}6 zuHv!ZLd(5W-&1;Eg7}!@G#to{mf!4eBjCFqqaPrizpkU+@gIP^1;`tK@OOFCcTNqY zjZO#t{4shI5dE#w9Av1yrd{aAbVp{maYD`|xEY$sugEzY7;dTjC#5pf>wKm9JgHPR zLQ1tB5U*4L2$$+XK)g~J$d&#aj|0S4s%tc@rytXBSyHJC&E!`~l>&@gD*i0O&04}j zeNX9b4nE`qst!IZTOM-o!DjRwe7GE(>fpm9a0Wh$aEFzo9DMi#JnG;>E%2y=4+9bM z4n73f_~66)U{ePl+5>DKd@w9=ouV9kcp5ChgAcRqOobhM2!O&4K7@k84?Y;BFEPsR z9rX9IF`-T^0T3U2*b0q!{$2qHJGJ}-i09N2fFwD!6n=`eMG5UN3PKJYq zBMKo1Ir#7bAUqbus1iau1U$(H-lWCJ!G{L`;Smm>G!|grFd!d%7zH4Yn0ULW08`L^ zKC30U68Yf6c_74TB|3bYEX&QWL5NeIFfuPO?-O#HFfuPLyMs`8N(eQjC*DNPL_YXn z5?=2r&VTU1rj~v1;dAu4DNuUals~;6ph*64lZ7ltKQ34>r|0 z_z)oT!H3ysYu>>J136jCmxB+DQ4sIogMma0B<$crJx#no-(~!|6>_|T4>m*&K3oNe z|KJ1f>wNl-nYMh75FTb$z+Mp!KJfnKpDrzZo6uT;R!W0(vUlk_<(&y~z4Tc;aL+>; z?oLbS!^}!`?1!1ZAf4e_*l2y1hnbv#IPDA}%fn30JN`BubMyjo)HwY)xI~%I3GqooJbAm}R780Un)?L~ zKJZMgg-ewwn|cg-7}T42O4iM#$`njdpZQW#M_ANlG((qasav{vz)ar3-N`zrdp<&O z+JfxPv5@jmX%8S=P#iG=+k-(!f;i1MbqFELqL(uqr+Q_PxwM$pgpqmC%c?5;78$UU z=Kg_|EC(MJTKVEO?v(g_$Ml1^QD5oG<6`?OZ!H-Gz2hqCbzq=`v%gk61@$43ty8KS zZw&$YNe$kp@1nEbzgIslDEdBt`rpuSo#Pj`Mm3o=i4&c8!eZ>8U8mTt$$ z!i%T)w-Kicx5mjXlUiPJ0@5U_f2R@4!w`6IvJd_R+$cW-T`jMK_gI%#bHDO0udsRj zJ#J7Zq5~_Tk{`6tiN{T7DVb(awH4C9ALZ?U z^aE+jP;Uj_>6XwNmE%6$IWfa~x>I!*x9U$}6T7qx?KLe#UI%{=6!mn+riUJU=mhN> z0TpzHrh6U9Nf%ikfe$d%-rSsDr)@Onq z#5GQtAt0Ima7`xYV!3t`Xep%H^5p3b8xcM{CW+1q1M!TAEfJ4ya4ozo1j7xK%^7oD zhVa1$lUAD63`6XL4>l%rBJ5}ZMv!=S4~EXXiEseI6X7X?Hs5 zsMSA4oU6D;Xb!^(^a#7sydGg!S{2nJ-1(Dcx#5^uKK>bJ6u9+00T#8d;cI;&_kU=8 zAMHa~N@(vdS}1*ZyoBOSK)NO_(Ra%00_jK7wn9f{P9lvjaPXl!idJ27U8L{&-~%fv zLAT(F@i+{o4nA-dB z-qj!Tv$LPM^W6`TzG(>0%Q|bE!OL?rZ(e4TtqDXZ*_%KF$Vn3jo5~t?=Ve!0`Qiyg zl_!(tWjOeN{XuHSU$bN04Sz4B)f_+Pi*GxX1il0 z_0>E>^j)6VcuKO#mXboro{|FOBqiC@Bqa^B^2JIjPEt~w>Y$V+-=^%ctDg^G3lOoZ z-vKwZt8XJ^SN~NYlb#uPU9jxxH}iJ&r(k-NeDHx|%&xvZ_|W#Zh*Om(S6@QIs@wdA zf2xBIJ-veu{k?+^y%tyT4nFiz2Osd|FRg%Ot<~T_dF}S_UT#ya)bIS2+WzdP+`U|N zG+`+c&*e2Czj*xx{D@I^U|vV4h?-*4b|i?hmwUDB<&Fcf4?;!s9w3WAls#B31GW-D z{23uR9dHDJnN)Kn9O#i7Iht_4&gf(Mp3*Buhrr_kd^BMbApWBX zhW`w|oMuSMbJ?~b;DU^1b!WZ|7b!fSo}v5jNmJ+1iYgO0YuT9_h+nl$@?I*A(i*#2zf^nY_R0L10YFxe-jb@yqhFnbd$!bqk(brZUel$%h7}_ zn(s>=e@mE+XXiFT>^ut)*Uke7*!j=ML$aN#qX`3G=PCXDM-%qzlz(?~V2&pAL?Z6d z1REB5G+~sk!O5m32iivyY()6c1YYAl@rCKg*CK@7yj0AzaWsL)=Qmv1dy3W+v{G8G zlYK?sDeo}I_0qd?*F7B;#pAI%Q4M_LbPjZrd^BM_*w<)brTQ+rd7ObbEe;{eZXV|y zf2FipGwpD5H0?{?&AS~rN}4&V-MsA>#cm&j0_9YU5f3PF-LIk(#IlQMC!*?}rhTP2Gez_)u3b$O=e~%Fkhd5|@zi7q zeoUm>a9xF{lv}Z=lo)<3_~$yta~7&pH{dMvxz77n`fj_5e5d1oG<3^X!o(XLh_A#| zYeHN_Y^3-~GzK!@D-l3ekHjbfWYWBc?L_^FZ~m{SC$Rw5y59oUlF8fY=PEqqeGClh zW6|%5r(h(6vx$q%#EGl$FJ0iOnn|kfG2mE!TxvBGvKtVt;keXrn&$RNQMHX7ZGddD zOjfz(<5KgXWVV91SV4enETWJN!loMI5dWGmBHIbx1B0tgwft)gIa3$TwwV)k{7Hsx z*^G%dN)ems^-PG(*hsONRzL=9CV*s{sSIQpHiH%a)rTWavw>*$d%jJw7_)uZ7#)b& zzAQu-EUABJmP+3p8w<8CZ(RqbpC+I)y4Yp9m48;^1bF-M)`~|o;-)Y}2|WvXBksQz zg08kNg*Ui;DcxGoIsI_*_GRtA;786q-cKw~97B{m*}jyrsumVS^YmRgrzb#B+m|+7wl5o5&gleg83DbFpg+*7uSQ1LA`(al>10Vl80;dmH*#)QuUyp2@ z)4le!EA1N9z6SoISwBj1lyO2HDaWs&C1b-= zbR|>X^^krvZ3c8?rZi&8zRf`8nm!Ok8?3nux84k7MI~rFu5mgm45l^%xe9O=R$%*Z zy~UQsn}J-|1f79vobC$&iJ`HY@kLaT#3p7-l5IfS!~&oY6SFa)CWe{eRGsyOt{Rv8 z#G7iXxJx*!y961?)g&voF6LhBknT;gMk2}`YSkobk%{sqS=%|v45@08<>b(5(T}#G4|^fH~mVkO9+1%7A$Rkbwa+faC$QCXnF+ zCOoo#MkCAk#Wdyl=sP`+?4OeN_e@4N>jF{UrC=%}VyX^0A-Ki;)O?K;1O_@T;-jpdoHuWo0CYzcxWeOvDQzn~gS%4vzm>RZRlAqM^ zs}0?<026PNA{NlS-BH{#eLs z@++K-&jfc_PR2|VC*vm!OTS}ci83Q5iDPrqGn|14(+u#bvR2@%SCTw4;$4GyDhyFV zPe(GGcnV>m3%Z&{3U6>4dD3ra+<|Fi>~H@xGWugVIA>5=W`@%SA!-30HU5fFpOf(o zEG=vn$pXzRQac$F%Pe<-mO14($i!ZPZd5JKbL5Zm-iO?3=|6LCG#)1D_D1bj<5!ZC z@jw{B9Q5e2F?~CJVEP8kB!r6SChS0O1W`7or^&|jVG!>}NI4mQp;JDkjY?UZv}!)@ zcQUpi;$(aQAjZjfE|S`hL}Y`T?R+*phpV{bo~GqC)c2Gz%C*>zcV7!0Aeh&J8$tsu z$@g0D^L5k+lgMb}9Xk=(RNk>Ktqt*xwHbZhu>-)Vykj2%XTUqQvz4TH$DRbF@{T|!=J3^j!Y=DiuV}C?a$~(3Pz_xd+VY#M_sv+@?-2#@NckBQSF?tAnEqDMF<{cXf z3ipmRiH*^Tr`#TN3a~MuPd)=6_Kw{Pjd)H00SG_&OfB_01q2{TPd*DTM8|Tw&glat z$7AvBSP0?n4lkYzL5O$kyMS;fir4NV)LOv%VCP0$krpT3u}=cRT{9+i0(?0P$lkG2 z0pzYeLA!B{(@-@0$y$;tk-cLVf)J;wA!M2Lb{6smBxZBVeD{dtVnG<0XS$^z6pjy} zri@L{JSMVttdTs+Rh-{D)~1&29b5NwOj4or+Uxw@v8%Myw_NGAcdU&F^N!uAxqmiN zCi}f(ZK~xR8z8fH>||?7V$@jNK+&S0l~PNcY!`jU{1@bU z>6J0{D0m8KxZ4(?-mzU#gUS2p6~Nv>3%gj~Wj~!WfO#{rXp?0>o%4>rQtGOi`noy# z2%L@6+agCvi%+$m{x3%0wu4c?BS5JF$~;MCA}^en;f&##$SHprqRd2u*txtWwy=n@ z6aNvYr91`c=2B&@p?2bDRLF2{=DEZOmnw4yMZLJ9rp~me%c!3&)mXQ5&jPdbZ|+WZ zK;6$F6sK=dmO&O$wsj8z!Uc`fc(COMA$UnG2=G4$A3= zsxU2t%KZZ?S-fLMTKVEOUhRb>FAP~k+UjqXrtUF2Z6tsmz zwoa+;II#{3HMmIMMQ0;{^VAv&c?=Lwt1{A#tymRdu}o>~LsB(>VqB(=`8^2KW1 zZK;*LW6|;{a?~ia5kh5p#{ybHV=HAizo2zdJD16~)YzR?50iJZy*vtGu(Zw6EF+GQ zg=hUo!E`sb#-%QkS{HBv(j@0r)`-`_5G6FON`|wA8|6Qst960!9_zYbZYuFx(T8Sy zatHbvd?51V3}-wy<17C)O9CZNwwI->$|}oT7_daMFlZGa7Fz2REp+j56Ix298GNH{ zfbxEU^aE*4Za_c%uWkvmd6i|hm-|%nwwKQ-mxfmT_dj?KlICBd?`nIwGSsQImu-5e zckBSbjeyULAl_bX^`hgjMI`7>xlR_j&BEZkz1$0Mwz&jdD%WcTJ^=+=ucf-ud3%}l znV_|}#wj}lB=aAxNxYR@t|J7x3sP-)G8bYaN>G-7o(%)>jEF4}U&X|=@ZJy%H&8Zb zyg!^F>>X>;+NI0D5ZgP}#)M9U-_-()AaMa451n}v;Q)ju!V3ZMyki59q=~SabT~Ql zPW5ky*Qu7_?BE{ZY8Z~MUp5=!UXOt9WU3zF3&RpWW|rI<8O|DReOtkz7UaIxCvyLX z*7s4Sw7v^#YN4m49511zWLjPIwn|@=HyqNBrd^HJXXYf*_b2mvqG;didOSsQ z>kV;MRDx#Uit#uMrZ&X63h+=xV1MFz(3Zv<;#}ASwZ=70kA{GxX|S3Tv{$Y_;Tk7y z8n(R9rV#*zGz}XQ(liXDqSi!M)37n2O(RnaFoL9MY)Wbx0SGsZuacTZ020?gk#92;A7NxEtGYWiTjV=-UA_*qRpF9OAw0$$=O=58>SPoK+*xyr8?vwQw* zgzb)%l%sjt=)3HmdrGp&mXboro{|FOBqiC@Bqg=5^2JIjO;S>v&PORtzD?O>gLxu= z-9W?!b6?!l2D6Qn4d&fICT}piU9fC0$Gr{a^_Vjyd&hE&*`l7rZvX$-`wA#2j;`$~R#?Jffdq%e z-Q8USgdmH%1!j>2g0s6bxWgg|?hb+Ai-kZ!kU$6$+$C6W3qk(pR^OVQsqX!U;ikP5irwSR!2y4+1Ft1WiG374^dpOkj3V*y|S>m zY-to}n9C+blHb56aUA7LN##Jr+U@Z+mp#c`ZgMEiWy=9#n#)=s2Vhv58W3-DS(X32 zH=hvznP!AKM4Az<0K{WPXhFb?@Gt!^G zf*2;Ja}hI5PIa&}IV}o^kICsCBzT*gsv;|TiiSNlFdmar9blTAI+h71nxTuE$ruj( zBBU+qD!%+tB}YYxb+{*HBhnGF5se4L(}*kxG@`Bm_%@=*R*C!_s+eP*;*?n`)v+o| z_l1&jn4#cWTDnwl;9jNRT!@(p*1=N2*L4NgK^|`ft0EhDijES|z)Xy!g_xd*c~q@K z6MP>fwgAuuP)GxxKib`uc||CmBXrAH9bs=7OYgV)6RAP`IAU1ID~+)nma+6~zUHAl zFlg;TixFy!-pIv^&}4}Nu#$JO1D?g_P+?jt@k~-Jmaz-a-F;W`PE$F|Y$bd#HI1$DX!fO4vA>)I)O`e0t;Dnh)C)WI@PCdC}L)=pKssLsaoGq ztvppJXS#1xezE*@(|w1}m+@GX*)m>xe=7 zc?zEnqwJ!a;_;ytuGb=tEX6W&mYko&EejT|XWc@kmgD^#qLnApj&Zn5N(Iou^{ir9 z7!hfQSS?P2o|B$lTR=A!u4P{9!nJ&;SqxfAru1F7E|o3FagLsM0iUW>E`y(3xR$aS z1BiUi*;%v@N40Q0ErlT6{H>Ta|JRtth>F~VrgA7kSAhHDfIo5HB2MA<(x7!1dh{$@ zkIrN+T$f5kBgHx#5~$7jn{a3>T>k`$v2d-^<-)c8(eBjHzG5&=F?xk(dj9L9r~M|Tpx zyDR;i5<1xqN_NrIi11ZzS!fSC5UtKpOT302Wm~NAe zv^m|5LXv0JVNAEzt0Z%}eT9Ri&%K!->qz-boerdBN?}3LGqpF6`jo<$ZdYW5nA7cENYUg}^?RY@ z(B=;BIo*%%DCBU9;J@*pbctFBRJyw3QqD{VY~<9DQqFgFa$1li=Xo1BjYb9&@x&N! z@}yUz+Ic)iOcU`$zKh(dqE$Riv>P%82R7`4CR!C0_e{IhB6q(K>UuPJPRV(SaVQtL zsp%S%XPxY6#>V8?mTXR*Eo9Za<>XnXQe*bKSSn(6u9t61*Qr_yP~^0nS#Rm-IX#o2 zYb`*ftHNaqcwyH9bfjznCxEoHbPJMNz?N&M76>f*}|;1VHd!K!@KuH^>CAgHW3h}giW zjKJ8y(2;Tj!>w~SCl7K1W3{<~Q4eziUkiCkQ5zWX3=8?Ad4n98Xp+4by~lXqH>7Ey zVIePW zmMxPi!U`i}`F8+L><4~L0Zi5exnnbyCz>>tpHP6ajEhqiCuPK&!_ssGgB+6(7crhX zRivsXm31b>N`*LYhrnAue;^d)FECL+MMc5 z@YAr>tzo)(T{0APbEN?Zrv zJrbfsCd3k+QAYC}xdyX2lt%Ma0WrVKtwW^Id>25J(fmdf=g1*9yP`zkVTXg7{{%4> zkTZx)64&8N6Z)lG$|?^1=0=HJ$Y6e_TSv$*TGs)@{Gzo5@{2##y8$u3XssYCxE%Q< z>S#dZ7pABF%O8LvJc1$|P)>y*= zB7^>O5Y)6|vOvgK<1HYj9g_v}D z$G}&JIeCC&)PEQRm#AbzmM?4lCHX#h=((k}PIgH?WJjh~vs)lUuCSr{Ep>|@iAYBM zigOu{;=GOeb!zNJ{RJ_Y`9bNwKuJMe{Bc`G6oxf3bB*wDr_HeikuyNUVFw!o8}%=U z90($~bONstoO^-dvfkUMU#DtD{T4DA^@rdNnMVBz@(uHsM*WZJZliFFZ>NN(3S$-I z1e)PWKr(`8{JBJ*k~kg8fPEawheN4fy$$2hDiUAdjN{P^r+_W7ygPxA9QHE!&!q%|AE$*W4cHk{=f6lV} z&7s^5qzbsiAse#X4y3x{FGd7%O_FrrvAYZAV8?;t z1t6Lj$yw9DVnL2YG;4b3A<9{kB>EL+VsIXn(;&)?#0j9r&~z!chbreqw9Pm_s7wi% z?$f-driUu$IR^EiqITA(%S8&7Dz8VniNFlaOGAna>Yjv{OYA{)Q)x)KEwcm=64WIc zAzNlE#4V^ymnd#SmamOeVV6i18=0haiN8^V&RnjFkg6gt*-&YWASKKGmtCtD_4A)m zb1wrj&q9P?JI zEhH2WQ>_)OT)fq)lQp&4l1;T*$n-YuQL9e%QEL^gUZmFXsJXXV$*?~J?ea=KrBIQd z=HFNAVh=8mdPA911~#|U8;5!_8SgMufb5d#%Q9lV9b&b32l_$kl)r;+?2pL2aearGlGXbi zX0@1I9ya*Yjk6U{uP+8axj!OhHS`hdOAK*TFEPb($Tj6}DlpSQ{~FU6p}N5wZUZ9p z0JuL6Scm%-u?~%Z#_7E@@F~OomD$bxk%Wb*SD!+gXv6uta%k+2+ylkfAJOTyhW(|W zeZ^q9Vnq8RH&GF45pK~?`fcF5M4%m<_D6z#b2zBYxkZTd^GbMQ2-b(Wdbrd626-9v%ydYrRI!Z zza$75_N%fcunYvz4f}PB?SyzVGf<4A^>QBQ%$yKgAT%Ma2Z%W#wm|HxmkZp==e?sd zy<(7~F^vd0&~Pjx!s!5WL^vHV#2678SK=(q7oi=Ur8uAv}5vJ7@zL&w;5jqjO(VkEmpxKG!xK&Wd>^XVEEh+WsflvLgJ3tTF!zlzcB z(+e7Ww}K@NzB~<~dD(HsDZJc?GUsJFS(`xElFbQ(h3qqd(5a+h&%Eq+tzI;NIEU(c zO(5{uYb?TvjKx*IH>MBDupjdUZ^M2i;2V!(S|ej{;3t@nN4)h`jN0>4~zO~d}RreXgw@6TSZFs%7ki-9$Q9R0tI=MecyVpV%uuXqk;ZN;)iR$^JP4y?v@ zckLOErh=;#yk#8VF+!;;sFHf&oPvBQ1B+6VSqG(f`cnCuxZ>qlidV$tF-Adf(lX9Y+@cuInJ6ES&K;1MDd z#8D*ujhH+okiMc(!TcQhEyD{u0OlzH9U)H%37rBeb0 zQ5)}50(FqZ`=i>5@m8$>^OS%EVL2rb8^Sy#pd;*032f&&?BmdHg<-`0y_PPG*rOqc zaZ2C}Vx|$h4wgpjJpu7KCGa;Ayp7mZk%v7+WAzdkkLkJ&@H!FopqsBw`*ZbSN3%-vPkK z0KY1_T7Bl#$cyJ90K0$|`H2mH^idM&SY6DS#NTm&^F3Di*XaiQI>O$7pWb6fl~W_@ zRK&1i*BxUv4EX68yx2oqXV9jD79-TanZ+}J9tSy7VAC!bKr@{7dK0u=v0IOx=(}R~ z4YDU^W~n)pD|S=?ml$G0mMeBtcl^bOtemNkr$!yi(~4abYUDFJHWqy@;(-y>6)zXV zfij*{7nk9<hJ@gGSbb0e>NgzsN)VA(OvBogefUs0Ryxy2nFJo7qF{U5lxgH0p9u znCsTSQ^&vx0gk>E=}AxtN*jq-wCIg|S4cr*z~2$cRK;lV3;d+HWU^Zj?`ZKY{EA4D z(-Nvow3rOPmrA1ABnMR;H!)9k0Hr#D?V*4Q|Qyyj@(9yX;M=VDVjw= zMXq~Q4t0Zynw(xo(KU+#m9BIkEeftcN{i``j+7P!yMVM<6j+dCQ7{WgpScaS6XQ>Q z+WH>ulWYN`b?+9iO{luLSq2fh85rD;X|;_!5q@WkCNA5IOVBNB!Qj3e%G*~8IO6Y; zchwfs6A-$?E_sJLS-BW@+a>R|PWIe+m%Q_~WNHQYv^8$Cg{)dcBsB<~sv3v1La`&7 zr#p12)@BsBD+{N$87HUrRCKM)sC1=T*=FuRZV?*Q?W z78V9SxkM>tHF}U72kq=EN`j+WqMTM#kZv}8&P>x+{kNFL2-Rh`aZ?hZPH=x55RUs6 zk@&39Ypdhtc$O$n7c`eB-&CWn5|+{5F`o0!fugHl%!9$C<@;t7TbX2 zIt<-Ox410*d+=SNp&gWLYN-+7qe2o?$PPs7Fw_#=qAvW%BsLftOsF}#MIQM4S0H{7 z?*+ep^@AKKseh%auG+mEUzG{B*}qN){7qe9waEDeXZbA7S^6}9wRJ(XfE!H;f%TV#>2AK~xUxzU0j3F{UPRLUiK+JIz3BQ?9lYWPMI(>ckd zKD~)qKsHTG$JjP8%nZ+P)gO4&7*UfJ&bHBzFqVe|+0cwhR$EMZk%ws@W9+(y+Juue-Y5%~4-Ew|(vg@@}SN;ZLr)jsG&vy+^RWwCqV`vbe znX%jx9C(`U(WmFUCR=I^uK<>Rj49JgRze`>m1}r(?~EyvPWIeKW6ESpHm6J$vbw)= z%A`|$rc8E3bIPPswHBbrf2%vJ8ScL2biqR74*OWHt8}Fl*#Ztgk(L&qBV`L%3Z$h4 zSdi2L+(6p40GBv}d#}n@H&!lC)JAYy^?H3DOSQb)=K%6mF@^N}GJDBqh4ln3!d z@HO0}6tzGZ&oJB_6&mEoO;fAEXgs&k+e&}F8vQMGThzTG{~{OANVE1ws^AR$Q_&EF43gnZuMrI zrD~kAI4L9Mi+fKY-$zu}-pFT&y@M{3$~qIGeRD=kvqNC++X9BWRnVaigKo?yWnSxy z@;LxDhP!3GXOzzSm1)m^TuT_)A|_JTQ;%ZF)XQ+U7AW?HyI`m$lx(4X}EhG5M{UQ>(J9<`Sh% zZ76_No7xz?QfU&q#orz1qaK0S?8lP~aSO=Krq&i@Z&Uj_7kZvUzaOn81UklcpVR^( zo7z8d8%z@d3xxJblR_7!34sMdHns7tc-z$G!qB5?`%cw*Z^8L(G0ylw={0d{Oq<%YJbsqo&~LA9Q>!EFY--DM?q-V15pSDXovPW?TF7Km zTLf*)w5e5)FPOiysqGFyOq*H-siGicQ=1JC-KMrJ1BP%Y$L-Aknjg#7A=0LHG9cbI zwe+f*tFd})7efpy^!G7oflVzf$yD>uzA$Jhu(}Z=mT=96M056Qo=KzSZhQY7M&P zt5&k9t%!D6w3$+9W5i;$sRa~=*r3su^v2TFlgaCijf1cyX5Z*@zf5nT5Ro%O*870xtpuk3z;{ruNPCQdcR(* z7LC4y`73qffy7TPSR4H0g0+;@XqB*O`g<#2O63)ZiSnG4o!T2Zgg1*N9u{8>~Fc^NQOhzg(>3)VW_cENfA z;EKWLiqWe8oJvAPs71KNa_MiBe4E?BX~B9p;MC^aqObI$Bzz^*mXEo5xYL3)>C-K4 z!iQCs4M@&`=uW!DWa-b5P=7lp&4;KFxkY&ix`v|lLX*?1h+3jsyn`RP#|A?kl$tYs z)n2U>OLa+tlh9+X-=HW}p~J!@=dynK>c0KxjgI2oQ5ZY=PJr4i+d@&U=Zy zUbi5}SsD=rqv3ds%W8?;91%_jyrj;%S|oOImT%*nrArvhU#a)KL>5c$lYBp*_noaJ zdtayS%(PDHe~T$B+WAh5=1_#r0{3?Tq3C^TP9i&>*Alz&vF!N}tvTl!$ssSXlcMnR zH1P2}wu2c<>~ssT{VriSP-;h=8!fSuu=qqge3v*5s1A}{gVc;4nv~Eq5=vde0=4TJ z7LZNX&@nb$LqQ@~2D`4IV{E&|KxUvA$*%FIPuH+O;rffDs^Km1!&j zW64@a$|dWd8`^@nIRwik>s&{08;liHCq`Ibn_5ayOV(^tyR=u3<0;m0Mg9)z)*S+h zZEE+LHnoRLo7#QeHnl&gFJvo$_Eu9f?@?fxGH{!mYM|Pl)?U6Hu6(RsAL8~dpm##D zdJRN2Jmi7-7_n$E@eDpd0HU;dU5|?>u^hymh((KxfH?B8)ho$>=NO2k5R+D~RS}sW zYTty}Bx2I)^>kIEg10&J+lNz6&I{uvDNEj)JGQH5=9zT zuLY6h_fwP@b4yvhruxI%>NR6EqfP}mlvc0L05+{&EfBJLJqC!k)vL;1+nY~W6lGey z>JVx5+6EAh)vE;ot5-JwzMnNVtX|tfFx~341sC4ctb~`<>r!wstzIoyvU*(usl2UT z4){yU0RMNzO5`r8zE*| zj_P1(IeHIL`&f?lM;>p>QB~v!PtjOk1jb`8ssnVZ*T>v;->Eiy$f)}ZE#0u#y{YQH z88Nf&I@qw-1;nTBXOQ4scU7dQW;A@iLoiarZ8xl5{|4G4g$^aF*G_<1tX@B2UWvVU zW&qG*^{N9jtJfKvZ?($*i*EI*BkZkS=}mL!mufg2gBaG-Zevu1)hj(EXL@K$4O&vX zfW-(ka9-r%asCnHOo10@0G);V>UmeQwR+uyp6I)#HWAs6FtZaJ$~85r0BiW;q{afvhC<4}Y)?@DWG{#ZEknZFv#GKIr~9RA%g{T~FBF$M3s4bKu<-D(_k9@JD{ zK>Tk!RR3)L26cW=z2105{~XjU9%^fo`m>^*)TqnFeXd*X>PABnp>Kfc8b(ioT~OL! z#G=KQNP9#IIusBk0`E8+RK;kq7k)^7nd}zCJ6bG(Umr&aB&M1aNu+Mb~!e zRk|u%?$S?(@RnVA9VvI|djo0NrMDnym;Q4g^<8@7J9 zke1UkD!L}8N>@!l%K6StP8})bJZ~qb1xa#lvyszibw&rM*oQj+H9GGOuuZ7Cb!8bu z=qg~)9Pe*w1ybgI^76uA;-*84^kPOqWp zTANYns&Lt665O-t8#+?9nOo4XrEge})MoYpsrL;zG^mo*&Gi*ur)uIWa(yM9)@2%S zdZ?mn;;VF3xD>y)o%lLZivKx~7V#}e5u=*3-7rP}+JTcbv^yx6l=DE!_ za|wA9;>c3vE6#E`j#;pTeCio8Jy`AM5Gi_j%Aw1oQ~)g@pQ_T25ykBgtHn*wbJEkR zJLtyymCS2hLY5CTtIcy0-zDT417My^&%2$(Pc9)F{Nxg{l+_qO$dLe}YW3Atomyb|NT1RR|ZJcgUD7%WwcUg4Sk02QGYfsY+X{{;cX zTst@|As+^u+MHW#mHs{nzmIz{j=6fc(-Jc2(=BqscZsiUKysao?xb6skp5-(E>Xh{ zO6z3Qh}^;@LD}p;v`$7X(Jd;$kMy&_(0D=389#XkpZ^MkR`yIUF*6d%W14bGBYv>@(QX$S+4h)8Qa(%Sr(a2(H%aZR0wB-xUWLq9LgqdFa*OY+fAvfQFJe3y8OCT{_r zMWfpYAl(SJNGXBa;Qyp^q-9wW*)5()PzM{3Y;L4%e7i$}sG;ecq~){T&@3REhNfd| z8yemYZgAC8)i4^L2p#YhEpL_$gEH?xRvH-OY{r;q_rlCiE@_$*?FC5k%r}gQ_A!-Y zPP82bEfej6NTPaqCfa{;W!`Y;`!v<5+S62#A9H4XGVzqtUn;uxG*#)UaQQSH@TbjW zLPyG{X=5NQPg4srRs1MX7)bqTYD~1-vO>&>_GF}Ja;o|{_>SpvCgAi$imu72($yW8 za$dEQQ%6cUciYKnL6V%aZR9i>84SPcVWhdxUyWzy@c=Omzw7!gG^>i%^)%7618AYS z1vOFs2VPB7Ei~sCOkJ4X3o~(^3LMIXW@@^|v{@&6nz1o$wk4a>W((P8+N@K3TDl?@ zpO4_~4uT=le#_mm{f*e)5V_vevlcB*5WH9C> zCjy#omvjA(T?{+?KfuV?J=h)OI8Mgy?*L5J8o6ULb|;!NcAu@X6dDqjEKbUZ7lpIA zhXpxCBQDw?pCM~es(MmcXF_aM2$vlKFFnIy?A`%`*f!9OR|%Qd`YLe^02^cXmfo)t z&in1j80X3e7^Wj80*9(Om}Kf@>|Pucdt-MnRBsY&?B0%eo*BtJoBslAifO`EPOMW9(iO_jL~*Xwuld)g#z4AR$Wp23!-wqQyb%20a2m z8oNgUa1RMl;u!!h5i^Y4!?*?uIFv?{DFHT(-F1jGb}tQxGIsBX;zA0svHM~WsLf9j zW8g~@_eIQmIfs6yqr`r|OcQq#1T-&nujl^y+8sE=Vszy67h9lf5> z%Z|PQavFB@6OhwlM}JW(QrgiAAdPQRXGP4gqwj{8X-99#Mt1aj$UQC z$t6lV`W?t(wWEKkSIW+g-U70-qqhaw+tDkf$5+ZfZ#5gzF}Ai577*FdpMXY8vmpzF zY$IL(Vww$EAU?Jck)L8jQ#H+`YJ4_ITzTqn&_L`G*U^!5M2@TYHvJAjXn4o3IUtrm zf_Hj>(=$71Lq7u$dT6-C@9x*d>g=)(b|hmc#WlfW_`{DES1 zvV0p$FUiq%WP0KMMOL?$9hu(1#)A-9&xY!E7C)>?M6#jR3nt@ZRpo~f0w#7=N_oI-0-%c*QuHfy@gCR^xvSb znKtwa63+ak4SjA1V%pFvNCyQukqB!fr)U9*{)}%@4`t#^4&|euH~5(L^EyP@&({US z+kT#wJ-QB8Gl8!V!(QJ2OnzWLPs@8FJhUkWZ2@R8VmB9imO~M`3FJ(H^XOUlHOlZT zs@d-KMd1$m?)42q_JhpqR}SS~A6395THBE2ULVyRfB5++&h&?;M%72qUf+JyNbU8> zRX$^@St>^@k`~nt%{&s*zEL!sY=^qD zAO`DD72+0DCcgb`LzZubRAKxES!`sI)+Hv{k?GBlR2A9V zhDt*KDOuXjzt-wSecbWf$4<+*dEbrWn@3`M-#jeXu!3@X6x9G2DB;WTMxKZ);7F}g z-fov59VTFKIu51IngM63)fO@d5L2zmtz5j-s*^Rf+LBGRTF5?X)u}#eO{vw3)cTXA zRZ1M7N*UF}4%omYNczk#I-o%$x{YAT$vk1&BEjwm^I)!p2j`QDAr-@9mn! zQ-d6>Xhhh7hT}CZtL++dL^vJL%NP+lOyevM;+$pYbgb4;?<+CErlUx{AJF^Gc9p$v z`wV6}{$FDnBUG=8<~t%n&w=~9fOF81nv=-RXR)8Z3~hvQuE`v-{X8kkE&hU!=dm5k zu%D+};1>HOtP4u*r*or?8WI*?y@T%(AKQRr*B~{!MLp>^mr&{&IzPExqjwDp$fj%P z7@MwP2hqERjo-+Xz+am zmR{2knwQOBoWje^CUahi5R33)_uaP}xhZEIwXrY1^CTFH4fa45GmOeN`L zO-Z(7Q%M%GkCJq%kCN7E^&%xL@=+4({~@KSw~}2heTML9A3|U(ed|cM^!*c% zzDwVpAy_Vb4>gy*Z(z>kYd=pZYU!Kp=U>kZa)i_5ss}V|44YMGI$(U0`mAX`f7P^~ zKj&>fe?i&LD}f%=HXaW6{a>(58CaHX>TU0vTE5UL&+@48)#w61uBUfGvY)Sx3w#e5 zmA#M^#eoA`~zYB&9`fM#-+MvIOAjVgttG)5ILD#|32K@rS zJ~rrIB9FHXx+-$Hr|2k=85ob{xen0n=l|xm>#rDGHR|r*Yn3kR-X49(sQU`UO#68q zEbCqY5TCjqMuKW0JH9q*(3cODqpZCKX<>#c_|!@q@0@DLyZze z(WuN`pd(~2NCt?f7g!MJ1rJa|-(E0Gv`U1p1ylFFidO@~9g&UJ_&Z8)$>lsXaEmac zM~NmVq(5Sj*=%4WWjUm~MNRnNMPIYt#ypNFUe|TIejQq$K0Xw|K8P`=r)>ko(cy*$)zIsFal{Ghp@9_$I~L=W{xlbU=EQ`czJG;yhei(w)I{E(t(pU>T*0OHaLArIH8G>1eq?fP}9W`&^01vs;A zgi(moiz&Khg`m<^;nE6W3H zN<2;c&pExJqHE%-bXB+%zv(-hyRRdq_{D&<+0K3FlT)Ru0YJ+6gPoi@Qp!2cPEHGwtJ`UyBmFB%Mq`BmfW(%ng2n}y8 zIlPUsaxsQF{G0(mI@vSqVJ|2)G7W()IRsjAtKl$`Mnj$IGcqdT46dK=$f#4bHlxVn zII})7PT=$@imtU8m97exZRQu~&0?OWBW0Ue38bZOSdi3aMgpn#4LLHZl9$?wuTwSg z6?v8tPwO&sIDLVlYvQYPRk#$t7#_tI@pYsW|6?F6;#-g;{=?YBS0!(<6 zC7ve!YEECL=$iN{T@^0HpJyk&j+EjLwiDliB=MU9X?yoo$*ODnHh!I|iLc1plz5u> z+c|x=qHE%-bXB+%KfbWJ`#MsJf5T3E3zEeD!A5)@FfkRL+Y7V3A&b>eIT|rclZ#-& zh%IrN34Y_DEiq^}V#po+Mvmh?lce+jBSl&8??tedXf!@CD3t%)iDoMjYqc98|~9tq460 z?vDcoLPrs~aa-xJG68k>Y(0JTxw-XJbs3H2pJc~x`7ob592#3sc|b9?o^-n0diqk^ zdYS+QD+YfmMz62}PB+sf!fnX%m4n&=nOs~zsPZ{jpd7SywG4vL-HQ^#5PN}`Tf~E$ z_`L$VEVO-f5I|}pQKBtk`(&11;bYYg8DDbkJf+YU7TuR9aUbvnl6Mjtpj@k`R^b+( zNxunv`YW*X3-3*uDhq=g8L6GNg^InV18S4TY^SFKDjV(eiOMoH&RI$?#_<>GNf(gC z*dq06r;_gnw9^X%WjlSXm=;?8Z!yJ>HL2U_X{V9k{w`n+wbLZ=yxOVPE{*X+0@SL4 zIa^Z2#(^bFvsLM2pH?*-y7A;Q^A8uI5otO~G)D3B5Oawy?4ZU@58X!`tpL<1p~0wr z8pTb8wA({kixL9>tcjRQYz15g%2q`844(jlFaKghPG&QRLlL@o1?^<)Asx+T9m&zo zcz0co>9pLvFyCFTAjva{Gu~a37ULxI-L)bmsmYr0?%E4UJ~OmJT#1St`aYy|s`ijl z}||%Gt@^rj_eRDQ9IMEv?*wBsntzso!Q}(7{2e9(a5NtW^)GN_gU% z2c^3E?kK8?9$|s-={jT#4!leQ)Mymqd52XyiuE?o5J(Gc!#L0P9LgO<8n|5YO;jg) z1~KDJ)Rt_%iCV~NaFcJMI@M>KQ^aVlm+v^IQ?(YL$fG#3KF*Ed^a+ZtwE&f_3YRUQ zbbw6@(2=qQqy*B^0xU>s0ncn&fP52GB`>rUU#Du~EAk8_p4I`r;q*C*u8FVGRpCz#iKmIboYPk;x+cC#SA|RQg9B~u zzK)dQ-?0FF<3#V^abWMDft_qjpe`P1Wj+Ejz z0MgR(yU}5iVsL}4Ksp45t$>b{wgTVi+|4%u zX)CbYv=vB-iN5d8!%&K{6^LgXldHTu$We2bpF_;T*lEn(KcV-x;={Yg#}v&xCijAm z$?ZUf1GMpS*pngAX=G5xdzJnIL3**3!XIW=;}c1(_F z@|fInm8EH%vN$Otj86Y@tqO8fL0pVPK10@rbeUAvnGgwAGh&4uVzsyqx@#C7VV6NS zj80`Ed~qXch_}(H^S+yGZu76jkv7CcKIAc8t0YseV{)yCo85~)F;q6E zd`!+oJhObuJYD|+&lqu(8*9sY#)Djh{tCV+1K-i3cn6xK=TThVKfdriCf5QDz)@V< zf#7okp!P;Wl*oZt1Y*&m0*pQi0w9mc{f^{z(jKHXV%-rlj>+BU8idp}Y9P->bO*#d zCZ|K>F}cZrsAF>DP+VISB=i0S0=4-`Vm*9$OfEC?&cUJI%P5g9NO&ES(-HERTm?YP zV{#VAFaA-YJs{>U!6-;JE=L}d8v%&VF}b2lE#;|=aZFB6_Z*Y65Y#a_MJQpG2PI08 zt8h|Htq?ukQ;3D23Q>gW)64?g`f&igvP#w&=2Q?anb@+$P0Dg?=UoL z9QX_T2w#N(7Q?Lh!#R3JuLFN8kkdHucRhiy9{3xq6)6w=H38B%@HYrCf-Ns!`V~v^UBXp zcpv%G$=Z=W3z?4mJ-}FC9{E#{BwTqYf5ei~=P3O$Wfo zJo2YQAXMshg^J>~TQ&~H7ykOn)Th@`=W4x|;3Wm;Ae+b2l; zGU)t3621^}PSyC~2Na@2b#S5bqr?!z>LM1I#0Km4JW6Z;fP{$>w-L*O81{1tj|y{KZ<_DG8h{KCC_nhgW%DJXNy|1WSHR^J4i1l;LqwmYW9Q~do z&X5Sky@=r;9;InWXwR-LS=)s}3k)k5}Bt4{S% z>t9;ENUgaN`>GWivyY?DE(`sj6xsl>SPw4(x>^Km339xrSJTd(OkS_17Xtk7o~m|h z8zPP@Kd3A-IStv-68cp+CeT8jwe+eGy>`g;k2Nj4lmAVWbPoh{E2#Xb}01|&YzJ(V+Xk`D8>%5 zPPaY0I2Lflpo(HdJHT#Kgj$4KERp_t$+w9eoOXYg0#0oXUu2N}PzhfKwdG>29`3aB zOZs$+Yw)oLXakaSIl7bh33}L_rc zh4;RA->3t`UDv>*T-|mz zmnuSM9H1?KHx0gxz|w0PLi4f#j8k~I{cq08bh0*quqB%l2n*R~0-;lVCJ;lkdeH=; zKdSFFFT>$QEQE?)2UWi}rVr}yBIXO;hZmKAi#&>1hm6623rR7vycMIi8ZRHBCQ3>g z$9bl4D7P9-CFx{MNw#EDNfxq?l60z%k|t^OA|(YT^;Qzzl_907w~}3MNF0OAgF(bf z*(e0YhJ=ok8xpy|(r3HF9D?PB#BWD%8;m!f`Is~L9$usrwIRWW7i0DYIr7rvD$ikc z>)z3&ad`1Bd3bTj3B209_CB%rUY=N7CCb#Ui*1WH>inXT>D&6o^Ff4;0@sv*d*o~b zHTN|5^3!qU^ZP&dafct#i!q&F^g}j$Yaf^-h((J*SeOne!RHs}$o1;;Ag(|xTBHM{ zK8SdkcS|v%#5)j+BYA>|NG2SW5R=Ci_whYC$)VrtDA5c6^Vp(}kjEB_0^)USQRP0P zxM1~79$TC&E^<C_M95iq4ZlTwE*?`trZeS@p|FmX^8WL zuT{DfXC{g;#JP-^DUJ@7;`9TA#EB9O5OX3nLBvB9yidO=?yo(iM~R(4d*sjo=IJ-b zMsWr0#rS^QDS$E3E+Ye5nOtIbRwZ!aQH9Bka$Yw&gl> z<9V0dfgnahE%}LeL)F2uq5cZ6Prqw{Jl?HT6&da+I!b&3jHi|A0Iyc+ z5_EFW%{jkT9O4Q6=%Nm>Ke|Zoze#^ngM2!~(6!QG7LKEf^z6>-p_MdfRYAk|(z)D& z9E#8uAZH4^L1TIZMDe^q+OBmbEvc_{WFC zML?QgfmezMbm=TZ-crg-v9Jb2kZCO`Mg(W`^YEN>NwF|_xfze9aPq>)bB-aZy!`GQ z(!QZf87p!Xm&>oiTSIAd=}dnEdC3bS&-oJ(0Z>I%nfDoV+mdocoC&FTZ|i=;~#EA5Eq2>Ui3ys4B%m(IJm3@0y)Jm(rB$je)PNZUb|GS(sh zm%qj*kJ9MU+36!(J|6%nuTvVuoPSbG5;|Uilr@6^S)UkQ;3*L3(m5p|yuT?g#lkWY zL8j%R7!jQ76TmA;mlO+=mkEPVQ}V*dbA}RCUdAU#C%TleF-dUwHW|Eult!1%QXeBP zd12%^qlq9dizP?eLb{Z(RVi?pAtk)clt!1%O{sC2XDp;VNNE&vo}ic{bVRQX`#LQk z@6*G(PXxMjUP%M5HoP#3g$4W$f=o+7F(NqMr-GM(E-4l!FPo$AaPq>)bCxBlybLAC zXLKoJXENZjP9}J5D2*LUs-V3Jv+SFlt!0Mzg)O% zJqJ>*qcn;+V<;vG9YY}Ht=xdr%Lnf`5$MucfV`QMmttY}h#=FRQ;Z1CdO6|wpT;G{ z!sO*j6dq1q72wW<+I{QOG%e9)(<~k9d@?@ zygZafmrnZansD;M$a7XDg1pRJ326=KQpUcnjLU@h)>~K?N~25X!Wy`wPxyrmrZkE< zM^H=>I<|$B!)pO@|1)^=h(MRlBQ@cbfEPxwu&qRpX+Kbm2+sS};T@w(iiOEb`p{fB zd12%^9}rbuRw2k+x|Fe>@QJaoQaBnEmh3Fj=+a3ig~G`TBhQ(e2=X$#K7r{{#%|%{ zOIUL(3WwFDG`e&?3dJR@^@p{iG>SQ$6qAIGQIPUPQ$WgKbuer=5$MvHj=YggkVdhv zxkQj@%PB?#XBlvIZlOzxg~>}=kq##>j6CN_qRPwY#z?zPmok>3B`!y|hWC=v=+bc% z&wlz#g+)I4TZuIKJHVlFW%_d&w}``S9PZ-KL>jSWvEY9G55ce2>i;8O$5#LIthYLH zC)MG=976uJ;!xMmgAc@i#C(!*Sc=0MvG89{U--b^YYxW+8rQ2hG_FiPQqCdqiC+$9 zaX6nt6KTXo$AVk=AA+Bt)qfdZ$5#JythY?@4f(euFv3$D>iRj$xN96PXWVzO;8O(| z9MW@Ggu{{?>ijdsf~))=g3qqizXD&!R{#7T85$_TVR%C0dN7B&etI&l4~LN)j^yzF zH~t)#d!0j7?-8-o|I=WjhHW`~oXEINnpm&7aeb37${|(mLpB%nPYG@=dnXVb*I&%^u%)wzf4l8r0=gJccuFii5zMxkBT6`T_{p+*d znsM0VV?!hDIMnqsopCccT*%=H4*!4S-*UO}w0eITOZ|hB8#PSEVGa)Sa;Vq;lUQ(7 z|3mO;wE7p}>)7i5I)$Nu_Z)umiE*8VLtQ_9oUY>v|A*j%wEAb_>)7hQETy4=7!I>y z`JDdpaA;ha{>l%;mtsEUIc&sXvsn07)^Kh4I{ZHbU*iMo|6N)`x54R*FoeU_9GaRp zVpBd4KllUjNirJcWaY3WhwV7j>l4N4GdP^X;lfz(&p7=r4ts|f90zi!^KX>NNNL95 z7!D_MsN>Uf`k*-C`(-gW4B{|~!%-aS{D)^ZQl@b@gTniCKO#Y>g^Tly)T!_aU= z4l8q5heKWe|HT^`iA_Jzthb+Y8n`0LGj4qx@k1DQD~|ZCjO)#z z(vPZ_uAjnO-%=b_;IImZI=&sJ)34Rh-zW}e#DaJJAHxs&KzTnD-@mY-_wgJ~YsF!E4vkdP|4@AHB1YcyapeCK<1cggPxa}{e7kel zhr|9Hnl(3K(Z!5#BrJ33ZwiNtI5bjC|3mT9Kal@x#@FHUXa7TevN1h(9PuxhKYh1? z{{D&ob;jT4Q0YhIGq{-k8s@u^!x#>CacClq*zcTvi^JO-K8Xc?<-d5TxPMDO<6%2X zf6*LH<8U5_2G#Wci#K!;n|`jb-V&EGaQQhb!l9{2Ble;APfHs49&q?i{AVz3eH`&6 zxtJq^siyy-_%0vF|0Lsc$FV-|86Ol!{4vH?j3a&y z;}&zclEbwenwl|UhdKQ&hmRGmtd2CUPyHXm-}pdzKNNqR_56y%_Z%iJXRrVNbo`SK zl=nmN9a(St${YH-$>CiNb*+9Vem3)85J&#i7}q|I_y>%8&f(u2zUNS{f0~L$%3}`S zaOhXbNZ0)j#iwU}apm8M@mo3kr}|80-1Io&+cEA$9Pz=dhvXcl<}iIM`YF!o)j6!m zVS`xk75|HO(BHqMp9`$dYaHI-@BxRiFfZ@FctaVn>8EIAgFd8+5zgaqF^68Nl+h2x zJDGp8IP!nT__T4vuVCCd4mWcc!=YaPlU0qB)zyq}3x~Tn{NLhFe<1&iTyA(A>rEr+=|)ba2CkKq%u9^$H>55@n<{NvRy zG@XFMR2=I1|4+xi`9OI;6d%TVn_1J)TnvZ1In?#}q4-72e_$N>XJTBLIO6v*?jVQ1 za(IG6z5bVK87b;_I?vQLuJ3U8zs0McC5|h9^^3vkXL7IoLw(eb28T25pYZCpP1Wzu z{u5sP8fy{euk@qx>H2xXIQ_Rm{XWx?#&sr6Z_QyR4*SM}SHENVe+938(J-#^ekfl3 zwo1o3#{F<|IEX|2uKlOu)vs*CRo)N9tB+Kx4}LbOXJ}A;!Bf}ghvL<@rBgEBf8wvc zf2%&L`cL?_%vb;VXE>+p_22Wkk)pm9u&BOqy^_QKEna;eC9eF{7ctalApWU7>Z2HC zxW4~{S07p#7)SgD#_1m**cXd_95owOswtqg^6==8Suksm(u5;WUirZff+JcYxR2pJ zflCKRcB$Fmvcr*0SRS~7aI}v|YvHtBN^3L~;OHHJo_`JCn!>e&>j2jot_xgOxbAS_ zaDCyvf*S-E0q24n4mS>N65Ld{8E|vq7Q!utTMD-t?pwI;;5NW*gxd-i1Gf`yH{2e$ zeQ*cij=-IO`yK8q+V zAB}LNflCLM9xf|fF1Xxq1>lOn6^APYR~D`^Ts64baG$|_4%Y;(8C*-a)^P3NI>U8= z>ju{w?kl)Ka6{p!-uTLeV+>q0+;q5^aC6}3uqPelTmiQpZWG*QI6C}E2S4}1{RBsc zA`ij+0{0u-DY(;c=izR^;p+^J+i>`5g5wb!zFpwJCkY(*6o5nEAf!KBAlyfAIG69h z0eD9`xDdFka5#YN$P0(V)DE0vcHsQ8qdXjr9XoKY*ijd*0UVCKI&fIlfz!2)ws0Nb zI>L2@>j~Ezu0PyRI5*rFxbbik;G*GXz|Df22e%k*Iouk!b#NQuw!`g&+XMGA+(Edb za3|o-z+Hs90`~{p9k@T?p2EF^dkyy%?j4-JpTiLV7X+6O?o+tba2en-!R3I<2Ui%b z1YAkDGI01ZhodH3J-7yNbjY+RTno6CaBbk)!L^6$3Ks^~1FjETf4D(#gW+6oZn$A^ zBjND*0LKKlXt-%`GvVgLErP>wbjNzQZE(BceuO&$cO32{+$p$=aM$5(z}<$s2loK( z1>7sRH*f-DL=aqJIDEau@iAO-xYTgz;j+Qyfur`A4`E@rVsItk@R1=$HMm-Eb>JGn zHG^vf*8#2*TvxbWaN%%$;Re7(z`5Z@!i|HQ2p0`E3vMCY61bIc>)^J+ZHN0F?nk(T zaL3?I!kvOU3wHtTBHR_Yn{c<`sJ?d*K7e}y7t!`@;rgkDHQe6s%GGhjJ}u~+)~eg$ zOAc2%SIC-_r`x~2-zi;ikAV+nwcHqg{-)j2&X>z@Dcn)wQQEfI+GcfhEL^AZ(eK*i zuG#JQZvh<#w|g~w%hX(7{xI^_uaeH0m^xdAur6hWOy9qB@A6KUZnYip=9`-5-tEeC z;LFsTPu{&Z^y=F!4_C!ouqRdP=*96mH~PKzz=GGu3>j2;`VWahj-A{8aCn=-bH1E$ zu1(MVpQmiKu)~SI_qVj`ov-ZV$>5QWjo_n6> zlRZn`r<(U$yk-qnwHPs{@BNkIYbD$CCgFfRH~P1J*y7c$;Cr1b6uZ-}M2||Jyb4dU ztxlg3zdqZ&f5)}<--M*!&|_WWO_NU@ez>l|irfna{8aJIxUZV691s$o&oy&smG3go z>C|<_)67?9EgaP4?8yvy2S1p(>f=h&R<)mT_tl|uD~miVTc%RqO+%BXJX@q`j{759 zRrJq$a&Mo46L$`oSTJPV;uo`0Julv2M#is3pUK_+%(Oo9mnSMTZ)dW!Uv8Q3_gmM7 z(>*HfcyP4zM=Oq2Pn_n!;g0^0#5( z2NSjUep1%WHv+P+>-<@35&c`|tNn)!3CJ~W&+UML0coc8Yt?98#Ze79mOQ#}U)MID zhxF_=)&0eadnX3ooY?!X#x>W}`EJe4&8JW8Nswc9+b4x<)SK1e*Jee!ZLZ&DS?Z~M zS5JAc>2=7VQK@T=F5dfD;sz^TRBQU;&)v82!IRWsug9e<5L|xLth#}7t8DHl8ZU12 zNAEVNaxBahJZO8dN)LAK-#u1Dh;5&h%zE-n_hM=Ck8Cja`0|m5rrfPErCfmq=b9HC zyCS41|5=yWM@zkY3()Eo3`vXDfz`nB)2>-Ve2&UgO)?&lf1-S7Eg>BAk%>ejm+es{pn zv$8Kuf2YZcAAh+tu}(8X>UH?YYlU-X^DE9q~`PJJ@nLeca zn45_+++UfeXzN2wCoY=ZrEIFPqsO|guiCa`)%__g@$;v56Q#W>(pOsBBlC=TP-P=gr)-T_4<;tD-V1Z@!N#82Qxj4$ke$+%G*1-{?c>r--Unt_0{OWtTR%KZ20U>mthYA z6CO--esGQ*vx@Z`)uzw22eil-gmw8hhJ2n*Iwh!4e`ITC z@U9JEd0XwD{o~Cxe>DGe;k}h3ZlwMB#MrSzv(Mev((&;}=~4z%ajaj}Y1Wa~Gy7F9 zyWywh&3=fgbt&AySuN)nelZ`Ebf{lOaCl&3ue5WqD;?|32HqbS#52~(}lk~ zpLFi#Bta)%t*SBNNx{FTzABOF-TD^!I&PhxxAeo%6}y}Co|fSf=_PcpfCfv59Sd-hu+WnAnxGU!$@8?$&$IiNvmo553v0IP3mYH<0+b4CG z&I}(HG$&(JyLF$`p18j8k%t$iHY{^<)Ai~Jwq%@E^;xl0T^H?77d^*ucj>0>3s&VW zvTy6~oiEQ6UUKB#!|(PNd%C^nJa_S9l4*6qFa-Qm9$?%%pE^P`W4eCyw9fBw(v zTs=6e@Y(pA->3g=Qo{cWvT)44f=TCm^7To6HmunBkYmy^j-&P4~ zELp#O&ylTP`RD7FE_m&}i8Ypw_@jqwZK9zYAFhp>dOPF3=XGc zvKLIADp|+;$F?PI6gJGcD}3sr;H!x$Wgk&@SB>e(=kJ_Zv)s>zBN|+(d+D#c10~J_-6PQy*Iy^I;Po@Ya6;&8hNK}-zUM{&ZMj| zs9=LCFDjR5Q+?;T@of{Q-&84NNZQ4ZTklNPbmN({emBmgKOO(-rhbkrHPbyVG^1C{ z-S~U1wZB;L^4QATj%8|IF*s+_`So+%9TF0LeRc8D6T<2({jAc1ttXs)Z>R0q?Ddz0 z{S$|_^-I6Zzf#X)UG_Zh*Zg*#LDvcv3<7cept{h&oz30=sqXrKBcoh_&0FDm%!o(nZo&VAd}G2*-Yhi|T_v3gRLDLQ3Hx4qZ5?>gTtZPFoo zD@>T!pvt^0Gun;*@w?Iu;{BO3d!8Hx8@DPD(WiB>y`?r6YZO)lYMN03@xp&K|k#q9r znb5C5|H+HS7kFJGG;6}2j%@j~RrOsZ@ASxDWzvb^W3z0CcVX1z_Ae{XnfO)fd4DZl z-7Z~lwsYSU8JBBS=cgezwsz?8>PY1W=`$Sqs7aMC<1H9HsPvy>XUzHbRI;e(oR3rf z(jYSA*FJwc{+QQ4ed3>sPwx>wxWoKmd&+#V>BZyq->B(|`8<3k^ox8{TGAlc{|cuBbQYaX`w$FJ`ZH1XbIZd`s`^8-mWw-cqG# z-=M1##t-R|`tE4|wS}{ED|u(lTeIzMr;3AqY+C_mkV-aOS$*nlEWjeuR63jqWJb{4J!BZuR0{`%;jZkvXtMK zd0FmL2@?+vEiwMph#kpa&rI8L;{5pWo?X0{WAKCRi5t6Dte!Bf-pL8eKmE4B>0ZNH z-(CK46SoVzXKN^^9eAg6rJ1tDKwb%FcwkΠbx&v@1`&I z>E34}HWltLqu2Aj^FuqOIlTAlP4`a^DE-yFHy@45G9me#a*gUNPM!9|hW=wWJDk;W3 z+k5qW!YzeTobKS?y02Xb6#Zk=yJS7K4eA>3%V*KY z8|{1A{NkBjg~aJ@2jV@xx+VVm>AgBuDDa@mzEX$6mKW-?echBVPXG8t=TDn9yw)Y; z)R-Z2{XhPw&CRCYkKB~K=bKW$3|Uh6((p@pGv2&*zU9jw>Rw8`bK+hPIZ zGn6WMcfj%zGcKJ;m+_NL2lswjxbu>c5j*}kvt`e!7Bl;lpS9%t$=|~7Ce+$KuW8q3 zgU<}Tvn^+G&w)LkmWuz-H(`13)}{MPmn%6qP3=<;>vTweYvST6r*i$#>F&4;tF~pW z`P~hM{F_=UjzZ>|;H@0722J^jP|M{j-F zx=2jl_7&15U#VUB(1q&_%Z3jfIPz|fNnuyVO>gi^?Rkec4f-8}{wwy5X63Bv$MFXO((KGw%7|+~I~Ne3|y&dNEVsCI#Qz z`hv3|&+QM#)vY?A^bK$N_wql<^UKo)1;$orS^0kM4b_Ky+h@VcpIp9ncTk(##ctK^ zz3;P0Lub?p&i3fa&*cgP%^FhtuWL_h-*~0i@^Q%_uU9D3_tT7vKJS;N-A~8Mr%$*2 zhsrrGr5n+r*78T~V((XtkBIzu&-tg-2!j z=wYjJM?-tQJfh9Sc~2Up=4mp&T$AaIJEePaugk9Adq(}7q1BuZ#+F@sIyT?-FB3NI zZWrIU;O+6hjLf!V)Wr3%7pC8QH!gNwnXTu0Y~0o1gFTI&RbE@Ht>6;Ww{tin~#G$fa^6d+wP% z~zLiL&14pj=slp}0U(*AWv@-~i5x;La{+o7c< z_RH0N<(&FM%PsliyR=8T_L`bfyug};+w=6hSHDovmi;#0{WN<}!lHZkN~eCb`*G2< zJ=>IgbQB`CffFrIb?{Qz7wT{GxByq~xkPVS2uLwLd@CbZ(6g zPi7nRP0rN*2TL~1Ft_^U!Jlq8a=U1TqHnyFx68V@uc!Ip{SQ|aTXf|7pk0}29r~{Q zOQ&}aAGQ0;>)*U|wS4A>$(x_tTm9r&u8f~vPQKOu+?7p3ehFGRW<}Q=>tmd%+ea2H zb>jTGxxbyboW)yg-@0_)e%QABq#8Xdy!lf91-~VyY+3d4oTul~rt9DOgXWXsaz5Rc z|Nf%FyM8EMyw%t)v9rROuO851;*(QLA~IhpHegJFJU3^z8;~I`--oYnO}p>h`5n7* z`!?3w@!_Pveyy5JdOGWmlULT{9Q?|LpU2 z;UoLBd9U&BLq>EcT&PRC#pNq5E;nlaj}^yMjBPk&N|WUcW<+&rm%CH=#utM^UR(3m zpi?JyJxD+J&*Tr+R97k6ya5tbRzurG>j1$K|P8J7439MUQ;E zt<->N2bbsGdhpbZufDF{yif!xKnR4w5Qu`^kOZl4 zADk-O6SRYHh=gc}g#rZEv1 z0}1d5(i6y$7m7dys0Xb<0VhKs3Kl>-B*Ga;g$LlR%Qc}m1VIv{z#S-FkH0}Mw1aSn zgc#5_;1l5tq{4l0>Qe_G93mkaoCZ7>jD~24gY9q>^i97z@D%hhvb<0ZYC&HZ4|5<6 zc0&@Rz#VuBS(unD0u`Vhw1zMk0=wZ1q{4mhHsXCkAe4i8&>F&EJj{VO*bQeO74Cz# zG4BxyLQ@EZ2pA7@AP#mz5~RQ#aGG#$PymWUHHd~dxC2g8eun}O1i{b_`od_4hE%u@ zPBZp}0#F=+AQ;*~I7Gn$h=)UP9G{9Mpr>FdpI|5zas=+y^I=b^}GA0@Q<$uG|9*fhbr232+8d;XZh~ zaSbR9wV*YG!4Qao7>I|!?mQ=iLIgxX48%hsq`)0`3ISo<3&i)}H#h^Sa36;B)(flv;bLPsdji@F9;y*UozArZp*@Qz^ttc5#} zyD!H=EeL@yh=gen3kh%t&cg%n_Tv~R0u>+_+Cg6!4T*3D?t{~x`-1{d9I8P$L_##g zLcjo?8OlK|2!Sw&glP~1@o)%|;U?scpxr?Q2!SCm4e}1;zMum1g;aO|-a+U%2!v|T z6gom*7!PwG4jzDaFz1JYP!8%rYY2lO5CschEhNHuxCRfvJA`AQAe4hz5CWkv1fn1g zw!=|KhMUlIDEmMJM8N`B3%lVwc!yDL5DC*D2I3(JQs4okAI|eb5vTz5AQa|6mPp%hhXNzm2ZEp}M8N`B3%el+Qs53eg@BP<6N*3us0X1i9_BzYbR0!F z!x>10`=Fqk91sZQpcaHcC`3RMEP(sqjN$&F02GI6&=fjCUlbk|ywXxC2iiU?S&$ za2O49APx?}dAJ6Fleh-df)EIW(J%+%U^^UzWC)BxA3-p*gT62x7C<~C!Wp;&6(;i@ zAPj~;6vRLR9ED`K3EnB(KLkQ)2!?hL4lxi9hu}OEn96yf9t?pfSO9BbHzdI|cmP4u zI2W{oaEOFy5Cid$2xlM_?t?R(_X`D}IMjnsh=y25fCu26!TmxY1VJ#ggK&t1Xo!Ub zNI#Qy2t^I`yD6)|2LokHF5Qu^pNP-l&4*`pK zXHXo1AQ;*~I7C4V#6uFKz#VuB0gGuHPy|{-IE;p9h=oIt3^(Bsq>rIopdeI$rqB`k z!e}@ODUf9e_XDM&DRhLsFdCxaJ~&I+4+5byRD-4v6U)6qBAkJ1@BqBaxi*x8S`Y%E z5CP+14#dHBNP-l&15Y7f1@{BRAqaw@9rT6K5Dl@A0EZwM?!Z$BSjn+a9D*PiIznF< z4|5<6w!=|KhMVvd0^&Fp!XXl3U^gT|3fzH!RlEa8T+Q=BDm;MnYxp}9feKI$T0CzCNQ5(R4IV+jI<5&tpaO(ID4d6D@BqB) zY5NcYp%4M%VGcalz_sIfW+)Cp5DbwJ4~cLFQsF)*h%*NigmMrHLm&#)!cj;A}h=c8L6q4a4JcZobI0ix> z6e3_e%z-#K3Mp_0oQ0Bw1zN~2_jD|U|7Is4tq`)0`3I+F2PB3RL`@n8UhMVvR z((mJ5p$G)QQ^=CYaZnCALSKm7&;3IjUf|yYzk8jlAX)RH z?XyUMg2=*6wtalQZBJZh+b!JfEc0zUPo(|6jG#tcBdWdc`SDL1rhUF$NCBG2hPLUR zU-Kq`kNcb2F|QXLxY507o1>TdV5w~K988*b+wUfH&Pc*CAKb8eqA>{YwR#ux0EHAifpF-y`ox^mSI zy^gP<*I6>w{=Va=Jxi-)c3;7%d_J+Z@=LC!=pmh`YKKD4q;5Ou#?Qzb+6WBV( zCuDUb6Ta!l_JWN05adtt(mwZSNvhj{@Ht{;ycz=1Ddz~6kp8(bY(6Fu783-4l z6#=Xz30!?N-s`+E!Rr(uaJ4ynLg4B+XdCTyCcq7-wZ`jAO7J>cpwAYsvk+Di$a)r5 zZ1*~6;4uNMfr(z{I|$hCb*>%oI++f7o$nzdfv(-5GJ&m`326NQs^0KAJ)kcEt&5=l zeXkP(&!BBOpA(eD=X8UDS$$4pXr0~XjD=P?e9joykjLkI4YTw5oc%C2pU*i6bMpI~ z15luV&nfr5&$(U6=i~_TIr*yioLbPZw$B*|jq3WG!SFSxJ^bE{k1BTeIalDtFrSmX zr_ZSf**^0*6`);zpED6^4e&X=q0T@b<3gWPdyvoR17{&=y3aX1&*%IBr{?>dM{sfh z=Y}l{IXB!|%(-KH&P~X+gwF&*)}=n@2gtIF&nvHDUzoVs=On;{H9luE^jhn4=0l(L zK4&5H-r#c_{%F_rcwc_pX)e$}zxvoy2cZ`HEj7uT~keXhFC zDO1b#c_&@E=X-Ze@Hky5_dz{;&bfX*XJdr@p3M8v|81)6aYnT8I4=`qK5>}G>7qbx z#M|7i`E>)^f8b5lIq>)Q|MEBqN4?HO1yv&zrjwb>5lgb#^ZEI^|Y+ov(JHPxg47&F8&NiDa+S`Jj z`F?xg7oFZCxc+m3>HGBXIPViY|I1X5b9x#&BF5uf*x+%p5)|Jl z3-_JP>ok4M>+H@)`z-Hu)_g>p96{R~<#qb4rwwoPI$5sJwy%1fN-z1G(E&cEQ+e7> zC+bSH&sj2?dpc$JbFeAp!}U*dt^ilZFPxwLxlT_{J^po(&p8z5bB3<7{o`HzzpbcR|G(7HcZo#M%9_N#+R#q==vis_~&*vm2a-Cy7=WVyH|CpI|E?j4J zq}Tauo!5EkGJ57kpVRgOpVO?P&zUt7J-~CQb$By|emUkOx`)qi@ z_F25q%DU$eYwy2iwCj4a+IIKvZU49k+dmN9FZre(x{iN)Q}-%U_r_B1>QL{#qt5+E zox4Sy3#86%K5XX?xopQDOtRybVqawE_{A)KXhq#~M$^x*$e~m`{ZFdbIR%w7_?$ms zDRr>Rhd$@c3O?tP&a|5@=&@Nor^V;!bKXhQlk9ie?t59P*%-YG+jZ6-w(IU&YugX6 zo88dnc`Zd}<+3{G*L$b7TUm`<>}5P>$5b3@Wicj`UBg$`_xydo!L$F&!j`f;`{PKD zGlOTJ&$G|v+0P%e=iZsw>dJwqcCK;f?0&vQS4h^=-ZSxUJ?eNK>UcZq_+tp9e%zgj ztw0_B9lPYWO&(_|bv%mt{Wf(w5n58eC1+nX-F*2oJLey@tge@*|0-D7=PX8dwyI=kYc>e~u7){`7V2*nm}OoUEMx8@69)<8{gp z<^9j}I>D>G&TMRf+Sr4IXd7M9(*9nfZ!ha}ygW z-YdMryRHS9r+A#=aC9;C9X?&>aYn-7_1I(Z@;-Di3{Lbo3m|nrWr>c;Lz}1oH|Uen z=dgQt*u&n-^b)q6lk(PcOgU@M74y)_Z5#HFB%XJwyIsd(t05ui_fWg{b0zJ0x4vV? zeYMcGcPzKccI%~mO((Akph0A)KdN3P1XD2kPh;D3m<>y zbt0e_x_1VYtmt!^K*3OKL~!O{U&4+vJ|_hvKVP>p`0OjYw{z%IwWF=*(_EZ;$_Abl zU0NuW=YGn(mA}ef<*qVUd8@2d z&MIS-ugX^Csxno1sx1BGc=D3G11!APt&c;`Ul(ZgKFCEb5_~$f6TV?<)3W7Kc-KRd{e--&t$dj zTMMmj)*A11%1-n;>!y31t~2e}wjMjzO8N;&#@hCN_6K>0*Ra2pSZwd(4!R)c3iq76 zf9V;o&(5=AhF!DJB>VlHU+laszjg2NAKG_YSN|7B|2IJY*F^t!LjRXV|4$6YJ|E8b z%GLj4hT47o)D8QkyPebXv0d{(W4q=j=xE*XY~Ec--rYB|?e8l-V+}5Ue?ptq7=91! zTI2W-^oV~f-!;_k_fRW4_r1T}{}uF!p7)kpkJntW_nUg(&%5CAldr2`W(|H zofFC5-)e%*59yjw?_eT&av_wb|7rnSdV8Jo5YX4_ybJY*c%3llJ=E(=hcdiBy~A9* zL%qj&yhpvuI=oB0&lA`lx8V)+Pi5$U4jKvLS2K2ojhnsBA(%n`wGj&JLs!FT`pdf@ zf6DhDpGtX5~!Jt|A(($WlRdA>7SRuu6KRTCCFCP=ahgZWf*fp1bz2xcn7;gw#kdwCbCbW z=*wiIRG?p%os#)upYtAc4#B>ImF;}aVMwCS{}Ep6hVFuAVf=p&#`gWVKPVG{EeH*H z$Lcp$&<@pi+?ZG0Mg`8>h5cXJeIsee4Gv5`E4{h&@XE zg=5$lH(fhp)FP|1V`)p0{@C2IhjUcMe-VjpUx!|295I%DW-a~9Qu>+i=x3^&vi-Zc zZMhZopc!=_k@r8IcQ48Oh1mj^>e=@EkL+4Ii`%g=xzau#cS#@lbw|23!j-B&atX*STIos|KZP$1>+4c|m&UDQSXQ|WFp?TDwebgPvqYQTL zmF~IM)HJ>F3;oK?E_Qquo?q>37iBNW8f@irtqS%XebjBnnq#hborIUDE9HI8nNIjH zX3-a&w*5B-+w(kM0M7Ao7ktm3IWJ?}h^eN}rq-}$@|Ljs+VO*J2l@NNwDwH-8H-7d zt~OgUpaJitCv9X587p+9o{ph!q~3hL z8$ZoiyT?r3?fhHY*!IfIcF)P5+5Nrj+BMz?uakeU-NUdlW^3*!Y}*einC&iqn&dUt zR*H9RrLFYq>G}I1>eK?t^nL17XX;cGb!sGa>Hu}>4Yy8>LuY4T-(!p==Cs8h$yj*_ z;|Sj@{D`sm5Am5?WX!PFi|?Y8*C}1vt~oNVJ;$i@_8bF?**)#2d?X(+?$^7_=dtZf z^=SuI4@F z$cEn`A2w4}e2CPG_pn=zQ7;}*FY;llsdsp?{E+#SYT_RdanD z73*8u8DAaUR@06t+r;j9iM##TJGMRJ75hC;-WQ(hnzTKR~mv9yV)egTaw*9uq=jW^r$fqS~@i*Un z%f|K|7P$H*b-6uf|MIr~*um+X+#GkTo7cI-b${c!H|AlJE%!PZ=*v=1U{77ZW=5|( zdq`jU0`=HO+j`sQq?W+PRGRTV_CV=R(C6s>?jx{SqkPWPsrYku(64;Kco3Z|`D>Kv zmU@)OCzMAw%A*72F@o}FPI;`RJnm8+SKadHH{NuKY}vW49dMDPBf9h78BZN%Jk^Tv z)M>{3k`ZB6HvYMXWqk2key`s2aY;q&9;#=u@rwFR^_%K5)n7_>Ww77c(5G(Uw}}O!tQ0{KHE-n#J0vV(?j9J@3>p@;;6x^JQT{i_=Y8w4HXg+Nu)Qn}G0(!5+#)S5}umwSWptO6@ zMZ6Qe7xi5l)5(`N1OB>&PQ1-E?|7ZX5dJ&ILmS8EOa_gq)mP-oMSlg-5xb!JJJ>+* zJ~l&VXkUtb;Zim1uIkuiHSwLpT-uoI?n$kD&Q4HY_AQ+1g?|NV_r-RDZ)tz>8Jw7i zF9&2NyvBQw{UhIk^lQ2}j-ze<4&x8{oNciAFxLdh)M{4$ek$hH?Vjd8mfu?bYDrmq zzVe4nK<}=cgAeH_w*E2vqv+e5fwX@(g|6KwT|3<8Bum$BI5=%xz+tluHMdn)#~6oW$c{EW9|21uHWQrQ`>&rz(uw%x?G8)ouTtSFKFOxOz{%f&%P!vJU<$ z#_A;)tAF0z<1A;qKAG|QFH<~D4aV$O*5aRE?{T8{dYnJ@d7L);X=4YO|76_$J$-t$ z(b!e=>jUD^$EnzVSFy1&aL)lgXARfrg59{JGrrv}=;&GacIm^9B{3g&l6jFc_FT(P zSXty@yd&A=mW@L{EjdYNqk0ogy_rJ2sYAUfK)qQ`z4_%$pVOauvxa&zg?f{Xdb5T1 z`~h`l5qR8sGvhUThkIN*sHMlY)!rn_eRdD;xnt~OrL2w&z;`Zr;`%maM@Wh%nXi8* zwpTmeQRm8xM{3dL>ew@FN@wSH9@+lsU0Xr(Op<-4O}Do`ZQC!<&#AANjNXxSC-IfG zd${BKJ#X9j)cz&Suy?cZ@0R-52|clO!o5xuHeLNi%;jS9*5JH3uz5Q^M#p4g&a$x2 zxrdKrdNZGMJ(PLL(LQI-9BfT&-UzqeddgZ~mYaU>v!du8+Q(OA?Rr=KHl_%eW_5hv zBQQf>wbcEO0FqpCXJo*akf-mA2XJ8jB!!FqSwb$8>U9dk5y2Xp` zdYd`Q61=z4=%PmS=d_y_u?yZpFTEFqp29A88NKu4A@tNyyVjn~Rz4@_4rMMZb`pwtsP?$N7wYAc8)iKl(o-x}Vu{r*kdtEd>AU0LDG&^nB><575`S(9IXn z$z{;JcVEVLk8a&q4gE^HU*3yx9=h>0^kG|cpJW?J()5nJ`R$#JiZWX)jQ;sB{iNh% z7VF;@y1FF8r}m!J-$-h?x?&X1yvWrR`SRI$Z(uu14z{*qWVcFEmRsG?*hUgVo7H`2 zeq1umoe!(CkG7Y{*pxC$ciespdd2F|Q;%&Yxc;5YytAUbtG9Va)p$2Kc_&?Y7aJpa z?(Mek_5SwGhxDcn(QioBrr5Q8AKCU7+>`D_bKa7RZ`v_m(0`T2k07ZVVb9~A)0lPJ z#!ctl{yx|pYyIi!@AmWTdDpwoyZ1di=kMHO?sx2*>#mwEeElr_={c{nWh6 zc>~QEXud#m1)3+&9D(KsG&i7m0nG_WvNK;M8z&ZZl@zUP+Y8Wnl3>OjdbSMQw}1TcI?tBno+kME`*e=Q^WgMNHb1?(~U@#rqJxzF*hfkPjD4kFxsyz&^k#$WVDvp%!?_~WAW z-7P|~5#}&waTL23rqFkvrSEPVh##50y9a&u6NuizSaGY*83%VjvT%w$|3T{hWw-7x z&1COcaTbzbeB!G6et&qS?AAZ;=|v3IX0LM(+oHujp8bH`SH}(Zo)+)1<9~W;Wv&<~ zNy%Pz&9vQo4heOh|Lueu^CFvB5=Z}`Ykof3woehmp_m5w$~9jqf4SyNcd~Ee~M92e2S#~A-iTGV4__WtB&IqcSvCefyM{Qe`)Fbk6VMlsX$#{Gcy}BALnyqRHVwmQ1M^{MqSu)Uq3D(|(B+`l84atiQP<%J z^Dx&S^Ifm=Iy}C|JHO9dPG-hLaFDk86{OOi{|Q$ZyFG?wSLGx?|_V>>l`9;q#u1-Qik4bVPsr-tZfo zionK(lLI*yG?|Cb9vaVQJOGUr;CF!Fh1kT+k`u$KL?iH*gP-E#BumfUFy>KF_TFzqZedV@$8f2PDZw zdsmzE#}ZF)$4&ki7|#c$7ncvW_B6hy>6E>p!~oGBeRa(1{Q7`*K|ho`*ypqx&U3nB z#@2Os2F@MJ7`YE)*)HLGm%{AXu7+VJC2$854M`0wKZ!2T)C^&3++KcQZ?Bj$Gm?=y<}Kb7`Kxn}yphkaxB*!~Z@{<_=v?SHa&vihl& zhkSjKGQ_p3Oy%E`9O-T4uQ^c7e`@Yi^PZAogYA9I$M#4B$(_x%zveVGpQ*V_&0|Wo z{KNH6_p37Ecu5^M7XO<8`anwrDa{H^A0HE$~^ zSH-DWa99rMwECR`r&2|rKT>H5YwyydojWx1+?YKhM>^z#IlN3m_W0uF- z@2i>L(0uI3D%c{_p$XKVz$?TAy@bE5Ji4kAap2UM%-p*q{y)J69XHR)>hfI1#Ea~_ zZ{A>C2j^c-A3B@`yXNdI`1zVR&m;&%GPh4hCd z=mT@FpkJg9Os4A6N{a{z`N7u2oF(b&zI&q4%`FCboJyPuUbA9O6y{@Zl|0T3T$!y}rG`1<9 zg)s+X);;B!Gx`W0J@sW9I;ReGrsPKS5IW~1IwuEprv*BvJoTqI^(UPA(;uC4#??9b zQ>+fA!3LEaoNe3EFOuxHt-Wgv&Owm$X>9l8w?ES^bjQ(Uup1!0+W(BRocXsoyDHf0 zdXo0knN69o5wHth=e;<*6G=Y$c|E^kTOOLvGW&}l0~k%eYd|4d%F(to&5btZI5%D`2DtBJ@7M$MokJ(L05)bt)2bLw-bW4rN%p0)dJ6L0sMeu14o-nE^Z?6Kc}bL&*3Tc>((|ML6%|A}woFlWLm z_KdRo{WgF3tX4-f=OgL(J@1@U0Qtrd%L%+prpa za~XY;8GVx#ee-ie=772}=Zenx5}k7nol^jvlOCP(5<2Habk6x<*vP}tUFe=E=$^^w zo_^?_Rp_3$7~+i3JuA>XbJlTSN+Df~JGTZE( z6m{1<LSnFOqw;tWAGei*;rp z#6*XBoHgzo)3#Aox1&bdvCZ80@}niOyGz;ef1-nR{*e=HpT4{882`Lt3)eUKR+8=C z*^Pxt9cATRfAD`@EJAVWt?tzykDj|5@11S`8Xf=ooWHNlVHc-71MZys`$s+EqtIU+ zd$OJgJ4|snBhg{j((dUwVrOXfW_Rr`HSFgT@Uea^bz%G}R>Skjk z#mFc=MzJx9i&0FB;$ajEqc|8z=I&{nbo`r%^DTlAoO6C*VrWV*?@j+!zp4QQ>8d`|Tun6HN}j1wk8i+NsW2xuLU{88;G z>oG8t@{WPVCx~|ftr3#1sug32VbGuP#9RnxOfeI*en@_-foaeq5bZ_3LFKoJ?*XkX zl8>u#33M3rDD88m!K_9;XFH5;V*alct+B0Oe_O`#@NFc|!!v75l6+%7OhPwCQO@+! zfpBU&`U13GNq)0shp1bym+{|KcMO=syr%l$2l4oKHrl(H6=db97z0V}S@Fw~d7oMNF7IIbK7QGBMWutb-E^m&TQN71wLaVbjo)oM*Z2R=hWhVj zLzU=i?`*N#zQf#@!s{Q{J3CX}-l1ZeBn^luR()w--G1Nj;eVfam0Nx6UdM&my&iI7 zwzZB#Ye*zr-TU8J)waj*kA_8+Xp5O>i%n>YxoC?UXp7rp@F8wsy&*nBe?RJ>N@qwtHEl)Z5``R04ti6P~ed}F!4)lwz__pU_=O4!h{Tpi$ z-tsy5=})@QZ-me+`oE6zUUTCjSGoFk{A1HOx+nj7oJ#Kc z;-DIK%`$GB!R=g(C%B%Z?U&|%`VpUP&8eopPUf?Fi{jqKaBol8_keqEhlkj6DE?2f zfblwME*!;}1W->GW4nFQkbA%`3JN8D4I4pzW#!ROjAolT#AIR@j9SaODQJw{l;tRM z0oVfhC>xcJd}IBvrIynF*G!LJ5w5+#m8_~Ro=0r3fqPY;wgJ=#!^B9XpTek8=BkD zyoTm9G@qfl49#O`4ny-7n!C`vh2|_YU!l1Q%~MELt~UEp?@^Nbrq$Q%7l^&W?vwOQ zvNl(dnFm{Ht-|-^Yj=AO6$W@Snzo|1>82r}5xFjRpT{9QaRT!2Jj8c@kIR zF9XTQjn+pLrfAWC&lNO1rVc73+PJV$eKf4`2#?@c9(O>DYztdo2=f{q|kN&EL{)$3> z4R!TbO?M6cv(dx>Q+HNVcmDi|SX}Ck2loP-o zHJacW!>*~K;y*6Q%om=Y=Bn7Z>)FzexLGmqjqqa|=&m~J~qxvN?ZL|&T zrX%gI=g$75}u9m{N= z8rWvtUHdFG)pYQVMz&92b@I<}jcvrxZM|iGi(F}T{}~W`F7%Wni~H<~3zGCPj zQLnbsFK#@J-->=QhI;iN7=JkRs;FD9_V6)Moxekn9s4Yk)rq-J@HalSzg_xUtWbt3 z%hw3S#;bZSQQspJAV z*z_FH;kI47l9j7+nn=>I9!>9Eb}ImLP^ox|IfIRcRU!rF8FEi>)(=5;&ngd1n8wK|eam;>C zQtKnNHc}E7XzNhJH`4AP!*{k$HDNY!Kp+{D!=7a~HP)ZsX5W`)pT=h)suTG#%{ z2h34G=8pIYpdmJZ*0`sofAOz#|HEBlye+3!{V4V_Z9gw>U=-m(4nO|d$xbsv(-{jClw7lkD7AMPpSpj+?Ve(_bFMP9S-%vh7`3dDClz&h@LHPsa3zYxQ@B7Py&8%nr*SOr#e`_PJEVA;D&9b1P zmFX`0V0s4sdadRQtc?9RK#m`?GS)*%EmTm<3InaNDE_K4oRwq`Qr&L+D>O)4#q$|2mTXbvOO%>-4Wj=wFM|zfPim%}xJ0 zl>YTi`q#7cuSMuzyV1X%rhhF=|C*ovbu|6!tweH#(Z7b%zdph@Ho^6cJ!oyubW0sN za>Z>|qp^D=og?k{6Wwk5-4?cevw>|>MIHU0)=_7#Xltoo47KM7`@;71+so&_V(yH6 z|JBd0Yi#=mALzL*)`!ZkatI{Tzq0nHIZ?@cJ`S$;qg;EEqA!{rE&RQ0?`~`LH|%4^ zRw4M+Kc$auZ})Z&KfL+V-!z$Z_(p z|CRb4XFX$`UunCtAsf!X)}c){--z8$+uMVFOa^vjpVcILM&ypOC*wZ=}e?Ehm8 z=;#)QQleW2vkOZH5P`S;JQ)u1nyU2wah$Jx=A@l!A2P#8zO zjW1vpd*0ch*)F&F5j5sDRoQR z@}Ed*d1 z#&HU8p0{`h${Y5e4Y7q>`vdwsP)YG<;FTU`+O-jE=Ur0V_XZuWRYTG@hS%0Q{0siyUpdsr#2ivJdqqo!A zF+R#m(tVlLUF9f~G+ATsSMem0WUsYz%{5d7Ne4G})4$fbChOp|HcxB#3xU@0*8r{M zuL)Yu9|T&{-v+d&wD1v8O(f|%ErGACE>C4+sdaQ+3NZ;-g4hb(plSI zYn&xR3)wwhd&TZ?w)+lyxIV9=QPxfeP+ujXZqCq5jDI8tN?X~^!H&9D#Lf|w(fTIk ztWmxi<*HGh8p#K5+4bh-vh5xRY}+40n^2dzYW7Q0k9L7wkh2H*s3I9hP9q;x4F1Xu z*bN8mUNX{e>DkpUNqVQVxy8olyyo3lbAL z|Dd(fl2yg+_Xn=cJm*`}Ns333Bs8?&6{jz$UdPIIIpbc*p`o_z&#RPuft8E$-6+?M z^4uuLjpW_h|L2&Dpb4hyO7vkoimp3`uDd(b%KtAnPVzsp&h{k=LFM3|x4rB3J6fAA z*|pN1Q|rhjEzelJtc{-Y&sSt}V^`1JCU)&7ySJYh>#4dE?`)T-h%c$an47w?oOa@=M}7cozPjDfMPZCT z@s)S}j2OE9#3&44{ntR|BnB~G0uQH?zhge@v=$JPh|l~*>R-he{AEkf=S%TVEW;?YPA9Jlw@i2M$!Gm7byL|wJ*pBveBT{l*~ zz?-)J(xs-O6{je9gE&SVFMCq5r82pU`B(W%HTSI?rkej&9#hSME0?L}!IjTcbK%Nq zs`+r`HPxKBa+_*iT=`A?bK|?{&s4W$yUOmAyvLd`{Y|#6Y*@*j^44D{hDS2)mc@K_ zB|fSg@lhwca6fK*)NXR<>AwB>^X|>D?dvn_`~}EW`5*C{r@3YA;V$Ee7a1Q)rtdI4 zvL?p18`d#Bq&!HHaT!fVKhLMZc7tuEFO;*a@)G)d%3OKMBpcj$j(pIz+TD9@+l z($99i0q8qPe%FVim{Q4vZ|wI1C++voZ{Zu}@BbNjfnRs)k>97?ySC{}oLzME;&TkRQkGWO7ZzoWle zy87z@V|BgjFX!0x8l<=Dt))ImzVBxB#P5%j56K1-l~tS)nqoYV(z#(X{FUs<*k-n zC*DQ>cNQDJ4`nlkvPq_Fw!39>^k-|2idmCvxo*d6OePt=&gKd<#?x3$QiNPKDg)&n z_2;vh@ek|AlU;v|^0G+2Ut?{+pPO=E8GC2%7a^{*D1Lx4_~y&nHNMzjW%$klyRYT9 zZQCDzT{+e6`_IDm`=4&!QRR?R{y621Q{FhqoVE6Tl%HF2xS5?x`C%llVAE+FEPGD2 zoa{K+aI)WIyUA{o&E~h)md&*1P#zV@=oq-4_W?W z`Htl`md{xJV)=^YCzg*`{$crsa-}IxnsTHmKiU}jV&z3s zPBec$v>|a;FO&;k5{bUiJzvDOlPp1>s6SKQW#wE}zGdZFR-R?$SXO>z> zK4s-n_UBO^kjBbLv5AtDGFGO_+b=n?#I}{QUozIsm0cg5Rui4J37s~`)oHi>wjTPI zj8?wN-7l%S#L7>3k0c8_*|p2IuyZF5H=nlRa1?tZ`C^{!bJeZ)A*^54^D7^!d%|^-o`Y~-=X4F6rZAa6vdw?-bC>wiYHP0h~(w6 zmM^~!Hq9%H+uAU`eq*G^*@-SVh%VSq+4n#Xyo6qo1YI=yeLDO3{q*a2PTi9~e@TsY zro-!h>~ms6h)r!rtR=Rlq_DfMKZi<&w03OIYyF$~&)o$;v&ioXN^Rue{01L9g7&{yg-`p{!i=%8jIa^vb2I zob<}4ti1HfsjS@e%B!sW^vbO~27Rmi%1uuaGXlz0@6WS5xQ&fx?=<&0Re5g7z`v|c z9KK`E*P*99pT7_Iu%fl0L9YFH0-IQ6sTd$h7S^0;+dpOxpkFG^wsP)hU8C~uXld}Wv^G+?d$c}M`FpfRQaOCIPEvV%v{q8Ne6(IN z?NNNqAbEg~M>fNopK%``nS<@3=gsc5?dC67dHHj`SL^2LfJOHE&RF~1pX=*Ka)IgW z=X+tdW20qaTotyDbu0&L|KHs;K)2@Gc4611P@W9QtK`knJvE~Z^an{5H~#HK+LNT? zEPJQQ6DR3$#QKgUOKtz=&Fr51-z6C_)qa2G_ATj#*zw9aCkb)qu-?K3khEnHa#8-x zMw`4!|NJ&>?Kb`MNZRBi+T;Y)-TECB-po z?XA|rY5lF%!)Xn!*2HNYuGYnAEw0waX+5si$7xNj*2v`yuyt};o2#{QTA!=+a$2LS zHFH|0t95f)tLtAo*BrYY&xcjQA*?vWLs{3F@9zH*S92IV1H54E{| zH&8y3Z$UXpYJu{Scxa=_O>zvBpX3ivj*@+#JS881a+UlB%2)C(C}+v9pu8n>U3*~7 zFndRbhgw~1{o;bm2 zth;yZ*btsmdnwM$?|0i<)5<^azSYN~tWuMlrv44rJ-8~j;-~7_|zVxjx zedkNx_|o^i^lh&t_=WUMFMZET-}2ITyz~t(eZNcJ?$UR=^vy1PuS?(R(s#P_jV^tk zOW)?wce(UUE`5(n-{R6Yxb*!keS1sa-O_iq^o=cjUrXQCnv`JQ($aUd^bIY2KkK_h z;_=Z}-ydY0cOAd;4f{S;|ND$VvS8b0weMi*8(8}OmA-wY?_TMfSGTc!^o=Wh-%8)M z`n?;zneNO%_GGU5GwNS|+R_00LIcs!gBV}UW4>*^eVG*qP`t$*SpAry5MMa|F4u0LuL-ndq(`RZal^-2eOu_Wmc+POgokPokaFaob7S zx>o1AROWqyIY6`JX%94{~E1{IT}u2bwQSbFrFBl?-!ZqIzGWeI-bS)XyyA{=hlZiHS8W0OD$Pi z+jPo)^qRzjzSjFu9Jl24zE)@Ttu9GWN z{T;?ylDL0}_d7*go%)qqdzrW7{v|EkcpZPA*(bZz6MfH55{J&wp8u!swXOMwnAw;A zmIHjs-*N+%DQC~FZwX0yX0~f8zFtzr^*?GIyW~fFe!B15^y3GE?7mATTYN>0<=E~k zi5K5(fB#^;olD;clpJt#$7r3oq%u0>dAT;Qa(Xfm8k9J!T%j9tz-D7Z&9tU zVs+@NQg-ii|KYrsv9I;3^0Udt?g+}$=C`#c4Y6}5$B3l*1G90ev%loH>l0CaWl5c) zw!d-_OCGPnuff0iwt?cUbew!b(uq?yG4F92Uky4$V;kl8YC?aYypj6Wfc!A>N6A0> zukU5bSv&X6f_AMJU$yPce~Y)tN&lettZ$q6`-u0chk9T7hLj}tyLJx$_pq{!ux;f( zmIO0Sna010zkVAu=l>fhhn&U_H%2pG0Ci`P-vgBURX$VA5$c&O42Fl=n_!9_7B%xJNlMNrM%~|t(5zGab|oi5SxuQ2br)*l)K{U zYm_r~iSokj@DYz%Aob6 z!Jsvze}dMPUIKk*Q0pEN6K(B-zBj1#5Blbye+|U+@}{Ts9STXsRi;~%M?+E~i)|}s z#q(|Qo2dS3Oz6*Xa$}*LLv2S=ZKL%I{;}%ovY5OZ@xg_v!{+cG6 zt?$|8*zY%7TkrSMww;N258bokFa2{L8&=ve6Q9{NS7)_*@P8Zg#&Wx+a;{5qyS`L? zLr&6RrJZvFzx(4}7i6;XtxbKFBp)zcruFxds{O3(D;K&X=x=M_tGaU)OM0V=sXLO~ z?mAO{+{f3hFGB0NBpU|XHMOowl6JYhKjkNpv`e*n@Xtp)nP&I>uir*XY+`@YcT)Yn z;Hp)ueEjpF%Uxfz)`Uq4t+INcJSG18H*dNzxc={nu5!|017A7?cmgx_BJ3O}6Q z%L`eVKYGpX_hCD`f8{5Tlw4}}wrdLO+0aLlhXHmT`Tryv>0?x1{Bb&aKDKgJE_%t1 z1Gep7r`GOEyN2@3NG`0gGVXfHbe3&^E%q^(KxSjc7pw_X{en$Q)@f-&HHw4 z{~Y|dz4rUtN9=dmJZiJWK(aKO=`qFNN~#mG zLUM75oii2PRMpi@E!}S(`2Dt1#@IDv_ey%dYJP@))p?ibuXG3cj_{Oh+%PqseE z-$w{|@u0?Bc=%=BFjNl+hq->F@(al-6x z%LDCi{c_=V2T5OdJ+@*w{c)P>-FRhx+{ih6Qz~!S*OI1jrepQJc1civ8;j~YZ~DfY zzVD`QyGa5Y*mL^x^?gkIiq@?cuR{zl^LBr+Hm@UdchOy0r^fuZ#!5Cd-t?$@MjxzqxI&0KGRZd&w zvsErz<*_ZW#q!rGcdhc)Drc?o)hbu5^3*Cv?dx|fH?8v0DkrV-(JB|M^3W;=t@6(* z_pI{HD(9^7%_`Td^2{p7tn$k$x2*EYDyOXS$tstu^2jQOtn$YycdYWpDrc~o)DkrS+!TNK-_9E6srL1ox>idZLHln_ZC}~#N>Vm$7Bk9z`wzb|+ zGSaPENBGW)BoFH*^nd#1kK|MA7R5j)XP0txDL4P-Ui9N6zk))USE=vafYt%pA+fMx*BcYuWbA0OJn!%_aFAdU-^80>YJp)0@Gbu zx2LswlI7XWucvhuS}P%GJFEC^)*`-=G0EL7jGu?vu_dnCbHy?ql_X*N1o5xd zd#0~Kj@^d%-9g{H)0zZ*_fG2)^zA#XP0;u6v_3)Kz|$H9eFsnL6!a}TtyR$X@U&h* zYn0QLB325tc0ucvvzNB-^FsMKDLs|;pj<}ALpa(!`8U7yu^`!ieJd)%Y@IMWy7TXVUp1t-BmYw;<-DbKSlt|+tGrKI_syoTP%3xq z+i2`qe3o=)->ziG#9S&%?0aMExNJh@auUV@^zhtH!dO6Wj0LDQr}O{N#$sjrMh*6P z`%7+<`T9P#?@nD?W(~?On`6M*0Bo%tYX`9PcC0PH*4(l709$v*+5~Lv9cve`^>?go zz}Dcg_5oXm$Jz*NEgowpu=RMXt-#jgvGxL6m&e)+Y;7KEH?Z}2tnI+o=&|+#Tc^j` z5Nxd;Ye%s4daNz69YO-viXmtJkq6o3Zc8 zvEy7V{r*%&_PEX0MAYpgpldwf9m~EM99vwwX*DZjJXc>l&{$yv+Qt8ARCt5px+at z>D}#jJa1k);yK`syn{B@p(S{ii#FC?w6XlWF~=Wmtn+AN^+Nlq1=?3Npb%}WWoTcy z#-I&`_EmeduN2X~dJh!PzG{m0RmVqIEASZW6v4A6_zvn*%o|4=tJyfr{lvT56>eDD zJ{8|wLw{=m-rWYFjkReP#zHTmpN}@y6O6e&zJm2WXkRr(`$Qe>E46gYpDV$hL3nq2 z0Bx*;<(Sie_LURHx;CPHwV{QwEVn(@#iNaN6K$-tj%Wj!V?1*>)=!PXJ~pE%5`w8tU4YaSC9>JWQ zlW3ozjdcNSto>+XMWKxqi8j`Lw6P-2k!_E?q5R4AA!3IH-Mt> zI3IV%cQQTb+&I3@m+h0p4kJyvZ*}YJM$Vvn&F0Y6?Hivlm)3EywW4hOCp)(GqHyf{ zPVAU)m+~Cjr;rnhq7CW^b`3Uo??-%>ZXWeeI7OxL>SGP{QLJE~`ty=1B@MAI#3vU=-dT5v*Q`oqB2{vy(4=Ab~r#0Nf+rC@^cR56ZTzd zcIfiCM|FFn-tR}c?bV|=b1`1R!q<(JB;$F^=Hjq5C9F-&)|Ie!HCtQ4+SY7+NnQKe zgzrtjzS+*c*UrAx&c4&mj&!s?oFG|$o9&}k>V&##EcS3lJ(mjD9+2~vpsxkk`+?hl z&0S|>P3#+4Y;Q|8=ET00wKiHw#`e}>>q_zf+hd2ViHHE~yN+ya#6rNnZNugnvGzXu z#toZq#P)w-&$r8{AK5-I>^aBw)nV`#mt5v+wk>^@41! z5&K>*TQ|tw^|J3~vc2QkJKuMJeLIWI!(?Mr>>FBaJ|-J$Vc&OR`}naj7xtYewjTw{ z1HF(3+yToAtR7+e{~Rvd#k)IpH&$-z z_LvBHMbFO-C+PayZOPC7{0{ZRY@`$6*tfdbTIExrv|gEgvzx71X5Z~*>z3I!-PziI z_6={ghM9feo$Uj_zUR%>Gk-iodjha;d$YC8?7Q!5e*pHKZ??|)BH9CNuK@PVZ?@+7 zr7^|~0Q>$oTmQ_y4bS!vVBZ2~YoXb9;@N%z?7QG>T{Qbh>@782$fzP3Ug4lUTW9->+at(7j*SVkv0!$5!I&&_Q@DfvEnvqj*qeQq zlg&M0>r2>o<=Gq*w$6loU!KiHVe3uUcjnog6t?ap9k976Z2ie(z~-p1btp3do2$as zqf7^E&I((X!se~8wJCMqrO$MxdtSHqhBn4b8$pLR8W>V?Ezs!z_$yBG;z2_W$oa*cq33Of~lXPI;f@X)Z zDxELl&!6OlR7TmJ-t16tBmZ^#i!}bvH`rTZeh0HHTmM}*$K%N|ibHJ~#WAokwcRc} zqia6k>na0n=yzf)U8C+B#ESX!`wee5EefUlUblBq^+#%VU7khxe~m5quiN+Kt}msj z?t3&Dm`}lUWczN{?Vs~y47tTwpln-{o{xBYj_nD|j#F7^r$V+EhBdC>Z6NLck`#xr z8!+)T?E|w>75iR-(}QV0n8Pz@Pnb75(a*(w8~#wfH%twGug$*S%?^zas&k($!8|nB zZJrV+iaZxB9YwIO_bc{u<-|t%Nhj+H(C@M+$h#^ zzn{UrLDtL01~=-|!)VKemCmxmje;B9Kf0sY7Wj(30J6|DFGiac7ppxFi34i2q*0 zf2%>VqZoZU_U~iN^<_t$ZS3KQN4Yewh`FcI{wfZ0m} zv;~?#2Xq2mfg$Jx`T-*_2n+$kzz8rBSbQl(BJ@ddNyDpdnBLO+j8~!xAwWrsBx36}-$0 zj09G|2H1lMzy(YJQ^5={6U+u!S|UUDRJI6s10UcESh`n327(PB7=(bWAPnpT`#>Z( z2x37TxCpL*B#;Wy!Cipu^JUnwN%j)F21Vcvcn>~{S07Vo4CC~sg0!=_u&=Rx* z9Y81073hKPpf4~20|Az&%gn(@fT27Y9>+2VFacmFPlj%|j8*sOM#wOX#~#bFMS!Jw zIiwH35SAP|R;4v-35Q{7cB!d)yp*h(-fT0$A_Y3I; z1>imS0)Buh@Eg-~`423`NMMfEmCGEC5S^5AX$eOvu&%)|^BYFJs-wP_P5+0^uME90W1o6hJdr zb`e|!N#Ht20e3(qcm$q;X8_GTSusGjNA>}H0vJ+|eF5d50{jFRVwTkc1=NMgpaEzM zntjZQG>xT3MYzSu{z~fVf=8kN8i?)MSB}F}msrGp5Q7^RF z(A|k``drQIHMnGwwSqyL@oD?pPu=WkF;idl`Zm3j-FLfYxL(wm*SX)CR`!oR^cZa1 z>s6P9EgS0j*6VRMNblRdO$&%DXQ79H8E zVBF3^d#=u6wS|4ABrYClre}ECxj|uOtpAHwucmF>s`)24(j0D4iatr_FSK)*zRhZH zaR0RHcfx<%KcMsL>D_+aytdi>@qTdab--|)o=127ZF&A$eE0JYEoSGry869M-u>Wv zpVUT*TlP(AYw2pVv!Zzai+x{8Dz!ciR#?<=t=i8(m;N(r4Caj<_T{ptX3W>GjqFt& zt`5*MpHk|%rSx~ONu1Bty_1(kG=Cd>N_$ier~Uock0&#(=wd~ zHXSx%K*8(>ZY}}4{M+7LHs12}{M6i!8~tLdXAStNdrdJ$&oZF>(#Ylc5zDf=JnVAC z?nP}`Le;&y7ml^ubo#kLR!7~lSE_siN=F~|5BhrP=tj49-fzyV4aD!a3hkcVY1*nN zy_11T;sXWECCUrBJM zp54GqX|cZBmVJF^ZYw$e-h7ElmD+vXljAM^8V5zV^xNEC@pbWm`VGeRYWwop)ZR^p z$BkML5`JUIkfB+5e-5`erP$Xf;{Jz=z4|TDy=?O$>XG{AiYdd&hqfC&#j8Z|!13dn zX~sit*qRTWvvXU=H!m;g&eFF#+9EtL<$J*U5%*3hm`0YkdHRkHJ>S?cYRUW73DJii z<*wAZ=Avq# z=JIjel;yuBYj$e;>BDDxGv)Pu4OY&M$$oG@X0>t7n<=B`RkS@g$T_-e&Ew=X>lB^S zH>x~ZTyN5-sh^kaa$W4Fa(e8>qR~%-?QcK2HYMD%Ec~VVx5B%QwrWqz0t`+kgudzN zz9o9sr?a=V$3ASdROw}(iQhY)+ir2^f}(wf-p7{Dzb-R=X5PoFMW-DllRqDsx#wx# zx?{uF+hgSiYYkTCqmwkFZI8fWi+o+XU<&=;9jm&3Xjjg))H0iQ~dT(2;LpEW? zC;WPPSEUZUpt!YNtBHd)IxZNcWfC+@b>xNYk=ZFvJ|tuhzxwgToP9AH^u5LvC=99j zxvA^pjxAf=GSl$x?z6PVj#VmEQ3=7_52`!(m+$Gny}B^;N9fPYkbJ8%u1dB)XQ^({ z)K|M3r?I4X+N<{iwl?z_sT;V-&$1x>?Sw&zKlT?bZZi1voer`tUA@Zx3_bZZ%QWth zS4XE^m;KkwbjS}?>aH07@I*|bWj|x5SGxqwN*VF=@YTrN6-(+D9vI-`lKQFF!B4Aw zum2sKYd!au<>6N+d>fs6VcvJf4)>y$GZ+6T{?p)|i$}=GZ`~q4jP5wXcXh-155A9D z^Y_7-%2cc1xr?0b&9aj-we@w{oL@Y(Bt>&X@3IYk8#+DPb}u_@=Sl4cDMK2XJbO_; z`+e}%wbdHEdNj!1U936WZ>&~tkM>hH_1E3_)KgVK$y8zJPxIbmoZfE;__X>=YLM=y z2|c~zd=E4kQ$HbMMq4k#xE|xm?jHR3J2U;?>ND>K@BjUGnPZ`)WAEK=mO4+?j4fYO z_PfhrrO}az`X4To3{t&!ZA+}nz6cdduXpbf6lHps%4V+pRXp3NS7M;Ht7)~7i%mVP zjK2-qsK3-zX>+aT;Euan+uT(%R;l^wxz~7e=&$#KPu)>TzkS3o<-6|z&GyIE4>Z|v zCEiulec$YH4SKITQW?=E^z{b4^N&-_y6^et*&BV2uNKEgJwCYi!c~u#kBdLwf2O!+ zyvE)4E4waeJnr^q{r&2)`UfowhE9w=_jW`^y!FxFLy87$Xpq+OYyW?Xe#OW6w`gj1 ztyNQpOZzo4@ip}`&l|VgdfC6G%kDK!mpjDk8a%n?Yjfu7!g2L~91Q#B|4D0Jt;Pe> zF4gLzf@`9RPTrsOx9F2oWA#y+7W>aQTpV$(^6sbQ!!ye7XdX4z^*ULx$t+amiG6S* zwVTQsjXS;=6l6bo$4B44d*1Z8mRkk;92uU|d+ln!L2uRW*`K}l*75%Gn~~EDI~L9K zv3MWp8MQK`#kgS$FV@6nBaWamhS_sEm8mD@FX+9%`$C^0<;AmlEH&PBuAAQRF;{2a z*;3N8Ys9#)`3+5tH`rzmPY7L6JM?h#QS-NJS?$&tyYWclc1L6GJ@b8beB}2}O9K{` ze@QOL2{CEkVuztyMC^`z?X%-w8yXzwf68v*n3PUdHtL;s>gs5$ecySE*@XVb7FvYf zy)pQhmFwTjlS({(+?n*R@!3IYeLAX#__&NU{rSq_U6=Zik4$54Ehcs z-|U(_W1<4jzibh->Xt?L6!Xb1)D#0%kM2Kf^!oM;YY&^9)2G-ETQRcT^%JX&v`gKK z9h-0cV$=DLjYV&-Zcbm)ci!)`4ZmkkdRy(-;?9u0N7ikzvD~^vHMzthOEqh%`C!M8 z_jxJZFXnv;nDV@Jyhi)0s*$@*Y%Hr){nzd--GAnSOBr#`Z$;=Ag!EkeX4>-ndd0B=j1vNkO@>X)d6@EKTweRmueDoE&M{lC zPD>@~Xu^UOOZ%qwc;2{Z^Q|jilKuMEXe+&L=zZkxXrH;E2ZrdlKe?P-qU+bS^`7d` z%x7=9JX7f%`gB+)+jk4J`fpg)wcXg81J6E`MHf10l=@B@SQ?sh^iNX#YYQ6$=(wdl zj0v5aaaB(?F8!26MvY6#yVjSrw}$LIQ(GQ(VV9qeQNXs{xvG`nsW%(-&dFG5s5mTc zc0{9W>-k27=ci6Ha?uGl>XWCk&$fEfmG^T$TJzgks?o`Xu|xG+AF$fC zu~qNLAp=iuunLXy>^{U_H|pl4fZ`qzkZLMvj(3BX-?qL^Ik6+=S%WC+4P9d=_KvyKC+BZ&>k&0-tsG+SJ^UPEmSJ{! zX8*GBtIMBF3+wdl^^rn_vF9wGrQfd!=+Z+G*Xu z$7-ra$VIa=3SC>RacFR+y>kQQ+ffNUZLaMv8mC-ZJ}P=+e)*Y+iC;QR*2;6PEYfuU zyXwoWZhGf5I^B}>cs;$+r1=PE_YXZL`SjnSv95(ilifbc{vLK+x+QNyqbQvV(SBa< zZSuFSkJwartjR{zh59?&>TAF6+@XA|%h0In$&Pa#=&cyC%%uDNZga1vWiD8CY6vK_5%kvwxQ%{dgn|bkt_PO?zdIh_` zCzqrTUf0-h_uK*Huev-;p5s@noYubGoiE2d6V7#87hBZ&MAs{QWBm?|%oy=QBTq4C z*WZX%mm1Y5r|&%9$tQPH$;}VH|1?nk-fh5CSIg*sCI{SFMs~L9K4(qJGbnV@KCIJe+<~imVm4r2% zpg3dr=^f3Q#t-S<%JN*)%N56p(xURl#aApj`q-dTP3twEEq>%qcof*ab#`RO>~fc; zy6G{qoBTO^edOm|WwYlEs(ha8s=Rcrx$2&T#f{$AYumJG=dIz#zy1Aal5C_<+2faI z`^+pQ-QcKoYul%#CzOut>S-Q(@K~Q6FTb20r}XP-W&KC3Hdr@(vS7)vshYtb8g_n> z+iqyvMytau=lFVuggx^*A6q}5{n(SoCm!rEd-9I7&cUOf_quXxK*qP&RU?;m49?s? zIyW$In$eeo!%Ms#k9#qzY(k5k8l8uC(7pD<+dyNJ&p;>LtdW20W!b77bIro%Zt?f` zSdw9TtJROo-CLU7^^43}aqU6Ha;vuu6OK=Aujct=a@T78Wv?@vMnp_WI<(oQ%~_pK zX5U_2Ev;;+9zEsQ`SpIMw;$Wkqh|P~Qv=L&gLLB0c_esT5AI|8IO0s}t17of-}gfA zQ>~?ewu^bkuGOV0X8GSr{J1pJtHNn-qrRi|I2A53Db*O;UBS@8;dbxIZ(N2t>4ZD& zjqF;JH`;C9$;@T>ZmO3j=N%vHwqp93unV%HBWeZjVm+dIrfjZW>GE!D#Mwc?S6=I- z*{F25aIs<5rY(vO{d~Ijj)vKfvhTE3 z2wpV5WV>?*trxNlUn?r-#Q#dtx2`t3vqrVor<%EnU2W4AWhS+A3o>5tvOwuhZj6BPWUjoAVFty%jyn|+pnHjs=1(@zthV;d0WE{mTdo; z_3hGz>wabZc2v9@7!dbyqU()Dt>!yuY4#r1w{M%B7TRjRHrSsSc0i@MuD3x(+%6~W zs*`IH&%Yg<-9vF>l$HK{%OO4DRS!jF_}sZOd_}kMzt{ZsyS=u<^~85p+Uwu`=-hPe zh3?IhC)u@}(4llh{sGmBBHbC6?e@(6{&qO(=i}mZv=>@}ouD+G)UYwZxYE165@+v#qDlfMI zwTt>&H>uGd(_~O!ZJ*PJYpmbdwOw(zG)3cO1OHYX;+4!(J}4e)6Q6O>e^6S|#yw7I zr&p?t>Tx10anhWB*DsG+mXfGsU;oe@W9?-sL$;;WtA99LTj9ct&3;O2%Y24p{s{_s z+0O4kaJ=uet-no1{9Av+MyXZt?*7duAJ7caeRIO1Ky7UwhmfS!J5LQ9W`1z+W}har z+75Fw@EvmKmW}U=8n@N|?1!G$*z@*@vtt+k`F{qxy=wn&{?9-0J2h2r&Y9@#>w3c> zwes(^jk(IZdtFS+l3f5!;EXSGLWw z`+6k62ZeFZ5;zEMKy2^v5jbFX7n!D}ETI;hv_WJ*BQ?j$-ar=0)%7GyrHLZNo zPffcO)XDd1sQNR9^Uq&2cbH!`aLt&3%J~-KU(UMOaqX%Y-!~)n?YPlw@WBU%BUiq8 zJUIPHL$k!)*=DFFbr4F6+3pv%>E^`6&m& z7Mt9hlKJ$mhjlMaTDdCtKGid|Ia4(@ziQs$M}fCt z)u)B~Zlv9eeP3&H`l;&S-!E+Tg}H20J^FEU-z)JeJ1RyDJfRZu%4$fd(%Q`m9;1R08{{FW9SIFfuX<=%m6FEW)KC=f}0=*d;oty6TA@Y1o{JO;0hLiHDDJw4iZ5o zCi;1Z%-=Z~|Nd4?z+5 z0aS(}4}u=R9E=6Cz)G+MM1%9-7I*6Mz@+1EJtBNC0=iEARy5%o1+&0Pumwbe^WYYE0X~6Rpkalw3Vor0*}BO@Dnt^OZHA+2(Sm!fHw#R`@tEI13rL1poty)gZ{u8xPk>>4cG;agG7)C z3c+_!-yZo0bO&a@2`mL0K{z-KZh)tt1gJTnz6Je&C2$8z!A1}cPJ10DrI@908ZWJ&*^!0!1ghmj(L31lR!&unYu&2yhYH0WZO4ARCMKc|aG8 znTU7NUFz& zJi#ik6&wT?z->_Fg7mv0{h$vR2_}L$z#nV}N5Ca;59EQbKyfnC5A=Zvumc`o83+Oq zAP%H}EbtCggT`)ne+l{m3or@H1*<_AI0`O<`yd~bgL+diFBlkrA;2C?1KuDQ><4E+ zDtHFogWo`HD)Iv82P}azm}GD*TEC;7W@JY=fW1CHy8mX059MNLcw8>0PccU z;0sWg2U`F=U<_=5J6H-ff^cve+yGBO38(^%=ED}C4;Tq1f;qq+YzIfcC2$Yqfv-Su z0m=~22PVJ{cz|Uf2tfiS!C*f)15&{=@E-gIYKu{ZKtEs!oWVR00Cs?5;0kyEUW0EyX$i^@Fa)N+ z0Za$W!6pz1;z1h72Bn||s4qns0!F|JxPbW}5bOjo;3~)f1)u^bFGG6>bOS?yBbWhJ zfG}_rTn6_+J}3wEykQGq0EPg2Fb#NvV6Y#Y0jb~_cn^L9wdJq{=m#u;GnfYgzz%Q> zTmcWjYw!&yt$;0nAut6FU^-Y1Hi1YG57Iy}s04vNNH2&1S3w3S02M%aCDIGJfuX<= z%m6FEW)KC=f}0=*d;otylT~>3g8sl7xPk>>4cG;agG7)C3c+_!-xtqb&>ffoComKE zfDmv1oCE3LIrs?vf~J0Gw}1g)6qpW{gH0e3#Dg@D4N5@`Q1{2Z2S&gOxPbW}5bOjo z;3~)f1)u^buZAr^H!u`9f*D{12m?pKWpE$lgK|(W0QVjkfFZyhOatB^80-gUKq`0! z-h4}1lR8&Qt{eP9CYfCpFxf zxPzr&BM1kl!42>flz=MGXfx_m&Za4IBa&!5#1td*Q0`LNUAQT)13E(bx1-<}<9k2z^1IEA>xPzr&BM1kl!42>f zlz=MGXeVp|`hbyOBA5gG!FF&2Tmtt%9{36rcOmZreP9CYfCpFxf2Cjey;5GOLl=h+Q14Cd6ocALP2mm|4F>nPu0I$I}pcIKPzz~=M z2QVEh2b(}7hzDsP4}1lRQLrD-2PVJ{cz{hH62yZvkPS*f4NyOT`UMyPE8qg=gFvto z#DJ?H0~CM?pd5|57IXtcfg_j!R)EbQ3Y-NuK@Ru;{(vS2VQ(-5*n?@n8w7*>;0#Cw z&%k@|8>k(Ey+J=<37o+^5CDP>BTs-hkOH#6J5UW8A3>e~eSrm-3YLHkU>}GD*TECe z`V8z0Oo0QK4wi#WAQHrbG>{ESK@Cukhuwe?umUb%J_rOmK@7MGGC%>S0Lo`!H_#0X z1&&|_SOGSJC~y|s1UcXX_yd}p!}A*S2iCw9EC6f3E^r(qf=o~d_Me9>!K8Jx{&4m+ zk9?JV6~4MXqPXO;qy!bu5*&H!;*^gv~Y=TTotsP>b@ zO%fAENWXrgjR!Brev;^mCpCU8!Gjkf9MM4J9+X7IX-V`&AzC#$uTMmJ><@U<&NudXhl59vgi`3}~Y z@MK5ZlO?n)g;P%haynrw;_9%F%5W0uKYm5?Clpur8^YJXJ#@uNV{yeT6G_$Krb5*h zSp35Bgz;c;w@v$yufHb3*Qgv)!eg&sBY8#5{*nW|}`d}dei_34RutfeW@^$&TxM@awCD*H=LVInj6kq}SV}%d5 z>VXTC0sf$#;`VyDgOa^^iBPq64n_aST}0m$s~lKdGv|u9EZUH9H2aIVEGCidQ_l)t zbFlP+1ua8OM>S;;rx*&;#iIT8M zl|)x8K!QC(-+sEuBVhQtLXku_ z`7_1?xRdT+a>~bZoj;5^P9i5KtT^RPNs4qw+nf+_-N3p|b|()ZBFKv!=re(ENvxzq z43*a<-Bc(K&IlB@|K4iKHzo3lBOhgzWs+OIA`eD-P+UE?3iWI)NSE(tgf0QI$=53s z1g>%5X0nmTZ*j%X@5t$-iZI*hX=I~=@+vfMBq`xjE86kD}sd#&KUJj1zl~ zoW41U+xd4U#dQ`b~Whi_ltfDkdM;7L}CA;wy;S}15l(>L(i`;~PJT4!^#hu0W#E$STl*yw8inwxlF3d+moBLAWdRfc$S{y-F z?B7Nd7zbsl_}-KV6MAG&mK*(8q|u>*wEr&eaP;Lh<`j92S&E#^lI=TB=r!UtX`kyQ zw9j8e+SfA`(Kkm6js<-3PXuf~lPpnjQRrok9RQfG^=m|2catcturVT=j%%D+-wOROq#G9Qm51D(qzkeV7u;V@33{D=FE1<;b`j+hNDz|r&hIHYS0^#dy7^VJ)jkrqd zophC0R6#sX`SEo5WeJT(PNQ5r=C9DD-BdEJwY*>30KI;e)D!K5*#e+DgpH9Zv+F8E5YzU$2csoz|eJ+vgF4ANo+$61`mBvtw4<0DhW1TieF(nB+(xufB2P)K{<$1 zM?DQm2VIT?BzLJPDl7!QUGXCtO+4Ab$7u^CXFDl(U0ouH{mUc)ud-y`gerFwig)8fcAw=#c7r;TU6cli zi~X2OPRX_+p!H}<-eP&P+UqGjdJ_voz(v87mZqtqm9V^=?nF6uZs2w?(xz6zWmnk&kVoIWh_0w5Zzi%g+RS>TcZ7{Ku%e$i zCC?XWY*tCW+Te-6m0qOWH}kEL4!M5Zak06dH9T5sW`Xh{{IA}S>wm!}cw zwL+f1ZB*$-uNf$OMNFlD`Da8eya9U#vgoyQMY4zUK>;N*;e>oA`SO+zR@^tGfSU5Q zgr6??O70|jCVFkj>C=Ak@aZ>$?sji2VTnP0q}L$Sq&&-y(4_=9$y@Em3dw2OSP^jL z9&#EpS~wYI^8BqRoW`R*Vrg{2Gn?mcZS0%DoYohKE1u7$EN4_GZbx+x#TALhE;sa< zeUzErUlG0>vDX8OOA%$5`%1N;H0sI+p-m2wC0@#NPRGIIq!uS~&U9Bw&`L9*eFxrX zn<6)KSzEGKAM^mYy@D(#=cM2_SHkcSsk-92$c0}_N!9hkgj2imbRYYnNbrE)F+9Q& zRN^P1FB(q14!sj5Y>KTcn6K2?A}*&Lbj4pNXgwxqGcmql&k7hMR%wL24T3akkci!w0Xb{ z7zJht+Bim-u*qgJ^q6Gfw7HbBNnD}OYdgvz3)r=t@MVkrQkYX03}N#GO~x%{PGM+K zaHlmtD6SVsK35`_S3}`QBhRasUr-t+BD-*3IVNQL8Ro)--*%F(`xsc}zBX!6g6e$~ z$@acYO88?Co+~lUfNolA`2dNzE8T52v7E=%vkm3wWOZTa)Gn0laVJIe-FPScgS?0a z^4|R}6heN*6kg{Pq0T`Z?6{1^1v8FLrKsGWdXb73G^B@4Eq2J^;gy$BUT=$z9anEK ziX#hOiC#GOwH?KgIq71=m^;;bME3q6uU_kgQo8)LMY>w?p{5A=P?H{Zmtt|9=q-Hp zn?k8Sl`J$Kx|eQ2YOT;~r3R^b>5g#P`qoQ5s!d342#{qJUKxbLEzp$Zx^<7b2VaXwywsL=%f!wc3Re^rb>L z-RC8>zLf}AQ%!k2*Faox8%B4Sy*|p**af$fIh{=tN*I??W>k71ve}%&lx*A1B8_eM zsKppJp@ah7wy?M~(NyONvie5J&M6eWzCI-FKjKNieSOO%y^div3wLV72g>%!`y3kh zmqq{KiU?@J;~J47R4x2YO4y>|&h7Q&6gh>Zi|F+#DM5zvoRhVUl<0nH> zhBXpb9I%h#+UzRgGFU+WF2vUVQ|AlP zg}1kr^2;_<@Vr{v%JXhLj62l>iFmxTN3!=G!d z@KS|4E&M`y<;jOXW?_3LDf)RLpq(N`@6$~@c!sSer~25qi^nyuh~lbM5|%jBfigra z?gH07hCk{ul;cS+?W2b~KMK`)wD|CN&-Co~@(qdLFRN5Ix_v@j&Nj?sngR*Sn zg$SW#B8ec_1HYbpe(mvukn<}m8yhhbzg?lXeRjzZYPZG zV?brpO+y&lD}xg2Z7(u`ERS?PktUL1w~CByf&?6^h`5l_9L&+|bCws?F@>L^$f0FM_ zw?q4quvbGq(iMp6k6-a)8TmSyD{k5rUQ9oum~wj=>QeOM<-PDfyd!m=>fL+tdUra{ zrpd^r+_R-VfoKE{TI^KjPPG5=xj*fnOzAlJLrw z#KM=7IFT=jcO)7YO271qB;kx^8NxkB3lw54z3IMKN?txn!u_)(4vCD9l86z7&#OCtV{BtDa9{!jYV6S)>%+|dq$IEt-1A?)ex`5HVd@#|It zNz|hKgI_~Xp+ihVUjxD)HQCIK; zU0gr`H_GEuQlWqcUkekan9>6v^sI22YeO?7e9=I`6{q3p%r9Iso}%0)f9^JEM;8uT zFA{Mfj4T7yhuV~iwzJ4>R6yCjrXN+Ni*BpQZF!gRMJ+GBVQu^fn%#CmMPieIVel4$W<5_|I` zp@R)qacyL#bdX169R7?kjdJwol=(+EUHVFyE)q|Be#I5z zDEhWk`7%|nI#a+?@)y_6G2~P!FD99NDWh~p-N@q_gf>6B;@dgmic5FU6}@Uj*0gjc zr|t5Ah-y4~S-@qEBH3fQQDHc?Sp*E}O1`e4g~u(?$(^dG(Pu@1Qk|*DoU9g3CVVEL zn}vugb08I&E-(_0%WFJYq8nb}^9055$why!iz|-j-L%c}Zd&aIvP2sT5%6R(={56# zNRU2%Mb*w%#Ff2?0+!*S!IhZ9UuJZWzswjGNmg}3mjec7$1>F0%wGNPi0HSjC8xZr z!fB!_S>nWRVTpM&$o4L@HGbyeWt|0 z?IQY;J{0{Sd2fDAS86DKi4(TJd5`oOqa~bF_mL%h@ucLoUxhbvEc#TuSm#Ql@?OYj z^g?($ynHL&v~k)Zpx;6Y=yyQ`+|8|O1grAsn@=OFPTneP|DhMj)<0 zaeJK$peuGqQ-sH*+?6}YI}>|mM5rRdXrgb9nI$@aU@WaV)wbfdVQqlHwb zD%XBECa-cQ^Bl73s}vE?(17BK*(99QFo4QT_#soIQH94fP(BehZ3Epj-(Mn6Xm_B1 zH86A&M1Z4Y9~Hi%^0Dj>XjHN2*B=swPWPv{3K17q^>P|HnWDwWol5xYroQqr^xl#Z zWZPfZt0`Ywu--%1>s~x%leY2(PcNP^uRRpLOcco12yLN6%ctaIEPtv+-6TVY8wkA? zm68ePqI66 zC2lEGE==wr;>w9apAx?2<2i&(UPGPDWbFhlIfALIlpszv6AxlAbts>a zXhB`bcoJVRUmadHQ{VCadFj_o>Mb6l{-HVb4+B%AbL~?l;YyvqN)pqlgI7z!tVr?_ zL0!7`pQT@yNc^JSTboMBaSnCOl>bVjcY84-PG^8L_Mtr)Tuf` z;w@@2gj4P!iHX!>svyyidQ9V}j}$|_qG8l4T1(xbBh&%T=szCOH z7)c$O0utKPkD-Z$q)nz+X0;jdb6=ldltjtvX6=kLuhF6)>N%`Q~idnpl zfo~qy#IN*NQ`8eqZ&y=Xxfl$F8Q5_P(XzO@V5Ft4EJJJN^cSUyJH1A8mpKJa7NvAg zPfFtm`Lp%H1kyedMTaYqz#DxDX!P+buGmJtYK?`j;$C#c(r?07EMKOfRbO0DEr-(h z1^pTxeMeog#D2^Q;L+PPqqxS&huEEXwc~&HfJqpu}^hcafyMe`AqGeQx_0`HT#c24t^%RDRqNe^V%~0tJyE{lDZ?q$ZqJ zuA>C0%ex+TztI&_^+jCE{V1<0T@m(jol4qwMHRW9S$8Vjc! z-nAdPK@=qgUL}4n6S_q3X1&`np-amEx&ub+ z5WccEl5zem5OqUp7DXSbBvgHl5d?PA(&Wz`Pd@WoX_AP(R|HjdR@x%2k3T5c(Rg-p zC1R5)`h46e?&K6qCDj)F74G!AD>;3WzhWG8hoYa*UBqRL7Yt0VnrLDBN6F-rHd<xKTdf zFmMv3(X&Ft)n+&O8i?1^JT5o>RCzT^MDI19w70n<9yBeqNH6UHq9|BZldoy=Y|?~B z-yPBOht?N9u9k{%HD36PPysMY3_}IVl~6lMap{-~rvUyz*-j6H_SBHuTOrR?i=ODOSb14Z9GTg26p*SKz7MO=k^Aml`%2-phxu$$(# zMpS7@ZgfSrWRY`{4Jp|QXx;KV^g4-@$h{{5vhUEdxboTxCAPMufP3%;fd`y|?7@7! zek!cGkKc||`R(v-LG{;cR}t{|6N#y+4L;5vGFT>D}7sd@~MSIFBi`pDwiig9A@%M|?&=46A{ zvD~TO7xI;tEA;xrpB>IR!Z=~5`dPqT7>nSR$T&pLp+N_Q5{kV3YH2R2j&UE+gK4N)HX zO{+kcnfdbBA(B0gk8#zXB%FGoS;&0t-7Bv6(S?k2v8}NEUAzQgzLNS1C6b^bbMkm5 zEYXcWVftH%1S#_|uIkYuuK05lP!YquJV6bONQvd&MS@O;krKM{4DgfpKi|nGBQ?R8 z4O7A-TLhdwlj^TuXdm+E_wh%0`C_4$oeN#DQcV5^3_PFy7CD5 zVmsvVT=WxC=VwCQ=kzx^mP6}k)Um-9A&5_*pjh--7X2w%FBG>*j8_*LG_BZGVzCZe3qH%&RxOE`7=%&UF8y5#{! zOd#Wq+ajK0XYNxjHbJT9zFPhw^}KtFxNh@W@`BtTiC9(545CmfEZOTd8Dw*iaJt2N zfTMd0vz4GB$^w?36J|@;MtXgHF0$;r1r*oGW}^F1f`NP%Pz%+o5+n{iA98B(NTgAf zZy=C~_9eHsb`@D-%uu1%8osz}c6*WR`$2Svl~EJ$fI9nm#!eRjeUnMA4XcFq9iSA` z>m}eN^-wD+;$fvCuCYDoVY<#u*xvgZnNYd4@U(-U@y7Nf{ zTy%)8*hBup{s-^yERbh_;|6rMXQKzeb94=FnYEL*%#1J|$TGRlYf&i-Xia%_ojk90 z;Q`OdJ5LiPkgA&3L_oJ2q?et((0-Z|-43=R2v4>Jx_s=4hqefNE!3j|)1kj`D*n!I zT0@b^s}50uW*`gj1nuXgqe?#W&u1p-6)m^@eou0`DRpXhD zRJv&=(HY>{Uyh`JW7>-P%iNig{jZIPYuRqnen+hc=*d?x4|*b^Kcz>xuuHUvt2^2u z%s6Z0Pnh@#WE{adZGungd-j&D75T&oJ?0#9U$&wM_vu>s4p*%2guh;`Q1K= z&*HKK9bP0XF?K&CcVt7!$+?Yqj@9#|@Hz=1U1{3%gt{m1qWSzHU+Xa_%1H z3*;L6af8Il4buN2-Idh4LYKq%8ZuKashNoDNd#$J5-FT=dEKC0DFW7F5Re6AQ>3{P zqo$D4;q&5l>b0hO=hsg-S?{Al(f~a`9`FR-wXnEm#){})@=>}y@=?0>i%Hcoq?HG3 zu$G*{{ug&|0;hBJ{{P?OJ@;*lG4||CNV3cz$uf48h9pr#!eE9e%a|Fv>_teUBt;BS zmcfuhgzQOnLnTSJBq52C{;%s?uX*3I-1kk}=iBdpKhkr~IoH{)bDis)_c`ym$KNjg zr4edCXZG4A8~KwqV&PyrgJ5}gQ_t{)yvzIT_oVW3pS8%nP_^gR%;a>pzALBYYwl?o z@t!JYrF&-=QbQFTG0AS~n9tNSB6`_T75K{~2i?bA@3qw7xW39ZfX7a$eGYY>WcHh? zWj)f-E~{`s?RJ$DcE;jdKzm^UrBhjvq)pv=!_HW}x@z_LA@-mhOi=rZT4|5aT)aIe zT3uMj&e(jMn#oLTe>i9_w9-a2&taEU^Fi&<_V;c3>NHhrjLvNj+E2Iylj7gOaTm)P zdP6N|?g@JbRdc-7_|OA(AHU~!w~RY(H=;hD=cXpw#b4%V|Lz{`njGzKzOc(GfW@w# zG@^{z`4zs`;JwBMO_~_U9}j^p_!*@DV8U=6Qn#7YtTiG}v~@VE!Klr!XjxjI<1Tz)MR$+>ikcf(=&T zyal0c`3>fmF*p@s5LwQk2j-pRt76aq&%+32@(&v3r1T~;f;n*8+hcGT=s+K8~6cE&=u9T5Mq zGtk~YH9SxEgy%83ltYJA>hxIK%lyO#srqhrJ|0gcQr7)fZO<@hl(xQ2X}iYf+N;zn z?wh03&DyT+yB(F^Zfc~zmbK}W9kqA8M!B%I zvO|yYzGO>HJE|u)gcng3*Whz-YSN(>ciJ6Vv`|~$x3eAf>>t|4X*g$MyWmPp#!(=n zy7J4cmcc8t5kY(j)z!?-=(k)uGz^Op8*%xJ*7y##K`d)B4=OKKx24XOSE)D7+pEPP zOB*rd8M~=BA7EKG?I_o?Ds=|GFv#LR+N^8v6!&K5b$)5o{AcXe#|G*nWt**bBO-s- zm1pI*w$$uGs{7RYZOb__N%b|)Z4)!@)J4*Hzn!sQRn7RdJL9XRb(=k7ku5bDcL*{< z%TC%I3ap|Q6IsaUYsEr4C3%<{b~yCSA-GmayZZTyb|><{%}SBOao$LUl;lOtR4nTp zl}mhK@h}bq8C5q*oA=2|yLmhL{aEKm+ff#O#jhP+abWT9cGq^DYG6mXe$uEH;6d2b zi8nQ>u>0oe40e6e)G1h(*od?jbw4n2ogJ0H*Gnqav4^18FFNQE?j75!eyWK}*io{^ z=U}Q*e7gs2(`Y_Z2kKHMTPn{N+U?r4?BXY5uOk_A!x8v{_$=c0PaZ~}(bNv5?0ru2 zIogS~-R%|+F05TGbg$j}9lxqnbY**>9v!7^iE3-NrTaVDmI3SRs62S9O4@SinB6>! zFIgYO0Snc(E>*3q&mVS17k)EBGDcyNQ6Wp`=og+2XlP99eK>A(=l5iTBiNlI^xjf~ z$#{@OC>9L?nr${HgUb_y?mljih*^Tr9y}QUU;k)OW=QV^} zj~d*K<8g!nU}-?RP6jfHM_yJnHNj#@&8>Mz^?TpDwle#7QO(Vdur-%hK@Dz2S=*GJ z#A%D@_ZJ)}qZav`!j@8^E@BVH;(xrUHRf|4j6T8}%lmrRjo95m4JN{U9WrOF+TfRi z?Qwtp6LnAXkJ|0puur9$jJBnm7#3+nN&Tg4Y1bNrCF;|nwp1aEy+nOj-|mowy}Lwp zKW?}F)yrDrAII$)kMIU=`7d_Vb0yVkPh)Liw{P-Ly62a6SzmsneQeyyo)n+)L}9YK z5d)6tG=2gbEn4mMvN{~K;apk#xmw!Pk8o7WsIC0vjp&KCRQxfm@kN|cu&ldd)pvgm zb7NGMiCWgjc(`O)+luLrzrzJ1>hvkwM_!<5M7OYoKX_YP+||9>IADgN$#)jo`rgUk zKrUFo>tK2O!{@?!?e;TnJGehaCrQ&}J7XCZf5QE1d7Fo5@y=DYRL^tT)HmU~SmWxu zRbQWfXLl&^HMR9K?vvtr+%~3R+sJM^zEkCd46wW1qN*yoKYSvKAA3-xzQV%=Ggj@P z9jegC*8Qxj8r9Uj!>wOTTR&;K-TKGh(5Um9?5GuAYlqIm{8{|fs#?|n_gO)79qr>+ zc!Hx;3^z+J^|Tvt<%VY5>2AdPrF1wNzGX|bE2!I`4(^lnp}DmYImX)Ej($hyO;sGM zP!k)bt5mg_c2mO|sd92Ovoj9hdz0U~w^aF#XvUa1cE)K_b%X}rXCDK7!7rr`!g|g= zR(e%izbeUImVdijE$3-G3$b0zc}_FpE8DX*ucqw^YG9W&i8b~?jr86(kLz$uJ!orn z2eyl1(RJ{ho@_+5AeCx{#<0e`PHk6gUt6o6PFJb1AKPU;$?wj3GuDoJw1w(^Jl0hf z-+O{)3|enX_2qNJ7WZ>Q;pI9U{qM3}M>lM*rK$B^up3bzOwD(r+kD?Dr%@3pw!Rje z(BUZPo6AcJa^trpkH2 zy1fMI9sG{e)ea;=cNtk-Y?$8NKH6edLirxP9 zjB2%2OFQbfd>VBUQ-bYUg_}yz{VFUc%($wYHnqU__Egw|eVa(_Xm8he^EDmX$5z|j z&dv9R=AW}`OvidHllXIXgl|YLwHNkG` z4_u^YV296fd?%+WdZt^^_cT>+a^$q#?UN5{jROkVqn*2wMon_h+P!78tW`MC;0P6A zS)aMfTEkzS`7*>VD;U2CC(3CNXSY7r7j!V??WkbBz0uV@w});~`-<3Q>wa4)HGtpG znCBLh>PVY~KTHhnFJmm{E4ZZK+uflCjCAJjwPeR?Q- ze3D7)J=8+s%8b{kB= zNe)8Ecpw3Ke{HbjxIv9?4H};`*mmB)g)Idnr(85hzGTq*4}&GpGtz2U294pp5!x1H z;0iXF0<%P9GR~lY-enAygc#H)XV4gfBKfKqxIzu4R5M7%v#R84Xt1P_L5-#cjhh*4 zYiZzWWiX|+LGoh;y*nE$>0(f$n?d952HScWxcV4Ofw4$C`x*2eVX$PRL5(p6jmH|u zo1>5%Jk6l8o(6xcaLqH3GZo(~GNFNs4c09;XrqV1uft)Xl&W|V1L8Lr1Z*^TL=T0( zRcza9BJb7H;7=5hdMJEJ(O(aR+Z{EM-z)N*H=(x`9raN7vSKm(KdNo4hr+*NCyG!K z)-m8=Jrw?0F}=2l46S2u2G7P2c}@?7Yw2n5F887EKK$O2OudEe?Rge*kGj2v^KDP~ z#CCm%%!`K7FFl2~oh0MB%l6be#_vd5FvOM`zFcSHNtA2 zx48@awfOTV?BbsstWtHG*p8$76B<>lz8&==H`Xm+{%qy|z49lpVz#*A3YD7W-a-!Hi_KjM+ZE58 zqAlLg((Y=nN3?mt?)&g5@LVz)eTy4E@pD6iwv7yCs*gmnV+{>?FlWb z*;-qPo1iHv>r?o8mQ|6vyg}GFFk_8Z)n209YjulqT2^!1p<|-R=jWfbte|6d#yk0Z zFg4Czt2cb3QXy%!RQ*&Pkge`FsOIF>8jFV8?P^+Bx6{*V*-<~frL(X+ydRqyJ3+O2 zUrsx!F>P;%+xB+#(c<&F=fud9Izm6^F=HnkD*3cF^`j+rQ+t1=Qu{{OQT@*8BrkWr z-7aj*j8RVP#({H>zXzTckIQ88Y_6&~$n&7m7Bh;plZg+6D zogQ^{wibWrUOTGKyBhTkHh#>w6vc|3@FKi4Vo-`bDzCOvwQad(_bYCf+SEcndxTRb z>Oc*3&#%2ak?o1+3=YAy+Nz`Num^goX(v?QAL8hoZCQYwrdVFHC+v&|3To8M6Lz~w z6w-{}yZ2cQ*n2D*>1FMotW8aU(`WG)HfYobXg#A2tmA|$Vw=XJEw%WII9a9CJ$cp4 z-a`3|`mwHd`&dC+Du`bUJF}`SwYRcbOZQ~ELsjr&dGzrM^$tH)GisMV69etyKj?jyF4HjWbiqPwL!~~9DK!NL+fWYZW26u-VG{;dsBJZnfFaS#iLa$@u0An9E z*ot#J$%oTM;6S87p^gUVzN0+9l_EHYt-$!js;yGnY;EPk@qk#w^B>#8U(?blQXbnB zTG#ha>A==;uMsar=qT=VkK(+~HDm6#?Toqj{`^t61C~{Y*Ge_qe(k_4&6ppfL#YLG zw22|u>%tTS;*HvZ|wXx-NFVVYm57we-4fmz3B?t+P9H zz=~r~u_$B=RuvW>izJ-VIesf@OsS?m)Q!`v`7igH$O<@)#W1u}j8(j+IHAaora+{T zqOW3>;xok!MdeyXvV-D9#cIVF#T{^bcVM+wBr4uk>{s}~@j#@SqO)SM;v>a*MTt5_ zGD0y}u|RQH;i_vy?o)JEysFrwxTFZdu>q=mR54t!L~&G+8w(6X>MCLt(-qqlR~2`` zNFdo(F-EaM@r@!M)@_J1RP<52rP!sop{T4Ig@ua2*kd4HilWs(Gu#D-n8==^4TA7% zWe`cllQ$rLuNrt38!RC2YXC!v=dkH%K^YP~>Zaif0UVePw{j4NbN8GajSdx{w(lr$((#-QTe2D|Pth^t~S4qG2&sC>V{ zo;n5z;RZz-8dQA9VAsP2aV-tTwKb@WNhZw2-6phDG5l*2TB10r=y2Rb z4pAg4K2cm&e0su&{HnO;TN8R$k*4s&P7v<)5MDz;?Y}9?>vH>uq5{rRkk(EyR*~a7 z6Ior+MNtde97skhrYZ{PYF$GSsTieLq!@GAHG*8mySB_*60P z7n62Ck>i>PjZ`dCJb%+fu2g)hi2B1sj#9j<*sHj%*suFRKdj|wOEtw(#aD{C{w8gQ z;*z4cZbN=@nY6NcBmS6TkK(4{U>+l4;j|bv)KH`<_A0I_%IIdMx#CWosUbsa#R$dk ziYf(6+9hn^AW}qkKaCWziY9s=-%pXOC|$&4ctlYSM~BGXMlnk9hoX$`p&n55QM|5* z3o-d-D|Rbd-f1F-DjMnDD@O6MVzpulo>WooM#Ybc-W5#bOhtSZ6Plygt7xTf5%f_^ zReYp4t=JG|@?B7r()SH!D0V7d#@-vXzppr^$f>)+<26lMUOfCmq=90c;(Nu%^-S7D zMH%eTAo-T!BgMChp!z25K1Hy;=1^bJOL0z7tdWsC*4V(mi9uDx6N<2ACbE;_B}MKB zOk`a}z7{6bP|-(mUJ=yNq}5P7r5LMtx|K)gp}X$q*4R>O^J$H<$Ju3l9H&ncy|DXa#!}cdNW11-u^&Tjw9<2iDb4J%ZU(4S z^w+jj@Ee_c*cVOz8D12CJ_doVLv9iW-b9YcT(A zg9FtKuGBIptG>DEgC^9kwZSXx3}mQh?^F|f5Dt^QnfjSp(td0ksZx>T=Y9~QAUeviXP(J06 zb6=!0TmI2JBlA}NBA4dJHLS<{hjMB9`(DbQkXzHe>2DL$z3B&k&%=DY>E|rdy|q6d z&iUo@8}#I<|GD#P`qN(8-?M0`X)?^;Ila~QMbPh@&k70Z@Bm+425?x}yn zLo_3&Nw)lBZ;?KM>BCTrr}ABQYWWiYPxhO{^aWnhYnRphs{l{>`;qCK#@X6`jp^R{ zca!Pf>@T34){nzykK$z0bcJO!wBmzzUlGPQX+9sxZB+m-LZL z57A<>^*@>E-o|$?(;Fbar~U`utpyX=%CE(QbT_Kf?*F%Bx>Vz-fALHo=0(33Dr#BY z#y{{LP4_nbMVRi*{>t7Wy$aLC{ynw7In(h5l6UsF(7mF};$h z+%H@G8=3x~mvon8#HWTLTmITi_h!EjGCc(OJ?STg>1|N5r}b-fWv$qoehxC-+xVVf zdUq7#$^SlBMaysKrF}0jJw(N__5U5Fdz(LLO!qc_3UT4`Hh;pI?rr|GVY;{ZGl=PZ zz3BIBsCLYoe*MEVJ&%|E7ht+K`>Vus8D>x8-XM z?e}Is6__3ZF;DjMAk)3Af79z}`QG%ilIh;`vx({6{Es7C%lGDg8ZrHGhVGiqzU3p+$WwYVroRKr^R&M{CmqAbn|@r znC{JfW-{HI{p@DCH~Trt^bqvHlYVY6JqY^ow0{a{EWP)xpYlxirk@&24>6^n30XdE znC{L0jApvHDNpvXn(1Y{lz)Wj-u%x6rhD^0g_>x=FZ+46pLtC+-JAVvWV$!~>}I+* z`#H^YZ}yX~nbz;kex6{uH~SgSbZ_=Ejp-q%#*_Vgz;ti+vq?4<_;}OLF{XRd&v~YM z^FNiOAtOHC{7);U$H9I)&9C*%HNQ9g ze8F^Y`Z>#VZ}#JOSj+cjKb4s7O}{-e+`0cz!sYBO+Q7M-qB0_iA;amOZtAMd-Fd5Ewz4c{-+|-+juE|2-9VK^rWBNOrPvU zKOI|X{oeF5i0R(+^8(Yo&5xZ-_hw%wnC{KKf*#fOd9$wwrb~W&ve{Q6(}TUFk7jy^ z$?TUc|6Hbf^G{1#Yr)?1x0C7K^jAo;JN$;Uarh0&=a(-iXFw8KQ6BLn@$bmAbAQN( z+gSWENN~Ovax~53YBI)>tRg2a^epAL+<27h1-TrrYk7hA*?iK=V^GSQihn0rp0vSy z(&boh6-2JXzx4LW{fYUc%e5Ngn&h19|FUVN!y)qL@o(>Rt^YNZcDM7P?D8d{hgxr_ zyxc#TPkQ-}jLA94^^#qKl;09EmEKhO+i8!S>6M+S@^U|wsr=U2%TIxPso5$o_f@{+ zMUO`zGdEe~eT^UPh8-&?=WAT5KyE7Ke2ojxMq z#e9{Qd#_CLS;j^5a1!!^-cfnE2g@Yia*P>6k;Ci6j-TFDIk^w>CWpIgN6|$pC--9B z8_L-? zv+4Cd?AA+p^f7dqwy!1IleHhl{vp?fa{IH&wa7fbr2b)$ze4$bS>-eM7yNNWM}t(Y zf3Od^U64znT>q?c4~_AkjQ&c!_>D2gG0Kg}D))ffua$J-)#l||Z-K0G3`==<|G-h6 za#g*^iGF%Pt`g;rW|i}xpP7(Pqr5AtJi}7|7Rar?G>u81zF`i%*$brPo?~-tnwMgYaZkpzNh8p$|}dO=wTP+LMVqH z^^F#<>dL!eA3IyV4uw(cb0P5<{Ps~y}clJlybh>Hx+Up z-bVY@L2f4HxW90(XBp}}3Axdf<37QoTu=ahJ%V!FFL;!z3Av7x%jT~#%%6^s+fBJR zw#W7x9AB}sv5>oi<0kir=98}HEOse+TnYJ$ly6CKyW9-paujlfR;u0j(ht5l&+#kE zyVFN`RUmhTa&3LcwS`;=>kY{&$FTGR--zTWN;zNlH7`SXJnnIi3;x_ux?jVuoH=T- zyt{qWdnJP$&lTL|WoTbXOpfv_uR_-HGVH_TYpu&tPWCkB<7501A>ZeH9T#8rh;OuT zbfugxd)xxKhbV_1GuO|c==(epE8T`1erwJVM7eD9IfH$LL(W0DysXEz!wmJ}YwjFp zsUKhcodmg~l=Ib(m5^IcIX>5T9KWNGTS~b~S=*PPAO1n`!<2i_hg=oN?WP>hV?5T| z7IH@@=WE^#gIsz)LVVOa4{{%{JUJ&epLF}muus_qx#JuUUwXa*xr3DRW>-~ENl7Gr zNV)E;)*jz1>z~+HOUPfKJdY*a`pKa0M98^5Q2P(bS}wy<-b~2dWO=^)!*5`FI$=Nsw#3>ehZ?CFGh>4qeJz z9)nWvQOH%IoUeJ}kI7q{a=zwC708vOoUeJ(7IJkd=WCt}gIsz)&{X}T>xDt-$2`cT z_alVywjE}$t6h*Q%X;NL&V16#%P>!_KrVFkt@T_oAIhVgFFiMdTma>=*zZ5Zc`W2EP|la0Qy_Pca=z^OAmp}C&X+ykfZR69`LgHoc=$O< zIbZhN5_0MN@MX`5kW24J2-WAwo@YXC7wh$9&s!jO4!EtKFN!NFV^{^M@k~Z90&r=~c zmU6!Iybf~DP%ebk+U;Xl{Pao4b)}pyKOI!eU0$uMb{qSYiS0I<(j}W%owwny| zsU#jEC$nB(cHIne@gLt>&%GcQLpfi1o(j2^l=J1U*Fml;<$U?;laL!ixu#kBo58Mw zaM&@8a@qWA2DzG$n@2fc{<cC<3Z1bN@IPv4LyfLZWHBv>A5@P7ErFEkM>Q1+)>Is?L%%Qlu8og+t3a*^<+AO2GT3ul$n~L|y!T)}9`rm6atF8G+Mee@ zZU^Oj>3J9AmQv2wJih|Dos{!s_a#Gc{zW-ocHazg>nPVid+S~gGw7ukE1H7PjuV9eS0N@ zJ>INELf9iw-5z~BvU;`9>NP_Xx<4D%KOsIWwokWS{kunpbxs@{7oFhvN6PAvkPsCY z>j(`EONj3l*1u2eAo&^p^@-|pTQy{CShvcR!v<8pt!%gKWbD28<0}717ZV02*eYw6 z5FMWo_H0zFU2@Z?Zat$D!us^>9$mG^;JC2rHA1V`3cc4>wj|tEJ46w^V!MWQ>lM|f zM;Jy9W0zjaZ541UmHZ=xgh3mQu)n5;u>J%7u{MNtj!WzrA05^GpDD37Mlqui!-BH} z)wbn#fZA0N5gp$rsu$AXOa|0e zCM0(69vy?9ag}G9P^)Ho6HKsrtxUn%=^?4Ab7Fi{Y+{0`8l^KQYBM=A)Gm!-*N~c! z7$4iGhve!V-MeqRX?kp**u>bVUa>=><2(0?O-PhfmFqkpHhQ3`qO&_=Y~O^Kf!$3k zIuP3z?GMb*e_U7fAE5m+D(mUMMNPVm*jj?ewc~pCPmCU9`j#;^ejtYC*=*4=L?R}3 z(mAege4>#+&rC%6AYj2!ql|+iMh-LqgVq^dIsqMw?vvQLdJQN>k}!;t)H`Z$*XYhQ z@68Ykf1&-bZD3&Ec>Ih=oV~~N@6#ps+KBW@wDj~)XV@ZQaQ1D-bi*>!R}2u1kdnH=h`UC0dp03c zpSr1WY0dgG`Z%aF#<@oyqca$t2*J~dkp6^HWh`}GAb_)FI{`vsOKOEsxMW7y)Bw_0 zjg3h>i^5M*EoYW7&J1Cck#3LrljgF2)`saM!Ox~jqhqN%-SWDL@-<^O^RsEvK-8RW z8{G!Fr^aDP)pV%cB*&Rgv6*s%t3@j69c>TjMCAL?ah{$sPwEz z#gFKK8Lz&521LihAIQLp_30D~H|jJyugp@JjS>SM+Z!g;8%7)@_LphYB`3<$f;)G1 z+i2&mQ3=Kj9r$)^e2)n~R$f16xxgf6uG!9ft_WwYa95Z!UwfzDSpOo!jFGMcTLTjfj*)XHJ*((G)B5s1!h zoj%~W>>uC^vgR!v5sp+;?6QvUb40kTtBXgZNs`N2lp_rZf!3LQju@2N$U2cSVh3W1 zTKgc091&<>n9Ev=Qk@lD*0=l7@<3NOa@RnAmW@DZ=bnr3_jlguvd#u1I`6V-NW=46 ze+)=LY%c5hT#?TFC?+@&IzoYANG)UiHXzbe_qii`ZO+=Rh-?+28P?gQ=-Ok>BG#_q z5zY`-sCH@89>-{;rH%;qFXt@jvI@jVyftHwBhqCZNF9;lyvt=xhsGt@`ZaX~{!*kf z%sS|wh?dl~J{TJAvbv`@>$$AbiT-V%i(`JH{qJ_Rw$9|5WhB-l&hjsS66Xewb{4nh zKNld$1+15H1cV^nX{E$RAR@oDC^#U*d55tDXRxc9E8Lma6*dxC@32-4i-9UOI}@E{ ztw}>eO*NYbB$~7f0g;~4T-L?sB2m7d%c_3aWj%Tsc7fpyi9{xcHPIE2=3mg+B+yC? z3<&kV!+D=|GcE;5!PbjGqhV_i)~xtYG{ZWTCtQNgnl5YWbD_?1t{CTiF6*8M$2P|&EfYHu}t-fiH za9ZE^M>_LbD{?0JS3tv7$0uRfOTa#@92NaAH9kaj%aD}EnmY{R)J<%qh|3xS^;fWF z51Zw(I_-e^(9JjUL_jXL^>ciR^HEotvsRkMPt22ufon7xD*nMQ#e;_ZofWL@17cv$ zk*Lr*4Fy=uUDo720i(s{FI%Vz4P7xT0A1*K5=wQrtb4@(F^@j}kI$nS19cvK2Q$e& zk6s_B^Qiv+?KBFv_RBPCp5mjb89FjdpMvP5!s0(GCaZ(drTI zi6s8D66TSygGxE>`bXTU%SwYkgim!@Qw};p;n^3Dm?gf>W&PwxM8e;9tt)5}`?HyZ zc<_TTiLAAFbg6D1?%&qwXN?|?+0k>fRa6>@#p?5bfE~`N*1$BlzSM2-vEi6FWn9(= z%SY%^ao7K?%@wu28;W%=;02epWCT2KX{>#YL}%S6oYe<7>mD>dcA=lRX16Q9NE`e< z4_$d8I`?Ic57n>7po4X-i-{>xqGT)pC!9x?38(cft@Ecm|D=%dj|n zi&Z`smfiPvI|4$?IylQ-DZ*gjLtx{ z2>DqTSDCFxkd?H<@gcJ3vd(-kBGKeO??`i5zaT#r=n2Sw&l3D3`C(|MbEajsGiPpW zQJgWb&w|#blo8?1dt74DXzhjrjtJSfSTmN42sL|}a>&0Qky6_$i?PwMI)$RY?%hZV zl7g&B17+RGWnIIPkjaa>tZ&RZjP>u^+?cIzC5pR6Rg0jZFm&p7tQx5NF6$B$9O0TJ zI}O_Jt_DbNpo`1$f`hs(M!Jk5H=Pj{nDI`+Br)PbT(ROZ03Z+y~~%~ z{g*jr=_;U0LW+AyXk@MGpCYS)l@=5rYlPEUL<3661I7PiTYg_2-&a}&!&~mBtHGJi z+^Ydr0hd)dQdfboRzQ+_5s0|0Mc~`vm~w4m#F4wKxBak9uvdZzXUQeESP4cO-+V27 zCHT@b%w7s2d@lvao8M*4SUw^Y!#NsVzjwz4^MR7Z-T}>-sQzRCK*?0d&f)%A*W~^mxBIdd*oAMRWsD8&ZJw_q<_k)c5|>l z__wWU4=Z{hyBBmxDyfX%?XAU+oL7BMY?C0G~o0?41Hq%3IrT`xD?@$ zpP1FY_CfzfT86#V*c|X8H=aww<26>Nqc||f0e_(Nyp;qykQ06!&)(n({~S4Qu7XFC zZ*bo1wCX#Z{qQUvj0XUd=W32bcbVT$be4#4 z<`2L@xXUUWiZkFC>&F2R`lua&E01$dIS22O;>;cJIV{j&&Gkpq^8`+TQsjOGQ=l3a z({MDsCJ0j<9OLwx;0*5T%+mr}L3zMOf7AT1_*4lr4l2yL)c>;S-OGWAI3P+yQT?4E z)|y1@Vbc#num{E&h8%-HW#y!IUky)@VY0SZqoE;8kc`(e(8%@Wc>K(1CGB>ETWxU2 zZiR`4?yzQW7?J3#XYK00!&%5$87K#5%Mw%2wf(sxaRQA~`+hqx7D?z`errQ;8lD`| zq+{;O0%!i{?2*Wt)7scC#_2fuH*%ZZGxRem?@2igdN(mmY(NJ3XztOXxS!+9Y5C;5 zcyg-a%vt>jXHY|!w44T3c3Jxq<*G_HtLax&=(5vVzX9eQJO&MXGw~#PdWJn6+iwFzwyo{B70Vge!fCBF+C3c?D(QjN-rx^2lr8zKRMVbZ)}G)PF%v5dS)qk* z5&}+UumpL!SROQ59*V5B@rhXu#{B)UVQv)abe?vWLd#3KtYkRm;_aPbmVpg)00g~Xi3qY54TUxJ@vrC%#uHP2DW|5jBrnuC zxo-qw@#wzQ&rA^O7@VQsBTh$Sr!%mH|C1;zb%0FQJh=M|3`ol2Z(a8}3$%cf8;GmA zt?~HZ`aBWNf-PLu$MG^Zu}>)yiDzz^n{Xz}aJ!T3Kt$*9lVa1ya$q9QeNLn?3#MWg z_+beh5pWV`y*C_k$5-9M6`v_UvQG;}_H+F{l+1gOxlCZdS{PS2CU}fgzdty}RDY)| z6V@G}STx{g!u^BA0+$yGZGn34vsOQgdwV3n;Pc~PVG4eTz^1eZyau}Fde)g|tt==e zN*14BtYLYrSS($i7|~$Y6s|ew{uCoxKytTeu@;@{mn65Dmx2Re)-S{3qp5G?!P@v| zSF-K?u=v{WZ@KZedj{gC9{6brHU$prrM_}n5gLeHY>e3@95HuJm93LGVq{~H!AjxXlyp!-? z*@>`hIU2FPj*r0`4n{|KYa$Rk9P608P%tks6zMSf(mOE23R#EB?7-gW>d+m|4pwz+ zh^$Yrum<5)Uapz*ThpSY6^*Qv+%h3^TC)qMN%~gFZVaQm9 zt_NeYnSJ8NO(0d$xe{Fjq{y!d4Uabw6!A&=7VPme`jHrwZ$nt$Zu^PGTK=TU91di#){_ZfmJrbSu0WxfiGc4 zmgOe!u29(;$Xh5)T~;~SBHUxm$F`;%9v;l?;el+ohmf&c*3MNUus@$Qm^XY_)y)kb z3aVzU9Vp9sVN6)_7Lk=YOb%vqSqtS|qK}8q(l(!lN5VTslB&=1=BjW5?sF|?9USqa z>yOKh9~+uQRzLw5hSRzjz`fSZO^y^^g&G$yH|Q@|wrto>C17X+1L|WJfPEW|p7AP5 zmJOe=`gMhIql2wy4?O>T*)cT3+>9}E6YIgjoLFhBC4&+%NsSqQ+V|xD+6#wUU(gG0 z%HoB?t*_~YcmLa7c*m{1uKfi z_2i42Sj*{)r)2fT+v$rJ|C_!z;?}-6C8IBn`P04__BsozxvcEsuP)Oyo-Lc*HD*rx z+pcjTUE}&c?Hbc_Zq48tKcH(&Z@BFmm(ev!!e4idCo{Un1#pdYGwDtU%4>ohX@oNZ z&hc?N$HUp2qj*MhmZ3hWsWlR>Oo)Sg@irYKUN-RTAP>_)zU$dRiud&H_00PT++EKN z`Wr^%d%u_Qy%jMpd+RvRjEsBhm~zXlW2T}qZ{bYA+*Y2{O~3^6q~hLI{!EAVZtfiS z_@(bFb;tQDla^}Iv$|Wn=6SbhcDLzo;z*A&>^t?2EWJ;^=aTmNgV zS><8lM`z!TAKgVidKHc))1LMO{bp6MbzQ+mT~&-5KVlO+6g&orxRhKJt^{`&Cy298p_Km5+f=9iqA9)7RmI!`ut zdv4Pyd42kwGDx3(fAIh7PruFZ@caAlfA#6tUIYK1*akMT*3s=956n>s+rZb%@uF-4 z8(AMS>5L{l{h!Ih)`- ztBNbZZ1fJ7&VFnO$>P@fIP6UEt3F{63$iX1le5G|)~2{fZuL&Khgbfx z=R7Jod73!e-1qod=?%9X>h%74nkWf>-JyP#(V=dDL-lqt*Ust_?yQ4H6mwcvKu!(| zTYV#(O|2nvW_gd5e4GB$>!xla{pb4Z{u7lIv!22A++p)dgLy`lqc%?mgZ2~h-+DZd zN7w(+1xh39bNaE(fw)p~-=8$Hj+q39wI>ia?B>bzKX89?J;B`0SljUXgK~9(M^pRi zEbJ6Tg2_qZNU?Tjn>GLtJh=*<;#pcrMprb~rz^^x!4>saSA^}q?TW_yU03uK zUC|uRuINR)E%Lu{ME{TM(SD%=n=kJeWZI(Lpa)xyo9T29=J8Hf67AoY`|q97={pg( zyDh`h?O{KCx}ABer(15qaKV?DXdTiE3>R*b!{vpB0@meT|DosFzqO>w=JI8n@ydzY zryhJ?=Cr@%`(*odCJuMPw|$u_IW9;JZo3Z9*QGbq_I11H>m=c?`?^uxGCaplbo)B{ zrUF;K){IiJU_@Bs@SFAW-df$Px479ZDoW`+#d$pP-p)m?*R9wU`o9U;{hwUq{+WA< zzhN?e!ue%Bi_h#!e5GNE{Y&>7ncSJLCS*yI24%k&kvG1s2Ftf8w6@L#`H? z_dJ9sKWoVlSnfE))(o_MGB1rawa!rNmvk|QwPuL?@+9szZtJEbOT%uvL#9Rcn?3*B z4a@D1YUY;z<(rv5;q&$3d{%~s^XxI0%T@65G}ndSOWoqs^Z(!L0&LY`edI5{tX4nJ zn$%BB+hHBbmE(Rt`sKy^7_k#G&`>II-2Qx}x> z6$FPOyxc-$>adC1KENMC(D6L z(XN6ZzW=Y(jTRcd2uk<_DD{5^N_`v1RB{ga3ON##d~po7B_AMbk>x>=%MUIBe~!R+ z_=4v^(a*P_*w5$WMo{#%1{6C=1;vhD2gN>K2E~rXf?`MgL9wG~Q0(Y&P~=*HVnH=1ks zM^N&81I`Awf^UHzg1OMY_d(IeOi=3Y4~o46f|Bpohtyuqf?_WRL8*5;_y8CMO1_6d zX-7S>3R#G}hA&8$^shm&>)qsfFemDn!|+scEaQiOQeQME`JW`4leIv}UxDF3^4bF$ ze+qmR>7Rg8!1bW?cNHk(KMR!hzYfZ{PX=Y&`-3u`y+IlGuAq$jTs$b_ z8N+Z(@KJL#4wUgZLcR_5Mtgga(V+CZ4JiF?28w)brdMRR z1jBj2e#n0bUz6AuJPpctegjJXw}DdsOi;%2E>P+#2FiHm1Z6ybuCL?yEhzP;fe(Q* z!KPq)P|9ftO1r9)WywJDLb#@X49fVfBA zdYXQm+zm?nS}+=%4R!;kg3|v9pv>ofptS!PP{uzBl<|K6lyMCuD}Z7LB|x!*AW-b! zT3xk+)1b(I1Bx9SVt6Mg^?U@1y)0(@To8YIsOn^LG~*LNv6G$*w+E$tO+e{?O;ERx1ZBK`!yk~4@KI3GcQX7j*azWMhUbDZzS9^U2TD8QKIWqjL%qL)UX z)L#q~Kd|Utt!El2<2x3V@r?te-frN-U>GR<`W}CvMDia1r9E5856D^MX!2=L#=A9H z8??}_!VCwH7prUhX;A9j2TJ*y$(7_>Q1ZXRFusc2$aQD@V<1eX)O{dSS?V58`dtVh^Jj?#lGm3_k>l z-fA&i5fpnU$#5P}^m#Q*`*9YO@l7M=fECe?XUJ}#=%+O(`e_1+d@ZI|V7M5=xxp&P z|6?fr#v=GFDE4p+6uoQ(rT$r<*h3g7^_2j{9&&+V4?kDcde4HbAh!pUeoX`=eaJ`PI%cY%_BJ(T2T<1%n0IE(4i zKn0Hxhuf~Fmy)VG=8RiKpr z7AW)MX)+R&b~I)BH8>?1*K?rA?**kj>p&Sl`CC9TK4U;Be;_FJbz^!vFc9HiOX2Tz zBL8=wgvT@dEGXqY1>$eRRE+?|Zt8#?z|x?U9|%ghIY80>uO&77Gbr_b$M7al?4biF z^QJW@^X6f)30aTn)fuitmLv0n(ykjN@JAoOZ$PR40Qe&KKG+|e4<>?df-(-TfFd^@ zly(hc_z6(-)g1H#>yp(#X=epc+F6DyO6F&JPKF)i_2Mdj8I=5I8UBX+f;<2|h4dZZ z4fwZdpvX^R`t#&)vNzZf>Fq$VgF2v$dks+9Uy2MMe=4T&$H-5}mE>%)5BLl0tQ#o( z+)z}{w^oBP-b+F8o72hX$#}8@D0*!N%KT^rihVR?{Cyz)c3IUxP|9U68|yy3(ENb6uoo+b7I|i9F%rG42oXvB};&!hdV&gLtaqy;LrH0g|uIv zf|CDZP}=(*DD8b4l>QB1d=%p!WBi?<^dl!I{rDb>sDw{~(%wDfEKu70Dk$x454zCq zHlWno9F%rf1*N?eL22)uptSc6#s`2h4qp|}dTTqi3^~t6W@ZJ!9$?Pe+J6BuojejZ-G+&%U~C9 z6ex0oL7Cq@K#_YG>z8{qF zlE1w!@ufi-ub+ao{^OwN^AITd+zBRt8$i+1Dp2$}7nJ-XKpEd>KpEc-pp0)NQ1lT5 zihs%hN_&6Hqr5`?0E!;>fFi#G6#czNjs`_v13}4O3-pIwhJm85yFk&G3zYWwfzr=k zgS4MNf)f7?DE)jNlzfXpY4K^{Q0%ZODD5Z;N;`r;X-8V1j>D&*jKfAy?0N+# z)35tGFK+)stpp=^c%6N1F zWjtDeG9INsv5RAHieeXAKw=>9Fi`Se@YCnHGoaM-6)1XN4@$e%fTH&mpy>Tw#=ilI-k}SV zuNx?OZv~3p8-Sws{GjN4KO#l%t3hekOiqGut&<|m3 zn;k7dxF<(l_?xoe7CchG%{n%NNtn;?gX6*BevaUg;6{W8F&qb0LVQo~B;vb(BM^=R zKSsDUxB+Yqt_K@|AAz;Obzn7cEm#r!5DWp=fJH&{EjS5Y3MhVOF_;W~115oQf#Qcuf58O^4`MhD zH2npSBfbl0`U@^ZxHb4L*c^NZYy{2+YlHK^YT(;oMQ|<{0?q-8g2`Y$@N3Wkn*PEM z9YgpcX!;AzLijj{F%Lchz6tIH-vD=j)4`44>)>i|8kh>c1}*@ng2~`lU=sKOI36_p z1*af9h~YTU^cOse_%5L7FZc?=t-&O)IruWz2!ss=*9Kn#tAUfiir_>r1e^dC1z!a7 zfnS0S(DWDn@e716f~LRVIE0Ub&x1$6G2mWsG`IsC1#SdKf~&z1U@ABqTmU`?CWD`Y zNnl@ayrjc^MuI~S9>j1QX!;8tL3|g`^cNh8aBFZd*c==LHUbBNwZQ>kHLyQe5ljR_ zzyz=;7!T$H4}%WS^cVg*4dIKR=`R?E@NuvYcm(VP?ggI(cYx1;8^Ks`HP{nO1$%%C zz!)$YJOn0zk>GgH^cU=g@F0fcK+|9FAmY1#roUi!gj<7M!RBBT*a++b)&@I+)xb_* zMeu1b1ndYF1)l=*fd@bbX!;8$3Evfb5j6b;+ar7&d=fkYwgYATY763bN*s@a8^Jc< zYVa{I6>JSI03QXD!F^y7*ccoSn*M?<5gx>F9BBFr?nQhT(DWC41mV_T3$QsD0X703 z25W=O!D`?`U`6mjFa&%6EDAOQ^MQLn2Wa~1kH6WB@I}z{7i@y?aj+411Z)8A1?z)5 zz;JLQSPxtc)&*0+I^Y7ZHkb^41}1@(!118zFL)oqgBXsJbl7=Ma2MjcfTq7-EreTx zHNoZ})`Z|jU=6S~SRJeeRs$=7VPFUt3Kj*cg89HtK?i91YvFGgBYY7w{RJx{EbI6^ z;1Td{a4%Q^+yUMN%DP@2Tn&~3Q^B&}0`N{S8TLCMz~EQ9n$U@5RRSQ4xTmH;b)#laA;7+4f63g!cgfC1ngpaa|vUd#bM zgL2P;_k+hlsrLw20^AE01b2YN!Hr-^a5Y#8Oa-fe$)MaAO27=YVtzZaP2jvz8rTl#0JzxM> z3v__ej*EV<7w{}7a>v2E;1Mt%xECx6?f?sc8^OZhY7l#u;8d^xxB$EZOa_a9)4|H% zc+d%s1pUE5pbLxx$AUdU3+w_0fRSJ>ur+u$*odqRRzn#7OuH+BH4qK~rQJnAsV5(J z75zt9rXB})9pP&Zt>+^6E5c{N-@xPGUC0OD;kbz~Y|QaHxDosVTn(a(;8dUjm`qLw z!w^maMUNvHKL`v(IF9i>!RiQi0i~Uhpw!bElzN(jKY@+FD`0J~Jme~ZA{PRRTv6~x zFdujk3;@eP?(=<4>7r{Nxt4s7oJme4A0iu)=k{v;6XbSs1Nja)i+rAZj(n7Sh%8GM zCj-eG zuYIQFeoY=G-yvs_gUNnm6xp7vO;#iGkWTXOF0E$|xrm%gzCunQ6Ukm=d-5^zKC&uV zkjzace5&<5OMbjl!)wUb$(PB#WDl|p89~-0tB{4sJmgh8z>2+IAP}3?(a& zPV)CPtd~4UE+gM1Um~9;pCP-F50MSY@?=T!4?I9g|9&CABoC0OvIyx%UQgBf4v?Rc3&}a;2y!6VnS7FLNZwC| zkVVNHpMe!O@2atOfDklk`u`>WG}KiS&ghn9!Sx8J|!2Db4dJk0^=|6 zrwWtW8!Ui<1S&^NX~;ljJ7yLvlKq zL=Gb3$Vjp^S%<7nmLLm~KP=SxPLZ3*wd5P*6ml@xk8DpqM%E>3kR{1N8{|EKS})UYV=u=gEWQE^;NALcT`6L=GhTk`I%O$ueXS z^5;2P-w)&=@-y;%atS$&oJan`391uWwZN#$uEzOAI{#n_ntdDyEAuZ zb{0?KR$PlSaS{%|7&KxlbilHh3ICfe{hh~CxDD6gES!u3u_yXtYuxptk&!g+=l9Wa;M$?!wKu1n1&l?2m!i7TwSli(vu$OI<*q%_n}xZMY5xU<|fH zKXk>)m={05I}@e-t2h^@<3Q|*?XfwonIQF-VtRZwULHS-CvY_`!O1updto@XMqjLk z4p<2D;DvG0@6R|IhhPMD!Di@gs}J`Tgru{}1&s#pm#qXEx+CH)=8Rk#?(;c#q#ZrEtJ)c3$j_zC95EO>92EPoAu z!b7+gm*IFEfnnGQtDyrv7%J`G#9#0jZpPI(11DmCjK&Vw0;{7V=EBSgj}MXl%V9pu zh7SglAI9M{^uU@}96!WoUrPP^cm|K-dR&21aV+-19@qjKqZ5|LzXwTw*YOnoh#PSg zPR9wT{V<#MejJ7Eu{qYlDwq$opX$@Y7=zu>8|z^~%!%=zOZ&gzLY$4=(S*&=8>^uM+M^w2Mgv|PDE*zq?{Ndp z#7Wo}Be5DfU;)g5lLkopqcBT9iPPY3eI-7POK~24fqk$QHo>Y`2@7IQeAGwUzk_G- z1TMq*I0*Yj6 zVsC7TKInoKu>j`4T|K4U%{UFmVHkEoAFPiRu{7qyOn5g&+W!lKu|3vAXSBmy_;<9_ zzm7+6AAXD9U@Z2=R@ej!Vov-iQrbU+D{&Eig@e$Dt*|;e;s=-x&-IY@PvRO}iW6}p zHbi%f4ww3&=#BNz9_`S8kHVy0JpO_^aTCtN85o1zu_3x+ar_X|;N$Mn-|u(^cj0E7 zk27%?evTm+fZkXS%VSB*hUxLIQ1ZZixE;si2&{|Mups8do86?nOZX%1#pSpF+h9|y zgr8sr{I@IZ;(6SQ+i)Sy#^D%?*FvP7i&!6PV;Qu^ESLt@c9HtauoX7JD)=cDz#RCX zv(&$dhj9;ngI{Ae48q#zf~Bz-X2j>6SYLP^SK=ZZgnh9q2BHVn#1dEt)$bka#~qJM z;syK}zr}BG0LEY~tb&CxFFp#EcJJU%cnDYFVhqH#SQ}li2Ql61vbX2SPAVg7d{S<_V40ZJb|-u3N}Vhtc+za4`#)`{iXfucoGleI$VxJZ~%6| z7FZn}u^{Hedq(N+8Xm!YxD@B%F#H??u`O1`N|*<;;`NTw-ygUKx8hJ7i1j+i^40Mp zEQrtAOZj~~jYn|}F2!*;978b}Kf^j$1oPoP?WDikxF2`m*Ek*{unYQP1I&yD%+^NQ zPmi}-OMC^7;{jZaOK>8NMD>H#`s+Iso1zz1#M1bH*6524SQc|& zM!eos`uhX-;dY#h)3FzZV>9%|Pq7rH#V5Yf&r$pVr{Os4h%K=c7RCRXNIU=FIXsD* z@H?D}W3dr>U|B4Vi+rU0IhebV#98o4Ly3RGHMkT<;1_7bR#*qC;zw8z4fx1g`niZ_ zaW8JeMK}kCV=RVX0D5CR%z^4RG4=PE@4UosaTtD%9k2z~!YWu4^JCWr(q16e!|GTJ z3*h6=Wcj;z5)b1_T!h0h76Y&imc+vNo2RsY8n@sYoPuMp8wO#0tc?XRCtmfC_T%w; z+<&%!cXlMqR1@C;o_gaV0Lo3HTL8V<@)3#^{0-u^{He z`)<++IuSug3sv zgLSYf+M^x*S5xZ$gFoXDT#EBB2D@Vebi>M626JI%yj?^3yMmkWI~;|BF&abB2kT=6 z{1~%hTD)3a`isXkxDSsF zRVD6%^|3Y7CGjJjfz!>a^EwK((MSHZve=A7)5AZCWzy&x91F#KxU`;HI#V`~8S6=$L zit%^=cj7{vjr}n?;qh|P&J>Kr-WY&wFdL@FRb{3AVjPV_Fc{loU95)1umJv7M%w!a zf5$Vp4cFleoQUnv4{Ko+v`0Hki%&k0e*eHJ3}^m_q+#)&u*Bd`nJDk1eQV{3bfeX$~z#wQ<1`8_;_`*9)8 z#-TV6J7Gus4C`Q7ERIi$Nq>LiaXf&Fa1IW`&#^Nau>rbaIV^$MF$3N%D*a!EF6LZ(1aZ@H)g>rg{A%9a2u|}SvVO7U<`J|mgt7A zxTcV_zZ6H}m)IGNSP!dXLClHwK9u&Z;Q`!`J6ZjPl zLVs+HE?5x@U=DnkOWM1Ib8$NM#t8Jm`dAT5V-C!Sw{uGSSMWF|X2 zU^Dc_f3wT-4=@g=;Xv$(EwC|`!xDHuo3wWWf57i?B`(78I08FiNA$p&SON>-2bd18 zeIWf`!~?h!C*nx#gdNcb>th+T$Bg(qtMv0Hp2JxE&Ya92}0Z*cyGYGM2&Ym;tY)mwqqeUfhP?;MX`1dtzH` zhE?!W%!+C8Qab7HJZ{JJI2FfY8*GaC(@Op9crT5_*YGI*fJ<;L4#j~Ogzc~ns$a^| zKd&u>dGNMD9>0PIaTm_Oi5QB(=#Dk8Bo@YB|4Xm;`xE~5uf(Tu7jDM+I1`890PKVv z@iVN0A7c?rgO8s{zlU)T4#!yRhC$dEJ+UH|#+;Z5?>v=$uHuil7w6%OgvX!A^4o9` z&cWdri%wV`Pd}FWM{zAK!?8FFLopb=ur8Lv5||CsDs(8>Yv<9!h_|<38Mu-{99c0AsKjdgG^9 z3Nxbt&p(j-qi&5AOtDyrL@X>u~=MtXB!?*|6;8L7{6R{(<#2V;?JJpQ{wd+yT*Hfa828|ET!3S6D28Ka zbi(rZ^DXJ;2rk3(Rk0Egm0 zY=CZ<{<^gH?3x&lzu*>JgX3^GcEcd7iO!fEGvJ?pNk8Xs4{pW&7>x_A$nvwWA4XwQ z^g;(Li@7li-n%UAUBi=j7&qWb{2Iq&UyQ_d=!Z4Y89&6_`0$eSe+zfwChUPB_!-v0 zqL?55{Zra|famcPeu%j-<_}rEJGR0m=!%u`kBhSWuQ(J3VlcMHI#?C$Fc+TvUD`W= z8*vp*!7=@EGpL<+uQcV=S7m0~W-b`1g6%7aqq0SO)E}&pBDX2R6aa z@Duz9vtnAj@vGGT6Mw|LxB?gASR96a*bvj=le5z9B|MKm;P&P#!CaUb?;ewW{=yS@ z5Le4?<-4yWK4?13TZgY~gImc(qB9&i09?O(=& zxC<9!9Ckr}^u~JlDVD;Vmw_hm;Nr`F5HZ>aSHasC~S?s=zf0=HWtBrcyE{VcMVVAL0pYXa3YSx80?O%(HE2e;?1|Df|Y%Mh~osg)k4^*&*#+#bdZ1SK(r8kIm5$%VB0T;MMP?{dnAu zJMdfl21nwT_#)B5!{D!a4JS%7yJzC;3xPI{Fi8zuf3*WxmqgrhJTL$L)m z#;RBevtSzhZ3Fq>I$VyEaWuwYcWjA1=!%uGFy_U7*Gqp7@B;pf-{S_1!)Z7GW3VkY z!%|ojPpy;we#E6X55K@Z7=UfCE>^>vYo)zQxEr_N*Ek;gU=M7AO|d#UViC-T1J_7@ zJ@M>niBI5GT#K`CGB!Xry#Afk{{s);PMnW3aRA0(9juB)F+V=kO$M!8JGp z2ViUTMK^Rsd$hyW-~rr;GjS3Q#{Sq5TVhRg#zL3}AFYu7?%;0Rf>UuUw!$V@ z1wX|+m=$j>m-a8=LEMG?F&bN=FS=kw9KB518-lS*CGL$a(FZGHY0QmT@b4v3|2m$; z!?+HY;}jf&ZLt| zzrsP-8I9%?JyTUn9lg{1RlhdxCp<(LD&g9Vhwb{0+<8u zel7j|h5K+jPQ;Pe9-CtcEQEhellFecBe)OO;c}dblW;Kh$Iq}1evCzM$yDiYE`Bsw z;)3{KlEgQ0CvL*2I2OC32^*s)eu||q2WG@O6Q#ea_!Az&b+{a-;27+M;n*5|u?XhF z?sd4bdITV@d2iUfPR5Uu=LC@MFw`|BaJ+7x64^!*w_X$6z>iMh7g5 zH^)f3m+%1Y#Q8WA`(O`jj*YMs7R867rTts@BkslJxByMq0mqD#`a>}o+hcWf#6p+{ zpL`|t@8Pfb6K=zG7>Cnv5cb6&Y=<6L6H8%HOp8xONFKl8Xk%2)<7;`8Cs z-etUi`*1s^#V5mL`ED45dGP~WIaHQggeL5Oc9;uq4w2w!}&N9W3e}O z#Fn`7bE&@wyAG5%5Z%xf?JyTU9U#m9jpy+cZpZaF2d82z_C^n^iGTN(_OIj5cmy}% zD*PJ9V_%HKcIb!Yu_UI$r~Rbgc>D#o;X0g#<1iXSu_=1tr&tOzqXEzNm3~j*MqGvC zaRhe7K&*ftF;e5%XYHyxB|oyM()NGtR=v7>1p&4pzki zm;)d7l=g4o3S5Y*qosTaPR7yL3&XKB`eHS7z(SY@|A~_JZ{tZkjB{`*wnIOxjV@@9 zc9;eqM@l~z@htAfEf|N>uqTG$_#V>E2n@jhtcay?XM`-j3FqQ;Y>b|GHC&dD$9=dR z=iv+t!%pacWibn;!L4D^{#qP|!!Z)Oq8~QI=iR0LL!67#@pJ5jZLt|v#Y&hDv*CkK zY5yjk#-q3fm*RLFflbj1ov=I>z#RCfoAh@F&){*~jH_`5PQ*y;ie6Y3i(o!{(pCDq zho|uNVnF;2y? zI1qbcC+vu2u{dVL=bfd$Q8*ZL`pe^)@RCvD^Y|Tpi^K49?0_w>7FNNcm>-{al=dHD zJpO{aaSJZMSvV92VrMjB19Zb|m>ySlkp36p5FCK*&<|^%6Bfq2*rmO+=Z|jaibXIV z{?ksDzl|sGATGxRI1~q>5nEw#{1DH#k@ipFCj1U3;V2Bj0QA6`m>;v_<<`>v1>A<~ za28I+7T6dEwv_rku{k!va##YhVp_b`Lh4_{L%184;{qIq!!Z)Oq8~OyXRLtvF+1LC zF8yD_qxb_(#|h|-_0S&e@S&fycME^UBe)({;Js$_kL}P8Yhe|%M>~ApRO&y(-M9ri zVMlbqikJg4;t^kIZyzqgIXD>mV@veG0;v7atahFDmL}pF{2Iq&Hw?o1SQ|@XVSMN# z?cKu7xEc#!4t&&DmcN5%@Hh^}{+J2>Yb5oqVmy9}-(UlDLwmHtOAV!+^EeuZU?=Q| zHP8tQU=Ffgi(o$dr-78;#)G&EXW?Xw#!zgIjW8RgNALR5 zem(pUbK@gVDZhh1;}KkqOK>8N#0czy4bTlsV=+vR&pf2x-|-A?$MrZHr(i7hMt^LL zHP8v|Fc;o)mwvC|9^8uU&<|a)GUmtZc&{Gq;Wk`{<8U~JV`ucndicDqwD%A<<7ym@ zL$E6bq9@kE5?BaB-K70s98+83p%{w6=!XrlIyzz@%!3PSNqe(#2oAs?Y=?RA13Xky z>hH#dI2*sje&~s{&<=CqwHngiMcj`&Z~@N3rs#!PFby88F755Y#TbW!u|FEI71l&& zyj4xwyNownCH@n?#_`zJMar9@D^|u_m>F+Xp?y4zd+=NQ28ZH648S&68(q+VkDR3+ zBeuf2SPhHghnNnZI!XPDcoui!CLDu9u^D=!GgiQSm<=B~NWVvb28*PvT+Rf@^RJj=?DGhIO$T+F>qyQc3!| zhv)GWevcclJDTvNkwJQl({_)7(8{}`^pr8o|UV@-6%ljWuU zVVs9EFbLaWc`S)pF)jXCPTD(%`*1rh#yISUQFySd)Zc~6a6XQ~p%{Q|u=z()zY#iO zIn0Au@qRH`{sx}MQ#c=I;vnpczSscsV|JWSRNDUvqcId+up;KeYj`4`+24P8+ZZ_;zFE_(HM&ESOW`T z9=w%D+P{nkaTm_Q$=DC0&>d@Far_W(=a%-b;96XUlW-Jv!ys&cZde+N;k;bZ{tO&~ z1MoAfgQc)2ro*Q>rJdjKG;YIn=!*?7EQ8eRgpJSxov=LS#w>UiJfql?~9nceNVL{A^+n-B+>v0;6!x-$2&CnZf|10&cpxZr( zT`@amz(aSXd^aw``8WoLVh;?#rs#!ESRRXDKD>5E`n!k~u{56jNy<;)DqM_1aUga_ z6E??2SOcA~1Qx=-Pe^~)@c{0`IXD%E;y~<r^lqfzwtO8z>T;H=ipQviUYAbny@B1V;;Ho;G^6sE(cN2K51@HB40H8>5&VNVRh2Iz*xumIlwQTn-o$8bL`!}&M@ zzrfCD#A@h(IWZGnIxPL2$DOzdXW?Y*i;>tGeX%Z9!*W;xGvf0@((j*m4maa!9FHTg z3;LrQx}rVW;XenZpWAo@_u)dEjYDxDcEA?sj1@2&rpFrx7#HrwEjS$~U?g_MhUktZ zu`oX0FYQ0XpYRYa!MWHA!_fn4VqwgSPk)g1|Hd@?oQC7DA4Xwg^u#Iqr2R1% zhMmwG>tPwR$7g$`{(U@)CvXKW#C{ls&CnYwVrk5P|L&1~&f_UufeUdE_Qf{X6dkZE zKHn|vKE&Vg4DP^u!j4!S9WfLB_r3IU0e{BL zxEjaf2n@jh^u$_N5({G*e7s%yJB2^uT%3-5um`rl##jMA#`O4Xo3wv-tN0gwv{B-M z_+W#?H}Mee#?`n4zsB(xi@mW6`eSu;#9WveFRz#WFW`^37uVu4oPiVZOYDb!*bvKN zar|$c^!E>5#tZl(?!~pZ3}@mb48u<7fi2=>GzN8w=Xj7F@9&X^ZJ z!1(W^pI>k}F2KRqAA_+y*2C&p5({G*e7s8fIf_5vR2+-DSITl*a3RjdAvgg2u{Bo3 zO86n>#s@2;{hRm`9>VYNTO5J|uo-$|SuBnj@ZaUq&pAAaYjGKl!{Hc)ov;ylpgr2* z&1KThCESBsF%G9;FAT>f_!;(ID(yw!#Dx-%#1IU?I#?A;V=>H*8SwrBY3~M}!;`oS z=i?yki>=WY>tIzZjm0oKX21vYrT?3F0e{9H@OzwxGw=)SgRQU$R>abn0soyR{hr5D zxE@#F7#xZr7=X3W1@mKeyf|0-Ig2ZC5e~(H*aU$Y z7~^m#4#aTmjIGfZov{Mu!K`?7lJp;s-{S_Hf@3fYJE0HO$5L1npG}nZ@8d~4jLUHW z4#5HFkFBu^eu~*JJ)W5${T;`JI2#9G40ga4SOcA~2cEXNW3#(v$%#Obgl=jcy9^8skaV&Pij#vw;U~bHU=Lbmpr*I>#!f@=2K3E^W z=r8sA;My38m*H192>r1&euj0hB9_Mdm>vI(mi8auQTzcH;4JKiQ5cAA(F^NhWh{es zmF{#6 z^mhTb;2NBXlQ0Uqp*PmU;`kw^!N+0J&u@4dci={xjZ-ibgV7l)pnrF1w>7$B4J?6$ z@ZV5b{sErE!?+$--~f!lcIby?u{b{JChgzB(|8o;<4o*_QP>KbU_~sA8S!~n>E|Mz z#T~d2XX6x%#I9Het6~Anf%ihBpKEvkcj7nrHFif6`eFktiG}fA7uv@IxD#jLWDLOo z^uU_s%z|m~d|T=N6fVKJ_yzXC4%h;nu>xkp^!Q5~Y5y2* z!8JGrhhhh8fzDU~Got}dwwCq}<4RnFovqk|9v9#& z9EF213cF!D^uzL464T&gU+MQW9>q1d6vyH)48>sd#(L<4<*^9n!$(b|-#hp-9>HZe zAHT$Y*cO|iBbLMbm>vJ|k^XMu2|S34a1IW~STtfQbis<49W&s~#?s##-+^%$i~i___GrNP0_2Zz7>oYshW2Q{`25tzIE+PqbVGYIV0=F6V;sh! zKf0kk8ZbUD^)U`((I4H=9t{|uhx!BXwk8Ws>3ayEZXV?z<1RD%F)C2ofUfSQ@Whz$d$kk8cg-aw}++5;ui-}uEJai#( zONlqEC2l40*44zVCEmG;xQ)a|R}iH(7mXr3jtLH__*Ohpv+J9(q zed4t}CGJG*ulm)>H>!5EzsX@LR{2H*NF1mRM6~jgl$Qusu^R7i@*P!2%7<2v<@2$= z7ZQKzAmu+3SNuZae4onl9o2TFwO^BXs5;)z;%3D8S>L^hXN*?ms((ASr!Hzc(3Zbi zQQC86eftJW?8y2~UrFK-TDht}jrv(x-+3sX;3@5uBhJP8Zcf~Dn3PW^zOVY$`aev( zO6_m8_$=|w7>S<{k5I1@t-PXIFWO)C?kZO6dqH|1%x=R;fHZt-L<*d3AiE#m$M!#z-7ZysnwVi(RCC!%!8gd~=cS-l9^zhw^h;xypAq`IcjS zpP+oTw=92;I4|qFL{({j=I2uGPkcx9rR6uASUVop;@QN@O%m@R{$zxTRsVLaq`i3c zKBz74thQ6_@BStgt2Xa+k$7WCDfgwkUc&mO{wUS1R=*?V`B>jQi3h9q5v@Fqc>fTI zFB5lF-Du@@)uq22tnbpqA<a)Rguzs^?Y9$1Ncy-$}&hK9KUW#BN0-&Y?}P)Zbt=Ag#U!@s=4X*48)s zn@>7Q`8D;tYkz^8RIKuMQ+aBCN6JWfM)kg@{VmnXRsCtyU#0rh+RsP1tCz$Th|j3^ zDXqLE@sLRp&m`WMLEFLPbV=S-xERlcjVCrD&h&={Nypgy9>-!ht!G)##7V+s2iSwy` zw7)4|t5{p#Z6xm6LCWX5OMGmjidFvO)cd0LXUF>9LHUOX>zn$I)OMofcZBlT1`=N; zF2wrI3<#%~Xdk1=`SmkRV-&Mt> z`~u}owdX_iF`Rs-)s^xal-sku%hi|m<~vDwSK>imO1y%&e^!bAB;H?0V!O|zemT~+ z4{?vFs$BJN*H+4xx0mI&tM#P))nQAG-8|(Wj<@;4X+WIi4 z?Ogk7_o>9?h%Zf$xC?Pj)t0vW1mYsB?>OQLtnVGfk6Os`x4fnOO%W>2XfXJa?+tq? z&)QJR>uS%3w!X>tuA7wGQQoJq#L>hL9VI?NTxNm9L)G)5{p}tkapp!6AI&0h8RDF* z|GvbrU8MX7af`_+*4BSJssFc98-IJ+U%f%aYCO5rcB1{QEG^}|DSxDuYwMr-Bdbff z_Bz%6^0NLf63?k1<=NExruJvY`u8UOBAt|L@2lEhi@XvKB987Q@m%7{tp63hvi!<$ zRj%?Kr`EIfSKeNhKS;T=_WWq;pL`#y$8)GY<0(H+{E)c#3RynRPjAi;wOqxjeS=Zr z_T!~IqPfIz~Y z7cAw!j-o#0g|%3f`;{)Nd`Z|2ipm z3z4|&Eb3DpIaA8-P@ZEg^?83Wt&#F^-K2i{8Pun|@pLJ73zhP`tEtcHrR#T69^YNc zf15^q%FAf68sE4uDKET=`aIt;E2X@0gp_ZaLVe1!XtAmvPx-KK42GQQ_0YP2EZ^Bz zi(?H1%SyZ_PReuTkhng}cgZ7h2I3FY`-t|pM?G&j)9f&u$|7;Nzr-KpmbmF$X>X9) zMzz1a)Q{66bzDaI5|yL&H^p6+A1t9E-bLcR#MOui4Ifbd>Id@3O6ngbe$4W_h?^0A zMeMA`spTL2k<@RkUjJIGPJ`-y4;kOZ@)D2EDdiW6NxWb0Z-?PlQHk?ZmGb_?p|iC( z)=;6elt)s(Z6S$U5Kkw5N_({nOSvcQITH`j^WR}`m14uBIO(q~<;!TV3;A_md|%m1 zg-pbA8SkiUQeT^QYJW`_?-F$!r~Um-K7;M`&`_Ry1`>Bm$ftyq=WQzEeO5|h&pFb5 z#^MsYP@a|b;qI@F$zNaA?)`qW}=Iqh#+C5bZ=|JhOE)@;vx z3rO6S@}6ot)9N=TzT+kFbMo&}OX5ew^VEi?Eg#JC8yIi>3ex|EDpKBn{x&6SPsG7$ zKdRNQKzxq&OAtGoqF)sXD%S5*Vi(GrYOm+?21Be`&)VN; zZGEdaj`*k^#~R$4N%^J$T6wG?g7OIB%9Ll&UJt5#9Q%t}3nhL;`5Nu{Rpr{}8rt8H zc@pPh`CsQte22Jfw8UkIYiRkZ=fuB*)bFL`r{Xx`O?n(_*g^b_mS4tLLo9JC;&|fK z>!o~^QQEt|K;j6sU1)#(wR~0m$^jC$)ACiZf$}k0zFO=r<)6^LFY#YdQoe)bOR>Il zvHk+IeAW7PBc7+nI}BHeM`-P(-(lEDT${Kx>+|YdDUTzrtFJ$`JnO4ekSb4SFkDmp zYJd5NpA%DZYP}>bAEw$(93S&f8jlW48Xr>mBwqfy zS$nO_mLG4nd~vh#y=L)$>UmAv{)B-^<0$q1l(>Ahdc7u&Pn*>bHml#nY<+b#TfR!p zr0vZyE5Bsc-Y~QB8|wWwaXyU$lE#JNlE$sf;u2=1|fN!L0ogX6y5gS-jXR|6FGMk1;D>F*|8~znR5F%-Wx8 zwmnxeYp=0coGv(N`-RM2Ps7yvf8ysizuESeUcKHEmp?U&kDJAxnQf1C%;F$p()Jpg z#f{9ySKTa5WA=O%Gkd*1HGBPyFk4<5OXBggGwa{qtUrUXyQzCnL?46E*w(Rf=cp)S zP-uuLEZP_q9T06YhM9Wxd|4D_itK5MG%E@Y_0<;%4iJ4Dd%8NdbailS9^NQCC?M3c zdqi{}Pkj*|zi20;(ZQjz(by>_EGRl8Jj_M@>D9KakArhVQ)HkiGCayp@5k9M+7#j0 ztf7ySPe7Ps<@(fc4+sqn3<&Dx71k--OY5vk%Ye`rlc)OgY3TH^(J3g@)5p)~n$Uw+ z{hmI4^^6MNmp!x!kL+fO)at0e7NLF~Mo*)vR86(5a*hs<^z!pEdV2bK8a=B9o1&s4 z!z~nOzacm{xpy%Ib@L5~ zis}^}8Eo;(q3Y{WultUdgZry5hX&fqLA^{YcsV$@_(q0=1%*TegnF2w142ThEY9BL zeP-_!77`s25E|0gByUI-XI~|CWH0YU7H9AL-m*`$E08zps-C?~K{3%L&z|bd+U(8U z*UwRHnx3z`e^*tH*6-=(qDcNWo2ciM?u4{mklC)JuAYin-ahKp^p>4c%96Hbx1$nw ze9wuect@jhcX-daTfS>iNmu^=o3s@>6P0XLvt+BiezSJB(PnMk?nCA4^8Y(uYjzka z-zx7fU(0t9DqrXSgM77PeFulSQGLRKc%|_g$Mu_Hhr04(d|1nW=e~$naiF zE>uxfuc+`)HE(gK`k5)(Jti_z&1Bre!=g>SqhBuM(j>5}DJa^()k_sbh6RMy4>5%X zyNAbwC0gi3OO;=?L=z1Y=TNOdK$LqxOy@2MbsNeY$I-!P3=D`02~x8qbr96q7!=;U zdw7^vqd*5wPe(NYiqlmPSExCYWuo4(bieQ+uYu!;F2^#5188tz){- zo@^IC{V8;5q(4~{sK>QgZq@pc;oZGsqN3Gv6&~G1J=2uyUS}F%QNlO10 z=jaZuOwx_PCZ_NSt0I}hvF5-@|JcFS^L1MdDaD6W`lxI@cemB3EI-)Nhhyt`d)H@{EuNUS+@)1MPt&-HCE63Y+j^pV(l-k-9OB$|oaJBc}>@D;$*nBEu`Sb8{43_UT^fB0c5@X>QY(9NSdH?Ty;*#>zt=UnJ0z95ZKf#}rf$V9NTqC>35umDTeZ_sS=(l6VsX|l z-=gIW#**txRMxhclvt6q~#(@1IhmhTJn z^ld%KupoU~&o5He_4}S$q%7;yFsra8^AzuK)B%i5CKT2rZ}~n(Wo?tWgauh!u~$*q z+GHAGNw!w)M^wT#nL${Tur+%Qm9R}F4=GI8@_mI$*e3G^vxMc!CM&Ogb5LKvN_zDh z7m2;)YCI1|mNCD|>@@|lhj>x&%GH2LOA=i#_o6^uXy@P{7Z>^kg-4iP6eL{P_43+3 zuf&)9dA?Zil{6h*$)7Y|Es$#uJQ50C%|A&=;`|c|RQ@lnSbfpXD}zc{I$==%OW%-t zF{)%HZ_WN!Kkl;iDX5eUAjP|3eGImq_@!(NmhX-AelDA?P zp(kzgc}TL7wrYo==WX+ONb>TwX7{1zZS#4ErFmPvGtu+5`8*^Uc_%uGx5>9|%-)i% zorhR9f|Tx@)UMnncknP9{JW-2*6fZ{%C?z@Shj{GKv}_ za~Rac7#yAmc| zvS?7>v# zHko>+G;^!=St@y(%tlk3yfu3%mAp+Rs5VI6^8J!Z-X?R_cPDS<2apcx_VwC*7lLID z`|7;JsBY73ii|c!Mu!=+S*W_dqc&R!>(yPKv~bfvCy$V*i0~*Aw_o&4Tv*Lr-R3Z| zm39ZhB#%3|%F^m?)aqt|CUs}aAd{!Bx}l+~e!D|;8_R@SRwk}j*)u9AAR-_z)RgE7 zN*Db>Rr^K1NiMK-aCDC}srj|kctamrRqclWg47)vyL2;lQg`>(9tr9lV2p@~G#Pt_ zL`KI1sK?Z#xkrpCM%}kjO`Wxs;83-Ny78uyW0MH&{{Q;D`}Mo{>pvFYr3S?PIn}Kh z)eOI@zTOhug|S+z$dG7Li|9_SdS)*N9Tegl5~3~r<_{9Id)UAJg9LSRNWHF>3AcN6 zaPTqp((dl~n!XwasXQH=)BmbCd3Fzp);|K$-n-QX zsWzV%TcnSA#;PQ2)s+)%);@ktMzx`x1-Wn z%c!3YXyWIccvZbC!%#2gPTtv^*>z$i&>bP5dvXe~> zbBz=v`~Kz@iIQ#ZXX{_9(tj2!=`U7Qd)u!ls9&tAr+%VG+Y>dn`A=tAlT6YzW6gWI z{#m7*d$A^=q-!S?B=ov9l;Zt|zLMljj;&YH`_Acg>&f!nmA-=H)R3)L(0fZptr;tJ zi~1UolT5E!Bd+gw*HOP@^x|FT{U@QV39CNx(^rO^rm}Wrq=r27^k6q z<%E;A*LSRv)}S%CHvf9luW zFJ=K z^A1sW>Qv`x^j{3nFQQFIKJk(c`W=Q|T}(eK%1KRi&NJzWSN*9|=e=IsE)q2~~Hk zRcCTtw1*P5IsJ#_d#bZ8uaxMgdG*#BYA3l|6KYh^{$Vuh)yGerJ4!hH=aA_1pSD># zYbO8`omauu6RM`QVMv>HZbwP{z=&us@p zhevw(rR>MB6YkKPg6+$S!)cYiO|EBq!?WO>oR^1nN7ZTsHo2(Hx)E4&aIHpQlPlY7 zH3G|zvDFA{a(SCIBe2EJLjN?()?e{?!=OBq^U_E>C~I~d`oL`cJs;Z+EX6w#eQdV= zvX5=YX8CSKAC#@X@$-&BHE)?PMR?t@SmI4Fr3YjGC$F!B8N^$TBU5?qFQ#VygX=xn z+f1r^`?7GmNu~KGd)rB+`CGXCq^`Y0iZ-FtI0Or~qSQD93pb=xvP(|U7L=-Tw{X)* zO}W4QEB02*s`cX>TYt~_4M%St$(l!4H^?7s|>P_D-;hq2GslC_EA5-nxe%D5l>fYg#w~?gMwBPYIlKOsBS=M&) zHf?Z&F^TvYP93Vh=>nH3xyTBvW=J2~p#Qh$3d z`oNN&!Pma`s=g_%<(qIFfK#ID0JQbd-0$@tDy#3|n%=P6)2qEGN_DRepS}Ia)W><3oFZZqJ8yV zo-ws9ldQ-@*G_1iCH~cWi(h-vfN#PjP#$sxlm#;k^96$9 z1Y1};(d$^oZ}BGy`g8X3OVKGjiDA}?J<`Y(yp3}((iC;l=tN5n21o5m$!Cv0xnyt zVl?Uxs!RQXLxN0EUf!*vBARRaP+kjf-|wjR@^@UT`l6wPHEj0%e)dEbG?cIrnKksv zcALUCCQr4BZE|aaq+99#Mz(Kwl2YlqP41Q;JC_vg545epCRYnuwl$=ljFY=Xq@Ii| z+bU9e$f0c*Ho5RJB^yR6N!qe)Bb6j=+2&#K(XqB&*yKvqlx!F8J6p>(i1(fCTek!& zP6((iz$O<1Cu0jpHCev(nNKxYzWo`u>b!({(p}U+Y~l;ptEr=C?dxkv4v~G-d5AZB zV51!>zx}9Nj>D`w6Jgs#-~PO(qBZ)Cr{0>g4Qh?rE%>xZ+u7UXihT>8`uCk^vY-0*ov1~hUihe+yT1Fa`3+-#{pT3TYVwtj_nex= zsJmq9pIN^6>Y#pxK(5VB{E3T?pNp0=a1)M1`w?qDYtlYhRd)`vau2Sz;%DVOc(ff? zLONFOSYBjg?c3CgjBL`7wvJvll(JXPYcjH;p(MA0vF0N+(n_?kTisfc++>U?|B&a^ h{A|+VYjU(|BK)Q_t#9--nWk)p_NEk5*qXuc{{SC4tDyh@ diff --git a/node_modules/kerberos/build/binding.Makefile b/node_modules/kerberos/build/binding.Makefile deleted file mode 100644 index 69e964f..0000000 --- a/node_modules/kerberos/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= ./build/. -.PHONY: all -all: - $(MAKE) kerberos diff --git a/node_modules/kerberos/build/config.gypi b/node_modules/kerberos/build/config.gypi deleted file mode 100644 index e3a958b..0000000 --- a/node_modules/kerberos/build/config.gypi +++ /dev/null @@ -1,202 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "asan": 0, - "build_v8_with_gn": "false", - "coverage": "false", - "debug_nghttp2": "false", - "debug_node": "false", - "enable_lto": "false", - "enable_pgo_generate": "false", - "enable_pgo_use": "false", - "force_dynamic_crt": 0, - "host_arch": "x64", - "icu_data_in": "../../deps/icu-small/source/data/in/icudt65l.dat", - "icu_default_data": "", - "icu_endianness": "l", - "icu_gyp_path": "tools/icu/icu-generic.gyp", - "icu_locales": "en,root", - "icu_path": "deps/icu-small", - "icu_small": "true", - "icu_ver_major": "65", - "is_debug": 0, - "llvm_version": "0.0", - "napi_build_version": "5", - "node_byteorder": "little", - "node_debug_lib": "false", - "node_enable_d8": "false", - "node_install_npm": "true", - "node_module_version": 72, - "node_no_browser_globals": "false", - "node_prefix": "/usr/local", - "node_release_urlbase": "https://nodejs.org/download/release/", - "node_report": "true", - "node_shared": "false", - "node_shared_brotli": "false", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_nghttp2": "false", - "node_shared_openssl": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_target_type": "executable", - "node_use_bundled_v8": "true", - "node_use_dtrace": "true", - "node_use_etw": "false", - "node_use_large_pages": "false", - "node_use_large_pages_script_lld": "false", - "node_use_node_code_cache": "true", - "node_use_node_snapshot": "true", - "node_use_openssl": "true", - "node_use_v8_platform": "true", - "node_with_ltcg": "false", - "node_without_node_options": "false", - "openssl_fips": "", - "openssl_is_fips": "false", - "shlib_suffix": "72.dylib", - "target_arch": "x64", - "v8_enable_gdbjit": 0, - "v8_enable_i18n_support": 1, - "v8_enable_inspector": 1, - "v8_no_strict_aliasing": 1, - "v8_optimized_debug": 1, - "v8_promise_internal_field_count": 1, - "v8_random_seed": 0, - "v8_trace_maps": 0, - "v8_use_siphash": 1, - "v8_use_snapshot": 1, - "want_separate_host_toolset": 0, - "xcode_version": "11.0", - "nodedir": "/Users/kai/Library/Caches/node-gyp/12.16.3", - "standalone_static_library": 1, - "dry_run": "", - "legacy_bundling": "", - "save_dev": "", - "browser": "", - "commit_hooks": "true", - "only": "", - "viewer": "man", - "also": "", - "rollback": "true", - "sign_git_commit": "", - "audit": "true", - "usage": "", - "globalignorefile": "/usr/local/etc/npmignore", - "init_author_url": "", - "maxsockets": "50", - "shell": "/bin/bash", - "metrics_registry": "https://registry.npmjs.org/", - "parseable": "", - "shrinkwrap": "true", - "init_license": "ISC", - "timing": "", - "if_present": "", - "cache_max": "Infinity", - "init_author_email": "", - "sign_git_tag": "", - "cert": "", - "git_tag_version": "true", - "local_address": "", - "long": "", - "preid": "", - "fetch_retries": "2", - "registry": "https://registry.npmjs.org/", - "key": "", - "message": "%s", - "versions": "", - "globalconfig": "/usr/local/etc/npmrc", - "always_auth": "", - "logs_max": "10", - "prefer_online": "", - "cache_lock_retries": "10", - "global_style": "", - "update_notifier": "true", - "audit_level": "low", - "heading": "npm", - "fetch_retry_mintimeout": "10000", - "offline": "", - "read_only": "", - "searchlimit": "20", - "access": "", - "json": "", - "allow_same_version": "", - "description": "true", - "engine_strict": "", - "https_proxy": "", - "init_module": "/Users/kai/.npm-init.js", - "userconfig": "/Users/kai/.npmrc", - "cidr": "", - "node_version": "12.16.3", - "user": "", - "save": "true", - "auth_type": "legacy", - "editor": "vi", - "ignore_prepublish": "", - "script_shell": "", - "tag": "latest", - "before": "", - "global": "", - "progress": "true", - "ham_it_up": "", - "optional": "true", - "searchstaleness": "900", - "bin_links": "true", - "force": "", - "save_prod": "", - "searchopts": "", - "depth": "Infinity", - "node_gyp": "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js", - "rebuild_bundle": "true", - "sso_poll_frequency": "500", - "unicode": "true", - "fetch_retry_maxtimeout": "60000", - "ca": "", - "save_prefix": "^", - "scripts_prepend_node_path": "warn-only", - "sso_type": "oauth", - "strict_ssl": "true", - "tag_version_prefix": "v", - "dev": "", - "fetch_retry_factor": "10", - "group": "20", - "save_exact": "", - "cache_lock_stale": "60000", - "prefer_offline": "", - "version": "", - "cache_min": "10", - "otp": "", - "cache": "/Users/kai/.npm", - "searchexclude": "", - "color": "true", - "package_lock": "true", - "fund": "true", - "package_lock_only": "", - "save_optional": "", - "user_agent": "npm/6.14.4 node/v12.16.3 darwin x64", - "ignore_scripts": "", - "cache_lock_wait": "10000", - "production": "", - "save_bundle": "", - "send_metrics": "", - "init_version": "1.0.0", - "node_options": "", - "umask": "0022", - "scope": "", - "git": "git", - "init_author_name": "", - "onload_script": "", - "tmp": "/var/folders/j0/cdgb7f992gz82psv0ndccctr0000gn/T", - "unsafe_perm": "true", - "format_package_lock": "true", - "link": "", - "prefix": "/usr/local" - } -} diff --git a/node_modules/kerberos/build/gyp-mac-tool b/node_modules/kerberos/build/gyp-mac-tool deleted file mode 100755 index 033b4e5..0000000 --- a/node_modules/kerberos/build/gyp-mac-tool +++ /dev/null @@ -1,615 +0,0 @@ -#!/usr/bin/env python -# Generated by gyp. Do not edit. -# Copyright (c) 2012 Google Inc. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Utility functions to perform Xcode-style build steps. - -These functions are executed via gyp-mac-tool when using the Makefile generator. -""" - -from __future__ import print_function - -import fcntl -import fnmatch -import glob -import json -import os -import plistlib -import re -import shutil -import string -import subprocess -import sys -import tempfile - -PY3 = bytes != str - - -def main(args): - executor = MacTool() - exit_code = executor.Dispatch(args) - if exit_code is not None: - sys.exit(exit_code) - - -class MacTool(object): - """This class performs all the Mac tooling steps. The methods can either be - executed directly, or dispatched from an argument list.""" - - def Dispatch(self, args): - """Dispatches a string command to a method.""" - if len(args) < 1: - raise Exception("Not enough arguments") - - method = "Exec%s" % self._CommandifyName(args[0]) - return getattr(self, method)(*args[1:]) - - def _CommandifyName(self, name_string): - """Transforms a tool name like copy-info-plist to CopyInfoPlist""" - return name_string.title().replace('-', '') - - def ExecCopyBundleResource(self, source, dest, convert_to_binary): - """Copies a resource file to the bundle/Resources directory, performing any - necessary compilation on each resource.""" - extension = os.path.splitext(source)[1].lower() - if os.path.isdir(source): - # Copy tree. - # TODO(thakis): This copies file attributes like mtime, while the - # single-file branch below doesn't. This should probably be changed to - # be consistent with the single-file branch. - if os.path.exists(dest): - shutil.rmtree(dest) - shutil.copytree(source, dest) - elif extension == '.xib': - return self._CopyXIBFile(source, dest) - elif extension == '.storyboard': - return self._CopyXIBFile(source, dest) - elif extension == '.strings': - self._CopyStringsFile(source, dest, convert_to_binary) - else: - shutil.copy(source, dest) - - def _CopyXIBFile(self, source, dest): - """Compiles a XIB file with ibtool into a binary plist in the bundle.""" - - # ibtool sometimes crashes with relative paths. See crbug.com/314728. - base = os.path.dirname(os.path.realpath(__file__)) - if os.path.relpath(source): - source = os.path.join(base, source) - if os.path.relpath(dest): - dest = os.path.join(base, dest) - - args = ['xcrun', 'ibtool', '--errors', '--warnings', '--notices', - '--output-format', 'human-readable-text', '--compile', dest, source] - ibtool_section_re = re.compile(r'/\*.*\*/') - ibtool_re = re.compile(r'.*note:.*is clipping its content') - ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE) - current_section_header = None - for line in ibtoolout.stdout: - if ibtool_section_re.match(line): - current_section_header = line - elif not ibtool_re.match(line): - if current_section_header: - sys.stdout.write(current_section_header) - current_section_header = None - sys.stdout.write(line) - return ibtoolout.returncode - - def _ConvertToBinary(self, dest): - subprocess.check_call([ - 'xcrun', 'plutil', '-convert', 'binary1', '-o', dest, dest]) - - def _CopyStringsFile(self, source, dest, convert_to_binary): - """Copies a .strings file using iconv to reconvert the input into UTF-16.""" - input_code = self._DetectInputEncoding(source) or "UTF-8" - - # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call - # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints - # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing - # semicolon in dictionary. - # on invalid files. Do the same kind of validation. - import CoreFoundation - s = open(source, 'rb').read() - d = CoreFoundation.CFDataCreate(None, s, len(s)) - _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None) - if error: - return - - fp = open(dest, 'wb') - fp.write(s.decode(input_code).encode('UTF-16')) - fp.close() - - if convert_to_binary == 'True': - self._ConvertToBinary(dest) - - def _DetectInputEncoding(self, file_name): - """Reads the first few bytes from file_name and tries to guess the text - encoding. Returns None as a guess if it can't detect it.""" - fp = open(file_name, 'rb') - try: - header = fp.read(3) - except Exception: - fp.close() - return None - fp.close() - if header.startswith("\xFE\xFF"): - return "UTF-16" - elif header.startswith("\xFF\xFE"): - return "UTF-16" - elif header.startswith("\xEF\xBB\xBF"): - return "UTF-8" - else: - return None - - def ExecCopyInfoPlist(self, source, dest, convert_to_binary, *keys): - """Copies the |source| Info.plist to the destination directory |dest|.""" - # Read the source Info.plist into memory. - fd = open(source, 'r') - lines = fd.read() - fd.close() - - # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild). - plist = plistlib.readPlistFromString(lines) - if keys: - plist = dict(plist.items() + json.loads(keys[0]).items()) - lines = plistlib.writePlistToString(plist) - - # Go through all the environment variables and replace them as variables in - # the file. - IDENT_RE = re.compile(r'[/\s]') - for key in os.environ: - if key.startswith('_'): - continue - evar = '${%s}' % key - evalue = os.environ[key] - lines = string.replace(lines, evar, evalue) - - # Xcode supports various suffices on environment variables, which are - # all undocumented. :rfc1034identifier is used in the standard project - # template these days, and :identifier was used earlier. They are used to - # convert non-url characters into things that look like valid urls -- - # except that the replacement character for :identifier, '_' isn't valid - # in a URL either -- oops, hence :rfc1034identifier was born. - evar = '${%s:identifier}' % key - evalue = IDENT_RE.sub('_', os.environ[key]) - lines = string.replace(lines, evar, evalue) - - evar = '${%s:rfc1034identifier}' % key - evalue = IDENT_RE.sub('-', os.environ[key]) - lines = string.replace(lines, evar, evalue) - - # Remove any keys with values that haven't been replaced. - lines = lines.split('\n') - for i in range(len(lines)): - if lines[i].strip().startswith("${"): - lines[i] = None - lines[i - 1] = None - lines = '\n'.join(filter(lambda x: x is not None, lines)) - - # Write out the file with variables replaced. - fd = open(dest, 'w') - fd.write(lines) - fd.close() - - # Now write out PkgInfo file now that the Info.plist file has been - # "compiled". - self._WritePkgInfo(dest) - - if convert_to_binary == 'True': - self._ConvertToBinary(dest) - - def _WritePkgInfo(self, info_plist): - """This writes the PkgInfo file from the data stored in Info.plist.""" - plist = plistlib.readPlist(info_plist) - if not plist: - return - - # Only create PkgInfo for executable types. - package_type = plist['CFBundlePackageType'] - if package_type != 'APPL': - return - - # The format of PkgInfo is eight characters, representing the bundle type - # and bundle signature, each four characters. If that is missing, four - # '?' characters are used instead. - signature_code = plist.get('CFBundleSignature', '????') - if len(signature_code) != 4: # Wrong length resets everything, too. - signature_code = '?' * 4 - - dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo') - fp = open(dest, 'w') - fp.write('%s%s' % (package_type, signature_code)) - fp.close() - - def ExecFlock(self, lockfile, *cmd_list): - """Emulates the most basic behavior of Linux's flock(1).""" - # Rely on exception handling to report errors. - fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666) - fcntl.flock(fd, fcntl.LOCK_EX) - return subprocess.call(cmd_list) - - def ExecFilterLibtool(self, *cmd_list): - """Calls libtool and filters out '/path/to/libtool: file: foo.o has no - symbols'.""" - libtool_re = re.compile(r'^.*libtool: file: .* has no symbols$') - libtool_re5 = re.compile( - r'^.*libtool: warning for library: ' + - r'.* the table of contents is empty ' + - r'\(no object file members in the library define global symbols\)$') - env = os.environ.copy() - # Ref: - # http://www.opensource.apple.com/source/cctools/cctools-809/misc/libtool.c - # The problem with this flag is that it resets the file mtime on the file to - # epoch=0, e.g. 1970-1-1 or 1969-12-31 depending on timezone. - env['ZERO_AR_DATE'] = '1' - libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE, env=env) - _, err = libtoolout.communicate() - if PY3: - err = err.decode('utf-8') - for line in err.splitlines(): - if not libtool_re.match(line) and not libtool_re5.match(line): - print(line, file=sys.stderr) - # Unconditionally touch the output .a file on the command line if present - # and the command succeeded. A bit hacky. - if not libtoolout.returncode: - for i in range(len(cmd_list) - 1): - if cmd_list[i] == "-o" and cmd_list[i+1].endswith('.a'): - os.utime(cmd_list[i+1], None) - break - return libtoolout.returncode - - def ExecPackageFramework(self, framework, version): - """Takes a path to Something.framework and the Current version of that and - sets up all the symlinks.""" - # Find the name of the binary based on the part before the ".framework". - binary = os.path.basename(framework).split('.')[0] - - CURRENT = 'Current' - RESOURCES = 'Resources' - VERSIONS = 'Versions' - - if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): - # Binary-less frameworks don't seem to contain symlinks (see e.g. - # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). - return - - # Move into the framework directory to set the symlinks correctly. - pwd = os.getcwd() - os.chdir(framework) - - # Set up the Current version. - self._Relink(version, os.path.join(VERSIONS, CURRENT)) - - # Set up the root symlinks. - self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) - self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) - - # Back to where we were before! - os.chdir(pwd) - - def _Relink(self, dest, link): - """Creates a symlink to |dest| named |link|. If |link| already exists, - it is overwritten.""" - if os.path.lexists(link): - os.remove(link) - os.symlink(dest, link) - - def ExecCompileXcassets(self, keys, *inputs): - """Compiles multiple .xcassets files into a single .car file. - - This invokes 'actool' to compile all the inputs .xcassets files. The - |keys| arguments is a json-encoded dictionary of extra arguments to - pass to 'actool' when the asset catalogs contains an application icon - or a launch image. - - Note that 'actool' does not create the Assets.car file if the asset - catalogs does not contains imageset. - """ - command_line = [ - 'xcrun', 'actool', '--output-format', 'human-readable-text', - '--compress-pngs', '--notices', '--warnings', '--errors', - ] - is_iphone_target = 'IPHONEOS_DEPLOYMENT_TARGET' in os.environ - if is_iphone_target: - platform = os.environ['CONFIGURATION'].split('-')[-1] - if platform not in ('iphoneos', 'iphonesimulator'): - platform = 'iphonesimulator' - command_line.extend([ - '--platform', platform, '--target-device', 'iphone', - '--target-device', 'ipad', '--minimum-deployment-target', - os.environ['IPHONEOS_DEPLOYMENT_TARGET'], '--compile', - os.path.abspath(os.environ['CONTENTS_FOLDER_PATH']), - ]) - else: - command_line.extend([ - '--platform', 'macosx', '--target-device', 'mac', - '--minimum-deployment-target', os.environ['MACOSX_DEPLOYMENT_TARGET'], - '--compile', - os.path.abspath(os.environ['UNLOCALIZED_RESOURCES_FOLDER_PATH']), - ]) - if keys: - keys = json.loads(keys) - for key, value in keys.items(): - arg_name = '--' + key - if isinstance(value, bool): - if value: - command_line.append(arg_name) - elif isinstance(value, list): - for v in value: - command_line.append(arg_name) - command_line.append(str(v)) - else: - command_line.append(arg_name) - command_line.append(str(value)) - # Note: actool crashes if inputs path are relative, so use os.path.abspath - # to get absolute path name for inputs. - command_line.extend(map(os.path.abspath, inputs)) - subprocess.check_call(command_line) - - def ExecMergeInfoPlist(self, output, *inputs): - """Merge multiple .plist files into a single .plist file.""" - merged_plist = {} - for path in inputs: - plist = self._LoadPlistMaybeBinary(path) - self._MergePlist(merged_plist, plist) - plistlib.writePlist(merged_plist, output) - - def ExecCodeSignBundle(self, key, resource_rules, entitlements, provisioning): - """Code sign a bundle. - - This function tries to code sign an iOS bundle, following the same - algorithm as Xcode: - 1. copy ResourceRules.plist from the user or the SDK into the bundle, - 2. pick the provisioning profile that best match the bundle identifier, - and copy it into the bundle as embedded.mobileprovision, - 3. copy Entitlements.plist from user or SDK next to the bundle, - 4. code sign the bundle. - """ - resource_rules_path = self._InstallResourceRules(resource_rules) - substitutions, overrides = self._InstallProvisioningProfile( - provisioning, self._GetCFBundleIdentifier()) - entitlements_path = self._InstallEntitlements( - entitlements, substitutions, overrides) - subprocess.check_call([ - 'codesign', '--force', '--sign', key, '--resource-rules', - resource_rules_path, '--entitlements', entitlements_path, - os.path.join( - os.environ['TARGET_BUILD_DIR'], - os.environ['FULL_PRODUCT_NAME'])]) - - def _InstallResourceRules(self, resource_rules): - """Installs ResourceRules.plist from user or SDK into the bundle. - - Args: - resource_rules: string, optional, path to the ResourceRules.plist file - to use, default to "${SDKROOT}/ResourceRules.plist" - - Returns: - Path to the copy of ResourceRules.plist into the bundle. - """ - source_path = resource_rules - target_path = os.path.join( - os.environ['BUILT_PRODUCTS_DIR'], - os.environ['CONTENTS_FOLDER_PATH'], - 'ResourceRules.plist') - if not source_path: - source_path = os.path.join( - os.environ['SDKROOT'], 'ResourceRules.plist') - shutil.copy2(source_path, target_path) - return target_path - - def _InstallProvisioningProfile(self, profile, bundle_identifier): - """Installs embedded.mobileprovision into the bundle. - - Args: - profile: string, optional, short name of the .mobileprovision file - to use, if empty or the file is missing, the best file installed - will be used - bundle_identifier: string, value of CFBundleIdentifier from Info.plist - - Returns: - A tuple containing two dictionary: variables substitutions and values - to overrides when generating the entitlements file. - """ - source_path, provisioning_data, team_id = self._FindProvisioningProfile( - profile, bundle_identifier) - target_path = os.path.join( - os.environ['BUILT_PRODUCTS_DIR'], - os.environ['CONTENTS_FOLDER_PATH'], - 'embedded.mobileprovision') - shutil.copy2(source_path, target_path) - substitutions = self._GetSubstitutions(bundle_identifier, team_id + '.') - return substitutions, provisioning_data['Entitlements'] - - def _FindProvisioningProfile(self, profile, bundle_identifier): - """Finds the .mobileprovision file to use for signing the bundle. - - Checks all the installed provisioning profiles (or if the user specified - the PROVISIONING_PROFILE variable, only consult it) and select the most - specific that correspond to the bundle identifier. - - Args: - profile: string, optional, short name of the .mobileprovision file - to use, if empty or the file is missing, the best file installed - will be used - bundle_identifier: string, value of CFBundleIdentifier from Info.plist - - Returns: - A tuple of the path to the selected provisioning profile, the data of - the embedded plist in the provisioning profile and the team identifier - to use for code signing. - - Raises: - SystemExit: if no .mobileprovision can be used to sign the bundle. - """ - profiles_dir = os.path.join( - os.environ['HOME'], 'Library', 'MobileDevice', 'Provisioning Profiles') - if not os.path.isdir(profiles_dir): - print('cannot find mobile provisioning for %s' % (bundle_identifier), file=sys.stderr) - sys.exit(1) - provisioning_profiles = None - if profile: - profile_path = os.path.join(profiles_dir, profile + '.mobileprovision') - if os.path.exists(profile_path): - provisioning_profiles = [profile_path] - if not provisioning_profiles: - provisioning_profiles = glob.glob( - os.path.join(profiles_dir, '*.mobileprovision')) - valid_provisioning_profiles = {} - for profile_path in provisioning_profiles: - profile_data = self._LoadProvisioningProfile(profile_path) - app_id_pattern = profile_data.get( - 'Entitlements', {}).get('application-identifier', '') - for team_identifier in profile_data.get('TeamIdentifier', []): - app_id = '%s.%s' % (team_identifier, bundle_identifier) - if fnmatch.fnmatch(app_id, app_id_pattern): - valid_provisioning_profiles[app_id_pattern] = ( - profile_path, profile_data, team_identifier) - if not valid_provisioning_profiles: - print('cannot find mobile provisioning for %s' % (bundle_identifier), file=sys.stderr) - sys.exit(1) - # If the user has multiple provisioning profiles installed that can be - # used for ${bundle_identifier}, pick the most specific one (ie. the - # provisioning profile whose pattern is the longest). - selected_key = max(valid_provisioning_profiles, key=lambda v: len(v)) - return valid_provisioning_profiles[selected_key] - - def _LoadProvisioningProfile(self, profile_path): - """Extracts the plist embedded in a provisioning profile. - - Args: - profile_path: string, path to the .mobileprovision file - - Returns: - Content of the plist embedded in the provisioning profile as a dictionary. - """ - with tempfile.NamedTemporaryFile() as temp: - subprocess.check_call([ - 'security', 'cms', '-D', '-i', profile_path, '-o', temp.name]) - return self._LoadPlistMaybeBinary(temp.name) - - def _MergePlist(self, merged_plist, plist): - """Merge |plist| into |merged_plist|.""" - for key, value in plist.items(): - if isinstance(value, dict): - merged_value = merged_plist.get(key, {}) - if isinstance(merged_value, dict): - self._MergePlist(merged_value, value) - merged_plist[key] = merged_value - else: - merged_plist[key] = value - else: - merged_plist[key] = value - - def _LoadPlistMaybeBinary(self, plist_path): - """Loads into a memory a plist possibly encoded in binary format. - - This is a wrapper around plistlib.readPlist that tries to convert the - plist to the XML format if it can't be parsed (assuming that it is in - the binary format). - - Args: - plist_path: string, path to a plist file, in XML or binary format - - Returns: - Content of the plist as a dictionary. - """ - try: - # First, try to read the file using plistlib that only supports XML, - # and if an exception is raised, convert a temporary copy to XML and - # load that copy. - return plistlib.readPlist(plist_path) - except: - pass - with tempfile.NamedTemporaryFile() as temp: - shutil.copy2(plist_path, temp.name) - subprocess.check_call(['plutil', '-convert', 'xml1', temp.name]) - return plistlib.readPlist(temp.name) - - def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix): - """Constructs a dictionary of variable substitutions for Entitlements.plist. - - Args: - bundle_identifier: string, value of CFBundleIdentifier from Info.plist - app_identifier_prefix: string, value for AppIdentifierPrefix - - Returns: - Dictionary of substitutions to apply when generating Entitlements.plist. - """ - return { - 'CFBundleIdentifier': bundle_identifier, - 'AppIdentifierPrefix': app_identifier_prefix, - } - - def _GetCFBundleIdentifier(self): - """Extracts CFBundleIdentifier value from Info.plist in the bundle. - - Returns: - Value of CFBundleIdentifier in the Info.plist located in the bundle. - """ - info_plist_path = os.path.join( - os.environ['TARGET_BUILD_DIR'], - os.environ['INFOPLIST_PATH']) - info_plist_data = self._LoadPlistMaybeBinary(info_plist_path) - return info_plist_data['CFBundleIdentifier'] - - def _InstallEntitlements(self, entitlements, substitutions, overrides): - """Generates and install the ${BundleName}.xcent entitlements file. - - Expands variables "$(variable)" pattern in the source entitlements file, - add extra entitlements defined in the .mobileprovision file and the copy - the generated plist to "${BundlePath}.xcent". - - Args: - entitlements: string, optional, path to the Entitlements.plist template - to use, defaults to "${SDKROOT}/Entitlements.plist" - substitutions: dictionary, variable substitutions - overrides: dictionary, values to add to the entitlements - - Returns: - Path to the generated entitlements file. - """ - source_path = entitlements - target_path = os.path.join( - os.environ['BUILT_PRODUCTS_DIR'], - os.environ['PRODUCT_NAME'] + '.xcent') - if not source_path: - source_path = os.path.join( - os.environ['SDKROOT'], - 'Entitlements.plist') - shutil.copy2(source_path, target_path) - data = self._LoadPlistMaybeBinary(target_path) - data = self._ExpandVariables(data, substitutions) - if overrides: - for key in overrides: - if key not in data: - data[key] = overrides[key] - plistlib.writePlist(data, target_path) - return target_path - - def _ExpandVariables(self, data, substitutions): - """Expands variables "$(variable)" in data. - - Args: - data: object, can be either string, list or dictionary - substitutions: dictionary, variable substitutions to perform - - Returns: - Copy of data where each references to "$(variable)" has been replaced - by the corresponding value found in substitutions, or left intact if - the key was not found. - """ - if isinstance(data, str): - for key, value in substitutions.items(): - data = data.replace('$(%s)' % key, value) - return data - if isinstance(data, list): - return [self._ExpandVariables(v, substitutions) for v in data] - if isinstance(data, dict): - return {k: self._ExpandVariables(data[k], substitutions) for k in data} - return data - -if __name__ == '__main__': - sys.exit(main(sys.argv[1:])) diff --git a/node_modules/kerberos/build/kerberos.target.mk b/node_modules/kerberos/build/kerberos.target.mk deleted file mode 100644 index d963dcd..0000000 --- a/node_modules/kerberos/build/kerberos.target.mk +++ /dev/null @@ -1,201 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := kerberos -DEFS_Debug := \ - '-DNODE_GYP_MODULE_NAME=kerberos' \ - '-DUSING_UV_SHARED=1' \ - '-DUSING_V8_SHARED=1' \ - '-DV8_DEPRECATION_WARNINGS=1' \ - '-DV8_DEPRECATION_WARNINGS' \ - '-DV8_IMMINENT_DEPRECATION_WARNINGS' \ - '-D_DARWIN_USE_64_BIT_INODE=1' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DOPENSSL_NO_PINSHARED' \ - '-DOPENSSL_THREADS' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' \ - '-DV8_ENABLE_CHECKS' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -O0 \ - -gdwarf-2 \ - -mmacosx-version-min=10.7 \ - -arch x86_64 \ - -Wall \ - -Wendif-labels \ - -W \ - -Wno-unused-parameter - -# Flags passed to only C files. -CFLAGS_C_Debug := \ - -fno-strict-aliasing - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -std=gnu++1y \ - -stdlib=libc++ \ - -fno-exceptions \ - -std=c++11 \ - -stdlib=libc++ - -# Flags passed to only ObjC files. -CFLAGS_OBJC_Debug := - -# Flags passed to only ObjC++ files. -CFLAGS_OBJCC_Debug := - -INCS_Debug := \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/include/node \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/src \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/openssl/config \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/openssl/openssl/include \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/uv/include \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/zlib \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/v8/include \ - -I$(srcdir)/../nan - -DEFS_Release := \ - '-DNODE_GYP_MODULE_NAME=kerberos' \ - '-DUSING_UV_SHARED=1' \ - '-DUSING_V8_SHARED=1' \ - '-DV8_DEPRECATION_WARNINGS=1' \ - '-DV8_DEPRECATION_WARNINGS' \ - '-DV8_IMMINENT_DEPRECATION_WARNINGS' \ - '-D_DARWIN_USE_64_BIT_INODE=1' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DOPENSSL_NO_PINSHARED' \ - '-DOPENSSL_THREADS' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -Os \ - -gdwarf-2 \ - -mmacosx-version-min=10.7 \ - -arch x86_64 \ - -Wall \ - -Wendif-labels \ - -W \ - -Wno-unused-parameter - -# Flags passed to only C files. -CFLAGS_C_Release := \ - -fno-strict-aliasing - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -std=gnu++1y \ - -stdlib=libc++ \ - -fno-exceptions \ - -std=c++11 \ - -stdlib=libc++ - -# Flags passed to only ObjC files. -CFLAGS_OBJC_Release := - -# Flags passed to only ObjC++ files. -CFLAGS_OBJCC_Release := - -INCS_Release := \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/include/node \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/src \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/openssl/config \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/openssl/openssl/include \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/uv/include \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/zlib \ - -I/Users/kai/Library/Caches/node-gyp/12.16.3/deps/v8/include \ - -I$(srcdir)/../nan - -OBJS := \ - $(obj).target/$(TARGET)/src/kerberos.o \ - $(obj).target/$(TARGET)/src/unix/base64.o \ - $(obj).target/$(TARGET)/src/unix/kerberos_gss.o \ - $(obj).target/$(TARGET)/src/unix/kerberos_unix.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) -$(OBJS): GYP_OBJCFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE)) -$(OBJS): GYP_OBJCXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -stdlib=libc++ \ - -undefined dynamic_lookup \ - -Wl,-no_pie \ - -Wl,-search_paths_first \ - -mmacosx-version-min=10.7 \ - -arch x86_64 \ - -L$(builddir) \ - -stdlib=libc++ - -LIBTOOLFLAGS_Debug := \ - -stdlib=libc++ \ - -undefined dynamic_lookup \ - -Wl,-no_pie \ - -Wl,-search_paths_first - -LDFLAGS_Release := \ - -stdlib=libc++ \ - -undefined dynamic_lookup \ - -Wl,-no_pie \ - -Wl,-search_paths_first \ - -mmacosx-version-min=10.7 \ - -arch x86_64 \ - -L$(builddir) \ - -stdlib=libc++ - -LIBTOOLFLAGS_Release := \ - -stdlib=libc++ \ - -undefined dynamic_lookup \ - -Wl,-no_pie \ - -Wl,-search_paths_first - -LIBS := \ - -lkrb5 \ - -lgssapi_krb5 - -$(builddir)/kerberos.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(builddir)/kerberos.node: LIBS := $(LIBS) -$(builddir)/kerberos.node: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE)) -$(builddir)/kerberos.node: TOOLSET := $(TOOLSET) -$(builddir)/kerberos.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(builddir)/kerberos.node -# Add target alias -.PHONY: kerberos -kerberos: $(builddir)/kerberos.node - -# Short alias for building this executable. -.PHONY: kerberos.node -kerberos.node: $(builddir)/kerberos.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/kerberos.node - diff --git a/node_modules/kerberos/etc/README.hbs b/node_modules/kerberos/etc/README.hbs deleted file mode 100644 index 424e1ad..0000000 --- a/node_modules/kerberos/etc/README.hbs +++ /dev/null @@ -1,51 +0,0 @@ -Kerberos -======== -[![Build Status](https://travis-ci.org/mongodb-js/kerberos.svg?branch=master)](https://travis-ci.org/mongodb-js/kerberos) - -The `kerberos` package is a C++ extension for Node.js that provides cross-platform support for kerberos authentication using GSSAPI on linux/osx, and SSPI on windows. Much of the code in this module is adapted from [ccs-kerberos](https://github.com/apple/ccs-pykerberos) and [winkerberos](https://github.com/mongodb-labs/winkerberos). - -### Requirements - -**Linux** -- `python` v2.7 -- `make` -- A proper C/C++ compiler toolchain, like [GCC](https://gcc.gnu.org/) -- Distribution-specific kerberos packages (e.g. `krb5-dev` on Ubuntu) - -**macOS** -- `Xcode Command Line Tools`: Can be installed with `xcode-select --install` -- Distribution-specific kerberos packages (e.g. `krb5` on Homebrew) - -**Windows** -- **Option 1:** Install all the required tools and configurations using Microsoft's [windows-build-tools](https://github.com/felixrieseberg/windows-build-tools) by running `npm install -g windows-build-tools` from an elevated PowerShell (run as Administrator). -- **Option 2:** Install dependencies and configuration manually - 1. Visual C++ Build Environment: - * **Option 1:** Install [Visual C++ Build Tools](http://go.microsoft.com/fwlink/?LinkId=691126) using the *Default Install* option. - * **Option 2:** Install [Visual Studio 2015](https://www.visualstudio.com/products/visual-studio-community-vs) (or modify an existing installation) and select *Common Tools for Visual C++* during setup. - - > :bulb: [Windows Vista / 7 only] requires [.NET Framework 4.5.1](http://www.microsoft.com/en-us/download/details.aspx?id=40773) - - 2. Install [Python 2.7](https://www.python.org/downloads/) or [Miniconda 2.7](http://conda.pydata.org/miniconda.html) (`v3.x.x` is not supported), and run `npm config set python python2.7` - 3. Launch cmd, `npm config set msvs_version 2015` - -### Installation - -Now you can install `kerberos` with the following: - -```bash -npm install kerberos -``` - -### Testing - -Run the test suite using: - -```bash -npm test -``` - -NOTE: The test suite requires an active kerberos deployment, see `test/scripts/travis.sh` to better understand these requirements. - -# Documentation - -{{>main}} diff --git a/node_modules/kerberos/index.js b/node_modules/kerberos/index.js deleted file mode 100644 index 7ebfcc5..0000000 --- a/node_modules/kerberos/index.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -const kerberos = require('./lib/kerberos'); - -// Get the Kerberos library -module.exports = kerberos; - -// Support legacy versions of the mongodb driver which expect this export -module.exports.Kerberos = kerberos; - -module.exports.version = require('./package.json').version; - -// Set up the auth processes -module.exports.processes = { - MongoAuthProcess: require('./lib/auth_processes/mongodb').MongoAuthProcess -}; diff --git a/node_modules/kerberos/lib/auth_processes/mongodb.js b/node_modules/kerberos/lib/auth_processes/mongodb.js deleted file mode 100644 index ff14b9e..0000000 --- a/node_modules/kerberos/lib/auth_processes/mongodb.js +++ /dev/null @@ -1,151 +0,0 @@ -'use strict'; -const dns = require('dns'); -const kerberos = require('../kerberos'); - -class MongoAuthProcess { - constructor(host, port, serviceName, options) { - options = options || {}; - this.host = host; - this.port = port; - - // Set up service name - this.serviceName = serviceName || options.gssapiServiceName || 'mongodb'; - - // Options - this.canonicalizeHostName = - typeof options.gssapiCanonicalizeHostName === 'boolean' - ? options.gssapiCanonicalizeHostName - : false; - - // Set up first transition - this._transition = firstTransition(this); - - // Number of retries - this.retries = 10; - } - - init(username, password, callback) { - const self = this; - this.username = username; - this.password = password; - - // Canonicialize host name if needed - function performGssapiCanonicalizeHostName(canonicalizeHostName, host, callback) { - if (!canonicalizeHostName) return callback(); - - // Attempt to resolve the host name - dns.resolveCname(host, (err, r) => { - if (err) return callback(err); - - // Get the first resolve host id - if (Array.isArray(r) && r.length > 0) { - self.host = r[0]; - } - - callback(); - }); - } - - // Canonicialize host name if needed - performGssapiCanonicalizeHostName(this.canonicalizeHostName, this.host, err => { - if (err) return callback(err); - - const initOptions = {}; - if (password != null) { - Object.assign(initOptions, { user: username, password }); - } - - const service = - process.platform === 'win32' - ? `${this.serviceName}/${this.host}` - : `${this.serviceName}@${this.host}`; - - kerberos.initializeClient(service, initOptions, (err, client) => { - if (err) return callback(err, null); - - self.client = client; - callback(null, client); - }); - }); - } - - transition(payload, callback) { - if (this._transition == null) { - return callback(new Error('Transition finished')); - } - - this._transition(payload, callback); - } -} - -function firstTransition(auth) { - return (payload, callback) => { - auth.client.step('', (err, response) => { - if (err) return callback(err); - - // Set up the next step - auth._transition = secondTransition(auth); - - // Return the payload - callback(null, response); - }); - }; -} - -function secondTransition(auth) { - return (payload, callback) => { - auth.client.step(payload, (err, response) => { - if (err && auth.retries === 0) return callback(err); - - // Attempt to re-establish a context - if (err) { - // Adjust the number of retries - auth.retries = auth.retries - 1; - - // Call same step again - return auth.transition(payload, callback); - } - - // Set up the next step - auth._transition = thirdTransition(auth); - - // Return the payload - callback(null, response || ''); - }); - }; -} - -function thirdTransition(auth) { - return (payload, callback) => { - // GSS Client Unwrap - auth.client.unwrap(payload, (err, response) => { - if (err) return callback(err, false); - - // Wrap the response - auth.client.wrap(response, { user: auth.username }, (err, wrapped) => { - if (err) return callback(err, false); - - // Set up the next step - auth._transition = fourthTransition(auth); - - // Return the payload - callback(null, wrapped); - }); - }); - }; -} - -function fourthTransition(auth) { - return (payload, callback) => { - // Set the transition to null - auth._transition = null; - - // Callback with valid authentication - callback(null, true); - }; -} - -// Set the process -module.exports = { - MongoAuthProcess -}; diff --git a/node_modules/kerberos/lib/kerberos.js b/node_modules/kerberos/lib/kerberos.js deleted file mode 100644 index 09f8425..0000000 --- a/node_modules/kerberos/lib/kerberos.js +++ /dev/null @@ -1,203 +0,0 @@ -'use strict'; - -const kerberos = require('bindings')('kerberos'); -const KerberosClient = kerberos.KerberosClient; -const KerberosServer = kerberos.KerberosServer; -const defineOperation = require('./util').defineOperation; - -// GSS Flags -const GSS_C_DELEG_FLAG = 1; -const GSS_C_MUTUAL_FLAG = 2; -const GSS_C_REPLAY_FLAG = 4; -const GSS_C_SEQUENCE_FLAG = 8; -const GSS_C_CONF_FLAG = 16; -const GSS_C_INTEG_FLAG = 32; -const GSS_C_ANON_FLAG = 64; -const GSS_C_PROT_READY_FLAG = 128; -const GSS_C_TRANS_FLAG = 256; - -// GSS_OID -const GSS_C_NO_OID = 0; -const GSS_MECH_OID_KRB5 = 9; -const GSS_MECH_OID_SPNEGO = 6; - -/** - * @class KerberosClient - * - * @property {string} username The username used for authentication - * @property {string} response The last response received during authentication steps - * @property {string} responseConf Indicates whether confidentiality was applied or not (GSSAPI only) - * @property {boolean} contextComplete Indicates that authentication has successfully completed or not - */ - -/** - * Processes a single kerberos client-side step using the supplied server challenge. - * - * @kind function - * @memberof KerberosClient - * @param {string} challenge A string containing the base64-encoded server data (which may be empty for the first step) - * @param {function} [callback] - * @return {Promise} returns Promise if no callback passed - */ -KerberosClient.prototype.step = defineOperation(KerberosClient.prototype.step, [ - { name: 'challenge', type: 'string' }, - { name: 'callback', type: 'function', required: false } -]); - -/** - * Perform the client side kerberos wrap step. - * - * @kind function - * @memberof KerberosClient - * @param {string} challenge The response returned after calling `unwrap` - * @param {object} [options] Optional settings - * @param {string} [options.user] The user to authorize - * @param {function} [callback] - * @return {Promise} returns Promise if no callback passed - */ -KerberosClient.prototype.wrap = defineOperation(KerberosClient.prototype.wrap, [ - { name: 'challenge', type: 'string' }, - { name: 'options', type: 'object' }, - { name: 'callback', type: 'function', required: false } -]); - -/** - * Perform the client side kerberos unwrap step - * - * @kind function - * @memberof KerberosClient - * @param {string} challenge A string containing the base64-encoded server data - * @param {function} [callback] - * @return {Promise} returns Promise if no callback passed - */ -KerberosClient.prototype.unwrap = defineOperation(KerberosClient.prototype.unwrap, [ - { name: 'challenge', type: 'string' }, - { name: 'callback', type: 'function', required: false } -]); - -/** - * @class KerberosServer - * - * @property {string} username The username used for authentication - * @property {string} response The last response received during authentication steps - * @property {string} targetName The target used for authentication - * @property {boolean} contextComplete Indicates that authentication has successfully completed or not - */ - -/** - * Processes a single kerberos server-side step using the supplied client data. - * - * @kind function - * @memberof KerberosServer - * @param {string} challenge A string containing the base64-encoded client data - * @param {function} [callback] - * @return {Promise} returns Promise if no callback passed - */ -KerberosServer.prototype.step = defineOperation(KerberosServer.prototype.step, [ - { name: 'challenge', type: 'string' }, - { name: 'callback', type: 'function', required: false } -]); - -/** - * This function provides a simple way to verify that a user name and password - * match those normally used for Kerberos authentication. - * It does this by checking that the supplied user name and password can be - * used to get a ticket for the supplied service. - * If the user name does not contain a realm, then the default realm supplied - * is used. - * - * For this to work properly the Kerberos must be configured properly on this - * machine. - * That will likely mean ensuring that the edu.mit.Kerberos preference file - * has the correct realms and KDCs listed. - * - * IMPORTANT: This method is vulnerable to KDC spoofing attacks and it should - * only be used for testing. Do not use this in any production system - your - * security could be compromised if you do. - * - * @kind function - * @param {string} username The Kerberos user name. If no realm is supplied, then the `defaultRealm` will be used. - * @param {string} password The password for the user. - * @param {string} service The Kerberos service to check access for. - * @param {string} [defaultRealm] The default realm to use if one is not supplied in the user argument. - * @param {function} [callback] - * @return {Promise} returns Promise if no callback passed - */ -const checkPassword = defineOperation(kerberos.checkPassword, [ - { name: 'username', type: 'string' }, - { name: 'password', type: 'string' }, - { name: 'service', type: 'string' }, - { name: 'defaultRealm', type: 'string', required: false }, - { name: 'callback', type: 'function', required: false } -]); - -/** - * This function returns the service principal for the server given a service type and hostname. - * - * Details are looked up via the `/etc/keytab` file. - * - * @kind function - * @param {string} service The Kerberos service type for the server. - * @param {string} hostname The hostname of the server. - * @param {function} [callback] - * @return {Promise} returns Promise if no callback passed - */ -const principalDetails = defineOperation(kerberos.principalDetails, [ - { name: 'service', type: 'string' }, - { name: 'hostname', type: 'string' }, - { name: 'callback', type: 'function', required: false } -]); - -/** - * Initializes a context for client-side authentication with the given service principal. - * - * @kind function - * @param {string} service A string containing the service principal in the form 'type@fqdn' (e.g. 'imap@mail.apple.com'). - * @param {object} [options] Optional settings - * @param {string} [options.principal] Optional string containing the client principal in the form 'user@realm' (e.g. 'jdoe@example.com'). - * @param {number} [options.gssFlags] Optional integer used to set GSS flags. (e.g. GSS_C_DELEG_FLAG|GSS_C_MUTUAL_FLAG|GSS_C_SEQUENCE_FLAG will allow for forwarding credentials to the remote host) - * @param {number} [options.mechOID] Optional GSS mech OID. Defaults to None (GSS_C_NO_OID). Other possible values are `GSS_MECH_OID_KRB5`, `GSS_MECH_OID_SPNEGO`. - * @param {function} [callback] - * @return {Promise} returns Promise if no callback passed - */ -const initializeClient = defineOperation(kerberos.initializeClient, [ - { name: 'service', type: 'string' }, - { name: 'options', type: 'object', default: { mechOID: GSS_C_NO_OID } }, - { name: 'callback', type: 'function', required: false } -]); - -/** - * Initializes a context for server-side authentication with the given service principal. - * - * @kind function - * @param {string} service A string containing the service principal in the form 'type@fqdn' (e.g. 'imap@mail.apple.com'). - * @param {function} [callback] - * @return {Promise} returns Promise if no callback passed - */ -const initializeServer = defineOperation(kerberos.initializeServer, [ - { name: 'service', type: 'string' }, - { name: 'callback', type: 'function', required: false } -]); - -module.exports = { - initializeClient, - initializeServer, - principalDetails, - checkPassword, - - // gss flags - GSS_C_DELEG_FLAG, - GSS_C_MUTUAL_FLAG, - GSS_C_REPLAY_FLAG, - GSS_C_SEQUENCE_FLAG, - GSS_C_CONF_FLAG, - GSS_C_INTEG_FLAG, - GSS_C_ANON_FLAG, - GSS_C_PROT_READY_FLAG, - GSS_C_TRANS_FLAG, - GSS_C_NO_OID, - - // mechanism OIDs - GSS_MECH_OID_KRB5, - GSS_MECH_OID_SPNEGO -}; diff --git a/node_modules/kerberos/lib/util.js b/node_modules/kerberos/lib/util.js deleted file mode 100644 index 27bdba0..0000000 --- a/node_modules/kerberos/lib/util.js +++ /dev/null @@ -1,80 +0,0 @@ -'use strict'; - -function validateParameter(parameter, specs, specIndex) { - const spec = specs[specIndex]; - if (parameter == null && spec.required === false) { - return; - } - - if (parameter == null) { - throw new TypeError(`Required parameter \`${spec.name}\` missing`); - } - - const paramType = typeof parameter; - if (spec.type && paramType !== spec.type) { - if (spec.required === false) { - if (specs.slice(specIndex).some(def => def.type === paramType)) { - return false; - } - } - - throw new TypeError( - `Invalid type for parameter \`${spec.name}\`, expected \`${ - spec.type - }\` but found \`${typeof parameter}\`` - ); - } - - return true; -} - -/** - * Monkey-patches an existing method to support parameter validation, as well - * as adding support for returning Promises if callbacks are not provided. - * - * @private - * @param {function} fn the function to override - * @param {Array} paramDefs the definitions of each parameter to the function - */ -function defineOperation(fn, paramDefs) { - return function() { - const args = Array.prototype.slice.call(arguments); - const params = []; - for (let i = 0, argIdx = 0; i < paramDefs.length; ++i, ++argIdx) { - const def = paramDefs[i]; - let arg = args[argIdx]; - - if (def.hasOwnProperty('default') && arg == null) arg = def.default; - if (def.type === 'object' && def.default != null) { - arg = Object.assign({}, def.default, arg); - } - - // special case to allow `options` to be optional - if (def.name === 'options' && (typeof arg === 'function' || arg == null)) { - arg = {}; - } - - if (validateParameter(arg, paramDefs, i)) { - params.push(arg); - } else { - argIdx--; - } - } - - const callback = arguments[arguments.length - 1]; - if (typeof callback !== 'function') { - return new Promise((resolve, reject) => { - params.push((err, response) => { - if (err) return reject(err); - resolve(response); - }); - - fn.apply(this, params); - }); - } - - fn.apply(this, params); - }; -} - -module.exports = { defineOperation, validateParameter }; diff --git a/node_modules/kerberos/package.json b/node_modules/kerberos/package.json deleted file mode 100644 index 3eeb6f1..0000000 --- a/node_modules/kerberos/package.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "_from": "kerberos", - "_id": "kerberos@1.1.3", - "_inBundle": false, - "_integrity": "sha512-R6LdXnkSTALLnrKaByYdIc+eRNhDf+ezA83BeqHiCcKhKE9R6m1PBD579YuX9KANPAakhWHEu/u6H7ZQBc/+Wg==", - "_location": "/kerberos", - "_phantomChildren": {}, - "_requested": { - "type": "tag", - "registry": true, - "raw": "kerberos", - "name": "kerberos", - "escapedName": "kerberos", - "rawSpec": "", - "saveSpec": null, - "fetchSpec": "latest" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/kerberos/-/kerberos-1.1.3.tgz", - "_shasum": "74c5620d09289e4a53beddc2d9a93eccfebd964d", - "_spec": "kerberos", - "_where": "/Users/kai/Desktop/node-course/dbproject", - "author": { - "name": "Matt Broadstone", - "email": "mbroadst@gmail.com" - }, - "bugs": { - "url": "https://github.com/mongodb-js/kerberos/issues" - }, - "bundleDependencies": false, - "dependencies": { - "bindings": "^1.5.0", - "nan": "^2.14.0", - "prebuild-install": "^5.3.0" - }, - "deprecated": false, - "description": "Kerberos library for Node.js", - "devDependencies": { - "chai": "^4.2.0", - "chai-string": "^1.5.0", - "clang-format": "^1.2.4", - "dmd-clear": "^0.1.2", - "eslint": "^5.16.0", - "eslint-plugin-prettier": "^2.6.2", - "jsdoc-to-markdown": "^4.0.1", - "mocha": "^5.2.0", - "mongodb": "^3.2.5", - "prebuild": "^7.6.2", - "prebuild-ci": "^2.2.3", - "prettier": "^1.17.1", - "request": "^2.88.0", - "segfault-handler": "^1.2.0", - "standard-version": "^4.4.0" - }, - "gitHead": "035be2e4619d7f3d7ea5103da1f60a6045ef8d7c", - "homepage": "https://github.com/mongodb-js/kerberos#readme", - "keywords": [ - "kerberos", - "security", - "authentication" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "kerberos", - "repository": { - "type": "git", - "url": "git+https://github.com/mongodb-js/kerberos.git" - }, - "scripts": { - "docs": "jsdoc2md --template etc/README.hbs --plugin dmd-clear --files lib/kerberos.js > README.md", - "format-cxx": "git-clang-format", - "format-js": "prettier --print-width 100 --tab-width 2 --single-quote --write index.js 'test/**/*.js' 'lib/**/*.js'", - "install": "prebuild-install || node-gyp rebuild", - "lint": "eslint index.js lib test", - "prebuild": "prebuild --all --strip --verbose", - "precommit": "check-clang-format", - "rebuild": "prebuild --compile", - "release": "standard-version -i HISTORY.md", - "test": "mocha ./test && prebuild-ci" - }, - "version": "1.1.3" -} diff --git a/node_modules/kerberos/src/kerberos.cc b/node_modules/kerberos/src/kerberos.cc deleted file mode 100644 index cbbb57b..0000000 --- a/node_modules/kerberos/src/kerberos.cc +++ /dev/null @@ -1,181 +0,0 @@ -#include "kerberos.h" -#include "kerberos_worker.h" - -/// KerberosClient -Nan::Persistent KerberosClient::constructor; -NAN_MODULE_INIT(KerberosClient::Init) { - v8::Local tpl = Nan::New(); - tpl->SetClassName(Nan::New("KerberosClient").ToLocalChecked()); - Nan::SetPrototypeMethod(tpl, "step", Step); - Nan::SetPrototypeMethod(tpl, "wrap", WrapData); - Nan::SetPrototypeMethod(tpl, "unwrap", UnwrapData); - - v8::Local itpl = tpl->InstanceTemplate(); - itpl->SetInternalFieldCount(1); - - Nan::SetAccessor(itpl, Nan::New("username").ToLocalChecked(), KerberosClient::UserNameGetter); - Nan::SetAccessor(itpl, Nan::New("response").ToLocalChecked(), KerberosClient::ResponseGetter); - Nan::SetAccessor( - itpl, Nan::New("responseConf").ToLocalChecked(), KerberosClient::ResponseConfGetter); - Nan::SetAccessor( - itpl, Nan::New("contextComplete").ToLocalChecked(), KerberosClient::ContextCompleteGetter); - - constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked()); - Nan::Set(target, - Nan::New("KerberosClient").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); -} - -v8::Local KerberosClient::NewInstance(krb_client_state* state) { - Nan::EscapableHandleScope scope; - v8::Local ctor = Nan::New(KerberosClient::constructor); - v8::Local object = Nan::NewInstance(ctor).ToLocalChecked(); - KerberosClient* class_instance = new KerberosClient(state); - class_instance->Wrap(object); - return scope.Escape(object); -} - -KerberosClient::KerberosClient(krb_client_state* state) : _state(state) {} - -krb_client_state* KerberosClient::state() const { - return _state; -} - -NAN_GETTER(KerberosClient::UserNameGetter) { - KerberosClient* client = Nan::ObjectWrap::Unwrap(info.This()); - (client->state()->username == NULL) - ? info.GetReturnValue().Set(Nan::Null()) - : info.GetReturnValue().Set(Nan::New(client->state()->username).ToLocalChecked()); -} - -NAN_GETTER(KerberosClient::ResponseGetter) { - KerberosClient* client = Nan::ObjectWrap::Unwrap(info.This()); - (client->state()->response == NULL) - ? info.GetReturnValue().Set(Nan::Null()) - : info.GetReturnValue().Set(Nan::New(client->state()->response).ToLocalChecked()); -} - -NAN_GETTER(KerberosClient::ResponseConfGetter) { - KerberosClient* client = Nan::ObjectWrap::Unwrap(info.This()); - info.GetReturnValue().Set(Nan::New(client->state()->responseConf)); -} - -NAN_GETTER(KerberosClient::ContextCompleteGetter) { - KerberosClient* client = Nan::ObjectWrap::Unwrap(info.This()); - info.GetReturnValue().Set(Nan::New(client->state()->context_complete)); -} - -/// KerberosServer -Nan::Persistent KerberosServer::constructor; -NAN_MODULE_INIT(KerberosServer::Init) { - v8::Local tpl = Nan::New(); - tpl->SetClassName(Nan::New("KerberosServer").ToLocalChecked()); - Nan::SetPrototypeMethod(tpl, "step", Step); - - v8::Local itpl = tpl->InstanceTemplate(); - itpl->SetInternalFieldCount(1); - - Nan::SetAccessor(itpl, Nan::New("username").ToLocalChecked(), KerberosServer::UserNameGetter); - Nan::SetAccessor(itpl, Nan::New("response").ToLocalChecked(), KerberosServer::ResponseGetter); - Nan::SetAccessor( - itpl, Nan::New("targetName").ToLocalChecked(), KerberosServer::TargetNameGetter); - Nan::SetAccessor( - itpl, Nan::New("contextComplete").ToLocalChecked(), KerberosServer::ContextCompleteGetter); - - constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked()); - Nan::Set(target, - Nan::New("KerberosServer").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); -} - -v8::Local KerberosServer::NewInstance(krb_server_state* state) { - Nan::EscapableHandleScope scope; - v8::Local ctor = Nan::New(KerberosServer::constructor); - v8::Local object = Nan::NewInstance(ctor).ToLocalChecked(); - KerberosServer* class_instance = new KerberosServer(state); - class_instance->Wrap(object); - return scope.Escape(object); -} - -KerberosServer::KerberosServer(krb_server_state* state) : _state(state) {} - -krb_server_state* KerberosServer::state() const { - return _state; -} - -NAN_GETTER(KerberosServer::UserNameGetter) { - KerberosServer* server = Nan::ObjectWrap::Unwrap(info.This()); - (server->_state->username == NULL) - ? info.GetReturnValue().Set(Nan::Null()) - : info.GetReturnValue().Set(Nan::New((char*)server->_state->username).ToLocalChecked()); -} - -NAN_GETTER(KerberosServer::ResponseGetter) { - KerberosServer* server = Nan::ObjectWrap::Unwrap(info.This()); - (server->_state->response == NULL) - ? info.GetReturnValue().Set(Nan::Null()) - : info.GetReturnValue().Set(Nan::New((char*)server->_state->response).ToLocalChecked()); -} - -NAN_GETTER(KerberosServer::TargetNameGetter) { - KerberosServer* server = Nan::ObjectWrap::Unwrap(info.This()); - (server->_state->targetname == NULL) - ? info.GetReturnValue().Set(Nan::Null()) - : info.GetReturnValue().Set(Nan::New((char*)server->_state->targetname).ToLocalChecked()); -} - -NAN_GETTER(KerberosServer::ContextCompleteGetter) { - KerberosServer* server = Nan::ObjectWrap::Unwrap(info.This()); - info.GetReturnValue().Set(Nan::New(server->_state->context_complete)); -} - -NAN_METHOD(TestMethod) { - std::string string(*Nan::Utf8String(info[0])); - bool shouldError = Nan::To(info[1]).FromJust(); - - std::string optionalString; - Nan::Callback* callback; - if (info[2]->IsFunction()) { - callback = new Nan::Callback(Nan::To(info[2]).ToLocalChecked()); - } else { - optionalString = *Nan::Utf8String(info[2]); - callback = new Nan::Callback(Nan::To(info[3]).ToLocalChecked()); - } - - KerberosWorker::Run(callback, "kerberos:TestMethod", [=](KerberosWorker::SetOnFinishedHandler onFinished) { - return onFinished([=](KerberosWorker* worker) { - Nan::HandleScope scope; - if (shouldError) { - v8::Local argv[] = {Nan::Error("an error occurred"), Nan::Null()}; - worker->Call(2, argv); - } else { - v8::Local argv[] = {Nan::Null(), Nan::New(optionalString.c_str()).ToLocalChecked()}; - worker->Call(2, argv); - } - }); - }); -} - -NAN_MODULE_INIT(Init) { - // Custom types - KerberosClient::Init(target); - KerberosServer::Init(target); - - Nan::Set(target, - Nan::New("initializeClient").ToLocalChecked(), - Nan::GetFunction(Nan::New(InitializeClient)).ToLocalChecked()); - Nan::Set(target, - Nan::New("initializeServer").ToLocalChecked(), - Nan::GetFunction(Nan::New(InitializeServer)).ToLocalChecked()); - Nan::Set(target, - Nan::New("principalDetails").ToLocalChecked(), - Nan::GetFunction(Nan::New(PrincipalDetails)).ToLocalChecked()); - Nan::Set(target, - Nan::New("checkPassword").ToLocalChecked(), - Nan::GetFunction(Nan::New(CheckPassword)).ToLocalChecked()); - Nan::Set(target, - Nan::New("_testMethod").ToLocalChecked(), - Nan::GetFunction(Nan::New(TestMethod)).ToLocalChecked()); -} - -NODE_MODULE(kerberos, Init) diff --git a/node_modules/kerberos/src/kerberos.h b/node_modules/kerberos/src/kerberos.h deleted file mode 100644 index d73eb3f..0000000 --- a/node_modules/kerberos/src/kerberos.h +++ /dev/null @@ -1,65 +0,0 @@ -#ifndef KERBEROS_NATIVE_EXTENSION_H -#define KERBEROS_NATIVE_EXTENSION_H - -#include -#include "kerberos_common.h" - -class KerberosServer : public Nan::ObjectWrap { - public: - static NAN_MODULE_INIT(Init); - static v8::Local NewInstance(krb_server_state* state); - - krb_server_state* state() const; - - private: - static Nan::Persistent constructor; - - static NAN_GETTER(UserNameGetter); - static NAN_GETTER(ResponseGetter); - static NAN_GETTER(TargetNameGetter); - static NAN_GETTER(ContextCompleteGetter); - - static NAN_METHOD(Step); - - private: - explicit KerberosServer(krb_server_state* server_state); - ~KerberosServer(); - - krb_server_state* _state; -}; - -class KerberosClient : public Nan::ObjectWrap { - public: - static NAN_MODULE_INIT(Init); - static v8::Local NewInstance(krb_client_state* state); - - krb_client_state* state() const; - - private: - static Nan::Persistent constructor; - - static NAN_GETTER(UserNameGetter); - static NAN_GETTER(ResponseGetter); - static NAN_GETTER(ResponseConfGetter); - static NAN_GETTER(ContextCompleteGetter); - - static NAN_METHOD(Step); - static NAN_METHOD(UnwrapData); - static NAN_METHOD(WrapData); - - private: - explicit KerberosClient(krb_client_state* client_state); - ~KerberosClient(); - - krb_client_state* _state; -}; - -NAN_METHOD(PrincipalDetails); -NAN_METHOD(InitializeClient); -NAN_METHOD(InitializeServer); -NAN_METHOD(CheckPassword); - -// NOTE: explicitly used for unit testing `defineOperation`, not meant to be exported -NAN_METHOD(TestMethod); - -#endif // KERBEROS_NATIVE_EXTENSION_H diff --git a/node_modules/kerberos/src/kerberos_common.h b/node_modules/kerberos/src/kerberos_common.h deleted file mode 100644 index fbd9472..0000000 --- a/node_modules/kerberos/src/kerberos_common.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef COMMON_H -#define COMMON_H - -#include - -#if defined(__linux__) || defined(__APPLE__) -#include "unix/kerberos_gss.h" - -typedef gss_client_state krb_client_state; -typedef gss_server_state krb_server_state; -typedef gss_result krb_result; -#else -#include "win32/kerberos_sspi.h" - -typedef sspi_client_state krb_client_state; -typedef sspi_server_state krb_server_state; -typedef sspi_result krb_result; -#endif - -// Provide a default custom delter for the `gss_result` type -inline void ResultDeleter(krb_result* result) { - free(result); -} - -// Useful methods for optional value handling -NAN_INLINE std::string StringOptionValue(v8::Local options, const char* _key) { - Nan::HandleScope scope; - v8::Local key = Nan::New(_key).ToLocalChecked(); - if (options.IsEmpty() || !Nan::Has(options, key).FromMaybe(false)) { - return std::string(); - } - - v8::Local value = Nan::Get(options, key).ToLocalChecked(); - if (!value->IsString()) { - return std::string(); - } - - return std::string(*(Nan::Utf8String(value))); -} - -NAN_INLINE uint32_t UInt32OptionValue(v8::Local options, - const char* _key, - uint32_t def) { - Nan::HandleScope scope; - v8::Local key = Nan::New(_key).ToLocalChecked(); - if (options.IsEmpty() || !Nan::Has(options, key).FromMaybe(false)) { - return def; - } - - v8::Local value = Nan::Get(options, key).ToLocalChecked(); - if (!value->IsNumber()) { - return def; - } - - return value->Uint32Value(Nan::GetCurrentContext()).FromJust(); -} - -#endif diff --git a/node_modules/kerberos/src/kerberos_worker.h b/node_modules/kerberos/src/kerberos_worker.h deleted file mode 100644 index 4b2c9dd..0000000 --- a/node_modules/kerberos/src/kerberos_worker.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef ASYNC_WORKER_H -#define ASYNC_WORKER_H - -#include -#include - -class KerberosWorker : public Nan::AsyncWorker { - public: - typedef std::function OnFinishedHandler; - typedef std::function SetOnFinishedHandler; - typedef std::function ExecuteHandler; - - explicit KerberosWorker(Nan::Callback *callback, const char* resource_name, ExecuteHandler handler) - : Nan::AsyncWorker(callback, resource_name), execute_handler(handler) {} - - template - void Call(T... t) { - callback->Call(t..., async_resource); - } - - virtual void Execute() { - execute_handler([=] (OnFinishedHandler handler) { - on_finished_handler = handler; - }); - } - - static void Run(Nan::Callback *callback, const char* resource_name, ExecuteHandler handler) { - Nan::TryCatch tryCatch; - if (tryCatch.HasCaught()) { - tryCatch.ReThrow(); - return; // don't proceed in case there were any previous errors - } - - auto worker = new KerberosWorker(callback, resource_name, handler); - Nan::AsyncQueueWorker(worker); - } - - protected: - void HandleOKCallback() { - on_finished_handler(this); - } - - private: - ExecuteHandler execute_handler; - OnFinishedHandler on_finished_handler; -}; - -#endif // ASYNC_WORKER_H diff --git a/node_modules/kerberos/src/unix/base64.cc b/node_modules/kerberos/src/unix/base64.cc deleted file mode 100644 index 3deb8bb..0000000 --- a/node_modules/kerberos/src/unix/base64.cc +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright (c) 2006-2018 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -#include "base64.h" - -#include -#include - -// base64 tables -static char basis_64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, - -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, - 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, - 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char* base64_encode(const unsigned char* value, size_t vlen) { - char* result = (char*)malloc((vlen * 4) / 3 + 5); - if (result == NULL) { - return NULL; - } - char* out = result; - while (vlen >= 3) { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) { - *out++ = basis_64[value[0] >> 2]; - unsigned char oval = (value[0] << 4) & 0x30; - if (vlen > 1) - oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char* base64_decode(const char* value, size_t* rlen) { - *rlen = 0; - int c1, c2, c3, c4; - - size_t vlen = strlen(value); - unsigned char* result = (unsigned char*)malloc((vlen * 3) / 4 + 1); - if (result == NULL) { - return NULL; - } - unsigned char* out = result; - - while (1) { - if (value[0] == 0) { - return result; - } - c1 = value[0]; - if (CHAR64(c1) == -1) { - goto base64_decode_error; - ; - } - c2 = value[1]; - if (CHAR64(c2) == -1) { - goto base64_decode_error; - ; - } - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) { - goto base64_decode_error; - ; - } - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) { - goto base64_decode_error; - ; - } - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - - if (c3 != '=') { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - - if (c4 != '=') { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - - return result; -} diff --git a/node_modules/kerberos/src/unix/base64.h b/node_modules/kerberos/src/unix/base64.h deleted file mode 100644 index 1cd548c..0000000 --- a/node_modules/kerberos/src/unix/base64.h +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ -#ifndef BASE64_H -#define BASE64_H - -#include - -char* base64_encode(const unsigned char* value, size_t vlen); -unsigned char* base64_decode(const char* value, size_t* rlen); - -#endif diff --git a/node_modules/kerberos/src/unix/kerberos_gss.cc b/node_modules/kerberos/src/unix/kerberos_gss.cc deleted file mode 100644 index 5cbfed5..0000000 --- a/node_modules/kerberos/src/unix/kerberos_gss.cc +++ /dev/null @@ -1,786 +0,0 @@ -/** - * Copyright (c) 2006-2013 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -#include "kerberos_gss.h" - -#include "base64.h" - -#include -#include -#include -#include - -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -#endif - -static gss_result* gss_success_result(int ret); -static gss_result* gss_error_result(OM_uint32 err_maj, OM_uint32 err_min); -static gss_result* gss_error_result_with_message(const char* message); -static gss_result* gss_error_result_with_message_and_code(const char* mesage, int code); - -gss_client_state* gss_client_state_new() { - gss_client_state* state = (gss_client_state*)malloc(sizeof(gss_client_state)); - state->username = NULL; - state->response = NULL; - state->responseConf = 0; - state->context_complete = false; - - return state; -} - -gss_server_state* gss_server_state_new() { - gss_server_state* state = (gss_server_state*)malloc(sizeof(gss_server_state)); - state->username = NULL; - state->response = NULL; - state->targetname = NULL; - state->context_complete = false; - - return state; -} - -gss_result* server_principal_details(const char* service, const char* hostname) { - char match[1024]; - size_t match_len = 0; - char* details = NULL; - gss_result* result = NULL; - - int code; - krb5_context kcontext; - krb5_keytab kt = NULL; - krb5_kt_cursor cursor = NULL; - krb5_keytab_entry entry; - char* pname = NULL; - - // Generate the principal prefix we want to match - snprintf(match, 1024, "%s/%s@", service, hostname); - match_len = strlen(match); - - code = krb5_init_context(&kcontext); - if (code) { - result = - gss_error_result_with_message_and_code("Cannot initialize Kerberos5 context", code); - return result; - } - - if ((code = krb5_kt_default(kcontext, &kt))) { - result = gss_error_result_with_message_and_code("Cannot get default keytab", code); - goto end; - } - - if ((code = krb5_kt_start_seq_get(kcontext, kt, &cursor))) { - result = - gss_error_result_with_message_and_code("Cannot get sequence cursor from keytab", code); - goto end; - } - - while ((code = krb5_kt_next_entry(kcontext, kt, &entry, &cursor)) == 0) { - if ((code = krb5_unparse_name(kcontext, entry.principal, &pname))) { - result = gss_error_result_with_message_and_code( - "Cannot parse principal name from keytab", code); - goto end; - } - - if (strncmp(pname, match, match_len) == 0) { - details = (char*)malloc(strlen(pname) + 1); - strcpy(details, pname); - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - break; - } - - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - } - - if (details == NULL) { - result = gss_error_result_with_message_and_code("Principal not found in keytab", -1); - } else { - result = gss_success_result(AUTH_GSS_COMPLETE); - result->data = details; - } -end: - if (cursor) - krb5_kt_end_seq_get(kcontext, kt, &cursor); - if (kt) - krb5_kt_close(kcontext, kt); - krb5_free_context(kcontext); - - return result; -} - -gss_result* authenticate_gss_client_init(const char* service, - const char* principal, - long int gss_flags, - gss_server_state* delegatestate, - gss_OID mech_oid, - gss_client_state* state) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc principal_token = GSS_C_EMPTY_BUFFER; - gss_result* ret = NULL; - - state->server_name = GSS_C_NO_NAME; - state->mech_oid = mech_oid; - state->context = GSS_C_NO_CONTEXT; - state->gss_flags = gss_flags; - state->client_creds = GSS_C_NO_CREDENTIAL; - state->username = NULL; - state->response = NULL; - - // Import server name first - name_token.length = strlen(service); - name_token.value = (char*)service; - - maj_stat = - gss_import_name(&min_stat, &name_token, gss_krb5_nt_service_name, &state->server_name); - - if (GSS_ERROR(maj_stat)) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - - // Use the delegate credentials if they exist - if (delegatestate && delegatestate->client_creds != GSS_C_NO_CREDENTIAL) { - state->client_creds = delegatestate->client_creds; - } - // If available use the principal to extract its associated credentials - else if (principal && *principal) { - gss_name_t name; - principal_token.length = strlen(principal); - principal_token.value = (char*)principal; - - maj_stat = gss_import_name(&min_stat, &principal_token, GSS_C_NT_USER_NAME, &name); - if (GSS_ERROR(maj_stat)) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - - maj_stat = gss_acquire_cred(&min_stat, - name, - GSS_C_INDEFINITE, - GSS_C_NO_OID_SET, - GSS_C_INITIATE, - &state->client_creds, - NULL, - NULL); - if (GSS_ERROR(maj_stat)) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - - maj_stat = gss_release_name(&min_stat, &name); - if (GSS_ERROR(maj_stat)) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - } - - ret = gss_success_result(AUTH_GSS_COMPLETE); -end: - return ret; -} - -int authenticate_gss_client_clean(gss_client_state* state) { - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - - if (state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - if (state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - if (state->client_creds != GSS_C_NO_CREDENTIAL && !(state->gss_flags & GSS_C_DELEG_FLAG)) - gss_release_cred(&min_stat, &state->client_creds); - if (state->username != NULL) { - free(state->username); - state->username = NULL; - } - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - return ret; -} - -gss_result* authenticate_gss_client_step(gss_client_state* state, - const char* challenge, - struct gss_channel_bindings_struct* channel_bindings) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - gss_result* ret = NULL; - int temp_ret = AUTH_GSS_CONTINUE; - - // Always clear out the old response - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) { - size_t len; - input_token.value = base64_decode(challenge, &len); - if (input_token.value == NULL) { - ret = gss_error_result_with_message("Ran out of memory decoding challenge"); - goto end; - } - - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_init_sec_context(&min_stat, - state->client_creds, - &state->context, - state->server_name, - state->mech_oid, - (OM_uint32)state->gss_flags, - 0, - channel_bindings, - &input_token, - NULL, - &output_token, - NULL, - NULL); - - if ((maj_stat != GSS_S_COMPLETE) && (maj_stat != GSS_S_CONTINUE_NEEDED)) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - - temp_ret = (maj_stat == GSS_S_COMPLETE) ? AUTH_GSS_COMPLETE : AUTH_GSS_CONTINUE; - // Grab the client response to send back to the server - if (output_token.length) { - state->response = - base64_encode((const unsigned char*)output_token.value, output_token.length); - if (state->response == NULL) { - ret = gss_error_result_with_message("Ran out of memory encoding response"); - goto end; - } - - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Try to get the user name if we have completed all GSS operations - if (temp_ret == AUTH_GSS_COMPLETE) { - state->context_complete = true; - - gss_name_t gssuser = GSS_C_NO_NAME; - maj_stat = gss_inquire_context( - &min_stat, state->context, &gssuser, NULL, NULL, NULL, NULL, NULL, NULL); - if (GSS_ERROR(maj_stat)) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - - gss_buffer_desc name_token; - name_token.length = 0; - maj_stat = gss_display_name(&min_stat, gssuser, &name_token, NULL); - if (GSS_ERROR(maj_stat)) { - if (name_token.value) { - gss_release_buffer(&min_stat, &name_token); - } - gss_release_name(&min_stat, &gssuser); - - ret = gss_error_result(maj_stat, min_stat); - goto end; - } else { - if (state->username != NULL) { - free(state->username); - state->username = NULL; - } - state->username = (char*)malloc(name_token.length + 1); - if (state->username == NULL) { - ret = gss_error_result_with_message("Ran out of memory allocating username"); - goto end; - } - strncpy(state->username, (char*)name_token.value, name_token.length); - state->username[name_token.length] = 0; - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - } - } - - ret = gss_success_result(temp_ret); -end: - if (output_token.value) { - gss_release_buffer(&min_stat, &output_token); - } - if (input_token.value) { - free(input_token.value); - } - return ret; -} - -gss_result* authenticate_gss_client_unwrap(gss_client_state* state, const char* challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int conf = 0; - gss_result* ret = NULL; - - // Always clear out the old response - if (state->response != NULL) { - free(state->response); - state->response = NULL; - state->responseConf = 0; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) { - size_t len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_unwrap(&min_stat, state->context, &input_token, &output_token, &conf, NULL); - - if (maj_stat != GSS_S_COMPLETE) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - - // Grab the client response - if (output_token.length) { - state->response = - base64_encode((const unsigned char*)output_token.value, output_token.length); - state->responseConf = conf; - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - ret = gss_success_result(AUTH_GSS_COMPLETE); -end: - if (output_token.value) - gss_release_buffer(&min_stat, &output_token); - if (input_token.value) - free(input_token.value); - - return ret; -} - -gss_result* authenticate_gss_client_wrap(gss_client_state* state, - const char* challenge, - const char* user, - int protect) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - char buf[4096]; - unsigned long buf_size; - gss_result* ret = NULL; - - // Always clear out the old response - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if (challenge && *challenge) { - size_t len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - if (user) { - // get bufsize - // server_conf_flags = ((char*) input_token.value)[0]; - ((char*)input_token.value)[0] = 0; - buf_size = ntohl(*((long*)input_token.value)); - free(input_token.value); -#ifdef PRINTFS - printf("User: %s, %c%c%c\n", - user, - server_conf_flags & GSS_AUTH_P_NONE ? 'N' : '-', - server_conf_flags & GSS_AUTH_P_INTEGRITY ? 'I' : '-', - server_conf_flags & GSS_AUTH_P_PRIVACY ? 'P' : '-'); - printf("Maximum GSS token size is %ld\n", buf_size); -#endif - - // agree to terms (hack!) - buf_size = htonl(buf_size); // not relevant without integrity/privacy - memcpy(buf, &buf_size, 4); - buf[0] = GSS_AUTH_P_NONE; - // server decides if principal can log in as user - strncpy(buf + 4, user, sizeof(buf) - 4); - input_token.value = buf; - input_token.length = 4 + strlen(user); - } - - // Do GSSAPI wrap - maj_stat = gss_wrap( - &min_stat, state->context, protect, GSS_C_QOP_DEFAULT, &input_token, NULL, &output_token); - - if (maj_stat != GSS_S_COMPLETE) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - - // Grab the client response to send back to the server - if (output_token.length) { - state->response = - base64_encode((const unsigned char*)output_token.value, output_token.length); - ; - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - ret = gss_success_result(AUTH_GSS_COMPLETE); -end: - if (output_token.value) - gss_release_buffer(&min_stat, &output_token); - - if (!user && input_token.value) - gss_release_buffer(&min_stat, &input_token); - - return ret; -} - -gss_result* authenticate_gss_server_init(const char* service, gss_server_state* state) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - size_t service_len; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - gss_result* ret = NULL; - - state->context = GSS_C_NO_CONTEXT; - state->server_name = GSS_C_NO_NAME; - state->client_name = GSS_C_NO_NAME; - state->server_creds = GSS_C_NO_CREDENTIAL; - state->client_creds = GSS_C_NO_CREDENTIAL; - state->username = NULL; - state->targetname = NULL; - state->response = NULL; - - // Server name may be empty which means we aren't going to create our own creds - service_len = strlen(service); - if (service_len != 0) { - // Import server name first - name_token.length = strlen(service); - name_token.value = (char*)service; - - maj_stat = gss_import_name( - &min_stat, &name_token, GSS_C_NT_HOSTBASED_SERVICE, &state->server_name); - - if (GSS_ERROR(maj_stat)) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - - // Get credentials - maj_stat = gss_acquire_cred(&min_stat, - state->server_name, - GSS_C_INDEFINITE, - GSS_C_NO_OID_SET, - GSS_C_ACCEPT, - &state->server_creds, - NULL, - NULL); - - if (GSS_ERROR(maj_stat)) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - } - - ret = gss_success_result(AUTH_GSS_COMPLETE); -end: - return ret; -} - -int authenticate_gss_server_clean(gss_server_state* state) { - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - - if (state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - if (state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - if (state->client_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->client_name); - if (state->server_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->server_creds); - if (state->client_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->client_creds); - if (state->username != NULL) { - free(state->username); - state->username = NULL; - } - if (state->targetname != NULL) { - free(state->targetname); - state->targetname = NULL; - } - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - return ret; -} - -gss_result* authenticate_gss_server_step(gss_server_state* state, const char* challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - gss_name_t target_name = GSS_C_NO_NAME; - // int ret = AUTH_GSS_CONTINUE; - gss_result* ret = NULL; - - // Always clear out the old response - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) { - size_t len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } else { - ret = gss_error_result_with_message("No challenge parameter in request from client"); - goto end; - } - - maj_stat = gss_accept_sec_context(&min_stat, - &state->context, - state->server_creds, - &input_token, - GSS_C_NO_CHANNEL_BINDINGS, - &state->client_name, - NULL, - &output_token, - NULL, - NULL, - &state->client_creds); - - if (GSS_ERROR(maj_stat)) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - - // Grab the server response to send back to the client - if (output_token.length) { - state->response = - base64_encode((const unsigned char*)output_token.value, output_token.length); - ; - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Get the user name - maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - state->username = (char*)malloc(output_token.length + 1); - strncpy(state->username, (char*)output_token.value, output_token.length); - state->username[output_token.length] = 0; - - // Get the target name if no server creds were supplied - if (state->server_creds == GSS_C_NO_CREDENTIAL) { - maj_stat = gss_inquire_context( - &min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL); - if (GSS_ERROR(maj_stat)) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - - // Free output token if necessary before reusing - if (output_token.length) - gss_release_buffer(&min_stat, &output_token); - - maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) { - ret = gss_error_result(maj_stat, min_stat); - goto end; - } - state->targetname = (char*)malloc(output_token.length + 1); - strncpy(state->targetname, (char*)output_token.value, output_token.length); - state->targetname[output_token.length] = 0; - } - - ret = gss_success_result(AUTH_GSS_COMPLETE); - state->context_complete = true; -end: - if (target_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &target_name); - if (output_token.length) - gss_release_buffer(&min_stat, &output_token); - if (input_token.value) - free(input_token.value); - return ret; -} - -gss_result* authenticate_user_krb5pwd(const char* user, - const char* pswd, - const char* service, - const char* default_realm) { - krb5_context kcontext = NULL; - krb5_error_code code; - krb5_principal client = NULL; - krb5_principal server = NULL; - gss_result* result = NULL; - int ret = 0; - char* name = NULL; - char* p = NULL; - - // for verify - krb5_creds creds; - krb5_get_init_creds_opt gic_options; - krb5_error_code verifyRet; - char *vName = NULL; - - code = krb5_init_context(&kcontext); - if (code) { - result = - gss_error_result_with_message_and_code("Cannot initialize Kerberos5 context", code); - return result; - } - - ret = krb5_parse_name(kcontext, service, &server); - if (ret) { - result = gss_error_result_with_message_and_code(krb5_get_err_text(kcontext, ret), ret); - goto end; - } - - code = krb5_unparse_name(kcontext, server, &name); - if (code) { - result = gss_error_result_with_message_and_code(krb5_get_err_text(kcontext, code), code); - goto end; - } - - free(name); - name = NULL; - name = (char*)malloc(256); - if (name == NULL) { - result = gss_error_result_with_message("Ran out of memory allocating name"); - goto end; - } - - p = strchr((char*)user, '@'); - if (p == NULL) { - snprintf(name, 256, "%s@%s", user, default_realm); - } else { - snprintf(name, 256, "%s", user); - } - - code = krb5_parse_name(kcontext, name, &client); - if (code) { - result = gss_error_result_with_message_and_code(krb5_get_err_text(kcontext, code), code); - goto end; - } - - // verify krb5 user - memset(&creds, 0, sizeof(creds)); - - verifyRet = krb5_unparse_name(kcontext, client, &vName); - if (verifyRet == 0) { - free(vName); - } - - krb5_get_init_creds_opt_init(&gic_options); - verifyRet = krb5_get_init_creds_password( - kcontext, &creds, client, (char*)pswd, NULL, NULL, 0, NULL, &gic_options); - if (verifyRet) { - result = gss_error_result_with_message_and_code(krb5_get_err_text(kcontext, verifyRet), - verifyRet); - krb5_free_cred_contents(kcontext, &creds); - goto end; - } - - krb5_free_cred_contents(kcontext, &creds); - result = gss_success_result(1); - -end: - if (name) { - free(name); - } - if (client) { - krb5_free_principal(kcontext, client); - } - if (server) { - krb5_free_principal(kcontext, server); - } - krb5_free_context(kcontext); - - return result; -} - -static gss_result* gss_success_result(int ret) { - gss_result* result = (gss_result*)malloc(sizeof(gss_result)); - result->code = ret; - result->message = NULL; - return result; -} - -static gss_result* gss_error_result(OM_uint32 err_maj, OM_uint32 err_min) { - OM_uint32 maj_stat, min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - char buf_maj[512]; - char buf_min[512]; - gss_result* result; - - do { - maj_stat = gss_display_status( - &min_stat, err_maj, GSS_C_GSS_CODE, GSS_C_NO_OID, &msg_ctx, &status_string); - if (GSS_ERROR(maj_stat)) - break; - strncpy(buf_maj, (char*)status_string.value, sizeof(buf_maj)); - gss_release_buffer(&min_stat, &status_string); - - maj_stat = gss_display_status( - &min_stat, err_min, GSS_C_MECH_CODE, GSS_C_NULL_OID, &msg_ctx, &status_string); - if (!GSS_ERROR(maj_stat)) { - strncpy(buf_min, (char*)status_string.value, sizeof(buf_min)); - gss_release_buffer(&min_stat, &status_string); - } - } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); - - result = (gss_result*)malloc(sizeof(gss_result)); - result->code = AUTH_GSS_ERROR; - result->message = (char*)malloc(sizeof(char) * 1024 + 2); - sprintf(result->message, "%s: %s", buf_maj, buf_min); - - return result; -} - -static gss_result* gss_error_result_with_message(const char* message) { - gss_result* result = (gss_result*)malloc(sizeof(gss_result)); - result->code = AUTH_GSS_ERROR; - result->message = strdup(message); - return result; -} - -static gss_result* gss_error_result_with_message_and_code(const char* message, int code) { - gss_result* result = (gss_result*)malloc(sizeof(gss_result)); - result->code = AUTH_GSS_ERROR; - result->message = (char*)malloc(strlen(message) + 20); - sprintf(result->message, "%s (%d)", message, code); - return result; -} - -#if defined(__clang__) -#pragma clang diagnostic pop -#endif diff --git a/node_modules/kerberos/src/unix/kerberos_gss.h b/node_modules/kerberos/src/unix/kerberos_gss.h deleted file mode 100644 index 449cd7e..0000000 --- a/node_modules/kerberos/src/unix/kerberos_gss.h +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright (c) 2006-2013 Apple Inc. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - **/ - -extern "C" { - #include - #include - #include -} - -#define krb5_get_err_text(context, code) error_message(code) - -#define AUTH_GSS_ERROR -1 -#define AUTH_GSS_COMPLETE 1 -#define AUTH_GSS_CONTINUE 0 - -#define GSS_AUTH_P_NONE 1 -#define GSS_AUTH_P_INTEGRITY 2 -#define GSS_AUTH_P_PRIVACY 4 - -typedef struct { - int code; - char* message; - char* data; -} gss_result; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - gss_OID mech_oid; - long int gss_flags; - gss_cred_id_t client_creds; - char* username; - char* response; - int responseConf; - bool context_complete; -} gss_client_state; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - gss_name_t client_name; - gss_cred_id_t server_creds; - gss_cred_id_t client_creds; - char* username; - char* targetname; - char* response; - bool context_complete; -} gss_server_state; - -gss_client_state* gss_client_state_new(); -gss_server_state* gss_server_state_new(); - -gss_result* server_principal_details(const char* service, const char* hostname); - -gss_result* authenticate_gss_client_init(const char* service, - const char* principal, - long int gss_flags, - gss_server_state* delegatestate, - gss_OID mech_oid, - gss_client_state* state); - -int authenticate_gss_client_clean(gss_client_state* state); -gss_result* authenticate_gss_client_step(gss_client_state* state, - const char* challenge, - struct gss_channel_bindings_struct* channel_bindings); -gss_result* authenticate_gss_client_unwrap(gss_client_state* state, const char* challenge); -gss_result* authenticate_gss_client_wrap(gss_client_state* state, - const char* challenge, - const char* user, - int protect); -gss_result* authenticate_gss_server_init(const char* service, gss_server_state* state); -int authenticate_gss_server_clean(gss_server_state* state); -gss_result* authenticate_gss_server_step(gss_server_state* state, const char* challenge); - -gss_result* authenticate_user_krb5pwd(const char* user, - const char* pswd, - const char* service, - const char* default_realm); diff --git a/node_modules/kerberos/src/unix/kerberos_unix.cc b/node_modules/kerberos/src/unix/kerberos_unix.cc deleted file mode 100644 index 3249267..0000000 --- a/node_modules/kerberos/src/unix/kerberos_unix.cc +++ /dev/null @@ -1,260 +0,0 @@ -#include - -#include "../kerberos.h" -#include "../kerberos_worker.h" - -#define GSS_MECH_OID_KRB5 9 -#define GSS_MECH_OID_SPNEGO 6 - -static char krb5_mech_oid_bytes[] = "\x2a\x86\x48\x86\xf7\x12\x01\x02\x02"; -gss_OID_desc krb5_mech_oid = {9, &krb5_mech_oid_bytes}; - -static char spnego_mech_oid_bytes[] = "\x2b\x06\x01\x05\x05\x02"; -gss_OID_desc spnego_mech_oid = {6, &spnego_mech_oid_bytes}; - -/// KerberosClient -KerberosClient::~KerberosClient() { - if (_state != NULL) { - authenticate_gss_client_clean(_state); - _state = NULL; - } -} - -NAN_METHOD(KerberosClient::Step) { - KerberosClient* client = Nan::ObjectWrap::Unwrap(info.This()); - std::string challenge(*Nan::Utf8String(info[0])); - Nan::Callback* callback = new Nan::Callback(Nan::To(info[1]).ToLocalChecked()); - - KerberosWorker::Run(callback, "kerberos:ClientStep", [=](KerberosWorker::SetOnFinishedHandler onFinished) { - std::shared_ptr result( - authenticate_gss_client_step(client->state(), challenge.c_str(), NULL), ResultDeleter); - - return onFinished([=](KerberosWorker* worker) { - Nan::HandleScope scope; - if (result->code == AUTH_GSS_ERROR) { - v8::Local argv[] = {Nan::Error(result->message), Nan::Null()}; - worker->Call(2, argv); - return; - } - - v8::Local response = Nan::Null(); - if (client->state()->response != NULL) { - response = Nan::New(client->state()->response).ToLocalChecked(); - } - - v8::Local argv[] = {Nan::Null(), response}; - worker->Call(2, argv); - }); - }); -} - -NAN_METHOD(KerberosClient::UnwrapData) { - KerberosClient* client = Nan::ObjectWrap::Unwrap(info.This()); - std::string challenge(*Nan::Utf8String(info[0])); - Nan::Callback* callback = new Nan::Callback(Nan::To(info[1]).ToLocalChecked()); - - KerberosWorker::Run(callback, "kerberos:ClientUnwrap", [=](KerberosWorker::SetOnFinishedHandler onFinished) { - std::shared_ptr result( - authenticate_gss_client_unwrap(client->state(), challenge.c_str()), ResultDeleter); - - return onFinished([=](KerberosWorker* worker) { - Nan::HandleScope scope; - if (result->code == AUTH_GSS_ERROR) { - v8::Local argv[] = {Nan::Error(result->message), Nan::Null()}; - worker->Call(2, argv); - return; - } - - v8::Local argv[] = {Nan::Null(), Nan::New(client->state()->response).ToLocalChecked()}; - worker->Call(2, argv); - }); - }); -} - -NAN_METHOD(KerberosClient::WrapData) { - KerberosClient* client = Nan::ObjectWrap::Unwrap(info.This()); - std::string challenge(*Nan::Utf8String(info[0])); - v8::Local options = Nan::To(info[1]).ToLocalChecked(); - Nan::Callback* callback = new Nan::Callback(Nan::To(info[2]).ToLocalChecked()); - std::string user = StringOptionValue(options, "user"); - - int protect = 0; // NOTE: this should be an option - - KerberosWorker::Run(callback, "kerberos:ClientWrap", [=](KerberosWorker::SetOnFinishedHandler onFinished) { - std::shared_ptr result(authenticate_gss_client_wrap( - client->state(), challenge.c_str(), user.c_str(), protect), ResultDeleter); - - return onFinished([=](KerberosWorker* worker) { - Nan::HandleScope scope; - if (result->code == AUTH_GSS_ERROR) { - v8::Local argv[] = {Nan::Error(result->message), Nan::Null()}; - worker->Call(2, argv); - return; - } - - v8::Local argv[] = {Nan::Null(), Nan::New(client->state()->response).ToLocalChecked()}; - worker->Call(2, argv); - }); - }); -} - -/// KerberosServer -KerberosServer::~KerberosServer() { - if (_state != NULL) { - authenticate_gss_server_clean(_state); - _state = NULL; - } -} - -NAN_METHOD(KerberosServer::Step) { - KerberosServer* server = Nan::ObjectWrap::Unwrap(info.This()); - std::string challenge(*Nan::Utf8String(info[0])); - Nan::Callback* callback = new Nan::Callback(Nan::To(info[1]).ToLocalChecked()); - - KerberosWorker::Run(callback, "kerberos:ServerStep", [=](KerberosWorker::SetOnFinishedHandler onFinished) { - std::shared_ptr result( - authenticate_gss_server_step(server->state(), challenge.c_str()), ResultDeleter); - - return onFinished([=](KerberosWorker* worker) { - Nan::HandleScope scope; - if (result->code == AUTH_GSS_ERROR) { - v8::Local argv[] = {Nan::Error(result->message), Nan::Null()}; - worker->Call(2, argv); - return; - } - - v8::Local response = Nan::Null(); - if (server->state()->response != NULL) { - response = Nan::New(server->state()->response).ToLocalChecked(); - } - - v8::Local argv[] = {Nan::Null(), response}; - worker->Call(2, argv); - }); - }); -} - -/// Global Methods -NAN_METHOD(InitializeClient) { - std::string service(*Nan::Utf8String(info[0])); - v8::Local options = Nan::To(info[1]).ToLocalChecked(); - Nan::Callback* callback = new Nan::Callback(Nan::To(info[2]).ToLocalChecked()); - - std::string principal = StringOptionValue(options, "principal"); - uint32_t gss_flags = - UInt32OptionValue(options, "gssFlags", GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG); - uint32_t mech_oid_int = UInt32OptionValue(options, "mechOID", 0); - gss_OID mech_oid = GSS_C_NO_OID; - if (mech_oid_int == GSS_MECH_OID_KRB5) { - mech_oid = &krb5_mech_oid; - } else if (mech_oid_int == GSS_MECH_OID_SPNEGO) { - mech_oid = &spnego_mech_oid; - } - - KerberosWorker::Run(callback, "kerberos:InitializeClient", [=](KerberosWorker::SetOnFinishedHandler onFinished) { - gss_client_state* client_state = gss_client_state_new(); - std::shared_ptr result(authenticate_gss_client_init( - service.c_str(), principal.c_str(), gss_flags, NULL, mech_oid, client_state), ResultDeleter); - - // must clean up state if we won't be using it, smart pointers won't help here unfortunately - // because we can't `release` a shared pointer. - if (result->code == AUTH_GSS_ERROR) { - free(client_state); - } - - return onFinished([=](KerberosWorker* worker) { - Nan::HandleScope scope; - if (result->code == AUTH_GSS_ERROR) { - v8::Local argv[] = {Nan::Error(result->message), Nan::Null()}; - worker->Call(2, argv); - return; - } - - v8::Local argv[] = {Nan::Null(), KerberosClient::NewInstance(client_state)}; - worker->Call(2, argv); - }); - }); -} - -NAN_METHOD(InitializeServer) { - std::string service(*Nan::Utf8String(info[0])); - Nan::Callback* callback = new Nan::Callback(Nan::To(info[1]).ToLocalChecked()); - - KerberosWorker::Run(callback, "kerberos:InitializeServer", [=](KerberosWorker::SetOnFinishedHandler onFinished) { - gss_server_state* server_state = gss_server_state_new(); - std::shared_ptr result( - authenticate_gss_server_init(service.c_str(), server_state), ResultDeleter); - - // must clean up state if we won't be using it, smart pointers won't help here unfortunately - // because we can't `release` a shared pointer. - if (result->code == AUTH_GSS_ERROR) { - free(server_state); - } - - return onFinished([=](KerberosWorker* worker) { - Nan::HandleScope scope; - if (result->code == AUTH_GSS_ERROR) { - v8::Local argv[] = {Nan::Error(result->message), Nan::Null()}; - worker->Call(2, argv); - return; - } - - v8::Local argv[] = {Nan::Null(), KerberosServer::NewInstance(server_state)}; - worker->Call(2, argv); - }); - }); -} - -NAN_METHOD(PrincipalDetails) { - std::string service(*Nan::Utf8String(info[0])); - std::string hostname(*Nan::Utf8String(info[1])); - Nan::Callback* callback = new Nan::Callback(Nan::To(info[2]).ToLocalChecked()); - - KerberosWorker::Run(callback, "kerberos:PrincipalDetails", [=](KerberosWorker::SetOnFinishedHandler onFinished) { - std::shared_ptr result( - server_principal_details(service.c_str(), hostname.c_str()), ResultDeleter); - - return onFinished([=](KerberosWorker* worker) { - Nan::HandleScope scope; - if (result->code == AUTH_GSS_ERROR) { - v8::Local argv[] = {Nan::Error(result->message), Nan::Null()}; - worker->Call(2, argv); - return; - } - - v8::Local argv[] = {Nan::Null(), Nan::New(result->data).ToLocalChecked()}; - worker->Call(2, argv); - }); - }); -} - -NAN_METHOD(CheckPassword) { - std::string username(*Nan::Utf8String(info[0])); - std::string password(*Nan::Utf8String(info[1])); - std::string service(*Nan::Utf8String(info[2])); - - std::string defaultRealm; - Nan::Callback* callback; - if (info[3]->IsFunction()) { - callback = new Nan::Callback(Nan::To(info[3]).ToLocalChecked()); - } else { - defaultRealm = *Nan::Utf8String(info[3]); - callback = new Nan::Callback(Nan::To(info[4]).ToLocalChecked()); - } - - KerberosWorker::Run(callback, "kerberos:CheckPassword", [=](KerberosWorker::SetOnFinishedHandler onFinished) { - std::shared_ptr result(authenticate_user_krb5pwd( - username.c_str(), password.c_str(), service.c_str(), defaultRealm.c_str()), ResultDeleter); - - return onFinished([=](KerberosWorker* worker) { - Nan::HandleScope scope; - if (result->code == AUTH_GSS_ERROR) { - v8::Local argv[] = {Nan::Error(result->message), Nan::Null()}; - worker->Call(2, argv); - } else { - v8::Local argv[] = {Nan::Null(), Nan::Null()}; - worker->Call(2, argv); - } - }); - }); -} diff --git a/node_modules/kerberos/src/win32/kerberos_sspi.cc b/node_modules/kerberos/src/win32/kerberos_sspi.cc deleted file mode 100644 index 722e32e..0000000 --- a/node_modules/kerberos/src/win32/kerberos_sspi.cc +++ /dev/null @@ -1,563 +0,0 @@ -#include -#include -#include "kerberos_sspi.h" - -static sspi_result* sspi_success_result(INT ret); -static sspi_result* sspi_error_result(DWORD errCode, const SEC_CHAR* msg); -static sspi_result* sspi_error_result_with_message(const char* message); -static SEC_CHAR* base64_encode(const SEC_CHAR* value, DWORD vlen); -static SEC_CHAR* base64_decode(const SEC_CHAR* value, DWORD* rlen); -static CHAR* wide_to_utf8(WCHAR* value); - -sspi_client_state* sspi_client_state_new() { - sspi_client_state* state = (sspi_client_state*)malloc(sizeof(sspi_client_state)); - state->username = NULL; - state->response = NULL; - state->responseConf = 0; - state->context_complete = FALSE; - return state; -} - -VOID -auth_sspi_client_clean(sspi_client_state* state) { - if (state->haveCtx) { - DeleteSecurityContext(&state->ctx); - state->haveCtx = 0; - } - if (state->haveCred) { - FreeCredentialsHandle(&state->cred); - state->haveCred = 0; - } - if (state->spn != NULL) { - free(state->spn); - state->spn = NULL; - } - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - if (state->username != NULL) { - free(state->username); - state->username = NULL; - } -} - -sspi_result* -auth_sspi_client_init(WCHAR* service, - ULONG flags, - WCHAR* user, - ULONG ulen, - WCHAR* domain, - ULONG dlen, - WCHAR* password, - ULONG plen, - WCHAR* mechoid, - sspi_client_state* state) { - SECURITY_STATUS status; - SEC_WINNT_AUTH_IDENTITY_W authIdentity; - TimeStamp ignored; - - state->response = NULL; - state->username = NULL; - state->qop = SECQOP_WRAP_NO_ENCRYPT; - state->flags = flags; - state->haveCred = 0; - state->haveCtx = 0; - state->spn = _wcsdup(service); - if (state->spn == NULL) { - return sspi_error_result_with_message("Ran out of memory assigning service"); - } - - if (*user) { - authIdentity.User = (unsigned short*)user; - authIdentity.UserLength = ulen; - - if (*password) { - authIdentity.Password = (unsigned short*)password; - authIdentity.PasswordLength = plen; - } - - if (*domain) { - authIdentity.Domain = (unsigned short*)domain; - authIdentity.DomainLength = dlen; - } - - authIdentity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; - } - - /* Note that the first paramater, pszPrincipal, appears to be - * completely ignored in the Kerberos SSP. For more details see - * https://github.com/mongodb-labs/winkerberos/issues/11. - * */ - status = AcquireCredentialsHandleW(/* Principal */ - NULL, - /* Security package name */ - mechoid, - /* Credentials Use */ - SECPKG_CRED_OUTBOUND, - /* LogonID (We don't use this) */ - NULL, - /* AuthData */ - *user ? &authIdentity : NULL, - /* Always NULL */ - NULL, - /* Always NULL */ - NULL, - /* CredHandle */ - &state->cred, - /* Expiry (Required but unused by us) */ - &ignored); - if (status != SEC_E_OK) { - return sspi_error_result(status, "AcquireCredentialsHandle"); - } - - state->haveCred = 1; - return sspi_success_result(AUTH_GSS_COMPLETE); -} - -sspi_result* -auth_sspi_client_step(sspi_client_state* state, SEC_CHAR* challenge, SecPkgContext_Bindings* sec_pkg_context_bindings) { - SecBufferDesc inbuf; - SecBuffer inBufs[2]; - SecBufferDesc outbuf; - SecBuffer outBufs[1]; - ULONG ignored; - SECURITY_STATUS status = AUTH_GSS_CONTINUE; - DWORD len; - BOOL haveToken = FALSE; - INT tokenBufferIndex = 0; - sspi_result* result; - - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - inbuf.ulVersion = SECBUFFER_VERSION; - inbuf.pBuffers = inBufs; - inbuf.cBuffers = 0; - - if (sec_pkg_context_bindings != NULL) { - inBufs[inbuf.cBuffers].BufferType = SECBUFFER_CHANNEL_BINDINGS; - inBufs[inbuf.cBuffers].pvBuffer = sec_pkg_context_bindings->Bindings; - inBufs[inbuf.cBuffers].cbBuffer = sec_pkg_context_bindings->BindingsLength; - inbuf.cBuffers++; - } - - tokenBufferIndex = inbuf.cBuffers; - if (state->haveCtx) { - haveToken = TRUE; - inBufs[tokenBufferIndex].BufferType = SECBUFFER_TOKEN; - inBufs[tokenBufferIndex].pvBuffer = base64_decode(challenge, &len); - if (!inBufs[tokenBufferIndex].pvBuffer) { - return sspi_error_result_with_message("Unable to base64 decode pvBuffer"); - } - - inBufs[tokenBufferIndex].cbBuffer = len; - inbuf.cBuffers++; - } - - outbuf.ulVersion = SECBUFFER_VERSION; - outbuf.cBuffers = 1; - outbuf.pBuffers = outBufs; - outBufs[0].pvBuffer = NULL; - outBufs[0].cbBuffer = 0; - outBufs[0].BufferType = SECBUFFER_TOKEN; - - status = InitializeSecurityContextW(/* CredHandle */ - &state->cred, - /* CtxtHandle (NULL on first call) */ - state->haveCtx ? &state->ctx : NULL, - /* Service Principal Name */ - state->spn, - /* Flags */ - ISC_REQ_ALLOCATE_MEMORY | state->flags, - /* Always 0 */ - 0, - /* Target data representation */ - SECURITY_NETWORK_DREP, - /* Challenge (Set to NULL if no buffers are set) */ - inbuf.cBuffers > 0 ? &inbuf : NULL, - /* Always 0 */ - 0, - /* CtxtHandle (Set on first call) */ - &state->ctx, - /* Output */ - &outbuf, - /* Context attributes */ - &ignored, - /* Expiry (We don't use this) */ - NULL); - - if (status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED) { - result = sspi_error_result(status, "InitializeSecurityContext"); - goto done; - } - - state->haveCtx = 1; - state->context_complete = TRUE; - if (outBufs[0].cbBuffer) { - state->response = base64_encode((const SEC_CHAR*)outBufs[0].pvBuffer, outBufs[0].cbBuffer); - if (!state->response) { - status = AUTH_GSS_ERROR; - goto done; - } - } - - if (status == SEC_E_OK) { - /* Get authenticated username. */ - SecPkgContext_NamesW names; - status = QueryContextAttributesW( - &state->ctx, SECPKG_ATTR_NAMES, &names); - - if (status != SEC_E_OK) { - result = sspi_error_result(status, "QueryContextAttributesW"); - goto done; - } - - state->username = wide_to_utf8(names.sUserName); - if (state->username == NULL) { - result = sspi_error_result_with_message("Unable to allocate memory for username"); - goto done; - } - - FreeContextBuffer(names.sUserName); - result = sspi_success_result(AUTH_GSS_COMPLETE); - } else { - result = sspi_success_result(AUTH_GSS_CONTINUE); - } -done: - if (haveToken) { - free(inBufs[tokenBufferIndex].pvBuffer); - } - if (outBufs[0].pvBuffer) { - FreeContextBuffer(outBufs[0].pvBuffer); - } - - return result; -} - -sspi_result* -auth_sspi_client_unwrap(sspi_client_state* state, SEC_CHAR* challenge) { - sspi_result* result; - SECURITY_STATUS status; - DWORD len; - SecBuffer wrapBufs[2]; - SecBufferDesc wrapBufDesc; - wrapBufDesc.ulVersion = SECBUFFER_VERSION; - wrapBufDesc.cBuffers = 2; - wrapBufDesc.pBuffers = wrapBufs; - - if (state->response != NULL) { - free(state->response); - state->response = NULL; - state->qop = SECQOP_WRAP_NO_ENCRYPT; - } - - if (!state->haveCtx) { - return sspi_error_result_with_message("Uninitialized security context. You must use authGSSClientStep to initialize the security context before calling this function."); - } - - wrapBufs[0].pvBuffer = base64_decode(challenge, &len); - if (!wrapBufs[0].pvBuffer) { - return sspi_error_result_with_message("Unable to decode base64 response"); - } - - wrapBufs[0].cbBuffer = len; - wrapBufs[0].BufferType = SECBUFFER_STREAM; - - wrapBufs[1].pvBuffer = NULL; - wrapBufs[1].cbBuffer = 0; - wrapBufs[1].BufferType = SECBUFFER_DATA; - - status = DecryptMessage(&state->ctx, &wrapBufDesc, 0, &state->qop); - if (status != SEC_E_OK) { - result = sspi_error_result(status, "DecryptMessage"); - goto done; - } - - if (wrapBufs[1].cbBuffer) { - state->response = base64_encode((const SEC_CHAR*)wrapBufs[1].pvBuffer, wrapBufs[1].cbBuffer); - if (!state->response) { - result = sspi_error_result_with_message("Unable to base65 encode decrypted message"); - goto done; - } - } - - result = sspi_success_result(AUTH_GSS_COMPLETE); -done: - if (wrapBufs[0].pvBuffer) { - free(wrapBufs[0].pvBuffer); - } - - return result; -} - -sspi_result* -auth_sspi_client_wrap(sspi_client_state* state, - SEC_CHAR* data, - SEC_CHAR* user, - ULONG ulen, - INT protect) { - SECURITY_STATUS status; - SecPkgContext_Sizes sizes; - SecBuffer wrapBufs[3]; - SecBufferDesc wrapBufDesc; - SEC_CHAR* decodedData = NULL; - SEC_CHAR* inbuf; - SIZE_T inbufSize; - SEC_CHAR* outbuf; - DWORD outbufSize; - SEC_CHAR* plaintextMessage; - ULONG plaintextMessageSize; - - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if (!state->haveCtx) { - return sspi_error_result_with_message("Uninitialized security context. You must use authGSSClientStep to initialize the security context before calling this function."); - } - - status = QueryContextAttributes(&state->ctx, SECPKG_ATTR_SIZES, &sizes); - if (status != SEC_E_OK) { - return sspi_error_result(status, "QueryContextAttributes"); - } - - if (*user) { - /* Length of user + 4 bytes for security layer (see below). */ - plaintextMessageSize = ulen + 4; - } else { - decodedData = base64_decode(data, &plaintextMessageSize); - if (!decodedData) { - return sspi_error_result_with_message("Unable to base64 decode message"); - } - } - - inbufSize = - sizes.cbSecurityTrailer + plaintextMessageSize + sizes.cbBlockSize; - inbuf = (SEC_CHAR*)malloc(inbufSize); - if (inbuf == NULL) { - free(decodedData); - return sspi_error_result_with_message("Unable to allocate memory for buffer"); - } - - plaintextMessage = inbuf + sizes.cbSecurityTrailer; - if (*user) { - /* Authenticate the provided user. Unlike pykerberos, we don't - * need any information from "data" to do that. - */ - plaintextMessage[0] = 1; /* No security layer */ - plaintextMessage[1] = 0; - plaintextMessage[2] = 0; - plaintextMessage[3] = 0; - memcpy_s( - plaintextMessage + 4, - inbufSize - sizes.cbSecurityTrailer - 4, - user, - strlen(user)); - } else { - /* No user provided. Just rewrap data. */ - memcpy_s( - plaintextMessage, - inbufSize - sizes.cbSecurityTrailer, - decodedData, - plaintextMessageSize); - free(decodedData); - } - - wrapBufDesc.cBuffers = 3; - wrapBufDesc.pBuffers = wrapBufs; - wrapBufDesc.ulVersion = SECBUFFER_VERSION; - - wrapBufs[0].cbBuffer = sizes.cbSecurityTrailer; - wrapBufs[0].BufferType = SECBUFFER_TOKEN; - wrapBufs[0].pvBuffer = inbuf; - - wrapBufs[1].cbBuffer = (ULONG)plaintextMessageSize; - wrapBufs[1].BufferType = SECBUFFER_DATA; - wrapBufs[1].pvBuffer = inbuf + sizes.cbSecurityTrailer; - - wrapBufs[2].cbBuffer = sizes.cbBlockSize; - wrapBufs[2].BufferType = SECBUFFER_PADDING; - wrapBufs[2].pvBuffer = - inbuf + (sizes.cbSecurityTrailer + plaintextMessageSize); - - status = EncryptMessage( - &state->ctx, - protect ? 0 : SECQOP_WRAP_NO_ENCRYPT, - &wrapBufDesc, - 0); - if (status != SEC_E_OK) { - free(inbuf); - return sspi_error_result(status, "EncryptMessage"); - } - - outbufSize = - wrapBufs[0].cbBuffer + wrapBufs[1].cbBuffer + wrapBufs[2].cbBuffer; - outbuf = (SEC_CHAR*)malloc(sizeof(SEC_CHAR) * outbufSize); - if (outbuf == NULL) { - free(inbuf); - return sspi_error_result_with_message("Unable to allocate memory for out buffer"); - } - - memcpy_s(outbuf, - outbufSize, - wrapBufs[0].pvBuffer, - wrapBufs[0].cbBuffer); - memcpy_s(outbuf + wrapBufs[0].cbBuffer, - outbufSize - wrapBufs[0].cbBuffer, - wrapBufs[1].pvBuffer, - wrapBufs[1].cbBuffer); - memcpy_s(outbuf + wrapBufs[0].cbBuffer + wrapBufs[1].cbBuffer, - outbufSize - wrapBufs[0].cbBuffer - wrapBufs[1].cbBuffer, - wrapBufs[2].pvBuffer, - wrapBufs[2].cbBuffer); - state->response = base64_encode(outbuf, outbufSize); - - sspi_result* result; - if (!state->response) { - result = sspi_error_result_with_message("Unable to base64 decode outbuf"); - } else { - result = sspi_success_result(AUTH_GSS_COMPLETE); - } - - free(inbuf); - free(outbuf); - return result; -} - -static sspi_result* sspi_success_result(int ret) { - sspi_result* result = (sspi_result*)malloc(sizeof(sspi_result)); - result->code = ret; - result->message = NULL; - return result; -} - -static sspi_result* sspi_error_result(DWORD errCode, const SEC_CHAR* msg) { - SEC_CHAR* err; - DWORD status; - DWORD flags = (FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS); - - status = FormatMessageA(flags, - NULL, - errCode, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPSTR)&err, - 0, - NULL); - - sspi_result* result = (sspi_result*)malloc(sizeof(sspi_result)); - result->code = AUTH_GSS_ERROR; - result->message = (char*)malloc(sizeof(char) * 1024 + 2); - if (status) { - sprintf(result->message, "%s: %s", msg, err); - } else { - sprintf(result->message, "%s", msg); - } - - return result; -} - -static sspi_result* sspi_error_result_with_message(const char* message) { - sspi_result* result = (sspi_result*)malloc(sizeof(sspi_result)); - result->code = AUTH_GSS_ERROR; - result->message = strdup(message); - return result; -} - -static SEC_CHAR* -base64_encode(const SEC_CHAR* value, DWORD vlen) { - SEC_CHAR* out = NULL; - DWORD len; - /* Get the correct size for the out buffer. */ - if (CryptBinaryToStringA((BYTE*)value, - vlen, - CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF, - NULL, - &len)) { - out = (SEC_CHAR*)malloc(sizeof(SEC_CHAR) * len); - if (out) { - /* Encode to the out buffer. */ - if (CryptBinaryToStringA((BYTE*)value, - vlen, - CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF, - out, - &len)) { - return out; - } else { - free(out); - } - } - } - - return NULL; -} - -static SEC_CHAR* -base64_decode(const SEC_CHAR* value, DWORD* rlen) { - SEC_CHAR* out = NULL; - /* Get the correct size for the out buffer. */ - if (CryptStringToBinaryA(value, - 0, - CRYPT_STRING_BASE64, - NULL, - rlen, - NULL, - NULL)) { - out = (SEC_CHAR*)malloc(sizeof(SEC_CHAR) * *rlen); - if (out) { - /* Decode to the out buffer. */ - if (CryptStringToBinaryA(value, - 0, - CRYPT_STRING_BASE64, - (BYTE*)out, - rlen, - NULL, - NULL)) { - return out; - } else { - free(out); - } - } - } - - return NULL; -} - -static CHAR* -wide_to_utf8(WCHAR* value) { - CHAR* out; - INT len = WideCharToMultiByte(CP_UTF8, - 0, - value, - -1, - NULL, - 0, - NULL, - NULL); - if (len) { - out = (CHAR*)malloc(sizeof(CHAR) * len); - if (!out) { - return NULL; - } - - if (WideCharToMultiByte(CP_UTF8, - 0, - value, - -1, - out, - len, - NULL, - NULL)) { - return out; - } else { - free(out); - } - } - - return NULL; -} diff --git a/node_modules/kerberos/src/win32/kerberos_sspi.h b/node_modules/kerberos/src/win32/kerberos_sspi.h deleted file mode 100644 index de1f91f..0000000 --- a/node_modules/kerberos/src/win32/kerberos_sspi.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2016 MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define SECURITY_WIN32 1 /* Required for SSPI */ - -#include -#include - -#define AUTH_GSS_ERROR -1 -#define AUTH_GSS_COMPLETE 1 -#define AUTH_GSS_CONTINUE 0 - -typedef struct { - int code; - char* message; - char* data; -} sspi_result; - -typedef struct { - CredHandle cred; - CtxtHandle ctx; - WCHAR* spn; - SEC_CHAR* response; - SEC_CHAR* username; - ULONG flags; - UCHAR haveCred; - UCHAR haveCtx; - ULONG qop; - - INT responseConf; - BOOL context_complete; -} sspi_client_state; - -typedef struct { - WCHAR* username; - WCHAR* response; - BOOL context_complete; - char* targetname; -} sspi_server_state; - -sspi_client_state* sspi_client_state_new(); -VOID auth_sspi_client_clean(sspi_client_state* state); -sspi_result* auth_sspi_client_init(WCHAR* service, - ULONG flags, - WCHAR* user, - ULONG ulen, - WCHAR* domain, - ULONG dlen, - WCHAR* password, - ULONG plen, - WCHAR* mechoid, - sspi_client_state* state); - -sspi_result* auth_sspi_client_step(sspi_client_state* state, SEC_CHAR* challenge, SecPkgContext_Bindings* sec_pkg_context_bindings); -sspi_result* auth_sspi_client_unwrap(sspi_client_state* state, SEC_CHAR* challenge); -sspi_result* auth_sspi_client_wrap(sspi_client_state* state, SEC_CHAR* data, SEC_CHAR* user, ULONG ulen, INT protect); diff --git a/node_modules/kerberos/src/win32/kerberos_win32.cc b/node_modules/kerberos/src/win32/kerberos_win32.cc deleted file mode 100644 index ba0a0c1..0000000 --- a/node_modules/kerberos/src/win32/kerberos_win32.cc +++ /dev/null @@ -1,191 +0,0 @@ -#include - -#include "../kerberos.h" -#include "../kerberos_worker.h" - -#define GSS_MECH_OID_KRB5 9 -#define GSS_MECH_OID_SPNEGO 6 -#define GSS_MECH_OID_KRB5_STR L"Kerberos" -#define GSS_MECH_OID_SPNEGO_STR L"Negotiate" - -#define GSS_C_MUTUAL_FLAG 2 -#define GSS_C_REPLAY_FLAG 4 -#define GSS_C_SEQUENCE_FLAG 8 - -const wchar_t* to_wstring(const char *bytes) { - unsigned int sizeOfStr = MultiByteToWideChar(CP_UTF8, 0, bytes, -1, NULL, 0); - wchar_t *output = new wchar_t[sizeOfStr]; - MultiByteToWideChar(CP_UTF8, 0, bytes, -1, output, sizeOfStr); - return output; -} - -NAN_INLINE std::wstring WStringOptionValue(v8::Local options, const char* _key) { - Nan::HandleScope scope; - v8::Local key = Nan::New(_key).ToLocalChecked(); - if (options.IsEmpty() || !Nan::Has(options, key).FromMaybe(false)) { - return std::wstring(); - } - - v8::Local value = Nan::Get(options, key).ToLocalChecked(); - if (!value->IsString()) { - return std::wstring(); - } - - return std::wstring(to_wstring(*(Nan::Utf8String(value)))); -} - -/// KerberosClient -KerberosClient::~KerberosClient() { - if (_state != NULL) { - auth_sspi_client_clean(_state); - _state = NULL; - } -} - -NAN_METHOD(KerberosClient::Step) { - KerberosClient* client = Nan::ObjectWrap::Unwrap(info.This()); - std::string challenge(*Nan::Utf8String(info[0])); - Nan::Callback* callback = new Nan::Callback(Nan::To(info[1]).ToLocalChecked()); - - KerberosWorker::Run(callback, "kerberos:ClientStep", [=](KerberosWorker::SetOnFinishedHandler onFinished) { - std::shared_ptr result( - auth_sspi_client_step(client->state(), (SEC_CHAR*)challenge.c_str(), NULL), ResultDeleter); - - return onFinished([=](KerberosWorker* worker) { - Nan::HandleScope scope; - if (result->code == AUTH_GSS_ERROR) { - v8::Local argv[] = {Nan::Error(result->message), Nan::Null()}; - worker->Call(2, argv); - return; - } - - v8::Local response = Nan::Null(); - if (client->state()->response != NULL) { - response = Nan::New(client->state()->response).ToLocalChecked(); - } - - v8::Local argv[] = {Nan::Null(), response}; - worker->Call(2, argv); - }); - }); -} - -NAN_METHOD(KerberosClient::UnwrapData) { - KerberosClient* client = Nan::ObjectWrap::Unwrap(info.This()); - std::string challenge(*Nan::Utf8String(info[0])); - Nan::Callback* callback = new Nan::Callback(Nan::To(info[1]).ToLocalChecked()); - - KerberosWorker::Run(callback, "kerberos:ClientUnwrap", [=](KerberosWorker::SetOnFinishedHandler onFinished) { - std::shared_ptr result( - auth_sspi_client_unwrap(client->state(), (SEC_CHAR*)challenge.c_str()), ResultDeleter); - - return onFinished([=](KerberosWorker* worker) { - Nan::HandleScope scope; - if (result->code == AUTH_GSS_ERROR) { - v8::Local argv[] = {Nan::Error(result->message), Nan::Null()}; - worker->Call(2, argv); - return; - } - - v8::Local argv[] = {Nan::Null(), Nan::New(client->state()->response).ToLocalChecked()}; - worker->Call(2, argv); - }); - }); -} - -NAN_METHOD(KerberosClient::WrapData) { - KerberosClient* client = Nan::ObjectWrap::Unwrap(info.This()); - std::string challenge(*Nan::Utf8String(info[0])); - v8::Local options = Nan::To(info[1]).ToLocalChecked(); - Nan::Callback* callback = new Nan::Callback(Nan::To(info[2]).ToLocalChecked()); - std::string user = StringOptionValue(options, "user"); - int protect = 0; // NOTE: this should be an option - - KerberosWorker::Run(callback, "kerberos:ClientWrap", [=](KerberosWorker::SetOnFinishedHandler onFinished) { - std::shared_ptr result(auth_sspi_client_wrap( - client->state(), (SEC_CHAR*)challenge.c_str(), (SEC_CHAR*)user.c_str(), user.length(), protect), ResultDeleter); - - return onFinished([=](KerberosWorker* worker) { - Nan::HandleScope scope; - - if (result->code == AUTH_GSS_ERROR) { - v8::Local argv[] = {Nan::Error(result->message), Nan::Null()}; - worker->Call(2, argv); - return; - } - - v8::Local argv[] = {Nan::Null(), Nan::New(client->state()->response).ToLocalChecked()}; - worker->Call(2, argv); - }); - }); -} - -/// KerberosServer -KerberosServer::~KerberosServer() { - // if (_state != NULL) { - // authenticate_gss_server_clean(_state); - // _state = NULL; - // } -} - -NAN_METHOD(KerberosServer::Step) { - KerberosServer* server = Nan::ObjectWrap::Unwrap(info.This()); - std::string challenge(*Nan::Utf8String(info[0])); - Nan::Callback* callback = new Nan::Callback(Nan::To(info[1]).ToLocalChecked()); - Nan::ThrowError("`KerberosServer::Step` is not implemented yet for windows"); -} - -/// Global Methods -NAN_METHOD(InitializeClient) { - std::wstring service(to_wstring(*(Nan::Utf8String(info[0])))); - v8::Local options = Nan::To(info[1]).ToLocalChecked(); - Nan::Callback* callback = new Nan::Callback(Nan::To(info[2]).ToLocalChecked()); - - std::wstring user = WStringOptionValue(options, "user"); - std::wstring domain = WStringOptionValue(options, "domain"); - std::wstring password = WStringOptionValue(options, "password"); - ULONG gss_flags = (ULONG)UInt32OptionValue(options, "flags", GSS_C_MUTUAL_FLAG|GSS_C_SEQUENCE_FLAG); - uint32_t mech_oid_int = UInt32OptionValue(options, "mechOID", 0); - std::wstring mech_oid = GSS_MECH_OID_KRB5_STR; - if (mech_oid_int == GSS_MECH_OID_SPNEGO) { - mech_oid = GSS_MECH_OID_SPNEGO_STR; - } - - KerberosWorker::Run(callback, "kerberos:InitializeClient", [=](KerberosWorker::SetOnFinishedHandler onFinished) { - sspi_client_state* client_state = sspi_client_state_new(); - std::shared_ptr result(auth_sspi_client_init( - (WCHAR*)service.c_str(), gss_flags, (WCHAR*)user.c_str(), user.length(), - (WCHAR*)domain.c_str(), domain.length(), (WCHAR*)password.c_str(), password.length(), - (WCHAR*)mech_oid.c_str(), client_state), ResultDeleter); - - // must clean up state if we won't be using it, smart pointers won't help here unfortunately - // because we can't `release` a shared pointer. - if (result->code == AUTH_GSS_ERROR) { - free(client_state); - } - - return onFinished([=](KerberosWorker* worker) { - Nan::HandleScope scope; - if (result->code == AUTH_GSS_ERROR) { - v8::Local argv[] = {Nan::Error(result->message), Nan::Null()}; - worker->Call(2, argv); - return; - } - - v8::Local argv[] = {Nan::Null(), KerberosClient::NewInstance(client_state)}; - worker->Call(2, argv); - }); - }); -} - -NAN_METHOD(InitializeServer) { - Nan::ThrowError("`initializeServer` is not implemented yet for windows"); -} - -NAN_METHOD(PrincipalDetails) { - Nan::ThrowError("`principalDetails` is not implemented yet for windows"); -} - -NAN_METHOD(CheckPassword) { - Nan::ThrowError("`checkPassword` is not implemented yet for windows"); -} diff --git a/node_modules/media-typer/HISTORY.md b/node_modules/media-typer/HISTORY.md deleted file mode 100644 index 62c2003..0000000 --- a/node_modules/media-typer/HISTORY.md +++ /dev/null @@ -1,22 +0,0 @@ -0.3.0 / 2014-09-07 -================== - - * Support Node.js 0.6 - * Throw error when parameter format invalid on parse - -0.2.0 / 2014-06-18 -================== - - * Add `typer.format()` to format media types - -0.1.0 / 2014-06-17 -================== - - * Accept `req` as argument to `parse` - * Accept `res` as argument to `parse` - * Parse media type with extra LWS between type and first parameter - -0.0.0 / 2014-06-13 -================== - - * Initial implementation diff --git a/node_modules/media-typer/LICENSE b/node_modules/media-typer/LICENSE deleted file mode 100644 index b7dce6c..0000000 --- a/node_modules/media-typer/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2014 Douglas Christopher Wilson - -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/media-typer/README.md b/node_modules/media-typer/README.md deleted file mode 100644 index d8df623..0000000 --- a/node_modules/media-typer/README.md +++ /dev/null @@ -1,81 +0,0 @@ -# media-typer - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Simple RFC 6838 media type parser - -## Installation - -```sh -$ npm install media-typer -``` - -## API - -```js -var typer = require('media-typer') -``` - -### typer.parse(string) - -```js -var obj = typer.parse('image/svg+xml; charset=utf-8') -``` - -Parse a media type string. This will return an object with the following -properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): - - - `type`: The type of the media type (always lower case). Example: `'image'` - - - `subtype`: The subtype of the media type (always lower case). Example: `'svg'` - - - `suffix`: The suffix of the media type (always lower case). Example: `'xml'` - - - `parameters`: An object of the parameters in the media type (name of parameter always lower case). Example: `{charset: 'utf-8'}` - -### typer.parse(req) - -```js -var obj = typer.parse(req) -``` - -Parse the `content-type` header from the given `req`. Short-cut for -`typer.parse(req.headers['content-type'])`. - -### typer.parse(res) - -```js -var obj = typer.parse(res) -``` - -Parse the `content-type` header set on the given `res`. Short-cut for -`typer.parse(res.getHeader('content-type'))`. - -### typer.format(obj) - -```js -var obj = typer.format({type: 'image', subtype: 'svg', suffix: 'xml'}) -``` - -Format an object into a media type string. This will return a string of the -mime type for the given object. For the properties of the object, see the -documentation for `typer.parse(string)`. - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/media-typer.svg?style=flat -[npm-url]: https://npmjs.org/package/media-typer -[node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg?style=flat -[node-version-url]: http://nodejs.org/download/ -[travis-image]: https://img.shields.io/travis/jshttp/media-typer.svg?style=flat -[travis-url]: https://travis-ci.org/jshttp/media-typer -[coveralls-image]: https://img.shields.io/coveralls/jshttp/media-typer.svg?style=flat -[coveralls-url]: https://coveralls.io/r/jshttp/media-typer -[downloads-image]: https://img.shields.io/npm/dm/media-typer.svg?style=flat -[downloads-url]: https://npmjs.org/package/media-typer diff --git a/node_modules/media-typer/index.js b/node_modules/media-typer/index.js deleted file mode 100644 index 07f7295..0000000 --- a/node_modules/media-typer/index.js +++ /dev/null @@ -1,270 +0,0 @@ -/*! - * media-typer - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * RegExp to match *( ";" parameter ) in RFC 2616 sec 3.7 - * - * parameter = token "=" ( token | quoted-string ) - * token = 1* - * separators = "(" | ")" | "<" | ">" | "@" - * | "," | ";" | ":" | "\" | <"> - * | "/" | "[" | "]" | "?" | "=" - * | "{" | "}" | SP | HT - * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - * qdtext = > - * quoted-pair = "\" CHAR - * CHAR = - * TEXT = - * LWS = [CRLF] 1*( SP | HT ) - * CRLF = CR LF - * CR = - * LF = - * SP = - * SHT = - * CTL = - * OCTET = - */ -var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g; -var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/ -var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ - -/** - * RegExp to match quoted-pair in RFC 2616 - * - * quoted-pair = "\" CHAR - * CHAR = - */ -var qescRegExp = /\\([\u0000-\u007f])/g; - -/** - * RegExp to match chars that must be quoted-pair in RFC 2616 - */ -var quoteRegExp = /([\\"])/g; - -/** - * RegExp to match type in RFC 6838 - * - * type-name = restricted-name - * subtype-name = restricted-name - * restricted-name = restricted-name-first *126restricted-name-chars - * restricted-name-first = ALPHA / DIGIT - * restricted-name-chars = ALPHA / DIGIT / "!" / "#" / - * "$" / "&" / "-" / "^" / "_" - * restricted-name-chars =/ "." ; Characters before first dot always - * ; specify a facet name - * restricted-name-chars =/ "+" ; Characters after last plus always - * ; specify a structured syntax suffix - * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z - * DIGIT = %x30-39 ; 0-9 - */ -var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/ -var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/ -var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; - -/** - * Module exports. - */ - -exports.format = format -exports.parse = parse - -/** - * Format object to media type. - * - * @param {object} obj - * @return {string} - * @api public - */ - -function format(obj) { - if (!obj || typeof obj !== 'object') { - throw new TypeError('argument obj is required') - } - - var parameters = obj.parameters - var subtype = obj.subtype - var suffix = obj.suffix - var type = obj.type - - if (!type || !typeNameRegExp.test(type)) { - throw new TypeError('invalid type') - } - - if (!subtype || !subtypeNameRegExp.test(subtype)) { - throw new TypeError('invalid subtype') - } - - // format as type/subtype - var string = type + '/' + subtype - - // append +suffix - if (suffix) { - if (!typeNameRegExp.test(suffix)) { - throw new TypeError('invalid suffix') - } - - string += '+' + suffix - } - - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() - - for (var i = 0; i < params.length; i++) { - param = params[i] - - if (!tokenRegExp.test(param)) { - throw new TypeError('invalid parameter name') - } - - string += '; ' + param + '=' + qstring(parameters[param]) - } - } - - return string -} - -/** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @api public - */ - -function parse(string) { - if (!string) { - throw new TypeError('argument string is required') - } - - // support req/res-like objects as argument - if (typeof string === 'object') { - string = getcontenttype(string) - } - - if (typeof string !== 'string') { - throw new TypeError('argument string is required to be a string') - } - - var index = string.indexOf(';') - var type = index !== -1 - ? string.substr(0, index) - : string - - var key - var match - var obj = splitType(type) - var params = {} - var value - - paramRegExp.lastIndex = index - - while (match = paramRegExp.exec(string)) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } - - index += match[0].length - key = match[1].toLowerCase() - value = match[2] - - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(qescRegExp, '$1') - } - - params[key] = value - } - - if (index !== -1 && index !== string.length) { - throw new TypeError('invalid parameter format') - } - - obj.parameters = params - - return obj -} - -/** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @api private - */ - -function getcontenttype(obj) { - if (typeof obj.getHeader === 'function') { - // res-like - return obj.getHeader('content-type') - } - - if (typeof obj.headers === 'object') { - // req-like - return obj.headers && obj.headers['content-type'] - } -} - -/** - * Quote a string if necessary. - * - * @param {string} val - * @return {string} - * @api private - */ - -function qstring(val) { - var str = String(val) - - // no need to quote tokens - if (tokenRegExp.test(str)) { - return str - } - - if (str.length > 0 && !textRegExp.test(str)) { - throw new TypeError('invalid parameter value') - } - - return '"' + str.replace(quoteRegExp, '\\$1') + '"' -} - -/** - * Simply "type/subtype+siffx" into parts. - * - * @param {string} string - * @return {Object} - * @api private - */ - -function splitType(string) { - var match = typeRegExp.exec(string.toLowerCase()) - - if (!match) { - throw new TypeError('invalid media type') - } - - var type = match[1] - var subtype = match[2] - var suffix - - // suffix after last + - var index = subtype.lastIndexOf('+') - if (index !== -1) { - suffix = subtype.substr(index + 1) - subtype = subtype.substr(0, index) - } - - var obj = { - type: type, - subtype: subtype, - suffix: suffix - } - - return obj -} diff --git a/node_modules/media-typer/package.json b/node_modules/media-typer/package.json deleted file mode 100644 index 0056387..0000000 --- a/node_modules/media-typer/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "_from": "media-typer@0.3.0", - "_id": "media-typer@0.3.0", - "_inBundle": false, - "_integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", - "_location": "/media-typer", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "media-typer@0.3.0", - "name": "media-typer", - "escapedName": "media-typer", - "rawSpec": "0.3.0", - "saveSpec": null, - "fetchSpec": "0.3.0" - }, - "_requiredBy": [ - "/type-is" - ], - "_resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "_shasum": "8710d7af0aa626f8fffa1ce00168545263255748", - "_spec": "media-typer@0.3.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/type-is", - "author": { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - "bugs": { - "url": "https://github.com/jshttp/media-typer/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Simple RFC 6838 media type parser and formatter", - "devDependencies": { - "istanbul": "0.3.2", - "mocha": "~1.21.4", - "should": "~4.0.4" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "LICENSE", - "HISTORY.md", - "index.js" - ], - "homepage": "https://github.com/jshttp/media-typer#readme", - "license": "MIT", - "name": "media-typer", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/media-typer.git" - }, - "scripts": { - "test": "mocha --reporter spec --check-leaks --bail test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" - }, - "version": "0.3.0" -} diff --git a/node_modules/memory-pager/.travis.yml b/node_modules/memory-pager/.travis.yml deleted file mode 100644 index 1c4ab31..0000000 --- a/node_modules/memory-pager/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - '4' - - '6' diff --git a/node_modules/memory-pager/LICENSE b/node_modules/memory-pager/LICENSE deleted file mode 100644 index 56fce08..0000000 --- a/node_modules/memory-pager/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017 Mathias Buus - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -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/memory-pager/README.md b/node_modules/memory-pager/README.md deleted file mode 100644 index aed1761..0000000 --- a/node_modules/memory-pager/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# memory-pager - -Access memory using small fixed sized buffers instead of allocating a huge buffer. -Useful if you are implementing sparse data structures (such as large bitfield). - -![travis](https://travis-ci.org/mafintosh/memory-pager.svg?branch=master) - -``` -npm install memory-pager -``` - -## Usage - -``` js -var pager = require('paged-memory') - -var pages = pager(1024) // use 1kb per page - -var page = pages.get(10) // get page #10 - -console.log(page.offset) // 10240 -console.log(page.buffer) // a blank 1kb buffer -``` - -## API - -#### `var pages = pager(pageSize)` - -Create a new pager. `pageSize` defaults to `1024`. - -#### `var page = pages.get(pageNumber, [noAllocate])` - -Get a page. The page will be allocated at first access. - -Optionally you can set the `noAllocate` flag which will make the -method return undefined if no page has been allocated already - -A page looks like this - -``` js -{ - offset: byteOffset, - buffer: bufferWithPageSize -} -``` - -#### `pages.set(pageNumber, buffer)` - -Explicitly set the buffer for a page. - -#### `pages.updated(page)` - -Mark a page as updated. - -#### `pages.lastUpdate()` - -Get the last page that was updated. - -#### `var buf = pages.toBuffer()` - -Concat all pages allocated pages into a single buffer - -## License - -MIT diff --git a/node_modules/memory-pager/index.js b/node_modules/memory-pager/index.js deleted file mode 100644 index 687f346..0000000 --- a/node_modules/memory-pager/index.js +++ /dev/null @@ -1,160 +0,0 @@ -module.exports = Pager - -function Pager (pageSize, opts) { - if (!(this instanceof Pager)) return new Pager(pageSize, opts) - - this.length = 0 - this.updates = [] - this.path = new Uint16Array(4) - this.pages = new Array(32768) - this.maxPages = this.pages.length - this.level = 0 - this.pageSize = pageSize || 1024 - this.deduplicate = opts ? opts.deduplicate : null - this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null -} - -Pager.prototype.updated = function (page) { - while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) { - page.deduplicate++ - if (page.deduplicate === this.deduplicate.length) { - page.deduplicate = 0 - if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate - break - } - } - if (page.updated || !this.updates) return - page.updated = true - this.updates.push(page) -} - -Pager.prototype.lastUpdate = function () { - if (!this.updates || !this.updates.length) return null - var page = this.updates.pop() - page.updated = false - return page -} - -Pager.prototype._array = function (i, noAllocate) { - if (i >= this.maxPages) { - if (noAllocate) return - grow(this, i) - } - - factor(i, this.path) - - var arr = this.pages - - for (var j = this.level; j > 0; j--) { - var p = this.path[j] - var next = arr[p] - - if (!next) { - if (noAllocate) return - next = arr[p] = new Array(32768) - } - - arr = next - } - - return arr -} - -Pager.prototype.get = function (i, noAllocate) { - var arr = this._array(i, noAllocate) - var first = this.path[0] - var page = arr && arr[first] - - if (!page && !noAllocate) { - page = arr[first] = new Page(i, alloc(this.pageSize)) - if (i >= this.length) this.length = i + 1 - } - - if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { - page.buffer = copy(page.buffer) - page.deduplicate = 0 - } - - return page -} - -Pager.prototype.set = function (i, buf) { - var arr = this._array(i, false) - var first = this.path[0] - - if (i >= this.length) this.length = i + 1 - - if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) { - arr[first] = undefined - return - } - - if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { - buf = this.deduplicate - } - - var page = arr[first] - var b = truncate(buf, this.pageSize) - - if (page) page.buffer = b - else arr[first] = new Page(i, b) -} - -Pager.prototype.toBuffer = function () { - var list = new Array(this.length) - var empty = alloc(this.pageSize) - var ptr = 0 - - while (ptr < list.length) { - var arr = this._array(ptr, true) - for (var i = 0; i < 32768 && ptr < list.length; i++) { - list[ptr++] = (arr && arr[i]) ? arr[i].buffer : empty - } - } - - return Buffer.concat(list) -} - -function grow (pager, index) { - while (pager.maxPages < index) { - var old = pager.pages - pager.pages = new Array(32768) - pager.pages[0] = old - pager.level++ - pager.maxPages *= 32768 - } -} - -function truncate (buf, len) { - if (buf.length === len) return buf - if (buf.length > len) return buf.slice(0, len) - var cpy = alloc(len) - buf.copy(cpy) - return cpy -} - -function alloc (size) { - if (Buffer.alloc) return Buffer.alloc(size) - var buf = new Buffer(size) - buf.fill(0) - return buf -} - -function copy (buf) { - var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length) - buf.copy(cpy) - return cpy -} - -function Page (i, buf) { - this.offset = i * buf.length - this.buffer = buf - this.updated = false - this.deduplicate = 0 -} - -function factor (n, out) { - n = (n - (out[0] = (n & 32767))) / 32768 - n = (n - (out[1] = (n & 32767))) / 32768 - out[3] = ((n - (out[2] = (n & 32767))) / 32768) & 32767 -} diff --git a/node_modules/memory-pager/package.json b/node_modules/memory-pager/package.json deleted file mode 100644 index 5c26bda..0000000 --- a/node_modules/memory-pager/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "_from": "memory-pager@^1.0.2", - "_id": "memory-pager@1.5.0", - "_inBundle": false, - "_integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", - "_location": "/memory-pager", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "memory-pager@^1.0.2", - "name": "memory-pager", - "escapedName": "memory-pager", - "rawSpec": "^1.0.2", - "saveSpec": null, - "fetchSpec": "^1.0.2" - }, - "_requiredBy": [ - "/sparse-bitfield" - ], - "_resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", - "_shasum": "d8751655d22d384682741c972f2c3d6dfa3e66b5", - "_spec": "memory-pager@^1.0.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/sparse-bitfield", - "author": { - "name": "Mathias Buus", - "url": "@mafintosh" - }, - "bugs": { - "url": "https://github.com/mafintosh/memory-pager/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Access memory using small fixed sized buffers", - "devDependencies": { - "standard": "^9.0.0", - "tape": "^4.6.3" - }, - "homepage": "https://github.com/mafintosh/memory-pager", - "license": "MIT", - "main": "index.js", - "name": "memory-pager", - "repository": { - "type": "git", - "url": "git+https://github.com/mafintosh/memory-pager.git" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "version": "1.5.0" -} diff --git a/node_modules/memory-pager/test.js b/node_modules/memory-pager/test.js deleted file mode 100644 index 1638210..0000000 --- a/node_modules/memory-pager/test.js +++ /dev/null @@ -1,80 +0,0 @@ -var tape = require('tape') -var pager = require('./') - -tape('get page', function (t) { - var pages = pager(1024) - - var page = pages.get(0) - - t.same(page.offset, 0) - t.same(page.buffer, Buffer.alloc(1024)) - t.end() -}) - -tape('get page twice', function (t) { - var pages = pager(1024) - t.same(pages.length, 0) - - var page = pages.get(0) - - t.same(page.offset, 0) - t.same(page.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1) - - var other = pages.get(0) - - t.same(other, page) - t.end() -}) - -tape('get no mutable page', function (t) { - var pages = pager(1024) - - t.ok(!pages.get(141, true)) - t.ok(pages.get(141)) - t.ok(pages.get(141, true)) - - t.end() -}) - -tape('get far out page', function (t) { - var pages = pager(1024) - - var page = pages.get(1000000) - - t.same(page.offset, 1000000 * 1024) - t.same(page.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1000000 + 1) - - var other = pages.get(1) - - t.same(other.offset, 1024) - t.same(other.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1000000 + 1) - t.ok(other !== page) - - t.end() -}) - -tape('updates', function (t) { - var pages = pager(1024) - - t.same(pages.lastUpdate(), null) - - var page = pages.get(10) - - page.buffer[42] = 1 - pages.updated(page) - - t.same(pages.lastUpdate(), page) - t.same(pages.lastUpdate(), null) - - page.buffer[42] = 2 - pages.updated(page) - pages.updated(page) - - t.same(pages.lastUpdate(), page) - t.same(pages.lastUpdate(), null) - - t.end() -}) diff --git a/node_modules/merge-descriptors/HISTORY.md b/node_modules/merge-descriptors/HISTORY.md deleted file mode 100644 index 486771f..0000000 --- a/node_modules/merge-descriptors/HISTORY.md +++ /dev/null @@ -1,21 +0,0 @@ -1.0.1 / 2016-01-17 -================== - - * perf: enable strict mode - -1.0.0 / 2015-03-01 -================== - - * Add option to only add new descriptors - * Add simple argument validation - * Add jsdoc to source file - -0.0.2 / 2013-12-14 -================== - - * Move repository to `component` organization - -0.0.1 / 2013-10-29 -================== - - * Initial release diff --git a/node_modules/merge-descriptors/LICENSE b/node_modules/merge-descriptors/LICENSE deleted file mode 100644 index 274bfd8..0000000 --- a/node_modules/merge-descriptors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -(The MIT License) - -Copyright (c) 2013 Jonathan Ong -Copyright (c) 2015 Douglas Christopher Wilson - -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/merge-descriptors/README.md b/node_modules/merge-descriptors/README.md deleted file mode 100644 index d593c0e..0000000 --- a/node_modules/merge-descriptors/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# Merge Descriptors - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Merge objects using descriptors. - -```js -var thing = { - get name() { - return 'jon' - } -} - -var animal = { - -} - -merge(animal, thing) - -animal.name === 'jon' -``` - -## API - -### merge(destination, source) - -Redefines `destination`'s descriptors with `source`'s. - -### merge(destination, source, false) - -Defines `source`'s descriptors on `destination` if `destination` does not have -a descriptor by the same name. - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/merge-descriptors.svg -[npm-url]: https://npmjs.org/package/merge-descriptors -[travis-image]: https://img.shields.io/travis/component/merge-descriptors/master.svg -[travis-url]: https://travis-ci.org/component/merge-descriptors -[coveralls-image]: https://img.shields.io/coveralls/component/merge-descriptors/master.svg -[coveralls-url]: https://coveralls.io/r/component/merge-descriptors?branch=master -[downloads-image]: https://img.shields.io/npm/dm/merge-descriptors.svg -[downloads-url]: https://npmjs.org/package/merge-descriptors diff --git a/node_modules/merge-descriptors/index.js b/node_modules/merge-descriptors/index.js deleted file mode 100644 index 573b132..0000000 --- a/node_modules/merge-descriptors/index.js +++ /dev/null @@ -1,60 +0,0 @@ -/*! - * merge-descriptors - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module exports. - * @public - */ - -module.exports = merge - -/** - * Module variables. - * @private - */ - -var hasOwnProperty = Object.prototype.hasOwnProperty - -/** - * Merge the property descriptors of `src` into `dest` - * - * @param {object} dest Object to add descriptors to - * @param {object} src Object to clone descriptors from - * @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties - * @returns {object} Reference to dest - * @public - */ - -function merge(dest, src, redefine) { - if (!dest) { - throw new TypeError('argument dest is required') - } - - if (!src) { - throw new TypeError('argument src is required') - } - - if (redefine === undefined) { - // Default to true - redefine = true - } - - Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) { - if (!redefine && hasOwnProperty.call(dest, name)) { - // Skip desriptor - return - } - - // Copy descriptor - var descriptor = Object.getOwnPropertyDescriptor(src, name) - Object.defineProperty(dest, name, descriptor) - }) - - return dest -} diff --git a/node_modules/merge-descriptors/package.json b/node_modules/merge-descriptors/package.json deleted file mode 100644 index 075b58f..0000000 --- a/node_modules/merge-descriptors/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "merge-descriptors@1.0.1", - "_id": "merge-descriptors@1.0.1", - "_inBundle": false, - "_integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=", - "_location": "/merge-descriptors", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "merge-descriptors@1.0.1", - "name": "merge-descriptors", - "escapedName": "merge-descriptors", - "rawSpec": "1.0.1", - "saveSpec": null, - "fetchSpec": "1.0.1" - }, - "_requiredBy": [ - "/express" - ], - "_resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", - "_shasum": "b00aaa556dd8b44568150ec9d1b953f3f90cbb61", - "_spec": "merge-descriptors@1.0.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "author": { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - }, - "bugs": { - "url": "https://github.com/component/merge-descriptors/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "Mike Grabowski", - "email": "grabbou@gmail.com" - } - ], - "deprecated": false, - "description": "Merge objects using descriptors", - "devDependencies": { - "istanbul": "0.4.1", - "mocha": "1.21.5" - }, - "files": [ - "HISTORY.md", - "LICENSE", - "README.md", - "index.js" - ], - "homepage": "https://github.com/component/merge-descriptors#readme", - "license": "MIT", - "name": "merge-descriptors", - "repository": { - "type": "git", - "url": "git+https://github.com/component/merge-descriptors.git" - }, - "scripts": { - "test": "mocha --reporter spec --bail --check-leaks test/", - "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" - }, - "version": "1.0.1" -} diff --git a/node_modules/methods/HISTORY.md b/node_modules/methods/HISTORY.md deleted file mode 100644 index c0ecf07..0000000 --- a/node_modules/methods/HISTORY.md +++ /dev/null @@ -1,29 +0,0 @@ -1.1.2 / 2016-01-17 -================== - - * perf: enable strict mode - -1.1.1 / 2014-12-30 -================== - - * Improve `browserify` support - -1.1.0 / 2014-07-05 -================== - - * Add `CONNECT` method - -1.0.1 / 2014-06-02 -================== - - * Fix module to work with harmony transform - -1.0.0 / 2014-05-08 -================== - - * Add `PURGE` method - -0.1.0 / 2013-10-28 -================== - - * Add `http.METHODS` support diff --git a/node_modules/methods/LICENSE b/node_modules/methods/LICENSE deleted file mode 100644 index 220dc1a..0000000 --- a/node_modules/methods/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2013-2014 TJ Holowaychuk -Copyright (c) 2015-2016 Douglas Christopher Wilson - -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/methods/README.md b/node_modules/methods/README.md deleted file mode 100644 index 672a32b..0000000 --- a/node_modules/methods/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# Methods - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -HTTP verbs that Node.js core's HTTP parser supports. - -This module provides an export that is just like `http.METHODS` from Node.js core, -with the following differences: - - * All method names are lower-cased. - * Contains a fallback list of methods for Node.js versions that do not have a - `http.METHODS` export (0.10 and lower). - * Provides the fallback list when using tools like `browserify` without pulling - in the `http` shim module. - -## Install - -```bash -$ npm install methods -``` - -## API - -```js -var methods = require('methods') -``` - -### methods - -This is an array of lower-cased method names that Node.js supports. If Node.js -provides the `http.METHODS` export, then this is the same array lower-cased, -otherwise it is a snapshot of the verbs from Node.js 0.10. - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/methods.svg?style=flat -[npm-url]: https://npmjs.org/package/methods -[node-version-image]: https://img.shields.io/node/v/methods.svg?style=flat -[node-version-url]: https://nodejs.org/en/download/ -[travis-image]: https://img.shields.io/travis/jshttp/methods.svg?style=flat -[travis-url]: https://travis-ci.org/jshttp/methods -[coveralls-image]: https://img.shields.io/coveralls/jshttp/methods.svg?style=flat -[coveralls-url]: https://coveralls.io/r/jshttp/methods?branch=master -[downloads-image]: https://img.shields.io/npm/dm/methods.svg?style=flat -[downloads-url]: https://npmjs.org/package/methods diff --git a/node_modules/methods/index.js b/node_modules/methods/index.js deleted file mode 100644 index 667a50b..0000000 --- a/node_modules/methods/index.js +++ /dev/null @@ -1,69 +0,0 @@ -/*! - * methods - * Copyright(c) 2013-2014 TJ Holowaychuk - * Copyright(c) 2015-2016 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module dependencies. - * @private - */ - -var http = require('http'); - -/** - * Module exports. - * @public - */ - -module.exports = getCurrentNodeMethods() || getBasicNodeMethods(); - -/** - * Get the current Node.js methods. - * @private - */ - -function getCurrentNodeMethods() { - return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) { - return method.toLowerCase(); - }); -} - -/** - * Get the "basic" Node.js methods, a snapshot from Node.js 0.10. - * @private - */ - -function getBasicNodeMethods() { - return [ - 'get', - 'post', - 'put', - 'head', - 'delete', - 'options', - 'trace', - 'copy', - 'lock', - 'mkcol', - 'move', - 'purge', - 'propfind', - 'proppatch', - 'unlock', - 'report', - 'mkactivity', - 'checkout', - 'merge', - 'm-search', - 'notify', - 'subscribe', - 'unsubscribe', - 'patch', - 'search', - 'connect' - ]; -} diff --git a/node_modules/methods/package.json b/node_modules/methods/package.json deleted file mode 100644 index 23232fd..0000000 --- a/node_modules/methods/package.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "_from": "methods@~1.1.2", - "_id": "methods@1.1.2", - "_inBundle": false, - "_integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=", - "_location": "/methods", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "methods@~1.1.2", - "name": "methods", - "escapedName": "methods", - "rawSpec": "~1.1.2", - "saveSpec": null, - "fetchSpec": "~1.1.2" - }, - "_requiredBy": [ - "/express" - ], - "_resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "_shasum": "5529a4d67654134edcc5266656835b0f851afcee", - "_spec": "methods@~1.1.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/express", - "browser": { - "http": false - }, - "bugs": { - "url": "https://github.com/jshttp/methods/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - }, - { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - } - ], - "deprecated": false, - "description": "HTTP methods that node supports", - "devDependencies": { - "istanbul": "0.4.1", - "mocha": "1.21.5" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "index.js", - "HISTORY.md", - "LICENSE" - ], - "homepage": "https://github.com/jshttp/methods#readme", - "keywords": [ - "http", - "methods" - ], - "license": "MIT", - "name": "methods", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/methods.git" - }, - "scripts": { - "test": "mocha --reporter spec --bail --check-leaks test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" - }, - "version": "1.1.2" -} diff --git a/node_modules/mime-db/HISTORY.md b/node_modules/mime-db/HISTORY.md deleted file mode 100644 index 85c0319..0000000 --- a/node_modules/mime-db/HISTORY.md +++ /dev/null @@ -1,446 +0,0 @@ -1.44.0 / 2020-04-22 -=================== - - * Add charsets from IANA - * Add extension `.cjs` to `application/node` - * Add new upstream MIME types - -1.43.0 / 2020-01-05 -=================== - - * Add `application/x-keepass2` with extension `.kdbx` - * Add extension `.mxmf` to `audio/mobile-xmf` - * Add extensions from IANA for `application/*+xml` types - * Add new upstream MIME types - -1.42.0 / 2019-09-25 -=================== - - * Add `image/vnd.ms-dds` with extension `.dds` - * Add new upstream MIME types - * Remove compressible from `multipart/mixed` - -1.41.0 / 2019-08-30 -=================== - - * Add new upstream MIME types - * Add `application/toml` with extension `.toml` - * Mark `font/ttf` as compressible - -1.40.0 / 2019-04-20 -=================== - - * Add extensions from IANA for `model/*` types - * Add `text/mdx` with extension `.mdx` - -1.39.0 / 2019-04-04 -=================== - - * Add extensions `.siv` and `.sieve` to `application/sieve` - * Add new upstream MIME types - -1.38.0 / 2019-02-04 -=================== - - * Add extension `.nq` to `application/n-quads` - * Add extension `.nt` to `application/n-triples` - * Add new upstream MIME types - * Mark `text/less` as compressible - -1.37.0 / 2018-10-19 -=================== - - * Add extensions to HEIC image types - * Add new upstream MIME types - -1.36.0 / 2018-08-20 -=================== - - * Add Apple file extensions from IANA - * Add extensions from IANA for `image/*` types - * Add new upstream MIME types - -1.35.0 / 2018-07-15 -=================== - - * Add extension `.owl` to `application/rdf+xml` - * Add new upstream MIME types - - Removes extension `.woff` from `application/font-woff` - -1.34.0 / 2018-06-03 -=================== - - * Add extension `.csl` to `application/vnd.citationstyles.style+xml` - * Add extension `.es` to `application/ecmascript` - * Add new upstream MIME types - * Add `UTF-8` as default charset for `text/turtle` - * Mark all XML-derived types as compressible - -1.33.0 / 2018-02-15 -=================== - - * Add extensions from IANA for `message/*` types - * Add new upstream MIME types - * Fix some incorrect OOXML types - * Remove `application/font-woff2` - -1.32.0 / 2017-11-29 -=================== - - * Add new upstream MIME types - * Update `text/hjson` to registered `application/hjson` - * Add `text/shex` with extension `.shex` - -1.31.0 / 2017-10-25 -=================== - - * Add `application/raml+yaml` with extension `.raml` - * Add `application/wasm` with extension `.wasm` - * Add new `font` type from IANA - * Add new upstream font extensions - * Add new upstream MIME types - * Add extensions for JPEG-2000 images - -1.30.0 / 2017-08-27 -=================== - - * Add `application/vnd.ms-outlook` - * Add `application/x-arj` - * Add extension `.mjs` to `application/javascript` - * Add glTF types and extensions - * Add new upstream MIME types - * Add `text/x-org` - * Add VirtualBox MIME types - * Fix `source` records for `video/*` types that are IANA - * Update `font/opentype` to registered `font/otf` - -1.29.0 / 2017-07-10 -=================== - - * Add `application/fido.trusted-apps+json` - * Add extension `.wadl` to `application/vnd.sun.wadl+xml` - * Add new upstream MIME types - * Add `UTF-8` as default charset for `text/css` - -1.28.0 / 2017-05-14 -=================== - - * Add new upstream MIME types - * Add extension `.gz` to `application/gzip` - * Update extensions `.md` and `.markdown` to be `text/markdown` - -1.27.0 / 2017-03-16 -=================== - - * Add new upstream MIME types - * Add `image/apng` with extension `.apng` - -1.26.0 / 2017-01-14 -=================== - - * Add new upstream MIME types - * Add extension `.geojson` to `application/geo+json` - -1.25.0 / 2016-11-11 -=================== - - * Add new upstream MIME types - -1.24.0 / 2016-09-18 -=================== - - * Add `audio/mp3` - * Add new upstream MIME types - -1.23.0 / 2016-05-01 -=================== - - * Add new upstream MIME types - * Add extension `.3gpp` to `audio/3gpp` - -1.22.0 / 2016-02-15 -=================== - - * Add `text/slim` - * Add extension `.rng` to `application/xml` - * Add new upstream MIME types - * Fix extension of `application/dash+xml` to be `.mpd` - * Update primary extension to `.m4a` for `audio/mp4` - -1.21.0 / 2016-01-06 -=================== - - * Add Google document types - * Add new upstream MIME types - -1.20.0 / 2015-11-10 -=================== - - * Add `text/x-suse-ymp` - * Add new upstream MIME types - -1.19.0 / 2015-09-17 -=================== - - * Add `application/vnd.apple.pkpass` - * Add new upstream MIME types - -1.18.0 / 2015-09-03 -=================== - - * Add new upstream MIME types - -1.17.0 / 2015-08-13 -=================== - - * Add `application/x-msdos-program` - * Add `audio/g711-0` - * Add `image/vnd.mozilla.apng` - * Add extension `.exe` to `application/x-msdos-program` - -1.16.0 / 2015-07-29 -=================== - - * Add `application/vnd.uri-map` - -1.15.0 / 2015-07-13 -=================== - - * Add `application/x-httpd-php` - -1.14.0 / 2015-06-25 -=================== - - * Add `application/scim+json` - * Add `application/vnd.3gpp.ussd+xml` - * Add `application/vnd.biopax.rdf+xml` - * Add `text/x-processing` - -1.13.0 / 2015-06-07 -=================== - - * Add nginx as a source - * Add `application/x-cocoa` - * Add `application/x-java-archive-diff` - * Add `application/x-makeself` - * Add `application/x-perl` - * Add `application/x-pilot` - * Add `application/x-redhat-package-manager` - * Add `application/x-sea` - * Add `audio/x-m4a` - * Add `audio/x-realaudio` - * Add `image/x-jng` - * Add `text/mathml` - -1.12.0 / 2015-06-05 -=================== - - * Add `application/bdoc` - * Add `application/vnd.hyperdrive+json` - * Add `application/x-bdoc` - * Add extension `.rtf` to `text/rtf` - -1.11.0 / 2015-05-31 -=================== - - * Add `audio/wav` - * Add `audio/wave` - * Add extension `.litcoffee` to `text/coffeescript` - * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` - * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` - -1.10.0 / 2015-05-19 -=================== - - * Add `application/vnd.balsamiq.bmpr` - * Add `application/vnd.microsoft.portable-executable` - * Add `application/x-ns-proxy-autoconfig` - -1.9.1 / 2015-04-19 -================== - - * Remove `.json` extension from `application/manifest+json` - - This is causing bugs downstream - -1.9.0 / 2015-04-19 -================== - - * Add `application/manifest+json` - * Add `application/vnd.micro+json` - * Add `image/vnd.zbrush.pcx` - * Add `image/x-ms-bmp` - -1.8.0 / 2015-03-13 -================== - - * Add `application/vnd.citationstyles.style+xml` - * Add `application/vnd.fastcopy-disk-image` - * Add `application/vnd.gov.sk.xmldatacontainer+xml` - * Add extension `.jsonld` to `application/ld+json` - -1.7.0 / 2015-02-08 -================== - - * Add `application/vnd.gerber` - * Add `application/vnd.msa-disk-image` - -1.6.1 / 2015-02-05 -================== - - * Community extensions ownership transferred from `node-mime` - -1.6.0 / 2015-01-29 -================== - - * Add `application/jose` - * Add `application/jose+json` - * Add `application/json-seq` - * Add `application/jwk+json` - * Add `application/jwk-set+json` - * Add `application/jwt` - * Add `application/rdap+json` - * Add `application/vnd.gov.sk.e-form+xml` - * Add `application/vnd.ims.imsccv1p3` - -1.5.0 / 2014-12-30 -================== - - * Add `application/vnd.oracle.resource+json` - * Fix various invalid MIME type entries - - `application/mbox+xml` - - `application/oscp-response` - - `application/vwg-multiplexed` - - `audio/g721` - -1.4.0 / 2014-12-21 -================== - - * Add `application/vnd.ims.imsccv1p2` - * Fix various invalid MIME type entries - - `application/vnd-acucobol` - - `application/vnd-curl` - - `application/vnd-dart` - - `application/vnd-dxr` - - `application/vnd-fdf` - - `application/vnd-mif` - - `application/vnd-sema` - - `application/vnd-wap-wmlc` - - `application/vnd.adobe.flash-movie` - - `application/vnd.dece-zip` - - `application/vnd.dvb_service` - - `application/vnd.micrografx-igx` - - `application/vnd.sealed-doc` - - `application/vnd.sealed-eml` - - `application/vnd.sealed-mht` - - `application/vnd.sealed-ppt` - - `application/vnd.sealed-tiff` - - `application/vnd.sealed-xls` - - `application/vnd.sealedmedia.softseal-html` - - `application/vnd.sealedmedia.softseal-pdf` - - `application/vnd.wap-slc` - - `application/vnd.wap-wbxml` - - `audio/vnd.sealedmedia.softseal-mpeg` - - `image/vnd-djvu` - - `image/vnd-svf` - - `image/vnd-wap-wbmp` - - `image/vnd.sealed-png` - - `image/vnd.sealedmedia.softseal-gif` - - `image/vnd.sealedmedia.softseal-jpg` - - `model/vnd-dwf` - - `model/vnd.parasolid.transmit-binary` - - `model/vnd.parasolid.transmit-text` - - `text/vnd-a` - - `text/vnd-curl` - - `text/vnd.wap-wml` - * Remove example template MIME types - - `application/example` - - `audio/example` - - `image/example` - - `message/example` - - `model/example` - - `multipart/example` - - `text/example` - - `video/example` - -1.3.1 / 2014-12-16 -================== - - * Fix missing extensions - - `application/json5` - - `text/hjson` - -1.3.0 / 2014-12-07 -================== - - * Add `application/a2l` - * Add `application/aml` - * Add `application/atfx` - * Add `application/atxml` - * Add `application/cdfx+xml` - * Add `application/dii` - * Add `application/json5` - * Add `application/lxf` - * Add `application/mf4` - * Add `application/vnd.apache.thrift.compact` - * Add `application/vnd.apache.thrift.json` - * Add `application/vnd.coffeescript` - * Add `application/vnd.enphase.envoy` - * Add `application/vnd.ims.imsccv1p1` - * Add `text/csv-schema` - * Add `text/hjson` - * Add `text/markdown` - * Add `text/yaml` - -1.2.0 / 2014-11-09 -================== - - * Add `application/cea` - * Add `application/dit` - * Add `application/vnd.gov.sk.e-form+zip` - * Add `application/vnd.tmd.mediaflex.api+xml` - * Type `application/epub+zip` is now IANA-registered - -1.1.2 / 2014-10-23 -================== - - * Rebuild database for `application/x-www-form-urlencoded` change - -1.1.1 / 2014-10-20 -================== - - * Mark `application/x-www-form-urlencoded` as compressible. - -1.1.0 / 2014-09-28 -================== - - * Add `application/font-woff2` - -1.0.3 / 2014-09-25 -================== - - * Fix engine requirement in package - -1.0.2 / 2014-09-25 -================== - - * Add `application/coap-group+json` - * Add `application/dcd` - * Add `application/vnd.apache.thrift.binary` - * Add `image/vnd.tencent.tap` - * Mark all JSON-derived types as compressible - * Update `text/vtt` data - -1.0.1 / 2014-08-30 -================== - - * Fix extension ordering - -1.0.0 / 2014-08-30 -================== - - * Add `application/atf` - * Add `application/merge-patch+json` - * Add `multipart/x-mixed-replace` - * Add `source: 'apache'` metadata - * Add `source: 'iana'` metadata - * Remove badly-assumed charset data diff --git a/node_modules/mime-db/LICENSE b/node_modules/mime-db/LICENSE deleted file mode 100644 index a7ae8ee..0000000 --- a/node_modules/mime-db/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ - -The MIT License (MIT) - -Copyright (c) 2014 Jonathan Ong me@jongleberry.com - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/mime-db/README.md b/node_modules/mime-db/README.md deleted file mode 100644 index d6a6f80..0000000 --- a/node_modules/mime-db/README.md +++ /dev/null @@ -1,102 +0,0 @@ -# mime-db - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][npm-url] -[![Node.js Version][node-image]][node-url] -[![Build Status][travis-image]][travis-url] -[![Coverage Status][coveralls-image]][coveralls-url] - -This is a database of all mime types. -It consists of a single, public JSON file and does not include any logic, -allowing it to remain as un-opinionated as possible with an API. -It aggregates data from the following sources: - -- http://www.iana.org/assignments/media-types/media-types.xhtml -- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types -- http://hg.nginx.org/nginx/raw-file/default/conf/mime.types - -## Installation - -```bash -npm install mime-db -``` - -### Database Download - -If you're crazy enough to use this in the browser, you can just grab the -JSON file using [jsDelivr](https://www.jsdelivr.com/). It is recommended to -replace `master` with [a release tag](https://github.com/jshttp/mime-db/tags) -as the JSON format may change in the future. - -``` -https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json -``` - -## Usage - - - -```js -var db = require('mime-db') - -// grab data on .js files -var data = db['application/javascript'] -``` - -## Data Structure - -The JSON file is a map lookup for lowercased mime types. -Each mime type has the following properties: - -- `.source` - where the mime type is defined. - If not set, it's probably a custom media type. - - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) - - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) - - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) -- `.extensions[]` - known extensions associated with this mime type. -- `.compressible` - whether a file of this type can be gzipped. -- `.charset` - the default charset associated with this type, if any. - -If unknown, every property could be `undefined`. - -## Contributing - -To edit the database, only make PRs against `src/custom.json` or -`src/custom-suffix.json`. - -The `src/custom.json` file is a JSON object with the MIME type as the keys -and the values being an object with the following keys: - -- `compressible` - leave out if you don't know, otherwise `true`/`false` to - indicate whether the data represented by the type is typically compressible. -- `extensions` - include an array of file extensions that are associated with - the type. -- `notes` - human-readable notes about the type, typically what the type is. -- `sources` - include an array of URLs of where the MIME type and the associated - extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); - links to type aggregating sites and Wikipedia are _not acceptable_. - -To update the build, run `npm run build`. - -### Adding Custom Media Types - -The best way to get new media types included in this library is to register -them with the IANA. The community registration procedure is outlined in -[RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types -registered with the IANA are automatically pulled into this library. - -If that is not possible / feasible, they can be added directly here as a -"custom" type. To do this, it is required to have a primary source that -definitively lists the media type. If an extension is going to be listed as -associateed with this media type, the source must definitively link the -media type and extension as well. - -[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master -[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master -[node-image]: https://badgen.net/npm/node/mime-db -[node-url]: https://nodejs.org/en/download -[npm-downloads-image]: https://badgen.net/npm/dm/mime-db -[npm-url]: https://npmjs.org/package/mime-db -[npm-version-image]: https://badgen.net/npm/v/mime-db -[travis-image]: https://badgen.net/travis/jshttp/mime-db/master -[travis-url]: https://travis-ci.org/jshttp/mime-db diff --git a/node_modules/mime-db/db.json b/node_modules/mime-db/db.json deleted file mode 100644 index e69f352..0000000 --- a/node_modules/mime-db/db.json +++ /dev/null @@ -1,8176 +0,0 @@ -{ - "application/1d-interleaved-parityfec": { - "source": "iana" - }, - "application/3gpdash-qoe-report+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/3gpp-ims+xml": { - "source": "iana", - "compressible": true - }, - "application/a2l": { - "source": "iana" - }, - "application/activemessage": { - "source": "iana" - }, - "application/activity+json": { - "source": "iana", - "compressible": true - }, - "application/alto-costmap+json": { - "source": "iana", - "compressible": true - }, - "application/alto-costmapfilter+json": { - "source": "iana", - "compressible": true - }, - "application/alto-directory+json": { - "source": "iana", - "compressible": true - }, - "application/alto-endpointcost+json": { - "source": "iana", - "compressible": true - }, - "application/alto-endpointcostparams+json": { - "source": "iana", - "compressible": true - }, - "application/alto-endpointprop+json": { - "source": "iana", - "compressible": true - }, - "application/alto-endpointpropparams+json": { - "source": "iana", - "compressible": true - }, - "application/alto-error+json": { - "source": "iana", - "compressible": true - }, - "application/alto-networkmap+json": { - "source": "iana", - "compressible": true - }, - "application/alto-networkmapfilter+json": { - "source": "iana", - "compressible": true - }, - "application/alto-updatestreamcontrol+json": { - "source": "iana", - "compressible": true - }, - "application/alto-updatestreamparams+json": { - "source": "iana", - "compressible": true - }, - "application/aml": { - "source": "iana" - }, - "application/andrew-inset": { - "source": "iana", - "extensions": ["ez"] - }, - "application/applefile": { - "source": "iana" - }, - "application/applixware": { - "source": "apache", - "extensions": ["aw"] - }, - "application/atf": { - "source": "iana" - }, - "application/atfx": { - "source": "iana" - }, - "application/atom+xml": { - "source": "iana", - "compressible": true, - "extensions": ["atom"] - }, - "application/atomcat+xml": { - "source": "iana", - "compressible": true, - "extensions": ["atomcat"] - }, - "application/atomdeleted+xml": { - "source": "iana", - "compressible": true, - "extensions": ["atomdeleted"] - }, - "application/atomicmail": { - "source": "iana" - }, - "application/atomsvc+xml": { - "source": "iana", - "compressible": true, - "extensions": ["atomsvc"] - }, - "application/atsc-dwd+xml": { - "source": "iana", - "compressible": true, - "extensions": ["dwd"] - }, - "application/atsc-dynamic-event-message": { - "source": "iana" - }, - "application/atsc-held+xml": { - "source": "iana", - "compressible": true, - "extensions": ["held"] - }, - "application/atsc-rdt+json": { - "source": "iana", - "compressible": true - }, - "application/atsc-rsat+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rsat"] - }, - "application/atxml": { - "source": "iana" - }, - "application/auth-policy+xml": { - "source": "iana", - "compressible": true - }, - "application/bacnet-xdd+zip": { - "source": "iana", - "compressible": false - }, - "application/batch-smtp": { - "source": "iana" - }, - "application/bdoc": { - "compressible": false, - "extensions": ["bdoc"] - }, - "application/beep+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/calendar+json": { - "source": "iana", - "compressible": true - }, - "application/calendar+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xcs"] - }, - "application/call-completion": { - "source": "iana" - }, - "application/cals-1840": { - "source": "iana" - }, - "application/cap+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/cbor": { - "source": "iana" - }, - "application/cbor-seq": { - "source": "iana" - }, - "application/cccex": { - "source": "iana" - }, - "application/ccmp+xml": { - "source": "iana", - "compressible": true - }, - "application/ccxml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["ccxml"] - }, - "application/cdfx+xml": { - "source": "iana", - "compressible": true, - "extensions": ["cdfx"] - }, - "application/cdmi-capability": { - "source": "iana", - "extensions": ["cdmia"] - }, - "application/cdmi-container": { - "source": "iana", - "extensions": ["cdmic"] - }, - "application/cdmi-domain": { - "source": "iana", - "extensions": ["cdmid"] - }, - "application/cdmi-object": { - "source": "iana", - "extensions": ["cdmio"] - }, - "application/cdmi-queue": { - "source": "iana", - "extensions": ["cdmiq"] - }, - "application/cdni": { - "source": "iana" - }, - "application/cea": { - "source": "iana" - }, - "application/cea-2018+xml": { - "source": "iana", - "compressible": true - }, - "application/cellml+xml": { - "source": "iana", - "compressible": true - }, - "application/cfw": { - "source": "iana" - }, - "application/clue+xml": { - "source": "iana", - "compressible": true - }, - "application/clue_info+xml": { - "source": "iana", - "compressible": true - }, - "application/cms": { - "source": "iana" - }, - "application/cnrp+xml": { - "source": "iana", - "compressible": true - }, - "application/coap-group+json": { - "source": "iana", - "compressible": true - }, - "application/coap-payload": { - "source": "iana" - }, - "application/commonground": { - "source": "iana" - }, - "application/conference-info+xml": { - "source": "iana", - "compressible": true - }, - "application/cose": { - "source": "iana" - }, - "application/cose-key": { - "source": "iana" - }, - "application/cose-key-set": { - "source": "iana" - }, - "application/cpl+xml": { - "source": "iana", - "compressible": true - }, - "application/csrattrs": { - "source": "iana" - }, - "application/csta+xml": { - "source": "iana", - "compressible": true - }, - "application/cstadata+xml": { - "source": "iana", - "compressible": true - }, - "application/csvm+json": { - "source": "iana", - "compressible": true - }, - "application/cu-seeme": { - "source": "apache", - "extensions": ["cu"] - }, - "application/cwt": { - "source": "iana" - }, - "application/cybercash": { - "source": "iana" - }, - "application/dart": { - "compressible": true - }, - "application/dash+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mpd"] - }, - "application/dashdelta": { - "source": "iana" - }, - "application/davmount+xml": { - "source": "iana", - "compressible": true, - "extensions": ["davmount"] - }, - "application/dca-rft": { - "source": "iana" - }, - "application/dcd": { - "source": "iana" - }, - "application/dec-dx": { - "source": "iana" - }, - "application/dialog-info+xml": { - "source": "iana", - "compressible": true - }, - "application/dicom": { - "source": "iana" - }, - "application/dicom+json": { - "source": "iana", - "compressible": true - }, - "application/dicom+xml": { - "source": "iana", - "compressible": true - }, - "application/dii": { - "source": "iana" - }, - "application/dit": { - "source": "iana" - }, - "application/dns": { - "source": "iana" - }, - "application/dns+json": { - "source": "iana", - "compressible": true - }, - "application/dns-message": { - "source": "iana" - }, - "application/docbook+xml": { - "source": "apache", - "compressible": true, - "extensions": ["dbk"] - }, - "application/dots+cbor": { - "source": "iana" - }, - "application/dskpp+xml": { - "source": "iana", - "compressible": true - }, - "application/dssc+der": { - "source": "iana", - "extensions": ["dssc"] - }, - "application/dssc+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xdssc"] - }, - "application/dvcs": { - "source": "iana" - }, - "application/ecmascript": { - "source": "iana", - "compressible": true, - "extensions": ["ecma","es"] - }, - "application/edi-consent": { - "source": "iana" - }, - "application/edi-x12": { - "source": "iana", - "compressible": false - }, - "application/edifact": { - "source": "iana", - "compressible": false - }, - "application/efi": { - "source": "iana" - }, - "application/emergencycalldata.comment+xml": { - "source": "iana", - "compressible": true - }, - "application/emergencycalldata.control+xml": { - "source": "iana", - "compressible": true - }, - "application/emergencycalldata.deviceinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/emergencycalldata.ecall.msd": { - "source": "iana" - }, - "application/emergencycalldata.providerinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/emergencycalldata.serviceinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/emergencycalldata.subscriberinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/emergencycalldata.veds+xml": { - "source": "iana", - "compressible": true - }, - "application/emma+xml": { - "source": "iana", - "compressible": true, - "extensions": ["emma"] - }, - "application/emotionml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["emotionml"] - }, - "application/encaprtp": { - "source": "iana" - }, - "application/epp+xml": { - "source": "iana", - "compressible": true - }, - "application/epub+zip": { - "source": "iana", - "compressible": false, - "extensions": ["epub"] - }, - "application/eshop": { - "source": "iana" - }, - "application/exi": { - "source": "iana", - "extensions": ["exi"] - }, - "application/expect-ct-report+json": { - "source": "iana", - "compressible": true - }, - "application/fastinfoset": { - "source": "iana" - }, - "application/fastsoap": { - "source": "iana" - }, - "application/fdt+xml": { - "source": "iana", - "compressible": true, - "extensions": ["fdt"] - }, - "application/fhir+json": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/fhir+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/fido.trusted-apps+json": { - "compressible": true - }, - "application/fits": { - "source": "iana" - }, - "application/flexfec": { - "source": "iana" - }, - "application/font-sfnt": { - "source": "iana" - }, - "application/font-tdpfr": { - "source": "iana", - "extensions": ["pfr"] - }, - "application/font-woff": { - "source": "iana", - "compressible": false - }, - "application/framework-attributes+xml": { - "source": "iana", - "compressible": true - }, - "application/geo+json": { - "source": "iana", - "compressible": true, - "extensions": ["geojson"] - }, - "application/geo+json-seq": { - "source": "iana" - }, - "application/geopackage+sqlite3": { - "source": "iana" - }, - "application/geoxacml+xml": { - "source": "iana", - "compressible": true - }, - "application/gltf-buffer": { - "source": "iana" - }, - "application/gml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["gml"] - }, - "application/gpx+xml": { - "source": "apache", - "compressible": true, - "extensions": ["gpx"] - }, - "application/gxf": { - "source": "apache", - "extensions": ["gxf"] - }, - "application/gzip": { - "source": "iana", - "compressible": false, - "extensions": ["gz"] - }, - "application/h224": { - "source": "iana" - }, - "application/held+xml": { - "source": "iana", - "compressible": true - }, - "application/hjson": { - "extensions": ["hjson"] - }, - "application/http": { - "source": "iana" - }, - "application/hyperstudio": { - "source": "iana", - "extensions": ["stk"] - }, - "application/ibe-key-request+xml": { - "source": "iana", - "compressible": true - }, - "application/ibe-pkg-reply+xml": { - "source": "iana", - "compressible": true - }, - "application/ibe-pp-data": { - "source": "iana" - }, - "application/iges": { - "source": "iana" - }, - "application/im-iscomposing+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/index": { - "source": "iana" - }, - "application/index.cmd": { - "source": "iana" - }, - "application/index.obj": { - "source": "iana" - }, - "application/index.response": { - "source": "iana" - }, - "application/index.vnd": { - "source": "iana" - }, - "application/inkml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["ink","inkml"] - }, - "application/iotp": { - "source": "iana" - }, - "application/ipfix": { - "source": "iana", - "extensions": ["ipfix"] - }, - "application/ipp": { - "source": "iana" - }, - "application/isup": { - "source": "iana" - }, - "application/its+xml": { - "source": "iana", - "compressible": true, - "extensions": ["its"] - }, - "application/java-archive": { - "source": "apache", - "compressible": false, - "extensions": ["jar","war","ear"] - }, - "application/java-serialized-object": { - "source": "apache", - "compressible": false, - "extensions": ["ser"] - }, - "application/java-vm": { - "source": "apache", - "compressible": false, - "extensions": ["class"] - }, - "application/javascript": { - "source": "iana", - "charset": "UTF-8", - "compressible": true, - "extensions": ["js","mjs"] - }, - "application/jf2feed+json": { - "source": "iana", - "compressible": true - }, - "application/jose": { - "source": "iana" - }, - "application/jose+json": { - "source": "iana", - "compressible": true - }, - "application/jrd+json": { - "source": "iana", - "compressible": true - }, - "application/json": { - "source": "iana", - "charset": "UTF-8", - "compressible": true, - "extensions": ["json","map"] - }, - "application/json-patch+json": { - "source": "iana", - "compressible": true - }, - "application/json-seq": { - "source": "iana" - }, - "application/json5": { - "extensions": ["json5"] - }, - "application/jsonml+json": { - "source": "apache", - "compressible": true, - "extensions": ["jsonml"] - }, - "application/jwk+json": { - "source": "iana", - "compressible": true - }, - "application/jwk-set+json": { - "source": "iana", - "compressible": true - }, - "application/jwt": { - "source": "iana" - }, - "application/kpml-request+xml": { - "source": "iana", - "compressible": true - }, - "application/kpml-response+xml": { - "source": "iana", - "compressible": true - }, - "application/ld+json": { - "source": "iana", - "compressible": true, - "extensions": ["jsonld"] - }, - "application/lgr+xml": { - "source": "iana", - "compressible": true, - "extensions": ["lgr"] - }, - "application/link-format": { - "source": "iana" - }, - "application/load-control+xml": { - "source": "iana", - "compressible": true - }, - "application/lost+xml": { - "source": "iana", - "compressible": true, - "extensions": ["lostxml"] - }, - "application/lostsync+xml": { - "source": "iana", - "compressible": true - }, - "application/lpf+zip": { - "source": "iana", - "compressible": false - }, - "application/lxf": { - "source": "iana" - }, - "application/mac-binhex40": { - "source": "iana", - "extensions": ["hqx"] - }, - "application/mac-compactpro": { - "source": "apache", - "extensions": ["cpt"] - }, - "application/macwriteii": { - "source": "iana" - }, - "application/mads+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mads"] - }, - "application/manifest+json": { - "charset": "UTF-8", - "compressible": true, - "extensions": ["webmanifest"] - }, - "application/marc": { - "source": "iana", - "extensions": ["mrc"] - }, - "application/marcxml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mrcx"] - }, - "application/mathematica": { - "source": "iana", - "extensions": ["ma","nb","mb"] - }, - "application/mathml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mathml"] - }, - "application/mathml-content+xml": { - "source": "iana", - "compressible": true - }, - "application/mathml-presentation+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-associated-procedure-description+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-deregister+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-envelope+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-msk+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-msk-response+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-protection-description+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-reception-report+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-register+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-register-response+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-schedule+xml": { - "source": "iana", - "compressible": true - }, - "application/mbms-user-service-description+xml": { - "source": "iana", - "compressible": true - }, - "application/mbox": { - "source": "iana", - "extensions": ["mbox"] - }, - "application/media-policy-dataset+xml": { - "source": "iana", - "compressible": true - }, - "application/media_control+xml": { - "source": "iana", - "compressible": true - }, - "application/mediaservercontrol+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mscml"] - }, - "application/merge-patch+json": { - "source": "iana", - "compressible": true - }, - "application/metalink+xml": { - "source": "apache", - "compressible": true, - "extensions": ["metalink"] - }, - "application/metalink4+xml": { - "source": "iana", - "compressible": true, - "extensions": ["meta4"] - }, - "application/mets+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mets"] - }, - "application/mf4": { - "source": "iana" - }, - "application/mikey": { - "source": "iana" - }, - "application/mipc": { - "source": "iana" - }, - "application/mmt-aei+xml": { - "source": "iana", - "compressible": true, - "extensions": ["maei"] - }, - "application/mmt-usd+xml": { - "source": "iana", - "compressible": true, - "extensions": ["musd"] - }, - "application/mods+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mods"] - }, - "application/moss-keys": { - "source": "iana" - }, - "application/moss-signature": { - "source": "iana" - }, - "application/mosskey-data": { - "source": "iana" - }, - "application/mosskey-request": { - "source": "iana" - }, - "application/mp21": { - "source": "iana", - "extensions": ["m21","mp21"] - }, - "application/mp4": { - "source": "iana", - "extensions": ["mp4s","m4p"] - }, - "application/mpeg4-generic": { - "source": "iana" - }, - "application/mpeg4-iod": { - "source": "iana" - }, - "application/mpeg4-iod-xmt": { - "source": "iana" - }, - "application/mrb-consumer+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xdf"] - }, - "application/mrb-publish+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xdf"] - }, - "application/msc-ivr+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/msc-mixer+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/msword": { - "source": "iana", - "compressible": false, - "extensions": ["doc","dot"] - }, - "application/mud+json": { - "source": "iana", - "compressible": true - }, - "application/multipart-core": { - "source": "iana" - }, - "application/mxf": { - "source": "iana", - "extensions": ["mxf"] - }, - "application/n-quads": { - "source": "iana", - "extensions": ["nq"] - }, - "application/n-triples": { - "source": "iana", - "extensions": ["nt"] - }, - "application/nasdata": { - "source": "iana" - }, - "application/news-checkgroups": { - "source": "iana", - "charset": "US-ASCII" - }, - "application/news-groupinfo": { - "source": "iana", - "charset": "US-ASCII" - }, - "application/news-transmission": { - "source": "iana" - }, - "application/nlsml+xml": { - "source": "iana", - "compressible": true - }, - "application/node": { - "source": "iana", - "extensions": ["cjs"] - }, - "application/nss": { - "source": "iana" - }, - "application/ocsp-request": { - "source": "iana" - }, - "application/ocsp-response": { - "source": "iana" - }, - "application/octet-stream": { - "source": "iana", - "compressible": false, - "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] - }, - "application/oda": { - "source": "iana", - "extensions": ["oda"] - }, - "application/odm+xml": { - "source": "iana", - "compressible": true - }, - "application/odx": { - "source": "iana" - }, - "application/oebps-package+xml": { - "source": "iana", - "compressible": true, - "extensions": ["opf"] - }, - "application/ogg": { - "source": "iana", - "compressible": false, - "extensions": ["ogx"] - }, - "application/omdoc+xml": { - "source": "apache", - "compressible": true, - "extensions": ["omdoc"] - }, - "application/onenote": { - "source": "apache", - "extensions": ["onetoc","onetoc2","onetmp","onepkg"] - }, - "application/oscore": { - "source": "iana" - }, - "application/oxps": { - "source": "iana", - "extensions": ["oxps"] - }, - "application/p2p-overlay+xml": { - "source": "iana", - "compressible": true, - "extensions": ["relo"] - }, - "application/parityfec": { - "source": "iana" - }, - "application/passport": { - "source": "iana" - }, - "application/patch-ops-error+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xer"] - }, - "application/pdf": { - "source": "iana", - "compressible": false, - "extensions": ["pdf"] - }, - "application/pdx": { - "source": "iana" - }, - "application/pem-certificate-chain": { - "source": "iana" - }, - "application/pgp-encrypted": { - "source": "iana", - "compressible": false, - "extensions": ["pgp"] - }, - "application/pgp-keys": { - "source": "iana" - }, - "application/pgp-signature": { - "source": "iana", - "extensions": ["asc","sig"] - }, - "application/pics-rules": { - "source": "apache", - "extensions": ["prf"] - }, - "application/pidf+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/pidf-diff+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/pkcs10": { - "source": "iana", - "extensions": ["p10"] - }, - "application/pkcs12": { - "source": "iana" - }, - "application/pkcs7-mime": { - "source": "iana", - "extensions": ["p7m","p7c"] - }, - "application/pkcs7-signature": { - "source": "iana", - "extensions": ["p7s"] - }, - "application/pkcs8": { - "source": "iana", - "extensions": ["p8"] - }, - "application/pkcs8-encrypted": { - "source": "iana" - }, - "application/pkix-attr-cert": { - "source": "iana", - "extensions": ["ac"] - }, - "application/pkix-cert": { - "source": "iana", - "extensions": ["cer"] - }, - "application/pkix-crl": { - "source": "iana", - "extensions": ["crl"] - }, - "application/pkix-pkipath": { - "source": "iana", - "extensions": ["pkipath"] - }, - "application/pkixcmp": { - "source": "iana", - "extensions": ["pki"] - }, - "application/pls+xml": { - "source": "iana", - "compressible": true, - "extensions": ["pls"] - }, - "application/poc-settings+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/postscript": { - "source": "iana", - "compressible": true, - "extensions": ["ai","eps","ps"] - }, - "application/ppsp-tracker+json": { - "source": "iana", - "compressible": true - }, - "application/problem+json": { - "source": "iana", - "compressible": true - }, - "application/problem+xml": { - "source": "iana", - "compressible": true - }, - "application/provenance+xml": { - "source": "iana", - "compressible": true, - "extensions": ["provx"] - }, - "application/prs.alvestrand.titrax-sheet": { - "source": "iana" - }, - "application/prs.cww": { - "source": "iana", - "extensions": ["cww"] - }, - "application/prs.hpub+zip": { - "source": "iana", - "compressible": false - }, - "application/prs.nprend": { - "source": "iana" - }, - "application/prs.plucker": { - "source": "iana" - }, - "application/prs.rdf-xml-crypt": { - "source": "iana" - }, - "application/prs.xsf+xml": { - "source": "iana", - "compressible": true - }, - "application/pskc+xml": { - "source": "iana", - "compressible": true, - "extensions": ["pskcxml"] - }, - "application/pvd+json": { - "source": "iana", - "compressible": true - }, - "application/qsig": { - "source": "iana" - }, - "application/raml+yaml": { - "compressible": true, - "extensions": ["raml"] - }, - "application/raptorfec": { - "source": "iana" - }, - "application/rdap+json": { - "source": "iana", - "compressible": true - }, - "application/rdf+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rdf","owl"] - }, - "application/reginfo+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rif"] - }, - "application/relax-ng-compact-syntax": { - "source": "iana", - "extensions": ["rnc"] - }, - "application/remote-printing": { - "source": "iana" - }, - "application/reputon+json": { - "source": "iana", - "compressible": true - }, - "application/resource-lists+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rl"] - }, - "application/resource-lists-diff+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rld"] - }, - "application/rfc+xml": { - "source": "iana", - "compressible": true - }, - "application/riscos": { - "source": "iana" - }, - "application/rlmi+xml": { - "source": "iana", - "compressible": true - }, - "application/rls-services+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rs"] - }, - "application/route-apd+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rapd"] - }, - "application/route-s-tsid+xml": { - "source": "iana", - "compressible": true, - "extensions": ["sls"] - }, - "application/route-usd+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rusd"] - }, - "application/rpki-ghostbusters": { - "source": "iana", - "extensions": ["gbr"] - }, - "application/rpki-manifest": { - "source": "iana", - "extensions": ["mft"] - }, - "application/rpki-publication": { - "source": "iana" - }, - "application/rpki-roa": { - "source": "iana", - "extensions": ["roa"] - }, - "application/rpki-updown": { - "source": "iana" - }, - "application/rsd+xml": { - "source": "apache", - "compressible": true, - "extensions": ["rsd"] - }, - "application/rss+xml": { - "source": "apache", - "compressible": true, - "extensions": ["rss"] - }, - "application/rtf": { - "source": "iana", - "compressible": true, - "extensions": ["rtf"] - }, - "application/rtploopback": { - "source": "iana" - }, - "application/rtx": { - "source": "iana" - }, - "application/samlassertion+xml": { - "source": "iana", - "compressible": true - }, - "application/samlmetadata+xml": { - "source": "iana", - "compressible": true - }, - "application/sbe": { - "source": "iana" - }, - "application/sbml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["sbml"] - }, - "application/scaip+xml": { - "source": "iana", - "compressible": true - }, - "application/scim+json": { - "source": "iana", - "compressible": true - }, - "application/scvp-cv-request": { - "source": "iana", - "extensions": ["scq"] - }, - "application/scvp-cv-response": { - "source": "iana", - "extensions": ["scs"] - }, - "application/scvp-vp-request": { - "source": "iana", - "extensions": ["spq"] - }, - "application/scvp-vp-response": { - "source": "iana", - "extensions": ["spp"] - }, - "application/sdp": { - "source": "iana", - "extensions": ["sdp"] - }, - "application/secevent+jwt": { - "source": "iana" - }, - "application/senml+cbor": { - "source": "iana" - }, - "application/senml+json": { - "source": "iana", - "compressible": true - }, - "application/senml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["senmlx"] - }, - "application/senml-etch+cbor": { - "source": "iana" - }, - "application/senml-etch+json": { - "source": "iana", - "compressible": true - }, - "application/senml-exi": { - "source": "iana" - }, - "application/sensml+cbor": { - "source": "iana" - }, - "application/sensml+json": { - "source": "iana", - "compressible": true - }, - "application/sensml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["sensmlx"] - }, - "application/sensml-exi": { - "source": "iana" - }, - "application/sep+xml": { - "source": "iana", - "compressible": true - }, - "application/sep-exi": { - "source": "iana" - }, - "application/session-info": { - "source": "iana" - }, - "application/set-payment": { - "source": "iana" - }, - "application/set-payment-initiation": { - "source": "iana", - "extensions": ["setpay"] - }, - "application/set-registration": { - "source": "iana" - }, - "application/set-registration-initiation": { - "source": "iana", - "extensions": ["setreg"] - }, - "application/sgml": { - "source": "iana" - }, - "application/sgml-open-catalog": { - "source": "iana" - }, - "application/shf+xml": { - "source": "iana", - "compressible": true, - "extensions": ["shf"] - }, - "application/sieve": { - "source": "iana", - "extensions": ["siv","sieve"] - }, - "application/simple-filter+xml": { - "source": "iana", - "compressible": true - }, - "application/simple-message-summary": { - "source": "iana" - }, - "application/simplesymbolcontainer": { - "source": "iana" - }, - "application/sipc": { - "source": "iana" - }, - "application/slate": { - "source": "iana" - }, - "application/smil": { - "source": "iana" - }, - "application/smil+xml": { - "source": "iana", - "compressible": true, - "extensions": ["smi","smil"] - }, - "application/smpte336m": { - "source": "iana" - }, - "application/soap+fastinfoset": { - "source": "iana" - }, - "application/soap+xml": { - "source": "iana", - "compressible": true - }, - "application/sparql-query": { - "source": "iana", - "extensions": ["rq"] - }, - "application/sparql-results+xml": { - "source": "iana", - "compressible": true, - "extensions": ["srx"] - }, - "application/spirits-event+xml": { - "source": "iana", - "compressible": true - }, - "application/sql": { - "source": "iana" - }, - "application/srgs": { - "source": "iana", - "extensions": ["gram"] - }, - "application/srgs+xml": { - "source": "iana", - "compressible": true, - "extensions": ["grxml"] - }, - "application/sru+xml": { - "source": "iana", - "compressible": true, - "extensions": ["sru"] - }, - "application/ssdl+xml": { - "source": "apache", - "compressible": true, - "extensions": ["ssdl"] - }, - "application/ssml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["ssml"] - }, - "application/stix+json": { - "source": "iana", - "compressible": true - }, - "application/swid+xml": { - "source": "iana", - "compressible": true, - "extensions": ["swidtag"] - }, - "application/tamp-apex-update": { - "source": "iana" - }, - "application/tamp-apex-update-confirm": { - "source": "iana" - }, - "application/tamp-community-update": { - "source": "iana" - }, - "application/tamp-community-update-confirm": { - "source": "iana" - }, - "application/tamp-error": { - "source": "iana" - }, - "application/tamp-sequence-adjust": { - "source": "iana" - }, - "application/tamp-sequence-adjust-confirm": { - "source": "iana" - }, - "application/tamp-status-query": { - "source": "iana" - }, - "application/tamp-status-response": { - "source": "iana" - }, - "application/tamp-update": { - "source": "iana" - }, - "application/tamp-update-confirm": { - "source": "iana" - }, - "application/tar": { - "compressible": true - }, - "application/taxii+json": { - "source": "iana", - "compressible": true - }, - "application/td+json": { - "source": "iana", - "compressible": true - }, - "application/tei+xml": { - "source": "iana", - "compressible": true, - "extensions": ["tei","teicorpus"] - }, - "application/tetra_isi": { - "source": "iana" - }, - "application/thraud+xml": { - "source": "iana", - "compressible": true, - "extensions": ["tfi"] - }, - "application/timestamp-query": { - "source": "iana" - }, - "application/timestamp-reply": { - "source": "iana" - }, - "application/timestamped-data": { - "source": "iana", - "extensions": ["tsd"] - }, - "application/tlsrpt+gzip": { - "source": "iana" - }, - "application/tlsrpt+json": { - "source": "iana", - "compressible": true - }, - "application/tnauthlist": { - "source": "iana" - }, - "application/toml": { - "compressible": true, - "extensions": ["toml"] - }, - "application/trickle-ice-sdpfrag": { - "source": "iana" - }, - "application/trig": { - "source": "iana" - }, - "application/ttml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["ttml"] - }, - "application/tve-trigger": { - "source": "iana" - }, - "application/tzif": { - "source": "iana" - }, - "application/tzif-leap": { - "source": "iana" - }, - "application/ulpfec": { - "source": "iana" - }, - "application/urc-grpsheet+xml": { - "source": "iana", - "compressible": true - }, - "application/urc-ressheet+xml": { - "source": "iana", - "compressible": true, - "extensions": ["rsheet"] - }, - "application/urc-targetdesc+xml": { - "source": "iana", - "compressible": true - }, - "application/urc-uisocketdesc+xml": { - "source": "iana", - "compressible": true - }, - "application/vcard+json": { - "source": "iana", - "compressible": true - }, - "application/vcard+xml": { - "source": "iana", - "compressible": true - }, - "application/vemmi": { - "source": "iana" - }, - "application/vividence.scriptfile": { - "source": "apache" - }, - "application/vnd.1000minds.decision-model+xml": { - "source": "iana", - "compressible": true, - "extensions": ["1km"] - }, - "application/vnd.3gpp-prose+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp-prose-pc3ch+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp-v2x-local-service-information": { - "source": "iana" - }, - "application/vnd.3gpp.access-transfer-events+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.bsf+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.gmop+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mc-signalling-ear": { - "source": "iana" - }, - "application/vnd.3gpp.mcdata-affiliation-command+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcdata-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcdata-payload": { - "source": "iana" - }, - "application/vnd.3gpp.mcdata-service-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcdata-signalling": { - "source": "iana" - }, - "application/vnd.3gpp.mcdata-ue-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcdata-user-profile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-affiliation-command+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-floor-request+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-location-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-service-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-signed+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-ue-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-ue-init-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcptt-user-profile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-affiliation-command+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-affiliation-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-location-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-service-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-transmission-request+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-ue-config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mcvideo-user-profile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.mid-call+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.pic-bw-large": { - "source": "iana", - "extensions": ["plb"] - }, - "application/vnd.3gpp.pic-bw-small": { - "source": "iana", - "extensions": ["psb"] - }, - "application/vnd.3gpp.pic-bw-var": { - "source": "iana", - "extensions": ["pvb"] - }, - "application/vnd.3gpp.sms": { - "source": "iana" - }, - "application/vnd.3gpp.sms+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.srvcc-ext+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.srvcc-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.state-and-event-info+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp.ussd+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp2.bcmcsinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.3gpp2.sms": { - "source": "iana" - }, - "application/vnd.3gpp2.tcap": { - "source": "iana", - "extensions": ["tcap"] - }, - "application/vnd.3lightssoftware.imagescal": { - "source": "iana" - }, - "application/vnd.3m.post-it-notes": { - "source": "iana", - "extensions": ["pwn"] - }, - "application/vnd.accpac.simply.aso": { - "source": "iana", - "extensions": ["aso"] - }, - "application/vnd.accpac.simply.imp": { - "source": "iana", - "extensions": ["imp"] - }, - "application/vnd.acucobol": { - "source": "iana", - "extensions": ["acu"] - }, - "application/vnd.acucorp": { - "source": "iana", - "extensions": ["atc","acutc"] - }, - "application/vnd.adobe.air-application-installer-package+zip": { - "source": "apache", - "compressible": false, - "extensions": ["air"] - }, - "application/vnd.adobe.flash.movie": { - "source": "iana" - }, - "application/vnd.adobe.formscentral.fcdt": { - "source": "iana", - "extensions": ["fcdt"] - }, - "application/vnd.adobe.fxp": { - "source": "iana", - "extensions": ["fxp","fxpl"] - }, - "application/vnd.adobe.partial-upload": { - "source": "iana" - }, - "application/vnd.adobe.xdp+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xdp"] - }, - "application/vnd.adobe.xfdf": { - "source": "iana", - "extensions": ["xfdf"] - }, - "application/vnd.aether.imp": { - "source": "iana" - }, - "application/vnd.afpc.afplinedata": { - "source": "iana" - }, - "application/vnd.afpc.afplinedata-pagedef": { - "source": "iana" - }, - "application/vnd.afpc.foca-charset": { - "source": "iana" - }, - "application/vnd.afpc.foca-codedfont": { - "source": "iana" - }, - "application/vnd.afpc.foca-codepage": { - "source": "iana" - }, - "application/vnd.afpc.modca": { - "source": "iana" - }, - "application/vnd.afpc.modca-formdef": { - "source": "iana" - }, - "application/vnd.afpc.modca-mediummap": { - "source": "iana" - }, - "application/vnd.afpc.modca-objectcontainer": { - "source": "iana" - }, - "application/vnd.afpc.modca-overlay": { - "source": "iana" - }, - "application/vnd.afpc.modca-pagesegment": { - "source": "iana" - }, - "application/vnd.ah-barcode": { - "source": "iana" - }, - "application/vnd.ahead.space": { - "source": "iana", - "extensions": ["ahead"] - }, - "application/vnd.airzip.filesecure.azf": { - "source": "iana", - "extensions": ["azf"] - }, - "application/vnd.airzip.filesecure.azs": { - "source": "iana", - "extensions": ["azs"] - }, - "application/vnd.amadeus+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.amazon.ebook": { - "source": "apache", - "extensions": ["azw"] - }, - "application/vnd.amazon.mobi8-ebook": { - "source": "iana" - }, - "application/vnd.americandynamics.acc": { - "source": "iana", - "extensions": ["acc"] - }, - "application/vnd.amiga.ami": { - "source": "iana", - "extensions": ["ami"] - }, - "application/vnd.amundsen.maze+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.android.ota": { - "source": "iana" - }, - "application/vnd.android.package-archive": { - "source": "apache", - "compressible": false, - "extensions": ["apk"] - }, - "application/vnd.anki": { - "source": "iana" - }, - "application/vnd.anser-web-certificate-issue-initiation": { - "source": "iana", - "extensions": ["cii"] - }, - "application/vnd.anser-web-funds-transfer-initiation": { - "source": "apache", - "extensions": ["fti"] - }, - "application/vnd.antix.game-component": { - "source": "iana", - "extensions": ["atx"] - }, - "application/vnd.apache.thrift.binary": { - "source": "iana" - }, - "application/vnd.apache.thrift.compact": { - "source": "iana" - }, - "application/vnd.apache.thrift.json": { - "source": "iana" - }, - "application/vnd.api+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.aplextor.warrp+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.apothekende.reservation+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.apple.installer+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mpkg"] - }, - "application/vnd.apple.keynote": { - "source": "iana", - "extensions": ["keynote"] - }, - "application/vnd.apple.mpegurl": { - "source": "iana", - "extensions": ["m3u8"] - }, - "application/vnd.apple.numbers": { - "source": "iana", - "extensions": ["numbers"] - }, - "application/vnd.apple.pages": { - "source": "iana", - "extensions": ["pages"] - }, - "application/vnd.apple.pkpass": { - "compressible": false, - "extensions": ["pkpass"] - }, - "application/vnd.arastra.swi": { - "source": "iana" - }, - "application/vnd.aristanetworks.swi": { - "source": "iana", - "extensions": ["swi"] - }, - "application/vnd.artisan+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.artsquare": { - "source": "iana" - }, - "application/vnd.astraea-software.iota": { - "source": "iana", - "extensions": ["iota"] - }, - "application/vnd.audiograph": { - "source": "iana", - "extensions": ["aep"] - }, - "application/vnd.autopackage": { - "source": "iana" - }, - "application/vnd.avalon+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.avistar+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.balsamiq.bmml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["bmml"] - }, - "application/vnd.balsamiq.bmpr": { - "source": "iana" - }, - "application/vnd.banana-accounting": { - "source": "iana" - }, - "application/vnd.bbf.usp.error": { - "source": "iana" - }, - "application/vnd.bbf.usp.msg": { - "source": "iana" - }, - "application/vnd.bbf.usp.msg+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.bekitzur-stech+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.bint.med-content": { - "source": "iana" - }, - "application/vnd.biopax.rdf+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.blink-idb-value-wrapper": { - "source": "iana" - }, - "application/vnd.blueice.multipass": { - "source": "iana", - "extensions": ["mpm"] - }, - "application/vnd.bluetooth.ep.oob": { - "source": "iana" - }, - "application/vnd.bluetooth.le.oob": { - "source": "iana" - }, - "application/vnd.bmi": { - "source": "iana", - "extensions": ["bmi"] - }, - "application/vnd.bpf": { - "source": "iana" - }, - "application/vnd.bpf3": { - "source": "iana" - }, - "application/vnd.businessobjects": { - "source": "iana", - "extensions": ["rep"] - }, - "application/vnd.byu.uapi+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.cab-jscript": { - "source": "iana" - }, - "application/vnd.canon-cpdl": { - "source": "iana" - }, - "application/vnd.canon-lips": { - "source": "iana" - }, - "application/vnd.capasystems-pg+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.cendio.thinlinc.clientconf": { - "source": "iana" - }, - "application/vnd.century-systems.tcp_stream": { - "source": "iana" - }, - "application/vnd.chemdraw+xml": { - "source": "iana", - "compressible": true, - "extensions": ["cdxml"] - }, - "application/vnd.chess-pgn": { - "source": "iana" - }, - "application/vnd.chipnuts.karaoke-mmd": { - "source": "iana", - "extensions": ["mmd"] - }, - "application/vnd.ciedi": { - "source": "iana" - }, - "application/vnd.cinderella": { - "source": "iana", - "extensions": ["cdy"] - }, - "application/vnd.cirpack.isdn-ext": { - "source": "iana" - }, - "application/vnd.citationstyles.style+xml": { - "source": "iana", - "compressible": true, - "extensions": ["csl"] - }, - "application/vnd.claymore": { - "source": "iana", - "extensions": ["cla"] - }, - "application/vnd.cloanto.rp9": { - "source": "iana", - "extensions": ["rp9"] - }, - "application/vnd.clonk.c4group": { - "source": "iana", - "extensions": ["c4g","c4d","c4f","c4p","c4u"] - }, - "application/vnd.cluetrust.cartomobile-config": { - "source": "iana", - "extensions": ["c11amc"] - }, - "application/vnd.cluetrust.cartomobile-config-pkg": { - "source": "iana", - "extensions": ["c11amz"] - }, - "application/vnd.coffeescript": { - "source": "iana" - }, - "application/vnd.collabio.xodocuments.document": { - "source": "iana" - }, - "application/vnd.collabio.xodocuments.document-template": { - "source": "iana" - }, - "application/vnd.collabio.xodocuments.presentation": { - "source": "iana" - }, - "application/vnd.collabio.xodocuments.presentation-template": { - "source": "iana" - }, - "application/vnd.collabio.xodocuments.spreadsheet": { - "source": "iana" - }, - "application/vnd.collabio.xodocuments.spreadsheet-template": { - "source": "iana" - }, - "application/vnd.collection+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.collection.doc+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.collection.next+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.comicbook+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.comicbook-rar": { - "source": "iana" - }, - "application/vnd.commerce-battelle": { - "source": "iana" - }, - "application/vnd.commonspace": { - "source": "iana", - "extensions": ["csp"] - }, - "application/vnd.contact.cmsg": { - "source": "iana", - "extensions": ["cdbcmsg"] - }, - "application/vnd.coreos.ignition+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.cosmocaller": { - "source": "iana", - "extensions": ["cmc"] - }, - "application/vnd.crick.clicker": { - "source": "iana", - "extensions": ["clkx"] - }, - "application/vnd.crick.clicker.keyboard": { - "source": "iana", - "extensions": ["clkk"] - }, - "application/vnd.crick.clicker.palette": { - "source": "iana", - "extensions": ["clkp"] - }, - "application/vnd.crick.clicker.template": { - "source": "iana", - "extensions": ["clkt"] - }, - "application/vnd.crick.clicker.wordbank": { - "source": "iana", - "extensions": ["clkw"] - }, - "application/vnd.criticaltools.wbs+xml": { - "source": "iana", - "compressible": true, - "extensions": ["wbs"] - }, - "application/vnd.cryptii.pipe+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.crypto-shade-file": { - "source": "iana" - }, - "application/vnd.ctc-posml": { - "source": "iana", - "extensions": ["pml"] - }, - "application/vnd.ctct.ws+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.cups-pdf": { - "source": "iana" - }, - "application/vnd.cups-postscript": { - "source": "iana" - }, - "application/vnd.cups-ppd": { - "source": "iana", - "extensions": ["ppd"] - }, - "application/vnd.cups-raster": { - "source": "iana" - }, - "application/vnd.cups-raw": { - "source": "iana" - }, - "application/vnd.curl": { - "source": "iana" - }, - "application/vnd.curl.car": { - "source": "apache", - "extensions": ["car"] - }, - "application/vnd.curl.pcurl": { - "source": "apache", - "extensions": ["pcurl"] - }, - "application/vnd.cyan.dean.root+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.cybank": { - "source": "iana" - }, - "application/vnd.d2l.coursepackage1p0+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.dart": { - "source": "iana", - "compressible": true, - "extensions": ["dart"] - }, - "application/vnd.data-vision.rdz": { - "source": "iana", - "extensions": ["rdz"] - }, - "application/vnd.datapackage+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.dataresource+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.dbf": { - "source": "iana" - }, - "application/vnd.debian.binary-package": { - "source": "iana" - }, - "application/vnd.dece.data": { - "source": "iana", - "extensions": ["uvf","uvvf","uvd","uvvd"] - }, - "application/vnd.dece.ttml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["uvt","uvvt"] - }, - "application/vnd.dece.unspecified": { - "source": "iana", - "extensions": ["uvx","uvvx"] - }, - "application/vnd.dece.zip": { - "source": "iana", - "extensions": ["uvz","uvvz"] - }, - "application/vnd.denovo.fcselayout-link": { - "source": "iana", - "extensions": ["fe_launch"] - }, - "application/vnd.desmume.movie": { - "source": "iana" - }, - "application/vnd.dir-bi.plate-dl-nosuffix": { - "source": "iana" - }, - "application/vnd.dm.delegation+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dna": { - "source": "iana", - "extensions": ["dna"] - }, - "application/vnd.document+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.dolby.mlp": { - "source": "apache", - "extensions": ["mlp"] - }, - "application/vnd.dolby.mobile.1": { - "source": "iana" - }, - "application/vnd.dolby.mobile.2": { - "source": "iana" - }, - "application/vnd.doremir.scorecloud-binary-document": { - "source": "iana" - }, - "application/vnd.dpgraph": { - "source": "iana", - "extensions": ["dpg"] - }, - "application/vnd.dreamfactory": { - "source": "iana", - "extensions": ["dfac"] - }, - "application/vnd.drive+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.ds-keypoint": { - "source": "apache", - "extensions": ["kpxx"] - }, - "application/vnd.dtg.local": { - "source": "iana" - }, - "application/vnd.dtg.local.flash": { - "source": "iana" - }, - "application/vnd.dtg.local.html": { - "source": "iana" - }, - "application/vnd.dvb.ait": { - "source": "iana", - "extensions": ["ait"] - }, - "application/vnd.dvb.dvbisl+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.dvbj": { - "source": "iana" - }, - "application/vnd.dvb.esgcontainer": { - "source": "iana" - }, - "application/vnd.dvb.ipdcdftnotifaccess": { - "source": "iana" - }, - "application/vnd.dvb.ipdcesgaccess": { - "source": "iana" - }, - "application/vnd.dvb.ipdcesgaccess2": { - "source": "iana" - }, - "application/vnd.dvb.ipdcesgpdd": { - "source": "iana" - }, - "application/vnd.dvb.ipdcroaming": { - "source": "iana" - }, - "application/vnd.dvb.iptv.alfec-base": { - "source": "iana" - }, - "application/vnd.dvb.iptv.alfec-enhancement": { - "source": "iana" - }, - "application/vnd.dvb.notif-aggregate-root+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.notif-container+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.notif-generic+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.notif-ia-msglist+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.notif-ia-registration-request+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.notif-ia-registration-response+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.notif-init+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.dvb.pfr": { - "source": "iana" - }, - "application/vnd.dvb.service": { - "source": "iana", - "extensions": ["svc"] - }, - "application/vnd.dxr": { - "source": "iana" - }, - "application/vnd.dynageo": { - "source": "iana", - "extensions": ["geo"] - }, - "application/vnd.dzr": { - "source": "iana" - }, - "application/vnd.easykaraoke.cdgdownload": { - "source": "iana" - }, - "application/vnd.ecdis-update": { - "source": "iana" - }, - "application/vnd.ecip.rlp": { - "source": "iana" - }, - "application/vnd.ecowin.chart": { - "source": "iana", - "extensions": ["mag"] - }, - "application/vnd.ecowin.filerequest": { - "source": "iana" - }, - "application/vnd.ecowin.fileupdate": { - "source": "iana" - }, - "application/vnd.ecowin.series": { - "source": "iana" - }, - "application/vnd.ecowin.seriesrequest": { - "source": "iana" - }, - "application/vnd.ecowin.seriesupdate": { - "source": "iana" - }, - "application/vnd.efi.img": { - "source": "iana" - }, - "application/vnd.efi.iso": { - "source": "iana" - }, - "application/vnd.emclient.accessrequest+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.enliven": { - "source": "iana", - "extensions": ["nml"] - }, - "application/vnd.enphase.envoy": { - "source": "iana" - }, - "application/vnd.eprints.data+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.epson.esf": { - "source": "iana", - "extensions": ["esf"] - }, - "application/vnd.epson.msf": { - "source": "iana", - "extensions": ["msf"] - }, - "application/vnd.epson.quickanime": { - "source": "iana", - "extensions": ["qam"] - }, - "application/vnd.epson.salt": { - "source": "iana", - "extensions": ["slt"] - }, - "application/vnd.epson.ssf": { - "source": "iana", - "extensions": ["ssf"] - }, - "application/vnd.ericsson.quickcall": { - "source": "iana" - }, - "application/vnd.espass-espass+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.eszigno3+xml": { - "source": "iana", - "compressible": true, - "extensions": ["es3","et3"] - }, - "application/vnd.etsi.aoc+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.asic-e+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.etsi.asic-s+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.etsi.cug+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvcommand+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvdiscovery+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvprofile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvsad-bc+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvsad-cod+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvsad-npvr+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvservice+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvsync+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.iptvueprofile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.mcid+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.mheg5": { - "source": "iana" - }, - "application/vnd.etsi.overload-control-policy-dataset+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.pstn+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.sci+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.simservs+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.timestamp-token": { - "source": "iana" - }, - "application/vnd.etsi.tsl+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.etsi.tsl.der": { - "source": "iana" - }, - "application/vnd.eudora.data": { - "source": "iana" - }, - "application/vnd.evolv.ecig.profile": { - "source": "iana" - }, - "application/vnd.evolv.ecig.settings": { - "source": "iana" - }, - "application/vnd.evolv.ecig.theme": { - "source": "iana" - }, - "application/vnd.exstream-empower+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.exstream-package": { - "source": "iana" - }, - "application/vnd.ezpix-album": { - "source": "iana", - "extensions": ["ez2"] - }, - "application/vnd.ezpix-package": { - "source": "iana", - "extensions": ["ez3"] - }, - "application/vnd.f-secure.mobile": { - "source": "iana" - }, - "application/vnd.fastcopy-disk-image": { - "source": "iana" - }, - "application/vnd.fdf": { - "source": "iana", - "extensions": ["fdf"] - }, - "application/vnd.fdsn.mseed": { - "source": "iana", - "extensions": ["mseed"] - }, - "application/vnd.fdsn.seed": { - "source": "iana", - "extensions": ["seed","dataless"] - }, - "application/vnd.ffsns": { - "source": "iana" - }, - "application/vnd.ficlab.flb+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.filmit.zfc": { - "source": "iana" - }, - "application/vnd.fints": { - "source": "iana" - }, - "application/vnd.firemonkeys.cloudcell": { - "source": "iana" - }, - "application/vnd.flographit": { - "source": "iana", - "extensions": ["gph"] - }, - "application/vnd.fluxtime.clip": { - "source": "iana", - "extensions": ["ftc"] - }, - "application/vnd.font-fontforge-sfd": { - "source": "iana" - }, - "application/vnd.framemaker": { - "source": "iana", - "extensions": ["fm","frame","maker","book"] - }, - "application/vnd.frogans.fnc": { - "source": "iana", - "extensions": ["fnc"] - }, - "application/vnd.frogans.ltf": { - "source": "iana", - "extensions": ["ltf"] - }, - "application/vnd.fsc.weblaunch": { - "source": "iana", - "extensions": ["fsc"] - }, - "application/vnd.fujitsu.oasys": { - "source": "iana", - "extensions": ["oas"] - }, - "application/vnd.fujitsu.oasys2": { - "source": "iana", - "extensions": ["oa2"] - }, - "application/vnd.fujitsu.oasys3": { - "source": "iana", - "extensions": ["oa3"] - }, - "application/vnd.fujitsu.oasysgp": { - "source": "iana", - "extensions": ["fg5"] - }, - "application/vnd.fujitsu.oasysprs": { - "source": "iana", - "extensions": ["bh2"] - }, - "application/vnd.fujixerox.art-ex": { - "source": "iana" - }, - "application/vnd.fujixerox.art4": { - "source": "iana" - }, - "application/vnd.fujixerox.ddd": { - "source": "iana", - "extensions": ["ddd"] - }, - "application/vnd.fujixerox.docuworks": { - "source": "iana", - "extensions": ["xdw"] - }, - "application/vnd.fujixerox.docuworks.binder": { - "source": "iana", - "extensions": ["xbd"] - }, - "application/vnd.fujixerox.docuworks.container": { - "source": "iana" - }, - "application/vnd.fujixerox.hbpl": { - "source": "iana" - }, - "application/vnd.fut-misnet": { - "source": "iana" - }, - "application/vnd.futoin+cbor": { - "source": "iana" - }, - "application/vnd.futoin+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.fuzzysheet": { - "source": "iana", - "extensions": ["fzs"] - }, - "application/vnd.genomatix.tuxedo": { - "source": "iana", - "extensions": ["txd"] - }, - "application/vnd.gentics.grd+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.geo+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.geocube+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.geogebra.file": { - "source": "iana", - "extensions": ["ggb"] - }, - "application/vnd.geogebra.tool": { - "source": "iana", - "extensions": ["ggt"] - }, - "application/vnd.geometry-explorer": { - "source": "iana", - "extensions": ["gex","gre"] - }, - "application/vnd.geonext": { - "source": "iana", - "extensions": ["gxt"] - }, - "application/vnd.geoplan": { - "source": "iana", - "extensions": ["g2w"] - }, - "application/vnd.geospace": { - "source": "iana", - "extensions": ["g3w"] - }, - "application/vnd.gerber": { - "source": "iana" - }, - "application/vnd.globalplatform.card-content-mgt": { - "source": "iana" - }, - "application/vnd.globalplatform.card-content-mgt-response": { - "source": "iana" - }, - "application/vnd.gmx": { - "source": "iana", - "extensions": ["gmx"] - }, - "application/vnd.google-apps.document": { - "compressible": false, - "extensions": ["gdoc"] - }, - "application/vnd.google-apps.presentation": { - "compressible": false, - "extensions": ["gslides"] - }, - "application/vnd.google-apps.spreadsheet": { - "compressible": false, - "extensions": ["gsheet"] - }, - "application/vnd.google-earth.kml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["kml"] - }, - "application/vnd.google-earth.kmz": { - "source": "iana", - "compressible": false, - "extensions": ["kmz"] - }, - "application/vnd.gov.sk.e-form+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.gov.sk.e-form+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.gov.sk.xmldatacontainer+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.grafeq": { - "source": "iana", - "extensions": ["gqf","gqs"] - }, - "application/vnd.gridmp": { - "source": "iana" - }, - "application/vnd.groove-account": { - "source": "iana", - "extensions": ["gac"] - }, - "application/vnd.groove-help": { - "source": "iana", - "extensions": ["ghf"] - }, - "application/vnd.groove-identity-message": { - "source": "iana", - "extensions": ["gim"] - }, - "application/vnd.groove-injector": { - "source": "iana", - "extensions": ["grv"] - }, - "application/vnd.groove-tool-message": { - "source": "iana", - "extensions": ["gtm"] - }, - "application/vnd.groove-tool-template": { - "source": "iana", - "extensions": ["tpl"] - }, - "application/vnd.groove-vcard": { - "source": "iana", - "extensions": ["vcg"] - }, - "application/vnd.hal+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.hal+xml": { - "source": "iana", - "compressible": true, - "extensions": ["hal"] - }, - "application/vnd.handheld-entertainment+xml": { - "source": "iana", - "compressible": true, - "extensions": ["zmm"] - }, - "application/vnd.hbci": { - "source": "iana", - "extensions": ["hbci"] - }, - "application/vnd.hc+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.hcl-bireports": { - "source": "iana" - }, - "application/vnd.hdt": { - "source": "iana" - }, - "application/vnd.heroku+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.hhe.lesson-player": { - "source": "iana", - "extensions": ["les"] - }, - "application/vnd.hp-hpgl": { - "source": "iana", - "extensions": ["hpgl"] - }, - "application/vnd.hp-hpid": { - "source": "iana", - "extensions": ["hpid"] - }, - "application/vnd.hp-hps": { - "source": "iana", - "extensions": ["hps"] - }, - "application/vnd.hp-jlyt": { - "source": "iana", - "extensions": ["jlt"] - }, - "application/vnd.hp-pcl": { - "source": "iana", - "extensions": ["pcl"] - }, - "application/vnd.hp-pclxl": { - "source": "iana", - "extensions": ["pclxl"] - }, - "application/vnd.httphone": { - "source": "iana" - }, - "application/vnd.hydrostatix.sof-data": { - "source": "iana", - "extensions": ["sfd-hdstx"] - }, - "application/vnd.hyper+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.hyper-item+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.hyperdrive+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.hzn-3d-crossword": { - "source": "iana" - }, - "application/vnd.ibm.afplinedata": { - "source": "iana" - }, - "application/vnd.ibm.electronic-media": { - "source": "iana" - }, - "application/vnd.ibm.minipay": { - "source": "iana", - "extensions": ["mpy"] - }, - "application/vnd.ibm.modcap": { - "source": "iana", - "extensions": ["afp","listafp","list3820"] - }, - "application/vnd.ibm.rights-management": { - "source": "iana", - "extensions": ["irm"] - }, - "application/vnd.ibm.secure-container": { - "source": "iana", - "extensions": ["sc"] - }, - "application/vnd.iccprofile": { - "source": "iana", - "extensions": ["icc","icm"] - }, - "application/vnd.ieee.1905": { - "source": "iana" - }, - "application/vnd.igloader": { - "source": "iana", - "extensions": ["igl"] - }, - "application/vnd.imagemeter.folder+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.imagemeter.image+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.immervision-ivp": { - "source": "iana", - "extensions": ["ivp"] - }, - "application/vnd.immervision-ivu": { - "source": "iana", - "extensions": ["ivu"] - }, - "application/vnd.ims.imsccv1p1": { - "source": "iana" - }, - "application/vnd.ims.imsccv1p2": { - "source": "iana" - }, - "application/vnd.ims.imsccv1p3": { - "source": "iana" - }, - "application/vnd.ims.lis.v2.result+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.ims.lti.v2.toolconsumerprofile+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.ims.lti.v2.toolproxy+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.ims.lti.v2.toolproxy.id+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.ims.lti.v2.toolsettings+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.ims.lti.v2.toolsettings.simple+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.informedcontrol.rms+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.informix-visionary": { - "source": "iana" - }, - "application/vnd.infotech.project": { - "source": "iana" - }, - "application/vnd.infotech.project+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.innopath.wamp.notification": { - "source": "iana" - }, - "application/vnd.insors.igm": { - "source": "iana", - "extensions": ["igm"] - }, - "application/vnd.intercon.formnet": { - "source": "iana", - "extensions": ["xpw","xpx"] - }, - "application/vnd.intergeo": { - "source": "iana", - "extensions": ["i2g"] - }, - "application/vnd.intertrust.digibox": { - "source": "iana" - }, - "application/vnd.intertrust.nncp": { - "source": "iana" - }, - "application/vnd.intu.qbo": { - "source": "iana", - "extensions": ["qbo"] - }, - "application/vnd.intu.qfx": { - "source": "iana", - "extensions": ["qfx"] - }, - "application/vnd.iptc.g2.catalogitem+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.iptc.g2.conceptitem+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.iptc.g2.knowledgeitem+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.iptc.g2.newsitem+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.iptc.g2.newsmessage+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.iptc.g2.packageitem+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.iptc.g2.planningitem+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.ipunplugged.rcprofile": { - "source": "iana", - "extensions": ["rcprofile"] - }, - "application/vnd.irepository.package+xml": { - "source": "iana", - "compressible": true, - "extensions": ["irp"] - }, - "application/vnd.is-xpr": { - "source": "iana", - "extensions": ["xpr"] - }, - "application/vnd.isac.fcs": { - "source": "iana", - "extensions": ["fcs"] - }, - "application/vnd.iso11783-10+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.jam": { - "source": "iana", - "extensions": ["jam"] - }, - "application/vnd.japannet-directory-service": { - "source": "iana" - }, - "application/vnd.japannet-jpnstore-wakeup": { - "source": "iana" - }, - "application/vnd.japannet-payment-wakeup": { - "source": "iana" - }, - "application/vnd.japannet-registration": { - "source": "iana" - }, - "application/vnd.japannet-registration-wakeup": { - "source": "iana" - }, - "application/vnd.japannet-setstore-wakeup": { - "source": "iana" - }, - "application/vnd.japannet-verification": { - "source": "iana" - }, - "application/vnd.japannet-verification-wakeup": { - "source": "iana" - }, - "application/vnd.jcp.javame.midlet-rms": { - "source": "iana", - "extensions": ["rms"] - }, - "application/vnd.jisp": { - "source": "iana", - "extensions": ["jisp"] - }, - "application/vnd.joost.joda-archive": { - "source": "iana", - "extensions": ["joda"] - }, - "application/vnd.jsk.isdn-ngn": { - "source": "iana" - }, - "application/vnd.kahootz": { - "source": "iana", - "extensions": ["ktz","ktr"] - }, - "application/vnd.kde.karbon": { - "source": "iana", - "extensions": ["karbon"] - }, - "application/vnd.kde.kchart": { - "source": "iana", - "extensions": ["chrt"] - }, - "application/vnd.kde.kformula": { - "source": "iana", - "extensions": ["kfo"] - }, - "application/vnd.kde.kivio": { - "source": "iana", - "extensions": ["flw"] - }, - "application/vnd.kde.kontour": { - "source": "iana", - "extensions": ["kon"] - }, - "application/vnd.kde.kpresenter": { - "source": "iana", - "extensions": ["kpr","kpt"] - }, - "application/vnd.kde.kspread": { - "source": "iana", - "extensions": ["ksp"] - }, - "application/vnd.kde.kword": { - "source": "iana", - "extensions": ["kwd","kwt"] - }, - "application/vnd.kenameaapp": { - "source": "iana", - "extensions": ["htke"] - }, - "application/vnd.kidspiration": { - "source": "iana", - "extensions": ["kia"] - }, - "application/vnd.kinar": { - "source": "iana", - "extensions": ["kne","knp"] - }, - "application/vnd.koan": { - "source": "iana", - "extensions": ["skp","skd","skt","skm"] - }, - "application/vnd.kodak-descriptor": { - "source": "iana", - "extensions": ["sse"] - }, - "application/vnd.las": { - "source": "iana" - }, - "application/vnd.las.las+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.las.las+xml": { - "source": "iana", - "compressible": true, - "extensions": ["lasxml"] - }, - "application/vnd.laszip": { - "source": "iana" - }, - "application/vnd.leap+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.liberty-request+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.llamagraphics.life-balance.desktop": { - "source": "iana", - "extensions": ["lbd"] - }, - "application/vnd.llamagraphics.life-balance.exchange+xml": { - "source": "iana", - "compressible": true, - "extensions": ["lbe"] - }, - "application/vnd.logipipe.circuit+zip": { - "source": "iana", - "compressible": false - }, - "application/vnd.loom": { - "source": "iana" - }, - "application/vnd.lotus-1-2-3": { - "source": "iana", - "extensions": ["123"] - }, - "application/vnd.lotus-approach": { - "source": "iana", - "extensions": ["apr"] - }, - "application/vnd.lotus-freelance": { - "source": "iana", - "extensions": ["pre"] - }, - "application/vnd.lotus-notes": { - "source": "iana", - "extensions": ["nsf"] - }, - "application/vnd.lotus-organizer": { - "source": "iana", - "extensions": ["org"] - }, - "application/vnd.lotus-screencam": { - "source": "iana", - "extensions": ["scm"] - }, - "application/vnd.lotus-wordpro": { - "source": "iana", - "extensions": ["lwp"] - }, - "application/vnd.macports.portpkg": { - "source": "iana", - "extensions": ["portpkg"] - }, - "application/vnd.mapbox-vector-tile": { - "source": "iana" - }, - "application/vnd.marlin.drm.actiontoken+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.marlin.drm.conftoken+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.marlin.drm.license+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.marlin.drm.mdcf": { - "source": "iana" - }, - "application/vnd.mason+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.maxmind.maxmind-db": { - "source": "iana" - }, - "application/vnd.mcd": { - "source": "iana", - "extensions": ["mcd"] - }, - "application/vnd.medcalcdata": { - "source": "iana", - "extensions": ["mc1"] - }, - "application/vnd.mediastation.cdkey": { - "source": "iana", - "extensions": ["cdkey"] - }, - "application/vnd.meridian-slingshot": { - "source": "iana" - }, - "application/vnd.mfer": { - "source": "iana", - "extensions": ["mwf"] - }, - "application/vnd.mfmp": { - "source": "iana", - "extensions": ["mfm"] - }, - "application/vnd.micro+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.micrografx.flo": { - "source": "iana", - "extensions": ["flo"] - }, - "application/vnd.micrografx.igx": { - "source": "iana", - "extensions": ["igx"] - }, - "application/vnd.microsoft.portable-executable": { - "source": "iana" - }, - "application/vnd.microsoft.windows.thumbnail-cache": { - "source": "iana" - }, - "application/vnd.miele+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.mif": { - "source": "iana", - "extensions": ["mif"] - }, - "application/vnd.minisoft-hp3000-save": { - "source": "iana" - }, - "application/vnd.mitsubishi.misty-guard.trustweb": { - "source": "iana" - }, - "application/vnd.mobius.daf": { - "source": "iana", - "extensions": ["daf"] - }, - "application/vnd.mobius.dis": { - "source": "iana", - "extensions": ["dis"] - }, - "application/vnd.mobius.mbk": { - "source": "iana", - "extensions": ["mbk"] - }, - "application/vnd.mobius.mqy": { - "source": "iana", - "extensions": ["mqy"] - }, - "application/vnd.mobius.msl": { - "source": "iana", - "extensions": ["msl"] - }, - "application/vnd.mobius.plc": { - "source": "iana", - "extensions": ["plc"] - }, - "application/vnd.mobius.txf": { - "source": "iana", - "extensions": ["txf"] - }, - "application/vnd.mophun.application": { - "source": "iana", - "extensions": ["mpn"] - }, - "application/vnd.mophun.certificate": { - "source": "iana", - "extensions": ["mpc"] - }, - "application/vnd.motorola.flexsuite": { - "source": "iana" - }, - "application/vnd.motorola.flexsuite.adsi": { - "source": "iana" - }, - "application/vnd.motorola.flexsuite.fis": { - "source": "iana" - }, - "application/vnd.motorola.flexsuite.gotap": { - "source": "iana" - }, - "application/vnd.motorola.flexsuite.kmr": { - "source": "iana" - }, - "application/vnd.motorola.flexsuite.ttc": { - "source": "iana" - }, - "application/vnd.motorola.flexsuite.wem": { - "source": "iana" - }, - "application/vnd.motorola.iprm": { - "source": "iana" - }, - "application/vnd.mozilla.xul+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xul"] - }, - "application/vnd.ms-3mfdocument": { - "source": "iana" - }, - "application/vnd.ms-artgalry": { - "source": "iana", - "extensions": ["cil"] - }, - "application/vnd.ms-asf": { - "source": "iana" - }, - "application/vnd.ms-cab-compressed": { - "source": "iana", - "extensions": ["cab"] - }, - "application/vnd.ms-color.iccprofile": { - "source": "apache" - }, - "application/vnd.ms-excel": { - "source": "iana", - "compressible": false, - "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] - }, - "application/vnd.ms-excel.addin.macroenabled.12": { - "source": "iana", - "extensions": ["xlam"] - }, - "application/vnd.ms-excel.sheet.binary.macroenabled.12": { - "source": "iana", - "extensions": ["xlsb"] - }, - "application/vnd.ms-excel.sheet.macroenabled.12": { - "source": "iana", - "extensions": ["xlsm"] - }, - "application/vnd.ms-excel.template.macroenabled.12": { - "source": "iana", - "extensions": ["xltm"] - }, - "application/vnd.ms-fontobject": { - "source": "iana", - "compressible": true, - "extensions": ["eot"] - }, - "application/vnd.ms-htmlhelp": { - "source": "iana", - "extensions": ["chm"] - }, - "application/vnd.ms-ims": { - "source": "iana", - "extensions": ["ims"] - }, - "application/vnd.ms-lrm": { - "source": "iana", - "extensions": ["lrm"] - }, - "application/vnd.ms-office.activex+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.ms-officetheme": { - "source": "iana", - "extensions": ["thmx"] - }, - "application/vnd.ms-opentype": { - "source": "apache", - "compressible": true - }, - "application/vnd.ms-outlook": { - "compressible": false, - "extensions": ["msg"] - }, - "application/vnd.ms-package.obfuscated-opentype": { - "source": "apache" - }, - "application/vnd.ms-pki.seccat": { - "source": "apache", - "extensions": ["cat"] - }, - "application/vnd.ms-pki.stl": { - "source": "apache", - "extensions": ["stl"] - }, - "application/vnd.ms-playready.initiator+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.ms-powerpoint": { - "source": "iana", - "compressible": false, - "extensions": ["ppt","pps","pot"] - }, - "application/vnd.ms-powerpoint.addin.macroenabled.12": { - "source": "iana", - "extensions": ["ppam"] - }, - "application/vnd.ms-powerpoint.presentation.macroenabled.12": { - "source": "iana", - "extensions": ["pptm"] - }, - "application/vnd.ms-powerpoint.slide.macroenabled.12": { - "source": "iana", - "extensions": ["sldm"] - }, - "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { - "source": "iana", - "extensions": ["ppsm"] - }, - "application/vnd.ms-powerpoint.template.macroenabled.12": { - "source": "iana", - "extensions": ["potm"] - }, - "application/vnd.ms-printdevicecapabilities+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.ms-printing.printticket+xml": { - "source": "apache", - "compressible": true - }, - "application/vnd.ms-printschematicket+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.ms-project": { - "source": "iana", - "extensions": ["mpp","mpt"] - }, - "application/vnd.ms-tnef": { - "source": "iana" - }, - "application/vnd.ms-windows.devicepairing": { - "source": "iana" - }, - "application/vnd.ms-windows.nwprinting.oob": { - "source": "iana" - }, - "application/vnd.ms-windows.printerpairing": { - "source": "iana" - }, - "application/vnd.ms-windows.wsd.oob": { - "source": "iana" - }, - "application/vnd.ms-wmdrm.lic-chlg-req": { - "source": "iana" - }, - "application/vnd.ms-wmdrm.lic-resp": { - "source": "iana" - }, - "application/vnd.ms-wmdrm.meter-chlg-req": { - "source": "iana" - }, - "application/vnd.ms-wmdrm.meter-resp": { - "source": "iana" - }, - "application/vnd.ms-word.document.macroenabled.12": { - "source": "iana", - "extensions": ["docm"] - }, - "application/vnd.ms-word.template.macroenabled.12": { - "source": "iana", - "extensions": ["dotm"] - }, - "application/vnd.ms-works": { - "source": "iana", - "extensions": ["wps","wks","wcm","wdb"] - }, - "application/vnd.ms-wpl": { - "source": "iana", - "extensions": ["wpl"] - }, - "application/vnd.ms-xpsdocument": { - "source": "iana", - "compressible": false, - "extensions": ["xps"] - }, - "application/vnd.msa-disk-image": { - "source": "iana" - }, - "application/vnd.mseq": { - "source": "iana", - "extensions": ["mseq"] - }, - "application/vnd.msign": { - "source": "iana" - }, - "application/vnd.multiad.creator": { - "source": "iana" - }, - "application/vnd.multiad.creator.cif": { - "source": "iana" - }, - "application/vnd.music-niff": { - "source": "iana" - }, - "application/vnd.musician": { - "source": "iana", - "extensions": ["mus"] - }, - "application/vnd.muvee.style": { - "source": "iana", - "extensions": ["msty"] - }, - "application/vnd.mynfc": { - "source": "iana", - "extensions": ["taglet"] - }, - "application/vnd.ncd.control": { - "source": "iana" - }, - "application/vnd.ncd.reference": { - "source": "iana" - }, - "application/vnd.nearst.inv+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.nervana": { - "source": "iana" - }, - "application/vnd.netfpx": { - "source": "iana" - }, - "application/vnd.neurolanguage.nlu": { - "source": "iana", - "extensions": ["nlu"] - }, - "application/vnd.nimn": { - "source": "iana" - }, - "application/vnd.nintendo.nitro.rom": { - "source": "iana" - }, - "application/vnd.nintendo.snes.rom": { - "source": "iana" - }, - "application/vnd.nitf": { - "source": "iana", - "extensions": ["ntf","nitf"] - }, - "application/vnd.noblenet-directory": { - "source": "iana", - "extensions": ["nnd"] - }, - "application/vnd.noblenet-sealer": { - "source": "iana", - "extensions": ["nns"] - }, - "application/vnd.noblenet-web": { - "source": "iana", - "extensions": ["nnw"] - }, - "application/vnd.nokia.catalogs": { - "source": "iana" - }, - "application/vnd.nokia.conml+wbxml": { - "source": "iana" - }, - "application/vnd.nokia.conml+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.nokia.iptv.config+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.nokia.isds-radio-presets": { - "source": "iana" - }, - "application/vnd.nokia.landmark+wbxml": { - "source": "iana" - }, - "application/vnd.nokia.landmark+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.nokia.landmarkcollection+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.nokia.n-gage.ac+xml": { - "source": "iana", - "compressible": true, - "extensions": ["ac"] - }, - "application/vnd.nokia.n-gage.data": { - "source": "iana", - "extensions": ["ngdat"] - }, - "application/vnd.nokia.n-gage.symbian.install": { - "source": "iana", - "extensions": ["n-gage"] - }, - "application/vnd.nokia.ncd": { - "source": "iana" - }, - "application/vnd.nokia.pcd+wbxml": { - "source": "iana" - }, - "application/vnd.nokia.pcd+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.nokia.radio-preset": { - "source": "iana", - "extensions": ["rpst"] - }, - "application/vnd.nokia.radio-presets": { - "source": "iana", - "extensions": ["rpss"] - }, - "application/vnd.novadigm.edm": { - "source": "iana", - "extensions": ["edm"] - }, - "application/vnd.novadigm.edx": { - "source": "iana", - "extensions": ["edx"] - }, - "application/vnd.novadigm.ext": { - "source": "iana", - "extensions": ["ext"] - }, - "application/vnd.ntt-local.content-share": { - "source": "iana" - }, - "application/vnd.ntt-local.file-transfer": { - "source": "iana" - }, - "application/vnd.ntt-local.ogw_remote-access": { - "source": "iana" - }, - "application/vnd.ntt-local.sip-ta_remote": { - "source": "iana" - }, - "application/vnd.ntt-local.sip-ta_tcp_stream": { - "source": "iana" - }, - "application/vnd.oasis.opendocument.chart": { - "source": "iana", - "extensions": ["odc"] - }, - "application/vnd.oasis.opendocument.chart-template": { - "source": "iana", - "extensions": ["otc"] - }, - "application/vnd.oasis.opendocument.database": { - "source": "iana", - "extensions": ["odb"] - }, - "application/vnd.oasis.opendocument.formula": { - "source": "iana", - "extensions": ["odf"] - }, - "application/vnd.oasis.opendocument.formula-template": { - "source": "iana", - "extensions": ["odft"] - }, - "application/vnd.oasis.opendocument.graphics": { - "source": "iana", - "compressible": false, - "extensions": ["odg"] - }, - "application/vnd.oasis.opendocument.graphics-template": { - "source": "iana", - "extensions": ["otg"] - }, - "application/vnd.oasis.opendocument.image": { - "source": "iana", - "extensions": ["odi"] - }, - "application/vnd.oasis.opendocument.image-template": { - "source": "iana", - "extensions": ["oti"] - }, - "application/vnd.oasis.opendocument.presentation": { - "source": "iana", - "compressible": false, - "extensions": ["odp"] - }, - "application/vnd.oasis.opendocument.presentation-template": { - "source": "iana", - "extensions": ["otp"] - }, - "application/vnd.oasis.opendocument.spreadsheet": { - "source": "iana", - "compressible": false, - "extensions": ["ods"] - }, - "application/vnd.oasis.opendocument.spreadsheet-template": { - "source": "iana", - "extensions": ["ots"] - }, - "application/vnd.oasis.opendocument.text": { - "source": "iana", - "compressible": false, - "extensions": ["odt"] - }, - "application/vnd.oasis.opendocument.text-master": { - "source": "iana", - "extensions": ["odm"] - }, - "application/vnd.oasis.opendocument.text-template": { - "source": "iana", - "extensions": ["ott"] - }, - "application/vnd.oasis.opendocument.text-web": { - "source": "iana", - "extensions": ["oth"] - }, - "application/vnd.obn": { - "source": "iana" - }, - "application/vnd.ocf+cbor": { - "source": "iana" - }, - "application/vnd.oci.image.manifest.v1+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.oftn.l10n+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.contentaccessdownload+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.contentaccessstreaming+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.cspg-hexbinary": { - "source": "iana" - }, - "application/vnd.oipf.dae.svg+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.dae.xhtml+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.mippvcontrolmessage+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.pae.gem": { - "source": "iana" - }, - "application/vnd.oipf.spdiscovery+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.spdlist+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.ueprofile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oipf.userprofile+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.olpc-sugar": { - "source": "iana", - "extensions": ["xo"] - }, - "application/vnd.oma-scws-config": { - "source": "iana" - }, - "application/vnd.oma-scws-http-request": { - "source": "iana" - }, - "application/vnd.oma-scws-http-response": { - "source": "iana" - }, - "application/vnd.oma.bcast.associated-procedure-parameter+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.drm-trigger+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.imd+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.ltkm": { - "source": "iana" - }, - "application/vnd.oma.bcast.notification+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.provisioningtrigger": { - "source": "iana" - }, - "application/vnd.oma.bcast.sgboot": { - "source": "iana" - }, - "application/vnd.oma.bcast.sgdd+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.sgdu": { - "source": "iana" - }, - "application/vnd.oma.bcast.simple-symbol-container": { - "source": "iana" - }, - "application/vnd.oma.bcast.smartcard-trigger+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.sprov+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.bcast.stkm": { - "source": "iana" - }, - "application/vnd.oma.cab-address-book+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.cab-feature-handler+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.cab-pcc+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.cab-subs-invite+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.cab-user-prefs+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.dcd": { - "source": "iana" - }, - "application/vnd.oma.dcdc": { - "source": "iana" - }, - "application/vnd.oma.dd2+xml": { - "source": "iana", - "compressible": true, - "extensions": ["dd2"] - }, - "application/vnd.oma.drm.risd+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.group-usage-list+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.lwm2m+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.lwm2m+tlv": { - "source": "iana" - }, - "application/vnd.oma.pal+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.poc.detailed-progress-report+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.poc.final-report+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.poc.groups+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.poc.invocation-descriptor+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.poc.optimized-progress-report+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.push": { - "source": "iana" - }, - "application/vnd.oma.scidm.messages+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oma.xcap-directory+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.omads-email+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/vnd.omads-file+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/vnd.omads-folder+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/vnd.omaloc-supl-init": { - "source": "iana" - }, - "application/vnd.onepager": { - "source": "iana" - }, - "application/vnd.onepagertamp": { - "source": "iana" - }, - "application/vnd.onepagertamx": { - "source": "iana" - }, - "application/vnd.onepagertat": { - "source": "iana" - }, - "application/vnd.onepagertatp": { - "source": "iana" - }, - "application/vnd.onepagertatx": { - "source": "iana" - }, - "application/vnd.openblox.game+xml": { - "source": "iana", - "compressible": true, - "extensions": ["obgx"] - }, - "application/vnd.openblox.game-binary": { - "source": "iana" - }, - "application/vnd.openeye.oeb": { - "source": "iana" - }, - "application/vnd.openofficeorg.extension": { - "source": "apache", - "extensions": ["oxt"] - }, - "application/vnd.openstreetmap.data+xml": { - "source": "iana", - "compressible": true, - "extensions": ["osm"] - }, - "application/vnd.openxmlformats-officedocument.custom-properties+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawing+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.extended-properties+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.presentation": { - "source": "iana", - "compressible": false, - "extensions": ["pptx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slide": { - "source": "iana", - "extensions": ["sldx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { - "source": "iana", - "extensions": ["ppsx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.template": { - "source": "iana", - "extensions": ["potx"] - }, - "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { - "source": "iana", - "compressible": false, - "extensions": ["xlsx"] - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { - "source": "iana", - "extensions": ["xltx"] - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.theme+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.themeoverride+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.vmldrawing": { - "source": "iana" - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { - "source": "iana", - "compressible": false, - "extensions": ["docx"] - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { - "source": "iana", - "extensions": ["dotx"] - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-package.core-properties+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.openxmlformats-package.relationships+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oracle.resource+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.orange.indata": { - "source": "iana" - }, - "application/vnd.osa.netdeploy": { - "source": "iana" - }, - "application/vnd.osgeo.mapguide.package": { - "source": "iana", - "extensions": ["mgp"] - }, - "application/vnd.osgi.bundle": { - "source": "iana" - }, - "application/vnd.osgi.dp": { - "source": "iana", - "extensions": ["dp"] - }, - "application/vnd.osgi.subsystem": { - "source": "iana", - "extensions": ["esa"] - }, - "application/vnd.otps.ct-kip+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.oxli.countgraph": { - "source": "iana" - }, - "application/vnd.pagerduty+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.palm": { - "source": "iana", - "extensions": ["pdb","pqa","oprc"] - }, - "application/vnd.panoply": { - "source": "iana" - }, - "application/vnd.paos.xml": { - "source": "iana" - }, - "application/vnd.patentdive": { - "source": "iana" - }, - "application/vnd.patientecommsdoc": { - "source": "iana" - }, - "application/vnd.pawaafile": { - "source": "iana", - "extensions": ["paw"] - }, - "application/vnd.pcos": { - "source": "iana" - }, - "application/vnd.pg.format": { - "source": "iana", - "extensions": ["str"] - }, - "application/vnd.pg.osasli": { - "source": "iana", - "extensions": ["ei6"] - }, - "application/vnd.piaccess.application-licence": { - "source": "iana" - }, - "application/vnd.picsel": { - "source": "iana", - "extensions": ["efif"] - }, - "application/vnd.pmi.widget": { - "source": "iana", - "extensions": ["wg"] - }, - "application/vnd.poc.group-advertisement+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.pocketlearn": { - "source": "iana", - "extensions": ["plf"] - }, - "application/vnd.powerbuilder6": { - "source": "iana", - "extensions": ["pbd"] - }, - "application/vnd.powerbuilder6-s": { - "source": "iana" - }, - "application/vnd.powerbuilder7": { - "source": "iana" - }, - "application/vnd.powerbuilder7-s": { - "source": "iana" - }, - "application/vnd.powerbuilder75": { - "source": "iana" - }, - "application/vnd.powerbuilder75-s": { - "source": "iana" - }, - "application/vnd.preminet": { - "source": "iana" - }, - "application/vnd.previewsystems.box": { - "source": "iana", - "extensions": ["box"] - }, - "application/vnd.proteus.magazine": { - "source": "iana", - "extensions": ["mgz"] - }, - "application/vnd.psfs": { - "source": "iana" - }, - "application/vnd.publishare-delta-tree": { - "source": "iana", - "extensions": ["qps"] - }, - "application/vnd.pvi.ptid1": { - "source": "iana", - "extensions": ["ptid"] - }, - "application/vnd.pwg-multiplexed": { - "source": "iana" - }, - "application/vnd.pwg-xhtml-print+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.qualcomm.brew-app-res": { - "source": "iana" - }, - "application/vnd.quarantainenet": { - "source": "iana" - }, - "application/vnd.quark.quarkxpress": { - "source": "iana", - "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] - }, - "application/vnd.quobject-quoxdocument": { - "source": "iana" - }, - "application/vnd.radisys.moml+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-audit+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-audit-conf+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-audit-conn+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-audit-dialog+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-audit-stream+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-conf+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog-base+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog-fax-detect+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog-group+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog-speech+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.radisys.msml-dialog-transform+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.rainstor.data": { - "source": "iana" - }, - "application/vnd.rapid": { - "source": "iana" - }, - "application/vnd.rar": { - "source": "iana" - }, - "application/vnd.realvnc.bed": { - "source": "iana", - "extensions": ["bed"] - }, - "application/vnd.recordare.musicxml": { - "source": "iana", - "extensions": ["mxl"] - }, - "application/vnd.recordare.musicxml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["musicxml"] - }, - "application/vnd.renlearn.rlprint": { - "source": "iana" - }, - "application/vnd.restful+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.rig.cryptonote": { - "source": "iana", - "extensions": ["cryptonote"] - }, - "application/vnd.rim.cod": { - "source": "apache", - "extensions": ["cod"] - }, - "application/vnd.rn-realmedia": { - "source": "apache", - "extensions": ["rm"] - }, - "application/vnd.rn-realmedia-vbr": { - "source": "apache", - "extensions": ["rmvb"] - }, - "application/vnd.route66.link66+xml": { - "source": "iana", - "compressible": true, - "extensions": ["link66"] - }, - "application/vnd.rs-274x": { - "source": "iana" - }, - "application/vnd.ruckus.download": { - "source": "iana" - }, - "application/vnd.s3sms": { - "source": "iana" - }, - "application/vnd.sailingtracker.track": { - "source": "iana", - "extensions": ["st"] - }, - "application/vnd.sar": { - "source": "iana" - }, - "application/vnd.sbm.cid": { - "source": "iana" - }, - "application/vnd.sbm.mid2": { - "source": "iana" - }, - "application/vnd.scribus": { - "source": "iana" - }, - "application/vnd.sealed.3df": { - "source": "iana" - }, - "application/vnd.sealed.csf": { - "source": "iana" - }, - "application/vnd.sealed.doc": { - "source": "iana" - }, - "application/vnd.sealed.eml": { - "source": "iana" - }, - "application/vnd.sealed.mht": { - "source": "iana" - }, - "application/vnd.sealed.net": { - "source": "iana" - }, - "application/vnd.sealed.ppt": { - "source": "iana" - }, - "application/vnd.sealed.tiff": { - "source": "iana" - }, - "application/vnd.sealed.xls": { - "source": "iana" - }, - "application/vnd.sealedmedia.softseal.html": { - "source": "iana" - }, - "application/vnd.sealedmedia.softseal.pdf": { - "source": "iana" - }, - "application/vnd.seemail": { - "source": "iana", - "extensions": ["see"] - }, - "application/vnd.sema": { - "source": "iana", - "extensions": ["sema"] - }, - "application/vnd.semd": { - "source": "iana", - "extensions": ["semd"] - }, - "application/vnd.semf": { - "source": "iana", - "extensions": ["semf"] - }, - "application/vnd.shade-save-file": { - "source": "iana" - }, - "application/vnd.shana.informed.formdata": { - "source": "iana", - "extensions": ["ifm"] - }, - "application/vnd.shana.informed.formtemplate": { - "source": "iana", - "extensions": ["itp"] - }, - "application/vnd.shana.informed.interchange": { - "source": "iana", - "extensions": ["iif"] - }, - "application/vnd.shana.informed.package": { - "source": "iana", - "extensions": ["ipk"] - }, - "application/vnd.shootproof+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.shopkick+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.shp": { - "source": "iana" - }, - "application/vnd.shx": { - "source": "iana" - }, - "application/vnd.sigrok.session": { - "source": "iana" - }, - "application/vnd.simtech-mindmapper": { - "source": "iana", - "extensions": ["twd","twds"] - }, - "application/vnd.siren+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.smaf": { - "source": "iana", - "extensions": ["mmf"] - }, - "application/vnd.smart.notebook": { - "source": "iana" - }, - "application/vnd.smart.teacher": { - "source": "iana", - "extensions": ["teacher"] - }, - "application/vnd.snesdev-page-table": { - "source": "iana" - }, - "application/vnd.software602.filler.form+xml": { - "source": "iana", - "compressible": true, - "extensions": ["fo"] - }, - "application/vnd.software602.filler.form-xml-zip": { - "source": "iana" - }, - "application/vnd.solent.sdkm+xml": { - "source": "iana", - "compressible": true, - "extensions": ["sdkm","sdkd"] - }, - "application/vnd.spotfire.dxp": { - "source": "iana", - "extensions": ["dxp"] - }, - "application/vnd.spotfire.sfs": { - "source": "iana", - "extensions": ["sfs"] - }, - "application/vnd.sqlite3": { - "source": "iana" - }, - "application/vnd.sss-cod": { - "source": "iana" - }, - "application/vnd.sss-dtf": { - "source": "iana" - }, - "application/vnd.sss-ntf": { - "source": "iana" - }, - "application/vnd.stardivision.calc": { - "source": "apache", - "extensions": ["sdc"] - }, - "application/vnd.stardivision.draw": { - "source": "apache", - "extensions": ["sda"] - }, - "application/vnd.stardivision.impress": { - "source": "apache", - "extensions": ["sdd"] - }, - "application/vnd.stardivision.math": { - "source": "apache", - "extensions": ["smf"] - }, - "application/vnd.stardivision.writer": { - "source": "apache", - "extensions": ["sdw","vor"] - }, - "application/vnd.stardivision.writer-global": { - "source": "apache", - "extensions": ["sgl"] - }, - "application/vnd.stepmania.package": { - "source": "iana", - "extensions": ["smzip"] - }, - "application/vnd.stepmania.stepchart": { - "source": "iana", - "extensions": ["sm"] - }, - "application/vnd.street-stream": { - "source": "iana" - }, - "application/vnd.sun.wadl+xml": { - "source": "iana", - "compressible": true, - "extensions": ["wadl"] - }, - "application/vnd.sun.xml.calc": { - "source": "apache", - "extensions": ["sxc"] - }, - "application/vnd.sun.xml.calc.template": { - "source": "apache", - "extensions": ["stc"] - }, - "application/vnd.sun.xml.draw": { - "source": "apache", - "extensions": ["sxd"] - }, - "application/vnd.sun.xml.draw.template": { - "source": "apache", - "extensions": ["std"] - }, - "application/vnd.sun.xml.impress": { - "source": "apache", - "extensions": ["sxi"] - }, - "application/vnd.sun.xml.impress.template": { - "source": "apache", - "extensions": ["sti"] - }, - "application/vnd.sun.xml.math": { - "source": "apache", - "extensions": ["sxm"] - }, - "application/vnd.sun.xml.writer": { - "source": "apache", - "extensions": ["sxw"] - }, - "application/vnd.sun.xml.writer.global": { - "source": "apache", - "extensions": ["sxg"] - }, - "application/vnd.sun.xml.writer.template": { - "source": "apache", - "extensions": ["stw"] - }, - "application/vnd.sus-calendar": { - "source": "iana", - "extensions": ["sus","susp"] - }, - "application/vnd.svd": { - "source": "iana", - "extensions": ["svd"] - }, - "application/vnd.swiftview-ics": { - "source": "iana" - }, - "application/vnd.symbian.install": { - "source": "apache", - "extensions": ["sis","sisx"] - }, - "application/vnd.syncml+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true, - "extensions": ["xsm"] - }, - "application/vnd.syncml.dm+wbxml": { - "source": "iana", - "charset": "UTF-8", - "extensions": ["bdm"] - }, - "application/vnd.syncml.dm+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true, - "extensions": ["xdm"] - }, - "application/vnd.syncml.dm.notification": { - "source": "iana" - }, - "application/vnd.syncml.dmddf+wbxml": { - "source": "iana" - }, - "application/vnd.syncml.dmddf+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true, - "extensions": ["ddf"] - }, - "application/vnd.syncml.dmtnds+wbxml": { - "source": "iana" - }, - "application/vnd.syncml.dmtnds+xml": { - "source": "iana", - "charset": "UTF-8", - "compressible": true - }, - "application/vnd.syncml.ds.notification": { - "source": "iana" - }, - "application/vnd.tableschema+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.tao.intent-module-archive": { - "source": "iana", - "extensions": ["tao"] - }, - "application/vnd.tcpdump.pcap": { - "source": "iana", - "extensions": ["pcap","cap","dmp"] - }, - "application/vnd.think-cell.ppttc+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.tmd.mediaflex.api+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.tml": { - "source": "iana" - }, - "application/vnd.tmobile-livetv": { - "source": "iana", - "extensions": ["tmo"] - }, - "application/vnd.tri.onesource": { - "source": "iana" - }, - "application/vnd.trid.tpt": { - "source": "iana", - "extensions": ["tpt"] - }, - "application/vnd.triscape.mxs": { - "source": "iana", - "extensions": ["mxs"] - }, - "application/vnd.trueapp": { - "source": "iana", - "extensions": ["tra"] - }, - "application/vnd.truedoc": { - "source": "iana" - }, - "application/vnd.ubisoft.webplayer": { - "source": "iana" - }, - "application/vnd.ufdl": { - "source": "iana", - "extensions": ["ufd","ufdl"] - }, - "application/vnd.uiq.theme": { - "source": "iana", - "extensions": ["utz"] - }, - "application/vnd.umajin": { - "source": "iana", - "extensions": ["umj"] - }, - "application/vnd.unity": { - "source": "iana", - "extensions": ["unityweb"] - }, - "application/vnd.uoml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["uoml"] - }, - "application/vnd.uplanet.alert": { - "source": "iana" - }, - "application/vnd.uplanet.alert-wbxml": { - "source": "iana" - }, - "application/vnd.uplanet.bearer-choice": { - "source": "iana" - }, - "application/vnd.uplanet.bearer-choice-wbxml": { - "source": "iana" - }, - "application/vnd.uplanet.cacheop": { - "source": "iana" - }, - "application/vnd.uplanet.cacheop-wbxml": { - "source": "iana" - }, - "application/vnd.uplanet.channel": { - "source": "iana" - }, - "application/vnd.uplanet.channel-wbxml": { - "source": "iana" - }, - "application/vnd.uplanet.list": { - "source": "iana" - }, - "application/vnd.uplanet.list-wbxml": { - "source": "iana" - }, - "application/vnd.uplanet.listcmd": { - "source": "iana" - }, - "application/vnd.uplanet.listcmd-wbxml": { - "source": "iana" - }, - "application/vnd.uplanet.signal": { - "source": "iana" - }, - "application/vnd.uri-map": { - "source": "iana" - }, - "application/vnd.valve.source.material": { - "source": "iana" - }, - "application/vnd.vcx": { - "source": "iana", - "extensions": ["vcx"] - }, - "application/vnd.vd-study": { - "source": "iana" - }, - "application/vnd.vectorworks": { - "source": "iana" - }, - "application/vnd.vel+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.verimatrix.vcas": { - "source": "iana" - }, - "application/vnd.veryant.thin": { - "source": "iana" - }, - "application/vnd.ves.encrypted": { - "source": "iana" - }, - "application/vnd.vidsoft.vidconference": { - "source": "iana" - }, - "application/vnd.visio": { - "source": "iana", - "extensions": ["vsd","vst","vss","vsw"] - }, - "application/vnd.visionary": { - "source": "iana", - "extensions": ["vis"] - }, - "application/vnd.vividence.scriptfile": { - "source": "iana" - }, - "application/vnd.vsf": { - "source": "iana", - "extensions": ["vsf"] - }, - "application/vnd.wap.sic": { - "source": "iana" - }, - "application/vnd.wap.slc": { - "source": "iana" - }, - "application/vnd.wap.wbxml": { - "source": "iana", - "charset": "UTF-8", - "extensions": ["wbxml"] - }, - "application/vnd.wap.wmlc": { - "source": "iana", - "extensions": ["wmlc"] - }, - "application/vnd.wap.wmlscriptc": { - "source": "iana", - "extensions": ["wmlsc"] - }, - "application/vnd.webturbo": { - "source": "iana", - "extensions": ["wtb"] - }, - "application/vnd.wfa.p2p": { - "source": "iana" - }, - "application/vnd.wfa.wsc": { - "source": "iana" - }, - "application/vnd.windows.devicepairing": { - "source": "iana" - }, - "application/vnd.wmc": { - "source": "iana" - }, - "application/vnd.wmf.bootstrap": { - "source": "iana" - }, - "application/vnd.wolfram.mathematica": { - "source": "iana" - }, - "application/vnd.wolfram.mathematica.package": { - "source": "iana" - }, - "application/vnd.wolfram.player": { - "source": "iana", - "extensions": ["nbp"] - }, - "application/vnd.wordperfect": { - "source": "iana", - "extensions": ["wpd"] - }, - "application/vnd.wqd": { - "source": "iana", - "extensions": ["wqd"] - }, - "application/vnd.wrq-hp3000-labelled": { - "source": "iana" - }, - "application/vnd.wt.stf": { - "source": "iana", - "extensions": ["stf"] - }, - "application/vnd.wv.csp+wbxml": { - "source": "iana" - }, - "application/vnd.wv.csp+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.wv.ssp+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.xacml+json": { - "source": "iana", - "compressible": true - }, - "application/vnd.xara": { - "source": "iana", - "extensions": ["xar"] - }, - "application/vnd.xfdl": { - "source": "iana", - "extensions": ["xfdl"] - }, - "application/vnd.xfdl.webform": { - "source": "iana" - }, - "application/vnd.xmi+xml": { - "source": "iana", - "compressible": true - }, - "application/vnd.xmpie.cpkg": { - "source": "iana" - }, - "application/vnd.xmpie.dpkg": { - "source": "iana" - }, - "application/vnd.xmpie.plan": { - "source": "iana" - }, - "application/vnd.xmpie.ppkg": { - "source": "iana" - }, - "application/vnd.xmpie.xlim": { - "source": "iana" - }, - "application/vnd.yamaha.hv-dic": { - "source": "iana", - "extensions": ["hvd"] - }, - "application/vnd.yamaha.hv-script": { - "source": "iana", - "extensions": ["hvs"] - }, - "application/vnd.yamaha.hv-voice": { - "source": "iana", - "extensions": ["hvp"] - }, - "application/vnd.yamaha.openscoreformat": { - "source": "iana", - "extensions": ["osf"] - }, - "application/vnd.yamaha.openscoreformat.osfpvg+xml": { - "source": "iana", - "compressible": true, - "extensions": ["osfpvg"] - }, - "application/vnd.yamaha.remote-setup": { - "source": "iana" - }, - "application/vnd.yamaha.smaf-audio": { - "source": "iana", - "extensions": ["saf"] - }, - "application/vnd.yamaha.smaf-phrase": { - "source": "iana", - "extensions": ["spf"] - }, - "application/vnd.yamaha.through-ngn": { - "source": "iana" - }, - "application/vnd.yamaha.tunnel-udpencap": { - "source": "iana" - }, - "application/vnd.yaoweme": { - "source": "iana" - }, - "application/vnd.yellowriver-custom-menu": { - "source": "iana", - "extensions": ["cmp"] - }, - "application/vnd.youtube.yt": { - "source": "iana" - }, - "application/vnd.zul": { - "source": "iana", - "extensions": ["zir","zirz"] - }, - "application/vnd.zzazz.deck+xml": { - "source": "iana", - "compressible": true, - "extensions": ["zaz"] - }, - "application/voicexml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["vxml"] - }, - "application/voucher-cms+json": { - "source": "iana", - "compressible": true - }, - "application/vq-rtcpxr": { - "source": "iana" - }, - "application/wasm": { - "compressible": true, - "extensions": ["wasm"] - }, - "application/watcherinfo+xml": { - "source": "iana", - "compressible": true - }, - "application/webpush-options+json": { - "source": "iana", - "compressible": true - }, - "application/whoispp-query": { - "source": "iana" - }, - "application/whoispp-response": { - "source": "iana" - }, - "application/widget": { - "source": "iana", - "extensions": ["wgt"] - }, - "application/winhlp": { - "source": "apache", - "extensions": ["hlp"] - }, - "application/wita": { - "source": "iana" - }, - "application/wordperfect5.1": { - "source": "iana" - }, - "application/wsdl+xml": { - "source": "iana", - "compressible": true, - "extensions": ["wsdl"] - }, - "application/wspolicy+xml": { - "source": "iana", - "compressible": true, - "extensions": ["wspolicy"] - }, - "application/x-7z-compressed": { - "source": "apache", - "compressible": false, - "extensions": ["7z"] - }, - "application/x-abiword": { - "source": "apache", - "extensions": ["abw"] - }, - "application/x-ace-compressed": { - "source": "apache", - "extensions": ["ace"] - }, - "application/x-amf": { - "source": "apache" - }, - "application/x-apple-diskimage": { - "source": "apache", - "extensions": ["dmg"] - }, - "application/x-arj": { - "compressible": false, - "extensions": ["arj"] - }, - "application/x-authorware-bin": { - "source": "apache", - "extensions": ["aab","x32","u32","vox"] - }, - "application/x-authorware-map": { - "source": "apache", - "extensions": ["aam"] - }, - "application/x-authorware-seg": { - "source": "apache", - "extensions": ["aas"] - }, - "application/x-bcpio": { - "source": "apache", - "extensions": ["bcpio"] - }, - "application/x-bdoc": { - "compressible": false, - "extensions": ["bdoc"] - }, - "application/x-bittorrent": { - "source": "apache", - "extensions": ["torrent"] - }, - "application/x-blorb": { - "source": "apache", - "extensions": ["blb","blorb"] - }, - "application/x-bzip": { - "source": "apache", - "compressible": false, - "extensions": ["bz"] - }, - "application/x-bzip2": { - "source": "apache", - "compressible": false, - "extensions": ["bz2","boz"] - }, - "application/x-cbr": { - "source": "apache", - "extensions": ["cbr","cba","cbt","cbz","cb7"] - }, - "application/x-cdlink": { - "source": "apache", - "extensions": ["vcd"] - }, - "application/x-cfs-compressed": { - "source": "apache", - "extensions": ["cfs"] - }, - "application/x-chat": { - "source": "apache", - "extensions": ["chat"] - }, - "application/x-chess-pgn": { - "source": "apache", - "extensions": ["pgn"] - }, - "application/x-chrome-extension": { - "extensions": ["crx"] - }, - "application/x-cocoa": { - "source": "nginx", - "extensions": ["cco"] - }, - "application/x-compress": { - "source": "apache" - }, - "application/x-conference": { - "source": "apache", - "extensions": ["nsc"] - }, - "application/x-cpio": { - "source": "apache", - "extensions": ["cpio"] - }, - "application/x-csh": { - "source": "apache", - "extensions": ["csh"] - }, - "application/x-deb": { - "compressible": false - }, - "application/x-debian-package": { - "source": "apache", - "extensions": ["deb","udeb"] - }, - "application/x-dgc-compressed": { - "source": "apache", - "extensions": ["dgc"] - }, - "application/x-director": { - "source": "apache", - "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] - }, - "application/x-doom": { - "source": "apache", - "extensions": ["wad"] - }, - "application/x-dtbncx+xml": { - "source": "apache", - "compressible": true, - "extensions": ["ncx"] - }, - "application/x-dtbook+xml": { - "source": "apache", - "compressible": true, - "extensions": ["dtb"] - }, - "application/x-dtbresource+xml": { - "source": "apache", - "compressible": true, - "extensions": ["res"] - }, - "application/x-dvi": { - "source": "apache", - "compressible": false, - "extensions": ["dvi"] - }, - "application/x-envoy": { - "source": "apache", - "extensions": ["evy"] - }, - "application/x-eva": { - "source": "apache", - "extensions": ["eva"] - }, - "application/x-font-bdf": { - "source": "apache", - "extensions": ["bdf"] - }, - "application/x-font-dos": { - "source": "apache" - }, - "application/x-font-framemaker": { - "source": "apache" - }, - "application/x-font-ghostscript": { - "source": "apache", - "extensions": ["gsf"] - }, - "application/x-font-libgrx": { - "source": "apache" - }, - "application/x-font-linux-psf": { - "source": "apache", - "extensions": ["psf"] - }, - "application/x-font-pcf": { - "source": "apache", - "extensions": ["pcf"] - }, - "application/x-font-snf": { - "source": "apache", - "extensions": ["snf"] - }, - "application/x-font-speedo": { - "source": "apache" - }, - "application/x-font-sunos-news": { - "source": "apache" - }, - "application/x-font-type1": { - "source": "apache", - "extensions": ["pfa","pfb","pfm","afm"] - }, - "application/x-font-vfont": { - "source": "apache" - }, - "application/x-freearc": { - "source": "apache", - "extensions": ["arc"] - }, - "application/x-futuresplash": { - "source": "apache", - "extensions": ["spl"] - }, - "application/x-gca-compressed": { - "source": "apache", - "extensions": ["gca"] - }, - "application/x-glulx": { - "source": "apache", - "extensions": ["ulx"] - }, - "application/x-gnumeric": { - "source": "apache", - "extensions": ["gnumeric"] - }, - "application/x-gramps-xml": { - "source": "apache", - "extensions": ["gramps"] - }, - "application/x-gtar": { - "source": "apache", - "extensions": ["gtar"] - }, - "application/x-gzip": { - "source": "apache" - }, - "application/x-hdf": { - "source": "apache", - "extensions": ["hdf"] - }, - "application/x-httpd-php": { - "compressible": true, - "extensions": ["php"] - }, - "application/x-install-instructions": { - "source": "apache", - "extensions": ["install"] - }, - "application/x-iso9660-image": { - "source": "apache", - "extensions": ["iso"] - }, - "application/x-java-archive-diff": { - "source": "nginx", - "extensions": ["jardiff"] - }, - "application/x-java-jnlp-file": { - "source": "apache", - "compressible": false, - "extensions": ["jnlp"] - }, - "application/x-javascript": { - "compressible": true - }, - "application/x-keepass2": { - "extensions": ["kdbx"] - }, - "application/x-latex": { - "source": "apache", - "compressible": false, - "extensions": ["latex"] - }, - "application/x-lua-bytecode": { - "extensions": ["luac"] - }, - "application/x-lzh-compressed": { - "source": "apache", - "extensions": ["lzh","lha"] - }, - "application/x-makeself": { - "source": "nginx", - "extensions": ["run"] - }, - "application/x-mie": { - "source": "apache", - "extensions": ["mie"] - }, - "application/x-mobipocket-ebook": { - "source": "apache", - "extensions": ["prc","mobi"] - }, - "application/x-mpegurl": { - "compressible": false - }, - "application/x-ms-application": { - "source": "apache", - "extensions": ["application"] - }, - "application/x-ms-shortcut": { - "source": "apache", - "extensions": ["lnk"] - }, - "application/x-ms-wmd": { - "source": "apache", - "extensions": ["wmd"] - }, - "application/x-ms-wmz": { - "source": "apache", - "extensions": ["wmz"] - }, - "application/x-ms-xbap": { - "source": "apache", - "extensions": ["xbap"] - }, - "application/x-msaccess": { - "source": "apache", - "extensions": ["mdb"] - }, - "application/x-msbinder": { - "source": "apache", - "extensions": ["obd"] - }, - "application/x-mscardfile": { - "source": "apache", - "extensions": ["crd"] - }, - "application/x-msclip": { - "source": "apache", - "extensions": ["clp"] - }, - "application/x-msdos-program": { - "extensions": ["exe"] - }, - "application/x-msdownload": { - "source": "apache", - "extensions": ["exe","dll","com","bat","msi"] - }, - "application/x-msmediaview": { - "source": "apache", - "extensions": ["mvb","m13","m14"] - }, - "application/x-msmetafile": { - "source": "apache", - "extensions": ["wmf","wmz","emf","emz"] - }, - "application/x-msmoney": { - "source": "apache", - "extensions": ["mny"] - }, - "application/x-mspublisher": { - "source": "apache", - "extensions": ["pub"] - }, - "application/x-msschedule": { - "source": "apache", - "extensions": ["scd"] - }, - "application/x-msterminal": { - "source": "apache", - "extensions": ["trm"] - }, - "application/x-mswrite": { - "source": "apache", - "extensions": ["wri"] - }, - "application/x-netcdf": { - "source": "apache", - "extensions": ["nc","cdf"] - }, - "application/x-ns-proxy-autoconfig": { - "compressible": true, - "extensions": ["pac"] - }, - "application/x-nzb": { - "source": "apache", - "extensions": ["nzb"] - }, - "application/x-perl": { - "source": "nginx", - "extensions": ["pl","pm"] - }, - "application/x-pilot": { - "source": "nginx", - "extensions": ["prc","pdb"] - }, - "application/x-pkcs12": { - "source": "apache", - "compressible": false, - "extensions": ["p12","pfx"] - }, - "application/x-pkcs7-certificates": { - "source": "apache", - "extensions": ["p7b","spc"] - }, - "application/x-pkcs7-certreqresp": { - "source": "apache", - "extensions": ["p7r"] - }, - "application/x-pki-message": { - "source": "iana" - }, - "application/x-rar-compressed": { - "source": "apache", - "compressible": false, - "extensions": ["rar"] - }, - "application/x-redhat-package-manager": { - "source": "nginx", - "extensions": ["rpm"] - }, - "application/x-research-info-systems": { - "source": "apache", - "extensions": ["ris"] - }, - "application/x-sea": { - "source": "nginx", - "extensions": ["sea"] - }, - "application/x-sh": { - "source": "apache", - "compressible": true, - "extensions": ["sh"] - }, - "application/x-shar": { - "source": "apache", - "extensions": ["shar"] - }, - "application/x-shockwave-flash": { - "source": "apache", - "compressible": false, - "extensions": ["swf"] - }, - "application/x-silverlight-app": { - "source": "apache", - "extensions": ["xap"] - }, - "application/x-sql": { - "source": "apache", - "extensions": ["sql"] - }, - "application/x-stuffit": { - "source": "apache", - "compressible": false, - "extensions": ["sit"] - }, - "application/x-stuffitx": { - "source": "apache", - "extensions": ["sitx"] - }, - "application/x-subrip": { - "source": "apache", - "extensions": ["srt"] - }, - "application/x-sv4cpio": { - "source": "apache", - "extensions": ["sv4cpio"] - }, - "application/x-sv4crc": { - "source": "apache", - "extensions": ["sv4crc"] - }, - "application/x-t3vm-image": { - "source": "apache", - "extensions": ["t3"] - }, - "application/x-tads": { - "source": "apache", - "extensions": ["gam"] - }, - "application/x-tar": { - "source": "apache", - "compressible": true, - "extensions": ["tar"] - }, - "application/x-tcl": { - "source": "apache", - "extensions": ["tcl","tk"] - }, - "application/x-tex": { - "source": "apache", - "extensions": ["tex"] - }, - "application/x-tex-tfm": { - "source": "apache", - "extensions": ["tfm"] - }, - "application/x-texinfo": { - "source": "apache", - "extensions": ["texinfo","texi"] - }, - "application/x-tgif": { - "source": "apache", - "extensions": ["obj"] - }, - "application/x-ustar": { - "source": "apache", - "extensions": ["ustar"] - }, - "application/x-virtualbox-hdd": { - "compressible": true, - "extensions": ["hdd"] - }, - "application/x-virtualbox-ova": { - "compressible": true, - "extensions": ["ova"] - }, - "application/x-virtualbox-ovf": { - "compressible": true, - "extensions": ["ovf"] - }, - "application/x-virtualbox-vbox": { - "compressible": true, - "extensions": ["vbox"] - }, - "application/x-virtualbox-vbox-extpack": { - "compressible": false, - "extensions": ["vbox-extpack"] - }, - "application/x-virtualbox-vdi": { - "compressible": true, - "extensions": ["vdi"] - }, - "application/x-virtualbox-vhd": { - "compressible": true, - "extensions": ["vhd"] - }, - "application/x-virtualbox-vmdk": { - "compressible": true, - "extensions": ["vmdk"] - }, - "application/x-wais-source": { - "source": "apache", - "extensions": ["src"] - }, - "application/x-web-app-manifest+json": { - "compressible": true, - "extensions": ["webapp"] - }, - "application/x-www-form-urlencoded": { - "source": "iana", - "compressible": true - }, - "application/x-x509-ca-cert": { - "source": "iana", - "extensions": ["der","crt","pem"] - }, - "application/x-x509-ca-ra-cert": { - "source": "iana" - }, - "application/x-x509-next-ca-cert": { - "source": "iana" - }, - "application/x-xfig": { - "source": "apache", - "extensions": ["fig"] - }, - "application/x-xliff+xml": { - "source": "apache", - "compressible": true, - "extensions": ["xlf"] - }, - "application/x-xpinstall": { - "source": "apache", - "compressible": false, - "extensions": ["xpi"] - }, - "application/x-xz": { - "source": "apache", - "extensions": ["xz"] - }, - "application/x-zmachine": { - "source": "apache", - "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] - }, - "application/x400-bp": { - "source": "iana" - }, - "application/xacml+xml": { - "source": "iana", - "compressible": true - }, - "application/xaml+xml": { - "source": "apache", - "compressible": true, - "extensions": ["xaml"] - }, - "application/xcap-att+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xav"] - }, - "application/xcap-caps+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xca"] - }, - "application/xcap-diff+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xdf"] - }, - "application/xcap-el+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xel"] - }, - "application/xcap-error+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xer"] - }, - "application/xcap-ns+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xns"] - }, - "application/xcon-conference-info+xml": { - "source": "iana", - "compressible": true - }, - "application/xcon-conference-info-diff+xml": { - "source": "iana", - "compressible": true - }, - "application/xenc+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xenc"] - }, - "application/xhtml+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xhtml","xht"] - }, - "application/xhtml-voice+xml": { - "source": "apache", - "compressible": true - }, - "application/xliff+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xlf"] - }, - "application/xml": { - "source": "iana", - "compressible": true, - "extensions": ["xml","xsl","xsd","rng"] - }, - "application/xml-dtd": { - "source": "iana", - "compressible": true, - "extensions": ["dtd"] - }, - "application/xml-external-parsed-entity": { - "source": "iana" - }, - "application/xml-patch+xml": { - "source": "iana", - "compressible": true - }, - "application/xmpp+xml": { - "source": "iana", - "compressible": true - }, - "application/xop+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xop"] - }, - "application/xproc+xml": { - "source": "apache", - "compressible": true, - "extensions": ["xpl"] - }, - "application/xslt+xml": { - "source": "iana", - "compressible": true, - "extensions": ["xslt"] - }, - "application/xspf+xml": { - "source": "apache", - "compressible": true, - "extensions": ["xspf"] - }, - "application/xv+xml": { - "source": "iana", - "compressible": true, - "extensions": ["mxml","xhvml","xvml","xvm"] - }, - "application/yang": { - "source": "iana", - "extensions": ["yang"] - }, - "application/yang-data+json": { - "source": "iana", - "compressible": true - }, - "application/yang-data+xml": { - "source": "iana", - "compressible": true - }, - "application/yang-patch+json": { - "source": "iana", - "compressible": true - }, - "application/yang-patch+xml": { - "source": "iana", - "compressible": true - }, - "application/yin+xml": { - "source": "iana", - "compressible": true, - "extensions": ["yin"] - }, - "application/zip": { - "source": "iana", - "compressible": false, - "extensions": ["zip"] - }, - "application/zlib": { - "source": "iana" - }, - "application/zstd": { - "source": "iana" - }, - "audio/1d-interleaved-parityfec": { - "source": "iana" - }, - "audio/32kadpcm": { - "source": "iana" - }, - "audio/3gpp": { - "source": "iana", - "compressible": false, - "extensions": ["3gpp"] - }, - "audio/3gpp2": { - "source": "iana" - }, - "audio/aac": { - "source": "iana" - }, - "audio/ac3": { - "source": "iana" - }, - "audio/adpcm": { - "source": "apache", - "extensions": ["adp"] - }, - "audio/amr": { - "source": "iana" - }, - "audio/amr-wb": { - "source": "iana" - }, - "audio/amr-wb+": { - "source": "iana" - }, - "audio/aptx": { - "source": "iana" - }, - "audio/asc": { - "source": "iana" - }, - "audio/atrac-advanced-lossless": { - "source": "iana" - }, - "audio/atrac-x": { - "source": "iana" - }, - "audio/atrac3": { - "source": "iana" - }, - "audio/basic": { - "source": "iana", - "compressible": false, - "extensions": ["au","snd"] - }, - "audio/bv16": { - "source": "iana" - }, - "audio/bv32": { - "source": "iana" - }, - "audio/clearmode": { - "source": "iana" - }, - "audio/cn": { - "source": "iana" - }, - "audio/dat12": { - "source": "iana" - }, - "audio/dls": { - "source": "iana" - }, - "audio/dsr-es201108": { - "source": "iana" - }, - "audio/dsr-es202050": { - "source": "iana" - }, - "audio/dsr-es202211": { - "source": "iana" - }, - "audio/dsr-es202212": { - "source": "iana" - }, - "audio/dv": { - "source": "iana" - }, - "audio/dvi4": { - "source": "iana" - }, - "audio/eac3": { - "source": "iana" - }, - "audio/encaprtp": { - "source": "iana" - }, - "audio/evrc": { - "source": "iana" - }, - "audio/evrc-qcp": { - "source": "iana" - }, - "audio/evrc0": { - "source": "iana" - }, - "audio/evrc1": { - "source": "iana" - }, - "audio/evrcb": { - "source": "iana" - }, - "audio/evrcb0": { - "source": "iana" - }, - "audio/evrcb1": { - "source": "iana" - }, - "audio/evrcnw": { - "source": "iana" - }, - "audio/evrcnw0": { - "source": "iana" - }, - "audio/evrcnw1": { - "source": "iana" - }, - "audio/evrcwb": { - "source": "iana" - }, - "audio/evrcwb0": { - "source": "iana" - }, - "audio/evrcwb1": { - "source": "iana" - }, - "audio/evs": { - "source": "iana" - }, - "audio/flexfec": { - "source": "iana" - }, - "audio/fwdred": { - "source": "iana" - }, - "audio/g711-0": { - "source": "iana" - }, - "audio/g719": { - "source": "iana" - }, - "audio/g722": { - "source": "iana" - }, - "audio/g7221": { - "source": "iana" - }, - "audio/g723": { - "source": "iana" - }, - "audio/g726-16": { - "source": "iana" - }, - "audio/g726-24": { - "source": "iana" - }, - "audio/g726-32": { - "source": "iana" - }, - "audio/g726-40": { - "source": "iana" - }, - "audio/g728": { - "source": "iana" - }, - "audio/g729": { - "source": "iana" - }, - "audio/g7291": { - "source": "iana" - }, - "audio/g729d": { - "source": "iana" - }, - "audio/g729e": { - "source": "iana" - }, - "audio/gsm": { - "source": "iana" - }, - "audio/gsm-efr": { - "source": "iana" - }, - "audio/gsm-hr-08": { - "source": "iana" - }, - "audio/ilbc": { - "source": "iana" - }, - "audio/ip-mr_v2.5": { - "source": "iana" - }, - "audio/isac": { - "source": "apache" - }, - "audio/l16": { - "source": "iana" - }, - "audio/l20": { - "source": "iana" - }, - "audio/l24": { - "source": "iana", - "compressible": false - }, - "audio/l8": { - "source": "iana" - }, - "audio/lpc": { - "source": "iana" - }, - "audio/melp": { - "source": "iana" - }, - "audio/melp1200": { - "source": "iana" - }, - "audio/melp2400": { - "source": "iana" - }, - "audio/melp600": { - "source": "iana" - }, - "audio/mhas": { - "source": "iana" - }, - "audio/midi": { - "source": "apache", - "extensions": ["mid","midi","kar","rmi"] - }, - "audio/mobile-xmf": { - "source": "iana", - "extensions": ["mxmf"] - }, - "audio/mp3": { - "compressible": false, - "extensions": ["mp3"] - }, - "audio/mp4": { - "source": "iana", - "compressible": false, - "extensions": ["m4a","mp4a"] - }, - "audio/mp4a-latm": { - "source": "iana" - }, - "audio/mpa": { - "source": "iana" - }, - "audio/mpa-robust": { - "source": "iana" - }, - "audio/mpeg": { - "source": "iana", - "compressible": false, - "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] - }, - "audio/mpeg4-generic": { - "source": "iana" - }, - "audio/musepack": { - "source": "apache" - }, - "audio/ogg": { - "source": "iana", - "compressible": false, - "extensions": ["oga","ogg","spx"] - }, - "audio/opus": { - "source": "iana" - }, - "audio/parityfec": { - "source": "iana" - }, - "audio/pcma": { - "source": "iana" - }, - "audio/pcma-wb": { - "source": "iana" - }, - "audio/pcmu": { - "source": "iana" - }, - "audio/pcmu-wb": { - "source": "iana" - }, - "audio/prs.sid": { - "source": "iana" - }, - "audio/qcelp": { - "source": "iana" - }, - "audio/raptorfec": { - "source": "iana" - }, - "audio/red": { - "source": "iana" - }, - "audio/rtp-enc-aescm128": { - "source": "iana" - }, - "audio/rtp-midi": { - "source": "iana" - }, - "audio/rtploopback": { - "source": "iana" - }, - "audio/rtx": { - "source": "iana" - }, - "audio/s3m": { - "source": "apache", - "extensions": ["s3m"] - }, - "audio/silk": { - "source": "apache", - "extensions": ["sil"] - }, - "audio/smv": { - "source": "iana" - }, - "audio/smv-qcp": { - "source": "iana" - }, - "audio/smv0": { - "source": "iana" - }, - "audio/sp-midi": { - "source": "iana" - }, - "audio/speex": { - "source": "iana" - }, - "audio/t140c": { - "source": "iana" - }, - "audio/t38": { - "source": "iana" - }, - "audio/telephone-event": { - "source": "iana" - }, - "audio/tetra_acelp": { - "source": "iana" - }, - "audio/tetra_acelp_bb": { - "source": "iana" - }, - "audio/tone": { - "source": "iana" - }, - "audio/uemclip": { - "source": "iana" - }, - "audio/ulpfec": { - "source": "iana" - }, - "audio/usac": { - "source": "iana" - }, - "audio/vdvi": { - "source": "iana" - }, - "audio/vmr-wb": { - "source": "iana" - }, - "audio/vnd.3gpp.iufp": { - "source": "iana" - }, - "audio/vnd.4sb": { - "source": "iana" - }, - "audio/vnd.audiokoz": { - "source": "iana" - }, - "audio/vnd.celp": { - "source": "iana" - }, - "audio/vnd.cisco.nse": { - "source": "iana" - }, - "audio/vnd.cmles.radio-events": { - "source": "iana" - }, - "audio/vnd.cns.anp1": { - "source": "iana" - }, - "audio/vnd.cns.inf1": { - "source": "iana" - }, - "audio/vnd.dece.audio": { - "source": "iana", - "extensions": ["uva","uvva"] - }, - "audio/vnd.digital-winds": { - "source": "iana", - "extensions": ["eol"] - }, - "audio/vnd.dlna.adts": { - "source": "iana" - }, - "audio/vnd.dolby.heaac.1": { - "source": "iana" - }, - "audio/vnd.dolby.heaac.2": { - "source": "iana" - }, - "audio/vnd.dolby.mlp": { - "source": "iana" - }, - "audio/vnd.dolby.mps": { - "source": "iana" - }, - "audio/vnd.dolby.pl2": { - "source": "iana" - }, - "audio/vnd.dolby.pl2x": { - "source": "iana" - }, - "audio/vnd.dolby.pl2z": { - "source": "iana" - }, - "audio/vnd.dolby.pulse.1": { - "source": "iana" - }, - "audio/vnd.dra": { - "source": "iana", - "extensions": ["dra"] - }, - "audio/vnd.dts": { - "source": "iana", - "extensions": ["dts"] - }, - "audio/vnd.dts.hd": { - "source": "iana", - "extensions": ["dtshd"] - }, - "audio/vnd.dts.uhd": { - "source": "iana" - }, - "audio/vnd.dvb.file": { - "source": "iana" - }, - "audio/vnd.everad.plj": { - "source": "iana" - }, - "audio/vnd.hns.audio": { - "source": "iana" - }, - "audio/vnd.lucent.voice": { - "source": "iana", - "extensions": ["lvp"] - }, - "audio/vnd.ms-playready.media.pya": { - "source": "iana", - "extensions": ["pya"] - }, - "audio/vnd.nokia.mobile-xmf": { - "source": "iana" - }, - "audio/vnd.nortel.vbk": { - "source": "iana" - }, - "audio/vnd.nuera.ecelp4800": { - "source": "iana", - "extensions": ["ecelp4800"] - }, - "audio/vnd.nuera.ecelp7470": { - "source": "iana", - "extensions": ["ecelp7470"] - }, - "audio/vnd.nuera.ecelp9600": { - "source": "iana", - "extensions": ["ecelp9600"] - }, - "audio/vnd.octel.sbc": { - "source": "iana" - }, - "audio/vnd.presonus.multitrack": { - "source": "iana" - }, - "audio/vnd.qcelp": { - "source": "iana" - }, - "audio/vnd.rhetorex.32kadpcm": { - "source": "iana" - }, - "audio/vnd.rip": { - "source": "iana", - "extensions": ["rip"] - }, - "audio/vnd.rn-realaudio": { - "compressible": false - }, - "audio/vnd.sealedmedia.softseal.mpeg": { - "source": "iana" - }, - "audio/vnd.vmx.cvsd": { - "source": "iana" - }, - "audio/vnd.wave": { - "compressible": false - }, - "audio/vorbis": { - "source": "iana", - "compressible": false - }, - "audio/vorbis-config": { - "source": "iana" - }, - "audio/wav": { - "compressible": false, - "extensions": ["wav"] - }, - "audio/wave": { - "compressible": false, - "extensions": ["wav"] - }, - "audio/webm": { - "source": "apache", - "compressible": false, - "extensions": ["weba"] - }, - "audio/x-aac": { - "source": "apache", - "compressible": false, - "extensions": ["aac"] - }, - "audio/x-aiff": { - "source": "apache", - "extensions": ["aif","aiff","aifc"] - }, - "audio/x-caf": { - "source": "apache", - "compressible": false, - "extensions": ["caf"] - }, - "audio/x-flac": { - "source": "apache", - "extensions": ["flac"] - }, - "audio/x-m4a": { - "source": "nginx", - "extensions": ["m4a"] - }, - "audio/x-matroska": { - "source": "apache", - "extensions": ["mka"] - }, - "audio/x-mpegurl": { - "source": "apache", - "extensions": ["m3u"] - }, - "audio/x-ms-wax": { - "source": "apache", - "extensions": ["wax"] - }, - "audio/x-ms-wma": { - "source": "apache", - "extensions": ["wma"] - }, - "audio/x-pn-realaudio": { - "source": "apache", - "extensions": ["ram","ra"] - }, - "audio/x-pn-realaudio-plugin": { - "source": "apache", - "extensions": ["rmp"] - }, - "audio/x-realaudio": { - "source": "nginx", - "extensions": ["ra"] - }, - "audio/x-tta": { - "source": "apache" - }, - "audio/x-wav": { - "source": "apache", - "extensions": ["wav"] - }, - "audio/xm": { - "source": "apache", - "extensions": ["xm"] - }, - "chemical/x-cdx": { - "source": "apache", - "extensions": ["cdx"] - }, - "chemical/x-cif": { - "source": "apache", - "extensions": ["cif"] - }, - "chemical/x-cmdf": { - "source": "apache", - "extensions": ["cmdf"] - }, - "chemical/x-cml": { - "source": "apache", - "extensions": ["cml"] - }, - "chemical/x-csml": { - "source": "apache", - "extensions": ["csml"] - }, - "chemical/x-pdb": { - "source": "apache" - }, - "chemical/x-xyz": { - "source": "apache", - "extensions": ["xyz"] - }, - "font/collection": { - "source": "iana", - "extensions": ["ttc"] - }, - "font/otf": { - "source": "iana", - "compressible": true, - "extensions": ["otf"] - }, - "font/sfnt": { - "source": "iana" - }, - "font/ttf": { - "source": "iana", - "compressible": true, - "extensions": ["ttf"] - }, - "font/woff": { - "source": "iana", - "extensions": ["woff"] - }, - "font/woff2": { - "source": "iana", - "extensions": ["woff2"] - }, - "image/aces": { - "source": "iana", - "extensions": ["exr"] - }, - "image/apng": { - "compressible": false, - "extensions": ["apng"] - }, - "image/avci": { - "source": "iana" - }, - "image/avcs": { - "source": "iana" - }, - "image/bmp": { - "source": "iana", - "compressible": true, - "extensions": ["bmp"] - }, - "image/cgm": { - "source": "iana", - "extensions": ["cgm"] - }, - "image/dicom-rle": { - "source": "iana", - "extensions": ["drle"] - }, - "image/emf": { - "source": "iana", - "extensions": ["emf"] - }, - "image/fits": { - "source": "iana", - "extensions": ["fits"] - }, - "image/g3fax": { - "source": "iana", - "extensions": ["g3"] - }, - "image/gif": { - "source": "iana", - "compressible": false, - "extensions": ["gif"] - }, - "image/heic": { - "source": "iana", - "extensions": ["heic"] - }, - "image/heic-sequence": { - "source": "iana", - "extensions": ["heics"] - }, - "image/heif": { - "source": "iana", - "extensions": ["heif"] - }, - "image/heif-sequence": { - "source": "iana", - "extensions": ["heifs"] - }, - "image/hej2k": { - "source": "iana", - "extensions": ["hej2"] - }, - "image/hsj2": { - "source": "iana", - "extensions": ["hsj2"] - }, - "image/ief": { - "source": "iana", - "extensions": ["ief"] - }, - "image/jls": { - "source": "iana", - "extensions": ["jls"] - }, - "image/jp2": { - "source": "iana", - "compressible": false, - "extensions": ["jp2","jpg2"] - }, - "image/jpeg": { - "source": "iana", - "compressible": false, - "extensions": ["jpeg","jpg","jpe"] - }, - "image/jph": { - "source": "iana", - "extensions": ["jph"] - }, - "image/jphc": { - "source": "iana", - "extensions": ["jhc"] - }, - "image/jpm": { - "source": "iana", - "compressible": false, - "extensions": ["jpm"] - }, - "image/jpx": { - "source": "iana", - "compressible": false, - "extensions": ["jpx","jpf"] - }, - "image/jxr": { - "source": "iana", - "extensions": ["jxr"] - }, - "image/jxra": { - "source": "iana", - "extensions": ["jxra"] - }, - "image/jxrs": { - "source": "iana", - "extensions": ["jxrs"] - }, - "image/jxs": { - "source": "iana", - "extensions": ["jxs"] - }, - "image/jxsc": { - "source": "iana", - "extensions": ["jxsc"] - }, - "image/jxsi": { - "source": "iana", - "extensions": ["jxsi"] - }, - "image/jxss": { - "source": "iana", - "extensions": ["jxss"] - }, - "image/ktx": { - "source": "iana", - "extensions": ["ktx"] - }, - "image/naplps": { - "source": "iana" - }, - "image/pjpeg": { - "compressible": false - }, - "image/png": { - "source": "iana", - "compressible": false, - "extensions": ["png"] - }, - "image/prs.btif": { - "source": "iana", - "extensions": ["btif"] - }, - "image/prs.pti": { - "source": "iana", - "extensions": ["pti"] - }, - "image/pwg-raster": { - "source": "iana" - }, - "image/sgi": { - "source": "apache", - "extensions": ["sgi"] - }, - "image/svg+xml": { - "source": "iana", - "compressible": true, - "extensions": ["svg","svgz"] - }, - "image/t38": { - "source": "iana", - "extensions": ["t38"] - }, - "image/tiff": { - "source": "iana", - "compressible": false, - "extensions": ["tif","tiff"] - }, - "image/tiff-fx": { - "source": "iana", - "extensions": ["tfx"] - }, - "image/vnd.adobe.photoshop": { - "source": "iana", - "compressible": true, - "extensions": ["psd"] - }, - "image/vnd.airzip.accelerator.azv": { - "source": "iana", - "extensions": ["azv"] - }, - "image/vnd.cns.inf2": { - "source": "iana" - }, - "image/vnd.dece.graphic": { - "source": "iana", - "extensions": ["uvi","uvvi","uvg","uvvg"] - }, - "image/vnd.djvu": { - "source": "iana", - "extensions": ["djvu","djv"] - }, - "image/vnd.dvb.subtitle": { - "source": "iana", - "extensions": ["sub"] - }, - "image/vnd.dwg": { - "source": "iana", - "extensions": ["dwg"] - }, - "image/vnd.dxf": { - "source": "iana", - "extensions": ["dxf"] - }, - "image/vnd.fastbidsheet": { - "source": "iana", - "extensions": ["fbs"] - }, - "image/vnd.fpx": { - "source": "iana", - "extensions": ["fpx"] - }, - "image/vnd.fst": { - "source": "iana", - "extensions": ["fst"] - }, - "image/vnd.fujixerox.edmics-mmr": { - "source": "iana", - "extensions": ["mmr"] - }, - "image/vnd.fujixerox.edmics-rlc": { - "source": "iana", - "extensions": ["rlc"] - }, - "image/vnd.globalgraphics.pgb": { - "source": "iana" - }, - "image/vnd.microsoft.icon": { - "source": "iana", - "extensions": ["ico"] - }, - "image/vnd.mix": { - "source": "iana" - }, - "image/vnd.mozilla.apng": { - "source": "iana" - }, - "image/vnd.ms-dds": { - "extensions": ["dds"] - }, - "image/vnd.ms-modi": { - "source": "iana", - "extensions": ["mdi"] - }, - "image/vnd.ms-photo": { - "source": "apache", - "extensions": ["wdp"] - }, - "image/vnd.net-fpx": { - "source": "iana", - "extensions": ["npx"] - }, - "image/vnd.radiance": { - "source": "iana" - }, - "image/vnd.sealed.png": { - "source": "iana" - }, - "image/vnd.sealedmedia.softseal.gif": { - "source": "iana" - }, - "image/vnd.sealedmedia.softseal.jpg": { - "source": "iana" - }, - "image/vnd.svf": { - "source": "iana" - }, - "image/vnd.tencent.tap": { - "source": "iana", - "extensions": ["tap"] - }, - "image/vnd.valve.source.texture": { - "source": "iana", - "extensions": ["vtf"] - }, - "image/vnd.wap.wbmp": { - "source": "iana", - "extensions": ["wbmp"] - }, - "image/vnd.xiff": { - "source": "iana", - "extensions": ["xif"] - }, - "image/vnd.zbrush.pcx": { - "source": "iana", - "extensions": ["pcx"] - }, - "image/webp": { - "source": "apache", - "extensions": ["webp"] - }, - "image/wmf": { - "source": "iana", - "extensions": ["wmf"] - }, - "image/x-3ds": { - "source": "apache", - "extensions": ["3ds"] - }, - "image/x-cmu-raster": { - "source": "apache", - "extensions": ["ras"] - }, - "image/x-cmx": { - "source": "apache", - "extensions": ["cmx"] - }, - "image/x-freehand": { - "source": "apache", - "extensions": ["fh","fhc","fh4","fh5","fh7"] - }, - "image/x-icon": { - "source": "apache", - "compressible": true, - "extensions": ["ico"] - }, - "image/x-jng": { - "source": "nginx", - "extensions": ["jng"] - }, - "image/x-mrsid-image": { - "source": "apache", - "extensions": ["sid"] - }, - "image/x-ms-bmp": { - "source": "nginx", - "compressible": true, - "extensions": ["bmp"] - }, - "image/x-pcx": { - "source": "apache", - "extensions": ["pcx"] - }, - "image/x-pict": { - "source": "apache", - "extensions": ["pic","pct"] - }, - "image/x-portable-anymap": { - "source": "apache", - "extensions": ["pnm"] - }, - "image/x-portable-bitmap": { - "source": "apache", - "extensions": ["pbm"] - }, - "image/x-portable-graymap": { - "source": "apache", - "extensions": ["pgm"] - }, - "image/x-portable-pixmap": { - "source": "apache", - "extensions": ["ppm"] - }, - "image/x-rgb": { - "source": "apache", - "extensions": ["rgb"] - }, - "image/x-tga": { - "source": "apache", - "extensions": ["tga"] - }, - "image/x-xbitmap": { - "source": "apache", - "extensions": ["xbm"] - }, - "image/x-xcf": { - "compressible": false - }, - "image/x-xpixmap": { - "source": "apache", - "extensions": ["xpm"] - }, - "image/x-xwindowdump": { - "source": "apache", - "extensions": ["xwd"] - }, - "message/cpim": { - "source": "iana" - }, - "message/delivery-status": { - "source": "iana" - }, - "message/disposition-notification": { - "source": "iana", - "extensions": [ - "disposition-notification" - ] - }, - "message/external-body": { - "source": "iana" - }, - "message/feedback-report": { - "source": "iana" - }, - "message/global": { - "source": "iana", - "extensions": ["u8msg"] - }, - "message/global-delivery-status": { - "source": "iana", - "extensions": ["u8dsn"] - }, - "message/global-disposition-notification": { - "source": "iana", - "extensions": ["u8mdn"] - }, - "message/global-headers": { - "source": "iana", - "extensions": ["u8hdr"] - }, - "message/http": { - "source": "iana", - "compressible": false - }, - "message/imdn+xml": { - "source": "iana", - "compressible": true - }, - "message/news": { - "source": "iana" - }, - "message/partial": { - "source": "iana", - "compressible": false - }, - "message/rfc822": { - "source": "iana", - "compressible": true, - "extensions": ["eml","mime"] - }, - "message/s-http": { - "source": "iana" - }, - "message/sip": { - "source": "iana" - }, - "message/sipfrag": { - "source": "iana" - }, - "message/tracking-status": { - "source": "iana" - }, - "message/vnd.si.simp": { - "source": "iana" - }, - "message/vnd.wfa.wsc": { - "source": "iana", - "extensions": ["wsc"] - }, - "model/3mf": { - "source": "iana", - "extensions": ["3mf"] - }, - "model/gltf+json": { - "source": "iana", - "compressible": true, - "extensions": ["gltf"] - }, - "model/gltf-binary": { - "source": "iana", - "compressible": true, - "extensions": ["glb"] - }, - "model/iges": { - "source": "iana", - "compressible": false, - "extensions": ["igs","iges"] - }, - "model/mesh": { - "source": "iana", - "compressible": false, - "extensions": ["msh","mesh","silo"] - }, - "model/mtl": { - "source": "iana", - "extensions": ["mtl"] - }, - "model/obj": { - "source": "iana", - "extensions": ["obj"] - }, - "model/stl": { - "source": "iana", - "extensions": ["stl"] - }, - "model/vnd.collada+xml": { - "source": "iana", - "compressible": true, - "extensions": ["dae"] - }, - "model/vnd.dwf": { - "source": "iana", - "extensions": ["dwf"] - }, - "model/vnd.flatland.3dml": { - "source": "iana" - }, - "model/vnd.gdl": { - "source": "iana", - "extensions": ["gdl"] - }, - "model/vnd.gs-gdl": { - "source": "apache" - }, - "model/vnd.gs.gdl": { - "source": "iana" - }, - "model/vnd.gtw": { - "source": "iana", - "extensions": ["gtw"] - }, - "model/vnd.moml+xml": { - "source": "iana", - "compressible": true - }, - "model/vnd.mts": { - "source": "iana", - "extensions": ["mts"] - }, - "model/vnd.opengex": { - "source": "iana", - "extensions": ["ogex"] - }, - "model/vnd.parasolid.transmit.binary": { - "source": "iana", - "extensions": ["x_b"] - }, - "model/vnd.parasolid.transmit.text": { - "source": "iana", - "extensions": ["x_t"] - }, - "model/vnd.rosette.annotated-data-model": { - "source": "iana" - }, - "model/vnd.usdz+zip": { - "source": "iana", - "compressible": false, - "extensions": ["usdz"] - }, - "model/vnd.valve.source.compiled-map": { - "source": "iana", - "extensions": ["bsp"] - }, - "model/vnd.vtu": { - "source": "iana", - "extensions": ["vtu"] - }, - "model/vrml": { - "source": "iana", - "compressible": false, - "extensions": ["wrl","vrml"] - }, - "model/x3d+binary": { - "source": "apache", - "compressible": false, - "extensions": ["x3db","x3dbz"] - }, - "model/x3d+fastinfoset": { - "source": "iana", - "extensions": ["x3db"] - }, - "model/x3d+vrml": { - "source": "apache", - "compressible": false, - "extensions": ["x3dv","x3dvz"] - }, - "model/x3d+xml": { - "source": "iana", - "compressible": true, - "extensions": ["x3d","x3dz"] - }, - "model/x3d-vrml": { - "source": "iana", - "extensions": ["x3dv"] - }, - "multipart/alternative": { - "source": "iana", - "compressible": false - }, - "multipart/appledouble": { - "source": "iana" - }, - "multipart/byteranges": { - "source": "iana" - }, - "multipart/digest": { - "source": "iana" - }, - "multipart/encrypted": { - "source": "iana", - "compressible": false - }, - "multipart/form-data": { - "source": "iana", - "compressible": false - }, - "multipart/header-set": { - "source": "iana" - }, - "multipart/mixed": { - "source": "iana" - }, - "multipart/multilingual": { - "source": "iana" - }, - "multipart/parallel": { - "source": "iana" - }, - "multipart/related": { - "source": "iana", - "compressible": false - }, - "multipart/report": { - "source": "iana" - }, - "multipart/signed": { - "source": "iana", - "compressible": false - }, - "multipart/vnd.bint.med-plus": { - "source": "iana" - }, - "multipart/voice-message": { - "source": "iana" - }, - "multipart/x-mixed-replace": { - "source": "iana" - }, - "text/1d-interleaved-parityfec": { - "source": "iana" - }, - "text/cache-manifest": { - "source": "iana", - "compressible": true, - "extensions": ["appcache","manifest"] - }, - "text/calendar": { - "source": "iana", - "extensions": ["ics","ifb"] - }, - "text/calender": { - "compressible": true - }, - "text/cmd": { - "compressible": true - }, - "text/coffeescript": { - "extensions": ["coffee","litcoffee"] - }, - "text/css": { - "source": "iana", - "charset": "UTF-8", - "compressible": true, - "extensions": ["css"] - }, - "text/csv": { - "source": "iana", - "compressible": true, - "extensions": ["csv"] - }, - "text/csv-schema": { - "source": "iana" - }, - "text/directory": { - "source": "iana" - }, - "text/dns": { - "source": "iana" - }, - "text/ecmascript": { - "source": "iana" - }, - "text/encaprtp": { - "source": "iana" - }, - "text/enriched": { - "source": "iana" - }, - "text/flexfec": { - "source": "iana" - }, - "text/fwdred": { - "source": "iana" - }, - "text/grammar-ref-list": { - "source": "iana" - }, - "text/html": { - "source": "iana", - "compressible": true, - "extensions": ["html","htm","shtml"] - }, - "text/jade": { - "extensions": ["jade"] - }, - "text/javascript": { - "source": "iana", - "compressible": true - }, - "text/jcr-cnd": { - "source": "iana" - }, - "text/jsx": { - "compressible": true, - "extensions": ["jsx"] - }, - "text/less": { - "compressible": true, - "extensions": ["less"] - }, - "text/markdown": { - "source": "iana", - "compressible": true, - "extensions": ["markdown","md"] - }, - "text/mathml": { - "source": "nginx", - "extensions": ["mml"] - }, - "text/mdx": { - "compressible": true, - "extensions": ["mdx"] - }, - "text/mizar": { - "source": "iana" - }, - "text/n3": { - "source": "iana", - "charset": "UTF-8", - "compressible": true, - "extensions": ["n3"] - }, - "text/parameters": { - "source": "iana", - "charset": "UTF-8" - }, - "text/parityfec": { - "source": "iana" - }, - "text/plain": { - "source": "iana", - "compressible": true, - "extensions": ["txt","text","conf","def","list","log","in","ini"] - }, - "text/provenance-notation": { - "source": "iana", - "charset": "UTF-8" - }, - "text/prs.fallenstein.rst": { - "source": "iana" - }, - "text/prs.lines.tag": { - "source": "iana", - "extensions": ["dsc"] - }, - "text/prs.prop.logic": { - "source": "iana" - }, - "text/raptorfec": { - "source": "iana" - }, - "text/red": { - "source": "iana" - }, - "text/rfc822-headers": { - "source": "iana" - }, - "text/richtext": { - "source": "iana", - "compressible": true, - "extensions": ["rtx"] - }, - "text/rtf": { - "source": "iana", - "compressible": true, - "extensions": ["rtf"] - }, - "text/rtp-enc-aescm128": { - "source": "iana" - }, - "text/rtploopback": { - "source": "iana" - }, - "text/rtx": { - "source": "iana" - }, - "text/sgml": { - "source": "iana", - "extensions": ["sgml","sgm"] - }, - "text/shex": { - "extensions": ["shex"] - }, - "text/slim": { - "extensions": ["slim","slm"] - }, - "text/strings": { - "source": "iana" - }, - "text/stylus": { - "extensions": ["stylus","styl"] - }, - "text/t140": { - "source": "iana" - }, - "text/tab-separated-values": { - "source": "iana", - "compressible": true, - "extensions": ["tsv"] - }, - "text/troff": { - "source": "iana", - "extensions": ["t","tr","roff","man","me","ms"] - }, - "text/turtle": { - "source": "iana", - "charset": "UTF-8", - "extensions": ["ttl"] - }, - "text/ulpfec": { - "source": "iana" - }, - "text/uri-list": { - "source": "iana", - "compressible": true, - "extensions": ["uri","uris","urls"] - }, - "text/vcard": { - "source": "iana", - "compressible": true, - "extensions": ["vcard"] - }, - "text/vnd.a": { - "source": "iana" - }, - "text/vnd.abc": { - "source": "iana" - }, - "text/vnd.ascii-art": { - "source": "iana" - }, - "text/vnd.curl": { - "source": "iana", - "extensions": ["curl"] - }, - "text/vnd.curl.dcurl": { - "source": "apache", - "extensions": ["dcurl"] - }, - "text/vnd.curl.mcurl": { - "source": "apache", - "extensions": ["mcurl"] - }, - "text/vnd.curl.scurl": { - "source": "apache", - "extensions": ["scurl"] - }, - "text/vnd.debian.copyright": { - "source": "iana", - "charset": "UTF-8" - }, - "text/vnd.dmclientscript": { - "source": "iana" - }, - "text/vnd.dvb.subtitle": { - "source": "iana", - "extensions": ["sub"] - }, - "text/vnd.esmertec.theme-descriptor": { - "source": "iana", - "charset": "UTF-8" - }, - "text/vnd.ficlab.flt": { - "source": "iana" - }, - "text/vnd.fly": { - "source": "iana", - "extensions": ["fly"] - }, - "text/vnd.fmi.flexstor": { - "source": "iana", - "extensions": ["flx"] - }, - "text/vnd.gml": { - "source": "iana" - }, - "text/vnd.graphviz": { - "source": "iana", - "extensions": ["gv"] - }, - "text/vnd.hgl": { - "source": "iana" - }, - "text/vnd.in3d.3dml": { - "source": "iana", - "extensions": ["3dml"] - }, - "text/vnd.in3d.spot": { - "source": "iana", - "extensions": ["spot"] - }, - "text/vnd.iptc.newsml": { - "source": "iana" - }, - "text/vnd.iptc.nitf": { - "source": "iana" - }, - "text/vnd.latex-z": { - "source": "iana" - }, - "text/vnd.motorola.reflex": { - "source": "iana" - }, - "text/vnd.ms-mediapackage": { - "source": "iana" - }, - "text/vnd.net2phone.commcenter.command": { - "source": "iana" - }, - "text/vnd.radisys.msml-basic-layout": { - "source": "iana" - }, - "text/vnd.senx.warpscript": { - "source": "iana" - }, - "text/vnd.si.uricatalogue": { - "source": "iana" - }, - "text/vnd.sosi": { - "source": "iana" - }, - "text/vnd.sun.j2me.app-descriptor": { - "source": "iana", - "charset": "UTF-8", - "extensions": ["jad"] - }, - "text/vnd.trolltech.linguist": { - "source": "iana", - "charset": "UTF-8" - }, - "text/vnd.wap.si": { - "source": "iana" - }, - "text/vnd.wap.sl": { - "source": "iana" - }, - "text/vnd.wap.wml": { - "source": "iana", - "extensions": ["wml"] - }, - "text/vnd.wap.wmlscript": { - "source": "iana", - "extensions": ["wmls"] - }, - "text/vtt": { - "source": "iana", - "charset": "UTF-8", - "compressible": true, - "extensions": ["vtt"] - }, - "text/x-asm": { - "source": "apache", - "extensions": ["s","asm"] - }, - "text/x-c": { - "source": "apache", - "extensions": ["c","cc","cxx","cpp","h","hh","dic"] - }, - "text/x-component": { - "source": "nginx", - "extensions": ["htc"] - }, - "text/x-fortran": { - "source": "apache", - "extensions": ["f","for","f77","f90"] - }, - "text/x-gwt-rpc": { - "compressible": true - }, - "text/x-handlebars-template": { - "extensions": ["hbs"] - }, - "text/x-java-source": { - "source": "apache", - "extensions": ["java"] - }, - "text/x-jquery-tmpl": { - "compressible": true - }, - "text/x-lua": { - "extensions": ["lua"] - }, - "text/x-markdown": { - "compressible": true, - "extensions": ["mkd"] - }, - "text/x-nfo": { - "source": "apache", - "extensions": ["nfo"] - }, - "text/x-opml": { - "source": "apache", - "extensions": ["opml"] - }, - "text/x-org": { - "compressible": true, - "extensions": ["org"] - }, - "text/x-pascal": { - "source": "apache", - "extensions": ["p","pas"] - }, - "text/x-processing": { - "compressible": true, - "extensions": ["pde"] - }, - "text/x-sass": { - "extensions": ["sass"] - }, - "text/x-scss": { - "extensions": ["scss"] - }, - "text/x-setext": { - "source": "apache", - "extensions": ["etx"] - }, - "text/x-sfv": { - "source": "apache", - "extensions": ["sfv"] - }, - "text/x-suse-ymp": { - "compressible": true, - "extensions": ["ymp"] - }, - "text/x-uuencode": { - "source": "apache", - "extensions": ["uu"] - }, - "text/x-vcalendar": { - "source": "apache", - "extensions": ["vcs"] - }, - "text/x-vcard": { - "source": "apache", - "extensions": ["vcf"] - }, - "text/xml": { - "source": "iana", - "compressible": true, - "extensions": ["xml"] - }, - "text/xml-external-parsed-entity": { - "source": "iana" - }, - "text/yaml": { - "extensions": ["yaml","yml"] - }, - "video/1d-interleaved-parityfec": { - "source": "iana" - }, - "video/3gpp": { - "source": "iana", - "extensions": ["3gp","3gpp"] - }, - "video/3gpp-tt": { - "source": "iana" - }, - "video/3gpp2": { - "source": "iana", - "extensions": ["3g2"] - }, - "video/bmpeg": { - "source": "iana" - }, - "video/bt656": { - "source": "iana" - }, - "video/celb": { - "source": "iana" - }, - "video/dv": { - "source": "iana" - }, - "video/encaprtp": { - "source": "iana" - }, - "video/flexfec": { - "source": "iana" - }, - "video/h261": { - "source": "iana", - "extensions": ["h261"] - }, - "video/h263": { - "source": "iana", - "extensions": ["h263"] - }, - "video/h263-1998": { - "source": "iana" - }, - "video/h263-2000": { - "source": "iana" - }, - "video/h264": { - "source": "iana", - "extensions": ["h264"] - }, - "video/h264-rcdo": { - "source": "iana" - }, - "video/h264-svc": { - "source": "iana" - }, - "video/h265": { - "source": "iana" - }, - "video/iso.segment": { - "source": "iana" - }, - "video/jpeg": { - "source": "iana", - "extensions": ["jpgv"] - }, - "video/jpeg2000": { - "source": "iana" - }, - "video/jpm": { - "source": "apache", - "extensions": ["jpm","jpgm"] - }, - "video/mj2": { - "source": "iana", - "extensions": ["mj2","mjp2"] - }, - "video/mp1s": { - "source": "iana" - }, - "video/mp2p": { - "source": "iana" - }, - "video/mp2t": { - "source": "iana", - "extensions": ["ts"] - }, - "video/mp4": { - "source": "iana", - "compressible": false, - "extensions": ["mp4","mp4v","mpg4"] - }, - "video/mp4v-es": { - "source": "iana" - }, - "video/mpeg": { - "source": "iana", - "compressible": false, - "extensions": ["mpeg","mpg","mpe","m1v","m2v"] - }, - "video/mpeg4-generic": { - "source": "iana" - }, - "video/mpv": { - "source": "iana" - }, - "video/nv": { - "source": "iana" - }, - "video/ogg": { - "source": "iana", - "compressible": false, - "extensions": ["ogv"] - }, - "video/parityfec": { - "source": "iana" - }, - "video/pointer": { - "source": "iana" - }, - "video/quicktime": { - "source": "iana", - "compressible": false, - "extensions": ["qt","mov"] - }, - "video/raptorfec": { - "source": "iana" - }, - "video/raw": { - "source": "iana" - }, - "video/rtp-enc-aescm128": { - "source": "iana" - }, - "video/rtploopback": { - "source": "iana" - }, - "video/rtx": { - "source": "iana" - }, - "video/smpte291": { - "source": "iana" - }, - "video/smpte292m": { - "source": "iana" - }, - "video/ulpfec": { - "source": "iana" - }, - "video/vc1": { - "source": "iana" - }, - "video/vc2": { - "source": "iana" - }, - "video/vnd.cctv": { - "source": "iana" - }, - "video/vnd.dece.hd": { - "source": "iana", - "extensions": ["uvh","uvvh"] - }, - "video/vnd.dece.mobile": { - "source": "iana", - "extensions": ["uvm","uvvm"] - }, - "video/vnd.dece.mp4": { - "source": "iana" - }, - "video/vnd.dece.pd": { - "source": "iana", - "extensions": ["uvp","uvvp"] - }, - "video/vnd.dece.sd": { - "source": "iana", - "extensions": ["uvs","uvvs"] - }, - "video/vnd.dece.video": { - "source": "iana", - "extensions": ["uvv","uvvv"] - }, - "video/vnd.directv.mpeg": { - "source": "iana" - }, - "video/vnd.directv.mpeg-tts": { - "source": "iana" - }, - "video/vnd.dlna.mpeg-tts": { - "source": "iana" - }, - "video/vnd.dvb.file": { - "source": "iana", - "extensions": ["dvb"] - }, - "video/vnd.fvt": { - "source": "iana", - "extensions": ["fvt"] - }, - "video/vnd.hns.video": { - "source": "iana" - }, - "video/vnd.iptvforum.1dparityfec-1010": { - "source": "iana" - }, - "video/vnd.iptvforum.1dparityfec-2005": { - "source": "iana" - }, - "video/vnd.iptvforum.2dparityfec-1010": { - "source": "iana" - }, - "video/vnd.iptvforum.2dparityfec-2005": { - "source": "iana" - }, - "video/vnd.iptvforum.ttsavc": { - "source": "iana" - }, - "video/vnd.iptvforum.ttsmpeg2": { - "source": "iana" - }, - "video/vnd.motorola.video": { - "source": "iana" - }, - "video/vnd.motorola.videop": { - "source": "iana" - }, - "video/vnd.mpegurl": { - "source": "iana", - "extensions": ["mxu","m4u"] - }, - "video/vnd.ms-playready.media.pyv": { - "source": "iana", - "extensions": ["pyv"] - }, - "video/vnd.nokia.interleaved-multimedia": { - "source": "iana" - }, - "video/vnd.nokia.mp4vr": { - "source": "iana" - }, - "video/vnd.nokia.videovoip": { - "source": "iana" - }, - "video/vnd.objectvideo": { - "source": "iana" - }, - "video/vnd.radgamettools.bink": { - "source": "iana" - }, - "video/vnd.radgamettools.smacker": { - "source": "iana" - }, - "video/vnd.sealed.mpeg1": { - "source": "iana" - }, - "video/vnd.sealed.mpeg4": { - "source": "iana" - }, - "video/vnd.sealed.swf": { - "source": "iana" - }, - "video/vnd.sealedmedia.softseal.mov": { - "source": "iana" - }, - "video/vnd.uvvu.mp4": { - "source": "iana", - "extensions": ["uvu","uvvu"] - }, - "video/vnd.vivo": { - "source": "iana", - "extensions": ["viv"] - }, - "video/vnd.youtube.yt": { - "source": "iana" - }, - "video/vp8": { - "source": "iana" - }, - "video/webm": { - "source": "apache", - "compressible": false, - "extensions": ["webm"] - }, - "video/x-f4v": { - "source": "apache", - "extensions": ["f4v"] - }, - "video/x-fli": { - "source": "apache", - "extensions": ["fli"] - }, - "video/x-flv": { - "source": "apache", - "compressible": false, - "extensions": ["flv"] - }, - "video/x-m4v": { - "source": "apache", - "extensions": ["m4v"] - }, - "video/x-matroska": { - "source": "apache", - "compressible": false, - "extensions": ["mkv","mk3d","mks"] - }, - "video/x-mng": { - "source": "apache", - "extensions": ["mng"] - }, - "video/x-ms-asf": { - "source": "apache", - "extensions": ["asf","asx"] - }, - "video/x-ms-vob": { - "source": "apache", - "extensions": ["vob"] - }, - "video/x-ms-wm": { - "source": "apache", - "extensions": ["wm"] - }, - "video/x-ms-wmv": { - "source": "apache", - "compressible": false, - "extensions": ["wmv"] - }, - "video/x-ms-wmx": { - "source": "apache", - "extensions": ["wmx"] - }, - "video/x-ms-wvx": { - "source": "apache", - "extensions": ["wvx"] - }, - "video/x-msvideo": { - "source": "apache", - "extensions": ["avi"] - }, - "video/x-sgi-movie": { - "source": "apache", - "extensions": ["movie"] - }, - "video/x-smv": { - "source": "apache", - "extensions": ["smv"] - }, - "x-conference/x-cooltalk": { - "source": "apache", - "extensions": ["ice"] - }, - "x-shader/x-fragment": { - "compressible": true - }, - "x-shader/x-vertex": { - "compressible": true - } -} diff --git a/node_modules/mime-db/index.js b/node_modules/mime-db/index.js deleted file mode 100644 index 551031f..0000000 --- a/node_modules/mime-db/index.js +++ /dev/null @@ -1,11 +0,0 @@ -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ - -/** - * Module exports. - */ - -module.exports = require('./db.json') diff --git a/node_modules/mime-db/package.json b/node_modules/mime-db/package.json deleted file mode 100644 index 1e425e5..0000000 --- a/node_modules/mime-db/package.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "_from": "mime-db@1.44.0", - "_id": "mime-db@1.44.0", - "_inBundle": false, - "_integrity": "sha512-/NOTfLrsPBVeH7YtFPgsVWveuL+4SjjYxaQ1xtM1KMFj7HdxlBlxeyNLzhyJVx7r4rZGJAZ/6lkKCitSc/Nmpg==", - "_location": "/mime-db", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "mime-db@1.44.0", - "name": "mime-db", - "escapedName": "mime-db", - "rawSpec": "1.44.0", - "saveSpec": null, - "fetchSpec": "1.44.0" - }, - "_requiredBy": [ - "/mime-types" - ], - "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.44.0.tgz", - "_shasum": "fa11c5eb0aca1334b4233cb4d52f10c5a6272f92", - "_spec": "mime-db@1.44.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mime-types", - "bugs": { - "url": "https://github.com/jshttp/mime-db/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - }, - { - "name": "Robert Kieffer", - "email": "robert@broofa.com", - "url": "http://github.com/broofa" - } - ], - "deprecated": false, - "description": "Media Type Database", - "devDependencies": { - "bluebird": "3.7.2", - "co": "4.6.0", - "cogent": "1.0.1", - "csv-parse": "4.8.9", - "eslint": "6.8.0", - "eslint-config-standard": "14.1.1", - "eslint-plugin-import": "2.20.2", - "eslint-plugin-markdown": "1.0.2", - "eslint-plugin-node": "11.1.0", - "eslint-plugin-promise": "4.2.1", - "eslint-plugin-standard": "4.0.1", - "gnode": "0.1.2", - "mocha": "7.1.1", - "nyc": "15.0.1", - "raw-body": "2.4.1", - "stream-to-array": "2.3.0" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "HISTORY.md", - "LICENSE", - "README.md", - "db.json", - "index.js" - ], - "homepage": "https://github.com/jshttp/mime-db#readme", - "keywords": [ - "mime", - "db", - "type", - "types", - "database", - "charset", - "charsets" - ], - "license": "MIT", - "name": "mime-db", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/mime-db.git" - }, - "scripts": { - "build": "node scripts/build", - "fetch": "node scripts/fetch-apache && gnode scripts/fetch-iana && node scripts/fetch-nginx", - "lint": "eslint --plugin markdown --ext js,md .", - "test": "mocha --reporter spec --bail --check-leaks test/", - "test-cov": "nyc --reporter=html --reporter=text npm test", - "test-travis": "nyc --reporter=text npm test", - "update": "npm run fetch && npm run build", - "version": "node scripts/version-history.js && git add HISTORY.md" - }, - "version": "1.44.0" -} diff --git a/node_modules/mime-types/HISTORY.md b/node_modules/mime-types/HISTORY.md deleted file mode 100644 index e93149a..0000000 --- a/node_modules/mime-types/HISTORY.md +++ /dev/null @@ -1,333 +0,0 @@ -2.1.27 / 2020-04-23 -=================== - - * deps: mime-db@1.44.0 - - Add charsets from IANA - - Add extension `.cjs` to `application/node` - - Add new upstream MIME types - -2.1.26 / 2020-01-05 -=================== - - * deps: mime-db@1.43.0 - - Add `application/x-keepass2` with extension `.kdbx` - - Add extension `.mxmf` to `audio/mobile-xmf` - - Add extensions from IANA for `application/*+xml` types - - Add new upstream MIME types - -2.1.25 / 2019-11-12 -=================== - - * deps: mime-db@1.42.0 - - Add new upstream MIME types - - Add `application/toml` with extension `.toml` - - Add `image/vnd.ms-dds` with extension `.dds` - -2.1.24 / 2019-04-20 -=================== - - * deps: mime-db@1.40.0 - - Add extensions from IANA for `model/*` types - - Add `text/mdx` with extension `.mdx` - -2.1.23 / 2019-04-17 -=================== - - * deps: mime-db@~1.39.0 - - Add extensions `.siv` and `.sieve` to `application/sieve` - - Add new upstream MIME types - -2.1.22 / 2019-02-14 -=================== - - * deps: mime-db@~1.38.0 - - Add extension `.nq` to `application/n-quads` - - Add extension `.nt` to `application/n-triples` - - Add new upstream MIME types - - Mark `text/less` as compressible - -2.1.21 / 2018-10-19 -=================== - - * deps: mime-db@~1.37.0 - - Add extensions to HEIC image types - - Add new upstream MIME types - -2.1.20 / 2018-08-26 -=================== - - * deps: mime-db@~1.36.0 - - Add Apple file extensions from IANA - - Add extensions from IANA for `image/*` types - - Add new upstream MIME types - -2.1.19 / 2018-07-17 -=================== - - * deps: mime-db@~1.35.0 - - Add extension `.csl` to `application/vnd.citationstyles.style+xml` - - Add extension `.es` to `application/ecmascript` - - Add extension `.owl` to `application/rdf+xml` - - Add new upstream MIME types - - Add UTF-8 as default charset for `text/turtle` - -2.1.18 / 2018-02-16 -=================== - - * deps: mime-db@~1.33.0 - - Add `application/raml+yaml` with extension `.raml` - - Add `application/wasm` with extension `.wasm` - - Add `text/shex` with extension `.shex` - - Add extensions for JPEG-2000 images - - Add extensions from IANA for `message/*` types - - Add new upstream MIME types - - Update font MIME types - - Update `text/hjson` to registered `application/hjson` - -2.1.17 / 2017-09-01 -=================== - - * deps: mime-db@~1.30.0 - - Add `application/vnd.ms-outlook` - - Add `application/x-arj` - - Add extension `.mjs` to `application/javascript` - - Add glTF types and extensions - - Add new upstream MIME types - - Add `text/x-org` - - Add VirtualBox MIME types - - Fix `source` records for `video/*` types that are IANA - - Update `font/opentype` to registered `font/otf` - -2.1.16 / 2017-07-24 -=================== - - * deps: mime-db@~1.29.0 - - Add `application/fido.trusted-apps+json` - - Add extension `.wadl` to `application/vnd.sun.wadl+xml` - - Add extension `.gz` to `application/gzip` - - Add new upstream MIME types - - Update extensions `.md` and `.markdown` to be `text/markdown` - -2.1.15 / 2017-03-23 -=================== - - * deps: mime-db@~1.27.0 - - Add new mime types - - Add `image/apng` - -2.1.14 / 2017-01-14 -=================== - - * deps: mime-db@~1.26.0 - - Add new mime types - -2.1.13 / 2016-11-18 -=================== - - * deps: mime-db@~1.25.0 - - Add new mime types - -2.1.12 / 2016-09-18 -=================== - - * deps: mime-db@~1.24.0 - - Add new mime types - - Add `audio/mp3` - -2.1.11 / 2016-05-01 -=================== - - * deps: mime-db@~1.23.0 - - Add new mime types - -2.1.10 / 2016-02-15 -=================== - - * deps: mime-db@~1.22.0 - - Add new mime types - - Fix extension of `application/dash+xml` - - Update primary extension for `audio/mp4` - -2.1.9 / 2016-01-06 -================== - - * deps: mime-db@~1.21.0 - - Add new mime types - -2.1.8 / 2015-11-30 -================== - - * deps: mime-db@~1.20.0 - - Add new mime types - -2.1.7 / 2015-09-20 -================== - - * deps: mime-db@~1.19.0 - - Add new mime types - -2.1.6 / 2015-09-03 -================== - - * deps: mime-db@~1.18.0 - - Add new mime types - -2.1.5 / 2015-08-20 -================== - - * deps: mime-db@~1.17.0 - - Add new mime types - -2.1.4 / 2015-07-30 -================== - - * deps: mime-db@~1.16.0 - - Add new mime types - -2.1.3 / 2015-07-13 -================== - - * deps: mime-db@~1.15.0 - - Add new mime types - -2.1.2 / 2015-06-25 -================== - - * deps: mime-db@~1.14.0 - - Add new mime types - -2.1.1 / 2015-06-08 -================== - - * perf: fix deopt during mapping - -2.1.0 / 2015-06-07 -================== - - * Fix incorrectly treating extension-less file name as extension - - i.e. `'path/to/json'` will no longer return `application/json` - * Fix `.charset(type)` to accept parameters - * Fix `.charset(type)` to match case-insensitive - * Improve generation of extension to MIME mapping - * Refactor internals for readability and no argument reassignment - * Prefer `application/*` MIME types from the same source - * Prefer any type over `application/octet-stream` - * deps: mime-db@~1.13.0 - - Add nginx as a source - - Add new mime types - -2.0.14 / 2015-06-06 -=================== - - * deps: mime-db@~1.12.0 - - Add new mime types - -2.0.13 / 2015-05-31 -=================== - - * deps: mime-db@~1.11.0 - - Add new mime types - -2.0.12 / 2015-05-19 -=================== - - * deps: mime-db@~1.10.0 - - Add new mime types - -2.0.11 / 2015-05-05 -=================== - - * deps: mime-db@~1.9.1 - - Add new mime types - -2.0.10 / 2015-03-13 -=================== - - * deps: mime-db@~1.8.0 - - Add new mime types - -2.0.9 / 2015-02-09 -================== - - * deps: mime-db@~1.7.0 - - Add new mime types - - Community extensions ownership transferred from `node-mime` - -2.0.8 / 2015-01-29 -================== - - * deps: mime-db@~1.6.0 - - Add new mime types - -2.0.7 / 2014-12-30 -================== - - * deps: mime-db@~1.5.0 - - Add new mime types - - Fix various invalid MIME type entries - -2.0.6 / 2014-12-30 -================== - - * deps: mime-db@~1.4.0 - - Add new mime types - - Fix various invalid MIME type entries - - Remove example template MIME types - -2.0.5 / 2014-12-29 -================== - - * deps: mime-db@~1.3.1 - - Fix missing extensions - -2.0.4 / 2014-12-10 -================== - - * deps: mime-db@~1.3.0 - - Add new mime types - -2.0.3 / 2014-11-09 -================== - - * deps: mime-db@~1.2.0 - - Add new mime types - -2.0.2 / 2014-09-28 -================== - - * deps: mime-db@~1.1.0 - - Add new mime types - - Add additional compressible - - Update charsets - -2.0.1 / 2014-09-07 -================== - - * Support Node.js 0.6 - -2.0.0 / 2014-09-02 -================== - - * Use `mime-db` - * Remove `.define()` - -1.0.2 / 2014-08-04 -================== - - * Set charset=utf-8 for `text/javascript` - -1.0.1 / 2014-06-24 -================== - - * Add `text/jsx` type - -1.0.0 / 2014-05-12 -================== - - * Return `false` for unknown types - * Set charset=utf-8 for `application/json` - -0.1.0 / 2014-05-02 -================== - - * Initial release diff --git a/node_modules/mime-types/LICENSE b/node_modules/mime-types/LICENSE deleted file mode 100644 index 0616607..0000000 --- a/node_modules/mime-types/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -(The MIT License) - -Copyright (c) 2014 Jonathan Ong -Copyright (c) 2015 Douglas Christopher Wilson - -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/mime-types/README.md b/node_modules/mime-types/README.md deleted file mode 100644 index 3863339..0000000 --- a/node_modules/mime-types/README.md +++ /dev/null @@ -1,123 +0,0 @@ -# mime-types - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][npm-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -The ultimate javascript content-type utility. - -Similar to [the `mime@1.x` module](https://www.npmjs.com/package/mime), except: - -- __No fallbacks.__ Instead of naively returning the first available type, - `mime-types` simply returns `false`, so do - `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. -- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. -- No `.define()` functionality -- Bug fixes for `.lookup(path)` - -Otherwise, the API is compatible with `mime` 1.x. - -## Install - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install mime-types -``` - -## Adding Types - -All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), -so open a PR there if you'd like to add mime types. - -## API - - - -```js -var mime = require('mime-types') -``` - -All functions return `false` if input is invalid or not found. - -### mime.lookup(path) - -Lookup the content-type associated with a file. - - - -```js -mime.lookup('json') // 'application/json' -mime.lookup('.md') // 'text/markdown' -mime.lookup('file.html') // 'text/html' -mime.lookup('folder/file.js') // 'application/javascript' -mime.lookup('folder/.htaccess') // false - -mime.lookup('cats') // false -``` - -### mime.contentType(type) - -Create a full content-type header given a content-type or extension. -When given an extension, `mime.lookup` is used to get the matching -content-type, otherwise the given content-type is used. Then if the -content-type does not already have a `charset` parameter, `mime.charset` -is used to get the default charset and add to the returned content-type. - - - -```js -mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' -mime.contentType('file.json') // 'application/json; charset=utf-8' -mime.contentType('text/html') // 'text/html; charset=utf-8' -mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' - -// from a full path -mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' -``` - -### mime.extension(type) - -Get the default extension for a content-type. - - - -```js -mime.extension('application/octet-stream') // 'bin' -``` - -### mime.charset(type) - -Lookup the implied default charset of a content-type. - - - -```js -mime.charset('text/markdown') // 'UTF-8' -``` - -### var type = mime.types[extension] - -A map of content-types by extension. - -### [extensions...] = mime.extensions[type] - -A map of extensions by content-type. - -## License - -[MIT](LICENSE) - -[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master -[coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master -[node-version-image]: https://badgen.net/npm/node/mime-types -[node-version-url]: https://nodejs.org/en/download -[npm-downloads-image]: https://badgen.net/npm/dm/mime-types -[npm-url]: https://npmjs.org/package/mime-types -[npm-version-image]: https://badgen.net/npm/v/mime-types -[travis-image]: https://badgen.net/travis/jshttp/mime-types/master -[travis-url]: https://travis-ci.org/jshttp/mime-types diff --git a/node_modules/mime-types/index.js b/node_modules/mime-types/index.js deleted file mode 100644 index b9f34d5..0000000 --- a/node_modules/mime-types/index.js +++ /dev/null @@ -1,188 +0,0 @@ -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var db = require('mime-db') -var extname = require('path').extname - -/** - * Module variables. - * @private - */ - -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ -var TEXT_TYPE_REGEXP = /^text\//i - -/** - * Module exports. - * @public - */ - -exports.charset = charset -exports.charsets = { lookup: charset } -exports.contentType = contentType -exports.extension = extension -exports.extensions = Object.create(null) -exports.lookup = lookup -exports.types = Object.create(null) - -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types) - -/** - * Get the default charset for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ - -function charset (type) { - if (!type || typeof type !== 'string') { - return false - } - - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - var mime = match && db[match[1].toLowerCase()] - - if (mime && mime.charset) { - return mime.charset - } - - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' - } - - return false -} - -/** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} - */ - -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false - } - - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str - - if (!mime) { - return false - } - - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() - } - - return mime -} - -/** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ - -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } - - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] - - if (!exts || !exts.length) { - return false - } - - return exts[0] -} - -/** - * Lookup the MIME type for a file path/extension. - * - * @param {string} path - * @return {boolean|string} - */ - -function lookup (path) { - if (!path || typeof path !== 'string') { - return false - } - - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) - - if (!extension) { - return false - } - - return exports.types[extension] || false -} - -/** - * Populate the extensions and types maps. - * @private - */ - -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] - - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions - - if (!exts || !exts.length) { - return - } - - // mime -> extensions - extensions[type] = exts - - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] - - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) - - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue - } - } - - // set the extension -> mime - types[extension] = type - } - }) -} diff --git a/node_modules/mime-types/package.json b/node_modules/mime-types/package.json deleted file mode 100644 index 474d194..0000000 --- a/node_modules/mime-types/package.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "_from": "mime-types@~2.1.24", - "_id": "mime-types@2.1.27", - "_inBundle": false, - "_integrity": "sha512-JIhqnCasI9yD+SsmkquHBxTSEuZdQX5BuQnS2Vc7puQQQ+8yiP5AY5uWhpdv4YL4VM5c6iliiYWPgJ/nJQLp7w==", - "_location": "/mime-types", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "mime-types@~2.1.24", - "name": "mime-types", - "escapedName": "mime-types", - "rawSpec": "~2.1.24", - "saveSpec": null, - "fetchSpec": "~2.1.24" - }, - "_requiredBy": [ - "/accepts", - "/type-is" - ], - "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.27.tgz", - "_shasum": "47949f98e279ea53119f5722e0f34e529bec009f", - "_spec": "mime-types@~2.1.24", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/accepts", - "bugs": { - "url": "https://github.com/jshttp/mime-types/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "Jeremiah Senkpiel", - "email": "fishrock123@rocketmail.com", - "url": "https://searchbeam.jit.su" - }, - { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - } - ], - "dependencies": { - "mime-db": "1.44.0" - }, - "deprecated": false, - "description": "The ultimate javascript content-type utility.", - "devDependencies": { - "eslint": "6.8.0", - "eslint-config-standard": "14.1.1", - "eslint-plugin-import": "2.20.2", - "eslint-plugin-markdown": "1.0.2", - "eslint-plugin-node": "11.1.0", - "eslint-plugin-promise": "4.2.1", - "eslint-plugin-standard": "4.0.1", - "mocha": "7.1.1", - "nyc": "15.0.1" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "HISTORY.md", - "LICENSE", - "index.js" - ], - "homepage": "https://github.com/jshttp/mime-types#readme", - "keywords": [ - "mime", - "types" - ], - "license": "MIT", - "name": "mime-types", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/mime-types.git" - }, - "scripts": { - "lint": "eslint --plugin markdown --ext js,md .", - "test": "mocha --reporter spec test/test.js", - "test-cov": "nyc --reporter=html --reporter=text npm test", - "test-travis": "nyc --reporter=text npm test" - }, - "version": "2.1.27" -} diff --git a/node_modules/mime/.npmignore b/node_modules/mime/.npmignore deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mime/CHANGELOG.md b/node_modules/mime/CHANGELOG.md deleted file mode 100644 index f127535..0000000 --- a/node_modules/mime/CHANGELOG.md +++ /dev/null @@ -1,164 +0,0 @@ -# Changelog - -## v1.6.0 (24/11/2017) -*No changelog for this release.* - ---- - -## v2.0.4 (24/11/2017) -- [**closed**] Switch to mime-score module for resolving extension contention issues. [#182](https://github.com/broofa/node-mime/issues/182) -- [**closed**] Update mime-db to 1.31.0 in v1.x branch [#181](https://github.com/broofa/node-mime/issues/181) - ---- - -## v1.5.0 (22/11/2017) -- [**closed**] need ES5 version ready in npm package [#179](https://github.com/broofa/node-mime/issues/179) -- [**closed**] mime-db no trace of iWork - pages / numbers / etc. [#178](https://github.com/broofa/node-mime/issues/178) -- [**closed**] How it works in brownser ? [#176](https://github.com/broofa/node-mime/issues/176) -- [**closed**] Missing `./Mime` [#175](https://github.com/broofa/node-mime/issues/175) -- [**closed**] Vulnerable Regular Expression [#167](https://github.com/broofa/node-mime/issues/167) - ---- - -## v2.0.3 (25/09/2017) -*No changelog for this release.* - ---- - -## v1.4.1 (25/09/2017) -- [**closed**] Issue when bundling with webpack [#172](https://github.com/broofa/node-mime/issues/172) - ---- - -## v2.0.2 (15/09/2017) -- [**V2**] fs.readFileSync is not a function [#165](https://github.com/broofa/node-mime/issues/165) -- [**closed**] The extension for video/quicktime should map to .mov, not .qt [#164](https://github.com/broofa/node-mime/issues/164) -- [**V2**] [v2 Feedback request] Mime class API [#163](https://github.com/broofa/node-mime/issues/163) -- [**V2**] [v2 Feedback request] Resolving conflicts over extensions [#162](https://github.com/broofa/node-mime/issues/162) -- [**V2**] Allow callers to load module with official, full, or no defined types. [#161](https://github.com/broofa/node-mime/issues/161) -- [**V2**] Use "facets" to resolve extension conflicts [#160](https://github.com/broofa/node-mime/issues/160) -- [**V2**] Remove fs and path dependencies [#152](https://github.com/broofa/node-mime/issues/152) -- [**V2**] Default content-type should not be application/octet-stream [#139](https://github.com/broofa/node-mime/issues/139) -- [**V2**] reset mime-types [#124](https://github.com/broofa/node-mime/issues/124) -- [**V2**] Extensionless paths should return null or false [#113](https://github.com/broofa/node-mime/issues/113) - ---- - -## v2.0.1 (14/09/2017) -- [**closed**] Changelog for v2.0 does not mention breaking changes [#171](https://github.com/broofa/node-mime/issues/171) -- [**closed**] MIME breaking with 'class' declaration as it is without 'use strict mode' [#170](https://github.com/broofa/node-mime/issues/170) - ---- - -## v2.0.0 (12/09/2017) -- [**closed**] woff and woff2 [#168](https://github.com/broofa/node-mime/issues/168) - ---- - -## v1.4.0 (28/08/2017) -- [**closed**] support for ac3 voc files [#159](https://github.com/broofa/node-mime/issues/159) -- [**closed**] Help understanding change from application/xml to text/xml [#158](https://github.com/broofa/node-mime/issues/158) -- [**closed**] no longer able to override mimetype [#157](https://github.com/broofa/node-mime/issues/157) -- [**closed**] application/vnd.adobe.photoshop [#147](https://github.com/broofa/node-mime/issues/147) -- [**closed**] Directories should appear as something other than application/octet-stream [#135](https://github.com/broofa/node-mime/issues/135) -- [**closed**] requested features [#131](https://github.com/broofa/node-mime/issues/131) -- [**closed**] Make types.json loading optional? [#129](https://github.com/broofa/node-mime/issues/129) -- [**closed**] Cannot find module './types.json' [#120](https://github.com/broofa/node-mime/issues/120) -- [**V2**] .wav files show up as "audio/x-wav" instead of "audio/x-wave" [#118](https://github.com/broofa/node-mime/issues/118) -- [**closed**] Don't be a pain in the ass for node community [#108](https://github.com/broofa/node-mime/issues/108) -- [**closed**] don't make default_type global [#78](https://github.com/broofa/node-mime/issues/78) -- [**closed**] mime.extension() fails if the content-type is parameterized [#74](https://github.com/broofa/node-mime/issues/74) - ---- - -## v1.3.6 (11/05/2017) -- [**closed**] .md should be text/markdown as of March 2016 [#154](https://github.com/broofa/node-mime/issues/154) -- [**closed**] Error while installing mime [#153](https://github.com/broofa/node-mime/issues/153) -- [**closed**] application/manifest+json [#149](https://github.com/broofa/node-mime/issues/149) -- [**closed**] Dynamic adaptive streaming over HTTP (DASH) file extension typo [#141](https://github.com/broofa/node-mime/issues/141) -- [**closed**] charsets image/png undefined [#140](https://github.com/broofa/node-mime/issues/140) -- [**closed**] Mime-db dependency out of date [#130](https://github.com/broofa/node-mime/issues/130) -- [**closed**] how to support plist? [#126](https://github.com/broofa/node-mime/issues/126) -- [**closed**] how does .types file format look like? [#123](https://github.com/broofa/node-mime/issues/123) -- [**closed**] Feature: support for expanding MIME patterns [#121](https://github.com/broofa/node-mime/issues/121) -- [**closed**] DEBUG_MIME doesn't work [#117](https://github.com/broofa/node-mime/issues/117) - ---- - -## v1.3.4 (06/02/2015) -*No changelog for this release.* - ---- - -## v1.3.3 (06/02/2015) -*No changelog for this release.* - ---- - -## v1.3.1 (05/02/2015) -- [**closed**] Consider adding support for Handlebars .hbs file ending [#111](https://github.com/broofa/node-mime/issues/111) -- [**closed**] Consider adding support for hjson. [#110](https://github.com/broofa/node-mime/issues/110) -- [**closed**] Add mime type for Opus audio files [#94](https://github.com/broofa/node-mime/issues/94) -- [**closed**] Consider making the `Requesting New Types` information more visible [#77](https://github.com/broofa/node-mime/issues/77) - ---- - -## v1.3.0 (05/02/2015) -- [**closed**] Add common name? [#114](https://github.com/broofa/node-mime/issues/114) -- [**closed**] application/x-yaml [#104](https://github.com/broofa/node-mime/issues/104) -- [**closed**] Add mime type for WOFF file format 2.0 [#102](https://github.com/broofa/node-mime/issues/102) -- [**closed**] application/x-msi for .msi [#99](https://github.com/broofa/node-mime/issues/99) -- [**closed**] Add mimetype for gettext translation files [#98](https://github.com/broofa/node-mime/issues/98) -- [**closed**] collaborators [#88](https://github.com/broofa/node-mime/issues/88) -- [**closed**] getting errot in installation of mime module...any1 can help? [#87](https://github.com/broofa/node-mime/issues/87) -- [**closed**] should application/json's charset be utf8? [#86](https://github.com/broofa/node-mime/issues/86) -- [**closed**] Add "license" and "licenses" to package.json [#81](https://github.com/broofa/node-mime/issues/81) -- [**closed**] lookup with extension-less file on Windows returns wrong type [#68](https://github.com/broofa/node-mime/issues/68) - ---- - -## v1.2.11 (15/08/2013) -- [**closed**] Update mime.types [#65](https://github.com/broofa/node-mime/issues/65) -- [**closed**] Publish a new version [#63](https://github.com/broofa/node-mime/issues/63) -- [**closed**] README should state upfront that "application/octet-stream" is default for unknown extension [#55](https://github.com/broofa/node-mime/issues/55) -- [**closed**] Suggested improvement to the charset API [#52](https://github.com/broofa/node-mime/issues/52) - ---- - -## v1.2.10 (25/07/2013) -- [**closed**] Mime type for woff files should be application/font-woff and not application/x-font-woff [#62](https://github.com/broofa/node-mime/issues/62) -- [**closed**] node.types in conflict with mime.types [#51](https://github.com/broofa/node-mime/issues/51) - ---- - -## v1.2.9 (17/01/2013) -- [**closed**] Please update "mime" NPM [#49](https://github.com/broofa/node-mime/issues/49) -- [**closed**] Please add semicolon [#46](https://github.com/broofa/node-mime/issues/46) -- [**closed**] parse full mime types [#43](https://github.com/broofa/node-mime/issues/43) - ---- - -## v1.2.8 (10/01/2013) -- [**closed**] /js directory mime is application/javascript. Is it correct? [#47](https://github.com/broofa/node-mime/issues/47) -- [**closed**] Add mime types for lua code. [#45](https://github.com/broofa/node-mime/issues/45) - ---- - -## v1.2.7 (19/10/2012) -- [**closed**] cannot install 1.2.7 via npm [#41](https://github.com/broofa/node-mime/issues/41) -- [**closed**] Transfer ownership to @broofa [#36](https://github.com/broofa/node-mime/issues/36) -- [**closed**] it's wrong to set charset to UTF-8 for text [#30](https://github.com/broofa/node-mime/issues/30) -- [**closed**] Allow multiple instances of MIME types container [#27](https://github.com/broofa/node-mime/issues/27) - ---- - -## v1.2.5 (16/02/2012) -- [**closed**] When looking up a types, check hasOwnProperty [#23](https://github.com/broofa/node-mime/issues/23) -- [**closed**] Bump version to 1.2.2 [#18](https://github.com/broofa/node-mime/issues/18) -- [**closed**] No license [#16](https://github.com/broofa/node-mime/issues/16) -- [**closed**] Some types missing that are used by html5/css3 [#13](https://github.com/broofa/node-mime/issues/13) -- [**closed**] npm install fails for 1.2.1 [#12](https://github.com/broofa/node-mime/issues/12) -- [**closed**] image/pjpeg + image/x-png [#10](https://github.com/broofa/node-mime/issues/10) -- [**closed**] symlink [#8](https://github.com/broofa/node-mime/issues/8) -- [**closed**] gzip [#2](https://github.com/broofa/node-mime/issues/2) -- [**closed**] ALL CAPS filenames return incorrect mime type [#1](https://github.com/broofa/node-mime/issues/1) diff --git a/node_modules/mime/LICENSE b/node_modules/mime/LICENSE deleted file mode 100644 index d3f46f7..0000000 --- a/node_modules/mime/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2010 Benjamin Thomas, Robert Kieffer - -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/mime/README.md b/node_modules/mime/README.md deleted file mode 100644 index 506fbe5..0000000 --- a/node_modules/mime/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# mime - -Comprehensive MIME type mapping API based on mime-db module. - -## Install - -Install with [npm](http://github.com/isaacs/npm): - - npm install mime - -## Contributing / Testing - - npm run test - -## Command Line - - mime [path_string] - -E.g. - - > mime scripts/jquery.js - application/javascript - -## API - Queries - -### mime.lookup(path) -Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. - -```js -var mime = require('mime'); - -mime.lookup('/path/to/file.txt'); // => 'text/plain' -mime.lookup('file.txt'); // => 'text/plain' -mime.lookup('.TXT'); // => 'text/plain' -mime.lookup('htm'); // => 'text/html' -``` - -### mime.default_type -Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) - -### mime.extension(type) -Get the default extension for `type` - -```js -mime.extension('text/html'); // => 'html' -mime.extension('application/octet-stream'); // => 'bin' -``` - -### mime.charsets.lookup() - -Map mime-type to charset - -```js -mime.charsets.lookup('text/plain'); // => 'UTF-8' -``` - -(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) - -## API - Defining Custom Types - -Custom type mappings can be added on a per-project basis via the following APIs. - -### mime.define() - -Add custom mime/extension mappings - -```js -mime.define({ - 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], - 'application/x-my-type': ['x-mt', 'x-mtt'], - // etc ... -}); - -mime.lookup('x-sft'); // => 'text/x-some-format' -``` - -The first entry in the extensions array is returned by `mime.extension()`. E.g. - -```js -mime.extension('text/x-some-format'); // => 'x-sf' -``` - -### mime.load(filepath) - -Load mappings from an Apache ".types" format file - -```js -mime.load('./my_project.types'); -``` -The .types file format is simple - See the `types` dir for examples. diff --git a/node_modules/mime/cli.js b/node_modules/mime/cli.js deleted file mode 100755 index 20b1ffe..0000000 --- a/node_modules/mime/cli.js +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env node - -var mime = require('./mime.js'); -var file = process.argv[2]; -var type = mime.lookup(file); - -process.stdout.write(type + '\n'); - diff --git a/node_modules/mime/mime.js b/node_modules/mime/mime.js deleted file mode 100644 index d7efbde..0000000 --- a/node_modules/mime/mime.js +++ /dev/null @@ -1,108 +0,0 @@ -var path = require('path'); -var fs = require('fs'); - -function Mime() { - // Map of extension -> mime type - this.types = Object.create(null); - - // Map of mime type -> extension - this.extensions = Object.create(null); -} - -/** - * Define mimetype -> extension mappings. Each key is a mime-type that maps - * to an array of extensions associated with the type. The first extension is - * used as the default extension for the type. - * - * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); - * - * @param map (Object) type definitions - */ -Mime.prototype.define = function (map) { - for (var type in map) { - var exts = map[type]; - for (var i = 0; i < exts.length; i++) { - if (process.env.DEBUG_MIME && this.types[exts[i]]) { - console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + - this.types[exts[i]] + ' to ' + type); - } - - this.types[exts[i]] = type; - } - - // Default extension is the first one we encounter - if (!this.extensions[type]) { - this.extensions[type] = exts[0]; - } - } -}; - -/** - * Load an Apache2-style ".types" file - * - * This may be called multiple times (it's expected). Where files declare - * overlapping types/extensions, the last file wins. - * - * @param file (String) path of file to load. - */ -Mime.prototype.load = function(file) { - this._loading = file; - // Read file and split into lines - var map = {}, - content = fs.readFileSync(file, 'ascii'), - lines = content.split(/[\r\n]+/); - - lines.forEach(function(line) { - // Clean up whitespace/comments, and split into fields - var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); - map[fields.shift()] = fields; - }); - - this.define(map); - - this._loading = null; -}; - -/** - * Lookup a mime type based on extension - */ -Mime.prototype.lookup = function(path, fallback) { - var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase(); - - return this.types[ext] || fallback || this.default_type; -}; - -/** - * Return file extension associated with a mime type - */ -Mime.prototype.extension = function(mimeType) { - var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); - return this.extensions[type]; -}; - -// Default instance -var mime = new Mime(); - -// Define built-in types -mime.define(require('./types.json')); - -// Default type -mime.default_type = mime.lookup('bin'); - -// -// Additional API specific to the default instance -// - -mime.Mime = Mime; - -/** - * Lookup a charset based on mime type. - */ -mime.charsets = { - lookup: function(mimeType, fallback) { - // Assume text types are utf8 - return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback; - } -}; - -module.exports = mime; diff --git a/node_modules/mime/package.json b/node_modules/mime/package.json deleted file mode 100644 index 15cd10b..0000000 --- a/node_modules/mime/package.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "_from": "mime@1.6.0", - "_id": "mime@1.6.0", - "_inBundle": false, - "_integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", - "_location": "/mime", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "mime@1.6.0", - "name": "mime", - "escapedName": "mime", - "rawSpec": "1.6.0", - "saveSpec": null, - "fetchSpec": "1.6.0" - }, - "_requiredBy": [ - "/send" - ], - "_resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "_shasum": "32cd9e5c64553bd58d19a568af452acff04981b1", - "_spec": "mime@1.6.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/send", - "author": { - "name": "Robert Kieffer", - "email": "robert@broofa.com", - "url": "http://github.com/broofa" - }, - "bin": { - "mime": "cli.js" - }, - "bugs": { - "url": "https://github.com/broofa/node-mime/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Benjamin Thomas", - "email": "benjamin@benjaminthomas.org", - "url": "http://github.com/bentomas" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "A comprehensive library for mime-type mapping", - "devDependencies": { - "github-release-notes": "0.13.1", - "mime-db": "1.31.0", - "mime-score": "1.1.0" - }, - "engines": { - "node": ">=4" - }, - "homepage": "https://github.com/broofa/node-mime#readme", - "keywords": [ - "util", - "mime" - ], - "license": "MIT", - "main": "mime.js", - "name": "mime", - "repository": { - "url": "git+https://github.com/broofa/node-mime.git", - "type": "git" - }, - "scripts": { - "changelog": "gren changelog --tags=all --generate --override", - "prepare": "node src/build.js", - "test": "node src/test.js" - }, - "version": "1.6.0" -} diff --git a/node_modules/mime/src/build.js b/node_modules/mime/src/build.js deleted file mode 100755 index 4928e48..0000000 --- a/node_modules/mime/src/build.js +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env node - -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const mimeScore = require('mime-score'); - -let db = require('mime-db'); -let chalk = require('chalk'); - -const STANDARD_FACET_SCORE = 900; - -const byExtension = {}; - -// Clear out any conflict extensions in mime-db -for (let type in db) { - let entry = db[type]; - entry.type = type; - - if (!entry.extensions) continue; - - entry.extensions.forEach(ext => { - if (ext in byExtension) { - const e0 = entry; - const e1 = byExtension[ext]; - e0.pri = mimeScore(e0.type, e0.source); - e1.pri = mimeScore(e1.type, e1.source); - - let drop = e0.pri < e1.pri ? e0 : e1; - let keep = e0.pri >= e1.pri ? e0 : e1; - drop.extensions = drop.extensions.filter(e => e !== ext); - - console.log(`${ext}: Keeping ${chalk.green(keep.type)} (${keep.pri}), dropping ${chalk.red(drop.type)} (${drop.pri})`); - } - byExtension[ext] = entry; - }); -} - -function writeTypesFile(types, path) { - fs.writeFileSync(path, JSON.stringify(types)); -} - -// Segregate into standard and non-standard types based on facet per -// https://tools.ietf.org/html/rfc6838#section-3.1 -const types = {}; - -Object.keys(db).sort().forEach(k => { - const entry = db[k]; - types[entry.type] = entry.extensions; -}); - -writeTypesFile(types, path.join(__dirname, '..', 'types.json')); diff --git a/node_modules/mime/src/test.js b/node_modules/mime/src/test.js deleted file mode 100644 index 42958a2..0000000 --- a/node_modules/mime/src/test.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Usage: node test.js - */ - -var mime = require('../mime'); -var assert = require('assert'); -var path = require('path'); - -// -// Test mime lookups -// - -assert.equal('text/plain', mime.lookup('text.txt')); // normal file -assert.equal('text/plain', mime.lookup('TEXT.TXT')); // uppercase -assert.equal('text/plain', mime.lookup('dir/text.txt')); // dir + file -assert.equal('text/plain', mime.lookup('.text.txt')); // hidden file -assert.equal('text/plain', mime.lookup('.txt')); // nameless -assert.equal('text/plain', mime.lookup('txt')); // extension-only -assert.equal('text/plain', mime.lookup('/txt')); // extension-less () -assert.equal('text/plain', mime.lookup('\\txt')); // Windows, extension-less -assert.equal('application/octet-stream', mime.lookup('text.nope')); // unrecognized -assert.equal('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default - -// -// Test extensions -// - -assert.equal('txt', mime.extension(mime.types.text)); -assert.equal('html', mime.extension(mime.types.htm)); -assert.equal('bin', mime.extension('application/octet-stream')); -assert.equal('bin', mime.extension('application/octet-stream ')); -assert.equal('html', mime.extension(' text/html; charset=UTF-8')); -assert.equal('html', mime.extension('text/html; charset=UTF-8 ')); -assert.equal('html', mime.extension('text/html; charset=UTF-8')); -assert.equal('html', mime.extension('text/html ; charset=UTF-8')); -assert.equal('html', mime.extension('text/html;charset=UTF-8')); -assert.equal('html', mime.extension('text/Html;charset=UTF-8')); -assert.equal(undefined, mime.extension('unrecognized')); - -// -// Test node.types lookups -// - -assert.equal('font/woff', mime.lookup('file.woff')); -assert.equal('application/octet-stream', mime.lookup('file.buffer')); -// TODO: Uncomment once #157 is resolved -// assert.equal('audio/mp4', mime.lookup('file.m4a')); -assert.equal('font/otf', mime.lookup('file.otf')); - -// -// Test charsets -// - -assert.equal('UTF-8', mime.charsets.lookup('text/plain')); -assert.equal('UTF-8', mime.charsets.lookup(mime.types.js)); -assert.equal('UTF-8', mime.charsets.lookup(mime.types.json)); -assert.equal(undefined, mime.charsets.lookup(mime.types.bin)); -assert.equal('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); - -console.log('\nAll tests passed'); diff --git a/node_modules/mime/types.json b/node_modules/mime/types.json deleted file mode 100644 index bec78ab..0000000 --- a/node_modules/mime/types.json +++ /dev/null @@ -1 +0,0 @@ -{"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomsvc+xml":["atomsvc"],"application/bdoc":["bdoc"],"application/ccxml+xml":["ccxml"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/font-tdpfr":["pfr"],"application/font-woff":[],"application/font-woff2":[],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/prs.cww":["cww"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":[],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":[],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":[],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":[],"application/x-msdownload":["com","bat"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["wmf","emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":[],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"application/xaml+xml":["xaml"],"application/xcap-diff+xml":["xdf"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":[],"audio/adpcm":["adp"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mp3":[],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/wav":["wav"],"audio/wave":[],"audio/webm":["weba"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":[],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":[],"audio/x-wav":[],"audio/xm":["xm"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/apng":["apng"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/g3fax":["g3"],"image/gif":["gif"],"image/ief":["ief"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/ktx":["ktx"],"image/png":["png"],"image/prs.btif":["btif"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/tiff":["tiff","tif"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":[],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/webp":["webp"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":[],"image/x-pcx":["pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/rfc822":["eml","mime"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.vtu":["vtu"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["x3db","x3dbz"],"model/x3d+vrml":["x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/hjson":["hjson"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/prs.lines.tag":["dsc"],"text/richtext":["rtx"],"text/rtf":[],"text/sgml":["sgml","sgm"],"text/slim":["slim","slm"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/vtt":["vtt"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":[],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"text/xml":[],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/jpeg":["jpgv"],"video/jpm":["jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/webm":["webm"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]} \ No newline at end of file diff --git a/node_modules/mimic-response/index.d.ts b/node_modules/mimic-response/index.d.ts deleted file mode 100644 index 8ff98e2..0000000 --- a/node_modules/mimic-response/index.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import {IncomingMessage} from 'http'; - -/** -Mimic a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) - -Makes `toStream` include the properties from `fromStream`. - -@param fromStream - The stream to copy the properties from. -@param toStream - The stream to copy the properties to. -@return The same object as `toStream`. -*/ -declare function mimicResponse( - fromStream: IncomingMessage, - toStream: T, -): IncomingMessage & T; - -export = mimicResponse; diff --git a/node_modules/mimic-response/index.js b/node_modules/mimic-response/index.js deleted file mode 100644 index edd0faf..0000000 --- a/node_modules/mimic-response/index.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -// We define these manually to ensure they're always copied -// even if they would move up the prototype chain -// https://nodejs.org/api/http.html#http_class_http_incomingmessage -const knownProperties = [ - 'aborted', - 'complete', - 'destroy', - 'headers', - 'httpVersion', - 'httpVersionMinor', - 'httpVersionMajor', - 'method', - 'rawHeaders', - 'rawTrailers', - 'setTimeout', - 'socket', - 'statusCode', - 'statusMessage', - 'trailers', - 'url' -]; - -module.exports = (fromStream, toStream) => { - const fromProperties = new Set(Object.keys(fromStream).concat(knownProperties)); - - for (const property of fromProperties) { - // Don't overwrite existing properties. - if (property in toStream) { - continue; - } - - toStream[property] = typeof fromStream[property] === 'function' ? fromStream[property].bind(fromStream) : fromStream[property]; - } - - return toStream; -}; diff --git a/node_modules/mimic-response/license b/node_modules/mimic-response/license deleted file mode 100644 index fa7ceba..0000000 --- a/node_modules/mimic-response/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (https://sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mimic-response/package.json b/node_modules/mimic-response/package.json deleted file mode 100644 index f3e2eec..0000000 --- a/node_modules/mimic-response/package.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "_from": "mimic-response@^2.0.0", - "_id": "mimic-response@2.1.0", - "_inBundle": false, - "_integrity": "sha512-wXqjST+SLt7R009ySCglWBCFpjUygmCIfD790/kVbiGmUgfYGuB14PiTd5DwVxSV4NcYHjzMkoj5LjQZwTQLEA==", - "_location": "/mimic-response", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "mimic-response@^2.0.0", - "name": "mimic-response", - "escapedName": "mimic-response", - "rawSpec": "^2.0.0", - "saveSpec": null, - "fetchSpec": "^2.0.0" - }, - "_requiredBy": [ - "/decompress-response" - ], - "_resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-2.1.0.tgz", - "_shasum": "d13763d35f613d09ec37ebb30bac0469c0ee8f43", - "_spec": "mimic-response@^2.0.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/decompress-response", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "https://sindresorhus.com" - }, - "bugs": { - "url": "https://github.com/sindresorhus/mimic-response/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Mimic a Node.js HTTP response stream", - "devDependencies": { - "@sindresorhus/tsconfig": "^0.3.0", - "@types/node": "^12.0.0", - "ava": "^1.1.0", - "create-test-server": "^2.4.0", - "pify": "^4.0.1", - "tsd": "^0.7.3", - "xo": "^0.24.0" - }, - "engines": { - "node": ">=8" - }, - "files": [ - "index.d.ts", - "index.js" - ], - "funding": "https://github.com/sponsors/sindresorhus", - "homepage": "https://github.com/sindresorhus/mimic-response#readme", - "keywords": [ - "mimic", - "response", - "stream", - "http", - "https", - "request", - "get", - "core" - ], - "license": "MIT", - "name": "mimic-response", - "repository": { - "type": "git", - "url": "git+https://github.com/sindresorhus/mimic-response.git" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "version": "2.1.0" -} diff --git a/node_modules/mimic-response/readme.md b/node_modules/mimic-response/readme.md deleted file mode 100644 index b7d1ec9..0000000 --- a/node_modules/mimic-response/readme.md +++ /dev/null @@ -1,57 +0,0 @@ -# mimic-response [![Build Status](https://travis-ci.org/sindresorhus/mimic-response.svg?branch=master)](https://travis-ci.org/sindresorhus/mimic-response) - -> Mimic a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) - -## Install - -``` -$ npm install mimic-response -``` - -## Usage - -```js -const stream = require('stream'); -const mimicResponse = require('mimic-response'); - -const responseStream = getHttpResponseStream(); -const myStream = new stream.PassThrough(); - -mimicResponse(responseStream, myStream); - -console.log(myStream.statusCode); -//=> 200 -``` - -## API - -### mimicResponse(from, to) - -#### from - -Type: `Stream` - -[Node.js HTTP response stream.](https://nodejs.org/api/http.html#http_class_http_incomingmessage) - -#### to - -Type: `Stream` - -Any stream. - -## Related - -- [mimic-fn](https://github.com/sindresorhus/mimic-fn) - Make a function mimic another one -- [clone-response](https://github.com/lukechilds/clone-response) - Clone a Node.js response stream - ---- - -
- - Get professional support for this package with a Tidelift subscription - -
- - Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. -
-
diff --git a/node_modules/minimist/.travis.yml b/node_modules/minimist/.travis.yml deleted file mode 100644 index 74c57bf..0000000 --- a/node_modules/minimist/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" - - "0.12" - - "iojs" -before_install: - - npm install -g npm@~1.4.6 diff --git a/node_modules/minimist/LICENSE b/node_modules/minimist/LICENSE deleted file mode 100644 index ee27ba4..0000000 --- a/node_modules/minimist/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -This software is released under the MIT license: - -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/minimist/example/parse.js b/node_modules/minimist/example/parse.js deleted file mode 100644 index f7c8d49..0000000 --- a/node_modules/minimist/example/parse.js +++ /dev/null @@ -1,2 +0,0 @@ -var argv = require('../')(process.argv.slice(2)); -console.log(argv); diff --git a/node_modules/minimist/index.js b/node_modules/minimist/index.js deleted file mode 100644 index d2afe5e..0000000 --- a/node_modules/minimist/index.js +++ /dev/null @@ -1,245 +0,0 @@ -module.exports = function (args, opts) { - if (!opts) opts = {}; - - var flags = { bools : {}, strings : {}, unknownFn: null }; - - if (typeof opts['unknown'] === 'function') { - flags.unknownFn = opts['unknown']; - } - - if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { - flags.allBools = true; - } else { - [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { - flags.bools[key] = true; - }); - } - - var aliases = {}; - Object.keys(opts.alias || {}).forEach(function (key) { - aliases[key] = [].concat(opts.alias[key]); - aliases[key].forEach(function (x) { - aliases[x] = [key].concat(aliases[key].filter(function (y) { - return x !== y; - })); - }); - }); - - [].concat(opts.string).filter(Boolean).forEach(function (key) { - flags.strings[key] = true; - if (aliases[key]) { - flags.strings[aliases[key]] = true; - } - }); - - var defaults = opts['default'] || {}; - - var argv = { _ : [] }; - Object.keys(flags.bools).forEach(function (key) { - setArg(key, defaults[key] === undefined ? false : defaults[key]); - }); - - var notFlags = []; - - if (args.indexOf('--') !== -1) { - notFlags = args.slice(args.indexOf('--')+1); - args = args.slice(0, args.indexOf('--')); - } - - function argDefined(key, arg) { - return (flags.allBools && /^--[^=]+$/.test(arg)) || - flags.strings[key] || flags.bools[key] || aliases[key]; - } - - function setArg (key, val, arg) { - if (arg && flags.unknownFn && !argDefined(key, arg)) { - if (flags.unknownFn(arg) === false) return; - } - - var value = !flags.strings[key] && isNumber(val) - ? Number(val) : val - ; - setKey(argv, key.split('.'), value); - - (aliases[key] || []).forEach(function (x) { - setKey(argv, x.split('.'), value); - }); - } - - function setKey (obj, keys, value) { - var o = obj; - for (var i = 0; i < keys.length-1; i++) { - var key = keys[i]; - if (key === '__proto__') return; - if (o[key] === undefined) o[key] = {}; - if (o[key] === Object.prototype || o[key] === Number.prototype - || o[key] === String.prototype) o[key] = {}; - if (o[key] === Array.prototype) o[key] = []; - o = o[key]; - } - - var key = keys[keys.length - 1]; - if (key === '__proto__') return; - if (o === Object.prototype || o === Number.prototype - || o === String.prototype) o = {}; - if (o === Array.prototype) o = []; - if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { - o[key] = value; - } - else if (Array.isArray(o[key])) { - o[key].push(value); - } - else { - o[key] = [ o[key], value ]; - } - } - - function aliasIsBoolean(key) { - return aliases[key].some(function (x) { - return flags.bools[x]; - }); - } - - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - - if (/^--.+=/.test(arg)) { - // Using [\s\S] instead of . because js doesn't support the - // 'dotall' regex modifier. See: - // http://stackoverflow.com/a/1068308/13216 - var m = arg.match(/^--([^=]+)=([\s\S]*)$/); - var key = m[1]; - var value = m[2]; - if (flags.bools[key]) { - value = value !== 'false'; - } - setArg(key, value, arg); - } - else if (/^--no-.+/.test(arg)) { - var key = arg.match(/^--no-(.+)/)[1]; - setArg(key, false, arg); - } - else if (/^--.+/.test(arg)) { - var key = arg.match(/^--(.+)/)[1]; - var next = args[i + 1]; - if (next !== undefined && !/^-/.test(next) - && !flags.bools[key] - && !flags.allBools - && (aliases[key] ? !aliasIsBoolean(key) : true)) { - setArg(key, next, arg); - i++; - } - else if (/^(true|false)$/.test(next)) { - setArg(key, next === 'true', arg); - i++; - } - else { - setArg(key, flags.strings[key] ? '' : true, arg); - } - } - else if (/^-[^-]+/.test(arg)) { - var letters = arg.slice(1,-1).split(''); - - var broken = false; - for (var j = 0; j < letters.length; j++) { - var next = arg.slice(j+2); - - if (next === '-') { - setArg(letters[j], next, arg) - continue; - } - - if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { - setArg(letters[j], next.split('=')[1], arg); - broken = true; - break; - } - - if (/[A-Za-z]/.test(letters[j]) - && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { - setArg(letters[j], next, arg); - broken = true; - break; - } - - if (letters[j+1] && letters[j+1].match(/\W/)) { - setArg(letters[j], arg.slice(j+2), arg); - broken = true; - break; - } - else { - setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); - } - } - - var key = arg.slice(-1)[0]; - if (!broken && key !== '-') { - if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) - && !flags.bools[key] - && (aliases[key] ? !aliasIsBoolean(key) : true)) { - setArg(key, args[i+1], arg); - i++; - } - else if (args[i+1] && /^(true|false)$/.test(args[i+1])) { - setArg(key, args[i+1] === 'true', arg); - i++; - } - else { - setArg(key, flags.strings[key] ? '' : true, arg); - } - } - } - else { - if (!flags.unknownFn || flags.unknownFn(arg) !== false) { - argv._.push( - flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) - ); - } - if (opts.stopEarly) { - argv._.push.apply(argv._, args.slice(i + 1)); - break; - } - } - } - - Object.keys(defaults).forEach(function (key) { - if (!hasKey(argv, key.split('.'))) { - setKey(argv, key.split('.'), defaults[key]); - - (aliases[key] || []).forEach(function (x) { - setKey(argv, x.split('.'), defaults[key]); - }); - } - }); - - if (opts['--']) { - argv['--'] = new Array(); - notFlags.forEach(function(key) { - argv['--'].push(key); - }); - } - else { - notFlags.forEach(function(key) { - argv._.push(key); - }); - } - - return argv; -}; - -function hasKey (obj, keys) { - var o = obj; - keys.slice(0,-1).forEach(function (key) { - o = (o[key] || {}); - }); - - var key = keys[keys.length - 1]; - return key in o; -} - -function isNumber (x) { - if (typeof x === 'number') return true; - if (/^0x[0-9a-f]+$/i.test(x)) return true; - return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); -} - diff --git a/node_modules/minimist/package.json b/node_modules/minimist/package.json deleted file mode 100644 index e2bef72..0000000 --- a/node_modules/minimist/package.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "_from": "minimist@^1.2.0", - "_id": "minimist@1.2.5", - "_inBundle": false, - "_integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", - "_location": "/minimist", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "minimist@^1.2.0", - "name": "minimist", - "escapedName": "minimist", - "rawSpec": "^1.2.0", - "saveSpec": null, - "fetchSpec": "^1.2.0" - }, - "_requiredBy": [ - "/mkdirp", - "/prebuild-install", - "/rc" - ], - "_resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", - "_shasum": "67d66014b66a6a8aaa0c083c5fd58df4e4e97602", - "_spec": "minimist@^1.2.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/prebuild-install", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "bugs": { - "url": "https://github.com/substack/minimist/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "parse argument options", - "devDependencies": { - "covert": "^1.0.0", - "tap": "~0.4.0", - "tape": "^3.5.0" - }, - "homepage": "https://github.com/substack/minimist", - "keywords": [ - "argv", - "getopt", - "parser", - "optimist" - ], - "license": "MIT", - "main": "index.js", - "name": "minimist", - "repository": { - "type": "git", - "url": "git://github.com/substack/minimist.git" - }, - "scripts": { - "coverage": "covert test/*.js", - "test": "tap test/*.js" - }, - "testling": { - "files": "test/*.js", - "browsers": [ - "ie/6..latest", - "ff/5", - "firefox/latest", - "chrome/10", - "chrome/latest", - "safari/5.1", - "safari/latest", - "opera/12" - ] - }, - "version": "1.2.5" -} diff --git a/node_modules/minimist/readme.markdown b/node_modules/minimist/readme.markdown deleted file mode 100644 index 5fd97ab..0000000 --- a/node_modules/minimist/readme.markdown +++ /dev/null @@ -1,95 +0,0 @@ -# minimist - -parse argument options - -This module is the guts of optimist's argument parser without all the -fanciful decoration. - -# example - -``` js -var argv = require('minimist')(process.argv.slice(2)); -console.log(argv); -``` - -``` -$ node example/parse.js -a beep -b boop -{ _: [], a: 'beep', b: 'boop' } -``` - -``` -$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz -{ _: [ 'foo', 'bar', 'baz' ], - x: 3, - y: 4, - n: 5, - a: true, - b: true, - c: true, - beep: 'boop' } -``` - -# security - -Previous versions had a prototype pollution bug that could cause privilege -escalation in some circumstances when handling untrusted user input. - -Please use version 1.2.3 or later: https://snyk.io/vuln/SNYK-JS-MINIMIST-559764 - -# methods - -``` js -var parseArgs = require('minimist') -``` - -## var argv = parseArgs(args, opts={}) - -Return an argument object `argv` populated with the array arguments from `args`. - -`argv._` contains all the arguments that didn't have an option associated with -them. - -Numeric-looking arguments will be returned as numbers unless `opts.string` or -`opts.boolean` is set for that argument name. - -Any arguments after `'--'` will not be parsed and will end up in `argv._`. - -options can be: - -* `opts.string` - a string or array of strings argument names to always treat as -strings -* `opts.boolean` - a boolean, string or array of strings to always treat as -booleans. if `true` will treat all double hyphenated arguments without equal signs -as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`) -* `opts.alias` - an object mapping string names to strings or arrays of string -argument names to use as aliases -* `opts.default` - an object mapping string argument names to default values -* `opts.stopEarly` - when true, populate `argv._` with everything after the -first non-option -* `opts['--']` - when true, populate `argv._` with everything before the `--` -and `argv['--']` with everything after the `--`. Here's an example: - - ``` - > require('./')('one two three -- four five --six'.split(' '), { '--': true }) - { _: [ 'one', 'two', 'three' ], - '--': [ 'four', 'five', '--six' ] } - ``` - - Note that with `opts['--']` set, parsing for arguments still stops after the - `--`. - -* `opts.unknown` - a function which is invoked with a command line parameter not -defined in the `opts` configuration object. If the function returns `false`, the -unknown option is not added to `argv`. - -# install - -With [npm](https://npmjs.org) do: - -``` -npm install minimist -``` - -# license - -MIT diff --git a/node_modules/minimist/test/all_bool.js b/node_modules/minimist/test/all_bool.js deleted file mode 100644 index ac83548..0000000 --- a/node_modules/minimist/test/all_bool.js +++ /dev/null @@ -1,32 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('flag boolean true (default all --args to boolean)', function (t) { - var argv = parse(['moo', '--honk', 'cow'], { - boolean: true - }); - - t.deepEqual(argv, { - honk: true, - _: ['moo', 'cow'] - }); - - t.deepEqual(typeof argv.honk, 'boolean'); - t.end(); -}); - -test('flag boolean true only affects double hyphen arguments without equals signs', function (t) { - var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], { - boolean: true - }); - - t.deepEqual(argv, { - honk: true, - tacos: 'good', - p: 55, - _: ['moo', 'cow'] - }); - - t.deepEqual(typeof argv.honk, 'boolean'); - t.end(); -}); diff --git a/node_modules/minimist/test/bool.js b/node_modules/minimist/test/bool.js deleted file mode 100644 index 5f7dbde..0000000 --- a/node_modules/minimist/test/bool.js +++ /dev/null @@ -1,178 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('flag boolean default false', function (t) { - var argv = parse(['moo'], { - boolean: ['t', 'verbose'], - default: { verbose: false, t: false } - }); - - t.deepEqual(argv, { - verbose: false, - t: false, - _: ['moo'] - }); - - t.deepEqual(typeof argv.verbose, 'boolean'); - t.deepEqual(typeof argv.t, 'boolean'); - t.end(); - -}); - -test('boolean groups', function (t) { - var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { - boolean: ['x','y','z'] - }); - - t.deepEqual(argv, { - x : true, - y : false, - z : true, - _ : [ 'one', 'two', 'three' ] - }); - - t.deepEqual(typeof argv.x, 'boolean'); - t.deepEqual(typeof argv.y, 'boolean'); - t.deepEqual(typeof argv.z, 'boolean'); - t.end(); -}); -test('boolean and alias with chainable api', function (t) { - var aliased = [ '-h', 'derp' ]; - var regular = [ '--herp', 'derp' ]; - var opts = { - herp: { alias: 'h', boolean: true } - }; - var aliasedArgv = parse(aliased, { - boolean: 'herp', - alias: { h: 'herp' } - }); - var propertyArgv = parse(regular, { - boolean: 'herp', - alias: { h: 'herp' } - }); - var expected = { - herp: true, - h: true, - '_': [ 'derp' ] - }; - - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -test('boolean and alias with options hash', function (t) { - var aliased = [ '-h', 'derp' ]; - var regular = [ '--herp', 'derp' ]; - var opts = { - alias: { 'h': 'herp' }, - boolean: 'herp' - }; - var aliasedArgv = parse(aliased, opts); - var propertyArgv = parse(regular, opts); - var expected = { - herp: true, - h: true, - '_': [ 'derp' ] - }; - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -test('boolean and alias array with options hash', function (t) { - var aliased = [ '-h', 'derp' ]; - var regular = [ '--herp', 'derp' ]; - var alt = [ '--harp', 'derp' ]; - var opts = { - alias: { 'h': ['herp', 'harp'] }, - boolean: 'h' - }; - var aliasedArgv = parse(aliased, opts); - var propertyArgv = parse(regular, opts); - var altPropertyArgv = parse(alt, opts); - var expected = { - harp: true, - herp: true, - h: true, - '_': [ 'derp' ] - }; - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.same(altPropertyArgv, expected); - t.end(); -}); - -test('boolean and alias using explicit true', function (t) { - var aliased = [ '-h', 'true' ]; - var regular = [ '--herp', 'true' ]; - var opts = { - alias: { h: 'herp' }, - boolean: 'h' - }; - var aliasedArgv = parse(aliased, opts); - var propertyArgv = parse(regular, opts); - var expected = { - herp: true, - h: true, - '_': [ ] - }; - - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -// regression, see https://github.com/substack/node-optimist/issues/71 -test('boolean and --x=true', function(t) { - var parsed = parse(['--boool', '--other=true'], { - boolean: 'boool' - }); - - t.same(parsed.boool, true); - t.same(parsed.other, 'true'); - - parsed = parse(['--boool', '--other=false'], { - boolean: 'boool' - }); - - t.same(parsed.boool, true); - t.same(parsed.other, 'false'); - t.end(); -}); - -test('boolean --boool=true', function (t) { - var parsed = parse(['--boool=true'], { - default: { - boool: false - }, - boolean: ['boool'] - }); - - t.same(parsed.boool, true); - t.end(); -}); - -test('boolean --boool=false', function (t) { - var parsed = parse(['--boool=false'], { - default: { - boool: true - }, - boolean: ['boool'] - }); - - t.same(parsed.boool, false); - t.end(); -}); - -test('boolean using something similar to true', function (t) { - var opts = { boolean: 'h' }; - var result = parse(['-h', 'true.txt'], opts); - var expected = { - h: true, - '_': ['true.txt'] - }; - - t.same(result, expected); - t.end(); -}); \ No newline at end of file diff --git a/node_modules/minimist/test/dash.js b/node_modules/minimist/test/dash.js deleted file mode 100644 index 5a4fa5b..0000000 --- a/node_modules/minimist/test/dash.js +++ /dev/null @@ -1,31 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('-', function (t) { - t.plan(5); - t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] }); - t.deepEqual(parse([ '-' ]), { _: [ '-' ] }); - t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] }); - t.deepEqual( - parse([ '-b', '-' ], { boolean: 'b' }), - { b: true, _: [ '-' ] } - ); - t.deepEqual( - parse([ '-s', '-' ], { string: 's' }), - { s: '-', _: [] } - ); -}); - -test('-a -- b', function (t) { - t.plan(3); - t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] }); - t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); - t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); -}); - -test('move arguments after the -- into their own `--` array', function(t) { - t.plan(1); - t.deepEqual( - parse([ '--name', 'John', 'before', '--', 'after' ], { '--': true }), - { name: 'John', _: [ 'before' ], '--': [ 'after' ] }); -}); diff --git a/node_modules/minimist/test/default_bool.js b/node_modules/minimist/test/default_bool.js deleted file mode 100644 index 780a311..0000000 --- a/node_modules/minimist/test/default_bool.js +++ /dev/null @@ -1,35 +0,0 @@ -var test = require('tape'); -var parse = require('../'); - -test('boolean default true', function (t) { - var argv = parse([], { - boolean: 'sometrue', - default: { sometrue: true } - }); - t.equal(argv.sometrue, true); - t.end(); -}); - -test('boolean default false', function (t) { - var argv = parse([], { - boolean: 'somefalse', - default: { somefalse: false } - }); - t.equal(argv.somefalse, false); - t.end(); -}); - -test('boolean default to null', function (t) { - var argv = parse([], { - boolean: 'maybe', - default: { maybe: null } - }); - t.equal(argv.maybe, null); - var argv = parse(['--maybe'], { - boolean: 'maybe', - default: { maybe: null } - }); - t.equal(argv.maybe, true); - t.end(); - -}) diff --git a/node_modules/minimist/test/dotted.js b/node_modules/minimist/test/dotted.js deleted file mode 100644 index d8b3e85..0000000 --- a/node_modules/minimist/test/dotted.js +++ /dev/null @@ -1,22 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('dotted alias', function (t) { - var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); - t.equal(argv.a.b, 22); - t.equal(argv.aa.bb, 22); - t.end(); -}); - -test('dotted default', function (t) { - var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); - t.equal(argv.a.b, 11); - t.equal(argv.aa.bb, 11); - t.end(); -}); - -test('dotted default with no alias', function (t) { - var argv = parse('', {default: {'a.b': 11}}); - t.equal(argv.a.b, 11); - t.end(); -}); diff --git a/node_modules/minimist/test/kv_short.js b/node_modules/minimist/test/kv_short.js deleted file mode 100644 index f813b30..0000000 --- a/node_modules/minimist/test/kv_short.js +++ /dev/null @@ -1,16 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('short -k=v' , function (t) { - t.plan(1); - - var argv = parse([ '-b=123' ]); - t.deepEqual(argv, { b: 123, _: [] }); -}); - -test('multi short -k=v' , function (t) { - t.plan(1); - - var argv = parse([ '-a=whatever', '-b=robots' ]); - t.deepEqual(argv, { a: 'whatever', b: 'robots', _: [] }); -}); diff --git a/node_modules/minimist/test/long.js b/node_modules/minimist/test/long.js deleted file mode 100644 index 5d3a1e0..0000000 --- a/node_modules/minimist/test/long.js +++ /dev/null @@ -1,31 +0,0 @@ -var test = require('tape'); -var parse = require('../'); - -test('long opts', function (t) { - t.deepEqual( - parse([ '--bool' ]), - { bool : true, _ : [] }, - 'long boolean' - ); - t.deepEqual( - parse([ '--pow', 'xixxle' ]), - { pow : 'xixxle', _ : [] }, - 'long capture sp' - ); - t.deepEqual( - parse([ '--pow=xixxle' ]), - { pow : 'xixxle', _ : [] }, - 'long capture eq' - ); - t.deepEqual( - parse([ '--host', 'localhost', '--port', '555' ]), - { host : 'localhost', port : 555, _ : [] }, - 'long captures sp' - ); - t.deepEqual( - parse([ '--host=localhost', '--port=555' ]), - { host : 'localhost', port : 555, _ : [] }, - 'long captures eq' - ); - t.end(); -}); diff --git a/node_modules/minimist/test/num.js b/node_modules/minimist/test/num.js deleted file mode 100644 index 2cc77f4..0000000 --- a/node_modules/minimist/test/num.js +++ /dev/null @@ -1,36 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('nums', function (t) { - var argv = parse([ - '-x', '1234', - '-y', '5.67', - '-z', '1e7', - '-w', '10f', - '--hex', '0xdeadbeef', - '789' - ]); - t.deepEqual(argv, { - x : 1234, - y : 5.67, - z : 1e7, - w : '10f', - hex : 0xdeadbeef, - _ : [ 789 ] - }); - t.deepEqual(typeof argv.x, 'number'); - t.deepEqual(typeof argv.y, 'number'); - t.deepEqual(typeof argv.z, 'number'); - t.deepEqual(typeof argv.w, 'string'); - t.deepEqual(typeof argv.hex, 'number'); - t.deepEqual(typeof argv._[0], 'number'); - t.end(); -}); - -test('already a number', function (t) { - var argv = parse([ '-x', 1234, 789 ]); - t.deepEqual(argv, { x : 1234, _ : [ 789 ] }); - t.deepEqual(typeof argv.x, 'number'); - t.deepEqual(typeof argv._[0], 'number'); - t.end(); -}); diff --git a/node_modules/minimist/test/parse.js b/node_modules/minimist/test/parse.js deleted file mode 100644 index 7b4a2a1..0000000 --- a/node_modules/minimist/test/parse.js +++ /dev/null @@ -1,197 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('parse args', function (t) { - t.deepEqual( - parse([ '--no-moo' ]), - { moo : false, _ : [] }, - 'no' - ); - t.deepEqual( - parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), - { v : ['a','b','c'], _ : [] }, - 'multi' - ); - t.end(); -}); - -test('comprehensive', function (t) { - t.deepEqual( - parse([ - '--name=meowmers', 'bare', '-cats', 'woo', - '-h', 'awesome', '--multi=quux', - '--key', 'value', - '-b', '--bool', '--no-meep', '--multi=baz', - '--', '--not-a-flag', 'eek' - ]), - { - c : true, - a : true, - t : true, - s : 'woo', - h : 'awesome', - b : true, - bool : true, - key : 'value', - multi : [ 'quux', 'baz' ], - meep : false, - name : 'meowmers', - _ : [ 'bare', '--not-a-flag', 'eek' ] - } - ); - t.end(); -}); - -test('flag boolean', function (t) { - var argv = parse([ '-t', 'moo' ], { boolean: 't' }); - t.deepEqual(argv, { t : true, _ : [ 'moo' ] }); - t.deepEqual(typeof argv.t, 'boolean'); - t.end(); -}); - -test('flag boolean value', function (t) { - var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { - boolean: [ 't', 'verbose' ], - default: { verbose: true } - }); - - t.deepEqual(argv, { - verbose: false, - t: true, - _: ['moo'] - }); - - t.deepEqual(typeof argv.verbose, 'boolean'); - t.deepEqual(typeof argv.t, 'boolean'); - t.end(); -}); - -test('newlines in params' , function (t) { - var args = parse([ '-s', "X\nX" ]) - t.deepEqual(args, { _ : [], s : "X\nX" }); - - // reproduce in bash: - // VALUE="new - // line" - // node program.js --s="$VALUE" - args = parse([ "--s=X\nX" ]) - t.deepEqual(args, { _ : [], s : "X\nX" }); - t.end(); -}); - -test('strings' , function (t) { - var s = parse([ '-s', '0001234' ], { string: 's' }).s; - t.equal(s, '0001234'); - t.equal(typeof s, 'string'); - - var x = parse([ '-x', '56' ], { string: 'x' }).x; - t.equal(x, '56'); - t.equal(typeof x, 'string'); - t.end(); -}); - -test('stringArgs', function (t) { - var s = parse([ ' ', ' ' ], { string: '_' })._; - t.same(s.length, 2); - t.same(typeof s[0], 'string'); - t.same(s[0], ' '); - t.same(typeof s[1], 'string'); - t.same(s[1], ' '); - t.end(); -}); - -test('empty strings', function(t) { - var s = parse([ '-s' ], { string: 's' }).s; - t.equal(s, ''); - t.equal(typeof s, 'string'); - - var str = parse([ '--str' ], { string: 'str' }).str; - t.equal(str, ''); - t.equal(typeof str, 'string'); - - var letters = parse([ '-art' ], { - string: [ 'a', 't' ] - }); - - t.equal(letters.a, ''); - t.equal(letters.r, true); - t.equal(letters.t, ''); - - t.end(); -}); - - -test('string and alias', function(t) { - var x = parse([ '--str', '000123' ], { - string: 's', - alias: { s: 'str' } - }); - - t.equal(x.str, '000123'); - t.equal(typeof x.str, 'string'); - t.equal(x.s, '000123'); - t.equal(typeof x.s, 'string'); - - var y = parse([ '-s', '000123' ], { - string: 'str', - alias: { str: 's' } - }); - - t.equal(y.str, '000123'); - t.equal(typeof y.str, 'string'); - t.equal(y.s, '000123'); - t.equal(typeof y.s, 'string'); - t.end(); -}); - -test('slashBreak', function (t) { - t.same( - parse([ '-I/foo/bar/baz' ]), - { I : '/foo/bar/baz', _ : [] } - ); - t.same( - parse([ '-xyz/foo/bar/baz' ]), - { x : true, y : true, z : '/foo/bar/baz', _ : [] } - ); - t.end(); -}); - -test('alias', function (t) { - var argv = parse([ '-f', '11', '--zoom', '55' ], { - alias: { z: 'zoom' } - }); - t.equal(argv.zoom, 55); - t.equal(argv.z, argv.zoom); - t.equal(argv.f, 11); - t.end(); -}); - -test('multiAlias', function (t) { - var argv = parse([ '-f', '11', '--zoom', '55' ], { - alias: { z: [ 'zm', 'zoom' ] } - }); - t.equal(argv.zoom, 55); - t.equal(argv.z, argv.zoom); - t.equal(argv.z, argv.zm); - t.equal(argv.f, 11); - t.end(); -}); - -test('nested dotted objects', function (t) { - var argv = parse([ - '--foo.bar', '3', '--foo.baz', '4', - '--foo.quux.quibble', '5', '--foo.quux.o_O', - '--beep.boop' - ]); - - t.same(argv.foo, { - bar : 3, - baz : 4, - quux : { - quibble : 5, - o_O : true - } - }); - t.same(argv.beep, { boop : true }); - t.end(); -}); diff --git a/node_modules/minimist/test/parse_modified.js b/node_modules/minimist/test/parse_modified.js deleted file mode 100644 index ab620dc..0000000 --- a/node_modules/minimist/test/parse_modified.js +++ /dev/null @@ -1,9 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('parse with modifier functions' , function (t) { - t.plan(1); - - var argv = parse([ '-b', '123' ], { boolean: 'b' }); - t.deepEqual(argv, { b: true, _: [123] }); -}); diff --git a/node_modules/minimist/test/proto.js b/node_modules/minimist/test/proto.js deleted file mode 100644 index 8649107..0000000 --- a/node_modules/minimist/test/proto.js +++ /dev/null @@ -1,44 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('proto pollution', function (t) { - var argv = parse(['--__proto__.x','123']); - t.equal({}.x, undefined); - t.equal(argv.__proto__.x, undefined); - t.equal(argv.x, undefined); - t.end(); -}); - -test('proto pollution (array)', function (t) { - var argv = parse(['--x','4','--x','5','--x.__proto__.z','789']); - t.equal({}.z, undefined); - t.deepEqual(argv.x, [4,5]); - t.equal(argv.x.z, undefined); - t.equal(argv.x.__proto__.z, undefined); - t.end(); -}); - -test('proto pollution (number)', function (t) { - var argv = parse(['--x','5','--x.__proto__.z','100']); - t.equal({}.z, undefined); - t.equal((4).z, undefined); - t.equal(argv.x, 5); - t.equal(argv.x.z, undefined); - t.end(); -}); - -test('proto pollution (string)', function (t) { - var argv = parse(['--x','abc','--x.__proto__.z','def']); - t.equal({}.z, undefined); - t.equal('...'.z, undefined); - t.equal(argv.x, 'abc'); - t.equal(argv.x.z, undefined); - t.end(); -}); - -test('proto pollution (constructor)', function (t) { - var argv = parse(['--constructor.prototype.y','123']); - t.equal({}.y, undefined); - t.equal(argv.y, undefined); - t.end(); -}); diff --git a/node_modules/minimist/test/short.js b/node_modules/minimist/test/short.js deleted file mode 100644 index d513a1c..0000000 --- a/node_modules/minimist/test/short.js +++ /dev/null @@ -1,67 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('numeric short args', function (t) { - t.plan(2); - t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] }); - t.deepEqual( - parse([ '-123', '456' ]), - { 1: true, 2: true, 3: 456, _: [] } - ); -}); - -test('short', function (t) { - t.deepEqual( - parse([ '-b' ]), - { b : true, _ : [] }, - 'short boolean' - ); - t.deepEqual( - parse([ 'foo', 'bar', 'baz' ]), - { _ : [ 'foo', 'bar', 'baz' ] }, - 'bare' - ); - t.deepEqual( - parse([ '-cats' ]), - { c : true, a : true, t : true, s : true, _ : [] }, - 'group' - ); - t.deepEqual( - parse([ '-cats', 'meow' ]), - { c : true, a : true, t : true, s : 'meow', _ : [] }, - 'short group next' - ); - t.deepEqual( - parse([ '-h', 'localhost' ]), - { h : 'localhost', _ : [] }, - 'short capture' - ); - t.deepEqual( - parse([ '-h', 'localhost', '-p', '555' ]), - { h : 'localhost', p : 555, _ : [] }, - 'short captures' - ); - t.end(); -}); - -test('mixed short bool and capture', function (t) { - t.same( - parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), - { - f : true, p : 555, h : 'localhost', - _ : [ 'script.js' ] - } - ); - t.end(); -}); - -test('short and long', function (t) { - t.deepEqual( - parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), - { - f : true, p : 555, h : 'localhost', - _ : [ 'script.js' ] - } - ); - t.end(); -}); diff --git a/node_modules/minimist/test/stop_early.js b/node_modules/minimist/test/stop_early.js deleted file mode 100644 index bdf9fbc..0000000 --- a/node_modules/minimist/test/stop_early.js +++ /dev/null @@ -1,15 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('stops parsing on the first non-option when stopEarly is set', function (t) { - var argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], { - stopEarly: true - }); - - t.deepEqual(argv, { - aaa: 'bbb', - _: ['ccc', '--ddd'] - }); - - t.end(); -}); diff --git a/node_modules/minimist/test/unknown.js b/node_modules/minimist/test/unknown.js deleted file mode 100644 index 462a36b..0000000 --- a/node_modules/minimist/test/unknown.js +++ /dev/null @@ -1,102 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('boolean and alias is not unknown', function (t) { - var unknown = []; - function unknownFn(arg) { - unknown.push(arg); - return false; - } - var aliased = [ '-h', 'true', '--derp', 'true' ]; - var regular = [ '--herp', 'true', '-d', 'true' ]; - var opts = { - alias: { h: 'herp' }, - boolean: 'h', - unknown: unknownFn - }; - var aliasedArgv = parse(aliased, opts); - var propertyArgv = parse(regular, opts); - - t.same(unknown, ['--derp', '-d']); - t.end(); -}); - -test('flag boolean true any double hyphen argument is not unknown', function (t) { - var unknown = []; - function unknownFn(arg) { - unknown.push(arg); - return false; - } - var argv = parse(['--honk', '--tacos=good', 'cow', '-p', '55'], { - boolean: true, - unknown: unknownFn - }); - t.same(unknown, ['--tacos=good', 'cow', '-p']); - t.same(argv, { - honk: true, - _: [] - }); - t.end(); -}); - -test('string and alias is not unknown', function (t) { - var unknown = []; - function unknownFn(arg) { - unknown.push(arg); - return false; - } - var aliased = [ '-h', 'hello', '--derp', 'goodbye' ]; - var regular = [ '--herp', 'hello', '-d', 'moon' ]; - var opts = { - alias: { h: 'herp' }, - string: 'h', - unknown: unknownFn - }; - var aliasedArgv = parse(aliased, opts); - var propertyArgv = parse(regular, opts); - - t.same(unknown, ['--derp', '-d']); - t.end(); -}); - -test('default and alias is not unknown', function (t) { - var unknown = []; - function unknownFn(arg) { - unknown.push(arg); - return false; - } - var aliased = [ '-h', 'hello' ]; - var regular = [ '--herp', 'hello' ]; - var opts = { - default: { 'h': 'bar' }, - alias: { 'h': 'herp' }, - unknown: unknownFn - }; - var aliasedArgv = parse(aliased, opts); - var propertyArgv = parse(regular, opts); - - t.same(unknown, []); - t.end(); - unknownFn(); // exercise fn for 100% coverage -}); - -test('value following -- is not unknown', function (t) { - var unknown = []; - function unknownFn(arg) { - unknown.push(arg); - return false; - } - var aliased = [ '--bad', '--', 'good', 'arg' ]; - var opts = { - '--': true, - unknown: unknownFn - }; - var argv = parse(aliased, opts); - - t.same(unknown, ['--bad']); - t.same(argv, { - '--': ['good', 'arg'], - '_': [] - }) - t.end(); -}); diff --git a/node_modules/minimist/test/whitespace.js b/node_modules/minimist/test/whitespace.js deleted file mode 100644 index 8a52a58..0000000 --- a/node_modules/minimist/test/whitespace.js +++ /dev/null @@ -1,8 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('whitespace should be whitespace' , function (t) { - t.plan(1); - var x = parse([ '-x', '\t' ]).x; - t.equal(x, '\t'); -}); diff --git a/node_modules/mkdirp-classic/LICENSE b/node_modules/mkdirp-classic/LICENSE deleted file mode 100644 index f6b3a0d..0000000 --- a/node_modules/mkdirp-classic/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2020 James Halliday (mail@substack.net) and Mathias Buus - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -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/mkdirp-classic/README.md b/node_modules/mkdirp-classic/README.md deleted file mode 100644 index be5ac93..0000000 --- a/node_modules/mkdirp-classic/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# mkdirp-classic - -Just a non-deprecated mirror of [mkdirp 0.5.2](https://github.com/substack/node-mkdirp/tree/0.5.1) -for use in modules where we depend on the non promise interface. - -``` -npm install mkdirp-classic -``` - -## Usage - -``` js -// See the above link -``` - -## License - -MIT diff --git a/node_modules/mkdirp-classic/index.js b/node_modules/mkdirp-classic/index.js deleted file mode 100644 index 6ce241b..0000000 --- a/node_modules/mkdirp-classic/index.js +++ /dev/null @@ -1,98 +0,0 @@ -var path = require('path'); -var fs = require('fs'); -var _0777 = parseInt('0777', 8); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; - } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); - } - if (!made) made = null; - - var cb = f || function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), opts, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); -} - -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); - } - if (!made) made = null; - - p = path.resolve(p); - - try { - xfs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - } - } - - return made; -}; diff --git a/node_modules/mkdirp-classic/package.json b/node_modules/mkdirp-classic/package.json deleted file mode 100644 index 2e90df7..0000000 --- a/node_modules/mkdirp-classic/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "_from": "mkdirp-classic@^0.5.2", - "_id": "mkdirp-classic@0.5.3", - "_inBundle": false, - "_integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", - "_location": "/mkdirp-classic", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "mkdirp-classic@^0.5.2", - "name": "mkdirp-classic", - "escapedName": "mkdirp-classic", - "rawSpec": "^0.5.2", - "saveSpec": null, - "fetchSpec": "^0.5.2" - }, - "_requiredBy": [ - "/tar-fs" - ], - "_resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", - "_shasum": "fa10c9115cc6d8865be221ba47ee9bed78601113", - "_spec": "mkdirp-classic@^0.5.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/tar-fs", - "author": { - "name": "Mathias Buus", - "url": "@mafintosh" - }, - "bugs": { - "url": "https://github.com/mafintosh/mkdirp-classic/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Mirror of mkdirp 0.5.2", - "devDependencies": {}, - "homepage": "https://github.com/mafintosh/mkdirp-classic", - "license": "MIT", - "main": "index.js", - "name": "mkdirp-classic", - "repository": { - "type": "git", - "url": "git+https://github.com/mafintosh/mkdirp-classic.git" - }, - "version": "0.5.3" -} diff --git a/node_modules/mkdirp/LICENSE b/node_modules/mkdirp/LICENSE deleted file mode 100644 index 432d1ae..0000000 --- a/node_modules/mkdirp/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: - -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/mkdirp/bin/cmd.js b/node_modules/mkdirp/bin/cmd.js deleted file mode 100755 index d95de15..0000000 --- a/node_modules/mkdirp/bin/cmd.js +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env node - -var mkdirp = require('../'); -var minimist = require('minimist'); -var fs = require('fs'); - -var argv = minimist(process.argv.slice(2), { - alias: { m: 'mode', h: 'help' }, - string: [ 'mode' ] -}); -if (argv.help) { - fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout); - return; -} - -var paths = argv._.slice(); -var mode = argv.mode ? parseInt(argv.mode, 8) : undefined; - -(function next () { - if (paths.length === 0) return; - var p = paths.shift(); - - if (mode === undefined) mkdirp(p, cb) - else mkdirp(p, mode, cb) - - function cb (err) { - if (err) { - console.error(err.message); - process.exit(1); - } - else next(); - } -})(); diff --git a/node_modules/mkdirp/bin/usage.txt b/node_modules/mkdirp/bin/usage.txt deleted file mode 100644 index f952aa2..0000000 --- a/node_modules/mkdirp/bin/usage.txt +++ /dev/null @@ -1,12 +0,0 @@ -usage: mkdirp [DIR1,DIR2..] {OPTIONS} - - Create each supplied directory including any necessary parent directories that - don't yet exist. - - If the directory already exists, do nothing. - -OPTIONS are: - - -m, --mode If a directory needs to be created, set the mode as an octal - permission string. - diff --git a/node_modules/mkdirp/index.js b/node_modules/mkdirp/index.js deleted file mode 100644 index 468d7cd..0000000 --- a/node_modules/mkdirp/index.js +++ /dev/null @@ -1,99 +0,0 @@ -var path = require('path'); -var fs = require('fs'); -var _0777 = parseInt('0777', 8); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; - } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 - } - if (!made) made = null; - - var cb = f || function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - if (path.dirname(p) === p) return cb(er); - mkdirP(path.dirname(p), opts, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); -} - -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 - } - if (!made) made = null; - - p = path.resolve(p); - - try { - xfs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - } - } - - return made; -}; diff --git a/node_modules/mkdirp/package.json b/node_modules/mkdirp/package.json deleted file mode 100644 index d7df6a4..0000000 --- a/node_modules/mkdirp/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "mkdirp@^0.5.1", - "_id": "mkdirp@0.5.5", - "_inBundle": false, - "_integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", - "_location": "/mkdirp", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "mkdirp@^0.5.1", - "name": "mkdirp", - "escapedName": "mkdirp", - "rawSpec": "^0.5.1", - "saveSpec": null, - "fetchSpec": "^0.5.1" - }, - "_requiredBy": [ - "/prebuild-install" - ], - "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", - "_shasum": "d91cefd62d1436ca0f41620e251288d420099def", - "_spec": "mkdirp@^0.5.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/prebuild-install", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "bin": { - "mkdirp": "bin/cmd.js" - }, - "bugs": { - "url": "https://github.com/substack/node-mkdirp/issues" - }, - "bundleDependencies": false, - "dependencies": { - "minimist": "^1.2.5" - }, - "deprecated": false, - "description": "Recursively mkdir, like `mkdir -p`", - "devDependencies": { - "mock-fs": "^3.7.0", - "tap": "^5.4.2" - }, - "files": [ - "bin", - "index.js" - ], - "homepage": "https://github.com/substack/node-mkdirp#readme", - "keywords": [ - "mkdir", - "directory" - ], - "license": "MIT", - "main": "index.js", - "name": "mkdirp", - "publishConfig": { - "tag": "legacy" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/substack/node-mkdirp.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "version": "0.5.5" -} diff --git a/node_modules/mkdirp/readme.markdown b/node_modules/mkdirp/readme.markdown deleted file mode 100644 index fc314bf..0000000 --- a/node_modules/mkdirp/readme.markdown +++ /dev/null @@ -1,100 +0,0 @@ -# mkdirp - -Like `mkdir -p`, but in node.js! - -[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp) - -# example - -## pow.js - -```js -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') -}); -``` - -Output - -``` -pow! -``` - -And now /tmp/foo/bar/baz exists, huzzah! - -# methods - -```js -var mkdirp = require('mkdirp'); -``` - -## mkdirp(dir, opts, cb) - -Create a new directory and any necessary subdirectories at `dir` with octal -permission string `opts.mode`. If `opts` is a non-object, it will be treated as -the `opts.mode`. - -If `opts.mode` isn't specified, it defaults to `0777`. - -`cb(err, made)` fires with the error or the first directory `made` -that had to be created, if any. - -You can optionally pass in an alternate `fs` implementation by passing in -`opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and -`opts.fs.stat(path, cb)`. - -## mkdirp.sync(dir, opts) - -Synchronously create a new directory and any necessary subdirectories at `dir` -with octal permission string `opts.mode`. If `opts` is a non-object, it will be -treated as the `opts.mode`. - -If `opts.mode` isn't specified, it defaults to `0777`. - -Returns the first directory that had to be created, if any. - -You can optionally pass in an alternate `fs` implementation by passing in -`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and -`opts.fs.statSync(path)`. - -# usage - -This package also ships with a `mkdirp` command. - -``` -usage: mkdirp [DIR1,DIR2..] {OPTIONS} - - Create each supplied directory including any necessary parent directories that - don't yet exist. - - If the directory already exists, do nothing. - -OPTIONS are: - - -m, --mode If a directory needs to be created, set the mode as an octal - permission string. - -``` - -# install - -With [npm](http://npmjs.org) do: - -``` -npm install mkdirp -``` - -to get the library, or - -``` -npm install -g mkdirp -``` - -to get the command. - -# license - -MIT diff --git a/node_modules/mongodb/HISTORY.md b/node_modules/mongodb/HISTORY.md deleted file mode 100644 index aeaa226..0000000 --- a/node_modules/mongodb/HISTORY.md +++ /dev/null @@ -1,2740 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - - -## [3.5.8](https://github.com/mongodb/node-mongodb-native/compare/v3.5.7...v3.5.8) (2020-05-28) - - -### Bug Fixes - -* always clear cancelled wait queue members during processing ([0394f9d](https://github.com/mongodb/node-mongodb-native/commit/0394f9d)) -* always include `writeErrors` on a `BulkWriteError` instance ([58b4f94](https://github.com/mongodb/node-mongodb-native/commit/58b4f94)) -* ensure implicit sessions are ended consistently ([5c6fda1](https://github.com/mongodb/node-mongodb-native/commit/5c6fda1)) -* filter servers before applying reducers ([4faf9f5](https://github.com/mongodb/node-mongodb-native/commit/4faf9f5)) -* unordered bulk write should attempt to execute all batches ([6cee96b](https://github.com/mongodb/node-mongodb-native/commit/6cee96b)) -* **ChangeStream:** should resume from errors when iterating ([5ecf18e](https://github.com/mongodb/node-mongodb-native/commit/5ecf18e)) -* honor journal=true in connection string ([#2359](https://github.com/mongodb/node-mongodb-native/issues/2359)) ([246669f](https://github.com/mongodb/node-mongodb-native/commit/246669f)) -* **ChangeStream:** whitelist resumable errors ([#2337](https://github.com/mongodb/node-mongodb-native/issues/2337)) ([a9d3965](https://github.com/mongodb/node-mongodb-native/commit/a9d3965)), closes [#17](https://github.com/mongodb/node-mongodb-native/issues/17) [#18](https://github.com/mongodb/node-mongodb-native/issues/18) - - - - -## [3.5.7](https://github.com/mongodb/node-mongodb-native/compare/v3.5.6...v3.5.7) (2020-04-29) - - -### Bug Fixes - -* limit growth of server sessions through lazy acquisition ([3d05a6d](https://github.com/mongodb/node-mongodb-native/commit/3d05a6d)) -* remove circular dependency warnings on node 14 ([56a1b8a](https://github.com/mongodb/node-mongodb-native/commit/56a1b8a)) - - - - -## [3.5.6](https://github.com/mongodb/node-mongodb-native/compare/v3.5.5...v3.5.6) (2020-04-14) - - -### Bug Fixes - -* always return empty array for selection on unknown topology ([f9e786a](https://github.com/mongodb/node-mongodb-native/commit/f9e786a)) -* createCollection only uses listCollections in strict mode ([d368f12](https://github.com/mongodb/node-mongodb-native/commit/d368f12)) -* don't throw if `withTransaction()` callback rejects with a null reason ([153646c](https://github.com/mongodb/node-mongodb-native/commit/153646c)) -* only mark server session dirty if the client session is alive ([611be8d](https://github.com/mongodb/node-mongodb-native/commit/611be8d)) -* polyfill for util.promisify ([1c4cf6c](https://github.com/mongodb/node-mongodb-native/commit/1c4cf6c)) -* single `readPreferenceTags` should be parsed as an array ([a50611b](https://github.com/mongodb/node-mongodb-native/commit/a50611b)) -* **cursor:** transforms should only be applied once to documents ([704f30a](https://github.com/mongodb/node-mongodb-native/commit/704f30a)) - - - - -## [3.5.5](https://github.com/mongodb/node-mongodb-native/compare/v3.5.4...v3.5.5) (2020-03-11) - - -### Bug Fixes - -* correctly use template string for connection string error message ([6238c84](https://github.com/mongodb/node-mongodb-native/commit/6238c84)) -* don't depend on private node api for `Timeout` wrapper ([3ddaa3e](https://github.com/mongodb/node-mongodb-native/commit/3ddaa3e)) -* multiple concurrent attempts to process the queue may fail ([f69f51c](https://github.com/mongodb/node-mongodb-native/commit/f69f51c)) -* pass optional promise lib to maybePromise ([cde11ec](https://github.com/mongodb/node-mongodb-native/commit/cde11ec)) -* **cursor:** hasNext consumes documents on cursor with limit ([ef04d00](https://github.com/mongodb/node-mongodb-native/commit/ef04d00)) - - - - -## [3.5.4](https://github.com/mongodb/node-mongodb-native/compare/v3.5.3...v3.5.4) (2020-02-25) - - -### Bug Fixes - -* **cmap:** don't run min connection thread if no minimum specified ([2d1b713](https://github.com/mongodb/node-mongodb-native/commit/2d1b713)) -* **sdam:** use ObjectId comparison to track maxElectionId ([a1e0849](https://github.com/mongodb/node-mongodb-native/commit/a1e0849)) -* **topology:** ensure selection wait queue is always processed ([bf701d6](https://github.com/mongodb/node-mongodb-native/commit/bf701d6)) -* **topology:** enter `STATE_CLOSING` before draining waitQueue ([494dffb](https://github.com/mongodb/node-mongodb-native/commit/494dffb)) -* don't consume first document when calling `hasNext` on cursor ([bb359a1](https://github.com/mongodb/node-mongodb-native/commit/bb359a1)) - - -### Features - -* add utility helper for returning promises or using callbacks ([ac9e4c9](https://github.com/mongodb/node-mongodb-native/commit/ac9e4c9)) - - - - -## [3.5.3](https://github.com/mongodb/node-mongodb-native/compare/v3.5.2...v3.5.3) (2020-02-12) - - -### Bug Fixes - -* **message-stream:** support multiple inbound message packets ([8388443](https://github.com/mongodb/node-mongodb-native/commit/8388443)) -* **server:** non-timeout network errors transition to Unknown state ([fa4b01b](https://github.com/mongodb/node-mongodb-native/commit/fa4b01b)) - - -### Features - -* **connection:** support exhaust behavior at the transport level ([9ccf268](https://github.com/mongodb/node-mongodb-native/commit/9ccf268)) - - - - -## [3.5.2](https://github.com/mongodb/node-mongodb-native/compare/v3.5.1...v3.5.2) (2020-01-20) - - -### Bug Fixes - -* properly handle err messages in MongoDB 2.6 servers ([0f4ab38](https://github.com/mongodb/node-mongodb-native/commit/0f4ab38)) -* **topology:** always emit SDAM unrecoverable errors ([57f158f](https://github.com/mongodb/node-mongodb-native/commit/57f158f)) - - - - -## [3.5.1](https://github.com/mongodb/node-mongodb-native/compare/v3.5.0...v3.5.1) (2020-01-17) - - -### Bug Fixes - -* **cmap:** accept all node TLS options as pool options ([5995d1d](https://github.com/mongodb/node-mongodb-native/commit/5995d1d)) -* **cmap:** error wait queue members on failed connection creation ([d13b153](https://github.com/mongodb/node-mongodb-native/commit/d13b153)) -* **connect:** listen to `secureConnect` for tls connections ([f8bdb8d](https://github.com/mongodb/node-mongodb-native/commit/f8bdb8d)) -* **transactions:** use options helper to resolve read preference ([9698a76](https://github.com/mongodb/node-mongodb-native/commit/9698a76)) -* **uri_parser:** TLS uri variants imply `ssl=true` ([c8d182e](https://github.com/mongodb/node-mongodb-native/commit/c8d182e)) - - - - -# [3.5.0](https://github.com/mongodb/node-mongodb-native/compare/v3.4.1...v3.5.0) (2020-01-14) - - -### Bug Fixes - -* copy `ssl` option to pool connection options ([563ced6](https://github.com/mongodb/node-mongodb-native/commit/563ced6)) -* destroy connections marked as closed on checkIn / checkOut ([2bd17a6](https://github.com/mongodb/node-mongodb-native/commit/2bd17a6)) -* ensure sync errors are thrown, and don't callback twice ([cca5b49](https://github.com/mongodb/node-mongodb-native/commit/cca5b49)) -* ignore connection errors during pool destruction ([b8805dc](https://github.com/mongodb/node-mongodb-native/commit/b8805dc)) -* not all message payloads are arrays of Buffer ([e4df5f4](https://github.com/mongodb/node-mongodb-native/commit/e4df5f4)) -* recover on network error during initial connect ([a13dc68](https://github.com/mongodb/node-mongodb-native/commit/a13dc68)) -* remove servers with me mismatch in `updateRsFromPrimary` ([95a772e](https://github.com/mongodb/node-mongodb-native/commit/95a772e)) -* report the correct platform in client metadata ([35d0274](https://github.com/mongodb/node-mongodb-native/commit/35d0274)) -* reschedule monitoring before emitting heartbeat events ([7fcbeb5](https://github.com/mongodb/node-mongodb-native/commit/7fcbeb5)) -* socket timeout for handshake should be `connectTimeoutMS` ([c83af9a](https://github.com/mongodb/node-mongodb-native/commit/c83af9a)) -* timed out streams should be destroyed on `timeout` event ([5319ff9](https://github.com/mongodb/node-mongodb-native/commit/5319ff9)) -* use remote address for stream identifier ([f13c20b](https://github.com/mongodb/node-mongodb-native/commit/f13c20b)) -* used weighted RTT calculation for server selection ([d446be5](https://github.com/mongodb/node-mongodb-native/commit/d446be5)) -* **execute-operation:** don't swallow synchronous errors ([0a2d4e9](https://github.com/mongodb/node-mongodb-native/commit/0a2d4e9)) -* **gridfs:** make a copy of chunk before writing to server ([b4ec5b8](https://github.com/mongodb/node-mongodb-native/commit/b4ec5b8)) - - -### Features - -* add a `withConnection` helper to the connection pool ([d59dced](https://github.com/mongodb/node-mongodb-native/commit/d59dced)) -* include `connectionId` for APM with new CMAP connection pool ([9bd360c](https://github.com/mongodb/node-mongodb-native/commit/9bd360c)) -* integrate CMAP connection pool into unified topology ([9dd3939](https://github.com/mongodb/node-mongodb-native/commit/9dd3939)) -* introduce `MongoServerSelectionError` ([0cf7ec9](https://github.com/mongodb/node-mongodb-native/commit/0cf7ec9)) -* introduce a class for tracking stream specific attributes ([f6bf82c](https://github.com/mongodb/node-mongodb-native/commit/f6bf82c)) -* introduce a new `Monitor` type for server monitoring ([2bfe2a1](https://github.com/mongodb/node-mongodb-native/commit/2bfe2a1)) -* relay all CMAP events to MongoClient ([1aea4de](https://github.com/mongodb/node-mongodb-native/commit/1aea4de)) -* support socket timeouts on a per-connection level ([93e8ad0](https://github.com/mongodb/node-mongodb-native/commit/93e8ad0)) - - - - -## [3.4.1](https://github.com/mongodb/node-mongodb-native/compare/v3.4.0...v3.4.1) (2019-12-19) - - -### Bug Fixes - -* **bulk:** use original indexes as map for current op index ([20800ac](https://github.com/mongodb/node-mongodb-native/commit/20800ac)) -* always check for network errors during SCRAM conversation ([e46a70e](https://github.com/mongodb/node-mongodb-native/commit/e46a70e)) - - - - -# [3.4.0](https://github.com/mongodb/node-mongodb-native/compare/v3.3.5...v3.4.0) (2019-12-10) - - -### Bug Fixes - -* **bulk:** use operation index from input to report operation error ([f713b13](https://github.com/mongodb/node-mongodb-native/commit/f713b13)) -* **command:** only add TransientTransactionError label when in a transaction ([478d714](https://github.com/mongodb/node-mongodb-native/commit/478d714)) -* **compression:** recalculate opcode after determine OP_COMPRESSED ([022f51b](https://github.com/mongodb/node-mongodb-native/commit/022f51b)) -* **connect:** connect with family 0 instead of family 4 ([db07366](https://github.com/mongodb/node-mongodb-native/commit/db07366)) -* **connection:** timed out connections should not be half closed ([850f4f5](https://github.com/mongodb/node-mongodb-native/commit/850f4f5)) -* **cursor:** call `initialize` after session support check ([e50c51a](https://github.com/mongodb/node-mongodb-native/commit/e50c51a)) -* **encryption:** autoEncryption must error on mongodb < 4.2 ([c274615](https://github.com/mongodb/node-mongodb-native/commit/c274615)) -* **encryption:** do not attempt to merge autoEncryption options ([e27fdf9](https://github.com/mongodb/node-mongodb-native/commit/e27fdf9)) -* **encryption:** encryption uses smaller batch size ([cb78e69](https://github.com/mongodb/node-mongodb-native/commit/cb78e69)) -* **encryption:** respect bypassAutoEncryption ([e927499](https://github.com/mongodb/node-mongodb-native/commit/e927499)) -* **encryption:** respect user bson options when using autoEncryption ([cb7a3f7](https://github.com/mongodb/node-mongodb-native/commit/cb7a3f7)) -* add calculated duration to server as `roundTripTime` ([cb107a8](https://github.com/mongodb/node-mongodb-native/commit/cb107a8)) -* **mongodb+srv:** respect overriding SRV-provided properties ([ea83360](https://github.com/mongodb/node-mongodb-native/commit/ea83360)) -* **pool:** flush workItems after next tick to avoid dupe selection ([3ec49e5](https://github.com/mongodb/node-mongodb-native/commit/3ec49e5)) -* **pool:** support a `drain` event for use with unified topology ([da931ea](https://github.com/mongodb/node-mongodb-native/commit/da931ea)) -* **scram:** verify server digest, ensuring mutual authentication ([806cd62](https://github.com/mongodb/node-mongodb-native/commit/806cd62)) -* **srv-poller:** always provide a valid number for `intervalMS` ([afb125f](https://github.com/mongodb/node-mongodb-native/commit/afb125f)) -* **topology:** correct logic for checking for sessions support ([8d157c8](https://github.com/mongodb/node-mongodb-native/commit/8d157c8)) -* **topology:** don't drain iteration timers on server selection ([fed6a57](https://github.com/mongodb/node-mongodb-native/commit/fed6a57)) - - -### Features - -* add `MessageStream` for streamed wire protocol messaging ([8c44044](https://github.com/mongodb/node-mongodb-native/commit/8c44044)) -* introduce a modern `Connection` replacement for CMAP ([7890e48](https://github.com/mongodb/node-mongodb-native/commit/7890e48)) -* support connection establishment cancellation ([2014b7b](https://github.com/mongodb/node-mongodb-native/commit/2014b7b)) -* support driver info for drivers wrapping the node driver ([1b6670b](https://github.com/mongodb/node-mongodb-native/commit/1b6670b)) - - - - -## [3.3.5](https://github.com/mongodb/node-mongodb-native/compare/v3.3.4...v3.3.5) (2019-11-26) - - -### Bug Fixes - -* **bulk:** use operation index from input to report operation error ([08ee53e](https://github.com/mongodb/node-mongodb-native/commit/08ee53e)) -* **command:** only add TransientTransactionError label when in a transaction ([8bab074](https://github.com/mongodb/node-mongodb-native/commit/8bab074)) -* **connect:** connect with family 0 instead of family 4 ([7a41279](https://github.com/mongodb/node-mongodb-native/commit/7a41279)) -* **cursor:** call `initialize` after session support check ([3b076b3](https://github.com/mongodb/node-mongodb-native/commit/3b076b3)) -* **mongodb+srv:** respect overriding SRV-provided properties ([5ed4c07](https://github.com/mongodb/node-mongodb-native/commit/5ed4c07)) -* **pool:** support a `drain` event for use with unified topology ([3471c28](https://github.com/mongodb/node-mongodb-native/commit/3471c28)) -* **topology:** correct logic for checking for sessions support ([2d976bd](https://github.com/mongodb/node-mongodb-native/commit/2d976bd)) -* **topology:** don't drain iteration timers on server selection ([261f1e5](https://github.com/mongodb/node-mongodb-native/commit/261f1e5)) - - -### Features - -* support driver info for drivers wrapping the node driver ([d85c4a8](https://github.com/mongodb/node-mongodb-native/commit/d85c4a8)) - - - - -## [3.3.4](https://github.com/mongodb/node-mongodb-native/compare/v3.3.3...v3.3.4) (2019-11-11) - - -### Bug Fixes - -* **close:** the unified topology emits a close event on close now ([ee0db01](https://github.com/mongodb/node-mongodb-native/commit/ee0db01)) -* **connect:** prevent multiple callbacks in error scenarios ([5f6a787](https://github.com/mongodb/node-mongodb-native/commit/5f6a787)) -* **monitoring:** incorrect states used to determine rescheduling ([ec1e04c](https://github.com/mongodb/node-mongodb-native/commit/ec1e04c)) -* **pool:** don't reset a pool if we'not already connected ([32316e4](https://github.com/mongodb/node-mongodb-native/commit/32316e4)) -* **pool:** only transition to `DISCONNECTED` if reconnect enabled ([43d461e](https://github.com/mongodb/node-mongodb-native/commit/43d461e)) -* **replset:** don't leak servers failing to connect ([f209160](https://github.com/mongodb/node-mongodb-native/commit/f209160)) -* **replset:** use correct `topologyId` for event emission ([19549ff](https://github.com/mongodb/node-mongodb-native/commit/19549ff)) -* **sdam:** `minHeartbeatIntervalMS` => `minHeartbeatFrequencyMS` ([af9fb45](https://github.com/mongodb/node-mongodb-native/commit/af9fb45)) -* **sdam:** don't emit `close` every time a child server closes ([818055a](https://github.com/mongodb/node-mongodb-native/commit/818055a)) -* **sdam:** don't lose servers when they fail monitoring ([8a534bb](https://github.com/mongodb/node-mongodb-native/commit/8a534bb)) -* **sdam:** don't remove unknown servers in topology updates ([1147ebf](https://github.com/mongodb/node-mongodb-native/commit/1147ebf)) -* **sdam:** ignore server errors when closing/closed ([49d7235](https://github.com/mongodb/node-mongodb-native/commit/49d7235)) -* **server:** don't emit error in connect if closing/closed ([62ada2a](https://github.com/mongodb/node-mongodb-native/commit/62ada2a)) -* **server:** ensure state is transitioned to closed on connect fail ([a471707](https://github.com/mongodb/node-mongodb-native/commit/a471707)) -* **topology:** report unified topology as `nodejs` ([d126665](https://github.com/mongodb/node-mongodb-native/commit/d126665)) -* **topology:** set max listeners to infinity for db event relay ([edb1335](https://github.com/mongodb/node-mongodb-native/commit/edb1335)) - - -### Features - -* **sdam_viz:** add new tool for visualizing driver sdam changes ([738189a](https://github.com/mongodb/node-mongodb-native/commit/738189a)) -* **sdam_viz:** support legacy topologies in sdam_viz tool ([1a5537e](https://github.com/mongodb/node-mongodb-native/commit/1a5537e)) -* **update-hints:** add support for `hint` to all update methods ([720f5e5](https://github.com/mongodb/node-mongodb-native/commit/720f5e5)) - - - - -## [3.3.3](https://github.com/mongodb/node-mongodb-native/compare/v3.3.2...v3.3.3) (2019-10-16) - - -### Bug Fixes - -* **change_stream:** emit 'close' event if reconnecting failed ([f24c084](https://github.com/mongodb/node-mongodb-native/commit/f24c084)) -* **ChangeStream:** remove startAtOperationTime once we have resumeToken ([362afd8](https://github.com/mongodb/node-mongodb-native/commit/362afd8)) -* **connect:** Switch new Buffer(size) -> Buffer.alloc(size) ([da90c3a](https://github.com/mongodb/node-mongodb-native/commit/da90c3a)) -* **MongoClient:** only check own properties for valid options ([9cde4b9](https://github.com/mongodb/node-mongodb-native/commit/9cde4b9)) -* **mongos:** disconnect proxies which are not mongos instances ([ee53983](https://github.com/mongodb/node-mongodb-native/commit/ee53983)) -* **mongos:** force close servers during reconnect flow ([186263f](https://github.com/mongodb/node-mongodb-native/commit/186263f)) -* **monitoring:** correct spelling mistake for heartbeat event ([21aa117](https://github.com/mongodb/node-mongodb-native/commit/21aa117)) -* **replset:** correct server leak on initial connect ([da39d1e](https://github.com/mongodb/node-mongodb-native/commit/da39d1e)) -* **replset:** destroy primary before removing from replsetstate ([45ac09a](https://github.com/mongodb/node-mongodb-native/commit/45ac09a)) -* **replset:** destroy servers that are removed during SDAM flow ([9ea0190](https://github.com/mongodb/node-mongodb-native/commit/9ea0190)) -* **saslprep:** add in missing saslprep dependency ([41f1165](https://github.com/mongodb/node-mongodb-native/commit/41f1165)) -* **topology:** don't early abort server selection on network errors ([2b6a359](https://github.com/mongodb/node-mongodb-native/commit/2b6a359)) -* **topology:** don't emit server closed event on network error ([194dcf0](https://github.com/mongodb/node-mongodb-native/commit/194dcf0)) -* **topology:** include all BSON types in ctor for bson-ext support ([aa4c832](https://github.com/mongodb/node-mongodb-native/commit/aa4c832)) -* **topology:** respect the `force` parameter for topology close ([d6e8936](https://github.com/mongodb/node-mongodb-native/commit/d6e8936)) - -### Features - -* **Update:** add the ability to specify a pipeline to an update command ([#2017](https://github.com/mongodb/node-mongodb-native/issues/2017)) ([44a4110](https://github.com/mongodb/node-mongodb-native/commit/44a4110)) -* **urlParser:** default useNewUrlParser to true ([52d76e3](https://github.com/mongodb/node-mongodb-native/commit/52d76e3)) - - -## [3.2.7](https://github.com/mongodb/node-mongodb-native/compare/v3.2.6...v3.2.7) (2019-06-04) - - -### Bug Fixes - -* **core:** updating core to version 3.2.7 ([2f91466](https://github.com/mongodb/node-mongodb-native/commit/2f91466)) -* **findOneAndReplace:** throw error if atomic operators provided for findOneAndReplace ([6a860a3](https://github.com/mongodb/node-mongodb-native/commit/6a860a3)) - - - - -## [3.3.2](https://github.com/mongodb/node-mongodb-native/compare/v3.3.1...v3.3.2) (2019-08-28) - - -### Bug Fixes - -* **change-stream:** default to server default batch size ([b3ae4c5](https://github.com/mongodb/node-mongodb-native/commit/b3ae4c5)) -* **execute-operation:** return promise on session support check ([a976c14](https://github.com/mongodb/node-mongodb-native/commit/a976c14)) -* **gridfs-stream:** ensure `close` is emitted after last chunk ([ae94cb9](https://github.com/mongodb/node-mongodb-native/commit/ae94cb9)) - - - - -## [3.3.1](https://github.com/mongodb/node-mongodb-native/compare/v3.3.0...v3.3.1) (2019-08-23) - - -### Bug Fixes - -* **find:** respect client-level provided read preference ([fec4f15](https://github.com/mongodb/node-mongodb-native/commit/fec4f15)) -* correct inverted defaults for unified topology ([cf598e1](https://github.com/mongodb/node-mongodb-native/commit/cf598e1)) - - - - -# [3.3.0](https://github.com/mongodb/node-mongodb-native/compare/v3.3.0-alpha1...v3.3.0) (2019-08-13) - - -### Bug Fixes - -* **aggregate-operation:** move type assertions to constructor ([25b27ff](https://github.com/mongodb/node-mongodb-native/commit/25b27ff)) -* **autoEncryption:** tear down mongocryptd client when main client closes ([fe2f57e](https://github.com/mongodb/node-mongodb-native/commit/fe2f57e)) -* **autoEncryption:** use new url parser for autoEncryption client ([d3670c2](https://github.com/mongodb/node-mongodb-native/commit/d3670c2)) -* **Bulk:** change BulkWriteError message to first item from writeErrors ([#2013](https://github.com/mongodb/node-mongodb-native/issues/2013)) ([6bcf1e4](https://github.com/mongodb/node-mongodb-native/commit/6bcf1e4)) -* **change_stream:** emit 'close' event if reconnecting failed ([41aba90](https://github.com/mongodb/node-mongodb-native/commit/41aba90)) -* **change_stream:** emit close event after cursor is closed during error ([c2d80b2](https://github.com/mongodb/node-mongodb-native/commit/c2d80b2)) -* **change-streams:** don't copy irrelevant resume options ([f190072](https://github.com/mongodb/node-mongodb-native/commit/f190072)) -* **changestream:** removes all event listeners on close ([30eeeb5](https://github.com/mongodb/node-mongodb-native/commit/30eeeb5)) -* **ChangeStream:** remove startAtOperationTime once we have resumeToken ([8d27e6e](https://github.com/mongodb/node-mongodb-native/commit/8d27e6e)) -* **ClientSessions:** initialize clientOptions and cluster time ([b95d64e](https://github.com/mongodb/node-mongodb-native/commit/b95d64e)) -* **connect:** don't treat 'connect' as an error event ([170a011](https://github.com/mongodb/node-mongodb-native/commit/170a011)) -* **connect:** fixed syntax issue in connect error handler ([ff7166d](https://github.com/mongodb/node-mongodb-native/commit/ff7166d)) -* **connections_stepdown_tests:** use correct version of mongo for tests ([ce2c9af](https://github.com/mongodb/node-mongodb-native/commit/ce2c9af)) -* **createCollection:** Db.createCollection should pass readConcern to new collection ([#2026](https://github.com/mongodb/node-mongodb-native/issues/2026)) ([6145d4b](https://github.com/mongodb/node-mongodb-native/commit/6145d4b)) -* **cursor:** do not truncate an existing Long ([317055b](https://github.com/mongodb/node-mongodb-native/commit/317055b)), closes [mongodb-js/mongodb-core#441](https://github.com/mongodb-js/mongodb-core/issues/441) -* **distinct:** return full response if `full` option was specified ([95a7d05](https://github.com/mongodb/node-mongodb-native/commit/95a7d05)) -* **MongoClient:** allow Object.prototype items as db names ([dc6fc37](https://github.com/mongodb/node-mongodb-native/commit/dc6fc37)) -* **MongoClient:** only check own properties for valid options ([c9dc717](https://github.com/mongodb/node-mongodb-native/commit/c9dc717)) -* **OpMsg:** cap requestIds at 0x7fffffff ([c0e87d5](https://github.com/mongodb/node-mongodb-native/commit/c0e87d5)) -* **read-operations:** send sessions on all read operations ([4d45c8a](https://github.com/mongodb/node-mongodb-native/commit/4d45c8a)) -* **ReadPreference:** improve ReadPreference error message and remove irrelevant sharding test ([dd34ce4](https://github.com/mongodb/node-mongodb-native/commit/dd34ce4)) -* **ReadPreference:** only allow valid ReadPreference modes ([06bbef2](https://github.com/mongodb/node-mongodb-native/commit/06bbef2)) -* **replset:** correct legacy max staleness calculation ([2eab8aa](https://github.com/mongodb/node-mongodb-native/commit/2eab8aa)) -* **replset:** introduce a fixed-time server selection loop ([cf53299](https://github.com/mongodb/node-mongodb-native/commit/cf53299)) -* **server:** emit "first connect" error if initial connect fails due to ECONNREFUSED ([#2016](https://github.com/mongodb/node-mongodb-native/issues/2016)) ([5a7b15b](https://github.com/mongodb/node-mongodb-native/commit/5a7b15b)) -* **serverSelection:** make sure to pass session to serverSelection ([eb5cc6b](https://github.com/mongodb/node-mongodb-native/commit/eb5cc6b)) -* **sessions:** ensure an error is thrown when attempting sharded transactions ([3a1fdc1](https://github.com/mongodb/node-mongodb-native/commit/3a1fdc1)) -* **topology:** add new error for retryWrites on MMAPv1 ([392f5a6](https://github.com/mongodb/node-mongodb-native/commit/392f5a6)) -* don't check non-unified topologies for session support check ([2bccd3f](https://github.com/mongodb/node-mongodb-native/commit/2bccd3f)) -* maintain internal database name on collection rename ([884d46f](https://github.com/mongodb/node-mongodb-native/commit/884d46f)) -* only check for transaction state if session exists ([360975a](https://github.com/mongodb/node-mongodb-native/commit/360975a)) -* preserve aggregate explain support for legacy servers ([032b204](https://github.com/mongodb/node-mongodb-native/commit/032b204)) -* read concern only supported for `mapReduce` without inline ([51a36f3](https://github.com/mongodb/node-mongodb-native/commit/51a36f3)) -* reintroduce support for 2.6 listIndexes ([c3bfc05](https://github.com/mongodb/node-mongodb-native/commit/c3bfc05)) -* return `executeOperation` for explain, if promise is desired ([b4a7ad7](https://github.com/mongodb/node-mongodb-native/commit/b4a7ad7)) -* validate atomic operations in all update methods ([88bb77e](https://github.com/mongodb/node-mongodb-native/commit/88bb77e)) -* **transactions:** fix error message for attempting sharded ([eb5dfc9](https://github.com/mongodb/node-mongodb-native/commit/eb5dfc9)) -* **transactions:** fix sharded transaction error logic ([083e18a](https://github.com/mongodb/node-mongodb-native/commit/083e18a)) - - -### Features - -* **Aggregate:** support ReadConcern in aggregates with $out ([21cdcf0](https://github.com/mongodb/node-mongodb-native/commit/21cdcf0)) -* **AutoEncryption:** improve error message for missing mongodb-client-encryption ([583f29f](https://github.com/mongodb/node-mongodb-native/commit/583f29f)) -* **ChangeStream:** adds new resume functionality to ChangeStreams ([9ec9b8f](https://github.com/mongodb/node-mongodb-native/commit/9ec9b8f)) -* **ChangeStreamCursor:** introduce new cursor type for change streams ([8813eb0](https://github.com/mongodb/node-mongodb-native/commit/8813eb0)) -* **cryptdConnectionString:** makes mongocryptd uri configurable ([#2049](https://github.com/mongodb/node-mongodb-native/issues/2049)) ([a487be4](https://github.com/mongodb/node-mongodb-native/commit/a487be4)) -* **eachAsync:** dedupe async iteration with a common helper ([c296f3a](https://github.com/mongodb/node-mongodb-native/commit/c296f3a)) -* **execute-operation:** allow execution with server selection ([36bc1fd](https://github.com/mongodb/node-mongodb-native/commit/36bc1fd)) -* **pool:** add support for resetting the connection pool ([2d1ff40](https://github.com/mongodb/node-mongodb-native/commit/2d1ff40)) -* **sessions:** track dirty state of sessions, drop after use ([f61df16](https://github.com/mongodb/node-mongodb-native/commit/f61df16)) -* add concept of `data-bearing` type to `ServerDescription` ([852e14f](https://github.com/mongodb/node-mongodb-native/commit/852e14f)) -* **transaction:** allow applications to set maxTimeMS for commitTransaction ([b3948aa](https://github.com/mongodb/node-mongodb-native/commit/b3948aa)) -* **Update:** add the ability to specify a pipeline to an update command ([#2017](https://github.com/mongodb/node-mongodb-native/issues/2017)) ([dc1387e](https://github.com/mongodb/node-mongodb-native/commit/dc1387e)) -* add `known`, `data-bearing` filters to `TopologyDescription` ([d0ccb56](https://github.com/mongodb/node-mongodb-native/commit/d0ccb56)) -* perform selection before cursor operation execution if needed ([808cf37](https://github.com/mongodb/node-mongodb-native/commit/808cf37)) -* perform selection before operation execution if needed ([1a25876](https://github.com/mongodb/node-mongodb-native/commit/1a25876)) -* support explain operations in `CommandOperationV2` ([86f5ba5](https://github.com/mongodb/node-mongodb-native/commit/86f5ba5)) -* support operations passed to a `Cursor` or subclass ([b78bb89](https://github.com/mongodb/node-mongodb-native/commit/b78bb89)) - - - - -## [3.2.7](https://github.com/mongodb/node-mongodb-native/compare/v3.2.6...v3.2.7) (2019-06-04) - - -### Bug Fixes - -* **core:** updating core to version 3.2.7 ([2f91466](https://github.com/mongodb/node-mongodb-native/commit/2f91466)) -* **findOneAndReplace:** throw error if atomic operators provided for findOneAndReplace ([6a860a3](https://github.com/mongodb/node-mongodb-native/commit/6a860a3)) - - - - -## [3.2.6](https://github.com/mongodb/node-mongodb-native/compare/v3.2.5...v3.2.6) (2019-05-24) - - - - -## [3.2.5](https://github.com/mongodb/node-mongodb-native/compare/v3.2.4...v3.2.5) (2019-05-17) - - -### Bug Fixes - -* **core:** updating core to 3.2.5 ([a2766c1](https://github.com/mongodb/node-mongodb-native/commit/a2766c1)) - - - - -## [3.2.4](https://github.com/mongodb/node-mongodb-native/compare/v3.2.2...v3.2.4) (2019-05-08) - - -### Bug Fixes - -* **aggregation:** fix field name typo ([4235d04](https://github.com/mongodb/node-mongodb-native/commit/4235d04)) -* **async:** rewrote asyncGenerator in node < 10 syntax ([49c8cef](https://github.com/mongodb/node-mongodb-native/commit/49c8cef)) -* **BulkOp:** run unordered bulk ops in serial ([f548bd7](https://github.com/mongodb/node-mongodb-native/commit/f548bd7)) -* **bulkWrite:** fix issue with bulkWrite continuing w/ callback ([2a4a42c](https://github.com/mongodb/node-mongodb-native/commit/2a4a42c)) -* **docs:** correctly document that default for `sslValidate` is false ([1f8e7fa](https://github.com/mongodb/node-mongodb-native/commit/1f8e7fa)) -* **gridfs-stream:** honor chunk size ([9eeb114](https://github.com/mongodb/node-mongodb-native/commit/9eeb114)) -* **unified-topology:** only clone pool size if provided ([8dc2416](https://github.com/mongodb/node-mongodb-native/commit/8dc2416)) - - -### Features - -* update to mongodb-core v3.2.3 ([1c5357a](https://github.com/mongodb/node-mongodb-native/commit/1c5357a)) -* **core:** update to mongodb-core v3.2.4 ([2059260](https://github.com/mongodb/node-mongodb-native/commit/2059260)) -* **lib:** implement executeOperationV2 ([67d4edf](https://github.com/mongodb/node-mongodb-native/commit/67d4edf)) - - - - -## [3.2.3](https://github.com/mongodb/node-mongodb-native/compare/v3.2.2...v3.2.3) (2019-04-05) - - -### Bug Fixes - -* **aggregation:** fix field name typo ([4235d04](https://github.com/mongodb/node-mongodb-native/commit/4235d04)) -* **async:** rewrote asyncGenerator in node < 10 syntax ([49c8cef](https://github.com/mongodb/node-mongodb-native/commit/49c8cef)) -* **bulkWrite:** fix issue with bulkWrite continuing w/ callback ([2a4a42c](https://github.com/mongodb/node-mongodb-native/commit/2a4a42c)) -* **docs:** correctly document that default for `sslValidate` is false ([1f8e7fa](https://github.com/mongodb/node-mongodb-native/commit/1f8e7fa)) - - -### Features - -* update to mongodb-core v3.2.3 ([1c5357a](https://github.com/mongodb/node-mongodb-native/commit/1c5357a)) - - - - -## [3.2.2](https://github.com/mongodb/node-mongodb-native/compare/v3.2.1...v3.2.2) (2019-03-22) - - -### Bug Fixes - -* **asyncIterator:** stronger guard against importing async generator ([e0826fb](https://github.com/mongodb/node-mongodb-native/commit/e0826fb)) - - -### Features - -* update to mongodb-core v3.2.2 ([868cfc3](https://github.com/mongodb/node-mongodb-native/commit/868cfc3)) - - - - -## [3.2.1](https://github.com/mongodb/node-mongodb-native/compare/v3.2.0...v3.2.1) (2019-03-21) - - -### Features - -* **core:** update to mongodb-core v3.2.1 ([30b0100](https://github.com/mongodb/node-mongodb-native/commit/30b0100)) - - - - -# [3.2.0](https://github.com/mongodb/node-mongodb-native/compare/v3.1.13...v3.2.0) (2019-03-21) - - -### Bug Fixes - -* **aggregate:** do not send batchSize for aggregation with $out ([ddb8d90](https://github.com/mongodb/node-mongodb-native/commit/ddb8d90)) -* **bulkWrite:** always count undefined values in bson size for bulk ([436d340](https://github.com/mongodb/node-mongodb-native/commit/436d340)) -* **db_ops:** rename db to add user on ([79931af](https://github.com/mongodb/node-mongodb-native/commit/79931af)) -* **mongo_client_ops:** only skip authentication if no authMechanism is specified ([3b6957d](https://github.com/mongodb/node-mongodb-native/commit/3b6957d)) -* **mongo-client:** ensure close callback is called with client ([f39e881](https://github.com/mongodb/node-mongodb-native/commit/f39e881)) - - -### Features - -* **core:** pin to mongodb-core v3.2.0 ([22af15a](https://github.com/mongodb/node-mongodb-native/commit/22af15a)) -* **Cursor:** adds support for AsyncIterator in cursors ([b972c1e](https://github.com/mongodb/node-mongodb-native/commit/b972c1e)) -* **db:** add database-level aggregation ([b629b21](https://github.com/mongodb/node-mongodb-native/commit/b629b21)) -* **mongo-client:** remove deprecated `logout` and print warning ([542859d](https://github.com/mongodb/node-mongodb-native/commit/542859d)) -* **topology-base:** support passing callbacks to `close` method ([7c111e0](https://github.com/mongodb/node-mongodb-native/commit/7c111e0)) -* **transactions:** support pinning mongos for sharded txns ([3886127](https://github.com/mongodb/node-mongodb-native/commit/3886127)) -* **unified-sdam:** backport unified SDAM to master for v3.2.0 ([79f33ca](https://github.com/mongodb/node-mongodb-native/commit/79f33ca)) - - - - -## [3.1.13](https://github.com/mongodb/node-mongodb-native/compare/v3.1.12...v3.1.13) (2019-01-23) - - -### Bug Fixes - -* restore ability to webpack by removing `makeLazyLoader` ([050267d](https://github.com/mongodb/node-mongodb-native/commit/050267d)) -* **bulk:** honor ignoreUndefined in initializeUnorderedBulkOp ([e806be4](https://github.com/mongodb/node-mongodb-native/commit/e806be4)) -* **changeStream:** properly handle changeStream event mid-close ([#1902](https://github.com/mongodb/node-mongodb-native/issues/1902)) ([5ad9fa9](https://github.com/mongodb/node-mongodb-native/commit/5ad9fa9)) -* **db_ops:** ensure we async resolve errors in createCollection ([210c71d](https://github.com/mongodb/node-mongodb-native/commit/210c71d)) - - - - -## [3.1.12](https://github.com/mongodb/node-mongodb-native/compare/v3.1.11...v3.1.12) (2019-01-16) - - -### Features - -* **core:** update to mongodb-core v3.1.11 ([9bef6e7](https://github.com/mongodb/node-mongodb-native/commit/9bef6e7)) - - - - -## [3.1.11](https://github.com/mongodb/node-mongodb-native/compare/v3.1.10...v3.1.11) (2019-01-15) - - -### Bug Fixes - -* **bulk:** fix error propagation in empty bulk.execute ([a3adb3f](https://github.com/mongodb/node-mongodb-native/commit/a3adb3f)) -* **bulk:** make sure that any error in bulk write is propagated ([bedc2d2](https://github.com/mongodb/node-mongodb-native/commit/bedc2d2)) -* **bulk:** properly calculate batch size for bulk writes ([aafe71b](https://github.com/mongodb/node-mongodb-native/commit/aafe71b)) -* **operations:** do not call require in a hot path ([ff82ff4](https://github.com/mongodb/node-mongodb-native/commit/ff82ff4)) - - - - -## [3.1.10](https://github.com/mongodb/node-mongodb-native/compare/v3.1.9...v3.1.10) (2018-11-16) - - -### Bug Fixes - -* **auth:** remember to default to admin database ([c7dec28](https://github.com/mongodb/node-mongodb-native/commit/c7dec28)) - - -### Features - -* **core:** update to mongodb-core v3.1.9 ([bd3355b](https://github.com/mongodb/node-mongodb-native/commit/bd3355b)) - - - - -## [3.1.9](https://github.com/mongodb/node-mongodb-native/compare/v3.1.8...v3.1.9) (2018-11-06) - - -### Bug Fixes - -* **db:** move db constants to other file to avoid circular ref ([#1858](https://github.com/mongodb/node-mongodb-native/issues/1858)) ([239036f](https://github.com/mongodb/node-mongodb-native/commit/239036f)) -* **estimated-document-count:** support options other than maxTimeMs ([36c3c7d](https://github.com/mongodb/node-mongodb-native/commit/36c3c7d)) - - -### Features - -* **core:** update to mongodb-core v3.1.8 ([80d7c79](https://github.com/mongodb/node-mongodb-native/commit/80d7c79)) - - - - -## [3.1.8](https://github.com/mongodb/node-mongodb-native/compare/v3.1.7...v3.1.8) (2018-10-10) - - -### Bug Fixes - -* **connect:** use reported default databse from new uri parser ([811f8f8](https://github.com/mongodb/node-mongodb-native/commit/811f8f8)) - - -### Features - -* **core:** update to mongodb-core v3.1.7 ([dbfc905](https://github.com/mongodb/node-mongodb-native/commit/dbfc905)) - - - - -## [3.1.7](https://github.com/mongodb/node-mongodb-native/compare/v3.1.6...v3.1.7) (2018-10-09) - - -### Features - -* **core:** update mongodb-core to v3.1.6 ([61b054e](https://github.com/mongodb/node-mongodb-native/commit/61b054e)) - - - - -## [3.1.6](https://github.com/mongodb/node-mongodb-native/compare/v3.1.5...v3.1.6) (2018-09-15) - - -### Features - -* **core:** update to core v3.1.5 ([c5f823d](https://github.com/mongodb/node-mongodb-native/commit/c5f823d)) - - - - -## [3.1.5](https://github.com/mongodb/node-mongodb-native/compare/v3.1.4...v3.1.5) (2018-09-14) - - -### Bug Fixes - -* **cursor:** allow `$meta` based sort when passing an array to `sort()` ([f93a8c3](https://github.com/mongodb/node-mongodb-native/commit/f93a8c3)) -* **utils:** only set retryWrites to true for valid operations ([3b725ef](https://github.com/mongodb/node-mongodb-native/commit/3b725ef)) - - -### Features - -* **core:** bump core to v3.1.4 ([805d58a](https://github.com/mongodb/node-mongodb-native/commit/805d58a)) - - - - -## [3.1.4](https://github.com/mongodb/node-mongodb-native/compare/v3.1.3...v3.1.4) (2018-08-25) - - -### Bug Fixes - -* **buffer:** use safe-buffer polyfill to maintain compatibility ([327da95](https://github.com/mongodb/node-mongodb-native/commit/327da95)) -* **change-stream:** properly support resumablity in stream mode ([c43a34b](https://github.com/mongodb/node-mongodb-native/commit/c43a34b)) -* **connect:** correct replacement of topology on connect callback ([918a1e0](https://github.com/mongodb/node-mongodb-native/commit/918a1e0)) -* **cursor:** remove deprecated notice on forEach ([a474158](https://github.com/mongodb/node-mongodb-native/commit/a474158)) -* **url-parser:** bail early on validation when using domain socket ([3cb3da3](https://github.com/mongodb/node-mongodb-native/commit/3cb3da3)) - - -### Features - -* **client-ops:** allow bypassing creation of topologies on connect ([fe39b93](https://github.com/mongodb/node-mongodb-native/commit/fe39b93)) -* **core:** update mongodb-core to 3.1.3 ([a029047](https://github.com/mongodb/node-mongodb-native/commit/a029047)) -* **test:** use connection strings for all calls to `newClient` ([1dac18f](https://github.com/mongodb/node-mongodb-native/commit/1dac18f)) - - - - -## [3.1.3](https://github.com/mongodb/node-mongodb-native/compare/v3.1.2...v3.1.3) (2018-08-13) - - -### Features - -* **core:** update to mongodb-core 3.1.2 ([337cb79](https://github.com/mongodb/node-mongodb-native/commit/337cb79)) - - - - -## [3.1.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.2) (2018-08-13) - - -### Bug Fixes - -* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) -* **buffer:** replace deprecated Buffer constructor ([759dd85](https://github.com/mongodb/node-mongodb-native/commit/759dd85)) -* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) -* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) -* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) -* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) -* **client-ops:** return transform map to map rather than function ([cfb7d83](https://github.com/mongodb/node-mongodb-native/commit/cfb7d83)) -* **collection:** correctly shallow clone passed in options ([7727700](https://github.com/mongodb/node-mongodb-native/commit/7727700)) -* **collection:** countDocuments throws error when query doesn't match docs ([09c7d8e](https://github.com/mongodb/node-mongodb-native/commit/09c7d8e)) -* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) -* **collection:** ensure findAndModify always use readPreference primary ([86344f4](https://github.com/mongodb/node-mongodb-native/commit/86344f4)) -* **collection:** isCapped returns false instead of undefined ([b8471f1](https://github.com/mongodb/node-mongodb-native/commit/b8471f1)) -* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) -* **count-documents:** return callback on error case ([fca1185](https://github.com/mongodb/node-mongodb-native/commit/fca1185)) -* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) -* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) -* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) -* **cursor:** set readPreference for cursor.count ([13d776f](https://github.com/mongodb/node-mongodb-native/commit/13d776f)) -* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) -* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) -* **db_ops:** call collection.find() with correct parameters ([#1795](https://github.com/mongodb/node-mongodb-native/issues/1795)) ([36e92f1](https://github.com/mongodb/node-mongodb-native/commit/36e92f1)) -* **db_ops:** fix two incorrectly named variables ([15dc808](https://github.com/mongodb/node-mongodb-native/commit/15dc808)) -* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) -* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) -* **mongo_client:** translate options for connectWithUrl ([78f6977](https://github.com/mongodb/node-mongodb-native/commit/78f6977)) -* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) -* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) -* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) -* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) -* **server:** remove unnecessary print statement ([2bcbc12](https://github.com/mongodb/node-mongodb-native/commit/2bcbc12)) -* **teardown:** properly destroy a topology when initial connect fails ([b8d2f1d](https://github.com/mongodb/node-mongodb-native/commit/b8d2f1d)) -* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) -* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) -* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) - - -### Features - -* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) -* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) -* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) -* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) -* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) -* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) -* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) -* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) -* **core:** bump core dependency to v3.1.0 ([4937240](https://github.com/mongodb/node-mongodb-native/commit/4937240)) -* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) -* **deprecation:** create deprecation function ([4f907a0](https://github.com/mongodb/node-mongodb-native/commit/4f907a0)) -* **deprecation:** wrap deprecated functions ([a5d0f1d](https://github.com/mongodb/node-mongodb-native/commit/a5d0f1d)) -* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) -* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) -* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) -* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) -* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) -* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) -* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) - - -### Reverts - -* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) - - - - -## [3.1.1](https://github.com/mongodb/node-mongodb-native/compare/v3.1.0...v3.1.1) (2018-07-05) - - -### Bug Fixes - -* **client-ops:** return transform map to map rather than function ([b8b4bfa](https://github.com/mongodb/node-mongodb-native/commit/b8b4bfa)) -* **collection:** correctly shallow clone passed in options ([2e6c4fa](https://github.com/mongodb/node-mongodb-native/commit/2e6c4fa)) -* **collection:** countDocuments throws error when query doesn't match docs ([4e83556](https://github.com/mongodb/node-mongodb-native/commit/4e83556)) -* **server:** remove unnecessary print statement ([20e11b3](https://github.com/mongodb/node-mongodb-native/commit/20e11b3)) - - - - -# [3.1.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.0) (2018-06-27) - - -### Bug Fixes - -* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) -* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) -* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) -* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) -* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) -* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) -* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) -* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) -* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) -* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) -* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) -* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) -* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) -* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) -* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) -* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) -* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) -* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) -* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) -* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) -* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) - - -### Features - -* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) -* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) -* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) -* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) -* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) -* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) -* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) -* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) -* **core:** bump core dependency to v3.1.0 ([855bfdb](https://github.com/mongodb/node-mongodb-native/commit/855bfdb)) -* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) -* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) -* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) -* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) -* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) -* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) -* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) -* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) - - -### Reverts - -* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) - - - - -## [3.0.6](https://github.com/mongodb/node-mongodb-native/compare/v3.0.5...v3.0.6) (2018-04-09) - - -### Bug Fixes - -* **db:** ensure `dropDatabase` always uses primary read preference ([e62e5c9](https://github.com/mongodb/node-mongodb-native/commit/e62e5c9)) -* **driverBench:** driverBench has default options object now ([c557817](https://github.com/mongodb/node-mongodb-native/commit/c557817)) - - -### Features - -* **command-monitoring:** support enabling command monitoring ([5903680](https://github.com/mongodb/node-mongodb-native/commit/5903680)) -* **core:** update to mongodb-core v3.0.6 ([cfdd0ae](https://github.com/mongodb/node-mongodb-native/commit/cfdd0ae)) -* **driverBench:** Implementing DriverBench ([d10fbad](https://github.com/mongodb/node-mongodb-native/commit/d10fbad)) - - - - -## [3.0.5](https://github.com/mongodb/node-mongodb-native/compare/v3.0.4...v3.0.5) (2018-03-23) - - -### Bug Fixes - -* **AggregationCursor:** adding session tracking to AggregationCursor ([baca5b7](https://github.com/mongodb/node-mongodb-native/commit/baca5b7)) -* **Collection:** fix session leak in parallelCollectonScan ([3331ec9](https://github.com/mongodb/node-mongodb-native/commit/3331ec9)) -* **comments:** adding fixes for PR comments ([ee110ac](https://github.com/mongodb/node-mongodb-native/commit/ee110ac)) -* **url_parser:** support a default database on mongodb+srv uris ([6d39b2a](https://github.com/mongodb/node-mongodb-native/commit/6d39b2a)) - - -### Features - -* **sessions:** adding implicit cursor session support ([a81245b](https://github.com/mongodb/node-mongodb-native/commit/a81245b)) - - - - -## [3.0.4](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.4) (2018-03-05) - - -### Bug Fixes - -* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) -* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) -* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) -* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) -* **utils:** fixes executeOperation to clean up sessions ([04e6ef6](https://github.com/mongodb/node-mongodb-native/commit/04e6ef6)) - - -### Features - -* **default-db:** use dbName from uri if none provided ([23b1938](https://github.com/mongodb/node-mongodb-native/commit/23b1938)) -* **mongodb-core:** update to mongodb-core 3.0.4 ([1fdbaa5](https://github.com/mongodb/node-mongodb-native/commit/1fdbaa5)) - - - - -## [3.0.3](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.3) (2018-02-23) - - -### Bug Fixes - -* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) -* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) -* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) -* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) - - - - -## [3.0.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.1...v3.0.2) (2018-01-29) - - -### Bug Fixes - -* **collection:** ensure dynamic require of `db` is wrapped in parentheses ([efa78f0](https://github.com/mongodb/node-mongodb-native/commit/efa78f0)) -* **db:** only callback with MongoError NODE-1293 ([#1652](https://github.com/mongodb/node-mongodb-native/issues/1652)) ([45bc722](https://github.com/mongodb/node-mongodb-native/commit/45bc722)) -* **topology base:** allow more than 10 event listeners ([#1630](https://github.com/mongodb/node-mongodb-native/issues/1630)) ([d9fb750](https://github.com/mongodb/node-mongodb-native/commit/d9fb750)) -* **url parser:** preserve auth creds when composing conn string ([#1640](https://github.com/mongodb/node-mongodb-native/issues/1640)) ([eddca5e](https://github.com/mongodb/node-mongodb-native/commit/eddca5e)) - - -### Features - -* **bulk:** forward 'checkKeys' option for ordered and unordered bulk operations ([421a6b2](https://github.com/mongodb/node-mongodb-native/commit/421a6b2)) -* **collection:** expose `dbName` property of collection ([6fd05c1](https://github.com/mongodb/node-mongodb-native/commit/6fd05c1)) - - - - -## [3.0.1](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0...v3.0.1) (2017-12-24) - -* update mongodb-core to 3.0.1 - - -# [3.0.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0-rc0...v3.0.0) (2017-12-24) - - -### Bug Fixes - -* **aggregate:** remove support for inline results for aggregate ([#1620](https://github.com/mongodb/node-mongodb-native/issues/1620)) ([84457ec](https://github.com/mongodb/node-mongodb-native/commit/84457ec)) -* **topologies:** unify topologies connect API ([#1615](https://github.com/mongodb/node-mongodb-native/issues/1615)) ([0fb4658](https://github.com/mongodb/node-mongodb-native/commit/0fb4658)) - - -### Features - -* **keepAlive:** make keepAlive options consistent ([#1612](https://github.com/mongodb/node-mongodb-native/issues/1612)) ([f608f44](https://github.com/mongodb/node-mongodb-native/commit/f608f44)) - - -### BREAKING CHANGES - -* **topologies:** Function signature for `.connect` method on replset and mongos has changed. You shouldn't have been using this anyway, but if you were, you only should pass `options` and `callback`. - -Part of NODE-1089 -* **keepAlive:** option `keepAlive` is now split into boolean `keepAlive` and -number `keepAliveInitialDelay` - -Fixes NODE-998 - - - - -# [3.0.0-rc0](https://github.com/mongodb/node-mongodb-native/compare/v2.2.31...v3.0.0-rc0) (2017-12-05) - - -### Bug Fixes - -* **aggregation:** ensure that the `cursor` key is always present ([f16f314](https://github.com/mongodb/node-mongodb-native/commit/f16f314)) -* **apm:** give users access to raw server responses ([88b206b](https://github.com/mongodb/node-mongodb-native/commit/88b206b)) -* **apm:** only rebuilt cursor if reply is non-null ([96052c8](https://github.com/mongodb/node-mongodb-native/commit/96052c8)) -* **apm:** rebuild lost `cursor` info on pre-OP_QUERY responses ([4242d49](https://github.com/mongodb/node-mongodb-native/commit/4242d49)) -* **bulk-unordered:** add check for ignoreUndefined ([f38641a](https://github.com/mongodb/node-mongodb-native/commit/f38641a)) -* **change stream examples:** use timeouts, cleanup ([c5fec5f](https://github.com/mongodb/node-mongodb-native/commit/c5fec5f)) -* **change-streams:** ensure a majority read concern on initial agg ([23011e9](https://github.com/mongodb/node-mongodb-native/commit/23011e9)) -* **changeStreams:** fixing node4 issue with util.inherits ([#1587](https://github.com/mongodb/node-mongodb-native/issues/1587)) ([168bb3d](https://github.com/mongodb/node-mongodb-native/commit/168bb3d)) -* **collection:** allow { upsert: 1 } for findOneAndUpdate() and update() ([5bcedd6](https://github.com/mongodb/node-mongodb-native/commit/5bcedd6)) -* **collection:** allow passing `noCursorTimeout` as an option to `find()` ([e9c4ffc](https://github.com/mongodb/node-mongodb-native/commit/e9c4ffc)) -* **collection:** make the parameters of findOne very explicit ([3054f1a](https://github.com/mongodb/node-mongodb-native/commit/3054f1a)) -* **cursor:** `hasNext` should propagate errors when using callback ([6339625](https://github.com/mongodb/node-mongodb-native/commit/6339625)) -* **cursor:** close readable on `null` response for dead cursor ([6aca2c5](https://github.com/mongodb/node-mongodb-native/commit/6aca2c5)) -* **dns txt records:** check options are set ([e5caf4f](https://github.com/mongodb/node-mongodb-native/commit/e5caf4f)) -* **docs:** Represent each valid option in docs in both places ([fde6e5d](https://github.com/mongodb/node-mongodb-native/commit/fde6e5d)) -* **grid-store:** add missing callback ([66a9a05](https://github.com/mongodb/node-mongodb-native/commit/66a9a05)) -* **grid-store:** move into callback scope ([b53f65f](https://github.com/mongodb/node-mongodb-native/commit/b53f65f)) -* **GridFS:** fix TypeError: doc.data.length is not a function ([#1570](https://github.com/mongodb/node-mongodb-native/issues/1570)) ([22a4628](https://github.com/mongodb/node-mongodb-native/commit/22a4628)) -* **list-collections:** ensure default of primary ReadPreference ([4a0cfeb](https://github.com/mongodb/node-mongodb-native/commit/4a0cfeb)) -* **mongo client:** close client before calling done ([c828aab](https://github.com/mongodb/node-mongodb-native/commit/c828aab)) -* **mongo client:** do not connect if url parse error ([cd10084](https://github.com/mongodb/node-mongodb-native/commit/cd10084)) -* **mongo client:** send error to cb ([eafc9e2](https://github.com/mongodb/node-mongodb-native/commit/eafc9e2)) -* **mongo-client:** move to inside of callback ([68b0fca](https://github.com/mongodb/node-mongodb-native/commit/68b0fca)) -* **mongo-client:** options should not be passed to `connect` ([474ac65](https://github.com/mongodb/node-mongodb-native/commit/474ac65)) -* **tests:** migrate 2.x tests to 3.x ([3a5232a](https://github.com/mongodb/node-mongodb-native/commit/3a5232a)) -* **updateOne/updateMany:** ensure that update documents contain atomic operators ([8b4255a](https://github.com/mongodb/node-mongodb-native/commit/8b4255a)) -* **url parser:** add check for options as cb ([52b6039](https://github.com/mongodb/node-mongodb-native/commit/52b6039)) -* **url parser:** compare srv address and parent domains ([daa186d](https://github.com/mongodb/node-mongodb-native/commit/daa186d)) -* **url parser:** compare string from first period on ([9e5d77e](https://github.com/mongodb/node-mongodb-native/commit/9e5d77e)) -* **url parser:** default to ssl true for mongodb+srv ([0fbca4b](https://github.com/mongodb/node-mongodb-native/commit/0fbca4b)) -* **url parser:** error when multiple hostnames used ([c1aa681](https://github.com/mongodb/node-mongodb-native/commit/c1aa681)) -* **url parser:** keep original uri options and default to ssl true ([e876a72](https://github.com/mongodb/node-mongodb-native/commit/e876a72)) -* **url parser:** log instead of throw error for unsupported url options ([155de2d](https://github.com/mongodb/node-mongodb-native/commit/155de2d)) -* **url parser:** make sure uri has 3 parts ([aa9871b](https://github.com/mongodb/node-mongodb-native/commit/aa9871b)) -* **url parser:** only 1 txt record allowed with 2 possible options ([d9f4218](https://github.com/mongodb/node-mongodb-native/commit/d9f4218)) -* **url parser:** only check for multiple hostnames with srv protocol ([5542bcc](https://github.com/mongodb/node-mongodb-native/commit/5542bcc)) -* **url parser:** remove .only from test ([642e39e](https://github.com/mongodb/node-mongodb-native/commit/642e39e)) -* **url parser:** return callback ([6096afc](https://github.com/mongodb/node-mongodb-native/commit/6096afc)) -* **url parser:** support single text record with multiple strings ([356fa57](https://github.com/mongodb/node-mongodb-native/commit/356fa57)) -* **url parser:** try catch bug, not actually returning from try loop ([758892b](https://github.com/mongodb/node-mongodb-native/commit/758892b)) -* **url parser:** use warn instead of info ([40ed27d](https://github.com/mongodb/node-mongodb-native/commit/40ed27d)) -* **url-parser:** remove comment, send error to cb ([d44420b](https://github.com/mongodb/node-mongodb-native/commit/d44420b)) - - -### Features - -* **aggregate:** support hit field for aggregate command ([aa7da15](https://github.com/mongodb/node-mongodb-native/commit/aa7da15)) -* **aggregation:** adds support for comment in aggregation command ([#1571](https://github.com/mongodb/node-mongodb-native/issues/1571)) ([4ac475c](https://github.com/mongodb/node-mongodb-native/commit/4ac475c)) -* **aggregation:** fail aggregation on explain + readConcern/writeConcern ([e0ca1b4](https://github.com/mongodb/node-mongodb-native/commit/e0ca1b4)) -* **causal-consistency:** support `afterClusterTime` in readConcern ([a9097f7](https://github.com/mongodb/node-mongodb-native/commit/a9097f7)) -* **change-streams:** add support for change streams ([c02d25c](https://github.com/mongodb/node-mongodb-native/commit/c02d25c)) -* **collection:** updating find API ([f26362d](https://github.com/mongodb/node-mongodb-native/commit/f26362d)) -* **execute-operation:** implementation for common op execution ([67c344f](https://github.com/mongodb/node-mongodb-native/commit/67c344f)) -* **listDatabases:** add support for nameOnly option to listDatabases ([eb79b5a](https://github.com/mongodb/node-mongodb-native/commit/eb79b5a)) -* **maxTimeMS:** adding maxTimeMS option to createIndexes and dropIndexes ([90d4a63](https://github.com/mongodb/node-mongodb-native/commit/90d4a63)) -* **mongo-client:** implement `MongoClient.prototype.startSession` ([bce5adf](https://github.com/mongodb/node-mongodb-native/commit/bce5adf)) -* **retryable-writes:** add support for `retryWrites` cs option ([2321870](https://github.com/mongodb/node-mongodb-native/commit/2321870)) -* **sessions:** MongoClient will now track sessions and release ([6829f47](https://github.com/mongodb/node-mongodb-native/commit/6829f47)) -* **sessions:** support passing sessions via objects in all methods ([a531f05](https://github.com/mongodb/node-mongodb-native/commit/a531f05)) -* **shared:** add helper utilities for assertion and suite setup ([b6cc34e](https://github.com/mongodb/node-mongodb-native/commit/b6cc34e)) -* **ssl:** adds missing ssl options ssl options for `ciphers` and `ecdhCurve` ([441b7b1](https://github.com/mongodb/node-mongodb-native/commit/441b7b1)) -* **test-shared:** add `notEqual` assertion ([41d93fd](https://github.com/mongodb/node-mongodb-native/commit/41d93fd)) -* **test-shared:** add `strictEqual` assertion method ([cad8e19](https://github.com/mongodb/node-mongodb-native/commit/cad8e19)) -* **topologies:** expose underlaying `logicalSessionTimeoutMinutes' ([1609a37](https://github.com/mongodb/node-mongodb-native/commit/1609a37)) -* **url parser:** better error message for slash in hostname ([457bc29](https://github.com/mongodb/node-mongodb-native/commit/457bc29)) - - -### BREAKING CHANGES - -* **aggregation:** If you use aggregation, and try to use the explain flag while you -have a readConcern or writeConcern, your query will fail -* **collection:** `find` and `findOne` no longer support the `fields` parameter. -You can achieve the same results as the `fields` parameter by -either using `Cursor.prototype.project`, or by passing the `projection` -property in on the `options` object. Additionally, `find` does not -support individual options like `skip` and `limit` as positional -parameters. You must pass in these parameters in the `options` object - - - -3.0.0 2017-??-?? ----------------- -* NODE-1043 URI-escaping authentication and hostname details in connection string - -2.2.31 2017-08-08 ------------------ -* update mongodb-core to 2.2.15 -* allow auth option in MongoClient.connect -* remove duplicate option `promoteLongs` from MongoClient's `connect` -* bulk operations should not throw an error on empty batch - -2.2.30 2017-07-07 ------------------ -* Update mongodb-core to 2.2.14 -* MongoClient - * add `appname` to list of valid option names - * added test for passing appname as option -* NODE-1052 ensure user options are applied while parsing connection string uris - -2.2.29 2017-06-19 ------------------ -* Update mongodb-core to 2.1.13 - * NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. - * Use actual server type in standalone SDAM events. -* Allow multiple map calls (Issue #1521, https://github.com/Robbilie). -* Clone insertMany options before mutating (Issue #1522, https://github.com/vkarpov15). -* NODE-1034 Fix GridStore issue caused by Node 8.0.0 breaking backward compatible fs.read API. -* NODE-1026, use operator instead of skip function in order to avoid useless fetch stage. - -2.2.28 2017-06-02 ------------------ -* Update mongodb-core to 2.1.12 - * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. - * Minor fix to report the correct state on error. - * NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). - * Fix require_optional loading of bson-ext. - * Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. - * NODE-999 SDAM fixes for Mongos and single Server event emitting. - * NODE-1014 Set socketTimeout to default to 360 seconds. - * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. -* Just handle Collection name errors distinctly from general callback errors avoiding double callbacks in Db.collection. -* NODE-999 SDAM fixes for Mongos and single Server event emitting. -* NODE-1000 Added guard condition for upload.js checkDone function in case of race condition caused by late arriving chunk write. - -2.2.27 2017-05-22 ------------------ -* Updated mongodb-core to 2.1.11 - * NODE-987 Clear out old intervalIds on when calling topologyMonitor. - * NODE-987 Moved filtering to pingServer method and added test case. - * Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). - * NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interval. -* NODE-985 Deprecated Db.authenticate and Admin.authenticate and moved auth methods into authenticate.js to ensure MongoClient.connect does not print deprecation warnings. -* NODE-988 Merged readConcern and hint correctly on collection(...).find(...).count() -* Fix passing the readConcern option to MongoClient.connect (Issue #1514, https://github.com/bausmeier). -* NODE-996 Propegate all events up to a MongoClient instance. -* Allow saving doc with null `_id` (Issue #1517, https://github.com/vkarpov15). -* NODE-993 Expose hasNext for command cursor and add docs for both CommandCursor and Aggregation Cursor. - -2.2.26 2017-04-18 ------------------ -* Updated mongodb-core to 2.1.10 - * NODE-981 delegate auth to replset/mongos if inTopology is set. - * NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. - * Remove dynamic require (Issue #175, https://github.com/tellnes). - * NODE-696 Handle interrupted error for createIndexes. - * Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. - * NODE-966 promoteValues not being promoted correctly to getMore. - * Merged in fix for flushing out monitoring operations. -* NODE-983 Add cursorId to aggregate and listCollections commands (Issue, #1510). -* Mark group and profilingInfo as deprecated methods -* NODE-956 DOCS Examples. -* Update readable-stream to version 2.2.7. -* NODE-978 Added test case to uncover connection.end issue for node 0.10.x. -* NODE-972 Fix(db): don't remove database name if collectionName == dbName (Issue, #1502) -* Fixed merging of writeConcerns on db.collection method. -* NODE-970 mix in readPreference for strict mode listCollections callback. -* NODE-966 added testcase for promoteValues being applied to getMore commands. -* NODE-962 Merge in ignoreUndefined from collection level for find/findOne. -* Remove multi option from updateMany tests/docs (Issue #1499, https://github.com/spratt). -* NODE-963 Correctly handle cursor.count when using APM. - -2.2.25 2017-03-17 ------------------ -* Don't rely on global toString() for checking if object (Issue #1494, https://github.com/vkarpov15). -* Remove obsolete option uri_decode_auth (Issue #1488, https://github.com/kamagatos). -* NODE-936 Correctly translate ReadPreference to CoreReadPreference for mongos queries. -* Exposed BSONRegExp type. -* NODE-950 push correct index for INSERT ops (https://github.com/mbroadst). -* NODE-951 Added support for sslCRL option and added a test case for it. -* NODE-953 Made batchSize issue general at cursor level. -* NODE-954 Remove write concern from reindex helper as it will not be supported in 3.6. -* Updated mongodb-core to 2.1.9. - * Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. - * Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. - * Ensure SSL error propegates better for Replset connections when there is a SSL validation error. - * NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. - * NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. - -2.2.24 2017-02-14 ------------------ -* NODE-935, NODE-931 Make MongoClient strict options validation optional and instead print annoying console.warn entries. - -2.2.23 2017-02-13 ------------------ -* Updated mongodb-core to 2.1.8. - * NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. - * NODE-927 fixes issue where authentication was performed against arbiter instances. - * NODE-915 Normalize all host names to avoid comparison issues. - * Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. -* NODE-931 Validates all the options for MongoClient.connect and fixes missing connection settings. -* NODE-929 Update SSL tutorial to correctly reflect the non-need for server/mongos/replset subobjects -* Fix sensitive command check (Issue #1473, https://github.com/Annoraaq) - -2.2.22 2017-01-24 ------------------ -* Updated mongodb-core to 2.1.7. - * NODE-919 ReplicaSet connection does not close immediately (Issue #156). - * NODE-901 Fixed bug when normalizing host names. - * NODE-909 Fixed readPreference issue caused by direct connection to primary. - * NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. -* Add missing unref implementations for replset, mongos (Issue #1455, https://github.com/zbjornson) - -2.2.21 2017-01-13 ------------------ -* Updated mongodb-core to 2.1.6. - * NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. - -2.2.20 2017-01-11 ------------------ -* Updated mongodb-core to 2.1.5 to include bson 1.0.4 and bson-ext 1.0.4 due to Buffer.from being broken in early node 4.x versions. - -2.2.19 2017-01-03 ------------------ -* Corrupted Npm release fix. - -2.2.18 2017-01-03 ------------------ -* Updated mongodb-core to 2.1.4 to fix bson ObjectId toString issue with utils.inspect messing with toString parameters in node 6. - -2.2.17 2017-01-02 ------------------ -* updated createCollection doc options and linked to create command. -* Updated mongodb-core to 2.1.3. - * Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining - * Moved replicaset monitoring away from serial mode and to parallel mode. - * updated bson and bson-ext dependencies to 1.0.2. - -2.2.16 2016-12-13 ------------------ -* NODE-899 reversed upsertedId change to bring back old behavior. - -2.2.15 2016-12-10 ------------------ -* Updated mongodb-core to 2.1.2. - * Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. - * Emit reconnect event in primary joining when in connected status for a replicaset (Fixes mongoose reconnect issue). - -2.2.14 2016-12-08 ------------------ -* Updated mongodb-core to 2.1.1. -* NODE-892 Passthrough options.readPreference to mongodb-core ReplSet instance. - -2.2.13 2016-12-05 ------------------ -* Updated mongodb-core to 2.1.0. -* NODE-889 Fixed issue where legacy killcursor wire protocol messages would not be sent when APM is enabled. -* Expose parserType as property on topology objects. - -2.2.12 2016-11-29 ------------------ -* Updated mongodb-core to 2.0.14. - * Updated bson library to 0.5.7. - * Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). - * Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). - * Only check isConnected against availableConnections (Issue #142). - * NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. - * Set default servername to host is not passed through for sni. - * Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). - * NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. - * NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. - * NODE-850 Update Max Staleness implementation. - * NODE-849 username no longer required for MONGODB-X509 auth. - * NODE-848 BSON Regex flags must be alphabetically ordered. - * NODE-846 Create notice for all third party libraries. - * NODE-843 Executing bulk operations overwrites write concern parameter. - * NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. - * NODE-840 Resync CRUD spec tests. - * Unescapable while(true) loop (Issue #152). -* NODE-864 close event not emits during network issues using single server topology. -* Introduced maxStalenessSeconds. -* NODE-840 Added CRUD specification test cases and fix minor issues with upserts reporting matchedCount > 0. -* Don't ignore Db-level authSource when using auth method. (https://github.com/donaldguy). - -2.2.11 2016-10-21 ------------------ -* Updated mongodb-core to 2.0.13. - - Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). - - Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). - - Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). - - NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). -* Updated bson library to 0.5.6. - - Included cyclic dependency detection -* Fix typo in serverHeartbeatFailed event name (Issue #1418, https://github.com/jakesjews). -* NODE-824, readPreference "nearest" does not work when specified at collection level. -* NODE-822, GridFSBucketWriteStream end method does not handle optional parameters. -* NODE-823, GridFSBucketWriteStream end: callback is invoked with invalid parameters. -* NODE-829, Using Start/End offset option in GridFSBucketReadStream doesn't return the right sized buffer. - -2.2.10 2016-09-15 ------------------ -* Updated mongodb-core to 2.0.12. -* fix debug logging message not printing server name. -* fixed application metadata being sent by wrong ismaster. -* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. -* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". -* Updated bson library to 0.5.5. -* Added DBPointer up conversion to DBRef. -* MongoDB 3.4-RC Pass **appname** through MongoClient.connect uri or options to allow metadata to be passed. -* MongoDB 3.4-RC Pass collation options on update, findOne, find, createIndex, aggregate. -* MongoDB 3.4-RC Allow write concerns to be passed to all supporting server commands. -* MongoDB 3.4-RC Allow passing of **servername** as SSL options to support SNI. - -2.2.9 2016-08-29 ----------------- -* Updated mongodb-core to 2.0.11. -* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. -* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). -* Ensure promoteBuffers is propegated in same fashion as promoteValues and promoteLongs. -* Don't treat ObjectId as object for mapReduce scope (Issue #1397, https://github.com/vkarpov15). - -2.2.8 2016-08-23 ----------------- -* Updated mongodb-core to 2.0.10. -* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. -* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). - -2.2.7 2016-08-19 ----------------- -* If only a single mongos is provided in the seedlist, fix issue where it would be assigned as single standalone server instead of mongos topology (Issue #130). -* Updated mongodb-core to 2.0.9. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* NODE-798 Driver hangs on count command in replica set with one member. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* Allow passing in servername for TLS connections for SNI support. - -2.2.6 2016-08-16 ----------------- -* Updated mongodb-core to 2.0.8. -* Allow execution of store operations independent of having both a primary and secondary available (Issue #123). -* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. -* Allow passing in an array of tags to ReadPreference constructor (Issue #1382, https://github.com/vkarpov15) -* Added hashed connection names and fullResult. -* Updated bson library to 0.5.3. -* Enable maxTimeMS in count, distinct, findAndModify. - -2.2.5 2016-07-28 ----------------- -* Updated mongodb-core to 2.0.7. -* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). -* Added better warnings when passing in illegal seed list members to a Mongos topology. -* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. -* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) -* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. - -2.2.4 2016-07-19 ----------------- -* NPM corrupted upload fix. - -2.2.3 2016-07-19 ----------------- -* Updated mongodb-core to 2.0.6. -* Destroy connection on socket timeout due to newer node versions not closing the socket. - -2.2.2 2016-07-15 ----------------- -* Updated mongodb-core to 2.0.5. -* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. -* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. -* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. -* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. - -2.2.1 2016-07-11 ----------------- -* Updated mongodb-core to 2.0.4. -* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. -* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. -* NODE-746 Improves replicaset errors for wrong setName. - -2.2.0 2016-07-05 ----------------- -* Updated mongodb-core to 2.0.3. -* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. -* All authentication methods now handle both auth/reauthenticate and logout events. -* Introduced logout method to get rid of onAll option for logout command. -* Updated bson to 0.5.0 that includes Decimal128 support. -* Fixed logger error serialization issue. -* Documentation fixes. -* Implemented Server Selection Specification test suite. -* Added warning level to logger. -* Added warning message when sockeTimeout < haInterval for Replset/Mongos. -* Mongos emits close event on no proxies available or when reconnect attempt fails. -* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. -* Don't throw in auth methods but return error in callback. - -2.1.21 2016-05-30 ------------------ -* Updated mongodb-core to 1.3.21. -* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). -* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. -* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. -* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). -* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. -* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. - -2.1.20 2016-05-25 ------------------ -* Refactored MongoClient options handling to simplify the logic, unifying it. -* NODE-707 Implemented openUploadStreamWithId on GridFS to allow for custom fileIds so users are able to customize shard key and shard distribution. -* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. -* Updated mongodb-core to 1.3.20. -* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. -* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. -* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. - -2.1.19 2016-05-17 ----------------- -* Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. -* Ensure replicaset topology destroy is never called by SDAM. -* Ensure all paths are correctly returned on inspectServer in replset. -* Updated mongodb-core to 1.3.19 to fix minor connectivity issue on quick open/close of MongoClient connections on auth enabled mongodb Replicasets. - -2.1.18 2016-04-27 ------------------ -* Updated mongodb-core to 1.3.18 to fix Node 6.0 issues. - -2.1.17 2016-04-26 ------------------ -* Updated mongodb-core to 1.3.16 to work around issue with early versions of node 0.10.x due to missing unref method on ClearText streams. -* INT-1308: Allow listIndexes to inherit readPreference from Collection or DB. -* Fix timeout issue using new flags #1361. -* Updated mongodb-core to 1.3.17. -* Better handling of unique createIndex error. -* Emit error only if db instance has an error listener. -* DEFAULT authMechanism; don't throw error if explicitly set by user. - -2.1.16 2016-04-06 ------------------ -* Updated mongodb-core to 1.3.16. - -2.1.15 2016-04-06 ------------------ -* Updated mongodb-core to 1.3.15. -* Set ssl, sslValidate etc to mongosOptions on url_parser (Issue #1352, https://github.com/rubenstolk). -- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. -- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. - -2.1.14 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.13. -* Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. - -2.1.13 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.12. - -2.1.12 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.11. -* Mongos setting acceptableLatencyMS exposed to control the latency women for mongos selection. -* Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. -* isConnected method for mongos uses same selection code as getServer. -* Exceptions in cursor getServer trapped and correctly delegated to high level handler. - -2.1.11 2016-03-23 ------------------ -* Updated mongodb-core to 1.3.10. -* Introducing simplified connections settings. - -2.1.10 2016-03-21 ------------------ -* Updated mongodb-core to 1.3.9. -* Fixing issue that prevented mapReduce stats from being resolved (Issue #1351, https://github.com/davidgtonge) -* Forwards SDAM monitoring events from mongodb-core. - -2.1.9 2016-03-16 ----------------- -* Updated mongodb-core to 1.3.7 to fix intermittent race condition that causes some users to experience big amounts of socket connections. -* Makde bson parser in ordered/unordered bulk be directly from mongodb-core to avoid intermittent null error on mongoose. - -2.1.8 2016-03-14 ----------------- -* Updated mongodb-core to 1.3.5. -* NODE-660 TypeError: Cannot read property 'noRelease' of undefined. -* Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. -* Ensure RequestId can never be larger than Max Number integer size. -* NODE-661 typo in url_parser.js resulting in replSetServerOptions is not defined when connecting over ssl. -* Confusing error with invalid partial index filter (Issue #1341, https://github.com/vkarpov15). -* NODE-669 Should only error out promise for bulkWrite when error is a driver level error not a write error or write concern error. -* NODE-662 shallow copy options on methods that are not currently doing it to avoid passed in options mutiation. -* NODE-663 added lookup helper on aggregation cursor. -* NODE-585 Result object specified incorrectly for findAndModify?. -* NODE-666 harden validation for findAndModify CRUD methods. - -2.1.7 2016-02-09 ----------------- -* NODE-656 fixed corner case where cursor count command could be left without a connection available. -* NODE-658 Work around issue that bufferMaxEntries:-1 for js gets interpreted wrongly due to double nature of Javascript numbers. -* Fix: GridFS always returns the oldest version due to incorrect field name (Issue #1338, https://github.com/mdebruijne). -* NODE-655 GridFS stream support for cancelling upload streams and download streams (Issue #1339, https://github.com/vkarpov15). -* NODE-657 insertOne don`t return promise in some cases. -* Added destroy alias for abort function on GridFSBucketWriteStream. - -2.1.6 2016-02-05 ----------------- -* Updated mongodb-core to 1.3.1. - -2.1.5 2016-02-04 ----------------- -* Updated mongodb-core to 1.3.0. -* Added raw support for the command function on topologies. -* Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) -* Copy over all the properties to the callback returned from bindToDomain, (Issue #72) -* Added connection hash id to be able to reference connection host/name without leaking it outside of driver. -* NODE-638, Cannot authenticate database user with utf-8 password. -* Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. -* Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. -* Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. -* Switched to using Array.push instead of concat for use cases of a lot of documents. -* Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. -* Added peer optional dependencies support using require_optional module. -* Bug is listCollections for collection names that start with db name (Issue #1333, https://github.com/flyingfisher) -* Emit error before closing stream (Issue #1335, https://github.com/eagleeye) - -2.1.4 2016-01-12 ----------------- -* Restricted node engine to >0.10.3 (https://jira.mongodb.org/browse/NODE-635). -* Multiple database names ignored without a warning (https://jira.mongodb.org/browse/NODE-636, Issue #1324, https://github.com/yousefhamza). -* Convert custom readPreference objects in collection.js (Issue #1326, https://github.com/Machyne). - -2.1.3 2016-01-04 ----------------- -* Updated mongodb-core to 1.2.31. -* Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) - -2.1.2 2015-12-23 ----------------- -* Updated mongodb-core to 1.2.30. -* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -2.1.1 2015-12-13 ----------------- -* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. -* Added readPreference support to listCollections and listIndexes helpers. -* Updated mongodb-core to 1.2.28. - -2.1.0 2015-12-06 ----------------- -* Implements the connection string specification, https://github.com/mongodb/specifications/blob/master/source/connection-string/connection-string-spec.rst. -* Implements the new GridFS specification, https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst. -* Full MongoDB 3.2 support. -* NODE-601 Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -* Updated mongodb-core to 1.2.26. -* Return destination in GridStore pipe function. -* NODE-606 better error handling on destroyed topology for db.js methods. -* Added isDestroyed method to server, replset and mongos topologies. -* Upgraded test suite to run using mongodb-topology-manager. - -2.0.53 2015-12-23 ------------------ -* Updated mongodb-core to 1.2.30. -* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -2.0.52 2015-12-14 ------------------ -* removed remove from Gridstore.close. - -2.0.51 2015-12-13 ------------------ -* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. -* Added readPreference support to listCollections and listIndexes helpers. -* Updated mongodb-core to 1.2.28. - -2.0.50 2015-12-06 ------------------ -* Updated mongodb-core to 1.2.26. - -2.0.49 2015-11-20 ------------------ -* Updated mongodb-core to 1.2.24 with several fixes. - * Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). - * $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. - * ismaster runs against admin.$cmd instead of system.$cmd. - * Fixes to handle getMore command errors for MongoDB 3.2 - * Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. - -2.0.48 2015-11-07 ------------------ -* GridFS no longer performs any deletes when writing a brand new file that does not have any previous .fs.chunks or .fs.files documents. -* Updated mongodb-core to 1.2.21. -* Hardened the checking for replicaset equality checks. -* OpReplay flag correctly set on Wire protocol query. -* Mongos load balancing added, introduced localThresholdMS to control the feature. -* Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. - -2.0.47 2015-10-28 ------------------ -* Updated mongodb-core to 1.2.20. -* Fixed bug in arbiter connection capping code. -* NODE-599 correctly handle arrays of server tags in order of priority. -* Fix for 2.6 wire protocol handler related to readPreference handling. -* Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -* Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). - -2.0.46 2015-10-15 ------------------ -* Updated mongodb-core to 1.2.19. -* NODE-578 Order of sort fields is lost for numeric field names. -* Expose BSON Map (ES6 Map or polyfill). -* Minor fixes for APM support to pass extended APM test suite. - -2.0.45 2015-09-30 ------------------ -* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. - -2.0.44 2015-09-28 ------------------ -* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. -* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. -* Updated mongodb-core to 1.2.14. -* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. -* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) -* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. -* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. -* NODE-572 Remove examples that use the second parameter to `find()`. - -2.0.43 2015-09-14 ------------------ -* Propagate timeout event correctly to db instances. -* Application Monitoring API (APM) implemented. -* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. -* Updated mongodb-core to 1.2.12. -* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. -* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) -* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) -* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) - -2.0.42 2015-08-18 ------------------ -* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. - -2.0.41 2015-08-14 ------------------ -* Added missing Mongos.prototype.parserType function. -* Updated mongodb-core to 1.2.10. - -2.0.40 2015-07-14 ------------------ -* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. -* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. -* NODE-518 connectTimeoutMS is doubled in 2.0.39. -* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). -* NODE-526 Unique index not throwing duplicate key error. -* NODE-528 Ignore undefined fields in Collection.find(). -* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. - -2.0.39 2015-07-14 ------------------ -* Updated mongodb-core to 1.2.6 for NODE-505. - -2.0.38 2015-07-14 ------------------ -* NODE-505 Query fails to find records that have a 'result' property with an array value. - -2.0.37 2015-07-14 ------------------ -* NODE-504 Collection * Default options when using promiseLibrary. -* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. -* Updated mongodb-core to 1.2.5 to fix NODE-492. - -2.0.36 2015-07-07 ------------------ -* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). -* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. - -2.0.35 2015-06-17 ------------------ -* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. - -2.0.34 2015-06-17 ------------------ -* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. -* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. -* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. -* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. -* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. - -2.0.33 2015-05-20 ------------------ -* Bumped mongodb-core to 1.1.32. - -2.0.32 2015-05-19 ------------------ -* NODE-463 db.close immediately executes its callback. -* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). -* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. - -2.0.31 2015-05-08 ------------------ -* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. - -2.0.30 2015-05-07 ------------------ -* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. - -2.0.29 2015-05-07 ------------------ -* NODE-444 Possible memory leak, too many listeners added. -* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. -* Bumped mongodb-core to 1.1.26. - -2.0.28 2015-04-24 ------------------ -* Bumped mongodb-core to 1.1.25 -* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. -* NODE-430 Cursor.count() opts argument masked by var opts = {} -* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. -* NODE-438 replaceOne is not returning the result.ops property as described in the docs. -* NODE-433 _read, pipe and write all open gridstore automatically if not open. -* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. -* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. -* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). -* Minor fix in GridStore.exists for dealing with regular expressions searches. - -2.0.27 2015-04-07 ------------------ -* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. - -2.0.26 2015-04-07 ------------------ -* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. -* NODE-408 Expose GridStore.currentChunk.chunkNumber. - -2.0.25 2015-03-26 ------------------ -* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. - -2.0.24 2015-03-24 ------------------ -* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. -* Upgraded mongodb-core to 1.1.20. - -2.0.23 2015-03-21 ------------------ -* NODE-380 Correctly return MongoError from toError method. -* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. -* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. -* Upgraded mongodb-core to 1.1.19. - -2.0.22 2015-03-16 ------------------ -* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. -* Upgraded mongodb-core to 1.1.17. - -2.0.21 2015-03-06 ------------------ -* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. - -2.0.20 2015-03-04 ------------------ -* Updated mongodb-core 1.1.15 to relax pickserver method. - -2.0.19 2015-03-03 ------------------ -* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) -* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) -* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) - -2.0.18 2015-02-27 ------------------ -* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. - -2.0.17 2015-02-27 ------------------ -* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. -* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. - -2.0.16 2015-02-16 ------------------ -* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. -* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. -* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) - -2.0.15 2015-02-02 ------------------ -* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. -* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. -* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. -* Added ~1.0 mongodb-tools module for test running. -* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. - -2.0.14 2015-01-21 ------------------ -* Fixed some MongoClient.connect options pass through issues and added test coverage. -* Bumped mongodb-core to 1.1.9 including fixes for io.js - -2.0.13 2015-01-09 ------------------ -* Bumped mongodb-core to 1.1.8. -* Optimized query path for performance, moving Object.defineProperty outside of constructors. - -2.0.12 2014-12-22 ------------------ -* Minor fixes to listCollections to ensure correct querying of a collection when using a string. - -2.0.11 2014-12-19 ------------------ -* listCollections filters out index namespaces on < 2.8 correctly -* Bumped mongo-client to 1.1.7 - -2.0.10 2014-12-18 ------------------ -* NODE-328 fixed db.open return when no callback available issue and added test. -* NODE-327 Refactored listCollections to return cursor to support 2.8. -* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. -* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. -* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) -* Bumped mongo-client to 1.1.6 - -2.0.9 2014-12-01 ----------------- -* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. -* All classes are now strict (Issue #1233) -* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. -* Fixed recursion issues in debug logging due to JSON.stringify() -* Documentation fixes (Issue #1232, https://github.com/wsmoak) -* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) - -2.0.8 2014-11-28 ----------------- -* NODE-322 Finished up prototype refactoring of Db class. -* NODE-322 Exposed Cursor in index.js for New Relic. - -2.0.7 2014-11-20 ----------------- -* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. -* NODE-318 collection.update error while setting a function with serializeFunctions option. -* Documentation fixes. - -2.0.6 2014-11-14 ----------------- -* Refactored code to be prototype based instead of privileged methods. -* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. -* Implemented missing aspects of the CRUD specification. -* Fixed documentation issues. -* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) -* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) - -2.0.5 2014-10-29 ----------------- -* Minor fixes to documentation and generation of documentation. -* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. - -2.0.4 2014-10-23 ----------------- -* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) -* Made each rewind on each call allowing for re-using the cursor. -* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. -* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. - -2.0.3 2014-10-14 ----------------- -* NODE-297 Aggregate Broken for case of pipeline with no options. - -2.0.2 2014-10-08 ----------------- -* Bumped mongodb-core to 1.0.2. -* Fixed bson module dependency issue by relying on the mongodb-core one. -* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) - -2.0.1 2014-10-07 ----------------- -* Dependency fix - -2.0.0 2014-10-07 ----------------- -* First release of 2.0 driver - -2.0.0-alpha2 2014-10-02 ------------------------ -* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) -* Cluster Management Spec compatible. - -2.0.0-alpha1 2014-09-08 ------------------------ -* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode -* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package -* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node -* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) - * Might break some application -* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove -* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) -* Removed Grid class -* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data - + seek will fail if attempt to use with w or w+ - + write will fail if attempted with w+ or r - + w+ only works for updating metadata on a file -* Cursor toArray and each resets and re-runs the cursor -* FindAndModify returns whole result document instead of just value -* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find -* Removed db.dereference method -* Removed db.cursorInfo method -* Removed db.stats method -* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections -* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. -* Added db.listCollections to replace several methods above - -1.4.10 2014-09-04 ------------------ -* Fixed BSON and Kerberos compilation issues -* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series -* Fixed Kerberos and bumped to 0.0.4 - -1.4.9 2014-08-26 ----------------- -* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) -* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) -* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) -* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) -* NODE-240 Operations on SSL connection hang on node 0.11.x -* NODE-235 writeResult is not being passed on when error occurs in insert -* NODE-229 Allow count to work with query hints -* NODE-233 collection.save() does not support fullResult -* NODE-244 Should parseError also emit a `disconnected` event? -* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. -* NODE-248 Crash with X509 auth -* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks -* Bumped BSON parser to 0.2.12 - - -1.4.8 2014-08-01 ----------------- -* NODE-205 correctly emit authenticate event -* NODE-210 ensure no undefined connection error when checking server state -* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones -* NODE-220 don't throw error if ensureIndex errors out in Gridstore -* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes -* Fixed test running filters -* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) -* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) -* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) -* Fixed parsing issue for w:0 in url parser when in connection string -* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) - -1.4.7 2014-06-18 ----------------- -* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) -* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) - -1.4.6 2014-06-12 ----------------- -* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) -* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) -* Added missing type check before calling optional callback function (Issue #1180) - -1.4.5 2014-05-21 ----------------- -* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. -* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. -* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) - -1.4.4 2014-05-13 ----------------- -* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID -* Removed leaking global variable (Issue #1174, https://github.com/dainis) -* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) -* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) - -1.4.3 2014-05-01 ----------------- -* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) -* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) -* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) -* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) -* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) -* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) - -1.4.2 2014-04-15 ----------------- -* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 -* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) -* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) -* Fixed global variable leak (Issue #1160, https://github.com/vaseker) - -1.4.1 2014-04-09 ----------------- -* Correctly emit joined event when primary change -* Add _id to documents correctly when using bulk operations - -1.4.0 2014-04-03 ----------------- -* All node exceptions will no longer be caught if on('error') is defined -* Added X509 auth support -* Fix for MongoClient connection timeout issue (NODE-97) -* Pass through error messages from parseError instead of just text (Issue #1125) -* Close db connection on error (Issue #1128, https://github.com/benighted) -* Fixed documentation generation -* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) -* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 -* Insert/Update/Remove using new write commands when available -* Added support for new roles based API's in 2.6 for addUser/removeUser -* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries -* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes -* Support for OP_LOG_REPLAY flag (NODE-94) -* Fixes for SSL HA ping and discovery. -* Uses createIndexes if available for ensureIndex/createIndex -* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors -* Made CommandCursor behave as Readable stream. -* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. -* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. -* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) -* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. -* Refactored commands to all go through command function ensuring consistent command execution. -* Fixed issues where readPreferences where not correctly passed to mongos. -* Catch error == null and make err detection more prominent (NODE-130) -* Allow reads from arbiter for single server connection (NODE-117) -* Handle error coming back with no documents (NODE-130) -* Correctly use close parameter in Gridstore.write() (NODE-125) -* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) -* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) -* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) -* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) -* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) -* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) -* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) -* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) -* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) -* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) -* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) - -1.3.19 2013-08-21 ------------------ -* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. -* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) -* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) - -1.3.18 2013-08-10 ------------------ -* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) -* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. - -1.3.17 2013-08-07 ------------------ -* Ignore return commands that have no registered callback -* Made collection.count not use the db.command function -* Fix throw exception on ping command (Issue #1055) - -1.3.16 2013-08-02 ------------------ -* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) -* Bug in unlink mulit filename (Issue #1054) - -1.3.15 2013-08-01 ------------------ -* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time - -1.3.14 2013-08-01 ------------------ -* Fixed issue with checkKeys where it would error on X.X - -1.3.13 2013-07-31 ------------------ -* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) -* BSON size checking now done pre serialization (Issue #1037) -* Added isConnected returns false when no connection Pool exists (Issue #1043) -* Unified command handling to ensure same handling (Issue #1041, #1042) -* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) -* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. -* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. -* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. -* Fixed issue with Kerberos authentication on Windows for re-authentication. -* Fixed Mongos failover behavior to correctly throw out old servers. -* Ensure stored queries/write ops are executed correctly after connection timeout -* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. - -1.3.12 2013-07-19 ------------------ -* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) -* Fixed bug with callback third parameter on some commands (Issue #1033) -* Fixed possible issue where killcursor command might leave hanging functions -* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers -* Throw error if dbName or collection name contains null character (at command level and at collection level) -* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) - -1.3.11 2013-07-04 ------------------ -* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) -* Add driver version to export (Issue #1021, https://github.com/aheckmann) -* Add text to readpreference obedient commands (Issue #1019) -* Drivers should check the query failure bit even on getmore response (Issue #1018) -* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) -* Support SASL PLAIN authentication (Issue #1009) -* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) -* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) -* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) - -1.3.10 2013-06-17 ------------------ -* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) -* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) -* Introduced write and read concerns for GridFS (Issue #996) -* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) -* Fixed issue with pool size on replicaset connections (Issue #1000) -* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) - -1.3.9 2013-06-05 ----------------- -* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. - -1.3.8 2013-05-31 ----------------- -* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) -* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) -* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. - -1.3.7 2013-05-29 ----------------- -* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) -* Updated Bson to 0.1.9 to fix ARM support (Issue #985) - -1.3.6 2013-05-21 ----------------- -* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) -* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) - -1.3.5 2013-05-14 ----------------- -* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. - -1.3.4 2013-05-14 ----------------- -* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) -* Fixed bug when passing a named index hint (Issue #974) - -1.3.3 2013-05-09 ----------------- -* Fixed auto-reconnect issue with single server instance. - -1.3.2 2013-05-08 ----------------- -* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. - -1.3.1 2013-05-06 ----------------- -* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly -* Applied auth before server instance is set as connected when single server connection -* Throw error if array of documents passed to save method - -1.3.0 2013-04-25 ----------------- -* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. -* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) -* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) -* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) -* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition -* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) - -1.2.14 2013-03-14 ------------------ -* Refactored test suite to speed up running of replicaset tests -* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) -* Corrected a slaveOk setting issue (Issue #906, #905) -* Fixed HA issue where ping's would not go to correct server on HA server connection failure. -* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream -* Fixed race condition in Cursor stream (NODE-31) -* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 -* Added support for maxMessageSizeBytes if available (DRIVERS-1) -* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) -* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) - -1.2.13 2013-02-22 ------------------ -* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) -* Fixed missing MongoErrors on some cursor methods (Issue #882) -* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) -* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) -* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) - -1.2.12 2013-02-13 ------------------ -* Added limit/skip options to Collection.count (Issue #870) -* Added applySkipLimit option to Cursor.count (Issue #870) -* Enabled ping strategy as default for Replicaset if none specified (Issue #876) -* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) - -1.2.11 2013-01-29 ------------------ -* Added fixes for handling type 2 binary due to PHP driver (Issue #864) -* Moved callBackStore to Base class to have single unified store (Issue #866) -* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead - -1.2.10 2013-01-25 ------------------ -* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. -* Only open a new HA socket when previous one dead (Issue #859, #857) -* Minor fixes - -1.2.9 2013-01-15 ----------------- -* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) -* Connection string with no db specified should default to admin db (Issue #848) -* Support port passed as string to Server class (Issue #844) -* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) -* Included toError wrapper code moved to utils.js file (Issue #839, #840) -* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% - -1.2.8 2013-01-07 ----------------- -* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) -* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) -* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) -* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) -* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) -* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) -* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) -* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) - -1.2.7 2012-12-23 ----------------- -* Rolled back batches as they hang in certain situations -* Fixes for NODE-25, keep reading from secondaries when primary goes down - -1.2.6 2012-12-21 ----------------- -* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) -* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) -* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) -* Cursor readPreference bug for non-supported read preferences (Issue #817) - -1.2.5 2012-12-12 ----------------- -* Fixed ssl regression, added more test coverage (Issue #800) -* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) - -1.2.4 2012-12-11 ----------------- -* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. - -1.2.3 2012-12-10 ----------------- -* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) -* Fixed seek issue in gridstore when using stream (Issue #790) - -1.2.2 2012-12-03 ----------------- -* Fix for journal write concern not correctly being passed under some circumstances. -* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). - -1.2.1 2012-11-30 ----------------- -* Fix for double callback on insert with w:0 specified (Issue #783) -* Small cleanup of urlparser. - -1.2.0 2012-11-27 ----------------- -* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) -* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) -* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) -* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) -* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) -* Force correct setting of read_secondary based on the read preference (Issue #741) -* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) -* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type -* Mongos connection with auth not working (Issue #737) -* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") -* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db - * open/close/db/connect methods implemented -* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. -* Fixed a bug with aggregation helper not properly accepting readPreference - -1.1.11 2012-10-10 ------------------ -* Removed strict mode and introduced normal handling of safe at DB level. - -1.1.10 2012-10-08 ------------------ -* fix Admin.serverStatus (Issue #723, https://github.com/Contra) -* logging on connection open/close(Issue #721, https://github.com/asiletto) -* more fixes for windows bson install (Issue #724) - -1.1.9 2012-10-05 ----------------- -* Updated bson to 0.1.5 to fix build problem on sunos/windows. - -1.1.8 2012-10-01 ----------------- -* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) -* Cleanup of non-closing connections (Issue #706) -* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) -* Set keepalive on as default, override if not needed -* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) -* Added domain socket support new Server("/tmp/mongodb.sock") style - -1.1.7 2012-09-10 ----------------- -* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) -* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) -* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) -* Proper stopping of strategy on replicaset stop -* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) -* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) - -1.1.6 2012-09-01 ----------------- -* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) -* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) - -1.1.5 2012-08-29 ----------------- -* Fix for eval on replicaset Issue #684 -* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) -* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) -* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X -* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes -* Added exhaust option for find for feature completion (not recommended for normal use) -* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval -* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) - -1.1.4 2012-08-12 ----------------- -* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. -* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. -* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). -* Fix gridfs readstream (Issue #607, https://github.com/tedeh). -* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). -* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). -* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). -* Cleanup map reduce (Issue #614, https://github.com/aheckmann). -* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). -* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. -* Date identification handled correctly in bson js parser when running in vm context. -* Documentation updates -* GridStore filename not set on read (Issue #621) -* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls -* Added support for awaitdata for tailable cursors (Issue #624) -* Implementing read preference setting at collection and cursor level - * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) - * db.collection("some", {readPreference:Server.SECONDARY}) -* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. - * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to -* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) -* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 -* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) -* Fixed auth to work better when multiple connections are involved. -* Default connection pool size increased to 5 connections. -* Fixes for the ReadStream class to work properly with 0.8 of Node.js -* Added explain function support to aggregation helper -* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js -* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required -* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) -* Fixed Always emit db events (Issue #657) -* Close event not correctly resets DB openCalled variable to allow reconnect -* Added open event on connection established for replicaset, mongos and server -* Much faster BSON C++ parser thanks to Lucasfilm Singapore. -* Refactoring of replicaset connection logic to simplify the code. -* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) -* Minor optimization for findAndModify when not using j,w or fsync for safe - -1.0.2 2012-05-15 ----------------- -* Reconnect functionality for replicaset fix for mongodb 2.0.5 - -1.0.1 2012-05-12 ----------------- -* Passing back getLastError object as 3rd parameter on findAndModify command. -* Fixed a bunch of performance regressions in objectId and cursor. -* Fixed issue #600 allowing for single document delete to be passed in remove command. - -1.0.0 2012-04-25 ----------------- -* Fixes to handling of failover on server error -* Only emits error messages if there are error listeners to avoid uncaught events -* Server.isConnected using the server state variable not the connection pool state - -0.9.9.8 2012-04-12 ------------------- -* _id=0 is being turned into an ObjectID (Issue #551) -* fix for error in GridStore write method (Issue #559) -* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) -* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) -* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) -* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) -* Connection pools handles closing themselves down and clearing the state -* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) -* Returning update status document at the end of the callback for updates, (Issue #569) -* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) - -0.9.9.7 2012-03-16 ------------------- -* Stats not returned from map reduce with inline results (Issue #542) -* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) -* Streaming large files from GridFS causes truncation (Issue #540) -* Make callback type checks agnostic to V8 context boundaries (Issue #545) -* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback -* Db.open throws if the application attemps to call open again without calling close first - -0.9.9.6 2012-03-12 ------------------- -* BSON parser is externalized in it's own repository, currently using git master -* Fixes for Replicaset connectivity issue (Issue #537) -* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) -* Removed SimpleEmitter and replaced with standard EventEmitter -* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) - -0.9.9.5 2012-03-07 ------------------- -* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) -* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) -* Fixed memory leak in C++ bson parser (Issue #526) -* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) -* Cannot save files with the same file name to GridFS (Issue #531) - -0.9.9.4 2012-02-26 ------------------- -* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) - -0.9.9.3 2012-02-23 ------------------- -* document: save callback arguments are both undefined, (Issue #518) -* Native BSON parser install error with npm, (Issue #517) - -0.9.9.2 2012-02-17 ------------------- -* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. -* Added wrap error around db.dropDatabase to catch all errors (Issue #512) -* Added aggregate helper to collection, only for MongoDB >= 2.1 - -0.9.9.1 2012-02-15 ------------------- -* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. -* Mapreduce now throws error if out parameter is not specified. - -0.9.9 2012-02-13 ----------------- -* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. -* Db.close(true) now makes connection unusable as it's been force closed by app. -* Fixed mapReduce and group functions to correctly send slaveOk on queries. -* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). -* A fix for connection error handling when using the SSL on MongoDB. - -0.9.8-7 2012-02-06 ------------------- -* Simplified findOne to use the find command instead of the custom code (Issue #498). -* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). - -0.9.8-6 2012-02-04 ------------------- -* Removed the check for replicaset change code as it will never work with node.js. - -0.9.8-5 2012-02-02 ------------------- -* Added geoNear command to Collection. -* Added geoHaystackSearch command to Collection. -* Added indexes command to collection to retrieve the indexes on a Collection. -* Added stats command to collection to retrieve the statistics on a Collection. -* Added listDatabases command to admin object to allow retrieval of all available dbs. -* Changed createCreateIndexCommand to work better with options. -* Fixed dereference method on Db class to correctly dereference Db reference objects. -* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. -* Removed writeBuffer method from gridstore, write handles switching automatically now. -* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. -* Moved Long class to bson directory. - -0.9.8-4 2012-01-28 ------------------- -* Added reIndex command to collection and db level. -* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. -* Added dropDups and v option to createIndex and ensureIndex. -* Added isCapped method to Collection. -* Added indexExists method to Collection. -* Added findAndRemove method to Collection. -* Fixed bug for replicaset connection when no active servers in the set. -* Fixed bug for replicaset connections when errors occur during connection. -* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. - -0.9.8-3 2012-01-21 ------------------- -* Workaround for issue with Object.defineProperty (Issue #484) -* ObjectID generation with date does not set rest of fields to zero (Issue #482) - -0.9.8-2 2012-01-20 ------------------- -* Fixed a missing this in the ReplSetServers constructor. - -0.9.8-1 2012-01-17 ------------------- -* FindAndModify bug fix for duplicate errors (Issue #481) - -0.9.8 2012-01-17 ----------------- -* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. - * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) -* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh -* Removed duplicate code for formattedOrderClause and moved to utils module -* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members -* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations -* Correct handling of illegal BSON messages during deserialization -* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) -* Correctly update existing user password when using addUser (Issue #470) - -0.9.7.3-5 2012-01-04 --------------------- -* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' -* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors - -0.9.7.3-4 2012-01-04 --------------------- -* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) -* Sanity checks for GridFS performance with benchmark added - -0.9.7.3-3 2012-01-04 --------------------- -* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux -* BSON bug fixes for performance - -0.9.7.3-2 2012-01-02 --------------------- -* Fixed up documentation to reflect the preferred way of instantiating bson types -* GC bug fix for JS bson parser to avoid stop-and-go GC collection - -0.9.7.3-1 2012-01-02 --------------------- -* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously - -0.9.7.3 2011-12-30 --------------------- -* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes -* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) -* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 -* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) -* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) - -0.9.7.2-5 2011-12-22 --------------------- -* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann - -0.9.7.2-4 2011-12-21 --------------------- -* Refactoring of callback code to work around performance regression on linux -* Fixed group function to correctly use the command mode as default - -0.9.7.2-3 2011-12-18 --------------------- -* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). -* Allow for force send query to primary, pass option (read:'primary') on find command. - * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` - -0.9.7.2-2 2011-12-16 --------------------- -* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) - -0.9.7.2-1 2011-12-16 --------------------- -* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) -* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver -* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents - -0.9.7.2 2011-12-15 ------------------- -* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) - * pass in the ssl:true option to the server or replicaset server config to enable - * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). -* Added getTimestamp() method to objectID that returns a date object -* Added finalize function to collection.group - * function group (keys, condition, initial, reduce, finalize, command, callback) -* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. - * reaperInterval, set interval for reaper (default 10000 miliseconds) - * reaperTimeout, set timeout for calls (default 30000 miliseconds) - * reaper, enable/disable reaper (default false) -* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb -* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close -* EnsureIndex command can be executed without a callback (Issue #438) -* Eval function no accepts options including nolock (Issue #432) - * eval(code, parameters, options, callback) (where options = {nolock:true}) - -0.9.7.1-4 2011-11-27 --------------------- -* Replaced install.sh with install.js to install correctly on all supported os's - -0.9.7.1-3 2011-11-27 --------------------- -* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch - -0.9.7.1-2 2011-11-27 --------------------- -* Set statistical selection strategy as default for secondary choice. - -0.9.7.1-1 2011-11-27 --------------------- -* Better handling of single server reconnect (fixes some bugs) -* Better test coverage of single server failure -* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect - -0.9.7.1 2011-11-24 ------------------- -* Better handling of dead server for single server instances -* FindOne and find treats selector == null as {}, Issue #403 -* Possible to pass in a strategy for the replicaset to pick secondary reader node - * parameter strategy - * ping (default), pings the servers and picks the one with the lowest ping time - * statistical, measures each request and pick the one with the lowest mean and std deviation -* Set replicaset read preference replicaset.setReadPreference() - * Server.READ_PRIMARY (use primary server for reads) - * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) - * tags, {object of tags} -* Added replay of commands issued to a closed connection when the connection is re-established -* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) -* Moved reaper to db.open instead of constructor (Issue #406) -* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions - * timeout = set seconds before connection times out (default 0) - * noDelay = Disables the Nagle algorithm (default true) - * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) - * encoding = ['ascii', 'utf8', or 'base64'] (default null) -* Fixes for handling of errors during shutdown off a socket connection -* Correctly applies socket options including timeout -* Cleanup of test management code to close connections correctly -* Handle parser errors better, closing down the connection and emitting an error -* Correctly emit errors from server.js only wrapping errors that are strings - -0.9.7 2011-11-10 ----------------- -* Added priority setting to replicaset manager -* Added correct handling of passive servers in replicaset -* Reworked socket code for simpler clearer handling -* Correct handling of connections in test helpers -* Added control of retries on failure - * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance -* Added reaper that will timeout and cleanup queries that never return - * control with parameters reaperInterval and reaperTimeout when creating a db instance -* Refactored test helper classes for replicaset tests -* Allows raw (no bson parser mode for insert, update, remove, find and findOne) - * control raw mode passing in option raw:true on the commands - * will return buffers with the binary bson objects -* Fixed memory leak in cursor.toArray -* Fixed bug in command creation for mongodb server with wrong scope of call -* Added db(dbName) method to db.js to allow for reuse of connections against other databases -* Serialization of functions in an object is off by default, override with parameter - * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify -* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) -* FindOne and find now share same code execution and will work in the same manner, Issue #399 -* Fix for tailable cursors, Issue #384 -* Fix for Cursor rewind broken, Issue #389 -* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) -* Updated documentation on https://github.com/christkv/node-mongodb-native -* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data - -0.9.6-22 2011-10-15 -------------------- -* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 -* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 - -0.9.6-21 2011-10-05 -------------------- -* Reworked reconnect code to work correctly -* Handling errors in different parts of the code to ensure that it does not lock the connection -* Consistent error handling for Object.createFromHexString for JS and C++ - -0.9.6-20 2011-10-04 -------------------- -* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc -* Reworked bson.cc to throw error when trying to serialize js bson types -* Added MinKey, MaxKey and Double support for JS and C++ parser -* Reworked socket handling code to emit errors on unparsable messages -* Added logger option for Db class, lets you pass in a function in the shape - { - log : function(message, object) {}, - error : function(errorMessage, errorObject) {}, - debug : function(debugMessage, object) {}, - } - - Usage is new Db(new Server(..), {logger: loggerInstance}) - -0.9.6-19 2011-09-29 -------------------- -* Fixing compatibility issues between C++ bson parser and js parser -* Added Symbol support to C++ parser -* Fixed socket handling bug for seldom misaligned message from mongodb -* Correctly handles serialization of functions using the C++ bson parser - -0.9.6-18 2011-09-22 -------------------- -* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 - -0.9.6-17 2011-09-21 -------------------- -* Fixed broken exception test causing bamboo to hang -* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 - -0.9.6-16 2011-09-14 -------------------- -* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. -* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 - -0.9.6-15 2011-09-09 -------------------- -* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 -* Fixed authentication issue with secondary servers in Replicaset, Issue #334 -* Duplicate replica-set servers when omitting port, Issue #341 -* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 -* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks - -0.9.6-14 2011-09-05 -------------------- -* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 -* Minor doc fixes -* Some more cursor sort tests added, Issue #333 -* Fixes to work with 0.5.X branch -* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 -* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 -* Implement correct safe/strict mode for findAndModify. - -0.9.6-13 2011-08-24 -------------------- -* Db names correctly error checked for illegal characters - -0.9.6-12 2011-08-24 -------------------- -* Nasty bug in GridFS if you changed the default chunk size -* Fixed error handling bug in findOne - -0.9.6-11 2011-08-23 -------------------- -* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) -* Fixes for memory leaks when using buffers and C++ parser -* Fixes to make tests pass on 0.5.X -* Cleanup of bson.js to remove duplicated code paths -* Fix for errors occurring in ensureIndex, Issue #326 -* Removing require.paths to make tests work with the 0.5.X branch - -0.9.6-10 2011-08-11 -------------------- -* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 -* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 -* Implementing fixes for mongodb 1.9.1 and higher to make tests pass -* Admin validateCollection now takes an options argument for you to pass in full option -* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 -* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 - -0.9.6-9 -------- -* Bug fix for bson parsing the key '':'' correctly without crashing - -0.9.6-8 -------- -* Changed to using node.js crypto library MD5 digest -* Connect method support documented mongodb: syntax by (https://github.com/sethml) -* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 -* Code object without scope serializing to correct BSON type -* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 -* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) -* Fixed C++ parser to reflect JS parser handling of long deserialization -* Bson small optimizations - -0.9.6-7 2011-07-13 ------------------- -* JS Bson deserialization bug #287 - -0.9.6-6 2011-07-12 ------------------- -* FindAndModify not returning error message as other methods Issue #277 -* Added test coverage for $push, $pushAll and $inc atomic operations -* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 -* Fixed terrible deserialization bug in js bson code #285 -* Fix by andrewjstone to avoid throwing errors when this.primary not defined - -0.9.6-5 2011-07-06 ------------------- -* Rewritten BSON js parser now faster than the C parser on my core2duo laptop -* Added option full to indexInformation to get all index info Issue #265 -* Passing in ObjectID for new Gridstore works correctly Issue #272 - -0.9.6-4 2011-07-01 ------------------- -* Added test and bug fix for insert/update/remove without callback supplied - -0.9.6-3 2011-07-01 ------------------- -* Added simple grid class called Grid with put, get, delete methods -* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly -* Automatic handling of buffers when using write method on GridStore -* GridStore now accepts a ObjectID instead of file name for write and read methods -* GridStore.list accepts id option to return of file ids instead of filenames -* GridStore close method returns document for the file allowing user to reference _id field - -0.9.6-2 2011-06-30 ------------------- -* Fixes for reconnect logic for server object (replays auth correctly) -* More testcases for auth -* Fixes in error handling for replicaset -* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout -* Fixed slaveOk bug for findOne method -* Implemented auth support for replicaset and test cases -* Fixed error when not passing in rs_name - -0.9.6-1 2011-06-25 ------------------- -* Fixes for test to run properly using c++ bson parser -* Fixes for dbref in native parser (correctly handles ref without db component) -* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) -* Fixes for timestamp in js bson parser (distinct timestamp type now) - -0.9.6 2011-06-21 ----------------- -* Worked around npm version handling bug -* Race condition fix for cygwin (https://github.com/vincentcr) - -0.9.5-1 2011-06-21 ------------------- -* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems -* Fixed driver strict mode issue - -0.9.5 2011-06-20 ----------------- -* Replicaset support (failover and reading from secondary servers) -* Removed ServerPair and ServerCluster -* Added connection pool functionality -* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences -* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} - -0.6.8 ------ -* Removed multiple message concept from bson -* Changed db.open(db) to be db.open(err, db) - -0.1 2010-01-30 --------------- -* Initial release support of driver using native node.js interface -* Supports gridfs specification -* Supports admin functionality diff --git a/node_modules/mongodb/LICENSE.md b/node_modules/mongodb/LICENSE.md deleted file mode 100644 index ad410e1..0000000 --- a/node_modules/mongodb/LICENSE.md +++ /dev/null @@ -1,201 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/node_modules/mongodb/README.md b/node_modules/mongodb/README.md deleted file mode 100644 index 00d31d8..0000000 --- a/node_modules/mongodb/README.md +++ /dev/null @@ -1,499 +0,0 @@ -[![npm](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![npm](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) - -[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.svg?branch=2.1)](http://travis-ci.org/mongodb/node-mongodb-native) -[![Coverage Status](https://coveralls.io/repos/github/mongodb/node-mongodb-native/badge.svg?branch=2.1)](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1) -[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -# Description - -The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users. - -**NOTE: v3.x was recently released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).** - -## MongoDB Node.JS Driver - -| what | where | -|---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native | -| api-doc | http://mongodb.github.io/node-mongodb-native/3.1/api | -| source | https://github.com/mongodb/node-mongodb-native | -| mongodb | http://www.mongodb.org | - -### Bugs / Feature Requests - -Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a -case in our issue management tool, JIRA: - -- Create an account and login [jira.mongodb.org](https://jira.mongodb.org). -- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE). -- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. - -Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the -Core Server (i.e. SERVER) project are **public**. - -### Support / Feedback - -For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](https://docs.mongodb.com/manual/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [MongoDB Community Forums](https://community.mongodb.com/tags/c/drivers-odms-connectors/7/node-js-driver). - -### Change Log - -Change history can be found in [`HISTORY.md`](HISTORY.md). - -### Compatibility - -For version compatibility matrices, please refer to the following links: - - * [MongoDB](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-mongodb-node) - * [NodeJS](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-language-node) - -# Installation - -The recommended way to get started using the Node.js 3.0 driver is by using the `npm` (Node Package Manager) to install the dependency in your project. - -## MongoDB Driver - -Given that you have created your own project using `npm init` we install the MongoDB driver and its dependencies by executing the following `npm` command. - -```bash -npm install mongodb --save -``` - -This will download the MongoDB driver and add a dependency entry in your `package.json` file. - -You can also use the [Yarn](https://yarnpkg.com/en) package manager. - -## Troubleshooting - -The MongoDB driver depends on several other packages. These are: - -* [mongodb-core](https://github.com/mongodb-js/mongodb-core) -* [bson](https://github.com/mongodb/js-bson) -* [kerberos](https://github.com/mongodb-js/kerberos) -* [node-gyp](https://github.com/nodejs/node-gyp) - -The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the `kerberos` module. Furthermore, the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install. - -**Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.** - -### Diagnosing on UNIX - -If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps. - -```bash -git clone https://github.com/mongodb-js/kerberos -cd kerberos -npm install -``` - -If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install `node-gyp` globally: - -```bash -npm install -g node-gyp -``` - -If it correctly compiles and runs the tests you are golden. We can now try to install the `mongod` driver by performing the following command. - -```bash -cd yourproject -npm install mongodb --save -``` - -If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. - -```bash -npm --loglevel verbose install mongodb -``` - -This will print out all the steps npm is performing while trying to install the module. - -### Diagnosing on Windows - -A compiler tool chain known to work for compiling `kerberos` on Windows is the following. - -* Visual Studio C++ 2010 (do not use higher versions) -* Windows 7 64bit SDK -* Python 2.7 or higher - -Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`. - -```bash -npm install -g node-gyp -``` - -Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild: - -```bash -git clone https://github.com/christkv/kerberos.git -cd kerberos -npm install -node-gyp rebuild -``` - -This should rebuild the driver successfully if you have everything set up correctly. - -### Other possible issues - -Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there). - -Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed. - -## Quick Start - -This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [tutorials](docs/reference/content/tutorials/main.md). - -### Create the `package.json` file - -First, create a directory where your application will live. - -```bash -mkdir myproject -cd myproject -``` - -Enter the following command and answer the questions to create the initial structure for your new project: - -```bash -npm init -``` - -Next, install the driver dependency. - -```bash -npm install mongodb --save -``` - -You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. - -### Start a MongoDB Server - -For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). - -1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads) -2. Create a database directory (in this case under **/data**). -3. Install and start a ``mongod`` process. - -```bash -mongod --dbpath=/data -``` - -You should see the **mongod** process start up and print some status information. - -### Connect to MongoDB - -Create a new **app.js** file and add the following code to try out some basic CRUD -operations using the MongoDB driver. - -Add code to connect to the server and the database **myproject**: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - client.close(); -}); -``` - -Run your app from the command line with: - -```bash -node app.js -``` - -The application should print **Connected successfully to server** to the console. - -### Insert a Document - -Add to **app.js** the following function which uses the **insertMany** -method to add three documents to the **documents** collection. - -```js -const insertDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Insert some documents - collection.insertMany([ - {a : 1}, {a : 2}, {a : 3} - ], function(err, result) { - assert.equal(err, null); - assert.equal(3, result.result.n); - assert.equal(3, result.ops.length); - console.log("Inserted 3 documents into the collection"); - callback(result); - }); -} -``` - -The **insert** command returns an object with the following fields: - -* **result** Contains the result document from MongoDB -* **ops** Contains the documents inserted with added **_id** fields -* **connection** Contains the connection used to perform the insert - -Add the following code to call the **insertDocuments** function: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - client.close(); - }); -}); -``` - -Run the updated **app.js** file: - -```bash -node app.js -``` - -The operation returns the following output: - -```bash -Connected successfully to server -Inserted 3 documents into the collection -``` - -### Find All Documents - -Add a query that returns all the documents. - -```js -const findDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Find some documents - collection.find({}).toArray(function(err, docs) { - assert.equal(err, null); - console.log("Found the following records"); - console.log(docs) - callback(docs); - }); -} -``` - -This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - findDocuments(db, function() { - client.close(); - }); - }); -}); -``` - -### Find Documents with a Query Filter - -Add a query filter to find only documents which meet the query criteria. - -```js -const findDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Find some documents - collection.find({'a': 3}).toArray(function(err, docs) { - assert.equal(err, null); - console.log("Found the following records"); - console.log(docs); - callback(docs); - }); -} -``` - -Only the documents which match ``'a' : 3`` should be returned. - -### Update a document - -The following operation updates a document in the **documents** collection. - -```js -const updateDocument = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Update document where a is 2, set b equal to 1 - collection.updateOne({ a : 2 } - , { $set: { b : 1 } }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Updated the document with the field a equal to 2"); - callback(result); - }); -} -``` - -The method updates the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Next, update the callback function from **MongoClient.connect** to include the update method. - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - updateDocument(db, function() { - client.close(); - }); - }); -}); -``` - -### Remove a document - -Remove the document where the field **a** is equal to **3**. - -```js -const removeDocument = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Delete document where a is 3 - collection.deleteOne({ a : 3 }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Removed the document with the field a equal to 3"); - callback(result); - }); -} -``` - -Add the new method to the **MongoClient.connect** callback function. - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - updateDocument(db, function() { - removeDocument(db, function() { - client.close(); - }); - }); - }); -}); -``` - -### Index a Collection - -[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's -performance. The following function creates an index on the **a** field in the -**documents** collection. - -```js -const indexCollection = function(db, callback) { - db.collection('documents').createIndex( - { "a": 1 }, - null, - function(err, results) { - console.log(results); - callback(); - } - ); -}; -``` - -Add the ``indexCollection`` method to your app: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - indexCollection(db, function() { - client.close(); - }); - }); -}); -``` - -For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md). - -## Next Steps - - * [MongoDB Documentation](http://mongodb.org) - * [Read about Schemas](http://learnmongodbthehardway.com) - * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) - -## License - -[Apache 2.0](LICENSE.md) - -© 2009-2012 Christian Amor Kvalheim -© 2012-present MongoDB [Contributors](CONTRIBUTORS.md) diff --git a/node_modules/mongodb/index.js b/node_modules/mongodb/index.js deleted file mode 100644 index 4e9e635..0000000 --- a/node_modules/mongodb/index.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict'; - -// Core module -const core = require('./lib/core'); -const Instrumentation = require('./lib/apm'); - -// Set up the connect function -const connect = require('./lib/mongo_client').connect; - -// Expose error class -connect.MongoError = core.MongoError; -connect.MongoNetworkError = core.MongoNetworkError; -connect.MongoTimeoutError = core.MongoTimeoutError; -connect.MongoServerSelectionError = core.MongoServerSelectionError; -connect.MongoParseError = core.MongoParseError; -connect.MongoWriteConcernError = core.MongoWriteConcernError; -connect.MongoBulkWriteError = require('./lib/bulk/common').BulkWriteError; -connect.BulkWriteError = connect.MongoBulkWriteError; - -// Actual driver classes exported -connect.Admin = require('./lib/admin'); -connect.MongoClient = require('./lib/mongo_client'); -connect.Db = require('./lib/db'); -connect.Collection = require('./lib/collection'); -connect.Server = require('./lib/topologies/server'); -connect.ReplSet = require('./lib/topologies/replset'); -connect.Mongos = require('./lib/topologies/mongos'); -connect.ReadPreference = core.ReadPreference; -connect.GridStore = require('./lib/gridfs/grid_store'); -connect.Chunk = require('./lib/gridfs/chunk'); -connect.Logger = core.Logger; -connect.AggregationCursor = require('./lib/aggregation_cursor'); -connect.CommandCursor = require('./lib/command_cursor'); -connect.Cursor = require('./lib/cursor'); -connect.GridFSBucket = require('./lib/gridfs-stream'); -// Exported to be used in tests not to be used anywhere else -connect.CoreServer = core.Server; -connect.CoreConnection = core.Connection; - -// BSON types exported -connect.Binary = core.BSON.Binary; -connect.Code = core.BSON.Code; -connect.Map = core.BSON.Map; -connect.DBRef = core.BSON.DBRef; -connect.Double = core.BSON.Double; -connect.Int32 = core.BSON.Int32; -connect.Long = core.BSON.Long; -connect.MinKey = core.BSON.MinKey; -connect.MaxKey = core.BSON.MaxKey; -connect.ObjectID = core.BSON.ObjectID; -connect.ObjectId = core.BSON.ObjectID; -connect.Symbol = core.BSON.Symbol; -connect.Timestamp = core.BSON.Timestamp; -connect.BSONRegExp = core.BSON.BSONRegExp; -connect.Decimal128 = core.BSON.Decimal128; - -// Add connect method -connect.connect = connect; - -// Set up the instrumentation method -connect.instrument = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - const instrumentation = new Instrumentation(); - instrumentation.instrument(connect.MongoClient, callback); - return instrumentation; -}; - -// Set our exports to be the connect function -module.exports = connect; diff --git a/node_modules/mongodb/lib/admin.js b/node_modules/mongodb/lib/admin.js deleted file mode 100644 index 716844b..0000000 --- a/node_modules/mongodb/lib/admin.js +++ /dev/null @@ -1,293 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('./utils').applyWriteConcern; - -const AddUserOperation = require('./operations/add_user'); -const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); -const RemoveUserOperation = require('./operations/remove_user'); -const ValidateCollectionOperation = require('./operations/validate_collection'); -const ListDatabasesOperation = require('./operations/list_databases'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Admin** class is an internal class that allows convenient access to - * the admin functionality and commands for MongoDB. - * - * **ADMIN Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Use the admin database for the operation - * const adminDb = client.db(dbName).admin(); - * - * // List all the available databases - * adminDb.listDatabases(function(err, dbs) { - * test.equal(null, err); - * test.ok(dbs.databases.length > 0); - * client.close(); - * }); - * }); - */ - -/** - * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {Admin} a collection instance. - */ -function Admin(db, topology, promiseLibrary) { - if (!(this instanceof Admin)) return new Admin(db, topology); - - // Internal state - this.s = { - db: db, - topology: topology, - promiseLibrary: promiseLibrary - }; -} - -/** - * The callback format for results - * @callback Admin~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.command = function(command, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : {}; - - const commandOperation = new ExecuteDbAdminCommandOperation(this.s.db, command, options); - - return executeOperation(this.s.db.s.topology, commandOperation, callback); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.buildInfo = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { buildinfo: 1 }; - - const buildInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, buildInfoOperation, callback); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverInfo = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { buildinfo: 1 }; - - const serverInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, serverInfoOperation, callback); -}; - -/** - * Retrieve this db's server status. - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverStatus = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const serverStatusOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - { serverStatus: 1 }, - options - ); - - return executeOperation(this.s.db.s.topology, serverStatusOperation, callback); -}; - -/** - * Ping the MongoDB server and retrieve results - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.ping = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { ping: 1 }; - - const pingOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, pingOperation, callback); -}; - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.addUser = function(username, password, options, callback) { - const args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - // Special case where there is no password ($external users) - if (typeof username === 'string' && password != null && typeof password === 'object') { - options = password; - password = null; - } - - options = args.length ? args.shift() : {}; - options = Object.assign({}, options); - // Get the options - options = applyWriteConcern(options, { db: this.s.db }); - // Set the db name to admin - options.dbName = 'admin'; - - const addUserOperation = new AddUserOperation(this.s.db, username, password, options); - - return executeOperation(this.s.db.s.topology, addUserOperation, callback); -}; - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.removeUser = function(username, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - options = args.length ? args.shift() : {}; - options = Object.assign({}, options); - // Get the options - options = applyWriteConcern(options, { db: this.s.db }); - // Set the db name - options.dbName = 'admin'; - - const removeUserOperation = new RemoveUserOperation(this.s.db, username, options); - - return executeOperation(this.s.db.s.topology, removeUserOperation, callback); -}; - -/** - * Validate an existing collection - * - * @param {string} collectionName The name of the collection to validate. - * @param {object} [options] Optional settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.validateCollection = function(collectionName, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const validateCollectionOperation = new ValidateCollectionOperation( - this, - collectionName, - options - ); - - return executeOperation(this.s.db.s.topology, validateCollectionOperation, callback); -}; - -/** - * List the available databases - * - * @param {object} [options] Optional settings. - * @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.listDatabases = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation( - this.s.db.s.topology, - new ListDatabasesOperation(this.s.db, options), - callback - ); -}; - -/** - * Get ReplicaSet status - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.replSetGetStatus = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const replSetGetStatusOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - { replSetGetStatus: 1 }, - options - ); - - return executeOperation(this.s.db.s.topology, replSetGetStatusOperation, callback); -}; - -module.exports = Admin; diff --git a/node_modules/mongodb/lib/aggregation_cursor.js b/node_modules/mongodb/lib/aggregation_cursor.js deleted file mode 100644 index b0977c6..0000000 --- a/node_modules/mongodb/lib/aggregation_cursor.js +++ /dev/null @@ -1,370 +0,0 @@ -'use strict'; - -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const CursorState = require('./core/cursor').CursorState; -const deprecate = require('util').deprecate; - -/** - * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 4.X - * or higher stream - * - * **AGGREGATIONCURSOR Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // Show that duplicate records got dropped - * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class AggregationCursor - * @extends external:Readable - * @fires AggregationCursor#data - * @fires AggregationCursor#end - * @fires AggregationCursor#close - * @fires AggregationCursor#readable - * @return {AggregationCursor} an AggregationCursor instance. - */ -class AggregationCursor extends Cursor { - constructor(topology, operation, options) { - super(topology, operation, options); - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @throws {MongoError} - * @return {AggregationCursor} - */ - batchSize(value) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - this.operation.options.batchSize = value; - this.setCursorBatchSize(value); - return this; - } - - /** - * Add a geoNear stage to the aggregation pipeline - * @method - * @param {object} document The geoNear stage document. - * @return {AggregationCursor} - */ - geoNear(document) { - this.operation.addToPipeline({ $geoNear: document }); - return this; - } - - /** - * Add a group stage to the aggregation pipeline - * @method - * @param {object} document The group stage document. - * @return {AggregationCursor} - */ - group(document) { - this.operation.addToPipeline({ $group: document }); - return this; - } - - /** - * Add a limit stage to the aggregation pipeline - * @method - * @param {number} value The state limit value. - * @return {AggregationCursor} - */ - limit(value) { - this.operation.addToPipeline({ $limit: value }); - return this; - } - - /** - * Add a match stage to the aggregation pipeline - * @method - * @param {object} document The match stage document. - * @return {AggregationCursor} - */ - match(document) { - this.operation.addToPipeline({ $match: document }); - return this; - } - - /** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {AggregationCursor} - */ - maxTimeMS(value) { - this.operation.options.maxTimeMS = value; - return this; - } - - /** - * Add a out stage to the aggregation pipeline - * @method - * @param {number} destination The destination name. - * @return {AggregationCursor} - */ - out(destination) { - this.operation.addToPipeline({ $out: destination }); - return this; - } - - /** - * Add a project stage to the aggregation pipeline - * @method - * @param {object} document The project stage document. - * @return {AggregationCursor} - */ - project(document) { - this.operation.addToPipeline({ $project: document }); - return this; - } - - /** - * Add a lookup stage to the aggregation pipeline - * @method - * @param {object} document The lookup stage document. - * @return {AggregationCursor} - */ - lookup(document) { - this.operation.addToPipeline({ $lookup: document }); - return this; - } - - /** - * Add a redact stage to the aggregation pipeline - * @method - * @param {object} document The redact stage document. - * @return {AggregationCursor} - */ - redact(document) { - this.operation.addToPipeline({ $redact: document }); - return this; - } - - /** - * Add a skip stage to the aggregation pipeline - * @method - * @param {number} value The state skip value. - * @return {AggregationCursor} - */ - skip(value) { - this.operation.addToPipeline({ $skip: value }); - return this; - } - - /** - * Add a sort stage to the aggregation pipeline - * @method - * @param {object} document The sort stage document. - * @return {AggregationCursor} - */ - sort(document) { - this.operation.addToPipeline({ $sort: document }); - return this; - } - - /** - * Add a unwind stage to the aggregation pipeline - * @method - * @param {number} field The unwind field name. - * @return {AggregationCursor} - */ - unwind(field) { - this.operation.addToPipeline({ $unwind: field }); - return this; - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -// aliases -AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; - -// deprecated methods -deprecate( - AggregationCursor.prototype.geoNear, - 'The `$geoNear` stage is deprecated in MongoDB 4.0, and removed in version 4.2.' -); - -/** - * AggregationCursor stream data event, fired for each document in the cursor. - * - * @event AggregationCursor#data - * @type {object} - */ - -/** - * AggregationCursor stream end event - * - * @event AggregationCursor#end - * @type {null} - */ - -/** - * AggregationCursor stream close event - * - * @event AggregationCursor#close - * @type {null} - */ - -/** - * AggregationCursor stream readable event - * - * @event AggregationCursor#readable - * @type {null} - */ - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function AggregationCursor.prototype.next - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function AggregationCursor.prototype.hasNext - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previously accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method AggregationCursor.prototype.toArray - * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method AggregationCursor.prototype.each - * @deprecated - * @param {AggregationCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a AggregationCursor command and emitting close. - * @method AggregationCursor.prototype.close - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method AggregationCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Execute the explain for the cursor - * @method AggregationCursor.prototype.explain - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Clone the cursor - * @function AggregationCursor.prototype.clone - * @return {AggregationCursor} - */ - -/** - * Resets the cursor - * @function AggregationCursor.prototype.rewind - * @return {AggregationCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback AggregationCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback AggregationCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/** - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method AggregationCursor.prototype.forEach - * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. - * @param {AggregationCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -module.exports = AggregationCursor; diff --git a/node_modules/mongodb/lib/apm.js b/node_modules/mongodb/lib/apm.js deleted file mode 100644 index f78e4aa..0000000 --- a/node_modules/mongodb/lib/apm.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; -const EventEmitter = require('events').EventEmitter; - -class Instrumentation extends EventEmitter { - constructor() { - super(); - } - - instrument(MongoClient, callback) { - // store a reference to the original functions - this.$MongoClient = MongoClient; - const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect); - - const instrumentation = this; - MongoClient.prototype.connect = function(callback) { - this.s.options.monitorCommands = true; - this.on('commandStarted', event => instrumentation.emit('started', event)); - this.on('commandSucceeded', event => instrumentation.emit('succeeded', event)); - this.on('commandFailed', event => instrumentation.emit('failed', event)); - return $prototypeConnect.call(this, callback); - }; - - if (typeof callback === 'function') callback(null, this); - } - - uninstrument() { - this.$MongoClient.prototype.connect = this.$prototypeConnect; - } -} - -module.exports = Instrumentation; diff --git a/node_modules/mongodb/lib/async/.eslintrc b/node_modules/mongodb/lib/async/.eslintrc deleted file mode 100644 index 93b2f64..0000000 --- a/node_modules/mongodb/lib/async/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "parserOptions": { - "ecmaVersion": 2018 - } -} diff --git a/node_modules/mongodb/lib/async/async_iterator.js b/node_modules/mongodb/lib/async/async_iterator.js deleted file mode 100644 index 6021aad..0000000 --- a/node_modules/mongodb/lib/async/async_iterator.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -// async function* asyncIterator() { -// while (true) { -// const value = await this.next(); -// if (!value) { -// await this.close(); -// return; -// } - -// yield value; -// } -// } - -// TODO: change this to the async generator function above -function asyncIterator() { - const cursor = this; - - return { - next: function() { - return Promise.resolve() - .then(() => cursor.next()) - .then(value => { - if (!value) { - return cursor.close().then(() => ({ value, done: true })); - } - return { value, done: false }; - }); - } - }; -} - -exports.asyncIterator = asyncIterator; diff --git a/node_modules/mongodb/lib/bulk/common.js b/node_modules/mongodb/lib/bulk/common.js deleted file mode 100644 index ac2fd5d..0000000 --- a/node_modules/mongodb/lib/bulk/common.js +++ /dev/null @@ -1,1253 +0,0 @@ -'use strict'; - -const Long = require('../core').BSON.Long; -const MongoError = require('../core').MongoError; -const ObjectID = require('../core').BSON.ObjectID; -const BSON = require('../core').BSON; -const MongoWriteConcernError = require('../core').MongoWriteConcernError; -const toError = require('../utils').toError; -const handleCallback = require('../utils').handleCallback; -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const executeLegacyOperation = require('../utils').executeLegacyOperation; -const isPromiseLike = require('../utils').isPromiseLike; - -// Error codes -const WRITE_CONCERN_ERROR = 64; - -// Insert types -const INSERT = 1; -const UPDATE = 2; -const REMOVE = 3; - -const bson = new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp -]); - -/** - * Keeps the state of a unordered batch so we can rewrite the results - * correctly after command execution - * @ignore - */ -class Batch { - constructor(batchType, originalZeroIndex) { - this.originalZeroIndex = originalZeroIndex; - this.currentIndex = 0; - this.originalIndexes = []; - this.batchType = batchType; - this.operations = []; - this.size = 0; - this.sizeBytes = 0; - } -} - -/** - * @classdesc - * The result of a bulk write. - */ -class BulkWriteResult { - /** - * Create a new BulkWriteResult instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(bulkResult) { - this.result = bulkResult; - } - - /** - * Evaluates to true if the bulk operation correctly executes - * @type {boolean} - */ - get ok() { - return this.result.ok; - } - - /** - * The number of inserted documents - * @type {number} - */ - get nInserted() { - return this.result.nInserted; - } - - /** - * Number of upserted documents - * @type {number} - */ - get nUpserted() { - return this.result.nUpserted; - } - - /** - * Number of matched documents - * @type {number} - */ - get nMatched() { - return this.result.nMatched; - } - - /** - * Number of documents updated physically on disk - * @type {number} - */ - get nModified() { - return this.result.nModified; - } - - /** - * Number of removed documents - * @type {number} - */ - get nRemoved() { - return this.result.nRemoved; - } - - /** - * Returns an array of all inserted ids - * - * @return {object[]} - */ - getInsertedIds() { - return this.result.insertedIds; - } - - /** - * Returns an array of all upserted ids - * - * @return {object[]} - */ - getUpsertedIds() { - return this.result.upserted; - } - - /** - * Returns the upserted id at the given index - * - * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index - * @return {object} - */ - getUpsertedIdAt(index) { - return this.result.upserted[index]; - } - - /** - * Returns raw internal result - * - * @return {object} - */ - getRawResponse() { - return this.result; - } - - /** - * Returns true if the bulk operation contains a write error - * - * @return {boolean} - */ - hasWriteErrors() { - return this.result.writeErrors.length > 0; - } - - /** - * Returns the number of write errors off the bulk operation - * - * @return {number} - */ - getWriteErrorCount() { - return this.result.writeErrors.length; - } - - /** - * Returns a specific write error object - * - * @param {number} index of the write error to return, returns null if there is no result for passed in index - * @return {WriteError} - */ - getWriteErrorAt(index) { - if (index < this.result.writeErrors.length) { - return this.result.writeErrors[index]; - } - return null; - } - - /** - * Retrieve all write errors - * - * @return {WriteError[]} - */ - getWriteErrors() { - return this.result.writeErrors; - } - - /** - * Retrieve lastOp if available - * - * @return {object} - */ - getLastOp() { - return this.result.lastOp; - } - - /** - * Retrieve the write concern error if any - * - * @return {WriteConcernError} - */ - getWriteConcernError() { - if (this.result.writeConcernErrors.length === 0) { - return null; - } else if (this.result.writeConcernErrors.length === 1) { - // Return the error - return this.result.writeConcernErrors[0]; - } else { - // Combine the errors - let errmsg = ''; - for (let i = 0; i < this.result.writeConcernErrors.length; i++) { - const err = this.result.writeConcernErrors[i]; - errmsg = errmsg + err.errmsg; - - // TODO: Something better - if (i === 0) errmsg = errmsg + ' and '; - } - - return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR }); - } - } - - /** - * @return {object} - */ - toJSON() { - return this.result; - } - - /** - * @return {string} - */ - toString() { - return `BulkWriteResult(${this.toJSON(this.result)})`; - } - - /** - * @return {boolean} - */ - isOk() { - return this.result.ok === 1; - } -} - -/** - * @classdesc An error representing a failure by the server to apply the requested write concern to the bulk operation. - */ -class WriteConcernError { - /** - * Create a new WriteConcernError instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(err) { - this.err = err; - } - - /** - * Write concern error code. - * @type {number} - */ - get code() { - return this.err.code; - } - - /** - * Write concern error message. - * @type {string} - */ - get errmsg() { - return this.err.errmsg; - } - - /** - * @return {object} - */ - toJSON() { - return { code: this.err.code, errmsg: this.err.errmsg }; - } - - /** - * @return {string} - */ - toString() { - return `WriteConcernError(${this.err.errmsg})`; - } -} - -/** - * @classdesc An error that occurred during a BulkWrite on the server. - */ -class WriteError { - /** - * Create a new WriteError instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(err) { - this.err = err; - } - - /** - * WriteError code. - * @type {number} - */ - get code() { - return this.err.code; - } - - /** - * WriteError original bulk operation index. - * @type {number} - */ - get index() { - return this.err.index; - } - - /** - * WriteError message. - * @type {string} - */ - get errmsg() { - return this.err.errmsg; - } - - /** - * Returns the underlying operation that caused the error - * @return {object} - */ - getOperation() { - return this.err.op; - } - - /** - * @return {object} - */ - toJSON() { - return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; - } - - /** - * @return {string} - */ - toString() { - return `WriteError(${JSON.stringify(this.toJSON())})`; - } -} - -/** - * Merges results into shared data structure - * @ignore - */ -function mergeBatchResults(batch, bulkResult, err, result) { - // If we have an error set the result to be the err object - if (err) { - result = err; - } else if (result && result.result) { - result = result.result; - } else if (result == null) { - return; - } - - // Do we have a top level error stop processing and return - if (result.ok === 0 && bulkResult.ok === 1) { - bulkResult.ok = 0; - - const writeError = { - index: 0, - code: result.code || 0, - errmsg: result.message, - op: batch.operations[0] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - return; - } else if (result.ok === 0 && bulkResult.ok === 0) { - return; - } - - // Deal with opTime if available - if (result.opTime || result.lastOp) { - const opTime = result.lastOp || result.opTime; - let lastOpTS = null; - let lastOpT = null; - - // We have a time stamp - if (opTime && opTime._bsontype === 'Timestamp') { - if (bulkResult.lastOp == null) { - bulkResult.lastOp = opTime; - } else if (opTime.greaterThan(bulkResult.lastOp)) { - bulkResult.lastOp = opTime; - } - } else { - // Existing TS - if (bulkResult.lastOp) { - lastOpTS = - typeof bulkResult.lastOp.ts === 'number' - ? Long.fromNumber(bulkResult.lastOp.ts) - : bulkResult.lastOp.ts; - lastOpT = - typeof bulkResult.lastOp.t === 'number' - ? Long.fromNumber(bulkResult.lastOp.t) - : bulkResult.lastOp.t; - } - - // Current OpTime TS - const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts; - const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t; - - // Compare the opTime's - if (bulkResult.lastOp == null) { - bulkResult.lastOp = opTime; - } else if (opTimeTS.greaterThan(lastOpTS)) { - bulkResult.lastOp = opTime; - } else if (opTimeTS.equals(lastOpTS)) { - if (opTimeT.greaterThan(lastOpT)) { - bulkResult.lastOp = opTime; - } - } - } - } - - // If we have an insert Batch type - if (batch.batchType === INSERT && result.n) { - bulkResult.nInserted = bulkResult.nInserted + result.n; - } - - // If we have an insert Batch type - if (batch.batchType === REMOVE && result.n) { - bulkResult.nRemoved = bulkResult.nRemoved + result.n; - } - - let nUpserted = 0; - - // We have an array of upserted values, we need to rewrite the indexes - if (Array.isArray(result.upserted)) { - nUpserted = result.upserted.length; - - for (let i = 0; i < result.upserted.length; i++) { - bulkResult.upserted.push({ - index: result.upserted[i].index + batch.originalZeroIndex, - _id: result.upserted[i]._id - }); - } - } else if (result.upserted) { - nUpserted = 1; - - bulkResult.upserted.push({ - index: batch.originalZeroIndex, - _id: result.upserted - }); - } - - // If we have an update Batch type - if (batch.batchType === UPDATE && result.n) { - const nModified = result.nModified; - bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; - bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); - - if (typeof nModified === 'number') { - bulkResult.nModified = bulkResult.nModified + nModified; - } else { - bulkResult.nModified = null; - } - } - - if (Array.isArray(result.writeErrors)) { - for (let i = 0; i < result.writeErrors.length; i++) { - const writeError = { - index: batch.originalIndexes[result.writeErrors[i].index], - code: result.writeErrors[i].code, - errmsg: result.writeErrors[i].errmsg, - op: batch.operations[result.writeErrors[i].index] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - } - } - - if (result.writeConcernError) { - bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); - } -} - -function executeCommands(bulkOperation, options, callback) { - if (bulkOperation.s.batches.length === 0) { - return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult)); - } - - const batch = bulkOperation.s.batches.shift(); - - function resultHandler(err, result) { - // Error is a driver related error not a bulk op error, terminate - if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { - return handleCallback(callback, err); - } - - // If we have and error - if (err) err.ok = 0; - if (err instanceof MongoWriteConcernError) { - return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback); - } - - // Merge the results together - const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); - const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); - if (mergeResult != null) { - return handleCallback(callback, null, writeResult); - } - - if (bulkOperation.handleWriteError(callback, writeResult)) return; - - // Execute the next command in line - executeCommands(bulkOperation, options, callback); - } - - bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); -} - -/** - * handles write concern error - * - * @ignore - * @param {object} batch - * @param {object} bulkResult - * @param {boolean} ordered - * @param {WriteConcernError} err - * @param {function} callback - */ -function handleMongoWriteConcernError(batch, bulkResult, err, callback) { - mergeBatchResults(batch, bulkResult, null, err.result); - - const wrappedWriteConcernError = new WriteConcernError({ - errmsg: err.result.writeConcernError.errmsg, - code: err.result.writeConcernError.result - }); - return handleCallback( - callback, - new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)), - null - ); -} - -/** - * @classdesc An error indicating an unsuccessful Bulk Write - */ -class BulkWriteError extends MongoError { - /** - * Creates a new BulkWriteError - * - * @param {Error|string|object} message The error message - * @param {BulkWriteResult} result The result of the bulk write operation - * @extends {MongoError} - */ - constructor(error, result) { - const message = error.err || error.errmsg || error.errMessage || error; - super(message); - - Object.assign(this, error); - - this.name = 'BulkWriteError'; - this.result = result; - } -} - -/** - * @classdesc A builder object that is returned from {@link BulkOperationBase#find}. - * Is used to build a write operation that involves a query filter. - */ -class FindOperators { - /** - * Creates a new FindOperators object. - * - * **NOTE:** Internal Type, do not instantiate directly - * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation - */ - constructor(bulkOperation) { - this.s = bulkOperation.s; - } - - /** - * Add a multiple update operation to the bulk operation - * - * @method - * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - update(updateDocument) { - // Perform upsert - const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - const document = { - q: this.s.currentOp.selector, - u: updateDocument, - multi: true, - upsert: upsert - }; - - if (updateDocument.hint) { - document.hint = updateDocument.hint; - } - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } - - /** - * Add a single update operation to the bulk operation - * - * @method - * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - updateOne(updateDocument) { - // Perform upsert - const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - const document = { - q: this.s.currentOp.selector, - u: updateDocument, - multi: false, - upsert: upsert - }; - - if (updateDocument.hint) { - document.hint = updateDocument.hint; - } - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } - - /** - * Add a replace one operation to the bulk operation - * - * @method - * @param {object} updateDocument the new document to replace the existing one with - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - replaceOne(updateDocument) { - this.updateOne(updateDocument); - } - - /** - * Upsert modifier for update bulk operation, noting that this operation is an upsert. - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {FindOperators} reference to self - */ - upsert() { - this.s.currentOp.upsert = true; - return this; - } - - /** - * Add a delete one operation to the bulk operation - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - deleteOne() { - // Establish the update command - const document = { - q: this.s.currentOp.selector, - limit: 1 - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } - - /** - * Add a delete many operation to the bulk operation - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - delete() { - // Establish the update command - const document = { - q: this.s.currentOp.selector, - limit: 0 - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } - - /** - * backwards compatability for deleteOne - */ - removeOne() { - return this.deleteOne(); - } - - /** - * backwards compatability for delete - */ - remove() { - return this.delete(); - } -} - -/** - * @classdesc Parent class to OrderedBulkOperation and UnorderedBulkOperation - * - * **NOTE:** Internal Type, do not instantiate directly - */ -class BulkOperationBase { - /** - * Create a new OrderedBulkOperation or UnorderedBulkOperation instance - * @property {number} length Get the number of operations in the bulk. - */ - constructor(topology, collection, options, isOrdered) { - // determine whether bulkOperation is ordered or unordered - this.isOrdered = isOrdered; - - options = options == null ? {} : options; - // TODO Bring from driver information in isMaster - // Get the namespace for the write operations - const namespace = collection.s.namespace; - // Used to mark operation as executed - const executed = false; - - // Current item - const currentOp = null; - - // Handle to the bson serializer, used to calculate running sizes - const bson = topology.bson; - // Set max byte size - const isMaster = topology.lastIsMaster(); - - // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents - // over 2mb are still allowed - const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter); - const maxBsonObjectSize = - isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16; - const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize; - const maxWriteBatchSize = - isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000; - - // Calculates the largest possible size of an Array key, represented as a BSON string - // element. This calculation: - // 1 byte for BSON type - // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) - // + 1 bytes for null terminator - const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, collection.s.db); - finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options); - const writeConcern = finalOptions.writeConcern; - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Final results - const bulkResult = { - ok: 1, - writeErrors: [], - writeConcernErrors: [], - insertedIds: [], - nInserted: 0, - nUpserted: 0, - nMatched: 0, - nModified: 0, - nRemoved: 0, - upserted: [] - }; - - // Internal state - this.s = { - // Final result - bulkResult: bulkResult, - // Current batch state - currentBatch: null, - currentIndex: 0, - // ordered specific - currentBatchSize: 0, - currentBatchSizeBytes: 0, - // unordered specific - currentInsertBatch: null, - currentUpdateBatch: null, - currentRemoveBatch: null, - batches: [], - // Write concern - writeConcern: writeConcern, - // Max batch size options - maxBsonObjectSize, - maxBatchSizeBytes, - maxWriteBatchSize, - maxKeySize, - // Namespace - namespace: namespace, - // BSON - bson: bson, - // Topology - topology: topology, - // Options - options: finalOptions, - // Current operation - currentOp: currentOp, - // Executed - executed: executed, - // Collection - collection: collection, - // Promise Library - promiseLibrary: promiseLibrary, - // Fundamental error - err: null, - // check keys - checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true - }; - - // bypass Validation - if (options.bypassDocumentValidation === true) { - this.s.bypassDocumentValidation = true; - } - } - - /** - * Add a single insert document to the bulk operation - * - * @param {object} document the document to insert - * @throws {MongoError} - * @return {BulkOperationBase} A reference to self - * - * @example - * const bulkOp = collection.initializeOrderedBulkOp(); - * // Adds three inserts to the bulkOp. - * bulkOp - * .insert({ a: 1 }) - * .insert({ b: 2 }) - * .insert({ c: 3 }); - * await bulkOp.execute(); - */ - insert(document) { - if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) - document._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, document); - } - - /** - * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. - * Returns a builder object used to complete the definition of the operation. - * - * @method - * @param {object} selector The selector for the bulk operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-q q documentation} - * @throws {MongoError} if a selector is not specified - * @return {FindOperators} A helper object with which the write operation can be defined. - * - * @example - * const bulkOp = collection.initializeOrderedBulkOp(); - * - * // Add an updateOne to the bulkOp - * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); - * - * // Add an updateMany to the bulkOp - * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); - * - * // Add an upsert - * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); - * - * // Add a deletion - * bulkOp.find({ g: 7 }).deleteOne(); - * - * // Add a multi deletion - * bulkOp.find({ h: 8 }).delete(); - * - * // Add a replaceOne - * bulkOp.find({ i: 9 }).replaceOne({ j: 10 }); - * - * // Update using a pipeline (requires Mongodb 4.2 or higher) - * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ - * { $set: { total: { $sum: [ '$y', '$z' ] } } } - * ]); - * - * // All of the ops will now be executed - * await bulkOp.execute(); - */ - find(selector) { - if (!selector) { - throw toError('Bulk find operation must specify a selector'); - } - - // Save a current selector - this.s.currentOp = { - selector: selector - }; - - return new FindOperators(this); - } - - /** - * Specifies a raw operation to perform in the bulk write. - * - * @method - * @param {object} op The raw operation to perform. - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @return {BulkOperationBase} A reference to self - */ - raw(op) { - const key = Object.keys(op)[0]; - - // Set up the force server object id - const forceServerObjectId = - typeof this.s.options.forceServerObjectId === 'boolean' - ? this.s.options.forceServerObjectId - : this.s.collection.s.db.options.forceServerObjectId; - - // Update operations - if ( - (op.updateOne && op.updateOne.q) || - (op.updateMany && op.updateMany.q) || - (op.replaceOne && op.replaceOne.q) - ) { - op[key].multi = op.updateOne || op.replaceOne ? false : true; - return this.s.options.addToOperationsList(this, UPDATE, op[key]); - } - - // Crud spec update format - if (op.updateOne || op.updateMany || op.replaceOne) { - const multi = op.updateOne || op.replaceOne ? false : true; - const operation = { - q: op[key].filter, - u: op[key].update || op[key].replacement, - multi: multi - }; - - if (op[key].hint) { - operation.hint = op[key].hint; - } - - if (this.isOrdered) { - operation.upsert = op[key].upsert ? true : false; - if (op.collation) operation.collation = op.collation; - } else { - if (op[key].upsert) operation.upsert = true; - } - if (op[key].arrayFilters) operation.arrayFilters = op[key].arrayFilters; - return this.s.options.addToOperationsList(this, UPDATE, operation); - } - - // Remove operations - if ( - op.removeOne || - op.removeMany || - (op.deleteOne && op.deleteOne.q) || - (op.deleteMany && op.deleteMany.q) - ) { - op[key].limit = op.removeOne ? 1 : 0; - return this.s.options.addToOperationsList(this, REMOVE, op[key]); - } - - // Crud spec delete operations, less efficient - if (op.deleteOne || op.deleteMany) { - const limit = op.deleteOne ? 1 : 0; - const operation = { q: op[key].filter, limit: limit }; - if (this.isOrdered) { - if (op.collation) operation.collation = op.collation; - } - return this.s.options.addToOperationsList(this, REMOVE, operation); - } - - // Insert operations - if (op.insertOne && op.insertOne.document == null) { - if (forceServerObjectId !== true && op.insertOne._id == null) - op.insertOne._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, op.insertOne); - } else if (op.insertOne && op.insertOne.document) { - if (forceServerObjectId !== true && op.insertOne.document._id == null) - op.insertOne.document._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document); - } - - if (op.insertMany) { - for (let i = 0; i < op.insertMany.length; i++) { - if (forceServerObjectId !== true && op.insertMany[i]._id == null) - op.insertMany[i]._id = new ObjectID(); - this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]); - } - - return; - } - - // No valid type of operation - throw toError( - 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany' - ); - } - - /** - * helper function to assist with promiseOrCallback behavior - * @ignore - * @param {*} err - * @param {*} callback - */ - _handleEarlyError(err, callback) { - if (typeof callback === 'function') { - callback(err, null); - return; - } - - return this.s.promiseLibrary.reject(err); - } - - /** - * An internal helper method. Do not invoke directly. Will be going away in the future - * - * @ignore - * @method - * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation - * @param {object} writeConcern - * @param {object} options - * @param {function} callback - */ - bulkExecute(_writeConcern, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (typeof _writeConcern === 'function') { - callback = _writeConcern; - } else if (_writeConcern && typeof _writeConcern === 'object') { - this.s.writeConcern = _writeConcern; - } - - if (this.s.executed) { - const executedError = toError('batch cannot be re-executed'); - return this._handleEarlyError(executedError, callback); - } - - // If we have current batch - if (this.isOrdered) { - if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); - } else { - if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); - if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); - if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); - } - // If we have no operations in the bulk raise an error - if (this.s.batches.length === 0) { - const emptyBatchError = toError('Invalid Operation, no operations specified'); - return this._handleEarlyError(emptyBatchError, callback); - } - return { options, callback }; - } - - /** - * The callback format for results - * @callback BulkOperationBase~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {BulkWriteResult} result The bulk write result. - */ - - /** - * Execute the bulk operation - * - * @method - * @param {WriteConcern} [_writeConcern] Optional write concern. Can also be specified through options. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {BulkOperationBase~resultCallback} [callback] A callback that will be invoked when bulkWrite finishes/errors - * @throws {MongoError} Throws error if the bulk object has already been executed - * @throws {MongoError} Throws error if the bulk object does not have any operations - * @return {Promise|void} returns Promise if no callback passed - */ - execute(_writeConcern, options, callback) { - const ret = this.bulkExecute(_writeConcern, options, callback); - if (!ret || isPromiseLike(ret)) { - return ret; - } - - options = ret.options; - callback = ret.callback; - - return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]); - } - - /** - * Handles final options before executing command - * - * An internal method. Do not invoke. Will not be accessible in the future - * - * @ignore - * @param {object} config - * @param {object} config.options - * @param {number} config.batch - * @param {function} config.resultHandler - * @param {function} callback - */ - finalOptionsHandler(config, callback) { - const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options); - if (this.s.writeConcern != null) { - finalOptions.writeConcern = this.s.writeConcern; - } - - if (finalOptions.bypassDocumentValidation !== true) { - delete finalOptions.bypassDocumentValidation; - } - - // Set an operationIf if provided - if (this.operationId) { - config.resultHandler.operationId = this.operationId; - } - - // Serialize functions - if (this.s.options.serializeFunctions) { - finalOptions.serializeFunctions = true; - } - - // Ignore undefined - if (this.s.options.ignoreUndefined) { - finalOptions.ignoreUndefined = true; - } - - // Is the bypassDocumentValidation options specific - if (this.s.bypassDocumentValidation === true) { - finalOptions.bypassDocumentValidation = true; - } - - // Is the checkKeys option disabled - if (this.s.checkKeys === false) { - finalOptions.checkKeys = false; - } - - if (finalOptions.retryWrites) { - if (config.batch.batchType === UPDATE) { - finalOptions.retryWrites = - finalOptions.retryWrites && !config.batch.operations.some(op => op.multi); - } - - if (config.batch.batchType === REMOVE) { - finalOptions.retryWrites = - finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0); - } - } - - try { - if (config.batch.batchType === INSERT) { - this.s.topology.insert( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } else if (config.batch.batchType === UPDATE) { - this.s.topology.update( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } else if (config.batch.batchType === REMOVE) { - this.s.topology.remove( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } - } catch (err) { - // Force top level error - err.ok = 0; - // Merge top level error and return - handleCallback(callback, null, mergeBatchResults(config.batch, this.s.bulkResult, err, null)); - } - } - - /** - * Handles the write error before executing commands - * - * An internal helper method. Do not invoke directly. Will be going away in the future - * - * @ignore - * @param {function} callback - * @param {BulkWriteResult} writeResult - * @param {class} self either OrderedBulkOperation or UnorderedBulkOperation - */ - handleWriteError(callback, writeResult) { - if (this.s.bulkResult.writeErrors.length > 0) { - const msg = this.s.bulkResult.writeErrors[0].errmsg - ? this.s.bulkResult.writeErrors[0].errmsg - : 'write operation failed'; - - handleCallback( - callback, - new BulkWriteError( - toError({ - message: msg, - code: this.s.bulkResult.writeErrors[0].code, - writeErrors: this.s.bulkResult.writeErrors - }), - writeResult - ), - null - ); - return true; - } - - if (writeResult.getWriteConcernError()) { - handleCallback( - callback, - new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult), - null - ); - return true; - } - } -} - -Object.defineProperty(BulkOperationBase.prototype, 'length', { - enumerable: true, - get: function() { - return this.s.currentIndex; - } -}); - -// Exports symbols -module.exports = { - Batch, - BulkOperationBase, - bson, - INSERT: INSERT, - UPDATE: UPDATE, - REMOVE: REMOVE, - BulkWriteError -}; diff --git a/node_modules/mongodb/lib/bulk/ordered.js b/node_modules/mongodb/lib/bulk/ordered.js deleted file mode 100644 index a976bed..0000000 --- a/node_modules/mongodb/lib/bulk/ordered.js +++ /dev/null @@ -1,110 +0,0 @@ -'use strict'; - -const common = require('./common'); -const BulkOperationBase = common.BulkOperationBase; -const Batch = common.Batch; -const bson = common.bson; -const utils = require('../utils'); -const toError = utils.toError; - -/** - * Add to internal list of Operations - * - * @ignore - * @param {OrderedBulkOperation} bulkOperation - * @param {number} docType number indicating the document type - * @param {object} document - * @return {OrderedBulkOperation} - */ -function addToOperationsList(bulkOperation, docType, document) { - // Get the bsonSize - const bsonSize = bson.calculateObjectSize(document, { - checkKeys: false, - - // Since we don't know what the user selected for BSON options here, - // err on the safe side, and check the size with ignoreUndefined: false. - ignoreUndefined: false - }); - - // Throw error if the doc is bigger than the max BSON size - if (bsonSize >= bulkOperation.s.maxBsonObjectSize) - throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBsonObjectSize); - - // Create a new batch object if we don't have a current one - if (bulkOperation.s.currentBatch == null) - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - const maxKeySize = bulkOperation.s.maxKeySize; - - // Check if we need to create a new batch - if ( - // New batch if we exceed the max batch op size - bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize || - // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, - // since we can't sent an empty batch - (bulkOperation.s.currentBatchSize > 0 && - bulkOperation.s.currentBatchSizeBytes + maxKeySize + bsonSize >= - bulkOperation.s.maxBatchSizeBytes) || - // New batch if the new op does not have the same op type as the current batch - bulkOperation.s.currentBatch.batchType !== docType - ) { - // Save the batch to the execution stack - bulkOperation.s.batches.push(bulkOperation.s.currentBatch); - - // Create a new batch - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - // Reset the current size trackers - bulkOperation.s.currentBatchSize = 0; - bulkOperation.s.currentBatchSizeBytes = 0; - } - - if (docType === common.INSERT) { - bulkOperation.s.bulkResult.insertedIds.push({ - index: bulkOperation.s.currentIndex, - _id: document._id - }); - } - - // We have an array of documents - if (Array.isArray(document)) { - throw toError('operation passed in cannot be an Array'); - } - - bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); - bulkOperation.s.currentBatch.operations.push(document); - bulkOperation.s.currentBatchSize += 1; - bulkOperation.s.currentBatchSizeBytes += maxKeySize + bsonSize; - bulkOperation.s.currentIndex += 1; - - // Return bulkOperation - return bulkOperation; -} - -/** - * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @extends BulkOperationBase - * @property {number} length Get the number of operations in the bulk. - * @return {OrderedBulkOperation} a OrderedBulkOperation instance. - */ -class OrderedBulkOperation extends BulkOperationBase { - constructor(topology, collection, options) { - options = options || {}; - options = Object.assign(options, { addToOperationsList }); - - super(topology, collection, options, true); - } -} - -/** - * Returns an unordered batch object - * @ignore - */ -function initializeOrderedBulkOp(topology, collection, options) { - return new OrderedBulkOperation(topology, collection, options); -} - -initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; -module.exports = initializeOrderedBulkOp; -module.exports.Bulk = OrderedBulkOperation; diff --git a/node_modules/mongodb/lib/bulk/unordered.js b/node_modules/mongodb/lib/bulk/unordered.js deleted file mode 100644 index c126c5b..0000000 --- a/node_modules/mongodb/lib/bulk/unordered.js +++ /dev/null @@ -1,131 +0,0 @@ -'use strict'; - -const common = require('./common'); -const BulkOperationBase = common.BulkOperationBase; -const Batch = common.Batch; -const bson = common.bson; -const utils = require('../utils'); -const toError = utils.toError; - -/** - * Add to internal list of Operations - * - * @ignore - * @param {UnorderedBulkOperation} bulkOperation - * @param {number} docType number indicating the document type - * @param {object} document - * @return {UnorderedBulkOperation} - */ -function addToOperationsList(bulkOperation, docType, document) { - // Get the bsonSize - const bsonSize = bson.calculateObjectSize(document, { - checkKeys: false, - - // Since we don't know what the user selected for BSON options here, - // err on the safe side, and check the size with ignoreUndefined: false. - ignoreUndefined: false - }); - // Throw error if the doc is bigger than the max BSON size - if (bsonSize >= bulkOperation.s.maxBsonObjectSize) - throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBsonObjectSize); - // Holds the current batch - bulkOperation.s.currentBatch = null; - // Get the right type of batch - if (docType === common.INSERT) { - bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch; - } else if (docType === common.UPDATE) { - bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch; - } else if (docType === common.REMOVE) { - bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch; - } - - const maxKeySize = bulkOperation.s.maxKeySize; - - // Create a new batch object if we don't have a current one - if (bulkOperation.s.currentBatch == null) - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - // Check if we need to create a new batch - if ( - // New batch if we exceed the max batch op size - bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize || - // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, - // since we can't sent an empty batch - (bulkOperation.s.currentBatch.size > 0 && - bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= - bulkOperation.s.maxBatchSizeBytes) || - // New batch if the new op does not have the same op type as the current batch - bulkOperation.s.currentBatch.batchType !== docType - ) { - // Save the batch to the execution stack - bulkOperation.s.batches.push(bulkOperation.s.currentBatch); - - // Create a new batch - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - } - - // We have an array of documents - if (Array.isArray(document)) { - throw toError('operation passed in cannot be an Array'); - } - - bulkOperation.s.currentBatch.operations.push(document); - bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); - bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1; - - // Save back the current Batch to the right type - if (docType === common.INSERT) { - bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch; - bulkOperation.s.bulkResult.insertedIds.push({ - index: bulkOperation.s.bulkResult.insertedIds.length, - _id: document._id - }); - } else if (docType === common.UPDATE) { - bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch; - } else if (docType === common.REMOVE) { - bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch; - } - - // Update current batch size - bulkOperation.s.currentBatch.size += 1; - bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize; - - // Return bulkOperation - return bulkOperation; -} - -/** - * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @extends BulkOperationBase - * @property {number} length Get the number of operations in the bulk. - * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. - */ -class UnorderedBulkOperation extends BulkOperationBase { - constructor(topology, collection, options) { - options = options || {}; - options = Object.assign(options, { addToOperationsList }); - - super(topology, collection, options, false); - } - - handleWriteError(callback, writeResult) { - if (this.s.batches.length) { - return false; - } - - return super.handleWriteError(callback, writeResult); - } -} - -/** - * Returns an unordered batch object - * @ignore - */ -function initializeUnorderedBulkOp(topology, collection, options) { - return new UnorderedBulkOperation(topology, collection, options); -} - -initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; -module.exports = initializeUnorderedBulkOp; -module.exports.Bulk = UnorderedBulkOperation; diff --git a/node_modules/mongodb/lib/change_stream.js b/node_modules/mongodb/lib/change_stream.js deleted file mode 100644 index 900da1e..0000000 --- a/node_modules/mongodb/lib/change_stream.js +++ /dev/null @@ -1,611 +0,0 @@ -'use strict'; - -const Denque = require('denque'); -const EventEmitter = require('events'); -const isResumableError = require('./error').isResumableError; -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const relayEvents = require('./core/utils').relayEvents; -const maxWireVersion = require('./core/utils').maxWireVersion; -const maybePromise = require('./utils').maybePromise; -const AggregateOperation = require('./operations/aggregate'); - -const kResumeQueue = Symbol('resumeQueue'); - -const CHANGE_STREAM_OPTIONS = ['resumeAfter', 'startAfter', 'startAtOperationTime', 'fullDocument']; -const CURSOR_OPTIONS = ['batchSize', 'maxAwaitTimeMS', 'collation', 'readPreference'].concat( - CHANGE_STREAM_OPTIONS -); - -const CHANGE_DOMAIN_TYPES = { - COLLECTION: Symbol('Collection'), - DATABASE: Symbol('Database'), - CLUSTER: Symbol('Cluster') -}; - -/** - * @typedef ResumeToken - * @description Represents the logical starting point for a new or resuming {@link ChangeStream} on the server. - * @see https://docs.mongodb.com/master/changeStreams/#change-stream-resume-token - */ - -/** - * @typedef OperationTime - * @description Represents a specific point in time on a server. Can be retrieved by using {@link Db#command} - * @see https://docs.mongodb.com/manual/reference/method/db.runCommand/#response - */ - -/** - * @typedef ChangeStreamOptions - * @description Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. - * @property {string} [fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @property {number} [maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query. - * @property {ResumeToken} [resumeAfter] Allows you to start a changeStream after a specified event. See {@link https://docs.mongodb.com/master/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}. - * @property {ResumeToken} [startAfter] Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/master/changeStreams/#startafter-for-change-streams|ChangeStream documentation}. - * @property {OperationTime} [startAtOperationTime] Will start the changeStream after the specified operationTime. - * @property {number} [batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @property {object} [collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @property {ReadPreference} [readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - */ - -/** - * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. - * @class ChangeStream - * @since 3.0.0 - * @param {(MongoClient|Db|Collection)} parent The parent object that created this change stream - * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents - * @param {ChangeStreamOptions} [options] Optional settings - * @fires ChangeStream#close - * @fires ChangeStream#change - * @fires ChangeStream#end - * @fires ChangeStream#error - * @fires ChangeStream#resumeTokenChanged - * @return {ChangeStream} a ChangeStream instance. - */ -class ChangeStream extends EventEmitter { - constructor(parent, pipeline, options) { - super(); - const Collection = require('./collection'); - const Db = require('./db'); - const MongoClient = require('./mongo_client'); - - this.pipeline = pipeline || []; - this.options = options || {}; - - this.parent = parent; - this.namespace = parent.s.namespace; - if (parent instanceof Collection) { - this.type = CHANGE_DOMAIN_TYPES.COLLECTION; - this.topology = parent.s.db.serverConfig; - } else if (parent instanceof Db) { - this.type = CHANGE_DOMAIN_TYPES.DATABASE; - this.topology = parent.serverConfig; - } else if (parent instanceof MongoClient) { - this.type = CHANGE_DOMAIN_TYPES.CLUSTER; - this.topology = parent.topology; - } else { - throw new TypeError( - 'parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient' - ); - } - - this.promiseLibrary = parent.s.promiseLibrary; - if (!this.options.readPreference && parent.s.readPreference) { - this.options.readPreference = parent.s.readPreference; - } - - this[kResumeQueue] = new Denque(); - - // Create contained Change Stream cursor - this.cursor = createChangeStreamCursor(this, options); - - this.closed = false; - - // Listen for any `change` listeners being added to ChangeStream - this.on('newListener', eventName => { - if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { - this.cursor.on('data', change => processNewChange(this, change)); - } - }); - - // Listen for all `change` listeners being removed from ChangeStream - this.on('removeListener', eventName => { - if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { - this.cursor.removeAllListeners('data'); - } - }); - } - - /** - * @property {ResumeToken} resumeToken - * The cached resume token that will be used to resume - * after the most recently returned change. - */ - get resumeToken() { - return this.cursor.resumeToken; - } - - /** - * Check if there is any document still available in the Change Stream - * @function ChangeStream.prototype.hasNext - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @returns {Promise|void} returns Promise if no callback passed - */ - hasNext(callback) { - return maybePromise(this.parent, callback, cb => { - getCursor(this, (err, cursor) => { - if (err) return cb(err); // failed to resume, raise an error - cursor.hasNext(cb); - }); - }); - } - - /** - * Get the next available document from the Change Stream, returns null if no more documents are available. - * @function ChangeStream.prototype.next - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @returns {Promise|void} returns Promise if no callback passed - */ - next(callback) { - return maybePromise(this.parent, callback, cb => { - getCursor(this, (err, cursor) => { - if (err) return cb(err); // failed to resume, raise an error - cursor.next((error, change) => { - if (error) { - this[kResumeQueue].push(() => this.next(cb)); - processError(this, error, cb); - return; - } - processNewChange(this, change, cb); - }); - }); - }); - } - - /** - * Is the change stream closed - * @method ChangeStream.prototype.isClosed - * @param {boolean} [checkCursor=true] also check if the underlying cursor is closed - * @return {boolean} - */ - isClosed() { - return this.closed || (this.cursor && this.cursor.isClosed()); - } - - /** - * Close the Change Stream - * @method ChangeStream.prototype.close - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - close(callback) { - return maybePromise(this.parent, callback, cb => { - if (this.closed) return cb(); - - // flag the change stream as explicitly closed - this.closed = true; - - if (!this.cursor) return cb(); - - // Tidy up the existing cursor - const cursor = this.cursor; - - return cursor.close(err => { - ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); - this.cursor = undefined; - - return cb(err); - }); - }); - } - - /** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @method - * @param {Writable} destination The destination for writing data - * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options} - * @return {null} - */ - pipe(destination, options) { - if (!this.pipeDestinations) { - this.pipeDestinations = []; - } - this.pipeDestinations.push(destination); - return this.cursor.pipe(destination, options); - } - - /** - * This method will remove the hooks set up for a previous pipe() call. - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - unpipe(destination) { - if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) { - this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1); - } - return this.cursor.unpipe(destination); - } - - /** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - */ - stream(options) { - this.streamOptions = options; - return this.cursor.stream(options); - } - - /** - * This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @return {null} - */ - pause() { - return this.cursor.pause(); - } - - /** - * This method will cause the readable stream to resume emitting data events. - * @return {null} - */ - resume() { - return this.cursor.resume(); - } -} - -class ChangeStreamCursor extends Cursor { - constructor(topology, operation, options) { - super(topology, operation, options); - - options = options || {}; - this._resumeToken = null; - this.startAtOperationTime = options.startAtOperationTime; - - if (options.startAfter) { - this.resumeToken = options.startAfter; - } else if (options.resumeAfter) { - this.resumeToken = options.resumeAfter; - } - } - - set resumeToken(token) { - this._resumeToken = token; - this.emit('resumeTokenChanged', token); - } - - get resumeToken() { - return this._resumeToken; - } - - get resumeOptions() { - const result = {}; - for (const optionName of CURSOR_OPTIONS) { - if (this.options[optionName]) result[optionName] = this.options[optionName]; - } - - if (this.resumeToken || this.startAtOperationTime) { - ['resumeAfter', 'startAfter', 'startAtOperationTime'].forEach(key => delete result[key]); - - if (this.resumeToken) { - const resumeKey = - this.options.startAfter && !this.hasReceived ? 'startAfter' : 'resumeAfter'; - result[resumeKey] = this.resumeToken; - } else if (this.startAtOperationTime && maxWireVersion(this.server) >= 7) { - result.startAtOperationTime = this.startAtOperationTime; - } - } - - return result; - } - - cacheResumeToken(resumeToken) { - if (this.bufferedCount() === 0 && this.cursorState.postBatchResumeToken) { - this.resumeToken = this.cursorState.postBatchResumeToken; - } else { - this.resumeToken = resumeToken; - } - this.hasReceived = true; - } - - _processBatch(batchName, response) { - const cursor = response.cursor; - if (cursor.postBatchResumeToken) { - this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; - - if (cursor[batchName].length === 0) { - this.resumeToken = cursor.postBatchResumeToken; - } - } - } - - _initializeCursor(callback) { - super._initializeCursor((err, result) => { - if (err) { - callback(err); - return; - } - - const response = result.documents[0]; - - if ( - this.startAtOperationTime == null && - this.resumeAfter == null && - this.startAfter == null && - maxWireVersion(this.server) >= 7 - ) { - this.startAtOperationTime = response.operationTime; - } - - this._processBatch('firstBatch', response); - - this.emit('init', result); - this.emit('response'); - callback(err, result); - }); - } - - _getMore(callback) { - super._getMore((err, response) => { - if (err) { - callback(err); - return; - } - - this._processBatch('nextBatch', response); - - this.emit('more', response); - this.emit('response'); - callback(err, response); - }); - } -} - -/** - * @event ChangeStreamCursor#response - * internal event DO NOT USE - * @ignore - */ - -// Create a new change stream cursor based on self's configuration -function createChangeStreamCursor(self, options) { - const changeStreamStageOptions = { fullDocument: options.fullDocument || 'default' }; - applyKnownOptions(changeStreamStageOptions, options, CHANGE_STREAM_OPTIONS); - if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) { - changeStreamStageOptions.allChangesForCluster = true; - } - - const pipeline = [{ $changeStream: changeStreamStageOptions }].concat(self.pipeline); - const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS); - - const changeStreamCursor = new ChangeStreamCursor( - self.topology, - new AggregateOperation(self.parent, pipeline, options), - cursorOptions - ); - - relayEvents(changeStreamCursor, self, ['resumeTokenChanged', 'end', 'close']); - - /** - * Fired for each new matching change in the specified namespace. Attaching a `change` - * event listener to a Change Stream will switch the stream into flowing mode. Data will - * then be passed as soon as it is available. - * - * @event ChangeStream#change - * @type {object} - */ - if (self.listenerCount('change') > 0) { - changeStreamCursor.on('data', function(change) { - processNewChange(self, change); - }); - } - - /** - * Change stream close event - * - * @event ChangeStream#close - * @type {null} - */ - - /** - * Change stream end event - * - * @event ChangeStream#end - * @type {null} - */ - - /** - * Emitted each time the change stream stores a new resume token. - * - * @event ChangeStream#resumeTokenChanged - * @type {ResumeToken} - */ - - /** - * Fired when the stream encounters an error. - * - * @event ChangeStream#error - * @type {Error} - */ - changeStreamCursor.on('error', function(error) { - processError(self, error); - }); - - if (self.pipeDestinations) { - const cursorStream = changeStreamCursor.stream(self.streamOptions); - for (let pipeDestination in self.pipeDestinations) { - cursorStream.pipe(pipeDestination); - } - } - - return changeStreamCursor; -} - -function applyKnownOptions(target, source, optionNames) { - optionNames.forEach(name => { - if (source[name]) { - target[name] = source[name]; - } - }); - - return target; -} - -// This method performs a basic server selection loop, satisfying the requirements of -// ChangeStream resumability until the new SDAM layer can be used. -const SELECTION_TIMEOUT = 30000; -function waitForTopologyConnected(topology, options, callback) { - setTimeout(() => { - if (options && options.start == null) options.start = process.hrtime(); - const start = options.start || process.hrtime(); - const timeout = options.timeout || SELECTION_TIMEOUT; - const readPreference = options.readPreference; - - if (topology.isConnected({ readPreference })) return callback(); - const hrElapsed = process.hrtime(start); - const elapsed = (hrElapsed[0] * 1e9 + hrElapsed[1]) / 1e6; - if (elapsed > timeout) return callback(new MongoError('Timed out waiting for connection')); - waitForTopologyConnected(topology, options, callback); - }, 500); // this is an arbitrary wait time to allow SDAM to transition -} - -function processNewChange(changeStream, change, callback) { - const cursor = changeStream.cursor; - - if (changeStream.closed) { - if (callback) callback(new MongoError('ChangeStream is closed')); - return; - } - - if (change && !change._id) { - const noResumeTokenError = new Error( - 'A change stream document has been received that lacks a resume token (_id).' - ); - - if (!callback) return changeStream.emit('error', noResumeTokenError); - return callback(noResumeTokenError); - } - - // cache the resume token - cursor.cacheResumeToken(change._id); - - // wipe the startAtOperationTime if there was one so that there won't be a conflict - // between resumeToken and startAtOperationTime if we need to reconnect the cursor - changeStream.options.startAtOperationTime = undefined; - - // Return the change - if (!callback) return changeStream.emit('change', change); - return callback(undefined, change); -} - -function processError(changeStream, error, callback) { - const topology = changeStream.topology; - const cursor = changeStream.cursor; - - // If the change stream has been closed explictly, do not process error. - if (changeStream.closed) { - if (callback) callback(new MongoError('ChangeStream is closed')); - return; - } - - // if the resume succeeds, continue with the new cursor - function resumeWithCursor(newCursor) { - changeStream.cursor = newCursor; - processResumeQueue(changeStream); - } - - // otherwise, raise an error and close the change stream - function unresumableError(err) { - if (!callback) { - changeStream.emit('error', err); - changeStream.emit('close'); - } - processResumeQueue(changeStream, err); - changeStream.closed = true; - } - - if (cursor && isResumableError(error, maxWireVersion(cursor.server))) { - changeStream.cursor = undefined; - - // stop listening to all events from old cursor - ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); - - // close internal cursor, ignore errors - cursor.close(); - - waitForTopologyConnected(topology, { readPreference: cursor.options.readPreference }, err => { - // if the topology can't reconnect, close the stream - if (err) return unresumableError(err); - - // create a new cursor, preserving the old cursor's options - const newCursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); - - // attempt to continue in emitter mode - if (!callback) return resumeWithCursor(newCursor); - - // attempt to continue in iterator mode - newCursor.hasNext(err => { - // if there's an error immediately after resuming, close the stream - if (err) return unresumableError(err); - resumeWithCursor(newCursor); - }); - }); - return; - } - - if (!callback) return changeStream.emit('error', error); - return callback(error); -} - -/** - * Safely provides a cursor across resume attempts - * - * @param {ChangeStream} changeStream the parent ChangeStream - * @param {function} callback gets the cursor or error - * @param {ChangeStreamCursor} [oldCursor] when resuming from an error, carry over options from previous cursor - */ -function getCursor(changeStream, callback) { - if (changeStream.isClosed()) { - callback(new MongoError('ChangeStream is closed.')); - return; - } - - // if a cursor exists and it is open, return it - if (changeStream.cursor) { - callback(undefined, changeStream.cursor); - return; - } - - // no cursor, queue callback until topology reconnects - changeStream[kResumeQueue].push(callback); -} - -/** - * Drain the resume queue when a new has become available - * - * @param {ChangeStream} changeStream the parent ChangeStream - * @param {ChangeStreamCursor?} changeStream.cursor the new cursor - * @param {Error} [err] error getting a new cursor - */ -function processResumeQueue(changeStream, err) { - while (changeStream[kResumeQueue].length) { - const request = changeStream[kResumeQueue].pop(); - if (changeStream.isClosed() && !err) { - request(new MongoError('Change Stream is not open.')); - return; - } - request(err, changeStream.cursor); - } -} - -/** - * The callback format for results - * @callback ChangeStream~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -module.exports = ChangeStream; diff --git a/node_modules/mongodb/lib/cmap/connection.js b/node_modules/mongodb/lib/cmap/connection.js deleted file mode 100644 index bec3aca..0000000 --- a/node_modules/mongodb/lib/cmap/connection.js +++ /dev/null @@ -1,377 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'); -const MessageStream = require('./message_stream'); -const MongoError = require('../core/error').MongoError; -const MongoNetworkError = require('../core/error').MongoNetworkError; -const MongoWriteConcernError = require('../core/error').MongoWriteConcernError; -const CommandResult = require('../core/connection/command_result'); -const StreamDescription = require('./stream_description').StreamDescription; -const wp = require('../core/wireprotocol'); -const apm = require('../core/connection/apm'); -const updateSessionFromResponse = require('../core/sessions').updateSessionFromResponse; -const uuidV4 = require('../core/utils').uuidV4; - -const kStream = Symbol('stream'); -const kQueue = Symbol('queue'); -const kMessageStream = Symbol('messageStream'); -const kGeneration = Symbol('generation'); -const kLastUseTime = Symbol('lastUseTime'); -const kClusterTime = Symbol('clusterTime'); -const kDescription = Symbol('description'); -const kIsMaster = Symbol('ismaster'); -const kAutoEncrypter = Symbol('autoEncrypter'); - -class Connection extends EventEmitter { - constructor(stream, options) { - super(options); - - this.id = options.id; - this.address = streamIdentifier(stream); - this.bson = options.bson; - this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - this.monitorCommands = - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false; - this.closed = false; - this.destroyed = false; - - this[kDescription] = new StreamDescription(this.address, options); - this[kGeneration] = options.generation; - this[kLastUseTime] = Date.now(); - - // retain a reference to an `AutoEncrypter` if present - if (options.autoEncrypter) { - this[kAutoEncrypter] = options.autoEncrypter; - } - - // setup parser stream and message handling - this[kQueue] = new Map(); - this[kMessageStream] = new MessageStream(options); - this[kMessageStream].on('message', messageHandler(this)); - this[kStream] = stream; - stream.on('error', () => { - /* ignore errors, listen to `close` instead */ - }); - - stream.on('close', () => { - if (this.closed) { - return; - } - - this.closed = true; - this[kQueue].forEach(op => - op.cb(new MongoNetworkError(`connection ${this.id} to ${this.address} closed`)) - ); - this[kQueue].clear(); - - this.emit('close'); - }); - - stream.on('timeout', () => { - if (this.closed) { - return; - } - - stream.destroy(); - this.closed = true; - this[kQueue].forEach(op => - op.cb(new MongoNetworkError(`connection ${this.id} to ${this.address} timed out`)) - ); - this[kQueue].clear(); - - this.emit('close'); - }); - - // hook the message stream up to the passed in stream - stream.pipe(this[kMessageStream]); - this[kMessageStream].pipe(stream); - } - - get description() { - return this[kDescription]; - } - - get ismaster() { - return this[kIsMaster]; - } - - // the `connect` method stores the result of the handshake ismaster on the connection - set ismaster(response) { - this[kDescription].receiveResponse(response); - - // TODO: remove this, and only use the `StreamDescription` in the future - this[kIsMaster] = response; - } - - get generation() { - return this[kGeneration] || 0; - } - - get idleTime() { - return Date.now() - this[kLastUseTime]; - } - - get clusterTime() { - return this[kClusterTime]; - } - - get stream() { - return this[kStream]; - } - - markAvailable() { - this[kLastUseTime] = Date.now(); - } - - destroy(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = Object.assign({ force: false }, options); - if (this[kStream] == null || this.destroyed) { - this.destroyed = true; - if (typeof callback === 'function') { - callback(); - } - - return; - } - - if (options.force) { - this[kStream].destroy(); - this.destroyed = true; - if (typeof callback === 'function') { - callback(); - } - - return; - } - - this[kStream].end(err => { - this.destroyed = true; - if (typeof callback === 'function') { - callback(err); - } - }); - } - - // Wire protocol methods - command(ns, cmd, options, callback) { - wp.command(makeServerTrampoline(this), ns, cmd, options, callback); - } - - query(ns, cmd, cursorState, options, callback) { - wp.query(makeServerTrampoline(this), ns, cmd, cursorState, options, callback); - } - - getMore(ns, cursorState, batchSize, options, callback) { - wp.getMore(makeServerTrampoline(this), ns, cursorState, batchSize, options, callback); - } - - killCursors(ns, cursorState, callback) { - wp.killCursors(makeServerTrampoline(this), ns, cursorState, callback); - } - - insert(ns, ops, options, callback) { - wp.insert(makeServerTrampoline(this), ns, ops, options, callback); - } - - update(ns, ops, options, callback) { - wp.update(makeServerTrampoline(this), ns, ops, options, callback); - } - - remove(ns, ops, options, callback) { - wp.remove(makeServerTrampoline(this), ns, ops, options, callback); - } -} - -/// This lets us emulate a legacy `Server` instance so we can work with the existing wire -/// protocol methods. Eventually, the operation executor will return a `Connection` to execute -/// against. -function makeServerTrampoline(connection) { - const server = { - description: connection.description, - clusterTime: connection[kClusterTime], - s: { - bson: connection.bson, - pool: { write: write.bind(connection), isConnected: () => true } - } - }; - - if (connection[kAutoEncrypter]) { - server.autoEncrypter = connection[kAutoEncrypter]; - } - - return server; -} - -function messageHandler(conn) { - return function messageHandler(message) { - // always emit the message, in case we are streaming - conn.emit('message', message); - if (!conn[kQueue].has(message.responseTo)) { - return; - } - - const operationDescription = conn[kQueue].get(message.responseTo); - - // SERVER-45775: For exhaust responses we should be able to use the same requestId to - // track response, however the server currently synthetically produces remote requests - // making the `responseTo` change on each response - conn[kQueue].delete(message.responseTo); - if (message.moreToCome) { - // requeue the callback for next synthetic request - conn[kQueue].set(message.requestId, operationDescription); - } - - const callback = operationDescription.cb; - if (operationDescription.socketTimeoutOverride) { - conn[kStream].setTimeout(conn.socketTimeout); - } - - try { - // Pass in the entire description because it has BSON parsing options - message.parse(operationDescription); - } catch (err) { - callback(new MongoError(err)); - return; - } - - if (message.documents[0]) { - const document = message.documents[0]; - const session = operationDescription.session; - if (session) { - updateSessionFromResponse(session, document); - } - - if (document.$clusterTime) { - conn[kClusterTime] = document.$clusterTime; - conn.emit('clusterTimeReceived', document.$clusterTime); - } - - if (operationDescription.command) { - if (document.writeConcernError) { - callback(new MongoWriteConcernError(document.writeConcernError, document)); - return; - } - - if (document.ok === 0 || document.$err || document.errmsg || document.code) { - callback(new MongoError(document)); - return; - } - } - } - - // NODE-2382: reenable in our glorious non-leaky abstraction future - // callback(null, operationDescription.fullResult ? message : message.documents[0]); - - callback( - undefined, - new CommandResult( - operationDescription.fullResult ? message : message.documents[0], - conn, - message - ) - ); - }; -} - -function streamIdentifier(stream) { - if (typeof stream.address === 'function') { - return `${stream.remoteAddress}:${stream.remotePort}`; - } - - return uuidV4().toString('hex'); -} - -// Not meant to be called directly, the wire protocol methods call this assuming it is a `Pool` instance -function write(command, options, callback) { - if (typeof options === 'function') { - callback = options; - } - - options = options || {}; - const operationDescription = { - requestId: command.requestId, - cb: callback, - session: options.session, - fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false, - noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false, - documentsReturnedIn: options.documentsReturnedIn, - command: !!options.command, - - // for BSON parsing - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, - raw: typeof options.raw === 'boolean' ? options.raw : false - }; - - if (this[kDescription] && this[kDescription].compressor) { - operationDescription.agreedCompressor = this[kDescription].compressor; - - if (this[kDescription].zlibCompressionLevel) { - operationDescription.zlibCompressionLevel = this[kDescription].zlibCompressionLevel; - } - } - - if (typeof options.socketTimeout === 'number') { - operationDescription.socketTimeoutOverride = true; - this[kStream].setTimeout(options.socketTimeout); - } - - // if command monitoring is enabled we need to modify the callback here - if (this.monitorCommands) { - this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); - - operationDescription.started = process.hrtime(); - operationDescription.cb = (err, reply) => { - if (err) { - this.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, err, operationDescription.started) - ); - } else { - if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { - this.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, reply.result, operationDescription.started) - ); - } else { - this.emit( - 'commandSucceeded', - new apm.CommandSucceededEvent(this, command, reply, operationDescription.started) - ); - } - } - - if (typeof callback === 'function') { - callback(err, reply); - } - }; - } - - if (!operationDescription.noResponse) { - this[kQueue].set(operationDescription.requestId, operationDescription); - } - - try { - this[kMessageStream].writeCommand(command, operationDescription); - } catch (e) { - if (!operationDescription.noResponse) { - this[kQueue].delete(operationDescription.requestId); - operationDescription.cb(e); - return; - } - } - - if (operationDescription.noResponse) { - operationDescription.cb(); - } -} - -module.exports = { - Connection -}; diff --git a/node_modules/mongodb/lib/cmap/connection_pool.js b/node_modules/mongodb/lib/cmap/connection_pool.js deleted file mode 100644 index 21e463a..0000000 --- a/node_modules/mongodb/lib/cmap/connection_pool.js +++ /dev/null @@ -1,601 +0,0 @@ -'use strict'; - -const Denque = require('denque'); -const EventEmitter = require('events').EventEmitter; -const Logger = require('../core/connection/logger'); -const makeCounter = require('../utils').makeCounter; -const MongoError = require('../core/error').MongoError; -const Connection = require('./connection').Connection; -const eachAsync = require('../core/utils').eachAsync; -const connect = require('../core/connection/connect'); -const relayEvents = require('../core/utils').relayEvents; - -const errors = require('./errors'); -const PoolClosedError = errors.PoolClosedError; -const WaitQueueTimeoutError = errors.WaitQueueTimeoutError; - -const events = require('./events'); -const ConnectionPoolCreatedEvent = events.ConnectionPoolCreatedEvent; -const ConnectionPoolClosedEvent = events.ConnectionPoolClosedEvent; -const ConnectionCreatedEvent = events.ConnectionCreatedEvent; -const ConnectionReadyEvent = events.ConnectionReadyEvent; -const ConnectionClosedEvent = events.ConnectionClosedEvent; -const ConnectionCheckOutStartedEvent = events.ConnectionCheckOutStartedEvent; -const ConnectionCheckOutFailedEvent = events.ConnectionCheckOutFailedEvent; -const ConnectionCheckedOutEvent = events.ConnectionCheckedOutEvent; -const ConnectionCheckedInEvent = events.ConnectionCheckedInEvent; -const ConnectionPoolClearedEvent = events.ConnectionPoolClearedEvent; - -const kLogger = Symbol('logger'); -const kConnections = Symbol('connections'); -const kPermits = Symbol('permits'); -const kMinPoolSizeTimer = Symbol('minPoolSizeTimer'); -const kGeneration = Symbol('generation'); -const kConnectionCounter = Symbol('connectionCounter'); -const kCancellationToken = Symbol('cancellationToken'); -const kWaitQueue = Symbol('waitQueue'); -const kCancelled = Symbol('cancelled'); - -const VALID_POOL_OPTIONS = new Set([ - // `connect` options - 'ssl', - 'bson', - 'connectionType', - 'monitorCommands', - 'socketTimeout', - 'credentials', - 'compression', - - // node Net options - 'host', - 'port', - 'localAddress', - 'localPort', - 'family', - 'hints', - 'lookup', - 'path', - - // node TLS options - 'ca', - 'cert', - 'sigalgs', - 'ciphers', - 'clientCertEngine', - 'crl', - 'dhparam', - 'ecdhCurve', - 'honorCipherOrder', - 'key', - 'privateKeyEngine', - 'privateKeyIdentifier', - 'maxVersion', - 'minVersion', - 'passphrase', - 'pfx', - 'secureOptions', - 'secureProtocol', - 'sessionIdContext', - 'allowHalfOpen', - 'rejectUnauthorized', - 'pskCallback', - 'ALPNProtocols', - 'servername', - 'checkServerIdentity', - 'session', - 'minDHSize', - 'secureContext', - - // spec options - 'maxPoolSize', - 'minPoolSize', - 'maxIdleTimeMS', - 'waitQueueTimeoutMS' -]); - -function resolveOptions(options, defaults) { - const newOptions = Array.from(VALID_POOL_OPTIONS).reduce((obj, key) => { - if (options.hasOwnProperty(key)) { - obj[key] = options[key]; - } - - return obj; - }, {}); - - return Object.freeze(Object.assign({}, defaults, newOptions)); -} - -/** - * Configuration options for drivers wrapping the node driver. - * - * @typedef {Object} ConnectionPoolOptions - * @property - * @property {string} [host] The host to connect to - * @property {number} [port] The port to connect to - * @property {bson} [bson] The BSON instance to use for new connections - * @property {number} [maxPoolSize=100] The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. - * @property {number} [minPoolSize=0] The minimum number of connections that MUST exist at any moment in a single connection pool. - * @property {number} [maxIdleTimeMS] The maximum amount of time a connection should remain idle in the connection pool before being marked idle. - * @property {number} [waitQueueTimeoutMS=0] The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. - */ - -/** - * A pool of connections which dynamically resizes, and emit events related to pool activity - * - * @property {number} generation An integer representing the SDAM generation of the pool - * @property {number} totalConnectionCount An integer expressing how many total connections (active + in use) the pool currently has - * @property {number} availableConnectionCount An integer expressing how many connections are currently available in the pool. - * @property {string} address The address of the endpoint the pool is connected to - * - * @emits ConnectionPool#connectionPoolCreated - * @emits ConnectionPool#connectionPoolClosed - * @emits ConnectionPool#connectionCreated - * @emits ConnectionPool#connectionReady - * @emits ConnectionPool#connectionClosed - * @emits ConnectionPool#connectionCheckOutStarted - * @emits ConnectionPool#connectionCheckOutFailed - * @emits ConnectionPool#connectionCheckedOut - * @emits ConnectionPool#connectionCheckedIn - * @emits ConnectionPool#connectionPoolCleared - */ -class ConnectionPool extends EventEmitter { - /** - * Create a new Connection Pool - * - * @param {ConnectionPoolOptions} options - */ - constructor(options) { - super(); - options = options || {}; - - this.closed = false; - this.options = resolveOptions(options, { - connectionType: Connection, - maxPoolSize: typeof options.maxPoolSize === 'number' ? options.maxPoolSize : 100, - minPoolSize: typeof options.minPoolSize === 'number' ? options.minPoolSize : 0, - maxIdleTimeMS: typeof options.maxIdleTimeMS === 'number' ? options.maxIdleTimeMS : 0, - waitQueueTimeoutMS: - typeof options.waitQueueTimeoutMS === 'number' ? options.waitQueueTimeoutMS : 0, - autoEncrypter: options.autoEncrypter, - metadata: options.metadata - }); - - if (options.minSize > options.maxSize) { - throw new TypeError( - 'Connection pool minimum size must not be greater than maxiumum pool size' - ); - } - - this[kLogger] = Logger('ConnectionPool', options); - this[kConnections] = new Denque(); - this[kPermits] = this.options.maxPoolSize; - this[kMinPoolSizeTimer] = undefined; - this[kGeneration] = 0; - this[kConnectionCounter] = makeCounter(1); - this[kCancellationToken] = new EventEmitter(); - this[kCancellationToken].setMaxListeners(Infinity); - this[kWaitQueue] = new Denque(); - - process.nextTick(() => { - this.emit('connectionPoolCreated', new ConnectionPoolCreatedEvent(this)); - ensureMinPoolSize(this); - }); - } - - get address() { - return `${this.options.host}:${this.options.port}`; - } - - get generation() { - return this[kGeneration]; - } - - get totalConnectionCount() { - return this[kConnections].length + (this.options.maxPoolSize - this[kPermits]); - } - - get availableConnectionCount() { - return this[kConnections].length; - } - - get waitQueueSize() { - return this[kWaitQueue].length; - } - - /** - * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it - * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or - * explicitly destroyed by the new owner. - * - * @param {ConnectionPool~checkOutCallback} callback - */ - checkOut(callback) { - this.emit('connectionCheckOutStarted', new ConnectionCheckOutStartedEvent(this)); - - if (this.closed) { - this.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(this, 'poolClosed')); - callback(new PoolClosedError(this)); - return; - } - - // add this request to the wait queue - const waitQueueMember = { callback }; - - const pool = this; - const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS; - if (waitQueueTimeoutMS) { - waitQueueMember.timer = setTimeout(() => { - waitQueueMember[kCancelled] = true; - waitQueueMember.timer = undefined; - - pool.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(pool, 'timeout')); - waitQueueMember.callback(new WaitQueueTimeoutError(pool)); - }, waitQueueTimeoutMS); - } - - // place the member at the end of the wait queue - this[kWaitQueue].push(waitQueueMember); - - // process the wait queue - processWaitQueue(this); - } - - /** - * Check a connection into the pool. - * - * @param {Connection} connection The connection to check in - */ - checkIn(connection) { - const poolClosed = this.closed; - const stale = connectionIsStale(this, connection); - const willDestroy = !!(poolClosed || stale || connection.closed); - - // Properly adjust state of connection - if (!willDestroy) { - connection.markAvailable(); - - this[kConnections].push(connection); - } - - this.emit('connectionCheckedIn', new ConnectionCheckedInEvent(this, connection)); - - if (willDestroy) { - const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; - destroyConnection(this, connection, reason); - } - - processWaitQueue(this); - } - - /** - * Clear the pool - * - * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a - * previous generation will eventually be pruned during subsequent checkouts. - */ - clear() { - this[kGeneration] += 1; - this.emit('connectionPoolCleared', new ConnectionPoolClearedEvent(this)); - } - - /** - * Close the pool - * - * @param {object} [options] Optional settings - * @param {boolean} [options.force] Force close connections - * @param {Function} callback - */ - close(options, callback) { - if (typeof options === 'function') { - callback = options; - } - - options = Object.assign({ force: false }, options); - if (this.closed) { - return callback(); - } - - // immediately cancel any in-flight connections - this[kCancellationToken].emit('cancel'); - - // drain the wait queue - while (this.waitQueueSize) { - const waitQueueMember = this[kWaitQueue].pop(); - clearTimeout(waitQueueMember.timer); - if (!waitQueueMember[kCancelled]) { - waitQueueMember.callback(new MongoError('connection pool closed')); - } - } - - // clear the min pool size timer - if (this[kMinPoolSizeTimer]) { - clearTimeout(this[kMinPoolSizeTimer]); - } - - // end the connection counter - if (typeof this[kConnectionCounter].return === 'function') { - this[kConnectionCounter].return(); - } - - // mark the pool as closed immediately - this.closed = true; - - eachAsync( - this[kConnections].toArray(), - (conn, cb) => { - this.emit('connectionClosed', new ConnectionClosedEvent(this, conn, 'poolClosed')); - conn.destroy(options, cb); - }, - err => { - this[kConnections].clear(); - this.emit('connectionPoolClosed', new ConnectionPoolClosedEvent(this)); - callback(err); - } - ); - } - - /** - * Runs a lambda with an implicitly checked out connection, checking that connection back in when the lambda - * has completed by calling back. - * - * NOTE: please note the required signature of `fn` - * - * @param {ConnectionPool~withConnectionCallback} fn A function which operates on a managed connection - * @param {Function} callback The original callback - * @return {Promise} - */ - withConnection(fn, callback) { - this.checkOut((err, conn) => { - // don't callback with `err` here, we might want to act upon it inside `fn` - - fn(err, conn, (fnErr, result) => { - if (typeof callback === 'function') { - if (fnErr) { - callback(fnErr); - } else { - callback(undefined, result); - } - } - - if (conn) { - this.checkIn(conn); - } - }); - }); - } -} - -function ensureMinPoolSize(pool) { - if (pool.closed || pool.options.minPoolSize === 0) { - return; - } - - const minPoolSize = pool.options.minPoolSize; - for (let i = pool.totalConnectionCount; i < minPoolSize; ++i) { - createConnection(pool); - } - - pool[kMinPoolSizeTimer] = setTimeout(() => ensureMinPoolSize(pool), 10); -} - -function connectionIsStale(pool, connection) { - return connection.generation !== pool[kGeneration]; -} - -function connectionIsIdle(pool, connection) { - return !!(pool.options.maxIdleTimeMS && connection.idleTime > pool.options.maxIdleTimeMS); -} - -function createConnection(pool, callback) { - const connectOptions = Object.assign( - { - id: pool[kConnectionCounter].next().value, - generation: pool[kGeneration] - }, - pool.options - ); - - pool[kPermits]--; - connect(connectOptions, pool[kCancellationToken], (err, connection) => { - if (err) { - pool[kPermits]++; - pool[kLogger].debug(`connection attempt failed with error [${JSON.stringify(err)}]`); - if (typeof callback === 'function') { - callback(err); - } - - return; - } - - // The pool might have closed since we started trying to create a connection - if (pool.closed) { - connection.destroy({ force: true }); - return; - } - - // forward all events from the connection to the pool - relayEvents(connection, pool, [ - 'commandStarted', - 'commandFailed', - 'commandSucceeded', - 'clusterTimeReceived' - ]); - - pool.emit('connectionCreated', new ConnectionCreatedEvent(pool, connection)); - - connection.markAvailable(); - pool.emit('connectionReady', new ConnectionReadyEvent(pool, connection)); - - // if a callback has been provided, check out the connection immediately - if (typeof callback === 'function') { - callback(undefined, connection); - return; - } - - // otherwise add it to the pool for later acquisition, and try to process the wait queue - pool[kConnections].push(connection); - processWaitQueue(pool); - }); -} - -function destroyConnection(pool, connection, reason) { - pool.emit('connectionClosed', new ConnectionClosedEvent(pool, connection, reason)); - - // allow more connections to be created - pool[kPermits]++; - - // destroy the connection - process.nextTick(() => connection.destroy()); -} - -function processWaitQueue(pool) { - if (pool.closed) { - return; - } - - while (pool.waitQueueSize) { - const waitQueueMember = pool[kWaitQueue].peekFront(); - if (waitQueueMember[kCancelled]) { - pool[kWaitQueue].shift(); - continue; - } - - if (!pool.availableConnectionCount) { - break; - } - - const connection = pool[kConnections].shift(); - const isStale = connectionIsStale(pool, connection); - const isIdle = connectionIsIdle(pool, connection); - if (!isStale && !isIdle && !connection.closed) { - pool.emit('connectionCheckedOut', new ConnectionCheckedOutEvent(pool, connection)); - clearTimeout(waitQueueMember.timer); - pool[kWaitQueue].shift(); - waitQueueMember.callback(undefined, connection); - return; - } - - const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; - destroyConnection(pool, connection, reason); - } - - const maxPoolSize = pool.options.maxPoolSize; - if (pool.waitQueueSize && (maxPoolSize <= 0 || pool.totalConnectionCount < maxPoolSize)) { - createConnection(pool, (err, connection) => { - const waitQueueMember = pool[kWaitQueue].shift(); - if (waitQueueMember == null) { - if (err == null) { - pool[kConnections].push(connection); - } - - return; - } - - if (waitQueueMember[kCancelled]) { - return; - } - - if (err) { - pool.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(pool, err)); - } else { - pool.emit('connectionCheckedOut', new ConnectionCheckedOutEvent(pool, connection)); - } - - clearTimeout(waitQueueMember.timer); - waitQueueMember.callback(err, connection); - }); - - return; - } -} - -/** - * A callback provided to `withConnection` - * - * @callback ConnectionPool~withConnectionCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Connection} connection The managed connection which was checked out of the pool. - * @param {Function} callback A function to call back after connection management is complete - */ - -/** - * A callback provided to `checkOut` - * - * @callback ConnectionPool~checkOutCallback - * @param {MongoError} error An error instance representing the error during checkout - * @param {Connection} connection A connection from the pool - */ - -/** - * Emitted once when the connection pool is created - * - * @event ConnectionPool#connectionPoolCreated - * @type {PoolCreatedEvent} - */ - -/** - * Emitted once when the connection pool is closed - * - * @event ConnectionPool#connectionPoolClosed - * @type {PoolClosedEvent} - */ - -/** - * Emitted each time a connection is created - * - * @event ConnectionPool#connectionCreated - * @type {ConnectionCreatedEvent} - */ - -/** - * Emitted when a connection becomes established, and is ready to use - * - * @event ConnectionPool#connectionReady - * @type {ConnectionReadyEvent} - */ - -/** - * Emitted when a connection is closed - * - * @event ConnectionPool#connectionClosed - * @type {ConnectionClosedEvent} - */ - -/** - * Emitted when an attempt to check out a connection begins - * - * @event ConnectionPool#connectionCheckOutStarted - * @type {ConnectionCheckOutStartedEvent} - */ - -/** - * Emitted when an attempt to check out a connection fails - * - * @event ConnectionPool#connectionCheckOutFailed - * @type {ConnectionCheckOutFailedEvent} - */ - -/** - * Emitted each time a connection is successfully checked out of the connection pool - * - * @event ConnectionPool#connectionCheckedOut - * @type {ConnectionCheckedOutEvent} - */ - -/** - * Emitted each time a connection is successfully checked into the connection pool - * - * @event ConnectionPool#connectionCheckedIn - * @type {ConnectionCheckedInEvent} - */ - -/** - * Emitted each time the connection pool is cleared and it's generation incremented - * - * @event ConnectionPool#connectionPoolCleared - * @type {PoolClearedEvent} - */ - -module.exports = { - ConnectionPool -}; diff --git a/node_modules/mongodb/lib/cmap/errors.js b/node_modules/mongodb/lib/cmap/errors.js deleted file mode 100644 index d933019..0000000 --- a/node_modules/mongodb/lib/cmap/errors.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; -const MongoError = require('../core/error').MongoError; - -/** - * An error indicating a connection pool is closed - * - * @property {string} address The address of the connection pool - * @extends MongoError - */ -class PoolClosedError extends MongoError { - constructor(pool) { - super('Attempted to check out a connection from closed connection pool'); - this.name = 'MongoPoolClosedError'; - this.address = pool.address; - } -} - -/** - * An error thrown when a request to check out a connection times out - * - * @property {string} address The address of the connection pool - * @extends MongoError - */ -class WaitQueueTimeoutError extends MongoError { - constructor(pool) { - super('Timed out while checking out a connection from connection pool'); - this.name = 'MongoWaitQueueTimeoutError'; - this.address = pool.address; - } -} - -module.exports = { - PoolClosedError, - WaitQueueTimeoutError -}; diff --git a/node_modules/mongodb/lib/cmap/events.js b/node_modules/mongodb/lib/cmap/events.js deleted file mode 100644 index dcc8b67..0000000 --- a/node_modules/mongodb/lib/cmap/events.js +++ /dev/null @@ -1,154 +0,0 @@ -'use strict'; - -/** - * The base class for all monitoring events published from the connection pool - * - * @property {number} time A timestamp when the event was created - * @property {string} address The address (host/port pair) of the pool - */ -class ConnectionPoolMonitoringEvent { - constructor(pool) { - this.time = new Date(); - this.address = pool.address; - } -} - -/** - * An event published when a connection pool is created - * - * @property {Object} options The options used to create this connection pool - */ -class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); - this.options = pool.options; - } -} - -/** - * An event published when a connection pool is closed - */ -class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); - } -} - -/** - * An event published when a connection pool creates a new connection - * - * @property {number} connectionId A monotonically increasing, per-pool id for the newly created connection - */ -class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection) { - super(pool); - this.connectionId = connection.id; - } -} - -/** - * An event published when a connection is ready for use - * - * @property {number} connectionId The id of the connection - */ -class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection) { - super(pool); - this.connectionId = connection.id; - } -} - -/** - * An event published when a connection is closed - * - * @property {number} connectionId The id of the connection - * @property {string} reason The reason the connection was closed - */ -class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection, reason) { - super(pool); - this.connectionId = connection.id; - this.reason = reason || 'unknown'; - } -} - -/** - * An event published when a request to check a connection out begins - */ -class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); - } -} - -/** - * An event published when a request to check a connection out fails - * - * @property {string} reason The reason the attempt to check out failed - */ -class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, reason) { - super(pool); - this.reason = reason; - } -} - -/** - * An event published when a connection is checked out of the connection pool - * - * @property {number} connectionId The id of the connection - */ -class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection) { - super(pool); - this.connectionId = connection.id; - } -} - -/** - * An event published when a connection is checked into the connection pool - * - * @property {number} connectionId The id of the connection - */ -class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection) { - super(pool); - this.connectionId = connection.id; - } -} - -/** - * An event published when a connection pool is cleared - */ -class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); - } -} - -const CMAP_EVENT_NAMES = [ - 'connectionPoolCreated', - 'connectionPoolClosed', - 'connectionCreated', - 'connectionReady', - 'connectionClosed', - 'connectionCheckOutStarted', - 'connectionCheckOutFailed', - 'connectionCheckedOut', - 'connectionCheckedIn', - 'connectionPoolCleared' -]; - -module.exports = { - CMAP_EVENT_NAMES, - ConnectionPoolCreatedEvent, - ConnectionPoolClosedEvent, - ConnectionCreatedEvent, - ConnectionReadyEvent, - ConnectionClosedEvent, - ConnectionCheckOutStartedEvent, - ConnectionCheckOutFailedEvent, - ConnectionCheckedOutEvent, - ConnectionCheckedInEvent, - ConnectionPoolClearedEvent -}; diff --git a/node_modules/mongodb/lib/cmap/message_stream.js b/node_modules/mongodb/lib/cmap/message_stream.js deleted file mode 100644 index c8f458e..0000000 --- a/node_modules/mongodb/lib/cmap/message_stream.js +++ /dev/null @@ -1,196 +0,0 @@ -'use strict'; - -const Duplex = require('stream').Duplex; -const BufferList = require('bl'); -const MongoParseError = require('../core/error').MongoParseError; -const decompress = require('../core/wireprotocol/compression').decompress; -const Response = require('../core/connection/commands').Response; -const BinMsg = require('../core/connection/msg').BinMsg; -const MongoError = require('../core/error').MongoError; -const OP_COMPRESSED = require('../core/wireprotocol/shared').opcodes.OP_COMPRESSED; -const OP_MSG = require('../core/wireprotocol/shared').opcodes.OP_MSG; -const MESSAGE_HEADER_SIZE = require('../core/wireprotocol/shared').MESSAGE_HEADER_SIZE; -const COMPRESSION_DETAILS_SIZE = require('../core/wireprotocol/shared').COMPRESSION_DETAILS_SIZE; -const opcodes = require('../core/wireprotocol/shared').opcodes; -const compress = require('../core/wireprotocol/compression').compress; -const compressorIDs = require('../core/wireprotocol/compression').compressorIDs; -const uncompressibleCommands = require('../core/wireprotocol/compression').uncompressibleCommands; -const Msg = require('../core/connection/msg').Msg; - -const kDefaultMaxBsonMessageSize = 1024 * 1024 * 16 * 4; -const kBuffer = Symbol('buffer'); - -/** - * A duplex stream that is capable of reading and writing raw wire protocol messages, with - * support for optional compression - */ -class MessageStream extends Duplex { - constructor(options) { - options = options || {}; - super(options); - - this.bson = options.bson; - this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize; - - this[kBuffer] = new BufferList(); - } - - _write(chunk, _, callback) { - const buffer = this[kBuffer]; - buffer.append(chunk); - - processIncomingData(this, callback); - } - - _read(/* size */) { - // NOTE: This implementation is empty because we explicitly push data to be read - // when `writeMessage` is called. - return; - } - - writeCommand(command, operationDescription) { - // TODO: agreed compressor should live in `StreamDescription` - const shouldCompress = operationDescription && !!operationDescription.agreedCompressor; - if (!shouldCompress || !canCompress(command)) { - const data = command.toBin(); - this.push(Array.isArray(data) ? Buffer.concat(data) : data); - return; - } - - // otherwise, compress the message - const concatenatedOriginalCommandBuffer = Buffer.concat(command.toBin()); - const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); - - // Extract information needed for OP_COMPRESSED from the uncompressed message - const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); - - // Compress the message body - compress({ options: operationDescription }, messageToBeCompressed, (err, compressedMessage) => { - if (err) { - operationDescription.cb(err, null); - return; - } - - // Create the msgHeader of OP_COMPRESSED - const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); - msgHeader.writeInt32LE( - MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, - 0 - ); // messageLength - msgHeader.writeInt32LE(command.requestId, 4); // requestID - msgHeader.writeInt32LE(0, 8); // responseTo (zero) - msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode - - // Create the compression details of OP_COMPRESSED - const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); - compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode - compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader - compressionDetails.writeUInt8(compressorIDs[operationDescription.agreedCompressor], 8); // compressorID - - this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); - }); - } -} - -// Return whether a command contains an uncompressible command term -// Will return true if command contains no uncompressible command terms -function canCompress(command) { - const commandDoc = command instanceof Msg ? command.command : command.query; - const commandName = Object.keys(commandDoc)[0]; - return !uncompressibleCommands.has(commandName); -} - -function processIncomingData(stream, callback) { - const buffer = stream[kBuffer]; - if (buffer.length < 4) { - callback(); - return; - } - - const sizeOfMessage = buffer.readInt32LE(0); - if (sizeOfMessage < 0) { - callback(new MongoParseError(`Invalid message size: ${sizeOfMessage}`)); - return; - } - - if (sizeOfMessage > stream.maxBsonMessageSize) { - callback( - new MongoParseError( - `Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}` - ) - ); - return; - } - - if (sizeOfMessage > buffer.length) { - callback(); - return; - } - - const message = buffer.slice(0, sizeOfMessage); - buffer.consume(sizeOfMessage); - - const messageHeader = { - length: message.readInt32LE(0), - requestId: message.readInt32LE(4), - responseTo: message.readInt32LE(8), - opCode: message.readInt32LE(12) - }; - - let ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; - const responseOptions = stream.responseOptions; - if (messageHeader.opCode !== OP_COMPRESSED) { - const messageBody = message.slice(MESSAGE_HEADER_SIZE); - stream.emit( - 'message', - new ResponseType(stream.bson, message, messageHeader, messageBody, responseOptions) - ); - - if (buffer.length >= 4) { - processIncomingData(stream, callback); - } else { - callback(); - } - - return; - } - - messageHeader.fromCompressed = true; - messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE); - messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4); - const compressorID = message[MESSAGE_HEADER_SIZE + 8]; - const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9); - - // recalculate based on wrapped opcode - ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; - - decompress(compressorID, compressedBuffer, (err, messageBody) => { - if (err) { - callback(err); - return; - } - - if (messageBody.length !== messageHeader.length) { - callback( - new MongoError( - 'Decompressing a compressed message from the server failed. The message is corrupt.' - ) - ); - - return; - } - - stream.emit( - 'message', - new ResponseType(stream.bson, message, messageHeader, messageBody, responseOptions) - ); - - if (buffer.length >= 4) { - processIncomingData(stream, callback); - } else { - callback(); - } - }); -} - -module.exports = MessageStream; diff --git a/node_modules/mongodb/lib/cmap/stream_description.js b/node_modules/mongodb/lib/cmap/stream_description.js deleted file mode 100644 index e806a5f..0000000 --- a/node_modules/mongodb/lib/cmap/stream_description.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; -const parseServerType = require('../core/sdam/server_description').parseServerType; - -const RESPONSE_FIELDS = [ - 'minWireVersion', - 'maxWireVersion', - 'maxBsonObjectSize', - 'maxMessageSizeBytes', - 'maxWriteBatchSize', - '__nodejs_mock_server__' -]; - -class StreamDescription { - constructor(address, options) { - this.address = address; - this.type = parseServerType(null); - this.minWireVersion = undefined; - this.maxWireVersion = undefined; - this.maxBsonObjectSize = 16777216; - this.maxMessageSizeBytes = 48000000; - this.maxWriteBatchSize = 100000; - this.compressors = - options && options.compression && Array.isArray(options.compression.compressors) - ? options.compression.compressors - : []; - } - - receiveResponse(response) { - this.type = parseServerType(response); - - RESPONSE_FIELDS.forEach(field => { - if (typeof response[field] !== 'undefined') { - this[field] = response[field]; - } - }); - - if (response.compression) { - this.compressor = this.compressors.filter(c => response.compression.indexOf(c) !== -1)[0]; - } - } -} - -module.exports = { - StreamDescription -}; diff --git a/node_modules/mongodb/lib/collection.js b/node_modules/mongodb/lib/collection.js deleted file mode 100644 index bf4861d..0000000 --- a/node_modules/mongodb/lib/collection.js +++ /dev/null @@ -1,2201 +0,0 @@ -'use strict'; - -const deprecate = require('util').deprecate; -const deprecateOptions = require('./utils').deprecateOptions; -const checkCollectionName = require('./utils').checkCollectionName; -const ObjectID = require('./core').BSON.ObjectID; -const MongoError = require('./core').MongoError; -const toError = require('./utils').toError; -const normalizeHintField = require('./utils').normalizeHintField; -const decorateCommand = require('./utils').decorateCommand; -const decorateWithCollation = require('./utils').decorateWithCollation; -const decorateWithReadConcern = require('./utils').decorateWithReadConcern; -const formattedOrderClause = require('./utils').formattedOrderClause; -const ReadPreference = require('./core').ReadPreference; -const unordered = require('./bulk/unordered'); -const ordered = require('./bulk/ordered'); -const ChangeStream = require('./change_stream'); -const executeLegacyOperation = require('./utils').executeLegacyOperation; -const resolveReadPreference = require('./utils').resolveReadPreference; -const WriteConcern = require('./write_concern'); -const ReadConcern = require('./read_concern'); -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const AggregationCursor = require('./aggregation_cursor'); -const CommandCursor = require('./command_cursor'); - -// Operations -const checkForAtomicOperators = require('./operations/collection_ops').checkForAtomicOperators; -const ensureIndex = require('./operations/collection_ops').ensureIndex; -const group = require('./operations/collection_ops').group; -const parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan; -const removeDocuments = require('./operations/common_functions').removeDocuments; -const save = require('./operations/collection_ops').save; -const updateDocuments = require('./operations/common_functions').updateDocuments; - -const AggregateOperation = require('./operations/aggregate'); -const BulkWriteOperation = require('./operations/bulk_write'); -const CountDocumentsOperation = require('./operations/count_documents'); -const CreateIndexOperation = require('./operations/create_index'); -const CreateIndexesOperation = require('./operations/create_indexes'); -const DeleteManyOperation = require('./operations/delete_many'); -const DeleteOneOperation = require('./operations/delete_one'); -const DistinctOperation = require('./operations/distinct'); -const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; -const DropIndexOperation = require('./operations/drop_index'); -const DropIndexesOperation = require('./operations/drop_indexes'); -const EstimatedDocumentCountOperation = require('./operations/estimated_document_count'); -const FindOperation = require('./operations/find'); -const FindOneOperation = require('./operations/find_one'); -const FindAndModifyOperation = require('./operations/find_and_modify'); -const FindOneAndDeleteOperation = require('./operations/find_one_and_delete'); -const FindOneAndReplaceOperation = require('./operations/find_one_and_replace'); -const FindOneAndUpdateOperation = require('./operations/find_one_and_update'); -const GeoHaystackSearchOperation = require('./operations/geo_haystack_search'); -const IndexesOperation = require('./operations/indexes'); -const IndexExistsOperation = require('./operations/index_exists'); -const IndexInformationOperation = require('./operations/index_information'); -const InsertManyOperation = require('./operations/insert_many'); -const InsertOneOperation = require('./operations/insert_one'); -const IsCappedOperation = require('./operations/is_capped'); -const ListIndexesOperation = require('./operations/list_indexes'); -const MapReduceOperation = require('./operations/map_reduce'); -const OptionsOperation = require('./operations/options_operation'); -const RenameOperation = require('./operations/rename'); -const ReIndexOperation = require('./operations/re_index'); -const ReplaceOneOperation = require('./operations/replace_one'); -const StatsOperation = require('./operations/stats'); -const UpdateManyOperation = require('./operations/update_many'); -const UpdateOneOperation = require('./operations/update_one'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection - * allowing for insert/update/remove/find and other command operation on that MongoDB collection. - * - * **COLLECTION Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - */ - -const mergeKeys = ['ignoreUndefined']; - -/** - * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) - * @class - */ -function Collection(db, topology, dbName, name, pkFactory, options) { - checkCollectionName(name); - - // Unpack variables - const internalHint = null; - const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; - const serializeFunctions = - options == null || options.serializeFunctions == null - ? db.s.options.serializeFunctions - : options.serializeFunctions; - const raw = options == null || options.raw == null ? db.s.options.raw : options.raw; - const promoteLongs = - options == null || options.promoteLongs == null - ? db.s.options.promoteLongs - : options.promoteLongs; - const promoteValues = - options == null || options.promoteValues == null - ? db.s.options.promoteValues - : options.promoteValues; - const promoteBuffers = - options == null || options.promoteBuffers == null - ? db.s.options.promoteBuffers - : options.promoteBuffers; - const collectionHint = null; - - const namespace = new MongoDBNamespace(dbName, name); - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Set custom primary key factory if provided - pkFactory = pkFactory == null ? ObjectID : pkFactory; - - // Internal state - this.s = { - // Set custom primary key factory if provided - pkFactory: pkFactory, - // Db - db: db, - // Topology - topology: topology, - // Options - options: options, - // Namespace - namespace: namespace, - // Read preference - readPreference: ReadPreference.fromOptions(options), - // SlaveOK - slaveOk: slaveOk, - // Serialize functions - serializeFunctions: serializeFunctions, - // Raw - raw: raw, - // promoteLongs - promoteLongs: promoteLongs, - // promoteValues - promoteValues: promoteValues, - // promoteBuffers - promoteBuffers: promoteBuffers, - // internalHint - internalHint: internalHint, - // collectionHint - collectionHint: collectionHint, - // Promise library - promiseLibrary: promiseLibrary, - // Read Concern - readConcern: ReadConcern.fromOptions(options), - // Write Concern - writeConcern: WriteConcern.fromOptions(options) - }; -} - -/** - * The name of the database this collection belongs to - * @member {string} dbName - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'dbName', { - enumerable: true, - get: function() { - return this.s.namespace.db; - } -}); - -/** - * The name of this collection - * @member {string} collectionName - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'collectionName', { - enumerable: true, - get: function() { - return this.s.namespace.collection; - } -}); - -/** - * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` - * @member {string} namespace - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'namespace', { - enumerable: true, - get: function() { - return this.s.namespace.toString(); - } -}); - -/** - * The current readConcern of the collection. If not explicitly defined for - * this collection, will be inherited from the parent DB - * @member {ReadConcern} [readConcern] - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'readConcern', { - enumerable: true, - get: function() { - if (this.s.readConcern == null) { - return this.s.db.readConcern; - } - return this.s.readConcern; - } -}); - -/** - * The current readPreference of the collection. If not explicitly defined for - * this collection, will be inherited from the parent DB - * @member {ReadPreference} [readPreference] - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'readPreference', { - enumerable: true, - get: function() { - if (this.s.readPreference == null) { - return this.s.db.readPreference; - } - - return this.s.readPreference; - } -}); - -/** - * The current writeConcern of the collection. If not explicitly defined for - * this collection, will be inherited from the parent DB - * @member {WriteConcern} [writeConcern] - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'writeConcern', { - enumerable: true, - get: function() { - if (this.s.writeConcern == null) { - return this.s.db.writeConcern; - } - return this.s.writeConcern; - } -}); - -/** - * The current index hint for the collection - * @member {object} [hint] - * @memberof Collection# - */ -Object.defineProperty(Collection.prototype, 'hint', { - enumerable: true, - get: function() { - return this.s.collectionHint; - }, - set: function(v) { - this.s.collectionHint = normalizeHintField(v); - } -}); - -const DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot']; - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB - * @method - * @param {object} [query={}] The cursor query object. - * @param {object} [options] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.projection] The fields to return in the query. Object of fields to either include or exclude (one of, not both), {'a':1, 'b': 1} **or** {'a': 0, 'b': 0} - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * @param {boolean} [options.explain=false] Explain the query instead of returning the data. - * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. - * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. - * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. - * @param {boolean} [options.awaitData=false] Specify if the cursor is a a tailable-await cursor. Requires `tailable` to be true - * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {boolean} [options.returnKey=false] Only return the index key. - * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. - * @param {number} [options.min] Set index bounds. - * @param {number} [options.max] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true - * @param {boolean} [options.noCursorTimeout] The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @throws {MongoError} - * @return {Cursor} - */ -Collection.prototype.find = deprecateOptions( - { - name: 'collection.find', - deprecatedOptions: DEPRECATED_FIND_OPTIONS, - optionsIndex: 1 - }, - function(query, options, callback) { - if (typeof callback === 'object') { - // TODO(MAJOR): throw in the future - console.warn('Third parameter to `find()` must be a callback or undefined'); - } - - let selector = query; - // figuring out arguments - if (typeof callback !== 'function') { - if (typeof options === 'function') { - callback = options; - options = undefined; - } else if (options == null) { - callback = typeof selector === 'function' ? selector : undefined; - selector = typeof selector === 'object' ? selector : undefined; - } - } - - // Ensure selector is not null - selector = selector == null ? {} : selector; - // Validate correctness off the selector - const object = selector; - if (Buffer.isBuffer(object)) { - const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24); - if (object_size !== object.length) { - const error = new Error( - 'query selector raw message size does not match message header size [' + - object.length + - '] != [' + - object_size + - ']' - ); - error.name = 'MongoError'; - throw error; - } - } - - // Check special case where we are using an objectId - if (selector != null && selector._bsontype === 'ObjectID') { - selector = { _id: selector }; - } - - if (!options) options = {}; - - let projection = options.projection || options.fields; - - if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) { - projection = projection.length - ? projection.reduce((result, field) => { - result[field] = 1; - return result; - }, {}) - : { _id: 1 }; - } - - // Make a shallow copy of options - let newOptions = Object.assign({}, options); - - // Make a shallow copy of the collection options - for (let key in this.s.options) { - if (mergeKeys.indexOf(key) !== -1) { - newOptions[key] = this.s.options[key]; - } - } - - // Unpack options - newOptions.skip = options.skip ? options.skip : 0; - newOptions.limit = options.limit ? options.limit : 0; - newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw; - newOptions.hint = - options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; - newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout; - // // If we have overridden slaveOk otherwise use the default db setting - newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; - - // Add read preference if needed - newOptions.readPreference = resolveReadPreference(this, newOptions); - - // Set slave ok to true if read preference different from primary - if ( - newOptions.readPreference != null && - (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary') - ) { - newOptions.slaveOk = true; - } - - // Ensure the query is an object - if (selector != null && typeof selector !== 'object') { - throw MongoError.create({ message: 'query selector must be an object', driver: true }); - } - - // Build the find command - const findCommand = { - find: this.s.namespace.toString(), - limit: newOptions.limit, - skip: newOptions.skip, - query: selector - }; - - // Ensure we use the right await data option - if (typeof newOptions.awaitdata === 'boolean') { - newOptions.awaitData = newOptions.awaitdata; - } - - // Translate to new command option noCursorTimeout - if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout; - - decorateCommand(findCommand, newOptions, ['session', 'collation']); - - if (projection) findCommand.fields = projection; - - // Add db object to the new options - newOptions.db = this.s.db; - - // Add the promise library - newOptions.promiseLibrary = this.s.promiseLibrary; - - // Set raw if available at collection level - if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw; - // Set promoteLongs if available at collection level - if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean') - newOptions.promoteLongs = this.s.promoteLongs; - if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean') - newOptions.promoteValues = this.s.promoteValues; - if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean') - newOptions.promoteBuffers = this.s.promoteBuffers; - - // Sort options - if (findCommand.sort) { - findCommand.sort = formattedOrderClause(findCommand.sort); - } - - // Set the readConcern - decorateWithReadConcern(findCommand, this, options); - - // Decorate find command with collation options - try { - decorateWithCollation(findCommand, this, options); - } catch (err) { - if (typeof callback === 'function') return callback(err, null); - throw err; - } - - const cursor = this.s.topology.cursor( - new FindOperation(this, this.s.namespace, findCommand, newOptions), - newOptions - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; - } -); - -/** - * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object} doc Document to insert. - * @param {object} [options] Optional settings. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertOne = function(doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const insertOneOperation = new InsertOneOperation(this, doc, options); - - return executeOperation(this.s.topology, insertOneOperation, callback); -}; - -/** - * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} docs Documents to insert. - * @param {object} [options] Optional settings. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertMany = function(docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : { ordered: true }; - - const insertManyOperation = new InsertManyOperation(this, docs, options); - - return executeOperation(this.s.topology, insertManyOperation, callback); -}; - -/** - * @typedef {Object} Collection~BulkWriteOpResult - * @property {number} insertedCount Number of documents inserted. - * @property {number} matchedCount Number of documents matched for update. - * @property {number} modifiedCount Number of documents modified. - * @property {number} deletedCount Number of documents deleted. - * @property {number} upsertedCount Number of documents upserted. - * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation - * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~bulkWriteOpCallback - * @param {BulkWriteError} error An error instance representing the error during the execution. - * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Perform a bulkWrite operation without a fluent API - * - * Legal operation types are - * - * { insertOne: { document: { a: 1 } } } - * - * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } - * - * { deleteOne: { filter: {c:1} } } - * - * { deleteMany: { filter: {c:1} } } - * - * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} - * - * If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} operations Bulk operations to perform. - * @param {object} [options] Optional settings. - * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object[]} [options.arrayFilters] Determines which array elements to modify for update operation in MongoDB 3.6 or higher. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~bulkWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.bulkWrite = function(operations, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || { ordered: true }; - - if (!Array.isArray(operations)) { - throw MongoError.create({ message: 'operations must be an array of documents', driver: true }); - } - - const bulkWriteOperation = new BulkWriteOperation(this, operations, options); - - return executeOperation(this.s.topology, bulkWriteOperation, callback); -}; - -/** - * @typedef {Object} Collection~WriteOpResult - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {object} connection The connection object used for the operation. - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~writeOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * @typedef {Object} Collection~insertWriteOpResult - * @property {number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {Object.} insertedIds Map of the index of the inserted document to the id of the inserted document. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {number} result.ok Is 1 if the command executed correctly. - * @property {number} result.n The total count of documents inserted. - */ - -/** - * @typedef {Object} Collection~insertOneWriteOpResult - * @property {number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {number} result.ok Is 1 if the command executed correctly. - * @property {number} result.n The total count of documents inserted. - */ - -/** - * The callback format for inserts - * @callback Collection~insertWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * The callback format for inserts - * @callback Collection~insertOneWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {(object|object[])} docs Documents to insert. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated Use insertOne, insertMany or bulkWrite - */ -Collection.prototype.insert = deprecate(function(docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || { ordered: false }; - docs = !Array.isArray(docs) ? [docs] : docs; - - if (options.keepGoing === true) { - options.ordered = false; - } - - return this.insertMany(docs, options, callback); -}, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); - -/** - * @typedef {Object} Collection~updateWriteOpResult - * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents scanned. - * @property {Number} result.nModified The total count of documents modified. - * @property {Object} connection The connection object used for the operation. - * @property {Number} matchedCount The number of documents that matched the filter. - * @property {Number} modifiedCount The number of documents that were modified. - * @property {Number} upsertedCount The number of documents upserted. - * @property {Object} upsertedId The upserted id. - * @property {ObjectId} upsertedId._id The upserted _id returned from the server. - * @property {Object} message The raw msg response wrapped in an internal class - * @property {object[]} [ops] In a response to {@link Collection#replaceOne replaceOne}, contains the new value of the document on the server. This is the same document that was originally passed in, and is only here for legacy purposes. - */ - -/** - * The callback format for inserts - * @callback Collection~updateWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Update a single document in a collection - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update The update operations to be applied to the document - * @param {object} [options] Optional settings. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query.. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateOne = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const updateOneOperation = new UpdateOneOperation(this, filter, update, options); - - return executeOperation(this.s.topology, updateOneOperation, callback); -}; - -/** - * Replace a document in a collection with another document - * @method - * @param {object} filter The Filter used to select the document to replace - * @param {object} doc The Document that replaces the matching document - * @param {object} [options] Optional settings. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.replaceOne = function(filter, doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const replaceOneOperation = new ReplaceOneOperation(this, filter, doc, options); - - return executeOperation(this.s.topology, replaceOneOperation, callback); -}; - -/** - * Update multiple documents in a collection - * @method - * @param {object} filter The Filter used to select the documents to update - * @param {object} update The update operations to be applied to the documents - * @param {object} [options] Optional settings. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query.. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateMany = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const updateManyOperation = new UpdateManyOperation(this, filter, update, options); - - return executeOperation(this.s.topology, updateManyOperation, callback); -}; - -/** - * Updates documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} update The update operations to be applied to the documents - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {boolean} [options.multi=false] Update one/all documents with operation. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - * @deprecated use updateOne, updateMany or bulkWrite - */ -Collection.prototype.update = deprecate(function(selector, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, updateDocuments, [ - this, - selector, - update, - options, - callback - ]); -}, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); - -/** - * @typedef {Object} Collection~deleteWriteOpResult - * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents deleted. - * @property {Object} connection The connection object used for the operation. - * @property {Number} deletedCount The number of documents deleted. - */ - -/** - * The callback format for deletes - * @callback Collection~deleteWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Delete a document from a collection - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteOne = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const deleteOneOperation = new DeleteOneOperation(this, filter, options); - - return executeOperation(this.s.topology, deleteOneOperation, callback); -}; - -Collection.prototype.removeOne = Collection.prototype.deleteOne; - -/** - * Delete multiple documents from a collection - * @method - * @param {object} filter The Filter used to select the documents to remove - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteMany = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const deleteManyOperation = new DeleteManyOperation(this, filter, options); - - return executeOperation(this.s.topology, deleteManyOperation, callback); -}; - -Collection.prototype.removeMany = Collection.prototype.deleteMany; - -/** - * Remove documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.single=false] Removes the first document found. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use deleteOne, deleteMany or bulkWrite - */ -Collection.prototype.remove = deprecate(function(selector, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, removeDocuments, [ - this, - selector, - options, - callback - ]); -}, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); - -/** - * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic - * operators and update instead for more efficient operations. - * @method - * @param {object} doc Document to save - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -Collection.prototype.save = deprecate(function(doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, save, [this, doc, options, callback]); -}, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.'); - -/** - * The callback format for results - * @callback Collection~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * The callback format for an aggregation call - * @callback Collection~aggregationCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. - */ - -/** - * Fetches the first document that matches the query - * @method - * @param {object} query Query for find Operation - * @param {object} [options] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * @param {boolean} [options.explain=false] Explain the query instead of returning the data. - * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. - * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. - * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. - * @param {number} [options.batchSize=1] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {boolean} [options.returnKey=false] Only return the index key. - * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. - * @param {number} [options.min] Set index bounds. - * @param {number} [options.max] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOne = deprecateOptions( - { - name: 'collection.find', - deprecatedOptions: DEPRECATED_FIND_OPTIONS, - optionsIndex: 1 - }, - function(query, options, callback) { - if (typeof callback === 'object') { - // TODO(MAJOR): throw in the future - console.warn('Third parameter to `findOne()` must be a callback or undefined'); - } - - if (typeof query === 'function') (callback = query), (query = {}), (options = {}); - if (typeof options === 'function') (callback = options), (options = {}); - query = query || {}; - options = options || {}; - - const findOneOperation = new FindOneOperation(this, query, options); - - return executeOperation(this.s.topology, findOneOperation, callback); - } -); - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Collection~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * Rename the collection. - * - * @method - * @param {string} newName New name of of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.rename = function(newName, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - const renameOperation = new RenameOperation(this, newName, options); - - return executeOperation(this.s.topology, renameOperation, callback); -}; - -/** - * Drop the collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {object} [options] Optional settings. - * @param {WriteConcern} [options.writeConcern] A full WriteConcern object - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j] The journal write concern - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.drop = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropCollectionOperation = new DropCollectionOperation( - this.s.db, - this.collectionName, - options - ); - - return executeOperation(this.s.topology, dropCollectionOperation, callback); -}; - -/** - * Returns the options of the collection. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.options = function(opts, callback) { - if (typeof opts === 'function') (callback = opts), (opts = {}); - opts = opts || {}; - - const optionsOperation = new OptionsOperation(this, opts); - - return executeOperation(this.s.topology, optionsOperation, callback); -}; - -/** - * Returns if the collection is a capped collection - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.isCapped = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const isCappedOperation = new IsCappedOperation(this, options); - - return executeOperation(this.s.topology, isCappedOperation, callback); -}; - -/** - * Creates an index on the db and collection collection. - * @method - * @param {(string|array|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @example - * const collection = client.db('foo').collection('bar'); - * - * await collection.createIndex({ a: 1, b: -1 }); - * - * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes - * await collection.createIndex([ [c, 1], [d, -1] ]); - * - * // Equivalent to { e: 1 } - * await collection.createIndex('e'); - * - * // Equivalent to { f: 1, g: 1 } - * await collection.createIndex(['f', 'g']) - * - * // Equivalent to { h: 1, i: -1 } - * await collection.createIndex([ { h: 1 }, { i: -1 } ]); - * - * // Equivalent to { j: 1, k: -1, l: 2d } - * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) - */ -Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const createIndexOperation = new CreateIndexOperation( - this.s.db, - this.collectionName, - fieldOrSpec, - options - ); - - return executeOperation(this.s.topology, createIndexOperation, callback); -}; - -/** - * @typedef {object} Collection~IndexDefinition - * @description A definition for an index. Used by the createIndex command. - * @see https://docs.mongodb.com/manual/reference/command/createIndexes/ - */ - -/** - * Creates multiple indexes in the collection, this method is only supported for - * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported - * error. - * - * **Note**: Unlike {@link Collection#createIndex createIndex}, this function takes in raw index specifications. - * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/ here}. - * - * @method - * @param {Collection~IndexDefinition[]} indexSpecs An array of index specifications to be created - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @example - * const collection = client.db('foo').collection('bar'); - * await collection.createIndexes([ - * // Simple index on field fizz - * { - * key: { fizz: 1 }, - * } - * // wildcard index - * { - * key: { '$**': 1 } - * }, - * // named index on darmok and jalad - * { - * key: { darmok: 1, jalad: -1 } - * name: 'tanagra' - * } - * ]); - */ -Collection.prototype.createIndexes = function(indexSpecs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - - options = options ? Object.assign({}, options) : {}; - if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; - - const createIndexesOperation = new CreateIndexesOperation(this, indexSpecs, options); - - return executeOperation(this.s.topology, createIndexesOperation, callback); -}; - -/** - * Drops an index from this collection. - * @method - * @param {string} indexName Name of the index to drop. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndex = function(indexName, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - options = args.length ? args.shift() || {} : {}; - // Run only against primary - options.readPreference = ReadPreference.PRIMARY; - - const dropIndexOperation = new DropIndexOperation(this, indexName, options); - - return executeOperation(this.s.topology, dropIndexOperation, callback); -}; - -/** - * Drops all indexes from this collection. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndexes = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : {}; - - if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; - - const dropIndexesOperation = new DropIndexesOperation(this, options); - - return executeOperation(this.s.topology, dropIndexesOperation, callback); -}; - -/** - * Drops all indexes from this collection. - * @method - * @deprecated use dropIndexes - * @param {Collection~resultCallback} callback The command result callback - * @return {Promise} returns Promise if no [callback] passed - */ -Collection.prototype.dropAllIndexes = deprecate( - Collection.prototype.dropIndexes, - 'collection.dropAllIndexes is deprecated. Use dropIndexes instead.' -); - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.reIndex = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const reIndexOperation = new ReIndexOperation(this, options); - - return executeOperation(this.s.topology, reIndexOperation, callback); -}; - -/** - * Get the list of all indexes information for the collection. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {CommandCursor} - */ -Collection.prototype.listIndexes = function(options) { - const cursor = new CommandCursor( - this.s.topology, - new ListIndexesOperation(this, options), - options - ); - - return cursor; -}; - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated use createIndexes instead - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.ensureIndex = deprecate(function(fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, ensureIndex, [ - this, - fieldOrSpec, - options, - callback - ]); -}, 'collection.ensureIndex is deprecated. Use createIndexes instead.'); - -/** - * Checks if one or more indexes exist on the collection, fails on first non-existing index - * @method - * @param {(string|array)} indexes One or more index names to check. - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexExists = function(indexes, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexExistsOperation = new IndexExistsOperation(this, indexes, options); - - return executeOperation(this.s.topology, indexExistsOperation, callback); -}; - -/** - * Retrieves this collections index info. - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexInformation = function(options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const indexInformationOperation = new IndexInformationOperation( - this.s.db, - this.collectionName, - options - ); - - return executeOperation(this.s.topology, indexInformationOperation, callback); -}; - -/** - * The callback format for results - * @callback Collection~countCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} result The count of documents that matched the query. - */ - -/** - * An estimated count of matching documents in the db to a query. - * - * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents - * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments countDocuments}. - * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount estimatedDocumentCount}. - * - * @method - * @param {object} [query={}] The query for the count. - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {boolean} [options.limit] The limit of documents to count. - * @param {boolean} [options.skip] The number of documents to skip for the count. - * @param {string} [options.hint] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~countCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use {@link Collection#countDocuments countDocuments} or {@link Collection#estimatedDocumentCount estimatedDocumentCount} instead - */ -Collection.prototype.count = deprecate(function(query, options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation( - this.s.topology, - new EstimatedDocumentCountOperation(this, query, options), - callback - ); -}, 'collection.count is deprecated, and will be removed in a future version.' + - ' Use Collection.countDocuments or Collection.estimatedDocumentCount instead'); - -/** - * Gets an estimate of the count of documents in a collection using collection metadata. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. - * @param {Collection~countCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed. - */ -Collection.prototype.estimatedDocumentCount = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const estimatedDocumentCountOperation = new EstimatedDocumentCountOperation(this, options); - - return executeOperation(this.s.topology, estimatedDocumentCountOperation, callback); -}; - -/** - * Gets the number of documents matching the filter. - * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount estimatedDocumentCount}. - * **Note**: When migrating from {@link Collection#count count} to {@link Collection#countDocuments countDocuments} - * the following query operators must be replaced: - * - * | Operator | Replacement | - * | -------- | ----------- | - * | `$where` | [`$expr`][1] | - * | `$near` | [`$geoWithin`][2] with [`$center`][3] | - * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | - * - * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ - * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ - * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center - * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere - * - * @param {object} [query] the query for the count - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specifies a collation. - * @param {string|object} [options.hint] The index to use. - * @param {number} [options.limit] The maximum number of document to count. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. - * @param {number} [options.skip] The number of documents to skip before counting. - * @param {Collection~countCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed. - * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ - * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ - * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center - * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere - */ - -Collection.prototype.countDocuments = function(query, options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - const countDocumentsOperation = new CountDocumentsOperation(this, query, options); - - return executeOperation(this.s.topology, countDocumentsOperation, callback); -}; - -/** - * The distinct command returns a list of distinct values for the given key across a collection. - * @method - * @param {string} key Field of the document to find distinct values for. - * @param {object} [query] The query for filtering the set of documents to which we apply the distinct filter. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.distinct = function(key, query, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - const queryOption = args.length ? args.shift() || {} : {}; - const optionsOption = args.length ? args.shift() || {} : {}; - - const distinctOperation = new DistinctOperation(this, key, queryOption, optionsOption); - - return executeOperation(this.s.topology, distinctOperation, callback); -}; - -/** - * Retrieve all the indexes on the collection. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexes = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexesOperation = new IndexesOperation(this, options); - - return executeOperation(this.s.topology, indexesOperation, callback); -}; - -/** - * Get all the collection statistics. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.scale] Divide the returned sizes by scale value. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.stats = function(options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const statsOperation = new StatsOperation(this, options); - - return executeOperation(this.s.topology, statsOperation, callback); -}; - -/** - * @typedef {Object} Collection~findAndModifyWriteOpResult - * @property {object} value Document returned from the `findAndModify` command. If no documents were found, `value` will be `null` by default (`returnOriginal: true`), even if a document was upserted; if `returnOriginal` was false, the upserted document will be returned in that case. - * @property {object} lastErrorObject The raw lastErrorObject returned from the command. See {@link https://docs.mongodb.com/manual/reference/command/findAndModify/index.html#lasterrorobject|findAndModify command documentation}. - * @property {Number} ok Is 1 if the command executed correctly. - */ - -/** - * The callback format for inserts - * @callback Collection~findAndModifyCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndDelete = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - - const findOneAndDeleteOperation = new FindOneAndDeleteOperation(this, filter, options); - - return executeOperation(this.s.topology, findOneAndDeleteOperation, callback); -}; - -/** - * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to replace - * @param {object} replacement The Document that replaces the matching document - * @param {object} [options] Optional settings. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - if (replacement == null || typeof replacement !== 'object') - throw toError('replacement parameter must be an object'); - - // Check that there are no atomic operators - const keys = Object.keys(replacement); - - if (keys[0] && keys[0][0] === '$') { - throw toError('The replacement document must not contain atomic operators.'); - } - - const findOneAndReplaceOperation = new FindOneAndReplaceOperation( - this, - filter, - replacement, - options - ); - - return executeOperation(this.s.topology, findOneAndReplaceOperation, callback); -}; - -/** - * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update Update operations to be performed on the document - * @param {object} [options] Optional settings. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - if (update == null || typeof update !== 'object') - throw toError('update parameter must be an object'); - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - const findOneAndUpdateOperation = new FindOneAndUpdateOperation(this, filter, update, options); - - return executeOperation(this.s.topology, findOneAndUpdateOperation, callback); -}; - -/** - * Find and update a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} doc The fields/vals to be updated. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.remove=false] Set to true to remove the object before returning. - * @param {boolean} [options.upsert=false] Perform an upsert operation. - * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. - * @param {object} [options.projection] Object containing the field projection for the result returned from the operation. - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {Collection~findAndModifyCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -Collection.prototype.findAndModify = deprecate( - _findAndModify, - 'collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.' -); - -/** - * @ignore - */ - -Collection.prototype._findAndModify = _findAndModify; - -function _findAndModify(query, sort, doc, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - sort = args.length ? args.shift() || [] : []; - doc = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Clone options - options = Object.assign({}, options); - // Force read preference primary - options.readPreference = ReadPreference.PRIMARY; - - return executeOperation( - this.s.topology, - new FindAndModifyOperation(this, query, sort, doc, options), - callback - ); -} - -/** - * Find and remove a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndDelete instead - */ -Collection.prototype.findAndRemove = deprecate(function(query, sort, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - sort = args.length ? args.shift() || [] : []; - options = args.length ? args.shift() || {} : {}; - - // Add the remove option - options.remove = true; - - return executeOperation( - this.s.topology, - new FindAndModifyOperation(this, query, sort, null, options), - callback - ); -}, 'collection.findAndRemove is deprecated. Use findOneAndDelete instead.'); - -/** - * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 - * @method - * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * @param {number} [options.cursor.batchSize=1000] Deprecated. Use `options.batchSize` - * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). - * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {string} [options.comment] Add a comment to an aggregation command - * @param {string|object} [options.hint] Add an index selection hint to an aggregation command - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~aggregationCallback} callback The command result callback - * @return {(null|AggregationCursor)} - */ -Collection.prototype.aggregate = function(pipeline, options, callback) { - if (Array.isArray(pipeline)) { - // Set up callback if one is provided - if (typeof options === 'function') { - callback = options; - options = {}; - } - - // If we have no options or callback we are doing - // a cursor based aggregation - if (options == null && callback == null) { - options = {}; - } - } else { - // Aggregation pipeline passed as arguments on the method - const args = Array.prototype.slice.call(arguments, 0); - // Get the callback - callback = args.pop(); - // Get the possible options object - const opts = args[args.length - 1]; - // If it contains any of the admissible options pop it of the args - options = - opts && - (opts.readPreference || - opts.explain || - opts.cursor || - opts.out || - opts.maxTimeMS || - opts.hint || - opts.allowDiskUse) - ? args.pop() - : {}; - // Left over arguments is the pipeline - pipeline = args; - } - - const cursor = new AggregationCursor( - this.s.topology, - new AggregateOperation(this, pipeline, options), - options - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; -}; - -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. - * @method - * @since 3.0.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -Collection.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * The callback format for results - * @callback Collection~parallelCollectionScanCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. - */ - -/** - * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are - * no ordering guarantees for returned results. - * @method - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) - * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.parallelCollectionScan = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = { numCursors: 1 }); - // Set number of cursors to 1 - options.numCursors = options.numCursors || 1; - options.batchSize = options.batchSize || 1000; - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(this, options); - - // Add a promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - if (options.session) { - options.session = undefined; - } - - return executeLegacyOperation( - this.s.topology, - parallelCollectionScan, - [this, options, callback], - { skipSessions: true } - ); -}, 'parallelCollectionScan is deprecated in MongoDB v4.1'); - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @method - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxDistance] Include results up to maxDistance from the point. - * @param {object} [options.search] Filter the results by a query. - * @param {number} [options.limit=false] Max number of results to return. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { - const args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const geoHaystackSearchOperation = new GeoHaystackSearchOperation(this, x, y, options); - - return executeOperation(this.s.topology, geoHaystackSearchOperation, callback); -}; - -/** - * Run a group command across a collection - * - * @method - * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. - * @param {object} condition An optional condition that must be true for a row to be considered. - * @param {object} initial Initial value of the aggregation counter object. - * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated - * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. - * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. - */ -Collection.prototype.group = deprecate(function( - keys, - condition, - initial, - reduce, - finalize, - command, - options, - callback -) { - const args = Array.prototype.slice.call(arguments, 3); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - reduce = args.length ? args.shift() : null; - finalize = args.length ? args.shift() : null; - command = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Make sure we are backward compatible - if (!(typeof finalize === 'function')) { - command = finalize; - finalize = null; - } - - if ( - !Array.isArray(keys) && - keys instanceof Object && - typeof keys !== 'function' && - !(keys._bsontype === 'Code') - ) { - keys = Object.keys(keys); - } - - if (typeof reduce === 'function') { - reduce = reduce.toString(); - } - - if (typeof finalize === 'function') { - finalize = finalize.toString(); - } - - // Set up the command as default - command = command == null ? true : command; - - return executeLegacyOperation(this.s.topology, group, [ - this, - keys, - condition, - initial, - reduce, - finalize, - command, - options, - callback - ]); -}, -'MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.'); - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * @method - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.out] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* - * @param {object} [options.query] Query filter object. - * @param {object} [options.sort] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. - * @param {number} [options.limit] Number of objects to return from collection. - * @param {boolean} [options.keeptemp=false] Keep temporary data. - * @param {(function|string)} [options.finalize] Finalize function. - * @param {object} [options.scope] Can pass in variables that can be access from map/reduce/finalize. - * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. - * @param {boolean} [options.verbose=false] Provide statistics on job execution time. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.mapReduce = function(map, reduce, options, callback) { - if ('function' === typeof options) (callback = options), (options = {}); - // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) - if (null == options.out) { - throw new Error( - 'the out option parameter must be defined, see mongodb docs for possible values' - ); - } - - if ('function' === typeof map) { - map = map.toString(); - } - - if ('function' === typeof reduce) { - reduce = reduce.toString(); - } - - if ('function' === typeof options.finalize) { - options.finalize = options.finalize.toString(); - } - const mapReduceOperation = new MapReduceOperation(this, map, reduce, options); - - return executeOperation(this.s.topology, mapReduceOperation, callback); -}; - -/** - * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. - * - * @method - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {UnorderedBulkOperation} - */ -Collection.prototype.initializeUnorderedBulkOp = function(options) { - options = options || {}; - // Give function's options precedence over session options. - if (options.ignoreUndefined == null) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - options.promiseLibrary = this.s.promiseLibrary; - return unordered(this.s.topology, this, options); -}; - -/** - * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. - * - * @method - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {OrderedBulkOperation} callback The command result callback - * @return {null} - */ -Collection.prototype.initializeOrderedBulkOp = function(options) { - options = options || {}; - // Give function's options precedence over session's options. - if (options.ignoreUndefined == null) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - options.promiseLibrary = this.s.promiseLibrary; - return ordered(this.s.topology, this, options); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -Collection.prototype.getLogger = function() { - return this.s.db.s.logger; -}; - -module.exports = Collection; diff --git a/node_modules/mongodb/lib/command_cursor.js b/node_modules/mongodb/lib/command_cursor.js deleted file mode 100644 index cd0f9d7..0000000 --- a/node_modules/mongodb/lib/command_cursor.js +++ /dev/null @@ -1,269 +0,0 @@ -'use strict'; - -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const CursorState = require('./core/cursor').CursorState; - -/** - * @fileOverview The **CommandCursor** class is an internal class that embodies a - * generalized cursor based on a MongoDB command allowing for iteration over the - * results returned. It supports one by one document iteration, conversion to an - * array or can be iterated as a Node 0.10.X or higher stream - * - * **CommandCursor Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('listCollectionsExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // List the database collections available - * db.listCollections().toArray(function(err, items) { - * test.equal(null, err); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class CommandCursor - * @extends external:Readable - * @fires CommandCursor#data - * @fires CommandCursor#end - * @fires CommandCursor#close - * @fires CommandCursor#readable - * @return {CommandCursor} an CommandCursor instance. - */ -class CommandCursor extends Cursor { - constructor(topology, ns, cmd, options) { - super(topology, ns, cmd, options); - } - - /** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ - setReadPreference(readPreference) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (this.s.state !== CursorState.INIT) { - throw MongoError.create({ - message: 'cannot change cursor readPreference after cursor has been accessed', - driver: true - }); - } - - if (readPreference instanceof ReadPreference) { - this.options.readPreference = readPreference; - } else if (typeof readPreference === 'string') { - this.options.readPreference = new ReadPreference(readPreference); - } else { - throw new TypeError('Invalid read preference: ' + readPreference); - } - - return this; - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. - * @throws {MongoError} - * @return {CommandCursor} - */ - batchSize(value) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - if (this.cmd.cursor) { - this.cmd.cursor.batchSize = value; - } - - this.setCursorBatchSize(value); - return this; - } - - /** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {CommandCursor} - */ - maxTimeMS(value) { - if (this.topology.lastIsMaster().minWireVersion > 2) { - this.cmd.maxTimeMS = value; - } - - return this; - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -// aliases -CommandCursor.prototype.get = CommandCursor.prototype.toArray; - -/** - * CommandCursor stream data event, fired for each document in the cursor. - * - * @event CommandCursor#data - * @type {object} - */ - -/** - * CommandCursor stream end event - * - * @event CommandCursor#end - * @type {null} - */ - -/** - * CommandCursor stream close event - * - * @event CommandCursor#close - * @type {null} - */ - -/** - * CommandCursor stream readable event - * - * @event CommandCursor#readable - * @type {null} - */ - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function CommandCursor.prototype.next - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function CommandCursor.prototype.hasNext - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previously accessed. - * @method CommandCursor.prototype.toArray - * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method CommandCursor.prototype.each - * @param {CommandCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a KillCursor command and emitting close. - * @method CommandCursor.prototype.close - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method CommandCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Clone the cursor - * @function CommandCursor.prototype.clone - * @return {CommandCursor} - */ - -/** - * Resets the cursor - * @function CommandCursor.prototype.rewind - * @return {CommandCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback CommandCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback CommandCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/* - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method CommandCursor.prototype.forEach - * @param {CommandCursor~iteratorCallback} iterator The iteration callback. - * @param {CommandCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -module.exports = CommandCursor; diff --git a/node_modules/mongodb/lib/constants.js b/node_modules/mongodb/lib/constants.js deleted file mode 100644 index d6cc68a..0000000 --- a/node_modules/mongodb/lib/constants.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -module.exports = { - SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces', - SYSTEM_INDEX_COLLECTION: 'system.indexes', - SYSTEM_PROFILE_COLLECTION: 'system.profile', - SYSTEM_USER_COLLECTION: 'system.users', - SYSTEM_COMMAND_COLLECTION: '$cmd', - SYSTEM_JS_COLLECTION: 'system.js' -}; diff --git a/node_modules/mongodb/lib/core/auth/auth_provider.js b/node_modules/mongodb/lib/core/auth/auth_provider.js deleted file mode 100644 index 7597b72..0000000 --- a/node_modules/mongodb/lib/core/auth/auth_provider.js +++ /dev/null @@ -1,158 +0,0 @@ -'use strict'; - -const MongoError = require('../error').MongoError; - -/** - * Creates a new AuthProvider, which dictates how to authenticate for a given - * mechanism. - * @class - */ -class AuthProvider { - constructor(bson) { - this.bson = bson; - this.authStore = []; - } - - /** - * Authenticate - * @method - * @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection - * @param {Connection[]} connections Connections to authenticate using this authenticator - * @param {MongoCredentials} credentials Authentication credentials - * @param {authResultCallback} callback The callback to return the result from the authentication - */ - auth(sendAuthCommand, connections, credentials, callback) { - // Total connections - let count = connections.length; - - if (count === 0) { - callback(null, null); - return; - } - - // Valid connections - let numberOfValidConnections = 0; - let errorObject = null; - - const execute = connection => { - this._authenticateSingleConnection(sendAuthCommand, connection, credentials, (err, r) => { - // Adjust count - count = count - 1; - - // If we have an error - if (err) { - errorObject = new MongoError(err); - } else if (r && (r.$err || r.errmsg)) { - errorObject = new MongoError(r); - } else { - numberOfValidConnections = numberOfValidConnections + 1; - } - - // Still authenticating against other connections. - if (count !== 0) { - return; - } - - // We have authenticated all connections - if (numberOfValidConnections > 0) { - // Store the auth details - this.addCredentials(credentials); - // Return correct authentication - callback(null, true); - } else { - if (errorObject == null) { - errorObject = new MongoError(`failed to authenticate using ${credentials.mechanism}`); - } - callback(errorObject, false); - } - }); - }; - - const executeInNextTick = _connection => process.nextTick(() => execute(_connection)); - - // For each connection we need to authenticate - while (connections.length > 0) { - executeInNextTick(connections.shift()); - } - } - - /** - * Implementation of a single connection authenticating. Is meant to be overridden. - * Will error if called directly - * @ignore - */ - _authenticateSingleConnection(/*sendAuthCommand, connection, credentials, callback*/) { - throw new Error('_authenticateSingleConnection must be overridden'); - } - - /** - * Adds credentials to store only if it does not exist - * @param {MongoCredentials} credentials credentials to add to store - */ - addCredentials(credentials) { - const found = this.authStore.some(cred => cred.equals(credentials)); - - if (!found) { - this.authStore.push(credentials); - } - } - - /** - * Re authenticate pool - * @method - * @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection - * @param {Connection[]} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - */ - reauthenticate(sendAuthCommand, connections, callback) { - const authStore = this.authStore.slice(0); - let count = authStore.length; - if (count === 0) { - return callback(null, null); - } - - for (let i = 0; i < authStore.length; i++) { - this.auth(sendAuthCommand, connections, authStore[i], function(err) { - count = count - 1; - if (count === 0) { - callback(err, null); - } - }); - } - } - - /** - * Remove credentials that have been previously stored in the auth provider - * @method - * @param {string} source Name of database we are removing authStore details about - * @return {object} - */ - logout(source) { - this.authStore = this.authStore.filter(credentials => credentials.source !== source); - } -} - -/** - * A function that writes authentication commands to a specific connection - * @callback SendAuthCommand - * @param {Connection} connection The connection to write to - * @param {Command} command A command with a toBin method that can be written to a connection - * @param {AuthWriteCallback} callback Callback called when command response is received - */ - -/** - * A callback for a specific auth command - * @callback AuthWriteCallback - * @param {Error} err If command failed, an error from the server - * @param {object} r The response from the server - */ - -/** - * This is a result from an authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = { AuthProvider }; diff --git a/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js b/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js deleted file mode 100644 index fc5f4c2..0000000 --- a/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -const MongoCR = require('./mongocr'); -const X509 = require('./x509'); -const Plain = require('./plain'); -const GSSAPI = require('./gssapi'); -const SSPI = require('./sspi'); -const ScramSHA1 = require('./scram').ScramSHA1; -const ScramSHA256 = require('./scram').ScramSHA256; - -/** - * Returns the default authentication providers. - * - * @param {BSON} bson Bson definition - * @returns {Object} a mapping of auth names to auth types - */ -function defaultAuthProviders(bson) { - return { - mongocr: new MongoCR(bson), - x509: new X509(bson), - plain: new Plain(bson), - gssapi: new GSSAPI(bson), - sspi: new SSPI(bson), - 'scram-sha-1': new ScramSHA1(bson), - 'scram-sha-256': new ScramSHA256(bson) - }; -} - -module.exports = { defaultAuthProviders }; diff --git a/node_modules/mongodb/lib/core/auth/gssapi.js b/node_modules/mongodb/lib/core/auth/gssapi.js deleted file mode 100644 index 936fb65..0000000 --- a/node_modules/mongodb/lib/core/auth/gssapi.js +++ /dev/null @@ -1,241 +0,0 @@ -'use strict'; - -const AuthProvider = require('./auth_provider').AuthProvider; -const retrieveKerberos = require('../utils').retrieveKerberos; -let kerberos; - -/** - * Creates a new GSSAPI authentication mechanism - * @class - * @extends AuthProvider - */ -class GSSAPI extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const source = credentials.source; - const username = credentials.username; - const password = credentials.password; - const mechanismProperties = credentials.mechanismProperties; - const gssapiServiceName = - mechanismProperties['gssapiservicename'] || - mechanismProperties['gssapiServiceName'] || - 'mongodb'; - - GSSAPIInitialize( - this, - kerberos.processes.MongoAuthProcess, - source, - username, - password, - source, - gssapiServiceName, - sendAuthCommand, - connection, - mechanismProperties, - callback - ); - } - - /** - * Authenticate - * @override - * @method - */ - auth(sendAuthCommand, connections, credentials, callback) { - if (kerberos == null) { - try { - kerberos = retrieveKerberos(); - } catch (e) { - return callback(e, null); - } - } - - super.auth(sendAuthCommand, connections, credentials, callback); - } -} - -// -// Initialize step -var GSSAPIInitialize = function( - self, - MongoAuthProcess, - db, - username, - password, - authdb, - gssapiServiceName, - sendAuthCommand, - connection, - options, - callback -) { - // Create authenticator - var mongo_auth_process = new MongoAuthProcess( - connection.host, - connection.port, - gssapiServiceName, - options - ); - - // Perform initialization - mongo_auth_process.init(username, password, function(err) { - if (err) return callback(err, false); - - // Perform the first step - mongo_auth_process.transition('', function(err, payload) { - if (err) return callback(err, false); - - // Call the next db step - MongoDBGSSAPIFirstStep( - self, - mongo_auth_process, - payload, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback - ); - }); - }); -}; - -// -// Perform first step against mongodb -var MongoDBGSSAPIFirstStep = function( - self, - mongo_auth_process, - payload, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback -) { - // Build the sasl start command - var command = { - saslStart: 1, - mechanism: 'GSSAPI', - payload: payload, - autoAuthorize: 1 - }; - - // Write the commmand on the connection - sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => { - if (err) return callback(err, false); - // Execute mongodb transition - mongo_auth_process.transition(doc.payload, function(err, payload) { - if (err) return callback(err, false); - - // MongoDB API Second Step - MongoDBGSSAPISecondStep( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback - ); - }); - }); -}; - -// -// Perform first step against mongodb -var MongoDBGSSAPISecondStep = function( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback -) { - // Build Authentication command to send to MongoDB - var command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload: payload - }; - - // Execute the command - // Write the commmand on the connection - sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => { - if (err) return callback(err, false); - // Call next transition for kerberos - mongo_auth_process.transition(doc.payload, function(err, payload) { - if (err) return callback(err, false); - - // Call the last and third step - MongoDBGSSAPIThirdStep( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback - ); - }); - }); -}; - -var MongoDBGSSAPIThirdStep = function( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback -) { - // Build final command - var command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload: payload - }; - - // Execute the command - sendAuthCommand(connection, '$external.$cmd', command, (err, r) => { - if (err) return callback(err, false); - mongo_auth_process.transition(null, function(err) { - if (err) return callback(err, null); - callback(null, r); - }); - }); -}; - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = GSSAPI; diff --git a/node_modules/mongodb/lib/core/auth/mongo_credentials.js b/node_modules/mongodb/lib/core/auth/mongo_credentials.js deleted file mode 100644 index 13c00b1..0000000 --- a/node_modules/mongodb/lib/core/auth/mongo_credentials.js +++ /dev/null @@ -1,81 +0,0 @@ -'use strict'; - -// Resolves the default auth mechanism according to -// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst -function getDefaultAuthMechanism(ismaster) { - if (ismaster) { - // If ismaster contains saslSupportedMechs, use scram-sha-256 - // if it is available, else scram-sha-1 - if (Array.isArray(ismaster.saslSupportedMechs)) { - return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0 - ? 'scram-sha-256' - : 'scram-sha-1'; - } - - // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 - if (ismaster.maxWireVersion >= 3) { - return 'scram-sha-1'; - } - } - - // Default for wireprotocol < 3 - return 'mongocr'; -} - -/** - * A representation of the credentials used by MongoDB - * @class - * @property {string} mechanism The method used to authenticate - * @property {string} [username] The username used for authentication - * @property {string} [password] The password used for authentication - * @property {string} [source] The database that the user should authenticate against - * @property {object} [mechanismProperties] Special properties used by some types of auth mechanisms - */ -class MongoCredentials { - /** - * Creates a new MongoCredentials object - * @param {object} [options] - * @param {string} [options.username] The username used for authentication - * @param {string} [options.password] The password used for authentication - * @param {string} [options.source] The database that the user should authenticate against - * @param {string} [options.mechanism] The method used to authenticate - * @param {object} [options.mechanismProperties] Special properties used by some types of auth mechanisms - */ - constructor(options) { - options = options || {}; - this.username = options.username; - this.password = options.password; - this.source = options.source || options.db; - this.mechanism = options.mechanism || 'default'; - this.mechanismProperties = options.mechanismProperties; - } - - /** - * Determines if two MongoCredentials objects are equivalent - * @param {MongoCredentials} other another MongoCredentials object - * @returns {boolean} true if the two objects are equal. - */ - equals(other) { - return ( - this.mechanism === other.mechanism && - this.username === other.username && - this.password === other.password && - this.source === other.source - ); - } - - /** - * If the authentication mechanism is set to "default", resolves the authMechanism - * based on the server version and server supported sasl mechanisms. - * - * @param {Object} [ismaster] An ismaster response from the server - */ - resolveAuthMechanism(ismaster) { - // If the mechanism is not "default", then it does not need to be resolved - if (this.mechanism.toLowerCase() === 'default') { - this.mechanism = getDefaultAuthMechanism(ismaster); - } - } -} - -module.exports = { MongoCredentials }; diff --git a/node_modules/mongodb/lib/core/auth/mongocr.js b/node_modules/mongodb/lib/core/auth/mongocr.js deleted file mode 100644 index be8fcb6..0000000 --- a/node_modules/mongodb/lib/core/auth/mongocr.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); -const AuthProvider = require('./auth_provider').AuthProvider; - -/** - * Creates a new MongoCR authentication mechanism - * - * @extends AuthProvider - */ -class MongoCR extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const username = credentials.username; - const password = credentials.password; - const source = credentials.source; - - sendAuthCommand(connection, `${source}.$cmd`, { getnonce: 1 }, (err, r) => { - let nonce = null; - let key = null; - - // Get nonce - if (err == null) { - nonce = r.nonce; - // Use node md5 generator - let md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password, 'utf8'); - const hash_password = md5.digest('hex'); - // Final key - md5 = crypto.createHash('md5'); - md5.update(nonce + username + hash_password, 'utf8'); - key = md5.digest('hex'); - } - - const authenticateCommand = { - authenticate: 1, - user: username, - nonce, - key - }; - - sendAuthCommand(connection, `${source}.$cmd`, authenticateCommand, callback); - }); - } -} - -module.exports = MongoCR; diff --git a/node_modules/mongodb/lib/core/auth/plain.js b/node_modules/mongodb/lib/core/auth/plain.js deleted file mode 100644 index 240de75..0000000 --- a/node_modules/mongodb/lib/core/auth/plain.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const retrieveBSON = require('../connection/utils').retrieveBSON; -const AuthProvider = require('./auth_provider').AuthProvider; - -// TODO: can we get the Binary type from this.bson instead? -const BSON = retrieveBSON(); -const Binary = BSON.Binary; - -/** - * Creates a new Plain authentication mechanism - * - * @extends AuthProvider - */ -class Plain extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const username = credentials.username; - const password = credentials.password; - const payload = new Binary(`\x00${username}\x00${password}`); - const command = { - saslStart: 1, - mechanism: 'PLAIN', - payload: payload, - autoAuthorize: 1 - }; - - sendAuthCommand(connection, '$external.$cmd', command, callback); - } -} - -module.exports = Plain; diff --git a/node_modules/mongodb/lib/core/auth/scram.js b/node_modules/mongodb/lib/core/auth/scram.js deleted file mode 100644 index 32fb4cd..0000000 --- a/node_modules/mongodb/lib/core/auth/scram.js +++ /dev/null @@ -1,329 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); -const Buffer = require('safe-buffer').Buffer; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const AuthProvider = require('./auth_provider').AuthProvider; - -const BSON = retrieveBSON(); -const Binary = BSON.Binary; - -let saslprep; -try { - saslprep = require('saslprep'); -} catch (e) { - // don't do anything; -} - -var parsePayload = function(payload) { - var dict = {}; - var parts = payload.split(','); - for (var i = 0; i < parts.length; i++) { - var valueParts = parts[i].split('='); - dict[valueParts[0]] = valueParts[1]; - } - - return dict; -}; - -var passwordDigest = function(username, password) { - if (typeof username !== 'string') throw new MongoError('username must be a string'); - if (typeof password !== 'string') throw new MongoError('password must be a string'); - if (password.length === 0) throw new MongoError('password cannot be empty'); - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password, 'utf8'); - return md5.digest('hex'); -}; - -// XOR two buffers -function xor(a, b) { - if (!Buffer.isBuffer(a)) a = Buffer.from(a); - if (!Buffer.isBuffer(b)) b = Buffer.from(b); - const length = Math.max(a.length, b.length); - const res = []; - - for (let i = 0; i < length; i += 1) { - res.push(a[i] ^ b[i]); - } - - return Buffer.from(res).toString('base64'); -} - -function H(method, text) { - return crypto - .createHash(method) - .update(text) - .digest(); -} - -function HMAC(method, key, text) { - return crypto - .createHmac(method, key) - .update(text) - .digest(); -} - -var _hiCache = {}; -var _hiCacheCount = 0; -var _hiCachePurge = function() { - _hiCache = {}; - _hiCacheCount = 0; -}; - -const hiLengthMap = { - sha256: 32, - sha1: 20 -}; - -function HI(data, salt, iterations, cryptoMethod) { - // omit the work if already generated - const key = [data, salt.toString('base64'), iterations].join('_'); - if (_hiCache[key] !== undefined) { - return _hiCache[key]; - } - - // generate the salt - const saltedData = crypto.pbkdf2Sync( - data, - salt, - iterations, - hiLengthMap[cryptoMethod], - cryptoMethod - ); - - // cache a copy to speed up the next lookup, but prevent unbounded cache growth - if (_hiCacheCount >= 200) { - _hiCachePurge(); - } - - _hiCache[key] = saltedData; - _hiCacheCount += 1; - return saltedData; -} - -function compareDigest(lhs, rhs) { - if (lhs.length !== rhs.length) { - return false; - } - - if (typeof crypto.timingSafeEqual === 'function') { - return crypto.timingSafeEqual(lhs, rhs); - } - - let result = 0; - for (let i = 0; i < lhs.length; i++) { - result |= lhs[i] ^ rhs[i]; - } - - return result === 0; -} - -/** - * Creates a new ScramSHA authentication mechanism - * @class - * @extends AuthProvider - */ -class ScramSHA extends AuthProvider { - constructor(bson, cryptoMethod) { - super(bson); - this.cryptoMethod = cryptoMethod || 'sha1'; - } - - static _getError(err, r) { - if (err) { - return err; - } - - if (r.$err || r.errmsg) { - return new MongoError(r); - } - } - - /** - * @ignore - */ - _executeScram(sendAuthCommand, connection, credentials, nonce, callback) { - let username = credentials.username; - const password = credentials.password; - const db = credentials.source; - - const cryptoMethod = this.cryptoMethod; - let mechanism = 'SCRAM-SHA-1'; - let processedPassword; - - if (cryptoMethod === 'sha256') { - mechanism = 'SCRAM-SHA-256'; - - processedPassword = saslprep ? saslprep(password) : password; - } else { - try { - processedPassword = passwordDigest(username, password); - } catch (e) { - return callback(e); - } - } - - // Clean up the user - username = username.replace('=', '=3D').replace(',', '=2C'); - - // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. - // Since the username is not sasl-prep-d, we need to do this here. - const firstBare = Buffer.concat([ - Buffer.from('n=', 'utf8'), - Buffer.from(username, 'utf8'), - Buffer.from(',r=', 'utf8'), - Buffer.from(nonce, 'utf8') - ]); - - // Build command structure - const saslStartCmd = { - saslStart: 1, - mechanism, - payload: new Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), firstBare])), - autoAuthorize: 1 - }; - - // Write the commmand on the connection - sendAuthCommand(connection, `${db}.$cmd`, saslStartCmd, (err, r) => { - let tmpError = ScramSHA._getError(err, r); - if (tmpError) { - return callback(tmpError, null); - } - - const payload = Buffer.isBuffer(r.payload) ? new Binary(r.payload) : r.payload; - const dict = parsePayload(payload.value()); - - const iterations = parseInt(dict.i, 10); - if (iterations && iterations < 4096) { - callback(new MongoError(`Server returned an invalid iteration count ${iterations}`), false); - return; - } - - const salt = dict.s; - const rnonce = dict.r; - if (rnonce.startsWith('nonce')) { - callback(new MongoError(`Server returned an invalid nonce: ${rnonce}`), false); - return; - } - - // Set up start of proof - const withoutProof = `c=biws,r=${rnonce}`; - const saltedPassword = HI( - processedPassword, - Buffer.from(salt, 'base64'), - iterations, - cryptoMethod - ); - - const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); - const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key'); - const storedKey = H(cryptoMethod, clientKey); - const authMessage = [firstBare, payload.value().toString('base64'), withoutProof].join(','); - - const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); - const clientProof = `p=${xor(clientKey, clientSignature)}`; - const clientFinal = [withoutProof, clientProof].join(','); - - const serverSignature = HMAC(cryptoMethod, serverKey, authMessage); - - const saslContinueCmd = { - saslContinue: 1, - conversationId: r.conversationId, - payload: new Binary(Buffer.from(clientFinal)) - }; - - sendAuthCommand(connection, `${db}.$cmd`, saslContinueCmd, (err, r) => { - if (err || (r && typeof r.ok === 'number' && r.ok === 0)) { - callback(err, r); - return; - } - - const parsedResponse = parsePayload(r.payload.value()); - if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) { - callback(new MongoError('Server returned an invalid signature')); - return; - } - - if (!r || r.done !== false) { - return callback(err, r); - } - - const retrySaslContinueCmd = { - saslContinue: 1, - conversationId: r.conversationId, - payload: Buffer.alloc(0) - }; - - sendAuthCommand(connection, `${db}.$cmd`, retrySaslContinueCmd, callback); - }); - }); - } - - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - // Create a random nonce - crypto.randomBytes(24, (err, buff) => { - if (err) { - return callback(err, null); - } - - return this._executeScram( - sendAuthCommand, - connection, - credentials, - buff.toString('base64'), - callback - ); - }); - } - - /** - * Authenticate - * @override - * @method - */ - auth(sendAuthCommand, connections, credentials, callback) { - this._checkSaslprep(); - super.auth(sendAuthCommand, connections, credentials, callback); - } - - _checkSaslprep() { - const cryptoMethod = this.cryptoMethod; - - if (cryptoMethod === 'sha256') { - if (!saslprep) { - console.warn('Warning: no saslprep library specified. Passwords will not be sanitized'); - } - } - } -} - -/** - * Creates a new ScramSHA1 authentication mechanism - * @class - * @extends ScramSHA - */ -class ScramSHA1 extends ScramSHA { - constructor(bson) { - super(bson, 'sha1'); - } -} - -/** - * Creates a new ScramSHA256 authentication mechanism - * @class - * @extends ScramSHA - */ -class ScramSHA256 extends ScramSHA { - constructor(bson) { - super(bson, 'sha256'); - } -} - -module.exports = { ScramSHA1, ScramSHA256 }; diff --git a/node_modules/mongodb/lib/core/auth/sspi.js b/node_modules/mongodb/lib/core/auth/sspi.js deleted file mode 100644 index 8a3f544..0000000 --- a/node_modules/mongodb/lib/core/auth/sspi.js +++ /dev/null @@ -1,131 +0,0 @@ -'use strict'; - -const AuthProvider = require('./auth_provider').AuthProvider; -const retrieveKerberos = require('../utils').retrieveKerberos; -let kerberos; - -/** - * Creates a new SSPI authentication mechanism - * @class - * @extends AuthProvider - */ -class SSPI extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - // TODO: Destructure this - const username = credentials.username; - const password = credentials.password; - const mechanismProperties = credentials.mechanismProperties; - const gssapiServiceName = - mechanismProperties['gssapiservicename'] || - mechanismProperties['gssapiServiceName'] || - 'mongodb'; - - SSIPAuthenticate( - this, - kerberos.processes.MongoAuthProcess, - username, - password, - gssapiServiceName, - sendAuthCommand, - connection, - mechanismProperties, - callback - ); - } - - /** - * Authenticate - * @override - * @method - */ - auth(sendAuthCommand, connections, credentials, callback) { - if (kerberos == null) { - try { - kerberos = retrieveKerberos(); - } catch (e) { - return callback(e, null); - } - } - - super.auth(sendAuthCommand, connections, credentials, callback); - } -} - -function SSIPAuthenticate( - self, - MongoAuthProcess, - username, - password, - gssapiServiceName, - sendAuthCommand, - connection, - options, - callback -) { - const authProcess = new MongoAuthProcess( - connection.host, - connection.port, - gssapiServiceName, - options - ); - - function authCommand(command, authCb) { - sendAuthCommand(connection, '$external.$cmd', command, authCb); - } - - authProcess.init(username, password, err => { - if (err) return callback(err, false); - - authProcess.transition('', (err, payload) => { - if (err) return callback(err, false); - - const command = { - saslStart: 1, - mechanism: 'GSSAPI', - payload, - autoAuthorize: 1 - }; - - authCommand(command, (err, doc) => { - if (err) return callback(err, false); - - authProcess.transition(doc.payload, (err, payload) => { - if (err) return callback(err, false); - const command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload - }; - - authCommand(command, (err, doc) => { - if (err) return callback(err, false); - - authProcess.transition(doc.payload, (err, payload) => { - if (err) return callback(err, false); - const command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload - }; - - authCommand(command, (err, response) => { - if (err) return callback(err, false); - - authProcess.transition(null, err => { - if (err) return callback(err, null); - callback(null, response); - }); - }); - }); - }); - }); - }); - }); - }); -} - -module.exports = SSPI; diff --git a/node_modules/mongodb/lib/core/auth/x509.js b/node_modules/mongodb/lib/core/auth/x509.js deleted file mode 100644 index 10d5b58..0000000 --- a/node_modules/mongodb/lib/core/auth/x509.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -const AuthProvider = require('./auth_provider').AuthProvider; - -/** - * Creates a new X509 authentication mechanism - * @class - * @extends AuthProvider - */ -class X509 extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const username = credentials.username; - const command = { authenticate: 1, mechanism: 'MONGODB-X509' }; - if (username) { - command.user = username; - } - - sendAuthCommand(connection, '$external.$cmd', command, callback); - } -} - -module.exports = X509; diff --git a/node_modules/mongodb/lib/core/connection/apm.js b/node_modules/mongodb/lib/core/connection/apm.js deleted file mode 100644 index 82858ef..0000000 --- a/node_modules/mongodb/lib/core/connection/apm.js +++ /dev/null @@ -1,251 +0,0 @@ -'use strict'; -const Msg = require('../connection/msg').Msg; -const KillCursor = require('../connection/commands').KillCursor; -const GetMore = require('../connection/commands').GetMore; -const calculateDurationInMs = require('../utils').calculateDurationInMs; - -/** Commands that we want to redact because of the sensitive nature of their contents */ -const SENSITIVE_COMMANDS = new Set([ - 'authenticate', - 'saslStart', - 'saslContinue', - 'getnonce', - 'createUser', - 'updateUser', - 'copydbgetnonce', - 'copydbsaslstart', - 'copydb' -]); - -// helper methods -const extractCommandName = commandDoc => Object.keys(commandDoc)[0]; -const namespace = command => command.ns; -const databaseName = command => command.ns.split('.')[0]; -const collectionName = command => command.ns.split('.')[1]; -const generateConnectionId = pool => - pool.options ? `${pool.options.host}:${pool.options.port}` : pool.address; -const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result); -const isLegacyPool = pool => pool.s && pool.queue; - -const LEGACY_FIND_QUERY_MAP = { - $query: 'filter', - $orderby: 'sort', - $hint: 'hint', - $comment: 'comment', - $maxScan: 'maxScan', - $max: 'max', - $min: 'min', - $returnKey: 'returnKey', - $showDiskLoc: 'showRecordId', - $maxTimeMS: 'maxTimeMS', - $snapshot: 'snapshot' -}; - -const LEGACY_FIND_OPTIONS_MAP = { - numberToSkip: 'skip', - numberToReturn: 'batchSize', - returnFieldsSelector: 'projection' -}; - -const OP_QUERY_KEYS = [ - 'tailable', - 'oplogReplay', - 'noCursorTimeout', - 'awaitData', - 'partial', - 'exhaust' -]; - -/** - * Extract the actual command from the query, possibly upconverting if it's a legacy - * format - * - * @param {Object} command the command - */ -const extractCommand = command => { - if (command instanceof GetMore) { - return { - getMore: command.cursorId, - collection: collectionName(command), - batchSize: command.numberToReturn - }; - } - - if (command instanceof KillCursor) { - return { - killCursors: collectionName(command), - cursors: command.cursorIds - }; - } - - if (command instanceof Msg) { - return command.command; - } - - if (command.query && command.query.$query) { - let result; - if (command.ns === 'admin.$cmd') { - // upconvert legacy command - result = Object.assign({}, command.query.$query); - } else { - // upconvert legacy find command - result = { find: collectionName(command) }; - Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { - if (typeof command.query[key] !== 'undefined') - result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key]; - }); - } - - Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { - if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key]; - }); - - OP_QUERY_KEYS.forEach(key => { - if (command[key]) result[key] = command[key]; - }); - - if (typeof command.pre32Limit !== 'undefined') { - result.limit = command.pre32Limit; - } - - if (command.query.$explain) { - return { explain: result }; - } - - return result; - } - - return command.query ? command.query : command; -}; - -const extractReply = (command, reply) => { - if (command instanceof GetMore) { - return { - ok: 1, - cursor: { - id: reply.message.cursorId, - ns: namespace(command), - nextBatch: reply.message.documents - } - }; - } - - if (command instanceof KillCursor) { - return { - ok: 1, - cursorsUnknown: command.cursorIds - }; - } - - // is this a legacy find command? - if (command.query && typeof command.query.$query !== 'undefined') { - return { - ok: 1, - cursor: { - id: reply.message.cursorId, - ns: namespace(command), - firstBatch: reply.message.documents - } - }; - } - - return reply && reply.result ? reply.result : reply; -}; - -const extractConnectionDetails = pool => { - if (isLegacyPool(pool)) { - return { - connectionId: generateConnectionId(pool) - }; - } - - // APM in the modern pool is done at the `Connection` level, so we rename it here for - // readability. - const connection = pool; - return { - address: connection.address, - connectionId: connection.id - }; -}; - -/** An event indicating the start of a given command */ -class CommandStartedEvent { - /** - * Create a started event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - */ - constructor(pool, command) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - const connectionDetails = extractConnectionDetails(pool); - - // NOTE: remove in major revision, this is not spec behavior - if (SENSITIVE_COMMANDS.has(commandName)) { - this.commandObj = {}; - this.commandObj[commandName] = true; - } - - Object.assign(this, connectionDetails, { - requestId: command.requestId, - databaseName: databaseName(command), - commandName, - command: cmd - }); - } -} - -/** An event indicating the success of a given command */ -class CommandSucceededEvent { - /** - * Create a succeeded event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - * @param {Object} reply the reply for this command from the server - * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration - */ - constructor(pool, command, reply, started) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - const connectionDetails = extractConnectionDetails(pool); - - Object.assign(this, connectionDetails, { - requestId: command.requestId, - commandName, - duration: calculateDurationInMs(started), - reply: maybeRedact(commandName, extractReply(command, reply)) - }); - } -} - -/** An event indicating the failure of a given command */ -class CommandFailedEvent { - /** - * Create a failure event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - * @param {MongoError|Object} error the generated error or a server error response - * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration - */ - constructor(pool, command, error, started) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - const connectionDetails = extractConnectionDetails(pool); - - Object.assign(this, connectionDetails, { - requestId: command.requestId, - commandName, - duration: calculateDurationInMs(started), - failure: maybeRedact(commandName, error) - }); - } -} - -module.exports = { - CommandStartedEvent, - CommandSucceededEvent, - CommandFailedEvent -}; diff --git a/node_modules/mongodb/lib/core/connection/command_result.js b/node_modules/mongodb/lib/core/connection/command_result.js deleted file mode 100644 index 762aa3f..0000000 --- a/node_modules/mongodb/lib/core/connection/command_result.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -/** - * Creates a new CommandResult instance - * @class - * @param {object} result CommandResult object - * @param {Connection} connection A connection instance associated with this result - * @return {CommandResult} A cursor instance - */ -var CommandResult = function(result, connection, message) { - this.result = result; - this.connection = connection; - this.message = message; -}; - -/** - * Convert CommandResult to JSON - * @method - * @return {object} - */ -CommandResult.prototype.toJSON = function() { - let result = Object.assign({}, this, this.result); - delete result.message; - return result; -}; - -/** - * Convert CommandResult to String representation - * @method - * @return {string} - */ -CommandResult.prototype.toString = function() { - return JSON.stringify(this.toJSON()); -}; - -module.exports = CommandResult; diff --git a/node_modules/mongodb/lib/core/connection/commands.js b/node_modules/mongodb/lib/core/connection/commands.js deleted file mode 100644 index b24ff84..0000000 --- a/node_modules/mongodb/lib/core/connection/commands.js +++ /dev/null @@ -1,507 +0,0 @@ -'use strict'; - -var retrieveBSON = require('./utils').retrieveBSON; -var BSON = retrieveBSON(); -var Long = BSON.Long; -const Buffer = require('safe-buffer').Buffer; - -// Incrementing request id -var _requestId = 0; - -// Wire command operation ids -var opcodes = require('../wireprotocol/shared').opcodes; - -// Query flags -var OPTS_TAILABLE_CURSOR = 2; -var OPTS_SLAVE = 4; -var OPTS_OPLOG_REPLAY = 8; -var OPTS_NO_CURSOR_TIMEOUT = 16; -var OPTS_AWAIT_DATA = 32; -var OPTS_EXHAUST = 64; -var OPTS_PARTIAL = 128; - -// Response flags -var CURSOR_NOT_FOUND = 1; -var QUERY_FAILURE = 2; -var SHARD_CONFIG_STALE = 4; -var AWAIT_CAPABLE = 8; - -/************************************************************** - * QUERY - **************************************************************/ -var Query = function(bson, ns, query, options) { - var self = this; - // Basic options needed to be passed in - if (ns == null) throw new Error('ns must be specified for query'); - if (query == null) throw new Error('query must be specified for query'); - - // Validate that we are not passing 0x00 in the collection name - if (ns.indexOf('\x00') !== -1) { - throw new Error('namespace cannot contain a null character'); - } - - // Basic options - this.bson = bson; - this.ns = ns; - this.query = query; - - // Additional options - this.numberToSkip = options.numberToSkip || 0; - this.numberToReturn = options.numberToReturn || 0; - this.returnFieldSelector = options.returnFieldSelector || null; - this.requestId = Query.getRequestId(); - - // special case for pre-3.2 find commands, delete ASAP - this.pre32Limit = options.pre32Limit; - - // Serialization option - this.serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; - this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true; - this.batchSize = self.numberToReturn; - - // Flags - this.tailable = false; - this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; - this.oplogReplay = false; - this.noCursorTimeout = false; - this.awaitData = false; - this.exhaust = false; - this.partial = false; -}; - -// -// Assign a new request Id -Query.prototype.incRequestId = function() { - this.requestId = _requestId++; -}; - -// -// Assign a new request Id -Query.nextRequestId = function() { - return _requestId + 1; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -Query.prototype.toBin = function() { - var self = this; - var buffers = []; - var projection = null; - - // Set up the flags - var flags = 0; - if (this.tailable) { - flags |= OPTS_TAILABLE_CURSOR; - } - - if (this.slaveOk) { - flags |= OPTS_SLAVE; - } - - if (this.oplogReplay) { - flags |= OPTS_OPLOG_REPLAY; - } - - if (this.noCursorTimeout) { - flags |= OPTS_NO_CURSOR_TIMEOUT; - } - - if (this.awaitData) { - flags |= OPTS_AWAIT_DATA; - } - - if (this.exhaust) { - flags |= OPTS_EXHAUST; - } - - if (this.partial) { - flags |= OPTS_PARTIAL; - } - - // If batchSize is different to self.numberToReturn - if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize; - - // Allocate write protocol header buffer - var header = Buffer.alloc( - 4 * 4 + // Header - 4 + // Flags - Buffer.byteLength(self.ns) + - 1 + // namespace - 4 + // numberToSkip - 4 // numberToReturn - ); - - // Add header to buffers - buffers.push(header); - - // Serialize the query - var query = self.bson.serialize(this.query, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - - // Add query document - buffers.push(query); - - if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { - // Serialize the projection document - projection = self.bson.serialize(this.returnFieldSelector, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - // Add projection document - buffers.push(projection); - } - - // Total message size - var totalLength = header.length + query.length + (projection ? projection.length : 0); - - // Set up the index - var index = 4; - - // Write total document length - header[3] = (totalLength >> 24) & 0xff; - header[2] = (totalLength >> 16) & 0xff; - header[1] = (totalLength >> 8) & 0xff; - header[0] = totalLength & 0xff; - - // Write header information requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = this.requestId & 0xff; - index = index + 4; - - // Write header information responseTo - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = 0 & 0xff; - index = index + 4; - - // Write header information OP_QUERY - header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff; - header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff; - header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff; - header[index] = opcodes.OP_QUERY & 0xff; - index = index + 4; - - // Write header information flags - header[index + 3] = (flags >> 24) & 0xff; - header[index + 2] = (flags >> 16) & 0xff; - header[index + 1] = (flags >> 8) & 0xff; - header[index] = flags & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Write header information flags numberToSkip - header[index + 3] = (this.numberToSkip >> 24) & 0xff; - header[index + 2] = (this.numberToSkip >> 16) & 0xff; - header[index + 1] = (this.numberToSkip >> 8) & 0xff; - header[index] = this.numberToSkip & 0xff; - index = index + 4; - - // Write header information flags numberToReturn - header[index + 3] = (this.numberToReturn >> 24) & 0xff; - header[index + 2] = (this.numberToReturn >> 16) & 0xff; - header[index + 1] = (this.numberToReturn >> 8) & 0xff; - header[index] = this.numberToReturn & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -}; - -Query.getRequestId = function() { - return ++_requestId; -}; - -/************************************************************** - * GETMORE - **************************************************************/ -var GetMore = function(bson, ns, cursorId, opts) { - opts = opts || {}; - this.numberToReturn = opts.numberToReturn || 0; - this.requestId = _requestId++; - this.bson = bson; - this.ns = ns; - this.cursorId = cursorId; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -GetMore.prototype.toBin = function() { - var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; - // Create command buffer - var index = 0; - // Allocate buffer - var _buffer = Buffer.alloc(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = length & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = this.requestId & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_GETMORE); - _buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff; - _buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff; - _buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff; - _buffer[index] = opcodes.OP_GETMORE & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // Write collection name - index = index + _buffer.write(this.ns, index, 'utf8') + 1; - _buffer[index - 1] = 0; - - // Write batch size - // index = write32bit(index, _buffer, numberToReturn); - _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; - _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; - _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; - _buffer[index] = this.numberToReturn & 0xff; - index = index + 4; - - // Write cursor id - // index = write32bit(index, _buffer, cursorId.getLowBits()); - _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; - _buffer[index] = this.cursorId.getLowBits() & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorId.getHighBits()); - _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; - _buffer[index] = this.cursorId.getHighBits() & 0xff; - index = index + 4; - - // Return buffer - return _buffer; -}; - -/************************************************************** - * KILLCURSOR - **************************************************************/ -var KillCursor = function(bson, ns, cursorIds) { - this.ns = ns; - this.requestId = _requestId++; - this.cursorIds = cursorIds; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -KillCursor.prototype.toBin = function() { - var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; - - // Create command buffer - var index = 0; - var _buffer = Buffer.alloc(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = length & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = this.requestId & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_KILL_CURSORS); - _buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff; - _buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff; - _buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff; - _buffer[index] = opcodes.OP_KILL_CURSORS & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // Write batch size - // index = write32bit(index, _buffer, this.cursorIds.length); - _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; - _buffer[index] = this.cursorIds.length & 0xff; - index = index + 4; - - // Write all the cursor ids into the array - for (var i = 0; i < this.cursorIds.length; i++) { - // Write cursor id - // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); - _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; - _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); - _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; - _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; - index = index + 4; - } - - // Return buffer - return _buffer; -}; - -var Response = function(bson, message, msgHeader, msgBody, opts) { - opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; - this.parsed = false; - this.raw = message; - this.data = msgBody; - this.bson = bson; - this.opts = opts; - - // Read the message header - this.length = msgHeader.length; - this.requestId = msgHeader.requestId; - this.responseTo = msgHeader.responseTo; - this.opCode = msgHeader.opCode; - this.fromCompressed = msgHeader.fromCompressed; - - // Read the message body - this.responseFlags = msgBody.readInt32LE(0); - this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); - this.startingFrom = msgBody.readInt32LE(12); - this.numberReturned = msgBody.readInt32LE(16); - - // Preallocate document array - this.documents = new Array(this.numberReturned); - - // Flag values - this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; - this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; - this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; - this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; - this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; - this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; - this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; -}; - -Response.prototype.isParsed = function() { - return this.parsed; -}; - -Response.prototype.parse = function(options) { - // Don't parse again if not needed - if (this.parsed) return; - options = options || {}; - - // Allow the return of raw documents instead of parsing - var raw = options.raw || false; - var documentsReturnedIn = options.documentsReturnedIn || null; - var promoteLongs = - typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; - var promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; - var promoteBuffers = - typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers; - var bsonSize, _options; - - // Set up the options - _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers - }; - - // Position within OP_REPLY at which documents start - // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) - this.index = 20; - - // - // Parse Body - // - for (var i = 0; i < this.numberReturned; i++) { - bsonSize = - this.data[this.index] | - (this.data[this.index + 1] << 8) | - (this.data[this.index + 2] << 16) | - (this.data[this.index + 3] << 24); - - // If we have raw results specified slice the return document - if (raw) { - this.documents[i] = this.data.slice(this.index, this.index + bsonSize); - } else { - this.documents[i] = this.bson.deserialize( - this.data.slice(this.index, this.index + bsonSize), - _options - ); - } - - // Adjust the index - this.index = this.index + bsonSize; - } - - if (this.documents.length === 1 && documentsReturnedIn != null && raw) { - const fieldsAsRaw = {}; - fieldsAsRaw[documentsReturnedIn] = true; - _options.fieldsAsRaw = fieldsAsRaw; - - const doc = this.bson.deserialize(this.documents[0], _options); - this.documents = [doc]; - } - - // Set parsed - this.parsed = true; -}; - -module.exports = { - Query: Query, - GetMore: GetMore, - Response: Response, - KillCursor: KillCursor -}; diff --git a/node_modules/mongodb/lib/core/connection/connect.js b/node_modules/mongodb/lib/core/connection/connect.js deleted file mode 100644 index b096e21..0000000 --- a/node_modules/mongodb/lib/core/connection/connect.js +++ /dev/null @@ -1,416 +0,0 @@ -'use strict'; -const net = require('net'); -const tls = require('tls'); -const Connection = require('./connection'); -const Query = require('./commands').Query; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; -const WIRE_CONSTANTS = require('../wireprotocol/constants'); -const makeClientMetadata = require('../utils').makeClientMetadata; -const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; -const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; -const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; -const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; -let AUTH_PROVIDERS; - -function connect(options, cancellationToken, callback) { - if (typeof cancellationToken === 'function') { - callback = cancellationToken; - cancellationToken = undefined; - } - - const ConnectionType = options && options.connectionType ? options.connectionType : Connection; - if (AUTH_PROVIDERS == null) { - AUTH_PROVIDERS = defaultAuthProviders(options.bson); - } - - const family = options.family !== void 0 ? options.family : 0; - makeConnection(family, options, cancellationToken, (err, socket) => { - if (err) { - callback(err, socket); // in the error case, `socket` is the originating error event name - return; - } - - performInitialHandshake(new ConnectionType(socket, options), options, callback); - }); -} - -function isModernConnectionType(conn) { - return typeof conn.command === 'function'; -} - -function getSaslSupportedMechs(options) { - if (!(options && options.credentials)) { - return {}; - } - - const credentials = options.credentials; - - // TODO: revisit whether or not items like `options.user` and `options.dbName` should be checked here - const authMechanism = credentials.mechanism; - const authSource = credentials.source || options.dbName || 'admin'; - const user = credentials.username || options.user; - - if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') { - return {}; - } - - if (!user) { - return {}; - } - - return { saslSupportedMechs: `${authSource}.${user}` }; -} - -function checkSupportedServer(ismaster, options) { - const serverVersionHighEnough = - ismaster && - typeof ismaster.maxWireVersion === 'number' && - ismaster.maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION; - const serverVersionLowEnough = - ismaster && - typeof ismaster.minWireVersion === 'number' && - ismaster.minWireVersion <= MAX_SUPPORTED_WIRE_VERSION; - - if (serverVersionHighEnough) { - if (serverVersionLowEnough) { - return null; - } - - const message = `Server at ${options.host}:${options.port} reports minimum wire version ${ismaster.minWireVersion}, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; - return new MongoError(message); - } - - const message = `Server at ${options.host}:${ - options.port - } reports maximum wire version ${ismaster.maxWireVersion || - 0}, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`; - return new MongoError(message); -} - -function performInitialHandshake(conn, options, _callback) { - const callback = function(err, ret) { - if (err && conn) { - conn.destroy(); - } - _callback(err, ret); - }; - - let compressors = []; - if (options.compression && options.compression.compressors) { - compressors = options.compression.compressors; - } - - const handshakeDoc = Object.assign( - { - ismaster: true, - client: options.metadata || makeClientMetadata(options), - compression: compressors - }, - getSaslSupportedMechs(options) - ); - - const handshakeOptions = Object.assign({}, options); - - // The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS - if (options.connectTimeoutMS || options.connectionTimeout) { - handshakeOptions.socketTimeout = options.connectTimeoutMS || options.connectionTimeout; - } - - const start = new Date().getTime(); - runCommand(conn, 'admin.$cmd', handshakeDoc, handshakeOptions, (err, ismaster) => { - if (err) { - callback(err); - return; - } - - if (ismaster.ok === 0) { - callback(new MongoError(ismaster)); - return; - } - - const supportedServerErr = checkSupportedServer(ismaster, options); - if (supportedServerErr) { - callback(supportedServerErr); - return; - } - - if (!isModernConnectionType(conn)) { - // resolve compression - if (ismaster.compression) { - const agreedCompressors = compressors.filter( - compressor => ismaster.compression.indexOf(compressor) !== -1 - ); - - if (agreedCompressors.length) { - conn.agreedCompressor = agreedCompressors[0]; - } - - if (options.compression && options.compression.zlibCompressionLevel) { - conn.zlibCompressionLevel = options.compression.zlibCompressionLevel; - } - } - } - - // NOTE: This is metadata attached to the connection while porting away from - // handshake being done in the `Server` class. Likely, it should be - // relocated, or at very least restructured. - conn.ismaster = ismaster; - conn.lastIsMasterMS = new Date().getTime() - start; - - const credentials = options.credentials; - if (!ismaster.arbiterOnly && credentials) { - credentials.resolveAuthMechanism(ismaster); - authenticate(conn, credentials, callback); - return; - } - - callback(undefined, conn); - }); -} - -const LEGAL_SSL_SOCKET_OPTIONS = [ - 'pfx', - 'key', - 'passphrase', - 'cert', - 'ca', - 'ciphers', - 'NPNProtocols', - 'ALPNProtocols', - 'servername', - 'ecdhCurve', - 'secureProtocol', - 'secureContext', - 'session', - 'minDHSize', - 'crl', - 'rejectUnauthorized' -]; - -function parseConnectOptions(family, options) { - const host = typeof options.host === 'string' ? options.host : 'localhost'; - if (host.indexOf('/') !== -1) { - return { path: host }; - } - - const result = { - family, - host, - port: typeof options.port === 'number' ? options.port : 27017, - rejectUnauthorized: false - }; - - return result; -} - -function parseSslOptions(family, options) { - const result = parseConnectOptions(family, options); - - // Merge in valid SSL options - for (const name in options) { - if (options[name] != null && LEGAL_SSL_SOCKET_OPTIONS.indexOf(name) !== -1) { - result[name] = options[name]; - } - } - - // Override checkServerIdentity behavior - if (options.checkServerIdentity === false) { - // Skip the identiy check by retuning undefined as per node documents - // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback - result.checkServerIdentity = function() { - return undefined; - }; - } else if (typeof options.checkServerIdentity === 'function') { - result.checkServerIdentity = options.checkServerIdentity; - } - - // Set default sni servername to be the same as host - if (result.servername == null) { - result.servername = result.host; - } - - return result; -} - -const SOCKET_ERROR_EVENTS = new Set(['error', 'close', 'timeout', 'parseError']); -function makeConnection(family, options, cancellationToken, _callback) { - const useSsl = typeof options.ssl === 'boolean' ? options.ssl : false; - const keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; - let keepAliveInitialDelay = - typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; - const noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true; - const connectionTimeout = - typeof options.connectionTimeout === 'number' - ? options.connectionTimeout - : typeof options.connectTimeoutMS === 'number' - ? options.connectTimeoutMS - : 30000; - const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - const rejectUnauthorized = - typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true; - - if (keepAliveInitialDelay > socketTimeout) { - keepAliveInitialDelay = Math.round(socketTimeout / 2); - } - - let socket; - const callback = function(err, ret) { - if (err && socket) { - socket.destroy(); - } - - _callback(err, ret); - }; - - try { - if (useSsl) { - socket = tls.connect(parseSslOptions(family, options)); - if (typeof socket.disableRenegotiation === 'function') { - socket.disableRenegotiation(); - } - } else { - socket = net.createConnection(parseConnectOptions(family, options)); - } - } catch (err) { - return callback(err); - } - - socket.setKeepAlive(keepAlive, keepAliveInitialDelay); - socket.setTimeout(connectionTimeout); - socket.setNoDelay(noDelay); - - const connectEvent = useSsl ? 'secureConnect' : 'connect'; - let cancellationHandler; - function errorHandler(eventName) { - return err => { - SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); - if (cancellationHandler) { - cancellationToken.removeListener('cancel', cancellationHandler); - } - - socket.removeListener(connectEvent, connectHandler); - callback(connectionFailureError(eventName, err)); - }; - } - - function connectHandler() { - SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); - if (cancellationHandler) { - cancellationToken.removeListener('cancel', cancellationHandler); - } - - if (socket.authorizationError && rejectUnauthorized) { - return callback(socket.authorizationError); - } - - socket.setTimeout(socketTimeout); - callback(null, socket); - } - - SOCKET_ERROR_EVENTS.forEach(event => socket.once(event, errorHandler(event))); - if (cancellationToken) { - cancellationHandler = errorHandler('cancel'); - cancellationToken.once('cancel', cancellationHandler); - } - - socket.once(connectEvent, connectHandler); -} - -const CONNECTION_ERROR_EVENTS = ['error', 'close', 'timeout', 'parseError']; -function runCommand(conn, ns, command, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - - // are we using the new connection type? if so, no need to simulate a rpc `command` method - if (isModernConnectionType(conn)) { - conn.command(ns, command, options, (err, result) => { - if (err) { - callback(err); - return; - } - - // NODE-2382: raw wire protocol messages, or command results should not be used anymore - callback(undefined, result.result); - }); - - return; - } - - const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - const bson = conn.options.bson; - const query = new Query(bson, ns, command, { - numberToSkip: 0, - numberToReturn: 1 - }); - - const noop = () => {}; - function _callback(err, result) { - callback(err, result); - callback = noop; - } - - function errorHandler(err) { - conn.resetSocketTimeout(); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); - conn.removeListener('message', messageHandler); - - if (err == null) { - err = new MongoError(`runCommand failed for connection to '${conn.address}'`); - } - - // ignore all future errors - conn.on('error', noop); - - _callback(err); - } - - function messageHandler(msg) { - if (msg.responseTo !== query.requestId) { - return; - } - - conn.resetSocketTimeout(); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); - conn.removeListener('message', messageHandler); - - msg.parse({ promoteValues: true }); - _callback(undefined, msg.documents[0]); - } - - conn.setSocketTimeout(socketTimeout); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.once(eventName, errorHandler)); - conn.on('message', messageHandler); - conn.write(query.toBin()); -} - -function authenticate(conn, credentials, callback) { - const mechanism = credentials.mechanism; - if (!AUTH_PROVIDERS[mechanism]) { - callback(new MongoError(`authMechanism '${mechanism}' not supported`)); - return; - } - - const provider = AUTH_PROVIDERS[mechanism]; - provider.auth(runCommand, [conn], credentials, err => { - if (err) return callback(err); - callback(undefined, conn); - }); -} - -function connectionFailureError(type, err) { - switch (type) { - case 'error': - return new MongoNetworkError(err); - case 'timeout': - return new MongoNetworkError(`connection timed out`); - case 'close': - return new MongoNetworkError(`connection closed`); - case 'cancel': - return new MongoNetworkError(`connection establishment was cancelled`); - default: - return new MongoNetworkError(`unknown network error`); - } -} - -module.exports = connect; diff --git a/node_modules/mongodb/lib/core/connection/connection.js b/node_modules/mongodb/lib/core/connection/connection.js deleted file mode 100644 index c1c5a3b..0000000 --- a/node_modules/mongodb/lib/core/connection/connection.js +++ /dev/null @@ -1,644 +0,0 @@ -'use strict'; - -const EventEmitter = require('events').EventEmitter; -const crypto = require('crypto'); -const debugOptions = require('./utils').debugOptions; -const parseHeader = require('../wireprotocol/shared').parseHeader; -const decompress = require('../wireprotocol/compression').decompress; -const Response = require('./commands').Response; -const BinMsg = require('./msg').BinMsg; -const MongoNetworkError = require('../error').MongoNetworkError; -const MongoError = require('../error').MongoError; -const Logger = require('./logger'); -const OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED; -const OP_MSG = require('../wireprotocol/shared').opcodes.OP_MSG; -const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; -const Buffer = require('safe-buffer').Buffer; - -let _id = 0; - -const DEFAULT_MAX_BSON_MESSAGE_SIZE = 1024 * 1024 * 16 * 4; -const DEBUG_FIELDS = [ - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'checkServerIdentity' -]; - -let connectionAccountingSpy = undefined; -let connectionAccounting = false; -let connections = {}; - -/** - * A class representing a single connection to a MongoDB server - * - * @fires Connection#connect - * @fires Connection#close - * @fires Connection#error - * @fires Connection#timeout - * @fires Connection#parseError - * @fires Connection#message - */ -class Connection extends EventEmitter { - /** - * Creates a new Connection instance - * - * **NOTE**: Internal class, do not instantiate directly - * - * @param {Socket} socket The socket this connection wraps - * @param {Object} options Various settings - * @param {object} options.bson An implementation of bson serialize and deserialize - * @param {string} [options.host='localhost'] The host the socket is connected to - * @param {number} [options.port=27017] The port used for the socket connection - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {boolean} [options.promoteLongs] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers] Promotes Binary BSON values to native Node Buffers. - * @param {number} [options.maxBsonMessageSize=0x4000000] Largest possible size of a BSON message (for legacy purposes) - */ - constructor(socket, options) { - super(); - - options = options || {}; - if (!options.bson) { - throw new TypeError('must pass in valid bson parser'); - } - - this.id = _id++; - this.options = options; - this.logger = Logger('Connection', options); - this.bson = options.bson; - this.tag = options.tag; - this.maxBsonMessageSize = options.maxBsonMessageSize || DEFAULT_MAX_BSON_MESSAGE_SIZE; - - this.port = options.port || 27017; - this.host = options.host || 'localhost'; - this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - - // These values are inspected directly in tests, but maybe not necessary to keep around - this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; - this.keepAliveInitialDelay = - typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; - this.connectionTimeout = - typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; - if (this.keepAliveInitialDelay > this.socketTimeout) { - this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2); - } - - // Debug information - if (this.logger.isDebug()) { - this.logger.debug( - `creating connection ${this.id} with options [${JSON.stringify( - debugOptions(DEBUG_FIELDS, options) - )}]` - ); - } - - // Response options - this.responseOptions = { - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false - }; - - // Flushing - this.flushing = false; - this.queue = []; - - // Internal state - this.writeStream = null; - this.destroyed = false; - this.timedOut = false; - - // Create hash method - const hash = crypto.createHash('sha1'); - hash.update(this.address); - this.hashedName = hash.digest('hex'); - - // All operations in flight on the connection - this.workItems = []; - - // setup socket - this.socket = socket; - this.socket.once('error', errorHandler(this)); - this.socket.once('timeout', timeoutHandler(this)); - this.socket.once('close', closeHandler(this)); - this.socket.on('data', dataHandler(this)); - - if (connectionAccounting) { - addConnection(this.id, this); - } - } - - setSocketTimeout(value) { - if (this.socket) { - this.socket.setTimeout(value); - } - } - - resetSocketTimeout() { - if (this.socket) { - this.socket.setTimeout(this.socketTimeout); - } - } - - static enableConnectionAccounting(spy) { - if (spy) { - connectionAccountingSpy = spy; - } - - connectionAccounting = true; - connections = {}; - } - - static disableConnectionAccounting() { - connectionAccounting = false; - connectionAccountingSpy = undefined; - } - - static connections() { - return connections; - } - - get address() { - return `${this.host}:${this.port}`; - } - - /** - * Unref this connection - * @method - * @return {boolean} - */ - unref() { - if (this.socket == null) { - this.once('connect', () => this.socket.unref()); - return; - } - - this.socket.unref(); - } - - /** - * Flush all work Items on this connection - * - * @param {*} err The error to propagate to the flushed work items - */ - flush(err) { - while (this.workItems.length > 0) { - const workItem = this.workItems.shift(); - if (workItem.cb) { - workItem.cb(err); - } - } - } - - /** - * Destroy connection - * @method - */ - destroy(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = Object.assign({ force: false }, options); - - if (connectionAccounting) { - deleteConnection(this.id); - } - - if (this.socket == null) { - this.destroyed = true; - return; - } - - if (options.force || this.timedOut) { - this.socket.destroy(); - this.destroyed = true; - if (typeof callback === 'function') callback(null, null); - return; - } - - this.socket.end(err => { - this.destroyed = true; - if (typeof callback === 'function') callback(err, null); - }); - } - - /** - * Write to connection - * @method - * @param {Command} command Command to write out need to implement toBin and toBinUnified - */ - write(buffer) { - // Debug Log - if (this.logger.isDebug()) { - if (!Array.isArray(buffer)) { - this.logger.debug(`writing buffer [${buffer.toString('hex')}] to ${this.address}`); - } else { - for (let i = 0; i < buffer.length; i++) - this.logger.debug(`writing buffer [${buffer[i].toString('hex')}] to ${this.address}`); - } - } - - // Double check that the connection is not destroyed - if (this.socket.destroyed === false) { - // Write out the command - if (!Array.isArray(buffer)) { - this.socket.write(buffer, 'binary'); - return true; - } - - // Iterate over all buffers and write them in order to the socket - for (let i = 0; i < buffer.length; i++) { - this.socket.write(buffer[i], 'binary'); - } - - return true; - } - - // Connection is destroyed return write failed - return false; - } - - /** - * Return id of connection as a string - * @method - * @return {string} - */ - toString() { - return '' + this.id; - } - - /** - * Return json object of connection - * @method - * @return {object} - */ - toJSON() { - return { id: this.id, host: this.host, port: this.port }; - } - - /** - * Is the connection connected - * @method - * @return {boolean} - */ - isConnected() { - if (this.destroyed) return false; - return !this.socket.destroyed && this.socket.writable; - } -} - -function deleteConnection(id) { - // console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : '')) - delete connections[id]; - - if (connectionAccountingSpy) { - connectionAccountingSpy.deleteConnection(id); - } -} - -function addConnection(id, connection) { - // console.log("=== added connection " + id + " :: " + connection.port) - connections[id] = connection; - - if (connectionAccountingSpy) { - connectionAccountingSpy.addConnection(id, connection); - } -} - -// -// Connection handlers -function errorHandler(conn) { - return function(err) { - if (connectionAccounting) deleteConnection(conn.id); - // Debug information - if (conn.logger.isDebug()) { - conn.logger.debug( - `connection ${conn.id} for [${conn.address}] errored out with [${JSON.stringify(err)}]` - ); - } - - conn.emit('error', new MongoNetworkError(err), conn); - }; -} - -function timeoutHandler(conn) { - return function() { - if (connectionAccounting) deleteConnection(conn.id); - - if (conn.logger.isDebug()) { - conn.logger.debug(`connection ${conn.id} for [${conn.address}] timed out`); - } - - conn.timedOut = true; - conn.emit( - 'timeout', - new MongoNetworkError(`connection ${conn.id} to ${conn.address} timed out`), - conn - ); - }; -} - -function closeHandler(conn) { - return function(hadError) { - if (connectionAccounting) deleteConnection(conn.id); - - if (conn.logger.isDebug()) { - conn.logger.debug(`connection ${conn.id} with for [${conn.address}] closed`); - } - - if (!hadError) { - conn.emit( - 'close', - new MongoNetworkError(`connection ${conn.id} to ${conn.address} closed`), - conn - ); - } - }; -} - -// Handle a message once it is received -function processMessage(conn, message) { - const msgHeader = parseHeader(message); - if (msgHeader.opCode !== OP_COMPRESSED) { - const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; - conn.emit( - 'message', - new ResponseConstructor( - conn.bson, - message, - msgHeader, - message.slice(MESSAGE_HEADER_SIZE), - conn.responseOptions - ), - conn - ); - - return; - } - - msgHeader.fromCompressed = true; - let index = MESSAGE_HEADER_SIZE; - msgHeader.opCode = message.readInt32LE(index); - index += 4; - msgHeader.length = message.readInt32LE(index); - index += 4; - const compressorID = message[index]; - index++; - - decompress(compressorID, message.slice(index), (err, decompressedMsgBody) => { - if (err) { - conn.emit('error', err); - return; - } - - if (decompressedMsgBody.length !== msgHeader.length) { - conn.emit( - 'error', - new MongoError( - 'Decompressing a compressed message from the server failed. The message is corrupt.' - ) - ); - - return; - } - - const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; - conn.emit( - 'message', - new ResponseConstructor( - conn.bson, - message, - msgHeader, - decompressedMsgBody, - conn.responseOptions - ), - conn - ); - }); -} - -function dataHandler(conn) { - return function(data) { - // Parse until we are done with the data - while (data.length > 0) { - // If we still have bytes to read on the current message - if (conn.bytesRead > 0 && conn.sizeOfMessage > 0) { - // Calculate the amount of remaining bytes - const remainingBytesToRead = conn.sizeOfMessage - conn.bytesRead; - // Check if the current chunk contains the rest of the message - if (remainingBytesToRead > data.length) { - // Copy the new data into the exiting buffer (should have been allocated when we know the message size) - data.copy(conn.buffer, conn.bytesRead); - // Adjust the number of bytes read so it point to the correct index in the buffer - conn.bytesRead = conn.bytesRead + data.length; - - // Reset state of buffer - data = Buffer.alloc(0); - } else { - // Copy the missing part of the data into our current buffer - data.copy(conn.buffer, conn.bytesRead, 0, remainingBytesToRead); - // Slice the overflow into a new buffer that we will then re-parse - data = data.slice(remainingBytesToRead); - - // Emit current complete message - const emitBuffer = conn.buffer; - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - - processMessage(conn, emitBuffer); - } - } else { - // Stub buffer is kept in case we don't get enough bytes to determine the - // size of the message (< 4 bytes) - if (conn.stubBuffer != null && conn.stubBuffer.length > 0) { - // If we have enough bytes to determine the message size let's do it - if (conn.stubBuffer.length + data.length > 4) { - // Prepad the data - const newData = Buffer.alloc(conn.stubBuffer.length + data.length); - conn.stubBuffer.copy(newData, 0); - data.copy(newData, conn.stubBuffer.length); - // Reassign for parsing - data = newData; - - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - } else { - // Add the the bytes to the stub buffer - const newStubBuffer = Buffer.alloc(conn.stubBuffer.length + data.length); - // Copy existing stub buffer - conn.stubBuffer.copy(newStubBuffer, 0); - // Copy missing part of the data - data.copy(newStubBuffer, conn.stubBuffer.length); - // Exit parsing loop - data = Buffer.alloc(0); - } - } else { - if (data.length > 4) { - // Retrieve the message size - const sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); - // If we have a negative sizeOfMessage emit error and return - if (sizeOfMessage < 0 || sizeOfMessage > conn.maxBsonMessageSize) { - const errorObject = { - err: 'socketHandler', - trace: '', - bin: conn.buffer, - parseState: { - sizeOfMessage: sizeOfMessage, - bytesRead: conn.bytesRead, - stubBuffer: conn.stubBuffer - } - }; - // We got a parse Error fire it off then keep going - conn.emit('parseError', errorObject, conn); - return; - } - - // Ensure that the size of message is larger than 0 and less than the max allowed - if ( - sizeOfMessage > 4 && - sizeOfMessage < conn.maxBsonMessageSize && - sizeOfMessage > data.length - ) { - conn.buffer = Buffer.alloc(sizeOfMessage); - // Copy all the data into the buffer - data.copy(conn.buffer, 0); - // Update bytes read - conn.bytesRead = data.length; - // Update sizeOfMessage - conn.sizeOfMessage = sizeOfMessage; - // Ensure stub buffer is null - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - } else if ( - sizeOfMessage > 4 && - sizeOfMessage < conn.maxBsonMessageSize && - sizeOfMessage === data.length - ) { - const emitBuffer = data; - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - // Emit the message - processMessage(conn, emitBuffer); - } else if (sizeOfMessage <= 4 || sizeOfMessage > conn.maxBsonMessageSize) { - const errorObject = { - err: 'socketHandler', - trace: null, - bin: data, - parseState: { - sizeOfMessage: sizeOfMessage, - bytesRead: 0, - buffer: null, - stubBuffer: null - } - }; - // We got a parse Error fire it off then keep going - conn.emit('parseError', errorObject, conn); - - // Clear out the state of the parser - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - } else { - const emitBuffer = data.slice(0, sizeOfMessage); - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Copy rest of message - data = data.slice(sizeOfMessage); - // Emit the message - processMessage(conn, emitBuffer); - } - } else { - // Create a buffer that contains the space for the non-complete message - conn.stubBuffer = Buffer.alloc(data.length); - // Copy the data to the stub buffer - data.copy(conn.stubBuffer, 0); - // Exit parsing loop - data = Buffer.alloc(0); - } - } - } - } - }; -} - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Connection#connect - * @type {Connection} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Connection#close - * @type {Connection} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Connection#error - * @type {Connection} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Connection#timeout - * @type {Connection} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Connection#parseError - * @type {Connection} - */ - -/** - * An event emitted each time the connection receives a parsed message from the wire - * - * @event Connection#message - * @type {Connection} - */ - -module.exports = Connection; diff --git a/node_modules/mongodb/lib/core/connection/logger.js b/node_modules/mongodb/lib/core/connection/logger.js deleted file mode 100644 index 3b0be90..0000000 --- a/node_modules/mongodb/lib/core/connection/logger.js +++ /dev/null @@ -1,251 +0,0 @@ -'use strict'; - -var f = require('util').format, - MongoError = require('../error').MongoError; - -// Filters for classes -var classFilters = {}; -var filteredClasses = {}; -var level = null; -// Save the process id -var pid = process.pid; -// current logger -var currentLogger = null; - -/** - * @callback Logger~loggerCallback - * @param {string} msg message being logged - * @param {object} state an object containing more metadata about the logging message - */ - -/** - * Creates a new Logger instance - * @class - * @param {string} className The Class name associated with the logging instance - * @param {object} [options=null] Optional settings. - * @param {Logger~loggerCallback} [options.logger=null] Custom logger function; - * @param {string} [options.loggerLevel=error] Override default global log level. - */ -var Logger = function(className, options) { - if (!(this instanceof Logger)) return new Logger(className, options); - options = options || {}; - - // Current reference - this.className = className; - - // Current logger - if (options.logger) { - currentLogger = options.logger; - } else if (currentLogger == null) { - currentLogger = console.log; - } - - // Set level of logging, default is error - if (options.loggerLevel) { - level = options.loggerLevel || 'error'; - } - - // Add all class names - if (filteredClasses[this.className] == null) classFilters[this.className] = true; -}; - -/** - * Log a message at the debug level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.debug = function(message, object) { - if ( - this.isDebug() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); - var state = { - type: 'debug', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } -}; - -/** - * Log a message at the warn level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -(Logger.prototype.warn = function(message, object) { - if ( - this.isWarn() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); - var state = { - type: 'warn', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } -}), - /** - * Log a message at the info level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ - (Logger.prototype.info = function(message, object) { - if ( - this.isInfo() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); - var state = { - type: 'info', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } - }), - /** - * Log a message at the error level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ - (Logger.prototype.error = function(message, object) { - if ( - this.isError() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); - var state = { - type: 'error', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } - }), - /** - * Is the logger set at info level - * @method - * @return {boolean} - */ - (Logger.prototype.isInfo = function() { - return level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at error level - * @method - * @return {boolean} - */ - (Logger.prototype.isError = function() { - return level === 'error' || level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at error level - * @method - * @return {boolean} - */ - (Logger.prototype.isWarn = function() { - return level === 'error' || level === 'warn' || level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at debug level - * @method - * @return {boolean} - */ - (Logger.prototype.isDebug = function() { - return level === 'debug'; - }); - -/** - * Resets the logger to default settings, error and no filtered classes - * @method - * @return {null} - */ -Logger.reset = function() { - level = 'error'; - filteredClasses = {}; -}; - -/** - * Get the current logger function - * @method - * @return {Logger~loggerCallback} - */ -Logger.currentLogger = function() { - return currentLogger; -}; - -/** - * Set the current logger function - * @method - * @param {Logger~loggerCallback} logger Logger function. - * @return {null} - */ -Logger.setCurrentLogger = function(logger) { - if (typeof logger !== 'function') throw new MongoError('current logger must be a function'); - currentLogger = logger; -}; - -/** - * Set what classes to log. - * @method - * @param {string} type The type of filter (currently only class) - * @param {string[]} values The filters to apply - * @return {null} - */ -Logger.filter = function(type, values) { - if (type === 'class' && Array.isArray(values)) { - filteredClasses = {}; - - values.forEach(function(x) { - filteredClasses[x] = true; - }); - } -}; - -/** - * Set the current log level - * @method - * @param {string} level Set current log level (debug, info, error) - * @return {null} - */ -Logger.setLevel = function(_level) { - if (_level !== 'info' && _level !== 'error' && _level !== 'debug' && _level !== 'warn') { - throw new Error(f('%s is an illegal logging level', _level)); - } - - level = _level; -}; - -module.exports = Logger; diff --git a/node_modules/mongodb/lib/core/connection/msg.js b/node_modules/mongodb/lib/core/connection/msg.js deleted file mode 100644 index 9f15a81..0000000 --- a/node_modules/mongodb/lib/core/connection/msg.js +++ /dev/null @@ -1,222 +0,0 @@ -'use strict'; - -// Implementation of OP_MSG spec: -// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst -// -// struct Section { -// uint8 payloadType; -// union payload { -// document document; // payloadType == 0 -// struct sequence { // payloadType == 1 -// int32 size; -// cstring identifier; -// document* documents; -// }; -// }; -// }; - -// struct OP_MSG { -// struct MsgHeader { -// int32 messageLength; -// int32 requestID; -// int32 responseTo; -// int32 opCode = 2013; -// }; -// uint32 flagBits; -// Section+ sections; -// [uint32 checksum;] -// }; - -const Buffer = require('safe-buffer').Buffer; -const opcodes = require('../wireprotocol/shared').opcodes; -const databaseNamespace = require('../wireprotocol/shared').databaseNamespace; -const ReadPreference = require('../topologies/read_preference'); - -// Incrementing request id -let _requestId = 0; - -// Msg Flags -const OPTS_CHECKSUM_PRESENT = 1; -const OPTS_MORE_TO_COME = 2; -const OPTS_EXHAUST_ALLOWED = 1 << 16; - -class Msg { - constructor(bson, ns, command, options) { - // Basic options needed to be passed in - if (command == null) throw new Error('query must be specified for query'); - - // Basic options - this.bson = bson; - this.ns = ns; - this.command = command; - this.command.$db = databaseNamespace(ns); - - if (options.readPreference && options.readPreference.mode !== ReadPreference.PRIMARY) { - this.command.$readPreference = options.readPreference.toJSON(); - } - - // Ensure empty options - this.options = options || {}; - - // Additional options - this.requestId = options.requestId ? options.requestId : Msg.getRequestId(); - - // Serialization option - this.serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; - - // flags - this.checksumPresent = false; - this.moreToCome = options.moreToCome || false; - this.exhaustAllowed = - typeof options.exhaustAllowed === 'boolean' ? options.exhaustAllowed : false; - } - - toBin() { - const buffers = []; - let flags = 0; - - if (this.checksumPresent) { - flags |= OPTS_CHECKSUM_PRESENT; - } - - if (this.moreToCome) { - flags |= OPTS_MORE_TO_COME; - } - - if (this.exhaustAllowed) { - flags |= OPTS_EXHAUST_ALLOWED; - } - - const header = Buffer.alloc( - 4 * 4 + // Header - 4 // Flags - ); - - buffers.push(header); - - let totalLength = header.length; - const command = this.command; - totalLength += this.makeDocumentSegment(buffers, command); - - header.writeInt32LE(totalLength, 0); // messageLength - header.writeInt32LE(this.requestId, 4); // requestID - header.writeInt32LE(0, 8); // responseTo - header.writeInt32LE(opcodes.OP_MSG, 12); // opCode - header.writeUInt32LE(flags, 16); // flags - return buffers; - } - - makeDocumentSegment(buffers, document) { - const payloadTypeBuffer = Buffer.alloc(1); - payloadTypeBuffer[0] = 0; - - const documentBuffer = this.serializeBson(document); - buffers.push(payloadTypeBuffer); - buffers.push(documentBuffer); - - return payloadTypeBuffer.length + documentBuffer.length; - } - - serializeBson(document) { - return this.bson.serialize(document, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - } -} - -Msg.getRequestId = function() { - _requestId = (_requestId + 1) & 0x7fffffff; - return _requestId; -}; - -class BinMsg { - constructor(bson, message, msgHeader, msgBody, opts) { - opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; - this.parsed = false; - this.raw = message; - this.data = msgBody; - this.bson = bson; - this.opts = opts; - - // Read the message header - this.length = msgHeader.length; - this.requestId = msgHeader.requestId; - this.responseTo = msgHeader.responseTo; - this.opCode = msgHeader.opCode; - this.fromCompressed = msgHeader.fromCompressed; - - // Read response flags - this.responseFlags = msgBody.readInt32LE(0); - this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; - this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; - this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; - this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; - this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; - this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; - - this.documents = []; - } - - isParsed() { - return this.parsed; - } - - parse(options) { - // Don't parse again if not needed - if (this.parsed) return; - options = options || {}; - - this.index = 4; - // Allow the return of raw documents instead of parsing - const raw = options.raw || false; - const documentsReturnedIn = options.documentsReturnedIn || null; - const promoteLongs = - typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; - const promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; - const promoteBuffers = - typeof options.promoteBuffers === 'boolean' - ? options.promoteBuffers - : this.opts.promoteBuffers; - - // Set up the options - const _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers - }; - - while (this.index < this.data.length) { - const payloadType = this.data.readUInt8(this.index++); - if (payloadType === 1) { - console.error('TYPE 1'); - } else if (payloadType === 0) { - const bsonSize = this.data.readUInt32LE(this.index); - const bin = this.data.slice(this.index, this.index + bsonSize); - this.documents.push(raw ? bin : this.bson.deserialize(bin, _options)); - - this.index += bsonSize; - } - } - - if (this.documents.length === 1 && documentsReturnedIn != null && raw) { - const fieldsAsRaw = {}; - fieldsAsRaw[documentsReturnedIn] = true; - _options.fieldsAsRaw = fieldsAsRaw; - - const doc = this.bson.deserialize(this.documents[0], _options); - this.documents = [doc]; - } - - this.parsed = true; - } -} - -module.exports = { Msg, BinMsg }; diff --git a/node_modules/mongodb/lib/core/connection/pool.js b/node_modules/mongodb/lib/core/connection/pool.js deleted file mode 100644 index 56d427e..0000000 --- a/node_modules/mongodb/lib/core/connection/pool.js +++ /dev/null @@ -1,1280 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const EventEmitter = require('events').EventEmitter; -const MongoError = require('../error').MongoError; -const MongoTimeoutError = require('../error').MongoTimeoutError; -const MongoWriteConcernError = require('../error').MongoWriteConcernError; -const Logger = require('./logger'); -const f = require('util').format; -const Msg = require('./msg').Msg; -const CommandResult = require('./command_result'); -const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; -const COMPRESSION_DETAILS_SIZE = require('../wireprotocol/shared').COMPRESSION_DETAILS_SIZE; -const opcodes = require('../wireprotocol/shared').opcodes; -const compress = require('../wireprotocol/compression').compress; -const compressorIDs = require('../wireprotocol/compression').compressorIDs; -const uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands; -const apm = require('./apm'); -const Buffer = require('safe-buffer').Buffer; -const connect = require('./connect'); -const updateSessionFromResponse = require('../sessions').updateSessionFromResponse; -const eachAsync = require('../utils').eachAsync; -const makeStateMachine = require('../utils').makeStateMachine; - -const DISCONNECTED = 'disconnected'; -const CONNECTING = 'connecting'; -const CONNECTED = 'connected'; -const DRAINING = 'draining'; -const DESTROYING = 'destroying'; -const DESTROYED = 'destroyed'; -const stateTransition = makeStateMachine({ - [DISCONNECTED]: [CONNECTING, DRAINING, DISCONNECTED], - [CONNECTING]: [CONNECTING, CONNECTED, DRAINING, DISCONNECTED], - [CONNECTED]: [CONNECTED, DISCONNECTED, DRAINING], - [DRAINING]: [DRAINING, DESTROYING, DESTROYED], - [DESTROYING]: [DESTROYING, DESTROYED], - [DESTROYED]: [DESTROYED] -}); - -const CONNECTION_EVENTS = new Set([ - 'error', - 'close', - 'timeout', - 'parseError', - 'connect', - 'message' -]); - -var _id = 0; - -/** - * Creates a new Pool instance - * @class - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Max server connection pool size - * @param {number} [options.minSize=0] Minimum server connection pool size - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @fires Pool#connect - * @fires Pool#close - * @fires Pool#error - * @fires Pool#timeout - * @fires Pool#parseError - * @return {Pool} A cursor instance - */ -var Pool = function(topology, options) { - // Add event listener - EventEmitter.call(this); - - // Store topology for later use - this.topology = topology; - - this.s = { - state: DISCONNECTED, - cancellationToken: new EventEmitter() - }; - - // we don't care how many connections are listening for cancellation - this.s.cancellationToken.setMaxListeners(Infinity); - - // Add the options - this.options = Object.assign( - { - // Host and port settings - host: 'localhost', - port: 27017, - // Pool default max size - size: 5, - // Pool default min size - minSize: 0, - // socket settings - connectionTimeout: 30000, - socketTimeout: 360000, - keepAlive: true, - keepAliveInitialDelay: 300000, - noDelay: true, - // SSL Settings - ssl: false, - checkServerIdentity: true, - ca: null, - crl: null, - cert: null, - key: null, - passphrase: null, - rejectUnauthorized: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - // Reconnection options - reconnect: true, - reconnectInterval: 1000, - reconnectTries: 30, - // Enable domains - domainsEnabled: false, - // feature flag for determining if we are running with the unified topology or not - legacyCompatMode: true - }, - options - ); - - // Identification information - this.id = _id++; - // Current reconnect retries - this.retriesLeft = this.options.reconnectTries; - this.reconnectId = null; - this.reconnectError = null; - // No bson parser passed in - if ( - !options.bson || - (options.bson && - (typeof options.bson.serialize !== 'function' || - typeof options.bson.deserialize !== 'function')) - ) { - throw new Error('must pass in valid bson parser'); - } - - // Logger instance - this.logger = Logger('Pool', options); - // Connections - this.availableConnections = []; - this.inUseConnections = []; - this.connectingConnections = 0; - // Currently executing - this.executing = false; - // Operation work queue - this.queue = []; - - // Number of consecutive timeouts caught - this.numberOfConsecutiveTimeouts = 0; - // Current pool Index - this.connectionIndex = 0; - - // event handlers - const pool = this; - this._messageHandler = messageHandler(this); - this._connectionCloseHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'close', err, connection); - }; - - this._connectionErrorHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'error', err, connection); - }; - - this._connectionTimeoutHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'timeout', err, connection); - }; - - this._connectionParseErrorHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'parseError', err, connection); - }; -}; - -inherits(Pool, EventEmitter); - -Object.defineProperty(Pool.prototype, 'size', { - enumerable: true, - get: function() { - return this.options.size; - } -}); - -Object.defineProperty(Pool.prototype, 'minSize', { - enumerable: true, - get: function() { - return this.options.minSize; - } -}); - -Object.defineProperty(Pool.prototype, 'connectionTimeout', { - enumerable: true, - get: function() { - return this.options.connectionTimeout; - } -}); - -Object.defineProperty(Pool.prototype, 'socketTimeout', { - enumerable: true, - get: function() { - return this.options.socketTimeout; - } -}); - -Object.defineProperty(Pool.prototype, 'state', { - enumerable: true, - get: function() { - return this.s.state; - } -}); - -// clears all pool state -function resetPoolState(pool) { - pool.inUseConnections = []; - pool.availableConnections = []; - pool.connectingConnections = 0; - pool.executing = false; - pool.numberOfConsecutiveTimeouts = 0; - pool.connectionIndex = 0; - pool.retriesLeft = pool.options.reconnectTries; - pool.reconnectId = null; -} - -function connectionFailureHandler(pool, event, err, conn) { - if (conn) { - if (conn._connectionFailHandled) { - return; - } - - conn._connectionFailHandled = true; - conn.destroy(); - - // Remove the connection - removeConnection(pool, conn); - - // flush remaining work items - conn.flush(err); - } - - // Did we catch a timeout, increment the numberOfConsecutiveTimeouts - if (event === 'timeout') { - pool.numberOfConsecutiveTimeouts = pool.numberOfConsecutiveTimeouts + 1; - - // Have we timed out more than reconnectTries in a row ? - // Force close the pool as we are trying to connect to tcp sink hole - if (pool.numberOfConsecutiveTimeouts > pool.options.reconnectTries) { - pool.numberOfConsecutiveTimeouts = 0; - // Destroy all connections and pool - pool.destroy(true); - // Emit close event - return pool.emit('close', pool); - } - } - - // No more socket available propegate the event - if (pool.socketCount() === 0) { - if (pool.state !== DESTROYED && pool.state !== DESTROYING && pool.state !== DRAINING) { - if (pool.options.reconnect) { - stateTransition(pool, DISCONNECTED); - } - } - - // Do not emit error events, they are always close events - // do not trigger the low level error handler in node - event = event === 'error' ? 'close' : event; - pool.emit(event, err); - } - - // Start reconnection attempts - if (!pool.reconnectId && pool.options.reconnect) { - pool.reconnectError = err; - pool.reconnectId = setTimeout(attemptReconnect(pool), pool.options.reconnectInterval); - } - - // Do we need to do anything to maintain the minimum pool size - const totalConnections = totalConnectionCount(pool); - if (totalConnections < pool.minSize) { - createConnection(pool); - } -} - -function attemptReconnect(pool, callback) { - return function() { - pool.emit('attemptReconnect', pool); - - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Cannot create connection when pool is destroyed')); - } - - return; - } - - pool.retriesLeft = pool.retriesLeft - 1; - if (pool.retriesLeft <= 0) { - pool.destroy(); - - const error = new MongoTimeoutError( - `failed to reconnect after ${pool.options.reconnectTries} attempts with interval ${pool.options.reconnectInterval} ms`, - pool.reconnectError - ); - - pool.emit('reconnectFailed', error); - if (typeof callback === 'function') { - callback(error); - } - - return; - } - - // clear the reconnect id on retry - pool.reconnectId = null; - - // now retry creating a connection - createConnection(pool, (err, conn) => { - if (err == null) { - pool.reconnectId = null; - pool.retriesLeft = pool.options.reconnectTries; - pool.emit('reconnect', pool); - } - - if (typeof callback === 'function') { - callback(err, conn); - } - }); - }; -} - -function moveConnectionBetween(connection, from, to) { - var index = from.indexOf(connection); - // Move the connection from connecting to available - if (index !== -1) { - from.splice(index, 1); - to.push(connection); - } -} - -function messageHandler(self) { - return function(message, connection) { - // workItem to execute - var workItem = null; - - // Locate the workItem - for (var i = 0; i < connection.workItems.length; i++) { - if (connection.workItems[i].requestId === message.responseTo) { - // Get the callback - workItem = connection.workItems[i]; - // Remove from list of workItems - connection.workItems.splice(i, 1); - } - } - - if (workItem && workItem.monitoring) { - moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); - } - - // Reset timeout counter - self.numberOfConsecutiveTimeouts = 0; - - // Reset the connection timeout if we modified it for - // this operation - if (workItem && workItem.socketTimeout) { - connection.resetSocketTimeout(); - } - - // Log if debug enabled - if (self.logger.isDebug()) { - self.logger.debug( - f( - 'message [%s] received from %s:%s', - message.raw.toString('hex'), - self.options.host, - self.options.port - ) - ); - } - - function handleOperationCallback(self, cb, err, result) { - // No domain enabled - if (!self.options.domainsEnabled) { - return process.nextTick(function() { - return cb(err, result); - }); - } - - // Domain enabled just call the callback - cb(err, result); - } - - // Keep executing, ensure current message handler does not stop execution - if (!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } - - // Time to dispatch the message if we have a callback - if (workItem && !workItem.immediateRelease) { - try { - // Parse the message according to the provided options - message.parse(workItem); - } catch (err) { - return handleOperationCallback(self, workItem.cb, new MongoError(err)); - } - - if (message.documents[0]) { - const document = message.documents[0]; - const session = workItem.session; - if (session) { - updateSessionFromResponse(session, document); - } - - if (self.topology && document.$clusterTime) { - self.topology.clusterTime = document.$clusterTime; - } - } - - // Establish if we have an error - if (workItem.command && message.documents[0]) { - const responseDoc = message.documents[0]; - - if (responseDoc.writeConcernError) { - const err = new MongoWriteConcernError(responseDoc.writeConcernError, responseDoc); - return handleOperationCallback(self, workItem.cb, err); - } - - if (responseDoc.ok === 0 || responseDoc.$err || responseDoc.errmsg || responseDoc.code) { - return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc)); - } - } - - // Add the connection details - message.hashedName = connection.hashedName; - - // Return the documents - handleOperationCallback( - self, - workItem.cb, - null, - new CommandResult(workItem.fullResult ? message : message.documents[0], connection, message) - ); - } - }; -} - -/** - * Return the total socket count in the pool. - * @method - * @return {Number} The number of socket available. - */ -Pool.prototype.socketCount = function() { - return this.availableConnections.length + this.inUseConnections.length; - // + this.connectingConnections.length; -}; - -function totalConnectionCount(pool) { - return ( - pool.availableConnections.length + pool.inUseConnections.length + pool.connectingConnections - ); -} - -/** - * Return all pool connections - * @method - * @return {Connection[]} The pool connections - */ -Pool.prototype.allConnections = function() { - return this.availableConnections.concat(this.inUseConnections); -}; - -/** - * Get a pool connection (round-robin) - * @method - * @return {Connection} - */ -Pool.prototype.get = function() { - return this.allConnections()[0]; -}; - -/** - * Is the pool connected - * @method - * @return {boolean} - */ -Pool.prototype.isConnected = function() { - // We are in a destroyed state - if (this.state === DESTROYED || this.state === DESTROYING) { - return false; - } - - // Get connections - var connections = this.availableConnections.concat(this.inUseConnections); - - // Check if we have any connected connections - for (var i = 0; i < connections.length; i++) { - if (connections[i].isConnected()) return true; - } - - // Not connected - return false; -}; - -/** - * Was the pool destroyed - * @method - * @return {boolean} - */ -Pool.prototype.isDestroyed = function() { - return this.state === DESTROYED || this.state === DESTROYING; -}; - -/** - * Is the pool in a disconnected state - * @method - * @return {boolean} - */ -Pool.prototype.isDisconnected = function() { - return this.state === DISCONNECTED; -}; - -/** - * Connect pool - */ -Pool.prototype.connect = function(callback) { - if (this.state !== DISCONNECTED) { - throw new MongoError('connection in unlawful state ' + this.state); - } - - stateTransition(this, CONNECTING); - createConnection(this, (err, conn) => { - if (err) { - if (typeof callback === 'function') { - this.destroy(); - callback(err); - return; - } - - if (this.state === CONNECTING) { - this.emit('error', err); - } - - this.destroy(); - return; - } - - stateTransition(this, CONNECTED); - - // create min connections - if (this.minSize) { - for (let i = 0; i < this.minSize; i++) { - createConnection(this); - } - } - - if (typeof callback === 'function') { - callback(null, conn); - } else { - this.emit('connect', this, conn); - } - }); -}; - -/** - * Authenticate using a specified mechanism - * @param {authResultCallback} callback A callback function - */ -Pool.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Logout all users against a database - * @param {authResultCallback} callback A callback function - */ -Pool.prototype.logout = function(dbName, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Unref the pool - * @method - */ -Pool.prototype.unref = function() { - // Get all the known connections - var connections = this.availableConnections.concat(this.inUseConnections); - - connections.forEach(function(c) { - c.unref(); - }); -}; - -// Destroy the connections -function destroy(self, connections, options, callback) { - stateTransition(self, DESTROYING); - - // indicate that in-flight connections should cancel - self.s.cancellationToken.emit('cancel'); - - eachAsync( - connections, - (conn, cb) => { - for (const eventName of CONNECTION_EVENTS) { - conn.removeAllListeners(eventName); - } - - // ignore any errors during destruction - conn.on('error', () => {}); - - conn.destroy(options, cb); - }, - err => { - if (err) { - if (typeof callback === 'function') callback(err, null); - return; - } - - resetPoolState(self); - self.queue = []; - - stateTransition(self, DESTROYED); - if (typeof callback === 'function') callback(null, null); - } - ); -} - -/** - * Destroy pool - * @method - */ -Pool.prototype.destroy = function(force, callback) { - var self = this; - if (typeof force === 'function') { - callback = force; - force = false; - } - - // Do not try again if the pool is already dead - if (this.state === DESTROYED || self.state === DESTROYING) { - if (typeof callback === 'function') callback(null, null); - return; - } - - // Set state to draining - stateTransition(this, DRAINING); - - // Are we force closing - if (force) { - // Get all the known connections - var connections = self.availableConnections.concat(self.inUseConnections); - - // Flush any remaining work items with - // an error - while (self.queue.length > 0) { - var workItem = self.queue.shift(); - if (typeof workItem.cb === 'function') { - workItem.cb(new MongoError('Pool was force destroyed')); - } - } - - // Destroy the topology - return destroy(self, connections, { force: true }, callback); - } - - // Clear out the reconnect if set - if (this.reconnectId) { - clearTimeout(this.reconnectId); - } - - // Wait for the operations to drain before we close the pool - function checkStatus() { - if (self.state === DESTROYED || self.state === DESTROYING) { - if (typeof callback === 'function') { - callback(); - } - - return; - } - - flushMonitoringOperations(self.queue); - - if (self.queue.length === 0) { - // Get all the known connections - var connections = self.availableConnections.concat(self.inUseConnections); - - // Check if we have any in flight operations - for (var i = 0; i < connections.length; i++) { - // There is an operation still in flight, reschedule a - // check waiting for it to drain - if (connections[i].workItems.length > 0) { - return setTimeout(checkStatus, 1); - } - } - - destroy(self, connections, { force: false }, callback); - } else { - // Ensure we empty the queue - _execute(self)(); - // Set timeout - setTimeout(checkStatus, 1); - } - } - - // Initiate drain of operations - checkStatus(); -}; - -/** - * Reset all connections of this pool - * - * @param {function} [callback] - */ -Pool.prototype.reset = function(callback) { - if (this.s.state !== CONNECTED) { - if (typeof callback === 'function') { - callback(new MongoError('pool is not connected, reset aborted')); - } - - return; - } - - // signal in-flight connections should be cancelled - this.s.cancellationToken.emit('cancel'); - - // destroy existing connections - const connections = this.availableConnections.concat(this.inUseConnections); - eachAsync( - connections, - (conn, cb) => { - for (const eventName of CONNECTION_EVENTS) { - conn.removeAllListeners(eventName); - } - - conn.destroy({ force: true }, cb); - }, - err => { - if (err) { - if (typeof callback === 'function') { - callback(err, null); - return; - } - } - - resetPoolState(this); - - // create a new connection, this will ultimately trigger execution - createConnection(this, () => { - if (typeof callback === 'function') { - callback(null, null); - } - }); - } - ); -}; - -// Prepare the buffer that Pool.prototype.write() uses to send to the server -function serializeCommand(self, command, callback) { - const originalCommandBuffer = command.toBin(); - - // Check whether we and the server have agreed to use a compressor - const shouldCompress = !!self.options.agreedCompressor; - if (!shouldCompress || !canCompress(command)) { - return callback(null, originalCommandBuffer); - } - - // Transform originalCommandBuffer into OP_COMPRESSED - const concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer); - const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); - - // Extract information needed for OP_COMPRESSED from the uncompressed message - const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); - - // Compress the message body - compress(self, messageToBeCompressed, function(err, compressedMessage) { - if (err) return callback(err, null); - - // Create the msgHeader of OP_COMPRESSED - const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); - msgHeader.writeInt32LE( - MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, - 0 - ); // messageLength - msgHeader.writeInt32LE(command.requestId, 4); // requestID - msgHeader.writeInt32LE(0, 8); // responseTo (zero) - msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode - - // Create the compression details of OP_COMPRESSED - const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); - compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode - compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader - compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID - - return callback(null, [msgHeader, compressionDetails, compressedMessage]); - }); -} - -/** - * Write a message to MongoDB - * @method - * @return {Connection} - */ -Pool.prototype.write = function(command, options, cb) { - var self = this; - // Ensure we have a callback - if (typeof options === 'function') { - cb = options; - } - - // Always have options - options = options || {}; - - // We need to have a callback function unless the message returns no response - if (!(typeof cb === 'function') && !options.noResponse) { - throw new MongoError('write method must provide a callback'); - } - - // Pool was destroyed error out - if (this.state === DESTROYED || this.state === DESTROYING) { - cb(new MongoError('pool destroyed')); - return; - } - - if (this.state === DRAINING) { - cb(new MongoError('pool is draining, new operations prohibited')); - return; - } - - if (this.options.domainsEnabled && process.domain && typeof cb === 'function') { - // if we have a domain bind to it - var oldCb = cb; - cb = process.domain.bind(function() { - // v8 - argumentsToArray one-liner - var args = new Array(arguments.length); - for (var i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } - // bounce off event loop so domain switch takes place - process.nextTick(function() { - oldCb.apply(null, args); - }); - }); - } - - // Do we have an operation - var operation = { - cb: cb, - raw: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - fullResult: false - }; - - // Set the options for the parsing - operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true; - operation.promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : true; - operation.promoteBuffers = - typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false; - operation.raw = typeof options.raw === 'boolean' ? options.raw : false; - operation.immediateRelease = - typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false; - operation.documentsReturnedIn = options.documentsReturnedIn; - operation.command = typeof options.command === 'boolean' ? options.command : false; - operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false; - operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false; - operation.session = options.session || null; - - // Optional per operation socketTimeout - operation.socketTimeout = options.socketTimeout; - operation.monitoring = options.monitoring; - - // Get the requestId - operation.requestId = command.requestId; - - // If command monitoring is enabled we need to modify the callback here - if (self.options.monitorCommands) { - this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); - - operation.started = process.hrtime(); - operation.cb = (err, reply) => { - if (err) { - self.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, err, operation.started) - ); - } else { - if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { - self.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, reply.result, operation.started) - ); - } else { - self.emit( - 'commandSucceeded', - new apm.CommandSucceededEvent(this, command, reply, operation.started) - ); - } - } - - if (typeof cb === 'function') cb(err, reply); - }; - } - - // Prepare the operation buffer - serializeCommand(self, command, (err, serializedBuffers) => { - if (err) throw err; - - // Set the operation's buffer to the serialization of the commands - operation.buffer = serializedBuffers; - - // If we have a monitoring operation schedule as the very first operation - // Otherwise add to back of queue - if (options.monitoring) { - self.queue.unshift(operation); - } else { - self.queue.push(operation); - } - - // Attempt to execute the operation - if (!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } - }); -}; - -// Return whether a command contains an uncompressible command term -// Will return true if command contains no uncompressible command terms -function canCompress(command) { - const commandDoc = command instanceof Msg ? command.command : command.query; - const commandName = Object.keys(commandDoc)[0]; - return !uncompressibleCommands.has(commandName); -} - -// Remove connection method -function remove(connection, connections) { - for (var i = 0; i < connections.length; i++) { - if (connections[i] === connection) { - connections.splice(i, 1); - return true; - } - } -} - -function removeConnection(self, connection) { - if (remove(connection, self.availableConnections)) return; - if (remove(connection, self.inUseConnections)) return; -} - -function createConnection(pool, callback) { - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Cannot create connection when pool is destroyed')); - } - - return; - } - - pool.connectingConnections++; - connect(pool.options, pool.s.cancellationToken, (err, connection) => { - pool.connectingConnections--; - - if (err) { - if (pool.logger.isDebug()) { - pool.logger.debug(`connection attempt failed with error [${JSON.stringify(err)}]`); - } - - // check if reconnect is enabled, and attempt retry if so - if (!pool.reconnectId && pool.options.reconnect) { - if (pool.state === CONNECTING && pool.options.legacyCompatMode) { - callback(err); - return; - } - - pool.reconnectError = err; - pool.reconnectId = setTimeout( - attemptReconnect(pool, callback), - pool.options.reconnectInterval - ); - - return; - } - - if (typeof callback === 'function') { - callback(err); - } - - return; - } - - // the pool might have been closed since we started creating the connection - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Pool was destroyed after connection creation')); - } - - connection.destroy(); - return; - } - - // otherwise, connect relevant event handlers and add it to our available connections - connection.on('error', pool._connectionErrorHandler); - connection.on('close', pool._connectionCloseHandler); - connection.on('timeout', pool._connectionTimeoutHandler); - connection.on('parseError', pool._connectionParseErrorHandler); - connection.on('message', pool._messageHandler); - - pool.availableConnections.push(connection); - - // if a callback was provided, return the connection - if (typeof callback === 'function') { - callback(null, connection); - } - - // immediately execute any waiting work - _execute(pool)(); - }); -} - -function flushMonitoringOperations(queue) { - for (var i = 0; i < queue.length; i++) { - if (queue[i].monitoring) { - var workItem = queue[i]; - queue.splice(i, 1); - workItem.cb( - new MongoError({ message: 'no connection available for monitoring', driver: true }) - ); - } - } -} - -function _execute(self) { - return function() { - if (self.state === DESTROYED) return; - // Already executing, skip - if (self.executing) return; - // Set pool as executing - self.executing = true; - - // New pool connections are in progress, wait them to finish - // before executing any more operation to ensure distribution of - // operations - if (self.connectingConnections > 0) { - self.executing = false; - return; - } - - // As long as we have available connections - // eslint-disable-next-line - while (true) { - // Total availble connections - const totalConnections = totalConnectionCount(self); - - // No available connections available, flush any monitoring ops - if (self.availableConnections.length === 0) { - // Flush any monitoring operations - flushMonitoringOperations(self.queue); - - // Try to create a new connection to execute stuck operation - if (totalConnections < self.options.size && self.queue.length > 0) { - createConnection(self); - } - - break; - } - - // No queue break - if (self.queue.length === 0) { - break; - } - - var connection = null; - const connections = self.availableConnections.filter(conn => conn.workItems.length === 0); - - // No connection found that has no work on it, just pick one for pipelining - if (connections.length === 0) { - connection = - self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; - } else { - connection = connections[self.connectionIndex++ % connections.length]; - } - - // Is the connection connected - if (!connection.isConnected()) { - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - break; - } - - // Get the next work item - var workItem = self.queue.shift(); - - // If we are monitoring we need to use a connection that is not - // running another operation to avoid socket timeout changes - // affecting an existing operation - if (workItem.monitoring) { - var foundValidConnection = false; - - for (let i = 0; i < self.availableConnections.length; i++) { - // If the connection is connected - // And there are no pending workItems on it - // Then we can safely use it for monitoring. - if ( - self.availableConnections[i].isConnected() && - self.availableConnections[i].workItems.length === 0 - ) { - foundValidConnection = true; - connection = self.availableConnections[i]; - break; - } - } - - // No safe connection found, attempt to grow the connections - // if possible and break from the loop - if (!foundValidConnection) { - // Put workItem back on the queue - self.queue.unshift(workItem); - - // Attempt to grow the pool if it's not yet maxsize - if (totalConnections < self.options.size && self.queue.length > 0) { - // Create a new connection - createConnection(self); - } - - // Re-execute the operation - setTimeout(() => _execute(self)(), 10); - break; - } - } - - // Don't execute operation until we have a full pool - if (totalConnections < self.options.size) { - // Connection has work items, then put it back on the queue - // and create a new connection - if (connection.workItems.length > 0) { - // Lets put the workItem back on the list - self.queue.unshift(workItem); - // Create a new connection - createConnection(self); - // Break from the loop - break; - } - } - - // Get actual binary commands - var buffer = workItem.buffer; - - // If we are monitoring take the connection of the availableConnections - if (workItem.monitoring) { - moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); - } - - // Track the executing commands on the mongo server - // as long as there is an expected response - if (!workItem.noResponse) { - connection.workItems.push(workItem); - } - - // We have a custom socketTimeout - if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') { - connection.setSocketTimeout(workItem.socketTimeout); - } - - // Capture if write was successful - var writeSuccessful = true; - - // Put operation on the wire - if (Array.isArray(buffer)) { - for (let i = 0; i < buffer.length; i++) { - writeSuccessful = connection.write(buffer[i]); - } - } else { - writeSuccessful = connection.write(buffer); - } - - // if the command is designated noResponse, call the callback immeditely - if (workItem.noResponse && typeof workItem.cb === 'function') { - workItem.cb(null, null); - } - - if (writeSuccessful === false) { - // If write not successful put back on queue - self.queue.unshift(workItem); - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - break; - } - } - - self.executing = false; - }; -} - -// Make execution loop available for testing -Pool._execute = _execute; - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Pool#connect - * @type {Pool} - */ - -/** - * A server reconnect event, used to verify that pool reconnected. - * - * @event Pool#reconnect - * @type {Pool} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Pool#close - * @type {Pool} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Pool#error - * @type {Pool} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Pool#timeout - * @type {Pool} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Pool#parseError - * @type {Pool} - */ - -/** - * The driver attempted to reconnect - * - * @event Pool#attemptReconnect - * @type {Pool} - */ - -/** - * The driver exhausted all reconnect attempts - * - * @event Pool#reconnectFailed - * @type {Pool} - */ - -module.exports = Pool; diff --git a/node_modules/mongodb/lib/core/connection/utils.js b/node_modules/mongodb/lib/core/connection/utils.js deleted file mode 100644 index 2f3d889..0000000 --- a/node_modules/mongodb/lib/core/connection/utils.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -const require_optional = require('require_optional'); - -function debugOptions(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -} - -function retrieveBSON() { - var BSON = require('bson'); - BSON.native = false; - - try { - var optionalBSON = require_optional('bson-ext'); - if (optionalBSON) { - optionalBSON.native = true; - return optionalBSON; - } - } catch (err) {} // eslint-disable-line - - return BSON; -} - -// Throw an error if an attempt to use Snappy is made when Snappy is not installed -function noSnappyWarning() { - throw new Error( - 'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.' - ); -} - -// Facilitate loading Snappy optionally -function retrieveSnappy() { - var snappy = null; - try { - snappy = require_optional('snappy'); - } catch (error) {} // eslint-disable-line - if (!snappy) { - snappy = { - compress: noSnappyWarning, - uncompress: noSnappyWarning, - compressSync: noSnappyWarning, - uncompressSync: noSnappyWarning - }; - } - return snappy; -} - -module.exports = { - debugOptions, - retrieveBSON, - retrieveSnappy -}; diff --git a/node_modules/mongodb/lib/core/cursor.js b/node_modules/mongodb/lib/core/cursor.js deleted file mode 100644 index 11c25fc..0000000 --- a/node_modules/mongodb/lib/core/cursor.js +++ /dev/null @@ -1,873 +0,0 @@ -'use strict'; - -const Logger = require('./connection/logger'); -const retrieveBSON = require('./connection/utils').retrieveBSON; -const MongoError = require('./error').MongoError; -const MongoNetworkError = require('./error').MongoNetworkError; -const collationNotSupported = require('./utils').collationNotSupported; -const ReadPreference = require('./topologies/read_preference'); -const isUnifiedTopology = require('./utils').isUnifiedTopology; -const executeOperation = require('../operations/execute_operation'); -const Readable = require('stream').Readable; -const SUPPORTS = require('../utils').SUPPORTS; -const MongoDBNamespace = require('../utils').MongoDBNamespace; -const OperationBase = require('../operations/operation').OperationBase; - -const BSON = retrieveBSON(); -const Long = BSON.Long; - -// Possible states for a cursor -const CursorState = { - INIT: 0, - OPEN: 1, - CLOSED: 2, - GET_MORE: 3 -}; - -// -// Handle callback (including any exceptions thrown) -function handleCallback(callback, err, result) { - try { - callback(err, result); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } -} - -/** - * This is a cursor results callback - * - * @callback resultCallback - * @param {error} error An error object. Set to null if no error present - * @param {object} document - */ - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. - * - * **CURSORS Cannot directly be instantiated** - */ - -/** - * The core cursor class. All cursors in the driver build off of this one. - * - * @property {number} cursorBatchSize The current cursorBatchSize for the cursor - * @property {number} cursorLimit The current cursorLimit for the cursor - * @property {number} cursorSkip The current cursorSkip for the cursor - */ -class CoreCursor extends Readable { - /** - * Create a new core `Cursor` instance. - * **NOTE** Not to be instantiated directly - * - * @param {object} topology The server topology instance. - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|Long} cmd The selector (can be a command or a cursorId) - * @param {object} [options=null] Optional settings. - * @param {object} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/| find command documentation} and {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {object} [options.transforms=null] Transform methods for the cursor results - * @param {function} [options.transforms.query] Transform the value returned from the initial query - * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype._next - */ - constructor(topology, ns, cmd, options) { - super({ objectMode: true }); - options = options || {}; - - if (ns instanceof OperationBase) { - this.operation = ns; - ns = this.operation.ns.toString(); - options = this.operation.options; - cmd = this.operation.cmd ? this.operation.cmd : {}; - } - - // Cursor pool - this.pool = null; - // Cursor server - this.server = null; - - // Do we have a not connected handler - this.disconnectHandler = options.disconnectHandler; - - // Set local values - this.bson = topology.s.bson; - this.ns = ns; - this.namespace = MongoDBNamespace.fromString(ns); - this.cmd = cmd; - this.options = options; - this.topology = topology; - - // All internal state - this.cursorState = { - cursorId: null, - cmd, - documents: options.documents || [], - cursorIndex: 0, - dead: false, - killed: false, - init: false, - notified: false, - limit: options.limit || cmd.limit || 0, - skip: options.skip || cmd.skip || 0, - batchSize: options.batchSize || cmd.batchSize || 1000, - currentLimit: 0, - // Result field name if not a cursor (contains the array of results) - transforms: options.transforms, - raw: options.raw || (cmd && cmd.raw) - }; - - if (typeof options.session === 'object') { - this.cursorState.session = options.session; - } - - // Add promoteLong to cursor state - const topologyOptions = topology.s.options; - if (typeof topologyOptions.promoteLongs === 'boolean') { - this.cursorState.promoteLongs = topologyOptions.promoteLongs; - } else if (typeof options.promoteLongs === 'boolean') { - this.cursorState.promoteLongs = options.promoteLongs; - } - - // Add promoteValues to cursor state - if (typeof topologyOptions.promoteValues === 'boolean') { - this.cursorState.promoteValues = topologyOptions.promoteValues; - } else if (typeof options.promoteValues === 'boolean') { - this.cursorState.promoteValues = options.promoteValues; - } - - // Add promoteBuffers to cursor state - if (typeof topologyOptions.promoteBuffers === 'boolean') { - this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; - } else if (typeof options.promoteBuffers === 'boolean') { - this.cursorState.promoteBuffers = options.promoteBuffers; - } - - if (topologyOptions.reconnect) { - this.cursorState.reconnect = topologyOptions.reconnect; - } - - // Logger - this.logger = Logger('Cursor', topologyOptions); - - // - // Did we pass in a cursor id - if (typeof cmd === 'number') { - this.cursorState.cursorId = Long.fromNumber(cmd); - this.cursorState.lastCursorId = this.cursorState.cursorId; - } else if (cmd instanceof Long) { - this.cursorState.cursorId = cmd; - this.cursorState.lastCursorId = cmd; - } - - // TODO: remove as part of NODE-2104 - if (this.operation) { - this.operation.cursorState = this.cursorState; - } - } - - setCursorBatchSize(value) { - this.cursorState.batchSize = value; - } - - cursorBatchSize() { - return this.cursorState.batchSize; - } - - setCursorLimit(value) { - this.cursorState.limit = value; - } - - cursorLimit() { - return this.cursorState.limit; - } - - setCursorSkip(value) { - this.cursorState.skip = value; - } - - cursorSkip() { - return this.cursorState.skip; - } - - /** - * Retrieve the next document from the cursor - * @method - * @param {resultCallback} callback A callback function - */ - _next(callback) { - nextFunction(this, callback); - } - - /** - * Clone the cursor - * @method - * @return {Cursor} - */ - clone() { - return this.topology.cursor(this.ns, this.cmd, this.options); - } - - /** - * Checks if the cursor is dead - * @method - * @return {boolean} A boolean signifying if the cursor is dead or not - */ - isDead() { - return this.cursorState.dead === true; - } - - /** - * Checks if the cursor was killed by the application - * @method - * @return {boolean} A boolean signifying if the cursor was killed by the application - */ - isKilled() { - return this.cursorState.killed === true; - } - - /** - * Checks if the cursor notified it's caller about it's death - * @method - * @return {boolean} A boolean signifying if the cursor notified the callback - */ - isNotified() { - return this.cursorState.notified === true; - } - - /** - * Returns current buffered documents length - * @method - * @return {number} The number of items in the buffered documents - */ - bufferedCount() { - return this.cursorState.documents.length - this.cursorState.cursorIndex; - } - - /** - * Returns current buffered documents - * @method - * @return {Array} An array of buffered documents - */ - readBufferedDocuments(number) { - const unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; - const length = number < unreadDocumentsLength ? number : unreadDocumentsLength; - let elements = this.cursorState.documents.slice( - this.cursorState.cursorIndex, - this.cursorState.cursorIndex + length - ); - - // Transform the doc with passed in transformation method if provided - if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') { - // Transform all the elements - for (let i = 0; i < elements.length; i++) { - elements[i] = this.cursorState.transforms.doc(elements[i]); - } - } - - // Ensure we do not return any more documents than the limit imposed - // Just return the number of elements up to the limit - if ( - this.cursorState.limit > 0 && - this.cursorState.currentLimit + elements.length > this.cursorState.limit - ) { - elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit); - this.kill(); - } - - // Adjust current limit - this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; - this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; - - // Return elements - return elements; - } - - /** - * Resets local state for this cursor instance, and issues a `killCursors` command to the server - * - * @param {resultCallback} callback A callback function - */ - kill(callback) { - // Set cursor to dead - this.cursorState.dead = true; - this.cursorState.killed = true; - // Remove documents - this.cursorState.documents = []; - - // If no cursor id just return - if ( - this.cursorState.cursorId == null || - this.cursorState.cursorId.isZero() || - this.cursorState.init === false - ) { - if (callback) callback(null, null); - return; - } - - this.server.killCursors(this.ns, this.cursorState, callback); - } - - /** - * Resets the cursor - */ - rewind() { - if (this.cursorState.init) { - if (!this.cursorState.dead) { - this.kill(); - } - - this.cursorState.currentLimit = 0; - this.cursorState.init = false; - this.cursorState.dead = false; - this.cursorState.killed = false; - this.cursorState.notified = false; - this.cursorState.documents = []; - this.cursorState.cursorId = null; - this.cursorState.cursorIndex = 0; - } - } - - // Internal methods - _read() { - if ((this.s && this.s.state === CursorState.CLOSED) || this.isDead()) { - return this.push(null); - } - - // Get the next item - this._next((err, result) => { - if (err) { - if (this.listeners('error') && this.listeners('error').length > 0) { - this.emit('error', err); - } - if (!this.isDead()) this.close(); - - // Emit end event - this.emit('end'); - return this.emit('finish'); - } - - // If we provided a transformation method - if ( - this.cursorState.streamOptions && - typeof this.cursorState.streamOptions.transform === 'function' && - result != null - ) { - return this.push(this.cursorState.streamOptions.transform(result)); - } - - // Return the result - this.push(result); - - if (result === null && this.isDead()) { - this.once('end', () => { - this.close(); - this.emit('finish'); - }); - } - }); - } - - _endSession(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - - const session = this.cursorState.session; - - if (session && (options.force || session.owner === this)) { - this.cursorState.session = undefined; - - if (this.operation) { - this.operation.clearSession(); - } - - session.endSession(callback); - return true; - } - - if (callback) { - callback(); - } - - return false; - } - - _getMore(callback) { - if (this.logger.isDebug()) { - this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`); - } - - // Set the current batchSize - let batchSize = this.cursorState.batchSize; - if ( - this.cursorState.limit > 0 && - this.cursorState.currentLimit + batchSize > this.cursorState.limit - ) { - batchSize = this.cursorState.limit - this.cursorState.currentLimit; - } - - const cursorState = this.cursorState; - this.server.getMore(this.ns, cursorState, batchSize, this.options, (err, result, conn) => { - // NOTE: `getMore` modifies `cursorState`, would be very ideal not to do so in the future - if (err || (cursorState.cursorId && cursorState.cursorId.isZero())) { - this._endSession(); - } - - callback(err, result, conn); - }); - } - - _initializeCursor(callback) { - const cursor = this; - - // NOTE: this goes away once cursors use `executeOperation` - if (isUnifiedTopology(cursor.topology) && cursor.topology.shouldCheckForSessionSupport()) { - cursor.topology.selectServer(ReadPreference.primaryPreferred, err => { - if (err) { - callback(err); - return; - } - - this._initializeCursor(callback); - }); - - return; - } - - function done(err, result) { - const cursorState = cursor.cursorState; - if (err || (cursorState.cursorId && cursorState.cursorId.isZero())) { - cursor._endSession(); - } - - if ( - cursorState.documents.length === 0 && - cursorState.cursorId && - cursorState.cursorId.isZero() && - !cursor.cmd.tailable && - !cursor.cmd.awaitData - ) { - return setCursorNotified(cursor, callback); - } - - callback(err, result); - } - - const queryCallback = (err, r) => { - if (err) { - return done(err); - } - - const result = r.message; - if (result.queryFailure) { - return done(new MongoError(result.documents[0]), null); - } - - // Check if we have a command cursor - if ( - Array.isArray(result.documents) && - result.documents.length === 1 && - (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) && - (typeof result.documents[0].cursor !== 'string' || - result.documents[0]['$err'] || - result.documents[0]['errmsg'] || - Array.isArray(result.documents[0].result)) - ) { - // We have an error document, return the error - if (result.documents[0]['$err'] || result.documents[0]['errmsg']) { - return done(new MongoError(result.documents[0]), null); - } - - // We have a cursor document - if (result.documents[0].cursor != null && typeof result.documents[0].cursor !== 'string') { - const id = result.documents[0].cursor.id; - // If we have a namespace change set the new namespace for getmores - if (result.documents[0].cursor.ns) { - cursor.ns = result.documents[0].cursor.ns; - } - // Promote id to long if needed - cursor.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; - cursor.cursorState.lastCursorId = cursor.cursorState.cursorId; - cursor.cursorState.operationTime = result.documents[0].operationTime; - - // If we have a firstBatch set it - if (Array.isArray(result.documents[0].cursor.firstBatch)) { - cursor.cursorState.documents = result.documents[0].cursor.firstBatch; //.reverse(); - } - - // Return after processing command cursor - return done(null, result); - } - - if (Array.isArray(result.documents[0].result)) { - cursor.cursorState.documents = result.documents[0].result; - cursor.cursorState.cursorId = Long.ZERO; - return done(null, result); - } - } - - // Otherwise fall back to regular find path - const cursorId = result.cursorId || 0; - cursor.cursorState.cursorId = cursorId instanceof Long ? cursorId : Long.fromNumber(cursorId); - cursor.cursorState.documents = result.documents; - cursor.cursorState.lastCursorId = result.cursorId; - - // Transform the results with passed in transformation method if provided - if ( - cursor.cursorState.transforms && - typeof cursor.cursorState.transforms.query === 'function' - ) { - cursor.cursorState.documents = cursor.cursorState.transforms.query(result); - } - - done(null, result); - }; - - if (cursor.operation) { - if (cursor.logger.isDebug()) { - cursor.logger.debug( - `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( - cursor.query - )}]` - ); - } - - executeOperation(cursor.topology, cursor.operation, (err, result) => { - if (err) { - done(err); - return; - } - - cursor.server = cursor.operation.server; - cursor.cursorState.init = true; - - // NOTE: this is a special internal method for cloning a cursor, consider removing - if (cursor.cursorState.cursorId != null) { - return done(); - } - - queryCallback(err, result); - }); - - return; - } - - // Very explicitly choose what is passed to selectServer - const serverSelectOptions = {}; - if (cursor.cursorState.session) { - serverSelectOptions.session = cursor.cursorState.session; - } - - if (cursor.operation) { - serverSelectOptions.readPreference = cursor.operation.readPreference; - } else if (cursor.options.readPreference) { - serverSelectOptions.readPreference = cursor.options.readPreference; - } - - return cursor.topology.selectServer(serverSelectOptions, (err, server) => { - if (err) { - const disconnectHandler = cursor.disconnectHandler; - if (disconnectHandler != null) { - return disconnectHandler.addObjectAndMethod( - 'cursor', - cursor, - 'next', - [callback], - callback - ); - } - - return callback(err); - } - - cursor.server = server; - cursor.cursorState.init = true; - if (collationNotSupported(cursor.server, cursor.cmd)) { - return callback(new MongoError(`server ${cursor.server.name} does not support collation`)); - } - - // NOTE: this is a special internal method for cloning a cursor, consider removing - if (cursor.cursorState.cursorId != null) { - return done(); - } - - if (cursor.logger.isDebug()) { - cursor.logger.debug( - `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( - cursor.query - )}]` - ); - } - - if (cursor.cmd.find != null) { - server.query(cursor.ns, cursor.cmd, cursor.cursorState, cursor.options, queryCallback); - return; - } - - const commandOptions = Object.assign({ session: cursor.cursorState.session }, cursor.options); - server.command(cursor.ns, cursor.cmd, commandOptions, queryCallback); - }); - } -} - -if (SUPPORTS.ASYNC_ITERATOR) { - CoreCursor.prototype[Symbol.asyncIterator] = require('../async/async_iterator').asyncIterator; -} - -/** - * Validate if the pool is dead and return error - */ -function isConnectionDead(self, callback) { - if (self.pool && self.pool.isDestroyed()) { - self.cursorState.killed = true; - const err = new MongoNetworkError( - `connection to host ${self.pool.host}:${self.pool.port} was destroyed` - ); - - _setCursorNotifiedImpl(self, () => callback(err)); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead but was not explicitly killed by user - */ -function isCursorDeadButNotkilled(self, callback) { - // Cursor is dead but not marked killed, return null - if (self.cursorState.dead && !self.cursorState.killed) { - self.cursorState.killed = true; - setCursorNotified(self, callback); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead and was killed by user - */ -function isCursorDeadAndKilled(self, callback) { - if (self.cursorState.dead && self.cursorState.killed) { - handleCallback(callback, new MongoError('cursor is dead')); - return true; - } - - return false; -} - -/** - * Validate if the cursor was killed by the user - */ -function isCursorKilled(self, callback) { - if (self.cursorState.killed) { - setCursorNotified(self, callback); - return true; - } - - return false; -} - -/** - * Mark cursor as being dead and notified - */ -function setCursorDeadAndNotified(self, callback) { - self.cursorState.dead = true; - setCursorNotified(self, callback); -} - -/** - * Mark cursor as being notified - */ -function setCursorNotified(self, callback) { - _setCursorNotifiedImpl(self, () => handleCallback(callback, null, null)); -} - -function _setCursorNotifiedImpl(self, callback) { - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - - if (self.cursorState.session) { - self._endSession(callback); - return; - } - - return callback(); -} - -function nextFunction(self, callback) { - // We have notified about it - if (self.cursorState.notified) { - return callback(new Error('cursor is exhausted')); - } - - // Cursor is killed return null - if (isCursorKilled(self, callback)) return; - - // Cursor is dead but not marked killed, return null - if (isCursorDeadButNotkilled(self, callback)) return; - - // We have a dead and killed cursor, attempting to call next should error - if (isCursorDeadAndKilled(self, callback)) return; - - // We have just started the cursor - if (!self.cursorState.init) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if (!self.topology.isConnected(self.options)) { - // Only need this for single server, because repl sets and mongos - // will always continue trying to reconnect - if (self.topology._type === 'server' && !self.topology.s.options.reconnect) { - // Reconnect is disabled, so we'll never reconnect - return callback(new MongoError('no connection available')); - } - - if (self.disconnectHandler != null) { - if (self.topology.isDestroyed()) { - // Topology was destroyed, so don't try to wait for it to reconnect - return callback(new MongoError('Topology was destroyed')); - } - - self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); - return; - } - } - - self._initializeCursor((err, result) => { - if (err || result === null) { - callback(err, result); - return; - } - - nextFunction(self, callback); - }); - - return; - } - - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } else if ( - self.cursorState.cursorIndex === self.cursorState.documents.length && - !Long.ZERO.equals(self.cursorState.cursorId) - ) { - // Ensure an empty cursor state - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - - // Check if topology is destroyed - if (self.topology.isDestroyed()) - return callback( - new MongoNetworkError('connection destroyed, not possible to instantiate cursor') - ); - - // Check if connection is dead and return if not possible to - // execute a getMore on this connection - if (isConnectionDead(self, callback)) return; - - // Execute the next get more - self._getMore(function(err, doc, connection) { - if (err) { - return handleCallback(callback, err); - } - - // Save the returned connection to ensure all getMore's fire over the same connection - self.connection = connection; - - // Tailable cursor getMore result, notify owner about it - // No attempt is made here to retry, this is left to the user of the - // core module to handle to keep core simple - if ( - self.cursorState.documents.length === 0 && - self.cmd.tailable && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - // No more documents in the tailed cursor - return handleCallback( - callback, - new MongoError({ - message: 'No more documents in tailed cursor', - tailable: self.cmd.tailable, - awaitData: self.cmd.awaitData - }) - ); - } else if ( - self.cursorState.documents.length === 0 && - self.cmd.tailable && - !Long.ZERO.equals(self.cursorState.cursorId) - ) { - return nextFunction(self, callback); - } - - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - return setCursorDeadAndNotified(self, callback); - } - - nextFunction(self, callback); - }); - } else if ( - self.cursorState.documents.length === self.cursorState.cursorIndex && - self.cmd.tailable && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - return handleCallback( - callback, - new MongoError({ - message: 'No more documents in tailed cursor', - tailable: self.cmd.tailable, - awaitData: self.cmd.awaitData - }) - ); - } else if ( - self.cursorState.documents.length === self.cursorState.cursorIndex && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - setCursorDeadAndNotified(self, callback); - } else { - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } - - // Increment the current cursor limit - self.cursorState.currentLimit += 1; - - // Get the document - let doc = self.cursorState.documents[self.cursorState.cursorIndex++]; - - // Doc overflow - if (!doc || doc.$err) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, function() { - handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); - }); - } - - // Transform the doc with passed in transformation method if provided - if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') { - doc = self.cursorState.transforms.doc(doc); - } - - // Return the document - handleCallback(callback, null, doc); - } -} - -module.exports = { - CursorState, - CoreCursor -}; diff --git a/node_modules/mongodb/lib/core/error.js b/node_modules/mongodb/lib/core/error.js deleted file mode 100644 index c50751d..0000000 --- a/node_modules/mongodb/lib/core/error.js +++ /dev/null @@ -1,277 +0,0 @@ -'use strict'; - -/** - * Creates a new MongoError - * - * @augments Error - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @property {string} stack The error call stack - */ -class MongoError extends Error { - constructor(message) { - if (message instanceof Error) { - super(message.message); - this.stack = message.stack; - } else { - if (typeof message === 'string') { - super(message); - } else { - super(message.message || message.errmsg || message.$err || 'n/a'); - for (var name in message) { - if (name === 'errmsg') { - continue; - } - - this[name] = message[name]; - } - } - - Error.captureStackTrace(this, this.constructor); - } - - this.name = 'MongoError'; - } - - /** - * Legacy name for server error responses - */ - get errmsg() { - return this.message; - } - - /** - * Creates a new MongoError object - * - * @param {Error|string|object} options The options used to create the error. - * @return {MongoError} A MongoError instance - * @deprecated Use `new MongoError()` instead. - */ - static create(options) { - return new MongoError(options); - } - - /** - * Checks the error to see if it has an error label - * @param {string} label The error label to check for - * @returns {boolean} returns true if the error has the provided error label - */ - hasErrorLabel(label) { - return this.errorLabels && this.errorLabels.indexOf(label) !== -1; - } -} - -/** - * An error indicating an issue with the network, including TCP - * errors and timeouts. - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @property {string} stack The error call stack - * @extends MongoError - */ -class MongoNetworkError extends MongoError { - constructor(message) { - super(message); - this.name = 'MongoNetworkError'; - } -} - -/** - * An error used when attempting to parse a value (like a connection string) - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @extends MongoError - */ -class MongoParseError extends MongoError { - constructor(message) { - super(message); - this.name = 'MongoParseError'; - } -} - -/** - * An error signifying a client-side timeout event - * - * @param {Error|string|object} message The error message - * @param {string|object} [reason] The reason the timeout occured - * @property {string} message The error message - * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers - * @extends MongoError - */ -class MongoTimeoutError extends MongoError { - constructor(message, reason) { - if (reason && reason.error) { - super(reason.error.message || reason.error); - } else { - super(message); - } - - this.name = 'MongoTimeoutError'; - if (reason) { - this.reason = reason; - } - } -} - -/** - * An error signifying a client-side server selection error - * - * @param {Error|string|object} message The error message - * @param {string|object} [reason] The reason the timeout occured - * @property {string} message The error message - * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers - * @extends MongoError - */ -class MongoServerSelectionError extends MongoTimeoutError { - constructor(message, reason) { - super(message, reason); - this.name = 'MongoServerSelectionError'; - } -} - -function makeWriteConcernResultObject(input) { - const output = Object.assign({}, input); - - if (output.ok === 0) { - output.ok = 1; - delete output.errmsg; - delete output.code; - delete output.codeName; - } - - return output; -} - -/** - * An error thrown when the server reports a writeConcernError - * - * @param {Error|string|object} message The error message - * @param {object} result The result document (provided if ok: 1) - * @property {string} message The error message - * @property {object} [result] The result document (provided if ok: 1) - * @extends MongoError - */ -class MongoWriteConcernError extends MongoError { - constructor(message, result) { - super(message); - this.name = 'MongoWriteConcernError'; - - if (result != null) { - this.result = makeWriteConcernResultObject(result); - } - } -} - -// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms -const RETRYABLE_ERROR_CODES = new Set([ - 6, // HostUnreachable - 7, // HostNotFound - 89, // NetworkTimeout - 91, // ShutdownInProgress - 189, // PrimarySteppedDown - 9001, // SocketException - 10107, // NotMaster - 11600, // InterruptedAtShutdown - 11602, // InterruptedDueToReplStateChange - 13435, // NotMasterNoSlaveOk - 13436 // NotMasterOrSecondary -]); - -/** - * Determines whether an error is something the driver should attempt to retry - * - * @ignore - * @param {MongoError|Error} error - */ -function isRetryableError(error) { - return ( - RETRYABLE_ERROR_CODES.has(error.code) || - error instanceof MongoNetworkError || - error.message.match(/not master/) || - error.message.match(/node is recovering/) - ); -} - -const SDAM_RECOVERING_CODES = new Set([ - 91, // ShutdownInProgress - 189, // PrimarySteppedDown - 11600, // InterruptedAtShutdown - 11602, // InterruptedDueToReplStateChange - 13436 // NotMasterOrSecondary -]); - -const SDAM_NOTMASTER_CODES = new Set([ - 10107, // NotMaster - 13435 // NotMasterNoSlaveOk -]); - -const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ - 11600, // InterruptedAtShutdown - 91 // ShutdownInProgress -]); - -function isRecoveringError(err) { - if (err.code && SDAM_RECOVERING_CODES.has(err.code)) { - return true; - } - - return err.message.match(/not master or secondary/) || err.message.match(/node is recovering/); -} - -function isNotMasterError(err) { - if (err.code && SDAM_NOTMASTER_CODES.has(err.code)) { - return true; - } - - if (isRecoveringError(err)) { - return false; - } - - return err.message.match(/not master/); -} - -function isNodeShuttingDownError(err) { - return err.code && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code); -} - -/** - * Determines whether SDAM can recover from a given error. If it cannot - * then the pool will be cleared, and server state will completely reset - * locally. - * - * @ignore - * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering - * @param {MongoError|Error} error - */ -function isSDAMUnrecoverableError(error) { - // NOTE: null check is here for a strictly pre-CMAP world, a timeout or - // close event are considered unrecoverable - if (error instanceof MongoParseError || error == null) { - return true; - } - - if (isRecoveringError(error) || isNotMasterError(error)) { - return true; - } - - return false; -} - -function isNetworkTimeoutError(err) { - return err instanceof MongoNetworkError && err.message.match(/timed out/); -} - -module.exports = { - MongoError, - MongoNetworkError, - MongoParseError, - MongoTimeoutError, - MongoServerSelectionError, - MongoWriteConcernError, - isRetryableError, - isSDAMUnrecoverableError, - isNodeShuttingDownError, - isNetworkTimeoutError -}; diff --git a/node_modules/mongodb/lib/core/index.js b/node_modules/mongodb/lib/core/index.js deleted file mode 100644 index 28aca32..0000000 --- a/node_modules/mongodb/lib/core/index.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -let BSON = require('bson'); -const require_optional = require('require_optional'); -const EJSON = require('./utils').retrieveEJSON(); - -try { - // Attempt to grab the native BSON parser - const BSONNative = require_optional('bson-ext'); - // If we got the native parser, use it instead of the - // Javascript one - if (BSONNative) { - BSON = BSONNative; - } -} catch (err) {} // eslint-disable-line - -module.exports = { - // Errors - MongoError: require('./error').MongoError, - MongoNetworkError: require('./error').MongoNetworkError, - MongoParseError: require('./error').MongoParseError, - MongoTimeoutError: require('./error').MongoTimeoutError, - MongoServerSelectionError: require('./error').MongoServerSelectionError, - MongoWriteConcernError: require('./error').MongoWriteConcernError, - // Core - Connection: require('./connection/connection'), - Server: require('./topologies/server'), - ReplSet: require('./topologies/replset'), - Mongos: require('./topologies/mongos'), - Logger: require('./connection/logger'), - Cursor: require('./cursor').CoreCursor, - ReadPreference: require('./topologies/read_preference'), - Sessions: require('./sessions'), - BSON: BSON, - EJSON: EJSON, - Topology: require('./sdam/topology').Topology, - // Raw operations - Query: require('./connection/commands').Query, - // Auth mechanisms - MongoCredentials: require('./auth/mongo_credentials').MongoCredentials, - defaultAuthProviders: require('./auth/defaultAuthProviders').defaultAuthProviders, - MongoCR: require('./auth/mongocr'), - X509: require('./auth/x509'), - Plain: require('./auth/plain'), - GSSAPI: require('./auth/gssapi'), - ScramSHA1: require('./auth/scram').ScramSHA1, - ScramSHA256: require('./auth/scram').ScramSHA256, - // Utilities - parseConnectionString: require('./uri_parser') -}; diff --git a/node_modules/mongodb/lib/core/sdam/common.js b/node_modules/mongodb/lib/core/sdam/common.js deleted file mode 100644 index c99b01c..0000000 --- a/node_modules/mongodb/lib/core/sdam/common.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -// shared state names -const STATE_CLOSING = 'closing'; -const STATE_CLOSED = 'closed'; -const STATE_CONNECTING = 'connecting'; -const STATE_CONNECTED = 'connected'; - -// An enumeration of topology types we know about -const TopologyType = { - Single: 'Single', - ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', - ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', - Sharded: 'Sharded', - Unknown: 'Unknown' -}; - -// An enumeration of server types we know about -const ServerType = { - Standalone: 'Standalone', - Mongos: 'Mongos', - PossiblePrimary: 'PossiblePrimary', - RSPrimary: 'RSPrimary', - RSSecondary: 'RSSecondary', - RSArbiter: 'RSArbiter', - RSOther: 'RSOther', - RSGhost: 'RSGhost', - Unknown: 'Unknown' -}; - -const TOPOLOGY_DEFAULTS = { - useUnifiedTopology: true, - localThresholdMS: 15, - serverSelectionTimeoutMS: 30000, - heartbeatFrequencyMS: 10000, - minHeartbeatFrequencyMS: 500 -}; - -function drainTimerQueue(queue) { - queue.forEach(clearTimeout); - queue.clear(); -} - -function clearAndRemoveTimerFrom(timer, timers) { - clearTimeout(timer); - return timers.delete(timer); -} - -module.exports = { - STATE_CLOSING, - STATE_CLOSED, - STATE_CONNECTING, - STATE_CONNECTED, - TOPOLOGY_DEFAULTS, - TopologyType, - ServerType, - drainTimerQueue, - clearAndRemoveTimerFrom -}; diff --git a/node_modules/mongodb/lib/core/sdam/events.js b/node_modules/mongodb/lib/core/sdam/events.js deleted file mode 100644 index 08a14ad..0000000 --- a/node_modules/mongodb/lib/core/sdam/events.js +++ /dev/null @@ -1,124 +0,0 @@ -'use strict'; - -/** - * Published when server description changes, but does NOT include changes to the RTT. - * - * @property {Object} topologyId A unique identifier for the topology - * @property {ServerAddress} address The address (host/port pair) of the server - * @property {ServerDescription} previousDescription The previous server description - * @property {ServerDescription} newDescription The new server description - */ -class ServerDescriptionChangedEvent { - constructor(topologyId, address, previousDescription, newDescription) { - Object.assign(this, { topologyId, address, previousDescription, newDescription }); - } -} - -/** - * Published when server is initialized. - * - * @property {Object} topologyId A unique identifier for the topology - * @property {ServerAddress} address The address (host/port pair) of the server - */ -class ServerOpeningEvent { - constructor(topologyId, address) { - Object.assign(this, { topologyId, address }); - } -} - -/** - * Published when server is closed. - * - * @property {ServerAddress} address The address (host/port pair) of the server - * @property {Object} topologyId A unique identifier for the topology - */ -class ServerClosedEvent { - constructor(topologyId, address) { - Object.assign(this, { topologyId, address }); - } -} - -/** - * Published when topology description changes. - * - * @property {Object} topologyId - * @property {TopologyDescription} previousDescription The old topology description - * @property {TopologyDescription} newDescription The new topology description - */ -class TopologyDescriptionChangedEvent { - constructor(topologyId, previousDescription, newDescription) { - Object.assign(this, { topologyId, previousDescription, newDescription }); - } -} - -/** - * Published when topology is initialized. - * - * @param {Object} topologyId A unique identifier for the topology - */ -class TopologyOpeningEvent { - constructor(topologyId) { - Object.assign(this, { topologyId }); - } -} - -/** - * Published when topology is closed. - * - * @param {Object} topologyId A unique identifier for the topology - */ -class TopologyClosedEvent { - constructor(topologyId) { - Object.assign(this, { topologyId }); - } -} - -/** - * Fired when the server monitor’s ismaster command is started - immediately before - * the ismaster command is serialized into raw BSON and written to the socket. - * - * @property {Object} connectionId The connection id for the command - */ -class ServerHeartbeatStartedEvent { - constructor(connectionId) { - Object.assign(this, { connectionId }); - } -} - -/** - * Fired when the server monitor’s ismaster succeeds. - * - * @param {Number} duration The execution time of the event in ms - * @param {Object} reply The command reply - * @param {Object} connectionId The connection id for the command - */ -class ServerHeartbeatSucceededEvent { - constructor(duration, reply, connectionId) { - Object.assign(this, { connectionId, duration, reply }); - } -} - -/** - * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. - * - * @param {Number} duration The execution time of the event in ms - * @param {MongoError|Object} failure The command failure - * @param {Object} connectionId The connection id for the command - */ -class ServerHeartbeatFailedEvent { - constructor(duration, failure, connectionId) { - Object.assign(this, { connectionId, duration, failure }); - } -} - -module.exports = { - ServerDescriptionChangedEvent, - ServerOpeningEvent, - ServerClosedEvent, - TopologyDescriptionChangedEvent, - TopologyOpeningEvent, - TopologyClosedEvent, - ServerHeartbeatStartedEvent, - ServerHeartbeatSucceededEvent, - ServerHeartbeatFailedEvent -}; diff --git a/node_modules/mongodb/lib/core/sdam/monitor.js b/node_modules/mongodb/lib/core/sdam/monitor.js deleted file mode 100644 index a5ddff8..0000000 --- a/node_modules/mongodb/lib/core/sdam/monitor.js +++ /dev/null @@ -1,251 +0,0 @@ -'use strict'; - -const ServerType = require('./common').ServerType; -const calculateDurationInMs = require('../utils').calculateDurationInMs; -const EventEmitter = require('events'); -const connect = require('../connection/connect'); -const Connection = require('../../cmap/connection').Connection; -const common = require('./common'); -const makeStateMachine = require('../utils').makeStateMachine; -const MongoError = require('../error').MongoError; - -const sdamEvents = require('./events'); -const ServerHeartbeatStartedEvent = sdamEvents.ServerHeartbeatStartedEvent; -const ServerHeartbeatSucceededEvent = sdamEvents.ServerHeartbeatSucceededEvent; -const ServerHeartbeatFailedEvent = sdamEvents.ServerHeartbeatFailedEvent; - -const kServer = Symbol('server'); -const kMonitorId = Symbol('monitorId'); -const kConnection = Symbol('connection'); -const kCancellationToken = Symbol('cancellationToken'); -const kLastCheckTime = Symbol('lastCheckTime'); - -const STATE_CLOSED = common.STATE_CLOSED; -const STATE_CLOSING = common.STATE_CLOSING; -const STATE_IDLE = 'idle'; -const STATE_MONITORING = 'monitoring'; -const stateTransition = makeStateMachine({ - [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED], - [STATE_CLOSED]: [STATE_CLOSED, STATE_MONITORING], - [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, STATE_CLOSING], - [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, STATE_CLOSING] -}); - -const INVALID_REQUEST_CHECK_STATES = new Set([STATE_CLOSING, STATE_CLOSED, STATE_MONITORING]); - -class Monitor extends EventEmitter { - constructor(server, options) { - super(options); - - this[kServer] = server; - this[kConnection] = undefined; - this[kCancellationToken] = new EventEmitter(); - this[kCancellationToken].setMaxListeners(Infinity); - this.s = { - state: STATE_CLOSED - }; - - this.address = server.description.address; - this.options = Object.freeze({ - connectTimeoutMS: - typeof options.connectionTimeout === 'number' - ? options.connectionTimeout - : typeof options.connectTimeoutMS === 'number' - ? options.connectTimeoutMS - : 10000, - heartbeatFrequencyMS: - typeof options.heartbeatFrequencyMS === 'number' ? options.heartbeatFrequencyMS : 10000, - minHeartbeatFrequencyMS: - typeof options.minHeartbeatFrequencyMS === 'number' ? options.minHeartbeatFrequencyMS : 500 - }); - - // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration - const addressParts = server.description.address.split(':'); - this.connectOptions = Object.freeze( - Object.assign( - { - id: '', - host: addressParts[0], - port: parseInt(addressParts[1], 10), - bson: server.s.bson, - connectionType: Connection - }, - server.s.options, - this.options, - - // force BSON serialization options - { - raw: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: true - } - ) - ); - } - - connect() { - if (this.s.state !== STATE_CLOSED) { - return; - } - - monitorServer(this); - } - - requestCheck() { - if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { - return; - } - - const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; - const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; - const remainingTime = heartbeatFrequencyMS - calculateDurationInMs(this[kLastCheckTime]); - if (remainingTime > minHeartbeatFrequencyMS && this[kMonitorId]) { - clearTimeout(this[kMonitorId]); - rescheduleMonitoring(this, minHeartbeatFrequencyMS); - return; - } - - if (this[kMonitorId]) { - clearTimeout(this[kMonitorId]); - } - - monitorServer(this); - } - - close() { - if (this.s.state === STATE_CLOSED || this.s.state === STATE_CLOSING) { - return; - } - - stateTransition(this, STATE_CLOSING); - this[kCancellationToken].emit('cancel'); - if (this[kMonitorId]) { - clearTimeout(this[kMonitorId]); - } - - if (this[kConnection]) { - this[kConnection].destroy({ force: true }); - } - - this.emit('close'); - stateTransition(this, STATE_CLOSED); - } -} - -function checkServer(monitor, callback) { - if (monitor[kConnection] && monitor[kConnection].closed) { - monitor[kConnection] = undefined; - } - - const start = process.hrtime(); - monitor.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(monitor.address)); - - function failureHandler(err) { - monitor.emit( - 'serverHeartbeatFailed', - new ServerHeartbeatFailedEvent(calculateDurationInMs(start), err, monitor.address) - ); - - callback(err); - } - - function successHandler(isMaster) { - monitor.emit( - 'serverHeartbeatSucceeded', - new ServerHeartbeatSucceededEvent(calculateDurationInMs(start), isMaster, monitor.address) - ); - - return callback(undefined, isMaster); - } - - if (monitor[kConnection] != null) { - const connectTimeoutMS = monitor.options.connectTimeoutMS; - monitor[kConnection].command( - 'admin.$cmd', - { ismaster: true }, - { socketTimeout: connectTimeoutMS }, - (err, result) => { - if (err) { - failureHandler(err); - return; - } - - successHandler(result.result); - } - ); - - return; - } - - // connecting does an implicit `ismaster` - connect(monitor.connectOptions, monitor[kCancellationToken], (err, conn) => { - if (err) { - monitor[kConnection] = undefined; - failureHandler(err); - return; - } - - if (monitor.s.state === STATE_CLOSING || monitor.s.state === STATE_CLOSED) { - conn.destroy({ force: true }); - failureHandler(new MongoError('monitor was destroyed')); - return; - } - - monitor[kConnection] = conn; - successHandler(conn.ismaster); - }); -} - -function monitorServer(monitor) { - stateTransition(monitor, STATE_MONITORING); - - // TODO: the next line is a legacy event, remove in v4 - process.nextTick(() => monitor.emit('monitoring', monitor[kServer])); - - checkServer(monitor, e0 => { - if (e0 == null) { - rescheduleMonitoring(monitor); - return; - } - - // otherwise an error occured on initial discovery, also bail - if (monitor[kServer].description.type === ServerType.Unknown) { - monitor.emit('resetServer', e0); - rescheduleMonitoring(monitor); - return; - } - - // According to the SDAM specification's "Network error during server check" section, if - // an ismaster call fails we reset the server's pool. If a server was once connected, - // change its type to `Unknown` only after retrying once. - monitor.emit('resetConnectionPool'); - - checkServer(monitor, e1 => { - if (e1) { - monitor.emit('resetServer', e1); - } - - rescheduleMonitoring(monitor); - }); - }); -} - -function rescheduleMonitoring(monitor, ms) { - const heartbeatFrequencyMS = monitor.options.heartbeatFrequencyMS; - if (monitor.s.state === STATE_CLOSING || monitor.s.state === STATE_CLOSED) { - return; - } - - stateTransition(monitor, STATE_IDLE); - - monitor[kLastCheckTime] = process.hrtime(); - monitor[kMonitorId] = setTimeout(() => { - monitor[kMonitorId] = undefined; - monitor.requestCheck(); - }, ms || heartbeatFrequencyMS); -} - -module.exports = { - Monitor -}; diff --git a/node_modules/mongodb/lib/core/sdam/server.js b/node_modules/mongodb/lib/core/sdam/server.js deleted file mode 100644 index 031d34d..0000000 --- a/node_modules/mongodb/lib/core/sdam/server.js +++ /dev/null @@ -1,495 +0,0 @@ -'use strict'; -const EventEmitter = require('events'); -const ConnectionPool = require('../../cmap/connection_pool').ConnectionPool; -const CMAP_EVENT_NAMES = require('../../cmap/events').CMAP_EVENT_NAMES; -const MongoError = require('../error').MongoError; -const relayEvents = require('../utils').relayEvents; -const BSON = require('../connection/utils').retrieveBSON(); -const Logger = require('../connection/logger'); -const ServerDescription = require('./server_description').ServerDescription; -const ReadPreference = require('../topologies/read_preference'); -const Monitor = require('./monitor').Monitor; -const MongoNetworkError = require('../error').MongoNetworkError; -const collationNotSupported = require('../utils').collationNotSupported; -const debugOptions = require('../connection/utils').debugOptions; -const isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError; -const isNetworkTimeoutError = require('../error').isNetworkTimeoutError; -const isNodeShuttingDownError = require('../error').isNodeShuttingDownError; -const maxWireVersion = require('../utils').maxWireVersion; -const makeStateMachine = require('../utils').makeStateMachine; -const common = require('./common'); - -// Used for filtering out fields for logging -const DEBUG_FIELDS = [ - 'reconnect', - 'reconnectTries', - 'reconnectInterval', - 'emitError', - 'cursorFactory', - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'checkServerIdentity', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'key', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'servername' -]; - -const STATE_CLOSING = common.STATE_CLOSING; -const STATE_CLOSED = common.STATE_CLOSED; -const STATE_CONNECTING = common.STATE_CONNECTING; -const STATE_CONNECTED = common.STATE_CONNECTED; -const stateTransition = makeStateMachine({ - [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], - [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], - [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], - [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] -}); - -const kMonitor = Symbol('monitor'); - -/** - * - * @fires Server#serverHeartbeatStarted - * @fires Server#serverHeartbeatSucceeded - * @fires Server#serverHeartbeatFailed - */ -class Server extends EventEmitter { - /** - * Create a server - * - * @param {ServerDescription} description - * @param {Object} options - */ - constructor(description, options, topology) { - super(); - - this.s = { - // the server description - description, - // a saved copy of the incoming options - options, - // the server logger - logger: Logger('Server', options), - // the bson parser - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // the server state - state: STATE_CLOSED, - credentials: options.credentials, - topology - }; - - // create the connection pool - // NOTE: this used to happen in `connect`, we supported overriding pool options there - const addressParts = this.description.address.split(':'); - const poolOptions = Object.assign( - { host: addressParts[0], port: parseInt(addressParts[1], 10), bson: this.s.bson }, - options - ); - - this.s.pool = new ConnectionPool(poolOptions); - relayEvents( - this.s.pool, - this, - ['commandStarted', 'commandSucceeded', 'commandFailed'].concat(CMAP_EVENT_NAMES) - ); - - this.s.pool.on('clusterTimeReceived', clusterTime => { - this.clusterTime = clusterTime; - }); - - // create the monitor - this[kMonitor] = new Monitor(this, this.s.options); - relayEvents(this[kMonitor], this, [ - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - - // legacy events - 'monitoring' - ]); - - this[kMonitor].on('resetConnectionPool', () => { - this.s.pool.clear(); - }); - - this[kMonitor].on('resetServer', error => markServerUnknown(this, error)); - this[kMonitor].on('serverHeartbeatSucceeded', event => { - this.emit( - 'descriptionReceived', - new ServerDescription(this.description.address, event.reply, { - roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration) - }) - ); - - if (this.s.state === STATE_CONNECTING) { - stateTransition(this, STATE_CONNECTED); - this.emit('connect', this); - } - }); - } - - get description() { - return this.s.description; - } - - get name() { - return this.s.description.address; - } - - get autoEncrypter() { - if (this.s.options && this.s.options.autoEncrypter) { - return this.s.options.autoEncrypter; - } - return null; - } - - /** - * Initiate server connect - */ - connect() { - if (this.s.state !== STATE_CLOSED) { - return; - } - - stateTransition(this, STATE_CONNECTING); - this[kMonitor].connect(); - } - - /** - * Destroy the server connection - * - * @param {object} [options] Optional settings - * @param {Boolean} [options.force=false] Force destroy the pool - */ - destroy(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { force: false }, options); - - if (this.s.state === STATE_CLOSED) { - if (typeof callback === 'function') { - callback(); - } - - return; - } - - stateTransition(this, STATE_CLOSING); - - this[kMonitor].close(); - this.s.pool.close(options, err => { - stateTransition(this, STATE_CLOSED); - this.emit('closed'); - if (typeof callback === 'function') { - callback(err); - } - }); - } - - /** - * Immediately schedule monitoring of this server. If there already an attempt being made - * this will be a no-op. - */ - requestCheck() { - this[kMonitor].requestCheck(); - } - - /** - * Execute a command - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {object} [options] Optional settings - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. - * @param {ClientSession} [options.session] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - command(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { - callback(new MongoError('server is closed')); - return; - } - - const error = basicReadValidations(this, options); - if (error) { - return callback(error); - } - - // Clone the options - options = Object.assign({}, options, { wireProtocolCommand: false }); - - // Debug log - if (this.s.logger.isDebug()) { - this.s.logger.debug( - `executing command [${JSON.stringify({ - ns, - cmd, - options: debugOptions(DEBUG_FIELDS, options) - })}] against ${this.name}` - ); - } - - // error if collation not supported - if (collationNotSupported(this, cmd)) { - callback(new MongoError(`server ${this.name} does not support collation`)); - return; - } - - this.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(this, err); - return cb(err); - } - - conn.command(ns, cmd, options, makeOperationHandler(this, options, cb)); - }, callback); - } - - /** - * Execute a query against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command document for the query - * @param {object} options Optional settings - * @param {function} callback - */ - query(ns, cmd, cursorState, options, callback) { - if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { - callback(new MongoError('server is closed')); - return; - } - - this.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(this, err); - return cb(err); - } - - conn.query(ns, cmd, cursorState, options, makeOperationHandler(this, options, cb)); - }, callback); - } - - /** - * Execute a `getMore` against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {object} options Optional settings - * @param {function} callback - */ - getMore(ns, cursorState, batchSize, options, callback) { - if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { - callback(new MongoError('server is closed')); - return; - } - - this.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(this, err); - return cb(err); - } - - conn.getMore(ns, cursorState, batchSize, options, makeOperationHandler(this, options, cb)); - }, callback); - } - - /** - * Execute a `killCursors` command against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {function} callback - */ - killCursors(ns, cursorState, callback) { - if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { - if (typeof callback === 'function') { - callback(new MongoError('server is closed')); - } - - return; - } - - this.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(this, err); - return cb(err); - } - - conn.killCursors(ns, cursorState, makeOperationHandler(this, null, cb)); - }, callback); - } - - /** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - insert(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback); - } - - /** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - update(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback); - } - - /** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - remove(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback); - } -} - -Object.defineProperty(Server.prototype, 'clusterTime', { - get: function() { - return this.s.topology.clusterTime; - }, - set: function(clusterTime) { - this.s.topology.clusterTime = clusterTime; - } -}); - -function calculateRoundTripTime(oldRtt, duration) { - const alpha = 0.2; - return alpha * duration + (1 - alpha) * oldRtt; -} - -function basicReadValidations(server, options) { - if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { - return new MongoError('readPreference must be an instance of ReadPreference'); - } -} - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const server = args.server; - const op = args.op; - const ns = args.ns; - const ops = Array.isArray(args.ops) ? args.ops : [args.ops]; - - if (server.s.state === STATE_CLOSING || server.s.state === STATE_CLOSED) { - callback(new MongoError('server is closed')); - return; - } - - if (collationNotSupported(server, options)) { - callback(new MongoError(`server ${server.name} does not support collation`)); - return; - } - - server.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(server, err); - return cb(err); - } - - conn[op](ns, ops, options, makeOperationHandler(server, options, cb)); - }, callback); -} - -function markServerUnknown(server, error) { - server.emit( - 'descriptionReceived', - new ServerDescription(server.description.address, null, { error }) - ); -} - -function makeOperationHandler(server, options, callback) { - const session = options && options.session; - - return function handleOperationResult(err, result) { - if (err) { - if (err instanceof MongoNetworkError) { - if (session && !session.hasEnded) { - session.serverSession.isDirty = true; - } - - if (!isNetworkTimeoutError(err)) { - markServerUnknown(server, err); - server.s.pool.clear(); - } - } else if (isSDAMUnrecoverableError(err)) { - if (maxWireVersion(server) <= 7 || isNodeShuttingDownError(err)) { - server.s.pool.clear(); - } - - markServerUnknown(server, err); - process.nextTick(() => server.requestCheck()); - } - } - - callback(err, result); - }; -} - -module.exports = { - Server -}; diff --git a/node_modules/mongodb/lib/core/sdam/server_description.js b/node_modules/mongodb/lib/core/sdam/server_description.js deleted file mode 100644 index 1a26c06..0000000 --- a/node_modules/mongodb/lib/core/sdam/server_description.js +++ /dev/null @@ -1,181 +0,0 @@ -'use strict'; - -const arrayStrictEqual = require('../utils').arrayStrictEqual; -const tagsStrictEqual = require('../utils').tagsStrictEqual; -const errorStrictEqual = require('../utils').errorStrictEqual; -const ServerType = require('./common').ServerType; - -const WRITABLE_SERVER_TYPES = new Set([ - ServerType.RSPrimary, - ServerType.Standalone, - ServerType.Mongos -]); - -const DATA_BEARING_SERVER_TYPES = new Set([ - ServerType.RSPrimary, - ServerType.RSSecondary, - ServerType.Mongos, - ServerType.Standalone -]); - -const ISMASTER_FIELDS = [ - 'minWireVersion', - 'maxWireVersion', - 'maxBsonObjectSize', - 'maxMessageSizeBytes', - 'maxWriteBatchSize', - 'compression', - 'me', - 'hosts', - 'passives', - 'arbiters', - 'tags', - 'setName', - 'setVersion', - 'electionId', - 'primary', - 'logicalSessionTimeoutMinutes', - 'saslSupportedMechs', - '__nodejs_mock_server__', - '$clusterTime' -]; - -/** - * The client's view of a single server, based on the most recent ismaster outcome. - * - * Internal type, not meant to be directly instantiated - */ -class ServerDescription { - /** - * Create a ServerDescription - * @param {String} address The address of the server - * @param {Object} [ismaster] An optional ismaster response for this server - * @param {Object} [options] Optional settings - * @param {Number} [options.roundTripTime] The round trip time to ping this server (in ms) - */ - constructor(address, ismaster, options) { - options = options || {}; - ismaster = Object.assign( - { - minWireVersion: 0, - maxWireVersion: 0, - hosts: [], - passives: [], - arbiters: [], - tags: [] - }, - ismaster - ); - - this.address = address; - this.error = options.error; - this.roundTripTime = options.roundTripTime || -1; - this.lastUpdateTime = Date.now(); - this.lastWriteDate = ismaster.lastWrite ? ismaster.lastWrite.lastWriteDate : null; - this.opTime = ismaster.lastWrite ? ismaster.lastWrite.opTime : null; - this.type = parseServerType(ismaster); - - // direct mappings - ISMASTER_FIELDS.forEach(field => { - if (typeof ismaster[field] !== 'undefined') this[field] = ismaster[field]; - }); - - // normalize case for hosts - if (this.me) this.me = this.me.toLowerCase(); - this.hosts = this.hosts.map(host => host.toLowerCase()); - this.passives = this.passives.map(host => host.toLowerCase()); - this.arbiters = this.arbiters.map(host => host.toLowerCase()); - } - - get allHosts() { - return this.hosts.concat(this.arbiters).concat(this.passives); - } - - /** - * @return {Boolean} Is this server available for reads - */ - get isReadable() { - return this.type === ServerType.RSSecondary || this.isWritable; - } - - /** - * @return {Boolean} Is this server data bearing - */ - get isDataBearing() { - return DATA_BEARING_SERVER_TYPES.has(this.type); - } - - /** - * @return {Boolean} Is this server available for writes - */ - get isWritable() { - return WRITABLE_SERVER_TYPES.has(this.type); - } - - /** - * Determines if another `ServerDescription` is equal to this one per the rules defined - * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} - * - * @param {ServerDescription} other - * @return {Boolean} - */ - equals(other) { - return ( - other != null && - errorStrictEqual(this.error, other.error) && - this.type === other.type && - this.minWireVersion === other.minWireVersion && - this.me === other.me && - arrayStrictEqual(this.hosts, other.hosts) && - tagsStrictEqual(this.tags, other.tags) && - this.setName === other.setName && - this.setVersion === other.setVersion && - (this.electionId - ? other.electionId && this.electionId.equals(other.electionId) - : this.electionId === other.electionId) && - this.primary === other.primary && - this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes - ); - } -} - -/** - * Parses an `ismaster` message and determines the server type - * - * @param {Object} ismaster The `ismaster` message to parse - * @return {ServerType} - */ -function parseServerType(ismaster) { - if (!ismaster || !ismaster.ok) { - return ServerType.Unknown; - } - - if (ismaster.isreplicaset) { - return ServerType.RSGhost; - } - - if (ismaster.msg && ismaster.msg === 'isdbgrid') { - return ServerType.Mongos; - } - - if (ismaster.setName) { - if (ismaster.hidden) { - return ServerType.RSOther; - } else if (ismaster.ismaster) { - return ServerType.RSPrimary; - } else if (ismaster.secondary) { - return ServerType.RSSecondary; - } else if (ismaster.arbiterOnly) { - return ServerType.RSArbiter; - } else { - return ServerType.RSOther; - } - } - - return ServerType.Standalone; -} - -module.exports = { - ServerDescription, - parseServerType -}; diff --git a/node_modules/mongodb/lib/core/sdam/server_selection.js b/node_modules/mongodb/lib/core/sdam/server_selection.js deleted file mode 100644 index 50b6919..0000000 --- a/node_modules/mongodb/lib/core/sdam/server_selection.js +++ /dev/null @@ -1,232 +0,0 @@ -'use strict'; -const ServerType = require('./common').ServerType; -const TopologyType = require('./common').TopologyType; -const ReadPreference = require('../topologies/read_preference'); -const MongoError = require('../error').MongoError; - -// max staleness constants -const IDLE_WRITE_PERIOD = 10000; -const SMALLEST_MAX_STALENESS_SECONDS = 90; - -/** - * Returns a server selector that selects for writable servers - */ -function writableServerSelector() { - return function(topologyDescription, servers) { - return latencyWindowReducer( - topologyDescription, - servers.filter(s => s.isWritable) - ); - }; -} - -/** - * Reduces the passed in array of servers by the rules of the "Max Staleness" specification - * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst - * - * @param {ReadPreference} readPreference The read preference providing max staleness guidance - * @param {topologyDescription} topologyDescription The topology description - * @param {ServerDescription[]} servers The list of server descriptions to be reduced - * @return {ServerDescription[]} The list of servers that satisfy the requirements of max staleness - */ -function maxStalenessReducer(readPreference, topologyDescription, servers) { - if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { - return servers; - } - - const maxStaleness = readPreference.maxStalenessSeconds; - const maxStalenessVariance = - (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; - if (maxStaleness < maxStalenessVariance) { - throw new MongoError(`maxStalenessSeconds must be at least ${maxStalenessVariance} seconds`); - } - - if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { - throw new MongoError( - `maxStalenessSeconds must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` - ); - } - - if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { - const primary = Array.from(topologyDescription.servers.values()).filter(primaryFilter)[0]; - return servers.reduce((result, server) => { - const stalenessMS = - server.lastUpdateTime - - server.lastWriteDate - - (primary.lastUpdateTime - primary.lastWriteDate) + - topologyDescription.heartbeatFrequencyMS; - - const staleness = stalenessMS / 1000; - if (staleness <= readPreference.maxStalenessSeconds) result.push(server); - return result; - }, []); - } else if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { - const sMax = servers.reduce((max, s) => (s.lastWriteDate > max.lastWriteDate ? s : max)); - return servers.reduce((result, server) => { - const stalenessMS = - sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; - - const staleness = stalenessMS / 1000; - if (staleness <= readPreference.maxStalenessSeconds) result.push(server); - return result; - }, []); - } - - return servers; -} - -/** - * Determines whether a server's tags match a given set of tags - * - * @param {String[]} tagSet The requested tag set to match - * @param {String[]} serverTags The server's tags - */ -function tagSetMatch(tagSet, serverTags) { - const keys = Object.keys(tagSet); - const serverTagKeys = Object.keys(serverTags); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { - return false; - } - } - - return true; -} - -/** - * Reduces a set of server descriptions based on tags requested by the read preference - * - * @param {ReadPreference} readPreference The read preference providing the requested tags - * @param {ServerDescription[]} servers The list of server descriptions to reduce - * @return {ServerDescription[]} The list of servers matching the requested tags - */ -function tagSetReducer(readPreference, servers) { - if ( - readPreference.tags == null || - (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) - ) { - return servers; - } - - for (let i = 0; i < readPreference.tags.length; ++i) { - const tagSet = readPreference.tags[i]; - const serversMatchingTagset = servers.reduce((matched, server) => { - if (tagSetMatch(tagSet, server.tags)) matched.push(server); - return matched; - }, []); - - if (serversMatchingTagset.length) { - return serversMatchingTagset; - } - } - - return []; -} - -/** - * Reduces a list of servers to ensure they fall within an acceptable latency window. This is - * further specified in the "Server Selection" specification, found here: - * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst - * - * @param {topologyDescription} topologyDescription The topology description - * @param {ServerDescription[]} servers The list of servers to reduce - * @returns {ServerDescription[]} The servers which fall within an acceptable latency window - */ -function latencyWindowReducer(topologyDescription, servers) { - const low = servers.reduce( - (min, server) => (min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min)), - -1 - ); - - const high = low + topologyDescription.localThresholdMS; - - return servers.reduce((result, server) => { - if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); - return result; - }, []); -} - -// filters -function primaryFilter(server) { - return server.type === ServerType.RSPrimary; -} - -function secondaryFilter(server) { - return server.type === ServerType.RSSecondary; -} - -function nearestFilter(server) { - return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; -} - -function knownFilter(server) { - return server.type !== ServerType.Unknown; -} - -/** - * Returns a function which selects servers based on a provided read preference - * - * @param {ReadPreference} readPreference The read preference to select with - */ -function readPreferenceServerSelector(readPreference) { - if (!readPreference.isValid()) { - throw new TypeError('Invalid read preference specified'); - } - - return function(topologyDescription, servers) { - const commonWireVersion = topologyDescription.commonWireVersion; - if ( - commonWireVersion && - readPreference.minWireVersion && - readPreference.minWireVersion > commonWireVersion - ) { - throw new MongoError( - `Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'` - ); - } - - if (topologyDescription.type === TopologyType.Unknown) { - return []; - } - - if ( - topologyDescription.type === TopologyType.Single || - topologyDescription.type === TopologyType.Sharded - ) { - return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); - } - - const mode = readPreference.mode; - if (mode === ReadPreference.PRIMARY) { - return servers.filter(primaryFilter); - } - - if (mode === ReadPreference.PRIMARY_PREFERRED) { - const result = servers.filter(primaryFilter); - if (result.length) { - return result; - } - } - - const filter = mode === ReadPreference.NEAREST ? nearestFilter : secondaryFilter; - const selectedServers = latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers.filter(filter)) - ) - ); - - if (mode === ReadPreference.SECONDARY_PREFERRED && selectedServers.length === 0) { - return servers.filter(primaryFilter); - } - - return selectedServers; - }; -} - -module.exports = { - writableServerSelector, - readPreferenceServerSelector -}; diff --git a/node_modules/mongodb/lib/core/sdam/srv_polling.js b/node_modules/mongodb/lib/core/sdam/srv_polling.js deleted file mode 100644 index 2c0b6ee..0000000 --- a/node_modules/mongodb/lib/core/sdam/srv_polling.js +++ /dev/null @@ -1,135 +0,0 @@ -'use strict'; - -const Logger = require('../connection/logger'); -const EventEmitter = require('events').EventEmitter; -const dns = require('dns'); -/** - * Determines whether a provided address matches the provided parent domain in order - * to avoid certain attack vectors. - * - * @param {String} srvAddress The address to check against a domain - * @param {String} parentDomain The domain to check the provided address against - * @return {Boolean} Whether the provided address matches the parent domain - */ -function matchesParentDomain(srvAddress, parentDomain) { - const regex = /^.*?\./; - const srv = `.${srvAddress.replace(regex, '')}`; - const parent = `.${parentDomain.replace(regex, '')}`; - return srv.endsWith(parent); -} - -class SrvPollingEvent { - constructor(srvRecords) { - this.srvRecords = srvRecords; - } - - addresses() { - return new Set(this.srvRecords.map(record => `${record.name}:${record.port}`)); - } -} - -class SrvPoller extends EventEmitter { - /** - * @param {object} options - * @param {string} options.srvHost - * @param {number} [options.heartbeatFrequencyMS] - * @param {function} [options.logger] - * @param {string} [options.loggerLevel] - */ - constructor(options) { - super(); - - if (!options || !options.srvHost) { - throw new TypeError('options for SrvPoller must exist and include srvHost'); - } - - this.srvHost = options.srvHost; - this.rescanSrvIntervalMS = 60000; - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - this.logger = Logger('srvPoller', options); - - this.haMode = false; - this.generation = 0; - - this._timeout = null; - } - - get srvAddress() { - return `_mongodb._tcp.${this.srvHost}`; - } - - get intervalMS() { - return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS; - } - - start() { - if (!this._timeout) { - this.schedule(); - } - } - - stop() { - if (this._timeout) { - clearTimeout(this._timeout); - this.generation += 1; - this._timeout = null; - } - } - - schedule() { - clearTimeout(this._timeout); - this._timeout = setTimeout(() => this._poll(), this.intervalMS); - } - - success(srvRecords) { - this.haMode = false; - this.schedule(); - this.emit('srvRecordDiscovery', new SrvPollingEvent(srvRecords)); - } - - failure(message, obj) { - this.logger.warn(message, obj); - this.haMode = true; - this.schedule(); - } - - parentDomainMismatch(srvRecord) { - this.logger.warn( - `parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`, - srvRecord - ); - } - - _poll() { - const generation = this.generation; - dns.resolveSrv(this.srvAddress, (err, srvRecords) => { - if (generation !== this.generation) { - return; - } - - if (err) { - this.failure('DNS error', err); - return; - } - - const finalAddresses = []; - srvRecords.forEach(record => { - if (matchesParentDomain(record.name, this.srvHost)) { - finalAddresses.push(record); - } else { - this.parentDomainMismatch(record); - } - }); - - if (!finalAddresses.length) { - this.failure('No valid addresses found at host'); - return; - } - - this.success(finalAddresses); - }); - } -} - -module.exports.SrvPollingEvent = SrvPollingEvent; -module.exports.SrvPoller = SrvPoller; diff --git a/node_modules/mongodb/lib/core/sdam/topology.js b/node_modules/mongodb/lib/core/sdam/topology.js deleted file mode 100644 index cdd9a47..0000000 --- a/node_modules/mongodb/lib/core/sdam/topology.js +++ /dev/null @@ -1,1131 +0,0 @@ -'use strict'; -const Denque = require('denque'); -const EventEmitter = require('events'); -const ServerDescription = require('./server_description').ServerDescription; -const ServerType = require('./common').ServerType; -const TopologyDescription = require('./topology_description').TopologyDescription; -const TopologyType = require('./common').TopologyType; -const events = require('./events'); -const Server = require('./server').Server; -const relayEvents = require('../utils').relayEvents; -const ReadPreference = require('../topologies/read_preference'); -const isRetryableWritesSupported = require('../topologies/shared').isRetryableWritesSupported; -const CoreCursor = require('../cursor').CoreCursor; -const deprecate = require('util').deprecate; -const BSON = require('../connection/utils').retrieveBSON(); -const createCompressionInfo = require('../topologies/shared').createCompressionInfo; -const isRetryableError = require('../error').isRetryableError; -const ClientSession = require('../sessions').ClientSession; -const MongoError = require('../error').MongoError; -const MongoServerSelectionError = require('../error').MongoServerSelectionError; -const resolveClusterTime = require('../topologies/shared').resolveClusterTime; -const SrvPoller = require('./srv_polling').SrvPoller; -const getMMAPError = require('../topologies/shared').getMMAPError; -const makeStateMachine = require('../utils').makeStateMachine; -const eachAsync = require('../utils').eachAsync; -const emitDeprecationWarning = require('../../utils').emitDeprecationWarning; -const ServerSessionPool = require('../sessions').ServerSessionPool; -const makeClientMetadata = require('../utils').makeClientMetadata; -const CMAP_EVENT_NAMES = require('../../cmap/events').CMAP_EVENT_NAMES; - -const common = require('./common'); -const drainTimerQueue = common.drainTimerQueue; -const clearAndRemoveTimerFrom = common.clearAndRemoveTimerFrom; - -const serverSelection = require('./server_selection'); -const readPreferenceServerSelector = serverSelection.readPreferenceServerSelector; -const writableServerSelector = serverSelection.writableServerSelector; - -// Global state -let globalTopologyCounter = 0; - -// events that we relay to the `Topology` -const SERVER_RELAY_EVENTS = [ - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - - // NOTE: Legacy events - 'monitoring' -].concat(CMAP_EVENT_NAMES); - -// all events we listen to from `Server` instances -const LOCAL_SERVER_EVENTS = ['connect', 'descriptionReceived', 'close', 'ended']; - -const STATE_CLOSING = common.STATE_CLOSING; -const STATE_CLOSED = common.STATE_CLOSED; -const STATE_CONNECTING = common.STATE_CONNECTING; -const STATE_CONNECTED = common.STATE_CONNECTED; -const stateTransition = makeStateMachine({ - [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], - [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], - [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], - [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] -}); - -const DEPRECATED_OPTIONS = new Set([ - 'autoReconnect', - 'reconnectTries', - 'reconnectInterval', - 'bufferMaxEntries' -]); - -const kCancelled = Symbol('cancelled'); -const kWaitQueue = Symbol('waitQueue'); - -/** - * A container of server instances representing a connection to a MongoDB topology. - * - * @fires Topology#serverOpening - * @fires Topology#serverClosed - * @fires Topology#serverDescriptionChanged - * @fires Topology#topologyOpening - * @fires Topology#topologyClosed - * @fires Topology#topologyDescriptionChanged - * @fires Topology#serverHeartbeatStarted - * @fires Topology#serverHeartbeatSucceeded - * @fires Topology#serverHeartbeatFailed - */ -class Topology extends EventEmitter { - /** - * Create a topology - * - * @param {Array|String} [seedlist] a string list, or array of Server instances to connect to - * @param {Object} [options] Optional settings - * @param {Number} [options.localThresholdMS=15] The size of the latency window for selecting among multiple suitable servers - * @param {Number} [options.serverSelectionTimeoutMS=30000] How long to block for server selection before throwing an error - * @param {Number} [options.heartbeatFrequencyMS=10000] The frequency with which topology updates are scheduled - */ - constructor(seedlist, options) { - super(); - if (typeof options === 'undefined' && typeof seedlist !== 'string') { - options = seedlist; - seedlist = []; - - // this is for legacy single server constructor support - if (options.host) { - seedlist.push({ host: options.host, port: options.port }); - } - } - - seedlist = seedlist || []; - if (typeof seedlist === 'string') { - seedlist = parseStringSeedlist(seedlist); - } - - options = Object.assign({}, common.TOPOLOGY_DEFAULTS, options); - options = Object.freeze( - Object.assign(options, { - metadata: makeClientMetadata(options), - compression: { compressors: createCompressionInfo(options) } - }) - ); - - DEPRECATED_OPTIONS.forEach(optionName => { - if (options[optionName]) { - emitDeprecationWarning( - `The option \`${optionName}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`, - 'DeprecationWarning' - ); - } - }); - - const topologyType = topologyTypeFromSeedlist(seedlist, options); - const topologyId = globalTopologyCounter++; - const serverDescriptions = seedlist.reduce((result, seed) => { - if (seed.domain_socket) seed.host = seed.domain_socket; - const address = seed.port ? `${seed.host}:${seed.port}` : `${seed.host}:27017`; - result.set(address, new ServerDescription(address)); - return result; - }, new Map()); - - this[kWaitQueue] = new Denque(); - this.s = { - // the id of this topology - id: topologyId, - // passed in options - options, - // initial seedlist of servers to connect to - seedlist: seedlist, - // initial state - state: STATE_CLOSED, - // the topology description - description: new TopologyDescription( - topologyType, - serverDescriptions, - options.replicaSet, - null, - null, - null, - options - ), - serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, - heartbeatFrequencyMS: options.heartbeatFrequencyMS, - minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS, - // allow users to override the cursor factory - Cursor: options.cursorFactory || CoreCursor, - // the bson parser - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // a map of server instances to normalized addresses - servers: new Map(), - // Server Session Pool - sessionPool: new ServerSessionPool(this), - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise, - credentials: options.credentials, - clusterTime: null, - - // timer management - connectionTimers: new Set() - }; - - if (options.srvHost) { - this.s.srvPoller = - options.srvPoller || - new SrvPoller({ - heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, - srvHost: options.srvHost, // TODO: GET THIS - logger: options.logger, - loggerLevel: options.loggerLevel - }); - this.s.detectTopologyDescriptionChange = ev => { - const previousType = ev.previousDescription.type; - const newType = ev.newDescription.type; - - if (previousType !== TopologyType.Sharded && newType === TopologyType.Sharded) { - this.s.handleSrvPolling = srvPollingHandler(this); - this.s.srvPoller.on('srvRecordDiscovery', this.s.handleSrvPolling); - this.s.srvPoller.start(); - } - }; - - this.on('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); - } - - // NOTE: remove this when NODE-1709 is resolved - this.setMaxListeners(Infinity); - } - - /** - * @return A `TopologyDescription` for this topology - */ - get description() { - return this.s.description; - } - - get parserType() { - return BSON.native ? 'c++' : 'js'; - } - - /** - * Initiate server connect - * - * @param {Object} [options] Optional settings - * @param {Array} [options.auth=null] Array of auth options to apply on connect - * @param {function} [callback] An optional callback called once on the first connected server - */ - connect(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - if (this.s.state === STATE_CONNECTED) { - if (typeof callback === 'function') { - callback(); - } - - return; - } - - stateTransition(this, STATE_CONNECTING); - - // emit SDAM monitoring events - this.emit('topologyOpening', new events.TopologyOpeningEvent(this.s.id)); - - // emit an event for the topology change - this.emit( - 'topologyDescriptionChanged', - new events.TopologyDescriptionChangedEvent( - this.s.id, - new TopologyDescription(TopologyType.Unknown), // initial is always Unknown - this.s.description - ) - ); - - // connect all known servers, then attempt server selection to connect - connectServers(this, Array.from(this.s.description.servers.values())); - - translateReadPreference(options); - const readPreference = options.readPreference || ReadPreference.primary; - this.selectServer(readPreferenceServerSelector(readPreference), options, err => { - if (err) { - this.close(); - - if (typeof callback === 'function') { - callback(err); - } else { - this.emit('error', err); - } - - return; - } - - stateTransition(this, STATE_CONNECTED); - this.emit('open', err, this); - this.emit('connect', this); - - if (typeof callback === 'function') callback(err, this); - }); - } - - /** - * Close this topology - */ - close(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - if (typeof options === 'boolean') { - options = { force: options }; - } - - options = options || {}; - if (this.s.state === STATE_CLOSED || this.s.state === STATE_CLOSING) { - if (typeof callback === 'function') { - callback(); - } - - return; - } - - stateTransition(this, STATE_CLOSING); - - drainWaitQueue(this[kWaitQueue], new MongoError('Topology closed')); - drainTimerQueue(this.s.connectionTimers); - - if (this.s.srvPoller) { - this.s.srvPoller.stop(); - if (this.s.handleSrvPolling) { - this.s.srvPoller.removeListener('srvRecordDiscovery', this.s.handleSrvPolling); - delete this.s.handleSrvPolling; - } - } - - if (this.s.detectTopologyDescriptionChange) { - this.removeListener('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); - delete this.s.detectTopologyDescriptionChange; - } - - this.s.sessions.forEach(session => session.endSession()); - this.s.sessionPool.endAllPooledSessions(() => { - eachAsync( - Array.from(this.s.servers.values()), - (server, cb) => destroyServer(server, this, options, cb), - err => { - this.s.servers.clear(); - - // emit an event for close - this.emit('topologyClosed', new events.TopologyClosedEvent(this.s.id)); - - stateTransition(this, STATE_CLOSED); - this.emit('close'); - - if (typeof callback === 'function') { - callback(err); - } - } - ); - }); - } - - /** - * Selects a server according to the selection predicate provided - * - * @param {function} [selector] An optional selector to select servers by, defaults to a random selection within a latency window - * @param {object} [options] Optional settings related to server selection - * @param {number} [options.serverSelectionTimeoutMS] How long to block for server selection before throwing an error - * @param {function} callback The callback used to indicate success or failure - * @return {Server} An instance of a `Server` meeting the criteria of the predicate provided - */ - selectServer(selector, options, callback) { - if (typeof options === 'function') { - callback = options; - if (typeof selector !== 'function') { - options = selector; - - let readPreference; - if (selector instanceof ReadPreference) { - readPreference = selector; - } else if (typeof selector === 'string') { - readPreference = new ReadPreference(selector); - } else { - translateReadPreference(options); - readPreference = options.readPreference || ReadPreference.primary; - } - - selector = readPreferenceServerSelector(readPreference); - } else { - options = {}; - } - } - - options = Object.assign( - {}, - { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, - options - ); - - const isSharded = this.description.type === TopologyType.Sharded; - const session = options.session; - const transaction = session && session.transaction; - - if (isSharded && transaction && transaction.server) { - callback(undefined, transaction.server); - return; - } - - // support server selection by options with readPreference - let serverSelector = selector; - if (typeof selector === 'object') { - const readPreference = selector.readPreference - ? selector.readPreference - : ReadPreference.primary; - - serverSelector = readPreferenceServerSelector(readPreference); - } - - const waitQueueMember = { - serverSelector, - transaction, - callback - }; - - const serverSelectionTimeoutMS = options.serverSelectionTimeoutMS; - if (serverSelectionTimeoutMS) { - waitQueueMember.timer = setTimeout(() => { - waitQueueMember[kCancelled] = true; - waitQueueMember.timer = undefined; - const timeoutError = new MongoServerSelectionError( - `Server selection timed out after ${serverSelectionTimeoutMS} ms`, - this.description - ); - - waitQueueMember.callback(timeoutError); - }, serverSelectionTimeoutMS); - } - - this[kWaitQueue].push(waitQueueMember); - processWaitQueue(this); - } - - // Sessions related methods - - /** - * @return Whether the topology should initiate selection to determine session support - */ - shouldCheckForSessionSupport() { - if (this.description.type === TopologyType.Single) { - return !this.description.hasKnownServers; - } - - return !this.description.hasDataBearingServers; - } - - /** - * @return Whether sessions are supported on the current topology - */ - hasSessionSupport() { - return this.description.logicalSessionTimeoutMinutes != null; - } - - /** - * Start a logical session - */ - startSession(options, clientOptions) { - const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); - session.once('ended', () => { - this.s.sessions.delete(session); - }); - - this.s.sessions.add(session); - return session; - } - - /** - * Send endSessions command(s) with the given session ids - * - * @param {Array} sessions The sessions to end - * @param {function} [callback] - */ - endSessions(sessions, callback) { - if (!Array.isArray(sessions)) { - sessions = [sessions]; - } - - this.command( - 'admin.$cmd', - { endSessions: sessions }, - { readPreference: ReadPreference.primaryPreferred, noResponse: true }, - () => { - // intentionally ignored, per spec - if (typeof callback === 'function') callback(); - } - ); - } - - /** - * Update the internal TopologyDescription with a ServerDescription - * - * @param {object} serverDescription The server to update in the internal list of server descriptions - */ - serverUpdateHandler(serverDescription) { - if (!this.s.description.hasServer(serverDescription.address)) { - return; - } - - // these will be used for monitoring events later - const previousTopologyDescription = this.s.description; - const previousServerDescription = this.s.description.servers.get(serverDescription.address); - - // Driver Sessions Spec: "Whenever a driver receives a cluster time from - // a server it MUST compare it to the current highest seen cluster time - // for the deployment. If the new cluster time is higher than the - // highest seen cluster time it MUST become the new highest seen cluster - // time. Two cluster times are compared using only the BsonTimestamp - // value of the clusterTime embedded field." - const clusterTime = serverDescription.$clusterTime; - if (clusterTime) { - resolveClusterTime(this, clusterTime); - } - - // If we already know all the information contained in this updated description, then - // we don't need to emit SDAM events, but still need to update the description, in order - // to keep client-tracked attributes like last update time and round trip time up to date - const equalDescriptions = - previousServerDescription && previousServerDescription.equals(serverDescription); - - // first update the TopologyDescription - this.s.description = this.s.description.update(serverDescription); - if (this.s.description.compatibilityError) { - this.emit('error', new MongoError(this.s.description.compatibilityError)); - return; - } - - // emit monitoring events for this change - if (!equalDescriptions) { - this.emit( - 'serverDescriptionChanged', - new events.ServerDescriptionChangedEvent( - this.s.id, - serverDescription.address, - previousServerDescription, - this.s.description.servers.get(serverDescription.address) - ) - ); - } - - // update server list from updated descriptions - updateServers(this, serverDescription); - - // attempt to resolve any outstanding server selection attempts - if (this[kWaitQueue].length > 0) { - processWaitQueue(this); - } - - if (!equalDescriptions) { - this.emit( - 'topologyDescriptionChanged', - new events.TopologyDescriptionChangedEvent( - this.s.id, - previousTopologyDescription, - this.s.description - ) - ); - } - } - - auth(credentials, callback) { - if (typeof credentials === 'function') (callback = credentials), (credentials = null); - if (typeof callback === 'function') callback(null, true); - } - - logout(callback) { - if (typeof callback === 'function') callback(null, true); - } - - // Basic operation support. Eventually this should be moved into command construction - // during the command refactor. - - /** - * Insert one or more documents - * - * @param {String} ns The full qualified namespace for this operation - * @param {Array} ops An array of documents to insert - * @param {Boolean} [options.ordered=true] Execute in order or out of order - * @param {Object} [options.writeConcern] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {ClientSession} [options.session] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - insert(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'insert', ns, ops }, options, callback); - } - - /** - * Perform one or more update operations - * - * @param {string} ns The fully qualified namespace for this operation - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {ClientSession} [options.session] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - update(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'update', ns, ops }, options, callback); - } - - /** - * Perform one or more remove operations - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - remove(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'remove', ns, ops }, options, callback); - } - - /** - * Execute a command - * - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - command(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - translateReadPreference(options); - const readPreference = options.readPreference || ReadPreference.primary; - - this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { - if (err) { - callback(err); - return; - } - - const willRetryWrite = - !options.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(this) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, options, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - server.command(ns, cmd, options, cb); - }); - } - - /** - * Create a new cursor - * - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ - cursor(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - const CursorClass = options.cursorFactory || this.s.Cursor; - translateReadPreference(options); - - return new CursorClass(topology, ns, cmd, options); - } - - get clientMetadata() { - return this.s.options.metadata; - } - - isConnected() { - return this.s.state === STATE_CONNECTED; - } - - isDestroyed() { - return this.s.state === STATE_CLOSED; - } - - unref() { - console.log('not implemented: `unref`'); - } - - // NOTE: There are many places in code where we explicitly check the last isMaster - // to do feature support detection. This should be done any other way, but for - // now we will just return the first isMaster seen, which should suffice. - lastIsMaster() { - const serverDescriptions = Array.from(this.description.servers.values()); - if (serverDescriptions.length === 0) return {}; - - const sd = serverDescriptions.filter(sd => sd.type !== ServerType.Unknown)[0]; - const result = sd || { maxWireVersion: this.description.commonWireVersion }; - return result; - } - - get logicalSessionTimeoutMinutes() { - return this.description.logicalSessionTimeoutMinutes; - } - - get bson() { - return this.s.bson; - } -} - -Object.defineProperty(Topology.prototype, 'clusterTime', { - enumerable: true, - get: function() { - return this.s.clusterTime; - }, - set: function(clusterTime) { - this.s.clusterTime = clusterTime; - } -}); - -// legacy aliases -Topology.prototype.destroy = deprecate( - Topology.prototype.close, - 'destroy() is deprecated, please use close() instead' -); - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Destroys a server, and removes all event listeners from the instance - * - * @param {Server} server - */ -function destroyServer(server, topology, options, callback) { - options = options || {}; - LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); - - server.destroy(options, () => { - topology.emit( - 'serverClosed', - new events.ServerClosedEvent(topology.s.id, server.description.address) - ); - - SERVER_RELAY_EVENTS.forEach(event => server.removeAllListeners(event)); - if (typeof callback === 'function') { - callback(); - } - }); -} - -/** - * Parses a basic seedlist in string form - * - * @param {string} seedlist The seedlist to parse - */ -function parseStringSeedlist(seedlist) { - return seedlist.split(',').map(seed => ({ - host: seed.split(':')[0], - port: seed.split(':')[1] || 27017 - })); -} - -function topologyTypeFromSeedlist(seedlist, options) { - const replicaSet = options.replicaSet || options.setName || options.rs_name; - if (seedlist.length === 1 && !replicaSet) return TopologyType.Single; - if (replicaSet) return TopologyType.ReplicaSetNoPrimary; - return TopologyType.Unknown; -} - -function randomSelection(array) { - return array[Math.floor(Math.random() * array.length)]; -} - -function createAndConnectServer(topology, serverDescription, connectDelay) { - topology.emit( - 'serverOpening', - new events.ServerOpeningEvent(topology.s.id, serverDescription.address) - ); - - const server = new Server(serverDescription, topology.s.options, topology); - relayEvents(server, topology, SERVER_RELAY_EVENTS); - - server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); - - if (connectDelay) { - const connectTimer = setTimeout(() => { - clearAndRemoveTimerFrom(connectTimer, topology.s.connectionTimers); - server.connect(); - }, connectDelay); - - topology.s.connectionTimers.add(connectTimer); - return server; - } - - server.connect(); - return server; -} - -/** - * Create `Server` instances for all initially known servers, connect them, and assign - * them to the passed in `Topology`. - * - * @param {Topology} topology The topology responsible for the servers - * @param {ServerDescription[]} serverDescriptions A list of server descriptions to connect - */ -function connectServers(topology, serverDescriptions) { - topology.s.servers = serverDescriptions.reduce((servers, serverDescription) => { - const server = createAndConnectServer(topology, serverDescription); - servers.set(serverDescription.address, server); - return servers; - }, new Map()); -} - -function updateServers(topology, incomingServerDescription) { - // update the internal server's description - if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { - const server = topology.s.servers.get(incomingServerDescription.address); - server.s.description = incomingServerDescription; - } - - // add new servers for all descriptions we currently don't know about locally - for (const serverDescription of topology.description.servers.values()) { - if (!topology.s.servers.has(serverDescription.address)) { - const server = createAndConnectServer(topology, serverDescription); - topology.s.servers.set(serverDescription.address, server); - } - } - - // for all servers no longer known, remove their descriptions and destroy their instances - for (const entry of topology.s.servers) { - const serverAddress = entry[0]; - if (topology.description.hasServer(serverAddress)) { - continue; - } - - const server = topology.s.servers.get(serverAddress); - topology.s.servers.delete(serverAddress); - - // prepare server for garbage collection - destroyServer(server, topology); - } -} - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const topology = args.topology; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(topology) && - !options.session.inTransaction(); - - topology.selectServer(writableServerSelector(), options, (err, server) => { - if (err) { - callback(err, null); - return; - } - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - err = getMMAPError(err); - return callback(err); - } - - if (willRetryWrite) { - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - } - - return callback(err); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // execute the write operation - server[op](ns, ops, options, handler); - }); -} - -function translateReadPreference(options) { - if (options.readPreference == null) { - return; - } - - let r = options.readPreference; - if (typeof r === 'string') { - options.readPreference = new ReadPreference(r); - } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { - const mode = r.mode || r.preference; - if (mode && typeof mode === 'string') { - options.readPreference = new ReadPreference(mode, r.tags, { - maxStalenessSeconds: r.maxStalenessSeconds - }); - } - } else if (!(r instanceof ReadPreference)) { - throw new TypeError('Invalid read preference: ' + r); - } - - return options; -} - -function srvPollingHandler(topology) { - return function handleSrvPolling(ev) { - const previousTopologyDescription = topology.s.description; - topology.s.description = topology.s.description.updateFromSrvPollingEvent(ev); - if (topology.s.description === previousTopologyDescription) { - // Nothing changed, so return - return; - } - - updateServers(topology); - - topology.emit( - 'topologyDescriptionChanged', - new events.TopologyDescriptionChangedEvent( - topology.s.id, - previousTopologyDescription, - topology.s.description - ) - ); - }; -} - -function drainWaitQueue(queue, err) { - while (queue.length) { - const waitQueueMember = queue.shift(); - clearTimeout(waitQueueMember.timer); - if (!waitQueueMember[kCancelled]) { - waitQueueMember.callback(err); - } - } -} - -function processWaitQueue(topology) { - if (topology.s.state === STATE_CLOSED) { - drainWaitQueue(topology[kWaitQueue], new MongoError('Topology is closed, please connect')); - return; - } - - const serverDescriptions = Array.from(topology.description.servers.values()); - const membersToProcess = topology[kWaitQueue].length; - for (let i = 0; i < membersToProcess && topology[kWaitQueue].length; ++i) { - const waitQueueMember = topology[kWaitQueue].shift(); - if (waitQueueMember[kCancelled]) { - continue; - } - - let selectedDescriptions; - try { - const serverSelector = waitQueueMember.serverSelector; - selectedDescriptions = serverSelector - ? serverSelector(topology.description, serverDescriptions) - : serverDescriptions; - } catch (e) { - clearTimeout(waitQueueMember.timer); - waitQueueMember.callback(e); - continue; - } - - if (selectedDescriptions.length === 0) { - topology[kWaitQueue].push(waitQueueMember); - continue; - } - - const selectedServerDescription = randomSelection(selectedDescriptions); - const selectedServer = topology.s.servers.get(selectedServerDescription.address); - const transaction = waitQueueMember.transaction; - const isSharded = topology.description.type === TopologyType.Sharded; - if (isSharded && transaction && transaction.isActive) { - transaction.pinServer(selectedServer); - } - - clearTimeout(waitQueueMember.timer); - waitQueueMember.callback(undefined, selectedServer); - } - - if (topology[kWaitQueue].length > 0) { - // ensure all server monitors attempt monitoring soon - topology.s.servers.forEach(server => process.nextTick(() => server.requestCheck())); - } -} - -/** - * A server opening SDAM monitoring event - * - * @event Topology#serverOpening - * @type {ServerOpeningEvent} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Topology#serverClosed - * @type {ServerClosedEvent} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Topology#serverDescriptionChanged - * @type {ServerDescriptionChangedEvent} - */ - -/** - * A topology open SDAM event - * - * @event Topology#topologyOpening - * @type {TopologyOpeningEvent} - */ - -/** - * A topology closed SDAM event - * - * @event Topology#topologyClosed - * @type {TopologyClosedEvent} - */ - -/** - * A topology structure SDAM change event - * - * @event Topology#topologyDescriptionChanged - * @type {TopologyDescriptionChangedEvent} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event Topology#serverHeartbeatStarted - * @type {ServerHeartbeatStartedEvent} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event Topology#serverHeartbeatFailed - * @type {ServerHearbeatFailedEvent} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event Topology#serverHeartbeatSucceeded - * @type {ServerHeartbeatSucceededEvent} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Topology#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Topology#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Topology#commandFailed - * @type {object} - */ - -module.exports = { - Topology -}; diff --git a/node_modules/mongodb/lib/core/sdam/topology_description.js b/node_modules/mongodb/lib/core/sdam/topology_description.js deleted file mode 100644 index d1beb22..0000000 --- a/node_modules/mongodb/lib/core/sdam/topology_description.js +++ /dev/null @@ -1,423 +0,0 @@ -'use strict'; -const ServerType = require('./common').ServerType; -const ServerDescription = require('./server_description').ServerDescription; -const WIRE_CONSTANTS = require('../wireprotocol/constants'); -const TopologyType = require('./common').TopologyType; - -// contstants related to compatability checks -const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; -const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; -const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; -const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; - -// Representation of a deployment of servers -class TopologyDescription { - /** - * Create a TopologyDescription - * - * @param {string} topologyType - * @param {Map} serverDescriptions the a map of address to ServerDescription - * @param {string} setName - * @param {number} maxSetVersion - * @param {ObjectId} maxElectionId - */ - constructor( - topologyType, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - options - ) { - options = options || {}; - - // TODO: consider assigning all these values to a temporary value `s` which - // we use `Object.freeze` on, ensuring the internal state of this type - // is immutable. - this.type = topologyType || TopologyType.Unknown; - this.setName = setName || null; - this.maxSetVersion = maxSetVersion || null; - this.maxElectionId = maxElectionId || null; - this.servers = serverDescriptions || new Map(); - this.stale = false; - this.compatible = true; - this.compatibilityError = null; - this.logicalSessionTimeoutMinutes = null; - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 0; - this.localThresholdMS = options.localThresholdMS || 0; - this.commonWireVersion = commonWireVersion || null; - - // save this locally, but don't display when printing the instance out - Object.defineProperty(this, 'options', { value: options, enumberable: false }); - - // determine server compatibility - for (const serverDescription of this.servers.values()) { - if (serverDescription.type === ServerType.Unknown) continue; - - if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { - this.compatible = false; - this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; - } - - if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { - this.compatible = false; - this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; - break; - } - } - - // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set - // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes - // value among ServerDescriptions of all data-bearing server types. If any have a null - // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be - // set to null. - const readableServers = Array.from(this.servers.values()).filter(s => s.isReadable); - this.logicalSessionTimeoutMinutes = readableServers.reduce((result, server) => { - if (server.logicalSessionTimeoutMinutes == null) return null; - if (result == null) return server.logicalSessionTimeoutMinutes; - return Math.min(result, server.logicalSessionTimeoutMinutes); - }, null); - } - - /** - * Returns a new TopologyDescription based on the SrvPollingEvent - * @param {SrvPollingEvent} ev The event - */ - updateFromSrvPollingEvent(ev) { - const newAddresses = ev.addresses(); - const serverDescriptions = new Map(this.servers); - for (const server of this.servers) { - if (newAddresses.has(server[0])) { - newAddresses.delete(server[0]); - } else { - serverDescriptions.delete(server[0]); - } - } - - if (serverDescriptions.size === this.servers.size && newAddresses.size === 0) { - return this; - } - - for (const address of newAddresses) { - serverDescriptions.set(address, new ServerDescription(address)); - } - - return new TopologyDescription( - this.type, - serverDescriptions, - this.setName, - this.maxSetVersion, - this.maxElectionId, - this.commonWireVersion, - this.options, - null - ); - } - - /** - * Returns a copy of this description updated with a given ServerDescription - * - * @param {ServerDescription} serverDescription - */ - update(serverDescription) { - const address = serverDescription.address; - // NOTE: there are a number of prime targets for refactoring here - // once we support destructuring assignments - - // potentially mutated values - let topologyType = this.type; - let setName = this.setName; - let maxSetVersion = this.maxSetVersion; - let maxElectionId = this.maxElectionId; - let commonWireVersion = this.commonWireVersion; - - const serverType = serverDescription.type; - let serverDescriptions = new Map(this.servers); - - // update common wire version - if (serverDescription.maxWireVersion !== 0) { - if (commonWireVersion == null) { - commonWireVersion = serverDescription.maxWireVersion; - } else { - commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); - } - } - - // update the actual server description - serverDescriptions.set(address, serverDescription); - - if (topologyType === TopologyType.Single) { - // once we are defined as single, that never changes - return new TopologyDescription( - TopologyType.Single, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - this.options - ); - } - - if (topologyType === TopologyType.Unknown) { - if (serverType === ServerType.Standalone) { - serverDescriptions.delete(address); - } else { - topologyType = topologyTypeForServerType(serverType); - } - } - - if (topologyType === TopologyType.Sharded) { - if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1) { - serverDescriptions.delete(address); - } - } - - if (topologyType === TopologyType.ReplicaSetNoPrimary) { - if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { - serverDescriptions.delete(address); - } - - if (serverType === ServerType.RSPrimary) { - const result = updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId - ); - - (topologyType = result[0]), - (setName = result[1]), - (maxSetVersion = result[2]), - (maxElectionId = result[3]); - } else if ( - [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 - ) { - const result = updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription); - (topologyType = result[0]), (setName = result[1]); - } - } - - if (topologyType === TopologyType.ReplicaSetWithPrimary) { - if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { - serverDescriptions.delete(address); - topologyType = checkHasPrimary(serverDescriptions); - } else if (serverType === ServerType.RSPrimary) { - const result = updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId - ); - - (topologyType = result[0]), - (setName = result[1]), - (maxSetVersion = result[2]), - (maxElectionId = result[3]); - } else if ( - [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 - ) { - topologyType = updateRsWithPrimaryFromMember( - serverDescriptions, - setName, - serverDescription - ); - } else { - topologyType = checkHasPrimary(serverDescriptions); - } - } - - return new TopologyDescription( - topologyType, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - this.options - ); - } - - get error() { - const descriptionsWithError = Array.from(this.servers.values()).filter(sd => sd.error); - if (descriptionsWithError.length > 0) { - return descriptionsWithError[0].error; - } - } - - /** - * Determines if the topology description has any known servers - */ - get hasKnownServers() { - return Array.from(this.servers.values()).some(sd => sd.type !== ServerType.Unknown); - } - - /** - * Determines if this topology description has a data-bearing server available. - */ - get hasDataBearingServers() { - return Array.from(this.servers.values()).some(sd => sd.isDataBearing); - } - - /** - * Determines if the topology has a definition for the provided address - * - * @param {String} address - * @return {Boolean} Whether the topology knows about this server - */ - hasServer(address) { - return this.servers.has(address); - } -} - -function topologyTypeForServerType(serverType) { - if (serverType === ServerType.Mongos) return TopologyType.Sharded; - if (serverType === ServerType.RSPrimary) return TopologyType.ReplicaSetWithPrimary; - return TopologyType.ReplicaSetNoPrimary; -} - -function compareObjectId(oid1, oid2) { - if (oid1 == null) { - return -1; - } - - if (oid2 == null) { - return 1; - } - - if (oid1.id instanceof Buffer && oid2.id instanceof Buffer) { - const oid1Buffer = oid1.id; - const oid2Buffer = oid2.id; - return oid1Buffer.compare(oid2Buffer); - } - - const oid1String = oid1.toString(); - const oid2String = oid2.toString(); - return oid1String.localeCompare(oid2String); -} - -function updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId -) { - setName = setName || serverDescription.setName; - if (setName !== serverDescription.setName) { - serverDescriptions.delete(serverDescription.address); - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; - } - - const electionId = serverDescription.electionId ? serverDescription.electionId : null; - if (serverDescription.setVersion && electionId) { - if (maxSetVersion && maxElectionId) { - if ( - maxSetVersion > serverDescription.setVersion || - compareObjectId(maxElectionId, electionId) > 0 - ) { - // this primary is stale, we must remove it - serverDescriptions.set( - serverDescription.address, - new ServerDescription(serverDescription.address) - ); - - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; - } - } - - maxElectionId = serverDescription.electionId; - } - - if ( - serverDescription.setVersion != null && - (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) - ) { - maxSetVersion = serverDescription.setVersion; - } - - // We've heard from the primary. Is it the same primary as before? - for (const address of serverDescriptions.keys()) { - const server = serverDescriptions.get(address); - - if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { - // Reset old primary's type to Unknown. - serverDescriptions.set(address, new ServerDescription(server.address)); - - // There can only be one primary - break; - } - } - - // Discover new hosts from this primary's response. - serverDescription.allHosts.forEach(address => { - if (!serverDescriptions.has(address)) { - serverDescriptions.set(address, new ServerDescription(address)); - } - }); - - // Remove hosts not in the response. - const currentAddresses = Array.from(serverDescriptions.keys()); - const responseAddresses = serverDescription.allHosts; - currentAddresses - .filter(addr => responseAddresses.indexOf(addr) === -1) - .forEach(address => { - serverDescriptions.delete(address); - }); - - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; -} - -function updateRsWithPrimaryFromMember(serverDescriptions, setName, serverDescription) { - if (setName == null) { - throw new TypeError('setName is required'); - } - - if ( - setName !== serverDescription.setName || - (serverDescription.me && serverDescription.address !== serverDescription.me) - ) { - serverDescriptions.delete(serverDescription.address); - } - - return checkHasPrimary(serverDescriptions); -} - -function updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription) { - let topologyType = TopologyType.ReplicaSetNoPrimary; - - setName = setName || serverDescription.setName; - if (setName !== serverDescription.setName) { - serverDescriptions.delete(serverDescription.address); - return [topologyType, setName]; - } - - serverDescription.allHosts.forEach(address => { - if (!serverDescriptions.has(address)) { - serverDescriptions.set(address, new ServerDescription(address)); - } - }); - - if (serverDescription.me && serverDescription.address !== serverDescription.me) { - serverDescriptions.delete(serverDescription.address); - } - - return [topologyType, setName]; -} - -function checkHasPrimary(serverDescriptions) { - for (const addr of serverDescriptions.keys()) { - if (serverDescriptions.get(addr).type === ServerType.RSPrimary) { - return TopologyType.ReplicaSetWithPrimary; - } - } - - return TopologyType.ReplicaSetNoPrimary; -} - -module.exports = { - TopologyDescription -}; diff --git a/node_modules/mongodb/lib/core/sessions.js b/node_modules/mongodb/lib/core/sessions.js deleted file mode 100644 index 9cc6b5b..0000000 --- a/node_modules/mongodb/lib/core/sessions.js +++ /dev/null @@ -1,787 +0,0 @@ -'use strict'; - -const retrieveBSON = require('./connection/utils').retrieveBSON; -const EventEmitter = require('events'); -const BSON = retrieveBSON(); -const Binary = BSON.Binary; -const uuidV4 = require('./utils').uuidV4; -const MongoError = require('./error').MongoError; -const isRetryableError = require('././error').isRetryableError; -const MongoNetworkError = require('./error').MongoNetworkError; -const MongoWriteConcernError = require('./error').MongoWriteConcernError; -const Transaction = require('./transactions').Transaction; -const TxnState = require('./transactions').TxnState; -const isPromiseLike = require('./utils').isPromiseLike; -const ReadPreference = require('./topologies/read_preference'); -const isTransactionCommand = require('./transactions').isTransactionCommand; -const resolveClusterTime = require('./topologies/shared').resolveClusterTime; -const isSharded = require('./wireprotocol/shared').isSharded; -const maxWireVersion = require('./utils').maxWireVersion; - -const minWireVersionForShardedTransactions = 8; - -function assertAlive(session, callback) { - if (session.serverSession == null) { - const error = new MongoError('Cannot use a session that has ended'); - if (typeof callback === 'function') { - callback(error, null); - return false; - } - - throw error; - } - - return true; -} - -/** - * Options to pass when creating a Client Session - * @typedef {Object} SessionOptions - * @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session - * @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session. - */ - -/** - * A BSON document reflecting the lsid of a {@link ClientSession} - * @typedef {Object} SessionId - */ - -const kServerSession = Symbol('serverSession'); - -/** - * A class representing a client session on the server - * WARNING: not meant to be instantiated directly. - * @class - * @hideconstructor - */ -class ClientSession extends EventEmitter { - /** - * Create a client session. - * WARNING: not meant to be instantiated directly - * - * @param {Topology} topology The current client's topology (Internal Class) - * @param {ServerSessionPool} sessionPool The server session pool (Internal Class) - * @param {SessionOptions} [options] Optional settings - * @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver - */ - constructor(topology, sessionPool, options, clientOptions) { - super(); - - if (topology == null) { - throw new Error('ClientSession requires a topology'); - } - - if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { - throw new Error('ClientSession requires a ServerSessionPool'); - } - - options = options || {}; - clientOptions = clientOptions || {}; - - this.topology = topology; - this.sessionPool = sessionPool; - this.hasEnded = false; - this.clientOptions = clientOptions; - this[kServerSession] = undefined; - - this.supports = { - causalConsistency: - typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true - }; - - this.clusterTime = options.initialClusterTime; - - this.operationTime = null; - this.explicit = !!options.explicit; - this.owner = options.owner; - this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); - this.transaction = new Transaction(); - } - - /** - * The server id associated with this session - * @type {SessionId} - */ - get id() { - return this.serverSession.id; - } - - get serverSession() { - if (this[kServerSession] == null) { - this[kServerSession] = this.sessionPool.acquire(); - } - - return this[kServerSession]; - } - - /** - * Ends this session on the server - * - * @param {Object} [options] Optional settings. Currently reserved for future use - * @param {Function} [callback] Optional callback for completion of this operation - */ - endSession(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (this.hasEnded) { - if (typeof callback === 'function') callback(null, null); - return; - } - - if (this.serverSession && this.inTransaction()) { - this.abortTransaction(); // pass in callback? - } - - // release the server session back to the pool - this.sessionPool.release(this.serverSession); - this[kServerSession] = undefined; - - // mark the session as ended, and emit a signal - this.hasEnded = true; - this.emit('ended', this); - - // spec indicates that we should ignore all errors for `endSessions` - if (typeof callback === 'function') callback(null, null); - } - - /** - * Advances the operationTime for a ClientSession. - * - * @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to - */ - advanceOperationTime(operationTime) { - if (this.operationTime == null) { - this.operationTime = operationTime; - return; - } - - if (operationTime.greaterThan(this.operationTime)) { - this.operationTime = operationTime; - } - } - - /** - * Used to determine if this session equals another - * @param {ClientSession} session - * @return {boolean} true if the sessions are equal - */ - equals(session) { - if (!(session instanceof ClientSession)) { - return false; - } - - return this.id.id.buffer.equals(session.id.id.buffer); - } - - /** - * Increment the transaction number on the internal ServerSession - */ - incrementTransactionNumber() { - this.serverSession.txnNumber++; - } - - /** - * @returns {boolean} whether this session is currently in a transaction or not - */ - inTransaction() { - return this.transaction.isActive; - } - - /** - * Starts a new transaction with the given options. - * - * @param {TransactionOptions} options Options for the transaction - */ - startTransaction(options) { - assertAlive(this); - if (this.inTransaction()) { - throw new MongoError('Transaction already in progress'); - } - - const topologyMaxWireVersion = maxWireVersion(this.topology); - if ( - isSharded(this.topology) && - topologyMaxWireVersion != null && - topologyMaxWireVersion < minWireVersionForShardedTransactions - ) { - throw new MongoError('Transactions are not supported on sharded clusters in MongoDB < 4.2.'); - } - - // increment txnNumber - this.incrementTransactionNumber(); - - // create transaction state - this.transaction = new Transaction( - Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions) - ); - - this.transaction.transition(TxnState.STARTING_TRANSACTION); - } - - /** - * Commits the currently active transaction in this session. - * - * @param {Function} [callback] optional callback for completion of this operation - * @return {Promise} A promise is returned if no callback is provided - */ - commitTransaction(callback) { - if (typeof callback === 'function') { - endTransaction(this, 'commitTransaction', callback); - return; - } - - return new Promise((resolve, reject) => { - endTransaction(this, 'commitTransaction', (err, reply) => - err ? reject(err) : resolve(reply) - ); - }); - } - - /** - * Aborts the currently active transaction in this session. - * - * @param {Function} [callback] optional callback for completion of this operation - * @return {Promise} A promise is returned if no callback is provided - */ - abortTransaction(callback) { - if (typeof callback === 'function') { - endTransaction(this, 'abortTransaction', callback); - return; - } - - return new Promise((resolve, reject) => { - endTransaction(this, 'abortTransaction', (err, reply) => - err ? reject(err) : resolve(reply) - ); - }); - } - - /** - * This is here to ensure that ClientSession is never serialized to BSON. - * @ignore - */ - toBSON() { - throw new Error('ClientSession cannot be serialized to BSON.'); - } - - /** - * A user provided function to be run within a transaction - * - * @callback WithTransactionCallback - * @param {ClientSession} session The parent session of the transaction running the operation. This should be passed into each operation within the lambda. - * @returns {Promise} The resulting Promise of operations run within this transaction - */ - - /** - * Runs a provided lambda within a transaction, retrying either the commit operation - * or entire transaction as needed (and when the error permits) to better ensure that - * the transaction can complete successfully. - * - * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not - * return a Promise will result in undefined behavior. - * - * @param {WithTransactionCallback} fn - * @param {TransactionOptions} [options] Optional settings for the transaction - */ - withTransaction(fn, options) { - const startTime = Date.now(); - return attemptTransaction(this, startTime, fn, options); - } -} - -const MAX_WITH_TRANSACTION_TIMEOUT = 120000; -const UNSATISFIABLE_WRITE_CONCERN_CODE = 100; -const UNKNOWN_REPL_WRITE_CONCERN_CODE = 79; -const MAX_TIME_MS_EXPIRED_CODE = 50; -const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ - 'CannotSatisfyWriteConcern', - 'UnknownReplWriteConcern', - 'UnsatisfiableWriteConcern' -]); - -function hasNotTimedOut(startTime, max) { - return Date.now() - startTime < max; -} - -function isUnknownTransactionCommitResult(err) { - return ( - isMaxTimeMSExpiredError(err) || - (!NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName) && - err.code !== UNSATISFIABLE_WRITE_CONCERN_CODE && - err.code !== UNKNOWN_REPL_WRITE_CONCERN_CODE) - ); -} - -function isMaxTimeMSExpiredError(err) { - if (err == null) return false; - return ( - err.code === MAX_TIME_MS_EXPIRED_CODE || - (err.writeConcernError && err.writeConcernError.code === MAX_TIME_MS_EXPIRED_CODE) - ); -} - -function attemptTransactionCommit(session, startTime, fn, options) { - return session.commitTransaction().catch(err => { - if ( - err instanceof MongoError && - hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && - !isMaxTimeMSExpiredError(err) - ) { - if (err.hasErrorLabel('UnknownTransactionCommitResult')) { - return attemptTransactionCommit(session, startTime, fn, options); - } - - if (err.hasErrorLabel('TransientTransactionError')) { - return attemptTransaction(session, startTime, fn, options); - } - } - - throw err; - }); -} - -const USER_EXPLICIT_TXN_END_STATES = new Set([ - TxnState.NO_TRANSACTION, - TxnState.TRANSACTION_COMMITTED, - TxnState.TRANSACTION_ABORTED -]); - -function userExplicitlyEndedTransaction(session) { - return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); -} - -function attemptTransaction(session, startTime, fn, options) { - session.startTransaction(options); - - let promise; - try { - promise = fn(session); - } catch (err) { - promise = Promise.reject(err); - } - - if (!isPromiseLike(promise)) { - session.abortTransaction(); - throw new TypeError('Function provided to `withTransaction` must return a Promise'); - } - - return promise - .then(() => { - if (userExplicitlyEndedTransaction(session)) { - return; - } - - return attemptTransactionCommit(session, startTime, fn, options); - }) - .catch(err => { - function maybeRetryOrThrow(err) { - if ( - err instanceof MongoError && - err.hasErrorLabel('TransientTransactionError') && - hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) - ) { - return attemptTransaction(session, startTime, fn, options); - } - - if (isMaxTimeMSExpiredError(err)) { - if (err.errorLabels == null) { - err.errorLabels = []; - } - err.errorLabels.push('UnknownTransactionCommitResult'); - } - - throw err; - } - - if (session.transaction.isActive) { - return session.abortTransaction().then(() => maybeRetryOrThrow(err)); - } - - return maybeRetryOrThrow(err); - }); -} - -function endTransaction(session, commandName, callback) { - if (!assertAlive(session, callback)) { - // checking result in case callback was called - return; - } - - // handle any initial problematic cases - let txnState = session.transaction.state; - - if (txnState === TxnState.NO_TRANSACTION) { - callback(new MongoError('No transaction started')); - return; - } - - if (commandName === 'commitTransaction') { - if ( - txnState === TxnState.STARTING_TRANSACTION || - txnState === TxnState.TRANSACTION_COMMITTED_EMPTY - ) { - // the transaction was never started, we can safely exit here - session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); - callback(null, null); - return; - } - - if (txnState === TxnState.TRANSACTION_ABORTED) { - callback(new MongoError('Cannot call commitTransaction after calling abortTransaction')); - return; - } - } else { - if (txnState === TxnState.STARTING_TRANSACTION) { - // the transaction was never started, we can safely exit here - session.transaction.transition(TxnState.TRANSACTION_ABORTED); - callback(null, null); - return; - } - - if (txnState === TxnState.TRANSACTION_ABORTED) { - callback(new MongoError('Cannot call abortTransaction twice')); - return; - } - - if ( - txnState === TxnState.TRANSACTION_COMMITTED || - txnState === TxnState.TRANSACTION_COMMITTED_EMPTY - ) { - callback(new MongoError('Cannot call abortTransaction after calling commitTransaction')); - return; - } - } - - // construct and send the command - const command = { [commandName]: 1 }; - - // apply a writeConcern if specified - let writeConcern; - if (session.transaction.options.writeConcern) { - writeConcern = Object.assign({}, session.transaction.options.writeConcern); - } else if (session.clientOptions && session.clientOptions.w) { - writeConcern = { w: session.clientOptions.w }; - } - - if (txnState === TxnState.TRANSACTION_COMMITTED) { - writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' }); - } - - if (writeConcern) { - Object.assign(command, { writeConcern }); - } - - if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { - Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); - } - - function commandHandler(e, r) { - if (commandName === 'commitTransaction') { - session.transaction.transition(TxnState.TRANSACTION_COMMITTED); - - if ( - e && - (e instanceof MongoNetworkError || - e instanceof MongoWriteConcernError || - isRetryableError(e) || - isMaxTimeMSExpiredError(e)) - ) { - if (e.errorLabels) { - const idx = e.errorLabels.indexOf('TransientTransactionError'); - if (idx !== -1) { - e.errorLabels.splice(idx, 1); - } - } else { - e.errorLabels = []; - } - - if (isUnknownTransactionCommitResult(e)) { - e.errorLabels.push('UnknownTransactionCommitResult'); - - // per txns spec, must unpin session in this case - session.transaction.unpinServer(); - } - } - } else { - session.transaction.transition(TxnState.TRANSACTION_ABORTED); - } - - callback(e, r); - } - - // The spec indicates that we should ignore all errors on `abortTransaction` - function transactionError(err) { - return commandName === 'commitTransaction' ? err : null; - } - - if ( - // Assumption here that commandName is "commitTransaction" or "abortTransaction" - session.transaction.recoveryToken && - supportsRecoveryToken(session) - ) { - command.recoveryToken = session.transaction.recoveryToken; - } - - // send the command - session.topology.command('admin.$cmd', command, { session }, (err, reply) => { - if (err && isRetryableError(err)) { - // SPEC-1185: apply majority write concern when retrying commitTransaction - if (command.commitTransaction) { - // per txns spec, must unpin session in this case - session.transaction.unpinServer(); - - command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { - w: 'majority' - }); - } - - return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) => - commandHandler(transactionError(_err), _reply) - ); - } - - commandHandler(transactionError(err), reply); - }); -} - -function supportsRecoveryToken(session) { - const topology = session.topology; - return !!topology.s.options.useRecoveryToken; -} - -/** - * Reflects the existence of a session on the server. Can be reused by the session pool. - * WARNING: not meant to be instantiated directly. For internal use only. - * @ignore - */ -class ServerSession { - constructor() { - this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; - this.lastUse = Date.now(); - this.txnNumber = 0; - this.isDirty = false; - } - - /** - * Determines if the server session has timed out. - * @ignore - * @param {Date} sessionTimeoutMinutes The server's "logicalSessionTimeoutMinutes" - * @return {boolean} true if the session has timed out. - */ - hasTimedOut(sessionTimeoutMinutes) { - // Take the difference of the lastUse timestamp and now, which will result in a value in - // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` - const idleTimeMinutes = Math.round( - (((Date.now() - this.lastUse) % 86400000) % 3600000) / 60000 - ); - - return idleTimeMinutes > sessionTimeoutMinutes - 1; - } -} - -/** - * Maintains a pool of Server Sessions. - * For internal use only - * @ignore - */ -class ServerSessionPool { - constructor(topology) { - if (topology == null) { - throw new Error('ServerSessionPool requires a topology'); - } - - this.topology = topology; - this.sessions = []; - } - - /** - * Ends all sessions in the session pool. - * @ignore - */ - endAllPooledSessions(callback) { - if (this.sessions.length) { - this.topology.endSessions( - this.sessions.map(session => session.id), - () => { - this.sessions = []; - if (typeof callback === 'function') { - callback(); - } - } - ); - - return; - } - - if (typeof callback === 'function') { - callback(); - } - } - - /** - * Acquire a Server Session from the pool. - * Iterates through each session in the pool, removing any stale sessions - * along the way. The first non-stale session found is removed from the - * pool and returned. If no non-stale session is found, a new ServerSession - * is created. - * @ignore - * @returns {ServerSession} - */ - acquire() { - const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; - while (this.sessions.length) { - const session = this.sessions.shift(); - if (!session.hasTimedOut(sessionTimeoutMinutes)) { - return session; - } - } - - return new ServerSession(); - } - - /** - * Release a session to the session pool - * Adds the session back to the session pool if the session has not timed out yet. - * This method also removes any stale sessions from the pool. - * @ignore - * @param {ServerSession} session The session to release to the pool - */ - release(session) { - const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; - while (this.sessions.length) { - const pooledSession = this.sessions[this.sessions.length - 1]; - if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) { - this.sessions.pop(); - } else { - break; - } - } - - if (!session.hasTimedOut(sessionTimeoutMinutes)) { - if (session.isDirty) { - return; - } - - // otherwise, readd this session to the session pool - this.sessions.unshift(session); - } - } -} - -// TODO: this should be codified in command construction -// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern -function commandSupportsReadConcern(command, options) { - if ( - command.aggregate || - command.count || - command.distinct || - command.find || - command.parallelCollectionScan || - command.geoNear || - command.geoSearch - ) { - return true; - } - - if (command.mapReduce && options.out && (options.out.inline === 1 || options.out === 'inline')) { - return true; - } - - return false; -} - -/** - * Optionally decorate a command with sessions specific keys - * - * @ignore - * @param {ClientSession} session the session tracking transaction state - * @param {Object} command the command to decorate - * @param {Object} topology the topology for tracking the cluster time - * @param {Object} [options] Optional settings passed to calling operation - * @return {MongoError|null} An error, if some error condition was met - */ -function applySession(session, command, options) { - if (session.hasEnded) { - // TODO: merge this with `assertAlive`, did not want to throw a try/catch here - return new MongoError('Cannot use a session that has ended'); - } - - const serverSession = session.serverSession; - serverSession.lastUse = Date.now(); - command.lsid = serverSession.id; - - // first apply non-transaction-specific sessions data - const inTransaction = session.inTransaction() || isTransactionCommand(command); - const isRetryableWrite = options.willRetryWrite; - const shouldApplyReadConcern = commandSupportsReadConcern(command); - - if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { - command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber); - } - - // now attempt to apply transaction-specific sessions data - if (!inTransaction) { - if (session.transaction.state !== TxnState.NO_TRANSACTION) { - session.transaction.transition(TxnState.NO_TRANSACTION); - } - - // TODO: the following should only be applied to read operation per spec. - // for causal consistency - if (session.supports.causalConsistency && session.operationTime && shouldApplyReadConcern) { - command.readConcern = command.readConcern || {}; - Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); - } - - return; - } - - if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) { - return new MongoError( - `Read preference in a transaction must be primary, not: ${options.readPreference.mode}` - ); - } - - // `autocommit` must always be false to differentiate from retryable writes - command.autocommit = false; - - if (session.transaction.state === TxnState.STARTING_TRANSACTION) { - session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); - command.startTransaction = true; - - const readConcern = - session.transaction.options.readConcern || session.clientOptions.readConcern; - if (readConcern) { - command.readConcern = readConcern; - } - - if (session.supports.causalConsistency && session.operationTime) { - command.readConcern = command.readConcern || {}; - Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); - } - } -} - -function updateSessionFromResponse(session, document) { - if (document.$clusterTime) { - resolveClusterTime(session, document.$clusterTime); - } - - if (document.operationTime && session && session.supports.causalConsistency) { - session.advanceOperationTime(document.operationTime); - } - - if (document.recoveryToken && session && session.inTransaction()) { - session.transaction._recoveryToken = document.recoveryToken; - } -} - -module.exports = { - ClientSession, - ServerSession, - ServerSessionPool, - TxnState, - applySession, - updateSessionFromResponse, - commandSupportsReadConcern -}; diff --git a/node_modules/mongodb/lib/core/tools/smoke_plugin.js b/node_modules/mongodb/lib/core/tools/smoke_plugin.js deleted file mode 100644 index 22d0298..0000000 --- a/node_modules/mongodb/lib/core/tools/smoke_plugin.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -var fs = require('fs'); - -/* Note: because this plugin uses process.on('uncaughtException'), only one - * of these can exist at any given time. This plugin and anything else that - * uses process.on('uncaughtException') will conflict. */ -exports.attachToRunner = function(runner, outputFile) { - var smokeOutput = { results: [] }; - var runningTests = {}; - - var integraPlugin = { - beforeTest: function(test, callback) { - test.startTime = Date.now(); - runningTests[test.name] = test; - callback(); - }, - afterTest: function(test, callback) { - smokeOutput.results.push({ - status: test.status, - start: test.startTime, - end: Date.now(), - test_file: test.name, - exit_code: 0, - url: '' - }); - delete runningTests[test.name]; - callback(); - }, - beforeExit: function(obj, callback) { - fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { - callback(); - }); - } - }; - - // In case of exception, make sure we write file - process.on('uncaughtException', function(err) { - // Mark all currently running tests as failed - for (var testName in runningTests) { - smokeOutput.results.push({ - status: 'fail', - start: runningTests[testName].startTime, - end: Date.now(), - test_file: testName, - exit_code: 0, - url: '' - }); - } - - // write file - fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); - - // Standard NodeJS uncaught exception handler - console.error(err.stack); - process.exit(1); - }); - - runner.plugin(integraPlugin); - return integraPlugin; -}; diff --git a/node_modules/mongodb/lib/core/topologies/mongos.js b/node_modules/mongodb/lib/core/topologies/mongos.js deleted file mode 100644 index 2937193..0000000 --- a/node_modules/mongodb/lib/core/topologies/mongos.js +++ /dev/null @@ -1,1384 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const f = require('util').format; -const EventEmitter = require('events').EventEmitter; -const CoreCursor = require('../cursor').CoreCursor; -const Logger = require('../connection/logger'); -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const Server = require('./server'); -const diff = require('./shared').diff; -const cloneOptions = require('./shared').cloneOptions; -const SessionMixins = require('./shared').SessionMixins; -const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; -const relayEvents = require('../utils').relayEvents; -const isRetryableError = require('../error').isRetryableError; -const BSON = retrieveBSON(); -const getMMAPError = require('./shared').getMMAPError; -const makeClientMetadata = require('../utils').makeClientMetadata; - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - */ - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYING = 'destroying'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYING, DESTROYED, DISCONNECTED], - connecting: [CONNECTING, DESTROYING, DESTROYED, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYING, DESTROYED, UNREFERENCED], - unreferenced: [UNREFERENCED, DESTROYING, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.state = newState; - } else { - self.s.logger.error( - f( - 'Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * Creates a new Mongos instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {Mongos} A cursor instance - * @fires Mongos#connect - * @fires Mongos#reconnect - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#failed - * @fires Mongos#fullsetup - * @fires Mongos#all - * @fires Mongos#serverHeartbeatStarted - * @fires Mongos#serverHeartbeatSucceeded - * @fires Mongos#serverHeartbeatFailed - * @fires Mongos#topologyOpening - * @fires Mongos#topologyClosed - * @fires Mongos#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Mongos = function(seedlist, options) { - options = options || {}; - - // Get replSet Id - this.id = id++; - - // Internal state - this.s = { - options: Object.assign({ metadata: makeClientMetadata(options) }, options), - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // Logger instance - logger: Logger('Mongos', options), - // Seedlist - seedlist: seedlist, - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug === 'boolean' ? options.debug : false, - // localThresholdMS - localThresholdMS: options.localThresholdMS || 15 - }; - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if ( - this.s.logger.isWarn() && - this.s.options.socketTimeout !== 0 && - this.s.options.socketTimeout < this.s.haInterval - ) { - this.s.logger.warn( - f( - 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', - this.s.options.socketTimeout, - this.s.haInterval - ) - ); - } - - // Disconnected state - this.state = DISCONNECTED; - - // Current proxies we are connecting to - this.connectingProxies = []; - // Currently connected proxies - this.connectedProxies = []; - // Disconnected proxies - this.disconnectedProxies = []; - // Index of proxy to run operations against - this.index = 0; - // High availability timeout id - this.haTimeoutId = null; - // Last ismaster - this.ismaster = null; - - // Description of the Replicaset - this.topologyDescription = { - topologyType: 'Unknown', - servers: [] - }; - - // Highest clusterTime seen in responses from the current deployment - this.clusterTime = null; - - // Add event listener - EventEmitter.call(this); -}; - -inherits(Mongos, EventEmitter); -Object.assign(Mongos.prototype, SessionMixins); - -Object.defineProperty(Mongos.prototype, 'type', { - enumerable: true, - get: function() { - return 'mongos'; - } -}); - -Object.defineProperty(Mongos.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(Mongos.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - if (!this.ismaster) return null; - return this.ismaster.logicalSessionTimeoutMinutes || null; - } -}); - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -const SERVER_EVENTS = ['serverDescriptionChanged', 'error', 'close', 'timeout', 'parseError']; -function destroyServer(server, options, callback) { - options = options || {}; - SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); - server.destroy(options, callback); -} - -/** - * Initiate server connect - */ -Mongos.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - - // Set connecting state - stateTransition(this, CONNECTING); - - // Create server instances - var servers = this.s.seedlist.map(function(x) { - const server = new Server( - Object.assign({}, self.s.options, x, options, { - reconnect: false, - monitoring: false, - parent: self - }) - ); - - relayEvents(server, self, ['serverDescriptionChanged']); - return server; - }); - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - - // Start all server connections - connectProxies(self, servers); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -Mongos.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -function handleEvent(self) { - return function() { - if (self.state === DESTROYED || self.state === DESTROYING) { - return; - } - - // Move to list of disconnectedProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Emit the left signal - self.emit('left', 'mongos', this); - // Emit the sdam event - self.emit('serverClosed', { - topologyId: self.id, - address: this.name - }); - }; -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - - // Destroy the instance - if (self.state === DESTROYED) { - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - return this.destroy(); - } - - // Check the type of server - if (event === 'connect') { - // Get last known ismaster - self.ismaster = _this.lastIsMaster(); - - // Is this not a proxy, remove t - if (self.ismaster.msg === 'isdbgrid') { - // Add to the connectd list - for (let i = 0; i < self.connectedProxies.length; i++) { - if (self.connectedProxies[i].name === _this.name) { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - _this.destroy(); - return self.emit('failed', _this); - } - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Move from connecting proxies connected - moveServerFrom(self.connectingProxies, self.connectedProxies, _this); - // Emit the joined event - self.emit('joined', 'mongos', _this); - } else { - // Print warning if we did not find a mongos proxy - if (self.s.logger.isWarn()) { - var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; - // We have a standalone server - if (!self.ismaster.hosts) { - message = 'expected mongos proxy, but found standalone mongod for server %s'; - } - - self.s.logger.warn(f(message, _this.name)); - } - - // This is not a mongos proxy, destroy and remove it completely - _this.destroy(true); - removeProxyFrom(self.connectingProxies, _this); - // Emit the left event - self.emit('left', 'server', _this); - // Emit failed event - self.emit('failed', _this); - } - } else { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - // Emit the left event - self.emit('left', 'mongos', this); - // Emit failed event - self.emit('failed', this); - } - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Trigger topologyMonitor - if (self.connectingProxies.length === 0) { - // Emit connected if we are connected - if (self.connectedProxies.length > 0 && self.state === CONNECTING) { - // Set the state to connected - stateTransition(self, CONNECTED); - // Emit the connect event - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if (self.disconnectedProxies.length === 0) { - // Print warning if we did not find a mongos proxy - if (self.s.logger.isWarn()) { - self.s.logger.warn( - f('no mongos proxies found in seed list, did you mean to connect to a replicaset') - ); - } - - // Emit the error that no proxies were found - return self.emit('error', new MongoError('no mongos proxies found in seed list')); - } - - // Topology monitor - topologyMonitor(self, { firstConnect: true }); - } - }; -} - -function connectProxies(self, servers) { - // Update connectingProxies - self.connectingProxies = self.connectingProxies.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Emit opening server event - self.emit('serverOpening', { - topologyId: self.id, - address: server.name - }); - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - - // Start all the servers - servers.forEach(server => connect(server, timeoutInterval++)); -} - -function pickProxy(self, session) { - // TODO: Destructure :) - const transaction = session && session.transaction; - - if (transaction && transaction.server) { - if (transaction.server.isConnected()) { - return transaction.server; - } else { - transaction.unpinServer(); - } - } - - // Get the currently connected Proxies - var connectedProxies = self.connectedProxies.slice(0); - - // Set lower bound - var lowerBoundLatency = Number.MAX_VALUE; - - // Determine the lower bound for the Proxies - for (var i = 0; i < connectedProxies.length; i++) { - if (connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { - lowerBoundLatency = connectedProxies[i].lastIsMasterMS; - } - } - - // Filter out the possible servers - connectedProxies = connectedProxies.filter(function(server) { - if ( - server.lastIsMasterMS <= lowerBoundLatency + self.s.localThresholdMS && - server.isConnected() - ) { - return true; - } - }); - - let proxy; - - // We have no connectedProxies pick first of the connected ones - if (connectedProxies.length === 0) { - proxy = self.connectedProxies[0]; - } else { - // Get proxy - proxy = connectedProxies[self.index % connectedProxies.length]; - // Update the index - self.index = (self.index + 1) % connectedProxies.length; - } - - if (transaction && transaction.isActive && proxy && proxy.isConnected()) { - transaction.pinServer(proxy); - } - - // Return the proxy - return proxy; -} - -function moveServerFrom(from, to, proxy) { - for (var i = 0; i < from.length; i++) { - if (from[i].name === proxy.name) { - from.splice(i, 1); - } - } - - for (i = 0; i < to.length; i++) { - if (to[i].name === proxy.name) { - to.splice(i, 1); - } - } - - to.push(proxy); -} - -function removeProxyFrom(from, proxy) { - for (var i = 0; i < from.length; i++) { - if (from[i].name === proxy.name) { - from.splice(i, 1); - } - } -} - -function reconnectProxies(self, proxies, callback) { - // Count lefts - var count = proxies.length; - - // Handle events - var _handleEvent = function(self, event) { - return function() { - var _self = this; - count = count - 1; - - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - return this.destroy(); - } - - if (event === 'connect') { - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - return _self.destroy(); - } - - // Remove the handlers - for (var i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Move to the connected servers - moveServerFrom(self.connectingProxies, self.connectedProxies, _self); - // Emit topology Change - emitTopologyDescriptionChanged(self); - // Emit joined event - self.emit('joined', 'mongos', _self); - } else { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - this.destroy(); - } - - // Are we done finish up callback - if (count === 0) { - callback(); - } - }; - }; - - // No new servers - if (count === 0) { - return callback(); - } - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Create a new server instance - var server = new Server( - Object.assign({}, self.s.options, { - host: _server.name.split(':')[0], - port: parseInt(_server.name.split(':')[1], 10), - reconnect: false, - monitoring: false, - parent: self - }) - ); - - destroyServer(_server, { force: true }); - removeProxyFrom(self.disconnectedProxies, _server); - - // Relay the server description change - relayEvents(server, self, ['serverDescriptionChanged']); - - // Emit opening server event - self.emit('serverOpening', { - topologyId: server.s.topologyId !== -1 ? server.s.topologyId : self.id, - address: server.name - }); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Connect to proxy - self.connectingProxies.push(server); - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for (var i = 0; i < proxies.length; i++) { - execute(proxies[i], i); - } -} - -function topologyMonitor(self, options) { - options = options || {}; - - // no need to set up the monitor if we're already closed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Set momitoring timeout - self.haTimeoutId = setTimeout(function() { - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // If we have a primary and a disconnect handler, execute - // buffered operations - if (self.isConnected() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } - - // Get the connectingServers - var proxies = self.connectedProxies.slice(0); - // Get the count - var count = proxies.length; - - // If the count is zero schedule a new fast - function pingServer(_self, _server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); - - // Execute ismaster - _server.command( - 'admin.$cmd', - { - ismaster: true - }, - { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000 - }, - function(err, r) { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - // Move from connectingProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - _server.destroy(); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - - // We had an error, remove it from the state - if (err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: _server.name - }); - // Move from connected proxies to disconnected proxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - } else { - // Update the server ismaster - _server.ismaster = r.result; - _server.lastIsMasterMS = latencyMS; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: _server.name - }); - } - - cb(err, r); - } - ); - } - - // No proxies initiate monitor again - if (proxies.length === 0) { - // Emit close event if any listeners registered - if (self.listeners('close').length > 0 && self.state === CONNECTING) { - self.emit('error', new MongoError('no mongos proxy available')); - } else { - self.emit('close', self); - } - - // Attempt to connect to any unknown servers - return reconnectProxies(self, self.disconnectedProxies, function() { - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Are we connected ? emit connect event - if (self.state === CONNECTING && options.firstConnect) { - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if (self.isConnected()) { - self.emit('reconnect', self); - } else if (!self.isConnected() && self.listeners('close').length > 0) { - self.emit('close', self); - } - - // Perform topology monitor - topologyMonitor(self); - }); - } - - // Ping all servers - for (var i = 0; i < proxies.length; i++) { - pingServer(self, proxies[i], function() { - count = count - 1; - - if (count === 0) { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - return; - } - - // Attempt to connect to any unknown servers - reconnectProxies(self, self.disconnectedProxies, function() { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - return; - } - - // Perform topology monitor - topologyMonitor(self); - }); - } - }); - } - }, self.s.haInterval); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Mongos.prototype.lastIsMaster = function() { - return this.ismaster; -}; - -/** - * Unref all connections belong to this server - * @method - */ -Mongos.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - // Get all proxies - var proxies = this.connectedProxies.concat(this.connectingProxies); - proxies.forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -}; - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -Mongos.prototype.destroy = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - - stateTransition(this, DESTROYING); - if (this.haTimeoutId) { - clearTimeout(this.haTimeoutId); - } - - const proxies = this.connectedProxies.concat(this.connectingProxies); - let serverCount = proxies.length; - const serverDestroyed = () => { - serverCount--; - if (serverCount > 0) { - return; - } - - emitTopologyDescriptionChanged(this); - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); - stateTransition(this, DESTROYED); - if (typeof callback === 'function') { - callback(null, null); - } - }; - - if (serverCount === 0) { - serverDestroyed(); - return; - } - - // Destroy all connecting servers - proxies.forEach(server => { - // Emit the sdam event - this.emit('serverClosed', { - topologyId: this.id, - address: server.name - }); - - destroyServer(server, options, serverDestroyed); - moveServerFrom(this.connectedProxies, this.disconnectedProxies, server); - }); -}; - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Mongos.prototype.isConnected = function() { - return this.connectedProxies.length > 0; -}; - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Mongos.prototype.isDestroyed = function() { - return this.state === DESTROYED; -}; - -// -// Operations -// - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const self = args.self; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - // Pick a server - let server = pickProxy(self, options.session); - // No server found error out - if (!server) return callback(new MongoError('no mongos proxy available')); - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction(); - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err) || !willRetryWrite) { - err = getMMAPError(err); - return callback(err); - } - - // Pick another server - server = pickProxy(self, options.session); - - // No server found error out with original error - if (!server) { - return callback(err); - } - - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // rerun the operation - server[op](ns, ops, options, handler); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.insert = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.update = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.remove = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); -}; - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; - -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.command = function(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - var self = this; - - // Pick a proxy - var server = pickProxy(self, options.session); - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if ((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // No server returned we had an error - if (server == null) { - return callback(new MongoError('no mongos proxy available')); - } - - // Cloned options - var clonedOptions = cloneOptions(options); - clonedOptions.topology = self; - - const willRetryWrite = - !options.retrying && - options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, clonedOptions, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // Execute the command - server.command(ns, cmd, clonedOptions, cb); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -Mongos.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * Selects a server - * - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Unused - * @param {ClientSession} [options.session] Specify a session if it is being used - * @param {function} callback - */ -Mongos.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') - (callback = options), (options = selector), (selector = undefined); - options = options || {}; - - const server = pickProxy(this, options.session); - if (server == null) { - callback(new MongoError('server selection failed')); - return; - } - - if (this.s.debug) this.emit('pickedServer', null, server); - callback(null, server); -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Mongos.prototype.connections = function() { - var connections = []; - - for (var i = 0; i < this.connectedProxies.length; i++) { - connections = connections.concat(this.connectedProxies[i].connections()); - } - - return connections; -}; - -function emitTopologyDescriptionChanged(self) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - if (self.connectedProxies.length > 0) { - topology = 'Sharded'; - } - - // Generate description - var description = { - topologyType: topology, - servers: [] - }; - - // All proxies - var proxies = self.disconnectedProxies.concat(self.connectingProxies); - - // Add all the disconnected proxies - description.servers = description.servers.concat( - proxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Unknown'; - return description; - }) - ); - - // Add all the connected proxies - description.servers = description.servers.concat( - self.connectedProxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Mongos'; - return description; - }) - ); - - // Get the diff - var diffResult = diff(self.topologyDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.topologyDescription, - newDescription: description, - diff: diffResult - }; - - // Emit the topologyDescription change - if (diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - } - - // Set the new description - self.topologyDescription = description; - } -} - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * A mongos reconnect event, used to verify that the mongos topology has reconnected - * - * @event Mongos#reconnect - * @type {Mongos} - */ - -/** - * A mongos fullsetup event, used to signal that all topology members have been contacted. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * A mongos all event, used to signal that all topology members have been contacted. - * - * @event Mongos#all - * @type {Mongos} - */ - -/** - * A server member left the mongos list - * - * @event Mongos#left - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos list - * - * @event Mongos#joined - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that joined - */ - -/** - * A server opening SDAM monitoring event - * - * @event Mongos#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Mongos#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Mongos#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Mongos#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Mongos#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Mongos#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event Mongos#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event Mongos#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event Mongos#serverHeartbeatSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Mongos#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Mongos#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Mongos#commandFailed - * @type {object} - */ - -module.exports = Mongos; diff --git a/node_modules/mongodb/lib/core/topologies/read_preference.js b/node_modules/mongodb/lib/core/topologies/read_preference.js deleted file mode 100644 index a813ec4..0000000 --- a/node_modules/mongodb/lib/core/topologies/read_preference.js +++ /dev/null @@ -1,202 +0,0 @@ -'use strict'; - -/** - * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is - * used to construct connections. - * @class - * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) - * @param {array} tags The tags object - * @param {object} [options] Additional read preference options - * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds. - * @see https://docs.mongodb.com/manual/core/read-preference/ - * @return {ReadPreference} - */ -const ReadPreference = function(mode, tags, options) { - if (!ReadPreference.isValid(mode)) { - throw new TypeError(`Invalid read preference mode ${mode}`); - } - - // TODO(major): tags MUST be an array of tagsets - if (tags && !Array.isArray(tags)) { - console.warn( - 'ReadPreference tags must be an array, this will change in the next major version' - ); - - if (typeof tags.maxStalenessSeconds !== 'undefined') { - // this is likely an options object - options = tags; - tags = undefined; - } else { - tags = [tags]; - } - } - - this.mode = mode; - this.tags = tags; - - options = options || {}; - if (options.maxStalenessSeconds != null) { - if (options.maxStalenessSeconds <= 0) { - throw new TypeError('maxStalenessSeconds must be a positive integer'); - } - - this.maxStalenessSeconds = options.maxStalenessSeconds; - - // NOTE: The minimum required wire version is 5 for this read preference. If the existing - // topology has a lower value then a MongoError will be thrown during server selection. - this.minWireVersion = 5; - } - - if (this.mode === ReadPreference.PRIMARY) { - if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { - throw new TypeError('Primary read preference cannot be combined with tags'); - } - - if (this.maxStalenessSeconds) { - throw new TypeError('Primary read preference cannot be combined with maxStalenessSeconds'); - } - } -}; - -// Support the deprecated `preference` property introduced in the porcelain layer -Object.defineProperty(ReadPreference.prototype, 'preference', { - enumerable: true, - get: function() { - return this.mode; - } -}); - -/* - * Read preference mode constants - */ -ReadPreference.PRIMARY = 'primary'; -ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; -ReadPreference.SECONDARY = 'secondary'; -ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; -ReadPreference.NEAREST = 'nearest'; - -const VALID_MODES = [ - ReadPreference.PRIMARY, - ReadPreference.PRIMARY_PREFERRED, - ReadPreference.SECONDARY, - ReadPreference.SECONDARY_PREFERRED, - ReadPreference.NEAREST, - null -]; - -/** - * Construct a ReadPreference given an options object. - * - * @param {object} options The options object from which to extract the read preference. - * @return {ReadPreference} - */ -ReadPreference.fromOptions = function(options) { - const readPreference = options.readPreference; - const readPreferenceTags = options.readPreferenceTags; - - if (readPreference == null) { - return null; - } - - if (typeof readPreference === 'string') { - return new ReadPreference(readPreference, readPreferenceTags); - } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { - const mode = readPreference.mode || readPreference.preference; - if (mode && typeof mode === 'string') { - return new ReadPreference(mode, readPreference.tags, { - maxStalenessSeconds: readPreference.maxStalenessSeconds - }); - } - } - - return readPreference; -}; - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} True if a mode is valid - */ -ReadPreference.isValid = function(mode) { - return VALID_MODES.indexOf(mode) !== -1; -}; - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} True if a mode is valid - */ -ReadPreference.prototype.isValid = function(mode) { - return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); -}; - -const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; - -/** - * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire - * @method - * @return {boolean} - * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query - */ -ReadPreference.prototype.slaveOk = function() { - return needSlaveOk.indexOf(this.mode) !== -1; -}; - -/** - * Are the two read preference equal - * @method - * @param {ReadPreference} readPreference The read preference with which to check equality - * @return {boolean} True if the two ReadPreferences are equivalent - */ -ReadPreference.prototype.equals = function(readPreference) { - return readPreference.mode === this.mode; -}; - -/** - * Return JSON representation - * @method - * @return {Object} A JSON representation of the ReadPreference - */ -ReadPreference.prototype.toJSON = function() { - const readPreference = { mode: this.mode }; - if (Array.isArray(this.tags)) readPreference.tags = this.tags; - if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; - return readPreference; -}; - -/** - * Primary read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.primary = new ReadPreference('primary'); -/** - * Primary Preferred read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); -/** - * Secondary read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.secondary = new ReadPreference('secondary'); -/** - * Secondary Preferred read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); -/** - * Nearest read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.nearest = new ReadPreference('nearest'); - -module.exports = ReadPreference; diff --git a/node_modules/mongodb/lib/core/topologies/replset.js b/node_modules/mongodb/lib/core/topologies/replset.js deleted file mode 100644 index b289d59..0000000 --- a/node_modules/mongodb/lib/core/topologies/replset.js +++ /dev/null @@ -1,1559 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const f = require('util').format; -const EventEmitter = require('events').EventEmitter; -const ReadPreference = require('./read_preference'); -const CoreCursor = require('../cursor').CoreCursor; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const Logger = require('../connection/logger'); -const MongoError = require('../error').MongoError; -const Server = require('./server'); -const ReplSetState = require('./replset_state'); -const Timeout = require('./shared').Timeout; -const Interval = require('./shared').Interval; -const SessionMixins = require('./shared').SessionMixins; -const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; -const relayEvents = require('../utils').relayEvents; -const isRetryableError = require('../error').isRetryableError; -const BSON = retrieveBSON(); -const calculateDurationInMs = require('../utils').calculateDurationInMs; -const getMMAPError = require('./shared').getMMAPError; -const makeClientMetadata = require('../utils').makeClientMetadata; - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYED, DISCONNECTED], - connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], - unreferenced: [UNREFERENCED, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.state = newState; - } else { - self.s.logger.error( - f( - 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * Creates a new Replset instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {boolean} options.setName The Replicaset set name - * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {boolean} [options.emitError=false] Server will emit errors events - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers - * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {ReplSet} A cursor instance - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#failed - * @fires ReplSet#fullsetup - * @fires ReplSet#all - * @fires ReplSet#error - * @fires ReplSet#serverHeartbeatStarted - * @fires ReplSet#serverHeartbeatSucceeded - * @fires ReplSet#serverHeartbeatFailed - * @fires ReplSet#topologyOpening - * @fires ReplSet#topologyClosed - * @fires ReplSet#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var ReplSet = function(seedlist, options) { - var self = this; - options = options || {}; - - // Validate seedlist - if (!Array.isArray(seedlist)) throw new MongoError('seedlist must be an array'); - // Validate list - if (seedlist.length === 0) throw new MongoError('seedlist must contain at least one entry'); - // Validate entries - seedlist.forEach(function(e) { - if (typeof e.host !== 'string' || typeof e.port !== 'number') - throw new MongoError('seedlist entry must contain a host and port'); - }); - - // Add event listener - EventEmitter.call(this); - - // Get replSet Id - this.id = id++; - - // Get the localThresholdMS - var localThresholdMS = options.localThresholdMS || 15; - // Backward compatibility - if (options.acceptableLatency) localThresholdMS = options.acceptableLatency; - - // Create a logger - var logger = Logger('ReplSet', options); - - // Internal state - this.s = { - options: Object.assign({ metadata: makeClientMetadata(options) }, options), - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // Logger instance - logger: logger, - // Seedlist - seedlist: seedlist, - // Replicaset state - replicaSetState: new ReplSetState({ - id: this.id, - setName: options.setName, - acceptableLatency: localThresholdMS, - heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, - logger: logger - }), - // Current servers we are connecting to - connectingServers: [], - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Minimum heartbeat frequency used if we detect a server close - minHeartbeatFrequencyMS: 500, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug === 'boolean' ? options.debug : false - }; - - // Add handler for topology change - this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { - self.emit('topologyDescriptionChanged', r); - }); - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if ( - this.s.logger.isWarn() && - this.s.options.socketTimeout !== 0 && - this.s.options.socketTimeout < this.s.haInterval - ) { - this.s.logger.warn( - f( - 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', - this.s.options.socketTimeout, - this.s.haInterval - ) - ); - } - - // Add forwarding of events from state handler - var types = ['joined', 'left']; - types.forEach(function(x) { - self.s.replicaSetState.on(x, function(t, s) { - self.emit(x, t, s); - }); - }); - - // Connect stat - this.initialConnectState = { - connect: false, - fullsetup: false, - all: false - }; - - // Disconnected state - this.state = DISCONNECTED; - this.haTimeoutId = null; - // Last ismaster - this.ismaster = null; - // Contains the intervalId - this.intervalIds = []; - - // Highest clusterTime seen in responses from the current deployment - this.clusterTime = null; -}; - -inherits(ReplSet, EventEmitter); -Object.assign(ReplSet.prototype, SessionMixins); - -Object.defineProperty(ReplSet.prototype, 'type', { - enumerable: true, - get: function() { - return 'replset'; - } -}); - -Object.defineProperty(ReplSet.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - return this.s.replicaSetState.logicalSessionTimeoutMinutes || null; - } -}); - -function rexecuteOperations(self) { - // If we have a primary and a disconnect handler, execute - // buffered operations - if (self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } else if (self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executePrimary: true }); - } else if (self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executeSecondary: true }); - } -} - -function connectNewServers(self, servers, callback) { - // No new servers - if (servers.length === 0) { - return callback(); - } - - // Count lefts - var count = servers.length; - var error = null; - - function done() { - count = count - 1; - if (count === 0) { - callback(error); - } - } - - // Handle events - var _handleEvent = function(self, event) { - return function(err) { - var _self = this; - - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - this.destroy({ force: true }); - return done(); - } - - if (event === 'connect') { - // Update the state - var result = self.s.replicaSetState.update(_self); - // Update the state with the new server - if (result) { - // Primary lastIsMaster store it - if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) { - self.ismaster = _self.lastIsMaster(); - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Enalbe the monitoring of the new server - monitorServer(_self.lastIsMaster().me, self, {}); - - // Rexecute any stalled operation - rexecuteOperations(self); - } else { - _self.destroy({ force: true }); - } - } else if (event === 'error') { - error = err; - } - - // Rexecute any stalled operation - rexecuteOperations(self); - done(); - }; - }; - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - // remove existing connecting server if it's failed to connect, otherwise - // wait for that server to connect - const existingServerIdx = self.s.connectingServers.findIndex(s => s.name === _server); - if (existingServerIdx >= 0) { - const connectingServer = self.s.connectingServers[existingServerIdx]; - connectingServer.destroy({ force: true }); - - self.s.connectingServers.splice(existingServerIdx, 1); - return done(); - } - - // Create a new server instance - var server = new Server( - Object.assign({}, self.s.options, { - host: _server.split(':')[0], - port: parseInt(_server.split(':')[1], 10), - reconnect: false, - monitoring: false, - parent: self - }) - ); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // SDAM Monitoring events - server.on('serverOpening', e => self.emit('serverOpening', e)); - server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); - server.on('serverClosed', e => self.emit('serverClosed', e)); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - self.s.connectingServers.push(server); - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for (var i = 0; i < servers.length; i++) { - execute(servers[i], i); - } -} - -// Ping the server -var pingServer = function(self, server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); - - // Execute ismaster - // Set the socketTimeout for a monitoring message to a low number - // Ensuring ismaster calls are timed out quickly - server.command( - 'admin.$cmd', - { - ismaster: true - }, - { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000 - }, - function(err, r) { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - server.destroy({ force: true }); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - - // Set the last updatedTime - var hrtime = process.hrtime(); - server.lastUpdateTime = (hrtime[0] * 1e9 + hrtime[1]) / 1e6; - - // We had an error, remove it from the state - if (err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: server.name - }); - - // Remove server from the state - self.s.replicaSetState.remove(server); - } else { - // Update the server ismaster - server.ismaster = r.result; - - // Check if we have a lastWriteDate convert it to MS - // and store on the server instance for later use - if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { - server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); - } - - // Do we have a brand new server - if (server.lastIsMasterMS === -1) { - server.lastIsMasterMS = latencyMS; - } else if (server.lastIsMasterMS) { - // After the first measurement, average RTT MUST be computed using an - // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. - // If the prior average is denoted old_rtt, then the new average (new_rtt) is - // computed from a new RTT measurement (x) using the following formula: - // alpha = 0.2 - // new_rtt = alpha * x + (1 - alpha) * old_rtt - server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; - } - - if (self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if (server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: server.name - }); - } - - // Calculate the staleness for this server - self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); - - // Callback - cb(err, r); - } - ); -}; - -// Each server is monitored in parallel in their own timeout loop -var monitorServer = function(host, self, options) { - // If this is not the initial scan - // Is this server already being monitoried, then skip monitoring - if (!options.haInterval) { - for (var i = 0; i < self.intervalIds.length; i++) { - if (self.intervalIds[i].__host === host) { - return; - } - } - } - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - // Create the interval - var intervalId = new _process(function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - // clearInterval(intervalId); - intervalId.stop(); - return; - } - - // Do we already have server connection available for this host - var _server = self.s.replicaSetState.get(host); - - // Check if we have a known server connection and reuse - if (_server) { - // Ping the server - return pingServer(self, _server, function(err) { - if (err) { - // NOTE: should something happen here? - return; - } - - if (self.state === DESTROYED || self.state === UNREFERENCED) { - intervalId.stop(); - return; - } - - // Filter out all called intervaliIds - self.intervalIds = self.intervalIds.filter(function(intervalId) { - return intervalId.isRunning(); - }); - - // Initial sweep - if (_process === Timeout) { - if ( - self.state === CONNECTING && - ((self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed) || - self.s.replicaSetState.hasPrimary()) - ) { - self.state = CONNECTED; - - // Emit connected sign - process.nextTick(function() { - self.emit('connect', self); - }); - - // Start topology interval check - topologyMonitor(self, {}); - } - } else { - if ( - self.state === DISCONNECTED && - ((self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed) || - self.s.replicaSetState.hasPrimary()) - ) { - self.state = CONNECTED; - - // Rexecute any stalled operation - rexecuteOperations(self); - - // Emit connected sign - process.nextTick(function() { - self.emit('reconnect', self); - }); - } - } - - if ( - self.initialConnectState.connect && - !self.initialConnectState.fullsetup && - self.s.replicaSetState.hasPrimaryAndSecondary() - ) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - }); - } - }, _haInterval); - - // Start the interval - intervalId.start(); - // Add the intervalId host name - intervalId.__host = host; - // Add the intervalId to our list of intervalIds - self.intervalIds.push(intervalId); -}; - -function topologyMonitor(self, options) { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - options = options || {}; - - // Get the servers - var servers = Object.keys(self.s.replicaSetState.set); - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - if (_process === Timeout) { - return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) { - // Don't emit errors if the connection was already - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { - if (err) { - return self.emit('error', err); - } - - self.emit( - 'error', - new MongoError('no primary found in replicaset or invalid replica set name') - ); - return self.destroy({ force: true }); - } else if ( - !self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed - ) { - if (err) { - return self.emit('error', err); - } - - self.emit( - 'error', - new MongoError('no secondary found in replicaset or invalid replica set name') - ); - return self.destroy({ force: true }); - } - - for (var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - }); - } else { - for (var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - } - - // Run the reconnect process - function executeReconnect(self) { - return function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - connectNewServers(self, self.s.replicaSetState.unknownServers, function() { - var monitoringFrequencey = self.s.replicaSetState.hasPrimary() - ? _haInterval - : self.s.minHeartbeatFrequencyMS; - - // Create a timeout - self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); - }); - }; - } - - // Decide what kind of interval to use - var intervalTime = !self.s.replicaSetState.hasPrimary() - ? self.s.minHeartbeatFrequencyMS - : _haInterval; - - self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start()); -} - -function addServerToList(list, server) { - for (var i = 0; i < list.length; i++) { - if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true; - } - - list.push(server); -} - -function handleEvent(self, event) { - return function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id) - ); - } - - // Remove from the replicaset state - self.s.replicaSetState.remove(this); - - // Are we in a destroyed state return - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - - // If no primary and secondary available - if ( - !self.s.replicaSetState.hasPrimary() && - !self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed - ) { - stateTransition(self, DISCONNECTED); - } else if (!self.s.replicaSetState.hasPrimary()) { - stateTransition(self, DISCONNECTED); - } - - addServerToList(self.s.connectingServers, this); - }; -} - -function shouldTriggerConnect(self) { - const isConnecting = self.state === CONNECTING; - const hasPrimary = self.s.replicaSetState.hasPrimary(); - const hasSecondary = self.s.replicaSetState.hasSecondary(); - const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed; - const readPreferenceSecondary = - self.s.connectOptions.readPreference && - self.s.connectOptions.readPreference.equals(ReadPreference.secondary); - - return ( - (isConnecting && - ((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) || - (hasSecondary && secondaryOnlyConnectionAllowed) - ); -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f( - 'handleInitialConnectEvent %s from server %s in replset with id %s', - event, - this.name, - self.id - ) - ); - } - - // Destroy the instance - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return this.destroy({ force: true }); - } - - // Check the type of server - if (event === 'connect') { - // Update the state - var result = self.s.replicaSetState.update(_this); - if (result === true) { - // Primary lastIsMaster store it - if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) { - self.ismaster = _this.lastIsMaster(); - } - - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f( - 'handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', - event, - _this.name, - self.id, - JSON.stringify(self.s.replicaSetState.set) - ) - ); - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Do we have a primary or primaryAndSecondary - if (shouldTriggerConnect(self)) { - // We are connected - self.state = CONNECTED; - - // Set initial connect state - self.initialConnectState.connect = true; - // Emit connect event - process.nextTick(function() { - self.emit('connect', self); - }); - - topologyMonitor(self, {}); - } - } else if (result instanceof MongoError) { - _this.destroy({ force: true }); - self.destroy({ force: true }); - return self.emit('error', result); - } else { - _this.destroy({ force: true }); - } - } else { - // Emit failure to connect - self.emit('failed', this); - - addServerToList(self.s.connectingServers, this); - // Remove from the state - self.s.replicaSetState.remove(this); - } - - if ( - self.initialConnectState.connect && - !self.initialConnectState.fullsetup && - self.s.replicaSetState.hasPrimaryAndSecondary() - ) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - - // Remove from the list from connectingServers - for (var i = 0; i < self.s.connectingServers.length; i++) { - if (self.s.connectingServers[i].equals(this)) { - self.s.connectingServers.splice(i, 1); - } - } - - // Trigger topologyMonitor - if (self.s.connectingServers.length === 0 && self.state === CONNECTING) { - topologyMonitor(self, { haInterval: 1 }); - } - }; -} - -function connectServers(self, servers) { - // Update connectingServers - self.s.connectingServers = self.s.connectingServers.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Add the server to the state - if (self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if (server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - - // SDAM Monitoring events - server.on('serverOpening', e => self.emit('serverOpening', e)); - server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); - server.on('serverClosed', e => self.emit('serverClosed', e)); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - - // Start all the servers - while (servers.length > 0) { - connect(servers.shift(), timeoutInterval++); - } -} - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -/** - * Initiate server connect - */ -ReplSet.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - - // Set connecting state - stateTransition(this, CONNECTING); - - // Create server instances - var servers = this.s.seedlist.map(function(x) { - return new Server( - Object.assign({}, self.s.options, x, options, { - reconnect: false, - monitoring: false, - parent: self - }) - ); - }); - - // Error out as high availbility interval must be < than socketTimeout - if ( - this.s.options.socketTimeout > 0 && - this.s.options.socketTimeout <= this.s.options.haInterval - ) { - return self.emit( - 'error', - new MongoError( - f( - 'haInterval [%s] MS must be set to less than socketTimeout [%s] MS', - this.s.options.haInterval, - this.s.options.socketTimeout - ) - ) - ); - } - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - // Start all server connections - connectServers(self, servers); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -ReplSet.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -ReplSet.prototype.destroy = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - - let destroyCount = this.s.connectingServers.length + 1; // +1 for the callback from `replicaSetState.destroy` - const serverDestroyed = () => { - destroyCount--; - if (destroyCount > 0) { - return; - } - - // Emit toplogy closing event - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); - - // Transition state - stateTransition(this, DESTROYED); - - if (typeof callback === 'function') { - callback(null, null); - } - }; - - // Clear out any monitoring process - if (this.haTimeoutId) clearTimeout(this.haTimeoutId); - - // Clear out all monitoring - for (var i = 0; i < this.intervalIds.length; i++) { - this.intervalIds[i].stop(); - } - - // Reset list of intervalIds - this.intervalIds = []; - - if (destroyCount === 0) { - serverDestroyed(); - return; - } - - // Destroy the replicaset - this.s.replicaSetState.destroy(options, serverDestroyed); - - // Destroy all connecting servers - this.s.connectingServers.forEach(function(x) { - x.destroy(options, serverDestroyed); - }); -}; - -/** - * Unref all connections belong to this server - * @method - */ -ReplSet.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - - this.s.replicaSetState.allServers().forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -}; - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -ReplSet.prototype.lastIsMaster = function() { - // If secondaryOnlyConnectionAllowed and no primary but secondary - // return the secondaries ismaster result. - if ( - this.s.options.secondaryOnlyConnectionAllowed && - !this.s.replicaSetState.hasPrimary() && - this.s.replicaSetState.hasSecondary() - ) { - return this.s.replicaSetState.secondaries[0].lastIsMaster(); - } - - return this.s.replicaSetState.primary - ? this.s.replicaSetState.primary.lastIsMaster() - : this.ismaster; -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -ReplSet.prototype.connections = function() { - var servers = this.s.replicaSetState.allServers(); - var connections = []; - for (var i = 0; i < servers.length; i++) { - connections = connections.concat(servers[i].connections()); - } - - return connections; -}; - -/** - * Figure out if the server is connected - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {boolean} - */ -ReplSet.prototype.isConnected = function(options) { - options = options || {}; - - // If we specified a read preference check if we are connected to something - // than can satisfy this - if (options.readPreference && options.readPreference.equals(ReadPreference.secondary)) { - return this.s.replicaSetState.hasSecondary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.primary)) { - return this.s.replicaSetState.hasPrimary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.primaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.secondaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if (this.s.options.secondaryOnlyConnectionAllowed && this.s.replicaSetState.hasSecondary()) { - return true; - } - - return this.s.replicaSetState.hasPrimary(); -}; - -/** - * Figure out if the replicaset instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -ReplSet.prototype.isDestroyed = function() { - return this.state === DESTROYED; -}; - -const SERVER_SELECTION_TIMEOUT_MS = 10000; // hardcoded `serverSelectionTimeoutMS` for legacy topology -const SERVER_SELECTION_INTERVAL_MS = 1000; // time to wait between selection attempts -/** - * Selects a server - * - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {ClientSession} [options.session] Unused - * @param {function} callback - */ -ReplSet.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') (callback = options), (options = selector); - options = options || {}; - - let readPreference; - if (selector instanceof ReadPreference) { - readPreference = selector; - } else { - readPreference = options.readPreference || ReadPreference.primary; - } - - let lastError; - const start = process.hrtime(); - const _selectServer = () => { - if (calculateDurationInMs(start) >= SERVER_SELECTION_TIMEOUT_MS) { - if (lastError != null) { - callback(lastError, null); - } else { - callback(new MongoError('Server selection timed out')); - } - - return; - } - - const server = this.s.replicaSetState.pickServer(readPreference); - if (server == null) { - setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); - return; - } - - if (!(server instanceof Server)) { - lastError = server; - setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); - return; - } - - if (this.s.debug) this.emit('pickedServer', options.readPreference, server); - callback(null, server); - }; - - _selectServer(); -}; - -/** - * Get all connected servers - * @method - * @return {Server[]} - */ -ReplSet.prototype.getServers = function() { - return this.s.replicaSetState.allServers(); -}; - -// -// Execute write operation -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const self = args.self; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - if (self.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction(); - - if (!self.s.replicaSetState.hasPrimary()) { - if (self.s.disconnectHandler) { - // Not connected but we have a disconnecthandler - return self.s.disconnectHandler.add(op, ns, ops, options, callback); - } else if (!willRetryWrite) { - // No server returned we had an error - return callback(new MongoError('no primary server found')); - } - } - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - err = getMMAPError(err); - return callback(err); - } - - if (willRetryWrite) { - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - } - - // Per SDAM, remove primary from replicaset - if (self.s.replicaSetState.primary) { - self.s.replicaSetState.primary.destroy(); - self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); - } - - return callback(err); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - self.s.replicaSetState.primary[op](ns, ops, options, handler); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.insert = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.update = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.remove = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); -}; - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; - -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.command = function(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - var self = this; - - // Establish readPreference - var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; - - // If the readPreference is primary and we have no primary, store it - if ( - readPreference.preference === 'primary' && - !this.s.replicaSetState.hasPrimary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if ( - readPreference.preference === 'secondary' && - !this.s.replicaSetState.hasSecondary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if ( - readPreference.preference !== 'primary' && - !this.s.replicaSetState.hasSecondary() && - !this.s.replicaSetState.hasPrimary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // Pick a server - var server = this.s.replicaSetState.pickServer(readPreference); - // We received an error, return it - if (!(server instanceof Server)) return callback(server); - // Emit debug event - if (self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); - - // No server returned we had an error - if (server == null) { - return callback( - new MongoError( - f('no server found that matches the provided readPreference %s', readPreference) - ) - ); - } - - const willRetryWrite = - !options.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, options, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - // Per SDAM, remove primary from replicaset - if (this.s.replicaSetState.primary) { - this.s.replicaSetState.primary.destroy(); - this.s.replicaSetState.remove(this.s.replicaSetState.primary, { force: true }); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // Execute the command - server.command(ns, cmd, options, cb); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -ReplSet.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * A replset reconnect event, used to verify that the topology reconnected - * - * @event ReplSet#reconnect - * @type {ReplSet} - */ - -/** - * A replset fullsetup event, used to signal that all topology members have been contacted. - * - * @event ReplSet#fullsetup - * @type {ReplSet} - */ - -/** - * A replset all event, used to signal that all topology members have been contacted. - * - * @event ReplSet#all - * @type {ReplSet} - */ - -/** - * A replset failed event, used to signal that initial replset connection failed. - * - * @event ReplSet#failed - * @type {ReplSet} - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * A server opening SDAM monitoring event - * - * @event ReplSet#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event ReplSet#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event ReplSet#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event ReplSet#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event ReplSet#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event ReplSet#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event ReplSet#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event ReplSet#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event ReplSet#serverHeartbeatSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event ReplSet#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event ReplSet#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event ReplSet#commandFailed - * @type {object} - */ - -module.exports = ReplSet; diff --git a/node_modules/mongodb/lib/core/topologies/replset_state.js b/node_modules/mongodb/lib/core/topologies/replset_state.js deleted file mode 100644 index 24c16d6..0000000 --- a/node_modules/mongodb/lib/core/topologies/replset_state.js +++ /dev/null @@ -1,1121 +0,0 @@ -'use strict'; - -var inherits = require('util').inherits, - f = require('util').format, - diff = require('./shared').diff, - EventEmitter = require('events').EventEmitter, - Logger = require('../connection/logger'), - ReadPreference = require('./read_preference'), - MongoError = require('../error').MongoError, - Buffer = require('safe-buffer').Buffer; - -var TopologyType = { - Single: 'Single', - ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', - ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', - Sharded: 'Sharded', - Unknown: 'Unknown' -}; - -var ServerType = { - Standalone: 'Standalone', - Mongos: 'Mongos', - PossiblePrimary: 'PossiblePrimary', - RSPrimary: 'RSPrimary', - RSSecondary: 'RSSecondary', - RSArbiter: 'RSArbiter', - RSOther: 'RSOther', - RSGhost: 'RSGhost', - Unknown: 'Unknown' -}; - -var ReplSetState = function(options) { - options = options || {}; - // Add event listener - EventEmitter.call(this); - // Topology state - this.topologyType = TopologyType.ReplicaSetNoPrimary; - this.setName = options.setName; - - // Server set - this.set = {}; - - // Unpacked options - this.id = options.id; - this.setName = options.setName; - - // Replicaset logger - this.logger = options.logger || Logger('ReplSet', options); - - // Server selection index - this.index = 0; - // Acceptable latency - this.acceptableLatency = options.acceptableLatency || 15; - - // heartbeatFrequencyMS - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - - // Server side - this.primary = null; - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - // Current unknown hosts - this.unknownServers = []; - // In set status - this.set = {}; - // Status - this.maxElectionId = null; - this.maxSetVersion = 0; - // Description of the Replicaset - this.replicasetDescription = { - topologyType: 'Unknown', - servers: [] - }; - - this.logicalSessionTimeoutMinutes = undefined; -}; - -inherits(ReplSetState, EventEmitter); - -ReplSetState.prototype.hasPrimaryAndSecondary = function() { - return this.primary != null && this.secondaries.length > 0; -}; - -ReplSetState.prototype.hasPrimaryOrSecondary = function() { - return this.hasPrimary() || this.hasSecondary(); -}; - -ReplSetState.prototype.hasPrimary = function() { - return this.primary != null; -}; - -ReplSetState.prototype.hasSecondary = function() { - return this.secondaries.length > 0; -}; - -ReplSetState.prototype.get = function(host) { - var servers = this.allServers(); - - for (var i = 0; i < servers.length; i++) { - if (servers[i].name.toLowerCase() === host.toLowerCase()) { - return servers[i]; - } - } - - return null; -}; - -ReplSetState.prototype.allServers = function(options) { - options = options || {}; - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - if (!options.ignoreArbiters) servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - return servers; -}; - -ReplSetState.prototype.destroy = function(options, callback) { - const serversToDestroy = this.secondaries - .concat(this.arbiters) - .concat(this.passives) - .concat(this.ghosts); - if (this.primary) serversToDestroy.push(this.primary); - - let serverCount = serversToDestroy.length; - const serverDestroyed = () => { - serverCount--; - if (serverCount > 0) { - return; - } - - // Clear out the complete state - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - this.unknownServers = []; - this.set = {}; - this.primary = null; - - // Emit the topology changed - emitTopologyDescriptionChanged(this); - - if (typeof callback === 'function') { - callback(null, null); - } - }; - - if (serverCount === 0) { - serverDestroyed(); - return; - } - - serversToDestroy.forEach(server => server.destroy(options, serverDestroyed)); -}; - -ReplSetState.prototype.remove = function(server, options) { - options = options || {}; - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // Only remove if the current server is not connected - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - - // Check if it's active and this is just a failed connection attempt - for (var i = 0; i < servers.length; i++) { - if ( - !options.force && - servers[i].equals(server) && - servers[i].isConnected && - servers[i].isConnected() - ) { - return; - } - } - - // If we have it in the set remove it - if (this.set[serverName]) { - this.set[serverName].type = ServerType.Unknown; - this.set[serverName].electionId = null; - this.set[serverName].setName = null; - this.set[serverName].setVersion = null; - } - - // Remove type - var removeType = null; - - // Remove from any lists - if (this.primary && this.primary.equals(server)) { - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - removeType = 'primary'; - } - - // Remove from any other server lists - removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; - removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; - removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; - removeFrom(server, this.ghosts); - removeFrom(server, this.unknownServers); - - // Push to unknownServers - this.unknownServers.push(serverName); - - // Do we have a removeType - if (removeType) { - this.emit('left', removeType, server); - } -}; - -const isArbiter = ismaster => ismaster.arbiterOnly && ismaster.setName; - -ReplSetState.prototype.update = function(server) { - var self = this; - // Get the current ismaster - var ismaster = server.lastIsMaster(); - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // - // Add any hosts - // - if (ismaster) { - // Join all the possible new hosts - var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; - hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); - hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); - hosts = hosts.map(function(s) { - return s.toLowerCase(); - }); - - // Add all hosts as unknownServers - for (var i = 0; i < hosts.length; i++) { - // Add to the list of unknown server - if ( - this.unknownServers.indexOf(hosts[i]) === -1 && - (!this.set[hosts[i]] || this.set[hosts[i]].type === ServerType.Unknown) - ) { - this.unknownServers.push(hosts[i].toLowerCase()); - } - - if (!this.set[hosts[i]]) { - this.set[hosts[i]] = { - type: ServerType.Unknown, - electionId: null, - setName: null, - setVersion: null - }; - } - } - } - - // - // Unknown server - // - if (!ismaster && !inList(ismaster, server, this.unknownServers)) { - self.set[serverName] = { - type: ServerType.Unknown, - setVersion: null, - electionId: null, - setName: null - }; - // Update set information about the server instance - self.set[serverName].type = ServerType.Unknown; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - - if (self.unknownServers.indexOf(server.name) === -1) { - self.unknownServers.push(serverName); - } - - // Set the topology - return false; - } - - // Update logicalSessionTimeoutMinutes - if (ismaster.logicalSessionTimeoutMinutes !== undefined && !isArbiter(ismaster)) { - if ( - self.logicalSessionTimeoutMinutes === undefined || - ismaster.logicalSessionTimeoutMinutes === null - ) { - self.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; - } else { - self.logicalSessionTimeoutMinutes = Math.min( - self.logicalSessionTimeoutMinutes, - ismaster.logicalSessionTimeoutMinutes - ); - } - } - - // - // Is this a mongos - // - if (ismaster && ismaster.msg === 'isdbgrid') { - if (this.primary && this.primary.name === serverName) { - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - return false; - } - - // A RSGhost instance - if (ismaster.isreplicaset) { - self.set[serverName] = { - type: ServerType.RSGhost, - setVersion: null, - electionId: null, - setName: ismaster.setName - }; - - if (this.primary && this.primary.name === serverName) { - this.primary = null; - } - - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - - // Set the topology - return false; - } - - // A RSOther instance - if ( - (ismaster.setName && ismaster.hidden) || - (ismaster.setName && - !ismaster.ismaster && - !ismaster.secondary && - !ismaster.arbiterOnly && - !ismaster.passive) - ) { - self.set[serverName] = { - type: ServerType.RSOther, - setVersion: null, - electionId: null, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - return false; - } - - // - // Standalone server, destroy and return - // - if (ismaster && ismaster.ismaster && !ismaster.setName) { - this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown; - this.remove(server, { force: true }); - return false; - } - - // - // Server in maintanance mode - // - if (ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { - this.remove(server, { force: true }); - return false; - } - - // - // If the .me field does not match the passed in server - // - if (ismaster.me && ismaster.me.toLowerCase() !== serverName) { - if (this.logger.isWarn()) { - this.logger.warn( - f( - 'the seedlist server was removed due to its address %s not matching its ismaster.me address %s', - server.name, - ismaster.me - ) - ); - } - - // Delete from the set - delete this.set[serverName]; - // Delete unknown servers - removeFrom(server, self.unknownServers); - - // Destroy the instance - server.destroy({ force: true }); - - // Set the type of topology we have - if (this.primary && !this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - // - // We have a potential primary - // - if (!this.primary && ismaster.primary) { - this.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, - setName: null, - electionId: null, - setVersion: null - }; - } - - return false; - } - - // - // Primary handling - // - if (!this.primary && ismaster.ismaster && ismaster.setName) { - var ismasterElectionId = server.lastIsMaster().electionId; - if (this.setName && this.setName !== ismaster.setName) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return new MongoError( - f( - 'setName from ismaster does not match provided connection setName [%s] != [%s]', - ismaster.setName, - this.setName - ) - ); - } - - if (!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if (this.maxElectionId && ismasterElectionId) { - var result = compareObjectIds(this.maxElectionId, ismasterElectionId); - // Get the electionIds - var ismasterSetVersion = server.lastIsMaster().setVersion; - - if (result === 1) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } else if (result === 0 && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - } - - this.maxSetVersion = ismasterSetVersion; - this.maxElectionId = ismasterElectionId; - } - - // Hande normalization of server names - var normalizedHosts = ismaster.hosts.map(function(x) { - return x.toLowerCase(); - }); - var locationIndex = normalizedHosts.indexOf(serverName); - - // Validate that the server exists in the host list - if (locationIndex !== -1) { - self.primary = server; - self.set[serverName] = { - type: ServerType.RSPrimary, - setVersion: ismaster.setVersion, - electionId: ismaster.electionId, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - emitTopologyDescriptionChanged(self); - return true; - } else if (ismaster.ismaster && ismaster.setName) { - // Get the electionIds - var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; - var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; - var currentSetName = self.set[self.primary.name.toLowerCase()].setName; - ismasterElectionId = server.lastIsMaster().electionId; - ismasterSetVersion = server.lastIsMaster().setVersion; - var ismasterSetName = server.lastIsMaster().setName; - - // Is it the same server instance - if (this.primary.equals(server) && currentSetName === ismasterSetName) { - return false; - } - - // If we do not have the same rs name - if (currentSetName && currentSetName !== ismasterSetName) { - if (!this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - return false; - } - - // Check if we need to replace the server - if (currentElectionId && ismasterElectionId) { - result = compareObjectIds(currentElectionId, ismasterElectionId); - - if (result === 1) { - return false; - } else if (result === 0 && currentSetVersion > ismasterSetVersion) { - return false; - } - } else if (!currentElectionId && ismasterElectionId && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - if (!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if (this.maxElectionId && ismasterElectionId) { - result = compareObjectIds(this.maxElectionId, ismasterElectionId); - - if (result === 1) { - return false; - } else if (result === 0 && currentSetVersion && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } else { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - this.maxElectionId = ismasterElectionId; - this.maxSetVersion = ismasterSetVersion; - } else { - this.maxSetVersion = ismasterSetVersion; - } - - // Modify the entry to unknown - self.set[self.primary.name.toLowerCase()] = { - type: ServerType.Unknown, - setVersion: null, - electionId: null, - setName: null - }; - - // Signal primary left - self.emit('left', 'primary', this.primary); - // Destroy the instance - self.primary.destroy({ force: true }); - // Set the new instance - self.primary = server; - // Set the set information - self.set[serverName] = { - type: ServerType.RSPrimary, - setVersion: ismaster.setVersion, - electionId: ismaster.electionId, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // A possible instance - if (!this.primary && ismaster.primary) { - self.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, - setVersion: null, - electionId: null, - setName: null - }; - } - - // - // Secondary handling - // - if ( - ismaster.secondary && - ismaster.setName && - !inList(ismaster, server, this.secondaries) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if (this.primary && this.primary.name.toLowerCase() === serverName) { - server.destroy({ force: true }); - this.primary = null; - self.emit('left', 'primary', server); - } - - // Emit secondary joined replicaset - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Arbiter handling - // - if ( - isArbiter(ismaster) && - !inList(ismaster, server, this.arbiters) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - self.emit('joined', 'arbiter', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Passive handling - // - if ( - ismaster.passive && - ismaster.setName && - !inList(ismaster, server, this.passives) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if (this.primary && this.primary.name.toLowerCase() === serverName) { - server.destroy({ force: true }); - this.primary = null; - self.emit('left', 'primary', server); - } - - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Remove the primary - // - if (this.set[serverName] && this.set[serverName].type === ServerType.RSPrimary) { - self.emit('left', 'primary', this.primary); - this.primary.destroy({ force: true }); - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - return false; -}; - -/** - * Recalculate single server max staleness - * @method - */ -ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { - // Locate the max secondary lastwrite - var max = 0; - // Go over all secondaries - for (var i = 0; i < this.secondaries.length; i++) { - max = Math.max(max, this.secondaries[i].lastWriteDate); - } - - // Perform this servers staleness calculation - if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary && this.hasPrimary()) { - server.staleness = - server.lastUpdateTime - - server.lastWriteDate - - (this.primary.lastUpdateTime - this.primary.lastWriteDate) + - haInterval; - } else if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary) { - server.staleness = max - server.lastWriteDate + haInterval; - } -}; - -/** - * Recalculate all the staleness values for secodaries - * @method - */ -ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { - for (var i = 0; i < this.secondaries.length; i++) { - this.updateServerMaxStaleness(this.secondaries[i], haInterval); - } -}; - -/** - * Pick a server by the passed in ReadPreference - * @method - * @param {ReadPreference} readPreference The ReadPreference instance to use - */ -ReplSetState.prototype.pickServer = function(readPreference) { - // If no read Preference set to primary by default - readPreference = readPreference || ReadPreference.primary; - - // maxStalenessSeconds is not allowed with a primary read - if (readPreference.preference === 'primary' && readPreference.maxStalenessSeconds != null) { - return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); - } - - // Check if we have any non compatible servers for maxStalenessSeconds - var allservers = this.primary ? [this.primary] : []; - allservers = allservers.concat(this.secondaries); - - // Does any of the servers not support the right wire protocol version - // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out - if (readPreference.maxStalenessSeconds != null) { - for (var i = 0; i < allservers.length; i++) { - if (allservers[i].ismaster.maxWireVersion < 5) { - return new MongoError( - 'maxStalenessSeconds not supported by at least one of the replicaset members' - ); - } - } - } - - // Do we have the nearest readPreference - if (readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds == null) { - return pickNearest(this, readPreference); - } else if ( - readPreference.preference === 'nearest' && - readPreference.maxStalenessSeconds != null - ) { - return pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Get all the secondaries - var secondaries = this.secondaries; - - // Check if we can satisfy and of the basic read Preferences - if (readPreference.equals(ReadPreference.secondary) && secondaries.length === 0) { - return new MongoError('no secondary server available'); - } - - if ( - readPreference.equals(ReadPreference.secondaryPreferred) && - secondaries.length === 0 && - this.primary == null - ) { - return new MongoError('no secondary or primary server available'); - } - - if (readPreference.equals(ReadPreference.primary) && this.primary == null) { - return new MongoError('no primary server available'); - } - - // Secondary preferred or just secondaries - if ( - readPreference.equals(ReadPreference.secondaryPreferred) || - readPreference.equals(ReadPreference.secondary) - ) { - if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - // Pick nearest of any other servers available - var server = pickNearest(this, readPreference); - // No server in the window return primary - if (server) { - return server; - } - } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - // Pick nearest of any other servers available - server = pickNearestMaxStalenessSeconds(this, readPreference); - // No server in the window return primary - if (server) { - return server; - } - } - - if (readPreference.equals(ReadPreference.secondaryPreferred)) { - return this.primary; - } - - return null; - } - - // Primary preferred - if (readPreference.equals(ReadPreference.primaryPreferred)) { - server = null; - - // We prefer the primary if it's available - if (this.primary) { - return this.primary; - } - - // Pick a secondary - if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - server = pickNearest(this, readPreference); - } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - server = pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Did we find a server - if (server) return server; - } - - // Return the primary - return this.primary; -}; - -// -// Filter serves by tags -var filterByTags = function(readPreference, servers) { - if (readPreference.tags == null) return servers; - var filteredServers = []; - var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; - - // Iterate over the tags - for (var j = 0; j < tagsArray.length; j++) { - var tags = tagsArray[j]; - - // Iterate over all the servers - for (var i = 0; i < servers.length; i++) { - var serverTag = servers[i].lastIsMaster().tags || {}; - - // Did we find the a matching server - var found = true; - // Check if the server is valid - for (var name in tags) { - if (serverTag[name] !== tags[name]) { - found = false; - } - } - - // Add to candidate list - if (found) { - filteredServers.push(servers[i]); - } - } - } - - // Returned filtered servers - return filteredServers; -}; - -function pickNearestMaxStalenessSeconds(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - - // Get the maxStalenessMS - var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; - - // Check if the maxStalenessMS > 90 seconds - if (maxStalenessMS < 90 * 1000) { - return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); - } - - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== 'secondary' && - readPreference.preference !== 'secondaryPreferred' - ) { - servers.push(self.primary); - } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if (self.primary && servers.length === 0 && readPreference.preference !== 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Filter by latency - servers = servers.filter(function(s) { - return s.staleness <= maxStalenessMS; - }); - - // Sort by time - servers.sort(function(a, b) { - return a.lastIsMasterMS - b.lastIsMasterMS; - }); - - // No servers, default to primary - if (servers.length === 0) { - return null; - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function pickNearest(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== 'secondary' && - readPreference.preference !== 'secondaryPreferred' - ) { - servers.push(self.primary); - } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if (servers.length === 0 && self.primary && readPreference.preference !== 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Sort by time - servers.sort(function(a, b) { - return a.lastIsMasterMS - b.lastIsMasterMS; - }); - - // Locate lowest time (picked servers are lowest time + acceptable Latency margin) - var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; - - // Filter by latency - servers = servers.filter(function(s) { - return s.lastIsMasterMS <= lowest + self.acceptableLatency; - }); - - // No servers, default to primary - if (servers.length === 0) { - return null; - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function inList(ismaster, server, list) { - for (var i = 0; i < list.length; i++) { - if (list[i] && list[i].name && list[i].name.toLowerCase() === server.name.toLowerCase()) - return true; - } - - return false; -} - -function addToList(self, type, ismaster, server, list) { - var serverName = server.name.toLowerCase(); - // Update set information about the server instance - self.set[serverName].type = type; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - // Add to the list - list.push(server); -} - -function compareObjectIds(id1, id2) { - var a = Buffer.from(id1.toHexString(), 'hex'); - var b = Buffer.from(id2.toHexString(), 'hex'); - - if (a === b) { - return 0; - } - - if (typeof Buffer.compare === 'function') { - return Buffer.compare(a, b); - } - - var x = a.length; - var y = b.length; - var len = Math.min(x, y); - - for (var i = 0; i < len; i++) { - if (a[i] !== b[i]) { - break; - } - } - - if (i !== len) { - x = a[i]; - y = b[i]; - } - - return x < y ? -1 : y < x ? 1 : 0; -} - -function removeFrom(server, list) { - for (var i = 0; i < list.length; i++) { - if (list[i].equals && list[i].equals(server)) { - list.splice(i, 1); - return true; - } else if (typeof list[i] === 'string' && list[i].toLowerCase() === server.name.toLowerCase()) { - list.splice(i, 1); - return true; - } - } - - return false; -} - -function emitTopologyDescriptionChanged(self) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - var setName = self.setName; - - if (self.hasPrimaryAndSecondary()) { - topology = 'ReplicaSetWithPrimary'; - } else if (!self.hasPrimary() && self.hasSecondary()) { - topology = 'ReplicaSetNoPrimary'; - } - - // Generate description - var description = { - topologyType: topology, - setName: setName, - servers: [] - }; - - // Add the primary to the list - if (self.hasPrimary()) { - var desc = self.primary.getDescription(); - desc.type = 'RSPrimary'; - description.servers.push(desc); - } - - // Add all the secondaries - description.servers = description.servers.concat( - self.secondaries.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - }) - ); - - // Add all the arbiters - description.servers = description.servers.concat( - self.arbiters.map(function(x) { - var description = x.getDescription(); - description.type = 'RSArbiter'; - return description; - }) - ); - - // Add all the passives - description.servers = description.servers.concat( - self.passives.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - }) - ); - - // Get the diff - var diffResult = diff(self.replicasetDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.replicasetDescription, - newDescription: description, - diff: diffResult - }; - - // Emit the topologyDescription change - // if(diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - // } - - // Set the new description - self.replicasetDescription = description; - } -} - -module.exports = ReplSetState; diff --git a/node_modules/mongodb/lib/core/topologies/server.js b/node_modules/mongodb/lib/core/topologies/server.js deleted file mode 100644 index 6f6de12..0000000 --- a/node_modules/mongodb/lib/core/topologies/server.js +++ /dev/null @@ -1,990 +0,0 @@ -'use strict'; - -var inherits = require('util').inherits, - f = require('util').format, - EventEmitter = require('events').EventEmitter, - ReadPreference = require('./read_preference'), - Logger = require('../connection/logger'), - debugOptions = require('../connection/utils').debugOptions, - retrieveBSON = require('../connection/utils').retrieveBSON, - Pool = require('../connection/pool'), - MongoError = require('../error').MongoError, - MongoNetworkError = require('../error').MongoNetworkError, - wireProtocol = require('../wireprotocol'), - CoreCursor = require('../cursor').CoreCursor, - sdam = require('./shared'), - createCompressionInfo = require('./shared').createCompressionInfo, - resolveClusterTime = require('./shared').resolveClusterTime, - SessionMixins = require('./shared').SessionMixins, - relayEvents = require('../utils').relayEvents; - -const collationNotSupported = require('../utils').collationNotSupported; -const makeClientMetadata = require('../utils').makeClientMetadata; - -// Used for filtering out fields for loggin -var debugFields = [ - 'reconnect', - 'reconnectTries', - 'reconnectInterval', - 'emitError', - 'cursorFactory', - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'checkServerIdentity', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'key', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'servername' -]; - -// Server instance id -var id = 0; -var serverAccounting = false; -var servers = {}; -var BSON = retrieveBSON(); - -function topologyId(server) { - return server.s.parent == null ? server.id : server.s.parent.id; -} - -/** - * Creates a new Server instance - * @class - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) - * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {Server} A cursor instance - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @fires Server#reconnectFailed - * @fires Server#serverHeartbeatStarted - * @fires Server#serverHeartbeatSucceeded - * @fires Server#serverHeartbeatFailed - * @fires Server#topologyOpening - * @fires Server#topologyClosed - * @fires Server#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Server = function(options) { - options = options || {}; - - // Add event listener - EventEmitter.call(this); - - // Server instance id - this.id = id++; - - // Internal state - this.s = { - // Options - options: Object.assign({ metadata: makeClientMetadata(options) }, options), - // Logger - logger: Logger('Server', options), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Pool - pool: null, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Monitor thread (keeps the connection alive) - monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, - // Is the server in a topology - inTopology: !!options.parent, - // Monitoring timeout - monitoringInterval: - typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, - compression: { compressors: createCompressionInfo(options) }, - // Optional parent topology - parent: options.parent - }; - - // If this is a single deployment we need to track the clusterTime here - if (!this.s.parent) { - this.s.clusterTime = null; - } - - // Curent ismaster - this.ismaster = null; - // Current ping time - this.lastIsMasterMS = -1; - // The monitoringProcessId - this.monitoringProcessId = null; - // Initial connection - this.initialConnect = true; - // Default type - this._type = 'server'; - - // Max Stalleness values - // last time we updated the ismaster state - this.lastUpdateTime = 0; - // Last write time - this.lastWriteDate = 0; - // Stalleness - this.staleness = 0; -}; - -inherits(Server, EventEmitter); -Object.assign(Server.prototype, SessionMixins); - -Object.defineProperty(Server.prototype, 'type', { - enumerable: true, - get: function() { - return this._type; - } -}); - -Object.defineProperty(Server.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - if (!this.ismaster) return null; - return this.ismaster.logicalSessionTimeoutMinutes || null; - } -}); - -Object.defineProperty(Server.prototype, 'clientMetadata', { - enumerable: true, - get: function() { - return this.s.options.metadata; - } -}); - -// In single server deployments we track the clusterTime directly on the topology, however -// in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the -// tracking objects so we can ensure we are gossiping the maximum time received from the -// server. -Object.defineProperty(Server.prototype, 'clusterTime', { - enumerable: true, - set: function(clusterTime) { - const settings = this.s.parent ? this.s.parent : this.s; - resolveClusterTime(settings, clusterTime); - }, - get: function() { - const settings = this.s.parent ? this.s.parent : this.s; - return settings.clusterTime || null; - } -}); - -Server.enableServerAccounting = function() { - serverAccounting = true; - servers = {}; -}; - -Server.disableServerAccounting = function() { - serverAccounting = false; -}; - -Server.servers = function() { - return servers; -}; - -Object.defineProperty(Server.prototype, 'name', { - enumerable: true, - get: function() { - return this.s.options.host + ':' + this.s.options.port; - } -}); - -function disconnectHandler(self, type, ns, cmd, options, callback) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if ( - !self.s.pool.isConnected() && - self.s.options.reconnect && - self.s.disconnectHandler != null && - !options.monitoring - ) { - self.s.disconnectHandler.add(type, ns, cmd, options, callback); - return true; - } - - // If we have no connection error - if (!self.s.pool.isConnected()) { - callback(new MongoError(f('no connection available to server %s', self.name))); - return true; - } -} - -function monitoringProcess(self) { - return function() { - // Pool was destroyed do not continue process - if (self.s.pool.isDestroyed()) return; - // Emit monitoring Process event - self.emit('monitoring', self); - // Perform ismaster call - // Get start time - var start = new Date().getTime(); - - // Execute the ismaster query - self.command( - 'admin.$cmd', - { ismaster: true }, - { - socketTimeout: - typeof self.s.options.connectionTimeout !== 'number' - ? 2000 - : self.s.options.connectionTimeout, - monitoring: true - }, - (err, result) => { - // Set initial lastIsMasterMS - self.lastIsMasterMS = new Date().getTime() - start; - if (self.s.pool.isDestroyed()) return; - // Update the ismaster view if we have a result - if (result) { - self.ismaster = result.result; - } - // Re-schedule the monitoring process - self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); - } - ); - }; -} - -var eventHandler = function(self, event) { - return function(err, conn) { - // Log information of received information if in info mode - if (self.s.logger.isInfo()) { - var object = err instanceof MongoError ? JSON.stringify(err) : {}; - self.s.logger.info( - f('server %s fired event %s out with message %s', self.name, event, object) - ); - } - - // Handle connect event - if (event === 'connect') { - self.initialConnect = false; - self.ismaster = conn.ismaster; - self.lastIsMasterMS = conn.lastIsMasterMS; - if (conn.agreedCompressor) { - self.s.pool.options.agreedCompressor = conn.agreedCompressor; - } - - if (conn.zlibCompressionLevel) { - self.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel; - } - - if (conn.ismaster.$clusterTime) { - const $clusterTime = conn.ismaster.$clusterTime; - self.clusterTime = $clusterTime; - } - - // It's a proxy change the type so - // the wireprotocol will send $readPreference - if (self.ismaster.msg === 'isdbgrid') { - self._type = 'mongos'; - } - - // Have we defined self monitoring - if (self.s.monitoring) { - self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); - } - - // Emit server description changed if something listening - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - }); - - if (!self.s.inTopology) { - // Emit topology description changed if something listening - sdam.emitTopologyDescriptionChanged(self, { - topologyType: 'Single', - servers: [ - { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - } - ] - }); - } - - // Log the ismaster if available - if (self.s.logger.isInfo()) { - self.s.logger.info( - f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster)) - ); - } - - // Emit connect - self.emit('connect', self); - } else if ( - event === 'error' || - event === 'parseError' || - event === 'close' || - event === 'timeout' || - event === 'reconnect' || - event === 'attemptReconnect' || - 'reconnectFailed' - ) { - // Remove server instance from accounting - if ( - serverAccounting && - ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1 - ) { - // Emit toplogy opening event if not in topology - if (!self.s.inTopology) { - self.emit('topologyOpening', { topologyId: self.id }); - } - - delete servers[self.id]; - } - - if (event === 'close') { - // Closing emits a server description changed event going to unknown. - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - }); - } - - // Reconnect failed return error - if (event === 'reconnectFailed') { - self.emit('reconnectFailed', err); - // Emit error if any listeners - if (self.listeners('error').length > 0) { - self.emit('error', err); - } - // Terminate - return; - } - - // On first connect fail - if ( - ['disconnected', 'connecting'].indexOf(self.s.pool.state) !== -1 && - self.initialConnect && - ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1 - ) { - self.initialConnect = false; - return self.emit( - 'error', - new MongoNetworkError( - f('failed to connect to server [%s] on first connect [%s]', self.name, err) - ) - ); - } - - // Reconnect event, emit the server - if (event === 'reconnect') { - // Reconnecting emits a server description changed event going from unknown to the - // current server type. - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - }); - return self.emit(event, self); - } - - // Emit the event - self.emit(event, err); - } - }; -}; - -/** - * Initiate server connect - */ -Server.prototype.connect = function(options) { - var self = this; - options = options || {}; - - // Set the connections - if (serverAccounting) servers[this.id] = this; - - // Do not allow connect to be called on anything that's not disconnected - if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { - throw new MongoError(f('server instance in invalid state %s', self.s.pool.state)); - } - - // Create a pool - self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson })); - - // Set up listeners - self.s.pool.on('close', eventHandler(self, 'close')); - self.s.pool.on('error', eventHandler(self, 'error')); - self.s.pool.on('timeout', eventHandler(self, 'timeout')); - self.s.pool.on('parseError', eventHandler(self, 'parseError')); - self.s.pool.on('connect', eventHandler(self, 'connect')); - self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); - self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); - - // Set up listeners for command monitoring - relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Emit toplogy opening event if not in topology - if (!self.s.inTopology) { - this.emit('topologyOpening', { topologyId: topologyId(self) }); - } - - // Emit opening server event - self.emit('serverOpening', { topologyId: topologyId(self), address: self.name }); - - self.s.pool.connect(); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -Server.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Get the server description - * @method - * @return {object} - */ -Server.prototype.getDescription = function() { - var ismaster = this.ismaster || {}; - var description = { - type: sdam.getTopologyType(this), - address: this.name - }; - - // Add fields if available - if (ismaster.hosts) description.hosts = ismaster.hosts; - if (ismaster.arbiters) description.arbiters = ismaster.arbiters; - if (ismaster.passives) description.passives = ismaster.passives; - if (ismaster.setName) description.setName = ismaster.setName; - return description; -}; - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Server.prototype.lastIsMaster = function() { - return this.ismaster; -}; - -/** - * Unref all connections belong to this server - * @method - */ -Server.prototype.unref = function() { - this.s.pool.unref(); -}; - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Server.prototype.isConnected = function() { - if (!this.s.pool) return false; - return this.s.pool.isConnected(); -}; - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Server.prototype.isDestroyed = function() { - if (!this.s.pool) return false; - return this.s.pool.isDestroyed(); -}; - -function basicWriteValidations(self) { - if (!self.s.pool) return new MongoError('server instance is not connected'); - if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed'); -} - -function basicReadValidations(self, options) { - basicWriteValidations(self, options); - - if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { - throw new Error('readPreference must be an instance of ReadPreference'); - } -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.command = function(ns, cmd, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicReadValidations(self, options); - if (result) return callback(result); - - // Clone the options - options = Object.assign({}, options, { wireProtocolCommand: false }); - - // Debug log - if (self.s.logger.isDebug()) - self.s.logger.debug( - f( - 'executing command [%s] against %s', - JSON.stringify({ - ns: ns, - cmd: cmd, - options: debugOptions(debugFields, options) - }), - self.name - ) - ); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, cmd)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - wireProtocol.command(self, ns, cmd, options, callback); -}; - -/** - * Execute a query against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command document for the query - * @param {object} options Optional settings - * @param {function} callback - */ -Server.prototype.query = function(ns, cmd, cursorState, options, callback) { - wireProtocol.query(this, ns, cmd, cursorState, options, callback); -}; - -/** - * Execute a `getMore` against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {object} options Optional settings - * @param {function} callback - */ -Server.prototype.getMore = function(ns, cursorState, batchSize, options, callback) { - wireProtocol.getMore(this, ns, cursorState, batchSize, options, callback); -}; - -/** - * Execute a `killCursors` command against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {function} callback - */ -Server.prototype.killCursors = function(ns, cursorState, callback) { - wireProtocol.killCursors(this, ns, cursorState, callback); -}; - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.insert = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return; - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - - // Execute write - return wireProtocol.insert(self, ns, ops, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.update = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'update', ns, ops, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, options)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return wireProtocol.update(self, ns, ops, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.remove = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, options)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return wireProtocol.remove(self, ns, ops, options, callback); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -Server.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * Compare two server instances - * @method - * @param {Server} server Server to compare equality against - * @return {boolean} - */ -Server.prototype.equals = function(server) { - if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase(); - if (server.name) return this.name.toLowerCase() === server.name.toLowerCase(); - return false; -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Server.prototype.connections = function() { - return this.s.pool.allConnections(); -}; - -/** - * Selects a server - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Unused - * @param {ClientSession} [options.session] Unused - * @return {Server} - */ -Server.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') - (callback = options), (options = selector), (selector = undefined); - - callback(null, this); -}; - -var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; - -/** - * Destroy the server connection - * @method - * @param {boolean} [options.emitClose=false] Emit close event on destroy - * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy - * @param {boolean} [options.force=false] Force destroy the pool - */ -Server.prototype.destroy = function(options, callback) { - if (this._destroyed) { - if (typeof callback === 'function') callback(null, null); - return; - } - - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - var self = this; - - // Set the connections - if (serverAccounting) delete servers[this.id]; - - // Destroy the monitoring process if any - if (this.monitoringProcessId) { - clearTimeout(this.monitoringProcessId); - } - - // No pool, return - if (!self.s.pool) { - this._destroyed = true; - if (typeof callback === 'function') callback(null, null); - return; - } - - // Emit close event - if (options.emitClose) { - self.emit('close', self); - } - - // Emit destroy event - if (options.emitDestroy) { - self.emit('destroy', self); - } - - // Remove all listeners - listeners.forEach(function(event) { - self.s.pool.removeAllListeners(event); - }); - - // Emit opening server event - if (self.listeners('serverClosed').length > 0) - self.emit('serverClosed', { topologyId: topologyId(self), address: self.name }); - - // Emit toplogy opening event if not in topology - if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { - self.emit('topologyClosed', { topologyId: topologyId(self) }); - } - - if (self.s.logger.isDebug()) { - self.s.logger.debug(f('destroy called on server %s', self.name)); - } - - // Destroy the pool - this.s.pool.destroy(options.force, callback); - this._destroyed = true; -}; - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Server#connect - * @type {Server} - */ - -/** - * A server reconnect event, used to verify that the server topology has reconnected - * - * @event Server#reconnect - * @type {Server} - */ - -/** - * A server opening SDAM monitoring event - * - * @event Server#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Server#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Server#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Server#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Server#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Server#topologyDescriptionChanged - * @type {object} - */ - -/** - * Server reconnect failed - * - * @event Server#reconnectFailed - * @type {Error} - */ - -/** - * Server connection pool closed - * - * @event Server#close - * @type {object} - */ - -/** - * Server connection pool caused an error - * - * @event Server#error - * @type {Error} - */ - -/** - * Server destroyed was called - * - * @event Server#destroy - * @type {Server} - */ - -module.exports = Server; diff --git a/node_modules/mongodb/lib/core/topologies/shared.js b/node_modules/mongodb/lib/core/topologies/shared.js deleted file mode 100644 index 590004b..0000000 --- a/node_modules/mongodb/lib/core/topologies/shared.js +++ /dev/null @@ -1,433 +0,0 @@ -'use strict'; -const ReadPreference = require('./read_preference'); -const TopologyType = require('../sdam/common').TopologyType; -const MongoError = require('../error').MongoError; - -const MMAPv1_RETRY_WRITES_ERROR_CODE = 20; - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -function createCompressionInfo(options) { - if (!options.compression || !options.compression.compressors) { - return []; - } - - // Check that all supplied compressors are valid - options.compression.compressors.forEach(function(compressor) { - if (compressor !== 'snappy' && compressor !== 'zlib') { - throw new Error('compressors must be at least one of snappy or zlib'); - } - }); - - return options.compression.compressors; -} - -function clone(object) { - return JSON.parse(JSON.stringify(object)); -} - -var getPreviousDescription = function(self) { - if (!self.s.serverDescription) { - self.s.serverDescription = { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - }; - } - - return self.s.serverDescription; -}; - -var emitServerDescriptionChanged = function(self, description) { - if (self.listeners('serverDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('serverDescriptionChanged', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name, - previousDescription: getPreviousDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -}; - -var getPreviousTopologyDescription = function(self) { - if (!self.s.topologyDescription) { - self.s.topologyDescription = { - topologyType: 'Unknown', - servers: [ - { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - } - ] - }; - } - - return self.s.topologyDescription; -}; - -var emitTopologyDescriptionChanged = function(self, description) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('topologyDescriptionChanged', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name, - previousDescription: getPreviousTopologyDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -}; - -var changedIsMaster = function(self, currentIsmaster, ismaster) { - var currentType = getTopologyType(self, currentIsmaster); - var newType = getTopologyType(self, ismaster); - if (newType !== currentType) return true; - return false; -}; - -var getTopologyType = function(self, ismaster) { - if (!ismaster) { - ismaster = self.ismaster; - } - - if (!ismaster) return 'Unknown'; - if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos'; - if (ismaster.ismaster && !ismaster.hosts) return 'Standalone'; - if (ismaster.ismaster) return 'RSPrimary'; - if (ismaster.secondary) return 'RSSecondary'; - if (ismaster.arbiterOnly) return 'RSArbiter'; - return 'Unknown'; -}; - -var inquireServerState = function(self) { - return function(callback) { - if (self.s.state === 'destroyed') return; - // Record response time - var start = new Date().getTime(); - - // emitSDAMEvent - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); - - // Attempt to execute ismaster command - self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) { - if (!err) { - // Legacy event sender - self.emit('ismaster', r, self); - - // Calculate latencyMS - var latencyMS = new Date().getTime() - start; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: self.name - }); - - // Did the server change - if (changedIsMaster(self, self.s.ismaster, r.result)) { - // Emit server description changed if something listening - emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) - }); - } - - // Updat ismaster view - self.s.ismaster = r.result; - - // Set server response time - self.s.isMasterLatencyMS = latencyMS; - } else { - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: self.name - }); - } - - // Peforming an ismaster monitoring callback operation - if (typeof callback === 'function') { - return callback(err, r); - } - - // Perform another sweep - self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); - }); - }; -}; - -// -// Clone the options -var cloneOptions = function(options) { - var opts = {}; - for (var name in options) { - opts[name] = options[name]; - } - return opts; -}; - -function Interval(fn, time) { - var timer = false; - - this.start = function() { - if (!this.isRunning()) { - timer = setInterval(fn, time); - } - - return this; - }; - - this.stop = function() { - clearInterval(timer); - timer = false; - return this; - }; - - this.isRunning = function() { - return timer !== false; - }; -} - -function Timeout(fn, time) { - var timer = false; - var func = () => { - if (timer) { - clearTimeout(timer); - timer = false; - - fn(); - } - }; - - this.start = function() { - if (!this.isRunning()) { - timer = setTimeout(func, time); - } - return this; - }; - - this.stop = function() { - clearTimeout(timer); - timer = false; - return this; - }; - - this.isRunning = function() { - return timer !== false; - }; -} - -function diff(previous, current) { - // Difference document - var diff = { - servers: [] - }; - - // Previous entry - if (!previous) { - previous = { servers: [] }; - } - - // Check if we have any previous servers missing in the current ones - for (var i = 0; i < previous.servers.length; i++) { - var found = false; - - for (var j = 0; j < current.servers.length; j++) { - if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) { - found = true; - break; - } - } - - if (!found) { - // Add to the diff - diff.servers.push({ - address: previous.servers[i].address, - from: previous.servers[i].type, - to: 'Unknown' - }); - } - } - - // Check if there are any severs that don't exist - for (j = 0; j < current.servers.length; j++) { - found = false; - - // Go over all the previous servers - for (i = 0; i < previous.servers.length; i++) { - if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) { - found = true; - break; - } - } - - // Add the server to the diff - if (!found) { - diff.servers.push({ - address: current.servers[j].address, - from: 'Unknown', - to: current.servers[j].type - }); - } - } - - // Got through all the servers - for (i = 0; i < previous.servers.length; i++) { - var prevServer = previous.servers[i]; - - // Go through all current servers - for (j = 0; j < current.servers.length; j++) { - var currServer = current.servers[j]; - - // Matching server - if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) { - // We had a change in state - if (prevServer.type !== currServer.type) { - diff.servers.push({ - address: prevServer.address, - from: prevServer.type, - to: currServer.type - }); - } - } - } - } - - // Return difference - return diff; -} - -/** - * Shared function to determine clusterTime for a given topology - * - * @param {*} topology - * @param {*} clusterTime - */ -function resolveClusterTime(topology, $clusterTime) { - if (topology.clusterTime == null) { - topology.clusterTime = $clusterTime; - } else { - if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { - topology.clusterTime = $clusterTime; - } - } -} - -// NOTE: this is a temporary move until the topologies can be more formally refactored -// to share code. -const SessionMixins = { - endSessions: function(sessions, callback) { - if (!Array.isArray(sessions)) { - sessions = [sessions]; - } - - // TODO: - // When connected to a sharded cluster the endSessions command - // can be sent to any mongos. When connected to a replica set the - // endSessions command MUST be sent to the primary if the primary - // is available, otherwise it MUST be sent to any available secondary. - // Is it enough to use: ReadPreference.primaryPreferred ? - this.command( - 'admin.$cmd', - { endSessions: sessions }, - { readPreference: ReadPreference.primaryPreferred }, - () => { - // intentionally ignored, per spec - if (typeof callback === 'function') callback(); - } - ); - } -}; - -function topologyType(topology) { - if (topology.description) { - return topology.description.type; - } - - if (topology.type === 'mongos') { - return TopologyType.Sharded; - } else if (topology.type === 'replset') { - return TopologyType.ReplicaSetWithPrimary; - } - - return TopologyType.Single; -} - -const RETRYABLE_WIRE_VERSION = 6; - -/** - * Determines whether the provided topology supports retryable writes - * - * @param {Mongos|Replset} topology - */ -const isRetryableWritesSupported = function(topology) { - const maxWireVersion = topology.lastIsMaster().maxWireVersion; - if (maxWireVersion < RETRYABLE_WIRE_VERSION) { - return false; - } - - if (!topology.logicalSessionTimeoutMinutes) { - return false; - } - - if (topologyType(topology) === TopologyType.Single) { - return false; - } - - return true; -}; - -const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = - 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; - -function getMMAPError(err) { - if (err.code !== MMAPv1_RETRY_WRITES_ERROR_CODE || !err.errmsg.includes('Transaction numbers')) { - return err; - } - - // According to the retryable writes spec, we must replace the error message in this case. - // We need to replace err.message so the thrown message is correct and we need to replace err.errmsg to meet the spec requirement. - const newErr = new MongoError({ - message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, - errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, - originalError: err - }); - return newErr; -} - -module.exports.SessionMixins = SessionMixins; -module.exports.resolveClusterTime = resolveClusterTime; -module.exports.inquireServerState = inquireServerState; -module.exports.getTopologyType = getTopologyType; -module.exports.emitServerDescriptionChanged = emitServerDescriptionChanged; -module.exports.emitTopologyDescriptionChanged = emitTopologyDescriptionChanged; -module.exports.cloneOptions = cloneOptions; -module.exports.createCompressionInfo = createCompressionInfo; -module.exports.clone = clone; -module.exports.diff = diff; -module.exports.Interval = Interval; -module.exports.Timeout = Timeout; -module.exports.isRetryableWritesSupported = isRetryableWritesSupported; -module.exports.getMMAPError = getMMAPError; -module.exports.topologyType = topologyType; diff --git a/node_modules/mongodb/lib/core/transactions.js b/node_modules/mongodb/lib/core/transactions.js deleted file mode 100644 index d0b0b73..0000000 --- a/node_modules/mongodb/lib/core/transactions.js +++ /dev/null @@ -1,179 +0,0 @@ -'use strict'; -const MongoError = require('./error').MongoError; -const ReadPreference = require('./topologies/read_preference'); -const ReadConcern = require('../read_concern'); -const WriteConcern = require('../write_concern'); - -let TxnState; -let stateMachine; - -(() => { - const NO_TRANSACTION = 'NO_TRANSACTION'; - const STARTING_TRANSACTION = 'STARTING_TRANSACTION'; - const TRANSACTION_IN_PROGRESS = 'TRANSACTION_IN_PROGRESS'; - const TRANSACTION_COMMITTED = 'TRANSACTION_COMMITTED'; - const TRANSACTION_COMMITTED_EMPTY = 'TRANSACTION_COMMITTED_EMPTY'; - const TRANSACTION_ABORTED = 'TRANSACTION_ABORTED'; - - TxnState = { - NO_TRANSACTION, - STARTING_TRANSACTION, - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - TRANSACTION_ABORTED - }; - - stateMachine = { - [NO_TRANSACTION]: [NO_TRANSACTION, STARTING_TRANSACTION], - [STARTING_TRANSACTION]: [ - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - TRANSACTION_ABORTED - ], - [TRANSACTION_IN_PROGRESS]: [ - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_ABORTED - ], - [TRANSACTION_COMMITTED]: [ - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - STARTING_TRANSACTION, - NO_TRANSACTION - ], - [TRANSACTION_ABORTED]: [STARTING_TRANSACTION, NO_TRANSACTION], - [TRANSACTION_COMMITTED_EMPTY]: [TRANSACTION_COMMITTED_EMPTY, NO_TRANSACTION] - }; -})(); - -/** - * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties - * of the data read from replica sets and replica set shards. - * @typedef {Object} ReadConcern - * @property {'local'|'available'|'majority'|'linearizable'|'snapshot'} level The readConcern Level - * @see https://docs.mongodb.com/manual/reference/read-concern/ - */ - -/** - * A MongoDB WriteConcern, which describes the level of acknowledgement - * requested from MongoDB for write operations. - * @typedef {Object} WriteConcern - * @property {number|'majority'|string} [w=1] requests acknowledgement that the write operation has - * propagated to a specified number of mongod hosts - * @property {boolean} [j=false] requests acknowledgement from MongoDB that the write operation has - * been written to the journal - * @property {number} [wtimeout] a time limit, in milliseconds, for the write concern - * @see https://docs.mongodb.com/manual/reference/write-concern/ - */ - -/** - * Configuration options for a transaction. - * @typedef {Object} TransactionOptions - * @property {ReadConcern} [readConcern] A default read concern for commands in this transaction - * @property {WriteConcern} [writeConcern] A default writeConcern for commands in this transaction - * @property {ReadPreference} [readPreference] A default read preference for commands in this transaction - */ - -/** - * A class maintaining state related to a server transaction. Internal Only - * @ignore - */ -class Transaction { - /** - * Create a transaction - * - * @ignore - * @param {TransactionOptions} [options] Optional settings - */ - constructor(options) { - options = options || {}; - - this.state = TxnState.NO_TRANSACTION; - this.options = {}; - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern) { - if (writeConcern.w <= 0) { - throw new MongoError('Transactions do not support unacknowledged write concern'); - } - - this.options.writeConcern = writeConcern; - } - - if (options.readConcern) { - this.options.readConcern = ReadConcern.fromOptions(options); - } - - if (options.readPreference) { - this.options.readPreference = ReadPreference.fromOptions(options); - } - - if (options.maxCommitTimeMS) { - this.options.maxTimeMS = options.maxCommitTimeMS; - } - - // TODO: This isn't technically necessary - this._pinnedServer = undefined; - this._recoveryToken = undefined; - } - - get server() { - return this._pinnedServer; - } - - get recoveryToken() { - return this._recoveryToken; - } - - get isPinned() { - return !!this.server; - } - - /** - * @ignore - * @return Whether this session is presently in a transaction - */ - get isActive() { - return ( - [TxnState.STARTING_TRANSACTION, TxnState.TRANSACTION_IN_PROGRESS].indexOf(this.state) !== -1 - ); - } - - /** - * Transition the transaction in the state machine - * @ignore - * @param {TxnState} state The new state to transition to - */ - transition(nextState) { - const nextStates = stateMachine[this.state]; - if (nextStates && nextStates.indexOf(nextState) !== -1) { - this.state = nextState; - if (this.state === TxnState.NO_TRANSACTION || this.state === TxnState.STARTING_TRANSACTION) { - this.unpinServer(); - } - return; - } - - throw new MongoError( - `Attempted illegal state transition from [${this.state}] to [${nextState}]` - ); - } - - pinServer(server) { - if (this.isActive) { - this._pinnedServer = server; - } - } - - unpinServer() { - this._pinnedServer = undefined; - } -} - -function isTransactionCommand(command) { - return !!(command.commitTransaction || command.abortTransaction); -} - -module.exports = { TxnState, Transaction, isTransactionCommand }; diff --git a/node_modules/mongodb/lib/core/uri_parser.js b/node_modules/mongodb/lib/core/uri_parser.js deleted file mode 100644 index 01685f5..0000000 --- a/node_modules/mongodb/lib/core/uri_parser.js +++ /dev/null @@ -1,688 +0,0 @@ -'use strict'; -const URL = require('url'); -const qs = require('querystring'); -const dns = require('dns'); -const MongoParseError = require('./error').MongoParseError; -const ReadPreference = require('./topologies/read_preference'); - -/** - * The following regular expression validates a connection string and breaks the - * provide string into the following capture groups: [protocol, username, password, hosts] - */ -const HOSTS_RX = /(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/; - -/** - * Determines whether a provided address matches the provided parent domain in order - * to avoid certain attack vectors. - * - * @param {String} srvAddress The address to check against a domain - * @param {String} parentDomain The domain to check the provided address against - * @return {Boolean} Whether the provided address matches the parent domain - */ -function matchesParentDomain(srvAddress, parentDomain) { - const regex = /^.*?\./; - const srv = `.${srvAddress.replace(regex, '')}`; - const parent = `.${parentDomain.replace(regex, '')}`; - return srv.endsWith(parent); -} - -/** - * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal - * connection string. - * - * @param {string} uri The connection string to parse - * @param {object} options Optional user provided connection string options - * @param {function} callback - */ -function parseSrvConnectionString(uri, options, callback) { - const result = URL.parse(uri, true); - - if (result.hostname.split('.').length < 3) { - return callback(new MongoParseError('URI does not have hostname, domain name and tld')); - } - - result.domainLength = result.hostname.split('.').length; - if (result.pathname && result.pathname.match(',')) { - return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); - } - - if (result.port) { - return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); - } - - // Resolve the SRV record and use the result as the list of hosts to connect to. - const lookupAddress = result.host; - dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { - if (err) return callback(err); - - if (addresses.length === 0) { - return callback(new MongoParseError('No addresses found at host')); - } - - for (let i = 0; i < addresses.length; i++) { - if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { - return callback( - new MongoParseError('Server record does not share hostname with parent URI') - ); - } - } - - // Convert the original URL to a non-SRV URL. - result.protocol = 'mongodb'; - result.host = addresses.map(address => `${address.name}:${address.port}`).join(','); - - // Default to SSL true if it's not specified. - if ( - !('ssl' in options) && - (!result.search || !('ssl' in result.query) || result.query.ssl === null) - ) { - result.query.ssl = true; - } - - // Resolve TXT record and add options from there if they exist. - dns.resolveTxt(lookupAddress, (err, record) => { - if (err) { - if (err.code !== 'ENODATA') { - return callback(err); - } - record = null; - } - - if (record) { - if (record.length > 1) { - return callback(new MongoParseError('Multiple text records not allowed')); - } - - record = qs.parse(record[0].join('')); - if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) { - return callback( - new MongoParseError('Text record must only set `authSource` or `replicaSet`') - ); - } - - result.query = Object.assign({}, record, result.query); - } - - // Set completed options back into the URL object. - result.search = qs.stringify(result.query); - - const finalString = URL.format(result); - parseConnectionString(finalString, options, (err, ret) => { - if (err) { - callback(err); - return; - } - - callback(null, Object.assign({}, ret, { srvHost: lookupAddress })); - }); - }); - }); -} - -/** - * Parses a query string item according to the connection string spec - * - * @param {string} key The key for the parsed value - * @param {Array|String} value The value to parse - * @return {Array|Object|String} The parsed value - */ -function parseQueryStringItemValue(key, value) { - if (Array.isArray(value)) { - // deduplicate and simplify arrays - value = value.filter((v, idx) => value.indexOf(v) === idx); - if (value.length === 1) value = value[0]; - } else if (value.indexOf(':') > 0) { - value = value.split(',').reduce((result, pair) => { - const parts = pair.split(':'); - result[parts[0]] = parseQueryStringItemValue(key, parts[1]); - return result; - }, {}); - } else if (value.indexOf(',') > 0) { - value = value.split(',').map(v => { - return parseQueryStringItemValue(key, v); - }); - } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { - value = value.toLowerCase() === 'true'; - } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { - const numericValue = parseFloat(value); - if (!Number.isNaN(numericValue)) { - value = parseFloat(value); - } - } - - return value; -} - -// Options that are known boolean types -const BOOLEAN_OPTIONS = new Set([ - 'slaveok', - 'slave_ok', - 'sslvalidate', - 'fsync', - 'safe', - 'retrywrites', - 'j' -]); - -// Known string options, only used to bypass Number coercion in `parseQueryStringItemValue` -const STRING_OPTIONS = new Set(['authsource', 'replicaset']); - -// Supported text representations of auth mechanisms -// NOTE: this list exists in native already, if it is merged here we should deduplicate -const AUTH_MECHANISMS = new Set([ - 'GSSAPI', - 'MONGODB-X509', - 'MONGODB-CR', - 'DEFAULT', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256', - 'PLAIN' -]); - -// Lookup table used to translate normalized (lower-cased) forms of connection string -// options to their expected camelCase version -const CASE_TRANSLATION = { - replicaset: 'replicaSet', - connecttimeoutms: 'connectTimeoutMS', - sockettimeoutms: 'socketTimeoutMS', - maxpoolsize: 'maxPoolSize', - minpoolsize: 'minPoolSize', - maxidletimems: 'maxIdleTimeMS', - waitqueuemultiple: 'waitQueueMultiple', - waitqueuetimeoutms: 'waitQueueTimeoutMS', - wtimeoutms: 'wtimeoutMS', - readconcern: 'readConcern', - readconcernlevel: 'readConcernLevel', - readpreference: 'readPreference', - maxstalenessseconds: 'maxStalenessSeconds', - readpreferencetags: 'readPreferenceTags', - authsource: 'authSource', - authmechanism: 'authMechanism', - authmechanismproperties: 'authMechanismProperties', - gssapiservicename: 'gssapiServiceName', - localthresholdms: 'localThresholdMS', - serverselectiontimeoutms: 'serverSelectionTimeoutMS', - serverselectiontryonce: 'serverSelectionTryOnce', - heartbeatfrequencyms: 'heartbeatFrequencyMS', - retrywrites: 'retryWrites', - uuidrepresentation: 'uuidRepresentation', - zlibcompressionlevel: 'zlibCompressionLevel', - tlsallowinvalidcertificates: 'tlsAllowInvalidCertificates', - tlsallowinvalidhostnames: 'tlsAllowInvalidHostnames', - tlsinsecure: 'tlsInsecure', - tlscafile: 'tlsCAFile', - tlscertificatekeyfile: 'tlsCertificateKeyFile', - tlscertificatekeyfilepassword: 'tlsCertificateKeyFilePassword', - wtimeout: 'wTimeoutMS', - j: 'journal' -}; - -/** - * Sets the value for `key`, allowing for any required translation - * - * @param {object} obj The object to set the key on - * @param {string} key The key to set the value for - * @param {*} value The value to set - * @param {object} options The options used for option parsing - */ -function applyConnectionStringOption(obj, key, value, options) { - // simple key translation - if (key === 'journal') { - key = 'j'; - } else if (key === 'wtimeoutms') { - key = 'wtimeout'; - } - - // more complicated translation - if (BOOLEAN_OPTIONS.has(key)) { - value = value === 'true' || value === true; - } else if (key === 'appname') { - value = decodeURIComponent(value); - } else if (key === 'readconcernlevel') { - obj['readConcernLevel'] = value; - key = 'readconcern'; - value = { level: value }; - } - - // simple validation - if (key === 'compressors') { - value = Array.isArray(value) ? value : [value]; - - if (!value.every(c => c === 'snappy' || c === 'zlib')) { - throw new MongoParseError( - 'Value for `compressors` must be at least one of: `snappy`, `zlib`' - ); - } - } - - if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { - throw new MongoParseError( - 'Value for `authMechanism` must be one of: `DEFAULT`, `GSSAPI`, `PLAIN`, `MONGODB-X509`, `SCRAM-SHA-1`, `SCRAM-SHA-256`' - ); - } - - if (key === 'readpreference' && !ReadPreference.isValid(value)) { - throw new MongoParseError( - 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' - ); - } - - if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { - throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); - } - - // special cases - if (key === 'compressors' || key === 'zlibcompressionlevel') { - obj.compression = obj.compression || {}; - obj = obj.compression; - } - - if (key === 'authmechanismproperties') { - if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; - if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; - if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { - obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; - } - } - - if (key === 'readpreferencetags') { - value = Array.isArray(value) ? splitArrayOfMultipleReadPreferenceTags(value) : [value]; - } - - // set the actual value - if (options.caseTranslate && CASE_TRANSLATION[key]) { - obj[CASE_TRANSLATION[key]] = value; - return; - } - - obj[key] = value; -} - -const USERNAME_REQUIRED_MECHANISMS = new Set([ - 'GSSAPI', - 'MONGODB-CR', - 'PLAIN', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256' -]); - -function splitArrayOfMultipleReadPreferenceTags(value) { - const parsedTags = []; - - for (let i = 0; i < value.length; i++) { - parsedTags[i] = {}; - value[i].split(',').forEach(individualTag => { - const splitTag = individualTag.split(':'); - parsedTags[i][splitTag[0]] = splitTag[1]; - }); - } - - return parsedTags; -} - -/** - * Modifies the parsed connection string object taking into account expectations we - * have for authentication-related options. - * - * @param {object} parsed The parsed connection string result - * @return The parsed connection string result possibly modified for auth expectations - */ -function applyAuthExpectations(parsed) { - if (parsed.options == null) { - return; - } - - const options = parsed.options; - const authSource = options.authsource || options.authSource; - if (authSource != null) { - parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); - } - - const authMechanism = options.authmechanism || options.authMechanism; - if (authMechanism != null) { - if ( - USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && - (!parsed.auth || parsed.auth.username == null) - ) { - throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); - } - - if (authMechanism === 'GSSAPI') { - if (authSource != null && authSource !== '$external') { - throw new MongoParseError( - `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` - ); - } - - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - - if (authMechanism === 'MONGODB-X509') { - if (parsed.auth && parsed.auth.password != null) { - throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); - } - - if (authSource != null && authSource !== '$external') { - throw new MongoParseError( - `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` - ); - } - - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - - if (authMechanism === 'PLAIN') { - if (parsed.auth && parsed.auth.db == null) { - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - } - } - - // default to `admin` if nothing else was resolved - if (parsed.auth && parsed.auth.db == null) { - parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); - } - - return parsed; -} - -/** - * Parses a query string according the connection string spec. - * - * @param {String} query The query string to parse - * @param {object} [options] The options used for options parsing - * @return {Object|Error} The parsed query string as an object, or an error if one was encountered - */ -function parseQueryString(query, options) { - const result = {}; - let parsedQueryString = qs.parse(query); - - checkTLSOptions(parsedQueryString); - - for (const key in parsedQueryString) { - const value = parsedQueryString[key]; - if (value === '' || value == null) { - throw new MongoParseError('Incomplete key value pair for option'); - } - - const normalizedKey = key.toLowerCase(); - const parsedValue = parseQueryStringItemValue(normalizedKey, value); - applyConnectionStringOption(result, normalizedKey, parsedValue, options); - } - - // special cases for known deprecated options - if (result.wtimeout && result.wtimeoutms) { - delete result.wtimeout; - console.warn('Unsupported option `wtimeout` specified'); - } - - return Object.keys(result).length ? result : null; -} - -/// Adds support for modern `tls` variants of out `ssl` options -function translateTLSOptions(queryString) { - if (queryString.tls) { - queryString.ssl = queryString.tls; - } - - if (queryString.tlsInsecure) { - queryString.checkServerIdentity = false; - queryString.sslValidate = false; - } else { - Object.assign(queryString, { - checkServerIdentity: queryString.tlsAllowInvalidHostnames ? false : true, - sslValidate: queryString.tlsAllowInvalidCertificates ? false : true - }); - } - - if (queryString.tlsCAFile) { - queryString.ssl = true; - queryString.sslCA = queryString.tlsCAFile; - } - - if (queryString.tlsCertificateKeyFile) { - queryString.ssl = true; - if (queryString.tlsCertificateFile) { - queryString.sslCert = queryString.tlsCertificateFile; - queryString.sslKey = queryString.tlsCertificateKeyFile; - } else { - queryString.sslKey = queryString.tlsCertificateKeyFile; - queryString.sslCert = queryString.tlsCertificateKeyFile; - } - } - - if (queryString.tlsCertificateKeyFilePassword) { - queryString.ssl = true; - queryString.sslPass = queryString.tlsCertificateKeyFilePassword; - } - - return queryString; -} - -/** - * Checks a query string for invalid tls options according to the URI options spec. - * - * @param {string} queryString The query string to check - * @throws {MongoParseError} - */ -function checkTLSOptions(queryString) { - const queryStringKeys = Object.keys(queryString); - if ( - queryStringKeys.indexOf('tlsInsecure') !== -1 && - (queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 || - queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1) - ) { - throw new MongoParseError( - 'The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.' - ); - } - - const tlsValue = assertTlsOptionsAreEqual('tls', queryString, queryStringKeys); - const sslValue = assertTlsOptionsAreEqual('ssl', queryString, queryStringKeys); - - if (tlsValue != null && sslValue != null) { - if (tlsValue !== sslValue) { - throw new MongoParseError('All values of `tls` and `ssl` must be the same.'); - } - } -} - -/** - * Checks a query string to ensure all tls/ssl options are the same. - * - * @param {string} key The key (tls or ssl) to check - * @param {string} queryString The query string to check - * @throws {MongoParseError} - * @return The value of the tls/ssl option - */ -function assertTlsOptionsAreEqual(optionName, queryString, queryStringKeys) { - const queryStringHasTLSOption = queryStringKeys.indexOf(optionName) !== -1; - - let optionValue; - if (Array.isArray(queryString[optionName])) { - optionValue = queryString[optionName][0]; - } else { - optionValue = queryString[optionName]; - } - - if (queryStringHasTLSOption) { - if (Array.isArray(queryString[optionName])) { - const firstValue = queryString[optionName][0]; - queryString[optionName].forEach(tlsValue => { - if (tlsValue !== firstValue) { - throw new MongoParseError(`All values of ${optionName} must be the same.`); - } - }); - } - } - - return optionValue; -} - -const PROTOCOL_MONGODB = 'mongodb'; -const PROTOCOL_MONGODB_SRV = 'mongodb+srv'; -const SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV]; - -/** - * Parses a MongoDB connection string - * - * @param {*} uri the MongoDB connection string to parse - * @param {object} [options] Optional settings. - * @param {boolean} [options.caseTranslate] Whether the parser should translate options back into camelCase after normalization - * @param {parseCallback} callback - */ -function parseConnectionString(uri, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { caseTranslate: true }, options); - - // Check for bad uris before we parse - try { - URL.parse(uri); - } catch (e) { - return callback(new MongoParseError('URI malformed, cannot be parsed')); - } - - const cap = uri.match(HOSTS_RX); - if (!cap) { - return callback(new MongoParseError('Invalid connection string')); - } - - const protocol = cap[1]; - if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) { - return callback(new MongoParseError('Invalid protocol provided')); - } - - if (protocol === PROTOCOL_MONGODB_SRV) { - return parseSrvConnectionString(uri, options, callback); - } - - const dbAndQuery = cap[4].split('?'); - const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null; - const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null; - - let parsedOptions; - try { - parsedOptions = parseQueryString(query, options); - } catch (parseError) { - return callback(parseError); - } - - parsedOptions = Object.assign({}, parsedOptions, options); - const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null }; - if (parsedOptions.auth) { - // maintain support for legacy options passed into `MongoClient` - if (parsedOptions.auth.username) auth.username = parsedOptions.auth.username; - if (parsedOptions.auth.user) auth.username = parsedOptions.auth.user; - if (parsedOptions.auth.password) auth.password = parsedOptions.auth.password; - } else { - if (parsedOptions.username) auth.username = parsedOptions.username; - if (parsedOptions.user) auth.username = parsedOptions.user; - if (parsedOptions.password) auth.password = parsedOptions.password; - } - - if (cap[4].split('?')[0].indexOf('@') !== -1) { - return callback(new MongoParseError('Unescaped slash in userinfo section')); - } - - const authorityParts = cap[3].split('@'); - if (authorityParts.length > 2) { - return callback(new MongoParseError('Unescaped at-sign in authority section')); - } - - if (authorityParts[0] == null || authorityParts[0] === '') { - return callback(new MongoParseError('No username provided in authority section')); - } - - if (authorityParts.length > 1) { - const authParts = authorityParts.shift().split(':'); - if (authParts.length > 2) { - return callback(new MongoParseError('Unescaped colon in authority section')); - } - - if (authParts[0] === '') { - return callback(new MongoParseError('Invalid empty username provided')); - } - - if (!auth.username) auth.username = qs.unescape(authParts[0]); - if (!auth.password) auth.password = authParts[1] ? qs.unescape(authParts[1]) : null; - } - - let hostParsingError = null; - const hosts = authorityParts - .shift() - .split(',') - .map(host => { - let parsedHost = URL.parse(`mongodb://${host}`); - if (parsedHost.path === '/:') { - hostParsingError = new MongoParseError('Double colon in host identifier'); - return null; - } - - // heuristically determine if we're working with a domain socket - if (host.match(/\.sock/)) { - parsedHost.hostname = qs.unescape(host); - parsedHost.port = null; - } - - if (Number.isNaN(parsedHost.port)) { - hostParsingError = new MongoParseError('Invalid port (non-numeric string)'); - return; - } - - const result = { - host: parsedHost.hostname, - port: parsedHost.port ? parseInt(parsedHost.port) : 27017 - }; - - if (result.port === 0) { - hostParsingError = new MongoParseError('Invalid port (zero) with hostname'); - return; - } - - if (result.port > 65535) { - hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname'); - return; - } - - if (result.port < 0) { - hostParsingError = new MongoParseError('Invalid port (negative number)'); - return; - } - - return result; - }) - .filter(host => !!host); - - if (hostParsingError) { - return callback(hostParsingError); - } - - if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) { - return callback(new MongoParseError('No hostname or hostnames provided in connection string')); - } - - const result = { - hosts: hosts, - auth: auth.db || auth.username ? auth : null, - options: Object.keys(parsedOptions).length ? parsedOptions : null - }; - - if (result.auth && result.auth.db) { - result.defaultDatabase = result.auth.db; - } else { - result.defaultDatabase = 'test'; - } - - // support modern `tls` variants to SSL options - result.options = translateTLSOptions(result.options); - - try { - applyAuthExpectations(result); - } catch (authError) { - return callback(authError); - } - - callback(null, result); -} - -module.exports = parseConnectionString; diff --git a/node_modules/mongodb/lib/core/utils.js b/node_modules/mongodb/lib/core/utils.js deleted file mode 100644 index 8250883..0000000 --- a/node_modules/mongodb/lib/core/utils.js +++ /dev/null @@ -1,279 +0,0 @@ -'use strict'; -const os = require('os'); -const crypto = require('crypto'); -const requireOptional = require('require_optional'); - -/** - * Generate a UUIDv4 - */ -const uuidV4 = () => { - const result = crypto.randomBytes(16); - result[6] = (result[6] & 0x0f) | 0x40; - result[8] = (result[8] & 0x3f) | 0x80; - return result; -}; - -/** - * Returns the duration calculated from two high resolution timers in milliseconds - * - * @param {Object} started A high resolution timestamp created from `process.hrtime()` - * @returns {Number} The duration in milliseconds - */ -const calculateDurationInMs = started => { - const hrtime = process.hrtime(started); - return (hrtime[0] * 1e9 + hrtime[1]) / 1e6; -}; - -/** - * Relays events for a given listener and emitter - * - * @param {EventEmitter} listener the EventEmitter to listen to the events from - * @param {EventEmitter} emitter the EventEmitter to relay the events to - */ -function relayEvents(listener, emitter, events) { - events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); -} - -function retrieveKerberos() { - let kerberos; - - try { - kerberos = requireOptional('kerberos'); - } catch (err) { - if (err.code === 'MODULE_NOT_FOUND') { - throw new Error('The `kerberos` module was not found. Please install it and try again.'); - } - - throw err; - } - - return kerberos; -} - -// Throw an error if an attempt to use EJSON is made when it is not installed -const noEJSONError = function() { - throw new Error('The `mongodb-extjson` module was not found. Please install it and try again.'); -}; - -// Facilitate loading EJSON optionally -function retrieveEJSON() { - let EJSON = null; - try { - EJSON = requireOptional('mongodb-extjson'); - } catch (error) {} // eslint-disable-line - if (!EJSON) { - EJSON = { - parse: noEJSONError, - deserialize: noEJSONError, - serialize: noEJSONError, - stringify: noEJSONError, - setBSONModule: noEJSONError, - BSON: noEJSONError - }; - } - - return EJSON; -} - -/** - * A helper function for determining `maxWireVersion` between legacy and new topology - * instances - * - * @private - * @param {(Topology|Server)} topologyOrServer - */ -function maxWireVersion(topologyOrServer) { - if (topologyOrServer) { - if (topologyOrServer.ismaster) { - return topologyOrServer.ismaster.maxWireVersion; - } - - if (typeof topologyOrServer.lastIsMaster === 'function') { - const lastIsMaster = topologyOrServer.lastIsMaster(); - if (lastIsMaster) { - return lastIsMaster.maxWireVersion; - } - } - - if (topologyOrServer.description) { - return topologyOrServer.description.maxWireVersion; - } - } - - return 0; -} - -/* - * Checks that collation is supported by server. - * - * @param {Server} [server] to check against - * @param {object} [cmd] object where collation may be specified - * @param {function} [callback] callback function - * @return true if server does not support collation - */ -function collationNotSupported(server, cmd) { - return cmd && cmd.collation && maxWireVersion(server) < 5; -} - -/** - * Checks if a given value is a Promise - * - * @param {*} maybePromise - * @return true if the provided value is a Promise - */ -function isPromiseLike(maybePromise) { - return maybePromise && typeof maybePromise.then === 'function'; -} - -/** - * Applies the function `eachFn` to each item in `arr`, in parallel. - * - * @param {array} arr an array of items to asynchronusly iterate over - * @param {function} eachFn A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete. - * @param {function} callback The callback called after every item has been iterated - */ -function eachAsync(arr, eachFn, callback) { - arr = arr || []; - - let idx = 0; - let awaiting = 0; - for (idx = 0; idx < arr.length; ++idx) { - awaiting++; - eachFn(arr[idx], eachCallback); - } - - if (awaiting === 0) { - callback(); - return; - } - - function eachCallback(err) { - awaiting--; - if (err) { - callback(err); - return; - } - - if (idx === arr.length && awaiting <= 0) { - callback(); - } - } -} - -function isUnifiedTopology(topology) { - return topology.description != null; -} - -function arrayStrictEqual(arr, arr2) { - if (!Array.isArray(arr) || !Array.isArray(arr2)) { - return false; - } - - return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]); -} - -function tagsStrictEqual(tags, tags2) { - const tagsKeys = Object.keys(tags); - const tags2Keys = Object.keys(tags2); - return tagsKeys.length === tags2Keys.length && tagsKeys.every(key => tags2[key] === tags[key]); -} - -function errorStrictEqual(lhs, rhs) { - if (lhs === rhs) { - return true; - } - - if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) { - return false; - } - - if (lhs.constructor.name !== rhs.constructor.name) { - return false; - } - - if (lhs.message !== rhs.message) { - return false; - } - - return true; -} - -function makeStateMachine(stateTable) { - return function stateTransition(target, newState) { - const legalStates = stateTable[target.s.state]; - if (legalStates && legalStates.indexOf(newState) < 0) { - throw new TypeError( - `illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]` - ); - } - - target.emit('stateChanged', target.s.state, newState); - target.s.state = newState; - }; -} - -function makeClientMetadata(options) { - options = options || {}; - - const metadata = { - driver: { - name: 'nodejs', - version: require('../../package.json').version - }, - os: { - type: os.type(), - name: process.platform, - architecture: process.arch, - version: os.release() - }, - platform: `'Node.js ${process.version}, ${os.endianness} (${ - options.useUnifiedTopology ? 'unified' : 'legacy' - })` - }; - - // support optionally provided wrapping driver info - if (options.driverInfo) { - if (options.driverInfo.name) { - metadata.driver.name = `${metadata.driver.name}|${options.driverInfo.name}`; - } - - if (options.driverInfo.version) { - metadata.version = `${metadata.driver.version}|${options.driverInfo.version}`; - } - - if (options.driverInfo.platform) { - metadata.platform = `${metadata.platform}|${options.driverInfo.platform}`; - } - } - - if (options.appname) { - // MongoDB requires the appname not exceed a byte length of 128 - const buffer = Buffer.from(options.appname); - metadata.application = { - name: buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname - }; - } - - return metadata; -} - -const noop = () => {}; - -module.exports = { - uuidV4, - calculateDurationInMs, - relayEvents, - collationNotSupported, - retrieveEJSON, - retrieveKerberos, - maxWireVersion, - isPromiseLike, - eachAsync, - isUnifiedTopology, - arrayStrictEqual, - tagsStrictEqual, - errorStrictEqual, - makeStateMachine, - makeClientMetadata, - noop -}; diff --git a/node_modules/mongodb/lib/core/wireprotocol/command.js b/node_modules/mongodb/lib/core/wireprotocol/command.js deleted file mode 100644 index 214385b..0000000 --- a/node_modules/mongodb/lib/core/wireprotocol/command.js +++ /dev/null @@ -1,185 +0,0 @@ -'use strict'; - -const Query = require('../connection/commands').Query; -const Msg = require('../connection/msg').Msg; -const MongoError = require('../error').MongoError; -const getReadPreference = require('./shared').getReadPreference; -const isSharded = require('./shared').isSharded; -const databaseNamespace = require('./shared').databaseNamespace; -const isTransactionCommand = require('../transactions').isTransactionCommand; -const applySession = require('../sessions').applySession; -const MongoNetworkError = require('../error').MongoNetworkError; -const maxWireVersion = require('../utils').maxWireVersion; - -function isClientEncryptionEnabled(server) { - const wireVersion = maxWireVersion(server); - return wireVersion && server.autoEncrypter; -} - -function command(server, ns, cmd, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (cmd == null) { - return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); - } - - if (!isClientEncryptionEnabled(server)) { - _command(server, ns, cmd, options, callback); - return; - } - - const wireVersion = maxWireVersion(server); - if (typeof wireVersion !== 'number' || wireVersion < 8) { - callback(new MongoError('Auto-encryption requires a minimum MongoDB version of 4.2')); - return; - } - - _cryptCommand(server, ns, cmd, options, callback); -} - -function _command(server, ns, cmd, options, callback) { - const bson = server.s.bson; - const pool = server.s.pool; - const readPreference = getReadPreference(cmd, options); - const shouldUseOpMsg = supportsOpMsg(server); - const session = options.session; - - let clusterTime = server.clusterTime; - let finalCmd = Object.assign({}, cmd); - if (hasSessionSupport(server) && session) { - if ( - session.clusterTime && - session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime) - ) { - clusterTime = session.clusterTime; - } - - const err = applySession(session, finalCmd, options); - if (err) { - return callback(err); - } - } - - // if we have a known cluster time, gossip it - if (clusterTime) { - finalCmd.$clusterTime = clusterTime; - } - - if ( - isSharded(server) && - !shouldUseOpMsg && - readPreference && - readPreference.preference !== 'primary' - ) { - finalCmd = { - $query: finalCmd, - $readPreference: readPreference.toJSON() - }; - } - - const commandOptions = Object.assign( - { - command: true, - numberToSkip: 0, - numberToReturn: -1, - checkKeys: false - }, - options - ); - - // This value is not overridable - commandOptions.slaveOk = readPreference.slaveOk(); - - const cmdNs = `${databaseNamespace(ns)}.$cmd`; - const message = shouldUseOpMsg - ? new Msg(bson, cmdNs, finalCmd, commandOptions) - : new Query(bson, cmdNs, finalCmd, commandOptions); - - const inTransaction = session && (session.inTransaction() || isTransactionCommand(finalCmd)); - const commandResponseHandler = inTransaction - ? function(err) { - // We need to add a TransientTransactionError errorLabel, as stated in the transaction spec. - if ( - err && - err instanceof MongoNetworkError && - !err.hasErrorLabel('TransientTransactionError') - ) { - if (err.errorLabels == null) { - err.errorLabels = []; - } - err.errorLabels.push('TransientTransactionError'); - } - - if ( - !cmd.commitTransaction && - err && - err instanceof MongoError && - err.hasErrorLabel('TransientTransactionError') - ) { - session.transaction.unpinServer(); - } - - return callback.apply(null, arguments); - } - : callback; - - try { - pool.write(message, commandOptions, commandResponseHandler); - } catch (err) { - commandResponseHandler(err); - } -} - -function hasSessionSupport(topology) { - if (topology == null) return false; - if (topology.description) { - return topology.description.maxWireVersion >= 6; - } - - return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6; -} - -function supportsOpMsg(topologyOrServer) { - const description = topologyOrServer.ismaster - ? topologyOrServer.ismaster - : topologyOrServer.description; - - if (description == null) { - return false; - } - - return description.maxWireVersion >= 6 && description.__nodejs_mock_server__ == null; -} - -function _cryptCommand(server, ns, cmd, options, callback) { - const autoEncrypter = server.autoEncrypter; - function commandResponseHandler(err, response) { - if (err || response == null) { - callback(err, response); - return; - } - - autoEncrypter.decrypt(response.result, options, (err, decrypted) => { - if (err) { - callback(err, null); - return; - } - - response.result = decrypted; - response.message.documents = [decrypted]; - callback(null, response); - }); - } - - autoEncrypter.encrypt(ns, cmd, options, (err, encrypted) => { - if (err) { - callback(err, null); - return; - } - - _command(server, ns, encrypted, options, commandResponseHandler); - }); -} - -module.exports = command; diff --git a/node_modules/mongodb/lib/core/wireprotocol/compression.js b/node_modules/mongodb/lib/core/wireprotocol/compression.js deleted file mode 100644 index b1e1583..0000000 --- a/node_modules/mongodb/lib/core/wireprotocol/compression.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict'; - -const Snappy = require('../connection/utils').retrieveSnappy(); -const zlib = require('zlib'); - -const compressorIDs = { - snappy: 1, - zlib: 2 -}; - -const uncompressibleCommands = new Set([ - 'ismaster', - 'saslStart', - 'saslContinue', - 'getnonce', - 'authenticate', - 'createUser', - 'updateUser', - 'copydbSaslStart', - 'copydbgetnonce', - 'copydb' -]); - -// Facilitate compressing a message using an agreed compressor -function compress(self, dataToBeCompressed, callback) { - switch (self.options.agreedCompressor) { - case 'snappy': - Snappy.compress(dataToBeCompressed, callback); - break; - case 'zlib': - // Determine zlibCompressionLevel - var zlibOptions = {}; - if (self.options.zlibCompressionLevel) { - zlibOptions.level = self.options.zlibCompressionLevel; - } - zlib.deflate(dataToBeCompressed, zlibOptions, callback); - break; - default: - throw new Error( - 'Attempt to compress message using unknown compressor "' + - self.options.agreedCompressor + - '".' - ); - } -} - -// Decompress a message using the given compressor -function decompress(compressorID, compressedData, callback) { - if (compressorID < 0 || compressorID > compressorIDs.length) { - throw new Error( - 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' + - compressorID + - ')' - ); - } - switch (compressorID) { - case compressorIDs.snappy: - Snappy.uncompress(compressedData, callback); - break; - case compressorIDs.zlib: - zlib.inflate(compressedData, callback); - break; - default: - callback(null, compressedData); - } -} - -module.exports = { - compressorIDs, - uncompressibleCommands, - compress, - decompress -}; diff --git a/node_modules/mongodb/lib/core/wireprotocol/constants.js b/node_modules/mongodb/lib/core/wireprotocol/constants.js deleted file mode 100644 index df2293b..0000000 --- a/node_modules/mongodb/lib/core/wireprotocol/constants.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -const MIN_SUPPORTED_SERVER_VERSION = '2.6'; -const MAX_SUPPORTED_SERVER_VERSION = '4.2'; -const MIN_SUPPORTED_WIRE_VERSION = 2; -const MAX_SUPPORTED_WIRE_VERSION = 8; - -module.exports = { - MIN_SUPPORTED_SERVER_VERSION, - MAX_SUPPORTED_SERVER_VERSION, - MIN_SUPPORTED_WIRE_VERSION, - MAX_SUPPORTED_WIRE_VERSION -}; diff --git a/node_modules/mongodb/lib/core/wireprotocol/get_more.js b/node_modules/mongodb/lib/core/wireprotocol/get_more.js deleted file mode 100644 index b2db320..0000000 --- a/node_modules/mongodb/lib/core/wireprotocol/get_more.js +++ /dev/null @@ -1,90 +0,0 @@ -'use strict'; - -const GetMore = require('../connection/commands').GetMore; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const BSON = retrieveBSON(); -const Long = BSON.Long; -const collectionNamespace = require('./shared').collectionNamespace; -const maxWireVersion = require('../utils').maxWireVersion; -const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; -const command = require('./command'); - -function getMore(server, ns, cursorState, batchSize, options, callback) { - options = options || {}; - - const wireVersion = maxWireVersion(server); - function queryCallback(err, result) { - if (err) return callback(err); - const response = result.message; - - // If we have a timed out query or a cursor that was killed - if (response.cursorNotFound) { - return callback(new MongoNetworkError('cursor killed or timed out'), null); - } - - if (wireVersion < 4) { - const cursorId = - typeof response.cursorId === 'number' - ? Long.fromNumber(response.cursorId) - : response.cursorId; - - cursorState.documents = response.documents; - cursorState.cursorId = cursorId; - - callback(null, null, response.connection); - return; - } - - // We have an error detected - if (response.documents[0].ok === 0) { - return callback(new MongoError(response.documents[0])); - } - - // Ensure we have a Long valid cursor id - const cursorId = - typeof response.documents[0].cursor.id === 'number' - ? Long.fromNumber(response.documents[0].cursor.id) - : response.documents[0].cursor.id; - - cursorState.documents = response.documents[0].cursor.nextBatch; - cursorState.cursorId = cursorId; - - callback(null, response.documents[0], response.connection); - } - - if (wireVersion < 4) { - const bson = server.s.bson; - const getMoreOp = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize }); - const queryOptions = applyCommonQueryOptions({}, cursorState); - server.s.pool.write(getMoreOp, queryOptions, queryCallback); - return; - } - - const getMoreCmd = { - getMore: cursorState.cursorId, - collection: collectionNamespace(ns), - batchSize: Math.abs(batchSize) - }; - - if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') { - getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; - } - - const commandOptions = Object.assign( - { - returnFieldSelector: null, - documentsReturnedIn: 'nextBatch' - }, - options - ); - - if (cursorState.session) { - commandOptions.session = cursorState.session; - } - - command(server, ns, getMoreCmd, commandOptions, queryCallback); -} - -module.exports = getMore; diff --git a/node_modules/mongodb/lib/core/wireprotocol/index.js b/node_modules/mongodb/lib/core/wireprotocol/index.js deleted file mode 100644 index b6ffda7..0000000 --- a/node_modules/mongodb/lib/core/wireprotocol/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; -const writeCommand = require('./write_command'); - -module.exports = { - insert: function insert(server, ns, ops, options, callback) { - writeCommand(server, 'insert', 'documents', ns, ops, options, callback); - }, - update: function update(server, ns, ops, options, callback) { - writeCommand(server, 'update', 'updates', ns, ops, options, callback); - }, - remove: function remove(server, ns, ops, options, callback) { - writeCommand(server, 'delete', 'deletes', ns, ops, options, callback); - }, - killCursors: require('./kill_cursors'), - getMore: require('./get_more'), - query: require('./query'), - command: require('./command') -}; diff --git a/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js b/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js deleted file mode 100644 index bb13477..0000000 --- a/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js +++ /dev/null @@ -1,70 +0,0 @@ -'use strict'; - -const KillCursor = require('../connection/commands').KillCursor; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const collectionNamespace = require('./shared').collectionNamespace; -const maxWireVersion = require('../utils').maxWireVersion; -const command = require('./command'); - -function killCursors(server, ns, cursorState, callback) { - callback = typeof callback === 'function' ? callback : () => {}; - const cursorId = cursorState.cursorId; - - if (maxWireVersion(server) < 4) { - const bson = server.s.bson; - const pool = server.s.pool; - const killCursor = new KillCursor(bson, ns, [cursorId]); - const options = { - immediateRelease: true, - noResponse: true - }; - - if (typeof cursorState.session === 'object') { - options.session = cursorState.session; - } - - if (pool && pool.isConnected()) { - try { - pool.write(killCursor, options, callback); - } catch (err) { - if (typeof callback === 'function') { - callback(err, null); - } else { - console.warn(err); - } - } - } - - return; - } - - const killCursorCmd = { - killCursors: collectionNamespace(ns), - cursors: [cursorId] - }; - - const options = {}; - if (typeof cursorState.session === 'object') options.session = cursorState.session; - - command(server, ns, killCursorCmd, options, (err, result) => { - if (err) { - return callback(err); - } - - const response = result.message; - if (response.cursorNotFound) { - return callback(new MongoNetworkError('cursor killed or timed out'), null); - } - - if (!Array.isArray(response.documents) || response.documents.length === 0) { - return callback( - new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`) - ); - } - - callback(null, response.documents[0]); - }); -} - -module.exports = killCursors; diff --git a/node_modules/mongodb/lib/core/wireprotocol/query.js b/node_modules/mongodb/lib/core/wireprotocol/query.js deleted file mode 100644 index c501b50..0000000 --- a/node_modules/mongodb/lib/core/wireprotocol/query.js +++ /dev/null @@ -1,231 +0,0 @@ -'use strict'; - -const Query = require('../connection/commands').Query; -const MongoError = require('../error').MongoError; -const getReadPreference = require('./shared').getReadPreference; -const collectionNamespace = require('./shared').collectionNamespace; -const isSharded = require('./shared').isSharded; -const maxWireVersion = require('../utils').maxWireVersion; -const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; -const command = require('./command'); - -function query(server, ns, cmd, cursorState, options, callback) { - options = options || {}; - if (cursorState.cursorId != null) { - return callback(); - } - - if (cmd == null) { - return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); - } - - if (maxWireVersion(server) < 4) { - const query = prepareLegacyFindQuery(server, ns, cmd, cursorState, options); - const queryOptions = applyCommonQueryOptions({}, cursorState); - if (typeof query.documentsReturnedIn === 'string') { - queryOptions.documentsReturnedIn = query.documentsReturnedIn; - } - - server.s.pool.write(query, queryOptions, callback); - return; - } - - const readPreference = getReadPreference(cmd, options); - const findCmd = prepareFindCommand(server, ns, cmd, cursorState, options); - - // NOTE: This actually modifies the passed in cmd, and our code _depends_ on this - // side-effect. Change this ASAP - cmd.virtual = false; - - const commandOptions = Object.assign( - { - documentsReturnedIn: 'firstBatch', - numberToReturn: 1, - slaveOk: readPreference.slaveOk() - }, - options - ); - - if (cmd.readPreference) { - commandOptions.readPreference = readPreference; - } - - if (cursorState.session) { - commandOptions.session = cursorState.session; - } - - command(server, ns, findCmd, commandOptions, callback); -} - -function prepareFindCommand(server, ns, cmd, cursorState) { - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - let findCmd = { - find: collectionNamespace(ns) - }; - - if (cmd.query) { - if (cmd.query['$query']) { - findCmd.filter = cmd.query['$query']; - } else { - findCmd.filter = cmd.query; - } - } - - let sortValue = cmd.sort; - if (Array.isArray(sortValue)) { - const sortObject = {}; - - if (sortValue.length > 0 && !Array.isArray(sortValue[0])) { - let sortDirection = sortValue[1]; - if (sortDirection === 'asc') { - sortDirection = 1; - } else if (sortDirection === 'desc') { - sortDirection = -1; - } - - sortObject[sortValue[0]] = sortDirection; - } else { - for (let i = 0; i < sortValue.length; i++) { - let sortDirection = sortValue[i][1]; - if (sortDirection === 'asc') { - sortDirection = 1; - } else if (sortDirection === 'desc') { - sortDirection = -1; - } - - sortObject[sortValue[i][0]] = sortDirection; - } - } - - sortValue = sortObject; - } - - if (cmd.sort) findCmd.sort = sortValue; - if (cmd.fields) findCmd.projection = cmd.fields; - if (cmd.hint) findCmd.hint = cmd.hint; - if (cmd.skip) findCmd.skip = cmd.skip; - if (cmd.limit) findCmd.limit = cmd.limit; - if (cmd.limit < 0) { - findCmd.limit = Math.abs(cmd.limit); - findCmd.singleBatch = true; - } - - if (typeof cmd.batchSize === 'number') { - if (cmd.batchSize < 0) { - if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) { - findCmd.limit = Math.abs(cmd.batchSize); - } - - findCmd.singleBatch = true; - } - - findCmd.batchSize = Math.abs(cmd.batchSize); - } - - if (cmd.comment) findCmd.comment = cmd.comment; - if (cmd.maxScan) findCmd.maxScan = cmd.maxScan; - if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; - if (cmd.min) findCmd.min = cmd.min; - if (cmd.max) findCmd.max = cmd.max; - findCmd.returnKey = cmd.returnKey ? cmd.returnKey : false; - findCmd.showRecordId = cmd.showDiskLoc ? cmd.showDiskLoc : false; - if (cmd.snapshot) findCmd.snapshot = cmd.snapshot; - if (cmd.tailable) findCmd.tailable = cmd.tailable; - if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; - if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; - if (cmd.awaitData) findCmd.awaitData = cmd.awaitData; - if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; - if (cmd.partial) findCmd.partial = cmd.partial; - if (cmd.collation) findCmd.collation = cmd.collation; - if (cmd.readConcern) findCmd.readConcern = cmd.readConcern; - - // If we have explain, we need to rewrite the find command - // to wrap it in the explain command - if (cmd.explain) { - findCmd = { - explain: findCmd - }; - } - - return findCmd; -} - -function prepareLegacyFindQuery(server, ns, cmd, cursorState, options) { - options = options || {}; - const bson = server.s.bson; - const readPreference = getReadPreference(cmd, options); - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - - let numberToReturn = 0; - if ( - cursorState.limit < 0 || - (cursorState.limit !== 0 && cursorState.limit < cursorState.batchSize) || - (cursorState.limit > 0 && cursorState.batchSize === 0) - ) { - numberToReturn = cursorState.limit; - } else { - numberToReturn = cursorState.batchSize; - } - - const numberToSkip = cursorState.skip || 0; - - const findCmd = {}; - if (isSharded(server) && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - } - - if (cmd.sort) findCmd['$orderby'] = cmd.sort; - if (cmd.hint) findCmd['$hint'] = cmd.hint; - if (cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot; - if (typeof cmd.returnKey !== 'undefined') findCmd['$returnKey'] = cmd.returnKey; - if (cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan; - if (cmd.min) findCmd['$min'] = cmd.min; - if (cmd.max) findCmd['$max'] = cmd.max; - if (typeof cmd.showDiskLoc !== 'undefined') findCmd['$showDiskLoc'] = cmd.showDiskLoc; - if (cmd.comment) findCmd['$comment'] = cmd.comment; - if (cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS; - if (cmd.explain) { - // nToReturn must be 0 (match all) or negative (match N and close cursor) - // nToReturn > 0 will give explain results equivalent to limit(0) - numberToReturn = -Math.abs(cmd.limit || 0); - findCmd['$explain'] = true; - } - - findCmd['$query'] = cmd.query; - if (cmd.readConcern && cmd.readConcern.level !== 'local') { - throw new MongoError( - `server find command does not support a readConcern level of ${cmd.readConcern.level}` - ); - } - - if (cmd.readConcern) { - cmd = Object.assign({}, cmd); - delete cmd['readConcern']; - } - - const serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - - const query = new Query(bson, ns, findCmd, { - numberToSkip: numberToSkip, - numberToReturn: numberToReturn, - pre32Limit: typeof cmd.limit !== 'undefined' ? cmd.limit : undefined, - checkKeys: false, - returnFieldSelector: cmd.fields, - serializeFunctions: serializeFunctions, - ignoreUndefined: ignoreUndefined - }); - - if (typeof cmd.tailable === 'boolean') query.tailable = cmd.tailable; - if (typeof cmd.oplogReplay === 'boolean') query.oplogReplay = cmd.oplogReplay; - if (typeof cmd.noCursorTimeout === 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; - if (typeof cmd.awaitData === 'boolean') query.awaitData = cmd.awaitData; - if (typeof cmd.partial === 'boolean') query.partial = cmd.partial; - - query.slaveOk = readPreference.slaveOk(); - return query; -} - -module.exports = query; diff --git a/node_modules/mongodb/lib/core/wireprotocol/shared.js b/node_modules/mongodb/lib/core/wireprotocol/shared.js deleted file mode 100644 index c586f05..0000000 --- a/node_modules/mongodb/lib/core/wireprotocol/shared.js +++ /dev/null @@ -1,115 +0,0 @@ -'use strict'; - -const ReadPreference = require('../topologies/read_preference'); -const MongoError = require('../error').MongoError; -const ServerType = require('../sdam/common').ServerType; -const TopologyDescription = require('../sdam/topology_description').TopologyDescription; - -const MESSAGE_HEADER_SIZE = 16; -const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID - -// OPCODE Numbers -// Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes -var opcodes = { - OP_REPLY: 1, - OP_UPDATE: 2001, - OP_INSERT: 2002, - OP_QUERY: 2004, - OP_GETMORE: 2005, - OP_DELETE: 2006, - OP_KILL_CURSORS: 2007, - OP_COMPRESSED: 2012, - OP_MSG: 2013 -}; - -var getReadPreference = function(cmd, options) { - // Default to command version of the readPreference - var readPreference = cmd.readPreference || new ReadPreference('primary'); - // If we have an option readPreference override the command one - if (options.readPreference) { - readPreference = options.readPreference; - } - - if (typeof readPreference === 'string') { - readPreference = new ReadPreference(readPreference); - } - - if (!(readPreference instanceof ReadPreference)) { - throw new MongoError('read preference must be a ReadPreference instance'); - } - - return readPreference; -}; - -// Parses the header of a wire protocol message -var parseHeader = function(message) { - return { - length: message.readInt32LE(0), - requestId: message.readInt32LE(4), - responseTo: message.readInt32LE(8), - opCode: message.readInt32LE(12) - }; -}; - -function applyCommonQueryOptions(queryOptions, options) { - Object.assign(queryOptions, { - raw: typeof options.raw === 'boolean' ? options.raw : false, - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, - monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, - fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false - }); - - if (typeof options.socketTimeout === 'number') { - queryOptions.socketTimeout = options.socketTimeout; - } - - if (options.session) { - queryOptions.session = options.session; - } - - if (typeof options.documentsReturnedIn === 'string') { - queryOptions.documentsReturnedIn = options.documentsReturnedIn; - } - - return queryOptions; -} - -function isSharded(topologyOrServer) { - if (topologyOrServer.type === 'mongos') return true; - if (topologyOrServer.description && topologyOrServer.description.type === ServerType.Mongos) { - return true; - } - - // NOTE: This is incredibly inefficient, and should be removed once command construction - // happens based on `Server` not `Topology`. - if (topologyOrServer.description && topologyOrServer.description instanceof TopologyDescription) { - const servers = Array.from(topologyOrServer.description.servers.values()); - return servers.some(server => server.type === ServerType.Mongos); - } - - return false; -} - -function databaseNamespace(ns) { - return ns.split('.')[0]; -} -function collectionNamespace(ns) { - return ns - .split('.') - .slice(1) - .join('.'); -} - -module.exports = { - getReadPreference, - MESSAGE_HEADER_SIZE, - COMPRESSION_DETAILS_SIZE, - opcodes, - parseHeader, - applyCommonQueryOptions, - isSharded, - databaseNamespace, - collectionNamespace -}; diff --git a/node_modules/mongodb/lib/core/wireprotocol/write_command.js b/node_modules/mongodb/lib/core/wireprotocol/write_command.js deleted file mode 100644 index e334d51..0000000 --- a/node_modules/mongodb/lib/core/wireprotocol/write_command.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -const MongoError = require('../error').MongoError; -const collectionNamespace = require('./shared').collectionNamespace; -const command = require('./command'); - -function writeCommand(server, type, opsField, ns, ops, options, callback) { - if (ops.length === 0) throw new MongoError(`${type} must contain at least one document`); - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; - const writeConcern = options.writeConcern; - - const writeCommand = {}; - writeCommand[type] = collectionNamespace(ns); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - - if (writeConcern && Object.keys(writeConcern).length > 0) { - writeCommand.writeConcern = writeConcern; - } - - if (options.collation) { - for (let i = 0; i < writeCommand[opsField].length; i++) { - if (!writeCommand[opsField][i].collation) { - writeCommand[opsField][i].collation = options.collation; - } - } - } - - if (options.bypassDocumentValidation === true) { - writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; - } - - const commandOptions = Object.assign( - { - checkKeys: type === 'insert', - numberToReturn: 1 - }, - options - ); - - command(server, ns, writeCommand, commandOptions, callback); -} - -module.exports = writeCommand; diff --git a/node_modules/mongodb/lib/cursor.js b/node_modules/mongodb/lib/cursor.js deleted file mode 100644 index 4d7cdcf..0000000 --- a/node_modules/mongodb/lib/cursor.js +++ /dev/null @@ -1,1136 +0,0 @@ -'use strict'; - -const Transform = require('stream').Transform; -const PassThrough = require('stream').PassThrough; -const deprecate = require('util').deprecate; -const handleCallback = require('./utils').handleCallback; -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const CoreCursor = require('./core/cursor').CoreCursor; -const CursorState = require('./core/cursor').CursorState; -const Map = require('./core').BSON.Map; -const maybePromise = require('./utils').maybePromise; -const executeOperation = require('./operations/execute_operation'); -const formattedOrderClause = require('./utils').formattedOrderClause; - -const each = require('./operations/cursor_ops').each; -const CountOperation = require('./operations/count'); - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 4.X - * or higher stream - * - * **CURSORS Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the code module - * @external CoreCursor - * @external Readable - */ - -// Flags allowed for cursor -const flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; -const fields = ['numberOfRetries', 'tailableRetryInterval']; - -/** - * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class Cursor - * @extends external:CoreCursor - * @extends external:Readable - * @property {string} sortValue Cursor query sort setting. - * @property {boolean} timeout Is Cursor able to time out. - * @property {ReadPreference} readPreference Get cursor ReadPreference. - * @fires Cursor#data - * @fires Cursor#end - * @fires Cursor#close - * @fires Cursor#readable - * @return {Cursor} a Cursor instance. - * @example - * Cursor cursor options. - * - * collection.find({}).project({a:1}) // Create a projection of field a - * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 - * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 - * collection.find({}).filter({a:1}) // Set query on the cursor - * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries - * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable - * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay - * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout - * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData - * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial - * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} - * collection.find({}).max(10) // Set the cursor max - * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS - * collection.find({}).min(100) // Set the cursor min - * collection.find({}).returnKey(true) // Set the cursor returnKey - * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference - * collection.find({}).showRecordId(true) // Set the cursor showRecordId - * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query - * collection.find({}).hint('a_1') // Set the cursor hint - * - * All options are chainable, so one can do the following. - * - * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) - */ -class Cursor extends CoreCursor { - constructor(topology, ns, cmd, options) { - super(topology, ns, cmd, options); - if (this.operation) { - options = this.operation.options; - } - - // Tailable cursor options - const numberOfRetries = options.numberOfRetries || 5; - const tailableRetryInterval = options.tailableRetryInterval || 500; - const currentNumberOfRetries = numberOfRetries; - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Internal cursor state - this.s = { - // Tailable cursor options - numberOfRetries: numberOfRetries, - tailableRetryInterval: tailableRetryInterval, - currentNumberOfRetries: currentNumberOfRetries, - // State - state: CursorState.INIT, - // Promise library - promiseLibrary, - // explicitlyIgnoreSession - explicitlyIgnoreSession: !!options.explicitlyIgnoreSession - }; - - // Optional ClientSession - if (!options.explicitlyIgnoreSession && options.session) { - this.cursorState.session = options.session; - } - - // Translate correctly - if (this.options.noCursorTimeout === true) { - this.addCursorFlag('noCursorTimeout', true); - } - - // Get the batchSize - let batchSize = 1000; - if (this.cmd.cursor && this.cmd.cursor.batchSize) { - batchSize = this.cmd.cursor.batchSize; - } else if (options.cursor && options.cursor.batchSize) { - batchSize = options.cursor.batchSize; - } else if (typeof options.batchSize === 'number') { - batchSize = options.batchSize; - } - - // Set the batchSize - this.setCursorBatchSize(batchSize); - } - - get readPreference() { - if (this.operation) { - return this.operation.readPreference; - } - - return this.options.readPreference; - } - - get sortValue() { - return this.cmd.sort; - } - - _initializeCursor(callback) { - if (this.operation && this.operation.session != null) { - this.cursorState.session = this.operation.session; - } else { - // implicitly create a session if one has not been provided - if ( - !this.s.explicitlyIgnoreSession && - !this.cursorState.session && - this.topology.hasSessionSupport() - ) { - this.cursorState.session = this.topology.startSession({ owner: this }); - - if (this.operation) { - this.operation.session = this.cursorState.session; - } - } - } - - super._initializeCursor(callback); - } - - /** - * Check if there is any document still available in the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - hasNext(callback) { - if (this.s.state === CursorState.CLOSED || (this.isDead && this.isDead())) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - return maybePromise(this, callback, cb => { - const cursor = this; - if (cursor.isNotified()) { - return cb(null, false); - } - - cursor._next((err, doc) => { - if (err) return cb(err); - if (doc == null || cursor.s.state === Cursor.CLOSED || cursor.isDead()) { - return cb(null, false); - } - - cursor.s.state = CursorState.OPEN; - - // NODE-2482: merge this into the core cursor implementation - cursor.cursorState.cursorIndex--; - if (cursor.cursorState.limit > 0) { - cursor.cursorState.currentLimit--; - } - - cb(null, true); - }); - }); - } - - /** - * Get the next available document from the cursor, returns null if no more documents are available. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - next(callback) { - return maybePromise(this, callback, cb => { - const cursor = this; - if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) { - cb(MongoError.create({ message: 'Cursor is closed', driver: true })); - return; - } - - if (cursor.s.state === CursorState.INIT && cursor.cmd.sort) { - try { - cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); - } catch (err) { - return cb(err); - } - } - - cursor._next((err, doc) => { - if (err) return cb(err); - cursor.s.state = CursorState.OPEN; - cb(null, doc); - }); - }); - } - - /** - * Set the cursor query - * @method - * @param {object} filter The filter object used for the cursor. - * @return {Cursor} - */ - filter(filter) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.query = filter; - return this; - } - - /** - * Set the cursor maxScan - * @method - * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query - * @deprecated as of MongoDB 4.0 - * @return {Cursor} - */ - maxScan(maxScan) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxScan = maxScan; - return this; - } - - /** - * Set the cursor hint - * @method - * @param {object} hint If specified, then the query system will only consider plans using the hinted index. - * @return {Cursor} - */ - hint(hint) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.hint = hint; - return this; - } - - /** - * Set the cursor min - * @method - * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. - * @return {Cursor} - */ - min(min) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.min = min; - return this; - } - - /** - * Set the cursor max - * @method - * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. - * @return {Cursor} - */ - max(max) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.max = max; - return this; - } - - /** - * Set the cursor returnKey. If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. - * @method - * @param {bool} returnKey the returnKey value. - * @return {Cursor} - */ - returnKey(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.returnKey = value; - return this; - } - - /** - * Set the cursor showRecordId - * @method - * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. - * @return {Cursor} - */ - showRecordId(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.showDiskLoc = value; - return this; - } - - /** - * Set the cursor snapshot - * @method - * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. - * @deprecated as of MongoDB 4.0 - * @return {Cursor} - */ - snapshot(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.snapshot = value; - return this; - } - - /** - * Set a node.js specific cursor option - * @method - * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. - * @param {object} value The field value. - * @throws {MongoError} - * @return {Cursor} - */ - setCursorOption(field, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (fields.indexOf(field) === -1) { - throw MongoError.create({ - message: `option ${field} is not a supported option ${fields}`, - driver: true - }); - } - - this.s[field] = value; - if (field === 'numberOfRetries') this.s.currentNumberOfRetries = value; - return this; - } - - /** - * Add a cursor flag to the cursor - * @method - * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial']. - * @param {boolean} value The flag boolean value. - * @throws {MongoError} - * @return {Cursor} - */ - addCursorFlag(flag, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (flags.indexOf(flag) === -1) { - throw MongoError.create({ - message: `flag ${flag} is not a supported flag ${flags}`, - driver: true - }); - } - - if (typeof value !== 'boolean') { - throw MongoError.create({ message: `flag ${flag} must be a boolean value`, driver: true }); - } - - this.cmd[flag] = value; - return this; - } - - /** - * Add a query modifier to the cursor query - * @method - * @param {string} name The query modifier (must start with $, such as $orderby etc) - * @param {string|boolean|number} value The modifier value. - * @throws {MongoError} - * @return {Cursor} - */ - addQueryModifier(name, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (name[0] !== '$') { - throw MongoError.create({ message: `${name} is not a valid query modifier`, driver: true }); - } - - // Strip of the $ - const field = name.substr(1); - // Set on the command - this.cmd[field] = value; - // Deal with the special case for sort - if (field === 'orderby') this.cmd.sort = this.cmd[field]; - return this; - } - - /** - * Add a comment to the cursor query allowing for tracking the comment in the log. - * @method - * @param {string} value The comment attached to this query. - * @throws {MongoError} - * @return {Cursor} - */ - comment(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.comment = value; - return this; - } - - /** - * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) - * @method - * @param {number} value Number of milliseconds to wait before aborting the tailed query. - * @throws {MongoError} - * @return {Cursor} - */ - maxAwaitTimeMS(value) { - if (typeof value !== 'number') { - throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxAwaitTimeMS = value; - return this; - } - - /** - * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) - * @method - * @param {number} value Number of milliseconds to wait before aborting the query. - * @throws {MongoError} - * @return {Cursor} - */ - maxTimeMS(value) { - if (typeof value !== 'number') { - throw MongoError.create({ message: 'maxTimeMS must be a number', driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxTimeMS = value; - return this; - } - - /** - * Sets a field projection for the query. - * @method - * @param {object} value The field projection object. - * @throws {MongoError} - * @return {Cursor} - */ - project(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.fields = value; - return this; - } - - /** - * Sets the sort order of the cursor query. - * @method - * @param {(string|array|object)} keyOrList The key or keys set for the sort. - * @param {number} [direction] The direction of the sorting (1 or -1). - * @throws {MongoError} - * @return {Cursor} - */ - sort(keyOrList, direction) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support sorting", driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - let order = keyOrList; - - // We have an array of arrays, we need to preserve the order of the sort - // so we will us a Map - if (Array.isArray(order) && Array.isArray(order[0])) { - order = new Map( - order.map(x => { - const value = [x[0], null]; - if (x[1] === 'asc') { - value[1] = 1; - } else if (x[1] === 'desc') { - value[1] = -1; - } else if (x[1] === 1 || x[1] === -1 || x[1].$meta) { - value[1] = x[1]; - } else { - throw new MongoError( - "Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" - ); - } - - return value; - }) - ); - } - - if (direction != null) { - order = [[keyOrList, direction]]; - } - - this.cmd.sort = order; - return this; - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. - * @throws {MongoError} - * @return {Cursor} - */ - batchSize(value) { - if (this.options.tailable) { - throw MongoError.create({ - message: "Tailable cursor doesn't support batchSize", - driver: true - }); - } - - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - this.cmd.batchSize = value; - this.setCursorBatchSize(value); - return this; - } - - /** - * Set the collation options for the cursor. - * @method - * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @throws {MongoError} - * @return {Cursor} - */ - collation(value) { - this.cmd.collation = value; - return this; - } - - /** - * Set the limit for the cursor. - * @method - * @param {number} value The limit for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ - limit(value) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support limit", driver: true }); - } - - if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'limit requires an integer', driver: true }); - } - - this.cmd.limit = value; - this.setCursorLimit(value); - return this; - } - - /** - * Set the skip for the cursor. - * @method - * @param {number} value The skip for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ - skip(value) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support skip", driver: true }); - } - - if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'skip requires an integer', driver: true }); - } - - this.cmd.skip = value; - this.setCursorSkip(value); - return this; - } - - /** - * The callback format for results - * @callback Cursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null|boolean)} result The result object if the command was executed successfully. - */ - - /** - * Clone the cursor - * @function external:CoreCursor#clone - * @return {Cursor} - */ - - /** - * Resets the cursor - * @function external:CoreCursor#rewind - * @return {null} - */ - - /** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method - * @deprecated - * @param {Cursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - each(callback) { - // Rewind cursor state - this.rewind(); - // Set current cursor to INIT - this.s.state = CursorState.INIT; - // Run the query - each(this, callback); - } - - /** - * The callback format for the forEach iterator method - * @callback Cursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - - /** - * The callback error format for the forEach iterator method - * @callback Cursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - - /** - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method - * @param {Cursor~iteratorCallback} iterator The iteration callback. - * @param {Cursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {Promise} if no callback supplied - */ - forEach(iterator, callback) { - // Rewind cursor state - this.rewind(); - - // Set current cursor to INIT - this.s.state = CursorState.INIT; - - if (typeof callback === 'function') { - each(this, (err, doc) => { - if (err) { - callback(err); - return false; - } - if (doc != null) { - iterator(doc); - return true; - } - if (doc == null && callback) { - const internalCallback = callback; - callback = null; - internalCallback(null); - return false; - } - }); - } else { - return new this.s.promiseLibrary((fulfill, reject) => { - each(this, (err, doc) => { - if (err) { - reject(err); - return false; - } else if (doc == null) { - fulfill(null); - return false; - } else { - iterator(doc); - return true; - } - }); - }); - } - } - - /** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ - setReadPreference(readPreference) { - if (this.s.state !== CursorState.INIT) { - throw MongoError.create({ - message: 'cannot change cursor readPreference after cursor has been accessed', - driver: true - }); - } - - if (readPreference instanceof ReadPreference) { - this.options.readPreference = readPreference; - } else if (typeof readPreference === 'string') { - this.options.readPreference = new ReadPreference(readPreference); - } else { - throw new TypeError('Invalid read preference: ' + readPreference); - } - - return this; - } - - /** - * The callback format for results - * @callback Cursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - - /** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contains partial - * results when this cursor had been previously accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - toArray(callback) { - if (this.options.tailable) { - throw MongoError.create({ - message: 'Tailable cursor cannot be converted to array', - driver: true - }); - } - - return maybePromise(this, callback, cb => { - const cursor = this; - const items = []; - - // Reset cursor - cursor.rewind(); - cursor.s.state = CursorState.INIT; - - // Fetch all the documents - const fetchDocs = () => { - cursor._next((err, doc) => { - if (err) { - return handleCallback(cb, err); - } - - if (doc == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(cb, null, items)); - } - - // Add doc to items - items.push(doc); - - // Get all buffered objects - if (cursor.bufferedCount() > 0) { - let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); - Array.prototype.push.apply(items, docs); - } - - // Attempt a fetch - fetchDocs(); - }); - }; - - fetchDocs(); - }); - } - - /** - * The callback format for results - * @callback Cursor~countResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} count The count of documents. - */ - - /** - * Get the count of documents for this cursor - * @method - * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. - * @param {object} [options] Optional settings. - * @param {number} [options.skip] The number of documents to skip. - * @param {number} [options.limit] The maximum amounts to count before aborting. - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {string} [options.hint] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Cursor~countResultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - count(applySkipLimit, opts, callback) { - if (this.cmd.query == null) - throw MongoError.create({ - message: 'count can only be used with find command', - driver: true - }); - if (typeof opts === 'function') (callback = opts), (opts = {}); - opts = opts || {}; - - if (typeof applySkipLimit === 'function') { - callback = applySkipLimit; - applySkipLimit = true; - } - - if (this.cursorState.session) { - opts = Object.assign({}, opts, { session: this.cursorState.session }); - } - - const countOperation = new CountOperation(this, applySkipLimit, opts); - - return executeOperation(this.topology, countOperation, callback); - } - - /** - * Close the cursor, sending a KillCursor command and emitting close. - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor. - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - close(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { skipKillCursors: false }, options); - - return maybePromise(this, callback, cb => { - this.s.state = CursorState.CLOSED; - if (!options.skipKillCursors) { - // Kill the cursor - this.kill(); - } - - this._endSession(() => { - this.emit('close'); - cb(null, this); - }); - }); - } - - /** - * Map all documents using the provided function - * @method - * @param {function} [transform] The mapping transformation method. - * @return {Cursor} - */ - map(transform) { - if (this.cursorState.transforms && this.cursorState.transforms.doc) { - const oldTransform = this.cursorState.transforms.doc; - this.cursorState.transforms.doc = doc => { - return transform(oldTransform(doc)); - }; - } else { - this.cursorState.transforms = { doc: transform }; - } - - return this; - } - - /** - * Is the cursor closed - * @method - * @return {boolean} - */ - isClosed() { - return this.isDead(); - } - - destroy(err) { - if (err) this.emit('error', err); - this.pause(); - this.close(); - } - - /** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - * TODO: replace this method with transformStream in next major release - */ - stream(options) { - this.cursorState.streamOptions = options || {}; - return this; - } - - /** - * Return a modified Readable stream that applies a given transform function, if supplied. If none supplied, - * returns a stream of unmodified docs. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {stream} - */ - transformStream(options) { - const streamOptions = options || {}; - if (typeof streamOptions.transform === 'function') { - const stream = new Transform({ - objectMode: true, - transform: function(chunk, encoding, callback) { - this.push(streamOptions.transform(chunk)); - callback(); - } - }); - - return this.pipe(stream); - } - - return this.pipe(new PassThrough({ objectMode: true })); - } - - /** - * Execute the explain for the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - explain(callback) { - // NOTE: the next line includes a special case for operations which do not - // subclass `CommandOperationV2`. To be removed asap. - if (this.operation && this.operation.cmd == null) { - this.operation.options.explain = true; - this.operation.fullResponse = false; - return executeOperation(this.topology, this.operation, callback); - } - - this.cmd.explain = true; - - // Do we have a readConcern - if (this.cmd.readConcern) { - delete this.cmd['readConcern']; - } - return maybePromise(this, callback, cb => { - CoreCursor.prototype._next.apply(this, [cb]); - }); - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -/** - * Cursor stream data event, fired for each document in the cursor. - * - * @event Cursor#data - * @type {object} - */ - -/** - * Cursor stream end event - * - * @event Cursor#end - * @type {null} - */ - -/** - * Cursor stream close event - * - * @event Cursor#close - * @type {null} - */ - -/** - * Cursor stream readable event - * - * @event Cursor#readable - * @type {null} - */ - -// aliases -Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; - -// deprecated methods -deprecate(Cursor.prototype.each, 'Cursor.each is deprecated. Use Cursor.forEach instead.'); -deprecate( - Cursor.prototype.maxScan, - 'Cursor.maxScan is deprecated, and will be removed in a later version' -); - -deprecate( - Cursor.prototype.snapshot, - 'Cursor Snapshot is deprecated, and will be removed in a later version' -); - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Readable#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Readable#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Readable#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Readable#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Readable#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Readable#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Readable#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Readable#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -module.exports = Cursor; diff --git a/node_modules/mongodb/lib/db.js b/node_modules/mongodb/lib/db.js deleted file mode 100644 index e28d25a..0000000 --- a/node_modules/mongodb/lib/db.js +++ /dev/null @@ -1,1031 +0,0 @@ -'use strict'; - -const EventEmitter = require('events').EventEmitter; -const inherits = require('util').inherits; -const getSingleProperty = require('./utils').getSingleProperty; -const CommandCursor = require('./command_cursor'); -const handleCallback = require('./utils').handleCallback; -const filterOptions = require('./utils').filterOptions; -const toError = require('./utils').toError; -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const ObjectID = require('./core').ObjectID; -const Logger = require('./core').Logger; -const Collection = require('./collection'); -const mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern; -const executeLegacyOperation = require('./utils').executeLegacyOperation; -const resolveReadPreference = require('./utils').resolveReadPreference; -const ChangeStream = require('./change_stream'); -const deprecate = require('util').deprecate; -const deprecateOptions = require('./utils').deprecateOptions; -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const CONSTANTS = require('./constants'); -const WriteConcern = require('./write_concern'); -const ReadConcern = require('./read_concern'); -const AggregationCursor = require('./aggregation_cursor'); - -// Operations -const createListener = require('./operations/db_ops').createListener; -const ensureIndex = require('./operations/db_ops').ensureIndex; -const evaluate = require('./operations/db_ops').evaluate; -const profilingInfo = require('./operations/db_ops').profilingInfo; -const validateDatabaseName = require('./operations/db_ops').validateDatabaseName; - -const AggregateOperation = require('./operations/aggregate'); -const AddUserOperation = require('./operations/add_user'); -const CollectionsOperation = require('./operations/collections'); -const CommandOperation = require('./operations/command'); -const CreateCollectionOperation = require('./operations/create_collection'); -const CreateIndexOperation = require('./operations/create_index'); -const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; -const DropDatabaseOperation = require('./operations/drop').DropDatabaseOperation; -const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); -const IndexInformationOperation = require('./operations/index_information'); -const ListCollectionsOperation = require('./operations/list_collections'); -const ProfilingLevelOperation = require('./operations/profiling_level'); -const RemoveUserOperation = require('./operations/remove_user'); -const RenameOperation = require('./operations/rename'); -const SetProfilingLevelOperation = require('./operations/set_profiling_level'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Db** class is a class that represents a MongoDB Database. - * - * @example - * const MongoClient = require('mongodb').MongoClient; - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Select the database by name - * const testDb = client.db(dbName); - * client.close(); - * }); - */ - -// Allowed parameters -const legalOptionNames = [ - 'w', - 'wtimeout', - 'fsync', - 'j', - 'readPreference', - 'readPreferenceTags', - 'native_parser', - 'forceServerObjectId', - 'pkFactory', - 'serializeFunctions', - 'raw', - 'bufferMaxEntries', - 'authSource', - 'ignoreUndefined', - 'promoteLongs', - 'promiseLibrary', - 'readConcern', - 'retryMiliSeconds', - 'numberOfRetries', - 'parentDb', - 'noListener', - 'loggerLevel', - 'logger', - 'promoteBuffers', - 'promoteLongs', - 'promoteValues', - 'compression', - 'retryWrites' -]; - -/** - * Creates a new Db instance - * @class - * @param {string} databaseName The name of the database this instance represents. - * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. - * @param {object} [options] Optional settings. - * @param {string} [options.authSource] If the database authentication is dependent on another databaseName. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. - * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database - * @property {string} databaseName The name of the database this instance represents. - * @property {object} options The options associated with the db instance. - * @property {boolean} native_parser The current value of the parameter native_parser. - * @property {boolean} slaveOk The current slaveOk value for the db instance. - * @property {object} writeConcern The current write concern values. - * @property {object} topology Access the topology object (single server, replicaset or mongos). - * @fires Db#close - * @fires Db#reconnect - * @fires Db#error - * @fires Db#timeout - * @fires Db#parseError - * @fires Db#fullsetup - * @return {Db} a Db instance. - */ -function Db(databaseName, topology, options) { - options = options || {}; - if (!(this instanceof Db)) return new Db(databaseName, topology, options); - EventEmitter.call(this); - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure we put the promiseLib in the options - options.promiseLibrary = promiseLibrary; - - // Internal state of the db object - this.s = { - // DbCache - dbCache: {}, - // Children db's - children: [], - // Topology - topology: topology, - // Options - options: options, - // Logger instance - logger: Logger('Db', options), - // Get the bson parser - bson: topology ? topology.bson : null, - // Unpack read preference - readPreference: ReadPreference.fromOptions(options), - // Set buffermaxEntries - bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1, - // Parent db (if chained) - parentDb: options.parentDb || null, - // Set up the primary key factory or fallback to ObjectID - pkFactory: options.pkFactory || ObjectID, - // Get native parser - nativeParser: options.nativeParser || options.native_parser, - // Promise library - promiseLibrary: promiseLibrary, - // No listener - noListener: typeof options.noListener === 'boolean' ? options.noListener : false, - // ReadConcern - readConcern: ReadConcern.fromOptions(options), - writeConcern: WriteConcern.fromOptions(options), - // Namespace - namespace: new MongoDBNamespace(databaseName) - }; - - // Ensure we have a valid db name - validateDatabaseName(databaseName); - - // Add a read Only property - getSingleProperty(this, 'serverConfig', this.s.topology); - getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries); - getSingleProperty(this, 'databaseName', this.s.namespace.db); - - // This is a child db, do not register any listeners - if (options.parentDb) return; - if (this.s.noListener) return; - - // Add listeners - topology.on('error', createListener(this, 'error', this)); - topology.on('timeout', createListener(this, 'timeout', this)); - topology.on('close', createListener(this, 'close', this)); - topology.on('parseError', createListener(this, 'parseError', this)); - topology.once('open', createListener(this, 'open', this)); - topology.once('fullsetup', createListener(this, 'fullsetup', this)); - topology.once('all', createListener(this, 'all', this)); - topology.on('reconnect', createListener(this, 'reconnect', this)); -} - -inherits(Db, EventEmitter); - -// Topology -Object.defineProperty(Db.prototype, 'topology', { - enumerable: true, - get: function() { - return this.s.topology; - } -}); - -// Options -Object.defineProperty(Db.prototype, 'options', { - enumerable: true, - get: function() { - return this.s.options; - } -}); - -// slaveOk specified -Object.defineProperty(Db.prototype, 'slaveOk', { - enumerable: true, - get: function() { - if ( - this.s.options.readPreference != null && - (this.s.options.readPreference !== 'primary' || - this.s.options.readPreference.mode !== 'primary') - ) { - return true; - } - return false; - } -}); - -Object.defineProperty(Db.prototype, 'readConcern', { - enumerable: true, - get: function() { - return this.s.readConcern; - } -}); - -Object.defineProperty(Db.prototype, 'readPreference', { - enumerable: true, - get: function() { - if (this.s.readPreference == null) { - // TODO: check client - return ReadPreference.primary; - } - - return this.s.readPreference; - } -}); - -// get the write Concern -Object.defineProperty(Db.prototype, 'writeConcern', { - enumerable: true, - get: function() { - return this.s.writeConcern; - } -}); - -Object.defineProperty(Db.prototype, 'namespace', { - enumerable: true, - get: function() { - return this.s.namespace.toString(); - } -}); - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.command = function(command, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - const commandOperation = new CommandOperation(this, options, null, command); - - return executeOperation(this.s.topology, commandOperation, callback); -}; - -/** - * Execute an aggregation framework pipeline against the database, needs MongoDB >= 3.6 - * @method - * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * @param {number} [options.cursor.batchSize=1000] Deprecated. Use `options.batchSize` - * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). - * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {string} [options.comment] Add a comment to an aggregation command - * @param {string|object} [options.hint] Add an index selection hint to an aggregation command - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Database~aggregationCallback} callback The command result callback - * @return {(null|AggregationCursor)} - */ -Db.prototype.aggregate = function(pipeline, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - // If we have no options or callback we are doing - // a cursor based aggregation - if (options == null && callback == null) { - options = {}; - } - - const cursor = new AggregationCursor( - this.s.topology, - new AggregateOperation(this, pipeline, options), - options - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; -}; - -/** - * Return the Admin db instance - * @method - * @return {Admin} return the new Admin db instance - */ -Db.prototype.admin = function() { - const Admin = require('./admin'); - - return new Admin(this, this.s.topology, this.s.promiseLibrary); -}; - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Db~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * The callback format for an aggregation call - * @callback Database~aggregationCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. - */ - -const collectionKeys = [ - 'pkFactory', - 'readPreference', - 'serializeFunctions', - 'strict', - 'readConcern', - 'ignoreUndefined', - 'promoteValues', - 'promoteBuffers', - 'promoteLongs' -]; - -/** - * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you - * can use it without a callback in the following way: `const collection = db.collection('mycollection');` - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @param {Db~collectionResultCallback} [callback] The collection result callback - * @return {Collection} return the new Collection instance if not in strict mode - */ -Db.prototype.collection = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options = Object.assign({}, options); - - // Set the promise library - options.promiseLibrary = this.s.promiseLibrary; - - // If we have not set a collection level readConcern set the db level one - options.readConcern = options.readConcern - ? new ReadConcern(options.readConcern.level) - : this.readConcern; - - // Do we have ignoreUndefined set - if (this.s.options.ignoreUndefined) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Merge in all needed options and ensure correct writeConcern merging from db level - options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true); - - // Execute - if (options == null || !options.strict) { - try { - const collection = new Collection( - this, - this.s.topology, - this.databaseName, - name, - this.s.pkFactory, - options - ); - if (callback) callback(null, collection); - return collection; - } catch (err) { - if (err instanceof MongoError && callback) return callback(err); - throw err; - } - } - - // Strict mode - if (typeof callback !== 'function') { - throw toError(`A callback is required in strict mode. While getting collection ${name}`); - } - - // Did the user destroy the topology - if (this.serverConfig && this.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - const listCollectionOptions = Object.assign({}, options, { nameOnly: true }); - - // Strict mode - this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => { - if (err != null) return handleCallback(callback, err, null); - if (collections.length === 0) - return handleCallback( - callback, - toError(`Collection ${name} does not exist. Currently in strict mode.`), - null - ); - - try { - return handleCallback( - callback, - null, - new Collection(this, this.s.topology, this.databaseName, name, this.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err, null); - } - }); -}; - -/** - * Create a new collection on a server with the specified options. Use this to create capped collections. - * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {boolean} [options.capped=false] Create a capped collection. - * @param {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 - * @param {number} [options.size] The size of the capped collection in bytes. - * @param {number} [options.max] The maximum number of documents in the capped collection. - * @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag. - * @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher. - * @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher. - * @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher. - * @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher. - * @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher. - * @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher. - * @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createCollection = deprecateOptions( - { - name: 'Db.createCollection', - deprecatedOptions: ['autoIndexId'], - optionsIndex: 1 - }, - function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; - options.readConcern = options.readConcern - ? new ReadConcern(options.readConcern.level) - : this.readConcern; - const createCollectionOperation = new CreateCollectionOperation(this, name, options); - - return executeOperation(this.s.topology, createCollectionOperation, callback); - } -); - -/** - * Get all the db statistics. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.scale] Divide the returned sizes by scale value. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.stats = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - // Build command object - const commandObject = { dbStats: true }; - // Check if we have the scale value - if (options['scale'] != null) commandObject['scale'] = options['scale']; - - // If we have a readPreference set - if (options.readPreference == null && this.s.readPreference) { - options.readPreference = this.s.readPreference; - } - - const statsOperation = new CommandOperation(this, options, null, commandObject); - - // Execute the command - return executeOperation(this.s.topology, statsOperation, callback); -}; - -/** - * Get the list of all collection information for the specified db. - * - * @method - * @param {object} [filter={}] Query to filter collections by - * @param {object} [options] Optional settings. - * @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info - * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {CommandCursor} - */ -Db.prototype.listCollections = function(filter, options) { - filter = filter || {}; - options = options || {}; - - return new CommandCursor( - this.s.topology, - new ListCollectionsOperation(this, filter, options), - options - ); -}; - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options] Optional settings. - * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaluation of the javascript. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.eval = deprecate(function(code, parameters, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - parameters = args.length ? args.shift() : parameters; - options = args.length ? args.shift() || {} : {}; - - return executeLegacyOperation(this.s.topology, evaluate, [ - this, - code, - parameters, - options, - callback - ]); -}, 'Db.eval is deprecated as of MongoDB version 3.2'); - -/** - * Rename a collection. - * - * @method - * @param {string} fromCollection Name of current collection to rename. - * @param {string} toCollection New name of of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Add return new collection - options.new_collection = true; - - const renameOperation = new RenameOperation( - this.collection(fromCollection), - toCollection, - options - ); - - return executeOperation(this.s.topology, renameOperation, callback); -}; - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {string} name Name of collection to drop - * @param {Object} [options] Optional settings - * @param {WriteConcern} [options.writeConcern] A full WriteConcern object - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j] The journal write concern - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropCollection = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropCollectionOperation = new DropCollectionOperation(this, name, options); - - return executeOperation(this.s.topology, dropCollectionOperation, callback); -}; - -/** - * Drop a database, removing it permanently from the server. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropDatabase = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropDatabaseOperation = new DropDatabaseOperation(this, options); - - return executeOperation(this.s.topology, dropDatabaseOperation, callback); -}; - -/** - * Fetch all collections for the current db. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionsResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.collections = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const collectionsOperation = new CollectionsOperation(this, options); - - return executeOperation(this.s.topology, collectionsOperation, callback); -}; - -/** - * Runs a command on the database as admin. - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.executeDbAdminCommand = function(selector, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options.readPreference = resolveReadPreference(this, options); - - const executeDbAdminCommandOperation = new ExecuteDbAdminCommandOperation( - this, - selector, - options - ); - - return executeOperation(this.s.topology, executeDbAdminCommandOperation, callback); -}; - -/** - * Creates an index on the db and collection. - * @method - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : {}; - - const createIndexOperation = new CreateIndexOperation(this, name, fieldOrSpec, options); - - return executeOperation(this.s.topology, createIndexOperation, callback); -}; - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated since version 2.0 - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, ensureIndex, [ - this, - name, - fieldOrSpec, - options, - callback - ]); -}, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0'); - -Db.prototype.addChild = function(db) { - if (this.s.parentDb) return this.s.parentDb.addChild(db); - this.s.children.push(db); -}; - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.addUser = function(username, password, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Special case where there is no password ($external users) - if (typeof username === 'string' && password != null && typeof password === 'object') { - options = password; - password = null; - } - - const addUserOperation = new AddUserOperation(this, username, password, options); - - return executeOperation(this.s.topology, addUserOperation, callback); -}; - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.removeUser = function(username, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const removeUserOperation = new RemoveUserOperation(this, username, options); - - return executeOperation(this.s.topology, removeUserOperation, callback); -}; - -/** - * Set the current profiling level of MongoDB - * - * @param {string} level The new profiling level (off, slow_only, all). - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.setProfilingLevel = function(level, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const setProfilingLevelOperation = new SetProfilingLevelOperation(this, level, options); - - return executeOperation(this.s.topology, setProfilingLevelOperation, callback); -}; - -/** - * Retrieve the current profiling information for MongoDB - * - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Query the system.profile collection directly. - */ -Db.prototype.profilingInfo = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, profilingInfo, [this, options, callback]); -}, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.'); - -/** - * Retrieve the current profiling Level for MongoDB - * - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.profilingLevel = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const profilingLevelOperation = new ProfilingLevelOperation(this, options); - - return executeOperation(this.s.topology, profilingLevelOperation, callback); -}; - -/** - * Retrieves this collections index info. - * @method - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.indexInformation = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexInformationOperation = new IndexInformationOperation(this, name, options); - - return executeOperation(this.s.topology, indexInformationOperation, callback); -}; - -/** - * Unref all sockets - * @method - */ -Db.prototype.unref = function() { - this.s.topology.unref(); -}; - -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections. - * @method - * @since 3.1.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -Db.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -Db.prototype.getLogger = function() { - return this.s.logger; -}; - -/** - * Db close event - * - * Emitted after a socket closed against a single server or mongos proxy. - * - * @event Db#close - * @type {MongoError} - */ - -/** - * Db reconnect event - * - * * Server: Emitted when the driver has reconnected and re-authenticated. - * * ReplicaSet: N/A - * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. - * - * @event Db#reconnect - * @type {object} - */ - -/** - * Db error event - * - * Emitted after an error occurred against a single server or mongos proxy. - * - * @event Db#error - * @type {MongoError} - */ - -/** - * Db timeout event - * - * Emitted after a socket timeout occurred against a single server or mongos proxy. - * - * @event Db#timeout - * @type {MongoError} - */ - -/** - * Db parseError event - * - * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. - * - * @event Db#parseError - * @type {MongoError} - */ - -/** - * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. - * - * * Server: Emitted when the driver has connected to the single server and has authenticated. - * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. - * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. - * - * @event Db#fullsetup - * @type {Db} - */ - -// Constants -Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; -Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; -Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; -Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; -Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; -Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; - -module.exports = Db; diff --git a/node_modules/mongodb/lib/dynamic_loaders.js b/node_modules/mongodb/lib/dynamic_loaders.js deleted file mode 100644 index c461002..0000000 --- a/node_modules/mongodb/lib/dynamic_loaders.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -let collection; -let cursor; -let db; - -function loadCollection() { - if (!collection) { - collection = require('./collection'); - } - return collection; -} - -function loadCursor() { - if (!cursor) { - cursor = require('./cursor'); - } - return cursor; -} - -function loadDb() { - if (!db) { - db = require('./db'); - } - return db; -} - -module.exports = { - loadCollection, - loadCursor, - loadDb -}; diff --git a/node_modules/mongodb/lib/error.js b/node_modules/mongodb/lib/error.js deleted file mode 100644 index a60525d..0000000 --- a/node_modules/mongodb/lib/error.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const MongoNetworkError = require('./core').MongoNetworkError; - -// From spec@https://github.com/mongodb/specifications/blob/f93d78191f3db2898a59013a7ed5650352ef6da8/source/change-streams/change-streams.rst#resumable-error -const GET_MORE_RESUMABLE_CODES = new Set([ - 6, // HostUnreachable - 7, // HostNotFound - 89, // NetworkTimeout - 91, // ShutdownInProgress - 189, // PrimarySteppedDown - 262, // ExceededTimeLimit - 9001, // SocketException - 10107, // NotMaster - 11600, // InterruptedAtShutdown - 11602, // InterruptedDueToReplStateChange - 13435, // NotMasterNoSlaveOk - 13436, // NotMasterOrSecondary - 63, // StaleShardVersion - 150, // StaleEpoch - 13388, // StaleConfig - 234, // RetryChangeStream - 133 // FailedToSatisfyReadPreference -]); - -function isResumableError(error, wireVersion) { - if (error instanceof MongoNetworkError) { - return true; - } - - if (wireVersion >= 9) { - return error.hasErrorLabel('ResumableChangeStreamError'); - } - - return GET_MORE_RESUMABLE_CODES.has(error.code); -} - -module.exports = { GET_MORE_RESUMABLE_CODES, isResumableError }; diff --git a/node_modules/mongodb/lib/gridfs-stream/download.js b/node_modules/mongodb/lib/gridfs-stream/download.js deleted file mode 100644 index 2c060fd..0000000 --- a/node_modules/mongodb/lib/gridfs-stream/download.js +++ /dev/null @@ -1,422 +0,0 @@ -'use strict'; - -var stream = require('stream'), - util = require('util'); - -module.exports = GridFSBucketReadStream; - -/** - * A readable stream that enables you to read buffers from GridFS. - * - * Do not instantiate this class directly. Use `openDownloadStream()` instead. - * - * @class - * @extends external:Readable - * @param {Collection} chunks Handle for chunks collection - * @param {Collection} files Handle for files collection - * @param {Object} readPreference The read preference to use - * @param {Object} filter The query to use to find the file document - * @param {Object} [options] Optional settings. - * @param {Number} [options.sort] Optional sort for the file find query - * @param {Number} [options.skip] Optional skip for the file find query - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @fires GridFSBucketReadStream#error - * @fires GridFSBucketReadStream#file - */ -function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { - this.s = { - bytesRead: 0, - chunks: chunks, - cursor: null, - expected: 0, - files: files, - filter: filter, - init: false, - expectedEnd: 0, - file: null, - options: options, - readPreference: readPreference - }; - - stream.Readable.call(this); -} - -util.inherits(GridFSBucketReadStream, stream.Readable); - -/** - * An error occurred - * - * @event GridFSBucketReadStream#error - * @type {Error} - */ - -/** - * Fires when the stream loaded the file document corresponding to the - * provided id. - * - * @event GridFSBucketReadStream#file - * @type {object} - */ - -/** - * Emitted when a chunk of data is available to be consumed. - * - * @event GridFSBucketReadStream#data - * @type {object} - */ - -/** - * Fired when the stream is exhausted (no more data events). - * - * @event GridFSBucketReadStream#end - * @type {object} - */ - -/** - * Fired when the stream is exhausted and the underlying cursor is killed - * - * @event GridFSBucketReadStream#close - * @type {object} - */ - -/** - * Reads from the cursor and pushes to the stream. - * Private Impl, do not call directly - * @ignore - * @method - */ - -GridFSBucketReadStream.prototype._read = function() { - var _this = this; - if (this.destroyed) { - return; - } - - waitForFile(_this, function() { - doRead(_this); - }); -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} start Offset in bytes to start reading at - * @return {GridFSBucketReadStream} Reference to Self - */ - -GridFSBucketReadStream.prototype.start = function(start) { - throwIfInitialized(this); - this.s.options.start = start; - return this; -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} end Offset in bytes to stop reading at - * @return {GridFSBucketReadStream} Reference to self - */ - -GridFSBucketReadStream.prototype.end = function(end) { - throwIfInitialized(this); - this.s.options.end = end; - return this; -}; - -/** - * Marks this stream as aborted (will never push another `data` event) - * and kills the underlying cursor. Will emit the 'end' event, and then - * the 'close' event once the cursor is successfully killed. - * - * @method - * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. - * @fires GridFSBucketWriteStream#close - * @fires GridFSBucketWriteStream#end - */ - -GridFSBucketReadStream.prototype.abort = function(callback) { - var _this = this; - this.push(null); - this.destroyed = true; - if (this.s.cursor) { - this.s.cursor.close(function(error) { - _this.emit('close'); - callback && callback(error); - }); - } else { - if (!this.s.init) { - // If not initialized, fire close event because we will never - // get a cursor - _this.emit('close'); - } - callback && callback(); - } -}; - -/** - * @ignore - */ - -function throwIfInitialized(self) { - if (self.s.init) { - throw new Error('You cannot change options after the stream has entered' + 'flowing mode!'); - } -} - -/** - * @ignore - */ - -function doRead(_this) { - if (_this.destroyed) { - return; - } - - _this.s.cursor.next(function(error, doc) { - if (_this.destroyed) { - return; - } - if (error) { - return __handleError(_this, error); - } - if (!doc) { - _this.push(null); - - process.nextTick(() => { - _this.s.cursor.close(function(error) { - if (error) { - __handleError(_this, error); - return; - } - - _this.emit('close'); - }); - }); - - return; - } - - var bytesRemaining = _this.s.file.length - _this.s.bytesRead; - var expectedN = _this.s.expected++; - var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining); - - if (doc.n > expectedN) { - var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - if (doc.n < expectedN) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; - - if (buf.length !== expectedLength) { - if (bytesRemaining <= 0) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; - return __handleError(_this, new Error(errmsg)); - } - - errmsg = - 'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength; - return __handleError(_this, new Error(errmsg)); - } - - _this.s.bytesRead += buf.length; - - if (buf.length === 0) { - return _this.push(null); - } - - var sliceStart = null; - var sliceEnd = null; - - if (_this.s.bytesToSkip != null) { - sliceStart = _this.s.bytesToSkip; - _this.s.bytesToSkip = 0; - } - - const atEndOfStream = expectedN === _this.s.expectedEnd - 1; - const bytesLeftToRead = _this.s.options.end - _this.s.bytesToSkip; - if (atEndOfStream && _this.s.bytesToTrim != null) { - sliceEnd = _this.s.file.chunkSize - _this.s.bytesToTrim; - } else if (_this.s.options.end && bytesLeftToRead < doc.data.length()) { - sliceEnd = bytesLeftToRead; - } - - if (sliceStart != null || sliceEnd != null) { - buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); - } - - _this.push(buf); - }); -} - -/** - * @ignore - */ - -function init(self) { - var findOneOptions = {}; - if (self.s.readPreference) { - findOneOptions.readPreference = self.s.readPreference; - } - if (self.s.options && self.s.options.sort) { - findOneOptions.sort = self.s.options.sort; - } - if (self.s.options && self.s.options.skip) { - findOneOptions.skip = self.s.options.skip; - } - - self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { - if (error) { - return __handleError(self, error); - } - if (!doc) { - var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename; - var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; - var err = new Error(errmsg); - err.code = 'ENOENT'; - return __handleError(self, err); - } - - // If document is empty, kill the stream immediately and don't - // execute any reads - if (doc.length <= 0) { - self.push(null); - return; - } - - if (self.destroyed) { - // If user destroys the stream before we have a cursor, wait - // until the query is done to say we're 'closed' because we can't - // cancel a query. - self.emit('close'); - return; - } - - self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); - - var filter = { files_id: doc._id }; - - // Currently (MongoDB 3.4.4) skip function does not support the index, - // it needs to retrieve all the documents first and then skip them. (CS-25811) - // As work around we use $gte on the "n" field. - if (self.s.options && self.s.options.start != null) { - var skip = Math.floor(self.s.options.start / doc.chunkSize); - if (skip > 0) { - filter['n'] = { $gte: skip }; - } - } - self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); - - if (self.s.readPreference) { - self.s.cursor.setReadPreference(self.s.readPreference); - } - - self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); - self.s.file = doc; - self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options); - self.emit('file', doc); - }); -} - -/** - * @ignore - */ - -function waitForFile(_this, callback) { - if (_this.s.file) { - return callback(); - } - - if (!_this.s.init) { - init(_this); - _this.s.init = true; - } - - _this.once('file', function() { - callback(); - }); -} - -/** - * @ignore - */ - -function handleStartOption(stream, doc, options) { - if (options && options.start != null) { - if (options.start > doc.length) { - throw new Error( - 'Stream start (' + - options.start + - ') must not be ' + - 'more than the length of the file (' + - doc.length + - ')' - ); - } - if (options.start < 0) { - throw new Error('Stream start (' + options.start + ') must not be ' + 'negative'); - } - if (options.end != null && options.end < options.start) { - throw new Error( - 'Stream start (' + - options.start + - ') must not be ' + - 'greater than stream end (' + - options.end + - ')' - ); - } - - stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; - stream.s.expected = Math.floor(options.start / doc.chunkSize); - - return options.start - stream.s.bytesRead; - } -} - -/** - * @ignore - */ - -function handleEndOption(stream, doc, cursor, options) { - if (options && options.end != null) { - if (options.end > doc.length) { - throw new Error( - 'Stream end (' + - options.end + - ') must not be ' + - 'more than the length of the file (' + - doc.length + - ')' - ); - } - if (options.start < 0) { - throw new Error('Stream end (' + options.end + ') must not be ' + 'negative'); - } - - var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; - - cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); - - stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); - - return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; - } -} - -/** - * @ignore - */ - -function __handleError(_this, error) { - _this.emit('error', error); -} diff --git a/node_modules/mongodb/lib/gridfs-stream/index.js b/node_modules/mongodb/lib/gridfs-stream/index.js deleted file mode 100644 index 6509839..0000000 --- a/node_modules/mongodb/lib/gridfs-stream/index.js +++ /dev/null @@ -1,359 +0,0 @@ -'use strict'; - -var Emitter = require('events').EventEmitter; -var GridFSBucketReadStream = require('./download'); -var GridFSBucketWriteStream = require('./upload'); -var shallowClone = require('../utils').shallowClone; -var toError = require('../utils').toError; -var util = require('util'); -var executeLegacyOperation = require('../utils').executeLegacyOperation; - -var DEFAULT_GRIDFS_BUCKET_OPTIONS = { - bucketName: 'fs', - chunkSizeBytes: 255 * 1024 -}; - -module.exports = GridFSBucket; - -/** - * Constructor for a streaming GridFS interface - * @class - * @extends external:EventEmitter - * @param {Db} db A db handle - * @param {object} [options] Optional settings. - * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. - * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB - * @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }` - * @param {object} [options.readPreference] Optional read preference to be passed to read operations - * @fires GridFSBucketWriteStream#index - */ - -function GridFSBucket(db, options) { - Emitter.apply(this); - this.setMaxListeners(0); - - if (options && typeof options === 'object') { - options = shallowClone(options); - var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); - for (var i = 0; i < keys.length; ++i) { - if (!options[keys[i]]) { - options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; - } - } - } else { - options = DEFAULT_GRIDFS_BUCKET_OPTIONS; - } - - this.s = { - db: db, - options: options, - _chunksCollection: db.collection(options.bucketName + '.chunks'), - _filesCollection: db.collection(options.bucketName + '.files'), - checkedIndexes: false, - calledOpenUploadStream: false, - promiseLibrary: db.s.promiseLibrary || Promise - }; -} - -util.inherits(GridFSBucket, Emitter); - -/** - * When the first call to openUploadStream is made, the upload stream will - * check to see if it needs to create the proper indexes on the chunks and - * files collections. This event is fired either when 1) it determines that - * no index creation is necessary, 2) when it successfully creates the - * necessary indexes. - * - * @event GridFSBucket#index - * @type {Error} - */ - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStream = function(filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - return new GridFSBucketWriteStream(this, filename, options); -}; - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string|number|object} id A custom id used to identify the file - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - - options.id = id; - - return new GridFSBucketWriteStream(this, filename, options); -}; - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming file - * data from GridFS. - * @method - * @param {ObjectId} id The id of the file doc - * @param {Object} [options] Optional settings. - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStream = function(id, options) { - var filter = { _id: id }; - options = { - start: options && options.start, - end: options && options.end - }; - - return new GridFSBucketReadStream( - this.s._chunksCollection, - this.s._filesCollection, - this.s.options.readPreference, - filter, - options - ); -}; - -/** - * Deletes a file with the given id - * @method - * @param {ObjectId} id The id of the file doc - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.delete = function(id, callback) { - return executeLegacyOperation(this.s.db.s.topology, _delete, [this, id, callback], { - skipSessions: true - }); -}; - -/** - * @ignore - */ - -function _delete(_this, id, callback) { - _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { - if (error) { - return callback(error); - } - - _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { - if (error) { - return callback(error); - } - - // Delete orphaned chunks before returning FileNotFound - if (!res.result.n) { - var errmsg = 'FileNotFound: no file with id ' + id + ' found'; - return callback(new Error(errmsg)); - } - - callback(); - }); - }); -} - -/** - * Convenience wrapper around find on the files collection - * @method - * @param {Object} filter - * @param {Object} [options] Optional settings for cursor - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find|find command documentation}. - * @param {number} [options.limit] Optional limit for cursor - * @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor - * @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag - * @param {number} [options.skip] Optional skip for cursor - * @param {object} [options.sort] Optional sort for cursor - * @return {Cursor} - */ - -GridFSBucket.prototype.find = function(filter, options) { - filter = filter || {}; - options = options || {}; - - var cursor = this.s._filesCollection.find(filter); - - if (options.batchSize != null) { - cursor.batchSize(options.batchSize); - } - if (options.limit != null) { - cursor.limit(options.limit); - } - if (options.maxTimeMS != null) { - cursor.maxTimeMS(options.maxTimeMS); - } - if (options.noCursorTimeout != null) { - cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); - } - if (options.skip != null) { - cursor.skip(options.skip); - } - if (options.sort != null) { - cursor.sort(options.sort); - } - - return cursor; -}; - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming the - * file with the given name from GridFS. If there are multiple files with - * the same name, this will stream the most recent file with the given name - * (as determined by the `uploadDate` field). You can set the `revision` - * option to change this behavior. - * @method - * @param {String} filename The name of the file to stream - * @param {Object} [options] Optional settings - * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { - var sort = { uploadDate: -1 }; - var skip = null; - if (options && options.revision != null) { - if (options.revision >= 0) { - sort = { uploadDate: 1 }; - skip = options.revision; - } else { - skip = -options.revision - 1; - } - } - - var filter = { filename: filename }; - options = { - sort: sort, - skip: skip, - start: options && options.start, - end: options && options.end - }; - return new GridFSBucketReadStream( - this.s._chunksCollection, - this.s._filesCollection, - this.s.options.readPreference, - filter, - options - ); -}; - -/** - * Renames the file with the given _id to the given string - * @method - * @param {ObjectId} id the id of the file to rename - * @param {String} filename new name for the file - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.rename = function(id, filename, callback) { - return executeLegacyOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], { - skipSessions: true - }); -}; - -/** - * @ignore - */ - -function _rename(_this, id, filename, callback) { - var filter = { _id: id }; - var update = { $set: { filename: filename } }; - _this.s._filesCollection.updateOne(filter, update, function(error, res) { - if (error) { - return callback(error); - } - if (!res.result.n) { - return callback(toError('File with id ' + id + ' not found')); - } - callback(); - }); -} - -/** - * Removes this bucket's files collection, followed by its chunks collection. - * @method - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.drop = function(callback) { - return executeLegacyOperation(this.s.db.s.topology, _drop, [this, callback], { - skipSessions: true - }); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -GridFSBucket.prototype.getLogger = function() { - return this.s.db.s.logger; -}; - -/** - * @ignore - */ - -function _drop(_this, callback) { - _this.s._filesCollection.drop(function(error) { - if (error) { - return callback(error); - } - _this.s._chunksCollection.drop(function(error) { - if (error) { - return callback(error); - } - - return callback(); - }); - }); -} - -/** - * Callback format for all GridFSBucket methods that can accept a callback. - * @callback GridFSBucket~errorCallback - * @param {MongoError|undefined} error If present, an error instance representing any errors that occurred - * @param {*} result If present, a returned result for the method - */ diff --git a/node_modules/mongodb/lib/gridfs-stream/upload.js b/node_modules/mongodb/lib/gridfs-stream/upload.js deleted file mode 100644 index 578949a..0000000 --- a/node_modules/mongodb/lib/gridfs-stream/upload.js +++ /dev/null @@ -1,538 +0,0 @@ -'use strict'; - -var core = require('../core'); -var crypto = require('crypto'); -var stream = require('stream'); -var util = require('util'); -var Buffer = require('safe-buffer').Buffer; - -var ERROR_NAMESPACE_NOT_FOUND = 26; - -module.exports = GridFSBucketWriteStream; - -/** - * A writable stream that enables you to write buffers to GridFS. - * - * Do not instantiate this class directly. Use `openUploadStream()` instead. - * - * @class - * @extends external:Writable - * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {string|number|object} [options.id] Custom file id for the GridFS file. - * @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes - * @param {number} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {number} [options.j] The journal write concern - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @fires GridFSBucketWriteStream#error - * @fires GridFSBucketWriteStream#finish - */ - -function GridFSBucketWriteStream(bucket, filename, options) { - options = options || {}; - this.bucket = bucket; - this.chunks = bucket.s._chunksCollection; - this.filename = filename; - this.files = bucket.s._filesCollection; - this.options = options; - // Signals the write is all done - this.done = false; - - this.id = options.id ? options.id : core.BSON.ObjectId(); - this.chunkSizeBytes = this.options.chunkSizeBytes; - this.bufToStore = Buffer.alloc(this.chunkSizeBytes); - this.length = 0; - this.md5 = !options.disableMD5 && crypto.createHash('md5'); - this.n = 0; - this.pos = 0; - this.state = { - streamEnd: false, - outstandingRequests: 0, - errored: false, - aborted: false, - promiseLibrary: this.bucket.s.promiseLibrary - }; - - if (!this.bucket.s.calledOpenUploadStream) { - this.bucket.s.calledOpenUploadStream = true; - - var _this = this; - checkIndexes(this, function() { - _this.bucket.s.checkedIndexes = true; - _this.bucket.emit('index'); - }); - } -} - -util.inherits(GridFSBucketWriteStream, stream.Writable); - -/** - * An error occurred - * - * @event GridFSBucketWriteStream#error - * @type {Error} - */ - -/** - * `end()` was called and the write stream successfully wrote the file - * metadata and all the chunks to MongoDB. - * - * @event GridFSBucketWriteStream#finish - * @type {object} - */ - -/** - * Write a buffer to the stream. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {GridFSBucket~errorCallback} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. - * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. - */ - -GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { - var _this = this; - return waitForIndexes(this, function() { - return doWrite(_this, chunk, encoding, callback); - }); -}; - -/** - * Places this write stream into an aborted state (all future writes fail) - * and deletes all chunks that have already been written. - * - * @method - * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred - * @return {Promise} if no callback specified - */ - -GridFSBucketWriteStream.prototype.abort = function(callback) { - if (this.state.streamEnd) { - var error = new Error('Cannot abort a stream that has already completed'); - if (typeof callback === 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - if (this.state.aborted) { - error = new Error('Cannot call abort() on a stream twice'); - if (typeof callback === 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - this.state.aborted = true; - this.chunks.deleteMany({ files_id: this.id }, function(error) { - if (typeof callback === 'function') callback(error); - }); -}; - -/** - * Tells the stream that no more data will be coming in. The stream will - * persist the remaining data to MongoDB, write the files document, and - * then emit a 'finish' event. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {GridFSBucket~errorCallback} callback Function to call when all files and chunks have been persisted to MongoDB - */ - -GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { - var _this = this; - if (typeof chunk === 'function') { - (callback = chunk), (chunk = null), (encoding = null); - } else if (typeof encoding === 'function') { - (callback = encoding), (encoding = null); - } - - if (checkAborted(this, callback)) { - return; - } - this.state.streamEnd = true; - - if (callback) { - this.once('finish', function(result) { - callback(null, result); - }); - } - - if (!chunk) { - waitForIndexes(this, function() { - writeRemnant(_this); - }); - return; - } - - this.write(chunk, encoding, function() { - writeRemnant(_this); - }); -}; - -/** - * @ignore - */ - -function __handleError(_this, error, callback) { - if (_this.state.errored) { - return; - } - _this.state.errored = true; - if (callback) { - return callback(error); - } - _this.emit('error', error); -} - -/** - * @ignore - */ - -function createChunkDoc(filesId, n, data) { - return { - _id: core.BSON.ObjectId(), - files_id: filesId, - n: n, - data: data - }; -} - -/** - * @ignore - */ - -function checkChunksIndex(_this, callback) { - _this.chunks.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === ERROR_NAMESPACE_NOT_FOUND) { - var index = { files_id: 1, n: 1 }; - _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - return; - } - return callback(error); - } - - var hasChunksIndex = false; - indexes.forEach(function(index) { - if (index.key) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { - hasChunksIndex = true; - } - } - }); - - if (hasChunksIndex) { - callback(); - } else { - index = { files_id: 1, n: 1 }; - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - indexOptions.unique = true; - - _this.chunks.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - } - }); -} - -/** - * @ignore - */ - -function checkDone(_this, callback) { - if (_this.done) return true; - if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) { - // Set done so we dont' trigger duplicate createFilesDoc - _this.done = true; - // Create a new files doc - var filesDoc = createFilesDoc( - _this.id, - _this.length, - _this.chunkSizeBytes, - _this.md5 && _this.md5.digest('hex'), - _this.filename, - _this.options.contentType, - _this.options.aliases, - _this.options.metadata - ); - - if (checkAborted(_this, callback)) { - return false; - } - - _this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error, callback); - } - _this.emit('finish', filesDoc); - }); - - return true; - } - - return false; -} - -/** - * @ignore - */ - -function checkIndexes(_this, callback) { - _this.files.findOne({}, { _id: 1 }, function(error, doc) { - if (error) { - return callback(error); - } - if (doc) { - return callback(); - } - - _this.files.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === ERROR_NAMESPACE_NOT_FOUND) { - var index = { filename: 1, uploadDate: 1 }; - _this.files.createIndex(index, { background: false }, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - return; - } - return callback(error); - } - - var hasFileIndex = false; - indexes.forEach(function(index) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { - hasFileIndex = true; - } - }); - - if (hasFileIndex) { - checkChunksIndex(_this, callback); - } else { - index = { filename: 1, uploadDate: 1 }; - - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - - _this.files.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - } - }); - }); -} - -/** - * @ignore - */ - -function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) { - var ret = { - _id: _id, - length: length, - chunkSize: chunkSize, - uploadDate: new Date(), - filename: filename - }; - - if (md5) { - ret.md5 = md5; - } - - if (contentType) { - ret.contentType = contentType; - } - - if (aliases) { - ret.aliases = aliases; - } - - if (metadata) { - ret.metadata = metadata; - } - - return ret; -} - -/** - * @ignore - */ - -function doWrite(_this, chunk, encoding, callback) { - if (checkAborted(_this, callback)) { - return false; - } - - var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); - - _this.length += inputBuf.length; - - // Input is small enough to fit in our buffer - if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { - inputBuf.copy(_this.bufToStore, _this.pos); - _this.pos += inputBuf.length; - - callback && callback(); - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // True means client can keep writing. - return true; - } - - // Otherwise, buffer is too big for current chunk, so we need to flush - // to MongoDB. - var inputBufRemaining = inputBuf.length; - var spaceRemaining = _this.chunkSizeBytes - _this.pos; - var numToCopy = Math.min(spaceRemaining, inputBuf.length); - var outstandingRequests = 0; - while (inputBufRemaining > 0) { - var inputBufPos = inputBuf.length - inputBufRemaining; - inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy); - _this.pos += numToCopy; - spaceRemaining -= numToCopy; - if (spaceRemaining === 0) { - if (_this.md5) { - _this.md5.update(_this.bufToStore); - } - var doc = createChunkDoc(_this.id, _this.n, Buffer.from(_this.bufToStore)); - ++_this.state.outstandingRequests; - ++outstandingRequests; - - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - --outstandingRequests; - - if (!outstandingRequests) { - _this.emit('drain', doc); - callback && callback(); - checkDone(_this); - } - }); - - spaceRemaining = _this.chunkSizeBytes; - _this.pos = 0; - ++_this.n; - } - inputBufRemaining -= numToCopy; - numToCopy = Math.min(spaceRemaining, inputBufRemaining); - } - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // False means the client should wait for the 'drain' event. - return false; -} - -/** - * @ignore - */ - -function getWriteOptions(_this) { - var obj = {}; - if (_this.options.writeConcern) { - obj.w = _this.options.writeConcern.w; - obj.wtimeout = _this.options.writeConcern.wtimeout; - obj.j = _this.options.writeConcern.j; - } - return obj; -} - -/** - * @ignore - */ - -function waitForIndexes(_this, callback) { - if (_this.bucket.s.checkedIndexes) { - return callback(false); - } - - _this.bucket.once('index', function() { - callback(true); - }); - - return true; -} - -/** - * @ignore - */ - -function writeRemnant(_this, callback) { - // Buffer is empty, so don't bother to insert - if (_this.pos === 0) { - return checkDone(_this, callback); - } - - ++_this.state.outstandingRequests; - - // Create a new buffer to make sure the buffer isn't bigger than it needs - // to be. - var remnant = Buffer.alloc(_this.pos); - _this.bufToStore.copy(remnant, 0, 0, _this.pos); - if (_this.md5) { - _this.md5.update(remnant); - } - var doc = createChunkDoc(_this.id, _this.n, remnant); - - // If the stream was aborted, do not write remnant - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - checkDone(_this); - }); -} - -/** - * @ignore - */ - -function checkAborted(_this, callback) { - if (_this.state.aborted) { - if (typeof callback === 'function') { - callback(new Error('this stream has been aborted')); - } - return true; - } - return false; -} diff --git a/node_modules/mongodb/lib/gridfs/chunk.js b/node_modules/mongodb/lib/gridfs/chunk.js deleted file mode 100644 index d276d72..0000000 --- a/node_modules/mongodb/lib/gridfs/chunk.js +++ /dev/null @@ -1,236 +0,0 @@ -'use strict'; - -var Binary = require('../core').BSON.Binary, - ObjectID = require('../core').BSON.ObjectID; - -var Buffer = require('safe-buffer').Buffer; - -/** - * Class for representing a single chunk in GridFS. - * - * @class - * - * @param file {GridStore} The {@link GridStore} object holding this chunk. - * @param mongoObject {object} The mongo object representation of this chunk. - * - * @throws Error when the type of data field for {@link mongoObject} is not - * supported. Currently supported types for data field are instances of - * {@link String}, {@link Array}, {@link Binary} and {@link Binary} - * from the bson module - * - * @see Chunk#buildMongoObject - */ -var Chunk = function(file, mongoObject, writeConcern) { - if (!(this instanceof Chunk)) return new Chunk(file, mongoObject); - - this.file = file; - var mongoObjectFinal = mongoObject == null ? {} : mongoObject; - this.writeConcern = writeConcern || { w: 1 }; - this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; - this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; - this.data = new Binary(); - - if (typeof mongoObjectFinal.data === 'string') { - var buffer = Buffer.alloc(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); - this.data = new Binary(buffer); - } else if (Array.isArray(mongoObjectFinal.data)) { - buffer = Buffer.alloc(mongoObjectFinal.data.length); - var data = mongoObjectFinal.data.join(''); - buffer.write(data, 0, data.length, 'binary'); - this.data = new Binary(buffer); - } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { - this.data = mongoObjectFinal.data; - } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { - throw Error('Illegal chunk format'); - } - - // Update position - this.internalPosition = 0; -}; - -/** - * Writes a data to this object and advance the read/write head. - * - * @param data {string} the data to write - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.write = function(data, callback) { - this.data.write(data, this.internalPosition, data.length, 'binary'); - this.internalPosition = this.data.length(); - if (callback != null) return callback(null, this); - return this; -}; - -/** - * Reads data and advances the read/write head. - * - * @param length {number} The length of data to read. - * - * @return {string} The data read if the given length will not exceed the end of - * the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.read = function(length) { - // Default to full read if no index defined - length = length == null || length === 0 ? this.length() : length; - - if (this.length() - this.internalPosition + 1 >= length) { - var data = this.data.read(this.internalPosition, length); - this.internalPosition = this.internalPosition + length; - return data; - } else { - return ''; - } -}; - -Chunk.prototype.readSlice = function(length) { - if (this.length() - this.internalPosition >= length) { - var data = null; - if (this.data.buffer != null) { - //Pure BSON - data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); - } else { - //Native BSON - data = Buffer.alloc(length); - length = this.data.readInto(data, this.internalPosition); - } - this.internalPosition = this.internalPosition + length; - return data; - } else { - return null; - } -}; - -/** - * Checks if the read/write head is at the end. - * - * @return {boolean} Whether the read/write head has reached the end of this - * chunk. - */ -Chunk.prototype.eof = function() { - return this.internalPosition === this.length() ? true : false; -}; - -/** - * Reads one character from the data of this chunk and advances the read/write - * head. - * - * @return {string} a single character data read if the the read/write head is - * not at the end of the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.getc = function() { - return this.read(1); -}; - -/** - * Clears the contents of the data in this chunk and resets the read/write head - * to the initial position. - */ -Chunk.prototype.rewind = function() { - this.internalPosition = 0; - this.data = new Binary(); -}; - -/** - * Saves this chunk to the database. Also overwrites existing entries having the - * same id as this chunk. - * - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.save = function(options, callback) { - var self = this; - if (typeof options === 'function') { - callback = options; - options = {}; - } - - self.file.chunkCollection(function(err, collection) { - if (err) return callback(err); - - // Merge the options - var writeOptions = { upsert: true }; - for (var name in options) writeOptions[name] = options[name]; - for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; - - if (self.data.length() > 0) { - self.buildMongoObject(function(mongoObject) { - var options = { forceServerObjectId: true }; - for (var name in self.writeConcern) { - options[name] = self.writeConcern[name]; - } - - collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) { - callback(err, self); - }); - }); - } else { - callback(null, self); - } - // }); - }); -}; - -/** - * Creates a mongoDB object representation of this chunk. - * - * @param callback {function(Object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *

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

- *        {
- *          '_id' : , // {number} id for this file
- *          'filename' : , // {string} name for this file
- *          'contentType' : , // {string} mime type for this file
- *          'length' : , // {number} size of this file?
- *          'chunksize' : , // {number} chunk size used by this file
- *          'uploadDate' : , // {Date}
- *          'aliases' : , // {array of string}
- *          'metadata' : , // {string}
- *        }
- *        
- * - * @ignore - */ -var buildMongoObject = function(self, callback) { - // Calcuate the length - var mongoObject = { - _id: self.fileId, - filename: self.filename, - contentType: self.contentType, - length: self.position ? self.position : 0, - chunkSize: self.chunkSize, - uploadDate: self.uploadDate, - aliases: self.aliases, - metadata: self.metadata - }; - - var md5Command = { filemd5: self.fileId, root: self.root }; - self.db.command(md5Command, function(err, results) { - if (err) return callback(err); - - mongoObject.md5 = results.md5; - callback(null, mongoObject); - }); -}; - -/** - * Gets the nth chunk of this file. - * @ignore - */ -var nthChunk = function(self, chunkNumber, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - options.readPreference = self.readPreference; - // Get the nth chunk - self - .chunkCollection() - .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) { - if (err) return callback(err); - - var finalChunk = chunk == null ? {} : chunk; - callback(null, new Chunk(self, finalChunk, self.writeConcern)); - }); -}; - -/** - * @ignore - */ -var lastChunkNumber = function(self) { - return Math.floor((self.length ? self.length - 1 : 0) / self.chunkSize); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @ignore - */ -var deleteChunks = function(self, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - - if (self.fileId != null) { - self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) { - if (err) return callback(err, false); - callback(null, true); - }); - } else { - callback(null, true); - } -}; - -/** - * The collection to be used for holding the files and chunks collection. - * - * @classconstant DEFAULT_ROOT_COLLECTION - */ -GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; - -/** - * Default file mime type - * - * @classconstant DEFAULT_CONTENT_TYPE - */ -GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; - -/** - * Seek mode where the given length is absolute. - * - * @classconstant IO_SEEK_SET - */ -GridStore.IO_SEEK_SET = 0; - -/** - * Seek mode where the given length is an offset to the current read/write head. - * - * @classconstant IO_SEEK_CUR - */ -GridStore.IO_SEEK_CUR = 1; - -/** - * Seek mode where the given length is an offset to the end of the file. - * - * @classconstant IO_SEEK_END - */ -GridStore.IO_SEEK_END = 2; - -/** - * Checks if a file exists in the database. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file to look for. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - exists, - [db, fileIdObject, rootCollection, options, callback], - { skipSessions: true } - ); -}; - -var exists = function(db, fileIdObject, rootCollection, options, callback) { - // Establish read preference - var readPreference = options.readPreference || ReadPreference.PRIMARY; - // Fetch collection - var rootCollectionFinal = - rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - db.collection(rootCollectionFinal + '.files', function(err, collection) { - if (err) return callback(err); - - // Build query - var query = - typeof fileIdObject === 'string' || - Object.prototype.toString.call(fileIdObject) === '[object RegExp]' - ? { filename: fileIdObject } - : { _id: fileIdObject }; // Attempt to locate file - - // We have a specific query - if ( - fileIdObject != null && - typeof fileIdObject === 'object' && - Object.prototype.toString.call(fileIdObject) !== '[object RegExp]' - ) { - query = fileIdObject; - } - - // Check if the entry exists - collection.findOne(query, { readPreference: readPreference }, function(err, item) { - if (err) return callback(err); - callback(null, item == null ? false : true); - }); - }); -}; - -/** - * Gets the list of files stored in the GridFS. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.list = function(db, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation(db.s.topology, list, [db, rootCollection, options, callback], { - skipSessions: true - }); -}; - -var list = function(db, rootCollection, options, callback) { - // Ensure we have correct values - if (rootCollection != null && typeof rootCollection === 'object') { - options = rootCollection; - rootCollection = null; - } - - // Establish read preference - var readPreference = options.readPreference || ReadPreference.primary; - // Check if we are returning by id not filename - var byId = options['id'] != null ? options['id'] : false; - // Fetch item - var rootCollectionFinal = - rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - var items = []; - db.collection(rootCollectionFinal + '.files', function(err, collection) { - if (err) return callback(err); - - collection.find({}, { readPreference: readPreference }, function(err, cursor) { - if (err) return callback(err); - - cursor.each(function(err, item) { - if (item != null) { - items.push(byId ? item._id : item.filename); - } else { - callback(err, items); - } - }); - }); - }); -}; - -/** - * Reads the contents of a file. - * - * This method has the following signatures - * - * (db, name, callback) - * (db, name, length, callback) - * (db, name, length, offset, callback) - * (db, name, length, offset, options, callback) - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file. - * @param {number} [length] The size of data to read. - * @param {number} [offset] The offset from the head of the file of which to start reading from. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.read = function(db, name, length, offset, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - length = args.length ? args.shift() : null; - offset = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - readStatic, - [db, name, length, offset, options, callback], - { skipSessions: true } - ); -}; - -var readStatic = function(db, name, length, offset, options, callback) { - new GridStore(db, name, 'r', options).open(function(err, gridStore) { - if (err) return callback(err); - // Make sure we are not reading out of bounds - if (offset && offset >= gridStore.length) - return callback('offset larger than size of file', null); - if (length && length > gridStore.length) - return callback('length is larger than the size of the file', null); - if (offset && length && offset + length > gridStore.length) - return callback('offset and length is larger than the size of the file', null); - - if (offset != null) { - gridStore.seek(offset, function(err, gridStore) { - if (err) return callback(err); - gridStore.read(length, callback); - }); - } else { - gridStore.read(length, callback); - } - }); -}; - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {(String|object)} name the name of the file. - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.readlines = function(db, name, separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - separator = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - readlinesStatic, - [db, name, separator, options, callback], - { skipSessions: true } - ); -}; - -var readlinesStatic = function(db, name, separator, options, callback) { - var finalSeperator = separator == null ? '\n' : separator; - new GridStore(db, name, 'r', options).open(function(err, gridStore) { - if (err) return callback(err); - gridStore.readlines(finalSeperator, callback); - }); -}; - -/** - * Deletes the chunks and metadata information of a file from GridFS. - * - * @method - * @static - * @param {Db} db The database to query. - * @param {(string|array)} names The name/names of the files to delete. - * @param {object} [options] Optional settings. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.unlink = function(db, names, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation(db.s.topology, unlinkStatic, [this, db, names, options, callback], { - skipSessions: true - }); -}; - -var unlinkStatic = function(self, db, names, options, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(db, options); - - // List of names - if (names.constructor === Array) { - var tc = 0; - for (var i = 0; i < names.length; i++) { - ++tc; - GridStore.unlink(db, names[i], options, function() { - if (--tc === 0) { - callback(null, self); - } - }); - } - } else { - new GridStore(db, names, 'w', options).open(function(err, gridStore) { - if (err) return callback(err); - deleteChunks(gridStore, function(err) { - if (err) return callback(err); - gridStore.collection(function(err, collection) { - if (err) return callback(err); - collection.remove({ _id: gridStore.fileId }, writeConcern, function(err) { - callback(err, self); - }); - }); - }); - }); - } -}; - -/** - * @ignore - */ -var _writeNormal = function(self, data, close, options, callback) { - // If we have a buffer write it using the writeBuffer method - if (Buffer.isBuffer(data)) { - return writeBuffer(self, data, close, callback); - } else { - return writeBuffer(self, Buffer.from(data, 'binary'), close, callback); - } -}; - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if (options.w != null) finalOptions.w = options.w; - if (options.journal === true) finalOptions.j = options.journal; - if (options.j === true) finalOptions.j = options.j; - if (options.fsync === true) finalOptions.fsync = options.fsync; - if (options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -}; - -/** - * @ignore - */ -var _getWriteConcern = function(self, options) { - // Final options - var finalOptions = { w: 1 }; - options = options || {}; - - // Local options verification - if ( - options.w != null || - typeof options.j === 'boolean' || - typeof options.journal === 'boolean' || - typeof options.fsync === 'boolean' - ) { - finalOptions = _setWriteConcernHash(options); - } else if (options.safe != null && typeof options.safe === 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if (typeof options.safe === 'boolean') { - finalOptions = { w: options.safe ? 1 : 0 }; - } else if ( - self.options.w != null || - typeof self.options.j === 'boolean' || - typeof self.options.journal === 'boolean' || - typeof self.options.fsync === 'boolean' - ) { - finalOptions = _setWriteConcernHash(self.options); - } else if ( - self.safe && - (self.safe.w != null || - typeof self.safe.j === 'boolean' || - typeof self.safe.journal === 'boolean' || - typeof self.safe.fsync === 'boolean') - ) { - finalOptions = _setWriteConcernHash(self.safe); - } else if (typeof self.safe === 'boolean') { - finalOptions = { w: self.safe ? 1 : 0 }; - } - - // Ensure we don't have an invalid combination of write concerns - if ( - finalOptions.w < 1 && - (finalOptions.journal === true || finalOptions.j === true || finalOptions.fsync === true) - ) - throw MongoError.create({ - message: 'No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true', - driver: true - }); - - // Return the options - return finalOptions; -}; - -/** - * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @extends external:Duplex - * @return {GridStoreStream} a GridStoreStream instance. - * @deprecated Use GridFSBucket API instead - */ -var GridStoreStream = function(gs) { - // Initialize the duplex stream - Duplex.call(this); - - // Get the gridstore - this.gs = gs; - - // End called - this.endCalled = false; - - // If we have a seek - this.totalBytesToRead = this.gs.length - this.gs.position; - this.seekPosition = this.gs.position; -}; - -// -// Inherit duplex -inherits(GridStoreStream, Duplex); - -GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; - -// Set up override -GridStoreStream.prototype.pipe = function(destination) { - var self = this; - - // Only open gridstore if not already open - if (!self.gs.isOpen) { - self.gs.open(function(err) { - if (err) return self.emit('error', err); - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - }); - } else { - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - } - - return destination; -}; - -// Called by stream -GridStoreStream.prototype._read = function() { - var self = this; - - var read = function() { - // Read data - self.gs.read(length, function(err, buffer) { - if (err && !self.endCalled) return self.emit('error', err); - - // Stream is closed - if (self.endCalled || buffer == null) return self.push(null); - // Remove bytes read - if (buffer.length <= self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer.length; - self.push(buffer); - } else if (buffer.length > self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer._index; - self.push(buffer.slice(0, buffer._index)); - } - - // Finished reading - if (self.totalBytesToRead <= 0) { - self.endCalled = true; - } - }); - }; - - // Set read length - var length = - self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; - if (!self.gs.isOpen) { - self.gs.open(function(err) { - self.totalBytesToRead = self.gs.length - self.gs.position; - if (err) return self.emit('error', err); - read(); - }); - } else { - read(); - } -}; - -GridStoreStream.prototype.destroy = function() { - this.pause(); - this.endCalled = true; - this.gs.close(); - this.emit('end'); -}; - -GridStoreStream.prototype.write = function(chunk) { - var self = this; - if (self.endCalled) - return self.emit( - 'error', - MongoError.create({ message: 'attempting to write to stream after end called', driver: true }) - ); - // Do we have to open the gridstore - if (!self.gs.isOpen) { - self.gs.open(function() { - self.gs.isOpen = true; - self.gs.write(chunk, function() { - process.nextTick(function() { - self.emit('drain'); - }); - }); - }); - return false; - } else { - self.gs.write(chunk, function() { - self.emit('drain'); - }); - return true; - } -}; - -GridStoreStream.prototype.end = function(chunk, encoding, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - chunk = args.length ? args.shift() : null; - encoding = args.length ? args.shift() : null; - self.endCalled = true; - - if (chunk) { - self.gs.write(chunk, function() { - self.gs.close(function() { - if (typeof callback === 'function') callback(); - self.emit('end'); - }); - }); - } - - self.gs.close(function() { - if (typeof callback === 'function') callback(); - self.emit('end'); - }); -}; - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Duplex#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Duplex#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Duplex#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Duplex#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Duplex#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Duplex#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Duplex#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Duplex#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -/** - * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. - * @function external:Duplex#write - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {boolean} - */ - -/** - * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. - * @function external:Duplex#end - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {null} - */ - -/** - * GridStoreStream stream data event, fired for each document in the cursor. - * - * @event GridStoreStream#data - * @type {object} - */ - -/** - * GridStoreStream stream end event - * - * @event GridStoreStream#end - * @type {null} - */ - -/** - * GridStoreStream stream close event - * - * @event GridStoreStream#close - * @type {null} - */ - -/** - * GridStoreStream stream readable event - * - * @event GridStoreStream#readable - * @type {null} - */ - -/** - * GridStoreStream stream drain event - * - * @event GridStoreStream#drain - * @type {null} - */ - -/** - * GridStoreStream stream finish event - * - * @event GridStoreStream#finish - * @type {null} - */ - -/** - * GridStoreStream stream pipe event - * - * @event GridStoreStream#pipe - * @type {null} - */ - -/** - * GridStoreStream stream unpipe event - * - * @event GridStoreStream#unpipe - * @type {null} - */ - -/** - * GridStoreStream stream error event - * - * @event GridStoreStream#error - * @type {null} - */ - -/** - * @ignore - */ -module.exports = GridStore; diff --git a/node_modules/mongodb/lib/mongo_client.js b/node_modules/mongodb/lib/mongo_client.js deleted file mode 100644 index db19e70..0000000 --- a/node_modules/mongodb/lib/mongo_client.js +++ /dev/null @@ -1,532 +0,0 @@ -'use strict'; - -const ChangeStream = require('./change_stream'); -const Db = require('./db'); -const EventEmitter = require('events').EventEmitter; -const inherits = require('util').inherits; -const MongoError = require('./core').MongoError; -const deprecate = require('util').deprecate; -const WriteConcern = require('./write_concern'); -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const ReadPreference = require('./core/topologies/read_preference'); -const maybePromise = require('./utils').maybePromise; -const NativeTopology = require('./topologies/native_topology'); -const connect = require('./operations/connect').connect; -const validOptions = require('./operations/connect').validOptions; - -/** - * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. - * - * @example - * // Connect using a MongoClient instance - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * const mongoClient = new MongoClient(url); - * mongoClient.connect(function(err, client) { - * const db = client.db(dbName); - * client.close(); - * }); - * - * @example - * // Connect using the MongoClient.connect static method - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * const db = client.db(dbName); - * client.close(); - * }); - */ - -/** - * A string specifying the level of a ReadConcern - * @typedef {'local'|'available'|'majority'|'linearizable'|'snapshot'} ReadConcernLevel - * @see https://docs.mongodb.com/manual/reference/read-concern/index.html#read-concern-levels - */ - -/** - * Configuration options for drivers wrapping the node driver. - * - * @typedef {Object} DriverInfoOptions - * @property {string} [name] The name of the driver - * @property {string} [version] The version of the driver - * @property {string} [platform] Optional platform information - */ - -/** - * Configuration options for drivers wrapping the node driver. - * - * @typedef {Object} DriverInfoOptions - * @property {string} [name] The name of the driver - * @property {string} [version] The version of the driver - * @property {string} [platform] Optional platform information - */ - -/** - * Creates a new MongoClient instance - * @class - * @param {string} url The connection URI string - * @param {object} [options] Optional settings - * @param {number} [options.poolSize=5] The maximum size of the individual server pool - * @param {boolean} [options.ssl=false] Enable SSL connection. *deprecated* use `tls` variants - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority - * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer *deprecated* use `tls` variants - * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer *deprecated* use `tls` variants - * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer *deprecated* use `tls` variants - * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase *deprecated* use `tls` variants - * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer *deprecated* use `tls` variants - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. *deprecated* use `tls` variants - * @param {boolean} [options.tls=false] Enable TLS connections - * @param {boolean} [options.tlsInsecure=false] Relax TLS constraints, disabling validation - * @param {string} [options.tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection - * @param {string} [options.tlsCertificateKeyFile] A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated - * @param {string} [options.tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections - * @param {boolean} [options.tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid - * @param {boolean} [options.tlsAllowInvalidHostnames] Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate - * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out - * @param {number} [options.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out - * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). - * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {string} [options.replicaSet=undefined] The Replicaset set name - * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {string} [options.authSource=undefined] Define the database to authenticate against - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j=false] Specify a journal write concern - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) - * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) - * @param {object} [options.logger=undefined] Custom logger object - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers - * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit - * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness - * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections - * @param {string} [options.auth.user=undefined] The username for auth - * @param {string} [options.auth.password=undefined] The password for auth - * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 - * @param {object} [options.compression] Type of compression to use: snappy or zlib - * @param {boolean} [options.fsync=false] Specify a file sync write concern - * @param {array} [options.readPreferenceTags] Read preference tags - * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor - * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client - * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections - * @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser. - * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer - * @param {Number} [options.localThresholdMS=15] **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers - * @param {Number} [options.serverSelectionTimeoutMS=30000] **Only applies to the unified topology** How long to block for server selection before throwing an error - * @param {Number} [options.heartbeatFrequencyMS=10000] **Only applies to the unified topology** The frequency with which topology updates are scheduled - * @param {AutoEncrypter~AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption - * @param {DriverInfoOptions} [options.driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {MongoClient} a MongoClient instance - */ -function MongoClient(url, options) { - if (!(this instanceof MongoClient)) return new MongoClient(url, options); - // Set up event emitter - EventEmitter.call(this); - - // The internal state - this.s = { - url: url, - options: options || {}, - promiseLibrary: (options && options.promiseLibrary) || Promise, - dbCache: new Map(), - sessions: new Set(), - writeConcern: WriteConcern.fromOptions(options), - namespace: new MongoDBNamespace('admin') - }; -} - -/** - * @ignore - */ -inherits(MongoClient, EventEmitter); - -Object.defineProperty(MongoClient.prototype, 'writeConcern', { - enumerable: true, - get: function() { - return this.s.writeConcern; - } -}); - -Object.defineProperty(MongoClient.prototype, 'readPreference', { - enumerable: true, - get: function() { - return ReadPreference.primary; - } -}); - -/** - * The callback format for results - * @callback MongoClient~connectCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {MongoClient} client The connected client. - */ - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.prototype.connect = function(callback) { - if (typeof callback === 'string') { - throw new TypeError('`connect` only accepts a callback'); - } - - const client = this; - return maybePromise(this, callback, cb => { - const err = validOptions(client.s.options); - if (err) return cb(err); - - connect(client, client.s.url, client.s.options, err => { - if (err) return cb(err); - cb(null, client); - }); - }); -}; - -MongoClient.prototype.logout = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - if (typeof callback === 'function') callback(null, true); -}, 'Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient'); - -/** - * Close the db and its underlying connections - * @method - * @param {boolean} [force=false] Force close, emitting no events - * @param {Db~noResultCallback} [callback] The result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.prototype.close = function(force, callback) { - if (typeof force === 'function') { - callback = force; - force = false; - } - - const client = this; - return maybePromise(this, callback, cb => { - const completeClose = err => { - client.emit('close', client); - - if (!(client.topology instanceof NativeTopology)) { - for (const item of client.s.dbCache) { - item[1].emit('close', client); - } - } - - client.removeAllListeners('close'); - cb(err); - }; - - if (client.topology == null) { - completeClose(); - return; - } - - client.topology.close(force, err => { - const autoEncrypter = client.topology.s.options.autoEncrypter; - if (!autoEncrypter) { - completeClose(err); - return; - } - - autoEncrypter.teardown(force, err2 => completeClose(err || err2)); - }); - }); -}; - -/** - * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are - * related in a parent-child relationship to the original instance so that events are correctly emitted on child - * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. - * You can control these behaviors with the options noListener and returnNonCachedInstance. - * - * @method - * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string. - * @param {object} [options] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {Db} - */ -MongoClient.prototype.db = function(dbName, options) { - options = options || {}; - - // Default to db from connection string if not provided - if (!dbName) { - dbName = this.s.options.dbName; - } - - // Copy the options and add out internal override of the not shared flag - const finalOptions = Object.assign({}, this.s.options, options); - - // Do we have the db in the cache already - if (this.s.dbCache.has(dbName) && finalOptions.returnNonCachedInstance !== true) { - return this.s.dbCache.get(dbName); - } - - // Add promiseLibrary - finalOptions.promiseLibrary = this.s.promiseLibrary; - - // If no topology throw an error message - if (!this.topology) { - throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'); - } - - // Return the db object - const db = new Db(dbName, this.topology, finalOptions); - - // Add the db to the cache - this.s.dbCache.set(dbName, db); - // Return the database - return db; -}; - -/** - * Check if MongoClient is connected - * - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {boolean} - */ -MongoClient.prototype.isConnected = function(options) { - options = options || {}; - - if (!this.topology) return false; - return this.topology.isConnected(options); -}; - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @static - * @param {string} url The connection URI string - * @param {object} [options] Optional settings - * @param {number} [options.poolSize=5] The maximum size of the individual server pool - * @param {boolean} [options.ssl=false] Enable SSL connection. *deprecated* use `tls` variants - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority - * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer *deprecated* use `tls` variants - * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer *deprecated* use `tls` variants - * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer *deprecated* use `tls` variants - * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase *deprecated* use `tls` variants - * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer *deprecated* use `tls` variants - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. *deprecated* use `tls` variants - * @param {boolean} [options.tls=false] Enable TLS connections - * @param {boolean} [options.tlsInsecure=false] Relax TLS constraints, disabling validation - * @param {string} [options.tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection - * @param {string} [options.tlsCertificateKeyFile] A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated - * @param {string} [options.tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections - * @param {boolean} [options.tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid - * @param {boolean} [options.tlsAllowInvalidHostnames] Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate - * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out - * @param {number} [options.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out - * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). - * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {string} [options.replicaSet=undefined] The Replicaset set name - * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {string} [options.authSource=undefined] Define the database to authenticate against - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j=false] Specify a journal write concern - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) - * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) - * @param {object} [options.logger=undefined] Custom logger object - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers - * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit - * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness - * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections - * @param {string} [options.auth.user=undefined] The username for auth - * @param {string} [options.auth.password=undefined] The password for auth - * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 - * @param {object} [options.compression] Type of compression to use: snappy or zlib - * @param {boolean} [options.fsync=false] Specify a file sync write concern - * @param {array} [options.readPreferenceTags] Read preference tags - * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor - * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client - * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections - * @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser. - * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer - * @param {Number} [options.localThresholdMS=15] **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers - * @param {Number} [options.serverSelectionTimeoutMS=30000] **Only applies to the unified topology** How long to block for server selection before throwing an error - * @param {Number} [options.heartbeatFrequencyMS=10000] **Only applies to the unified topology** The frequency with which topology updates are scheduled - * @param {AutoEncrypter~AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption - * @param {DriverInfoOptions} [options.driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.connect = function(url, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : null; - options = options || {}; - - // Create client - const mongoClient = new MongoClient(url, options); - // Execute the connect method - return mongoClient.connect(callback); -}; - -/** - * Starts a new session on the server - * - * @param {SessionOptions} [options] optional settings for a driver session - * @return {ClientSession} the newly established session - */ -MongoClient.prototype.startSession = function(options) { - options = Object.assign({ explicit: true }, options); - if (!this.topology) { - throw new MongoError('Must connect to a server before calling this method'); - } - - if (!this.topology.hasSessionSupport()) { - throw new MongoError('Current topology does not support sessions'); - } - - return this.topology.startSession(options, this.s.options); -}; - -/** - * Runs a given operation with an implicitly created session. The lifetime of the session - * will be handled without the need for user interaction. - * - * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function) - * - * @param {Object} [options] Optional settings to be appled to implicitly created session - * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}` - * @return {Promise} - */ -MongoClient.prototype.withSession = function(options, operation) { - if (typeof options === 'function') (operation = options), (options = undefined); - const session = this.startSession(options); - - let cleanupHandler = (err, result, opts) => { - // prevent multiple calls to cleanupHandler - cleanupHandler = () => { - throw new ReferenceError('cleanupHandler was called too many times'); - }; - - opts = Object.assign({ throw: true }, opts); - session.endSession(); - - if (err) { - if (opts.throw) throw err; - return Promise.reject(err); - } - }; - - try { - const result = operation(session); - return Promise.resolve(result) - .then(result => cleanupHandler(null, result)) - .catch(err => cleanupHandler(err, null, { throw: true })); - } catch (err) { - return cleanupHandler(err, null, { throw: false }); - } -}; -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin, - * and config databases. - * @method - * @since 3.1.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -MongoClient.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * Return the mongo client logger - * @method - * @return {Logger} return the mongo client logger - * @ignore - */ -MongoClient.prototype.getLogger = function() { - return this.s.options.logger; -}; - -module.exports = MongoClient; diff --git a/node_modules/mongodb/lib/operations/add_user.js b/node_modules/mongodb/lib/operations/add_user.js deleted file mode 100644 index 1f3f3a6..0000000 --- a/node_modules/mongodb/lib/operations/add_user.js +++ /dev/null @@ -1,96 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const crypto = require('crypto'); -const handleCallback = require('../utils').handleCallback; -const toError = require('../utils').toError; - -class AddUserOperation extends CommandOperation { - constructor(db, username, password, options) { - super(db, options); - - this.username = username; - this.password = password; - } - - _buildCommand() { - const db = this.db; - const username = this.username; - const password = this.password; - const options = this.options; - - // Get additional values - let roles = Array.isArray(options.roles) ? options.roles : []; - - // If not roles defined print deprecated message - // TODO: handle deprecation properly - if (roles.length === 0) { - console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); - } - - // Check the db name and add roles if needed - if ( - (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && - !Array.isArray(options.roles) - ) { - roles = ['root']; - } else if (!Array.isArray(options.roles)) { - roles = ['dbOwner']; - } - - const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; - - let userPassword = password; - - if (!digestPassword) { - // Use node md5 generator - const md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password); - userPassword = md5.digest('hex'); - } - - // Build the command to execute - const command = { - createUser: username, - customData: options.customData || {}, - roles: roles, - digestPassword - }; - - // No password - if (typeof password === 'string') { - command.pwd = userPassword; - } - - return command; - } - - execute(callback) { - const options = this.options; - - // Error out if digestPassword set - if (options.digestPassword != null) { - return callback( - toError( - "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." - ) - ); - } - - // Attempt to execute auth command - super.execute((err, r) => { - if (!err) { - return handleCallback(callback, err, r); - } - - return handleCallback(callback, err, null); - }); - } -} - -defineAspects(AddUserOperation, Aspect.WRITE_OPERATION); - -module.exports = AddUserOperation; diff --git a/node_modules/mongodb/lib/operations/admin_ops.js b/node_modules/mongodb/lib/operations/admin_ops.js deleted file mode 100644 index b08071c..0000000 --- a/node_modules/mongodb/lib/operations/admin_ops.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; - -const executeCommand = require('./db_ops').executeCommand; -const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; - -/** - * Get ReplicaSet status - * - * @param {Admin} a collection instance. - * @param {Object} [options] Optional settings. See Admin.prototype.replSetGetStatus for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback. - */ -function replSetGetStatus(admin, options, callback) { - executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback); -} - -/** - * Retrieve this db's server status. - * - * @param {Admin} a collection instance. - * @param {Object} [options] Optional settings. See Admin.prototype.serverStatus for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback - */ -function serverStatus(admin, options, callback) { - executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback); -} - -/** - * Validate an existing collection - * - * @param {Admin} a collection instance. - * @param {string} collectionName The name of the collection to validate. - * @param {Object} [options] Optional settings. See Admin.prototype.validateCollection for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback. - */ -function validateCollection(admin, collectionName, options, callback) { - const command = { validate: collectionName }; - const keys = Object.keys(options); - - // Decorate command with extra options - for (let i = 0; i < keys.length; i++) { - if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { - command[keys[i]] = options[keys[i]]; - } - } - - executeCommand(admin.s.db, command, options, (err, doc) => { - if (err != null) return callback(err, null); - - if (doc.ok === 0) return callback(new Error('Error with validate command'), null); - if (doc.result != null && doc.result.constructor !== String) - return callback(new Error('Error with validation data'), null); - if (doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error('Error: invalid collection ' + collectionName), null); - if (doc.valid != null && !doc.valid) - return callback(new Error('Error: invalid collection ' + collectionName), null); - - return callback(null, doc); - }); -} - -module.exports = { replSetGetStatus, serverStatus, validateCollection }; diff --git a/node_modules/mongodb/lib/operations/aggregate.js b/node_modules/mongodb/lib/operations/aggregate.js deleted file mode 100644 index e0f2da8..0000000 --- a/node_modules/mongodb/lib/operations/aggregate.js +++ /dev/null @@ -1,106 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const MongoError = require('../core').MongoError; -const maxWireVersion = require('../core/utils').maxWireVersion; -const ReadPreference = require('../core').ReadPreference; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; - -const DB_AGGREGATE_COLLECTION = 1; -const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8; - -class AggregateOperation extends CommandOperationV2 { - constructor(parent, pipeline, options) { - super(parent, options, { fullResponse: true }); - - this.target = - parent.s.namespace && parent.s.namespace.collection - ? parent.s.namespace.collection - : DB_AGGREGATE_COLLECTION; - - this.pipeline = pipeline; - - // determine if we have a write stage, override read preference if so - this.hasWriteStage = false; - if (typeof options.out === 'string') { - this.pipeline = this.pipeline.concat({ $out: options.out }); - this.hasWriteStage = true; - } else if (pipeline.length > 0) { - const finalStage = pipeline[pipeline.length - 1]; - if (finalStage.$out || finalStage.$merge) { - this.hasWriteStage = true; - } - } - - if (this.hasWriteStage) { - this.readPreference = ReadPreference.primary; - } - - if (options.explain && (this.readConcern || this.writeConcern)) { - throw new MongoError( - '"explain" cannot be used on an aggregate call with readConcern/writeConcern' - ); - } - - if (options.cursor != null && typeof options.cursor !== 'object') { - throw new MongoError('cursor options must be an object'); - } - } - - get canRetryRead() { - return !this.hasWriteStage; - } - - addToPipeline(stage) { - this.pipeline.push(stage); - } - - execute(server, callback) { - const options = this.options; - const serverWireVersion = maxWireVersion(server); - const command = { aggregate: this.target, pipeline: this.pipeline }; - - if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { - this.readConcern = null; - } - - if (serverWireVersion >= 5) { - if (this.hasWriteStage && this.writeConcern) { - Object.assign(command, { writeConcern: this.writeConcern }); - } - } - - if (options.bypassDocumentValidation === true) { - command.bypassDocumentValidation = options.bypassDocumentValidation; - } - - if (typeof options.allowDiskUse === 'boolean') { - command.allowDiskUse = options.allowDiskUse; - } - - if (options.hint) { - command.hint = options.hint; - } - - if (options.explain) { - options.full = false; - command.explain = options.explain; - } - - command.cursor = options.cursor || {}; - if (options.batchSize && !this.hasWriteStage) { - command.cursor.batchSize = options.batchSize; - } - - super.executeCommand(server, command, callback); - } -} - -defineAspects(AggregateOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = AggregateOperation; diff --git a/node_modules/mongodb/lib/operations/bulk_write.js b/node_modules/mongodb/lib/operations/bulk_write.js deleted file mode 100644 index 8f14f02..0000000 --- a/node_modules/mongodb/lib/operations/bulk_write.js +++ /dev/null @@ -1,104 +0,0 @@ -'use strict'; - -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const MongoError = require('../core').MongoError; -const OperationBase = require('./operation').OperationBase; - -class BulkWriteOperation extends OperationBase { - constructor(collection, operations, options) { - super(options); - - this.collection = collection; - this.operations = operations; - } - - execute(callback) { - const coll = this.collection; - const operations = this.operations; - let options = this.options; - - // Add ignoreUndfined - if (coll.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = coll.s.options.ignoreUndefined; - } - - // Create the bulk operation - const bulk = - options.ordered === true || options.ordered == null - ? coll.initializeOrderedBulkOp(options) - : coll.initializeUnorderedBulkOp(options); - - // Do we have a collation - let collation = false; - - // for each op go through and add to the bulk - try { - for (let i = 0; i < operations.length; i++) { - // Get the operation type - const key = Object.keys(operations[i])[0]; - // Check if we have a collation - if (operations[i][key].collation) { - collation = true; - } - - // Pass to the raw bulk - bulk.raw(operations[i]); - } - } catch (err) { - return callback(err, null); - } - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; - const capabilities = coll.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - // Execute the bulk - bulk.execute(writeCon, finalOptions, (err, r) => { - // We have connection level error - if (!r && err) { - return callback(err, null); - } - - r.insertedCount = r.nInserted; - r.matchedCount = r.nMatched; - r.modifiedCount = r.nModified || 0; - r.deletedCount = r.nRemoved; - r.upsertedCount = r.getUpsertedIds().length; - r.upsertedIds = {}; - r.insertedIds = {}; - - // Update the n - r.n = r.insertedCount; - - // Inserted documents - const inserted = r.getInsertedIds(); - // Map inserted ids - for (let i = 0; i < inserted.length; i++) { - r.insertedIds[inserted[i].index] = inserted[i]._id; - } - - // Upserted documents - const upserted = r.getUpsertedIds(); - // Map upserted ids - for (let i = 0; i < upserted.length; i++) { - r.upsertedIds[upserted[i].index] = upserted[i]._id; - } - - // Return the results - callback(null, r); - }); - } -} - -module.exports = BulkWriteOperation; diff --git a/node_modules/mongodb/lib/operations/collection_ops.js b/node_modules/mongodb/lib/operations/collection_ops.js deleted file mode 100644 index df5995d..0000000 --- a/node_modules/mongodb/lib/operations/collection_ops.js +++ /dev/null @@ -1,374 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const createIndexDb = require('./db_ops').createIndex; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const ensureIndexDb = require('./db_ops').ensureIndex; -const evaluate = require('./db_ops').evaluate; -const executeCommand = require('./db_ops').executeCommand; -const resolveReadPreference = require('../utils').resolveReadPreference; -const handleCallback = require('../utils').handleCallback; -const indexInformationDb = require('./db_ops').indexInformation; -const Long = require('../core').BSON.Long; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const insertDocuments = require('./common_functions').insertDocuments; -const updateDocuments = require('./common_functions').updateDocuments; - -/** - * Group function helper - * @ignore - */ -// var groupFunction = function () { -// var c = db[ns].find(condition); -// var map = new Map(); -// var reduce_function = reduce; -// -// while (c.hasNext()) { -// var obj = c.next(); -// var key = {}; -// -// for (var i = 0, len = keys.length; i < len; ++i) { -// var k = keys[i]; -// key[k] = obj[k]; -// } -// -// var aggObj = map.get(key); -// -// if (aggObj == null) { -// var newObj = Object.extend({}, key); -// aggObj = Object.extend(newObj, initial); -// map.put(key, aggObj); -// } -// -// reduce_function(obj, aggObj); -// } -// -// return { "result": map.values() }; -// }.toString(); -const groupFunction = - 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; - -// Check the update operation to ensure it has atomic operators. -function checkForAtomicOperators(update) { - if (Array.isArray(update)) { - return update.reduce((err, u) => err || checkForAtomicOperators(u), null); - } - - const keys = Object.keys(update); - - // same errors as the server would give for update doc lacking atomic operators - if (keys.length === 0) { - return toError('The update operation document must contain at least one atomic operator.'); - } - - if (keys[0][0] !== '$') { - return toError('the update operation document must contain atomic operators.'); - } -} - -/** - * Create an index on the db and collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function createIndex(coll, fieldOrSpec, options, callback) { - createIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); -} - -/** - * Create multiple indexes in the collection. This method is only supported for - * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported - * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. - * - * @method - * @param {Collection} a Collection instance. - * @param {array} indexSpecs An array of index specifications to be created - * @param {Object} [options] Optional settings. See Collection.prototype.createIndexes for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function createIndexes(coll, indexSpecs, options, callback) { - const capabilities = coll.s.topology.capabilities(); - - // Ensure we generate the correct name if the parameter is not set - for (let i = 0; i < indexSpecs.length; i++) { - if (indexSpecs[i].name == null) { - const keys = []; - - // Did the user pass in a collation, check if our write server supports it - if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - for (let name in indexSpecs[i].key) { - keys.push(`${name}_${indexSpecs[i].key[name]}`); - } - - // Set the name - indexSpecs[i].name = keys.join('_'); - } - } - - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Execute the index - executeCommand( - coll.s.db, - { - createIndexes: coll.collectionName, - indexes: indexSpecs - }, - options, - callback - ); -} - -/** - * Ensure that an index exists. If the index does not exist, this function creates it. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function ensureIndex(coll, fieldOrSpec, options, callback) { - ensureIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); -} - -/** - * Run a group command across a collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. - * @param {object} condition An optional condition that must be true for a row to be considered. - * @param {object} initial Initial value of the aggregation counter object. - * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated - * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. - * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. - * @param {object} [options] Optional settings. See Collection.prototype.group for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework. - */ -function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) { - // Execute using the command - if (command) { - const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); - - const selector = { - group: { - ns: coll.collectionName, - $reduce: reduceFunction, - cond: condition, - initial: initial, - out: 'inline' - } - }; - - // if finalize is defined - if (finalize != null) selector.group['finalize'] = finalize; - // Set up group selector - if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) { - selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); - } else { - const hash = {}; - keys.forEach(key => { - hash[key] = 1; - }); - selector.group.key = hash; - } - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(coll, options); - - // Do we have a readConcern specified - decorateWithReadConcern(selector, coll, options); - - // Have we specified collation - try { - decorateWithCollation(selector, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute command - executeCommand(coll.s.db, selector, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.retval); - }); - } else { - // Create execution scope - const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; - - scope.ns = coll.collectionName; - scope.keys = keys; - scope.condition = condition; - scope.initial = initial; - - // Pass in the function text to execute within mongodb. - const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); - - evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, results.result || results); - }); - } -} - -/** - * Retrieve all the indexes on the collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexes(coll, options, callback) { - options = Object.assign({}, { full: true }, options); - indexInformationDb(coll.s.db, coll.collectionName, options, callback); -} - -/** - * Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|array)} indexes One or more index names to check. - * @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexExists(coll, indexes, options, callback) { - indexInformation(coll, options, (err, indexInformation) => { - // If we have an error return - if (err != null) return handleCallback(callback, err, null); - // Let's check for the index names - if (!Array.isArray(indexes)) - return handleCallback(callback, null, indexInformation[indexes] != null); - // Check in list of indexes - for (let i = 0; i < indexes.length; i++) { - if (indexInformation[indexes[i]] == null) { - return handleCallback(callback, null, false); - } - } - - // All keys found return true - return handleCallback(callback, null, true); - }); -} - -/** - * Retrieve this collection's index info. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexInformation(coll, options, callback) { - indexInformationDb(coll.s.db, coll.collectionName, options, callback); -} - -/** - * Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are - * no ordering guarantees for returned results. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - */ -function parallelCollectionScan(coll, options, callback) { - // Create command object - const commandObject = { - parallelCollectionScan: coll.collectionName, - numCursors: options.numCursors - }; - - // Do we have a readConcern specified - decorateWithReadConcern(commandObject, coll, options); - - // Store the raw value - const raw = options.raw; - delete options['raw']; - - // Execute the command - executeCommand(coll.s.db, commandObject, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result == null) - return handleCallback( - callback, - new Error('no result returned for parallelCollectionScan'), - null - ); - - options = Object.assign({ explicitlyIgnoreSession: true }, options); - - const cursors = []; - // Add the raw back to the option - if (raw) options.raw = raw; - // Create command cursors for each item - for (let i = 0; i < result.cursors.length; i++) { - const rawId = result.cursors[i].cursor.id; - // Convert cursorId to Long if needed - const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; - // Add a command cursor - cursors.push(coll.s.topology.cursor(coll.namespace, cursorId, options)); - } - - handleCallback(callback, null, cursors); - }); -} - -/** - * Save a document. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} doc Document to save - * @param {object} [options] Optional settings. See Collection.prototype.save for a list of options. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -function save(coll, doc, options, callback) { - // Get the write concern options - const finalOptions = applyWriteConcern( - Object.assign({}, options), - { db: coll.s.db, collection: coll }, - options - ); - // Establish if we need to perform an insert or update - if (doc._id != null) { - finalOptions.upsert = true; - return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback); - } - - // Insert the document - insertDocuments(coll, [doc], finalOptions, (err, result) => { - if (callback == null) return; - if (doc == null) return handleCallback(callback, null, null); - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); -} - -module.exports = { - checkForAtomicOperators, - createIndex, - createIndexes, - ensureIndex, - group, - indexes, - indexExists, - indexInformation, - parallelCollectionScan, - save -}; diff --git a/node_modules/mongodb/lib/operations/collections.js b/node_modules/mongodb/lib/operations/collections.js deleted file mode 100644 index eac690a..0000000 --- a/node_modules/mongodb/lib/operations/collections.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; - -let collection; -function loadCollection() { - if (!collection) { - collection = require('../collection'); - } - return collection; -} - -class CollectionsOperation extends OperationBase { - constructor(db, options) { - super(options); - - this.db = db; - } - - execute(callback) { - const db = this.db; - let options = this.options; - - let Collection = loadCollection(); - - options = Object.assign({}, options, { nameOnly: true }); - // Let's get the collection names - db.listCollections({}, options).toArray((err, documents) => { - if (err != null) return handleCallback(callback, err, null); - // Filter collections removing any illegal ones - documents = documents.filter(doc => { - return doc.name.indexOf('$') === -1; - }); - - // Return the collection objects - handleCallback( - callback, - null, - documents.map(d => { - return new Collection( - db, - db.s.topology, - db.databaseName, - d.name, - db.s.pkFactory, - db.s.options - ); - }) - ); - }); - } -} - -module.exports = CollectionsOperation; diff --git a/node_modules/mongodb/lib/operations/command.js b/node_modules/mongodb/lib/operations/command.js deleted file mode 100644 index 3c795be..0000000 --- a/node_modules/mongodb/lib/operations/command.js +++ /dev/null @@ -1,120 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const applyWriteConcern = require('../utils').applyWriteConcern; -const debugOptions = require('../utils').debugOptions; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const resolveReadPreference = require('../utils').resolveReadPreference; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -const debugFields = [ - 'authSource', - 'w', - 'wtimeout', - 'j', - 'native_parser', - 'forceServerObjectId', - 'serializeFunctions', - 'raw', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bufferMaxEntries', - 'numberOfRetries', - 'retryMiliSeconds', - 'readPreference', - 'pkFactory', - 'parentDb', - 'promiseLibrary', - 'noListener' -]; - -class CommandOperation extends OperationBase { - constructor(db, options, collection, command) { - super(options); - - if (!this.hasAspect(Aspect.WRITE_OPERATION)) { - if (collection != null) { - this.options.readPreference = resolveReadPreference(collection, options); - } else { - this.options.readPreference = resolveReadPreference(db, options); - } - } else { - if (collection != null) { - applyWriteConcern(this.options, { db, coll: collection }, this.options); - } else { - applyWriteConcern(this.options, { db }, this.options); - } - this.options.readPreference = ReadPreference.primary; - } - - this.db = db; - - if (command != null) { - this.command = command; - } - - if (collection != null) { - this.collection = collection; - } - } - - _buildCommand() { - if (this.command != null) { - return this.command; - } - } - - execute(callback) { - const db = this.db; - const options = Object.assign({}, this.options); - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - let command; - try { - command = this._buildCommand(); - } catch (e) { - return callback(e); - } - - // Get the db name we are executing against - const dbName = options.dbName || options.authdb || db.databaseName; - - // Convert the readPreference if its not a write - if (this.hasAspect(Aspect.WRITE_OPERATION)) { - if (options.writeConcern && (!options.session || !options.session.inTransaction())) { - command.writeConcern = options.writeConcern; - } - } - - // Debug information - if (db.s.logger.isDebug()) { - db.s.logger.debug( - `executing command ${JSON.stringify( - command - )} against ${dbName}.$cmd with options [${JSON.stringify( - debugOptions(debugFields, options) - )}]` - ); - } - - const namespace = - this.namespace != null ? this.namespace : new MongoDBNamespace(dbName, '$cmd'); - - // Execute command - db.s.topology.command(namespace, command, options, (err, result) => { - if (err) return handleCallback(callback, err); - if (options.full) return handleCallback(callback, null, result); - handleCallback(callback, null, result.result); - }); - } -} - -module.exports = CommandOperation; diff --git a/node_modules/mongodb/lib/operations/command_v2.js b/node_modules/mongodb/lib/operations/command_v2.js deleted file mode 100644 index 8081d90..0000000 --- a/node_modules/mongodb/lib/operations/command_v2.js +++ /dev/null @@ -1,107 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const resolveReadPreference = require('../utils').resolveReadPreference; -const ReadConcern = require('../read_concern'); -const WriteConcern = require('../write_concern'); -const maxWireVersion = require('../core/utils').maxWireVersion; -const commandSupportsReadConcern = require('../core/sessions').commandSupportsReadConcern; -const MongoError = require('../error').MongoError; - -const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; - -class CommandOperationV2 extends OperationBase { - constructor(parent, options, operationOptions) { - super(options); - - this.ns = parent.s.namespace.withCollection('$cmd'); - this.readPreference = resolveReadPreference(parent, this.options); - this.readConcern = resolveReadConcern(parent, this.options); - this.writeConcern = resolveWriteConcern(parent, this.options); - this.explain = false; - - if (operationOptions && typeof operationOptions.fullResponse === 'boolean') { - this.fullResponse = true; - } - - // TODO: A lot of our code depends on having the read preference in the options. This should - // go away, but also requires massive test rewrites. - this.options.readPreference = this.readPreference; - - // TODO(NODE-2056): make logger another "inheritable" property - if (parent.s.logger) { - this.logger = parent.s.logger; - } else if (parent.s.db && parent.s.db.logger) { - this.logger = parent.s.db.logger; - } - } - - executeCommand(server, cmd, callback) { - // TODO: consider making this a non-enumerable property - this.server = server; - - const options = this.options; - const serverWireVersion = maxWireVersion(server); - const inTransaction = this.session && this.session.inTransaction(); - - if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) { - Object.assign(cmd, { readConcern: this.readConcern }); - } - - if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { - callback( - new MongoError( - `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation` - ) - ); - return; - } - - if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { - if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION)) { - Object.assign(cmd, { writeConcern: this.writeConcern }); - } - - if (options.collation && typeof options.collation === 'object') { - Object.assign(cmd, { collation: options.collation }); - } - } - - if (typeof options.maxTimeMS === 'number') { - cmd.maxTimeMS = options.maxTimeMS; - } - - if (typeof options.comment === 'string') { - cmd.comment = options.comment; - } - - if (this.logger && this.logger.isDebug()) { - this.logger.debug(`executing command ${JSON.stringify(cmd)} against ${this.ns}`); - } - - server.command(this.ns.toString(), cmd, this.options, (err, result) => { - if (err) { - callback(err, null); - return; - } - - if (this.fullResponse) { - callback(null, result); - return; - } - - callback(null, result.result); - }); - } -} - -function resolveWriteConcern(parent, options) { - return WriteConcern.fromOptions(options) || parent.writeConcern; -} - -function resolveReadConcern(parent, options) { - return ReadConcern.fromOptions(options) || parent.readConcern; -} - -module.exports = CommandOperationV2; diff --git a/node_modules/mongodb/lib/operations/common_functions.js b/node_modules/mongodb/lib/operations/common_functions.js deleted file mode 100644 index c027697..0000000 --- a/node_modules/mongodb/lib/operations/common_functions.js +++ /dev/null @@ -1,409 +0,0 @@ -'use strict'; - -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const CursorState = require('../core/cursor').CursorState; - -/** - * Build the count command. - * - * @method - * @param {collectionOrCursor} an instance of a collection or cursor - * @param {object} query The query for the count. - * @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options. - */ -function buildCountCommand(collectionOrCursor, query, options) { - const skip = options.skip; - const limit = options.limit; - let hint = options.hint; - const maxTimeMS = options.maxTimeMS; - query = query || {}; - - // Final query - const cmd = { - count: options.collectionName, - query: query - }; - - if (collectionOrCursor.s.numberOfRetries) { - // collectionOrCursor is a cursor - if (collectionOrCursor.options.hint) { - hint = collectionOrCursor.options.hint; - } else if (collectionOrCursor.cmd.hint) { - hint = collectionOrCursor.cmd.hint; - } - decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.cmd); - } else { - decorateWithCollation(cmd, collectionOrCursor, options); - } - - // Add limit, skip and maxTimeMS if defined - if (typeof skip === 'number') cmd.skip = skip; - if (typeof limit === 'number') cmd.limit = limit; - if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; - if (hint) cmd.hint = hint; - - // Do we have a readConcern specified - decorateWithReadConcern(cmd, collectionOrCursor); - - return cmd; -} - -function deleteCallback(err, r, callback) { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - r.deletedCount = r.result.n; - if (callback) callback(null, r); -} - -/** - * Find and update a document. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} doc The fields/vals to be updated. - * @param {object} [options] Optional settings. See Collection.prototype.findAndModify for a list of options. - * @param {Collection~findAndModifyCallback} [callback] The command result callback - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -function findAndModify(coll, query, sort, doc, options, callback) { - // Create findAndModify command object - const queryObject = { - findAndModify: coll.collectionName, - query: query - }; - - sort = formattedOrderClause(sort); - if (sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; - - const projection = options.projection || options.fields; - - if (projection) { - queryObject.fields = projection; - } - - if (options.arrayFilters) { - queryObject.arrayFilters = options.arrayFilters; - delete options.arrayFilters; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; - - // Either use override on the function, or go back to default on either the collection - // level or db - options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // No check on the documents - options.checkKeys = false; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // Decorate the findAndModify command with the write Concern - if (finalOptions.writeConcern) { - queryObject.writeConcern = finalOptions.writeConcern; - } - - // Have we specified bypassDocumentValidation - if (finalOptions.bypassDocumentValidation === true) { - queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; - } - - finalOptions.readPreference = ReadPreference.primary; - - // Have we specified collation - try { - decorateWithCollation(queryObject, coll, finalOptions); - } catch (err) { - return callback(err, null); - } - - // Execute the command - executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { - if (err) return handleCallback(callback, err, null); - - return handleCallback(callback, null, result); - }); -} - -/** - * Retrieves this collections index info. - * - * @method - * @param {Db} db The Db instance on which to retrieve the index info. - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function indexInformation(db, name, options, callback) { - // If we specified full information - const full = options['full'] == null ? false : options['full']; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Process all the results from the index command and collection - function processResults(indexes) { - // Contains all the information - let info = {}; - // Process all the indexes - for (let i = 0; i < indexes.length; i++) { - const index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for (let name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - db.collection(name) - .listIndexes(options) - .toArray((err, indexes) => { - if (err) return callback(toError(err)); - if (!Array.isArray(indexes)) return handleCallback(callback, null, []); - if (full) return handleCallback(callback, null, indexes); - handleCallback(callback, null, processResults(indexes)); - }); -} - -function prepareDocs(coll, docs, options) { - const forceServerObjectId = - typeof options.forceServerObjectId === 'boolean' - ? options.forceServerObjectId - : coll.s.db.options.forceServerObjectId; - - // no need to modify the docs if server sets the ObjectId - if (forceServerObjectId === true) { - return docs; - } - - return docs.map(doc => { - if (forceServerObjectId !== true && doc._id == null) { - doc._id = coll.s.pkFactory.createPk(); - } - - return doc; - }); -} - -// Get the next available document from the cursor, returns null if no more documents are available. -function nextObject(cursor, callback) { - if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) { - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - } - - if (cursor.s.state === CursorState.INIT && cursor.cmd && cursor.cmd.sort) { - try { - cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); - } catch (err) { - return handleCallback(callback, err); - } - } - - // Get the next object - cursor._next((err, doc) => { - cursor.s.state = CursorState.OPEN; - if (err) return handleCallback(callback, err); - handleCallback(callback, null, doc); - }); -} - -function insertDocuments(coll, docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - // Ensure we are operating on an array op docs - docs = Array.isArray(docs) ? docs : [docs]; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // If keep going set unordered - if (finalOptions.keepGoing === true) finalOptions.ordered = false; - finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - docs = prepareDocs(coll, docs, options); - - // File inserts - coll.s.topology.insert(coll.s.namespace, docs, finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) - return handleCallback(callback, toError(result.result.writeErrors[0])); - // Add docs to the list - result.ops = docs; - // Return the results - handleCallback(callback, null, result); - }); -} - -function removeDocuments(coll, selector, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}); - } else if (typeof selector === 'function') { - callback = selector; - options = {}; - selector = {}; - } - - // Create an empty options object if the provided one is null - options = options || {}; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // If selector is null set empty - if (selector == null) selector = {}; - - // Build the op - const op = { q: selector, limit: 0 }; - if (options.single) { - op.limit = 1; - } else if (finalOptions.retryWrites) { - finalOptions.retryWrites = false; - } - - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute the remove - coll.s.topology.remove(coll.s.namespace, [op], finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) { - return handleCallback(callback, toError(result.result.writeErrors[0])); - } - - // Return the results - handleCallback(callback, null, result); - }); -} - -function updateDocuments(coll, selector, document, options, callback) { - if ('function' === typeof options) (callback = options), (options = null); - if (options == null) options = {}; - if (!('function' === typeof callback)) callback = null; - - // If we are not providing a selector or document throw - if (selector == null || typeof selector !== 'object') - return callback(toError('selector must be a valid JavaScript object')); - if (document == null || typeof document !== 'object') - return callback(toError('document must be a valid JavaScript object')); - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // Do we return the actual result document - // Either use override on the function, or go back to default on either the collection - // level or db - finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // Execute the operation - const op = { q: selector, u: document }; - op.upsert = options.upsert !== void 0 ? !!options.upsert : false; - op.multi = options.multi !== void 0 ? !!options.multi : false; - - if (options.hint) { - op.hint = options.hint; - } - - if (finalOptions.arrayFilters) { - op.arrayFilters = finalOptions.arrayFilters; - delete finalOptions.arrayFilters; - } - - if (finalOptions.retryWrites && op.multi) { - finalOptions.retryWrites = false; - } - - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } - - // Update options - coll.s.topology.update(coll.s.namespace, [op], finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) - return handleCallback(callback, toError(result.result.writeErrors[0])); - // Return the results - handleCallback(callback, null, result); - }); -} - -function updateCallback(err, r, callback) { - if (callback == null) return; - if (err) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - callback(null, r); -} - -module.exports = { - buildCountCommand, - deleteCallback, - findAndModify, - indexInformation, - nextObject, - prepareDocs, - insertDocuments, - removeDocuments, - updateDocuments, - updateCallback -}; diff --git a/node_modules/mongodb/lib/operations/connect.js b/node_modules/mongodb/lib/operations/connect.js deleted file mode 100644 index 178077e..0000000 --- a/node_modules/mongodb/lib/operations/connect.js +++ /dev/null @@ -1,804 +0,0 @@ -'use strict'; - -const deprecate = require('util').deprecate; -const Logger = require('../core').Logger; -const MongoCredentials = require('../core').MongoCredentials; -const MongoError = require('../core').MongoError; -const Mongos = require('../topologies/mongos'); -const NativeTopology = require('../topologies/native_topology'); -const parse = require('../core').parseConnectionString; -const ReadConcern = require('../read_concern'); -const ReadPreference = require('../core').ReadPreference; -const ReplSet = require('../topologies/replset'); -const Server = require('../topologies/server'); -const ServerSessionPool = require('../core').Sessions.ServerSessionPool; -const emitDeprecationWarning = require('../utils').emitDeprecationWarning; -const fs = require('fs'); -const BSON = require('../core/connection/utils').retrieveBSON(); -const CMAP_EVENT_NAMES = require('../cmap/events').CMAP_EVENT_NAMES; - -let client; -function loadClient() { - if (!client) { - client = require('../mongo_client'); - } - return client; -} - -const legacyParse = deprecate( - require('../url_parser'), - 'current URL string parser is deprecated, and will be removed in a future version. ' + - 'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.' -); - -const AUTH_MECHANISM_INTERNAL_MAP = { - DEFAULT: 'default', - 'MONGODB-CR': 'mongocr', - PLAIN: 'plain', - 'MONGODB-X509': 'x509', - 'SCRAM-SHA-1': 'scram-sha-1', - 'SCRAM-SHA-256': 'scram-sha-256' -}; - -const monitoringEvents = [ - 'timeout', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha', - 'all', - 'fullsetup', - 'open' -]; - -const VALID_AUTH_MECHANISMS = new Set([ - 'DEFAULT', - 'MONGODB-CR', - 'PLAIN', - 'MONGODB-X509', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256', - 'GSSAPI' -]); - -const validOptionNames = [ - 'poolSize', - 'ssl', - 'sslValidate', - 'sslCA', - 'sslCert', - 'sslKey', - 'sslPass', - 'sslCRL', - 'autoReconnect', - 'noDelay', - 'keepAlive', - 'keepAliveInitialDelay', - 'connectTimeoutMS', - 'family', - 'socketTimeoutMS', - 'reconnectTries', - 'reconnectInterval', - 'ha', - 'haInterval', - 'replicaSet', - 'secondaryAcceptableLatencyMS', - 'acceptableLatencyMS', - 'connectWithNoPrimary', - 'authSource', - 'w', - 'wtimeout', - 'j', - 'forceServerObjectId', - 'serializeFunctions', - 'ignoreUndefined', - 'raw', - 'bufferMaxEntries', - 'readPreference', - 'pkFactory', - 'promiseLibrary', - 'readConcern', - 'maxStalenessSeconds', - 'loggerLevel', - 'logger', - 'promoteValues', - 'promoteBuffers', - 'promoteLongs', - 'domainsEnabled', - 'checkServerIdentity', - 'validateOptions', - 'appname', - 'auth', - 'user', - 'password', - 'authMechanism', - 'compression', - 'fsync', - 'readPreferenceTags', - 'numberOfRetries', - 'auto_reconnect', - 'minSize', - 'monitorCommands', - 'retryWrites', - 'retryReads', - 'useNewUrlParser', - 'useUnifiedTopology', - 'serverSelectionTimeoutMS', - 'useRecoveryToken', - 'autoEncryption', - 'driverInfo', - 'tls', - 'tlsInsecure', - 'tlsinsecure', - 'tlsAllowInvalidCertificates', - 'tlsAllowInvalidHostnames', - 'tlsCAFile', - 'tlsCertificateFile', - 'tlsCertificateKeyFile', - 'tlsCertificateKeyFilePassword', - 'minHeartbeatFrequencyMS', - 'heartbeatFrequencyMS', - 'waitQueueTimeoutMS' -]; - -const ignoreOptionNames = ['native_parser']; -const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db']; - -// Validate options object -function validOptions(options) { - const _validOptions = validOptionNames.concat(legacyOptionNames); - - for (const name in options) { - if (ignoreOptionNames.indexOf(name) !== -1) { - continue; - } - - if (_validOptions.indexOf(name) === -1) { - if (options.validateOptions) { - return new MongoError(`option ${name} is not supported`); - } else { - console.warn(`the options [${name}] is not supported`); - } - } - - if (legacyOptionNames.indexOf(name) !== -1) { - console.warn( - `the server/replset/mongos/db options are deprecated, ` + - `all their options are supported at the top level of the options object [${validOptionNames}]` - ); - } - } -} - -const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => { - obj[name.toLowerCase()] = name; - return obj; -}, {}); - -function addListeners(mongoClient, topology) { - topology.on('authenticated', createListener(mongoClient, 'authenticated')); - topology.on('error', createListener(mongoClient, 'error')); - topology.on('timeout', createListener(mongoClient, 'timeout')); - topology.on('close', createListener(mongoClient, 'close')); - topology.on('parseError', createListener(mongoClient, 'parseError')); - topology.once('open', createListener(mongoClient, 'open')); - topology.once('fullsetup', createListener(mongoClient, 'fullsetup')); - topology.once('all', createListener(mongoClient, 'all')); - topology.on('reconnect', createListener(mongoClient, 'reconnect')); -} - -function assignTopology(client, topology) { - client.topology = topology; - - if (!(topology instanceof NativeTopology)) { - topology.s.sessionPool = new ServerSessionPool(topology.s.coreTopology); - } -} - -// Clear out all events -function clearAllEvents(topology) { - monitoringEvents.forEach(event => topology.removeAllListeners(event)); -} - -// Collect all events in order from SDAM -function collectEvents(mongoClient, topology) { - let MongoClient = loadClient(); - const collectedEvents = []; - - if (mongoClient instanceof MongoClient) { - monitoringEvents.forEach(event => { - topology.on(event, (object1, object2) => { - if (event === 'open') { - collectedEvents.push({ event: event, object1: mongoClient }); - } else { - collectedEvents.push({ event: event, object1: object1, object2: object2 }); - } - }); - }); - } - - return collectedEvents; -} - -function resolveTLSOptions(options) { - if (options.tls == null) { - return; - } - - ['sslCA', 'sslKey', 'sslCert'].forEach(optionName => { - if (options[optionName]) { - options[optionName] = fs.readFileSync(options[optionName]); - } - }); -} - -const emitDeprecationForNonUnifiedTopology = deprecate(() => {}, -'current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. ' + 'To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.'); - -function connect(mongoClient, url, options, callback) { - options = Object.assign({}, options); - - // If callback is null throw an exception - if (callback == null) { - throw new Error('no callback function provided'); - } - - let didRequestAuthentication = false; - const logger = Logger('MongoClient', options); - - // Did we pass in a Server/ReplSet/Mongos - if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) { - return connectWithUrl(mongoClient, url, options, connectCallback); - } - - const useNewUrlParser = options.useNewUrlParser !== false; - - const parseFn = useNewUrlParser ? parse : legacyParse; - const transform = useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions; - - parseFn(url, options, (err, _object) => { - // Do not attempt to connect if parsing error - if (err) return callback(err); - - // Flatten - const object = transform(_object); - - // Parse the string - const _finalOptions = createUnifiedOptions(object, options); - - // Check if we have connection and socket timeout set - if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000; - if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 10000; - if (_finalOptions.retryWrites == null) _finalOptions.retryWrites = true; - if (_finalOptions.useRecoveryToken == null) _finalOptions.useRecoveryToken = true; - if (_finalOptions.readPreference == null) _finalOptions.readPreference = 'primary'; - - if (_finalOptions.db_options && _finalOptions.db_options.auth) { - delete _finalOptions.db_options.auth; - } - - // `journal` should be translated to `j` for the driver - if (_finalOptions.journal != null) { - _finalOptions.j = _finalOptions.journal; - _finalOptions.journal = undefined; - } - - // resolve tls options if needed - resolveTLSOptions(_finalOptions); - - // Store the merged options object - mongoClient.s.options = _finalOptions; - - // Failure modes - if (object.servers.length === 0) { - return callback(new Error('connection string must contain at least one seed host')); - } - - if (_finalOptions.auth && !_finalOptions.credentials) { - try { - didRequestAuthentication = true; - _finalOptions.credentials = generateCredentials( - mongoClient, - _finalOptions.auth.user, - _finalOptions.auth.password, - _finalOptions - ); - } catch (err) { - return callback(err); - } - } - - if (_finalOptions.useUnifiedTopology) { - return createTopology(mongoClient, 'unified', _finalOptions, connectCallback); - } - - emitDeprecationForNonUnifiedTopology(); - - // Do we have a replicaset then skip discovery and go straight to connectivity - if (_finalOptions.replicaSet || _finalOptions.rs_name) { - return createTopology(mongoClient, 'replicaset', _finalOptions, connectCallback); - } else if (object.servers.length > 1) { - return createTopology(mongoClient, 'mongos', _finalOptions, connectCallback); - } else { - return createServer(mongoClient, _finalOptions, connectCallback); - } - }); - - function connectCallback(err, topology) { - const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`; - if (err && err.message === 'no mongos proxies found in seed list') { - if (logger.isWarn()) { - logger.warn(warningMessage); - } - - // Return a more specific error message for MongoClient.connect - return callback(new MongoError(warningMessage)); - } - - if (didRequestAuthentication) { - mongoClient.emit('authenticated', null, true); - } - - // Return the error and db instance - callback(err, topology); - } -} - -function connectWithUrl(mongoClient, url, options, connectCallback) { - // Set the topology - assignTopology(mongoClient, url); - - // Add listeners - addListeners(mongoClient, url); - - // Propagate the events to the client - relayEvents(mongoClient, url); - - let finalOptions = Object.assign({}, options); - - // If we have a readPreference passed in by the db options, convert it from a string - if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { - finalOptions.readPreference = new ReadPreference( - options.readPreference || options.read_preference - ); - } - - const isDoingAuth = finalOptions.user || finalOptions.password || finalOptions.authMechanism; - if (isDoingAuth && !finalOptions.credentials) { - try { - finalOptions.credentials = generateCredentials( - mongoClient, - finalOptions.user, - finalOptions.password, - finalOptions - ); - } catch (err) { - return connectCallback(err, url); - } - } - - return url.connect(finalOptions, connectCallback); -} - -function createListener(mongoClient, event) { - const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']); - return (v1, v2) => { - if (eventSet.has(event)) { - return mongoClient.emit(event, mongoClient); - } - - mongoClient.emit(event, v1, v2); - }; -} - -function createServer(mongoClient, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; - - // Set default options - const servers = translateOptions(options); - - const server = servers[0]; - - // Propagate the events to the client - const collectedEvents = collectEvents(mongoClient, server); - - // Connect to topology - server.connect(options, (err, topology) => { - if (err) { - server.close(true); - return callback(err); - } - // Clear out all the collected event listeners - clearAllEvents(server); - - // Relay all the events - relayEvents(mongoClient, server); - // Add listeners - addListeners(mongoClient, server); - // Check if we are really speaking to a mongos - const ismaster = topology.lastIsMaster(); - - // Set the topology - assignTopology(mongoClient, topology); - - // Do we actually have a mongos - if (ismaster && ismaster.msg === 'isdbgrid') { - // Destroy the current connection - topology.close(); - // Create mongos connection instead - return createTopology(mongoClient, 'mongos', options, callback); - } - - // Fire all the events - replayEvents(mongoClient, collectedEvents); - // Otherwise callback - callback(err, topology); - }); -} - -const DEPRECATED_UNIFIED_EVENTS = new Set([ - 'reconnect', - 'reconnectFailed', - 'attemptReconnect', - 'joined', - 'left', - 'ping', - 'ha', - 'all', - 'fullsetup', - 'open' -]); - -function registerDeprecatedEventNotifiers(client) { - client.on('newListener', eventName => { - if (DEPRECATED_UNIFIED_EVENTS.has(eventName)) { - emitDeprecationWarning( - `The \`${eventName}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`, - 'DeprecationWarning' - ); - } - }); -} - -function createTopology(mongoClient, topologyType, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; - - const translationOptions = {}; - if (topologyType === 'unified') translationOptions.createServers = false; - - // Set default options - const servers = translateOptions(options, translationOptions); - - // determine CSFLE support - if (options.autoEncryption != null) { - let AutoEncrypter; - try { - require.resolve('mongodb-client-encryption'); - } catch (err) { - callback( - new MongoError( - 'Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project' - ) - ); - return; - } - - try { - let mongodbClientEncryption = require('mongodb-client-encryption'); - if (typeof mongodbClientEncryption.extension !== 'function') { - callback( - new MongoError( - 'loaded version of `mongodb-client-encryption` does not have property `extension`. Please make sure you are loading the correct version of `mongodb-client-encryption`' - ) - ); - } - AutoEncrypter = mongodbClientEncryption.extension(require('../../index')).AutoEncrypter; - } catch (err) { - callback(err); - return; - } - - const mongoCryptOptions = Object.assign( - { - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]) - }, - options.autoEncryption - ); - - options.autoEncrypter = new AutoEncrypter(mongoClient, mongoCryptOptions); - } - - // Create the topology - let topology; - if (topologyType === 'mongos') { - topology = new Mongos(servers, options); - } else if (topologyType === 'replicaset') { - topology = new ReplSet(servers, options); - } else if (topologyType === 'unified') { - topology = new NativeTopology(options.servers, options); - registerDeprecatedEventNotifiers(mongoClient); - } - - // Add listeners - addListeners(mongoClient, topology); - - // Propagate the events to the client - relayEvents(mongoClient, topology); - - // Open the connection - assignTopology(mongoClient, topology); - - // initialize CSFLE if requested - if (options.autoEncrypter) { - options.autoEncrypter.init(err => { - if (err) { - callback(err); - return; - } - - topology.connect(options, err => { - if (err) { - topology.close(true); - callback(err); - return; - } - - callback(undefined, topology); - }); - }); - - return; - } - - // otherwise connect normally - topology.connect(options, err => { - if (err) { - topology.close(true); - return callback(err); - } - - callback(undefined, topology); - return; - }); -} - -function createUnifiedOptions(finalOptions, options) { - const childOptions = [ - 'mongos', - 'server', - 'db', - 'replset', - 'db_options', - 'server_options', - 'rs_options', - 'mongos_options' - ]; - const noMerge = ['readconcern', 'compression', 'autoencryption']; - - for (const name in options) { - if (noMerge.indexOf(name.toLowerCase()) !== -1) { - finalOptions[name] = options[name]; - } else if (childOptions.indexOf(name.toLowerCase()) !== -1) { - finalOptions = mergeOptions(finalOptions, options[name], false); - } else { - if ( - options[name] && - typeof options[name] === 'object' && - !Buffer.isBuffer(options[name]) && - !Array.isArray(options[name]) - ) { - finalOptions = mergeOptions(finalOptions, options[name], true); - } else { - finalOptions[name] = options[name]; - } - } - } - - return finalOptions; -} - -function generateCredentials(client, username, password, options) { - options = Object.assign({}, options); - - // the default db to authenticate against is 'self' - // if authententicate is called from a retry context, it may be another one, like admin - const source = options.authSource || options.authdb || options.dbName; - - // authMechanism - const authMechanismRaw = options.authMechanism || 'DEFAULT'; - const authMechanism = authMechanismRaw.toUpperCase(); - - if (!VALID_AUTH_MECHANISMS.has(authMechanism)) { - throw MongoError.create({ - message: `authentication mechanism ${authMechanismRaw} not supported', options.authMechanism`, - driver: true - }); - } - - if (authMechanism === 'GSSAPI') { - return new MongoCredentials({ - mechanism: process.platform === 'win32' ? 'sspi' : 'gssapi', - mechanismProperties: options, - source, - username, - password - }); - } - - return new MongoCredentials({ - mechanism: AUTH_MECHANISM_INTERNAL_MAP[authMechanism], - source, - username, - password - }); -} - -function legacyTransformUrlOptions(object) { - return mergeOptions(createUnifiedOptions({}, object), object, false); -} - -function mergeOptions(target, source, flatten) { - for (const name in source) { - if (source[name] && typeof source[name] === 'object' && flatten) { - target = mergeOptions(target, source[name], flatten); - } else { - target[name] = source[name]; - } - } - - return target; -} - -function relayEvents(mongoClient, topology) { - const serverOrCommandEvents = [ - // APM - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - - // SDAM - 'serverOpening', - 'serverClosed', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - - // Legacy - 'joined', - 'left', - 'ping', - 'ha' - ].concat(CMAP_EVENT_NAMES); - - serverOrCommandEvents.forEach(event => { - topology.on(event, (object1, object2) => { - mongoClient.emit(event, object1, object2); - }); - }); -} - -// -// Replay any events due to single server connection switching to Mongos -// -function replayEvents(mongoClient, events) { - for (let i = 0; i < events.length; i++) { - mongoClient.emit(events[i].event, events[i].object1, events[i].object2); - } -} - -function transformUrlOptions(_object) { - let object = Object.assign({ servers: _object.hosts }, _object.options); - for (let name in object) { - const camelCaseName = LEGACY_OPTIONS_MAP[name]; - if (camelCaseName) { - object[camelCaseName] = object[name]; - } - } - - const hasUsername = _object.auth && _object.auth.username; - const hasAuthMechanism = _object.options && _object.options.authMechanism; - if (hasUsername || hasAuthMechanism) { - object.auth = Object.assign({}, _object.auth); - if (object.auth.db) { - object.authSource = object.authSource || object.auth.db; - } - - if (object.auth.username) { - object.auth.user = object.auth.username; - } - } - - if (_object.defaultDatabase) { - object.dbName = _object.defaultDatabase; - } - - if (object.maxPoolSize) { - object.poolSize = object.maxPoolSize; - } - - if (object.readConcernLevel) { - object.readConcern = new ReadConcern(object.readConcernLevel); - } - - if (object.wTimeoutMS) { - object.wtimeout = object.wTimeoutMS; - } - - if (_object.srvHost) { - object.srvHost = _object.srvHost; - } - - return object; -} - -function translateOptions(options, translationOptions) { - translationOptions = Object.assign({}, { createServers: true }, translationOptions); - - // If we have a readPreference passed in by the db options - if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { - options.readPreference = new ReadPreference(options.readPreference || options.read_preference); - } - - // Do we have readPreference tags, add them - if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { - options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; - } - - // Do we have maxStalenessSeconds - if (options.maxStalenessSeconds) { - options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; - } - - // Set the socket and connection timeouts - if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000; - if (options.connectTimeoutMS == null) options.connectTimeoutMS = 10000; - - if (!translationOptions.createServers) { - return; - } - - // Create server instances - return options.servers.map(serverObj => { - return serverObj.domain_socket - ? new Server(serverObj.domain_socket, 27017, options) - : new Server(serverObj.host, serverObj.port, options); - }); -} - -module.exports = { validOptions, connect }; diff --git a/node_modules/mongodb/lib/operations/count.js b/node_modules/mongodb/lib/operations/count.js deleted file mode 100644 index a7216d6..0000000 --- a/node_modules/mongodb/lib/operations/count.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict'; - -const buildCountCommand = require('./common_functions').buildCountCommand; -const OperationBase = require('./operation').OperationBase; - -class CountOperation extends OperationBase { - constructor(cursor, applySkipLimit, options) { - super(options); - - this.cursor = cursor; - this.applySkipLimit = applySkipLimit; - } - - execute(callback) { - const cursor = this.cursor; - const applySkipLimit = this.applySkipLimit; - const options = this.options; - - if (applySkipLimit) { - if (typeof cursor.cursorSkip() === 'number') options.skip = cursor.cursorSkip(); - if (typeof cursor.cursorLimit() === 'number') options.limit = cursor.cursorLimit(); - } - - // Ensure we have the right read preference inheritance - if (options.readPreference) { - cursor.setReadPreference(options.readPreference); - } - - if ( - typeof options.maxTimeMS !== 'number' && - cursor.cmd && - typeof cursor.cmd.maxTimeMS === 'number' - ) { - options.maxTimeMS = cursor.cmd.maxTimeMS; - } - - let finalOptions = {}; - finalOptions.skip = options.skip; - finalOptions.limit = options.limit; - finalOptions.hint = options.hint; - finalOptions.maxTimeMS = options.maxTimeMS; - - // Command - finalOptions.collectionName = cursor.namespace.collection; - - let command; - try { - command = buildCountCommand(cursor, cursor.cmd.query, finalOptions); - } catch (err) { - return callback(err); - } - - // Set cursor server to the same as the topology - cursor.server = cursor.topology.s.coreTopology; - - // Execute the command - cursor.topology.command( - cursor.namespace.withCollection('$cmd'), - command, - cursor.options, - (err, result) => { - callback(err, result ? result.result.n : null); - } - ); - } -} - -module.exports = CountOperation; diff --git a/node_modules/mongodb/lib/operations/count_documents.js b/node_modules/mongodb/lib/operations/count_documents.js deleted file mode 100644 index d043abf..0000000 --- a/node_modules/mongodb/lib/operations/count_documents.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -const AggregateOperation = require('./aggregate'); - -class CountDocumentsOperation extends AggregateOperation { - constructor(collection, query, options) { - const pipeline = [{ $match: query }]; - if (typeof options.skip === 'number') { - pipeline.push({ $skip: options.skip }); - } - - if (typeof options.limit === 'number') { - pipeline.push({ $limit: options.limit }); - } - - pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); - - super(collection, pipeline, options); - } - - execute(server, callback) { - super.execute(server, (err, result) => { - if (err) { - callback(err, null); - return; - } - - // NOTE: We're avoiding creating a cursor here to reduce the callstack. - const response = result.result; - if (response.cursor == null || response.cursor.firstBatch == null) { - callback(null, 0); - return; - } - - const docs = response.cursor.firstBatch; - callback(null, docs.length ? docs[0].n : 0); - }); - } -} - -module.exports = CountDocumentsOperation; diff --git a/node_modules/mongodb/lib/operations/create_collection.js b/node_modules/mongodb/lib/operations/create_collection.js deleted file mode 100644 index d8ab4ae..0000000 --- a/node_modules/mongodb/lib/operations/create_collection.js +++ /dev/null @@ -1,117 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperation = require('./command'); -const applyWriteConcern = require('../utils').applyWriteConcern; -const handleCallback = require('../utils').handleCallback; -const loadCollection = require('../dynamic_loaders').loadCollection; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; - -// Filter out any write concern options -const illegalCommandFields = [ - 'w', - 'wtimeout', - 'j', - 'fsync', - 'autoIndexId', - 'strict', - 'serializeFunctions', - 'pkFactory', - 'raw', - 'readPreference', - 'session', - 'readConcern', - 'writeConcern' -]; - -class CreateCollectionOperation extends CommandOperation { - constructor(db, name, options) { - super(db, options); - - this.name = name; - } - - _buildCommand() { - const name = this.name; - const options = this.options; - - // Create collection command - const cmd = { create: name }; - // Add all optional parameters - for (let n in options) { - if ( - options[n] != null && - typeof options[n] !== 'function' && - illegalCommandFields.indexOf(n) === -1 - ) { - cmd[n] = options[n]; - } - } - - return cmd; - } - - execute(callback) { - const db = this.db; - const name = this.name; - const options = this.options; - - let Collection = loadCollection(); - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - let listCollectionOptions = Object.assign({}, options, { nameOnly: true }); - listCollectionOptions = applyWriteConcern(listCollectionOptions, { db }, listCollectionOptions); - - // Check if we have the name - db.listCollections({ name }, listCollectionOptions) - .setReadPreference(ReadPreference.PRIMARY) - .toArray((err, collections) => { - if (err != null) return handleCallback(callback, err, null); - if (collections.length > 0 && listCollectionOptions.strict) { - return handleCallback( - callback, - MongoError.create({ - message: `Collection ${name} already exists. Currently in strict mode.`, - driver: true - }), - null - ); - } else if (collections.length > 0) { - try { - return handleCallback( - callback, - null, - new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err); - } - } - - // Execute command - super.execute(err => { - if (err) return handleCallback(callback, err); - - try { - return handleCallback( - callback, - null, - new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err); - } - }); - }); - } -} - -defineAspects(CreateCollectionOperation, Aspect.WRITE_OPERATION); - -module.exports = CreateCollectionOperation; diff --git a/node_modules/mongodb/lib/operations/create_index.js b/node_modules/mongodb/lib/operations/create_index.js deleted file mode 100644 index 98bba71..0000000 --- a/node_modules/mongodb/lib/operations/create_index.js +++ /dev/null @@ -1,92 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const parseIndexOptions = require('../utils').parseIndexOptions; - -const keysToOmit = new Set([ - 'name', - 'key', - 'writeConcern', - 'w', - 'wtimeout', - 'j', - 'fsync', - 'readPreference', - 'session' -]); - -class CreateIndexOperation extends CommandOperation { - constructor(db, name, fieldOrSpec, options) { - super(db, options); - - // Build the index - const indexParameters = parseIndexOptions(fieldOrSpec); - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - // Set up the index - const indexesObject = { name: indexName, key: indexParameters.fieldHash }; - - this.name = name; - this.fieldOrSpec = fieldOrSpec; - this.indexes = indexesObject; - } - - _buildCommand() { - const options = this.options; - const name = this.name; - const indexes = this.indexes; - - // merge all the options - for (let optionName in options) { - if (!keysToOmit.has(optionName)) { - indexes[optionName] = options[optionName]; - } - } - - // Create command, apply write concern to command - const cmd = { createIndexes: name, indexes: [indexes] }; - - return cmd; - } - - execute(callback) { - const db = this.db; - const options = this.options; - const indexes = this.indexes; - - // Get capabilities - const capabilities = db.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (options.collation && capabilities && !capabilities.commandsTakeCollation) { - // Create a new error - const error = new MongoError('server/primary/mongos does not support collation'); - error.code = 67; - // Return the error - return callback(error); - } - - // Ensure we have a callback - if (options.writeConcern && typeof callback !== 'function') { - throw MongoError.create({ - message: 'Cannot use a writeConcern without a provided callback', - driver: true - }); - } - - // Attempt to run using createIndexes command - super.execute((err, result) => { - if (err == null) return handleCallback(callback, err, indexes.name); - - return handleCallback(callback, err, result); - }); - } -} - -defineAspects(CreateIndexOperation, Aspect.WRITE_OPERATION); - -module.exports = CreateIndexOperation; diff --git a/node_modules/mongodb/lib/operations/create_indexes.js b/node_modules/mongodb/lib/operations/create_indexes.js deleted file mode 100644 index 46228e8..0000000 --- a/node_modules/mongodb/lib/operations/create_indexes.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; -const executeCommand = require('./db_ops').executeCommand; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; - -class CreateIndexesOperation extends OperationBase { - constructor(collection, indexSpecs, options) { - super(options); - - this.collection = collection; - this.indexSpecs = indexSpecs; - } - - execute(callback) { - const coll = this.collection; - const indexSpecs = this.indexSpecs; - let options = this.options; - - const capabilities = coll.s.topology.capabilities(); - - // Ensure we generate the correct name if the parameter is not set - for (let i = 0; i < indexSpecs.length; i++) { - if (indexSpecs[i].name == null) { - const keys = []; - - // Did the user pass in a collation, check if our write server supports it - if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - for (let name in indexSpecs[i].key) { - keys.push(`${name}_${indexSpecs[i].key[name]}`); - } - - // Set the name - indexSpecs[i].name = keys.join('_'); - } - } - - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Execute the index - executeCommand( - coll.s.db, - { - createIndexes: coll.collectionName, - indexes: indexSpecs - }, - options, - callback - ); - } -} - -defineAspects(CreateIndexesOperation, Aspect.WRITE_OPERATION); - -module.exports = CreateIndexesOperation; diff --git a/node_modules/mongodb/lib/operations/cursor_ops.js b/node_modules/mongodb/lib/operations/cursor_ops.js deleted file mode 100644 index fda4c91..0000000 --- a/node_modules/mongodb/lib/operations/cursor_ops.js +++ /dev/null @@ -1,167 +0,0 @@ -'use strict'; - -const buildCountCommand = require('./collection_ops').buildCountCommand; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const push = Array.prototype.push; -const CursorState = require('../core/cursor').CursorState; - -/** - * Get the count of documents for this cursor. - * - * @method - * @param {Cursor} cursor The Cursor instance on which to count. - * @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options. - * @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options. - * @param {Cursor~countResultCallback} [callback] The result callback. - */ -function count(cursor, applySkipLimit, opts, callback) { - if (applySkipLimit) { - if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip(); - if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit(); - } - - // Ensure we have the right read preference inheritance - if (opts.readPreference) { - cursor.setReadPreference(opts.readPreference); - } - - if ( - typeof opts.maxTimeMS !== 'number' && - cursor.cmd && - typeof cursor.cmd.maxTimeMS === 'number' - ) { - opts.maxTimeMS = cursor.cmd.maxTimeMS; - } - - let options = {}; - options.skip = opts.skip; - options.limit = opts.limit; - options.hint = opts.hint; - options.maxTimeMS = opts.maxTimeMS; - - // Command - options.collectionName = cursor.namespace.collection; - - let command; - try { - command = buildCountCommand(cursor, cursor.cmd.query, options); - } catch (err) { - return callback(err); - } - - // Set cursor server to the same as the topology - cursor.server = cursor.topology.s.coreTopology; - - // Execute the command - cursor.topology.command( - cursor.namespace.withCollection('$cmd'), - command, - cursor.options, - (err, result) => { - callback(err, result ? result.result.n : null); - } - ); -} - -/** - * Iterates over all the documents for this cursor. See Cursor.prototype.each for more information. - * - * @method - * @deprecated - * @param {Cursor} cursor The Cursor instance on which to run. - * @param {Cursor~resultCallback} callback The result callback. - */ -function each(cursor, callback) { - if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); - if (cursor.isNotified()) return; - if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) { - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - } - - if (cursor.s.state === CursorState.INIT) { - cursor.s.state = CursorState.OPEN; - } - - // Define function to avoid global scope escape - let fn = null; - // Trampoline all the entries - if (cursor.bufferedCount() > 0) { - while ((fn = loop(cursor, callback))) fn(cursor, callback); - each(cursor, callback); - } else { - cursor.next((err, item) => { - if (err) return handleCallback(callback, err); - if (item == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); - } - - if (handleCallback(callback, null, item) === false) return; - each(cursor, callback); - }); - } -} - -// Trampoline emptying the number of retrieved items -// without incurring a nextTick operation -function loop(cursor, callback) { - // No more items we are done - if (cursor.bufferedCount() === 0) return; - // Get the next document - cursor._next(callback); - // Loop - return loop; -} - -/** - * Returns an array of documents. See Cursor.prototype.toArray for more information. - * - * @method - * @param {Cursor} cursor The Cursor instance from which to get the next document. - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - */ -function toArray(cursor, callback) { - const items = []; - - // Reset cursor - cursor.rewind(); - cursor.s.state = CursorState.INIT; - - // Fetch all the documents - const fetchDocs = () => { - cursor._next((err, doc) => { - if (err) { - return handleCallback(callback, err); - } - - if (doc == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); - } - - // Add doc to items - items.push(doc); - - // Get all buffered objects - if (cursor.bufferedCount() > 0) { - let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); - - // Transform the doc if transform method added - if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { - docs = docs.map(cursor.s.transforms.doc); - } - - push.apply(items, docs); - } - - // Attempt a fetch - fetchDocs(); - }); - }; - - fetchDocs(); -} - -module.exports = { count, each, toArray }; diff --git a/node_modules/mongodb/lib/operations/db_ops.js b/node_modules/mongodb/lib/operations/db_ops.js deleted file mode 100644 index 8fc458a..0000000 --- a/node_modules/mongodb/lib/operations/db_ops.js +++ /dev/null @@ -1,468 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const resolveReadPreference = require('../utils').resolveReadPreference; -const debugOptions = require('../utils').debugOptions; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const parseIndexOptions = require('../utils').parseIndexOptions; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const CONSTANTS = require('../constants'); -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -const debugFields = [ - 'authSource', - 'w', - 'wtimeout', - 'j', - 'native_parser', - 'forceServerObjectId', - 'serializeFunctions', - 'raw', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bufferMaxEntries', - 'numberOfRetries', - 'retryMiliSeconds', - 'readPreference', - 'pkFactory', - 'parentDb', - 'promiseLibrary', - 'noListener' -]; - -/** - * Creates an index on the db and collection. - * @method - * @param {Db} db The Db instance on which to create an index. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function createIndex(db, name, fieldOrSpec, options, callback) { - // Get the write concern options - let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); - finalOptions = applyWriteConcern(finalOptions, { db }, options); - - // Ensure we have a callback - if (finalOptions.writeConcern && typeof callback !== 'function') { - throw MongoError.create({ - message: 'Cannot use a writeConcern without a provided callback', - driver: true - }); - } - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // Attempt to run using createIndexes command - createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => { - if (err == null) return handleCallback(callback, err, result); - - /** - * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert: - * 67 = 'CannotCreateIndex' (malformed index options) - * 85 = 'IndexOptionsConflict' (index already exists with different options) - * 86 = 'IndexKeySpecsConflict' (index already exists with the same name) - * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) - * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) - * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`) - */ - if ( - err.code === 67 || - err.code === 11000 || - err.code === 85 || - err.code === 86 || - err.code === 11600 || - err.code === 197 - ) { - return handleCallback(callback, err, result); - } - - // Create command - const doc = createCreateIndexCommand(db, name, fieldOrSpec, options); - // Set no key checking - finalOptions.checkKeys = false; - // Insert document - db.s.topology.insert( - db.s.namespace.withCollection(CONSTANTS.SYSTEM_INDEX_COLLECTION), - doc, - finalOptions, - (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err); - if (result == null) return handleCallback(callback, null, null); - if (result.result.writeErrors) - return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); - handleCallback(callback, null, doc.name); - } - ); - }); -} - -// Add listeners to topology -function createListener(db, e, object) { - function listener(err) { - if (object.listeners(e).length > 0) { - object.emit(e, err, db); - - // Emit on all associated db's if available - for (let i = 0; i < db.s.children.length; i++) { - db.s.children[i].emit(e, err, db.s.children[i]); - } - } - } - return listener; -} - -/** - * Ensures that an index exists. If it does not, creates it. - * - * @method - * @param {Db} db The Db instance on which to ensure the index. - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function ensureIndex(db, name, fieldOrSpec, options, callback) { - // Get the write concern options - const finalOptions = applyWriteConcern({}, { db }, options); - // Create command - const selector = createCreateIndexCommand(db, name, fieldOrSpec, options); - const index_name = selector.name; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // Merge primary readPreference - finalOptions.readPreference = ReadPreference.PRIMARY; - - // Check if the index already exists - indexInformation(db, name, finalOptions, (err, indexInformation) => { - if (err != null && err.code !== 26) return handleCallback(callback, err, null); - // If the index does not exist, create it - if (indexInformation == null || !indexInformation[index_name]) { - createIndex(db, name, fieldOrSpec, options, callback); - } else { - if (typeof callback === 'function') return handleCallback(callback, null, index_name); - } - }); -} - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Db} db The Db instance. - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options] Optional settings. See Db.prototype.eval for a list of options. - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - */ -function evaluate(db, code, parameters, options, callback) { - let finalCode = code; - let finalParameters = []; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // If not a code object translate to one - if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode); - // Ensure the parameters are correct - if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = [parameters]; - } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = parameters; - } - - // Create execution selector - let cmd = { $eval: finalCode, args: finalParameters }; - // Check if the nolock parameter is passed in - if (options['nolock']) { - cmd['nolock'] = options['nolock']; - } - - // Set primary read preference - options.readPreference = new ReadPreference(ReadPreference.PRIMARY); - - // Execute the command - executeCommand(db, cmd, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result && result.ok === 1) return handleCallback(callback, null, result.retval); - if (result) - return handleCallback( - callback, - MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }), - null - ); - handleCallback(callback, err, result); - }); -} - -/** - * Execute a command - * - * @method - * @param {Db} db The Db instance on which to execute the command. - * @param {object} command The command hash - * @param {object} [options] Optional settings. See Db.prototype.command for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeCommand(db, command, options, callback) { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Get the db name we are executing against - const dbName = options.dbName || options.authdb || db.databaseName; - - // Convert the readPreference if its not a write - options.readPreference = resolveReadPreference(db, options); - - // Debug information - if (db.s.logger.isDebug()) - db.s.logger.debug( - `executing command ${JSON.stringify( - command - )} against ${dbName}.$cmd with options [${JSON.stringify( - debugOptions(debugFields, options) - )}]` - ); - - // Execute command - db.s.topology.command(db.s.namespace.withCollection('$cmd'), command, options, (err, result) => { - if (err) return handleCallback(callback, err); - if (options.full) return handleCallback(callback, null, result); - handleCallback(callback, null, result.result); - }); -} - -/** - * Runs a command on the database as admin. - * - * @method - * @param {Db} db The Db instance on which to execute the command. - * @param {object} command The command hash - * @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeDbAdminCommand(db, command, options, callback) { - const namespace = new MongoDBNamespace('admin', '$cmd'); - - db.s.topology.command(namespace, command, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); -} - -/** - * Retrieves this collections index info. - * - * @method - * @param {Db} db The Db instance on which to retrieve the index info. - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function indexInformation(db, name, options, callback) { - // If we specified full information - const full = options['full'] == null ? false : options['full']; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Process all the results from the index command and collection - function processResults(indexes) { - // Contains all the information - let info = {}; - // Process all the indexes - for (let i = 0; i < indexes.length; i++) { - const index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for (let name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - db.collection(name) - .listIndexes(options) - .toArray((err, indexes) => { - if (err) return callback(toError(err)); - if (!Array.isArray(indexes)) return handleCallback(callback, null, []); - if (full) return handleCallback(callback, null, indexes); - handleCallback(callback, null, processResults(indexes)); - }); -} - -/** - * Retrieve the current profiling information for MongoDB - * - * @method - * @param {Db} db The Db instance on which to retrieve the profiling info. - * @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options. - * @param {Db~resultCallback} [callback] The command result callback. - * @deprecated Query the system.profile collection directly. - */ -function profilingInfo(db, options, callback) { - try { - db.collection('system.profile') - .find({}, options) - .toArray(callback); - } catch (err) { - return callback(err, null); - } -} - -// Validate the database name -function validateDatabaseName(databaseName) { - if (typeof databaseName !== 'string') - throw MongoError.create({ message: 'database name must be a string', driver: true }); - if (databaseName.length === 0) - throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); - if (databaseName === '$external') return; - - const invalidChars = [' ', '.', '$', '/', '\\']; - for (let i = 0; i < invalidChars.length; i++) { - if (databaseName.indexOf(invalidChars[i]) !== -1) - throw MongoError.create({ - message: "database names cannot contain the character '" + invalidChars[i] + "'", - driver: true - }); - } -} - -/** - * Create the command object for Db.prototype.createIndex. - * - * @param {Db} db The Db instance on which to create the command. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @return {Object} The insert command object. - */ -function createCreateIndexCommand(db, name, fieldOrSpec, options) { - const indexParameters = parseIndexOptions(fieldOrSpec); - const fieldHash = indexParameters.fieldHash; - - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - const selector = { - ns: db.s.namespace.withCollection(name).toString(), - key: fieldHash, - name: indexName - }; - - // Ensure we have a correct finalUnique - const finalUnique = options == null || 'object' === typeof options ? false : options; - // Set up options - options = options == null || typeof options === 'boolean' ? {} : options; - - // Add all the options - const keysToOmit = Object.keys(selector); - for (let optionName in options) { - if (keysToOmit.indexOf(optionName) === -1) { - selector[optionName] = options[optionName]; - } - } - - if (selector['unique'] == null) selector['unique'] = finalUnique; - - // Remove any write concern operations - const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session']; - for (let i = 0; i < removeKeys.length; i++) { - delete selector[removeKeys[i]]; - } - - // Return the command creation selector - return selector; -} - -/** - * Create index using the createIndexes command. - * - * @param {Db} db The Db instance on which to execute the command. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback. - */ -function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) { - // Build the index - const indexParameters = parseIndexOptions(fieldOrSpec); - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - // Set up the index - const indexes = [{ name: indexName, key: indexParameters.fieldHash }]; - // merge all the options - const keysToOmit = Object.keys(indexes[0]).concat([ - 'writeConcern', - 'w', - 'wtimeout', - 'j', - 'fsync', - 'readPreference', - 'session' - ]); - - for (let optionName in options) { - if (keysToOmit.indexOf(optionName) === -1) { - indexes[0][optionName] = options[optionName]; - } - } - - // Get capabilities - const capabilities = db.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { - // Create a new error - const error = new MongoError('server/primary/mongos does not support collation'); - error.code = 67; - // Return the error - return callback(error); - } - - // Create command, apply write concern to command - const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options); - - // ReadPreference primary - options.readPreference = ReadPreference.PRIMARY; - - // Build the command - executeCommand(db, cmd, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result.ok === 0) return handleCallback(callback, toError(result), null); - // Return the indexName for backward compatibility - handleCallback(callback, null, indexName); - }); -} - -module.exports = { - createListener, - createIndex, - ensureIndex, - evaluate, - executeCommand, - executeDbAdminCommand, - indexInformation, - profilingInfo, - validateDatabaseName -}; diff --git a/node_modules/mongodb/lib/operations/delete_many.js b/node_modules/mongodb/lib/operations/delete_many.js deleted file mode 100644 index d881f67..0000000 --- a/node_modules/mongodb/lib/operations/delete_many.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const deleteCallback = require('./common_functions').deleteCallback; -const removeDocuments = require('./common_functions').removeDocuments; - -class DeleteManyOperation extends OperationBase { - constructor(collection, filter, options) { - super(options); - - this.collection = collection; - this.filter = filter; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const options = this.options; - - options.single = false; - removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); - } -} - -module.exports = DeleteManyOperation; diff --git a/node_modules/mongodb/lib/operations/delete_one.js b/node_modules/mongodb/lib/operations/delete_one.js deleted file mode 100644 index b05597f..0000000 --- a/node_modules/mongodb/lib/operations/delete_one.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const deleteCallback = require('./common_functions').deleteCallback; -const removeDocuments = require('./common_functions').removeDocuments; - -class DeleteOneOperation extends OperationBase { - constructor(collection, filter, options) { - super(options); - - this.collection = collection; - this.filter = filter; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const options = this.options; - - options.single = true; - removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); - } -} - -module.exports = DeleteOneOperation; diff --git a/node_modules/mongodb/lib/operations/distinct.js b/node_modules/mongodb/lib/operations/distinct.js deleted file mode 100644 index dcf4f7e..0000000 --- a/node_modules/mongodb/lib/operations/distinct.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperationV2 = require('./command_v2'); -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; - -/** - * Return a list of distinct values for the given key across a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {string} key Field of the document to find distinct values for. - * @property {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @property {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. - */ -class DistinctOperation extends CommandOperationV2 { - /** - * Construct a Distinct operation. - * - * @param {Collection} a Collection instance. - * @param {string} key Field of the document to find distinct values for. - * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @param {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. - */ - constructor(collection, key, query, options) { - super(collection, options); - - this.collection = collection; - this.key = key; - this.query = query; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(server, callback) { - const coll = this.collection; - const key = this.key; - const query = this.query; - const options = this.options; - - // Distinct command - const cmd = { - distinct: coll.collectionName, - key: key, - query: query - }; - - // Add maxTimeMS if defined - if (typeof options.maxTimeMS === 'number') { - cmd.maxTimeMS = options.maxTimeMS; - } - - // Do we have a readConcern specified - decorateWithReadConcern(cmd, coll, options); - - // Have we specified collation - try { - decorateWithCollation(cmd, coll, options); - } catch (err) { - return callback(err, null); - } - - super.executeCommand(server, cmd, (err, result) => { - if (err) { - callback(err); - return; - } - - callback(null, this.options.full ? result : result.values); - }); - } -} - -defineAspects(DistinctOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = DistinctOperation; diff --git a/node_modules/mongodb/lib/operations/drop.js b/node_modules/mongodb/lib/operations/drop.js deleted file mode 100644 index be03716..0000000 --- a/node_modules/mongodb/lib/operations/drop.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; - -class DropOperation extends CommandOperation { - constructor(db, options) { - const finalOptions = Object.assign({}, options, db.s.options); - - if (options.session) { - finalOptions.session = options.session; - } - - super(db, finalOptions); - } - - execute(callback) { - super.execute((err, result) => { - if (err) return handleCallback(callback, err); - if (result.ok) return handleCallback(callback, null, true); - handleCallback(callback, null, false); - }); - } -} - -defineAspects(DropOperation, Aspect.WRITE_OPERATION); - -class DropCollectionOperation extends DropOperation { - constructor(db, name, options) { - super(db, options); - - this.name = name; - this.namespace = `${db.namespace}.${name}`; - } - - _buildCommand() { - return { drop: this.name }; - } -} - -class DropDatabaseOperation extends DropOperation { - _buildCommand() { - return { dropDatabase: 1 }; - } -} - -module.exports = { - DropOperation, - DropCollectionOperation, - DropDatabaseOperation -}; diff --git a/node_modules/mongodb/lib/operations/drop_index.js b/node_modules/mongodb/lib/operations/drop_index.js deleted file mode 100644 index a6ca783..0000000 --- a/node_modules/mongodb/lib/operations/drop_index.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperation = require('./command'); -const applyWriteConcern = require('../utils').applyWriteConcern; -const handleCallback = require('../utils').handleCallback; - -class DropIndexOperation extends CommandOperation { - constructor(collection, indexName, options) { - super(collection.s.db, options, collection); - - this.collection = collection; - this.indexName = indexName; - } - - _buildCommand() { - const collection = this.collection; - const indexName = this.indexName; - const options = this.options; - - let cmd = { dropIndexes: collection.collectionName, index: indexName }; - - // Decorate command with writeConcern if supported - cmd = applyWriteConcern(cmd, { db: collection.s.db, collection }, options); - - return cmd; - } - - execute(callback) { - // Execute command - super.execute((err, result) => { - if (typeof callback !== 'function') return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); - } -} - -defineAspects(DropIndexOperation, Aspect.WRITE_OPERATION); - -module.exports = DropIndexOperation; diff --git a/node_modules/mongodb/lib/operations/drop_indexes.js b/node_modules/mongodb/lib/operations/drop_indexes.js deleted file mode 100644 index ed404ee..0000000 --- a/node_modules/mongodb/lib/operations/drop_indexes.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const DropIndexOperation = require('./drop_index'); -const handleCallback = require('../utils').handleCallback; - -class DropIndexesOperation extends DropIndexOperation { - constructor(collection, options) { - super(collection, '*', options); - } - - execute(callback) { - super.execute(err => { - if (err) return handleCallback(callback, err, false); - handleCallback(callback, null, true); - }); - } -} - -defineAspects(DropIndexesOperation, Aspect.WRITE_OPERATION); - -module.exports = DropIndexesOperation; diff --git a/node_modules/mongodb/lib/operations/estimated_document_count.js b/node_modules/mongodb/lib/operations/estimated_document_count.js deleted file mode 100644 index e2d6556..0000000 --- a/node_modules/mongodb/lib/operations/estimated_document_count.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperationV2 = require('./command_v2'); - -class EstimatedDocumentCountOperation extends CommandOperationV2 { - constructor(collection, query, options) { - if (typeof options === 'undefined') { - options = query; - query = undefined; - } - - super(collection, options); - this.collectionName = collection.s.namespace.collection; - if (query) { - this.query = query; - } - } - - execute(server, callback) { - const options = this.options; - const cmd = { count: this.collectionName }; - - if (this.query) { - cmd.query = this.query; - } - - if (typeof options.skip === 'number') { - cmd.skip = options.skip; - } - - if (typeof options.limit === 'number') { - cmd.limit = options.limit; - } - - if (options.hint) { - cmd.hint = options.hint; - } - - super.executeCommand(server, cmd, (err, response) => { - if (err) { - callback(err); - return; - } - - callback(null, response.n); - }); - } -} - -defineAspects(EstimatedDocumentCountOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = EstimatedDocumentCountOperation; diff --git a/node_modules/mongodb/lib/operations/execute_db_admin_command.js b/node_modules/mongodb/lib/operations/execute_db_admin_command.js deleted file mode 100644 index d15fc8e..0000000 --- a/node_modules/mongodb/lib/operations/execute_db_admin_command.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -class ExecuteDbAdminCommandOperation extends OperationBase { - constructor(db, selector, options) { - super(options); - - this.db = db; - this.selector = selector; - } - - execute(callback) { - const db = this.db; - const selector = this.selector; - const options = this.options; - - const namespace = new MongoDBNamespace('admin', '$cmd'); - db.s.topology.command(namespace, selector, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); - } -} - -module.exports = ExecuteDbAdminCommandOperation; diff --git a/node_modules/mongodb/lib/operations/execute_operation.js b/node_modules/mongodb/lib/operations/execute_operation.js deleted file mode 100644 index 80d5785..0000000 --- a/node_modules/mongodb/lib/operations/execute_operation.js +++ /dev/null @@ -1,186 +0,0 @@ -'use strict'; - -const MongoError = require('../core/error').MongoError; -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const ReadPreference = require('../core/topologies/read_preference'); -const isRetryableError = require('../core/error').isRetryableError; -const maxWireVersion = require('../core/utils').maxWireVersion; -const isUnifiedTopology = require('../core/utils').isUnifiedTopology; - -/** - * Executes the given operation with provided arguments. - * - * This method reduces large amounts of duplication in the entire codebase by providing - * a single point for determining whether callbacks or promises should be used. Additionally - * it allows for a single point of entry to provide features such as implicit sessions, which - * are required by the Driver Sessions specification in the event that a ClientSession is - * not provided - * - * @param {object} topology The topology to execute this operation on - * @param {Operation} operation The operation to execute - * @param {function} callback The command result callback - */ -function executeOperation(topology, operation, callback) { - if (topology == null) { - throw new TypeError('This method requires a valid topology instance'); - } - - if (!(operation instanceof OperationBase)) { - throw new TypeError('This method requires a valid operation instance'); - } - - if (isUnifiedTopology(topology) && topology.shouldCheckForSessionSupport()) { - return selectServerForSessionSupport(topology, operation, callback); - } - - const Promise = topology.s.promiseLibrary; - - // The driver sessions spec mandates that we implicitly create sessions for operations - // that are not explicitly provided with a session. - let session, owner; - if (topology.hasSessionSupport()) { - if (operation.session == null) { - owner = Symbol(); - session = topology.startSession({ owner }); - operation.session = session; - } else if (operation.session.hasEnded) { - throw new MongoError('Use of expired sessions is not permitted'); - } - } - - let result; - if (typeof callback !== 'function') { - result = new Promise((resolve, reject) => { - callback = (err, res) => { - if (err) return reject(err); - resolve(res); - }; - }); - } - - function executeCallback(err, result) { - if (session && session.owner === owner) { - session.endSession(); - if (operation.session === session) { - operation.clearSession(); - } - } - - callback(err, result); - } - - try { - if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) { - executeWithServerSelection(topology, operation, executeCallback); - } else { - operation.execute(executeCallback); - } - } catch (e) { - if (session && session.owner === owner) { - session.endSession(); - if (operation.session === session) { - operation.clearSession(); - } - } - - throw e; - } - - return result; -} - -function supportsRetryableReads(server) { - return maxWireVersion(server) >= 6; -} - -function executeWithServerSelection(topology, operation, callback) { - const readPreference = operation.readPreference || ReadPreference.primary; - const inTransaction = operation.session && operation.session.inTransaction(); - - if (inTransaction && !readPreference.equals(ReadPreference.primary)) { - callback( - new MongoError( - `Read preference in a transaction must be primary, not: ${readPreference.mode}` - ) - ); - - return; - } - - const serverSelectionOptions = { - readPreference, - session: operation.session - }; - - function callbackWithRetry(err, result) { - if (err == null) { - return callback(null, result); - } - - if (!isRetryableError(err)) { - return callback(err); - } - - // select a new server, and attempt to retry the operation - topology.selectServer(serverSelectionOptions, (err, server) => { - if (err || !supportsRetryableReads(server)) { - callback(err, null); - return; - } - - operation.execute(server, callback); - }); - } - - // select a server, and execute the operation against it - topology.selectServer(serverSelectionOptions, (err, server) => { - if (err) { - callback(err, null); - return; - } - - const shouldRetryReads = - topology.s.options.retryReads !== false && - operation.session && - !inTransaction && - supportsRetryableReads(server) && - operation.canRetryRead; - - if (operation.hasAspect(Aspect.RETRYABLE) && shouldRetryReads) { - operation.execute(server, callbackWithRetry); - return; - } - - operation.execute(server, callback); - }); -} - -// TODO: This is only supported for unified topology, it should go away once -// we remove support for legacy topology types. -function selectServerForSessionSupport(topology, operation, callback) { - const Promise = topology.s.promiseLibrary; - - let result; - if (typeof callback !== 'function') { - result = new Promise((resolve, reject) => { - callback = (err, result) => { - if (err) return reject(err); - resolve(result); - }; - }); - } - - topology.selectServer(ReadPreference.primaryPreferred, err => { - if (err) { - callback(err); - return; - } - - executeOperation(topology, operation, callback); - }); - - return result; -} - -module.exports = executeOperation; diff --git a/node_modules/mongodb/lib/operations/find.js b/node_modules/mongodb/lib/operations/find.js deleted file mode 100644 index 5d47db6..0000000 --- a/node_modules/mongodb/lib/operations/find.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const resolveReadPreference = require('../utils').resolveReadPreference; - -class FindOperation extends OperationBase { - constructor(collection, ns, command, options) { - super(options); - - this.ns = ns; - this.cmd = command; - this.readPreference = resolveReadPreference(collection, this.options); - } - - execute(server, callback) { - // copied from `CommandOperationV2`, to be subclassed in the future - this.server = server; - - const cursorState = this.cursorState || {}; - - // TOOD: use `MongoDBNamespace` through and through - server.query(this.ns.toString(), this.cmd, cursorState, this.options, callback); - } -} - -defineAspects(FindOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = FindOperation; diff --git a/node_modules/mongodb/lib/operations/find_and_modify.js b/node_modules/mongodb/lib/operations/find_and_modify.js deleted file mode 100644 index 8965eb4..0000000 --- a/node_modules/mongodb/lib/operations/find_and_modify.js +++ /dev/null @@ -1,98 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const decorateWithCollation = require('../utils').decorateWithCollation; -const executeCommand = require('./db_ops').executeCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const handleCallback = require('../utils').handleCallback; -const ReadPreference = require('../core').ReadPreference; - -class FindAndModifyOperation extends OperationBase { - constructor(collection, query, sort, doc, options) { - super(options); - - this.collection = collection; - this.query = query; - this.sort = sort; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const query = this.query; - const sort = formattedOrderClause(this.sort); - const doc = this.doc; - let options = this.options; - - // Create findAndModify command object - const queryObject = { - findAndModify: coll.collectionName, - query: query - }; - - if (sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; - - const projection = options.projection || options.fields; - - if (projection) { - queryObject.fields = projection; - } - - if (options.arrayFilters) { - queryObject.arrayFilters = options.arrayFilters; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; - - // Either use override on the function, or go back to default on either the collection - // level or db - options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // No check on the documents - options.checkKeys = false; - - // Final options for retryable writes and write concern - options = applyRetryableWrites(options, coll.s.db); - options = applyWriteConcern(options, { db: coll.s.db, collection: coll }, options); - - // Decorate the findAndModify command with the write Concern - if (options.writeConcern) { - queryObject.writeConcern = options.writeConcern; - } - - // Have we specified bypassDocumentValidation - if (options.bypassDocumentValidation === true) { - queryObject.bypassDocumentValidation = options.bypassDocumentValidation; - } - - options.readPreference = ReadPreference.primary; - - // Have we specified collation - try { - decorateWithCollation(queryObject, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute the command - executeCommand(coll.s.db, queryObject, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - - return handleCallback(callback, null, result); - }); - } -} - -module.exports = FindAndModifyOperation; diff --git a/node_modules/mongodb/lib/operations/find_one.js b/node_modules/mongodb/lib/operations/find_one.js deleted file mode 100644 index b584db6..0000000 --- a/node_modules/mongodb/lib/operations/find_one.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -const handleCallback = require('../utils').handleCallback; -const OperationBase = require('./operation').OperationBase; -const toError = require('../utils').toError; - -class FindOneOperation extends OperationBase { - constructor(collection, query, options) { - super(options); - - this.collection = collection; - this.query = query; - } - - execute(callback) { - const coll = this.collection; - const query = this.query; - const options = this.options; - - try { - const cursor = coll - .find(query, options) - .limit(-1) - .batchSize(1); - - // Return the item - cursor.next((err, item) => { - if (err != null) return handleCallback(callback, toError(err), null); - handleCallback(callback, null, item); - }); - } catch (e) { - callback(e); - } - } -} - -module.exports = FindOneOperation; diff --git a/node_modules/mongodb/lib/operations/find_one_and_delete.js b/node_modules/mongodb/lib/operations/find_one_and_delete.js deleted file mode 100644 index 1c7527d..0000000 --- a/node_modules/mongodb/lib/operations/find_one_and_delete.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -const FindAndModifyOperation = require('./find_and_modify'); - -class FindOneAndDeleteOperation extends FindAndModifyOperation { - constructor(collection, filter, options) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.remove = true; - - super(collection, filter, finalOptions.sort, null, finalOptions); - } -} - -module.exports = FindOneAndDeleteOperation; diff --git a/node_modules/mongodb/lib/operations/find_one_and_replace.js b/node_modules/mongodb/lib/operations/find_one_and_replace.js deleted file mode 100644 index ae37df5..0000000 --- a/node_modules/mongodb/lib/operations/find_one_and_replace.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -const FindAndModifyOperation = require('./find_and_modify'); - -class FindOneAndReplaceOperation extends FindAndModifyOperation { - constructor(collection, filter, replacement, options) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false; - finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false; - - super(collection, filter, finalOptions.sort, replacement, finalOptions); - } -} - -module.exports = FindOneAndReplaceOperation; diff --git a/node_modules/mongodb/lib/operations/find_one_and_update.js b/node_modules/mongodb/lib/operations/find_one_and_update.js deleted file mode 100644 index 6a19965..0000000 --- a/node_modules/mongodb/lib/operations/find_one_and_update.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const FindAndModifyOperation = require('./find_and_modify'); - -class FindOneAndUpdateOperation extends FindAndModifyOperation { - constructor(collection, filter, update, options) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = - typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false; - finalOptions.upsert = typeof options.upsert === 'boolean' ? options.upsert : false; - - super(collection, filter, finalOptions.sort, update, finalOptions); - } -} - -module.exports = FindOneAndUpdateOperation; diff --git a/node_modules/mongodb/lib/operations/geo_haystack_search.js b/node_modules/mongodb/lib/operations/geo_haystack_search.js deleted file mode 100644 index edd1fb1..0000000 --- a/node_modules/mongodb/lib/operations/geo_haystack_search.js +++ /dev/null @@ -1,79 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; -const decorateCommand = require('../utils').decorateCommand; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const handleCallback = require('../utils').handleCallback; -const resolveReadPreference = require('../utils').resolveReadPreference; -const toError = require('../utils').toError; - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @property {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @property {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. - */ -class GeoHaystackSearchOperation extends OperationBase { - /** - * Construct a GeoHaystackSearch operation. - * - * @param {Collection} a Collection instance. - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. - */ - constructor(collection, x, y, options) { - super(options); - - this.collection = collection; - this.x = x; - this.y = y; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(callback) { - const coll = this.collection; - const x = this.x; - const y = this.y; - let options = this.options; - - // Build command object - let commandObject = { - geoSearch: coll.collectionName, - near: [x, y] - }; - - // Remove read preference from hash if it exists - commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']); - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(coll, options); - - // Do we have a readConcern specified - decorateWithReadConcern(commandObject, coll, options); - - // Execute the command - executeCommand(coll.s.db, commandObject, options, (err, res) => { - if (err) return handleCallback(callback, err); - if (res.err || res.errmsg) handleCallback(callback, toError(res)); - // should we only be returning res.results here? Not sure if the user - // should see the other return information - handleCallback(callback, null, res); - }); - } -} - -defineAspects(GeoHaystackSearchOperation, Aspect.READ_OPERATION); - -module.exports = GeoHaystackSearchOperation; diff --git a/node_modules/mongodb/lib/operations/index_exists.js b/node_modules/mongodb/lib/operations/index_exists.js deleted file mode 100644 index bd9dc0e..0000000 --- a/node_modules/mongodb/lib/operations/index_exists.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const indexInformationDb = require('./db_ops').indexInformation; - -class IndexExistsOperation extends OperationBase { - constructor(collection, indexes, options) { - super(options); - - this.collection = collection; - this.indexes = indexes; - } - - execute(callback) { - const coll = this.collection; - const indexes = this.indexes; - const options = this.options; - - indexInformationDb(coll.s.db, coll.collectionName, options, (err, indexInformation) => { - // If we have an error return - if (err != null) return handleCallback(callback, err, null); - // Let's check for the index names - if (!Array.isArray(indexes)) - return handleCallback(callback, null, indexInformation[indexes] != null); - // Check in list of indexes - for (let i = 0; i < indexes.length; i++) { - if (indexInformation[indexes[i]] == null) { - return handleCallback(callback, null, false); - } - } - - // All keys found return true - return handleCallback(callback, null, true); - }); - } -} - -module.exports = IndexExistsOperation; diff --git a/node_modules/mongodb/lib/operations/index_information.js b/node_modules/mongodb/lib/operations/index_information.js deleted file mode 100644 index b18a603..0000000 --- a/node_modules/mongodb/lib/operations/index_information.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const indexInformation = require('./common_functions').indexInformation; - -class IndexInformationOperation extends OperationBase { - constructor(db, name, options) { - super(options); - - this.db = db; - this.name = name; - } - - execute(callback) { - const db = this.db; - const name = this.name; - const options = this.options; - - indexInformation(db, name, options, callback); - } -} - -module.exports = IndexInformationOperation; diff --git a/node_modules/mongodb/lib/operations/indexes.js b/node_modules/mongodb/lib/operations/indexes.js deleted file mode 100644 index e29a88a..0000000 --- a/node_modules/mongodb/lib/operations/indexes.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const indexInformation = require('./common_functions').indexInformation; - -class IndexesOperation extends OperationBase { - constructor(collection, options) { - super(options); - - this.collection = collection; - } - - execute(callback) { - const coll = this.collection; - let options = this.options; - - options = Object.assign({}, { full: true }, options); - indexInformation(coll.s.db, coll.collectionName, options, callback); - } -} - -module.exports = IndexesOperation; diff --git a/node_modules/mongodb/lib/operations/insert_many.js b/node_modules/mongodb/lib/operations/insert_many.js deleted file mode 100644 index 460a535..0000000 --- a/node_modules/mongodb/lib/operations/insert_many.js +++ /dev/null @@ -1,63 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const BulkWriteOperation = require('./bulk_write'); -const MongoError = require('../core').MongoError; -const prepareDocs = require('./common_functions').prepareDocs; - -class InsertManyOperation extends OperationBase { - constructor(collection, docs, options) { - super(options); - - this.collection = collection; - this.docs = docs; - } - - execute(callback) { - const coll = this.collection; - let docs = this.docs; - const options = this.options; - - if (!Array.isArray(docs)) { - return callback( - MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) - ); - } - - // If keep going set unordered - options['serializeFunctions'] = options['serializeFunctions'] || coll.s.serializeFunctions; - - docs = prepareDocs(coll, docs, options); - - // Generate the bulk write operations - const operations = [ - { - insertMany: docs - } - ]; - - const bulkWriteOperation = new BulkWriteOperation(coll, operations, options); - - bulkWriteOperation.execute((err, result) => { - if (err) return callback(err, null); - callback(null, mapInsertManyResults(docs, result)); - }); - } -} - -function mapInsertManyResults(docs, r) { - const finalResult = { - result: { ok: 1, n: r.insertedCount }, - ops: docs, - insertedCount: r.insertedCount, - insertedIds: r.insertedIds - }; - - if (r.getLastOp()) { - finalResult.result.opTime = r.getLastOp(); - } - - return finalResult; -} - -module.exports = InsertManyOperation; diff --git a/node_modules/mongodb/lib/operations/insert_one.js b/node_modules/mongodb/lib/operations/insert_one.js deleted file mode 100644 index 5e70880..0000000 --- a/node_modules/mongodb/lib/operations/insert_one.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const MongoError = require('../core').MongoError; -const OperationBase = require('./operation').OperationBase; -const insertDocuments = require('./common_functions').insertDocuments; - -class InsertOneOperation extends OperationBase { - constructor(collection, doc, options) { - super(options); - - this.collection = collection; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const doc = this.doc; - const options = this.options; - - if (Array.isArray(doc)) { - return callback( - MongoError.create({ message: 'doc parameter must be an object', driver: true }) - ); - } - - insertDocuments(coll, [doc], options, (err, r) => { - if (callback == null) return; - if (err && callback) return callback(err); - // Workaround for pre 2.6 servers - if (r == null) return callback(null, { result: { ok: 1 } }); - // Add values to top level to ensure crud spec compatibility - r.insertedCount = r.result.n; - r.insertedId = doc._id; - if (callback) callback(null, r); - }); - } -} - -module.exports = InsertOneOperation; diff --git a/node_modules/mongodb/lib/operations/is_capped.js b/node_modules/mongodb/lib/operations/is_capped.js deleted file mode 100644 index 3bfd9ff..0000000 --- a/node_modules/mongodb/lib/operations/is_capped.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const OptionsOperation = require('./options_operation'); -const handleCallback = require('../utils').handleCallback; - -class IsCappedOperation extends OptionsOperation { - constructor(collection, options) { - super(collection, options); - } - - execute(callback) { - super.execute((err, document) => { - if (err) return handleCallback(callback, err); - handleCallback(callback, null, !!(document && document.capped)); - }); - } -} - -module.exports = IsCappedOperation; diff --git a/node_modules/mongodb/lib/operations/list_collections.js b/node_modules/mongodb/lib/operations/list_collections.js deleted file mode 100644 index ee01d31..0000000 --- a/node_modules/mongodb/lib/operations/list_collections.js +++ /dev/null @@ -1,106 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const maxWireVersion = require('../core/utils').maxWireVersion; -const CONSTANTS = require('../constants'); - -const LIST_COLLECTIONS_WIRE_VERSION = 3; - -function listCollectionsTransforms(databaseName) { - const matching = `${databaseName}.`; - - return { - doc: doc => { - const index = doc.name.indexOf(matching); - // Remove database name if available - if (doc.name && index === 0) { - doc.name = doc.name.substr(index + matching.length); - } - - return doc; - } - }; -} - -class ListCollectionsOperation extends CommandOperationV2 { - constructor(db, filter, options) { - super(db, options, { fullResponse: true }); - - this.db = db; - this.filter = filter; - this.nameOnly = !!this.options.nameOnly; - - if (typeof this.options.batchSize === 'number') { - this.batchSize = this.options.batchSize; - } - } - - execute(server, callback) { - if (maxWireVersion(server) < LIST_COLLECTIONS_WIRE_VERSION) { - let filter = this.filter; - const databaseName = this.db.s.namespace.db; - - // If we have legacy mode and have not provided a full db name filter it - if ( - typeof filter.name === 'string' && - !new RegExp('^' + databaseName + '\\.').test(filter.name) - ) { - filter = Object.assign({}, filter); - filter.name = this.db.s.namespace.withCollection(filter.name).toString(); - } - - // No filter, filter by current database - if (filter == null) { - filter.name = `/${databaseName}/`; - } - - // Rewrite the filter to use $and to filter out indexes - if (filter.name) { - filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; - } else { - filter = { name: /^((?!\$).)*$/ }; - } - - const transforms = listCollectionsTransforms(databaseName); - server.query( - `${databaseName}.${CONSTANTS.SYSTEM_NAMESPACE_COLLECTION}`, - { query: filter }, - { batchSize: this.batchSize || 1000 }, - {}, - (err, result) => { - if ( - result && - result.message && - result.message.documents && - Array.isArray(result.message.documents) - ) { - result.message.documents = result.message.documents.map(transforms.doc); - } - - callback(err, result); - } - ); - - return; - } - - const command = { - listCollections: 1, - filter: this.filter, - cursor: this.batchSize ? { batchSize: this.batchSize } : {}, - nameOnly: this.nameOnly - }; - - return super.executeCommand(server, command, callback); - } -} - -defineAspects(ListCollectionsOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListCollectionsOperation; diff --git a/node_modules/mongodb/lib/operations/list_databases.js b/node_modules/mongodb/lib/operations/list_databases.js deleted file mode 100644 index 62b2606..0000000 --- a/node_modules/mongodb/lib/operations/list_databases.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -class ListDatabasesOperation extends CommandOperationV2 { - constructor(db, options) { - super(db, options); - this.ns = new MongoDBNamespace('admin', '$cmd'); - } - - execute(server, callback) { - const cmd = { listDatabases: 1 }; - if (this.options.nameOnly) { - cmd.nameOnly = Number(cmd.nameOnly); - } - - if (this.options.filter) { - cmd.filter = this.options.filter; - } - - if (typeof this.options.authorizedDatabases === 'boolean') { - cmd.authorizedDatabases = this.options.authorizedDatabases; - } - - super.executeCommand(server, cmd, callback); - } -} - -defineAspects(ListDatabasesOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListDatabasesOperation; diff --git a/node_modules/mongodb/lib/operations/list_indexes.js b/node_modules/mongodb/lib/operations/list_indexes.js deleted file mode 100644 index 302a31b..0000000 --- a/node_modules/mongodb/lib/operations/list_indexes.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const maxWireVersion = require('../core/utils').maxWireVersion; - -const LIST_INDEXES_WIRE_VERSION = 3; - -class ListIndexesOperation extends CommandOperationV2 { - constructor(collection, options) { - super(collection, options, { fullResponse: true }); - - this.collectionNamespace = collection.s.namespace; - } - - execute(server, callback) { - const serverWireVersion = maxWireVersion(server); - if (serverWireVersion < LIST_INDEXES_WIRE_VERSION) { - const systemIndexesNS = this.collectionNamespace.withCollection('system.indexes').toString(); - const collectionNS = this.collectionNamespace.toString(); - - server.query(systemIndexesNS, { query: { ns: collectionNS } }, {}, this.options, callback); - return; - } - - const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; - super.executeCommand( - server, - { listIndexes: this.collectionNamespace.collection, cursor }, - callback - ); - } -} - -defineAspects(ListIndexesOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListIndexesOperation; diff --git a/node_modules/mongodb/lib/operations/map_reduce.js b/node_modules/mongodb/lib/operations/map_reduce.js deleted file mode 100644 index 4ea2ac7..0000000 --- a/node_modules/mongodb/lib/operations/map_reduce.js +++ /dev/null @@ -1,190 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const handleCallback = require('../utils').handleCallback; -const isObject = require('../utils').isObject; -const loadDb = require('../dynamic_loaders').loadDb; -const OperationBase = require('./operation').OperationBase; -const resolveReadPreference = require('../utils').resolveReadPreference; -const toError = require('../utils').toError; - -const exclusionList = [ - 'readPreference', - 'session', - 'bypassDocumentValidation', - 'w', - 'wtimeout', - 'j', - 'writeConcern' -]; - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {(function|string)} map The mapping function. - * @property {(function|string)} reduce The reduce function. - * @property {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. - */ -class MapReduceOperation extends OperationBase { - /** - * Constructs a MapReduce operation. - * - * @param {Collection} a Collection instance. - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. - */ - constructor(collection, map, reduce, options) { - super(options); - - this.collection = collection; - this.map = map; - this.reduce = reduce; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(callback) { - const coll = this.collection; - const map = this.map; - const reduce = this.reduce; - let options = this.options; - - const mapCommandHash = { - mapreduce: coll.collectionName, - map: map, - reduce: reduce - }; - - // Add any other options passed in - for (let n in options) { - if ('scope' === n) { - mapCommandHash[n] = processScope(options[n]); - } else { - // Only include if not in exclusion list - if (exclusionList.indexOf(n) === -1) { - mapCommandHash[n] = options[n]; - } - } - } - - options = Object.assign({}, options); - - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(coll, options); - - // If we have a read preference and inline is not set as output fail hard - if ( - options.readPreference !== false && - options.readPreference !== 'primary' && - options['out'] && - options['out'].inline !== 1 && - options['out'] !== 'inline' - ) { - // Force readPreference to primary - options.readPreference = 'primary'; - // Decorate command with writeConcern if supported - applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); - } else { - decorateWithReadConcern(mapCommandHash, coll, options); - } - - // Is bypassDocumentValidation specified - if (options.bypassDocumentValidation === true) { - mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Have we specified collation - try { - decorateWithCollation(mapCommandHash, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute command - executeCommand(coll.s.db, mapCommandHash, options, (err, result) => { - if (err) return handleCallback(callback, err); - // Check if we have an error - if (1 !== result.ok || result.err || result.errmsg) { - return handleCallback(callback, toError(result)); - } - - // Create statistics value - const stats = {}; - if (result.timeMillis) stats['processtime'] = result.timeMillis; - if (result.counts) stats['counts'] = result.counts; - if (result.timing) stats['timing'] = result.timing; - - // invoked with inline? - if (result.results) { - // If we wish for no verbosity - if (options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, null, result.results); - } - - return handleCallback(callback, null, { results: result.results, stats: stats }); - } - - // The returned collection - let collection = null; - - // If we have an object it's a different db - if (result.result != null && typeof result.result === 'object') { - const doc = result.result; - // Return a collection from another db - let Db = loadDb(); - collection = new Db(doc.db, coll.s.db.s.topology, coll.s.db.s.options).collection( - doc.collection - ); - } else { - // Create a collection object that wraps the result collection - collection = coll.s.db.collection(result.result); - } - - // If we wish for no verbosity - if (options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, err, collection); - } - - // Return stats as third set of values - handleCallback(callback, err, { collection: collection, stats: stats }); - }); - } -} - -/** - * Functions that are passed as scope args must - * be converted to Code instances. - * @ignore - */ -function processScope(scope) { - if (!isObject(scope) || scope._bsontype === 'ObjectID') { - return scope; - } - - const keys = Object.keys(scope); - let key; - const new_scope = {}; - - for (let i = keys.length - 1; i >= 0; i--) { - key = keys[i]; - if ('function' === typeof scope[key]) { - new_scope[key] = new Code(String(scope[key])); - } else { - new_scope[key] = processScope(scope[key]); - } - } - - return new_scope; -} - -module.exports = MapReduceOperation; diff --git a/node_modules/mongodb/lib/operations/operation.js b/node_modules/mongodb/lib/operations/operation.js deleted file mode 100644 index fd82e66..0000000 --- a/node_modules/mongodb/lib/operations/operation.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -const Aspect = { - READ_OPERATION: Symbol('READ_OPERATION'), - WRITE_OPERATION: Symbol('WRITE_OPERATION'), - RETRYABLE: Symbol('RETRYABLE'), - EXECUTE_WITH_SELECTION: Symbol('EXECUTE_WITH_SELECTION') -}; - -/** - * This class acts as a parent class for any operation and is responsible for setting this.options, - * as well as setting and getting a session. - * Additionally, this class implements `hasAspect`, which determines whether an operation has - * a specific aspect. - */ -class OperationBase { - constructor(options) { - this.options = Object.assign({}, options); - } - - hasAspect(aspect) { - if (this.constructor.aspects == null) { - return false; - } - return this.constructor.aspects.has(aspect); - } - - set session(session) { - Object.assign(this.options, { session }); - } - - get session() { - return this.options.session; - } - - clearSession() { - delete this.options.session; - } - - get canRetryRead() { - return true; - } - - execute() { - throw new TypeError('`execute` must be implemented for OperationBase subclasses'); - } -} - -function defineAspects(operation, aspects) { - if (!Array.isArray(aspects) && !(aspects instanceof Set)) { - aspects = [aspects]; - } - aspects = new Set(aspects); - Object.defineProperty(operation, 'aspects', { - value: aspects, - writable: false - }); - return aspects; -} - -module.exports = { - Aspect, - defineAspects, - OperationBase -}; diff --git a/node_modules/mongodb/lib/operations/options_operation.js b/node_modules/mongodb/lib/operations/options_operation.js deleted file mode 100644 index 9a739a5..0000000 --- a/node_modules/mongodb/lib/operations/options_operation.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; - -class OptionsOperation extends OperationBase { - constructor(collection, options) { - super(options); - - this.collection = collection; - } - - execute(callback) { - const coll = this.collection; - const opts = this.options; - - coll.s.db.listCollections({ name: coll.collectionName }, opts).toArray((err, collections) => { - if (err) return handleCallback(callback, err); - if (collections.length === 0) { - return handleCallback( - callback, - MongoError.create({ message: `collection ${coll.namespace} not found`, driver: true }) - ); - } - - handleCallback(callback, err, collections[0].options || null); - }); - } -} - -module.exports = OptionsOperation; diff --git a/node_modules/mongodb/lib/operations/profiling_level.js b/node_modules/mongodb/lib/operations/profiling_level.js deleted file mode 100644 index 3f7639b..0000000 --- a/node_modules/mongodb/lib/operations/profiling_level.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); - -class ProfilingLevelOperation extends CommandOperation { - constructor(db, command, options) { - super(db, options); - } - - _buildCommand() { - const command = { profile: -1 }; - - return command; - } - - execute(callback) { - super.execute((err, doc) => { - if (err == null && doc.ok === 1) { - const was = doc.was; - if (was === 0) return callback(null, 'off'); - if (was === 1) return callback(null, 'slow_only'); - if (was === 2) return callback(null, 'all'); - return callback(new Error('Error: illegal profiling level value ' + was), null); - } else { - err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); - } - }); - } -} - -module.exports = ProfilingLevelOperation; diff --git a/node_modules/mongodb/lib/operations/re_index.js b/node_modules/mongodb/lib/operations/re_index.js deleted file mode 100644 index 89437fe..0000000 --- a/node_modules/mongodb/lib/operations/re_index.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); -const handleCallback = require('../utils').handleCallback; - -class ReIndexOperation extends CommandOperation { - constructor(collection, options) { - super(collection.s.db, options, collection); - } - - _buildCommand() { - const collection = this.collection; - - const cmd = { reIndex: collection.collectionName }; - - return cmd; - } - - execute(callback) { - super.execute((err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); - } -} - -module.exports = ReIndexOperation; diff --git a/node_modules/mongodb/lib/operations/remove_user.js b/node_modules/mongodb/lib/operations/remove_user.js deleted file mode 100644 index 9e8376b..0000000 --- a/node_modules/mongodb/lib/operations/remove_user.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; -const WriteConcern = require('../write_concern'); - -class RemoveUserOperation extends CommandOperation { - constructor(db, username, options) { - const commandOptions = {}; - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern != null) { - commandOptions.writeConcern = writeConcern; - } - - if (options.dbName) { - commandOptions.dbName = options.dbName; - } - - // Add maxTimeMS to options if set - if (typeof options.maxTimeMS === 'number') { - commandOptions.maxTimeMS = options.maxTimeMS; - } - - super(db, commandOptions); - - this.username = username; - } - - _buildCommand() { - const username = this.username; - - // Build the command to execute - const command = { dropUser: username }; - - return command; - } - - execute(callback) { - // Attempt to execute command - super.execute((err, result) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, err, result.ok ? true : false); - }); - } -} - -defineAspects(RemoveUserOperation, Aspect.WRITE_OPERATION); - -module.exports = RemoveUserOperation; diff --git a/node_modules/mongodb/lib/operations/rename.js b/node_modules/mongodb/lib/operations/rename.js deleted file mode 100644 index 8098fe6..0000000 --- a/node_modules/mongodb/lib/operations/rename.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const applyWriteConcern = require('../utils').applyWriteConcern; -const checkCollectionName = require('../utils').checkCollectionName; -const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; -const handleCallback = require('../utils').handleCallback; -const loadCollection = require('../dynamic_loaders').loadCollection; -const toError = require('../utils').toError; - -class RenameOperation extends OperationBase { - constructor(collection, newName, options) { - super(options); - - this.collection = collection; - this.newName = newName; - } - - execute(callback) { - const coll = this.collection; - const newName = this.newName; - const options = this.options; - - let Collection = loadCollection(); - // Check the collection name - checkCollectionName(newName); - // Build the command - const renameCollection = coll.namespace; - const toCollection = coll.s.namespace.withCollection(newName).toString(); - const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; - const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; - - // Decorate command with writeConcern if supported - applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); - - // Execute against admin - executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => { - if (err) return handleCallback(callback, err, null); - // We have an error - if (doc.errmsg) return handleCallback(callback, toError(doc), null); - try { - return handleCallback( - callback, - null, - new Collection( - coll.s.db, - coll.s.topology, - coll.s.namespace.db, - newName, - coll.s.pkFactory, - coll.s.options - ) - ); - } catch (err) { - return handleCallback(callback, toError(err), null); - } - }); - } -} - -module.exports = RenameOperation; diff --git a/node_modules/mongodb/lib/operations/replace_one.js b/node_modules/mongodb/lib/operations/replace_one.js deleted file mode 100644 index a5aa760..0000000 --- a/node_modules/mongodb/lib/operations/replace_one.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateDocuments = require('./common_functions').updateDocuments; - -class ReplaceOneOperation extends OperationBase { - constructor(collection, filter, doc, options) { - super(options); - - this.collection = collection; - this.filter = filter; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const doc = this.doc; - const options = this.options; - - // Set single document update - options.multi = false; - - // Execute update - updateDocuments(coll, filter, doc, options, (err, r) => replaceCallback(err, r, doc, callback)); - } -} - -function replaceCallback(err, r, doc, callback) { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - r.ops = [doc]; // TODO: Should we still have this? - if (callback) callback(null, r); -} - -module.exports = ReplaceOneOperation; diff --git a/node_modules/mongodb/lib/operations/set_profiling_level.js b/node_modules/mongodb/lib/operations/set_profiling_level.js deleted file mode 100644 index b31cc13..0000000 --- a/node_modules/mongodb/lib/operations/set_profiling_level.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); -const levelValues = new Set(['off', 'slow_only', 'all']); - -class SetProfilingLevelOperation extends CommandOperation { - constructor(db, level, options) { - let profile = 0; - - if (level === 'off') { - profile = 0; - } else if (level === 'slow_only') { - profile = 1; - } else if (level === 'all') { - profile = 2; - } - - super(db, options); - this.level = level; - this.profile = profile; - } - - _buildCommand() { - const profile = this.profile; - - // Set up the profile number - const command = { profile }; - - return command; - } - - execute(callback) { - const level = this.level; - - if (!levelValues.has(level)) { - return callback(new Error('Error: illegal profiling level value ' + level)); - } - - super.execute((err, doc) => { - if (err == null && doc.ok === 1) return callback(null, level); - return err != null - ? callback(err, null) - : callback(new Error('Error with profile command'), null); - }); - } -} - -module.exports = SetProfilingLevelOperation; diff --git a/node_modules/mongodb/lib/operations/stats.js b/node_modules/mongodb/lib/operations/stats.js deleted file mode 100644 index ff79126..0000000 --- a/node_modules/mongodb/lib/operations/stats.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; - -/** - * Get all the collection statistics. - * - * @class - * @property {Collection} a Collection instance. - * @property {object} [options] Optional settings. See Collection.prototype.stats for a list of options. - */ -class StatsOperation extends CommandOperation { - /** - * Construct a Stats operation. - * - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.stats for a list of options. - */ - constructor(collection, options) { - super(collection.s.db, options, collection); - } - - _buildCommand() { - const collection = this.collection; - const options = this.options; - - // Build command object - const command = { - collStats: collection.collectionName - }; - - // Check if we have the scale value - if (options['scale'] != null) { - command['scale'] = options['scale']; - } - - return command; - } -} - -defineAspects(StatsOperation, Aspect.READ_OPERATION); - -module.exports = StatsOperation; diff --git a/node_modules/mongodb/lib/operations/update_many.js b/node_modules/mongodb/lib/operations/update_many.js deleted file mode 100644 index 9a18d25..0000000 --- a/node_modules/mongodb/lib/operations/update_many.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateCallback = require('./common_functions').updateCallback; -const updateDocuments = require('./common_functions').updateDocuments; - -class UpdateManyOperation extends OperationBase { - constructor(collection, filter, update, options) { - super(options); - - this.collection = collection; - this.filter = filter; - this.update = update; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const update = this.update; - const options = this.options; - - // Set single document update - options.multi = true; - // Execute update - updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); - } -} - -module.exports = UpdateManyOperation; diff --git a/node_modules/mongodb/lib/operations/update_one.js b/node_modules/mongodb/lib/operations/update_one.js deleted file mode 100644 index b1c1bc1..0000000 --- a/node_modules/mongodb/lib/operations/update_one.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateDocuments = require('./common_functions').updateDocuments; - -class UpdateOneOperation extends OperationBase { - constructor(collection, filter, update, options) { - super(options); - - this.collection = collection; - this.filter = filter; - this.update = update; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const update = this.update; - const options = this.options; - - // Set single document update - options.multi = false; - // Execute update - updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); - } -} - -function updateCallback(err, r, callback) { - if (callback == null) return; - if (err) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - callback(null, r); -} - -module.exports = UpdateOneOperation; diff --git a/node_modules/mongodb/lib/operations/validate_collection.js b/node_modules/mongodb/lib/operations/validate_collection.js deleted file mode 100644 index 133c6c4..0000000 --- a/node_modules/mongodb/lib/operations/validate_collection.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); - -class ValidateCollectionOperation extends CommandOperation { - constructor(admin, collectionName, options) { - // Decorate command with extra options - let command = { validate: collectionName }; - const keys = Object.keys(options); - for (let i = 0; i < keys.length; i++) { - if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { - command[keys[i]] = options[keys[i]]; - } - } - - super(admin.s.db, options, null, command); - - this.collectionName; - } - - execute(callback) { - const collectionName = this.collectionName; - - super.execute((err, doc) => { - if (err != null) return callback(err, null); - - if (doc.ok === 0) return callback(new Error('Error with validate command'), null); - if (doc.result != null && doc.result.constructor !== String) - return callback(new Error('Error with validation data'), null); - if (doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error('Error: invalid collection ' + collectionName), null); - if (doc.valid != null && !doc.valid) - return callback(new Error('Error: invalid collection ' + collectionName), null); - - return callback(null, doc); - }); - } -} - -module.exports = ValidateCollectionOperation; diff --git a/node_modules/mongodb/lib/read_concern.js b/node_modules/mongodb/lib/read_concern.js deleted file mode 100644 index b48b8e0..0000000 --- a/node_modules/mongodb/lib/read_concern.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -/** - * The **ReadConcern** class is a class that represents a MongoDB ReadConcern. - * @class - * @property {string} level The read concern level - * @see https://docs.mongodb.com/manual/reference/read-concern/index.html - */ -class ReadConcern { - /** - * Constructs a ReadConcern from the read concern properties. - * @param {string} [level] The read concern level ({'local'|'available'|'majority'|'linearizable'|'snapshot'}) - */ - constructor(level) { - if (level != null) { - this.level = level; - } - } - - /** - * Construct a ReadConcern given an options object. - * - * @param {object} options The options object from which to extract the write concern. - * @return {ReadConcern} - */ - static fromOptions(options) { - if (options == null) { - return; - } - - if (options.readConcern) { - if (options.readConcern instanceof ReadConcern) { - return options.readConcern; - } - - return new ReadConcern(options.readConcern.level); - } - - if (options.level) { - return new ReadConcern(options.level); - } - } - - static get MAJORITY() { - return 'majority'; - } - - static get AVAILABLE() { - return 'available'; - } - - static get LINEARIZABLE() { - return 'linearizable'; - } - - static get SNAPSHOT() { - return 'snapshot'; - } -} - -module.exports = ReadConcern; diff --git a/node_modules/mongodb/lib/topologies/mongos.js b/node_modules/mongodb/lib/topologies/mongos.js deleted file mode 100644 index 10e66d2..0000000 --- a/node_modules/mongodb/lib/topologies/mongos.js +++ /dev/null @@ -1,445 +0,0 @@ -'use strict'; - -const TopologyBase = require('./topology_base').TopologyBase; -const MongoError = require('../core').MongoError; -const CMongos = require('../core').Mongos; -const Cursor = require('../cursor'); -const Server = require('./server'); -const Store = require('./topology_base').Store; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - * - * **Mongos Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'acceptableLatencyMS', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCRL', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'promiseLibrary', - 'monitorCommands' -]; - -/** - * Creates a new Mongos instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options] Optional settings. - * @param {booelan} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=5000] Time between each replicaset status check. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out - * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires Mongos#connect - * @fires Mongos#ha - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#fullsetup - * @fires Mongos#open - * @fires Mongos#close - * @fires Mongos#error - * @fires Mongos#timeout - * @fires Mongos#parseError - * @fires Mongos#commandStarted - * @fires Mongos#commandSucceeded - * @fires Mongos#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {Mongos} a Mongos instance. - */ -class Mongos extends TopologyBase { - constructor(servers, options) { - super(); - - options = options || {}; - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for (var i = 0; i < servers.length; i++) { - if (!(servers[i] instanceof Server)) { - throw MongoError.create({ - message: 'all seed list instances must be of the Server type', - driver: true - }); - } - } - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Build seed list - var seedlist = servers.map(function(x) { - return { host: x.host, port: x.port }; - }); - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Internal state - this.s = { - // Create the Mongos - coreTopology: new CMongos(seedlist, clonedOptions), - // Server capabilities - sCapabilities: null, - // Debug turned on - debug: clonedOptions.debug, - // Store option defaults - storeOptions: storeOptions, - // Cloned options - clonedOptions: clonedOptions, - // Actual store of callbacks - store: store, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise - }; - } - - // Connect - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = {}; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.removeListener(e, connectErrorHandler); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - // Force close the topology - self.close(true); - - // Try to callback - try { - callback(err); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Error handler - var reconnectHandler = function() { - self.emit('reconnect'); - self.s.store.execute(); - }; - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - var events = ['timeout', 'error', 'close', 'fullsetup']; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up listeners - self.s.coreTopology.on('timeout', errorHandler('timeout')); - self.s.coreTopology.on('error', errorHandler('error')); - self.s.coreTopology.on('close', errorHandler('close')); - - // Set up serverConfig listeners - self.s.coreTopology.on('fullsetup', function() { - self.emit('fullsetup', self); - }); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Clear out all the current handlers left over - var events = [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed' - ]; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - - // Set up listeners - self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); - self.s.coreTopology.once('error', connectErrorHandler('error')); - self.s.coreTopology.once('close', connectErrorHandler('close')); - self.s.coreTopology.once('connect', connectHandler); - // Join and leave events - self.s.coreTopology.on('joined', relay('joined')); - self.s.coreTopology.on('left', relay('left')); - - // Reconnect server - self.s.coreTopology.on('reconnect', reconnectHandler); - - // Start connection - self.s.coreTopology.connect(_options); - } -} - -Object.defineProperty(Mongos.prototype, 'haInterval', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.haInterval; - } -}); - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * The mongos high availability event - * - * @event Mongos#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the mongos set - * - * @event Mongos#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos set - * - * @event Mongos#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * Mongos open event, emitted when mongos can start processing commands. - * - * @event Mongos#open - * @type {Mongos} - */ - -/** - * Mongos close event - * - * @event Mongos#close - * @type {object} - */ - -/** - * Mongos error event, emitted if there is an error listener. - * - * @event Mongos#error - * @type {MongoError} - */ - -/** - * Mongos timeout event - * - * @event Mongos#timeout - * @type {object} - */ - -/** - * Mongos parseError event - * - * @event Mongos#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Mongos#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Mongos#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Mongos#commandFailed - * @type {object} - */ - -module.exports = Mongos; diff --git a/node_modules/mongodb/lib/topologies/native_topology.js b/node_modules/mongodb/lib/topologies/native_topology.js deleted file mode 100644 index 778ddc9..0000000 --- a/node_modules/mongodb/lib/topologies/native_topology.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict'; - -const Topology = require('../core').Topology; -const ServerCapabilities = require('./topology_base').ServerCapabilities; -const Cursor = require('../cursor'); -const translateOptions = require('../utils').translateOptions; - -class NativeTopology extends Topology { - constructor(servers, options) { - options = options || {}; - - let clonedOptions = Object.assign( - {}, - { - cursorFactory: Cursor, - reconnect: false, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - maxPoolSize: typeof options.poolSize === 'number' ? options.poolSize : 5, - minPoolSize: typeof options.minSize === 'number' ? options.minSize : 0, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - super(servers, clonedOptions); - } - - capabilities() { - if (this.s.sCapabilities) return this.s.sCapabilities; - if (this.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.lastIsMaster()); - return this.s.sCapabilities; - } - - // Command - command(ns, cmd, options, callback) { - super.command(ns.toString(), cmd, options, callback); - } - - // Insert - insert(ns, ops, options, callback) { - super.insert(ns.toString(), ops, options, callback); - } - - // Update - update(ns, ops, options, callback) { - super.update(ns.toString(), ops, options, callback); - } - - // Remove - remove(ns, ops, options, callback) { - super.remove(ns.toString(), ops, options, callback); - } -} - -module.exports = NativeTopology; diff --git a/node_modules/mongodb/lib/topologies/replset.js b/node_modules/mongodb/lib/topologies/replset.js deleted file mode 100644 index 69df26d..0000000 --- a/node_modules/mongodb/lib/topologies/replset.js +++ /dev/null @@ -1,489 +0,0 @@ -'use strict'; - -const Server = require('./server'); -const Cursor = require('../cursor'); -const MongoError = require('../core').MongoError; -const TopologyBase = require('./topology_base').TopologyBase; -const Store = require('./topology_base').Store; -const CReplSet = require('../core').ReplSet; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is - * used to construct connections. - * - * **ReplSet Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'replicaSet', - 'rs_name', - 'secondaryAcceptableLatencyMS', - 'connectWithNoPrimary', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslCRL', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'strategy', - 'debug', - 'family', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'maxStalenessSeconds', - 'promiseLibrary', - 'minSize', - 'monitorCommands' -]; - -/** - * Creates a new ReplSet instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options] Optional settings. - * @param {boolean} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=10000] Time between each replicaset status check. - * @param {string} [options.replicaSet] The name of the replicaset to connect to. - * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher. - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out - * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#fullsetup - * @fires ReplSet#open - * @fires ReplSet#close - * @fires ReplSet#error - * @fires ReplSet#timeout - * @fires ReplSet#parseError - * @fires ReplSet#commandStarted - * @fires ReplSet#commandSucceeded - * @fires ReplSet#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {ReplSet} a ReplSet instance. - */ -class ReplSet extends TopologyBase { - constructor(servers, options) { - super(); - - options = options || {}; - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for (var i = 0; i < servers.length; i++) { - if (!(servers[i] instanceof Server)) { - throw MongoError.create({ - message: 'all seed list instances must be of the Server type', - driver: true - }); - } - } - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Build seed list - var seedlist = servers.map(function(x) { - return { host: x.host, port: x.port }; - }); - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: false, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Create the ReplSet - var coreTopology = new CReplSet(seedlist, clonedOptions); - - // Listen to reconnect event - coreTopology.on('reconnect', function() { - self.emit('reconnect'); - store.execute(); - }); - - // Internal state - this.s = { - // Replicaset - coreTopology: coreTopology, - // Server capabilities - sCapabilities: null, - // Debug tag - tag: options.tag, - // Store options - storeOptions: storeOptions, - // Cloned options - clonedOptions: clonedOptions, - // Store - store: store, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise - }; - - // Debug - if (clonedOptions.debug) { - // Last ismaster - Object.defineProperty(this, 'replset', { - enumerable: true, - get: function() { - return coreTopology; - } - }); - } - } - - // Connect method - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = {}; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Clear out all the current handlers left over - var events = [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha' - ]; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Replset events relay - var replsetRelay = function(event) { - return function(t, server) { - self.emit(event, t, server.lastIsMaster(), server); - }; - }; - - // Relay ha - var relayHa = function(t, state) { - self.emit('ha', t, state); - - if (t === 'start') { - self.emit('ha_connect', t, state); - } else if (t === 'end') { - self.emit('ha_ismaster', t, state); - } - }; - - // Set up serverConfig listeners - self.s.coreTopology.on('joined', replsetRelay('joined')); - self.s.coreTopology.on('left', relay('left')); - self.s.coreTopology.on('ping', relay('ping')); - self.s.coreTopology.on('ha', relayHa); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - - self.s.coreTopology.on('fullsetup', function() { - self.emit('fullsetup', self, self); - }); - - self.s.coreTopology.on('all', function() { - self.emit('all', null, self); - }); - - // Connect handler - var connectHandler = function() { - // Set up listeners - self.s.coreTopology.once('timeout', errorHandler('timeout')); - self.s.coreTopology.once('error', errorHandler('error')); - self.s.coreTopology.once('close', errorHandler('close')); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - ['timeout', 'error', 'close'].forEach(function(e) { - self.s.coreTopology.removeListener(e, connectErrorHandler); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - // Destroy the replset - self.s.coreTopology.destroy(); - - // Try to callback - try { - callback(err); - } catch (err) { - if (!self.s.coreTopology.isConnected()) - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Set up listeners - self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); - self.s.coreTopology.once('error', connectErrorHandler('error')); - self.s.coreTopology.once('close', connectErrorHandler('close')); - self.s.coreTopology.once('connect', connectHandler); - - // Start connection - self.s.coreTopology.connect(_options); - } - - close(forceClosed, callback) { - ['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e)); - super.close(forceClosed, callback); - } -} - -Object.defineProperty(ReplSet.prototype, 'haInterval', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.haInterval; - } -}); - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * The replset high availability event - * - * @event ReplSet#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * ReplSet open event, emitted when replicaset can start processing commands. - * - * @event ReplSet#open - * @type {Replset} - */ - -/** - * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. - * - * @event ReplSet#fullsetup - * @type {Replset} - */ - -/** - * ReplSet close event - * - * @event ReplSet#close - * @type {object} - */ - -/** - * ReplSet error event, emitted if there is an error listener. - * - * @event ReplSet#error - * @type {MongoError} - */ - -/** - * ReplSet timeout event - * - * @event ReplSet#timeout - * @type {object} - */ - -/** - * ReplSet parseError event - * - * @event ReplSet#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event ReplSet#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event ReplSet#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event ReplSet#commandFailed - * @type {object} - */ - -module.exports = ReplSet; diff --git a/node_modules/mongodb/lib/topologies/server.js b/node_modules/mongodb/lib/topologies/server.js deleted file mode 100644 index 3079cb9..0000000 --- a/node_modules/mongodb/lib/topologies/server.js +++ /dev/null @@ -1,448 +0,0 @@ -'use strict'; - -const CServer = require('../core').Server; -const Cursor = require('../cursor'); -const TopologyBase = require('./topology_base').TopologyBase; -const Store = require('./topology_base').Store; -const MongoError = require('../core').MongoError; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **Server** class is a class that represents a single server topology and is - * used to construct connections. - * - * **Server Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'acceptableLatencyMS', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCRL', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'family', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'reconnectInterval', - 'monitoring', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'compression', - 'promiseLibrary', - 'monitorCommands' -]; - -/** - * Creates a new Server instance - * @class - * @deprecated - * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. - * @param {number} [port] The server port if IP4. - * @param {object} [options] Optional settings. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error. - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out - * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.monitoring=true] Triggers the server instance to call ismaster - * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @fires Server#commandStarted - * @fires Server#commandSucceeded - * @fires Server#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {Server} a Server instance. - */ -class Server extends TopologyBase { - constructor(host, port, options) { - super(); - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Promise library - const promiseLibrary = options.promiseLibrary; - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Detect if we have a socket connection - if (host.indexOf('/') !== -1) { - if (port != null && typeof port === 'object') { - options = port; - port = null; - } - } else if (port == null) { - throw MongoError.create({ message: 'port must be specified', driver: true }); - } - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - host: host, - port: port, - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Define the internal properties - this.s = { - // Create an instance of a server instance from core module - coreTopology: new CServer(clonedOptions), - // Server capabilities - sCapabilities: null, - // Cloned options - clonedOptions: clonedOptions, - // Reconnect - reconnect: clonedOptions.reconnect, - // Emit error - emitError: clonedOptions.emitError, - // Pool size - poolSize: clonedOptions.size, - // Store Options - storeOptions: storeOptions, - // Store - store: store, - // Host - host: host, - // Port - port: port, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: promiseLibrary || Promise - }; - } - - // Connect - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = this.s.clonedOptions; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.s.coreTopology.removeListener(e, connectHandlers[e]); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - - // Try to callback - try { - callback(err); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Error handler - var reconnectHandler = function() { - self.emit('reconnect', self); - self.s.store.execute(); - }; - - // Reconnect failed - var reconnectFailedHandler = function(err) { - self.emit('reconnectFailed', err); - self.s.store.flush(err); - }; - - // Destroy called on topology, perform cleanup - var destroyHandler = function() { - self.s.store.flush(); - }; - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - ['timeout', 'error', 'close', 'destroy'].forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up listeners - self.s.coreTopology.on('timeout', errorHandler('timeout')); - self.s.coreTopology.once('error', errorHandler('error')); - self.s.coreTopology.on('close', errorHandler('close')); - // Only called on destroy - self.s.coreTopology.on('destroy', destroyHandler); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Set up listeners - var connectHandlers = { - timeout: connectErrorHandler('timeout'), - error: connectErrorHandler('error'), - close: connectErrorHandler('close') - }; - - // Clear out all the current handlers left over - [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed' - ].forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Add the event handlers - self.s.coreTopology.once('timeout', connectHandlers.timeout); - self.s.coreTopology.once('error', connectHandlers.error); - self.s.coreTopology.once('close', connectHandlers.close); - self.s.coreTopology.once('connect', connectHandler); - // Reconnect server - self.s.coreTopology.on('reconnect', reconnectHandler); - self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect')); - self.s.coreTopology.on('monitoring', relay('monitoring')); - - // Start connection - self.s.coreTopology.connect(_options); - } -} - -Object.defineProperty(Server.prototype, 'poolSize', { - enumerable: true, - get: function() { - return this.s.coreTopology.connections().length; - } -}); - -Object.defineProperty(Server.prototype, 'autoReconnect', { - enumerable: true, - get: function() { - return this.s.reconnect; - } -}); - -Object.defineProperty(Server.prototype, 'host', { - enumerable: true, - get: function() { - return this.s.host; - } -}); - -Object.defineProperty(Server.prototype, 'port', { - enumerable: true, - get: function() { - return this.s.port; - } -}); - -/** - * Server connect event - * - * @event Server#connect - * @type {object} - */ - -/** - * Server close event - * - * @event Server#close - * @type {object} - */ - -/** - * Server reconnect event - * - * @event Server#reconnect - * @type {object} - */ - -/** - * Server error event - * - * @event Server#error - * @type {MongoError} - */ - -/** - * Server timeout event - * - * @event Server#timeout - * @type {object} - */ - -/** - * Server parseError event - * - * @event Server#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Server#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Server#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Server#commandFailed - * @type {object} - */ - -module.exports = Server; diff --git a/node_modules/mongodb/lib/topologies/topology_base.js b/node_modules/mongodb/lib/topologies/topology_base.js deleted file mode 100644 index 967b4cd..0000000 --- a/node_modules/mongodb/lib/topologies/topology_base.js +++ /dev/null @@ -1,417 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'), - MongoError = require('../core').MongoError, - f = require('util').format, - translateReadPreference = require('../utils').translateReadPreference, - ClientSession = require('../core').Sessions.ClientSession; - -// The store of ops -var Store = function(topology, storeOptions) { - var self = this; - var storedOps = []; - storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; - - // Internal state - this.s = { - storedOps: storedOps, - storeOptions: storeOptions, - topology: topology - }; - - Object.defineProperty(this, 'length', { - enumerable: true, - get: function() { - return self.s.storedOps.length; - } - }); -}; - -Store.prototype.add = function(opType, ns, ops, options, callback) { - if (this.s.storeOptions.force) { - return callback(MongoError.create({ message: 'db closed by application', driver: true })); - } - - if (this.s.storeOptions.bufferMaxEntries === 0) { - return callback( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - if ( - this.s.storeOptions.bufferMaxEntries > 0 && - this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries - ) { - while (this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - return; - } - - this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback }); -}; - -Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { - if (this.s.storeOptions.force) { - return callback(MongoError.create({ message: 'db closed by application', driver: true })); - } - - if (this.s.storeOptions.bufferMaxEntries === 0) { - return callback( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - if ( - this.s.storeOptions.bufferMaxEntries > 0 && - this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries - ) { - while (this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - return; - } - - this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback }); -}; - -Store.prototype.flush = function(err) { - while (this.s.storedOps.length > 0) { - this.s.storedOps - .shift() - .c( - err || - MongoError.create({ message: f('no connection available for operation'), driver: true }) - ); - } -}; - -var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; -var secondaryOptions = ['secondary', 'secondaryPreferred']; - -Store.prototype.execute = function(options) { - options = options || {}; - // Get current ops - var ops = this.s.storedOps; - // Reset the ops - this.s.storedOps = []; - - // Unpack options - var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true; - var executeSecondary = - typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true; - - // Execute all the stored ops - while (ops.length > 0) { - var op = ops.shift(); - - if (op.t === 'cursor') { - if (executePrimary && executeSecondary) { - op.o[op.m].apply(op.o, op.p); - } else if ( - executePrimary && - op.o.options && - op.o.options.readPreference && - primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 - ) { - op.o[op.m].apply(op.o, op.p); - } else if ( - !executePrimary && - executeSecondary && - op.o.options && - op.o.options.readPreference && - secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 - ) { - op.o[op.m].apply(op.o, op.p); - } - } else if (op.t === 'auth') { - this.s.topology[op.t].apply(this.s.topology, op.o); - } else { - if (executePrimary && executeSecondary) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if ( - executePrimary && - op.op && - op.op.readPreference && - primaryOptions.indexOf(op.op.readPreference.mode) !== -1 - ) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if ( - !executePrimary && - executeSecondary && - op.op && - op.op.readPreference && - secondaryOptions.indexOf(op.op.readPreference.mode) !== -1 - ) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } - } - } -}; - -Store.prototype.all = function() { - return this.s.storedOps; -}; - -// Server capabilities -var ServerCapabilities = function(ismaster) { - var setup_get_property = function(object, name, value) { - Object.defineProperty(object, name, { - enumerable: true, - get: function() { - return value; - } - }); - }; - - // Capabilities - var aggregationCursor = false; - var writeCommands = false; - var textSearch = false; - var authCommands = false; - var listCollections = false; - var listIndexes = false; - var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; - var commandsTakeWriteConcern = false; - var commandsTakeCollation = false; - - if (ismaster.minWireVersion >= 0) { - textSearch = true; - } - - if (ismaster.maxWireVersion >= 1) { - aggregationCursor = true; - authCommands = true; - } - - if (ismaster.maxWireVersion >= 2) { - writeCommands = true; - } - - if (ismaster.maxWireVersion >= 3) { - listCollections = true; - listIndexes = true; - } - - if (ismaster.maxWireVersion >= 5) { - commandsTakeWriteConcern = true; - commandsTakeCollation = true; - } - - // If no min or max wire version set to 0 - if (ismaster.minWireVersion == null) { - ismaster.minWireVersion = 0; - } - - if (ismaster.maxWireVersion == null) { - ismaster.maxWireVersion = 0; - } - - // Map up read only parameters - setup_get_property(this, 'hasAggregationCursor', aggregationCursor); - setup_get_property(this, 'hasWriteCommands', writeCommands); - setup_get_property(this, 'hasTextSearch', textSearch); - setup_get_property(this, 'hasAuthCommands', authCommands); - setup_get_property(this, 'hasListCollectionsCommand', listCollections); - setup_get_property(this, 'hasListIndexesCommand', listIndexes); - setup_get_property(this, 'minWireVersion', ismaster.minWireVersion); - setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion); - setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch); - setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern); - setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation); -}; - -class TopologyBase extends EventEmitter { - constructor() { - super(); - this.setMaxListeners(Infinity); - } - - // Sessions related methods - hasSessionSupport() { - return this.logicalSessionTimeoutMinutes != null; - } - - startSession(options, clientOptions) { - const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); - - session.once('ended', () => { - this.s.sessions.delete(session); - }); - - this.s.sessions.add(session); - return session; - } - - endSessions(sessions, callback) { - return this.s.coreTopology.endSessions(sessions, callback); - } - - get clientMetadata() { - return this.s.coreTopology.s.options.metadata; - } - - // Server capabilities - capabilities() { - if (this.s.sCapabilities) return this.s.sCapabilities; - if (this.s.coreTopology.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster()); - return this.s.sCapabilities; - } - - // Command - command(ns, cmd, options, callback) { - this.s.coreTopology.command(ns.toString(), cmd, translateReadPreference(options), callback); - } - - // Insert - insert(ns, ops, options, callback) { - this.s.coreTopology.insert(ns.toString(), ops, options, callback); - } - - // Update - update(ns, ops, options, callback) { - this.s.coreTopology.update(ns.toString(), ops, options, callback); - } - - // Remove - remove(ns, ops, options, callback) { - this.s.coreTopology.remove(ns.toString(), ops, options, callback); - } - - // IsConnected - isConnected(options) { - options = options || {}; - options = translateReadPreference(options); - - return this.s.coreTopology.isConnected(options); - } - - // IsDestroyed - isDestroyed() { - return this.s.coreTopology.isDestroyed(); - } - - // Cursor - cursor(ns, cmd, options) { - options = options || {}; - options = translateReadPreference(options); - options.disconnectHandler = this.s.store; - options.topology = this; - - return this.s.coreTopology.cursor(ns, cmd, options); - } - - lastIsMaster() { - return this.s.coreTopology.lastIsMaster(); - } - - selectServer(selector, options, callback) { - return this.s.coreTopology.selectServer(selector, options, callback); - } - - /** - * Unref all sockets - * @method - */ - unref() { - return this.s.coreTopology.unref(); - } - - /** - * All raw connections - * @method - * @return {array} - */ - connections() { - return this.s.coreTopology.connections(); - } - - close(forceClosed, callback) { - // If we have sessions, we want to individually move them to the session pool, - // and then send a single endSessions call. - this.s.sessions.forEach(session => session.endSession()); - - if (this.s.sessionPool) { - this.s.sessionPool.endAllPooledSessions(); - } - - // We need to wash out all stored processes - if (forceClosed === true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } - - this.s.coreTopology.destroy( - { - force: typeof forceClosed === 'boolean' ? forceClosed : false - }, - callback - ); - } -} - -// Properties -Object.defineProperty(TopologyBase.prototype, 'bson', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.bson; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'parserType', { - enumerable: true, - get: function() { - return this.s.coreTopology.parserType; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - return this.s.coreTopology.logicalSessionTimeoutMinutes; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'type', { - enumerable: true, - get: function() { - return this.s.coreTopology.type; - } -}); - -exports.Store = Store; -exports.ServerCapabilities = ServerCapabilities; -exports.TopologyBase = TopologyBase; diff --git a/node_modules/mongodb/lib/url_parser.js b/node_modules/mongodb/lib/url_parser.js deleted file mode 100644 index c0f10b4..0000000 --- a/node_modules/mongodb/lib/url_parser.js +++ /dev/null @@ -1,623 +0,0 @@ -'use strict'; - -const ReadPreference = require('./core').ReadPreference, - parser = require('url'), - f = require('util').format, - Logger = require('./core').Logger, - dns = require('dns'); -const ReadConcern = require('./read_concern'); - -module.exports = function(url, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - let result; - try { - result = parser.parse(url, true); - } catch (e) { - return callback(new Error('URL malformed, cannot be parsed')); - } - - if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') { - return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`')); - } - - if (result.protocol === 'mongodb:') { - return parseHandler(url, options, callback); - } - - // Otherwise parse this as an SRV record - if (result.hostname.split('.').length < 3) { - return callback(new Error('URI does not have hostname, domain name and tld')); - } - - result.domainLength = result.hostname.split('.').length; - - if (result.pathname && result.pathname.match(',')) { - return callback(new Error('Invalid URI, cannot contain multiple hostnames')); - } - - if (result.port) { - return callback(new Error('Ports not accepted with `mongodb+srv` URIs')); - } - - let srvAddress = `_mongodb._tcp.${result.host}`; - dns.resolveSrv(srvAddress, function(err, addresses) { - if (err) return callback(err); - - if (addresses.length === 0) { - return callback(new Error('No addresses found at host')); - } - - for (let i = 0; i < addresses.length; i++) { - if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { - return callback(new Error('Server record does not share hostname with parent URI')); - } - } - - let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; - let connectionStrings = addresses.map(function(address, i) { - if (i === 0) return `${base}${address.name}:${address.port}`; - else return `${address.name}:${address.port}`; - }); - - let connectionString = connectionStrings.join(',') + '/'; - let connectionStringOptions = []; - - // Add the default database if needed - if (result.path) { - let defaultDb = result.path.slice(1); - if (defaultDb.indexOf('?') !== -1) { - defaultDb = defaultDb.slice(0, defaultDb.indexOf('?')); - } - - connectionString += defaultDb; - } - - // Default to SSL true - if (!options.ssl && !result.search) { - connectionStringOptions.push('ssl=true'); - } else if (!options.ssl && result.search && !result.search.match('ssl')) { - connectionStringOptions.push('ssl=true'); - } - - // Keep original uri options - if (result.search) { - connectionStringOptions.push(result.search.replace('?', '')); - } - - dns.resolveTxt(result.host, function(err, record) { - if (err && err.code !== 'ENODATA') return callback(err); - if (err && err.code === 'ENODATA') record = null; - - if (record) { - if (record.length > 1) { - return callback(new Error('Multiple text records not allowed')); - } - - record = record[0]; - if (record.length > 1) record = record.join(''); - else record = record[0]; - - if (!record.includes('authSource') && !record.includes('replicaSet')) { - return callback(new Error('Text record must only set `authSource` or `replicaSet`')); - } - - connectionStringOptions.push(record); - } - - // Add any options to the connection string - if (connectionStringOptions.length) { - connectionString += `?${connectionStringOptions.join('&')}`; - } - - parseHandler(connectionString, options, callback); - }); - }); -}; - -function matchesParentDomain(srvAddress, parentDomain) { - let regex = /^.*?\./; - let srv = `.${srvAddress.replace(regex, '')}`; - let parent = `.${parentDomain.replace(regex, '')}`; - if (srv.endsWith(parent)) return true; - else return false; -} - -function parseHandler(address, options, callback) { - let result, err; - try { - result = parseConnectionString(address, options); - } catch (e) { - err = e; - } - - return err ? callback(err, null) : callback(null, result); -} - -function parseConnectionString(url, options) { - // Variables - let connection_part = ''; - let auth_part = ''; - let query_string_part = ''; - let dbName = 'admin'; - - // Url parser result - let result = parser.parse(url, true); - if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) { - throw new Error('No hostname or hostnames provided in connection string'); - } - - if (result.port === '0') { - throw new Error('Invalid port (zero) with hostname'); - } - - if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { - throw new Error('Invalid port (larger than 65535) with hostname'); - } - - if ( - result.path && - result.path.length > 0 && - result.path[0] !== '/' && - url.indexOf('.sock') === -1 - ) { - throw new Error('Missing delimiting slash between hosts and options'); - } - - if (result.query) { - for (let name in result.query) { - if (name.indexOf('::') !== -1) { - throw new Error('Double colon in host identifier'); - } - - if (result.query[name] === '') { - throw new Error('Query parameter ' + name + ' is an incomplete value pair'); - } - } - } - - if (result.auth) { - let parts = result.auth.split(':'); - if (url.indexOf(result.auth) !== -1 && parts.length > 2) { - throw new Error('Username with password containing an unescaped colon'); - } - - if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) { - throw new Error('Username containing an unescaped at-sign'); - } - } - - // Remove query - let clean = url.split('?').shift(); - - // Extract the list of hosts - let strings = clean.split(','); - let hosts = []; - - for (let i = 0; i < strings.length; i++) { - let hostString = strings[i]; - - if (hostString.indexOf('mongodb') !== -1) { - if (hostString.indexOf('@') !== -1) { - hosts.push(hostString.split('@').pop()); - } else { - hosts.push(hostString.substr('mongodb://'.length)); - } - } else if (hostString.indexOf('/') !== -1) { - hosts.push(hostString.split('/').shift()); - } else if (hostString.indexOf('/') === -1) { - hosts.push(hostString.trim()); - } - } - - for (let i = 0; i < hosts.length; i++) { - let r = parser.parse(f('mongodb://%s', hosts[i].trim())); - if (r.path && r.path.indexOf('.sock') !== -1) continue; - if (r.path && r.path.indexOf(':') !== -1) { - // Not connecting to a socket so check for an extra slash in the hostname. - // Using String#split as perf is better than match. - if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) { - throw new Error('Slash in host identifier'); - } else { - throw new Error('Double colon in host identifier'); - } - } - } - - // If we have a ? mark cut the query elements off - if (url.indexOf('?') !== -1) { - query_string_part = url.substr(url.indexOf('?') + 1); - connection_part = url.substring('mongodb://'.length, url.indexOf('?')); - } else { - connection_part = url.substring('mongodb://'.length); - } - - // Check if we have auth params - if (connection_part.indexOf('@') !== -1) { - auth_part = connection_part.split('@')[0]; - connection_part = connection_part.split('@')[1]; - } - - // Check there is not more than one unescaped slash - if (connection_part.split('/').length > 2) { - throw new Error( - "Unsupported host '" + - connection_part.split('?')[0] + - "', hosts must be URL encoded and contain at most one unencoded slash" - ); - } - - // Check if the connection string has a db - if (connection_part.indexOf('.sock') !== -1) { - if (connection_part.indexOf('.sock/') !== -1) { - dbName = connection_part.split('.sock/')[1]; - // Check if multiple database names provided, or just an illegal trailing backslash - if (dbName.indexOf('/') !== -1) { - if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - connection_part = connection_part.split( - '/', - connection_part.indexOf('.sock') + '.sock'.length - ); - } - } else if (connection_part.indexOf('/') !== -1) { - // Check if multiple database names provided, or just an illegal trailing backslash - if (connection_part.split('/').length > 2) { - if (connection_part.split('/')[2].length === 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - dbName = connection_part.split('/')[1]; - connection_part = connection_part.split('/')[0]; - } - - // URI decode the host information - connection_part = decodeURIComponent(connection_part); - - // Result object - let object = {}; - - // Pick apart the authentication part of the string - let authPart = auth_part || ''; - let auth = authPart.split(':', 2); - - // Decode the authentication URI components and verify integrity - let user = decodeURIComponent(auth[0]); - if (auth[0] !== encodeURIComponent(user)) { - throw new Error('Username contains an illegal unescaped character'); - } - auth[0] = user; - - if (auth[1]) { - let pass = decodeURIComponent(auth[1]); - if (auth[1] !== encodeURIComponent(pass)) { - throw new Error('Password contains an illegal unescaped character'); - } - auth[1] = pass; - } - - // Add auth to final object if we have 2 elements - if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] }; - // if user provided auth options, use that - if (options && options.auth != null) object.auth = options.auth; - - // Variables used for temporary storage - let hostPart; - let urlOptions; - let servers; - let compression; - let serverOptions = { socketOptions: {} }; - let dbOptions = { read_preference_tags: [] }; - let replSetServersOptions = { socketOptions: {} }; - let mongosOptions = { socketOptions: {} }; - // Add server options to final object - object.server_options = serverOptions; - object.db_options = dbOptions; - object.rs_options = replSetServersOptions; - object.mongos_options = mongosOptions; - - // Let's check if we are using a domain socket - if (url.match(/\.sock/)) { - // Split out the socket part - let domainSocket = url.substring( - url.indexOf('mongodb://') + 'mongodb://'.length, - url.lastIndexOf('.sock') + '.sock'.length - ); - // Clean out any auth stuff if any - if (domainSocket.indexOf('@') !== -1) domainSocket = domainSocket.split('@')[1]; - domainSocket = decodeURIComponent(domainSocket); - servers = [{ domain_socket: domainSocket }]; - } else { - // Split up the db - hostPart = connection_part; - // Deduplicate servers - let deduplicatedServers = {}; - - // Parse all server results - servers = hostPart - .split(',') - .map(function(h) { - let _host, _port, ipv6match; - //check if it matches [IPv6]:port, where the port number is optional - if ((ipv6match = /\[([^\]]+)\](?::(.+))?/.exec(h))) { - _host = ipv6match[1]; - _port = parseInt(ipv6match[2], 10) || 27017; - } else { - //otherwise assume it's IPv4, or plain hostname - let hostPort = h.split(':', 2); - _host = hostPort[0] || 'localhost'; - _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; - // Check for localhost?safe=true style case - if (_host.indexOf('?') !== -1) _host = _host.split(/\?/)[0]; - } - - // No entry returned for duplicate server - if (deduplicatedServers[_host + '_' + _port]) return null; - deduplicatedServers[_host + '_' + _port] = 1; - - // Return the mapped object - return { host: _host, port: _port }; - }) - .filter(function(x) { - return x != null; - }); - } - - // Get the db name - object.dbName = dbName || 'admin'; - // Split up all the options - urlOptions = (query_string_part || '').split(/[&;]/); - // Ugh, we have to figure out which options go to which constructor manually. - urlOptions.forEach(function(opt) { - if (!opt) return; - var splitOpt = opt.split('='), - name = splitOpt[0], - value = splitOpt[1]; - - // Options implementations - switch (name) { - case 'slaveOk': - case 'slave_ok': - serverOptions.slave_ok = value === 'true'; - dbOptions.slaveOk = value === 'true'; - break; - case 'maxPoolSize': - case 'poolSize': - serverOptions.poolSize = parseInt(value, 10); - replSetServersOptions.poolSize = parseInt(value, 10); - break; - case 'appname': - object.appname = decodeURIComponent(value); - break; - case 'autoReconnect': - case 'auto_reconnect': - serverOptions.auto_reconnect = value === 'true'; - break; - case 'ssl': - if (value === 'prefer') { - serverOptions.ssl = value; - replSetServersOptions.ssl = value; - mongosOptions.ssl = value; - break; - } - serverOptions.ssl = value === 'true'; - replSetServersOptions.ssl = value === 'true'; - mongosOptions.ssl = value === 'true'; - break; - case 'sslValidate': - serverOptions.sslValidate = value === 'true'; - replSetServersOptions.sslValidate = value === 'true'; - mongosOptions.sslValidate = value === 'true'; - break; - case 'replicaSet': - case 'rs_name': - replSetServersOptions.rs_name = value; - break; - case 'reconnectWait': - replSetServersOptions.reconnectWait = parseInt(value, 10); - break; - case 'retries': - replSetServersOptions.retries = parseInt(value, 10); - break; - case 'readSecondary': - case 'read_secondary': - replSetServersOptions.read_secondary = value === 'true'; - break; - case 'fsync': - dbOptions.fsync = value === 'true'; - break; - case 'journal': - dbOptions.j = value === 'true'; - break; - case 'safe': - dbOptions.safe = value === 'true'; - break; - case 'nativeParser': - case 'native_parser': - dbOptions.native_parser = value === 'true'; - break; - case 'readConcernLevel': - dbOptions.readConcern = new ReadConcern(value); - break; - case 'connectTimeoutMS': - serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - break; - case 'socketTimeoutMS': - serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - break; - case 'w': - dbOptions.w = parseInt(value, 10); - if (isNaN(dbOptions.w)) dbOptions.w = value; - break; - case 'authSource': - dbOptions.authSource = value; - break; - case 'gssapiServiceName': - dbOptions.gssapiServiceName = value; - break; - case 'authMechanism': - if (value === 'GSSAPI') { - // If no password provided decode only the principal - if (object.auth == null) { - let urlDecodeAuthPart = decodeURIComponent(authPart); - if (urlDecodeAuthPart.indexOf('@') === -1) - throw new Error('GSSAPI requires a provided principal'); - object.auth = { user: urlDecodeAuthPart, password: null }; - } else { - object.auth.user = decodeURIComponent(object.auth.user); - } - } else if (value === 'MONGODB-X509') { - object.auth = { user: decodeURIComponent(authPart) }; - } - - // Only support GSSAPI or MONGODB-CR for now - if ( - value !== 'GSSAPI' && - value !== 'MONGODB-X509' && - value !== 'MONGODB-CR' && - value !== 'DEFAULT' && - value !== 'SCRAM-SHA-1' && - value !== 'SCRAM-SHA-256' && - value !== 'PLAIN' - ) - throw new Error( - 'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism' - ); - - // Authentication mechanism - dbOptions.authMechanism = value; - break; - case 'authMechanismProperties': - { - // Split up into key, value pairs - let values = value.split(','); - let o = {}; - // For each value split into key, value - values.forEach(function(x) { - let v = x.split(':'); - o[v[0]] = v[1]; - }); - - // Set all authMechanismProperties - dbOptions.authMechanismProperties = o; - // Set the service name value - if (typeof o.SERVICE_NAME === 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; - if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; - if (typeof o.CANONICALIZE_HOST_NAME === 'string') - dbOptions.gssapiCanonicalizeHostName = - o.CANONICALIZE_HOST_NAME === 'true' ? true : false; - } - break; - case 'wtimeoutMS': - dbOptions.wtimeout = parseInt(value, 10); - break; - case 'readPreference': - if (!ReadPreference.isValid(value)) - throw new Error( - 'readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest' - ); - dbOptions.readPreference = value; - break; - case 'maxStalenessSeconds': - dbOptions.maxStalenessSeconds = parseInt(value, 10); - break; - case 'readPreferenceTags': - { - // Decode the value - value = decodeURIComponent(value); - // Contains the tag object - let tagObject = {}; - if (value == null || value === '') { - dbOptions.read_preference_tags.push(tagObject); - break; - } - - // Split up the tags - let tags = value.split(/,/); - for (let i = 0; i < tags.length; i++) { - let parts = tags[i].trim().split(/:/); - tagObject[parts[0]] = parts[1]; - } - - // Set the preferences tags - dbOptions.read_preference_tags.push(tagObject); - } - break; - case 'compressors': - { - compression = serverOptions.compression || {}; - let compressors = value.split(','); - if ( - !compressors.every(function(compressor) { - return compressor === 'snappy' || compressor === 'zlib'; - }) - ) { - throw new Error('Compressors must be at least one of snappy or zlib'); - } - - compression.compressors = compressors; - serverOptions.compression = compression; - } - break; - case 'zlibCompressionLevel': - { - compression = serverOptions.compression || {}; - let zlibCompressionLevel = parseInt(value, 10); - if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) { - throw new Error('zlibCompressionLevel must be an integer between -1 and 9'); - } - - compression.zlibCompressionLevel = zlibCompressionLevel; - serverOptions.compression = compression; - } - break; - case 'retryWrites': - dbOptions.retryWrites = value === 'true'; - break; - case 'minSize': - dbOptions.minSize = parseInt(value, 10); - break; - default: - { - let logger = Logger('URL Parser'); - logger.warn(`${name} is not supported as a connection string option`); - } - break; - } - }); - - // No tags: should be null (not []) - if (dbOptions.read_preference_tags.length === 0) { - dbOptions.read_preference_tags = null; - } - - // Validate if there are an invalid write concern combinations - if ( - (dbOptions.w === -1 || dbOptions.w === 0) && - (dbOptions.journal === true || dbOptions.fsync === true || dbOptions.safe === true) - ) - throw new Error('w set to -1 or 0 cannot be combined with safe/w/journal/fsync'); - - // If no read preference set it to primary - if (!dbOptions.readPreference) { - dbOptions.readPreference = 'primary'; - } - - // make sure that user-provided options are applied with priority - dbOptions = Object.assign(dbOptions, options); - - // Add servers to result - object.servers = servers; - - // Returned parsed object - return object; -} diff --git a/node_modules/mongodb/lib/utils.js b/node_modules/mongodb/lib/utils.js deleted file mode 100644 index 1eded66..0000000 --- a/node_modules/mongodb/lib/utils.js +++ /dev/null @@ -1,768 +0,0 @@ -'use strict'; -const MongoError = require('./core/error').MongoError; -const ReadPreference = require('./core/topologies/read_preference'); -const WriteConcern = require('./write_concern'); - -var shallowClone = function(obj) { - var copy = {}; - for (var name in obj) copy[name] = obj[name]; - return copy; -}; - -// Figure out the read preference -var translateReadPreference = function(options) { - var r = null; - if (options.readPreference) { - r = options.readPreference; - } else { - return options; - } - - if (typeof r === 'string') { - options.readPreference = new ReadPreference(r); - } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { - const mode = r.mode || r.preference; - if (mode && typeof mode === 'string') { - options.readPreference = new ReadPreference(mode, r.tags, { - maxStalenessSeconds: r.maxStalenessSeconds - }); - } - } else if (!(r instanceof ReadPreference)) { - throw new TypeError('Invalid read preference: ' + r); - } - - return options; -}; - -// Set simple property -var getSingleProperty = function(obj, name, value) { - Object.defineProperty(obj, name, { - enumerable: true, - get: function() { - return value; - } - }); -}; - -var formatSortValue = (exports.formatSortValue = function(sortDirection) { - var value = ('' + sortDirection).toLowerCase(); - - switch (value) { - case 'ascending': - case 'asc': - case '1': - return 1; - case 'descending': - case 'desc': - case '-1': - return -1; - default: - throw new Error( - 'Illegal sort clause, must be of the form ' + - "[['field1', '(ascending|descending)'], " + - "['field2', '(ascending|descending)']]" - ); - } -}); - -var formattedOrderClause = (exports.formattedOrderClause = function(sortValue) { - var orderBy = {}; - if (sortValue == null) return null; - if (Array.isArray(sortValue)) { - if (sortValue.length === 0) { - return null; - } - - for (var i = 0; i < sortValue.length; i++) { - if (sortValue[i].constructor === String) { - orderBy[sortValue[i]] = 1; - } else { - orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); - } - } - } else if (sortValue != null && typeof sortValue === 'object') { - orderBy = sortValue; - } else if (typeof sortValue === 'string') { - orderBy[sortValue] = 1; - } else { - throw new Error( - 'Illegal sort clause, must be of the form ' + - "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" - ); - } - - return orderBy; -}); - -var checkCollectionName = function checkCollectionName(collectionName) { - if ('string' !== typeof collectionName) { - throw new MongoError('collection name must be a String'); - } - - if (!collectionName || collectionName.indexOf('..') !== -1) { - throw new MongoError('collection names cannot be empty'); - } - - if ( - collectionName.indexOf('$') !== -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null - ) { - throw new MongoError("collection names must not contain '$'"); - } - - if (collectionName.match(/^\.|\.$/) != null) { - throw new MongoError("collection names must not start or end with '.'"); - } - - // Validate that we are not passing 0x00 in the collection name - if (collectionName.indexOf('\x00') !== -1) { - throw new MongoError('collection names cannot contain a null character'); - } -}; - -var handleCallback = function(callback, err, value1, value2) { - try { - if (callback == null) return; - - if (callback) { - return value2 ? callback(err, value1, value2) : callback(err, value1); - } - } catch (err) { - process.nextTick(function() { - throw err; - }); - return false; - } - - return true; -}; - -/** - * Wrap a Mongo error document in an Error instance - * @ignore - * @api private - */ -var toError = function(error) { - if (error instanceof Error) return error; - - var msg = error.err || error.errmsg || error.errMessage || error; - var e = MongoError.create({ message: msg, driver: true }); - - // Get all object keys - var keys = typeof error === 'object' ? Object.keys(error) : []; - - for (var i = 0; i < keys.length; i++) { - try { - e[keys[i]] = error[keys[i]]; - } catch (err) { - // continue - } - } - - return e; -}; - -/** - * @ignore - */ -var normalizeHintField = function normalizeHintField(hint) { - var finalHint = null; - - if (typeof hint === 'string') { - finalHint = hint; - } else if (Array.isArray(hint)) { - finalHint = {}; - - hint.forEach(function(param) { - finalHint[param] = 1; - }); - } else if (hint != null && typeof hint === 'object') { - finalHint = {}; - for (var name in hint) { - finalHint[name] = hint[name]; - } - } - - return finalHint; -}; - -/** - * Create index name based on field spec - * - * @ignore - * @api private - */ -var parseIndexOptions = function(fieldOrSpec) { - var fieldHash = {}; - var indexes = []; - var keys; - - // Get all the fields accordingly - if ('string' === typeof fieldOrSpec) { - // 'type' - indexes.push(fieldOrSpec + '_' + 1); - fieldHash[fieldOrSpec] = 1; - } else if (Array.isArray(fieldOrSpec)) { - fieldOrSpec.forEach(function(f) { - if ('string' === typeof f) { - // [{location:'2d'}, 'type'] - indexes.push(f + '_' + 1); - fieldHash[f] = 1; - } else if (Array.isArray(f)) { - // [['location', '2d'],['type', 1]] - indexes.push(f[0] + '_' + (f[1] || 1)); - fieldHash[f[0]] = f[1] || 1; - } else if (isObject(f)) { - // [{location:'2d'}, {type:1}] - keys = Object.keys(f); - keys.forEach(function(k) { - indexes.push(k + '_' + f[k]); - fieldHash[k] = f[k]; - }); - } else { - // undefined (ignore) - } - }); - } else if (isObject(fieldOrSpec)) { - // {location:'2d', type:1} - keys = Object.keys(fieldOrSpec); - keys.forEach(function(key) { - indexes.push(key + '_' + fieldOrSpec[key]); - fieldHash[key] = fieldOrSpec[key]; - }); - } - - return { - name: indexes.join('_'), - keys: keys, - fieldHash: fieldHash - }; -}; - -var isObject = (exports.isObject = function(arg) { - return '[object Object]' === Object.prototype.toString.call(arg); -}); - -var debugOptions = function(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -}; - -var decorateCommand = function(command, options, exclude) { - for (var name in options) { - if (exclude.indexOf(name) === -1) command[name] = options[name]; - } - - return command; -}; - -var mergeOptions = function(target, source) { - for (var name in source) { - target[name] = source[name]; - } - - return target; -}; - -// Merge options with translation -var translateOptions = function(target, source) { - var translations = { - // SSL translation options - sslCA: 'ca', - sslCRL: 'crl', - sslValidate: 'rejectUnauthorized', - sslKey: 'key', - sslCert: 'cert', - sslPass: 'passphrase', - // SocketTimeout translation options - socketTimeoutMS: 'socketTimeout', - connectTimeoutMS: 'connectionTimeout', - // Replicaset options - replicaSet: 'setName', - rs_name: 'setName', - secondaryAcceptableLatencyMS: 'acceptableLatency', - connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', - // Mongos options - acceptableLatencyMS: 'localThresholdMS' - }; - - for (var name in source) { - if (translations[name]) { - target[translations[name]] = source[name]; - } else { - target[name] = source[name]; - } - } - - return target; -}; - -var filterOptions = function(options, names) { - var filterOptions = {}; - - for (var name in options) { - if (names.indexOf(name) !== -1) filterOptions[name] = options[name]; - } - - // Filtered options - return filterOptions; -}; - -// Write concern keys -var writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync']; - -// Merge the write concern options -var mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) { - // Mix in any allowed options - for (var i = 0; i < keys.length; i++) { - if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) { - targetOptions[keys[i]] = sourceOptions[keys[i]]; - } - } - - // No merging of write concern - if (!mergeWriteConcern) return targetOptions; - - // Found no write Concern options - var found = false; - for (i = 0; i < writeConcernKeys.length; i++) { - if (targetOptions[writeConcernKeys[i]]) { - found = true; - break; - } - } - - if (!found) { - for (i = 0; i < writeConcernKeys.length; i++) { - if (sourceOptions[writeConcernKeys[i]]) { - targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; - } - } - } - - return targetOptions; -}; - -/** - * Executes the given operation with provided arguments. - * - * This method reduces large amounts of duplication in the entire codebase by providing - * a single point for determining whether callbacks or promises should be used. Additionally - * it allows for a single point of entry to provide features such as implicit sessions, which - * are required by the Driver Sessions specification in the event that a ClientSession is - * not provided - * - * @param {object} topology The topology to execute this operation on - * @param {function} operation The operation to execute - * @param {array} args Arguments to apply the provided operation - * @param {object} [options] Options that modify the behavior of the method - */ -const executeLegacyOperation = (topology, operation, args, options) => { - if (topology == null) { - throw new TypeError('This method requires a valid topology instance'); - } - - if (!Array.isArray(args)) { - throw new TypeError('This method requires an array of arguments to apply'); - } - - options = options || {}; - const Promise = topology.s.promiseLibrary; - let callback = args[args.length - 1]; - - // The driver sessions spec mandates that we implicitly create sessions for operations - // that are not explicitly provided with a session. - let session, opOptions, owner; - if (!options.skipSessions && topology.hasSessionSupport()) { - opOptions = args[args.length - 2]; - if (opOptions == null || opOptions.session == null) { - owner = Symbol(); - session = topology.startSession({ owner }); - const optionsIndex = args.length - 2; - args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session }); - } else if (opOptions.session && opOptions.session.hasEnded) { - throw new MongoError('Use of expired sessions is not permitted'); - } - } - - const makeExecuteCallback = (resolve, reject) => - function executeCallback(err, result) { - if (session && session.owner === owner && !options.returnsCursor) { - session.endSession(() => { - delete opOptions.session; - if (err) return reject(err); - resolve(result); - }); - } else { - if (err) return reject(err); - resolve(result); - } - }; - - // Execute using callback - if (typeof callback === 'function') { - callback = args.pop(); - const handler = makeExecuteCallback( - result => callback(null, result), - err => callback(err, null) - ); - args.push(handler); - - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - throw e; - } - } - - // Return a Promise - if (args[args.length - 1] != null) { - throw new TypeError('final argument to `executeLegacyOperation` must be a callback'); - } - - return new Promise(function(resolve, reject) { - const handler = makeExecuteCallback(resolve, reject); - args[args.length - 1] = handler; - - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - } - }); -}; - -/** - * Applies retryWrites: true to a command if retryWrites is set on the command's database. - * - * @param {object} target The target command to which we will apply retryWrites. - * @param {object} db The database from which we can inherit a retryWrites value. - */ -function applyRetryableWrites(target, db) { - if (db && db.s.options.retryWrites) { - target.retryWrites = true; - } - - return target; -} - -/** - * Applies a write concern to a command based on well defined inheritance rules, optionally - * detecting support for the write concern in the first place. - * - * @param {Object} target the target command we will be applying the write concern to - * @param {Object} sources sources where we can inherit default write concerns from - * @param {Object} [options] optional settings passed into a command for write concern overrides - * @returns {Object} the (now) decorated target - */ -function applyWriteConcern(target, sources, options) { - options = options || {}; - const db = sources.db; - const coll = sources.collection; - - if (options.session && options.session.inTransaction()) { - // writeConcern is not allowed within a multi-statement transaction - if (target.writeConcern) { - delete target.writeConcern; - } - - return target; - } - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern) { - return Object.assign(target, { writeConcern }); - } - - if (coll && coll.writeConcern) { - return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); - } - - if (db && db.writeConcern) { - return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); - } - - return target; -} - -/** - * Resolves a read preference based on well-defined inheritance rules. This method will not only - * determine the read preference (if there is one), but will also ensure the returned value is a - * properly constructed instance of `ReadPreference`. - * - * @param {Collection|Db|MongoClient} parent The parent of the operation on which to determine the read - * preference, used for determining the inherited read preference. - * @param {Object} options The options passed into the method, potentially containing a read preference - * @returns {(ReadPreference|null)} The resolved read preference - */ -function resolveReadPreference(parent, options) { - options = options || {}; - const session = options.session; - - const inheritedReadPreference = parent.readPreference; - - let readPreference; - if (options.readPreference) { - readPreference = ReadPreference.fromOptions(options); - } else if (session && session.inTransaction() && session.transaction.options.readPreference) { - // The transaction’s read preference MUST override all other user configurable read preferences. - readPreference = session.transaction.options.readPreference; - } else if (inheritedReadPreference != null) { - readPreference = inheritedReadPreference; - } else { - throw new Error('No readPreference was provided or inherited.'); - } - - return typeof readPreference === 'string' ? new ReadPreference(readPreference) : readPreference; -} - -/** - * Checks if a given value is a Promise - * - * @param {*} maybePromise - * @return true if the provided value is a Promise - */ -function isPromiseLike(maybePromise) { - return maybePromise && typeof maybePromise.then === 'function'; -} - -/** - * Applies collation to a given command. - * - * @param {object} [command] the command on which to apply collation - * @param {(Cursor|Collection)} [target] target of command - * @param {object} [options] options containing collation settings - */ -function decorateWithCollation(command, target, options) { - const topology = (target.s && target.s.topology) || target.topology; - - if (!topology) { - throw new TypeError('parameter "target" is missing a topology'); - } - - const capabilities = topology.capabilities(); - if (options.collation && typeof options.collation === 'object') { - if (capabilities && capabilities.commandsTakeCollation) { - command.collation = options.collation; - } else { - throw new MongoError(`Current topology does not support collation`); - } - } -} - -/** - * Applies a read concern to a given command. - * - * @param {object} command the command on which to apply the read concern - * @param {Collection} coll the parent collection of the operation calling this method - */ -function decorateWithReadConcern(command, coll, options) { - if (options && options.session && options.session.inTransaction()) { - return; - } - let readConcern = Object.assign({}, command.readConcern || {}); - if (coll.s.readConcern) { - Object.assign(readConcern, coll.s.readConcern); - } - - if (Object.keys(readConcern).length > 0) { - Object.assign(command, { readConcern: readConcern }); - } -} - -const emitProcessWarning = msg => process.emitWarning(msg, 'DeprecationWarning'); -const emitConsoleWarning = msg => console.error(msg); -const emitDeprecationWarning = process.emitWarning ? emitProcessWarning : emitConsoleWarning; - -/** - * Default message handler for generating deprecation warnings. - * - * @param {string} name function name - * @param {string} option option name - * @return {string} warning message - * @ignore - * @api private - */ -function defaultMsgHandler(name, option) { - return `${name} option [${option}] is deprecated and will be removed in a later version.`; -} - -/** - * Deprecates a given function's options. - * - * @param {object} config configuration for deprecation - * @param {string} config.name function name - * @param {Array} config.deprecatedOptions options to deprecate - * @param {number} config.optionsIndex index of options object in function arguments array - * @param {function} [config.msgHandler] optional custom message handler to generate warnings - * @param {function} fn the target function of deprecation - * @return {function} modified function that warns once per deprecated option, and executes original function - * @ignore - * @api private - */ -function deprecateOptions(config, fn) { - if (process.noDeprecation === true) { - return fn; - } - - const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; - - const optionsWarned = new Set(); - function deprecated() { - const options = arguments[config.optionsIndex]; - - // ensure options is a valid, non-empty object, otherwise short-circuit - if (!isObject(options) || Object.keys(options).length === 0) { - return fn.apply(this, arguments); - } - - config.deprecatedOptions.forEach(deprecatedOption => { - if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) { - optionsWarned.add(deprecatedOption); - const msg = msgHandler(config.name, deprecatedOption); - emitDeprecationWarning(msg); - if (this && this.getLogger) { - const logger = this.getLogger(); - if (logger) { - logger.warn(msg); - } - } - } - }); - - return fn.apply(this, arguments); - } - - // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 - // The wrapper will keep the same prototype as fn to maintain prototype chain - Object.setPrototypeOf(deprecated, fn); - if (fn.prototype) { - // Setting this (rather than using Object.setPrototype, as above) ensures - // that calling the unwrapped constructor gives an instanceof the wrapped - // constructor. - deprecated.prototype = fn.prototype; - } - - return deprecated; -} - -const SUPPORTS = {}; -// Test asyncIterator support -try { - require('./async/async_iterator'); - SUPPORTS.ASYNC_ITERATOR = true; -} catch (e) { - SUPPORTS.ASYNC_ITERATOR = false; -} - -class MongoDBNamespace { - constructor(db, collection) { - this.db = db; - this.collection = collection; - } - - toString() { - return this.collection ? `${this.db}.${this.collection}` : this.db; - } - - withCollection(collection) { - return new MongoDBNamespace(this.db, collection); - } - - static fromString(namespace) { - if (!namespace) { - throw new Error(`Cannot parse namespace from "${namespace}"`); - } - - const index = namespace.indexOf('.'); - return new MongoDBNamespace(namespace.substring(0, index), namespace.substring(index + 1)); - } -} - -function* makeCounter(seed) { - let count = seed || 0; - while (true) { - const newCount = count; - count += 1; - yield newCount; - } -} - -/** - * Helper function for either accepting a callback, or returning a promise - * - * @param {Object} parent an instance of parent with promiseLibrary. - * @param {object} parent.s an object containing promiseLibrary. - * @param {function} parent.s.promiseLibrary an object containing promiseLibrary. - * @param {[Function]} callback an optional callback. - * @param {Function} fn A function that takes a callback - * @returns {Promise|void} Returns nothing if a callback is supplied, else returns a Promise. - */ -function maybePromise(parent, callback, fn) { - const PromiseLibrary = (parent && parent.s && parent.s.promiseLibrary) || Promise; - - let result; - if (typeof callback !== 'function') { - result = new PromiseLibrary((resolve, reject) => { - callback = (err, res) => { - if (err) return reject(err); - resolve(res); - }; - }); - } - - fn(function(err, res) { - if (err != null) { - try { - callback(err); - } catch (error) { - return process.nextTick(() => { - throw error; - }); - } - return; - } - - callback(err, res); - }); - - return result; -} - -module.exports = { - filterOptions, - mergeOptions, - translateOptions, - shallowClone, - getSingleProperty, - checkCollectionName, - toError, - formattedOrderClause, - parseIndexOptions, - normalizeHintField, - handleCallback, - decorateCommand, - isObject, - debugOptions, - MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1, - mergeOptionsAndWriteConcern, - translateReadPreference, - executeLegacyOperation, - applyRetryableWrites, - applyWriteConcern, - isPromiseLike, - decorateWithCollation, - decorateWithReadConcern, - deprecateOptions, - SUPPORTS, - MongoDBNamespace, - resolveReadPreference, - emitDeprecationWarning, - makeCounter, - maybePromise -}; diff --git a/node_modules/mongodb/lib/write_concern.js b/node_modules/mongodb/lib/write_concern.js deleted file mode 100644 index 79b0f09..0000000 --- a/node_modules/mongodb/lib/write_concern.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -/** - * The **WriteConcern** class is a class that represents a MongoDB WriteConcern. - * @class - * @property {(number|string)} w The write concern - * @property {number} wtimeout The write concern timeout - * @property {boolean} j The journal write concern - * @property {boolean} fsync The file sync write concern - * @see https://docs.mongodb.com/manual/reference/write-concern/index.html - */ -class WriteConcern { - /** - * Constructs a WriteConcern from the write concern properties. - * @param {(number|string)} [w] The write concern - * @param {number} [wtimeout] The write concern timeout - * @param {boolean} [j] The journal write concern - * @param {boolean} [fsync] The file sync write concern - */ - constructor(w, wtimeout, j, fsync) { - if (w != null) { - this.w = w; - } - if (wtimeout != null) { - this.wtimeout = wtimeout; - } - if (j != null) { - this.j = j; - } - if (fsync != null) { - this.fsync = fsync; - } - } - - /** - * Construct a WriteConcern given an options object. - * - * @param {object} options The options object from which to extract the write concern. - * @return {WriteConcern} - */ - static fromOptions(options) { - if ( - options == null || - (options.writeConcern == null && - options.w == null && - options.wtimeout == null && - options.j == null && - options.fsync == null) - ) { - return; - } - - if (options.writeConcern) { - return new WriteConcern( - options.writeConcern.w, - options.writeConcern.wtimeout, - options.writeConcern.j, - options.writeConcern.fsync - ); - } - - return new WriteConcern(options.w, options.wtimeout, options.j, options.fsync); - } -} - -module.exports = WriteConcern; diff --git a/node_modules/mongodb/package.json b/node_modules/mongodb/package.json deleted file mode 100644 index bb42e7a..0000000 --- a/node_modules/mongodb/package.json +++ /dev/null @@ -1,108 +0,0 @@ -{ - "_from": "mongodb@^3.5.8", - "_id": "mongodb@3.5.8", - "_inBundle": false, - "_integrity": "sha512-jz7mR58z66JKL8Px4ZY+FXbgB7d0a0hEGCT7kw8iye46/gsqPrOEpZOswwJ2BQlfzsrCLKdsF9UcaUfGVN2HrQ==", - "_location": "/mongodb", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "mongodb@^3.5.8", - "name": "mongodb", - "escapedName": "mongodb", - "rawSpec": "^3.5.8", - "saveSpec": null, - "fetchSpec": "^3.5.8" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.5.8.tgz", - "_shasum": "34550856449b745d145873734bf922c12d6b9caa", - "_spec": "mongodb@^3.5.8", - "_where": "/workspace/dbproject", - "bugs": { - "url": "https://github.com/mongodb/node-mongodb-native/issues" - }, - "bundleDependencies": false, - "dependencies": { - "bl": "^2.2.0", - "bson": "^1.1.4", - "denque": "^1.4.1", - "require_optional": "^1.0.1", - "safe-buffer": "^5.1.2", - "saslprep": "^1.0.0" - }, - "deprecated": false, - "description": "The official MongoDB driver for Node.js", - "devDependencies": { - "chai": "^4.1.1", - "chai-subset": "^1.6.0", - "chalk": "^2.4.2", - "co": "4.6.0", - "coveralls": "^2.11.6", - "eslint": "^4.5.0", - "eslint-plugin-prettier": "^2.2.0", - "istanbul": "^0.4.5", - "jsdoc": "3.5.5", - "lodash.camelcase": "^4.3.0", - "mocha": "5.2.0", - "mocha-sinon": "^2.1.0", - "mongodb-extjson": "^2.1.1", - "mongodb-mock-server": "^1.0.1", - "prettier": "^1.19.1", - "semver": "^5.5.0", - "sinon": "^4.3.0", - "sinon-chai": "^3.2.0", - "snappy": "^6.3.4", - "standard-version": "^4.4.0", - "util.promisify": "^1.0.1", - "worker-farm": "^1.5.0", - "wtfnode": "^0.8.0", - "yargs": "^14.2.0" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "index.js", - "lib" - ], - "homepage": "https://github.com/mongodb/node-mongodb-native", - "keywords": [ - "mongodb", - "driver", - "official" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "mongodb", - "optionalDependencies": { - "saslprep": "^1.0.0" - }, - "peerOptionalDependencies": { - "kerberos": "^1.1.0", - "mongodb-client-encryption": "^1.0.0", - "mongodb-extjson": "^2.1.2", - "snappy": "^6.3.4", - "bson-ext": "^2.0.0" - }, - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" - }, - "scripts": { - "atlas": "node ./test/tools/atlas_connectivity_tests.js", - "bench": "node test/benchmarks/driverBench/", - "coverage": "istanbul cover mongodb-test-runner -- -t 60000 test/core test/unit test/functional", - "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", - "generate-evergreen": "node .evergreen/generate_evergreen_tasks.js", - "lint": "eslint -v && eslint lib test", - "release": "standard-version -i HISTORY.md", - "test": "npm run lint && mocha --recursive test/functional test/unit test/core", - "test-nolint": "mocha --recursive test/functional test/unit test/core" - }, - "version": "3.5.8" -} diff --git a/node_modules/mongoose-legacy-pluralize/LICENSE b/node_modules/mongoose-legacy-pluralize/LICENSE deleted file mode 100644 index 261eeb9..0000000 --- a/node_modules/mongoose-legacy-pluralize/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/node_modules/mongoose-legacy-pluralize/README.md b/node_modules/mongoose-legacy-pluralize/README.md deleted file mode 100644 index 3296efb..0000000 --- a/node_modules/mongoose-legacy-pluralize/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# mongoose-legacy-pluralize -Legacy pluralization logic for mongoose diff --git a/node_modules/mongoose-legacy-pluralize/index.js b/node_modules/mongoose-legacy-pluralize/index.js deleted file mode 100644 index 1dd451d..0000000 --- a/node_modules/mongoose-legacy-pluralize/index.js +++ /dev/null @@ -1,95 +0,0 @@ -module.exports = pluralize; - -/** - * Pluralization rules. - * - * These rules are applied while processing the argument to `toCollectionName`. - * - * @deprecated remove in 4.x gh-1350 - */ - -exports.pluralization = [ - [/(m)an$/gi, '$1en'], - [/(pe)rson$/gi, '$1ople'], - [/(child)$/gi, '$1ren'], - [/^(ox)$/gi, '$1en'], - [/(ax|test)is$/gi, '$1es'], - [/(octop|vir)us$/gi, '$1i'], - [/(alias|status)$/gi, '$1es'], - [/(bu)s$/gi, '$1ses'], - [/(buffal|tomat|potat)o$/gi, '$1oes'], - [/([ti])um$/gi, '$1a'], - [/sis$/gi, 'ses'], - [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'], - [/(hive)$/gi, '$1s'], - [/([^aeiouy]|qu)y$/gi, '$1ies'], - [/(x|ch|ss|sh)$/gi, '$1es'], - [/(matr|vert|ind)ix|ex$/gi, '$1ices'], - [/([m|l])ouse$/gi, '$1ice'], - [/(kn|w|l)ife$/gi, '$1ives'], - [/(quiz)$/gi, '$1zes'], - [/s$/gi, 's'], - [/([^a-z])$/, '$1'], - [/$/gi, 's'] -]; -var rules = exports.pluralization; - -/** - * Uncountable words. - * - * These words are applied while processing the argument to `toCollectionName`. - * @api public - */ - -exports.uncountables = [ - 'advice', - 'energy', - 'excretion', - 'digestion', - 'cooperation', - 'health', - 'justice', - 'labour', - 'machinery', - 'equipment', - 'information', - 'pollution', - 'sewage', - 'paper', - 'money', - 'species', - 'series', - 'rain', - 'rice', - 'fish', - 'sheep', - 'moose', - 'deer', - 'news', - 'expertise', - 'status', - 'media' -]; -var uncountables = exports.uncountables; - -/*! - * Pluralize function. - * - * @author TJ Holowaychuk (extracted from _ext.js_) - * @param {String} string to pluralize - * @api private - */ - -function pluralize(str) { - var found; - str = str.toLowerCase(); - if (!~uncountables.indexOf(str)) { - found = rules.filter(function(rule) { - return str.match(rule[0]); - }); - if (found[0]) { - return str.replace(found[0][0], found[0][1]); - } - } - return str; -} diff --git a/node_modules/mongoose-legacy-pluralize/package.json b/node_modules/mongoose-legacy-pluralize/package.json deleted file mode 100644 index c268ff9..0000000 --- a/node_modules/mongoose-legacy-pluralize/package.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "_from": "mongoose-legacy-pluralize@1.0.2", - "_id": "mongoose-legacy-pluralize@1.0.2", - "_inBundle": false, - "_integrity": "sha512-Yo/7qQU4/EyIS8YDFSeenIvXxZN+ld7YdV9LqFVQJzTLye8unujAWPZ4NWKfFA+RNjh+wvTWKY9Z3E5XM6ZZiQ==", - "_location": "/mongoose-legacy-pluralize", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "mongoose-legacy-pluralize@1.0.2", - "name": "mongoose-legacy-pluralize", - "escapedName": "mongoose-legacy-pluralize", - "rawSpec": "1.0.2", - "saveSpec": null, - "fetchSpec": "1.0.2" - }, - "_requiredBy": [ - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/mongoose-legacy-pluralize/-/mongoose-legacy-pluralize-1.0.2.tgz", - "_shasum": "3ba9f91fa507b5186d399fb40854bff18fb563e4", - "_spec": "mongoose-legacy-pluralize@1.0.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mongoose", - "author": { - "name": "Valeri Karpov", - "email": "val@karpov.io" - }, - "bugs": { - "url": "https://github.com/vkarpov15/mongoose-legacy-pluralize/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Legacy pluralization logic for mongoose", - "homepage": "https://github.com/vkarpov15/mongoose-legacy-pluralize", - "keywords": [ - "mongoose", - "mongodb" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "mongoose-legacy-pluralize", - "peerDependencies": { - "mongoose": "*" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/vkarpov15/mongoose-legacy-pluralize.git" - }, - "version": "1.0.2" -} diff --git a/node_modules/mongoose/.travis.yml b/node_modules/mongoose/.travis.yml deleted file mode 100644 index 687ab6b..0000000 --- a/node_modules/mongoose/.travis.yml +++ /dev/null @@ -1,23 +0,0 @@ -language: node_js -sudo: false -node_js: [14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4] -install: - - travis_retry npm install -before_script: - - wget http://downloads.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1604-4.0.2.tgz - - tar -zxvf mongodb-linux-x86_64-ubuntu1604-4.0.2.tgz - - mkdir -p ./data/db/27017 - - mkdir -p ./data/db/27000 - - printf "\n--timeout 8000" >> ./test/mocha.opts - - ./mongodb-linux-x86_64-ubuntu1604-4.0.2/bin/mongod --fork --dbpath ./data/db/27017 --syslog --port 27017 - - export PATH=`pwd`/mongodb-linux-x86_64-ubuntu1604-4.0.2/bin/:$PATH - - sleep 2 - - mongod --version -matrix: - include: - - name: "👕Linter" - node_js: 10 - before_script: skip - script: npm run lint -notifications: - email: false diff --git a/node_modules/mongoose/History.md b/node_modules/mongoose/History.md deleted file mode 100644 index eed6cc6..0000000 --- a/node_modules/mongoose/History.md +++ /dev/null @@ -1,5763 +0,0 @@ -5.9.14 / 2020-05-13 -=================== - * fix(cursor): add index as second parameter to eachAsync callback #8972 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(query): cast filter according to discriminator schema if discriminator key in filter #8881 - * fix(model): fix throwing error when populating virtual path defined on child discriminator #8924 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(errors): handle case when user has make `Error.prototype.toJSON` read only #8986 [osher](https://github.com/osher) - * fix(model): add `kind` to cast errors thrown by query execution #8953 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(update): use child schema strict on single nested updates if useNestedStrict not set #8922 - * docs(model): improve `save()` docs #8956 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs: add immutable type to Schema Types #8987 [Andrew5569](https://github.com/Andrew5569) - * docs: sort schema reserved keys in documentation #8966 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - -5.9.13 / 2020-05-08 -=================== - * fix(schema): mark correct path as modified when setting a path underneath a nested array of documents #8926 - * fix(query): Query#select({ field: false }) should not overwrite schema selection options #8929 #8923 - * fix(update): handle immutable properties are ignored in bulk upserts #8952 [philippejer](https://github.com/philippejer) - * docs(browser): add back sample webpack config #8890 - * docs(faq): fix broken reference in limit vs perDocumentLimit #8937 - -5.9.12 / 2020-05-04 -=================== - * fix(document): report cast error on array elements with array index instead of just being a cast error for the whole array #8888 - * fix(connection): throw more helpful error in case of IP whitelisting issue with Atlas #8846 - * fix(schema): throw error on schema with reserved key with type of object #8869 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(connection): inherit config for useDB from default connection #8267 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(query): set mongodb options for `distinct()` #8906 [clhuang](https://github.com/clhuang) - * fix(schema): allow adding descending indexes on schema #8895 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(document): set defaults if setting nested path to empty object with `minimize: false` #8829 - * fix(populate): check discriminator existence before accessing schema in getModelsMapForPopulate #8837 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs: fix broken references to Mongoose#Document API, and prefer mongoose.model(...) over Document#model(...) #8914 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs(model): adds options.limit to Model.insertMany(...) #8864 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs: add flattenMaps and aliases to Document#toObject() #8901 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs(model): add options.overwrite to findOneAndUpdate #8865 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs(populate+faq): separate limit-vs-perDocumentLimit into its own section, add FAQ for populate and limit #8917 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - -5.9.11 / 2020-04-30 -=================== - * fix: upgrade mongodb driver -> 3.5.7 #8842 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix: validate nested paths on Model.validate(...) #8848 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(populate): make doc.execPopulate(options) a shorthand for doc.populate(options).execPopulate() #8840 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(model): return validation errors when all docs are invalid & rawResult set #8853 [tusharf5](https://github.com/tusharf5) - * fix(schemaType): treat select: null or select: undefined as not specified #8850 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix: fix stream close event listener being called multiple times in Node 14 #8835 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(populate): handle `clone` with `lean` when setting a path to `null` #8807 - * docs(faq): clarify setting paths under document arrays with `markModified()` #8854 - * docs: fix race condition in creating connection for lambda #8845 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs: add options.path for Model.populate(...) #8833 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs: use ES6 classes for custom schema type example #8802 - -5.9.10 / 2020-04-20 -=================== - * fix: upgrade mongodb -> 3.5.6, bson -> 1.1.4 #8719 - * fix(document): avoid calling `$set()` on object keys if object path isn't in schema #8751 - * fix(timestamps): handle timestamps on doubly nested subdocuments #8799 - * fix(schematype): throw error if default is set to a schema instance #8751 - * fix: handle $elemMatch projection with `select: false` in schema #8818 #8806 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs: make FAQ questions more linkable #8825 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs(validation): use `init()` as opposed to `once('index')` in `unique` example #8816 - * docs: clarify `insertMany()` return value #8820 [dandv](https://github.com/dandv) - * docs(populate+query): fix typos #8793 #8794 [dandv](https://github.com/dandv) - * docs(model): document skipId parameter #8791 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - -5.9.9 / 2020-04-13 -================== - * fix(model): make Model.bulkWrite accept `strict` option #8782 #8788 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(virtual): make populated virtual getter return value when it is passed in #8775 #8774 [makinde](https://github.com/makinde) - * fix(document): handle validating document array whose docs contain maps and nested paths #8767 - * fix(document): skip discriminator key when overwriting a document #8765 - * fix(populate): support `clone` option with `lean` #8761 #8760 - * docs(transactions): use `endSession()` in all transactions examples #8741 - * docs(queries): expand streaming section to include async iterators, cursor timeouts, and sesssion idle timeouts #8720 - * docs(model+query+findoneandupdate): add docs for `returnOriginal` option #8766 - * docs(model): fix punctuation #8788 [dandv](https://github.com/dandv) - * docs: fix typos #8780 #8799 [dandv](https://github.com/dandv) - -5.9.8 / 2020-04-06 -================== - * fix(map): run getters when calling `Map#get()` #8730 - * fix(populate): handle `refPath` function in embedded discriminator #8731 - * fix(model): allow setting timestamps to false for bulkWrite #8758 #8745 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(model): pass custom options to `exists()` when no changes to save #8764 #8739 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(update): respect `useNestedStrict: false` when updating a single nested path #8735 - * fix(schema): allow `modelName` as a schema path, since `modelName` is a static property on models #7967 - * docs(promises): add section about using `exec()` with queries and `await` #8747 - * docs(connections): clarify that `connectTimeoutMS` doesn't do anything with `useUnifiedTopology`, should use `serverSelectionTimeoutMS` #8721 - * chore: upgrade mpath -> 0.7.0 #8762 [roja548](https://github.com/roja548) - -5.9.7 / 2020-03-30 -================== - * fix(map): avoid infinite loop when setting a map of documents to a document copied using spread operator #8722 - * fix(query): clean stack trace for filter cast errors so they include the calling file #8691 - * fix(model): make bulkWrite updates error if `strict` and `upsert` are set and `filter` contains a non-schema path #8698 - * fix(cast): make internal `castToNumber()` allow undefined #8725 [p3x-robot](https://github.com/p3x-robot) - -5.9.6 / 2020-03-23 -================== - * fix(document): allow saving document with nested document array after setting `nestedArr.0` #8689 - * docs(connections): expand section about multiple connections to describe patterns for exporting schemas #8679 - * docs(populate): add note about `execPopulate()` to "populate an existing document" section #8671 #8275 - * docs: fix broken links #8690 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs(guide): fix typos #8704 [MateRyze](https://github.com/MateRyze) - * docs(guide): fix minor typo #8683 [pkellz](https://github.com/pkellz) - -5.9.5 / 2020-03-16 -================== - * fix: upgrade mongodb driver -> 3.5.5 #8667 #8664 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(connection): emit "disconnected" after losing connectivity to every member of a replica set with `useUnifiedTopology: true` #8643 - * fix(array): allow calling `slice()` after `push()` #8668 #8655 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(map): avoid marking map as modified if setting `key` to the same value #8652 - * fix(updateValidators): don't run `Mixed` update validator on dotted path underneath mixed type #8659 - * fix(populate): ensure top-level `limit` applies if one document being populated has more than `limit` results #8657 - * fix(populate): throw error if both `limit` and `perDocumentLimit` are set #8661 #8658 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs(findOneAndUpdate): add a section about the `rawResult` option #8662 - * docs(guide): add section about `loadClass()` #8623 - * docs(query): improve `Query#populate()` example to clarify that `sort` doesn't affect the original result's order #8647 - -5.9.4 / 2020-03-09 -================== - * fix(document): allow `new Model(doc)` to set immutable properties when doc is a mongoose document #8642 - * fix(array): make sure you can call `unshift()` after `slice()` #8482 - * fix(schema): propagate `typePojoToMixed` to implicitly created arrays #8627 - * fix(schema): also propagate `typePojoToMixed` option to schemas implicitly created because of `typePojoToMixed` #8627 - * fix(model): support passing `background` option to `syncIndexes()` #8645 - * docs(schema): add a section about the `_id` path in schemas #8625 - * docs(virtualtype+populate): document using `match` with virtual populate #8616 - * docs(guide): fix typo #8648 [sauzy34](https://github.com/sauzy34) - -5.9.3 / 2020-03-02 -================== - * fix: upgrade mongodb driver -> 3.5.4 #8620 - * fix(document): set subpath defaults when overwriting single nested subdoc #8603 - * fix(document): make calling `validate()` with single nested subpath only validate that single nested subpath #8626 - * fix(browser): make `mongoose.model()` return a class in the browser to allow hydrating populated data in the browser #8605 - * fix(model): make `syncIndexes()` and `cleanIndexes()` drop compound indexes with `_id` that aren't in the schema #8559 - * docs(connection+index): add warnings to explain that bufferMaxEntries does nothing with `useUnifiedTopology` #8604 - * docs(document+model+query): add `options.timestamps` parameter docs to `findOneAndUpdate()` and `findByIdAndUpdate()` #8619 - * docs: fix out of date links to tumblr #8599 - -5.9.2 / 2020-02-21 -================== - * fix(model): add discriminator key to bulkWrite filters #8590 - * fix(document): when setting nested array path to non-nested array, wrap values top-down rather than bottom up when possible #8544 - * fix(document): dont leave nested key as undefined when setting nested key to empty object with minimize #8565 - * fix(document): avoid throwing error if setting path to Mongoose document with nullish `_doc` #8565 - * fix(update): handle Binary type correctly with `runValidators` #8580 - * fix(query): run `deleteOne` hooks only on `Document#deleteOne()` when setting `options.document = true` for `Schema#pre()` #8555 - * fix(document): allow calling `validate()` in post validate hook without causing parallel validation error #8597 - * fix(virtualtype): correctly copy options when cloning #8587 - * fix(collection): skip creating capped collection if `autoCreate` set to `false` #8566 - * docs(middleware): clarify that updateOne and deleteOne hooks are query middleware by default, not document middleware #8581 - * docs(aggregate): clarify that `Aggregate#unwind()` can take object parameters as well as strings #8594 - -5.9.1 / 2020-02-14 -================== - * fix(model): set session when calling `save()` with no changes #8571 - * fix(schema): return correct pathType when single nested path is embedded under a nested path with a numeric name #8583 - * fix(queryhelpers): remove `Object.values()` for Node.js 4.x-6.x support #8596 - * fix(cursor): respect sort order when using `eachAsync()` with `parallel` and a sync callback #8577 - * docs: update documentation of custom _id overriding in discriminators #8591 [sam-mfb](https://github.com/sam-mfb) - -5.9.0 / 2020-02-13 -================== - * fix: upgrade to MongoDB driver 3.5 #8520 #8563 - * feat(schematype): support setting default options for schema type (`trim` on all strings, etc.) #8487 - * feat(populate): add `perDocumentLimit` option that limits per document in `find()` result, rather than across all documents #7318 - * feat(schematype): enable setting `transform` option on individual schematypes #8403 - * feat(timestamps): allow setting `currentTime` option for setting custom function to get the current time #3957 - * feat(connection): add `Connection#watch()` to watch for changes on an entire database #8425 - * feat(document): add `Document#$op` property to make it easier to tell what operation is running in middleware #8439 - * feat(populate): support `limit` as top-level populate option #8445 - -5.8.13 / 2020-02-13 -=================== - * fix(populate): use safe get to avoid crash if schematype doesn't have options #8586 - -5.8.12 / 2020-02-12 -=================== - * fix(query): correctly cast dbref `$id` with `$elemMatch` #8577 - * fix(populate): handle populating when some embedded discriminator schemas have `refPath` but none of the subdocs have `refPath` #8553 - * docs: add useUnifiedTopology to homepage example #8558 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * refactor(utils): moving promiseOrCallback to helpers/promiseOrCallback #8573 [hugosenari](https://github.com/hugosenari) - -5.8.11 / 2020-01-31 -=================== - * fix(document): allow calling `validate()` multiple times in parallel on subdocs to avoid errors if Mongoose double-validates [taxilian](https://github.com/taxilian) #8548 #8539 - * fix(connection): allow calling initial `mongoose.connect()` after connection helpers on the same tick #8534 - * fix(connection): throw helpful error when callback param to `mongoose.connect()` or `mongoose.createConnection()` is not a function #8556 - * fix(drivers): avoid unnecessary caught error when importing #8528 - * fix(discriminator): remove unnecessary `utils.merge()` [samgladstone](https://github.com/samgladstone) #8542 - * docs: add "built with mongoose" page #8540 - -5.8.10 / 2020-01-27 -=================== - * perf(document): improve performance of document creation by skipping unnecessary split() calls #8533 [igrunert-atlassian](https://github.com/igrunert-atlassian) - * fix(document): only call validate once for deeply nested subdocuments #8532 #8531 [taxilian](https://github.com/taxilian) - * fix(document): create document array defaults in forward order, not reverse #8514 - * fix(document): allow function as message for date min/max validator #8512 - * fix(populate): don't try to populate embedded discriminator that has populated path but no `refPath` #8527 - * fix(document): plugins from base schema when creating a discriminator #8536 [samgladstone](https://github.com/samgladstone) - * fix(document): ensure parent and ownerDocument are set for subdocs in document array defaults #8509 - * fix(document): dont set undefined keys to null if minimize is false #8504 - * fix(update): bump timestamps when using update aggregation pipelines #8524 - * fix(model): ensure `cleanIndexes()` drops indexes with different collations #8521 - * docs(model): document `insertMany` `lean` option #8522 - * docs(connections): document `authSource` option #8517 - -5.8.9 / 2020-01-17 -================== - * fix(populate): skip populating embedded discriminator array values that don't have a `refPath` #8499 - * docs(queries): clarify when to use queries versus aggregations #8494 - -5.8.8 / 2020-01-14 -================== - * fix(model): allow using `lean` with `insertMany()` #8507 #8234 [ntsekouras](https://github.com/ntsekouras) - * fix(document): don't throw parallel validate error when validating subdoc underneath modified nested path #8486 - * fix: allow `typePojoToMixed` as top-level option #8501 #8500 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs(populate+schematypes): make note of `_id` getter for ObjectIds in populate docs #8483 - -5.8.7 / 2020-01-10 -================== - * fix(documentarray): modify ownerDocument when setting doc array to a doc array thats part of another document #8479 - * fix(document): ensure that you can call `splice()` after `slice()` on an array #8482 - * docs(populate): improve cross-db populate docs to include model refs #8497 - -5.8.6 / 2020-01-07 -==================== - * chore: merge changes from 4.13.20 and override mistaken publish to latest tag - -4.13.20 / 2020-01-07 -==================== - * fix(schema): make aliases handle mongoose-lean-virtuals #6069 - -5.8.5 / 2020-01-06 -================== - * fix(document): throw error when running `validate()` multiple times on the same document #8468 - * fix(model): ensure deleteOne() and deleteMany() set discriminator filter even if no conditions passed #8471 - * fix(document): allow pre('validate') hooks to throw errors with `name = 'ValidationError'` #8466 - * fix(update): move top level $set of immutable properties to $setOnInsert so upserting with immutable properties actually sets the property #8467 - * fix(document): avoid double-running validators on single nested subdocs within single nested subdocs #8468 - * fix(populate): support top-level match option for virtual populate #8475 - * fix(model): avoid applying skip when populating virtual with count #8476 - -5.8.4 / 2020-01-02 -================== - * fix(populate): ensure populate virtual gets set to empty array if `localField` is undefined in the database #8455 - * fix(connection): wrap `mongoose.connect()` server selection timeouts in MongooseTimeoutError for more readable stack traces #8451 - * fix(populate): allow deselecting `foreignField` from projection by prefixing with `-` #8460 - * fix(populate): support embedded discriminators with `refPath` when not all discriminator schemas have `refPath` #8452 - * fix(array): allow defining `enum` on array if an array of numbers #8449 - -5.8.3 / 2019-12-23 -================== - * fix: upgrade mongodb -> 3.4.1 #8430 [jaschaio](https://github.com/jaschaio) - * fix(populate): don't add empty subdocument to array when populating path underneath a non-existent document array #8432 - * fix(schema): handle `_id` option for document array schematypes #8450 - * fix(update): call setters when updating mixed type #8444 - * docs(connections): add note about MongoTimeoutError.reason #8402 - -5.8.2 / 2019-12-20 -================== - * fix(schema): copy `.add()`-ed paths when calling `.add()` with schema argument #8429 - * fix(cursor): pull schema-level readPreference when using `Query#cursor()` #8421 - * fix(cursor): wait for all promises to resolve if `parallel` is greater than number of documents #8422 - * fix(document): depopulate entire array when setting array path to a partially populated array #8443 - * fix: handle setDefaultsOnInsert with deeply nested subdocs #8392 - * fix(document): report `DocumentNotFoundError` if underlying document deleted but no changes made #8428 #8371 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs(populate): clarify limitations of `limit` option for populate and suggest workaround #8409 - * docs(deprecations): explain which connection options are no longer relevant with useUnifiedTopology #8411 - * chore: allow browser build to be published #8435 #8427 [captaincaius](https://github.com/captaincaius) - -5.8.1 / 2019-12-12 -================== - * fix(documentarray): dont attempt to cast when modifying array returned from map() #8399 - * fix(document): update single nested subdoc parent when setting to existing single nested doc #8400 - * fix(schema): add `$embeddedSchemaType` property to arrays for consistency with document arrays #8389 - -5.8.0 / 2019-12-09 -================== - * feat: wrap server selection timeout errors in `MongooseTimeoutError` to retain original stack trace #8259 - * feat(model): add `Model.validate()` function that validates a POJO against the model's schema #7587 - * feat(schema): add `Schema#pick()` function to create a new schema with a picked subset of the original schema's paths #8207 - * feat(schema): add ability to change CastError message using `cast` option to SchemaType #8300 - * feat(schema): group indexes defined in schema path with the same name #6499 - * fix(model): build all indexes even if one index fails #8185 [unusualbob](https://github.com/unusualbob) - * feat(browser): pre-compile mongoose/browser #8350 [captaincaius](https://github.com/captaincaius) - * fix(connection): throw error when setting unsupported option #8335 #6899 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * feat(schema): support `enum` validator for number type #8139 - * feat(update): allow using MongoDB 4.2 update aggregation pipelines, with no Mongoose casting #8225 - * fix(update): make update validators run on all subpaths when setting a nested path, even omitted subpaths #3587 - * feat(schema): support setting `_id` as an option to single nested schema paths #8137 - * feat(query): add Query#mongooseOptions() function #8296 - * feat(array): make `MongooseArray#push()` support using `$position` #4322 - * feat(schema): make pojo paths optionally become subdoc instead of Mixed #8228 [captaincaius](https://github.com/captaincaius) - * feat(model): add Model.cleanIndexes() to drop non-schema indexes #6676 - * feat(document): make `updateOne()` document middleware pass `this` to post hooks #8262 - * feat(aggregate): run pre/post aggregate hooks on `explain()` #5887 - * docs(model+query): add `session` option to docs for findOneAndX() methods #8396 - -5.7.14 / 2019-12-06 -=================== - * fix(cursor): wait until all `eachAsync()` functions finish before resolving the promise #8352 - * fix(update): handle embedded discriminator paths when discriminator key is defined in the update #8378 - * fix(schematype): handle passing `message` function to `SchemaType#validate()` as positional arg #8360 - * fix(map): handle cloning a schema that has a map of subdocuments #8357 - * docs(schema): clarify that `uppercase`, `lowercase`, and `trim` options for SchemaString don't affect RegExp queries #8333 - -5.7.13 / 2019-11-29 -=================== - * fix: upgrade mongodb driver -> 3.3.5 #8383 - * fix(model): catch the error when insertMany fails to initialize the document #8365 #8363 [Fonger](https://github.com/Fonger) - * fix(schema): add array.$, array.$.$ subpaths for nested arrays #6405 - * docs(error): add more detail about the ValidatorError class, including properties #8346 - * docs(connection): document `Connection#models` property #8314 - -5.7.12 / 2019-11-19 -=================== - * fix: avoid throwing error if calling `push()` on a doc array with no parent #8351 #8317 #8312 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(connection): only buffer for "open" events when calling connection helper while connecting #8319 - * fix(connection): pull default database from connection string if specified #8355 #8354 [zachazar](https://github.com/zachazar) - * fix(populate+discriminator): handle populating document whose discriminator value is different from discriminator model name #8324 - * fix: add `mongoose.isValidObjectId()` function to test whether Mongoose can cast a value to an objectid #3823 - * fix(model): support setting `excludeIndexes` as schema option for subdocs #8343 - * fix: add SchemaMapOptions class for options to map schematype #8318 - * docs(query): remove duplicate omitUndefined options #8349 [mdumandag](https://github.com/mdumandag) - * docs(schema): add Schema#paths docs to public API docs #8340 - -5.7.11 / 2019-11-14 -=================== - * fix: update mongodb driver -> 3.3.4 #8276 - * fix(model): throw readable error when casting bulkWrite update without a 'filter' or 'update' #8332 #8331 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(connection): bubble up connected/disconnected events with unified topology #8338 #8337 - * fix(model): delete $versionError after saving #8326 #8048 [Fonger](https://github.com/Fonger) - * test(model): add test for issue #8040 #8341 [Fonger](https://github.com/Fonger) - -5.7.10 / 2019-11-11 -=================== - * perf(cursor): remove unnecessary `setTimeout()` in `eachAsync()`, 4x speedup in basic benchmarks #8310 - * docs(README): re-order sections for better readability #8321 [dandv](https://github.com/dandv) - * chore: make npm test not hard-code file paths #8322 [stieg](https://github.com/stieg) - -5.7.9 / 2019-11-08 -================== - * fix(schema): support setting schema path to an instance of SchemaTypeOptions to fix integration with mongoose-i18n-localize #8297 #8292 - * fix(populate): make `retainNullValues` set array element to `null` if foreign doc with that id was not found #8293 - * fix(document): support getter setting virtual on manually populated doc when calling toJSON() #8295 - * fix(model): allow objects with `toBSON()` to make it to `save()` #8299 - -5.7.8 / 2019-11-04 -================== - * fix(document): allow manually populating path within document array #8273 - * fix(populate): update top-level `populated()` when updating document array with populated subpaths #8265 - * fix(cursor): throw error when using aggregation cursor as async iterator #8280 - * fix(schema): retain `_id: false` in schema after nesting in another schema #8274 - * fix(document): make Document class an event emitter to support defining documents without models in node #8272 - * docs: document return types for `.discriminator()` #8287 - * docs(connection): add note about exporting schemas, not models, in multi connection paradigm #8275 - * docs: clarify that transforms defined in `toObject()` options are applied to subdocs #8260 - -5.7.7 / 2019-10-24 -================== - * fix(populate): make populate virtual consistently an empty array if local field is only empty arrays #8230 - * fix(query): allow findOne(objectid) and find(objectid) #8268 - -5.7.6 / 2019-10-21 -================== - * fix: upgrade mongodb driver -> 3.3.3 to fix issue with failing to connect to a replica set if one member is down #8209 - * fix(document): fix TypeError when setting a single nested subdoc with timestamps #8251 - * fix(cursor): fix issue with long-running `eachAsync()` cursor #8249 #8235 - * fix(connection): ensure repeated `close` events from useUnifiedTopology don't disconnect Mongoose from replica set #8224 - * fix(document): support calling `Document` constructor directly in Node.js #8237 - * fix(populate): add document array subpaths to parent doc `populated()` when calling `DocumentArray#push()` #8247 - * fix(options): add missing minlength and maxlength to SchemaStringOptions #8256 - * docs: add documentarraypath to API docs, including DocumentArrayPath#discriminator() #8164 - * docs(schematypes): add a section about the `type` property #8227 - * docs(api): fix Connection.close return param #8258 [gosuhiman](https://github.com/gosuhiman) - * docs: update link to broken image on home page #8253 [krosenk729](https://github.com/krosenk729) - -5.7.5 / 2019-10-14 -================== - * fix(query): delete top-level `_bsontype` property in queries to prevent silent empty queries #8222 - * fix(update): handle subdocument pre('validate') errors in update validation #7187 - * fix(subdocument): make subdocument#isModified use parent document's isModified #8223 - * docs(index): add favicon to home page #8226 - * docs: add schema options to API docs #8012 - * docs(middleware): add note about accessing the document being updated in pre('findOneAndUpdate') #8218 - * refactor: remove redundant code in ValidationError #8244 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - -5.7.4 / 2019-10-09 -================== - * fix(schema): handle `required: null` and `required: undefined` as `required: false` #8219 - * fix(update): support updating array embedded discriminator props if discriminator key in $elemMatch #8063 - * fix(populate): allow accessing populate virtual prop underneath array when virtual defined on top level #8198 - * fix(model): support passing `options` to `Model.remove()` #8211 - * fix(document): handle `Document#set()` merge option when setting underneath single nested schema #8201 - * fix: use options constructor class for all schematypes #8012 - -5.7.3 / 2019-09-30 -================== - * fix: make CoreMongooseArray#includes() handle `fromIndex` parameter #8203 - * fix(update): cast right hand side of `$pull` as a query instead of an update for document arrays #8166 - * fix(populate): handle virtual populate of an embedded discriminator nested path #8173 - * docs(validation): remove deprecated `isAsync` from validation docs in favor of emphasizing promises #8184 - * docs(documents): add overwriting section #8178 - * docs(promises): add note about queries being thenable #8110 - * perf: avoid update validators going into Mixed types #8192 [birdofpreyru](https://github.com/birdofpreyru) - * refactor: remove async as a prod dependency #8073 - -5.7.2 / 2019-09-23 -================== - * fix(mongoose): support `mongoose.set('autoIndex', false)` #8158 - * fix(discriminator): support `tiedValue` parameter for embedded discriminators analagous to top-level discriminators #8164 - * fix(query): handle `toConstructor()` with entries-style sort syntax #8159 - * fix(populate): avoid converting mixed paths into arrays if populating an object path under `Mixed` #8157 - * fix: use $wrapCallback when using promises for mongoose-async-hooks - * fix: handle queries with setter that converts value to Number instance #8150 - * docs: add mongoosejs-cli to readme #8142 - * docs: fix example typo for Schema.prototype.plugin() #8175 [anaethoss](https://github.com/anaethoss) - -5.7.1 / 2019-09-13 -================== - * fix(query): fix TypeError when calling `findOneAndUpdate()` with `runValidators` #8151 [fernandolguevara](https://github.com/fernandolguevara) - * fix(document): throw strict mode error if setting an immutable path with strict mode: false #8149 - * fix(mongoose): support passing options object to Mongoose constructor #8144 - * fix(model): make syncIndexes() handle changes in index key order #8135 - * fix(error): export StrictModeError as a static property of MongooseError #8148 [ouyuran](https://github.com/ouyuran) - * docs(connection+mongoose): add `useUnifiedTopology` option to `connect()` and `openUri()` docs #8146 - -5.7.0 / 2019-09-09 -================== - * feat(document+query): support conditionally immutable schema paths #8001 - * perf(documentarray): refactor to use ES6 classes instead of mixins, ~30% speedup #7895 - * feat: use MongoDB driver 3.3.x for MongoDB 4.2 support #8083 #8078 - * feat(schema+query): add pre('validate') and post('validate') hooks for update validation #7984 - * fix(timestamps): ensure updatedAt gets incremented consistently using update with and without $set #4768 - * feat(query): add `Query#get()` to make writing custom setters that handle both queries and documents easier #7312 - * feat(document): run setters on defaults #8012 - * feat(document): add `aliases: false` option to `Document#toObject()` #7548 - * feat(timestamps): support skipping updatedAt and createdAt for individual save() and update() #3934 - * docs: fix index creation link in guide #8138 [joebowbeer](https://github.com/joebowbeer) - -5.6.13 / 2019-09-04 -=================== - * fix(parallel): fix parallelLimit when fns is empty #8130 #8128 [sibelius](https://github.com/sibelius) - * fix(document): ensure nested mixed validator gets called exactly once #8117 - * fix(populate): handle `justOne = undefined` #8125 [taxilian](https://github.com/taxilian) - -5.6.12 / 2019-09-03 -=================== - * fix(schema): handle required validator correctly with `clone()` #8111 - * fix(schema): copy schematype getters and setters when cloning #8124 [StphnDamon](https://github.com/StphnDamon) - * fix(discriminator): avoid unnecessarily cloning schema to avoid leaking memory on repeated `discriminator()` calls #2874 - * docs(schematypes): clarify when Mongoose uses `toString()` to convert an object to a string #8112 [TheTrueRandom](https://github.com/TheTrueRandom) - * docs(plugins): fix out of date link to npm docs #8100 - * docs(deprecations): fix typo #8109 [jgcmarins](https://github.com/jgcmarins) - * refactor(model): remove dependency on `async.parallelLimit()` for `insertMany()` #8073 - -5.6.11 / 2019-08-25 -=================== - * fix(model): allow passing options to `exists()` #8075 - * fix(document): make `validateUpdatedOnly` option handle pre-existing errors #8091 - * fix: throw readable error if middleware callback isnt a function #8087 - * fix: don't throw error if calling `find()` on a nested array #8089 - * docs(middleware): clarify that you must add middleware before compiling your model #5087 - * docs(query): add missing options to `setOptions()` #8099 - -5.6.10 / 2019-08-20 -=================== - * fix(schema): fix require() path to work around yet another bug in Jest #8053 - * fix(document): skip casting when initing a populated path #8062 - * fix(document): prevent double-calling validators on mixed objects with nested properties #8067 - * fix(query): handle schematype with `null` options when checking immutability #8070 [rich-earth](https://github.com/rich-earth) - * fix(schema): support `Schema#path()` to get schema path underneath doc array #8057 - * docs(faq): add disable color instruction #8066 - -5.6.9 / 2019-08-07 -================== - * fix(model): delete versionError after saving to prevent memory leak #8048 - * fix(cursor): correctly handle batchSize option with query cursor #8039 - * fix(populate): handle virtual populate with count = 0 if virtual embedded in doc array #7573 - * fix(schema): allow declaring ObjectId array with `{ type: 'ObjectID' }`, last 'D' case insensitive #8034 - -5.6.8 / 2019-08-02 -================== - * fix(aggregate): allow modifying pipeline in pre('aggregate') hooks #8017 - * fix(query): make `findOneAndReplace()` work with `orFail()` #8030 - * fix(document): allow saving an unchanged document if required populated path is null #8018 - * fix(debug): support disabling colors in debug mode #8033 [Mangosteen-Yang](https://github.com/Mangosteen-Yang) - * docs: add async-await guide #8028 [Rossh87](https://github.com/Rossh87) - * docs(plugins): rewrite plugins docs to be more modern and not use strange `= exports` syntax #8026 - * docs(transactions): clarify relationship between `session` in docs and MongoDB driver ClientSession class, link to driver docs #8009 - -5.6.7 / 2019-07-26 -================== - * fix(document): support validators on nested arrays #7926 - * fix(timestamps): handle `timestamps: false` in child schema #8007 - * fix(query): consistently support `new` option to `findOneAndX()` as an alternative to `returnOriginal` #7846 - * fix(document): make `inspect()` never return `null`, because a document or nested path is never `== null` #7942 - * docs(query+lean): add links to mongoose-lean-virtuals, mongoose-lean-getters, mongoose-lean-defaults #5606 - * docs: add example for `Schema#pre(Array)` #8022 [Mangosteen-Yang](https://github.com/Mangosteen-Yang) - * docs(schematype): updated comment from Schema.path to proper s.path #8013 [chrisweilacker](https://github.com/chrisweilacker) - * chore: upgrade nyc #8015 [kolya182](https://github.com/kolya182) - -5.6.6 / 2019-07-22 -================== - * fix(populate): handle refPath returning a virtual with `Query#populate()` #7341 - * fix(populate): handle `refPath` in discriminator when populating top-level model #5109 - * fix(mongoose): ensure destucturing and named imports work for Mongoose singleton methods like `set()`, etc. #6039 - * fix(query): add missing options for deleteOne and deleteMany in Query #8004 [Fonger](https://github.com/Fonger) - * fix(schema): make embedded discriminators `instanceof` their parent types #5005 - * fix(array): make `validators` a private property that doesn't show up in for/in #6572 - * docs(api): fix array API docs that vanished because of #7798 #7979 - * docs(discriminators+api): add single nested discriminator to discriminator docs and API docs #7983 - * docs(connection+mongoose): make option lists consistent between `mongoose.connect()`, `mongoose.createConnection()`, and `conn.openUri()` #7976 - * docs(validation): clarify resolve(false) vs reject() for promise-based async custom validators #7761 - * docs(guide): use correct `mongoose.set()` instead of `mongoose.use()` #7998 - * docs: add redis cache example #7997 [usama-asfar](https://github.com/usama-asfar) - -5.6.5 / 2019-07-17 -================== - * fix(document): handle setting non-schema path to ObjectId or Decimal128 if strict: false #7973 - * fix(connection): remove backwards-breaking multiple mongoose.connect() call for now #7977 - * fix(schema): print invalid value in error message when a schema path is set to undefined or null #7956 - * fix(model): throw readable error if calling `new Model.discriminator()` #7957 - * fix(mongoose): export `cast()` function #7975 [perfectstorm88](https://github.com/perfectstorm88) - * docs(model): fix link to Model.inspect() and add example #7990 - * docs: fix broken anchor links on validation tutorial #7966 - * docs(api): fix broken links to split API pages #7978 - * chore: create LICENSE.md #7989 [Fonger](https://github.com/Fonger) - -5.6.4 / 2019-07-08 -================== - * fix(schema): support pre(Array, Function) and post(Array, Function) #7803 - * fix(document): load docs with a `once` property successfully #7958 - * fix(queryhelpers): ensure parent `select` overwrites child path `select` if parent is nested #7945 - * fix(schema): make `clone()` correctly copy array embedded discriminators #7954 - * fix(update): fix error when update property gets casted to null #7949 - * fix(connection): bubble up attemptReconnect event for now #7872 - * docs(tutorials): add virtuals tutorial #7965 - * docs(connection): add section on connection handling #6997 - -5.6.3 / 2019-07-03 -================== - * fix(document): respect projection when running getters #7940 - * fix(model): call createCollection() in syncIndexes() to ensure the collection exists #7931 - * fix(document): consistently use post-order traversal for gathering subdocs for hooks #7929 - * fix(schema): ensure `Schema#pathType()` returns correct path type given non-existent positional path #7935 - * fix(ChangeStream): set `closed` if emitting close event #7930 - * fix(connection): bubble up 'attemptReconnect' event from MongoDB connection #7872 - * docs: fix broken .jade links on search page #7932 - * docs: correct link to `Query#select()` #7953 [rayhatfield](https://github.com/rayhatfield) - * docs(README): add list of related projects #7773 - -4.13.19 / 2019-07-02 -==================== - * fix(aggregate): make `setOptions()` work as advertised #7950 #6011 [cdimitroulas](https://github.com/cdimitroulas) - -5.6.2 / 2019-06-28 -================== - * fix(update): allow using `update()` with immutable `createdAt` #7917 - * fix(model): pass `doc` parameter to save() error handling middleware #7832 - * fix(mongoose): add applyPluginsToChildSchemas option to allow opting out of global plugins for child schemas #7916 - * docs(connection): document `useCache` option for `useDb()` #7923 - * docs: fix broken link in FAQ #7925 [christophergeiger3](https://github.com/christophergeiger3) - -5.6.1 / 2019-06-24 -================== - * fix(update): skip setting defaults for single embedded subdocs underneath maps #7909 - * fix(document): copy date objects correctly when strict = false #7907 - * feat(mongoose): throw an error if calling `mongoose.connect()` multiple times while connected #7905 [Fonger](https://github.com/Fonger) - * fix(document): copies virtuals from array subdocs when casting array of docs with same schema #7898 - * fix(schema): ensure clone() copies single embedded discriminators correctly #7894 - * fix(discriminator): merge instead of overwriting conflicting nested schemas in discriminator schema #7884 - * fix(populate): ignore nullish arguments when calling `populate()` #7913 [rayhatfield](https://github.com/rayhatfield) - * docs: add getters/setters tutorial #7919 - * docs: clean up error docs so they refer to `Error` rather than `MongooseError` #7867 - * docs: fix a couple broken links #7921 [kizmo04](https://github.com/kizmo04) - * refactor: remove unnecessary if #7911 [rayhatfield](https://github.com/rayhatfield) - -5.6.0 / 2019-06-14 -================== - * feat(schematype): add `immutable` option to disallow changing a given field #7671 - * docs: split API docs into separate pages to make API documentation more Google-able #7812 - * perf(array): remove all mixins in favor of ES6 classes, ~20% faster in basic benchmarks #7798 - * feat(document): use promise rejection error message when async custom validator throws an error #4913 - * feat(virtual): pass document as 3rd parameter to virtual getters and setters to enable using arrow functions #4143 - * feat(model): add `Model.exists()` function to quickly check whether a document matching `filter` exists #6872 - * feat(index+connection): support setting global and connection-level `maxTimeMS` - * feat(populate): support setting `ref` to a function for conventional populate #7669 - * feat(document): add overwrite() function that overwrites all values in a document #7830 - * feat(populate): support `PopulateOptions#connection` option to allow cross-db populate with refPath #6520 - * feat(populate): add skipInvalidIds option to silently skip population if id is invalid, instead of throwing #7706 - * feat(array): skip empty array default if there's a 2dsphere index on a geojson path #3233 - * feat(query): add `getFilter()` as an alias of `getQuery()` to be more in line with API docs #7839 - * feat(model): add Model.inspect() to make models not clutter `util.inspect()` #7836 - * perf(discriminator): skip calling `createIndex()` on indexes that are defined in the base schema #7379 - * docs: upgrade from Jade to latest Pug #7812 - * docs(README): update reference to example schema.js #7899 [sharils](https://github.com/sharils) - * docs(README): improve variable name #7900 [sharils](https://github.com/sharils) - * chore: replace charAt(0) with startsWith #7897 [Fonger](https://github.com/Fonger) - * chore: replace indexOf with includes, startsWith and endsWith for String #7897 [Fonger](https://github.com/Fonger) - -5.5.15 / 2019-06-12 -=================== - * fix(connection): reject initial connect promise even if there is an on('error') listener #7850 - * fix(map): make `of` automatically convert POJOs to schemas unless typeKey is set #7859 - * fix(update): use discriminator schema to cast update if discriminator key specified in filter #7843 - * fix(array): copy atomics from source array #7891 #7889 [jyrkive](https://github.com/jyrkive) - * fix(schema): return this when Schema.prototype.add is called with Schema #7887 [Mickael-van-der-Beek](https://github.com/Mickael-van-der-Beek) - * fix(document): add `numAffected` and `result` to DocumentNotFoundError for better debugging #7892 #7844 - -5.5.14 / 2019-06-08 -=================== - * fix(query): correct this scope of setters in update query #7876 [Fonger](https://github.com/Fonger) - * fix(model): reset modifiedPaths after successful insertMany #7852 #7873 [Fonger](https://github.com/Fonger) - * fix(populate): allow using `refPath` with virtual populate #7848 - * fix(document): prepend private methods getValue and setValue with $ #7870 [Fonger](https://github.com/Fonger) - * fix: update mongodb driver -> 3.2.7 #7871 [Fonger](https://github.com/Fonger) - * docs(tutorials): add tutorial about custom casting functions #7045 - * docs(connection): fix outdated events document #7874 [Fonger](https://github.com/Fonger) - * docs: fix typo in lean docs #7875 [tannakartikey](https://github.com/tannakartikey) - * docs: move off of KeenIO for tracking and use self-hosted analytics instead - -5.5.13 / 2019-06-05 -=================== - * fix(model): support passing deleteOne options #7860 #7857 [Fonger](https://github.com/Fonger) - * fix(update): run setters on array elements when doing $addToSet, $push, etc #4185 - * fix(model): support getting discriminator by value when creating a new model #7851 - * docs(transactions): add section about the `withTransaction()` helper #7598 - * docs(schema): clarify relationship between Schema#static() and Schema#statics #7827 - * docs(model): fix typo `projetion` to `projection` #7868 [dfdeagle47](https://github.com/dfdeagle47) - * docs(schema): correct schema options lists #7828 - -5.5.12 / 2019-05-31 -=================== - * fix(document): fix unexpected error when loading a document with a nested property named `schema` #7831 - * fix(model): skip applying static hooks by default if static name conflicts with query middleware (re: mongoose-delete plugin) #7790 - * fix(query): apply schema-level projections to the result of `findOneAndReplace()` #7654 - * fix: upgrade mongodb driver -> 3.2.6 - * docs(tutorials): add findOneAndUpdate() tutorial #7847 - * docs(validation): add `updateOne()` and `updateMany()` to list of update validator operations #7845 - * docs(model): make sure options lists in `update()` API line up #7842 - -5.5.11 / 2019-05-23 -=================== - * fix(discriminator): allow numeric discriminator keys for embedded discriminators #7808 - * chore: add Node.js 12 to travis build matrix #7784 - -5.5.10 / 2019-05-20 -=================== - * fix(discriminator): allow user-defined discriminator path in schema #7807 - * fix(query): ensure `findOneAndReplace()` sends `replacement` to server #7654 - * fix(cast): allow `[]` as a value when casting `$nin` #7806 - * docs(model): clarify that setters do run on `update()` by default #7801 - * docs: fix typo in FAQ #7821 [jaona](https://github.com/jaona) - -5.5.9 / 2019-05-16 -================== - * fix(query): skip schema setters when casting $regexp $options #7802 [Fonger](https://github.com/Fonger) - * fix(populate): don't skip populating doc array properties whose name conflicts with an array method #7782 - * fix(populate): make populated virtual return undefined if not populated #7795 - * fix(schema): handle custom setters in arrays of document arrays #7804 [Fonger](https://github.com/Fonger) - * docs(tutorials): add query casting tutorial #7789 - -5.5.8 / 2019-05-13 -================== - * fix(document): run pre save hooks on nested child schemas #7792 - * fix(model): set $session() before validation middleware for bulkWrite/insertMany #7785 #7769 [Fonger](https://github.com/Fonger) - * fix(query): make `getPopulatedPaths()` return deeply populated paths #7757 - * fix(query): suppress findAndModify deprecation warning when using `Model.findOneAndUpdate()` #7794 - * fix: upgrade mongodb -> 3.2.4 #7794 - * fix(document): handle a couple edge cases with atomics that happen when schema defines an array property named 'undefined' #7756 - * docs(discriminator): correct function parameters #7786 [gfpacheco](https://github.com/gfpacheco) - -5.5.7 / 2019-05-09 -================== - * fix(model): set $session() before pre save middleware runs when calling save() with options #7742 - * fix(model): set $session before pre remove hooks run when calling remove() with options #7742 - * fix(schema): support `remove()` on nested path #2398 - * fix(map): handle setting populated map element to doc #7745 - * fix(query): return rawResult when inserting with options `{new:false,upsert:true,rawResult:true}` #7774 #7770 [LiaanM](https://github.com/LiaanM) - * fix(schematype): remove internal `validators` option because it conflicts with Backbone #7720 - -5.5.6 / 2019-05-06 -================== - * fix(document): stop converting arrays to objects when setting non-schema path to array with strict: false #7733 - * fix(array): make two Mongoose arrays `assert.deepEqual()` each other if they have the same values #7700 - * fix(populate): support populating a path in a document array embedded in an array #7647 - * fix(populate): set populate virtual count to 0 if local field is empty #7731 - * fix(update): avoid throwing cast error if casting array filter that isn't in schema with strictQuery = false #7728 - * docs: fix typo in `distinct()` description #7767 [phil-r](https://github.com/phil-r) - -5.5.5 / 2019-04-30 -================== - * fix(document): ensure nested properties within single nested subdocs get set correctly when overwriting single nested subdoc #7748 - * fix(document): skip non-object `validators` in schema types #7720 - * fix: bump mongodb driver -> 3.2.3 #7752 - * fix(map): disallow setting map key with special properties #7750 [Fonger](https://github.com/Fonger) - -5.5.4 / 2019-04-25 -================== - * fix(document): avoid calling custom getters when saving #7719 - * fix(timestamps): handle child schema timestamps correctly when reusing child schemas #7712 - * fix(query): pass correct callback for _legacyFindAndModify #7736 [Fonger](https://github.com/Fonger) - * fix(model+query): allow setting `replacement` parameter for `findOneAndReplace()` #7654 - * fix(map): make `delete()` unset the key in the database #7746 [Fonger](https://github.com/Fonger) - * fix(array): use symbol for `_schema` property to avoid confusing deep equality checks #7700 - * fix(document): prevent `depopulate()` from removing fields with empty array #7741 #7740 [Fonger](https://github.com/Fonger) - * fix: make `MongooseArray#includes` support ObjectIds #7732 #6354 [hansemannn](https://github.com/hansemannn) - * fix(document): report correct validation error index when pushing onto doc array #7744 [Fonger](https://github.com/Fonger) - -5.5.3 / 2019-04-22 -================== - * fix: add findAndModify deprecation warning that references the useFindAndModify option #7644 - * fix(document): handle pushing a doc onto a discriminator that contains a doc array #7704 - * fix(update): run setters on array elements when doing $set #7679 - * fix: correct usage of arguments while buffering commands #7718 [rzymek](https://github.com/rzymek) - * fix(document): avoid error clearing modified subpaths if doc not defined #7715 [bitflower](https://github.com/bitflower) - * refactor(array): move `_parent` property behind a symbol #7726 #7700 - * docs(model): list out all operations and options for `bulkWrite()` #7055 - * docs(aggregate): use `eachAsync()` instead of nonexistent `each()` #7699 - * docs(validation): add CastError validation example #7514 - * docs(query+model): list out all options and callback details for Model.updateX() and Query#updateX() #7646 - -5.5.2 / 2019-04-16 -================== - * fix(document): support setting nested path to non-POJO object #7639 - * perf(connection): remove leaked event handler in `Model.init()` so `deleteModel()` frees all memory #7682 - * fix(timestamps): handle custom statics that conflict with built-in functions (like mongoose-delete plugin) #7698 - * fix(populate): make `Document#populated()` work for populated subdocs #7685 - * fix(document): support `.set()` on document array underneath embedded discriminator path #7656 - -5.5.1 / 2019-04-11 -================== - * fix(document): correctly overwrite all properties when setting a single nested subdoc #7660 #7681 - * fix(array): allow customization of array required validator #7696 [freewil](https://github.com/freewil) - * fix(discriminator): handle embedded discriminators when casting array defaults #7687 - * fix(collection): ensure collection functions return a promise even if disconnected #7676 - * fix(schematype): avoid indexing properties with `{ unique: false, index: false }` #7620 - * fix(aggregate): make `Aggregate#model()` with no arguments return the aggregation's model #7608 - -5.5.0 / 2019-04-08 -================== - * feat(model): support applying hooks to custom static functions #5982 - * feat(populate): support specifying a function as `match` #7397 - * perf(buffer): avoid calling `defineProperties()` in Buffer constructor #7331 - * feat(connection): add `plugin()` for connection-scoped plugins #7378 - * feat(model): add Model#deleteOne() and corresponding hooks #7538 - * feat(query): support hooks for `Query#distinct()` #5938 - * feat(model): print warning when calling create() incorrectly with a session #7535 - * feat(document): add Document#isEmpty() and corresponding helpers for nested paths #5369 - * feat(document): add `getters` option to Document#get() #7233 - * feat(query): add Query#projection() to get or overwrite the current projection #7384 - * fix(document): set full validator path on validatorProperties if `propsParameter` set on validator #7447 - * feat(document): add Document#directModifiedPaths() #7373 - * feat(document): add $locals property #7691 - * feat(document): add validateUpdatedOnly option that only validates modified paths in `save()` #7492 [captaincaius](https://github.com/captaincaius) - * chore: upgrade MongoDB driver to v3.2.0 #7641 - * fix(schematype): deprecate `isAsync` option for custom validators #6700 - * chore(mongoose): deprecate global.MONGOOSE_DRIVER_PATH so we can be webpack-warning-free in 6.0 #7501 - -5.4.23 / 2019-04-08 -=================== - * fix(document): report cast error when string path in schema is an array in MongoDB #7619 - * fix(query): set deletedCount on result of remove() #7629 - * docs(subdocs): add note about parent() and ownerDocument() to subdocument docs #7576 - -5.4.22 / 2019-04-04 -=================== - * fix(aggregate): allow modifying options in pre('aggregate') hook #7606 - * fix(map): correctly init maps of maps when loading from MongoDB #7630 - * docs(model+query): add `omitUndefined` option to docs for updateX() and findOneAndX() #3486 - * docs: removed duplicate Query.prototype.merge() reference from doc #7684 [shihabmridha](https://github.com/shihabmridha) - * docs(schema): fix shardKey type to object instead of bool #7668 [kyletsang](https://github.com/kyletsang) - * docs(api): fix `Model.prototypedelete` link #7665 [pixcai](https://github.com/pixcai) - -5.4.21 / 2019-04-02 -=================== - * fix(updateValidators): run update validators correctly on Decimal128 paths #7561 - * fix(update): cast array filters in nested doc arrays correctly #7603 - * fix(document): allow .get() + .set() with aliased paths #7592 - * fix(document): ensure custom getters on single nested subdocs don't get persisted if toObject.getters = true #7601 - * fix(document): support setting subdoc path to subdoc copied using object rest `{...doc}` #7645 - * docs(schema): correct out-of-date list of reserved words #7593 - * docs(model+query): add link to update results docs and examples of using results of updateOne(), etc. #7582 - * docs: use atomic as opposed to $atomic consistently #7649 [720degreeLotus](https://github.com/720degreeLotus) - -5.4.20 / 2019-03-25 -=================== - * docs(tutorials): add tutorial about `lean()` #7640 - * fix(discriminator): fix wrong modelName being used as value to partialFilterExpression index #7635 #7634 [egorovli](https://github.com/egorovli) - * fix(document): allow setters to modify `this` when overwriting single nested subdoc #7585 - * fix(populate): handle count option correctly with multiple docs #7573 - * fix(date): support declaring min/max validators as functions #7600 [ChienDevIT](https://github.com/ChienDevIT) - * fix(discriminator): avoid projecting in embedded discriminator if only auto-selected path is discriminator key #7574 - * fix(discriminator): use discriminator model when using `new BaseModel()` with discriminator key #7586 - * fix(timestamps): avoid throwing if doc array has timestamps and array is undefined #7625 [serg33v](https://github.com/serg33v) - * docs(document): explain DocumentNotFoundError in save() docs #7580 - * docs(query): fix .all() param type and add example #7612 [720degreeLotus](https://github.com/720degreeLotus) - * docs: add useNewUrlParser to mongoose.connect for some pages #7615 [YC](https://github.com/YC) - -5.4.19 / 2019-03-11 -=================== - * fix(mongoose): ensure virtuals set on subdocs in global plugins get applied #7572 - * docs(tutorials): add "Working With Dates" tutorial #7597 - * docs(guide): clarify that versioning only affects array fields #7555 - * docs(model): list out all bulkWrite() options #7550 - -5.4.18 / 2019-03-08 -=================== - * fix(document): handle nested virtuals in populated docs when parent path is projected out #7491 - * fix(model): make subclassed models handle discriminators correctly #7547 - * fix(model): remove $versionError from save options for better debug output #7570 - -5.4.17 / 2019-03-03 -=================== - * fix(update): handle all positional operator when casting array filters #7540 - * fix(populate): handle populating nested path where top-level path is a primitive in the db #7545 - * fix(update): run update validators on array filters #7536 - * fix(document): clean modified subpaths when sorting an array #7556 - * fix(model): cast $setOnInsert correctly with nested docs #7534 - * docs: remove extra curly brace from example #7569 [kolya182](https://github.com/kolya182) - -5.4.16 / 2019-02-26 -=================== - * fix(schema): handle nested objects with `_id: false` #7524 - * fix(schema): don't throw error if declaring a virtual that starts with a map path name #7464 - * fix(browser): add stubbed `model()` function so code that uses model doesn't throw #7541 [caub](https://github.com/caub) - * fix(schema): merge virtuals correctly #7563 [yoursdearboy](https://github.com/yoursdearboy) - * docs(connections): add reconnectFailed to connection docs #7477 - * docs(index): fix typo #7553 [DenrizSusam](https://github.com/DenrizSusam) - * refactor(schema): iterate over paths instead of depending on childSchemas #7554 - -5.4.15 / 2019-02-22 -=================== - * fix(update): don't call schematype validators on array if using $pull with runValidators #6971 - * fix(schema): clone all schema types when cloning an array #7537 - * docs(connections): improve connectTimeoutMS docs and socketTimeoutMS docs to link to Node.js net.setTimeout() #5169 - * docs: fix setters example in migration guide #7546 [freewil](https://github.com/freewil) - -5.4.14 / 2019-02-19 -=================== - * fix(populate): make `getters` option handle nested paths #7521 - * fix(documentarray): report validation errors that occur in an array subdoc created using `create()` and then `set()` #7504 - * docs(schema): add examples for schema functions that didn't have any #7525 - * docs: add MongooseError to API docs and add list of error names - * docs(CONTRIBUTING): fix link #7530 [sarpik](https://github.com/sarpik) - -5.4.13 / 2019-02-15 -=================== - * fix(query): throw handy error when using updateOne() with overwrite: true and no dollar keys #7475 - * fix(schema): support inheriting existing schema types using Node.js `util.inherits` like mongoose-float #7486 - * docs(connections): add list of connection events #7477 - -5.4.12 / 2019-02-13 -=================== - * fix(connection): dont emit reconnected due to socketTimeoutMS #7452 - * fix(schema): revert check for `false` schema paths #7516 #7512 - * fix(model): don't delete unaliased keys in translateAliases #7510 [chrischen](https://github.com/chrischen) - * fix(document): run single nested schematype validator if nested path has a default and subpath is modified #7493 - * fix(query): copy mongoose options when using `Query#merge()` #1790 - * fix(timestamps): don't call createdAt getters when setting updatedAt on new doc #7496 - * docs: improve description of ValidationError #7515 [JulioJu](https://github.com/JulioJu) - * docs: add an asterisk before comment, otherwise the comment line is not generated #7513 [JulioJu](https://github.com/JulioJu) - -5.4.11 / 2019-02-09 -=================== - * fix(schema): handle `_id: false` in schema paths as a shortcut for setting the `_id` option to `false` #7480 - * fix(update): handle $addToSet and $push with ObjectIds and castNonArrays=false #7479 - * docs(model): document `session` option to `save()` #7484 - * chore: fix gitignore syntax #7498 [JulioJu](https://github.com/JulioJu) - * docs: document that Document#validateSync returns ValidationError #7499 - * refactor: use consolidated `isPOJO()` function instead of constructor checks #7500 - -5.4.10 / 2019-02-05 -=================== - * docs: add search bar and /search page #6706 - * fix: support dotted aliases #7478 [chrischen](https://github.com/chrischen) - * fix(document): copy atomics when setting document array to an existing document array #7472 - * chore: upgrade to mongodb driver 3.1.13 #7488 - * docs: remove confusing references to executing a query "immediately" #7461 - * docs(guides+schematypes): link to custom schematypes docs #7407 - -5.4.9 / 2019-02-01 -================== - * fix(document): make `remove()`, `updateOne()`, and `update()` use the document's associated session #7455 - * fix(document): support passing args to hooked custom methods #7456 - * fix(document): avoid double calling single nested getters on `toObject()` #7442 - * fix(discriminator): handle global plugins modifying top-level discriminator options with applyPluginsToDiscriminators: true #7458 - * docs(documents): improve explanation of documents and use more modern syntax #7463 - * docs(middleware+api): fix a couple typos in examples #7474 [arniu](https://github.com/arniu) - -5.4.8 / 2019-01-30 -================== - * fix(query): fix unhandled error when casting object in array filters #7431 - * fix(query): cast query $elemMatch to discriminator schema if discriminator key set #7449 - * docs: add table of contents to all guides #7430 - -5.4.7 / 2019-01-26 -================== - * fix(populate): set `populated()` when using virtual populate #7440 - * fix(discriminator): defer applying plugins to embedded discriminators until model compilation so global plugins work #7435 - * fix(schema): report correct pathtype underneath map so setting dotted paths underneath maps works #7448 - * fix: get debug from options using the get helper #7451 #7446 [LucGranato](https://github.com/LucGranato) - * fix: use correct variable name #7443 [esben-semmle](https://github.com/esben-semmle) - * docs: fix broken QueryCursor link #7438 [shihabmridha](https://github.com/shihabmridha) - -5.4.6 / 2019-01-22 -================== - * fix(utils): make minimize leave empty objects in arrays instead of setting the array element to undefined #7322 - * fix(document): support passing `{document, query}` options to Schema#pre(regex) and Schema#post(regex) #7423 - * docs: add migrating to 5 guide to docs #7434 - * docs(deprecations): add instructions for fixing `count()` deprecation #7419 - * docs(middleware): add description and example for aggregate hooks #7402 - -4.13.18 / 2019-01-21 -==================== - * fix(model): handle setting populated path set via `Document#populate()` #7302 - * fix(cast): backport fix from #7290 to 4.x - -5.4.5 / 2019-01-18 -================== - * fix(populate): handle nested array `foreignField` with virtual populate #7374 - * fix(query): support not passing any arguments to `orFail()` #7409 - * docs(query): document what the resolved value for `deleteOne()`, `deleteMany()`, and `remove()` contains #7324 - * fix(array): allow opting out of converting non-arrays into arrays with `castNonArrays` option #7371 - * fix(query): ensure updateOne() doesnt unintentionally double call Schema#post(regexp) #7418 - -5.4.4 / 2019-01-14 -================== - * fix(query): run casting on arrayFilters option #7079 - * fix(document): support skipping timestamps on save() with `save({ timestamps: false })` #7357 - * fix(model): apply custom where on `Document#remove()` so we attach the shardKey #7393 - * docs(mongoose): document `mongoose.connections` #7338 - -5.4.3 / 2019-01-09 -================== - * fix(populate): handle `count` option when using `Document#populate()` on a virtual #7380 - * fix(connection): set connection state to DISCONNECTED if replica set has no primary #7330 - * fix(mongoose): apply global plugins to schemas nested underneath embedded discriminators #7370 - * fix(document): make modifiedPaths() return nested paths 1 level down on initial set #7313 - * fix(plugins): ensure sharding plugin works even if ObjectId has a `valueOf()` #7353 - -5.4.2 / 2019-01-03 -================== - * fix(document): ensure Document#updateOne() returns a query but still calls hooks #7366 - * fix(query): allow explicitly projecting out populated paths that are automatically projected in #7383 - * fix(document): support setting `flattenMaps` option for `toObject()` and `toJSON()` at schema level #7274 - * fix(query): handle merging objectids with `.where()` #7360 - * fix(schema): copy `.base` when cloning #7377 - * docs: remove links to plugins.mongoosejs.com in favor of plugins.mongoosejs.io #7364 - -5.4.1 / 2018-12-26 -================== - * fix(document): ensure doc array defaults get casted #7337 - * fix(document): make `save()` not crash if nested doc has a property 'get' #7316 - * fix(schema): allow using Schema.Types.Map as well as Map to declare a map type #7305 - * fix(map): make set after init mark correct path as modified #7321 - * fix(mongoose): don't recompile model if same collection and schema passed in to `mongoose.model()` #5767 - * fix(schema): improve error message when type is invalid #7303 - * fix(schema): add `populated` to reserved property names #7317 - * fix(model): don't run built-in middleware on custom methods and ensure timestamp hooks don't run if children don't have timestamps set #7342 - * docs(schematypes): clarify that you can add arbitrary options to a SchemaType #7340 - * docs(mongoose): clarify that passing same name+schema to `mongoose.model()` returns the model #5767 - * docs(index): add useNewUrlParser to example #7368 [JIBIN-P](https://github.com/JIBIN-P) - * docs(connection): add useNewUrlParser to examples #7362 [JIBIN-P](https://github.com/JIBIN-P) - * docs(discriminators): add back missing example from 'recursive embedded discriminators section' #7349 - * docs(schema): improve docs for string and boolean cast() #7351 - -5.4.0 / 2018-12-14 -================== - * feat(schematype): add `SchemaType.get()`, custom getters across all instances of a schematype #6912 - * feat(schematype): add `SchemaType.cast()`, configure casting for individual schematypes #7045 - * feat(schematype): add `SchemaType.checkRequired()`, configure what values pass `required` check for a schematype #7186 #7150 - * feat(model): add `Model.findOneAndReplace()` #7162 - * feat(model): add `Model.events` emitter that emits all `error`'s that occur with a given model #7125 - * feat(populate): add `count` option to populate virtuals, support returning # of populated docs instead of docs themselves #4469 - * feat(aggregate): add `.catch()` helper to make aggregations full thenables #7267 - * feat(query): add hooks for `deleteOne()` and `deleteMany()` #7195 - * feat(document): add hooks for `updateOne()` #7133 - * feat(query): add `Query#map()` for synchronously transforming results before post middleware runs #7142 - * feat(schema): support passing an array of objects or schemas to `Schema` constructor #7218 - * feat(populate): add `clone` option to ensure multiple docs don't share the same populated doc #3258 - * feat(query): add `Query#maxTimeMS()` helper #7254 - * fix(query): deprecate broken `Aggregate#addCursorFlag()` #7120 - * docs(populate): fix incorrect example #7335 [zcfan](https://github.com/zcfan) - * docs(middleware): add `findOneAndDelete` to middleware list #7327 [danielkesselberg](https://github.com/danielkesselberg) - -5.3.16 / 2018-12-11 -=================== - * fix(document): handle `__proto__` in queries #7290 - * fix(document): use Array.isArray() instead of checking constructor name for arrays #7290 - * docs(populate): add section about what happens when no document matches #7279 - * fix(mongoose): avoid crash on `import mongoose, {Schema} from 'mongoose'` #5648 - -5.3.15 / 2018-12-05 -=================== - * fix(query): handle `orFail()` with `findOneAndUpdate()` and `findOneAndDelete()` #7297 #7280 - * fix(document): make `save()` succeed if strict: false with a `collection` property #7276 - * fix(document): add `flattenMaps` option for toObject() #7274 - * docs(document): document flattenMaps option #7274 - * fix(populate): support populating individual subdoc path in document array #7273 - * fix(populate): ensure `model` option overrides `refPath` #7273 - * fix(map): don't call subdoc setters on init #7272 - * fix(document): use internal get() helper instead of lodash.get to support `null` projection param #7271 - * fix(document): continue running validateSync() for all elements in doc array after first error #6746 - -5.3.14 / 2018-11-27 -=================== - * docs(api): use `openUri()` instead of legacy `open()` #7277 [artemjackson](https://github.com/artemjackson) - * fix(document): don't mark date underneath single nested as modified if setting to string #7264 - * fix(update): set timestamps on subdocs if not using $set with no overwrite #7261 - * fix(document): use symbol instead of `__parent` so user code doesn't conflict #7230 - * fix(mongoose): allow using `mongoose.model()` without context, like `import {model} from 'mongoose'` #3768 - -5.3.13 / 2018-11-20 -=================== - * fix: bump mongodb driver -> 3.1.10 #7266 - * fix(populate): support setting a model as a `ref` #7253 - * docs(schematype): add ref() function to document what is a valid `ref` path in a schematype #7253 - * fix(array): clean modified subpaths when calling `splice()` #7249 - * docs(compatibility): don't show Mongoose 4.11 as compatible with MongoDB 3.6 re: MongoDB's official compatibility table #7248 [a-harrison](https://github.com/a-harrison) - * fix(document): report correct validation error if doc array set to primitive #7242 - * fix(mongoose): print warning when including server-side lib with jest jsdom environment #7240 - -5.3.12 / 2018-11-13 -=================== - * docs(compatibility): don't show Mongoose 4.11 as compatible with MongoDB 3.6 re: MongoDB's official compatibility table #7238 [a-harrison](https://github.com/a-harrison) - * fix(populate): use `instanceof` rather than class name for comparison #7237 [ivanseidel](https://github.com/ivanseidel) - * docs(api): make options show up as a nested list #7232 - * fix(document): don't mark array as modified on init if doc array has default #7227 - * docs(api): link to bulk write result object in `bulkWrite()` docs #7225 - -5.3.11 / 2018-11-09 -=================== - * fix(model): make parent pointers non-enumerable so they don't crash JSON.stringify() #7220 - * fix(document): allow saving docs with nested props with '.' using `checkKeys: false` #7144 - * docs(lambda): use async/await with lambda example #7019 - -5.3.10 / 2018-11-06 -=================== - * fix(discriminator): support reusing a schema for multiple discriminators #7200 - * fix(cursor): handle `lean(false)` correctly with query cursors #7197 - * fix(document): avoid manual populate if `ref` not set #7193 - * fix(schema): handle schema without `.base` for browser build #7170 - * docs: add further reading section - -5.3.9 / 2018-11-02 -================== - * fix: upgrade bson dep -> 1.1.0 to match mongodb-core #7213 [NewEraCracker](https://github.com/NewEraCracker) - * docs(api): fix broken anchor link #7210 [gfranco93](https://github.com/gfranco93) - * fix: don't set parent timestamps because a child has timestamps set to false #7203 #7202 [lineus](https://github.com/lineus) - * fix(document): run setter only once when doing `.set()` underneath a single nested subdoc #7196 - * fix(document): surface errors in subdoc pre validate #7187 - * fix(query): run default functions after hydrating the loaded document #7182 - * fix(query): handle strictQuery: 'throw' with nested path correctly #7178 - * fix(update): update timestamps on replaceOne() #7152 - * docs(transactions): add example of aborting a transaction #7113 - -5.3.8 / 2018-10-30 -================== - * fix: bump mongodb driver -> 3.1.8 to fix connecting to +srv uri with no credentials #7191 #6881 [lineus](https://github.com/lineus) - * fix(document): sets defaults correctly in child docs with projection #7159 - * fix(mongoose): handle setting custom type on a separate mongoose global #7158 - * fix: add unnecessary files to npmignore #7157 - * fix(model): set session when creating new subdoc #7104 - -5.3.7 / 2018-10-26 -================== - * fix(browser): fix buffer usage in browser build #7184 #7173 [lineus](https://github.com/lineus) - * fix(document): make depopulate() work on populate virtuals and unpopulated docs #7180 #6075 [lineus](https://github.com/lineus) - * fix(document): only pass properties as 2nd arg to custom validator if `propsParameter` set #7145 - * docs(schematypes): add note about nested paths with `type` getting converted to mixed #7143 - * fix(update): run update validators on nested doc when $set on an array #7135 - * fix(update): copy exact errors from array subdoc validation into top-level update validator error #7135 - -5.3.6 / 2018-10-23 -================== - * fix(cursor): fix undefined transforms error - -5.3.5 / 2018-10-22 -================== - * fix(model): make sure versionKey on `replaceOne()` always gets set at top level to prevent cast errors #7138 - * fix(cursor): handle non-boolean lean option in `eachAsync()` #7137 - * fix(update): correct cast update that overwrites a map #7111 - * fix(schema): handle arrays of mixed correctly #7109 - * fix(query): use correct path when getting schema for child timestamp update #7106 - * fix(document): make `$session()` propagate sessions to child docs #7104 - * fix(document): handle user setting `schema.options.strict = 'throw'` #7103 - * fix(types): use core Node.js buffer prototype instead of safe-buffer because safe-buffer is broken for Node.js 4.x #7102 - * fix(document): handle setting single doc with refPath to document #7070 - * fix(model): handle array filters when updating timestamps for subdocs #7032 - -5.3.4 / 2018-10-15 -================== - * fix(schema): make `add()` and `remove()` return the schema instance #7131 [lineus](https://github.com/lineus) - * fix(query): don't require passing model to `cast()` #7118 - * fix: support `useFindAndModify` as a connection-level option #7110 [lineus](https://github.com/lineus) - * fix(populate): handle plus path projection with virtual populate #7050 - * fix(schema): allow using ObjectId type as schema path type #7049 - * docs(schematypes): elaborate on how schematypes relate to types #7049 - * docs(deprecations): add note about gridstore deprecation #6922 - * docs(guide): add storeSubdocValidationError option to guide #6802 - -5.3.3 / 2018-10-12 -================== - * fix(document): enable storing mongoose validation error in MongoDB by removing `$isValidatorError` property #7127 - * docs(api): clarify that aggregate triggers aggregate middleware #7126 [lineus](https://github.com/lineus) - * fix(connection): handle Model.init() when an index exists on schema + autoCreate == true #7122 [jesstelford](https://github.com/jesstelford) - * docs(middleware): explain how to switch between document and query hooks for `remove()` #7093 - * docs(api): clean up encoding issues in SchemaType.prototype.validate docs #7091 - * docs(schema): add schema types to api docs and update links on schematypes page #7080 #7076 [lineus](https://github.com/lineus) - * docs(model): expand model constructor docs with examples and `fields` param #7077 - * docs(aggregate): remove incorrect description of noCursorTimeout and add description of aggregate options #7056 - * docs: re-add array type to API docs #7027 - * docs(connections): add note about `members.host` errors due to bad host names in replica set #7006 - -5.3.2 / 2018-10-07 -================== - * fix(query): make sure to return correct result from `orFail()` #7101 #7099 [gsandorx](https://github.com/gsandorx) - * fix(schema): handle `{ timestamps: false }` correctly #7088 #7074 [lineus](https://github.com/lineus) - * docs: fix markdown in options.useCreateIndex documentation #7085 [Cyral](https://github.com/Cyral) - * docs(schema): correct field name in timestamps example #7082 [kizmo04](https://github.com/kizmo04) - * docs(migrating_to_5): correct markdown syntax #7078 [gwuah](https://github.com/gwuah) - * fix(connection): add useFindAndModify option in connect #7059 [NormanPerrin](https://github.com/NormanPerrin) - * fix(document): dont mark single nested path as modified if setting to the same value #7048 - * fix(populate): use WeakMap to track lean populate models rather than leanPopulateSymbol #7026 - * fix(mongoose): avoid unhandled rejection when `mongoose.connect()` errors with a callback #6997 - * fix(mongoose): isolate Schema.Types between custom Mongoose instances #6933 - -5.3.1 / 2018-10-02 -================== - * fix(ChangeStream): expose driver's `close()` function #7068 #7022 [lineus](https://github.com/lineus) - * fix(model): avoid printing warning if `_id` index is set to "hashed" #7053 - * fix(populate): handle nested populate underneath lean array correctly #7052 - * fix(update): make timestamps not crash on a null or undefined update #7041 - * docs(schematypes+validation): clean up links from validation docs to schematypes docs #7040 - * fix(model): apply timestamps to nested docs in bulkWrite() #7032 - * docs(populate): rewrite refPath docs to be simpler and more direct #7013 - * docs(faq): explain why destructuring imports are not supported in FAQ #7009 - -5.3.0 / 2018-09-28 -================== - * feat(mongoose): support `mongoose.set('debug', WritableStream)` so you can pipe debug to stderr, file, or network #7018 - * feat(query): add useNestedStrict option #6973 #5144 [lineus](https://github.com/lineus) - * feat(query): add getPopulatedPaths helper to Query.prototype #6970 #6677 [lineus](https://github.com/lineus) - * feat(model): add `createCollection()` helper to make transactions easier #6948 #6711 [Fonger](https://github.com/Fonger) - * feat(schema): add ability to do `schema.add(otherSchema)` to merge hooks, virtuals, etc. #6897 - * feat(query): add `orFail()` helper that throws an error if no documents match `filter` #6841 - * feat(mongoose): support global toObject and toJSON #6815 - * feat(connection): add deleteModel() to remove a model from a connection #6813 - * feat(mongoose): add top-level mongoose.ObjectId, mongoose.Decimal128 for easier schema declarations #6760 - * feat(aggregate+query): support for/await/of (async iterators) #6737 - * feat(mongoose): add global `now()` function that you can stub for testing timestamps #6728 - * feat(schema): support `schema.pre(RegExp, fn)` and `schema.post(RegExp, fn)` #6680 - * docs(query): add better docs for the `mongooseOptions()` function #6677 - * feat(mongoose): add support for global strict object #6858 - * feat(schema+mongoose): add autoCreate option to automatically create collections #6489 - * feat(update): update timestamps on nested subdocs when using `$set` #4412 - * feat(query+schema): add query `remove` hook and ability to switch between query `remove` and document `remove` middleware #3054 - -5.2.18 / 2018-09-27 -=================== - * docs(migrating_to_5): add note about overwriting filter properties #7030 - * fix(query): correctly handle `select('+c')` if c is not in schema #7017 - * fix(document): check path exists before checking for required #6974 - * fix(document): retain user-defined key order on initial set with nested docs #6944 - * fix(populate): handle multiple localFields + foreignFields using `localField: function() {}` syntax #5704 - -5.2.17 / 2018-09-21 -=================== - * docs(guide): clarify that Mongoose only increments versionKey on `save()` and add a workaround for `findOneAndUpdate()` #7038 - * fix(model): correctly handle `createIndex` option to `ensureIndexes()` #7036 #6922 [lineus](https://github.com/lineus) - * docs(migrating_to_5): add a note about changing debug output from stderr to stdout #7034 #7018 [lineus](https://github.com/lineus) - * fix(query): add `setUpdate()` to allow overwriting update without changing op #7024 #7012 [lineus](https://github.com/lineus) - * fix(update): find top-level version key even if there are `$` operators in the update #7003 - * docs(model+query): explain which operators `count()` supports that `countDocuments()` doesn't #6911 - -5.2.16 / 2018-09-19 -=================== - * fix(index): use dynamic require only when needed for better webpack support #7014 #7010 [jaydp17](https://github.com/jaydp17) - * fix(map): handle arrays of mixed maps #6995 - * fix(populate): leave justOne as null if populating underneath a Mixed type #6985 - * fix(populate): add justOne option to allow overriding any bugs with justOne #6985 - * fix(query): add option to skip adding timestamps to an update #6980 - * docs(model+schematype): improve docs about background indexes and init() #6966 - * fix: bump mongodb -> 3.1.6 to allow connecting to srv url without credentials #6955 #6881 [lineus](https://github.com/lineus) - * fix(connection): allow specifying `useCreateIndex` at the connection level, overrides global-level #6922 - * fix(schema): throw a helpful error if setting `ref` to an invalid value #6915 - -5.2.15 / 2018-09-15 -=================== - * fix(populate): handle virtual justOne correctly if it isn't set #6988 - * fix(populate): consistently use lowercase `model` instead of `Model` so double-populating works with existing docs #6978 - * fix(model): allow calling `Model.init()` again after calling `dropDatabase()` #6967 - * fix(populate): find correct justOne when double-populating underneath an array #6798 - * docs(webpack): make webpack docs use es2015 preset for correct libs and use acorn to test output is valid ES5 #6740 - * fix(populate): add selectPopulatedPaths option to opt out of auto-adding `populate()`-ed fields to `select()` #6546 - * fix(model): set timestamps on bulkWrite `insertOne` and `replaceOne` #5708 - -5.2.14 / 2018-09-09 -=================== - * docs: fix wording on promise docs to not imply queries only return promises #6983 #6982 [lineus](https://github.com/lineus) - * fix(map): throw TypeError if keys are not string #6956 - * fix(document): ensure you can `validate()` a child doc #6931 - * fix(populate): avoid cast error if refPath points to localFields with 2 different types #6870 - * fix(populate): handle populating already-populated paths #6839 - * fix(schematype): make ObjectIds handle refPaths when checking required #6714 - * fix(model): set timestamps on bulkWrite() updates #5708 - -5.2.13 / 2018-09-04 -=================== - * fix(map): throw TypeError if keys are not string #6968 [Fonger](https://github.com/Fonger) - * fix(update): make array op casting work with strict:false and {} #6962 #6952 [lineus](https://github.com/lineus) - * fix(document): add doc.deleteOne(), doc.updateOne(), doc.replaceOne() re: deprecation warnings #6959 #6940 [lineus](https://github.com/lineus) - * docs(faq+schematypes): add note about map keys needing to be strings #6957 #6956 [lineus](https://github.com/lineus) - * fix(schematype): remove unused if statement #6950 #6949 [cacothi](https://github.com/cacothi) - * docs: add /docs/deprecations.html for dealing with MongoDB driver deprecation warnings #6922 - * fix(populate): handle refPath where first element in array has no refPath #6913 - * fix(mongoose): allow setting useCreateIndex option after creating a model but before initial connection succeeds #6890 - * fix(updateValidators): ensure $pull validators always get an array #6889 - -5.2.12 / 2018-08-30 -=================== - * fix(document): disallow setting `constructor` and `prototype` if strict mode false - -4.13.17 / 2018-08-30 -==================== - * fix(document): disallow setting `constructor` and `prototype` if strict mode false - -5.2.11 / 2018-08-30 -=================== - * fix(document): disallow setting __proto__ if strict mode false - * fix(document): run document middleware on docs embedded in maps #6945 #6938 [Fonger](https://github.com/Fonger) - * fix(query): make castForQuery return a CastError #6943 #6927 [lineus](https://github.com/lineus) - * fix(query): use correct `this` scope when casting query with legacy 2dsphere pairs defined in schema #6939 #6937 [Fonger](https://github.com/Fonger) - * fix(document): avoid crash when calling `get()` on deeply nested subdocs #6929 #6925 [jakemccloskey](https://github.com/jakemccloskey) - * fix(plugins): make saveSubdocs execute child post save hooks _after_ the actual save #6926 - * docs: add dbName to api docs for .connect() #6923 [p722](https://github.com/p722) - * fix(populate): convert to array when schema specifies array, even if doc doesn't have an array #6908 - * fix(populate): handle `justOne` virtual populate underneath array #6867 - * fix(model): dont set versionKey on upsert if it is already `$set` #5973 - -4.13.16 / 2018-08-30 -==================== - * fix(document): disallow setting __proto__ if strict mode false - * feat(error): backport adding modified paths to VersionError #6928 [freewil](https://github.com/freewil) - -5.2.10 / 2018-08-27 -=================== - * fix: bump mongodb driver -> 3.1.4 #6920 #6903 #6884 #6799 #6741 [Fonger](https://github.com/Fonger) - * fix(model): track `session` option for `save()` as the document's `$session()` #6909 - * fix(query): add Query.getOptions() helper #6907 [Fonger](https://github.com/Fonger) - * fix(document): ensure array atomics get cleared after save() #6900 - * fix(aggregate): add missing redact and readConcern helpers #6895 [Fonger](https://github.com/Fonger) - * fix: add global option `mongoose.set('useCreateIndex', true)` to avoid ensureIndex deprecation warning #6890 - * fix(query): use `projection` option to avoid deprecation warnings #6888 #6880 [Fonger](https://github.com/Fonger) - * fix(query): use `findOneAndReplace()` internally if using `overwrite: true` with `findOneAndUpdate()` #6888 [Fonger](https://github.com/Fonger) - * fix(document): ensure required cache gets cleared correctly between subsequent saves #6892 - * fix(aggregate): support session chaining correctly #6886 #6885 [Fonger](https://github.com/Fonger) - * fix(query): use `projection` instead of `fields` internally for `find()` and `findOne()` to avoid deprecation warning #6880 - * fix(populate): add `getters` option to opt in to calling getters on populate #6844 - -5.2.9 / 2018-08-17 -================== - * fix(document): correctly propagate write concern options in save() #6877 [Fonger](https://github.com/Fonger) - * fix: upgrade mongodb driver -> 3.1.3 for numerous fixes #6869 #6843 #6692 #6670 [simllll](https://github.com/simllll) - * fix: correct `this` scope of default functions for DocumentArray and Array #6868 #6840 [Fonger](https://github.com/Fonger) - * fix(types): support casting JSON form of buffers #6866 #6863 [Fonger](https://github.com/Fonger) - * fix(query): get global runValidators option correctly #6865 #6578 - * fix(query): add Query.prototype.setQuery() analogous to `getQuery()` #6855 #6854 - * docs(connections): add note about the `family` option for IPv4 vs IPv6 and add port to example URIs #6784 - * fix(query): get global runValidators option correctly #6578 - -4.13.15 / 2018-08-14 -==================== - * fix(mongoose): add global `usePushEach` option for easier Mongoose 4.x + MongoDB 3.6 #6858 - * chore: fix flakey tests for 4.x #6853 [Fonger](https://github.com/Fonger) - * feat(error): add version number to VersionError #6852 [freewil](https://github.com/freewil) - -5.2.8 / 2018-08-13 -================== - * docs: update `execPopulate()` code example #6851 [WJakub](https://github.com/WJakub) - * fix(document): allow passing callback to `execPopulate()` #6851 - * fix(populate): populate with undefined fields without error #6848 #6845 [Fonger](https://github.com/Fonger) - * docs(migrating_to_5): Add `objectIdGetter` option docs #6842 [jwalton](https://github.com/jwalton) - * chore: run lint in parallel and only on Node.js v10 #6836 [Fonger](https://github.com/Fonger) - * fix(populate): throw helpful error if refPath excluded in query #6834 - * docs(migrating_to_5): add note about removing runSettersOnQuery #6832 - * fix: use safe-buffer to avoid buffer deprecation errors in Node.js 10 #6829 [Fonger](https://github.com/Fonger) - * docs(query): fix broken links #6828 [yaynick](https://github.com/yaynick) - * docs(defaults): clarify that defaults only run on undefined #6827 - * chore: fix flakey tests #6824 [Fonger](https://github.com/Fonger) - * docs: fix custom inspect function deprecation warning in Node.js 10 #6821 [yelworc](https://github.com/yelworc) - * fix(document): ensure subdocs get set to init state after save() so validators can run again #6818 - * fix(query): make sure embedded query casting always throws a CastError #6803 - * fix(document): ensure `required` function only gets called once when validating #6801 - * docs(connections): note that you must specify port if using `useNewUrlParser: true` #6789 - * fix(populate): support `options.match` in virtual populate schema definition #6787 - * fix(update): strip out virtuals from updates if strict: 'throw' rather than returning an error #6731 - -5.2.7 / 2018-08-06 -================== - * fix(model): check `expireAfterSeconds` option when diffing indexes in syncIndexes() #6820 #6819 [christopherhex](https://github.com/christopherhex) - * chore: fix some common test flakes in travis #6816 [Fonger](https://github.com/Fonger) - * chore: bump eslint and webpack to avoid bad versions of eslint-scope #6814 - * test(model): add delay to session tests to improve pass rate #6811 [Fonger](https://github.com/Fonger) - * fix(model): support options in `deleteMany` #6810 [Fonger](https://github.com/Fonger) - * fix(query): don't use $each when pushing an array into an array #6809 [lineus](https://github.com/lineus) - * chore: bump mquery so eslint isn't a prod dependency #6800 - * fix(populate): correctly get schema type when calling `populate()` on already populated path #6798 - * fix(populate): propagate readConcern options in populate from parent query #6792 #6785 [Fonger](https://github.com/Fonger) - * docs(connection): add description of useNewUrlParser option #6789 - * fix(query): make select('+path') a no-op if no select prop in schema #6785 - * docs(schematype+validation): document using function syntax for custom validator message #6772 - * fix(update): throw CastError if updating with `$inc: null` #6770 - * fix(connection): throw helpful error when calling `createConnection(undefined)` #6763 - -5.2.6 / 2018-07-30 -================== - * fix(document): don't double-call deeply nested custom getters when using `get()` #6779 #6637 - * fix(query): upgrade mquery for readConcern() helper #6777 - * docs(schematypes): clean up typos #6773 [sajadtorkamani](https://github.com/sajadtorkamani) - * refactor(browser): fix webpack warnings #6771 #6705 - * fix(populate): make error reported when no `localField` specified catchable #6767 - * docs(connection): use correct form in createConnection example #6766 [lineus](https://github.com/lineus) - * fix(connection): throw helpful error when using legacy `mongoose.connect()` syntax #6756 - * fix(document): handle overwriting `$session` in `execPopulate()` #6754 - * fix(query): propagate top-level session down to `populate()` #6754 - * fix(aggregate): add `session()` helper for consistency with query api #6752 - * fix(map): avoid infinite recursion when update overwrites a map #6750 - * fix(model): be consistent about passing noop callback to mongoose.model() `init()` as well as db.model() #6707 - -5.2.5 / 2018-07-23 -================== - * fix(boolean): expose `convertToTrue` and `convertToFalse` for custom boolean casting #6758 - * docs(schematypes): add note about what values are converted to booleans #6758 - * fix(document): fix(document): report castError when setting single nested doc to array #6753 - * docs: prefix mongoose.Schema call with new operator #6751 [sajadtorkamani](https://github.com/sajadtorkamani) - * docs(query): add examples and links to schema writeConcern option for writeConcern helpers #6748 - * docs(middleware): clarify that init middleware is sync #6747 - * perf(model): create error rather than modifying stack for source map perf #6735 - * fix(model): throw helpful error when passing object to aggregate() #6732 - * fix(model): pass Model instance as context to applyGetters when calling getters for virtual populate #6726 [lineus](https://github.com/lineus) - * fix(documentarray): remove `isNew` and `save` listeners on CastError because otherwise they never get removed #6723 - * docs(model+query): clarify when to use `countDocuments()` vs `estimatedDocumentCount()` #6713 - * fix(populate): correctly set virtual nestedSchemaPath when calling populate() multiple times #6644 - * docs(connections): add note about the `family` option for IPv4 vs IPv6 and add port to example URIs #6566 - -5.2.4 / 2018-07-16 -================== - * docs: Model.insertMany rawResult option in api docs #6724 [lineus](https://github.com/lineus) - * docs: fix typo on migrating to 5 guide #6722 [iagowp](https://github.com/iagowp) - * docs: update doc about keepalive #6719 #6718 [simllll](https://github.com/simllll) - * fix: ensure debug mode doesn't crash with sessions #6712 - * fix(document): report castError when setting single nested doc to primitive value #6710 - * fix(connection): throw helpful error if using `new db.model(foo)(bar)` #6698 - * fix(model): throw readable error with better stack trace when non-cb passed to $wrapCallback() #6640 - -5.2.3 / 2018-07-11 -================== - * fix(populate): if a getter is defined on the localField, use it when populating #6702 #6618 [lineus](https://github.com/lineus) - * docs(schema): add example of nested aliases #6671 - * fix(query): add `session()` function to queries to avoid positional argument mistakes #6663 - * docs(transactions): use new session() helper to make positional args less confusing #6663 - * fix(query+model+schema): add support for `writeConcern` option and writeConcern helpers #6620 - * docs(guide): add `writeConcern` option and re-add description for `safe` option #6620 - * docs(schema): fix broken API links #6619 - * docs(connections): add information re: socketTimeoutMS and connectTimeoutMS #4789 - -5.2.2 / 2018-07-08 -================== - * fix(model+query): add missing estimatedDocumentCount() function #6697 - * docs(faq): improve array-defaults section #6695 [lineus](https://github.com/lineus) - * docs(model): fix countDocuments() docs, bad copy/paste from count() docs #6694 #6643 - * fix(connection): add `startSession()` helper to connection and mongoose global #6689 - * fix: upgrade mongodb driver -> 3.1.1 for countDocuments() fix #6688 #6666 - * docs(compatibility): add MongoDB 4 range #6685 - * fix(populate): add ability to define refPath as a function #6683 [lineus](https://github.com/lineus) - * docs: add rudimentary transactions guide #6672 - * fix(update): make setDefaultsOnInsert handle nested subdoc updates with deeply nested defaults #6665 - * docs: use latest acquit-ignore to handle examples that start with acquit:ignore:start #6657 - * fix(validation): format `properties.message` as well as `message` #6621 - -5.2.1 / 2018-07-03 -================== - * fix(connection): allow setting the mongodb driver's useNewUrlParser option, default to false #6656 #6648 #6647 - * fix(model): only warn on custom _id index if index only has _id key #6650 - -5.2.0 / 2018-07-02 -================== - * feat(model): add `countDocuments()` #6643 - * feat(model): make ensureIndexes() fail if specifying an index on _id #6605 - * feat(mongoose): add `objectIdGetter` option to remove ObjectId.prototype._id #6588 - * feat: upgrade mongodb -> 3.1.0 for full MongoDB 4.0 support #6579 - * feat(query): support `runValidators` as a global option #6578 - * perf(schema): use WeakMap instead of array for schema stack #6503 - * feat(model): decorate unique discriminator indexes with partialFilterExpressions #6347 - * feat(model): add `syncIndexes()`, drops indexes that aren't in schema #6281 - * feat(document): add default getter/setter if virtual doesn't have one #6262 - * feat(discriminator): support discriminators on nested doc arrays #6202 - * feat(update): add `Query.prototype.set()` #5770 - -5.1.8 / 2018-07-02 -================== - * fix: don't throw TypeError if calling save() after original save() failed with push() #6638 [evanhenke](https://github.com/evanhenke) - * fix(query): add explain() helper and don't hydrate explain output #6625 - * docs(query): fix `setOptions()` lists #6624 - * docs: add geojson docs #6607 - * fix: bump mongodb -> 3.0.11 to avoid cyclic dependency error with retryWrites #6109 - -5.1.7 / 2018-06-26 -================== - * docs: add npm badge to readme #6623 [VFedyk](https://github.com/VFedyk) - * fix(document): don't throw parallel save error if post save hooks in parallel #6614 #6611 [lineus](https://github.com/lineus) - * fix(populate): allow dynamic ref to handle >1 model getModelsMapForPopulate #6613 #6612 [jimmytsao](https://github.com/jimmytsao) - * fix(document): handle `push()` on triple nested document array #6602 - * docs(validation): improve update validator doc headers #6577 [joeytwiddle](https://github.com/joeytwiddle) - * fix(document): handle document arrays in `modifiedPaths()` with includeChildren option #5904 - -5.1.6 / 2018-06-19 -================== - * fix: upgrade mongodb -> 3.0.10 - * docs(model+document): clarify that `save()` returns `undefined` if passed a callback #6604 [lineus](https://github.com/lineus) - * fix(schema): apply alias when adding fields with .add() #6593 - * docs: add full list of guides and streamline nav #6592 - * docs(model): add `projection` option to `findOneAndUpdate()` #6590 [lineus](https://github.com/lineus) - * docs: support @static JSDoc declaration #6584 - * fix(query): use boolean casting logic for $exists #6581 - * fix(query): cast all $text options to correct values #6581 - * fix(model): add support synchronous pre hooks for `createModel` #6552 [profbiss](https://github.com/profbiss) - * docs: add note about the `applyPluginsToDiscriminators` option #4965 - -5.1.5 / 2018-06-11 -================== - * docs(guide): rework query helper example #6575 [lineus](https://github.com/lineus) - * fix(populate): handle virtual populate with embedded discriminator under single nested subdoc #6571 - * docs: add string option to projections that call query select #6563 [lineus](https://github.com/lineus) - * style: use ES6 in collection.js #6560 [l33ds](https://github.com/l33ds) - * fix(populate): add virtual ref function ability getModelsMapForPopulate #6559 #6554 [lineus](https://github.com/lineus) - * docs(queries): fix link #6557 [sun1x](https://github.com/sun1x) - * fix(schema): rename indexes -> getIndexes to avoid webpack duplicate declaration #6547 - * fix(document): support `toString()` as custom method #6538 - * docs: add @instance for instance methods to be more compliant with JSDoc #6516 [treble-snake](https://github.com/treble-snake) - * fix(populate): avoid converting to map when using mongoose-deep-populate #6460 - * docs(browser): create new browser docs page #6061 - -5.1.4 / 2018-06-04 -================== - * docs(faq): add hr tags for parallel save error #6550 [lineus](https://github.com/lineus) - * docs(connection): fix broken link #6545 [iblamefish](https://github.com/iblamefish) - * fix(populate): honor subpopulate options #6539 #6528 [lineus](https://github.com/lineus) - * fix(populate): allow population of refpath under array #6537 #6509 [lineus](https://github.com/lineus) - * fix(query): dont treat $set the same as the other ops in update casting #6535 [lineus](https://github.com/lineus) - * fix: bump async -> 2.6.1 #6534 #6505 [lineus](https://github.com/lineus) - * fix: support using a function as validation error message #6530 [lucandrade](https://github.com/lucandrade) - * fix(populate): propagate `lean()` down to subpopulate #6498 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * docs(lambda): add info on what happens if database does down between lambda function calls #6409 - * fix(update): allow updating embedded discriminator path if discriminator key is in filter #5841 - -5.1.3 / 2018-05-28 -================== - * fix(document): support set() on path underneath array embedded discriminator #6526 - * chore: update lodash and nsp dev dependencies #6514 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix(document): throw readable error when saving the same doc instance more than once in parallel #6511 #6456 #4064 [lineus](https://github.com/lineus) - * fix(populate): set correct nestedSchemaPath for virtual underneath embedded discriminator #6501 #6487 [lineus](https://github.com/lineus) - * docs(query): add section on promises and warning about not mixing promises and callbacks #6495 - * docs(connection): add concrete example of connecting to multiple hosts #6492 [lineus](https://github.com/lineus) - * fix(populate): handle virtual populate under single nested doc under embedded discriminator #6488 - * fix(schema): collect indexes from embedded discriminators for autoIndex build #6485 - * fix(document): handle `doc.set()` underneath embedded discriminator #6482 - * fix(document): handle set() on path under embedded discriminator with object syntax #6482 - * fix(document): handle setting nested property to object with only non-schema properties #6436 - -4.13.14 / 2018-05-25 -==================== - * fix(model): handle retainKeyOrder option in findOneAndUpdate() #6484 - -5.1.2 / 2018-05-21 -================== - * docs(guide): add missing SchemaTypes #6490 [distancesprinter](https://github.com/distancesprinter) - * fix(map): make MongooseMap.toJSON return a serialized object #6486 #6478 [lineus](https://github.com/lineus) - * fix(query): make CustomQuery inherit from model.Query for hooks #6483 #6455 [lineus](https://github.com/lineus) - * fix(document): prevent default falses from being skipped by $__dirty #6481 #6477 [lineus](https://github.com/lineus) - * docs(connection): document `useDb()` #6480 - * fix(model): skip redundant clone in insertMany #6479 [d1manson](https://github.com/d1manson) - * fix(aggregate): let replaceRoot accept objects as well as strings #6475 #6474 [lineus](https://github.com/lineus) - * docs(model): clarify `emit()` in mapReduce and how map/reduce are run #6465 - * fix(populate): flatten array to handle multi-level nested `refPath` #6457 - * fix(date): cast small numeric strings as years #6444 [AbdelrahmanHafez](https://github.com/AbdelrahmanHafez) - * fix(populate): remove unmatched ids when using virtual populate on already hydrated document #6435 - * fix(array): use custom array class to avoid clobbered property names #6431 - * fix(model): handle hooks for custom methods that return promises #6385 - -4.13.13 / 2018-05-17 -==================== - * fix(update): stop clobbering $in when casting update #6441 #6339 - * fix: upgrade async -> 2.6.0 re: security warning - -5.1.1 / 2018-05-14 -================== - * docs(schema): add notes in api and guide about schema.methods object #6470 #6440 [lineus](https://github.com/lineus) - * fix(error): add modified paths to VersionError #6464 #6433 [paglias](https://github.com/paglias) - * fix(populate): only call populate with full param signature when match is not present #6458 #6451 [lineus](https://github.com/lineus) - * docs: fix geoNear link in migration guide #6450 [kawache](https://github.com/kawache) - * fix(discriminator): throw readable error when `create()` with a non-existent discriminator key #6434 - * fix(populate): add `retainNullValues` option to avoid stripping out null keys #6432 - * fix(populate): handle populate in embedded discriminators underneath nested paths #6411 - * docs(model): add change streams and ToC, make terminology more consistent #5888 - -5.1.0 / 2018-05-10 -================== - * feat(ObjectId): add `_id` getter so you can get a usable id whether or not the path is populated #6415 #6115 - * feat(model): add Model.startSession() #6362 - * feat(document): add doc.$session() and set session on doc after query #6362 - * feat: add Map type that supports arbitrary keys #6287 #681 - * feat: add `cloneSchemas` option to mongoose global to opt in to always cloning schemas before use #6274 - * feat(model): add `findOneAndDelete()` and `findByIdAndDelete()` #6164 - * feat(document): support `$ignore()` on single nested and array subdocs #6152 - * feat(document): add warning about calling `save()` on subdocs #6152 - * fix(model): make `save()` use `updateOne()` instead of `update()` #6031 - * feat(error): add version number to VersionError #5966 - * fix(query): allow `[]` as a value for `$in` when casting #5913 - * fix(document): avoid running validators on single nested paths if only a child path is modified #5885 - * feat(schema): print warning if method conflicts with mongoose internals #5860 - -5.0.18 / 2018-05-09 -=================== - * fix(update): stop clobbering $in when casting update #6441 #6339 [lineus](https://github.com/lineus) - * fix: upgrade mongodb driver -> 3.0.8 to fix session issue #6437 #6357 [simllll](https://github.com/simllll) - * fix: upgrade bson -> 1.0.5 re: https://snyk.io/vuln/npm:bson:20180225 #6423 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix: look for `valueOf()` when casting to Decimal128 #6419 #6418 [lineus](https://github.com/lineus) - * fix: populate array of objects with space separated paths #6414 [lineus](https://github.com/lineus) - * test: add coverage for `mongoose.pluralize()` #6412 [FastDeath](https://github.com/FastDeath) - * fix(document): avoid running default functions on init() if path has value #6410 - * fix(document): allow saving document with `null` id #6406 - * fix: prevent casting of populated docs in document.init #6390 [lineus](https://github.com/lineus) - * fix: remove `toHexString()` helper that was added in 5.0.15 #6359 - -5.0.17 / 2018-04-30 -=================== - * docs(migration): certain chars in passwords may cause connection failures #6401 [markstos](https://github.com/markstos) - * fix(document): don't throw when `push()` on a nested doc array #6398 - * fix(model): apply hooks to custom methods if specified #6385 - * fix(schema): support opting out of one timestamp field but not the other for `insertMany()` #6381 - * fix(documentarray): handle `required: true` within documentarray definition #6364 - * fix(document): ensure `isNew` is set before default functions run on init #3793 - -5.0.16 / 2018-04-23 -=================== - * docs(api): sort api methods based on their string property #6374 [lineus](https://github.com/lineus) - * docs(connection): fix typo in `createCollection()` #6370 [mattc41190](https://github.com/mattc41190) - * docs(document): remove vestigial reference to `numAffected` #6367 [ekulabuhov](https://github.com/ekulabuhov) - * docs(schema): fix typo #6366 [dhritzkiv](https://github.com/dhritzkiv) - * docs(schematypes): add missing `minlength` and `maxlength` docs #6365 [treble-snake](https://github.com/treble-snake) - * docs(queries): fix formatting #6360 [treble-snake](https://github.com/treble-snake) - * docs(api): add cursors to API docs #6353 #6344 [lineus](https://github.com/lineus) - * docs(aggregate): remove reference to non-existent `.select()` method #6346 - * fix(update): handle `required` array with update validators and $pull #6341 - * fix(update): avoid setting __v in findOneAndUpdate if it is `$set` #5973 - -5.0.15 / 2018-04-16 -=================== - * fix: add ability for casting from number to decimal128 #6336 #6331 [lineus](https://github.com/lineus) - * docs(middleware): enumerate the ways to error out in a hook #6315 - * fix(document): respect schema-level depopulate option for toObject() #6313 - * fix: bump mongodb driver -> 3.0.6 #6310 - * fix(number): check for `valueOf()` function to support Decimal.js #6306 #6299 [lineus](https://github.com/lineus) - * fix(query): run array setters on query if input value is an array #6277 - * fix(versioning): don't require matching version when using array.pull() #6190 - * fix(document): add `toHexString()` function so you don't need to check whether a path is populated to get an id #6115 - -5.0.14 / 2018-04-09 -=================== - * fix(schema): clone aliases and alternative option syntax correctly - * fix(query): call utils.toObject in query.count like in query.find #6325 [lineus](https://github.com/lineus) - * docs(populate): add middleware examples #6320 [BorntraegerMarc](https://github.com/BorntraegerMarc) - * docs(compatibility): fix dead link #6319 [lacivert](https://github.com/lacivert) - * docs(api): fix markdown parsing for parameters #6318 #6314 [lineus](https://github.com/lineus) - * fix(populate): handle space-delimited paths in array populate #6296 #6284 [lineus](https://github.com/lineus) - * fix(populate): support basic virtual populate underneath embedded discriminators #6273 - -5.0.13 / 2018-04-05 -=================== - * docs(faq): add middleware to faq arrow function warning #6309 [lineus](https://github.com/lineus) - * docs(schema): add example to loadClass() docs #6308 - * docs: clean up misc typos #6304 [sfrieson](https://github.com/sfrieson) - * fix(document): apply virtuals when calling `toJSON()` on a nested path #6294 - * refactor(connection): use `client.db()` syntax rather than double-parsing the URI #6292 #6286 - * docs: document new behavior of required validator for arrays #6288 [daltones](https://github.com/daltones) - * fix(schema): treat set() options as user-provided options #6274 - * fix(schema): clone discriminators correctly #6274 - * fix(update): make setDefaultsOnInsert not create subdoc if only default is id #6269 - * docs(discriminator): clarify 3rd argument to Model.discriminator() #2596 - -5.0.12 / 2018-03-27 -=================== - * docs(query): updating model name in query API docs #6280 [lineus](https://github.com/lineus) - * docs: fix typo in tests #6275 [styler](https://github.com/styler) - * fix: add missing `.hint()` to aggregate #6272 #6251 [lineus](https://github.com/lineus) - * docs(api): add headers to each API docs section for easer nav #6261 - * fix(query): ensure hooked query functions always run on next tick for chaining #6250 - * fix(populate): ensure populated array not set to null if it isn't set #6245 - * fix(connection): set readyState to disconnected if initial connection fails #6244 #6131 - * docs(model): make `create()` params show up correctly in docs #6242 - * fix(model): make error handlers work with MongoDB server errors and `insertMany()` #6228 - * fix(browser): ensure browser document builds defaults for embedded arrays correctly #6175 - * fix(timestamps): set timestamps when using `updateOne()` and `updateMany()` #6282 [gualopezb](https://github.com/gualopezb) - -5.0.11 / 2018-03-19 -=================== - * fix(update): handle $pull with $in in update validators #6240 - * fix(query): don't convert undefined to null when casting so driver `ignoreUndefined` option works #6236 - * docs(middleware): add example of using async/await with middleware #6235 - * fix(populate): apply justOne option before `completeMany()` so it works with lean() #6234 - * fix(query): ensure errors in user callbacks aren't caught in init #6195 #6178 - * docs(connections): document dbName option for Atlas connections #6179 - * fix(discriminator): make child schema nested paths overwrite parent schema paths #6076 - -4.13.12 / 2018-03-13 -==================== - * fix(document): make virtual get() return undefined instead of null if no getters #6223 - * docs: fix url in useMongoClient error message #6219 #6217 [lineus](https://github.com/lineus) - * fix(discriminator): don't copy `discriminators` property from base schema #6122 #6064 - -5.0.10 / 2018-03-12 -=================== - * docs(schematype): add notes re: running setters on queries #6209 - * docs: fix typo #6208 [kamagatos](https://github.com/kamagatos) - * fix(query): only call setters once on query filter props for findOneAndUpdate and findOneAndRemove #6203 - * docs: elaborate on connection string changes in migration guide #6193 - * fix(document): skip applyDefaults if subdoc is null #6187 - * docs: fix schematypes docs and link to them #6176 - * docs(faq): add FAQs re: array defaults and casting aggregation pipelines #6184 #6176 #6170 [lineus](https://github.com/lineus) - * fix(document): ensure primitive defaults are set and built-in default functions run before setters #6155 - * fix(query): handle single embedded embedded discriminators in castForQuery #6027 - -5.0.9 / 2018-03-05 -================== - * perf: bump mongodb -> 3.0.4 to fix SSL perf issue #6065 - -5.0.8 / 2018-03-03 -================== - * docs: remove obsolete references to `emitIndexErrors` #6186 [isaackwan](https://github.com/isaackwan) - * fix(query): don't cast findOne() until exec() so setters don't run twice #6157 - * fix: remove document_provider.web.js file #6186 - * fix(discriminator): support custom discriminator model names #6100 [wentout](https://github.com/wentout) - * fix: support caching calls to `useDb()` #6036 [rocketspacer](https://github.com/rocketspacer) - * fix(query): add omitUndefined option so setDefaultsOnInsert can kick in on undefined #6034 - * fix: upgrade mongodb -> 3.0.3 for reconnectTries: 0 blocking process exit fix #6028 - -5.0.7 / 2018-02-23 -================== - * fix: support eachAsync options with aggregation cursor #6169 #6168 [vichle](https://github.com/vichle) - * docs: fix link to MongoDB compound indexes docs #6162 [br0p0p](https://github.com/br0p0p) - * docs(aggregate): use eachAsync instead of incorrect `each()` #6160 [simllll](https://github.com/simllll) - * chore: fix benchmarks #6158 [pradel](https://github.com/pradel) - * docs: remove dead link to old blog post #6154 [markstos](https://github.com/markstos) - * fix: don't convert dates to numbers when updating mixed path #6146 #6145 [s4rbagamble](https://github.com/s4rbagamble) - * feat(aggregate): add replaceRoot, count, sortByCount helpers #6142 [jakesjews](https://github.com/jakesjews) - * fix(document): add includedChildren flag to modifiedPaths() #6134 - * perf: don't create wrapper function if no hooks specified #6126 - * fix(schema): allow indexes on single nested subdocs for geoJSON #6113 - * fix(document): allow depopulating all fields #6073 - * feat(mongoose): add support for `useFindAndModify` option on singleton #5616 - -5.0.6 / 2018-02-15 -================== - * refactor(query.castUpdate): avoid creating error until necessary #6137 - * docs(api): fix missing api docs #6136 [lineus](https://github.com/lineus) - * fix(schema): copy virtuals when using `clone()` #6133 - * fix(update): avoid digging into buffers with upsert and replaceOne #6124 - * fix(schema): support `enum` on arrays of strings #6102 - * fix(update): cast `$addToSet: [1, 2]` -> `$addToSet: { $each: [1, 2] }` #6086 - -5.0.5 / 2018-02-13 -================== - * docs: make > show up correctly in API docs #6114 - * fix(query): support `where()` overwriting primitive with object #6097 - * fix(schematype): don't run internal `resetId` setter on queries with _id #6093 - * fix(discriminator): don't copy `discriminators` property from base schema #6064 - * fix(utils): respect `valueOf()` when merging object for update #6059 - * docs(validation): fix typo 'maxLength' #4720 - * fix(document): apply defaults after setting initial value so default functions don't see empty doc #3781 - -5.0.4 / 2018-02-08 -================== - * docs: add lambda guide #6107 - * fix(connection): add `dbName` option to work around `mongodb+srv` not supporting db name in URI #6106 - * fix(schematype): fix regexp typo in ObjectId #6098 [JoshuaWise](https://github.com/JoshuaWise) - * perf(document): re-use the modifiedPaths list #6092 [tarun1793](https://github.com/tarun1793) - * fix: use console.info() instead of console.error() for debug output #6088 [yuristsepaniuk](https://github.com/yuristsepaniuk) - * docs(validation): clean up runValidators and isAsync options docs for 5.x #6083 - * docs(model): use array instead of spread consistently for aggregate() #6070 - * fix(schema): make aliases handle mongoose-lean-virtuals #6069 - * docs(layout): add link to subdocs guide #6056 - * fix(query): make strictQuery: true strip out fields that aren't in the schema #6032 - * docs(guide): add notes for `strictQuery` option #6032 - -4.13.11 / 2018-02-07 -==================== - * docs: fix links in 4.x docs #6081 - * chore: add release script that uses --tag for npm publish for 4.x releases #6063 - -5.0.3 / 2018-01-31 -================== - * fix: consistently use process.nextTick() to avoid sinon.useFakeTimers() causing ops to hang #6074 - * docs(aggregate): fix typo #6072 [adursun](https://github.com/adursun) - * chore: add return type to `mongoose.model()` docs [bryant1410](https://github.com/bryant1410) - * fix(document): depopulate push()-ed docs when saving #6048 - * fix: upgrade mongodb -> 3.0.2 #6019 - -5.0.2 / 2018-01-28 -================== - * fix(schema): do not overwrite default values in schema when nested timestamps are provided #6024 [cdeveas](https://github.com/cdeveas) - * docs: fix syntax highlighting in models.jade, schematypes.jade, subdocs.jade #6058 [lineus](https://github.com/lineus) - * fix: use lazy loading so we can build mongoose with webpack #5993 #5842 - * docs(connections): clarify multi-mongos with useMongoClient for 4.x docs #5984 - * fix(populate): handle populating embedded discriminator paths #5970 - -4.13.10 / 2018-01-28 -==================== - * docs(model+query): add lean() option to Model helpers #5996 [aguyinmontreal](https://github.com/aguyinmontreal) - * fix: use lazy loading so we can build mongoose with webpack #5993 #5842 - * docs(connections): clarify multi-mongos with useMongoClient for 4.x docs #5984 - * fix(populate): handle populating embedded discriminator paths #5970 - * docs(query+aggregate): add more detail re: maxTimeMS #4066 - -5.0.1 / 2018-01-19 -================== - * fix(document): make validate() not resolve to document #6014 - * fix(model): make save() not return DocumentNotFoundError if using fire-and-forget writes #6012 - * fix(aggregate): make options() work as advertised #6011 [spederiva](https://github.com/spederiva) - * docs(queries): fix code samples #6008 - -5.0.0 / 2018-01-17 -================== - * test: refactor tests to use start fewer connections #5985 [fenanquin](https://github.com/fenanquin) - * feat: add global bufferCommands option #5879 - * docs: new docs site and build system #5976 - * test: increase timeout on slow test cases #5968 [fenanquin](https://github.com/fenanquin) - * fix: avoid casting out array filter elements #5965 - * feat: add Model.watch() wrapper #5964 - * chore: replace istanbul with nyc #5962 [ChristianMurphy](https://github.com/ChristianMurphy) - -4.13.9 / 2018-01-07 -=================== - * chore: update marked (dev dependency) re: security vulnerability #5951 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix: upgrade mongodb -> 2.2.34 for ipv6 and autoReconnect fixes #5794 #5760 - * docs: use useMongooseAggCursor for aggregate docs #2955 - -5.0.0-rc2 / 2018-01-04 -====================== - * fix: add cleaner warning about no longer needing `useMongoClient` in 5.x #5961 - * chore: update acquit -> 0.5.1 for minor security patch #5961 [ChristianMurphy](https://github.com/ChristianMurphy) - * docs: add docs for mongoose 4.x at http://mongoosejs.com/docs/4.x #5959 - * docs: add link to migration guide #5957 - * chore: update eslint to version 4.14.0 #5955 [ChristianMurphy](https://github.com/ChristianMurphy) - * chore: update mocha to version 4.1.0 [ChristianMurphy](https://github.com/ChristianMurphy) - -5.0.0-rc1 / 2018-01-02 -====================== - * fix(index): use pluralize correctly for `mongoose.model()` #5958 - * fix: make mquery use native promises by default #5945 - * fix(connection): ensure 'joined' and 'left' events get bubbled up #5944 - -5.0.0-rc0 / 2017-12-28 -====================== - * BREAKING CHANGE: always use mongoose aggregation cursor when using `.aggregate().cursor()` #5941 - * BREAKING CHANGE: attach query middleware when compiling model #5939 - * BREAKING CHANGE: `emitIndexErrors` is on by default, failing index build will throw uncaught error if not handled #5910 - * BREAKING CHANGE: remove precompiled browser bundle #5895 - * feat: add `mongoose.pluralize()` function #5877 - * BREAKING CHANGE: remove `passRawResult` option for `findOneAndUpdate`, use `rawResult` #5869 - * BREAKING CHANGE: implicit async validators (based on number of function args) are removed, return a promise instead #5824 - * BREAKING CHANGE: fail fast if user sets a unique index on `_id` #5820 [varunjayaraman](https://github.com/varunjayaraman) - * BREAKING CHANGE: mapReduce resolves to an object with 2 keys rather than 2 separate args #5816 - * BREAKING CHANGE: `mongoose.connect()` returns a promise, removed MongooseThenable #5796 - * BREAKING CHANGE: query stream removed, use `cursor()` instead #5795 - * BREAKING CHANGE: connection `open()` and `openSet()` removed, use `openUri()` instead #5795 - * BREAKING CHANGE: use MongoDB driver 3.0.0, drop support for MongoDB server < 3.0.0 #5791 #4740 - * BREAKING CHANGE: remove support for `$pushAll`, remove `usePushEach` option #5670 - * BREAKING CHANGE: make date casting use native Date #5395 [varunjayaraman](https://github.com/varunjayaraman) - * BREAKING CHANGE: remove `runSettersOnQuery`, always run setters on query #5340 - * BREAKING CHANGE: array of length 0 now satisfies `required: true` for arays #5139 [wlingke](https://github.com/wlingke) - * BREAKING CHANGE: remove `saveErrorIfNotFound`, always error out if `save()` did not update a document #4973 - * BREAKING CHANGE: don't execute getters in reverse order #4835 - * BREAKING CHANGE: make boolean casting more strict #4245 - * BREAKING CHANGE: `toObject()` and `toJSON()` option parameter merges with defaults rather than overwriting #4131 - * feat: allow setting `default` on `_id` #4069 - * BREAKING CHANGE: `deleteX()` and `remove()` promise resolves to the write object result #4013 - * feat: support returning a promise from middleware functions #3779 - * BREAKING CHANGE: don't return a promise if callback specified #3670 - * BREAKING CHANGE: only cast `update()`, `updateX()`, `replaceOne()`, `remove()`, `deleteX()` in exec #3529 - * BREAKING CHANGE: sync errors in middleware functions are now handled #3483 - * BREAKING CHANGE: post hooks get flow control #3232 - * BREAKING CHANGE: deduplicate hooks when merging discriminator schema #2945 - * BREAKING CHANGE: use native promises by default, remove support for mpromise #2917 - * BREAKING CHANGE: remove `retainKeyOrder`, always use forward order when iterating through objects #2749 - * BREAKING CHANGE: `aggregate()` no longer accepts a spread #2716 - -4.13.8 / 2017-12-27 -=================== - * docs(guide): use more up-to-date syntax for autoIndex example #5933 - * docs: fix grammar #5927 [abagh0703](https://github.com/abagh0703) - * fix: propagate lean options to child schemas #5914 - * fix(populate): use correct model with discriminators + nested populate #5858 - -4.13.7 / 2017-12-11 -=================== - * docs(schematypes): fix typo #5889 [gokaygurcan](https://github.com/gokaygurcan) - * fix(cursor): handle `reject(null)` with eachAsync callback #5875 #5874 [ZacharyRSmith](https://github.com/ZacharyRSmith) - * fix: disallow setting `mongoose.connection` to invalid values #5871 [jinasonlin](https://github.com/jinasonlin) - * docs(middleware): suggest using `return next()` to stop middleware execution #5866 - * docs(connection): improve connection string query param docs #5864 - * fix(document): run validate hooks on array subdocs even if not directly modified #5861 - * fix(discriminator): don't treat $meta as defining projection when querying #5859 - * fix(types): handle Decimal128 when using bson-ext on server side #5850 - * fix(document): ensure projection with only $slice isn't treated as inclusive for discriminators #4991 - * fix(model): throw error when passing non-object to create() #2037 - -4.13.6 / 2017-12-02 -=================== - * fix(schema): support strictBool option in schema #5856 [ekulabuhov](https://github.com/ekulabuhov) - * fix(update): make upsert option consistently handle truthy values, not just booleans, for updateOne() #5839 - * refactor: remove unnecessary constructor check #2057 - * docs(query): correct function signature for .mod() helper #1806 - * fix(query): report ObjectParameterError when passing non-object as filter to find() and findOne() #1698 - -4.13.5 / 2017-11-24 -=================== - * fix(model): handle update cast errors correctly with bulkWrite #5845 [Michael77](https://github.com/Michael77) - * docs: add link to bufferCommands option #5844 [ralphite](https://github.com/ralphite) - * fix(model): allow virtual ref function to return arrays #5834 [brunohcastro](https://github.com/brunohcastro) - * fix(query): don't throw uncaught error if query filter too big #5812 - * fix(document): if setting unselected nested path, don't overwrite nested path #5800 - * fix(document): support calling `populate()` on nested document props #5703 - * fix: add `strictBool` option for schema type boolean #5344 #5211 #4245 - * docs(faq): add faq re: typeKey #1886 - * docs(query): add more detailed docs re: options #1702 - -4.13.4 / 2017-11-17 -=================== - * fix(aggregate): add chainable .option() helper for setting arbitrary options #5829 - * fix(aggregate): add `.pipeline()` helper to get the current pipeline #5825 - * docs: grammar fixes for `unique` FAQ #5823 [mfluehr](https://github.com/mfluehr) - * chore: add node 9 to travis #5822 [superheri](https://github.com/superheri) - * fix(model): fix infinite recursion with recursive embedded discriminators #5821 [Faibk](https://github.com/Faibk) - -4.13.3 / 2017-11-15 -=================== - * chore: add node 8 to travis #5818 [superheri](https://github.com/superheri) - * fix(document): don't apply transforms to nested docs when updating already saved doc #5807 - -4.13.2 / 2017-11-11 -=================== - * feat(buffer): add support for subtype prop #5530 - -4.13.1 / 2017-11-08 -=================== - * fix: accept multiple paths or array of paths to depopulate #5798 #5797 [adamreisnz](https://github.com/adamreisnz) - * fix(document): pass default array as actual array rather than taking first element #5780 - * fix(model): increment version when $set-ing it in a save() that requires a version bump #5779 - * fix(query): don't explicitly project in discriminator key if user projected in parent path #5775 #5754 - * fix(model): cast query option to geoNear() #5765 - * fix(query): don't treat projection with just $slice as inclusive #5737 - * fix(discriminator): defer applying embedded discriminator hooks until top-level model is compiled #5706 - * docs(discriminator): add warning to always attach hooks before calling discriminator() #5706 - -4.13.0 / 2017-11-02 -=================== - * feat(aggregate): add $addFields helper #5740 [AyushG3112](https://github.com/AyushG3112) - * feat(connection): add connection-level bufferCommands #5720 - * feat(connection): add createCollection() helper #5712 - * feat(populate): support setting localField and foreignField to functions #5704 #5602 - * feat(query): add multipleCastError option for aggregating cast errors when casting update #5609 - * feat(populate): allow passing a function to virtual ref #5602 - * feat(schema): add excludeIndexes option to optionally prevent collecting indexes from nested schemas #5575 - * feat(model): report validation errors from `insertMany()` if using `ordered: false` and `rawResult: true` #5337 - * feat(aggregate): add pre/post aggregate middleware #5251 - * feat(schema): allow using `set` as a schema path #1939 - -4.12.6 / 2017-11-01 -=================== - * fix(schema): make clone() copy query helpers correctly #5752 - * fix: undeprecate `ensureIndex()` and use it by default #3280 - -4.12.5 / 2017-10-29 -=================== - * fix(query): correctly handle `$in` and required for $pull and update validators #5744 - * feat(aggegate): add $addFields pipeline operator #5740 [AyushG3112](https://github.com/AyushG3112) - * fix(document): catch sync errors in document pre hooks and report as error #5738 - * fix(populate): handle slice projections correctly when automatically selecting populated fields #5737 - * fix(discriminator): fix hooks for embedded discriminators #5706 [wlingke](https://github.com/wlingke) - * fix(model): throw sane error when customer calls `mongoose.Model()` over `mongoose.model()` #2005 - -4.12.4 / 2017-10-21 -=================== - * test(plugins): add coverage for idGetter with id as a schema property #5713 [wlingke](https://github.com/wlingke) - * fix(model): avoid copying recursive $$context object when creating discriminator after querying #5721 - * fix(connection): ensure connection promise helpers are removed before emitting 'connected' #5714 - * docs(schema): add notes about runSettersOnQuery to schema setters #5705 - * fix(collection): ensure queued operations run on the next tick #5562 - -4.12.3 / 2017-10-16 -=================== - * fix(connection): emit 'reconnect' event as well as 'reconnected' for consistency with driver #5719 - * fix: correctly bubble up left/joined events for replica set #5718 - * fix(connection): allow passing in `autoIndex` as top-level option rather than requiring `config.autoIndex` #5711 - * docs(connection): improve docs regarding reconnectTries, autoReconnect, and bufferMaxEntries #5711 - * fix(query): handle null with addToSet/push/pull/pullAll update validators #5710 - * fix(model): handle setDefaultsOnInsert option for bulkWrite updateOne and updateMany #5708 - * fix(query): avoid infinite recursion edge case when cloning a buffer #5702 - -4.12.2 / 2017-10-14 -=================== - * docs(faq): add FAQ about using arrow functions for getters/setters, virtuals, and methods #5700 - * docs(schema): document the childSchemas property and add to public API #5695 - * fix(query): don't project in populated field if parent field is already projected in #5669 - * fix: bump mongodb -> 2.2.33 for issue with autoReconnect #4513 - -4.12.1 / 2017-10-08 -=================== - * fix(document): create new doc when setting single nested, no more set() on copy of priorVal #5693 - * fix(model): recursively call applyMethods on child schemas for global plugins #5690 - * docs: fix bad promise lib example on home page #5686 - * fix(query): handle false when checking for inclusive/exclusive projection #5685 - * fix(discriminator): allow reusing child schema #5684 - * fix: make addToSet() on empty array with subdoc trigger manual population #5504 - -4.12.0 / 2017-10-02 -=================== - * docs(validation): add docs coverage for ValidatorError.reason #5681 - * feat(discriminator): always add discriminatorKey to base schema to allow updating #5613 - * fix(document): make nested docs no longer inherit parent doc's schema props #5586 #5546 #5470 - * feat(query): run update validators on $pull and $pullAll #5555 - * feat(query): add .error() helper to query to error out in pre hooks #5520 - * feat(connection): add dropCollection() helper #5393 - * feat(schema): add schema-level collation option #5295 - * feat(types): add `discriminator()` function for single nested subdocs #5244 - * feat(document): add $isDeleted() getter/setter for better support for soft deletes #4428 - * feat(connection): bubble up reconnectFailed event when driver gives up reconnecting #4027 - * fix(query): report error if passing array or other non-object as filter to update query #3677 - * fix(collection): use createIndex() instead of deprecated ensureIndex() #3280 - -4.11.14 / 2017-09-30 -==================== - * chore: add nsp check to the CI build #5679 [hairyhenderson](https://github.com/hairyhenderson) - * fix: bump mquery because of security issue with debug package #5677 #5675 [jonathanprl](https://github.com/jonathanprl) - * fix(populate): automatically select() populated()-ed fields #5669 - * fix(connection): make force close work as expected #5664 - * fix(document): treat $elemMatch as inclusive projection #5661 - * docs(model/query): clarify which functions fire which middleware #5654 - * fix(model): make `init()` public and return a promise that resolves when indexes are done building #5563 - -4.11.13 / 2017-09-24 -==================== - * fix(query): correctly run replaceOne with update validators #5665 [sime1](https://github.com/sime1) - * fix(schema): replace mistype in setupTimestamp method #5656 [zipp3r](https://github.com/zipp3r) - * fix(query): avoid throwing cast error for strict: throw with nested id in query #5640 - * fix(model): ensure class gets combined schema when using class syntax with discriminators #5635 - * fix(document): handle setting doc array to array of top-level docs #5632 - * fix(model): handle casting findOneAndUpdate() with overwrite and upsert #5631 - * fix(update): correctly handle $ in updates #5628 - * fix(types): handle manual population consistently for unshift() and splice() #5504 - -4.11.12 / 2017-09-18 -==================== - * docs(model): asterisk should not render as markdown bullet #5644 [timkinnane](https://github.com/timkinnane) - * docs: use useMongoClient in connection example #5627 [GabrielNicolasAvellaneda](https://github.com/GabrielNicolasAvellaneda) - * fix(connection): call callback when initial connection failed #5626 - * fix(query): apply select correctly if a given nested schema is used for 2 different paths #5603 - * fix(document): add graceful fallback for setting a doc array value and `pull()`-ing a doc #3511 - -4.11.11 / 2017-09-10 -==================== - * fix(connection): properly set readyState in response to driver 'close' and 'reconnect' events #5604 - * fix(document): ensure single embedded doc setters only get called once, with correct value #5601 - * fix(timestamps): allow enabling updatedAt without createdAt #5598 - * test: improve unique validator test by making create run before ensureIndex #5595 #5562 - * fix(query): ensure find callback only gets called once when post init hook throws error #5592 - -4.11.10 / 2017-09-03 -==================== - * docs: add KeenIO tracking #5612 - * fix(schema): ensure validators declared with `.validate()` get copied with clone() #5607 - * fix: remove unnecessary jest warning #5480 - * fix(discriminator): prevent implicit discriminator schema id from clobbering base schema custom id #5591 - * fix(schema): hide schema objectid warning for non-hex strings of length 24 #5587 - * docs(populate): use story schema defined key author instead of creator #5578 [dmric](https://github.com/dmric) - * docs(document): describe usage of `.set()` #5576 - * fix(document): ensure correct scope in single nested validators #5569 - * fix(populate): don't mark path as populated until populate() is done #5564 - * fix(document): make push()-ing a doc onto an empty array act as manual population #5504 - * fix(connection): emit timeout event on socket timeout #4513 - -4.11.9 / 2017-08-27 -=================== - * fix(error): avoid using arguments.callee because that breaks strict mode #5572 - * docs(schematypes): fix spacing #5567 - * fix(query): enforce binary subtype always propagates to mongodb #5551 - * fix(query): only skip castForQuery for mongoose arrays #5536 - * fix(browser): rely on browser entrypoint to decide whether to use BrowserDocument or NodeDocument #5480 - -4.11.8 / 2017-08-23 -=================== - * feat: add warning about using schema ObjectId as type ObjectId #5571 [efkan](https://github.com/efkan) - * fix(schema): allow setting `id` property after schema was created #5570 #5548 - * docs(populate): remove confusing _ from populate docs #5560 - * fix(connection): expose parsed uri fields (host, port, dbname) when using openUri() #5556 - * docs: added type boolean to options documentation #5547 [ndabAP](https://github.com/ndabAP) - * test: add test coverage for stopping/starting server #5524 - * fix(aggregate): pull read preference from schema by default #5522 - -4.11.7 / 2017-08-14 -=================== - * fix: correct properties when calling toJSON() on populated virtual #5544 #5442 [davidwu226](https://github.com/davidwu226) - * docs: fix spelling #5535 [et](https://github.com/et) - * fix(error): always set name before stack #5533 - * fix: add warning about running jest in jsdom environment #5532 #5513 #4943 - * fix(document): ensure overwriting a doc array cleans out individual docs #5523 - * fix(schema): handle creating arrays of single nested using type key #5521 - * fix: upgrade mongodb -> 2.2.31 to support user/pass options #5419 - -4.11.6 / 2017-08-07 -=================== - * fix: limiting number of async operations per time in insertMany #5529 [andresattler](https://github.com/andresattler) - * fix: upgrade mongodb -> 2.2.30 #5517 - * fix(browserDocument): prevent stack overflow caused by double-wrapping embedded doc save() in jest #5513 - * fix(document): clear single nested doc when setting to empty object #5506 - * fix(connection): emit reconnected and disconnected events correctly with useMongoClient #5498 - * fix(populate): ensure nested virtual populate gets set even if top-level property is null #5431 - -4.11.5 / 2017-07-30 -=================== - * docs: fix link to $lookup #5516 [TalhaAwan](https://github.com/TalhaAwan) - * fix: better parallelization for eachAsync #5502 [lchenay](https://github.com/lchenay) - * docs(document): copy docs for save from model to doc #5493 - * fix(document): handle dotted virtuals in toJSON output #5473 - * fix(populate): restore user-provided limit after mutating so cursor() works with populate limit #5468 - * fix(query): don't throw StrictModeError if geo query with upsert #5467 - * fix(populate): propagate readPreference from query to populate queries by default #5460 - * docs: warn not to use arrow functions for statics and methods #5458 - * fix(query): iterate over all condition keys for setDefaultsOnInsert #5455 - * docs(connection): clarify server/replset/mongos option deprecation with useMongoClient #5442 - -4.11.4 / 2017-07-23 -=================== - * fix: handle next() errors in `eachAsync()` #5486 [lchenay](https://github.com/lchenay) - * fix(schema): propagate runSettersOnQuery option to implicitly created schemas #5479 [https://github.com/ValYouW] - * fix(query): run castConditions() correctly in update ops #5477 - * fix(query): ensure castConditions called for findOne and findOneAnd* #5477 - * docs: clarify relationship between $lookup and populate #5475 [TalhaAwan](https://github.com/TalhaAwan) - * test: add coverage for arrays of arrays [zbjornson](https://github.com/zbjornson) - * fix(middleware): ensure that error handlers for save get doc as 2nd param #5466 - * fix: handle strict: false correctly #5454 #5453 [wookieb](https://github.com/wookieb) - * fix(query): apply schema excluded paths if only projection is a $slice #5450 - * fix(query): correct discriminator handling for schema `select: false` fields in schema #5448 - * fix(cursor): call next() in series when parallel option used #5446 - * chore: load bundled driver first to avoid packaging problem #5443 [prototypeme](https://github.com/prototypeme) - * fix(query): defer condition casting until final exec #5434 - * fix(aggregate): don't rely on mongodb aggregate to put a cursor in the callback #5394 - * docs(aggregate): add useMongooseAggCursor docs #5394 - * docs(middleware): clarify context for document, query, and model middleware #5381 - -4.11.3 / 2017-07-14 -=================== - * fix(connection): remove .then() before resolving to prevent infinite recursion #5471 - -4.11.2 / 2017-07-13 -=================== - * docs: fix comment typo in connect example #5435 [ConnorMcF](https://github.com/ConnorMcF) - * fix(update): correctly cast document array in update validators with exec() #5430 - * fix(connection): handle autoIndex with useMongoClient #5423 - * fix(schema): handle `type: [Array]` in schemas #5416 - * fix(timestamps): if overwrite is set and there's a $set, use $set instead of top-level update #5413 - * fix(document): don't double-validate deeply nested doc array elements #5411 - * fix(schematype): clone default objects so default not shared across object instances unless `shared` specified #5407 - * fix(document): reset down the nested subdocs when resetting parent doc #5406 - * fix: don't pass error arg twice to error handlers #5405 - * fix(connection): make openUri() return connection decorated with then() and catch() #5404 - * fix: enforce $set on an array must be an array #5403 - * fix(document): don't crash if calling `validateSync()` after overwriting doc array index #5389 - * fix(discriminator): ensure discriminator key doesn't count as user-selected field for projection #4629 - -4.11.1 / 2017-07-02 -=================== -* docs: populate virtuals fix justOne description #5427 [fredericosilva](https://github.com/fredericosilva) - * fix(connection): make sure to call onOpen in openUri() #5404 - * docs(query): justOne is actually single, and it default to false #5402 [zbjornson](https://github.com/zbjornson) - * docs: fix small typo in lib/schema.js #5398 #5396 [pjo336](https://github.com/pjo336) - * fix: emit remove on single nested subdocs when removing parent #5388 - * fix(update): handle update with defaults and overwrite but no update validators #5384 - * fix(populate): handle undefined refPath values in middle of array #5377 - * fix(document): ensure consistent setter context for single nested #5363 - * fix(query): support runSettersOnQuery as query option #5350 - -4.11.0 / 2017-06-25 -=================== - * feat(query): execute setters with query as context for `runSettersOnQuery` #5339 - * feat(model): add translateAliases function #5338 [rocketspacer](https://github.com/rocketspacer) - * feat(connection): add `useMongoClient` and `openUri` functions, deprecate current connect logic #5304 - * refactor(schema): make id virtual not access doc internals #5279 - * refactor: handle non-boolean lean #5279 - * feat(cursor): add addCursorFlag() support to query and agg cursors #4814 - * feat(cursor): add parallel option to eachAsync #4244 - * feat(schema): allow setting custom error constructor for custom validators #4009 - -4.10.8 / 2017-06-21 -=================== - * docs: fix small formatting typo on schematypes #5374 [gianpaj](https://github.com/gianpaj) - * fix(model): allow null as an _id #5370 - * fix(populate): don't throw async uncaught exception if model not found in populate #5364 - * fix: correctly cast decimals in update #5361 - * fix(error): don't use custom getter for ValidationError message #5359 - * fix(query): handle runSettersOnQuery in built-in _id setter #5351 - * fix(document): ensure consistent context for nested doc custom validators #5347 - -4.10.7 / 2017-06-18 -=================== - * docs(validation): show overriding custom validator error with 2nd cb arg #5358 - * fix: `parseOption` mutates user passed option map #5357 [igwejk](https://github.com/igwejk) - * docs: fix guide.jade typo #5356 [CalebAnderson2014](https://github.com/CalebAnderson2014) - * fix(populate): don't set populate virtual to ids when match fails #5336 - * fix(query): callback with cast error if remove and delete* args have a cast error #5323 - -4.10.6 / 2017-06-12 -=================== - * fix(cursor): handle custom model option for populate #5334 - * fix(populate): handle empty virtual populate with Model.populate #5331 - * fix(model): make ensureIndexes() run with autoIndex: false unless called internally #5328 #5324 #5317 - * fix: wait for all connections to close before resolving disconnect() promise #5316 - * fix(document): handle setting populated path with custom typeKey in schema #5313 - * fix(error): add toJSON helper to ValidationError so `message` shows up with JSON.stringify #5309 - * feat: add `getPromiseConstructor()` to prevent need for `mongoose.Promise.ES6` #5305 - * fix(document): handle conditional required with undefined props #5296 - * fix(model): clone options before inserting in save() #5294 - * docs(populate): clarify that multiple populate() calls on same path overwrite #5274 - -4.10.5 / 2017-06-06 -=================== - * chore: improve contrib guide for building docs #5312 - * fix(populate): handle init-ing nested virtuals properly #5311 - * fix(update): report update validator error if required path under single nested doc not set - * fix(schema): remove default validate pre hook that was causing issues with jest #4943 - -4.10.4 / 2017-05-29 -=================== - * chore: dont store test data in same directory #5303 - * chore: add data dirs to npmignore #5301 [Starfox64](https://github.com/Starfox64) - * docs(query): add docs about runSettersOnQuery #5300 - -4.10.3 / 2017-05-27 -=================== - * docs: correct inconsistent references to updateOne and replaceOne #5297 [dhritzkiv](https://github.com/dhritzkiv) - * docs: fix dropdowns in docs #5292 [nathanallen](https://github.com/nathanallen) - * docs: add description of alias option #5287 - * fix(document): prevent infinite loop if validating nested array #5282 - * fix(schema): correctly handle ref ObjectIds from different mongoose libs #5259 - * fix(schema): load child class methods after base class methods to allow override #5227 - -4.10.2 / 2017-05-22 -=================== - * fix: bump ms -> 2.0.0 and mquery -> 2.3.1 for minor security vulnerability #5275 - -4.10.1 / 2017-05-21 -=================== - * fix(aggregate): handle sorting by text score correctly #5258 - * fix(populate): handle doc.populate() with virtuals #5240 - * fix(schema): enforce that `_id` is never null #5236 - -4.10.0 / 2017-05-18 -=================== - * fix(schema): update clone method to include indexes #5268 [clozanosanchez](https://github.com/clozanosanchez) - * feat(schema): support aliases #5184 [rocketspacer](https://github.com/rocketspacer) - * feat(aggregate): add mongoose-specific aggregation cursor option #5145 - * refactor(model): make sharding into a plugin instead of core #5105 - * fix(document): make nested doc mongoose internals not enumerable again #5078 - * feat(model): pass params to pre hooks #5064 - * feat(timestamps): support already defined timestamp paths in schema #4868 - * feat(query): add runSettersOnQuery option #4569 - * fix(query): add strictQuery option that throws when not querying on field not in schema #4136 - * fix(update): more complete handling for overwrite option with update validators #3556 - * feat: support `unique: true` in arrays via the mongoose-unique-array plugin #3347 - * fix(model): always emit 'index', even if no indexes #3347 - * fix(schema): set unique indexes on primitive arrays #3347 - * feat(validation): include failed paths in error message and inspect output #3064 #2135 - * fix(model): return saved docs when create() fails #2190 - -4.9.10 / 2017-05-17 -=================== - * fix(connection): ensure callback arg to openSet() is handled properly #5249 - * docs: remove dead plugins repo and add content links #5247 - * fix(model): skip index build if connecting after model init and autoIndex false #5176 - -4.9.9 / 2017-05-13 -================== - * docs: correct value for Query#regex() #5230 - * fix(connection): don't throw if .catch() on open() promise #5229 - * fix(schema): allow update with $currentDate for updatedAt to succeed #5222 - * fix(model): versioning doesn't fail if version key undefined #5221 [basileos](https://github.com/basileos) - * fix(document): don't emit model error if callback specified for consistency with docs #5216 - * fix(document): handle errors in subdoc pre validate #5215 - -4.9.8 / 2017-05-07 -================== - * docs(subdocs): rewrite subdocs guide #5217 - * fix(document): avoid circular JSON if error in doc array under single nested subdoc #5208 - * fix(document): set intermediate empty objects for deeply nested undefined paths before path itself #5206 - * fix(schema): throw error if first param to schema.plugin() is not a function #5201 - * perf(document): major speedup in validating subdocs (50x in some cases) #5191 - -4.9.7 / 2017-04-30 -================== - * docs: fix typo #5204 [phutchins](https://github.com/phutchins) - * fix(schema): ensure correct path for deeply nested schema indexes #5199 - * fix(schema): make remove a reserved name #5197 - * fix(model): handle Decimal type in insertMany correctly #5190 - * fix: upgrade kareem to handle async pre hooks correctly #5188 - * docs: add details about unique not being a validator #5179 - * fix(validation): handle returning a promise with isAsync: true #5171 - -4.9.6 / 2017-04-23 -================== - * fix: update `parentArray` references when directly assigning document arrays #5192 [jhob](https://github.com/jhob) - * docs: improve schematype validator docs #5178 [milesbarr](https://github.com/milesbarr) - * fix(model): modify discriminator() class in place #5175 - * fix(model): handle bulkWrite updateMany casting #5172 [tzellman](https://github.com/tzellman) - * docs(model): fix replaceOne example for bulkWrite #5168 - * fix(document): don't create a new array subdoc when creating schema array #5162 - * fix(model): merge query hooks from discriminators #5147 - * fix(document): add parent() function to subdocument to match array subdoc #5134 - -4.9.5 / 2017-04-16 -================== - * fix(query): correct $pullAll casting of null #5164 [Sebmaster](https://github.com/Sebmaster) - * docs: add advanced schemas docs for loadClass #5157 - * fix(document): handle null/undefined gracefully in applyGetters() #5143 - * fix(model): add resolveToObject option for mapReduce with ES6 promises #4945 - -4.9.4 / 2017-04-09 -================== - * fix(schema): clone query middleware correctly #5153 #5141 [clozanosanchez](https://github.com/clozanosanchez) - * docs(aggregate): fix typo #5142 - * fix(query): cast .$ update to underlying array type #5130 - * fix(populate): don't mutate populate result in place #5128 - * fix(query): handle $setOnInsert consistent with $set #5126 - * docs(query): add strict mode option for findOneAndUpdate #5108 - -4.9.3 / 2017-04-02 -================== - * docs: document.js fixes for functions prepended with `$` #5131 [krmannix](https://github.com/krmannix) - * fix: Avoid exception on constructor check #5129 [monkbroc](https://github.com/monkbroc) - * docs(schematype): explain how to use `isAsync` with validate() #5125 - * docs(schematype): explain custom message with required function #5123 - * fix(populate): only apply refPath duplicate id optimization if not array #5114 - * fix(document): copy non-objects to doc when init() #5111 - * perf(populate): dont clone whole options every time #5103 - * feat(document): add isDirectSelected() to minimize isSelected() changes #5063 - * docs(schematypes): explain some subtleties with arrays #5059 - -4.9.2 / 2017-03-26 -================== - * fix(discriminator): handle class names consistently #5104 - * fix(schema): make clone() work with reusing discriminator schemas #5098 - * fix(querycursor): run pre find hooks with .cursor() #5096 - * fix(connection): throw error if username:password includes @ or : #5091 - * fix(timestamps): handle overwriting createdAt+updatedAt consistently #5088 - * fix(document): ensure subdoc post save runs after parent save #5085 - * docs(model): improve update docs #5076 [bertolo1988](https://github.com/bertolo1988) - -4.9.1 / 2017-03-19 -================== - * fix(query): handle $type for arrays #5080 #5079 [zoellner](https://github.com/zoellner) - * fix(model): handle ordered param for `insertMany` validation errors #5072 [sjorssnoeren](https://github.com/sjorssnoeren) - * fix(populate): avoid duplicate ids in dynref queries #5054 - * fix(timestamps): dont set timestamps in update if user set it #5045 - * fix(update): dont double-call setters on arrays #5041 - * fix: upgrade driver -> 2.2.25 for jest fix #5033 - * fix(model): get promise each time save() is called rather than once #5030 - * fix(connection): make connect return value consistent #5006 - -4.9.0 / 2017-03-13 -================== - * feat(document): return this from `depopulate()` #5027 - * fix(drivers): stop emitting timeouts as errors #5026 - * feat(schema): add a clone() function for schemas #4983 - * feat(query): add rawResult option to replace passRawResult, deprecate passRawResult #4977 #4925 - * feat(schematype): support isAsync validator option and handle returning promises from validators, deprecate implicit async validators #4290 - * feat(query): add `replaceOne()`, `deleteOne()`, `deleteMany()` #3998 - * feat(model): add `bulkWrite()` #3998 - -4.8.7 / 2017-03-12 -================== - * fix(model): if last arg in spread is falsy, treat it as a callback #5061 - * fix(document): use $hook instead of hook to enable 'hook' as a path name #5047 - * fix(populate): dont select foreign field if parent field is selected #5037 - * fix(populate): handle passing no args to query.populate #5036 - * fix(update): use correct method for casting nested arrays #5032 - * fix(discriminator): handle array discriminators when casting $push #5009 - -4.8.6 / 2017-03-05 -================== - * docs(document): remove text that implies that transform is false by default #5023 - * fix(applyHooks): dont wrap a function if it is already wrapped #5019 - * fix(document): ensure nested docs' toObject() clones #5008 - -4.8.5 / 2017-02-25 -================== - * fix: check for empty schemaPath before accessing property $isMongooseDocumentArray #5017 [https://github.com/randyhoulahan](randyhoulahan) - * fix(discriminators): handle create() and push() for embedded discriminators #5001 - * fix(querycursor): ensure close emitted after last data event #4998 - * fix(discriminators): remove fields not selected in child when querying by base model #4991 - -4.8.4 / 2017-02-19 -================== - * docs(discriminators): explain embedded discriminators #4997 - * fix(query): fix TypeError when findOneAndUpdate errors #4990 - * fix(update): handle nested single embedded in update validators correctly #4989 - * fix(browser): make browser doc constructor not crash #4987 - -4.8.3 / 2017-02-15 -================== - * chore: upgrade mongodb driver -> 2.2.24 - * docs(connections): addd some details about callbacks #4986 - * fix: ensure class is created with new keyword #4972 #4947 [benhjames](https://github.com/benhjames) - * fix(discriminator): add applyPluginsToDiscriminators option #4965 - * fix(update): properly cast array subdocs when casting update #4960 - * fix(populate): ensure foreign field is selected for virtual populate #4959 - * docs(query): document some query callback params #4949 - * fix(document): ensure errors in validators get caught #2185 - -4.8.2 / 2017-02-10 -================== - * fix(update): actually run validators on addToSet #4953 - * fix(update): improve buffer error handling #4944 [ValYouW](https://github.com/ValYouW) - * fix(discriminator): handle subclassing with loadClass correctly #4942 - * fix(query): allow passing Map to sort() #4941 - * fix(document): handle setting discriminator doc #4935 - * fix(schema): return correct value from pre init hook #4928 - * fix(query): ensure consistent params in error handlers if pre hook errors #4927 - -4.8.1 / 2017-01-30 -================== - * fix(query): handle $exists for arrays and embedded docs #4937 - * fix(query): handle passing string to hint() #4931 - -4.8.0 / 2017-01-28 -================== - * feat(schema): add saveErrorIfNotFound option and $where property #4924 #4004 - * feat(query): add $in implicitly if passed an array #4912 [QuotableWater7](https://github.com/QuotableWater7) - * feat(aggregate): helper for $facet #4904 [varunjayaraman](https://github.com/varunjayaraman) - * feat(query): add collation method #4839 - * feat(schema): propogate strict option to implicit array subschemas #4831 [dkrosso](https://github.com/dkrosso) - * feat(aggregate): add helper for graphLookup #4819 [varunjayaraman](https://github.com/varunjayaraman) - * feat(types): support Decimal128 #4759 - * feat(aggregate): add eachAsync() to aggregate cursor #4300 - * feat(query): add updateOne and updateMany #3997 - * feat(model): support options for insertMany #3893 - * fix(document): run validation on single nested docs if not directly modified #3884 - * feat(model): use discriminator constructor based on discriminatorKey in create() #3624 - * feat: pass collection as context to debug function #3261 - * feat(query): support push and addToSet for update validators #2933 - * perf(document): refactor registerHooksFromSchema so hooks are defined on doc prototype #2754 - * feat(types): add discriminator() function to doc arrays #2723 #1856 - * fix(populate): return an error if sorting underneath a doc array #2202 - -4.7.9 / 2017-01-27 -================== - * fix(query): handle casting $exists under $not #4933 - * chore: upgrade mongodb -> 2.2.22 re: #4931 - -4.7.8 / 2017-01-23 -================== - * fix(populate): better handling for virtual populate under arrays #4923 - * docs: upgrade contributors count #4918 [AdamZaczek](https://github.com/AdamZaczek) - * fix(query): don't set nested path default if setting parent path #4911 - * docs(promise): add missing bracket #4907 - * fix(connection): ensure error handling is consistently async #4905 - * fix: handle authMechanism in query string #4900 - * fix(document): ensure error handlers run for validate #4885 - -4.7.7 / 2017-01-15 -================== - * fix(utils): don't crash if to[key] is null #4881 - * fix: upgrade mongodb -> 2.2.21 #4867 - * fix: add a toBSON to documents for easier querying #4866 - * fix: suppress bluebird warning #4854 [davidwu226](https://github.com/davidwu226) - * fix(populate): handle nested virtuals in virtual populate #4851 - -4.7.6 / 2017-01-02 -================== - * fix(model): allow passing non-array to insertMany #4846 - * fix(populate): use base model name if no discriminator for backwards compat #4843 - * fix: allow internal validate callback to be optional #4842 [arciisine](https://github.com/arciisine) - * fix(document): don't skip pointCut if save not defined (like in browser doc) #4841 - * chore: improve benchmarks #4838 [billouboq](https://github.com/billouboq) - * perf: remove some unused parameters #4837 [billouboq](https://github.com/billouboq) - * fix(query): don't call error handler if passRawResult is true and no error occurred #4836 - -4.7.5 / 2016-12-26 -================== - * docs(model): fix spelling mistake #4828 [paulinoj](https://github.com/paulinoj) - * fix(aggregate): remove unhandled rejection when using aggregate.then() #4824 - * perf: remove try/catch that kills optimizer #4821 - * fix(model): handles populating with discriminators that may not have a ref #4817 - * fix(document): handle setting array of discriminators #3575 - -4.7.4 / 2016-12-21 -================== - * docs: fix typo #4810 [GEEKIAM](https://github.com/GEEKIAM) - * fix(query): timestamps with $push + $each #4805 - * fix(document): handle buffers correctly in minimize #4800 - * fix: don't disallow overwriting default and cast fns #4795 [pdspicer](https://github.com/pdspicer) - * fix(document): don't convert single nested docs to POJOs #4793 - * fix(connection): handle reconnect to replica set correctly #4972 [gfzabarino](https://github.com/gfzabarino) - -4.7.3 / 2016-12-16 -================== - * fix: upgrade mongodb driver -> 2.2.16 for several bug fixes and 3.4 support #4799 - * fix(model): ensure discriminator key is correct for child schema on discriminator #4790 - * fix(document): handle mark valid in subdocs correctly #4778 - * fix(query): check for objects consistently #4775 - -4.7.2 / 2016-12-07 -================== - * test(populate): fix justOne test #4772 [cblanc](https://github.com/cblanc) - * chore: fix benchmarks #4769 [billouboq](https://github.com/billouboq) - * fix(document): handle setting subdoc to null after setting parent doc #4766 - * fix(query): support passRawResult with lean #4762 #4761 [mhfrantz](https://github.com/mhfrantz) - * fix(query): throw StrictModeError if upsert with nonexisting field in condition #4757 - * test: fix a couple of sort tests #4756 [japod](https://github.com/japod) - * chore: upgrade mongodb driver -> 2.2.12 #4753 [mdlavin](https://github.com/mdlavin) - * fix(query): handle update with upsert and overwrite correctly #4749 - -4.7.1 / 2016-11-30 -================== - * fix(schema): throw error if you use prototype as a schema path #4746 - * fix(schema): throw helpful error if you define a virtual with the same path as a real path #4744 - * fix(connection): make createConnection not throw rejected promises #4742 - * fix(populate): allow specifiying options in model schema #4741 - * fix(document): handle selected nested elements with defaults #4739 - * fix(query): add model to cast error if possible #4729 - * fix(query): handle timestamps with overwrite #4054 - -4.7.0 / 2016-11-23 -================== - * docs: clean up schematypes #4732 [kidlj](https://github.com/kidlj) - * perf: only get stack when necessary with VersionError #4726 [Sebmaster](https://github.com/Sebmaster) - * fix(query): ensure correct casting when setting array element #4724 - * fix(connection): ensure db name gets set when you pass 4 params #4721 - * fix: prevent TypeError in node v7 #4719 #4706 - * feat(document): support .set() on virtual subpaths #4716 - * feat(populate): support populate virtuals on nested schemas #4715 - * feat(querycursor): support transform option and .map() #4714 #4705 [cblanc](https://github.com/cblanc) - * fix(document): dont set defaults on not-selected nested paths #4707 - * fix(populate): don't throw if empty string passed to populate #4702 - * feat(model): add `loadClass()` function for importing schema from ES6 class #4668 [rockmacaca](https://github.com/rockmacaca) - -4.6.8 / 2016-11-14 -================== - * fix(querycursor): clear stack when iterating onto next doc #4697 - * fix: handle null keys in validation error #4693 #4689 [arciisine](https://github.com/arciisine) - * fix(populate): handle pre init middleware correctly with populate virtuals #4683 - * fix(connection): ensure consistent return value for open and openSet #4659 - * fix(schema): handle falsy defaults for arrays #4620 - -4.6.7 / 2016-11-10 -================== - * fix(document): only invalidate in subdoc if using update validators #4681 - * fix(document): don't create subdocs when excluded in projection #4669 - * fix(document): ensure single embedded schema validator runs with correct context #4663 - * fix(document): make sure to depopulate top level for sharding #4658 - * fix(connection): throw more helpful error when .model() called incorrectly #4652 - * fix(populate): throw more descriptive error when trying to populate a virtual that doesn't have proper options #4602 - * fix(document): ensure subtype gets set properly when saving with a buffer id #4506 - * fix(query): handle setDefaultsOnInsert with defaults on doc arrays #4456 - * fix(drivers): make debug output better by calling toBSON() #4356 - -4.6.6 / 2016-11-03 -================== - * chore: upgrade deps #4674 [TrejGun](https://github.com/TrejGun) - * chore: run tests on node v7 #4673 [TrejGun](https://github.com/TrejGun) - * perf: make setDefaultsOnInsert more efficient if upsert is off #4672 [CamHenlin](https://github.com/CamHenlin) - * fix(populate): ensure document array is returned #4656 - * fix(query): cast doc arrays with positionals correctly for update #4655 - * fix(document): ensure single nested doc validators run with correct context #4654 - * fix: handle reconnect failed error in new version of driver #4653 [loris](https://github.com/loris) - * fix(populate): if setting a populated doc, take its id #4632 - * fix(populate): handle populated virtuals in init #4618 - -4.6.5 / 2016-10-23 -================== - * docs: fix grammar issues #4642 #4640 #4639 [silvermanj7](https://github.com/silvermanj7) - * fix(populate): filter out nonexistant values for dynref #4637 - * fix(query): handle $type as a schematype operator #4632 - * fix(schema): better handling for uppercase: false and lowercase: false #4622 - * fix(query): don't run transforms on updateForExec() #4621 - * fix(query): handle id = 0 in findById #4610 - * fix(query): handle buffers in mergeClone #4609 - * fix(document): handle undefined with conditional validator for validateSync #4607 - * fix: upgrade to mongodb driver 2.2.11 #4581 - * docs(schematypes): clarify schema.path() #4518 - * fix(query): ensure path is defined before checking in timestamps #4514 - * fix(model): set version key in upsert #4505 - * fix(document): never depopulate top-level doc #3057 - * refactor: ensure sync for setting non-capped collections #2690 - -4.6.4 / 2016-10-16 -================== - * fix(query): cast $not correctly #4616 #4592 [prssn](https://github.com/prssn) - * fix: address issue with caching global plugins #4608 #4601 [TrejGun](https://github.com/TrejGun) - * fix(model): make sure to depopulate in insertMany #4590 - * fix(model): buffer autoIndex if bufferCommands disabled #4589 - * fix(populate): copy ids array before modifying #4585 - * feat(schema): add retainKeyOrder prop #4542 - * fix(document): return isModified true for children of direct modified paths #4528 - * fix(connection): add dropDatabase() helper #4490 - * fix(model): add usePushEach option for schemas #4455 - * docs(connections): add some warnings about buffering #4413 - * fix: add ability to set promise implementation in browser #4395 - -4.6.3 / 2016-10-05 -================== - * fix(document): ensure single nested docs get initialized correctly when setting nested paths #4578 - * fix: turn off transforms when writing nested docs to db #4574 - * fix(document): don't set single nested subdocs to null when removing parent doc #4566 - * fix(model): ensure versionKey gets set in insertMany #4561 - * fix(schema): handle typeKey in arrays #4548 - * feat(schema): set $implicitlyCreated on schema if created by interpretAsType #4443 - -4.6.2 / 2016-09-30 -================== - * chore: upgrade to async 2.0.1 internally #4579 [billouboq](https://github.com/billouboq) - * fix(types): ensure nested single doc schema errors reach update validators #4557 #4519 - * fix(connection): handle rs names with leading numbers (muri 1.1.1) #4556 - * fix(model): don't throw if method name conflicts with Object.prototype prop #4551 - * docs: fix broken link #4544 [VFedyk](https://github.com/VFedyk) - * fix: allow overwriting model on mongoose singleton #4541 [Nainterceptor](https://github.com/Nainterceptor) - * fix(document): don't use init: true when building doc defaults #4540 - * fix(connection): use replSet option if replset not specified #4535 - * fix(query): cast $not objects #4495 - -4.6.1 / 2016-09-20 -================== - * fix(query): improve handling of $not with $elemMatch #4531 #3719 [timbowhite](https://github.com/timbowhite) - * fix: upgrade mongodb -> 2.2.10 #4517 - * chore: fix webpack build issue #4512 [saiichihashimoto](https://github.com/saiichihashimoto) - * fix(query): emit error on next tick when exec callback errors #4500 - * test: improve test case #4496 [isayme](https://github.com/isayme) - * fix(schema): use same check for array types and top-level types #4493 - * style: fix indentation in docs #4489 [dhurlburtusa](https://github.com/dhurlburtusa) - * fix(schema): expose original object passed to constructor #4486 - * fix(query): handle findOneAndUpdate with array of arrays #4484 #4470 [fedotov](https://github.com/fedotov) - * feat(document): add $ignore to make a path ignored #4480 - * fix(query): properly handle setting single embedded in update #4475 #4466 #4465 - * fix(updateValidators): handle single nested schema subpaths correctly #4479 - * fix(model): throw handy error when method name conflicts with property name #4475 - * fix(schema): handle .set() with array field #4472 - * fix(query): check nested path when avoiding double-validating Mixed #4441 - * fix(schema): handle calling path.trim() with no args correctly #4042 - -4.6.0 / 2016-09-02 -================== - * docs(document): clarify the findById and findByIdAndUpdate examples #4471 [mdcanham](https://github.com/mdcanham) - * docs(schematypes): add details re: options #4452 - * docs(middleware): add docs for insertMany hooks #4451 - * fix(schema): create new array when copying from existing object to preserve change tracking #4449 - * docs: fix typo in index.jade #4448 - * fix(query): allow array for populate options #4446 - * fix(model): create should not cause unhandle reject promise #4439 - * fix: upgrade to mongodb driver 2.2.9 #4363 #4341 #4311 (see [comments here](https://github.com/mongodb/js-bson/commit/aa0b54597a0af28cce3530d2144af708e4b66bf0#commitcomment-18850498) if you use node 0.10) - -4.5.10 / 2016-08-23 -=================== - * docs: fix typo on documents.jade #4444 [Gabri3l](https://github.com/Gabri3l) - * chore: upgrade mocha to 3.0.2 #4437 [TrejGun](https://github.com/TrejGun) - * fix: subdocuments causing error with parent timestamp on update #4434 [dyang108](https://github.com/dyang108) - * fix(query): don't crash if timestamps on and update doesn't have a path #4425 #4424 #4418 - * fix(query): ensure single nested subdoc is hydrated when running update validators #4420 - * fix(query): cast non-$geometry operators for $geoWithin #4419 - * docs: update contributor count #4415 [AdamZaczek](https://github.com/AdamZaczek) - * docs: add more clarification re: the index event #4410 - * fix(document): only skip modifying subdoc path if parent is direct modified #4405 - * fix(schema): throw cast error if provided date invalid #4404 - * feat(error): use util.inspect() so CastError never prints "[object Object]" #4398 - * fix(model): dont error if the discriminator key is unchanged #4387 - * fix(query): don't throw unhandled rejection with bluebird when using cbs #4379 - -4.5.9 / 2016-08-14 -================== - * docs: add mixed schema doc for Object literal #4400 [Kikobeats](https://github.com/Kikobeats) - * fix(query): cast $geoWithin and convert mongoose objects to POJOs before casting #4392 - * fix(schematype): dont cast defaults without parent doc #4390 - * fix(query): disallow passing empty string to findOne() #4378 - * fix(document): set single nested doc isNew correctly #4369 - * fix(types): checks field name correctly with nested arrays and populate #4365 - * fix(drivers): make debug output copy-pastable into mongodb shell #4352 - * fix(services): run update validators on nested paths #4332 - * fix(model): handle typeKey with discriminators #4339 - * fix(query): apply timestamps to child schemas when explicitly specified in update #4049 - * fix(schema): set prefix as nested path with add() #1730 - -4.5.8 / 2016-08-01 -================== - * fix(model): make changing the discriminator key cause a cast error #4374 - * fix(query): pass projection fields to cursor #4371 #4342 [Corei13](https://github.com/Corei13) - * fix(document): support multiple paths for isModified #4370 [adambuczynski](https://github.com/adambuczynski) - * fix(querycursor): always cast fields before returning cursor #4355 - * fix(query): support projection as alias for fields in findOneAndUpdate #4315 - * fix(schema): treat index false + unique false as no index #4304 - * fix(types): dont mark single nested subpath as modified if whole doc already modified #4224 - -4.5.7 / 2016-07-25 -================== - * fix(document): ensure no unhandled rejections if callback specified for save #4364 - -4.5.6 / 2016-07-23 -================== - * fix(schema): don't overwrite createdAt if it isn't selected #4351 [tusbar](https://github.com/tusbar) - * docs(api): fix link to populate() and add a new one from depopulate() #4345 [Delapouite](https://github.com/Delapouite) - * fix(types): ownerDocument() works properly with single nested docs #4344 [vichle](https://github.com/vichle) - * fix(populate): dont use findOne when justOne option set #4329 - * fix(document): dont trigger .then() deprecated warning when calling doc.remove() #4291 - * docs(connection): add promiseLibrary option #4280 - * fix(plugins): apply global plugins to subschemas #4271 - * fix(model): ensure `ensureIndex()` never calls back in the same tick #4246 - * docs(schema): improve post hook docs on schema #4238 - -4.5.5 / 2016-07-18 -================== - * fix(document): handle setting root to empty obj if minimize false #4337 - * fix: downgrade to mongodb 2.1.18 #4335 #4334 #4328 #4323 - * perf(types): remove defineProperty usage in documentarray #4333 - * fix(query): correctly pass model in .toConstructor() #4318 - * fix(services): avoid double-validating mixed types with update validators #4305 - * docs(middleware): add docs describing error handling middleware #4229 - * fix(types): throw correct error when invalidating doc array #3602 - -4.5.4 / 2016-07-11 -================== - * fix(types): fix removing embedded documents #4309 [RoCat](https://github.com/RoCat) - * docs: various docs improvements #4302 #4294 [simonxca](https://github.com/simonxca) - * fix: upgrade mongodb -> 2.1.21 #4295 #4202 [RoCat](https://github.com/RoCat) - * fix(populate): convert single result to array for virtual populate because of lean #4288 - * fix(populate): handle empty results for populate virtuals properly #4285 #4284 - * fix(query): dont cast $inc to number if type is long #4283 - * fix(types): allow setting single nested doc to null #4281 - * fix(populate): handle deeply nested virtual populate #4278 - * fix(document): allow setting empty obj if strict mode is false #4274 - * fix(aggregate): allow passing obj to .unwind() #4239 - * docs(document): add return statements to transform examples #1963 - -4.5.3 / 2016-06-30 -================== - * fix(query): pass correct options to QueryCursor #4277 #4266 - * fix(querycursor): handle lean option correctly #4276 [gchudnov](https://github.com/gchudnov) - * fix(document): fix error handling when no error occurred #4275 - * fix(error): use strict mode for version error #4272 - * docs(populate): fix crashing compilation for populate.jade #4267 - * fix(populate): support `justOne` option for populate virtuals #4263 - * fix(populate): ensure model param gets used for populate virtuals #4261 #4243 - * fix(querycursor): add ability to properly close the cursor #4258 - * docs(model): correct link to Document #4250 - * docs(populate): correct path for refPath populate #4240 - * fix(document): support validator.isEmail as validator #4064 - -4.5.2 / 2016-06-24 -================== - * fix(connection): add checks for collection presence for `onOpen` and `onClose` #4259 [nodkz](https://github.com/nodkz) - * fix(cast): allow strings for $type operator #4256 - * fix(querycursor): support lean() #4255 [pyramation](https://github.com/pyramation) - * fix(aggregate): allow setting noCursorTimeout option #4241 - * fix(document): handle undefined for Array.pull #4222 [Sebmaster](https://github.com/Sebmaster) - * fix(connection): ensure promise.catch() catches initial connection error #4135 - * fix(document): show additional context for VersionError #2633 - -4.5.1 / 2016-06-18 -================== - * fix(model): ensure wrapped insertMany() returns a promise #4237 - * fix(populate): dont overwrite populateVirtuals when populating multiple paths #4234 - * docs(model): clarify relationship between create() and save() #4233 - * fix(types): handle option param in subdoc remove() #4231 [tdebarochez](https://github.com/tdebarochez) - * fix(document): dedupe modified paths #4226 #4223 [adambuczynski](https://github.com/adambuczynski) - * fix(model): don't modify user-provided options object #4221 - * fix(document): handle setting nested path to empty object #4218 #4182 - * fix(document): clean subpaths when removing single nested #4216 - * fix(document): don't force transform on subdocs with inspect #4213 - * fix(error): allow setting .messages object #4207 - -4.5.0 / 2016-06-13 -================== - * feat(query): added Query.prototype.catch() #4215 #4173 [adambuczynski](https://github.com/adambuczynski) - * feat(query): add Query.prototype.cursor() as a .stream() alternative #4117 #3637 #1907 - * feat(document): add markUnmodified() function #4092 [vincentcr](https://github.com/vincentcr) - * feat(aggregate): convert aggregate object to a thenable #3995 #3946 [megagon](https://github.com/megagon) - * perf(types): remove defineProperties call for array (**Note:** Because of this, a mongoose array will no longer `assert.deepEqual()` a plain old JS array) #3886 - * feat(model): add hooks for insertMany() #3846 - * feat(schema): add support for custom query methods #3740 #2372 - * feat(drivers): emit error on 'serverClosed' because that means that reconnect failed #3615 - * feat(model): emit error event when callback throws exception #3499 - * feat(model): inherit options from discriminator base schema #3414 #1818 - * feat(populate): expose mongoose-populate-virtuals inspired populate API #2562 - * feat(document): trigger remove hooks on subdocs when removing parent #2348 - * feat(schema): add support for express-style error handling middleware #2284 - * fix(model): disallow setting discriminator key #2041 - * feat(schema): add support for nested arrays #1361 - -4.4.20 / 2016-06-05 -=================== - * docs: clarify command buffering when using driver directly #4195 - * fix(promise): correct broken mpromise .catch() #4189 - * fix(document): clean modified subpaths when set path to empty obj #4182 - * fix(query): support minDistance with query casting and `.near()` #4179 - * fix(model): remove unnecessary .save() promise #4177 - * fix(schema): cast all valid ObjectId strings to object ids #3365 - * docs: remove unclear "unsafe" term in query docs #3282 - -4.4.19 / 2016-05-21 -=================== - * fix(model): handle insertMany if timestamps not set #4171 - -4.4.18 / 2016-05-21 -=================== - * docs: add missing period #4170 [gitname](https://github.com/gitname) - * docs: change build badge to svg #4158 [a0viedo](https://github.com/a0viedo) - * fix(model): update timestamps when setting `createdAt` #4155 - * fix(utils): make sure to require in document properly #4152 - * fix(model): throw overwrite error when discriminator name conflicts #4148 - -4.4.17 / 2016-05-13 -=================== - * docs: remove repetition in QueryStream docs #4147 [hugoabonizio](https://github.com/hugoabonizio) - * fix(document): dont double-validate doc array elements #4145 - * fix(document): call required function with correct scope #4142 [JedWatson](https://github.com/JedWatson) - -4.4.16 / 2016-05-09 -=================== - * refactor(document): use function reference #4133 [dciccale](https://github.com/dciccale) - * docs(querystream): clarify `destroy()` and close event #4126 [AnthonyCC](https://github.com/AnthonyCC) - * test: make before hook fail fast if it can't connect #4121 - * docs: add description of CastError constructor params #4120 - * fix(schematype): ensure single embedded defaults have $parent #4115 - * fix(document): mark nested paths for validation #4111 - * fix(schema): make sure element is always a subdoc in doc array validation #3816 - -4.4.15 / 2016-05-06 -=================== - * fix(schema): support overwriting array default #4109 - * fix(populate): assign values when resolving each populate #4104 - * fix(aggregate): dont send async option to server #4101 - * fix(model): ensure isNew set to false after insertMany #4099 - * fix(connection): emit on error if listeners and no callback #4098 - * fix(document): treat required fn that returns false as required: false #4094 - -4.4.14 / 2016-04-27 -=================== - * fix: upgrade mongodb -> 2.1.18 #4102 - * feat(connection): allow setting mongos as a uri query param #4093 #4035 [burtonjc](https://github.com/burtonjc) - * fix(populate): make sure to use correct assignment order for each model #4073 - * fix(schema): add complete set of geospatial operators for single embedded subdocs #4014 - -3.8.40 / 2016-04-24 -=================== - * upgraded; mquery -> 1.10.0 #3989 - -4.4.13 / 2016-04-21 -=================== - * docs: add docs favicons #4082 [robertjustjones](https://github.com/robertjustjones) - * docs(model): correct Model.remove() return value #4075 [Jokero](https://github.com/Jokero) - * fix(query): add $geoWithin query casting for single embedded docs #4044 - * fix(schema): handle setting trim option to falsy #4042 - * fix(query): handle setDefaultsOnInsert with empty update #3835 - -4.4.12 / 2016-04-08 -=================== - * docs(query): document context option for update and findOneAndUpdate #4055 - * docs(query): correct link to $geoWithin docs #4050 - * fix(project): upgrade to mongodb driver 2.1.16 #4048 [schmalliso](https://github.com/schmalliso) - * docs(validation): fix validation docs #4028 - * fix(types): improve .id() check for document arrays #4011 - * fix(query): remove premature return when using $rename #3171 - * docs(connection): clarify relationship between models and connections #2157 - -4.4.11 / 2016-04-03 -=================== - * fix: upgrade to mongodb driver 2.1.14 #4036 #4030 #3945 - * fix(connection): allow connecting with { mongos: true } to handle query params #4032 [burtonjc](https://github.com/burtonjc) - * docs(connection): add autoIndex example #4026 [tilleps](https://github.com/tilleps) - * fix(query): handle passRawResult option when zero results #4023 - * fix(populate): clone options before modifying #4022 - * docs: add missing whitespace #4019 [chenxsan](https://github.com/chenxsan) - * chore: upgrade to ESLint 2.4.0 #4015 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix(types): single nested subdocs get ids by default #4008 - * chore(project): add dependency status badge #4007 [Maheshkumar-Kakade](http://github.com/Maheshkumar-Kakade) - * fix: make sure timestamps don't trigger unnecessary updates #4005 #3991 [tommarien](https://github.com/tommarien) - * fix(document): inspect inherits schema options #4001 - * fix(populate): don't mark populated path as modified if setting to object w/ same id #3992 - * fix(document): support kind argument to invalidate #3965 - -4.4.10 / 2016-03-24 -=================== - * fix(document): copy isNew when copying a document #3982 - * fix(document): don't override defaults with undefined keys #3981 - * fix(populate): merge multiple deep populate options for the same path #3974 - -4.4.9 / 2016-03-22 -================== - * fix: upgrade mongodb -> 2.1.10 re https://jira.mongodb.org/browse/NODE-679 #4010 - * docs: add syntax highlighting for acquit examples #3975 - -4.4.8 / 2016-03-18 -================== - * docs(aggregate): clarify promises #3990 [megagon](https://github.com/megagon) - * fix: upgrade mquery -> 1.10 #3988 [matskiv](https://github.com/matskiv) - * feat(connection): 'all' event for repl sets #3986 [xizhibei](https://github.com/xizhibei) - * docs(types): clarify Array.pull #3985 [seriousManual](https://github.com/seriousManual) - * feat(query): support array syntax for .sort() via mquery 1.9 #3980 - * fix(populate): support > 3 level nested populate #3973 - * fix: MongooseThenable exposes connection correctly #3972 - * docs(connection): add note about reconnectTries and reconnectInterval #3969 - * feat(document): invalidate returns the new validationError #3964 - * fix(query): .eq() as shorthand for .equals #3953 [Fonger](https://github.com/Fonger) - * docs(connection): clarify connection string vs passed options #3941 - * docs(query): select option for findOneAndUpdate #3933 - * fix(error): ValidationError.properties no longer enumerable #3925 - * docs(validation): clarify how required validators work with nested schemas #3915 - * fix: upgrade mongodb driver -> 2.1.8 to make partial index errors more sane #3864 - -4.4.7 / 2016-03-11 -================== - * fix(query): stop infinite recursion caused by merging a mongoose buffer #3961 - * fix(populate): handle deep populate array -> array #3954 - * fix(schema): allow setting timestamps with .set() #3952 #3951 #3907 [Fonger](https://github.com/Fonger) - * fix: MongooseThenable doesn't overwrite constructors #3940 - * fix(schema): don't cast boolean to date #3935 - * fix(drivers): support sslValidate in connection string #3929 - * fix(types): correct markModified() for single nested subdocs #3910 - * fix(drivers): catch and report any errors that occur in driver methods #3906 - * fix(populate): get subpopulate model correctly when array under nested #3904 - * fix(document): allow fields named 'pre' and 'post' #3902 - * docs(query): clarify runValidators and setDefaultsOnInsert options #3892 - * docs(validation): show how to use custom required messages in schema #2616 - -4.4.6 / 2016-03-02 -================== - * fix: upgrade mongodb driver to 2.1.7 #3938 - * docs: fix plugins link #3917 #3909 [fbertone](https://github.com/fbertone) - * fix(query): sort+select with count works #3914 - * fix(query): improve mergeUpdate's ability to handle nested docs #3890 - -4.4.5 / 2016-02-24 -================== - * fix(query): ability to select a length field (upgrade to mquery 1.7.0) #3903 - * fix: include nested CastError as reason for array CastError #3897 [kotarou3](https://github.com/kotarou3) - * fix(schema): check for doc existence before taking fields #3889 - * feat(schema): useNestedStrict option to take nested strict mode for update #3883 - * docs(validation): clarify relationship between required and checkRequired #3822 - * docs(populate): dynamic reference docs #3809 - * docs: expand dropdown when clicking on file name #3807 - * docs: plugins.mongoosejs.io is up #3127 - * fix(schema): ability to add a virtual with same name as removed path #2398 - -4.4.4 / 2016-02-17 -================== - * fix(schema): handle field selection when casting single nested subdocs #3880 - * fix(populate): populating using base model with multiple child models in result #3878 - * fix: ability to properly use return value of `mongoose.connect()` #3874 - * fix(populate): dont hydrate populated subdoc if lean option set #3873 - * fix(connection): dont re-auth if already connected with useDb #3871 - * docs: cover how to set underlying driver's promise lib #3869 - * fix(document): handle conflicting names in validation errors with subdocs #3867 - * fix(populate): set undefined instead of null consistently when populate couldn't find results #3859 - * docs: link to `execPopulate()` in `doc.populate()` docs #3836 - * docs(plugin): link to the `mongoose.plugin()` function #3732 - -4.4.3 / 2016-02-09 -================== - * fix: upgrade to mongodb 2.1.6 to remove kerberos log output #3861 #3860 [cartuchogl](https://github.com/cartuchogl) - * fix: require('mongoose') is no longer a pseudo-promise #3856 - * fix(query): update casting for single nested docs #3820 - * fix(populate): deep populating multiple paths with same options #3808 - * docs(middleware): clarify save/validate hook order #1149 - -4.4.2 / 2016-02-05 -================== - * fix(aggregate): handle calling .cursor() with no options #3855 - * fix: upgrade mongodb driver to 2.1.5 for GridFS memory leak fix #3854 - * docs: fix schematype.html conflict #3853 #3850 #3843 - * fix(model): bluebird unhandled rejection with ensureIndexes() on init #3837 - * docs: autoIndex option for createConnection #3805 - -4.4.1 / 2016-02-03 -================== - * fix: linting broke some cases where we use `== null` as shorthand #3852 - * docs: fix up schematype.html conflict #3848 #3843 [mynameiscoffey](https://github.com/mynameiscoffey) - * fix: backwards breaking change with `.connect()` return value #3847 - * docs: downgrade dox and highlight.js to fix docs build #3845 - * docs: clean up typo #3842 [Flash-](https://github.com/Flash-) - * fix(document): storeShard handles undefined values #3841 - * chore: more linting #3838 [TrejGun](https://github.com/TrejGun) - * fix(schema): handle `text: true` as a way to declare a text index #3824 - -4.4.0 / 2016-02-02 -================== - * docs: fix expireAfterSeconds index option name #3831 [Flash-](https://github.com/Flash-) - * chore: run lint after test #3829 [ChristianMurphy](https://github.com/ChristianMurphy) - * chore: use power-assert instead of assert #3828 [TrejGun](https://github.com/TrejGun) - * chore: stricter lint #3827 [TrejGun](https://github.com/TrejGun) - * feat(types): casting moment to date #3813 [TrejGun](https://github.com/TrejGun) - * chore: comma-last lint for test folder #3810 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix: upgrade async mpath, mpromise, muri, and sliced #3801 [TrejGun](https://github.com/TrejGun) - * fix(query): geo queries now return proper ES2015 promises #3800 [TrejGun](https://github.com/TrejGun) - * perf(types): use `Object.defineProperties()` for array #3799 [TrejGun](https://github.com/TrejGun) - * fix(model): mapReduce, ensureIndexes, remove, and save properly return ES2015 promises #3795 #3628 #3595 [TrejGun](https://github.com/TrejGun) - * docs: fixed dates in History.md #3791 [Jokero](https://github.com/Jokero) - * feat: connect, open, openSet, and disconnect return ES2015 promises #3790 #3622 [TrejGun](https://github.com/TrejGun) - * feat: custom type for int32 via mongoose-int32 npm package #3652 #3102 - * feat: basic custom schema type API #995 - * feat(model): `insertMany()` for more performant bulk inserts #723 - -4.3.7 / 2016-01-23 -================== - * docs: grammar fix in timestamps docs #3786 [zclancy](https://github.com/zclancy) - * fix(document): setting nested populated docs #3783 [slamuu](https://github.com/slamuu) - * fix(document): don't call post save hooks twice for pushed docs #3780 - * fix(model): handle `_id=0` correctly #3776 - * docs(middleware): async post hooks #3770 - * docs: remove confusing sentence #3765 [marcusmellis89](https://github.com/marcusmellis89) - -3.8.39 / 2016-01-15 -=================== - * fixed; casting a number to a buffer #3764 - * fixed; enumerating virtual property with nested objects #3743 [kusold](https://github.com/kusold) - -4.3.6 / 2016-01-15 -================== - * fix(types): casting a number to a buffer #3764 - * fix: add "listener" to reserved keywords #3759 - * chore: upgrade uglify #3757 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix: broken execPopulate() in 4.3.5 #3755 #3753 - * fix: ability to remove() a single embedded doc #3754 - * style: comma-last in test folder #3751 [ChristianMurphy](https://github.com/ChristianMurphy) - * docs: clarify versionKey option #3747 - * fix: improve colorization for arrays #3744 [TrejGun](https://github.com/TrejGun) - * fix: webpack build #3713 - -4.3.5 / 2016-01-09 -================== - * fix(query): throw when 4th parameter to update not a function #3741 [kasselTrankos](https://github.com/kasselTrankos) - * fix(document): separate error type for setting an object to a primitive #3735 - * fix(populate): Model.populate returns ES6 promise #3734 - * fix(drivers): re-register event handlers after manual reconnect #3729 - * docs: broken links #3727 - * fix(validation): update validators run array validation #3724 - * docs: clarify the need to use markModified with in-place date ops #3722 - * fix(document): mark correct path as populated when manually populating array #3721 - * fix(aggregate): support for array pipeline argument to append #3718 [dbkup](https://github.com/dbkup) - * docs: clarify `.connect()` callback #3705 - * fix(schema): properly validate nested single nested docs #3702 - * fix(types): handle setting documentarray of wrong type #3701 - * docs: broken links #3700 - * fix(drivers): debug output properly displays '0' #3689 - -3.8.38 / 2016-01-07 -=================== - * fixed; aggregate.append an array #3730 [dbkup](https://github.com/dbkup) - -4.3.4 / 2015-12-23 -================== - * fix: upgrade mongodb driver to 2.1.2 for repl set error #3712 [sansmischevia](https://github.com/sansmischevia) - * docs: validation docs typo #3709 [ivanmaeder](https://github.com/ivanmaeder) - * style: remove unused variables #3708 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix(schema): duck-typing for schemas #3703 [mgcrea](https://github.com/mgcrea) - * docs: connection sample code issue #3697 - * fix(schema): duck-typing for schemas #3693 [mgcrea](https://github.com/mgcrea) - * docs: clarify id schema option #3638 - -4.3.3 / 2015-12-18 -================== - * fix(connection): properly support 'replSet' as well as 'replset' #3688 [taxilian](https://github.com/taxilian) - * fix(document): single nested doc pre hooks called before nested doc array #3687 [aliatsis](https://github.com/aliatsis) - -4.3.2 / 2015-12-17 -================== - * fix(document): .set() into single nested schemas #3686 - * fix(connection): support 'replSet' as well as 'replset' option #3685 - * fix(document): bluebird unhandled rejection when validating doc arrays #3681 - * fix(document): hooks for doc arrays in single nested schemas #3680 - * fix(document): post hooks for single nested schemas #3679 - * fix: remove unused npm module #3674 [sybarite](https://github.com/sybarite) - * fix(model): don't swallow exceptions in nested doc save callback #3671 - * docs: update keepAlive info #3667 [ChrisZieba](https://github.com/ChrisZieba) - * fix(document): strict 'throw' throws a specific mongoose error #3662 - * fix: flakey test #3332 - * fix(query): more robust check for RegExp #2969 - -4.3.1 / 2015-12-11 -================== - * feat(aggregate): `.sample()` helper #3665 - * fix(query): bitwise query operators with buffers #3663 - * docs(migration): clarify `new` option and findByIdAndUpdate #3661 - -4.3.0 / 2015-12-09 -================== - * feat(query): support for mongodb 3.2 bitwise query operators #3660 - * style: use comma-last style consistently #3657 [ChristianMurphy](https://github.com/ChristianMurphy) - * feat: upgrade mongodb driver to 2.1.0 for full MongoDB 3.2 support #3656 - * feat(aggregate): `.lookup()` helper #3532 - -4.2.10 / 2015-12-08 -=================== - * fixed; upgraded marked #3653 [ChristianMurphy](https://github.com/ChristianMurphy) - * docs; cross-db populate #3648 - * docs; update mocha URL #3646 [ojhaujjwal](https://github.com/ojhaujjwal) - * fixed; call close callback asynchronously #3645 - * docs; virtuals.html issue #3644 [Psarna94](https://github.com/Psarna94) - * fixed; single embedded doc casting on init #3642 - * docs; validation docs improvements #3640 - -4.2.9 / 2015-12-02 -================== - * docs; defaults docs #3625 - * fix; nested numeric keys causing an embedded document crash #3623 - * fix; apply path getters before virtual getters #3618 - * fix; casting for arrays in single nested schemas #3616 - -4.2.8 / 2015-11-25 -================== - * docs; clean up README links #3612 [ReadmeCritic](https://github.com/ReadmeCritic) - * fix; ESLint improvements #3605 [ChristianMurphy](https://github.com/ChristianMurphy) - * fix; assigning single nested subdocs #3601 - * docs; describe custom logging functions in `mongoose.set()` docs #3557 - -4.2.7 / 2015-11-20 -================== - * fixed; readPreference connection string option #3600 - * fixed; pulling from manually populated arrays #3598 #3579 - * docs; FAQ about OverwriteModelError #3597 [stcruy](https://github.com/stcruy) - * fixed; setting single embedded schemas to null #3596 - * fixed; indexes for single embedded schemas #3594 - * docs; clarify projection for `findOne()` #3593 [gunar](https://github.com/gunar) - * fixed; .ownerDocument() method on single embedded schemas #3589 - * fixed; properly throw casterror for query on single embedded schema #3580 - * upgraded; mongodb driver -> 2.0.49 for reconnect issue fix #3481 - -4.2.6 / 2015-11-16 -================== - * fixed; ability to manually populate an array #3575 - * docs; clarify `isAsync` parameter to hooks #3573 - * fixed; use captureStackTrace if possible instead #3571 - * fixed; crash with buffer and update validators #3565 [johnpeb](https://github.com/johnpeb) - * fixed; update casting with operators overwrite: true #3564 - * fixed; validation with single embedded docs #3562 - * fixed; inline docs inherit parents $type key #3560 - * docs; bad grammar in populate docs #3559 [amaurymedeiros](https://github.com/amaurymedeiros) - * fixed; properly handle populate option for find() #2321 - -3.8.37 / 2015-11-16 -=================== - * fixed; use retainKeyOrder for cloning update op #3572 - -4.2.5 / 2015-11-09 -================== - * fixed; handle setting fields in pre update hooks with exec #3549 - * upgraded; ESLint #3547 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; bluebird unhandled rejections with cast errors and .exec #3543 - * fixed; min/max validators handling undefined #3539 - * fixed; standalone mongos connections #3537 - * fixed; call `.toObject()` when setting a single nested doc #3535 - * fixed; single nested docs now have methods #3534 - * fixed; single nested docs with .create() #3533 #3521 [tusbar](https://github.com/tusbar) - * docs; deep populate docs #3528 - * fixed; deep populate schema ref handling #3507 - * upgraded; mongodb driver -> 2.0.48 for sort overflow issue #3493 - * docs; clarify default ids for discriminators #3482 - * fixed; properly support .update(doc) #3221 - -4.2.4 / 2015-11-02 -================== - * fixed; upgraded `ms` package for security vulnerability #3524 [fhemberger](https://github.com/fhemberger) - * fixed; ESlint rules #3517 [ChristianMurphy](https://github.com/ChristianMurphy) - * docs; typo in aggregation docs #3513 [rafakato](https://github.com/rafakato) - * fixed; add `dontThrowCastError` option to .update() for promises #3512 - * fixed; don't double-cast buffers in node 4.x #3510 #3496 - * fixed; population with single embedded schemas #3501 - * fixed; pre('set') hooks work properly #3479 - * docs; promises guide #3441 - -4.2.3 / 2015-10-26 -================== - * docs; remove unreferenced function in middleware.jade #3506 - * fixed; handling auth with no username/password #3500 #3498 #3484 [mleanos](https://github.com/mleanos) - * fixed; more ESlint rules #3491 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; swallowing exceptions in save callback #3478 - * docs; fixed broken links in subdocs guide #3477 - * fixed; casting booleans to numbers #3475 - * fixed; report CastError for subdoc arrays in findOneAndUpdate #3468 - * fixed; geoNear returns ES6 promise #3458 - -4.2.2 / 2015-10-22 -================== - * fixed; go back to old pluralization code #3490 - -4.2.1 / 2015-10-22 -================== - * fixed; pluralization issues #3492 [ChristianMurphy](https://github.com/ChristianMurphy) - -4.2.0 / 2015-10-22 -================== - * added; support for skipVersioning for document arrays #3467 [chazmo03](https://github.com/chazmo03) - * added; ability to customize schema 'type' key #3459 #3245 - * fixed; writeConcern for index builds #3455 - * added; emit event when individual index build starts #3440 [objectiveSee](https://github.com/objectiveSee) - * added; 'context' option for update validators #3430 - * refactor; pluralization now in separate pluralize-mongoose npm module #3415 [ChristianMurphy](https://github.com/ChristianMurphy) - * added; customizable error validation messages #3406 [geronime](https://github.com/geronime) - * added; support for passing 'minimize' option to update #3381 - * added; ability to customize debug logging format #3261 - * added; baseModelName property for discriminator models #3202 - * added; 'emitIndexErrors' option #3174 - * added; 'async' option for aggregation cursor to support buffering #3160 - * added; ability to skip validation for individual save() calls #2981 - * added; single embedded schema support #2689 #585 - * added; depopulate function #2509 - -4.1.12 / 2015-10-19 -=================== - * docs; use readPreference instead of slaveOk for Query.setOptions docs #3471 [buunguyen](https://github.com/buunguyen) - * fixed; more helpful error when regexp contains null bytes #3456 - * fixed; x509 auth issue #3454 [NoxHarmonium](https://github.com/NoxHarmonium) - -3.8.36 / 2015-10-18 -=================== - * fixed; Make array props non-enumerable #3461 [boblauer](https://github.com/boblauer) - -4.1.11 / 2015-10-12 -=================== - * fixed; update timestamps for update() if they're enabled #3450 [isayme](https://github.com/isayme) - * fixed; unit test error on node 0.10 #3449 [isayme](https://github.com/isayme) - * docs; timestamp option docs #3448 [isayme](https://github.com/isayme) - * docs; fix unexpected indent #3443 [isayme](https://github.com/isayme) - * fixed; use ES6 promises for Model.prototype.remove() #3442 - * fixed; don't use unused 'safe' option for index builds #3439 - * fixed; elemMatch casting bug #3437 #3435 [DefinitelyCarter](https://github.com/DefinitelyCarter) - * docs; schema.index docs #3434 - * fixed; exceptions in save() callback getting swallowed on mongodb 2.4 #3371 - -4.1.10 / 2015-10-05 -=================== - * docs; improve virtuals docs to explain virtuals schema option #3433 [zoyaH](https://github.com/zoyaH) - * docs; MongoDB server version compatibility guide #3427 - * docs; clarify that findById and findByIdAndUpdate fire hooks #3422 - * docs; clean up Model.save() docs #3420 - * fixed; properly handle projection with just id #3407 #3412 - * fixed; infinite loop when database document is corrupted #3405 - * docs; clarify remove middleware #3388 - -4.1.9 / 2015-09-28 -================== - * docs; minlength and maxlength string validation docs #3368 #3413 [cosmosgenius](https://github.com/cosmosgenius) - * fixed; linting for infix operators #3397 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; proper casting for $all #3394 - * fixed; unhandled rejection warnings with .create() #3391 - * docs; clarify update validators on paths that aren't explicitly set #3386 - * docs; custom validator examples #2778 - -4.1.8 / 2015-09-21 -================== - * docs; fixed typo in example #3390 [kmctown](https://github.com/kmctown) - * fixed; error in toObject() #3387 [guumaster](https://github.com/guumaster) - * fixed; handling for casting null dates #3383 [alexmingoia](https://github.com/alexmingoia) - * fixed; passing composite ids to `findByIdAndUpdate` #3380 - * fixed; linting #3376 #3375 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; added NodeJS v4 to Travis #3374 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; casting $elemMatch inside of $not #3373 [gaguirre](https://github.com/gaguirre) - * fixed; handle case where $slice is 0 #3369 - * fixed; avoid running getters if path is populated #3357 - * fixed; cast documents to objects when setting to a nested path #3346 - -4.1.7 / 2015-09-14 -================== - * docs; typos in SchemaType documentation #3367 [jasson15](https://github.com/jasson15) - * fixed; MONGOOSE_DRIVER_PATH env variable again #3360 - * docs; added validateSync docs #3353 - * fixed; set findOne op synchronously in query #3344 - * fixed; handling for `.pull()` on a documentarray without an id #3341 - * fixed; use natural order for cloning update conditions #3338 - * fixed; issue with strict mode casting for mixed type updates #3337 - -4.1.6 / 2015-09-08 -================== - * fixed; MONGOOSE_DRIVER_PATH env variable #3345 [g13013](https://github.com/g13013) - * docs; global autoIndex option #3335 [albertorestifo](https://github.com/albertorestifo) - * docs; model documentation typos #3330 - * fixed; report reason for CastError #3320 - * fixed; .populate() no longer returns true after re-assigning #3308 - * fixed; discriminators with aggregation geoNear #3304 - * docs; discriminator docs #2743 - -4.1.5 / 2015-09-01 -================== - * fixed; document.remove() removing all docs #3326 #3325 - * fixed; connect() checks for rs_name in options #3299 - * docs; examples for schema.set() #3288 - * fixed; checkKeys issue with bluebird #3286 [gregthegeek](https://github.com/gregthegeek) - -4.1.4 / 2015-08-31 -================== - * fixed; ability to set strict: false for update #3305 - * fixed; .create() properly uses ES6 promises #3297 - * fixed; pre hooks on nested subdocs #3291 #3284 [aliatsis](https://github.com/aliatsis) - * docs; remove unclear text in .remove() docs #3282 - * fixed; pre hooks called twice for 3rd-level nested doc #3281 - * fixed; nested transforms #3279 - * upgraded; mquery -> 1.6.3 #3278 #3272 - * fixed; don't swallow callback errors by default #3273 #3222 - * fixed; properly get nested paths from nested schemas #3265 - * fixed; remove() with id undefined deleting all docs #3260 [thanpolas](https://github.com/thanpolas) - * fixed; handling for non-numeric projections #3256 - * fixed; findById with id undefined returning first doc #3255 - * fixed; use retainKeyOrder for update #3215 - * added; passRawResult option to findOneAndUpdate for backwards compat #3173 - -4.1.3 / 2015-08-16 -================== - * fixed; getUpdate() in pre update hooks #3520 [gregthegeek](https://github.com/gregthegeek) - * fixed; handleArray() ensures arg is an array #3238 [jloveridge](https://github.com/jloveridge) - * fixed; refresh required path cache when recreating docs #3199 - * fixed; $ operator on unwind aggregation helper #3197 - * fixed; findOneAndUpdate() properly returns raw result as third arg to callback #3173 - * fixed; querystream with dynamic refs #3108 - -3.8.35 / 2015-08-14 -=================== - * fixed; handling for minimize on nested objects #2930 - * fixed; don't crash when schema.path.options undefined #1824 - -4.1.2 / 2015-08-10 -================== - * fixed; better handling for Jade templates #3241 [kbadk](https://github.com/kbadk) - * added; ESlint trailing spaces #3234 [ChristianMurphy](https://github.com/ChristianMurphy) - * added; ESlint #3191 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; properly emit event on disconnect #3183 - * fixed; copy options properly using Query.toConstructor() #3176 - * fixed; setMaxListeners() issue in browser build #3170 - * fixed; node driver -> 2.0.40 to not store undefined keys as null #3169 - * fixed; update validators handle positional operator #3167 - * fixed; handle $all + $elemMatch query casting #3163 - * fixed; post save hooks don't swallow extra args #3155 - * docs; spelling mistake in index.jade #3154 - * fixed; don't crash when toObject() has no fields #3130 - * fixed; apply toObject() recursively for find and update queries #3086 [naoina](https://github.com/naoina) - -4.1.1 / 2015-08-03 -================== - * fixed; aggregate exec() crash with no callback #3212 #3198 [jpgarcia](https://github.com/jpgarcia) - * fixed; pre init hooks now properly synchronous #3207 [burtonjc](https://github.com/burtonjc) - * fixed; updateValidators doesn't flatten dates #3206 #3194 [victorkohl](https://github.com/victorkohl) - * fixed; default fields don't make document dirty between saves #3205 [burtonjc](https://github.com/burtonjc) - * fixed; save passes 0 as numAffected rather than undefined when no change #3195 [burtonjc](https://github.com/burtonjc) - * fixed; better handling for positional operator in update #3185 - * fixed; use Travis containers #3181 [ChristianMurphy](https://github.com/ChristianMurphy) - * fixed; leaked variable #3180 [ChristianMurphy](https://github.com/ChristianMurphy) - -4.1.0 / 2015-07-24 -================== - * added; `schema.queue()` now public #3193 - * added; raw result as third parameter to findOneAndX callback #3173 - * added; ability to run validateSync() on only certain fields #3153 - * added; subPopulate #3103 [timbur](https://github.com/timbur) - * added; $isDefault function on documents #3077 - * added; additional properties for built-in validator messages #3063 [KLicheR](https://github.com/KLicheR) - * added; getQuery() and getUpdate() functions for Query #3013 - * added; export DocumentProvider #2996 - * added; ability to remove path from schema #2993 [JohnnyEstilles](https://github.com/JohnnyEstilles) - * added; .explain() helper for aggregate #2714 - * added; ability to specify which ES6-compatible promises library mongoose uses #2688 - * added; export Aggregate #1910 - -4.0.8 / 2015-07-20 -================== - * fixed; assignment with document arrays #3178 [rosston](https://github.com/rosston) - * docs; remove duplicate paragraph #3164 [rhmeeuwisse](https://github.com/rhmeeuwisse) - * docs; improve findOneAndXYZ parameter descriptions #3159 [rhmeeuwisse](https://github.com/rhmeeuwisse) - * docs; add findOneAndRemove to list of supported middleware #3158 - * docs; clarify ensureIndex #3156 - * fixed; refuse to save/remove document without id #3118 - * fixed; hooks next() no longer accidentally returns promise #3104 - * fixed; strict mode for findOneAndUpdate #2947 - * added; .min.js.gz file for browser component #2806 - -3.8.34 / 2015-07-20 -=================== - * fixed; allow using $rename #3171 - * fixed; no longer modifies update arguments #3008 - -4.0.7 / 2015-07-11 -================== - * fixed; documentarray id method when using object id #3157 [siboulet](https://github.com/siboulet) - * docs; improve findById docs #3147 - * fixed; update validators handle null properly #3136 [odeke-em](https://github.com/odeke-em) - * docs; jsdoc syntax errors #3128 [rhmeeuwisse](https://github.com/rhmeeuwisse) - * docs; fix typo #3126 [rhmeeuwisse](https://github.com/rhmeeuwisse) - * docs; proper formatting in queries.jade #3121 [rhmeeuwisse](https://github.com/rhmeeuwisse) - * docs; correct example for string maxlength validator #3111 [rhmeeuwisse](https://github.com/rhmeeuwisse) - * fixed; setDefaultsOnInsert with arrays #3107 - * docs; LearnBoost -> Automattic in package.json #3099 - * docs; pre update hook example #3094 [danpe](https://github.com/danpe) - * docs; clarify query middleware example #3051 - * fixed; ValidationErrors in strict mode #3046 - * fixed; set findOneAndUpdate properties before hooks run #3024 - -3.8.33 / 2015-07-10 -=================== - * upgraded; node driver -> 1.4.38 - * fixed; dont crash when `match` validator undefined - -4.0.6 / 2015-06-21 -================== - * upgraded; node driver -> 2.0.34 #3087 - * fixed; apply setters on addToSet, etc #3067 [victorkohl](https://github.com/victorkohl) - * fixed; missing semicolons #3065 [sokolikp](https://github.com/sokolikp) - * fixed; proper handling for async doc hooks #3062 [gregthegeek](https://github.com/gregthegeek) - * fixed; dont set failed populate field to null if other docs are successfully populated #3055 [eloytoro](https://github.com/eloytoro) - * fixed; setDefaultsOnInsert with document arrays #3034 [taxilian](https://github.com/taxilian) - * fixed; setters fired on array items #3032 - * fixed; stop validateSync() on first error #3025 [victorkohl](https://github.com/victorkohl) - * docs; improve query docs #3016 - * fixed; always exclude _id when its deselected #3010 - * fixed; enum validator kind property #3009 - * fixed; mquery collection names #3005 - * docs; clarify mongos option #3000 - * docs; clarify that query builder has a .then() #2995 - * fixed; race condition in dynamic ref #2992 - -3.8.31 / 2015-06-20 -=================== - * fixed; properly handle text search with discriminators and $meta #2166 - -4.0.5 / 2015-06-05 -================== - * fixed; ObjectIds and buffers when mongodb driver is a sibling dependency #3050 #3048 #3040 #3031 #3020 #2988 #2951 - * fixed; warn user when 'increment' is used in schema #3039 - * fixed; setDefaultsOnInsert with array in schema #3035 - * fixed; dont use default Object toString to cast to string #3030 - * added; npm badge #3020 [odeke-em](https://github.com/odeke-em) - * fixed; proper handling for calling .set() with a subdoc #2782 - * fixed; dont throw cast error when using $rename on non-string path #1845 - -3.8.30 / 2015-06-05 -=================== - * fixed; enable users to set all options with tailable() #2883 - -4.0.4 / 2015-05-28 -================== - * docs; findAndModify new parameter correct default value #3012 [JonForest](https://github.com/JonForest) - * docs; clarify pluralization rules #2999 [anonmily](https://github.com/anonmily) - * fix; discriminators with schema methods #2978 - * fix; make `isModified` a schema reserved keyword #2975 - * fix; properly fire setters when initializing path with object #2943 - * fix; can use `setDefaultsOnInsert` without specifying `runValidators` #2938 - * fix; always set validation errors `kind` property #2885 - * upgraded; node driver -> 2.0.33 #2865 - -3.8.29 / 2015-05-27 -=================== - * fixed; Handle JSON.stringify properly for nested docs #2990 - -4.0.3 / 2015-05-13 -================== - * upgraded; mquery -> 1.5.1 #2983 - * docs; clarify context for query middleware #2974 - * docs; fix missing type -> kind rename in History.md #2961 - * fixed; broken ReadPreference include on Heroku #2957 - * docs; correct form for cursor aggregate option #2955 - * fixed; sync post hooks now properly called after function #2949 #2925 - * fixed; fix sub-doc validate() function #2929 - * upgraded; node driver -> 2.0.30 #2926 - * docs; retainKeyOrder for save() #2924 - * docs; fix broken class names #2913 - * fixed; error when using node-clone on a doc #2909 - * fixed; no more hard references to bson #2908 #2906 - * fixed; dont overwrite array values #2907 [naoina](https://github.com/naoina) - * fixed; use readPreference=primary for findOneAndUpdate #2899 #2823 - * docs; clarify that update validators only run on $set and $unset #2889 - * fixed; set kind consistently for built-in validators #2885 - * docs; single field populated documents #2884 - * fixed; nested objects are now enumerable #2880 [toblerpwn](https://github.com/toblerpwn) - * fixed; properly populate field when ref, lean, stream used together #2841 - * docs; fixed migration guide jade error #2807 - -3.8.28 / 2015-05-12 -=================== - * fixed; proper handling for toJSON options #2910 - * fixed; dont attach virtuals to embedded docs in update() #2046 - -4.0.2 / 2015-04-23 -================== - * fixed; error thrown when calling .validate() on subdoc not in an array #2902 - * fixed; rename define() to play nice with webpack #2900 [jspears](https://github.com/jspears) - * fixed; pre validate called twice with discriminators #2892 - * fixed; .inspect() on mongoose.Types #2875 - * docs; correct callback params for Model.update #2872 - * fixed; setDefaultsOnInsert now works when runValidators not specified #2870 - * fixed; Document now wraps EventEmitter.addListener #2867 - * fixed; call non-hook functions in schema queue #2856 - * fixed; statics can be mocked out for tests #2848 [ninelb](https://github.com/ninelb) - * upgraded; mquery 1.4.0 for bluebird bug fix #2846 - * fixed; required validators run first #2843 - * docs; improved docs for new option to findAndMody #2838 - * docs; populate example now uses correct field #2837 [swilliams](https://github.com/swilliams) - * fixed; pre validate changes causing VersionError #2835 - * fixed; get path from correct place when setting CastError #2832 - * docs; improve docs for Model.update() function signature #2827 [irnc](https://github.com/irnc) - * fixed; populating discriminators #2825 [chetverikov](https://github.com/chetverikov) - * fixed; discriminators with nested schemas #2821 - * fixed; CastErrors with embedded docs #2819 - * fixed; post save hook context #2816 - * docs; 3.8.x -> 4.x migration guide #2807 - * fixed; proper _distinct copying for query #2765 [cdelauder](https://github.com/cdelauder) - -3.8.27 / 2015-04-22 -=================== - * fixed; dont duplicate db calls on Q.ninvoke() #2864 - * fixed; Model.find arguments naming in docs #2828 - * fixed; Support ipv6 in connection strings #2298 - -3.8.26 / 2015-04-07 -=================== - * fixed; TypeError when setting date to undefined #2833 - * fixed; handle CastError properly in distinct() with no callback #2786 - * fixed; broken links in queries docs #2779 - * fixed; dont mark buffer as modified when setting type initially #2738 - * fixed; dont crash when using slice with populate #1934 - -4.0.1 / 2015-03-28 -================== - * fixed; properly handle empty cast doc in update() with promises #2796 - * fixed; unstable warning #2794 - * fixed; findAndModify docs now show new option is false by default #2793 - -4.0.0 / 2015-03-25 -================== - * fixed; on-the-fly schema docs typo #2783 [artiifix](https://github.com/artiifix) - * fixed; cast error validation handling #2775 #2766 #2678 - * fixed; discriminators with populate() #2773 #2719 [chetverikov](https://github.com/chetverikov) - * fixed; increment now a reserved path #2709 - * fixed; avoid sending duplicate object ids in populate() #2683 - * upgraded; mongodb to 2.0.24 to properly emit reconnect event multiple times #2656 - -4.0.0-rc4 / 2015-03-14 -====================== - * fixed; toObject virtuals schema option handled properly #2751 - * fixed; update validators work on document arrays #2733 - * fixed; check for cast errors on $set #2729 - * fixed; instance field set for all schema types #2727 [csdco](https://github.com/csdco) - * fixed; dont run other validators if required fails #2725 - * fixed; custom getters execute on ref paths #2610 - * fixed; save defaults if they were set when doc was loaded from db #2558 - * fixed; pre validate now runs before pre save #2462 - * fixed; no longer throws errors with --use_strict #2281 - -3.8.25 / 2015-03-13 -=================== - * fixed; debug output reverses order of aggregation keys #2759 - * fixed; $eq is a valid query selector in 3.0 #2752 - * fixed; upgraded node driver to 1.4.32 for handling non-numeric poolSize #2682 - * fixed; update() with overwrite sets _id for nested docs #2658 - * fixed; casting for operators in $elemMatch #2199 - -4.0.0-rc3 / 2015-02-28 -====================== - * fixed; update() pre hooks run before validators #2706 - * fixed; setters not called on arrays of refs #2698 [brandom](https://github.com/brandom) - * fixed; use node driver 2.0.18 for nodejs 0.12 support #2685 - * fixed; comments reference file that no longer exists #2681 - * fixed; populated() returns _id of manually populated doc #2678 - * added; ability to exclude version key in toObject() #2675 - * fixed; dont allow setting nested path to a string #2592 - * fixed; can cast objects with _id field to ObjectIds #2581 - * fixed; on-the-fly schema getters #2360 - * added; strict option for findOneAndUpdate() #1967 - -3.8.24 / 2015-02-25 -=================== - * fixed; properly apply child schema transforms #2691 - * fixed; make copy of findOneAndUpdate options before modifying #2687 - * fixed; apply defaults when parent path is selected #2670 #2629 - * fixed; properly get ref property for nested paths #2665 - * fixed; node driver makes copy of authenticate options before modifying them #2619 - * fixed; dont block process exit when auth fails #2599 - * fixed; remove redundant clone in update() #2537 - -4.0.0-rc2 / 2015-02-10 -====================== - * added; io.js to travis build - * removed; browser build dependencies not installed by default - * added; dynamic refpaths #2640 [chetverikov](https://github.com/chetverikov) - * fixed; dont call child schema transforms on parent #2639 [chetverikov](https://github.com/chetverikov) - * fixed; get rid of remove option if new is set in findAndModify #2598 - * fixed; aggregate all document array validation errors #2589 - * fixed; custom setters called when setting value to undefined #1892 - -3.8.23 / 2015-02-06 -=================== - * fixed; unset opts.remove when upsert is true #2519 - * fixed; array saved as object when path is object in array #2442 - * fixed; inline transforms #2440 - * fixed; check for callback in count() #2204 - * fixed; documentation for selecting fields #1534 - -4.0.0-rc1 / 2015-02-01 -====================== - * fixed; use driver 2.0.14 - * changed; use transform: true by default #2245 - -4.0.0-rc0 / 2015-01-31 -=================== - * fixed; wrong order for distinct() params #2628 - * fixed; handling no query argument to remove() #2627 - * fixed; createModel and discriminators #2623 [ashaffer](https://github.com/ashaffer) - * added; pre('count') middleware #2621 - * fixed; double validation calls on document arrays #2618 - * added; validate() catches cast errors #2611 - * fixed; respect replicaSet parameter in connection string #2609 - * added; can explicitly exclude paths from versioning #2576 [csabapalfi](https://github.com/csabapalfi) - * upgraded; driver to 2.0.15 #2552 - * fixed; save() handles errors more gracefully in ES6 #2371 - * fixed; undefined is now a valid argument to findOneAndUpdate #2272 - * changed; `new` option to findAndModify ops is false by default #2262 - -3.8.22 / 2015-01-24 -=================== - * upgraded; node-mongodb-native to 1.4.28 #2587 [Climax777](https://github.com/Climax777) - * added; additional documentation for validators #2449 - * fixed; stack overflow when creating massive arrays #2423 - * fixed; undefined is a valid id for queries #2411 - * fixed; properly create nested schema index when same schema used twice #2322 - * added; link to plugin generator in docs #2085 [huei90](https://github.com/huei90) - * fixed; optional arguments documentation for findOne() #1971 [nachinius](https://github.com/nachinius) - -3.9.7 / 2014-12-19 -=================== - * added; proper cursors for aggregate #2539 [changyy](https://github.com/changyy) - * added; min/max built-in validators for dates #2531 [bshamblen](https://github.com/bshamblen) - * fixed; save and validate are now reserved keywords #2380 - * added; basic documentation for browser component #2256 - * added; find and findOne hooks (query middleware) #2138 - * fixed; throw a DivergentArrayError when saving positional operator queries #2031 - * added; ability to use options as a document property #1416 - * fixed; document no longer inherits from event emitter and so domain and _events are no longer reserved #1351 - * removed; setProfiling #1349 - -3.8.21 / 2014-12-18 -=================== - * fixed; syntax in index.jade #2517 [elderbas](https://github.com/elderbas) - * fixed; writable statics #2510 #2528 - * fixed; overwrite and explicit $set casting #2515 - -3.9.6 / 2014-12-05 -=================== - * added; correctly run validators on each element of array when entire array is modified #661 #1227 - * added; castErrors in validation #1013 [jondavidjohn](https://github.com/jondavidjohn) - * added; specify text indexes in schema fields #1401 [sr527](https://github.com/sr527) - * added; ability to set field with validators to undefined #1594 [alabid](https://github.com/alabid) - * added; .create() returns an array when passed an array #1746 [alabid](https://github.com/alabid) - * added; test suite and docs for use with co and yield #2177 #2474 - * fixed; subdocument toObject() transforms #2447 [chmanie](https://github.com/chmanie) - * fixed; Model.create() with save errors #2484 - * added; pass options to .save() and .remove() #2494 [jondavidjohn](https://github.com/jondavidjohn) - -3.8.20 / 2014-12-01 -=================== - * fixed; recursive readPref #2490 [kjvalencik](https://github.com/kjvalencik) - * fixed; make sure to copy parameters to update() before modifying #2406 [alabid](https://github.com/alabid) - * fixed; unclear documentation about query callbacks #2319 - * fixed; setting a schema-less field to an empty object #2314 [alabid](https://github.com/alabid) - * fixed; registering statics and methods for discriminators #2167 [alabid](https://github.com/alabid) - -3.9.5 / 2014-11-10 -=================== - * added; ability to disable autoIndex on a per-connection basis #1875 [sr527](https://github.com/sr527) - * fixed; `geoNear()` no longer enforces legacy coordinate pairs - supports GeoJSON #1987 [alabid](https://github.com/alabid) - * fixed; browser component works when minified with mangled variable names #2302 - * fixed; `doc.errors` now cleared before `validate()` called #2302 - * added; `execPopulate()` function to make `doc.populate()` compatible with promises #2317 - * fixed; `count()` no longer throws an error when used with `sort()` #2374 - * fixed; `save()` no longer recursively calls `save()` on populated fields #2418 - -3.8.19 / 2014-11-09 -=================== - * fixed; make sure to not override subdoc _ids on find #2276 [alabid](https://github.com/alabid) - * fixed; exception when comparing two documents when one lacks _id #2333 [slawo](https://github.com/slawo) - * fixed; getters for properties with non-strict schemas #2439 [alabid](https://github.com/alabid) - * fixed; inconsistent URI format in docs #2414 [sr527](https://github.com/sr527) - -3.9.4 / 2014-10-25 -================== - * fixed; statics no longer can be overwritten #2343 [nkcmr](https://github.com/chetverikov) - * added; ability to set single populated paths to documents #1530 - * added; setDefaultsOnInsert and runValidator options for findOneAndUpdate() #860 - -3.8.18 / 2014-10-22 -================== - * fixed; Dont use all toObject options in save #2340 [chetverikov](https://github.com/chetverikov) - -3.9.3 / 2014-10-01 -================= - * added; support for virtuals that return objects #2294 - * added; ability to manually hydrate POJOs into mongoose objects #2292 - * added; setDefaultsOnInsert and runValidator options for update() #860 - -3.8.17 / 2014-09-29 -================== - * fixed; use schema options retainKeyOrder in save() #2274 - * fixed; fix skip in populate when limit is set #2252 - * fixed; fix stack overflow when passing MongooseArray to findAndModify #2214 - * fixed; optimize .length usage in populate #2289 - -3.9.2 / 2014-09-08 -================== - * added; test coverage for browser component #2255 - * added; in-order execution of validators #2243 - * added; custom fields for validators #2132 - * removed; exception thrown when find() used with count() #1950 - -3.8.16 / 2014-09-08 -================== - * fixed; properly remove modified array paths if array has been overwritten #1638 - * fixed; key check errors #1884 - * fixed; make sure populate on an array always returns a Mongoose array #2214 - * fixed; SSL connections with node 0.11 #2234 - * fixed; return sensible strings for promise errors #2239 - -3.9.1 / 2014-08-17 -================== - * added; alpha version of browser-side schema validation #2254 - * added; support passing a function to schemas `required` field #2247 - * added; support for setting updatedAt and createdAt timestamps #2227 - * added; document.validate() returns a promise #2131 - -3.8.15 / 2014-08-17 -================== - * fixed; Replica set connection string example in docs #2246 - * fixed; bubble up parseError event #2229 - * fixed; removed buggy populate cache #2176 - * fixed; dont $inc versionKey if its being $set #1933 - * fixed; cast $or and $and in $pull #1932 - * fixed; properly cast to schema in stream() #1862 - * fixed; memory leak in nested objects #1565 #2211 [devongovett](https://github.com/devongovett) - -3.8.14 / 2014-07-26 -================== - * fixed; stringifying MongooseArray shows nested arrays #2002 - * fixed; use populated doc schema in toObject and toJSON by default #2035 - * fixed; dont crash on arrays containing null #2140 - * fixed; model.update w/ upsert has same return values on .exec and promise #2143 - * fixed; better handling for populate limit with multiple documents #2151 - * fixed; dont prevent users from adding weights to text index #2183 - * fixed; helper for aggregation cursor #2187 - * updated; node-mongodb-native to 1.4.7 - -3.8.13 / 2014-07-15 -================== - * fixed; memory leak with isNew events #2159 - * fixed; docs for overwrite option for update() #2144 - * fixed; storeShard() handles dates properly #2127 - * fixed; sub-doc changes not getting persisted to db after save #2082 - * fixed; populate with _id: 0 actually removes _id instead of setting to undefined #2123 - * fixed; save versionKey on findOneAndUpdate w/ upsert #2122 - * fixed; fix typo in 2.8 docs #2120 [shakirullahi](https://github.com/shakirullahi) - * fixed; support maxTimeMs #2102 [yuukinajima](https://github.com/yuukinajima) - * fixed; support $currentDate #2019 - * fixed; $addToSet handles objects without _ids properly #1973 - * fixed; dont crash on invalid nearSphere query #1874 - -3.8.12 / 2014-05-30 -================== - * fixed; single-server reconnect event fires #1672 - * fixed; sub-docs not saved when pushed into populated array #1794 - * fixed; .set() sometimes converts embedded docs to pojos #1954 [archangel-irk](https://github.com/archangel-irk) - * fixed; sub-doc changes not getting persisted to db after save #2082 - * fixed; custom getter might cause mongoose to mistakenly think a path is dirty #2100 [pgherveou](https://github.com/pgherveou) - * fixed; chainable helper for allowDiskUse option in aggregation #2114 - -3.9.0 (unstable) / 2014-05-22 -================== - * changed; added `domain` to reserved keywords #1338 #2052 [antoinepairet](https://github.com/antoinepairet) - * added; asynchronous post hooks #1977 #2081 [chopachom](https://github.com/chopachom) [JasonGhent](https://github.com/JasonGhent) - * added; using model for population, cross-db populate [mihai-chiorean](https://github.com/mihai-chiorean) - * added; can define a type for schema validators - * added; `doc.remove()` returns a promise #1619 [refack](https://github.com/refack) - * added; internal promises for hooks, pre-save hooks run in parallel #1732 [refack](https://github.com/refack) - * fixed; geoSearch hanging when no results returned #1846 [ghartnett](https://github.com/ghartnett) - * fixed; do not set .type property on ValidationError, use .kind instead #1323 - -3.8.11 / 2014-05-22 -================== - * updated; node-mongodb-native to 1.4.5 - * reverted; #2052, fixes #2097 - -3.8.10 / 2014-05-20 -================== - - * updated; node-mongodb-native to 1.4.4 - * fixed; _.isEqual false negatives bug in js-bson #2070 - * fixed; missing check for schema.options #2014 - * fixed; missing support for $position #2024 - * fixed; options object corruption #2049 - * fixed; improvements to virtuals docs #2055 - * fixed; added `domain` to reserved keywords #2052 #1338 - -3.8.9 / 2014-05-08 -================== - - * updated; mquery to 0.7.0 - * updated; node-mongodb-native to 1.4.3 - * fixed; $near failing against MongoDB 2.6 - * fixed; relying on .options() to determine if collection exists - * fixed; $out aggregate helper - * fixed; all test failures against MongoDB 2.6.1, with caveat #2065 - -3.8.8 / 2014-02-22 -================== - - * fixed; saving Buffers #1914 - * updated; expose connection states for user-land #1926 [yorkie](https://github.com/yorkie) - * updated; mquery to 0.5.3 - * updated; added get / set to reserved path list #1903 [tstrimple](https://github.com/tstrimple) - * docs; README code highlighting, syntax fixes #1930 [IonicaBizau](https://github.com/IonicaBizau) - * docs; fixes link in the doc at #1925 [kapeels](https://github.com/kapeels) - * docs; add a missed word 'hook' for the description of the post-hook api #1924 [ipoval](https://github.com/ipoval) - -3.8.7 / 2014-02-09 -================== - - * fixed; sending safe/read options in Query#exec #1895 - * fixed; findOneAnd..() with sort #1887 - -3.8.6 / 2014-01-30 -================== - - * fixed; setting readPreferences #1895 - -3.8.5 / 2014-01-23 -================== - - * fixed; ssl setting when using URI #1882 - * fixed; findByIdAndUpdate now respects the overwrite option #1809 [owenallenaz](https://github.com/owenallenaz) - -3.8.4 / 2014-01-07 -================== - - * updated; mongodb driver to 1.3.23 - * updated; mquery to 0.4.1 - * updated; mpromise to 0.4.3 - * fixed; discriminators now work when selecting fields #1820 [daemon1981](https://github.com/daemon1981) - * fixed; geoSearch with no results timeout #1846 [ghartnett](https://github.com/ghartnett) - * fixed; infitite recursion in ValidationError #1834 [chetverikov](https://github.com/chetverikov) - -3.8.3 / 2013-12-17 -================== - - * fixed; setting empty array with model.update #1838 - * docs; fix url - -3.8.2 / 2013-12-14 -================== - - * fixed; enum validation of multiple values #1778 [heroicyang](https://github.com/heroicyang) - * fixed; global var leak #1803 - * fixed; post remove now fires on subdocs #1810 - * fixed; no longer set default empty array for geospatial-indexed fields #1668 [shirish87](https://github.com/shirish87) - * fixed; model.stream() not hydrating discriminators correctly #1792 [j](https://github.com/j) - * docs: Stablility -> Stability [nikmartin](https://github.com/nikmartin) - * tests; improve shard error handling - -3.8.1 / 2013-11-19 -================== - - * fixed; mishandling of Dates with minimize/getters #1764 - * fixed; Normalize bugs.email, so `npm` will shut up #1769 [refack](https://github.com/refack) - * docs; Improve the grammar where "lets us" was used #1777 [alexyoung](https://github.com/alexyoung) - * docs; Fix some grammatical issues in the documentation #1777 [alexyoung](https://github.com/alexyoung) - * docs; fix Query api exposure - * docs; fix return description - * docs; Added Notes on findAndUpdate() #1750 [sstadelman](https://github.com/sstadelman) - * docs; Update version number in README #1762 [Fodi69](https://github.com/Fodi69) - -3.8.0 / 2013-10-31 -================== - - * updated; warn when using an unstable version - * updated; error message returned in doc.save() #1595 - * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) - * updated; mquery to 0.3.2 - * updated; mocha to 1.12.0 - * updated; mpromise 0.3.0 - * updated; sliced 0.0.5 - * removed; mongoose.Error.DocumentError (never used) - * removed; namedscope (undocumented and broken) #679 #642 #455 #379 - * changed; no longer offically supporting node 0.6.x - * changed; query.within getter is now a method -> query.within() - * changed; query.intersects getter is now a method -> query.intersects() - * added; custom error msgs for built-in validators #747 - * added; discriminator support #1647 #1003 [j](https://github.com/j) - * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack) - * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing) - * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing) - * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing) - * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing) - * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing) - * added; promise support to model.mapReduce() - * added; promise support to model.ensureIndexes() - * added; promise support to model.populate() - * added; benchmarks [ebensing](https://github.com/ebensing) - * added; publicly exposed connection states #1585 - * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing) - * added; query method chain validation - * added; model.update `overwrite` option - * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing) - * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing) - * added; MongooseBuffer#subtype() - * added; model.create() now returns a promise #1340 - * added; support for `awaitdata` query option - * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner) - * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard) - * fixed; document.toObject when using `minimize` and `getters` options #1607 [JedWatson](https://github.com/JedWatson) - * fixed; Mixed types can now be required #1722 [Reggino](https://github.com/Reggino) - * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack) - * fixed; repopulating modified populated paths #1697 - * fixed; doc.equals() when _id option is set to false #1687 - * fixed; strict mode warnings #1686 - * fixed; $near GeoJSON casting #1683 - * fixed; nearSphere GeoJSON query builder - * fixed; population field selection w/ strings #1669 - * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) - * fixed; handle another versioning edge case #1520 - * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing) - * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann) - * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing) - * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing) - * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j) - * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing) - * fixed; model.remove() removes only what is necessary #1649 - * fixed; update() now only runs with cb or explicit true #1644 - * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing) - * fixed; model.update "overwrite" option works as documented - * fixed; query#remove() works as documented - * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing) - * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing) - * fixed; benchmarks to actually output valid json - * deprecated; promise#addBack (use promise#onResolve) - * deprecated; promise#complete (use promise#fulfill) - * deprecated; promise#addCallback (use promise#onFulFill) - * deprecated; promise#addErrback (use promise#onReject) - * deprecated; query.nearSphere() (use query.near) - * deprecated; query.center() (use query.circle) - * deprecated; query.centerSphere() (use query.circle) - * deprecated; query#slaveOk (use query#read) - * docs; custom validator messages - * docs; 10gen -> MongoDB - * docs; add Date method caveats #1598 - * docs; more validation details - * docs; state which branch is stable/unstable - * docs; mention that middleware does not run on Models - * docs; promise.fulfill() - * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis) - * docs; fixed up the README and examples [ebensing](https://github.com/ebensing) - * website; add "show code" for properties - * website; move "show code" links down - * website; update guide - * website; add unstable docs - * website; many improvements - * website; fix copyright #1439 - * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin) - * tests; refactor 1703 - * tests; add test generator - * tests; validate formatMessage() throws - * tests; add script for continuously running tests - * tests; fixed versioning tests - * tests; race conditions in tests - * tests; added for nested and/or queries - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; replace deprecated method names - * tests; convert id to string - * tests; fix sharding tests for MongoDB 2.4.5 - * tests; now 4-5 seconds faster - * tests; fix race condition - * make; suppress warning msg in test - * benchmarks; updated for pull requests - * examples; improved and expanded [ebensing](https://github.com/ebensing) - -3.7.4 (unstable) / 2013-10-01 -============================= - - * updated; mquery to 0.3.2 - * removed; mongoose.Error.DocumentError (never used) - * added; custom error msgs for built-in validators #747 - * added; discriminator support #1647 #1003 [j](https://github.com/j) - * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack) - * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack) - * fixed; repopulating modified populated paths #1697 - * fixed; doc.equals() when _id option is set to false #1687 - * fixed; strict mode warnings #1686 - * fixed; $near GeoJSON casting #1683 - * fixed; nearSphere GeoJSON query builder - * fixed; population field selection w/ strings #1669 - * docs; custom validator messages - * docs; 10gen -> MongoDB - * docs; add Date method caveats #1598 - * docs; more validation details - * website; add "show code" for properties - * website; move "show code" links down - * tests; refactor 1703 - * tests; add test generator - * tests; validate formatMessage() throws - -3.7.3 (unstable) / 2013-08-22 -============================= - - * updated; warn when using an unstable version - * updated; mquery to 0.3.1 - * updated; mocha to 1.12.0 - * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) - * changed; no longer offically supporting node 0.6.x - * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing) - * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing) - * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing) - * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing) - * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) - * fixed; handle another versioning edge case #1520 - * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing) - * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann) - * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing) - * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing) - * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j) - * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing) - * make; suppress warning msg in test - * docs; state which branch is stable/unstable - * docs; mention that middleware does not run on Models - * tests; add script for continuously running tests - * tests; fixed versioning tests - * benchmarks; updated for pull requests - -3.7.2 (unstable) / 2013-08-15 -================== - - * fixed; model.remove() removes only what is necessary #1649 - * fixed; update() now only runs with cb or explicit true #1644 - * tests; race conditions in tests - * website; update guide - -3.7.1 (unstable) / 2013-08-13 -============================= - - * updated; driver to 1.3.18 (fixes memory leak) - * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing) - * added; promise support to model.mapReduce() - * added; promise support to model.ensureIndexes() - * added; promise support to model.populate() - * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing) - * fixed; model.update "overwrite" option works as documented - * fixed; query#remove() works as documented - * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing) - * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing) - * fixed; benchmarks to actually output valid json - * tests; added for nested and/or queries - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; replace deprecated method names - * tests; convert id to string - * docs; promise.fulfill() - -3.7.0 (unstable) / 2013-08-05 -=================== - - * changed; query.within getter is now a method -> query.within() - * changed; query.intersects getter is now a method -> query.intersects() - * deprecated; promise#addBack (use promise#onResolve) - * deprecated; promise#complete (use promise#fulfill) - * deprecated; promise#addCallback (use promise#onFulFill) - * deprecated; promise#addErrback (use promise#onReject) - * deprecated; query.nearSphere() (use query.near) - * deprecated; query.center() (use query.circle) - * deprecated; query.centerSphere() (use query.circle) - * deprecated; query#slaveOk (use query#read) - * removed; namedscope (undocumented and broken) #679 #642 #455 #379 - * added; benchmarks [ebensing](https://github.com/ebensing) - * added; publicly exposed connection states #1585 - * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing) - * added; query method chain validation - * added; model.update `overwrite` option - * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing) - * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing) - * added; MongooseBuffer#subtype() - * added; model.create() now returns a promise #1340 - * added; support for `awaitdata` query option - * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner) - * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard) - * updated; integrate mquery #1562 [ebensing](https://github.com/ebensing) - * updated; error msg in doc.save() #1595 - * updated; bump driver to 1.3.15 - * updated; mpromise 0.3.0 - * updated; sliced 0.0.5 - * tests; fix sharding tests for MongoDB 2.4.5 - * tests; now 4-5 seconds faster - * tests; fix race condition - * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis) - * docs; fixed up the README and examples [ebensing](https://github.com/ebensing) - * website; add unstable docs - * website; many improvements - * website; fix copyright #1439 - * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin) - * examples; improved and expanded [ebensing](https://github.com/ebensing) - -3.6.20 (stable) / 2013-09-23 -=================== - - * fixed; repopulating modified populated paths #1697 - * fixed; doc.equals w/ _id false #1687 - * fixed; strict mode warning #1686 - * docs; near/nearSphere - -3.6.19 (stable) / 2013-09-04 -================== - - * fixed; population field selection w/ strings #1669 - * docs; Date method caveats #1598 - -3.6.18 (stable) / 2013-08-22 -=================== - - * updated; warn when using an unstable version of mongoose - * updated; mocha to 1.12.0 - * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) - * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) - * fixed; properly exclude subdocument fields #1280 [ebensing](https://github.com/ebensing) - * fixed; cast error in findAndModify #1643 [aheuermann](https://github.com/aheuermann) - * website; update guide - * website; added documentation for safe:false and versioning interaction - * docs; mention that middleware dont run on Models - * docs; fix indexes link - * make; suppress warning msg in test - * tests; moar - -3.6.17 / 2013-08-13 -=================== - - * updated; driver to 1.3.18 (fixes memory leak) - * fixed; casting ref docs on creation #1606 - * docs; query options - -3.6.16 / 2013-08-08 -=================== - - * added; publicly expose connection states #1585 - * fixed; limit applies to individual items on population #1490 [ebensing](https://github.com/ebensing) - * fixed; positional operator casting in updates #1572 [ebensing](https://github.com/ebensing) - * updated; MongoDB driver to 1.3.17 - * updated; sliced to 0.0.5 - * website; tweak homepage - * tests; fixed + added - * docs; fix some examples - * docs; multi-mongos support details - * docs; auto open browser after starting static server - -3.6.15 / 2013-07-16 -================== - - * added; mongos failover support #1037 - * updated; make schematype return vals return self #1580 - * docs; add note to model.update #571 - * docs; document third param to document.save callback #1536 - * tests; tweek mongos test timeout - -3.6.14 / 2013-07-05 -=================== - - * updated; driver to 1.3.11 - * fixed; issue with findOneAndUpdate not returning null on upserts #1533 [ebensing](https://github.com/ebensing) - * fixed; missing return statement in SchemaArray#$geoIntersects() #1498 [bsrykt](https://github.com/bsrykt) - * fixed; wrong isSelected() behavior #1521 [kyano](https://github.com/kyano) - * docs; note about toObject behavior during save() - * docs; add callbacks details #1547 [nikmartin](https://github.com/nikmartin) - -3.6.13 / 2013-06-27 -=================== - - * fixed; calling model.distinct without conditions #1541 - * fixed; regression in Query#count() #1542 - * now working on 3.6.13 - -3.6.12 / 2013-06-25 -=================== - - * updated; driver to 1.3.10 - * updated; clearer capped collection error message #1509 [bitmage](https://github.com/bitmage) - * fixed; MongooseBuffer subtype loss during casting #1517 [zedgu](https://github.com/zedgu) - * fixed; docArray#id when doc.id is disabled #1492 - * fixed; docArray#id now supports matches on populated arrays #1492 [pgherveou](https://github.com/pgherveou) - * website; fix example - * website; improve _id disabling example - * website; fix typo #1494 [dejj](https://github.com/dejj) - * docs; added a 'Requesting new features' section #1504 [shovon](https://github.com/shovon) - * docs; improve subtypes description - * docs; clarify _id disabling - * docs: display by alphabetical order the methods list #1508 [nicolasleger](https://github.com/nicolasleger) - * tests; refactor isSelected checks - * tests; remove pointless test - * tests; fixed timeouts - -3.6.11 / 2013-05-15 -=================== - - * updated; driver to 1.3.5 - * fixed; compat w/ Object.create(null) #1484 #1485 - * fixed; cloning objects w/ missing constructors - * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako) - * docs; add doc.increment() example - * docs; add $size example - * docs; add "distinct" example - -3.6.10 / 2013-05-09 -================== - - * update driver to 1.3.3 - * fixed; increment() works without other changes #1475 - * website; fix links to posterous - * docs; fix link #1472 - -3.6.9 / 2013-05-02 -================== - - * fixed; depopulation of mixed documents #1471 - * fixed; use of $options in array #1462 - * tests; fix race condition - * docs; fix default example - -3.6.8 / 2013-04-25 -================== - - * updated; driver to 1.3.0 - * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex) - * tests; 4-5 seconds faster - -3.6.7 / 2013-04-19 -================== - - * fixed; population regression in 3.6.6 #1444 - -3.6.6 / 2013-04-18 -================== - - * fixed; saving populated new documents #1442 - * fixed; population regession in 3.6.5 #1441 - * website; fix copyright #1439 - -3.6.5 / 2013-04-15 -================== - - * fixed; strict:throw edge case using .set(path, val) - * fixed; schema.pathType() on some numbericAlpha paths - * fixed; numbericAlpha path versioning - * fixed; setting nested mixed paths #1418 - * fixed; setting nested objects with null prop #1326 - * fixed; regression in v3.6 population performance #1426 [vedmalex](https://github.com/vedmalex) - * fixed; read pref typos #1422 [kyano](https://github.com/kyano) - * docs; fix method example - * website; update faq - * website; add more deep links - * website; update poolSize docs - * website; add 3.6 release notes - * website; note about keepAlive - -3.6.4 / 2013-04-03 -================== - - * fixed; +field conflict with $slice #1370 - * fixed; nested deselection conflict #1333 - * fixed; RangeError in ValidationError.toString() #1296 - * fixed; do not save user defined transforms #1415 - * tests; fix race condition - -3.6.3 / 2013-04-02 -================== - - * fixed; setting subdocuments deeply nested fields #1394 - * fixed; regression: populated streams #1411 - * docs; mention hooks/validation with findAndModify - * docs; mention auth - * docs; add more links - * examples; add document methods example - * website; display "see" links for properties - * website; clean up homepage - -3.6.2 / 2013-03-29 -================== - - * fixed; corrupted sub-doc array #1408 - * fixed; document#update returns a Query #1397 - * docs; readpref strategy - -3.6.1 / 2013-03-27 -================== - - * added; populate support to findAndModify varients #1395 - * added; text index type to schematypes - * expose allowed index types as Schema.indexTypes - * fixed; use of `setMaxListeners` as path - * fixed; regression in node 0.6 on docs with > 10 arrays - * fixed; do not alter schema arguments #1364 - * fixed; subdoc#ownerDocument() #1385 - * website; change search id - * website; add search from google [jackdbernier](https://github.com/jackdbernier) - * website; fix link - * website; add 3.5.x docs release - * website; fix link - * docs; fix geometry - * docs; hide internal constructor - * docs; aggregation does not cast arguments #1399 - * docs; querystream options - * examples; added for population - -3.6.0 / 2013-03-18 -================== - - * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach) - * changed; Buffer arrays can now contain nulls - * added; QueryStream transform option - * added; support for authSource driver option - * added; {mongoose,db}.modelNames() - * added; $push w/ $slice,$sort support (MongoDB 2.4) - * added; hashed index type (MongoDB 2.4) - * added; support for mongodb 2.4 geojson (MongoDB 2.4) - * added; value at time of validation error - * added; support for object literal schemas - * added; bufferCommands schema option - * added; allow auth option in connections #1360 [geoah](https://github.com/geoah) - * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9) - * added; allow adding uncasted docs to populated arrays and properties #570 - * added; doc#populated(path) stores original populated _ids - * added; lean population #1260 - * added; query.populate() now accepts an options object - * added; document#populate(opts, callback) - * added; Model.populate(docs, opts, callback) - * added; support for rich nested path population - * added; doc.array.remove(value) subdoc with _id value support #1278 - * added; optionally allow non-strict sets and updates - * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise) - * added; promise#then - * added; promise#end - * fixed; use of `model` as doc property - * fixed; lean population #1382 - * fixed; empty object mixed defaults #1380 - * fixed; populate w/ deselected _id using string syntax - * fixed; attempted save of divergent populated arrays #1334 related - * fixed; better error msg when attempting toObject as property name - * fixed; non population buffer casting from doc - * fixed; setting populated paths #570 - * fixed; casting when added docs to populated arrays #570 - * fixed; prohibit updating arrays selected with $elemMatch #1334 - * fixed; pull / set subdoc combination #1303 - * fixed; multiple bg index creation #1365 - * fixed; manual reconnection to single mongod - * fixed; Constructor / version exposure #1124 - * fixed; CastError race condition - * fixed; no longer swallowing misuse of subdoc#invalidate() - * fixed; utils.clone retains RegExp opts - * fixed; population of non-schema property - * fixed; allow updating versionKey #1265 - * fixed; add EventEmitter props to reserved paths #1338 - * fixed; can now deselect populated doc _ids #1331 - * fixed; properly pass subtype to Binary in MongooseBuffer - * fixed; casting _id from document with non-ObjectId _id - * fixed; specifying schema type edge case { path: [{type: "String" }] } - * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock) - * updated; driver to 1.2.14 - * updated; muri to 0.3.1 - * updated; mpromise to 0.2.1 - * updated; mocha 1.8.1 - * updated; mpath to 0.1.1 - * deprecated; pluralization will die in 4.x - * refactor; rename private methods to something unusable as doc properties - * refactor MongooseArray#remove - * refactor; move expires index to SchemaDate #1328 - * refactor; internal document properties #1171 #1184 - * tests; added - * docs; indexes - * docs; validation - * docs; populate - * docs; populate - * docs; add note about stream compatibility with node 0.8 - * docs; fix for private names - * docs; Buffer -> mongodb.Binary #1363 - * docs; auth options - * docs; improved - * website; update FAQ - * website; add more api links - * website; add 3.5.x docs to prior releases - * website; Change mongoose-types to an active repo [jackdbernier](https://github.com/jackdbernier) - * website; compat with node 0.10 - * website; add news section - * website; use T for generic type - * benchmark; make adjustable - -3.6.0rc1 / 2013-03-12 -====================== - - * refactor; rename private methods to something unusable as doc properties - * added; {mongoose,db}.modelNames() - * added; $push w/ $slice,$sort support (MongoDB 2.4) - * added; hashed index type (MongoDB 2.4) - * added; support for mongodb 2.4 geojson (MongoDB 2.4) - * added; value at time of validation error - * added; support for object literal schemas - * added; bufferCommands schema option - * added; allow auth option in connections #1360 [geoah](https://github.com/geoah) - * fixed; lean population #1382 - * fixed; empty object mixed defaults #1380 - * fixed; populate w/ deselected _id using string syntax - * fixed; attempted save of divergent populated arrays #1334 related - * fixed; better error msg when attempting toObject as property name - * fixed; non population buffer casting from doc - * fixed; setting populated paths #570 - * fixed; casting when added docs to populated arrays #570 - * fixed; prohibit updating arrays selected with $elemMatch #1334 - * fixed; pull / set subdoc combination #1303 - * fixed; multiple bg index creation #1365 - * fixed; manual reconnection to single mongod - * fixed; Constructor / version exposure #1124 - * fixed; CastError race condition - * fixed; no longer swallowing misuse of subdoc#invalidate() - * fixed; utils.clone retains RegExp opts - * fixed; population of non-schema property - * fixed; allow updating versionKey #1265 - * fixed; add EventEmitter props to reserved paths #1338 - * fixed; can now deselect populated doc _ids #1331 - * updated; muri to 0.3.1 - * updated; driver to 1.2.12 - * updated; mpromise to 0.2.1 - * deprecated; pluralization will die in 4.x - * docs; Buffer -> mongodb.Binary #1363 - * docs; auth options - * docs; improved - * website; add news section - * benchmark; make adjustable - -3.6.0rc0 / 2013-02-03 -====================== - - * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach) - * changed; Buffer arrays can now contain nulls - * fixed; properly pass subtype to Binary in MongooseBuffer - * fixed; casting _id from document with non-ObjectId _id - * fixed; specifying schema type edge case { path: [{type: "String" }] } - * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock) - * refactor; move expires index to SchemaDate #1328 - * refactor; internal document properties #1171 #1184 - * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9) - * added; allow adding uncasted docs to populated arrays and properties #570 - * added; doc#populated(path) stores original populated _ids - * added; lean population #1260 - * added; query.populate() now accepts an options object - * added; document#populate(opts, callback) - * added; Model.populate(docs, opts, callback) - * added; support for rich nested path population - * added; doc.array.remove(value) subdoc with _id value support #1278 - * added; optionally allow non-strict sets and updates - * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise) - * added; promise#then - * added; promise#end - * updated; mocha 1.8.1 - * updated; muri to 0.3.0 - * updated; mpath to 0.1.1 - * updated; docs - -3.5.16 / 2013-08-13 -=================== - - * updated; driver to 1.3.18 - -3.5.15 / 2013-07-26 -================== - - * updated; sliced to 0.0.5 - * updated; driver to 1.3.12 - * fixed; regression in Query#count() due to driver change - * tests; fixed timeouts - * tests; handle differing test uris - -3.5.14 / 2013-05-15 -=================== - - * updated; driver to 1.3.5 - * fixed; compat w/ Object.create(null) #1484 #1485 - * fixed; cloning objects missing constructors - * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako) - -3.5.13 / 2013-05-09 -================== - - * update driver to 1.3.3 - * fixed; use of $options in array #1462 - -3.5.12 / 2013-04-25 -=================== - - * updated; driver to 1.3.0 - * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex) - * fixed; read pref typos #1422 [kyano](https://github.com/kyano) - -3.5.11 / 2013-04-03 -================== - - * fixed; +field conflict with $slice #1370 - * fixed; RangeError in ValidationError.toString() #1296 - * fixed; nested deselection conflict #1333 - * remove time from Makefile - -3.5.10 / 2013-04-02 -================== - - * fixed; setting subdocuments deeply nested fields #1394 - * fixed; do not alter schema arguments #1364 - -3.5.9 / 2013-03-15 -================== - - * updated; driver to 1.2.14 - * added; support for authSource driver option (mongodb 2.4) - * added; QueryStream transform option (node 0.10 helper) - * fixed; backport for saving required populated buffers - * fixed; pull / set subdoc combination #1303 - * fixed; multiple bg index creation #1365 - * test; added for saveable required populated buffers - * test; added for #1365 - * test; add authSource test - -3.5.8 / 2013-03-12 -================== - - * added; auth option in connection [geoah](https://github.com/geoah) - * fixed; CastError race condition - * docs; add note about stream compatibility with node 0.8 - -3.5.7 / 2013-02-22 -================== - - * updated; driver to 1.2.13 - * updated; muri to 0.3.1 #1347 - * fixed; utils.clone retains RegExp opts #1355 - * fixed; deepEquals RegExp support - * tests; fix a connection test - * website; clean up docs [afshinm](https://github.com/afshinm) - * website; update homepage - * website; migragtion: emphasize impact of strict docs #1264 - -3.5.6 / 2013-02-14 -================== - - * updated; driver to 1.2.12 - * fixed; properly pass Binary subtype - * fixed; add EventEmitter props to reserved paths #1338 - * fixed; use correct node engine version - * fixed; display empty docs as {} in log output #953 follow up - * improved; "bad $within $box argument" error message - * populate; add unscientific benchmark - * website; add stack overflow to help section - * website; use better code font #1336 [risseraka](https://github.com/risseraka) - * website; clarify where help is available - * website; fix source code links #1272 [floatingLomas](https://github.com/floatingLomas) - * docs; be specific about _id schema option #1103 - * docs; add ensureIndex error handling example - * docs; README - * docs; CONTRIBUTING.md - -3.5.5 / 2013-01-29 -================== - - * updated; driver to 1.2.11 - * removed; old node < 0.6x shims - * fixed; documents with Buffer _ids equality - * fixed; MongooseBuffer properly casts numbers - * fixed; reopening closed connection on alt host/port #1287 - * docs; fixed typo in Readme #1298 [rened](https://github.com/rened) - * docs; fixed typo in migration docs [Prinzhorn](https://github.com/Prinzhorn) - * docs; fixed incorrect annotation in SchemaNumber#min [bilalq](https://github.com/bilalq) - * docs; updated - -3.5.4 / 2013-01-07 -================== - - * changed; "_pres" & "_posts" are now reserved pathnames #1261 - * updated; driver to 1.2.8 - * fixed; exception when reopening a replica set. #1263 [ethankan](https://github.com/ethankan) - * website; updated - -3.5.3 / 2012-12-26 -================== - - * added; support for geo object notation #1257 - * fixed; $within query casting with arrays - * fixed; unix domain socket support #1254 - * updated; driver to 1.2.7 - * updated; muri to 0.0.5 - -3.5.2 / 2012-12-17 -================== - - * fixed; using auth with replica sets #1253 - -3.5.1 / 2012-12-12 -================== - - * fixed; regression when using subdoc with `path` as pathname #1245 [daeq](https://github.com/daeq) - * fixed; safer db option checks - * updated; driver to 1.2.5 - * website; add more examples - * website; clean up old docs - * website; fix prev release urls - * docs; clarify streaming with HTTP responses - -3.5.0 / 2012-12-10 -================== - - * added; paths to CastErrors #1239 - * added; support for mongodb connection string spec #1187 - * added; post validate event - * added; Schema#get (to retrieve schema options) - * added; VersionError #1071 - * added; npmignore [hidekiy](https://github.com/hidekiy) - * update; driver to 1.2.3 - * fixed; stackoverflow in setter #1234 - * fixed; utils.isObject() - * fixed; do not clobber user specified driver writeConcern #1227 - * fixed; always pass current document to post hooks - * fixed; throw error when user attempts to overwrite a model - * fixed; connection.model only caches on connection #1209 - * fixed; respect conn.model() creation when matching global model exists #1209 - * fixed; passing model name + collection name now always honors collection name - * fixed; setting virtual field to an empty object #1154 - * fixed; subclassed MongooseErrors exposure, now available in mongoose.Error.xxxx - * fixed; model.remove() ignoring callback when executed twice [daeq](https://github.com/daeq) #1210 - * docs; add collection option to schema api docs #1222 - * docs; NOTE about db safe options - * docs; add post hooks docs - * docs; connection string options - * docs; middleware is not executed with Model.remove #1241 - * docs; {g,s}etter introspection #777 - * docs; update validation docs - * docs; add link to plugins page - * docs; clarify error returned by unique indexes #1225 - * docs; more detail about disabling autoIndex behavior - * docs; add homepage section to package (npm docs mongoose) - * docs; more detail around collection name pluralization #1193 - * website; add .important css - * website; update models page - * website; update getting started - * website; update quick start - -3.4.0 / 2012-11-10 -================== - - * added; support for generic toJSON/toObject transforms #1160 #1020 #1197 - * added; doc.set() merge support #1148 [NuORDER](https://github.com/NuORDER) - * added; query#add support #1188 [aleclofabbro](https://github.com/aleclofabbro) - * changed; adding invalid nested paths to non-objects throws 4216f14 - * changed; fixed; stop invalid function cloning (internal fix) - * fixed; add query $and casting support #1180 [anotheri](https://github.com/anotheri) - * fixed; overwriting of query arguments #1176 - * docs; fix expires examples - * docs; transforms - * docs; schema `collection` option docs [hermanjunge](https://github.com/hermanjunge) - * website; updated - * tests; added - -3.3.1 / 2012-10-11 -================== - - * fixed; allow goose.connect(uris, dbname, opts) #1144 - * docs; persist API private checked state across page loads - -3.3.0 / 2012-10-10 -================== - - * fixed; passing options as 2nd arg to connect() #1144 - * fixed; race condition after no-op save #1139 - * fixed; schema field selection application in findAndModify #1150 - * fixed; directly setting arrays #1126 - * updated; driver to 1.1.11 - * updated; collection pluralization rules [mrickard](https://github.com/mrickard) - * tests; added - * docs; updated - -3.2.2 / 2012-10-08 -================== - - * updated; driver to 1.1.10 #1143 - * updated; use sliced 0.0.3 - * fixed; do not recast embedded docs unnecessarily - * fixed; expires schema option helper #1132 - * fixed; built in string setters #1131 - * fixed; debug output for Dates/ObjectId properties #1129 - * docs; fixed Javascript syntax error in example [olalonde](https://github.com/olalonde) - * docs; fix toJSON example #1137 - * docs; add ensureIndex production notes - * docs; fix spelling - * docs; add blogposts about v3 - * website; updated - * removed; undocumented inGroupsOf util - * tests; added - -3.2.1 / 2012-09-28 -================== - - * fixed; remove query batchSize option default of 1000 https://github.com/learnboost/mongoose/commit/3edaa8651 - * docs; updated - * website; updated - -3.2.0 / 2012-09-27 -================== - - * added; direct array index assignment with casting support `doc.array.set(index, value)` - * fixed; QueryStream#resume within same tick as pause() #1116 - * fixed; default value validatation #1109 - * fixed; array splice() not casting #1123 - * fixed; default array construction edge case #1108 - * fixed; query casting for inequalities in arrays #1101 [dpatti](https://github.com/dpatti) - * tests; added - * website; more documentation - * website; fixed layout issue #1111 [SlashmanX](https://github.com/SlashmanX) - * website; refactored [guille](https://github.com/guille) - -3.1.2 / 2012-09-10 -================== - - * added; ReadPreferrence schema option #1097 - * updated; driver to 1.1.7 - * updated; default query batchSize to 1000 - * fixed; we now cast the mapReduce query option #1095 - * fixed; $elemMatch+$in with field selection #1091 - * fixed; properly cast $elemMatch+$in conditions #1100 - * fixed; default field application of subdocs #1027 - * fixed; querystream prematurely dying #1092 - * fixed; querystream never resumes when paused at getMore boundries #1092 - * fixed; querystream occasionally emits data events after destroy #1092 - * fixed; remove unnecessary ObjectId creation in querystream - * fixed; allow ne(boolean) again #1093 - * docs; add populate/field selection syntax notes - * docs; add toObject/toJSON options detail - * docs; `read` schema option - -3.1.1 / 2012-08-31 -================== - - * updated; driver to 1.1.6 - -3.1.0 / 2012-08-29 -================== - - * changed; fixed; directly setting nested objects now overwrites entire object (previously incorrectly merged them) - * added; read pref support (mongodb 2.2) 205a709c - * added; aggregate support (mongodb 2.2) f3a5bd3d - * added; virtual {g,s}etter introspection (#1070) - * updated; docs [brettz9](https://github.com/brettz9) - * updated; driver to 1.1.5 - * fixed; retain virtual setter return values (#1069) - -3.0.3 / 2012-08-23 -================== - - * fixed; use of nested paths beginning w/ numbers #1062 - * fixed; query population edge case #1053 #1055 [jfremy](https://github.com/jfremy) - * fixed; simultaneous top and sub level array modifications #1073 - * added; id and _id schema option aliases + tests - * improve debug formatting to allow copy/paste logged queries into mongo shell [eknkc](https://github.com/eknkc) - * docs - -3.0.2 / 2012-08-17 -================== - - * added; missing support for v3 sort/select syntax to findAndModify helpers (#1058) - * fixed; replset fullsetup event emission - * fixed; reconnected event for replsets - * fixed; server reconnection setting discovery - * fixed; compat with non-schema path props using positional notation (#1048) - * fixed; setter/casting order (#665) - * docs; updated - -3.0.1 / 2012-08-11 -================== - - * fixed; throw Error on bad validators (1044) - * fixed; typo in EmbeddedDocument#parentArray [lackac] - * fixed; repair mongoose.SchemaTypes alias - * updated; docs - -3.0.0 / 2012-08-07 -================== - - * removed; old subdocument#commit method - * fixed; setting arrays of matching docs [6924cbc2] - * fixed; doc!remove event now emits in save order as save for consistency - * fixed; pre-save hooks no longer fire on subdocuments when validation fails - * added; subdoc#parent() and subdoc#parentArray() to access subdocument parent objects - * added; query#lean() helper - -3.0.0rc0 / 2012-08-01 -===================== - - * fixed; allow subdoc literal declarations containing "type" pathname (#993) - * fixed; unsetting a default array (#758) - * fixed; boolean $in queries (#998) - * fixed; allow use of `options` as a pathname (#529) - * fixed; `model` is again a permitted schema path name - * fixed; field selection option on subdocs (#1022) - * fixed; handle another edge case with subdoc saving (#975) - * added; emit save err on model if listening - * added; MongoDB TTL collection support (#1006) - * added; $center options support - * added; $nearSphere and $polygon support - * updated; driver version to 1.1.2 - -3.0.0alpha2 / 2012-07-18 -========================= - - * changed; index errors are now emitted on their model and passed to an optional callback (#984) - * fixed; specifying index along with sparse/unique option no longer overwrites (#1004) - * fixed; never swallow connection errors (#618) - * fixed; creating object from model with emded object no longer overwrites defaults [achurkin] (#859) - * fixed; stop needless validation of unchanged/unselected fields (#891) - * fixed; document#equals behavior of objectids (#974) - * fixed; honor the minimize schema option (#978) - * fixed; provide helpful error msgs when reserved schema path is used (#928) - * fixed; callback to conn#disconnect is optional (#875) - * fixed; handle missing protocols in connection urls (#987) - * fixed; validate args to query#where (#969) - * fixed; saving modified/removed subdocs (#975) - * fixed; update with $pull from Mixed array (#735) - * fixed; error with null shard key value - * fixed; allow unsetting enums (#967) - * added; support for manual index creation (#984) - * added; support for disabled auto-indexing (#984) - * added; support for preserving MongooseArray#sort changes (#752) - * added; emit state change events on connection - * added; support for specifying BSON subtype in MongooseBuffer#toObject [jcrugzz] - * added; support for disabled versioning (#977) - * added; implicit "new" support for models and Schemas - -3.0.0alpha1 / 2012-06-15 -========================= - - * removed; doc#commit (use doc#markModified) - * removed; doc.modified getter (#950) - * removed; mongoose{connectSet,createSetConnection}. use connect,createConnection instead - * removed; query alias methods 1149804c - * removed; MongooseNumber - * changed; now creating indexes in background by default - * changed; strict mode now enabled by default (#952) - * changed; doc#modifiedPaths is now a method (#950) - * changed; getters no longer cast (#820); casting happens during set - * fixed; no need to pass updateArg to findOneAndUpdate (#931) - * fixed: utils.merge bug when merging nested non-objects. [treygriffith] - * fixed; strict:throw should produce errors in findAndModify (#963) - * fixed; findAndUpdate no longer overwrites document (#962) - * fixed; setting default DocumentArrays (#953) - * fixed; selection of _id with schema deselection (#954) - * fixed; ensure promise#error emits instanceof Error - * fixed; CursorStream: No stack overflow on any size result (#929) - * fixed; doc#remove now passes safe options - * fixed; invalid use of $set during $pop - * fixed; array#{$pop,$shift} mirror MongoDB behavior - * fixed; no longer test non-required vals in string match (#934) - * fixed; edge case with doc#inspect - * fixed; setter order (#665) - * fixed; setting invalid paths in strict mode (#916) - * fixed; handle docs without id in DocumentArray#id method (#897) - * fixed; do not save virtuals during model.update (#894) - * fixed; sub doc toObject virtuals application (#889) - * fixed; MongooseArray#pull of ObjectId (#881) - * fixed; handle passing db name with any repl set string - * fixed; default application of selected fields (#870) - * fixed; subdoc paths reported in validation errors (#725) - * fixed; incorrect reported num of affected docs in update ops (#862) - * fixed; connection assignment in Model#model (#853) - * fixed; stringifying arrays of docs (#852) - * fixed; modifying subdoc and parent array works (#842) - * fixed; passing undefined to next hook (#785) - * fixed; Query#{update,remove}() works without callbacks (#788) - * fixed; set/updating nested objects by parent pathname (#843) - * fixed; allow null in number arrays (#840) - * fixed; isNew on sub doc after insertion error (#837) - * fixed; if an insert fails, set isNew back to false [boutell] - * fixed; isSelected when only _id is selected (#730) - * fixed; setting an unset default value (#742) - * fixed; query#sort error messaging (#671) - * fixed; support for passing $options with $regex - * added; array of object literal notation in schema creates DocumentArrays - * added; gt,gte,lt,lte query support for arrays (#902) - * added; capped collection support (#938) - * added; document versioning support - * added; inclusion of deselected schema path (#786) - * added; non-atomic array#pop - * added; EmbeddedDocument constructor is now exposed in DocArray#create 7cf8beec - * added; mapReduce support (#678) - * added; support for a configurable minimize option #to{Object,JSON}(option) (#848) - * added; support for strict: `throws` [regality] - * added; support for named schema types (#795) - * added; to{Object,JSON} schema options (#805) - * added; findByIdAnd{Update,Remove}() - * added; findOneAnd{Update,Remove}() - * added; query.setOptions() - * added; instance.update() (#794) - * added; support specifying model in populate() [DanielBaulig] - * added; `lean` query option [gitfy] - * added; multi-atomic support to MongooseArray#nonAtomicPush - * added; support for $set + other $atomic ops on single array - * added; tests - * updated; driver to 1.0.2 - * updated; query.sort() syntax to mirror query.select() - * updated; clearer cast error msg for array numbers - * updated; docs - * updated; doc.clone 3x faster (#950) - * updated; only create _id if necessary (#950) - -2.7.3 / 2012-08-01 -================== - - * fixed; boolean $in queries (#998) - * fixed field selection option on subdocs (#1022) - -2.7.2 / 2012-07-18 -================== - - * fixed; callback to conn#disconnect is optional (#875) - * fixed; handle missing protocols in connection urls (#987) - * fixed; saving modified/removed subdocs (#975) - * updated; tests - -2.7.1 / 2012-06-26 -=================== - - * fixed; sharding: when a document holds a null as a value of the shard key - * fixed; update() using $pull on an array of Mixed (gh-735) - * deprecated; MongooseNumber#{inc, increment, decrement} methods - * tests; now using mocha - -2.7.0 / 2012-06-14 -=================== - - * added; deprecation warnings to methods being removed in 3.x - -2.6.8 / 2012-06-14 -=================== - - * fixed; edge case when using 'options' as a path name (#961) - -2.6.7 / 2012-06-08 -=================== - - * fixed; ensure promise#error always emits instanceof Error - * fixed; selection of _id w/ another excluded path (#954) - * fixed; setting default DocumentArrays (#953) - -2.6.6 / 2012-06-06 -=================== - - * fixed; stack overflow in query stream with large result sets (#929) - * added; $gt, $gte, $lt, $lte support to arrays (#902) - * fixed; pass option `safe` along to doc#remove() calls - -2.6.5 / 2012-05-24 -=================== - - * fixed; do not save virtuals in Model.update (#894) - * added; missing $ prefixed query aliases (going away in 3.x) (#884) [timoxley] - * fixed; setting invalid paths in strict mode (#916) - * fixed; resetting isNew after insert failure (#837) [boutell] - -2.6.4 / 2012-05-15 -=================== - - * updated; backport string regex $options to 2.x - * updated; use driver 1.0.2 (performance improvements) (#914) - * fixed; calling MongooseDocumentArray#id when the doc has no _id (#897) - -2.6.3 / 2012-05-03 -=================== - - * fixed; repl-set connectivity issues during failover on MongoDB 2.0.1 - * updated; driver to 1.0.0 - * fixed; virtuals application of subdocs when using toObject({ virtuals: true }) (#889) - * fixed; MongooseArray#pull of ObjectId correctly updates the array itself (#881) - -2.6.2 / 2012-04-30 -=================== - - * fixed; default field application of selected fields (#870) - -2.6.1 / 2012-04-30 -=================== - - * fixed; connection assignment in mongoose#model (#853, #877) - * fixed; incorrect reported num of affected docs in update ops (#862) - -2.6.0 / 2012-04-19 -=================== - - * updated; hooks.js to 0.2.1 - * fixed; issue with passing undefined to a hook callback. thanks to [chrisleishman] for reporting. - * fixed; updating/setting nested objects in strict schemas (#843) as reported by [kof] - * fixed; Query#{update,remove}() work without callbacks again (#788) - * fixed; modifying subdoc along with parent array $atomic op (#842) - -2.5.14 / 2012-04-13 -=================== - - * fixed; setting an unset default value (#742) - * fixed; doc.isSelected(otherpath) when only _id is selected (#730) - * updated; docs - -2.5.13 / 2012-03-22 -=================== - - * fixed; failing validation of unselected required paths (#730,#713) - * fixed; emitting connection error when only one listener (#759) - * fixed; MongooseArray#splice was not returning values (#784) [chrisleishman] - -2.5.12 / 2012-03-21 -=================== - - * fixed; honor the `safe` option in all ensureIndex calls - * updated; node-mongodb-native driver to 0.9.9-7 - -2.5.11 / 2012-03-15 -=================== - - * added; introspection for getters/setters (#745) - * updated; node-mongodb-driver to 0.9.9-5 - * added; tailable method to Query (#769) [holic] - * fixed; Number min/max validation of null (#764) [btamas] - * added; more flexible user/password connection options (#738) [KarneAsada] - -2.5.10 / 2012-03-06 -=================== - - * updated; node-mongodb-native driver to 0.9.9-4 - * added; Query#comment() - * fixed; allow unsetting arrays - * fixed; hooking the set method of subdocuments (#746) - * fixed; edge case in hooks - * fixed; allow $id and $ref in queries (fixes compatibility with mongoose-dbref) (#749) [richtera] - * added; default path selection to SchemaTypes - -2.5.9 / 2012-02-22 -=================== - - * fixed; properly cast nested atomic update operators for sub-documents - -2.5.8 / 2012-02-21 -=================== - - * added; post 'remove' middleware includes model that was removed (#729) [timoxley] - -2.5.7 / 2012-02-09 -=================== - - * fixed; RegExp validators on node >= v0.6.x - -2.5.6 / 2012-02-09 -=================== - - * fixed; emit errors returned from db.collection() on the connection (were being swallowed) - * added; can add multiple validators in your schema at once (#718) [diogogmt] - * fixed; strict embedded documents (#717) - * updated; docs [niemyjski] - * added; pass number of affected docs back in model.update/save - -2.5.5 / 2012-02-03 -=================== - - * fixed; RangeError: maximum call stack exceed error when removing docs with Number _id (#714) - -2.5.4 / 2012-02-03 -=================== - - * fixed; RangeError: maximum call stack exceed error (#714) - -2.5.3 / 2012-02-02 -=================== - - * added; doc#isSelected(path) - * added; query#equals() - * added; beta sharding support - * added; more descript error msgs (#700) [obeleh] - * added; document.modifiedPaths (#709) [ljharb] - * fixed; only functions can be added as getters/setters (#707,704) [ljharb] - -2.5.2 / 2012-01-30 -=================== - - * fixed; rollback -native driver to 0.9.7-3-5 (was causing timeouts and other replica set weirdness) - * deprecated; MongooseNumber (will be moved to a separate repo for 3.x) - * added; init event is emitted on schemas - -2.5.1 / 2012-01-27 -=================== - - * fixed; honor strict schemas in Model.update (#699) - -2.5.0 / 2012-01-26 -=================== - - * added; doc.toJSON calls toJSON on embedded docs when exists [jerem] - * added; populate support for refs of type Buffer (#686) [jerem] - * added; $all support for ObjectIds and Dates (#690) - * fixed; virtual setter calling on instantiation when strict: true (#682) [hunterloftis] - * fixed; doc construction triggering getters (#685) - * fixed; MongooseBuffer check in deepEquals (#688) - * fixed; range error when using Number _ids with `instance.save()` (#691) - * fixed; isNew on embedded docs edge case (#680) - * updated; driver to 0.9.8-3 - * updated; expose `model()` method within static methods - -2.4.10 / 2012-01-10 -=================== - - * added; optional getter application in .toObject()/.toJSON() (#412) - * fixed; nested $operators in $all queries (#670) - * added; $nor support (#674) - * fixed; bug when adding nested schema (#662) [paulwe] - -2.4.9 / 2012-01-04 -=================== - - * updated; driver to 0.9.7-3-5 to fix Linux performance degradation on some boxes - -2.4.8 / 2011-12-22 -=================== - - * updated; bump -native to 0.9.7.2-5 - * fixed; compatibility with date.js (#646) [chrisleishman] - * changed; undocumented schema "lax" option to "strict" - * fixed; default value population for strict schemas - * updated; the nextTick helper for small performance gain. 1bee2a2 - -2.4.7 / 2011-12-16 -=================== - - * fixed; bug in 2.4.6 with path setting - * updated; bump -native to 0.9.7.2-1 - * added; strict schema option [nw] - -2.4.6 / 2011-12-16 -=================== - - * fixed; conflicting mods on update bug [sirlantis] - * improved; doc.id getter performance - -2.4.5 / 2011-12-14 -=================== - - * fixed; bad MongooseArray behavior in 2.4.2 - 2.4.4 - -2.4.4 / 2011-12-14 -=================== - - * fixed; MongooseArray#doAtomics throwing after sliced - -2.4.3 / 2011-12-14 -=================== - - * updated; system.profile schema for MongoDB 2x - -2.4.2 / 2011-12-12 -=================== - - * fixed; partially populating multiple children of subdocs (#639) [kenpratt] - * fixed; allow Update of numbers to null (#640) [jerem] - -2.4.1 / 2011-12-02 -=================== - - * added; options support for populate() queries - * updated; -native driver to 0.9.7-1.4 - -2.4.0 / 2011-11-29 -=================== - - * added; QueryStreams (#614) - * added; debug print mode for development - * added; $within support to Array queries (#586) [ggoodale] - * added; $centerSphere query support - * fixed; $within support - * added; $unset is now used when setting a path to undefined (#519) - * added; query#batchSize support - * updated; docs - * updated; -native driver to 0.9.7-1.3 (provides Windows support) - -2.3.13 / 2011-11-15 -=================== - - * fixed; required validation for Refs (#612) [ded] - * added; $nearSphere support for Arrays (#610) - -2.3.12 / 2011-11-09 -=================== - - * fixed; regression, objects passed to Model.update should not be changed (#605) - * fixed; regression, empty Model.update should not be executed - -2.3.11 / 2011-11-08 -=================== - - * fixed; using $elemMatch on arrays of Mixed types (#591) - * fixed; allow using $regex when querying Arrays (#599) - * fixed; calling Model.update with no atomic keys (#602) - -2.3.10 / 2011-11-05 -=================== - - * fixed; model.update casting for nested paths works (#542) - -2.3.9 / 2011-11-04 -================== - - * fixed; deepEquals check for MongooseArray returned false - * fixed; reset modified flags of embedded docs after save [gitfy] - * fixed; setting embedded doc with identical values no longer marks modified [gitfy] - * updated; -native driver to 0.9.6.23 [mlazarov] - * fixed; Model.update casting (#542, #545, #479) - * fixed; populated refs no longer fail required validators (#577) - * fixed; populating refs of objects with custom ids works - * fixed; $pop & $unset work with Model.update (#574) - * added; more helpful debugging message for Schema#add (#578) - * fixed; accessing .id when no _id exists now returns null (#590) - -2.3.8 / 2011-10-26 -================== - - * added; callback to query#findOne is now optional (#581) - -2.3.7 / 2011-10-24 -================== - - * fixed; wrapped save/remove callbacks in nextTick to mitigate -native swallowing thrown errors - -2.3.6 / 2011-10-21 -================== - - * fixed; exclusion of embedded doc _id from query results (#541) - -2.3.5 / 2011-10-19 -================== - - * fixed; calling queries without passing a callback works (#569) - * fixed; populate() works with String and Number _ids too (#568) - -2.3.4 / 2011-10-18 -================== - - * added; Model.create now accepts an array as a first arg - * fixed; calling toObject on a DocumentArray with nulls no longer throws - * fixed; calling inspect on a DocumentArray with nulls no longer throws - * added; MongooseArray#unshift support - * fixed; save hooks now fire on embedded documents [gitfy] (#456) - * updated; -native driver to 0.9.6-22 - * fixed; correctly pass $addToSet op instead of $push - * fixed; $addToSet properly detects dates - * fixed; $addToSet with multiple items works - * updated; better node 0.6 Buffer support - -2.3.3 / 2011-10-12 -================== - - * fixed; population conditions in multi-query settings [vedmalex] (#563) - * fixed; now compatible with Node v0.5.x - -2.3.2 / 2011-10-11 -================== - - * fixed; population of null subdoc properties no longer hangs (#561) - -2.3.1 / 2011-10-10 -================== - - * added; support for Query filters to populate() [eneko] - * fixed; querying with number no longer crashes mongodb (#555) [jlbyrey] - * updated; version of -native driver to 0.9.6-21 - * fixed; prevent query callbacks that throw errors from corrupting -native connection state - -2.3.0 / 2011-10-04 -================== - - * fixed; nulls as default values for Boolean now works as expected - * updated; version of -native driver to 0.9.6-20 - -2.2.4 / 2011-10-03 -================== - - * fixed; populate() works when returned array contains undefined/nulls - -2.2.3 / 2011-09-29 -================== - - * updated; version of -native driver to 0.9.6-19 - -2.2.2 / 2011-09-28 -================== - - * added; $regex support to String [davidandrewcope] - * added; support for other contexts like repl etc (#535) - * fixed; clear modified state properly after saving - * added; $addToSet support to Array - -2.2.1 / 2011-09-22 -================== - - * more descript error when casting undefined to string - * updated; version of -native driver to 0.9.6-18 - -2.2.0 / 2011-09-22 -================== - - * fixed; maxListeners warning on schemas with many arrays (#530) - * changed; return / apply defaults based on fields selected in query (#423) - * fixed; correctly detect Mixed types within schema arrays (#532) - -2.1.4 / 2011-09-20 -================== - - * fixed; new private methods that stomped on users code - * changed; finished removing old "compat" support which did nothing - -2.1.3 / 2011-09-16 -================== - - * updated; version of -native driver to 0.9.6-15 - * added; emit `error` on connection when open fails [edwardhotchkiss] - * added; index support to Buffers (thanks justmoon for helping track this down) - * fixed; passing collection name via schema in conn.model() now works (thanks vedmalex for reporting) - -2.1.2 / 2011-09-07 -================== - - * fixed; Query#find with no args no longer throws - -2.1.1 / 2011-09-07 -================== - - * added; support Model.count(fn) - * fixed; compatibility with node >=0.4.0 < 0.4.3 - * added; pass model.options.safe through with .save() so w:2, wtimeout:5000 options work [andrewjstone] - * added; support for $type queries - * added; support for Query#or - * added; more tests - * optimized populate queries - -2.1.0 / 2011-09-01 -================== - - * changed; document#validate is a public method - * fixed; setting number to same value no longer marks modified (#476) [gitfy] - * fixed; Buffers shouldn't have default vals - * added; allow specifying collection name in schema (#470) [ixti] - * fixed; reset modified paths and atomics after saved (#459) - * fixed; set isNew on embedded docs to false after save - * fixed; use self to ensure proper scope of options in doOpenSet (#483) [andrewjstone] - -2.0.4 / 2011-08-29 -================== - - * Fixed; Only send the depopulated ObjectId instead of the entire doc on save (DBRefs) - * Fixed; Properly cast nested array values in Model.update (the data was stored in Mongo incorrectly but recast on document fetch was "fixing" it) - -2.0.3 / 2011-08-28 -================== - - * Fixed; manipulating a populated array no longer causes infinite loop in BSON serializer during save (#477) - * Fixed; populating an empty array no longer hangs foreeeeeeeever (#481) - -2.0.2 / 2011-08-25 -================== - - * Fixed; Maintain query option key order (fixes 'bad hint' error from compound query hints) - -2.0.1 / 2011-08-25 -================== - - * Fixed; do not over-write the doc when no valide props exist in Model.update (#473) - -2.0.0 / 2011-08-24 -=================== - - * Added; support for Buffers [justmoon] - * Changed; improved error handling [maelstrom] - * Removed: unused utils.erase - * Fixed; support for passing other context object into Schemas (#234) [Sija] - * Fixed; getters are no longer circular refs to themselves (#366) - * Removed; unused compat.js - * Fixed; getter/setter scopes are set properly - * Changed; made several private properties more obvious by prefixing _ - * Added; DBRef support [guille] - * Changed; removed support for multiple collection names per model - * Fixed; no longer applying setters when document returned from db - * Changed; default auto_reconnect to true - * Changed; Query#bind no longer clones the query - * Fixed; Model.update now accepts $pull, $inc and friends (#404) - * Added; virtual type option support [nw] - -1.8.4 / 2011-08-21 -=================== - - * Fixed; validation bug when instantiated with non-schema properties (#464) [jmreidy] - -1.8.3 / 2011-08-19 -=================== - - * Fixed; regression in connection#open [jshaw86] - -1.8.2 / 2011-08-17 -=================== - - * fixed; reset connection.readyState after failure [tomseago] - * fixed; can now query positionally for non-embedded docs (arrays of numbers/strings etc) - * fixed; embedded document query casting - * added; support for passing options to node-mongo-native db, server, and replsetserver [tomseago] - -1.8.1 / 2011-08-10 -=================== - - * fixed; ObjectIds were always marked modified - * fixed; can now query using document instances - * fixed; can now query/update using documents with subdocs - -1.8.0 / 2011-08-04 -=================== - - * fixed; can now use $all with String and Number - * fixed; can query subdoc array with $ne: null - * fixed; instance.subdocs#id now works with custom _ids - * fixed; do not apply setters when doc returned from db (change in bad behavior) - -1.7.4 / 2011-07-25 -=================== - - * fixed; sparse now a valid seperate schema option - * fixed; now catching cast errors in queries - * fixed; calling new Schema with object created in vm.runInNewContext now works (#384) [Sija] - * fixed; String enum was disallowing null - * fixed; Find by nested document _id now works (#389) - -1.7.3 / 2011-07-16 -=================== - - * fixed; MongooseArray#indexOf now works with ObjectIds - * fixed; validation scope now set properly (#418) - * fixed; added missing colors dependency (#398) - -1.7.2 / 2011-07-13 -=================== - - * changed; node-mongodb-native driver to v0.9.6.7 - -1.7.1 / 2011-07-12 -=================== - - * changed; roll back node-mongodb-native driver to v0.9.6.4 - -1.7.0 / 2011-07-12 -=================== - - * fixed; collection name misspelling [mathrawka] - * fixed; 2nd param is required for ReplSetServers [kevinmarvin] - * fixed; MongooseArray behaves properly with Object.keys - * changed; node-mongodb-native driver to v0.9.6.6 - * fixed/changed; Mongodb segfault when passed invalid ObjectId (#407) - - This means invalid data passed to the ObjectId constructor will now error - -1.6.0 / 2011-07-07 -=================== - - * changed; .save() errors are now emitted on the instances db instead of the instance 9782463fc - * fixed; errors occurring when creating indexes now properly emit on db - * added; $maxDistance support to MongooseArrays - * fixed; RegExps now work with $all - * changed; node-mongodb-native driver to v0.9.6.4 - * fixed; model names are now accessible via .modelName - * added; Query#slaveOk support - -1.5.0 / 2011-06-27 -=================== - - * changed; saving without a callback no longer ignores the error (@bnoguchi) - * changed; hook-js version bump to 0.1.9 - * changed; node-mongodb-native version bumped to 0.9.6.1 - When .remove() doesn't - return an error, null is no longer passed. - * fixed; two memory leaks (@justmoon) - * added; sparse index support - * added; more ObjectId conditionals (gt, lt, gte, lte) (@phillyqueso) - * added; options are now passed in model#remote (@JerryLuke) - -1.4.0 / 2011-06-10 -=================== - - * bumped hooks-js dependency (fixes issue passing null as first arg to next()) - * fixed; document#inspect now works properly with nested docs - * fixed; 'set' now works as a schema attribute (GH-365) - * fixed; _id is now set properly within pre-init hooks (GH-289) - * added; Query#distinct / Model#distinct support (GH-155) - * fixed; embedded docs now can use instance methods (GH-249) - * fixed; can now overwrite strings conflicting with schema type - -1.3.7 / 2011-06-03 -=================== - - * added MongooseArray#splice support - * fixed; 'path' is now a valid Schema pathname - * improved hooks (utilizing https://github.com/bnoguchi/hooks-js) - * fixed; MongooseArray#$shift now works (never did) - * fixed; Document.modified no longer throws - * fixed; modifying subdoc property sets modified paths for subdoc and parent doc - * fixed; marking subdoc path as modified properly persists the value to the db - * fixed; RexExps can again be saved ( #357 ) - -1.3.6 / 2011-05-18 -=================== - - * fixed; corrected casting for queries against array types - * added; Document#set now accepts Document instances - -1.3.5 / 2011-05-17 -=================== - - * fixed; $ne queries work properly with single vals - * added; #inspect() methods to improve console.log output - -1.3.4 / 2011-05-17 -=================== - - * fixed; find by Date works as expected (#336) - * added; geospatial 2d index support - * added; support for $near (#309) - * updated; node-mongodb-native driver - * fixed; updating numbers work (#342) - * added; better error msg when try to remove an embedded doc without an _id (#307) - * added; support for 'on-the-fly' schemas (#227) - * changed; virtual id getters can now be skipped - * fixed; .index() called on subdoc schema now works as expected - * fixed; db.setProfile() now buffers until the db is open (#340) - -1.3.3 / 2011-04-27 -=================== - - * fixed; corrected query casting on nested mixed types - -1.3.2 / 2011-04-27 -=================== - - * fixed; query hints now retain key order - -1.3.1 / 2011-04-27 -=================== - - * fixed; setting a property on an embedded array no longer overwrites entire array (GH-310) - * fixed; setting nested properties works when sibling prop is named "type" - * fixed; isModified is now much finer grained when .set() is used (GH-323) - * fixed; mongoose.model() and connection.model() now return the Model (GH-308, GH-305) - * fixed; can now use $gt, $lt, $gte, $lte with String schema types (GH-317) - * fixed; .lowercase() -> .toLowerCase() in pluralize() - * fixed; updating an embedded document by index works (GH-334) - * changed; .save() now passes the instance to the callback (GH-294, GH-264) - * added; can now query system.profile and system.indexes collections - * added; db.model('system.profile') is now included as a default Schema - * added; db.setProfiling(level, ms, callback) - * added; Query#hint() support - * added; more tests - * updated node-mongodb-native to 0.9.3 - -1.3.0 / 2011-04-19 -=================== - - * changed; save() callbacks now fire only once on failed validation - * changed; Errors returned from save() callbacks now instances of ValidationError - * fixed; MongooseArray#indexOf now works properly - -1.2.0 / 2011-04-11 -=================== - - * changed; MongooseNumber now casts empty string to null - -1.1.25 / 2011-04-08 -=================== - - * fixed; post init now fires at proper time - -1.1.24 / 2011-04-03 -=================== - - * fixed; pushing an array onto an Array works on existing docs - -1.1.23 / 2011-04-01 -=================== - - * Added Model#model - -1.1.22 / 2011-03-31 -=================== - - * Fixed; $in queries on mixed types now work - -1.1.21 / 2011-03-31 -=================== - - * Fixed; setting object root to null/undefined works - -1.1.20 / 2011-03-31 -=================== - - * Fixed; setting multiple props on null field works - -1.1.19 / 2011-03-31 -=================== - - * Fixed; no longer using $set on paths to an unexisting fields - -1.1.18 / 2011-03-30 -=================== - - * Fixed; non-mixed type object setters work after initd from null - -1.1.17 / 2011-03-30 -=================== - - * Fixed; nested object property access works when root initd with null value - -1.1.16 / 2011-03-28 -=================== - - * Fixed; empty arrays are now saved - -1.1.15 / 2011-03-28 -=================== - - * Fixed; `null` and `undefined` are set atomically. - -1.1.14 / 2011-03-28 -=================== - - * Changed; more forgiving date casting, accepting '' as null. - -1.1.13 / 2011-03-26 -=================== - - * Fixed setting values as `undefined`. - -1.1.12 / 2011-03-26 -=================== - - * Fixed; nested objects now convert to JSON properly - * Fixed; setting nested objects directly now works - * Update node-mongodb-native - -1.1.11 / 2011-03-25 -=================== - - * Fixed for use of `type` as a key. - -1.1.10 / 2011-03-23 -=================== - - * Changed; Make sure to only ensure indexes while connected - -1.1.9 / 2011-03-2 -================== - - * Fixed; Mixed can now default to empty arrays - * Fixed; keys by the name 'type' are now valid - * Fixed; null values retrieved from the database are hydrated as null values. - * Fixed repeated atomic operations when saving a same document twice. - -1.1.8 / 2011-03-23 -================== - - * Fixed 'id' overriding. [bnoguchi] - -1.1.7 / 2011-03-22 -================== - - * Fixed RegExp query casting when querying against an Array of Strings [bnoguchi] - * Fixed getters/setters for nested virtualsl. [bnoguchi] - -1.1.6 / 2011-03-22 -================== - - * Only doValidate when path exists in Schema [aheckmann] - * Allow function defaults for Array types [aheckmann] - * Fix validation hang [aheckmann] - * Fix setting of isRequired of SchemaType [aheckmann] - * Fix SchemaType#required(false) filter [aheckmann] - * More backwards compatibility [aheckmann] - * More tests [aheckmann] - -1.1.5 / 2011-03-14 -================== - - * Added support for `uri, db, fn` and `uri, fn` signatures for replica sets. - * Improved/extended replica set tests. - -1.1.4 / 2011-03-09 -================== - - * Fixed; running an empty Query doesn't throw. [aheckmann] - * Changed; Promise#addBack returns promise. [aheckmann] - * Added streaming cursor support. [aheckmann] - * Changed; Query#update defaults to use$SetOnSave now. [brian] - * Added more docs. - -1.1.3 / 2011-03-04 -================== - - * Added Promise#resolve [aheckmann] - * Fixed backward compatibility with nulls [aheckmann] - * Changed; Query#{run,exec} return promises [aheckmann] - -1.1.2 / 2011-03-03 -================== - - * Restored Query#exec and added notion of default operation [brian] - * Fixed ValidatorError messages [brian] - -1.1.1 / 2011-03-01 -================== - - * Added SchemaType String `lowercase`, `uppercase`, `trim`. - * Public exports (`Model`, `Document`) and tests. - * Added ObjectId casting support for `Document`s. - -1.1.0 / 2011-02-25 -================== - - * Added support for replica sets. - -1.0.16 / 2011-02-18 -=================== - - * Added $nin as another whitelisted $conditional for SchemaArray [brian] - * Changed #with to #where [brian] - * Added ability to use $in conditional with Array types [brian] - -1.0.15 / 2011-02-18 -=================== - - * Added `id` virtual getter for documents to easily access the hexString of - the `_id`. - -1.0.14 / 2011-02-17 -=================== - - * Fix for arrays within subdocuments [brian] - -1.0.13 / 2011-02-16 -=================== - - * Fixed embedded documents saving. - -1.0.12 / 2011-02-14 -=================== - - * Minor refactorings [brian] - -1.0.11 / 2011-02-14 -=================== - - * Query refactor and $ne, $slice, $or, $size, $elemMatch, $nin, $exists support [brian] - * Named scopes sugar [brian] - -1.0.10 / 2011-02-11 -=================== - - * Updated node-mongodb-native driver [thanks John Allen] - -1.0.9 / 2011-02-09 -================== - - * Fixed single member arrays as defaults [brian] - -1.0.8 / 2011-02-09 -================== - - * Fixed for collection-level buffering of commands [gitfy] - * Fixed `Document#toJSON` [dalejefferson] - * Fixed `Connection` authentication [robrighter] - * Fixed clash of accessors in getters/setters [eirikurn] - * Improved `Model#save` promise handling - -1.0.7 / 2011-02-05 -================== - - * Fixed memory leak warnings for test suite on 0.3 - * Fixed querying documents that have an array that contain at least one - specified member. [brian] - * Fixed default value for Array types (fixes GH-210). [brian] - * Fixed example code. - -1.0.6 / 2011-02-03 -================== - - * Fixed `post` middleware - * Fixed; it's now possible to instantiate a model even when one of the paths maps - to an undefined value [brian] - -1.0.5 / 2011-02-02 -================== - - * Fixed; combo $push and $pushAll auto-converts into a $pushAll [brian] - * Fixed; combo $pull and $pullAll auto-converts to a single $pullAll [brian] - * Fixed; $pullAll now removes said members from array before save (so it acts just - like pushAll) [brian] - * Fixed; multiple $pulls and $pushes become a single $pullAll and $pushAll. - Moreover, $pull now modifies the array before save to reflect the immediate - change [brian] - * Added tests for nested shortcut getters [brian] - * Added tests that show that Schemas with nested Arrays don't apply defaults - [brian] - -1.0.4 / 2011-02-02 -================== - - * Added MongooseNumber#toString - * Added MongooseNumber unit tests - -1.0.3 / 2011-02-02 -================== - - * Make sure safe mode works with Model#save - * Changed Schema options: safe mode is now the default - * Updated node-mongodb-native to HEAD - -1.0.2 / 2011-02-02 -================== - - * Added a Model.create shortcut for creating documents. [brian] - * Fixed; we can now instantiate models with hashes that map to at least one - null value. [brian] - * Fixed Schema with more than 2 nested levels. [brian] - -1.0.1 / 2011-02-02 -================== - - * Improved `MongooseNumber`, works almost like the native except for `typeof` - not being `'number'`. diff --git a/node_modules/mongoose/LICENSE.md b/node_modules/mongoose/LICENSE.md deleted file mode 100644 index 14cdf56..0000000 --- a/node_modules/mongoose/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -# MIT License - -Copyright (c) 2010 LearnBoost - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/node_modules/mongoose/README.md b/node_modules/mongoose/README.md deleted file mode 100644 index e6e3914..0000000 --- a/node_modules/mongoose/README.md +++ /dev/null @@ -1,369 +0,0 @@ -# Mongoose - -Mongoose is a [MongoDB](https://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks. - -[![Slack Status](http://slack.mongoosejs.io/badge.svg)](http://slack.mongoosejs.io) -[![Build Status](https://api.travis-ci.org/Automattic/mongoose.svg?branch=master)](https://travis-ci.org/Automattic/mongoose) -[![NPM version](https://badge.fury.io/js/mongoose.svg)](http://badge.fury.io/js/mongoose) - -[![npm](https://nodei.co/npm/mongoose.png)](https://www.npmjs.com/package/mongoose) - -## Documentation - -The official documentation website is [mongoosejs.com](http://mongoosejs.com/). - -[Mongoose 5.0.0](https://github.com/Automattic/mongoose/blob/master/History.md#500--2018-01-17) was released on January 17, 2018. You can find more details on [backwards breaking changes in 5.0.0 on our docs site](https://mongoosejs.com/docs/migrating_to_5.html). - -## Support - - - [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose) - - [Bug Reports](https://github.com/Automattic/mongoose/issues/) - - [Mongoose Slack Channel](http://slack.mongoosejs.io/) - - [Help Forum](http://groups.google.com/group/mongoose-orm) - - [MongoDB Support](https://docs.mongodb.org/manual/support/) - -## Plugins - -Check out the [plugins search site](http://plugins.mongoosejs.io/) to see hundreds of related modules from the community. Next, learn how to write your own plugin from the [docs](http://mongoosejs.com/docs/plugins.html) or [this blog post](http://thecodebarbarian.com/2015/03/06/guide-to-mongoose-plugins). - -## Contributors - -Pull requests are always welcome! Please base pull requests against the `master` -branch and follow the [contributing guide](https://github.com/Automattic/mongoose/blob/master/CONTRIBUTING.md). - -If your pull requests makes documentation changes, please do **not** -modify any `.html` files. The `.html` files are compiled code, so please make -your changes in `docs/*.pug`, `lib/*.js`, or `test/docs/*.js`. - -View all 400+ [contributors](https://github.com/Automattic/mongoose/graphs/contributors). - -## Installation - -First install [Node.js](http://nodejs.org/) and [MongoDB](https://www.mongodb.org/downloads). Then: - -```sh -$ npm install mongoose -``` - -## Importing - -```javascript -// Using Node.js `require()` -const mongoose = require('mongoose'); - -// Using ES6 imports -import mongoose from 'mongoose'; -``` - -## Mongoose for Enterprise - -Available as part of the Tidelift Subscription - -The maintainers of mongoose and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-mongoose?utm_source=npm-mongoose&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - -## Overview - -### Connecting to MongoDB - -First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`. - -Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`. - -```js -await mongoose.connect('mongodb://localhost/my_database', { - useNewUrlParser: true, - useUnifiedTopology: true -}); -``` - -Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`. - -**Note:** _If the local connection fails then try using 127.0.0.1 instead of localhost. Sometimes issues may arise when the local hostname has been changed._ - -**Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc. - -### Defining a Model - -Models are defined through the `Schema` interface. - -```js -const Schema = mongoose.Schema; -const ObjectId = Schema.ObjectId; - -const BlogPost = new Schema({ - author: ObjectId, - title: String, - body: String, -  date: Date -}); -``` - -Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of: - -* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync) -* [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default) -* [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get) -* [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set) -* [Indexes](http://mongoosejs.com/docs/guide.html#indexes) -* [Middleware](http://mongoosejs.com/docs/middleware.html) -* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition -* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition -* [Plugins](http://mongoosejs.com/docs/plugins.html) -* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html) - -The following example shows some of these features: - -```js -const Comment = new Schema({ - name: { type: String, default: 'hahaha' }, - age: { type: Number, min: 18, index: true }, - bio: { type: String, match: /[a-z]/ }, - date: { type: Date, default: Date.now }, - buff: Buffer -}); - -// a setter -Comment.path('name').set(function (v) { - return capitalize(v); -}); - -// middleware -Comment.pre('save', function (next) { - notify(this.get('email')); - next(); -}); -``` - -Take a look at the example in [`examples/schema/schema.js`](https://github.com/Automattic/mongoose/blob/master/examples/schema/schema.js) for an end-to-end example of a typical setup. - -### Accessing a Model - -Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function - -```js -const MyModel = mongoose.model('ModelName'); -``` - -Or just do it all at once - -```js -const MyModel = mongoose.model('ModelName', mySchema); -``` - -The first argument is the _singular_ name of the collection your model is for. **Mongoose automatically looks for the _plural_ version of your model name.** For example, if you use - -```js -const MyModel = mongoose.model('Ticket', mySchema); -``` - -Then Mongoose will create the model for your __tickets__ collection, not your __ticket__ collection. - -Once we have our model, we can then instantiate it, and save it: - -```js -const instance = new MyModel(); -instance.my.key = 'hello'; -instance.save(function (err) { - // -}); -``` - -Or we can find documents from the same collection - -```js -MyModel.find({}, function (err, docs) { - // docs.forEach -}); -``` - -You can also `findOne`, `findById`, `update`, etc. - -```js -const instance = await MyModel.findOne({ ... }); -console.log(instance.my.key); // 'hello' -``` - -For more details check out [the docs](http://mongoosejs.com/docs/queries.html). - -**Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created: - -```js -const conn = mongoose.createConnection('your connection string'); -const MyModel = conn.model('ModelName', schema); -const m = new MyModel; -m.save(); // works -``` - -vs - -```js -const conn = mongoose.createConnection('your connection string'); -const MyModel = mongoose.model('ModelName', schema); -const m = new MyModel; -m.save(); // does not work b/c the default connection object was never connected -``` - -### Embedded Documents - -In the first example snippet, we defined a key in the Schema that looks like: - -``` -comments: [Comment] -``` - -Where `Comment` is a `Schema` we created. This means that creating embedded documents is as simple as: - -```js -// retrieve my model -const BlogPost = mongoose.model('BlogPost'); - -// create a blog post -const post = new BlogPost(); - -// create a comment -post.comments.push({ title: 'My comment' }); - -post.save(function (err) { - if (!err) console.log('Success!'); -}); -``` - -The same goes for removing them: - -```js -BlogPost.findById(myId, function (err, post) { - if (!err) { - post.comments[0].remove(); - post.save(function (err) { - // do something - }); - } -}); -``` - -Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it's bubbled to the `save()` error callback, so error handling is a snap! - - -### Middleware - -See the [docs](http://mongoosejs.com/docs/middleware.html) page. - -#### Intercepting and mutating method arguments - -You can intercept method arguments via middleware. - -For example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value: - -```js -schema.pre('set', function (next, path, val, typel) { - // `this` is the current Document - this.emit('set', path, val); - - // Pass control to the next pre - next(); -}); -``` - -Moreover, you can mutate the incoming `method` arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to `next`: - -```js -.pre(method, function firstPre (next, methodArg1, methodArg2) { - // Mutate methodArg1 - next("altered-" + methodArg1.toString(), methodArg2); -}); - -// pre declaration is chainable -.pre(method, function secondPre (next, methodArg1, methodArg2) { - console.log(methodArg1); - // => 'altered-originalValOfMethodArg1' - - console.log(methodArg2); - // => 'originalValOfMethodArg2' - - // Passing no arguments to `next` automatically passes along the current argument values - // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)` - // and also equivalent to, with the example method arg - // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')` - next(); -}); -``` - -#### Schema gotcha - -`type`, when used in a schema has special meaning within Mongoose. If your schema requires using `type` as a nested property you must use object notation: - -```js -new Schema({ - broken: { type: Boolean }, - asset: { - name: String, - type: String // uh oh, it broke. asset will be interpreted as String - } -}); - -new Schema({ - works: { type: Boolean }, - asset: { - name: String, - type: { type: String } // works. asset is an object with a type property - } -}); -``` - -### Driver Access - -Mongoose is built on top of the [official MongoDB Node.js driver](https://github.com/mongodb/node-mongodb-native). Each mongoose model keeps a reference to a [native MongoDB driver collection](http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html). The collection object can be accessed using `YourModel.collection`. However, using the collection object directly bypasses all mongoose features, including hooks, validation, etc. The one -notable exception that `YourModel.collection` still buffers -commands. As such, `YourModel.collection.find()` will **not** -return a cursor. - -## API Docs - -Find the API docs [here](http://mongoosejs.com/docs/api.html), generated using [dox](https://github.com/tj/dox) -and [acquit](https://github.com/vkarpov15/acquit). - -## Related Projects - -#### MongoDB Runners - -- [run-rs](https://www.npmjs.com/package/run-rs) -- [mongodb-memory-server](https://www.npmjs.com/package/mongodb-memory-server) -- [mongodb-topology-manager](https://www.npmjs.com/package/mongodb-topology-manager) - -#### Unofficial CLIs - -- [mongoosejs-cli](https://www.npmjs.com/package/mongoosejs-cli) - -#### Data Seeding - -- [dookie](https://www.npmjs.com/package/dookie) -- [seedgoose](https://www.npmjs.com/package/seedgoose) -- [mongoose-data-seed](https://www.npmjs.com/package/mongoose-data-seed) - -#### Express Session Stores - -- [connect-mongodb-session](https://www.npmjs.com/package/connect-mongodb-session) -- [connect-mongo](https://www.npmjs.com/package/connect-mongo) - -## License - -Copyright (c) 2010 LearnBoost <dev@learnboost.com> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/SECURITY.md b/node_modules/mongoose/SECURITY.md deleted file mode 100644 index 41b89d8..0000000 --- a/node_modules/mongoose/SECURITY.md +++ /dev/null @@ -1 +0,0 @@ -Please follow the instructions on [Tidelift's security page](https://tidelift.com/docs/security) to report a security issue. diff --git a/node_modules/mongoose/browser.js b/node_modules/mongoose/browser.js deleted file mode 100644 index 4cf8228..0000000 --- a/node_modules/mongoose/browser.js +++ /dev/null @@ -1,8 +0,0 @@ -/** - * Export lib/mongoose - * - */ - -'use strict'; - -module.exports = require('./lib/browser'); diff --git a/node_modules/mongoose/build-browser.js b/node_modules/mongoose/build-browser.js deleted file mode 100644 index 6f4aa16..0000000 --- a/node_modules/mongoose/build-browser.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -const config = require('./webpack.config.js'); -const webpack = require('webpack'); - -const compiler = webpack(config); - -console.log('Starting browser build...'); -compiler.run((err, stats) => { - if (err) { - console.err(stats.toString()); - console.err('Browser build unsuccessful.'); - process.exit(1); - } - console.log(stats.toString()); - console.log('Browser build successful.'); - process.exit(0); -}); diff --git a/node_modules/mongoose/dist/browser.umd.js b/node_modules/mongoose/dist/browser.umd.js deleted file mode 100644 index d65f026..0000000 --- a/node_modules/mongoose/dist/browser.umd.js +++ /dev/null @@ -1,1547 +0,0 @@ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.mongoose=e():t.mongoose=e()}("undefined"!=typeof self?self:this,function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var i=e[n]={i:n,l:!1,exports:{}};return t[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)r.d(n,i,function(e){return t[e]}.bind(null,i));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=93)}([function(t,e,r){"use strict";e.arrayAtomicsSymbol=Symbol("mongoose#Array#_atomics"),e.arrayParentSymbol=Symbol("mongoose#Array#_parent"),e.arrayPathSymbol=Symbol("mongoose#Array#_path"),e.arraySchemaSymbol=Symbol("mongoose#Array#_schema"),e.documentArrayParent=Symbol("mongoose:documentArrayParent"),e.documentSchemaSymbol=Symbol("mongoose#Document#schema"),e.getSymbol=Symbol("mongoose#Document#get"),e.modelSymbol=Symbol("mongoose#Model"),e.objectIdSymbol=Symbol("mongoose#ObjectId"),e.populateModelSymbol=Symbol("mongoose.PopulateOptions#Model"),e.schemaTypeSymbol=Symbol("mongoose#schemaType"),e.validatorErrorSymbol=Symbol("mongoose:validatorError")},function(t,e,r){"use strict";(function(t){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -var n=r(95),i=r(96),o=r(97);function s(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(t,e){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|t}function d(t,e){if(u.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return L(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return U(t).length;default:if(n)return L(t).length;e=(""+e).toLowerCase(),n=!0}}function y(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function v(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=u.from(e,n)),u.isBuffer(e))return 0===e.length?-1:_(t,e,r,n,i);if("number"==typeof e)return e&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):_(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function _(t,e,r,n,i){var o,s=1,a=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,a/=2,u/=2,r/=2}function c(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var l=-1;for(o=r;oa&&(r=a-u),o=r;o>=0;o--){for(var f=!0,h=0;hi&&(n=i):n=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function E(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function A(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:c>223?3:c>191?2:1;if(i+f<=r)switch(f){case 1:c<128&&(l=c);break;case 2:128==(192&(o=t[i+1]))&&(u=(31&c)<<6|63&o)>127&&(l=u);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(u=(15&c)<<12|(63&o)<<6|63&s)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:o=t[i+1],s=t[i+2],a=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(u=(15&c)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(l=u)}null===l?(l=65533,f=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),i+=f}return function(t){var e=t.length;if(e<=$)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return N(this,e,r);case"utf8":case"utf-8":return A(this,e,r);case"ascii":return j(this,e,r);case"latin1":case"binary":return x(this,e,r);case"base64":return E(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},u.prototype.equals=function(t){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===u.compare(this,t)},u.prototype.inspect=function(){var t="",r=e.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(t+=" ... ")),""},u.prototype.compare=function(t,e,r,n,i){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var o=i-n,s=r-e,a=Math.min(o,s),c=this.slice(n,i),l=t.slice(e,r),f=0;fi)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return m(this,t,e,r);case"utf8":case"utf-8":return g(this,t,e,r);case"ascii":return b(this,t,e,r);case"latin1":case"binary":return w(this,t,e,r);case"base64":return O(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var $=4096;function j(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function T(t,e,r,n,i,o){if(!u.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function B(t,e,r,n){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-r,2);i>>8*(n?i:1-i)}function C(t,e,r,n){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-r,4);i>>8*(n?i:3-i)&255}function D(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function M(t,e,r,n,o){return o||D(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function R(t,e,r,n,o){return o||D(t,0,r,8),i.write(t,e,r,n,52,8),r+8}u.prototype.slice=function(t,e){var r,n=this.length;if(t=~~t,e=void 0===e?n:~~e,t<0?(t+=n)<0&&(t=0):t>n&&(t=n),e<0?(e+=n)<0&&(e=0):e>n&&(e=n),e0&&(i*=256);)n+=this[t+--e]*i;return n},u.prototype.readUInt8=function(t,e){return e||k(t,1,this.length),this[t]},u.prototype.readUInt16LE=function(t,e){return e||k(t,2,this.length),this[t]|this[t+1]<<8},u.prototype.readUInt16BE=function(t,e){return e||k(t,2,this.length),this[t]<<8|this[t+1]},u.prototype.readUInt32LE=function(t,e){return e||k(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},u.prototype.readUInt32BE=function(t,e){return e||k(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},u.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||k(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},u.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||k(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},u.prototype.readInt8=function(t,e){return e||k(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},u.prototype.readInt16LE=function(t,e){e||k(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(t,e){e||k(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(t,e){return e||k(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},u.prototype.readInt32BE=function(t,e){return e||k(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},u.prototype.readFloatLE=function(t,e){return e||k(t,4,this.length),i.read(this,t,!0,23,4)},u.prototype.readFloatBE=function(t,e){return e||k(t,4,this.length),i.read(this,t,!1,23,4)},u.prototype.readDoubleLE=function(t,e){return e||k(t,8,this.length),i.read(this,t,!0,52,8)},u.prototype.readDoubleBE=function(t,e){return e||k(t,8,this.length),i.read(this,t,!1,52,8)},u.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||T(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o=0&&(o*=256);)this[e+i]=t/o&255;return e+r},u.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||T(this,t,e,1,255,0),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},u.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||T(this,t,e,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):B(this,t,e,!0),e+2},u.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||T(this,t,e,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):B(this,t,e,!1),e+2},u.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||T(this,t,e,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):C(this,t,e,!0),e+4},u.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||T(this,t,e,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):C(this,t,e,!1),e+4},u.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);T(this,t,e,r,i-1,-i)}var o=0,s=1,a=0;for(this[e]=255&t;++o>0)-a&255;return e+r},u.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var i=Math.pow(2,8*r-1);T(this,t,e,r,i-1,-i)}var o=r-1,s=1,a=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===a&&0!==this[e+o+1]&&(a=1),this[e+o]=(t/s>>0)-a&255;return e+r},u.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||T(this,t,e,1,127,-128),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},u.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||T(this,t,e,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):B(this,t,e,!0),e+2},u.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||T(this,t,e,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):B(this,t,e,!1),e+2},u.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||T(this,t,e,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):C(this,t,e,!0),e+4},u.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||T(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):C(this,t,e,!1),e+4},u.prototype.writeFloatLE=function(t,e,r){return M(this,t,e,!0,r)},u.prototype.writeFloatBE=function(t,e,r){return M(this,t,e,!1,r)},u.prototype.writeDoubleLE=function(t,e,r){return R(this,t,e,!0,r)},u.prototype.writeDoubleBE=function(t,e,r){return R(this,t,e,!1,r)},u.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e=0;--i)t[i+e]=this[i+r];else if(o<1e3||!u.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(o=e;o55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function U(t){return n.toByteArray(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(F,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function V(t,e,r,n){for(var i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}}).call(this,r(11))},function(t,e,r){"use strict";(function(t){ -/*! - * Module dependencies. - */ -var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(111),o=r(44),s=r(62),a=r(45).Buffer,u=r(19),c=r(12),l=r(113),f=r(46),h=r(20),p=r(65),d=r(64),y=r(27),v=r(24),_=r(47),m=void 0;e.specialProperties=_, -/*! - * Produces a collection name from model `name`. By default, just returns - * the model name - * - * @param {String} name a model name - * @param {Function} pluralize function that pluralizes the collection name - * @return {String} a collection name - * @api private - */ -e.toCollectionName=function(t,e){return"system.profile"===t?t:"system.indexes"===t?t:"function"==typeof e?e(t):t}, -/*! - * Determines if `a` and `b` are deep equal. - * - * Modified from node/lib/assert.js - * - * @param {any} a a value to compare to `b` - * @param {any} b a value to compare to `a` - * @return {Boolean} - * @api private - */ -e.deepEqual=function t(r,i){if(r===i)return!0;if(r instanceof Date&&i instanceof Date)return r.getTime()===i.getTime();if(p(r,"ObjectID")&&p(i,"ObjectID")||p(r,"Decimal128")&&p(i,"Decimal128"))return r.toString()===i.toString();if(r instanceof RegExp&&i instanceof RegExp)return r.source===i.source&&r.ignoreCase===i.ignoreCase&&r.multiline===i.multiline&&r.global===i.global;if("object"!==(void 0===r?"undefined":n(r))&&"object"!==(void 0===i?"undefined":n(i)))return r==i;if(null===r||null===i||void 0===r||void 0===i)return!1;if(r.prototype!==i.prototype)return!1;if(r instanceof Number&&i instanceof Number)return r.valueOf()===i.valueOf();if(a.isBuffer(r))return e.buffer.areEqual(r,i);y(r)&&(r=r.toObject()),y(i)&&(i=i.toObject());var o=void 0,s=void 0,u=void 0,c=void 0;try{o=Object.keys(r),s=Object.keys(i)}catch(t){return!1}if(o.length!==s.length)return!1;for(o.sort(),s.sort(),c=o.length-1;c>=0;c--)if(o[c]!==s[c])return!1;for(c=o.length-1;c>=0;c--)if(!t(r[u=o[c]],i[u]))return!1;return!0}, -/*! - * Get the last element of an array - */ -e.last=function(t){if(t.length>0)return t[t.length-1]},e.clone=f, -/*! - * ignore - */ -e.promiseOrCallback=v, -/*! - * ignore - */ -e.omit=function(t,e){if(null==e)return Object.assign({},t);Array.isArray(e)||(e=[e]);var r=Object.assign({},t),n=!0,i=!1,o=void 0;try{for(var s,a=e[Symbol.iterator]();!(n=(s=a.next()).done);n=!0){delete r[s.value]}}catch(t){i=!0,o=t}finally{try{!n&&a.return&&a.return()}finally{if(i)throw o}}return r}, -/*! - * Shallow copies defaults into options. - * - * @param {Object} defaults - * @param {Object} options - * @return {Object} the merged object - * @api private - */ -e.options=function(t,e){var r=Object.keys(t),n=r.length,i=void 0;for(e=e||{};n--;)(i=r[n])in e||(e[i]=t[i]);return e}, -/*! - * Generates a random string - * - * @api private - */ -e.random=function(){return Math.random().toString().substr(3)}, -/*! - * Merges `from` into `to` without overwriting existing properties. - * - * @param {Object} to - * @param {Object} from - * @api private - */ -e.merge=function t(r,n,i,o){i=i||{};var s=Object.keys(n),a=0,u=s.length,l=void 0;o=o||"";for(var f=i.omitNested||{};a [1,2,3,4] - * - * @param {Array} arr - * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsy value, the item will not be included in the results. - * @return {Array} - * @private - */ -e.array.flatten=function t(e,r,n){return n||(n=[]),e.forEach(function(e){Array.isArray(e)?t(e,r,n):r&&!r(e)||n.push(e)}),n}; -/*! - * ignore - */ -var b=Object.prototype.hasOwnProperty;e.hasUserDefinedProperty=function(t,r){if(null==t)return!1;if(Array.isArray(r)){var i=!0,o=!1,s=void 0;try{for(var a,u=r[Symbol.iterator]();!(i=(a=u.next()).done);i=!0){var c=a.value;if(e.hasUserDefinedProperty(t,c))return!0}}catch(t){o=!0,s=t}finally{try{!i&&u.return&&u.return()}finally{if(o)throw s}}return!1}if(b.call(t,r))return!0;if("object"===(void 0===t?"undefined":n(t))&&r in t){var l=t[r];return l!==Object.prototype[r]&&l!==Array.prototype[r]}return!1}; -/*! - * ignore - */ -var w=Math.pow(2,32)-1;e.isArrayIndex=function(t){return"number"==typeof t?t>=0&&t<=w:"string"==typeof t&&(!!/^\d+$/.test(t)&&((t=+t)>=0&&t<=w))}, -/*! - * Removes duplicate values from an array - * - * [1, 2, 3, 3, 5] => [1, 2, 3, 5] - * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ] - * => [ObjectId("550988ba0c19d57f697dc45e")] - * - * @param {Array} arr - * @return {Array} - * @private - */ -e.array.unique=function(t){var e={},r={},n=[],i=!0,o=!1,s=void 0;try{for(var a,u=t[Symbol.iterator]();!(i=(a=u.next()).done);i=!0){var l=a.value;if("number"==typeof l||"string"==typeof l||null==l){if(e[l])continue;n.push(l),e[l]=!0}else if(l instanceof c){if(r[l.toString()])continue;n.push(l),r[l.toString()]=!0}else n.push(l)}}catch(t){o=!0,s=t}finally{try{!i&&u.return&&u.return()}finally{if(o)throw s}}return n}, -/*! - * Determines if two buffers are equal. - * - * @param {Buffer} a - * @param {Object} b - */ -e.buffer={},e.buffer.areEqual=function(t,e){if(!a.isBuffer(t))return!1;if(!a.isBuffer(e))return!1;if(t.length!==e.length)return!1;for(var r=0,n=t.length;r=i)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}}),a=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),y(r)?n.showHidden=r:r&&e._extend(n,r),g(n.showHidden)&&(n.showHidden=!1),g(n.depth)&&(n.depth=2),g(n.colors)&&(n.colors=!1),g(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=c),f(n,t,n.depth)}function c(t,e){var r=u.styles[e];return r?"["+u.colors[r][0]+"m"+t+"["+u.colors[r][1]+"m":t}function l(t,e){return t}function f(t,r,n){if(t.customInspect&&r&&E(r.inspect)&&r.inspect!==e.inspect&&(!r.constructor||r.constructor.prototype!==r)){var i=r.inspect(n,t);return m(i)||(i=f(t,i,n)),i}var o=function(t,e){if(g(e))return t.stylize("undefined","undefined");if(m(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(_(e))return t.stylize(""+e,"number");if(y(e))return t.stylize(""+e,"boolean");if(v(e))return t.stylize("null","null")}(t,r);if(o)return o;var s=Object.keys(r),a=function(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}(s);if(t.showHidden&&(s=Object.getOwnPropertyNames(r)),S(r)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return h(r);if(0===s.length){if(E(r)){var u=r.name?": "+r.name:"";return t.stylize("[Function"+u+"]","special")}if(b(r))return t.stylize(RegExp.prototype.toString.call(r),"regexp");if(O(r))return t.stylize(Date.prototype.toString.call(r),"date");if(S(r))return h(r)}var c,l="",w=!1,A=["{","}"];(d(r)&&(w=!0,A=["[","]"]),E(r))&&(l=" [Function"+(r.name?": "+r.name:"")+"]");return b(r)&&(l=" "+RegExp.prototype.toString.call(r)),O(r)&&(l=" "+Date.prototype.toUTCString.call(r)),S(r)&&(l=" "+h(r)),0!==s.length||w&&0!=r.length?n<0?b(r)?t.stylize(RegExp.prototype.toString.call(r),"regexp"):t.stylize("[Object]","special"):(t.seen.push(r),c=w?function(t,e,r,n,i){for(var o=[],s=0,a=e.length;s=0&&0,t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(c,l,A)):A[0]+l+A[1]}function h(t){return"["+Error.prototype.toString.call(t)+"]"}function p(t,e,r,n,i,o){var s,a,u;if((u=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?a=u.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):u.set&&(a=t.stylize("[Setter]","special")),x(n,i)||(s="["+i+"]"),a||(t.seen.indexOf(u.value)<0?(a=v(r)?f(t,u.value,null):f(t,u.value,r-1)).indexOf("\n")>-1&&(a=o?a.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+a.split("\n").map(function(t){return" "+t}).join("\n")):a=t.stylize("[Circular]","special")),g(s)){if(o&&i.match(/^\d+$/))return a;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=t.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=t.stylize(s,"string"))}return s+": "+a}function d(t){return Array.isArray(t)}function y(t){return"boolean"==typeof t}function v(t){return null===t}function _(t){return"number"==typeof t}function m(t){return"string"==typeof t}function g(t){return void 0===t}function b(t){return w(t)&&"[object RegExp]"===A(t)}function w(t){return"object"===(void 0===t?"undefined":n(t))&&null!==t}function O(t){return w(t)&&"[object Date]"===A(t)}function S(t){return w(t)&&("[object Error]"===A(t)||t instanceof Error)}function E(t){return"function"==typeof t}function A(t){return Object.prototype.toString.call(t)}function $(t){return t<10?"0"+t.toString(10):t.toString(10)}e.debuglog=function(r){if(g(s)&&(s=t.env.NODE_DEBUG||""),r=r.toUpperCase(),!a[r])if(new RegExp("\\b"+r+"\\b","i").test(s)){var n=t.pid;a[r]=function(){var t=e.format.apply(e,arguments);console.error("%s %d: %s",r,n,t)}}else a[r]=function(){};return a[r]},e.inspect=u,u.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},u.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},e.isArray=d,e.isBoolean=y,e.isNull=v,e.isNullOrUndefined=function(t){return null==t},e.isNumber=_,e.isString=m,e.isSymbol=function(t){return"symbol"===(void 0===t?"undefined":n(t))},e.isUndefined=g,e.isRegExp=b,e.isObject=w,e.isDate=O,e.isError=S,e.isFunction=E,e.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"===(void 0===t?"undefined":n(t))||void 0===t},e.isBuffer=r(100);var j=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function x(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.log=function(){console.log("%s - %s",function(){var t=new Date,e=[$(t.getHours()),$(t.getMinutes()),$(t.getSeconds())].join(":");return[t.getDate(),j[t.getMonth()],e].join(" ")}(),e.format.apply(e,arguments))},e.inherits=r(101),e._extend=function(t,e){if(!e||!w(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t};var N="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function P(t,e){if(!t){var r=new Error("Promise was rejected with a falsy value");r.reason=t,t=r}return e(t)}e.promisify=function(t){if("function"!=typeof t)throw new TypeError('The "original" argument must be of type Function');if(N&&t[N]){var e;if("function"!=typeof(e=t[N]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(e,N,{value:e,enumerable:!1,writable:!1,configurable:!0}),e}function e(){for(var e,r,n=new Promise(function(t,n){e=t,r=n}),i=[],o=0;o0?".":"")+I[y],q||(this.$set(W,{}),this.isSelected(W)||this.unmarkModified(W),q=this.$__getValue(W));var Y=void 0;if(I.length<=1)Y=t;else{for(y=0;y0&&null!=e[0]&&null!=e[0].$__&&null!=e[0].$__.populated){var st=Object.keys(e[0].$__.populated),at=!0,ut=!1,ct=void 0;try{for(var lt,ft=function(){var r=lt.value;s.populated(t+"."+r,e.map(function(t){return t.populated(r)}),e[0].$__.populated[r].options)},ht=st[Symbol.iterator]();!(at=(lt=ht.next()).done);at=!0)ft()}catch(t){ut=!0,ct=t}finally{try{!at&&ht.return&&ht.return()}finally{if(ut)throw ct}}it=!0}if(!it&&this.$__.populated){if(Array.isArray(e)&&this.$__.populated[t])for(var pt=0;pt0){var r=this.get(t);return null==r||"object"===(void 0===r?"undefined":i(r))&&(T.isPOJO(r)?function t(e){if(null==e)return!0;if("object"!==(void 0===e?"undefined":i(e))||Array.isArray(e))return!1;var r=!0;var n=!1;var o=void 0;try{for(var s,a=Object.keys(e)[Symbol.iterator]();!(r=(s=a.next()).done);r=!0){var u=s.value;if(!t(e[u]))return!1}}catch(t){n=!0,o=t}finally{try{!r&&a.return&&a.return()}finally{if(n)throw o}}return!0}(r):0===Object.keys(r.toObject(e)).length)}return 0===Object.keys(this.toObject(e)).length},H.prototype.modifiedPaths=function(t){t=t||{};var e=this;return Object.keys(this.$__.activePaths.states.modify).reduce(function(r,n){var o=n.split(".");if(r=r.concat(o.reduce(function(t,e,r){return t.concat(o.slice(0,r).concat(e).join("."))},[]).filter(function(t){return-1===r.indexOf(t)})),!t.includeChildren)return r;var s=e.get(n);if(null!=s&&"object"===(void 0===s?"undefined":i(s)))if(s._doc&&(s=s._doc),Array.isArray(s)){for(var a=s.length,u=0;ue.path?1:0});var r=[],n=void 0,i=void 0;return e.forEach(function(t){t&&(null==n||0!==t.path.indexOf(n)?(n=t.path+".",r.push(t),i=t):null!=i&&null!=i.value&&null!=i.value[M]&&i.value.hasAtomics()&&(i.value[M]={},i.value[M].$set=i.value))}),i=n=null,r},H.prototype.$__setSchema=function(t){t.plugin($,{deduplicate:!0}),b(t.tree,this,void 0,t.options);var e=!0,r=!1,n=void 0;try{for(var i,o=Object.keys(t.virtuals)[Symbol.iterator]();!(e=(i=o.next()).done);e=!0){var s=i.value;t.virtuals[s]._applyDefaultGetters()}}catch(t){r=!0,n=t}finally{try{!e&&o.return&&o.return()}finally{if(r)throw n}}this.schema=t,this[F]=t},H.prototype.$__getArrayPathsToValidate=function(){return U||(U=r(17)),this.$__.activePaths.map("init","modify",function(t){return this.$__getValue(t)}.bind(this)).filter(function(t){return t&&t instanceof Array&&t.isMongooseDocumentArray&&t.length}).reduce(function(t,e){return t.concat(e)},[]).filter(function(t){return t})},H.prototype.$__getAllSubdocs=function(){U||(U=r(17)),q=q||r(25);var t=this;return Object.keys(this._doc).reduce(function(e,r){return function t(e,r,n){var i=e;return n&&(i=e instanceof H&&e[F].paths[n]?e._doc[n]:e[n]),i instanceof q?r.push(i):i instanceof Map?r=Array.from(i.keys()).reduce(function(e,r){return t(i.get(r),e,null)},r):i&&i.$isSingleNested?(r=Object.keys(i._doc).reduce(function(e,r){return t(i._doc,e,r)},r)).push(i):i&&i.isMongooseDocumentArray?i.forEach(function(e){e&&e._doc&&(r=Object.keys(e._doc).reduce(function(r,n){return t(e._doc,r,n)},r),e instanceof q&&r.push(e))}):i instanceof H&&i.$__isNested&&(r=Object.keys(i).reduce(function(e,r){return t(i,e,r)},r)),r}(t,e,r)},[])},H.prototype.$__handleReject=function(t){this.listeners("error").length?this.emit("error",t):this.constructor.listeners&&this.constructor.listeners("error").length?this.constructor.emit("error",t):this.listeners&&this.listeners("error").length&&this.emit("error",t)},H.prototype.$toObject=function(t,e){var r={transform:!0,flattenDecimals:!0},i=e?"toJSON":"toObject",o=S(this,"constructor.base.options."+i,{}),s=S(this,"schema.options",{});r=T.options(r,B(o)),r=T.options(r,B(s[i]||{})),"flattenMaps"in(t=T.isPOJO(t)?B(t):{})||(t.flattenMaps=r.flattenMaps);var a=void 0;a=null!=t.minimize?t.minimize:null!=r.minimize?r.minimize:s.minimize;var u=Object.assign(T.clone(t),{_isNested:!0,json:e,minimize:a});if(T.hasUserDefinedProperty(t,"getters")&&(u.getters=t.getters),T.hasUserDefinedProperty(t,"virtuals")&&(u.virtuals=t.virtuals),(t.depopulate||S(t,"_parentOptions.depopulate",!1))&&t._isNested&&this.$__.wasPopulated)return B(this._id,u);(t=T.options(r,t))._isNested=!0,t.json=e,t.minimize=a,u._parentOptions=t,u._skipSingleNestedGetters=!0;var c=Object.assign({},u);c._skipSingleNestedGetters=!1;var l=t.transform,f=B(this._doc,u)||{};t.getters&&(!function(t,e,r){var n=t.schema,i=Object.keys(n.paths),o=i.length,s=void 0,a=t._doc,u=void 0;if(!a)return e;for(;o--;){var c=(s=i[o]).split("."),l=c.length,f=l-1,h=e,p=void 0;if(a=t._doc,t.isSelected(s))for(var d=0;d1&&(this.defaultValue=d.args(arguments)),this.defaultValue},m.prototype.index=function(t){return this._index=t,d.expires(this._index),this},m.prototype.unique=function(t){if(!1===this._index){if(!t)return;throw new Error('Path "'+this.path+'" may not have `index` set to false and `unique` set to true')}return null==this._index||!0===this._index?this._index={}:"string"==typeof this._index&&(this._index={type:this._index}),this._index.unique=t,this},m.prototype.text=function(t){if(!1===this._index){if(!t)return;throw new Error('Path "'+this.path+'" may not have `index` set to false and `text` set to true')}return null===this._index||void 0===this._index||"boolean"==typeof this._index?this._index={}:"string"==typeof this._index&&(this._index={type:this._index}),this._index.text=t,this},m.prototype.sparse=function(t){if(!1===this._index){if(!t)return;throw new Error('Path "'+this.path+'" may not have `index` set to false and `sparse` set to true')}return null==this._index||"boolean"==typeof this._index?this._index={}:"string"==typeof this._index&&(this._index={type:this._index}),this._index.sparse=t,this},m.prototype.immutable=function(t){return this.$immutable=t,l(this),this},m.prototype.set=function(t){if("function"!=typeof t)throw new TypeError("A setter must be a function.");return this.setters.push(t),this},m.prototype.get=function(t){if("function"!=typeof t)throw new TypeError("A getter must be a function.");return this.getters.push(t),this},m.prototype.validate=function(t,e,r){if("function"==typeof t||t&&"RegExp"===d.getFunctionName(t.constructor)){var n=void 0;return"function"==typeof e?(n={validator:t,message:e}).type=r||"user defined":e instanceof Object&&!r?((n=d.clone(e)).message||(n.message=n.msg),n.validator=t,n.type=n.type||"user defined"):(null==e&&(e=o.messages.general.default),r||(r="user defined"),n={message:e,type:r,validator:t}),n.isAsync&&g(),this.validators.push(n),this}var s,a=void 0,u=void 0;for(a=0,s=arguments.length;a0&&null==t)return this.validators=this.validators.filter(function(t){return t.validator!==this.requiredValidator},this),this.isRequired=!1,delete this.originalRequiredValue,this;if("object"===(void 0===t?"undefined":i(t))&&(e=(r=t).message||e,t=t.isRequired),!1===t)return this.validators=this.validators.filter(function(t){return t.validator!==this.requiredValidator},this),this.isRequired=!1,delete this.originalRequiredValue,this;var n=this;this.isRequired=!0,this.requiredValidator=function(e){var r=c(this,"$__.cachedRequired");if(null!=r&&!this.isSelected(n.path)&&!this.isModified(n.path))return!0;if(null!=r&&n.path in r){var i=!r[n.path]||n.checkRequired(e,this);return delete r[n.path],i}return"function"==typeof t&&!t.apply(this)||n.checkRequired(e,this)},this.originalRequiredValue=t,"string"==typeof t&&(e=t,t=void 0);var s=e||o.messages.general.required;return this.validators.unshift(Object.assign({},r,{validator:this.requiredValidator,message:s,type:"required"})),this},m.prototype.ref=function(t){return this.options.ref=t,this},m.prototype.getDefault=function(t,e){var r="function"==typeof this.defaultValue?this.defaultValue.call(t):this.defaultValue;if(null!==r&&void 0!==r){"object"!==(void 0===r?"undefined":i(r))||this.options&&this.options.shared||(r=d.clone(r));var n=this.applySetters(r,t,e);return n&&n.$isSingleNested&&(n.$parent=t),n}return r}, -/*! - * Applies setters without casting - * - * @api private - */ -m.prototype._applySetters=function(t,e,r,n){var i=t,s=this.setters,a=this.caster,u=!0,c=!1,l=void 0;try{for(var f,h=d.clone(s).reverse()[Symbol.iterator]();!(u=(f=h.next()).done);u=!0){i=f.value.call(e,i,this)}}catch(t){c=!0,l=t}finally{try{!u&&h.return&&h.return()}finally{if(c)throw l}}if(Array.isArray(i)&&a&&a.setters){for(var p=[],y=0;y0&&"required"===this.validators[0].type))return null;o=[this.validators[0]]}var s=null;return o.forEach(function(o){if(!s&&null!=o&&"object"===(void 0===o?"undefined":i(o))){var u=o.validator,c=d.clone(o);c.path=r&&r.path?r.path:n,c.value=t;var l=void 0;if(!u.isAsync)if(u instanceof RegExp)a(u.test(t),c);else if("function"==typeof u){try{l=c.propsParameter?u.call(e,t,c):u.call(e,t)}catch(t){l=!1,c.reason=t}null!=l&&"function"==typeof l.then||a(l,c)}}}),s;function a(t,e){if(!s&&void 0!==t&&!t){var r=e.ErrorConstructor||_;(s=new r(e))[y]=!0}}},m._isRef=function(t,e,r,i){var o=i&&t.options&&(t.options.ref||t.options.refPath);if(!o&&r&&null!=r.$__){var s=r.$__fullPath(t.path);o=(r.ownerDocument?r.ownerDocument():r).populated(s)||r.populated(t.path)}if(o){if(null==e)return!0;if(!n.isBuffer(e)&&"Binary"!==e._bsontype&&d.isObject(e))return!0}return!1},m.prototype.$conditionalHandlers={$all:function(t){var e=this;return Array.isArray(t)?t.map(function(t){return e.castForQuery(t)}):[this.castForQuery(t)]},$eq:b,$in:w,$ne:b,$nin:w,$exists:a,$type:u}, -/*! - * Wraps `castForQuery` to handle context - */ -m.prototype.castForQueryWrapper=function(t){return this.$$context=t.context,"$conditional"in t?this.castForQuery(t.$conditional,t.val):t.$skipQueryCastForUpdate||t.$applySetters?this._castForQuery(t.val):this.castForQuery(t.val)},m.prototype.castForQuery=function(t,e){var r=void 0;if(2===arguments.length){if(!(r=this.$conditionalHandlers[t]))throw new Error("Can't use "+t);return r.call(this,e)}return e=t,this._castForQuery(e)}, -/*! - * Internal switch for runSetters - * - * @api private - */ -m.prototype._castForQuery=function(t){return this.applySetters(t,this.$$context)},m.checkRequired=function(t){return arguments.length>0&&(this._checkRequired=t),this._checkRequired},m.prototype.checkRequired=function(t){return null!=t}, -/*! - * ignore - */ -m.prototype.clone=function(){var t=Object.assign({},this.options),e=new this.constructor(this.path,t,this.instance);return e.validators=this.validators.slice(),void 0!==this.requiredValidator&&(e.requiredValidator=this.requiredValidator),void 0!==this.defaultValue&&(e.defaultValue=this.defaultValue),void 0!==this.$immutable&&void 0===this.options.immutable&&(e.$immutable=this.$immutable,l(e)),void 0!==this._index&&(e._index=this._index),void 0!==this.selected&&(e.selected=this.selected),void 0!==this.isRequired&&(e.isRequired=this.isRequired),void 0!==this.originalRequiredValue&&(e.originalRequiredValue=this.originalRequiredValue),e.getters=this.getters.slice(),e.setters=this.setters.slice(),e}, -/*! - * Module exports. - */ -t.exports=e=m,e.CastError=v,e.ValidatorError=_}).call(this,r(1).Buffer)},function(t,e,r){"use strict";var n,i,o=t.exports={};function s(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function u(t){if(n===setTimeout)return setTimeout(t,0);if((n===s||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:s}catch(t){n=s}try{i="function"==typeof clearTimeout?clearTimeout:a}catch(t){i=a}}();var c,l=[],f=!1,h=-1;function p(){f&&c&&(f=!1,c.length?l=c.concat(l):h=-1,l.length&&d())}function d(){if(!f){var t=u(p);f=!0;for(var e=l.length;e;){for(c=l,l=[];++h1)for(var r=1;r0&&this.init(t,e,r,i,o),n.call(this,this.formatMessage()),this.name="CastError",Error.captureStackTrace?Error.captureStackTrace(this):this.stack=(new Error).stack} -/*! - * Inherits from MongooseError. - */s.prototype=Object.create(n.prototype),s.prototype.constructor=n, -/*! - * ignore - */ -s.prototype.init=function(t,e,r,n,s){var a=o.inspect(e);(a=a.replace(/^'/,'"').replace(/'$/,'"')).startsWith('"')||(a='"'+a+'"'),"string"==typeof i(s,"options.cast",null)&&(this.messageFormat=s.options.cast),this.stringValue=a,this.kind=t,this.value=e,this.path=r,this.reason=n}, -/*! - * ignore - */ -s.prototype.copy=function(t){this.messageFormat=t.messageFormat,this.stringValue=t.stringValue,this.kind=t.kind,this.value=t.value,this.path=t.path,this.reason=t.reason,this.message=t.message}, -/*! - * ignore - */ -s.prototype.setModel=function(t){this.model=t,this.message=this.formatMessage(t)}, -/*! - * ignore - */ -s.prototype.formatMessage=function(t){if(null!=this.messageFormat){var e=this.messageFormat.replace("{KIND}",this.kind).replace("{VALUE}",this.stringValue).replace("{PATH}",this.path);return null!=t&&(e=e.replace("{MODEL}",t.modelName)),e}var r="Cast to "+this.kind+" failed for value "+this.stringValue+' at path "'+this.path+'"';return null!=t&&(r+=' for model "'+t.modelName+'"'),r}, -/*! - * exports - */ -t.exports=s},function(t,e,r){"use strict"; -/*! - * ignore - */var n=null;t.exports.get=function(){return n},t.exports.set=function(t){n=t}},function(t,e,r){"use strict";(function(e){function r(t,r){return new e(t,r)}t.exports={normalizedFunctionString:function(t){return t.toString().replace(/function *\(/,"function (")},allocBuffer:"function"==typeof e.alloc?function(){return e.alloc.apply(e,arguments)}:r,toBuffer:"function"==typeof e.from?function(){return e.from.apply(e,arguments)}:r}}).call(this,r(1).Buffer)},function(t,e,r){"use strict"; -/*! - * ignore - */function n(t){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this):this.stack=(new Error).stack,this.message=t,this.name="MongooseError"} -/*! - * Inherits from Error. - */n.prototype=Object.create(Error.prototype),n.prototype.constructor=Error,t.exports=n},function(t,e,r){"use strict";(function(e){ -/*! - * Module dependencies. - */ -var n=function(){function t(t,e){for(var r=0;r0&&s.length>i&&!s.warned){s.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=s.length,function(t){console&&console.warn&&console.warn(t)}(a)}return t}function p(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=function(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}.bind(n);return i.listener=r,n.wrapFn=i,i}function d(t,e,r){var n=t._events;if(void 0===n)return[];var i=n[e];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?function(t){for(var e=new Array(t.length),r=0;r0&&(o=e[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var u=i[t];if(void 0===u)return!1;if("function"==typeof u)s(u,this,e);else{var c=u.length,l=v(u,c);for(r=0;r=0;o--)if(r[o]===e||r[o].listener===e){s=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():function(t,e){for(;e+1=0;n--)this.removeListener(t,e[n]);return this},u.prototype.listeners=function(t){return d(this,t,!0)},u.prototype.rawListeners=function(t){return d(this,t,!1)},u.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):y.call(t,e)},u.prototype.listenerCount=y,u.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},function(t,e,r){"use strict";t.exports=r(14).get().Decimal128},function(t,e,r){"use strict";(function(e){ -/*! - * Determines if `arg` is an object. - * - * @param {Object|Array|String|Function|RegExp|any} arg - * @api private - * @return {Boolean} - */ -t.exports=function(t){return!!e.isBuffer(t)||"[object Object]"===Object.prototype.toString.call(t)}}).call(this,r(1).Buffer)},function(t,e,r){"use strict";(function(e){var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(114); -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -function o(t,e){if(t===e)return 0;for(var r=t.length,n=e.length,i=0,o=Math.min(r,n);i=0;u--)if(l[u]!==f[u])return!1;for(u=l.length-1;u>=0;u--)if(s=l[u],!b(t[s],e[s],r,n))return!1;return!0}(t,e,r,i))}return r?t===e:t==e}function w(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function O(t,e){if(!t||!e)return!1;if("[object RegExp]"==Object.prototype.toString.call(e))return e.test(t);try{if(t instanceof e)return!0}catch(t){}return!Error.isPrototypeOf(e)&&!0===e.call({},t)}function S(t,e,r,n){var i;if("function"!=typeof e)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=function(t){var e;try{t()}catch(t){e=t}return e}(e),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),t&&!i&&m(i,r,"Missing expected exception"+n);var o="string"==typeof n,s=!t&&a.isError(i),u=!t&&i&&!r;if((s&&o&&O(i,r)||u)&&m(i,r,"Got unwanted exception"+n),t&&i&&r&&!O(i,r)||!t&&i)throw i}p.AssertionError=function(t){this.name="AssertionError",this.actual=t.actual,this.expected=t.expected,this.operator=t.operator,t.message?(this.message=t.message,this.generatedMessage=!1):(this.message=function(t){return v(_(t.actual),128)+" "+t.operator+" "+v(_(t.expected),128)}(this),this.generatedMessage=!0);var e=t.stackStartFunction||m;if(Error.captureStackTrace)Error.captureStackTrace(this,e);else{var r=new Error;if(r.stack){var n=r.stack,i=y(e),o=n.indexOf("\n"+i);if(o>=0){var s=n.indexOf("\n",o+1);n=n.substring(s+1)}this.stack=n}}},a.inherits(p.AssertionError,Error),p.fail=m,p.ok=g,p.equal=function(t,e,r){t!=e&&m(t,e,r,"==",p.equal)},p.notEqual=function(t,e,r){t==e&&m(t,e,r,"!=",p.notEqual)},p.deepEqual=function(t,e,r){b(t,e,!1)||m(t,e,r,"deepEqual",p.deepEqual)},p.deepStrictEqual=function(t,e,r){b(t,e,!0)||m(t,e,r,"deepStrictEqual",p.deepStrictEqual)},p.notDeepEqual=function(t,e,r){b(t,e,!1)&&m(t,e,r,"notDeepEqual",p.notDeepEqual)},p.notDeepStrictEqual=function t(e,r,n){b(e,r,!0)&&m(e,r,n,"notDeepStrictEqual",t)},p.strictEqual=function(t,e,r){t!==e&&m(t,e,r,"===",p.strictEqual)},p.notStrictEqual=function(t,e,r){t===e&&m(t,e,r,"!==",p.notStrictEqual)},p.throws=function(t,e,r){S(!0,t,e,r)},p.doesNotThrow=function(t,e,r){S(!1,t,e,r)},p.ifError=function(t){if(t)throw t},p.strict=i(function t(e,r){e||m(e,!0,r,"==",t)},p,{equal:p.strictEqual,deepEqual:p.deepStrictEqual,notEqual:p.notStrictEqual,notDeepEqual:p.notDeepStrictEqual}),p.strict.strict=p.strict;var E=Object.keys||function(t){var e=[];for(var r in t)u.call(t,r)&&e.push(r);return e}}).call(this,r(11))},function(t,e,r){"use strict"; -/*! - * ignore - */e.internalToObjectOptions={transform:!1,virtuals:!1,getters:!1,_skipDepopulateTopLevel:!0,depopulate:!0,flattenDecimals:!1}},function(t,e,r){"use strict";function n(t,e){if(!(this instanceof n))return new n(t,e);this._bsontype="Long",this.low_=0|t,this.high_=0|e}n.prototype.toInt=function(){return this.low_},n.prototype.toNumber=function(){return this.high_*n.TWO_PWR_32_DBL_+this.getLowBitsUnsigned()},n.prototype.toJSON=function(){return this.toString()},n.prototype.toString=function(t){var e=t||10;if(e<2||36=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var t=0!==this.high_?this.high_:this.low_,e=31;e>0&&0==(t&1<0},n.prototype.greaterThanOrEqual=function(t){return this.compare(t)>=0},n.prototype.compare=function(t){if(this.equals(t))return 0;var e=this.isNegative(),r=t.isNegative();return e&&!r?-1:!e&&r?1:this.subtract(t).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(t){var e=this.high_>>>16,r=65535&this.high_,i=this.low_>>>16,o=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,c=0,l=0,f=0,h=0;return f+=(h+=o+(65535&t.low_))>>>16,h&=65535,l+=(f+=i+u)>>>16,f&=65535,c+=(l+=r+a)>>>16,l&=65535,c+=e+s,c&=65535,n.fromBits(f<<16|h,c<<16|l)},n.prototype.subtract=function(t){return this.add(t.negate())},n.prototype.multiply=function(t){if(this.isZero())return n.ZERO;if(t.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return t.isOdd()?n.MIN_VALUE:n.ZERO;if(t.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return t.isNegative()?this.negate().multiply(t.negate()):this.negate().multiply(t).negate();if(t.isNegative())return this.multiply(t.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&t.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*t.toNumber());var e=this.high_>>>16,r=65535&this.high_,i=this.low_>>>16,o=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,c=65535&t.low_,l=0,f=0,h=0,p=0;return h+=(p+=o*c)>>>16,p&=65535,f+=(h+=i*c)>>>16,h&=65535,f+=(h+=o*u)>>>16,h&=65535,l+=(f+=r*c)>>>16,f&=65535,l+=(f+=i*u)>>>16,f&=65535,l+=(f+=o*a)>>>16,f&=65535,l+=e*c+r*u+i*a+o*s,l&=65535,n.fromBits(h<<16|p,l<<16|f)},n.prototype.div=function(t){if(t.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(t.equals(n.ONE)||t.equals(n.NEG_ONE))return n.MIN_VALUE;if(t.equals(n.MIN_VALUE))return n.ONE;var e=this.shiftRight(1).div(t).shiftLeft(1);if(e.equals(n.ZERO))return t.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(t.multiply(e));return e.add(r.div(t))}if(t.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return t.isNegative()?this.negate().div(t.negate()):this.negate().div(t).negate();if(t.isNegative())return this.div(t.negate()).negate();var i=n.ZERO;for(r=this;r.greaterThanOrEqual(t);){e=Math.max(1,Math.floor(r.toNumber()/t.toNumber()));for(var o=Math.ceil(Math.log(e)/Math.LN2),s=o<=48?1:Math.pow(2,o-48),a=n.fromNumber(e),u=a.multiply(t);u.isNegative()||u.greaterThan(r);)e-=s,u=(a=n.fromNumber(e)).multiply(t);a.isZero()&&(a=n.ONE),i=i.add(a),r=r.subtract(u)}return i},n.prototype.modulo=function(t){return this.subtract(this.div(t).multiply(t))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(t){return n.fromBits(this.low_&t.low_,this.high_&t.high_)},n.prototype.or=function(t){return n.fromBits(this.low_|t.low_,this.high_|t.high_)},n.prototype.xor=function(t){return n.fromBits(this.low_^t.low_,this.high_^t.high_)},n.prototype.shiftLeft=function(t){if(0===(t&=63))return this;var e=this.low_;if(t<32){var r=this.high_;return n.fromBits(e<>>32-t)}return n.fromBits(0,e<>>t|e<<32-t,e>>t)}return n.fromBits(e>>t-32,e>=0?0:-1)},n.prototype.shiftRightUnsigned=function(t){if(0===(t&=63))return this;var e=this.high_;if(t<32){var r=this.low_;return n.fromBits(r>>>t|e<<32-t,e>>>t)}return 32===t?n.fromBits(e,0):n.fromBits(e>>>t-32,0)},n.fromInt=function(t){if(-128<=t&&t<128){var e=n.INT_CACHE_[t];if(e)return e}var r=new n(0|t,t<0?-1:0);return-128<=t&&t<128&&(n.INT_CACHE_[t]=r),r},n.fromNumber=function(t){return isNaN(t)||!isFinite(t)?n.ZERO:t<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:t+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:t<0?n.fromNumber(-t).negate():new n(t%n.TWO_PWR_32_DBL_|0,t/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(t,e){return new n(t,e)},n.fromString=function(t,e){if(0===t.length)throw Error("number format error: empty string");var r=e||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+t);for(var i=n.fromNumber(Math.pow(r,8)),o=n.ZERO,s=0;s0&&!r[i]&&(r[i]=!0,o.emit("error",r));try{t(r)}catch(r){return e.nextTick(function(){throw r})}}}):new(n.get())(function(t,e){r(function(r,n){return null!=r?(null!=o&&o.listeners("error").length>0&&!r[i]&&(r[i]=!0,o.emit("error",r)),e(r)):arguments.length>2?t(Array.prototype.slice.call(arguments,1)):void t(n)})})}}).call(this,r(8))},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(61)(),i=r(18).EventEmitter,o=r(29),s=r(50),a=r(22).internalToObjectOptions,u=r(5),c=r(24),l=r(3),f=r(0).documentArrayParent,h=r(0).validatorErrorSymbol;function p(t,e,r,i,o){null!=e&&e.isMongooseDocumentArray?(this.__parentArray=e,this[f]=e.$parent()):(this.__parentArray=void 0,this[f]=void 0),this.$setIndex(o),this.$isDocumentArrayElement=!0,n.call(this,t,i,r);var s=this;this.on("isNew",function(t){s.isNew=t}),s.on("save",function(){s.constructor.emit("save",s)})} -/*! - * Inherit from Document - */for(var d in p.prototype=Object.create(n.prototype),p.prototype.constructor=p,i.prototype)p[d]=i.prototype[d];p.prototype.toBSON=function(){return this.toObject(a)}, -/*! - * ignore - */ -p.prototype.$setIndex=function(t){if(this.__index=t,null!=u(this,"$__.validationError",null)){var e=Object.keys(this.$__.validationError.errors),r=!0,n=!1,i=void 0;try{for(var o,s=e[Symbol.iterator]();!(r=(o=s.next()).done);r=!0){var a=o.value;this.invalidate(a,this.$__.validationError.errors[a])}}catch(t){n=!0,i=t}finally{try{!r&&s.return&&s.return()}finally{if(n)throw i}}}},p.prototype.markModified=function(t){this.$__.activePaths.modify(t),this.__parentArray&&(this.isNew?this.__parentArray._markModified():this.__parentArray._markModified(this,t))}, -/*! - * ignore - */ -p.prototype.populate=function(){throw new Error('Mongoose does not support calling populate() on nested docs. Instead of `doc.arr[0].populate("path")`, use `doc.populate("arr.0.path")`')},p.prototype.save=function(t,e){var r=this;return"function"==typeof t&&(e=t,t={}),(t=t||{}).suppressWarning||console.warn("mongoose: calling `save()` on a subdoc does **not** save the document to MongoDB, it only runs save middleware. Use `subdoc.save({ suppressWarning: true })` to hide this warning if you're sure this behavior is right for your app."),c(e,function(t){r.$__save(t)})},p.prototype.$__save=function(t){var e=this;return s(function(){return t(null,e)})}, -/*! - * no-op for hooks - */ -p.prototype.$__remove=function(t){return t(null,this)},p.prototype.remove=function(t,e){if("function"!=typeof t||e||(e=t,t=void 0),!this.__parentArray||t&&t.noop)return e&&e(null),this;var r=void 0;if(!this.willRemove){if(!(r=this._doc._id))throw new Error("For your own good, Mongoose does not know how to remove an EmbeddedDocument that has no _id");this.__parentArray.pull({_id:r}),this.willRemove=!0, -/*! - * Registers remove event listeners for triggering - * on subdocuments. - * - * @param {EmbeddedDocument} sub - * @api private - */ -function(t){var e=t.ownerDocument();function r(){e.removeListener("save",r),e.removeListener("remove",r),t.emit("remove",t),t.constructor.emit("remove",t),e=t=null}e.on("save",r),e.on("remove",r)}(this)}return e&&e(null),this},p.prototype.update=function(){throw new Error("The #update method is not available on EmbeddedDocuments")},p.prototype.inspect=function(){return this.toObject({transform:!1,virtuals:!1,flattenDecimals:!1})},l.inspect.custom&&( -/*! - * Avoid Node deprecation warning DEP0079 - */ -p.prototype[l.inspect.custom]=p.prototype.inspect),p.prototype.invalidate=function(t,e,r){if(n.prototype.invalidate.call(this,t,e,r),!this[f]||null==this.__index){if(e[h]||e instanceof o)return!0;throw e}var i=this.__index,s=[this.__parentArray.$path(),i,t].join(".");return this[f].invalidate(s,e,r),!0},p.prototype.$markValid=function(t){if(this[f]){var e=this.__index;if(void 0!==e){var r=[this.__parentArray.$path(),e,t].join(".");this[f].$markValid(r)}}}, -/*! - * ignore - */ -p.prototype.$ignore=function(t){if(n.prototype.$ignore.call(this,t),this[f]){var e=this.__index;if(void 0!==e){var r=[this.__parentArray.$path(),e,t].join(".");this[f].$ignore(r)}}},p.prototype.$isValid=function(t){return void 0===this.__index||!this[f]||(!this[f].$__.validationError||!this[f].$__.validationError.errors[this.$__fullPath(t)])},p.prototype.ownerDocument=function(){if(this.$__.ownerDocument)return this.$__.ownerDocument;var t=this[f];if(!t)return this;for(;t[f]||t.$parent;)t=t[f]||t.$parent;return this.$__.ownerDocument=t,this.$__.ownerDocument},p.prototype.$__fullPath=function(t){if(!this.$__.fullPath){var e=this;if(!e[f])return t;for(var r=[];e[f]||e.$parent;)e[f]?r.unshift(e.__parentArray.$path()):r.unshift(e.$basePath),e=e[f]||e.$parent;this.$__.fullPath=r.join("."),this.$__.ownerDocument||(this.$__.ownerDocument=e)}return t?this.$__.fullPath+"."+t:this.$__.fullPath},p.prototype.parent=function(){return this[f]},p.prototype.parentArray=function(){return this.__parentArray}, -/*! - * Module exports. - */ -t.exports=p},function(t,e,r){"use strict";(function(e){if(void 0!==e)var n=r(1).Buffer;var i=r(15);function o(t,e){if(!(this instanceof o))return new o(t,e);if(!(null==t||"string"==typeof t||n.isBuffer(t)||t instanceof Uint8Array||Array.isArray(t)))throw new Error("only String, Buffer, Uint8Array or Array accepted");if(this._bsontype="Binary",t instanceof Number?(this.sub_type=t,this.position=0):(this.sub_type=null==e?s:e,this.position=0),null==t||t instanceof Number)void 0!==n?this.buffer=i.allocBuffer(o.BUFFER_SIZE):"undefined"!=typeof Uint8Array?this.buffer=new Uint8Array(new ArrayBuffer(o.BUFFER_SIZE)):this.buffer=new Array(o.BUFFER_SIZE),this.position=0;else{if("string"==typeof t)if(void 0!==n)this.buffer=i.toBuffer(t);else{if("undefined"==typeof Uint8Array&&"[object Array]"!==Object.prototype.toString.call(t))throw new Error("only String, Buffer, Uint8Array or Array accepted");this.buffer=a(t)}else this.buffer=t;this.position=t.length}}o.prototype.put=function(t){if(null!=t.length&&"number"!=typeof t&&1!==t.length)throw new Error("only accepts single character String, Uint8Array or Array");if("number"!=typeof t&&t<0||t>255)throw new Error("only accepts number in a valid unsigned byte range 0-255");var e=null;if(e="string"==typeof t?t.charCodeAt(0):null!=t.length?t[0]:t,this.buffer.length>this.position)this.buffer[this.position++]=e;else if(void 0!==n&&n.isBuffer(this.buffer)){var r=i.allocBuffer(o.BUFFER_SIZE+this.buffer.length);this.buffer.copy(r,0,0,this.buffer.length),this.buffer=r,this.buffer[this.position++]=e}else{r=null,r="[object Uint8Array]"===Object.prototype.toString.call(this.buffer)?new Uint8Array(new ArrayBuffer(o.BUFFER_SIZE+this.buffer.length)):new Array(o.BUFFER_SIZE+this.buffer.length);for(var s=0;sthis.position?e+t.length:this.position;else if(void 0!==n&&"string"==typeof t&&n.isBuffer(this.buffer))this.buffer.write(t,e,"binary"),this.position=e+t.length>this.position?e+t.length:this.position;else if("[object Uint8Array]"===Object.prototype.toString.call(t)||"[object Array]"===Object.prototype.toString.call(t)&&"string"!=typeof t){for(o=0;othis.position?e:this.position}else if("string"==typeof t){for(o=0;othis.position?e:this.position}},o.prototype.read=function(t,e){if(e=e&&e>0?e:this.position,this.buffer.slice)return this.buffer.slice(t,t+e);for(var r="undefined"!=typeof Uint8Array?new Uint8Array(new ArrayBuffer(e)):new Array(e),n=0;n=0?this.low_:n.TWO_PWR_32_DBL_+this.low_},n.prototype.getNumBitsAbs=function(){if(this.isNegative())return this.equals(n.MIN_VALUE)?64:this.negate().getNumBitsAbs();for(var t=0!==this.high_?this.high_:this.low_,e=31;e>0&&0==(t&1<0},n.prototype.greaterThanOrEqual=function(t){return this.compare(t)>=0},n.prototype.compare=function(t){if(this.equals(t))return 0;var e=this.isNegative(),r=t.isNegative();return e&&!r?-1:!e&&r?1:this.subtract(t).isNegative()?-1:1},n.prototype.negate=function(){return this.equals(n.MIN_VALUE)?n.MIN_VALUE:this.not().add(n.ONE)},n.prototype.add=function(t){var e=this.high_>>>16,r=65535&this.high_,i=this.low_>>>16,o=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,c=0,l=0,f=0,h=0;return f+=(h+=o+(65535&t.low_))>>>16,h&=65535,l+=(f+=i+u)>>>16,f&=65535,c+=(l+=r+a)>>>16,l&=65535,c+=e+s,c&=65535,n.fromBits(f<<16|h,c<<16|l)},n.prototype.subtract=function(t){return this.add(t.negate())},n.prototype.multiply=function(t){if(this.isZero())return n.ZERO;if(t.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE))return t.isOdd()?n.MIN_VALUE:n.ZERO;if(t.equals(n.MIN_VALUE))return this.isOdd()?n.MIN_VALUE:n.ZERO;if(this.isNegative())return t.isNegative()?this.negate().multiply(t.negate()):this.negate().multiply(t).negate();if(t.isNegative())return this.multiply(t.negate()).negate();if(this.lessThan(n.TWO_PWR_24_)&&t.lessThan(n.TWO_PWR_24_))return n.fromNumber(this.toNumber()*t.toNumber());var e=this.high_>>>16,r=65535&this.high_,i=this.low_>>>16,o=65535&this.low_,s=t.high_>>>16,a=65535&t.high_,u=t.low_>>>16,c=65535&t.low_,l=0,f=0,h=0,p=0;return h+=(p+=o*c)>>>16,p&=65535,f+=(h+=i*c)>>>16,h&=65535,f+=(h+=o*u)>>>16,h&=65535,l+=(f+=r*c)>>>16,f&=65535,l+=(f+=i*u)>>>16,f&=65535,l+=(f+=o*a)>>>16,f&=65535,l+=e*c+r*u+i*a+o*s,l&=65535,n.fromBits(h<<16|p,l<<16|f)},n.prototype.div=function(t){if(t.isZero())throw Error("division by zero");if(this.isZero())return n.ZERO;if(this.equals(n.MIN_VALUE)){if(t.equals(n.ONE)||t.equals(n.NEG_ONE))return n.MIN_VALUE;if(t.equals(n.MIN_VALUE))return n.ONE;var e=this.shiftRight(1).div(t).shiftLeft(1);if(e.equals(n.ZERO))return t.isNegative()?n.ONE:n.NEG_ONE;var r=this.subtract(t.multiply(e));return e.add(r.div(t))}if(t.equals(n.MIN_VALUE))return n.ZERO;if(this.isNegative())return t.isNegative()?this.negate().div(t.negate()):this.negate().div(t).negate();if(t.isNegative())return this.div(t.negate()).negate();var i=n.ZERO;for(r=this;r.greaterThanOrEqual(t);){e=Math.max(1,Math.floor(r.toNumber()/t.toNumber()));for(var o=Math.ceil(Math.log(e)/Math.LN2),s=o<=48?1:Math.pow(2,o-48),a=n.fromNumber(e),u=a.multiply(t);u.isNegative()||u.greaterThan(r);)e-=s,u=(a=n.fromNumber(e)).multiply(t);a.isZero()&&(a=n.ONE),i=i.add(a),r=r.subtract(u)}return i},n.prototype.modulo=function(t){return this.subtract(this.div(t).multiply(t))},n.prototype.not=function(){return n.fromBits(~this.low_,~this.high_)},n.prototype.and=function(t){return n.fromBits(this.low_&t.low_,this.high_&t.high_)},n.prototype.or=function(t){return n.fromBits(this.low_|t.low_,this.high_|t.high_)},n.prototype.xor=function(t){return n.fromBits(this.low_^t.low_,this.high_^t.high_)},n.prototype.shiftLeft=function(t){if(0===(t&=63))return this;var e=this.low_;if(t<32){var r=this.high_;return n.fromBits(e<>>32-t)}return n.fromBits(0,e<>>t|e<<32-t,e>>t)}return n.fromBits(e>>t-32,e>=0?0:-1)},n.prototype.shiftRightUnsigned=function(t){if(0===(t&=63))return this;var e=this.high_;if(t<32){var r=this.low_;return n.fromBits(r>>>t|e<<32-t,e>>>t)}return 32===t?n.fromBits(e,0):n.fromBits(e>>>t-32,0)},n.fromInt=function(t){if(-128<=t&&t<128){var e=n.INT_CACHE_[t];if(e)return e}var r=new n(0|t,t<0?-1:0);return-128<=t&&t<128&&(n.INT_CACHE_[t]=r),r},n.fromNumber=function(t){return isNaN(t)||!isFinite(t)?n.ZERO:t<=-n.TWO_PWR_63_DBL_?n.MIN_VALUE:t+1>=n.TWO_PWR_63_DBL_?n.MAX_VALUE:t<0?n.fromNumber(-t).negate():new n(t%n.TWO_PWR_32_DBL_|0,t/n.TWO_PWR_32_DBL_|0)},n.fromBits=function(t,e){return new n(t,e)},n.fromString=function(t,e){if(0===t.length)throw Error("number format error: empty string");var r=e||10;if(r<2||36=0)throw Error('number format error: interior "-" character: '+t);for(var i=n.fromNumber(Math.pow(r,8)),o=n.ZERO,s=0;s>8&255,i[1]=t>>16&255,i[0]=t>>24&255,i[6]=255&s,i[5]=s>>8&255,i[4]=s>>16&255,i[8]=255&e,i[7]=e>>8&255,i[11]=255&r,i[10]=r>>8&255,i[9]=r>>16&255,i},c.prototype.toString=function(t){return this.id&&this.id.copy?this.id.toString("string"==typeof t?t:"hex"):this.toHexString()},c.prototype[i]=c.prototype.toString,c.prototype.toJSON=function(){return this.toHexString()},c.prototype.equals=function(t){return t instanceof c?this.toString()===t.toString():"string"==typeof t&&c.isValid(t)&&12===t.length&&this.id instanceof p?t===this.id.toString("binary"):"string"==typeof t&&c.isValid(t)&&24===t.length?t.toLowerCase()===this.toHexString():"string"==typeof t&&c.isValid(t)&&12===t.length?t===this.id:!(null==t||!(t instanceof c||t.toHexString))&&t.toHexString()===this.toHexString()},c.prototype.getTimestamp=function(){var t=new Date,e=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;return t.setTime(1e3*Math.floor(e)),t},c.index=~~(16777215*Math.random()),c.createPk=function(){return new c},c.createFromTime=function(t){var e=o.toBuffer([0,0,0,0,0,0,0,0,0,0,0,0]);return e[3]=255&t,e[2]=t>>8&255,e[1]=t>>16&255,e[0]=t>>24&255,new c(e)};var h=[];for(f=0;f<10;)h[48+f]=f++;for(;f<16;)h[55+f]=h[87+f]=f++;var p=e,d=function(t){return t.toString("hex")};c.createFromHexString=function(t){if(void 0===t||null!=t&&24!==t.length)throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");if(u)return new c(o.toBuffer(t,"hex"));for(var e=new p(12),r=0,n=0;n<24;)e[r++]=h[t.charCodeAt(n++)]<<4|h[t.charCodeAt(n++)];return new c(e)},c.isValid=function(t){return null!=t&&("number"==typeof t||("string"==typeof t?12===t.length||24===t.length&&a.test(t):t instanceof c||(t instanceof p||!!t.toHexString&&(12===t.id.length||24===t.id.length&&a.test(t.id)))))},Object.defineProperty(c.prototype,"generationTime",{enumerable:!0,get:function(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24},set:function(t){this.id[3]=255&t,this.id[2]=t>>8&255,this.id[1]=t>>16&255,this.id[0]=t>>24&255}}),t.exports=c,t.exports.ObjectID=c,t.exports.ObjectId=c}).call(this,r(1).Buffer,r(8))},function(t,e,r){"use strict";function n(t,e){if(!(this instanceof n))return new n;this._bsontype="BSONRegExp",this.pattern=t||"",this.options=e||"";for(var r=0;r=7e3)throw new Error(t+" not a valid Decimal128 string");var T=t.match(i),B=t.match(o),C=t.match(s);if(!T&&!B&&!C||0===t.length)throw new Error(t+" not a valid Decimal128 string");if(T&&T[4]&&void 0===T[2])throw new Error(t+" not a valid Decimal128 string");if("+"!==t[k]&&"-"!==t[k]||(r="-"===t[k++]),!p(t[k])&&"."!==t[k]){if("i"===t[k]||"I"===t[k])return new y(h.toBuffer(r?c:l));if("N"===t[k])return new y(h.toBuffer(u))}for(;p(t[k])||"."===t[k];)if("."!==t[k])S<34&&("0"!==t[k]||v)&&(v||(w=m),v=!0,O[E++]=parseInt(t[k],10),S+=1),v&&(g+=1),d&&(b+=1),m+=1,k+=1;else{if(d)return new y(h.toBuffer(u));d=!0,k+=1}if(d&&!m)throw new Error(t+" not a valid Decimal128 string");if("e"===t[k]||"E"===t[k]){var D=t.substr(++k).match(f);if(!D||!D[2])return new y(h.toBuffer(u));j=parseInt(D[0],10),k+=D[0].length}if(t[k])return new y(h.toBuffer(u));if(A=0,S){if($=S-1,_=g,0!==j&&1!==_)for(;"0"===t[w+_-1];)_-=1}else A=0,$=0,O[0]=0,g=1,S=1,_=0;for(j<=b&&b-j>16384?j=-6176:j-=b;j>6111;){if(($+=1)-A>34){var M=O.join("");if(M.match(/^0+$/)){j=6111;break}return new y(h.toBuffer(r?c:l))}j-=1}for(;j<-6176||S=5&&(I=1,5===F))for(I=O[$]%2==1,x=w+$+2;x=0&&++O[L]>9;L--)if(O[L]=0,0===L){if(!(j<6111))return new y(h.toBuffer(r?c:l));j+=1,O[L]=1}}if(N=n.fromNumber(0),P=n.fromNumber(0),0===_)N=n.fromNumber(0),P=n.fromNumber(0);else if($-A<17)for(L=A,P=n.fromNumber(O[L++]),N=new n(0,0);L<=$;L++)P=(P=P.multiply(n.fromNumber(10))).add(n.fromNumber(O[L]));else{for(L=A,N=n.fromNumber(O[L++]);L<=$-17;L++)N=(N=N.multiply(n.fromNumber(10))).add(n.fromNumber(O[L]));for(P=n.fromNumber(O[L++]);L<=$;L++)P=(P=P.multiply(n.fromNumber(10))).add(n.fromNumber(O[L]))}var U=function(t,e){if(!t&&!e)return{high:n.fromNumber(0),low:n.fromNumber(0)};var r=t.shiftRightUnsigned(32),i=new n(t.getLowBits(),0),o=e.shiftRightUnsigned(32),s=new n(e.getLowBits(),0),a=r.multiply(o),u=r.multiply(s),c=i.multiply(o),l=i.multiply(s);return a=a.add(u.shiftRightUnsigned(32)),u=new n(u.getLowBits(),0).add(c).add(l.shiftRightUnsigned(32)),{high:a=a.add(u.shiftRightUnsigned(32)),low:l=u.shiftLeft(32).add(new n(l.getLowBits(),0))}}(N,n.fromString("100000000000000000"));U.low=U.low.add(P),function(t,e){var r=t.high_>>>0,n=e.high_>>>0;return r>>0>>0}(U.low,P)&&(U.high=U.high.add(n.fromNumber(1))),e=j+a;var V={low:n.fromNumber(0),high:n.fromNumber(0)};U.high.shiftRightUnsigned(49).and(n.fromNumber(1)).equals(n.fromNumber)?(V.high=V.high.or(n.fromNumber(3).shiftLeft(61)),V.high=V.high.or(n.fromNumber(e).and(n.fromNumber(16383).shiftLeft(47))),V.high=V.high.or(U.high.and(n.fromNumber(0x7fffffffffff)))):(V.high=V.high.or(n.fromNumber(16383&e).shiftLeft(49)),V.high=V.high.or(U.high.and(n.fromNumber(562949953421311)))),V.low=U.low,r&&(V.high=V.high.or(n.fromString("9223372036854775808")));var q=h.allocBuffer(16);return k=0,q[k++]=255&V.low.low_,q[k++]=V.low.low_>>8&255,q[k++]=V.low.low_>>16&255,q[k++]=V.low.low_>>24&255,q[k++]=255&V.low.high_,q[k++]=V.low.high_>>8&255,q[k++]=V.low.high_>>16&255,q[k++]=V.low.high_>>24&255,q[k++]=255&V.high.low_,q[k++]=V.high.low_>>8&255,q[k++]=V.high.low_>>16&255,q[k++]=V.high.low_>>24&255,q[k++]=255&V.high.high_,q[k++]=V.high.high_>>8&255,q[k++]=V.high.high_>>16&255,q[k++]=V.high.high_>>24&255,new y(q)};a=6176,y.prototype.toString=function(){for(var t,e,r,i,o,s,u=0,c=new Array(36),l=0;l>26&31)>>3==3){if(30===o)return b.join("")+"Infinity";if(31===o)return"NaN";s=t>>15&16383,p=8+(t>>14&1)}else p=t>>14&7,s=t>>17&16383;if(f=s-a,g.parts[0]=(16383&t)+((15&p)<<14),g.parts[1]=e,g.parts[2]=r,g.parts[3]=i,0===g.parts[0]&&0===g.parts[1]&&0===g.parts[2]&&0===g.parts[3])m=!0;else for(v=3;v>=0;v--){var O=0,S=d(g);if(g=S.quotient,O=S.rem.low_)for(y=8;y>=0;y--)c[9*v+y]=O%10,O=Math.floor(O/10)}if(m)u=1,c[_]=0;else for(u=36,l=0;!c[_];)l++,u-=1,_+=1;if((h=u-1+f)>=34||h<=-7||f>0){for(b.push(c[_++]),(u-=1)&&b.push("."),l=0;l0?b.push("+"+h):b.push(h)}else if(f>=0)for(l=0;l0)for(l=0;l0&&!A.hasUserDefinedProperty(e.of,this.options.typeKey)?new T(e.of):e.of;this.paths[h]=this.interpretAsType(h,p,this.options),f.$__schemaType=this.paths[h]}if(f.$isSingleNested){for(var d in f.schema.paths)this.singleNestedPaths[t+"."+d]=f.schema.paths[d];for(var y in f.schema.singleNestedPaths)this.singleNestedPaths[t+"."+y]=f.schema.singleNestedPaths[y];for(var v in f.schema.subpaths)this.singleNestedPaths[t+"."+v]=f.schema.subpaths[v];Object.defineProperty(f.schema,"base",{configurable:!0,enumerable:!1,writable:!1,value:this.base}),f.caster.base=this.base,this.childSchemas.push({schema:f.schema,model:f.caster})}else f.$isMongooseDocumentArray&&(Object.defineProperty(f.schema,"base",{configurable:!0,enumerable:!1,writable:!1,value:this.base}),f.casterConstructor.base=this.base,this.childSchemas.push({schema:f.schema,model:f.casterConstructor}));if(f.$isMongooseArray&&f.caster instanceof c){for(var _=t,m=f,g=[];m.$isMongooseArray;)_+=".$",m.$isMongooseDocumentArray?(m.$embeddedSchemaType._arrayPath=_,m=m.$embeddedSchemaType.clone()):(m.caster._arrayPath=_,m=m.caster.clone()),m.path=_,g.push(m);var b=!0,w=!1,O=void 0;try{for(var S,E=g[Symbol.iterator]();!(b=(S=E.next()).done);b=!0){var j=S.value;this.subpaths[j.path]=j}}catch(t){w=!0,O=t}finally{try{!b&&E.return&&E.return()}finally{if(w)throw O}}}if(f.$isMongooseDocumentArray){var x=!0,N=!1,P=void 0;try{for(var k,F=Object.keys(f.schema.paths)[Symbol.iterator]();!(x=(k=F.next()).done);x=!0){var I=k.value;this.subpaths[t+"."+I]=f.schema.paths[I],f.schema.paths[I].$isUnderneathDocArray=!0}}catch(t){N=!0,P=t}finally{try{!x&&F.return&&F.return()}finally{if(N)throw P}}var L=!0,U=!1,V=void 0;try{for(var q,W=Object.keys(f.schema.subpaths)[Symbol.iterator]();!(L=(q=W.next()).done);L=!0){var H=q.value;this.subpaths[t+"."+H]=f.schema.subpaths[H],f.schema.subpaths[H].$isUnderneathDocArray=!0}}catch(t){U=!0,V=t}finally{try{!L&&W.return&&W.return()}finally{if(U)throw V}}var Y=!0,z=!1,K=void 0;try{for(var Q,J=Object.keys(f.schema.singleNestedPaths)[Symbol.iterator]();!(Y=(Q=J.next()).done);Y=!0){var G=Q.value;this.subpaths[t+"."+G]=f.schema.singleNestedPaths[G],f.schema.singleNestedPaths[G].$isUnderneathDocArray=!0}}catch(t){z=!0,K=t}finally{try{!Y&&J.return&&J.return()}finally{if(z)throw K}}}return this},Object.defineProperty(T.prototype,"base",{configurable:!0,enumerable:!1,writable:!0,value:null}),T.prototype.interpretAsType=function(t,e,r){if(e instanceof c)return e;var o=null!=this.base?this.base.Schema.Types:T.Types;if(!(A.isPOJO(e)||e instanceof l)&&"Object"!==A.getFunctionName(e.constructor)){var s=e;(e={})[r.typeKey]=s}var a=!e[r.typeKey]||"type"===r.typeKey&&e.type.type?{}:e[r.typeKey],u=void 0;if(A.isPOJO(a)||"mixed"===a)return new o.Mixed(t,e);if(Array.isArray(a)||Array===a||"array"===a){var f=Array===a||"array"===a?e.cast:a[0];if(f&&f.instanceOfSchema)return new o.DocumentArray(t,f,e);if(f&&f[r.typeKey]&&f[r.typeKey].instanceOfSchema)return new o.DocumentArray(t,f[r.typeKey],e,f);if(Array.isArray(f))return new o.Array(t,this.interpretAsType(t,f,r),e);if("string"==typeof f)f=o[f.charAt(0).toUpperCase()+f.substring(1)];else if(f&&(!f[r.typeKey]||"type"===r.typeKey&&f.type.type)&&A.isPOJO(f)){if(Object.keys(f).length){var h={minimize:r.minimize};r.typeKey&&(h.typeKey=r.typeKey),r.hasOwnProperty("strict")&&(h.strict=r.strict),r.hasOwnProperty("typePojoToMixed")&&(h.typePojoToMixed=r.typePojoToMixed);var p=new T(f,h);return p.$implicitlyCreated=!0,new o.DocumentArray(t,p,e)}return new o.Array(t,o.Mixed,e)}if(f&&(u="string"==typeof(a=!f[r.typeKey]||"type"===r.typeKey&&f.type.type?f:f[r.typeKey])?a:a.schemaName||A.getFunctionName(a),!o.hasOwnProperty(u)))throw new TypeError("Invalid schema configuration: `"+u+"` is not a valid type within the array `"+t+"`.See http://bit.ly/mongoose-schematypes for a list of valid schema types.");return new o.Array(t,f||o.Mixed,e,r)}if(a&&a.instanceOfSchema)return new o.Embedded(a,t,e);if((u=n.isBuffer(a)?"Buffer":"function"==typeof a||"object"===(void 0===a?"undefined":i(a))?a.schemaName||A.getFunctionName(a):null==a?""+a:a.toString())&&(u=u.charAt(0).toUpperCase()+u.substring(1)),"ObjectID"===u&&(u="ObjectId"),null==o[u])throw new TypeError("Invalid schema configuration: `"+u+"` is not a valid type at path `"+t+"`. See http://bit.ly/mongoose-schematypes for a list of valid schema types.");return new o[u](t,e)},T.prototype.eachPath=function(t){for(var e=Object.keys(this.paths),r=e.length,n=0;n0?t+"."+e[r]:e[r])in this.paths&&this.paths[t]instanceof j.Mixed)return this.paths[t];return null},T.prototype.setupTimestamp=function(t){var e=this.childSchemas.find(function(t){return!!t.schema.options.timestamps});if(t||e){var r=g(t,"createdAt"),n=g(t,"updatedAt"),i=null!=t&&t.hasOwnProperty("currentTime")?t.currentTime:null,o={};this.$timestamps={createdAt:r,updatedAt:n},n&&!this.paths[n]&&(o[n]=Date),r&&!this.paths[r]&&(o[r]=Date),this.add(o),this.pre("save",function(t){var e=_(this,"$__.saveOptions.timestamps");if(!1===e)return t();var o=null!=e&&!1===e.updatedAt,s=null!=e&&!1===e.createdAt,a=null!=i?i():(this.ownerDocument?this.ownerDocument():this).constructor.base.now(),u=this._id&&this._id.auto;if(!s&&r&&!this.get(r)&&this.isSelected(r)&&this.set(r,u?this._id.getTimestamp():a),!o&&n&&(this.isNew||this.isModified())){var c=a;this.isNew&&(null!=r?c=this.$__getValue(r):u&&(c=this._id.getTimestamp())),this.set(n,c)}t()}),this.methods.initializeTimestamps=function(){var t=null!=i?i():this.constructor.base.now();return r&&!this.get(r)&&this.set(r,t),n&&!this.get(n)&&this.set(n,t),this},a[S.builtInMiddleware]=!0;var s={query:!0,model:!1};this.pre("findOneAndUpdate",s,a),this.pre("replaceOne",s,a),this.pre("update",s,a),this.pre("updateOne",s,a),this.pre("updateMany",s,a)}function a(t){var e=null!=i?i():this.model.base.now();y(e,r,n,this.getUpdate(),this.options,this.schema),d(e,this.getUpdate(),this.model.schema),t()}},T.prototype.queue=function(t,e){return this.callQueue.push([t,e]),this},T.prototype.pre=function(t){if(t instanceof RegExp){var e=Array.prototype.slice.call(arguments,1),r=!0,n=!1,i=void 0;try{for(var o,s=P[Symbol.iterator]();!(r=(o=s.next()).done);r=!0){var a=o.value;t.test(a)&&this.pre.apply(this,[a].concat(e))}}catch(t){n=!0,i=t}finally{try{!r&&s.return&&s.return()}finally{if(n)throw i}}return this}if(Array.isArray(t)){var u=Array.prototype.slice.call(arguments,1),c=!0,l=!1,f=void 0;try{for(var h,p=t[Symbol.iterator]();!(c=(h=p.next()).done);c=!0){var d=h.value;this.pre.apply(this,[d].concat(u))}}catch(t){l=!0,f=t}finally{try{!c&&p.return&&p.return()}finally{if(l)throw f}}return this}return this.s.hooks.pre.apply(this.s.hooks,arguments),this},T.prototype.post=function(t){if(t instanceof RegExp){var e=Array.prototype.slice.call(arguments,1),r=!0,n=!1,i=void 0;try{for(var o,s=P[Symbol.iterator]();!(r=(o=s.next()).done);r=!0){var a=o.value;t.test(a)&&this.post.apply(this,[a].concat(e))}}catch(t){n=!0,i=t}finally{try{!r&&s.return&&s.return()}finally{if(n)throw i}}return this}if(Array.isArray(t)){var u=Array.prototype.slice.call(arguments,1),c=!0,l=!1,f=void 0;try{for(var h,p=t[Symbol.iterator]();!(c=(h=p.next()).done);c=!0){var d=h.value;this.post.apply(this,[d].concat(u))}}catch(t){l=!0,f=t}finally{try{!c&&p.return&&p.return()}finally{if(l)throw f}}return this}return this.s.hooks.post.apply(this.s.hooks,arguments),this},T.prototype.plugin=function(t,e){if("function"!=typeof t)throw new Error('First param to `schema.plugin()` must be a function, got "'+(void 0===t?"undefined":i(t))+'"');if(e&&e.deduplicate){var r=!0,n=!1,o=void 0;try{for(var s,a=this.plugins[Symbol.iterator]();!(r=(s=a.next()).done);r=!0){if(s.value.fn===t)return this}}catch(t){n=!0,o=t}finally{try{!r&&a.return&&a.return()}finally{if(n)throw o}}}return this.plugins.push({fn:t,opts:e}),t(this,e),this},T.prototype.method=function(t,e,r){if("string"!=typeof t)for(var n in t)this.methods[n]=t[n],this.methodOptions[n]=A.clone(r);else this.methods[t]=e,this.methodOptions[t]=A.clone(r);return this},T.prototype.static=function(t,e){if("string"!=typeof t)for(var r in t)this.statics[r]=t[r];else this.statics[t]=e;return this},T.prototype.index=function(t,e){return t||(t={}),e||(e={}),e.expires&&A.expires(e),this._indexes.push([t,e]),this},T.prototype.set=function(t,e,r){if(1===arguments.length)return this.options[t];switch(t){case"read":this.options[t]=O(e,r),this._userProvidedOptions[t]=this.options[t];break;case"safe":F(this.options,e),this._userProvidedOptions[t]=this.options[t];break;case"timestamps":this.setupTimestamp(e),this.options[t]=e,this._userProvidedOptions[t]=this.options[t];break;default:this.options[t]=e,this._userProvidedOptions[t]=this.options[t]}return this}; -/*! - * ignore - */ -var F=E.deprecate(function(t,e){t.safe=!1===e?{w:0}:e},"Mongoose: The `safe` option for schemas is deprecated. Use the `writeConcern` option instead: http://bit.ly/mongoose-write-concern");T.prototype.get=function(t){return this.options[t]};var I="2d 2dsphere hashed text".split(" "); -/*! - * ignore - */ -function L(t,e){var r=e.split("."),n=r.pop(),i=t.tree,o=!0,s=!1,a=void 0;try{for(var u,c=r[Symbol.iterator]();!(o=(u=c.next()).done);o=!0){i=i[u.value]}}catch(t){s=!0,a=t}finally{try{!o&&c.return&&c.return()}finally{if(s)throw a}}delete i[n]} -/*! - * ignore - */ -function U(t){return t.startsWith("$[")&&t.endsWith("]")} -/*! - * Module exports. - */Object.defineProperty(T,"indexTypes",{get:function(){return I},set:function(){throw new Error("Cannot overwrite Schema.indexTypes")}}),T.prototype.indexes=function(){return m(this)},T.prototype.virtual=function(t,e){var r=this;if(t instanceof h)return this.virtual(t.path,t.options);if(e=new f(e),A.hasUserDefinedProperty(e,["ref","refPath"])){if(null==e.localField)throw new Error("Reference virtuals require `localField` option");if(null==e.foreignField)throw new Error("Reference virtuals require `foreignField` option");this.pre("init",function(r){if(w.has(t,r)){var n=w.get(t,r);this.$$populatedVirtuals||(this.$$populatedVirtuals={}),e.justOne||e.count?this.$$populatedVirtuals[t]=Array.isArray(n)?n[0]:n:this.$$populatedVirtuals[t]=Array.isArray(n)?n:null==n?[]:[n],w.unset(t,r)}});var n=this.virtual(t);return n.options=e,n.get(function(e){return this.$$populatedVirtuals&&this.$$populatedVirtuals.hasOwnProperty(t)?this.$$populatedVirtuals[t]:null!=e?e:void 0}).set(function(r){this.$$populatedVirtuals||(this.$$populatedVirtuals={}),e.justOne||e.count?(this.$$populatedVirtuals[t]=Array.isArray(r)?r[0]:r,"object"!==i(this.$$populatedVirtuals[t])&&(this.$$populatedVirtuals[t]=e.count?r:null)):(this.$$populatedVirtuals[t]=Array.isArray(r)?r:null==r?[]:[r],this.$$populatedVirtuals[t]=this.$$populatedVirtuals[t].filter(function(t){return t&&"object"===(void 0===t?"undefined":i(t))}))})}var o=this.virtuals,s=t.split(".");if("real"===this.pathType(t))throw new Error('Virtual path "'+t+'" conflicts with a real path in the schema');o[t]=s.reduce(function(r,n,i){return r[n]||(r[n]=i===s.length-1?new h(e,t):{}),r[n]},this.tree);for(var a=s[0],u=0;u0||this.setters.length>0)){var t="$"+this.path;this.getters.push(function(){return this[t]}),this.setters.push(function(e){this[t]=e})}}, -/*! - * ignore - */ -n.prototype.clone=function(){var t=new n(this.options,this.path);return t.getters=[].concat(this.getters),t.setters=[].concat(this.setters),t},n.prototype.get=function(t){return this.getters.push(t),this},n.prototype.set=function(t){return this.setters.push(t),this},n.prototype.applyGetters=function(t,e){for(var r=t,n=this.getters.length-1;n>=0;n--)r=this.getters[n].call(e,r,this,e);return r},n.prototype.applySetters=function(t,e){for(var r=t,n=this.setters.length-1;n>=0;n--)r=this.setters[n].call(e,r,this,e);return r}, -/*! - * exports - */ -t.exports=n},function(t,e,r){"use strict"; -/*! - * Module exports. - */e.String=r(144),e.Number=r(77),e.Boolean=r(148),e.DocumentArray=r(149),e.Embedded=r(155),e.Array=r(55),e.Buffer=r(157),e.Date=r(159),e.ObjectId=r(162),e.Mixed=r(31),e.Decimal128=e.Decimal=r(164),e.Map=r(166),e.Oid=e.ObjectId,e.Object=e.Mixed,e.Bool=e.Boolean,e.ObjectID=e.ObjectId},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(48),i=r(71),o=r(16),s=r(150),a=r(7),u=a.CastError,c=r(31),l=r(151),f=r(152),h=r(5),p=r(79),d=r(3),y=r(2),v=r(32).castToNumber,_=r(80),m=r(56),g=void 0,b=void 0,w=Symbol("mongoose#isNestedArray");function O(t,e,n,i){b||(b=r(57).Embedded);var o="type";if(i&&i.typeKey&&(o=i.typeKey),this.schemaOptions=i,e){var s={};y.isPOJO(e)&&(e[o]?(delete(s=y.clone(e))[o],e=e[o]):e=c),e===Object&&(e=c);var u="string"==typeof e?e:y.getFunctionName(e),l=r(54),f=l.hasOwnProperty(u)?l[u]:e;this.casterConstructor=f,this.casterConstructor instanceof O&&(this.casterConstructor[w]=!0),"function"!=typeof f||f.$isArraySubdocument||f.$isSchemaMap?this.caster=f:this.caster=new f(null,s),this.$embeddedSchemaType=this.caster,this.caster instanceof b||(this.caster.path=t)}this.$isMongooseArray=!0,a.call(this,t,n,"Array");var h=void 0,p=void 0;if(null!=this.defaultValue&&(h=this.defaultValue,p="function"==typeof h),!("defaultValue"in this)||void 0!==this.defaultValue){var d=function(){var t=[];return p?t=h.call(this):null!=h&&(t=t.concat(h)),t};d.$runBeforeSetters=!0,this.default(d)}}O.schemaName="Array",O.options={castNonArrays:!0},O.defaultOptions={},O.set=a.set, -/*! - * Inherits from SchemaType. - */ -O.prototype=Object.create(a.prototype),O.prototype.constructor=O,O.prototype.OptionsConstructor=s, -/*! - * ignore - */ -O._checkRequired=a.prototype.checkRequired,O.checkRequired=a.checkRequired,O.prototype.checkRequired=function(t,e){return a._isRef(this,t,e,!0)?!!t:("function"==typeof this.constructor.checkRequired?this.constructor.checkRequired():O.checkRequired())(t)},O.prototype.enum=function(){for(var t=this;;){var e=h(t,"caster.instance");if("Array"!==e){if("String"!==e&&"Number"!==e)throw new Error("`enum` can only be set on an array of strings or numbers , not "+e);break}t=t.caster}return t.caster.enum.apply(t.caster,arguments),this},O.prototype.applyGetters=function(t,e){return this.caster.options&&this.caster.options.ref?t:a.prototype.applyGetters.call(this,t,e)},O.prototype._applySetters=function(t,e,r,n){if(this.casterConstructor instanceof O&&O.options.castNonArrays&&!this[w]){for(var i=0,o=this;null!=o&&o instanceof O&&!o.$isMongooseDocumentArray;)++i,o=o.casterConstructor;if(null!=t&&t.length>0){var s=l(t);if(s.min===s.max&&s.maxo;)n[i-o]=t[i];return n}},function(t,e,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=Object.prototype.toString;t.exports=function(t){if(!function(t){return"object"==(void 0===t?"undefined":n(t))&&"[object RegExp]"==i.call(t)}(t))throw new TypeError("Not a RegExp");var e=[];t.global&&e.push("g"),t.multiline&&e.push("m"),t.ignoreCase&&e.push("i"),t.dotAll&&e.push("s"),t.unicode&&e.push("u"),t.sticky&&e.push("y");var r=new RegExp(t.source,e.join(""));return"number"==typeof t.lastIndex&&(r.lastIndex=t.lastIndex),r}},function(t,e,r){"use strict";t.exports=function(t){return t.name?t.name:(t.toString().trim().match(/^function\s*([^\s(]+)/)||[])[1]}},function(t,e,r){"use strict";var n=r(5); -/*! - * Get the bson type, if it exists - */t.exports=function(t,e){return n(t,"_bsontype",void 0)===e}},function(t,e,r){"use strict";(function(e){ -/*! - * ignore - */ -var n=r(21),i=r(115),o={_promise:null,get:function(){return o._promise},set:function(t){n.ok("function"==typeof t,"mongoose.Promise must be a function, got "+t),o._promise=t,i.Promise=t}}; -/*! - * Use native promises by default - */ -o.set(e.Promise),t.exports=o}).call(this,r(11))},function(t,e,r){"use strict";(function(t,n){ -/*! - * Module dependencies. - */ -var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o=r(45).Buffer,s=r(63),a=e.clone=function t(r,n){if(void 0===r||null===r)return r;if(Array.isArray(r))return e.cloneArray(r,n);if(r.constructor){if(/ObjectI[dD]$/.test(r.constructor.name))return"function"==typeof r.clone?r.clone():new r.constructor(r.id);if("ReadPreference"===r.constructor.name)return new r.constructor(r.mode,t(r.tags,n));if("Binary"==r._bsontype&&r.buffer&&r.value)return"function"==typeof r.clone?r.clone():new r.constructor(r.value(!0),r.sub_type);if("Date"===r.constructor.name||"Function"===r.constructor.name)return new r.constructor(+r);if("RegExp"===r.constructor.name)return s(r);if("Buffer"===r.constructor.name)return e.cloneBuffer(r)}return c(r)?e.cloneObject(r,n):r.valueOf?r.valueOf():void 0}; -/*! - * ignore - */ -e.cloneObject=function(t,e){var r,n,i,o=e&&e.minimize,s={};for(i in t)n=a(t[i],e),o&&void 0===n||(r||(r=!0),s[i]=n);return o?r&&s:s},e.cloneArray=function(t,e){for(var r=[],n=0,i=t.length;n1)throw new Error("Adding properties is not supported");function e(){}return e.prototype=t,new e},e.inherits=function(t,r){t.prototype=e.create(r.prototype),t.prototype.constructor=t};var l=e.soon="function"==typeof t?t:n.nextTick;e.cloneBuffer=function(t){var e=o.alloc(t.length);return t.copy(e,0,0,t.length),e},e.isArgumentsObject=function(t){return"[object Arguments]"===Object.prototype.toString.call(t)}}).call(this,r(68).setImmediate,r(8))},function(t,e,r){"use strict";(function(t){var n=void 0!==t&&t||"undefined"!=typeof self&&self||window,i=Function.prototype.apply;function o(t,e){this._id=t,this._clearFn=e}e.setTimeout=function(){return new o(i.call(setTimeout,n,arguments),clearTimeout)},e.setInterval=function(){return new o(i.call(setInterval,n,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},o.prototype.unref=o.prototype.ref=function(){},o.prototype.close=function(){this._clearFn.call(n,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function(){t._onTimeout&&t._onTimeout()},e))},r(116),e.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==t&&t.setImmediate||void 0,e.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==t&&t.clearImmediate||void 0}).call(this,r(11))},function(t,e,r){"use strict";(function(t,r,n,i){var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};e.isNode=void 0!==t&&"object"==o(r)&&"object"==(void 0===n?"undefined":o(n))&&"function"==typeof i&&t.argv,e.isMongo=!e.isNode&&"function"==typeof printjson&&"function"==typeof ObjectId&&"function"==typeof rs&&"function"==typeof sh,e.isBrowser=!e.isNode&&!e.isMongo&&"undefined"!=typeof window,e.type=e.isNode?"node":e.isMongo?"mongo":e.isBrowser?"browser":"unknown"}).call(this,r(8),r(121)(t),r(11),r(1).Buffer)},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(4);function i(t){var e=t.message;e||(e=n.messages.general.default);var r=this.formatMessage(e,t);n.call(this,r),t=Object.assign({},t,{message:r}),this.name="ValidatorError",Error.captureStackTrace?Error.captureStackTrace(this):this.stack=(new Error).stack,this.properties=t,this.kind=t.type,this.path=t.path,this.value=t.value,this.reason=t.reason} -/*! - * Inherits from MongooseError - */i.prototype=Object.create(n.prototype),i.prototype.constructor=n, -/*! - * The object used to define this validator. Not enumerable to hide - * it from `require('util').inspect()` output re: gh-3925 - */ -Object.defineProperty(i.prototype,"properties",{enumerable:!1,writable:!0,value:null}), -/*! - * Formats error messages - */ -i.prototype.formatMessage=function(t,e){if("function"==typeof t)return t(e);var r=Object.keys(e),n=!0,i=!1,o=void 0;try{for(var s,a=r[Symbol.iterator]();!(n=(s=a.next()).done);n=!0){var u=s.value;"message"!==u&&(t=t.replace("{"+u.toUpperCase()+"}",e[u]))}}catch(t){i=!0,o=t}finally{try{!n&&a.return&&a.return()}finally{if(i)throw o}}return t}, -/*! - * toString helper - */ -i.prototype.toString=function(){return this.message}, -/*! - * exports - */ -t.exports=i},function(t,e,r){"use strict"; -/*! - * ignore - */t.exports=function(t){if("number"!=typeof t&&"string"!=typeof t)throw new Error("$type parameter must be number or string");return t}},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(4);function i(t,e){var r=Array.isArray(e)?"array":"primitive value";n.call(this,"Tried to set nested object field `"+t+"` to "+r+" `"+e+"` and strict mode is set to throw."),this.name="ObjectExpectedError",Error.captureStackTrace?Error.captureStackTrace(this):this.stack=(new Error).stack,this.path=t} -/*! - * Inherits from MongooseError. - */i.prototype=Object.create(n.prototype),i.prototype.constructor=n,t.exports=i},function(t,e,r){"use strict";t.exports=function(t){var e={_id:{auto:!0}};e._id[t.options.typeKey]="ObjectId",t.add(e)}},function(t,e,r){"use strict";t.exports= -/*! - * ignore - */ -function(t,e){if(null==t)return null;if("boolean"==typeof t)return e;if("boolean"==typeof t[e])return t[e]?e:null;if(!(e in t))return e;return t[e]}},function(t,e,r){"use strict";var n=r(51),i=r(24); -/*! - * Register hooks for this model - * - * @param {Model} model - * @param {Schema} schema - */ -function o(t,e,r){var s={useErrorHandlers:!0,numCallbackParams:1,nullResultByDefault:!0,contextParameter:!0},a=(r=r||{}).decorateDoc?t:t.prototype;t.$appliedHooks=!0;var u=!0,c=!1,l=void 0;try{for(var f,h=Object.keys(e.paths)[Symbol.iterator]();!(u=(f=h.next()).done);u=!0){var p=f.value,d=e.paths[p],y=null;if(d.$isSingleNested)y=d.caster;else{if(!d.$isMongooseDocumentArray)continue;y=d.Constructor}if(!y.$appliedHooks&&(o(y,d.schema,r),null!=y.discriminators)){var v=Object.keys(y.discriminators),_=!0,m=!1,g=void 0;try{for(var b,w=v[Symbol.iterator]();!(_=(b=w.next()).done);_=!0){var O=b.value;o(y.discriminators[O],y.discriminators[O].schema,r)}}catch(t){m=!0,g=t}finally{try{!_&&w.return&&w.return()}finally{if(m)throw g}}}}}catch(t){c=!0,l=t}finally{try{!u&&h.return&&h.return()}finally{if(c)throw l}}var S=e.s.hooks.filter(function(t){return"updateOne"===t.name||"deleteOne"===t.name?!!t.document:"remove"!==t.name||(null==t.document||!!t.document)}).filter(function(t){return!e.methods[t.name]||!t.fn[n.builtInMiddleware]});t._middleware=S,a.$__originalValidate=a.$__originalValidate||a.$__validate;for(var E=["save","validate","remove","deleteOne"],A=0;A=t},message:r,type:"min",min:t})}return this},h.prototype.max=function(t,e){if(this.maxValidator&&(this.validators=this.validators.filter(function(t){return t.validator!==this.maxValidator},this)),null!==t&&void 0!==t){var r=e||n.messages.Number.max;r=r.replace(/{MAX}/,t),this.validators.push({validator:this.maxValidator=function(e){return null==e||e<=t},message:r,type:"max",max:t})}return this},h.prototype.enum=function(t,e){return this.enumValidator&&(this.validators=this.validators.filter(function(t){return t.validator!==this.enumValidator},this)),Array.isArray(t)||(t=Array.prototype.slice.call(arguments),e=n.messages.Number.enum),e=null==e?n.messages.Number.enum:e,this.enumValidator=function(e){return null==e||-1!==t.indexOf(e)},this.validators.push({validator:this.enumValidator,message:e,type:"enum",enumValues:t}),this},h.prototype.cast=function(t,n,i){if(o._isRef(this,t,n,i)){if(null===t||void 0===t)return t;if(f||(f=r(6)),t instanceof f)return t.$__.wasPopulated=!0,t;if("number"==typeof t)return t;if(e.isBuffer(t)||!u.isObject(t))throw new l("Number",t,this.path,null,this);var s=n.$__fullPath(this.path),a=new((n.ownerDocument?n.ownerDocument():n).populated(s,!0).options[c])(t);return a.$__.wasPopulated=!0,a}var p=t&&void 0!==t._id?t._id:t,d="function"==typeof this.constructor.cast?this.constructor.cast():h.cast();try{return d(p)}catch(t){throw new l("Number",p,this.path,t,this)}},h.prototype.$conditionalHandlers=u.options(o.prototype.$conditionalHandlers,{$bitsAllClear:a,$bitsAnyClear:a,$bitsAllSet:a,$bitsAnySet:a,$gt:p,$gte:p,$lt:p,$lte:p,$mod:function(t){var e=this;return Array.isArray(t)?t.map(function(t){return e.cast(t)}):[this.cast(t)]}}),h.prototype.castForQuery=function(t,e){var r=void 0;if(2===arguments.length){if(!(r=this.$conditionalHandlers[t]))throw new l("number",e,this.path,null,this);return r.call(this,e)}return e=this._castForQuery(t)}, -/*! - * Module exports. - */ -t.exports=h}).call(this,r(1).Buffer)},function(t,e,r){"use strict";(function(e){ -/*! - * Module requirements. - */ -var n=r(13); -/*! - * ignore - */ -/*! - * ignore - */ -function i(t,e){var r=Number(e);if(isNaN(r))throw new n("number",e,t);return r}t.exports=function(t){var r=this;return Array.isArray(t)?t.map(function(t){return i(r.path,t)}):e.isBuffer(t)?t:i(r.path,t)}}).call(this,r(1).Buffer)},function(t,e,r){"use strict";var n=new Set(["$ref","$id","$db"]);t.exports=function(t){return t.startsWith("$")&&!n.has(t)}},function(t,e,r){"use strict"; -/*! - * Module requirements. - */var n=r(32).castArraysOfNumbers,i=r(32).castToNumber;function o(t,e){switch(t.$geometry.type){case"Polygon":case"LineString":case"Point":n(t.$geometry.coordinates,e)}return s(e,t),t}function s(t,e){e.$maxDistance&&(e.$maxDistance=i.call(t,e.$maxDistance)),e.$minDistance&&(e.$minDistance=i.call(t,e.$minDistance))} -/*! - * ignore - */ -e.cast$geoIntersects=function(t){if(!t.$geometry)return;return o(t,this),t},e.cast$near=function(t){var e=r(55);if(Array.isArray(t))return n(t,this),t;if(s(this,t),t&&t.$geometry)return o(t,this);return e.prototype.castForQuery.call(this,t)},e.cast$within=function(t){var e=this;if(s(this,t),t.$box||t.$polygon){var r=t.$box?"$box":"$polygon";t[r].forEach(function(t){if(!Array.isArray(t)){var r="Invalid $within $box argument. Expected an array, received "+t;throw new TypeError(r)}t.forEach(function(r,n){t[n]=i.call(e,r)})})}else if(t.$center||t.$centerSphere){var n=t.$center?"$center":"$centerSphere";t[n].forEach(function(r,o){Array.isArray(r)?r.forEach(function(t,n){r[n]=i.call(e,t)}):t[n][o]=i.call(e,r)})}else t.$geometry&&o(t,this);return t}},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(82),i=r(6),o=r(0).arrayAtomicsSymbol,s=r(0).arrayParentSymbol,a=r(0).arrayPathSymbol,u=r(0).arraySchemaSymbol,c=Array.prototype.push; -/*! - * Module exports. - */ -t.exports=function(t,e,r){var l=new n;if(l[o]={},Array.isArray(t)){for(var f=t.length,h=0;h0?t:r)}return this}},{key:"_registerAtomic",value:function(t,e){if("$set"===t)return this[p]={$set:e},u(this[d],this[y]),this._markModified(),this;var r=this[p];if("$pop"===t&&!("$pop"in r)){var n=this;this[d].once("save",function(){n._popped=n._shifted=null})}if(this[p].$set||Object.keys(r).length&&!(t in r))return this[p]={$set:this},this;var i=void 0;if("$pullAll"===t||"$addToSet"===t)r[t]||(r[t]=[]),r[t]=r[t].concat(e);else if("$pullDocs"===t){var s=r.$pull||(r.$pull={});e[0]instanceof o?(i=s.$or||(s.$or=[]),Array.prototype.push.apply(i,e.map(function(t){return t.toObject({transform:!1,virtuals:!1})}))):(i=s._id||(s._id={$in:[]})).$in=i.$in.concat(e)}else"$push"===t?(r.$push=r.$push||{$each:[]},null!=e&&f.hasUserDefinedProperty(e,"$each")?r.$push=e:r.$push.$each=r.$push.$each.concat(e)):r[t]=e;return this}},{key:"addToSet",value:function(){w(this,arguments);var t=[].map.call(arguments,this._mapCast,this),e=[],r="";return(t=this[v].applySetters(t,this[d]))[0]instanceof o?r="doc":t[0]instanceof Date&&(r="date"),t.forEach(function(t){var n=void 0,i=+t;switch(r){case"doc":n=this.some(function(e){return e.equals(t)});break;case"date":n=this.some(function(t){return+t===i});break;default:n=~this.indexOf(t)}n||([].push.call(this,t),this._registerAtomic("$addToSet",t),this._markModified(),[].push.call(e,t))},this),e}},{key:"hasAtomics",value:function(){return f.isPOJO(this[p])?Object.keys(this[p]).length:0}},{key:"includes",value:function(t,e){return-1!==this.indexOf(t,e)}},{key:"indexOf",value:function(t,e){t instanceof a&&(t=t.toString()),e=null==e?0:e;for(var r=this.length,n=e;n0&&this._registerAtomic("$set",this),this}},{key:"push",value:function(){var t=arguments,e=t,r=null!=t[0]&&f.hasUserDefinedProperty(t[0],"$each");if(r&&(e=t[0],t=t[0].$each),null==this[v])return m.apply(this,t);w(this,t);var n=this[d];t=[].map.call(t,this._mapCast,this),t=this[v].applySetters(t,n,void 0,void 0,{skipDocumentArrayCast:!0});var i=void 0,o=this[p];if(r){if(e.$each=t,c(o,"$push.$each.length",0)>0&&o.$push.$position!=o.$position)throw new s("Cannot call `Array#push()` multiple times with different `$position`");null!=e.$position?([].splice.apply(this,[e.$position,0].concat(t)),i=this.length):i=[].push.apply(this,t)}else{if(c(o,"$push.$each.length",0)>0&&null!=o.$push.$position)throw new s("Cannot call `Array#push()` multiple times with different `$position`");e=t,i=[].push.apply(this,t)}return this._registerAtomic("$push",e),this._markModified(),i}},{key:"remove",value:function(){return this.pull.apply(this,arguments)}},{key:"set",value:function(t,e){var r=this._cast(e,t);return this[t]=r,this._markModified(t),this}},{key:"shift",value:function(){var t=[].shift.call(this);return this._registerAtomic("$set",this),this._markModified(),t}},{key:"sort",value:function(){var t=[].sort.apply(this,arguments);return this._registerAtomic("$set",this),t}},{key:"splice",value:function(){var t=void 0;if(w(this,Array.prototype.slice.call(arguments,2)),arguments.length){var e=void 0;if(null==this[v])e=arguments;else{e=[];for(var r=0;r0&& -/*! - * ignore - */ -function(t,e){if(!e)return!1;var r=!0,n=!1,o=void 0;try{for(var s,a=t[Symbol.iterator]();!(r=(s=a.next()).done);r=!0){var u=s.value;if(null==u)return!1;var c=u.constructor;if(!(u instanceof i)||c.modelName!==e&&c.baseModelName!==e)return!1}}catch(t){n=!0,o=t}finally{try{!r&&a.return&&a.return()}finally{if(n)throw o}}return!0}(e,r)&&t[d].populated(t[y],[],function(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}({},_,e[0].constructor))}h.inspect.custom&&(b.prototype[h.inspect.custom]=b.prototype.inspect),t.exports=b}).call(this,r(1).Buffer)},function(t,e,r){"use strict"; -/*! - * ignore - */t.exports=function(t,e,r){var n=(r=r||{}).skipDocArrays,i=0;if(!t)return i;var o=!0,s=!1,a=void 0;try{for(var u,c=Object.keys(t.$__.activePaths.states.modify)[Symbol.iterator]();!(o=(u=c.next()).done);o=!0){var l=u.value;if(n){var f=t.schema.path(l);if(f&&f.$isMongooseDocumentArray)continue}l.startsWith(e+".")&&(delete t.$__.activePaths.states.modify[l],++i)}}catch(t){s=!0,a=t}finally{try{!o&&c.return&&c.return()}finally{if(s)throw a}}return i}},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(14).get().Binary,i=r(2),o=r(45).Buffer,s=o.from("").constructor.prototype;function a(t,e,r){var n=void 0;n=0===arguments.length||null===arguments[0]||void 0===arguments[0]?0:t;var s=void 0,u=void 0,l=void 0;Array.isArray(e)?(u=e[0],l=e[1]):s=e;var f=void 0;return f="number"==typeof n||n instanceof Number?o.alloc(n):o.from(n,s,r),i.decorate(f,a.mixin),f.isMongooseBuffer=!0,f[a.pathSymbol]=u,f[c]=l,f._subtype=0,f}var u=Symbol.for("mongoose#Buffer#_path"),c=Symbol.for("mongoose#Buffer#_parent");a.pathSymbol=u, -/*! - * Inherit from Buffer. - */ -a.mixin={_subtype:void 0,_markModified:function(){var t=this[c];return t&&t.markModified(this[a.pathSymbol]),this},write:function(){var t=s.write.apply(this,arguments);return t>0&&this._markModified(),t},copy:function(t){var e=s.copy.apply(this,arguments);return t&&t.isMongooseBuffer&&t._markModified(),e}}, -/*! - * Compile other Buffer methods marking this buffer as modified. - */ -"writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 writeFloat writeDouble fill utf8Write binaryWrite asciiWrite set writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE writeInt16LE writeInt16BE writeInt32LE writeInt32BE writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE".split(" ").forEach(function(t){s[t]&&(a.mixin[t]=function(){var e=s[t].apply(this,arguments);return this._markModified(),e})}),a.mixin.toObject=function(t){var e="number"==typeof t?t:this._subtype||0;return new n(o.from(this),e)},a.mixin.toBSON=function(){return new n(this,this._subtype||0)},a.mixin.equals=function(t){if(!o.isBuffer(t))return!1;if(this.length!==t.length)return!1;for(var e=0;e0?s-4:s;for(r=0;r>16&255,u[l++]=e>>8&255,u[l++]=255&e;2===a&&(e=i[t.charCodeAt(r)]<<2|i[t.charCodeAt(r+1)]>>4,u[l++]=255&e);1===a&&(e=i[t.charCodeAt(r)]<<10|i[t.charCodeAt(r+1)]<<4|i[t.charCodeAt(r+2)]>>2,u[l++]=e>>8&255,u[l++]=255&e);return u},e.fromByteArray=function(t){for(var e,r=t.length,i=r%3,o=[],s=0,a=r-i;sa?a:s+16383));1===i?(e=t[r-1],o.push(n[e>>2]+n[e<<4&63]+"==")):2===i&&(e=(t[r-2]<<8)+t[r-1],o.push(n[e>>10]+n[e>>4&63]+n[e<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function l(t){return n[t>>18&63]+n[t>>12&63]+n[t>>6&63]+n[63&t]}function f(t,e,r){for(var n,i=[],o=e;o>1,l=-7,f=r?i-1:0,h=r?-1:1,p=t[e+f];for(f+=h,o=p&(1<<-l)-1,p>>=-l,l+=a;l>0;o=256*o+t[e+f],f+=h,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=n;l>0;s=256*s+t[e+f],f+=h,l-=8);if(0===o)o=1-c;else{if(o===u)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=c}return(p?-1:1)*s*Math.pow(2,o-n)},e.write=function(t,e,r,n,i,o){var s,a,u,c=8*o-i-1,l=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=l):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),(e+=s+f>=1?h/u:h*Math.pow(2,1-f))*u>=2&&(s++,u/=2),s+f>=l?(a=0,s=l):s+f>=1?(a=(e*u-1)*Math.pow(2,i),s+=f):(a=e*Math.pow(2,f-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=255&a,p+=d,a/=256,i-=8);for(s=s<0;t[r+p]=255&s,p+=d,s/=256,c-=8);t[r+p-d]|=128*y}},function(t,e,r){"use strict";var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,e,r){"use strict"; -/*! - * Module exports. - */e.Binary=r(99),e.Collection=function(){throw new Error("Cannot create a collection from browser library")},e.Decimal128=r(106),e.ObjectId=r(107),e.ReadPreference=r(108)},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(33).Binary; -/*! - * Module exports. - */t.exports=n},function(t,e,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};t.exports=function(t){return t&&"object"===(void 0===t?"undefined":n(t))&&"function"==typeof t.copy&&"function"==typeof t.fill&&"function"==typeof t.readUInt8}},function(t,e,r){"use strict";"function"==typeof Object.create?t.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},function(module,exports,__webpack_require__){"use strict";var Long=__webpack_require__(23).Long,Double=__webpack_require__(34).Double,Timestamp=__webpack_require__(35).Timestamp,ObjectID=__webpack_require__(36).ObjectID,_Symbol=__webpack_require__(38).Symbol,Code=__webpack_require__(39).Code,MinKey=__webpack_require__(41).MinKey,MaxKey=__webpack_require__(42).MaxKey,Decimal128=__webpack_require__(40),Int32=__webpack_require__(60),DBRef=__webpack_require__(43).DBRef,BSONRegExp=__webpack_require__(37).BSONRegExp,Binary=__webpack_require__(26).Binary,utils=__webpack_require__(15),deserialize=function(t,e,r){var n=(e=null==e?{}:e)&&e.index?e.index:0,i=t[n]|t[n+1]<<8|t[n+2]<<16|t[n+3]<<24;if(i<5||t.lengtht.length)throw new Error("corrupt bson message");if(0!==t[n+i-1])throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");return deserializeObject(t,n,e,r)},deserializeObject=function t(e,r,n,i){var o=null!=n.evalFunctions&&n.evalFunctions,s=null!=n.cacheFunctions&&n.cacheFunctions,a=null!=n.cacheFunctionsCrc32&&n.cacheFunctionsCrc32;if(!a)var u=null;var c=null==n.fieldsAsRaw?null:n.fieldsAsRaw,l=null!=n.raw&&n.raw,f="boolean"==typeof n.bsonRegExp&&n.bsonRegExp,h=null!=n.promoteBuffers&&n.promoteBuffers,p=null==n.promoteLongs||n.promoteLongs,d=null==n.promoteValues||n.promoteValues,y=r;if(e.length<5)throw new Error("corrupt bson message < 5 bytes long");var v=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24;if(v<5||v>e.length)throw new Error("corrupt bson message");for(var _=i?[]:{},m=0;;){var g=e[r++];if(0===g)break;for(var b=r;0!==e[b]&&b=e.length)throw new Error("Bad BSON Document: illegal CString");var w=i?m++:e.toString("utf8",r,b);if(r=b+1,g===BSON.BSON_DATA_STRING){var O=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24;if(O<=0||O>e.length-r||0!==e[r+O-1])throw new Error("bad string length in bson");_[w]=e.toString("utf8",r,r+O-1),r+=O}else if(g===BSON.BSON_DATA_OID){var S=utils.allocBuffer(12);e.copy(S,0,r,r+12),_[w]=new ObjectID(S),r+=12}else if(g===BSON.BSON_DATA_INT&&!1===d)_[w]=new Int32(e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24);else if(g===BSON.BSON_DATA_INT)_[w]=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24;else if(g===BSON.BSON_DATA_NUMBER&&!1===d)_[w]=new Double(e.readDoubleLE(r)),r+=8;else if(g===BSON.BSON_DATA_NUMBER)_[w]=e.readDoubleLE(r),r+=8;else if(g===BSON.BSON_DATA_DATE){var E=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24,A=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24;_[w]=new Date(new Long(E,A).toNumber())}else if(g===BSON.BSON_DATA_BOOLEAN){if(0!==e[r]&&1!==e[r])throw new Error("illegal boolean type value");_[w]=1===e[r++]}else if(g===BSON.BSON_DATA_OBJECT){var $=r,j=e[r]|e[r+1]<<8|e[r+2]<<16|e[r+3]<<24;if(j<=0||j>e.length-r)throw new Error("bad embedded document length in bson");_[w]=l?e.slice(r,r+j):t(e,$,n,!1),r+=j}else if(g===BSON.BSON_DATA_ARRAY){$=r;var x=n,N=r+(j=e[r]|e[r+1]<<8|e[r+2]<<16|e[r+3]<<24);if(c&&c[w]){for(var P in x={},n)x[P]=n[P];x.raw=!0}if(_[w]=t(e,$,x,!0),0!==e[(r+=j)-1])throw new Error("invalid array terminator byte");if(r!==N)throw new Error("corrupted array bson")}else if(g===BSON.BSON_DATA_UNDEFINED)_[w]=void 0;else if(g===BSON.BSON_DATA_NULL)_[w]=null;else if(g===BSON.BSON_DATA_LONG){E=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24,A=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24;var k=new Long(E,A);_[w]=p&&!0===d&&k.lessThanOrEqual(JS_INT_MAX_LONG)&&k.greaterThanOrEqual(JS_INT_MIN_LONG)?k.toNumber():k}else if(g===BSON.BSON_DATA_DECIMAL128){var T=utils.allocBuffer(16);e.copy(T,0,r,r+16),r+=16;var B=new Decimal128(T);_[w]=B.toObject?B.toObject():B}else if(g===BSON.BSON_DATA_BINARY){var C=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24,D=C,M=e[r++];if(C<0)throw new Error("Negative binary type element size found");if(C>e.length)throw new Error("Binary type size larger than document size");if(null!=e.slice){if(M===Binary.SUBTYPE_BYTE_ARRAY){if((C=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24)<0)throw new Error("Negative binary type element size found for subtype 0x02");if(C>D-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(CD-4)throw new Error("Binary type with subtype 0x02 contains to long binary size");if(C=e.length)throw new Error("Bad BSON Document: illegal CString");var F=e.toString("utf8",r,b);for(b=r=b+1;0!==e[b]&&b=e.length)throw new Error("Bad BSON Document: illegal CString");var I=e.toString("utf8",r,b);r=b+1;var L=new Array(I.length);for(b=0;b=e.length)throw new Error("Bad BSON Document: illegal CString");for(F=e.toString("utf8",r,b),b=r=b+1;0!==e[b]&&b=e.length)throw new Error("Bad BSON Document: illegal CString");I=e.toString("utf8",r,b),r=b+1,_[w]=new BSONRegExp(F,I)}else if(g===BSON.BSON_DATA_SYMBOL){if((O=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24)<=0||O>e.length-r||0!==e[r+O-1])throw new Error("bad string length in bson");_[w]=new _Symbol(e.toString("utf8",r,r+O-1)),r+=O}else if(g===BSON.BSON_DATA_TIMESTAMP)E=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24,A=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24,_[w]=new Timestamp(E,A);else if(g===BSON.BSON_DATA_MIN_KEY)_[w]=new MinKey;else if(g===BSON.BSON_DATA_MAX_KEY)_[w]=new MaxKey;else if(g===BSON.BSON_DATA_CODE){if((O=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24)<=0||O>e.length-r||0!==e[r+O-1])throw new Error("bad string length in bson");var U=e.toString("utf8",r,r+O-1);if(o)if(s){var V=a?u(U):U;_[w]=isolateEvalWithHash(functionCache,V,U,_)}else _[w]=isolateEval(U);else _[w]=new Code(U);r+=O}else if(g===BSON.BSON_DATA_CODE_W_SCOPE){var q=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24;if(q<13)throw new Error("code_w_scope total size shorter minimum expected length");if((O=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24)<=0||O>e.length-r||0!==e[r+O-1])throw new Error("bad string length in bson");U=e.toString("utf8",r,r+O-1),$=r+=O,j=e[r]|e[r+1]<<8|e[r+2]<<16|e[r+3]<<24;var W=t(e,$,n,!1);if(r+=j,q<8+j+O)throw new Error("code_w_scope total size is to short, truncating scope");if(q>8+j+O)throw new Error("code_w_scope total size is to long, clips outer document");o?(s?(V=a?u(U):U,_[w]=isolateEvalWithHash(functionCache,V,U,_)):_[w]=isolateEval(U),_[w].scope=W):_[w]=new Code(U,W)}else{if(g!==BSON.BSON_DATA_DBPOINTER)throw new Error("Detected unknown BSON type "+g.toString(16)+' for fieldname "'+w+'", are you using the latest BSON parser');if((O=e[r++]|e[r++]<<8|e[r++]<<16|e[r++]<<24)<=0||O>e.length-r||0!==e[r+O-1])throw new Error("bad string length in bson");var H=e.toString("utf8",r,r+O-1);r+=O;var Y=utils.allocBuffer(12);e.copy(Y,0,r,r+12),S=new ObjectID(Y),r+=12;var z=H.split("."),K=z.shift(),Q=z.join(".");_[w]=new DBRef(Q,S,K)}}if(v!==r-y){if(i)throw new Error("corrupt array bson");throw new Error("corrupt object bson")}return null!=_.$id&&(_=new DBRef(_.$ref,_.$id,_.$db)),_},isolateEvalWithHash=function isolateEvalWithHash(functionCache,hash,functionString,object){var value=null;return null==functionCache[hash]&&(eval("value = "+functionString),functionCache[hash]=value),functionCache[hash].bind(object)},isolateEval=function isolateEval(functionString){var value=null;return eval("value = "+functionString),value},BSON={},functionCache=BSON.functionCache={};BSON.BSON_DATA_NUMBER=1,BSON.BSON_DATA_STRING=2,BSON.BSON_DATA_OBJECT=3,BSON.BSON_DATA_ARRAY=4,BSON.BSON_DATA_BINARY=5,BSON.BSON_DATA_UNDEFINED=6,BSON.BSON_DATA_OID=7,BSON.BSON_DATA_BOOLEAN=8,BSON.BSON_DATA_DATE=9,BSON.BSON_DATA_NULL=10,BSON.BSON_DATA_REGEXP=11,BSON.BSON_DATA_DBPOINTER=12,BSON.BSON_DATA_CODE=13,BSON.BSON_DATA_SYMBOL=14,BSON.BSON_DATA_CODE_W_SCOPE=15,BSON.BSON_DATA_INT=16,BSON.BSON_DATA_TIMESTAMP=17,BSON.BSON_DATA_LONG=18,BSON.BSON_DATA_DECIMAL128=19,BSON.BSON_DATA_MIN_KEY=255,BSON.BSON_DATA_MAX_KEY=127,BSON.BSON_BINARY_SUBTYPE_DEFAULT=0,BSON.BSON_BINARY_SUBTYPE_FUNCTION=1,BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY=2,BSON.BSON_BINARY_SUBTYPE_UUID=3,BSON.BSON_BINARY_SUBTYPE_MD5=4,BSON.BSON_BINARY_SUBTYPE_USER_DEFINED=128,BSON.BSON_INT32_MAX=2147483647,BSON.BSON_INT32_MIN=-2147483648,BSON.BSON_INT64_MAX=Math.pow(2,63)-1,BSON.BSON_INT64_MIN=-Math.pow(2,63),BSON.JS_INT_MAX=9007199254740992,BSON.JS_INT_MIN=-9007199254740992;var JS_INT_MAX_LONG=Long.fromNumber(9007199254740992),JS_INT_MIN_LONG=Long.fromNumber(-9007199254740992);module.exports=deserialize},function(t,e,r){"use strict";(function(e){var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(104).writeIEEE754,o=r(23).Long,s=r(59),a=r(26).Binary,u=r(15).normalizedFunctionString,c=/\x00/,l=["$db","$ref","$id","$clusterTime"],f=function(t){return"object"===(void 0===t?"undefined":n(t))&&"[object Date]"===Object.prototype.toString.call(t)},h=function(t){return"[object RegExp]"===Object.prototype.toString.call(t)},p=function(t,e,r,n,i){t[n++]=C.BSON_DATA_STRING,t[(n=n+(i?t.write(e,n,"ascii"):t.write(e,n,"utf8"))+1)-1]=0;var o=t.write(r,n+4,"utf8");return t[n+3]=o+1>>24&255,t[n+2]=o+1>>16&255,t[n+1]=o+1>>8&255,t[n]=o+1&255,n=n+4+o,t[n++]=0,n},d=function(t,e,r,n,s){if(Math.floor(r)===r&&r>=C.JS_INT_MIN&&r<=C.JS_INT_MAX)if(r>=C.BSON_INT32_MIN&&r<=C.BSON_INT32_MAX){t[n++]=C.BSON_DATA_INT;var a=s?t.write(e,n,"ascii"):t.write(e,n,"utf8");n+=a,t[n++]=0,t[n++]=255&r,t[n++]=r>>8&255,t[n++]=r>>16&255,t[n++]=r>>24&255}else if(r>=C.JS_INT_MIN&&r<=C.JS_INT_MAX)t[n++]=C.BSON_DATA_NUMBER,n+=a=s?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,i(t,r,n,"little",52,8),n+=8;else{t[n++]=C.BSON_DATA_LONG,n+=a=s?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var u=o.fromNumber(r),c=u.getLowBits(),l=u.getHighBits();t[n++]=255&c,t[n++]=c>>8&255,t[n++]=c>>16&255,t[n++]=c>>24&255,t[n++]=255&l,t[n++]=l>>8&255,t[n++]=l>>16&255,t[n++]=l>>24&255}else t[n++]=C.BSON_DATA_NUMBER,n+=a=s?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,i(t,r,n,"little",52,8),n+=8;return n},y=function(t,e,r,n,i){return t[n++]=C.BSON_DATA_NULL,n+=i?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,n},v=function(t,e,r,n,i){return t[n++]=C.BSON_DATA_BOOLEAN,n+=i?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,t[n++]=r?1:0,n},_=function(t,e,r,n,i){t[n++]=C.BSON_DATA_DATE,n+=i?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var s=o.fromNumber(r.getTime()),a=s.getLowBits(),u=s.getHighBits();return t[n++]=255&a,t[n++]=a>>8&255,t[n++]=a>>16&255,t[n++]=a>>24&255,t[n++]=255&u,t[n++]=u>>8&255,t[n++]=u>>16&255,t[n++]=u>>24&255,n},m=function(t,e,r,n,i){if(t[n++]=C.BSON_DATA_REGEXP,n+=i?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,r.source&&null!=r.source.match(c))throw Error("value "+r.source+" must not contain null bytes");return n+=t.write(r.source,n,"utf8"),t[n++]=0,r.global&&(t[n++]=115),r.ignoreCase&&(t[n++]=105),r.multiline&&(t[n++]=109),t[n++]=0,n},g=function(t,e,r,n,i){if(t[n++]=C.BSON_DATA_REGEXP,n+=i?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,null!=r.pattern.match(c))throw Error("pattern "+r.pattern+" must not contain null bytes");return n+=t.write(r.pattern,n,"utf8"),t[n++]=0,n+=t.write(r.options.split("").sort().join(""),n,"utf8"),t[n++]=0,n},b=function(t,e,r,n,i){return null===r?t[n++]=C.BSON_DATA_NULL:"MinKey"===r._bsontype?t[n++]=C.BSON_DATA_MIN_KEY:t[n++]=C.BSON_DATA_MAX_KEY,n+=i?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,n},w=function(t,e,r,n,i){if(t[n++]=C.BSON_DATA_OID,n+=i?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,"string"==typeof r.id)t.write(r.id,n,"binary");else{if(!r.id||!r.id.copy)throw new Error("object ["+JSON.stringify(r)+"] is not a valid ObjectId");r.id.copy(t,n,0,12)}return n+12},O=function(t,e,r,n,i){t[n++]=C.BSON_DATA_BINARY,n+=i?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var o=r.length;return t[n++]=255&o,t[n++]=o>>8&255,t[n++]=o>>16&255,t[n++]=o>>24&255,t[n++]=C.BSON_BINARY_SUBTYPE_DEFAULT,r.copy(t,n,0,o),n+=o},S=function(t,e,r,n,i,o,s,a,u,c){for(var l=0;l>8&255,t[n++]=o>>16&255,t[n++]=o>>24&255,t[n++]=255&s,t[n++]=s>>8&255,t[n++]=s>>16&255,t[n++]=s>>24&255,n},$=function(t,e,r,n,i){return t[n++]=C.BSON_DATA_INT,n+=i?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,t[n++]=255&r,t[n++]=r>>8&255,t[n++]=r>>16&255,t[n++]=r>>24&255,n},j=function(t,e,r,n,o){return t[n++]=C.BSON_DATA_NUMBER,n+=o?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0,i(t,r,n,"little",52,8),n+=8},x=function(t,e,r,n,i,o,s){t[n++]=C.BSON_DATA_CODE,n+=s?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var a=u(r),c=t.write(a,n+4,"utf8")+1;return t[n]=255&c,t[n+1]=c>>8&255,t[n+2]=c>>16&255,t[n+3]=c>>24&255,n=n+4+c-1,t[n++]=0,n},N=function(t,e,r,i,o,s,a,u,c){if(r.scope&&"object"===n(r.scope)){t[i++]=C.BSON_DATA_CODE_W_SCOPE;var l=c?t.write(e,i,"ascii"):t.write(e,i,"utf8");i+=l,t[i++]=0;var f=i,h="string"==typeof r.code?r.code:r.code.toString();i+=4;var p=t.write(h,i+4,"utf8")+1;t[i]=255&p,t[i+1]=p>>8&255,t[i+2]=p>>16&255,t[i+3]=p>>24&255,t[i+4+p-1]=0,i=i+p+4;var d=B(t,r.scope,o,i,s+1,a,u);i=d-1;var y=d-f;t[f++]=255&y,t[f++]=y>>8&255,t[f++]=y>>16&255,t[f++]=y>>24&255,t[i++]=0}else{t[i++]=C.BSON_DATA_CODE,i+=l=c?t.write(e,i,"ascii"):t.write(e,i,"utf8"),t[i++]=0,h=r.code.toString();var v=t.write(h,i+4,"utf8")+1;t[i]=255&v,t[i+1]=v>>8&255,t[i+2]=v>>16&255,t[i+3]=v>>24&255,i=i+4+v-1,t[i++]=0}return i},P=function(t,e,r,n,i){t[n++]=C.BSON_DATA_BINARY,n+=i?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var o=r.value(!0),s=r.position;return r.sub_type===a.SUBTYPE_BYTE_ARRAY&&(s+=4),t[n++]=255&s,t[n++]=s>>8&255,t[n++]=s>>16&255,t[n++]=s>>24&255,t[n++]=r.sub_type,r.sub_type===a.SUBTYPE_BYTE_ARRAY&&(s-=4,t[n++]=255&s,t[n++]=s>>8&255,t[n++]=s>>16&255,t[n++]=s>>24&255),o.copy(t,n,0,r.position),n+=r.position},k=function(t,e,r,n,i){t[n++]=C.BSON_DATA_SYMBOL,n+=i?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var o=t.write(r.value,n+4,"utf8")+1;return t[n]=255&o,t[n+1]=o>>8&255,t[n+2]=o>>16&255,t[n+3]=o>>24&255,n=n+4+o-1,t[n++]=0,n},T=function(t,e,r,n,i,o,s){t[n++]=C.BSON_DATA_OBJECT,n+=s?t.write(e,n,"ascii"):t.write(e,n,"utf8"),t[n++]=0;var a,u=n,c=(a=null!=r.db?B(t,{$ref:r.namespace,$id:r.oid,$db:r.db},!1,n,i+1,o):B(t,{$ref:r.namespace,$id:r.oid},!1,n,i+1,o))-u;return t[u++]=255&c,t[u++]=c>>8&255,t[u++]=c>>16&255,t[u++]=c>>24&255,a},B=function(t,r,i,o,a,u,B,C){o=o||0,(C=C||[]).push(r);var D=o+4;if(Array.isArray(r))for(var M=0;M>8&255,t[o++]=q>>16&255,t[o++]=q>>24&255,D},C={BSON_DATA_NUMBER:1,BSON_DATA_STRING:2,BSON_DATA_OBJECT:3,BSON_DATA_ARRAY:4,BSON_DATA_BINARY:5,BSON_DATA_UNDEFINED:6,BSON_DATA_OID:7,BSON_DATA_BOOLEAN:8,BSON_DATA_DATE:9,BSON_DATA_NULL:10,BSON_DATA_REGEXP:11,BSON_DATA_CODE:13,BSON_DATA_SYMBOL:14,BSON_DATA_CODE_W_SCOPE:15,BSON_DATA_INT:16,BSON_DATA_TIMESTAMP:17,BSON_DATA_LONG:18,BSON_DATA_DECIMAL128:19,BSON_DATA_MIN_KEY:255,BSON_DATA_MAX_KEY:127,BSON_BINARY_SUBTYPE_DEFAULT:0,BSON_BINARY_SUBTYPE_FUNCTION:1,BSON_BINARY_SUBTYPE_BYTE_ARRAY:2,BSON_BINARY_SUBTYPE_UUID:3,BSON_BINARY_SUBTYPE_MD5:4,BSON_BINARY_SUBTYPE_USER_DEFINED:128,BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648};C.BSON_INT64_MAX=Math.pow(2,63)-1,C.BSON_INT64_MIN=-Math.pow(2,63),C.JS_INT_MAX=9007199254740992,C.JS_INT_MIN=-9007199254740992,t.exports=B}).call(this,r(1).Buffer)},function(t,e,r){"use strict";e.readIEEE754=function(t,e,r,n,i){var o,s,a="big"===r,u=8*i-n-1,c=(1<>1,f=-7,h=a?0:i-1,p=a?1:-1,d=t[e+h];for(h+=p,o=d&(1<<-f)-1,d>>=-f,f+=u;f>0;o=256*o+t[e+h],h+=p,f-=8);for(s=o&(1<<-f)-1,o>>=-f,f+=n;f>0;s=256*s+t[e+h],h+=p,f-=8);if(0===o)o=1-l;else{if(o===c)return s?NaN:1/0*(d?-1:1);s+=Math.pow(2,n),o-=l}return(d?-1:1)*s*Math.pow(2,o-n)},e.writeIEEE754=function(t,e,r,n,i,o){var s,a,u,c="big"===n,l=8*o-i-1,f=(1<>1,p=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=c?o-1:0,y=c?-1:1,v=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=f):(s=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-s))<1&&(s--,u*=2),(e+=s+h>=1?p/u:p*Math.pow(2,1-h))*u>=2&&(s++,u/=2),s+h>=f?(a=0,s=f):s+h>=1?(a=(e*u-1)*Math.pow(2,i),s+=h):(a=e*Math.pow(2,h-1)*Math.pow(2,i),s=0));i>=8;t[r+d]=255&a,d+=y,a/=256,i-=8);for(s=s<0;t[r+d]=255&s,d+=y,s/=256,l-=8);t[r+d-y]|=128*v}},function(t,e,r){"use strict";(function(e){var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(23).Long,o=r(34).Double,s=r(35).Timestamp,a=r(36).ObjectID,u=r(38).Symbol,c=r(37).BSONRegExp,l=r(39).Code,f=r(40),h=r(41).MinKey,p=r(42).MaxKey,d=r(43).DBRef,y=r(26).Binary,v=r(15).normalizedFunctionString,_=function(t){return"object"===(void 0===t?"undefined":n(t))&&"[object Date]"===Object.prototype.toString.call(t)},m=function(t,e,r){var n=5;if(Array.isArray(t))for(var i=0;i=b.JS_INT_MIN&&r<=b.JS_INT_MAX&&r>=b.BSON_INT32_MIN&&r<=b.BSON_INT32_MAX?(null!=t?e.byteLength(t,"utf8")+1:0)+5:(null!=t?e.byteLength(t,"utf8")+1:0)+9;case"undefined":return w||!O?(null!=t?e.byteLength(t,"utf8")+1:0)+1:0;case"boolean":return(null!=t?e.byteLength(t,"utf8")+1:0)+2;case"object":if(null==r||r instanceof h||r instanceof p||"MinKey"===r._bsontype||"MaxKey"===r._bsontype)return(null!=t?e.byteLength(t,"utf8")+1:0)+1;if(r instanceof a||"ObjectID"===r._bsontype||"ObjectId"===r._bsontype)return(null!=t?e.byteLength(t,"utf8")+1:0)+13;if(r instanceof Date||_(r))return(null!=t?e.byteLength(t,"utf8")+1:0)+9;if(void 0!==e&&e.isBuffer(r))return(null!=t?e.byteLength(t,"utf8")+1:0)+6+r.length;if(r instanceof i||r instanceof o||r instanceof s||"Long"===r._bsontype||"Double"===r._bsontype||"Timestamp"===r._bsontype)return(null!=t?e.byteLength(t,"utf8")+1:0)+9;if(r instanceof f||"Decimal128"===r._bsontype)return(null!=t?e.byteLength(t,"utf8")+1:0)+17;if(r instanceof l||"Code"===r._bsontype)return null!=r.scope&&Object.keys(r.scope).length>0?(null!=t?e.byteLength(t,"utf8")+1:0)+1+4+4+e.byteLength(r.code.toString(),"utf8")+1+m(r.scope,g,O):(null!=t?e.byteLength(t,"utf8")+1:0)+1+4+e.byteLength(r.code.toString(),"utf8")+1;if(r instanceof y||"Binary"===r._bsontype)return r.sub_type===y.SUBTYPE_BYTE_ARRAY?(null!=t?e.byteLength(t,"utf8")+1:0)+(r.position+1+4+1+4):(null!=t?e.byteLength(t,"utf8")+1:0)+(r.position+1+4+1);if(r instanceof u||"Symbol"===r._bsontype)return(null!=t?e.byteLength(t,"utf8")+1:0)+e.byteLength(r.value,"utf8")+4+1+1;if(r instanceof d||"DBRef"===r._bsontype){var S={$ref:r.namespace,$id:r.oid};return null!=r.db&&(S.$db=r.db),(null!=t?e.byteLength(t,"utf8")+1:0)+1+m(S,g,O)}return r instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(r)?(null!=t?e.byteLength(t,"utf8")+1:0)+1+e.byteLength(r.source,"utf8")+1+(r.global?1:0)+(r.ignoreCase?1:0)+(r.multiline?1:0)+1:r instanceof c||"BSONRegExp"===r._bsontype?(null!=t?e.byteLength(t,"utf8")+1:0)+1+e.byteLength(r.pattern,"utf8")+1+e.byteLength(r.options,"utf8")+1:(null!=t?e.byteLength(t,"utf8")+1:0)+m(r,g,O)+1;case"function":if(r instanceof RegExp||"[object RegExp]"===Object.prototype.toString.call(r)||"[object RegExp]"===String.call(r))return(null!=t?e.byteLength(t,"utf8")+1:0)+1+e.byteLength(r.source,"utf8")+1+(r.global?1:0)+(r.ignoreCase?1:0)+(r.multiline?1:0)+1;if(g&&null!=r.scope&&Object.keys(r.scope).length>0)return(null!=t?e.byteLength(t,"utf8")+1:0)+1+4+4+e.byteLength(v(r),"utf8")+1+m(r.scope,g,O);if(g)return(null!=t?e.byteLength(t,"utf8")+1:0)+1+4+e.byteLength(v(r),"utf8")+1}return 0}var b={BSON_INT32_MAX:2147483647,BSON_INT32_MIN:-2147483648,JS_INT_MAX:9007199254740992,JS_INT_MIN:-9007199254740992};t.exports=m}).call(this,r(1).Buffer)},function(t,e,r){"use strict"; -/*! - * ignore - */t.exports=r(33).Decimal128},function(t,e,r){"use strict"; -/*! - * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId - * @constructor NodeMongoDbObjectId - * @see ObjectId - */var n=r(33).ObjectID; -/*! - * Getter for convenience with populate, see gh-6115 - */Object.defineProperty(n.prototype,"_id",{enumerable:!1,configurable:!0,get:function(){return this}}), -/*! - * ignore - */ -t.exports=n},function(t,e,r){"use strict"; -/*! - * ignore - */t.exports=function(){}},function(t,e,r){"use strict"; -/*! - * Dependencies - */var n=r(110).ctor("require","modify","init","default","ignore");t.exports=function(){this.strictMode=void 0,this.selected=void 0,this.shardval=void 0,this.saveError=void 0,this.validationError=void 0,this.adhocPaths=void 0,this.removing=void 0,this.inserting=void 0,this.saving=void 0,this.version=void 0,this.getters={},this._id=void 0,this.populate=void 0,this.populated=void 0,this.wasPopulated=!1,this.scope=void 0,this.activePaths=new n,this.pathsToScopes={},this.cachedRequired={},this.session=null,this.$setCalled=new Set,this.ownerDocument=void 0,this.fullPath=void 0}},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(2),i=t.exports=function(){}; -/*! - * StateMachine represents a minimal `interface` for the - * constructors it builds via StateMachine.ctor(...). - * - * @api private - */ -/*! - * StateMachine.ctor('state1', 'state2', ...) - * A factory method for subclassing StateMachine. - * The arguments are a list of states. For each state, - * the constructor's prototype gets state transition - * methods named after each state. These transition methods - * place their path argument into the given state. - * - * @param {String} state - * @param {String} [state] - * @return {Function} subclass constructor - * @private - */ -i.ctor=function(){var t=n.args(arguments),e=function(){i.apply(this,arguments),this.paths={},this.states={},this.stateNames=t;for(var e=t.length,r=void 0;e--;)r=t[e],this.states[r]={}};return e.prototype=new i,t.forEach(function(t){e.prototype[t]=function(e){this._changeState(e,t)}}),e}, -/*! - * This function is wrapped by the state change functions: - * - * - `require(path)` - * - `modify(path)` - * - `init(path)` - * - * @api private - */ -i.prototype._changeState=function(t,e){var r=this.states[this.paths[t]];r&&delete r[t],this.paths[t]=e,this.states[e][t]=!0}, -/*! - * ignore - */ -i.prototype.clear=function(t){for(var e=Object.keys(this.states[t]),r=e.length,n=void 0;r--;)n=e[r],delete this.states[t][n],delete this.paths[n]}, -/*! - * Checks to see if at least one path is in the states passed in via `arguments` - * e.g., this.some('required', 'inited') - * - * @param {String} state that we want to check for. - * @private - */ -i.prototype.some=function(){var t=this,e=arguments.length?arguments:this.stateNames;return Array.prototype.some.call(e,function(e){return Object.keys(t.states[e]).length})}, -/*! - * This function builds the functions that get assigned to `forEach` and `map`, - * since both of those methods share a lot of the same logic. - * - * @param {String} iterMethod is either 'forEach' or 'map' - * @return {Function} - * @api private - */ -i.prototype._iter=function(t){return function(){var e=arguments.length,r=n.args(arguments,0,e-1),i=arguments[e-1];r.length||(r=this.stateNames);var o=this;return r.reduce(function(t,e){return t.concat(Object.keys(o.states[e]))},[])[t](function(t,e,r){return i(t,e,r)})}}, -/*! - * Iterates over the paths that belong to one of the parameter states. - * - * The function profile can look like: - * this.forEach(state1, fn); // iterates over all paths in state1 - * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 - * this.forEach(fn); // iterates over all paths in all states - * - * @param {String} [state] - * @param {String} [state] - * @param {Function} callback - * @private - */ -i.prototype.forEach=function(){return this.forEach=this._iter("forEach"),this.forEach.apply(this,arguments)}, -/*! - * Maps over the paths that belong to one of the parameter states. - * - * The function profile can look like: - * this.forEach(state1, fn); // iterates over all paths in state1 - * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 - * this.forEach(fn); // iterates over all paths in all states - * - * @param {String} [state] - * @param {String} [state] - * @param {Function} callback - * @return {Array} - * @private - */ -i.prototype.map=function(){return this.map=this._iter("map"),this.map.apply(this,arguments)}},function(t,e,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=1e3,o=60*i,s=60*o,a=24*s,u=7*a,c=365.25*a;function l(t,e,r,n){var i=e>=1.5*r;return Math.round(t/r)+" "+n+(i?"s":"")}t.exports=function(t,e){e=e||{};var r=void 0===t?"undefined":n(t);if("string"===r&&t.length>0)return function(t){if((t=String(t)).length>100)return;var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(!e)return;var r=parseFloat(e[1]);switch((e[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*c;case"weeks":case"week":case"w":return r*u;case"days":case"day":case"d":return r*a;case"hours":case"hour":case"hrs":case"hr":case"h":return r*s;case"minutes":case"minute":case"mins":case"min":case"m":return r*o;case"seconds":case"second":case"secs":case"sec":case"s":return r*i;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(t);if("number"===r&&isFinite(t))return e.long?function(t){var e=Math.abs(t);if(e>=a)return l(t,e,a,"day");if(e>=s)return l(t,e,s,"hour");if(e>=o)return l(t,e,o,"minute");if(e>=i)return l(t,e,i,"second");return t+" ms"}(t):function(t){var e=Math.abs(t);if(e>=a)return Math.round(t/a)+"d";if(e>=s)return Math.round(t/s)+"h";if(e>=o)return Math.round(t/o)+"m";if(e>=i)return Math.round(t/i)+"s";return t+"ms"}(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},function(t,e,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=["__proto__","constructor","prototype"]; -/*! - * Returns the value passed to it. - */ -function o(t){return t}e.get=function(t,r,n,i){var s;"function"==typeof n&&(n.length<2?(i=n,n=void 0):(s=n,n=void 0)),i||(i=o);var a="string"==typeof t?t.split("."):t;if(!Array.isArray(a))throw new TypeError("Invalid `path`. Must be either string or array");for(var u,c=r,l=0;l");t.sort.set(r,n)})} -/*! - * limit, skip, maxScan, batchSize, comment - * - * Sets these associated options. - * - * query.comment('feed query'); - */(this.options,t),this;throw new TypeError("Invalid sort() argument. Must be a string, object, or array.")}; -/*! - * @ignore - */ -var f={1:1,"-1":-1,asc:1,ascending:1,desc:-1,descending:-1};function h(t,e,r){if(Array.isArray(t.sort))throw new TypeError("Can't mix sort syntaxes. Use either array or object:\n- `.sort([['field', 1], ['test', -1]])`\n- `.sort({ field: 1, test: -1 })`");var n;if(r&&r.$meta)(n=t.sort||(t.sort={}))[e]={$meta:r.$meta};else{n=t.sort||(t.sort={});var i=String(r||1).toLowerCase();if(!(i=f[i]))throw new TypeError("Invalid sort value: { "+e+": "+r+" }");n[e]=i}}function p(t,e,r){if(t.sort=t.sort||[],!Array.isArray(t.sort))throw new TypeError("Can't mix sort syntaxes. Use either array or object:\n- `.sort([['field', 1], ['test', -1]])`\n- `.sort({ field: 1, test: -1 })`");var n=String(r||1).toLowerCase();if(!(n=f[n]))throw new TypeError("Invalid sort value: [ "+e+", "+r+" ]");t.sort.push([e,n])} -/*! - * Internal helper for update, updateMany, updateOne - */ -function d(t,e,r,n,i,o,s){return t.op=e,c.canMerge(r)&&t.merge(r),n&&t._mergeUpdate(n),a.isObject(i)&&t.setOptions(i),o||s?!t._update||!t.options.overwrite&&0===a.keys(t._update).length?(s&&a.soon(s.bind(null,null,0)),t):(i=t._optionsForExec(),s||(i.safe=!1),r=t._conditions,n=t._updateForExec(),u("update",t._collection.collectionName,r,n,i),s=t._wrapCallback(e,s,{conditions:r,doc:n,options:i}),t._collection[e](r,n,i,a.tick(s)),t):t}["limit","skip","maxScan","batchSize","comment"].forEach(function(t){c.prototype[t]=function(e){return this._validate(t),this.options[t]=e,this}}),c.prototype.maxTime=c.prototype.maxTimeMS=function(t){return this._validate("maxTime"),this.options.maxTimeMS=t,this},c.prototype.snapshot=function(){return this._validate("snapshot"),this.options.snapshot=!arguments.length||!!arguments[0],this},c.prototype.hint=function(){if(0===arguments.length)return this;this._validate("hint");var t=arguments[0];if(a.isObject(t)){var e=this.options.hint||(this.options.hint={});for(var r in t)e[r]=t[r];return this}if("string"==typeof t)return this.options.hint=t,this;throw new TypeError("Invalid hint. "+t)},c.prototype.j=function(t){return this.options.j=t,this},c.prototype.slaveOk=function(t){return this.options.slaveOk=!arguments.length||!!t,this},c.prototype.read=c.prototype.setReadPreference=function(t){return arguments.length>1&&!c.prototype.read.deprecationWarningIssued&&(console.error("Deprecation warning: 'tags' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead."),c.prototype.read.deprecationWarningIssued=!0),this.options.readPreference=a.readPref(t),this},c.prototype.readConcern=c.prototype.r=function(t){return this.options.readConcern=a.readConcern(t),this},c.prototype.tailable=function(){return this._validate("tailable"),this.options.tailable=!arguments.length||!!arguments[0],this},c.prototype.writeConcern=c.prototype.w=function(t){return"object"===(void 0===t?"undefined":n(t))?(void 0!==t.j&&(this.options.j=t.j),void 0!==t.w&&(this.options.w=t.w),void 0!==t.wtimeout&&(this.options.wtimeout=t.wtimeout)):this.options.w="m"===t?"majority":t,this},c.prototype.wtimeout=c.prototype.wTimeout=function(t){return this.options.wtimeout=t,this},c.prototype.merge=function(t){if(!t)return this;if(!c.canMerge(t))throw new TypeError("Invalid argument. Expected instanceof mquery or plain object");return t instanceof c?(t._conditions&&a.merge(this._conditions,t._conditions),t._fields&&(this._fields||(this._fields={}),a.merge(this._fields,t._fields)),t.options&&(this.options||(this.options={}),a.merge(this.options,t.options)),t._update&&(this._update||(this._update={}),a.mergeClone(this._update,t._update)),t._distinct&&(this._distinct=t._distinct),this):(a.merge(this._conditions,t),this)},c.prototype.find=function(t,e){if(this.op="find","function"==typeof t?(e=t,t=void 0):c.canMerge(t)&&this.merge(t),!e)return this;var r=this._conditions,n=this._optionsForExec();return this.$useProjection?n.projection=this._fieldsForExec():n.fields=this._fieldsForExec(),u("find",this._collection.collectionName,r,n),e=this._wrapCallback("find",e,{conditions:r,options:n}),this._collection.find(r,n,a.tick(e)),this},c.prototype.cursor=function(t){if(this.op){if("find"!==this.op)throw new TypeError(".cursor only support .find method")}else this.find(t);var e=this._conditions,r=this._optionsForExec();return this.$useProjection?r.projection=this._fieldsForExec():r.fields=this._fieldsForExec(),u("findCursor",this._collection.collectionName,e,r),this._collection.findCursor(e,r)},c.prototype.findOne=function(t,e){if(this.op="findOne","function"==typeof t?(e=t,t=void 0):c.canMerge(t)&&this.merge(t),!e)return this;var r=this._conditions,n=this._optionsForExec();return this.$useProjection?n.projection=this._fieldsForExec():n.fields=this._fieldsForExec(),u("findOne",this._collection.collectionName,r,n),e=this._wrapCallback("findOne",e,{conditions:r,options:n}),this._collection.findOne(r,n,a.tick(e)),this},c.prototype.count=function(t,e){if(this.op="count",this._validate(),"function"==typeof t?(e=t,t=void 0):c.canMerge(t)&&this.merge(t),!e)return this;var r=this._conditions,n=this._optionsForExec();return u("count",this._collection.collectionName,r,n),e=this._wrapCallback("count",e,{conditions:r,options:n}),this._collection.count(r,n,a.tick(e)),this},c.prototype.distinct=function(t,e,r){if(this.op="distinct",this._validate(),!r){switch(void 0===e?"undefined":n(e)){case"function":r=e,"string"==typeof t&&(e=t,t=void 0);break;case"undefined":case"string":break;default:throw new TypeError("Invalid `field` argument. Must be string or function")}switch(void 0===t?"undefined":n(t)){case"function":r=t,t=e=void 0;break;case"string":e=t,t=void 0}}if("string"==typeof e&&(this._distinct=e),c.canMerge(t)&&this.merge(t),!r)return this;if(!this._distinct)throw new Error("No value for `distinct` has been declared");var i=this._conditions,o=this._optionsForExec();return u("distinct",this._collection.collectionName,i,o),r=this._wrapCallback("distinct",r,{conditions:i,options:o}),this._collection.distinct(this._distinct,i,o,a.tick(r)),this},c.prototype.update=function(t,e,r,i){var o;switch(arguments.length){case 3:"function"==typeof r&&(i=r,r=void 0);break;case 2:"function"==typeof e&&(i=e,e=t,t=void 0);break;case 1:switch(void 0===t?"undefined":n(t)){case"function":i=t,t=r=e=void 0;break;case"boolean":o=t,t=void 0;break;default:e=t,t=r=void 0}}return d(this,"update",t,e,r,o,i)},c.prototype.updateMany=function(t,e,r,i){var o;switch(arguments.length){case 3:"function"==typeof r&&(i=r,r=void 0);break;case 2:"function"==typeof e&&(i=e,e=t,t=void 0);break;case 1:switch(void 0===t?"undefined":n(t)){case"function":i=t,t=r=e=void 0;break;case"boolean":o=t,t=void 0;break;default:e=t,t=r=void 0}}return d(this,"updateMany",t,e,r,o,i)},c.prototype.updateOne=function(t,e,r,i){var o;switch(arguments.length){case 3:"function"==typeof r&&(i=r,r=void 0);break;case 2:"function"==typeof e&&(i=e,e=t,t=void 0);break;case 1:switch(void 0===t?"undefined":n(t)){case"function":i=t,t=r=e=void 0;break;case"boolean":o=t,t=void 0;break;default:e=t,t=r=void 0}}return d(this,"updateOne",t,e,r,o,i)},c.prototype.replaceOne=function(t,e,r,i){var o;switch(arguments.length){case 3:"function"==typeof r&&(i=r,r=void 0);break;case 2:"function"==typeof e&&(i=e,e=t,t=void 0);break;case 1:switch(void 0===t?"undefined":n(t)){case"function":i=t,t=r=e=void 0;break;case"boolean":o=t,t=void 0;break;default:e=t,t=r=void 0}}return this.setOptions({overwrite:!0}),d(this,"replaceOne",t,e,r,o,i)},c.prototype.remove=function(t,e){var r;if(this.op="remove","function"==typeof t?(e=t,t=void 0):c.canMerge(t)?this.merge(t):!0===t&&(r=t,t=void 0),!r&&!e)return this;var n=this._optionsForExec();e||(n.safe=!1);var i=this._conditions;return u("remove",this._collection.collectionName,i,n),e=this._wrapCallback("remove",e,{conditions:i,options:n}),this._collection.remove(i,n,a.tick(e)),this},c.prototype.deleteOne=function(t,e){var r;if(this.op="deleteOne","function"==typeof t?(e=t,t=void 0):c.canMerge(t)?this.merge(t):!0===t&&(r=t,t=void 0),!r&&!e)return this;var n=this._optionsForExec();e||(n.safe=!1),delete n.justOne;var i=this._conditions;return u("deleteOne",this._collection.collectionName,i,n),e=this._wrapCallback("deleteOne",e,{conditions:i,options:n}),this._collection.deleteOne(i,n,a.tick(e)),this},c.prototype.deleteMany=function(t,e){var r;if(this.op="deleteMany","function"==typeof t?(e=t,t=void 0):c.canMerge(t)?this.merge(t):!0===t&&(r=t,t=void 0),!r&&!e)return this;var n=this._optionsForExec();e||(n.safe=!1),delete n.justOne;var i=this._conditions;return u("deleteOne",this._collection.collectionName,i,n),e=this._wrapCallback("deleteOne",e,{conditions:i,options:n}),this._collection.deleteMany(i,n,a.tick(e)),this},c.prototype.findOneAndUpdate=function(t,e,r,n){switch(this.op="findOneAndUpdate",this._validate(),arguments.length){case 3:"function"==typeof r&&(n=r,r={});break;case 2:"function"==typeof e&&(n=e,e=t,t=void 0),r=void 0;break;case 1:"function"==typeof t?(n=t,t=r=e=void 0):(e=t,t=r=void 0)}return c.canMerge(t)&&this.merge(t),e&&this._mergeUpdate(e),r&&this.setOptions(r),n?this._findAndModify("update",n):this},c.prototype.findOneAndRemove=c.prototype.findOneAndDelete=function(t,e,r){return this.op="findOneAndRemove",this._validate(),"function"==typeof e?(r=e,e=void 0):"function"==typeof t&&(r=t,t=void 0),c.canMerge(t)&&this.merge(t),e&&this.setOptions(e),r?this._findAndModify("remove",r):this},c.prototype._findAndModify=function(t,e){o.equal("function",void 0===e?"undefined":n(e));var r,i=this._optionsForExec();if("remove"==t)i.remove=!0;else if("new"in i||(i.new=!0),"upsert"in i||(i.upsert=!1),!(r=this._updateForExec())){if(!i.upsert)return this.findOne(e);r={$set:{}}}null!=this._fieldsForExec()&&(this.$useProjection?i.projection=this._fieldsForExec():i.fields=this._fieldsForExec());var s=this._conditions;return u("findAndModify",this._collection.collectionName,s,r,i),e=this._wrapCallback("findAndModify",e,{conditions:s,doc:r,options:i}),this._collection.findAndModify(s,r,i,a.tick(e)),this},c.prototype._wrapCallback=function(t,e,r){var n=this._traceFunction||c.traceFunction;if(n){r.collectionName=this._collection.collectionName;var i=n&&n.call(null,t,r,this),o=(new Date).getTime();return function(t,r){if(i){var n=(new Date).getTime()-o;i.call(null,t,r,n)}e&&e.apply(null,arguments)}}return e},c.prototype.setTraceFunction=function(t){return this._traceFunction=t,this},c.prototype.exec=function(t,e){switch(void 0===t?"undefined":n(t)){case"function":e=t,t=null;break;case"string":this.op=t}o.ok(this.op,"Missing query type: (find, update, etc)"),"update"!=this.op&&"remove"!=this.op||e||(e=!0);var r=this;if("function"!=typeof e)return new c.Promise(function(t,e){r[r.op](function(r,n){r?e(r):t(n),t=e=null})});this[this.op](e)},c.prototype.thunk=function(){var t=this;return function(e){t.exec(e)}},c.prototype.then=function(t,e){var r=this;return new c.Promise(function(t,e){r.exec(function(r,n){r?e(r):t(n),t=e=null})}).then(t,e)},c.prototype.stream=function(t){if("find"!=this.op)throw new Error("stream() is only available for find");var e=this._conditions,r=this._optionsForExec();return this.$useProjection?r.projection=this._fieldsForExec():r.fields=this._fieldsForExec(),u("stream",this._collection.collectionName,e,r,t),this._collection.findStream(e,r,t)},c.prototype.selected=function(){return!!(this._fields&&Object.keys(this._fields).length>0)},c.prototype.selectedInclusively=function(){if(!this._fields)return!1;var t=Object.keys(this._fields);if(0===t.length)return!1;for(var e=0;e=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(t){}}(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.formatters.j=function(t){try{return JSON.stringify(t)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}},e.enable(o())}).call(this,r(8))},function(t,e,r){"use strict";function n(t){var r;function n(){if(n.enabled){var t=n,i=+new Date,o=i-(r||i);t.diff=o,t.prev=r,t.curr=i,r=i;for(var s=new Array(arguments.length),a=0;a0)return function(t){if((t=String(t)).length>100)return;var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(!e)return;var r=parseFloat(e[1]);switch((e[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*u;case"days":case"day":case"d":return r*a;case"hours":case"hour":case"hrs":case"hr":case"h":return r*s;case"minutes":case"minute":case"mins":case"min":case"m":return r*o;case"seconds":case"second":case"secs":case"sec":case"s":return r*i;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(t);if("number"===r&&!1===isNaN(t))return e.long?function(t){return c(t,a,"day")||c(t,s,"hour")||c(t,o,"minute")||c(t,i,"second")||t+" ms"}(t):function(t){if(t>=a)return Math.round(t/a)+"d";if(t>=s)return Math.round(t/s)+"h";if(t>=o)return Math.round(t/o)+"m";if(t>=i)return Math.round(t/i)+"s";return t+"ms"}(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},function(t,e,r){"use strict";var n=e;n.distinct=function(t){return t._fields&&Object.keys(t._fields).length>0?"field selection and slice":(Object.keys(n.distinct).every(function(r){return!t.options[r]||(e=r,!1)}),e);var e},n.distinct.select=n.distinct.slice=n.distinct.sort=n.distinct.limit=n.distinct.skip=n.distinct.batchSize=n.distinct.comment=n.distinct.maxScan=n.distinct.snapshot=n.distinct.hint=n.distinct.tailable=!0,n.findOneAndUpdate=n.findOneAndRemove=function(t){var e;return Object.keys(n.findOneAndUpdate).every(function(r){return!t.options[r]||(e=r,!1)}),e},n.findOneAndUpdate.limit=n.findOneAndUpdate.skip=n.findOneAndUpdate.batchSize=n.findOneAndUpdate.maxScan=n.findOneAndUpdate.snapshot=n.findOneAndUpdate.hint=n.findOneAndUpdate.tailable=n.findOneAndUpdate.comment=!0,n.count=function(t){return t._fields&&Object.keys(t._fields).length>0?"field selection and slice":(Object.keys(n.count).every(function(r){return!t.options[r]||(e=r,!1)}),e);var e},n.count.slice=n.count.batchSize=n.count.comment=n.count.maxScan=n.count.snapshot=n.count.tailable=!0},function(t,e,r){"use strict";t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,r){"use strict";var n=r(69);if("unknown"==n.type)throw new Error("Unknown environment");t.exports=n.isNode?r(123):(n.isMongo,r(28))},function(t,e,r){"use strict";var n=r(28);function i(t){this.collection=t,this.collectionName=t.collectionName}r(67).inherits(i,n),i.prototype.find=function(t,e,r){this.collection.find(t,e,function(t,e){if(t)return r(t);try{e.toArray(r)}catch(t){r(t)}})},i.prototype.findOne=function(t,e,r){this.collection.findOne(t,e,r)},i.prototype.count=function(t,e,r){this.collection.count(t,e,r)},i.prototype.distinct=function(t,e,r,n){this.collection.distinct(t,e,r,n)},i.prototype.update=function(t,e,r,n){this.collection.update(t,e,r,n)},i.prototype.updateMany=function(t,e,r,n){this.collection.updateMany(t,e,r,n)},i.prototype.updateOne=function(t,e,r,n){this.collection.updateOne(t,e,r,n)},i.prototype.replaceOne=function(t,e,r,n){this.collection.replaceOne(t,e,r,n)},i.prototype.deleteOne=function(t,e,r){this.collection.deleteOne(t,e,r)},i.prototype.deleteMany=function(t,e,r){this.collection.deleteMany(t,e,r)},i.prototype.remove=function(t,e,r){this.collection.remove(t,e,r)},i.prototype.findAndModify=function(t,e,r,n){var i=Array.isArray(r.sort)?r.sort:[];this.collection.findAndModify(t,i,e,r,n)},i.prototype.findStream=function(t,e,r){return this.collection.find(t,e).stream(r)},i.prototype.findCursor=function(t,e){return this.collection.find(t,e)},t.exports=i},function(t,e,r){"use strict";(function(r,n,i){var o,s,a,u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};!function(r){"object"==u(e)&&void 0!==t?t.exports=r():(s=[],void 0===(a="function"==typeof(o=r)?o.apply(e,s):o)||(t.exports=a))}(function(){var t,e,o;return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof _dereq_&&_dereq_;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(t){var r=e[s][1][t];return i(r||t)},l,l.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0;){var e=t.shift();if("function"==typeof e){var r=t.shift(),n=t.shift();e.call(r,n)}else e._settlePromises()}},u.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},u.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},u.prototype._reset=function(){this._isTickUsed=!1},e.exports=u,e.exports.firstLineError=i},{"./queue":26,"./schedule":29,"./util":36}],3:[function(t,e,r){e.exports=function(t,e,r,n){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)},u=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=n.propagateFromFunction(),t.prototype._boundValue=n.boundValueFunction());var c=r(o),l=new t(e);l._propagateFrom(this,1);var f=this._target();if(l._setBoundTo(c),c instanceof t){var h={promiseRejectionQueued:!1,promise:l,target:f,bindingPromise:c};f._then(e,s,void 0,l,h),c._then(a,u,void 0,l,h),l._setOnCancel(c)}else l._resolveCallback(f);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,r){return t.resolve(r).bind(e)}}},{}],4:[function(t,e,r){var n;"undefined"!=typeof Promise&&(n=Promise);var i=t("./promise")();i.noConflict=function(){try{Promise===i&&(Promise=n)}catch(t){}return i},e.exports=i},{"./promise":22}],5:[function(t,e,r){var n=Object.create;if(n){var i=n(null),o=n(null);i[" size"]=o[" size"]=0}e.exports=function(e){var r=t("./util"),n=r.canEvaluate;r.isIdentifier;function i(t){return function(t,n){var i;if(null!=t&&(i=t[n]),"function"!=typeof i){var o="Object "+r.classString(t)+" has no method '"+r.toString(n)+"'";throw new e.TypeError(o)}return i}(t,this.pop()).apply(t,this)}function o(t){return t[this]}function s(t){var e=+this;return e<0&&(e=Math.max(0,e+t.length)),t[e]}e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(i,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e;if("number"==typeof t)e=s;else if(n){var r=(void 0)(t);e=null!==r?r:o}else e=o;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e,r){e.exports=function(e,r,n,i){var o=t("./util"),s=o.tryCatch,a=o.errorObj,u=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 r=t._cancellationParent;if(null==r||!r._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=r}},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))},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),u.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 r=0;r=0)return r[t]}return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},n.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,r.push(this._trace))},n.prototype._popContext=function(){if(void 0!==this._trace){var t=r.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},n.CapturedTrace=null,n.create=function(){if(e)return new n},n.deactivateLongStackTraces=function(){},n.activateLongStackTraces=function(){var r=t.prototype._pushContext,o=t.prototype._popContext,s=t._peekContext,a=t.prototype._peekContext,u=t.prototype._promiseCreated;n.deactivateLongStackTraces=function(){t.prototype._pushContext=r,t.prototype._popContext=o,t._peekContext=s,t.prototype._peekContext=a,t.prototype._promiseCreated=u,e=!1},e=!0,t.prototype._pushContext=n.prototype._pushContext,t.prototype._popContext=n.prototype._popContext,t._peekContext=t.prototype._peekContext=i,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},n}},{}],9:[function(t,e,n){e.exports=function(e,n){var i,o,s,a=e._getDomain,c=e._async,l=t("./errors").Warning,f=t("./util"),h=f.canAttachTrace,p=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,d=/\((?:timers\.js):\d+:\d+\)/,y=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,v=null,_=null,m=!1,g=!(0==f.env("BLUEBIRD_DEBUG")),b=!(0==f.env("BLUEBIRD_WARNINGS")||!g&&!f.env("BLUEBIRD_WARNINGS")),w=!(0==f.env("BLUEBIRD_LONG_STACK_TRACES")||!g&&!f.env("BLUEBIRD_LONG_STACK_TRACES")),O=0!=f.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(b||!!f.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){if(0==(524288&this._bitField)){this._setRejectionIsUnhandled();var t=this;setTimeout(function(){t._notifyUnhandledRejection()},1)}},e.prototype._notifyUnhandledRejectionIsHandled=function(){W("rejectionHandled",i,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!=(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),W("unhandledRejection",o,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},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,r){return L(t,e,r||this)},e.onPossiblyUnhandledRejection=function(t){var e=a();o="function"==typeof t?null===e?t:f.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=a();i="function"==typeof t?null===e?t:f.domainBind(e,t):void 0};var S=function(){};e.longStackTraces=function(){if(c.haveItemsQueued()&&!X.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!X.longStackTraces&&Y()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;X.longStackTraces=!0,S=function(){if(c.haveItemsQueued()&&!X.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,n.deactivateLongStackTraces(),c.enableTrampoline(),X.longStackTraces=!1},e.prototype._captureStackTrace=F,e.prototype._attachExtraTrace=I,n.activateLongStackTraces(),c.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return X.longStackTraces&&Y()};var E=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return f.global.dispatchEvent(t),function(t,e){var r=new CustomEvent(t.toLowerCase(),{detail:e,cancelable:!0});return!f.global.dispatchEvent(r)}}if("function"==typeof Event){t=new Event("CustomEvent");return f.global.dispatchEvent(t),function(t,e){var r=new Event(t.toLowerCase(),{cancelable:!0});return r.detail=e,!f.global.dispatchEvent(r)}}return(t=document.createEvent("CustomEvent")).initCustomEvent("testingtheevent",!1,!0,{}),f.global.dispatchEvent(t),function(t,e){var r=document.createEvent("CustomEvent");return r.initCustomEvent(t.toLowerCase(),!1,!0,e),!f.global.dispatchEvent(r)}}catch(t){}return function(){return!1}}(),A=f.isNode?function(){return r.emit.apply(r,arguments)}:f.global?function(t){var e="on"+t.toLowerCase(),r=f.global[e];return!!r&&(r.apply(f.global,[].slice.call(arguments,1)),!0)}:function(){return!1};function $(t,e){return{promise:e}}var j={promiseCreated:$,promiseFulfilled:$,promiseRejected:$,promiseResolved:$,promiseCancelled:$,promiseChained:function(t,e,r){return{promise:e,child:r}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,r){return{reason:e,promise:r}},rejectionHandled:$},x=function(t){var e=!1;try{e=A.apply(null,arguments)}catch(t){c.throwLater(t),e=!0}var r=!1;try{r=E(t,j[t].apply(null,arguments))}catch(t){c.throwLater(t),r=!0}return r||e};function N(){return!1}function P(t,e,r){var n=this;try{t(e,r,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+f.toString(t));n._attachCancellationCallback(t)})}catch(t){return t}}function k(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?f.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function T(){return this._onCancelField}function B(t){this._onCancelField=t}function C(){this._cancellationParent=void 0,this._onCancelField=void 0}function D(t,e){if(0!=(1&e)){this._cancellationParent=t;var r=t._branchesRemainingToCancel;void 0===r&&(r=0),t._branchesRemainingToCancel=r+1}0!=(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}e.config=function(t){if("longStackTraces"in(t=Object(t))&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&S()),"warnings"in t){var r=t.warnings;X.warnings=!!r,O=X.warnings,f.isObject(r)&&"wForgottenReturn"in r&&(O=!!r.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!X.cancellation){if(c.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=C,e.prototype._propagateFrom=D,e.prototype._onCancel=T,e.prototype._setOnCancel=B,e.prototype._attachCancellationCallback=k,e.prototype._execute=P,M=D,X.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!X.monitoring?(X.monitoring=!0,e.prototype._fireEvent=x):!t.monitoring&&X.monitoring&&(X.monitoring=!1,e.prototype._fireEvent=N)),e},e.prototype._fireEvent=N,e.prototype._execute=function(t,e,r){try{t(e,r)}catch(t){return t}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var M=function(t,e){0!=(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)};function R(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function F(){this._trace=new J(this._peekContext())}function I(t,e){if(h(t)){var r=this._trace;if(void 0!==r&&e&&(r=r._parent),void 0!==r)r.attachExtraTrace(t);else if(!t.__stackCleaned__){var n=V(t);f.notEnumerableProp(t,"stack",n.message+"\n"+n.stack.join("\n")),f.notEnumerableProp(t,"__stackCleaned__",!0)}}}function L(t,r,n){if(X.warnings){var i,o=new l(t);if(r)n._attachExtraTrace(o);else if(X.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var s=V(o);o.stack=s.message+"\n"+s.stack.join("\n")}x("warning",o)||q(o,"",!0)}}function U(t){for(var e=[],r=0;r0?function(t){for(var e=t.stack.replace(/\s+$/g,"").split("\n"),r=0;r0&&"SyntaxError"!=t.name&&(e=e.slice(r)),e}(t):[" (No stack trace)"],{message:r,stack:"SyntaxError"==t.name?e:U(e)}}function q(t,e,r){if("undefined"!=typeof console){var n;if(f.isObject(t)){var i=t.stack;n=e+_(i,t)}else n=e+String(t);"function"==typeof s?s(n,r):"function"!=typeof console.log&&"object"!==u(console.log)||console.log(n)}}function W(t,e,r,n){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(n):e(r,n))}catch(t){c.throwLater(t)}"unhandledRejection"===t?x(t,r,n)||i||q(r,"Unhandled rejection "):x(t,n)}function H(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():f.toString(t);if(/\[object [a-zA-Z0-9$_]+\]/.test(e))try{e=JSON.stringify(t)}catch(t){}0===e.length&&(e="(empty array)")}return"(<"+function(t){if(t.length<41)return t;return t.substr(0,38)+"..."}(e)+">, no stack trace)"}function Y(){return"function"==typeof G}var z=function(){return!1},K=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function Q(t){var e=t.match(K);if(e)return{fileName:e[1],line:parseInt(e[2],10)}}function J(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);G(this,J),e>32&&this.uncycle()}f.inherits(J,Error),n.CapturedTrace=J,J.prototype.uncycle=function(){var t=this._length;if(!(t<2)){for(var e=[],r={},n=0,i=this;void 0!==i;++n)e.push(i),i=i._parent;for(n=(t=this._length=n)-1;n>=0;--n){var o=e[n].stack;void 0===r[o]&&(r[o]=n)}for(n=0;n0&&(e[s-1]._parent=void 0,e[s-1]._length=1),e[n]._parent=void 0,e[n]._length=1;var a=n>0?e[n-1]:this;s=0;--c)e[c]._length=u,u++;return}}}},J.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=V(t),r=e.message,n=[e.stack],i=this;void 0!==i;)n.push(U(i.stack.split("\n"))),i=i._parent;!function(t){for(var e=t[0],r=1;r=0;--a)if(n[a]===o){s=a;break}for(a=s;a>=0;--a){var u=n[a];if(e[i]!==u)break;e.pop(),i--}e=n}}(n),function(t){for(var e=0;e=0)return v=/@/,_=e,m=!0,function(t){t.stack=(new Error).stack};try{throw new Error}catch(t){n="stack"in t}return"stack"in i||!n||"number"!=typeof Error.stackTraceLimit?(_=function(t,e){return"string"==typeof t?t:"object"!==(void 0===e?"undefined":u(e))&&"function"!=typeof e||void 0===e.name||void 0===e.message?H(e):e.toString()},null):(v=t,_=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}();"undefined"!=typeof console&&void 0!==console.warn&&(s=function(t){console.warn(t)},f.isNode&&r.stderr.isTTY?s=function(t,e){var r=e?"":"";console.warn(r+t+"\n")}:f.isNode||"string"!=typeof(new Error).stack||(s=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var X={warnings:b,longStackTraces:!1,cancellation:!1,monitoring:!1};return w&&e.longStackTraces(),{longStackTraces:function(){return X.longStackTraces},warnings:function(){return X.warnings},cancellation:function(){return X.cancellation},monitoring:function(){return X.monitoring},propagateFromFunction:function(){return M},boundValueFunction:function(){return R},checkForgottenReturns:function(t,e,r,n,i){if(void 0===t&&null!==e&&O){if(void 0!==i&&i._returnedNonUndefined())return;if(0==(65535&n._bitField))return;r&&(r+=" ");var o="",s="";if(e._trace){for(var a=e._trace.stack.split("\n"),u=U(a),c=u.length-1;c>=0;--c){var l=u[c];if(!d.test(l)){var f=l.match(y);f&&(o="at "+f[1]+":"+f[2]+":"+f[3]+" ");break}}if(u.length>0){var h=u[0];for(c=0;c0&&(s="\n"+a[c-1]);break}}}var p="a promise was created in a "+r+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+s;n._warn(p,!0,e)}},setBounds:function(t,e){if(Y()){for(var r,n,i=t.stack.split("\n"),o=e.stack.split("\n"),s=-1,a=-1,u=0;u=a||(z=function(t){if(p.test(t))return!0;var e=Q(t);return!!(e&&e.fileName===r&&s<=e.line&&e.line<=a)})}},warn:L,deprecated:function(t,e){var r=t+" is deprecated and will be removed in a future version.";return e&&(r+=" Use "+e+" instead."),L(r)},CapturedTrace:J,fireDomEvent:E,fireGlobalEvent:A}}},{"./errors":12,"./util":36}],10:[function(t,e,r){e.exports=function(t){function e(){return this.value}function r(){throw this.reason}t.prototype.return=t.prototype.thenReturn=function(r){return r instanceof t&&r.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:r},void 0)},t.prototype.throw=t.prototype.thenThrow=function(t){return this._then(r,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,r,void 0,{reason:t},void 0);var e=arguments[1];return this.caught(t,function(){throw e})},t.prototype.catchReturn=function(r){if(arguments.length<=1)return r instanceof t&&r.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:r},void 0);var n=arguments[1];n instanceof t&&n.suppressUnhandledRejections();return this.caught(r,function(){return n})}}},{}],11:[function(t,e,r){e.exports=function(t,e){var r=t.reduce,n=t.all;function i(){return n(this)}t.prototype.each=function(t){return r(this,t,e,0)._then(i,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return r(this,t,e,e)},t.each=function(t,n){return r(t,n,e,0)._then(i,void 0,void 0,t,void 0)},t.mapSeries=function(t,n){return r(t,n,e,e)}}},{}],12:[function(t,e,r){var n,i,o=t("./es5"),s=o.freeze,a=t("./util"),u=a.inherits,c=a.notEnumerableProp;function l(t,e){function r(n){if(!(this instanceof r))return new r(n);c(this,"message","string"==typeof n?n:e),c(this,"name",t),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this)}return u(r,Error),r}var f=l("Warning","warning"),h=l("CancellationError","cancellation error"),p=l("TimeoutError","timeout error"),d=l("AggregateError","aggregate error");try{n=TypeError,i=RangeError}catch(t){n=l("TypeError","type error"),i=l("RangeError","range error")}for(var y="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),v=0;v1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0)}function f(){return p.call(this,this.promise._target()._settledValue())}function h(t){if(!l(this,t))return s.e=t,s}function p(t){var i=this.promise,a=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?a.call(i._boundValue()):a.call(i._boundValue(),t);if(u===n)return u;if(void 0!==u){i._setReturnedNonUndefined();var p=r(u,i);if(p instanceof e){if(null!=this.cancelPromise){if(p._isCancelled()){var d=new o("late cancellation observer");return i._attachExtraTrace(d),s.e=d,s}p.isPending()&&p._attachCancellationCallback(new c(this))}return p._then(f,h,void 0,this,void 0)}}}return i.isRejected()?(l(this),s.e=t,s):(l(this),t)}return u.prototype.isFinallyHandler=function(){return 0===this.type},c.prototype._resultCancelled=function(){l(this.finallyHandler)},e.prototype._passThrough=function(t,e,r,n){return"function"!=typeof t?this.then():this._then(r,n,void 0,new u(this,e,t),void 0)},e.prototype.lastly=e.prototype.finally=function(t){return this._passThrough(t,0,p,p)},e.prototype.tap=function(t){return this._passThrough(t,1,p)},e.prototype.tapCatch=function(t){var r=arguments.length;if(1===r)return this._passThrough(t,1,void 0,p);var n,o=new Array(r-1),s=0;for(n=0;n0&&"function"==typeof arguments[e]&&(t=arguments[e]);var n=[].slice.call(arguments);t&&n.pop();var i=new r(n).promise();return void 0!==t?i.spread(t):i}}},{"./util":36}],18:[function(t,e,r){e.exports=function(e,r,n,i,o,s){var a=e._getDomain,c=t("./util"),l=c.tryCatch,f=c.errorObj,h=e._async;function p(t,e,r,n){this.constructor$(t),this._promise._captureStackTrace();var i=a();this._callback=null===i?e:c.domainBind(i,e),this._preservedValues=n===o?new Array(this.length()):null,this._limit=r,this._inFlight=0,this._queue=[],h.invoke(this._asyncInit,this,void 0)}function d(t,r,i,o){if("function"!=typeof r)return n("expecting a function but got "+c.classString(r));var s=0;if(void 0!==i){if("object"!==(void 0===i?"undefined":u(i))||null===i)return e.reject(new TypeError("options argument must be an object but it is "+c.classString(i)));if("number"!=typeof i.concurrency)return e.reject(new TypeError("'concurrency' must be a number but it is "+c.classString(i.concurrency)));s=i.concurrency}return new p(t,r,s="number"==typeof s&&isFinite(s)&&s>=1?s:0,o).promise()}c.inherits(p,r),p.prototype._asyncInit=function(){this._init$(void 0,-2)},p.prototype._init=function(){},p.prototype._promiseFulfilled=function(t,r){var n=this._values,o=this.length(),a=this._preservedValues,u=this._limit;if(r<0){if(n[r=-1*r-1]=t,u>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(u>=1&&this._inFlight>=u)return n[r]=t,this._queue.push(r),!1;null!==a&&(a[r]=t);var c=this._promise,h=this._callback,p=c._boundValue();c._pushContext();var d=l(h).call(p,t,r,o),y=c._popContext();if(s.checkForgottenReturns(d,y,null!==a?"Promise.filter":"Promise.map",c),d===f)return this._reject(d.e),!0;var v=i(d,this._promise);if(v instanceof e){var _=(v=v._target())._bitField;if(0==(50397184&_))return u>=1&&this._inFlight++,n[r]=v,v._proxy(this,-1*(r+1)),!1;if(0==(33554432&_))return 0!=(16777216&_)?(this._reject(v._reason()),!0):(this._cancel(),!0);d=v._value()}n[r]=d}return++this._totalResolved>=o&&(null!==a?this._filter(n,a):this._resolve(n),!0)},p.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,r=this._values;t.length>0&&this._inFlight1){o.deprecated("calling Promise.try with more than 1 argument");var c=arguments[1],l=arguments[2];n=s.isArray(c)?a(t).apply(l,c):a(t).call(l,c)}else n=a(t)();var f=u._popContext();return o.checkForgottenReturns(n,f,"Promise.try",u),u._resolveFromSyncValue(n),u},e.prototype._resolveFromSyncValue=function(t){t===s.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e,r){var n=t("./util"),i=n.maybeWrapAsError,o=t("./errors").OperationalError,s=t("./es5");var a=/^(?:name|message|stack|cause)$/;function u(t){var e;if(function(t){return t instanceof Error&&s.getPrototypeOf(t)===Error.prototype}(t)){(e=new o(t)).name=t.name,e.message=t.message,e.stack=t.stack;for(var r=s.keys(t),i=0;i1){var r,n=new Array(e-1),i=0;for(r=0;r0&&"function"!=typeof t&&"function"!=typeof e){var r=".then() only accepts functions but was passed: "+c.classString(t);arguments.length>1&&(r+=", "+c.classString(e)),this._warn(r)}return this._then(t,e,void 0,void 0,void 0)},N.prototype.done=function(t,e){this._then(t,e,void 0,void 0,void 0)._setIsFinal()},N.prototype.spread=function(t){return"function"!=typeof t?o("expecting a function but got "+c.classString(t)):this.all()._then(t,void 0,void 0,_,void 0)},N.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},N.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new b(this).promise()},N.prototype.error=function(t){return this.caught(c.originatesFromRejection,t)},N.getNewLibraryCopy=e.exports,N.is=function(t){return t instanceof N},N.fromNode=N.fromCallback=function(t){var e=new N(v);e._captureStackTrace();var r=arguments.length>1&&!!Object(arguments[1]).multiArgs,n=x(t)($(e,r));return n===j&&e._rejectCallback(n.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},N.all=function(t){return new b(t).promise()},N.cast=function(t){var e=g(t);return e instanceof N||((e=new N(v))._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},N.resolve=N.fulfilled=N.cast,N.reject=N.rejected=function(t){var e=new N(v);return e._captureStackTrace(),e._rejectCallback(t,!0),e},N.setScheduler=function(t){if("function"!=typeof t)throw new d("expecting a function but got "+c.classString(t));return h.setScheduler(t)},N.prototype._then=function(t,e,r,n,i){var o=void 0!==i,s=o?i:new N(v),u=this._target(),l=u._bitField;o||(s._propagateFrom(this,3),s._captureStackTrace(),void 0===n&&0!=(2097152&this._bitField)&&(n=0!=(50397184&l)?this._boundValue():u===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,s));var f=a();if(0!=(50397184&l)){var p,d,_=u._settlePromiseCtx;0!=(33554432&l)?(d=u._rejectionHandler0,p=t):0!=(16777216&l)?(d=u._fulfillmentHandler0,p=e,u._unsetRejectionIsUnhandled()):(_=u._settlePromiseLateCancellationObserver,d=new y("late cancellation observer"),u._attachExtraTrace(d),p=e),h.invoke(_,u,{handler:null===f?p:"function"==typeof p&&c.domainBind(f,p),promise:s,receiver:n,value:d})}else u._addCallbacks(t,e,s,n,f);return s},N.prototype._length=function(){return 65535&this._bitField},N.prototype._isFateSealed=function(){return 0!=(117506048&this._bitField)},N.prototype._isFollowing=function(){return 67108864==(67108864&this._bitField)},N.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},N.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},N.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},N.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},N.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},N.prototype._isFinal=function(){return(4194304&this._bitField)>0},N.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},N.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},N.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},N.prototype._setAsyncGuaranteed=function(){h.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},N.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];if(e!==u)return void 0===e&&this._isBound()?this._boundValue():e},N.prototype._promiseAt=function(t){return this[4*t-4+2]},N.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},N.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},N.prototype._boundValue=function(){},N.prototype._migrateCallback0=function(t){t._bitField;var e=t._fulfillmentHandler0,r=t._rejectionHandler0,n=t._promise0,i=t._receiverAt(0);void 0===i&&(i=u),this._addCallbacks(e,r,n,i,null)},N.prototype._migrateCallbackAt=function(t,e){var r=t._fulfillmentHandlerAt(e),n=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=u),this._addCallbacks(r,n,i,o,null)},N.prototype._addCallbacks=function(t,e,r,n,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=r,this._receiver0=n,"function"==typeof t&&(this._fulfillmentHandler0=null===i?t:c.domainBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:c.domainBind(i,e));else{var s=4*o-4;this[s+2]=r,this[s+3]=n,"function"==typeof t&&(this[s+0]=null===i?t:c.domainBind(i,t)),"function"==typeof e&&(this[s+1]=null===i?e:c.domainBind(i,e))}return this._setLength(o+1),o},N.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},N.prototype._resolveCallback=function(t,e){if(0==(117506048&this._bitField)){if(t===this)return this._rejectCallback(n(),!1);var r=g(t,this);if(!(r instanceof N))return this._fulfill(t);e&&this._propagateFrom(r,2);var i=r._target();if(i!==this){var o=i._bitField;if(0==(50397184&o)){var s=this._length();s>0&&i._migrateCallback0(this);for(var a=1;a>>16)){if(t===this){var r=n();return this._attachExtraTrace(r),this._reject(r)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!=(134217728&e)?this._settlePromises():h.settlePromises(this))}},N.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(this._setRejected(),this._fulfillmentHandler0=t,this._isFinal())return h.fatalError(t,c.isNode);(65535&e)>0?h.settlePromises(this):this._ensurePossibleRejectionHandled()}},N.prototype._fulfillPromises=function(t,e){for(var r=1;r0){if(0!=(16842752&t)){var r=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,r,t),this._rejectPromises(e,r)}else{var n=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,n,t),this._fulfillPromises(e,n)}this._setLength(0)}this._clearCancellationData()},N.prototype._settledValue=function(){var t=this._bitField;return 0!=(33554432&t)?this._rejectionHandler0:0!=(16777216&t)?this._fulfillmentHandler0:void 0},N.defer=N.pending=function(){return S.deprecated("Promise.defer","new Promise"),{promise:new N(v),resolve:P,reject:k}},c.notEnumerableProp(N,"_makeSelfResolutionError",n),t("./method")(N,v,g,o,S),t("./bind")(N,v,g,S),t("./cancel")(N,b,o,S),t("./direct_resolve")(N),t("./synchronous_inspection")(N),t("./join")(N,b,g,v,h,a),N.Promise=N,N.version="3.5.1",t("./map.js")(N,b,o,g,v,S),t("./call_get.js")(N),t("./using.js")(N,o,g,O,v,S),t("./timers.js")(N,v,S),t("./generators.js")(N,o,v,g,s,S),t("./nodeify.js")(N),t("./promisify.js")(N,v),t("./props.js")(N,b,g,o),t("./race.js")(N,v,g,o),t("./reduce.js")(N,b,o,g,v,S),t("./settle.js")(N,b,S),t("./some.js")(N,b,o),t("./filter.js")(N,v),t("./each.js")(N,v),t("./any.js")(N),c.toFastProperties(N),c.toFastProperties(N.prototype),T({a:1}),T({b:2}),T({c:3}),T(1),T(function(){}),T(void 0),T(!1),T(new N(v)),S.setBounds(f.firstLineError,c.lastLineError),N}},{"./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}],23:[function(t,e,r){e.exports=function(e,r,n,i,o){var s=t("./util");s.isArray;function a(t){var n=this._promise=new e(r);t instanceof e&&n._propagateFrom(t,3),n._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return s.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function t(r,o){var a=n(this._values,this._promise);if(a instanceof e){var u=(a=a._target())._bitField;if(this._values=a,0==(50397184&u))return this._promise._setAsyncGuaranteed(),a._then(t,this._reject,void 0,this,o);if(0==(33554432&u))return 0!=(16777216&u)?this._reject(a._reason()):this._cancel();a=a._value()}if(null!==(a=s.asArray(a)))0!==a.length?this._iterate(a):-5===o?this._resolveEmptyArray():this._resolve(function(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}(o));else{var c=i("expecting an array or an iterable object but got "+s.classString(a)).reason();this._promise._rejectCallback(c,!1)}},a.prototype._iterate=function(t){var r=this.getActualLength(t.length);this._length=r,this._values=this.shouldCopyValues()?new Array(r):this._values;for(var i=this._promise,o=!1,s=null,a=0;a=this._length&&(this._resolve(this._values),!0)},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 r=0;r=this._length){var r;if(this._isMap)r=function(t){for(var e=new o,r=t.length/2|0,n=0;n>1},e.prototype.props=function(){return f(this)},e.props=function(t){return f(t)}}},{"./es5":13,"./util":36}],26:[function(t,e,r){function n(t){this._capacity=t,this._length=0,this._front=0}n.prototype._willBeOverCapacity=function(t){return this._capacity=this._length&&(this._resolve(this._values),!0)},o.prototype._promiseFulfilled=function(t,e){var r=new i;return r._bitField=33554432,r._settledValueField=t,this._promiseResolved(e,r)},o.prototype._promiseRejected=function(t,e){var r=new i;return r._bitField=16777216,r._settledValueField=t,this._promiseResolved(e,r)},e.settle=function(t){return n.deprecated(".settle()",".reflect()"),new o(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e,r){e.exports=function(e,r,n){var i=t("./util"),o=t("./errors").RangeError,s=t("./errors").AggregateError,a=i.isArray,u={};function c(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function l(t,e){if((0|e)!==e||e<0)return n("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var r=new c(t),i=r.promise();return r.setHowMany(e),r.init(),i}i.inherits(c,r),c.prototype._init=function(){if(this._initialized)if(0!==this._howMany){this._init$(void 0,-5);var t=a(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}else this._resolve([])},c.prototype.init=function(){this._initialized=!0,this._init()},c.prototype.setUnwrap=function(){this._unwrap=!0},c.prototype.howMany=function(){return this._howMany},c.prototype.setHowMany=function(t){this._howMany=t},c.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)},c.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},c.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(u),this._checkOutcome())},c.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new s,e=this.length();e0?this._reject(t):this._cancel(),!0}return!1},c.prototype._fulfilled=function(){return this._totalResolved},c.prototype._rejected=function(){return this._values.length-this.length()},c.prototype._addRejected=function(t){this._values.push(t)},c.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},c.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},c.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new o(e)},c.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return l(t,e)},e.prototype.some=function(t){return l(this,t)},e._SomePromiseArray=c}},{"./errors":12,"./util":36}],32:[function(t,e,r){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 r=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()},n=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 r.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),n.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,r){e.exports=function(e,r){var n=t("./util"),i=n.errorObj,o=n.isObject;var s={}.hasOwnProperty;return function(t,a){if(o(t)){if(t instanceof e)return t;var u=function(t){try{return function(t){return t.then}(t)}catch(t){return i.e=t,i}}(t);if(u===i){a&&a._pushContext();var c=e.reject(u.e);return a&&a._popContext(),c}if("function"==typeof u)return function(t){try{return s.call(t,"_promise0")}catch(t){return!1}}(t)?(c=new e(r),t._then(c._fulfill,c._reject,void 0,c,null),c):function(t,o,s){var a=new e(r),u=a;s&&s._pushContext(),a._captureStackTrace(),s&&s._popContext();var c=!0,l=n.tryCatch(o).call(t,function(t){a&&(a._resolveCallback(t),a=null)},function(t){a&&(a._rejectCallback(t,c,!0),a=null)});return c=!1,a&&l===i&&(a._rejectCallback(l.e,!0,!0),a=null),u}(t,u,a)}return t}}},{"./util":36}],34:[function(t,e,r){e.exports=function(e,r,n){var i=t("./util"),o=e.TimeoutError;function s(t){this.handle=t}s.prototype._resultCancelled=function(){clearTimeout(this.handle)};var a=function(t){return u(+this).thenReturn(t)},u=e.delay=function(t,i){var o,u;return void 0!==i?(o=e.resolve(i)._then(a,null,null,t,void 0),n.cancellation()&&i instanceof e&&o._setOnCancel(i)):(o=new e(r),u=setTimeout(function(){o._fulfill()},+t),n.cancellation()&&o._setOnCancel(new s(u)),o._captureStackTrace()),o._setAsyncGuaranteed(),o};e.prototype.delay=function(t){return u(t,this)};function c(t){return clearTimeout(this.handle),t}function l(t){throw clearTimeout(this.handle),t}e.prototype.timeout=function(t,e){var r,a;t=+t;var u=new s(setTimeout(function(){r.isPending()&&function(t,e,r){var n;n="string"!=typeof e?e instanceof Error?e:new o("operation timed out"):new o(e),i.markAsOriginatingFromRejection(n),t._attachExtraTrace(n),t._reject(n),null!=r&&r.cancel()}(r,e,a)},t));return n.cancellation()?(a=this.then(),(r=a._then(c,l,void 0,u,void 0))._setOnCancel(u)):r=this._then(c,l,void 0,u,void 0),r}}},{"./util":36}],35:[function(t,e,r){e.exports=function(e,r,n,i,o,s){var a=t("./util"),u=t("./errors").TypeError,c=t("./util").inherits,l=a.errorObj,f=a.tryCatch,h={};function p(t){setTimeout(function(){throw t},0)}function d(t,r){var i=0,s=t.length,a=new e(o);return function o(){if(i>=s)return a._fulfill();var u=function(t){var e=n(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}(t[i++]);if(u instanceof e&&u._isDisposable()){try{u=n(u._getDisposer().tryDispose(r),t.promise)}catch(t){return p(t)}if(u instanceof e)return u._then(o,p,null,null,null)}o()}(),a}function y(t,e,r){this._data=t,this._promise=e,this._context=r}function v(t,e,r){this.constructor$(t,e,r)}function _(t){return y.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function m(t){this.length=t,this.promise=null,this[t-1]=null}y.prototype.data=function(){return this._data},y.prototype.promise=function(){return this._promise},y.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():h},y.prototype.tryDispose=function(t){var e=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=e!==h?this.doDispose(e,t):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},y.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},c(v,y),v.prototype.doDispose=function(t,e){return this.data().call(t,t,e)},m.prototype._resultCancelled=function(){for(var t=this.length,r=0;r0},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 v(t,this,i());throw new u}}},{"./errors":12,"./util":36}],36:[function(t,e,i){var o=t("./es5"),s="undefined"==typeof navigator,a={e:{}},c,l="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==n?n:void 0!==this?this:null;function f(){try{var t=c;return c=null,t.apply(this,arguments)}catch(t){return a.e=t,a}}function h(t){return c=t,f}var p=function(t,e){var r={}.hasOwnProperty;function n(){for(var n in this.constructor=t,this.constructor$=e,e.prototype)r.call(e.prototype,n)&&"$"!==n.charAt(n.length-1)&&(this[n+"$"]=e.prototype[n])}return n.prototype=e.prototype,t.prototype=new n,t.prototype};function d(t){return null==t||!0===t||!1===t||"string"==typeof t||"number"==typeof t}function y(t){return"function"==typeof t||"object"===(void 0===t?"undefined":u(t))&&null!==t}function v(t){return d(t)?new Error(x(t)):t}function _(t,e){var r,n=t.length,i=new Array(n+1);for(r=0;r1,n=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=O.test(t+"")&&o.names(t).length>0;if(r||n||i)return!0}return!1}catch(t){return!1}}function E(t){function e(){}e.prototype=t;for(var r=8;r--;)new e;return t}var A=/^[a-z$_][a-z$_0-9]*$/i;function $(t){return A.test(t)}function j(t,e,r){for(var n=new Array(t),i=0;i10||t[0]>0}(),q.isNode&&q.toFastProperties(r);try{throw new Error}catch(t){q.lastLineError=t}e.exports=q},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(this,r(8),r(11),r(68).setImmediate)},function(t,e,r){"use strict";var n=t.exports={};n.DocumentNotFoundError=null,n.general={},n.general.default="Validator failed for path `{PATH}` with value `{VALUE}`",n.general.required="Path `{PATH}` is required.",n.Number={},n.Number.min="Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).",n.Number.max="Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).",n.Number.enum="`{VALUE}` is not a valid enum value for path `{PATH}`.",n.Date={},n.Date.min="Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).",n.Date.max="Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).",n.String={},n.String.enum="`{VALUE}` is not a valid enum value for path `{PATH}`.",n.String.match="Path `{PATH}` is invalid ({VALUE}).",n.String.minlength="Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).",n.String.maxlength="Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH})."},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(4),i=r(3); -/*! - * OverwriteModel Error constructor. - * - * @inherits MongooseError - */ -function o(t,e,r,o){var s=void 0,a=n.messages;s=null!=a.DocumentNotFoundError?"function"==typeof a.DocumentNotFoundError?a.DocumentNotFoundError(t,e):a.DocumentNotFoundError:'No document found for query "'+i.inspect(t)+'" on model "'+e+'"',n.call(this,s),this.name="DocumentNotFoundError",this.result=o,this.numAffected=r,Error.captureStackTrace?Error.captureStackTrace(this):this.stack=(new Error).stack,this.filter=t,this.query=t} -/*! - * Inherits from MongooseError. - */o.prototype=Object.create(n.prototype),o.prototype.constructor=n, -/*! - * exports - */ -t.exports=o},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(4);function i(t,e,r){var i=r.join(", ");n.call(this,'No matching document found for id "'+t._id+'" version '+e+' modifiedPaths "'+i+'"'),this.name="VersionError",this.version=e,this.modifiedPaths=r} -/*! - * Inherits from MongooseError. - */i.prototype=Object.create(n.prototype),i.prototype.constructor=n, -/*! - * exports - */ -t.exports=i},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(4);function i(t){n.call(this,"Can't save() the same doc multiple times in parallel. Document: "+t._id),this.name="ParallelSaveError"} -/*! - * Inherits from MongooseError. - */i.prototype=Object.create(n.prototype),i.prototype.constructor=n, -/*! - * exports - */ -t.exports=i},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(4); -/*! - * OverwriteModel Error constructor. - * - * @inherits MongooseError - */function i(t){n.call(this,"Cannot overwrite `"+t+"` model once compiled."),this.name="OverwriteModelError",Error.captureStackTrace?Error.captureStackTrace(this):this.stack=(new Error).stack} -/*! - * Inherits from MongooseError. - */i.prototype=Object.create(n.prototype),i.prototype.constructor=n, -/*! - * exports - */ -t.exports=i},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(4); -/*! - * MissingSchema Error constructor. - * - * @inherits MongooseError - */function i(t){var e="Schema hasn't been registered for model \""+t+'".\nUse mongoose.model(name, schema)';n.call(this,e),this.name="MissingSchemaError",Error.captureStackTrace?Error.captureStackTrace(this):this.stack=(new Error).stack} -/*! - * Inherits from MongooseError. - */i.prototype=Object.create(n.prototype),i.prototype.constructor=n, -/*! - * exports - */ -t.exports=i},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(4); -/*! - * DivergentArrayError constructor. - * - * @inherits MongooseError - */function i(t){var e="For your own good, using `document.save()` to update an array which was selected using an $elemMatch projection OR populated using skip, limit, query conditions, or exclusion of the _id field when the operation results in a $pop or $set of the entire array is not supported. The following path(s) would have been modified unsafely:\n "+t.join("\n ")+"\nUse Model.update() to update these arrays instead.";n.call(this,e),this.name="DivergentArrayError",Error.captureStackTrace?Error.captureStackTrace(this):this.stack=(new Error).stack} -/*! - * Inherits from MongooseError. - */i.prototype=Object.create(n.prototype),i.prototype.constructor=n, -/*! - * exports - */ -t.exports=i},function(t,e,r){"use strict";var n=r(30); -/*! - * ignore - */t.exports=function(t){t.$immutable?(t.$immutableSetter=function(t,e){return function(r){if(null==this||null==this.$__)return r;if(this.isNew)return r;var i="function"==typeof e?e.call(this,this):e;if(!i)return r;if("throw"===this.$__.strictMode&&r!==this[t])throw new n(t,"Path `"+t+"` is immutable and strict mode is set to throw.",!0);return this[t]}}(t.path,t.options.immutable),t.set(t.$immutableSetter)):t.$immutableSetter&&(t.setters=t.setters.filter(function(e){return e!==t.$immutableSetter}),delete t.$immutableSetter)}},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(4);function i(t,e,r){n.call(this,'Parameter "'+e+'" to '+r+"() must be an object, got "+t.toString()),this.name="ObjectParameterError",Error.captureStackTrace?Error.captureStackTrace(this):this.stack=(new Error).stack} -/*! - * Inherits from MongooseError. - */i.prototype=Object.create(n.prototype),i.prototype.constructor=n,t.exports=i},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(16);function i(t){n.call(this,"Can't validate() the same doc multiple times in parallel. Document: "+t._id),this.name="ParallelValidateError"} -/*! - * Inherits from MongooseError. - */i.prototype=Object.create(n.prototype),i.prototype.constructor=n, -/*! - * exports - */ -t.exports=i},function(t,e,r){"use strict";(function(e){var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};function n(){this._pres=new Map,this._posts=new Map}function i(t,e,r,n,i,o,s){if(o.useErrorHandlers){var a={error:e};return t.execPost(r,n,i,a,function(t){return"function"==typeof s&&s(t)})}return"function"==typeof s?s(e):void 0}function o(t,e,r){return t.has(e)?t.get(e):r}function s(t,e,r,n){var i=void 0;try{i=t.apply(e,r)}catch(t){return n(t)}a(i)&&i.then(function(){return n()},function(t){return n(t)})}function a(t){return null!=t&&"function"==typeof t.then}function u(t){var r=!1,n=this;return function(){var i=arguments;if(!r)return r=!0,e.nextTick(function(){return t.apply(n,i)})}}n.prototype.execPre=function(t,r,n,i){3===arguments.length&&(i=n,n=[]);var c=o(this._pres,t,[]),l=c.length,f=0,h=c.numAsync||0,p=!1,d=n;if(!l)return e.nextTick(function(){i(null)});var y=function t(){if(!(f>=l)){var n=c[f];if(n.isAsync){var o=[u(v),u(function(t){if(t){if(p)return;return p=!0,i(t)}if(0==--h&&f>=l)return i(null)})];s(n.fn,r,o,o[0])}else if(n.fn.length>0){o=[u(v)];for(var y=arguments.length>=2?arguments:[null].concat(d),_=1;_=l)return h>0?void 0:e.nextTick(function(){i(m)});t(m)}}}};function v(t){if(t){if(p)return;return p=!0,i(t)}if(++f>=l)return h>0?void 0:i(null);y.apply(r,arguments)}y.apply(null,[null].concat(n))},n.prototype.execPreSync=function(t,e,r){for(var n=o(this._pres,t,[]),i=n.length,s=0;s=f)return c.call(null,p);t()});s(e,r,[p].concat(d).concat([v]),v)}else{if(++h>=f)return c.call(null,p);t()}else{var _=u(function(e){return e?(p=e,t()):++h>=f?c.apply(null,[null].concat(n)):void t()});if(e.length===i+2)return++h>=f?c.apply(null,[null].concat(n)):t();if(e.length===i+1)s(e,r,d.concat([_]),_);else{var m=void 0,g=void 0;try{g=e.apply(r,d)}catch(t){m=t,p=t}if(a(g))return g.then(function(){return _()},function(t){return _(t)});if(++h>=f)return c.apply(null,[m].concat(n));t()}}}()},n.prototype.execPostSync=function(t,e,r){for(var n=o(this._posts,t,[]),i=n.length,s=0;s0?n[n.length-1]:null,a=("function"==typeof s&&n.slice(0,n.length-1),this),u=(o=o||{}).checkForPromise;this.execPre(t,r,n,function(c){if(c){for(var l=o.numCallbackParams||0,f=o.contextParameter?[r]:[],h=f.length;h0;--S){var E=r.path(O.slice(0,S).join("."));null!=E&&(E.$isMongooseDocumentArray||E.$isSingleNested)&&w.push({parentPath:u.split(".").slice(0,S).join("."),parentSchemaType:E})}if(Array.isArray(e.$set[u])&&h.$isMongooseDocumentArray)o(e.$set[u],h,t);else if(e.$set[u]&&h.$isSingleNested)s(e.$set[u],h,t);else if(w.length>0){var A=!0,$=!1,j=void 0;try{for(var x,N=w[Symbol.iterator]();!(A=(x=N.next()).done);A=!0){var P=x.value,k=P.parentPath,T=P.parentSchemaType;if(f=T.schema.options.timestamps,c=i(f,"createdAt"),l=i(f,"updatedAt"),f&&null!=l)if(T.$isSingleNested)e.$set[k+"."+l]=t;else if(T.$isMongooseDocumentArray){var B=u.substr(k.length+1);if(/^\d+$/.test(B)){e.$set[k+"."+B][l]=t;continue}var C=B.indexOf(".");B=-1!==C?B.substr(0,C):B,e.$set[k+"."+B+"."+l]=t}}}catch(t){$=!0,j=t}finally{try{!A&&N.return&&N.return()}finally{if($)throw j}}}else if(null!=h.schema&&h.schema!=r&&e.$set[u]){if(f=h.schema.options.timestamps,c=i(f,"createdAt"),l=i(f,"updatedAt"),!f)continue;null!=l&&(e.$set[u][l]=t),null!=c&&(e.$set[u][c]=t)}}}}catch(t){v=!0,_=t}finally{try{!y&&g.return&&g.return()}finally{if(v)throw _}}}}else{var D=Object.keys(e).filter(function(t){return!t.startsWith("$")}),M=!0,R=!1,F=void 0;try{for(var I,L=D[Symbol.iterator]();!(M=(I=L.next()).done);M=!0){u=I.value;var U=n(u);(h=r.path(U))&&(Array.isArray(e[u])&&h.$isMongooseDocumentArray?o(e[u],h,t):null!=e[u]&&h.$isSingleNested&&s(e[u],h,t))}}catch(t){R=!0,F=t}finally{try{!M&&L.return&&L.return()}finally{if(R)throw F}}}}},function(t,e,r){"use strict";t.exports=function(t){return t.replace(/\.\$(\[[^\]]*\])?\./g,".0.").replace(/\.(\[[^\]]*\])?\$$/g,".0")}},function(t,e,r){"use strict"; -/*! - * ignore - */var n=r(5);t.exports= -/*! - * ignore - */ -function(t,e,r,i,o){var s=i,a=s,u=n(o,"overwrite",!1),c=n(o,"timestamps",!0);if(!c||null==s)return i;var l=null!=c&&!1===c.createdAt,f=null!=c&&!1===c.updatedAt;if(u)return i&&i.$set&&(i=i.$set,s.$set={},a=s.$set),f||!r||i[r]||(a[r]=t),l||!e||i[e]||(a[e]=t),s;if(i=i||{},Array.isArray(s))return s.push({$set:{updatedAt:t}}),s;s.$set=s.$set||{},f||!r||i.$currentDate&&i.$currentDate[r]||(s.$set[r]=t,s.hasOwnProperty(r)&&delete s[r]);!l&&e&&(i[e]&&delete i[e],i.$set&&i.$set[e]&&delete i.$set[e],s.$setOnInsert=s.$setOnInsert||{},s.$setOnInsert[e]=t);0===Object.keys(s.$set).length&&delete s.$set;return s}},function(t,e,r){"use strict";var n=r(5),i=r(20); -/*! - * Gather all indexes defined in the schema, including single nested, - * document arrays, and embedded discriminators. - */ -t.exports=function(t){var e=[],r=new WeakMap,o=t.constructor.indexTypes,s=new Map;return function t(a,u,c){if(r.has(a))return;r.set(a,!0);u=u||"";var l=Object.keys(a.paths);var f=!0;var h=!1;var p=void 0;try{for(var d,y=l[Symbol.iterator]();!(f=(d=y.next()).done);f=!0){var v=d.value,_=a.paths[v];if(null==c||!c.paths[v]){if(_.$isMongooseDocumentArray||_.$isSingleNested){if(!0!==n(_,"options.excludeIndexes")&&!0!==n(_,"schemaOptions.excludeIndexes")&&!0!==n(_,"schema.options.excludeIndexes")&&t(_.schema,u+v+"."),null!=_.schema.discriminators){var m=_.schema.discriminators,g=Object.keys(m),b=!0,w=!1,O=void 0;try{for(var S,E=g[Symbol.iterator]();!(b=(S=E.next()).done);b=!0){var A=S.value;t(m[A],u+v+".",_.schema)}}catch(t){w=!0,O=t}finally{try{!b&&E.return&&E.return()}finally{if(w)throw O}}}if(_.$isMongooseDocumentArray)continue}var $=_._index||_.caster&&_.caster._index;if(!1!==$&&null!==$&&void 0!==$){var j={},x=i($),N=x?$:{},P="string"==typeof $?$:!!x&&$.type;if(P&&-1!==o.indexOf(P))j[u+v]=P;else if(N.text)j[u+v]="text",delete N.text;else{var k=-1===Number($);j[u+v]=k?-1:1}delete N.type,"background"in N||(N.background=!0);var T=N&&N.name;"string"==typeof T&&s.has(T)?Object.assign(s.get(T),j):(e.push([j,N]),s.set(T,j))}}}}catch(t){h=!0,p=t}finally{try{!f&&y.return&&y.return()}finally{if(h)throw p}}r.delete(a);u? -/*! - * Checks for indexes added to subdocs using Schema.index(). - * These indexes need their paths prefixed properly. - * - * schema._indexes = [ [indexObj, options], [indexObj, options] ..] - */ -function(t,r){for(var n=t._indexes,i=n.length,o=0;o0&&!t?this:this.set(function(t,e){return"string"!=typeof t&&(t=e.cast(t)),t?t.toLowerCase():t})},f.prototype.uppercase=function(t){return arguments.length>0&&!t?this:this.set(function(t,e){return"string"!=typeof t&&(t=e.cast(t)),t?t.toUpperCase():t})},f.prototype.trim=function(t){return arguments.length>0&&!t?this:this.set(function(t,e){return"string"!=typeof t&&(t=e.cast(t)),t?t.trim():t})},f.prototype.minlength=function(t,e){if(this.minlengthValidator&&(this.validators=this.validators.filter(function(t){return t.validator!==this.minlengthValidator},this)),null!==t&&void 0!==t){var r=e||i.messages.String.minlength;r=r.replace(/{MINLENGTH}/,t),this.validators.push({validator:this.minlengthValidator=function(e){return null===e||e.length>=t},message:r,type:"minlength",minlength:t})}return this},f.prototype.maxlength=function(t,e){if(this.maxlengthValidator&&(this.validators=this.validators.filter(function(t){return t.validator!==this.maxlengthValidator},this)),null!==t&&void 0!==t){var r=e||i.messages.String.maxlength;r=r.replace(/{MAXLENGTH}/,t),this.validators.push({validator:this.maxlengthValidator=function(e){return null===e||e.length<=t},message:r,type:"maxlength",maxlength:t})}return this},f.prototype.match=function(t,e){var r=e||i.messages.String.match;return this.validators.push({validator:function(e){return!!t&&(null==e||""===e||t.test(e))},message:r,type:"regexp",regexp:t}),this},f.prototype.checkRequired=function(t,e){return n._isRef(this,t,e,!0)?!!t:("function"==typeof this.constructor.checkRequired?this.constructor.checkRequired():f.checkRequired())(t)},f.prototype.cast=function(t,i,o){if(n._isRef(this,t,i,o)){if(null===t||void 0===t)return t;if(l||(l=r(6)),t instanceof l)return t.$__.wasPopulated=!0,t;if("string"==typeof t)return t;if(e.isBuffer(t)||!a.isObject(t))throw new c("string",t,this.path,null,this);var s=i.$__fullPath(this.path),h=new((i.ownerDocument?i.ownerDocument():i).populated(s,!0).options[u])(t);return h.$__.wasPopulated=!0,h}var p="function"==typeof this.constructor.cast?this.constructor.cast():f.cast();try{return p(t)}catch(e){throw new c("string",t,this.path,null,this)}};var p=a.options(n.prototype.$conditionalHandlers,{$all:function(t){var e=this;return Array.isArray(t)?t.map(function(t){return e.castForQuery(t)}):[this.castForQuery(t)]},$gt:h,$gte:h,$lt:h,$lte:h,$options:String,$regex:h,$not:h});Object.defineProperty(f.prototype,"$conditionalHandlers",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(p)}),f.prototype.castForQuery=function(t,e){var r=void 0;if(2===arguments.length){if(!(r=this.$conditionalHandlers[t]))throw new Error("Can't use "+t+" with String.");return r.call(this,e)}return e=t,"[object RegExp]"===Object.prototype.toString.call(e)?e:this._castForQuery(e)}, -/*! - * Module exports. - */ -t.exports=f}).call(this,r(1).Buffer)},function(t,e,r){"use strict";var n=r(9),i=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,n),e}(),o=r(10);Object.defineProperty(i.prototype,"enum",o),Object.defineProperty(i.prototype,"match",o),Object.defineProperty(i.prototype,"lowercase",o),Object.defineProperty(i.prototype,"trim",o),Object.defineProperty(i.prototype,"uppercase",o),Object.defineProperty(i.prototype,"minlength",o),Object.defineProperty(i.prototype,"maxlength",o), -/*! - * ignore - */ -t.exports=i},function(t,e,r){"use strict";var n=r(9),i=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,n),e}(),o=r(10);Object.defineProperty(i.prototype,"min",o),Object.defineProperty(i.prototype,"max",o),Object.defineProperty(i.prototype,"enum",o), -/*! - * ignore - */ -t.exports=i},function(t,e,r){"use strict";var n=r(21); -/*! - * Given a value, cast it to a number, or throw a `CastError` if the value - * cannot be casted. `null` and `undefined` are considered valid. - * - * @param {Any} value - * @param {String} [path] optional the path to set on the CastError - * @return {Boolean|null|undefined} - * @throws {Error} if `value` is not one of the allowed values - * @api private - */t.exports=function(t){return null==t?t:""===t?null:("string"!=typeof t&&"boolean"!=typeof t||(t=Number(t)),n.ok(!isNaN(t)),t instanceof Number?t.valueOf():"number"==typeof t?t:Array.isArray(t)||"function"!=typeof t.valueOf?t.toString&&!Array.isArray(t)&&t.toString()==Number(t)?Number(t):void n.ok(!1):Number(t.valueOf()))}},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(13),i=r(7),o=r(49),s=r(2);function a(t,e){i.call(this,t,e,"Boolean")}a.schemaName="Boolean",a.defaultOptions={}, -/*! - * Inherits from SchemaType. - */ -a.prototype=Object.create(i.prototype),a.prototype.constructor=a, -/*! - * ignore - */ -a._cast=o,a.set=i.set,a.cast=function(t){return 0===arguments.length?this._cast:(!1===t&&(t=function(t){if(null!=t&&"boolean"!=typeof t)throw new Error;return t}),this._cast=t,this._cast)}, -/*! - * ignore - */ -a._checkRequired=function(t){return!0===t||!1===t},a.checkRequired=i.checkRequired,a.prototype.checkRequired=function(t){return this.constructor._checkRequired(t)},Object.defineProperty(a,"convertToTrue",{get:function(){return o.convertToTrue},set:function(t){o.convertToTrue=t}}),Object.defineProperty(a,"convertToFalse",{get:function(){return o.convertToFalse},set:function(t){o.convertToFalse=t}}),a.prototype.cast=function(t){var e="function"==typeof this.constructor.cast?this.constructor.cast():a.cast();try{return e(t)}catch(e){throw new n("Boolean",t,this.path,e,this)}},a.$conditionalHandlers=s.options(i.prototype.$conditionalHandlers,{}),a.prototype.castForQuery=function(t,e){var r=void 0;return 2===arguments.length?(r=a.$conditionalHandlers[t])?r.call(this,e):this._castForQuery(e):this._castForQuery(t)}, -/*! - * Module exports. - */ -t.exports=a},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n=r(55),i=r(13),o=r(18).EventEmitter,s=r(154),a=r(7),u=r(29),c=r(89),l=r(5),f=r(90),h=r(3),p=r(2),d=r(91),y=r(0).arrayPathSymbol,v=r(0).documentArrayParent,_=void 0,m=void 0;function g(t,e,r,i){null!=i&&null!=i._id?e=f(e,i):null!=r&&null!=r._id&&(e=f(e,r));var o=b(e,r);o.prototype.$basePath=t,n.call(this,t,o,r),this.schema=e,this.schemaOptions=i||{},this.$isMongooseDocumentArray=!0,this.Constructor=o,o.base=e.base;var s=this.defaultValue;"defaultValue"in this&&void 0===s||this.default(function(){var t=s.call(this);return Array.isArray(t)||(t=[t]),t});var u=this;this.$embeddedSchemaType=new a(t+".$",{required:l(this,"schemaOptions.required",!1)}),this.$embeddedSchemaType.cast=function(t,e,r){return u.cast(t,e,r)[0]},this.$embeddedSchemaType.$isMongooseDocumentArrayElement=!0,this.$embeddedSchemaType.caster=this.Constructor,this.$embeddedSchemaType.schema=this.schema} -/*! - * Ignore - */ -function b(t,e,n){function i(){m.apply(this,arguments),this.$session(this.ownerDocument().$session())}m||(m=r(25));var s=null!=n?n.prototype:m.prototype;for(var a in i.prototype=Object.create(s),i.prototype.$__setSchema(t),i.schema=t,i.prototype.constructor=i,i.$isArraySubdocument=!0,i.events=new o,t.methods)i.prototype[a]=t.methods[a];for(var u in t.statics)i[u]=t.statics[u];for(var c in o.prototype)i[c]=o.prototype[c];return i.options=e,i} -/*! - * Scopes paths selected in a query to this array. - * Necessary for proper default application of subdocument values. - * - * @param {DocumentArrayPath} array - the array to scope `fields` paths - * @param {Object|undefined} fields - the root fields selected in the query - * @param {Boolean|undefined} init - if we are being created part of a query result - */ -function w(t,e,r){if(r&&e){for(var n=t.path+".",i=Object.keys(e),o=i.length,s={},a=void 0,u=void 0,c=void 0;o--;)if((u=i[o]).startsWith(n)){if("$"===(c=u.substring(n.length)))continue;c.startsWith("$.")&&(c=c.substr(2)),a||(a=!0),s[c]=e[u]}return a&&s||void 0}} -/*! - * Module exports. - */g.schemaName="DocumentArray",g.options={castNonArrays:!0}, -/*! - * Inherits from ArrayType. - */ -g.prototype=Object.create(n.prototype),g.prototype.constructor=g,g.prototype.OptionsConstructor=s,g.prototype.discriminator=function(t,e,r){"function"==typeof t&&(t=p.getFunctionName(t));var n=b(e=c(this.casterConstructor,t,e,r),null,this.casterConstructor);n.baseCasterConstructor=this.casterConstructor;try{Object.defineProperty(n,"name",{value:t})}catch(t){}return this.casterConstructor.discriminators[t]=n,this.casterConstructor.discriminators[t]},g.prototype.doValidate=function(t,e,n,i){_||(_=r(17));var o=this;try{a.prototype.doValidate.call(this,t,function(r){if(r)return r.$isArrayValidatorError=!0,e(r);var s=t&&t.length,a=void 0;if(!s)return e();if(i&&i.updateValidator)return e();t.isMongooseDocumentArray||(t=new _(t,o.path,n));function c(t){null!=t&&((a=t)instanceof u||(a.$isArrayValidatorError=!0)),--s||e(a)}for(var l=0,f=s;lr.max&&(r.max=i.max)}r.min=r.min+1;r.max=r.max+1;return r}},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(30),o=r(54),s=r(153),a=r(5),u=r(79),c=r(3),l=r(20),f=r(27),h=["Polygon","MultiPolygon"];function p(t,e,r){if(Array.isArray(t))t.forEach(function(n,i){if(Array.isArray(n)||l(n))return p(n,e,r);t[i]=e.castForQueryWrapper({val:n,context:r})});else for(var n=Object.keys(t),i=n.length;i--;){var o=n[i],s=t[o];Array.isArray(s)||l(s)?(p(s,e,r),t[o]=s):t[o]=e.castForQuery({val:s,context:r})}}t.exports=function t(e,r,d,y){if(Array.isArray(r))throw new Error("Query filter must be an object, got an array ",c.inspect(r));r.hasOwnProperty("_bsontype")&&"ObjectID"!==r._bsontype&&delete r._bsontype;var v=Object.keys(r),_=v.length,m=void 0,g=void 0,b=void 0,w=void 0,O=void 0,S=void 0;for(d=d||{};_--;)if(S=r[w=v[_]],"$or"===w||"$nor"===w||"$and"===w)for(var E=S.length;E--;)S[E]=t(e,S[E],d,y);else{if("$where"===w){if("string"!==(O=void 0===S?"undefined":n(S))&&"function"!==O)throw new Error("Must have a string or function for $where");"function"===O&&(r[w]=S.toString());continue}if("$elemMatch"===w)S=t(e,S,d,y);else if("$text"===w)S=s(S,w);else{if(!e)continue;if(!(g=e.path(w)))for(var A=w.split("."),$=A.length;$--;){var j=A.slice(0,$).join("."),x=A.slice($).join("."),N=e.path(j),P=a(N,"schema.options.discriminatorKey");if(null!=N&&null!=a(N,"schema.discriminators")&&null!=P&&x!==P){var k=a(r,j+"."+P);null!=k&&(g=N.schema.discriminators[k].path(x))}}if(g){if(null==S)continue;if("Object"===S.constructor.name)if(Object.keys(S).some(u))for(var T=Object.keys(S),B=void 0,C=T.length;C--;)if(b=S[B=T[C]],"$not"===B){if(b&&g&&!g.caster){if((m=Object.keys(b)).length&&u(m[0]))for(var D in b)b[D]=g.castForQueryWrapper({$conditional:D,val:b[D],context:y});else S[B]=g.castForQueryWrapper({$conditional:B,val:b,context:y});continue}t(g.caster?g.caster.schema:e,b,d,y)}else S[B]=g.castForQueryWrapper({$conditional:B,val:b,context:y});else r[w]=g.castForQueryWrapper({val:S,context:y});else if(Array.isArray(S)&&-1===["Buffer","Array"].indexOf(g.instance)){var M=[],R=S,F=!0,I=!1,L=void 0;try{for(var U,V=R[Symbol.iterator]();!(F=(U=V.next()).done);F=!0){var q=U.value;M.push(g.castForQueryWrapper({val:q,context:y}))}}catch(t){I=!0,L=t}finally{try{!F&&V.return&&V.return()}finally{if(I)throw L}}r[w]={$in:M}}else r[w]=g.castForQueryWrapper({val:S,context:y})}else{for(var W=w.split("."),H=W.length,Y=void 0,z=void 0,K=void 0;H--&&(Y=W.slice(0,H).join("."),!(g=e.path(Y))););if(g){g.caster&&g.caster.schema?((K={})[z=W.slice(H).join(".")]=S,r[w]=t(g.caster.schema,K,d,y)[z]):r[w]=S;continue}if(l(S)){var Q="";if(S.$near?Q="$near":S.$nearSphere?Q="$nearSphere":S.$within?Q="$within":S.$geoIntersects?Q="$geoIntersects":S.$geoWithin&&(Q="$geoWithin"),Q){var J=new o.Number("__QueryCasting__"),G=S[Q];if(null!=S.$maxDistance&&(S.$maxDistance=J.castForQueryWrapper({val:S.$maxDistance,context:y})),null!=S.$minDistance&&(S.$minDistance=J.castForQueryWrapper({val:S.$minDistance,context:y})),"$within"===Q){var X=G.$center||G.$centerSphere||G.$box||G.$polygon;if(!X)throw new Error("Bad $within parameter: "+JSON.stringify(S));G=X}else if("$near"===Q&&"string"==typeof G.type&&Array.isArray(G.coordinates))G=G.coordinates;else if(("$near"===Q||"$nearSphere"===Q||"$geoIntersects"===Q)&&G.$geometry&&"string"==typeof G.$geometry.type&&Array.isArray(G.$geometry.coordinates))null!=G.$maxDistance&&(G.$maxDistance=J.castForQueryWrapper({val:G.$maxDistance,context:y})),null!=G.$minDistance&&(G.$minDistance=J.castForQueryWrapper({val:G.$minDistance,context:y})),f(G.$geometry)&&(G.$geometry=G.$geometry.toObject({transform:!1,virtuals:!1})),G=G.$geometry.coordinates;else if("$geoWithin"===Q)if(G.$geometry){f(G.$geometry)&&(G.$geometry=G.$geometry.toObject({virtuals:!1}));var Z=G.$geometry.type;if(-1===h.indexOf(Z))throw new Error('Invalid geoJSON type for $geoWithin "'+Z+'", must be "Polygon" or "MultiPolygon"');G=G.$geometry.coordinates}else G=G.$box||G.$polygon||G.$center||G.$centerSphere,f(G)&&(G=G.toObject({virtuals:!1}));p(G,J,y);continue}}if(e.nested[w])continue;if(d.upsert&&d.strict){if("throw"===d.strict)throw new i(w);throw new i(w,'Path "'+w+'" is not in schema, strict mode is `true`, and upsert is `true`.')}if("throw"===d.strictQuery)throw new i(w,'Path "'+w+"\" is not in schema and strictQuery is 'throw'.");d.strictQuery&&delete r[w]}}}return r}},function(t,e,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(13),o=r(49),s=r(76); -/*! - * Casts val to an object suitable for `$text`. Throws an error if the object - * can't be casted. - * - * @param {Any} val value to cast - * @param {String} [path] path to associate with any errors that occured - * @return {Object} casted object - * @see https://docs.mongodb.com/manual/reference/operator/query/text/ - * @api private - */ -t.exports=function(t,e){if(null==t||"object"!==(void 0===t?"undefined":n(t)))throw new i("$text",t,e);return null!=t.$search&&(t.$search=s(t.$search,e+".$search")),null!=t.$language&&(t.$language=s(t.$language,e+".$language")),null!=t.$caseSensitive&&(t.$caseSensitive=o(t.$caseSensitive,e+".$castSensitive")),null!=t.$diacriticSensitive&&(t.$diacriticSensitive=o(t.$diacriticSensitive,e+".$diacriticSensitive")),t}},function(t,e,r){"use strict";var n=r(9),i=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,n),e}(),o=r(10);Object.defineProperty(i.prototype,"excludeIndexes",o),Object.defineProperty(i.prototype,"_id",o), -/*! - * ignore - */ -t.exports=i},function(t,e,r){"use strict"; -/*! - * Module dependencies. - */var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(13),o=r(18).EventEmitter,s=r(72),a=r(156),u=r(7),c=r(48),l=r(32).castToNumber,f=r(89),h=r(80),p=r(5),d=r(91),y=r(90),v=r(22).internalToObjectOptions,_=void 0;function m(t,e,r){t=y(t,r),this.caster=g(t),this.caster.path=e,this.caster.prototype.$basePath=e,this.schema=t,this.$isSingleNested=!0,u.call(this,e,r,"Embedded")} -/*! - * ignore - */ -/*! - * ignore - */ -function g(t,e){_||(_=r(88));var n=function(t,e,r){var n=this;this.$parent=r,_.apply(this,arguments),this.$session(this.ownerDocument().$session()),r&&(r.on("save",function(){n.emit("save",n),n.constructor.emit("save",n)}),r.on("isNew",function(t){n.isNew=t,n.emit("isNew",t),n.constructor.emit("isNew",t)}))},i=null!=e?e.prototype:_.prototype;for(var s in(n.prototype=Object.create(i)).$__setSchema(t),n.prototype.constructor=n,n.schema=t,n.$isSingleNested=!0,n.events=new o,n.prototype.toBSON=function(){return this.toObject(v)},t.methods)n.prototype[s]=t.methods[s];for(var a in t.statics)n[a]=t.statics[a];for(var u in o.prototype)n[u]=o.prototype[u];return n} -/*! - * Special case for when users use a common location schema to represent - * locations for use with $geoWithin. - * https://docs.mongodb.org/manual/reference/operator/query/geoWithin/ - * - * @param {Object} val - * @api private - */t.exports=m,m.prototype=Object.create(u.prototype),m.prototype.constructor=m,m.prototype.OptionsConstructor=a,m.prototype.$conditionalHandlers.$geoWithin=function(t){return{$geometry:this.castForQuery(t.$geometry)}}, -/*! - * ignore - */ -m.prototype.$conditionalHandlers.$near=m.prototype.$conditionalHandlers.$nearSphere=h.cast$near,m.prototype.$conditionalHandlers.$within=m.prototype.$conditionalHandlers.$geoWithin=h.cast$within,m.prototype.$conditionalHandlers.$geoIntersects=h.cast$geoIntersects,m.prototype.$conditionalHandlers.$minDistance=l,m.prototype.$conditionalHandlers.$maxDistance=l,m.prototype.$conditionalHandlers.$exists=c,m.prototype.cast=function(t,e,r,i){if(t&&t.$isSingleNested&&t.parent===e)return t;if(null!=t&&("object"!==(void 0===t?"undefined":n(t))||Array.isArray(t)))throw new s(this.path,t);var o=d(this.caster,t),a=void 0,u=p(e,"$__.selected",{}),c=this.path,l=Object.keys(u).reduce(function(t,e){return e.startsWith(c+".")&&(t[e.substr(c.length+1)]=u[e]),t},{});return r?((a=new o(void 0,l,e)).init(t),a):0===Object.keys(t).length?new o({},l,e):new o(t,l,e,void 0,{priorDoc:i})},m.prototype.castForQuery=function(t,e,r){var n=void 0;if(2===arguments.length){if(!(n=this.$conditionalHandlers[t]))throw new Error("Can't use "+t);return n.call(this,e)}if(null==(e=t))return e;this.options.runSetters&&(e=this._applySetters(e));var o=d(this.caster,e),s=null!=r&&null!=r.strict?r.strict:void 0;try{e=new o(e,s)}catch(t){if(!(t instanceof i))throw new i("Embedded",e,this.path,t,this);throw t}return e},m.prototype.doValidate=function(t,e,r,n){var i=d(this.caster,t);if(n&&n.skipSchemaValidators)return t instanceof i||(t=new i(t,null,r)),t.validate(e);u.prototype.doValidate.call(this,t,function(r){return r?e(r):t?void t.validate(e):e(null)},r,n)},m.prototype.doValidateSync=function(t,e,r){if(!r||!r.skipSchemaValidators){var n=u.prototype.doValidateSync.call(this,t,e);if(n)return n}if(t)return t.validateSync()},m.prototype.discriminator=function(t,e,r){return e=f(this.caster,t,e,r),this.caster.discriminators[t]=g(e,this.caster),this.caster.discriminators[t]}, -/*! - * ignore - */ -m.prototype.clone=function(){var t=Object.assign({},this.options),e=new this.constructor(this.schema,this.path,t);return e.validators=this.validators.slice(),e.caster.discriminators=Object.assign({},this.caster.discriminators),e}},function(t,e,r){"use strict";var n=r(9),i=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,n),e}(),o=r(10);Object.defineProperty(i.prototype,"_id",o),t.exports=i},function(t,e,r){"use strict";(function(e){ -/*! - * Module dependencies. - */ -var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(84),o=r(158),s=r(7),a=r(78),u=r(2),c=r(0).populateModelSymbol,l=i.Binary,f=s.CastError,h=void 0;function p(t,e){s.call(this,t,e,"Buffer")} -/*! - * ignore - */ -function d(t){return this.castForQuery(t)}p.schemaName="Buffer",p.defaultOptions={}, -/*! - * Inherits from SchemaType. - */ -p.prototype=Object.create(s.prototype),p.prototype.constructor=p,p.prototype.OptionsConstructor=o, -/*! - * ignore - */ -p._checkRequired=function(t){return!(!t||!t.length)},p.set=s.set,p.checkRequired=s.checkRequired,p.prototype.checkRequired=function(t,e){return s._isRef(this,t,e,!0)?!!t:this.constructor._checkRequired(t)},p.prototype.cast=function(t,o,a){var p=void 0;if(s._isRef(this,t,o,a)){if(null===t||void 0===t)return t;if(h||(h=r(6)),t instanceof h)return t.$__.wasPopulated=!0,t;if(e.isBuffer(t))return t;if(!u.isObject(t))throw new f("Buffer",t,this.path,null,this);var d=o.$__fullPath(this.path);return(p=new((o.ownerDocument?o.ownerDocument():o).populated(d,!0).options[c])(t)).$__.wasPopulated=!0,p}if(t&&t._id&&(t=t._id),t&&t.isMongooseBuffer)return t;if(e.isBuffer(t))return t&&t.isMongooseBuffer||(t=new i(t,[this.path,o]),null!=this.options.subtype&&(t._subtype=this.options.subtype)),t;if(t instanceof l){if(p=new i(t.value(!0),[this.path,o]),"number"!=typeof t.sub_type)throw new f("Buffer",t,this.path,null,this);return p._subtype=t.sub_type,p}if(null===t)return t;var y=void 0===t?"undefined":n(t);if("string"===y||"number"===y||Array.isArray(t)||"object"===y&&"Buffer"===t.type&&Array.isArray(t.data))return"number"===y&&(t=[t]),p=new i(t,[this.path,o]),null!=this.options.subtype&&(p._subtype=this.options.subtype),p;throw new f("Buffer",t,this.path,null,this)},p.prototype.subtype=function(t){return this.options.subtype=t,this},p.prototype.$conditionalHandlers=u.options(s.prototype.$conditionalHandlers,{$bitsAllClear:a,$bitsAnyClear:a,$bitsAllSet:a,$bitsAnySet:a,$gt:d,$gte:d,$lt:d,$lte:d}),p.prototype.castForQuery=function(t,e){var r=void 0;if(2===arguments.length){if(!(r=this.$conditionalHandlers[t]))throw new Error("Can't use "+t+" with Buffer.");return r.call(this,e)}e=t;var n=this._castForQuery(e);return n?n.toObject({transform:!1,virtuals:!1}):n}, -/*! - * Module exports. - */ -t.exports=p}).call(this,r(1).Buffer)},function(t,e,r){"use strict";var n=r(9),i=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,n),e}(),o=r(10);Object.defineProperty(i.prototype,"subtype",o), -/*! - * ignore - */ -t.exports=i},function(t,e,r){"use strict"; -/*! - * Module requirements. - */var n=r(4),i=r(160),o=r(7),s=r(161),a=r(2),u=o.CastError;function c(t,e){o.call(this,t,e,"Date")} -/*! - * Date Query casting. - * - * @api private - */ -function l(t){return this.cast(t)}c.schemaName="Date",c.defaultOptions={}, -/*! - * Inherits from SchemaType. - */ -c.prototype=Object.create(o.prototype),c.prototype.constructor=c,c.prototype.OptionsConstructor=i, -/*! - * ignore - */ -c._cast=s,c.set=o.set,c.cast=function(t){return 0===arguments.length?this._cast:(!1===t&&(t=function(t){if(null!=t&&!(t instanceof Date))throw new Error;return t}),this._cast=t,this._cast)},c.prototype.expires=function(t){return this._index&&"Object"===this._index.constructor.name||(this._index={}),this._index.expires=t,a.expires(this._index),this}, -/*! - * ignore - */ -c._checkRequired=function(t){return t instanceof Date},c.checkRequired=o.checkRequired,c.prototype.checkRequired=function(t,e){return o._isRef(this,t,e,!0)?!!t:("function"==typeof this.constructor.checkRequired?this.constructor.checkRequired():c.checkRequired())(t)},c.prototype.min=function(t,e){if(this.minValidator&&(this.validators=this.validators.filter(function(t){return t.validator!==this.minValidator},this)),t){var r=e||n.messages.Date.min;"string"==typeof r&&(r=r.replace(/{MIN}/,t===Date.now?"Date.now()":t.toString()));var i=this;this.validators.push({validator:this.minValidator=function(e){var r=t;"function"==typeof t&&t!==Date.now&&(r=r.call(this));var n=r===Date.now?r():i.cast(r);return null===e||e.valueOf()>=n.valueOf()},message:r,type:"min",min:t})}return this},c.prototype.max=function(t,e){if(this.maxValidator&&(this.validators=this.validators.filter(function(t){return t.validator!==this.maxValidator},this)),t){var r=e||n.messages.Date.max;"string"==typeof r&&(r=r.replace(/{MAX}/,t===Date.now?"Date.now()":t.toString()));var i=this;this.validators.push({validator:this.maxValidator=function(e){var r=t;"function"==typeof r&&r!==Date.now&&(r=r.call(this));var n=r===Date.now?r():i.cast(r);return null===e||e.valueOf()<=n.valueOf()},message:r,type:"max",max:t})}return this},c.prototype.cast=function(t){var e="function"==typeof this.constructor.cast?this.constructor.cast():c.cast();try{return e(t)}catch(e){throw new u("date",t,this.path,e,this)}},c.prototype.$conditionalHandlers=a.options(o.prototype.$conditionalHandlers,{$gt:l,$gte:l,$lt:l,$lte:l}),c.prototype.castForQuery=function(t,e){if(2!==arguments.length)return this._castForQuery(t);var r=this.$conditionalHandlers[t];if(!r)throw new Error("Can't use "+t+" with Date.");return r.call(this,e)}, -/*! - * Module exports. - */ -t.exports=c},function(t,e,r){"use strict";var n=r(9),i=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,n),e}(),o=r(10);Object.defineProperty(i.prototype,"min",o),Object.defineProperty(i.prototype,"max",o),Object.defineProperty(i.prototype,"expires",o), -/*! - * ignore - */ -t.exports=i},function(t,e,r){"use strict";var n=r(21);t.exports=function(t){if(null==t||""===t)return null;if(t instanceof Date)return n.ok(!isNaN(t.valueOf())),t;var e=void 0;if(n.ok("boolean"!=typeof t),e=t instanceof Number||"number"==typeof t?new Date(t):"string"==typeof t&&!isNaN(Number(t))&&(Number(t)>=275761||Number(t)<-271820)?new Date(Number(t)):"function"==typeof t.valueOf?new Date(t.valueOf()):new Date(t),!isNaN(e.valueOf()))return e;n.ok(!1)}},function(t,e,r){"use strict";(function(e){ -/*! - * Module dependencies. - */ -var n=r(163),i=r(7),o=r(85),s=r(12),a=r(2),u=r(0).populateModelSymbol,c=i.CastError,l=void 0;function f(t,e){var r="string"==typeof t&&24===t.length&&/^[a-f0-9]+$/i.test(t),n=e&&e.suppressWarning;!r&&void 0!==t||n||(console.warn("mongoose: To create a new ObjectId please try `Mongoose.Types.ObjectId` instead of using `Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if you're trying to create a hex char path in your schema."),console.trace()),i.call(this,t,e,"ObjectID")} -/*! - * ignore - */ -function h(t){return this.cast(t)} -/*! - * ignore - */ -function p(){return new s}function d(t){if(l||(l=r(6)),this instanceof l){if(void 0===t){var e=new s;return this.$__._id=e,e}this.$__._id=t}return t} -/*! - * Module exports. - */f.schemaName="ObjectId",f.defaultOptions={}, -/*! - * Inherits from SchemaType. - */ -f.prototype=Object.create(i.prototype),f.prototype.constructor=f,f.prototype.OptionsConstructor=n,f.get=i.get,f.set=i.set,f.prototype.auto=function(t){return t&&(this.default(p),this.set(d)),this}, -/*! - * ignore - */ -f._checkRequired=function(t){return t instanceof s}, -/*! - * ignore - */ -f._cast=o,f.cast=function(t){return 0===arguments.length?this._cast:(!1===t&&(t=function(t){if(!(t instanceof s))throw new Error(t+" is not an instance of ObjectId");return t}),this._cast=t,this._cast)},f.checkRequired=i.checkRequired,f.prototype.checkRequired=function(t,e){return i._isRef(this,t,e,!0)?!!t:("function"==typeof this.constructor.checkRequired?this.constructor.checkRequired():f.checkRequired())(t)},f.prototype.cast=function(t,n,o){if(i._isRef(this,t,n,o)){if(null===t||void 0===t)return t;if(l||(l=r(6)),t instanceof l)return t.$__.wasPopulated=!0,t;if(t instanceof s)return t;if("objectid"===(t.constructor.name||"").toLowerCase())return new s(t.toHexString());if(e.isBuffer(t)||!a.isObject(t))throw new c("ObjectId",t,this.path,null,this);var h=n.$__fullPath(this.path),p=(n.ownerDocument?n.ownerDocument():n).populated(h,!0),d=t;return n.$__.populated&&n.$__.populated[h]&&n.$__.populated[h].options&&n.$__.populated[h].options.options&&n.$__.populated[h].options.options.lean||((d=new p.options[u](t)).$__.wasPopulated=!0),d}var y="function"==typeof this.constructor.cast?this.constructor.cast():f.cast();try{return y(t)}catch(e){throw new c("ObjectId",t,this.path,e,this)}},f.prototype.$conditionalHandlers=a.options(i.prototype.$conditionalHandlers,{$gt:h,$gte:h,$lt:h,$lte:h}),p.$runBeforeSetters=!0,t.exports=f}).call(this,r(1).Buffer)},function(t,e,r){"use strict";var n=r(9),i=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,n),e}(),o=r(10);Object.defineProperty(i.prototype,"auto",o), -/*! - * ignore - */ -t.exports=i},function(t,e,r){"use strict";(function(e){ -/*! - * Module dependencies. - */ -var n=r(7),i=n.CastError,o=r(19),s=r(165),a=r(2),u=r(0).populateModelSymbol,c=void 0;function l(t,e){n.call(this,t,e,"Decimal128")} -/*! - * ignore - */ -function f(t){return this.cast(t)}l.schemaName="Decimal128",l.defaultOptions={}, -/*! - * Inherits from SchemaType. - */ -l.prototype=Object.create(n.prototype),l.prototype.constructor=l, -/*! - * ignore - */ -l._cast=s,l.set=n.set,l.cast=function(t){return 0===arguments.length?this._cast:(!1===t&&(t=function(t){if(null!=t&&!(t instanceof o))throw new Error;return t}),this._cast=t,this._cast)}, -/*! - * ignore - */ -l._checkRequired=function(t){return t instanceof o},l.checkRequired=n.checkRequired,l.prototype.checkRequired=function(t,e){return n._isRef(this,t,e,!0)?!!t:("function"==typeof this.constructor.checkRequired?this.constructor.checkRequired():l.checkRequired())(t)},l.prototype.cast=function(t,s,f){if(n._isRef(this,t,s,f)){if(null===t||void 0===t)return t;if(c||(c=r(6)),t instanceof c)return t.$__.wasPopulated=!0,t;if(t instanceof o)return t;if(e.isBuffer(t)||!a.isObject(t))throw new i("Decimal128",t,this.path,null,this);var h=s.$__fullPath(this.path),p=(s.ownerDocument?s.ownerDocument():s).populated(h,!0),d=t;return s.$__.populated&&s.$__.populated[h]&&s.$__.populated[h].options&&s.$__.populated[h].options.options&&s.$__.populated[h].options.options.lean||((d=new p.options[u](t)).$__.wasPopulated=!0),d}var y="function"==typeof this.constructor.cast?this.constructor.cast():l.cast();try{return y(t)}catch(e){throw new i("Decimal128",t,this.path,e,this)}},l.prototype.$conditionalHandlers=a.options(n.prototype.$conditionalHandlers,{$gt:f,$gte:f,$lt:f,$lte:f}), -/*! - * Module exports. - */ -t.exports=l}).call(this,r(1).Buffer)},function(t,e,r){"use strict";(function(e){var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(19),o=r(21);t.exports=function(t){return null==t?t:"object"===(void 0===t?"undefined":n(t))&&"string"==typeof t.$numberDecimal?i.fromString(t.$numberDecimal):t instanceof i?t:"string"==typeof t?i.fromString(t):e.isBuffer(t)?new i(t):"number"==typeof t?i.fromString(String(t)):"function"==typeof t.valueOf&&"string"==typeof t.valueOf()?i.fromString(t.valueOf()):void o.ok(!1)}}).call(this,r(1).Buffer)},function(t,e,r){"use strict";(function(e){ -/*! - * ignore - */ -var n=function(){function t(t,e){for(var r=0;r0)&&!(e instanceof t)&&!(e instanceof o)&&!(e instanceof i)}e.flatten= -/*! - * ignore - */ -function e(r,n,i,o){var s=void 0;s=r&&a(r)&&!t.isBuffer(r)?Object.keys(r.toObject({transform:!1,virtuals:!1})):Object.keys(r||{});var c=s.length;var l={};n=n?n+".":"";for(var f=0;f { - if (!this._pipeline.length) { - const err = new Error('Aggregate has empty pipeline'); - return cb(err); - } - - prepareDiscriminatorPipeline(this); - - model.hooks.execPre('aggregate', this, error => { - if (error) { - const _opts = { error: error }; - return model.hooks.execPost('aggregate', this, [null], _opts, error => { - cb(error); - }); - } - - this.options.explain = true; - - model.collection. - aggregate(this._pipeline, this.options || {}). - explain((error, result) => { - const _opts = { error: error }; - return model.hooks.execPost('aggregate', this, [result], _opts, error => { - if (error) { - return cb(error); - } - return cb(null, result); - }); - }); - }); - }, model.events); -}; - -/** - * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) - * - * ####Example: - * - * await Model.aggregate([{ $match: { foo: 'bar' } }]).allowDiskUse(true); - * - * @param {Boolean} value Should tell server it can use hard drive to store data during aggregation. - * @param {Array} [tags] optional tags for this query - * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ - */ - -Aggregate.prototype.allowDiskUse = function(value) { - this.options.allowDiskUse = value; - return this; -}; - -/** - * Sets the hint option for the aggregation query (ignored for < 3.6.0) - * - * ####Example: - * - * Model.aggregate(..).hint({ qty: 1, category: 1 }).exec(callback) - * - * @param {Object|String} value a hint object or the index name - * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ - */ - -Aggregate.prototype.hint = function(value) { - this.options.hint = value; - return this; -}; - -/** - * Sets the session for this aggregation. Useful for [transactions](/docs/transactions.html). - * - * ####Example: - * - * const session = await Model.startSession(); - * await Model.aggregate(..).session(session); - * - * @param {ClientSession} session - * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ - */ - -Aggregate.prototype.session = function(session) { - if (session == null) { - delete this.options.session; - } else { - this.options.session = session; - } - return this; -}; - -/** - * Lets you set arbitrary options, for middleware or plugins. - * - * ####Example: - * - * var agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option - * agg.options; // `{ allowDiskUse: true }` - * - * @param {Object} options keys to merge into current options - * @param [options.maxTimeMS] number limits the time this aggregation will run, see [MongoDB docs on `maxTimeMS`](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) - * @param [options.allowDiskUse] boolean if true, the MongoDB server will use the hard drive to store data during this aggregation - * @param [options.collation] object see [`Aggregate.prototype.collation()`](./docs/api.html#aggregate_Aggregate-collation) - * @param [options.session] ClientSession see [`Aggregate.prototype.session()`](./docs/api.html#aggregate_Aggregate-session) - * @see mongodb http://docs.mongodb.org/manual/reference/command/aggregate/ - * @return {Aggregate} this - * @api public - */ - -Aggregate.prototype.option = function(value) { - for (const key in value) { - this.options[key] = value[key]; - } - return this; -}; - -/** - * Sets the cursor option option for the aggregation query (ignored for < 2.6.0). - * Note the different syntax below: .exec() returns a cursor object, and no callback - * is necessary. - * - * ####Example: - * - * var cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec(); - * cursor.eachAsync(function(doc, i) { - * // use doc - * }); - * - * @param {Object} options - * @param {Number} options.batchSize set the cursor batch size - * @param {Boolean} [options.useMongooseAggCursor] use experimental mongoose-specific aggregation cursor (for `eachAsync()` and other query cursor semantics) - * @return {Aggregate} this - * @api public - * @see mongodb http://mongodb.github.io/node-mongodb-native/2.0/api/AggregationCursor.html - */ - -Aggregate.prototype.cursor = function(options) { - if (!this.options) { - this.options = {}; - } - this.options.cursor = options || {}; - return this; -}; - -/** - * Sets an option on this aggregation. This function will be deprecated in a - * future release. Use the [`cursor()`](./api.html#aggregate_Aggregate-cursor), - * [`collation()`](./api.html#aggregate_Aggregate-collation), etc. helpers to - * set individual options, or access `agg.options` directly. - * - * Note that MongoDB aggregations [do **not** support the `noCursorTimeout` flag](https://jira.mongodb.org/browse/SERVER-6036), - * if you try setting that flag with this function you will get a "unrecognized field 'noCursorTimeout'" error. - * - * @param {String} flag - * @param {Boolean} value - * @return {Aggregate} this - * @api public - * @deprecated Use [`.option()`](api.html#aggregate_Aggregate-option) instead. Note that MongoDB aggregations do **not** support a `noCursorTimeout` option. - */ - -Aggregate.prototype.addCursorFlag = util.deprecate(function(flag, value) { - if (!this.options) { - this.options = {}; - } - this.options[flag] = value; - return this; -}, 'Mongoose: `Aggregate#addCursorFlag()` is deprecated, use `option()` instead'); - -/** - * Adds a collation - * - * ####Example: - * - * Model.aggregate(..).collation({ locale: 'en_US', strength: 1 }).exec(); - * - * @param {Object} collation options - * @return {Aggregate} this - * @api public - * @see mongodb http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#aggregate - */ - -Aggregate.prototype.collation = function(collation) { - if (!this.options) { - this.options = {}; - } - this.options.collation = collation; - return this; -}; - -/** - * Combines multiple aggregation pipelines. - * - * ####Example: - * - * Model.aggregate(...) - * .facet({ - * books: [{ groupBy: '$author' }], - * price: [{ $bucketAuto: { groupBy: '$price', buckets: 2 } }] - * }) - * .exec(); - * - * // Output: { books: [...], price: [{...}, {...}] } - * - * @param {Object} facet options - * @return {Aggregate} this - * @see $facet https://docs.mongodb.com/v3.4/reference/operator/aggregation/facet/ - * @api public - */ - -Aggregate.prototype.facet = function(options) { - return this.append({ $facet: options }); -}; - -/** - * Returns the current pipeline - * - * ####Example: - * - * MyModel.aggregate().match({ test: 1 }).pipeline(); // [{ $match: { test: 1 } }] - * - * @return {Array} - * @api public - */ - - -Aggregate.prototype.pipeline = function() { - return this._pipeline; -}; - -/** - * Executes the aggregate pipeline on the currently bound Model. - * - * ####Example: - * - * aggregate.exec(callback); - * - * // Because a promise is returned, the `callback` is optional. - * var promise = aggregate.exec(); - * promise.then(..); - * - * @see Promise #promise_Promise - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Aggregate.prototype.exec = function(callback) { - if (!this._model) { - throw new Error('Aggregate not bound to any Model'); - } - const model = this._model; - const collection = this._model.collection; - - applyGlobalMaxTimeMS(this.options, model); - - if (this.options && this.options.cursor) { - return new AggregationCursor(this); - } - - return promiseOrCallback(callback, cb => { - - prepareDiscriminatorPipeline(this); - - model.hooks.execPre('aggregate', this, error => { - if (error) { - const _opts = { error: error }; - return model.hooks.execPost('aggregate', this, [null], _opts, error => { - cb(error); - }); - } - if (!this._pipeline.length) { - return cb(new Error('Aggregate has empty pipeline')); - } - - const options = utils.clone(this.options || {}); - collection.aggregate(this._pipeline, options, (error, cursor) => { - if (error) { - const _opts = { error: error }; - return model.hooks.execPost('aggregate', this, [null], _opts, error => { - if (error) { - return cb(error); - } - return cb(null); - }); - } - cursor.toArray((error, result) => { - const _opts = { error: error }; - model.hooks.execPost('aggregate', this, [result], _opts, (error, result) => { - if (error) { - return cb(error); - } - - cb(null, result); - }); - }); - }); - }); - }, model.events); -}; - -/** - * Provides promise for aggregate. - * - * ####Example: - * - * Model.aggregate(..).then(successCallback, errorCallback); - * - * @see Promise #promise_Promise - * @param {Function} [resolve] successCallback - * @param {Function} [reject] errorCallback - * @return {Promise} - */ -Aggregate.prototype.then = function(resolve, reject) { - return this.exec().then(resolve, reject); -}; - -/** - * Executes the query returning a `Promise` which will be - * resolved with either the doc(s) or rejected with the error. - * Like [`.then()`](#query_Query-then), but only takes a rejection handler. - * - * @param {Function} [reject] - * @return {Promise} - * @api public - */ - -Aggregate.prototype.catch = function(reject) { - return this.exec().then(null, reject); -}; - -/** - * Returns an asyncIterator for use with [`for/await/of` loops](http://bit.ly/async-iterators) - * You do not need to call this function explicitly, the JavaScript runtime - * will call it for you. - * - * ####Example - * - * const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]); - * for await (const doc of agg) { - * console.log(doc.name); - * } - * - * Node.js 10.x supports async iterators natively without any flags. You can - * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). - * - * **Note:** This function is not set if `Symbol.asyncIterator` is undefined. If - * `Symbol.asyncIterator` is undefined, that means your Node.js version does not - * support async iterators. - * - * @method Symbol.asyncIterator - * @memberOf Aggregate - * @instance - * @api public - */ - -if (Symbol.asyncIterator != null) { - Aggregate.prototype[Symbol.asyncIterator] = function() { - return this.cursor({ useMongooseAggCursor: true }). - exec(). - transformNull(). - map(doc => { - return doc == null ? { done: true } : { value: doc, done: false }; - }); - }; -} - -/*! - * Helpers - */ - -/** - * Checks whether an object is likely a pipeline operator - * - * @param {Object} obj object to check - * @return {Boolean} - * @api private - */ - -function isOperator(obj) { - if (typeof obj !== 'object') { - return false; - } - - const k = Object.keys(obj); - - return k.length === 1 && k.some(key => { return key[0] === '$'; }); -} - -/*! - * Adds the appropriate `$match` pipeline step to the top of an aggregate's - * pipeline, should it's model is a non-root discriminator type. This is - * analogous to the `prepareDiscriminatorCriteria` function in `lib/query.js`. - * - * @param {Aggregate} aggregate Aggregate to prepare - */ - -Aggregate._prepareDiscriminatorPipeline = prepareDiscriminatorPipeline; - -function prepareDiscriminatorPipeline(aggregate) { - const schema = aggregate._model.schema; - const discriminatorMapping = schema && schema.discriminatorMapping; - - if (discriminatorMapping && !discriminatorMapping.isRoot) { - const originalPipeline = aggregate._pipeline; - const discriminatorKey = discriminatorMapping.key; - const discriminatorValue = discriminatorMapping.value; - - // If the first pipeline stage is a match and it doesn't specify a `__t` - // key, add the discriminator key to it. This allows for potential - // aggregation query optimizations not to be disturbed by this feature. - if (originalPipeline[0] && originalPipeline[0].$match && !originalPipeline[0].$match[discriminatorKey]) { - originalPipeline[0].$match[discriminatorKey] = discriminatorValue; - // `originalPipeline` is a ref, so there's no need for - // aggregate._pipeline = originalPipeline - } else if (originalPipeline[0] && originalPipeline[0].$geoNear) { - originalPipeline[0].$geoNear.query = - originalPipeline[0].$geoNear.query || {}; - originalPipeline[0].$geoNear.query[discriminatorKey] = discriminatorValue; - } else { - const match = {}; - match[discriminatorKey] = discriminatorValue; - aggregate._pipeline.unshift({ $match: match }); - } - } -} - -/*! - * Exports - */ - -module.exports = Aggregate; diff --git a/node_modules/mongoose/lib/browser.js b/node_modules/mongoose/lib/browser.js deleted file mode 100644 index b151d51..0000000 --- a/node_modules/mongoose/lib/browser.js +++ /dev/null @@ -1,155 +0,0 @@ -/* eslint-env browser */ - -'use strict'; - -require('./driver').set(require('./drivers/browser')); - -const DocumentProvider = require('./document_provider.js'); -const PromiseProvider = require('./promise_provider'); - -DocumentProvider.setBrowser(true); - -/** - * The Mongoose [Promise](#promise_Promise) constructor. - * - * @method Promise - * @api public - */ - -Object.defineProperty(exports, 'Promise', { - get: function() { - return PromiseProvider.get(); - }, - set: function(lib) { - PromiseProvider.set(lib); - } -}); - -/** - * Storage layer for mongoose promises - * - * @method PromiseProvider - * @api public - */ - -exports.PromiseProvider = PromiseProvider; - -/** - * The [MongooseError](#error_MongooseError) constructor. - * - * @method Error - * @api public - */ - -exports.Error = require('./error/index'); - -/** - * The Mongoose [Schema](#schema_Schema) constructor - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var Schema = mongoose.Schema; - * var CatSchema = new Schema(..); - * - * @method Schema - * @api public - */ - -exports.Schema = require('./schema'); - -/** - * The various Mongoose Types. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var array = mongoose.Types.Array; - * - * ####Types: - * - * - [ObjectId](#types-objectid-js) - * - [Buffer](#types-buffer-js) - * - [SubDocument](#types-embedded-js) - * - [Array](#types-array-js) - * - [DocumentArray](#types-documentarray-js) - * - * Using this exposed access to the `ObjectId` type, we can construct ids on demand. - * - * var ObjectId = mongoose.Types.ObjectId; - * var id1 = new ObjectId; - * - * @property Types - * @api public - */ -exports.Types = require('./types'); - -/** - * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor - * - * @method VirtualType - * @api public - */ -exports.VirtualType = require('./virtualtype'); - -/** - * The various Mongoose SchemaTypes. - * - * ####Note: - * - * _Alias of mongoose.Schema.Types for backwards compatibility._ - * - * @property SchemaTypes - * @see Schema.SchemaTypes #schema_Schema.Types - * @api public - */ - -exports.SchemaType = require('./schematype.js'); - -/** - * Internal utils - * - * @property utils - * @api private - */ - -exports.utils = require('./utils.js'); - -/** - * The Mongoose browser [Document](/api/document.html) constructor. - * - * @method Document - * @api public - */ -exports.Document = DocumentProvider(); - -/** - * Return a new browser model. In the browser, a model is just - * a simplified document with a schema - it does **not** have - * functions like `findOne()`, etc. - * - * @method model - * @api public - * @param {String} name - * @param {Schema} schema - * @return Class - */ -exports.model = function(name, schema) { - class Model extends exports.Document { - constructor(obj, fields) { - super(obj, schema, fields); - } - } - Model.modelName = name; - - return Model; -}; - -/*! - * Module exports. - */ - -if (typeof window !== 'undefined') { - window.mongoose = module.exports; - window.Buffer = Buffer; -} diff --git a/node_modules/mongoose/lib/browserDocument.js b/node_modules/mongoose/lib/browserDocument.js deleted file mode 100644 index a44f307..0000000 --- a/node_modules/mongoose/lib/browserDocument.js +++ /dev/null @@ -1,100 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const NodeJSDocument = require('./document'); -const EventEmitter = require('events').EventEmitter; -const MongooseError = require('./error/index'); -const Schema = require('./schema'); -const ObjectId = require('./types/objectid'); -const ValidationError = MongooseError.ValidationError; -const applyHooks = require('./helpers/model/applyHooks'); -const isObject = require('./helpers/isObject'); - -/** - * Document constructor. - * - * @param {Object} obj the values to set - * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data - * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `init`: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose. - * @event `save`: Emitted when the document is successfully saved - * @api private - */ - -function Document(obj, schema, fields, skipId, skipInit) { - if (!(this instanceof Document)) { - return new Document(obj, schema, fields, skipId, skipInit); - } - - if (isObject(schema) && !schema.instanceOfSchema) { - schema = new Schema(schema); - } - - // When creating EmbeddedDocument, it already has the schema and he doesn't need the _id - schema = this.schema || schema; - - // Generate ObjectId if it is missing, but it requires a scheme - if (!this.schema && schema.options._id) { - obj = obj || {}; - - if (obj._id === undefined) { - obj._id = new ObjectId(); - } - } - - if (!schema) { - throw new MongooseError.MissingSchemaError(); - } - - this.$__setSchema(schema); - - NodeJSDocument.call(this, obj, fields, skipId, skipInit); - - applyHooks(this, schema, { decorateDoc: true }); - - // apply methods - for (const m in schema.methods) { - this[m] = schema.methods[m]; - } - // apply statics - for (const s in schema.statics) { - this[s] = schema.statics[s]; - } -} - -/*! - * Inherit from the NodeJS document - */ - -Document.prototype = Object.create(NodeJSDocument.prototype); -Document.prototype.constructor = Document; - -/*! - * ignore - */ - -Document.events = new EventEmitter(); - -/*! - * Browser doc exposes the event emitter API - */ - -Document.$emitter = new EventEmitter(); - -['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', - 'removeAllListeners', 'addListener'].forEach(function(emitterFn) { - Document[emitterFn] = function() { - return Document.$emitter[emitterFn].apply(Document.$emitter, arguments); - }; -}); - -/*! - * Module exports. - */ - -Document.ValidationError = ValidationError; -module.exports = exports = Document; diff --git a/node_modules/mongoose/lib/cast.js b/node_modules/mongoose/lib/cast.js deleted file mode 100644 index 7e22963..0000000 --- a/node_modules/mongoose/lib/cast.js +++ /dev/null @@ -1,350 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const StrictModeError = require('./error/strict'); -const Types = require('./schema/index'); -const castTextSearch = require('./schema/operators/text'); -const get = require('./helpers/get'); -const isOperator = require('./helpers/query/isOperator'); -const util = require('util'); -const isObject = require('./helpers/isObject'); -const isMongooseObject = require('./helpers/isMongooseObject'); - -const ALLOWED_GEOWITHIN_GEOJSON_TYPES = ['Polygon', 'MultiPolygon']; - -/** - * Handles internal casting for query filters. - * - * @param {Schema} schema - * @param {Object} obj Object to cast - * @param {Object} options the query options - * @param {Query} context passed to setters - * @api private - */ -module.exports = function cast(schema, obj, options, context) { - if (Array.isArray(obj)) { - throw new Error('Query filter must be an object, got an array ', util.inspect(obj)); - } - - // bson 1.x has the unfortunate tendency to remove filters that have a top-level - // `_bsontype` property. But we should still allow ObjectIds because - // `Collection#find()` has a special case to support `find(objectid)`. - // Should remove this when we upgrade to bson 4.x. See gh-8222, gh-8268 - if (obj.hasOwnProperty('_bsontype') && obj._bsontype !== 'ObjectID') { - delete obj._bsontype; - } - - const paths = Object.keys(obj); - let i = paths.length; - let _keys; - let any$conditionals; - let schematype; - let nested; - let path; - let type; - let val; - - options = options || {}; - - while (i--) { - path = paths[i]; - val = obj[path]; - - if (path === '$or' || path === '$nor' || path === '$and') { - let k = val.length; - - while (k--) { - val[k] = cast(schema, val[k], options, context); - } - } else if (path === '$where') { - type = typeof val; - - if (type !== 'string' && type !== 'function') { - throw new Error('Must have a string or function for $where'); - } - - if (type === 'function') { - obj[path] = val.toString(); - } - - continue; - } else if (path === '$elemMatch') { - val = cast(schema, val, options, context); - } else if (path === '$text') { - val = castTextSearch(val, path); - } else { - if (!schema) { - // no casting for Mixed types - continue; - } - - schematype = schema.path(path); - - // Check for embedded discriminator paths - if (!schematype) { - const split = path.split('.'); - let j = split.length; - while (j--) { - const pathFirstHalf = split.slice(0, j).join('.'); - const pathLastHalf = split.slice(j).join('.'); - const _schematype = schema.path(pathFirstHalf); - const discriminatorKey = get(_schematype, 'schema.options.discriminatorKey'); - - // gh-6027: if we haven't found the schematype but this path is - // underneath an embedded discriminator and the embedded discriminator - // key is in the query, use the embedded discriminator schema - if (_schematype != null && - get(_schematype, 'schema.discriminators') != null && - discriminatorKey != null && - pathLastHalf !== discriminatorKey) { - const discriminatorVal = get(obj, pathFirstHalf + '.' + discriminatorKey); - if (discriminatorVal != null) { - schematype = _schematype.schema.discriminators[discriminatorVal]. - path(pathLastHalf); - } - } - } - } - - if (!schematype) { - // Handle potential embedded array queries - const split = path.split('.'); - let j = split.length; - let pathFirstHalf; - let pathLastHalf; - let remainingConds; - - // Find the part of the var path that is a path of the Schema - while (j--) { - pathFirstHalf = split.slice(0, j).join('.'); - schematype = schema.path(pathFirstHalf); - if (schematype) { - break; - } - } - - // If a substring of the input path resolves to an actual real path... - if (schematype) { - // Apply the casting; similar code for $elemMatch in schema/array.js - if (schematype.caster && schematype.caster.schema) { - remainingConds = {}; - pathLastHalf = split.slice(j).join('.'); - remainingConds[pathLastHalf] = val; - obj[path] = cast(schematype.caster.schema, remainingConds, options, context)[pathLastHalf]; - } else { - obj[path] = val; - } - continue; - } - - if (isObject(val)) { - // handle geo schemas that use object notation - // { loc: { long: Number, lat: Number } - - let geo = ''; - if (val.$near) { - geo = '$near'; - } else if (val.$nearSphere) { - geo = '$nearSphere'; - } else if (val.$within) { - geo = '$within'; - } else if (val.$geoIntersects) { - geo = '$geoIntersects'; - } else if (val.$geoWithin) { - geo = '$geoWithin'; - } - - if (geo) { - const numbertype = new Types.Number('__QueryCasting__'); - let value = val[geo]; - - if (val.$maxDistance != null) { - val.$maxDistance = numbertype.castForQueryWrapper({ - val: val.$maxDistance, - context: context - }); - } - if (val.$minDistance != null) { - val.$minDistance = numbertype.castForQueryWrapper({ - val: val.$minDistance, - context: context - }); - } - - if (geo === '$within') { - const withinType = value.$center - || value.$centerSphere - || value.$box - || value.$polygon; - - if (!withinType) { - throw new Error('Bad $within parameter: ' + JSON.stringify(val)); - } - - value = withinType; - } else if (geo === '$near' && - typeof value.type === 'string' && Array.isArray(value.coordinates)) { - // geojson; cast the coordinates - value = value.coordinates; - } else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') && - value.$geometry && typeof value.$geometry.type === 'string' && - Array.isArray(value.$geometry.coordinates)) { - if (value.$maxDistance != null) { - value.$maxDistance = numbertype.castForQueryWrapper({ - val: value.$maxDistance, - context: context - }); - } - if (value.$minDistance != null) { - value.$minDistance = numbertype.castForQueryWrapper({ - val: value.$minDistance, - context: context - }); - } - if (isMongooseObject(value.$geometry)) { - value.$geometry = value.$geometry.toObject({ - transform: false, - virtuals: false - }); - } - value = value.$geometry.coordinates; - } else if (geo === '$geoWithin') { - if (value.$geometry) { - if (isMongooseObject(value.$geometry)) { - value.$geometry = value.$geometry.toObject({ virtuals: false }); - } - const geoWithinType = value.$geometry.type; - if (ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf(geoWithinType) === -1) { - throw new Error('Invalid geoJSON type for $geoWithin "' + - geoWithinType + '", must be "Polygon" or "MultiPolygon"'); - } - value = value.$geometry.coordinates; - } else { - value = value.$box || value.$polygon || value.$center || - value.$centerSphere; - if (isMongooseObject(value)) { - value = value.toObject({ virtuals: false }); - } - } - } - - _cast(value, numbertype, context); - continue; - } - } - - if (schema.nested[path]) { - continue; - } - if (options.upsert && options.strict) { - if (options.strict === 'throw') { - throw new StrictModeError(path); - } - throw new StrictModeError(path, 'Path "' + path + '" is not in ' + - 'schema, strict mode is `true`, and upsert is `true`.'); - } else if (options.strictQuery === 'throw') { - throw new StrictModeError(path, 'Path "' + path + '" is not in ' + - 'schema and strictQuery is \'throw\'.'); - } else if (options.strictQuery) { - delete obj[path]; - } - } else if (val == null) { - continue; - } else if (val.constructor.name === 'Object') { - any$conditionals = Object.keys(val).some(isOperator); - - if (!any$conditionals) { - obj[path] = schematype.castForQueryWrapper({ - val: val, - context: context - }); - } else { - const ks = Object.keys(val); - let $cond; - - let k = ks.length; - - while (k--) { - $cond = ks[k]; - nested = val[$cond]; - - if ($cond === '$not') { - if (nested && schematype && !schematype.caster) { - _keys = Object.keys(nested); - if (_keys.length && isOperator(_keys[0])) { - for (const key in nested) { - nested[key] = schematype.castForQueryWrapper({ - $conditional: key, - val: nested[key], - context: context - }); - } - } else { - val[$cond] = schematype.castForQueryWrapper({ - $conditional: $cond, - val: nested, - context: context - }); - } - continue; - } - cast(schematype.caster ? schematype.caster.schema : schema, nested, options, context); - } else { - val[$cond] = schematype.castForQueryWrapper({ - $conditional: $cond, - val: nested, - context: context - }); - } - } - } - } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1) { - const casted = []; - const valuesArray = val; - - for (const _val of valuesArray) { - casted.push(schematype.castForQueryWrapper({ - val: _val, - context: context - })); - } - - obj[path] = { $in: casted }; - } else { - obj[path] = schematype.castForQueryWrapper({ - val: val, - context: context - }); - } - } - } - - return obj; -}; - -function _cast(val, numbertype, context) { - if (Array.isArray(val)) { - val.forEach(function(item, i) { - if (Array.isArray(item) || isObject(item)) { - return _cast(item, numbertype, context); - } - val[i] = numbertype.castForQueryWrapper({ val: item, context: context }); - }); - } else { - const nearKeys = Object.keys(val); - let nearLen = nearKeys.length; - while (nearLen--) { - const nkey = nearKeys[nearLen]; - const item = val[nkey]; - if (Array.isArray(item) || isObject(item)) { - _cast(item, numbertype, context); - val[nkey] = item; - } else { - val[nkey] = numbertype.castForQuery({ val: item, context: context }); - } - } - } -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/cast/boolean.js b/node_modules/mongoose/lib/cast/boolean.js deleted file mode 100644 index 4843e1f..0000000 --- a/node_modules/mongoose/lib/cast/boolean.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -const CastError = require('../error/cast'); - -/*! - * Given a value, cast it to a boolean, or throw a `CastError` if the value - * cannot be casted. `null` and `undefined` are considered valid. - * - * @param {Any} value - * @param {String} [path] optional the path to set on the CastError - * @return {Boolean|null|undefined} - * @throws {CastError} if `value` is not one of the allowed values - * @api private - */ - -module.exports = function castBoolean(value, path) { - if (value == null) { - return value; - } - - if (module.exports.convertToTrue.has(value)) { - return true; - } - if (module.exports.convertToFalse.has(value)) { - return false; - } - throw new CastError('boolean', value, path); -}; - -module.exports.convertToTrue = new Set([true, 'true', 1, '1', 'yes']); -module.exports.convertToFalse = new Set([false, 'false', 0, '0', 'no']); diff --git a/node_modules/mongoose/lib/cast/date.js b/node_modules/mongoose/lib/cast/date.js deleted file mode 100644 index ac17006..0000000 --- a/node_modules/mongoose/lib/cast/date.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -const assert = require('assert'); - -module.exports = function castDate(value) { - // Support empty string because of empty form values. Originally introduced - // in https://github.com/Automattic/mongoose/commit/efc72a1898fc3c33a319d915b8c5463a22938dfe - if (value == null || value === '') { - return null; - } - - if (value instanceof Date) { - assert.ok(!isNaN(value.valueOf())); - - return value; - } - - let date; - - assert.ok(typeof value !== 'boolean'); - - if (value instanceof Number || typeof value === 'number') { - date = new Date(value); - } else if (typeof value === 'string' && !isNaN(Number(value)) && (Number(value) >= 275761 || Number(value) < -271820)) { - // string representation of milliseconds take this path - date = new Date(Number(value)); - } else if (typeof value.valueOf === 'function') { - // support for moment.js. This is also the path strings will take because - // strings have a `valueOf()` - date = new Date(value.valueOf()); - } else { - // fallback - date = new Date(value); - } - - if (!isNaN(date.valueOf())) { - return date; - } - - assert.ok(false); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/cast/decimal128.js b/node_modules/mongoose/lib/cast/decimal128.js deleted file mode 100644 index bfb1578..0000000 --- a/node_modules/mongoose/lib/cast/decimal128.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -const Decimal128Type = require('../types/decimal128'); -const assert = require('assert'); - -module.exports = function castDecimal128(value) { - if (value == null) { - return value; - } - - if (typeof value === 'object' && typeof value.$numberDecimal === 'string') { - return Decimal128Type.fromString(value.$numberDecimal); - } - - if (value instanceof Decimal128Type) { - return value; - } - - if (typeof value === 'string') { - return Decimal128Type.fromString(value); - } - - if (Buffer.isBuffer(value)) { - return new Decimal128Type(value); - } - - if (typeof value === 'number') { - return Decimal128Type.fromString(String(value)); - } - - if (typeof value.valueOf === 'function' && typeof value.valueOf() === 'string') { - return Decimal128Type.fromString(value.valueOf()); - } - - assert.ok(false); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/cast/number.js b/node_modules/mongoose/lib/cast/number.js deleted file mode 100644 index 7cd7f84..0000000 --- a/node_modules/mongoose/lib/cast/number.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -const assert = require('assert'); - -/*! - * Given a value, cast it to a number, or throw a `CastError` if the value - * cannot be casted. `null` and `undefined` are considered valid. - * - * @param {Any} value - * @param {String} [path] optional the path to set on the CastError - * @return {Boolean|null|undefined} - * @throws {Error} if `value` is not one of the allowed values - * @api private - */ - -module.exports = function castNumber(val) { - if (val == null) { - return val; - } - if (val === '') { - return null; - } - - if (typeof val === 'string' || typeof val === 'boolean') { - val = Number(val); - } - - assert.ok(!isNaN(val)); - if (val instanceof Number) { - return val.valueOf(); - } - if (typeof val === 'number') { - return val; - } - if (!Array.isArray(val) && typeof val.valueOf === 'function') { - return Number(val.valueOf()); - } - if (val.toString && !Array.isArray(val) && val.toString() == Number(val)) { - return Number(val); - } - - assert.ok(false); -}; diff --git a/node_modules/mongoose/lib/cast/objectid.js b/node_modules/mongoose/lib/cast/objectid.js deleted file mode 100644 index 67cffb5..0000000 --- a/node_modules/mongoose/lib/cast/objectid.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -const ObjectId = require('../driver').get().ObjectId; -const assert = require('assert'); - -module.exports = function castObjectId(value) { - if (value == null) { - return value; - } - - if (value instanceof ObjectId) { - return value; - } - - if (value._id) { - if (value._id instanceof ObjectId) { - return value._id; - } - if (value._id.toString instanceof Function) { - return new ObjectId(value._id.toString()); - } - } - - if (value.toString instanceof Function) { - return new ObjectId(value.toString()); - } - - assert.ok(false); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/cast/string.js b/node_modules/mongoose/lib/cast/string.js deleted file mode 100644 index 4d89f8e..0000000 --- a/node_modules/mongoose/lib/cast/string.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -const CastError = require('../error/cast'); - -/*! - * Given a value, cast it to a string, or throw a `CastError` if the value - * cannot be casted. `null` and `undefined` are considered valid. - * - * @param {Any} value - * @param {String} [path] optional the path to set on the CastError - * @return {string|null|undefined} - * @throws {CastError} - * @api private - */ - -module.exports = function castString(value, path) { - // If null or undefined - if (value == null) { - return value; - } - - // handle documents being passed - if (value._id && typeof value._id === 'string') { - return value._id; - } - - // Re: gh-647 and gh-3030, we're ok with casting using `toString()` - // **unless** its the default Object.toString, because "[object Object]" - // doesn't really qualify as useful data - if (value.toString && - value.toString !== Object.prototype.toString && - !Array.isArray(value)) { - return value.toString(); - } - - throw new CastError('string', value, path); -}; diff --git a/node_modules/mongoose/lib/collection.js b/node_modules/mongoose/lib/collection.js deleted file mode 100644 index b537094..0000000 --- a/node_modules/mongoose/lib/collection.js +++ /dev/null @@ -1,269 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const EventEmitter = require('events').EventEmitter; -const STATES = require('./connectionstate'); -const immediate = require('./helpers/immediate'); - -/** - * Abstract Collection constructor - * - * This is the base class that drivers inherit from and implement. - * - * @param {String} name name of the collection - * @param {Connection} conn A MongooseConnection instance - * @param {Object} opts optional collection options - * @api public - */ - -function Collection(name, conn, opts) { - if (opts === void 0) { - opts = {}; - } - if (opts.capped === void 0) { - opts.capped = {}; - } - - opts.bufferCommands = undefined === opts.bufferCommands - ? true - : opts.bufferCommands; - - if (typeof opts.capped === 'number') { - opts.capped = { size: opts.capped }; - } - - this.opts = opts; - this.name = name; - this.collectionName = name; - this.conn = conn; - this.queue = []; - this.buffer = this.opts.bufferCommands; - this.emitter = new EventEmitter(); - - if (STATES.connected === this.conn.readyState) { - this.onOpen(); - } -} - -/** - * The collection name - * - * @api public - * @property name - */ - -Collection.prototype.name; - -/** - * The collection name - * - * @api public - * @property collectionName - */ - -Collection.prototype.collectionName; - -/** - * The Connection instance - * - * @api public - * @property conn - */ - -Collection.prototype.conn; - -/** - * Called when the database connects - * - * @api private - */ - -Collection.prototype.onOpen = function() { - this.buffer = false; - immediate(() => this.doQueue()); -}; - -/** - * Called when the database disconnects - * - * @api private - */ - -Collection.prototype.onClose = function(force) { - if (this.opts.bufferCommands && !force) { - this.buffer = true; - } -}; - -/** - * Queues a method for later execution when its - * database connection opens. - * - * @param {String} name name of the method to queue - * @param {Array} args arguments to pass to the method when executed - * @api private - */ - -Collection.prototype.addQueue = function(name, args) { - this.queue.push([name, args]); - return this; -}; - -/** - * Executes all queued methods and clears the queue. - * - * @api private - */ - -Collection.prototype.doQueue = function() { - for (const method of this.queue) { - if (typeof method[0] === 'function') { - method[0].apply(this, method[1]); - } else { - this[method[0]].apply(this, method[1]); - } - } - this.queue = []; - const _this = this; - process.nextTick(function() { - _this.emitter.emit('queue'); - }); - return this; -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.ensureIndex = function() { - throw new Error('Collection#ensureIndex unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.createIndex = function() { - throw new Error('Collection#ensureIndex unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findAndModify = function() { - throw new Error('Collection#findAndModify unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findOneAndUpdate = function() { - throw new Error('Collection#findOneAndUpdate unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findOneAndDelete = function() { - throw new Error('Collection#findOneAndDelete unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findOneAndReplace = function() { - throw new Error('Collection#findOneAndReplace unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findOne = function() { - throw new Error('Collection#findOne unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.find = function() { - throw new Error('Collection#find unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.insert = function() { - throw new Error('Collection#insert unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.insertOne = function() { - throw new Error('Collection#insertOne unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.insertMany = function() { - throw new Error('Collection#insertMany unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.save = function() { - throw new Error('Collection#save unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.update = function() { - throw new Error('Collection#update unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.getIndexes = function() { - throw new Error('Collection#getIndexes unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.mapReduce = function() { - throw new Error('Collection#mapReduce unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.watch = function() { - throw new Error('Collection#watch unimplemented by driver'); -}; - -/*! - * Module exports. - */ - -module.exports = Collection; diff --git a/node_modules/mongoose/lib/connection.js b/node_modules/mongoose/lib/connection.js deleted file mode 100644 index 12f0517..0000000 --- a/node_modules/mongoose/lib/connection.js +++ /dev/null @@ -1,1286 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const ChangeStream = require('./cursor/ChangeStream'); -const EventEmitter = require('events').EventEmitter; -const Schema = require('./schema'); -const Collection = require('./driver').get().Collection; -const STATES = require('./connectionstate'); -const MongooseError = require('./error/index'); -const PromiseProvider = require('./promise_provider'); -const ServerSelectionError = require('./error/serverSelection'); -const applyPlugins = require('./helpers/schema/applyPlugins'); -const promiseOrCallback = require('./helpers/promiseOrCallback'); -const get = require('./helpers/get'); -const immediate = require('./helpers/immediate'); -const mongodb = require('mongodb'); -const pkg = require('../package.json'); -const utils = require('./utils'); - -const parseConnectionString = require('mongodb/lib/core').parseConnectionString; - -let id = 0; - -/*! - * A list of authentication mechanisms that don't require a password for authentication. - * This is used by the authMechanismDoesNotRequirePassword method. - * - * @api private - */ -const noPasswordAuthMechanisms = [ - 'MONGODB-X509' -]; - -/** - * Connection constructor - * - * For practical reasons, a Connection equals a Db. - * - * @param {Mongoose} base a mongoose instance - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `connecting`: Emitted when `connection.openUri()` is executed on this connection. - * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios. - * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models. - * @event `disconnecting`: Emitted when `connection.close()` was executed. - * @event `disconnected`: Emitted after getting disconnected from the db. - * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models. - * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successful connection. - * @event `error`: Emitted when an error occurs on this connection. - * @event `fullsetup`: Emitted after the driver has connected to primary and all secondaries if specified in the connection string. - * @api public - */ - -function Connection(base) { - this.base = base; - this.collections = {}; - this.models = {}; - this.config = { autoIndex: true }; - this.replica = false; - this.options = null; - this.otherDbs = []; // FIXME: To be replaced with relatedDbs - this.relatedDbs = {}; // Hashmap of other dbs that share underlying connection - this.states = STATES; - this._readyState = STATES.disconnected; - this._closeCalled = false; - this._hasOpened = false; - this.plugins = []; - this.id = id++; -} - -/*! - * Inherit from EventEmitter - */ - -Connection.prototype.__proto__ = EventEmitter.prototype; - -/** - * Connection ready state - * - * - 0 = disconnected - * - 1 = connected - * - 2 = connecting - * - 3 = disconnecting - * - * Each state change emits its associated event name. - * - * ####Example - * - * conn.on('connected', callback); - * conn.on('disconnected', callback); - * - * @property readyState - * @memberOf Connection - * @instance - * @api public - */ - -Object.defineProperty(Connection.prototype, 'readyState', { - get: function() { - return this._readyState; - }, - set: function(val) { - if (!(val in STATES)) { - throw new Error('Invalid connection state: ' + val); - } - - if (this._readyState !== val) { - this._readyState = val; - // [legacy] loop over the otherDbs on this connection and change their state - for (const db of this.otherDbs) { - db.readyState = val; - } - - // loop over relatedDbs on this connection and change their state - for (const k in this.relatedDbs) { - this.relatedDbs[k].readyState = val; - } - - if (STATES.connected === val) { - this._hasOpened = true; - } - - this.emit(STATES[val]); - } - } -}); - -/** - * Gets the value of the option `key`. Equivalent to `conn.options[key]` - * - * ####Example: - * - * conn.get('test'); // returns the 'test' value - * - * @param {String} key - * @method get - * @api public - */ - -Connection.prototype.get = function(key) { - return get(this.options, key); -}; - -/** - * Sets the value of the option `key`. Equivalent to `conn.options[key] = val` - * - * Supported options include: - * - * - `maxTimeMS`: Set [`maxTimeMS`](/docs/api.html#query_Query-maxTimeMS) for all queries on this connection. - * - `useFindAndModify`: Set to `false` to work around the [`findAndModify()` deprecation warning](/docs/deprecations.html#findandmodify) - * - * ####Example: - * - * conn.set('test', 'foo'); - * conn.get('test'); // 'foo' - * conn.options.test; // 'foo' - * - * @param {String} key - * @param {Any} val - * @method set - * @api public - */ - -Connection.prototype.set = function(key, val) { - this.options = this.options || {}; - this.options[key] = val; - return val; -}; - -/** - * A hash of the collections associated with this connection - * - * @property collections - * @memberOf Connection - * @instance - * @api public - */ - -Connection.prototype.collections; - -/** - * The name of the database this connection points to. - * - * ####Example - * - * mongoose.createConnection('mongodb://localhost:27017/mydb').name; // "mydb" - * - * @property name - * @memberOf Connection - * @instance - * @api public - */ - -Connection.prototype.name; - -/** - * A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing - * a map from model names to models. Contains all models that have been - * added to this connection using [`Connection#model()`](/docs/api/connection.html#connection_Connection-model). - * - * ####Example - * - * const conn = mongoose.createConnection(); - * const Test = conn.model('Test', mongoose.Schema({ name: String })); - * - * Object.keys(conn.models).length; // 1 - * conn.models.Test === Test; // true - * - * @property models - * @memberOf Connection - * @instance - * @api public - */ - -Connection.prototype.models; - -/** - * A number identifier for this connection. Used for debugging when - * you have [multiple connections](/docs/connections.html#multiple_connections). - * - * ####Example - * - * // The default connection has `id = 0` - * mongoose.connection.id; // 0 - * - * // If you create a new connection, Mongoose increments id - * const conn = mongoose.createConnection(); - * conn.id; // 1 - * - * @property id - * @memberOf Connection - * @instance - * @api public - */ - -Connection.prototype.id; - -/** - * The plugins that will be applied to all models created on this connection. - * - * ####Example: - * - * const db = mongoose.createConnection('mongodb://localhost:27017/mydb'); - * db.plugin(() => console.log('Applied')); - * db.plugins.length; // 1 - * - * db.model('Test', new Schema({})); // Prints "Applied" - * - * @property plugins - * @memberOf Connection - * @instance - * @api public - */ - -Object.defineProperty(Connection.prototype, 'plugins', { - configurable: false, - enumerable: true, - writable: true -}); - -/** - * The host name portion of the URI. If multiple hosts, such as a replica set, - * this will contain the first host name in the URI - * - * ####Example - * - * mongoose.createConnection('mongodb://localhost:27017/mydb').host; // "localhost" - * - * @property host - * @memberOf Connection - * @instance - * @api public - */ - -Object.defineProperty(Connection.prototype, 'host', { - configurable: true, - enumerable: true, - writable: true -}); - -/** - * The port portion of the URI. If multiple hosts, such as a replica set, - * this will contain the port from the first host name in the URI. - * - * ####Example - * - * mongoose.createConnection('mongodb://localhost:27017/mydb').port; // 27017 - * - * @property port - * @memberOf Connection - * @instance - * @api public - */ - -Object.defineProperty(Connection.prototype, 'port', { - configurable: true, - enumerable: true, - writable: true -}); - -/** - * The username specified in the URI - * - * ####Example - * - * mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').user; // "val" - * - * @property user - * @memberOf Connection - * @instance - * @api public - */ - -Object.defineProperty(Connection.prototype, 'user', { - configurable: true, - enumerable: true, - writable: true -}); - -/** - * The password specified in the URI - * - * ####Example - * - * mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').pass; // "psw" - * - * @property pass - * @memberOf Connection - * @instance - * @api public - */ - -Object.defineProperty(Connection.prototype, 'pass', { - configurable: true, - enumerable: true, - writable: true -}); - -/** - * The mongodb.Db instance, set when the connection is opened - * - * @property db - * @memberOf Connection - * @instance - * @api public - */ - -Connection.prototype.db; - -/** - * A hash of the global options that are associated with this connection - * - * @property config - * @memberOf Connection - * @instance - * @api public - */ - -Connection.prototype.config; - -/** - * Helper for `createCollection()`. Will explicitly create the given collection - * with specified options. Used to create [capped collections](https://docs.mongodb.com/manual/core/capped-collections/) - * and [views](https://docs.mongodb.com/manual/core/views/) from mongoose. - * - * Options are passed down without modification to the [MongoDB driver's `createCollection()` function](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection) - * - * @method createCollection - * @param {string} collection The collection to create - * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/2.2/api/Db.html#createCollection) - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Connection.prototype.createCollection = _wrapConnHelper(function createCollection(collection, options, cb) { - if (typeof options === 'function') { - cb = options; - options = {}; - } - this.db.createCollection(collection, options, cb); -}); - -/** - * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) - * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), - * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). - * - * ####Example: - * - * const session = await conn.startSession(); - * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session }); - * await doc.remove(); - * // `doc` will always be null, even if reading from a replica set - * // secondary. Without causal consistency, it is possible to - * // get a doc back from the below query if the query reads from a - * // secondary that is experiencing replication lag. - * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' }); - * - * - * @method startSession - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) - * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency - * @param {Function} [callback] - * @return {Promise} promise that resolves to a MongoDB driver `ClientSession` - * @api public - */ - -Connection.prototype.startSession = _wrapConnHelper(function startSession(options, cb) { - if (typeof options === 'function') { - cb = options; - options = null; - } - const session = this.client.startSession(options); - cb(null, session); -}); - -/** - * Helper for `dropCollection()`. Will delete the given collection, including - * all documents and indexes. - * - * @method dropCollection - * @param {string} collection The collection to delete - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Connection.prototype.dropCollection = _wrapConnHelper(function dropCollection(collection, cb) { - this.db.dropCollection(collection, cb); -}); - -/** - * Helper for `dropDatabase()`. Deletes the given database, including all - * collections, documents, and indexes. - * - * ####Example: - * - * const conn = mongoose.createConnection('mongodb://localhost:27017/mydb'); - * // Deletes the entire 'mydb' database - * await conn.dropDatabase(); - * - * @method dropDatabase - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Connection.prototype.dropDatabase = _wrapConnHelper(function dropDatabase(cb) { - // If `dropDatabase()` is called, this model's collection will not be - // init-ed. It is sufficiently common to call `dropDatabase()` after - // `mongoose.connect()` but before creating models that we want to - // support this. See gh-6967 - for (const name of Object.keys(this.models)) { - delete this.models[name].$init; - } - this.db.dropDatabase(cb); -}); - -/*! - * ignore - */ - -function _wrapConnHelper(fn) { - return function() { - const cb = arguments.length > 0 ? arguments[arguments.length - 1] : null; - const argsWithoutCb = typeof cb === 'function' ? - Array.prototype.slice.call(arguments, 0, arguments.length - 1) : - Array.prototype.slice.call(arguments); - const disconnectedError = new MongooseError('Connection ' + this.id + - ' was disconnected when calling `' + fn.name + '`'); - return promiseOrCallback(cb, cb => { - // Make it ok to call collection helpers before `mongoose.connect()` - // as long as `mongoose.connect()` is called on the same tick. - // Re: gh-8534 - immediate(() => { - if (this.readyState === STATES.connecting) { - this.once('open', function() { - fn.apply(this, argsWithoutCb.concat([cb])); - }); - } else if (this.readyState === STATES.disconnected && this.db == null) { - cb(disconnectedError); - } else { - fn.apply(this, argsWithoutCb.concat([cb])); - } - }); - }); - }; -} - -/** - * error - * - * Graceful error handling, passes error to callback - * if available, else emits error on the connection. - * - * @param {Error} err - * @param {Function} callback optional - * @api private - */ - -Connection.prototype.error = function(err, callback) { - if (callback) { - callback(err); - return null; - } - if (this.listeners('error').length > 0) { - this.emit('error', err); - } - return Promise.reject(err); -}; - -/** - * Called when the connection is opened - * - * @api private - */ - -Connection.prototype.onOpen = function() { - this.readyState = STATES.connected; - - // avoid having the collection subscribe to our event emitter - // to prevent 0.3 warning - for (const i in this.collections) { - if (utils.object.hasOwnProperty(this.collections, i)) { - this.collections[i].onOpen(); - } - } - - this.emit('open'); -}; - -/** - * Opens the connection with a URI using `MongoClient.connect()`. - * - * @param {String} uri The URI to connect with. - * @param {Object} [options] Passed on to http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect - * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. - * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string. - * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. - * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. - * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. - * @param {Boolean} [options.useNewUrlParser=false] False by default. Set to `true` to opt in to the MongoDB driver's new URL parser logic. - * @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to `true` to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine. - * @param {Boolean} [options.useCreateIndex=true] Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](/docs/deprecations.html#ensureindex) for automatic index builds via [`Model.init()`](/docs/api.html#model_Model.init). - * @param {Boolean} [options.useFindAndModify=true] True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`. - * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. - * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above. - * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html). - * @param {Number} [options.poolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). - * @param {Number} [options.bufferMaxEntries] This option does nothing if `useUnifiedTopology` is set. The MongoDB driver also has its own buffering mechanism that kicks in when the driver is disconnected. Set this option to 0 and set `bufferCommands` to `false` on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection. - * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). - * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes. - * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both. - * @param {Function} [callback] - * @returns {Connection} this - * @api public - */ - -Connection.prototype.openUri = function(uri, options, callback) { - this.readyState = STATES.connecting; - this._closeCalled = false; - - if (typeof options === 'function') { - callback = options; - options = null; - } - - if (['string', 'number'].indexOf(typeof options) !== -1) { - throw new MongooseError('Mongoose 5.x no longer supports ' + - '`mongoose.connect(host, dbname, port)` or ' + - '`mongoose.createConnection(host, dbname, port)`. See ' + - 'http://mongoosejs.com/docs/connections.html for supported connection syntax'); - } - - if (typeof uri !== 'string') { - throw new MongooseError('The `uri` parameter to `openUri()` must be a ' + - `string, got "${typeof uri}". Make sure the first parameter to ` + - '`mongoose.connect()` or `mongoose.createConnection()` is a string.'); - } - - if (callback != null && typeof callback !== 'function') { - throw new MongooseError('3rd parameter to `mongoose.connect()` or ' + - '`mongoose.createConnection()` must be a function, got "' + - typeof callback + '"'); - } - - const Promise = PromiseProvider.get(); - const _this = this; - - if (options) { - options = utils.clone(options); - const autoIndex = options.config && options.config.autoIndex != null ? - options.config.autoIndex : - options.autoIndex; - if (autoIndex != null) { - this.config.autoIndex = autoIndex !== false; - delete options.config; - delete options.autoIndex; - } - - if ('autoCreate' in options) { - this.config.autoCreate = !!options.autoCreate; - delete options.autoCreate; - } - if ('useCreateIndex' in options) { - this.config.useCreateIndex = !!options.useCreateIndex; - delete options.useCreateIndex; - } - - if ('useFindAndModify' in options) { - this.config.useFindAndModify = !!options.useFindAndModify; - delete options.useFindAndModify; - } - - // Backwards compat - if (options.user || options.pass) { - options.auth = options.auth || {}; - options.auth.user = options.user; - options.auth.password = options.pass; - - this.user = options.user; - this.pass = options.pass; - } - delete options.user; - delete options.pass; - - if (options.bufferCommands != null) { - options.bufferMaxEntries = 0; - this.config.bufferCommands = options.bufferCommands; - delete options.bufferCommands; - } - - if (options.useMongoClient != null) { - handleUseMongoClient(options); - } - } else { - options = {}; - } - - this._connectionOptions = options; - const dbName = options.dbName; - if (dbName != null) { - this.$dbName = dbName; - } - delete options.dbName; - - if (!('promiseLibrary' in options)) { - options.promiseLibrary = PromiseProvider.get(); - } - if (!('useNewUrlParser' in options)) { - if ('useNewUrlParser' in this.base.options) { - options.useNewUrlParser = this.base.options.useNewUrlParser; - } else { - options.useNewUrlParser = false; - } - } - if (!utils.hasUserDefinedProperty(options, 'useUnifiedTopology')) { - if (utils.hasUserDefinedProperty(this.base.options, 'useUnifiedTopology')) { - options.useUnifiedTopology = this.base.options.useUnifiedTopology; - } else { - options.useUnifiedTopology = false; - } - } - if (!utils.hasUserDefinedProperty(options, 'driverInfo')) { - options.driverInfo = { - name: 'Mongoose', - version: pkg.version - }; - } - - const parsePromise = new Promise((resolve, reject) => { - parseConnectionString(uri, options, (err, parsed) => { - if (err) { - return reject(err); - } - if (dbName) { - this.name = dbName; - } else if (parsed.defaultDatabase) { - this.name = parsed.defaultDatabase; - } else { - this.name = get(parsed, 'auth.db', null); - } - this.host = get(parsed, 'hosts.0.host', 'localhost'); - this.port = get(parsed, 'hosts.0.port', 27017); - this.user = this.user || get(parsed, 'auth.username'); - this.pass = this.pass || get(parsed, 'auth.password'); - resolve(); - }); - }); - - const _handleReconnect = () => { - // If we aren't disconnected, we assume this reconnect is due to a - // socket timeout. If there's no activity on a socket for - // `socketTimeoutMS`, the driver will attempt to reconnect and emit - // this event. - if (_this.readyState !== STATES.connected) { - _this.readyState = STATES.connected; - _this.emit('reconnect'); - _this.emit('reconnected'); - } - }; - - const promise = new Promise((resolve, reject) => { - const client = new mongodb.MongoClient(uri, options); - _this.client = client; - client.connect(function(error) { - if (error) { - _this.readyState = STATES.disconnected; - return reject(error); - } - - const db = dbName != null ? client.db(dbName) : client.db(); - _this.db = db; - - // `useUnifiedTopology` events - const type = get(db, 's.topology.s.description.type', ''); - if (options.useUnifiedTopology) { - if (type === 'Single') { - const server = Array.from(db.s.topology.s.servers.values())[0]; - - server.s.topology.on('serverHeartbeatSucceeded', () => { - _handleReconnect(); - }); - server.s.pool.on('reconnect', () => { - _handleReconnect(); - }); - client.on('serverDescriptionChanged', ev => { - const newDescription = ev.newDescription; - if (newDescription.type === 'Standalone') { - _handleReconnect(); - } else { - _this.readyState = STATES.disconnected; - } - }); - } else if (type.startsWith('ReplicaSet')) { - client.on('topologyDescriptionChanged', ev => { - // Emit disconnected if we've lost connectivity to _all_ servers - // in the replica set. - const description = ev.newDescription; - const servers = Array.from(ev.newDescription.servers.values()); - const allServersDisconnected = description.type === 'ReplicaSetNoPrimary' && - servers.reduce((cur, d) => cur || d.type === 'Unknown', false); - if (_this.readyState === STATES.connected && allServersDisconnected) { - // Implicitly emits 'disconnected' - _this.readyState = STATES.disconnected; - } else if (_this.readyState === STATES.disconnected && !allServersDisconnected) { - _handleReconnect(); - } - }); - - db.on('close', function() { - const type = get(db, 's.topology.s.description.type', ''); - if (type !== 'ReplicaSetWithPrimary') { - // Implicitly emits 'disconnected' - _this.readyState = STATES.disconnected; - } - }); - } - } - - // Backwards compat for mongoose 4.x - db.on('reconnect', function() { - _handleReconnect(); - }); - db.s.topology.on('reconnectFailed', function() { - _this.emit('reconnectFailed'); - }); - - if (!options.useUnifiedTopology) { - db.s.topology.on('left', function(data) { - _this.emit('left', data); - }); - } - db.s.topology.on('joined', function(data) { - _this.emit('joined', data); - }); - db.s.topology.on('fullsetup', function(data) { - _this.emit('fullsetup', data); - }); - if (get(db, 's.topology.s.coreTopology.s.pool') != null) { - db.s.topology.s.coreTopology.s.pool.on('attemptReconnect', function() { - _this.emit('attemptReconnect'); - }); - } - if (!options.useUnifiedTopology || !type.startsWith('ReplicaSet')) { - db.on('close', function() { - // Implicitly emits 'disconnected' - _this.readyState = STATES.disconnected; - }); - } - - if (!options.useUnifiedTopology) { - client.on('left', function() { - if (_this.readyState === STATES.connected && - get(db, 's.topology.s.coreTopology.s.replicaSetState.topologyType') === 'ReplicaSetNoPrimary') { - _this.readyState = STATES.disconnected; - } - }); - } - - db.on('timeout', function() { - _this.emit('timeout'); - }); - - delete _this.then; - delete _this.catch; - _this.readyState = STATES.connected; - - for (const i in _this.collections) { - if (utils.object.hasOwnProperty(_this.collections, i)) { - _this.collections[i].onOpen(); - } - } - - resolve(_this); - _this.emit('open'); - }); - }); - - const serverSelectionError = new ServerSelectionError(); - this.$initialConnection = Promise.all([promise, parsePromise]). - then(res => res[0]). - catch(err => { - if (err != null && err.name === 'MongoServerSelectionError') { - err = serverSelectionError.assimilateError(err); - } - - if (this.listeners('error').length > 0) { - process.nextTick(() => this.emit('error', err)); - } - throw err; - }); - this.then = function(resolve, reject) { - return this.$initialConnection.then(resolve, reject); - }; - this.catch = function(reject) { - return this.$initialConnection.catch(reject); - }; - - if (callback != null) { - this.$initialConnection = this.$initialConnection.then( - () => callback(null, this), - err => callback(err) - ); - } - - return this; -}; - -/*! - * ignore - */ - -const handleUseMongoClient = function handleUseMongoClient(options) { - console.warn('WARNING: The `useMongoClient` option is no longer ' + - 'necessary in mongoose 5.x, please remove it.'); - const stack = new Error().stack; - console.warn(stack.substr(stack.indexOf('\n') + 1)); - delete options.useMongoClient; -}; - -/** - * Closes the connection - * - * @param {Boolean} [force] optional - * @param {Function} [callback] optional - * @return {Promise} - * @api public - */ - -Connection.prototype.close = function(force, callback) { - if (typeof force === 'function') { - callback = force; - force = false; - } - - this.$wasForceClosed = !!force; - - return promiseOrCallback(callback, cb => { - this._close(force, cb); - }); -}; - -/** - * Handles closing the connection - * - * @param {Boolean} force - * @param {Function} callback - * @api private - */ -Connection.prototype._close = function(force, callback) { - const _this = this; - this._closeCalled = true; - - switch (this.readyState) { - case STATES.disconnected: - callback(); - break; - - case STATES.connected: - this.readyState = STATES.disconnecting; - this.doClose(force, function(err) { - if (err) { - return callback(err); - } - _this.onClose(force); - callback(null); - }); - - break; - case STATES.connecting: - this.once('open', function() { - _this.close(callback); - }); - break; - - case STATES.disconnecting: - this.once('close', function() { - callback(); - }); - break; - } - - return this; -}; - -/** - * Called when the connection closes - * - * @api private - */ - -Connection.prototype.onClose = function(force) { - this.readyState = STATES.disconnected; - - // avoid having the collection subscribe to our event emitter - // to prevent 0.3 warning - for (const i in this.collections) { - if (utils.object.hasOwnProperty(this.collections, i)) { - this.collections[i].onClose(force); - } - } - - this.emit('close', force); -}; - -/** - * Retrieves a collection, creating it if not cached. - * - * Not typically needed by applications. Just talk to your collection through your model. - * - * @param {String} name of the collection - * @param {Object} [options] optional collection options - * @return {Collection} collection instance - * @api public - */ - -Connection.prototype.collection = function(name, options) { - options = options ? utils.clone(options) : {}; - options.$wasForceClosed = this.$wasForceClosed; - if (!(name in this.collections)) { - this.collections[name] = new Collection(name, this, options); - } - return this.collections[name]; -}; - -/** - * Declares a plugin executed on all schemas you pass to `conn.model()` - * - * Equivalent to calling `.plugin(fn)` on each schema you create. - * - * ####Example: - * const db = mongoose.createConnection('mongodb://localhost:27017/mydb'); - * db.plugin(() => console.log('Applied')); - * db.plugins.length; // 1 - * - * db.model('Test', new Schema({})); // Prints "Applied" - * - * @param {Function} fn plugin callback - * @param {Object} [opts] optional options - * @return {Connection} this - * @see plugins ./plugins.html - * @api public - */ - -Connection.prototype.plugin = function(fn, opts) { - this.plugins.push([fn, opts]); - return this; -}; - -/** - * Defines or retrieves a model. - * - * var mongoose = require('mongoose'); - * var db = mongoose.createConnection(..); - * db.model('Venue', new Schema(..)); - * var Ticket = db.model('Ticket', new Schema(..)); - * var Venue = db.model('Venue'); - * - * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ - * - * ####Example: - * - * var schema = new Schema({ name: String }, { collection: 'actor' }); - * - * // or - * - * schema.set('collection', 'actor'); - * - * // or - * - * var collectionName = 'actor' - * var M = conn.model('Actor', schema, collectionName) - * - * @param {String|Function} name the model name or class extending Model - * @param {Schema} [schema] a schema. necessary when defining a model - * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name - * @see Mongoose#model #index_Mongoose-model - * @return {Model} The compiled model - * @api public - */ - -Connection.prototype.model = function(name, schema, collection) { - if (!(this instanceof Connection)) { - throw new MongooseError('`connection.model()` should not be run with ' + - '`new`. If you are doing `new db.model(foo)(bar)`, use ' + - '`db.model(foo)(bar)` instead'); - } - - let fn; - if (typeof name === 'function') { - fn = name; - name = fn.name; - } - - // collection name discovery - if (typeof schema === 'string') { - collection = schema; - schema = false; - } - - if (utils.isObject(schema) && !schema.instanceOfSchema) { - schema = new Schema(schema); - } - if (schema && !schema.instanceOfSchema) { - throw new Error('The 2nd parameter to `mongoose.model()` should be a ' + - 'schema or a POJO'); - } - - if (this.models[name] && !collection) { - // model exists but we are not subclassing with custom collection - if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) { - throw new MongooseError.OverwriteModelError(name); - } - return this.models[name]; - } - - const opts = { cache: false, connection: this }; - let model; - - if (schema && schema.instanceOfSchema) { - applyPlugins(schema, this.plugins, null, '$connectionPluginsApplied'); - - // compile a model - model = this.base.model(fn || name, schema, collection, opts); - - // only the first model with this name is cached to allow - // for one-offs with custom collection names etc. - if (!this.models[name]) { - this.models[name] = model; - } - - // Errors handled internally, so safe to ignore error - model.init(function $modelInitNoop() {}); - - return model; - } - - if (this.models[name] && collection) { - // subclassing current model with alternate collection - model = this.models[name]; - schema = model.prototype.schema; - const sub = model.__subclass(this, schema, collection); - // do not cache the sub model - return sub; - } - - // lookup model in mongoose module - model = this.base.models[name]; - - if (!model) { - throw new MongooseError.MissingSchemaError(name); - } - - if (this === model.prototype.db - && (!collection || collection === model.collection.name)) { - // model already uses this connection. - - // only the first model with this name is cached to allow - // for one-offs with custom collection names etc. - if (!this.models[name]) { - this.models[name] = model; - } - - return model; - } - this.models[name] = model.__subclass(this, schema, collection); - return this.models[name]; -}; - -/** - * Removes the model named `name` from this connection, if it exists. You can - * use this function to clean up any models you created in your tests to - * prevent OverwriteModelErrors. - * - * ####Example: - * - * conn.model('User', new Schema({ name: String })); - * console.log(conn.model('User')); // Model object - * conn.deleteModel('User'); - * console.log(conn.model('User')); // undefined - * - * // Usually useful in a Mocha `afterEach()` hook - * afterEach(function() { - * conn.deleteModel(/.+/); // Delete every model - * }); - * - * @api public - * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. - * @return {Connection} this - */ - -Connection.prototype.deleteModel = function(name) { - if (typeof name === 'string') { - const model = this.model(name); - if (model == null) { - return this; - } - const collectionName = model.collection.name; - delete this.models[name]; - delete this.collections[collectionName]; - delete this.base.modelSchemas[name]; - } else if (name instanceof RegExp) { - const pattern = name; - const names = this.modelNames(); - for (const name of names) { - if (pattern.test(name)) { - this.deleteModel(name); - } - } - } else { - throw new Error('First parameter to `deleteModel()` must be a string ' + - 'or regexp, got "' + name + '"'); - } - - return this; -}; - -/** - * Watches the entire underlying database for changes. Similar to - * [`Model.watch()`](/docs/api/model.html#model_Model.watch). - * - * This function does **not** trigger any middleware. In particular, it - * does **not** trigger aggregate middleware. - * - * The ChangeStream object is an event emitter that emits the following events: - * - * - 'change': A change occurred, see below example - * - 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates. - * - 'end': Emitted if the underlying stream is closed - * - 'close': Emitted if the underlying stream is closed - * - * ####Example: - * - * const User = conn.model('User', new Schema({ name: String })); - * - * const changeStream = conn.watch().on('change', data => console.log(data)); - * - * // Triggers a 'change' event on the change stream. - * await User.create({ name: 'test' }); - * - * @api public - * @param {Array} [pipeline] - * @param {Object} [options] passed without changes to [the MongoDB driver's `Db#watch()` function](https://mongodb.github.io/node-mongodb-native/3.4/api/Db.html#watch) - * @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter - */ - -Connection.prototype.watch = function(pipeline, options) { - const disconnectedError = new MongooseError('Connection ' + this.id + - ' was disconnected when calling `watch()`'); - - const changeStreamThunk = cb => { - immediate(() => { - if (this.readyState === STATES.connecting) { - this.once('open', function() { - const driverChangeStream = this.db.watch(pipeline, options); - cb(null, driverChangeStream); - }); - } else if (this.readyState === STATES.disconnected && this.db == null) { - cb(disconnectedError); - } else { - const driverChangeStream = this.db.watch(pipeline, options); - cb(null, driverChangeStream); - } - }); - }; - - const changeStream = new ChangeStream(changeStreamThunk, pipeline, options); - return changeStream; -}; - -/** - * Returns an array of model names created on this connection. - * @api public - * @return {Array} - */ - -Connection.prototype.modelNames = function() { - return Object.keys(this.models); -}; - -/** - * @brief Returns if the connection requires authentication after it is opened. Generally if a - * username and password are both provided than authentication is needed, but in some cases a - * password is not required. - * @api private - * @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false. - */ -Connection.prototype.shouldAuthenticate = function() { - return this.user != null && - (this.pass != null || this.authMechanismDoesNotRequirePassword()); -}; - -/** - * @brief Returns a boolean value that specifies if the current authentication mechanism needs a - * password to authenticate according to the auth objects passed into the openUri methods. - * @api private - * @return {Boolean} true if the authentication mechanism specified in the options object requires - * a password, otherwise false. - */ -Connection.prototype.authMechanismDoesNotRequirePassword = function() { - if (this.options && this.options.auth) { - return noPasswordAuthMechanisms.indexOf(this.options.auth.authMechanism) >= 0; - } - return true; -}; - -/** - * @brief Returns a boolean value that specifies if the provided objects object provides enough - * data to authenticate with. Generally this is true if the username and password are both specified - * but in some authentication methods, a password is not required for authentication so only a username - * is required. - * @param {Object} [options] the options object passed into the openUri methods. - * @api private - * @return {Boolean} true if the provided options object provides enough data to authenticate with, - * otherwise false. - */ -Connection.prototype.optionsProvideAuthenticationData = function(options) { - return (options) && - (options.user) && - ((options.pass) || this.authMechanismDoesNotRequirePassword()); -}; - -/** - * Switches to a different database using the same connection pool. - * - * Returns a new connection object, with the new db. - * - * @method useDb - * @memberOf Connection - * @param {String} name The database name - * @param {Object} [options] - * @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object. - * @return {Connection} New Connection Object - * @api public - */ - -/*! - * Module exports. - */ - -Connection.STATES = STATES; -module.exports = Connection; diff --git a/node_modules/mongoose/lib/connectionstate.js b/node_modules/mongoose/lib/connectionstate.js deleted file mode 100644 index 920f45b..0000000 --- a/node_modules/mongoose/lib/connectionstate.js +++ /dev/null @@ -1,26 +0,0 @@ - -/*! - * Connection states - */ - -'use strict'; - -const STATES = module.exports = exports = Object.create(null); - -const disconnected = 'disconnected'; -const connected = 'connected'; -const connecting = 'connecting'; -const disconnecting = 'disconnecting'; -const uninitialized = 'uninitialized'; - -STATES[0] = disconnected; -STATES[1] = connected; -STATES[2] = connecting; -STATES[3] = disconnecting; -STATES[99] = uninitialized; - -STATES[disconnected] = 0; -STATES[connected] = 1; -STATES[connecting] = 2; -STATES[disconnecting] = 3; -STATES[uninitialized] = 99; diff --git a/node_modules/mongoose/lib/cursor/AggregationCursor.js b/node_modules/mongoose/lib/cursor/AggregationCursor.js deleted file mode 100644 index 9137a88..0000000 --- a/node_modules/mongoose/lib/cursor/AggregationCursor.js +++ /dev/null @@ -1,310 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('../error/mongooseError'); -const Readable = require('stream').Readable; -const promiseOrCallback = require('../helpers/promiseOrCallback'); -const eachAsync = require('../helpers/cursor/eachAsync'); -const util = require('util'); - -/** - * An AggregationCursor is a concurrency primitive for processing aggregation - * results one document at a time. It is analogous to QueryCursor. - * - * An AggregationCursor fulfills the Node.js streams3 API, - * in addition to several other mechanisms for loading documents from MongoDB - * one at a time. - * - * Creating an AggregationCursor executes the model's pre aggregate hooks, - * but **not** the model's post aggregate hooks. - * - * Unless you're an advanced user, do **not** instantiate this class directly. - * Use [`Aggregate#cursor()`](/docs/api.html#aggregate_Aggregate-cursor) instead. - * - * @param {Aggregate} agg - * @param {Object} options - * @inherits Readable - * @event `cursor`: Emitted when the cursor is created - * @event `error`: Emitted when an error occurred - * @event `data`: Emitted when the stream is flowing and the next doc is ready - * @event `end`: Emitted when the stream is exhausted - * @api public - */ - -function AggregationCursor(agg) { - Readable.call(this, { objectMode: true }); - - this.cursor = null; - this.agg = agg; - this._transforms = []; - const model = agg._model; - delete agg.options.cursor.useMongooseAggCursor; - this._mongooseOptions = {}; - - _init(model, this, agg); -} - -util.inherits(AggregationCursor, Readable); - -/*! - * ignore - */ - -function _init(model, c, agg) { - if (!model.collection.buffer) { - model.hooks.execPre('aggregate', agg, function() { - c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {}); - c.emit('cursor', c.cursor); - }); - } else { - model.collection.emitter.once('queue', function() { - model.hooks.execPre('aggregate', agg, function() { - c.cursor = model.collection.aggregate(agg._pipeline, agg.options || {}); - c.emit('cursor', c.cursor); - }); - }); - } -} - -/*! - * Necessary to satisfy the Readable API - */ - -AggregationCursor.prototype._read = function() { - const _this = this; - _next(this, function(error, doc) { - if (error) { - return _this.emit('error', error); - } - if (!doc) { - _this.push(null); - _this.cursor.close(function(error) { - if (error) { - return _this.emit('error', error); - } - setTimeout(function() { - // on node >= 14 streams close automatically (gh-8834) - const isNotClosedAutomatically = !_this.destroyed; - if (isNotClosedAutomatically) { - _this.emit('close'); - } - }, 0); - }); - return; - } - _this.push(doc); - }); -}; - -if (Symbol.asyncIterator != null) { - const msg = 'Mongoose does not support using async iterators with an ' + - 'existing aggregation cursor. See http://bit.ly/mongoose-async-iterate-aggregation'; - - AggregationCursor.prototype[Symbol.asyncIterator] = function() { - throw new MongooseError(msg); - }; -} - -/** - * Registers a transform function which subsequently maps documents retrieved - * via the streams interface or `.next()` - * - * ####Example - * - * // Map documents returned by `data` events - * Thing. - * find({ name: /^hello/ }). - * cursor(). - * map(function (doc) { - * doc.foo = "bar"; - * return doc; - * }) - * on('data', function(doc) { console.log(doc.foo); }); - * - * // Or map documents returned by `.next()` - * var cursor = Thing.find({ name: /^hello/ }). - * cursor(). - * map(function (doc) { - * doc.foo = "bar"; - * return doc; - * }); - * cursor.next(function(error, doc) { - * console.log(doc.foo); - * }); - * - * @param {Function} fn - * @return {AggregationCursor} - * @api public - * @method map - */ - -AggregationCursor.prototype.map = function(fn) { - this._transforms.push(fn); - return this; -}; - -/*! - * Marks this cursor as errored - */ - -AggregationCursor.prototype._markError = function(error) { - this._error = error; - return this; -}; - -/** - * Marks this cursor as closed. Will stop streaming and subsequent calls to - * `next()` will error. - * - * @param {Function} callback - * @return {Promise} - * @api public - * @method close - * @emits close - * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close - */ - -AggregationCursor.prototype.close = function(callback) { - return promiseOrCallback(callback, cb => { - this.cursor.close(error => { - if (error) { - cb(error); - return this.listeners('error').length > 0 && this.emit('error', error); - } - this.emit('close'); - cb(null); - }); - }); -}; - -/** - * Get the next document from this cursor. Will return `null` when there are - * no documents left. - * - * @param {Function} callback - * @return {Promise} - * @api public - * @method next - */ - -AggregationCursor.prototype.next = function(callback) { - return promiseOrCallback(callback, cb => { - _next(this, cb); - }); -}; - -/** - * Execute `fn` for every document in the cursor. If `fn` returns a promise, - * will wait for the promise to resolve before iterating on to the next one. - * Returns a promise that resolves when done. - * - * @param {Function} fn - * @param {Object} [options] - * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1. - * @param {Function} [callback] executed when all docs have been processed - * @return {Promise} - * @api public - * @method eachAsync - */ - -AggregationCursor.prototype.eachAsync = function(fn, opts, callback) { - const _this = this; - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - opts = opts || {}; - - return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback); -}; - -/*! - * ignore - */ - -AggregationCursor.prototype.transformNull = function(val) { - if (arguments.length === 0) { - val = true; - } - this._mongooseOptions.transformNull = val; - return this; -}; - -/** - * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). - * Useful for setting the `noCursorTimeout` and `tailable` flags. - * - * @param {String} flag - * @param {Boolean} value - * @return {AggregationCursor} this - * @api public - * @method addCursorFlag - */ - -AggregationCursor.prototype.addCursorFlag = function(flag, value) { - const _this = this; - _waitForCursor(this, function() { - _this.cursor.addCursorFlag(flag, value); - }); - return this; -}; - -/*! - * ignore - */ - -function _waitForCursor(ctx, cb) { - if (ctx.cursor) { - return cb(); - } - ctx.once('cursor', function() { - cb(); - }); -} - -/*! - * Get the next doc from the underlying cursor and mongooseify it - * (populate, etc.) - */ - -function _next(ctx, cb) { - let callback = cb; - if (ctx._transforms.length) { - callback = function(err, doc) { - if (err || (doc === null && !ctx._mongooseOptions.transformNull)) { - return cb(err, doc); - } - cb(err, ctx._transforms.reduce(function(doc, fn) { - return fn(doc); - }, doc)); - }; - } - - if (ctx._error) { - return process.nextTick(function() { - callback(ctx._error); - }); - } - - if (ctx.cursor) { - return ctx.cursor.next(function(error, doc) { - if (error) { - return callback(error); - } - if (!doc) { - return callback(null, null); - } - - callback(null, doc); - }); - } else { - ctx.once('cursor', function() { - _next(ctx, cb); - }); - } -} - -module.exports = AggregationCursor; diff --git a/node_modules/mongoose/lib/cursor/ChangeStream.js b/node_modules/mongoose/lib/cursor/ChangeStream.js deleted file mode 100644 index b3445b0..0000000 --- a/node_modules/mongoose/lib/cursor/ChangeStream.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const EventEmitter = require('events').EventEmitter; - -/*! - * ignore - */ - -class ChangeStream extends EventEmitter { - constructor(changeStreamThunk, pipeline, options) { - super(); - - this.driverChangeStream = null; - this.closed = false; - this.pipeline = pipeline; - this.options = options; - - // This wrapper is necessary because of buffering. - changeStreamThunk((err, driverChangeStream) => { - if (err != null) { - this.emit('error', err); - return; - } - - this.driverChangeStream = driverChangeStream; - this._bindEvents(); - this.emit('ready'); - }); - } - - _bindEvents() { - this.driverChangeStream.on('close', () => { - this.closed = true; - }); - - ['close', 'change', 'end', 'error'].forEach(ev => { - this.driverChangeStream.on(ev, data => this.emit(ev, data)); - }); - } - - _queue(cb) { - this.once('ready', () => cb()); - } - - close() { - this.closed = true; - if (this.driverChangeStream) { - this.driverChangeStream.close(); - } - } -} - -/*! - * ignore - */ - -module.exports = ChangeStream; diff --git a/node_modules/mongoose/lib/cursor/QueryCursor.js b/node_modules/mongoose/lib/cursor/QueryCursor.js deleted file mode 100644 index a77f5bb..0000000 --- a/node_modules/mongoose/lib/cursor/QueryCursor.js +++ /dev/null @@ -1,363 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const Readable = require('stream').Readable; -const promiseOrCallback = require('../helpers/promiseOrCallback'); -const eachAsync = require('../helpers/cursor/eachAsync'); -const helpers = require('../queryhelpers'); -const util = require('util'); - -/** - * A QueryCursor is a concurrency primitive for processing query results - * one document at a time. A QueryCursor fulfills the Node.js streams3 API, - * in addition to several other mechanisms for loading documents from MongoDB - * one at a time. - * - * QueryCursors execute the model's pre find hooks, but **not** the model's - * post find hooks. - * - * Unless you're an advanced user, do **not** instantiate this class directly. - * Use [`Query#cursor()`](/docs/api.html#query_Query-cursor) instead. - * - * @param {Query} query - * @param {Object} options query options passed to `.find()` - * @inherits Readable - * @event `cursor`: Emitted when the cursor is created - * @event `error`: Emitted when an error occurred - * @event `data`: Emitted when the stream is flowing and the next doc is ready - * @event `end`: Emitted when the stream is exhausted - * @api public - */ - -function QueryCursor(query, options) { - Readable.call(this, { objectMode: true }); - - this.cursor = null; - this.query = query; - const _this = this; - const model = query.model; - this._mongooseOptions = {}; - this._transforms = []; - this.model = model; - this.options = options || {}; - - model.hooks.execPre('find', query, () => { - this._transforms = this._transforms.concat(query._transforms.slice()); - if (this.options.transform) { - this._transforms.push(options.transform); - } - // Re: gh-8039, you need to set the `cursor.batchSize` option, top-level - // `batchSize` option doesn't work. - if (this.options.batchSize) { - this.options.cursor = options.cursor || {}; - this.options.cursor.batchSize = options.batchSize; - } - model.collection.find(query._conditions, this.options, function(err, cursor) { - if (_this._error) { - cursor.close(function() {}); - _this.listeners('error').length > 0 && _this.emit('error', _this._error); - } - if (err) { - return _this.emit('error', err); - } - _this.cursor = cursor; - _this.emit('cursor', cursor); - }); - }); -} - -util.inherits(QueryCursor, Readable); - -/*! - * Necessary to satisfy the Readable API - */ - -QueryCursor.prototype._read = function() { - const _this = this; - _next(this, function(error, doc) { - if (error) { - return _this.emit('error', error); - } - if (!doc) { - _this.push(null); - _this.cursor.close(function(error) { - if (error) { - return _this.emit('error', error); - } - setTimeout(function() { - // on node >= 14 streams close automatically (gh-8834) - const isNotClosedAutomatically = !_this.destroyed; - if (isNotClosedAutomatically) { - _this.emit('close'); - } - }, 0); - }); - return; - } - _this.push(doc); - }); -}; - -/** - * Registers a transform function which subsequently maps documents retrieved - * via the streams interface or `.next()` - * - * ####Example - * - * // Map documents returned by `data` events - * Thing. - * find({ name: /^hello/ }). - * cursor(). - * map(function (doc) { - * doc.foo = "bar"; - * return doc; - * }) - * on('data', function(doc) { console.log(doc.foo); }); - * - * // Or map documents returned by `.next()` - * var cursor = Thing.find({ name: /^hello/ }). - * cursor(). - * map(function (doc) { - * doc.foo = "bar"; - * return doc; - * }); - * cursor.next(function(error, doc) { - * console.log(doc.foo); - * }); - * - * @param {Function} fn - * @return {QueryCursor} - * @api public - * @method map - */ - -QueryCursor.prototype.map = function(fn) { - this._transforms.push(fn); - return this; -}; - -/*! - * Marks this cursor as errored - */ - -QueryCursor.prototype._markError = function(error) { - this._error = error; - return this; -}; - -/** - * Marks this cursor as closed. Will stop streaming and subsequent calls to - * `next()` will error. - * - * @param {Function} callback - * @return {Promise} - * @api public - * @method close - * @emits close - * @see MongoDB driver cursor#close http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close - */ - -QueryCursor.prototype.close = function(callback) { - return promiseOrCallback(callback, cb => { - this.cursor.close(error => { - if (error) { - cb(error); - return this.listeners('error').length > 0 && this.emit('error', error); - } - this.emit('close'); - cb(null); - }); - }, this.model.events); -}; - -/** - * Get the next document from this cursor. Will return `null` when there are - * no documents left. - * - * @param {Function} callback - * @return {Promise} - * @api public - * @method next - */ - -QueryCursor.prototype.next = function(callback) { - return promiseOrCallback(callback, cb => { - _next(this, function(error, doc) { - if (error) { - return cb(error); - } - cb(null, doc); - }); - }, this.model.events); -}; - -/** - * Execute `fn` for every document in the cursor. If `fn` returns a promise, - * will wait for the promise to resolve before iterating on to the next one. - * Returns a promise that resolves when done. - * - * ####Example - * - * // Iterate over documents asynchronously - * Thing. - * find({ name: /^hello/ }). - * cursor(). - * eachAsync(async function (doc, i) { - * doc.foo = doc.bar + i; - * await doc.save(); - * }) - * - * @param {Function} fn - * @param {Object} [options] - * @param {Number} [options.parallel] the number of promises to execute in parallel. Defaults to 1. - * @param {Function} [callback] executed when all docs have been processed - * @return {Promise} - * @api public - * @method eachAsync - */ - -QueryCursor.prototype.eachAsync = function(fn, opts, callback) { - const _this = this; - if (typeof opts === 'function') { - callback = opts; - opts = {}; - } - opts = opts || {}; - - return eachAsync(function(cb) { return _next(_this, cb); }, fn, opts, callback); -}; - -/** - * The `options` passed in to the `QueryCursor` constructor. - * - * @api public - * @property options - */ - -QueryCursor.prototype.options; - -/** - * Adds a [cursor flag](http://mongodb.github.io/node-mongodb-native/2.2/api/Cursor.html#addCursorFlag). - * Useful for setting the `noCursorTimeout` and `tailable` flags. - * - * @param {String} flag - * @param {Boolean} value - * @return {AggregationCursor} this - * @api public - * @method addCursorFlag - */ - -QueryCursor.prototype.addCursorFlag = function(flag, value) { - const _this = this; - _waitForCursor(this, function() { - _this.cursor.addCursorFlag(flag, value); - }); - return this; -}; - -/*! - * ignore - */ - -QueryCursor.prototype.transformNull = function(val) { - if (arguments.length === 0) { - val = true; - } - this._mongooseOptions.transformNull = val; - return this; -}; - -/*! - * Get the next doc from the underlying cursor and mongooseify it - * (populate, etc.) - */ - -function _next(ctx, cb) { - let callback = cb; - if (ctx._transforms.length) { - callback = function(err, doc) { - if (err || (doc === null && !ctx._mongooseOptions.transformNull)) { - return cb(err, doc); - } - cb(err, ctx._transforms.reduce(function(doc, fn) { - return fn.call(ctx, doc); - }, doc)); - }; - } - - if (ctx._error) { - return process.nextTick(function() { - callback(ctx._error); - }); - } - - if (ctx.cursor) { - return ctx.cursor.next(function(error, doc) { - if (error) { - return callback(error); - } - if (!doc) { - return callback(null, null); - } - - const opts = ctx.query._mongooseOptions; - if (!opts.populate) { - return opts.lean ? - callback(null, doc) : - _create(ctx, doc, null, callback); - } - - const pop = helpers.preparePopulationOptionsMQ(ctx.query, - ctx.query._mongooseOptions); - pop.__noPromise = true; - ctx.query.model.populate(doc, pop, function(err, doc) { - if (err) { - return callback(err); - } - return opts.lean ? - callback(null, doc) : - _create(ctx, doc, pop, callback); - }); - }); - } else { - ctx.once('cursor', function() { - _next(ctx, cb); - }); - } -} - -/*! - * ignore - */ - -function _waitForCursor(ctx, cb) { - if (ctx.cursor) { - return cb(); - } - ctx.once('cursor', function() { - cb(); - }); -} - -/*! - * Convert a raw doc into a full mongoose doc. - */ - -function _create(ctx, doc, populatedIds, cb) { - const instance = helpers.createModel(ctx.query.model, doc, ctx.query._fields); - const opts = populatedIds ? - { populated: populatedIds } : - undefined; - - instance.init(doc, opts, function(err) { - if (err) { - return cb(err); - } - cb(null, instance); - }); -} - -module.exports = QueryCursor; diff --git a/node_modules/mongoose/lib/document.js b/node_modules/mongoose/lib/document.js deleted file mode 100644 index dce5600..0000000 --- a/node_modules/mongoose/lib/document.js +++ /dev/null @@ -1,3802 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const EventEmitter = require('events').EventEmitter; -const InternalCache = require('./internal'); -const MongooseError = require('./error/index'); -const MixedSchema = require('./schema/mixed'); -const ObjectExpectedError = require('./error/objectExpected'); -const ObjectParameterError = require('./error/objectParameter'); -const ParallelValidateError = require('./error/parallelValidate'); -const Schema = require('./schema'); -const StrictModeError = require('./error/strict'); -const ValidationError = require('./error/validation'); -const ValidatorError = require('./error/validator'); -const VirtualType = require('./virtualtype'); -const promiseOrCallback = require('./helpers/promiseOrCallback'); -const cleanModifiedSubpaths = require('./helpers/document/cleanModifiedSubpaths'); -const compile = require('./helpers/document/compile').compile; -const defineKey = require('./helpers/document/compile').defineKey; -const flatten = require('./helpers/common').flatten; -const get = require('./helpers/get'); -const getEmbeddedDiscriminatorPath = require('./helpers/document/getEmbeddedDiscriminatorPath'); -const handleSpreadDoc = require('./helpers/document/handleSpreadDoc'); -const idGetter = require('./plugins/idGetter'); -const isDefiningProjection = require('./helpers/projection/isDefiningProjection'); -const isExclusive = require('./helpers/projection/isExclusive'); -const inspect = require('util').inspect; -const internalToObjectOptions = require('./options').internalToObjectOptions; -const mpath = require('mpath'); -const utils = require('./utils'); - -const clone = utils.clone; -const deepEqual = utils.deepEqual; -const isMongooseObject = utils.isMongooseObject; - -const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol; -const documentArrayParent = require('./helpers/symbols').documentArrayParent; -const documentSchemaSymbol = require('./helpers/symbols').documentSchemaSymbol; -const getSymbol = require('./helpers/symbols').getSymbol; -const populateModelSymbol = require('./helpers/symbols').populateModelSymbol; - -let DocumentArray; -let MongooseArray; -let Embedded; - -const specialProperties = utils.specialProperties; - -/** - * The core Mongoose document constructor. You should not call this directly, - * the Mongoose [Model constructor](./api.html#Model) calls this for you. - * - * @param {Object} obj the values to set - * @param {Object} [fields] optional object containing the fields which were selected in the query returning this document and any populated paths data - * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `init`: Emitted on a document after it has been retrieved from the db and fully hydrated by Mongoose. - * @event `save`: Emitted when the document is successfully saved - * @api private - */ - -function Document(obj, fields, skipId, options) { - if (typeof skipId === 'object' && skipId != null) { - options = skipId; - skipId = options.skipId; - } - options = options || {}; - - // Support `browserDocument.js` syntax - if (this.schema == null) { - const _schema = utils.isObject(fields) && !fields.instanceOfSchema ? - new Schema(fields) : - fields; - this.$__setSchema(_schema); - fields = skipId; - skipId = options; - options = arguments[4] || {}; - } - - this.$__ = new InternalCache; - this.$__.emitter = new EventEmitter(); - this.isNew = 'isNew' in options ? options.isNew : true; - this.errors = undefined; - this.$__.$options = options || {}; - - if (obj != null && typeof obj !== 'object') { - throw new ObjectParameterError(obj, 'obj', 'Document'); - } - - const schema = this.schema; - - if (typeof fields === 'boolean' || fields === 'throw') { - this.$__.strictMode = fields; - fields = undefined; - } else { - this.$__.strictMode = schema.options.strict; - this.$__.selected = fields; - } - - const requiredPaths = schema.requiredPaths(true); - for (const path of requiredPaths) { - this.$__.activePaths.require(path); - } - - this.$__.emitter.setMaxListeners(0); - - let exclude = null; - - // determine if this doc is a result of a query with - // excluded fields - if (utils.isPOJO(fields)) { - exclude = isExclusive(fields); - } - - const hasIncludedChildren = exclude === false && fields ? - $__hasIncludedChildren(fields) : - {}; - - if (this._doc == null) { - this.$__buildDoc(obj, fields, skipId, exclude, hasIncludedChildren, false); - - // By default, defaults get applied **before** setting initial values - // Re: gh-6155 - $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, true, { - isNew: this.isNew - }); - } - - if (obj) { - // Skip set hooks - if (this.$__original_set) { - this.$__original_set(obj, undefined, true); - } else { - this.$set(obj, undefined, true); - } - - if (obj instanceof Document) { - this.isNew = obj.isNew; - } - } - - // Function defaults get applied **after** setting initial values so they - // see the full doc rather than an empty one, unless they opt out. - // Re: gh-3781, gh-6155 - if (options.willInit) { - EventEmitter.prototype.once.call(this, 'init', () => { - $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, { - isNew: this.isNew - }); - }); - } else { - $__applyDefaults(this, fields, skipId, exclude, hasIncludedChildren, false, options.skipDefaults, { - isNew: this.isNew - }); - } - - this.$__._id = this._id; - this.$locals = {}; - this.$op = null; - - if (!this.$__.strictMode && obj) { - const _this = this; - const keys = Object.keys(this._doc); - - keys.forEach(function(key) { - if (!(key in schema.tree)) { - defineKey(key, null, _this); - } - }); - } - - applyQueue(this); -} - -/*! - * Document exposes the NodeJS event emitter API, so you can use - * `on`, `once`, etc. - */ -utils.each( - ['on', 'once', 'emit', 'listeners', 'removeListener', 'setMaxListeners', - 'removeAllListeners', 'addListener'], - function(emitterFn) { - Document.prototype[emitterFn] = function() { - return this.$__.emitter[emitterFn].apply(this.$__.emitter, arguments); - }; - }); - -Document.prototype.constructor = Document; - -for (const i in EventEmitter.prototype) { - Document[i] = EventEmitter.prototype[i]; -} - -/** - * The documents schema. - * - * @api public - * @property schema - * @memberOf Document - * @instance - */ - -Document.prototype.schema; - -/** - * Empty object that you can use for storing properties on the document. This - * is handy for passing data to middleware without conflicting with Mongoose - * internals. - * - * ####Example: - * - * schema.pre('save', function() { - * // Mongoose will set `isNew` to `false` if `save()` succeeds - * this.$locals.wasNew = this.isNew; - * }); - * - * schema.post('save', function() { - * // Prints true if `isNew` was set before `save()` - * console.log(this.$locals.wasNew); - * }); - * - * @api public - * @property $locals - * @memberOf Document - * @instance - */ - -Object.defineProperty(Document.prototype, '$locals', { - configurable: false, - enumerable: false, - writable: true -}); - -/** - * Boolean flag specifying if the document is new. - * - * @api public - * @property isNew - * @memberOf Document - * @instance - */ - -Document.prototype.isNew; - -/** - * The string version of this documents _id. - * - * ####Note: - * - * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time. - * - * new Schema({ name: String }, { id: false }); - * - * @api public - * @see Schema options /docs/guide.html#options - * @property id - * @memberOf Document - * @instance - */ - -Document.prototype.id; - -/** - * Hash containing current validation errors. - * - * @api public - * @property errors - * @memberOf Document - * @instance - */ - -Document.prototype.errors; - -/** - * A string containing the current operation that Mongoose is executing - * on this document. May be `null`, `'save'`, `'validate'`, or `'remove'`. - * - * ####Example: - * - * const doc = new Model({ name: 'test' }); - * doc.$op; // null - * - * const promise = doc.save(); - * doc.$op; // 'save' - * - * await promise; - * doc.$op; // null - * - * @api public - * @property $op - * @memberOf Document - * @instance - */ - -Document.prototype.$op; - -/*! - * ignore - */ - -function $__hasIncludedChildren(fields) { - const hasIncludedChildren = {}; - const keys = Object.keys(fields); - - for (const key of keys) { - const parts = key.split('.'); - const c = []; - - for (const part of parts) { - c.push(part); - hasIncludedChildren[c.join('.')] = 1; - } - } - - return hasIncludedChildren; -} - -/*! - * ignore - */ - -function $__applyDefaults(doc, fields, skipId, exclude, hasIncludedChildren, isBeforeSetters, pathsToSkip) { - const paths = Object.keys(doc.schema.paths); - const plen = paths.length; - - for (let i = 0; i < plen; ++i) { - let def; - let curPath = ''; - const p = paths[i]; - - if (p === '_id' && skipId) { - continue; - } - - const type = doc.schema.paths[p]; - const path = p.indexOf('.') === -1 ? [p] : p.split('.'); - const len = path.length; - let included = false; - let doc_ = doc._doc; - - for (let j = 0; j < len; ++j) { - if (doc_ == null) { - break; - } - - const piece = path[j]; - curPath += (!curPath.length ? '' : '.') + piece; - - if (exclude === true) { - if (curPath in fields) { - break; - } - } else if (exclude === false && fields && !included) { - if (curPath in fields) { - included = true; - } else if (!hasIncludedChildren[curPath]) { - break; - } - } - - if (j === len - 1) { - if (doc_[piece] !== void 0) { - break; - } - - if (typeof type.defaultValue === 'function') { - if (!type.defaultValue.$runBeforeSetters && isBeforeSetters) { - break; - } - if (type.defaultValue.$runBeforeSetters && !isBeforeSetters) { - break; - } - } else if (!isBeforeSetters) { - // Non-function defaults should always run **before** setters - continue; - } - - if (pathsToSkip && pathsToSkip[curPath]) { - break; - } - - if (fields && exclude !== null) { - if (exclude === true) { - // apply defaults to all non-excluded fields - if (p in fields) { - continue; - } - - def = type.getDefault(doc, false); - if (typeof def !== 'undefined') { - doc_[piece] = def; - doc.$__.activePaths.default(p); - } - } else if (included) { - // selected field - def = type.getDefault(doc, false); - if (typeof def !== 'undefined') { - doc_[piece] = def; - doc.$__.activePaths.default(p); - } - } - } else { - def = type.getDefault(doc, false); - if (typeof def !== 'undefined') { - doc_[piece] = def; - doc.$__.activePaths.default(p); - } - } - } else { - doc_ = doc_[piece]; - } - } - } -} - -/** - * Builds the default doc structure - * - * @param {Object} obj - * @param {Object} [fields] - * @param {Boolean} [skipId] - * @api private - * @method $__buildDoc - * @memberOf Document - * @instance - */ - -Document.prototype.$__buildDoc = function(obj, fields, skipId, exclude, hasIncludedChildren) { - const doc = {}; - - const paths = Object.keys(this.schema.paths). - // Don't build up any paths that are underneath a map, we don't know - // what the keys will be - filter(p => !p.includes('$*')); - const plen = paths.length; - let ii = 0; - - for (; ii < plen; ++ii) { - const p = paths[ii]; - - if (p === '_id') { - if (skipId) { - continue; - } - if (obj && '_id' in obj) { - continue; - } - } - - const path = p.split('.'); - const len = path.length; - const last = len - 1; - let curPath = ''; - let doc_ = doc; - let included = false; - - for (let i = 0; i < len; ++i) { - const piece = path[i]; - - curPath += (!curPath.length ? '' : '.') + piece; - - // support excluding intermediary levels - if (exclude === true) { - if (curPath in fields) { - break; - } - } else if (exclude === false && fields && !included) { - if (curPath in fields) { - included = true; - } else if (!hasIncludedChildren[curPath]) { - break; - } - } - - if (i < last) { - doc_ = doc_[piece] || (doc_[piece] = {}); - } - } - } - - this._doc = doc; -}; - -/*! - * Converts to POJO when you use the document for querying - */ - -Document.prototype.toBSON = function() { - return this.toObject(internalToObjectOptions); -}; - -/** - * Initializes the document without setters or marking anything modified. - * - * Called internally after a document is returned from mongodb. Normally, - * you do **not** need to call this function on your own. - * - * This function triggers `init` [middleware](/docs/middleware.html). - * Note that `init` hooks are [synchronous](/docs/middleware.html#synchronous). - * - * @param {Object} doc document returned by mongo - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.init = function(doc, opts, fn) { - if (typeof opts === 'function') { - fn = opts; - opts = null; - } - - this.$__init(doc, opts); - - if (fn) { - fn(null, this); - } - - return this; -}; - -/*! - * ignore - */ - -Document.prototype.$__init = function(doc, opts) { - this.isNew = false; - this.$init = true; - opts = opts || {}; - - // handle docs with populated paths - // If doc._id is not null or undefined - if (doc._id != null && opts.populated && opts.populated.length) { - const id = String(doc._id); - for (const item of opts.populated) { - if (item.isVirtual) { - this.populated(item.path, utils.getValue(item.path, doc), item); - } else { - this.populated(item.path, item._docs[id], item); - } - } - } - - init(this, doc, this._doc, opts); - - markArraySubdocsPopulated(this, opts.populated); - - this.emit('init', this); - this.constructor.emit('init', this); - - this.$__._id = this._id; - - return this; -}; - -/*! - * If populating a path within a document array, make sure each - * subdoc within the array knows its subpaths are populated. - * - * ####Example: - * const doc = await Article.findOne().populate('comments.author'); - * doc.comments[0].populated('author'); // Should be set - */ - -function markArraySubdocsPopulated(doc, populated) { - if (doc._id == null || populated == null || populated.length === 0) { - return; - } - - const id = String(doc._id); - for (const item of populated) { - if (item.isVirtual) { - continue; - } - const path = item.path; - const pieces = path.split('.'); - for (let i = 0; i < pieces.length - 1; ++i) { - const subpath = pieces.slice(0, i + 1).join('.'); - const rest = pieces.slice(i + 1).join('.'); - const val = doc.get(subpath); - if (val == null) { - continue; - } - - if (val.isMongooseDocumentArray) { - for (let j = 0; j < val.length; ++j) { - val[j].populated(rest, item._docs[id] == null ? [] : item._docs[id][j], item); - } - break; - } - } - } -} - -/*! - * Init helper. - * - * @param {Object} self document instance - * @param {Object} obj raw mongodb doc - * @param {Object} doc object we are initializing - * @api private - */ - -function init(self, obj, doc, opts, prefix) { - prefix = prefix || ''; - - const keys = Object.keys(obj); - const len = keys.length; - let schema; - let path; - let i; - let index = 0; - - while (index < len) { - _init(index++); - } - - function _init(index) { - i = keys[index]; - path = prefix + i; - schema = self.schema.path(path); - - // Should still work if not a model-level discriminator, but should not be - // necessary. This is *only* to catch the case where we queried using the - // base model and the discriminated model has a projection - if (self.schema.$isRootDiscriminator && !self.isSelected(path)) { - return; - } - - if (!schema && utils.isPOJO(obj[i])) { - // assume nested object - if (!doc[i]) { - doc[i] = {}; - } - init(self, obj[i], doc[i], opts, path + '.'); - } else if (!schema) { - doc[i] = obj[i]; - } else { - if (obj[i] === null) { - doc[i] = null; - } else if (obj[i] !== undefined) { - const intCache = obj[i].$__ || {}; - const wasPopulated = intCache.wasPopulated || null; - - if (schema && !wasPopulated) { - try { - doc[i] = schema.cast(obj[i], self, true); - } catch (e) { - self.invalidate(e.path, new ValidatorError({ - path: e.path, - message: e.message, - type: 'cast', - value: e.value - })); - } - } else { - doc[i] = obj[i]; - } - } - // mark as hydrated - if (!self.isModified(path)) { - self.$__.activePaths.init(path); - } - } - } -} - -/** - * Sends an update command with this document `_id` as the query selector. - * - * ####Example: - * - * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback); - * - * ####Valid options: - * - * - same as in [Model.update](#model_Model.update) - * - * @see Model.update #model_Model.update - * @param {Object} doc - * @param {Object} options - * @param {Function} callback - * @return {Query} - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.update = function update() { - const args = utils.args(arguments); - args.unshift({ _id: this._id }); - const query = this.constructor.update.apply(this.constructor, args); - - if (this.$session() != null) { - if (!('session' in query.options)) { - query.options.session = this.$session(); - } - } - - return query; -}; - -/** - * Sends an updateOne command with this document `_id` as the query selector. - * - * ####Example: - * - * weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback); - * - * ####Valid options: - * - * - same as in [Model.updateOne](#model_Model.updateOne) - * - * @see Model.updateOne #model_Model.updateOne - * @param {Object} doc - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Function} callback - * @return {Query} - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.updateOne = function updateOne(doc, options, callback) { - const query = this.constructor.updateOne({ _id: this._id }, doc, options); - query._pre(cb => { - this.constructor._middleware.execPre('updateOne', this, [this], cb); - }); - query._post(cb => { - this.constructor._middleware.execPost('updateOne', this, [this], {}, cb); - }); - - if (this.$session() != null) { - if (!('session' in query.options)) { - query.options.session = this.$session(); - } - } - - if (callback != null) { - return query.exec(callback); - } - - return query; -}; - -/** - * Sends a replaceOne command with this document `_id` as the query selector. - * - * ####Valid options: - * - * - same as in [Model.replaceOne](#model_Model.replaceOne) - * - * @see Model.replaceOne #model_Model.replaceOne - * @param {Object} doc - * @param {Object} options - * @param {Function} callback - * @return {Query} - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.replaceOne = function replaceOne() { - const args = utils.args(arguments); - args.unshift({ _id: this._id }); - return this.constructor.replaceOne.apply(this.constructor, args); -}; - -/** - * Getter/setter around the session associated with this document. Used to - * automatically set `session` if you `save()` a doc that you got from a - * query with an associated session. - * - * ####Example: - * - * const session = MyModel.startSession(); - * const doc = await MyModel.findOne().session(session); - * doc.$session() === session; // true - * doc.$session(null); - * doc.$session() === null; // true - * - * If this is a top-level document, setting the session propagates to all child - * docs. - * - * @param {ClientSession} [session] overwrite the current session - * @return {ClientSession} - * @method $session - * @api public - * @memberOf Document - */ - -Document.prototype.$session = function $session(session) { - if (arguments.length === 0) { - return this.$__.session; - } - this.$__.session = session; - - if (!this.ownerDocument) { - const subdocs = this.$__getAllSubdocs(); - for (const child of subdocs) { - child.$session(session); - } - } - - return session; -}; - -/** - * Overwrite all values in this document with the values of `obj`, except - * for immutable properties. Behaves similarly to `set()`, except for it - * unsets all properties that aren't in `obj`. - * - * @param {Object} obj the object to overwrite this document with - * @method overwrite - * @name overwrite - * @memberOf Document - * @instance - * @api public - */ - -Document.prototype.overwrite = function overwrite(obj) { - const keys = Array.from(new Set(Object.keys(this._doc).concat(Object.keys(obj)))); - - for (const key of keys) { - if (key === '_id') { - continue; - } - // Explicitly skip version key - if (this.schema.options.versionKey && key === this.schema.options.versionKey) { - continue; - } - if (this.schema.options.discriminatorKey && key === this.schema.options.discriminatorKey) { - continue; - } - this.$set(key, obj[key]); - } - - return this; -}; - -/** - * Alias for `set()`, used internally to avoid conflicts - * - * @param {String|Object} path path or object of key/vals to set - * @param {Any} val the value to set - * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes - * @param {Object} [options] optionally specify options that modify the behavior of the set - * @method $set - * @name $set - * @memberOf Document - * @instance - * @api public - */ - -Document.prototype.$set = function $set(path, val, type, options) { - if (utils.isPOJO(type)) { - options = type; - type = undefined; - } - - options = options || {}; - const merge = options.merge; - const adhoc = type && type !== true; - const constructing = type === true; - let adhocs; - let keys; - let i = 0; - let pathtype; - let key; - let prefix; - - const strict = 'strict' in options - ? options.strict - : this.$__.strictMode; - - if (adhoc) { - adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); - adhocs[path] = this.schema.interpretAsType(path, type, this.schema.options); - } - - if (typeof path !== 'string') { - // new Document({ key: val }) - if (path instanceof Document) { - if (path.$__isNested) { - path = path.toObject(); - } else { - path = path._doc; - } - } - - if (path == null) { - const _ = path; - path = val; - val = _; - } else { - prefix = val ? val + '.' : ''; - - keys = Object.keys(path); - const len = keys.length; - - // `_skipMinimizeTopLevel` is because we may have deleted the top-level - // nested key to ensure key order. - const _skipMinimizeTopLevel = get(options, '_skipMinimizeTopLevel', false); - if (len === 0 && _skipMinimizeTopLevel) { - delete options._skipMinimizeTopLevel; - if (val) { - this.$set(val, {}); - } - return this; - } - - while (i < len) { - _handleIndex.call(this, i++); - } - - return this; - } - } else { - this.$__.$setCalled.add(path); - } - - function _handleIndex(i) { - key = keys[i]; - const pathName = prefix + key; - pathtype = this.schema.pathType(pathName); - - // On initial set, delete any nested keys if we're going to overwrite - // them to ensure we keep the user's key order. - if (type === true && - !prefix && - path[key] != null && - pathtype === 'nested' && - this._doc[key] != null && - Object.keys(this._doc[key]).length === 0) { - delete this._doc[key]; - // Make sure we set `{}` back even if we minimize re: gh-8565 - options = Object.assign({}, options, { _skipMinimizeTopLevel: true }); - } - - if (typeof path[key] === 'object' && - !utils.isNativeObject(path[key]) && - !utils.isMongooseType(path[key]) && - path[key] != null && - pathtype !== 'virtual' && - pathtype !== 'real' && - pathtype !== 'adhocOrUndefined' && - !(this.$__path(pathName) instanceof MixedSchema) && - !(this.schema.paths[pathName] && - this.schema.paths[pathName].options && - this.schema.paths[pathName].options.ref)) { - this.$__.$setCalled.add(prefix + key); - this.$set(path[key], prefix + key, constructing, options); - } else if (strict) { - // Don't overwrite defaults with undefined keys (gh-3981) - if (constructing && path[key] === void 0 && - this.get(key) !== void 0) { - return; - } - - if (pathtype === 'adhocOrUndefined') { - pathtype = getEmbeddedDiscriminatorPath(this, pathName, { typeOnly: true }); - } - - if (pathtype === 'real' || pathtype === 'virtual') { - // Check for setting single embedded schema to document (gh-3535) - let p = path[key]; - if (this.schema.paths[pathName] && - this.schema.paths[pathName].$isSingleNested && - path[key] instanceof Document) { - p = p.toObject({ virtuals: false, transform: false }); - } - this.$set(prefix + key, p, constructing, options); - } else if (pathtype === 'nested' && path[key] instanceof Document) { - this.$set(prefix + key, - path[key].toObject({ transform: false }), constructing, options); - } else if (strict === 'throw') { - if (pathtype === 'nested') { - throw new ObjectExpectedError(key, path[key]); - } else { - throw new StrictModeError(key); - } - } - } else if (path[key] !== void 0) { - this.$set(prefix + key, path[key], constructing, options); - } - } - - let pathType = this.schema.pathType(path); - if (pathType === 'adhocOrUndefined') { - pathType = getEmbeddedDiscriminatorPath(this, path, { typeOnly: true }); - } - - // Assume this is a Mongoose document that was copied into a POJO using - // `Object.assign()` or `{...doc}` - val = handleSpreadDoc(val); - - if (pathType === 'nested' && val) { - if (typeof val === 'object' && val != null) { - if (!merge) { - this.$__setValue(path, null); - cleanModifiedSubpaths(this, path); - } else { - return this.$set(val, path, constructing); - } - - const keys = Object.keys(val); - this.$__setValue(path, {}); - for (const key of keys) { - this.$set(path + '.' + key, val[key], constructing); - } - this.markModified(path); - cleanModifiedSubpaths(this, path, { skipDocArrays: true }); - return this; - } - this.invalidate(path, new MongooseError.CastError('Object', val, path)); - return this; - } - - let schema; - const parts = path.indexOf('.') === -1 ? [path] : path.split('.'); - - // Might need to change path for top-level alias - if (typeof this.schema.aliases[parts[0]] == 'string') { - parts[0] = this.schema.aliases[parts[0]]; - } - - if (pathType === 'adhocOrUndefined' && strict) { - // check for roots that are Mixed types - let mixed; - - for (i = 0; i < parts.length; ++i) { - const subpath = parts.slice(0, i + 1).join('.'); - - // If path is underneath a virtual, bypass everything and just set it. - if (i + 1 < parts.length && this.schema.pathType(subpath) === 'virtual') { - mpath.set(path, val, this); - return this; - } - - schema = this.schema.path(subpath); - if (schema == null) { - continue; - } - - if (schema instanceof MixedSchema) { - // allow changes to sub paths of mixed types - mixed = true; - break; - } - } - - if (schema == null) { - // Check for embedded discriminators - schema = getEmbeddedDiscriminatorPath(this, path); - } - - if (!mixed && !schema) { - if (strict === 'throw') { - throw new StrictModeError(path); - } - return this; - } - } else if (pathType === 'virtual') { - schema = this.schema.virtualpath(path); - schema.applySetters(val, this); - return this; - } else { - schema = this.$__path(path); - } - - // gh-4578, if setting a deeply nested path that doesn't exist yet, create it - let cur = this._doc; - let curPath = ''; - for (i = 0; i < parts.length - 1; ++i) { - cur = cur[parts[i]]; - curPath += (curPath.length > 0 ? '.' : '') + parts[i]; - if (!cur) { - this.$set(curPath, {}); - // Hack re: gh-5800. If nested field is not selected, it probably exists - // so `MongoError: cannot use the part (nested of nested.num) to - // traverse the element ({nested: null})` is not likely. If user gets - // that error, its their fault for now. We should reconsider disallowing - // modifying not selected paths for 6.x - if (!this.isSelected(curPath)) { - this.unmarkModified(curPath); - } - cur = this.$__getValue(curPath); - } - } - - let pathToMark; - - // When using the $set operator the path to the field must already exist. - // Else mongodb throws: "LEFT_SUBFIELD only supports Object" - - if (parts.length <= 1) { - pathToMark = path; - } else { - for (i = 0; i < parts.length; ++i) { - const subpath = parts.slice(0, i + 1).join('.'); - if (this.get(subpath, null, { getters: false }) === null) { - pathToMark = subpath; - break; - } - } - - if (!pathToMark) { - pathToMark = path; - } - } - - // if this doc is being constructed we should not trigger getters - const priorVal = (() => { - if (this.$__.$options.priorDoc != null) { - return this.$__.$options.priorDoc.$__getValue(path); - } - if (constructing) { - return void 0; - } - return this.$__getValue(path); - })(); - - if (!schema) { - this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); - return this; - } - - if (schema.$isSingleNested && val != null && merge) { - if (val instanceof Document) { - val = val.toObject({ virtuals: false, transform: false }); - } - const keys = Object.keys(val); - for (const key of keys) { - this.$set(path + '.' + key, val[key], constructing, options); - } - - return this; - } - - let shouldSet = true; - try { - // If the user is trying to set a ref path to a document with - // the correct model name, treat it as populated - const refMatches = (() => { - if (schema.options == null) { - return false; - } - if (!(val instanceof Document)) { - return false; - } - const model = val.constructor; - - // Check ref - const ref = schema.options.ref; - if (ref != null && (ref === model.modelName || ref === model.baseModelName)) { - return true; - } - - // Check refPath - const refPath = schema.options.refPath; - if (refPath == null) { - return false; - } - const modelName = val.get(refPath); - return modelName === model.modelName || modelName === model.baseModelName; - })(); - - let didPopulate = false; - if (refMatches && val instanceof Document) { - this.populated(path, val._id, { [populateModelSymbol]: val.constructor }); - didPopulate = true; - } - - let popOpts; - if (schema.options && - Array.isArray(schema.options[this.schema.options.typeKey]) && - schema.options[this.schema.options.typeKey].length && - schema.options[this.schema.options.typeKey][0].ref && - _isManuallyPopulatedArray(val, schema.options[this.schema.options.typeKey][0].ref)) { - if (this.ownerDocument) { - popOpts = { [populateModelSymbol]: val[0].constructor }; - this.ownerDocument().populated(this.$__fullPath(path), - val.map(function(v) { return v._id; }), popOpts); - } else { - popOpts = { [populateModelSymbol]: val[0].constructor }; - this.populated(path, val.map(function(v) { return v._id; }), popOpts); - } - didPopulate = true; - } - - if (this.schema.singleNestedPaths[path] == null) { - // If this path is underneath a single nested schema, we'll call the setter - // later in `$__set()` because we don't take `_doc` when we iterate through - // a single nested doc. That's to make sure we get the correct context. - // Otherwise we would double-call the setter, see gh-7196. - val = schema.applySetters(val, this, false, priorVal); - } - - if (schema.$isMongooseDocumentArray && - Array.isArray(val) && - val.length > 0 && - val[0] != null && - val[0].$__ != null && - val[0].$__.populated != null) { - const populatedPaths = Object.keys(val[0].$__.populated); - for (const populatedPath of populatedPaths) { - this.populated(path + '.' + populatedPath, - val.map(v => v.populated(populatedPath)), - val[0].$__.populated[populatedPath].options); - } - didPopulate = true; - } - - if (!didPopulate && this.$__.populated) { - // If this array partially contains populated documents, convert them - // all to ObjectIds re: #8443 - if (Array.isArray(val) && this.$__.populated[path]) { - for (let i = 0; i < val.length; ++i) { - if (val[i] instanceof Document) { - val[i] = val[i]._id; - } - } - } - delete this.$__.populated[path]; - } - - this.$markValid(path); - } catch (e) { - if (e instanceof MongooseError.StrictModeError && e.isImmutableError) { - this.invalidate(path, e); - } else if (e instanceof MongooseError.CastError) { - this.invalidate(e.path, e); - if (e.$originalErrorPath) { - this.invalidate(path, - new MongooseError.CastError(schema.instance, val, path, e.$originalErrorPath)); - } - } else { - this.invalidate(path, - new MongooseError.CastError(schema.instance, val, path, e)); - } - shouldSet = false; - } - - if (shouldSet) { - this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); - } - - if (schema.$isSingleNested && (this.isDirectModified(path) || val == null)) { - cleanModifiedSubpaths(this, path); - } - - return this; -}; - -/*! - * ignore - */ - -function _isManuallyPopulatedArray(val, ref) { - if (!Array.isArray(val)) { - return false; - } - if (val.length === 0) { - return false; - } - - for (const el of val) { - if (!(el instanceof Document)) { - return false; - } - const modelName = el.constructor.modelName; - if (modelName == null) { - return false; - } - if (el.constructor.modelName != ref && el.constructor.baseModelName != ref) { - return false; - } - } - - return true; -} - -/** - * Sets the value of a path, or many paths. - * - * ####Example: - * - * // path, value - * doc.set(path, value) - * - * // object - * doc.set({ - * path : value - * , path2 : { - * path : value - * } - * }) - * - * // on-the-fly cast to number - * doc.set(path, value, Number) - * - * // on-the-fly cast to string - * doc.set(path, value, String) - * - * // changing strict mode behavior - * doc.set(path, value, { strict: false }); - * - * @param {String|Object} path path or object of key/vals to set - * @param {Any} val the value to set - * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for "on-the-fly" attributes - * @param {Object} [options] optionally specify options that modify the behavior of the set - * @api public - * @method set - * @memberOf Document - * @instance - */ - -Document.prototype.set = Document.prototype.$set; - -/** - * Determine if we should mark this change as modified. - * - * @return {Boolean} - * @api private - * @method $__shouldModify - * @memberOf Document - * @instance - */ - -Document.prototype.$__shouldModify = function(pathToMark, path, constructing, parts, schema, val, priorVal) { - if (this.isNew) { - return true; - } - - // Re: the note about gh-7196, `val` is the raw value without casting or - // setters if the full path is under a single nested subdoc because we don't - // want to double run setters. So don't set it as modified. See gh-7264. - if (this.schema.singleNestedPaths[path] != null) { - return false; - } - - if (val === void 0 && !this.isSelected(path)) { - // when a path is not selected in a query, its initial - // value will be undefined. - return true; - } - - if (val === void 0 && path in this.$__.activePaths.states.default) { - // we're just unsetting the default value which was never saved - return false; - } - - // gh-3992: if setting a populated field to a doc, don't mark modified - // if they have the same _id - if (this.populated(path) && - val instanceof Document && - deepEqual(val._id, priorVal)) { - return false; - } - - if (!deepEqual(val, priorVal || this.get(path))) { - return true; - } - - if (!constructing && - val !== null && - val !== undefined && - path in this.$__.activePaths.states.default && - deepEqual(val, schema.getDefault(this, constructing))) { - // a path with a default was $unset on the server - // and the user is setting it to the same value again - return true; - } - return false; -}; - -/** - * Handles the actual setting of the value and marking the path modified if appropriate. - * - * @api private - * @method $__set - * @memberOf Document - * @instance - */ - -Document.prototype.$__set = function(pathToMark, path, constructing, parts, schema, val, priorVal) { - Embedded = Embedded || require('./types/embedded'); - - const shouldModify = this.$__shouldModify(pathToMark, path, constructing, parts, - schema, val, priorVal); - const _this = this; - - if (shouldModify) { - this.markModified(pathToMark); - - // handle directly setting arrays (gh-1126) - MongooseArray || (MongooseArray = require('./types/array')); - if (val && val.isMongooseArray) { - val._registerAtomic('$set', val); - - // Update embedded document parent references (gh-5189) - if (val.isMongooseDocumentArray) { - val.forEach(function(item) { - item && item.__parentArray && (item.__parentArray = val); - }); - } - - // Small hack for gh-1638: if we're overwriting the entire array, ignore - // paths that were modified before the array overwrite - this.$__.activePaths.forEach(function(modifiedPath) { - if (modifiedPath.startsWith(path + '.')) { - _this.$__.activePaths.ignore(modifiedPath); - } - }); - } - } - - let obj = this._doc; - let i = 0; - const l = parts.length; - let cur = ''; - - for (; i < l; i++) { - const next = i + 1; - const last = next === l; - cur += (cur ? '.' + parts[i] : parts[i]); - if (specialProperties.has(parts[i])) { - return; - } - - if (last) { - if (obj instanceof Map) { - obj.set(parts[i], val); - } else { - obj[parts[i]] = val; - } - } else { - if (utils.isPOJO(obj[parts[i]])) { - obj = obj[parts[i]]; - } else if (obj[parts[i]] && obj[parts[i]] instanceof Embedded) { - obj = obj[parts[i]]; - } else if (obj[parts[i]] && obj[parts[i]].$isSingleNested) { - obj = obj[parts[i]]; - } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) { - obj = obj[parts[i]]; - } else { - obj[parts[i]] = obj[parts[i]] || {}; - obj = obj[parts[i]]; - } - } - } -}; - -/** - * Gets a raw value from a path (no getters) - * - * @param {String} path - * @api private - */ - -Document.prototype.$__getValue = function(path) { - return utils.getValue(path, this._doc); -}; - -/** - * Sets a raw value for a path (no casting, setters, transformations) - * - * @param {String} path - * @param {Object} value - * @api private - */ - -Document.prototype.$__setValue = function(path, val) { - utils.setValue(path, val, this._doc); - return this; -}; - -/** - * Returns the value of a path. - * - * ####Example - * - * // path - * doc.get('age') // 47 - * - * // dynamic casting to a string - * doc.get('age', String) // "47" - * - * @param {String} path - * @param {Schema|String|Number|Buffer|*} [type] optionally specify a type for on-the-fly attributes - * @param {Object} [options] - * @param {Boolean} [options.virtuals=false] Apply virtuals before getting this path - * @param {Boolean} [options.getters=true] If false, skip applying getters and just get the raw value - * @api public - */ - -Document.prototype.get = function(path, type, options) { - let adhoc; - options = options || {}; - if (type) { - adhoc = this.schema.interpretAsType(path, type, this.schema.options); - } - - let schema = this.$__path(path); - if (schema == null) { - schema = this.schema.virtualpath(path); - } - if (schema instanceof MixedSchema) { - const virtual = this.schema.virtualpath(path); - if (virtual != null) { - schema = virtual; - } - } - const pieces = path.split('.'); - let obj = this._doc; - - if (schema instanceof VirtualType) { - if (schema.getters.length === 0) { - return void 0; - } - return schema.applyGetters(null, this); - } - - // Might need to change path for top-level alias - if (typeof this.schema.aliases[pieces[0]] == 'string') { - pieces[0] = this.schema.aliases[pieces[0]]; - } - - for (let i = 0, l = pieces.length; i < l; i++) { - if (obj && obj._doc) { - obj = obj._doc; - } - - if (obj == null) { - obj = void 0; - } else if (obj instanceof Map) { - obj = obj.get(pieces[i], { getters: false }); - } else if (i === l - 1) { - obj = utils.getValue(pieces[i], obj); - } else { - obj = obj[pieces[i]]; - } - } - - if (adhoc) { - obj = adhoc.cast(obj); - } - - if (schema != null && options.getters !== false) { - obj = schema.applyGetters(obj, this); - } else if (this.schema.nested[path] && options.virtuals) { - // Might need to apply virtuals if this is a nested path - return applyVirtuals(this, utils.clone(obj) || {}, { path: path }); - } - - return obj; -}; - -/*! - * ignore - */ - -Document.prototype[getSymbol] = Document.prototype.get; - -/** - * Returns the schematype for the given `path`. - * - * @param {String} path - * @api private - * @method $__path - * @memberOf Document - * @instance - */ - -Document.prototype.$__path = function(path) { - const adhocs = this.$__.adhocPaths; - const adhocType = adhocs && adhocs.hasOwnProperty(path) ? adhocs[path] : null; - - if (adhocType) { - return adhocType; - } - return this.schema.path(path); -}; - -/** - * Marks the path as having pending changes to write to the db. - * - * _Very helpful when using [Mixed](./schematypes.html#mixed) types._ - * - * ####Example: - * - * doc.mixed.type = 'changed'; - * doc.markModified('mixed.type'); - * doc.save() // changes to mixed.type are now persisted - * - * @param {String} path the path to mark modified - * @param {Document} [scope] the scope to run validators with - * @api public - */ - -Document.prototype.markModified = function(path, scope) { - this.$__.activePaths.modify(path); - if (scope != null && !this.ownerDocument) { - this.$__.pathsToScopes[path] = scope; - } -}; - -/** - * Clears the modified state on the specified path. - * - * ####Example: - * - * doc.foo = 'bar'; - * doc.unmarkModified('foo'); - * doc.save(); // changes to foo will not be persisted - * - * @param {String} path the path to unmark modified - * @api public - */ - -Document.prototype.unmarkModified = function(path) { - this.$__.activePaths.init(path); - delete this.$__.pathsToScopes[path]; -}; - -/** - * Don't run validation on this path or persist changes to this path. - * - * ####Example: - * - * doc.foo = null; - * doc.$ignore('foo'); - * doc.save(); // changes to foo will not be persisted and validators won't be run - * - * @memberOf Document - * @instance - * @method $ignore - * @param {String} path the path to ignore - * @api public - */ - -Document.prototype.$ignore = function(path) { - this.$__.activePaths.ignore(path); -}; - -/** - * Returns the list of paths that have been directly modified. A direct - * modified path is a path that you explicitly set, whether via `doc.foo = 'bar'`, - * `Object.assign(doc, { foo: 'bar' })`, or `doc.set('foo', 'bar')`. - * - * A path `a` may be in `modifiedPaths()` but not in `directModifiedPaths()` - * because a child of `a` was directly modified. - * - * ####Example - * const schema = new Schema({ foo: String, nested: { bar: String } }); - * const Model = mongoose.model('Test', schema); - * await Model.create({ foo: 'original', nested: { bar: 'original' } }); - * - * const doc = await Model.findOne(); - * doc.nested.bar = 'modified'; - * doc.directModifiedPaths(); // ['nested.bar'] - * doc.modifiedPaths(); // ['nested', 'nested.bar'] - * - * @return {Array} - * @api public - */ - -Document.prototype.directModifiedPaths = function() { - return Object.keys(this.$__.activePaths.states.modify); -}; - -/** - * Returns true if the given path is nullish or only contains empty objects. - * Useful for determining whether this subdoc will get stripped out by the - * [minimize option](/docs/guide.html#minimize). - * - * ####Example: - * const schema = new Schema({ nested: { foo: String } }); - * const Model = mongoose.model('Test', schema); - * const doc = new Model({}); - * doc.$isEmpty('nested'); // true - * doc.nested.$isEmpty(); // true - * - * doc.nested.foo = 'bar'; - * doc.$isEmpty('nested'); // false - * doc.nested.$isEmpty(); // false - * - * @memberOf Document - * @instance - * @api public - * @method $isEmpty - * @return {Boolean} - */ - -Document.prototype.$isEmpty = function(path) { - const isEmptyOptions = { - minimize: true, - virtuals: false, - getters: false, - transform: false - }; - - if (arguments.length > 0) { - const v = this.get(path); - if (v == null) { - return true; - } - if (typeof v !== 'object') { - return false; - } - if (utils.isPOJO(v)) { - return _isEmpty(v); - } - return Object.keys(v.toObject(isEmptyOptions)).length === 0; - } - - return Object.keys(this.toObject(isEmptyOptions)).length === 0; -}; - -function _isEmpty(v) { - if (v == null) { - return true; - } - if (typeof v !== 'object' || Array.isArray(v)) { - return false; - } - for (const key of Object.keys(v)) { - if (!_isEmpty(v[key])) { - return false; - } - } - return true; -} - -/** - * Returns the list of paths that have been modified. - * - * @param {Object} [options] - * @param {Boolean} [options.includeChildren=false] if true, returns children of modified paths as well. For example, if false, the list of modified paths for `doc.colors = { primary: 'blue' };` will **not** contain `colors.primary`. If true, `modifiedPaths()` will return an array that contains `colors.primary`. - * @return {Array} - * @api public - */ - -Document.prototype.modifiedPaths = function(options) { - options = options || {}; - const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); - const _this = this; - return directModifiedPaths.reduce(function(list, path) { - const parts = path.split('.'); - list = list.concat(parts.reduce(function(chains, part, i) { - return chains.concat(parts.slice(0, i).concat(part).join('.')); - }, []).filter(function(chain) { - return (list.indexOf(chain) === -1); - })); - - if (!options.includeChildren) { - return list; - } - - let cur = _this.get(path); - if (cur != null && typeof cur === 'object') { - if (cur._doc) { - cur = cur._doc; - } - if (Array.isArray(cur)) { - const len = cur.length; - for (let i = 0; i < len; ++i) { - if (list.indexOf(path + '.' + i) === -1) { - list.push(path + '.' + i); - if (cur[i] != null && cur[i].$__) { - const modified = cur[i].modifiedPaths(); - for (const childPath of modified) { - list.push(path + '.' + i + '.' + childPath); - } - } - } - } - } else { - Object.keys(cur). - filter(function(key) { - return list.indexOf(path + '.' + key) === -1; - }). - forEach(function(key) { - list.push(path + '.' + key); - }); - } - } - - return list; - }, []); -}; - -/** - * Returns true if this document was modified, else false. - * - * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified. - * - * ####Example - * - * doc.set('documents.0.title', 'changed'); - * doc.isModified() // true - * doc.isModified('documents') // true - * doc.isModified('documents.0.title') // true - * doc.isModified('documents otherProp') // true - * doc.isDirectModified('documents') // false - * - * @param {String} [path] optional - * @return {Boolean} - * @api public - */ - -Document.prototype.isModified = function(paths, modifiedPaths) { - if (paths) { - if (!Array.isArray(paths)) { - paths = paths.split(' '); - } - const modified = modifiedPaths || this.modifiedPaths(); - const directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); - const isModifiedChild = paths.some(function(path) { - return !!~modified.indexOf(path); - }); - return isModifiedChild || paths.some(function(path) { - return directModifiedPaths.some(function(mod) { - return mod === path || path.startsWith(mod + '.'); - }); - }); - } - return this.$__.activePaths.some('modify'); -}; - -/** - * Checks if a path is set to its default. - * - * ####Example - * - * MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} }); - * const m = new MyModel(); - * m.$isDefault('name'); // true - * - * @memberOf Document - * @instance - * @method $isDefault - * @param {String} [path] - * @return {Boolean} - * @api public - */ - -Document.prototype.$isDefault = function(path) { - return (path in this.$__.activePaths.states.default); -}; - -/** - * Getter/setter, determines whether the document was removed or not. - * - * ####Example: - * product.remove(function (err, product) { - * product.$isDeleted(); // true - * product.remove(); // no-op, doesn't send anything to the db - * - * product.$isDeleted(false); - * product.$isDeleted(); // false - * product.remove(); // will execute a remove against the db - * }) - * - * @param {Boolean} [val] optional, overrides whether mongoose thinks the doc is deleted - * @return {Boolean} whether mongoose thinks this doc is deleted. - * @method $isDeleted - * @memberOf Document - * @instance - * @api public - */ - -Document.prototype.$isDeleted = function(val) { - if (arguments.length === 0) { - return !!this.$__.isDeleted; - } - - this.$__.isDeleted = !!val; - return this; -}; - -/** - * Returns true if `path` was directly set and modified, else false. - * - * ####Example - * - * doc.set('documents.0.title', 'changed'); - * doc.isDirectModified('documents.0.title') // true - * doc.isDirectModified('documents') // false - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isDirectModified = function(path) { - return (path in this.$__.activePaths.states.modify); -}; - -/** - * Checks if `path` was initialized. - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isInit = function(path) { - return (path in this.$__.activePaths.states.init); -}; - -/** - * Checks if `path` was selected in the source query which initialized this document. - * - * ####Example - * - * Thing.findOne().select('name').exec(function (err, doc) { - * doc.isSelected('name') // true - * doc.isSelected('age') // false - * }) - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isSelected = function isSelected(path) { - if (this.$__.selected) { - if (path === '_id') { - return this.$__.selected._id !== 0; - } - - const paths = Object.keys(this.$__.selected); - let i = paths.length; - let inclusive = null; - let cur; - - if (i === 1 && paths[0] === '_id') { - // only _id was selected. - return this.$__.selected._id === 0; - } - - while (i--) { - cur = paths[i]; - if (cur === '_id') { - continue; - } - if (!isDefiningProjection(this.$__.selected[cur])) { - continue; - } - inclusive = !!this.$__.selected[cur]; - break; - } - - if (inclusive === null) { - return true; - } - - if (path in this.$__.selected) { - return inclusive; - } - - i = paths.length; - const pathDot = path + '.'; - - while (i--) { - cur = paths[i]; - if (cur === '_id') { - continue; - } - - if (cur.startsWith(pathDot)) { - return inclusive || cur !== pathDot; - } - - if (pathDot.startsWith(cur + '.')) { - return inclusive; - } - } - - return !inclusive; - } - - return true; -}; - -/** - * Checks if `path` was explicitly selected. If no projection, always returns - * true. - * - * ####Example - * - * Thing.findOne().select('nested.name').exec(function (err, doc) { - * doc.isDirectSelected('nested.name') // true - * doc.isDirectSelected('nested.otherName') // false - * doc.isDirectSelected('nested') // false - * }) - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isDirectSelected = function isDirectSelected(path) { - if (this.$__.selected) { - if (path === '_id') { - return this.$__.selected._id !== 0; - } - - const paths = Object.keys(this.$__.selected); - let i = paths.length; - let inclusive = null; - let cur; - - if (i === 1 && paths[0] === '_id') { - // only _id was selected. - return this.$__.selected._id === 0; - } - - while (i--) { - cur = paths[i]; - if (cur === '_id') { - continue; - } - if (!isDefiningProjection(this.$__.selected[cur])) { - continue; - } - inclusive = !!this.$__.selected[cur]; - break; - } - - if (inclusive === null) { - return true; - } - - if (path in this.$__.selected) { - return inclusive; - } - - return !inclusive; - } - - return true; -}; - -/** - * Executes registered validation rules for this document. - * - * ####Note: - * - * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`. - * - * ####Example: - * - * doc.validate(function (err) { - * if (err) handleError(err); - * else // validation passed - * }); - * - * @param {Array|String} [pathsToValidate] list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list. - * @param {Object} [options] internal options - * @param {Function} [callback] optional callback called after validation completes, passing an error if one occurred - * @return {Promise} Promise - * @api public - */ - -Document.prototype.validate = function(pathsToValidate, options, callback) { - let parallelValidate; - this.$op = 'validate'; - - if (this.ownerDocument != null) { - // Skip parallel validate check for subdocuments - } else if (this.$__.validating) { - parallelValidate = new ParallelValidateError(this, { - parentStack: options && options.parentStack, - conflictStack: this.$__.validating.stack - }); - } else { - this.$__.validating = new ParallelValidateError(this, { parentStack: options && options.parentStack }); - } - - if (typeof pathsToValidate === 'function') { - callback = pathsToValidate; - options = null; - pathsToValidate = null; - } else if (typeof options === 'function') { - callback = options; - options = pathsToValidate; - pathsToValidate = null; - } - - return promiseOrCallback(callback, cb => { - if (parallelValidate != null) { - return cb(parallelValidate); - } - - this.$__validate(pathsToValidate, options, (error) => { - this.$op = null; - cb(error); - }); - }, this.constructor.events); -}; - -/*! - * ignore - */ - -function _evaluateRequiredFunctions(doc) { - Object.keys(doc.$__.activePaths.states.require).forEach(path => { - const p = doc.schema.path(path); - - if (p != null && typeof p.originalRequiredValue === 'function') { - doc.$__.cachedRequired[path] = p.originalRequiredValue.call(doc); - } - }); -} - -/*! - * ignore - */ - -function _getPathsToValidate(doc) { - const skipSchemaValidators = {}; - - _evaluateRequiredFunctions(doc); - - // only validate required fields when necessary - let paths = new Set(Object.keys(doc.$__.activePaths.states.require).filter(function(path) { - if (!doc.isSelected(path) && !doc.isModified(path)) { - return false; - } - if (path in doc.$__.cachedRequired) { - return doc.$__.cachedRequired[path]; - } - return true; - })); - - - Object.keys(doc.$__.activePaths.states.init).forEach(addToPaths); - Object.keys(doc.$__.activePaths.states.modify).forEach(addToPaths); - Object.keys(doc.$__.activePaths.states.default).forEach(addToPaths); - function addToPaths(p) { paths.add(p); } - - const subdocs = doc.$__getAllSubdocs(); - const modifiedPaths = doc.modifiedPaths(); - for (const subdoc of subdocs) { - if (subdoc.$basePath) { - // Remove child paths for now, because we'll be validating the whole - // subdoc - for (const p of paths) { - if (p === null || p.startsWith(subdoc.$basePath + '.')) { - paths.delete(p); - } - } - - if (doc.isModified(subdoc.$basePath, modifiedPaths) && - !doc.isDirectModified(subdoc.$basePath) && - !doc.$isDefault(subdoc.$basePath)) { - paths.add(subdoc.$basePath); - - skipSchemaValidators[subdoc.$basePath] = true; - } - } - } - - // from here on we're not removing items from paths - - // gh-661: if a whole array is modified, make sure to run validation on all - // the children as well - for (const path of paths) { - const _pathType = doc.schema.path(path); - if (!_pathType || - !_pathType.$isMongooseArray || - // To avoid potential performance issues, skip doc arrays whose children - // are not required. `getPositionalPathType()` may be slow, so avoid - // it unless we have a case of #6364 - (_pathType.$isMongooseDocumentArray && !get(_pathType, 'schemaOptions.required'))) { - continue; - } - - const val = doc.$__getValue(path); - _pushNestedArrayPaths(val, paths, path); - } - - function _pushNestedArrayPaths(val, paths, path) { - if (val != null) { - const numElements = val.length; - for (let j = 0; j < numElements; ++j) { - if (Array.isArray(val[j])) { - _pushNestedArrayPaths(val[j], paths, path + '.' + j); - } else { - paths.add(path + '.' + j); - } - } - } - } - - const flattenOptions = { skipArrays: true }; - for (const pathToCheck of paths) { - if (doc.schema.nested[pathToCheck]) { - let _v = doc.$__getValue(pathToCheck); - if (isMongooseObject(_v)) { - _v = _v.toObject({ transform: false }); - } - const flat = flatten(_v, pathToCheck, flattenOptions, doc.schema); - Object.keys(flat).forEach(addToPaths); - } - } - - - for (const path of paths) { - // Single nested paths (paths embedded under single nested subdocs) will - // be validated on their own when we call `validate()` on the subdoc itself. - // Re: gh-8468 - if (doc.schema.singleNestedPaths.hasOwnProperty(path)) { - paths.delete(path); - continue; - } - const _pathType = doc.schema.path(path); - if (!_pathType || !_pathType.$isSchemaMap) { - continue; - } - - const val = doc.$__getValue(path); - if (val == null) { - continue; - } - for (const key of val.keys()) { - paths.add(path + '.' + key); - } - } - - paths = Array.from(paths); - return [paths, skipSchemaValidators]; -} - -/*! - * ignore - */ - -Document.prototype.$__validate = function(pathsToValidate, options, callback) { - if (typeof pathsToValidate === 'function') { - callback = pathsToValidate; - options = null; - pathsToValidate = null; - } else if (typeof options === 'function') { - callback = options; - options = null; - } - - const hasValidateModifiedOnlyOption = options && - (typeof options === 'object') && - ('validateModifiedOnly' in options); - - let shouldValidateModifiedOnly; - if (hasValidateModifiedOnlyOption) { - shouldValidateModifiedOnly = !!options.validateModifiedOnly; - } else { - shouldValidateModifiedOnly = this.schema.options.validateModifiedOnly; - } - - const _this = this; - const _complete = () => { - let validationError = this.$__.validationError; - this.$__.validationError = undefined; - - if (shouldValidateModifiedOnly && validationError != null) { - // Remove any validation errors that aren't from modified paths - const errors = Object.keys(validationError.errors); - for (const errPath of errors) { - if (!this.isModified(errPath)) { - delete validationError.errors[errPath]; - } - } - if (Object.keys(validationError.errors).length === 0) { - validationError = void 0; - } - } - - this.$__.cachedRequired = {}; - this.emit('validate', _this); - this.constructor.emit('validate', _this); - - this.$__.validating = null; - if (validationError) { - for (const key in validationError.errors) { - // Make sure cast errors persist - if (!this[documentArrayParent] && - validationError.errors[key] instanceof MongooseError.CastError) { - this.invalidate(key, validationError.errors[key]); - } - } - - return validationError; - } - }; - - // only validate required fields when necessary - const pathDetails = _getPathsToValidate(this); - let paths = shouldValidateModifiedOnly ? - pathDetails[0].filter((path) => this.isModified(path)) : - pathDetails[0]; - const skipSchemaValidators = pathDetails[1]; - - if (Array.isArray(pathsToValidate)) { - paths = _handlePathsToValidate(paths, pathsToValidate); - } - - if (paths.length === 0) { - return process.nextTick(function() { - const error = _complete(); - if (error) { - return _this.schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) { - callback(error); - }); - } - callback(null, _this); - }); - } - - const validated = {}; - let total = 0; - - const complete = function() { - const error = _complete(); - if (error) { - return _this.schema.s.hooks.execPost('validate:error', _this, [_this], { error: error }, function(error) { - callback(error); - }); - } - callback(null, _this); - }; - - const validatePath = function(path) { - if (path == null || validated[path]) { - return; - } - - validated[path] = true; - total++; - - process.nextTick(function() { - const schemaType = _this.schema.path(path); - - if (!schemaType) { - return --total || complete(); - } - - // If user marked as invalid or there was a cast error, don't validate - if (!_this.$isValid(path)) { - --total || complete(); - return; - } - - let val = _this.$__getValue(path); - - // If you `populate()` and get back a null value, required validators - // shouldn't fail (gh-8018). We should always fall back to the populated - // value. - let pop; - if (val == null && (pop = _this.populated(path))) { - val = pop; - } - const scope = path in _this.$__.pathsToScopes ? - _this.$__.pathsToScopes[path] : - _this; - - const doValidateOptions = { - skipSchemaValidators: skipSchemaValidators[path], - path: path - }; - schemaType.doValidate(val, function(err) { - if (err && (!schemaType.$isMongooseDocumentArray || err.$isArrayValidatorError)) { - if (schemaType.$isSingleNested && - err instanceof ValidationError && - schemaType.schema.options.storeSubdocValidationError === false) { - return --total || complete(); - } - _this.invalidate(path, err, undefined, true); - } - --total || complete(); - }, scope, doValidateOptions); - }); - }; - - const numPaths = paths.length; - for (let i = 0; i < numPaths; ++i) { - validatePath(paths[i]); - } -}; - -/*! - * ignore - */ - -function _handlePathsToValidate(paths, pathsToValidate) { - const _pathsToValidate = new Set(pathsToValidate); - const parentPaths = new Map([]); - for (const path of pathsToValidate) { - if (path.indexOf('.') === -1) { - continue; - } - const pieces = path.split('.'); - let cur = pieces[0]; - for (let i = 1; i < pieces.length; ++i) { - // Since we skip subpaths under single nested subdocs to - // avoid double validation, we need to add back the - // single nested subpath if the user asked for it (gh-8626) - parentPaths.set(cur, path); - cur = cur + '.' + pieces[i]; - } - } - - const ret = []; - for (const path of paths) { - if (_pathsToValidate.has(path)) { - ret.push(path); - } else if (parentPaths.has(path)) { - ret.push(parentPaths.get(path)); - } - } - return ret; -} - -/** - * Executes registered validation rules (skipping asynchronous validators) for this document. - * - * ####Note: - * - * This method is useful if you need synchronous validation. - * - * ####Example: - * - * const err = doc.validateSync(); - * if (err) { - * handleError(err); - * } else { - * // validation passed - * } - * - * @param {Array|string} pathsToValidate only validate the given paths - * @return {ValidationError|undefined} ValidationError if there are errors during validation, or undefined if there is no error. - * @api public - */ - -Document.prototype.validateSync = function(pathsToValidate, options) { - const _this = this; - - const hasValidateModifiedOnlyOption = options && - (typeof options === 'object') && - ('validateModifiedOnly' in options); - - let shouldValidateModifiedOnly; - if (hasValidateModifiedOnlyOption) { - shouldValidateModifiedOnly = !!options.validateModifiedOnly; - } else { - shouldValidateModifiedOnly = this.schema.options.validateModifiedOnly; - } - - if (typeof pathsToValidate === 'string') { - pathsToValidate = pathsToValidate.split(' '); - } - - // only validate required fields when necessary - const pathDetails = _getPathsToValidate(this); - let paths = shouldValidateModifiedOnly ? - pathDetails[0].filter((path) => this.isModified(path)) : - pathDetails[0]; - const skipSchemaValidators = pathDetails[1]; - - if (Array.isArray(pathsToValidate)) { - paths = _handlePathsToValidate(paths, pathsToValidate); - } - - const validating = {}; - - paths.forEach(function(path) { - if (validating[path]) { - return; - } - - validating[path] = true; - - const p = _this.schema.path(path); - if (!p) { - return; - } - if (!_this.$isValid(path)) { - return; - } - - const val = _this.$__getValue(path); - const err = p.doValidateSync(val, _this, { - skipSchemaValidators: skipSchemaValidators[path], - path: path - }); - if (err && (!p.$isMongooseDocumentArray || err.$isArrayValidatorError)) { - if (p.$isSingleNested && - err instanceof ValidationError && - p.schema.options.storeSubdocValidationError === false) { - return; - } - _this.invalidate(path, err, undefined, true); - } - }); - - const err = _this.$__.validationError; - _this.$__.validationError = undefined; - _this.emit('validate', _this); - _this.constructor.emit('validate', _this); - - if (err) { - for (const key in err.errors) { - // Make sure cast errors persist - if (err.errors[key] instanceof MongooseError.CastError) { - _this.invalidate(key, err.errors[key]); - } - } - } - - return err; -}; - -/** - * Marks a path as invalid, causing validation to fail. - * - * The `errorMsg` argument will become the message of the `ValidationError`. - * - * The `value` argument (if passed) will be available through the `ValidationError.value` property. - * - * doc.invalidate('size', 'must be less than 20', 14); - - * doc.validate(function (err) { - * console.log(err) - * // prints - * { message: 'Validation failed', - * name: 'ValidationError', - * errors: - * { size: - * { message: 'must be less than 20', - * name: 'ValidatorError', - * path: 'size', - * type: 'user defined', - * value: 14 } } } - * }) - * - * @param {String} path the field to invalidate - * @param {String|Error} errorMsg the error which states the reason `path` was invalid - * @param {Object|String|Number|any} value optional invalid value - * @param {String} [kind] optional `kind` property for the error - * @return {ValidationError} the current ValidationError, with all currently invalidated paths - * @api public - */ - -Document.prototype.invalidate = function(path, err, val, kind) { - if (!this.$__.validationError) { - this.$__.validationError = new ValidationError(this); - } - - if (this.$__.validationError.errors[path]) { - return; - } - - if (!err || typeof err === 'string') { - err = new ValidatorError({ - path: path, - message: err, - type: kind || 'user defined', - value: val - }); - } - - if (this.$__.validationError === err) { - return this.$__.validationError; - } - - this.$__.validationError.addError(path, err); - return this.$__.validationError; -}; - -/** - * Marks a path as valid, removing existing validation errors. - * - * @param {String} path the field to mark as valid - * @api public - * @memberOf Document - * @instance - * @method $markValid - */ - -Document.prototype.$markValid = function(path) { - if (!this.$__.validationError || !this.$__.validationError.errors[path]) { - return; - } - - delete this.$__.validationError.errors[path]; - if (Object.keys(this.$__.validationError.errors).length === 0) { - this.$__.validationError = null; - } -}; - -/** - * Saves this document. - * - * ####Example: - * - * product.sold = Date.now(); - * product = await product.save(); - * - * If save is successful, the returned promise will fulfill with the document - * saved. - * - * ####Example: - * - * const newProduct = await product.save(); - * newProduct === product; // true - * - * @param {Object} [options] options optional options - * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). - * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead. - * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. - * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) - * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) - * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). - * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) - * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. - * @param {Function} [fn] optional callback - * @method save - * @memberOf Document - * @instance - * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating). - * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. - * @api public - * @see middleware http://mongoosejs.com/docs/middleware.html - */ - -/** - * Checks if a path is invalid - * - * @param {String} path the field to check - * @method $isValid - * @memberOf Document - * @instance - * @api private - */ - -Document.prototype.$isValid = function(path) { - return !this.$__.validationError || !this.$__.validationError.errors[path]; -}; - -/** - * Resets the internal modified state of this document. - * - * @api private - * @return {Document} - * @method $__reset - * @memberOf Document - * @instance - */ - -Document.prototype.$__reset = function reset() { - let _this = this; - DocumentArray || (DocumentArray = require('./types/documentarray')); - - this.$__.activePaths - .map('init', 'modify', function(i) { - return _this.$__getValue(i); - }) - .filter(function(val) { - return val && val instanceof Array && val.isMongooseDocumentArray && val.length; - }) - .forEach(function(array) { - let i = array.length; - while (i--) { - const doc = array[i]; - if (!doc) { - continue; - } - doc.$__reset(); - } - - _this.$__.activePaths.init(array.$path()); - - array[arrayAtomicsSymbol] = {}; - }); - - this.$__.activePaths. - map('init', 'modify', function(i) { - return _this.$__getValue(i); - }). - filter(function(val) { - return val && val.$isSingleNested; - }). - forEach(function(doc) { - doc.$__reset(); - _this.$__.activePaths.init(doc.$basePath); - }); - - // clear atomics - this.$__dirty().forEach(function(dirt) { - const type = dirt.value; - - if (type && type[arrayAtomicsSymbol]) { - type[arrayAtomicsSymbol] = {}; - } - }); - - // Clear 'dirty' cache - this.$__.activePaths.clear('modify'); - this.$__.activePaths.clear('default'); - this.$__.validationError = undefined; - this.errors = undefined; - _this = this; - this.schema.requiredPaths().forEach(function(path) { - _this.$__.activePaths.require(path); - }); - - return this; -}; - -/** - * Returns this documents dirty paths / vals. - * - * @api private - * @method $__dirty - * @memberOf Document - * @instance - */ - -Document.prototype.$__dirty = function() { - const _this = this; - - let all = this.$__.activePaths.map('modify', function(path) { - return { - path: path, - value: _this.$__getValue(path), - schema: _this.$__path(path) - }; - }); - - // gh-2558: if we had to set a default and the value is not undefined, - // we have to save as well - all = all.concat(this.$__.activePaths.map('default', function(path) { - if (path === '_id' || _this.$__getValue(path) == null) { - return; - } - return { - path: path, - value: _this.$__getValue(path), - schema: _this.$__path(path) - }; - })); - - // Sort dirty paths in a flat hierarchy. - all.sort(function(a, b) { - return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0)); - }); - - // Ignore "foo.a" if "foo" is dirty already. - const minimal = []; - let lastPath; - let top; - - all.forEach(function(item) { - if (!item) { - return; - } - if (lastPath == null || item.path.indexOf(lastPath) !== 0) { - lastPath = item.path + '.'; - minimal.push(item); - top = item; - } else if (top != null && - top.value != null && - top.value[arrayAtomicsSymbol] != null && - top.value.hasAtomics()) { - // special case for top level MongooseArrays - // the `top` array itself and a sub path of `top` are being modified. - // the only way to honor all of both modifications is through a $set - // of entire array. - top.value[arrayAtomicsSymbol] = {}; - top.value[arrayAtomicsSymbol].$set = top.value; - } - }); - - top = lastPath = null; - return minimal; -}; - -/** - * Assigns/compiles `schema` into this documents prototype. - * - * @param {Schema} schema - * @api private - * @method $__setSchema - * @memberOf Document - * @instance - */ - -Document.prototype.$__setSchema = function(schema) { - schema.plugin(idGetter, { deduplicate: true }); - compile(schema.tree, this, undefined, schema.options); - - // Apply default getters if virtual doesn't have any (gh-6262) - for (const key of Object.keys(schema.virtuals)) { - schema.virtuals[key]._applyDefaultGetters(); - } - - this.schema = schema; - this[documentSchemaSymbol] = schema; -}; - - -/** - * Get active path that were changed and are arrays - * - * @api private - * @method $__getArrayPathsToValidate - * @memberOf Document - * @instance - */ - -Document.prototype.$__getArrayPathsToValidate = function() { - DocumentArray || (DocumentArray = require('./types/documentarray')); - - // validate all document arrays. - return this.$__.activePaths - .map('init', 'modify', function(i) { - return this.$__getValue(i); - }.bind(this)) - .filter(function(val) { - return val && val instanceof Array && val.isMongooseDocumentArray && val.length; - }).reduce(function(seed, array) { - return seed.concat(array); - }, []) - .filter(function(doc) { - return doc; - }); -}; - - -/** - * Get all subdocs (by bfs) - * - * @api private - * @method $__getAllSubdocs - * @memberOf Document - * @instance - */ - -Document.prototype.$__getAllSubdocs = function() { - DocumentArray || (DocumentArray = require('./types/documentarray')); - Embedded = Embedded || require('./types/embedded'); - - function docReducer(doc, seed, path) { - let val = doc; - if (path) { - if (doc instanceof Document && doc[documentSchemaSymbol].paths[path]) { - val = doc._doc[path]; - } else { - val = doc[path]; - } - } - if (val instanceof Embedded) { - seed.push(val); - } else if (val instanceof Map) { - seed = Array.from(val.keys()).reduce(function(seed, path) { - return docReducer(val.get(path), seed, null); - }, seed); - } else if (val && val.$isSingleNested) { - seed = Object.keys(val._doc).reduce(function(seed, path) { - return docReducer(val._doc, seed, path); - }, seed); - seed.push(val); - } else if (val && val.isMongooseDocumentArray) { - val.forEach(function _docReduce(doc) { - if (!doc || !doc._doc) { - return; - } - seed = Object.keys(doc._doc).reduce(function(seed, path) { - return docReducer(doc._doc, seed, path); - }, seed); - if (doc instanceof Embedded) { - seed.push(doc); - } - }); - } else if (val instanceof Document && val.$__isNested) { - seed = Object.keys(val).reduce(function(seed, path) { - return docReducer(val, seed, path); - }, seed); - } - return seed; - } - - const _this = this; - const subDocs = Object.keys(this._doc).reduce(function(seed, path) { - return docReducer(_this, seed, path); - }, []); - - return subDocs; -}; - -/*! - * Runs queued functions - */ - -function applyQueue(doc) { - const q = doc.schema && doc.schema.callQueue; - if (!q.length) { - return; - } - - for (const pair of q) { - if (pair[0] !== 'pre' && pair[0] !== 'post' && pair[0] !== 'on') { - doc[pair[0]].apply(doc, pair[1]); - } - } -} - -/*! - * ignore - */ - -Document.prototype.$__handleReject = function handleReject(err) { - // emit on the Model if listening - if (this.listeners('error').length) { - this.emit('error', err); - } else if (this.constructor.listeners && this.constructor.listeners('error').length) { - this.constructor.emit('error', err); - } else if (this.listeners && this.listeners('error').length) { - this.emit('error', err); - } -}; - -/** - * Internal helper for toObject() and toJSON() that doesn't manipulate options - * - * @api private - * @method $toObject - * @memberOf Document - * @instance - */ - -Document.prototype.$toObject = function(options, json) { - let defaultOptions = { - transform: true, - flattenDecimals: true - }; - - const path = json ? 'toJSON' : 'toObject'; - const baseOptions = get(this, 'constructor.base.options.' + path, {}); - const schemaOptions = get(this, 'schema.options', {}); - // merge base default options with Schema's set default options if available. - // `clone` is necessary here because `utils.options` directly modifies the second input. - defaultOptions = utils.options(defaultOptions, clone(baseOptions)); - defaultOptions = utils.options(defaultOptions, clone(schemaOptions[path] || {})); - - // If options do not exist or is not an object, set it to empty object - options = utils.isPOJO(options) ? clone(options) : {}; - - if (!('flattenMaps' in options)) { - options.flattenMaps = defaultOptions.flattenMaps; - } - - let _minimize; - if (options.minimize != null) { - _minimize = options.minimize; - } else if (defaultOptions.minimize != null) { - _minimize = defaultOptions.minimize; - } else { - _minimize = schemaOptions.minimize; - } - - // The original options that will be passed to `clone()`. Important because - // `clone()` will recursively call `$toObject()` on embedded docs, so we - // need the original options the user passed in, plus `_isNested` and - // `_parentOptions` for checking whether we need to depopulate. - const cloneOptions = Object.assign(utils.clone(options), { - _isNested: true, - json: json, - minimize: _minimize - }); - - if (utils.hasUserDefinedProperty(options, 'getters')) { - cloneOptions.getters = options.getters; - } - if (utils.hasUserDefinedProperty(options, 'virtuals')) { - cloneOptions.virtuals = options.virtuals; - } - - const depopulate = options.depopulate || - get(options, '_parentOptions.depopulate', false); - // _isNested will only be true if this is not the top level document, we - // should never depopulate - if (depopulate && options._isNested && this.$__.wasPopulated) { - // populated paths that we set to a document - return clone(this._id, cloneOptions); - } - - // merge default options with input options. - options = utils.options(defaultOptions, options); - options._isNested = true; - options.json = json; - options.minimize = _minimize; - - cloneOptions._parentOptions = options; - cloneOptions._skipSingleNestedGetters = true; - - const gettersOptions = Object.assign({}, cloneOptions); - gettersOptions._skipSingleNestedGetters = false; - - // remember the root transform function - // to save it from being overwritten by sub-transform functions - const originalTransform = options.transform; - - let ret = clone(this._doc, cloneOptions) || {}; - - if (options.getters) { - applyGetters(this, ret, gettersOptions); - - if (options.minimize) { - ret = minimize(ret) || {}; - } - } - - if (options.virtuals || (options.getters && options.virtuals !== false)) { - applyVirtuals(this, ret, gettersOptions, options); - } - - if (options.versionKey === false && this.schema.options.versionKey) { - delete ret[this.schema.options.versionKey]; - } - - let transform = options.transform; - - // In the case where a subdocument has its own transform function, we need to - // check and see if the parent has a transform (options.transform) and if the - // child schema has a transform (this.schema.options.toObject) In this case, - // we need to adjust options.transform to be the child schema's transform and - // not the parent schema's - if (transform) { - applySchemaTypeTransforms(this, ret, gettersOptions, options); - } - - if (transform === true || (schemaOptions.toObject && transform)) { - const opts = options.json ? schemaOptions.toJSON : schemaOptions.toObject; - - if (opts) { - transform = (typeof options.transform === 'function' ? options.transform : opts.transform); - } - } else { - options.transform = originalTransform; - } - - if (typeof transform === 'function') { - const xformed = transform(this, ret, options); - if (typeof xformed !== 'undefined') { - ret = xformed; - } - } - - return ret; -}; - -/** - * Converts this document into a plain javascript object, ready for storage in MongoDB. - * - * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage. - * - * ####Options: - * - * - `getters` apply all getters (path and virtual getters), defaults to false - * - `aliases` apply all aliases if `virtuals=true`, defaults to true - * - `virtuals` apply virtual getters (can override `getters` option), defaults to false - * - `minimize` remove empty objects, defaults to true - * - `transform` a transform function to apply to the resulting document before returning - * - `depopulate` depopulate any populated paths, replacing them with their original refs, defaults to false - * - `versionKey` whether to include the version key, defaults to true - * - `flattenMaps` convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject(), defaults to false - * - * ####Getters/Virtuals - * - * Example of only applying path getters - * - * doc.toObject({ getters: true, virtuals: false }) - * - * Example of only applying virtual getters - * - * doc.toObject({ virtuals: true }) - * - * Example of applying both path and virtual getters - * - * doc.toObject({ getters: true }) - * - * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument. - * - * schema.set('toObject', { virtuals: true }) - * - * ####Transform - * - * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function. - * - * Transform functions receive three arguments - * - * function (doc, ret, options) {} - * - * - `doc` The mongoose document which is being converted - * - `ret` The plain object representation which has been converted - * - `options` The options in use (either schema options or the options passed inline) - * - * ####Example - * - * // specify the transform schema option - * if (!schema.options.toObject) schema.options.toObject = {}; - * schema.options.toObject.transform = function (doc, ret, options) { - * // remove the _id of every document before returning the result - * delete ret._id; - * return ret; - * } - * - * // without the transformation in the schema - * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } - * - * // with the transformation - * doc.toObject(); // { name: 'Wreck-it Ralph' } - * - * With transformations we can do a lot more than remove properties. We can even return completely new customized objects: - * - * if (!schema.options.toObject) schema.options.toObject = {}; - * schema.options.toObject.transform = function (doc, ret, options) { - * return { movie: ret.name } - * } - * - * // without the transformation in the schema - * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } - * - * // with the transformation - * doc.toObject(); // { movie: 'Wreck-it Ralph' } - * - * _Note: if a transform function returns `undefined`, the return value will be ignored._ - * - * Transformations may also be applied inline, overridding any transform set in the options: - * - * function xform (doc, ret, options) { - * return { inline: ret.name, custom: true } - * } - * - * // pass the transform as an inline option - * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true } - * - * If you want to skip transformations, use `transform: false`: - * - * schema.options.toObject.hide = '_id'; - * schema.options.toObject.transform = function (doc, ret, options) { - * if (options.hide) { - * options.hide.split(' ').forEach(function (prop) { - * delete ret[prop]; - * }); - * } - * return ret; - * } - * - * const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }); - * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' } - * doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' } - * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' } - * - * If you pass a transform in `toObject()` options, Mongoose will apply the transform - * to [subdocuments](/docs/subdocs.html) in addition to the top-level document. - * Similarly, `transform: false` skips transforms for all subdocuments. - * Note that this is behavior is different for transforms defined in the schema: - * if you define a transform in `schema.options.toObject.transform`, that transform - * will **not** apply to subdocuments. - * - * const memberSchema = new Schema({ name: String, email: String }); - * const groupSchema = new Schema({ members: [memberSchema], name: String, email }); - * const Group = mongoose.model('Group', groupSchema); - * - * const doc = new Group({ - * name: 'Engineering', - * email: 'dev@mongoosejs.io', - * members: [{ name: 'Val', email: 'val@mongoosejs.io' }] - * }); - * - * // Removes `email` from both top-level document **and** array elements - * // { name: 'Engineering', members: [{ name: 'Val' }] } - * doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } }); - * - * Transforms, like all of these options, are also available for `toJSON`. See [this guide to `JSON.stringify()`](https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html) to learn why `toJSON()` and `toObject()` are separate functions. - * - * See [schema options](/docs/guide.html#toObject) for some more details. - * - * _During save, no custom options are applied to the document before being sent to the database._ - * - * @param {Object} [options] - * @param {Boolean} [options.getters=false] if true, apply all getters, including virtuals - * @param {Boolean} [options.virtuals=false] if true, apply virtuals, including aliases. Use `{ getters: true, virtuals: false }` to just apply getters, not virtuals - * @param {Boolean} [options.aliases=true] if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. - * @param {Boolean} [options.minimize=true] if true, omit any empty objects from the output - * @param {Function|null} [options.transform=null] if set, mongoose will call this function to allow you to transform the returned object - * @param {Boolean} [options.depopulate=false] if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. - * @param {Boolean} [options.versionKey=true] if false, exclude the version key (`__v` by default) from the output - * @param {Boolean} [options.flattenMaps=false] if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. - * @return {Object} js object - * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.toObject = function(options) { - return this.$toObject(options); -}; - -/*! - * Minimizes an object, removing undefined values and empty objects - * - * @param {Object} object to minimize - * @return {Object} - */ - -function minimize(obj) { - const keys = Object.keys(obj); - let i = keys.length; - let hasKeys; - let key; - let val; - - while (i--) { - key = keys[i]; - val = obj[key]; - - if (utils.isObject(val) && !Buffer.isBuffer(val)) { - obj[key] = minimize(val); - } - - if (undefined === obj[key]) { - delete obj[key]; - continue; - } - - hasKeys = true; - } - - return hasKeys - ? obj - : undefined; -} - -/*! - * Applies virtuals properties to `json`. - */ - -function applyVirtuals(self, json, options, toObjectOptions) { - const schema = self.schema; - const paths = Object.keys(schema.virtuals); - let i = paths.length; - const numPaths = i; - let path; - let assignPath; - let cur = self._doc; - let v; - const aliases = get(toObjectOptions, 'aliases', true); - - if (!cur) { - return json; - } - - options = options || {}; - for (i = 0; i < numPaths; ++i) { - path = paths[i]; - - // Allow skipping aliases with `toObject({ virtuals: true, aliases: false })` - if (!aliases && schema.aliases.hasOwnProperty(path)) { - continue; - } - - // We may be applying virtuals to a nested object, for example if calling - // `doc.nestedProp.toJSON()`. If so, the path we assign to, `assignPath`, - // will be a trailing substring of the `path`. - assignPath = path; - if (options.path != null) { - if (!path.startsWith(options.path + '.')) { - continue; - } - assignPath = path.substr(options.path.length + 1); - } - const parts = assignPath.split('.'); - v = clone(self.get(path), options); - if (v === void 0) { - continue; - } - const plen = parts.length; - cur = json; - for (let j = 0; j < plen - 1; ++j) { - cur[parts[j]] = cur[parts[j]] || {}; - cur = cur[parts[j]]; - } - cur[parts[plen - 1]] = v; - } - - return json; -} - -/*! - * Applies virtuals properties to `json`. - * - * @param {Document} self - * @param {Object} json - * @return {Object} `json` - */ - -function applyGetters(self, json, options) { - const schema = self.schema; - const paths = Object.keys(schema.paths); - let i = paths.length; - let path; - let cur = self._doc; - let v; - - if (!cur) { - return json; - } - - while (i--) { - path = paths[i]; - - const parts = path.split('.'); - const plen = parts.length; - const last = plen - 1; - let branch = json; - let part; - cur = self._doc; - - if (!self.isSelected(path)) { - continue; - } - - for (let ii = 0; ii < plen; ++ii) { - part = parts[ii]; - v = cur[part]; - if (ii === last) { - const val = self.get(path); - branch[part] = clone(val, options); - } else if (v == null) { - if (part in cur) { - branch[part] = v; - } - break; - } else { - branch = branch[part] || (branch[part] = {}); - } - cur = v; - } - } - - return json; -} - -/*! - * Applies schema type transforms to `json`. - * - * @param {Document} self - * @param {Object} json - * @return {Object} `json` - */ - -function applySchemaTypeTransforms(self, json) { - const schema = self.schema; - const paths = Object.keys(schema.paths || {}); - const cur = self._doc; - - if (!cur) { - return json; - } - - for (const path of paths) { - const schematype = schema.paths[path]; - if (typeof schematype.options.transform === 'function') { - const val = self.get(path); - json[path] = schematype.options.transform.call(self, val); - } else if (schematype.$embeddedSchemaType != null && - typeof schematype.$embeddedSchemaType.options.transform === 'function') { - const vals = [].concat(self.get(path)); - const transform = schematype.$embeddedSchemaType.options.transform; - for (let i = 0; i < vals.length; ++i) { - vals[i] = transform.call(self, vals[i]); - } - - json[path] = vals; - } - } - - return json; -} - -/** - * The return value of this method is used in calls to JSON.stringify(doc). - * - * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument. - * - * schema.set('toJSON', { virtuals: true }) - * - * See [schema options](/docs/guide.html#toJSON) for details. - * - * @param {Object} options - * @return {Object} - * @see Document#toObject #document_Document-toObject - * @see JSON.stringify() in JavaScript https://thecodebarbarian.com/the-80-20-guide-to-json-stringify-in-javascript.html - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.toJSON = function(options) { - return this.$toObject(options, true); -}; - -/** - * Helper for console.log - * - * @api public - * @method inspect - * @memberOf Document - * @instance - */ - -Document.prototype.inspect = function(options) { - const isPOJO = utils.isPOJO(options); - let opts; - if (isPOJO) { - opts = options; - opts.minimize = false; - } - const ret = this.toObject(opts); - - if (ret == null) { - // If `toObject()` returns null, `this` is still an object, so if `inspect()` - // prints out null this can cause some serious confusion. See gh-7942. - return 'MongooseDocument { ' + ret + ' }'; - } - - return ret; -}; - -if (inspect.custom) { - /*! - * Avoid Node deprecation warning DEP0079 - */ - - Document.prototype[inspect.custom] = Document.prototype.inspect; -} - -/** - * Helper for console.log - * - * @api public - * @method toString - * @memberOf Document - * @instance - */ - -Document.prototype.toString = function() { - const ret = this.inspect(); - if (typeof ret === 'string') { - return ret; - } - return inspect(ret); -}; - -/** - * Returns true if the Document stores the same data as doc. - * - * Documents are considered equal when they have matching `_id`s, unless neither - * document has an `_id`, in which case this function falls back to using - * `deepEqual()`. - * - * @param {Document} doc a document to compare - * @return {Boolean} - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.equals = function(doc) { - if (!doc) { - return false; - } - - const tid = this.get('_id'); - const docid = doc.get ? doc.get('_id') : doc; - if (!tid && !docid) { - return deepEqual(this, doc); - } - return tid && tid.equals - ? tid.equals(docid) - : tid === docid; -}; - -/** - * Populates document references, executing the `callback` when complete. - * If you want to use promises instead, use this function with - * [`execPopulate()`](#document_Document-execPopulate) - * - * ####Example: - * - * doc - * .populate('company') - * .populate({ - * path: 'notes', - * match: /airline/, - * select: 'text', - * model: 'modelName' - * options: opts - * }, function (err, user) { - * assert(doc._id === user._id) // the document itself is passed - * }) - * - * // summary - * doc.populate(path) // not executed - * doc.populate(options); // not executed - * doc.populate(path, callback) // executed - * doc.populate(options, callback); // executed - * doc.populate(callback); // executed - * doc.populate(options).execPopulate() // executed, returns promise - * - * - * ####NOTE: - * - * Population does not occur unless a `callback` is passed *or* you explicitly - * call `execPopulate()`. - * Passing the same path a second time will overwrite the previous path options. - * See [Model.populate()](#model_Model.populate) for explaination of options. - * - * @see Model.populate #model_Model.populate - * @see Document.execPopulate #document_Document-execPopulate - * @param {String|Object} [path] The path to populate or an options object - * @param {Function} [callback] When passed, population is invoked - * @api public - * @return {Document} this - * @memberOf Document - * @instance - */ - -Document.prototype.populate = function populate() { - if (arguments.length === 0) { - return this; - } - - const pop = this.$__.populate || (this.$__.populate = {}); - const args = utils.args(arguments); - let fn; - - if (typeof args[args.length - 1] === 'function') { - fn = args.pop(); - } - - // allow `doc.populate(callback)` - if (args.length) { - // use hash to remove duplicate paths - const res = utils.populate.apply(null, args); - for (const populateOptions of res) { - pop[populateOptions.path] = populateOptions; - } - } - - if (fn) { - const paths = utils.object.vals(pop); - this.$__.populate = undefined; - let topLevelModel = this.constructor; - if (this.$__isNested) { - topLevelModel = this.$__.scope.constructor; - const nestedPath = this.$__.nestedPath; - paths.forEach(function(populateOptions) { - populateOptions.path = nestedPath + '.' + populateOptions.path; - }); - } - - // Use `$session()` by default if the document has an associated session - // See gh-6754 - if (this.$session() != null) { - const session = this.$session(); - paths.forEach(path => { - if (path.options == null) { - path.options = { session: session }; - return; - } - if (!('session' in path.options)) { - path.options.session = session; - } - }); - } - - topLevelModel.populate(this, paths, fn); - } - - return this; -}; - -/** - * Explicitly executes population and returns a promise. Useful for ES2015 - * integration. - * - * ####Example: - * - * const promise = doc. - * populate('company'). - * populate({ - * path: 'notes', - * match: /airline/, - * select: 'text', - * model: 'modelName' - * options: opts - * }). - * execPopulate(); - * - * // summary - * doc.execPopulate().then(resolve, reject); - * - * // you can also use doc.execPopulate(options) as a shorthand for - * // doc.populate(options).execPopulate() - * - * - * ####Example: - * const promise = doc.execPopulate({ path: 'company', select: 'employees' }); - * - * // summary - * promise.then(resolve,reject); - * - * @see Document.populate #document_Document-populate - * @api public - * @param {Function} [callback] optional callback. If specified, a promise will **not** be returned - * @return {Promise} promise that resolves to the document when population is done - * @memberOf Document - * @instance - */ - -Document.prototype.execPopulate = function(callback) { - const isUsingShorthand = callback != null && typeof callback !== 'function'; - if (isUsingShorthand) { - return this.populate.apply(this, arguments).execPopulate(); - } - - return promiseOrCallback(callback, cb => { - this.populate(cb); - }, this.constructor.events); -}; - -/** - * Gets _id(s) used during population of the given `path`. - * - * ####Example: - * - * Model.findOne().populate('author').exec(function (err, doc) { - * console.log(doc.author.name) // Dr.Seuss - * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7' - * }) - * - * If the path was not populated, undefined is returned. - * - * @param {String} path - * @return {Array|ObjectId|Number|Buffer|String|undefined} - * @memberOf Document - * @instance - * @api public - */ - -Document.prototype.populated = function(path, val, options) { - // val and options are internal - if (val === null || val === void 0) { - if (!this.$__.populated) { - return undefined; - } - const v = this.$__.populated[path]; - if (v) { - return v.value; - } - return undefined; - } - - // internal - if (val === true) { - if (!this.$__.populated) { - return undefined; - } - return this.$__.populated[path]; - } - - this.$__.populated || (this.$__.populated = {}); - this.$__.populated[path] = { value: val, options: options }; - - // If this was a nested populate, make sure each populated doc knows - // about its populated children (gh-7685) - const pieces = path.split('.'); - for (let i = 0; i < pieces.length - 1; ++i) { - const subpath = pieces.slice(0, i + 1).join('.'); - const subdoc = this.get(subpath); - if (subdoc != null && subdoc.$__ != null && this.populated(subpath)) { - const rest = pieces.slice(i + 1).join('.'); - subdoc.populated(rest, val, options); - // No need to continue because the above recursion should take care of - // marking the rest of the docs as populated - break; - } - } - - return val; -}; - -/** - * Takes a populated field and returns it to its unpopulated state. - * - * ####Example: - * - * Model.findOne().populate('author').exec(function (err, doc) { - * console.log(doc.author.name); // Dr.Seuss - * console.log(doc.depopulate('author')); - * console.log(doc.author); // '5144cf8050f071d979c118a7' - * }) - * - * If the path was not populated, this is a no-op. - * - * @param {String} path - * @return {Document} this - * @see Document.populate #document_Document-populate - * @api public - * @memberOf Document - * @instance - */ - -Document.prototype.depopulate = function(path) { - if (typeof path === 'string') { - path = path.split(' '); - } - - let populatedIds; - const virtualKeys = this.$$populatedVirtuals ? Object.keys(this.$$populatedVirtuals) : []; - const populated = get(this, '$__.populated', {}); - - if (arguments.length === 0) { - // Depopulate all - for (const virtualKey of virtualKeys) { - delete this.$$populatedVirtuals[virtualKey]; - delete this._doc[virtualKey]; - delete populated[virtualKey]; - } - - const keys = Object.keys(populated); - - for (const key of keys) { - populatedIds = this.populated(key); - if (!populatedIds) { - continue; - } - delete populated[key]; - this.$set(key, populatedIds); - } - return this; - } - - for (const singlePath of path) { - populatedIds = this.populated(singlePath); - delete populated[singlePath]; - - if (virtualKeys.indexOf(singlePath) !== -1) { - delete this.$$populatedVirtuals[singlePath]; - delete this._doc[singlePath]; - } else if (populatedIds) { - this.$set(singlePath, populatedIds); - } - } - return this; -}; - - -/** - * Returns the full path to this document. - * - * @param {String} [path] - * @return {String} - * @api private - * @method $__fullPath - * @memberOf Document - * @instance - */ - -Document.prototype.$__fullPath = function(path) { - // overridden in SubDocuments - return path || ''; -}; - -/*! - * Module exports. - */ - -Document.ValidationError = ValidationError; -module.exports = exports = Document; diff --git a/node_modules/mongoose/lib/document_provider.js b/node_modules/mongoose/lib/document_provider.js deleted file mode 100644 index 1ace61f..0000000 --- a/node_modules/mongoose/lib/document_provider.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -/* eslint-env browser */ - -/*! - * Module dependencies. - */ -const Document = require('./document.js'); -const BrowserDocument = require('./browserDocument.js'); - -let isBrowser = false; - -/** - * Returns the Document constructor for the current context - * - * @api private - */ -module.exports = function() { - if (isBrowser) { - return BrowserDocument; - } - return Document; -}; - -/*! - * ignore - */ -module.exports.setBrowser = function(flag) { - isBrowser = flag; -}; diff --git a/node_modules/mongoose/lib/driver.js b/node_modules/mongoose/lib/driver.js deleted file mode 100644 index cf7ca3d..0000000 --- a/node_modules/mongoose/lib/driver.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -let driver = null; - -module.exports.get = function() { - return driver; -}; - -module.exports.set = function(v) { - driver = v; -}; diff --git a/node_modules/mongoose/lib/drivers/SPEC.md b/node_modules/mongoose/lib/drivers/SPEC.md deleted file mode 100644 index 6464693..0000000 --- a/node_modules/mongoose/lib/drivers/SPEC.md +++ /dev/null @@ -1,4 +0,0 @@ - -# Driver Spec - -TODO diff --git a/node_modules/mongoose/lib/drivers/browser/ReadPreference.js b/node_modules/mongoose/lib/drivers/browser/ReadPreference.js deleted file mode 100644 index 1363570..0000000 --- a/node_modules/mongoose/lib/drivers/browser/ReadPreference.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * ignore - */ - -'use strict'; - -module.exports = function() {}; diff --git a/node_modules/mongoose/lib/drivers/browser/binary.js b/node_modules/mongoose/lib/drivers/browser/binary.js deleted file mode 100644 index 4658f7b..0000000 --- a/node_modules/mongoose/lib/drivers/browser/binary.js +++ /dev/null @@ -1,14 +0,0 @@ - -/*! - * Module dependencies. - */ - -'use strict'; - -const Binary = require('bson').Binary; - -/*! - * Module exports. - */ - -module.exports = exports = Binary; diff --git a/node_modules/mongoose/lib/drivers/browser/decimal128.js b/node_modules/mongoose/lib/drivers/browser/decimal128.js deleted file mode 100644 index 5668182..0000000 --- a/node_modules/mongoose/lib/drivers/browser/decimal128.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * ignore - */ - -'use strict'; - -module.exports = require('bson').Decimal128; diff --git a/node_modules/mongoose/lib/drivers/browser/index.js b/node_modules/mongoose/lib/drivers/browser/index.js deleted file mode 100644 index 56d0b8a..0000000 --- a/node_modules/mongoose/lib/drivers/browser/index.js +++ /dev/null @@ -1,13 +0,0 @@ -/*! - * Module exports. - */ - -'use strict'; - -exports.Binary = require('./binary'); -exports.Collection = function() { - throw new Error('Cannot create a collection from browser library'); -}; -exports.Decimal128 = require('./decimal128'); -exports.ObjectId = require('./objectid'); -exports.ReadPreference = require('./ReadPreference'); diff --git a/node_modules/mongoose/lib/drivers/browser/objectid.js b/node_modules/mongoose/lib/drivers/browser/objectid.js deleted file mode 100644 index b1e603d..0000000 --- a/node_modules/mongoose/lib/drivers/browser/objectid.js +++ /dev/null @@ -1,28 +0,0 @@ - -/*! - * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId - * @constructor NodeMongoDbObjectId - * @see ObjectId - */ - -'use strict'; - -const ObjectId = require('bson').ObjectID; - -/*! - * Getter for convenience with populate, see gh-6115 - */ - -Object.defineProperty(ObjectId.prototype, '_id', { - enumerable: false, - configurable: true, - get: function() { - return this; - } -}); - -/*! - * ignore - */ - -module.exports = exports = ObjectId; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js deleted file mode 100644 index 024ee18..0000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/ReadPreference.js +++ /dev/null @@ -1,47 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const mongodb = require('mongodb'); -const ReadPref = mongodb.ReadPreference; - -/*! - * Converts arguments to ReadPrefs the driver - * can understand. - * - * @param {String|Array} pref - * @param {Array} [tags] - */ - -module.exports = function readPref(pref, tags) { - if (Array.isArray(pref)) { - tags = pref[1]; - pref = pref[0]; - } - - if (pref instanceof ReadPref) { - return pref; - } - - switch (pref) { - case 'p': - pref = 'primary'; - break; - case 'pp': - pref = 'primaryPreferred'; - break; - case 's': - pref = 'secondary'; - break; - case 'sp': - pref = 'secondaryPreferred'; - break; - case 'n': - pref = 'nearest'; - break; - } - - return new ReadPref(pref, tags); -}; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js deleted file mode 100644 index 4e3c86f..0000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js +++ /dev/null @@ -1,10 +0,0 @@ - -/*! - * Module dependencies. - */ - -'use strict'; - -const Binary = require('mongodb').Binary; - -module.exports = exports = Binary; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js deleted file mode 100644 index d868188..0000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js +++ /dev/null @@ -1,361 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const MongooseCollection = require('../../collection'); -const MongooseError = require('../../error/mongooseError'); -const Collection = require('mongodb').Collection; -const get = require('../../helpers/get'); -const sliced = require('sliced'); -const stream = require('stream'); -const util = require('util'); - -/** - * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation. - * - * All methods methods from the [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver are copied and wrapped in queue management. - * - * @inherits Collection - * @api private - */ - -function NativeCollection(name, options) { - this.collection = null; - this.Promise = options.Promise || Promise; - this._closed = false; - MongooseCollection.apply(this, arguments); -} - -/*! - * Inherit from abstract Collection. - */ - -NativeCollection.prototype.__proto__ = MongooseCollection.prototype; - -/** - * Called when the connection opens. - * - * @api private - */ - -NativeCollection.prototype.onOpen = function() { - const _this = this; - - // always get a new collection in case the user changed host:port - // of parent db instance when re-opening the connection. - - if (!_this.opts.capped.size) { - // non-capped - callback(null, _this.conn.db.collection(_this.name)); - return _this.collection; - } - - if (_this.opts.autoCreate === false) { - _this.collection = _this.conn.db.collection(_this.name); - return _this.collection; - } - - // capped - return _this.conn.db.collection(_this.name, function(err, c) { - if (err) return callback(err); - - // discover if this collection exists and if it is capped - _this.conn.db.listCollections({ name: _this.name }).toArray(function(err, docs) { - if (err) { - return callback(err); - } - const doc = docs[0]; - const exists = !!doc; - - if (exists) { - if (doc.options && doc.options.capped) { - callback(null, c); - } else { - const msg = 'A non-capped collection exists with the name: ' + _this.name + '\n\n' - + ' To use this collection as a capped collection, please ' - + 'first convert it.\n' - + ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped'; - err = new Error(msg); - callback(err); - } - } else { - // create - const opts = Object.assign({}, _this.opts.capped); - opts.capped = true; - _this.conn.db.createCollection(_this.name, opts, callback); - } - }); - }); - - function callback(err, collection) { - if (err) { - // likely a strict mode error - _this.conn.emit('error', err); - } else { - _this.collection = collection; - MongooseCollection.prototype.onOpen.call(_this); - } - } -}; - -/** - * Called when the connection closes - * - * @api private - */ - -NativeCollection.prototype.onClose = function(force) { - MongooseCollection.prototype.onClose.call(this, force); -}; - -/*! - * ignore - */ - -const syncCollectionMethods = { watch: true }; - -/*! - * Copy the collection methods and make them subject to queues - */ - -function iter(i) { - NativeCollection.prototype[i] = function() { - const collection = this.collection; - const args = Array.from(arguments); - const _this = this; - const debug = get(_this, 'conn.base.options.debug'); - const lastArg = arguments[arguments.length - 1]; - - // If user force closed, queueing will hang forever. See #5664 - if (this.conn.$wasForceClosed) { - const error = new MongooseError('Connection was force closed'); - if (args.length > 0 && - typeof args[args.length - 1] === 'function') { - args[args.length - 1](error); - return; - } else { - throw error; - } - } - - if (this.buffer) { - if (syncCollectionMethods[i]) { - throw new Error('Collection method ' + i + ' is synchronous'); - } - if (typeof lastArg === 'function') { - this.addQueue(i, args); - return; - } - return new this.Promise((resolve, reject) => { - this.addQueue(i, [].concat(args).concat([(err, res) => { - if (err != null) { - return reject(err); - } - resolve(res); - }])); - }); - } - - if (debug) { - if (typeof debug === 'function') { - debug.apply(_this, - [_this.name, i].concat(sliced(args, 0, args.length - 1))); - } else if (debug instanceof stream.Writable) { - this.$printToStream(_this.name, i, args, debug); - } else { - this.$print(_this.name, i, args, typeof debug.color === 'undefined' ? true : debug.color); - } - } - - try { - return collection[i].apply(collection, args); - } catch (error) { - // Collection operation may throw because of max bson size, catch it here - // See gh-3906 - if (args.length > 0 && - typeof args[args.length - 1] === 'function') { - args[args.length - 1](error); - } else { - throw error; - } - } - }; -} - -for (const key of Object.keys(Collection.prototype)) { - // Janky hack to work around gh-3005 until we can get rid of the mongoose - // collection abstraction - const descriptor = Object.getOwnPropertyDescriptor(Collection.prototype, key); - // Skip properties with getters because they may throw errors (gh-8528) - if (descriptor.get !== undefined) { - continue; - } - if (typeof Collection.prototype[key] !== 'function') { - continue; - } - - iter(key); -} - -/** - * Debug print helper - * - * @api public - * @method $print - */ - -NativeCollection.prototype.$print = function(name, i, args, color) { - const moduleName = color ? '\x1B[0;36mMongoose:\x1B[0m ' : 'Mongoose: '; - const functionCall = [name, i].join('.'); - const _args = []; - for (let j = args.length - 1; j >= 0; --j) { - if (this.$format(args[j]) || _args.length) { - _args.unshift(this.$format(args[j], color)); - } - } - const params = '(' + _args.join(', ') + ')'; - - console.info(moduleName + functionCall + params); -}; - -/** - * Debug print helper - * - * @api public - * @method $print - */ - -NativeCollection.prototype.$printToStream = function(name, i, args, stream) { - const functionCall = [name, i].join('.'); - const _args = []; - for (let j = args.length - 1; j >= 0; --j) { - if (this.$format(args[j]) || _args.length) { - _args.unshift(this.$format(args[j])); - } - } - const params = '(' + _args.join(', ') + ')'; - - stream.write(functionCall + params, 'utf8'); -}; - -/** - * Formatter for debug print args - * - * @api public - * @method $format - */ - -NativeCollection.prototype.$format = function(arg, color) { - const type = typeof arg; - if (type === 'function' || type === 'undefined') return ''; - return format(arg, false, color); -}; - -/*! - * Debug print helper - */ - -function inspectable(representation) { - const ret = { - inspect: function() { return representation; } - }; - if (util.inspect.custom) { - ret[util.inspect.custom] = ret.inspect; - } - return ret; -} -function map(o) { - return format(o, true); -} -function formatObjectId(x, key) { - x[key] = inspectable('ObjectId("' + x[key].toHexString() + '")'); -} -function formatDate(x, key) { - x[key] = inspectable('new Date("' + x[key].toUTCString() + '")'); -} -function format(obj, sub, color) { - if (obj && typeof obj.toBSON === 'function') { - obj = obj.toBSON(); - } - if (obj == null) { - return obj; - } - - const clone = require('../../helpers/clone'); - let x = clone(obj, { transform: false }); - - if (x.constructor.name === 'Binary') { - x = 'BinData(' + x.sub_type + ', "' + x.toString('base64') + '")'; - } else if (x.constructor.name === 'ObjectID') { - x = inspectable('ObjectId("' + x.toHexString() + '")'); - } else if (x.constructor.name === 'Date') { - x = inspectable('new Date("' + x.toUTCString() + '")'); - } else if (x.constructor.name === 'Object') { - const keys = Object.keys(x); - const numKeys = keys.length; - let key; - for (let i = 0; i < numKeys; ++i) { - key = keys[i]; - if (x[key]) { - let error; - if (typeof x[key].toBSON === 'function') { - try { - // `session.toBSON()` throws an error. This means we throw errors - // in debug mode when using transactions, see gh-6712. As a - // workaround, catch `toBSON()` errors, try to serialize without - // `toBSON()`, and rethrow if serialization still fails. - x[key] = x[key].toBSON(); - } catch (_error) { - error = _error; - } - } - if (x[key].constructor.name === 'Binary') { - x[key] = 'BinData(' + x[key].sub_type + ', "' + - x[key].buffer.toString('base64') + '")'; - } else if (x[key].constructor.name === 'Object') { - x[key] = format(x[key], true); - } else if (x[key].constructor.name === 'ObjectID') { - formatObjectId(x, key); - } else if (x[key].constructor.name === 'Date') { - formatDate(x, key); - } else if (x[key].constructor.name === 'ClientSession') { - x[key] = inspectable('ClientSession("' + - get(x[key], 'id.id.buffer', '').toString('hex') + '")'); - } else if (Array.isArray(x[key])) { - x[key] = x[key].map(map); - } else if (error != null) { - // If there was an error with `toBSON()` and the object wasn't - // already converted to a string representation, rethrow it. - // Open to better ideas on how to handle this. - throw error; - } - } - } - } - if (sub) { - return x; - } - - return util. - inspect(x, false, 10, color). - replace(/\n/g, ''). - replace(/\s{2,}/g, ' '); -} - -/** - * Retrieves information about this collections indexes. - * - * @param {Function} callback - * @method getIndexes - * @api public - */ - -NativeCollection.prototype.getIndexes = NativeCollection.prototype.indexInformation; - -/*! - * Module exports. - */ - -module.exports = NativeCollection; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js deleted file mode 100644 index 8041a88..0000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js +++ /dev/null @@ -1,185 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseConnection = require('../../connection'); -const STATES = require('../../connectionstate'); - -/** - * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation. - * - * @inherits Connection - * @api private - */ - -function NativeConnection() { - MongooseConnection.apply(this, arguments); - this._listening = false; -} - -/** - * Expose the possible connection states. - * @api public - */ - -NativeConnection.STATES = STATES; - -/*! - * Inherits from Connection. - */ - -NativeConnection.prototype.__proto__ = MongooseConnection.prototype; - -/** - * Switches to a different database using the same connection pool. - * - * Returns a new connection object, with the new db. If you set the `useCache` - * option, `useDb()` will cache connections by `name`. - * - * @param {String} name The database name - * @param {Object} [options] - * @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object. - * @return {Connection} New Connection Object - * @api public - */ - -NativeConnection.prototype.useDb = function(name, options) { - // Return immediately if cached - if (options && options.useCache && this.relatedDbs[name]) { - return this.relatedDbs[name]; - } - - // we have to manually copy all of the attributes... - const newConn = new this.constructor(); - newConn.name = name; - newConn.base = this.base; - newConn.collections = {}; - newConn.models = {}; - newConn.replica = this.replica; - newConn.config = Object.assign({}, this.base.connection.config, newConn.config); - newConn.name = this.name; - newConn.options = this.options; - newConn._readyState = this._readyState; - newConn._closeCalled = this._closeCalled; - newConn._hasOpened = this._hasOpened; - newConn._listening = false; - - newConn.host = this.host; - newConn.port = this.port; - newConn.user = this.user; - newConn.pass = this.pass; - - // First, when we create another db object, we are not guaranteed to have a - // db object to work with. So, in the case where we have a db object and it - // is connected, we can just proceed with setting everything up. However, if - // we do not have a db or the state is not connected, then we need to wait on - // the 'open' event of the connection before doing the rest of the setup - // the 'connected' event is the first time we'll have access to the db object - - const _this = this; - - newConn.client = _this.client; - - if (this.db && this._readyState === STATES.connected) { - wireup(); - } else { - this.once('connected', wireup); - } - - function wireup() { - newConn.client = _this.client; - newConn.db = _this.client.db(name); - newConn.onOpen(); - // setup the events appropriately - listen(newConn); - } - - newConn.name = name; - - // push onto the otherDbs stack, this is used when state changes - this.otherDbs.push(newConn); - newConn.otherDbs.push(this); - - // push onto the relatedDbs cache, this is used when state changes - if (options && options.useCache) { - this.relatedDbs[newConn.name] = newConn; - newConn.relatedDbs = this.relatedDbs; - } - - return newConn; -}; - -/*! - * Register listeners for important events and bubble appropriately. - */ - -function listen(conn) { - if (conn.db._listening) { - return; - } - conn.db._listening = true; - - conn.db.on('close', function(force) { - if (conn._closeCalled) return; - - // the driver never emits an `open` event. auto_reconnect still - // emits a `close` event but since we never get another - // `open` we can't emit close - if (conn.db.serverConfig.autoReconnect) { - conn.readyState = STATES.disconnected; - conn.emit('close'); - return; - } - conn.onClose(force); - }); - conn.db.on('error', function(err) { - conn.emit('error', err); - }); - conn.db.on('reconnect', function() { - conn.readyState = STATES.connected; - conn.emit('reconnect'); - conn.emit('reconnected'); - conn.onOpen(); - }); - conn.db.on('timeout', function(err) { - conn.emit('timeout', err); - }); - conn.db.on('open', function(err, db) { - if (STATES.disconnected === conn.readyState && db && db.databaseName) { - conn.readyState = STATES.connected; - conn.emit('reconnect'); - conn.emit('reconnected'); - } - }); - conn.db.on('parseError', function(err) { - conn.emit('parseError', err); - }); -} - -/** - * Closes the connection - * - * @param {Boolean} [force] - * @param {Function} [fn] - * @return {Connection} this - * @api private - */ - -NativeConnection.prototype.doClose = function(force, fn) { - this.client.close(force, (err, res) => { - // Defer because the driver will wait at least 1ms before finishing closing - // the pool, see https://github.com/mongodb-js/mongodb-core/blob/a8f8e4ce41936babc3b9112bf42d609779f03b39/lib/connection/pool.js#L1026-L1030. - // If there's queued operations, you may still get some background work - // after the callback is called. - setTimeout(() => fn(err, res), 1); - }); - return this; -}; - -/*! - * Module exports. - */ - -module.exports = NativeConnection; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/decimal128.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/decimal128.js deleted file mode 100644 index c895f17..0000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/decimal128.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * ignore - */ - -'use strict'; - -module.exports = require('mongodb').Decimal128; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js deleted file mode 100644 index 2cd749e..0000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js +++ /dev/null @@ -1,11 +0,0 @@ -/*! - * Module exports. - */ - -'use strict'; - -exports.Binary = require('./binary'); -exports.Collection = require('./collection'); -exports.Decimal128 = require('./decimal128'); -exports.ObjectId = require('./objectid'); -exports.ReadPreference = require('./ReadPreference'); \ No newline at end of file diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js deleted file mode 100644 index 6f432b7..0000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js +++ /dev/null @@ -1,16 +0,0 @@ - -/*! - * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId - * @constructor NodeMongoDbObjectId - * @see ObjectId - */ - -'use strict'; - -const ObjectId = require('mongodb').ObjectId; - -/*! - * ignore - */ - -module.exports = exports = ObjectId; diff --git a/node_modules/mongoose/lib/error/browserMissingSchema.js b/node_modules/mongoose/lib/error/browserMissingSchema.js deleted file mode 100644 index 852f873..0000000 --- a/node_modules/mongoose/lib/error/browserMissingSchema.js +++ /dev/null @@ -1,38 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/*! - * MissingSchema Error constructor. - * - * @inherits MongooseError - */ - -function MissingSchemaError() { - const msg = 'Schema hasn\'t been registered for document.\n' - + 'Use mongoose.Document(name, schema)'; - MongooseError.call(this, msg); - this.name = 'MissingSchemaError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -MissingSchemaError.prototype = Object.create(MongooseError.prototype); -MissingSchemaError.prototype.constructor = MongooseError; - -/*! - * exports - */ - -module.exports = MissingSchemaError; diff --git a/node_modules/mongoose/lib/error/cast.js b/node_modules/mongoose/lib/error/cast.js deleted file mode 100644 index 6719317..0000000 --- a/node_modules/mongoose/lib/error/cast.js +++ /dev/null @@ -1,117 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const MongooseError = require('./mongooseError'); -const get = require('../helpers/get'); -const util = require('util'); - -/** - * Casting Error constructor. - * - * @param {String} type - * @param {String} value - * @inherits MongooseError - * @api private - */ - -function CastError(type, value, path, reason, schemaType) { - // If no args, assume we'll `init()` later. - if (arguments.length > 0) { - this.init(type, value, path, reason, schemaType); - } - - MongooseError.call(this, this.formatMessage()); - this.name = 'CastError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -CastError.prototype = Object.create(MongooseError.prototype); -CastError.prototype.constructor = MongooseError; - -/*! - * ignore - */ - -CastError.prototype.init = function init(type, value, path, reason, schemaType) { - let stringValue = util.inspect(value); - stringValue = stringValue.replace(/^'/, '"').replace(/'$/, '"'); - if (!stringValue.startsWith('"')) { - stringValue = '"' + stringValue + '"'; - } - - const messageFormat = get(schemaType, 'options.cast', null); - if (typeof messageFormat === 'string') { - this.messageFormat = schemaType.options.cast; - } - this.stringValue = stringValue; - this.kind = type; - this.value = value; - this.path = path; - this.reason = reason; -}; - -/*! - * ignore - */ - -CastError.prototype.copy = function copy(other) { - this.messageFormat = other.messageFormat; - this.stringValue = other.stringValue; - this.kind = other.kind; - this.value = other.value; - this.path = other.path; - this.reason = other.reason; - this.message = other.message; -}; - -/*! - * ignore - */ - -CastError.prototype.setModel = function(model) { - this.model = model; - this.message = this.formatMessage(model); -}; - -/*! - * ignore - */ - -CastError.prototype.formatMessage = function(model) { - if (this.messageFormat != null) { - let ret = this.messageFormat. - replace('{KIND}', this.kind). - replace('{VALUE}', this.stringValue). - replace('{PATH}', this.path); - if (model != null) { - ret = ret.replace('{MODEL}', model.modelName); - } - - return ret; - } else { - let ret = 'Cast to ' + this.kind + ' failed for value ' + - this.stringValue + ' at path "' + this.path + '"'; - if (model != null) { - ret += ' for model "' + model.modelName + '"'; - } - - return ret; - } -}; - -/*! - * exports - */ - -module.exports = CastError; diff --git a/node_modules/mongoose/lib/error/disconnected.js b/node_modules/mongoose/lib/error/disconnected.js deleted file mode 100644 index 3e36c1c..0000000 --- a/node_modules/mongoose/lib/error/disconnected.js +++ /dev/null @@ -1,43 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/** - * The connection failed to reconnect and will never successfully reconnect to - * MongoDB without manual intervention. - * - * @param {String} type - * @param {String} value - * @inherits MongooseError - * @api private - */ - -function DisconnectedError(connectionString) { - MongooseError.call(this, 'Ran out of retries trying to reconnect to "' + - connectionString + '". Try setting `server.reconnectTries` and ' + - '`server.reconnectInterval` to something higher.'); - this.name = 'DisconnectedError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -DisconnectedError.prototype = Object.create(MongooseError.prototype); -DisconnectedError.prototype.constructor = MongooseError; - - -/*! - * exports - */ - -module.exports = DisconnectedError; diff --git a/node_modules/mongoose/lib/error/divergentArray.js b/node_modules/mongoose/lib/error/divergentArray.js deleted file mode 100644 index 872fd2b..0000000 --- a/node_modules/mongoose/lib/error/divergentArray.js +++ /dev/null @@ -1,48 +0,0 @@ - -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/*! - * DivergentArrayError constructor. - * - * @inherits MongooseError - */ - -function DivergentArrayError(paths) { - const msg = 'For your own good, using `document.save()` to update an array ' - + 'which was selected using an $elemMatch projection OR ' - + 'populated using skip, limit, query conditions, or exclusion of ' - + 'the _id field when the operation results in a $pop or $set of ' - + 'the entire array is not supported. The following ' - + 'path(s) would have been modified unsafely:\n' - + ' ' + paths.join('\n ') + '\n' - + 'Use Model.update() to update these arrays instead.'; - // TODO write up a docs page (FAQ) and link to it - - MongooseError.call(this, msg); - this.name = 'DivergentArrayError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -DivergentArrayError.prototype = Object.create(MongooseError.prototype); -DivergentArrayError.prototype.constructor = MongooseError; - - -/*! - * exports - */ - -module.exports = DivergentArrayError; diff --git a/node_modules/mongoose/lib/error/index.js b/node_modules/mongoose/lib/error/index.js deleted file mode 100644 index ec4188d..0000000 --- a/node_modules/mongoose/lib/error/index.js +++ /dev/null @@ -1,205 +0,0 @@ -'use strict'; - -/** - * MongooseError constructor. MongooseError is the base class for all - * Mongoose-specific errors. - * - * ####Example: - * const Model = mongoose.model('Test', new Schema({ answer: Number })); - * const doc = new Model({ answer: 'not a number' }); - * const err = doc.validateSync(); - * - * err instanceof mongoose.Error; // true - * - * @constructor Error - * @param {String} msg Error message - * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error - */ - -const MongooseError = require('./mongooseError'); - -/** - * The name of the error. The name uniquely identifies this Mongoose error. The - * possible values are: - * - * - `MongooseError`: general Mongoose error - * - `CastError`: Mongoose could not convert a value to the type defined in the schema path. May be in a `ValidationError` class' `errors` property. - * - `DisconnectedError`: This [connection](connections.html) timed out in trying to reconnect to MongoDB and will not successfully reconnect to MongoDB unless you explicitly reconnect. - * - `DivergentArrayError`: You attempted to `save()` an array that was modified after you loaded it with a `$elemMatch` or similar projection - * - `MissingSchemaError`: You tried to access a model with [`mongoose.model()`](api.html#mongoose_Mongoose-model) that was not defined - * - `DocumentNotFoundError`: The document you tried to [`save()`](api.html#document_Document-save) was not found - * - `ValidatorError`: error from an individual schema path's validator - * - `ValidationError`: error returned from [`validate()`](api.html#document_Document-validate) or [`validateSync()`](api.html#document_Document-validateSync). Contains zero or more `ValidatorError` instances in `.errors` property. - * - `MissingSchemaError`: You called `mongoose.Document()` without a schema - * - `ObjectExpectedError`: Thrown when you set a nested path to a non-object value with [strict mode set](guide.html#strict). - * - `ObjectParameterError`: Thrown when you pass a non-object value to a function which expects an object as a paramter - * - `OverwriteModelError`: Thrown when you call [`mongoose.model()`](api.html#mongoose_Mongoose-model) to re-define a model that was already defined. - * - `ParallelSaveError`: Thrown when you call [`save()`](api.html#model_Model-save) on a document when the same document instance is already saving. - * - `StrictModeError`: Thrown when you set a path that isn't the schema and [strict mode](guide.html#strict) is set to `throw`. - * - `VersionError`: Thrown when the [document is out of sync](guide.html#versionKey) - * - * @api public - * @property {String} name - * @memberOf Error - * @instance - */ - -/*! - * Module exports. - */ - -module.exports = exports = MongooseError; - -/** - * The default built-in validator error messages. - * - * @see Error.messages #error_messages_MongooseError-messages - * @api public - * @memberOf Error - * @static messages - */ - -MongooseError.messages = require('./messages'); - -// backward compat -MongooseError.Messages = MongooseError.messages; - -/** - * An instance of this error class will be returned when `save()` fails - * because the underlying - * document was not found. The constructor takes one parameter, the - * conditions that mongoose passed to `update()` when trying to update - * the document. - * - * @api public - * @memberOf Error - * @static DocumentNotFoundError - */ - -MongooseError.DocumentNotFoundError = require('./notFound'); - -/** - * An instance of this error class will be returned when mongoose failed to - * cast a value. - * - * @api public - * @memberOf Error - * @static CastError - */ - -MongooseError.CastError = require('./cast'); - -/** - * An instance of this error class will be returned when [validation](/docs/validation.html) failed. - * The `errors` property contains an object whose keys are the paths that failed and whose values are - * instances of CastError or ValidationError. - * - * @api public - * @memberOf Error - * @static ValidationError - */ - -MongooseError.ValidationError = require('./validation'); - -/** - * A `ValidationError` has a hash of `errors` that contain individual - * `ValidatorError` instances. - * - * ####Example: - * - * const schema = Schema({ name: { type: String, required: true } }); - * const Model = mongoose.model('Test', schema); - * const doc = new Model({}); - * - * // Top-level error is a ValidationError, **not** a ValidatorError - * const err = doc.validateSync(); - * err instanceof mongoose.Error.ValidationError; // true - * - * // A ValidationError `err` has 0 or more ValidatorErrors keyed by the - * // path in the `err.errors` property. - * err.errors['name'] instanceof mongoose.Error.ValidatorError; - * - * err.errors['name'].kind; // 'required' - * err.errors['name'].path; // 'name' - * err.errors['name'].value; // undefined - * - * Instances of `ValidatorError` have the following properties: - * - * - `kind`: The validator's `type`, like `'required'` or `'regexp'` - * - `path`: The path that failed validation - * - `value`: The value that failed validation - * - * @api public - * @memberOf Error - * @static ValidatorError - */ - -MongooseError.ValidatorError = require('./validator'); - -/** - * An instance of this error class will be returned when you call `save()` after - * the document in the database was changed in a potentially unsafe way. See - * the [`versionKey` option](/docs/guide.html#versionKey) for more information. - * - * @api public - * @memberOf Error - * @static VersionError - */ - -MongooseError.VersionError = require('./version'); - -/** - * An instance of this error class will be returned when you call `save()` multiple - * times on the same document in parallel. See the [FAQ](/docs/faq.html) for more - * information. - * - * @api public - * @memberOf Error - * @static ParallelSaveError - */ - -MongooseError.ParallelSaveError = require('./parallelSave'); - -/** - * Thrown when a model with the given name was already registered on the connection. - * See [the FAQ about `OverwriteModelError`](/docs/faq.html#overwrite-model-error). - * - * @api public - * @memberOf Error - * @static OverwriteModelError - */ - -MongooseError.OverwriteModelError = require('./overwriteModel'); - -/** - * Thrown when you try to access a model that has not been registered yet - * - * @api public - * @memberOf Error - * @static MissingSchemaError - */ - -MongooseError.MissingSchemaError = require('./missingSchema'); - -/** - * An instance of this error will be returned if you used an array projection - * and then modified the array in an unsafe way. - * - * @api public - * @memberOf Error - * @static DivergentArrayError - */ - -MongooseError.DivergentArrayError = require('./divergentArray'); - -/** - * Thrown when your try to pass values to model contrtuctor that - * were not specified in schema or change immutable properties when - * `strict` mode is `"throw"` - * - * @api public - * @memberOf Error - * @static StrictModeError - */ - -MongooseError.StrictModeError = require('./strict'); diff --git a/node_modules/mongoose/lib/error/messages.js b/node_modules/mongoose/lib/error/messages.js deleted file mode 100644 index 78fb6d5..0000000 --- a/node_modules/mongoose/lib/error/messages.js +++ /dev/null @@ -1,47 +0,0 @@ - -/** - * The default built-in validator error messages. These may be customized. - * - * // customize within each schema or globally like so - * var mongoose = require('mongoose'); - * mongoose.Error.messages.String.enum = "Your custom message for {PATH}."; - * - * As you might have noticed, error messages support basic templating - * - * - `{PATH}` is replaced with the invalid document path - * - `{VALUE}` is replaced with the invalid value - * - `{TYPE}` is replaced with the validator type such as "regexp", "min", or "user defined" - * - `{MIN}` is replaced with the declared min value for the Number.min validator - * - `{MAX}` is replaced with the declared max value for the Number.max validator - * - * Click the "show code" link below to see all defaults. - * - * @static messages - * @receiver MongooseError - * @api public - */ - -'use strict'; - -const msg = module.exports = exports = {}; - -msg.DocumentNotFoundError = null; - -msg.general = {}; -msg.general.default = 'Validator failed for path `{PATH}` with value `{VALUE}`'; -msg.general.required = 'Path `{PATH}` is required.'; - -msg.Number = {}; -msg.Number.min = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).'; -msg.Number.max = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).'; -msg.Number.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.'; - -msg.Date = {}; -msg.Date.min = 'Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).'; -msg.Date.max = 'Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).'; - -msg.String = {}; -msg.String.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.'; -msg.String.match = 'Path `{PATH}` is invalid ({VALUE}).'; -msg.String.minlength = 'Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'; -msg.String.maxlength = 'Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH}).'; diff --git a/node_modules/mongoose/lib/error/missingSchema.js b/node_modules/mongoose/lib/error/missingSchema.js deleted file mode 100644 index 3195158..0000000 --- a/node_modules/mongoose/lib/error/missingSchema.js +++ /dev/null @@ -1,39 +0,0 @@ - -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/*! - * MissingSchema Error constructor. - * - * @inherits MongooseError - */ - -function MissingSchemaError(name) { - const msg = 'Schema hasn\'t been registered for model "' + name + '".\n' - + 'Use mongoose.model(name, schema)'; - MongooseError.call(this, msg); - this.name = 'MissingSchemaError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -MissingSchemaError.prototype = Object.create(MongooseError.prototype); -MissingSchemaError.prototype.constructor = MongooseError; - -/*! - * exports - */ - -module.exports = MissingSchemaError; diff --git a/node_modules/mongoose/lib/error/mongooseError.js b/node_modules/mongoose/lib/error/mongooseError.js deleted file mode 100644 index 2487dfe..0000000 --- a/node_modules/mongoose/lib/error/mongooseError.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -function MongooseError(msg) { - Error.call(this); - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } - this.message = msg; - this.name = 'MongooseError'; -} - -/*! - * Inherits from Error. - */ - -MongooseError.prototype = Object.create(Error.prototype); -MongooseError.prototype.constructor = Error; - -module.exports = MongooseError; \ No newline at end of file diff --git a/node_modules/mongoose/lib/error/notFound.js b/node_modules/mongoose/lib/error/notFound.js deleted file mode 100644 index a12bcb2..0000000 --- a/node_modules/mongoose/lib/error/notFound.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const MongooseError = require('./'); -const util = require('util'); - -/*! - * OverwriteModel Error constructor. - * - * @inherits MongooseError - */ - -function DocumentNotFoundError(filter, model, numAffected, result) { - let msg; - const messages = MongooseError.messages; - if (messages.DocumentNotFoundError != null) { - msg = typeof messages.DocumentNotFoundError === 'function' ? - messages.DocumentNotFoundError(filter, model) : - messages.DocumentNotFoundError; - } else { - msg = 'No document found for query "' + util.inspect(filter) + - '" on model "' + model + '"'; - } - - MongooseError.call(this, msg); - - this.name = 'DocumentNotFoundError'; - this.result = result; - this.numAffected = numAffected; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } - - this.filter = filter; - // Backwards compat - this.query = filter; -} - -/*! - * Inherits from MongooseError. - */ - -DocumentNotFoundError.prototype = Object.create(MongooseError.prototype); -DocumentNotFoundError.prototype.constructor = MongooseError; - -/*! - * exports - */ - -module.exports = DocumentNotFoundError; diff --git a/node_modules/mongoose/lib/error/objectExpected.js b/node_modules/mongoose/lib/error/objectExpected.js deleted file mode 100644 index 9f9fac7..0000000 --- a/node_modules/mongoose/lib/error/objectExpected.js +++ /dev/null @@ -1,38 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/** - * Strict mode error constructor - * - * @param {String} type - * @param {String} value - * @inherits MongooseError - * @api private - */ - -function ObjectExpectedError(path, val) { - const typeDescription = Array.isArray(val) ? 'array' : 'primitive value'; - MongooseError.call(this, 'Tried to set nested object field `' + path + - `\` to ${typeDescription} \`` + val + '` and strict mode is set to throw.'); - this.name = 'ObjectExpectedError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } - this.path = path; -} - -/*! - * Inherits from MongooseError. - */ - -ObjectExpectedError.prototype = Object.create(MongooseError.prototype); -ObjectExpectedError.prototype.constructor = MongooseError; - -module.exports = ObjectExpectedError; diff --git a/node_modules/mongoose/lib/error/objectParameter.js b/node_modules/mongoose/lib/error/objectParameter.js deleted file mode 100644 index 3a7f284..0000000 --- a/node_modules/mongoose/lib/error/objectParameter.js +++ /dev/null @@ -1,38 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/** - * Constructor for errors that happen when a parameter that's expected to be - * an object isn't an object - * - * @param {Any} value - * @param {String} paramName - * @param {String} fnName - * @inherits MongooseError - * @api private - */ - -function ObjectParameterError(value, paramName, fnName) { - MongooseError.call(this, 'Parameter "' + paramName + '" to ' + fnName + - '() must be an object, got ' + value.toString()); - this.name = 'ObjectParameterError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -ObjectParameterError.prototype = Object.create(MongooseError.prototype); -ObjectParameterError.prototype.constructor = MongooseError; - -module.exports = ObjectParameterError; diff --git a/node_modules/mongoose/lib/error/overwriteModel.js b/node_modules/mongoose/lib/error/overwriteModel.js deleted file mode 100644 index 21013b6..0000000 --- a/node_modules/mongoose/lib/error/overwriteModel.js +++ /dev/null @@ -1,37 +0,0 @@ - -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/*! - * OverwriteModel Error constructor. - * - * @inherits MongooseError - */ - -function OverwriteModelError(name) { - MongooseError.call(this, 'Cannot overwrite `' + name + '` model once compiled.'); - this.name = 'OverwriteModelError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -OverwriteModelError.prototype = Object.create(MongooseError.prototype); -OverwriteModelError.prototype.constructor = MongooseError; - -/*! - * exports - */ - -module.exports = OverwriteModelError; diff --git a/node_modules/mongoose/lib/error/parallelSave.js b/node_modules/mongoose/lib/error/parallelSave.js deleted file mode 100644 index 1b54613..0000000 --- a/node_modules/mongoose/lib/error/parallelSave.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const MongooseError = require('./'); - -/** - * ParallelSave Error constructor. - * - * @inherits MongooseError - * @api private - */ - -function ParallelSaveError(doc) { - const msg = 'Can\'t save() the same doc multiple times in parallel. Document: '; - MongooseError.call(this, msg + doc._id); - this.name = 'ParallelSaveError'; -} - -/*! - * Inherits from MongooseError. - */ - -ParallelSaveError.prototype = Object.create(MongooseError.prototype); -ParallelSaveError.prototype.constructor = MongooseError; - -/*! - * exports - */ - -module.exports = ParallelSaveError; diff --git a/node_modules/mongoose/lib/error/parallelValidate.js b/node_modules/mongoose/lib/error/parallelValidate.js deleted file mode 100644 index c5cc83b..0000000 --- a/node_modules/mongoose/lib/error/parallelValidate.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const MongooseError = require('./mongooseError'); - -/** - * ParallelValidate Error constructor. - * - * @inherits MongooseError - * @api private - */ - -function ParallelValidateError(doc) { - const msg = 'Can\'t validate() the same doc multiple times in parallel. Document: '; - MongooseError.call(this, msg + doc._id); - this.name = 'ParallelValidateError'; -} - -/*! - * Inherits from MongooseError. - */ - -ParallelValidateError.prototype = Object.create(MongooseError.prototype); -ParallelValidateError.prototype.constructor = MongooseError; - -/*! - * exports - */ - -module.exports = ParallelValidateError; \ No newline at end of file diff --git a/node_modules/mongoose/lib/error/serverSelection.js b/node_modules/mongoose/lib/error/serverSelection.js deleted file mode 100644 index 13f96b7..0000000 --- a/node_modules/mongoose/lib/error/serverSelection.js +++ /dev/null @@ -1,59 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./mongooseError'); -const allServersUnknown = require('../helpers/topology/allServersUnknown'); -const isAtlas = require('../helpers/topology/isAtlas'); - -/** - * MongooseServerSelectionError constructor - * - * @param {String} type - * @param {String} value - * @inherits MongooseError - * @api private - */ - -function MongooseServerSelectionError(message) { - MongooseError.call(this, message); - this.name = 'MongooseServerSelectionError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } -} - -/*! - * Inherits from MongooseError. - */ - -MongooseServerSelectionError.prototype = Object.create(MongooseError.prototype); -MongooseServerSelectionError.prototype.constructor = MongooseError; - -/*! - * ignore - */ - -const atlasMessage = 'Could not connect to any servers in your MongoDB Atlas ' + - 'cluster. Make sure your current IP address is on your Atlas cluster\'s IP ' + - 'whitelist: https://docs.atlas.mongodb.com/security-whitelist/.'; - -MongooseServerSelectionError.prototype.assimilateError = function(err) { - const reason = err.reason; - // Special message for a case that is likely due to IP whitelisting issues. - const isAtlasWhitelistError = isAtlas(reason) && allServersUnknown(reason); - this.message = isAtlasWhitelistError ? - atlasMessage : - err.message; - Object.assign(this, err, { - name: 'MongooseServerSelectionError' - }); - - return this; -}; - -module.exports = MongooseServerSelectionError; diff --git a/node_modules/mongoose/lib/error/strict.js b/node_modules/mongoose/lib/error/strict.js deleted file mode 100644 index 7f32268..0000000 --- a/node_modules/mongoose/lib/error/strict.js +++ /dev/null @@ -1,39 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/** - * Strict mode error constructor - * - * @param {String} type - * @param {String} value - * @inherits MongooseError - * @api private - */ - -function StrictModeError(path, msg, immutable) { - msg = msg || 'Field `' + path + '` is not in schema and strict ' + - 'mode is set to throw.'; - MongooseError.call(this, msg); - this.name = 'StrictModeError'; - this.isImmutableError = !!immutable; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } - this.path = path; -} - -/*! - * Inherits from MongooseError. - */ - -StrictModeError.prototype = Object.create(MongooseError.prototype); -StrictModeError.prototype.constructor = MongooseError; - -module.exports = StrictModeError; diff --git a/node_modules/mongoose/lib/error/validation.js b/node_modules/mongoose/lib/error/validation.js deleted file mode 100644 index ced82fc..0000000 --- a/node_modules/mongoose/lib/error/validation.js +++ /dev/null @@ -1,118 +0,0 @@ -/*! - * Module requirements - */ - -'use strict'; - -const MongooseError = require('./'); -const util = require('util'); - -/** - * Document Validation Error - * - * @api private - * @param {Document} instance - * @inherits MongooseError - */ - -function ValidationError(instance) { - this.errors = {}; - this._message = ''; - - if (instance && instance.constructor.name === 'model') { - this._message = instance.constructor.modelName + ' validation failed'; - } else { - this._message = 'Validation failed'; - } - MongooseError.call(this, this._message); - this.name = 'ValidationError'; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } - - if (instance) { - instance.errors = this.errors; - } -} - -/*! - * Inherits from MongooseError. - */ - -ValidationError.prototype = Object.create(MongooseError.prototype); -ValidationError.prototype.constructor = MongooseError; - -/** - * Console.log helper - */ - -ValidationError.prototype.toString = function() { - return this.name + ': ' + _generateMessage(this); -}; - -/*! - * inspect helper - */ - -ValidationError.prototype.inspect = function() { - return Object.assign(new Error(this.message), this); -}; - -if (util.inspect.custom) { - /*! - * Avoid Node deprecation warning DEP0079 - */ - - ValidationError.prototype[util.inspect.custom] = ValidationError.prototype.inspect; -} - -/*! - * Helper for JSON.stringify - */ -Object.defineProperty(ValidationError.prototype, 'toJSON', { - enumerable: false, - writable: false, - configurable: true, - value: function() { - return Object.assign({}, this, { message: this.message }); - } -}); - -/*! - * add message - */ - -ValidationError.prototype.addError = function(path, error) { - this.errors[path] = error; - this.message = this._message + ': ' + _generateMessage(this); -}; - -/*! - * ignore - */ - -function _generateMessage(err) { - const keys = Object.keys(err.errors || {}); - const len = keys.length; - const msgs = []; - let key; - - for (let i = 0; i < len; ++i) { - key = keys[i]; - if (err === err.errors[key]) { - continue; - } - msgs.push(key + ': ' + err.errors[key].message); - } - - return msgs.join(', '); -} - -/*! - * Module exports - */ - -module.exports = exports = ValidationError; diff --git a/node_modules/mongoose/lib/error/validator.js b/node_modules/mongoose/lib/error/validator.js deleted file mode 100644 index 2464581..0000000 --- a/node_modules/mongoose/lib/error/validator.js +++ /dev/null @@ -1,90 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseError = require('./'); - -/** - * Schema validator error - * - * @param {Object} properties - * @inherits MongooseError - * @api private - */ - -function ValidatorError(properties) { - let msg = properties.message; - if (!msg) { - msg = MongooseError.messages.general.default; - } - - const message = this.formatMessage(msg, properties); - MongooseError.call(this, message); - - properties = Object.assign({}, properties, { message: message }); - this.name = 'ValidatorError'; - if (Error.captureStackTrace) { - Error.captureStackTrace(this); - } else { - this.stack = new Error().stack; - } - this.properties = properties; - this.kind = properties.type; - this.path = properties.path; - this.value = properties.value; - this.reason = properties.reason; -} - -/*! - * Inherits from MongooseError - */ - -ValidatorError.prototype = Object.create(MongooseError.prototype); -ValidatorError.prototype.constructor = MongooseError; - -/*! - * The object used to define this validator. Not enumerable to hide - * it from `require('util').inspect()` output re: gh-3925 - */ - -Object.defineProperty(ValidatorError.prototype, 'properties', { - enumerable: false, - writable: true, - value: null -}); - -/*! - * Formats error messages - */ - -ValidatorError.prototype.formatMessage = function(msg, properties) { - if (typeof msg === 'function') { - return msg(properties); - } - - const propertyNames = Object.keys(properties); - for (const propertyName of propertyNames) { - if (propertyName === 'message') { - continue; - } - msg = msg.replace('{' + propertyName.toUpperCase() + '}', properties[propertyName]); - } - - return msg; -}; - -/*! - * toString helper - */ - -ValidatorError.prototype.toString = function() { - return this.message; -}; - -/*! - * exports - */ - -module.exports = ValidatorError; diff --git a/node_modules/mongoose/lib/error/version.js b/node_modules/mongoose/lib/error/version.js deleted file mode 100644 index 9fe9201..0000000 --- a/node_modules/mongoose/lib/error/version.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const MongooseError = require('./'); - -/** - * Version Error constructor. - * - * @inherits MongooseError - * @api private - */ - -function VersionError(doc, currentVersion, modifiedPaths) { - const modifiedPathsStr = modifiedPaths.join(', '); - MongooseError.call(this, 'No matching document found for id "' + doc._id + - '" version ' + currentVersion + ' modifiedPaths "' + modifiedPathsStr + '"'); - this.name = 'VersionError'; - this.version = currentVersion; - this.modifiedPaths = modifiedPaths; -} - -/*! - * Inherits from MongooseError. - */ - -VersionError.prototype = Object.create(MongooseError.prototype); -VersionError.prototype.constructor = MongooseError; - -/*! - * exports - */ - -module.exports = VersionError; diff --git a/node_modules/mongoose/lib/helpers/arrayDepth.js b/node_modules/mongoose/lib/helpers/arrayDepth.js deleted file mode 100644 index 0ac39ef..0000000 --- a/node_modules/mongoose/lib/helpers/arrayDepth.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -module.exports = arrayDepth; - -function arrayDepth(arr) { - if (!Array.isArray(arr)) { - return { min: 0, max: 0 }; - } - if (arr.length === 0) { - return { min: 1, max: 1 }; - } - - const res = arrayDepth(arr[0]); - for (let i = 1; i < arr.length; ++i) { - const _res = arrayDepth(arr[i]); - if (_res.min < res.min) { - res.min = _res.min; - } - if (_res.max > res.max) { - res.max = _res.max; - } - } - - res.min = res.min + 1; - res.max = res.max + 1; - - return res; -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/clone.js b/node_modules/mongoose/lib/helpers/clone.js deleted file mode 100644 index 1d53776..0000000 --- a/node_modules/mongoose/lib/helpers/clone.js +++ /dev/null @@ -1,137 +0,0 @@ -'use strict'; - - -const cloneRegExp = require('regexp-clone'); -const Decimal = require('../types/decimal128'); -const ObjectId = require('../types/objectid'); -const specialProperties = require('./specialProperties'); -const isMongooseObject = require('./isMongooseObject'); -const getFunctionName = require('./getFunctionName'); -const isBsonType = require('./isBsonType'); -const isObject = require('./isObject'); -const symbols = require('./symbols'); - - -/*! - * Object clone with Mongoose natives support. - * - * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible. - * - * Functions are never cloned. - * - * @param {Object} obj the object to clone - * @param {Object} options - * @param {Boolean} isArrayChild true if cloning immediately underneath an array. Special case for minimize. - * @return {Object} the cloned object - * @api private - */ - -function clone(obj, options, isArrayChild) { - if (obj == null) { - return obj; - } - - if (Array.isArray(obj)) { - return cloneArray(obj, options); - } - - if (isMongooseObject(obj)) { - // Single nested subdocs should apply getters later in `applyGetters()` - // when calling `toObject()`. See gh-7442, gh-8295 - if (options && options._skipSingleNestedGetters && obj.$isSingleNested) { - options = Object.assign({}, options, { getters: false }); - } - if (options && options.json && typeof obj.toJSON === 'function') { - return obj.toJSON(options); - } - return obj.toObject(options); - } - - if (obj.constructor) { - switch (getFunctionName(obj.constructor)) { - case 'Object': - return cloneObject(obj, options, isArrayChild); - case 'Date': - return new obj.constructor(+obj); - case 'RegExp': - return cloneRegExp(obj); - default: - // ignore - break; - } - } - - if (obj instanceof ObjectId) { - return new ObjectId(obj.id); - } - - if (isBsonType(obj, 'Decimal128')) { - if (options && options.flattenDecimals) { - return obj.toJSON(); - } - return Decimal.fromString(obj.toString()); - } - - if (!obj.constructor && isObject(obj)) { - // object created with Object.create(null) - return cloneObject(obj, options, isArrayChild); - } - - if (obj[symbols.schemaTypeSymbol]) { - return obj.clone(); - } - - // If we're cloning this object to go into a MongoDB command, - // and there's a `toBSON()` function, assume this object will be - // stored as a primitive in MongoDB and doesn't need to be cloned. - if (options && options.bson && typeof obj.toBSON === 'function') { - return obj; - } - - if (obj.valueOf != null) { - return obj.valueOf(); - } - - return cloneObject(obj, options, isArrayChild); -} -module.exports = clone; - -/*! - * ignore - */ - -function cloneObject(obj, options, isArrayChild) { - const minimize = options && options.minimize; - const ret = {}; - let hasKeys; - - for (const k in obj) { - if (specialProperties.has(k)) { - continue; - } - - // Don't pass `isArrayChild` down - const val = clone(obj[k], options); - - if (!minimize || (typeof val !== 'undefined')) { - if (minimize === false && typeof val === 'undefined') { - delete ret[k]; - } else { - hasKeys || (hasKeys = true); - ret[k] = val; - } - } - } - - return minimize && !isArrayChild ? hasKeys && ret : ret; -} - -function cloneArray(arr, options) { - const ret = []; - - for (const item of arr) { - ret.push(clone(item, options, true)); - } - - return ret; -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/common.js b/node_modules/mongoose/lib/helpers/common.js deleted file mode 100644 index ed7dc42..0000000 --- a/node_modules/mongoose/lib/helpers/common.js +++ /dev/null @@ -1,106 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const Binary = require('../driver').get().Binary; -const Decimal128 = require('../types/decimal128'); -const ObjectId = require('../types/objectid'); -const isMongooseObject = require('./isMongooseObject'); - -exports.flatten = flatten; -exports.modifiedPaths = modifiedPaths; - -/*! - * ignore - */ - -function flatten(update, path, options, schema) { - let keys; - if (update && isMongooseObject(update) && !Buffer.isBuffer(update)) { - keys = Object.keys(update.toObject({ transform: false, virtuals: false })); - } else { - keys = Object.keys(update || {}); - } - - const numKeys = keys.length; - const result = {}; - path = path ? path + '.' : ''; - - for (let i = 0; i < numKeys; ++i) { - const key = keys[i]; - const val = update[key]; - result[path + key] = val; - - // Avoid going into mixed paths if schema is specified - const keySchema = schema && schema.path && schema.path(path + key); - const isNested = schema && schema.nested && schema.nested[path + key]; - if (keySchema && keySchema.instance === 'Mixed') continue; - - if (shouldFlatten(val)) { - if (options && options.skipArrays && Array.isArray(val)) { - continue; - } - const flat = flatten(val, path + key, options, schema); - for (const k in flat) { - result[k] = flat[k]; - } - if (Array.isArray(val)) { - result[path + key] = val; - } - } - - if (isNested) { - const paths = Object.keys(schema.paths); - for (const p of paths) { - if (p.startsWith(path + key + '.') && !result.hasOwnProperty(p)) { - result[p] = void 0; - } - } - } - } - - return result; -} - -/*! - * ignore - */ - -function modifiedPaths(update, path, result) { - const keys = Object.keys(update || {}); - const numKeys = keys.length; - result = result || {}; - path = path ? path + '.' : ''; - - for (let i = 0; i < numKeys; ++i) { - const key = keys[i]; - let val = update[key]; - - result[path + key] = true; - if (isMongooseObject(val) && !Buffer.isBuffer(val)) { - val = val.toObject({ transform: false, virtuals: false }); - } - if (shouldFlatten(val)) { - modifiedPaths(val, path + key, result); - } - } - - return result; -} - -/*! - * ignore - */ - -function shouldFlatten(val) { - return val && - typeof val === 'object' && - !(val instanceof Date) && - !(val instanceof ObjectId) && - (!Array.isArray(val) || val.length > 0) && - !(val instanceof Buffer) && - !(val instanceof Decimal128) && - !(val instanceof Binary); -} diff --git a/node_modules/mongoose/lib/helpers/cursor/eachAsync.js b/node_modules/mongoose/lib/helpers/cursor/eachAsync.js deleted file mode 100644 index 4afff03..0000000 --- a/node_modules/mongoose/lib/helpers/cursor/eachAsync.js +++ /dev/null @@ -1,121 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const promiseOrCallback = require('../promiseOrCallback'); - -/** - * Execute `fn` for every document in the cursor. If `fn` returns a promise, - * will wait for the promise to resolve before iterating on to the next one. - * Returns a promise that resolves when done. - * - * @param {Function} next the thunk to call to get the next document - * @param {Function} fn - * @param {Object} options - * @param {Function} [callback] executed when all docs have been processed - * @return {Promise} - * @api public - * @method eachAsync - */ - -module.exports = function eachAsync(next, fn, options, callback) { - const parallel = options.parallel || 1; - const enqueue = asyncQueue(); - - return promiseOrCallback(callback, cb => { - iterate(cb); - }); - - function iterate(finalCallback) { - let drained = false; - let handleResultsInProgress = 0; - let currentDocumentIndex = 0; - - let error = null; - for (let i = 0; i < parallel; ++i) { - enqueue(fetch); - } - - function fetch(done) { - if (drained || error) { - return done(); - } - - next(function(err, doc) { - if (drained || error != null) { - return done(); - } - if (err != null) { - error = err; - finalCallback(err); - return done(); - } - if (doc == null) { - drained = true; - if (handleResultsInProgress <= 0) { - finalCallback(null); - } - return done(); - } - - ++handleResultsInProgress; - - // Kick off the subsequent `next()` before handling the result, but - // make sure we know that we still have a result to handle re: #8422 - process.nextTick(() => done()); - - handleNextResult(doc, currentDocumentIndex++, function(err) { - --handleResultsInProgress; - if (err != null) { - error = err; - return finalCallback(err); - } - if (drained && handleResultsInProgress <= 0) { - return finalCallback(null); - } - - setTimeout(() => enqueue(fetch), 0); - }); - }); - } - } - - function handleNextResult(doc, i, callback) { - const promise = fn(doc, i); - if (promise && typeof promise.then === 'function') { - promise.then( - function() { callback(null); }, - function(error) { callback(error || new Error('`eachAsync()` promise rejected without error')); }); - } else { - callback(null); - } - } -}; - -// `next()` can only execute one at a time, so make sure we always execute -// `next()` in series, while still allowing multiple `fn()` instances to run -// in parallel. -function asyncQueue() { - const _queue = []; - let inProgress = null; - let id = 0; - - return function enqueue(fn) { - if (_queue.length === 0 && inProgress == null) { - inProgress = id++; - return fn(_step); - } - _queue.push(fn); - }; - - function _step() { - inProgress = null; - if (_queue.length > 0) { - inProgress = id++; - const fn = _queue.shift(); - fn(_step); - } - } -} diff --git a/node_modules/mongoose/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js b/node_modules/mongoose/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js deleted file mode 100644 index 755de88..0000000 --- a/node_modules/mongoose/lib/helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -module.exports = function checkEmbeddedDiscriminatorKeyProjection(userProjection, path, schema, selected, addedPaths) { - const userProjectedInPath = Object.keys(userProjection). - reduce((cur, key) => cur || key.startsWith(path + '.'), false); - const _discriminatorKey = path + '.' + schema.options.discriminatorKey; - if (!userProjectedInPath && - addedPaths.length === 1 && - addedPaths[0] === _discriminatorKey) { - selected.splice(selected.indexOf(_discriminatorKey), 1); - } -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/discriminator/getConstructor.js b/node_modules/mongoose/lib/helpers/discriminator/getConstructor.js deleted file mode 100644 index 04a3ded..0000000 --- a/node_modules/mongoose/lib/helpers/discriminator/getConstructor.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -const getDiscriminatorByValue = require('./getDiscriminatorByValue'); - -/*! - * Find the correct constructor, taking into account discriminators - */ - -module.exports = function getConstructor(Constructor, value) { - const discriminatorKey = Constructor.schema.options.discriminatorKey; - if (value != null && - Constructor.discriminators && - value[discriminatorKey] != null) { - if (Constructor.discriminators[value[discriminatorKey]]) { - Constructor = Constructor.discriminators[value[discriminatorKey]]; - } else { - const constructorByValue = getDiscriminatorByValue(Constructor, value[discriminatorKey]); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } - - return Constructor; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/discriminator/getDiscriminatorByValue.js b/node_modules/mongoose/lib/helpers/discriminator/getDiscriminatorByValue.js deleted file mode 100644 index 87b3ad9..0000000 --- a/node_modules/mongoose/lib/helpers/discriminator/getDiscriminatorByValue.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -/*! -* returns discriminator by discriminatorMapping.value -* -* @param {Model} model -* @param {string} value -*/ - -module.exports = function getDiscriminatorByValue(model, value) { - let discriminator = null; - if (!model.discriminators) { - return discriminator; - } - for (const name in model.discriminators) { - const it = model.discriminators[name]; - if ( - it.schema && - it.schema.discriminatorMapping && - it.schema.discriminatorMapping.value == value - ) { - discriminator = it; - break; - } - } - return discriminator; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js b/node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js deleted file mode 100644 index 252d348..0000000 --- a/node_modules/mongoose/lib/helpers/document/cleanModifiedSubpaths.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function cleanModifiedSubpaths(doc, path, options) { - options = options || {}; - const skipDocArrays = options.skipDocArrays; - - let deleted = 0; - if (!doc) { - return deleted; - } - for (const modifiedPath of Object.keys(doc.$__.activePaths.states.modify)) { - if (skipDocArrays) { - const schemaType = doc.schema.path(modifiedPath); - if (schemaType && schemaType.$isMongooseDocumentArray) { - continue; - } - } - if (modifiedPath.startsWith(path + '.')) { - delete doc.$__.activePaths.states.modify[modifiedPath]; - ++deleted; - } - } - return deleted; -}; diff --git a/node_modules/mongoose/lib/helpers/document/compile.js b/node_modules/mongoose/lib/helpers/document/compile.js deleted file mode 100644 index f6eb160..0000000 --- a/node_modules/mongoose/lib/helpers/document/compile.js +++ /dev/null @@ -1,180 +0,0 @@ -'use strict'; - -const documentSchemaSymbol = require('../../helpers/symbols').documentSchemaSymbol; -const get = require('../../helpers/get'); -const getSymbol = require('../../helpers/symbols').getSymbol; -const utils = require('../../utils'); - -let Document; - -/*! - * exports - */ - -exports.compile = compile; -exports.defineKey = defineKey; - -/*! - * Compiles schemas. - */ - -function compile(tree, proto, prefix, options) { - Document = Document || require('../../document'); - const keys = Object.keys(tree); - const len = keys.length; - let limb; - let key; - - for (let i = 0; i < len; ++i) { - key = keys[i]; - limb = tree[key]; - - const hasSubprops = utils.isPOJO(limb) && Object.keys(limb).length && - (!limb[options.typeKey] || (options.typeKey === 'type' && limb.type.type)); - const subprops = hasSubprops ? limb : null; - - defineKey(key, subprops, proto, prefix, keys, options); - } -} - -/*! - * Defines the accessor named prop on the incoming prototype. - */ - -function defineKey(prop, subprops, prototype, prefix, keys, options) { - Document = Document || require('../../document'); - const path = (prefix ? prefix + '.' : '') + prop; - prefix = prefix || ''; - - if (subprops) { - Object.defineProperty(prototype, prop, { - enumerable: true, - configurable: true, - get: function() { - const _this = this; - if (!this.$__.getters) { - this.$__.getters = {}; - } - - if (!this.$__.getters[path]) { - const nested = Object.create(Document.prototype, getOwnPropertyDescriptors(this)); - - // save scope for nested getters/setters - if (!prefix) { - nested.$__.scope = this; - } - nested.$__.nestedPath = path; - - Object.defineProperty(nested, 'schema', { - enumerable: false, - configurable: true, - writable: false, - value: prototype.schema - }); - - Object.defineProperty(nested, documentSchemaSymbol, { - enumerable: false, - configurable: true, - writable: false, - value: prototype.schema - }); - - Object.defineProperty(nested, 'toObject', { - enumerable: false, - configurable: true, - writable: false, - value: function() { - return utils.clone(_this.get(path, null, { - virtuals: get(this, 'schema.options.toObject.virtuals', null) - })); - } - }); - - Object.defineProperty(nested, 'toJSON', { - enumerable: false, - configurable: true, - writable: false, - value: function() { - return _this.get(path, null, { - virtuals: get(_this, 'schema.options.toJSON.virtuals', null) - }); - } - }); - - Object.defineProperty(nested, '$__isNested', { - enumerable: false, - configurable: true, - writable: false, - value: true - }); - - const _isEmptyOptions = Object.freeze({ - minimize: true, - virtuals: false, - getters: false, - transform: false - }); - Object.defineProperty(nested, '$isEmpty', { - enumerable: false, - configurable: true, - writable: false, - value: function() { - return Object.keys(this.get(path, null, _isEmptyOptions) || {}).length === 0; - } - }); - - compile(subprops, nested, path, options); - this.$__.getters[path] = nested; - } - - return this.$__.getters[path]; - }, - set: function(v) { - if (v instanceof Document) { - v = v.toObject({ transform: false }); - } - const doc = this.$__.scope || this; - return doc.$set(path, v); - } - }); - } else { - Object.defineProperty(prototype, prop, { - enumerable: true, - configurable: true, - get: function() { - return this[getSymbol].call(this.$__.scope || this, path); - }, - set: function(v) { - return this.$set.call(this.$__.scope || this, path, v); - } - }); - } -} - -// gets descriptors for all properties of `object` -// makes all properties non-enumerable to match previous behavior to #2211 -function getOwnPropertyDescriptors(object) { - const result = {}; - - Object.getOwnPropertyNames(object).forEach(function(key) { - result[key] = Object.getOwnPropertyDescriptor(object, key); - // Assume these are schema paths, ignore them re: #5470 - if (result[key].get) { - delete result[key]; - return; - } - result[key].enumerable = [ - 'isNew', - '$__', - 'errors', - '_doc', - '$locals', - '$op', - '__parentArray', - '__index', - '$isDocumentArrayElement' - ].indexOf(key) === -1; - }); - - return result; -} diff --git a/node_modules/mongoose/lib/helpers/document/getEmbeddedDiscriminatorPath.js b/node_modules/mongoose/lib/helpers/document/getEmbeddedDiscriminatorPath.js deleted file mode 100644 index a2784e3..0000000 --- a/node_modules/mongoose/lib/helpers/document/getEmbeddedDiscriminatorPath.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -const get = require('../get'); - -/*! - * Like `schema.path()`, except with a document, because impossible to - * determine path type without knowing the embedded discriminator key. - */ - -module.exports = function getEmbeddedDiscriminatorPath(doc, path, options) { - options = options || {}; - const typeOnly = options.typeOnly; - const parts = path.split('.'); - let schema = null; - let type = 'adhocOrUndefined'; - - for (let i = 0; i < parts.length; ++i) { - const subpath = parts.slice(0, i + 1).join('.'); - schema = doc.schema.path(subpath); - if (schema == null) { - type = 'adhocOrUndefined'; - continue; - } - if (schema.instance === 'Mixed') { - return typeOnly ? 'real' : schema; - } - type = doc.schema.pathType(subpath); - if ((schema.$isSingleNested || schema.$isMongooseDocumentArrayElement) && - schema.schema.discriminators != null) { - const discriminators = schema.schema.discriminators; - const discriminatorKey = doc.get(subpath + '.' + - get(schema, 'schema.options.discriminatorKey')); - if (discriminatorKey == null || discriminators[discriminatorKey] == null) { - continue; - } - const rest = parts.slice(i + 1).join('.'); - return getEmbeddedDiscriminatorPath(doc.get(subpath), rest, options); - } - } - - // Are we getting the whole schema or just the type, 'real', 'nested', etc. - return typeOnly ? type : schema; -}; diff --git a/node_modules/mongoose/lib/helpers/document/handleSpreadDoc.js b/node_modules/mongoose/lib/helpers/document/handleSpreadDoc.js deleted file mode 100644 index d3075e4..0000000 --- a/node_modules/mongoose/lib/helpers/document/handleSpreadDoc.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -const utils = require('../../utils'); - -/** - * Using spread operator on a Mongoose document gives you a - * POJO that has a tendency to cause infinite recursion. So - * we use this function on `set()` to prevent that. - */ - -module.exports = function handleSpreadDoc(v) { - if (utils.isPOJO(v) && v.$__ != null && v._doc != null) { - return v._doc; - } - - return v; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/each.js b/node_modules/mongoose/lib/helpers/each.js deleted file mode 100644 index fe70069..0000000 --- a/node_modules/mongoose/lib/helpers/each.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -module.exports = function each(arr, cb, done) { - if (arr.length === 0) { - return done(); - } - - let remaining = arr.length; - let err = null; - for (const v of arr) { - cb(v, function(_err) { - if (err != null) { - return; - } - if (_err != null) { - err = _err; - return done(err); - } - - if (--remaining <= 0) { - return done(); - } - }); - } -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/get.js b/node_modules/mongoose/lib/helpers/get.js deleted file mode 100644 index dcb3881..0000000 --- a/node_modules/mongoose/lib/helpers/get.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -/*! - * Simplified lodash.get to work around the annoying null quirk. See: - * https://github.com/lodash/lodash/issues/3659 - */ - -module.exports = function get(obj, path, def) { - const parts = path.split('.'); - let rest = path; - let cur = obj; - for (const part of parts) { - if (cur == null) { - return def; - } - - // `lib/cast.js` depends on being able to get dotted paths in updates, - // like `{ $set: { 'a.b': 42 } }` - if (cur[rest] != null) { - return cur[rest]; - } - - cur = getProperty(cur, part); - - rest = rest.substr(part.length + 1); - } - - return cur == null ? def : cur; -}; - -function getProperty(obj, prop) { - if (obj == null) { - return obj; - } - if (obj instanceof Map) { - return obj.get(prop); - } - return obj[prop]; -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/getFunctionName.js b/node_modules/mongoose/lib/helpers/getFunctionName.js deleted file mode 100644 index 87a2c69..0000000 --- a/node_modules/mongoose/lib/helpers/getFunctionName.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -module.exports = function(fn) { - if (fn.name) { - return fn.name; - } - return (fn.toString().trim().match(/^function\s*([^\s(]+)/) || [])[1]; -}; diff --git a/node_modules/mongoose/lib/helpers/immediate.js b/node_modules/mongoose/lib/helpers/immediate.js deleted file mode 100644 index ddb7060..0000000 --- a/node_modules/mongoose/lib/helpers/immediate.js +++ /dev/null @@ -1,12 +0,0 @@ -/*! - * Centralize this so we can more easily work around issues with people - * stubbing out `process.nextTick()` in tests using sinon: - * https://github.com/sinonjs/lolex#automatically-incrementing-mocked-time - * See gh-6074 - */ - -'use strict'; - -module.exports = function immediate(cb) { - return process.nextTick(cb); -}; diff --git a/node_modules/mongoose/lib/helpers/indexes/isDefaultIdIndex.js b/node_modules/mongoose/lib/helpers/indexes/isDefaultIdIndex.js deleted file mode 100644 index c975dcf..0000000 --- a/node_modules/mongoose/lib/helpers/indexes/isDefaultIdIndex.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -const get = require('../get'); - -module.exports = function isDefaultIdIndex(index) { - if (Array.isArray(index)) { - // Mongoose syntax - const keys = Object.keys(index[0]); - return keys.length === 1 && keys[0] === '_id' && index[0]._id !== 'hashed'; - } - - if (typeof index !== 'object') { - return false; - } - - const key = get(index, 'key', {}); - return Object.keys(key).length === 1 && key.hasOwnProperty('_id'); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/isBsonType.js b/node_modules/mongoose/lib/helpers/isBsonType.js deleted file mode 100644 index 01435d3..0000000 --- a/node_modules/mongoose/lib/helpers/isBsonType.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -const get = require('./get'); - -/*! - * Get the bson type, if it exists - */ - -function isBsonType(obj, typename) { - return get(obj, '_bsontype', void 0) === typename; -} - -module.exports = isBsonType; diff --git a/node_modules/mongoose/lib/helpers/isMongooseObject.js b/node_modules/mongoose/lib/helpers/isMongooseObject.js deleted file mode 100644 index 016f9e6..0000000 --- a/node_modules/mongoose/lib/helpers/isMongooseObject.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -/*! - * Returns if `v` is a mongoose object that has a `toObject()` method we can use. - * - * This is for compatibility with libs like Date.js which do foolish things to Natives. - * - * @param {any} v - * @api private - */ - -module.exports = function(v) { - if (v == null) { - return false; - } - - return v.$__ != null || // Document - v.isMongooseArray || // Array or Document Array - v.isMongooseBuffer || // Buffer - v.$isMongooseMap; // Map -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/isObject.js b/node_modules/mongoose/lib/helpers/isObject.js deleted file mode 100644 index f8ac313..0000000 --- a/node_modules/mongoose/lib/helpers/isObject.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -/*! - * Determines if `arg` is an object. - * - * @param {Object|Array|String|Function|RegExp|any} arg - * @api private - * @return {Boolean} - */ - -module.exports = function(arg) { - if (Buffer.isBuffer(arg)) { - return true; - } - return Object.prototype.toString.call(arg) === '[object Object]'; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/model/applyHooks.js b/node_modules/mongoose/lib/helpers/model/applyHooks.js deleted file mode 100644 index de45f96..0000000 --- a/node_modules/mongoose/lib/helpers/model/applyHooks.js +++ /dev/null @@ -1,135 +0,0 @@ -'use strict'; - -const symbols = require('../../schema/symbols'); -const promiseOrCallback = require('../promiseOrCallback'); - -/*! - * ignore - */ - -module.exports = applyHooks; - -/*! - * ignore - */ - -applyHooks.middlewareFunctions = [ - 'deleteOne', - 'save', - 'validate', - 'remove', - 'updateOne', - 'init' -]; - -/*! - * Register hooks for this model - * - * @param {Model} model - * @param {Schema} schema - */ - -function applyHooks(model, schema, options) { - options = options || {}; - - const kareemOptions = { - useErrorHandlers: true, - numCallbackParams: 1, - nullResultByDefault: true, - contextParameter: true - }; - const objToDecorate = options.decorateDoc ? model : model.prototype; - - model.$appliedHooks = true; - for (const key of Object.keys(schema.paths)) { - const type = schema.paths[key]; - let childModel = null; - if (type.$isSingleNested) { - childModel = type.caster; - } else if (type.$isMongooseDocumentArray) { - childModel = type.Constructor; - } else { - continue; - } - - if (childModel.$appliedHooks) { - continue; - } - - applyHooks(childModel, type.schema, options); - if (childModel.discriminators != null) { - const keys = Object.keys(childModel.discriminators); - for (const key of keys) { - applyHooks(childModel.discriminators[key], - childModel.discriminators[key].schema, options); - } - } - } - - // Built-in hooks rely on hooking internal functions in order to support - // promises and make it so that `doc.save.toString()` provides meaningful - // information. - - const middleware = schema.s.hooks. - filter(hook => { - if (hook.name === 'updateOne' || hook.name === 'deleteOne') { - return !!hook['document']; - } - if (hook.name === 'remove') { - return hook['document'] == null || !!hook['document']; - } - return true; - }). - filter(hook => { - // If user has overwritten the method, don't apply built-in middleware - if (schema.methods[hook.name]) { - return !hook.fn[symbols.builtInMiddleware]; - } - - return true; - }); - - model._middleware = middleware; - - objToDecorate.$__originalValidate = objToDecorate.$__originalValidate || objToDecorate.$__validate; - - for (const method of ['save', 'validate', 'remove', 'deleteOne']) { - const toWrap = method === 'validate' ? '$__originalValidate' : `$__${method}`; - const wrapped = middleware. - createWrapper(method, objToDecorate[toWrap], null, kareemOptions); - objToDecorate[`$__${method}`] = wrapped; - } - objToDecorate.$__init = middleware. - createWrapperSync('init', objToDecorate.$__init, null, kareemOptions); - - // Support hooks for custom methods - const customMethods = Object.keys(schema.methods); - const customMethodOptions = Object.assign({}, kareemOptions, { - // Only use `checkForPromise` for custom methods, because mongoose - // query thunks are not as consistent as I would like about returning - // a nullish value rather than the query. If a query thunk returns - // a query, `checkForPromise` causes infinite recursion - checkForPromise: true - }); - for (const method of customMethods) { - if (!middleware.hasHooks(method)) { - // Don't wrap if there are no hooks for the custom method to avoid - // surprises. Also, `createWrapper()` enforces consistent async, - // so wrapping a sync method would break it. - continue; - } - const originalMethod = objToDecorate[method]; - objToDecorate[method] = function() { - const args = Array.prototype.slice.call(arguments); - const cb = args.slice(-1).pop(); - const argsWithoutCallback = typeof cb === 'function' ? - args.slice(0, args.length - 1) : args; - return promiseOrCallback(cb, callback => { - return this[`$__${method}`].apply(this, - argsWithoutCallback.concat([callback])); - }, model.events); - }; - objToDecorate[`$__${method}`] = middleware. - createWrapper(method, originalMethod, null, customMethodOptions); - } -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/model/applyMethods.js b/node_modules/mongoose/lib/helpers/model/applyMethods.js deleted file mode 100644 index 912f3aa..0000000 --- a/node_modules/mongoose/lib/helpers/model/applyMethods.js +++ /dev/null @@ -1,56 +0,0 @@ -'use strict'; - -const get = require('../get'); - -/*! - * Register methods for this model - * - * @param {Model} model - * @param {Schema} schema - */ - -module.exports = function applyMethods(model, schema) { - function apply(method, schema) { - Object.defineProperty(model.prototype, method, { - get: function() { - const h = {}; - for (const k in schema.methods[method]) { - h[k] = schema.methods[method][k].bind(this); - } - return h; - }, - configurable: true - }); - } - for (const method of Object.keys(schema.methods)) { - const fn = schema.methods[method]; - if (schema.tree.hasOwnProperty(method)) { - throw new Error('You have a method and a property in your schema both ' + - 'named "' + method + '"'); - } - if (schema.reserved[method] && - !get(schema, `methodOptions.${method}.suppressWarning`, false)) { - console.warn(`mongoose: the method name "${method}" is used by mongoose ` + - 'internally, overwriting it may cause bugs. If you\'re sure you know ' + - 'what you\'re doing, you can suppress this error by using ' + - `\`schema.method('${method}', fn, { suppressWarning: true })\`.`); - } - if (typeof fn === 'function') { - model.prototype[method] = fn; - } else { - apply(method, schema); - } - } - - // Recursively call `applyMethods()` on child schemas - model.$appliedMethods = true; - for (const key of Object.keys(schema.paths)) { - const type = schema.paths[key]; - if (type.$isSingleNested && !type.caster.$appliedMethods) { - applyMethods(type.caster, type.schema); - } - if (type.$isMongooseDocumentArray && !type.Constructor.$appliedMethods) { - applyMethods(type.Constructor, type.schema); - } - } -}; diff --git a/node_modules/mongoose/lib/helpers/model/applyStaticHooks.js b/node_modules/mongoose/lib/helpers/model/applyStaticHooks.js deleted file mode 100644 index 219e289..0000000 --- a/node_modules/mongoose/lib/helpers/model/applyStaticHooks.js +++ /dev/null @@ -1,71 +0,0 @@ -'use strict'; - -const middlewareFunctions = require('../query/applyQueryMiddleware').middlewareFunctions; -const promiseOrCallback = require('../promiseOrCallback'); - -module.exports = function applyStaticHooks(model, hooks, statics) { - const kareemOptions = { - useErrorHandlers: true, - numCallbackParams: 1 - }; - - hooks = hooks.filter(hook => { - // If the custom static overwrites an existing query middleware, don't apply - // middleware to it by default. This avoids a potential backwards breaking - // change with plugins like `mongoose-delete` that use statics to overwrite - // built-in Mongoose functions. - if (middlewareFunctions.indexOf(hook.name) !== -1) { - return !!hook.model; - } - return hook.model !== false; - }); - - model.$__insertMany = hooks.createWrapper('insertMany', - model.$__insertMany, model, kareemOptions); - - for (const key of Object.keys(statics)) { - if (hooks.hasHooks(key)) { - const original = model[key]; - - model[key] = function() { - const numArgs = arguments.length; - const lastArg = numArgs > 0 ? arguments[numArgs - 1] : null; - const cb = typeof lastArg === 'function' ? lastArg : null; - const args = Array.prototype.slice. - call(arguments, 0, cb == null ? numArgs : numArgs - 1); - // Special case: can't use `Kareem#wrap()` because it doesn't currently - // support wrapped functions that return a promise. - return promiseOrCallback(cb, callback => { - hooks.execPre(key, model, args, function(err) { - if (err != null) { - return callback(err); - } - - let postCalled = 0; - const ret = original.apply(model, args.concat(post)); - if (ret != null && typeof ret.then === 'function') { - ret.then(res => post(null, res), err => post(err)); - } - - function post(error, res) { - if (postCalled++ > 0) { - return; - } - - if (error != null) { - return callback(error); - } - - hooks.execPost(key, model, [res], function(error) { - if (error != null) { - return callback(error); - } - callback(null, res); - }); - } - }); - }, model.events); - }; - } - } -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/model/applyStatics.js b/node_modules/mongoose/lib/helpers/model/applyStatics.js deleted file mode 100644 index 3b9501e..0000000 --- a/node_modules/mongoose/lib/helpers/model/applyStatics.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -/*! - * Register statics for this model - * @param {Model} model - * @param {Schema} schema - */ -module.exports = function applyStatics(model, schema) { - for (const i in schema.statics) { - model[i] = schema.statics[i]; - } -}; diff --git a/node_modules/mongoose/lib/helpers/model/castBulkWrite.js b/node_modules/mongoose/lib/helpers/model/castBulkWrite.js deleted file mode 100644 index c08d588..0000000 --- a/node_modules/mongoose/lib/helpers/model/castBulkWrite.js +++ /dev/null @@ -1,172 +0,0 @@ -'use strict'; - -const applyTimestampsToChildren = require('../update/applyTimestampsToChildren'); -const applyTimestampsToUpdate = require('../update/applyTimestampsToUpdate'); -const cast = require('../../cast'); -const castUpdate = require('../query/castUpdate'); -const setDefaultsOnInsert = require('../setDefaultsOnInsert'); - -/*! - * Given a model and a bulkWrite op, return a thunk that handles casting and - * validating the individual op. - */ - -module.exports = function castBulkWrite(model, op, options) { - const now = model.base.now(); - const schema = model.schema; - const strict = options.strict != null ? options.strict : model.schema.options.strict; - - if (op['insertOne']) { - return (callback) => { - const doc = new model(op['insertOne']['document']); - if (model.schema.options.timestamps != null) { - doc.initializeTimestamps(); - } - if (options.session != null) { - doc.$session(options.session); - } - op['insertOne']['document'] = doc; - op['insertOne']['document'].validate({ __noPromise: true }, function(error) { - if (error) { - return callback(error, null); - } - callback(null); - }); - }; - } else if (op['updateOne']) { - return (callback) => { - try { - if (!op['updateOne']['filter']) throw new Error('Must provide a filter object.'); - if (!op['updateOne']['update']) throw new Error('Must provide an update object.'); - - _addDiscriminatorToObject(schema, op['updateOne']['filter']); - op['updateOne']['filter'] = cast(model.schema, op['updateOne']['filter'], { - strict: strict, - upsert: op['updateOne'].upsert - }); - op['updateOne']['update'] = castUpdate(model.schema, op['updateOne']['update'], { - strict: strict, - overwrite: false, - upsert: op['updateOne'].upsert - }); - - if (op['updateOne'].setDefaultsOnInsert) { - setDefaultsOnInsert(op['updateOne']['filter'], model.schema, op['updateOne']['update'], { - setDefaultsOnInsert: true, - upsert: op['updateOne'].upsert - }); - } - if (model.schema.$timestamps != null && op['updateOne'].timestamps !== false) { - const createdAt = model.schema.$timestamps.createdAt; - const updatedAt = model.schema.$timestamps.updatedAt; - applyTimestampsToUpdate(now, createdAt, updatedAt, op['updateOne']['update'], {}); - } - applyTimestampsToChildren(now, op['updateOne']['update'], model.schema); - } catch (error) { - return callback(error, null); - } - - callback(null); - }; - } else if (op['updateMany']) { - return (callback) => { - try { - if (!op['updateMany']['filter']) throw new Error('Must provide a filter object.'); - if (!op['updateMany']['update']) throw new Error('Must provide an update object.'); - - _addDiscriminatorToObject(schema, op['updateMany']['filter']); - op['updateMany']['filter'] = cast(model.schema, op['updateMany']['filter'], { - strict: strict, - upsert: op['updateMany'].upsert - }); - op['updateMany']['update'] = castUpdate(model.schema, op['updateMany']['update'], { - strict: strict, - overwrite: false, - upsert: op['updateMany'].upsert - }); - if (op['updateMany'].setDefaultsOnInsert) { - setDefaultsOnInsert(op['updateMany']['filter'], model.schema, op['updateMany']['update'], { - setDefaultsOnInsert: true, - upsert: op['updateMany'].upsert - }); - } - if (model.schema.$timestamps != null && op['updateMany'].timestamps !== false) { - const createdAt = model.schema.$timestamps.createdAt; - const updatedAt = model.schema.$timestamps.updatedAt; - applyTimestampsToUpdate(now, createdAt, updatedAt, op['updateMany']['update'], {}); - } - applyTimestampsToChildren(now, op['updateMany']['update'], model.schema); - } catch (error) { - return callback(error, null); - } - - callback(null); - }; - } else if (op['replaceOne']) { - return (callback) => { - _addDiscriminatorToObject(schema, op['replaceOne']['filter']); - try { - op['replaceOne']['filter'] = cast(model.schema, op['replaceOne']['filter'], { - strict: strict, - upsert: op['replaceOne'].upsert - }); - } catch (error) { - return callback(error, null); - } - - // set `skipId`, otherwise we get "_id field cannot be changed" - const doc = new model(op['replaceOne']['replacement'], strict, true); - if (model.schema.options.timestamps != null) { - doc.initializeTimestamps(); - } - if (options.session != null) { - doc.$session(options.session); - } - op['replaceOne']['replacement'] = doc; - - op['replaceOne']['replacement'].validate({ __noPromise: true }, function(error) { - if (error) { - return callback(error, null); - } - callback(null); - }); - }; - } else if (op['deleteOne']) { - return (callback) => { - _addDiscriminatorToObject(schema, op['deleteOne']['filter']); - try { - op['deleteOne']['filter'] = cast(model.schema, - op['deleteOne']['filter']); - } catch (error) { - return callback(error, null); - } - - callback(null); - }; - } else if (op['deleteMany']) { - return (callback) => { - _addDiscriminatorToObject(schema, op['deleteMany']['filter']); - try { - op['deleteMany']['filter'] = cast(model.schema, - op['deleteMany']['filter']); - } catch (error) { - return callback(error, null); - } - - callback(null); - }; - } else { - return (callback) => { - callback(new Error('Invalid op passed to `bulkWrite()`'), null); - }; - } -}; - -function _addDiscriminatorToObject(schema, obj) { - if (schema == null) { - return; - } - if (schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { - obj[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; - } -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/model/discriminator.js b/node_modules/mongoose/lib/helpers/model/discriminator.js deleted file mode 100644 index d689e1c..0000000 --- a/node_modules/mongoose/lib/helpers/model/discriminator.js +++ /dev/null @@ -1,183 +0,0 @@ -'use strict'; - -const defineKey = require('../document/compile').defineKey; -const get = require('../get'); -const utils = require('../../utils'); - -const CUSTOMIZABLE_DISCRIMINATOR_OPTIONS = { - toJSON: true, - toObject: true, - _id: true, - id: true -}; - -/*! - * ignore - */ - -module.exports = function discriminator(model, name, schema, tiedValue, applyPlugins) { - if (!(schema && schema.instanceOfSchema)) { - throw new Error('You must pass a valid discriminator Schema'); - } - - if (model.schema.discriminatorMapping && - !model.schema.discriminatorMapping.isRoot) { - throw new Error('Discriminator "' + name + - '" can only be a discriminator of the root model'); - } - - if (applyPlugins) { - const applyPluginsToDiscriminators = get(model.base, - 'options.applyPluginsToDiscriminators', false); - // Even if `applyPluginsToDiscriminators` isn't set, we should still apply - // global plugins to schemas embedded in the discriminator schema (gh-7370) - model.base._applyPlugins(schema, { - skipTopLevel: !applyPluginsToDiscriminators - }); - } - - const key = model.schema.options.discriminatorKey; - - const existingPath = model.schema.path(key); - if (existingPath != null) { - if (!utils.hasUserDefinedProperty(existingPath.options, 'select')) { - existingPath.options.select = true; - } - existingPath.options.$skipDiscriminatorCheck = true; - } else { - const baseSchemaAddition = {}; - baseSchemaAddition[key] = { - default: void 0, - select: true, - $skipDiscriminatorCheck: true - }; - baseSchemaAddition[key][model.schema.options.typeKey] = String; - model.schema.add(baseSchemaAddition); - defineKey(key, null, model.prototype, null, [key], model.schema.options); - } - - if (schema.path(key) && schema.path(key).options.$skipDiscriminatorCheck !== true) { - throw new Error('Discriminator "' + name + - '" cannot have field with name "' + key + '"'); - } - - let value = name; - if (typeof tiedValue == 'string' && tiedValue.length) { - value = tiedValue; - } - - function merge(schema, baseSchema) { - // Retain original schema before merging base schema - schema._baseSchema = baseSchema; - if (baseSchema.paths._id && - baseSchema.paths._id.options && - !baseSchema.paths._id.options.auto) { - schema.remove('_id'); - } - - // Find conflicting paths: if something is a path in the base schema - // and a nested path in the child schema, overwrite the base schema path. - // See gh-6076 - const baseSchemaPaths = Object.keys(baseSchema.paths); - const conflictingPaths = []; - - for (const path of baseSchemaPaths) { - if (schema.nested[path]) { - conflictingPaths.push(path); - } - } - - utils.merge(schema, baseSchema, { - omit: { discriminators: true, base: true }, - omitNested: conflictingPaths.reduce((cur, path) => { - cur['tree.' + path] = true; - return cur; - }, {}) - }); - - // Clean up conflicting paths _after_ merging re: gh-6076 - for (const conflictingPath of conflictingPaths) { - delete schema.paths[conflictingPath]; - } - - // Rebuild schema models because schemas may have been merged re: #7884 - schema.childSchemas.forEach(obj => { - obj.model.prototype.$__setSchema(obj.schema); - }); - - const obj = {}; - obj[key] = { - default: value, - select: true, - set: function(newName) { - if (newName === value) { - return value; - } - throw new Error('Can\'t set discriminator key "' + key + '"'); - }, - $skipDiscriminatorCheck: true - }; - obj[key][schema.options.typeKey] = existingPath ? - existingPath.instance : - String; - schema.add(obj); - schema.discriminatorMapping = { key: key, value: value, isRoot: false }; - - if (baseSchema.options.collection) { - schema.options.collection = baseSchema.options.collection; - } - - const toJSON = schema.options.toJSON; - const toObject = schema.options.toObject; - const _id = schema.options._id; - const id = schema.options.id; - - const keys = Object.keys(schema.options); - schema.options.discriminatorKey = baseSchema.options.discriminatorKey; - - for (const _key of keys) { - if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) { - if (!utils.deepEqual(schema.options[_key], baseSchema.options[_key])) { - throw new Error('Can\'t customize discriminator option ' + _key + - ' (can only modify ' + - Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(', ') + - ')'); - } - } - } - schema.options = utils.clone(baseSchema.options); - if (toJSON) schema.options.toJSON = toJSON; - if (toObject) schema.options.toObject = toObject; - if (typeof _id !== 'undefined') { - schema.options._id = _id; - } - schema.options.id = id; - schema.s.hooks = model.schema.s.hooks.merge(schema.s.hooks); - - schema.plugins = Array.prototype.slice.call(baseSchema.plugins); - schema.callQueue = baseSchema.callQueue.concat(schema.callQueue); - delete schema._requiredpaths; // reset just in case Schema#requiredPaths() was called on either schema - } - - // merges base schema into new discriminator schema and sets new type field. - merge(schema, model.schema); - - if (!model.discriminators) { - model.discriminators = {}; - } - - if (!model.schema.discriminatorMapping) { - model.schema.discriminatorMapping = { key: key, value: null, isRoot: true }; - } - if (!model.schema.discriminators) { - model.schema.discriminators = {}; - } - - model.schema.discriminators[name] = schema; - - if (model.discriminators[name]) { - throw new Error('Discriminator with name "' + name + '" already exists'); - } - - return schema; -}; diff --git a/node_modules/mongoose/lib/helpers/once.js b/node_modules/mongoose/lib/helpers/once.js deleted file mode 100644 index 0267579..0000000 --- a/node_modules/mongoose/lib/helpers/once.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -module.exports = function once(fn) { - let called = false; - return function() { - if (called) { - return; - } - called = true; - return fn.apply(null, arguments); - }; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/parallelLimit.js b/node_modules/mongoose/lib/helpers/parallelLimit.js deleted file mode 100644 index 9b07c02..0000000 --- a/node_modules/mongoose/lib/helpers/parallelLimit.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -module.exports = parallelLimit; - -/*! - * ignore - */ - -function parallelLimit(fns, limit, callback) { - let numInProgress = 0; - let numFinished = 0; - let error = null; - - if (limit <= 0) { - throw new Error('Limit must be positive'); - } - - if (fns.length === 0) { - return callback(null, []); - } - - for (let i = 0; i < fns.length && i < limit; ++i) { - _start(); - } - - function _start() { - fns[numFinished + numInProgress](_done(numFinished + numInProgress)); - ++numInProgress; - } - - const results = []; - - function _done(index) { - return (err, res) => { - --numInProgress; - ++numFinished; - - if (error != null) { - return; - } - if (err != null) { - error = err; - return callback(error); - } - - results[index] = res; - - if (numFinished === fns.length) { - return callback(null, results); - } else if (numFinished + numInProgress < fns.length) { - _start(); - } - }; - } -} diff --git a/node_modules/mongoose/lib/helpers/populate/SkipPopulateValue.js b/node_modules/mongoose/lib/helpers/populate/SkipPopulateValue.js deleted file mode 100644 index 5d46cfd..0000000 --- a/node_modules/mongoose/lib/helpers/populate/SkipPopulateValue.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -module.exports = function SkipPopulateValue(val) { - if (!(this instanceof SkipPopulateValue)) { - return new SkipPopulateValue(val); - } - - this.val = val; - return this; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/assignRawDocsToIdStructure.js b/node_modules/mongoose/lib/helpers/populate/assignRawDocsToIdStructure.js deleted file mode 100644 index 843c148..0000000 --- a/node_modules/mongoose/lib/helpers/populate/assignRawDocsToIdStructure.js +++ /dev/null @@ -1,98 +0,0 @@ -'use strict'; - -const leanPopulateMap = require('./leanPopulateMap'); -const modelSymbol = require('../symbols').modelSymbol; -const utils = require('../../utils'); - -module.exports = assignRawDocsToIdStructure; - -/*! - * Assign `vals` returned by mongo query to the `rawIds` - * structure returned from utils.getVals() honoring - * query sort order if specified by user. - * - * This can be optimized. - * - * Rules: - * - * if the value of the path is not an array, use findOne rules, else find. - * for findOne the results are assigned directly to doc path (including null results). - * for find, if user specified sort order, results are assigned directly - * else documents are put back in original order of array if found in results - * - * @param {Array} rawIds - * @param {Array} vals - * @param {Boolean} sort - * @api private - */ - -function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, recursed) { - // honor user specified sort order - const newOrder = []; - const sorting = options.sort && rawIds.length > 1; - const nullIfNotFound = options.$nullIfNotFound; - let doc; - let sid; - let id; - - for (let i = 0; i < rawIds.length; ++i) { - id = rawIds[i]; - - if (Array.isArray(id)) { - // handle [ [id0, id2], [id3] ] - assignRawDocsToIdStructure(id, resultDocs, resultOrder, options, true); - newOrder.push(id); - continue; - } - - if (id === null && !sorting) { - // keep nulls for findOne unless sorting, which always - // removes them (backward compat) - newOrder.push(id); - continue; - } - - sid = String(id); - - doc = resultDocs[sid]; - // If user wants separate copies of same doc, use this option - if (options.clone && doc != null) { - if (options.lean) { - const _model = leanPopulateMap.get(doc); - doc = utils.clone(doc); - leanPopulateMap.set(doc, _model); - } else { - doc = doc.constructor.hydrate(doc._doc); - } - } - - if (recursed) { - if (doc) { - if (sorting) { - newOrder[resultOrder[sid]] = doc; - } else { - newOrder.push(doc); - } - } else if (id != null && id[modelSymbol] != null) { - newOrder.push(id); - } else { - newOrder.push(options.retainNullValues || nullIfNotFound ? null : id); - } - } else { - // apply findOne behavior - if document in results, assign, else assign null - newOrder[i] = doc || null; - } - } - - rawIds.length = 0; - if (newOrder.length) { - // reassign the documents based on corrected order - - // forEach skips over sparse entries in arrays so we - // can safely use this to our advantage dealing with sorted - // result sets too. - newOrder.forEach(function(doc, i) { - rawIds[i] = doc; - }); - } -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/assignVals.js b/node_modules/mongoose/lib/helpers/populate/assignVals.js deleted file mode 100644 index bd93e81..0000000 --- a/node_modules/mongoose/lib/helpers/populate/assignVals.js +++ /dev/null @@ -1,239 +0,0 @@ -'use strict'; - -const SkipPopulateValue = require('./SkipPopulateValue'); -const assignRawDocsToIdStructure = require('./assignRawDocsToIdStructure'); -const get = require('../get'); -const getVirtual = require('./getVirtual'); -const leanPopulateMap = require('./leanPopulateMap'); -const mpath = require('mpath'); -const sift = require('sift').default; -const utils = require('../../utils'); - -module.exports = function assignVals(o) { - // Options that aren't explicitly listed in `populateOptions` - const userOptions = get(o, 'allOptions.options.options'); - // `o.options` contains options explicitly listed in `populateOptions`, like - // `match` and `limit`. - const populateOptions = Object.assign({}, o.options, userOptions, { - justOne: o.justOne - }); - populateOptions.$nullIfNotFound = o.isVirtual; - - const originalIds = [].concat(o.rawIds); - - // replace the original ids in our intermediate _ids structure - // with the documents found by query - assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, populateOptions); - - // now update the original documents being populated using the - // result structure that contains real documents. - const docs = o.docs; - const rawIds = o.rawIds; - const options = o.options; - const count = o.count && o.isVirtual; - - function setValue(val) { - if (count) { - return val; - } - if (val instanceof SkipPopulateValue) { - return val.val; - } - if (o.justOne === true && Array.isArray(val)) { - return valueFilter(val[0], options, populateOptions); - } else if (o.justOne === false && !Array.isArray(val)) { - return valueFilter([val], options, populateOptions); - } - return valueFilter(val, options, populateOptions); - } - - for (let i = 0; i < docs.length; ++i) { - const existingVal = utils.getValue(o.path, docs[i]); - if (existingVal == null && !getVirtual(o.originalModel.schema, o.path)) { - continue; - } - - let valueToSet; - if (count) { - valueToSet = numDocs(rawIds[i]); - } else if (Array.isArray(o.match)) { - valueToSet = Array.isArray(rawIds[i]) ? - sift(o.match[i], rawIds[i]) : - sift(o.match[i], [rawIds[i]])[0]; - } else { - valueToSet = rawIds[i]; - } - - // If we're populating a map, the existing value will be an object, so - // we need to transform again - const originalSchema = o.originalModel.schema; - const isDoc = get(docs[i], '$__', null) != null; - let isMap = isDoc ? - existingVal instanceof Map : - utils.isPOJO(existingVal); - // If we pass the first check, also make sure the local field's schematype - // is map (re: gh-6460) - isMap = isMap && get(originalSchema._getSchema(o.path), '$isSchemaMap'); - if (!o.isVirtual && isMap) { - const _keys = existingVal instanceof Map ? - Array.from(existingVal.keys()) : - Object.keys(existingVal); - valueToSet = valueToSet.reduce((cur, v, i) => { - cur.set(_keys[i], v); - return cur; - }, new Map()); - } - - if (o.isVirtual && isDoc) { - docs[i].populated(o.path, o.justOne ? originalIds[0] : originalIds, o.allOptions); - // If virtual populate and doc is already init-ed, need to walk through - // the actual doc to set rather than setting `_doc` directly - mpath.set(o.path, valueToSet, docs[i], setValue); - continue; - } - - const parts = o.path.split('.'); - let cur = docs[i]; - const curPath = parts[0]; - for (let j = 0; j < parts.length - 1; ++j) { - // If we get to an array with a dotted path, like `arr.foo`, don't set - // `foo` on the array. - if (Array.isArray(cur) && !utils.isArrayIndex(parts[j])) { - break; - } - - if (cur[parts[j]] == null) { - // If nothing to set, avoid creating an unnecessary array. Otherwise - // we'll end up with a single doc in the array with only defaults. - // See gh-8342, gh-8455 - const schematype = originalSchema._getSchema(curPath); - if (valueToSet == null && schematype != null && schematype.$isMongooseArray) { - return; - } - cur[parts[j]] = {}; - } - cur = cur[parts[j]]; - // If the property in MongoDB is a primitive, we won't be able to populate - // the nested path, so skip it. See gh-7545 - if (typeof cur !== 'object') { - return; - } - } - if (docs[i].$__) { - docs[i].populated(o.path, o.allIds[i], o.allOptions); - } - - // If lean, need to check that each individual virtual respects - // `justOne`, because you may have a populated virtual with `justOne` - // underneath an array. See gh-6867 - utils.setValue(o.path, valueToSet, docs[i], setValue, false); - } -}; - -function numDocs(v) { - if (Array.isArray(v)) { - // If setting underneath an array of populated subdocs, we may have an - // array of arrays. See gh-7573 - if (v.some(el => Array.isArray(el))) { - return v.map(el => numDocs(el)); - } - return v.length; - } - return v == null ? 0 : 1; -} - -/*! - * 1) Apply backwards compatible find/findOne behavior to sub documents - * - * find logic: - * a) filter out non-documents - * b) remove _id from sub docs when user specified - * - * findOne - * a) if no doc found, set to null - * b) remove _id from sub docs when user specified - * - * 2) Remove _ids when specified by users query. - * - * background: - * _ids are left in the query even when user excludes them so - * that population mapping can occur. - */ - -function valueFilter(val, assignmentOpts, populateOptions) { - if (Array.isArray(val)) { - // find logic - const ret = []; - const numValues = val.length; - for (let i = 0; i < numValues; ++i) { - const subdoc = val[i]; - if (!isPopulatedObject(subdoc) && (!populateOptions.retainNullValues || subdoc != null)) { - continue; - } - maybeRemoveId(subdoc, assignmentOpts); - ret.push(subdoc); - if (assignmentOpts.originalLimit && - ret.length >= assignmentOpts.originalLimit) { - break; - } - } - - // Since we don't want to have to create a new mongoosearray, make sure to - // modify the array in place - while (val.length > ret.length) { - Array.prototype.pop.apply(val, []); - } - for (let i = 0; i < ret.length; ++i) { - val[i] = ret[i]; - } - return val; - } - - // findOne - if (isPopulatedObject(val)) { - maybeRemoveId(val, assignmentOpts); - return val; - } - - if (val instanceof Map) { - return val; - } - - if (populateOptions.justOne === true) { - return (val == null ? val : null); - } - if (populateOptions.justOne === false) { - return []; - } - return val; -} - -/*! - * Remove _id from `subdoc` if user specified "lean" query option - */ - -function maybeRemoveId(subdoc, assignmentOpts) { - if (assignmentOpts.excludeId) { - if (typeof subdoc.$__setValue === 'function') { - delete subdoc._doc._id; - } else { - delete subdoc._id; - } - } -} - -/*! - * Determine if `obj` is something we can set a populated path to. Can be a - * document, a lean document, or an array/map that contains docs. - */ - -function isPopulatedObject(obj) { - if (obj == null) { - return false; - } - - return Array.isArray(obj) || - obj.$isMongooseMap || - obj.$__ != null || - leanPopulateMap.has(obj); -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/getModelsMapForPopulate.js b/node_modules/mongoose/lib/helpers/populate/getModelsMapForPopulate.js deleted file mode 100644 index d6b51c3..0000000 --- a/node_modules/mongoose/lib/helpers/populate/getModelsMapForPopulate.js +++ /dev/null @@ -1,492 +0,0 @@ -'use strict'; - -const MongooseError = require('../../error/index'); -const SkipPopulateValue = require('./SkipPopulateValue'); -const get = require('../get'); -const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue'); -const isPathExcluded = require('../projection/isPathExcluded'); -const getSchemaTypes = require('./getSchemaTypes'); -const getVirtual = require('./getVirtual'); -const normalizeRefPath = require('./normalizeRefPath'); -const util = require('util'); -const utils = require('../../utils'); - -const modelSymbol = require('../symbols').modelSymbol; -const populateModelSymbol = require('../symbols').populateModelSymbol; -const schemaMixedSymbol = require('../../schema/symbols').schemaMixedSymbol; - -module.exports = function getModelsMapForPopulate(model, docs, options) { - let i; - let doc; - const len = docs.length; - const available = {}; - const map = []; - const modelNameFromQuery = options.model && options.model.modelName || options.model; - let schema; - let refPath; - let Model; - let currentOptions; - let modelNames; - let modelName; - let modelForFindSchema; - - const originalModel = options.model; - let isVirtual = false; - const modelSchema = model.schema; - - let allSchemaTypes = getSchemaTypes(modelSchema, null, options.path); - allSchemaTypes = Array.isArray(allSchemaTypes) ? allSchemaTypes : [allSchemaTypes].filter(v => v != null); - const _firstWithRefPath = allSchemaTypes.find(schematype => get(schematype, 'options.refPath', null) != null); - - for (i = 0; i < len; i++) { - doc = docs[i]; - - schema = getSchemaTypes(modelSchema, doc, options.path); - const isUnderneathDocArray = schema && schema.$isUnderneathDocArray; - if (isUnderneathDocArray && get(options, 'options.sort') != null) { - return new MongooseError('Cannot populate with `sort` on path ' + options.path + - ' because it is a subproperty of a document array'); - } - - modelNames = null; - let isRefPath = !!_firstWithRefPath; - let normalizedRefPath = _firstWithRefPath ? get(_firstWithRefPath, 'options.refPath', null) : null; - - if (Array.isArray(schema)) { - const schemasArray = schema; - for (const _schema of schemasArray) { - let _modelNames; - let res; - try { - res = _getModelNames(doc, _schema); - _modelNames = res.modelNames; - isRefPath = isRefPath || res.isRefPath; - normalizedRefPath = normalizeRefPath(normalizedRefPath, doc, options.path) || - res.refPath; - } catch (error) { - return error; - } - - if (isRefPath && !res.isRefPath) { - continue; - } - if (!_modelNames) { - continue; - } - modelNames = modelNames || []; - for (const modelName of _modelNames) { - if (modelNames.indexOf(modelName) === -1) { - modelNames.push(modelName); - } - } - } - } else { - try { - const res = _getModelNames(doc, schema); - modelNames = res.modelNames; - isRefPath = res.isRefPath; - normalizedRefPath = res.refPath; - } catch (error) { - return error; - } - - if (!modelNames) { - continue; - } - } - - const _virtualRes = getVirtual(model.schema, options.path); - const virtual = _virtualRes == null ? null : _virtualRes.virtual; - - let localField; - let count = false; - if (virtual && virtual.options) { - const virtualPrefix = _virtualRes.nestedSchemaPath ? - _virtualRes.nestedSchemaPath + '.' : ''; - if (typeof virtual.options.localField === 'function') { - localField = virtualPrefix + virtual.options.localField.call(doc, doc); - } else { - localField = virtualPrefix + virtual.options.localField; - } - count = virtual.options.count; - - if (virtual.options.skip != null && !options.hasOwnProperty('skip')) { - options.skip = virtual.options.skip; - } - if (virtual.options.limit != null && !options.hasOwnProperty('limit')) { - options.limit = virtual.options.limit; - } - if (virtual.options.perDocumentLimit != null && !options.hasOwnProperty('perDocumentLimit')) { - options.perDocumentLimit = virtual.options.perDocumentLimit; - } - } else { - localField = options.path; - } - let foreignField = virtual && virtual.options ? - virtual.options.foreignField : - '_id'; - - // `justOne = null` means we don't know from the schema whether the end - // result should be an array or a single doc. This can result from - // populating a POJO using `Model.populate()` - let justOne = null; - if ('justOne' in options && options.justOne !== void 0) { - justOne = options.justOne; - } else if (virtual && virtual.options && virtual.options.refPath) { - const normalizedRefPath = - normalizeRefPath(virtual.options.refPath, doc, options.path); - justOne = !!virtual.options.justOne; - isVirtual = true; - const refValue = utils.getValue(normalizedRefPath, doc); - modelNames = Array.isArray(refValue) ? refValue : [refValue]; - } else if (virtual && virtual.options && virtual.options.ref) { - let normalizedRef; - if (typeof virtual.options.ref === 'function') { - normalizedRef = virtual.options.ref.call(doc, doc); - } else { - normalizedRef = virtual.options.ref; - } - justOne = !!virtual.options.justOne; - isVirtual = true; - if (!modelNames) { - modelNames = [].concat(normalizedRef); - } - } else if (schema && !schema[schemaMixedSymbol]) { - // Skip Mixed types because we explicitly don't do casting on those. - justOne = !schema.$isMongooseArray; - } - - if (!modelNames) { - continue; - } - - if (virtual && (!localField || !foreignField)) { - return new MongooseError('If you are populating a virtual, you must set the ' + - 'localField and foreignField options'); - } - - options.isVirtual = isVirtual; - options.virtual = virtual; - if (typeof localField === 'function') { - localField = localField.call(doc, doc); - } - if (typeof foreignField === 'function') { - foreignField = foreignField.call(doc); - } - - const localFieldPathType = modelSchema._getPathType(localField); - const localFieldPath = localFieldPathType === 'real' ? modelSchema.path(localField) : localFieldPathType.schema; - const localFieldGetters = localFieldPath && localFieldPath.getters ? localFieldPath.getters : []; - let ret; - - const _populateOptions = get(options, 'options', {}); - - const getters = 'getters' in _populateOptions ? - _populateOptions.getters : - options.isVirtual && get(virtual, 'options.getters', false); - if (localFieldGetters.length > 0 && getters) { - const hydratedDoc = (doc.$__ != null) ? doc : model.hydrate(doc); - const localFieldValue = utils.getValue(localField, doc); - if (Array.isArray(localFieldValue)) { - const localFieldHydratedValue = utils.getValue(localField.split('.').slice(0, -1), hydratedDoc); - ret = localFieldValue.map((localFieldArrVal, localFieldArrIndex) => - localFieldPath.applyGetters(localFieldArrVal, localFieldHydratedValue[localFieldArrIndex])); - } else { - ret = localFieldPath.applyGetters(localFieldValue, hydratedDoc); - } - } else { - ret = convertTo_id(utils.getValue(localField, doc), schema); - } - - const id = String(utils.getValue(foreignField, doc)); - options._docs[id] = Array.isArray(ret) ? ret.slice() : ret; - - let match = get(options, 'match', null) || - get(currentOptions, 'match', null) || - get(options, 'virtual.options.match', null) || - get(options, 'virtual.options.options.match', null); - - const hasMatchFunction = typeof match === 'function'; - if (hasMatchFunction) { - match = match.call(doc, doc); - } - - // Re: gh-8452. Embedded discriminators may not have `refPath`, so clear - // out embedded discriminator docs that don't have a `refPath` on the - // populated path. - if (isRefPath && normalizedRefPath != null) { - const pieces = normalizedRefPath.split('.'); - let cur = ''; - for (const piece of pieces) { - cur = cur + (cur.length === 0 ? '' : '.') + piece; - const schematype = modelSchema.path(cur); - if (schematype != null && - schematype.$isMongooseArray && - schematype.caster.discriminators != null && - Object.keys(schematype.caster.discriminators).length > 0) { - const subdocs = utils.getValue(cur, doc); - const remnant = options.path.substr(cur.length + 1); - const discriminatorKey = schematype.caster.schema.options.discriminatorKey; - modelNames = []; - for (const subdoc of subdocs) { - const discriminatorName = utils.getValue(discriminatorKey, subdoc); - const discriminator = schematype.caster.discriminators[discriminatorName]; - const discriminatorSchema = discriminator && discriminator.schema; - if (discriminatorSchema == null) { - continue; - } - const _path = discriminatorSchema.path(remnant); - if (_path == null || _path.options.refPath == null) { - const docValue = utils.getValue(localField.substr(cur.length + 1), subdoc); - ret = ret.map(v => v === docValue ? SkipPopulateValue(v) : v); - continue; - } - const modelName = utils.getValue(pieces.slice(i + 1).join('.'), subdoc); - modelNames.push(modelName); - } - } - } - } - - let k = modelNames.length; - while (k--) { - modelName = modelNames[k]; - if (modelName == null) { - continue; - } - - // `PopulateOptions#connection`: if the model is passed as a string, the - // connection matters because different connections have different models. - const connection = options.connection != null ? options.connection : model.db; - - try { - Model = originalModel && originalModel[modelSymbol] ? - originalModel : - modelName[modelSymbol] ? modelName : connection.model(modelName); - } catch (error) { - return error; - } - - let ids = ret; - const flat = Array.isArray(ret) ? utils.array.flatten(ret) : []; - - if (isRefPath && Array.isArray(ret) && flat.length === modelNames.length) { - ids = flat.filter((val, i) => modelNames[i] === modelName); - } - - if (!available[modelName] || currentOptions.perDocumentLimit != null) { - currentOptions = { - model: Model - }; - - if (isVirtual && get(virtual, 'options.options')) { - currentOptions.options = utils.clone(virtual.options.options); - } - utils.merge(currentOptions, options); - - // Used internally for checking what model was used to populate this - // path. - options[populateModelSymbol] = Model; - - available[modelName] = { - model: Model, - options: currentOptions, - match: hasMatchFunction ? [match] : match, - docs: [doc], - ids: [ids], - allIds: [ret], - localField: new Set([localField]), - foreignField: new Set([foreignField]), - justOne: justOne, - isVirtual: isVirtual, - virtual: virtual, - count: count, - [populateModelSymbol]: Model - }; - map.push(available[modelName]); - } else { - available[modelName].localField.add(localField); - available[modelName].foreignField.add(foreignField); - available[modelName].docs.push(doc); - available[modelName].ids.push(ids); - available[modelName].allIds.push(ret); - if (hasMatchFunction) { - available[modelName].match.push(match); - } - } - } - } - - return map; - - function _getModelNames(doc, schema) { - let modelNames; - let discriminatorKey; - let isRefPath = false; - - if (schema && schema.caster) { - schema = schema.caster; - } - if (schema && schema.$isSchemaMap) { - schema = schema.$__schemaType; - } - - if (!schema && model.discriminators) { - discriminatorKey = model.schema.discriminatorMapping.key; - } - - refPath = schema && schema.options && schema.options.refPath; - - const normalizedRefPath = normalizeRefPath(refPath, doc, options.path); - - if (modelNameFromQuery) { - modelNames = [modelNameFromQuery]; // query options - } else if (normalizedRefPath) { - if (options._queryProjection != null && isPathExcluded(options._queryProjection, normalizedRefPath)) { - throw new MongooseError('refPath `' + normalizedRefPath + - '` must not be excluded in projection, got ' + - util.inspect(options._queryProjection)); - } - - if (modelSchema.virtuals.hasOwnProperty(normalizedRefPath) && doc.$__ == null) { - modelNames = [modelSchema.virtuals[normalizedRefPath].applyGetters(void 0, doc)]; - } else { - modelNames = utils.getValue(normalizedRefPath, doc); - } - - if (Array.isArray(modelNames)) { - modelNames = utils.array.flatten(modelNames); - } - - isRefPath = true; - } else { - let modelForCurrentDoc = model; - let schemaForCurrentDoc; - - if (!schema && discriminatorKey) { - modelForFindSchema = utils.getValue(discriminatorKey, doc); - if (modelForFindSchema) { - // `modelForFindSchema` is the discriminator value, so we might need - // find the discriminated model name - const discriminatorModel = getDiscriminatorByValue(model, modelForFindSchema); - if (discriminatorModel != null) { - modelForCurrentDoc = discriminatorModel; - } else { - try { - modelForCurrentDoc = model.db.model(modelForFindSchema); - } catch (error) { - return error; - } - } - - schemaForCurrentDoc = modelForCurrentDoc.schema._getSchema(options.path); - - if (schemaForCurrentDoc && schemaForCurrentDoc.caster) { - schemaForCurrentDoc = schemaForCurrentDoc.caster; - } - } - } else { - schemaForCurrentDoc = schema; - } - const _virtualRes = getVirtual(modelForCurrentDoc.schema, options.path); - const virtual = _virtualRes == null ? null : _virtualRes.virtual; - - let ref; - let refPath; - - if ((ref = get(schemaForCurrentDoc, 'options.ref')) != null) { - ref = handleRefFunction(ref, doc); - modelNames = [ref]; - } else if ((ref = get(virtual, 'options.ref')) != null) { - ref = handleRefFunction(ref, doc); - - // When referencing nested arrays, the ref should be an Array - // of modelNames. - if (Array.isArray(ref)) { - modelNames = ref; - } else { - modelNames = [ref]; - } - - isVirtual = true; - } else if ((refPath = get(schemaForCurrentDoc, 'options.refPath')) != null) { - isRefPath = true; - refPath = normalizeRefPath(refPath, doc, options.path); - modelNames = utils.getValue(refPath, doc); - if (Array.isArray(modelNames)) { - modelNames = utils.array.flatten(modelNames); - } - } else { - // We may have a discriminator, in which case we don't want to - // populate using the base model by default - modelNames = discriminatorKey ? null : [model.modelName]; - } - } - - if (!modelNames) { - return { modelNames: modelNames, isRefPath: isRefPath, refPath: normalizedRefPath }; - } - - if (!Array.isArray(modelNames)) { - modelNames = [modelNames]; - } - - return { modelNames: modelNames, isRefPath: isRefPath, refPath: normalizedRefPath }; - } -}; - -/*! - * ignore - */ - -function handleRefFunction(ref, doc) { - if (typeof ref === 'function' && !ref[modelSymbol]) { - return ref.call(doc, doc); - } - return ref; -} - -/*! - * Retrieve the _id of `val` if a Document or Array of Documents. - * - * @param {Array|Document|Any} val - * @return {Array|Document|Any} - */ - -function convertTo_id(val, schema) { - if (val != null && val.$__ != null) return val._id; - - if (Array.isArray(val)) { - for (let i = 0; i < val.length; ++i) { - if (val[i] != null && val[i].$__ != null) { - val[i] = val[i]._id; - } - } - if (val.isMongooseArray && val.$schema()) { - return val.$schema().cast(val, val.$parent()); - } - - return [].concat(val); - } - - // `populate('map')` may be an object if populating on a doc that hasn't - // been hydrated yet - if (val != null && - val.constructor.name === 'Object' && - // The intent here is we should only flatten the object if we expect - // to get a Map in the end. Avoid doing this for mixed types. - (schema == null || schema[schemaMixedSymbol] == null)) { - const ret = []; - for (const key of Object.keys(val)) { - ret.push(val[key]); - } - return ret; - } - // If doc has already been hydrated, e.g. `doc.populate('map').execPopulate()` - // then `val` will already be a map - if (val instanceof Map) { - return Array.from(val.values()); - } - - return val; -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/getSchemaTypes.js b/node_modules/mongoose/lib/helpers/populate/getSchemaTypes.js deleted file mode 100644 index 15660df..0000000 --- a/node_modules/mongoose/lib/helpers/populate/getSchemaTypes.js +++ /dev/null @@ -1,198 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -const Mixed = require('../../schema/mixed'); -const get = require('../get'); -const leanPopulateMap = require('./leanPopulateMap'); -const mpath = require('mpath'); - -const populateModelSymbol = require('../symbols').populateModelSymbol; - -/*! - * @param {Schema} schema - * @param {Object} doc POJO - * @param {string} path - */ - -module.exports = function getSchemaTypes(schema, doc, path) { - const pathschema = schema.path(path); - const topLevelDoc = doc; - - if (pathschema) { - return pathschema; - } - - function search(parts, schema, subdoc, nestedPath) { - let p = parts.length + 1; - let foundschema; - let trypath; - - while (p--) { - trypath = parts.slice(0, p).join('.'); - foundschema = schema.path(trypath); - - if (foundschema == null) { - continue; - } - - if (foundschema.caster) { - // array of Mixed? - if (foundschema.caster instanceof Mixed) { - return foundschema.caster; - } - - let schemas = null; - if (foundschema.schema != null && foundschema.schema.discriminators != null) { - const discriminators = foundschema.schema.discriminators; - const discriminatorKeyPath = trypath + '.' + - foundschema.schema.options.discriminatorKey; - const keys = subdoc ? mpath.get(discriminatorKeyPath, subdoc) || [] : []; - schemas = Object.keys(discriminators). - reduce(function(cur, discriminator) { - if (doc == null || keys.indexOf(discriminator) !== -1) { - cur.push(discriminators[discriminator]); - } - return cur; - }, []); - } - - // Now that we found the array, we need to check if there - // are remaining document paths to look up for casting. - // Also we need to handle array.$.path since schema.path - // doesn't work for that. - // If there is no foundschema.schema we are dealing with - // a path like array.$ - if (p !== parts.length && foundschema.schema) { - let ret; - if (parts[p] === '$') { - if (p + 1 === parts.length) { - // comments.$ - return foundschema; - } - // comments.$.comments.$.title - ret = search( - parts.slice(p + 1), - schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); - if (ret) { - ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - } - return ret; - } - - if (schemas != null && schemas.length > 0) { - ret = []; - for (const schema of schemas) { - const _ret = search( - parts.slice(p), - schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); - if (_ret != null) { - _ret.$isUnderneathDocArray = _ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - if (_ret.$isUnderneathDocArray) { - ret.$isUnderneathDocArray = true; - } - ret.push(_ret); - } - } - return ret; - } else { - ret = search( - parts.slice(p), - foundschema.schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); - - if (ret) { - ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - } - - return ret; - } - } else if (p !== parts.length && - foundschema.$isMongooseArray && - foundschema.casterConstructor.$isMongooseArray) { - // Nested arrays. Drill down to the bottom of the nested array. - // Ignore discriminators. - let type = foundschema; - while (type.$isMongooseArray && !type.$isMongooseDocumentArray) { - type = type.casterConstructor; - } - return search( - parts.slice(p), - type.schema, - null, - nestedPath.concat(parts.slice(0, p)) - ); - } - } - - const fullPath = nestedPath.concat([trypath]).join('.'); - if (topLevelDoc != null && topLevelDoc.$__ && topLevelDoc.populated(fullPath) && p < parts.length) { - const model = doc.$__.populated[fullPath].options[populateModelSymbol]; - if (model != null) { - const ret = search( - parts.slice(p), - model.schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); - - if (ret) { - ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || - !model.schema.$isSingleNested; - } - - return ret; - } - } - - const _val = get(topLevelDoc, trypath); - if (_val != null) { - const model = Array.isArray(_val) && _val.length > 0 ? - leanPopulateMap.get(_val[0]) : - leanPopulateMap.get(_val); - // Populated using lean, `leanPopulateMap` value is the foreign model - const schema = model != null ? model.schema : null; - if (schema != null) { - const ret = search( - parts.slice(p), - schema, - subdoc ? mpath.get(trypath, subdoc) : null, - nestedPath.concat(parts.slice(0, p)) - ); - - if (ret) { - ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || - !schema.$isSingleNested; - } - - return ret; - } - } - - return foundschema; - } - } - - // look for arrays - const parts = path.split('.'); - for (let i = 0; i < parts.length; ++i) { - if (parts[i] === '$') { - // Re: gh-5628, because `schema.path()` doesn't take $ into account. - parts[i] = '0'; - } - } - return search(parts, schema, doc, []); -}; diff --git a/node_modules/mongoose/lib/helpers/populate/getVirtual.js b/node_modules/mongoose/lib/helpers/populate/getVirtual.js deleted file mode 100644 index fc1641d..0000000 --- a/node_modules/mongoose/lib/helpers/populate/getVirtual.js +++ /dev/null @@ -1,72 +0,0 @@ -'use strict'; - -module.exports = getVirtual; - -/*! - * ignore - */ - -function getVirtual(schema, name) { - if (schema.virtuals[name]) { - return { virtual: schema.virtuals[name], path: void 0 }; - } - - const parts = name.split('.'); - let cur = ''; - let nestedSchemaPath = ''; - for (let i = 0; i < parts.length; ++i) { - cur += (cur.length > 0 ? '.' : '') + parts[i]; - if (schema.virtuals[cur]) { - if (i === parts.length - 1) { - return { virtual: schema.virtuals[cur], path: nestedSchemaPath }; - } - continue; - } - - if (schema.nested[cur]) { - continue; - } - - if (schema.paths[cur] && schema.paths[cur].schema) { - schema = schema.paths[cur].schema; - const rest = parts.slice(i + 1).join('.'); - - if (schema.virtuals[rest]) { - if (i === parts.length - 2) { - return { - virtual: schema.virtuals[rest], - nestedSchemaPath: [nestedSchemaPath, cur].filter(v => !!v).join('.') - }; - } - continue; - } - - if (i + 1 < parts.length && schema.discriminators) { - for (const key of Object.keys(schema.discriminators)) { - const res = getVirtual(schema.discriminators[key], rest); - if (res != null) { - const _path = [nestedSchemaPath, cur, res.nestedSchemaPath]. - filter(v => !!v).join('.'); - return { - virtual: res.virtual, - nestedSchemaPath: _path - }; - } - } - } - - nestedSchemaPath += (nestedSchemaPath.length > 0 ? '.' : '') + cur; - cur = ''; - continue; - } - - if (schema.discriminators) { - for (const discriminatorKey of Object.keys(schema.discriminators)) { - const virtualFromDiscriminator = getVirtual(schema.discriminators[discriminatorKey], name); - if (virtualFromDiscriminator) return virtualFromDiscriminator; - } - } - - return null; - } -} diff --git a/node_modules/mongoose/lib/helpers/populate/leanPopulateMap.js b/node_modules/mongoose/lib/helpers/populate/leanPopulateMap.js deleted file mode 100644 index a333124..0000000 --- a/node_modules/mongoose/lib/helpers/populate/leanPopulateMap.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = new WeakMap(); \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/normalizeRefPath.js b/node_modules/mongoose/lib/helpers/populate/normalizeRefPath.js deleted file mode 100644 index 233b741..0000000 --- a/node_modules/mongoose/lib/helpers/populate/normalizeRefPath.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -module.exports = function normalizeRefPath(refPath, doc, populatedPath) { - if (refPath == null) { - return refPath; - } - - if (typeof refPath === 'function') { - refPath = refPath.call(doc, doc, populatedPath); - } - - // If populated path has numerics, the end `refPath` should too. For example, - // if populating `a.0.b` instead of `a.b` and `b` has `refPath = a.c`, we - // should return `a.0.c` for the refPath. - const hasNumericProp = /(\.\d+$|\.\d+\.)/g; - - if (hasNumericProp.test(populatedPath)) { - const chunks = populatedPath.split(hasNumericProp); - - if (chunks[chunks.length - 1] === '') { - throw new Error('Can\'t populate individual element in an array'); - } - - let _refPath = ''; - let _remaining = refPath; - // 2nd, 4th, etc. will be numeric props. For example: `[ 'a', '.0.', 'b' ]` - for (let i = 0; i < chunks.length; i += 2) { - const chunk = chunks[i]; - if (_remaining.startsWith(chunk + '.')) { - _refPath += _remaining.substr(0, chunk.length) + chunks[i + 1]; - _remaining = _remaining.substr(chunk.length + 1); - } else if (i === chunks.length - 1) { - _refPath += _remaining; - _remaining = ''; - break; - } else { - throw new Error('Could not normalize ref path, chunk ' + chunk + ' not in populated path'); - } - } - - return _refPath; - } - - return refPath; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/populate/validateRef.js b/node_modules/mongoose/lib/helpers/populate/validateRef.js deleted file mode 100644 index 9dc2b6f..0000000 --- a/node_modules/mongoose/lib/helpers/populate/validateRef.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const MongooseError = require('../../error/mongooseError'); -const util = require('util'); - -module.exports = validateRef; - -function validateRef(ref, path) { - if (typeof ref === 'string') { - return; - } - - if (typeof ref === 'function') { - return; - } - - throw new MongooseError('Invalid ref at path "' + path + '". Got ' + - util.inspect(ref, { depth: 0 })); -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/printJestWarning.js b/node_modules/mongoose/lib/helpers/printJestWarning.js deleted file mode 100644 index eb3a8eb..0000000 --- a/node_modules/mongoose/lib/helpers/printJestWarning.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -if (typeof jest !== 'undefined' && typeof window !== 'undefined') { - console.warn('Mongoose: looks like you\'re trying to test a Mongoose app ' + - 'with Jest\'s default jsdom test environment. Please make sure you read ' + - 'Mongoose\'s docs on configuring Jest to test Node.js apps: ' + - 'http://mongoosejs.com/docs/jest.html'); -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/projection/isDefiningProjection.js b/node_modules/mongoose/lib/helpers/projection/isDefiningProjection.js deleted file mode 100644 index 67dfb39..0000000 --- a/node_modules/mongoose/lib/helpers/projection/isDefiningProjection.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function isDefiningProjection(val) { - if (val == null) { - // `undefined` or `null` become exclusive projections - return true; - } - if (typeof val === 'object') { - // Only cases where a value does **not** define whether the whole projection - // is inclusive or exclusive are `$meta` and `$slice`. - return !('$meta' in val) && !('$slice' in val); - } - return true; -}; diff --git a/node_modules/mongoose/lib/helpers/projection/isExclusive.js b/node_modules/mongoose/lib/helpers/projection/isExclusive.js deleted file mode 100644 index 8c64bc5..0000000 --- a/node_modules/mongoose/lib/helpers/projection/isExclusive.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -const isDefiningProjection = require('./isDefiningProjection'); - -/*! - * ignore - */ - -module.exports = function isExclusive(projection) { - const keys = Object.keys(projection); - let ki = keys.length; - let exclude = null; - - if (ki === 1 && keys[0] === '_id') { - exclude = !!projection[keys[ki]]; - } else { - while (ki--) { - // Does this projection explicitly define inclusion/exclusion? - // Explicitly avoid `$meta` and `$slice` - if (keys[ki] !== '_id' && isDefiningProjection(projection[keys[ki]])) { - exclude = !projection[keys[ki]]; - break; - } - } - } - - return exclude; -}; diff --git a/node_modules/mongoose/lib/helpers/projection/isInclusive.js b/node_modules/mongoose/lib/helpers/projection/isInclusive.js deleted file mode 100644 index 098309f..0000000 --- a/node_modules/mongoose/lib/helpers/projection/isInclusive.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const isDefiningProjection = require('./isDefiningProjection'); - -/*! - * ignore - */ - -module.exports = function isInclusive(projection) { - if (projection == null) { - return false; - } - - const props = Object.keys(projection); - const numProps = props.length; - if (numProps === 0) { - return false; - } - - for (let i = 0; i < numProps; ++i) { - const prop = props[i]; - // Plus paths can't define the projection (see gh-7050) - if (prop.startsWith('+')) { - continue; - } - // If field is truthy (1, true, etc.) and not an object, then this - // projection must be inclusive. If object, assume its $meta, $slice, etc. - if (isDefiningProjection(projection[prop]) && !!projection[prop]) { - return true; - } - } - - return false; -}; diff --git a/node_modules/mongoose/lib/helpers/projection/isPathExcluded.js b/node_modules/mongoose/lib/helpers/projection/isPathExcluded.js deleted file mode 100644 index fc2592c..0000000 --- a/node_modules/mongoose/lib/helpers/projection/isPathExcluded.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const isDefiningProjection = require('./isDefiningProjection'); - -/*! - * Determines if `path` is excluded by `projection` - * - * @param {Object} projection - * @param {string} path - * @return {Boolean} - */ - -module.exports = function isPathExcluded(projection, path) { - if (path === '_id') { - return projection._id === 0; - } - - const paths = Object.keys(projection); - let type = null; - - for (const _path of paths) { - if (isDefiningProjection(projection[_path])) { - type = projection[path] === 1 ? 'inclusive' : 'exclusive'; - break; - } - } - - if (type === 'inclusive') { - return projection[path] !== 1; - } - if (type === 'exclusive') { - return projection[path] === 0; - } - return false; -}; diff --git a/node_modules/mongoose/lib/helpers/projection/isPathSelectedInclusive.js b/node_modules/mongoose/lib/helpers/projection/isPathSelectedInclusive.js deleted file mode 100644 index 8a05fc9..0000000 --- a/node_modules/mongoose/lib/helpers/projection/isPathSelectedInclusive.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function isPathSelectedInclusive(fields, path) { - const chunks = path.split('.'); - let cur = ''; - let j; - let keys; - let numKeys; - for (let i = 0; i < chunks.length; ++i) { - cur += cur.length ? '.' : '' + chunks[i]; - if (fields[cur]) { - keys = Object.keys(fields); - numKeys = keys.length; - for (j = 0; j < numKeys; ++j) { - if (keys[i].indexOf(cur + '.') === 0 && keys[i].indexOf(path) !== 0) { - continue; - } - } - return true; - } - } - - return false; -}; diff --git a/node_modules/mongoose/lib/helpers/projection/parseProjection.js b/node_modules/mongoose/lib/helpers/projection/parseProjection.js deleted file mode 100644 index d2a44b1..0000000 --- a/node_modules/mongoose/lib/helpers/projection/parseProjection.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -/** - * Convert a string or array into a projection object, retaining all - * `-` and `+` paths. - */ - -module.exports = function parseProjection(v, retainMinusPaths) { - const type = typeof v; - - if (type === 'string') { - v = v.split(/\s+/); - } - if (!Array.isArray(v) && Object.prototype.toString.call(v) !== '[object Arguments]') { - return v; - } - - const len = v.length; - const ret = {}; - for (let i = 0; i < len; ++i) { - let field = v[i]; - if (!field) { - continue; - } - const include = '-' == field[0] ? 0 : 1; - if (!retainMinusPaths && include === 0) { - field = field.substring(1); - } - ret[field] = include; - } - - return ret; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/promiseOrCallback.js b/node_modules/mongoose/lib/helpers/promiseOrCallback.js deleted file mode 100644 index a1aff55..0000000 --- a/node_modules/mongoose/lib/helpers/promiseOrCallback.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -const PromiseProvider = require('../promise_provider'); - -const emittedSymbol = Symbol.for('mongoose:emitted'); - -module.exports = function promiseOrCallback(callback, fn, ee) { - if (typeof callback === 'function') { - return fn(function(error) { - if (error != null) { - if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) { - error[emittedSymbol] = true; - ee.emit('error', error); - } - try { - callback(error); - } catch (error) { - return process.nextTick(() => { - throw error; - }); - } - return; - } - callback.apply(this, arguments); - }); - } - - const Promise = PromiseProvider.get(); - - return new Promise((resolve, reject) => { - fn(function(error, res) { - if (error != null) { - if (ee != null && ee.listeners('error').length > 0 && !error[emittedSymbol]) { - error[emittedSymbol] = true; - ee.emit('error', error); - } - return reject(error); - } - if (arguments.length > 2) { - return resolve(Array.prototype.slice.call(arguments, 1)); - } - resolve(res); - }); - }); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/applyGlobalMaxTimeMS.js b/node_modules/mongoose/lib/helpers/query/applyGlobalMaxTimeMS.js deleted file mode 100644 index cb49260..0000000 --- a/node_modules/mongoose/lib/helpers/query/applyGlobalMaxTimeMS.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -const utils = require('../../utils'); - -module.exports = function applyGlobalMaxTimeMS(options, model) { - if (utils.hasUserDefinedProperty(options, 'maxTimeMS')) { - return; - } - - if (utils.hasUserDefinedProperty(model.db.options, 'maxTimeMS')) { - options.maxTimeMS = model.db.options.maxTimeMS; - } else if (utils.hasUserDefinedProperty(model.base.options, 'maxTimeMS')) { - options.maxTimeMS = model.base.options.maxTimeMS; - } -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/applyQueryMiddleware.js b/node_modules/mongoose/lib/helpers/query/applyQueryMiddleware.js deleted file mode 100644 index a08baf8..0000000 --- a/node_modules/mongoose/lib/helpers/query/applyQueryMiddleware.js +++ /dev/null @@ -1,90 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = applyQueryMiddleware; - -/*! - * ignore - */ - -applyQueryMiddleware.middlewareFunctions = [ - 'count', - 'countDocuments', - 'deleteMany', - 'deleteOne', - 'distinct', - 'estimatedDocumentCount', - 'find', - 'findOne', - 'findOneAndDelete', - 'findOneAndRemove', - 'findOneAndReplace', - 'findOneAndUpdate', - 'remove', - 'replaceOne', - 'update', - 'updateMany', - 'updateOne', - 'validate' -]; - -/*! - * Apply query middleware - * - * @param {Query} query constructor - * @param {Model} model - */ - -function applyQueryMiddleware(Query, model) { - const kareemOptions = { - useErrorHandlers: true, - numCallbackParams: 1, - nullResultByDefault: true - }; - - const middleware = model.hooks.filter(hook => { - const contexts = _getContexts(hook); - if (hook.name === 'updateOne') { - return contexts.query == null || !!contexts.query; - } - if (hook.name === 'deleteOne') { - return !!contexts.query || Object.keys(contexts).length === 0; - } - if (hook.name === 'validate' || hook.name === 'remove') { - return !!contexts.query; - } - return true; - }); - - // `update()` thunk has a different name because `_update` was already taken - Query.prototype._execUpdate = middleware.createWrapper('update', - Query.prototype._execUpdate, null, kareemOptions); - // `distinct()` thunk has a different name because `_distinct` was already taken - Query.prototype.__distinct = middleware.createWrapper('distinct', - Query.prototype.__distinct, null, kareemOptions); - - // `validate()` doesn't have a thunk because it doesn't execute a query. - Query.prototype.validate = middleware.createWrapper('validate', - Query.prototype.validate, null, kareemOptions); - - applyQueryMiddleware.middlewareFunctions. - filter(v => v !== 'update' && v !== 'distinct' && v !== 'validate'). - forEach(fn => { - Query.prototype[`_${fn}`] = middleware.createWrapper(fn, - Query.prototype[`_${fn}`], null, kareemOptions); - }); -} - -function _getContexts(hook) { - const ret = {}; - if (hook.hasOwnProperty('query')) { - ret.query = hook.query; - } - if (hook.hasOwnProperty('document')) { - ret.document = hook.document; - } - return ret; -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/castFilterPath.js b/node_modules/mongoose/lib/helpers/query/castFilterPath.js deleted file mode 100644 index 74ff1c2..0000000 --- a/node_modules/mongoose/lib/helpers/query/castFilterPath.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -const isOperator = require('./isOperator'); - -module.exports = function castFilterPath(query, schematype, val) { - const ctx = query; - const any$conditionals = Object.keys(val).some(isOperator); - - if (!any$conditionals) { - return schematype.castForQueryWrapper({ - val: val, - context: ctx - }); - } - - const ks = Object.keys(val); - - let k = ks.length; - - while (k--) { - const $cond = ks[k]; - const nested = val[$cond]; - - if ($cond === '$not') { - if (nested && schematype && !schematype.caster) { - const _keys = Object.keys(nested); - if (_keys.length && isOperator(_keys[0])) { - for (const key in nested) { - nested[key] = schematype.castForQueryWrapper({ - $conditional: key, - val: nested[key], - context: ctx - }); - } - } else { - val[$cond] = schematype.castForQueryWrapper({ - $conditional: $cond, - val: nested, - context: ctx - }); - } - continue; - } - // cast(schematype.caster ? schematype.caster.schema : schema, nested, options, context); - } else { - val[$cond] = schematype.castForQueryWrapper({ - $conditional: $cond, - val: nested, - context: ctx - }); - } - } - - return val; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/castUpdate.js b/node_modules/mongoose/lib/helpers/query/castUpdate.js deleted file mode 100644 index 327d9d2..0000000 --- a/node_modules/mongoose/lib/helpers/query/castUpdate.js +++ /dev/null @@ -1,529 +0,0 @@ -'use strict'; - -const CastError = require('../../error/cast'); -const MongooseError = require('../../error/mongooseError'); -const StrictModeError = require('../../error/strict'); -const ValidationError = require('../../error/validation'); -const castNumber = require('../../cast/number'); -const cast = require('../../cast'); -const getEmbeddedDiscriminatorPath = require('./getEmbeddedDiscriminatorPath'); -const handleImmutable = require('./handleImmutable'); -const moveImmutableProperties = require('../update/moveImmutableProperties'); -const schemaMixedSymbol = require('../../schema/symbols').schemaMixedSymbol; -const utils = require('../../utils'); - -/*! - * Casts an update op based on the given schema - * - * @param {Schema} schema - * @param {Object} obj - * @param {Object} options - * @param {Boolean} [options.overwrite] defaults to false - * @param {Boolean|String} [options.strict] defaults to true - * @param {Query} context passed to setters - * @return {Boolean} true iff the update is non-empty - */ - -module.exports = function castUpdate(schema, obj, options, context, filter) { - if (obj == null) { - return undefined; - } - options = options || {}; - - // Update pipeline - if (Array.isArray(obj)) { - const len = obj.length; - for (let i = 0; i < len; ++i) { - const ops = Object.keys(obj[i]); - for (const op of ops) { - obj[i][op] = castPipelineOperator(op, obj[i][op]); - } - } - return obj; - } - - if (options.upsert) { - moveImmutableProperties(schema, obj, context); - } - - const ops = Object.keys(obj); - let i = ops.length; - const ret = {}; - let val; - let hasDollarKey = false; - const overwrite = options.overwrite; - - filter = filter || {}; - - while (i--) { - const op = ops[i]; - // if overwrite is set, don't do any of the special $set stuff - if (op[0] !== '$' && !overwrite) { - // fix up $set sugar - if (!ret.$set) { - if (obj.$set) { - ret.$set = obj.$set; - } else { - ret.$set = {}; - } - } - ret.$set[op] = obj[op]; - ops.splice(i, 1); - if (!~ops.indexOf('$set')) ops.push('$set'); - } else if (op === '$set') { - if (!ret.$set) { - ret[op] = obj[op]; - } - } else { - ret[op] = obj[op]; - } - } - - // cast each value - i = ops.length; - - while (i--) { - const op = ops[i]; - val = ret[op]; - hasDollarKey = hasDollarKey || op.startsWith('$'); - - if (val && - typeof val === 'object' && - !Buffer.isBuffer(val) && - (!overwrite || hasDollarKey)) { - walkUpdatePath(schema, val, op, options, context, filter); - } else if (overwrite && ret && typeof ret === 'object') { - walkUpdatePath(schema, ret, '$set', options, context, filter); - } else { - const msg = 'Invalid atomic update value for ' + op + '. ' - + 'Expected an object, received ' + typeof val; - throw new Error(msg); - } - - if (op.startsWith('$') && utils.isEmptyObject(val)) { - delete ret[op]; - } - } - - return ret; -}; - -/*! - * ignore - */ - -function castPipelineOperator(op, val) { - if (op === '$unset') { - if (!Array.isArray(val) || val.find(v => typeof v !== 'string')) { - throw new MongooseError('Invalid $unset in pipeline, must be ' + - 'an array of strings'); - } - return val; - } - if (op === '$project') { - if (val == null || typeof val !== 'object') { - throw new MongooseError('Invalid $project in pipeline, must be an object'); - } - return val; - } - if (op === '$addFields' || op === '$set') { - if (val == null || typeof val !== 'object') { - throw new MongooseError('Invalid ' + op + ' in pipeline, must be an object'); - } - return val; - } else if (op === '$replaceRoot' || op === '$replaceWith') { - if (val == null || typeof val !== 'object') { - throw new MongooseError('Invalid ' + op + ' in pipeline, must be an object'); - } - return val; - } - - throw new MongooseError('Invalid update pipeline operator: "' + op + '"'); -} - -/*! - * Walk each path of obj and cast its values - * according to its schema. - * - * @param {Schema} schema - * @param {Object} obj - part of a query - * @param {String} op - the atomic operator ($pull, $set, etc) - * @param {Object} options - * @param {Boolean|String} [options.strict] - * @param {Boolean} [options.omitUndefined] - * @param {Query} context - * @param {String} pref - path prefix (internal only) - * @return {Bool} true if this path has keys to update - * @api private - */ - -function walkUpdatePath(schema, obj, op, options, context, filter, pref) { - const strict = options.strict; - const prefix = pref ? pref + '.' : ''; - const keys = Object.keys(obj); - let i = keys.length; - let hasKeys = false; - let schematype; - let key; - let val; - - let aggregatedError = null; - - let useNestedStrict; - if (options.useNestedStrict === undefined) { - useNestedStrict = schema.options.useNestedStrict; - } else { - useNestedStrict = options.useNestedStrict; - } - - while (i--) { - key = keys[i]; - val = obj[key]; - - // `$pull` is special because we need to cast the RHS as a query, not as - // an update. - if (op === '$pull') { - schematype = schema._getSchema(prefix + key); - if (schematype != null && schematype.schema != null) { - obj[key] = cast(schematype.schema, obj[key], options, context); - hasKeys = true; - continue; - } - } - - if (val && val.constructor.name === 'Object') { - // watch for embedded doc schemas - schematype = schema._getSchema(prefix + key); - - if (handleImmutable(schematype, strict, obj, key, prefix + key, context)) { - continue; - } - - if (schematype && schematype.caster && op in castOps) { - // embedded doc schema - if ('$each' in val) { - hasKeys = true; - try { - obj[key] = { - $each: castUpdateVal(schematype, val.$each, op, key, context, prefix + key) - }; - } catch (error) { - aggregatedError = _handleCastError(error, context, key, aggregatedError); - } - - if (val.$slice != null) { - obj[key].$slice = val.$slice | 0; - } - - if (val.$sort) { - obj[key].$sort = val.$sort; - } - - if (val.$position != null) { - obj[key].$position = castNumber(val.$position); - } - } else { - if (schematype != null && schematype.$isSingleNested) { - // Special case to make sure `strict` bubbles down correctly to - // single nested re: gh-8735 - let _strict = strict; - if (useNestedStrict !== false && schematype.schema.options.hasOwnProperty('strict')) { - _strict = schematype.schema.options.strict; - } else if (useNestedStrict === false) { - _strict = schema.options.strict; - } - try { - obj[key] = schematype.castForQuery(val, context, { strict: _strict }); - } catch (error) { - aggregatedError = _handleCastError(error, context, key, aggregatedError); - } - } else { - try { - obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); - } catch (error) { - aggregatedError = _handleCastError(error, context, key, aggregatedError); - } - } - - if (options.omitUndefined && obj[key] === void 0) { - delete obj[key]; - continue; - } - - hasKeys = true; - } - } else if ((op === '$currentDate') || (op in castOps && schematype)) { - // $currentDate can take an object - try { - obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); - } catch (error) { - aggregatedError = _handleCastError(error, context, key, aggregatedError); - } - - if (options.omitUndefined && obj[key] === void 0) { - delete obj[key]; - continue; - } - - hasKeys = true; - } else { - const pathToCheck = (prefix + key); - const v = schema._getPathType(pathToCheck); - let _strict = strict; - if (useNestedStrict && - v && - v.schema && - 'strict' in v.schema.options) { - _strict = v.schema.options.strict; - } - - if (v.pathType === 'undefined') { - if (_strict === 'throw') { - throw new StrictModeError(pathToCheck); - } else if (_strict) { - delete obj[key]; - continue; - } - } - - // gh-2314 - // we should be able to set a schema-less field - // to an empty object literal - hasKeys |= walkUpdatePath(schema, val, op, options, context, filter, prefix + key) || - (utils.isObject(val) && Object.keys(val).length === 0); - } - } else { - const checkPath = (key === '$each' || key === '$or' || key === '$and' || key === '$in') ? - pref : prefix + key; - schematype = schema._getSchema(checkPath); - - // You can use `$setOnInsert` with immutable keys - if (op !== '$setOnInsert' && - handleImmutable(schematype, strict, obj, key, prefix + key, context)) { - continue; - } - - let pathDetails = schema._getPathType(checkPath); - - // If no schema type, check for embedded discriminators because the - // filter or update may imply an embedded discriminator type. See #8378 - if (schematype == null) { - const _res = getEmbeddedDiscriminatorPath(schema, obj, filter, checkPath); - if (_res.schematype != null) { - schematype = _res.schematype; - pathDetails = _res.type; - } - } - - let isStrict = strict; - if (useNestedStrict && - pathDetails && - pathDetails.schema && - 'strict' in pathDetails.schema.options) { - isStrict = pathDetails.schema.options.strict; - } - - const skip = isStrict && - !schematype && - !/real|nested/.test(pathDetails.pathType); - - if (skip) { - // Even if strict is `throw`, avoid throwing an error because of - // virtuals because of #6731 - if (isStrict === 'throw' && schema.virtuals[checkPath] == null) { - throw new StrictModeError(prefix + key); - } else { - delete obj[key]; - } - } else { - // gh-1845 temporary fix: ignore $rename. See gh-3027 for tracking - // improving this. - if (op === '$rename') { - hasKeys = true; - continue; - } - - try { - obj[key] = castUpdateVal(schematype, val, op, key, context, prefix + key); - } catch (error) { - aggregatedError = _handleCastError(error, context, key, aggregatedError); - } - - if (Array.isArray(obj[key]) && (op === '$addToSet' || op === '$push') && key !== '$each') { - if (schematype && schematype.caster && !schematype.caster.$isMongooseArray) { - obj[key] = { $each: obj[key] }; - } - } - - if (options.omitUndefined && obj[key] === void 0) { - delete obj[key]; - continue; - } - - hasKeys = true; - } - } - } - - if (aggregatedError != null) { - throw aggregatedError; - } - - return hasKeys; -} - -/*! - * ignore - */ - -function _handleCastError(error, query, key, aggregatedError) { - if (typeof query !== 'object' || !query.options.multipleCastError) { - throw error; - } - aggregatedError = aggregatedError || new ValidationError(); - aggregatedError.addError(key, error); - return aggregatedError; -} - -/*! - * These operators should be cast to numbers instead - * of their path schema type. - */ - -const numberOps = { - $pop: 1, - $inc: 1 -}; - -/*! - * These ops require no casting because the RHS doesn't do anything. - */ - -const noCastOps = { - $unset: 1 -}; - -/*! - * These operators require casting docs - * to real Documents for Update operations. - */ - -const castOps = { - $push: 1, - $addToSet: 1, - $set: 1, - $setOnInsert: 1 -}; - -/*! - * ignore - */ - -const overwriteOps = { - $set: 1, - $setOnInsert: 1 -}; - -/*! - * Casts `val` according to `schema` and atomic `op`. - * - * @param {SchemaType} schema - * @param {Object} val - * @param {String} op - the atomic operator ($pull, $set, etc) - * @param {String} $conditional - * @param {Query} context - * @api private - */ - -function castUpdateVal(schema, val, op, $conditional, context, path) { - if (!schema) { - // non-existing schema path - if (op in numberOps) { - try { - return castNumber(val); - } catch (err) { - throw new CastError('number', val, path); - } - } - return val; - } - - const cond = schema.caster && op in castOps && - (utils.isObject(val) || Array.isArray(val)); - if (cond && !overwriteOps[op]) { - // Cast values for ops that add data to MongoDB. - // Ensures embedded documents get ObjectIds etc. - let schemaArrayDepth = 0; - let cur = schema; - while (cur.$isMongooseArray) { - ++schemaArrayDepth; - cur = cur.caster; - } - let arrayDepth = 0; - let _val = val; - while (Array.isArray(_val)) { - ++arrayDepth; - _val = _val[0]; - } - - const additionalNesting = schemaArrayDepth - arrayDepth; - while (arrayDepth < schemaArrayDepth) { - val = [val]; - ++arrayDepth; - } - - let tmp = schema.applySetters(Array.isArray(val) ? val : [val], context); - - for (let i = 0; i < additionalNesting; ++i) { - tmp = tmp[0]; - } - return tmp; - } - - if (op in noCastOps) { - return val; - } - if (op in numberOps) { - // Null and undefined not allowed for $pop, $inc - if (val == null) { - throw new CastError('number', val, schema.path); - } - if (op === '$inc') { - // Support `$inc` with long, int32, etc. (gh-4283) - return schema.castForQueryWrapper({ - val: val, - context: context - }); - } - try { - return castNumber(val); - } catch (error) { - throw new CastError('number', val, schema.path); - } - } - if (op === '$currentDate') { - if (typeof val === 'object') { - return { $type: val.$type }; - } - return Boolean(val); - } - - if (/^\$/.test($conditional)) { - return schema.castForQueryWrapper({ - $conditional: $conditional, - val: val, - context: context - }); - } - - if (overwriteOps[op]) { - return schema.castForQueryWrapper({ - val: val, - context: context, - $skipQueryCastForUpdate: val != null && schema.$isMongooseArray && schema.$fullPath != null && !schema.$fullPath.match(/\d+$/), - $applySetters: schema[schemaMixedSymbol] != null - }); - } - - return schema.castForQueryWrapper({ val: val, context: context }); -} diff --git a/node_modules/mongoose/lib/helpers/query/completeMany.js b/node_modules/mongoose/lib/helpers/query/completeMany.js deleted file mode 100644 index aabe596..0000000 --- a/node_modules/mongoose/lib/helpers/query/completeMany.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -const helpers = require('../../queryhelpers'); - -module.exports = completeMany; - -/*! - * Given a model and an array of docs, hydrates all the docs to be instances - * of the model. Used to initialize docs returned from the db from `find()` - * - * @param {Model} model - * @param {Array} docs - * @param {Object} fields the projection used, including `select` from schemas - * @param {Object} userProvidedFields the user-specified projection - * @param {Object} opts - * @param {Array} [opts.populated] - * @param {ClientSession} [opts.session] - * @param {Function} callback - */ - -function completeMany(model, docs, fields, userProvidedFields, opts, callback) { - const arr = []; - let count = docs.length; - const len = count; - let error = null; - - function init(_error) { - if (_error != null) { - error = error || _error; - } - if (error != null) { - --count || process.nextTick(() => callback(error)); - return; - } - --count || process.nextTick(() => callback(error, arr)); - } - - for (let i = 0; i < len; ++i) { - arr[i] = helpers.createModel(model, docs[i], fields, userProvidedFields); - try { - arr[i].init(docs[i], opts, init); - } catch (error) { - init(error); - } - arr[i].$session(opts.session); - } -} diff --git a/node_modules/mongoose/lib/helpers/query/getEmbeddedDiscriminatorPath.js b/node_modules/mongoose/lib/helpers/query/getEmbeddedDiscriminatorPath.js deleted file mode 100644 index ff297ac..0000000 --- a/node_modules/mongoose/lib/helpers/query/getEmbeddedDiscriminatorPath.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -const cleanPositionalOperators = require('../schema/cleanPositionalOperators'); -const get = require('../get'); - -/*! - * Like `schema.path()`, except with a document, because impossible to - * determine path type without knowing the embedded discriminator key. - */ - -module.exports = function getEmbeddedDiscriminatorPath(schema, update, filter, path) { - const parts = path.split('.'); - let schematype = null; - let type = 'adhocOrUndefined'; - - filter = filter || {}; - update = update || {}; - - for (let i = 0; i < parts.length; ++i) { - const subpath = cleanPositionalOperators(parts.slice(0, i + 1).join('.')); - schematype = schema.path(subpath); - if (schematype == null) { - continue; - } - - type = schema.pathType(subpath); - if ((schematype.$isSingleNested || schematype.$isMongooseDocumentArrayElement) && - schematype.schema.discriminators != null) { - const discriminators = schematype.schema.discriminators; - const key = get(schematype, 'schema.options.discriminatorKey'); - const discriminatorValuePath = subpath + '.' + key; - const discriminatorFilterPath = - discriminatorValuePath.replace(/\.\d+\./, '.'); - let discriminatorKey = null; - - if (discriminatorValuePath in filter) { - discriminatorKey = filter[discriminatorValuePath]; - } - if (discriminatorFilterPath in filter) { - discriminatorKey = filter[discriminatorFilterPath]; - } - const wrapperPath = subpath.replace(/\.\d+$/, ''); - if (schematype.$isMongooseDocumentArrayElement && - get(filter[wrapperPath], '$elemMatch.' + key) != null) { - discriminatorKey = filter[wrapperPath].$elemMatch[key]; - } - - if (discriminatorValuePath in update) { - discriminatorKey = update[discriminatorValuePath]; - } - - if (discriminatorKey == null || discriminators[discriminatorKey] == null) { - continue; - } - const rest = parts.slice(i + 1).join('.'); - schematype = discriminators[discriminatorKey].path(rest); - if (schematype != null) { - type = discriminators[discriminatorKey]._getPathType(rest); - break; - } - } - } - - return { type: type, schematype: schematype }; -}; diff --git a/node_modules/mongoose/lib/helpers/query/handleImmutable.js b/node_modules/mongoose/lib/helpers/query/handleImmutable.js deleted file mode 100644 index 22adb3c..0000000 --- a/node_modules/mongoose/lib/helpers/query/handleImmutable.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -const StrictModeError = require('../../error/strict'); - -module.exports = function handleImmutable(schematype, strict, obj, key, fullPath, ctx) { - if (schematype == null || !schematype.options || !schematype.options.immutable) { - return false; - } - let immutable = schematype.options.immutable; - - if (typeof immutable === 'function') { - immutable = immutable.call(ctx, ctx); - } - if (!immutable) { - return false; - } - - if (strict === false) { - return false; - } - if (strict === 'throw') { - throw new StrictModeError(null, - `Field ${fullPath} is immutable and strict = 'throw'`); - } - - delete obj[key]; - return true; -}; diff --git a/node_modules/mongoose/lib/helpers/query/hasDollarKeys.js b/node_modules/mongoose/lib/helpers/query/hasDollarKeys.js deleted file mode 100644 index 958e1c9..0000000 --- a/node_modules/mongoose/lib/helpers/query/hasDollarKeys.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function(obj) { - if (obj == null) { - return false; - } - const keys = Object.keys(obj); - const len = keys.length; - for (let i = 0; i < len; ++i) { - if (keys[i].startsWith('$')) { - return true; - } - } - return false; -}; diff --git a/node_modules/mongoose/lib/helpers/query/isOperator.js b/node_modules/mongoose/lib/helpers/query/isOperator.js deleted file mode 100644 index 3b98139..0000000 --- a/node_modules/mongoose/lib/helpers/query/isOperator.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -const specialKeys = new Set([ - '$ref', - '$id', - '$db' -]); - -module.exports = function isOperator(path) { - return path.startsWith('$') && !specialKeys.has(path); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/query/selectPopulatedFields.js b/node_modules/mongoose/lib/helpers/query/selectPopulatedFields.js deleted file mode 100644 index 0653f18..0000000 --- a/node_modules/mongoose/lib/helpers/query/selectPopulatedFields.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function selectPopulatedFields(query) { - const opts = query._mongooseOptions; - - if (opts.populate != null) { - const paths = Object.keys(opts.populate); - const userProvidedFields = query._userProvidedFields || {}; - if (query.selectedInclusively()) { - for (const path of paths) { - if (!isPathInFields(userProvidedFields, path)) { - query.select(path); - } else if (userProvidedFields[path] === 0) { - delete query._fields[path]; - } - } - } else if (query.selectedExclusively()) { - for (const path of paths) { - if (userProvidedFields[path] == null) { - delete query._fields[path]; - } - } - } - } -}; - -/*! - * ignore - */ - -function isPathInFields(userProvidedFields, path) { - const pieces = path.split('.'); - const len = pieces.length; - let cur = pieces[0]; - for (let i = 1; i < len; ++i) { - if (userProvidedFields[cur] != null) { - return true; - } - cur += '.' + pieces[i]; - } - return userProvidedFields[cur] != null; -} diff --git a/node_modules/mongoose/lib/helpers/query/wrapThunk.js b/node_modules/mongoose/lib/helpers/query/wrapThunk.js deleted file mode 100644 index 0005c33..0000000 --- a/node_modules/mongoose/lib/helpers/query/wrapThunk.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -/*! - * A query thunk is the function responsible for sending the query to MongoDB, - * like `Query#_findOne()` or `Query#_execUpdate()`. The `Query#exec()` function - * calls a thunk. The term "thunk" here is the traditional Node.js definition: - * a function that takes exactly 1 parameter, a callback. - * - * This function defines common behavior for all query thunks. - */ - -module.exports = function wrapThunk(fn) { - return function _wrappedThunk(cb) { - ++this._executionCount; - - fn.call(this, cb); - }; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/addAutoId.js b/node_modules/mongoose/lib/helpers/schema/addAutoId.js deleted file mode 100644 index 11a1f23..0000000 --- a/node_modules/mongoose/lib/helpers/schema/addAutoId.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -module.exports = function addAutoId(schema) { - const _obj = { _id: { auto: true } }; - _obj._id[schema.options.typeKey] = 'ObjectId'; - schema.add(_obj); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/applyPlugins.js b/node_modules/mongoose/lib/helpers/schema/applyPlugins.js deleted file mode 100644 index f1daf40..0000000 --- a/node_modules/mongoose/lib/helpers/schema/applyPlugins.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -module.exports = function applyPlugins(schema, plugins, options, cacheKey) { - if (schema[cacheKey]) { - return; - } - schema[cacheKey] = true; - - if (!options || !options.skipTopLevel) { - for (const plugin of plugins) { - schema.plugin(plugin[0], plugin[1]); - } - } - - options = Object.assign({}, options); - delete options.skipTopLevel; - - if (options.applyPluginsToChildSchemas !== false) { - for (const path of Object.keys(schema.paths)) { - const type = schema.paths[path]; - if (type.schema != null) { - applyPlugins(type.schema, plugins, options, cacheKey); - - // Recompile schema because plugins may have changed it, see gh-7572 - type.caster.prototype.$__setSchema(type.schema); - } - } - } - - const discriminators = schema.discriminators; - if (discriminators == null) { - return; - } - - const applyPluginsToDiscriminators = options.applyPluginsToDiscriminators; - - const keys = Object.keys(discriminators); - for (const discriminatorKey of keys) { - const discriminatorSchema = discriminators[discriminatorKey]; - - applyPlugins(discriminatorSchema, plugins, - { skipTopLevel: !applyPluginsToDiscriminators }, cacheKey); - } -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/applyWriteConcern.js b/node_modules/mongoose/lib/helpers/schema/applyWriteConcern.js deleted file mode 100644 index 168156d..0000000 --- a/node_modules/mongoose/lib/helpers/schema/applyWriteConcern.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -const get = require('../get'); - -module.exports = function applyWriteConcern(schema, options) { - const writeConcern = get(schema, 'options.writeConcern', {}); - if (!('w' in options) && writeConcern.w != null) { - options.w = writeConcern.w; - } - if (!('j' in options) && writeConcern.j != null) { - options.j = writeConcern.j; - } - if (!('wtimeout' in options) && writeConcern.wtimeout != null) { - options.wtimeout = writeConcern.wtimeout; - } -}; diff --git a/node_modules/mongoose/lib/helpers/schema/cleanPositionalOperators.js b/node_modules/mongoose/lib/helpers/schema/cleanPositionalOperators.js deleted file mode 100644 index b467be4..0000000 --- a/node_modules/mongoose/lib/helpers/schema/cleanPositionalOperators.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -/** - * For consistency's sake, we replace positional operator `$` and array filters - * `$[]` and `$[foo]` with `0` when looking up schema paths. - */ - -module.exports = function cleanPositionalOperators(path) { - return path. - replace(/\.\$(\[[^\]]*\])?\./g, '.0.'). - replace(/\.(\[[^\]]*\])?\$$/g, '.0'); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/getIndexes.js b/node_modules/mongoose/lib/helpers/schema/getIndexes.js deleted file mode 100644 index ce4286b..0000000 --- a/node_modules/mongoose/lib/helpers/schema/getIndexes.js +++ /dev/null @@ -1,141 +0,0 @@ -'use strict'; - -const get = require('../get'); -const helperIsObject = require('../isObject'); - -/*! - * Gather all indexes defined in the schema, including single nested, - * document arrays, and embedded discriminators. - */ - -module.exports = function getIndexes(schema) { - let indexes = []; - const schemaStack = new WeakMap(); - const indexTypes = schema.constructor.indexTypes; - const indexByName = new Map(); - - collectIndexes(schema); - return indexes; - - function collectIndexes(schema, prefix, baseSchema) { - // Ignore infinitely nested schemas, if we've already seen this schema - // along this path there must be a cycle - if (schemaStack.has(schema)) { - return; - } - schemaStack.set(schema, true); - - prefix = prefix || ''; - const keys = Object.keys(schema.paths); - - for (const key of keys) { - const path = schema.paths[key]; - if (baseSchema != null && baseSchema.paths[key]) { - // If looking at an embedded discriminator schema, don't look at paths - // that the - continue; - } - - if (path.$isMongooseDocumentArray || path.$isSingleNested) { - if (get(path, 'options.excludeIndexes') !== true && - get(path, 'schemaOptions.excludeIndexes') !== true && - get(path, 'schema.options.excludeIndexes') !== true) { - collectIndexes(path.schema, prefix + key + '.'); - } - - if (path.schema.discriminators != null) { - const discriminators = path.schema.discriminators; - const discriminatorKeys = Object.keys(discriminators); - for (const discriminatorKey of discriminatorKeys) { - collectIndexes(discriminators[discriminatorKey], - prefix + key + '.', path.schema); - } - } - - // Retained to minimize risk of backwards breaking changes due to - // gh-6113 - if (path.$isMongooseDocumentArray) { - continue; - } - } - - const index = path._index || (path.caster && path.caster._index); - - if (index !== false && index !== null && index !== undefined) { - const field = {}; - const isObject = helperIsObject(index); - const options = isObject ? index : {}; - const type = typeof index === 'string' ? index : - isObject ? index.type : - false; - - if (type && indexTypes.indexOf(type) !== -1) { - field[prefix + key] = type; - } else if (options.text) { - field[prefix + key] = 'text'; - delete options.text; - } else { - const isDescendingIndex = Number(index) === -1; - field[prefix + key] = isDescendingIndex ? -1 : 1; - } - - delete options.type; - if (!('background' in options)) { - options.background = true; - } - - const indexName = options && options.name; - if (typeof indexName === 'string') { - if (indexByName.has(indexName)) { - Object.assign(indexByName.get(indexName), field); - } else { - indexes.push([field, options]); - indexByName.set(indexName, field); - } - } else { - indexes.push([field, options]); - indexByName.set(indexName, field); - } - } - } - - schemaStack.delete(schema); - - if (prefix) { - fixSubIndexPaths(schema, prefix); - } else { - schema._indexes.forEach(function(index) { - if (!('background' in index[1])) { - index[1].background = true; - } - }); - indexes = indexes.concat(schema._indexes); - } - } - - /*! - * Checks for indexes added to subdocs using Schema.index(). - * These indexes need their paths prefixed properly. - * - * schema._indexes = [ [indexObj, options], [indexObj, options] ..] - */ - - function fixSubIndexPaths(schema, prefix) { - const subindexes = schema._indexes; - const len = subindexes.length; - for (let i = 0; i < len; ++i) { - const indexObj = subindexes[i][0]; - const keys = Object.keys(indexObj); - const klen = keys.length; - const newindex = {}; - - // use forward iteration, order matters - for (let j = 0; j < klen; ++j) { - const key = keys[j]; - newindex[prefix + key] = indexObj[key]; - } - - indexes.push([newindex, subindexes[i][1]]); - } - } -}; diff --git a/node_modules/mongoose/lib/helpers/schema/getPath.js b/node_modules/mongoose/lib/helpers/schema/getPath.js deleted file mode 100644 index ccbc67c..0000000 --- a/node_modules/mongoose/lib/helpers/schema/getPath.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -/*! - * Behaves like `Schema#path()`, except for it also digs into arrays without - * needing to put `.0.`, so `getPath(schema, 'docArr.elProp')` works. - */ - -module.exports = function getPath(schema, path) { - let schematype = schema.path(path); - if (schematype != null) { - return schematype; - } - - const pieces = path.split('.'); - let cur = ''; - let isArray = false; - - for (const piece of pieces) { - if (/^\d+$/.test(piece) && isArray) { - continue; - } - cur = cur.length === 0 ? piece : cur + '.' + piece; - - schematype = schema.path(cur); - if (schematype != null && schematype.schema) { - schema = schematype.schema; - cur = ''; - if (schematype.$isMongooseDocumentArray) { - isArray = true; - } - } - } - - return schematype; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/handleIdOption.js b/node_modules/mongoose/lib/helpers/schema/handleIdOption.js deleted file mode 100644 index 569bf9f..0000000 --- a/node_modules/mongoose/lib/helpers/schema/handleIdOption.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -const addAutoId = require('./addAutoId'); - -module.exports = function handleIdOption(schema, options) { - if (options == null || options._id == null) { - return schema; - } - - schema = schema.clone(); - if (!options._id) { - schema.remove('_id'); - schema.options._id = false; - } else if (!schema.paths['_id']) { - addAutoId(schema); - schema.options._id = true; - } - - return schema; -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/handleTimestampOption.js b/node_modules/mongoose/lib/helpers/schema/handleTimestampOption.js deleted file mode 100644 index 1551b7c..0000000 --- a/node_modules/mongoose/lib/helpers/schema/handleTimestampOption.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -module.exports = handleTimestampOption; - -/*! - * ignore - */ - -function handleTimestampOption(arg, prop) { - if (arg == null) { - return null; - } - - if (typeof arg === 'boolean') { - return prop; - } - if (typeof arg[prop] === 'boolean') { - return arg[prop] ? prop : null; - } - if (!(prop in arg)) { - return prop; - } - return arg[prop]; -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/schema/merge.js b/node_modules/mongoose/lib/helpers/schema/merge.js deleted file mode 100644 index d206500..0000000 --- a/node_modules/mongoose/lib/helpers/schema/merge.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -module.exports = function merge(s1, s2) { - s1.add(s2.tree || {}); - - s1.callQueue = s1.callQueue.concat(s2.callQueue); - s1.method(s2.methods); - s1.static(s2.statics); - - for (const query in s2.query) { - s1.query[query] = s2.query[query]; - } - - for (const virtual in s2.virtuals) { - s1.virtuals[virtual] = s2.virtuals[virtual].clone(); - } - - s1.s.hooks.merge(s2.s.hooks, false); -}; diff --git a/node_modules/mongoose/lib/helpers/schematype/handleImmutable.js b/node_modules/mongoose/lib/helpers/schematype/handleImmutable.js deleted file mode 100644 index 14f647a..0000000 --- a/node_modules/mongoose/lib/helpers/schematype/handleImmutable.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -const StrictModeError = require('../../error/strict'); - -/*! - * ignore - */ - -module.exports = function(schematype) { - if (schematype.$immutable) { - schematype.$immutableSetter = createImmutableSetter(schematype.path, - schematype.options.immutable); - schematype.set(schematype.$immutableSetter); - } else if (schematype.$immutableSetter) { - schematype.setters = schematype.setters. - filter(fn => fn !== schematype.$immutableSetter); - delete schematype.$immutableSetter; - } -}; - -function createImmutableSetter(path, immutable) { - return function immutableSetter(v) { - if (this == null || this.$__ == null) { - return v; - } - if (this.isNew) { - return v; - } - - const _immutable = typeof immutable === 'function' ? - immutable.call(this, this) : - immutable; - if (!_immutable) { - return v; - } - if (this.$__.strictMode === 'throw' && v !== this[path]) { - throw new StrictModeError(path, 'Path `' + path + '` is immutable ' + - 'and strict mode is set to throw.', true); - } - - return this[path]; - }; -} diff --git a/node_modules/mongoose/lib/helpers/setDefaultsOnInsert.js b/node_modules/mongoose/lib/helpers/setDefaultsOnInsert.js deleted file mode 100644 index 0545e80..0000000 --- a/node_modules/mongoose/lib/helpers/setDefaultsOnInsert.js +++ /dev/null @@ -1,120 +0,0 @@ -'use strict'; - -const modifiedPaths = require('./common').modifiedPaths; - -/** - * Applies defaults to update and findOneAndUpdate operations. - * - * @param {Object} filter - * @param {Schema} schema - * @param {Object} castedDoc - * @param {Object} options - * @method setDefaultsOnInsert - * @api private - */ - -module.exports = function(filter, schema, castedDoc, options) { - const keys = Object.keys(castedDoc || {}); - const updatedKeys = {}; - const updatedValues = {}; - const numKeys = keys.length; - const modified = {}; - - let hasDollarUpdate = false; - - options = options || {}; - - if (!options.upsert || !options.setDefaultsOnInsert) { - return castedDoc; - } - - for (let i = 0; i < numKeys; ++i) { - if (keys[i].startsWith('$')) { - modifiedPaths(castedDoc[keys[i]], '', modified); - hasDollarUpdate = true; - } - } - - if (!hasDollarUpdate) { - modifiedPaths(castedDoc, '', modified); - } - - const paths = Object.keys(filter); - const numPaths = paths.length; - for (let i = 0; i < numPaths; ++i) { - const path = paths[i]; - const condition = filter[path]; - if (condition && typeof condition === 'object') { - const conditionKeys = Object.keys(condition); - const numConditionKeys = conditionKeys.length; - let hasDollarKey = false; - for (let j = 0; j < numConditionKeys; ++j) { - if (conditionKeys[j].startsWith('$')) { - hasDollarKey = true; - break; - } - } - if (hasDollarKey) { - continue; - } - } - updatedKeys[path] = true; - modified[path] = true; - } - - if (options && options.overwrite && !hasDollarUpdate) { - // Defaults will be set later, since we're overwriting we'll cast - // the whole update to a document - return castedDoc; - } - - schema.eachPath(function(path, schemaType) { - // Skip single nested paths if underneath a map - const isUnderneathMap = schemaType.path.endsWith('.$*') || - schemaType.path.indexOf('.$*.') !== -1; - if (schemaType.$isSingleNested && !isUnderneathMap) { - // Only handle nested schemas 1-level deep to avoid infinite - // recursion re: https://github.com/mongodb-js/mongoose-autopopulate/issues/11 - schemaType.schema.eachPath(function(_path, _schemaType) { - if (_path === '_id' && _schemaType.auto) { - // Ignore _id if auto id so we don't create subdocs - return; - } - - const def = _schemaType.getDefault(null, true); - if (!isModified(modified, path + '.' + _path) && - typeof def !== 'undefined') { - castedDoc = castedDoc || {}; - castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; - castedDoc.$setOnInsert[path + '.' + _path] = def; - updatedValues[path + '.' + _path] = def; - } - }); - } else { - const def = schemaType.getDefault(null, true); - if (!isModified(modified, path) && typeof def !== 'undefined') { - castedDoc = castedDoc || {}; - castedDoc.$setOnInsert = castedDoc.$setOnInsert || {}; - castedDoc.$setOnInsert[path] = def; - updatedValues[path] = def; - } - } - }); - - return castedDoc; -}; - -function isModified(modified, path) { - if (modified[path]) { - return true; - } - const sp = path.split('.'); - let cur = sp[0]; - for (let i = 1; i < sp.length; ++i) { - if (modified[cur]) { - return true; - } - cur += '.' + sp[i]; - } - return false; -} diff --git a/node_modules/mongoose/lib/helpers/specialProperties.js b/node_modules/mongoose/lib/helpers/specialProperties.js deleted file mode 100644 index 1e1aca5..0000000 --- a/node_modules/mongoose/lib/helpers/specialProperties.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = new Set(['__proto__', 'constructor', 'prototype']); \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/symbols.js b/node_modules/mongoose/lib/helpers/symbols.js deleted file mode 100644 index 3860f23..0000000 --- a/node_modules/mongoose/lib/helpers/symbols.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -exports.arrayAtomicsSymbol = Symbol('mongoose#Array#_atomics'); -exports.arrayParentSymbol = Symbol('mongoose#Array#_parent'); -exports.arrayPathSymbol = Symbol('mongoose#Array#_path'); -exports.arraySchemaSymbol = Symbol('mongoose#Array#_schema'); -exports.documentArrayParent = Symbol('mongoose:documentArrayParent'); -exports.documentSchemaSymbol = Symbol('mongoose#Document#schema'); -exports.getSymbol = Symbol('mongoose#Document#get'); -exports.modelSymbol = Symbol('mongoose#Model'); -exports.objectIdSymbol = Symbol('mongoose#ObjectId'); -exports.populateModelSymbol = Symbol('mongoose.PopulateOptions#Model'); -exports.schemaTypeSymbol = Symbol('mongoose#schemaType'); -exports.validatorErrorSymbol = Symbol('mongoose:validatorError'); \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/topology/allServersUnknown.js b/node_modules/mongoose/lib/helpers/topology/allServersUnknown.js deleted file mode 100644 index f85b727..0000000 --- a/node_modules/mongoose/lib/helpers/topology/allServersUnknown.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -module.exports = function allServersUnknown(topologyDescription) { - if (topologyDescription == null || - topologyDescription.constructor.name !== 'TopologyDescription') { - return false; - } - - return Array.from(topologyDescription.servers.values()). - every(server => server.type === 'Unknown'); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/topology/isAtlas.js b/node_modules/mongoose/lib/helpers/topology/isAtlas.js deleted file mode 100644 index b7647fd..0000000 --- a/node_modules/mongoose/lib/helpers/topology/isAtlas.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -module.exports = function isAtlas(topologyDescription) { - if (topologyDescription == null || - topologyDescription.constructor.name !== 'TopologyDescription') { - return false; - } - - return Array.from(topologyDescription.servers.keys()). - every(host => host.endsWith('.mongodb.net:27017')); -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/update/applyTimestampsToChildren.js b/node_modules/mongoose/lib/helpers/update/applyTimestampsToChildren.js deleted file mode 100644 index 1b37617..0000000 --- a/node_modules/mongoose/lib/helpers/update/applyTimestampsToChildren.js +++ /dev/null @@ -1,185 +0,0 @@ -'use strict'; - -const cleanPositionalOperators = require('../schema/cleanPositionalOperators'); -const handleTimestampOption = require('../schema/handleTimestampOption'); - -module.exports = applyTimestampsToChildren; - -/*! - * ignore - */ - -function applyTimestampsToChildren(now, update, schema) { - if (update == null) { - return; - } - - const keys = Object.keys(update); - let key; - let createdAt; - let updatedAt; - let timestamps; - let path; - - const hasDollarKey = keys.length && keys[0].startsWith('$'); - - if (hasDollarKey) { - if (update.$push) { - for (key in update.$push) { - const $path = schema.path(key); - if (update.$push[key] && - $path && - $path.$isMongooseDocumentArray && - $path.schema.options.timestamps) { - timestamps = $path.schema.options.timestamps; - createdAt = handleTimestampOption(timestamps, 'createdAt'); - updatedAt = handleTimestampOption(timestamps, 'updatedAt'); - if (update.$push[key].$each) { - update.$push[key].$each.forEach(function(subdoc) { - if (updatedAt != null) { - subdoc[updatedAt] = now; - } - if (createdAt != null) { - subdoc[createdAt] = now; - } - }); - } else { - if (updatedAt != null) { - update.$push[key][updatedAt] = now; - } - if (createdAt != null) { - update.$push[key][createdAt] = now; - } - } - } - } - } - if (update.$set != null) { - const keys = Object.keys(update.$set); - for (key of keys) { - // Replace positional operator `$` and array filters `$[]` and `$[.*]` - const keyToSearch = cleanPositionalOperators(key); - path = schema.path(keyToSearch); - if (!path) { - continue; - } - - const parentSchemaTypes = []; - const pieces = keyToSearch.split('.'); - for (let i = pieces.length - 1; i > 0; --i) { - const s = schema.path(pieces.slice(0, i).join('.')); - if (s != null && - (s.$isMongooseDocumentArray || s.$isSingleNested)) { - parentSchemaTypes.push({ parentPath: key.split('.').slice(0, i).join('.'), parentSchemaType: s }); - } - } - - if (Array.isArray(update.$set[key]) && path.$isMongooseDocumentArray) { - applyTimestampsToDocumentArray(update.$set[key], path, now); - } else if (update.$set[key] && path.$isSingleNested) { - applyTimestampsToSingleNested(update.$set[key], path, now); - } else if (parentSchemaTypes.length > 0) { - for (const item of parentSchemaTypes) { - const parentPath = item.parentPath; - const parentSchemaType = item.parentSchemaType; - timestamps = parentSchemaType.schema.options.timestamps; - createdAt = handleTimestampOption(timestamps, 'createdAt'); - updatedAt = handleTimestampOption(timestamps, 'updatedAt'); - - if (!timestamps || updatedAt == null) { - continue; - } - - if (parentSchemaType.$isSingleNested) { - // Single nested is easy - update.$set[parentPath + '.' + updatedAt] = now; - continue; - } - - if (parentSchemaType.$isMongooseDocumentArray) { - let childPath = key.substr(parentPath.length + 1); - - if (/^\d+$/.test(childPath)) { - update.$set[parentPath + '.' + childPath][updatedAt] = now; - continue; - } - - const firstDot = childPath.indexOf('.'); - childPath = firstDot !== -1 ? childPath.substr(0, firstDot) : childPath; - - update.$set[parentPath + '.' + childPath + '.' + updatedAt] = now; - } - } - } else if (path.schema != null && path.schema != schema && update.$set[key]) { - timestamps = path.schema.options.timestamps; - createdAt = handleTimestampOption(timestamps, 'createdAt'); - updatedAt = handleTimestampOption(timestamps, 'updatedAt'); - - if (!timestamps) { - continue; - } - - if (updatedAt != null) { - update.$set[key][updatedAt] = now; - } - if (createdAt != null) { - update.$set[key][createdAt] = now; - } - } - } - } - } else { - const keys = Object.keys(update).filter(key => !key.startsWith('$')); - for (key of keys) { - // Replace positional operator `$` and array filters `$[]` and `$[.*]` - const keyToSearch = cleanPositionalOperators(key); - path = schema.path(keyToSearch); - if (!path) { - continue; - } - - if (Array.isArray(update[key]) && path.$isMongooseDocumentArray) { - applyTimestampsToDocumentArray(update[key], path, now); - } else if (update[key] != null && path.$isSingleNested) { - applyTimestampsToSingleNested(update[key], path, now); - } - } - } -} - -function applyTimestampsToDocumentArray(arr, schematype, now) { - const timestamps = schematype.schema.options.timestamps; - - if (!timestamps) { - return; - } - - const len = arr.length; - - const createdAt = handleTimestampOption(timestamps, 'createdAt'); - const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); - for (let i = 0; i < len; ++i) { - if (updatedAt != null) { - arr[i][updatedAt] = now; - } - if (createdAt != null) { - arr[i][createdAt] = now; - } - } -} - -function applyTimestampsToSingleNested(subdoc, schematype, now) { - const timestamps = schematype.schema.options.timestamps; - if (!timestamps) { - return; - } - - const createdAt = handleTimestampOption(timestamps, 'createdAt'); - const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); - if (updatedAt != null) { - subdoc[updatedAt] = now; - } - if (createdAt != null) { - subdoc[createdAt] = now; - } -} diff --git a/node_modules/mongoose/lib/helpers/update/applyTimestampsToUpdate.js b/node_modules/mongoose/lib/helpers/update/applyTimestampsToUpdate.js deleted file mode 100644 index 7318232..0000000 --- a/node_modules/mongoose/lib/helpers/update/applyTimestampsToUpdate.js +++ /dev/null @@ -1,78 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -const get = require('../get'); - -module.exports = applyTimestampsToUpdate; - -/*! - * ignore - */ - -function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, options) { - const updates = currentUpdate; - let _updates = updates; - const overwrite = get(options, 'overwrite', false); - const timestamps = get(options, 'timestamps', true); - - // Support skipping timestamps at the query level, see gh-6980 - if (!timestamps || updates == null) { - return currentUpdate; - } - - const skipCreatedAt = timestamps != null && timestamps.createdAt === false; - const skipUpdatedAt = timestamps != null && timestamps.updatedAt === false; - - if (overwrite) { - if (currentUpdate && currentUpdate.$set) { - currentUpdate = currentUpdate.$set; - updates.$set = {}; - _updates = updates.$set; - } - if (!skipUpdatedAt && updatedAt && !currentUpdate[updatedAt]) { - _updates[updatedAt] = now; - } - if (!skipCreatedAt && createdAt && !currentUpdate[createdAt]) { - _updates[createdAt] = now; - } - return updates; - } - currentUpdate = currentUpdate || {}; - - if (Array.isArray(updates)) { - // Update with aggregation pipeline - updates.push({ $set: { updatedAt: now } }); - - return updates; - } - - updates.$set = updates.$set || {}; - if (!skipUpdatedAt && updatedAt && - (!currentUpdate.$currentDate || !currentUpdate.$currentDate[updatedAt])) { - updates.$set[updatedAt] = now; - if (updates.hasOwnProperty(updatedAt)) { - delete updates[updatedAt]; - } - } - - if (!skipCreatedAt && createdAt) { - if (currentUpdate[createdAt]) { - delete currentUpdate[createdAt]; - } - if (currentUpdate.$set && currentUpdate.$set[createdAt]) { - delete currentUpdate.$set[createdAt]; - } - - updates.$setOnInsert = updates.$setOnInsert || {}; - updates.$setOnInsert[createdAt] = now; - } - - if (Object.keys(updates.$set).length === 0) { - delete updates.$set; - } - - return updates; -} diff --git a/node_modules/mongoose/lib/helpers/update/castArrayFilters.js b/node_modules/mongoose/lib/helpers/update/castArrayFilters.js deleted file mode 100644 index 471fda3..0000000 --- a/node_modules/mongoose/lib/helpers/update/castArrayFilters.js +++ /dev/null @@ -1,77 +0,0 @@ -'use strict'; - -const castFilterPath = require('../query/castFilterPath'); -const cleanPositionalOperators = require('../schema/cleanPositionalOperators'); -const getPath = require('../schema/getPath'); -const modifiedPaths = require('./modifiedPaths'); - -module.exports = function castArrayFilters(query) { - const arrayFilters = query.options.arrayFilters; - if (!Array.isArray(arrayFilters)) { - return; - } - - const update = query.getUpdate(); - const schema = query.schema; - const strictQuery = schema.options.strictQuery; - - const updatedPaths = modifiedPaths(update); - - const updatedPathsByFilter = Object.keys(updatedPaths).reduce((cur, path) => { - const matches = path.match(/\$\[[^\]]+\]/g); - if (matches == null) { - return cur; - } - for (const match of matches) { - const firstMatch = path.indexOf(match); - if (firstMatch !== path.lastIndexOf(match)) { - throw new Error(`Path '${path}' contains the same array filter multiple times`); - } - cur[match.substring(2, match.length - 1)] = path. - substr(0, firstMatch - 1). - replace(/\$\[[^\]]+\]/g, '0'); - } - return cur; - }, {}); - - for (const filter of arrayFilters) { - if (filter == null) { - throw new Error(`Got null array filter in ${arrayFilters}`); - } - const firstKey = Object.keys(filter)[0]; - - if (filter[firstKey] == null) { - continue; - } - - const dot = firstKey.indexOf('.'); - let filterPath = dot === -1 ? - updatedPathsByFilter[firstKey] + '.0' : - updatedPathsByFilter[firstKey.substr(0, dot)] + '.0' + firstKey.substr(dot); - - if (filterPath == null) { - throw new Error(`Filter path not found for ${firstKey}`); - } - - // If there are multiple array filters in the path being updated, make sure - // to replace them so we can get the schema path. - filterPath = cleanPositionalOperators(filterPath); - - const schematype = getPath(schema, filterPath); - if (schematype == null) { - if (!strictQuery) { - return; - } - // For now, treat `strictQuery = true` and `strictQuery = 'throw'` as - // equivalent for casting array filters. `strictQuery = true` doesn't - // quite work in this context because we never want to silently strip out - // array filters, even if the path isn't in the schema. - throw new Error(`Could not find path "${filterPath}" in schema`); - } - if (typeof filter[firstKey] === 'object') { - filter[firstKey] = castFilterPath(query, schematype, filter[firstKey]); - } else { - filter[firstKey] = schematype.castForQuery(filter[firstKey]); - } - } -}; \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/update/modifiedPaths.js b/node_modules/mongoose/lib/helpers/update/modifiedPaths.js deleted file mode 100644 index 9cb567d..0000000 --- a/node_modules/mongoose/lib/helpers/update/modifiedPaths.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -const _modifiedPaths = require('../common').modifiedPaths; - -/** - * Given an update document with potential update operators (`$set`, etc.) - * returns an object whose keys are the directly modified paths. - * - * If there are any top-level keys that don't start with `$`, we assume those - * will get wrapped in a `$set`. The Mongoose Query is responsible for wrapping - * top-level keys in `$set`. - * - * @param {Object} update - * @return {Object} modified - */ - -module.exports = function modifiedPaths(update) { - const keys = Object.keys(update); - const res = {}; - - const withoutDollarKeys = {}; - for (const key of keys) { - if (key.startsWith('$')) { - _modifiedPaths(update[key], '', res); - continue; - } - withoutDollarKeys[key] = update[key]; - } - - _modifiedPaths(withoutDollarKeys, '', res); - - return res; -}; diff --git a/node_modules/mongoose/lib/helpers/update/moveImmutableProperties.js b/node_modules/mongoose/lib/helpers/update/moveImmutableProperties.js deleted file mode 100644 index 8541c5b..0000000 --- a/node_modules/mongoose/lib/helpers/update/moveImmutableProperties.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -const get = require('../get'); - -/** - * Given an update, move all $set on immutable properties to $setOnInsert. - * This should only be called for upserts, because $setOnInsert bypasses the - * strictness check for immutable properties. - */ - -module.exports = function moveImmutableProperties(schema, update, ctx) { - if (update == null) { - return; - } - - const keys = Object.keys(update); - for (const key of keys) { - const isDollarKey = key.startsWith('$'); - - if (key === '$set') { - const updatedPaths = Object.keys(update[key]); - for (const path of updatedPaths) { - _walkUpdatePath(schema, update[key], path, update, ctx); - } - } else if (!isDollarKey) { - _walkUpdatePath(schema, update, key, update, ctx); - } - - } -}; - -function _walkUpdatePath(schema, op, path, update, ctx) { - const schematype = schema.path(path); - if (schematype == null) { - return; - } - - let immutable = get(schematype, 'options.immutable', null); - if (immutable == null) { - return; - } - if (typeof immutable === 'function') { - immutable = immutable.call(ctx, ctx); - } - - if (!immutable) { - return; - } - - update.$setOnInsert = update.$setOnInsert || {}; - update.$setOnInsert[path] = op[path]; - delete op[path]; -} \ No newline at end of file diff --git a/node_modules/mongoose/lib/helpers/updateValidators.js b/node_modules/mongoose/lib/helpers/updateValidators.js deleted file mode 100644 index b6ecaac..0000000 --- a/node_modules/mongoose/lib/helpers/updateValidators.js +++ /dev/null @@ -1,250 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const ValidationError = require('../error/validation'); -const cleanPositionalOperators = require('./schema/cleanPositionalOperators'); -const flatten = require('./common').flatten; -const modifiedPaths = require('./common').modifiedPaths; - -/** - * Applies validators and defaults to update and findOneAndUpdate operations, - * specifically passing a null doc as `this` to validators and defaults - * - * @param {Query} query - * @param {Schema} schema - * @param {Object} castedDoc - * @param {Object} options - * @method runValidatorsOnUpdate - * @api private - */ - -module.exports = function(query, schema, castedDoc, options, callback) { - let _keys; - const keys = Object.keys(castedDoc || {}); - let updatedKeys = {}; - let updatedValues = {}; - const isPull = {}; - const arrayAtomicUpdates = {}; - const numKeys = keys.length; - let hasDollarUpdate = false; - const modified = {}; - let currentUpdate; - let key; - let i; - - for (i = 0; i < numKeys; ++i) { - if (keys[i].startsWith('$')) { - hasDollarUpdate = true; - if (keys[i] === '$push' || keys[i] === '$addToSet') { - _keys = Object.keys(castedDoc[keys[i]]); - for (let ii = 0; ii < _keys.length; ++ii) { - currentUpdate = castedDoc[keys[i]][_keys[ii]]; - if (currentUpdate && currentUpdate.$each) { - arrayAtomicUpdates[_keys[ii]] = (arrayAtomicUpdates[_keys[ii]] || []). - concat(currentUpdate.$each); - } else { - arrayAtomicUpdates[_keys[ii]] = (arrayAtomicUpdates[_keys[ii]] || []). - concat([currentUpdate]); - } - } - continue; - } - modifiedPaths(castedDoc[keys[i]], '', modified); - const flat = flatten(castedDoc[keys[i]], null, null, schema); - const paths = Object.keys(flat); - const numPaths = paths.length; - for (let j = 0; j < numPaths; ++j) { - const updatedPath = cleanPositionalOperators(paths[j]); - key = keys[i]; - // With `$pull` we might flatten `$in`. Skip stuff nested under `$in` - // for the rest of the logic, it will get handled later. - if (updatedPath.includes('$')) { - continue; - } - if (key === '$set' || key === '$setOnInsert' || - key === '$pull' || key === '$pullAll') { - updatedValues[updatedPath] = flat[paths[j]]; - isPull[updatedPath] = key === '$pull' || key === '$pullAll'; - } else if (key === '$unset') { - updatedValues[updatedPath] = undefined; - } - updatedKeys[updatedPath] = true; - } - } - } - - if (!hasDollarUpdate) { - modifiedPaths(castedDoc, '', modified); - updatedValues = flatten(castedDoc, null, null, schema); - updatedKeys = Object.keys(updatedValues); - } - - const updates = Object.keys(updatedValues); - const numUpdates = updates.length; - const validatorsToExecute = []; - const validationErrors = []; - - const alreadyValidated = []; - - const context = options && options.context === 'query' ? query : null; - function iter(i, v) { - const schemaPath = schema._getSchema(updates[i]); - if (schemaPath == null) { - return; - } - if (schemaPath.instance === 'Mixed' && schemaPath.path !== updates[i]) { - return; - } - - if (v && Array.isArray(v.$in)) { - v.$in.forEach((v, i) => { - validatorsToExecute.push(function(callback) { - schemaPath.doValidate( - v, - function(err) { - if (err) { - err.path = updates[i] + '.$in.' + i; - validationErrors.push(err); - } - callback(null); - }, - context, - { updateValidator: true }); - }); - }); - } else { - if (isPull[updates[i]] && - schemaPath.$isMongooseArray) { - return; - } - - if (schemaPath.$isMongooseDocumentArrayElement && v != null && v.$__ != null) { - alreadyValidated.push(updates[i]); - validatorsToExecute.push(function(callback) { - schemaPath.doValidate(v, function(err) { - if (err) { - err.path = updates[i]; - validationErrors.push(err); - return callback(null); - } - - v.validate(function(err) { - if (err) { - if (err.errors) { - for (const key of Object.keys(err.errors)) { - const _err = err.errors[key]; - _err.path = updates[i] + '.' + key; - validationErrors.push(_err); - } - } else { - err.path = updates[i]; - validationErrors.push(err); - } - } - callback(null); - }); - }, context, { updateValidator: true }); - }); - } else { - validatorsToExecute.push(function(callback) { - for (const path of alreadyValidated) { - if (updates[i].startsWith(path + '.')) { - return callback(null); - } - } - schemaPath.doValidate(v, function(err) { - if (err) { - err.path = updates[i]; - validationErrors.push(err); - } - callback(null); - }, context, { updateValidator: true }); - }); - } - } - } - for (i = 0; i < numUpdates; ++i) { - iter(i, updatedValues[updates[i]]); - } - - const arrayUpdates = Object.keys(arrayAtomicUpdates); - for (const arrayUpdate of arrayUpdates) { - let schemaPath = schema._getSchema(arrayUpdate); - if (schemaPath && schemaPath.$isMongooseDocumentArray) { - validatorsToExecute.push(function(callback) { - schemaPath.doValidate( - arrayAtomicUpdates[arrayUpdate], - getValidationCallback(arrayUpdate, validationErrors, callback), - options && options.context === 'query' ? query : null); - }); - } else { - schemaPath = schema._getSchema(arrayUpdate + '.0'); - for (const atomicUpdate of arrayAtomicUpdates[arrayUpdate]) { - validatorsToExecute.push(function(callback) { - schemaPath.doValidate( - atomicUpdate, - getValidationCallback(arrayUpdate, validationErrors, callback), - options && options.context === 'query' ? query : null, - { updateValidator: true }); - }); - } - } - } - - if (callback != null) { - let numValidators = validatorsToExecute.length; - if (numValidators === 0) { - return _done(callback); - } - for (const validator of validatorsToExecute) { - validator(function() { - if (--numValidators <= 0) { - _done(callback); - } - }); - } - - return; - } - - return function(callback) { - let numValidators = validatorsToExecute.length; - if (numValidators === 0) { - return _done(callback); - } - for (const validator of validatorsToExecute) { - validator(function() { - if (--numValidators <= 0) { - _done(callback); - } - }); - } - }; - - function _done(callback) { - if (validationErrors.length) { - const err = new ValidationError(null); - - for (const validationError of validationErrors) { - err.addError(validationError.path, validationError); - } - - return callback(err); - } - callback(null); - } - - function getValidationCallback(arrayUpdate, validationErrors, callback) { - return function(err) { - if (err) { - err.path = arrayUpdate; - validationErrors.push(err); - } - callback(null); - }; - } -}; - diff --git a/node_modules/mongoose/lib/index.js b/node_modules/mongoose/lib/index.js deleted file mode 100644 index 8c7c9f0..0000000 --- a/node_modules/mongoose/lib/index.js +++ /dev/null @@ -1,1117 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -if (global.MONGOOSE_DRIVER_PATH) { - const deprecationWarning = 'The `MONGOOSE_DRIVER_PATH` global property is ' + - 'deprecated. Use `mongoose.driver.set()` instead.'; - const setDriver = require('util').deprecate(function() { - require('./driver').set(require(global.MONGOOSE_DRIVER_PATH)); - }, deprecationWarning); - setDriver(); -} else { - require('./driver').set(require('./drivers/node-mongodb-native')); -} - -const Document = require('./document'); -const Schema = require('./schema'); -const SchemaType = require('./schematype'); -const SchemaTypes = require('./schema/index'); -const VirtualType = require('./virtualtype'); -const STATES = require('./connectionstate'); -const VALID_OPTIONS = require('./validoptions'); -const Types = require('./types'); -const Query = require('./query'); -const Model = require('./model'); -const applyPlugins = require('./helpers/schema/applyPlugins'); -const get = require('./helpers/get'); -const promiseOrCallback = require('./helpers/promiseOrCallback'); -const legacyPluralize = require('mongoose-legacy-pluralize'); -const utils = require('./utils'); -const pkg = require('../package.json'); -const cast = require('./cast'); -const removeSubdocs = require('./plugins/removeSubdocs'); -const saveSubdocs = require('./plugins/saveSubdocs'); -const validateBeforeSave = require('./plugins/validateBeforeSave'); - -const Aggregate = require('./aggregate'); -const PromiseProvider = require('./promise_provider'); -const shardingPlugin = require('./plugins/sharding'); - -const defaultMongooseSymbol = Symbol.for('mongoose:default'); - -require('./helpers/printJestWarning'); - -/** - * Mongoose constructor. - * - * The exports object of the `mongoose` module is an instance of this class. - * Most apps will only use this one instance. - * - * ####Example: - * const mongoose = require('mongoose'); - * mongoose instanceof mongoose.Mongoose; // true - * - * // Create a new Mongoose instance with its own `connect()`, `set()`, `model()`, etc. - * const m = new mongoose.Mongoose(); - * - * @api public - * @param {Object} options see [`Mongoose#set()` docs](/docs/api/mongoose.html#mongoose_Mongoose-set) - */ -function Mongoose(options) { - this.connections = []; - this.models = {}; - this.modelSchemas = {}; - // default global options - this.options = Object.assign({ - pluralization: true - }, options); - const conn = this.createConnection(); // default connection - conn.models = this.models; - - if (this.options.pluralization) { - this._pluralize = legacyPluralize; - } - - // If a user creates their own Mongoose instance, give them a separate copy - // of the `Schema` constructor so they get separate custom types. (gh-6933) - if (!options || !options[defaultMongooseSymbol]) { - const _this = this; - this.Schema = function() { - this.base = _this; - return Schema.apply(this, arguments); - }; - this.Schema.prototype = Object.create(Schema.prototype); - - Object.assign(this.Schema, Schema); - this.Schema.base = this; - this.Schema.Types = Object.assign({}, Schema.Types); - } else { - // Hack to work around babel's strange behavior with - // `import mongoose, { Schema } from 'mongoose'`. Because `Schema` is not - // an own property of a Mongoose global, Schema will be undefined. See gh-5648 - for (const key of ['Schema', 'model']) { - this[key] = Mongoose.prototype[key]; - } - } - this.Schema.prototype.base = this; - - Object.defineProperty(this, 'plugins', { - configurable: false, - enumerable: true, - writable: false, - value: [ - [saveSubdocs, { deduplicate: true }], - [validateBeforeSave, { deduplicate: true }], - [shardingPlugin, { deduplicate: true }], - [removeSubdocs, { deduplicate: true }] - ] - }); -} -Mongoose.prototype.cast = cast; -/** - * Expose connection states for user-land - * - * @memberOf Mongoose - * @property STATES - * @api public - */ -Mongoose.prototype.STATES = STATES; - -/** - * The underlying driver this Mongoose instance uses to communicate with - * the database. A driver is a Mongoose-specific interface that defines functions - * like `find()`. - * - * @memberOf Mongoose - * @property driver - * @api public - */ - -Mongoose.prototype.driver = require('./driver'); - -/** - * Sets mongoose options - * - * ####Example: - * - * mongoose.set('test', value) // sets the 'test' option to `value` - * - * mongoose.set('debug', true) // enable logging collection methods + arguments to the console - * - * mongoose.set('debug', function(collectionName, methodName, arg1, arg2...) {}); // use custom function to log collection methods + arguments - * - * Currently supported options are: - * - 'debug': prints the operations mongoose sends to MongoDB to the console - * - 'bufferCommands': enable/disable mongoose's buffering mechanism for all connections and models - * - 'useCreateIndex': false by default. Set to `true` to make Mongoose's default index build use `createIndex()` instead of `ensureIndex()` to avoid deprecation warnings from the MongoDB driver. - * - 'useFindAndModify': true by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`. - * - 'useNewUrlParser': false by default. Set to `true` to make all connections set the `useNewUrlParser` option by default - * - 'useUnifiedTopology': false by default. Set to `true` to make all connections set the `useUnifiedTopology` option by default - * - 'cloneSchemas': false by default. Set to `true` to `clone()` all schemas before compiling into a model. - * - 'applyPluginsToDiscriminators': false by default. Set to true to apply global plugins to discriminator schemas. This typically isn't necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema. - * - 'applyPluginsToChildSchemas': true by default. Set to false to skip applying global plugins to child schemas - * - 'objectIdGetter': true by default. Mongoose adds a getter to MongoDB ObjectId's called `_id` that returns `this` for convenience with populate. Set this to false to remove the getter. - * - 'runValidators': false by default. Set to true to enable [update validators](/docs/validation.html#update-validators) for all validators by default. - * - 'toObject': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toObject()`](/docs/api.html#document_Document-toObject) - * - 'toJSON': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toJSON()`](/docs/api.html#document_Document-toJSON), for determining how Mongoose documents get serialized by `JSON.stringify()` - * - 'strict': true by default, may be `false`, `true`, or `'throw'`. Sets the default strict mode for schemas. - * - 'selectPopulatedPaths': true by default. Set to false to opt out of Mongoose adding all fields that you `populate()` to your `select()`. The schema-level option `selectPopulatedPaths` overwrites this one. - * - 'typePojoToMixed': true by default, may be `false` or `true`. Sets the default typePojoToMixed for schemas. - * - 'maxTimeMS': If set, attaches [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) to every query - * - 'autoIndex': true by default. Set to false to disable automatic index creation for all models associated with this Mongoose instance. - * - * @param {String} key - * @param {String|Function|Boolean} value - * @api public - */ - -Mongoose.prototype.set = function(key, value) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - if (VALID_OPTIONS.indexOf(key) === -1) throw new Error(`\`${key}\` is an invalid option.`); - - if (arguments.length === 1) { - return _mongoose.options[key]; - } - - _mongoose.options[key] = value; - - if (key === 'objectIdGetter') { - if (value) { - Object.defineProperty(mongoose.Types.ObjectId.prototype, '_id', { - enumerable: false, - configurable: true, - get: function() { - return this; - } - }); - } else { - delete mongoose.Types.ObjectId.prototype._id; - } - } - - return _mongoose; -}; - -/** - * Gets mongoose options - * - * ####Example: - * - * mongoose.get('test') // returns the 'test' value - * - * @param {String} key - * @method get - * @api public - */ - -Mongoose.prototype.get = Mongoose.prototype.set; - -/** - * Creates a Connection instance. - * - * Each `connection` instance maps to a single database. This method is helpful when mangaging multiple db connections. - * - * - * _Options passed take precedence over options included in connection strings._ - * - * ####Example: - * - * // with mongodb:// URI - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); - * - * // and options - * var opts = { db: { native_parser: true }} - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts); - * - * // replica sets - * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database'); - * - * // and options - * var opts = { replset: { strategy: 'ping', rs_name: 'testSet' }} - * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts); - * - * // and options - * var opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' } - * db = mongoose.createConnection('localhost', 'database', port, opts) - * - * // initialize now, connect later - * db = mongoose.createConnection(); - * db.openUri('localhost', 'database', port, [opts]); - * - * @param {String} [uri] a mongodb:// URI - * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below. - * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. - * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string. - * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. - * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. - * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. - * @param {Boolean} [options.useNewUrlParser=false] False by default. Set to `true` to make all connections set the `useNewUrlParser` option by default. - * @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to `true` to make all connections set the `useUnifiedTopology` option by default. - * @param {Boolean} [options.useCreateIndex=true] Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](/docs/deprecations.html#ensureindex) for automatic index builds via [`Model.init()`](/docs/api.html#model_Model.init). - * @param {Boolean} [options.useFindAndModify=true] True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`. - * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. - * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above. - * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html). - * @param {Number} [options.poolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). - * @param {Number} [options.bufferMaxEntries] This option does nothing if `useUnifiedTopology` is set. The MongoDB driver also has its own buffering mechanism that kicks in when the driver is disconnected. Set this option to 0 and set `bufferCommands` to `false` on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection. - * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). - * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes. - * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both. - * @return {Connection} the created Connection object. Connections are thenable, so you can do `await mongoose.createConnection()` - * @api public - */ - -Mongoose.prototype.createConnection = function(uri, options, callback) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - const conn = new Connection(_mongoose); - if (typeof options === 'function') { - callback = options; - options = null; - } - _mongoose.connections.push(conn); - - if (arguments.length > 0) { - return conn.openUri(uri, options, callback); - } - - return conn; -}; - -/** - * Opens the default mongoose connection. - * - * ####Example: - * - * mongoose.connect('mongodb://user:pass@localhost:port/database'); - * - * // replica sets - * var uri = 'mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase'; - * mongoose.connect(uri); - * - * // with options - * mongoose.connect(uri, options); - * - * // optional callback that gets fired when initial connection completed - * var uri = 'mongodb://nonexistent.domain:27000'; - * mongoose.connect(uri, function(error) { - * // if error is truthy, the initial connection failed. - * }) - * - * @param {String} uri(s) - * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below. - * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. - * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string. - * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. - * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. - * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection. - * @param {Boolean} [options.useNewUrlParser=false] False by default. Set to `true` to opt in to the MongoDB driver's new URL parser logic. - * @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to `true` to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine. - * @param {Boolean} [options.useCreateIndex=true] Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](/docs/deprecations.html#ensureindex) for automatic index builds via [`Model.init()`](/docs/api.html#model_Model.init). - * @param {Boolean} [options.useFindAndModify=true] True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`. - * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections. - * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above. - * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html). - * @param {Number} [options.poolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs). - * @param {Number} [options.bufferMaxEntries] This option does nothing if `useUnifiedTopology` is set. The MongoDB driver also has its own buffering mechanism that kicks in when the driver is disconnected. Set this option to 0 and set `bufferCommands` to `false` on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection. - * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback). - * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes. - * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both. - * @param {Function} [callback] - * @see Mongoose#createConnection #index_Mongoose-createConnection - * @api public - * @return {Promise} resolves to `this` if connection succeeded - */ - -Mongoose.prototype.connect = function(uri, options, callback) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - const conn = _mongoose.connection; - return conn.openUri(uri, options, callback).then(() => _mongoose); -}; - -/** - * Runs `.close()` on all connections in parallel. - * - * @param {Function} [callback] called after all connection close, or when first error occurred. - * @return {Promise} resolves when all connections are closed, or rejects with the first error that occurred. - * @api public - */ - -Mongoose.prototype.disconnect = function(callback) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - return promiseOrCallback(callback, cb => { - let remaining = _mongoose.connections.length; - if (remaining <= 0) { - return cb(null); - } - _mongoose.connections.forEach(conn => { - conn.close(function(error) { - if (error) { - return cb(error); - } - if (!--remaining) { - cb(null); - } - }); - }); - }); -}; - -/** - * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) - * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), - * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). - * - * Calling `mongoose.startSession()` is equivalent to calling `mongoose.connection.startSession()`. - * Sessions are scoped to a connection, so calling `mongoose.startSession()` - * starts a session on the [default mongoose connection](/docs/api.html#mongoose_Mongoose-connection). - * - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) - * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency - * @param {Function} [callback] - * @return {Promise} promise that resolves to a MongoDB driver `ClientSession` - * @api public - */ - -Mongoose.prototype.startSession = function() { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - return _mongoose.connection.startSession.apply(_mongoose.connection, arguments); -}; - -/** - * Getter/setter around function for pluralizing collection names. - * - * @param {Function|null} [fn] overwrites the function used to pluralize collection names - * @return {Function|null} the current function used to pluralize collection names, defaults to the legacy function from `mongoose-legacy-pluralize`. - * @api public - */ - -Mongoose.prototype.pluralize = function(fn) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - if (arguments.length > 0) { - _mongoose._pluralize = fn; - } - return _mongoose._pluralize; -}; - -/** - * Defines a model or retrieves it. - * - * Models defined on the `mongoose` instance are available to all connection - * created by the same `mongoose` instance. - * - * If you call `mongoose.model()` with twice the same name but a different schema, - * you will get an `OverwriteModelError`. If you call `mongoose.model()` with - * the same name and same schema, you'll get the same schema back. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * - * // define an Actor model with this mongoose instance - * const Schema = new Schema({ name: String }); - * mongoose.model('Actor', schema); - * - * // create a new connection - * var conn = mongoose.createConnection(..); - * - * // create Actor model - * var Actor = conn.model('Actor', schema); - * conn.model('Actor') === Actor; // true - * conn.model('Actor', schema) === Actor; // true, same schema - * conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name - * - * // This throws an `OverwriteModelError` because the schema is different. - * conn.model('Actor', new Schema({ name: String })); - * - * _When no `collection` argument is passed, Mongoose uses the model name. If you don't like this behavior, either pass a collection name, use `mongoose.pluralize()`, or set your schemas collection name option._ - * - * ####Example: - * - * var schema = new Schema({ name: String }, { collection: 'actor' }); - * - * // or - * - * schema.set('collection', 'actor'); - * - * // or - * - * var collectionName = 'actor' - * var M = mongoose.model('Actor', schema, collectionName) - * - * @param {String|Function} name model name or class extending Model - * @param {Schema} [schema] the schema to use. - * @param {String} [collection] name (optional, inferred from model name) - * @param {Boolean} [skipInit] whether to skip initialization (defaults to false) - * @return {Model} The model associated with `name`. Mongoose will create the model if it doesn't already exist. - * @api public - */ - -Mongoose.prototype.model = function(name, schema, collection, skipInit) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - let model; - if (typeof name === 'function') { - model = name; - name = model.name; - if (!(model.prototype instanceof Model)) { - throw new _mongoose.Error('The provided class ' + name + ' must extend Model'); - } - } - - if (typeof schema === 'string') { - collection = schema; - schema = false; - } - - if (utils.isObject(schema) && !(schema.instanceOfSchema)) { - schema = new Schema(schema); - } - if (schema && !schema.instanceOfSchema) { - throw new Error('The 2nd parameter to `mongoose.model()` should be a ' + - 'schema or a POJO'); - } - - if (typeof collection === 'boolean') { - skipInit = collection; - collection = null; - } - - // handle internal options from connection.model() - let options; - if (skipInit && utils.isObject(skipInit)) { - options = skipInit; - skipInit = true; - } else { - options = {}; - } - - // look up schema for the collection. - if (!_mongoose.modelSchemas[name]) { - if (schema) { - // cache it so we only apply plugins once - _mongoose.modelSchemas[name] = schema; - } else { - throw new mongoose.Error.MissingSchemaError(name); - } - } - - const originalSchema = schema; - if (schema) { - if (_mongoose.get('cloneSchemas')) { - schema = schema.clone(); - } - _mongoose._applyPlugins(schema); - } - - let sub; - - // connection.model() may be passing a different schema for - // an existing model name. in this case don't read from cache. - if (_mongoose.models[name] && options.cache !== false) { - if (originalSchema && - originalSchema.instanceOfSchema && - originalSchema !== _mongoose.models[name].schema) { - throw new _mongoose.Error.OverwriteModelError(name); - } - - if (collection && collection !== _mongoose.models[name].collection.name) { - // subclass current model with alternate collection - model = _mongoose.models[name]; - schema = model.prototype.schema; - sub = model.__subclass(_mongoose.connection, schema, collection); - // do not cache the sub model - return sub; - } - - return _mongoose.models[name]; - } - - // ensure a schema exists - if (!schema) { - schema = this.modelSchemas[name]; - if (!schema) { - throw new mongoose.Error.MissingSchemaError(name); - } - } - - // Apply relevant "global" options to the schema - if (!('pluralization' in schema.options)) { - schema.options.pluralization = _mongoose.options.pluralization; - } - - if (!collection) { - collection = schema.get('collection') || - utils.toCollectionName(name, _mongoose.pluralize()); - } - - const connection = options.connection || _mongoose.connection; - model = _mongoose.Model.compile(model || name, schema, collection, connection, _mongoose); - - if (!skipInit) { - // Errors handled internally, so safe to ignore error - model.init(function $modelInitNoop() {}); - } - - if (options.cache === false) { - return model; - } - - _mongoose.models[name] = model; - return _mongoose.models[name]; -}; - -/** - * Removes the model named `name` from the default connection, if it exists. - * You can use this function to clean up any models you created in your tests to - * prevent OverwriteModelErrors. - * - * Equivalent to `mongoose.connection.deleteModel(name)`. - * - * ####Example: - * - * mongoose.model('User', new Schema({ name: String })); - * console.log(mongoose.model('User')); // Model object - * mongoose.deleteModel('User'); - * console.log(mongoose.model('User')); // undefined - * - * // Usually useful in a Mocha `afterEach()` hook - * afterEach(function() { - * mongoose.deleteModel(/.+/); // Delete every model - * }); - * - * @api public - * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. - * @return {Mongoose} this - */ - -Mongoose.prototype.deleteModel = function(name) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - _mongoose.connection.deleteModel(name); - return _mongoose; -}; - -/** - * Returns an array of model names created on this instance of Mongoose. - * - * ####Note: - * - * _Does not include names of models created using `connection.model()`._ - * - * @api public - * @return {Array} - */ - -Mongoose.prototype.modelNames = function() { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - const names = Object.keys(_mongoose.models); - return names; -}; - -/** - * Applies global plugins to `schema`. - * - * @param {Schema} schema - * @api private - */ - -Mongoose.prototype._applyPlugins = function(schema, options) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - options = options || {}; - options.applyPluginsToDiscriminators = get(_mongoose, - 'options.applyPluginsToDiscriminators', false); - options.applyPluginsToChildSchemas = get(_mongoose, - 'options.applyPluginsToChildSchemas', true); - applyPlugins(schema, _mongoose.plugins, options, '$globalPluginsApplied'); -}; - -/** - * Declares a global plugin executed on all Schemas. - * - * Equivalent to calling `.plugin(fn)` on each Schema you create. - * - * @param {Function} fn plugin callback - * @param {Object} [opts] optional options - * @return {Mongoose} this - * @see plugins ./plugins.html - * @api public - */ - -Mongoose.prototype.plugin = function(fn, opts) { - const _mongoose = this instanceof Mongoose ? this : mongoose; - - _mongoose.plugins.push([fn, opts]); - return _mongoose; -}; - -/** - * The Mongoose module's default connection. Equivalent to `mongoose.connections[0]`, see [`connections`](#mongoose_Mongoose-connections). - * - * ####Example: - * - * var mongoose = require('mongoose'); - * mongoose.connect(...); - * mongoose.connection.on('error', cb); - * - * This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model). - * - * To create a new connection, use [`createConnection()`](#mongoose_Mongoose-createConnection). - * - * @memberOf Mongoose - * @instance - * @property {Connection} connection - * @api public - */ - -Mongoose.prototype.__defineGetter__('connection', function() { - return this.connections[0]; -}); - -Mongoose.prototype.__defineSetter__('connection', function(v) { - if (v instanceof Connection) { - this.connections[0] = v; - this.models = v.models; - } -}); - -/** - * An array containing all [connections](connections.html) associated with this - * Mongoose instance. By default, there is 1 connection. Calling - * [`createConnection()`](#mongoose_Mongoose-createConnection) adds a connection - * to this array. - * - * ####Example: - * - * const mongoose = require('mongoose'); - * mongoose.connections.length; // 1, just the default connection - * mongoose.connections[0] === mongoose.connection; // true - * - * mongoose.createConnection('mongodb://localhost:27017/test'); - * mongoose.connections.length; // 2 - * - * @memberOf Mongoose - * @instance - * @property {Array} connections - * @api public - */ - -Mongoose.prototype.connections; - -/*! - * Driver dependent APIs - */ - -const driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native'; - -/*! - * Connection - */ - -const Connection = require(driver + '/connection'); - -/*! - * Collection - */ - -const Collection = require(driver + '/collection'); - -/** - * The Mongoose Aggregate constructor - * - * @method Aggregate - * @api public - */ - -Mongoose.prototype.Aggregate = Aggregate; - -/** - * The Mongoose Collection constructor - * - * @method Collection - * @api public - */ - -Mongoose.prototype.Collection = Collection; - -/** - * The Mongoose [Connection](#connection_Connection) constructor - * - * @memberOf Mongoose - * @instance - * @method Connection - * @api public - */ - -Mongoose.prototype.Connection = Connection; - -/** - * The Mongoose version - * - * #### Example - * - * console.log(mongoose.version); // '5.x.x' - * - * @property version - * @api public - */ - -Mongoose.prototype.version = pkg.version; - -/** - * The Mongoose constructor - * - * The exports of the mongoose module is an instance of this class. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var mongoose2 = new mongoose.Mongoose(); - * - * @method Mongoose - * @api public - */ - -Mongoose.prototype.Mongoose = Mongoose; - -/** - * The Mongoose [Schema](#schema_Schema) constructor - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var Schema = mongoose.Schema; - * var CatSchema = new Schema(..); - * - * @method Schema - * @api public - */ - -Mongoose.prototype.Schema = Schema; - -/** - * The Mongoose [SchemaType](#schematype_SchemaType) constructor - * - * @method SchemaType - * @api public - */ - -Mongoose.prototype.SchemaType = SchemaType; - -/** - * The various Mongoose SchemaTypes. - * - * ####Note: - * - * _Alias of mongoose.Schema.Types for backwards compatibility._ - * - * @property SchemaTypes - * @see Schema.SchemaTypes #schema_Schema.Types - * @api public - */ - -Mongoose.prototype.SchemaTypes = Schema.Types; - -/** - * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor - * - * @method VirtualType - * @api public - */ - -Mongoose.prototype.VirtualType = VirtualType; - -/** - * The various Mongoose Types. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var array = mongoose.Types.Array; - * - * ####Types: - * - * - [ObjectId](#types-objectid-js) - * - [Buffer](#types-buffer-js) - * - [SubDocument](#types-embedded-js) - * - [Array](#types-array-js) - * - [DocumentArray](#types-documentarray-js) - * - * Using this exposed access to the `ObjectId` type, we can construct ids on demand. - * - * var ObjectId = mongoose.Types.ObjectId; - * var id1 = new ObjectId; - * - * @property Types - * @api public - */ - -Mongoose.prototype.Types = Types; - -/** - * The Mongoose [Query](#query_Query) constructor. - * - * @method Query - * @api public - */ - -Mongoose.prototype.Query = Query; - -/** - * The Mongoose [Promise](#promise_Promise) constructor. - * - * @memberOf Mongoose - * @instance - * @property Promise - * @api public - */ - -Object.defineProperty(Mongoose.prototype, 'Promise', { - get: function() { - return PromiseProvider.get(); - }, - set: function(lib) { - PromiseProvider.set(lib); - } -}); - -/** - * Storage layer for mongoose promises - * - * @method PromiseProvider - * @api public - */ - -Mongoose.prototype.PromiseProvider = PromiseProvider; - -/** - * The Mongoose [Model](#model_Model) constructor. - * - * @method Model - * @api public - */ - -Mongoose.prototype.Model = Model; - -/** - * The Mongoose [Document](/api/document.html) constructor. - * - * @method Document - * @api public - */ - -Mongoose.prototype.Document = Document; - -/** - * The Mongoose DocumentProvider constructor. Mongoose users should not have to - * use this directly - * - * @method DocumentProvider - * @api public - */ - -Mongoose.prototype.DocumentProvider = require('./document_provider'); - -/** - * The Mongoose ObjectId [SchemaType](/docs/schematypes.html). Used for - * declaring paths in your schema that should be - * [MongoDB ObjectIds](https://docs.mongodb.com/manual/reference/method/ObjectId/). - * Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId` - * instead. - * - * ####Example: - * - * const childSchema = new Schema({ parentId: mongoose.ObjectId }); - * - * @property ObjectId - * @api public - */ - -Mongoose.prototype.ObjectId = SchemaTypes.ObjectId; - -/** - * Returns true if Mongoose can cast the given value to an ObjectId, or - * false otherwise. - * - * ####Example: - * - * mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true - * mongoose.isValidObjectId('0123456789ab'); // true - * mongoose.isValidObjectId(6); // false - * - * @method isValidObjectId - * @api public - */ - -Mongoose.prototype.isValidObjectId = function(v) { - if (v == null) { - return true; - } - const base = this || mongoose; - const ObjectId = base.driver.get().ObjectId; - if (v instanceof ObjectId) { - return true; - } - - if (v._id != null) { - if (v._id instanceof ObjectId) { - return true; - } - if (v._id.toString instanceof Function) { - v = v._id.toString(); - return typeof v === 'string' && (v.length === 12 || v.length === 24); - } - } - - if (v.toString instanceof Function) { - v = v.toString(); - } - - if (typeof v === 'string' && (v.length === 12 || v.length === 24)) { - return true; - } - - return false; -}; - -/** - * The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for - * declaring paths in your schema that should be - * [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html). - * Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128` - * instead. - * - * ####Example: - * - * const vehicleSchema = new Schema({ fuelLevel: mongoose.Decimal128 }); - * - * @property Decimal128 - * @api public - */ - -Mongoose.prototype.Decimal128 = SchemaTypes.Decimal128; - -/** - * The Mongoose Mixed [SchemaType](/docs/schematypes.html). Used for - * declaring paths in your schema that Mongoose's change tracking, casting, - * and validation should ignore. - * - * ####Example: - * - * const schema = new Schema({ arbitrary: mongoose.Mixed }); - * - * @property Mixed - * @api public - */ - -Mongoose.prototype.Mixed = SchemaTypes.Mixed; - -/** - * The Mongoose Date [SchemaType](/docs/schematypes.html). - * - * ####Example: - * - * const schema = new Schema({ test: Date }); - * schema.path('test') instanceof mongoose.Date; // true - * - * @property Date - * @api public - */ - -Mongoose.prototype.Date = SchemaTypes.Date; - -/** - * The Mongoose Number [SchemaType](/docs/schematypes.html). Used for - * declaring paths in your schema that Mongoose should cast to numbers. - * - * ####Example: - * - * const schema = new Schema({ num: mongoose.Number }); - * // Equivalent to: - * const schema = new Schema({ num: 'number' }); - * - * @property Number - * @api public - */ - -Mongoose.prototype.Number = SchemaTypes.Number; - -/** - * The [MongooseError](#error_MongooseError) constructor. - * - * @method Error - * @api public - */ - -Mongoose.prototype.Error = require('./error/index'); - -/** - * Mongoose uses this function to get the current time when setting - * [timestamps](/docs/guide.html#timestamps). You may stub out this function - * using a tool like [Sinon](https://www.npmjs.com/package/sinon) for testing. - * - * @method now - * @returns Date the current time - * @api public - */ - -Mongoose.prototype.now = function now() { return new Date(); }; - -/** - * The Mongoose CastError constructor - * - * @method CastError - * @param {String} type The name of the type - * @param {Any} value The value that failed to cast - * @param {String} path The path `a.b.c` in the doc where this cast error occurred - * @param {Error} [reason] The original error that was thrown - * @api public - */ - -Mongoose.prototype.CastError = require('./error/cast'); - -/** - * The constructor used for schematype options - * - * @method SchemaTypeOptions - * @api public - */ - -Mongoose.prototype.SchemaTypeOptions = require('./options/SchemaTypeOptions'); - -/** - * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses. - * - * @property mongo - * @api public - */ - -Mongoose.prototype.mongo = require('mongodb'); - -/** - * The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses. - * - * @property mquery - * @api public - */ - -Mongoose.prototype.mquery = require('mquery'); - -/*! - * The exports object is an instance of Mongoose. - * - * @api public - */ - -const mongoose = module.exports = exports = new Mongoose({ - [defaultMongooseSymbol]: true -}); diff --git a/node_modules/mongoose/lib/internal.js b/node_modules/mongoose/lib/internal.js deleted file mode 100644 index 7642477..0000000 --- a/node_modules/mongoose/lib/internal.js +++ /dev/null @@ -1,38 +0,0 @@ -/*! - * Dependencies - */ - -'use strict'; - -const StateMachine = require('./statemachine'); -const ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default', 'ignore'); - -module.exports = exports = InternalCache; - -function InternalCache() { - this.strictMode = undefined; - this.selected = undefined; - this.shardval = undefined; - this.saveError = undefined; - this.validationError = undefined; - this.adhocPaths = undefined; - this.removing = undefined; - this.inserting = undefined; - this.saving = undefined; - this.version = undefined; - this.getters = {}; - this._id = undefined; - this.populate = undefined; // what we want to populate in this doc - this.populated = undefined;// the _ids that have been populated - this.wasPopulated = false; // if this doc was the result of a population - this.scope = undefined; - this.activePaths = new ActiveRoster; - this.pathsToScopes = {}; - this.cachedRequired = {}; - this.session = null; - this.$setCalled = new Set(); - - // embedded docs - this.ownerDocument = undefined; - this.fullPath = undefined; -} diff --git a/node_modules/mongoose/lib/model.js b/node_modules/mongoose/lib/model.js deleted file mode 100644 index cc9a785..0000000 --- a/node_modules/mongoose/lib/model.js +++ /dev/null @@ -1,4945 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const Aggregate = require('./aggregate'); -const ChangeStream = require('./cursor/ChangeStream'); -const Document = require('./document'); -const DocumentNotFoundError = require('./error/notFound'); -const DivergentArrayError = require('./error/divergentArray'); -const EventEmitter = require('events').EventEmitter; -const MongooseBuffer = require('./types/buffer'); -const MongooseError = require('./error/index'); -const OverwriteModelError = require('./error/overwriteModel'); -const PromiseProvider = require('./promise_provider'); -const Query = require('./query'); -const RemoveOptions = require('./options/removeOptions'); -const SaveOptions = require('./options/saveOptions'); -const Schema = require('./schema'); -const ServerSelectionError = require('./error/serverSelection'); -const SkipPopulateValue = require('./helpers/populate/SkipPopulateValue'); -const ValidationError = require('./error/validation'); -const VersionError = require('./error/version'); -const ParallelSaveError = require('./error/parallelSave'); -const applyQueryMiddleware = require('./helpers/query/applyQueryMiddleware'); -const applyHooks = require('./helpers/model/applyHooks'); -const applyMethods = require('./helpers/model/applyMethods'); -const applyStaticHooks = require('./helpers/model/applyStaticHooks'); -const applyStatics = require('./helpers/model/applyStatics'); -const applyWriteConcern = require('./helpers/schema/applyWriteConcern'); -const assignVals = require('./helpers/populate/assignVals'); -const castBulkWrite = require('./helpers/model/castBulkWrite'); -const discriminator = require('./helpers/model/discriminator'); -const each = require('./helpers/each'); -const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue'); -const getModelsMapForPopulate = require('./helpers/populate/getModelsMapForPopulate'); -const immediate = require('./helpers/immediate'); -const internalToObjectOptions = require('./options').internalToObjectOptions; -const isDefaultIdIndex = require('./helpers/indexes/isDefaultIdIndex'); -const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive'); -const get = require('./helpers/get'); -const leanPopulateMap = require('./helpers/populate/leanPopulateMap'); -const modifiedPaths = require('./helpers/update/modifiedPaths'); -const mpath = require('mpath'); -const parallelLimit = require('./helpers/parallelLimit'); -const promiseOrCallback = require('./helpers/promiseOrCallback'); -const parseProjection = require('./helpers/projection/parseProjection'); -const util = require('util'); -const utils = require('./utils'); - -const VERSION_WHERE = 1; -const VERSION_INC = 2; -const VERSION_ALL = VERSION_WHERE | VERSION_INC; - -const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol; -const modelCollectionSymbol = Symbol('mongoose#Model#collection'); -const modelDbSymbol = Symbol('mongoose#Model#db'); -const modelSymbol = require('./helpers/symbols').modelSymbol; -const subclassedSymbol = Symbol('mongoose#Model#subclassed'); - -const saveToObjectOptions = Object.assign({}, internalToObjectOptions, { - bson: true -}); - -/** - * A Model is a class that's your primary tool for interacting with MongoDB. - * An instance of a Model is called a [Document](./api.html#Document). - * - * In Mongoose, the term "Model" refers to subclasses of the `mongoose.Model` - * class. You should not use the `mongoose.Model` class directly. The - * [`mongoose.model()`](./api.html#mongoose_Mongoose-model) and - * [`connection.model()`](./api.html#connection_Connection-model) functions - * create subclasses of `mongoose.Model` as shown below. - * - * ####Example: - * - * // `UserModel` is a "Model", a subclass of `mongoose.Model`. - * const UserModel = mongoose.model('User', new Schema({ name: String })); - * - * // You can use a Model to create new documents using `new`: - * const userDoc = new UserModel({ name: 'Foo' }); - * await userDoc.save(); - * - * // You also use a model to create queries: - * const userFromDb = await UserModel.findOne({ name: 'Foo' }); - * - * @param {Object} doc values for initial set - * @param [fields] optional object containing the fields that were selected in the query which returned this document. You do **not** need to set this parameter to ensure Mongoose handles your [query projection](./api.html#query_Query-select). - * @param {Boolean} [skipId=false] optional boolean. If true, mongoose doesn't add an `_id` field to the document. - * @inherits Document http://mongoosejs.com/docs/api/document.html - * @event `error`: If listening to this event, 'error' is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model. - * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event. - * @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event. - * @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed. - * @api public - */ - -function Model(doc, fields, skipId) { - if (fields instanceof Schema) { - throw new TypeError('2nd argument to `Model` must be a POJO or string, ' + - '**not** a schema. Make sure you\'re calling `mongoose.model()`, not ' + - '`mongoose.Model()`.'); - } - Document.call(this, doc, fields, skipId); -} - -/*! - * Inherits from Document. - * - * All Model.prototype features are available on - * top level (non-sub) documents. - */ - -Model.prototype.__proto__ = Document.prototype; -Model.prototype.$isMongooseModelPrototype = true; - -/** - * Connection the model uses. - * - * @api public - * @property db - * @memberOf Model - * @instance - */ - -Model.prototype.db; - -/** - * Collection the model uses. - * - * This property is read-only. Modifying this property is a no-op. - * - * @api public - * @property collection - * @memberOf Model - * @instance - */ - -Model.prototype.collection; - -/** - * The name of the model - * - * @api public - * @property modelName - * @memberOf Model - * @instance - */ - -Model.prototype.modelName; - -/** - * Additional properties to attach to the query when calling `save()` and - * `isNew` is false. - * - * @api public - * @property $where - * @memberOf Model - * @instance - */ - -Model.prototype.$where; - -/** - * If this is a discriminator model, `baseModelName` is the name of - * the base model. - * - * @api public - * @property baseModelName - * @memberOf Model - * @instance - */ - -Model.prototype.baseModelName; - -/** - * Event emitter that reports any errors that occurred. Useful for global error - * handling. - * - * ####Example: - * - * MyModel.events.on('error', err => console.log(err.message)); - * - * // Prints a 'CastError' because of the above handler - * await MyModel.findOne({ _id: 'notanid' }).catch(noop); - * - * @api public - * @fires error whenever any query or model function errors - * @memberOf Model - * @static events - */ - -Model.events; - -/*! - * Compiled middleware for this model. Set in `applyHooks()`. - * - * @api private - * @property _middleware - * @memberOf Model - * @static - */ - -Model._middleware; - -/*! - * ignore - */ - -function _applyCustomWhere(doc, where) { - if (doc.$where == null) { - return; - } - - const keys = Object.keys(doc.$where); - const len = keys.length; - for (let i = 0; i < len; ++i) { - where[keys[i]] = doc.$where[keys[i]]; - } -} - -/*! - * ignore - */ - -Model.prototype.$__handleSave = function(options, callback) { - const _this = this; - let saveOptions = {}; - - if ('safe' in options) { - _handleSafe(options); - } - applyWriteConcern(this.schema, options); - if ('w' in options) { - saveOptions.w = options.w; - } - if ('j' in options) { - saveOptions.j = options.j; - } - if ('wtimeout' in options) { - saveOptions.wtimeout = options.wtimeout; - } - if ('checkKeys' in options) { - saveOptions.checkKeys = options.checkKeys; - } - - const session = this.$session(); - if (!saveOptions.hasOwnProperty('session')) { - saveOptions.session = session; - } - - if (Object.keys(saveOptions).length === 0) { - saveOptions = null; - } - - if (this.isNew) { - // send entire doc - const obj = this.toObject(saveToObjectOptions); - - if ((obj || {})._id === void 0) { - // documents must have an _id else mongoose won't know - // what to update later if more changes are made. the user - // wouldn't know what _id was generated by mongodb either - // nor would the ObjectId generated by mongodb necessarily - // match the schema definition. - setTimeout(function() { - callback(new MongooseError('document must have an _id before saving')); - }, 0); - return; - } - - this.$__version(true, obj); - this[modelCollectionSymbol].insertOne(obj, saveOptions, function(err, ret) { - if (err) { - _setIsNew(_this, true); - - callback(err, null); - return; - } - - callback(null, ret); - }); - this.$__reset(); - _setIsNew(this, false); - // Make it possible to retry the insert - this.$__.inserting = true; - } else { - // Make sure we don't treat it as a new object on error, - // since it already exists - this.$__.inserting = false; - - const delta = this.$__delta(); - - if (delta) { - if (delta instanceof MongooseError) { - callback(delta); - return; - } - - const where = this.$__where(delta[0]); - if (where instanceof MongooseError) { - callback(where); - return; - } - - _applyCustomWhere(this, where); - - this[modelCollectionSymbol].updateOne(where, delta[1], saveOptions, function(err, ret) { - if (err) { - callback(err); - return; - } - ret.$where = where; - callback(null, ret); - }); - } else { - const optionsWithCustomValues = Object.assign({}, options, saveOptions); - this.constructor.exists(this.$__where(), optionsWithCustomValues) - .then((documentExists) => { - if (!documentExists) throw new DocumentNotFoundError(this.$__where(), this.constructor.modelName); - - this.$__reset(); - callback(); - }) - .catch(callback); - return; - } - - _setIsNew(this, false); - } -}; - -/*! - * ignore - */ - -Model.prototype.$__save = function(options, callback) { - this.$__handleSave(options, (error, result) => { - const hooks = this.schema.s.hooks; - if (error) { - return hooks.execPost('save:error', this, [this], { error: error }, (error) => { - callback(error, this); - }); - } - - // store the modified paths before the document is reset - const modifiedPaths = this.modifiedPaths(); - - this.$__reset(); - - let numAffected = 0; - if (get(options, 'safe.w') !== 0 && get(options, 'w') !== 0) { - // Skip checking if write succeeded if writeConcern is set to - // unacknowledged writes, because otherwise `numAffected` will always be 0 - if (result) { - if (Array.isArray(result)) { - numAffected = result.length; - } else if (result.result && result.result.n !== undefined) { - numAffected = result.result.n; - } else if (result.result && result.result.nModified !== undefined) { - numAffected = result.result.nModified; - } else { - numAffected = result; - } - } - - // was this an update that required a version bump? - if (this.$__.version && !this.$__.inserting) { - const doIncrement = VERSION_INC === (VERSION_INC & this.$__.version); - this.$__.version = undefined; - - const key = this.schema.options.versionKey; - const version = this.$__getValue(key) || 0; - - if (numAffected <= 0) { - // the update failed. pass an error back - const err = this.$__.$versionError || - new VersionError(this, version, modifiedPaths); - return callback(err); - } - - // increment version if was successful - if (doIncrement) { - this.$__setValue(key, version + 1); - } - } - - if (result != null && numAffected <= 0) { - error = new DocumentNotFoundError(result.$where, - this.constructor.modelName, numAffected, result); - return hooks.execPost('save:error', this, [this], { error: error }, (error) => { - callback(error, this); - }); - } - } - this.$__.saving = undefined; - this.emit('save', this, numAffected); - this.constructor.emit('save', this, numAffected); - callback(null, this); - }); -}; - -/*! - * ignore - */ - -function generateVersionError(doc, modifiedPaths) { - const key = doc.schema.options.versionKey; - if (!key) { - return null; - } - const version = doc.$__getValue(key) || 0; - return new VersionError(doc, version, modifiedPaths); -} - -/** - * Saves this document. - * - * ####Example: - * - * product.sold = Date.now(); - * product = await product.save(); - * - * If save is successful, the returned promise will fulfill with the document - * saved. - * - * ####Example: - * - * const newProduct = await product.save(); - * newProduct === product; // true - * - * @param {Object} [options] options optional options - * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). - * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead. - * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. - * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) - * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) - * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). - * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) - * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. - * @param {Function} [fn] optional callback - * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating). - * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. - * @api public - * @see middleware http://mongoosejs.com/docs/middleware.html - */ - -Model.prototype.save = function(options, fn) { - let parallelSave; - this.$op = 'save'; - - if (this.$__.saving) { - parallelSave = new ParallelSaveError(this); - } else { - this.$__.saving = new ParallelSaveError(this); - } - - if (typeof options === 'function') { - fn = options; - options = undefined; - } - - options = new SaveOptions(options); - if (options.hasOwnProperty('session')) { - this.$session(options.session); - } - - this.$__.$versionError = generateVersionError(this, this.modifiedPaths()); - - fn = this.constructor.$handleCallbackError(fn); - - return promiseOrCallback(fn, cb => { - cb = this.constructor.$wrapCallback(cb); - - if (parallelSave) { - this.$__handleReject(parallelSave); - return cb(parallelSave); - } - - this.$__.saveOptions = options; - - this.$__save(options, error => { - this.$__.saving = undefined; - delete this.$__.saveOptions; - delete this.$__.$versionError; - this.$op = null; - - if (error) { - this.$__handleReject(error); - return cb(error); - } - cb(null, this); - }); - }, this.constructor.events); -}; - -/*! - * Determines whether versioning should be skipped for the given path - * - * @param {Document} self - * @param {String} path - * @return {Boolean} true if versioning should be skipped for the given path - */ -function shouldSkipVersioning(self, path) { - const skipVersioning = self.schema.options.skipVersioning; - if (!skipVersioning) return false; - - // Remove any array indexes from the path - path = path.replace(/\.\d+\./, '.'); - - return skipVersioning[path]; -} - -/*! - * Apply the operation to the delta (update) clause as - * well as track versioning for our where clause. - * - * @param {Document} self - * @param {Object} where - * @param {Object} delta - * @param {Object} data - * @param {Mixed} val - * @param {String} [operation] - */ - -function operand(self, where, delta, data, val, op) { - // delta - op || (op = '$set'); - if (!delta[op]) delta[op] = {}; - delta[op][data.path] = val; - - // disabled versioning? - if (self.schema.options.versionKey === false) return; - - // path excluded from versioning? - if (shouldSkipVersioning(self, data.path)) return; - - // already marked for versioning? - if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return; - - switch (op) { - case '$set': - case '$unset': - case '$pop': - case '$pull': - case '$pullAll': - case '$push': - case '$addToSet': - break; - default: - // nothing to do - return; - } - - // ensure updates sent with positional notation are - // editing the correct array element. - // only increment the version if an array position changes. - // modifying elements of an array is ok if position does not change. - if (op === '$push' || op === '$addToSet' || op === '$pullAll' || op === '$pull') { - self.$__.version = VERSION_INC; - } else if (/^\$p/.test(op)) { - // potentially changing array positions - self.increment(); - } else if (Array.isArray(val)) { - // $set an array - self.increment(); - } else if (/\.\d+\.|\.\d+$/.test(data.path)) { - // now handling $set, $unset - // subpath of array - self.$__.version = VERSION_WHERE; - } -} - -/*! - * Compiles an update and where clause for a `val` with _atomics. - * - * @param {Document} self - * @param {Object} where - * @param {Object} delta - * @param {Object} data - * @param {Array} value - */ - -function handleAtomics(self, where, delta, data, value) { - if (delta.$set && delta.$set[data.path]) { - // $set has precedence over other atomics - return; - } - - if (typeof value.$__getAtomics === 'function') { - value.$__getAtomics().forEach(function(atomic) { - const op = atomic[0]; - const val = atomic[1]; - operand(self, where, delta, data, val, op); - }); - return; - } - - // legacy support for plugins - - const atomics = value[arrayAtomicsSymbol]; - const ops = Object.keys(atomics); - let i = ops.length; - let val; - let op; - - if (i === 0) { - // $set - - if (utils.isMongooseObject(value)) { - value = value.toObject({ depopulate: 1, _isNested: true }); - } else if (value.valueOf) { - value = value.valueOf(); - } - - return operand(self, where, delta, data, value); - } - - function iter(mem) { - return utils.isMongooseObject(mem) - ? mem.toObject({ depopulate: 1, _isNested: true }) - : mem; - } - - while (i--) { - op = ops[i]; - val = atomics[op]; - - if (utils.isMongooseObject(val)) { - val = val.toObject({ depopulate: true, transform: false, _isNested: true }); - } else if (Array.isArray(val)) { - val = val.map(iter); - } else if (val.valueOf) { - val = val.valueOf(); - } - - if (op === '$addToSet') { - val = { $each: val }; - } - - operand(self, where, delta, data, val, op); - } -} - -/** - * Produces a special query document of the modified properties used in updates. - * - * @api private - * @method $__delta - * @memberOf Model - * @instance - */ - -Model.prototype.$__delta = function() { - const dirty = this.$__dirty(); - if (!dirty.length && VERSION_ALL !== this.$__.version) { - return; - } - - const where = {}; - const delta = {}; - const len = dirty.length; - const divergent = []; - let d = 0; - - where._id = this._doc._id; - // If `_id` is an object, need to depopulate, but also need to be careful - // because `_id` can technically be null (see gh-6406) - if (get(where, '_id.$__', null) != null) { - where._id = where._id.toObject({ transform: false, depopulate: true }); - } - - for (; d < len; ++d) { - const data = dirty[d]; - let value = data.value; - - const match = checkDivergentArray(this, data.path, value); - if (match) { - divergent.push(match); - continue; - } - - const pop = this.populated(data.path, true); - if (!pop && this.$__.selected) { - // If any array was selected using an $elemMatch projection, we alter the path and where clause - // NOTE: MongoDB only supports projected $elemMatch on top level array. - const pathSplit = data.path.split('.'); - const top = pathSplit[0]; - if (this.$__.selected[top] && this.$__.selected[top].$elemMatch) { - // If the selected array entry was modified - if (pathSplit.length > 1 && pathSplit[1] == 0 && typeof where[top] === 'undefined') { - where[top] = this.$__.selected[top]; - pathSplit[1] = '$'; - data.path = pathSplit.join('.'); - } - // if the selected array was modified in any other way throw an error - else { - divergent.push(data.path); - continue; - } - } - } - - if (divergent.length) continue; - - if (value === undefined) { - operand(this, where, delta, data, 1, '$unset'); - } else if (value === null) { - operand(this, where, delta, data, null); - } else if (value.isMongooseArray && value.$path() && value[arrayAtomicsSymbol]) { - // arrays and other custom types (support plugins etc) - handleAtomics(this, where, delta, data, value); - } else if (value[MongooseBuffer.pathSymbol] && Buffer.isBuffer(value)) { - // MongooseBuffer - value = value.toObject(); - operand(this, where, delta, data, value); - } else { - value = utils.clone(value, { - depopulate: true, - transform: false, - virtuals: false, - getters: false, - _isNested: true - }); - operand(this, where, delta, data, value); - } - } - - if (divergent.length) { - return new DivergentArrayError(divergent); - } - - if (this.$__.version) { - this.$__version(where, delta); - } - - return [where, delta]; -}; - -/*! - * Determine if array was populated with some form of filter and is now - * being updated in a manner which could overwrite data unintentionally. - * - * @see https://github.com/Automattic/mongoose/issues/1334 - * @param {Document} doc - * @param {String} path - * @return {String|undefined} - */ - -function checkDivergentArray(doc, path, array) { - // see if we populated this path - const pop = doc.populated(path, true); - - if (!pop && doc.$__.selected) { - // If any array was selected using an $elemMatch projection, we deny the update. - // NOTE: MongoDB only supports projected $elemMatch on top level array. - const top = path.split('.')[0]; - if (doc.$__.selected[top + '.$']) { - return top; - } - } - - if (!(pop && array && array.isMongooseArray)) return; - - // If the array was populated using options that prevented all - // documents from being returned (match, skip, limit) or they - // deselected the _id field, $pop and $set of the array are - // not safe operations. If _id was deselected, we do not know - // how to remove elements. $pop will pop off the _id from the end - // of the array in the db which is not guaranteed to be the - // same as the last element we have here. $set of the entire array - // would be similarily destructive as we never received all - // elements of the array and potentially would overwrite data. - const check = pop.options.match || - pop.options.options && utils.object.hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted - pop.options.options && pop.options.options.skip || // 0 is permitted - pop.options.select && // deselected _id? - (pop.options.select._id === 0 || - /\s?-_id\s?/.test(pop.options.select)); - - if (check) { - const atomics = array[arrayAtomicsSymbol]; - if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) { - return path; - } - } -} - -/** - * Appends versioning to the where and update clauses. - * - * @api private - * @method $__version - * @memberOf Model - * @instance - */ - -Model.prototype.$__version = function(where, delta) { - const key = this.schema.options.versionKey; - - if (where === true) { - // this is an insert - if (key) this.$__setValue(key, delta[key] = 0); - return; - } - - // updates - - // only apply versioning if our versionKey was selected. else - // there is no way to select the correct version. we could fail - // fast here and force them to include the versionKey but - // thats a bit intrusive. can we do this automatically? - if (!this.isSelected(key)) { - return; - } - - // $push $addToSet don't need the where clause set - if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) { - const value = this.$__getValue(key); - if (value != null) where[key] = value; - } - - if (VERSION_INC === (VERSION_INC & this.$__.version)) { - if (get(delta.$set, key, null) != null) { - // Version key is getting set, means we'll increment the doc's version - // after a successful save, so we should set the incremented version so - // future saves don't fail (gh-5779) - ++delta.$set[key]; - } else { - delta.$inc = delta.$inc || {}; - delta.$inc[key] = 1; - } - } -}; - -/** - * Signal that we desire an increment of this documents version. - * - * ####Example: - * - * Model.findById(id, function (err, doc) { - * doc.increment(); - * doc.save(function (err) { .. }) - * }) - * - * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey - * @api public - */ - -Model.prototype.increment = function increment() { - this.$__.version = VERSION_ALL; - return this; -}; - -/** - * Returns a query object - * - * @api private - * @method $__where - * @memberOf Model - * @instance - */ - -Model.prototype.$__where = function _where(where) { - where || (where = {}); - - if (!where._id) { - where._id = this._doc._id; - } - - if (this._doc._id === void 0) { - return new MongooseError('No _id found on document!'); - } - - return where; -}; - -/** - * Removes this document from the db. - * - * ####Example: - * product.remove(function (err, product) { - * if (err) return handleError(err); - * Product.findById(product._id, function (err, product) { - * console.log(product) // null - * }) - * }) - * - * - * As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to recieve errors - * - * ####Example: - * product.remove().then(function (product) { - * ... - * }).catch(function (err) { - * assert.ok(err) - * }) - * - * @param {Object} [options] - * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). - * @param {function(err,product)} [fn] optional callback - * @return {Promise} Promise - * @api public - */ - -Model.prototype.remove = function remove(options, fn) { - if (typeof options === 'function') { - fn = options; - options = undefined; - } - - options = new RemoveOptions(options); - if (options.hasOwnProperty('session')) { - this.$session(options.session); - } - this.$op = 'remove'; - - fn = this.constructor.$handleCallbackError(fn); - - return promiseOrCallback(fn, cb => { - cb = this.constructor.$wrapCallback(cb); - this.$__remove(options, (err, res) => { - this.$op = null; - cb(err, res); - }); - }, this.constructor.events); -}; - -/** - * Alias for remove - */ - -Model.prototype.delete = Model.prototype.remove; - -/** - * Removes this document from the db. Equivalent to `.remove()`. - * - * ####Example: - * product = await product.deleteOne(); - * await Product.findById(product._id); // null - * - * @param {function(err,product)} [fn] optional callback - * @return {Promise} Promise - * @api public - */ - -Model.prototype.deleteOne = function deleteOne(options, fn) { - if (typeof options === 'function') { - fn = options; - options = undefined; - } - - if (!options) { - options = {}; - } - - fn = this.constructor.$handleCallbackError(fn); - - return promiseOrCallback(fn, cb => { - cb = this.constructor.$wrapCallback(cb); - this.$__deleteOne(options, cb); - }, this.constructor.events); -}; - -/*! - * ignore - */ - -Model.prototype.$__remove = function $__remove(options, cb) { - if (this.$__.isDeleted) { - return immediate(() => cb(null, this)); - } - - const where = this.$__where(); - if (where instanceof MongooseError) { - return cb(where); - } - - _applyCustomWhere(this, where); - - const session = this.$session(); - if (!options.hasOwnProperty('session')) { - options.session = session; - } - - this[modelCollectionSymbol].deleteOne(where, options, err => { - if (!err) { - this.$__.isDeleted = true; - this.emit('remove', this); - this.constructor.emit('remove', this); - return cb(null, this); - } - this.$__.isDeleted = false; - cb(err); - }); -}; - -/*! - * ignore - */ - -Model.prototype.$__deleteOne = Model.prototype.$__remove; - -/** - * Returns another Model instance. - * - * ####Example: - * - * var doc = new Tank; - * doc.model('User').findById(id, callback); - * - * @param {String} name model name - * @api public - */ - -Model.prototype.model = function model(name) { - return this[modelDbSymbol].model(name); -}; - -/** - * Returns true if at least one document exists in the database that matches - * the given `filter`, and false otherwise. - * - * Under the hood, `MyModel.exists({ answer: 42 })` is equivalent to - * `MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean().then(doc => !!doc)` - * - * ####Example: - * await Character.deleteMany({}); - * await Character.create({ name: 'Jean-Luc Picard' }); - * - * await Character.exists({ name: /picard/i }); // true - * await Character.exists({ name: /riker/i }); // false - * - * This function triggers the following middleware. - * - * - `findOne()` - * - * @param {Object} filter - * @param {Function} [callback] callback - * @return {Promise} - */ - -Model.exists = function exists(filter, options, callback) { - _checkContext(this, 'exists'); - - if (typeof options === 'function') { - callback = options; - options = null; - } - - const query = this.findOne(filter). - select({ _id: 1 }). - lean(). - setOptions(options); - - if (typeof callback === 'function') { - query.exec(function(err, doc) { - if (err != null) { - return callback(err); - } - callback(null, !!doc); - }); - return; - } - - return query.then(doc => !!doc); -}; - -/** - * Adds a discriminator type. - * - * ####Example: - * - * function BaseSchema() { - * Schema.apply(this, arguments); - * - * this.add({ - * name: String, - * createdAt: Date - * }); - * } - * util.inherits(BaseSchema, Schema); - * - * var PersonSchema = new BaseSchema(); - * var BossSchema = new BaseSchema({ department: String }); - * - * var Person = mongoose.model('Person', PersonSchema); - * var Boss = Person.discriminator('Boss', BossSchema); - * new Boss().__t; // "Boss". `__t` is the default `discriminatorKey` - * - * var employeeSchema = new Schema({ boss: ObjectId }); - * var Employee = Person.discriminator('Employee', employeeSchema, 'staff'); - * new Employee().__t; // "staff" because of 3rd argument above - * - * @param {String} name discriminator model name - * @param {Schema} schema discriminator model schema - * @param {String} [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. - * @return {Model} The newly created discriminator model - * @api public - */ - -Model.discriminator = function(name, schema, value) { - let model; - if (typeof name === 'function') { - model = name; - name = utils.getFunctionName(model); - if (!(model.prototype instanceof Model)) { - throw new MongooseError('The provided class ' + name + ' must extend Model'); - } - } - - _checkContext(this, 'discriminator'); - - schema = discriminator(this, name, schema, value, true); - if (this.db.models[name]) { - throw new OverwriteModelError(name); - } - - schema.$isRootDiscriminator = true; - schema.$globalPluginsApplied = true; - - model = this.db.model(model || name, schema, this.collection.name); - this.discriminators[name] = model; - const d = this.discriminators[name]; - d.prototype.__proto__ = this.prototype; - Object.defineProperty(d, 'baseModelName', { - value: this.modelName, - configurable: true, - writable: false - }); - - // apply methods and statics - applyMethods(d, schema); - applyStatics(d, schema); - - if (this[subclassedSymbol] != null) { - for (const submodel of this[subclassedSymbol]) { - submodel.discriminators = submodel.discriminators || {}; - submodel.discriminators[name] = - model.__subclass(model.db, schema, submodel.collection.name); - } - } - - return d; -}; - -/*! - * Make sure `this` is a model - */ - -function _checkContext(ctx, fnName) { - // Check context, because it is easy to mistakenly type - // `new Model.discriminator()` and get an incomprehensible error - if (ctx == null || ctx === global) { - throw new MongooseError('`Model.' + fnName + '()` cannot run without a ' + - 'model as `this`. Make sure you are calling `MyModel.' + fnName + '()` ' + - 'where `MyModel` is a Mongoose model.'); - } else if (ctx[modelSymbol] == null) { - throw new MongooseError('`Model.' + fnName + '()` cannot run without a ' + - 'model as `this`. Make sure you are not calling ' + - '`new Model.' + fnName + '()`'); - } -} - -// Model (class) features - -/*! - * Give the constructor the ability to emit events. - */ - -for (const i in EventEmitter.prototype) { - Model[i] = EventEmitter.prototype[i]; -} - -/** - * This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/), - * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off. - * - * Mongoose calls this function automatically when a model is created using - * [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or - * [`connection.model()`](/docs/api.html#connection_Connection-model), so you - * don't need to call it. This function is also idempotent, so you may call it - * to get back a promise that will resolve when your indexes are finished - * building as an alternative to [`MyModel.on('index')`](/docs/guide.html#indexes) - * - * ####Example: - * - * var eventSchema = new Schema({ thing: { type: 'string', unique: true }}) - * // This calls `Event.init()` implicitly, so you don't need to call - * // `Event.init()` on your own. - * var Event = mongoose.model('Event', eventSchema); - * - * Event.init().then(function(Event) { - * // You can also use `Event.on('index')` if you prefer event emitters - * // over promises. - * console.log('Indexes are done building!'); - * }); - * - * @api public - * @param {Function} [callback] - * @returns {Promise} - */ - -Model.init = function init(callback) { - _checkContext(this, 'init'); - - this.schema.emit('init', this); - - if (this.$init != null) { - if (callback) { - this.$init.then(() => callback(), err => callback(err)); - return null; - } - return this.$init; - } - - const Promise = PromiseProvider.get(); - const autoIndex = utils.getOption('autoIndex', - this.schema.options, this.db.config, this.db.base.options); - const autoCreate = this.schema.options.autoCreate == null ? - this.db.config.autoCreate : - this.schema.options.autoCreate; - - const _ensureIndexes = autoIndex ? - cb => this.ensureIndexes({ _automatic: true }, cb) : - cb => cb(); - const _createCollection = autoCreate ? - cb => this.createCollection({}, cb) : - cb => cb(); - - this.$init = new Promise((resolve, reject) => { - _createCollection(error => { - if (error) { - return reject(error); - } - _ensureIndexes(error => { - if (error) { - return reject(error); - } - resolve(this); - }); - }); - }); - - if (callback) { - this.$init.then(() => callback(), err => callback(err)); - this.$caught = true; - return null; - } else { - const _catch = this.$init.catch; - const _this = this; - this.$init.catch = function() { - this.$caught = true; - return _catch.apply(_this.$init, arguments); - }; - } - - return this.$init; -}; - - -/** - * Create the collection for this model. By default, if no indexes are specified, - * mongoose will not create the collection for the model until any documents are - * created. Use this method to create the collection explicitly. - * - * Note 1: You may need to call this before starting a transaction - * See https://docs.mongodb.com/manual/core/transactions/#transactions-and-operations - * - * Note 2: You don't have to call this if your schema contains index or unique field. - * In that case, just use `Model.init()` - * - * ####Example: - * - * var userSchema = new Schema({ name: String }) - * var User = mongoose.model('User', userSchema); - * - * User.createCollection().then(function(collection) { - * console.log('Collection is created!'); - * }); - * - * @api public - * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection) - * @param {Function} [callback] - * @returns {Promise} - */ - -Model.createCollection = function createCollection(options, callback) { - _checkContext(this, 'createCollection'); - - if (typeof options === 'string') { - throw new MongooseError('You can\'t specify a new collection name in Model.createCollection.' + - 'This is not like Connection.createCollection. Only options are accepted here.'); - } else if (typeof options === 'function') { - callback = options; - options = null; - } - - const schemaCollation = get(this, 'schema.options.collation', null); - if (schemaCollation != null) { - options = Object.assign({ collation: schemaCollation }, options); - } - - callback = this.$handleCallbackError(callback); - - return promiseOrCallback(callback, cb => { - cb = this.$wrapCallback(cb); - - this.db.createCollection(this.collection.collectionName, options, utils.tick((error) => { - if (error) { - return cb(error); - } - this.collection = this.db.collection(this.collection.collectionName, options); - cb(null, this.collection); - })); - }, this.events); -}; - -/** - * Makes the indexes in MongoDB match the indexes defined in this model's - * schema. This function will drop any indexes that are not defined in - * the model's schema except the `_id` index, and build any indexes that - * are in your schema but not in MongoDB. - * - * See the [introductory blog post](http://thecodebarbarian.com/whats-new-in-mongoose-5-2-syncindexes) - * for more information. - * - * ####Example: - * - * const schema = new Schema({ name: { type: String, unique: true } }); - * const Customer = mongoose.model('Customer', schema); - * await Customer.createIndex({ age: 1 }); // Index is not in schema - * // Will drop the 'age' index and create an index on `name` - * await Customer.syncIndexes(); - * - * @param {Object} [options] options to pass to `ensureIndexes()` - * @param {Boolean} [options.background=null] if specified, overrides each index's `background` property - * @param {Function} [callback] optional callback - * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. - * @api public - */ - -Model.syncIndexes = function syncIndexes(options, callback) { - _checkContext(this, 'syncIndexes'); - - callback = this.$handleCallbackError(callback); - - return promiseOrCallback(callback, cb => { - cb = this.$wrapCallback(cb); - - this.createCollection(err => { - if (err) { - return cb(err); - } - this.cleanIndexes((err, dropped) => { - if (err != null) { - return cb(err); - } - this.createIndexes(options, err => { - if (err != null) { - return cb(err); - } - cb(null, dropped); - }); - }); - }); - }, this.events); -}; - -/** - * Deletes all indexes that aren't defined in this model's schema. Used by - * `syncIndexes()`. - * - * The returned promise resolves to a list of the dropped indexes' names as an array - * - * @param {Function} [callback] optional callback - * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. - * @api public - */ - -Model.cleanIndexes = function cleanIndexes(callback) { - _checkContext(this, 'cleanIndexes'); - - callback = this.$handleCallbackError(callback); - - return promiseOrCallback(callback, cb => { - const collection = this.collection; - - this.listIndexes((err, indexes) => { - if (err != null) { - return cb(err); - } - - const schemaIndexes = this.schema.indexes(); - const toDrop = []; - - for (const index of indexes) { - let found = false; - // Never try to drop `_id` index, MongoDB server doesn't allow it - if (isDefaultIdIndex(index)) { - continue; - } - - for (const schemaIndex of schemaIndexes) { - if (isIndexEqual(this, schemaIndex, index)) { - found = true; - } - } - - if (!found) { - toDrop.push(index.name); - } - } - - if (toDrop.length === 0) { - return cb(null, []); - } - - dropIndexes(toDrop, cb); - }); - - function dropIndexes(toDrop, cb) { - let remaining = toDrop.length; - let error = false; - toDrop.forEach(indexName => { - collection.dropIndex(indexName, err => { - if (err != null) { - error = true; - return cb(err); - } - if (!error) { - --remaining || cb(null, toDrop); - } - }); - }); - } - }); -}; - -/*! - * ignore - */ - -function isIndexEqual(model, schemaIndex, dbIndex) { - const key = schemaIndex[0]; - const options = _decorateDiscriminatorIndexOptions(model, - utils.clone(schemaIndex[1])); - - // If these options are different, need to rebuild the index - const optionKeys = [ - 'unique', - 'partialFilterExpression', - 'sparse', - 'expireAfterSeconds', - 'collation' - ]; - for (const key of optionKeys) { - if (!(key in options) && !(key in dbIndex)) { - continue; - } - if (!utils.deepEqual(options[key], dbIndex[key])) { - return false; - } - } - - const schemaIndexKeys = Object.keys(key); - const dbIndexKeys = Object.keys(dbIndex.key); - if (schemaIndexKeys.length !== dbIndexKeys.length) { - return false; - } - for (let i = 0; i < schemaIndexKeys.length; ++i) { - if (schemaIndexKeys[i] !== dbIndexKeys[i]) { - return false; - } - if (!utils.deepEqual(key[schemaIndexKeys[i]], dbIndex.key[dbIndexKeys[i]])) { - return false; - } - } - - return true; -} - -/** - * Lists the indexes currently defined in MongoDB. This may or may not be - * the same as the indexes defined in your schema depending on whether you - * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you - * build indexes manually. - * - * @param {Function} [cb] optional callback - * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. - * @api public - */ - -Model.listIndexes = function init(callback) { - _checkContext(this, 'listIndexes'); - - const _listIndexes = cb => { - this.collection.listIndexes().toArray(cb); - }; - - callback = this.$handleCallbackError(callback); - - return promiseOrCallback(callback, cb => { - cb = this.$wrapCallback(cb); - - // Buffering - if (this.collection.buffer) { - this.collection.addQueue(_listIndexes, [cb]); - } else { - _listIndexes(cb); - } - }, this.events); -}; - -/** - * Sends `createIndex` commands to mongo for each index declared in the schema. - * The `createIndex` commands are sent in series. - * - * ####Example: - * - * Event.ensureIndexes(function (err) { - * if (err) return handleError(err); - * }); - * - * After completion, an `index` event is emitted on this `Model` passing an error if one occurred. - * - * ####Example: - * - * var eventSchema = new Schema({ thing: { type: 'string', unique: true }}) - * var Event = mongoose.model('Event', eventSchema); - * - * Event.on('index', function (err) { - * if (err) console.error(err); // error occurred during index creation - * }) - * - * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._ - * - * @param {Object} [options] internal options - * @param {Function} [cb] optional callback - * @return {Promise} - * @api public - */ - -Model.ensureIndexes = function ensureIndexes(options, callback) { - _checkContext(this, 'ensureIndexes'); - - if (typeof options === 'function') { - callback = options; - options = null; - } - - callback = this.$handleCallbackError(callback); - - return promiseOrCallback(callback, cb => { - cb = this.$wrapCallback(cb); - - _ensureIndexes(this, options || {}, error => { - if (error) { - return cb(error); - } - cb(null); - }); - }, this.events); -}; - -/** - * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex) - * function. - * - * @param {Object} [options] internal options - * @param {Function} [cb] optional callback - * @return {Promise} - * @api public - */ - -Model.createIndexes = function createIndexes(options, callback) { - _checkContext(this, 'createIndexes'); - - if (typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - options.createIndex = true; - return this.ensureIndexes(options, callback); -}; - -/*! - * ignore - */ - -function _ensureIndexes(model, options, callback) { - const indexes = model.schema.indexes(); - let indexError; - - options = options || {}; - - const done = function(err) { - if (err && !model.$caught) { - model.emit('error', err); - } - model.emit('index', err || indexError); - callback && callback(err); - }; - - for (const index of indexes) { - if (isDefaultIdIndex(index)) { - console.warn('mongoose: Cannot specify a custom index on `_id` for ' + - 'model name "' + model.modelName + '", ' + - 'MongoDB does not allow overwriting the default `_id` index. See ' + - 'http://bit.ly/mongodb-id-index'); - } - } - - if (!indexes.length) { - immediate(function() { - done(); - }); - return; - } - // Indexes are created one-by-one to support how MongoDB < 2.4 deals - // with background indexes. - - const indexSingleDone = function(err, fields, options, name) { - model.emit('index-single-done', err, fields, options, name); - }; - const indexSingleStart = function(fields, options) { - model.emit('index-single-start', fields, options); - }; - - const baseSchema = model.schema._baseSchema; - const baseSchemaIndexes = baseSchema ? baseSchema.indexes() : []; - - const create = function() { - if (options._automatic) { - if (model.schema.options.autoIndex === false || - (model.schema.options.autoIndex == null && model.db.config.autoIndex === false)) { - return done(); - } - } - - const index = indexes.shift(); - if (!index) { - return done(); - } - - if (baseSchemaIndexes.find(i => utils.deepEqual(i, index))) { - return create(); - } - - const indexFields = utils.clone(index[0]); - const indexOptions = utils.clone(index[1]); - - _decorateDiscriminatorIndexOptions(model, indexOptions); - if ('safe' in options) { - _handleSafe(options); - } - applyWriteConcern(model.schema, indexOptions); - - indexSingleStart(indexFields, options); - let useCreateIndex = !!model.base.options.useCreateIndex; - if ('useCreateIndex' in model.db.config) { - useCreateIndex = !!model.db.config.useCreateIndex; - } - if ('createIndex' in options) { - useCreateIndex = !!options.createIndex; - } - if ('background' in options) { - indexOptions.background = options.background; - } - - const methodName = useCreateIndex ? 'createIndex' : 'ensureIndex'; - model.collection[methodName](indexFields, indexOptions, utils.tick(function(err, name) { - indexSingleDone(err, indexFields, indexOptions, name); - if (err) { - if (!indexError) { - indexError = err; - } - if (!model.$caught) { - model.emit('error', err); - } - } - create(); - })); - }; - - immediate(function() { - // If buffering is off, do this manually. - if (options._automatic && !model.collection.collection) { - model.collection.addQueue(create, []); - } else { - create(); - } - }); -} - -function _decorateDiscriminatorIndexOptions(model, indexOptions) { - // If the model is a discriminator and it has a unique index, add a - // partialFilterExpression by default so the unique index will only apply - // to that discriminator. - if (model.baseModelName != null && indexOptions.unique && - !('partialFilterExpression' in indexOptions) && - !('sparse' in indexOptions)) { - - const value = ( - model.schema.discriminatorMapping && - model.schema.discriminatorMapping.value - ) || model.modelName; - - indexOptions.partialFilterExpression = { - [model.schema.options.discriminatorKey]: value - }; - } - return indexOptions; -} - -const safeDeprecationWarning = 'Mongoose: the `safe` option for `save()` is ' + - 'deprecated. Use the `w` option instead: http://bit.ly/mongoose-save'; - -const _handleSafe = util.deprecate(function _handleSafe(options) { - if (options.safe) { - if (typeof options.safe === 'boolean') { - options.w = options.safe; - delete options.safe; - } - if (typeof options.safe === 'object') { - options.w = options.safe.w; - options.j = options.safe.j; - options.wtimeout = options.safe.wtimeout; - delete options.safe; - } - } -}, safeDeprecationWarning); - -/** - * Schema the model uses. - * - * @property schema - * @receiver Model - * @api public - * @memberOf Model - */ - -Model.schema; - -/*! - * Connection instance the model uses. - * - * @property db - * @api public - * @memberOf Model - */ - -Model.db; - -/*! - * Collection the model uses. - * - * @property collection - * @api public - * @memberOf Model - */ - -Model.collection; - -/** - * Base Mongoose instance the model uses. - * - * @property base - * @api public - * @memberOf Model - */ - -Model.base; - -/** - * Registered discriminators for this model. - * - * @property discriminators - * @api public - * @memberOf Model - */ - -Model.discriminators; - -/** - * Translate any aliases fields/conditions so the final query or document object is pure - * - * ####Example: - * - * Character - * .find(Character.translateAliases({ - * '名': 'Eddard Stark' // Alias for 'name' - * }) - * .exec(function(err, characters) {}) - * - * ####Note: - * Only translate arguments of object type anything else is returned raw - * - * @param {Object} raw fields/conditions that may contain aliased keys - * @return {Object} the translated 'pure' fields/conditions - */ -Model.translateAliases = function translateAliases(fields) { - _checkContext(this, 'translateAliases'); - - const translate = (key, value) => { - let alias; - const translated = []; - const fieldKeys = key.split('.'); - let currentSchema = this.schema; - for (const i in fieldKeys) { - const name = fieldKeys[i]; - if (currentSchema && currentSchema.aliases[name]) { - alias = currentSchema.aliases[name]; - // Alias found, - translated.push(alias); - } else { - // Alias not found, so treat as un-aliased key - translated.push(name); - } - - // Check if aliased path is a schema - if (currentSchema && currentSchema.paths[alias]) { - currentSchema = currentSchema.paths[alias].schema; - } - else - currentSchema = null; - } - - const translatedKey = translated.join('.'); - if (fields instanceof Map) - fields.set(translatedKey, value); - else - fields[translatedKey] = value; - - if (translatedKey !== key) { - // We'll be using the translated key instead - if (fields instanceof Map) { - // Delete from map - fields.delete(key); - } else { - // Delete from object - delete fields[key]; // We'll be using the translated key instead - } - } - return fields; - }; - - if (typeof fields === 'object') { - // Fields is an object (query conditions or document fields) - if (fields instanceof Map) { - // A Map was supplied - for (const field of new Map(fields)) { - fields = translate(field[0], field[1]); - } - } else { - // Infer a regular object was supplied - for (const key of Object.keys(fields)) { - fields = translate(key, fields[key]); - if (key[0] === '$') { - if (Array.isArray(fields[key])) { - for (const i in fields[key]) { - // Recursively translate nested queries - fields[key][i] = this.translateAliases(fields[key][i]); - } - } - } - } - } - - return fields; - } else { - // Don't know typeof fields - return fields; - } -}; - -/** - * Removes all documents that match `conditions` from the collection. - * To remove just the first document that matches `conditions`, set the `single` - * option to true. - * - * ####Example: - * - * const res = await Character.remove({ name: 'Eddard Stark' }); - * res.deletedCount; // Number of documents removed - * - * ####Note: - * - * This method sends a remove command directly to MongoDB, no Mongoose documents - * are involved. Because no Mongoose documents are involved, Mongoose does - * not execute [document middleware](/docs/middleware.html#types-of-middleware). - * - * @param {Object} conditions - * @param {Object} [options] - * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation. - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.remove = function remove(conditions, options, callback) { - _checkContext(this, 'remove'); - - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - options = null; - } else if (typeof options === 'function') { - callback = options; - options = null; - } - - // get the mongodb collection object - const mq = new this.Query({}, {}, this, this.collection); - mq.setOptions(options); - - callback = this.$handleCallbackError(callback); - - return mq.remove(conditions, callback); -}; - -/** - * Deletes the first document that matches `conditions` from the collection. - * Behaves like `remove()`, but deletes at most one document regardless of the - * `single` option. - * - * ####Example: - * - * Character.deleteOne({ name: 'Eddard Stark' }, function (err) {}); - * - * ####Note: - * - * Like `Model.remove()`, this function does **not** trigger `pre('remove')` or `post('remove')` hooks. - * - * @param {Object} conditions - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.deleteOne = function deleteOne(conditions, options, callback) { - _checkContext(this, 'deleteOne'); - - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - options = null; - } - else if (typeof options === 'function') { - callback = options; - options = null; - } - - const mq = new this.Query({}, {}, this, this.collection); - mq.setOptions(options); - - callback = this.$handleCallbackError(callback); - - return mq.deleteOne(conditions, callback); -}; - -/** - * Deletes all of the documents that match `conditions` from the collection. - * Behaves like `remove()`, but deletes all documents that match `conditions` - * regardless of the `single` option. - * - * ####Example: - * - * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, function (err) {}); - * - * ####Note: - * - * Like `Model.remove()`, this function does **not** trigger `pre('remove')` or `post('remove')` hooks. - * - * @param {Object} conditions - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.deleteMany = function deleteMany(conditions, options, callback) { - _checkContext(this, 'deleteMany'); - - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - options = null; - } else if (typeof options === 'function') { - callback = options; - options = null; - } - - const mq = new this.Query({}, {}, this, this.collection); - mq.setOptions(options); - - callback = this.$handleCallbackError(callback); - - return mq.deleteMany(conditions, callback); -}; - -/** - * Finds documents. - * - * The `filter` are cast to their respective SchemaTypes before the command is sent. - * See our [query casting tutorial](/docs/tutorials/query_casting.html) for - * more information on how Mongoose casts `filter`. - * - * ####Examples: - * - * // named john and at least 18 - * MyModel.find({ name: 'john', age: { $gte: 18 }}); - * - * // executes, passing results to callback - * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {}); - * - * // executes, name LIKE john and only selecting the "name" and "friends" fields - * MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { }) - * - * // passing options - * MyModel.find({ name: /john/i }, null, { skip: 10 }) - * - * // passing options and executes - * MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {}); - * - * // executing a query explicitly - * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }) - * query.exec(function (err, docs) {}); - * - * // using the promise returned from executing a query - * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }); - * var promise = query.exec(); - * promise.addBack(function (err, docs) {}); - * - * @param {Object|ObjectId} filter - * @param {Object|String} [projection] optional fields to return, see [`Query.prototype.select()`](http://mongoosejs.com/docs/api.html#query_Query-select) - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see query casting /docs/tutorials/query_casting.html - * @api public - */ - -Model.find = function find(conditions, projection, options, callback) { - _checkContext(this, 'find'); - - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - projection = null; - options = null; - } else if (typeof projection === 'function') { - callback = projection; - projection = null; - options = null; - } else if (typeof options === 'function') { - callback = options; - options = null; - } - - const mq = new this.Query({}, {}, this, this.collection); - mq.select(projection); - - mq.setOptions(options); - if (this.schema.discriminatorMapping && - this.schema.discriminatorMapping.isRoot && - mq.selectedInclusively()) { - // Need to select discriminator key because original schema doesn't have it - mq.select(this.schema.options.discriminatorKey); - } - - callback = this.$handleCallbackError(callback); - - return mq.find(conditions, callback); -}; - -/** - * Finds a single document by its _id field. `findById(id)` is almost* - * equivalent to `findOne({ _id: id })`. If you want to query by a document's - * `_id`, use `findById()` instead of `findOne()`. - * - * The `id` is cast based on the Schema before sending the command. - * - * This function triggers the following middleware. - * - * - `findOne()` - * - * \* Except for how it treats `undefined`. If you use `findOne()`, you'll see - * that `findOne(undefined)` and `findOne({ _id: undefined })` are equivalent - * to `findOne({})` and return arbitrary documents. However, mongoose - * translates `findById(undefined)` into `findOne({ _id: null })`. - * - * ####Example: - * - * // find adventure by id and execute - * Adventure.findById(id, function (err, adventure) {}); - * - * // same as above - * Adventure.findById(id).exec(callback); - * - * // select only the adventures name and length - * Adventure.findById(id, 'name length', function (err, adventure) {}); - * - * // same as above - * Adventure.findById(id, 'name length').exec(callback); - * - * // include all properties except for `length` - * Adventure.findById(id, '-length').exec(function (err, adventure) {}); - * - * // passing options (in this case return the raw js objects, not mongoose documents by passing `lean` - * Adventure.findById(id, 'name', { lean: true }, function (err, doc) {}); - * - * // same as above - * Adventure.findById(id, 'name').lean().exec(function (err, doc) {}); - * - * @param {Any} id value of `_id` to query by - * @param {Object|String} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see lean queries /docs/tutorials/lean.html - * @see findById in Mongoose https://masteringjs.io/tutorials/mongoose/find-by-id - * @api public - */ - -Model.findById = function findById(id, projection, options, callback) { - _checkContext(this, 'findById'); - - if (typeof id === 'undefined') { - id = null; - } - - callback = this.$handleCallbackError(callback); - - return this.findOne({ _id: id }, projection, options, callback); -}; - -/** - * Finds one document. - * - * The `conditions` are cast to their respective SchemaTypes before the command is sent. - * - * *Note:* `conditions` is optional, and if `conditions` is null or undefined, - * mongoose will send an empty `findOne` command to MongoDB, which will return - * an arbitrary document. If you're querying by `_id`, use `findById()` instead. - * - * ####Example: - * - * // find one iphone adventures - iphone adventures?? - * Adventure.findOne({ type: 'iphone' }, function (err, adventure) {}); - * - * // same as above - * Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {}); - * - * // select only the adventures name - * Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {}); - * - * // same as above - * Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {}); - * - * // specify options, in this case lean - * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback); - * - * // same as above - * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback); - * - * // chaining findOne queries (same as above) - * Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback); - * - * @param {Object} [conditions] - * @param {Object|String} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see lean queries /docs/tutorials/lean.html - * @api public - */ - -Model.findOne = function findOne(conditions, projection, options, callback) { - _checkContext(this, 'findOne'); - - if (typeof options === 'function') { - callback = options; - options = null; - } else if (typeof projection === 'function') { - callback = projection; - projection = null; - options = null; - } else if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - projection = null; - options = null; - } - - const mq = new this.Query({}, {}, this, this.collection); - mq.select(projection); - - mq.setOptions(options); - if (this.schema.discriminatorMapping && - this.schema.discriminatorMapping.isRoot && - mq.selectedInclusively()) { - mq.select(this.schema.options.discriminatorKey); - } - - callback = this.$handleCallbackError(callback); - - return mq.findOne(conditions, callback); -}; - -/** - * Estimates the number of documents in the MongoDB collection. Faster than - * using `countDocuments()` for large collections because - * `estimatedDocumentCount()` uses collection metadata rather than scanning - * the entire collection. - * - * ####Example: - * - * const numAdventures = Adventure.estimatedDocumentCount(); - * - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.estimatedDocumentCount = function estimatedDocumentCount(options, callback) { - _checkContext(this, 'estimatedDocumentCount'); - - const mq = new this.Query({}, {}, this, this.collection); - - callback = this.$handleCallbackError(callback); - - return mq.estimatedDocumentCount(options, callback); -}; - -/** - * Counts number of documents matching `filter` in a database collection. - * - * ####Example: - * - * Adventure.countDocuments({ type: 'jungle' }, function (err, count) { - * console.log('there are %d jungle adventures', count); - * }); - * - * If you want to count all documents in a large collection, - * use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount) - * instead. If you call `countDocuments({})`, MongoDB will always execute - * a full collection scan and **not** use any indexes. - * - * The `countDocuments()` function is similar to `count()`, but there are a - * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). - * Below are the operators that `count()` supports but `countDocuments()` does not, - * and the suggested replacement: - * - * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/) - * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center) - * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere) - * - * @param {Object} filter - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.countDocuments = function countDocuments(conditions, callback) { - _checkContext(this, 'countDocuments'); - - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - } - - const mq = new this.Query({}, {}, this, this.collection); - - callback = this.$handleCallbackError(callback); - - return mq.countDocuments(conditions, callback); -}; - -/** - * Counts number of documents that match `filter` in a database collection. - * - * This method is deprecated. If you want to count the number of documents in - * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount) - * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#model_Model.countDocuments) function instead. - * - * ####Example: - * - * Adventure.count({ type: 'jungle' }, function (err, count) { - * if (err) .. - * console.log('there are %d jungle adventures', count); - * }); - * - * @deprecated - * @param {Object} filter - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.count = function count(conditions, callback) { - _checkContext(this, 'count'); - - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - } - - const mq = new this.Query({}, {}, this, this.collection); - - callback = this.$handleCallbackError(callback); - - return mq.count(conditions, callback); -}; - -/** - * Creates a Query for a `distinct` operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) { - * if (err) return handleError(err); - * - * assert(Array.isArray(result)); - * console.log('unique urls with more than 100 clicks', result); - * }) - * - * var query = Link.distinct('url'); - * query.exec(callback); - * - * @param {String} field - * @param {Object} [conditions] optional - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.distinct = function distinct(field, conditions, callback) { - _checkContext(this, 'distinct'); - - const mq = new this.Query({}, {}, this, this.collection); - - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - } - callback = this.$handleCallbackError(callback); - - return mq.distinct(field, conditions, callback); -}; - -/** - * Creates a Query, applies the passed conditions, and returns the Query. - * - * For example, instead of writing: - * - * User.find({age: {$gte: 21, $lte: 65}}, callback); - * - * we can instead write: - * - * User.where('age').gte(21).lte(65).exec(callback); - * - * Since the Query class also supports `where` you can continue chaining - * - * User - * .where('age').gte(21).lte(65) - * .where('name', /^b/i) - * ... etc - * - * @param {String} path - * @param {Object} [val] optional value - * @return {Query} - * @api public - */ - -Model.where = function where(path, val) { - _checkContext(this, 'where'); - - void val; // eslint - const mq = new this.Query({}, {}, this, this.collection).find({}); - return mq.where.apply(mq, arguments); -}; - -/** - * Creates a `Query` and specifies a `$where` condition. - * - * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model. - * - * Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {}); - * - * @param {String|Function} argument is a javascript string or anonymous function - * @method $where - * @memberOf Model - * @return {Query} - * @see Query.$where #query_Query-%24where - * @api public - */ - -Model.$where = function $where() { - _checkContext(this, '$where'); - - const mq = new this.Query({}, {}, this, this.collection).find({}); - return mq.$where.apply(mq, arguments); -}; - -/** - * Issues a mongodb findAndModify update command. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes if `callback` is passed else a Query object is returned. - * - * ####Options: - * - * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()` - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findOneAndUpdate(conditions, update, options, callback) // executes - * A.findOneAndUpdate(conditions, update, options) // returns Query - * A.findOneAndUpdate(conditions, update, callback) // executes - * A.findOneAndUpdate(conditions, update) // returns Query - * A.findOneAndUpdate() // returns Query - * - * ####Note: - * - * All top level update keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * var query = { name: 'borne' }; - * Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback) - * - * // is sent as - * Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback) - * - * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`. - * - * ####Note: - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * `findAndModify` helpers support limited validation. You can - * enable these by setting the `runValidators` options, - * respectively. - * - * If you need full-fledged validation, use the traditional approach of first - * retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }); - * - * @param {Object} [conditions] - * @param {Object} [update] - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. - * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `update`, Mongoose will wrap `update` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. An alternative to this would be using [Model.findOneAndReplace(conditions, update, options, callback)](https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndReplace). - * @param {Function} [callback] - * @return {Query} - * @see Tutorial /docs/tutorials/findoneandupdate.html - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Model.findOneAndUpdate = function(conditions, update, options, callback) { - _checkContext(this, 'findOneAndUpdate'); - - if (typeof options === 'function') { - callback = options; - options = null; - } else if (arguments.length === 1) { - if (typeof conditions === 'function') { - const msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n' - + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n' - + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n' - + ' ' + this.modelName + '.findOneAndUpdate(update)\n' - + ' ' + this.modelName + '.findOneAndUpdate()\n'; - throw new TypeError(msg); - } - update = conditions; - conditions = undefined; - } - callback = this.$handleCallbackError(callback); - - let fields; - if (options) { - fields = options.fields || options.projection; - } - - update = utils.clone(update, { - depopulate: true, - _isNested: true - }); - - _decorateUpdateWithVersionKey(update, options, this.schema.options.versionKey); - - const mq = new this.Query({}, {}, this, this.collection); - mq.select(fields); - - return mq.findOneAndUpdate(conditions, update, options, callback); -}; - -/*! - * Decorate the update with a version key, if necessary - */ - -function _decorateUpdateWithVersionKey(update, options, versionKey) { - if (!versionKey || !get(options, 'upsert', false)) { - return; - } - - const updatedPaths = modifiedPaths(update); - if (!updatedPaths[versionKey]) { - if (options.overwrite) { - update[versionKey] = 0; - } else { - if (!update.$setOnInsert) { - update.$setOnInsert = {}; - } - update.$setOnInsert[versionKey] = 0; - } - } -} - -/** - * Issues a mongodb findAndModify update command by a document's _id field. - * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`. - * - * Finds a matching document, updates it according to the `update` arg, - * passing any `options`, and returns the found document (if any) to the - * callback. The query executes if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndUpdate()` - * - * ####Options: - * - * - `new`: bool - true to return the modified document rather than the original. defaults to false - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findByIdAndUpdate(id, update, options, callback) // executes - * A.findByIdAndUpdate(id, update, options) // returns Query - * A.findByIdAndUpdate(id, update, callback) // executes - * A.findByIdAndUpdate(id, update) // returns Query - * A.findByIdAndUpdate() // returns Query - * - * ####Note: - * - * All top level update keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback) - * - * // is sent as - * Model.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options, callback) - * - * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`. - * - * ####Note: - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * `findAndModify` helpers support limited validation. You can - * enable these by setting the `runValidators` options, - * respectively. - * - * If you need full-fledged validation, use the traditional approach of first - * retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }); - * - * @param {Object|Number|String} id value of `_id` to query by - * @param {Object} [update] - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. - * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `update`, Mongoose will wrap `update` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. An alternative to this would be using [Model.findOneAndReplace({ _id: id }, update, options, callback)](https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndReplace). - * @param {Function} [callback] - * @return {Query} - * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Model.findByIdAndUpdate = function(id, update, options, callback) { - _checkContext(this, 'findByIdAndUpdate'); - - callback = this.$handleCallbackError(callback); - if (arguments.length === 1) { - if (typeof id === 'function') { - const msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n' - + ' ' + this.modelName + '.findByIdAndUpdate(id)\n' - + ' ' + this.modelName + '.findByIdAndUpdate()\n'; - throw new TypeError(msg); - } - return this.findOneAndUpdate({ _id: id }, undefined); - } - - // if a model is passed in instead of an id - if (id instanceof Document) { - id = id._id; - } - - return this.findOneAndUpdate.call(this, { _id: id }, update, options, callback); -}; - -/** - * Issue a MongoDB `findOneAndDelete()` command. - * - * Finds a matching document, removes it, and passes the found document - * (if any) to the callback. - * - * Executes the query if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndDelete()` - * - * This function differs slightly from `Model.findOneAndRemove()` in that - * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/), - * as opposed to a `findOneAndDelete()` command. For most mongoose use cases, - * this distinction is purely pedantic. You should use `findOneAndDelete()` - * unless you have a good reason not to. - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `select`: sets the document fields to return - * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findOneAndDelete(conditions, options, callback) // executes - * A.findOneAndDelete(conditions, options) // return Query - * A.findOneAndDelete(conditions, callback) // executes - * A.findOneAndDelete(conditions) // returns Query - * A.findOneAndDelete() // returns Query - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * `findAndModify` helpers support limited validation. You can - * enable these by setting the `runValidators` options, - * respectively. - * - * If you need full-fledged validation, use the traditional approach of first - * retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }); - * - * @param {Object} conditions - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.findOneAndDelete = function(conditions, options, callback) { - _checkContext(this, 'findOneAndDelete'); - - if (arguments.length === 1 && typeof conditions === 'function') { - const msg = 'Model.findOneAndDelete(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findOneAndDelete(conditions, callback)\n' - + ' ' + this.modelName + '.findOneAndDelete(conditions)\n' - + ' ' + this.modelName + '.findOneAndDelete()\n'; - throw new TypeError(msg); - } - - if (typeof options === 'function') { - callback = options; - options = undefined; - } - callback = this.$handleCallbackError(callback); - - let fields; - if (options) { - fields = options.select; - options.select = undefined; - } - - const mq = new this.Query({}, {}, this, this.collection); - mq.select(fields); - - return mq.findOneAndDelete(conditions, options, callback); -}; - -/** - * Issue a MongoDB `findOneAndDelete()` command by a document's _id field. - * In other words, `findByIdAndDelete(id)` is a shorthand for - * `findOneAndDelete({ _id: id })`. - * - * This function triggers the following middleware. - * - * - `findOneAndDelete()` - * - * @param {Object|Number|String} id value of `_id` to query by - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Function} [callback] - * @return {Query} - * @see Model.findOneAndRemove #model_Model.findOneAndRemove - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - */ - -Model.findByIdAndDelete = function(id, options, callback) { - _checkContext(this, 'findByIdAndDelete'); - - if (arguments.length === 1 && typeof id === 'function') { - const msg = 'Model.findByIdAndDelete(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findByIdAndDelete(id, callback)\n' - + ' ' + this.modelName + '.findByIdAndDelete(id)\n' - + ' ' + this.modelName + '.findByIdAndDelete()\n'; - throw new TypeError(msg); - } - callback = this.$handleCallbackError(callback); - - return this.findOneAndDelete({ _id: id }, options, callback); -}; - -/** - * Issue a MongoDB `findOneAndReplace()` command. - * - * Finds a matching document, replaces it with the provided doc, and passes the - * returned doc to the callback. - * - * Executes the query if `callback` is passed. - * - * This function triggers the following query middleware. - * - * - `findOneAndReplace()` - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `select`: sets the document fields to return - * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findOneAndReplace(conditions, options, callback) // executes - * A.findOneAndReplace(conditions, options) // return Query - * A.findOneAndReplace(conditions, callback) // executes - * A.findOneAndReplace(conditions) // returns Query - * A.findOneAndReplace() // returns Query - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * @param {Object} filter Replace the first document that matches this filter - * @param {Object} [replacement] Replace with this document - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.findOneAndReplace = function(filter, replacement, options, callback) { - _checkContext(this, 'findOneAndReplace'); - - if (arguments.length === 1 && typeof filter === 'function') { - const msg = 'Model.findOneAndReplace(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findOneAndReplace(conditions, callback)\n' - + ' ' + this.modelName + '.findOneAndReplace(conditions)\n' - + ' ' + this.modelName + '.findOneAndReplace()\n'; - throw new TypeError(msg); - } - - if (arguments.length === 3 && typeof options === 'function') { - callback = options; - options = replacement; - replacement = void 0; - } - if (arguments.length === 2 && typeof replacement === 'function') { - callback = replacement; - replacement = void 0; - options = void 0; - } - callback = this.$handleCallbackError(callback); - - let fields; - if (options) { - fields = options.select; - options.select = undefined; - } - - const mq = new this.Query({}, {}, this, this.collection); - mq.select(fields); - - return mq.findOneAndReplace(filter, replacement, options, callback); -}; - -/** - * Issue a mongodb findAndModify remove command. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * - * Executes the query if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndRemove()` - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `select`: sets the document fields to return - * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findOneAndRemove(conditions, options, callback) // executes - * A.findOneAndRemove(conditions, options) // return Query - * A.findOneAndRemove(conditions, callback) // executes - * A.findOneAndRemove(conditions) // returns Query - * A.findOneAndRemove() // returns Query - * - * Values are cast to their appropriate types when using the findAndModify helpers. - * However, the below are not executed by default. - * - * - defaults. Use the `setDefaultsOnInsert` option to override. - * - * `findAndModify` helpers support limited validation. You can - * enable these by setting the `runValidators` options, - * respectively. - * - * If you need full-fledged validation, use the traditional approach of first - * retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }); - * - * @param {Object} conditions - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Function} [callback] - * @return {Query} - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Model.findOneAndRemove = function(conditions, options, callback) { - _checkContext(this, 'findOneAndRemove'); - - if (arguments.length === 1 && typeof conditions === 'function') { - const msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n' - + ' ' + this.modelName + '.findOneAndRemove(conditions)\n' - + ' ' + this.modelName + '.findOneAndRemove()\n'; - throw new TypeError(msg); - } - - if (typeof options === 'function') { - callback = options; - options = undefined; - } - callback = this.$handleCallbackError(callback); - - let fields; - if (options) { - fields = options.select; - options.select = undefined; - } - - const mq = new this.Query({}, {}, this, this.collection); - mq.select(fields); - - return mq.findOneAndRemove(conditions, options, callback); -}; - -/** - * Issue a mongodb findAndModify remove command by a document's _id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * - * Executes the query if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndRemove()` - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update - * - * ####Examples: - * - * A.findByIdAndRemove(id, options, callback) // executes - * A.findByIdAndRemove(id, options) // return Query - * A.findByIdAndRemove(id, callback) // executes - * A.findByIdAndRemove(id) // returns Query - * A.findByIdAndRemove() // returns Query - * - * @param {Object|Number|String} id value of `_id` to query by - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Function} [callback] - * @return {Query} - * @see Model.findOneAndRemove #model_Model.findOneAndRemove - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - */ - -Model.findByIdAndRemove = function(id, options, callback) { - _checkContext(this, 'findByIdAndRemove'); - - if (arguments.length === 1 && typeof id === 'function') { - const msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n' - + ' ' + this.modelName + '.findByIdAndRemove(id)\n' - + ' ' + this.modelName + '.findByIdAndRemove()\n'; - throw new TypeError(msg); - } - callback = this.$handleCallbackError(callback); - - return this.findOneAndRemove({ _id: id }, options, callback); -}; - -/** - * Shortcut for saving one or more documents to the database. - * `MyModel.create(docs)` does `new MyModel(doc).save()` for every doc in - * docs. - * - * This function triggers the following middleware. - * - * - `save()` - * - * ####Example: - * - * // pass a spread of docs and a callback - * Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) { - * if (err) // ... - * }); - * - * // pass an array of docs - * var array = [{ type: 'jelly bean' }, { type: 'snickers' }]; - * Candy.create(array, function (err, candies) { - * if (err) // ... - * - * var jellybean = candies[0]; - * var snickers = candies[1]; - * // ... - * }); - * - * // callback is optional; use the returned promise if you like: - * var promise = Candy.create({ type: 'jawbreaker' }); - * promise.then(function (jawbreaker) { - * // ... - * }) - * - * @param {Array|Object} docs Documents to insert, as a spread or array - * @param {Object} [options] Options passed down to `save()`. To specify `options`, `docs` **must** be an array, not a spread. - * @param {Function} [callback] callback - * @return {Promise} - * @api public - */ - -Model.create = function create(doc, options, callback) { - _checkContext(this, 'create'); - - let args; - let cb; - const discriminatorKey = this.schema.options.discriminatorKey; - - if (Array.isArray(doc)) { - args = doc; - cb = typeof options === 'function' ? options : callback; - options = options != null && typeof options === 'object' ? options : {}; - } else { - const last = arguments[arguments.length - 1]; - options = {}; - // Handle falsy callbacks re: #5061 - if (typeof last === 'function' || !last) { - cb = last; - args = utils.args(arguments, 0, arguments.length - 1); - } else { - args = utils.args(arguments); - } - - if (args.length === 2 && - args[0] != null && - args[1] != null && - args[0].session == null && - last.session != null && - last.session.constructor.name === 'ClientSession' && - !this.schema.path('session')) { - // Probably means the user is running into the common mistake of trying - // to use a spread to specify options, see gh-7535 - console.warn('WARNING: to pass a `session` to `Model.create()` in ' + - 'Mongoose, you **must** pass an array as the first argument. See: ' + - 'https://mongoosejs.com/docs/api.html#model_Model.create'); - } - } - - return promiseOrCallback(cb, cb => { - cb = this.$wrapCallback(cb); - if (args.length === 0) { - return cb(null); - } - - const toExecute = []; - let firstError; - args.forEach(doc => { - toExecute.push(callback => { - const Model = this.discriminators && doc[discriminatorKey] != null ? - this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this, doc[discriminatorKey]) : - this; - if (Model == null) { - throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` + - `found for model "${this.modelName}"`); - } - let toSave = doc; - const callbackWrapper = (error, doc) => { - if (error) { - if (!firstError) { - firstError = error; - } - return callback(null, { error: error }); - } - callback(null, { doc: doc }); - }; - - if (!(toSave instanceof Model)) { - try { - toSave = new Model(toSave); - } catch (error) { - return callbackWrapper(error); - } - } - - toSave.save(options, callbackWrapper); - }); - }); - - let numFns = toExecute.length; - if (numFns === 0) { - return cb(null, []); - } - const _done = (error, res) => { - const savedDocs = []; - const len = res.length; - for (let i = 0; i < len; ++i) { - if (res[i].doc) { - savedDocs.push(res[i].doc); - } - } - - if (firstError) { - return cb(firstError, savedDocs); - } - - if (doc instanceof Array) { - cb(null, savedDocs); - } else { - cb.apply(this, [null].concat(savedDocs)); - } - }; - - const _res = []; - toExecute.forEach((fn, i) => { - fn((err, res) => { - _res[i] = res; - if (--numFns <= 0) { - return _done(null, _res); - } - }); - }); - }, this.events); -}; - -/** - * _Requires a replica set running MongoDB >= 3.6.0._ Watches the - * underlying collection for changes using - * [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/). - * - * This function does **not** trigger any middleware. In particular, it - * does **not** trigger aggregate middleware. - * - * The ChangeStream object is an event emitter that emits the following events: - * - * - 'change': A change occurred, see below example - * - 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates. - * - 'end': Emitted if the underlying stream is closed - * - 'close': Emitted if the underlying stream is closed - * - * ####Example: - * - * const doc = await Person.create({ name: 'Ned Stark' }); - * const changeStream = Person.watch().on('change', change => console.log(change)); - * // Will print from the above `console.log()`: - * // { _id: { _data: ... }, - * // operationType: 'delete', - * // ns: { db: 'mydb', coll: 'Person' }, - * // documentKey: { _id: 5a51b125c5500f5aa094c7bd } } - * await doc.remove(); - * - * @param {Array} [pipeline] - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#watch) - * @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter - * @api public - */ - -Model.watch = function(pipeline, options) { - _checkContext(this, 'watch'); - - const changeStreamThunk = cb => { - if (this.collection.buffer) { - this.collection.addQueue(() => { - if (this.closed) { - return; - } - const driverChangeStream = this.collection.watch(pipeline, options); - cb(null, driverChangeStream); - }); - } else { - const driverChangeStream = this.collection.watch(pipeline, options); - cb(null, driverChangeStream); - } - }; - - return new ChangeStream(changeStreamThunk, pipeline, options); -}; - -/** - * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) - * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), - * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). - * - * Calling `MyModel.startSession()` is equivalent to calling `MyModel.db.startSession()`. - * - * This function does not trigger any middleware. - * - * ####Example: - * - * const session = await Person.startSession(); - * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session }); - * await doc.remove(); - * // `doc` will always be null, even if reading from a replica set - * // secondary. Without causal consistency, it is possible to - * // get a doc back from the below query if the query reads from a - * // secondary that is experiencing replication lag. - * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' }); - * - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) - * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency - * @param {Function} [callback] - * @return {Promise} promise that resolves to a MongoDB driver `ClientSession` - * @api public - */ - -Model.startSession = function() { - _checkContext(this, 'startSession'); - - return this.db.startSession.apply(this.db, arguments); -}; - -/** - * Shortcut for validating an array of documents and inserting them into - * MongoDB if they're all valid. This function is faster than `.create()` - * because it only sends one operation to the server, rather than one for each - * document. - * - * Mongoose always validates each document **before** sending `insertMany` - * to MongoDB. So if one document has a validation error, no documents will - * be saved, unless you set - * [the `ordered` option to false](https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/#error-handling). - * - * This function does **not** trigger save middleware. - * - * This function triggers the following middleware. - * - * - `insertMany()` - * - * ####Example: - * - * var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }]; - * Movies.insertMany(arr, function(error, docs) {}); - * - * @param {Array|Object|*} doc(s) - * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany) - * @param {Boolean} [options.ordered = true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An `insertMany()` with `ordered = false` is called an "unordered" `insertMany()`. - * @param {Boolean} [options.rawResult = false] if false, the returned promise resolves to the documents that passed mongoose document validation. If `true`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback) with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`. - * @param {Boolean} [options.lean = false] if `true`, skips hydrating and validating the documents. This option is useful if you need the extra performance, but Mongoose won't validate the documents before inserting. - * @param {Number} [options.limit = null] this limits the number of documents being processed (validation/casting) by mongoose in parallel, this does **NOT** send the documents in batches to MongoDB. Use this option if you're processing a large number of documents and your app is running out of memory. - * @param {Function} [callback] callback - * @return {Promise} resolving to the raw result from the MongoDB driver if `options.rawResult` was `true`, or the documents that passed validation, otherwise - * @api public - */ - -Model.insertMany = function(arr, options, callback) { - _checkContext(this, 'insertMany'); - - if (typeof options === 'function') { - callback = options; - options = null; - } - return promiseOrCallback(callback, cb => { - this.$__insertMany(arr, options, cb); - }, this.events); -}; - -/*! - * ignore - */ - -Model.$__insertMany = function(arr, options, callback) { - const _this = this; - if (typeof options === 'function') { - callback = options; - options = null; - } - if (callback) { - callback = this.$handleCallbackError(callback); - callback = this.$wrapCallback(callback); - } - callback = callback || utils.noop; - options = options || {}; - const limit = get(options, 'limit', 1000); - const rawResult = get(options, 'rawResult', false); - const ordered = get(options, 'ordered', true); - const lean = get(options, 'lean', false); - - if (!Array.isArray(arr)) { - arr = [arr]; - } - - const validationErrors = []; - const toExecute = arr.map(doc => - callback => { - if (!(doc instanceof _this)) { - try { - doc = new _this(doc); - } catch (err) { - return callback(err); - } - } - if (options.session != null) { - doc.$session(options.session); - } - // If option `lean` is set to true bypass validation - if (lean) { - // we have to execute callback at the nextTick to be compatible - // with parallelLimit, as `results` variable has TDZ issue if we - // execute the callback synchronously - return process.nextTick(() => callback(null, doc)); - } - doc.validate({ __noPromise: true }, function(error) { - if (error) { - // Option `ordered` signals that insert should be continued after reaching - // a failing insert. Therefore we delegate "null", meaning the validation - // failed. It's up to the next function to filter out all failed models - if (ordered === false) { - validationErrors.push(error); - return callback(null, null); - } - return callback(error); - } - callback(null, doc); - }); - }); - - parallelLimit(toExecute, limit, function(error, docs) { - if (error) { - callback(error, null); - return; - } - // We filter all failed pre-validations by removing nulls - const docAttributes = docs.filter(function(doc) { - return doc != null; - }); - // Quickly escape while there aren't any valid docAttributes - if (docAttributes.length < 1) { - if (rawResult) { - const res = { - mongoose: { - validationErrors: validationErrors - } - }; - return callback(null, res); - } - callback(null, []); - return; - } - const docObjects = docAttributes.map(function(doc) { - if (doc.schema.options.versionKey) { - doc[doc.schema.options.versionKey] = 0; - } - if (doc.initializeTimestamps) { - return doc.initializeTimestamps().toObject(internalToObjectOptions); - } - return doc.toObject(internalToObjectOptions); - }); - - _this.collection.insertMany(docObjects, options, function(error, res) { - if (error) { - callback(error, null); - return; - } - - for (const attribute of docAttributes) { - attribute.$__reset(); - _setIsNew(attribute, false); - } - - if (rawResult) { - if (ordered === false) { - // Decorate with mongoose validation errors in case of unordered, - // because then still do `insertMany()` - res.mongoose = { - validationErrors: validationErrors - }; - } - return callback(null, res); - } - callback(null, docAttributes); - }); - }); -}; - -/*! - * ignore - */ - -function _setIsNew(doc, val) { - doc.isNew = val; - doc.emit('isNew', val); - doc.constructor.emit('isNew', val); - - const subdocs = doc.$__getAllSubdocs(); - for (const subdoc of subdocs) { - subdoc.isNew = val; - } -} - -/** - * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`, - * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one - * command. This is faster than sending multiple independent operations (e.g. - * if you use `create()`) because with `bulkWrite()` there is only one round - * trip to MongoDB. - * - * Mongoose will perform casting on all operations you provide. - * - * This function does **not** trigger any middleware, neither `save()`, nor `update()`. - * If you need to trigger - * `save()` middleware for every document use [`create()`](http://mongoosejs.com/docs/api.html#model_Model.create) instead. - * - * ####Example: - * - * Character.bulkWrite([ - * { - * insertOne: { - * document: { - * name: 'Eddard Stark', - * title: 'Warden of the North' - * } - * } - * }, - * { - * updateOne: { - * filter: { name: 'Eddard Stark' }, - * // If you were using the MongoDB driver directly, you'd need to do - * // `update: { $set: { title: ... } }` but mongoose adds $set for - * // you. - * update: { title: 'Hand of the King' } - * } - * }, - * { - * deleteOne: { - * { - * filter: { name: 'Eddard Stark' } - * } - * } - * } - * ]).then(res => { - * // Prints "1 1 1" - * console.log(res.insertedCount, res.modifiedCount, res.deletedCount); - * }); - * - * The [supported operations](https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/#db.collection.bulkWrite) are: - * - * - `insertOne` - * - `updateOne` - * - `updateMany` - * - `deleteOne` - * - `deleteMany` - * - `replaceOne` - * - * @param {Array} ops - * @param {Object} [ops.insertOne.document] The document to insert - * @param {Object} [opts.updateOne.filter] Update the first document that matches this filter - * @param {Object} [opts.updateOne.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/) - * @param {Boolean} [opts.updateOne.upsert=false] If true, insert a doc if none match - * @param {Boolean} [opts.updateOne.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation - * @param {Object} [opts.updateOne.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use - * @param {Array} [opts.updateOne.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update` - * @param {Object} [opts.updateMany.filter] Update all the documents that match this filter - * @param {Object} [opts.updateMany.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/) - * @param {Boolean} [opts.updateMany.upsert=false] If true, insert a doc if no documents match `filter` - * @param {Boolean} [opts.updateMany.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation - * @param {Object} [opts.updateMany.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use - * @param {Array} [opts.updateMany.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update` - * @param {Object} [opts.deleteOne.filter] Delete the first document that matches this filter - * @param {Object} [opts.deleteMany.filter] Delete all documents that match this filter - * @param {Object} [opts.replaceOne.filter] Replace the first document that matches this filter - * @param {Object} [opts.replaceOne.replacement] The replacement document - * @param {Boolean} [opts.replaceOne.upsert=false] If true, insert a doc if no documents match `filter` - * @param {Object} [options] - * @param {Boolean} [options.ordered=true] If true, execute writes in order and stop at the first error. If false, execute writes in parallel and continue until all writes have either succeeded or errored. - * @param {ClientSession} [options.session=null] The session associated with this bulk write. See [transactions docs](/docs/transactions.html). - * @param {String|number} [options.w=1] The [write concern](https://docs.mongodb.com/manual/reference/write-concern/). See [`Query#w()`](/docs/api.html#query_Query-w) for more information. - * @param {number} [options.wtimeout=null] The [write concern timeout](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). - * @param {Boolean} [options.j=true] If false, disable [journal acknowledgement](https://docs.mongodb.com/manual/reference/write-concern/#j-option) - * @param {Boolean} [options.bypassDocumentValidation=false] If true, disable [MongoDB server-side schema validation](https://docs.mongodb.com/manual/core/schema-validation/) for all writes in this bulk. - * @param {Boolean} [options.strict=null] Overwrites the [`strict` option](/docs/guide.html#strict) on schema. If false, allows filtering and writing fields not defined in the schema for all writes in this bulk. - * @param {Function} [callback] callback `function(error, bulkWriteOpResult) {}` - * @return {Promise} resolves to a [`BulkWriteOpResult`](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult) if the operation succeeds - * @api public - */ - -Model.bulkWrite = function(ops, options, callback) { - _checkContext(this, 'bulkWrite'); - - if (typeof options === 'function') { - callback = options; - options = null; - } - options = options || {}; - - const validations = ops.map(op => castBulkWrite(this, op, options)); - - callback = this.$handleCallbackError(callback); - - return promiseOrCallback(callback, cb => { - cb = this.$wrapCallback(cb); - each(validations, (fn, cb) => fn(cb), error => { - if (error) { - return cb(error); - } - - this.collection.bulkWrite(ops, options, (error, res) => { - if (error) { - return cb(error); - } - - cb(null, res); - }); - }); - }, this.events); -}; - -/** - * Shortcut for creating a new Document from existing raw data, pre-saved in the DB. - * The document returned has no paths marked as modified initially. - * - * ####Example: - * - * // hydrate previous data into a Mongoose document - * var mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' }); - * - * @param {Object} obj - * @return {Document} document instance - * @api public - */ - -Model.hydrate = function(obj) { - _checkContext(this, 'hydrate'); - - const model = require('./queryhelpers').createModel(this, obj); - model.init(obj); - return model; -}; - -/** - * Updates one document in the database without returning it. - * - * This function triggers the following middleware. - * - * - `update()` - * - * ####Examples: - * - * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn); - * - * const res = await MyModel.update({ name: 'Tobi' }, { ferret: true }); - * res.n; // Number of documents that matched `{ name: 'Tobi' }` - * // Number of documents that were changed. If every doc matched already - * // had `ferret` set to `true`, `nModified` will be 0. - * res.nModified; - * - * ####Valid options: - * - * - `strict` (boolean): overrides the [schema-level `strict` option](/docs/guide.html#strict) for this update - * - `upsert` (boolean): whether to create the doc if it doesn't match (false) - * - `writeConcern` (object): sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * - `omitUndefined` (boolean): If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * - `multi` (boolean): whether multiple documents should be updated (false) - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert` (boolean): if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `timestamps` (boolean): If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * - `overwrite` (boolean): disables update-only mode, allowing you to overwrite the doc (false) - * - * All `update` values are cast to their appropriate SchemaTypes before being sent. - * - * The `callback` function receives `(err, rawResponse)`. - * - * - `err` is the error if any occurred - * - `rawResponse` is the full response from Mongo - * - * ####Note: - * - * All top level keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * var query = { name: 'borne' }; - * Model.update(query, { name: 'jason bourne' }, options, callback); - * - * // is sent as - * Model.update(query, { $set: { name: 'jason bourne' }}, options, function(err, res)); - * // if overwrite option is false. If overwrite is true, sent without the $set wrapper. - * - * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason bourne' }`. - * - * ####Note: - * - * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error. - * - * ####Note: - * - * Mongoose casts values and runs setters when using update. The following - * features are **not** applied by default. - * - * - [defaults](/docs/defaults.html#the-setdefaultsoninsert-option) - * - [validators](/docs/validation.html#update-validators) - * - middleware - * - * If you need document middleware and fully-featured validation, load the - * document first and then use [`save()`](/docs/api.html#model_Model-save). - * - * Model.findOne({ name: 'borne' }, function (err, doc) { - * if (err) .. - * doc.name = 'jason bourne'; - * doc.save(callback); - * }) - * - * @see strict http://mongoosejs.com/docs/guide.html#strict - * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output - * @param {Object} filter - * @param {Object} doc - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.multi=false] whether multiple documents should be updated or just the first one that matches `filter`. - * @param {Boolean} [options.runValidators=false] if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * @param {Boolean} [options.setDefaultsOnInsert=false] if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `doc`, Mongoose will wrap `doc` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. - * @param {Function} [callback] params are (error, writeOpResult) - * @param {Function} [callback] - * @return {Query} - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @see Query docs https://mongoosejs.com/docs/queries.html - * @api public - */ - -Model.update = function update(conditions, doc, options, callback) { - _checkContext(this, 'update'); - - return _update(this, 'update', conditions, doc, options, callback); -}; - -/** - * Same as `update()`, except MongoDB will update _all_ documents that match - * `filter` (as opposed to just the first one) regardless of the value of - * the `multi` option. - * - * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')` - * and `post('updateMany')` instead. - * - * ####Example: - * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true }); - * res.n; // Number of documents matched - * res.nModified; // Number of documents modified - * - * This function triggers the following middleware. - * - * - `updateMany()` - * - * @param {Object} filter - * @param {Object} doc - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`. - * @return {Query} - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @api public - */ - -Model.updateMany = function updateMany(conditions, doc, options, callback) { - _checkContext(this, 'updateMany'); - - return _update(this, 'updateMany', conditions, doc, options, callback); -}; - -/** - * Same as `update()`, except it does not support the `multi` or `overwrite` - * options. - * - * - MongoDB will update _only_ the first document that matches `filter` regardless of the value of the `multi` option. - * - Use `replaceOne()` if you want to overwrite an entire document rather than using atomic operators like `$set`. - * - * ####Example: - * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' }); - * res.n; // Number of documents matched - * res.nModified; // Number of documents modified - * - * This function triggers the following middleware. - * - * - `updateOne()` - * - * @param {Object} filter - * @param {Object} doc - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] params are (error, writeOpResult) - * @return {Query} - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @api public - */ - -Model.updateOne = function updateOne(conditions, doc, options, callback) { - _checkContext(this, 'updateOne'); - - return _update(this, 'updateOne', conditions, doc, options, callback); -}; - -/** - * Same as `update()`, except MongoDB replace the existing document with the - * given document (no atomic operators like `$set`). - * - * ####Example: - * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' }); - * res.n; // Number of documents matched - * res.nModified; // Number of documents modified - * - * This function triggers the following middleware. - * - * - `replaceOne()` - * - * @param {Object} filter - * @param {Object} doc - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`. - * @return {Query} - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @return {Query} - * @api public - */ - -Model.replaceOne = function replaceOne(conditions, doc, options, callback) { - _checkContext(this, 'replaceOne'); - - const versionKey = get(this, 'schema.options.versionKey', null); - if (versionKey && !doc[versionKey]) { - doc[versionKey] = 0; - } - - return _update(this, 'replaceOne', conditions, doc, options, callback); -}; - -/*! - * Common code for `updateOne()`, `updateMany()`, `replaceOne()`, and `update()` - * because they need to do the same thing - */ - -function _update(model, op, conditions, doc, options, callback) { - const mq = new model.Query({}, {}, model, model.collection); - - callback = model.$handleCallbackError(callback); - // gh-2406 - // make local deep copy of conditions - if (conditions instanceof Document) { - conditions = conditions.toObject(); - } else { - conditions = utils.clone(conditions); - } - options = typeof options === 'function' ? options : utils.clone(options); - - const versionKey = get(model, 'schema.options.versionKey', null); - _decorateUpdateWithVersionKey(doc, options, versionKey); - - return mq[op](conditions, doc, options, callback); -} - -/** - * Executes a mapReduce command. - * - * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options. - * - * This function does not trigger any middleware. - * - * ####Example: - * - * var o = {}; - * // `map()` and `reduce()` are run on the MongoDB server, not Node.js, - * // these functions are converted to strings - * o.map = function () { emit(this.name, 1) }; - * o.reduce = function (k, vals) { return vals.length }; - * User.mapReduce(o, function (err, results) { - * console.log(results) - * }) - * - * ####Other options: - * - * - `query` {Object} query filter object. - * - `sort` {Object} sort input objects using this key - * - `limit` {Number} max number of documents - * - `keeptemp` {Boolean, default:false} keep temporary data - * - `finalize` {Function} finalize function - * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution - * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X - * - `verbose` {Boolean, default:false} provide statistics on job execution time. - * - `readPreference` {String} - * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job. - * - * ####* out options: - * - * - `{inline:1}` the results are returned in an array - * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection - * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions - * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old - * - * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the [`lean` option](/docs/tutorials/lean.html); meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc). - * - * ####Example: - * - * var o = {}; - * // You can also define `map()` and `reduce()` as strings if your - * // linter complains about `emit()` not being defined - * o.map = 'function () { emit(this.name, 1) }'; - * o.reduce = 'function (k, vals) { return vals.length }'; - * o.out = { replace: 'createdCollectionNameForResults' } - * o.verbose = true; - * - * User.mapReduce(o, function (err, model, stats) { - * console.log('map reduce took %d ms', stats.processtime) - * model.find().where('value').gt(10).exec(function (err, docs) { - * console.log(docs); - * }); - * }) - * - * // `mapReduce()` returns a promise. However, ES6 promises can only - * // resolve to exactly one value, - * o.resolveToObject = true; - * var promise = User.mapReduce(o); - * promise.then(function (res) { - * var model = res.model; - * var stats = res.stats; - * console.log('map reduce took %d ms', stats.processtime) - * return model.find().where('value').gt(10).exec(); - * }).then(function (docs) { - * console.log(docs); - * }).then(null, handleError).end() - * - * @param {Object} o an object specifying map-reduce options - * @param {Function} [callback] optional callback - * @see http://www.mongodb.org/display/DOCS/MapReduce - * @return {Promise} - * @api public - */ - -Model.mapReduce = function mapReduce(o, callback) { - _checkContext(this, 'mapReduce'); - - callback = this.$handleCallbackError(callback); - - return promiseOrCallback(callback, cb => { - cb = this.$wrapCallback(cb); - - if (!Model.mapReduce.schema) { - const opts = { noId: true, noVirtualId: true, strict: false }; - Model.mapReduce.schema = new Schema({}, opts); - } - - if (!o.out) o.out = { inline: 1 }; - if (o.verbose !== false) o.verbose = true; - - o.map = String(o.map); - o.reduce = String(o.reduce); - - if (o.query) { - let q = new this.Query(o.query); - q.cast(this); - o.query = q._conditions; - q = undefined; - } - - this.collection.mapReduce(null, null, o, (err, res) => { - if (err) { - return cb(err); - } - if (res.collection) { - // returned a collection, convert to Model - const model = Model.compile('_mapreduce_' + res.collection.collectionName, - Model.mapReduce.schema, res.collection.collectionName, this.db, - this.base); - - model._mapreduce = true; - res.model = model; - - return cb(null, res); - } - - cb(null, res); - }); - }, this.events); -}; - -/** - * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection. - * - * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned. - * - * This function triggers the following middleware. - * - * - `aggregate()` - * - * ####Example: - * - * // Find the max balance of all accounts - * Users.aggregate([ - * { $group: { _id: null, maxBalance: { $max: '$balance' }}}, - * { $project: { _id: 0, maxBalance: 1 }} - * ]). - * then(function (res) { - * console.log(res); // [ { maxBalance: 98000 } ] - * }); - * - * // Or use the aggregation pipeline builder. - * Users.aggregate(). - * group({ _id: null, maxBalance: { $max: '$balance' } }). - * project('-id maxBalance'). - * exec(function (err, res) { - * if (err) return handleError(err); - * console.log(res); // [ { maxBalance: 98 } ] - * }); - * - * ####NOTE: - * - * - Mongoose does **not** cast aggregation pipelines to the model's schema because `$project` and `$group` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. You can use the [mongoose-cast-aggregation plugin](https://github.com/AbdelrahmanHafez/mongoose-cast-aggregation) to enable minimal casting for aggregation pipelines. - * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). - * - * @see Aggregate #aggregate_Aggregate - * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ - * @param {Array} [pipeline] aggregation pipeline as an array of objects - * @param {Function} [callback] - * @return {Aggregate} - * @api public - */ - -Model.aggregate = function aggregate(pipeline, callback) { - _checkContext(this, 'aggregate'); - - if (arguments.length > 2 || get(pipeline, 'constructor.name') === 'Object') { - throw new MongooseError('Mongoose 5.x disallows passing a spread of operators ' + - 'to `Model.aggregate()`. Instead of ' + - '`Model.aggregate({ $match }, { $skip })`, do ' + - '`Model.aggregate([{ $match }, { $skip }])`'); - } - - if (typeof pipeline === 'function') { - callback = pipeline; - pipeline = []; - } - - const aggregate = new Aggregate(pipeline || []); - aggregate.model(this); - - if (typeof callback === 'undefined') { - return aggregate; - } - - callback = this.$handleCallbackError(callback); - callback = this.$wrapCallback(callback); - - aggregate.exec(callback); - return aggregate; -}; - -/** - * Casts and validates the given object against this model's schema, passing the - * given `context` to custom validators. - * - * ####Example: - * - * const Model = mongoose.model('Test', Schema({ - * name: { type: String, required: true }, - * age: { type: Number, required: true } - * }); - * - * try { - * await Model.validate({ name: null }, ['name']) - * } catch (err) { - * err instanceof mongoose.Error.ValidationError; // true - * Object.keys(err.errors); // ['name'] - * } - * - * @param {Object} obj - * @param {Array} pathsToValidate - * @param {Object} [context] - * @param {Function} [callback] - * @return {Promise|undefined} - * @api public - */ - -Model.validate = function validate(obj, pathsToValidate, context, callback) { - return promiseOrCallback(callback, cb => { - const schema = this.schema; - let paths = Object.keys(schema.paths); - - if (pathsToValidate != null) { - const _pathsToValidate = new Set(pathsToValidate); - paths = paths.filter(p => { - const pieces = p.split('.'); - let cur = pieces[0]; - - for (const piece of pieces) { - if (_pathsToValidate.has(cur)) { - return true; - } - cur += '.' + piece; - } - - return _pathsToValidate.has(p); - }); - } - - for (const path of paths) { - const schemaType = schema.path(path); - if (!schemaType || !schemaType.$isMongooseArray) { - continue; - } - - const val = get(obj, path); - pushNestedArrayPaths(val, path); - } - - let remaining = paths.length; - let error = null; - - for (const path of paths) { - const schemaType = schema.path(path); - if (schemaType == null) { - _checkDone(); - continue; - } - - const pieces = path.split('.'); - let cur = obj; - for (let i = 0; i < pieces.length - 1; ++i) { - cur = cur[pieces[i]]; - } - - let val = get(obj, path, void 0); - - if (val != null) { - try { - val = schemaType.cast(val); - cur[pieces[pieces.length - 1]] = val; - } catch (err) { - error = error || new ValidationError(); - error.addError(path, err); - - _checkDone(); - continue; - } - } - - schemaType.doValidate(val, err => { - if (err) { - error = error || new ValidationError(); - if (err instanceof ValidationError) { - for (const _err of Object.keys(err.errors)) { - error.addError(`${path}.${err.errors[_err].path}`, _err); - } - } else { - error.addError(err.path, err); - } - } - _checkDone(); - }, context, { path: path }); - } - - function pushNestedArrayPaths(nestedArray, path) { - if (nestedArray == null) { - return; - } - - for (let i = 0; i < nestedArray.length; ++i) { - if (Array.isArray(nestedArray[i])) { - pushNestedArrayPaths(nestedArray[i], path + '.' + i); - } else { - paths.push(path + '.' + i); - } - } - } - - function _checkDone() { - if (--remaining <= 0) { - return cb(error); - } - } - }); -}; - -/** - * Implements `$geoSearch` functionality for Mongoose - * - * This function does not trigger any middleware - * - * ####Example: - * - * var options = { near: [10, 10], maxDistance: 5 }; - * Locations.geoSearch({ type : "house" }, options, function(err, res) { - * console.log(res); - * }); - * - * ####Options: - * - `near` {Array} x,y point to search for - * - `maxDistance` {Number} the maximum distance from the point near that a result can be - * - `limit` {Number} The maximum number of results to return - * - `lean` {Object|Boolean} return the raw object instead of the Mongoose Model - * - * @param {Object} conditions an object that specifies the match condition (required) - * @param {Object} options for the geoSearch, some (near, maxDistance) are required - * @param {Object|Boolean} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {Function} [callback] optional callback - * @return {Promise} - * @see http://docs.mongodb.org/manual/reference/command/geoSearch/ - * @see http://docs.mongodb.org/manual/core/geohaystack/ - * @api public - */ - -Model.geoSearch = function(conditions, options, callback) { - _checkContext(this, 'geoSearch'); - - if (typeof options === 'function') { - callback = options; - options = {}; - } - - callback = this.$handleCallbackError(callback); - - return promiseOrCallback(callback, cb => { - cb = this.$wrapCallback(cb); - let error; - if (conditions === undefined || !utils.isObject(conditions)) { - error = new MongooseError('Must pass conditions to geoSearch'); - } else if (!options.near) { - error = new MongooseError('Must specify the near option in geoSearch'); - } else if (!Array.isArray(options.near)) { - error = new MongooseError('near option must be an array [x, y]'); - } - - if (error) { - return cb(error); - } - - // send the conditions in the options object - options.search = conditions; - - this.collection.geoHaystackSearch(options.near[0], options.near[1], options, (err, res) => { - if (err) { - return cb(err); - } - - let count = res.results.length; - if (options.lean || count === 0) { - return cb(null, res.results); - } - - const errSeen = false; - - function init(err) { - if (err && !errSeen) { - return cb(err); - } - - if (!--count && !errSeen) { - cb(null, res.results); - } - } - - for (let i = 0; i < res.results.length; ++i) { - const temp = res.results[i]; - res.results[i] = new this(); - res.results[i].init(temp, {}, init); - } - }); - }, this.events); -}; - -/** - * Populates document references. - * - * ####Available top-level options: - * - * - path: space delimited path(s) to populate - * - select: optional fields to select - * - match: optional query conditions to match - * - model: optional name of the model to use for population - * - options: optional query options like sort, limit, etc - * - justOne: optional boolean, if true Mongoose will always set `path` to an array. Inferred from schema by default. - * - * ####Examples: - * - * // populates a single object - * User.findById(id, function (err, user) { - * var opts = [ - * { path: 'company', match: { x: 1 }, select: 'name' }, - * { path: 'notes', options: { limit: 10 }, model: 'override' } - * ]; - * - * User.populate(user, opts, function (err, user) { - * console.log(user); - * }); - * }); - * - * // populates an array of objects - * User.find(match, function (err, users) { - * var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]; - * - * var promise = User.populate(users, opts); - * promise.then(console.log).end(); - * }) - * - * // imagine a Weapon model exists with two saved documents: - * // { _id: 389, name: 'whip' } - * // { _id: 8921, name: 'boomerang' } - * // and this schema: - * // new Schema({ - * // name: String, - * // weapon: { type: ObjectId, ref: 'Weapon' } - * // }); - * - * var user = { name: 'Indiana Jones', weapon: 389 }; - * Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) { - * console.log(user.weapon.name); // whip - * }) - * - * // populate many plain objects - * var users = [{ name: 'Indiana Jones', weapon: 389 }] - * users.push({ name: 'Batman', weapon: 8921 }) - * Weapon.populate(users, { path: 'weapon' }, function (err, users) { - * users.forEach(function (user) { - * console.log('%s uses a %s', users.name, user.weapon.name) - * // Indiana Jones uses a whip - * // Batman uses a boomerang - * }); - * }); - * // Note that we didn't need to specify the Weapon model because - * // it is in the schema's ref - * - * @param {Document|Array} docs Either a single document or array of documents to populate. - * @param {Object|String} options Either the paths to populate or an object specifying all parameters - * @param {string} [options.path=null] The path to populate. - * @param {boolean} [options.retainNullValues=false] By default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries. - * @param {boolean} [options.getters=false] If true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options). - * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them. - * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object. - * @param {Boolean} [options.skipInvalidIds=false] By default, Mongoose throws a cast error if `localField` and `foreignField` schemas don't line up. If you enable this option, Mongoose will instead filter out any `localField` properties that cannot be casted to `foreignField`'s schema type. - * @param {Number} [options.perDocumentLimit=null] For legacy reasons, `limit` with `populate()` may give incorrect results because it only executes a single query for every document being populated. If you set `perDocumentLimit`, Mongoose will ensure correct `limit` per document by executing a separate query for each document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` will execute 2 additional queries if `.find()` returns 2 documents. - * @param {Object} [options.options=null] Additional options like `limit` and `lean`. - * @param {Function} [callback(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. - * @return {Promise} - * @api public - */ - -Model.populate = function(docs, paths, callback) { - _checkContext(this, 'populate'); - - const _this = this; - - // normalized paths - paths = utils.populate(paths); - - // data that should persist across subPopulate calls - const cache = {}; - - callback = this.$handleCallbackError(callback); - - return promiseOrCallback(callback, cb => { - cb = this.$wrapCallback(cb); - _populate(_this, docs, paths, cache, cb); - }, this.events); -}; - -/*! - * Populate helper - * - * @param {Model} model the model to use - * @param {Document|Array} docs Either a single document or array of documents to populate. - * @param {Object} paths - * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. - * @return {Function} - * @api private - */ - -function _populate(model, docs, paths, cache, callback) { - let pending = paths.length; - - if (paths.length === 0) { - return callback(null, docs); - } - - // each path has its own query options and must be executed separately - for (const path of paths) { - populate(model, docs, path, next); - } - - function next(err) { - if (err) { - return callback(err, null); - } - if (--pending) { - return; - } - callback(null, docs); - } -} - -/*! - * Populates `docs` - */ -const excludeIdReg = /\s?-_id\s?/; -const excludeIdRegGlobal = /\s?-_id\s?/g; - -function populate(model, docs, options, callback) { - // normalize single / multiple docs passed - if (!Array.isArray(docs)) { - docs = [docs]; - } - - if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) { - return callback(); - } - - const modelsMap = getModelsMapForPopulate(model, docs, options); - - if (modelsMap instanceof MongooseError) { - return immediate(function() { - callback(modelsMap); - }); - } - - const len = modelsMap.length; - let vals = []; - - function flatten(item) { - // no need to include undefined values in our query - return undefined !== item; - } - - let _remaining = len; - let hasOne = false; - const params = []; - for (let i = 0; i < len; ++i) { - const mod = modelsMap[i]; - let select = mod.options.select; - const match = _formatMatch(mod.match); - - let ids = utils.array.flatten(mod.ids, flatten); - ids = utils.array.unique(ids); - - const assignmentOpts = {}; - assignmentOpts.sort = get(mod, 'options.options.sort', void 0); - assignmentOpts.excludeId = excludeIdReg.test(select) || (select && select._id === 0); - - if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) { - // Ensure that we set populate virtuals to 0 or empty array even - // if we don't actually execute a query because they don't have - // a value by default. See gh-7731, gh-8230 - --_remaining; - if (mod.count || mod.isVirtual) { - _assign(model, [], mod, assignmentOpts); - } - continue; - } - - hasOne = true; - if (mod.foreignField.size === 1) { - const foreignField = Array.from(mod.foreignField)[0]; - const foreignSchemaType = mod.model.schema.path(foreignField); - if (foreignField !== '_id' || !match['_id']) { - ids = _filterInvalidIds(ids, foreignSchemaType, mod.options.skipInvalidIds); - match[foreignField] = { $in: ids }; - } - } else { - const $or = []; - if (Array.isArray(match.$or)) { - match.$and = [{ $or: match.$or }, { $or: $or }]; - delete match.$or; - } else { - match.$or = $or; - } - for (const foreignField of mod.foreignField) { - if (foreignField !== '_id' || !match['_id']) { - const foreignSchemaType = mod.model.schema.path(foreignField); - ids = _filterInvalidIds(ids, foreignSchemaType, mod.options.skipInvalidIds); - $or.push({ [foreignField]: { $in: ids } }); - } - } - } - - if (assignmentOpts.excludeId) { - // override the exclusion from the query so we can use the _id - // for document matching during assignment. we'll delete the - // _id back off before returning the result. - if (typeof select === 'string') { - select = select.replace(excludeIdRegGlobal, ' '); - } else { - // preserve original select conditions by copying - select = utils.object.shallowCopy(select); - delete select._id; - } - } - - if (mod.options.options && mod.options.options.limit != null) { - assignmentOpts.originalLimit = mod.options.options.limit; - } else if (mod.options.limit != null) { - assignmentOpts.originalLimit = mod.options.limit; - } - - params.push([mod, match, select, assignmentOpts, _next]); - } - - if (!hasOne) { - return callback(); - } - - for (const arr of params) { - _execPopulateQuery.apply(null, arr); - } - - function _next(err, valsFromDb) { - if (err != null) { - return callback(err, null); - } - vals = vals.concat(valsFromDb); - if (--_remaining === 0) { - _done(); - } - } - - function _done() { - for (const arr of params) { - const mod = arr[0]; - const assignmentOpts = arr[3]; - _assign(model, vals, mod, assignmentOpts); - } - callback(); - } -} - -/*! - * ignore - */ - -function _execPopulateQuery(mod, match, select, assignmentOpts, callback) { - const subPopulate = utils.clone(mod.options.populate); - - const queryOptions = Object.assign({ - skip: mod.options.skip, - limit: mod.options.limit, - perDocumentLimit: mod.options.perDocumentLimit - }, mod.options.options); - - if (mod.count) { - delete queryOptions.skip; - } - - if (queryOptions.perDocumentLimit != null) { - queryOptions.limit = queryOptions.perDocumentLimit; - delete queryOptions.perDocumentLimit; - } else if (queryOptions.limit != null) { - queryOptions.limit = queryOptions.limit * mod.ids.length; - } - - const query = mod.model.find(match, select, queryOptions); - // If we're doing virtual populate and projection is inclusive and foreign - // field is not selected, automatically select it because mongoose needs it. - // If projection is exclusive and client explicitly unselected the foreign - // field, that's the client's fault. - for (const foreignField of mod.foreignField) { - if (foreignField !== '_id' && query.selectedInclusively() && - !isPathSelectedInclusive(query._fields, foreignField)) { - query.select(foreignField); - } - } - - // If using count, still need the `foreignField` so we can match counts - // to documents, otherwise we would need a separate `count()` for every doc. - if (mod.count) { - for (const foreignField of mod.foreignField) { - query.select(foreignField); - } - } - - // If we need to sub-populate, call populate recursively - if (subPopulate) { - query.populate(subPopulate); - } - - query.exec(callback); -} - -/*! - * ignore - */ - -function _assign(model, vals, mod, assignmentOpts) { - const options = mod.options; - const isVirtual = mod.isVirtual; - const justOne = mod.justOne; - let _val; - const lean = get(options, 'options.lean', false); - const projection = parseProjection(get(options, 'select', null), true) || - parseProjection(get(options, 'options.select', null), true); - const len = vals.length; - const rawOrder = {}; - const rawDocs = {}; - let key; - let val; - - // Clone because `assignRawDocsToIdStructure` will mutate the array - const allIds = utils.clone(mod.allIds); - - // optimization: - // record the document positions as returned by - // the query result. - for (let i = 0; i < len; i++) { - val = vals[i]; - if (val == null) { - continue; - } - for (const foreignField of mod.foreignField) { - _val = utils.getValue(foreignField, val); - if (Array.isArray(_val)) { - _val = utils.array.flatten(_val); - - for (let __val of _val) { - if (__val instanceof Document) { - __val = __val._id; - } - key = String(__val); - if (rawDocs[key]) { - if (Array.isArray(rawDocs[key])) { - rawDocs[key].push(val); - rawOrder[key].push(i); - } else { - rawDocs[key] = [rawDocs[key], val]; - rawOrder[key] = [rawOrder[key], i]; - } - } else { - if (isVirtual && !justOne) { - rawDocs[key] = [val]; - rawOrder[key] = [i]; - } else { - rawDocs[key] = val; - rawOrder[key] = i; - } - } - } - } else { - if (_val instanceof Document) { - _val = _val._id; - } - key = String(_val); - if (rawDocs[key]) { - if (Array.isArray(rawDocs[key])) { - rawDocs[key].push(val); - rawOrder[key].push(i); - } else { - rawDocs[key] = [rawDocs[key], val]; - rawOrder[key] = [rawOrder[key], i]; - } - } else { - rawDocs[key] = val; - rawOrder[key] = i; - } - } - // flag each as result of population - if (lean) { - leanPopulateMap.set(val, mod.model); - } else { - val.$__.wasPopulated = true; - } - - // gh-8460: if user used `-foreignField`, assume this means they - // want the foreign field unset even if it isn't excluded in the query. - if (projection != null && projection.hasOwnProperty('-' + foreignField)) { - if (val.$__ != null) { - val.set(foreignField, void 0); - } else { - mpath.unset(foreignField, val); - } - } - } - } - - assignVals({ - originalModel: model, - // If virtual, make sure to not mutate original field - rawIds: mod.isVirtual ? allIds : mod.allIds, - allIds: allIds, - foreignField: mod.foreignField, - rawDocs: rawDocs, - rawOrder: rawOrder, - docs: mod.docs, - path: options.path, - options: assignmentOpts, - justOne: mod.justOne, - isVirtual: mod.isVirtual, - allOptions: mod, - lean: lean, - virtual: mod.virtual, - count: mod.count, - match: mod.match - }); -} - -/*! - * Optionally filter out invalid ids that don't conform to foreign field's schema - * to avoid cast errors (gh-7706) - */ - -function _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds) { - ids = ids.filter(v => !(v instanceof SkipPopulateValue)); - if (!skipInvalidIds) { - return ids; - } - return ids.filter(id => { - try { - foreignSchemaType.cast(id); - return true; - } catch (err) { - return false; - } - }); -} - -/*! - * Format `mod.match` given that it may be an array that we need to $or if - * the client has multiple docs with match functions - */ - -function _formatMatch(match) { - if (Array.isArray(match)) { - if (match.length > 1) { - return { $or: [].concat(match.map(m => Object.assign({}, m))) }; - } - return Object.assign({}, match[0]); - } - return Object.assign({}, match); -} - -/*! - * Compiler utility. - * - * @param {String|Function} name model name or class extending Model - * @param {Schema} schema - * @param {String} collectionName - * @param {Connection} connection - * @param {Mongoose} base mongoose instance - */ - -Model.compile = function compile(name, schema, collectionName, connection, base) { - const versioningEnabled = schema.options.versionKey !== false; - - if (versioningEnabled && !schema.paths[schema.options.versionKey]) { - // add versioning to top level documents only - const o = {}; - o[schema.options.versionKey] = Number; - schema.add(o); - } - - let model; - if (typeof name === 'function' && name.prototype instanceof Model) { - model = name; - name = model.name; - schema.loadClass(model, false); - model.prototype.$isMongooseModelPrototype = true; - } else { - // generate new class - model = function model(doc, fields, skipId) { - model.hooks.execPreSync('createModel', doc); - if (!(this instanceof model)) { - return new model(doc, fields, skipId); - } - const discriminatorKey = model.schema.options.discriminatorKey; - - if (model.discriminators == null || doc == null || doc[discriminatorKey] == null) { - Model.call(this, doc, fields, skipId); - return; - } - - // If discriminator key is set, use the discriminator instead (gh-7586) - const Discriminator = model.discriminators[doc[discriminatorKey]] || - getDiscriminatorByValue(model, doc[discriminatorKey]); - if (Discriminator != null) { - return new Discriminator(doc, fields, skipId); - } - - // Otherwise, just use the top-level model - Model.call(this, doc, fields, skipId); - }; - } - - model.hooks = schema.s.hooks.clone(); - model.base = base; - model.modelName = name; - - if (!(model.prototype instanceof Model)) { - model.__proto__ = Model; - model.prototype.__proto__ = Model.prototype; - } - model.model = function model(name) { - return this.db.model(name); - }; - model.db = connection; - model.prototype.db = connection; - model.prototype[modelDbSymbol] = connection; - model.discriminators = model.prototype.discriminators = undefined; - model[modelSymbol] = true; - model.events = new EventEmitter(); - - model.prototype.$__setSchema(schema); - - const _userProvidedOptions = schema._userProvidedOptions || {}; - - // `bufferCommands` is true by default... - let bufferCommands = true; - // First, take the global option - if (connection.base.get('bufferCommands') != null) { - bufferCommands = connection.base.get('bufferCommands'); - } - // Connection-specific overrides the global option - if (connection.config.bufferCommands != null) { - bufferCommands = connection.config.bufferCommands; - } - // And schema options override global and connection - if (_userProvidedOptions.bufferCommands != null) { - bufferCommands = _userProvidedOptions.bufferCommands; - } - - const collectionOptions = { - bufferCommands: bufferCommands, - capped: schema.options.capped, - autoCreate: schema.options.autoCreate, - Promise: model.base.Promise - }; - - model.prototype.collection = connection.collection( - collectionName, - collectionOptions - ); - model.prototype[modelCollectionSymbol] = model.prototype.collection; - - // apply methods and statics - applyMethods(model, schema); - applyStatics(model, schema); - applyHooks(model, schema); - applyStaticHooks(model, schema.s.hooks, schema.statics); - - model.schema = model.prototype.schema; - model.collection = model.prototype.collection; - - // Create custom query constructor - model.Query = function() { - Query.apply(this, arguments); - }; - model.Query.prototype = Object.create(Query.prototype); - model.Query.base = Query.base; - applyQueryMiddleware(model.Query, model); - applyQueryMethods(model, schema.query); - - return model; -}; - -/*! - * Register custom query methods for this model - * - * @param {Model} model - * @param {Schema} schema - */ - -function applyQueryMethods(model, methods) { - for (const i in methods) { - model.Query.prototype[i] = methods[i]; - } -} - -/*! - * Subclass this model with `conn`, `schema`, and `collection` settings. - * - * @param {Connection} conn - * @param {Schema} [schema] - * @param {String} [collection] - * @return {Model} - */ - -Model.__subclass = function subclass(conn, schema, collection) { - // subclass model using this connection and collection name - const _this = this; - - const Model = function Model(doc, fields, skipId) { - if (!(this instanceof Model)) { - return new Model(doc, fields, skipId); - } - _this.call(this, doc, fields, skipId); - }; - - Model.__proto__ = _this; - Model.prototype.__proto__ = _this.prototype; - Model.db = conn; - Model.prototype.db = conn; - Model.prototype[modelDbSymbol] = conn; - - _this[subclassedSymbol] = _this[subclassedSymbol] || []; - _this[subclassedSymbol].push(Model); - if (_this.discriminators != null) { - Model.discriminators = {}; - for (const key of Object.keys(_this.discriminators)) { - Model.discriminators[key] = _this.discriminators[key]. - __subclass(_this.db, _this.discriminators[key].schema, collection); - } - } - - const s = schema && typeof schema !== 'string' - ? schema - : _this.prototype.schema; - - const options = s.options || {}; - const _userProvidedOptions = s._userProvidedOptions || {}; - - if (!collection) { - collection = _this.prototype.schema.get('collection') || - utils.toCollectionName(_this.modelName, this.base.pluralize()); - } - - let bufferCommands = true; - if (s) { - if (conn.config.bufferCommands != null) { - bufferCommands = conn.config.bufferCommands; - } - if (_userProvidedOptions.bufferCommands != null) { - bufferCommands = _userProvidedOptions.bufferCommands; - } - } - const collectionOptions = { - bufferCommands: bufferCommands, - capped: s && options.capped - }; - - Model.prototype.collection = conn.collection(collection, collectionOptions); - Model.prototype[modelCollectionSymbol] = Model.prototype.collection; - Model.collection = Model.prototype.collection; - // Errors handled internally, so ignore - Model.init(() => {}); - return Model; -}; - -Model.$handleCallbackError = function(callback) { - if (callback == null) { - return callback; - } - if (typeof callback !== 'function') { - throw new MongooseError('Callback must be a function, got ' + callback); - } - - const _this = this; - return function() { - try { - callback.apply(null, arguments); - } catch (error) { - _this.emit('error', error); - } - }; -}; - -/*! - * ignore - */ - -Model.$wrapCallback = function(callback) { - const serverSelectionError = new ServerSelectionError(); - const _this = this; - - return function(err) { - if (err != null && err.name === 'MongoServerSelectionError') { - arguments[0] = serverSelectionError.assimilateError(err); - } - if (err != null && err.name === 'MongoNetworkError' && err.message.endsWith('timed out')) { - _this.db.emit('timeout'); - } - - return callback.apply(null, arguments); - }; -}; - -/** - * Helper for console.log. Given a model named 'MyModel', returns the string - * `'Model { MyModel }'`. - * - * ####Example: - * - * const MyModel = mongoose.model('Test', Schema({ name: String })); - * MyModel.inspect(); // 'Model { Test }' - * console.log(MyModel); // Prints 'Model { Test }' - * - * @api public - */ - -Model.inspect = function() { - return `Model { ${this.modelName} }`; -}; - -if (util.inspect.custom) { - /*! - * Avoid Node deprecation warning DEP0079 - */ - - Model[util.inspect.custom] = Model.inspect; -} - -/*! - * Module exports. - */ - -module.exports = exports = Model; diff --git a/node_modules/mongoose/lib/options.js b/node_modules/mongoose/lib/options.js deleted file mode 100644 index 8e9fc29..0000000 --- a/node_modules/mongoose/lib/options.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -exports.internalToObjectOptions = { - transform: false, - virtuals: false, - getters: false, - _skipDepopulateTopLevel: true, - depopulate: true, - flattenDecimals: false -}; diff --git a/node_modules/mongoose/lib/options/PopulateOptions.js b/node_modules/mongoose/lib/options/PopulateOptions.js deleted file mode 100644 index b60d45a..0000000 --- a/node_modules/mongoose/lib/options/PopulateOptions.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const clone = require('../helpers/clone'); - -class PopulateOptions { - constructor(obj) { - this._docs = {}; - - if (obj == null) { - return; - } - obj = clone(obj); - Object.assign(this, obj); - if (typeof obj.subPopulate === 'object') { - this.populate = obj.subPopulate; - } - - - if (obj.perDocumentLimit != null && obj.limit != null) { - throw new Error('Can not use `limit` and `perDocumentLimit` at the same time. Path: `' + obj.path + '`.'); - } - } -} - -/** - * The connection used to look up models by name. If not specified, Mongoose - * will default to using the connection associated with the model in - * `PopulateOptions#model`. - * - * @memberOf PopulateOptions - * @property {Connection} connection - * @api public - */ - -module.exports = PopulateOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaArrayOptions.js b/node_modules/mongoose/lib/options/SchemaArrayOptions.js deleted file mode 100644 index ddd0b37..0000000 --- a/node_modules/mongoose/lib/options/SchemaArrayOptions.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const SchemaTypeOptions = require('./SchemaTypeOptions'); - -/** - * The options defined on an Array schematype. - * - * ####Example: - * - * const schema = new Schema({ tags: [String] }); - * schema.path('tags').options; // SchemaArrayOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaArrayOptions - */ - -class SchemaArrayOptions extends SchemaTypeOptions {} - -const opts = require('./propertyOptions'); - -/** - * If this is an array of strings, an array of allowed values for this path. - * Throws an error if this array isn't an array of strings. - * - * @api public - * @property enum - * @memberOf SchemaArrayOptions - * @type Array - * @instance - */ - -Object.defineProperty(SchemaArrayOptions.prototype, 'enum', opts); - -/*! - * ignore - */ - -module.exports = SchemaArrayOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaBufferOptions.js b/node_modules/mongoose/lib/options/SchemaBufferOptions.js deleted file mode 100644 index 258130d..0000000 --- a/node_modules/mongoose/lib/options/SchemaBufferOptions.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const SchemaTypeOptions = require('./SchemaTypeOptions'); - -/** - * The options defined on a Buffer schematype. - * - * ####Example: - * - * const schema = new Schema({ bitmap: Buffer }); - * schema.path('bitmap').options; // SchemaBufferOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaBufferOptions - */ - -class SchemaBufferOptions extends SchemaTypeOptions {} - -const opts = require('./propertyOptions'); - -/** - * Set the default subtype for this buffer. - * - * @api public - * @property subtype - * @memberOf SchemaBufferOptions - * @type Number - * @instance - */ - -Object.defineProperty(SchemaBufferOptions.prototype, 'subtype', opts); - -/*! - * ignore - */ - -module.exports = SchemaBufferOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaDateOptions.js b/node_modules/mongoose/lib/options/SchemaDateOptions.js deleted file mode 100644 index 09bf27f..0000000 --- a/node_modules/mongoose/lib/options/SchemaDateOptions.js +++ /dev/null @@ -1,64 +0,0 @@ -'use strict'; - -const SchemaTypeOptions = require('./SchemaTypeOptions'); - -/** - * The options defined on a Date schematype. - * - * ####Example: - * - * const schema = new Schema({ startedAt: Date }); - * schema.path('startedAt').options; // SchemaDateOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaDateOptions - */ - -class SchemaDateOptions extends SchemaTypeOptions {} - -const opts = require('./propertyOptions'); - -/** - * If set, Mongoose adds a validator that checks that this path is after the - * given `min`. - * - * @api public - * @property min - * @memberOf SchemaDateOptions - * @type Date - * @instance - */ - -Object.defineProperty(SchemaDateOptions.prototype, 'min', opts); - -/** - * If set, Mongoose adds a validator that checks that this path is before the - * given `max`. - * - * @api public - * @property max - * @memberOf SchemaDateOptions - * @type Date - * @instance - */ - -Object.defineProperty(SchemaDateOptions.prototype, 'max', opts); - -/** - * If set, Mongoose creates a TTL index on this path. - * - * @api public - * @property expires - * @memberOf SchemaDateOptions - * @type Date - * @instance - */ - -Object.defineProperty(SchemaDateOptions.prototype, 'expires', opts); - -/*! - * ignore - */ - -module.exports = SchemaDateOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaDocumentArrayOptions.js b/node_modules/mongoose/lib/options/SchemaDocumentArrayOptions.js deleted file mode 100644 index f3fb7a9..0000000 --- a/node_modules/mongoose/lib/options/SchemaDocumentArrayOptions.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict'; - -const SchemaTypeOptions = require('./SchemaTypeOptions'); - -/** - * The options defined on an Document Array schematype. - * - * ####Example: - * - * const schema = new Schema({ users: [{ name: string }] }); - * schema.path('users').options; // SchemaDocumentArrayOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaDocumentOptions - */ - -class SchemaDocumentArrayOptions extends SchemaTypeOptions {} - -const opts = require('./propertyOptions'); - -/** - * If `true`, Mongoose will skip building any indexes defined in this array's schema. - * If not set, Mongoose will build all indexes defined in this array's schema. - * - * ####Example: - * - * const childSchema = Schema({ name: { type: String, index: true } }); - * // If `excludeIndexes` is `true`, Mongoose will skip building an index - * // on `arr.name`. Otherwise, Mongoose will build an index on `arr.name`. - * const parentSchema = Schema({ - * arr: { type: [childSchema], excludeIndexes: true } - * }); - * - * @api public - * @property excludeIndexes - * @memberOf SchemaDocumentArrayOptions - * @type Array - * @instance - */ - -Object.defineProperty(SchemaDocumentArrayOptions.prototype, 'excludeIndexes', opts); - -/** - * If set, overwrites the child schema's `_id` option. - * - * ####Example: - * - * const childSchema = Schema({ name: String }); - * const parentSchema = Schema({ - * child: { type: childSchema, _id: false } - * }); - * parentSchema.path('child').schema.options._id; // false - * - * @api public - * @property _id - * @memberOf SchemaDocumentArrayOptions - * @type Array - * @instance - */ - -Object.defineProperty(SchemaDocumentArrayOptions.prototype, '_id', opts); - -/*! - * ignore - */ - -module.exports = SchemaDocumentArrayOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaMapOptions.js b/node_modules/mongoose/lib/options/SchemaMapOptions.js deleted file mode 100644 index 335d84a..0000000 --- a/node_modules/mongoose/lib/options/SchemaMapOptions.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -const SchemaTypeOptions = require('./SchemaTypeOptions'); - -/** - * The options defined on a Map schematype. - * - * ####Example: - * - * const schema = new Schema({ socialMediaHandles: { type: Map, of: String } }); - * schema.path('socialMediaHandles').options; // SchemaMapOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaMapOptions - */ - -class SchemaMapOptions extends SchemaTypeOptions {} - -const opts = require('./propertyOptions'); - -/** - * If set, specifies the type of this map's values. Mongoose will cast - * this map's values to the given type. - * - * If not set, Mongoose will not cast the map's values. - * - * ####Example: - * - * // Mongoose will cast `socialMediaHandles` values to strings - * const schema = new Schema({ socialMediaHandles: { type: Map, of: String } }); - * schema.path('socialMediaHandles').options.of; // String - * - * @api public - * @property of - * @memberOf SchemaMapOptions - * @type Function|string - * @instance - */ - -Object.defineProperty(SchemaMapOptions.prototype, 'of', opts); - -module.exports = SchemaMapOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaNumberOptions.js b/node_modules/mongoose/lib/options/SchemaNumberOptions.js deleted file mode 100644 index 42b0a01..0000000 --- a/node_modules/mongoose/lib/options/SchemaNumberOptions.js +++ /dev/null @@ -1,74 +0,0 @@ -'use strict'; - -const SchemaTypeOptions = require('./SchemaTypeOptions'); - -/** - * The options defined on a Number schematype. - * - * ####Example: - * - * const schema = new Schema({ count: Number }); - * schema.path('count').options; // SchemaNumberOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaNumberOptions - */ - -class SchemaNumberOptions extends SchemaTypeOptions {} - -const opts = require('./propertyOptions'); - -/** - * If set, Mongoose adds a validator that checks that this path is at least the - * given `min`. - * - * @api public - * @property min - * @memberOf SchemaNumberOptions - * @type Number - * @instance - */ - -Object.defineProperty(SchemaNumberOptions.prototype, 'min', opts); - -/** - * If set, Mongoose adds a validator that checks that this path is less than the - * given `max`. - * - * @api public - * @property max - * @memberOf SchemaNumberOptions - * @type Number - * @instance - */ - -Object.defineProperty(SchemaNumberOptions.prototype, 'max', opts); - -/** - * If set, Mongoose adds a validator that checks that this path is strictly - * equal to one of the given values. - * - * ####Example: - * const schema = new Schema({ - * favoritePrime: { - * type: Number, - * enum: [3, 5, 7] - * } - * }); - * schema.path('favoritePrime').options.enum; // [3, 5, 7] - * - * @api public - * @property enum - * @memberOf SchemaNumberOptions - * @type Array - * @instance - */ - -Object.defineProperty(SchemaNumberOptions.prototype, 'enum', opts); - -/*! - * ignore - */ - -module.exports = SchemaNumberOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaObjectIdOptions.js b/node_modules/mongoose/lib/options/SchemaObjectIdOptions.js deleted file mode 100644 index cf887d0..0000000 --- a/node_modules/mongoose/lib/options/SchemaObjectIdOptions.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const SchemaTypeOptions = require('./SchemaTypeOptions'); - -/** - * The options defined on an ObjectId schematype. - * - * ####Example: - * - * const schema = new Schema({ testId: mongoose.ObjectId }); - * schema.path('testId').options; // SchemaObjectIdOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaObjectIdOptions - */ - -class SchemaObjectIdOptions extends SchemaTypeOptions {} - -const opts = require('./propertyOptions'); - -/** - * If truthy, uses Mongoose's default built-in ObjectId path. - * - * @api public - * @property auto - * @memberOf SchemaObjectIdOptions - * @type Boolean - * @instance - */ - -Object.defineProperty(SchemaObjectIdOptions.prototype, 'auto', opts); - -/*! - * ignore - */ - -module.exports = SchemaObjectIdOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaSingleNestedOptions.js b/node_modules/mongoose/lib/options/SchemaSingleNestedOptions.js deleted file mode 100644 index c916d0f..0000000 --- a/node_modules/mongoose/lib/options/SchemaSingleNestedOptions.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -const SchemaTypeOptions = require('./SchemaTypeOptions'); - -/** - * The options defined on a single nested schematype. - * - * ####Example: - * - * const schema = Schema({ child: Schema({ name: String }) }); - * schema.path('child').options; // SchemaSingleNestedOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaSingleNestedOptions - */ - -class SchemaSingleNestedOptions extends SchemaTypeOptions {} - -const opts = require('./propertyOptions'); - -/** - * If set, overwrites the child schema's `_id` option. - * - * ####Example: - * - * const childSchema = Schema({ name: String }); - * const parentSchema = Schema({ - * child: { type: childSchema, _id: false } - * }); - * parentSchema.path('child').schema.options._id; // false - * - * @api public - * @property of - * @memberOf SchemaSingleNestedOptions - * @type Function|string - * @instance - */ - -Object.defineProperty(SchemaSingleNestedOptions.prototype, '_id', opts); - -module.exports = SchemaSingleNestedOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaStringOptions.js b/node_modules/mongoose/lib/options/SchemaStringOptions.js deleted file mode 100644 index 7654993..0000000 --- a/node_modules/mongoose/lib/options/SchemaStringOptions.js +++ /dev/null @@ -1,116 +0,0 @@ -'use strict'; - -const SchemaTypeOptions = require('./SchemaTypeOptions'); - -/** - * The options defined on a string schematype. - * - * ####Example: - * - * const schema = new Schema({ name: String }); - * schema.path('name').options; // SchemaStringOptions instance - * - * @api public - * @inherits SchemaTypeOptions - * @constructor SchemaStringOptions - */ - -class SchemaStringOptions extends SchemaTypeOptions {} - -const opts = require('./propertyOptions'); - -/** - * Array of allowed values for this path - * - * @api public - * @property enum - * @memberOf SchemaStringOptions - * @type Array - * @instance - */ - -Object.defineProperty(SchemaStringOptions.prototype, 'enum', opts); - -/** - * Attach a validator that succeeds if the data string matches the given regular - * expression, and fails otherwise. - * - * @api public - * @property match - * @memberOf SchemaStringOptions - * @type RegExp - * @instance - */ - -Object.defineProperty(SchemaStringOptions.prototype, 'match', opts); - -/** - * If truthy, Mongoose will add a custom setter that lowercases this string - * using JavaScript's built-in `String#toLowerCase()`. - * - * @api public - * @property lowercase - * @memberOf SchemaStringOptions - * @type Boolean - * @instance - */ - -Object.defineProperty(SchemaStringOptions.prototype, 'lowercase', opts); - -/** - * If truthy, Mongoose will add a custom setter that removes leading and trailing - * whitespace using JavaScript's built-in `String#trim()`. - * - * @api public - * @property trim - * @memberOf SchemaStringOptions - * @type Boolean - * @instance - */ - -Object.defineProperty(SchemaStringOptions.prototype, 'trim', opts); - -/** - * If truthy, Mongoose will add a custom setter that uppercases this string - * using JavaScript's built-in `String#toUpperCase()`. - * - * @api public - * @property uppercase - * @memberOf SchemaStringOptions - * @type Boolean - * @instance - */ - -Object.defineProperty(SchemaStringOptions.prototype, 'uppercase', opts); - -/** - * If set, Mongoose will add a custom validator that ensures the given - * string's `length` is at least the given number. - * - * @api public - * @property minlength - * @memberOf SchemaStringOptions - * @type Number - * @instance - */ - -Object.defineProperty(SchemaStringOptions.prototype, 'minlength', opts); - -/** - * If set, Mongoose will add a custom validator that ensures the given - * string's `length` is at most the given number. - * - * @api public - * @property maxlength - * @memberOf SchemaStringOptions - * @type Number - * @instance - */ - -Object.defineProperty(SchemaStringOptions.prototype, 'maxlength', opts); - -/*! - * ignore - */ - -module.exports = SchemaStringOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/SchemaTypeOptions.js b/node_modules/mongoose/lib/options/SchemaTypeOptions.js deleted file mode 100644 index 5dc5995..0000000 --- a/node_modules/mongoose/lib/options/SchemaTypeOptions.js +++ /dev/null @@ -1,232 +0,0 @@ -'use strict'; - -const clone = require('../helpers/clone'); - -/** - * The options defined on a schematype. - * - * ####Example: - * - * const schema = new Schema({ name: String }); - * schema.path('name').options instanceof mongoose.SchemaTypeOptions; // true - * - * @api public - * @constructor SchemaTypeOptions - */ - -class SchemaTypeOptions { - constructor(obj) { - if (obj == null) { - return this; - } - Object.assign(this, clone(obj)); - } -} - -const opts = require('./propertyOptions'); - -/** - * The type to cast this path to. - * - * @api public - * @property type - * @memberOf SchemaTypeOptions - * @type Function|String|Object - * @instance - */ - -Object.defineProperty(SchemaTypeOptions.prototype, 'type', opts); - -/** - * Function or object describing how to validate this schematype. - * - * @api public - * @property validate - * @memberOf SchemaTypeOptions - * @type Function|Object - * @instance - */ - -Object.defineProperty(SchemaTypeOptions.prototype, 'validate', opts); - -/** - * Allows overriding casting logic for this individual path. If a string, the - * given string overwrites Mongoose's default cast error message. - * - * ####Example: - * - * const schema = new Schema({ - * num: { - * type: Number, - * cast: '{VALUE} is not a valid number' - * } - * }); - * - * // Throws 'CastError: "bad" is not a valid number' - * schema.path('num').cast('bad'); - * - * const Model = mongoose.model('Test', schema); - * const doc = new Model({ num: 'fail' }); - * const err = doc.validateSync(); - * - * err.errors['num']; // 'CastError: "fail" is not a valid number' - * - * @api public - * @property cast - * @memberOf SchemaTypeOptions - * @type String - * @instance - */ - -Object.defineProperty(SchemaTypeOptions.prototype, 'cast', opts); - -/** - * If true, attach a required validator to this path, which ensures this path - * path cannot be set to a nullish value. If a function, Mongoose calls the - * function and only checks for nullish values if the function returns a truthy value. - * - * @api public - * @property required - * @memberOf SchemaTypeOptions - * @type Function|Boolean - * @instance - */ - -Object.defineProperty(SchemaTypeOptions.prototype, 'required', opts); - -/** - * The default value for this path. If a function, Mongoose executes the function - * and uses the return value as the default. - * - * @api public - * @property default - * @memberOf SchemaTypeOptions - * @type Function|Any - * @instance - */ - -Object.defineProperty(SchemaTypeOptions.prototype, 'default', opts); - -/** - * The model that `populate()` should use if populating this path. - * - * @api public - * @property ref - * @memberOf SchemaTypeOptions - * @type Function|String - * @instance - */ - -Object.defineProperty(SchemaTypeOptions.prototype, 'ref', opts); - -/** - * Whether to include or exclude this path by default when loading documents - * using `find()`, `findOne()`, etc. - * - * @api public - * @property select - * @memberOf SchemaTypeOptions - * @type Boolean|Number - * @instance - */ - -Object.defineProperty(SchemaTypeOptions.prototype, 'select', opts); - -/** - * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will - * build an index on this path when the model is - * compiled. - * - * @api public - * @property index - * @memberOf SchemaTypeOptions - * @type Boolean|Number|Object - * @instance - */ - -Object.defineProperty(SchemaTypeOptions.prototype, 'index', opts); - -/** - * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose - * will build a unique index on this path when the - * model is compiled. [The `unique` option is **not** a validator](/docs/validation.html#the-unique-option-is-not-a-validator). - * - * @api public - * @property unique - * @memberOf SchemaTypeOptions - * @type Boolean|Number - * @instance - */ - -Object.defineProperty(SchemaTypeOptions.prototype, 'unique', opts); - -/** - * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will - * disallow changes to this path once the document - * is saved to the database for the first time. Read more about [immutability in Mongoose here](http://thecodebarbarian.com/whats-new-in-mongoose-5-6-immutable-properties.html). - * - * @api public - * @property immutable - * @memberOf SchemaTypeOptions - * @type Function|Boolean - * @instance - */ - -Object.defineProperty(SchemaTypeOptions.prototype, 'immutable', opts); - -/** - * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose will - * build a sparse index on this path. - * - * @api public - * @property sparse - * @memberOf SchemaTypeOptions - * @type Boolean|Number - * @instance - */ - -Object.defineProperty(SchemaTypeOptions.prototype, 'sparse', opts); - -/** - * If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), Mongoose - * will build a text index on this path. - * - * @api public - * @property text - * @memberOf SchemaTypeOptions - * @type Boolean|Number|Object - * @instance - */ - -Object.defineProperty(SchemaTypeOptions.prototype, 'text', opts); - -/** - * Define a transform function for this individual schema type. - * Only called when calling `toJSON()` or `toObject()`. - * - * ####Example: - * - * const schema = Schema({ - * myDate: { - * type: Date, - * transform: v => v.getFullYear() - * } - * }); - * const Model = mongoose.model('Test', schema); - * - * const doc = new Model({ myDate: new Date('2019/06/01') }); - * doc.myDate instanceof Date; // true - * - * const res = doc.toObject({ transform: true }); - * res.myDate; // 2019 - * - * @api public - * @property transform - * @memberOf SchemaTypeOptions - * @type Function - * @instance - */ - -Object.defineProperty(SchemaTypeOptions.prototype, 'transform', opts); - -module.exports = SchemaTypeOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/VirtualOptions.js b/node_modules/mongoose/lib/options/VirtualOptions.js deleted file mode 100644 index a266414..0000000 --- a/node_modules/mongoose/lib/options/VirtualOptions.js +++ /dev/null @@ -1,164 +0,0 @@ -'use strict'; - -const opts = require('./propertyOptions'); - -class VirtualOptions { - constructor(obj) { - Object.assign(this, obj); - - if (obj != null && obj.options != null) { - this.options = Object.assign({}, obj.options); - } - } -} - -/** - * Marks this virtual as a populate virtual, and specifies the model to - * use for populate. - * - * @api public - * @property ref - * @memberOf VirtualOptions - * @type String|Model|Function - * @instance - */ - -Object.defineProperty(VirtualOptions.prototype, 'ref', opts); - -/** - * Marks this virtual as a populate virtual, and specifies the path that - * contains the name of the model to populate - * - * @api public - * @property refPath - * @memberOf VirtualOptions - * @type String|Function - * @instance - */ - -Object.defineProperty(VirtualOptions.prototype, 'refPath', opts); - -/** - * The name of the property in the local model to match to `foreignField` - * in the foreign model. - * - * @api public - * @property localField - * @memberOf VirtualOptions - * @type String|Function - * @instance - */ - -Object.defineProperty(VirtualOptions.prototype, 'localField', opts); - -/** - * The name of the property in the foreign model to match to `localField` - * in the local model. - * - * @api public - * @property foreignField - * @memberOf VirtualOptions - * @type String|Function - * @instance - */ - -Object.defineProperty(VirtualOptions.prototype, 'foreignField', opts); - -/** - * Whether to populate this virtual as a single document (true) or an - * array of documents (false). - * - * @api public - * @property justOne - * @memberOf VirtualOptions - * @type Boolean - * @instance - */ - -Object.defineProperty(VirtualOptions.prototype, 'justOne', opts); - -/** - * If true, populate just the number of documents where `localField` - * matches `foreignField`, as opposed to the documents themselves. - * - * If `count` is set, it overrides `justOne`. - * - * @api public - * @property count - * @memberOf VirtualOptions - * @type Boolean - * @instance - */ - -Object.defineProperty(VirtualOptions.prototype, 'count', opts); - -/** - * Add an additional filter to populate, in addition to `localField` - * matches `foreignField`. - * - * @api public - * @property match - * @memberOf VirtualOptions - * @type Object|Function - * @instance - */ - -Object.defineProperty(VirtualOptions.prototype, 'match', opts); - -/** - * Additional options to pass to the query used to `populate()`: - * - * - `sort` - * - `skip` - * - `limit` - * - * @api public - * @property options - * @memberOf VirtualOptions - * @type Object - * @instance - */ - -Object.defineProperty(VirtualOptions.prototype, 'options', opts); - -/** - * If true, add a `skip` to the query used to `populate()`. - * - * @api public - * @property skip - * @memberOf VirtualOptions - * @type Number - * @instance - */ - -Object.defineProperty(VirtualOptions.prototype, 'skip', opts); - -/** - * If true, add a `limit` to the query used to `populate()`. - * - * @api public - * @property limit - * @memberOf VirtualOptions - * @type Number - * @instance - */ - -Object.defineProperty(VirtualOptions.prototype, 'limit', opts); - -/** - * The `limit` option for `populate()` has [some unfortunate edge cases](/docs/populate.html#query-conditions) - * when working with multiple documents, like `.find().populate()`. The - * `perDocumentLimit` option makes `populate()` execute a separate query - * for each document returned from `find()` to ensure each document - * gets up to `perDocumentLimit` populated docs if possible. - * - * @api public - * @property perDocumentLimit - * @memberOf VirtualOptions - * @type Number - * @instance - */ - -Object.defineProperty(VirtualOptions.prototype, 'perDocumentLimit', opts); - -module.exports = VirtualOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/propertyOptions.js b/node_modules/mongoose/lib/options/propertyOptions.js deleted file mode 100644 index b7488a3..0000000 --- a/node_modules/mongoose/lib/options/propertyOptions.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -module.exports = Object.freeze({ - enumerable: true, - configurable: true, - writable: true, - value: void 0 -}); \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/removeOptions.js b/node_modules/mongoose/lib/options/removeOptions.js deleted file mode 100644 index 0d91586..0000000 --- a/node_modules/mongoose/lib/options/removeOptions.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -const clone = require('../helpers/clone'); - -class RemoveOptions { - constructor(obj) { - if (obj == null) { - return; - } - Object.assign(this, clone(obj)); - } -} - -module.exports = RemoveOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/options/saveOptions.js b/node_modules/mongoose/lib/options/saveOptions.js deleted file mode 100644 index 22ef437..0000000 --- a/node_modules/mongoose/lib/options/saveOptions.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -const clone = require('../helpers/clone'); - -class SaveOptions { - constructor(obj) { - if (obj == null) { - return; - } - Object.assign(this, clone(obj)); - } -} - -module.exports = SaveOptions; \ No newline at end of file diff --git a/node_modules/mongoose/lib/plugins/idGetter.js b/node_modules/mongoose/lib/plugins/idGetter.js deleted file mode 100644 index f4e6356..0000000 --- a/node_modules/mongoose/lib/plugins/idGetter.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function(schema) { - // ensure the documents receive an id getter unless disabled - const autoIdGetter = !schema.paths['id'] && - (!schema.options.noVirtualId && schema.options.id); - if (!autoIdGetter) { - return; - } - - schema.virtual('id').get(idGetter); -}; - -/*! - * Returns this documents _id cast to a string. - */ - -function idGetter() { - if (this._id != null) { - return String(this._id); - } - - return null; -} diff --git a/node_modules/mongoose/lib/plugins/removeSubdocs.js b/node_modules/mongoose/lib/plugins/removeSubdocs.js deleted file mode 100644 index 44b2ea6..0000000 --- a/node_modules/mongoose/lib/plugins/removeSubdocs.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -const each = require('../helpers/each'); - -/*! - * ignore - */ - -module.exports = function(schema) { - const unshift = true; - schema.s.hooks.pre('remove', false, function(next) { - if (this.ownerDocument) { - next(); - return; - } - - const _this = this; - const subdocs = this.$__getAllSubdocs(); - - each(subdocs, function(subdoc, cb) { - subdoc.$__remove(cb); - }, function(error) { - if (error) { - return _this.schema.s.hooks.execPost('remove:error', _this, [_this], { error: error }, function(error) { - next(error); - }); - } - next(); - }); - }, null, unshift); -}; diff --git a/node_modules/mongoose/lib/plugins/saveSubdocs.js b/node_modules/mongoose/lib/plugins/saveSubdocs.js deleted file mode 100644 index c0a3144..0000000 --- a/node_modules/mongoose/lib/plugins/saveSubdocs.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -const each = require('../helpers/each'); - -/*! - * ignore - */ - -module.exports = function(schema) { - const unshift = true; - schema.s.hooks.pre('save', false, function(next) { - if (this.ownerDocument) { - next(); - return; - } - - const _this = this; - const subdocs = this.$__getAllSubdocs(); - - if (!subdocs.length) { - next(); - return; - } - - each(subdocs, function(subdoc, cb) { - subdoc.schema.s.hooks.execPre('save', subdoc, function(err) { - cb(err); - }); - }, function(error) { - if (error) { - return _this.schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) { - next(error); - }); - } - next(); - }); - }, null, unshift); - - schema.s.hooks.post('save', function(doc, next) { - if (this.ownerDocument) { - next(); - return; - } - - const _this = this; - const subdocs = this.$__getAllSubdocs(); - - if (!subdocs.length) { - next(); - return; - } - - each(subdocs, function(subdoc, cb) { - subdoc.schema.s.hooks.execPost('save', subdoc, [subdoc], function(err) { - cb(err); - }); - }, function(error) { - if (error) { - return _this.schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) { - next(error); - }); - } - next(); - }); - }, null, unshift); -}; diff --git a/node_modules/mongoose/lib/plugins/sharding.js b/node_modules/mongoose/lib/plugins/sharding.js deleted file mode 100644 index 560053e..0000000 --- a/node_modules/mongoose/lib/plugins/sharding.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict'; - -const objectIdSymbol = require('../helpers/symbols').objectIdSymbol; -const utils = require('../utils'); - -/*! - * ignore - */ - -module.exports = function shardingPlugin(schema) { - schema.post('init', function() { - storeShard.call(this); - return this; - }); - schema.pre('save', function(next) { - applyWhere.call(this); - next(); - }); - schema.pre('remove', function(next) { - applyWhere.call(this); - next(); - }); - schema.post('save', function() { - storeShard.call(this); - }); -}; - -/*! - * ignore - */ - -function applyWhere() { - let paths; - let len; - - if (this.$__.shardval) { - paths = Object.keys(this.$__.shardval); - len = paths.length; - - this.$where = this.$where || {}; - for (let i = 0; i < len; ++i) { - this.$where[paths[i]] = this.$__.shardval[paths[i]]; - } - } -} - -/*! - * ignore - */ - -module.exports.storeShard = storeShard; - -/*! - * ignore - */ - -function storeShard() { - // backwards compat - const key = this.schema.options.shardKey || this.schema.options.shardkey; - if (!utils.isPOJO(key)) { - return; - } - - const orig = this.$__.shardval = {}; - const paths = Object.keys(key); - const len = paths.length; - let val; - - for (let i = 0; i < len; ++i) { - val = this.$__getValue(paths[i]); - if (val == null) { - orig[paths[i]] = val; - } else if (utils.isMongooseObject(val)) { - orig[paths[i]] = val.toObject({ depopulate: true, _isNested: true }); - } else if (val instanceof Date || val[objectIdSymbol]) { - orig[paths[i]] = val; - } else if (typeof val.valueOf === 'function') { - orig[paths[i]] = val.valueOf(); - } else { - orig[paths[i]] = val; - } - } -} diff --git a/node_modules/mongoose/lib/plugins/validateBeforeSave.js b/node_modules/mongoose/lib/plugins/validateBeforeSave.js deleted file mode 100644 index 4635de1..0000000 --- a/node_modules/mongoose/lib/plugins/validateBeforeSave.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function(schema) { - const unshift = true; - schema.pre('save', false, function validateBeforeSave(next, options) { - const _this = this; - // Nested docs have their own presave - if (this.ownerDocument) { - return next(); - } - - const hasValidateBeforeSaveOption = options && - (typeof options === 'object') && - ('validateBeforeSave' in options); - - let shouldValidate; - if (hasValidateBeforeSaveOption) { - shouldValidate = !!options.validateBeforeSave; - } else { - shouldValidate = this.schema.options.validateBeforeSave; - } - - // Validate - if (shouldValidate) { - const hasValidateModifiedOnlyOption = options && - (typeof options === 'object') && - ('validateModifiedOnly' in options); - const validateOptions = hasValidateModifiedOnlyOption ? - { validateModifiedOnly: options.validateModifiedOnly } : - null; - this.validate(validateOptions, function(error) { - return _this.schema.s.hooks.execPost('save:error', _this, [_this], { error: error }, function(error) { - _this.$op = 'save'; - next(error); - }); - }); - } else { - next(); - } - }, null, unshift); -}; diff --git a/node_modules/mongoose/lib/promise_provider.js b/node_modules/mongoose/lib/promise_provider.js deleted file mode 100644 index 3febf36..0000000 --- a/node_modules/mongoose/lib/promise_provider.js +++ /dev/null @@ -1,49 +0,0 @@ -/*! - * ignore - */ - -'use strict'; - -const assert = require('assert'); -const mquery = require('mquery'); - -/** - * Helper for multiplexing promise implementations - * - * @api private - */ - -const store = { - _promise: null -}; - -/** - * Get the current promise constructor - * - * @api private - */ - -store.get = function() { - return store._promise; -}; - -/** - * Set the current promise constructor - * - * @api private - */ - -store.set = function(lib) { - assert.ok(typeof lib === 'function', - `mongoose.Promise must be a function, got ${lib}`); - store._promise = lib; - mquery.Promise = lib; -}; - -/*! - * Use native promises by default - */ - -store.set(global.Promise); - -module.exports = store; diff --git a/node_modules/mongoose/lib/query.js b/node_modules/mongoose/lib/query.js deleted file mode 100644 index de1686e..0000000 --- a/node_modules/mongoose/lib/query.js +++ /dev/null @@ -1,5359 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const CastError = require('./error/cast'); -const DocumentNotFoundError = require('./error/notFound'); -const Kareem = require('kareem'); -const MongooseError = require('./error/mongooseError'); -const ObjectParameterError = require('./error/objectParameter'); -const QueryCursor = require('./cursor/QueryCursor'); -const ReadPreference = require('./driver').get().ReadPreference; -const applyGlobalMaxTimeMS = require('./helpers/query/applyGlobalMaxTimeMS'); -const applyWriteConcern = require('./helpers/schema/applyWriteConcern'); -const cast = require('./cast'); -const castArrayFilters = require('./helpers/update/castArrayFilters'); -const castUpdate = require('./helpers/query/castUpdate'); -const completeMany = require('./helpers/query/completeMany'); -const get = require('./helpers/get'); -const promiseOrCallback = require('./helpers/promiseOrCallback'); -const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue'); -const hasDollarKeys = require('./helpers/query/hasDollarKeys'); -const helpers = require('./queryhelpers'); -const isInclusive = require('./helpers/projection/isInclusive'); -const mquery = require('mquery'); -const parseProjection = require('./helpers/projection/parseProjection'); -const selectPopulatedFields = require('./helpers/query/selectPopulatedFields'); -const setDefaultsOnInsert = require('./helpers/setDefaultsOnInsert'); -const slice = require('sliced'); -const updateValidators = require('./helpers/updateValidators'); -const util = require('util'); -const utils = require('./utils'); -const wrapThunk = require('./helpers/query/wrapThunk'); - -/** - * Query constructor used for building queries. You do not need - * to instantiate a `Query` directly. Instead use Model functions like - * [`Model.find()`](/docs/api.html#find_find). - * - * ####Example: - * - * const query = MyModel.find(); // `query` is an instance of `Query` - * query.setOptions({ lean : true }); - * query.collection(MyModel.collection); - * query.where('age').gte(21).exec(callback); - * - * // You can instantiate a query directly. There is no need to do - * // this unless you're an advanced user with a very good reason to. - * const query = new mongoose.Query(); - * - * @param {Object} [options] - * @param {Object} [model] - * @param {Object} [conditions] - * @param {Object} [collection] Mongoose collection - * @api public - */ - -function Query(conditions, options, model, collection) { - // this stuff is for dealing with custom queries created by #toConstructor - if (!this._mongooseOptions) { - this._mongooseOptions = {}; - } - options = options || {}; - - this._transforms = []; - this._hooks = new Kareem(); - this._executionCount = 0; - - // this is the case where we have a CustomQuery, we need to check if we got - // options passed in, and if we did, merge them in - const keys = Object.keys(options); - for (const key of keys) { - this._mongooseOptions[key] = options[key]; - } - - if (collection) { - this.mongooseCollection = collection; - } - - if (model) { - this.model = model; - this.schema = model.schema; - } - - // this is needed because map reduce returns a model that can be queried, but - // all of the queries on said model should be lean - if (this.model && this.model._mapreduce) { - this.lean(); - } - - // inherit mquery - mquery.call(this, this.mongooseCollection, options); - - if (conditions) { - this.find(conditions); - } - - this.options = this.options || {}; - - // For gh-6880. mquery still needs to support `fields` by default for old - // versions of MongoDB - this.$useProjection = true; - - const collation = get(this, 'schema.options.collation', null); - if (collation != null) { - this.options.collation = collation; - } -} - -/*! - * inherit mquery - */ - -Query.prototype = new mquery; -Query.prototype.constructor = Query; -Query.base = mquery.prototype; - -/** - * Flag to opt out of using `$geoWithin`. - * - * mongoose.Query.use$geoWithin = false; - * - * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with `$within`). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work. - * - * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/ - * @default true - * @property use$geoWithin - * @memberOf Query - * @receiver Query - * @api public - */ - -Query.use$geoWithin = mquery.use$geoWithin; - -/** - * Converts this query to a customized, reusable query constructor with all arguments and options retained. - * - * ####Example - * - * // Create a query for adventure movies and read from the primary - * // node in the replica-set unless it is down, in which case we'll - * // read from a secondary node. - * var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred'); - * - * // create a custom Query constructor based off these settings - * var Adventure = query.toConstructor(); - * - * // Adventure is now a subclass of mongoose.Query and works the same way but with the - * // default query parameters and options set. - * Adventure().exec(callback) - * - * // further narrow down our query results while still using the previous settings - * Adventure().where({ name: /^Life/ }).exec(callback); - * - * // since Adventure is a stand-alone constructor we can also add our own - * // helper methods and getters without impacting global queries - * Adventure.prototype.startsWith = function (prefix) { - * this.where({ name: new RegExp('^' + prefix) }) - * return this; - * } - * Object.defineProperty(Adventure.prototype, 'highlyRated', { - * get: function () { - * this.where({ rating: { $gt: 4.5 }}); - * return this; - * } - * }) - * Adventure().highlyRated.startsWith('Life').exec(callback) - * - * @return {Query} subclass-of-Query - * @api public - */ - -Query.prototype.toConstructor = function toConstructor() { - const model = this.model; - const coll = this.mongooseCollection; - - const CustomQuery = function(criteria, options) { - if (!(this instanceof CustomQuery)) { - return new CustomQuery(criteria, options); - } - this._mongooseOptions = utils.clone(p._mongooseOptions); - Query.call(this, criteria, options || null, model, coll); - }; - - util.inherits(CustomQuery, model.Query); - - // set inherited defaults - const p = CustomQuery.prototype; - - p.options = {}; - - // Need to handle `sort()` separately because entries-style `sort()` syntax - // `sort([['prop1', 1]])` confuses mquery into losing the outer nested array. - // See gh-8159 - const options = Object.assign({}, this.options); - if (options.sort != null) { - p.sort(options.sort); - delete options.sort; - } - p.setOptions(options); - - p.op = this.op; - p._conditions = utils.clone(this._conditions); - p._fields = utils.clone(this._fields); - p._update = utils.clone(this._update, { - flattenDecimals: false - }); - p._path = this._path; - p._distinct = this._distinct; - p._collection = this._collection; - p._mongooseOptions = this._mongooseOptions; - - return CustomQuery; -}; - -/** - * Specifies a javascript function or expression to pass to MongoDBs query system. - * - * ####Example - * - * query.$where('this.comments.length === 10 || this.name.length === 5') - * - * // or - * - * query.$where(function () { - * return this.comments.length === 10 || this.name.length === 5; - * }) - * - * ####NOTE: - * - * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. - * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.** - * - * @see $where http://docs.mongodb.org/manual/reference/operator/where/ - * @method $where - * @param {String|Function} js javascript string or function - * @return {Query} this - * @memberOf Query - * @instance - * @method $where - * @api public - */ - -/** - * Specifies a `path` for use with chaining. - * - * ####Example - * - * // instead of writing: - * User.find({age: {$gte: 21, $lte: 65}}, callback); - * - * // we can instead write: - * User.where('age').gte(21).lte(65); - * - * // passing query conditions is permitted - * User.find().where({ name: 'vonderful' }) - * - * // chaining - * User - * .where('age').gte(21).lte(65) - * .where('name', /^vonderful/i) - * .where('friends').slice(10) - * .exec(callback) - * - * @method where - * @memberOf Query - * @instance - * @param {String|Object} [path] - * @param {any} [val] - * @return {Query} this - * @api public - */ - -Query.prototype.slice = function() { - if (arguments.length === 0) { - return this; - } - - this._validate('slice'); - - let path; - let val; - - if (arguments.length === 1) { - const arg = arguments[0]; - if (typeof arg === 'object' && !Array.isArray(arg)) { - const keys = Object.keys(arg); - const numKeys = keys.length; - for (let i = 0; i < numKeys; ++i) { - this.slice(keys[i], arg[keys[i]]); - } - return this; - } - this._ensurePath('slice'); - path = this._path; - val = arguments[0]; - } else if (arguments.length === 2) { - if ('number' === typeof arguments[0]) { - this._ensurePath('slice'); - path = this._path; - val = slice(arguments); - } else { - path = arguments[0]; - val = arguments[1]; - } - } else if (arguments.length === 3) { - path = arguments[0]; - val = slice(arguments, 1); - } - - const p = {}; - p[path] = { $slice: val }; - this.select(p); - - return this; -}; - - -/** - * Specifies the complementary comparison value for paths specified with `where()` - * - * ####Example - * - * User.where('age').equals(49); - * - * // is the same as - * - * User.where('age', 49); - * - * @method equals - * @memberOf Query - * @instance - * @param {Object} val - * @return {Query} this - * @api public - */ - -/** - * Specifies arguments for an `$or` condition. - * - * ####Example - * - * query.or([{ color: 'red' }, { status: 'emergency' }]) - * - * @see $or http://docs.mongodb.org/manual/reference/operator/or/ - * @method or - * @memberOf Query - * @instance - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -/** - * Specifies arguments for a `$nor` condition. - * - * ####Example - * - * query.nor([{ color: 'green' }, { status: 'ok' }]) - * - * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/ - * @method nor - * @memberOf Query - * @instance - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -/** - * Specifies arguments for a `$and` condition. - * - * ####Example - * - * query.and([{ color: 'green' }, { status: 'ok' }]) - * - * @method and - * @memberOf Query - * @instance - * @see $and http://docs.mongodb.org/manual/reference/operator/and/ - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -/** - * Specifies a `$gt` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example - * - * Thing.find().where('age').gt(21) - * - * // or - * Thing.find().gt('age', 21) - * - * @method gt - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/ - * @api public - */ - -/** - * Specifies a `$gte` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method gte - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/ - * @api public - */ - -/** - * Specifies a `$lt` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lt - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/ - * @api public - */ - -/** - * Specifies a `$lte` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lte - * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/ - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a `$ne` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/ - * @method ne - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an `$in` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $in http://docs.mongodb.org/manual/reference/operator/in/ - * @method in - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an `$nin` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/ - * @method nin - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an `$all` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example: - * - * MyModel.find().where('pets').all(['dog', 'cat', 'ferret']); - * // Equivalent: - * MyModel.find().all('pets', ['dog', 'cat', 'ferret']); - * - * @see $all http://docs.mongodb.org/manual/reference/operator/all/ - * @method all - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Array} val - * @api public - */ - -/** - * Specifies a `$size` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example - * - * MyModel.where('tags').size(0).exec(function (err, docs) { - * if (err) return handleError(err); - * - * assert(Array.isArray(docs)); - * console.log('documents with 0 tags', docs); - * }) - * - * @see $size http://docs.mongodb.org/manual/reference/operator/size/ - * @method size - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a `$regex` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/ - * @method regex - * @memberOf Query - * @instance - * @param {String} [path] - * @param {String|RegExp} val - * @api public - */ - -/** - * Specifies a `maxDistance` query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - * @method maxDistance - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a `$mod` condition, filters documents for documents whose - * `path` property is a number that is equal to `remainder` modulo `divisor`. - * - * ####Example - * - * // All find products whose inventory is odd - * Product.find().mod('inventory', [2, 1]); - * Product.find().where('inventory').mod([2, 1]); - * // This syntax is a little strange, but supported. - * Product.find().where('inventory').mod(2, 1); - * - * @method mod - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Array} val must be of length 2, first element is `divisor`, 2nd element is `remainder`. - * @return {Query} this - * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/ - * @api public - */ - -Query.prototype.mod = function() { - let val; - let path; - - if (arguments.length === 1) { - this._ensurePath('mod'); - val = arguments[0]; - path = this._path; - } else if (arguments.length === 2 && !Array.isArray(arguments[1])) { - this._ensurePath('mod'); - val = slice(arguments); - path = this._path; - } else if (arguments.length === 3) { - val = slice(arguments, 1); - path = arguments[0]; - } else { - val = arguments[1]; - path = arguments[0]; - } - - const conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$mod = val; - return this; -}; - -/** - * Specifies an `$exists` condition - * - * ####Example - * - * // { name: { $exists: true }} - * Thing.where('name').exists() - * Thing.where('name').exists(true) - * Thing.find().exists('name') - * - * // { name: { $exists: false }} - * Thing.where('name').exists(false); - * Thing.find().exists('name', false); - * - * @method exists - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/ - * @api public - */ - -/** - * Specifies an `$elemMatch` condition - * - * ####Example - * - * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) - * - * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) - * - * query.elemMatch('comment', function (elem) { - * elem.where('author').equals('autobot'); - * elem.where('votes').gte(5); - * }) - * - * query.where('comment').elemMatch(function (elem) { - * elem.where({ author: 'autobot' }); - * elem.where('votes').gte(5); - * }) - * - * @method elemMatch - * @memberOf Query - * @instance - * @param {String|Object|Function} path - * @param {Object|Function} filter - * @return {Query} this - * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/ - * @api public - */ - -/** - * Defines a `$within` or `$geoWithin` argument for geo-spatial queries. - * - * ####Example - * - * query.where(path).within().box() - * query.where(path).within().circle() - * query.where(path).within().geometry() - * - * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); - * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); - * query.where('loc').within({ polygon: [[],[],[],[]] }); - * - * query.where('loc').within([], [], []) // polygon - * query.where('loc').within([], []) // box - * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry - * - * **MUST** be used after `where()`. - * - * ####NOTE: - * - * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin). - * - * ####NOTE: - * - * In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). - * - * @method within - * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ - * @see $box http://docs.mongodb.org/manual/reference/operator/box/ - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see $center http://docs.mongodb.org/manual/reference/operator/center/ - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @memberOf Query - * @instance - * @return {Query} this - * @api public - */ - -/** - * Specifies a `$slice` projection for an array. - * - * ####Example - * - * query.slice('comments', 5) - * query.slice('comments', -5) - * query.slice('comments', [10, 5]) - * query.where('comments').slice(5) - * query.where('comments').slice([-10, 5]) - * - * @method slice - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Number} val number/range of elements to slice - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements - * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice - * @api public - */ - -/** - * Specifies the maximum number of documents the query will return. - * - * ####Example - * - * query.limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method limit - * @memberOf Query - * @instance - * @param {Number} val - * @api public - */ - -/** - * Specifies the number of documents to skip. - * - * ####Example - * - * query.skip(100).limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method skip - * @memberOf Query - * @instance - * @param {Number} val - * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/ - * @api public - */ - -/** - * Specifies the maxScan option. - * - * ####Example - * - * query.maxScan(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method maxScan - * @memberOf Query - * @instance - * @param {Number} val - * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/ - * @api public - */ - -/** - * Specifies the batchSize option. - * - * ####Example - * - * query.batchSize(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method batchSize - * @memberOf Query - * @instance - * @param {Number} val - * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/ - * @api public - */ - -/** - * Specifies the `comment` option. - * - * ####Example - * - * query.comment('login query') - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method comment - * @memberOf Query - * @instance - * @param {String} val - * @see comment http://docs.mongodb.org/manual/reference/operator/comment/ - * @api public - */ - -/** - * Specifies this query as a `snapshot` query. - * - * ####Example - * - * query.snapshot() // true - * query.snapshot(true) - * query.snapshot(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method snapshot - * @memberOf Query - * @instance - * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/ - * @return {Query} this - * @api public - */ - -/** - * Sets query hints. - * - * ####Example - * - * query.hint({ indexA: 1, indexB: -1}) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method hint - * @memberOf Query - * @instance - * @param {Object} val a hint object - * @return {Query} this - * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/ - * @api public - */ - -/** - * Get/set the current projection (AKA fields). Pass `null` to remove the - * current projection. - * - * Unlike `projection()`, the `select()` function modifies the current - * projection in place. This function overwrites the existing projection. - * - * ####Example: - * - * const q = Model.find(); - * q.projection(); // null - * - * q.select('a b'); - * q.projection(); // { a: 1, b: 1 } - * - * q.projection({ c: 1 }); - * q.projection(); // { c: 1 } - * - * q.projection(null); - * q.projection(); // null - * - * - * @method projection - * @memberOf Query - * @instance - * @param {Object|null} arg - * @return {Object} the current projection - * @api public - */ - -Query.prototype.projection = function(arg) { - if (arguments.length === 0) { - return this._fields; - } - - this._fields = {}; - this._userProvidedFields = {}; - this.select(arg); - return this._fields; -}; - -/** - * Specifies which document fields to include or exclude (also known as the query "projection") - * - * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select). - * - * A projection _must_ be either inclusive or exclusive. In other words, you must - * either list the fields to include (which excludes all others), or list the fields - * to exclude (which implies all other fields are included). The [`_id` field is the only exception because MongoDB includes it by default](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#suppress-id-field). - * - * ####Example - * - * // include a and b, exclude other fields - * query.select('a b'); - * - * // exclude c and d, include other fields - * query.select('-c -d'); - * - * // Use `+` to override schema-level `select: false` without making the - * // projection inclusive. - * const schema = new Schema({ - * foo: { type: String, select: false }, - * bar: String - * }); - * // ... - * query.select('+foo'); // Override foo's `select: false` without excluding `bar` - * - * // or you may use object notation, useful when - * // you have keys already prefixed with a "-" - * query.select({ a: 1, b: 1 }); - * query.select({ c: 0, d: 0 }); - * - * - * @method select - * @memberOf Query - * @instance - * @param {Object|String} arg - * @return {Query} this - * @see SchemaType - * @api public - */ - -Query.prototype.select = function select() { - let arg = arguments[0]; - if (!arg) return this; - let i; - - if (arguments.length !== 1) { - throw new Error('Invalid select: select only takes 1 argument'); - } - - this._validate('select'); - - const fields = this._fields || (this._fields = {}); - const userProvidedFields = this._userProvidedFields || (this._userProvidedFields = {}); - - arg = parseProjection(arg); - - if (utils.isObject(arg)) { - const keys = Object.keys(arg); - for (i = 0; i < keys.length; ++i) { - fields[keys[i]] = arg[keys[i]]; - userProvidedFields[keys[i]] = arg[keys[i]]; - } - return this; - } - - throw new TypeError('Invalid select() argument. Must be string or object.'); -}; - -/** - * _DEPRECATED_ Sets the slaveOk option. - * - * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read). - * - * ####Example: - * - * query.slaveOk() // true - * query.slaveOk(true) - * query.slaveOk(false) - * - * @method slaveOk - * @memberOf Query - * @instance - * @deprecated use read() preferences instead if on mongodb >= 2.2 - * @param {Boolean} v defaults to true - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/ - * @see read() #query_Query-read - * @return {Query} this - * @api public - */ - -/** - * Determines the MongoDB nodes from which to read. - * - * ####Preferences: - * - * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. - * secondary Read from secondary if available, otherwise error. - * primaryPreferred Read from primary if available, otherwise a secondary. - * secondaryPreferred Read from a secondary if available, otherwise read from the primary. - * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. - * - * Aliases - * - * p primary - * pp primaryPreferred - * s secondary - * sp secondaryPreferred - * n nearest - * - * ####Example: - * - * new Query().read('primary') - * new Query().read('p') // same as primary - * - * new Query().read('primaryPreferred') - * new Query().read('pp') // same as primaryPreferred - * - * new Query().read('secondary') - * new Query().read('s') // same as secondary - * - * new Query().read('secondaryPreferred') - * new Query().read('sp') // same as secondaryPreferred - * - * new Query().read('nearest') - * new Query().read('n') // same as nearest - * - * // read from secondaries with matching tags - * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) - * - * Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). - * - * @method read - * @memberOf Query - * @instance - * @param {String} pref one of the listed preference options or aliases - * @param {Array} [tags] optional tags for this query - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences - * @return {Query} this - * @api public - */ - -Query.prototype.read = function read(pref, tags) { - // first cast into a ReadPreference object to support tags - const read = new ReadPreference(pref, tags); - this.options.readPreference = read; - return this; -}; - -/** - * Sets the [MongoDB session](https://docs.mongodb.com/manual/reference/server-sessions/) - * associated with this query. Sessions are how you mark a query as part of a - * [transaction](/docs/transactions.html). - * - * Calling `session(null)` removes the session from this query. - * - * ####Example: - * - * const s = await mongoose.startSession(); - * await mongoose.model('Person').findOne({ name: 'Axl Rose' }).session(s); - * - * @method session - * @memberOf Query - * @instance - * @param {ClientSession} [session] from `await conn.startSession()` - * @see Connection.prototype.startSession() /docs/api.html#connection_Connection-startSession - * @see mongoose.startSession() /docs/api.html#mongoose_Mongoose-startSession - * @return {Query} this - * @api public - */ - -Query.prototype.session = function session(v) { - if (v == null) { - delete this.options.session; - } - this.options.session = v; - return this; -}; - -/** - * Sets the specified number of `mongod` servers, or tag set of `mongod` servers, - * that must acknowledge this write before this write is considered successful. - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndReplace()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the schema's [`writeConcern.w` option](/docs/guide.html#writeConcern) - * - * ####Example: - * - * // The 'majority' option means the `deleteOne()` promise won't resolve - * // until the `deleteOne()` has propagated to the majority of the replica set - * await mongoose.model('Person'). - * deleteOne({ name: 'Ned Stark' }). - * w('majority'); - * - * @method w - * @memberOf Query - * @instance - * @param {String|number} val 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option). - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option - * @return {Query} this - * @api public - */ - -Query.prototype.w = function w(val) { - if (val == null) { - delete this.options.w; - } - this.options.w = val; - return this; -}; - -/** - * Requests acknowledgement that this operation has been persisted to MongoDB's - * on-disk journal. - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndReplace()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the schema's [`writeConcern.j` option](/docs/guide.html#writeConcern) - * - * ####Example: - * - * await mongoose.model('Person').deleteOne({ name: 'Ned Stark' }).j(true); - * - * @method j - * @memberOf Query - * @instance - * @param {boolean} val - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option - * @return {Query} this - * @api public - */ - -Query.prototype.j = function j(val) { - if (val == null) { - delete this.options.j; - } - this.options.j = val; - return this; -}; - -/** - * If [`w > 1`](/docs/api.html#query_Query-w), the maximum amount of time to - * wait for this write to propagate through the replica set before this - * operation fails. The default is `0`, which means no timeout. - * - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndReplace()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the schema's [`writeConcern.wtimeout` option](/docs/guide.html#writeConcern) - * - * ####Example: - * - * // The `deleteOne()` promise won't resolve until this `deleteOne()` has - * // propagated to at least `w = 2` members of the replica set. If it takes - * // longer than 1 second, this `deleteOne()` will fail. - * await mongoose.model('Person'). - * deleteOne({ name: 'Ned Stark' }). - * w(2). - * wtimeout(1000); - * - * @method wtimeout - * @memberOf Query - * @instance - * @param {number} ms number of milliseconds to wait - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout - * @return {Query} this - * @api public - */ - -Query.prototype.wtimeout = function wtimeout(ms) { - if (ms == null) { - delete this.options.wtimeout; - } - this.options.wtimeout = ms; - return this; -}; - -/** - * Sets the readConcern option for the query. - * - * ####Example: - * - * new Query().readConcern('local') - * new Query().readConcern('l') // same as local - * - * new Query().readConcern('available') - * new Query().readConcern('a') // same as available - * - * new Query().readConcern('majority') - * new Query().readConcern('m') // same as majority - * - * new Query().readConcern('linearizable') - * new Query().readConcern('lz') // same as linearizable - * - * new Query().readConcern('snapshot') - * new Query().readConcern('s') // same as snapshot - * - * - * ####Read Concern Level: - * - * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). - * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). - * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. - * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. - * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. - * - * Aliases - * - * l local - * a available - * m majority - * lz linearizable - * s snapshot - * - * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). - * - * @memberOf Query - * @method readConcern - * @param {String} level one of the listed read concern level or their aliases - * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ - * @return {Query} this - * @api public - */ - -/** - * Gets query options. - * - * ####Example: - * - * var query = new Query(); - * query.limit(10); - * query.setOptions({ maxTimeMS: 1000 }) - * query.getOptions(); // { limit: 10, maxTimeMS: 1000 } - * - * @return {Object} the options - * @api public - */ - -Query.prototype.getOptions = function() { - return this.options; -}; - -/** - * Sets query options. Some options only make sense for certain operations. - * - * ####Options: - * - * The following options are only for `find()`: - * - * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) - * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) - * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) - * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) - * - [maxscan](https://docs.mongodb.org/v3.2/reference/operator/meta/maxScan/#metaOp._S_maxScan) - * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) - * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) - * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) - * - [readPreference](http://docs.mongodb.org/manual/applications/replication/#read-preference) - * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) - * - * The following options are only for write operations: `update()`, `updateOne()`, `updateMany()`, `replaceOne()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`: - * - * - [upsert](https://docs.mongodb.com/manual/reference/method/db.collection.update/) - * - [writeConcern](https://docs.mongodb.com/manual/reference/method/db.collection.update/) - * - [timestamps](https://mongoosejs.com/docs/guide.html#timestamps): If `timestamps` is set in the schema, set this option to `false` to skip timestamps for that particular update. Has no effect if `timestamps` is not enabled in the schema options. - * - omitUndefined: delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * - * The following options are only for `find()`, `findOne()`, `findById()`, `findOneAndUpdate()`, and `findByIdAndUpdate()`: - * - * - [lean](./api.html#query_Query-lean) - * - [populate](/docs/populate.html) - * - [projection](/docs/api/query.html#query_Query-projection) - * - * The following options are only for all operations **except** `update()`, `updateOne()`, `updateMany()`, `remove()`, `deleteOne()`, and `deleteMany()`: - * - * - [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) - * - * The following options are for `findOneAndUpdate()` and `findOneAndRemove()` - * - * - [useFindAndModify](/docs/deprecations.html#findandmodify) - * - rawResult - * - * The following options are for all operations: - * - * - [collation](https://docs.mongodb.com/manual/reference/collation/) - * - [session](https://docs.mongodb.com/manual/reference/server-sessions/) - * - [explain](https://docs.mongodb.com/manual/reference/method/cursor.explain/) - * - * @param {Object} options - * @return {Query} this - * @api public - */ - -Query.prototype.setOptions = function(options, overwrite) { - // overwrite is only for internal use - if (overwrite) { - // ensure that _mongooseOptions & options are two different objects - this._mongooseOptions = (options && utils.clone(options)) || {}; - this.options = options || {}; - - if ('populate' in options) { - this.populate(this._mongooseOptions); - } - return this; - } - - if (options == null) { - return this; - } - if (typeof options !== 'object') { - throw new Error('Options must be an object, got "' + options + '"'); - } - - if (Array.isArray(options.populate)) { - const populate = options.populate; - delete options.populate; - const _numPopulate = populate.length; - for (let i = 0; i < _numPopulate; ++i) { - this.populate(populate[i]); - } - } - - if ('useFindAndModify' in options) { - this._mongooseOptions.useFindAndModify = options.useFindAndModify; - delete options.useFindAndModify; - } - if ('omitUndefined' in options) { - this._mongooseOptions.omitUndefined = options.omitUndefined; - delete options.omitUndefined; - } - - return Query.base.setOptions.call(this, options); -}; - -/** - * Sets the [`explain` option](https://docs.mongodb.com/manual/reference/method/cursor.explain/), - * which makes this query return detailed execution stats instead of the actual - * query result. This method is useful for determining what index your queries - * use. - * - * Calling `query.explain(v)` is equivalent to `query.setOption({ explain: v })` - * - * ####Example: - * - * const query = new Query(); - * const res = await query.find({ a: 1 }).explain('queryPlanner'); - * console.log(res); - * - * @param {String} [verbose] The verbosity mode. Either 'queryPlanner', 'executionStats', or 'allPlansExecution'. The default is 'queryPlanner' - * @return {Query} this - * @api public - */ - -Query.prototype.explain = function(verbose) { - if (arguments.length === 0) { - this.options.explain = true; - return this; - } - this.options.explain = verbose; - return this; -}; - -/** - * Sets the [maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS/) - * option. This will tell the MongoDB server to abort if the query or write op - * has been running for more than `ms` milliseconds. - * - * Calling `query.maxTimeMS(v)` is equivalent to `query.setOption({ maxTimeMS: v })` - * - * ####Example: - * - * const query = new Query(); - * // Throws an error 'operation exceeded time limit' as long as there's - * // >= 1 doc in the queried collection - * const res = await query.find({ $where: 'sleep(1000) || true' }).maxTimeMS(100); - * - * @param {Number} [ms] The number of milliseconds - * @return {Query} this - * @api public - */ - -Query.prototype.maxTimeMS = function(ms) { - this.options.maxTimeMS = ms; - return this; -}; - -/** - * Returns the current query filter (also known as conditions) as a POJO. - * - * ####Example: - * - * const query = new Query(); - * query.find({ a: 1 }).where('b').gt(2); - * query.getFilter(); // { a: 1, b: { $gt: 2 } } - * - * @return {Object} current query filter - * @api public - */ - -Query.prototype.getFilter = function() { - return this._conditions; -}; - -/** - * Returns the current query filter. Equivalent to `getFilter()`. - * - * You should use `getFilter()` instead of `getQuery()` where possible. `getQuery()` - * will likely be deprecated in a future release. - * - * ####Example: - * - * var query = new Query(); - * query.find({ a: 1 }).where('b').gt(2); - * query.getQuery(); // { a: 1, b: { $gt: 2 } } - * - * @return {Object} current query filter - * @api public - */ - -Query.prototype.getQuery = function() { - return this._conditions; -}; - -/** - * Sets the query conditions to the provided JSON object. - * - * ####Example: - * - * var query = new Query(); - * query.find({ a: 1 }) - * query.setQuery({ a: 2 }); - * query.getQuery(); // { a: 2 } - * - * @param {Object} new query conditions - * @return {undefined} - * @api public - */ - -Query.prototype.setQuery = function(val) { - this._conditions = val; -}; - -/** - * Returns the current update operations as a JSON object. - * - * ####Example: - * - * var query = new Query(); - * query.update({}, { $set: { a: 5 } }); - * query.getUpdate(); // { $set: { a: 5 } } - * - * @return {Object} current update operations - * @api public - */ - -Query.prototype.getUpdate = function() { - return this._update; -}; - -/** - * Sets the current update operation to new value. - * - * ####Example: - * - * var query = new Query(); - * query.update({}, { $set: { a: 5 } }); - * query.setUpdate({ $set: { b: 6 } }); - * query.getUpdate(); // { $set: { b: 6 } } - * - * @param {Object} new update operation - * @return {undefined} - * @api public - */ - -Query.prototype.setUpdate = function(val) { - this._update = val; -}; - -/** - * Returns fields selection for this query. - * - * @method _fieldsForExec - * @return {Object} - * @api private - * @receiver Query - */ - -Query.prototype._fieldsForExec = function() { - return utils.clone(this._fields); -}; - - -/** - * Return an update document with corrected `$set` operations. - * - * @method _updateForExec - * @api private - * @receiver Query - */ - -Query.prototype._updateForExec = function() { - const update = utils.clone(this._update, { - transform: false, - depopulate: true - }); - const ops = Object.keys(update); - let i = ops.length; - const ret = {}; - - while (i--) { - const op = ops[i]; - - if (this.options.overwrite) { - ret[op] = update[op]; - continue; - } - - if ('$' !== op[0]) { - // fix up $set sugar - if (!ret.$set) { - if (update.$set) { - ret.$set = update.$set; - } else { - ret.$set = {}; - } - } - ret.$set[op] = update[op]; - ops.splice(i, 1); - if (!~ops.indexOf('$set')) ops.push('$set'); - } else if ('$set' === op) { - if (!ret.$set) { - ret[op] = update[op]; - } - } else { - ret[op] = update[op]; - } - } - - return ret; -}; - -/** - * Makes sure _path is set. - * - * @method _ensurePath - * @param {String} method - * @api private - * @receiver Query - */ - -/** - * Determines if `conds` can be merged using `mquery().merge()` - * - * @method canMerge - * @memberOf Query - * @instance - * @param {Object} conds - * @return {Boolean} - * @api private - */ - -/** - * Returns default options for this query. - * - * @param {Model} model - * @api private - */ - -Query.prototype._optionsForExec = function(model) { - const options = utils.clone(this.options); - - delete options.populate; - model = model || this.model; - - if (!model) { - return options; - } - - const safe = get(model, 'schema.options.safe', null); - if (!('safe' in options) && safe != null) { - setSafe(options, safe); - } - - // Apply schema-level `writeConcern` option - applyWriteConcern(model.schema, options); - - const readPreference = get(model, 'schema.options.read'); - if (!('readPreference' in options) && readPreference) { - options.readPreference = readPreference; - } - - if (options.upsert !== void 0) { - options.upsert = !!options.upsert; - } - - return options; -}; - -/*! - * ignore - */ - -const safeDeprecationWarning = 'Mongoose: the `safe` option is deprecated. ' + - 'Use write concerns instead: http://bit.ly/mongoose-w'; - -const setSafe = util.deprecate(function setSafe(options, safe) { - options.safe = safe; -}, safeDeprecationWarning); - -/** - * Sets the lean option. - * - * Documents returned from queries with the `lean` option enabled are plain - * javascript objects, not [Mongoose Documents](/api/document.html). They have no - * `save` method, getters/setters, virtuals, or other Mongoose features. - * - * ####Example: - * - * new Query().lean() // true - * new Query().lean(true) - * new Query().lean(false) - * - * const docs = await Model.find().lean(); - * docs[0] instanceof mongoose.Document; // false - * - * [Lean is great for high-performance, read-only cases](/docs/tutorials/lean.html), - * especially when combined - * with [cursors](/docs/queries.html#streaming). - * - * If you need virtuals, getters/setters, or defaults with `lean()`, you need - * to use a plugin. See: - * - * - [mongoose-lean-virtuals](https://plugins.mongoosejs.io/plugins/lean-virtuals) - * - [mongoose-lean-getters](https://plugins.mongoosejs.io/plugins/lean-getters) - * - [mongoose-lean-defaults](https://www.npmjs.com/package/mongoose-lean-defaults) - * - * @param {Boolean|Object} bool defaults to true - * @return {Query} this - * @api public - */ - -Query.prototype.lean = function(v) { - this._mongooseOptions.lean = arguments.length ? v : true; - return this; -}; - -/** - * Returns an object containing the Mongoose-specific options for this query, - * including `lean` and `populate`. - * - * Mongoose-specific options are different from normal options (`sort`, `limit`, etc.) - * because they are **not** sent to the MongoDB server. - * - * ####Example: - * - * const q = new Query(); - * q.mongooseOptions().lean; // undefined - * - * q.lean(); - * q.mongooseOptions().lean; // true - * - * This function is useful for writing [query middleware](/docs/middleware.html). - * Below is a full list of properties the return value from this function may have: - * - * - `populate` - * - `lean` - * - `omitUndefined` - * - `strict` - * - `nearSphere` - * - `useFindAndModify` - * - * @return {Object} Mongoose-specific options - * @param public - */ - -Query.prototype.mongooseOptions = function() { - return this._mongooseOptions; -}; - -/** - * Adds a `$set` to this query's update without changing the operation. - * This is useful for query middleware so you can add an update regardless - * of whether you use `updateOne()`, `updateMany()`, `findOneAndUpdate()`, etc. - * - * ####Example: - * - * // Updates `{ $set: { updatedAt: new Date() } }` - * new Query().updateOne({}, {}).set('updatedAt', new Date()); - * new Query().updateMany({}, {}).set({ updatedAt: new Date() }); - * - * @param {String|Object} path path or object of key/value pairs to set - * @param {Any} [val] the value to set - * @return {Query} this - * @api public - */ - -Query.prototype.set = function(path, val) { - if (typeof path === 'object') { - const keys = Object.keys(path); - for (const key of keys) { - this.set(key, path[key]); - } - return this; - } - - this._update = this._update || {}; - this._update.$set = this._update.$set || {}; - this._update.$set[path] = val; - return this; -}; - -/** - * For update operations, returns the value of a path in the update's `$set`. - * Useful for writing getters/setters that can work with both update operations - * and `save()`. - * - * ####Example: - * - * const query = Model.updateOne({}, { $set: { name: 'Jean-Luc Picard' } }); - * query.get('name'); // 'Jean-Luc Picard' - * - * @param {String|Object} path path or object of key/value pairs to set - * @param {Any} [val] the value to set - * @return {Query} this - * @api public - */ - -Query.prototype.get = function get(path) { - const update = this._update; - if (update == null) { - return void 0; - } - const $set = update.$set; - if ($set == null) { - return update[path]; - } - - if (utils.hasUserDefinedProperty(update, path)) { - return update[path]; - } - if (utils.hasUserDefinedProperty($set, path)) { - return $set[path]; - } - - return void 0; -}; - -/** - * Gets/sets the error flag on this query. If this flag is not null or - * undefined, the `exec()` promise will reject without executing. - * - * ####Example: - * - * Query().error(); // Get current error value - * Query().error(null); // Unset the current error - * Query().error(new Error('test')); // `exec()` will resolve with test - * Schema.pre('find', function() { - * if (!this.getQuery().userId) { - * this.error(new Error('Not allowed to query without setting userId')); - * } - * }); - * - * Note that query casting runs **after** hooks, so cast errors will override - * custom errors. - * - * ####Example: - * var TestSchema = new Schema({ num: Number }); - * var TestModel = db.model('Test', TestSchema); - * TestModel.find({ num: 'not a number' }).error(new Error('woops')).exec(function(error) { - * // `error` will be a cast error because `num` failed to cast - * }); - * - * @param {Error|null} err if set, `exec()` will fail fast before sending the query to MongoDB - * @return {Query} this - * @api public - */ - -Query.prototype.error = function error(err) { - if (arguments.length === 0) { - return this._error; - } - - this._error = err; - return this; -}; - -/*! - * ignore - */ - -Query.prototype._unsetCastError = function _unsetCastError() { - if (this._error != null && !(this._error instanceof CastError)) { - return; - } - return this.error(null); -}; - -/** - * Getter/setter around the current mongoose-specific options for this query - * Below are the current Mongoose-specific options. - * - * - `populate`: an array representing what paths will be populated. Should have one entry for each call to [`Query.prototype.populate()`](/docs/api.html#query_Query-populate) - * - `lean`: if truthy, Mongoose will not [hydrate](/docs/api.html#model_Model.hydrate) any documents that are returned from this query. See [`Query.prototype.lean()`](/docs/api.html#query_Query-lean) for more information. - * - `strict`: controls how Mongoose handles keys that aren't in the schema for updates. This option is `true` by default, which means Mongoose will silently strip any paths in the update that aren't in the schema. See the [`strict` mode docs](/docs/guide.html#strict) for more information. - * - `strictQuery`: controls how Mongoose handles keys that aren't in the schema for the query `filter`. This option is `false` by default for backwards compatibility, which means Mongoose will allow `Model.find({ foo: 'bar' })` even if `foo` is not in the schema. See the [`strictQuery` docs](/docs/guide.html#strictQuery) for more information. - * - `useFindAndModify`: used to work around the [`findAndModify()` deprecation warning](/docs/deprecations.html#findandmodify) - * - `omitUndefined`: delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * - `nearSphere`: use `$nearSphere` instead of `near()`. See the [`Query.prototype.nearSphere()` docs](/docs/api.html#query_Query-nearSphere) - * - * Mongoose maintains a separate object for internal options because - * Mongoose sends `Query.prototype.options` to the MongoDB server, and the - * above options are not relevant for the MongoDB server. - * - * @param {Object} options if specified, overwrites the current options - * @return {Object} the options - * @api public - */ - -Query.prototype.mongooseOptions = function(v) { - if (arguments.length > 0) { - this._mongooseOptions = v; - } - return this._mongooseOptions; -}; - -/*! - * ignore - */ - -Query.prototype._castConditions = function() { - try { - this.cast(this.model); - this._unsetCastError(); - } catch (err) { - this.error(err); - } -}; - -/*! - * ignore - */ - -function _castArrayFilters(query) { - try { - castArrayFilters(query); - } catch (err) { - query.error(err); - } -} - -/** - * Thunk around find() - * - * @param {Function} [callback] - * @return {Query} this - * @api private - */ -Query.prototype._find = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return null; - } - - callback = _wrapThunkCallback(this, callback); - - this._applyPaths(); - this._fields = this._castFields(this._fields); - - const fields = this._fieldsForExec(); - const mongooseOptions = this._mongooseOptions; - const _this = this; - const userProvidedFields = _this._userProvidedFields || {}; - - applyGlobalMaxTimeMS(this.options, this.model); - - // Separate options to pass down to `completeMany()` in case we need to - // set a session on the document - const completeManyOptions = Object.assign({}, { - session: get(this, 'options.session', null) - }); - - const cb = (err, docs) => { - if (err) { - return callback(err); - } - - if (docs.length === 0) { - return callback(null, docs); - } - if (this.options.explain) { - return callback(null, docs); - } - - if (!mongooseOptions.populate) { - return mongooseOptions.lean ? - callback(null, docs) : - completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, callback); - } - - const pop = helpers.preparePopulationOptionsMQ(_this, mongooseOptions); - completeManyOptions.populated = pop; - _this.model.populate(docs, pop, function(err, docs) { - if (err) return callback(err); - return mongooseOptions.lean ? - callback(null, docs) : - completeMany(_this.model, docs, fields, userProvidedFields, completeManyOptions, callback); - }); - }; - - const options = this._optionsForExec(); - options.projection = this._fieldsForExec(); - const filter = this._conditions; - - this._collection.find(filter, options, cb); - return null; -}); - -/** - * Find all documents that match `selector`. The result will be an array of documents. - * - * If there are too many documents in the result to fit in memory, use - * [`Query.prototype.cursor()`](api.html#query_Query-cursor) - * - * ####Example - * - * // Using async/await - * const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } }); - * - * // Using callbacks - * Movie.find({ year: { $gte: 1980, $lte: 1989 } }, function(err, arr) {}); - * - * @param {Object|ObjectId} [filter] mongodb selector. If not specified, returns all documents. - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.find = function(conditions, callback) { - this.op = 'find'; - - if (typeof conditions === 'function') { - callback = conditions; - conditions = {}; - } - - conditions = utils.toObject(conditions); - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - - prepareDiscriminatorCriteria(this); - } else if (conditions != null) { - this.error(new ObjectParameterError(conditions, 'filter', 'find')); - } - - // if we don't have a callback, then just return the query object - if (!callback) { - return Query.base.find.call(this); - } - - this.exec(callback); - - return this; -}; - -/** - * Merges another Query or conditions object into this one. - * - * When a Query is passed, conditions, field selection and options are merged. - * - * @param {Query|Object} source - * @return {Query} this - */ - -Query.prototype.merge = function(source) { - if (!source) { - return this; - } - - const opts = { overwrite: true }; - - if (source instanceof Query) { - // if source has a feature, apply it to ourselves - - if (source._conditions) { - utils.merge(this._conditions, source._conditions, opts); - } - - if (source._fields) { - this._fields || (this._fields = {}); - utils.merge(this._fields, source._fields, opts); - } - - if (source.options) { - this.options || (this.options = {}); - utils.merge(this.options, source.options, opts); - } - - if (source._update) { - this._update || (this._update = {}); - utils.mergeClone(this._update, source._update); - } - - if (source._distinct) { - this._distinct = source._distinct; - } - - utils.merge(this._mongooseOptions, source._mongooseOptions); - - return this; - } - - // plain object - utils.merge(this._conditions, source, opts); - - return this; -}; - -/** - * Adds a collation to this op (MongoDB 3.4 and up) - * - * @param {Object} value - * @return {Query} this - * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation - * @api public - */ - -Query.prototype.collation = function(value) { - if (this.options == null) { - this.options = {}; - } - this.options.collation = value; - return this; -}; - -/** - * Hydrate a single doc from `findOne()`, `findOneAndUpdate()`, etc. - * - * @api private - */ - -Query.prototype._completeOne = function(doc, res, callback) { - if (!doc && !this.options.rawResult) { - return callback(null, null); - } - - const model = this.model; - const projection = utils.clone(this._fields); - const userProvidedFields = this._userProvidedFields || {}; - // `populate`, `lean` - const mongooseOptions = this._mongooseOptions; - // `rawResult` - const options = this.options; - - if (options.explain) { - return callback(null, doc); - } - - if (!mongooseOptions.populate) { - return mongooseOptions.lean ? - _completeOneLean(doc, res, options, callback) : - completeOne(model, doc, res, options, projection, userProvidedFields, - null, callback); - } - - const pop = helpers.preparePopulationOptionsMQ(this, this._mongooseOptions); - model.populate(doc, pop, (err, doc) => { - if (err) { - return callback(err); - } - return mongooseOptions.lean ? - _completeOneLean(doc, res, options, callback) : - completeOne(model, doc, res, options, projection, userProvidedFields, - pop, callback); - }); -}; - -/** - * Thunk around findOne() - * - * @param {Function} [callback] - * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ - * @api private - */ - -Query.prototype._findOne = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error()) { - callback(this.error()); - return null; - } - - this._applyPaths(); - this._fields = this._castFields(this._fields); - - applyGlobalMaxTimeMS(this.options, this.model); - - // don't pass in the conditions because we already merged them in - Query.base.findOne.call(this, {}, (err, doc) => { - if (err) { - callback(err); - return null; - } - - this._completeOne(doc, null, _wrapThunkCallback(this, callback)); - }); -}); - -/** - * Declares the query a findOne operation. When executed, the first found document is passed to the callback. - * - * Passing a `callback` executes the query. The result of the query is a single document. - * - * * *Note:* `conditions` is optional, and if `conditions` is null or undefined, - * mongoose will send an empty `findOne` command to MongoDB, which will return - * an arbitrary document. If you're querying by `_id`, use `Model.findById()` - * instead. - * - * This function triggers the following middleware. - * - * - `findOne()` - * - * ####Example - * - * var query = Kitten.where({ color: 'white' }); - * query.findOne(function (err, kitten) { - * if (err) return handleError(err); - * if (kitten) { - * // doc may be null if no document matched - * } - * }); - * - * @param {Object} [filter] mongodb selector - * @param {Object} [projection] optional fields to return - * @param {Object} [options] see [`setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] optional params are (error, document) - * @return {Query} this - * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ - * @see Query.select #query_Query-select - * @api public - */ - -Query.prototype.findOne = function(conditions, projection, options, callback) { - this.op = 'findOne'; - - if (typeof conditions === 'function') { - callback = conditions; - conditions = null; - projection = null; - options = null; - } else if (typeof projection === 'function') { - callback = projection; - options = null; - projection = null; - } else if (typeof options === 'function') { - callback = options; - options = null; - } - - // make sure we don't send in the whole Document to merge() - conditions = utils.toObject(conditions); - - if (options) { - this.setOptions(options); - } - - if (projection) { - this.select(projection); - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - - prepareDiscriminatorCriteria(this); - } else if (conditions != null) { - this.error(new ObjectParameterError(conditions, 'filter', 'findOne')); - } - - if (!callback) { - // already merged in the conditions, don't need to send them in. - return Query.base.findOne.call(this); - } - - this.exec(callback); - - return this; -}; - -/** - * Thunk around count() - * - * @param {Function} [callback] - * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ - * @api private - */ - -Query.prototype._count = wrapThunk(function(callback) { - try { - this.cast(this.model); - } catch (err) { - this.error(err); - } - - if (this.error()) { - return callback(this.error()); - } - - const conds = this._conditions; - const options = this._optionsForExec(); - - this._collection.count(conds, options, utils.tick(callback)); -}); - -/** - * Thunk around countDocuments() - * - * @param {Function} [callback] - * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments - * @api private - */ - -Query.prototype._countDocuments = wrapThunk(function(callback) { - try { - this.cast(this.model); - } catch (err) { - this.error(err); - } - - if (this.error()) { - return callback(this.error()); - } - - const conds = this._conditions; - const options = this._optionsForExec(); - - this._collection.collection.countDocuments(conds, options, utils.tick(callback)); -}); - -/** - * Thunk around estimatedDocumentCount() - * - * @param {Function} [callback] - * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount - * @api private - */ - -Query.prototype._estimatedDocumentCount = wrapThunk(function(callback) { - if (this.error()) { - return callback(this.error()); - } - - const options = this._optionsForExec(); - - this._collection.collection.estimatedDocumentCount(options, utils.tick(callback)); -}); - -/** - * Specifies this query as a `count` query. - * - * This method is deprecated. If you want to count the number of documents in - * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#query_Query-estimatedDocumentCount) - * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#query_Query-countDocuments) function instead. - * - * Passing a `callback` executes the query. - * - * This function triggers the following middleware. - * - * - `count()` - * - * ####Example: - * - * var countQuery = model.where({ 'color': 'black' }).count(); - * - * query.count({ color: 'black' }).count(callback) - * - * query.count({ color: 'black' }, callback) - * - * query.where('color', 'black').count(function (err, count) { - * if (err) return handleError(err); - * console.log('there are %d kittens', count); - * }) - * - * @deprecated - * @param {Object} [filter] count documents that match this object - * @param {Function} [callback] optional params are (error, count) - * @return {Query} this - * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ - * @api public - */ - -Query.prototype.count = function(filter, callback) { - this.op = 'count'; - if (typeof filter === 'function') { - callback = filter; - filter = undefined; - } - - filter = utils.toObject(filter); - - if (mquery.canMerge(filter)) { - this.merge(filter); - } - - if (!callback) { - return this; - } - - this.exec(callback); - - return this; -}; - -/** - * Specifies this query as a `estimatedDocumentCount()` query. Faster than - * using `countDocuments()` for large collections because - * `estimatedDocumentCount()` uses collection metadata rather than scanning - * the entire collection. - * - * `estimatedDocumentCount()` does **not** accept a filter. `Model.find({ foo: bar }).estimatedDocumentCount()` - * is equivalent to `Model.find().estimatedDocumentCount()` - * - * This function triggers the following middleware. - * - * - `estimatedDocumentCount()` - * - * ####Example: - * - * await Model.find().estimatedDocumentCount(); - * - * @param {Object} [options] passed transparently to the [MongoDB driver](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount) - * @param {Function} [callback] optional params are (error, count) - * @return {Query} this - * @see estimatedDocumentCount http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#estimatedDocumentCount - * @api public - */ - -Query.prototype.estimatedDocumentCount = function(options, callback) { - this.op = 'estimatedDocumentCount'; - if (typeof options === 'function') { - callback = options; - options = undefined; - } - - if (typeof options === 'object' && options != null) { - this.setOptions(options); - } - - if (!callback) { - return this; - } - - this.exec(callback); - - return this; -}; - -/** - * Specifies this query as a `countDocuments()` query. Behaves like `count()`, - * except it always does a full collection scan when passed an empty filter `{}`. - * - * There are also minor differences in how `countDocuments()` handles - * [`$where` and a couple geospatial operators](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). - * versus `count()`. - * - * Passing a `callback` executes the query. - * - * This function triggers the following middleware. - * - * - `countDocuments()` - * - * ####Example: - * - * const countQuery = model.where({ 'color': 'black' }).countDocuments(); - * - * query.countDocuments({ color: 'black' }).count(callback); - * - * query.countDocuments({ color: 'black' }, callback); - * - * query.where('color', 'black').countDocuments(function(err, count) { - * if (err) return handleError(err); - * console.log('there are %d kittens', count); - * }); - * - * The `countDocuments()` function is similar to `count()`, but there are a - * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). - * Below are the operators that `count()` supports but `countDocuments()` does not, - * and the suggested replacement: - * - * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/) - * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center) - * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere) - * - * @param {Object} [filter] mongodb selector - * @param {Function} [callback] optional params are (error, count) - * @return {Query} this - * @see countDocuments http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments - * @api public - */ - -Query.prototype.countDocuments = function(conditions, callback) { - this.op = 'countDocuments'; - if (typeof conditions === 'function') { - callback = conditions; - conditions = undefined; - } - - conditions = utils.toObject(conditions); - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } - - if (!callback) { - return this; - } - - this.exec(callback); - - return this; -}; - -/** - * Thunk around distinct() - * - * @param {Function} [callback] - * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ - * @api private - */ - -Query.prototype.__distinct = wrapThunk(function __distinct(callback) { - this._castConditions(); - - if (this.error()) { - callback(this.error()); - return null; - } - - const options = this._optionsForExec(); - - // don't pass in the conditions because we already merged them in - this._collection.collection. - distinct(this._distinct, this._conditions, options, callback); -}); - -/** - * Declares or executes a distinct() operation. - * - * Passing a `callback` executes the query. - * - * This function does not trigger any middleware. - * - * ####Example - * - * distinct(field, conditions, callback) - * distinct(field, conditions) - * distinct(field, callback) - * distinct(field) - * distinct(callback) - * distinct() - * - * @param {String} [field] - * @param {Object|Query} [filter] - * @param {Function} [callback] optional params are (error, arr) - * @return {Query} this - * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ - * @api public - */ - -Query.prototype.distinct = function(field, conditions, callback) { - this.op = 'distinct'; - if (!callback) { - if (typeof conditions === 'function') { - callback = conditions; - conditions = undefined; - } else if (typeof field === 'function') { - callback = field; - field = undefined; - conditions = undefined; - } - } - - conditions = utils.toObject(conditions); - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - - prepareDiscriminatorCriteria(this); - } else if (conditions != null) { - this.error(new ObjectParameterError(conditions, 'filter', 'distinct')); - } - - if (field != null) { - this._distinct = field; - } - - if (callback != null) { - this.exec(callback); - } - - return this; -}; - -/** - * Sets the sort order - * - * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. - * - * If a string is passed, it must be a space delimited list of path names. The - * sort order of each path is ascending unless the path name is prefixed with `-` - * which will be treated as descending. - * - * ####Example - * - * // sort by "field" ascending and "test" descending - * query.sort({ field: 'asc', test: -1 }); - * - * // equivalent - * query.sort('field -test'); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|String} arg - * @return {Query} this - * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/ - * @api public - */ - -Query.prototype.sort = function(arg) { - if (arguments.length > 1) { - throw new Error('sort() only takes 1 Argument'); - } - - return Query.base.sort.call(this, arg); -}; - -/** - * Declare and/or execute this query as a remove() operation. `remove()` is - * deprecated, you should use [`deleteOne()`](#query_Query-deleteOne) - * or [`deleteMany()`](#query_Query-deleteMany) instead. - * - * This function does not trigger any middleware - * - * ####Example - * - * Character.remove({ name: /Stark/ }, callback); - * - * This function calls the MongoDB driver's [`Collection#remove()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove). - * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an - * object that contains 3 properties: - * - * - `ok`: `1` if no errors occurred - * - `deletedCount`: the number of documents deleted - * - `n`: the number of documents deleted. Equal to `deletedCount`. - * - * ####Example - * - * const res = await Character.remove({ name: /Stark/ }); - * // Number of docs deleted - * res.deletedCount; - * - * ####Note - * - * Calling `remove()` creates a [Mongoose query](./queries.html), and a query - * does not execute until you either pass a callback, call [`Query#then()`](#query_Query-then), - * or call [`Query#exec()`](#query_Query-exec). - * - * // not executed - * const query = Character.remove({ name: /Stark/ }); - * - * // executed - * Character.remove({ name: /Stark/ }, callback); - * Character.remove({ name: /Stark/ }).remove(callback); - * - * // executed without a callback - * Character.exec(); - * - * @param {Object|Query} [filter] mongodb selector - * @param {Function} [callback] optional params are (error, mongooseDeleteResult) - * @return {Query} this - * @deprecated - * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult - * @see MongoDB driver remove http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#remove - * @api public - */ - -Query.prototype.remove = function(filter, callback) { - this.op = 'remove'; - if (typeof filter === 'function') { - callback = filter; - filter = null; - } - - filter = utils.toObject(filter); - - if (mquery.canMerge(filter)) { - this.merge(filter); - - prepareDiscriminatorCriteria(this); - } else if (filter != null) { - this.error(new ObjectParameterError(filter, 'filter', 'remove')); - } - - if (!callback) { - return Query.base.remove.call(this); - } - - this.exec(callback); - return this; -}; - -/*! - * ignore - */ - -Query.prototype._remove = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return this; - } - - callback = _wrapThunkCallback(this, callback); - - return Query.base.remove.call(this, helpers.handleDeleteWriteOpResult(callback)); -}); - -/** - * Declare and/or execute this query as a `deleteOne()` operation. Works like - * remove, except it deletes at most one document regardless of the `single` - * option. - * - * This function does not trigger any middleware. - * - * ####Example - * - * Character.deleteOne({ name: 'Eddard Stark' }, callback); - * Character.deleteOne({ name: 'Eddard Stark' }).then(next); - * - * This function calls the MongoDB driver's [`Collection#deleteOne()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne). - * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an - * object that contains 3 properties: - * - * - `ok`: `1` if no errors occurred - * - `deletedCount`: the number of documents deleted - * - `n`: the number of documents deleted. Equal to `deletedCount`. - * - * ####Example - * - * const res = await Character.deleteOne({ name: 'Eddard Stark' }); - * // `1` if MongoDB deleted a doc, `0` if no docs matched the filter `{ name: ... }` - * res.deletedCount; - * - * @param {Object|Query} [filter] mongodb selector - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] optional params are (error, mongooseDeleteResult) - * @return {Query} this - * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult - * @see MongoDB Driver deleteOne http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteOne - * @api public - */ - -Query.prototype.deleteOne = function(filter, options, callback) { - this.op = 'deleteOne'; - if (typeof filter === 'function') { - callback = filter; - filter = null; - options = null; - } else if (typeof options === 'function') { - callback = options; - options = null; - } else { - this.setOptions(options); - } - - filter = utils.toObject(filter); - - if (mquery.canMerge(filter)) { - this.merge(filter); - - prepareDiscriminatorCriteria(this); - } else if (filter != null) { - this.error(new ObjectParameterError(filter, 'filter', 'deleteOne')); - } - - if (!callback) { - return Query.base.deleteOne.call(this); - } - - this.exec.call(this, callback); - - return this; -}; - -/*! - * Internal thunk for `deleteOne()` - */ - -Query.prototype._deleteOne = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return this; - } - - callback = _wrapThunkCallback(this, callback); - - return Query.base.deleteOne.call(this, helpers.handleDeleteWriteOpResult(callback)); -}); - -/** - * Declare and/or execute this query as a `deleteMany()` operation. Works like - * remove, except it deletes _every_ document that matches `filter` in the - * collection, regardless of the value of `single`. - * - * This function does not trigger any middleware - * - * ####Example - * - * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback) - * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }).then(next) - * - * This function calls the MongoDB driver's [`Collection#deleteMany()` function](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany). - * The returned [promise](https://mongoosejs.com/docs/queries.html) resolves to an - * object that contains 3 properties: - * - * - `ok`: `1` if no errors occurred - * - `deletedCount`: the number of documents deleted - * - `n`: the number of documents deleted. Equal to `deletedCount`. - * - * ####Example - * - * const res = await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); - * // `0` if no docs matched the filter, number of docs deleted otherwise - * res.deletedCount; - * - * @param {Object|Query} [filter] mongodb selector - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Function} [callback] optional params are (error, mongooseDeleteResult) - * @return {Query} this - * @see deleteWriteOpResult http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~deleteWriteOpResult - * @see MongoDB Driver deleteMany http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany - * @api public - */ - -Query.prototype.deleteMany = function(filter, options, callback) { - this.op = 'deleteMany'; - if (typeof filter === 'function') { - callback = filter; - filter = null; - options = null; - } else if (typeof options === 'function') { - callback = options; - options = null; - } else { - this.setOptions(options); - } - - filter = utils.toObject(filter); - - if (mquery.canMerge(filter)) { - this.merge(filter); - - prepareDiscriminatorCriteria(this); - } else if (filter != null) { - this.error(new ObjectParameterError(filter, 'filter', 'deleteMany')); - } - - if (!callback) { - return Query.base.deleteMany.call(this); - } - - this.exec.call(this, callback); - - return this; -}; - -/*! - * Internal thunk around `deleteMany()` - */ - -Query.prototype._deleteMany = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return this; - } - - callback = _wrapThunkCallback(this, callback); - - return Query.base.deleteMany.call(this, helpers.handleDeleteWriteOpResult(callback)); -}); - -/*! - * hydrates a document - * - * @param {Model} model - * @param {Document} doc - * @param {Object} res 3rd parameter to callback - * @param {Object} fields - * @param {Query} self - * @param {Array} [pop] array of paths used in population - * @param {Function} callback - */ - -function completeOne(model, doc, res, options, fields, userProvidedFields, pop, callback) { - const opts = pop ? - { populated: pop } - : undefined; - - if (options.rawResult && doc == null) { - _init(null); - return null; - } - - const casted = helpers.createModel(model, doc, fields, userProvidedFields); - try { - casted.init(doc, opts, _init); - } catch (error) { - _init(error); - } - - function _init(err) { - if (err) { - return process.nextTick(() => callback(err)); - } - - - if (options.rawResult) { - if (doc && casted) { - casted.$session(options.session); - res.value = casted; - } else { - res.value = null; - } - return process.nextTick(() => callback(null, res)); - } - casted.$session(options.session); - process.nextTick(() => callback(null, casted)); - } -} - -/*! - * If the model is a discriminator type and not root, then add the key & value to the criteria. - */ - -function prepareDiscriminatorCriteria(query) { - if (!query || !query.model || !query.model.schema) { - return; - } - - const schema = query.model.schema; - - if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { - query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; - } -} - -/** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found - * document (if any) to the callback. The query executes if - * `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndUpdate()` - * - * ####Available options - * - * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()` - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false. - * - * ####Callback Signature - * function(error, doc) { - * // error: any errors that occurred - * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` - * } - * - * ####Examples - * - * query.findOneAndUpdate(conditions, update, options, callback) // executes - * query.findOneAndUpdate(conditions, update, options) // returns Query - * query.findOneAndUpdate(conditions, update, callback) // executes - * query.findOneAndUpdate(conditions, update) // returns Query - * query.findOneAndUpdate(update, callback) // returns Query - * query.findOneAndUpdate(update) // returns Query - * query.findOneAndUpdate(callback) // executes - * query.findOneAndUpdate() // returns Query - * - * @method findOneAndUpdate - * @memberOf Query - * @instance - * @param {Object|Query} [filter] - * @param {Object} [doc] - * @param {Object} [options] - * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. - * @param {Function} [callback] optional params are (error, doc), _unless_ `rawResult` is used, in which case params are (error, writeOpResult) - * @see Tutorial /docs/tutorials/findoneandupdate.html - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @return {Query} this - * @api public - */ - -Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) { - this.op = 'findOneAndUpdate'; - this._validate(); - - switch (arguments.length) { - case 3: - if (typeof options === 'function') { - callback = options; - options = {}; - } - break; - case 2: - if (typeof doc === 'function') { - callback = doc; - doc = criteria; - criteria = undefined; - } - options = undefined; - break; - case 1: - if (typeof criteria === 'function') { - callback = criteria; - criteria = options = doc = undefined; - } else { - doc = criteria; - criteria = options = undefined; - } - } - - if (mquery.canMerge(criteria)) { - this.merge(criteria); - } - - // apply doc - if (doc) { - this._mergeUpdate(doc); - } - - if (options) { - options = utils.clone(options); - if (options.projection) { - this.select(options.projection); - delete options.projection; - } - if (options.fields) { - this.select(options.fields); - delete options.fields; - } - - this.setOptions(options); - } - - if (!callback) { - return this; - } - - this.exec(callback); - - return this; -}; - -/*! - * Thunk around findOneAndUpdate() - * - * @param {Function} [callback] - * @api private - */ - -Query.prototype._findOneAndUpdate = wrapThunk(function(callback) { - if (this.error() != null) { - return callback(this.error()); - } - - this._findAndModify('update', callback); -}); - -/** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. - * - * Finds a matching document, removes it, passing the found document (if any) to - * the callback. Executes if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndRemove()` - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - * ####Callback Signature - * function(error, doc) { - * // error: any errors that occurred - * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` - * } - * - * ####Examples - * - * A.where().findOneAndRemove(conditions, options, callback) // executes - * A.where().findOneAndRemove(conditions, options) // return Query - * A.where().findOneAndRemove(conditions, callback) // executes - * A.where().findOneAndRemove(conditions) // returns Query - * A.where().findOneAndRemove(callback) // executes - * A.where().findOneAndRemove() // returns Query - * - * @method findOneAndRemove - * @memberOf Query - * @instance - * @param {Object} [conditions] - * @param {Object} [options] - * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Function} [callback] optional params are (error, document) - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Query.prototype.findOneAndRemove = function(conditions, options, callback) { - this.op = 'findOneAndRemove'; - this._validate(); - - switch (arguments.length) { - case 2: - if (typeof options === 'function') { - callback = options; - options = {}; - } - break; - case 1: - if (typeof conditions === 'function') { - callback = conditions; - conditions = undefined; - options = undefined; - } - break; - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } - - options && this.setOptions(options); - - if (!callback) { - return this; - } - - this.exec(callback); - - return this; -}; - -/** - * Issues a MongoDB [findOneAndDelete](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/) command. - * - * Finds a matching document, removes it, and passes the found document (if any) - * to the callback. Executes if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndDelete()` - * - * This function differs slightly from `Model.findOneAndRemove()` in that - * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/), - * as opposed to a `findOneAndDelete()` command. For most mongoose use cases, - * this distinction is purely pedantic. You should use `findOneAndDelete()` - * unless you have a good reason not to. - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - * ####Callback Signature - * function(error, doc) { - * // error: any errors that occurred - * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` - * } - * - * ####Examples - * - * A.where().findOneAndDelete(conditions, options, callback) // executes - * A.where().findOneAndDelete(conditions, options) // return Query - * A.where().findOneAndDelete(conditions, callback) // executes - * A.where().findOneAndDelete(conditions) // returns Query - * A.where().findOneAndDelete(callback) // executes - * A.where().findOneAndDelete() // returns Query - * - * @method findOneAndDelete - * @memberOf Query - * @param {Object} [conditions] - * @param {Object} [options] - * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Function} [callback] optional params are (error, document) - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Query.prototype.findOneAndDelete = function(conditions, options, callback) { - this.op = 'findOneAndDelete'; - this._validate(); - - switch (arguments.length) { - case 2: - if (typeof options === 'function') { - callback = options; - options = {}; - } - break; - case 1: - if (typeof conditions === 'function') { - callback = conditions; - conditions = undefined; - options = undefined; - } - break; - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } - - options && this.setOptions(options); - - if (!callback) { - return this; - } - - this.exec(callback); - - return this; -}; - -/*! - * Thunk around findOneAndDelete() - * - * @param {Function} [callback] - * @return {Query} this - * @api private - */ -Query.prototype._findOneAndDelete = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return null; - } - - const filter = this._conditions; - const options = this._optionsForExec(); - let fields = null; - - if (this._fields != null) { - options.projection = this._castFields(utils.clone(this._fields)); - fields = options.projection; - if (fields instanceof Error) { - callback(fields); - return null; - } - } - - this._collection.collection.findOneAndDelete(filter, options, _wrapThunkCallback(this, (err, res) => { - if (err) { - return callback(err); - } - - const doc = res.value; - - return this._completeOne(doc, res, callback); - })); -}); - -/** - * Issues a MongoDB [findOneAndReplace](https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/) command. - * - * Finds a matching document, removes it, and passes the found document (if any) - * to the callback. Executes if `callback` is passed. - * - * This function triggers the following middleware. - * - * - `findOneAndReplace()` - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 - * - `rawResult`: if true, resolves to the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * - * ####Callback Signature - * function(error, doc) { - * // error: any errors that occurred - * // doc: the document before updates are applied if `new: false`, or after updates if `new = true` - * } - * - * ####Examples - * - * A.where().findOneAndReplace(filter, replacement, options, callback); // executes - * A.where().findOneAndReplace(filter, replacement, options); // return Query - * A.where().findOneAndReplace(filter, replacement, callback); // executes - * A.where().findOneAndReplace(filter); // returns Query - * A.where().findOneAndReplace(callback); // executes - * A.where().findOneAndReplace(); // returns Query - * - * @method findOneAndReplace - * @memberOf Query - * @param {Object} [filter] - * @param {Object} [replacement] - * @param {Object} [options] - * @param {Boolean} [options.rawResult] if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. - * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). - * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. - * @param {Function} [callback] optional params are (error, document) - * @return {Query} this - * @api public - */ - -Query.prototype.findOneAndReplace = function(filter, replacement, options, callback) { - this.op = 'findOneAndReplace'; - this._validate(); - - switch (arguments.length) { - case 3: - if (typeof options === 'function') { - callback = options; - options = void 0; - } - break; - case 2: - if (typeof replacement === 'function') { - callback = replacement; - replacement = void 0; - } - break; - case 1: - if (typeof filter === 'function') { - callback = filter; - filter = void 0; - replacement = void 0; - options = void 0; - } - break; - } - - if (mquery.canMerge(filter)) { - this.merge(filter); - } - - if (replacement != null) { - if (hasDollarKeys(replacement)) { - throw new Error('The replacement document must not contain atomic operators.'); - } - this._mergeUpdate(replacement); - } - - options && this.setOptions(options); - - if (!callback) { - return this; - } - - this.exec(callback); - - return this; -}; - -/*! - * Thunk around findOneAndReplace() - * - * @param {Function} [callback] - * @return {Query} this - * @api private - */ -Query.prototype._findOneAndReplace = wrapThunk(function(callback) { - this._castConditions(); - - if (this.error() != null) { - callback(this.error()); - return null; - } - - const filter = this._conditions; - const options = this._optionsForExec(); - convertNewToReturnOriginal(options); - let fields = null; - - let castedDoc = new this.model(this._update, null, true); - this._update = castedDoc; - - this._applyPaths(); - if (this._fields != null) { - options.projection = this._castFields(utils.clone(this._fields)); - fields = options.projection; - if (fields instanceof Error) { - callback(fields); - return null; - } - } - - castedDoc.validate(err => { - if (err != null) { - return callback(err); - } - - if (castedDoc.toBSON) { - castedDoc = castedDoc.toBSON(); - } - - this._collection.collection.findOneAndReplace(filter, castedDoc, options, _wrapThunkCallback(this, (err, res) => { - if (err) { - return callback(err); - } - - const doc = res.value; - - return this._completeOne(doc, res, callback); - })); - }); -}); - -/*! - * Support the `new` option as an alternative to `returnOriginal` for backwards - * compat. - */ - -function convertNewToReturnOriginal(options) { - if ('new' in options) { - options.returnOriginal = !options['new']; - delete options['new']; - } -} - -/*! - * Thunk around findOneAndRemove() - * - * @param {Function} [callback] - * @return {Query} this - * @api private - */ -Query.prototype._findOneAndRemove = wrapThunk(function(callback) { - if (this.error() != null) { - callback(this.error()); - return; - } - - this._findAndModify('remove', callback); -}); - -/*! - * Get options from query opts, falling back to the base mongoose object. - */ - -function _getOption(query, option, def) { - const opts = query._optionsForExec(query.model); - - if (option in opts) { - return opts[option]; - } - if (option in query.model.base.options) { - return query.model.base.options[option]; - } - return def; -} - -/*! - * Override mquery.prototype._findAndModify to provide casting etc. - * - * @param {String} type - either "remove" or "update" - * @param {Function} callback - * @api private - */ - -Query.prototype._findAndModify = function(type, callback) { - if (typeof callback !== 'function') { - throw new Error('Expected callback in _findAndModify'); - } - - const model = this.model; - const schema = model.schema; - const _this = this; - let fields; - - const castedQuery = castQuery(this); - if (castedQuery instanceof Error) { - return callback(castedQuery); - } - - _castArrayFilters(this); - - const opts = this._optionsForExec(model); - - if ('strict' in opts) { - this._mongooseOptions.strict = opts.strict; - } - - const isOverwriting = this.options.overwrite && !hasDollarKeys(this._update); - if (isOverwriting) { - this._update = new this.model(this._update, null, true); - } - - if (type === 'remove') { - opts.remove = true; - } else { - if (!('new' in opts) && !('returnOriginal' in opts)) { - opts.new = false; - } - if (!('upsert' in opts)) { - opts.upsert = false; - } - if (opts.upsert || opts['new']) { - opts.remove = false; - } - - if (!isOverwriting) { - this._update = castDoc(this, opts.overwrite); - this._update = setDefaultsOnInsert(this._conditions, schema, this._update, opts); - if (!this._update || Object.keys(this._update).length === 0) { - if (opts.upsert) { - // still need to do the upsert to empty doc - const doc = utils.clone(castedQuery); - delete doc._id; - this._update = { $set: doc }; - } else { - this.findOne(callback); - return this; - } - } else if (this._update instanceof Error) { - return callback(this._update); - } else { - // In order to make MongoDB 2.6 happy (see - // https://jira.mongodb.org/browse/SERVER-12266 and related issues) - // if we have an actual update document but $set is empty, junk the $set. - if (this._update.$set && Object.keys(this._update.$set).length === 0) { - delete this._update.$set; - } - } - } - } - - this._applyPaths(); - - const options = this._mongooseOptions; - - if (this._fields) { - fields = utils.clone(this._fields); - opts.projection = this._castFields(fields); - if (opts.projection instanceof Error) { - return callback(opts.projection); - } - } - - if (opts.sort) convertSortToArray(opts); - - const cb = function(err, doc, res) { - if (err) { - return callback(err); - } - - _this._completeOne(doc, res, callback); - }; - - let useFindAndModify = true; - const runValidators = _getOption(this, 'runValidators', false); - const base = _this.model && _this.model.base; - const conn = get(model, 'collection.conn', {}); - if ('useFindAndModify' in base.options) { - useFindAndModify = base.get('useFindAndModify'); - } - if ('useFindAndModify' in conn.config) { - useFindAndModify = conn.config.useFindAndModify; - } - if ('useFindAndModify' in options) { - useFindAndModify = options.useFindAndModify; - } - if (useFindAndModify === false) { - // Bypass mquery - const collection = _this._collection.collection; - convertNewToReturnOriginal(opts); - - if (type === 'remove') { - collection.findOneAndDelete(castedQuery, opts, _wrapThunkCallback(_this, function(error, res) { - return cb(error, res ? res.value : res, res); - })); - - return this; - } - - // honors legacy overwrite option for backward compatibility - const updateMethod = isOverwriting ? 'findOneAndReplace' : 'findOneAndUpdate'; - - if (runValidators) { - this.validate(this._update, opts, isOverwriting, error => { - if (error) { - return callback(error); - } - if (this._update && this._update.toBSON) { - this._update = this._update.toBSON(); - } - - collection[updateMethod](castedQuery, this._update, opts, _wrapThunkCallback(_this, function(error, res) { - return cb(error, res ? res.value : res, res); - })); - }); - } else { - if (this._update && this._update.toBSON) { - this._update = this._update.toBSON(); - } - collection[updateMethod](castedQuery, this._update, opts, _wrapThunkCallback(_this, function(error, res) { - return cb(error, res ? res.value : res, res); - })); - } - - return this; - } - - if (runValidators) { - this.validate(this._update, opts, isOverwriting, function(error) { - if (error) { - return callback(error); - } - _legacyFindAndModify.call(_this, castedQuery, _this._update, opts, cb); - }); - } else { - _legacyFindAndModify.call(_this, castedQuery, _this._update, opts, cb); - } - - return this; -}; - -/*! - * ignore - */ - -function _completeOneLean(doc, res, opts, callback) { - if (opts.rawResult) { - return callback(null, res); - } - return callback(null, doc); -} - - -/*! - * ignore - */ - -const _legacyFindAndModify = util.deprecate(function(filter, update, opts, cb) { - if (update && update.toBSON) { - update = update.toBSON(); - } - const collection = this._collection; - const sort = opts != null && Array.isArray(opts.sort) ? opts.sort : []; - const _cb = _wrapThunkCallback(this, function(error, res) { - return cb(error, res ? res.value : res, res); - }); - collection.collection._findAndModify(filter, sort, update, opts, _cb); -}, 'Mongoose: `findOneAndUpdate()` and `findOneAndDelete()` without the ' + - '`useFindAndModify` option set to false are deprecated. See: ' + - 'https://mongoosejs.com/docs/deprecations.html#findandmodify'); - -/*! - * Override mquery.prototype._mergeUpdate to handle mongoose objects in - * updates. - * - * @param {Object} doc - * @api private - */ - -Query.prototype._mergeUpdate = function(doc) { - if (doc == null || (typeof doc === 'object' && Object.keys(doc).length === 0)) { - return; - } - - if (!this._update) { - this._update = Array.isArray(doc) ? [] : {}; - } - if (doc instanceof Query) { - if (Array.isArray(this._update)) { - throw new Error('Cannot mix array and object updates'); - } - if (doc._update) { - utils.mergeClone(this._update, doc._update); - } - } else if (Array.isArray(doc)) { - if (!Array.isArray(this._update)) { - throw new Error('Cannot mix array and object updates'); - } - this._update = this._update.concat(doc); - } else { - if (Array.isArray(this._update)) { - throw new Error('Cannot mix array and object updates'); - } - utils.mergeClone(this._update, doc); - } -}; - -/*! - * The mongodb driver 1.3.23 only supports the nested array sort - * syntax. We must convert it or sorting findAndModify will not work. - */ - -function convertSortToArray(opts) { - if (Array.isArray(opts.sort)) { - return; - } - if (!utils.isObject(opts.sort)) { - return; - } - - const sort = []; - - for (const key in opts.sort) { - if (utils.object.hasOwnProperty(opts.sort, key)) { - sort.push([key, opts.sort[key]]); - } - } - - opts.sort = sort; -} - -/*! - * ignore - */ - -function _updateThunk(op, callback) { - this._castConditions(); - - _castArrayFilters(this); - - if (this.error() != null) { - callback(this.error()); - return null; - } - - callback = _wrapThunkCallback(this, callback); - const oldCb = callback; - callback = function(error, result) { - oldCb(error, result ? result.result : { ok: 0, n: 0, nModified: 0 }); - }; - - const castedQuery = this._conditions; - const options = this._optionsForExec(this.model); - - ++this._executionCount; - - this._update = utils.clone(this._update, options); - const isOverwriting = this.options.overwrite && !hasDollarKeys(this._update); - if (isOverwriting) { - if (op === 'updateOne' || op === 'updateMany') { - return callback(new MongooseError('The MongoDB server disallows ' + - 'overwriting documents using `' + op + '`. See: ' + - 'https://mongoosejs.com/docs/deprecations.html#update')); - } - this._update = new this.model(this._update, null, true); - } else { - this._update = castDoc(this, options.overwrite); - - if (this._update instanceof Error) { - callback(this._update); - return null; - } - - if (this._update == null || Object.keys(this._update).length === 0) { - callback(null, 0); - return null; - } - - this._update = setDefaultsOnInsert(this._conditions, this.model.schema, - this._update, options); - } - - const runValidators = _getOption(this, 'runValidators', false); - if (runValidators) { - this.validate(this._update, options, isOverwriting, err => { - if (err) { - return callback(err); - } - - if (this._update.toBSON) { - this._update = this._update.toBSON(); - } - this._collection[op](castedQuery, this._update, options, callback); - }); - return null; - } - - if (this._update.toBSON) { - this._update = this._update.toBSON(); - } - - this._collection[op](castedQuery, this._update, options, callback); - return null; -} - -/*! - * Mongoose calls this function internally to validate the query if - * `runValidators` is set - * - * @param {Object} castedDoc the update, after casting - * @param {Object} options the options from `_optionsForExec()` - * @param {Function} callback - * @api private - */ - -Query.prototype.validate = function validate(castedDoc, options, isOverwriting, callback) { - return promiseOrCallback(callback, cb => { - try { - if (isOverwriting) { - castedDoc.validate(cb); - } else { - updateValidators(this, this.model.schema, castedDoc, options, cb); - } - } catch (err) { - process.nextTick(function() { - cb(err); - }); - } - }); -}; - -/*! - * Internal thunk for .update() - * - * @param {Function} callback - * @see Model.update #model_Model.update - * @api private - */ -Query.prototype._execUpdate = wrapThunk(function(callback) { - return _updateThunk.call(this, 'update', callback); -}); - -/*! - * Internal thunk for .updateMany() - * - * @param {Function} callback - * @see Model.update #model_Model.update - * @api private - */ -Query.prototype._updateMany = wrapThunk(function(callback) { - return _updateThunk.call(this, 'updateMany', callback); -}); - -/*! - * Internal thunk for .updateOne() - * - * @param {Function} callback - * @see Model.update #model_Model.update - * @api private - */ -Query.prototype._updateOne = wrapThunk(function(callback) { - return _updateThunk.call(this, 'updateOne', callback); -}); - -/*! - * Internal thunk for .replaceOne() - * - * @param {Function} callback - * @see Model.replaceOne #model_Model.replaceOne - * @api private - */ -Query.prototype._replaceOne = wrapThunk(function(callback) { - return _updateThunk.call(this, 'replaceOne', callback); -}); - -/** - * Declare and/or execute this query as an update() operation. - * - * _All paths passed that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operations will become `$set` ops._ - * - * This function triggers the following middleware. - * - * - `update()` - * - * ####Example - * - * Model.where({ _id: id }).update({ title: 'words' }) - * - * // becomes - * - * Model.where({ _id: id }).update({ $set: { title: 'words' }}) - * - * ####Valid options: - * - * - `upsert` (boolean) whether to create the doc if it doesn't match (false) - * - `multi` (boolean) whether multiple documents should be updated (false) - * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. - * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). - * - `strict` (boolean) overrides the `strict` option for this update - * - `overwrite` (boolean) disables update-only mode, allowing you to overwrite the doc (false) - * - `context` (string) if set to 'query' and `runValidators` is on, `this` will refer to the query in custom validator functions that update validation runs. Does nothing if `runValidators` is false. - * - `read` - * - `writeConcern` - * - * ####Note - * - * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback, we must first call update() and then execute it by using the `exec()` method. - * - * var q = Model.where({ _id: id }); - * q.update({ $set: { name: 'bob' }}).update(); // not executed - * - * q.update({ $set: { name: 'bob' }}).exec(); // executed - * - * // keys that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) ops become `$set`. - * // this executes the same command as the previous example. - * q.update({ name: 'bob' }).exec(); - * - * // overwriting with empty docs - * var q = Model.where({ _id: id }).setOptions({ overwrite: true }) - * q.update({ }, callback); // executes - * - * // multi update with overwrite to empty doc - * var q = Model.where({ _id: id }); - * q.setOptions({ multi: true, overwrite: true }) - * q.update({ }); - * q.update(callback); // executed - * - * // multi updates - * Model.where() - * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) - * - * // more multi updates - * Model.where() - * .setOptions({ multi: true }) - * .update({ $set: { arr: [] }}, callback) - * - * // single update by default - * Model.where({ email: 'address@example.com' }) - * .update({ $inc: { counter: 1 }}, callback) - * - * API summary - * - * update(filter, doc, options, cb) // executes - * update(filter, doc, options) - * update(filter, doc, cb) // executes - * update(filter, doc) - * update(doc, cb) // executes - * update(doc) - * update(cb) // executes - * update(true) // executes - * update() - * - * @param {Object} [filter] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] params are (error, writeOpResult) - * @return {Query} this - * @see Model.update #model_Model.update - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @api public - */ - -Query.prototype.update = function(conditions, doc, options, callback) { - if (typeof options === 'function') { - // .update(conditions, doc, callback) - callback = options; - options = null; - } else if (typeof doc === 'function') { - // .update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if (typeof conditions === 'function') { - // .update(callback) - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } else if (typeof conditions === 'object' && !doc && !options && !callback) { - // .update(doc) - doc = conditions; - conditions = undefined; - options = undefined; - callback = undefined; - } - - return _update(this, 'update', conditions, doc, options, callback); -}; - -/** - * Declare and/or execute this query as an updateMany() operation. Same as - * `update()`, except MongoDB will update _all_ documents that match - * `filter` (as opposed to just the first one) regardless of the value of - * the `multi` option. - * - * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')` - * and `post('updateMany')` instead. - * - * ####Example: - * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true }); - * res.n; // Number of documents matched - * res.nModified; // Number of documents modified - * - * This function triggers the following middleware. - * - * - `updateMany()` - * - * @param {Object} [filter] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] params are (error, writeOpResult) - * @return {Query} this - * @see Model.update #model_Model.update - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @api public - */ - -Query.prototype.updateMany = function(conditions, doc, options, callback) { - if (typeof options === 'function') { - // .update(conditions, doc, callback) - callback = options; - options = null; - } else if (typeof doc === 'function') { - // .update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if (typeof conditions === 'function') { - // .update(callback) - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } else if (typeof conditions === 'object' && !doc && !options && !callback) { - // .update(doc) - doc = conditions; - conditions = undefined; - options = undefined; - callback = undefined; - } - - return _update(this, 'updateMany', conditions, doc, options, callback); -}; - -/** - * Declare and/or execute this query as an updateOne() operation. Same as - * `update()`, except it does not support the `multi` or `overwrite` options. - * - * - MongoDB will update _only_ the first document that matches `filter` regardless of the value of the `multi` option. - * - Use `replaceOne()` if you want to overwrite an entire document rather than using [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators like `$set`. - * - * **Note** updateOne will _not_ fire update middleware. Use `pre('updateOne')` - * and `post('updateOne')` instead. - * - * ####Example: - * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' }); - * res.n; // Number of documents matched - * res.nModified; // Number of documents modified - * - * This function triggers the following middleware. - * - * - `updateOne()` - * - * @param {Object} [filter] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] params are (error, writeOpResult) - * @return {Query} this - * @see Model.update #model_Model.update - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @api public - */ - -Query.prototype.updateOne = function(conditions, doc, options, callback) { - if (typeof options === 'function') { - // .update(conditions, doc, callback) - callback = options; - options = null; - } else if (typeof doc === 'function') { - // .update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if (typeof conditions === 'function') { - // .update(callback) - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } else if (typeof conditions === 'object' && !doc && !options && !callback) { - // .update(doc) - doc = conditions; - conditions = undefined; - options = undefined; - callback = undefined; - } - - return _update(this, 'updateOne', conditions, doc, options, callback); -}; - -/** - * Declare and/or execute this query as a replaceOne() operation. Same as - * `update()`, except MongoDB will replace the existing document and will - * not accept any [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.) - * - * **Note** replaceOne will _not_ fire update middleware. Use `pre('replaceOne')` - * and `post('replaceOne')` instead. - * - * ####Example: - * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' }); - * res.n; // Number of documents matched - * res.nModified; // Number of documents modified - * - * This function triggers the following middleware. - * - * - `replaceOne()` - * - * @param {Object} [filter] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Boolean} [options.multipleCastError] by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors. - * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) - * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document - * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) - * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. - * @param {Function} [callback] params are (error, writeOpResult) - * @return {Query} this - * @see Model.update #model_Model.update - * @see Query docs https://mongoosejs.com/docs/queries.html - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult - * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output - * @api public - */ - -Query.prototype.replaceOne = function(conditions, doc, options, callback) { - if (typeof options === 'function') { - // .update(conditions, doc, callback) - callback = options; - options = null; - } else if (typeof doc === 'function') { - // .update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if (typeof conditions === 'function') { - // .update(callback) - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } else if (typeof conditions === 'object' && !doc && !options && !callback) { - // .update(doc) - doc = conditions; - conditions = undefined; - options = undefined; - callback = undefined; - } - - this.setOptions({ overwrite: true }); - return _update(this, 'replaceOne', conditions, doc, options, callback); -}; - -/*! - * Internal helper for update, updateMany, updateOne, replaceOne - */ - -function _update(query, op, filter, doc, options, callback) { - // make sure we don't send in the whole Document to merge() - query.op = op; - filter = utils.toObject(filter); - doc = doc || {}; - - // strict is an option used in the update checking, make sure it gets set - if (options != null) { - if ('strict' in options) { - query._mongooseOptions.strict = options.strict; - } - } - - if (!(filter instanceof Query) && - filter != null && - filter.toString() !== '[object Object]') { - query.error(new ObjectParameterError(filter, 'filter', op)); - } else { - query.merge(filter); - } - - if (utils.isObject(options)) { - query.setOptions(options); - } - - query._mergeUpdate(doc); - - // Hooks - if (callback) { - query.exec(callback); - - return query; - } - - return Query.base[op].call(query, filter, void 0, options, callback); -} - -/** - * Runs a function `fn` and treats the return value of `fn` as the new value - * for the query to resolve to. - * - * Any functions you pass to `map()` will run **after** any post hooks. - * - * ####Example: - * - * const res = await MyModel.findOne().map(res => { - * // Sets a `loadedAt` property on the doc that tells you the time the - * // document was loaded. - * return res == null ? - * res : - * Object.assign(res, { loadedAt: new Date() }); - * }); - * - * @method map - * @memberOf Query - * @instance - * @param {Function} fn function to run to transform the query result - * @return {Query} this - */ - -Query.prototype.map = function(fn) { - this._transforms.push(fn); - return this; -}; - -/** - * Make this query throw an error if no documents match the given `filter`. - * This is handy for integrating with async/await, because `orFail()` saves you - * an extra `if` statement to check if no document was found. - * - * ####Example: - * - * // Throws if no doc returned - * await Model.findOne({ foo: 'bar' }).orFail(); - * - * // Throws if no document was updated - * await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail(); - * - * // Throws "No docs found!" error if no docs match `{ foo: 'bar' }` - * await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!')); - * - * // Throws "Not found" error if no document was found - * await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }). - * orFail(() => Error('Not found')); - * - * @method orFail - * @memberOf Query - * @instance - * @param {Function|Error} [err] optional error to throw if no docs match `filter`. If not specified, `orFail()` will throw a `DocumentNotFoundError` - * @return {Query} this - */ - -Query.prototype.orFail = function(err) { - this.map(res => { - switch (this.op) { - case 'find': - if (res.length === 0) { - throw _orFailError(err, this); - } - break; - case 'findOne': - if (res == null) { - throw _orFailError(err, this); - } - break; - case 'update': - case 'updateMany': - case 'updateOne': - if (get(res, 'nModified') === 0) { - throw _orFailError(err, this); - } - break; - case 'findOneAndDelete': - if (get(res, 'lastErrorObject.n') === 0) { - throw _orFailError(err, this); - } - break; - case 'findOneAndUpdate': - case 'findOneAndReplace': - if (get(res, 'lastErrorObject.updatedExisting') === false) { - throw _orFailError(err, this); - } - break; - case 'deleteMany': - case 'deleteOne': - case 'remove': - if (res.n === 0) { - throw _orFailError(err, this); - } - break; - default: - break; - } - - return res; - }); - return this; -}; - -/*! - * Get the error to throw for `orFail()` - */ - -function _orFailError(err, query) { - if (typeof err === 'function') { - err = err.call(query); - } - - if (err == null) { - err = new DocumentNotFoundError(query.getQuery(), query.model.modelName); - } - - return err; -} - -/** - * Executes the query - * - * ####Examples: - * - * var promise = query.exec(); - * var promise = query.exec('update'); - * - * query.exec(callback); - * query.exec('find', callback); - * - * @param {String|Function} [operation] - * @param {Function} [callback] optional params depend on the function being called - * @return {Promise} - * @api public - */ - -Query.prototype.exec = function exec(op, callback) { - const _this = this; - // Ensure that `exec()` is the first thing that shows up in - // the stack when cast errors happen. - const castError = new CastError(); - - if (typeof op === 'function') { - callback = op; - op = null; - } else if (typeof op === 'string') { - this.op = op; - } - - callback = this.model.$handleCallbackError(callback); - - return promiseOrCallback(callback, (cb) => { - cb = this.model.$wrapCallback(cb); - - if (!_this.op) { - cb(); - return; - } - - this._hooks.execPre('exec', this, [], (error) => { - if (error != null) { - return cb(_cleanCastErrorStack(castError, error)); - } - let thunk = '_' + this.op; - if (this.op === 'update') { - thunk = '_execUpdate'; - } else if (this.op === 'distinct') { - thunk = '__distinct'; - } - this[thunk].call(this, (error, res) => { - if (error) { - return cb(_cleanCastErrorStack(castError, error)); - } - - this._hooks.execPost('exec', this, [], {}, (error) => { - if (error) { - return cb(_cleanCastErrorStack(castError, error)); - } - - cb(null, res); - }); - }); - }); - }, this.model.events); -}; - -/*! - * ignore - */ - -function _cleanCastErrorStack(castError, error) { - if (error instanceof CastError) { - castError.copy(error); - return castError; - } - - return error; -} - -/*! - * ignore - */ - -function _wrapThunkCallback(query, cb) { - return function(error, res) { - if (error != null) { - return cb(error); - } - - for (const fn of query._transforms) { - try { - res = fn(res); - } catch (error) { - return cb(error); - } - } - - return cb(null, res); - }; -} - -/** - * Executes the query returning a `Promise` which will be - * resolved with either the doc(s) or rejected with the error. - * - * @param {Function} [resolve] - * @param {Function} [reject] - * @return {Promise} - * @api public - */ - -Query.prototype.then = function(resolve, reject) { - return this.exec().then(resolve, reject); -}; - -/** - * Executes the query returning a `Promise` which will be - * resolved with either the doc(s) or rejected with the error. - * Like `.then()`, but only takes a rejection handler. - * - * @param {Function} [reject] - * @return {Promise} - * @api public - */ - -Query.prototype.catch = function(reject) { - return this.exec().then(null, reject); -}; - -/*! - * ignore - */ - -Query.prototype._pre = function(fn) { - this._hooks.pre('exec', fn); - return this; -}; - -/*! - * ignore - */ - -Query.prototype._post = function(fn) { - this._hooks.post('exec', fn); - return this; -}; - -/*! - * Casts obj for an update command. - * - * @param {Object} obj - * @return {Object} obj after casting its values - * @api private - */ - -Query.prototype._castUpdate = function _castUpdate(obj, overwrite) { - let strict; - if ('strict' in this._mongooseOptions) { - strict = this._mongooseOptions.strict; - } else if (this.schema && this.schema.options) { - strict = this.schema.options.strict; - } else { - strict = true; - } - - let omitUndefined = false; - if ('omitUndefined' in this._mongooseOptions) { - omitUndefined = this._mongooseOptions.omitUndefined; - } - - let useNestedStrict; - if ('useNestedStrict' in this.options) { - useNestedStrict = this.options.useNestedStrict; - } - - let upsert; - if ('upsert' in this.options) { - upsert = this.options.upsert; - } - - let schema = this.schema; - const filter = this._conditions; - if (schema != null && - utils.hasUserDefinedProperty(filter, schema.options.discriminatorKey) && - typeof filter[schema.options.discriminatorKey] !== 'object' && - schema.discriminators != null) { - const discriminatorValue = filter[schema.options.discriminatorKey]; - const byValue = getDiscriminatorByValue(this.model, discriminatorValue); - schema = schema.discriminators[discriminatorValue] || - (byValue && byValue.schema) || - schema; - } - - return castUpdate(schema, obj, { - overwrite: overwrite, - strict: strict, - omitUndefined, - useNestedStrict: useNestedStrict, - upsert: upsert - }, this, this._conditions); -}; - -/*! - * castQuery - * @api private - */ - -function castQuery(query) { - try { - return query.cast(query.model); - } catch (err) { - return err; - } -} - -/*! - * castDoc - * @api private - */ - -function castDoc(query, overwrite) { - try { - return query._castUpdate(query._update, overwrite); - } catch (err) { - return err; - } -} - -/** - * Specifies paths which should be populated with other documents. - * - * ####Example: - * - * let book = await Book.findOne().populate('authors'); - * book.title; // 'Node.js in Action' - * book.authors[0].name; // 'TJ Holowaychuk' - * book.authors[1].name; // 'Nathan Rajlich' - * - * let books = await Book.find().populate({ - * path: 'authors', - * // `match` and `sort` apply to the Author model, - * // not the Book model. These options do not affect - * // which documents are in `books`, just the order and - * // contents of each book document's `authors`. - * match: { name: new RegExp('.*h.*', 'i') }, - * sort: { name: -1 } - * }); - * books[0].title; // 'Node.js in Action' - * // Each book's `authors` are sorted by name, descending. - * books[0].authors[0].name; // 'TJ Holowaychuk' - * books[0].authors[1].name; // 'Marc Harter' - * - * books[1].title; // 'Professional AngularJS' - * // Empty array, no authors' name has the letter 'h' - * books[1].authors; // [] - * - * Paths are populated after the query executes and a response is received. A - * separate query is then executed for each path specified for population. After - * a response for each query has also been returned, the results are passed to - * the callback. - * - * @param {Object|String} path either the path to populate or an object specifying all parameters - * @param {Object|String} [select] Field selection for the population query - * @param {Model} [model] The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's `ref` field. - * @param {Object} [match] Conditions for the population query - * @param {Object} [options] Options for the population query (sort, etc) - * @param {String} [options.path=null] The path to populate. - * @param {boolean} [options.retainNullValues=false] by default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries. - * @param {boolean} [options.getters=false] if true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options). - * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them. - * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object. - * @param {Object} [options.options=null] Additional options like `limit` and `lean`. - * @see population ./populate.html - * @see Query#select #query_Query-select - * @see Model.populate #model_Model.populate - * @return {Query} this - * @api public - */ - -Query.prototype.populate = function() { - // Bail when given no truthy arguments - if (!Array.from(arguments).some(Boolean)) { - return this; - } - - const res = utils.populate.apply(null, arguments); - - // Propagate readConcern and readPreference and lean from parent query, - // unless one already specified - if (this.options != null) { - const readConcern = this.options.readConcern; - const readPref = this.options.readPreference; - - for (const populateOptions of res) { - if (readConcern != null && get(populateOptions, 'options.readConcern') == null) { - populateOptions.options = populateOptions.options || {}; - populateOptions.options.readConcern = readConcern; - } - if (readPref != null && get(populateOptions, 'options.readPreference') == null) { - populateOptions.options = populateOptions.options || {}; - populateOptions.options.readPreference = readPref; - } - } - } - - const opts = this._mongooseOptions; - - if (opts.lean != null) { - const lean = opts.lean; - for (const populateOptions of res) { - if (get(populateOptions, 'options.lean') == null) { - populateOptions.options = populateOptions.options || {}; - populateOptions.options.lean = lean; - } - } - } - - if (!utils.isObject(opts.populate)) { - opts.populate = {}; - } - - const pop = opts.populate; - - for (const populateOptions of res) { - const path = populateOptions.path; - if (pop[path] && pop[path].populate && populateOptions.populate) { - populateOptions.populate = pop[path].populate.concat(populateOptions.populate); - } - - pop[populateOptions.path] = populateOptions; - } - - return this; -}; - -/** - * Gets a list of paths to be populated by this query - * - * ####Example: - * bookSchema.pre('findOne', function() { - * let keys = this.getPopulatedPaths(); // ['author'] - * }); - * ... - * Book.findOne({}).populate('author'); - * - * ####Example: - * // Deep populate - * const q = L1.find().populate({ - * path: 'level2', - * populate: { path: 'level3' } - * }); - * q.getPopulatedPaths(); // ['level2', 'level2.level3'] - * - * @return {Array} an array of strings representing populated paths - * @api public - */ - -Query.prototype.getPopulatedPaths = function getPopulatedPaths() { - const obj = this._mongooseOptions.populate || {}; - const ret = Object.keys(obj); - for (const path of Object.keys(obj)) { - const pop = obj[path]; - if (!Array.isArray(pop.populate)) { - continue; - } - _getPopulatedPaths(ret, pop.populate, path + '.'); - } - return ret; -}; - -/*! - * ignore - */ - -function _getPopulatedPaths(list, arr, prefix) { - for (const pop of arr) { - list.push(prefix + pop.path); - if (!Array.isArray(pop.populate)) { - continue; - } - _getPopulatedPaths(list, pop.populate, prefix + pop.path + '.'); - } -} - -/** - * Casts this query to the schema of `model` - * - * ####Note - * - * If `obj` is present, it is cast instead of this query. - * - * @param {Model} [model] the model to cast to. If not set, defaults to `this.model` - * @param {Object} [obj] - * @return {Object} - * @api public - */ - -Query.prototype.cast = function(model, obj) { - obj || (obj = this._conditions); - - model = model || this.model; - - const discriminatorKey = model.schema.options.discriminatorKey; - if (obj != null && - obj.hasOwnProperty(discriminatorKey)) { - model = getDiscriminatorByValue(model, obj[discriminatorKey]) || model; - } - - try { - return cast(model.schema, obj, { - upsert: this.options && this.options.upsert, - strict: (this.options && 'strict' in this.options) ? - this.options.strict : - get(model, 'schema.options.strict', null), - strictQuery: (this.options && this.options.strictQuery) || - get(model, 'schema.options.strictQuery', null) - }, this); - } catch (err) { - // CastError, assign model - if (typeof err.setModel === 'function') { - err.setModel(model); - } - throw err; - } -}; - -/** - * Casts selected field arguments for field selection with mongo 2.2 - * - * query.select({ ids: { $elemMatch: { $in: [hexString] }}) - * - * @param {Object} fields - * @see https://github.com/Automattic/mongoose/issues/1091 - * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ - * @api private - */ - -Query.prototype._castFields = function _castFields(fields) { - let selected, - elemMatchKeys, - keys, - key, - out, - i; - - if (fields) { - keys = Object.keys(fields); - elemMatchKeys = []; - i = keys.length; - - // collect $elemMatch args - while (i--) { - key = keys[i]; - if (fields[key].$elemMatch) { - selected || (selected = {}); - selected[key] = fields[key]; - elemMatchKeys.push(key); - } - } - } - - if (selected) { - // they passed $elemMatch, cast em - try { - out = this.cast(this.model, selected); - } catch (err) { - return err; - } - - // apply the casted field args - i = elemMatchKeys.length; - while (i--) { - key = elemMatchKeys[i]; - fields[key] = out[key]; - } - } - - return fields; -}; - -/** - * Applies schematype selected options to this query. - * @api private - */ - -Query.prototype._applyPaths = function applyPaths() { - this._fields = this._fields || {}; - helpers.applyPaths(this._fields, this.model.schema); - - let _selectPopulatedPaths = true; - - if ('selectPopulatedPaths' in this.model.base.options) { - _selectPopulatedPaths = this.model.base.options.selectPopulatedPaths; - } - if ('selectPopulatedPaths' in this.model.schema.options) { - _selectPopulatedPaths = this.model.schema.options.selectPopulatedPaths; - } - - if (_selectPopulatedPaths) { - selectPopulatedFields(this); - } -}; - -/** - * Returns a wrapper around a [mongodb driver cursor](http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html). - * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function. - * - * The `.cursor()` function triggers pre find hooks, but **not** post find hooks. - * - * ####Example - * - * // There are 2 ways to use a cursor. First, as a stream: - * Thing. - * find({ name: /^hello/ }). - * cursor(). - * on('data', function(doc) { console.log(doc); }). - * on('end', function() { console.log('Done!'); }); - * - * // Or you can use `.next()` to manually get the next doc in the stream. - * // `.next()` returns a promise, so you can use promises or callbacks. - * var cursor = Thing.find({ name: /^hello/ }).cursor(); - * cursor.next(function(error, doc) { - * console.log(doc); - * }); - * - * // Because `.next()` returns a promise, you can use co - * // to easily iterate through all documents without loading them - * // all into memory. - * co(function*() { - * const cursor = Thing.find({ name: /^hello/ }).cursor(); - * for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) { - * console.log(doc); - * } - * }); - * - * ####Valid options - * - * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data` and returned by `.next()`. - * - * @return {QueryCursor} - * @param {Object} [options] - * @see QueryCursor - * @api public - */ - -Query.prototype.cursor = function cursor(opts) { - this._applyPaths(); - this._fields = this._castFields(this._fields); - this.setOptions({ projection: this._fieldsForExec() }); - if (opts) { - this.setOptions(opts); - } - - const options = Object.assign({}, this._optionsForExec(), { - projection: this.projection() - }); - try { - this.cast(this.model); - } catch (err) { - return (new QueryCursor(this, options))._markError(err); - } - - return new QueryCursor(this, options); -}; - -// the rest of these are basically to support older Mongoose syntax with mquery - -/** - * _DEPRECATED_ Alias of `maxScan` - * - * @deprecated - * @see maxScan #query_Query-maxScan - * @method maxscan - * @memberOf Query - * @instance - */ - -Query.prototype.maxscan = Query.base.maxScan; - -/** - * Sets the tailable option (for use with capped collections). - * - * ####Example - * - * query.tailable() // true - * query.tailable(true) - * query.tailable(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Boolean} bool defaults to true - * @param {Object} [opts] options to set - * @param {Number} [opts.numberOfRetries] if cursor is exhausted, retry this many times before giving up - * @param {Number} [opts.tailableRetryInterval] if cursor is exhausted, wait this many milliseconds before retrying - * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/ - * @api public - */ - -Query.prototype.tailable = function(val, opts) { - // we need to support the tailable({ awaitdata : true }) as well as the - // tailable(true, {awaitdata :true}) syntax that mquery does not support - if (val && val.constructor.name === 'Object') { - opts = val; - val = true; - } - - if (val === undefined) { - val = true; - } - - if (opts && typeof opts === 'object') { - for (const key in opts) { - if (key === 'awaitdata') { - // For backwards compatibility - this.options[key] = !!opts[key]; - } else { - this.options[key] = opts[key]; - } - } - } - - return Query.base.tailable.call(this, val); -}; - -/** - * Declares an intersects query for `geometry()`. - * - * ####Example - * - * query.where('path').intersects().geometry({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * query.where('path').intersects({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * ####NOTE: - * - * **MUST** be used after `where()`. - * - * ####NOTE: - * - * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). - * - * @method intersects - * @memberOf Query - * @instance - * @param {Object} [arg] - * @return {Query} this - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/ - * @api public - */ - -/** - * Specifies a `$geometry` condition - * - * ####Example - * - * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] - * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) - * - * // or - * var polyB = [[ 0, 0 ], [ 1, 1 ]] - * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) - * - * // or - * var polyC = [ 0, 0 ] - * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) - * - * // or - * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) - * - * The argument is assigned to the most recent path passed to `where()`. - * - * ####NOTE: - * - * `geometry()` **must** come after either `intersects()` or `within()`. - * - * The `object` argument must contain `type` and `coordinates` properties. - * - type {String} - * - coordinates {Array} - * - * @method geometry - * @memberOf Query - * @instance - * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. - * @return {Query} this - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/** - * Specifies a `$near` or `$nearSphere` condition - * - * These operators return documents sorted by distance. - * - * ####Example - * - * query.where('loc').near({ center: [10, 10] }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); - * query.near('loc', { center: [10, 10], maxDistance: 5 }); - * - * @method near - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see $near http://docs.mongodb.org/manual/reference/operator/near/ - * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/*! - * Overwriting mquery is needed to support a couple different near() forms found in older - * versions of mongoose - * near([1,1]) - * near(1,1) - * near(field, [1,2]) - * near(field, 1, 2) - * In addition to all of the normal forms supported by mquery - */ - -Query.prototype.near = function() { - const params = []; - const sphere = this._mongooseOptions.nearSphere; - - // TODO refactor - - if (arguments.length === 1) { - if (Array.isArray(arguments[0])) { - params.push({ center: arguments[0], spherical: sphere }); - } else if (typeof arguments[0] === 'string') { - // just passing a path - params.push(arguments[0]); - } else if (utils.isObject(arguments[0])) { - if (typeof arguments[0].spherical !== 'boolean') { - arguments[0].spherical = sphere; - } - params.push(arguments[0]); - } else { - throw new TypeError('invalid argument'); - } - } else if (arguments.length === 2) { - if (typeof arguments[0] === 'number' && typeof arguments[1] === 'number') { - params.push({ center: [arguments[0], arguments[1]], spherical: sphere }); - } else if (typeof arguments[0] === 'string' && Array.isArray(arguments[1])) { - params.push(arguments[0]); - params.push({ center: arguments[1], spherical: sphere }); - } else if (typeof arguments[0] === 'string' && utils.isObject(arguments[1])) { - params.push(arguments[0]); - if (typeof arguments[1].spherical !== 'boolean') { - arguments[1].spherical = sphere; - } - params.push(arguments[1]); - } else { - throw new TypeError('invalid argument'); - } - } else if (arguments.length === 3) { - if (typeof arguments[0] === 'string' && typeof arguments[1] === 'number' - && typeof arguments[2] === 'number') { - params.push(arguments[0]); - params.push({ center: [arguments[1], arguments[2]], spherical: sphere }); - } else { - throw new TypeError('invalid argument'); - } - } else { - throw new TypeError('invalid argument'); - } - - return Query.base.near.apply(this, params); -}; - -/** - * _DEPRECATED_ Specifies a `$nearSphere` condition - * - * ####Example - * - * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); - * - * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`. - * - * ####Example - * - * query.where('loc').near({ center: [10, 10], spherical: true }); - * - * @deprecated - * @see near() #query_Query-near - * @see $near http://docs.mongodb.org/manual/reference/operator/near/ - * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - */ - -Query.prototype.nearSphere = function() { - this._mongooseOptions.nearSphere = true; - this.near.apply(this, arguments); - return this; -}; - -/** - * Returns an asyncIterator for use with [`for/await/of` loops](http://bit.ly/async-iterators) - * This function *only* works for `find()` queries. - * You do not need to call this function explicitly, the JavaScript runtime - * will call it for you. - * - * ####Example - * - * for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) { - * console.log(doc.name); - * } - * - * Node.js 10.x supports async iterators natively without any flags. You can - * enable async iterators in Node.js 8.x using the [`--harmony_async_iteration` flag](https://github.com/tc39/proposal-async-iteration/issues/117#issuecomment-346695187). - * - * **Note:** This function is not if `Symbol.asyncIterator` is undefined. If - * `Symbol.asyncIterator` is undefined, that means your Node.js version does not - * support async iterators. - * - * @method Symbol.asyncIterator - * @memberOf Query - * @instance - * @api public - */ - -if (Symbol.asyncIterator != null) { - Query.prototype[Symbol.asyncIterator] = function() { - return this.cursor().transformNull().map(doc => { - return doc == null ? { done: true } : { value: doc, done: false }; - }); - }; -} - -/** - * Specifies a `$polygon` condition - * - * ####Example - * - * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) - * query.polygon('loc', [10,20], [13, 25], [7,15]) - * - * @method polygon - * @memberOf Query - * @instance - * @param {String|Array} [path] - * @param {Array|Object} [coordinatePairs...] - * @return {Query} this - * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/** - * Specifies a `$box` condition - * - * ####Example - * - * var lowerLeft = [40.73083, -73.99756] - * var upperRight= [40.741404, -73.988135] - * - * query.where('loc').within().box(lowerLeft, upperRight) - * query.box({ ll : lowerLeft, ur : upperRight }) - * - * @method box - * @memberOf Query - * @instance - * @see $box http://docs.mongodb.org/manual/reference/operator/box/ - * @see within() Query#within #query_Query-within - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @param {Object} val - * @param [Array] Upper Right Coords - * @return {Query} this - * @api public - */ - -/*! - * this is needed to support the mongoose syntax of: - * box(field, { ll : [x,y], ur : [x2,y2] }) - * box({ ll : [x,y], ur : [x2,y2] }) - */ - -Query.prototype.box = function(ll, ur) { - if (!Array.isArray(ll) && utils.isObject(ll)) { - ur = ll.ur; - ll = ll.ll; - } - return Query.base.box.call(this, ll, ur); -}; - -/** - * Specifies a `$center` or `$centerSphere` condition. - * - * ####Example - * - * var area = { center: [50, 50], radius: 10, unique: true } - * query.where('loc').within().circle(area) - * // alternatively - * query.circle('loc', area); - * - * // spherical calculations - * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } - * query.where('loc').within().circle(area) - * // alternatively - * query.circle('loc', area); - * - * @method circle - * @memberOf Query - * @instance - * @param {String} [path] - * @param {Object} area - * @return {Query} this - * @see $center http://docs.mongodb.org/manual/reference/operator/center/ - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/geoWithin/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/** - * _DEPRECATED_ Alias for [circle](#query_Query-circle) - * - * **Deprecated.** Use [circle](#query_Query-circle) instead. - * - * @deprecated - * @method center - * @memberOf Query - * @instance - * @api public - */ - -Query.prototype.center = Query.base.circle; - -/** - * _DEPRECATED_ Specifies a `$centerSphere` condition - * - * **Deprecated.** Use [circle](#query_Query-circle) instead. - * - * ####Example - * - * var area = { center: [50, 50], radius: 10 }; - * query.where('loc').within().centerSphere(area); - * - * @deprecated - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @api public - */ - -Query.prototype.centerSphere = function() { - if (arguments[0] && arguments[0].constructor.name === 'Object') { - arguments[0].spherical = true; - } - - if (arguments[1] && arguments[1].constructor.name === 'Object') { - arguments[1].spherical = true; - } - - Query.base.circle.apply(this, arguments); -}; - -/** - * Determines if field selection has been made. - * - * @method selected - * @memberOf Query - * @instance - * @return {Boolean} - * @api public - */ - -/** - * Determines if inclusive field selection has been made. - * - * query.selectedInclusively() // false - * query.select('name') - * query.selectedInclusively() // true - * - * @method selectedInclusively - * @memberOf Query - * @instance - * @return {Boolean} - * @api public - */ - -Query.prototype.selectedInclusively = function selectedInclusively() { - return isInclusive(this._fields); -}; - -/** - * Determines if exclusive field selection has been made. - * - * query.selectedExclusively() // false - * query.select('-name') - * query.selectedExclusively() // true - * query.selectedInclusively() // false - * - * @method selectedExclusively - * @memberOf Query - * @instance - * @return {Boolean} - * @api public - */ - -Query.prototype.selectedExclusively = function selectedExclusively() { - if (!this._fields) { - return false; - } - - const keys = Object.keys(this._fields); - for (const key of keys) { - if (key === '_id') { - continue; - } - if (this._fields[key] === 0 || this._fields[key] === false) { - return true; - } - } - - return false; -}; - -/*! - * Export - */ - -module.exports = Query; diff --git a/node_modules/mongoose/lib/queryhelpers.js b/node_modules/mongoose/lib/queryhelpers.js deleted file mode 100644 index 53a6f61..0000000 --- a/node_modules/mongoose/lib/queryhelpers.js +++ /dev/null @@ -1,307 +0,0 @@ -'use strict'; - -/*! - * Module dependencies - */ - -const checkEmbeddedDiscriminatorKeyProjection = - require('./helpers/discriminator/checkEmbeddedDiscriminatorKeyProjection'); -const get = require('./helpers/get'); -const getDiscriminatorByValue = - require('./helpers/discriminator/getDiscriminatorByValue'); -const isDefiningProjection = require('./helpers/projection/isDefiningProjection'); -const clone = require('./helpers/clone'); - -/*! - * Prepare a set of path options for query population. - * - * @param {Query} query - * @param {Object} options - * @return {Array} - */ - -exports.preparePopulationOptions = function preparePopulationOptions(query, options) { - const _populate = query.options.populate; - const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []); - - // lean options should trickle through all queries - if (options.lean != null) { - pop. - filter(p => get(p, 'options.lean') == null). - forEach(makeLean(options.lean)); - } - - return pop; -}; - -/*! - * Prepare a set of path options for query population. This is the MongooseQuery - * version - * - * @param {Query} query - * @param {Object} options - * @return {Array} - */ - -exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ(query, options) { - const _populate = query._mongooseOptions.populate; - const pop = Object.keys(_populate).reduce((vals, key) => vals.concat([_populate[key]]), []); - - // lean options should trickle through all queries - if (options.lean != null) { - pop. - filter(p => get(p, 'options.lean') == null). - forEach(makeLean(options.lean)); - } - - const session = get(query, 'options.session', null); - if (session != null) { - pop.forEach(path => { - if (path.options == null) { - path.options = { session: session }; - return; - } - if (!('session' in path.options)) { - path.options.session = session; - } - }); - } - - const projection = query._fieldsForExec(); - pop.forEach(p => { - p._queryProjection = projection; - }); - - return pop; -}; - -/*! - * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise, - * it returns an instance of the given model. - * - * @param {Model} model - * @param {Object} doc - * @param {Object} fields - * - * @return {Document} - */ -exports.createModel = function createModel(model, doc, fields, userProvidedFields) { - model.hooks.execPreSync('createModel', doc); - const discriminatorMapping = model.schema ? - model.schema.discriminatorMapping : - null; - - const key = discriminatorMapping && discriminatorMapping.isRoot ? - discriminatorMapping.key : - null; - - const value = doc[key]; - if (key && value && model.discriminators) { - const discriminator = model.discriminators[value] || getDiscriminatorByValue(model, value); - if (discriminator) { - const _fields = clone(userProvidedFields); - exports.applyPaths(_fields, discriminator.schema); - return new discriminator(undefined, _fields, true); - } - } - - return new model(undefined, fields, { - skipId: true, - isNew: false, - willInit: true - }); -}; - -/*! - * ignore - */ - -exports.applyPaths = function applyPaths(fields, schema) { - // determine if query is selecting or excluding fields - let exclude; - let keys; - let keyIndex; - - if (fields) { - keys = Object.keys(fields); - keyIndex = keys.length; - - while (keyIndex--) { - if (keys[keyIndex][0] === '+') { - continue; - } - const field = fields[keys[keyIndex]]; - // Skip `$meta` and `$slice` - if (!isDefiningProjection(field)) { - continue; - } - exclude = !field; - break; - } - } - - // if selecting, apply default schematype select:true fields - // if excluding, apply schematype select:false fields - - const selected = []; - const excluded = []; - const stack = []; - - analyzeSchema(schema); - - switch (exclude) { - case true: - for (const fieldName of excluded) { - fields[fieldName] = 0; - } - break; - case false: - if (schema && - schema.paths['_id'] && - schema.paths['_id'].options && - schema.paths['_id'].options.select === false) { - fields._id = 0; - } - - for (const fieldName of selected) { - fields[fieldName] = fields[fieldName] || 1; - } - break; - case undefined: - if (fields == null) { - break; - } - // Any leftover plus paths must in the schema, so delete them (gh-7017) - for (const key of Object.keys(fields || {})) { - if (key.startsWith('+')) { - delete fields[key]; - } - } - - // user didn't specify fields, implies returning all fields. - // only need to apply excluded fields and delete any plus paths - for (const fieldName of excluded) { - fields[fieldName] = 0; - } - break; - } - - function analyzeSchema(schema, prefix) { - prefix || (prefix = ''); - - // avoid recursion - if (stack.indexOf(schema) !== -1) { - return []; - } - stack.push(schema); - - const addedPaths = []; - schema.eachPath(function(path, type) { - if (prefix) path = prefix + '.' + path; - - const addedPath = analyzePath(path, type); - if (addedPath != null) { - addedPaths.push(addedPath); - } - - // nested schemas - if (type.schema) { - const _addedPaths = analyzeSchema(type.schema, path); - - // Special case: if discriminator key is the only field that would - // be projected in, remove it. - if (exclude === false) { - checkEmbeddedDiscriminatorKeyProjection(fields, path, type.schema, - selected, _addedPaths); - } - } - }); - - stack.pop(); - return addedPaths; - } - - function analyzePath(path, type) { - const plusPath = '+' + path; - const hasPlusPath = fields && plusPath in fields; - if (hasPlusPath) { - // forced inclusion - delete fields[plusPath]; - } - - if (typeof type.selected !== 'boolean') return; - - if (hasPlusPath) { - // forced inclusion - delete fields[plusPath]; - - // if there are other fields being included, add this one - // if no other included fields, leave this out (implied inclusion) - if (exclude === false && keys.length > 1 && !~keys.indexOf(path)) { - fields[path] = 1; - } - - return; - } - - // check for parent exclusions - const pieces = path.split('.'); - let cur = ''; - for (let i = 0; i < pieces.length; ++i) { - cur += cur.length ? '.' + pieces[i] : pieces[i]; - if (excluded.indexOf(cur) !== -1) { - return; - } - } - - // Special case: if user has included a parent path of a discriminator key, - // don't explicitly project in the discriminator key because that will - // project out everything else under the parent path - if (!exclude && get(type, 'options.$skipDiscriminatorCheck', false)) { - let cur = ''; - for (let i = 0; i < pieces.length; ++i) { - cur += (cur.length === 0 ? '' : '.') + pieces[i]; - const projection = get(fields, cur, false); - if (projection && typeof projection !== 'object') { - return; - } - } - } - - (type.selected ? selected : excluded).push(path); - return path; - } -}; - -/*! - * Set each path query option to lean - * - * @param {Object} option - */ - -function makeLean(val) { - return function(option) { - option.options || (option.options = {}); - option.options.lean = val; - }; -} - -/*! - * Handle the `WriteOpResult` from the server - */ - -exports.handleDeleteWriteOpResult = function handleDeleteWriteOpResult(callback) { - return function _handleDeleteWriteOpResult(error, res) { - if (error) { - return callback(error); - } - const mongooseResult = Object.assign({}, res.result); - if (get(res, 'result.n', null) != null) { - mongooseResult.deletedCount = res.result.n; - } - if (res.deletedCount != null) { - mongooseResult.deletedCount = res.deletedCount; - } - return callback(null, mongooseResult); - }; -}; diff --git a/node_modules/mongoose/lib/schema.js b/node_modules/mongoose/lib/schema.js deleted file mode 100644 index 777cfce..0000000 --- a/node_modules/mongoose/lib/schema.js +++ /dev/null @@ -1,2194 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const EventEmitter = require('events').EventEmitter; -const Kareem = require('kareem'); -const MongooseError = require('./error/mongooseError'); -const SchemaType = require('./schematype'); -const SchemaTypeOptions = require('./options/SchemaTypeOptions'); -const VirtualOptions = require('./options/VirtualOptions'); -const VirtualType = require('./virtualtype'); -const addAutoId = require('./helpers/schema/addAutoId'); -const applyTimestampsToChildren = require('./helpers/update/applyTimestampsToChildren'); -const applyTimestampsToUpdate = require('./helpers/update/applyTimestampsToUpdate'); -const arrayParentSymbol = require('./helpers/symbols').arrayParentSymbol; -const get = require('./helpers/get'); -const getIndexes = require('./helpers/schema/getIndexes'); -const handleTimestampOption = require('./helpers/schema/handleTimestampOption'); -const merge = require('./helpers/schema/merge'); -const mpath = require('mpath'); -const readPref = require('./driver').get().ReadPreference; -const symbols = require('./schema/symbols'); -const util = require('util'); -const utils = require('./utils'); -const validateRef = require('./helpers/populate/validateRef'); - -let MongooseTypes; - -const queryHooks = require('./helpers/query/applyQueryMiddleware'). - middlewareFunctions; -const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions; -const hookNames = queryHooks.concat(documentHooks). - reduce((s, hook) => s.add(hook), new Set()); - -let id = 0; - -/** - * Schema constructor. - * - * ####Example: - * - * var child = new Schema({ name: String }); - * var schema = new Schema({ name: String, age: Number, children: [child] }); - * var Tree = mongoose.model('Tree', schema); - * - * // setting schema options - * new Schema({ name: String }, { _id: false, autoIndex: false }) - * - * ####Options: - * - * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option) - * - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option) - * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true - * - [capped](/docs/guide.html#capped): bool - defaults to false - * - [collection](/docs/guide.html#collection): string - no default - * - [id](/docs/guide.html#id): bool - defaults to true - * - [_id](/docs/guide.html#_id): bool - defaults to true - * - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true - * - [read](/docs/guide.html#read): string - * - [writeConcern](/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://docs.mongodb.com/manual/reference/write-concern/) - * - [shardKey](/docs/guide.html#shardKey): object - defaults to `null` - * - [strict](/docs/guide.html#strict): bool - defaults to true - * - [strictQuery](/docs/guide.html#strictQuery): bool - defaults to false - * - [toJSON](/docs/guide.html#toJSON) - object - no default - * - [toObject](/docs/guide.html#toObject) - object - no default - * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type' - * - [typePojoToMixed](/docs/guide.html#typePojoToMixed) - boolean - defaults to true. Determines whether a type set to a POJO becomes a Mixed path or a Subdocument - * - [useNestedStrict](/docs/guide.html#useNestedStrict) - boolean - defaults to false - * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true` - * - [versionKey](/docs/guide.html#versionKey): string - defaults to "__v" - * - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation) - * - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true` - * - [skipVersioning](/docs/guide.html#skipVersioning): object - paths to exclude from versioning - * - [timestamps](/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you. - * - [storeSubdocValidationError](/docs/guide.html#storeSubdocValidationError): boolean - Defaults to true. If false, Mongoose will wrap validation errors in single nested document subpaths into a single validation error on the single nested subdoc's path. - * - * ####Options for Nested Schemas: - * - `excludeIndexes`: bool - defaults to `false`. If `true`, skip building indexes on this schema's paths. - * - * ####Note: - * - * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._ - * - * @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas - * @param {Object} [options] - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `init`: Emitted after the schema is compiled into a `Model`. - * @api public - */ - -function Schema(obj, options) { - if (!(this instanceof Schema)) { - return new Schema(obj, options); - } - - this.obj = obj; - this.paths = {}; - this.aliases = {}; - this.subpaths = {}; - this.virtuals = {}; - this.singleNestedPaths = {}; - this.nested = {}; - this.inherits = {}; - this.callQueue = []; - this._indexes = []; - this.methods = {}; - this.methodOptions = {}; - this.statics = {}; - this.tree = {}; - this.query = {}; - this.childSchemas = []; - this.plugins = []; - // For internal debugging. Do not use this to try to save a schema in MDB. - this.$id = ++id; - - this.s = { - hooks: new Kareem() - }; - - this.options = this.defaultOptions(options); - - // build paths - if (Array.isArray(obj)) { - for (const definition of obj) { - this.add(definition); - } - } else if (obj) { - this.add(obj); - } - - // check if _id's value is a subdocument (gh-2276) - const _idSubDoc = obj && obj._id && utils.isObject(obj._id); - - // ensure the documents get an auto _id unless disabled - const auto_id = !this.paths['_id'] && - (!this.options.noId && this.options._id) && !_idSubDoc; - - if (auto_id) { - addAutoId(this); - } - - this.setupTimestamp(this.options.timestamps); -} - -/*! - * Create virtual properties with alias field - */ -function aliasFields(schema, paths) { - paths = paths || Object.keys(schema.paths); - for (const path of paths) { - const options = get(schema.paths[path], 'options'); - if (options == null) { - continue; - } - - const prop = schema.paths[path].path; - const alias = options.alias; - - if (!alias) { - continue; - } - - if (typeof alias !== 'string') { - throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias); - } - - schema.aliases[alias] = prop; - - schema. - virtual(alias). - get((function(p) { - return function() { - if (typeof this.get === 'function') { - return this.get(p); - } - return this[p]; - }; - })(prop)). - set((function(p) { - return function(v) { - return this.set(p, v); - }; - })(prop)); - } -} - -/*! - * Inherit from EventEmitter. - */ -Schema.prototype = Object.create(EventEmitter.prototype); -Schema.prototype.constructor = Schema; -Schema.prototype.instanceOfSchema = true; - -/*! - * ignore - */ - -Object.defineProperty(Schema.prototype, '$schemaType', { - configurable: false, - enumerable: false, - writable: true -}); - -/** - * Array of child schemas (from document arrays and single nested subdocs) - * and their corresponding compiled models. Each element of the array is - * an object with 2 properties: `schema` and `model`. - * - * This property is typically only useful for plugin authors and advanced users. - * You do not need to interact with this property at all to use mongoose. - * - * @api public - * @property childSchemas - * @memberOf Schema - * @instance - */ - -Object.defineProperty(Schema.prototype, 'childSchemas', { - configurable: false, - enumerable: true, - writable: true -}); - -/** - * The original object passed to the schema constructor - * - * ####Example: - * - * var schema = new Schema({ a: String }).add({ b: String }); - * schema.obj; // { a: String } - * - * @api public - * @property obj - * @memberOf Schema - * @instance - */ - -Schema.prototype.obj; - -/** - * The paths defined on this schema. The keys are the top-level paths - * in this schema, and the values are instances of the SchemaType class. - * - * ####Example: - * const schema = new Schema({ name: String }, { _id: false }); - * schema.paths; // { name: SchemaString { ... } } - * - * schema.add({ age: Number }); - * schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } } - * - * @api public - * @property paths - * @memberOf Schema - * @instance - */ - -Schema.prototype.paths; - -/** - * Schema as a tree - * - * ####Example: - * { - * '_id' : ObjectId - * , 'nested' : { - * 'key' : String - * } - * } - * - * @api private - * @property tree - * @memberOf Schema - * @instance - */ - -Schema.prototype.tree; - -/** - * Returns a deep copy of the schema - * - * ####Example: - * - * const schema = new Schema({ name: String }); - * const clone = schema.clone(); - * clone === schema; // false - * clone.path('name'); // SchemaString { ... } - * - * @return {Schema} the cloned schema - * @api public - * @memberOf Schema - * @instance - */ - -Schema.prototype.clone = function() { - const s = new Schema({}, this._userProvidedOptions); - s.base = this.base; - s.obj = this.obj; - s.options = utils.clone(this.options); - s.callQueue = this.callQueue.map(function(f) { return f; }); - s.methods = utils.clone(this.methods); - s.methodOptions = utils.clone(this.methodOptions); - s.statics = utils.clone(this.statics); - s.query = utils.clone(this.query); - s.plugins = Array.prototype.slice.call(this.plugins); - s._indexes = utils.clone(this._indexes); - s.s.hooks = this.s.hooks.clone(); - - s.tree = utils.clone(this.tree); - s.paths = utils.clone(this.paths); - s.nested = utils.clone(this.nested); - s.subpaths = utils.clone(this.subpaths); - s.singleNestedPaths = utils.clone(this.singleNestedPaths); - s.childSchemas = gatherChildSchemas(s); - - s.virtuals = utils.clone(this.virtuals); - s.$globalPluginsApplied = this.$globalPluginsApplied; - s.$isRootDiscriminator = this.$isRootDiscriminator; - s.$implicitlyCreated = this.$implicitlyCreated; - - if (this.discriminatorMapping != null) { - s.discriminatorMapping = Object.assign({}, this.discriminatorMapping); - } - if (this.discriminators != null) { - s.discriminators = Object.assign({}, this.discriminators); - } - - s.aliases = Object.assign({}, this.aliases); - - // Bubble up `init` for backwards compat - s.on('init', v => this.emit('init', v)); - - return s; -}; - -/** - * Returns a new schema that has the picked `paths` from this schema. - * - * This method is analagous to [Lodash's `pick()` function](https://lodash.com/docs/4.17.15#pick) for Mongoose schemas. - * - * ####Example: - * - * const schema = Schema({ name: String, age: Number }); - * // Creates a new schema with the same `name` path as `schema`, - * // but no `age` path. - * const newSchema = schema.pick(['name']); - * - * newSchema.path('name'); // SchemaString { ... } - * newSchema.path('age'); // undefined - * - * @param {Array} paths list of paths to pick - * @param {Object} [options] options to pass to the schema constructor. Defaults to `this.options` if not set. - * @return {Schema} - * @api public - */ - -Schema.prototype.pick = function(paths, options) { - const newSchema = new Schema({}, options || this.options); - if (!Array.isArray(paths)) { - throw new MongooseError('Schema#pick() only accepts an array argument, ' + - 'got "' + typeof paths + '"'); - } - - for (const path of paths) { - if (this.nested[path]) { - newSchema.add({ [path]: get(this.tree, path) }); - } else { - const schematype = this.path(path); - if (schematype == null) { - throw new MongooseError('Path `' + path + '` is not in the schema'); - } - newSchema.add({ [path]: schematype }); - } - } - - return newSchema; -}; - -/** - * Returns default options for this schema, merged with `options`. - * - * @param {Object} options - * @return {Object} - * @api private - */ - -Schema.prototype.defaultOptions = function(options) { - if (options && options.safe === false) { - options.safe = { w: 0 }; - } - - if (options && options.safe && options.safe.w === 0) { - // if you turn off safe writes, then versioning goes off as well - options.versionKey = false; - } - - this._userProvidedOptions = options == null ? {} : utils.clone(options); - - const baseOptions = get(this, 'base.options', {}); - options = utils.options({ - strict: 'strict' in baseOptions ? baseOptions.strict : true, - bufferCommands: true, - capped: false, // { size, max, autoIndexId } - versionKey: '__v', - discriminatorKey: '__t', - minimize: true, - autoIndex: null, - shardKey: null, - read: null, - validateBeforeSave: true, - // the following are only applied at construction time - noId: false, // deprecated, use { _id: false } - _id: true, - noVirtualId: false, // deprecated, use { id: false } - id: true, - typeKey: 'type', - typePojoToMixed: 'typePojoToMixed' in baseOptions ? baseOptions.typePojoToMixed : true - }, utils.clone(options)); - - if (options.read) { - options.read = readPref(options.read); - } - - return options; -}; - -/** - * Adds key path / schema type pairs to this schema. - * - * ####Example: - * - * const ToySchema = new Schema(); - * ToySchema.add({ name: 'string', color: 'string', price: 'number' }); - * - * const TurboManSchema = new Schema(); - * // You can also `add()` another schema and copy over all paths, virtuals, - * // getters, setters, indexes, methods, and statics. - * TurboManSchema.add(ToySchema).add({ year: Number }); - * - * @param {Object|Schema} obj plain object with paths to add, or another schema - * @param {String} [prefix] path to prefix the newly added paths with - * @return {Schema} the Schema instance - * @api public - */ - -Schema.prototype.add = function add(obj, prefix) { - if (obj instanceof Schema) { - merge(this, obj); - return this; - } - - // Special case: setting top-level `_id` to false should convert to disabling - // the `_id` option. This behavior never worked before 5.4.11 but numerous - // codebases use it (see gh-7516, gh-7512). - if (obj._id === false && prefix == null) { - this.options._id = false; - } - - prefix = prefix || ''; - const keys = Object.keys(obj); - - for (const key of keys) { - const fullPath = prefix + key; - - if (obj[key] == null) { - throw new TypeError('Invalid value for schema path `' + fullPath + - '`, got value "' + obj[key] + '"'); - } - // Retain `_id: false` but don't set it as a path, re: gh-8274. - if (key === '_id' && obj[key] === false) { - continue; - } - if (obj[key] instanceof VirtualType) { - this.virtual(obj[key]); - continue; - } - - if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) { - throw new TypeError('Invalid value for schema Array path `' + fullPath + - '`, got value "' + obj[key][0] + '"'); - } - - if (!(utils.isPOJO(obj[key]) || obj[key] instanceof SchemaTypeOptions)) { - // Special-case: Non-options definitely a path so leaf at this node - // Examples: Schema instances, SchemaType instances - if (prefix) { - this.nested[prefix.substr(0, prefix.length - 1)] = true; - } - this.path(prefix + key, obj[key]); - } else if (Object.keys(obj[key]).length < 1) { - // Special-case: {} always interpreted as Mixed path so leaf at this node - if (prefix) { - this.nested[prefix.substr(0, prefix.length - 1)] = true; - } - this.path(fullPath, obj[key]); // mixed type - } else if (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type)) { - // Special-case: POJO with no bona-fide type key - interpret as tree of deep paths so recurse - // nested object { last: { name: String }} - this.nested[fullPath] = true; - this.add(obj[key], fullPath + '.'); - } else { - // There IS a bona-fide type key that may also be a POJO - if (!this.options.typePojoToMixed && utils.isPOJO(obj[key][this.options.typeKey])) { - // If a POJO is the value of a type key, make it a subdocument - if (prefix) { - this.nested[prefix.substr(0, prefix.length - 1)] = true; - } - // Propage `typePojoToMixed` to implicitly created schemas - const opts = { typePojoToMixed: false }; - const _schema = new Schema(obj[key][this.options.typeKey], opts); - const schemaWrappedPath = Object.assign({}, obj[key], { type: _schema }); - this.path(prefix + key, schemaWrappedPath); - } else { - // Either the type is non-POJO or we interpret it as Mixed anyway - if (prefix) { - this.nested[prefix.substr(0, prefix.length - 1)] = true; - } - this.path(prefix + key, obj[key]); - } - } - } - - const addedKeys = Object.keys(obj). - map(key => prefix ? prefix + key : key); - aliasFields(this, addedKeys); - return this; -}; - -/** - * Reserved document keys. - * - * Keys in this object are names that are rejected in schema declarations - * because they conflict with Mongoose functionality. If you create a schema - * using `new Schema()` with one of these property names, Mongoose will throw - * an error. - * - * - _posts - * - _pres - * - collection - * - db - * - emit - * - errors - * - get - * - init - * - isModified - * - isNew - * - listeners - * - modelName - * - on - * - once - * - populated - * - prototype - * - remove - * - removeListener - * - save - * - schema - * - toObject - * - validate - * - * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on. - * - * var schema = new Schema(..); - * schema.methods.init = function () {} // potentially breaking - */ - -Schema.reserved = Object.create(null); -Schema.prototype.reserved = Schema.reserved; -const reserved = Schema.reserved; -// Core object -reserved['prototype'] = -// EventEmitter -reserved.emit = -reserved.listeners = -reserved.on = -reserved.removeListener = -// document properties and functions -reserved.collection = -reserved.db = -reserved.errors = -reserved.get = -reserved.init = -reserved.isModified = -reserved.isNew = -reserved.populated = -reserved.remove = -reserved.save = -reserved.schema = -reserved.toObject = -reserved.validate = 1; - -/*! - * Document keys to print warnings for - */ - -const warnings = {}; -warnings.increment = '`increment` should not be used as a schema path name ' + - 'unless you have disabled versioning.'; - -/** - * Gets/sets schema paths. - * - * Sets a path (if arity 2) - * Gets a path (if arity 1) - * - * ####Example - * - * schema.path('name') // returns a SchemaType - * schema.path('name', Number) // changes the schemaType of `name` to Number - * - * @param {String} path - * @param {Object} constructor - * @api public - */ - -Schema.prototype.path = function(path, obj) { - // Convert to '.$' to check subpaths re: gh-6405 - const cleanPath = _pathToPositionalSyntax(path); - if (obj === undefined) { - let schematype = _getPath(this, path, cleanPath); - if (schematype != null) { - return schematype; - } - - // Look for maps - const mapPath = getMapPath(this, path); - if (mapPath != null) { - return mapPath; - } - - // Look if a parent of this path is mixed - schematype = this.hasMixedParent(cleanPath); - if (schematype != null) { - return schematype; - } - - // subpaths? - return /\.\d+\.?.*$/.test(path) - ? getPositionalPath(this, path) - : undefined; - } - - // some path names conflict with document methods - const firstPieceOfPath = path.split('.')[0]; - if (reserved[firstPieceOfPath]) { - throw new Error('`' + firstPieceOfPath + '` may not be used as a schema pathname'); - } - - if (warnings[path]) { - console.log('WARN: ' + warnings[path]); - } - - if (typeof obj === 'object' && utils.hasUserDefinedProperty(obj, 'ref')) { - validateRef(obj.ref, path); - } - - // update the tree - const subpaths = path.split(/\./); - const last = subpaths.pop(); - let branch = this.tree; - - subpaths.forEach(function(sub, i) { - if (!branch[sub]) { - branch[sub] = {}; - } - if (typeof branch[sub] !== 'object') { - const msg = 'Cannot set nested path `' + path + '`. ' - + 'Parent path `' - + subpaths.slice(0, i).concat([sub]).join('.') - + '` already set to type ' + branch[sub].name - + '.'; - throw new Error(msg); - } - branch = branch[sub]; - }); - - branch[last] = utils.clone(obj); - - this.paths[path] = this.interpretAsType(path, obj, this.options); - const schemaType = this.paths[path]; - - if (schemaType.$isSchemaMap) { - // Maps can have arbitrary keys, so `$*` is internal shorthand for "any key" - // The '$' is to imply this path should never be stored in MongoDB so we - // can easily build a regexp out of this path, and '*' to imply "any key." - const mapPath = path + '.$*'; - let _mapType = { type: {} }; - if (utils.hasUserDefinedProperty(obj, 'of')) { - const isInlineSchema = utils.isPOJO(obj.of) && - Object.keys(obj.of).length > 0 && - !utils.hasUserDefinedProperty(obj.of, this.options.typeKey); - _mapType = isInlineSchema ? new Schema(obj.of) : obj.of; - } - this.paths[mapPath] = this.interpretAsType(mapPath, - _mapType, this.options); - schemaType.$__schemaType = this.paths[mapPath]; - } - - if (schemaType.$isSingleNested) { - for (const key in schemaType.schema.paths) { - this.singleNestedPaths[path + '.' + key] = schemaType.schema.paths[key]; - } - for (const key in schemaType.schema.singleNestedPaths) { - this.singleNestedPaths[path + '.' + key] = - schemaType.schema.singleNestedPaths[key]; - } - for (const key in schemaType.schema.subpaths) { - this.singleNestedPaths[path + '.' + key] = - schemaType.schema.subpaths[key]; - } - - Object.defineProperty(schemaType.schema, 'base', { - configurable: true, - enumerable: false, - writable: false, - value: this.base - }); - - schemaType.caster.base = this.base; - this.childSchemas.push({ - schema: schemaType.schema, - model: schemaType.caster - }); - } else if (schemaType.$isMongooseDocumentArray) { - Object.defineProperty(schemaType.schema, 'base', { - configurable: true, - enumerable: false, - writable: false, - value: this.base - }); - - schemaType.casterConstructor.base = this.base; - this.childSchemas.push({ - schema: schemaType.schema, - model: schemaType.casterConstructor - }); - } - - if (schemaType.$isMongooseArray && schemaType.caster instanceof SchemaType) { - let arrayPath = path; - let _schemaType = schemaType; - - const toAdd = []; - while (_schemaType.$isMongooseArray) { - arrayPath = arrayPath + '.$'; - - // Skip arrays of document arrays - if (_schemaType.$isMongooseDocumentArray) { - _schemaType.$embeddedSchemaType._arrayPath = arrayPath; - _schemaType = _schemaType.$embeddedSchemaType.clone(); - } else { - _schemaType.caster._arrayPath = arrayPath; - _schemaType = _schemaType.caster.clone(); - } - - _schemaType.path = arrayPath; - toAdd.push(_schemaType); - } - - for (const _schemaType of toAdd) { - this.subpaths[_schemaType.path] = _schemaType; - } - } - - if (schemaType.$isMongooseDocumentArray) { - for (const key of Object.keys(schemaType.schema.paths)) { - this.subpaths[path + '.' + key] = schemaType.schema.paths[key]; - schemaType.schema.paths[key].$isUnderneathDocArray = true; - } - for (const key of Object.keys(schemaType.schema.subpaths)) { - this.subpaths[path + '.' + key] = schemaType.schema.subpaths[key]; - schemaType.schema.subpaths[key].$isUnderneathDocArray = true; - } - for (const key of Object.keys(schemaType.schema.singleNestedPaths)) { - this.subpaths[path + '.' + key] = schemaType.schema.singleNestedPaths[key]; - schemaType.schema.singleNestedPaths[key].$isUnderneathDocArray = true; - } - } - - return this; -}; - -/*! - * ignore - */ - -function gatherChildSchemas(schema) { - const childSchemas = []; - - for (const path of Object.keys(schema.paths)) { - const schematype = schema.paths[path]; - if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) { - childSchemas.push({ schema: schematype.schema, model: schematype.caster }); - } - } - - return childSchemas; -} - -/*! - * ignore - */ - -function _getPath(schema, path, cleanPath) { - if (schema.paths.hasOwnProperty(path)) { - return schema.paths[path]; - } - if (schema.subpaths.hasOwnProperty(cleanPath)) { - return schema.subpaths[cleanPath]; - } - if (schema.singleNestedPaths.hasOwnProperty(cleanPath)) { - return schema.singleNestedPaths[cleanPath]; - } - - return null; -} - -/*! - * ignore - */ - -function _pathToPositionalSyntax(path) { - if (!/\.\d+/.test(path)) { - return path; - } - return path.replace(/\.\d+\./g, '.$.').replace(/\.\d+$/, '.$'); -} - -/*! - * ignore - */ - -function getMapPath(schema, path) { - for (const _path of Object.keys(schema.paths)) { - if (!_path.includes('.$*')) { - continue; - } - const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$'); - if (re.test(path)) { - return schema.paths[_path]; - } - } - - return null; -} - -/** - * The Mongoose instance this schema is associated with - * - * @property base - * @api private - */ - -Object.defineProperty(Schema.prototype, 'base', { - configurable: true, - enumerable: false, - writable: true, - value: null -}); - -/** - * Converts type arguments into Mongoose Types. - * - * @param {String} path - * @param {Object} obj constructor - * @api private - */ - -Schema.prototype.interpretAsType = function(path, obj, options) { - if (obj instanceof SchemaType) { - return obj; - } - - // If this schema has an associated Mongoose object, use the Mongoose object's - // copy of SchemaTypes re: gh-7158 gh-6933 - const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types; - - if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) { - const constructorName = utils.getFunctionName(obj.constructor); - if (constructorName !== 'Object') { - const oldObj = obj; - obj = {}; - obj[options.typeKey] = oldObj; - } - } - - // Get the type making sure to allow keys named "type" - // and default to mixed if not specified. - // { type: { type: String, default: 'freshcut' } } - let type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type) - ? obj[options.typeKey] - : {}; - let name; - - if (utils.isPOJO(type) || type === 'mixed') { - return new MongooseTypes.Mixed(path, obj); - } - - if (Array.isArray(type) || Array === type || type === 'array') { - // if it was specified through { type } look for `cast` - let cast = (Array === type || type === 'array') - ? obj.cast - : type[0]; - - if (cast && cast.instanceOfSchema) { - return new MongooseTypes.DocumentArray(path, cast, obj); - } - if (cast && - cast[options.typeKey] && - cast[options.typeKey].instanceOfSchema) { - return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast); - } - - if (Array.isArray(cast)) { - return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj); - } - - if (typeof cast === 'string') { - cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)]; - } else if (cast && (!cast[options.typeKey] || (options.typeKey === 'type' && cast.type.type)) - && utils.isPOJO(cast)) { - if (Object.keys(cast).length) { - // The `minimize` and `typeKey` options propagate to child schemas - // declared inline, like `{ arr: [{ val: { $type: String } }] }`. - // See gh-3560 - const childSchemaOptions = { minimize: options.minimize }; - if (options.typeKey) { - childSchemaOptions.typeKey = options.typeKey; - } - // propagate 'strict' option to child schema - if (options.hasOwnProperty('strict')) { - childSchemaOptions.strict = options.strict; - } - if (options.hasOwnProperty('typePojoToMixed')) { - childSchemaOptions.typePojoToMixed = options.typePojoToMixed; - } - const childSchema = new Schema(cast, childSchemaOptions); - childSchema.$implicitlyCreated = true; - return new MongooseTypes.DocumentArray(path, childSchema, obj); - } else { - // Special case: empty object becomes mixed - return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj); - } - } - - if (cast) { - type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type) - ? cast[options.typeKey] - : cast; - - name = typeof type === 'string' - ? type - : type.schemaName || utils.getFunctionName(type); - - if (!MongooseTypes.hasOwnProperty(name)) { - throw new TypeError('Invalid schema configuration: ' + - `\`${name}\` is not a valid type within the array \`${path}\`.` + - 'See http://bit.ly/mongoose-schematypes for a list of valid schema types.'); - } - } - - return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options); - } - - if (type && type.instanceOfSchema) { - return new MongooseTypes.Embedded(type, path, obj); - } - - if (Buffer.isBuffer(type)) { - name = 'Buffer'; - } else if (typeof type === 'function' || typeof type === 'object') { - name = type.schemaName || utils.getFunctionName(type); - } else { - name = type == null ? '' + type : type.toString(); - } - - if (name) { - name = name.charAt(0).toUpperCase() + name.substring(1); - } - // Special case re: gh-7049 because the bson `ObjectID` class' capitalization - // doesn't line up with Mongoose's. - if (name === 'ObjectID') { - name = 'ObjectId'; - } - - if (MongooseTypes[name] == null) { - throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` + - `a valid type at path \`${path}\`. See ` + - 'http://bit.ly/mongoose-schematypes for a list of valid schema types.'); - } - - return new MongooseTypes[name](path, obj); -}; - -/** - * Iterates the schemas paths similar to Array#forEach. - * - * The callback is passed the pathname and the schemaType instance. - * - * ####Example: - * - * const userSchema = new Schema({ name: String, registeredAt: Date }); - * userSchema.eachPath((pathname, schematype) => { - * // Prints twice: - * // name SchemaString { ... } - * // registeredAt SchemaDate { ... } - * console.log(pathname, schematype); - * }); - * - * @param {Function} fn callback function - * @return {Schema} this - * @api public - */ - -Schema.prototype.eachPath = function(fn) { - const keys = Object.keys(this.paths); - const len = keys.length; - - for (let i = 0; i < len; ++i) { - fn(keys[i], this.paths[keys[i]]); - } - - return this; -}; - -/** - * Returns an Array of path strings that are required by this schema. - * - * ####Example: - * const s = new Schema({ - * name: { type: String, required: true }, - * age: { type: String, required: true }, - * notes: String - * }); - * s.requiredPaths(); // [ 'age', 'name' ] - * - * @api public - * @param {Boolean} invalidate refresh the cache - * @return {Array} - */ - -Schema.prototype.requiredPaths = function requiredPaths(invalidate) { - if (this._requiredpaths && !invalidate) { - return this._requiredpaths; - } - - const paths = Object.keys(this.paths); - let i = paths.length; - const ret = []; - - while (i--) { - const path = paths[i]; - if (this.paths[path].isRequired) { - ret.push(path); - } - } - this._requiredpaths = ret; - return this._requiredpaths; -}; - -/** - * Returns indexes from fields and schema-level indexes (cached). - * - * @api private - * @return {Array} - */ - -Schema.prototype.indexedPaths = function indexedPaths() { - if (this._indexedpaths) { - return this._indexedpaths; - } - this._indexedpaths = this.indexes(); - return this._indexedpaths; -}; - -/** - * Returns the pathType of `path` for this schema. - * - * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path. - * - * ####Example: - * const s = new Schema({ name: String, nested: { foo: String } }); - * s.virtual('foo').get(() => 42); - * s.pathType('name'); // "real" - * s.pathType('nested'); // "nested" - * s.pathType('foo'); // "virtual" - * s.pathType('fail'); // "adhocOrUndefined" - * - * @param {String} path - * @return {String} - * @api public - */ - -Schema.prototype.pathType = function(path) { - // Convert to '.$' to check subpaths re: gh-6405 - const cleanPath = _pathToPositionalSyntax(path); - - if (this.paths.hasOwnProperty(path)) { - return 'real'; - } - if (this.virtuals.hasOwnProperty(path)) { - return 'virtual'; - } - if (this.nested.hasOwnProperty(path)) { - return 'nested'; - } - if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) { - return 'real'; - } - if (this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path)) { - return 'real'; - } - - // Look for maps - const mapPath = getMapPath(this, path); - if (mapPath != null) { - return 'real'; - } - - if (/\.\d+\.|\.\d+$/.test(path)) { - return getPositionalPathType(this, path); - } - return 'adhocOrUndefined'; -}; - -/** - * Returns true iff this path is a child of a mixed schema. - * - * @param {String} path - * @return {Boolean} - * @api private - */ - -Schema.prototype.hasMixedParent = function(path) { - const subpaths = path.split(/\./g); - path = ''; - for (let i = 0; i < subpaths.length; ++i) { - path = i > 0 ? path + '.' + subpaths[i] : subpaths[i]; - if (path in this.paths && - this.paths[path] instanceof MongooseTypes.Mixed) { - return this.paths[path]; - } - } - - return null; -}; - -/** - * Setup updatedAt and createdAt timestamps to documents if enabled - * - * @param {Boolean|Object} timestamps timestamps options - * @api private - */ -Schema.prototype.setupTimestamp = function(timestamps) { - const childHasTimestamp = this.childSchemas.find(withTimestamp); - - function withTimestamp(s) { - const ts = s.schema.options.timestamps; - return !!ts; - } - - if (!timestamps && !childHasTimestamp) { - return; - } - - const createdAt = handleTimestampOption(timestamps, 'createdAt'); - const updatedAt = handleTimestampOption(timestamps, 'updatedAt'); - const currentTime = timestamps != null && timestamps.hasOwnProperty('currentTime') ? - timestamps.currentTime : - null; - const schemaAdditions = {}; - - this.$timestamps = { createdAt: createdAt, updatedAt: updatedAt }; - - if (updatedAt && !this.paths[updatedAt]) { - schemaAdditions[updatedAt] = Date; - } - - if (createdAt && !this.paths[createdAt]) { - schemaAdditions[createdAt] = Date; - } - - this.add(schemaAdditions); - - this.pre('save', function(next) { - const timestampOption = get(this, '$__.saveOptions.timestamps'); - if (timestampOption === false) { - return next(); - } - - const skipUpdatedAt = timestampOption != null && timestampOption.updatedAt === false; - const skipCreatedAt = timestampOption != null && timestampOption.createdAt === false; - - const defaultTimestamp = currentTime != null ? - currentTime() : - (this.ownerDocument ? this.ownerDocument() : this).constructor.base.now(); - const auto_id = this._id && this._id.auto; - - if (!skipCreatedAt && createdAt && !this.get(createdAt) && this.isSelected(createdAt)) { - this.set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp); - } - - if (!skipUpdatedAt && updatedAt && (this.isNew || this.isModified())) { - let ts = defaultTimestamp; - if (this.isNew) { - if (createdAt != null) { - ts = this.$__getValue(createdAt); - } else if (auto_id) { - ts = this._id.getTimestamp(); - } - } - this.set(updatedAt, ts); - } - - next(); - }); - - this.methods.initializeTimestamps = function() { - const ts = currentTime != null ? - currentTime() : - this.constructor.base.now(); - if (createdAt && !this.get(createdAt)) { - this.set(createdAt, ts); - } - if (updatedAt && !this.get(updatedAt)) { - this.set(updatedAt, ts); - } - return this; - }; - - _setTimestampsOnUpdate[symbols.builtInMiddleware] = true; - - const opts = { query: true, model: false }; - this.pre('findOneAndUpdate', opts, _setTimestampsOnUpdate); - this.pre('replaceOne', opts, _setTimestampsOnUpdate); - this.pre('update', opts, _setTimestampsOnUpdate); - this.pre('updateOne', opts, _setTimestampsOnUpdate); - this.pre('updateMany', opts, _setTimestampsOnUpdate); - - function _setTimestampsOnUpdate(next) { - const now = currentTime != null ? - currentTime() : - this.model.base.now(); - applyTimestampsToUpdate(now, createdAt, updatedAt, this.getUpdate(), - this.options, this.schema); - applyTimestampsToChildren(now, this.getUpdate(), this.model.schema); - next(); - } -}; - -/*! - * ignore. Deprecated re: #6405 - */ - -function getPositionalPathType(self, path) { - const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); - if (subpaths.length < 2) { - return self.paths.hasOwnProperty(subpaths[0]) ? - self.paths[subpaths[0]] : - 'adhocOrUndefined'; - } - - let val = self.path(subpaths[0]); - let isNested = false; - if (!val) { - return 'adhocOrUndefined'; - } - - const last = subpaths.length - 1; - - for (let i = 1; i < subpaths.length; ++i) { - isNested = false; - const subpath = subpaths[i]; - - if (i === last && val && !/\D/.test(subpath)) { - if (val.$isMongooseDocumentArray) { - val = val.$embeddedSchemaType; - } else if (val instanceof MongooseTypes.Array) { - // StringSchema, NumberSchema, etc - val = val.caster; - } else { - val = undefined; - } - break; - } - - // ignore if its just a position segment: path.0.subpath - if (!/\D/.test(subpath)) { - // Nested array - if (val instanceof MongooseTypes.Array && i !== last) { - val = val.caster; - } - continue; - } - - if (!(val && val.schema)) { - val = undefined; - break; - } - - const type = val.schema.pathType(subpath); - isNested = (type === 'nested'); - val = val.schema.path(subpath); - } - - self.subpaths[path] = val; - if (val) { - return 'real'; - } - if (isNested) { - return 'nested'; - } - return 'adhocOrUndefined'; -} - - -/*! - * ignore - */ - -function getPositionalPath(self, path) { - getPositionalPathType(self, path); - return self.subpaths[path]; -} - -/** - * Adds a method call to the queue. - * - * ####Example: - * - * schema.methods.print = function() { console.log(this); }; - * schema.queue('print', []); // Print the doc every one is instantiated - * - * const Model = mongoose.model('Test', schema); - * new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }' - * - * @param {String} name name of the document method to call later - * @param {Array} args arguments to pass to the method - * @api public - */ - -Schema.prototype.queue = function(name, args) { - this.callQueue.push([name, args]); - return this; -}; - -/** - * Defines a pre hook for the document. - * - * ####Example - * - * var toySchema = new Schema({ name: String, created: Date }); - * - * toySchema.pre('save', function(next) { - * if (!this.created) this.created = new Date; - * next(); - * }); - * - * toySchema.pre('validate', function(next) { - * if (this.name !== 'Woody') this.name = 'Woody'; - * next(); - * }); - * - * // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`. - * toySchema.pre(/^find/, function(next) { - * console.log(this.getFilter()); - * }); - * - * // Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`. - * toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) { - * console.log(this.getFilter()); - * }); - * - * toySchema.pre('deleteOne', function() { - * // Runs when you call `Toy.deleteOne()` - * }); - * - * toySchema.pre('deleteOne', { document: true }, function() { - * // Runs when you call `doc.deleteOne()` - * }); - * - * @param {String|RegExp} The method name or regular expression to match method name - * @param {Object} [options] - * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. For example, set `options.document` to `true` to apply this hook to `Document#deleteOne()` rather than `Query#deleteOne()`. - * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware. - * @param {Function} callback - * @api public - */ - -Schema.prototype.pre = function(name) { - if (name instanceof RegExp) { - const remainingArgs = Array.prototype.slice.call(arguments, 1); - for (const fn of hookNames) { - if (name.test(fn)) { - this.pre.apply(this, [fn].concat(remainingArgs)); - } - } - return this; - } - if (Array.isArray(name)) { - const remainingArgs = Array.prototype.slice.call(arguments, 1); - for (const el of name) { - this.pre.apply(this, [el].concat(remainingArgs)); - } - return this; - } - this.s.hooks.pre.apply(this.s.hooks, arguments); - return this; -}; - -/** - * Defines a post hook for the document - * - * var schema = new Schema(..); - * schema.post('save', function (doc) { - * console.log('this fired after a document was saved'); - * }); - * - * schema.post('find', function(docs) { - * console.log('this fired after you ran a find query'); - * }); - * - * schema.post(/Many$/, function(res) { - * console.log('this fired after you ran `updateMany()` or `deleteMany()`); - * }); - * - * var Model = mongoose.model('Model', schema); - * - * var m = new Model(..); - * m.save(function(err) { - * console.log('this fires after the `post` hook'); - * }); - * - * m.find(function(err, docs) { - * console.log('this fires after the post find hook'); - * }); - * - * @param {String|RegExp} The method name or regular expression to match method name - * @param {Object} [options] - * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. - * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware. - * @param {Function} fn callback - * @see middleware http://mongoosejs.com/docs/middleware.html - * @see kareem http://npmjs.org/package/kareem - * @api public - */ - -Schema.prototype.post = function(name) { - if (name instanceof RegExp) { - const remainingArgs = Array.prototype.slice.call(arguments, 1); - for (const fn of hookNames) { - if (name.test(fn)) { - this.post.apply(this, [fn].concat(remainingArgs)); - } - } - return this; - } - if (Array.isArray(name)) { - const remainingArgs = Array.prototype.slice.call(arguments, 1); - for (const el of name) { - this.post.apply(this, [el].concat(remainingArgs)); - } - return this; - } - this.s.hooks.post.apply(this.s.hooks, arguments); - return this; -}; - -/** - * Registers a plugin for this schema. - * - * ####Example: - * - * const s = new Schema({ name: String }); - * s.plugin(schema => console.log(schema.path('name').path)); - * mongoose.model('Test', s); // Prints 'name' - * - * @param {Function} plugin callback - * @param {Object} [opts] - * @see plugins - * @api public - */ - -Schema.prototype.plugin = function(fn, opts) { - if (typeof fn !== 'function') { - throw new Error('First param to `schema.plugin()` must be a function, ' + - 'got "' + (typeof fn) + '"'); - } - - if (opts && opts.deduplicate) { - for (const plugin of this.plugins) { - if (plugin.fn === fn) { - return this; - } - } - } - this.plugins.push({ fn: fn, opts: opts }); - - fn(this, opts); - return this; -}; - -/** - * Adds an instance method to documents constructed from Models compiled from this schema. - * - * ####Example - * - * var schema = kittySchema = new Schema(..); - * - * schema.method('meow', function () { - * console.log('meeeeeoooooooooooow'); - * }) - * - * var Kitty = mongoose.model('Kitty', schema); - * - * var fizz = new Kitty; - * fizz.meow(); // meeeeeooooooooooooow - * - * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. - * - * schema.method({ - * purr: function () {} - * , scratch: function () {} - * }); - * - * // later - * fizz.purr(); - * fizz.scratch(); - * - * NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](./guide.html#methods) - * - * @param {String|Object} method name - * @param {Function} [fn] - * @api public - */ - -Schema.prototype.method = function(name, fn, options) { - if (typeof name !== 'string') { - for (const i in name) { - this.methods[i] = name[i]; - this.methodOptions[i] = utils.clone(options); - } - } else { - this.methods[name] = fn; - this.methodOptions[name] = utils.clone(options); - } - return this; -}; - -/** - * Adds static "class" methods to Models compiled from this schema. - * - * ####Example - * - * const schema = new Schema(..); - * // Equivalent to `schema.statics.findByName = function(name) {}`; - * schema.static('findByName', function(name) { - * return this.find({ name: name }); - * }); - * - * const Drink = mongoose.model('Drink', schema); - * await Drink.findByName('LaCroix'); - * - * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics. - * - * @param {String|Object} name - * @param {Function} [fn] - * @api public - * @see Statics /docs/guide.html#statics - */ - -Schema.prototype.static = function(name, fn) { - if (typeof name !== 'string') { - for (const i in name) { - this.statics[i] = name[i]; - } - } else { - this.statics[name] = fn; - } - return this; -}; - -/** - * Defines an index (most likely compound) for this schema. - * - * ####Example - * - * schema.index({ first: 1, last: -1 }) - * - * @param {Object} fields - * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#createIndex) - * @param {String} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link. - * @api public - */ - -Schema.prototype.index = function(fields, options) { - fields || (fields = {}); - options || (options = {}); - - if (options.expires) { - utils.expires(options); - } - - this._indexes.push([fields, options]); - return this; -}; - -/** - * Sets/gets a schema option. - * - * ####Example - * - * schema.set('strict'); // 'true' by default - * schema.set('strict', false); // Sets 'strict' to false - * schema.set('strict'); // 'false' - * - * @param {String} key option name - * @param {Object} [value] if not passed, the current option value is returned - * @see Schema ./ - * @api public - */ - -Schema.prototype.set = function(key, value, _tags) { - if (arguments.length === 1) { - return this.options[key]; - } - - switch (key) { - case 'read': - this.options[key] = readPref(value, _tags); - this._userProvidedOptions[key] = this.options[key]; - break; - case 'safe': - setSafe(this.options, value); - this._userProvidedOptions[key] = this.options[key]; - break; - case 'timestamps': - this.setupTimestamp(value); - this.options[key] = value; - this._userProvidedOptions[key] = this.options[key]; - break; - default: - this.options[key] = value; - this._userProvidedOptions[key] = this.options[key]; - break; - } - - return this; -}; - -/*! - * ignore - */ - -const safeDeprecationWarning = 'Mongoose: The `safe` option for schemas is ' + - 'deprecated. Use the `writeConcern` option instead: ' + - 'http://bit.ly/mongoose-write-concern'; - -const setSafe = util.deprecate(function setSafe(options, value) { - options.safe = value === false ? - { w: 0 } : - value; -}, safeDeprecationWarning); - -/** - * Gets a schema option. - * - * ####Example: - * - * schema.get('strict'); // true - * schema.set('strict', false); - * schema.get('strict'); // false - * - * @param {String} key option name - * @api public - * @return {Any} the option's value - */ - -Schema.prototype.get = function(key) { - return this.options[key]; -}; - -/** - * The allowed index types - * - * @receiver Schema - * @static indexTypes - * @api public - */ - -const indexTypes = '2d 2dsphere hashed text'.split(' '); - -Object.defineProperty(Schema, 'indexTypes', { - get: function() { - return indexTypes; - }, - set: function() { - throw new Error('Cannot overwrite Schema.indexTypes'); - } -}); - -/** - * Returns a list of indexes that this schema declares, via `schema.index()` - * or by `index: true` in a path's options. - * - * ####Example: - * - * const userSchema = new Schema({ - * email: { type: String, required: true, unique: true }, - * registeredAt: { type: Date, index: true } - * }); - * - * // [ [ { email: 1 }, { unique: true, background: true } ], - * // [ { registeredAt: 1 }, { background: true } ] ] - * userSchema.indexes(); - * - * @api public - * @return {Array} list of indexes defined in the schema - */ - -Schema.prototype.indexes = function() { - return getIndexes(this); -}; - -/** - * Creates a virtual type with the given name. - * - * @param {String} name - * @param {Object} [options] - * @param {String|Model} [options.ref] model name or model instance. Marks this as a [populate virtual](populate.html#populate-virtuals). - * @param {String|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information. - * @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](populate.html#populate-virtuals) for more information. - * @param {Boolean|Function} [options.justOne=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), will be a single doc or `null`. Otherwise, the populate virtual will be an array. - * @param {Boolean} [options.count=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`. - * @return {VirtualType} - */ - -Schema.prototype.virtual = function(name, options) { - if (name instanceof VirtualType) { - return this.virtual(name.path, name.options); - } - - options = new VirtualOptions(options); - - if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) { - if (options.localField == null) { - throw new Error('Reference virtuals require `localField` option'); - } - - if (options.foreignField == null) { - throw new Error('Reference virtuals require `foreignField` option'); - } - - this.pre('init', function(obj) { - if (mpath.has(name, obj)) { - const _v = mpath.get(name, obj); - if (!this.$$populatedVirtuals) { - this.$$populatedVirtuals = {}; - } - - if (options.justOne || options.count) { - this.$$populatedVirtuals[name] = Array.isArray(_v) ? - _v[0] : - _v; - } else { - this.$$populatedVirtuals[name] = Array.isArray(_v) ? - _v : - _v == null ? [] : [_v]; - } - - mpath.unset(name, obj); - } - }); - - const virtual = this.virtual(name); - virtual.options = options; - return virtual. - get(function(_v) { - if (this.$$populatedVirtuals && - this.$$populatedVirtuals.hasOwnProperty(name)) { - return this.$$populatedVirtuals[name]; - } - if (_v == null) return undefined; - return _v; - }). - set(function(_v) { - if (!this.$$populatedVirtuals) { - this.$$populatedVirtuals = {}; - } - - if (options.justOne || options.count) { - this.$$populatedVirtuals[name] = Array.isArray(_v) ? - _v[0] : - _v; - - if (typeof this.$$populatedVirtuals[name] !== 'object') { - this.$$populatedVirtuals[name] = options.count ? _v : null; - } - } else { - this.$$populatedVirtuals[name] = Array.isArray(_v) ? - _v : - _v == null ? [] : [_v]; - - this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) { - return doc && typeof doc === 'object'; - }); - } - }); - } - - const virtuals = this.virtuals; - const parts = name.split('.'); - - if (this.pathType(name) === 'real') { - throw new Error('Virtual path "' + name + '"' + - ' conflicts with a real path in the schema'); - } - - virtuals[name] = parts.reduce(function(mem, part, i) { - mem[part] || (mem[part] = (i === parts.length - 1) - ? new VirtualType(options, name) - : {}); - return mem[part]; - }, this.tree); - - // Workaround for gh-8198: if virtual is under document array, make a fake - // virtual. See gh-8210 - let cur = parts[0]; - for (let i = 0; i < parts.length - 1; ++i) { - if (this.paths[cur] != null && this.paths[cur].$isMongooseDocumentArray) { - const remnant = parts.slice(i + 1).join('.'); - const v = this.paths[cur].schema.virtual(remnant); - v.get((v, virtual, doc) => { - const parent = doc.__parentArray[arrayParentSymbol]; - const path = cur + '.' + doc.__index + '.' + remnant; - return parent.get(path); - }); - break; - } - - cur += '.' + parts[i + 1]; - } - - return virtuals[name]; -}; - -/** - * Returns the virtual type with the given `name`. - * - * @param {String} name - * @return {VirtualType} - */ - -Schema.prototype.virtualpath = function(name) { - return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null; -}; - -/** - * Removes the given `path` (or [`paths`]). - * - * ####Example: - * - * const schema = new Schema({ name: String, age: Number }); - * schema.remove('name'); - * schema.path('name'); // Undefined - * schema.path('age'); // SchemaNumber { ... } - * - * @param {String|Array} path - * @return {Schema} the Schema instance - * @api public - */ -Schema.prototype.remove = function(path) { - if (typeof path === 'string') { - path = [path]; - } - if (Array.isArray(path)) { - path.forEach(function(name) { - if (this.path(name) == null && !this.nested[name]) { - return; - } - if (this.nested[name]) { - const allKeys = Object.keys(this.paths). - concat(Object.keys(this.nested)); - for (const path of allKeys) { - if (path.startsWith(name + '.')) { - delete this.paths[path]; - delete this.nested[path]; - _deletePath(this, path); - } - } - - delete this.nested[name]; - _deletePath(this, name); - return; - } - - delete this.paths[name]; - _deletePath(this, name); - }, this); - } - return this; -}; - -/*! - * ignore - */ - -function _deletePath(schema, name) { - const pieces = name.split('.'); - const last = pieces.pop(); - - let branch = schema.tree; - - for (const piece of pieces) { - branch = branch[piece]; - } - - delete branch[last]; -} - -/** - * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static), - * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions) - * to schema [virtuals](http://mongoosejs.com/docs/guide.html#virtuals), - * [statics](http://mongoosejs.com/docs/guide.html#statics), and - * [methods](http://mongoosejs.com/docs/guide.html#methods). - * - * ####Example: - * - * ```javascript - * const md5 = require('md5'); - * const userSchema = new Schema({ email: String }); - * class UserClass { - * // `gravatarImage` becomes a virtual - * get gravatarImage() { - * const hash = md5(this.email.toLowerCase()); - * return `https://www.gravatar.com/avatar/${hash}`; - * } - * - * // `getProfileUrl()` becomes a document method - * getProfileUrl() { - * return `https://mysite.com/${this.email}`; - * } - * - * // `findByEmail()` becomes a static - * static findByEmail(email) { - * return this.findOne({ email }); - * } - * } - * - * // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method, - * // and a `findByEmail()` static - * userSchema.loadClass(UserClass); - * ``` - * - * @param {Function} model - * @param {Boolean} [virtualsOnly] if truthy, only pulls virtuals from the class, not methods or statics - */ -Schema.prototype.loadClass = function(model, virtualsOnly) { - if (model === Object.prototype || - model === Function.prototype || - model.prototype.hasOwnProperty('$isMongooseModelPrototype')) { - return this; - } - - this.loadClass(Object.getPrototypeOf(model)); - - // Add static methods - if (!virtualsOnly) { - Object.getOwnPropertyNames(model).forEach(function(name) { - if (name.match(/^(length|name|prototype)$/)) { - return; - } - const method = Object.getOwnPropertyDescriptor(model, name); - if (typeof method.value === 'function') { - this.static(name, method.value); - } - }, this); - } - - // Add methods and virtuals - Object.getOwnPropertyNames(model.prototype).forEach(function(name) { - if (name.match(/^(constructor)$/)) { - return; - } - const method = Object.getOwnPropertyDescriptor(model.prototype, name); - if (!virtualsOnly) { - if (typeof method.value === 'function') { - this.method(name, method.value); - } - } - if (typeof method.get === 'function') { - this.virtual(name).get(method.get); - } - if (typeof method.set === 'function') { - this.virtual(name).set(method.set); - } - }, this); - - return this; -}; - -/*! - * ignore - */ - -Schema.prototype._getSchema = function(path) { - const _this = this; - const pathschema = _this.path(path); - const resultPath = []; - - if (pathschema) { - pathschema.$fullPath = path; - return pathschema; - } - - function search(parts, schema) { - let p = parts.length + 1; - let foundschema; - let trypath; - - while (p--) { - trypath = parts.slice(0, p).join('.'); - foundschema = schema.path(trypath); - if (foundschema) { - resultPath.push(trypath); - - if (foundschema.caster) { - // array of Mixed? - if (foundschema.caster instanceof MongooseTypes.Mixed) { - foundschema.caster.$fullPath = resultPath.join('.'); - return foundschema.caster; - } - - // Now that we found the array, we need to check if there - // are remaining document paths to look up for casting. - // Also we need to handle array.$.path since schema.path - // doesn't work for that. - // If there is no foundschema.schema we are dealing with - // a path like array.$ - if (p !== parts.length && foundschema.schema) { - let ret; - if (parts[p] === '$' || isArrayFilter(parts[p])) { - if (p + 1 === parts.length) { - // comments.$ - return foundschema; - } - // comments.$.comments.$.title - ret = search(parts.slice(p + 1), foundschema.schema); - if (ret) { - ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - } - return ret; - } - // this is the last path of the selector - ret = search(parts.slice(p), foundschema.schema); - if (ret) { - ret.$isUnderneathDocArray = ret.$isUnderneathDocArray || - !foundschema.schema.$isSingleNested; - } - return ret; - } - } - - foundschema.$fullPath = resultPath.join('.'); - - return foundschema; - } - } - } - - // look for arrays - const parts = path.split('.'); - for (let i = 0; i < parts.length; ++i) { - if (parts[i] === '$' || isArrayFilter(parts[i])) { - // Re: gh-5628, because `schema.path()` doesn't take $ into account. - parts[i] = '0'; - } - } - return search(parts, _this); -}; - -/*! - * ignore - */ - -Schema.prototype._getPathType = function(path) { - const _this = this; - const pathschema = _this.path(path); - - if (pathschema) { - return 'real'; - } - - function search(parts, schema) { - let p = parts.length + 1, - foundschema, - trypath; - - while (p--) { - trypath = parts.slice(0, p).join('.'); - foundschema = schema.path(trypath); - if (foundschema) { - if (foundschema.caster) { - // array of Mixed? - if (foundschema.caster instanceof MongooseTypes.Mixed) { - return { schema: foundschema, pathType: 'mixed' }; - } - - // Now that we found the array, we need to check if there - // are remaining document paths to look up for casting. - // Also we need to handle array.$.path since schema.path - // doesn't work for that. - // If there is no foundschema.schema we are dealing with - // a path like array.$ - if (p !== parts.length && foundschema.schema) { - if (parts[p] === '$' || isArrayFilter(parts[p])) { - if (p === parts.length - 1) { - return { schema: foundschema, pathType: 'nested' }; - } - // comments.$.comments.$.title - return search(parts.slice(p + 1), foundschema.schema); - } - // this is the last path of the selector - return search(parts.slice(p), foundschema.schema); - } - return { - schema: foundschema, - pathType: foundschema.$isSingleNested ? 'nested' : 'array' - }; - } - return { schema: foundschema, pathType: 'real' }; - } else if (p === parts.length && schema.nested[trypath]) { - return { schema: schema, pathType: 'nested' }; - } - } - return { schema: foundschema || schema, pathType: 'undefined' }; - } - - // look for arrays - return search(path.split('.'), _this); -}; - -/*! - * ignore - */ - -function isArrayFilter(piece) { - return piece.startsWith('$[') && piece.endsWith(']'); -} - -/*! - * Module exports. - */ - -module.exports = exports = Schema; - -// require down here because of reference issues - -/** - * The various built-in Mongoose Schema Types. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var ObjectId = mongoose.Schema.Types.ObjectId; - * - * ####Types: - * - * - [String](#schema-string-js) - * - [Number](#schema-number-js) - * - [Boolean](#schema-boolean-js) | Bool - * - [Array](#schema-array-js) - * - [Buffer](#schema-buffer-js) - * - [Date](#schema-date-js) - * - [ObjectId](#schema-objectid-js) | Oid - * - [Mixed](#schema-mixed-js) - * - * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema. - * - * var Mixed = mongoose.Schema.Types.Mixed; - * new mongoose.Schema({ _user: Mixed }) - * - * @api public - */ - -Schema.Types = MongooseTypes = require('./schema/index'); - -/*! - * ignore - */ - -exports.ObjectId = MongooseTypes.ObjectId; diff --git a/node_modules/mongoose/lib/schema/SingleNestedPath.js b/node_modules/mongoose/lib/schema/SingleNestedPath.js deleted file mode 100644 index d7abd6c..0000000 --- a/node_modules/mongoose/lib/schema/SingleNestedPath.js +++ /dev/null @@ -1,313 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const CastError = require('../error/cast'); -const EventEmitter = require('events').EventEmitter; -const ObjectExpectedError = require('../error/objectExpected'); -const SchemaSingleNestedOptions = require('../options/SchemaSingleNestedOptions'); -const SchemaType = require('../schematype'); -const $exists = require('./operators/exists'); -const castToNumber = require('./operators/helpers').castToNumber; -const discriminator = require('../helpers/model/discriminator'); -const geospatial = require('./operators/geospatial'); -const get = require('../helpers/get'); -const getConstructor = require('../helpers/discriminator/getConstructor'); -const handleIdOption = require('../helpers/schema/handleIdOption'); -const internalToObjectOptions = require('../options').internalToObjectOptions; - -let Subdocument; - -module.exports = SingleNestedPath; - -/** - * Single nested subdocument SchemaType constructor. - * - * @param {Schema} schema - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function SingleNestedPath(schema, path, options) { - schema = handleIdOption(schema, options); - - this.caster = _createConstructor(schema); - this.caster.path = path; - this.caster.prototype.$basePath = path; - this.schema = schema; - this.$isSingleNested = true; - SchemaType.call(this, path, options, 'Embedded'); -} - -/*! - * ignore - */ - -SingleNestedPath.prototype = Object.create(SchemaType.prototype); -SingleNestedPath.prototype.constructor = SingleNestedPath; -SingleNestedPath.prototype.OptionsConstructor = SchemaSingleNestedOptions; - -/*! - * ignore - */ - -function _createConstructor(schema, baseClass) { - // lazy load - Subdocument || (Subdocument = require('../types/subdocument')); - - const _embedded = function SingleNested(value, path, parent) { - const _this = this; - - this.$parent = parent; - Subdocument.apply(this, arguments); - - this.$session(this.ownerDocument().$session()); - - if (parent) { - parent.on('save', function() { - _this.emit('save', _this); - _this.constructor.emit('save', _this); - }); - - parent.on('isNew', function(val) { - _this.isNew = val; - _this.emit('isNew', val); - _this.constructor.emit('isNew', val); - }); - } - }; - - const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype; - _embedded.prototype = Object.create(proto); - _embedded.prototype.$__setSchema(schema); - _embedded.prototype.constructor = _embedded; - _embedded.schema = schema; - _embedded.$isSingleNested = true; - _embedded.events = new EventEmitter(); - _embedded.prototype.toBSON = function() { - return this.toObject(internalToObjectOptions); - }; - - // apply methods - for (const i in schema.methods) { - _embedded.prototype[i] = schema.methods[i]; - } - - // apply statics - for (const i in schema.statics) { - _embedded[i] = schema.statics[i]; - } - - for (const i in EventEmitter.prototype) { - _embedded[i] = EventEmitter.prototype[i]; - } - - return _embedded; -} - -/*! - * Special case for when users use a common location schema to represent - * locations for use with $geoWithin. - * https://docs.mongodb.org/manual/reference/operator/query/geoWithin/ - * - * @param {Object} val - * @api private - */ - -SingleNestedPath.prototype.$conditionalHandlers.$geoWithin = function handle$geoWithin(val) { - return { $geometry: this.castForQuery(val.$geometry) }; -}; - -/*! - * ignore - */ - -SingleNestedPath.prototype.$conditionalHandlers.$near = -SingleNestedPath.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near; - -SingleNestedPath.prototype.$conditionalHandlers.$within = -SingleNestedPath.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within; - -SingleNestedPath.prototype.$conditionalHandlers.$geoIntersects = - geospatial.cast$geoIntersects; - -SingleNestedPath.prototype.$conditionalHandlers.$minDistance = castToNumber; -SingleNestedPath.prototype.$conditionalHandlers.$maxDistance = castToNumber; - -SingleNestedPath.prototype.$conditionalHandlers.$exists = $exists; - -/** - * Casts contents - * - * @param {Object} value - * @api private - */ - -SingleNestedPath.prototype.cast = function(val, doc, init, priorVal) { - if (val && val.$isSingleNested && val.parent === doc) { - return val; - } - - if (val != null && (typeof val !== 'object' || Array.isArray(val))) { - throw new ObjectExpectedError(this.path, val); - } - - const Constructor = getConstructor(this.caster, val); - - let subdoc; - - // Only pull relevant selected paths and pull out the base path - const parentSelected = get(doc, '$__.selected', {}); - const path = this.path; - const selected = Object.keys(parentSelected).reduce((obj, key) => { - if (key.startsWith(path + '.')) { - obj[key.substr(path.length + 1)] = parentSelected[key]; - } - return obj; - }, {}); - - if (init) { - subdoc = new Constructor(void 0, selected, doc); - subdoc.init(val); - } else { - if (Object.keys(val).length === 0) { - return new Constructor({}, selected, doc); - } - - return new Constructor(val, selected, doc, undefined, { priorDoc: priorVal }); - } - - return subdoc; -}; - -/** - * Casts contents for query - * - * @param {string} [$conditional] optional query operator (like `$eq` or `$in`) - * @param {any} value - * @api private - */ - -SingleNestedPath.prototype.castForQuery = function($conditional, val, options) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new Error('Can\'t use ' + $conditional); - } - return handler.call(this, val); - } - val = $conditional; - if (val == null) { - return val; - } - - if (this.options.runSetters) { - val = this._applySetters(val); - } - - const Constructor = getConstructor(this.caster, val); - const overrideStrict = options != null && options.strict != null ? - options.strict : - void 0; - - try { - val = new Constructor(val, overrideStrict); - } catch (error) { - // Make sure we always wrap in a CastError (gh-6803) - if (!(error instanceof CastError)) { - throw new CastError('Embedded', val, this.path, error, this); - } - throw error; - } - return val; -}; - -/** - * Async validation on this single nested doc. - * - * @api private - */ - -SingleNestedPath.prototype.doValidate = function(value, fn, scope, options) { - const Constructor = getConstructor(this.caster, value); - - if (options && options.skipSchemaValidators) { - if (!(value instanceof Constructor)) { - value = new Constructor(value, null, scope); - } - return value.validate(fn); - } - - SchemaType.prototype.doValidate.call(this, value, function(error) { - if (error) { - return fn(error); - } - if (!value) { - return fn(null); - } - - value.validate(fn); - }, scope, options); -}; - -/** - * Synchronously validate this single nested doc - * - * @api private - */ - -SingleNestedPath.prototype.doValidateSync = function(value, scope, options) { - if (!options || !options.skipSchemaValidators) { - const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope); - if (schemaTypeError) { - return schemaTypeError; - } - } - if (!value) { - return; - } - return value.validateSync(); -}; - -/** - * Adds a discriminator to this single nested subdocument. - * - * ####Example: - * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' }); - * const schema = Schema({ shape: shapeSchema }); - * - * const singleNestedPath = parentSchema.path('shape'); - * singleNestedPath.discriminator('Circle', Schema({ radius: Number })); - * - * @param {String} name - * @param {Schema} schema fields to add to the schema for instances of this sub-class - * @param {String} [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. - * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model - * @see discriminators /docs/discriminators.html - * @api public - */ - -SingleNestedPath.prototype.discriminator = function(name, schema, value) { - schema = discriminator(this.caster, name, schema, value); - - this.caster.discriminators[name] = _createConstructor(schema, this.caster); - - return this.caster.discriminators[name]; -}; - -/*! - * ignore - */ - -SingleNestedPath.prototype.clone = function() { - const options = Object.assign({}, this.options); - const schematype = new this.constructor(this.schema, this.path, options); - schematype.validators = this.validators.slice(); - schematype.caster.discriminators = Object.assign({}, this.caster.discriminators); - return schematype; -}; diff --git a/node_modules/mongoose/lib/schema/array.js b/node_modules/mongoose/lib/schema/array.js deleted file mode 100644 index bc828a1..0000000 --- a/node_modules/mongoose/lib/schema/array.js +++ /dev/null @@ -1,580 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const $exists = require('./operators/exists'); -const $type = require('./operators/type'); -const MongooseError = require('../error/mongooseError'); -const SchemaArrayOptions = require('../options/SchemaArrayOptions'); -const SchemaType = require('../schematype'); -const CastError = SchemaType.CastError; -const Mixed = require('./mixed'); -const arrayDepth = require('../helpers/arrayDepth'); -const cast = require('../cast'); -const get = require('../helpers/get'); -const isOperator = require('../helpers/query/isOperator'); -const util = require('util'); -const utils = require('../utils'); -const castToNumber = require('./operators/helpers').castToNumber; -const geospatial = require('./operators/geospatial'); -const getDiscriminatorByValue = require('../helpers/discriminator/getDiscriminatorByValue'); - -let MongooseArray; -let EmbeddedDoc; - -const isNestedArraySymbol = Symbol('mongoose#isNestedArray'); - -/** - * Array SchemaType constructor - * - * @param {String} key - * @param {SchemaType} cast - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function SchemaArray(key, cast, options, schemaOptions) { - // lazy load - EmbeddedDoc || (EmbeddedDoc = require('../types').Embedded); - - let typeKey = 'type'; - if (schemaOptions && schemaOptions.typeKey) { - typeKey = schemaOptions.typeKey; - } - this.schemaOptions = schemaOptions; - - if (cast) { - let castOptions = {}; - - if (utils.isPOJO(cast)) { - if (cast[typeKey]) { - // support { type: Woot } - castOptions = utils.clone(cast); // do not alter user arguments - delete castOptions[typeKey]; - cast = cast[typeKey]; - } else { - cast = Mixed; - } - } - - if (cast === Object) { - cast = Mixed; - } - - // support { type: 'String' } - const name = typeof cast === 'string' - ? cast - : utils.getFunctionName(cast); - - const Types = require('./index.js'); - const caster = Types.hasOwnProperty(name) ? Types[name] : cast; - - this.casterConstructor = caster; - - if (this.casterConstructor instanceof SchemaArray) { - this.casterConstructor[isNestedArraySymbol] = true; - } - - if (typeof caster === 'function' && - !caster.$isArraySubdocument && - !caster.$isSchemaMap) { - this.caster = new caster(null, castOptions); - } else { - this.caster = caster; - } - - this.$embeddedSchemaType = this.caster; - - if (!(this.caster instanceof EmbeddedDoc)) { - this.caster.path = key; - } - } - - this.$isMongooseArray = true; - - SchemaType.call(this, key, options, 'Array'); - - let defaultArr; - let fn; - - if (this.defaultValue != null) { - defaultArr = this.defaultValue; - fn = typeof defaultArr === 'function'; - } - - if (!('defaultValue' in this) || this.defaultValue !== void 0) { - const defaultFn = function() { - let arr = []; - if (fn) { - arr = defaultArr.call(this); - } else if (defaultArr != null) { - arr = arr.concat(defaultArr); - } - // Leave it up to `cast()` to convert the array - return arr; - }; - defaultFn.$runBeforeSetters = true; - this.default(defaultFn); - } -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -SchemaArray.schemaName = 'Array'; - - -/** - * Options for all arrays. - * - * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. - * - * @static options - * @api public - */ - -SchemaArray.options = { castNonArrays: true }; - -SchemaArray.defaultOptions = {}; - -/** - * Sets a default option for all Array instances. - * - * ####Example: - * - * // Make all Array instances have `required` of true by default. - * mongoose.Schema.Array.set('required', true); - * - * const User = mongoose.model('User', new Schema({ test: Array })); - * new User({ }).validateSync().errors.test.message; // Path `test` is required. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ -SchemaArray.set = SchemaType.set; - -/*! - * Inherits from SchemaType. - */ -SchemaArray.prototype = Object.create(SchemaType.prototype); -SchemaArray.prototype.constructor = SchemaArray; -SchemaArray.prototype.OptionsConstructor = SchemaArrayOptions; - -/*! - * ignore - */ - -SchemaArray._checkRequired = SchemaType.prototype.checkRequired; - -/** - * Override the function the required validator uses to check whether an array - * passes the `required` check. - * - * ####Example: - * - * // Require non-empty array to pass `required` check - * mongoose.Schema.Types.Array.checkRequired(v => Array.isArray(v) && v.length); - * - * const M = mongoose.model({ arr: { type: Array, required: true } }); - * new M({ arr: [] }).validateSync(); // `null`, validation fails! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -SchemaArray.checkRequired = SchemaType.checkRequired; - -/** - * Check if the given value satisfies the `required` validator. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - -SchemaArray.prototype.checkRequired = function checkRequired(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - - // `require('util').inherits()` does **not** copy static properties, and - // plugins like mongoose-float use `inherits()` for pre-ES6. - const _checkRequired = typeof this.constructor.checkRequired == 'function' ? - this.constructor.checkRequired() : - SchemaArray.checkRequired(); - - return _checkRequired(value); -}; - -/** - * Adds an enum validator if this is an array of strings or numbers. Equivalent to - * `SchemaString.prototype.enum()` or `SchemaNumber.prototype.enum()` - * - * @param {String|Object} [args...] enumeration values - * @return {SchemaArray} this - */ - -SchemaArray.prototype.enum = function() { - let arr = this; - while (true) { - const instance = get(arr, 'caster.instance'); - if (instance === 'Array') { - arr = arr.caster; - continue; - } - if (instance !== 'String' && instance !== 'Number') { - throw new Error('`enum` can only be set on an array of strings or numbers ' + - ', not ' + instance); - } - break; - } - arr.caster.enum.apply(arr.caster, arguments); - return this; -}; - -/** - * Overrides the getters application for the population special-case - * - * @param {Object} value - * @param {Object} scope - * @api private - */ - -SchemaArray.prototype.applyGetters = function(value, scope) { - if (this.caster.options && this.caster.options.ref) { - // means the object id was populated - return value; - } - - return SchemaType.prototype.applyGetters.call(this, value, scope); -}; - -SchemaArray.prototype._applySetters = function(value, scope, init, priorVal) { - if (this.casterConstructor instanceof SchemaArray && - SchemaArray.options.castNonArrays && - !this[isNestedArraySymbol]) { - // Check nesting levels and wrap in array if necessary - let depth = 0; - let arr = this; - while (arr != null && - arr instanceof SchemaArray && - !arr.$isMongooseDocumentArray) { - ++depth; - arr = arr.casterConstructor; - } - - // No need to wrap empty arrays - if (value != null && value.length > 0) { - const valueDepth = arrayDepth(value); - if (valueDepth.min === valueDepth.max && valueDepth.max < depth) { - for (let i = valueDepth.max; i < depth; ++i) { - value = [value]; - } - } - } - } - - return SchemaType.prototype._applySetters.call(this, value, scope, init, priorVal); -}; - -/** - * Casts values for set(). - * - * @param {Object} value - * @param {Document} doc document that triggers the casting - * @param {Boolean} init whether this is an initialization cast - * @api private - */ - -SchemaArray.prototype.cast = function(value, doc, init, prev, options) { - // lazy load - MongooseArray || (MongooseArray = require('../types').Array); - - let i; - let l; - - if (Array.isArray(value)) { - if (!value.length && doc) { - const indexes = doc.schema.indexedPaths(); - - const arrayPath = this.path; - for (i = 0, l = indexes.length; i < l; ++i) { - const pathIndex = indexes[i][0][arrayPath]; - if (pathIndex === '2dsphere' || pathIndex === '2d') { - return; - } - } - - // Special case: if this index is on the parent of what looks like - // GeoJSON, skip setting the default to empty array re: #1668, #3233 - const arrayGeojsonPath = this.path.endsWith('.coordinates') ? - this.path.substr(0, this.path.lastIndexOf('.')) : null; - if (arrayGeojsonPath != null) { - for (i = 0, l = indexes.length; i < l; ++i) { - const pathIndex = indexes[i][0][arrayGeojsonPath]; - if (pathIndex === '2dsphere') { - return; - } - } - } - } - - if (!(value && value.isMongooseArray)) { - value = new MongooseArray(value, this.path, doc); - } else if (value && value.isMongooseArray) { - // We need to create a new array, otherwise change tracking will - // update the old doc (gh-4449) - value = new MongooseArray(value, this.path, doc); - } - - const isPopulated = doc != null && doc.$__ != null && doc.populated(this.path); - if (isPopulated) { - return value; - } - - if (this.caster && this.casterConstructor !== Mixed) { - try { - for (i = 0, l = value.length; i < l; i++) { - // Special case: number arrays disallow undefined. - // Re: gh-840 - // See commit 1298fe92d2c790a90594bd08199e45a4a09162a6 - if (this.caster.instance === 'Number' && value[i] === void 0) { - throw new MongooseError('Mongoose number arrays disallow storing undefined'); - } - const opts = {}; - if (options != null && options.arrayPath != null) { - opts.arrayPath = options.arrayPath + '.' + i; - } else if (this.caster._arrayPath != null) { - opts.arrayPath = this.caster._arrayPath.slice(0, -2) + '.' + i; - } - value[i] = this.caster.cast(value[i], doc, init, void 0, opts); - } - } catch (e) { - // rethrow - throw new CastError('[' + e.kind + ']', util.inspect(value), this.path, e, this); - } - } - - return value; - } - - if (init || SchemaArray.options.castNonArrays) { - // gh-2442: if we're loading this from the db and its not an array, mark - // the whole array as modified. - if (!!doc && !!init) { - doc.markModified(this.path); - } - return this.cast([value], doc, init); - } - - throw new CastError('Array', util.inspect(value), this.path, null, this); -}; - -/*! - * Ignore - */ - -SchemaArray.prototype.discriminator = function(name, schema) { - let arr = this; // eslint-disable-line consistent-this - while (arr.$isMongooseArray && !arr.$isMongooseDocumentArray) { - arr = arr.casterConstructor; - if (arr == null || typeof arr === 'function') { - throw new MongooseError('You can only add an embedded discriminator on ' + - 'a document array, ' + this.path + ' is a plain array'); - } - } - return arr.discriminator(name, schema); -}; - -/*! - * ignore - */ - -SchemaArray.prototype.clone = function() { - const options = Object.assign({}, this.options); - const schematype = new this.constructor(this.path, this.caster, options, this.schemaOptions); - schematype.validators = this.validators.slice(); - return schematype; -}; - -/** - * Casts values for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaArray.prototype.castForQuery = function($conditional, value) { - let handler; - let val; - - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - - if (!handler) { - throw new Error('Can\'t use ' + $conditional + ' with Array.'); - } - - val = handler.call(this, value); - } else { - val = $conditional; - let Constructor = this.casterConstructor; - - if (val && - Constructor.discriminators && - Constructor.schema && - Constructor.schema.options && - Constructor.schema.options.discriminatorKey) { - if (typeof val[Constructor.schema.options.discriminatorKey] === 'string' && - Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) { - Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]; - } else { - const constructorByValue = getDiscriminatorByValue(Constructor, val[Constructor.schema.options.discriminatorKey]); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } - - const proto = this.casterConstructor.prototype; - let method = proto && (proto.castForQuery || proto.cast); - if (!method && Constructor.castForQuery) { - method = Constructor.castForQuery; - } - const caster = this.caster; - - if (Array.isArray(val)) { - this.setters.reverse().forEach(setter => { - val = setter.call(this, val, this); - }); - val = val.map(function(v) { - if (utils.isObject(v) && v.$elemMatch) { - return v; - } - if (method) { - v = method.call(caster, v); - return v; - } - if (v != null) { - v = new Constructor(v); - return v; - } - return v; - }); - } else if (method) { - val = method.call(caster, val); - } else if (val != null) { - val = new Constructor(val); - } - } - - return val; -}; - -function cast$all(val) { - if (!Array.isArray(val)) { - val = [val]; - } - - val = val.map(function(v) { - if (utils.isObject(v)) { - const o = {}; - o[this.path] = v; - return cast(this.casterConstructor.schema, o)[this.path]; - } - return v; - }, this); - - return this.castForQuery(val); -} - -function cast$elemMatch(val) { - const keys = Object.keys(val); - const numKeys = keys.length; - for (let i = 0; i < numKeys; ++i) { - const key = keys[i]; - const value = val[key]; - if (isOperator(key) && value != null) { - val[key] = this.castForQuery(key, value); - } - } - - // Is this an embedded discriminator and is the discriminator key set? - // If so, use the discriminator schema. See gh-7449 - const discriminatorKey = get(this, - 'casterConstructor.schema.options.discriminatorKey'); - const discriminators = get(this, 'casterConstructor.schema.discriminators', {}); - if (discriminatorKey != null && - val[discriminatorKey] != null && - discriminators[val[discriminatorKey]] != null) { - return cast(discriminators[val[discriminatorKey]], val); - } - - return cast(this.casterConstructor.schema, val); -} - -const handle = SchemaArray.prototype.$conditionalHandlers = {}; - -handle.$all = cast$all; -handle.$options = String; -handle.$elemMatch = cast$elemMatch; -handle.$geoIntersects = geospatial.cast$geoIntersects; -handle.$or = handle.$and = function(val) { - if (!Array.isArray(val)) { - throw new TypeError('conditional $or/$and require array'); - } - - const ret = []; - for (const obj of val) { - ret.push(cast(this.casterConstructor.schema, obj)); - } - - return ret; -}; - -handle.$near = -handle.$nearSphere = geospatial.cast$near; - -handle.$within = -handle.$geoWithin = geospatial.cast$within; - -handle.$size = -handle.$minDistance = -handle.$maxDistance = castToNumber; - -handle.$exists = $exists; -handle.$type = $type; - -handle.$eq = -handle.$gt = -handle.$gte = -handle.$lt = -handle.$lte = -handle.$ne = -handle.$regex = SchemaArray.prototype.castForQuery; - -// `$in` is special because you can also include an empty array in the query -// like `$in: [1, []]`, see gh-5913 -handle.$nin = SchemaType.prototype.$conditionalHandlers.$nin; -handle.$in = SchemaType.prototype.$conditionalHandlers.$in; - -/*! - * Module exports. - */ - -module.exports = SchemaArray; diff --git a/node_modules/mongoose/lib/schema/boolean.js b/node_modules/mongoose/lib/schema/boolean.js deleted file mode 100644 index 4280d94..0000000 --- a/node_modules/mongoose/lib/schema/boolean.js +++ /dev/null @@ -1,231 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const CastError = require('../error/cast'); -const SchemaType = require('../schematype'); -const castBoolean = require('../cast/boolean'); -const utils = require('../utils'); - -/** - * Boolean SchemaType constructor. - * - * @param {String} path - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function SchemaBoolean(path, options) { - SchemaType.call(this, path, options, 'Boolean'); -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -SchemaBoolean.schemaName = 'Boolean'; - -SchemaBoolean.defaultOptions = {}; - -/*! - * Inherits from SchemaType. - */ -SchemaBoolean.prototype = Object.create(SchemaType.prototype); -SchemaBoolean.prototype.constructor = SchemaBoolean; - -/*! - * ignore - */ - -SchemaBoolean._cast = castBoolean; - -/** - * Sets a default option for all Boolean instances. - * - * ####Example: - * - * // Make all booleans have `default` of false. - * mongoose.Schema.Boolean.set('default', false); - * - * const Order = mongoose.model('Order', new Schema({ isPaid: Boolean })); - * new Order({ }).isPaid; // false - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - -SchemaBoolean.set = SchemaType.set; - -/** - * Get/set the function used to cast arbitrary values to booleans. - * - * ####Example: - * - * // Make Mongoose cast empty string '' to false. - * const original = mongoose.Schema.Boolean.cast(); - * mongoose.Schema.Boolean.cast(v => { - * if (v === '') { - * return false; - * } - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Schema.Boolean.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - -SchemaBoolean.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => { - if (v != null && typeof v !== 'boolean') { - throw new Error(); - } - return v; - }; - } - this._cast = caster; - - return this._cast; -}; - -/*! - * ignore - */ - -SchemaBoolean._checkRequired = v => v === true || v === false; - -/** - * Override the function the required validator uses to check whether a boolean - * passes the `required` check. - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -SchemaBoolean.checkRequired = SchemaType.checkRequired; - -/** - * Check if the given value satisfies a required validator. For a boolean - * to satisfy a required validator, it must be strictly equal to true or to - * false. - * - * @param {Any} value - * @return {Boolean} - * @api public - */ - -SchemaBoolean.prototype.checkRequired = function(value) { - return this.constructor._checkRequired(value); -}; - -/** - * Configure which values get casted to `true`. - * - * ####Example: - * - * const M = mongoose.model('Test', new Schema({ b: Boolean })); - * new M({ b: 'affirmative' }).b; // undefined - * mongoose.Schema.Boolean.convertToTrue.add('affirmative'); - * new M({ b: 'affirmative' }).b; // true - * - * @property convertToTrue - * @type Set - * @api public - */ - -Object.defineProperty(SchemaBoolean, 'convertToTrue', { - get: () => castBoolean.convertToTrue, - set: v => { castBoolean.convertToTrue = v; } -}); - -/** - * Configure which values get casted to `false`. - * - * ####Example: - * - * const M = mongoose.model('Test', new Schema({ b: Boolean })); - * new M({ b: 'nay' }).b; // undefined - * mongoose.Schema.Types.Boolean.convertToFalse.add('nay'); - * new M({ b: 'nay' }).b; // false - * - * @property convertToFalse - * @type Set - * @api public - */ - -Object.defineProperty(SchemaBoolean, 'convertToFalse', { - get: () => castBoolean.convertToFalse, - set: v => { castBoolean.convertToFalse = v; } -}); - -/** - * Casts to boolean - * - * @param {Object} value - * @param {Object} model - this value is optional - * @api private - */ - -SchemaBoolean.prototype.cast = function(value) { - const castBoolean = typeof this.constructor.cast === 'function' ? - this.constructor.cast() : - SchemaBoolean.cast(); - try { - return castBoolean(value); - } catch (error) { - throw new CastError('Boolean', value, this.path, error, this); - } -}; - -SchemaBoolean.$conditionalHandlers = - utils.options(SchemaType.prototype.$conditionalHandlers, {}); - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} val - * @api private - */ - -SchemaBoolean.prototype.castForQuery = function($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = SchemaBoolean.$conditionalHandlers[$conditional]; - - if (handler) { - return handler.call(this, val); - } - - return this._castForQuery(val); - } - - return this._castForQuery($conditional); -}; - -/*! - * Module exports. - */ - -module.exports = SchemaBoolean; diff --git a/node_modules/mongoose/lib/schema/buffer.js b/node_modules/mongoose/lib/schema/buffer.js deleted file mode 100644 index 631d18f..0000000 --- a/node_modules/mongoose/lib/schema/buffer.js +++ /dev/null @@ -1,276 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const MongooseBuffer = require('../types/buffer'); -const SchemaBufferOptions = require('../options/SchemaBufferOptions'); -const SchemaType = require('../schematype'); -const handleBitwiseOperator = require('./operators/bitwise'); -const utils = require('../utils'); - -const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; - -const Binary = MongooseBuffer.Binary; -const CastError = SchemaType.CastError; -let Document; - -/** - * Buffer SchemaType constructor - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function SchemaBuffer(key, options) { - SchemaType.call(this, key, options, 'Buffer'); -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -SchemaBuffer.schemaName = 'Buffer'; - -SchemaBuffer.defaultOptions = {}; - -/*! - * Inherits from SchemaType. - */ -SchemaBuffer.prototype = Object.create(SchemaType.prototype); -SchemaBuffer.prototype.constructor = SchemaBuffer; -SchemaBuffer.prototype.OptionsConstructor = SchemaBufferOptions; - -/*! - * ignore - */ - -SchemaBuffer._checkRequired = v => !!(v && v.length); - -/** - * Sets a default option for all Buffer instances. - * - * ####Example: - * - * // Make all buffers have `required` of true by default. - * mongoose.Schema.Buffer.set('required', true); - * - * const User = mongoose.model('User', new Schema({ test: Buffer })); - * new User({ }).validateSync().errors.test.message; // Path `test` is required. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - -SchemaBuffer.set = SchemaType.set; - -/** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * ####Example: - * - * // Allow empty strings to pass `required` check - * mongoose.Schema.Types.String.checkRequired(v => v != null); - * - * const M = mongoose.model({ buf: { type: Buffer, required: true } }); - * new M({ buf: Buffer.from('') }).validateSync(); // validation passes! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -SchemaBuffer.checkRequired = SchemaType.checkRequired; - -/** - * Check if the given value satisfies a required validator. To satisfy a - * required validator, a buffer must not be null or undefined and have - * non-zero length. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - -SchemaBuffer.prototype.checkRequired = function(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - return this.constructor._checkRequired(value); -}; - -/** - * Casts contents - * - * @param {Object} value - * @param {Document} doc document that triggers the casting - * @param {Boolean} init - * @api private - */ - -SchemaBuffer.prototype.cast = function(value, doc, init) { - let ret; - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (value === null || value === undefined) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (Buffer.isBuffer(value)) { - return value; - } else if (!utils.isObject(value)) { - throw new CastError('Buffer', value, this.path, null, this); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - const path = doc.$__fullPath(this.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - const pop = owner.populated(path, true); - ret = new pop.options[populateModelSymbol](value); - ret.$__.wasPopulated = true; - return ret; - } - - // documents - if (value && value._id) { - value = value._id; - } - - if (value && value.isMongooseBuffer) { - return value; - } - - if (Buffer.isBuffer(value)) { - if (!value || !value.isMongooseBuffer) { - value = new MongooseBuffer(value, [this.path, doc]); - if (this.options.subtype != null) { - value._subtype = this.options.subtype; - } - } - return value; - } - - if (value instanceof Binary) { - ret = new MongooseBuffer(value.value(true), [this.path, doc]); - if (typeof value.sub_type !== 'number') { - throw new CastError('Buffer', value, this.path, null, this); - } - ret._subtype = value.sub_type; - return ret; - } - - if (value === null) { - return value; - } - - - const type = typeof value; - if ( - type === 'string' || type === 'number' || Array.isArray(value) || - (type === 'object' && value.type === 'Buffer' && Array.isArray(value.data)) // gh-6863 - ) { - if (type === 'number') { - value = [value]; - } - ret = new MongooseBuffer(value, [this.path, doc]); - if (this.options.subtype != null) { - ret._subtype = this.options.subtype; - } - return ret; - } - - throw new CastError('Buffer', value, this.path, null, this); -}; - -/** - * Sets the default [subtype](https://studio3t.com/whats-new/best-practices-uuid-mongodb/) - * for this buffer. You can find a [list of allowed subtypes here](http://api.mongodb.com/python/current/api/bson/binary.html). - * - * ####Example: - * - * var s = new Schema({ uuid: { type: Buffer, subtype: 4 }); - * var M = db.model('M', s); - * var m = new M({ uuid: 'test string' }); - * m.uuid._subtype; // 4 - * - * @param {Number} subtype the default subtype - * @return {SchemaType} this - * @api public - */ - -SchemaBuffer.prototype.subtype = function(subtype) { - this.options.subtype = subtype; - return this; -}; - -/*! - * ignore - */ -function handleSingle(val) { - return this.castForQuery(val); -} - -SchemaBuffer.prototype.$conditionalHandlers = - utils.options(SchemaType.prototype.$conditionalHandlers, { - $bitsAllClear: handleBitwiseOperator, - $bitsAnyClear: handleBitwiseOperator, - $bitsAllSet: handleBitwiseOperator, - $bitsAnySet: handleBitwiseOperator, - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle - }); - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaBuffer.prototype.castForQuery = function($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new Error('Can\'t use ' + $conditional + ' with Buffer.'); - } - return handler.call(this, val); - } - val = $conditional; - const casted = this._castForQuery(val); - return casted ? casted.toObject({ transform: false, virtuals: false }) : casted; -}; - -/*! - * Module exports. - */ - -module.exports = SchemaBuffer; diff --git a/node_modules/mongoose/lib/schema/date.js b/node_modules/mongoose/lib/schema/date.js deleted file mode 100644 index ebeaf47..0000000 --- a/node_modules/mongoose/lib/schema/date.js +++ /dev/null @@ -1,390 +0,0 @@ -/*! - * Module requirements. - */ - -'use strict'; - -const MongooseError = require('../error/index'); -const SchemaDateOptions = require('../options/SchemaDateOptions'); -const SchemaType = require('../schematype'); -const castDate = require('../cast/date'); -const utils = require('../utils'); - -const CastError = SchemaType.CastError; - -/** - * Date SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function SchemaDate(key, options) { - SchemaType.call(this, key, options, 'Date'); -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -SchemaDate.schemaName = 'Date'; - -SchemaDate.defaultOptions = {}; - -/*! - * Inherits from SchemaType. - */ -SchemaDate.prototype = Object.create(SchemaType.prototype); -SchemaDate.prototype.constructor = SchemaDate; -SchemaDate.prototype.OptionsConstructor = SchemaDateOptions; - -/*! - * ignore - */ - -SchemaDate._cast = castDate; - -/** - * Sets a default option for all Date instances. - * - * ####Example: - * - * // Make all dates have `required` of true by default. - * mongoose.Schema.Date.set('required', true); - * - * const User = mongoose.model('User', new Schema({ test: Date })); - * new User({ }).validateSync().errors.test.message; // Path `test` is required. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - -SchemaDate.set = SchemaType.set; - -/** - * Get/set the function used to cast arbitrary values to dates. - * - * ####Example: - * - * // Mongoose converts empty string '' into `null` for date types. You - * // can create a custom caster to disable it. - * const original = mongoose.Schema.Types.Date.cast(); - * mongoose.Schema.Types.Date.cast(v => { - * assert.ok(v !== ''); - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Schema.Types.Date.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - -SchemaDate.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => { - if (v != null && !(v instanceof Date)) { - throw new Error(); - } - return v; - }; - } - this._cast = caster; - - return this._cast; -}; - -/** - * Declares a TTL index (rounded to the nearest second) for _Date_ types only. - * - * This sets the `expireAfterSeconds` index option available in MongoDB >= 2.1.2. - * This index type is only compatible with Date types. - * - * ####Example: - * - * // expire in 24 hours - * new Schema({ createdAt: { type: Date, expires: 60*60*24 }}); - * - * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax: - * - * ####Example: - * - * // expire in 24 hours - * new Schema({ createdAt: { type: Date, expires: '24h' }}); - * - * // expire in 1.5 hours - * new Schema({ createdAt: { type: Date, expires: '1.5h' }}); - * - * // expire in 7 days - * var schema = new Schema({ createdAt: Date }); - * schema.path('createdAt').expires('7d'); - * - * @param {Number|String} when - * @added 3.0.0 - * @return {SchemaType} this - * @api public - */ - -SchemaDate.prototype.expires = function(when) { - if (!this._index || this._index.constructor.name !== 'Object') { - this._index = {}; - } - - this._index.expires = when; - utils.expires(this._index); - return this; -}; - -/*! - * ignore - */ - -SchemaDate._checkRequired = v => v instanceof Date; - -/** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * ####Example: - * - * // Allow empty strings to pass `required` check - * mongoose.Schema.Types.String.checkRequired(v => v != null); - * - * const M = mongoose.model({ str: { type: String, required: true } }); - * new M({ str: '' }).validateSync(); // `null`, validation passes! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -SchemaDate.checkRequired = SchemaType.checkRequired; - -/** - * Check if the given value satisfies a required validator. To satisfy - * a required validator, the given value must be an instance of `Date`. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - -SchemaDate.prototype.checkRequired = function(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - - // `require('util').inherits()` does **not** copy static properties, and - // plugins like mongoose-float use `inherits()` for pre-ES6. - const _checkRequired = typeof this.constructor.checkRequired == 'function' ? - this.constructor.checkRequired() : - SchemaDate.checkRequired(); - return _checkRequired(value); -}; - -/** - * Sets a minimum date validator. - * - * ####Example: - * - * var s = new Schema({ d: { type: Date, min: Date('1970-01-01') }) - * var M = db.model('M', s) - * var m = new M({ d: Date('1969-12-31') }) - * m.save(function (err) { - * console.error(err) // validator error - * m.d = Date('2014-12-08'); - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MIN} token which will be replaced with the invalid value - * var min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; - * var schema = new Schema({ d: { type: Date, min: min }) - * var M = mongoose.model('M', schema); - * var s= new M({ d: Date('1969-12-31') }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01). - * }) - * - * @param {Date} value minimum date - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaDate.prototype.min = function(value, message) { - if (this.minValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.minValidator; - }, this); - } - - if (value) { - let msg = message || MongooseError.messages.Date.min; - if (typeof msg === 'string') { - msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : value.toString())); - } - const _this = this; - this.validators.push({ - validator: this.minValidator = function(val) { - let _value = value; - if (typeof value === 'function' && value !== Date.now) { - _value = _value.call(this); - } - const min = (_value === Date.now ? _value() : _this.cast(_value)); - return val === null || val.valueOf() >= min.valueOf(); - }, - message: msg, - type: 'min', - min: value - }); - } - - return this; -}; - -/** - * Sets a maximum date validator. - * - * ####Example: - * - * var s = new Schema({ d: { type: Date, max: Date('2014-01-01') }) - * var M = db.model('M', s) - * var m = new M({ d: Date('2014-12-08') }) - * m.save(function (err) { - * console.error(err) // validator error - * m.d = Date('2013-12-31'); - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MAX} token which will be replaced with the invalid value - * var max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; - * var schema = new Schema({ d: { type: Date, max: max }) - * var M = mongoose.model('M', schema); - * var s= new M({ d: Date('2014-12-08') }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01). - * }) - * - * @param {Date} maximum date - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaDate.prototype.max = function(value, message) { - if (this.maxValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.maxValidator; - }, this); - } - - if (value) { - let msg = message || MongooseError.messages.Date.max; - if (typeof msg === 'string') { - msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : value.toString())); - } - const _this = this; - this.validators.push({ - validator: this.maxValidator = function(val) { - let _value = value; - if (typeof _value === 'function' && _value !== Date.now) { - _value = _value.call(this); - } - const max = (_value === Date.now ? _value() : _this.cast(_value)); - return val === null || val.valueOf() <= max.valueOf(); - }, - message: msg, - type: 'max', - max: value - }); - } - - return this; -}; - -/** - * Casts to date - * - * @param {Object} value to cast - * @api private - */ - -SchemaDate.prototype.cast = function(value) { - const castDate = typeof this.constructor.cast === 'function' ? - this.constructor.cast() : - SchemaDate.cast(); - try { - return castDate(value); - } catch (error) { - throw new CastError('date', value, this.path, error, this); - } -}; - -/*! - * Date Query casting. - * - * @api private - */ - -function handleSingle(val) { - return this.cast(val); -} - -SchemaDate.prototype.$conditionalHandlers = - utils.options(SchemaType.prototype.$conditionalHandlers, { - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle - }); - - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaDate.prototype.castForQuery = function($conditional, val) { - if (arguments.length !== 2) { - return this._castForQuery($conditional); - } - - const handler = this.$conditionalHandlers[$conditional]; - - if (!handler) { - throw new Error('Can\'t use ' + $conditional + ' with Date.'); - } - - return handler.call(this, val); -}; - -/*! - * Module exports. - */ - -module.exports = SchemaDate; diff --git a/node_modules/mongoose/lib/schema/decimal128.js b/node_modules/mongoose/lib/schema/decimal128.js deleted file mode 100644 index ca9bcb4..0000000 --- a/node_modules/mongoose/lib/schema/decimal128.js +++ /dev/null @@ -1,235 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const SchemaType = require('../schematype'); -const CastError = SchemaType.CastError; -const Decimal128Type = require('../types/decimal128'); -const castDecimal128 = require('../cast/decimal128'); -const utils = require('../utils'); - -const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; - -let Document; - -/** - * Decimal128 SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function Decimal128(key, options) { - SchemaType.call(this, key, options, 'Decimal128'); -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -Decimal128.schemaName = 'Decimal128'; - -Decimal128.defaultOptions = {}; - -/*! - * Inherits from SchemaType. - */ -Decimal128.prototype = Object.create(SchemaType.prototype); -Decimal128.prototype.constructor = Decimal128; - -/*! - * ignore - */ - -Decimal128._cast = castDecimal128; - -/** - * Sets a default option for all Decimal128 instances. - * - * ####Example: - * - * // Make all decimal 128s have `required` of true by default. - * mongoose.Schema.Decimal128.set('required', true); - * - * const User = mongoose.model('User', new Schema({ test: mongoose.Decimal128 })); - * new User({ }).validateSync().errors.test.message; // Path `test` is required. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - -Decimal128.set = SchemaType.set; - -/** - * Get/set the function used to cast arbitrary values to decimals. - * - * ####Example: - * - * // Make Mongoose only refuse to cast numbers as decimal128 - * const original = mongoose.Schema.Types.Decimal128.cast(); - * mongoose.Decimal128.cast(v => { - * assert.ok(typeof v !== 'number'); - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Decimal128.cast(false); - * - * @param {Function} [caster] - * @return {Function} - * @function get - * @static - * @api public - */ - -Decimal128.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => { - if (v != null && !(v instanceof Decimal128Type)) { - throw new Error(); - } - return v; - }; - } - this._cast = caster; - - return this._cast; -}; - -/*! - * ignore - */ - -Decimal128._checkRequired = v => v instanceof Decimal128Type; - -/** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -Decimal128.checkRequired = SchemaType.checkRequired; - -/** - * Check if the given value satisfies a required validator. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - -Decimal128.prototype.checkRequired = function checkRequired(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - - // `require('util').inherits()` does **not** copy static properties, and - // plugins like mongoose-float use `inherits()` for pre-ES6. - const _checkRequired = typeof this.constructor.checkRequired == 'function' ? - this.constructor.checkRequired() : - Decimal128.checkRequired(); - - return _checkRequired(value); -}; - -/** - * Casts to Decimal128 - * - * @param {Object} value - * @param {Object} doc - * @param {Boolean} init whether this is an initialization cast - * @api private - */ - -Decimal128.prototype.cast = function(value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (value === null || value === undefined) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (value instanceof Decimal128Type) { - return value; - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('Decimal128', value, this.path, null, this); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - const path = doc.$__fullPath(this.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - const pop = owner.populated(path, true); - let ret = value; - if (!doc.$__.populated || - !doc.$__.populated[path] || - !doc.$__.populated[path].options || - !doc.$__.populated[path].options.options || - !doc.$__.populated[path].options.options.lean) { - ret = new pop.options[populateModelSymbol](value); - ret.$__.wasPopulated = true; - } - - return ret; - } - - const castDecimal128 = typeof this.constructor.cast === 'function' ? - this.constructor.cast() : - Decimal128.cast(); - try { - return castDecimal128(value); - } catch (error) { - throw new CastError('Decimal128', value, this.path, error, this); - } -}; - -/*! - * ignore - */ - -function handleSingle(val) { - return this.cast(val); -} - -Decimal128.prototype.$conditionalHandlers = - utils.options(SchemaType.prototype.$conditionalHandlers, { - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle - }); - -/*! - * Module exports. - */ - -module.exports = Decimal128; diff --git a/node_modules/mongoose/lib/schema/documentarray.js b/node_modules/mongoose/lib/schema/documentarray.js deleted file mode 100644 index 57e2fa4..0000000 --- a/node_modules/mongoose/lib/schema/documentarray.js +++ /dev/null @@ -1,517 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const ArrayType = require('./array'); -const CastError = require('../error/cast'); -const EventEmitter = require('events').EventEmitter; -const SchemaDocumentArrayOptions = - require('../options/SchemaDocumentArrayOptions'); -const SchemaType = require('../schematype'); -const ValidationError = require('../error/validation'); -const discriminator = require('../helpers/model/discriminator'); -const get = require('../helpers/get'); -const handleIdOption = require('../helpers/schema/handleIdOption'); -const util = require('util'); -const utils = require('../utils'); -const getConstructor = require('../helpers/discriminator/getConstructor'); - -const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol; -const documentArrayParent = require('../helpers/symbols').documentArrayParent; - -let MongooseDocumentArray; -let Subdocument; - -/** - * SubdocsArray SchemaType constructor - * - * @param {String} key - * @param {Schema} schema - * @param {Object} options - * @inherits SchemaArray - * @api public - */ - -function DocumentArrayPath(key, schema, options, schemaOptions) { - if (schemaOptions != null && schemaOptions._id != null) { - schema = handleIdOption(schema, schemaOptions); - } else if (options != null && options._id != null) { - schema = handleIdOption(schema, options); - } - - const EmbeddedDocument = _createConstructor(schema, options); - EmbeddedDocument.prototype.$basePath = key; - - ArrayType.call(this, key, EmbeddedDocument, options); - - this.schema = schema; - this.schemaOptions = schemaOptions || {}; - this.$isMongooseDocumentArray = true; - this.Constructor = EmbeddedDocument; - - EmbeddedDocument.base = schema.base; - - const fn = this.defaultValue; - - if (!('defaultValue' in this) || fn !== void 0) { - this.default(function() { - let arr = fn.call(this); - if (!Array.isArray(arr)) { - arr = [arr]; - } - // Leave it up to `cast()` to convert this to a documentarray - return arr; - }); - } - - const parentSchemaType = this; - this.$embeddedSchemaType = new SchemaType(key + '.$', { - required: get(this, 'schemaOptions.required', false) - }); - this.$embeddedSchemaType.cast = function(value, doc, init) { - return parentSchemaType.cast(value, doc, init)[0]; - }; - this.$embeddedSchemaType.$isMongooseDocumentArrayElement = true; - this.$embeddedSchemaType.caster = this.Constructor; - this.$embeddedSchemaType.schema = this.schema; -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -DocumentArrayPath.schemaName = 'DocumentArray'; - -/** - * Options for all document arrays. - * - * - `castNonArrays`: `true` by default. If `false`, Mongoose will throw a CastError when a value isn't an array. If `true`, Mongoose will wrap the provided value in an array before casting. - * - * @api public - */ - -DocumentArrayPath.options = { castNonArrays: true }; - -/*! - * Inherits from ArrayType. - */ -DocumentArrayPath.prototype = Object.create(ArrayType.prototype); -DocumentArrayPath.prototype.constructor = DocumentArrayPath; -DocumentArrayPath.prototype.OptionsConstructor = SchemaDocumentArrayOptions; - -/*! - * Ignore - */ - -function _createConstructor(schema, options, baseClass) { - Subdocument || (Subdocument = require('../types/embedded')); - - // compile an embedded document for this schema - function EmbeddedDocument() { - Subdocument.apply(this, arguments); - - this.$session(this.ownerDocument().$session()); - } - - const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype; - EmbeddedDocument.prototype = Object.create(proto); - EmbeddedDocument.prototype.$__setSchema(schema); - EmbeddedDocument.schema = schema; - EmbeddedDocument.prototype.constructor = EmbeddedDocument; - EmbeddedDocument.$isArraySubdocument = true; - EmbeddedDocument.events = new EventEmitter(); - - // apply methods - for (const i in schema.methods) { - EmbeddedDocument.prototype[i] = schema.methods[i]; - } - - // apply statics - for (const i in schema.statics) { - EmbeddedDocument[i] = schema.statics[i]; - } - - for (const i in EventEmitter.prototype) { - EmbeddedDocument[i] = EventEmitter.prototype[i]; - } - - EmbeddedDocument.options = options; - - return EmbeddedDocument; -} - -/** - * Adds a discriminator to this document array. - * - * ####Example: - * const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' }); - * const schema = Schema({ shapes: [shapeSchema] }); - * - * const docArrayPath = parentSchema.path('shapes'); - * docArrayPath.discriminator('Circle', Schema({ radius: Number })); - * - * @param {String} name - * @param {Schema} schema fields to add to the schema for instances of this sub-class - * @param {String} [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. - * @see discriminators /docs/discriminators.html - * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model - * @api public - */ - -DocumentArrayPath.prototype.discriminator = function(name, schema, tiedValue) { - if (typeof name === 'function') { - name = utils.getFunctionName(name); - } - - schema = discriminator(this.casterConstructor, name, schema, tiedValue); - - const EmbeddedDocument = _createConstructor(schema, null, this.casterConstructor); - EmbeddedDocument.baseCasterConstructor = this.casterConstructor; - - try { - Object.defineProperty(EmbeddedDocument, 'name', { - value: name - }); - } catch (error) { - // Ignore error, only happens on old versions of node - } - - this.casterConstructor.discriminators[name] = EmbeddedDocument; - - return this.casterConstructor.discriminators[name]; -}; - -/** - * Performs local validations first, then validations on each embedded doc - * - * @api private - */ - -DocumentArrayPath.prototype.doValidate = function(array, fn, scope, options) { - // lazy load - MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray')); - - const _this = this; - try { - SchemaType.prototype.doValidate.call(this, array, cb, scope); - } catch (err) { - err.$isArrayValidatorError = true; - return fn(err); - } - - function cb(err) { - if (err) { - err.$isArrayValidatorError = true; - return fn(err); - } - - let count = array && array.length; - let error; - - if (!count) { - return fn(); - } - if (options && options.updateValidator) { - return fn(); - } - if (!array.isMongooseDocumentArray) { - array = new MongooseDocumentArray(array, _this.path, scope); - } - - // handle sparse arrays, do not use array.forEach which does not - // iterate over sparse elements yet reports array.length including - // them :( - - function callback(err) { - if (err != null) { - error = err; - if (!(error instanceof ValidationError)) { - error.$isArrayValidatorError = true; - } - } - --count || fn(error); - } - - for (let i = 0, len = count; i < len; ++i) { - // sidestep sparse entries - let doc = array[i]; - if (doc == null) { - --count || fn(error); - continue; - } - - // If you set the array index directly, the doc might not yet be - // a full fledged mongoose subdoc, so make it into one. - if (!(doc instanceof Subdocument)) { - const Constructor = getConstructor(_this.casterConstructor, array[i]); - doc = array[i] = new Constructor(doc, array, undefined, undefined, i); - } - - doc.$__validate(callback); - } - } -}; - -/** - * Performs local validations first, then validations on each embedded doc. - * - * ####Note: - * - * This method ignores the asynchronous validators. - * - * @return {MongooseError|undefined} - * @api private - */ - -DocumentArrayPath.prototype.doValidateSync = function(array, scope) { - const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope); - if (schemaTypeError != null) { - schemaTypeError.$isArrayValidatorError = true; - return schemaTypeError; - } - - const count = array && array.length; - let resultError = null; - - if (!count) { - return; - } - - // handle sparse arrays, do not use array.forEach which does not - // iterate over sparse elements yet reports array.length including - // them :( - - for (let i = 0, len = count; i < len; ++i) { - // sidestep sparse entries - let doc = array[i]; - if (!doc) { - continue; - } - - // If you set the array index directly, the doc might not yet be - // a full fledged mongoose subdoc, so make it into one. - if (!(doc instanceof Subdocument)) { - const Constructor = getConstructor(this.casterConstructor, array[i]); - doc = array[i] = new Constructor(doc, array, undefined, undefined, i); - } - - const subdocValidateError = doc.validateSync(); - - if (subdocValidateError && resultError == null) { - resultError = subdocValidateError; - } - } - - return resultError; -}; - -/*! - * ignore - */ - -DocumentArrayPath.prototype.getDefault = function(scope) { - let ret = typeof this.defaultValue === 'function' - ? this.defaultValue.call(scope) - : this.defaultValue; - - if (ret == null) { - return ret; - } - - // lazy load - MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray')); - - if (!Array.isArray(ret)) { - ret = [ret]; - } - - ret = new MongooseDocumentArray(ret, this.path, scope); - - for (let i = 0; i < ret.length; ++i) { - const Constructor = getConstructor(this.casterConstructor, ret[i]); - const _subdoc = new Constructor({}, ret, undefined, - undefined, i); - _subdoc.init(ret[i]); - _subdoc.isNew = true; - - // Make sure all paths in the subdoc are set to `default` instead - // of `init` since we used `init`. - Object.assign(_subdoc.$__.activePaths.default, _subdoc.$__.activePaths.init); - _subdoc.$__.activePaths.init = {}; - - ret[i] = _subdoc; - } - - return ret; -}; - -/** - * Casts contents - * - * @param {Object} value - * @param {Document} document that triggers the casting - * @api private - */ - -DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) { - // lazy load - MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray')); - - let selected; - let subdoc; - const _opts = { transform: false, virtuals: false }; - options = options || {}; - - if (!Array.isArray(value)) { - if (!init && !DocumentArrayPath.options.castNonArrays) { - throw new CastError('DocumentArray', util.inspect(value), this.path, null, this); - } - // gh-2442 mark whole array as modified if we're initializing a doc from - // the db and the path isn't an array in the document - if (!!doc && init) { - doc.markModified(this.path); - } - return this.cast([value], doc, init, prev, options); - } - - if (!(value && value.isMongooseDocumentArray) && - !options.skipDocumentArrayCast) { - value = new MongooseDocumentArray(value, this.path, doc); - } else if (value && value.isMongooseDocumentArray) { - // We need to create a new array, otherwise change tracking will - // update the old doc (gh-4449) - value = new MongooseDocumentArray(value, this.path, doc); - } - - if (options.arrayPath != null) { - value[arrayPathSymbol] = options.arrayPath; - } - - const len = value.length; - - for (let i = 0; i < len; ++i) { - if (!value[i]) { - continue; - } - - const Constructor = getConstructor(this.casterConstructor, value[i]); - - // Check if the document has a different schema (re gh-3701) - if ((value[i].$__) && - (!(value[i] instanceof Constructor) || value[i][documentArrayParent] !== doc)) { - value[i] = value[i].toObject({ - transform: false, - // Special case: if different model, but same schema, apply virtuals - // re: gh-7898 - virtuals: value[i].schema === Constructor.schema - }); - } - - if (value[i] instanceof Subdocument) { - // Might not have the correct index yet, so ensure it does. - if (value[i].__index == null) { - value[i].$setIndex(i); - } - } else if (value[i] != null) { - if (init) { - if (doc) { - selected || (selected = scopePaths(this, doc.$__.selected, init)); - } else { - selected = true; - } - - subdoc = new Constructor(null, value, true, selected, i); - value[i] = subdoc.init(value[i]); - } else { - if (prev && typeof prev.id === 'function') { - subdoc = prev.id(value[i]._id); - } - - if (prev && subdoc && utils.deepEqual(subdoc.toObject(_opts), value[i])) { - // handle resetting doc with existing id and same data - subdoc.set(value[i]); - // if set() is hooked it will have no return value - // see gh-746 - value[i] = subdoc; - } else { - try { - subdoc = new Constructor(value[i], value, undefined, - undefined, i); - // if set() is hooked it will have no return value - // see gh-746 - value[i] = subdoc; - } catch (error) { - const valueInErrorMessage = util.inspect(value[i]); - throw new CastError('embedded', valueInErrorMessage, - value[arrayPathSymbol], error, this); - } - } - } - } - } - - return value; -}; - -/*! - * ignore - */ - -DocumentArrayPath.prototype.clone = function() { - const options = Object.assign({}, this.options); - const schematype = new this.constructor(this.path, this.schema, options, this.schemaOptions); - schematype.validators = this.validators.slice(); - schematype.Constructor.discriminators = Object.assign({}, - this.Constructor.discriminators); - return schematype; -}; - -/*! - * Scopes paths selected in a query to this array. - * Necessary for proper default application of subdocument values. - * - * @param {DocumentArrayPath} array - the array to scope `fields` paths - * @param {Object|undefined} fields - the root fields selected in the query - * @param {Boolean|undefined} init - if we are being created part of a query result - */ - -function scopePaths(array, fields, init) { - if (!(init && fields)) { - return undefined; - } - - const path = array.path + '.'; - const keys = Object.keys(fields); - let i = keys.length; - const selected = {}; - let hasKeys; - let key; - let sub; - - while (i--) { - key = keys[i]; - if (key.startsWith(path)) { - sub = key.substring(path.length); - if (sub === '$') { - continue; - } - if (sub.startsWith('$.')) { - sub = sub.substr(2); - } - hasKeys || (hasKeys = true); - selected[sub] = fields[key]; - } - } - - return hasKeys && selected || undefined; -} - -/*! - * Module exports. - */ - -module.exports = DocumentArrayPath; diff --git a/node_modules/mongoose/lib/schema/index.js b/node_modules/mongoose/lib/schema/index.js deleted file mode 100644 index f33b084..0000000 --- a/node_modules/mongoose/lib/schema/index.js +++ /dev/null @@ -1,37 +0,0 @@ - -/*! - * Module exports. - */ - -'use strict'; - -exports.String = require('./string'); - -exports.Number = require('./number'); - -exports.Boolean = require('./boolean'); - -exports.DocumentArray = require('./documentarray'); - -exports.Embedded = require('./SingleNestedPath'); - -exports.Array = require('./array'); - -exports.Buffer = require('./buffer'); - -exports.Date = require('./date'); - -exports.ObjectId = require('./objectid'); - -exports.Mixed = require('./mixed'); - -exports.Decimal128 = exports.Decimal = require('./decimal128'); - -exports.Map = require('./map'); - -// alias - -exports.Oid = exports.ObjectId; -exports.Object = exports.Mixed; -exports.Bool = exports.Boolean; -exports.ObjectID = exports.ObjectId; diff --git a/node_modules/mongoose/lib/schema/map.js b/node_modules/mongoose/lib/schema/map.js deleted file mode 100644 index 468faea..0000000 --- a/node_modules/mongoose/lib/schema/map.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -const MongooseMap = require('../types/map'); -const SchemaMapOptions = require('../options/SchemaMapOptions'); -const SchemaType = require('../schematype'); -/*! - * ignore - */ - -class Map extends SchemaType { - constructor(key, options) { - super(key, options, 'Map'); - this.$isSchemaMap = true; - } - - set(option, value) { - return SchemaType.set(option, value); - } - - cast(val, doc, init) { - if (val instanceof MongooseMap) { - return val; - } - - if (init) { - const map = new MongooseMap({}, this.path, doc, this.$__schemaType); - - if (val instanceof global.Map) { - for (const key of val.keys()) { - map.$init(key, map.$__schemaType.cast(val.get(key), doc, true)); - } - } else { - for (const key of Object.keys(val)) { - map.$init(key, map.$__schemaType.cast(val[key], doc, true)); - } - } - - return map; - } - - return new MongooseMap(val, this.path, doc, this.$__schemaType); - } - - clone() { - const schematype = super.clone(); - - if (this.$__schemaType != null) { - schematype.$__schemaType = this.$__schemaType.clone(); - } - return schematype; - } -} - -Map.prototype.OptionsConstructor = SchemaMapOptions; - -Map.defaultOptions = {}; - -module.exports = Map; diff --git a/node_modules/mongoose/lib/schema/mixed.js b/node_modules/mongoose/lib/schema/mixed.js deleted file mode 100644 index 88e4db6..0000000 --- a/node_modules/mongoose/lib/schema/mixed.js +++ /dev/null @@ -1,128 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const SchemaType = require('../schematype'); -const symbols = require('./symbols'); -const isObject = require('../helpers/isObject'); - -/** - * Mixed SchemaType constructor. - * - * @param {String} path - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function Mixed(path, options) { - if (options && options.default) { - const def = options.default; - if (Array.isArray(def) && def.length === 0) { - // make sure empty array defaults are handled - options.default = Array; - } else if (!options.shared && isObject(def) && Object.keys(def).length === 0) { - // prevent odd "shared" objects between documents - options.default = function() { - return {}; - }; - } - } - - SchemaType.call(this, path, options, 'Mixed'); - - this[symbols.schemaMixedSymbol] = true; -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -Mixed.schemaName = 'Mixed'; - -Mixed.defaultOptions = {}; - -/*! - * Inherits from SchemaType. - */ -Mixed.prototype = Object.create(SchemaType.prototype); -Mixed.prototype.constructor = Mixed; - -/** - * Attaches a getter for all Mixed paths. - * - * ####Example: - * - * // Hide the 'hidden' path - * mongoose.Schema.Mixed.get(v => Object.assign({}, v, { hidden: null })); - * - * const Model = mongoose.model('Test', new Schema({ test: {} })); - * new Model({ test: { hidden: 'Secret!' } }).test.hidden; // null - * - * @param {Function} getter - * @return {this} - * @function get - * @static - * @api public - */ - -Mixed.get = SchemaType.get; - -/** - * Sets a default option for all Mixed instances. - * - * ####Example: - * - * // Make all mixed instances have `required` of true by default. - * mongoose.Schema.Mixed.set('required', true); - * - * const User = mongoose.model('User', new Schema({ test: mongoose.Mixed })); - * new User({ }).validateSync().errors.test.message; // Path `test` is required. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - -Mixed.set = SchemaType.set; - -/** - * Casts `val` for Mixed. - * - * _this is a no-op_ - * - * @param {Object} value to cast - * @api private - */ - -Mixed.prototype.cast = function(val) { - return val; -}; - -/** - * Casts contents for queries. - * - * @param {String} $cond - * @param {any} [val] - * @api private - */ - -Mixed.prototype.castForQuery = function($cond, val) { - if (arguments.length === 2) { - return val; - } - return $cond; -}; - -/*! - * Module exports. - */ - -module.exports = Mixed; diff --git a/node_modules/mongoose/lib/schema/number.js b/node_modules/mongoose/lib/schema/number.js deleted file mode 100644 index 0b532bc..0000000 --- a/node_modules/mongoose/lib/schema/number.js +++ /dev/null @@ -1,444 +0,0 @@ -'use strict'; - -/*! - * Module requirements. - */ - -const MongooseError = require('../error/index'); -const SchemaNumberOptions = require('../options/SchemaNumberOptions'); -const SchemaType = require('../schematype'); -const castNumber = require('../cast/number'); -const handleBitwiseOperator = require('./operators/bitwise'); -const utils = require('../utils'); - -const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; - -const CastError = SchemaType.CastError; -let Document; - -/** - * Number SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function SchemaNumber(key, options) { - SchemaType.call(this, key, options, 'Number'); -} - -/** - * Attaches a getter for all Number instances. - * - * ####Example: - * - * // Make all numbers round down - * mongoose.Number.get(function(v) { return Math.floor(v); }); - * - * const Model = mongoose.model('Test', new Schema({ test: Number })); - * new Model({ test: 3.14 }).test; // 3 - * - * @param {Function} getter - * @return {this} - * @function get - * @static - * @api public - */ - -SchemaNumber.get = SchemaType.get; - -/** - * Sets a default option for all Number instances. - * - * ####Example: - * - * // Make all numbers have option `min` equal to 0. - * mongoose.Schema.Number.set('min', 0); - * - * const Order = mongoose.model('Order', new Schema({ amount: Number })); - * new Order({ amount: -10 }).validateSync().errors.amount.message; // Path `amount` must be larger than 0. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - -SchemaNumber.set = SchemaType.set; - -/*! - * ignore - */ - -SchemaNumber._cast = castNumber; - -/** - * Get/set the function used to cast arbitrary values to numbers. - * - * ####Example: - * - * // Make Mongoose cast empty strings '' to 0 for paths declared as numbers - * const original = mongoose.Number.cast(); - * mongoose.Number.cast(v => { - * if (v === '') { return 0; } - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Number.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - -SchemaNumber.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => { - if (typeof v !== 'number') { - throw new Error(); - } - return v; - }; - } - this._cast = caster; - - return this._cast; -}; - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -SchemaNumber.schemaName = 'Number'; - -SchemaNumber.defaultOptions = {}; - -/*! - * Inherits from SchemaType. - */ -SchemaNumber.prototype = Object.create(SchemaType.prototype); -SchemaNumber.prototype.constructor = SchemaNumber; -SchemaNumber.prototype.OptionsConstructor = SchemaNumberOptions; - -/*! - * ignore - */ - -SchemaNumber._checkRequired = v => typeof v === 'number' || v instanceof Number; - -/** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -SchemaNumber.checkRequired = SchemaType.checkRequired; - -/** - * Check if the given value satisfies a required validator. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - -SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - - // `require('util').inherits()` does **not** copy static properties, and - // plugins like mongoose-float use `inherits()` for pre-ES6. - const _checkRequired = typeof this.constructor.checkRequired == 'function' ? - this.constructor.checkRequired() : - SchemaNumber.checkRequired(); - - return _checkRequired(value); -}; - -/** - * Sets a minimum number validator. - * - * ####Example: - * - * var s = new Schema({ n: { type: Number, min: 10 }) - * var M = db.model('M', s) - * var m = new M({ n: 9 }) - * m.save(function (err) { - * console.error(err) // validator error - * m.n = 10; - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MIN} token which will be replaced with the invalid value - * var min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; - * var schema = new Schema({ n: { type: Number, min: min }) - * var M = mongoose.model('Measurement', schema); - * var s= new M({ n: 4 }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10). - * }) - * - * @param {Number} value minimum number - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaNumber.prototype.min = function(value, message) { - if (this.minValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.minValidator; - }, this); - } - - if (value !== null && value !== undefined) { - let msg = message || MongooseError.messages.Number.min; - msg = msg.replace(/{MIN}/, value); - this.validators.push({ - validator: this.minValidator = function(v) { - return v == null || v >= value; - }, - message: msg, - type: 'min', - min: value - }); - } - - return this; -}; - -/** - * Sets a maximum number validator. - * - * ####Example: - * - * var s = new Schema({ n: { type: Number, max: 10 }) - * var M = db.model('M', s) - * var m = new M({ n: 11 }) - * m.save(function (err) { - * console.error(err) // validator error - * m.n = 10; - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MAX} token which will be replaced with the invalid value - * var max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; - * var schema = new Schema({ n: { type: Number, max: max }) - * var M = mongoose.model('Measurement', schema); - * var s= new M({ n: 4 }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10). - * }) - * - * @param {Number} maximum number - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaNumber.prototype.max = function(value, message) { - if (this.maxValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.maxValidator; - }, this); - } - - if (value !== null && value !== undefined) { - let msg = message || MongooseError.messages.Number.max; - msg = msg.replace(/{MAX}/, value); - this.validators.push({ - validator: this.maxValidator = function(v) { - return v == null || v <= value; - }, - message: msg, - type: 'max', - max: value - }); - } - - return this; -}; - -/** - * Sets a enum validator - * - * ####Example: - * - * var s = new Schema({ n: { type: Number, enum: [1, 2, 3] }); - * var M = db.model('M', s); - * - * var m = new M({ n: 4 }); - * await m.save(); // throws validation error - * - * m.n = 3; - * await m.save(); // succeeds - * - * @param {Array} values allowed values - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaNumber.prototype.enum = function(values, message) { - if (this.enumValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.enumValidator; - }, this); - } - - if (!Array.isArray(values)) { - values = Array.prototype.slice.call(arguments); - message = MongooseError.messages.Number.enum; - } - - message = message == null ? MongooseError.messages.Number.enum : message; - - this.enumValidator = v => v == null || values.indexOf(v) !== -1; - this.validators.push({ - validator: this.enumValidator, - message: message, - type: 'enum', - enumValues: values - }); - - return this; -}; - -/** - * Casts to number - * - * @param {Object} value value to cast - * @param {Document} doc document that triggers the casting - * @param {Boolean} init - * @api private - */ - -SchemaNumber.prototype.cast = function(value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (value === null || value === undefined) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (typeof value === 'number') { - return value; - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('Number', value, this.path, null, this); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - const path = doc.$__fullPath(this.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - const pop = owner.populated(path, true); - const ret = new pop.options[populateModelSymbol](value); - ret.$__.wasPopulated = true; - return ret; - } - - const val = value && typeof value._id !== 'undefined' ? - value._id : // documents - value; - - const castNumber = typeof this.constructor.cast === 'function' ? - this.constructor.cast() : - SchemaNumber.cast(); - try { - return castNumber(val); - } catch (err) { - throw new CastError('Number', val, this.path, err, this); - } -}; - -/*! - * ignore - */ - -function handleSingle(val) { - return this.cast(val); -} - -function handleArray(val) { - const _this = this; - if (!Array.isArray(val)) { - return [this.cast(val)]; - } - return val.map(function(m) { - return _this.cast(m); - }); -} - -SchemaNumber.prototype.$conditionalHandlers = - utils.options(SchemaType.prototype.$conditionalHandlers, { - $bitsAllClear: handleBitwiseOperator, - $bitsAnyClear: handleBitwiseOperator, - $bitsAllSet: handleBitwiseOperator, - $bitsAnySet: handleBitwiseOperator, - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle, - $mod: handleArray - }); - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaNumber.prototype.castForQuery = function($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new CastError('number', val, this.path, null, this); - } - return handler.call(this, val); - } - val = this._castForQuery($conditional); - return val; -}; - -/*! - * Module exports. - */ - -module.exports = SchemaNumber; diff --git a/node_modules/mongoose/lib/schema/objectid.js b/node_modules/mongoose/lib/schema/objectid.js deleted file mode 100644 index ee27f2e..0000000 --- a/node_modules/mongoose/lib/schema/objectid.js +++ /dev/null @@ -1,319 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const SchemaObjectIdOptions = require('../options/SchemaObjectIdOptions'); -const SchemaType = require('../schematype'); -const castObjectId = require('../cast/objectid'); -const oid = require('../types/objectid'); -const utils = require('../utils'); - -const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; - -const CastError = SchemaType.CastError; -let Document; - -/** - * ObjectId SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function ObjectId(key, options) { - const isKeyHexStr = typeof key === 'string' && key.length === 24 && /^[a-f0-9]+$/i.test(key); - const suppressWarning = options && options.suppressWarning; - if ((isKeyHexStr || typeof key === 'undefined') && !suppressWarning) { - console.warn('mongoose: To create a new ObjectId please try ' + - '`Mongoose.Types.ObjectId` instead of using ' + - '`Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if ' + - 'you\'re trying to create a hex char path in your schema.'); - console.trace(); - } - SchemaType.call(this, key, options, 'ObjectID'); -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -ObjectId.schemaName = 'ObjectId'; - -ObjectId.defaultOptions = {}; - -/*! - * Inherits from SchemaType. - */ -ObjectId.prototype = Object.create(SchemaType.prototype); -ObjectId.prototype.constructor = ObjectId; -ObjectId.prototype.OptionsConstructor = SchemaObjectIdOptions; - -/** - * Attaches a getter for all ObjectId instances - * - * ####Example: - * - * // Always convert to string when getting an ObjectId - * mongoose.ObjectId.get(v => v.toString()); - * - * const Model = mongoose.model('Test', new Schema({})); - * typeof (new Model({})._id); // 'string' - * - * @param {Function} getter - * @return {this} - * @function get - * @static - * @api public - */ - -ObjectId.get = SchemaType.get; - -/** - * Sets a default option for all ObjectId instances. - * - * ####Example: - * - * // Make all object ids have option `required` equal to true. - * mongoose.Schema.ObjectId.set('required', true); - * - * const Order = mongoose.model('Order', new Schema({ userId: ObjectId })); - * new Order({ }).validateSync().errors.userId.message; // Path `userId` is required. - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - -ObjectId.set = SchemaType.set; - -/** - * Adds an auto-generated ObjectId default if turnOn is true. - * @param {Boolean} turnOn auto generated ObjectId defaults - * @api public - * @return {SchemaType} this - */ - -ObjectId.prototype.auto = function(turnOn) { - if (turnOn) { - this.default(defaultId); - this.set(resetId); - } - - return this; -}; - -/*! - * ignore - */ - -ObjectId._checkRequired = v => v instanceof oid; - -/*! - * ignore - */ - -ObjectId._cast = castObjectId; - -/** - * Get/set the function used to cast arbitrary values to objectids. - * - * ####Example: - * - * // Make Mongoose only try to cast length 24 strings. By default, any 12 - * // char string is a valid ObjectId. - * const original = mongoose.ObjectId.cast(); - * mongoose.ObjectId.cast(v => { - * assert.ok(typeof v !== 'string' || v.length === 24); - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.ObjectId.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - -ObjectId.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => { - if (!(v instanceof oid)) { - throw new Error(v + ' is not an instance of ObjectId'); - } - return v; - }; - } - this._cast = caster; - - return this._cast; -}; - -/** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * ####Example: - * - * // Allow empty strings to pass `required` check - * mongoose.Schema.Types.String.checkRequired(v => v != null); - * - * const M = mongoose.model({ str: { type: String, required: true } }); - * new M({ str: '' }).validateSync(); // `null`, validation passes! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -ObjectId.checkRequired = SchemaType.checkRequired; - -/** - * Check if the given value satisfies a required validator. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - -ObjectId.prototype.checkRequired = function checkRequired(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - - // `require('util').inherits()` does **not** copy static properties, and - // plugins like mongoose-float use `inherits()` for pre-ES6. - const _checkRequired = typeof this.constructor.checkRequired == 'function' ? - this.constructor.checkRequired() : - ObjectId.checkRequired(); - - return _checkRequired(value); -}; - -/** - * Casts to ObjectId - * - * @param {Object} value - * @param {Object} doc - * @param {Boolean} init whether this is an initialization cast - * @api private - */ - -ObjectId.prototype.cast = function(value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (value === null || value === undefined) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (value instanceof oid) { - return value; - } else if ((value.constructor.name || '').toLowerCase() === 'objectid') { - return new oid(value.toHexString()); - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('ObjectId', value, this.path, null, this); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - const path = doc.$__fullPath(this.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - const pop = owner.populated(path, true); - let ret = value; - if (!doc.$__.populated || - !doc.$__.populated[path] || - !doc.$__.populated[path].options || - !doc.$__.populated[path].options.options || - !doc.$__.populated[path].options.options.lean) { - ret = new pop.options[populateModelSymbol](value); - ret.$__.wasPopulated = true; - } - - return ret; - } - - const castObjectId = typeof this.constructor.cast === 'function' ? - this.constructor.cast() : - ObjectId.cast(); - try { - return castObjectId(value); - } catch (error) { - throw new CastError('ObjectId', value, this.path, error, this); - } -}; - -/*! - * ignore - */ - -function handleSingle(val) { - return this.cast(val); -} - -ObjectId.prototype.$conditionalHandlers = - utils.options(SchemaType.prototype.$conditionalHandlers, { - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle - }); - -/*! - * ignore - */ - -function defaultId() { - return new oid(); -} - -defaultId.$runBeforeSetters = true; - -function resetId(v) { - Document || (Document = require('./../document')); - - if (this instanceof Document) { - if (v === void 0) { - const _v = new oid; - this.$__._id = _v; - return _v; - } - - this.$__._id = v; - } - - return v; -} - -/*! - * Module exports. - */ - -module.exports = ObjectId; diff --git a/node_modules/mongoose/lib/schema/operators/bitwise.js b/node_modules/mongoose/lib/schema/operators/bitwise.js deleted file mode 100644 index 07e18cd..0000000 --- a/node_modules/mongoose/lib/schema/operators/bitwise.js +++ /dev/null @@ -1,38 +0,0 @@ -/*! - * Module requirements. - */ - -'use strict'; - -const CastError = require('../../error/cast'); - -/*! - * ignore - */ - -function handleBitwiseOperator(val) { - const _this = this; - if (Array.isArray(val)) { - return val.map(function(v) { - return _castNumber(_this.path, v); - }); - } else if (Buffer.isBuffer(val)) { - return val; - } - // Assume trying to cast to number - return _castNumber(_this.path, val); -} - -/*! - * ignore - */ - -function _castNumber(path, num) { - const v = Number(num); - if (isNaN(v)) { - throw new CastError('number', num, path); - } - return v; -} - -module.exports = handleBitwiseOperator; diff --git a/node_modules/mongoose/lib/schema/operators/exists.js b/node_modules/mongoose/lib/schema/operators/exists.js deleted file mode 100644 index 916b4cb..0000000 --- a/node_modules/mongoose/lib/schema/operators/exists.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -const castBoolean = require('../../cast/boolean'); - -/*! - * ignore - */ - -module.exports = function(val) { - const path = this != null ? this.path : null; - return castBoolean(val, path); -}; diff --git a/node_modules/mongoose/lib/schema/operators/geospatial.js b/node_modules/mongoose/lib/schema/operators/geospatial.js deleted file mode 100644 index 73e38f8..0000000 --- a/node_modules/mongoose/lib/schema/operators/geospatial.js +++ /dev/null @@ -1,102 +0,0 @@ -/*! - * Module requirements. - */ - -'use strict'; - -const castArraysOfNumbers = require('./helpers').castArraysOfNumbers; -const castToNumber = require('./helpers').castToNumber; - -/*! - * ignore - */ - -exports.cast$geoIntersects = cast$geoIntersects; -exports.cast$near = cast$near; -exports.cast$within = cast$within; - -function cast$near(val) { - const SchemaArray = require('../array'); - - if (Array.isArray(val)) { - castArraysOfNumbers(val, this); - return val; - } - - _castMinMaxDistance(this, val); - - if (val && val.$geometry) { - return cast$geometry(val, this); - } - - return SchemaArray.prototype.castForQuery.call(this, val); -} - -function cast$geometry(val, self) { - switch (val.$geometry.type) { - case 'Polygon': - case 'LineString': - case 'Point': - castArraysOfNumbers(val.$geometry.coordinates, self); - break; - default: - // ignore unknowns - break; - } - - _castMinMaxDistance(self, val); - - return val; -} - -function cast$within(val) { - _castMinMaxDistance(this, val); - - if (val.$box || val.$polygon) { - const type = val.$box ? '$box' : '$polygon'; - val[type].forEach(arr => { - if (!Array.isArray(arr)) { - const msg = 'Invalid $within $box argument. ' - + 'Expected an array, received ' + arr; - throw new TypeError(msg); - } - arr.forEach((v, i) => { - arr[i] = castToNumber.call(this, v); - }); - }); - } else if (val.$center || val.$centerSphere) { - const type = val.$center ? '$center' : '$centerSphere'; - val[type].forEach((item, i) => { - if (Array.isArray(item)) { - item.forEach((v, j) => { - item[j] = castToNumber.call(this, v); - }); - } else { - val[type][i] = castToNumber.call(this, item); - } - }); - } else if (val.$geometry) { - cast$geometry(val, this); - } - - return val; -} - -function cast$geoIntersects(val) { - const geo = val.$geometry; - if (!geo) { - return; - } - - cast$geometry(val, this); - return val; -} - -function _castMinMaxDistance(self, val) { - if (val.$maxDistance) { - val.$maxDistance = castToNumber.call(self, val.$maxDistance); - } - if (val.$minDistance) { - val.$minDistance = castToNumber.call(self, val.$minDistance); - } -} diff --git a/node_modules/mongoose/lib/schema/operators/helpers.js b/node_modules/mongoose/lib/schema/operators/helpers.js deleted file mode 100644 index a17951c..0000000 --- a/node_modules/mongoose/lib/schema/operators/helpers.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -/*! - * Module requirements. - */ - -const SchemaNumber = require('../number'); - -/*! - * @ignore - */ - -exports.castToNumber = castToNumber; -exports.castArraysOfNumbers = castArraysOfNumbers; - -/*! - * @ignore - */ - -function castToNumber(val) { - return SchemaNumber.cast()(val); -} - -function castArraysOfNumbers(arr, self) { - arr.forEach(function(v, i) { - if (Array.isArray(v)) { - castArraysOfNumbers(v, self); - } else { - arr[i] = castToNumber.call(self, v); - } - }); -} diff --git a/node_modules/mongoose/lib/schema/operators/text.js b/node_modules/mongoose/lib/schema/operators/text.js deleted file mode 100644 index 4b95916..0000000 --- a/node_modules/mongoose/lib/schema/operators/text.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const CastError = require('../../error/cast'); -const castBoolean = require('../../cast/boolean'); -const castString = require('../../cast/string'); - -/*! - * Casts val to an object suitable for `$text`. Throws an error if the object - * can't be casted. - * - * @param {Any} val value to cast - * @param {String} [path] path to associate with any errors that occured - * @return {Object} casted object - * @see https://docs.mongodb.com/manual/reference/operator/query/text/ - * @api private - */ - -module.exports = function(val, path) { - if (val == null || typeof val !== 'object') { - throw new CastError('$text', val, path); - } - - if (val.$search != null) { - val.$search = castString(val.$search, path + '.$search'); - } - if (val.$language != null) { - val.$language = castString(val.$language, path + '.$language'); - } - if (val.$caseSensitive != null) { - val.$caseSensitive = castBoolean(val.$caseSensitive, - path + '.$castSensitive'); - } - if (val.$diacriticSensitive != null) { - val.$diacriticSensitive = castBoolean(val.$diacriticSensitive, - path + '.$diacriticSensitive'); - } - - return val; -}; diff --git a/node_modules/mongoose/lib/schema/operators/type.js b/node_modules/mongoose/lib/schema/operators/type.js deleted file mode 100644 index c8e391a..0000000 --- a/node_modules/mongoose/lib/schema/operators/type.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -/*! - * ignore - */ - -module.exports = function(val) { - if (typeof val !== 'number' && typeof val !== 'string') { - throw new Error('$type parameter must be number or string'); - } - - return val; -}; diff --git a/node_modules/mongoose/lib/schema/string.js b/node_modules/mongoose/lib/schema/string.js deleted file mode 100644 index 68906da..0000000 --- a/node_modules/mongoose/lib/schema/string.js +++ /dev/null @@ -1,675 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const SchemaType = require('../schematype'); -const MongooseError = require('../error/index'); -const SchemaStringOptions = require('../options/SchemaStringOptions'); -const castString = require('../cast/string'); -const utils = require('../utils'); - -const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; - -const CastError = SchemaType.CastError; -let Document; - -/** - * String SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api public - */ - -function SchemaString(key, options) { - this.enumValues = []; - this.regExp = null; - SchemaType.call(this, key, options, 'String'); -} - -/** - * This schema type's name, to defend against minifiers that mangle - * function names. - * - * @api public - */ -SchemaString.schemaName = 'String'; - -SchemaString.defaultOptions = {}; - -/*! - * Inherits from SchemaType. - */ -SchemaString.prototype = Object.create(SchemaType.prototype); -SchemaString.prototype.constructor = SchemaString; -Object.defineProperty(SchemaString.prototype, 'OptionsConstructor', { - configurable: false, - enumerable: false, - writable: false, - value: SchemaStringOptions -}); - -/*! - * ignore - */ - -SchemaString._cast = castString; - -/** - * Get/set the function used to cast arbitrary values to strings. - * - * ####Example: - * - * // Throw an error if you pass in an object. Normally, Mongoose allows - * // objects with custom `toString()` functions. - * const original = mongoose.Schema.Types.String.cast(); - * mongoose.Schema.Types.String.cast(v => { - * assert.ok(v == null || typeof v !== 'object'); - * return original(v); - * }); - * - * // Or disable casting entirely - * mongoose.Schema.Types.String.cast(false); - * - * @param {Function} caster - * @return {Function} - * @function get - * @static - * @api public - */ - -SchemaString.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => { - if (v != null && typeof v !== 'string') { - throw new Error(); - } - return v; - }; - } - this._cast = caster; - - return this._cast; -}; - -/** - * Attaches a getter for all String instances. - * - * ####Example: - * - * // Make all numbers round down - * mongoose.Schema.String.get(v => v.toLowerCase()); - * - * const Model = mongoose.model('Test', new Schema({ test: String })); - * new Model({ test: 'FOO' }).test; // 'foo' - * - * @param {Function} getter - * @return {this} - * @function get - * @static - * @api public - */ - -SchemaString.get = SchemaType.get; - -/** - * Sets a default option for all String instances. - * - * ####Example: - * - * // Make all strings have option `trim` equal to true. - * mongoose.Schema.String.set('trim', true); - * - * const User = mongoose.model('User', new Schema({ name: String })); - * new User({ name: ' John Doe ' }).name; // 'John Doe' - * - * @param {String} option - The option you'd like to set the value for - * @param {*} value - value for option - * @return {undefined} - * @function set - * @static - * @api public - */ - -SchemaString.set = SchemaType.set; - -/*! - * ignore - */ - -SchemaString._checkRequired = v => (v instanceof String || typeof v === 'string') && v.length; - -/** - * Override the function the required validator uses to check whether a string - * passes the `required` check. - * - * ####Example: - * - * // Allow empty strings to pass `required` check - * mongoose.Schema.Types.String.checkRequired(v => v != null); - * - * const M = mongoose.model({ str: { type: String, required: true } }); - * new M({ str: '' }).validateSync(); // `null`, validation passes! - * - * @param {Function} fn - * @return {Function} - * @function checkRequired - * @static - * @api public - */ - -SchemaString.checkRequired = SchemaType.checkRequired; - -/** - * Adds an enum validator - * - * ####Example: - * - * var states = ['opening', 'open', 'closing', 'closed'] - * var s = new Schema({ state: { type: String, enum: states }}) - * var M = db.model('M', s) - * var m = new M({ state: 'invalid' }) - * m.save(function (err) { - * console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`. - * m.state = 'open' - * m.save(callback) // success - * }) - * - * // or with custom error messages - * var enum = { - * values: ['opening', 'open', 'closing', 'closed'], - * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`' - * } - * var s = new Schema({ state: { type: String, enum: enum }) - * var M = db.model('M', s) - * var m = new M({ state: 'invalid' }) - * m.save(function (err) { - * console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid` - * m.state = 'open' - * m.save(callback) // success - * }) - * - * @param {String|Object} [args...] enumeration values - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaString.prototype.enum = function() { - if (this.enumValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.enumValidator; - }, this); - this.enumValidator = false; - } - - if (arguments[0] === void 0 || arguments[0] === false) { - return this; - } - - let values; - let errorMessage; - - if (utils.isObject(arguments[0])) { - values = arguments[0].values; - errorMessage = arguments[0].message; - } else { - values = arguments; - errorMessage = MongooseError.messages.String.enum; - } - - for (const value of values) { - if (value !== undefined) { - this.enumValues.push(this.cast(value)); - } - } - - const vals = this.enumValues; - this.enumValidator = function(v) { - return undefined === v || ~vals.indexOf(v); - }; - this.validators.push({ - validator: this.enumValidator, - message: errorMessage, - type: 'enum', - enumValues: vals - }); - - return this; -}; - -/** - * Adds a lowercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). - * - * ####Example: - * - * var s = new Schema({ email: { type: String, lowercase: true }}) - * var M = db.model('M', s); - * var m = new M({ email: 'SomeEmail@example.COM' }); - * console.log(m.email) // someemail@example.com - * M.find({ email: 'SomeEmail@example.com' }); // Queries by 'someemail@example.com' - * - * Note that `lowercase` does **not** affect regular expression queries: - * - * ####Example: - * // Still queries for documents whose `email` matches the regular - * // expression /SomeEmail/. Mongoose does **not** convert the RegExp - * // to lowercase. - * M.find({ email: /SomeEmail/ }); - * - * @api public - * @return {SchemaType} this - */ - -SchemaString.prototype.lowercase = function(shouldApply) { - if (arguments.length > 0 && !shouldApply) { - return this; - } - return this.set(function(v, self) { - if (typeof v !== 'string') { - v = self.cast(v); - } - if (v) { - return v.toLowerCase(); - } - return v; - }); -}; - -/** - * Adds an uppercase [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). - * - * ####Example: - * - * var s = new Schema({ caps: { type: String, uppercase: true }}) - * var M = db.model('M', s); - * var m = new M({ caps: 'an example' }); - * console.log(m.caps) // AN EXAMPLE - * M.find({ caps: 'an example' }) // Matches documents where caps = 'AN EXAMPLE' - * - * Note that `uppercase` does **not** affect regular expression queries: - * - * ####Example: - * // Mongoose does **not** convert the RegExp to uppercase. - * M.find({ email: /an example/ }); - * - * @api public - * @return {SchemaType} this - */ - -SchemaString.prototype.uppercase = function(shouldApply) { - if (arguments.length > 0 && !shouldApply) { - return this; - } - return this.set(function(v, self) { - if (typeof v !== 'string') { - v = self.cast(v); - } - if (v) { - return v.toUpperCase(); - } - return v; - }); -}; - -/** - * Adds a trim [setter](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set). - * - * The string value will be trimmed when set. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, trim: true }}); - * var M = db.model('M', s); - * var string = ' some name '; - * console.log(string.length); // 11 - * var m = new M({ name: string }); - * console.log(m.name.length); // 9 - * - * // Equivalent to `findOne({ name: string.trim() })` - * M.findOne({ name: string }); - * - * Note that `trim` does **not** affect regular expression queries: - * - * ####Example: - * // Mongoose does **not** trim whitespace from the RegExp. - * M.find({ name: / some name / }); - * - * @api public - * @return {SchemaType} this - */ - -SchemaString.prototype.trim = function(shouldTrim) { - if (arguments.length > 0 && !shouldTrim) { - return this; - } - return this.set(function(v, self) { - if (typeof v !== 'string') { - v = self.cast(v); - } - if (v) { - return v.trim(); - } - return v; - }); -}; - -/** - * Sets a minimum length validator. - * - * ####Example: - * - * var schema = new Schema({ postalCode: { type: String, minlength: 5 }) - * var Address = db.model('Address', schema) - * var address = new Address({ postalCode: '9512' }) - * address.save(function (err) { - * console.error(err) // validator error - * address.postalCode = '95125'; - * address.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length - * var minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).']; - * var schema = new Schema({ postalCode: { type: String, minlength: minlength }) - * var Address = mongoose.model('Address', schema); - * var address = new Address({ postalCode: '9512' }); - * address.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5). - * }) - * - * @param {Number} value minimum string length - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaString.prototype.minlength = function(value, message) { - if (this.minlengthValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.minlengthValidator; - }, this); - } - - if (value !== null && value !== undefined) { - let msg = message || MongooseError.messages.String.minlength; - msg = msg.replace(/{MINLENGTH}/, value); - this.validators.push({ - validator: this.minlengthValidator = function(v) { - return v === null || v.length >= value; - }, - message: msg, - type: 'minlength', - minlength: value - }); - } - - return this; -}; - -/** - * Sets a maximum length validator. - * - * ####Example: - * - * var schema = new Schema({ postalCode: { type: String, maxlength: 9 }) - * var Address = db.model('Address', schema) - * var address = new Address({ postalCode: '9512512345' }) - * address.save(function (err) { - * console.error(err) // validator error - * address.postalCode = '95125'; - * address.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length - * var maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).']; - * var schema = new Schema({ postalCode: { type: String, maxlength: maxlength }) - * var Address = mongoose.model('Address', schema); - * var address = new Address({ postalCode: '9512512345' }); - * address.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9). - * }) - * - * @param {Number} value maximum string length - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaString.prototype.maxlength = function(value, message) { - if (this.maxlengthValidator) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.maxlengthValidator; - }, this); - } - - if (value !== null && value !== undefined) { - let msg = message || MongooseError.messages.String.maxlength; - msg = msg.replace(/{MAXLENGTH}/, value); - this.validators.push({ - validator: this.maxlengthValidator = function(v) { - return v === null || v.length <= value; - }, - message: msg, - type: 'maxlength', - maxlength: value - }); - } - - return this; -}; - -/** - * Sets a regexp validator. - * - * Any value that does not pass `regExp`.test(val) will fail validation. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, match: /^a/ }}) - * var M = db.model('M', s) - * var m = new M({ name: 'I am invalid' }) - * m.validate(function (err) { - * console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)." - * m.name = 'apples' - * m.validate(function (err) { - * assert.ok(err) // success - * }) - * }) - * - * // using a custom error message - * var match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ]; - * var s = new Schema({ file: { type: String, match: match }}) - * var M = db.model('M', s); - * var m = new M({ file: 'invalid' }); - * m.validate(function (err) { - * console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)" - * }) - * - * Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also. - * - * var s = new Schema({ name: { type: String, match: /^a/, required: true }}) - * - * @param {RegExp} regExp regular expression to test against - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaString.prototype.match = function match(regExp, message) { - // yes, we allow multiple match validators - - const msg = message || MongooseError.messages.String.match; - - const matchValidator = function(v) { - if (!regExp) { - return false; - } - - const ret = ((v != null && v !== '') - ? regExp.test(v) - : true); - return ret; - }; - - this.validators.push({ - validator: matchValidator, - message: msg, - type: 'regexp', - regexp: regExp - }); - return this; -}; - -/** - * Check if the given value satisfies the `required` validator. The value is - * considered valid if it is a string (that is, not `null` or `undefined`) and - * has positive length. The `required` validator **will** fail for empty - * strings. - * - * @param {Any} value - * @param {Document} doc - * @return {Boolean} - * @api public - */ - -SchemaString.prototype.checkRequired = function checkRequired(value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return !!value; - } - - // `require('util').inherits()` does **not** copy static properties, and - // plugins like mongoose-float use `inherits()` for pre-ES6. - const _checkRequired = typeof this.constructor.checkRequired == 'function' ? - this.constructor.checkRequired() : - SchemaString.checkRequired(); - - return _checkRequired(value); -}; - -/** - * Casts to String - * - * @api private - */ - -SchemaString.prototype.cast = function(value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (value === null || value === undefined) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (typeof value === 'string') { - return value; - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('string', value, this.path, null, this); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - const path = doc.$__fullPath(this.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - const pop = owner.populated(path, true); - const ret = new pop.options[populateModelSymbol](value); - ret.$__.wasPopulated = true; - return ret; - } - - const castString = typeof this.constructor.cast === 'function' ? - this.constructor.cast() : - SchemaString.cast(); - try { - return castString(value); - } catch (error) { - throw new CastError('string', value, this.path, null, this); - } -}; - -/*! - * ignore - */ - -function handleSingle(val) { - return this.castForQuery(val); -} - -function handleArray(val) { - const _this = this; - if (!Array.isArray(val)) { - return [this.castForQuery(val)]; - } - return val.map(function(m) { - return _this.castForQuery(m); - }); -} - -const $conditionalHandlers = utils.options(SchemaType.prototype.$conditionalHandlers, { - $all: handleArray, - $gt: handleSingle, - $gte: handleSingle, - $lt: handleSingle, - $lte: handleSingle, - $options: String, - $regex: handleSingle, - $not: handleSingle -}); - -Object.defineProperty(SchemaString.prototype, '$conditionalHandlers', { - configurable: false, - enumerable: false, - writable: false, - value: Object.freeze($conditionalHandlers) -}); - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [val] - * @api private - */ - -SchemaString.prototype.castForQuery = function($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new Error('Can\'t use ' + $conditional + ' with String.'); - } - return handler.call(this, val); - } - val = $conditional; - if (Object.prototype.toString.call(val) === '[object RegExp]') { - return val; - } - - return this._castForQuery(val); -}; - -/*! - * Module exports. - */ - -module.exports = SchemaString; diff --git a/node_modules/mongoose/lib/schema/symbols.js b/node_modules/mongoose/lib/schema/symbols.js deleted file mode 100644 index 08d1d27..0000000 --- a/node_modules/mongoose/lib/schema/symbols.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -exports.schemaMixedSymbol = Symbol.for('mongoose:schema_mixed'); - -exports.builtInMiddleware = Symbol.for('mongoose:built-in-middleware'); \ No newline at end of file diff --git a/node_modules/mongoose/lib/schematype.js b/node_modules/mongoose/lib/schematype.js deleted file mode 100644 index 9cb62ca..0000000 --- a/node_modules/mongoose/lib/schematype.js +++ /dev/null @@ -1,1530 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const MongooseError = require('./error/index'); -const SchemaTypeOptions = require('./options/SchemaTypeOptions'); -const $exists = require('./schema/operators/exists'); -const $type = require('./schema/operators/type'); -const get = require('./helpers/get'); -const handleImmutable = require('./helpers/schematype/handleImmutable'); -const immediate = require('./helpers/immediate'); -const schemaTypeSymbol = require('./helpers/symbols').schemaTypeSymbol; -const util = require('util'); -const utils = require('./utils'); -const validatorErrorSymbol = require('./helpers/symbols').validatorErrorSymbol; - -const CastError = MongooseError.CastError; -const ValidatorError = MongooseError.ValidatorError; - -/** - * SchemaType constructor. Do **not** instantiate `SchemaType` directly. - * Mongoose converts your schema paths into SchemaTypes automatically. - * - * ####Example: - * - * const schema = new Schema({ name: String }); - * schema.path('name') instanceof SchemaType; // true - * - * @param {String} path - * @param {SchemaTypeOptions} [options] See [SchemaTypeOptions docs](/docs/api/schematypeoptions.html) - * @param {String} [instance] - * @api public - */ - -function SchemaType(path, options, instance) { - this[schemaTypeSymbol] = true; - this.path = path; - this.instance = instance; - this.validators = []; - this.getters = this.constructor.hasOwnProperty('getters') ? - this.constructor.getters.slice() : - []; - this.setters = []; - - options = options || {}; - const defaultOptions = this.constructor.defaultOptions || {}; - const defaultOptionsKeys = Object.keys(defaultOptions); - - for (const option of defaultOptionsKeys) { - if (defaultOptions.hasOwnProperty(option) && !options.hasOwnProperty(option)) { - options[option] = defaultOptions[option]; - } - } - - - if (options.select == null) { - delete options.select; - } - - const Options = this.OptionsConstructor || SchemaTypeOptions; - this.options = new Options(options); - this._index = null; - - - if (utils.hasUserDefinedProperty(this.options, 'immutable')) { - this.$immutable = this.options.immutable; - - handleImmutable(this); - } - - const keys = Object.keys(this.options); - for (const prop of keys) { - if (prop === 'cast') { - continue; - } - if (utils.hasUserDefinedProperty(this.options, prop) && typeof this[prop] === 'function') { - // { unique: true, index: true } - if (prop === 'index' && this._index) { - if (options.index === false) { - const index = this._index; - if (typeof index === 'object' && index != null) { - if (index.unique) { - throw new Error('Path "' + this.path + '" may not have `index` ' + - 'set to false and `unique` set to true'); - } - if (index.sparse) { - throw new Error('Path "' + this.path + '" may not have `index` ' + - 'set to false and `sparse` set to true'); - } - } - - this._index = false; - } - continue; - } - - const val = options[prop]; - // Special case so we don't screw up array defaults, see gh-5780 - if (prop === 'default') { - this.default(val); - continue; - } - - const opts = Array.isArray(val) ? val : [val]; - - this[prop].apply(this, opts); - } - } - - Object.defineProperty(this, '$$context', { - enumerable: false, - configurable: false, - writable: true, - value: null - }); -} - -/*! - * ignore - */ - -SchemaType.prototype.OptionsConstructor = SchemaTypeOptions; - -/** - * Get/set the function used to cast arbitrary values to this type. - * - * ####Example: - * - * // Disallow `null` for numbers, and don't try to cast any values to - * // numbers, so even strings like '123' will cause a CastError. - * mongoose.Number.cast(function(v) { - * assert.ok(v === undefined || typeof v === 'number'); - * return v; - * }); - * - * @param {Function|false} caster Function that casts arbitrary values to this type, or throws an error if casting failed - * @return {Function} - * @static - * @receiver SchemaType - * @function cast - * @api public - */ - -SchemaType.cast = function cast(caster) { - if (arguments.length === 0) { - return this._cast; - } - if (caster === false) { - caster = v => v; - } - this._cast = caster; - - return this._cast; -}; - -/** - * Sets a default option for this schema type. - * - * ####Example: - * - * // Make all strings be trimmed by default - * mongoose.SchemaTypes.String.set('trim', true); - * - * @param {String} option The name of the option you'd like to set (e.g. trim, lowercase, etc...) - * @param {*} value The value of the option you'd like to set. - * @return {void} - * @static - * @receiver SchemaType - * @function set - * @api public - */ - -SchemaType.set = function set(option, value) { - if (!this.hasOwnProperty('defaultOptions')) { - this.defaultOptions = Object.assign({}, this.defaultOptions); - } - this.defaultOptions[option] = value; -}; - -/** - * Attaches a getter for all instances of this schema type. - * - * ####Example: - * - * // Make all numbers round down - * mongoose.Number.get(function(v) { return Math.floor(v); }); - * - * @param {Function} getter - * @return {this} - * @static - * @receiver SchemaType - * @function get - * @api public - */ - -SchemaType.get = function(getter) { - this.getters = this.hasOwnProperty('getters') ? this.getters : []; - this.getters.push(getter); -}; - -/** - * Sets a default value for this SchemaType. - * - * ####Example: - * - * var schema = new Schema({ n: { type: Number, default: 10 }) - * var M = db.model('M', schema) - * var m = new M; - * console.log(m.n) // 10 - * - * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation. - * - * ####Example: - * - * // values are cast: - * var schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }}) - * var M = db.model('M', schema) - * var m = new M; - * console.log(m.aNumber) // 4.815162342 - * - * // default unique objects for Mixed types: - * var schema = new Schema({ mixed: Schema.Types.Mixed }); - * schema.path('mixed').default(function () { - * return {}; - * }); - * - * // if we don't use a function to return object literals for Mixed defaults, - * // each document will receive a reference to the same object literal creating - * // a "shared" object instance: - * var schema = new Schema({ mixed: Schema.Types.Mixed }); - * schema.path('mixed').default({}); - * var M = db.model('M', schema); - * var m1 = new M; - * m1.mixed.added = 1; - * console.log(m1.mixed); // { added: 1 } - * var m2 = new M; - * console.log(m2.mixed); // { added: 1 } - * - * @param {Function|any} val the default value - * @return {defaultValue} - * @api public - */ - -SchemaType.prototype.default = function(val) { - if (arguments.length === 1) { - if (val === void 0) { - this.defaultValue = void 0; - return void 0; - } - - if (val != null && val.instanceOfSchema) { - throw new MongooseError('Cannot set default value of path `' + this.path + - '` to a mongoose Schema instance.'); - } - - this.defaultValue = val; - return this.defaultValue; - } else if (arguments.length > 1) { - this.defaultValue = utils.args(arguments); - } - return this.defaultValue; -}; - -/** - * Declares the index options for this schematype. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, index: true }) - * var s = new Schema({ loc: { type: [Number], index: 'hashed' }) - * var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true }) - * var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }}) - * var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }}) - * s.path('my.path').index(true); - * s.path('my.date').index({ expires: 60 }); - * s.path('my.path').index({ unique: true, sparse: true }); - * - * ####NOTE: - * - * _Indexes are created [in the background](https://docs.mongodb.com/manual/core/index-creation/#index-creation-background) - * by default. If `background` is set to `false`, MongoDB will not execute any - * read/write operations you send until the index build. - * Specify `background: false` to override Mongoose's default._ - * - * @param {Object|Boolean|String} options - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.index = function(options) { - this._index = options; - utils.expires(this._index); - return this; -}; - -/** - * Declares an unique index. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, unique: true }}); - * s.path('name').index({ unique: true }); - * - * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._ - * - * @param {Boolean} bool - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.unique = function(bool) { - if (this._index === false) { - if (!bool) { - return; - } - throw new Error('Path "' + this.path + '" may not have `index` set to ' + - 'false and `unique` set to true'); - } - if (this._index == null || this._index === true) { - this._index = {}; - } else if (typeof this._index === 'string') { - this._index = { type: this._index }; - } - - this._index.unique = bool; - return this; -}; - -/** - * Declares a full text index. - * - * ###Example: - * - * var s = new Schema({name : {type: String, text : true }) - * s.path('name').index({text : true}); - * @param {Boolean} bool - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.text = function(bool) { - if (this._index === false) { - if (!bool) { - return; - } - throw new Error('Path "' + this.path + '" may not have `index` set to ' + - 'false and `text` set to true'); - } - - if (this._index === null || this._index === undefined || - typeof this._index === 'boolean') { - this._index = {}; - } else if (typeof this._index === 'string') { - this._index = { type: this._index }; - } - - this._index.text = bool; - return this; -}; - -/** - * Declares a sparse index. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, sparse: true } }); - * s.path('name').index({ sparse: true }); - * - * @param {Boolean} bool - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.sparse = function(bool) { - if (this._index === false) { - if (!bool) { - return; - } - throw new Error('Path "' + this.path + '" may not have `index` set to ' + - 'false and `sparse` set to true'); - } - - if (this._index == null || typeof this._index === 'boolean') { - this._index = {}; - } else if (typeof this._index === 'string') { - this._index = { type: this._index }; - } - - this._index.sparse = bool; - return this; -}; - -/** - * Defines this path as immutable. Mongoose prevents you from changing - * immutable paths unless the parent document has [`isNew: true`](/docs/api.html#document_Document-isNew). - * - * ####Example: - * - * const schema = new Schema({ - * name: { type: String, immutable: true }, - * age: Number - * }); - * const Model = mongoose.model('Test', schema); - * - * await Model.create({ name: 'test' }); - * const doc = await Model.findOne(); - * - * doc.isNew; // false - * doc.name = 'new name'; - * doc.name; // 'test', because `name` is immutable - * - * Mongoose also prevents changing immutable properties using `updateOne()` - * and `updateMany()` based on [strict mode](/docs/guide.html#strict). - * - * ####Example: - * - * // Mongoose will strip out the `name` update, because `name` is immutable - * Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } }); - * - * // If `strict` is set to 'throw', Mongoose will throw an error if you - * // update `name` - * const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }). - * then(() => null, err => err); - * err.name; // StrictModeError - * - * // If `strict` is `false`, Mongoose allows updating `name` even though - * // the property is immutable. - * Model.updateOne({}, { name: 'test2' }, { strict: false }); - * - * @param {Boolean} bool - * @return {SchemaType} this - * @see isNew /docs/api.html#document_Document-isNew - * @api public - */ - -SchemaType.prototype.immutable = function(bool) { - this.$immutable = bool; - handleImmutable(this); - - return this; -}; - -/** - * Adds a setter to this schematype. - * - * ####Example: - * - * function capitalize (val) { - * if (typeof val !== 'string') val = ''; - * return val.charAt(0).toUpperCase() + val.substring(1); - * } - * - * // defining within the schema - * var s = new Schema({ name: { type: String, set: capitalize }}); - * - * // or with the SchemaType - * var s = new Schema({ name: String }) - * s.path('name').set(capitalize); - * - * Setters allow you to transform the data before it gets to the raw mongodb - * document or query. - * - * Suppose you are implementing user registration for a website. Users provide - * an email and password, which gets saved to mongodb. The email is a string - * that you will want to normalize to lower case, in order to avoid one email - * having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM. - * - * You can set up email lower case normalization easily via a Mongoose setter. - * - * function toLower(v) { - * return v.toLowerCase(); - * } - * - * var UserSchema = new Schema({ - * email: { type: String, set: toLower } - * }); - * - * var User = db.model('User', UserSchema); - * - * var user = new User({email: 'AVENUE@Q.COM'}); - * console.log(user.email); // 'avenue@q.com' - * - * // or - * var user = new User(); - * user.email = 'Avenue@Q.com'; - * console.log(user.email); // 'avenue@q.com' - * User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com' - * - * As you can see above, setters allow you to transform the data before it - * stored in MongoDB, or before executing a query. - * - * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._ - * - * new Schema({ email: { type: String, lowercase: true }}) - * - * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema. - * - * function inspector (val, schematype) { - * if (schematype.options.required) { - * return schematype.path + ' is required'; - * } else { - * return val; - * } - * } - * - * var VirusSchema = new Schema({ - * name: { type: String, required: true, set: inspector }, - * taxonomy: { type: String, set: inspector } - * }) - * - * var Virus = db.model('Virus', VirusSchema); - * var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' }); - * - * console.log(v.name); // name is required - * console.log(v.taxonomy); // Parvovirinae - * - * You can also use setters to modify other properties on the document. If - * you're setting a property `name` on a document, the setter will run with - * `this` as the document. Be careful, in mongoose 5 setters will also run - * when querying by `name` with `this` as the query. - * - * ```javascript - * const nameSchema = new Schema({ name: String, keywords: [String] }); - * nameSchema.path('name').set(function(v) { - * // Need to check if `this` is a document, because in mongoose 5 - * // setters will also run on queries, in which case `this` will be a - * // mongoose query object. - * if (this instanceof Document && v != null) { - * this.keywords = v.split(' '); - * } - * return v; - * }); - * ``` - * - * @param {Function} fn - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.set = function(fn) { - if (typeof fn !== 'function') { - throw new TypeError('A setter must be a function.'); - } - this.setters.push(fn); - return this; -}; - -/** - * Adds a getter to this schematype. - * - * ####Example: - * - * function dob (val) { - * if (!val) return val; - * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear(); - * } - * - * // defining within the schema - * var s = new Schema({ born: { type: Date, get: dob }) - * - * // or by retreiving its SchemaType - * var s = new Schema({ born: Date }) - * s.path('born').get(dob) - * - * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see. - * - * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way: - * - * function obfuscate (cc) { - * return '****-****-****-' + cc.slice(cc.length-4, cc.length); - * } - * - * var AccountSchema = new Schema({ - * creditCardNumber: { type: String, get: obfuscate } - * }); - * - * var Account = db.model('Account', AccountSchema); - * - * Account.findById(id, function (err, found) { - * console.log(found.creditCardNumber); // '****-****-****-1234' - * }); - * - * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema. - * - * function inspector (val, schematype) { - * if (schematype.options.required) { - * return schematype.path + ' is required'; - * } else { - * return schematype.path + ' is not'; - * } - * } - * - * var VirusSchema = new Schema({ - * name: { type: String, required: true, get: inspector }, - * taxonomy: { type: String, get: inspector } - * }) - * - * var Virus = db.model('Virus', VirusSchema); - * - * Virus.findById(id, function (err, virus) { - * console.log(virus.name); // name is required - * console.log(virus.taxonomy); // taxonomy is not - * }) - * - * @param {Function} fn - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.get = function(fn) { - if (typeof fn !== 'function') { - throw new TypeError('A getter must be a function.'); - } - this.getters.push(fn); - return this; -}; - -/** - * Adds validator(s) for this document path. - * - * Validators always receive the value to validate as their first argument and - * must return `Boolean`. Returning `false` or throwing an error means - * validation failed. - * - * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used. - * - * ####Examples: - * - * // make sure every value is equal to "something" - * function validator (val) { - * return val == 'something'; - * } - * new Schema({ name: { type: String, validate: validator }}); - * - * // with a custom error message - * - * var custom = [validator, 'Uh oh, {PATH} does not equal "something".'] - * new Schema({ name: { type: String, validate: custom }}); - * - * // adding many validators at a time - * - * var many = [ - * { validator: validator, msg: 'uh oh' } - * , { validator: anotherValidator, msg: 'failed' } - * ] - * new Schema({ name: { type: String, validate: many }}); - * - * // or utilizing SchemaType methods directly: - * - * var schema = new Schema({ name: 'string' }); - * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`'); - * - * ####Error message templates: - * - * From the examples above, you may have noticed that error messages support - * basic templating. There are a few other template keywords besides `{PATH}` - * and `{VALUE}` too. To find out more, details are available - * [here](#error_messages_MongooseError.messages). - * - * If Mongoose's built-in error message templating isn't enough, Mongoose - * supports setting the `message` property to a function. - * - * schema.path('name').validate({ - * validator: function() { return v.length > 5; }, - * // `errors['name']` will be "name must have length 5, got 'foo'" - * message: function(props) { - * return `${props.path} must have length 5, got '${props.value}'`; - * } - * }); - * - * To bypass Mongoose's error messages and just copy the error message that - * the validator throws, do this: - * - * schema.path('name').validate({ - * validator: function() { throw new Error('Oops!'); }, - * // `errors['name']` will be "Oops!" - * message: function(props) { return props.reason.message; } - * }); - * - * ####Asynchronous validation: - * - * Mongoose supports validators that return a promise. A validator that returns - * a promise is called an _async validator_. Async validators run in - * parallel, and `validate()` will wait until all async validators have settled. - * - * schema.path('name').validate({ - * validator: function (value) { - * return new Promise(function (resolve, reject) { - * resolve(false); // validation failed - * }); - * } - * }); - * - * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs. - * - * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate). - * - * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along. - * - * var conn = mongoose.createConnection(..); - * conn.on('error', handleError); - * - * var Product = conn.model('Product', yourSchema); - * var dvd = new Product(..); - * dvd.save(); // emits error on the `conn` above - * - * If you want to handle these errors at the Model level, add an `error` - * listener to your Model as shown below. - * - * // registering an error listener on the Model lets us handle errors more locally - * Product.on('error', handleError); - * - * @param {RegExp|Function|Object} obj validator function, or hash describing options - * @param {Function} [obj.validator] validator function. If the validator function returns `undefined` or a truthy value, validation succeeds. If it returns [falsy](https://masteringjs.io/tutorials/fundamentals/falsy) (except `undefined`) or throws an error, validation fails. - * @param {String|Function} [obj.message] optional error message. If function, should return the error message as a string - * @param {Boolean} [obj.propsParameter=false] If true, Mongoose will pass the validator properties object (with the `validator` function, `message`, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators [rely on positional args](https://github.com/chriso/validator.js#validators), so turning this on may cause unpredictable behavior in external validators. - * @param {String|Function} [errorMsg] optional error message. If function, should return the error message as a string - * @param {String} [type] optional validator type - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.validate = function(obj, message, type) { - if (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') { - let properties; - if (typeof message === 'function') { - properties = { validator: obj, message: message }; - properties.type = type || 'user defined'; - } else if (message instanceof Object && !type) { - properties = utils.clone(message); - if (!properties.message) { - properties.message = properties.msg; - } - properties.validator = obj; - properties.type = properties.type || 'user defined'; - } else { - if (message == null) { - message = MongooseError.messages.general.default; - } - if (!type) { - type = 'user defined'; - } - properties = { message: message, type: type, validator: obj }; - } - - if (properties.isAsync) { - handleIsAsync(); - } - - this.validators.push(properties); - return this; - } - - let i; - let length; - let arg; - - for (i = 0, length = arguments.length; i < length; i++) { - arg = arguments[i]; - if (!utils.isPOJO(arg)) { - const msg = 'Invalid validator. Received (' + typeof arg + ') ' - + arg - + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate'; - - throw new Error(msg); - } - this.validate(arg.validator, arg); - } - - return this; -}; - -/*! - * ignore - */ - -const handleIsAsync = util.deprecate(function handleIsAsync() {}, - 'Mongoose: the `isAsync` option for custom validators is deprecated. Make ' + - 'your async validators return a promise instead: ' + - 'https://mongoosejs.com/docs/validation.html#async-custom-validators'); - -/** - * Adds a required validator to this SchemaType. The validator gets added - * to the front of this SchemaType's validators array using `unshift()`. - * - * ####Example: - * - * var s = new Schema({ born: { type: Date, required: true }) - * - * // or with custom error message - * - * var s = new Schema({ born: { type: Date, required: '{PATH} is required!' }) - * - * // or with a function - * - * var s = new Schema({ - * userId: ObjectId, - * username: { - * type: String, - * required: function() { return this.userId != null; } - * } - * }) - * - * // or with a function and a custom message - * var s = new Schema({ - * userId: ObjectId, - * username: { - * type: String, - * required: [ - * function() { return this.userId != null; }, - * 'username is required if id is specified' - * ] - * } - * }) - * - * // or through the path API - * - * s.path('name').required(true); - * - * // with custom error messaging - * - * s.path('name').required(true, 'grrr :( '); - * - * // or make a path conditionally required based on a function - * var isOver18 = function() { return this.age >= 18; }; - * s.path('voterRegistrationId').required(isOver18); - * - * The required validator uses the SchemaType's `checkRequired` function to - * determine whether a given value satisfies the required validator. By default, - * a value satisfies the required validator if `val != null` (that is, if - * the value is not null nor undefined). However, most built-in mongoose schema - * types override the default `checkRequired` function: - * - * @param {Boolean|Function|Object} required enable/disable the validator, or function that returns required boolean, or options object - * @param {Boolean|Function} [options.isRequired] enable/disable the validator, or function that returns required boolean - * @param {Function} [options.ErrorConstructor] custom error constructor. The constructor receives 1 parameter, an object containing the validator properties. - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @see SchemaArray#checkRequired #schema_array_SchemaArray.checkRequired - * @see SchemaBoolean#checkRequired #schema_boolean_SchemaBoolean-checkRequired - * @see SchemaBuffer#checkRequired #schema_buffer_SchemaBuffer.schemaName - * @see SchemaNumber#checkRequired #schema_number_SchemaNumber-min - * @see SchemaObjectId#checkRequired #schema_objectid_ObjectId-auto - * @see SchemaString#checkRequired #schema_string_SchemaString-checkRequired - * @api public - */ - -SchemaType.prototype.required = function(required, message) { - let customOptions = {}; - - if (arguments.length > 0 && required == null) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.requiredValidator; - }, this); - - this.isRequired = false; - delete this.originalRequiredValue; - return this; - } - - if (typeof required === 'object') { - customOptions = required; - message = customOptions.message || message; - required = required.isRequired; - } - - if (required === false) { - this.validators = this.validators.filter(function(v) { - return v.validator !== this.requiredValidator; - }, this); - - this.isRequired = false; - delete this.originalRequiredValue; - return this; - } - - const _this = this; - this.isRequired = true; - - this.requiredValidator = function(v) { - const cachedRequired = get(this, '$__.cachedRequired'); - - // no validation when this path wasn't selected in the query. - if (cachedRequired != null && !this.isSelected(_this.path) && !this.isModified(_this.path)) { - return true; - } - - // `$cachedRequired` gets set in `_evaluateRequiredFunctions()` so we - // don't call required functions multiple times in one validate call - // See gh-6801 - if (cachedRequired != null && _this.path in cachedRequired) { - const res = cachedRequired[_this.path] ? - _this.checkRequired(v, this) : - true; - delete cachedRequired[_this.path]; - return res; - } else if (typeof required === 'function') { - return required.apply(this) ? _this.checkRequired(v, this) : true; - } - - return _this.checkRequired(v, this); - }; - this.originalRequiredValue = required; - - if (typeof required === 'string') { - message = required; - required = undefined; - } - - const msg = message || MongooseError.messages.general.required; - this.validators.unshift(Object.assign({}, customOptions, { - validator: this.requiredValidator, - message: msg, - type: 'required' - })); - - return this; -}; - -/** - * Set the model that this path refers to. This is the option that [populate](https://mongoosejs.com/docs/populate.html) - * looks at to determine the foreign collection it should query. - * - * ####Example: - * const userSchema = new Schema({ name: String }); - * const User = mongoose.model('User', userSchema); - * - * const postSchema = new Schema({ user: mongoose.ObjectId }); - * postSchema.path('user').ref('User'); // By model name - * postSchema.path('user').ref(User); // Can pass the model as well - * - * // Or you can just declare the `ref` inline in your schema - * const postSchema2 = new Schema({ - * user: { type: mongoose.ObjectId, ref: User } - * }); - * - * @param {String|Model|Function} ref either a model name, a [Model](https://mongoosejs.com/docs/models.html), or a function that returns a model name or model. - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.ref = function(ref) { - this.options.ref = ref; - return this; -}; - -/** - * Gets the default value - * - * @param {Object} scope the scope which callback are executed - * @param {Boolean} init - * @api private - */ - -SchemaType.prototype.getDefault = function(scope, init) { - let ret = typeof this.defaultValue === 'function' - ? this.defaultValue.call(scope) - : this.defaultValue; - - if (ret !== null && ret !== undefined) { - if (typeof ret === 'object' && (!this.options || !this.options.shared)) { - ret = utils.clone(ret); - } - - const casted = this.applySetters(ret, scope, init); - if (casted && casted.$isSingleNested) { - casted.$parent = scope; - } - return casted; - } - return ret; -}; - -/*! - * Applies setters without casting - * - * @api private - */ - -SchemaType.prototype._applySetters = function(value, scope, init, priorVal) { - let v = value; - const setters = this.setters; - const caster = this.caster; - - for (const setter of utils.clone(setters).reverse()) { - v = setter.call(scope, v, this); - } - - if (Array.isArray(v) && caster && caster.setters) { - const newVal = []; - - for (let i = 0; i < v.length; ++i) { - const value = v[i]; - try { - newVal.push(caster.applySetters(value, scope, init, priorVal)); - } catch (err) { - if (err instanceof MongooseError.CastError) { - err.$originalErrorPath = err.path; - err.path = err.path + '.' + i; - } - throw err; - } - } - v = newVal; - } - - - return v; -}; - -/** - * Applies setters - * - * @param {Object} value - * @param {Object} scope - * @param {Boolean} init - * @api private - */ - -SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) { - let v = this._applySetters(value, scope, init, priorVal, options); - - if (v == null) { - return v; - } - - // do not cast until all setters are applied #665 - v = this.cast(v, scope, init, priorVal, options); - - return v; -}; - -/** - * Applies getters to a value - * - * @param {Object} value - * @param {Object} scope - * @api private - */ - -SchemaType.prototype.applyGetters = function(value, scope) { - let v = value; - const getters = this.getters; - const len = getters.length; - - if (len === 0) { - return v; - } - - for (let i = 0; i < len; ++i) { - v = getters[i].call(scope, v, this); - } - - return v; -}; - -/** - * Sets default `select()` behavior for this path. - * - * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level. - * - * ####Example: - * - * T = db.model('T', new Schema({ x: { type: String, select: true }})); - * T.find(..); // field x will always be selected .. - * // .. unless overridden; - * T.find().select('-x').exec(callback); - * - * @param {Boolean} val - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.select = function select(val) { - this.selected = !!val; - return this; -}; - -/** - * Performs a validation of `value` using the validators declared for this SchemaType. - * - * @param {any} value - * @param {Function} callback - * @param {Object} scope - * @api private - */ - -SchemaType.prototype.doValidate = function(value, fn, scope, options) { - let err = false; - const path = this.path; - - // Avoid non-object `validators` - const validators = this.validators. - filter(v => v != null && typeof v === 'object'); - - let count = validators.length; - - if (!count) { - return fn(null); - } - - const _this = this; - validators.forEach(function(v) { - if (err) { - return; - } - - const validator = v.validator; - let ok; - - const validatorProperties = utils.clone(v); - validatorProperties.path = options && options.path ? options.path : path; - validatorProperties.value = value; - - if (validator instanceof RegExp) { - validate(validator.test(value), validatorProperties); - return; - } - - if (typeof validator !== 'function') { - return; - } - - if (value === undefined && validator !== _this.requiredValidator) { - validate(true, validatorProperties); - return; - } - - if (validatorProperties.isAsync) { - asyncValidate(validator, scope, value, validatorProperties, validate); - return; - } - - try { - if (validatorProperties.propsParameter) { - ok = validator.call(scope, value, validatorProperties); - } else { - ok = validator.call(scope, value); - } - } catch (error) { - ok = false; - validatorProperties.reason = error; - if (error.message) { - validatorProperties.message = error.message; - } - } - - if (ok != null && typeof ok.then === 'function') { - ok.then( - function(ok) { validate(ok, validatorProperties); }, - function(error) { - validatorProperties.reason = error; - validatorProperties.message = error.message; - ok = false; - validate(ok, validatorProperties); - }); - } else { - validate(ok, validatorProperties); - } - - }); - - function validate(ok, validatorProperties) { - if (err) { - return; - } - if (ok === undefined || ok) { - if (--count <= 0) { - immediate(function() { - fn(null); - }); - } - } else { - const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; - err = new ErrorConstructor(validatorProperties); - err[validatorErrorSymbol] = true; - immediate(function() { - fn(err); - }); - } - } -}; - -/*! - * Handle async validators - */ - -function asyncValidate(validator, scope, value, props, cb) { - let called = false; - const returnVal = validator.call(scope, value, function(ok, customMsg) { - if (called) { - return; - } - called = true; - if (customMsg) { - props.message = customMsg; - } - cb(ok, props); - }); - if (typeof returnVal === 'boolean') { - called = true; - cb(returnVal, props); - } else if (returnVal && typeof returnVal.then === 'function') { - // Promise - returnVal.then( - function(ok) { - if (called) { - return; - } - called = true; - cb(ok, props); - }, - function(error) { - if (called) { - return; - } - called = true; - - props.reason = error; - props.message = error.message; - cb(false, props); - }); - } -} - -/** - * Performs a validation of `value` using the validators declared for this SchemaType. - * - * ####Note: - * - * This method ignores the asynchronous validators. - * - * @param {any} value - * @param {Object} scope - * @return {MongooseError|undefined} - * @api private - */ - -SchemaType.prototype.doValidateSync = function(value, scope, options) { - const path = this.path; - const count = this.validators.length; - - if (!count) { - return null; - } - - let validators = this.validators; - if (value === void 0) { - if (this.validators.length > 0 && this.validators[0].type === 'required') { - validators = [this.validators[0]]; - } else { - return null; - } - } - - let err = null; - validators.forEach(function(v) { - if (err) { - return; - } - - if (v == null || typeof v !== 'object') { - return; - } - - const validator = v.validator; - const validatorProperties = utils.clone(v); - validatorProperties.path = options && options.path ? options.path : path; - validatorProperties.value = value; - let ok; - - // Skip any explicit async validators. Validators that return a promise - // will still run, but won't trigger any errors. - if (validator.isAsync) { - return; - } - - if (validator instanceof RegExp) { - validate(validator.test(value), validatorProperties); - return; - } - - if (typeof validator !== 'function') { - return; - } - - try { - if (validatorProperties.propsParameter) { - ok = validator.call(scope, value, validatorProperties); - } else { - ok = validator.call(scope, value); - } - } catch (error) { - ok = false; - validatorProperties.reason = error; - } - - // Skip any validators that return a promise, we can't handle those - // synchronously - if (ok != null && typeof ok.then === 'function') { - return; - } - validate(ok, validatorProperties); - }); - - return err; - - function validate(ok, validatorProperties) { - if (err) { - return; - } - if (ok !== undefined && !ok) { - const ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError; - err = new ErrorConstructor(validatorProperties); - err[validatorErrorSymbol] = true; - } - } -}; - -/** - * Determines if value is a valid Reference. - * - * @param {SchemaType} self - * @param {Object} value - * @param {Document} doc - * @param {Boolean} init - * @return {Boolean} - * @api private - */ - -SchemaType._isRef = function(self, value, doc, init) { - // fast path - let ref = init && self.options && (self.options.ref || self.options.refPath); - - if (!ref && doc && doc.$__ != null) { - // checks for - // - this populated with adhoc model and no ref was set in schema OR - // - setting / pushing values after population - const path = doc.$__fullPath(self.path); - const owner = doc.ownerDocument ? doc.ownerDocument() : doc; - ref = owner.populated(path) || doc.populated(self.path); - } - - if (ref) { - if (value == null) { - return true; - } - if (!Buffer.isBuffer(value) && // buffers are objects too - value._bsontype !== 'Binary' // raw binary value from the db - && utils.isObject(value) // might have deselected _id in population query - ) { - return true; - } - } - - return false; -}; - -/*! - * ignore - */ - -function handleSingle(val) { - return this.castForQuery(val); -} - -/*! - * ignore - */ - -function handleArray(val) { - const _this = this; - if (!Array.isArray(val)) { - return [this.castForQuery(val)]; - } - return val.map(function(m) { - return _this.castForQuery(m); - }); -} - -/*! - * Just like handleArray, except also allows `[]` because surprisingly - * `$in: [1, []]` works fine - */ - -function handle$in(val) { - const _this = this; - if (!Array.isArray(val)) { - return [this.castForQuery(val)]; - } - return val.map(function(m) { - if (Array.isArray(m) && m.length === 0) { - return m; - } - return _this.castForQuery(m); - }); -} - -/*! - * ignore - */ - -SchemaType.prototype.$conditionalHandlers = { - $all: handleArray, - $eq: handleSingle, - $in: handle$in, - $ne: handleSingle, - $nin: handle$in, - $exists: $exists, - $type: $type -}; - -/*! - * Wraps `castForQuery` to handle context - */ - -SchemaType.prototype.castForQueryWrapper = function(params) { - this.$$context = params.context; - if ('$conditional' in params) { - return this.castForQuery(params.$conditional, params.val); - } - if (params.$skipQueryCastForUpdate || params.$applySetters) { - return this._castForQuery(params.val); - } - return this.castForQuery(params.val); -}; - -/** - * Cast the given value with the given optional query operator. - * - * @param {String} [$conditional] query operator, like `$eq` or `$in` - * @param {any} val - * @api private - */ - -SchemaType.prototype.castForQuery = function($conditional, val) { - let handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) { - throw new Error('Can\'t use ' + $conditional); - } - return handler.call(this, val); - } - val = $conditional; - return this._castForQuery(val); -}; - -/*! - * Internal switch for runSetters - * - * @api private - */ - -SchemaType.prototype._castForQuery = function(val) { - return this.applySetters(val, this.$$context); -}; - -/** - * Override the function the required validator uses to check whether a value - * passes the `required` check. Override this on the individual SchemaType. - * - * ####Example: - * - * // Use this to allow empty strings to pass the `required` validator - * mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string'); - * - * @param {Function} fn - * @return {Function} - * @static - * @receiver SchemaType - * @function checkRequired - * @api public - */ - -SchemaType.checkRequired = function(fn) { - if (arguments.length > 0) { - this._checkRequired = fn; - } - - return this._checkRequired; -}; - -/** - * Default check for if this path satisfies the `required` validator. - * - * @param {any} val - * @api private - */ - -SchemaType.prototype.checkRequired = function(val) { - return val != null; -}; - -/*! - * ignore - */ - -SchemaType.prototype.clone = function() { - const options = Object.assign({}, this.options); - const schematype = new this.constructor(this.path, options, this.instance); - schematype.validators = this.validators.slice(); - if (this.requiredValidator !== undefined) schematype.requiredValidator = this.requiredValidator; - if (this.defaultValue !== undefined) schematype.defaultValue = this.defaultValue; - if (this.$immutable !== undefined && this.options.immutable === undefined) { - schematype.$immutable = this.$immutable; - - handleImmutable(schematype); - } - if (this._index !== undefined) schematype._index = this._index; - if (this.selected !== undefined) schematype.selected = this.selected; - if (this.isRequired !== undefined) schematype.isRequired = this.isRequired; - if (this.originalRequiredValue !== undefined) schematype.originalRequiredValue = this.originalRequiredValue; - schematype.getters = this.getters.slice(); - schematype.setters = this.setters.slice(); - return schematype; -}; - -/*! - * Module exports. - */ - -module.exports = exports = SchemaType; - -exports.CastError = CastError; - -exports.ValidatorError = ValidatorError; diff --git a/node_modules/mongoose/lib/statemachine.js b/node_modules/mongoose/lib/statemachine.js deleted file mode 100644 index 7e36dc1..0000000 --- a/node_modules/mongoose/lib/statemachine.js +++ /dev/null @@ -1,180 +0,0 @@ - -/*! - * Module dependencies. - */ - -'use strict'; - -const utils = require('./utils'); - -/*! - * StateMachine represents a minimal `interface` for the - * constructors it builds via StateMachine.ctor(...). - * - * @api private - */ - -const StateMachine = module.exports = exports = function StateMachine() { -}; - -/*! - * StateMachine.ctor('state1', 'state2', ...) - * A factory method for subclassing StateMachine. - * The arguments are a list of states. For each state, - * the constructor's prototype gets state transition - * methods named after each state. These transition methods - * place their path argument into the given state. - * - * @param {String} state - * @param {String} [state] - * @return {Function} subclass constructor - * @private - */ - -StateMachine.ctor = function() { - const states = utils.args(arguments); - - const ctor = function() { - StateMachine.apply(this, arguments); - this.paths = {}; - this.states = {}; - this.stateNames = states; - - let i = states.length, - state; - - while (i--) { - state = states[i]; - this.states[state] = {}; - } - }; - - ctor.prototype = new StateMachine(); - - states.forEach(function(state) { - // Changes the `path`'s state to `state`. - ctor.prototype[state] = function(path) { - this._changeState(path, state); - }; - }); - - return ctor; -}; - -/*! - * This function is wrapped by the state change functions: - * - * - `require(path)` - * - `modify(path)` - * - `init(path)` - * - * @api private - */ - -StateMachine.prototype._changeState = function _changeState(path, nextState) { - const prevBucket = this.states[this.paths[path]]; - if (prevBucket) delete prevBucket[path]; - - this.paths[path] = nextState; - this.states[nextState][path] = true; -}; - -/*! - * ignore - */ - -StateMachine.prototype.clear = function clear(state) { - const keys = Object.keys(this.states[state]); - let i = keys.length; - let path; - - while (i--) { - path = keys[i]; - delete this.states[state][path]; - delete this.paths[path]; - } -}; - -/*! - * Checks to see if at least one path is in the states passed in via `arguments` - * e.g., this.some('required', 'inited') - * - * @param {String} state that we want to check for. - * @private - */ - -StateMachine.prototype.some = function some() { - const _this = this; - const what = arguments.length ? arguments : this.stateNames; - return Array.prototype.some.call(what, function(state) { - return Object.keys(_this.states[state]).length; - }); -}; - -/*! - * This function builds the functions that get assigned to `forEach` and `map`, - * since both of those methods share a lot of the same logic. - * - * @param {String} iterMethod is either 'forEach' or 'map' - * @return {Function} - * @api private - */ - -StateMachine.prototype._iter = function _iter(iterMethod) { - return function() { - const numArgs = arguments.length; - let states = utils.args(arguments, 0, numArgs - 1); - const callback = arguments[numArgs - 1]; - - if (!states.length) states = this.stateNames; - - const _this = this; - - const paths = states.reduce(function(paths, state) { - return paths.concat(Object.keys(_this.states[state])); - }, []); - - return paths[iterMethod](function(path, i, paths) { - return callback(path, i, paths); - }); - }; -}; - -/*! - * Iterates over the paths that belong to one of the parameter states. - * - * The function profile can look like: - * this.forEach(state1, fn); // iterates over all paths in state1 - * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 - * this.forEach(fn); // iterates over all paths in all states - * - * @param {String} [state] - * @param {String} [state] - * @param {Function} callback - * @private - */ - -StateMachine.prototype.forEach = function forEach() { - this.forEach = this._iter('forEach'); - return this.forEach.apply(this, arguments); -}; - -/*! - * Maps over the paths that belong to one of the parameter states. - * - * The function profile can look like: - * this.forEach(state1, fn); // iterates over all paths in state1 - * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 - * this.forEach(fn); // iterates over all paths in all states - * - * @param {String} [state] - * @param {String} [state] - * @param {Function} callback - * @return {Array} - * @private - */ - -StateMachine.prototype.map = function map() { - this.map = this._iter('map'); - return this.map.apply(this, arguments); -}; diff --git a/node_modules/mongoose/lib/types/array.js b/node_modules/mongoose/lib/types/array.js deleted file mode 100644 index 41c51e5..0000000 --- a/node_modules/mongoose/lib/types/array.js +++ /dev/null @@ -1,66 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const CoreMongooseArray = require('./core_array'); -const Document = require('../document'); - -const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol; -const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol; -const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol; -const arraySchemaSymbol = require('../helpers/symbols').arraySchemaSymbol; - -const _basePush = Array.prototype.push; - -/** - * Mongoose Array constructor. - * - * ####NOTE: - * - * _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._ - * - * @param {Array} values - * @param {String} path - * @param {Document} doc parent document - * @api private - * @inherits Array - * @see http://bit.ly/f6CnZU - */ - -function MongooseArray(values, path, doc) { - // TODO: replace this with `new CoreMongooseArray().concat()` when we remove - // support for node 4.x and 5.x, see https://i.imgur.com/UAAHk4S.png - const arr = new CoreMongooseArray(); - arr[arrayAtomicsSymbol] = {}; - - if (Array.isArray(values)) { - const len = values.length; - for (let i = 0; i < len; ++i) { - _basePush.call(arr, values[i]); - } - - arr[arrayAtomicsSymbol] = values[arrayAtomicsSymbol] || {}; - } - - arr[arrayPathSymbol] = path; - arr[arraySchemaSymbol] = void 0; - - // Because doc comes from the context of another function, doc === global - // can happen if there was a null somewhere up the chain (see #3020) - // RB Jun 17, 2015 updated to check for presence of expected paths instead - // to make more proof against unusual node environments - if (doc && doc instanceof Document) { - arr[arrayParentSymbol] = doc; - arr[arraySchemaSymbol] = doc.schema.path(path); - } - - return arr; -} - -/*! - * Module exports. - */ - -module.exports = exports = MongooseArray; diff --git a/node_modules/mongoose/lib/types/buffer.js b/node_modules/mongoose/lib/types/buffer.js deleted file mode 100644 index 5dbe2d4..0000000 --- a/node_modules/mongoose/lib/types/buffer.js +++ /dev/null @@ -1,279 +0,0 @@ -/*! - * Module dependencies. - */ - -'use strict'; - -const Binary = require('../driver').get().Binary; -const utils = require('../utils'); -const Buffer = require('safe-buffer').Buffer; - -// Yes this is weird. See https://github.com/feross/safe-buffer/pull/23 -const proto = Buffer.from('').constructor.prototype; - -/** - * Mongoose Buffer constructor. - * - * Values always have to be passed to the constructor to initialize. - * - * @param {Buffer} value - * @param {String} encode - * @param {Number} offset - * @api private - * @inherits Buffer - * @see http://bit.ly/f6CnZU - */ - -function MongooseBuffer(value, encode, offset) { - const length = arguments.length; - let val; - - if (length === 0 || arguments[0] === null || arguments[0] === undefined) { - val = 0; - } else { - val = value; - } - - let encoding; - let path; - let doc; - - if (Array.isArray(encode)) { - // internal casting - path = encode[0]; - doc = encode[1]; - } else { - encoding = encode; - } - - let buf; - if (typeof val === 'number' || val instanceof Number) { - buf = Buffer.alloc(val); - } else { // string, array or object { type: 'Buffer', data: [...] } - buf = Buffer.from(val, encoding, offset); - } - utils.decorate(buf, MongooseBuffer.mixin); - buf.isMongooseBuffer = true; - - // make sure these internal props don't show up in Object.keys() - buf[MongooseBuffer.pathSymbol] = path; - buf[parentSymbol] = doc; - - buf._subtype = 0; - return buf; -} - -const pathSymbol = Symbol.for('mongoose#Buffer#_path'); -const parentSymbol = Symbol.for('mongoose#Buffer#_parent'); -MongooseBuffer.pathSymbol = pathSymbol; - -/*! - * Inherit from Buffer. - */ - -MongooseBuffer.mixin = { - - /** - * Default subtype for the Binary representing this Buffer - * - * @api private - * @property _subtype - * @receiver MongooseBuffer - */ - - _subtype: undefined, - - /** - * Marks this buffer as modified. - * - * @api private - * @method _markModified - * @receiver MongooseBuffer - */ - - _markModified: function() { - const parent = this[parentSymbol]; - - if (parent) { - parent.markModified(this[MongooseBuffer.pathSymbol]); - } - return this; - }, - - /** - * Writes the buffer. - * - * @api public - * @method write - * @receiver MongooseBuffer - */ - - write: function() { - const written = proto.write.apply(this, arguments); - - if (written > 0) { - this._markModified(); - } - - return written; - }, - - /** - * Copies the buffer. - * - * ####Note: - * - * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this. - * - * @return {Number} The number of bytes copied. - * @param {Buffer} target - * @method copy - * @receiver MongooseBuffer - */ - - copy: function(target) { - const ret = proto.copy.apply(this, arguments); - - if (target && target.isMongooseBuffer) { - target._markModified(); - } - - return ret; - } -}; - -/*! - * Compile other Buffer methods marking this buffer as modified. - */ - -( -// node < 0.5 - ('writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' + - 'writeFloat writeDouble fill ' + - 'utf8Write binaryWrite asciiWrite set ' + - - // node >= 0.5 - 'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' + - 'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' + 'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE') -).split(' ').forEach(function(method) { - if (!proto[method]) { - return; - } - MongooseBuffer.mixin[method] = function() { - const ret = proto[method].apply(this, arguments); - this._markModified(); - return ret; - }; -}); - -/** - * Converts this buffer to its Binary type representation. - * - * ####SubTypes: - * - * var bson = require('bson') - * bson.BSON_BINARY_SUBTYPE_DEFAULT - * bson.BSON_BINARY_SUBTYPE_FUNCTION - * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY - * bson.BSON_BINARY_SUBTYPE_UUID - * bson.BSON_BINARY_SUBTYPE_MD5 - * bson.BSON_BINARY_SUBTYPE_USER_DEFINED - * - * doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED); - * - * @see http://bsonspec.org/#/specification - * @param {Hex} [subtype] - * @return {Binary} - * @api public - * @method toObject - * @receiver MongooseBuffer - */ - -MongooseBuffer.mixin.toObject = function(options) { - const subtype = typeof options === 'number' - ? options - : (this._subtype || 0); - return new Binary(Buffer.from(this), subtype); -}; - -/** - * Converts this buffer for storage in MongoDB, including subtype - * - * @return {Binary} - * @api public - * @method toBSON - * @receiver MongooseBuffer - */ - -MongooseBuffer.mixin.toBSON = function() { - return new Binary(this, this._subtype || 0); -}; - -/** - * Determines if this buffer is equals to `other` buffer - * - * @param {Buffer} other - * @return {Boolean} - * @method equals - * @receiver MongooseBuffer - */ - -MongooseBuffer.mixin.equals = function(other) { - if (!Buffer.isBuffer(other)) { - return false; - } - - if (this.length !== other.length) { - return false; - } - - for (let i = 0; i < this.length; ++i) { - if (this[i] !== other[i]) { - return false; - } - } - - return true; -}; - -/** - * Sets the subtype option and marks the buffer modified. - * - * ####SubTypes: - * - * var bson = require('bson') - * bson.BSON_BINARY_SUBTYPE_DEFAULT - * bson.BSON_BINARY_SUBTYPE_FUNCTION - * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY - * bson.BSON_BINARY_SUBTYPE_UUID - * bson.BSON_BINARY_SUBTYPE_MD5 - * bson.BSON_BINARY_SUBTYPE_USER_DEFINED - * - * doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID); - * - * @see http://bsonspec.org/#/specification - * @param {Hex} subtype - * @api public - * @method subtype - * @receiver MongooseBuffer - */ - -MongooseBuffer.mixin.subtype = function(subtype) { - if (typeof subtype !== 'number') { - throw new TypeError('Invalid subtype. Expected a number'); - } - - if (this._subtype !== subtype) { - this._markModified(); - } - - this._subtype = subtype; -}; - -/*! - * Module exports. - */ - -MongooseBuffer.Binary = Binary; - -module.exports = MongooseBuffer; diff --git a/node_modules/mongoose/lib/types/core_array.js b/node_modules/mongoose/lib/types/core_array.js deleted file mode 100644 index b663235..0000000 --- a/node_modules/mongoose/lib/types/core_array.js +++ /dev/null @@ -1,947 +0,0 @@ -'use strict'; - -const Document = require('../document'); -const EmbeddedDocument = require('./embedded'); -const MongooseError = require('../error/mongooseError'); -const ObjectId = require('./objectid'); -const cleanModifiedSubpaths = require('../helpers/document/cleanModifiedSubpaths'); -const get = require('../helpers/get'); -const internalToObjectOptions = require('../options').internalToObjectOptions; -const utils = require('../utils'); -const util = require('util'); - -const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol; -const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol; -const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol; -const arraySchemaSymbol = require('../helpers/symbols').arraySchemaSymbol; -const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; - -const _basePush = Array.prototype.push; - -const validatorsSymbol = Symbol('mongoose#MongooseCoreArray#validators'); - -/*! - * ignore - */ - -class CoreMongooseArray extends Array { - get isMongooseArray() { - return true; - } - - get validators() { - return this[validatorsSymbol]; - } - - set validators(v) { - this[validatorsSymbol] = v; - } - - /** - * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB. - * - * If no atomics exist, we return all array values after conversion. - * - * @return {Array} - * @method $__getAtomics - * @memberOf MongooseArray - * @instance - * @api private - */ - - $__getAtomics() { - const ret = []; - const keys = Object.keys(this[arrayAtomicsSymbol]); - let i = keys.length; - - const opts = Object.assign({}, internalToObjectOptions, { _isNested: true }); - - if (i === 0) { - ret[0] = ['$set', this.toObject(opts)]; - return ret; - } - - while (i--) { - const op = keys[i]; - let val = this[arrayAtomicsSymbol][op]; - - // the atomic values which are arrays are not MongooseArrays. we - // need to convert their elements as if they were MongooseArrays - // to handle populated arrays versus DocumentArrays properly. - if (utils.isMongooseObject(val)) { - val = val.toObject(opts); - } else if (Array.isArray(val)) { - val = this.toObject.call(val, opts); - } else if (val != null && Array.isArray(val.$each)) { - val.$each = this.toObject.call(val.$each, opts); - } else if (val != null && typeof val.valueOf === 'function') { - val = val.valueOf(); - } - - if (op === '$addToSet') { - val = { $each: val }; - } - - ret.push([op, val]); - } - - return ret; - } - - /*! - * ignore - */ - - $atomics() { - return this[arrayAtomicsSymbol]; - } - - /*! - * ignore - */ - - $parent() { - return this[arrayParentSymbol]; - } - - /*! - * ignore - */ - - $path() { - return this[arrayPathSymbol]; - } - - /** - * Atomically shifts the array at most one time per document `save()`. - * - * ####NOTE: - * - * _Calling this multiple times on an array before saving sends the same command as calling it once._ - * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ - * - * doc.array = [1,2,3]; - * - * var shifted = doc.array.$shift(); - * console.log(shifted); // 1 - * console.log(doc.array); // [2,3] - * - * // no affect - * shifted = doc.array.$shift(); - * console.log(doc.array); // [2,3] - * - * doc.save(function (err) { - * if (err) return handleError(err); - * - * // we saved, now $shift works again - * shifted = doc.array.$shift(); - * console.log(shifted ); // 2 - * console.log(doc.array); // [3] - * }) - * - * @api public - * @memberOf MongooseArray - * @instance - * @method $shift - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop - */ - - $shift() { - this._registerAtomic('$pop', -1); - this._markModified(); - - // only allow shifting once - if (this._shifted) { - return; - } - this._shifted = true; - - return [].shift.call(this); - } - - /** - * Pops the array atomically at most one time per document `save()`. - * - * #### NOTE: - * - * _Calling this mulitple times on an array before saving sends the same command as calling it once._ - * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ - * - * doc.array = [1,2,3]; - * - * var popped = doc.array.$pop(); - * console.log(popped); // 3 - * console.log(doc.array); // [1,2] - * - * // no affect - * popped = doc.array.$pop(); - * console.log(doc.array); // [1,2] - * - * doc.save(function (err) { - * if (err) return handleError(err); - * - * // we saved, now $pop works again - * popped = doc.array.$pop(); - * console.log(popped); // 2 - * console.log(doc.array); // [1] - * }) - * - * @api public - * @method $pop - * @memberOf MongooseArray - * @instance - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop - * @method $pop - * @memberOf MongooseArray - */ - - $pop() { - this._registerAtomic('$pop', 1); - this._markModified(); - - // only allow popping once - if (this._popped) { - return; - } - this._popped = true; - - return [].pop.call(this); - } - - /*! - * ignore - */ - - $schema() { - return this[arraySchemaSymbol]; - } - - /** - * Casts a member based on this arrays schema. - * - * @param {any} value - * @return value the casted value - * @method _cast - * @api private - * @memberOf MongooseArray - */ - - _cast(value) { - let populated = false; - let Model; - - if (this[arrayParentSymbol]) { - populated = this[arrayParentSymbol].populated(this[arrayPathSymbol], true); - } - - if (populated && value !== null && value !== undefined) { - // cast to the populated Models schema - Model = populated.options[populateModelSymbol]; - - // only objects are permitted so we can safely assume that - // non-objects are to be interpreted as _id - if (Buffer.isBuffer(value) || - value instanceof ObjectId || !utils.isObject(value)) { - value = { _id: value }; - } - - // gh-2399 - // we should cast model only when it's not a discriminator - const isDisc = value.schema && value.schema.discriminatorMapping && - value.schema.discriminatorMapping.key !== undefined; - if (!isDisc) { - value = new Model(value); - } - return this[arraySchemaSymbol].caster.applySetters(value, this[arrayParentSymbol], true); - } - - return this[arraySchemaSymbol].caster.applySetters(value, this[arrayParentSymbol], false); - } - - /** - * Internal helper for .map() - * - * @api private - * @return {Number} - * @method _mapCast - * @memberOf MongooseArray - */ - - _mapCast(val, index) { - return this._cast(val, this.length + index); - } - - /** - * Marks this array as modified. - * - * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments) - * - * @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array - * @param {String} embeddedPath the path which changed in the embeddedDoc - * @method _markModified - * @api private - * @memberOf MongooseArray - */ - - _markModified(elem, embeddedPath) { - const parent = this[arrayParentSymbol]; - let dirtyPath; - - if (parent) { - dirtyPath = this[arrayPathSymbol]; - - if (arguments.length) { - if (embeddedPath != null) { - // an embedded doc bubbled up the change - dirtyPath = dirtyPath + '.' + this.indexOf(elem) + '.' + embeddedPath; - } else { - // directly set an index - dirtyPath = dirtyPath + '.' + elem; - } - } - - if (dirtyPath != null && dirtyPath.endsWith('.$')) { - return this; - } - - parent.markModified(dirtyPath, arguments.length > 0 ? elem : parent); - } - - return this; - } - - /** - * Register an atomic operation with the parent. - * - * @param {Array} op operation - * @param {any} val - * @method _registerAtomic - * @api private - * @memberOf MongooseArray - */ - - _registerAtomic(op, val) { - if (op === '$set') { - // $set takes precedence over all other ops. - // mark entire array modified. - this[arrayAtomicsSymbol] = { $set: val }; - cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]); - this._markModified(); - return this; - } - - const atomics = this[arrayAtomicsSymbol]; - - // reset pop/shift after save - if (op === '$pop' && !('$pop' in atomics)) { - const _this = this; - this[arrayParentSymbol].once('save', function() { - _this._popped = _this._shifted = null; - }); - } - - // check for impossible $atomic combos (Mongo denies more than one - // $atomic op on a single path - if (this[arrayAtomicsSymbol].$set || Object.keys(atomics).length && !(op in atomics)) { - // a different op was previously registered. - // save the entire thing. - this[arrayAtomicsSymbol] = { $set: this }; - return this; - } - - let selector; - - if (op === '$pullAll' || op === '$addToSet') { - atomics[op] || (atomics[op] = []); - atomics[op] = atomics[op].concat(val); - } else if (op === '$pullDocs') { - const pullOp = atomics['$pull'] || (atomics['$pull'] = {}); - if (val[0] instanceof EmbeddedDocument) { - selector = pullOp['$or'] || (pullOp['$or'] = []); - Array.prototype.push.apply(selector, val.map(function(v) { - return v.toObject({ transform: false, virtuals: false }); - })); - } else { - selector = pullOp['_id'] || (pullOp['_id'] = { $in: [] }); - selector['$in'] = selector['$in'].concat(val); - } - } else if (op === '$push') { - atomics.$push = atomics.$push || { $each: [] }; - if (val != null && utils.hasUserDefinedProperty(val, '$each')) { - atomics.$push = val; - } else { - atomics.$push.$each = atomics.$push.$each.concat(val); - } - } else { - atomics[op] = val; - } - - return this; - } - - /** - * Adds values to the array if not already present. - * - * ####Example: - * - * console.log(doc.array) // [2,3,4] - * var added = doc.array.addToSet(4,5); - * console.log(doc.array) // [2,3,4,5] - * console.log(added) // [5] - * - * @param {any} [args...] - * @return {Array} the values that were added - * @memberOf MongooseArray - * @api public - * @method addToSet - */ - - addToSet() { - _checkManualPopulation(this, arguments); - - let values = [].map.call(arguments, this._mapCast, this); - values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); - const added = []; - let type = ''; - if (values[0] instanceof EmbeddedDocument) { - type = 'doc'; - } else if (values[0] instanceof Date) { - type = 'date'; - } - - values.forEach(function(v) { - let found; - const val = +v; - switch (type) { - case 'doc': - found = this.some(function(doc) { - return doc.equals(v); - }); - break; - case 'date': - found = this.some(function(d) { - return +d === val; - }); - break; - default: - found = ~this.indexOf(v); - } - - if (!found) { - [].push.call(this, v); - this._registerAtomic('$addToSet', v); - this._markModified(); - [].push.call(added, v); - } - }, this); - - return added; - } - - /** - * Returns the number of pending atomic operations to send to the db for this array. - * - * @api private - * @return {Number} - * @method hasAtomics - * @memberOf MongooseArray - */ - - hasAtomics() { - if (!utils.isPOJO(this[arrayAtomicsSymbol])) { - return 0; - } - - return Object.keys(this[arrayAtomicsSymbol]).length; - } - - /** - * Return whether or not the `obj` is included in the array. - * - * @param {Object} obj the item to check - * @return {Boolean} - * @api public - * @method includes - * @memberOf MongooseArray - */ - - includes(obj, fromIndex) { - const ret = this.indexOf(obj, fromIndex); - return ret !== -1; - } - - /** - * Return the index of `obj` or `-1` if not found. - * - * @param {Object} obj the item to look for - * @return {Number} - * @api public - * @method indexOf - * @memberOf MongooseArray - */ - - indexOf(obj, fromIndex) { - if (obj instanceof ObjectId) { - obj = obj.toString(); - } - - fromIndex = fromIndex == null ? 0 : fromIndex; - const len = this.length; - for (let i = fromIndex; i < len; ++i) { - if (obj == this[i]) { - return i; - } - } - return -1; - } - - /** - * Helper for console.log - * - * @api public - * @method inspect - * @memberOf MongooseArray - */ - - inspect() { - return JSON.stringify(this); - } - - /** - * Pushes items to the array non-atomically. - * - * ####NOTE: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @param {any} [args...] - * @api public - * @method nonAtomicPush - * @memberOf MongooseArray - */ - - nonAtomicPush() { - const values = [].map.call(arguments, this._mapCast, this); - const ret = [].push.apply(this, values); - this._registerAtomic('$set', this); - this._markModified(); - return ret; - } - - /** - * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking. - * - * ####Note: - * - * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @see MongooseArray#$pop #types_array_MongooseArray-%24pop - * @api public - * @method pop - * @memberOf MongooseArray - */ - - pop() { - const ret = [].pop.call(this); - this._registerAtomic('$set', this); - this._markModified(); - return ret; - } - - /** - * Pulls items from the array atomically. Equality is determined by casting - * the provided value to an embedded document and comparing using - * [the `Document.equals()` function.](./api.html#document_Document-equals) - * - * ####Examples: - * - * doc.array.pull(ObjectId) - * doc.array.pull({ _id: 'someId' }) - * doc.array.pull(36) - * doc.array.pull('tag 1', 'tag 2') - * - * To remove a document from a subdocument array we may pass an object with a matching `_id`. - * - * doc.subdocs.push({ _id: 4815162342 }) - * doc.subdocs.pull({ _id: 4815162342 }) // removed - * - * Or we may passing the _id directly and let mongoose take care of it. - * - * doc.subdocs.push({ _id: 4815162342 }) - * doc.subdocs.pull(4815162342); // works - * - * The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime. - * - * @param {any} [args...] - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull - * @api public - * @method pull - * @memberOf MongooseArray - */ - - pull() { - const values = [].map.call(arguments, this._cast, this); - const cur = this[arrayParentSymbol].get(this[arrayPathSymbol]); - let i = cur.length; - let mem; - - while (i--) { - mem = cur[i]; - if (mem instanceof Document) { - const some = values.some(function(v) { - return mem.equals(v); - }); - if (some) { - [].splice.call(cur, i, 1); - } - } else if (~cur.indexOf.call(values, mem)) { - [].splice.call(cur, i, 1); - } - } - - if (values[0] instanceof EmbeddedDocument) { - this._registerAtomic('$pullDocs', values.map(function(v) { - return v._id || v; - })); - } else { - this._registerAtomic('$pullAll', values); - } - - this._markModified(); - - // Might have modified child paths and then pulled, like - // `doc.children[1].name = 'test';` followed by - // `doc.children.remove(doc.children[0]);`. In this case we fall back - // to a `$set` on the whole array. See #3511 - if (cleanModifiedSubpaths(this[arrayParentSymbol], this[arrayPathSymbol]) > 0) { - this._registerAtomic('$set', this); - } - - return this; - } - - /** - * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. - * - * ####Example: - * - * const schema = Schema({ nums: [Number] }); - * const Model = mongoose.model('Test', schema); - * - * const doc = await Model.create({ nums: [3, 4] }); - * doc.nums.push(5); // Add 5 to the end of the array - * await doc.save(); - * - * // You can also pass an object with `$each` as the - * // first parameter to use MongoDB's `$position` - * doc.nums.push({ - * $each: [1, 2], - * $position: 0 - * }); - * doc.nums; // [1, 2, 3, 4, 5] - * - * @param {Object} [args...] - * @api public - * @method push - * @memberOf MongooseArray - */ - - push() { - let values = arguments; - let atomic = values; - const isOverwrite = values[0] != null && - utils.hasUserDefinedProperty(values[0], '$each'); - if (isOverwrite) { - atomic = values[0]; - values = values[0].$each; - } - - if (this[arraySchemaSymbol] == null) { - return _basePush.apply(this, values); - } - - _checkManualPopulation(this, values); - - const parent = this[arrayParentSymbol]; - values = [].map.call(values, this._mapCast, this); - values = this[arraySchemaSymbol].applySetters(values, parent, undefined, - undefined, { skipDocumentArrayCast: true }); - let ret; - const atomics = this[arrayAtomicsSymbol]; - - if (isOverwrite) { - atomic.$each = values; - - if (get(atomics, '$push.$each.length', 0) > 0 && - atomics.$push.$position != atomics.$position) { - throw new MongooseError('Cannot call `Array#push()` multiple times ' + - 'with different `$position`'); - } - - if (atomic.$position != null) { - [].splice.apply(this, [atomic.$position, 0].concat(values)); - ret = this.length; - } else { - ret = [].push.apply(this, values); - } - } else { - if (get(atomics, '$push.$each.length', 0) > 0 && - atomics.$push.$position != null) { - throw new MongooseError('Cannot call `Array#push()` multiple times ' + - 'with different `$position`'); - } - atomic = values; - ret = [].push.apply(this, values); - } - this._registerAtomic('$push', atomic); - this._markModified(); - return ret; - } - - /** - * Alias of [pull](#types_array_MongooseArray-pull) - * - * @see MongooseArray#pull #types_array_MongooseArray-pull - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull - * @api public - * @memberOf MongooseArray - * @instance - * @method remove - */ - - remove() { - return this.pull.apply(this, arguments); - } - - /** - * Sets the casted `val` at index `i` and marks the array modified. - * - * ####Example: - * - * // given documents based on the following - * var Doc = mongoose.model('Doc', new Schema({ array: [Number] })); - * - * var doc = new Doc({ array: [2,3,4] }) - * - * console.log(doc.array) // [2,3,4] - * - * doc.array.set(1,"5"); - * console.log(doc.array); // [2,5,4] // properly cast to number - * doc.save() // the change is saved - * - * // VS not using array#set - * doc.array[1] = "5"; - * console.log(doc.array); // [2,"5",4] // no casting - * doc.save() // change is not saved - * - * @return {Array} this - * @api public - * @method set - * @memberOf MongooseArray - */ - - set(i, val) { - const value = this._cast(val, i); - this[i] = value; - this._markModified(i); - return this; - } - - /** - * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. - * - * ####Example: - * - * doc.array = [2,3]; - * var res = doc.array.shift(); - * console.log(res) // 2 - * console.log(doc.array) // [3] - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - * @method shift - * @memberOf MongooseArray - */ - - shift() { - const ret = [].shift.call(this); - this._registerAtomic('$set', this); - this._markModified(); - return ret; - } - - /** - * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking. - * - * ####NOTE: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - * @method sort - * @memberOf MongooseArray - * @see https://masteringjs.io/tutorials/fundamentals/array-sort - */ - - sort() { - const ret = [].sort.apply(this, arguments); - this._registerAtomic('$set', this); - return ret; - } - - /** - * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - * @method splice - * @memberOf MongooseArray - * @see https://masteringjs.io/tutorials/fundamentals/array-splice - */ - - splice() { - let ret; - - _checkManualPopulation(this, Array.prototype.slice.call(arguments, 2)); - - if (arguments.length) { - let vals; - if (this[arraySchemaSymbol] == null) { - vals = arguments; - } else { - vals = []; - for (let i = 0; i < arguments.length; ++i) { - vals[i] = i < 2 ? - arguments[i] : - this._cast(arguments[i], arguments[0] + (i - 2)); - } - } - - ret = [].splice.apply(this, vals); - this._registerAtomic('$set', this); - } - - return ret; - } - - /*! - * ignore - */ - - slice() { - const ret = super.slice.apply(this, arguments); - ret[arrayParentSymbol] = this[arrayParentSymbol]; - ret[arraySchemaSymbol] = this[arraySchemaSymbol]; - ret[arrayAtomicsSymbol] = this[arrayAtomicsSymbol]; - return ret; - } - - /*! - * ignore - */ - - toBSON() { - return this.toObject(internalToObjectOptions); - } - - /** - * Returns a native js Array. - * - * @param {Object} options - * @return {Array} - * @api public - * @method toObject - * @memberOf MongooseArray - */ - - toObject(options) { - if (options && options.depopulate) { - options = utils.clone(options); - options._isNested = true; - return this.map(function(doc) { - return doc instanceof Document - ? doc.toObject(options) - : doc; - }); - } - - return this.slice(); - } - - /** - * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - * @method unshift - * @memberOf MongooseArray - */ - - unshift() { - _checkManualPopulation(this, arguments); - - let values = [].map.call(arguments, this._cast, this); - values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]); - [].unshift.apply(this, values); - this._registerAtomic('$set', this); - this._markModified(); - return this.length; - } -} - -if (util.inspect.custom) { - CoreMongooseArray.prototype[util.inspect.custom] = - CoreMongooseArray.prototype.inspect; -} - -/*! - * ignore - */ - -function _isAllSubdocs(docs, ref) { - if (!ref) { - return false; - } - - for (const arg of docs) { - if (arg == null) { - return false; - } - const model = arg.constructor; - if (!(arg instanceof Document) || - (model.modelName !== ref && model.baseModelName !== ref)) { - return false; - } - } - - return true; -} - -/*! - * ignore - */ - -function _checkManualPopulation(arr, docs) { - const ref = arr == null ? - null : - get(arr[arraySchemaSymbol], 'caster.options.ref', null); - if (arr.length === 0 && - docs.length > 0) { - if (_isAllSubdocs(docs, ref)) { - arr[arrayParentSymbol].populated(arr[arrayPathSymbol], [], { - [populateModelSymbol]: docs[0].constructor - }); - } - } -} - -module.exports = CoreMongooseArray; \ No newline at end of file diff --git a/node_modules/mongoose/lib/types/decimal128.js b/node_modules/mongoose/lib/types/decimal128.js deleted file mode 100644 index f0bae2a..0000000 --- a/node_modules/mongoose/lib/types/decimal128.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * ObjectId type constructor - * - * ####Example - * - * var id = new mongoose.Types.ObjectId; - * - * @constructor ObjectId - */ - -'use strict'; - -module.exports = require('../driver').get().Decimal128; diff --git a/node_modules/mongoose/lib/types/documentarray.js b/node_modules/mongoose/lib/types/documentarray.js deleted file mode 100644 index b5ebbeb..0000000 --- a/node_modules/mongoose/lib/types/documentarray.js +++ /dev/null @@ -1,421 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const CoreMongooseArray = require('./core_array'); -const Document = require('../document'); -const ObjectId = require('./objectid'); -const castObjectId = require('../cast/objectid'); -const getDiscriminatorByValue = require('../helpers/discriminator/getDiscriminatorByValue'); -const internalToObjectOptions = require('../options').internalToObjectOptions; -const util = require('util'); -const utils = require('../utils'); - -const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol; -const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol; -const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol; -const arraySchemaSymbol = require('../helpers/symbols').arraySchemaSymbol; -const documentArrayParent = require('../helpers/symbols').documentArrayParent; - -const _basePush = Array.prototype.push; - -class CoreDocumentArray extends CoreMongooseArray { - get isMongooseDocumentArray() { - return true; - } - - /*! - * ignore - */ - - toBSON() { - return this.toObject(internalToObjectOptions); - } - - /*! - * ignore - */ - - map() { - const ret = super.map.apply(this, arguments); - ret[arraySchemaSymbol] = null; - ret[arrayPathSymbol] = null; - ret[arrayParentSymbol] = null; - - return ret; - } - - /** - * Overrides MongooseArray#cast - * - * @method _cast - * @api private - * @receiver MongooseDocumentArray - */ - - _cast(value, index) { - if (this[arraySchemaSymbol] == null) { - return value; - } - let Constructor = this[arraySchemaSymbol].casterConstructor; - const isInstance = Constructor.$isMongooseDocumentArray ? - value && value.isMongooseDocumentArray : - value instanceof Constructor; - if (isInstance || - // Hack re: #5001, see #5005 - (value && value.constructor && value.constructor.baseCasterConstructor === Constructor)) { - if (!(value[documentArrayParent] && value.__parentArray)) { - // value may have been created using array.create() - value[documentArrayParent] = this[arrayParentSymbol]; - value.__parentArray = this; - } - value.$setIndex(index); - return value; - } - - if (value === undefined || value === null) { - return null; - } - - // handle cast('string') or cast(ObjectId) etc. - // only objects are permitted so we can safely assume that - // non-objects are to be interpreted as _id - if (Buffer.isBuffer(value) || - value instanceof ObjectId || !utils.isObject(value)) { - value = { _id: value }; - } - - if (value && - Constructor.discriminators && - Constructor.schema && - Constructor.schema.options && - Constructor.schema.options.discriminatorKey) { - if (typeof value[Constructor.schema.options.discriminatorKey] === 'string' && - Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) { - Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]; - } else { - const constructorByValue = getDiscriminatorByValue(Constructor, value[Constructor.schema.options.discriminatorKey]); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } - - if (Constructor.$isMongooseDocumentArray) { - return Constructor.cast(value, this, undefined, undefined, index); - } - return new Constructor(value, this, undefined, undefined, index); - } - - /** - * Searches array items for the first document with a matching _id. - * - * ####Example: - * - * var embeddedDoc = m.array.id(some_id); - * - * @return {EmbeddedDocument|null} the subdocument or null if not found. - * @param {ObjectId|String|Number|Buffer} id - * @TODO cast to the _id based on schema for proper comparison - * @method id - * @api public - * @receiver MongooseDocumentArray - */ - - id(id) { - let casted; - let sid; - let _id; - - try { - casted = castObjectId(id).toString(); - } catch (e) { - casted = null; - } - - for (const val of this) { - if (!val) { - continue; - } - - _id = val.get('_id'); - - if (_id === null || typeof _id === 'undefined') { - continue; - } else if (_id instanceof Document) { - sid || (sid = String(id)); - if (sid == _id._id) { - return val; - } - } else if (!(id instanceof ObjectId) && !(_id instanceof ObjectId)) { - if (utils.deepEqual(id, _id)) { - return val; - } - } else if (casted == _id) { - return val; - } - } - - return null; - } - - /** - * Returns a native js Array of plain js objects - * - * ####NOTE: - * - * _Each sub-document is converted to a plain object by calling its `#toObject` method._ - * - * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion - * @return {Array} - * @method toObject - * @api public - * @receiver MongooseDocumentArray - */ - - toObject(options) { - // `[].concat` coerces the return value into a vanilla JS array, rather - // than a Mongoose array. - return [].concat(this.map(function(doc) { - if (doc == null) { - return null; - } - if (typeof doc.toObject !== 'function') { - return doc; - } - return doc.toObject(options); - })); - } - - slice() { - const arr = super.slice.apply(this, arguments); - arr[arrayParentSymbol] = this[arrayParentSymbol]; - arr[arrayPathSymbol] = this[arrayPathSymbol]; - - return arr; - } - - /** - * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. - * - * @param {Object} [args...] - * @api public - * @method push - * @memberOf MongooseDocumentArray - */ - - push() { - const ret = super.push.apply(this, arguments); - - _updateParentPopulated(this); - - return ret; - } - - /** - * Pulls items from the array atomically. - * - * @param {Object} [args...] - * @api public - * @method pull - * @memberOf MongooseDocumentArray - */ - - pull() { - const ret = super.pull.apply(this, arguments); - - _updateParentPopulated(this); - - return ret; - } - - /** - * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. - */ - - shift() { - const ret = super.shift.apply(this, arguments); - - _updateParentPopulated(this); - - return ret; - } - - /** - * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. - */ - - splice() { - const ret = super.splice.apply(this, arguments); - - _updateParentPopulated(this); - - return ret; - } - - /** - * Helper for console.log - * - * @method inspect - * @api public - * @receiver MongooseDocumentArray - */ - - inspect() { - return this.toObject(); - } - - /** - * Creates a subdocument casted to this schema. - * - * This is the same subdocument constructor used for casting. - * - * @param {Object} obj the value to cast to this arrays SubDocument schema - * @method create - * @api public - * @receiver MongooseDocumentArray - */ - - create(obj) { - let Constructor = this[arraySchemaSymbol].casterConstructor; - if (obj && - Constructor.discriminators && - Constructor.schema && - Constructor.schema.options && - Constructor.schema.options.discriminatorKey) { - if (typeof obj[Constructor.schema.options.discriminatorKey] === 'string' && - Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) { - Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]; - } else { - const constructorByValue = getDiscriminatorByValue(Constructor, obj[Constructor.schema.options.discriminatorKey]); - if (constructorByValue) { - Constructor = constructorByValue; - } - } - } - - return new Constructor(obj, this); - } - - /*! - * ignore - */ - - notify(event) { - const _this = this; - return function notify(val, _arr) { - _arr = _arr || _this; - let i = _arr.length; - while (i--) { - if (_arr[i] == null) { - continue; - } - switch (event) { - // only swap for save event for now, we may change this to all event types later - case 'save': - val = _this[i]; - break; - default: - // NO-OP - break; - } - - if (_arr[i].isMongooseArray) { - notify(val, _arr[i]); - } else if (_arr[i]) { - _arr[i].emit(event, val); - } - } - }; - } -} - -if (util.inspect.custom) { - CoreDocumentArray.prototype[util.inspect.custom] = - CoreDocumentArray.prototype.inspect; -} - -/*! - * If this is a document array, each element may contain single - * populated paths, so we need to modify the top-level document's - * populated cache. See gh-8247, gh-8265. - */ - -function _updateParentPopulated(arr) { - const parent = arr[arrayParentSymbol]; - if (!parent || parent.$__.populated == null) return; - - const populatedPaths = Object.keys(parent.$__.populated). - filter(p => p.startsWith(arr[arrayPathSymbol] + '.')); - - for (const path of populatedPaths) { - const remnant = path.slice((arr[arrayPathSymbol] + '.').length); - if (!Array.isArray(parent.$__.populated[path].value)) { - continue; - } - - parent.$__.populated[path].value = arr.map(val => val.populated(remnant)); - } -} - -/** - * DocumentArray constructor - * - * @param {Array} values - * @param {String} path the path to this array - * @param {Document} doc parent document - * @api private - * @return {MongooseDocumentArray} - * @inherits MongooseArray - * @see http://bit.ly/f6CnZU - */ - -function MongooseDocumentArray(values, path, doc) { - // TODO: replace this with `new CoreDocumentArray().concat()` when we remove - // support for node 4.x and 5.x, see https://i.imgur.com/UAAHk4S.png - const arr = new CoreDocumentArray(); - - arr[arrayAtomicsSymbol] = {}; - arr[arraySchemaSymbol] = void 0; - if (Array.isArray(values)) { - if (values instanceof CoreDocumentArray && - values[arrayPathSymbol] === path && - values[arrayParentSymbol] === doc) { - arr[arrayAtomicsSymbol] = Object.assign({}, values[arrayAtomicsSymbol]); - } - values.forEach(v => { - _basePush.call(arr, v); - }); - } - arr[arrayPathSymbol] = path; - - // Because doc comes from the context of another function, doc === global - // can happen if there was a null somewhere up the chain (see #3020 && #3034) - // RB Jun 17, 2015 updated to check for presence of expected paths instead - // to make more proof against unusual node environments - if (doc && doc instanceof Document) { - arr[arrayParentSymbol] = doc; - arr[arraySchemaSymbol] = doc.schema.path(path); - - // `schema.path()` doesn't drill into nested arrays properly yet, see - // gh-6398, gh-6602. This is a workaround because nested arrays are - // always plain non-document arrays, so once you get to a document array - // nesting is done. Matryoshka code. - while (arr != null && - arr[arraySchemaSymbol] != null && - arr[arraySchemaSymbol].$isMongooseArray && - !arr[arraySchemaSymbol].$isMongooseDocumentArray) { - arr[arraySchemaSymbol] = arr[arraySchemaSymbol].casterConstructor; - } - } - - return arr; -} - -/*! - * Module exports. - */ - -module.exports = MongooseDocumentArray; diff --git a/node_modules/mongoose/lib/types/embedded.js b/node_modules/mongoose/lib/types/embedded.js deleted file mode 100644 index 4296d6c..0000000 --- a/node_modules/mongoose/lib/types/embedded.js +++ /dev/null @@ -1,445 +0,0 @@ -/* eslint no-func-assign: 1 */ - -/*! - * Module dependencies. - */ - -'use strict'; - -const Document = require('../document_provider')(); -const EventEmitter = require('events').EventEmitter; -const ValidationError = require('../error/validation'); -const immediate = require('../helpers/immediate'); -const internalToObjectOptions = require('../options').internalToObjectOptions; -const get = require('../helpers/get'); -const promiseOrCallback = require('../helpers/promiseOrCallback'); -const util = require('util'); - -const documentArrayParent = require('../helpers/symbols').documentArrayParent; -const validatorErrorSymbol = require('../helpers/symbols').validatorErrorSymbol; - -/** - * EmbeddedDocument constructor. - * - * @param {Object} obj js object returned from the db - * @param {MongooseDocumentArray} parentArr the parent array of this document - * @param {Boolean} skipId - * @inherits Document - * @api private - */ - -function EmbeddedDocument(obj, parentArr, skipId, fields, index) { - if (parentArr != null && parentArr.isMongooseDocumentArray) { - this.__parentArray = parentArr; - this[documentArrayParent] = parentArr.$parent(); - } else { - this.__parentArray = undefined; - this[documentArrayParent] = undefined; - } - this.$setIndex(index); - this.$isDocumentArrayElement = true; - - Document.call(this, obj, fields, skipId); - - const _this = this; - this.on('isNew', function(val) { - _this.isNew = val; - }); - - _this.on('save', function() { - _this.constructor.emit('save', _this); - }); -} - -/*! - * Inherit from Document - */ -EmbeddedDocument.prototype = Object.create(Document.prototype); -EmbeddedDocument.prototype.constructor = EmbeddedDocument; - -for (const i in EventEmitter.prototype) { - EmbeddedDocument[i] = EventEmitter.prototype[i]; -} - -EmbeddedDocument.prototype.toBSON = function() { - return this.toObject(internalToObjectOptions); -}; - -/*! - * ignore - */ - -EmbeddedDocument.prototype.$setIndex = function(index) { - this.__index = index; - - if (get(this, '$__.validationError', null) != null) { - const keys = Object.keys(this.$__.validationError.errors); - for (const key of keys) { - this.invalidate(key, this.$__.validationError.errors[key]); - } - } -}; - -/** - * Marks the embedded doc modified. - * - * ####Example: - * - * var doc = blogpost.comments.id(hexstring); - * doc.mixed.type = 'changed'; - * doc.markModified('mixed.type'); - * - * @param {String} path the path which changed - * @api public - * @receiver EmbeddedDocument - */ - -EmbeddedDocument.prototype.markModified = function(path) { - this.$__.activePaths.modify(path); - if (!this.__parentArray) { - return; - } - - if (this.isNew) { - // Mark the WHOLE parent array as modified - // if this is a new document (i.e., we are initializing - // a document), - this.__parentArray._markModified(); - } else { - this.__parentArray._markModified(this, path); - } -}; - -/*! - * ignore - */ - -EmbeddedDocument.prototype.populate = function() { - throw new Error('Mongoose does not support calling populate() on nested ' + - 'docs. Instead of `doc.arr[0].populate("path")`, use ' + - '`doc.populate("arr.0.path")`'); -}; - -/** - * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3) - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @return {Promise} resolved Promise - * @api private - */ - -EmbeddedDocument.prototype.save = function(options, fn) { - if (typeof options === 'function') { - fn = options; - options = {}; - } - options = options || {}; - - if (!options.suppressWarning) { - console.warn('mongoose: calling `save()` on a subdoc does **not** save ' + - 'the document to MongoDB, it only runs save middleware. ' + - 'Use `subdoc.save({ suppressWarning: true })` to hide this warning ' + - 'if you\'re sure this behavior is right for your app.'); - } - - return promiseOrCallback(fn, cb => { - this.$__save(cb); - }); -}; - -/** - * Used as a stub for middleware - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @method $__save - * @api private - */ - -EmbeddedDocument.prototype.$__save = function(fn) { - return immediate(() => fn(null, this)); -}; - -/*! - * Registers remove event listeners for triggering - * on subdocuments. - * - * @param {EmbeddedDocument} sub - * @api private - */ - -function registerRemoveListener(sub) { - let owner = sub.ownerDocument(); - - function emitRemove() { - owner.removeListener('save', emitRemove); - owner.removeListener('remove', emitRemove); - sub.emit('remove', sub); - sub.constructor.emit('remove', sub); - owner = sub = null; - } - - owner.on('save', emitRemove); - owner.on('remove', emitRemove); -} - -/*! - * no-op for hooks - */ - -EmbeddedDocument.prototype.$__remove = function(cb) { - return cb(null, this); -}; - -/** - * Removes the subdocument from its parent array. - * - * @param {Object} [options] - * @param {Function} [fn] - * @api public - */ - -EmbeddedDocument.prototype.remove = function(options, fn) { - if (typeof options === 'function' && !fn) { - fn = options; - options = undefined; - } - if (!this.__parentArray || (options && options.noop)) { - fn && fn(null); - return this; - } - - let _id; - if (!this.willRemove) { - _id = this._doc._id; - if (!_id) { - throw new Error('For your own good, Mongoose does not know ' + - 'how to remove an EmbeddedDocument that has no _id'); - } - this.__parentArray.pull({ _id: _id }); - this.willRemove = true; - registerRemoveListener(this); - } - - if (fn) { - fn(null); - } - - return this; -}; - -/** - * Override #update method of parent documents. - * @api private - */ - -EmbeddedDocument.prototype.update = function() { - throw new Error('The #update method is not available on EmbeddedDocuments'); -}; - -/** - * Helper for console.log - * - * @api public - */ - -EmbeddedDocument.prototype.inspect = function() { - return this.toObject({ - transform: false, - virtuals: false, - flattenDecimals: false - }); -}; - -if (util.inspect.custom) { - /*! - * Avoid Node deprecation warning DEP0079 - */ - - EmbeddedDocument.prototype[util.inspect.custom] = EmbeddedDocument.prototype.inspect; -} - -/** - * Marks a path as invalid, causing validation to fail. - * - * @param {String} path the field to invalidate - * @param {String|Error} err error which states the reason `path` was invalid - * @return {Boolean} - * @api public - */ - -EmbeddedDocument.prototype.invalidate = function(path, err, val) { - Document.prototype.invalidate.call(this, path, err, val); - - if (!this[documentArrayParent] || this.__index == null) { - if (err[validatorErrorSymbol] || err instanceof ValidationError) { - return true; - } - throw err; - } - - const index = this.__index; - const parentPath = this.__parentArray.$path(); - const fullPath = [parentPath, index, path].join('.'); - this[documentArrayParent].invalidate(fullPath, err, val); - - return true; -}; - -/** - * Marks a path as valid, removing existing validation errors. - * - * @param {String} path the field to mark as valid - * @api private - * @method $markValid - * @receiver EmbeddedDocument - */ - -EmbeddedDocument.prototype.$markValid = function(path) { - if (!this[documentArrayParent]) { - return; - } - - const index = this.__index; - if (typeof index !== 'undefined') { - const parentPath = this.__parentArray.$path(); - const fullPath = [parentPath, index, path].join('.'); - this[documentArrayParent].$markValid(fullPath); - } -}; - -/*! - * ignore - */ - -EmbeddedDocument.prototype.$ignore = function(path) { - Document.prototype.$ignore.call(this, path); - - if (!this[documentArrayParent]) { - return; - } - - const index = this.__index; - if (typeof index !== 'undefined') { - const parentPath = this.__parentArray.$path(); - const fullPath = [parentPath, index, path].join('.'); - this[documentArrayParent].$ignore(fullPath); - } -}; - -/** - * Checks if a path is invalid - * - * @param {String} path the field to check - * @api private - * @method $isValid - * @receiver EmbeddedDocument - */ - -EmbeddedDocument.prototype.$isValid = function(path) { - const index = this.__index; - if (typeof index !== 'undefined' && this[documentArrayParent]) { - return !this[documentArrayParent].$__.validationError || - !this[documentArrayParent].$__.validationError.errors[this.$__fullPath(path)]; - } - - return true; -}; - -/** - * Returns the top level document of this sub-document. - * - * @return {Document} - */ - -EmbeddedDocument.prototype.ownerDocument = function() { - if (this.$__.ownerDocument) { - return this.$__.ownerDocument; - } - - let parent = this[documentArrayParent]; - if (!parent) { - return this; - } - - while (parent[documentArrayParent] || parent.$parent) { - parent = parent[documentArrayParent] || parent.$parent; - } - - this.$__.ownerDocument = parent; - return this.$__.ownerDocument; -}; - -/** - * Returns the full path to this document. If optional `path` is passed, it is appended to the full path. - * - * @param {String} [path] - * @return {String} - * @api private - * @method $__fullPath - * @memberOf EmbeddedDocument - * @instance - */ - -EmbeddedDocument.prototype.$__fullPath = function(path) { - if (!this.$__.fullPath) { - let parent = this; // eslint-disable-line consistent-this - if (!parent[documentArrayParent]) { - return path; - } - - const paths = []; - while (parent[documentArrayParent] || parent.$parent) { - if (parent[documentArrayParent]) { - paths.unshift(parent.__parentArray.$path()); - } else { - paths.unshift(parent.$basePath); - } - parent = parent[documentArrayParent] || parent.$parent; - } - - this.$__.fullPath = paths.join('.'); - - if (!this.$__.ownerDocument) { - // optimization - this.$__.ownerDocument = parent; - } - } - - return path - ? this.$__.fullPath + '.' + path - : this.$__.fullPath; -}; - -/** - * Returns this sub-documents parent document. - * - * @api public - */ - -EmbeddedDocument.prototype.parent = function() { - return this[documentArrayParent]; -}; - -/** - * Returns this sub-documents parent array. - * - * @api public - */ - -EmbeddedDocument.prototype.parentArray = function() { - return this.__parentArray; -}; - -/*! - * Module exports. - */ - -module.exports = EmbeddedDocument; diff --git a/node_modules/mongoose/lib/types/index.js b/node_modules/mongoose/lib/types/index.js deleted file mode 100644 index a1945a0..0000000 --- a/node_modules/mongoose/lib/types/index.js +++ /dev/null @@ -1,20 +0,0 @@ - -/*! - * Module exports. - */ - -'use strict'; - -exports.Array = require('./array'); -exports.Buffer = require('./buffer'); - -exports.Document = // @deprecate -exports.Embedded = require('./embedded'); - -exports.DocumentArray = require('./documentarray'); -exports.Decimal128 = require('./decimal128'); -exports.ObjectId = require('./objectid'); - -exports.Map = require('./map'); - -exports.Subdocument = require('./subdocument'); diff --git a/node_modules/mongoose/lib/types/map.js b/node_modules/mongoose/lib/types/map.js deleted file mode 100644 index 73c9269..0000000 --- a/node_modules/mongoose/lib/types/map.js +++ /dev/null @@ -1,218 +0,0 @@ -'use strict'; - -const Mixed = require('../schema/mixed'); -const deepEqual = require('../utils').deepEqual; -const get = require('../helpers/get'); -const handleSpreadDoc = require('../helpers/document/handleSpreadDoc'); -const util = require('util'); -const specialProperties = require('../helpers/specialProperties'); - -const populateModelSymbol = require('../helpers/symbols').populateModelSymbol; - -/*! - * ignore - */ - -class MongooseMap extends Map { - constructor(v, path, doc, schemaType) { - if (v != null && v.constructor.name === 'Object') { - v = Object.keys(v).reduce((arr, key) => arr.concat([[key, v[key]]]), []); - } - super(v); - - this.$__parent = doc != null && doc.$__ != null ? doc : null; - this.$__path = path; - this.$__schemaType = schemaType == null ? new Mixed(path) : schemaType; - - this.$__runDeferred(); - } - - $init(key, value) { - checkValidKey(key); - - super.set(key, value); - - if (value != null && value.$isSingleNested) { - value.$basePath = this.$__path + '.' + key; - } - } - - $__set(key, value) { - super.set(key, value); - } - - get(key, options) { - options = options || {}; - if (options.getters === false) { - return super.get(key); - } - return this.$__schemaType.applyGetters(super.get(key), this.$__parent); - } - - set(key, value) { - checkValidKey(key); - value = handleSpreadDoc(value); - - // Weird, but because you can't assign to `this` before calling `super()` - // you can't get access to `$__schemaType` to cast in the initial call to - // `set()` from the `super()` constructor. - - if (this.$__schemaType == null) { - this.$__deferred = this.$__deferred || []; - this.$__deferred.push({ key: key, value: value }); - return; - } - - const fullPath = this.$__path + '.' + key; - const populated = this.$__parent != null && this.$__parent.$__ ? - this.$__parent.populated(fullPath) || this.$__parent.populated(this.$__path) : - null; - const priorVal = this.get(key); - - if (populated != null) { - if (value.$__ == null) { - value = new populated.options[populateModelSymbol](value); - } - value.$__.wasPopulated = true; - } else { - try { - value = this.$__schemaType. - applySetters(value, this.$__parent, false, this.get(key)); - } catch (error) { - if (this.$__parent != null && this.$__parent.$__ != null) { - this.$__parent.invalidate(fullPath, error); - return; - } - throw error; - } - } - - super.set(key, value); - - if (value != null && value.$isSingleNested) { - value.$basePath = this.$__path + '.' + key; - } - - const parent = this.$__parent; - if (parent != null && parent.$__ != null && !deepEqual(value, priorVal)) { - parent.markModified(this.$__path + '.' + key); - } - } - - delete(key) { - this.set(key, undefined); - super.delete(key); - } - - toBSON() { - return new Map(this); - } - - toObject(options) { - if (get(options, 'flattenMaps')) { - const ret = {}; - const keys = this.keys(); - for (const key of keys) { - ret[key] = this.get(key); - } - return ret; - } - - return new Map(this); - } - - toJSON() { - const ret = {}; - const keys = this.keys(); - for (const key of keys) { - ret[key] = this.get(key); - } - return ret; - } - - inspect() { - return new Map(this); - } - - $__runDeferred() { - if (!this.$__deferred) { - return; - } - - for (const keyValueObject of this.$__deferred) { - this.set(keyValueObject.key, keyValueObject.value); - } - - this.$__deferred = null; - } -} - -if (util.inspect.custom) { - Object.defineProperty(MongooseMap.prototype, util.inspect.custom, { - enumerable: false, - writable: false, - configurable: false, - value: MongooseMap.prototype.inspect - }); -} - -Object.defineProperty(MongooseMap.prototype, '$__set', { - enumerable: false, - writable: true, - configurable: false -}); - -Object.defineProperty(MongooseMap.prototype, '$__parent', { - enumerable: false, - writable: true, - configurable: false -}); - -Object.defineProperty(MongooseMap.prototype, '$__path', { - enumerable: false, - writable: true, - configurable: false -}); - -Object.defineProperty(MongooseMap.prototype, '$__schemaType', { - enumerable: false, - writable: true, - configurable: false -}); - -Object.defineProperty(MongooseMap.prototype, '$isMongooseMap', { - enumerable: false, - writable: false, - configurable: false, - value: true -}); - -Object.defineProperty(MongooseMap.prototype, '$__deferredCalls', { - enumerable: false, - writable: false, - configurable: false, - value: true -}); - -/*! - * Since maps are stored as objects under the hood, keys must be strings - * and can't contain any invalid characters - */ - -function checkValidKey(key) { - const keyType = typeof key; - if (keyType !== 'string') { - throw new TypeError(`Mongoose maps only support string keys, got ${keyType}`); - } - if (key.startsWith('$')) { - throw new Error(`Mongoose maps do not support keys that start with "$", got "${key}"`); - } - if (key.includes('.')) { - throw new Error(`Mongoose maps do not support keys that contain ".", got "${key}"`); - } - if (specialProperties.has(key)) { - throw new Error(`Mongoose maps do not support reserved key name "${key}"`); - } -} - -module.exports = MongooseMap; diff --git a/node_modules/mongoose/lib/types/objectid.js b/node_modules/mongoose/lib/types/objectid.js deleted file mode 100644 index 4c3f8b4..0000000 --- a/node_modules/mongoose/lib/types/objectid.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * ObjectId type constructor - * - * ####Example - * - * var id = new mongoose.Types.ObjectId; - * - * @constructor ObjectId - */ - -'use strict'; - -const ObjectId = require('../driver').get().ObjectId; -const objectIdSymbol = require('../helpers/symbols').objectIdSymbol; - -/*! - * Getter for convenience with populate, see gh-6115 - */ - -Object.defineProperty(ObjectId.prototype, '_id', { - enumerable: false, - configurable: true, - get: function() { - return this; - } -}); - -ObjectId.prototype[objectIdSymbol] = true; - -module.exports = ObjectId; diff --git a/node_modules/mongoose/lib/types/subdocument.js b/node_modules/mongoose/lib/types/subdocument.js deleted file mode 100644 index 521237a..0000000 --- a/node_modules/mongoose/lib/types/subdocument.js +++ /dev/null @@ -1,282 +0,0 @@ -'use strict'; - -const Document = require('../document'); -const immediate = require('../helpers/immediate'); -const internalToObjectOptions = require('../options').internalToObjectOptions; -const promiseOrCallback = require('../helpers/promiseOrCallback'); - -const documentArrayParent = require('../helpers/symbols').documentArrayParent; - -module.exports = Subdocument; - -/** - * Subdocument constructor. - * - * @inherits Document - * @api private - */ - -function Subdocument(value, fields, parent, skipId, options) { - this.$isSingleNested = true; - - const hasPriorDoc = options != null && options.priorDoc; - let initedPaths = null; - if (hasPriorDoc) { - this._doc = Object.assign({}, options.priorDoc._doc); - delete this._doc[this.schema.options.discriminatorKey]; - initedPaths = Object.keys(options.priorDoc._doc || {}). - filter(key => key !== this.schema.options.discriminatorKey); - } - if (parent != null) { - // If setting a nested path, should copy isNew from parent re: gh-7048 - options = Object.assign({}, options, { isNew: parent.isNew }); - } - Document.call(this, value, fields, skipId, options); - - if (hasPriorDoc) { - for (const key of initedPaths) { - if (!this.$__.activePaths.states.modify[key] && - !this.$__.activePaths.states.default[key] && - !this.$__.$setCalled.has(key)) { - const schematype = this.schema.path(key); - const def = schematype == null ? void 0 : schematype.getDefault(this); - if (def === void 0) { - delete this._doc[key]; - } else { - this._doc[key] = def; - this.$__.activePaths.default(key); - } - } - } - } -} - -Subdocument.prototype = Object.create(Document.prototype); - -Subdocument.prototype.toBSON = function() { - return this.toObject(internalToObjectOptions); -}; - -/** - * Used as a stub for middleware - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @return {Promise} resolved Promise - * @api private - */ - -Subdocument.prototype.save = function(options, fn) { - if (typeof options === 'function') { - fn = options; - options = {}; - } - options = options || {}; - - if (!options.suppressWarning) { - console.warn('mongoose: calling `save()` on a subdoc does **not** save ' + - 'the document to MongoDB, it only runs save middleware. ' + - 'Use `subdoc.save({ suppressWarning: true })` to hide this warning ' + - 'if you\'re sure this behavior is right for your app.'); - } - - return promiseOrCallback(fn, cb => { - this.$__save(cb); - }); -}; - -/** - * Used as a stub for middleware - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @method $__save - * @api private - */ - -Subdocument.prototype.$__save = function(fn) { - return immediate(() => fn(null, this)); -}; - -Subdocument.prototype.$isValid = function(path) { - if (this.$parent && this.$basePath) { - return this.$parent.$isValid([this.$basePath, path].join('.')); - } - return Document.prototype.$isValid.call(this, path); -}; - -Subdocument.prototype.markModified = function(path) { - Document.prototype.markModified.call(this, path); - - if (this.$parent && this.$basePath) { - if (this.$parent.isDirectModified(this.$basePath)) { - return; - } - this.$parent.markModified([this.$basePath, path].join('.'), this); - } -}; - -Subdocument.prototype.isModified = function(paths, modifiedPaths) { - if (this.$parent && this.$basePath) { - if (Array.isArray(paths) || typeof paths === 'string') { - paths = (Array.isArray(paths) ? paths : paths.split(' ')); - paths = paths.map(p => [this.$basePath, p].join('.')); - } - - return this.$parent.isModified(paths, modifiedPaths); - } - - return Document.prototype.isModified.call(this, paths, modifiedPaths); -}; - -/** - * Marks a path as valid, removing existing validation errors. - * - * @param {String} path the field to mark as valid - * @api private - * @method $markValid - * @receiver Subdocument - */ - -Subdocument.prototype.$markValid = function(path) { - Document.prototype.$markValid.call(this, path); - if (this.$parent && this.$basePath) { - this.$parent.$markValid([this.$basePath, path].join('.')); - } -}; - -/*! - * ignore - */ - -Subdocument.prototype.invalidate = function(path, err, val) { - // Hack: array subdocuments' validationError is equal to the owner doc's, - // so validating an array subdoc gives the top-level doc back. Temporary - // workaround for #5208 so we don't have circular errors. - if (err !== this.ownerDocument().$__.validationError) { - Document.prototype.invalidate.call(this, path, err, val); - } - - if (this.$parent && this.$basePath) { - this.$parent.invalidate([this.$basePath, path].join('.'), err, val); - } else if (err.kind === 'cast' || err.name === 'CastError') { - throw err; - } -}; - -/*! - * ignore - */ - -Subdocument.prototype.$ignore = function(path) { - Document.prototype.$ignore.call(this, path); - if (this.$parent && this.$basePath) { - this.$parent.$ignore([this.$basePath, path].join('.')); - } -}; - -/** - * Returns the top level document of this sub-document. - * - * @return {Document} - */ - -Subdocument.prototype.ownerDocument = function() { - if (this.$__.ownerDocument) { - return this.$__.ownerDocument; - } - - let parent = this.$parent; - if (!parent) { - return this; - } - - while (parent.$parent || parent[documentArrayParent]) { - parent = parent.$parent || parent[documentArrayParent]; - } - - this.$__.ownerDocument = parent; - return this.$__.ownerDocument; -}; - -/** - * Returns this sub-documents parent document. - * - * @api public - */ - -Subdocument.prototype.parent = function() { - return this.$parent; -}; - -/*! - * no-op for hooks - */ - -Subdocument.prototype.$__remove = function(cb) { - return cb(null, this); -}; - -/** - * Null-out this subdoc - * - * @param {Object} [options] - * @param {Function} [callback] optional callback for compatibility with Document.prototype.remove - */ - -Subdocument.prototype.remove = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = null; - } - - registerRemoveListener(this); - - // If removing entire doc, no need to remove subdoc - if (!options || !options.noop) { - this.$parent.set(this.$basePath, null); - } - - if (typeof callback === 'function') { - callback(null); - } -}; - -/*! - * ignore - */ - -Subdocument.prototype.populate = function() { - throw new Error('Mongoose does not support calling populate() on nested ' + - 'docs. Instead of `doc.nested.populate("path")`, use ' + - '`doc.populate("nested.path")`'); -}; - -/*! - * Registers remove event listeners for triggering - * on subdocuments. - * - * @param {Subdocument} sub - * @api private - */ - -function registerRemoveListener(sub) { - let owner = sub.ownerDocument(); - - function emitRemove() { - owner.removeListener('save', emitRemove); - owner.removeListener('remove', emitRemove); - sub.emit('remove', sub); - sub.constructor.emit('remove', sub); - owner = sub = null; - } - - owner.on('save', emitRemove); - owner.on('remove', emitRemove); -} diff --git a/node_modules/mongoose/lib/utils.js b/node_modules/mongoose/lib/utils.js deleted file mode 100644 index 23411ee..0000000 --- a/node_modules/mongoose/lib/utils.js +++ /dev/null @@ -1,901 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -const ms = require('ms'); -const mpath = require('mpath'); -const sliced = require('sliced'); -const Buffer = require('safe-buffer').Buffer; -const Decimal = require('./types/decimal128'); -const ObjectId = require('./types/objectid'); -const PopulateOptions = require('./options/PopulateOptions'); -const clone = require('./helpers/clone'); -const isObject = require('./helpers/isObject'); -const isBsonType = require('./helpers/isBsonType'); -const getFunctionName = require('./helpers/getFunctionName'); -const isMongooseObject = require('./helpers/isMongooseObject'); -const promiseOrCallback = require('./helpers/promiseOrCallback'); -const specialProperties = require('./helpers/specialProperties'); - -let Document; - -exports.specialProperties = specialProperties; - -/*! - * Produces a collection name from model `name`. By default, just returns - * the model name - * - * @param {String} name a model name - * @param {Function} pluralize function that pluralizes the collection name - * @return {String} a collection name - * @api private - */ - -exports.toCollectionName = function(name, pluralize) { - if (name === 'system.profile') { - return name; - } - if (name === 'system.indexes') { - return name; - } - if (typeof pluralize === 'function') { - return pluralize(name); - } - return name; -}; - -/*! - * Determines if `a` and `b` are deep equal. - * - * Modified from node/lib/assert.js - * - * @param {any} a a value to compare to `b` - * @param {any} b a value to compare to `a` - * @return {Boolean} - * @api private - */ - -exports.deepEqual = function deepEqual(a, b) { - if (a === b) { - return true; - } - - if (a instanceof Date && b instanceof Date) { - return a.getTime() === b.getTime(); - } - - if ((isBsonType(a, 'ObjectID') && isBsonType(b, 'ObjectID')) || - (isBsonType(a, 'Decimal128') && isBsonType(b, 'Decimal128'))) { - return a.toString() === b.toString(); - } - - if (a instanceof RegExp && b instanceof RegExp) { - return a.source === b.source && - a.ignoreCase === b.ignoreCase && - a.multiline === b.multiline && - a.global === b.global; - } - - if (typeof a !== 'object' && typeof b !== 'object') { - return a == b; - } - - if (a === null || b === null || a === undefined || b === undefined) { - return false; - } - - if (a.prototype !== b.prototype) { - return false; - } - - // Handle MongooseNumbers - if (a instanceof Number && b instanceof Number) { - return a.valueOf() === b.valueOf(); - } - - if (Buffer.isBuffer(a)) { - return exports.buffer.areEqual(a, b); - } - - if (isMongooseObject(a)) { - a = a.toObject(); - } - if (isMongooseObject(b)) { - b = b.toObject(); - } - - let ka; - let kb; - let key; - let i; - try { - ka = Object.keys(a); - kb = Object.keys(b); - } catch (e) { - // happens when one is a string literal and the other isn't - return false; - } - - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length !== kb.length) { - return false; - } - - // the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - - // ~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] !== kb[i]) { - return false; - } - } - - // equivalent values for every corresponding key, and - // ~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!deepEqual(a[key], b[key])) { - return false; - } - } - - return true; -}; - -/*! - * Get the last element of an array - */ - -exports.last = function(arr) { - if (arr.length > 0) { - return arr[arr.length - 1]; - } - return void 0; -}; - -exports.clone = clone; - -/*! - * ignore - */ - -exports.promiseOrCallback = promiseOrCallback; - -/*! - * ignore - */ - -exports.omit = function omit(obj, keys) { - if (keys == null) { - return Object.assign({}, obj); - } - if (!Array.isArray(keys)) { - keys = [keys]; - } - - const ret = Object.assign({}, obj); - for (const key of keys) { - delete ret[key]; - } - return ret; -}; - - -/*! - * Shallow copies defaults into options. - * - * @param {Object} defaults - * @param {Object} options - * @return {Object} the merged object - * @api private - */ - -exports.options = function(defaults, options) { - const keys = Object.keys(defaults); - let i = keys.length; - let k; - - options = options || {}; - - while (i--) { - k = keys[i]; - if (!(k in options)) { - options[k] = defaults[k]; - } - } - - return options; -}; - -/*! - * Generates a random string - * - * @api private - */ - -exports.random = function() { - return Math.random().toString().substr(3); -}; - -/*! - * Merges `from` into `to` without overwriting existing properties. - * - * @param {Object} to - * @param {Object} from - * @api private - */ - -exports.merge = function merge(to, from, options, path) { - options = options || {}; - - const keys = Object.keys(from); - let i = 0; - const len = keys.length; - let key; - - path = path || ''; - const omitNested = options.omitNested || {}; - - while (i < len) { - key = keys[i++]; - if (options.omit && options.omit[key]) { - continue; - } - if (omitNested[path]) { - continue; - } - if (specialProperties.has(key)) { - continue; - } - if (to[key] == null) { - to[key] = from[key]; - } else if (exports.isObject(from[key])) { - if (!exports.isObject(to[key])) { - to[key] = {}; - } - if (from[key] != null) { - if (from[key].instanceOfSchema) { - if (to[key].instanceOfSchema) { - to[key].add(from[key].clone()); - } else { - to[key] = from[key].clone(); - } - continue; - } else if (from[key] instanceof ObjectId) { - to[key] = new ObjectId(from[key]); - continue; - } - } - merge(to[key], from[key], options, path ? path + '.' + key : key); - } else if (options.overwrite) { - to[key] = from[key]; - } - } -}; - -/*! - * Applies toObject recursively. - * - * @param {Document|Array|Object} obj - * @return {Object} - * @api private - */ - -exports.toObject = function toObject(obj) { - Document || (Document = require('./document')); - let ret; - - if (obj == null) { - return obj; - } - - if (obj instanceof Document) { - return obj.toObject(); - } - - if (Array.isArray(obj)) { - ret = []; - - for (const doc of obj) { - ret.push(toObject(doc)); - } - - return ret; - } - - if (exports.isPOJO(obj)) { - ret = {}; - - for (const k in obj) { - if (specialProperties.has(k)) { - continue; - } - ret[k] = toObject(obj[k]); - } - - return ret; - } - - return obj; -}; - -exports.isObject = isObject; - -/*! - * Determines if `arg` is a plain old JavaScript object (POJO). Specifically, - * `arg` must be an object but not an instance of any special class, like String, - * ObjectId, etc. - * - * `Object.getPrototypeOf()` is part of ES5: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf - * - * @param {Object|Array|String|Function|RegExp|any} arg - * @api private - * @return {Boolean} - */ - -exports.isPOJO = function isPOJO(arg) { - if (arg == null || typeof arg !== 'object') { - return false; - } - const proto = Object.getPrototypeOf(arg); - // Prototype may be null if you used `Object.create(null)` - // Checking `proto`'s constructor is safe because `getPrototypeOf()` - // explicitly crosses the boundary from object data to object metadata - return !proto || proto.constructor.name === 'Object'; -}; - -/*! - * Determines if `obj` is a built-in object like an array, date, boolean, - * etc. - */ - -exports.isNativeObject = function(arg) { - return Array.isArray(arg) || - arg instanceof Date || - arg instanceof Boolean || - arg instanceof Number || - arg instanceof String; -}; - -/*! - * Determines if `val` is an object that has no own keys - */ - -exports.isEmptyObject = function(val) { - return val != null && - typeof val === 'object' && - Object.keys(val).length === 0; -}; - -/*! - * Search if `obj` or any POJOs nested underneath `obj` has a property named - * `key` - */ - -exports.hasKey = function hasKey(obj, key) { - const props = Object.keys(obj); - for (const prop of props) { - if (prop === key) { - return true; - } - if (exports.isPOJO(obj[prop]) && exports.hasKey(obj[prop], key)) { - return true; - } - } - return false; -}; - -/*! - * A faster Array.prototype.slice.call(arguments) alternative - * @api private - */ - -exports.args = sliced; - -/*! - * process.nextTick helper. - * - * Wraps `callback` in a try/catch + nextTick. - * - * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback. - * - * @param {Function} callback - * @api private - */ - -exports.tick = function tick(callback) { - if (typeof callback !== 'function') { - return; - } - return function() { - try { - callback.apply(this, arguments); - } catch (err) { - // only nextTick on err to get out of - // the event loop and avoid state corruption. - process.nextTick(function() { - throw err; - }); - } - }; -}; - -/*! - * Returns true if `v` is an object that can be serialized as a primitive in - * MongoDB - */ - -exports.isMongooseType = function(v) { - return v instanceof ObjectId || v instanceof Decimal || v instanceof Buffer; -}; - -exports.isMongooseObject = isMongooseObject; - -/*! - * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB. - * - * @param {Object} object - * @api private - */ - -exports.expires = function expires(object) { - if (!(object && object.constructor.name === 'Object')) { - return; - } - if (!('expires' in object)) { - return; - } - - let when; - if (typeof object.expires !== 'string') { - when = object.expires; - } else { - when = Math.round(ms(object.expires) / 1000); - } - object.expireAfterSeconds = when; - delete object.expires; -}; - -/*! - * populate helper - */ - -exports.populate = function populate(path, select, model, match, options, subPopulate, justOne, count) { - // might have passed an object specifying all arguments - let obj = null; - if (arguments.length === 1) { - if (path instanceof PopulateOptions) { - return [path]; - } - - if (Array.isArray(path)) { - const singles = makeSingles(path); - return singles.map(o => exports.populate(o)[0]); - } - - if (exports.isObject(path)) { - obj = Object.assign({}, path); - } else { - obj = { path: path }; - } - } else if (typeof model === 'object') { - obj = { - path: path, - select: select, - match: model, - options: match - }; - } else { - obj = { - path: path, - select: select, - model: model, - match: match, - options: options, - populate: subPopulate, - justOne: justOne, - count: count - }; - } - - if (typeof obj.path !== 'string') { - throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`'); - } - - return _populateObj(obj); - - // The order of select/conditions args is opposite Model.find but - // necessary to keep backward compatibility (select could be - // an array, string, or object literal). - function makeSingles(arr) { - const ret = []; - arr.forEach(function(obj) { - if (/[\s]/.test(obj.path)) { - const paths = obj.path.split(' '); - paths.forEach(function(p) { - const copy = Object.assign({}, obj); - copy.path = p; - ret.push(copy); - }); - } else { - ret.push(obj); - } - }); - - return ret; - } -}; - -function _populateObj(obj) { - if (Array.isArray(obj.populate)) { - const ret = []; - obj.populate.forEach(function(obj) { - if (/[\s]/.test(obj.path)) { - const copy = Object.assign({}, obj); - const paths = copy.path.split(' '); - paths.forEach(function(p) { - copy.path = p; - ret.push(exports.populate(copy)[0]); - }); - } else { - ret.push(exports.populate(obj)[0]); - } - }); - obj.populate = exports.populate(ret); - } else if (obj.populate != null && typeof obj.populate === 'object') { - obj.populate = exports.populate(obj.populate); - } - - const ret = []; - const paths = obj.path.split(' '); - if (obj.options != null) { - obj.options = exports.clone(obj.options); - } - - for (const path of paths) { - ret.push(new PopulateOptions(Object.assign({}, obj, { path: path }))); - } - - return ret; -} - -/*! - * Return the value of `obj` at the given `path`. - * - * @param {String} path - * @param {Object} obj - */ - -exports.getValue = function(path, obj, map) { - return mpath.get(path, obj, '_doc', map); -}; - -/*! - * Sets the value of `obj` at the given `path`. - * - * @param {String} path - * @param {Anything} val - * @param {Object} obj - */ - -exports.setValue = function(path, val, obj, map, _copying) { - mpath.set(path, val, obj, '_doc', map, _copying); -}; - -/*! - * Returns an array of values from object `o`. - * - * @param {Object} o - * @return {Array} - * @private - */ - -exports.object = {}; -exports.object.vals = function vals(o) { - const keys = Object.keys(o); - let i = keys.length; - const ret = []; - - while (i--) { - ret.push(o[keys[i]]); - } - - return ret; -}; - -/*! - * @see exports.options - */ - -exports.object.shallowCopy = exports.options; - -/*! - * Safer helper for hasOwnProperty checks - * - * @param {Object} obj - * @param {String} prop - */ - -const hop = Object.prototype.hasOwnProperty; -exports.object.hasOwnProperty = function(obj, prop) { - return hop.call(obj, prop); -}; - -/*! - * Determine if `val` is null or undefined - * - * @return {Boolean} - */ - -exports.isNullOrUndefined = function(val) { - return val === null || val === undefined; -}; - -/*! - * ignore - */ - -exports.array = {}; - -/*! - * Flattens an array. - * - * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4] - * - * @param {Array} arr - * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsy value, the item will not be included in the results. - * @return {Array} - * @private - */ - -exports.array.flatten = function flatten(arr, filter, ret) { - ret || (ret = []); - - arr.forEach(function(item) { - if (Array.isArray(item)) { - flatten(item, filter, ret); - } else { - if (!filter || filter(item)) { - ret.push(item); - } - } - }); - - return ret; -}; - -/*! - * ignore - */ - -const _hasOwnProperty = Object.prototype.hasOwnProperty; - -exports.hasUserDefinedProperty = function(obj, key) { - if (obj == null) { - return false; - } - - if (Array.isArray(key)) { - for (const k of key) { - if (exports.hasUserDefinedProperty(obj, k)) { - return true; - } - } - return false; - } - - if (_hasOwnProperty.call(obj, key)) { - return true; - } - if (typeof obj === 'object' && key in obj) { - const v = obj[key]; - return v !== Object.prototype[key] && v !== Array.prototype[key]; - } - - return false; -}; - -/*! - * ignore - */ - -const MAX_ARRAY_INDEX = Math.pow(2, 32) - 1; - -exports.isArrayIndex = function(val) { - if (typeof val === 'number') { - return val >= 0 && val <= MAX_ARRAY_INDEX; - } - if (typeof val === 'string') { - if (!/^\d+$/.test(val)) { - return false; - } - val = +val; - return val >= 0 && val <= MAX_ARRAY_INDEX; - } - - return false; -}; - -/*! - * Removes duplicate values from an array - * - * [1, 2, 3, 3, 5] => [1, 2, 3, 5] - * [ ObjectId("550988ba0c19d57f697dc45e"), ObjectId("550988ba0c19d57f697dc45e") ] - * => [ObjectId("550988ba0c19d57f697dc45e")] - * - * @param {Array} arr - * @return {Array} - * @private - */ - -exports.array.unique = function(arr) { - const primitives = {}; - const ids = {}; - const ret = []; - - for (const item of arr) { - if (typeof item === 'number' || typeof item === 'string' || item == null) { - if (primitives[item]) { - continue; - } - ret.push(item); - primitives[item] = true; - } else if (item instanceof ObjectId) { - if (ids[item.toString()]) { - continue; - } - ret.push(item); - ids[item.toString()] = true; - } else { - ret.push(item); - } - } - - return ret; -}; - -/*! - * Determines if two buffers are equal. - * - * @param {Buffer} a - * @param {Object} b - */ - -exports.buffer = {}; -exports.buffer.areEqual = function(a, b) { - if (!Buffer.isBuffer(a)) { - return false; - } - if (!Buffer.isBuffer(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - for (let i = 0, len = a.length; i < len; ++i) { - if (a[i] !== b[i]) { - return false; - } - } - return true; -}; - -exports.getFunctionName = getFunctionName; -/*! - * Decorate buffers - */ - -exports.decorate = function(destination, source) { - for (const key in source) { - if (specialProperties.has(key)) { - continue; - } - destination[key] = source[key]; - } -}; - -/** - * merges to with a copy of from - * - * @param {Object} to - * @param {Object} fromObj - * @api private - */ - -exports.mergeClone = function(to, fromObj) { - if (isMongooseObject(fromObj)) { - fromObj = fromObj.toObject({ - transform: false, - virtuals: false, - depopulate: true, - getters: false, - flattenDecimals: false - }); - } - const keys = Object.keys(fromObj); - const len = keys.length; - let i = 0; - let key; - - while (i < len) { - key = keys[i++]; - if (specialProperties.has(key)) { - continue; - } - if (typeof to[key] === 'undefined') { - to[key] = exports.clone(fromObj[key], { - transform: false, - virtuals: false, - depopulate: true, - getters: false, - flattenDecimals: false - }); - } else { - let val = fromObj[key]; - if (val != null && val.valueOf && !(val instanceof Date)) { - val = val.valueOf(); - } - if (exports.isObject(val)) { - let obj = val; - if (isMongooseObject(val) && !val.isMongooseBuffer) { - obj = obj.toObject({ - transform: false, - virtuals: false, - depopulate: true, - getters: false, - flattenDecimals: false - }); - } - if (val.isMongooseBuffer) { - obj = Buffer.from(obj); - } - exports.mergeClone(to[key], obj); - } else { - to[key] = exports.clone(val, { - flattenDecimals: false - }); - } - } - } -}; - -/** - * Executes a function on each element of an array (like _.each) - * - * @param {Array} arr - * @param {Function} fn - * @api private - */ - -exports.each = function(arr, fn) { - for (const item of arr) { - fn(item); - } -}; - -/*! - * ignore - */ - -exports.getOption = function(name) { - const sources = Array.prototype.slice.call(arguments, 1); - - for (const source of sources) { - if (source[name] != null) { - return source[name]; - } - } - - return null; -}; - -/*! - * ignore - */ - -exports.noop = function() {}; diff --git a/node_modules/mongoose/lib/validoptions.js b/node_modules/mongoose/lib/validoptions.js deleted file mode 100644 index 9464e4d..0000000 --- a/node_modules/mongoose/lib/validoptions.js +++ /dev/null @@ -1,30 +0,0 @@ - -/*! - * Valid mongoose options - */ - -'use strict'; - -const VALID_OPTIONS = Object.freeze([ - 'applyPluginsToChildSchemas', - 'applyPluginsToDiscriminators', - 'autoIndex', - 'bufferCommands', - 'cloneSchemas', - 'debug', - 'maxTimeMS', - 'objectIdGetter', - 'runValidators', - 'selectPopulatedPaths', - 'strict', - 'toJSON', - 'toObject', - 'useCreateIndex', - 'useFindAndModify', - 'useNewUrlParser', - 'usePushEach', - 'useUnifiedTopology', - 'typePojoToMixed' -]); - -module.exports = VALID_OPTIONS; diff --git a/node_modules/mongoose/lib/virtualtype.js b/node_modules/mongoose/lib/virtualtype.js deleted file mode 100644 index f91438a..0000000 --- a/node_modules/mongoose/lib/virtualtype.js +++ /dev/null @@ -1,168 +0,0 @@ -'use strict'; - -/** - * VirtualType constructor - * - * This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`. - * - * ####Example: - * - * const fullname = schema.virtual('fullname'); - * fullname instanceof mongoose.VirtualType // true - * - * @param {Object} options - * @param {string|function} [options.ref] if `ref` is not nullish, this becomes a [populated virtual](/docs/populate.html#populate-virtuals) - * @param {string|function} [options.localField] the local field to populate on if this is a populated virtual. - * @param {string|function} [options.foreignField] the foreign field to populate on if this is a populated virtual. - * @param {boolean} [options.justOne=false] by default, a populated virtual is an array. If you set `justOne`, the populated virtual will be a single doc or `null`. - * @param {boolean} [options.getters=false] if you set this to `true`, Mongoose will call any custom getters you defined on this virtual - * @param {boolean} [options.count=false] if you set this to `true`, `populate()` will set this virtual to the number of populated documents, as opposed to the documents themselves, using [`Query#countDocuments()`](./api.html#query_Query-countDocuments) - * @param {Object|Function} [options.match=null] add an extra match condition to `populate()` - * @param {Number} [options.limit=null] add a default `limit` to the `populate()` query - * @param {Number} [options.skip=null] add a default `skip` to the `populate()` query - * @param {Number} [options.perDocumentLimit=null] For legacy reasons, `limit` with `populate()` may give incorrect results because it only executes a single query for every document being populated. If you set `perDocumentLimit`, Mongoose will ensure correct `limit` per document by executing a separate query for each document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` will execute 2 additional queries if `.find()` returns 2 documents. - * @param {Object} [options.options=null] Additional options like `limit` and `lean`. - * @api public - */ - -function VirtualType(options, name) { - this.path = name; - this.getters = []; - this.setters = []; - this.options = Object.assign({}, options); -} - -/** - * If no getters/getters, add a default - * - * @param {Function} fn - * @return {VirtualType} this - * @api private - */ - -VirtualType.prototype._applyDefaultGetters = function() { - if (this.getters.length > 0 || this.setters.length > 0) { - return; - } - - const path = this.path; - const internalProperty = '$' + path; - this.getters.push(function() { - return this[internalProperty]; - }); - this.setters.push(function(v) { - this[internalProperty] = v; - }); -}; - -/*! - * ignore - */ - -VirtualType.prototype.clone = function() { - const clone = new VirtualType(this.options, this.path); - clone.getters = [].concat(this.getters); - clone.setters = [].concat(this.setters); - return clone; -}; - -/** - * Adds a custom getter to this virtual. - * - * Mongoose calls the getter function with 3 parameters: - * - * - `value`: the value returned by the previous getter. If there is only one getter, `value` will be `undefined`. - * - `virtual`: the virtual object you called `.get()` on - * - `doc`: the document this virtual is attached to. Equivalent to `this`. - * - * ####Example: - * - * var virtual = schema.virtual('fullname'); - * virtual.get(function(value, virtual, doc) { - * return this.name.first + ' ' + this.name.last; - * }); - * - * @param {Function(Any, VirtualType, Document)} fn - * @return {VirtualType} this - * @api public - */ - -VirtualType.prototype.get = function(fn) { - this.getters.push(fn); - return this; -}; - -/** - * Adds a custom setter to this virtual. - * - * Mongoose calls the setter function with 3 parameters: - * - * - `value`: the value being set - * - `virtual`: the virtual object you're calling `.set()` on - * - `doc`: the document this virtual is attached to. Equivalent to `this`. - * - * ####Example: - * - * const virtual = schema.virtual('fullname'); - * virtual.set(function(value, virtual, doc) { - * var parts = value.split(' '); - * this.name.first = parts[0]; - * this.name.last = parts[1]; - * }); - * - * const Model = mongoose.model('Test', schema); - * const doc = new Model(); - * // Calls the setter with `value = 'Jean-Luc Picard'` - * doc.fullname = 'Jean-Luc Picard'; - * doc.name.first; // 'Jean-Luc' - * doc.name.last; // 'Picard' - * - * @param {Function(Any, VirtualType, Document)} fn - * @return {VirtualType} this - * @api public - */ - -VirtualType.prototype.set = function(fn) { - this.setters.push(fn); - return this; -}; - -/** - * Applies getters to `value`. - * - * @param {Object} value - * @param {Document} doc The document this virtual is attached to - * @return {any} the value after applying all getters - * @api public - */ - -VirtualType.prototype.applyGetters = function(value, doc) { - let v = value; - for (let l = this.getters.length - 1; l >= 0; l--) { - v = this.getters[l].call(doc, v, this, doc); - } - return v; -}; - -/** - * Applies setters to `value`. - * - * @param {Object} value - * @param {Document} doc - * @return {any} the value after applying all setters - * @api public - */ - -VirtualType.prototype.applySetters = function(value, doc) { - let v = value; - for (let l = this.setters.length - 1; l >= 0; l--) { - v = this.setters[l].call(doc, v, this, doc); - } - return v; -}; - -/*! - * exports - */ - -module.exports = VirtualType; diff --git a/node_modules/mongoose/node_modules/mongodb/HISTORY.md b/node_modules/mongoose/node_modules/mongodb/HISTORY.md deleted file mode 100644 index 9b36b8d..0000000 --- a/node_modules/mongoose/node_modules/mongodb/HISTORY.md +++ /dev/null @@ -1,2723 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - - -## [3.5.7](https://github.com/mongodb/node-mongodb-native/compare/v3.5.6...v3.5.7) (2020-04-29) - - -### Bug Fixes - -* limit growth of server sessions through lazy acquisition ([3d05a6d](https://github.com/mongodb/node-mongodb-native/commit/3d05a6d)) -* remove circular dependency warnings on node 14 ([56a1b8a](https://github.com/mongodb/node-mongodb-native/commit/56a1b8a)) - - - - -## [3.5.6](https://github.com/mongodb/node-mongodb-native/compare/v3.5.5...v3.5.6) (2020-04-14) - - -### Bug Fixes - -* always return empty array for selection on unknown topology ([f9e786a](https://github.com/mongodb/node-mongodb-native/commit/f9e786a)) -* createCollection only uses listCollections in strict mode ([d368f12](https://github.com/mongodb/node-mongodb-native/commit/d368f12)) -* don't throw if `withTransaction()` callback rejects with a null reason ([153646c](https://github.com/mongodb/node-mongodb-native/commit/153646c)) -* only mark server session dirty if the client session is alive ([611be8d](https://github.com/mongodb/node-mongodb-native/commit/611be8d)) -* polyfill for util.promisify ([1c4cf6c](https://github.com/mongodb/node-mongodb-native/commit/1c4cf6c)) -* single `readPreferenceTags` should be parsed as an array ([a50611b](https://github.com/mongodb/node-mongodb-native/commit/a50611b)) -* **cursor:** transforms should only be applied once to documents ([704f30a](https://github.com/mongodb/node-mongodb-native/commit/704f30a)) - - - - -## [3.5.5](https://github.com/mongodb/node-mongodb-native/compare/v3.5.4...v3.5.5) (2020-03-11) - - -### Bug Fixes - -* correctly use template string for connection string error message ([6238c84](https://github.com/mongodb/node-mongodb-native/commit/6238c84)) -* don't depend on private node api for `Timeout` wrapper ([3ddaa3e](https://github.com/mongodb/node-mongodb-native/commit/3ddaa3e)) -* multiple concurrent attempts to process the queue may fail ([f69f51c](https://github.com/mongodb/node-mongodb-native/commit/f69f51c)) -* pass optional promise lib to maybePromise ([cde11ec](https://github.com/mongodb/node-mongodb-native/commit/cde11ec)) -* **cursor:** hasNext consumes documents on cursor with limit ([ef04d00](https://github.com/mongodb/node-mongodb-native/commit/ef04d00)) - - - - -## [3.5.4](https://github.com/mongodb/node-mongodb-native/compare/v3.5.3...v3.5.4) (2020-02-25) - - -### Bug Fixes - -* **cmap:** don't run min connection thread if no minimum specified ([2d1b713](https://github.com/mongodb/node-mongodb-native/commit/2d1b713)) -* **sdam:** use ObjectId comparison to track maxElectionId ([a1e0849](https://github.com/mongodb/node-mongodb-native/commit/a1e0849)) -* **topology:** ensure selection wait queue is always processed ([bf701d6](https://github.com/mongodb/node-mongodb-native/commit/bf701d6)) -* **topology:** enter `STATE_CLOSING` before draining waitQueue ([494dffb](https://github.com/mongodb/node-mongodb-native/commit/494dffb)) -* don't consume first document when calling `hasNext` on cursor ([bb359a1](https://github.com/mongodb/node-mongodb-native/commit/bb359a1)) - - -### Features - -* add utility helper for returning promises or using callbacks ([ac9e4c9](https://github.com/mongodb/node-mongodb-native/commit/ac9e4c9)) - - - - -## [3.5.3](https://github.com/mongodb/node-mongodb-native/compare/v3.5.2...v3.5.3) (2020-02-12) - - -### Bug Fixes - -* **message-stream:** support multiple inbound message packets ([8388443](https://github.com/mongodb/node-mongodb-native/commit/8388443)) -* **server:** non-timeout network errors transition to Unknown state ([fa4b01b](https://github.com/mongodb/node-mongodb-native/commit/fa4b01b)) - - -### Features - -* **connection:** support exhaust behavior at the transport level ([9ccf268](https://github.com/mongodb/node-mongodb-native/commit/9ccf268)) - - - - -## [3.5.2](https://github.com/mongodb/node-mongodb-native/compare/v3.5.1...v3.5.2) (2020-01-20) - - -### Bug Fixes - -* properly handle err messages in MongoDB 2.6 servers ([0f4ab38](https://github.com/mongodb/node-mongodb-native/commit/0f4ab38)) -* **topology:** always emit SDAM unrecoverable errors ([57f158f](https://github.com/mongodb/node-mongodb-native/commit/57f158f)) - - - - -## [3.5.1](https://github.com/mongodb/node-mongodb-native/compare/v3.5.0...v3.5.1) (2020-01-17) - - -### Bug Fixes - -* **cmap:** accept all node TLS options as pool options ([5995d1d](https://github.com/mongodb/node-mongodb-native/commit/5995d1d)) -* **cmap:** error wait queue members on failed connection creation ([d13b153](https://github.com/mongodb/node-mongodb-native/commit/d13b153)) -* **connect:** listen to `secureConnect` for tls connections ([f8bdb8d](https://github.com/mongodb/node-mongodb-native/commit/f8bdb8d)) -* **transactions:** use options helper to resolve read preference ([9698a76](https://github.com/mongodb/node-mongodb-native/commit/9698a76)) -* **uri_parser:** TLS uri variants imply `ssl=true` ([c8d182e](https://github.com/mongodb/node-mongodb-native/commit/c8d182e)) - - - - -# [3.5.0](https://github.com/mongodb/node-mongodb-native/compare/v3.4.1...v3.5.0) (2020-01-14) - - -### Bug Fixes - -* copy `ssl` option to pool connection options ([563ced6](https://github.com/mongodb/node-mongodb-native/commit/563ced6)) -* destroy connections marked as closed on checkIn / checkOut ([2bd17a6](https://github.com/mongodb/node-mongodb-native/commit/2bd17a6)) -* ensure sync errors are thrown, and don't callback twice ([cca5b49](https://github.com/mongodb/node-mongodb-native/commit/cca5b49)) -* ignore connection errors during pool destruction ([b8805dc](https://github.com/mongodb/node-mongodb-native/commit/b8805dc)) -* not all message payloads are arrays of Buffer ([e4df5f4](https://github.com/mongodb/node-mongodb-native/commit/e4df5f4)) -* recover on network error during initial connect ([a13dc68](https://github.com/mongodb/node-mongodb-native/commit/a13dc68)) -* remove servers with me mismatch in `updateRsFromPrimary` ([95a772e](https://github.com/mongodb/node-mongodb-native/commit/95a772e)) -* report the correct platform in client metadata ([35d0274](https://github.com/mongodb/node-mongodb-native/commit/35d0274)) -* reschedule monitoring before emitting heartbeat events ([7fcbeb5](https://github.com/mongodb/node-mongodb-native/commit/7fcbeb5)) -* socket timeout for handshake should be `connectTimeoutMS` ([c83af9a](https://github.com/mongodb/node-mongodb-native/commit/c83af9a)) -* timed out streams should be destroyed on `timeout` event ([5319ff9](https://github.com/mongodb/node-mongodb-native/commit/5319ff9)) -* use remote address for stream identifier ([f13c20b](https://github.com/mongodb/node-mongodb-native/commit/f13c20b)) -* used weighted RTT calculation for server selection ([d446be5](https://github.com/mongodb/node-mongodb-native/commit/d446be5)) -* **execute-operation:** don't swallow synchronous errors ([0a2d4e9](https://github.com/mongodb/node-mongodb-native/commit/0a2d4e9)) -* **gridfs:** make a copy of chunk before writing to server ([b4ec5b8](https://github.com/mongodb/node-mongodb-native/commit/b4ec5b8)) - - -### Features - -* add a `withConnection` helper to the connection pool ([d59dced](https://github.com/mongodb/node-mongodb-native/commit/d59dced)) -* include `connectionId` for APM with new CMAP connection pool ([9bd360c](https://github.com/mongodb/node-mongodb-native/commit/9bd360c)) -* integrate CMAP connection pool into unified topology ([9dd3939](https://github.com/mongodb/node-mongodb-native/commit/9dd3939)) -* introduce `MongoServerSelectionError` ([0cf7ec9](https://github.com/mongodb/node-mongodb-native/commit/0cf7ec9)) -* introduce a class for tracking stream specific attributes ([f6bf82c](https://github.com/mongodb/node-mongodb-native/commit/f6bf82c)) -* introduce a new `Monitor` type for server monitoring ([2bfe2a1](https://github.com/mongodb/node-mongodb-native/commit/2bfe2a1)) -* relay all CMAP events to MongoClient ([1aea4de](https://github.com/mongodb/node-mongodb-native/commit/1aea4de)) -* support socket timeouts on a per-connection level ([93e8ad0](https://github.com/mongodb/node-mongodb-native/commit/93e8ad0)) - - - - -## [3.4.1](https://github.com/mongodb/node-mongodb-native/compare/v3.4.0...v3.4.1) (2019-12-19) - - -### Bug Fixes - -* **bulk:** use original indexes as map for current op index ([20800ac](https://github.com/mongodb/node-mongodb-native/commit/20800ac)) -* always check for network errors during SCRAM conversation ([e46a70e](https://github.com/mongodb/node-mongodb-native/commit/e46a70e)) - - - - -# [3.4.0](https://github.com/mongodb/node-mongodb-native/compare/v3.3.5...v3.4.0) (2019-12-10) - - -### Bug Fixes - -* **bulk:** use operation index from input to report operation error ([f713b13](https://github.com/mongodb/node-mongodb-native/commit/f713b13)) -* **command:** only add TransientTransactionError label when in a transaction ([478d714](https://github.com/mongodb/node-mongodb-native/commit/478d714)) -* **compression:** recalculate opcode after determine OP_COMPRESSED ([022f51b](https://github.com/mongodb/node-mongodb-native/commit/022f51b)) -* **connect:** connect with family 0 instead of family 4 ([db07366](https://github.com/mongodb/node-mongodb-native/commit/db07366)) -* **connection:** timed out connections should not be half closed ([850f4f5](https://github.com/mongodb/node-mongodb-native/commit/850f4f5)) -* **cursor:** call `initialize` after session support check ([e50c51a](https://github.com/mongodb/node-mongodb-native/commit/e50c51a)) -* **encryption:** autoEncryption must error on mongodb < 4.2 ([c274615](https://github.com/mongodb/node-mongodb-native/commit/c274615)) -* **encryption:** do not attempt to merge autoEncryption options ([e27fdf9](https://github.com/mongodb/node-mongodb-native/commit/e27fdf9)) -* **encryption:** encryption uses smaller batch size ([cb78e69](https://github.com/mongodb/node-mongodb-native/commit/cb78e69)) -* **encryption:** respect bypassAutoEncryption ([e927499](https://github.com/mongodb/node-mongodb-native/commit/e927499)) -* **encryption:** respect user bson options when using autoEncryption ([cb7a3f7](https://github.com/mongodb/node-mongodb-native/commit/cb7a3f7)) -* add calculated duration to server as `roundTripTime` ([cb107a8](https://github.com/mongodb/node-mongodb-native/commit/cb107a8)) -* **mongodb+srv:** respect overriding SRV-provided properties ([ea83360](https://github.com/mongodb/node-mongodb-native/commit/ea83360)) -* **pool:** flush workItems after next tick to avoid dupe selection ([3ec49e5](https://github.com/mongodb/node-mongodb-native/commit/3ec49e5)) -* **pool:** support a `drain` event for use with unified topology ([da931ea](https://github.com/mongodb/node-mongodb-native/commit/da931ea)) -* **scram:** verify server digest, ensuring mutual authentication ([806cd62](https://github.com/mongodb/node-mongodb-native/commit/806cd62)) -* **srv-poller:** always provide a valid number for `intervalMS` ([afb125f](https://github.com/mongodb/node-mongodb-native/commit/afb125f)) -* **topology:** correct logic for checking for sessions support ([8d157c8](https://github.com/mongodb/node-mongodb-native/commit/8d157c8)) -* **topology:** don't drain iteration timers on server selection ([fed6a57](https://github.com/mongodb/node-mongodb-native/commit/fed6a57)) - - -### Features - -* add `MessageStream` for streamed wire protocol messaging ([8c44044](https://github.com/mongodb/node-mongodb-native/commit/8c44044)) -* introduce a modern `Connection` replacement for CMAP ([7890e48](https://github.com/mongodb/node-mongodb-native/commit/7890e48)) -* support connection establishment cancellation ([2014b7b](https://github.com/mongodb/node-mongodb-native/commit/2014b7b)) -* support driver info for drivers wrapping the node driver ([1b6670b](https://github.com/mongodb/node-mongodb-native/commit/1b6670b)) - - - - -## [3.3.5](https://github.com/mongodb/node-mongodb-native/compare/v3.3.4...v3.3.5) (2019-11-26) - - -### Bug Fixes - -* **bulk:** use operation index from input to report operation error ([08ee53e](https://github.com/mongodb/node-mongodb-native/commit/08ee53e)) -* **command:** only add TransientTransactionError label when in a transaction ([8bab074](https://github.com/mongodb/node-mongodb-native/commit/8bab074)) -* **connect:** connect with family 0 instead of family 4 ([7a41279](https://github.com/mongodb/node-mongodb-native/commit/7a41279)) -* **cursor:** call `initialize` after session support check ([3b076b3](https://github.com/mongodb/node-mongodb-native/commit/3b076b3)) -* **mongodb+srv:** respect overriding SRV-provided properties ([5ed4c07](https://github.com/mongodb/node-mongodb-native/commit/5ed4c07)) -* **pool:** support a `drain` event for use with unified topology ([3471c28](https://github.com/mongodb/node-mongodb-native/commit/3471c28)) -* **topology:** correct logic for checking for sessions support ([2d976bd](https://github.com/mongodb/node-mongodb-native/commit/2d976bd)) -* **topology:** don't drain iteration timers on server selection ([261f1e5](https://github.com/mongodb/node-mongodb-native/commit/261f1e5)) - - -### Features - -* support driver info for drivers wrapping the node driver ([d85c4a8](https://github.com/mongodb/node-mongodb-native/commit/d85c4a8)) - - - - -## [3.3.4](https://github.com/mongodb/node-mongodb-native/compare/v3.3.3...v3.3.4) (2019-11-11) - - -### Bug Fixes - -* **close:** the unified topology emits a close event on close now ([ee0db01](https://github.com/mongodb/node-mongodb-native/commit/ee0db01)) -* **connect:** prevent multiple callbacks in error scenarios ([5f6a787](https://github.com/mongodb/node-mongodb-native/commit/5f6a787)) -* **monitoring:** incorrect states used to determine rescheduling ([ec1e04c](https://github.com/mongodb/node-mongodb-native/commit/ec1e04c)) -* **pool:** don't reset a pool if we'not already connected ([32316e4](https://github.com/mongodb/node-mongodb-native/commit/32316e4)) -* **pool:** only transition to `DISCONNECTED` if reconnect enabled ([43d461e](https://github.com/mongodb/node-mongodb-native/commit/43d461e)) -* **replset:** don't leak servers failing to connect ([f209160](https://github.com/mongodb/node-mongodb-native/commit/f209160)) -* **replset:** use correct `topologyId` for event emission ([19549ff](https://github.com/mongodb/node-mongodb-native/commit/19549ff)) -* **sdam:** `minHeartbeatIntervalMS` => `minHeartbeatFrequencyMS` ([af9fb45](https://github.com/mongodb/node-mongodb-native/commit/af9fb45)) -* **sdam:** don't emit `close` every time a child server closes ([818055a](https://github.com/mongodb/node-mongodb-native/commit/818055a)) -* **sdam:** don't lose servers when they fail monitoring ([8a534bb](https://github.com/mongodb/node-mongodb-native/commit/8a534bb)) -* **sdam:** don't remove unknown servers in topology updates ([1147ebf](https://github.com/mongodb/node-mongodb-native/commit/1147ebf)) -* **sdam:** ignore server errors when closing/closed ([49d7235](https://github.com/mongodb/node-mongodb-native/commit/49d7235)) -* **server:** don't emit error in connect if closing/closed ([62ada2a](https://github.com/mongodb/node-mongodb-native/commit/62ada2a)) -* **server:** ensure state is transitioned to closed on connect fail ([a471707](https://github.com/mongodb/node-mongodb-native/commit/a471707)) -* **topology:** report unified topology as `nodejs` ([d126665](https://github.com/mongodb/node-mongodb-native/commit/d126665)) -* **topology:** set max listeners to infinity for db event relay ([edb1335](https://github.com/mongodb/node-mongodb-native/commit/edb1335)) - - -### Features - -* **sdam_viz:** add new tool for visualizing driver sdam changes ([738189a](https://github.com/mongodb/node-mongodb-native/commit/738189a)) -* **sdam_viz:** support legacy topologies in sdam_viz tool ([1a5537e](https://github.com/mongodb/node-mongodb-native/commit/1a5537e)) -* **update-hints:** add support for `hint` to all update methods ([720f5e5](https://github.com/mongodb/node-mongodb-native/commit/720f5e5)) - - - - -## [3.3.3](https://github.com/mongodb/node-mongodb-native/compare/v3.3.2...v3.3.3) (2019-10-16) - - -### Bug Fixes - -* **change_stream:** emit 'close' event if reconnecting failed ([f24c084](https://github.com/mongodb/node-mongodb-native/commit/f24c084)) -* **ChangeStream:** remove startAtOperationTime once we have resumeToken ([362afd8](https://github.com/mongodb/node-mongodb-native/commit/362afd8)) -* **connect:** Switch new Buffer(size) -> Buffer.alloc(size) ([da90c3a](https://github.com/mongodb/node-mongodb-native/commit/da90c3a)) -* **MongoClient:** only check own properties for valid options ([9cde4b9](https://github.com/mongodb/node-mongodb-native/commit/9cde4b9)) -* **mongos:** disconnect proxies which are not mongos instances ([ee53983](https://github.com/mongodb/node-mongodb-native/commit/ee53983)) -* **mongos:** force close servers during reconnect flow ([186263f](https://github.com/mongodb/node-mongodb-native/commit/186263f)) -* **monitoring:** correct spelling mistake for heartbeat event ([21aa117](https://github.com/mongodb/node-mongodb-native/commit/21aa117)) -* **replset:** correct server leak on initial connect ([da39d1e](https://github.com/mongodb/node-mongodb-native/commit/da39d1e)) -* **replset:** destroy primary before removing from replsetstate ([45ac09a](https://github.com/mongodb/node-mongodb-native/commit/45ac09a)) -* **replset:** destroy servers that are removed during SDAM flow ([9ea0190](https://github.com/mongodb/node-mongodb-native/commit/9ea0190)) -* **saslprep:** add in missing saslprep dependency ([41f1165](https://github.com/mongodb/node-mongodb-native/commit/41f1165)) -* **topology:** don't early abort server selection on network errors ([2b6a359](https://github.com/mongodb/node-mongodb-native/commit/2b6a359)) -* **topology:** don't emit server closed event on network error ([194dcf0](https://github.com/mongodb/node-mongodb-native/commit/194dcf0)) -* **topology:** include all BSON types in ctor for bson-ext support ([aa4c832](https://github.com/mongodb/node-mongodb-native/commit/aa4c832)) -* **topology:** respect the `force` parameter for topology close ([d6e8936](https://github.com/mongodb/node-mongodb-native/commit/d6e8936)) - -### Features - -* **Update:** add the ability to specify a pipeline to an update command ([#2017](https://github.com/mongodb/node-mongodb-native/issues/2017)) ([44a4110](https://github.com/mongodb/node-mongodb-native/commit/44a4110)) -* **urlParser:** default useNewUrlParser to true ([52d76e3](https://github.com/mongodb/node-mongodb-native/commit/52d76e3)) - - -## [3.2.7](https://github.com/mongodb/node-mongodb-native/compare/v3.2.6...v3.2.7) (2019-06-04) - - -### Bug Fixes - -* **core:** updating core to version 3.2.7 ([2f91466](https://github.com/mongodb/node-mongodb-native/commit/2f91466)) -* **findOneAndReplace:** throw error if atomic operators provided for findOneAndReplace ([6a860a3](https://github.com/mongodb/node-mongodb-native/commit/6a860a3)) - - - - -## [3.3.2](https://github.com/mongodb/node-mongodb-native/compare/v3.3.1...v3.3.2) (2019-08-28) - - -### Bug Fixes - -* **change-stream:** default to server default batch size ([b3ae4c5](https://github.com/mongodb/node-mongodb-native/commit/b3ae4c5)) -* **execute-operation:** return promise on session support check ([a976c14](https://github.com/mongodb/node-mongodb-native/commit/a976c14)) -* **gridfs-stream:** ensure `close` is emitted after last chunk ([ae94cb9](https://github.com/mongodb/node-mongodb-native/commit/ae94cb9)) - - - - -## [3.3.1](https://github.com/mongodb/node-mongodb-native/compare/v3.3.0...v3.3.1) (2019-08-23) - - -### Bug Fixes - -* **find:** respect client-level provided read preference ([fec4f15](https://github.com/mongodb/node-mongodb-native/commit/fec4f15)) -* correct inverted defaults for unified topology ([cf598e1](https://github.com/mongodb/node-mongodb-native/commit/cf598e1)) - - - - -# [3.3.0](https://github.com/mongodb/node-mongodb-native/compare/v3.3.0-alpha1...v3.3.0) (2019-08-13) - - -### Bug Fixes - -* **aggregate-operation:** move type assertions to constructor ([25b27ff](https://github.com/mongodb/node-mongodb-native/commit/25b27ff)) -* **autoEncryption:** tear down mongocryptd client when main client closes ([fe2f57e](https://github.com/mongodb/node-mongodb-native/commit/fe2f57e)) -* **autoEncryption:** use new url parser for autoEncryption client ([d3670c2](https://github.com/mongodb/node-mongodb-native/commit/d3670c2)) -* **Bulk:** change BulkWriteError message to first item from writeErrors ([#2013](https://github.com/mongodb/node-mongodb-native/issues/2013)) ([6bcf1e4](https://github.com/mongodb/node-mongodb-native/commit/6bcf1e4)) -* **change_stream:** emit 'close' event if reconnecting failed ([41aba90](https://github.com/mongodb/node-mongodb-native/commit/41aba90)) -* **change_stream:** emit close event after cursor is closed during error ([c2d80b2](https://github.com/mongodb/node-mongodb-native/commit/c2d80b2)) -* **change-streams:** don't copy irrelevant resume options ([f190072](https://github.com/mongodb/node-mongodb-native/commit/f190072)) -* **changestream:** removes all event listeners on close ([30eeeb5](https://github.com/mongodb/node-mongodb-native/commit/30eeeb5)) -* **ChangeStream:** remove startAtOperationTime once we have resumeToken ([8d27e6e](https://github.com/mongodb/node-mongodb-native/commit/8d27e6e)) -* **ClientSessions:** initialize clientOptions and cluster time ([b95d64e](https://github.com/mongodb/node-mongodb-native/commit/b95d64e)) -* **connect:** don't treat 'connect' as an error event ([170a011](https://github.com/mongodb/node-mongodb-native/commit/170a011)) -* **connect:** fixed syntax issue in connect error handler ([ff7166d](https://github.com/mongodb/node-mongodb-native/commit/ff7166d)) -* **connections_stepdown_tests:** use correct version of mongo for tests ([ce2c9af](https://github.com/mongodb/node-mongodb-native/commit/ce2c9af)) -* **createCollection:** Db.createCollection should pass readConcern to new collection ([#2026](https://github.com/mongodb/node-mongodb-native/issues/2026)) ([6145d4b](https://github.com/mongodb/node-mongodb-native/commit/6145d4b)) -* **cursor:** do not truncate an existing Long ([317055b](https://github.com/mongodb/node-mongodb-native/commit/317055b)), closes [mongodb-js/mongodb-core#441](https://github.com/mongodb-js/mongodb-core/issues/441) -* **distinct:** return full response if `full` option was specified ([95a7d05](https://github.com/mongodb/node-mongodb-native/commit/95a7d05)) -* **MongoClient:** allow Object.prototype items as db names ([dc6fc37](https://github.com/mongodb/node-mongodb-native/commit/dc6fc37)) -* **MongoClient:** only check own properties for valid options ([c9dc717](https://github.com/mongodb/node-mongodb-native/commit/c9dc717)) -* **OpMsg:** cap requestIds at 0x7fffffff ([c0e87d5](https://github.com/mongodb/node-mongodb-native/commit/c0e87d5)) -* **read-operations:** send sessions on all read operations ([4d45c8a](https://github.com/mongodb/node-mongodb-native/commit/4d45c8a)) -* **ReadPreference:** improve ReadPreference error message and remove irrelevant sharding test ([dd34ce4](https://github.com/mongodb/node-mongodb-native/commit/dd34ce4)) -* **ReadPreference:** only allow valid ReadPreference modes ([06bbef2](https://github.com/mongodb/node-mongodb-native/commit/06bbef2)) -* **replset:** correct legacy max staleness calculation ([2eab8aa](https://github.com/mongodb/node-mongodb-native/commit/2eab8aa)) -* **replset:** introduce a fixed-time server selection loop ([cf53299](https://github.com/mongodb/node-mongodb-native/commit/cf53299)) -* **server:** emit "first connect" error if initial connect fails due to ECONNREFUSED ([#2016](https://github.com/mongodb/node-mongodb-native/issues/2016)) ([5a7b15b](https://github.com/mongodb/node-mongodb-native/commit/5a7b15b)) -* **serverSelection:** make sure to pass session to serverSelection ([eb5cc6b](https://github.com/mongodb/node-mongodb-native/commit/eb5cc6b)) -* **sessions:** ensure an error is thrown when attempting sharded transactions ([3a1fdc1](https://github.com/mongodb/node-mongodb-native/commit/3a1fdc1)) -* **topology:** add new error for retryWrites on MMAPv1 ([392f5a6](https://github.com/mongodb/node-mongodb-native/commit/392f5a6)) -* don't check non-unified topologies for session support check ([2bccd3f](https://github.com/mongodb/node-mongodb-native/commit/2bccd3f)) -* maintain internal database name on collection rename ([884d46f](https://github.com/mongodb/node-mongodb-native/commit/884d46f)) -* only check for transaction state if session exists ([360975a](https://github.com/mongodb/node-mongodb-native/commit/360975a)) -* preserve aggregate explain support for legacy servers ([032b204](https://github.com/mongodb/node-mongodb-native/commit/032b204)) -* read concern only supported for `mapReduce` without inline ([51a36f3](https://github.com/mongodb/node-mongodb-native/commit/51a36f3)) -* reintroduce support for 2.6 listIndexes ([c3bfc05](https://github.com/mongodb/node-mongodb-native/commit/c3bfc05)) -* return `executeOperation` for explain, if promise is desired ([b4a7ad7](https://github.com/mongodb/node-mongodb-native/commit/b4a7ad7)) -* validate atomic operations in all update methods ([88bb77e](https://github.com/mongodb/node-mongodb-native/commit/88bb77e)) -* **transactions:** fix error message for attempting sharded ([eb5dfc9](https://github.com/mongodb/node-mongodb-native/commit/eb5dfc9)) -* **transactions:** fix sharded transaction error logic ([083e18a](https://github.com/mongodb/node-mongodb-native/commit/083e18a)) - - -### Features - -* **Aggregate:** support ReadConcern in aggregates with $out ([21cdcf0](https://github.com/mongodb/node-mongodb-native/commit/21cdcf0)) -* **AutoEncryption:** improve error message for missing mongodb-client-encryption ([583f29f](https://github.com/mongodb/node-mongodb-native/commit/583f29f)) -* **ChangeStream:** adds new resume functionality to ChangeStreams ([9ec9b8f](https://github.com/mongodb/node-mongodb-native/commit/9ec9b8f)) -* **ChangeStreamCursor:** introduce new cursor type for change streams ([8813eb0](https://github.com/mongodb/node-mongodb-native/commit/8813eb0)) -* **cryptdConnectionString:** makes mongocryptd uri configurable ([#2049](https://github.com/mongodb/node-mongodb-native/issues/2049)) ([a487be4](https://github.com/mongodb/node-mongodb-native/commit/a487be4)) -* **eachAsync:** dedupe async iteration with a common helper ([c296f3a](https://github.com/mongodb/node-mongodb-native/commit/c296f3a)) -* **execute-operation:** allow execution with server selection ([36bc1fd](https://github.com/mongodb/node-mongodb-native/commit/36bc1fd)) -* **pool:** add support for resetting the connection pool ([2d1ff40](https://github.com/mongodb/node-mongodb-native/commit/2d1ff40)) -* **sessions:** track dirty state of sessions, drop after use ([f61df16](https://github.com/mongodb/node-mongodb-native/commit/f61df16)) -* add concept of `data-bearing` type to `ServerDescription` ([852e14f](https://github.com/mongodb/node-mongodb-native/commit/852e14f)) -* **transaction:** allow applications to set maxTimeMS for commitTransaction ([b3948aa](https://github.com/mongodb/node-mongodb-native/commit/b3948aa)) -* **Update:** add the ability to specify a pipeline to an update command ([#2017](https://github.com/mongodb/node-mongodb-native/issues/2017)) ([dc1387e](https://github.com/mongodb/node-mongodb-native/commit/dc1387e)) -* add `known`, `data-bearing` filters to `TopologyDescription` ([d0ccb56](https://github.com/mongodb/node-mongodb-native/commit/d0ccb56)) -* perform selection before cursor operation execution if needed ([808cf37](https://github.com/mongodb/node-mongodb-native/commit/808cf37)) -* perform selection before operation execution if needed ([1a25876](https://github.com/mongodb/node-mongodb-native/commit/1a25876)) -* support explain operations in `CommandOperationV2` ([86f5ba5](https://github.com/mongodb/node-mongodb-native/commit/86f5ba5)) -* support operations passed to a `Cursor` or subclass ([b78bb89](https://github.com/mongodb/node-mongodb-native/commit/b78bb89)) - - - - -## [3.2.7](https://github.com/mongodb/node-mongodb-native/compare/v3.2.6...v3.2.7) (2019-06-04) - - -### Bug Fixes - -* **core:** updating core to version 3.2.7 ([2f91466](https://github.com/mongodb/node-mongodb-native/commit/2f91466)) -* **findOneAndReplace:** throw error if atomic operators provided for findOneAndReplace ([6a860a3](https://github.com/mongodb/node-mongodb-native/commit/6a860a3)) - - - - -## [3.2.6](https://github.com/mongodb/node-mongodb-native/compare/v3.2.5...v3.2.6) (2019-05-24) - - - - -## [3.2.5](https://github.com/mongodb/node-mongodb-native/compare/v3.2.4...v3.2.5) (2019-05-17) - - -### Bug Fixes - -* **core:** updating core to 3.2.5 ([a2766c1](https://github.com/mongodb/node-mongodb-native/commit/a2766c1)) - - - - -## [3.2.4](https://github.com/mongodb/node-mongodb-native/compare/v3.2.2...v3.2.4) (2019-05-08) - - -### Bug Fixes - -* **aggregation:** fix field name typo ([4235d04](https://github.com/mongodb/node-mongodb-native/commit/4235d04)) -* **async:** rewrote asyncGenerator in node < 10 syntax ([49c8cef](https://github.com/mongodb/node-mongodb-native/commit/49c8cef)) -* **BulkOp:** run unordered bulk ops in serial ([f548bd7](https://github.com/mongodb/node-mongodb-native/commit/f548bd7)) -* **bulkWrite:** fix issue with bulkWrite continuing w/ callback ([2a4a42c](https://github.com/mongodb/node-mongodb-native/commit/2a4a42c)) -* **docs:** correctly document that default for `sslValidate` is false ([1f8e7fa](https://github.com/mongodb/node-mongodb-native/commit/1f8e7fa)) -* **gridfs-stream:** honor chunk size ([9eeb114](https://github.com/mongodb/node-mongodb-native/commit/9eeb114)) -* **unified-topology:** only clone pool size if provided ([8dc2416](https://github.com/mongodb/node-mongodb-native/commit/8dc2416)) - - -### Features - -* update to mongodb-core v3.2.3 ([1c5357a](https://github.com/mongodb/node-mongodb-native/commit/1c5357a)) -* **core:** update to mongodb-core v3.2.4 ([2059260](https://github.com/mongodb/node-mongodb-native/commit/2059260)) -* **lib:** implement executeOperationV2 ([67d4edf](https://github.com/mongodb/node-mongodb-native/commit/67d4edf)) - - - - -## [3.2.3](https://github.com/mongodb/node-mongodb-native/compare/v3.2.2...v3.2.3) (2019-04-05) - - -### Bug Fixes - -* **aggregation:** fix field name typo ([4235d04](https://github.com/mongodb/node-mongodb-native/commit/4235d04)) -* **async:** rewrote asyncGenerator in node < 10 syntax ([49c8cef](https://github.com/mongodb/node-mongodb-native/commit/49c8cef)) -* **bulkWrite:** fix issue with bulkWrite continuing w/ callback ([2a4a42c](https://github.com/mongodb/node-mongodb-native/commit/2a4a42c)) -* **docs:** correctly document that default for `sslValidate` is false ([1f8e7fa](https://github.com/mongodb/node-mongodb-native/commit/1f8e7fa)) - - -### Features - -* update to mongodb-core v3.2.3 ([1c5357a](https://github.com/mongodb/node-mongodb-native/commit/1c5357a)) - - - - -## [3.2.2](https://github.com/mongodb/node-mongodb-native/compare/v3.2.1...v3.2.2) (2019-03-22) - - -### Bug Fixes - -* **asyncIterator:** stronger guard against importing async generator ([e0826fb](https://github.com/mongodb/node-mongodb-native/commit/e0826fb)) - - -### Features - -* update to mongodb-core v3.2.2 ([868cfc3](https://github.com/mongodb/node-mongodb-native/commit/868cfc3)) - - - - -## [3.2.1](https://github.com/mongodb/node-mongodb-native/compare/v3.2.0...v3.2.1) (2019-03-21) - - -### Features - -* **core:** update to mongodb-core v3.2.1 ([30b0100](https://github.com/mongodb/node-mongodb-native/commit/30b0100)) - - - - -# [3.2.0](https://github.com/mongodb/node-mongodb-native/compare/v3.1.13...v3.2.0) (2019-03-21) - - -### Bug Fixes - -* **aggregate:** do not send batchSize for aggregation with $out ([ddb8d90](https://github.com/mongodb/node-mongodb-native/commit/ddb8d90)) -* **bulkWrite:** always count undefined values in bson size for bulk ([436d340](https://github.com/mongodb/node-mongodb-native/commit/436d340)) -* **db_ops:** rename db to add user on ([79931af](https://github.com/mongodb/node-mongodb-native/commit/79931af)) -* **mongo_client_ops:** only skip authentication if no authMechanism is specified ([3b6957d](https://github.com/mongodb/node-mongodb-native/commit/3b6957d)) -* **mongo-client:** ensure close callback is called with client ([f39e881](https://github.com/mongodb/node-mongodb-native/commit/f39e881)) - - -### Features - -* **core:** pin to mongodb-core v3.2.0 ([22af15a](https://github.com/mongodb/node-mongodb-native/commit/22af15a)) -* **Cursor:** adds support for AsyncIterator in cursors ([b972c1e](https://github.com/mongodb/node-mongodb-native/commit/b972c1e)) -* **db:** add database-level aggregation ([b629b21](https://github.com/mongodb/node-mongodb-native/commit/b629b21)) -* **mongo-client:** remove deprecated `logout` and print warning ([542859d](https://github.com/mongodb/node-mongodb-native/commit/542859d)) -* **topology-base:** support passing callbacks to `close` method ([7c111e0](https://github.com/mongodb/node-mongodb-native/commit/7c111e0)) -* **transactions:** support pinning mongos for sharded txns ([3886127](https://github.com/mongodb/node-mongodb-native/commit/3886127)) -* **unified-sdam:** backport unified SDAM to master for v3.2.0 ([79f33ca](https://github.com/mongodb/node-mongodb-native/commit/79f33ca)) - - - - -## [3.1.13](https://github.com/mongodb/node-mongodb-native/compare/v3.1.12...v3.1.13) (2019-01-23) - - -### Bug Fixes - -* restore ability to webpack by removing `makeLazyLoader` ([050267d](https://github.com/mongodb/node-mongodb-native/commit/050267d)) -* **bulk:** honor ignoreUndefined in initializeUnorderedBulkOp ([e806be4](https://github.com/mongodb/node-mongodb-native/commit/e806be4)) -* **changeStream:** properly handle changeStream event mid-close ([#1902](https://github.com/mongodb/node-mongodb-native/issues/1902)) ([5ad9fa9](https://github.com/mongodb/node-mongodb-native/commit/5ad9fa9)) -* **db_ops:** ensure we async resolve errors in createCollection ([210c71d](https://github.com/mongodb/node-mongodb-native/commit/210c71d)) - - - - -## [3.1.12](https://github.com/mongodb/node-mongodb-native/compare/v3.1.11...v3.1.12) (2019-01-16) - - -### Features - -* **core:** update to mongodb-core v3.1.11 ([9bef6e7](https://github.com/mongodb/node-mongodb-native/commit/9bef6e7)) - - - - -## [3.1.11](https://github.com/mongodb/node-mongodb-native/compare/v3.1.10...v3.1.11) (2019-01-15) - - -### Bug Fixes - -* **bulk:** fix error propagation in empty bulk.execute ([a3adb3f](https://github.com/mongodb/node-mongodb-native/commit/a3adb3f)) -* **bulk:** make sure that any error in bulk write is propagated ([bedc2d2](https://github.com/mongodb/node-mongodb-native/commit/bedc2d2)) -* **bulk:** properly calculate batch size for bulk writes ([aafe71b](https://github.com/mongodb/node-mongodb-native/commit/aafe71b)) -* **operations:** do not call require in a hot path ([ff82ff4](https://github.com/mongodb/node-mongodb-native/commit/ff82ff4)) - - - - -## [3.1.10](https://github.com/mongodb/node-mongodb-native/compare/v3.1.9...v3.1.10) (2018-11-16) - - -### Bug Fixes - -* **auth:** remember to default to admin database ([c7dec28](https://github.com/mongodb/node-mongodb-native/commit/c7dec28)) - - -### Features - -* **core:** update to mongodb-core v3.1.9 ([bd3355b](https://github.com/mongodb/node-mongodb-native/commit/bd3355b)) - - - - -## [3.1.9](https://github.com/mongodb/node-mongodb-native/compare/v3.1.8...v3.1.9) (2018-11-06) - - -### Bug Fixes - -* **db:** move db constants to other file to avoid circular ref ([#1858](https://github.com/mongodb/node-mongodb-native/issues/1858)) ([239036f](https://github.com/mongodb/node-mongodb-native/commit/239036f)) -* **estimated-document-count:** support options other than maxTimeMs ([36c3c7d](https://github.com/mongodb/node-mongodb-native/commit/36c3c7d)) - - -### Features - -* **core:** update to mongodb-core v3.1.8 ([80d7c79](https://github.com/mongodb/node-mongodb-native/commit/80d7c79)) - - - - -## [3.1.8](https://github.com/mongodb/node-mongodb-native/compare/v3.1.7...v3.1.8) (2018-10-10) - - -### Bug Fixes - -* **connect:** use reported default databse from new uri parser ([811f8f8](https://github.com/mongodb/node-mongodb-native/commit/811f8f8)) - - -### Features - -* **core:** update to mongodb-core v3.1.7 ([dbfc905](https://github.com/mongodb/node-mongodb-native/commit/dbfc905)) - - - - -## [3.1.7](https://github.com/mongodb/node-mongodb-native/compare/v3.1.6...v3.1.7) (2018-10-09) - - -### Features - -* **core:** update mongodb-core to v3.1.6 ([61b054e](https://github.com/mongodb/node-mongodb-native/commit/61b054e)) - - - - -## [3.1.6](https://github.com/mongodb/node-mongodb-native/compare/v3.1.5...v3.1.6) (2018-09-15) - - -### Features - -* **core:** update to core v3.1.5 ([c5f823d](https://github.com/mongodb/node-mongodb-native/commit/c5f823d)) - - - - -## [3.1.5](https://github.com/mongodb/node-mongodb-native/compare/v3.1.4...v3.1.5) (2018-09-14) - - -### Bug Fixes - -* **cursor:** allow `$meta` based sort when passing an array to `sort()` ([f93a8c3](https://github.com/mongodb/node-mongodb-native/commit/f93a8c3)) -* **utils:** only set retryWrites to true for valid operations ([3b725ef](https://github.com/mongodb/node-mongodb-native/commit/3b725ef)) - - -### Features - -* **core:** bump core to v3.1.4 ([805d58a](https://github.com/mongodb/node-mongodb-native/commit/805d58a)) - - - - -## [3.1.4](https://github.com/mongodb/node-mongodb-native/compare/v3.1.3...v3.1.4) (2018-08-25) - - -### Bug Fixes - -* **buffer:** use safe-buffer polyfill to maintain compatibility ([327da95](https://github.com/mongodb/node-mongodb-native/commit/327da95)) -* **change-stream:** properly support resumablity in stream mode ([c43a34b](https://github.com/mongodb/node-mongodb-native/commit/c43a34b)) -* **connect:** correct replacement of topology on connect callback ([918a1e0](https://github.com/mongodb/node-mongodb-native/commit/918a1e0)) -* **cursor:** remove deprecated notice on forEach ([a474158](https://github.com/mongodb/node-mongodb-native/commit/a474158)) -* **url-parser:** bail early on validation when using domain socket ([3cb3da3](https://github.com/mongodb/node-mongodb-native/commit/3cb3da3)) - - -### Features - -* **client-ops:** allow bypassing creation of topologies on connect ([fe39b93](https://github.com/mongodb/node-mongodb-native/commit/fe39b93)) -* **core:** update mongodb-core to 3.1.3 ([a029047](https://github.com/mongodb/node-mongodb-native/commit/a029047)) -* **test:** use connection strings for all calls to `newClient` ([1dac18f](https://github.com/mongodb/node-mongodb-native/commit/1dac18f)) - - - - -## [3.1.3](https://github.com/mongodb/node-mongodb-native/compare/v3.1.2...v3.1.3) (2018-08-13) - - -### Features - -* **core:** update to mongodb-core 3.1.2 ([337cb79](https://github.com/mongodb/node-mongodb-native/commit/337cb79)) - - - - -## [3.1.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.2) (2018-08-13) - - -### Bug Fixes - -* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) -* **buffer:** replace deprecated Buffer constructor ([759dd85](https://github.com/mongodb/node-mongodb-native/commit/759dd85)) -* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) -* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) -* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) -* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) -* **client-ops:** return transform map to map rather than function ([cfb7d83](https://github.com/mongodb/node-mongodb-native/commit/cfb7d83)) -* **collection:** correctly shallow clone passed in options ([7727700](https://github.com/mongodb/node-mongodb-native/commit/7727700)) -* **collection:** countDocuments throws error when query doesn't match docs ([09c7d8e](https://github.com/mongodb/node-mongodb-native/commit/09c7d8e)) -* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) -* **collection:** ensure findAndModify always use readPreference primary ([86344f4](https://github.com/mongodb/node-mongodb-native/commit/86344f4)) -* **collection:** isCapped returns false instead of undefined ([b8471f1](https://github.com/mongodb/node-mongodb-native/commit/b8471f1)) -* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) -* **count-documents:** return callback on error case ([fca1185](https://github.com/mongodb/node-mongodb-native/commit/fca1185)) -* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) -* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) -* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) -* **cursor:** set readPreference for cursor.count ([13d776f](https://github.com/mongodb/node-mongodb-native/commit/13d776f)) -* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) -* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) -* **db_ops:** call collection.find() with correct parameters ([#1795](https://github.com/mongodb/node-mongodb-native/issues/1795)) ([36e92f1](https://github.com/mongodb/node-mongodb-native/commit/36e92f1)) -* **db_ops:** fix two incorrectly named variables ([15dc808](https://github.com/mongodb/node-mongodb-native/commit/15dc808)) -* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) -* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) -* **mongo_client:** translate options for connectWithUrl ([78f6977](https://github.com/mongodb/node-mongodb-native/commit/78f6977)) -* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) -* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) -* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) -* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) -* **server:** remove unnecessary print statement ([2bcbc12](https://github.com/mongodb/node-mongodb-native/commit/2bcbc12)) -* **teardown:** properly destroy a topology when initial connect fails ([b8d2f1d](https://github.com/mongodb/node-mongodb-native/commit/b8d2f1d)) -* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) -* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) -* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) - - -### Features - -* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) -* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) -* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) -* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) -* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) -* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) -* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) -* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) -* **core:** bump core dependency to v3.1.0 ([4937240](https://github.com/mongodb/node-mongodb-native/commit/4937240)) -* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) -* **deprecation:** create deprecation function ([4f907a0](https://github.com/mongodb/node-mongodb-native/commit/4f907a0)) -* **deprecation:** wrap deprecated functions ([a5d0f1d](https://github.com/mongodb/node-mongodb-native/commit/a5d0f1d)) -* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) -* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) -* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) -* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) -* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) -* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) -* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) - - -### Reverts - -* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) - - - - -## [3.1.1](https://github.com/mongodb/node-mongodb-native/compare/v3.1.0...v3.1.1) (2018-07-05) - - -### Bug Fixes - -* **client-ops:** return transform map to map rather than function ([b8b4bfa](https://github.com/mongodb/node-mongodb-native/commit/b8b4bfa)) -* **collection:** correctly shallow clone passed in options ([2e6c4fa](https://github.com/mongodb/node-mongodb-native/commit/2e6c4fa)) -* **collection:** countDocuments throws error when query doesn't match docs ([4e83556](https://github.com/mongodb/node-mongodb-native/commit/4e83556)) -* **server:** remove unnecessary print statement ([20e11b3](https://github.com/mongodb/node-mongodb-native/commit/20e11b3)) - - - - -# [3.1.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.0) (2018-06-27) - - -### Bug Fixes - -* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) -* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) -* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) -* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) -* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) -* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) -* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) -* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) -* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) -* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) -* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) -* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) -* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) -* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) -* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) -* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) -* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) -* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) -* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) -* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) -* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) - - -### Features - -* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) -* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) -* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) -* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) -* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) -* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) -* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) -* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) -* **core:** bump core dependency to v3.1.0 ([855bfdb](https://github.com/mongodb/node-mongodb-native/commit/855bfdb)) -* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) -* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) -* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) -* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) -* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) -* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) -* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) -* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) - - -### Reverts - -* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) - - - - -## [3.0.6](https://github.com/mongodb/node-mongodb-native/compare/v3.0.5...v3.0.6) (2018-04-09) - - -### Bug Fixes - -* **db:** ensure `dropDatabase` always uses primary read preference ([e62e5c9](https://github.com/mongodb/node-mongodb-native/commit/e62e5c9)) -* **driverBench:** driverBench has default options object now ([c557817](https://github.com/mongodb/node-mongodb-native/commit/c557817)) - - -### Features - -* **command-monitoring:** support enabling command monitoring ([5903680](https://github.com/mongodb/node-mongodb-native/commit/5903680)) -* **core:** update to mongodb-core v3.0.6 ([cfdd0ae](https://github.com/mongodb/node-mongodb-native/commit/cfdd0ae)) -* **driverBench:** Implementing DriverBench ([d10fbad](https://github.com/mongodb/node-mongodb-native/commit/d10fbad)) - - - - -## [3.0.5](https://github.com/mongodb/node-mongodb-native/compare/v3.0.4...v3.0.5) (2018-03-23) - - -### Bug Fixes - -* **AggregationCursor:** adding session tracking to AggregationCursor ([baca5b7](https://github.com/mongodb/node-mongodb-native/commit/baca5b7)) -* **Collection:** fix session leak in parallelCollectonScan ([3331ec9](https://github.com/mongodb/node-mongodb-native/commit/3331ec9)) -* **comments:** adding fixes for PR comments ([ee110ac](https://github.com/mongodb/node-mongodb-native/commit/ee110ac)) -* **url_parser:** support a default database on mongodb+srv uris ([6d39b2a](https://github.com/mongodb/node-mongodb-native/commit/6d39b2a)) - - -### Features - -* **sessions:** adding implicit cursor session support ([a81245b](https://github.com/mongodb/node-mongodb-native/commit/a81245b)) - - - - -## [3.0.4](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.4) (2018-03-05) - - -### Bug Fixes - -* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) -* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) -* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) -* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) -* **utils:** fixes executeOperation to clean up sessions ([04e6ef6](https://github.com/mongodb/node-mongodb-native/commit/04e6ef6)) - - -### Features - -* **default-db:** use dbName from uri if none provided ([23b1938](https://github.com/mongodb/node-mongodb-native/commit/23b1938)) -* **mongodb-core:** update to mongodb-core 3.0.4 ([1fdbaa5](https://github.com/mongodb/node-mongodb-native/commit/1fdbaa5)) - - - - -## [3.0.3](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.3) (2018-02-23) - - -### Bug Fixes - -* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) -* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) -* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) -* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) - - - - -## [3.0.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.1...v3.0.2) (2018-01-29) - - -### Bug Fixes - -* **collection:** ensure dynamic require of `db` is wrapped in parentheses ([efa78f0](https://github.com/mongodb/node-mongodb-native/commit/efa78f0)) -* **db:** only callback with MongoError NODE-1293 ([#1652](https://github.com/mongodb/node-mongodb-native/issues/1652)) ([45bc722](https://github.com/mongodb/node-mongodb-native/commit/45bc722)) -* **topology base:** allow more than 10 event listeners ([#1630](https://github.com/mongodb/node-mongodb-native/issues/1630)) ([d9fb750](https://github.com/mongodb/node-mongodb-native/commit/d9fb750)) -* **url parser:** preserve auth creds when composing conn string ([#1640](https://github.com/mongodb/node-mongodb-native/issues/1640)) ([eddca5e](https://github.com/mongodb/node-mongodb-native/commit/eddca5e)) - - -### Features - -* **bulk:** forward 'checkKeys' option for ordered and unordered bulk operations ([421a6b2](https://github.com/mongodb/node-mongodb-native/commit/421a6b2)) -* **collection:** expose `dbName` property of collection ([6fd05c1](https://github.com/mongodb/node-mongodb-native/commit/6fd05c1)) - - - - -## [3.0.1](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0...v3.0.1) (2017-12-24) - -* update mongodb-core to 3.0.1 - - -# [3.0.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0-rc0...v3.0.0) (2017-12-24) - - -### Bug Fixes - -* **aggregate:** remove support for inline results for aggregate ([#1620](https://github.com/mongodb/node-mongodb-native/issues/1620)) ([84457ec](https://github.com/mongodb/node-mongodb-native/commit/84457ec)) -* **topologies:** unify topologies connect API ([#1615](https://github.com/mongodb/node-mongodb-native/issues/1615)) ([0fb4658](https://github.com/mongodb/node-mongodb-native/commit/0fb4658)) - - -### Features - -* **keepAlive:** make keepAlive options consistent ([#1612](https://github.com/mongodb/node-mongodb-native/issues/1612)) ([f608f44](https://github.com/mongodb/node-mongodb-native/commit/f608f44)) - - -### BREAKING CHANGES - -* **topologies:** Function signature for `.connect` method on replset and mongos has changed. You shouldn't have been using this anyway, but if you were, you only should pass `options` and `callback`. - -Part of NODE-1089 -* **keepAlive:** option `keepAlive` is now split into boolean `keepAlive` and -number `keepAliveInitialDelay` - -Fixes NODE-998 - - - - -# [3.0.0-rc0](https://github.com/mongodb/node-mongodb-native/compare/v2.2.31...v3.0.0-rc0) (2017-12-05) - - -### Bug Fixes - -* **aggregation:** ensure that the `cursor` key is always present ([f16f314](https://github.com/mongodb/node-mongodb-native/commit/f16f314)) -* **apm:** give users access to raw server responses ([88b206b](https://github.com/mongodb/node-mongodb-native/commit/88b206b)) -* **apm:** only rebuilt cursor if reply is non-null ([96052c8](https://github.com/mongodb/node-mongodb-native/commit/96052c8)) -* **apm:** rebuild lost `cursor` info on pre-OP_QUERY responses ([4242d49](https://github.com/mongodb/node-mongodb-native/commit/4242d49)) -* **bulk-unordered:** add check for ignoreUndefined ([f38641a](https://github.com/mongodb/node-mongodb-native/commit/f38641a)) -* **change stream examples:** use timeouts, cleanup ([c5fec5f](https://github.com/mongodb/node-mongodb-native/commit/c5fec5f)) -* **change-streams:** ensure a majority read concern on initial agg ([23011e9](https://github.com/mongodb/node-mongodb-native/commit/23011e9)) -* **changeStreams:** fixing node4 issue with util.inherits ([#1587](https://github.com/mongodb/node-mongodb-native/issues/1587)) ([168bb3d](https://github.com/mongodb/node-mongodb-native/commit/168bb3d)) -* **collection:** allow { upsert: 1 } for findOneAndUpdate() and update() ([5bcedd6](https://github.com/mongodb/node-mongodb-native/commit/5bcedd6)) -* **collection:** allow passing `noCursorTimeout` as an option to `find()` ([e9c4ffc](https://github.com/mongodb/node-mongodb-native/commit/e9c4ffc)) -* **collection:** make the parameters of findOne very explicit ([3054f1a](https://github.com/mongodb/node-mongodb-native/commit/3054f1a)) -* **cursor:** `hasNext` should propagate errors when using callback ([6339625](https://github.com/mongodb/node-mongodb-native/commit/6339625)) -* **cursor:** close readable on `null` response for dead cursor ([6aca2c5](https://github.com/mongodb/node-mongodb-native/commit/6aca2c5)) -* **dns txt records:** check options are set ([e5caf4f](https://github.com/mongodb/node-mongodb-native/commit/e5caf4f)) -* **docs:** Represent each valid option in docs in both places ([fde6e5d](https://github.com/mongodb/node-mongodb-native/commit/fde6e5d)) -* **grid-store:** add missing callback ([66a9a05](https://github.com/mongodb/node-mongodb-native/commit/66a9a05)) -* **grid-store:** move into callback scope ([b53f65f](https://github.com/mongodb/node-mongodb-native/commit/b53f65f)) -* **GridFS:** fix TypeError: doc.data.length is not a function ([#1570](https://github.com/mongodb/node-mongodb-native/issues/1570)) ([22a4628](https://github.com/mongodb/node-mongodb-native/commit/22a4628)) -* **list-collections:** ensure default of primary ReadPreference ([4a0cfeb](https://github.com/mongodb/node-mongodb-native/commit/4a0cfeb)) -* **mongo client:** close client before calling done ([c828aab](https://github.com/mongodb/node-mongodb-native/commit/c828aab)) -* **mongo client:** do not connect if url parse error ([cd10084](https://github.com/mongodb/node-mongodb-native/commit/cd10084)) -* **mongo client:** send error to cb ([eafc9e2](https://github.com/mongodb/node-mongodb-native/commit/eafc9e2)) -* **mongo-client:** move to inside of callback ([68b0fca](https://github.com/mongodb/node-mongodb-native/commit/68b0fca)) -* **mongo-client:** options should not be passed to `connect` ([474ac65](https://github.com/mongodb/node-mongodb-native/commit/474ac65)) -* **tests:** migrate 2.x tests to 3.x ([3a5232a](https://github.com/mongodb/node-mongodb-native/commit/3a5232a)) -* **updateOne/updateMany:** ensure that update documents contain atomic operators ([8b4255a](https://github.com/mongodb/node-mongodb-native/commit/8b4255a)) -* **url parser:** add check for options as cb ([52b6039](https://github.com/mongodb/node-mongodb-native/commit/52b6039)) -* **url parser:** compare srv address and parent domains ([daa186d](https://github.com/mongodb/node-mongodb-native/commit/daa186d)) -* **url parser:** compare string from first period on ([9e5d77e](https://github.com/mongodb/node-mongodb-native/commit/9e5d77e)) -* **url parser:** default to ssl true for mongodb+srv ([0fbca4b](https://github.com/mongodb/node-mongodb-native/commit/0fbca4b)) -* **url parser:** error when multiple hostnames used ([c1aa681](https://github.com/mongodb/node-mongodb-native/commit/c1aa681)) -* **url parser:** keep original uri options and default to ssl true ([e876a72](https://github.com/mongodb/node-mongodb-native/commit/e876a72)) -* **url parser:** log instead of throw error for unsupported url options ([155de2d](https://github.com/mongodb/node-mongodb-native/commit/155de2d)) -* **url parser:** make sure uri has 3 parts ([aa9871b](https://github.com/mongodb/node-mongodb-native/commit/aa9871b)) -* **url parser:** only 1 txt record allowed with 2 possible options ([d9f4218](https://github.com/mongodb/node-mongodb-native/commit/d9f4218)) -* **url parser:** only check for multiple hostnames with srv protocol ([5542bcc](https://github.com/mongodb/node-mongodb-native/commit/5542bcc)) -* **url parser:** remove .only from test ([642e39e](https://github.com/mongodb/node-mongodb-native/commit/642e39e)) -* **url parser:** return callback ([6096afc](https://github.com/mongodb/node-mongodb-native/commit/6096afc)) -* **url parser:** support single text record with multiple strings ([356fa57](https://github.com/mongodb/node-mongodb-native/commit/356fa57)) -* **url parser:** try catch bug, not actually returning from try loop ([758892b](https://github.com/mongodb/node-mongodb-native/commit/758892b)) -* **url parser:** use warn instead of info ([40ed27d](https://github.com/mongodb/node-mongodb-native/commit/40ed27d)) -* **url-parser:** remove comment, send error to cb ([d44420b](https://github.com/mongodb/node-mongodb-native/commit/d44420b)) - - -### Features - -* **aggregate:** support hit field for aggregate command ([aa7da15](https://github.com/mongodb/node-mongodb-native/commit/aa7da15)) -* **aggregation:** adds support for comment in aggregation command ([#1571](https://github.com/mongodb/node-mongodb-native/issues/1571)) ([4ac475c](https://github.com/mongodb/node-mongodb-native/commit/4ac475c)) -* **aggregation:** fail aggregation on explain + readConcern/writeConcern ([e0ca1b4](https://github.com/mongodb/node-mongodb-native/commit/e0ca1b4)) -* **causal-consistency:** support `afterClusterTime` in readConcern ([a9097f7](https://github.com/mongodb/node-mongodb-native/commit/a9097f7)) -* **change-streams:** add support for change streams ([c02d25c](https://github.com/mongodb/node-mongodb-native/commit/c02d25c)) -* **collection:** updating find API ([f26362d](https://github.com/mongodb/node-mongodb-native/commit/f26362d)) -* **execute-operation:** implementation for common op execution ([67c344f](https://github.com/mongodb/node-mongodb-native/commit/67c344f)) -* **listDatabases:** add support for nameOnly option to listDatabases ([eb79b5a](https://github.com/mongodb/node-mongodb-native/commit/eb79b5a)) -* **maxTimeMS:** adding maxTimeMS option to createIndexes and dropIndexes ([90d4a63](https://github.com/mongodb/node-mongodb-native/commit/90d4a63)) -* **mongo-client:** implement `MongoClient.prototype.startSession` ([bce5adf](https://github.com/mongodb/node-mongodb-native/commit/bce5adf)) -* **retryable-writes:** add support for `retryWrites` cs option ([2321870](https://github.com/mongodb/node-mongodb-native/commit/2321870)) -* **sessions:** MongoClient will now track sessions and release ([6829f47](https://github.com/mongodb/node-mongodb-native/commit/6829f47)) -* **sessions:** support passing sessions via objects in all methods ([a531f05](https://github.com/mongodb/node-mongodb-native/commit/a531f05)) -* **shared:** add helper utilities for assertion and suite setup ([b6cc34e](https://github.com/mongodb/node-mongodb-native/commit/b6cc34e)) -* **ssl:** adds missing ssl options ssl options for `ciphers` and `ecdhCurve` ([441b7b1](https://github.com/mongodb/node-mongodb-native/commit/441b7b1)) -* **test-shared:** add `notEqual` assertion ([41d93fd](https://github.com/mongodb/node-mongodb-native/commit/41d93fd)) -* **test-shared:** add `strictEqual` assertion method ([cad8e19](https://github.com/mongodb/node-mongodb-native/commit/cad8e19)) -* **topologies:** expose underlaying `logicalSessionTimeoutMinutes' ([1609a37](https://github.com/mongodb/node-mongodb-native/commit/1609a37)) -* **url parser:** better error message for slash in hostname ([457bc29](https://github.com/mongodb/node-mongodb-native/commit/457bc29)) - - -### BREAKING CHANGES - -* **aggregation:** If you use aggregation, and try to use the explain flag while you -have a readConcern or writeConcern, your query will fail -* **collection:** `find` and `findOne` no longer support the `fields` parameter. -You can achieve the same results as the `fields` parameter by -either using `Cursor.prototype.project`, or by passing the `projection` -property in on the `options` object. Additionally, `find` does not -support individual options like `skip` and `limit` as positional -parameters. You must pass in these parameters in the `options` object - - - -3.0.0 2017-??-?? ----------------- -* NODE-1043 URI-escaping authentication and hostname details in connection string - -2.2.31 2017-08-08 ------------------ -* update mongodb-core to 2.2.15 -* allow auth option in MongoClient.connect -* remove duplicate option `promoteLongs` from MongoClient's `connect` -* bulk operations should not throw an error on empty batch - -2.2.30 2017-07-07 ------------------ -* Update mongodb-core to 2.2.14 -* MongoClient - * add `appname` to list of valid option names - * added test for passing appname as option -* NODE-1052 ensure user options are applied while parsing connection string uris - -2.2.29 2017-06-19 ------------------ -* Update mongodb-core to 2.1.13 - * NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. - * Use actual server type in standalone SDAM events. -* Allow multiple map calls (Issue #1521, https://github.com/Robbilie). -* Clone insertMany options before mutating (Issue #1522, https://github.com/vkarpov15). -* NODE-1034 Fix GridStore issue caused by Node 8.0.0 breaking backward compatible fs.read API. -* NODE-1026, use operator instead of skip function in order to avoid useless fetch stage. - -2.2.28 2017-06-02 ------------------ -* Update mongodb-core to 2.1.12 - * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. - * Minor fix to report the correct state on error. - * NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). - * Fix require_optional loading of bson-ext. - * Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. - * NODE-999 SDAM fixes for Mongos and single Server event emitting. - * NODE-1014 Set socketTimeout to default to 360 seconds. - * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. -* Just handle Collection name errors distinctly from general callback errors avoiding double callbacks in Db.collection. -* NODE-999 SDAM fixes for Mongos and single Server event emitting. -* NODE-1000 Added guard condition for upload.js checkDone function in case of race condition caused by late arriving chunk write. - -2.2.27 2017-05-22 ------------------ -* Updated mongodb-core to 2.1.11 - * NODE-987 Clear out old intervalIds on when calling topologyMonitor. - * NODE-987 Moved filtering to pingServer method and added test case. - * Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). - * NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interval. -* NODE-985 Deprecated Db.authenticate and Admin.authenticate and moved auth methods into authenticate.js to ensure MongoClient.connect does not print deprecation warnings. -* NODE-988 Merged readConcern and hint correctly on collection(...).find(...).count() -* Fix passing the readConcern option to MongoClient.connect (Issue #1514, https://github.com/bausmeier). -* NODE-996 Propegate all events up to a MongoClient instance. -* Allow saving doc with null `_id` (Issue #1517, https://github.com/vkarpov15). -* NODE-993 Expose hasNext for command cursor and add docs for both CommandCursor and Aggregation Cursor. - -2.2.26 2017-04-18 ------------------ -* Updated mongodb-core to 2.1.10 - * NODE-981 delegate auth to replset/mongos if inTopology is set. - * NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. - * Remove dynamic require (Issue #175, https://github.com/tellnes). - * NODE-696 Handle interrupted error for createIndexes. - * Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. - * NODE-966 promoteValues not being promoted correctly to getMore. - * Merged in fix for flushing out monitoring operations. -* NODE-983 Add cursorId to aggregate and listCollections commands (Issue, #1510). -* Mark group and profilingInfo as deprecated methods -* NODE-956 DOCS Examples. -* Update readable-stream to version 2.2.7. -* NODE-978 Added test case to uncover connection.end issue for node 0.10.x. -* NODE-972 Fix(db): don't remove database name if collectionName == dbName (Issue, #1502) -* Fixed merging of writeConcerns on db.collection method. -* NODE-970 mix in readPreference for strict mode listCollections callback. -* NODE-966 added testcase for promoteValues being applied to getMore commands. -* NODE-962 Merge in ignoreUndefined from collection level for find/findOne. -* Remove multi option from updateMany tests/docs (Issue #1499, https://github.com/spratt). -* NODE-963 Correctly handle cursor.count when using APM. - -2.2.25 2017-03-17 ------------------ -* Don't rely on global toString() for checking if object (Issue #1494, https://github.com/vkarpov15). -* Remove obsolete option uri_decode_auth (Issue #1488, https://github.com/kamagatos). -* NODE-936 Correctly translate ReadPreference to CoreReadPreference for mongos queries. -* Exposed BSONRegExp type. -* NODE-950 push correct index for INSERT ops (https://github.com/mbroadst). -* NODE-951 Added support for sslCRL option and added a test case for it. -* NODE-953 Made batchSize issue general at cursor level. -* NODE-954 Remove write concern from reindex helper as it will not be supported in 3.6. -* Updated mongodb-core to 2.1.9. - * Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. - * Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. - * Ensure SSL error propegates better for Replset connections when there is a SSL validation error. - * NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. - * NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. - -2.2.24 2017-02-14 ------------------ -* NODE-935, NODE-931 Make MongoClient strict options validation optional and instead print annoying console.warn entries. - -2.2.23 2017-02-13 ------------------ -* Updated mongodb-core to 2.1.8. - * NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. - * NODE-927 fixes issue where authentication was performed against arbiter instances. - * NODE-915 Normalize all host names to avoid comparison issues. - * Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. -* NODE-931 Validates all the options for MongoClient.connect and fixes missing connection settings. -* NODE-929 Update SSL tutorial to correctly reflect the non-need for server/mongos/replset subobjects -* Fix sensitive command check (Issue #1473, https://github.com/Annoraaq) - -2.2.22 2017-01-24 ------------------ -* Updated mongodb-core to 2.1.7. - * NODE-919 ReplicaSet connection does not close immediately (Issue #156). - * NODE-901 Fixed bug when normalizing host names. - * NODE-909 Fixed readPreference issue caused by direct connection to primary. - * NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. -* Add missing unref implementations for replset, mongos (Issue #1455, https://github.com/zbjornson) - -2.2.21 2017-01-13 ------------------ -* Updated mongodb-core to 2.1.6. - * NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. - -2.2.20 2017-01-11 ------------------ -* Updated mongodb-core to 2.1.5 to include bson 1.0.4 and bson-ext 1.0.4 due to Buffer.from being broken in early node 4.x versions. - -2.2.19 2017-01-03 ------------------ -* Corrupted Npm release fix. - -2.2.18 2017-01-03 ------------------ -* Updated mongodb-core to 2.1.4 to fix bson ObjectId toString issue with utils.inspect messing with toString parameters in node 6. - -2.2.17 2017-01-02 ------------------ -* updated createCollection doc options and linked to create command. -* Updated mongodb-core to 2.1.3. - * Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining - * Moved replicaset monitoring away from serial mode and to parallel mode. - * updated bson and bson-ext dependencies to 1.0.2. - -2.2.16 2016-12-13 ------------------ -* NODE-899 reversed upsertedId change to bring back old behavior. - -2.2.15 2016-12-10 ------------------ -* Updated mongodb-core to 2.1.2. - * Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. - * Emit reconnect event in primary joining when in connected status for a replicaset (Fixes mongoose reconnect issue). - -2.2.14 2016-12-08 ------------------ -* Updated mongodb-core to 2.1.1. -* NODE-892 Passthrough options.readPreference to mongodb-core ReplSet instance. - -2.2.13 2016-12-05 ------------------ -* Updated mongodb-core to 2.1.0. -* NODE-889 Fixed issue where legacy killcursor wire protocol messages would not be sent when APM is enabled. -* Expose parserType as property on topology objects. - -2.2.12 2016-11-29 ------------------ -* Updated mongodb-core to 2.0.14. - * Updated bson library to 0.5.7. - * Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). - * Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). - * Only check isConnected against availableConnections (Issue #142). - * NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. - * Set default servername to host is not passed through for sni. - * Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). - * NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. - * NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. - * NODE-850 Update Max Staleness implementation. - * NODE-849 username no longer required for MONGODB-X509 auth. - * NODE-848 BSON Regex flags must be alphabetically ordered. - * NODE-846 Create notice for all third party libraries. - * NODE-843 Executing bulk operations overwrites write concern parameter. - * NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. - * NODE-840 Resync CRUD spec tests. - * Unescapable while(true) loop (Issue #152). -* NODE-864 close event not emits during network issues using single server topology. -* Introduced maxStalenessSeconds. -* NODE-840 Added CRUD specification test cases and fix minor issues with upserts reporting matchedCount > 0. -* Don't ignore Db-level authSource when using auth method. (https://github.com/donaldguy). - -2.2.11 2016-10-21 ------------------ -* Updated mongodb-core to 2.0.13. - - Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). - - Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). - - Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). - - NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). -* Updated bson library to 0.5.6. - - Included cyclic dependency detection -* Fix typo in serverHeartbeatFailed event name (Issue #1418, https://github.com/jakesjews). -* NODE-824, readPreference "nearest" does not work when specified at collection level. -* NODE-822, GridFSBucketWriteStream end method does not handle optional parameters. -* NODE-823, GridFSBucketWriteStream end: callback is invoked with invalid parameters. -* NODE-829, Using Start/End offset option in GridFSBucketReadStream doesn't return the right sized buffer. - -2.2.10 2016-09-15 ------------------ -* Updated mongodb-core to 2.0.12. -* fix debug logging message not printing server name. -* fixed application metadata being sent by wrong ismaster. -* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. -* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". -* Updated bson library to 0.5.5. -* Added DBPointer up conversion to DBRef. -* MongoDB 3.4-RC Pass **appname** through MongoClient.connect uri or options to allow metadata to be passed. -* MongoDB 3.4-RC Pass collation options on update, findOne, find, createIndex, aggregate. -* MongoDB 3.4-RC Allow write concerns to be passed to all supporting server commands. -* MongoDB 3.4-RC Allow passing of **servername** as SSL options to support SNI. - -2.2.9 2016-08-29 ----------------- -* Updated mongodb-core to 2.0.11. -* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. -* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). -* Ensure promoteBuffers is propegated in same fashion as promoteValues and promoteLongs. -* Don't treat ObjectId as object for mapReduce scope (Issue #1397, https://github.com/vkarpov15). - -2.2.8 2016-08-23 ----------------- -* Updated mongodb-core to 2.0.10. -* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. -* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). - -2.2.7 2016-08-19 ----------------- -* If only a single mongos is provided in the seedlist, fix issue where it would be assigned as single standalone server instead of mongos topology (Issue #130). -* Updated mongodb-core to 2.0.9. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* NODE-798 Driver hangs on count command in replica set with one member. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* Allow passing in servername for TLS connections for SNI support. - -2.2.6 2016-08-16 ----------------- -* Updated mongodb-core to 2.0.8. -* Allow execution of store operations independent of having both a primary and secondary available (Issue #123). -* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. -* Allow passing in an array of tags to ReadPreference constructor (Issue #1382, https://github.com/vkarpov15) -* Added hashed connection names and fullResult. -* Updated bson library to 0.5.3. -* Enable maxTimeMS in count, distinct, findAndModify. - -2.2.5 2016-07-28 ----------------- -* Updated mongodb-core to 2.0.7. -* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). -* Added better warnings when passing in illegal seed list members to a Mongos topology. -* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. -* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) -* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. - -2.2.4 2016-07-19 ----------------- -* NPM corrupted upload fix. - -2.2.3 2016-07-19 ----------------- -* Updated mongodb-core to 2.0.6. -* Destroy connection on socket timeout due to newer node versions not closing the socket. - -2.2.2 2016-07-15 ----------------- -* Updated mongodb-core to 2.0.5. -* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. -* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. -* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. -* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. - -2.2.1 2016-07-11 ----------------- -* Updated mongodb-core to 2.0.4. -* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. -* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. -* NODE-746 Improves replicaset errors for wrong setName. - -2.2.0 2016-07-05 ----------------- -* Updated mongodb-core to 2.0.3. -* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. -* All authentication methods now handle both auth/reauthenticate and logout events. -* Introduced logout method to get rid of onAll option for logout command. -* Updated bson to 0.5.0 that includes Decimal128 support. -* Fixed logger error serialization issue. -* Documentation fixes. -* Implemented Server Selection Specification test suite. -* Added warning level to logger. -* Added warning message when sockeTimeout < haInterval for Replset/Mongos. -* Mongos emits close event on no proxies available or when reconnect attempt fails. -* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. -* Don't throw in auth methods but return error in callback. - -2.1.21 2016-05-30 ------------------ -* Updated mongodb-core to 1.3.21. -* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). -* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. -* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. -* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). -* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. -* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. - -2.1.20 2016-05-25 ------------------ -* Refactored MongoClient options handling to simplify the logic, unifying it. -* NODE-707 Implemented openUploadStreamWithId on GridFS to allow for custom fileIds so users are able to customize shard key and shard distribution. -* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. -* Updated mongodb-core to 1.3.20. -* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. -* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. -* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. - -2.1.19 2016-05-17 ----------------- -* Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. -* Ensure replicaset topology destroy is never called by SDAM. -* Ensure all paths are correctly returned on inspectServer in replset. -* Updated mongodb-core to 1.3.19 to fix minor connectivity issue on quick open/close of MongoClient connections on auth enabled mongodb Replicasets. - -2.1.18 2016-04-27 ------------------ -* Updated mongodb-core to 1.3.18 to fix Node 6.0 issues. - -2.1.17 2016-04-26 ------------------ -* Updated mongodb-core to 1.3.16 to work around issue with early versions of node 0.10.x due to missing unref method on ClearText streams. -* INT-1308: Allow listIndexes to inherit readPreference from Collection or DB. -* Fix timeout issue using new flags #1361. -* Updated mongodb-core to 1.3.17. -* Better handling of unique createIndex error. -* Emit error only if db instance has an error listener. -* DEFAULT authMechanism; don't throw error if explicitly set by user. - -2.1.16 2016-04-06 ------------------ -* Updated mongodb-core to 1.3.16. - -2.1.15 2016-04-06 ------------------ -* Updated mongodb-core to 1.3.15. -* Set ssl, sslValidate etc to mongosOptions on url_parser (Issue #1352, https://github.com/rubenstolk). -- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. -- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. - -2.1.14 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.13. -* Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. - -2.1.13 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.12. - -2.1.12 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.11. -* Mongos setting acceptableLatencyMS exposed to control the latency women for mongos selection. -* Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. -* isConnected method for mongos uses same selection code as getServer. -* Exceptions in cursor getServer trapped and correctly delegated to high level handler. - -2.1.11 2016-03-23 ------------------ -* Updated mongodb-core to 1.3.10. -* Introducing simplified connections settings. - -2.1.10 2016-03-21 ------------------ -* Updated mongodb-core to 1.3.9. -* Fixing issue that prevented mapReduce stats from being resolved (Issue #1351, https://github.com/davidgtonge) -* Forwards SDAM monitoring events from mongodb-core. - -2.1.9 2016-03-16 ----------------- -* Updated mongodb-core to 1.3.7 to fix intermittent race condition that causes some users to experience big amounts of socket connections. -* Makde bson parser in ordered/unordered bulk be directly from mongodb-core to avoid intermittent null error on mongoose. - -2.1.8 2016-03-14 ----------------- -* Updated mongodb-core to 1.3.5. -* NODE-660 TypeError: Cannot read property 'noRelease' of undefined. -* Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. -* Ensure RequestId can never be larger than Max Number integer size. -* NODE-661 typo in url_parser.js resulting in replSetServerOptions is not defined when connecting over ssl. -* Confusing error with invalid partial index filter (Issue #1341, https://github.com/vkarpov15). -* NODE-669 Should only error out promise for bulkWrite when error is a driver level error not a write error or write concern error. -* NODE-662 shallow copy options on methods that are not currently doing it to avoid passed in options mutiation. -* NODE-663 added lookup helper on aggregation cursor. -* NODE-585 Result object specified incorrectly for findAndModify?. -* NODE-666 harden validation for findAndModify CRUD methods. - -2.1.7 2016-02-09 ----------------- -* NODE-656 fixed corner case where cursor count command could be left without a connection available. -* NODE-658 Work around issue that bufferMaxEntries:-1 for js gets interpreted wrongly due to double nature of Javascript numbers. -* Fix: GridFS always returns the oldest version due to incorrect field name (Issue #1338, https://github.com/mdebruijne). -* NODE-655 GridFS stream support for cancelling upload streams and download streams (Issue #1339, https://github.com/vkarpov15). -* NODE-657 insertOne don`t return promise in some cases. -* Added destroy alias for abort function on GridFSBucketWriteStream. - -2.1.6 2016-02-05 ----------------- -* Updated mongodb-core to 1.3.1. - -2.1.5 2016-02-04 ----------------- -* Updated mongodb-core to 1.3.0. -* Added raw support for the command function on topologies. -* Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) -* Copy over all the properties to the callback returned from bindToDomain, (Issue #72) -* Added connection hash id to be able to reference connection host/name without leaking it outside of driver. -* NODE-638, Cannot authenticate database user with utf-8 password. -* Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. -* Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. -* Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. -* Switched to using Array.push instead of concat for use cases of a lot of documents. -* Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. -* Added peer optional dependencies support using require_optional module. -* Bug is listCollections for collection names that start with db name (Issue #1333, https://github.com/flyingfisher) -* Emit error before closing stream (Issue #1335, https://github.com/eagleeye) - -2.1.4 2016-01-12 ----------------- -* Restricted node engine to >0.10.3 (https://jira.mongodb.org/browse/NODE-635). -* Multiple database names ignored without a warning (https://jira.mongodb.org/browse/NODE-636, Issue #1324, https://github.com/yousefhamza). -* Convert custom readPreference objects in collection.js (Issue #1326, https://github.com/Machyne). - -2.1.3 2016-01-04 ----------------- -* Updated mongodb-core to 1.2.31. -* Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) - -2.1.2 2015-12-23 ----------------- -* Updated mongodb-core to 1.2.30. -* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -2.1.1 2015-12-13 ----------------- -* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. -* Added readPreference support to listCollections and listIndexes helpers. -* Updated mongodb-core to 1.2.28. - -2.1.0 2015-12-06 ----------------- -* Implements the connection string specification, https://github.com/mongodb/specifications/blob/master/source/connection-string/connection-string-spec.rst. -* Implements the new GridFS specification, https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst. -* Full MongoDB 3.2 support. -* NODE-601 Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -* Updated mongodb-core to 1.2.26. -* Return destination in GridStore pipe function. -* NODE-606 better error handling on destroyed topology for db.js methods. -* Added isDestroyed method to server, replset and mongos topologies. -* Upgraded test suite to run using mongodb-topology-manager. - -2.0.53 2015-12-23 ------------------ -* Updated mongodb-core to 1.2.30. -* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -2.0.52 2015-12-14 ------------------ -* removed remove from Gridstore.close. - -2.0.51 2015-12-13 ------------------ -* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. -* Added readPreference support to listCollections and listIndexes helpers. -* Updated mongodb-core to 1.2.28. - -2.0.50 2015-12-06 ------------------ -* Updated mongodb-core to 1.2.26. - -2.0.49 2015-11-20 ------------------ -* Updated mongodb-core to 1.2.24 with several fixes. - * Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). - * $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. - * ismaster runs against admin.$cmd instead of system.$cmd. - * Fixes to handle getMore command errors for MongoDB 3.2 - * Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. - -2.0.48 2015-11-07 ------------------ -* GridFS no longer performs any deletes when writing a brand new file that does not have any previous .fs.chunks or .fs.files documents. -* Updated mongodb-core to 1.2.21. -* Hardened the checking for replicaset equality checks. -* OpReplay flag correctly set on Wire protocol query. -* Mongos load balancing added, introduced localThresholdMS to control the feature. -* Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. - -2.0.47 2015-10-28 ------------------ -* Updated mongodb-core to 1.2.20. -* Fixed bug in arbiter connection capping code. -* NODE-599 correctly handle arrays of server tags in order of priority. -* Fix for 2.6 wire protocol handler related to readPreference handling. -* Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -* Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). - -2.0.46 2015-10-15 ------------------ -* Updated mongodb-core to 1.2.19. -* NODE-578 Order of sort fields is lost for numeric field names. -* Expose BSON Map (ES6 Map or polyfill). -* Minor fixes for APM support to pass extended APM test suite. - -2.0.45 2015-09-30 ------------------ -* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. - -2.0.44 2015-09-28 ------------------ -* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. -* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. -* Updated mongodb-core to 1.2.14. -* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. -* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) -* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. -* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. -* NODE-572 Remove examples that use the second parameter to `find()`. - -2.0.43 2015-09-14 ------------------ -* Propagate timeout event correctly to db instances. -* Application Monitoring API (APM) implemented. -* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. -* Updated mongodb-core to 1.2.12. -* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. -* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) -* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) -* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) - -2.0.42 2015-08-18 ------------------ -* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. - -2.0.41 2015-08-14 ------------------ -* Added missing Mongos.prototype.parserType function. -* Updated mongodb-core to 1.2.10. - -2.0.40 2015-07-14 ------------------ -* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. -* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. -* NODE-518 connectTimeoutMS is doubled in 2.0.39. -* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). -* NODE-526 Unique index not throwing duplicate key error. -* NODE-528 Ignore undefined fields in Collection.find(). -* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. - -2.0.39 2015-07-14 ------------------ -* Updated mongodb-core to 1.2.6 for NODE-505. - -2.0.38 2015-07-14 ------------------ -* NODE-505 Query fails to find records that have a 'result' property with an array value. - -2.0.37 2015-07-14 ------------------ -* NODE-504 Collection * Default options when using promiseLibrary. -* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. -* Updated mongodb-core to 1.2.5 to fix NODE-492. - -2.0.36 2015-07-07 ------------------ -* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). -* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. - -2.0.35 2015-06-17 ------------------ -* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. - -2.0.34 2015-06-17 ------------------ -* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. -* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. -* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. -* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. -* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. - -2.0.33 2015-05-20 ------------------ -* Bumped mongodb-core to 1.1.32. - -2.0.32 2015-05-19 ------------------ -* NODE-463 db.close immediately executes its callback. -* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). -* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. - -2.0.31 2015-05-08 ------------------ -* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. - -2.0.30 2015-05-07 ------------------ -* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. - -2.0.29 2015-05-07 ------------------ -* NODE-444 Possible memory leak, too many listeners added. -* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. -* Bumped mongodb-core to 1.1.26. - -2.0.28 2015-04-24 ------------------ -* Bumped mongodb-core to 1.1.25 -* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. -* NODE-430 Cursor.count() opts argument masked by var opts = {} -* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. -* NODE-438 replaceOne is not returning the result.ops property as described in the docs. -* NODE-433 _read, pipe and write all open gridstore automatically if not open. -* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. -* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. -* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). -* Minor fix in GridStore.exists for dealing with regular expressions searches. - -2.0.27 2015-04-07 ------------------ -* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. - -2.0.26 2015-04-07 ------------------ -* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. -* NODE-408 Expose GridStore.currentChunk.chunkNumber. - -2.0.25 2015-03-26 ------------------ -* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. - -2.0.24 2015-03-24 ------------------ -* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. -* Upgraded mongodb-core to 1.1.20. - -2.0.23 2015-03-21 ------------------ -* NODE-380 Correctly return MongoError from toError method. -* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. -* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. -* Upgraded mongodb-core to 1.1.19. - -2.0.22 2015-03-16 ------------------ -* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. -* Upgraded mongodb-core to 1.1.17. - -2.0.21 2015-03-06 ------------------ -* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. - -2.0.20 2015-03-04 ------------------ -* Updated mongodb-core 1.1.15 to relax pickserver method. - -2.0.19 2015-03-03 ------------------ -* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) -* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) -* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) - -2.0.18 2015-02-27 ------------------ -* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. - -2.0.17 2015-02-27 ------------------ -* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. -* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. - -2.0.16 2015-02-16 ------------------ -* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. -* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. -* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) - -2.0.15 2015-02-02 ------------------ -* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. -* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. -* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. -* Added ~1.0 mongodb-tools module for test running. -* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. - -2.0.14 2015-01-21 ------------------ -* Fixed some MongoClient.connect options pass through issues and added test coverage. -* Bumped mongodb-core to 1.1.9 including fixes for io.js - -2.0.13 2015-01-09 ------------------ -* Bumped mongodb-core to 1.1.8. -* Optimized query path for performance, moving Object.defineProperty outside of constructors. - -2.0.12 2014-12-22 ------------------ -* Minor fixes to listCollections to ensure correct querying of a collection when using a string. - -2.0.11 2014-12-19 ------------------ -* listCollections filters out index namespaces on < 2.8 correctly -* Bumped mongo-client to 1.1.7 - -2.0.10 2014-12-18 ------------------ -* NODE-328 fixed db.open return when no callback available issue and added test. -* NODE-327 Refactored listCollections to return cursor to support 2.8. -* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. -* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. -* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) -* Bumped mongo-client to 1.1.6 - -2.0.9 2014-12-01 ----------------- -* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. -* All classes are now strict (Issue #1233) -* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. -* Fixed recursion issues in debug logging due to JSON.stringify() -* Documentation fixes (Issue #1232, https://github.com/wsmoak) -* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) - -2.0.8 2014-11-28 ----------------- -* NODE-322 Finished up prototype refactoring of Db class. -* NODE-322 Exposed Cursor in index.js for New Relic. - -2.0.7 2014-11-20 ----------------- -* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. -* NODE-318 collection.update error while setting a function with serializeFunctions option. -* Documentation fixes. - -2.0.6 2014-11-14 ----------------- -* Refactored code to be prototype based instead of privileged methods. -* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. -* Implemented missing aspects of the CRUD specification. -* Fixed documentation issues. -* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) -* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) - -2.0.5 2014-10-29 ----------------- -* Minor fixes to documentation and generation of documentation. -* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. - -2.0.4 2014-10-23 ----------------- -* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) -* Made each rewind on each call allowing for re-using the cursor. -* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. -* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. - -2.0.3 2014-10-14 ----------------- -* NODE-297 Aggregate Broken for case of pipeline with no options. - -2.0.2 2014-10-08 ----------------- -* Bumped mongodb-core to 1.0.2. -* Fixed bson module dependency issue by relying on the mongodb-core one. -* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) - -2.0.1 2014-10-07 ----------------- -* Dependency fix - -2.0.0 2014-10-07 ----------------- -* First release of 2.0 driver - -2.0.0-alpha2 2014-10-02 ------------------------ -* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) -* Cluster Management Spec compatible. - -2.0.0-alpha1 2014-09-08 ------------------------ -* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode -* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package -* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node -* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) - * Might break some application -* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove -* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) -* Removed Grid class -* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data - + seek will fail if attempt to use with w or w+ - + write will fail if attempted with w+ or r - + w+ only works for updating metadata on a file -* Cursor toArray and each resets and re-runs the cursor -* FindAndModify returns whole result document instead of just value -* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find -* Removed db.dereference method -* Removed db.cursorInfo method -* Removed db.stats method -* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections -* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. -* Added db.listCollections to replace several methods above - -1.4.10 2014-09-04 ------------------ -* Fixed BSON and Kerberos compilation issues -* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series -* Fixed Kerberos and bumped to 0.0.4 - -1.4.9 2014-08-26 ----------------- -* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) -* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) -* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) -* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) -* NODE-240 Operations on SSL connection hang on node 0.11.x -* NODE-235 writeResult is not being passed on when error occurs in insert -* NODE-229 Allow count to work with query hints -* NODE-233 collection.save() does not support fullResult -* NODE-244 Should parseError also emit a `disconnected` event? -* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. -* NODE-248 Crash with X509 auth -* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks -* Bumped BSON parser to 0.2.12 - - -1.4.8 2014-08-01 ----------------- -* NODE-205 correctly emit authenticate event -* NODE-210 ensure no undefined connection error when checking server state -* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones -* NODE-220 don't throw error if ensureIndex errors out in Gridstore -* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes -* Fixed test running filters -* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) -* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) -* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) -* Fixed parsing issue for w:0 in url parser when in connection string -* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) - -1.4.7 2014-06-18 ----------------- -* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) -* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) - -1.4.6 2014-06-12 ----------------- -* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) -* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) -* Added missing type check before calling optional callback function (Issue #1180) - -1.4.5 2014-05-21 ----------------- -* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. -* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. -* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) - -1.4.4 2014-05-13 ----------------- -* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID -* Removed leaking global variable (Issue #1174, https://github.com/dainis) -* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) -* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) - -1.4.3 2014-05-01 ----------------- -* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) -* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) -* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) -* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) -* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) -* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) - -1.4.2 2014-04-15 ----------------- -* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 -* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) -* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) -* Fixed global variable leak (Issue #1160, https://github.com/vaseker) - -1.4.1 2014-04-09 ----------------- -* Correctly emit joined event when primary change -* Add _id to documents correctly when using bulk operations - -1.4.0 2014-04-03 ----------------- -* All node exceptions will no longer be caught if on('error') is defined -* Added X509 auth support -* Fix for MongoClient connection timeout issue (NODE-97) -* Pass through error messages from parseError instead of just text (Issue #1125) -* Close db connection on error (Issue #1128, https://github.com/benighted) -* Fixed documentation generation -* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) -* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 -* Insert/Update/Remove using new write commands when available -* Added support for new roles based API's in 2.6 for addUser/removeUser -* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries -* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes -* Support for OP_LOG_REPLAY flag (NODE-94) -* Fixes for SSL HA ping and discovery. -* Uses createIndexes if available for ensureIndex/createIndex -* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors -* Made CommandCursor behave as Readable stream. -* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. -* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. -* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) -* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. -* Refactored commands to all go through command function ensuring consistent command execution. -* Fixed issues where readPreferences where not correctly passed to mongos. -* Catch error == null and make err detection more prominent (NODE-130) -* Allow reads from arbiter for single server connection (NODE-117) -* Handle error coming back with no documents (NODE-130) -* Correctly use close parameter in Gridstore.write() (NODE-125) -* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) -* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) -* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) -* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) -* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) -* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) -* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) -* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) -* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) -* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) -* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) - -1.3.19 2013-08-21 ------------------ -* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. -* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) -* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) - -1.3.18 2013-08-10 ------------------ -* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) -* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. - -1.3.17 2013-08-07 ------------------ -* Ignore return commands that have no registered callback -* Made collection.count not use the db.command function -* Fix throw exception on ping command (Issue #1055) - -1.3.16 2013-08-02 ------------------ -* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) -* Bug in unlink mulit filename (Issue #1054) - -1.3.15 2013-08-01 ------------------ -* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time - -1.3.14 2013-08-01 ------------------ -* Fixed issue with checkKeys where it would error on X.X - -1.3.13 2013-07-31 ------------------ -* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) -* BSON size checking now done pre serialization (Issue #1037) -* Added isConnected returns false when no connection Pool exists (Issue #1043) -* Unified command handling to ensure same handling (Issue #1041, #1042) -* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) -* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. -* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. -* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. -* Fixed issue with Kerberos authentication on Windows for re-authentication. -* Fixed Mongos failover behavior to correctly throw out old servers. -* Ensure stored queries/write ops are executed correctly after connection timeout -* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. - -1.3.12 2013-07-19 ------------------ -* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) -* Fixed bug with callback third parameter on some commands (Issue #1033) -* Fixed possible issue where killcursor command might leave hanging functions -* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers -* Throw error if dbName or collection name contains null character (at command level and at collection level) -* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) - -1.3.11 2013-07-04 ------------------ -* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) -* Add driver version to export (Issue #1021, https://github.com/aheckmann) -* Add text to readpreference obedient commands (Issue #1019) -* Drivers should check the query failure bit even on getmore response (Issue #1018) -* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) -* Support SASL PLAIN authentication (Issue #1009) -* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) -* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) -* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) - -1.3.10 2013-06-17 ------------------ -* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) -* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) -* Introduced write and read concerns for GridFS (Issue #996) -* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) -* Fixed issue with pool size on replicaset connections (Issue #1000) -* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) - -1.3.9 2013-06-05 ----------------- -* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. - -1.3.8 2013-05-31 ----------------- -* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) -* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) -* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. - -1.3.7 2013-05-29 ----------------- -* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) -* Updated Bson to 0.1.9 to fix ARM support (Issue #985) - -1.3.6 2013-05-21 ----------------- -* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) -* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) - -1.3.5 2013-05-14 ----------------- -* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. - -1.3.4 2013-05-14 ----------------- -* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) -* Fixed bug when passing a named index hint (Issue #974) - -1.3.3 2013-05-09 ----------------- -* Fixed auto-reconnect issue with single server instance. - -1.3.2 2013-05-08 ----------------- -* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. - -1.3.1 2013-05-06 ----------------- -* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly -* Applied auth before server instance is set as connected when single server connection -* Throw error if array of documents passed to save method - -1.3.0 2013-04-25 ----------------- -* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. -* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) -* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) -* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) -* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition -* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) - -1.2.14 2013-03-14 ------------------ -* Refactored test suite to speed up running of replicaset tests -* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) -* Corrected a slaveOk setting issue (Issue #906, #905) -* Fixed HA issue where ping's would not go to correct server on HA server connection failure. -* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream -* Fixed race condition in Cursor stream (NODE-31) -* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 -* Added support for maxMessageSizeBytes if available (DRIVERS-1) -* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) -* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) - -1.2.13 2013-02-22 ------------------ -* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) -* Fixed missing MongoErrors on some cursor methods (Issue #882) -* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) -* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) -* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) - -1.2.12 2013-02-13 ------------------ -* Added limit/skip options to Collection.count (Issue #870) -* Added applySkipLimit option to Cursor.count (Issue #870) -* Enabled ping strategy as default for Replicaset if none specified (Issue #876) -* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) - -1.2.11 2013-01-29 ------------------ -* Added fixes for handling type 2 binary due to PHP driver (Issue #864) -* Moved callBackStore to Base class to have single unified store (Issue #866) -* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead - -1.2.10 2013-01-25 ------------------ -* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. -* Only open a new HA socket when previous one dead (Issue #859, #857) -* Minor fixes - -1.2.9 2013-01-15 ----------------- -* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) -* Connection string with no db specified should default to admin db (Issue #848) -* Support port passed as string to Server class (Issue #844) -* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) -* Included toError wrapper code moved to utils.js file (Issue #839, #840) -* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% - -1.2.8 2013-01-07 ----------------- -* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) -* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) -* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) -* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) -* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) -* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) -* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) -* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) - -1.2.7 2012-12-23 ----------------- -* Rolled back batches as they hang in certain situations -* Fixes for NODE-25, keep reading from secondaries when primary goes down - -1.2.6 2012-12-21 ----------------- -* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) -* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) -* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) -* Cursor readPreference bug for non-supported read preferences (Issue #817) - -1.2.5 2012-12-12 ----------------- -* Fixed ssl regression, added more test coverage (Issue #800) -* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) - -1.2.4 2012-12-11 ----------------- -* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. - -1.2.3 2012-12-10 ----------------- -* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) -* Fixed seek issue in gridstore when using stream (Issue #790) - -1.2.2 2012-12-03 ----------------- -* Fix for journal write concern not correctly being passed under some circumstances. -* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). - -1.2.1 2012-11-30 ----------------- -* Fix for double callback on insert with w:0 specified (Issue #783) -* Small cleanup of urlparser. - -1.2.0 2012-11-27 ----------------- -* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) -* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) -* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) -* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) -* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) -* Force correct setting of read_secondary based on the read preference (Issue #741) -* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) -* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type -* Mongos connection with auth not working (Issue #737) -* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") -* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db - * open/close/db/connect methods implemented -* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. -* Fixed a bug with aggregation helper not properly accepting readPreference - -1.1.11 2012-10-10 ------------------ -* Removed strict mode and introduced normal handling of safe at DB level. - -1.1.10 2012-10-08 ------------------ -* fix Admin.serverStatus (Issue #723, https://github.com/Contra) -* logging on connection open/close(Issue #721, https://github.com/asiletto) -* more fixes for windows bson install (Issue #724) - -1.1.9 2012-10-05 ----------------- -* Updated bson to 0.1.5 to fix build problem on sunos/windows. - -1.1.8 2012-10-01 ----------------- -* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) -* Cleanup of non-closing connections (Issue #706) -* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) -* Set keepalive on as default, override if not needed -* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) -* Added domain socket support new Server("/tmp/mongodb.sock") style - -1.1.7 2012-09-10 ----------------- -* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) -* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) -* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) -* Proper stopping of strategy on replicaset stop -* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) -* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) - -1.1.6 2012-09-01 ----------------- -* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) -* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) - -1.1.5 2012-08-29 ----------------- -* Fix for eval on replicaset Issue #684 -* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) -* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) -* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X -* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes -* Added exhaust option for find for feature completion (not recommended for normal use) -* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval -* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) - -1.1.4 2012-08-12 ----------------- -* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. -* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. -* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). -* Fix gridfs readstream (Issue #607, https://github.com/tedeh). -* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). -* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). -* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). -* Cleanup map reduce (Issue #614, https://github.com/aheckmann). -* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). -* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. -* Date identification handled correctly in bson js parser when running in vm context. -* Documentation updates -* GridStore filename not set on read (Issue #621) -* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls -* Added support for awaitdata for tailable cursors (Issue #624) -* Implementing read preference setting at collection and cursor level - * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) - * db.collection("some", {readPreference:Server.SECONDARY}) -* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. - * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to -* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) -* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 -* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) -* Fixed auth to work better when multiple connections are involved. -* Default connection pool size increased to 5 connections. -* Fixes for the ReadStream class to work properly with 0.8 of Node.js -* Added explain function support to aggregation helper -* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js -* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required -* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) -* Fixed Always emit db events (Issue #657) -* Close event not correctly resets DB openCalled variable to allow reconnect -* Added open event on connection established for replicaset, mongos and server -* Much faster BSON C++ parser thanks to Lucasfilm Singapore. -* Refactoring of replicaset connection logic to simplify the code. -* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) -* Minor optimization for findAndModify when not using j,w or fsync for safe - -1.0.2 2012-05-15 ----------------- -* Reconnect functionality for replicaset fix for mongodb 2.0.5 - -1.0.1 2012-05-12 ----------------- -* Passing back getLastError object as 3rd parameter on findAndModify command. -* Fixed a bunch of performance regressions in objectId and cursor. -* Fixed issue #600 allowing for single document delete to be passed in remove command. - -1.0.0 2012-04-25 ----------------- -* Fixes to handling of failover on server error -* Only emits error messages if there are error listeners to avoid uncaught events -* Server.isConnected using the server state variable not the connection pool state - -0.9.9.8 2012-04-12 ------------------- -* _id=0 is being turned into an ObjectID (Issue #551) -* fix for error in GridStore write method (Issue #559) -* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) -* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) -* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) -* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) -* Connection pools handles closing themselves down and clearing the state -* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) -* Returning update status document at the end of the callback for updates, (Issue #569) -* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) - -0.9.9.7 2012-03-16 ------------------- -* Stats not returned from map reduce with inline results (Issue #542) -* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) -* Streaming large files from GridFS causes truncation (Issue #540) -* Make callback type checks agnostic to V8 context boundaries (Issue #545) -* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback -* Db.open throws if the application attemps to call open again without calling close first - -0.9.9.6 2012-03-12 ------------------- -* BSON parser is externalized in it's own repository, currently using git master -* Fixes for Replicaset connectivity issue (Issue #537) -* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) -* Removed SimpleEmitter and replaced with standard EventEmitter -* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) - -0.9.9.5 2012-03-07 ------------------- -* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) -* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) -* Fixed memory leak in C++ bson parser (Issue #526) -* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) -* Cannot save files with the same file name to GridFS (Issue #531) - -0.9.9.4 2012-02-26 ------------------- -* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) - -0.9.9.3 2012-02-23 ------------------- -* document: save callback arguments are both undefined, (Issue #518) -* Native BSON parser install error with npm, (Issue #517) - -0.9.9.2 2012-02-17 ------------------- -* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. -* Added wrap error around db.dropDatabase to catch all errors (Issue #512) -* Added aggregate helper to collection, only for MongoDB >= 2.1 - -0.9.9.1 2012-02-15 ------------------- -* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. -* Mapreduce now throws error if out parameter is not specified. - -0.9.9 2012-02-13 ----------------- -* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. -* Db.close(true) now makes connection unusable as it's been force closed by app. -* Fixed mapReduce and group functions to correctly send slaveOk on queries. -* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). -* A fix for connection error handling when using the SSL on MongoDB. - -0.9.8-7 2012-02-06 ------------------- -* Simplified findOne to use the find command instead of the custom code (Issue #498). -* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). - -0.9.8-6 2012-02-04 ------------------- -* Removed the check for replicaset change code as it will never work with node.js. - -0.9.8-5 2012-02-02 ------------------- -* Added geoNear command to Collection. -* Added geoHaystackSearch command to Collection. -* Added indexes command to collection to retrieve the indexes on a Collection. -* Added stats command to collection to retrieve the statistics on a Collection. -* Added listDatabases command to admin object to allow retrieval of all available dbs. -* Changed createCreateIndexCommand to work better with options. -* Fixed dereference method on Db class to correctly dereference Db reference objects. -* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. -* Removed writeBuffer method from gridstore, write handles switching automatically now. -* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. -* Moved Long class to bson directory. - -0.9.8-4 2012-01-28 ------------------- -* Added reIndex command to collection and db level. -* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. -* Added dropDups and v option to createIndex and ensureIndex. -* Added isCapped method to Collection. -* Added indexExists method to Collection. -* Added findAndRemove method to Collection. -* Fixed bug for replicaset connection when no active servers in the set. -* Fixed bug for replicaset connections when errors occur during connection. -* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. - -0.9.8-3 2012-01-21 ------------------- -* Workaround for issue with Object.defineProperty (Issue #484) -* ObjectID generation with date does not set rest of fields to zero (Issue #482) - -0.9.8-2 2012-01-20 ------------------- -* Fixed a missing this in the ReplSetServers constructor. - -0.9.8-1 2012-01-17 ------------------- -* FindAndModify bug fix for duplicate errors (Issue #481) - -0.9.8 2012-01-17 ----------------- -* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. - * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) -* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh -* Removed duplicate code for formattedOrderClause and moved to utils module -* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members -* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations -* Correct handling of illegal BSON messages during deserialization -* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) -* Correctly update existing user password when using addUser (Issue #470) - -0.9.7.3-5 2012-01-04 --------------------- -* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' -* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors - -0.9.7.3-4 2012-01-04 --------------------- -* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) -* Sanity checks for GridFS performance with benchmark added - -0.9.7.3-3 2012-01-04 --------------------- -* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux -* BSON bug fixes for performance - -0.9.7.3-2 2012-01-02 --------------------- -* Fixed up documentation to reflect the preferred way of instantiating bson types -* GC bug fix for JS bson parser to avoid stop-and-go GC collection - -0.9.7.3-1 2012-01-02 --------------------- -* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously - -0.9.7.3 2011-12-30 --------------------- -* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes -* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) -* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 -* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) -* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) - -0.9.7.2-5 2011-12-22 --------------------- -* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann - -0.9.7.2-4 2011-12-21 --------------------- -* Refactoring of callback code to work around performance regression on linux -* Fixed group function to correctly use the command mode as default - -0.9.7.2-3 2011-12-18 --------------------- -* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). -* Allow for force send query to primary, pass option (read:'primary') on find command. - * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` - -0.9.7.2-2 2011-12-16 --------------------- -* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) - -0.9.7.2-1 2011-12-16 --------------------- -* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) -* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver -* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents - -0.9.7.2 2011-12-15 ------------------- -* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) - * pass in the ssl:true option to the server or replicaset server config to enable - * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). -* Added getTimestamp() method to objectID that returns a date object -* Added finalize function to collection.group - * function group (keys, condition, initial, reduce, finalize, command, callback) -* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. - * reaperInterval, set interval for reaper (default 10000 miliseconds) - * reaperTimeout, set timeout for calls (default 30000 miliseconds) - * reaper, enable/disable reaper (default false) -* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb -* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close -* EnsureIndex command can be executed without a callback (Issue #438) -* Eval function no accepts options including nolock (Issue #432) - * eval(code, parameters, options, callback) (where options = {nolock:true}) - -0.9.7.1-4 2011-11-27 --------------------- -* Replaced install.sh with install.js to install correctly on all supported os's - -0.9.7.1-3 2011-11-27 --------------------- -* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch - -0.9.7.1-2 2011-11-27 --------------------- -* Set statistical selection strategy as default for secondary choice. - -0.9.7.1-1 2011-11-27 --------------------- -* Better handling of single server reconnect (fixes some bugs) -* Better test coverage of single server failure -* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect - -0.9.7.1 2011-11-24 ------------------- -* Better handling of dead server for single server instances -* FindOne and find treats selector == null as {}, Issue #403 -* Possible to pass in a strategy for the replicaset to pick secondary reader node - * parameter strategy - * ping (default), pings the servers and picks the one with the lowest ping time - * statistical, measures each request and pick the one with the lowest mean and std deviation -* Set replicaset read preference replicaset.setReadPreference() - * Server.READ_PRIMARY (use primary server for reads) - * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) - * tags, {object of tags} -* Added replay of commands issued to a closed connection when the connection is re-established -* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) -* Moved reaper to db.open instead of constructor (Issue #406) -* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions - * timeout = set seconds before connection times out (default 0) - * noDelay = Disables the Nagle algorithm (default true) - * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) - * encoding = ['ascii', 'utf8', or 'base64'] (default null) -* Fixes for handling of errors during shutdown off a socket connection -* Correctly applies socket options including timeout -* Cleanup of test management code to close connections correctly -* Handle parser errors better, closing down the connection and emitting an error -* Correctly emit errors from server.js only wrapping errors that are strings - -0.9.7 2011-11-10 ----------------- -* Added priority setting to replicaset manager -* Added correct handling of passive servers in replicaset -* Reworked socket code for simpler clearer handling -* Correct handling of connections in test helpers -* Added control of retries on failure - * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance -* Added reaper that will timeout and cleanup queries that never return - * control with parameters reaperInterval and reaperTimeout when creating a db instance -* Refactored test helper classes for replicaset tests -* Allows raw (no bson parser mode for insert, update, remove, find and findOne) - * control raw mode passing in option raw:true on the commands - * will return buffers with the binary bson objects -* Fixed memory leak in cursor.toArray -* Fixed bug in command creation for mongodb server with wrong scope of call -* Added db(dbName) method to db.js to allow for reuse of connections against other databases -* Serialization of functions in an object is off by default, override with parameter - * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify -* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) -* FindOne and find now share same code execution and will work in the same manner, Issue #399 -* Fix for tailable cursors, Issue #384 -* Fix for Cursor rewind broken, Issue #389 -* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) -* Updated documentation on https://github.com/christkv/node-mongodb-native -* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data - -0.9.6-22 2011-10-15 -------------------- -* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 -* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 - -0.9.6-21 2011-10-05 -------------------- -* Reworked reconnect code to work correctly -* Handling errors in different parts of the code to ensure that it does not lock the connection -* Consistent error handling for Object.createFromHexString for JS and C++ - -0.9.6-20 2011-10-04 -------------------- -* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc -* Reworked bson.cc to throw error when trying to serialize js bson types -* Added MinKey, MaxKey and Double support for JS and C++ parser -* Reworked socket handling code to emit errors on unparsable messages -* Added logger option for Db class, lets you pass in a function in the shape - { - log : function(message, object) {}, - error : function(errorMessage, errorObject) {}, - debug : function(debugMessage, object) {}, - } - - Usage is new Db(new Server(..), {logger: loggerInstance}) - -0.9.6-19 2011-09-29 -------------------- -* Fixing compatibility issues between C++ bson parser and js parser -* Added Symbol support to C++ parser -* Fixed socket handling bug for seldom misaligned message from mongodb -* Correctly handles serialization of functions using the C++ bson parser - -0.9.6-18 2011-09-22 -------------------- -* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 - -0.9.6-17 2011-09-21 -------------------- -* Fixed broken exception test causing bamboo to hang -* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 - -0.9.6-16 2011-09-14 -------------------- -* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. -* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 - -0.9.6-15 2011-09-09 -------------------- -* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 -* Fixed authentication issue with secondary servers in Replicaset, Issue #334 -* Duplicate replica-set servers when omitting port, Issue #341 -* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 -* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks - -0.9.6-14 2011-09-05 -------------------- -* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 -* Minor doc fixes -* Some more cursor sort tests added, Issue #333 -* Fixes to work with 0.5.X branch -* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 -* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 -* Implement correct safe/strict mode for findAndModify. - -0.9.6-13 2011-08-24 -------------------- -* Db names correctly error checked for illegal characters - -0.9.6-12 2011-08-24 -------------------- -* Nasty bug in GridFS if you changed the default chunk size -* Fixed error handling bug in findOne - -0.9.6-11 2011-08-23 -------------------- -* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) -* Fixes for memory leaks when using buffers and C++ parser -* Fixes to make tests pass on 0.5.X -* Cleanup of bson.js to remove duplicated code paths -* Fix for errors occurring in ensureIndex, Issue #326 -* Removing require.paths to make tests work with the 0.5.X branch - -0.9.6-10 2011-08-11 -------------------- -* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 -* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 -* Implementing fixes for mongodb 1.9.1 and higher to make tests pass -* Admin validateCollection now takes an options argument for you to pass in full option -* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 -* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 - -0.9.6-9 -------- -* Bug fix for bson parsing the key '':'' correctly without crashing - -0.9.6-8 -------- -* Changed to using node.js crypto library MD5 digest -* Connect method support documented mongodb: syntax by (https://github.com/sethml) -* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 -* Code object without scope serializing to correct BSON type -* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 -* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) -* Fixed C++ parser to reflect JS parser handling of long deserialization -* Bson small optimizations - -0.9.6-7 2011-07-13 ------------------- -* JS Bson deserialization bug #287 - -0.9.6-6 2011-07-12 ------------------- -* FindAndModify not returning error message as other methods Issue #277 -* Added test coverage for $push, $pushAll and $inc atomic operations -* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 -* Fixed terrible deserialization bug in js bson code #285 -* Fix by andrewjstone to avoid throwing errors when this.primary not defined - -0.9.6-5 2011-07-06 ------------------- -* Rewritten BSON js parser now faster than the C parser on my core2duo laptop -* Added option full to indexInformation to get all index info Issue #265 -* Passing in ObjectID for new Gridstore works correctly Issue #272 - -0.9.6-4 2011-07-01 ------------------- -* Added test and bug fix for insert/update/remove without callback supplied - -0.9.6-3 2011-07-01 ------------------- -* Added simple grid class called Grid with put, get, delete methods -* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly -* Automatic handling of buffers when using write method on GridStore -* GridStore now accepts a ObjectID instead of file name for write and read methods -* GridStore.list accepts id option to return of file ids instead of filenames -* GridStore close method returns document for the file allowing user to reference _id field - -0.9.6-2 2011-06-30 ------------------- -* Fixes for reconnect logic for server object (replays auth correctly) -* More testcases for auth -* Fixes in error handling for replicaset -* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout -* Fixed slaveOk bug for findOne method -* Implemented auth support for replicaset and test cases -* Fixed error when not passing in rs_name - -0.9.6-1 2011-06-25 ------------------- -* Fixes for test to run properly using c++ bson parser -* Fixes for dbref in native parser (correctly handles ref without db component) -* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) -* Fixes for timestamp in js bson parser (distinct timestamp type now) - -0.9.6 2011-06-21 ----------------- -* Worked around npm version handling bug -* Race condition fix for cygwin (https://github.com/vincentcr) - -0.9.5-1 2011-06-21 ------------------- -* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems -* Fixed driver strict mode issue - -0.9.5 2011-06-20 ----------------- -* Replicaset support (failover and reading from secondary servers) -* Removed ServerPair and ServerCluster -* Added connection pool functionality -* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences -* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} - -0.6.8 ------ -* Removed multiple message concept from bson -* Changed db.open(db) to be db.open(err, db) - -0.1 2010-01-30 --------------- -* Initial release support of driver using native node.js interface -* Supports gridfs specification -* Supports admin functionality diff --git a/node_modules/mongoose/node_modules/mongodb/LICENSE.md b/node_modules/mongoose/node_modules/mongodb/LICENSE.md deleted file mode 100644 index ad410e1..0000000 --- a/node_modules/mongoose/node_modules/mongodb/LICENSE.md +++ /dev/null @@ -1,201 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mongodb/README.md b/node_modules/mongoose/node_modules/mongodb/README.md deleted file mode 100644 index 00d31d8..0000000 --- a/node_modules/mongoose/node_modules/mongodb/README.md +++ /dev/null @@ -1,499 +0,0 @@ -[![npm](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![npm](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) - -[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.svg?branch=2.1)](http://travis-ci.org/mongodb/node-mongodb-native) -[![Coverage Status](https://coveralls.io/repos/github/mongodb/node-mongodb-native/badge.svg?branch=2.1)](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1) -[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -# Description - -The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users. - -**NOTE: v3.x was recently released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).** - -## MongoDB Node.JS Driver - -| what | where | -|---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native | -| api-doc | http://mongodb.github.io/node-mongodb-native/3.1/api | -| source | https://github.com/mongodb/node-mongodb-native | -| mongodb | http://www.mongodb.org | - -### Bugs / Feature Requests - -Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a -case in our issue management tool, JIRA: - -- Create an account and login [jira.mongodb.org](https://jira.mongodb.org). -- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE). -- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. - -Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the -Core Server (i.e. SERVER) project are **public**. - -### Support / Feedback - -For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](https://docs.mongodb.com/manual/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [MongoDB Community Forums](https://community.mongodb.com/tags/c/drivers-odms-connectors/7/node-js-driver). - -### Change Log - -Change history can be found in [`HISTORY.md`](HISTORY.md). - -### Compatibility - -For version compatibility matrices, please refer to the following links: - - * [MongoDB](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-mongodb-node) - * [NodeJS](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-language-node) - -# Installation - -The recommended way to get started using the Node.js 3.0 driver is by using the `npm` (Node Package Manager) to install the dependency in your project. - -## MongoDB Driver - -Given that you have created your own project using `npm init` we install the MongoDB driver and its dependencies by executing the following `npm` command. - -```bash -npm install mongodb --save -``` - -This will download the MongoDB driver and add a dependency entry in your `package.json` file. - -You can also use the [Yarn](https://yarnpkg.com/en) package manager. - -## Troubleshooting - -The MongoDB driver depends on several other packages. These are: - -* [mongodb-core](https://github.com/mongodb-js/mongodb-core) -* [bson](https://github.com/mongodb/js-bson) -* [kerberos](https://github.com/mongodb-js/kerberos) -* [node-gyp](https://github.com/nodejs/node-gyp) - -The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the `kerberos` module. Furthermore, the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install. - -**Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.** - -### Diagnosing on UNIX - -If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps. - -```bash -git clone https://github.com/mongodb-js/kerberos -cd kerberos -npm install -``` - -If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install `node-gyp` globally: - -```bash -npm install -g node-gyp -``` - -If it correctly compiles and runs the tests you are golden. We can now try to install the `mongod` driver by performing the following command. - -```bash -cd yourproject -npm install mongodb --save -``` - -If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. - -```bash -npm --loglevel verbose install mongodb -``` - -This will print out all the steps npm is performing while trying to install the module. - -### Diagnosing on Windows - -A compiler tool chain known to work for compiling `kerberos` on Windows is the following. - -* Visual Studio C++ 2010 (do not use higher versions) -* Windows 7 64bit SDK -* Python 2.7 or higher - -Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`. - -```bash -npm install -g node-gyp -``` - -Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild: - -```bash -git clone https://github.com/christkv/kerberos.git -cd kerberos -npm install -node-gyp rebuild -``` - -This should rebuild the driver successfully if you have everything set up correctly. - -### Other possible issues - -Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there). - -Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed. - -## Quick Start - -This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [tutorials](docs/reference/content/tutorials/main.md). - -### Create the `package.json` file - -First, create a directory where your application will live. - -```bash -mkdir myproject -cd myproject -``` - -Enter the following command and answer the questions to create the initial structure for your new project: - -```bash -npm init -``` - -Next, install the driver dependency. - -```bash -npm install mongodb --save -``` - -You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. - -### Start a MongoDB Server - -For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). - -1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads) -2. Create a database directory (in this case under **/data**). -3. Install and start a ``mongod`` process. - -```bash -mongod --dbpath=/data -``` - -You should see the **mongod** process start up and print some status information. - -### Connect to MongoDB - -Create a new **app.js** file and add the following code to try out some basic CRUD -operations using the MongoDB driver. - -Add code to connect to the server and the database **myproject**: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - client.close(); -}); -``` - -Run your app from the command line with: - -```bash -node app.js -``` - -The application should print **Connected successfully to server** to the console. - -### Insert a Document - -Add to **app.js** the following function which uses the **insertMany** -method to add three documents to the **documents** collection. - -```js -const insertDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Insert some documents - collection.insertMany([ - {a : 1}, {a : 2}, {a : 3} - ], function(err, result) { - assert.equal(err, null); - assert.equal(3, result.result.n); - assert.equal(3, result.ops.length); - console.log("Inserted 3 documents into the collection"); - callback(result); - }); -} -``` - -The **insert** command returns an object with the following fields: - -* **result** Contains the result document from MongoDB -* **ops** Contains the documents inserted with added **_id** fields -* **connection** Contains the connection used to perform the insert - -Add the following code to call the **insertDocuments** function: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - client.close(); - }); -}); -``` - -Run the updated **app.js** file: - -```bash -node app.js -``` - -The operation returns the following output: - -```bash -Connected successfully to server -Inserted 3 documents into the collection -``` - -### Find All Documents - -Add a query that returns all the documents. - -```js -const findDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Find some documents - collection.find({}).toArray(function(err, docs) { - assert.equal(err, null); - console.log("Found the following records"); - console.log(docs) - callback(docs); - }); -} -``` - -This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - findDocuments(db, function() { - client.close(); - }); - }); -}); -``` - -### Find Documents with a Query Filter - -Add a query filter to find only documents which meet the query criteria. - -```js -const findDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Find some documents - collection.find({'a': 3}).toArray(function(err, docs) { - assert.equal(err, null); - console.log("Found the following records"); - console.log(docs); - callback(docs); - }); -} -``` - -Only the documents which match ``'a' : 3`` should be returned. - -### Update a document - -The following operation updates a document in the **documents** collection. - -```js -const updateDocument = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Update document where a is 2, set b equal to 1 - collection.updateOne({ a : 2 } - , { $set: { b : 1 } }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Updated the document with the field a equal to 2"); - callback(result); - }); -} -``` - -The method updates the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Next, update the callback function from **MongoClient.connect** to include the update method. - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - updateDocument(db, function() { - client.close(); - }); - }); -}); -``` - -### Remove a document - -Remove the document where the field **a** is equal to **3**. - -```js -const removeDocument = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Delete document where a is 3 - collection.deleteOne({ a : 3 }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Removed the document with the field a equal to 3"); - callback(result); - }); -} -``` - -Add the new method to the **MongoClient.connect** callback function. - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - updateDocument(db, function() { - removeDocument(db, function() { - client.close(); - }); - }); - }); -}); -``` - -### Index a Collection - -[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's -performance. The following function creates an index on the **a** field in the -**documents** collection. - -```js -const indexCollection = function(db, callback) { - db.collection('documents').createIndex( - { "a": 1 }, - null, - function(err, results) { - console.log(results); - callback(); - } - ); -}; -``` - -Add the ``indexCollection`` method to your app: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - indexCollection(db, function() { - client.close(); - }); - }); -}); -``` - -For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md). - -## Next Steps - - * [MongoDB Documentation](http://mongodb.org) - * [Read about Schemas](http://learnmongodbthehardway.com) - * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) - -## License - -[Apache 2.0](LICENSE.md) - -© 2009-2012 Christian Amor Kvalheim -© 2012-present MongoDB [Contributors](CONTRIBUTORS.md) diff --git a/node_modules/mongoose/node_modules/mongodb/index.js b/node_modules/mongoose/node_modules/mongodb/index.js deleted file mode 100644 index 4e9e635..0000000 --- a/node_modules/mongoose/node_modules/mongodb/index.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict'; - -// Core module -const core = require('./lib/core'); -const Instrumentation = require('./lib/apm'); - -// Set up the connect function -const connect = require('./lib/mongo_client').connect; - -// Expose error class -connect.MongoError = core.MongoError; -connect.MongoNetworkError = core.MongoNetworkError; -connect.MongoTimeoutError = core.MongoTimeoutError; -connect.MongoServerSelectionError = core.MongoServerSelectionError; -connect.MongoParseError = core.MongoParseError; -connect.MongoWriteConcernError = core.MongoWriteConcernError; -connect.MongoBulkWriteError = require('./lib/bulk/common').BulkWriteError; -connect.BulkWriteError = connect.MongoBulkWriteError; - -// Actual driver classes exported -connect.Admin = require('./lib/admin'); -connect.MongoClient = require('./lib/mongo_client'); -connect.Db = require('./lib/db'); -connect.Collection = require('./lib/collection'); -connect.Server = require('./lib/topologies/server'); -connect.ReplSet = require('./lib/topologies/replset'); -connect.Mongos = require('./lib/topologies/mongos'); -connect.ReadPreference = core.ReadPreference; -connect.GridStore = require('./lib/gridfs/grid_store'); -connect.Chunk = require('./lib/gridfs/chunk'); -connect.Logger = core.Logger; -connect.AggregationCursor = require('./lib/aggregation_cursor'); -connect.CommandCursor = require('./lib/command_cursor'); -connect.Cursor = require('./lib/cursor'); -connect.GridFSBucket = require('./lib/gridfs-stream'); -// Exported to be used in tests not to be used anywhere else -connect.CoreServer = core.Server; -connect.CoreConnection = core.Connection; - -// BSON types exported -connect.Binary = core.BSON.Binary; -connect.Code = core.BSON.Code; -connect.Map = core.BSON.Map; -connect.DBRef = core.BSON.DBRef; -connect.Double = core.BSON.Double; -connect.Int32 = core.BSON.Int32; -connect.Long = core.BSON.Long; -connect.MinKey = core.BSON.MinKey; -connect.MaxKey = core.BSON.MaxKey; -connect.ObjectID = core.BSON.ObjectID; -connect.ObjectId = core.BSON.ObjectID; -connect.Symbol = core.BSON.Symbol; -connect.Timestamp = core.BSON.Timestamp; -connect.BSONRegExp = core.BSON.BSONRegExp; -connect.Decimal128 = core.BSON.Decimal128; - -// Add connect method -connect.connect = connect; - -// Set up the instrumentation method -connect.instrument = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - const instrumentation = new Instrumentation(); - instrumentation.instrument(connect.MongoClient, callback); - return instrumentation; -}; - -// Set our exports to be the connect function -module.exports = connect; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/admin.js b/node_modules/mongoose/node_modules/mongodb/lib/admin.js deleted file mode 100644 index 716844b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/admin.js +++ /dev/null @@ -1,293 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('./utils').applyWriteConcern; - -const AddUserOperation = require('./operations/add_user'); -const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); -const RemoveUserOperation = require('./operations/remove_user'); -const ValidateCollectionOperation = require('./operations/validate_collection'); -const ListDatabasesOperation = require('./operations/list_databases'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Admin** class is an internal class that allows convenient access to - * the admin functionality and commands for MongoDB. - * - * **ADMIN Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Use the admin database for the operation - * const adminDb = client.db(dbName).admin(); - * - * // List all the available databases - * adminDb.listDatabases(function(err, dbs) { - * test.equal(null, err); - * test.ok(dbs.databases.length > 0); - * client.close(); - * }); - * }); - */ - -/** - * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {Admin} a collection instance. - */ -function Admin(db, topology, promiseLibrary) { - if (!(this instanceof Admin)) return new Admin(db, topology); - - // Internal state - this.s = { - db: db, - topology: topology, - promiseLibrary: promiseLibrary - }; -} - -/** - * The callback format for results - * @callback Admin~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.command = function(command, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : {}; - - const commandOperation = new ExecuteDbAdminCommandOperation(this.s.db, command, options); - - return executeOperation(this.s.db.s.topology, commandOperation, callback); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.buildInfo = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { buildinfo: 1 }; - - const buildInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, buildInfoOperation, callback); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverInfo = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { buildinfo: 1 }; - - const serverInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, serverInfoOperation, callback); -}; - -/** - * Retrieve this db's server status. - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverStatus = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const serverStatusOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - { serverStatus: 1 }, - options - ); - - return executeOperation(this.s.db.s.topology, serverStatusOperation, callback); -}; - -/** - * Ping the MongoDB server and retrieve results - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.ping = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { ping: 1 }; - - const pingOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, pingOperation, callback); -}; - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.addUser = function(username, password, options, callback) { - const args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - // Special case where there is no password ($external users) - if (typeof username === 'string' && password != null && typeof password === 'object') { - options = password; - password = null; - } - - options = args.length ? args.shift() : {}; - options = Object.assign({}, options); - // Get the options - options = applyWriteConcern(options, { db: this.s.db }); - // Set the db name to admin - options.dbName = 'admin'; - - const addUserOperation = new AddUserOperation(this.s.db, username, password, options); - - return executeOperation(this.s.db.s.topology, addUserOperation, callback); -}; - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.removeUser = function(username, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - options = args.length ? args.shift() : {}; - options = Object.assign({}, options); - // Get the options - options = applyWriteConcern(options, { db: this.s.db }); - // Set the db name - options.dbName = 'admin'; - - const removeUserOperation = new RemoveUserOperation(this.s.db, username, options); - - return executeOperation(this.s.db.s.topology, removeUserOperation, callback); -}; - -/** - * Validate an existing collection - * - * @param {string} collectionName The name of the collection to validate. - * @param {object} [options] Optional settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.validateCollection = function(collectionName, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const validateCollectionOperation = new ValidateCollectionOperation( - this, - collectionName, - options - ); - - return executeOperation(this.s.db.s.topology, validateCollectionOperation, callback); -}; - -/** - * List the available databases - * - * @param {object} [options] Optional settings. - * @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.listDatabases = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation( - this.s.db.s.topology, - new ListDatabasesOperation(this.s.db, options), - callback - ); -}; - -/** - * Get ReplicaSet status - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.replSetGetStatus = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const replSetGetStatusOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - { replSetGetStatus: 1 }, - options - ); - - return executeOperation(this.s.db.s.topology, replSetGetStatusOperation, callback); -}; - -module.exports = Admin; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js deleted file mode 100644 index b0977c6..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/aggregation_cursor.js +++ /dev/null @@ -1,370 +0,0 @@ -'use strict'; - -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const CursorState = require('./core/cursor').CursorState; -const deprecate = require('util').deprecate; - -/** - * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 4.X - * or higher stream - * - * **AGGREGATIONCURSOR Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // Show that duplicate records got dropped - * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class AggregationCursor - * @extends external:Readable - * @fires AggregationCursor#data - * @fires AggregationCursor#end - * @fires AggregationCursor#close - * @fires AggregationCursor#readable - * @return {AggregationCursor} an AggregationCursor instance. - */ -class AggregationCursor extends Cursor { - constructor(topology, operation, options) { - super(topology, operation, options); - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @throws {MongoError} - * @return {AggregationCursor} - */ - batchSize(value) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - this.operation.options.batchSize = value; - this.setCursorBatchSize(value); - return this; - } - - /** - * Add a geoNear stage to the aggregation pipeline - * @method - * @param {object} document The geoNear stage document. - * @return {AggregationCursor} - */ - geoNear(document) { - this.operation.addToPipeline({ $geoNear: document }); - return this; - } - - /** - * Add a group stage to the aggregation pipeline - * @method - * @param {object} document The group stage document. - * @return {AggregationCursor} - */ - group(document) { - this.operation.addToPipeline({ $group: document }); - return this; - } - - /** - * Add a limit stage to the aggregation pipeline - * @method - * @param {number} value The state limit value. - * @return {AggregationCursor} - */ - limit(value) { - this.operation.addToPipeline({ $limit: value }); - return this; - } - - /** - * Add a match stage to the aggregation pipeline - * @method - * @param {object} document The match stage document. - * @return {AggregationCursor} - */ - match(document) { - this.operation.addToPipeline({ $match: document }); - return this; - } - - /** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {AggregationCursor} - */ - maxTimeMS(value) { - this.operation.options.maxTimeMS = value; - return this; - } - - /** - * Add a out stage to the aggregation pipeline - * @method - * @param {number} destination The destination name. - * @return {AggregationCursor} - */ - out(destination) { - this.operation.addToPipeline({ $out: destination }); - return this; - } - - /** - * Add a project stage to the aggregation pipeline - * @method - * @param {object} document The project stage document. - * @return {AggregationCursor} - */ - project(document) { - this.operation.addToPipeline({ $project: document }); - return this; - } - - /** - * Add a lookup stage to the aggregation pipeline - * @method - * @param {object} document The lookup stage document. - * @return {AggregationCursor} - */ - lookup(document) { - this.operation.addToPipeline({ $lookup: document }); - return this; - } - - /** - * Add a redact stage to the aggregation pipeline - * @method - * @param {object} document The redact stage document. - * @return {AggregationCursor} - */ - redact(document) { - this.operation.addToPipeline({ $redact: document }); - return this; - } - - /** - * Add a skip stage to the aggregation pipeline - * @method - * @param {number} value The state skip value. - * @return {AggregationCursor} - */ - skip(value) { - this.operation.addToPipeline({ $skip: value }); - return this; - } - - /** - * Add a sort stage to the aggregation pipeline - * @method - * @param {object} document The sort stage document. - * @return {AggregationCursor} - */ - sort(document) { - this.operation.addToPipeline({ $sort: document }); - return this; - } - - /** - * Add a unwind stage to the aggregation pipeline - * @method - * @param {number} field The unwind field name. - * @return {AggregationCursor} - */ - unwind(field) { - this.operation.addToPipeline({ $unwind: field }); - return this; - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -// aliases -AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; - -// deprecated methods -deprecate( - AggregationCursor.prototype.geoNear, - 'The `$geoNear` stage is deprecated in MongoDB 4.0, and removed in version 4.2.' -); - -/** - * AggregationCursor stream data event, fired for each document in the cursor. - * - * @event AggregationCursor#data - * @type {object} - */ - -/** - * AggregationCursor stream end event - * - * @event AggregationCursor#end - * @type {null} - */ - -/** - * AggregationCursor stream close event - * - * @event AggregationCursor#close - * @type {null} - */ - -/** - * AggregationCursor stream readable event - * - * @event AggregationCursor#readable - * @type {null} - */ - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function AggregationCursor.prototype.next - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function AggregationCursor.prototype.hasNext - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previously accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method AggregationCursor.prototype.toArray - * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method AggregationCursor.prototype.each - * @deprecated - * @param {AggregationCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a AggregationCursor command and emitting close. - * @method AggregationCursor.prototype.close - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method AggregationCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Execute the explain for the cursor - * @method AggregationCursor.prototype.explain - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Clone the cursor - * @function AggregationCursor.prototype.clone - * @return {AggregationCursor} - */ - -/** - * Resets the cursor - * @function AggregationCursor.prototype.rewind - * @return {AggregationCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback AggregationCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback AggregationCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/** - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method AggregationCursor.prototype.forEach - * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. - * @param {AggregationCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -module.exports = AggregationCursor; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/apm.js b/node_modules/mongoose/node_modules/mongodb/lib/apm.js deleted file mode 100644 index f78e4aa..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/apm.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; -const EventEmitter = require('events').EventEmitter; - -class Instrumentation extends EventEmitter { - constructor() { - super(); - } - - instrument(MongoClient, callback) { - // store a reference to the original functions - this.$MongoClient = MongoClient; - const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect); - - const instrumentation = this; - MongoClient.prototype.connect = function(callback) { - this.s.options.monitorCommands = true; - this.on('commandStarted', event => instrumentation.emit('started', event)); - this.on('commandSucceeded', event => instrumentation.emit('succeeded', event)); - this.on('commandFailed', event => instrumentation.emit('failed', event)); - return $prototypeConnect.call(this, callback); - }; - - if (typeof callback === 'function') callback(null, this); - } - - uninstrument() { - this.$MongoClient.prototype.connect = this.$prototypeConnect; - } -} - -module.exports = Instrumentation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/async/.eslintrc b/node_modules/mongoose/node_modules/mongodb/lib/async/.eslintrc deleted file mode 100644 index 93b2f64..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/async/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "parserOptions": { - "ecmaVersion": 2018 - } -} diff --git a/node_modules/mongoose/node_modules/mongodb/lib/async/async_iterator.js b/node_modules/mongoose/node_modules/mongodb/lib/async/async_iterator.js deleted file mode 100644 index 6021aad..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/async/async_iterator.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -// async function* asyncIterator() { -// while (true) { -// const value = await this.next(); -// if (!value) { -// await this.close(); -// return; -// } - -// yield value; -// } -// } - -// TODO: change this to the async generator function above -function asyncIterator() { - const cursor = this; - - return { - next: function() { - return Promise.resolve() - .then(() => cursor.next()) - .then(value => { - if (!value) { - return cursor.close().then(() => ({ value, done: true })); - } - return { value, done: false }; - }); - } - }; -} - -exports.asyncIterator = asyncIterator; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js b/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js deleted file mode 100644 index fea6c18..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/bulk/common.js +++ /dev/null @@ -1,1260 +0,0 @@ -'use strict'; - -const Long = require('../core').BSON.Long; -const MongoError = require('../core').MongoError; -const ObjectID = require('../core').BSON.ObjectID; -const BSON = require('../core').BSON; -const MongoWriteConcernError = require('../core').MongoWriteConcernError; -const toError = require('../utils').toError; -const handleCallback = require('../utils').handleCallback; -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const executeLegacyOperation = require('../utils').executeLegacyOperation; -const isPromiseLike = require('../utils').isPromiseLike; - -// Error codes -const WRITE_CONCERN_ERROR = 64; - -// Insert types -const INSERT = 1; -const UPDATE = 2; -const REMOVE = 3; - -const bson = new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp -]); - -/** - * Keeps the state of a unordered batch so we can rewrite the results - * correctly after command execution - * @ignore - */ -class Batch { - constructor(batchType, originalZeroIndex) { - this.originalZeroIndex = originalZeroIndex; - this.currentIndex = 0; - this.originalIndexes = []; - this.batchType = batchType; - this.operations = []; - this.size = 0; - this.sizeBytes = 0; - } -} - -/** - * @classdesc - * The result of a bulk write. - */ -class BulkWriteResult { - /** - * Create a new BulkWriteResult instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(bulkResult) { - this.result = bulkResult; - } - - /** - * Evaluates to true if the bulk operation correctly executes - * @type {boolean} - */ - get ok() { - return this.result.ok; - } - - /** - * The number of inserted documents - * @type {number} - */ - get nInserted() { - return this.result.nInserted; - } - - /** - * Number of upserted documents - * @type {number} - */ - get nUpserted() { - return this.result.nUpserted; - } - - /** - * Number of matched documents - * @type {number} - */ - get nMatched() { - return this.result.nMatched; - } - - /** - * Number of documents updated physically on disk - * @type {number} - */ - get nModified() { - return this.result.nModified; - } - - /** - * Number of removed documents - * @type {number} - */ - get nRemoved() { - return this.result.nRemoved; - } - - /** - * Returns an array of all inserted ids - * - * @return {object[]} - */ - getInsertedIds() { - return this.result.insertedIds; - } - - /** - * Returns an array of all upserted ids - * - * @return {object[]} - */ - getUpsertedIds() { - return this.result.upserted; - } - - /** - * Returns the upserted id at the given index - * - * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index - * @return {object} - */ - getUpsertedIdAt(index) { - return this.result.upserted[index]; - } - - /** - * Returns raw internal result - * - * @return {object} - */ - getRawResponse() { - return this.result; - } - - /** - * Returns true if the bulk operation contains a write error - * - * @return {boolean} - */ - hasWriteErrors() { - return this.result.writeErrors.length > 0; - } - - /** - * Returns the number of write errors off the bulk operation - * - * @return {number} - */ - getWriteErrorCount() { - return this.result.writeErrors.length; - } - - /** - * Returns a specific write error object - * - * @param {number} index of the write error to return, returns null if there is no result for passed in index - * @return {WriteError} - */ - getWriteErrorAt(index) { - if (index < this.result.writeErrors.length) { - return this.result.writeErrors[index]; - } - return null; - } - - /** - * Retrieve all write errors - * - * @return {WriteError[]} - */ - getWriteErrors() { - return this.result.writeErrors; - } - - /** - * Retrieve lastOp if available - * - * @return {object} - */ - getLastOp() { - return this.result.lastOp; - } - - /** - * Retrieve the write concern error if any - * - * @return {WriteConcernError} - */ - getWriteConcernError() { - if (this.result.writeConcernErrors.length === 0) { - return null; - } else if (this.result.writeConcernErrors.length === 1) { - // Return the error - return this.result.writeConcernErrors[0]; - } else { - // Combine the errors - let errmsg = ''; - for (let i = 0; i < this.result.writeConcernErrors.length; i++) { - const err = this.result.writeConcernErrors[i]; - errmsg = errmsg + err.errmsg; - - // TODO: Something better - if (i === 0) errmsg = errmsg + ' and '; - } - - return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR }); - } - } - - /** - * @return {object} - */ - toJSON() { - return this.result; - } - - /** - * @return {string} - */ - toString() { - return `BulkWriteResult(${this.toJSON(this.result)})`; - } - - /** - * @return {boolean} - */ - isOk() { - return this.result.ok === 1; - } -} - -/** - * @classdesc An error representing a failure by the server to apply the requested write concern to the bulk operation. - */ -class WriteConcernError { - /** - * Create a new WriteConcernError instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(err) { - this.err = err; - } - - /** - * Write concern error code. - * @type {number} - */ - get code() { - return this.err.code; - } - - /** - * Write concern error message. - * @type {string} - */ - get errmsg() { - return this.err.errmsg; - } - - /** - * @return {object} - */ - toJSON() { - return { code: this.err.code, errmsg: this.err.errmsg }; - } - - /** - * @return {string} - */ - toString() { - return `WriteConcernError(${this.err.errmsg})`; - } -} - -/** - * @classdesc An error that occurred during a BulkWrite on the server. - */ -class WriteError { - /** - * Create a new WriteError instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(err) { - this.err = err; - } - - /** - * WriteError code. - * @type {number} - */ - get code() { - return this.err.code; - } - - /** - * WriteError original bulk operation index. - * @type {number} - */ - get index() { - return this.err.index; - } - - /** - * WriteError message. - * @type {string} - */ - get errmsg() { - return this.err.errmsg; - } - - /** - * Returns the underlying operation that caused the error - * @return {object} - */ - getOperation() { - return this.err.op; - } - - /** - * @return {object} - */ - toJSON() { - return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; - } - - /** - * @return {string} - */ - toString() { - return `WriteError(${JSON.stringify(this.toJSON())})`; - } -} - -/** - * Merges results into shared data structure - * @ignore - */ -function mergeBatchResults(batch, bulkResult, err, result) { - // If we have an error set the result to be the err object - if (err) { - result = err; - } else if (result && result.result) { - result = result.result; - } else if (result == null) { - return; - } - - // Do we have a top level error stop processing and return - if (result.ok === 0 && bulkResult.ok === 1) { - bulkResult.ok = 0; - - const writeError = { - index: 0, - code: result.code || 0, - errmsg: result.message, - op: batch.operations[0] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - return; - } else if (result.ok === 0 && bulkResult.ok === 0) { - return; - } - - // Deal with opTime if available - if (result.opTime || result.lastOp) { - const opTime = result.lastOp || result.opTime; - let lastOpTS = null; - let lastOpT = null; - - // We have a time stamp - if (opTime && opTime._bsontype === 'Timestamp') { - if (bulkResult.lastOp == null) { - bulkResult.lastOp = opTime; - } else if (opTime.greaterThan(bulkResult.lastOp)) { - bulkResult.lastOp = opTime; - } - } else { - // Existing TS - if (bulkResult.lastOp) { - lastOpTS = - typeof bulkResult.lastOp.ts === 'number' - ? Long.fromNumber(bulkResult.lastOp.ts) - : bulkResult.lastOp.ts; - lastOpT = - typeof bulkResult.lastOp.t === 'number' - ? Long.fromNumber(bulkResult.lastOp.t) - : bulkResult.lastOp.t; - } - - // Current OpTime TS - const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts; - const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t; - - // Compare the opTime's - if (bulkResult.lastOp == null) { - bulkResult.lastOp = opTime; - } else if (opTimeTS.greaterThan(lastOpTS)) { - bulkResult.lastOp = opTime; - } else if (opTimeTS.equals(lastOpTS)) { - if (opTimeT.greaterThan(lastOpT)) { - bulkResult.lastOp = opTime; - } - } - } - } - - // If we have an insert Batch type - if (batch.batchType === INSERT && result.n) { - bulkResult.nInserted = bulkResult.nInserted + result.n; - } - - // If we have an insert Batch type - if (batch.batchType === REMOVE && result.n) { - bulkResult.nRemoved = bulkResult.nRemoved + result.n; - } - - let nUpserted = 0; - - // We have an array of upserted values, we need to rewrite the indexes - if (Array.isArray(result.upserted)) { - nUpserted = result.upserted.length; - - for (let i = 0; i < result.upserted.length; i++) { - bulkResult.upserted.push({ - index: result.upserted[i].index + batch.originalZeroIndex, - _id: result.upserted[i]._id - }); - } - } else if (result.upserted) { - nUpserted = 1; - - bulkResult.upserted.push({ - index: batch.originalZeroIndex, - _id: result.upserted - }); - } - - // If we have an update Batch type - if (batch.batchType === UPDATE && result.n) { - const nModified = result.nModified; - bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; - bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); - - if (typeof nModified === 'number') { - bulkResult.nModified = bulkResult.nModified + nModified; - } else { - bulkResult.nModified = null; - } - } - - if (Array.isArray(result.writeErrors)) { - for (let i = 0; i < result.writeErrors.length; i++) { - const writeError = { - index: batch.originalIndexes[result.writeErrors[i].index], - code: result.writeErrors[i].code, - errmsg: result.writeErrors[i].errmsg, - op: batch.operations[result.writeErrors[i].index] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - } - } - - if (result.writeConcernError) { - bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); - } -} - -function executeCommands(bulkOperation, options, callback) { - if (bulkOperation.s.batches.length === 0) { - return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult)); - } - - const batch = bulkOperation.s.batches.shift(); - - function resultHandler(err, result) { - // Error is a driver related error not a bulk op error, terminate - if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { - return handleCallback(callback, err); - } - - // If we have and error - if (err) err.ok = 0; - if (err instanceof MongoWriteConcernError) { - return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback); - } - - // Merge the results together - const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); - const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); - if (mergeResult != null) { - return handleCallback(callback, null, writeResult); - } - - if (bulkOperation.handleWriteError(callback, writeResult)) return; - - // Execute the next command in line - executeCommands(bulkOperation, options, callback); - } - - bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); -} - -/** - * handles write concern error - * - * @ignore - * @param {object} batch - * @param {object} bulkResult - * @param {boolean} ordered - * @param {WriteConcernError} err - * @param {function} callback - */ -function handleMongoWriteConcernError(batch, bulkResult, err, callback) { - mergeBatchResults(batch, bulkResult, null, err.result); - - const wrappedWriteConcernError = new WriteConcernError({ - errmsg: err.result.writeConcernError.errmsg, - code: err.result.writeConcernError.result - }); - return handleCallback( - callback, - new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)), - null - ); -} - -/** - * @classdesc An error indicating an unsuccessful Bulk Write - */ -class BulkWriteError extends MongoError { - /** - * Creates a new BulkWriteError - * - * @param {Error|string|object} message The error message - * @param {BulkWriteResult} result The result of the bulk write operation - * @extends {MongoError} - */ - constructor(error, result) { - const message = error.err || error.errmsg || error.errMessage || error; - super(message); - - Object.assign(this, error); - - this.name = 'BulkWriteError'; - this.result = result; - } -} - -/** - * @classdesc A builder object that is returned from {@link BulkOperationBase#find}. - * Is used to build a write operation that involves a query filter. - */ -class FindOperators { - /** - * Creates a new FindOperators object. - * - * **NOTE:** Internal Type, do not instantiate directly - * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation - */ - constructor(bulkOperation) { - this.s = bulkOperation.s; - } - - /** - * Add a multiple update operation to the bulk operation - * - * @method - * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - update(updateDocument) { - // Perform upsert - const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - const document = { - q: this.s.currentOp.selector, - u: updateDocument, - multi: true, - upsert: upsert - }; - - if (updateDocument.hint) { - document.hint = updateDocument.hint; - } - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } - - /** - * Add a single update operation to the bulk operation - * - * @method - * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - updateOne(updateDocument) { - // Perform upsert - const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - const document = { - q: this.s.currentOp.selector, - u: updateDocument, - multi: false, - upsert: upsert - }; - - if (updateDocument.hint) { - document.hint = updateDocument.hint; - } - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } - - /** - * Add a replace one operation to the bulk operation - * - * @method - * @param {object} updateDocument the new document to replace the existing one with - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - replaceOne(updateDocument) { - this.updateOne(updateDocument); - } - - /** - * Upsert modifier for update bulk operation, noting that this operation is an upsert. - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {FindOperators} reference to self - */ - upsert() { - this.s.currentOp.upsert = true; - return this; - } - - /** - * Add a delete one operation to the bulk operation - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - deleteOne() { - // Establish the update command - const document = { - q: this.s.currentOp.selector, - limit: 1 - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } - - /** - * Add a delete many operation to the bulk operation - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - delete() { - // Establish the update command - const document = { - q: this.s.currentOp.selector, - limit: 0 - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } - - /** - * backwards compatability for deleteOne - */ - removeOne() { - return this.deleteOne(); - } - - /** - * backwards compatability for delete - */ - remove() { - return this.delete(); - } -} - -/** - * @classdesc Parent class to OrderedBulkOperation and UnorderedBulkOperation - * - * **NOTE:** Internal Type, do not instantiate directly - */ -class BulkOperationBase { - /** - * Create a new OrderedBulkOperation or UnorderedBulkOperation instance - * @property {number} length Get the number of operations in the bulk. - */ - constructor(topology, collection, options, isOrdered) { - // determine whether bulkOperation is ordered or unordered - this.isOrdered = isOrdered; - - options = options == null ? {} : options; - // TODO Bring from driver information in isMaster - // Get the namespace for the write operations - const namespace = collection.s.namespace; - // Used to mark operation as executed - const executed = false; - - // Current item - const currentOp = null; - - // Handle to the bson serializer, used to calculate running sizes - const bson = topology.bson; - // Set max byte size - const isMaster = topology.lastIsMaster(); - - // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents - // over 2mb are still allowed - const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter); - const maxBsonObjectSize = - isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16; - const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize; - const maxWriteBatchSize = - isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000; - - // Calculates the largest possible size of an Array key, represented as a BSON string - // element. This calculation: - // 1 byte for BSON type - // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) - // + 1 bytes for null terminator - const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, collection.s.db); - finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options); - const writeConcern = finalOptions.writeConcern; - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Final results - const bulkResult = { - ok: 1, - writeErrors: [], - writeConcernErrors: [], - insertedIds: [], - nInserted: 0, - nUpserted: 0, - nMatched: 0, - nModified: 0, - nRemoved: 0, - upserted: [] - }; - - // Internal state - this.s = { - // Final result - bulkResult: bulkResult, - // Current batch state - currentBatch: null, - currentIndex: 0, - // ordered specific - currentBatchSize: 0, - currentBatchSizeBytes: 0, - // unordered specific - currentInsertBatch: null, - currentUpdateBatch: null, - currentRemoveBatch: null, - batches: [], - // Write concern - writeConcern: writeConcern, - // Max batch size options - maxBsonObjectSize, - maxBatchSizeBytes, - maxWriteBatchSize, - maxKeySize, - // Namespace - namespace: namespace, - // BSON - bson: bson, - // Topology - topology: topology, - // Options - options: finalOptions, - // Current operation - currentOp: currentOp, - // Executed - executed: executed, - // Collection - collection: collection, - // Promise Library - promiseLibrary: promiseLibrary, - // Fundamental error - err: null, - // check keys - checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true - }; - - // bypass Validation - if (options.bypassDocumentValidation === true) { - this.s.bypassDocumentValidation = true; - } - } - - /** - * Add a single insert document to the bulk operation - * - * @param {object} document the document to insert - * @throws {MongoError} - * @return {BulkOperationBase} A reference to self - * - * @example - * const bulkOp = collection.initializeOrderedBulkOp(); - * // Adds three inserts to the bulkOp. - * bulkOp - * .insert({ a: 1 }) - * .insert({ b: 2 }) - * .insert({ c: 3 }); - * await bulkOp.execute(); - */ - insert(document) { - if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) - document._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, document); - } - - /** - * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. - * Returns a builder object used to complete the definition of the operation. - * - * @method - * @param {object} selector The selector for the bulk operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-q q documentation} - * @throws {MongoError} if a selector is not specified - * @return {FindOperators} A helper object with which the write operation can be defined. - * - * @example - * const bulkOp = collection.initializeOrderedBulkOp(); - * - * // Add an updateOne to the bulkOp - * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); - * - * // Add an updateMany to the bulkOp - * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); - * - * // Add an upsert - * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); - * - * // Add a deletion - * bulkOp.find({ g: 7 }).deleteOne(); - * - * // Add a multi deletion - * bulkOp.find({ h: 8 }).delete(); - * - * // Add a replaceOne - * bulkOp.find({ i: 9 }).replaceOne({ j: 10 }); - * - * // Update using a pipeline (requires Mongodb 4.2 or higher) - * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ - * { $set: { total: { $sum: [ '$y', '$z' ] } } } - * ]); - * - * // All of the ops will now be executed - * await bulkOp.execute(); - */ - find(selector) { - if (!selector) { - throw toError('Bulk find operation must specify a selector'); - } - - // Save a current selector - this.s.currentOp = { - selector: selector - }; - - return new FindOperators(this); - } - - /** - * Specifies a raw operation to perform in the bulk write. - * - * @method - * @param {object} op The raw operation to perform. - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @return {BulkOperationBase} A reference to self - */ - raw(op) { - const key = Object.keys(op)[0]; - - // Set up the force server object id - const forceServerObjectId = - typeof this.s.options.forceServerObjectId === 'boolean' - ? this.s.options.forceServerObjectId - : this.s.collection.s.db.options.forceServerObjectId; - - // Update operations - if ( - (op.updateOne && op.updateOne.q) || - (op.updateMany && op.updateMany.q) || - (op.replaceOne && op.replaceOne.q) - ) { - op[key].multi = op.updateOne || op.replaceOne ? false : true; - return this.s.options.addToOperationsList(this, UPDATE, op[key]); - } - - // Crud spec update format - if (op.updateOne || op.updateMany || op.replaceOne) { - const multi = op.updateOne || op.replaceOne ? false : true; - const operation = { - q: op[key].filter, - u: op[key].update || op[key].replacement, - multi: multi - }; - - if (op[key].hint) { - operation.hint = op[key].hint; - } - - if (this.isOrdered) { - operation.upsert = op[key].upsert ? true : false; - if (op.collation) operation.collation = op.collation; - } else { - if (op[key].upsert) operation.upsert = true; - } - if (op[key].arrayFilters) operation.arrayFilters = op[key].arrayFilters; - return this.s.options.addToOperationsList(this, UPDATE, operation); - } - - // Remove operations - if ( - op.removeOne || - op.removeMany || - (op.deleteOne && op.deleteOne.q) || - (op.deleteMany && op.deleteMany.q) - ) { - op[key].limit = op.removeOne ? 1 : 0; - return this.s.options.addToOperationsList(this, REMOVE, op[key]); - } - - // Crud spec delete operations, less efficient - if (op.deleteOne || op.deleteMany) { - const limit = op.deleteOne ? 1 : 0; - const operation = { q: op[key].filter, limit: limit }; - if (this.isOrdered) { - if (op.collation) operation.collation = op.collation; - } - return this.s.options.addToOperationsList(this, REMOVE, operation); - } - - // Insert operations - if (op.insertOne && op.insertOne.document == null) { - if (forceServerObjectId !== true && op.insertOne._id == null) - op.insertOne._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, op.insertOne); - } else if (op.insertOne && op.insertOne.document) { - if (forceServerObjectId !== true && op.insertOne.document._id == null) - op.insertOne.document._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document); - } - - if (op.insertMany) { - for (let i = 0; i < op.insertMany.length; i++) { - if (forceServerObjectId !== true && op.insertMany[i]._id == null) - op.insertMany[i]._id = new ObjectID(); - this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]); - } - - return; - } - - // No valid type of operation - throw toError( - 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany' - ); - } - - /** - * helper function to assist with promiseOrCallback behavior - * @ignore - * @param {*} err - * @param {*} callback - */ - _handleEarlyError(err, callback) { - if (typeof callback === 'function') { - callback(err, null); - return; - } - - return this.s.promiseLibrary.reject(err); - } - - /** - * An internal helper method. Do not invoke directly. Will be going away in the future - * - * @ignore - * @method - * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation - * @param {object} writeConcern - * @param {object} options - * @param {function} callback - */ - bulkExecute(_writeConcern, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (typeof _writeConcern === 'function') { - callback = _writeConcern; - } else if (_writeConcern && typeof _writeConcern === 'object') { - this.s.writeConcern = _writeConcern; - } - - if (this.s.executed) { - const executedError = toError('batch cannot be re-executed'); - return this._handleEarlyError(executedError, callback); - } - - // If we have current batch - if (this.isOrdered) { - if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); - } else { - if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); - if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); - if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); - } - // If we have no operations in the bulk raise an error - if (this.s.batches.length === 0) { - const emptyBatchError = toError('Invalid Operation, no operations specified'); - return this._handleEarlyError(emptyBatchError, callback); - } - return { options, callback }; - } - - /** - * The callback format for results - * @callback BulkOperationBase~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {BulkWriteResult} result The bulk write result. - */ - - /** - * Execute the bulk operation - * - * @method - * @param {WriteConcern} [_writeConcern] Optional write concern. Can also be specified through options. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {BulkOperationBase~resultCallback} [callback] A callback that will be invoked when bulkWrite finishes/errors - * @throws {MongoError} Throws error if the bulk object has already been executed - * @throws {MongoError} Throws error if the bulk object does not have any operations - * @return {Promise|void} returns Promise if no callback passed - */ - execute(_writeConcern, options, callback) { - const ret = this.bulkExecute(_writeConcern, options, callback); - if (!ret || isPromiseLike(ret)) { - return ret; - } - - options = ret.options; - callback = ret.callback; - - return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]); - } - - /** - * Handles final options before executing command - * - * An internal method. Do not invoke. Will not be accessible in the future - * - * @ignore - * @param {object} config - * @param {object} config.options - * @param {number} config.batch - * @param {function} config.resultHandler - * @param {function} callback - */ - finalOptionsHandler(config, callback) { - const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options); - if (this.s.writeConcern != null) { - finalOptions.writeConcern = this.s.writeConcern; - } - - if (finalOptions.bypassDocumentValidation !== true) { - delete finalOptions.bypassDocumentValidation; - } - - // Set an operationIf if provided - if (this.operationId) { - config.resultHandler.operationId = this.operationId; - } - - // Serialize functions - if (this.s.options.serializeFunctions) { - finalOptions.serializeFunctions = true; - } - - // Ignore undefined - if (this.s.options.ignoreUndefined) { - finalOptions.ignoreUndefined = true; - } - - // Is the bypassDocumentValidation options specific - if (this.s.bypassDocumentValidation === true) { - finalOptions.bypassDocumentValidation = true; - } - - // Is the checkKeys option disabled - if (this.s.checkKeys === false) { - finalOptions.checkKeys = false; - } - - if (finalOptions.retryWrites) { - if (config.batch.batchType === UPDATE) { - finalOptions.retryWrites = - finalOptions.retryWrites && !config.batch.operations.some(op => op.multi); - } - - if (config.batch.batchType === REMOVE) { - finalOptions.retryWrites = - finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0); - } - } - - try { - if (config.batch.batchType === INSERT) { - this.s.topology.insert( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } else if (config.batch.batchType === UPDATE) { - this.s.topology.update( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } else if (config.batch.batchType === REMOVE) { - this.s.topology.remove( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } - } catch (err) { - // Force top level error - err.ok = 0; - // Merge top level error and return - handleCallback(callback, null, mergeBatchResults(config.batch, this.s.bulkResult, err, null)); - } - } - - /** - * Handles the write error before executing commands - * - * An internal helper method. Do not invoke directly. Will be going away in the future - * - * @ignore - * @param {function} callback - * @param {BulkWriteResult} writeResult - * @param {class} self either OrderedBulkOperation or UnorderdBulkOperation - */ - handleWriteError(callback, writeResult) { - if (this.s.bulkResult.writeErrors.length > 0) { - if (this.s.bulkResult.writeErrors.length === 1) { - handleCallback( - callback, - new BulkWriteError(toError(this.s.bulkResult.writeErrors[0]), writeResult), - null - ); - return true; - } - - const msg = this.s.bulkResult.writeErrors[0].errmsg - ? this.s.bulkResult.writeErrors[0].errmsg - : 'write operation failed'; - - handleCallback( - callback, - new BulkWriteError( - toError({ - message: msg, - code: this.s.bulkResult.writeErrors[0].code, - writeErrors: this.s.bulkResult.writeErrors - }), - writeResult - ), - null - ); - return true; - } else if (writeResult.getWriteConcernError()) { - handleCallback( - callback, - new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult), - null - ); - return true; - } - } -} - -Object.defineProperty(BulkOperationBase.prototype, 'length', { - enumerable: true, - get: function() { - return this.s.currentIndex; - } -}); - -// Exports symbols -module.exports = { - Batch, - BulkOperationBase, - bson, - INSERT: INSERT, - UPDATE: UPDATE, - REMOVE: REMOVE, - BulkWriteError -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js b/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js deleted file mode 100644 index a976bed..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/bulk/ordered.js +++ /dev/null @@ -1,110 +0,0 @@ -'use strict'; - -const common = require('./common'); -const BulkOperationBase = common.BulkOperationBase; -const Batch = common.Batch; -const bson = common.bson; -const utils = require('../utils'); -const toError = utils.toError; - -/** - * Add to internal list of Operations - * - * @ignore - * @param {OrderedBulkOperation} bulkOperation - * @param {number} docType number indicating the document type - * @param {object} document - * @return {OrderedBulkOperation} - */ -function addToOperationsList(bulkOperation, docType, document) { - // Get the bsonSize - const bsonSize = bson.calculateObjectSize(document, { - checkKeys: false, - - // Since we don't know what the user selected for BSON options here, - // err on the safe side, and check the size with ignoreUndefined: false. - ignoreUndefined: false - }); - - // Throw error if the doc is bigger than the max BSON size - if (bsonSize >= bulkOperation.s.maxBsonObjectSize) - throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBsonObjectSize); - - // Create a new batch object if we don't have a current one - if (bulkOperation.s.currentBatch == null) - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - const maxKeySize = bulkOperation.s.maxKeySize; - - // Check if we need to create a new batch - if ( - // New batch if we exceed the max batch op size - bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize || - // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, - // since we can't sent an empty batch - (bulkOperation.s.currentBatchSize > 0 && - bulkOperation.s.currentBatchSizeBytes + maxKeySize + bsonSize >= - bulkOperation.s.maxBatchSizeBytes) || - // New batch if the new op does not have the same op type as the current batch - bulkOperation.s.currentBatch.batchType !== docType - ) { - // Save the batch to the execution stack - bulkOperation.s.batches.push(bulkOperation.s.currentBatch); - - // Create a new batch - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - // Reset the current size trackers - bulkOperation.s.currentBatchSize = 0; - bulkOperation.s.currentBatchSizeBytes = 0; - } - - if (docType === common.INSERT) { - bulkOperation.s.bulkResult.insertedIds.push({ - index: bulkOperation.s.currentIndex, - _id: document._id - }); - } - - // We have an array of documents - if (Array.isArray(document)) { - throw toError('operation passed in cannot be an Array'); - } - - bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); - bulkOperation.s.currentBatch.operations.push(document); - bulkOperation.s.currentBatchSize += 1; - bulkOperation.s.currentBatchSizeBytes += maxKeySize + bsonSize; - bulkOperation.s.currentIndex += 1; - - // Return bulkOperation - return bulkOperation; -} - -/** - * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @extends BulkOperationBase - * @property {number} length Get the number of operations in the bulk. - * @return {OrderedBulkOperation} a OrderedBulkOperation instance. - */ -class OrderedBulkOperation extends BulkOperationBase { - constructor(topology, collection, options) { - options = options || {}; - options = Object.assign(options, { addToOperationsList }); - - super(topology, collection, options, true); - } -} - -/** - * Returns an unordered batch object - * @ignore - */ -function initializeOrderedBulkOp(topology, collection, options) { - return new OrderedBulkOperation(topology, collection, options); -} - -initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; -module.exports = initializeOrderedBulkOp; -module.exports.Bulk = OrderedBulkOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js b/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js deleted file mode 100644 index 37a2783..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js +++ /dev/null @@ -1,123 +0,0 @@ -'use strict'; - -const common = require('./common'); -const BulkOperationBase = common.BulkOperationBase; -const Batch = common.Batch; -const bson = common.bson; -const utils = require('../utils'); -const toError = utils.toError; - -/** - * Add to internal list of Operations - * - * @ignore - * @param {UnorderedBulkOperation} bulkOperation - * @param {number} docType number indicating the document type - * @param {object} document - * @return {UnorderedBulkOperation} - */ -function addToOperationsList(bulkOperation, docType, document) { - // Get the bsonSize - const bsonSize = bson.calculateObjectSize(document, { - checkKeys: false, - - // Since we don't know what the user selected for BSON options here, - // err on the safe side, and check the size with ignoreUndefined: false. - ignoreUndefined: false - }); - // Throw error if the doc is bigger than the max BSON size - if (bsonSize >= bulkOperation.s.maxBsonObjectSize) - throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBsonObjectSize); - // Holds the current batch - bulkOperation.s.currentBatch = null; - // Get the right type of batch - if (docType === common.INSERT) { - bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch; - } else if (docType === common.UPDATE) { - bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch; - } else if (docType === common.REMOVE) { - bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch; - } - - const maxKeySize = bulkOperation.s.maxKeySize; - - // Create a new batch object if we don't have a current one - if (bulkOperation.s.currentBatch == null) - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - // Check if we need to create a new batch - if ( - // New batch if we exceed the max batch op size - bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize || - // New batch if we exceed the maxBatchSizeBytes. Only matters if batch already has a doc, - // since we can't sent an empty batch - (bulkOperation.s.currentBatch.size > 0 && - bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= - bulkOperation.s.maxBatchSizeBytes) || - // New batch if the new op does not have the same op type as the current batch - bulkOperation.s.currentBatch.batchType !== docType - ) { - // Save the batch to the execution stack - bulkOperation.s.batches.push(bulkOperation.s.currentBatch); - - // Create a new batch - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - } - - // We have an array of documents - if (Array.isArray(document)) { - throw toError('operation passed in cannot be an Array'); - } - - bulkOperation.s.currentBatch.operations.push(document); - bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); - bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1; - - // Save back the current Batch to the right type - if (docType === common.INSERT) { - bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch; - bulkOperation.s.bulkResult.insertedIds.push({ - index: bulkOperation.s.bulkResult.insertedIds.length, - _id: document._id - }); - } else if (docType === common.UPDATE) { - bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch; - } else if (docType === common.REMOVE) { - bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch; - } - - // Update current batch size - bulkOperation.s.currentBatch.size += 1; - bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize; - - // Return bulkOperation - return bulkOperation; -} - -/** - * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @extends BulkOperationBase - * @property {number} length Get the number of operations in the bulk. - * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. - */ -class UnorderedBulkOperation extends BulkOperationBase { - constructor(topology, collection, options) { - options = options || {}; - options = Object.assign(options, { addToOperationsList }); - - super(topology, collection, options, false); - } -} - -/** - * Returns an unordered batch object - * @ignore - */ -function initializeUnorderedBulkOp(topology, collection, options) { - return new UnorderedBulkOperation(topology, collection, options); -} - -initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; -module.exports = initializeUnorderedBulkOp; -module.exports.Bulk = UnorderedBulkOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/change_stream.js b/node_modules/mongoose/node_modules/mongodb/lib/change_stream.js deleted file mode 100644 index 6e15022..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/change_stream.js +++ /dev/null @@ -1,575 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'); -const isResumableError = require('./error').isResumableError; -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const relayEvents = require('./core/utils').relayEvents; -const maxWireVersion = require('./core/utils').maxWireVersion; -const maybePromise = require('./utils').maybePromise; -const AggregateOperation = require('./operations/aggregate'); - -const CHANGE_STREAM_OPTIONS = ['resumeAfter', 'startAfter', 'startAtOperationTime', 'fullDocument']; -const CURSOR_OPTIONS = ['batchSize', 'maxAwaitTimeMS', 'collation', 'readPreference'].concat( - CHANGE_STREAM_OPTIONS -); - -const CHANGE_DOMAIN_TYPES = { - COLLECTION: Symbol('Collection'), - DATABASE: Symbol('Database'), - CLUSTER: Symbol('Cluster') -}; - -/** - * @typedef ResumeToken - * @description Represents the logical starting point for a new or resuming {@link ChangeStream} on the server. - * @see https://docs.mongodb.com/master/changeStreams/#change-stream-resume-token - */ - -/** - * @typedef OperationTime - * @description Represents a specific point in time on a server. Can be retrieved by using {@link Db#command} - * @see https://docs.mongodb.com/manual/reference/method/db.runCommand/#response - */ - -/** - * @typedef ChangeStreamOptions - * @description Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. - * @property {string} [fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @property {number} [maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query. - * @property {ResumeToken} [resumeAfter] Allows you to start a changeStream after a specified event. See {@link https://docs.mongodb.com/master/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}. - * @property {ResumeToken} [startAfter] Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/master/changeStreams/#startafter-for-change-streams|ChangeStream documentation}. - * @property {OperationTime} [startAtOperationTime] Will start the changeStream after the specified operationTime. - * @property {number} [batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @property {object} [collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @property {ReadPreference} [readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - */ - -/** - * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. - * @class ChangeStream - * @since 3.0.0 - * @param {(MongoClient|Db|Collection)} parent The parent object that created this change stream - * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents - * @param {ChangeStreamOptions} [options] Optional settings - * @fires ChangeStream#close - * @fires ChangeStream#change - * @fires ChangeStream#end - * @fires ChangeStream#error - * @fires ChangeStream#resumeTokenChanged - * @return {ChangeStream} a ChangeStream instance. - */ -class ChangeStream extends EventEmitter { - constructor(parent, pipeline, options) { - super(); - const Collection = require('./collection'); - const Db = require('./db'); - const MongoClient = require('./mongo_client'); - - this.pipeline = pipeline || []; - this.options = options || {}; - - this.parent = parent; - this.namespace = parent.s.namespace; - if (parent instanceof Collection) { - this.type = CHANGE_DOMAIN_TYPES.COLLECTION; - this.topology = parent.s.db.serverConfig; - } else if (parent instanceof Db) { - this.type = CHANGE_DOMAIN_TYPES.DATABASE; - this.topology = parent.serverConfig; - } else if (parent instanceof MongoClient) { - this.type = CHANGE_DOMAIN_TYPES.CLUSTER; - this.topology = parent.topology; - } else { - throw new TypeError( - 'parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient' - ); - } - - this.promiseLibrary = parent.s.promiseLibrary; - if (!this.options.readPreference && parent.s.readPreference) { - this.options.readPreference = parent.s.readPreference; - } - - // Create contained Change Stream cursor - this.cursor = createChangeStreamCursor(this, options); - - // Listen for any `change` listeners being added to ChangeStream - this.on('newListener', eventName => { - if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { - this.cursor.on('data', change => - processNewChange({ changeStream: this, change, eventEmitter: true }) - ); - } - }); - - // Listen for all `change` listeners being removed from ChangeStream - this.on('removeListener', eventName => { - if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { - this.cursor.removeAllListeners('data'); - } - }); - } - - /** - * @property {ResumeToken} resumeToken - * The cached resume token that will be used to resume - * after the most recently returned change. - */ - get resumeToken() { - return this.cursor.resumeToken; - } - - /** - * Check if there is any document still available in the Change Stream - * @function ChangeStream.prototype.hasNext - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @returns {Promise|void} returns Promise if no callback passed - */ - hasNext(callback) { - return maybePromise(this.parent, callback, cb => this.cursor.hasNext(cb)); - } - - /** - * Get the next available document from the Change Stream, returns null if no more documents are available. - * @function ChangeStream.prototype.next - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @returns {Promise|void} returns Promise if no callback passed - */ - next(callback) { - return maybePromise(this.parent, callback, cb => { - if (this.isClosed()) { - return cb(new Error('Change Stream is not open.')); - } - this.cursor.next((error, change) => { - processNewChange({ changeStream: this, error, change, callback: cb }); - }); - }); - } - - /** - * Is the cursor closed - * @method ChangeStream.prototype.isClosed - * @return {boolean} - */ - isClosed() { - if (this.cursor) { - return this.cursor.isClosed(); - } - return true; - } - - /** - * Close the Change Stream - * @method ChangeStream.prototype.close - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - close(callback) { - if (!this.cursor) { - if (callback) return callback(); - return this.promiseLibrary.resolve(); - } - - // Tidy up the existing cursor - const cursor = this.cursor; - - if (callback) { - return cursor.close(err => { - ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); - delete this.cursor; - - return callback(err); - }); - } - - const PromiseCtor = this.promiseLibrary || Promise; - return new PromiseCtor((resolve, reject) => { - cursor.close(err => { - ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); - delete this.cursor; - - if (err) return reject(err); - resolve(); - }); - }); - } - - /** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @method - * @param {Writable} destination The destination for writing data - * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options} - * @return {null} - */ - pipe(destination, options) { - if (!this.pipeDestinations) { - this.pipeDestinations = []; - } - this.pipeDestinations.push(destination); - return this.cursor.pipe(destination, options); - } - - /** - * This method will remove the hooks set up for a previous pipe() call. - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - unpipe(destination) { - if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) { - this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1); - } - return this.cursor.unpipe(destination); - } - - /** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - */ - stream(options) { - this.streamOptions = options; - return this.cursor.stream(options); - } - - /** - * This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @return {null} - */ - pause() { - return this.cursor.pause(); - } - - /** - * This method will cause the readable stream to resume emitting data events. - * @return {null} - */ - resume() { - return this.cursor.resume(); - } -} - -class ChangeStreamCursor extends Cursor { - constructor(topology, operation, options) { - super(topology, operation, options); - - options = options || {}; - this._resumeToken = null; - this.startAtOperationTime = options.startAtOperationTime; - - if (options.startAfter) { - this.resumeToken = options.startAfter; - } else if (options.resumeAfter) { - this.resumeToken = options.resumeAfter; - } - } - - set resumeToken(token) { - this._resumeToken = token; - this.emit('resumeTokenChanged', token); - } - - get resumeToken() { - return this._resumeToken; - } - - get resumeOptions() { - const result = {}; - for (const optionName of CURSOR_OPTIONS) { - if (this.options[optionName]) result[optionName] = this.options[optionName]; - } - - if (this.resumeToken || this.startAtOperationTime) { - ['resumeAfter', 'startAfter', 'startAtOperationTime'].forEach(key => delete result[key]); - - if (this.resumeToken) { - result.resumeAfter = this.resumeToken; - } else if (this.startAtOperationTime && maxWireVersion(this.server) >= 7) { - result.startAtOperationTime = this.startAtOperationTime; - } - } - - return result; - } - - _initializeCursor(callback) { - super._initializeCursor((err, result) => { - if (err) { - callback(err, null); - return; - } - - const response = result.documents[0]; - - if ( - this.startAtOperationTime == null && - this.resumeAfter == null && - this.startAfter == null && - maxWireVersion(this.server) >= 7 - ) { - this.startAtOperationTime = response.operationTime; - } - - const cursor = response.cursor; - if (cursor.postBatchResumeToken) { - this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; - - if (cursor.firstBatch.length === 0) { - this.resumeToken = cursor.postBatchResumeToken; - } - } - - this.emit('response'); - callback(err, result); - }); - } - - _getMore(callback) { - super._getMore((err, response) => { - if (err) { - callback(err, null); - return; - } - - const cursor = response.cursor; - if (cursor.postBatchResumeToken) { - this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; - - if (cursor.nextBatch.length === 0) { - this.resumeToken = cursor.postBatchResumeToken; - } - } - - this.emit('response'); - callback(err, response); - }); - } -} - -/** - * @event ChangeStreamCursor#response - * internal event DO NOT USE - * @ignore - */ - -// Create a new change stream cursor based on self's configuration -function createChangeStreamCursor(self, options) { - const changeStreamStageOptions = { fullDocument: options.fullDocument || 'default' }; - applyKnownOptions(changeStreamStageOptions, options, CHANGE_STREAM_OPTIONS); - if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) { - changeStreamStageOptions.allChangesForCluster = true; - } - - const pipeline = [{ $changeStream: changeStreamStageOptions }].concat(self.pipeline); - const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS); - const changeStreamCursor = new ChangeStreamCursor( - self.topology, - new AggregateOperation(self.parent, pipeline, options), - cursorOptions - ); - - relayEvents(changeStreamCursor, self, ['resumeTokenChanged', 'end', 'close']); - - /** - * Fired for each new matching change in the specified namespace. Attaching a `change` - * event listener to a Change Stream will switch the stream into flowing mode. Data will - * then be passed as soon as it is available. - * - * @event ChangeStream#change - * @type {object} - */ - if (self.listenerCount('change') > 0) { - changeStreamCursor.on('data', function(change) { - processNewChange({ changeStream: self, change, eventEmitter: true }); - }); - } - - /** - * Change stream close event - * - * @event ChangeStream#close - * @type {null} - */ - - /** - * Change stream end event - * - * @event ChangeStream#end - * @type {null} - */ - - /** - * Emitted each time the change stream stores a new resume token. - * - * @event ChangeStream#resumeTokenChanged - * @type {ResumeToken} - */ - - /** - * Fired when the stream encounters an error. - * - * @event ChangeStream#error - * @type {Error} - */ - changeStreamCursor.on('error', function(error) { - processNewChange({ changeStream: self, error, eventEmitter: true }); - }); - - if (self.pipeDestinations) { - const cursorStream = changeStreamCursor.stream(self.streamOptions); - for (let pipeDestination in self.pipeDestinations) { - cursorStream.pipe(pipeDestination); - } - } - - return changeStreamCursor; -} - -function applyKnownOptions(target, source, optionNames) { - optionNames.forEach(name => { - if (source[name]) { - target[name] = source[name]; - } - }); - - return target; -} - -// This method performs a basic server selection loop, satisfying the requirements of -// ChangeStream resumability until the new SDAM layer can be used. -const SELECTION_TIMEOUT = 30000; -function waitForTopologyConnected(topology, options, callback) { - setTimeout(() => { - if (options && options.start == null) options.start = process.hrtime(); - const start = options.start || process.hrtime(); - const timeout = options.timeout || SELECTION_TIMEOUT; - const readPreference = options.readPreference; - - if (topology.isConnected({ readPreference })) return callback(null, null); - const hrElapsed = process.hrtime(start); - const elapsed = (hrElapsed[0] * 1e9 + hrElapsed[1]) / 1e6; - if (elapsed > timeout) return callback(new MongoError('Timed out waiting for connection')); - waitForTopologyConnected(topology, options, callback); - }, 3000); // this is an arbitrary wait time to allow SDAM to transition -} - -// Handle new change events. This method brings together the routes from the callback, event emitter, and promise ways of using ChangeStream. -function processNewChange(args) { - const changeStream = args.changeStream; - const error = args.error; - const change = args.change; - const callback = args.callback; - const eventEmitter = args.eventEmitter || false; - - // If the changeStream is closed, then it should not process a change. - if (changeStream.isClosed()) { - // We do not error in the eventEmitter case. - if (eventEmitter) { - return; - } - - const error = new MongoError('ChangeStream is closed'); - return typeof callback === 'function' - ? callback(error, null) - : changeStream.promiseLibrary.reject(error); - } - - const cursor = changeStream.cursor; - const topology = changeStream.topology; - const options = changeStream.cursor.options; - - if (error) { - if (isResumableError(error) && !changeStream.attemptingResume) { - changeStream.attemptingResume = true; - - // stop listening to all events from old cursor - ['data', 'close', 'end', 'error'].forEach(event => - changeStream.cursor.removeAllListeners(event) - ); - - // close internal cursor, ignore errors - changeStream.cursor.close(); - - // attempt recreating the cursor - if (eventEmitter) { - waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { - if (err) { - changeStream.emit('error', err); - changeStream.emit('close'); - return; - } - changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); - }); - - return; - } - - if (callback) { - waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { - if (err) return callback(err, null); - - changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); - changeStream.next(callback); - }); - - return; - } - - return new Promise((resolve, reject) => { - waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { - if (err) return reject(err); - resolve(); - }); - }) - .then( - () => (changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions)) - ) - .then(() => changeStream.next()); - } - - if (eventEmitter) return changeStream.emit('error', error); - if (typeof callback === 'function') return callback(error, null); - return changeStream.promiseLibrary.reject(error); - } - - changeStream.attemptingResume = false; - - if (change && !change._id) { - const noResumeTokenError = new Error( - 'A change stream document has been received that lacks a resume token (_id).' - ); - - if (eventEmitter) return changeStream.emit('error', noResumeTokenError); - if (typeof callback === 'function') return callback(noResumeTokenError, null); - return changeStream.promiseLibrary.reject(noResumeTokenError); - } - - // cache the resume token - if (cursor.bufferedCount() === 0 && cursor.cursorState.postBatchResumeToken) { - cursor.resumeToken = cursor.cursorState.postBatchResumeToken; - } else { - cursor.resumeToken = change._id; - } - - // wipe the startAtOperationTime if there was one so that there won't be a conflict - // between resumeToken and startAtOperationTime if we need to reconnect the cursor - changeStream.options.startAtOperationTime = undefined; - - // Return the change - if (eventEmitter) return changeStream.emit('change', change); - if (typeof callback === 'function') return callback(error, change); - return changeStream.promiseLibrary.resolve(change); -} - -/** - * The callback format for results - * @callback ChangeStream~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -module.exports = ChangeStream; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/cmap/connection.js b/node_modules/mongoose/node_modules/mongodb/lib/cmap/connection.js deleted file mode 100644 index bec3aca..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/cmap/connection.js +++ /dev/null @@ -1,377 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'); -const MessageStream = require('./message_stream'); -const MongoError = require('../core/error').MongoError; -const MongoNetworkError = require('../core/error').MongoNetworkError; -const MongoWriteConcernError = require('../core/error').MongoWriteConcernError; -const CommandResult = require('../core/connection/command_result'); -const StreamDescription = require('./stream_description').StreamDescription; -const wp = require('../core/wireprotocol'); -const apm = require('../core/connection/apm'); -const updateSessionFromResponse = require('../core/sessions').updateSessionFromResponse; -const uuidV4 = require('../core/utils').uuidV4; - -const kStream = Symbol('stream'); -const kQueue = Symbol('queue'); -const kMessageStream = Symbol('messageStream'); -const kGeneration = Symbol('generation'); -const kLastUseTime = Symbol('lastUseTime'); -const kClusterTime = Symbol('clusterTime'); -const kDescription = Symbol('description'); -const kIsMaster = Symbol('ismaster'); -const kAutoEncrypter = Symbol('autoEncrypter'); - -class Connection extends EventEmitter { - constructor(stream, options) { - super(options); - - this.id = options.id; - this.address = streamIdentifier(stream); - this.bson = options.bson; - this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - this.monitorCommands = - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false; - this.closed = false; - this.destroyed = false; - - this[kDescription] = new StreamDescription(this.address, options); - this[kGeneration] = options.generation; - this[kLastUseTime] = Date.now(); - - // retain a reference to an `AutoEncrypter` if present - if (options.autoEncrypter) { - this[kAutoEncrypter] = options.autoEncrypter; - } - - // setup parser stream and message handling - this[kQueue] = new Map(); - this[kMessageStream] = new MessageStream(options); - this[kMessageStream].on('message', messageHandler(this)); - this[kStream] = stream; - stream.on('error', () => { - /* ignore errors, listen to `close` instead */ - }); - - stream.on('close', () => { - if (this.closed) { - return; - } - - this.closed = true; - this[kQueue].forEach(op => - op.cb(new MongoNetworkError(`connection ${this.id} to ${this.address} closed`)) - ); - this[kQueue].clear(); - - this.emit('close'); - }); - - stream.on('timeout', () => { - if (this.closed) { - return; - } - - stream.destroy(); - this.closed = true; - this[kQueue].forEach(op => - op.cb(new MongoNetworkError(`connection ${this.id} to ${this.address} timed out`)) - ); - this[kQueue].clear(); - - this.emit('close'); - }); - - // hook the message stream up to the passed in stream - stream.pipe(this[kMessageStream]); - this[kMessageStream].pipe(stream); - } - - get description() { - return this[kDescription]; - } - - get ismaster() { - return this[kIsMaster]; - } - - // the `connect` method stores the result of the handshake ismaster on the connection - set ismaster(response) { - this[kDescription].receiveResponse(response); - - // TODO: remove this, and only use the `StreamDescription` in the future - this[kIsMaster] = response; - } - - get generation() { - return this[kGeneration] || 0; - } - - get idleTime() { - return Date.now() - this[kLastUseTime]; - } - - get clusterTime() { - return this[kClusterTime]; - } - - get stream() { - return this[kStream]; - } - - markAvailable() { - this[kLastUseTime] = Date.now(); - } - - destroy(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = Object.assign({ force: false }, options); - if (this[kStream] == null || this.destroyed) { - this.destroyed = true; - if (typeof callback === 'function') { - callback(); - } - - return; - } - - if (options.force) { - this[kStream].destroy(); - this.destroyed = true; - if (typeof callback === 'function') { - callback(); - } - - return; - } - - this[kStream].end(err => { - this.destroyed = true; - if (typeof callback === 'function') { - callback(err); - } - }); - } - - // Wire protocol methods - command(ns, cmd, options, callback) { - wp.command(makeServerTrampoline(this), ns, cmd, options, callback); - } - - query(ns, cmd, cursorState, options, callback) { - wp.query(makeServerTrampoline(this), ns, cmd, cursorState, options, callback); - } - - getMore(ns, cursorState, batchSize, options, callback) { - wp.getMore(makeServerTrampoline(this), ns, cursorState, batchSize, options, callback); - } - - killCursors(ns, cursorState, callback) { - wp.killCursors(makeServerTrampoline(this), ns, cursorState, callback); - } - - insert(ns, ops, options, callback) { - wp.insert(makeServerTrampoline(this), ns, ops, options, callback); - } - - update(ns, ops, options, callback) { - wp.update(makeServerTrampoline(this), ns, ops, options, callback); - } - - remove(ns, ops, options, callback) { - wp.remove(makeServerTrampoline(this), ns, ops, options, callback); - } -} - -/// This lets us emulate a legacy `Server` instance so we can work with the existing wire -/// protocol methods. Eventually, the operation executor will return a `Connection` to execute -/// against. -function makeServerTrampoline(connection) { - const server = { - description: connection.description, - clusterTime: connection[kClusterTime], - s: { - bson: connection.bson, - pool: { write: write.bind(connection), isConnected: () => true } - } - }; - - if (connection[kAutoEncrypter]) { - server.autoEncrypter = connection[kAutoEncrypter]; - } - - return server; -} - -function messageHandler(conn) { - return function messageHandler(message) { - // always emit the message, in case we are streaming - conn.emit('message', message); - if (!conn[kQueue].has(message.responseTo)) { - return; - } - - const operationDescription = conn[kQueue].get(message.responseTo); - - // SERVER-45775: For exhaust responses we should be able to use the same requestId to - // track response, however the server currently synthetically produces remote requests - // making the `responseTo` change on each response - conn[kQueue].delete(message.responseTo); - if (message.moreToCome) { - // requeue the callback for next synthetic request - conn[kQueue].set(message.requestId, operationDescription); - } - - const callback = operationDescription.cb; - if (operationDescription.socketTimeoutOverride) { - conn[kStream].setTimeout(conn.socketTimeout); - } - - try { - // Pass in the entire description because it has BSON parsing options - message.parse(operationDescription); - } catch (err) { - callback(new MongoError(err)); - return; - } - - if (message.documents[0]) { - const document = message.documents[0]; - const session = operationDescription.session; - if (session) { - updateSessionFromResponse(session, document); - } - - if (document.$clusterTime) { - conn[kClusterTime] = document.$clusterTime; - conn.emit('clusterTimeReceived', document.$clusterTime); - } - - if (operationDescription.command) { - if (document.writeConcernError) { - callback(new MongoWriteConcernError(document.writeConcernError, document)); - return; - } - - if (document.ok === 0 || document.$err || document.errmsg || document.code) { - callback(new MongoError(document)); - return; - } - } - } - - // NODE-2382: reenable in our glorious non-leaky abstraction future - // callback(null, operationDescription.fullResult ? message : message.documents[0]); - - callback( - undefined, - new CommandResult( - operationDescription.fullResult ? message : message.documents[0], - conn, - message - ) - ); - }; -} - -function streamIdentifier(stream) { - if (typeof stream.address === 'function') { - return `${stream.remoteAddress}:${stream.remotePort}`; - } - - return uuidV4().toString('hex'); -} - -// Not meant to be called directly, the wire protocol methods call this assuming it is a `Pool` instance -function write(command, options, callback) { - if (typeof options === 'function') { - callback = options; - } - - options = options || {}; - const operationDescription = { - requestId: command.requestId, - cb: callback, - session: options.session, - fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false, - noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false, - documentsReturnedIn: options.documentsReturnedIn, - command: !!options.command, - - // for BSON parsing - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, - raw: typeof options.raw === 'boolean' ? options.raw : false - }; - - if (this[kDescription] && this[kDescription].compressor) { - operationDescription.agreedCompressor = this[kDescription].compressor; - - if (this[kDescription].zlibCompressionLevel) { - operationDescription.zlibCompressionLevel = this[kDescription].zlibCompressionLevel; - } - } - - if (typeof options.socketTimeout === 'number') { - operationDescription.socketTimeoutOverride = true; - this[kStream].setTimeout(options.socketTimeout); - } - - // if command monitoring is enabled we need to modify the callback here - if (this.monitorCommands) { - this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); - - operationDescription.started = process.hrtime(); - operationDescription.cb = (err, reply) => { - if (err) { - this.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, err, operationDescription.started) - ); - } else { - if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { - this.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, reply.result, operationDescription.started) - ); - } else { - this.emit( - 'commandSucceeded', - new apm.CommandSucceededEvent(this, command, reply, operationDescription.started) - ); - } - } - - if (typeof callback === 'function') { - callback(err, reply); - } - }; - } - - if (!operationDescription.noResponse) { - this[kQueue].set(operationDescription.requestId, operationDescription); - } - - try { - this[kMessageStream].writeCommand(command, operationDescription); - } catch (e) { - if (!operationDescription.noResponse) { - this[kQueue].delete(operationDescription.requestId); - operationDescription.cb(e); - return; - } - } - - if (operationDescription.noResponse) { - operationDescription.cb(); - } -} - -module.exports = { - Connection -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/cmap/connection_pool.js b/node_modules/mongoose/node_modules/mongodb/lib/cmap/connection_pool.js deleted file mode 100644 index 51ab907..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/cmap/connection_pool.js +++ /dev/null @@ -1,593 +0,0 @@ -'use strict'; - -const Denque = require('denque'); -const EventEmitter = require('events').EventEmitter; -const Logger = require('../core/connection/logger'); -const makeCounter = require('../utils').makeCounter; -const MongoError = require('../core/error').MongoError; -const Connection = require('./connection').Connection; -const eachAsync = require('../core/utils').eachAsync; -const connect = require('../core/connection/connect'); -const relayEvents = require('../core/utils').relayEvents; - -const errors = require('./errors'); -const PoolClosedError = errors.PoolClosedError; -const WaitQueueTimeoutError = errors.WaitQueueTimeoutError; - -const events = require('./events'); -const ConnectionPoolCreatedEvent = events.ConnectionPoolCreatedEvent; -const ConnectionPoolClosedEvent = events.ConnectionPoolClosedEvent; -const ConnectionCreatedEvent = events.ConnectionCreatedEvent; -const ConnectionReadyEvent = events.ConnectionReadyEvent; -const ConnectionClosedEvent = events.ConnectionClosedEvent; -const ConnectionCheckOutStartedEvent = events.ConnectionCheckOutStartedEvent; -const ConnectionCheckOutFailedEvent = events.ConnectionCheckOutFailedEvent; -const ConnectionCheckedOutEvent = events.ConnectionCheckedOutEvent; -const ConnectionCheckedInEvent = events.ConnectionCheckedInEvent; -const ConnectionPoolClearedEvent = events.ConnectionPoolClearedEvent; - -const kLogger = Symbol('logger'); -const kConnections = Symbol('connections'); -const kPermits = Symbol('permits'); -const kMinPoolSizeTimer = Symbol('minPoolSizeTimer'); -const kGeneration = Symbol('generation'); -const kConnectionCounter = Symbol('connectionCounter'); -const kCancellationToken = Symbol('cancellationToken'); -const kWaitQueue = Symbol('waitQueue'); -const kCancelled = Symbol('cancelled'); - -const VALID_POOL_OPTIONS = new Set([ - // `connect` options - 'ssl', - 'bson', - 'connectionType', - 'monitorCommands', - 'socketTimeout', - 'credentials', - 'compression', - - // node Net options - 'host', - 'port', - 'localAddress', - 'localPort', - 'family', - 'hints', - 'lookup', - 'path', - - // node TLS options - 'ca', - 'cert', - 'sigalgs', - 'ciphers', - 'clientCertEngine', - 'crl', - 'dhparam', - 'ecdhCurve', - 'honorCipherOrder', - 'key', - 'privateKeyEngine', - 'privateKeyIdentifier', - 'maxVersion', - 'minVersion', - 'passphrase', - 'pfx', - 'secureOptions', - 'secureProtocol', - 'sessionIdContext', - 'allowHalfOpen', - 'rejectUnauthorized', - 'pskCallback', - 'ALPNProtocols', - 'servername', - 'checkServerIdentity', - 'session', - 'minDHSize', - 'secureContext', - - // spec options - 'maxPoolSize', - 'minPoolSize', - 'maxIdleTimeMS', - 'waitQueueTimeoutMS' -]); - -function resolveOptions(options, defaults) { - const newOptions = Array.from(VALID_POOL_OPTIONS).reduce((obj, key) => { - if (options.hasOwnProperty(key)) { - obj[key] = options[key]; - } - - return obj; - }, {}); - - return Object.freeze(Object.assign({}, defaults, newOptions)); -} - -/** - * Configuration options for drivers wrapping the node driver. - * - * @typedef {Object} ConnectionPoolOptions - * @property - * @property {string} [host] The host to connect to - * @property {number} [port] The port to connect to - * @property {bson} [bson] The BSON instance to use for new connections - * @property {number} [maxPoolSize=100] The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. - * @property {number} [minPoolSize=0] The minimum number of connections that MUST exist at any moment in a single connection pool. - * @property {number} [maxIdleTimeMS] The maximum amount of time a connection should remain idle in the connection pool before being marked idle. - * @property {number} [waitQueueTimeoutMS=0] The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. - */ - -/** - * A pool of connections which dynamically resizes, and emit events related to pool activity - * - * @property {number} generation An integer representing the SDAM generation of the pool - * @property {number} totalConnectionCount An integer expressing how many total connections (active + in use) the pool currently has - * @property {number} availableConnectionCount An integer expressing how many connections are currently available in the pool. - * @property {string} address The address of the endpoint the pool is connected to - * - * @emits ConnectionPool#connectionPoolCreated - * @emits ConnectionPool#connectionPoolClosed - * @emits ConnectionPool#connectionCreated - * @emits ConnectionPool#connectionReady - * @emits ConnectionPool#connectionClosed - * @emits ConnectionPool#connectionCheckOutStarted - * @emits ConnectionPool#connectionCheckOutFailed - * @emits ConnectionPool#connectionCheckedOut - * @emits ConnectionPool#connectionCheckedIn - * @emits ConnectionPool#connectionPoolCleared - */ -class ConnectionPool extends EventEmitter { - /** - * Create a new Connection Pool - * - * @param {ConnectionPoolOptions} options - */ - constructor(options) { - super(); - options = options || {}; - - this.closed = false; - this.options = resolveOptions(options, { - connectionType: Connection, - maxPoolSize: typeof options.maxPoolSize === 'number' ? options.maxPoolSize : 100, - minPoolSize: typeof options.minPoolSize === 'number' ? options.minPoolSize : 0, - maxIdleTimeMS: typeof options.maxIdleTimeMS === 'number' ? options.maxIdleTimeMS : 0, - waitQueueTimeoutMS: - typeof options.waitQueueTimeoutMS === 'number' ? options.waitQueueTimeoutMS : 0, - autoEncrypter: options.autoEncrypter, - metadata: options.metadata - }); - - if (options.minSize > options.maxSize) { - throw new TypeError( - 'Connection pool minimum size must not be greater than maxiumum pool size' - ); - } - - this[kLogger] = Logger('ConnectionPool', options); - this[kConnections] = new Denque(); - this[kPermits] = this.options.maxPoolSize; - this[kMinPoolSizeTimer] = undefined; - this[kGeneration] = 0; - this[kConnectionCounter] = makeCounter(1); - this[kCancellationToken] = new EventEmitter(); - this[kCancellationToken].setMaxListeners(Infinity); - this[kWaitQueue] = new Denque(); - - process.nextTick(() => { - this.emit('connectionPoolCreated', new ConnectionPoolCreatedEvent(this)); - ensureMinPoolSize(this); - }); - } - - get address() { - return `${this.options.host}:${this.options.port}`; - } - - get generation() { - return this[kGeneration]; - } - - get totalConnectionCount() { - return this[kConnections].length + (this.options.maxPoolSize - this[kPermits]); - } - - get availableConnectionCount() { - return this[kConnections].length; - } - - /** - * Check a connection out of this pool. The connection will continue to be tracked, but no reference to it - * will be held by the pool. This means that if a connection is checked out it MUST be checked back in or - * explicitly destroyed by the new owner. - * - * @param {ConnectionPool~checkOutCallback} callback - */ - checkOut(callback) { - this.emit('connectionCheckOutStarted', new ConnectionCheckOutStartedEvent(this)); - - if (this.closed) { - this.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(this, 'poolClosed')); - callback(new PoolClosedError(this)); - return; - } - - // add this request to the wait queue - const waitQueueMember = { callback }; - - const pool = this; - const waitQueueTimeoutMS = this.options.waitQueueTimeoutMS; - if (waitQueueTimeoutMS) { - waitQueueMember.timer = setTimeout(() => { - waitQueueMember[kCancelled] = true; - waitQueueMember.timer = undefined; - - pool.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(pool, 'timeout')); - waitQueueMember.callback(new WaitQueueTimeoutError(pool)); - }, waitQueueTimeoutMS); - } - - // place the member at the end of the wait queue - this[kWaitQueue].push(waitQueueMember); - - // process the wait queue - processWaitQueue(this); - } - - /** - * Check a connection into the pool. - * - * @param {Connection} connection The connection to check in - */ - checkIn(connection) { - const poolClosed = this.closed; - const stale = connectionIsStale(this, connection); - const willDestroy = !!(poolClosed || stale || connection.closed); - - // Properly adjust state of connection - if (!willDestroy) { - connection.markAvailable(); - - this[kConnections].push(connection); - } - - this.emit('connectionCheckedIn', new ConnectionCheckedInEvent(this, connection)); - - if (willDestroy) { - const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; - destroyConnection(this, connection, reason); - } - - processWaitQueue(this); - } - - /** - * Clear the pool - * - * Pool reset is handled by incrementing the pool's generation count. Any existing connection of a - * previous generation will eventually be pruned during subsequent checkouts. - */ - clear() { - this[kGeneration] += 1; - this.emit('connectionPoolCleared', new ConnectionPoolClearedEvent(this)); - } - - /** - * Close the pool - * - * @param {object} [options] Optional settings - * @param {boolean} [options.force] Force close connections - * @param {Function} callback - */ - close(options, callback) { - if (typeof options === 'function') { - callback = options; - } - - options = Object.assign({ force: false }, options); - if (this.closed) { - return callback(); - } - - // immediately cancel any in-flight connections - this[kCancellationToken].emit('cancel'); - - // drain the wait queue - while (this[kWaitQueue].length) { - const waitQueueMember = this[kWaitQueue].pop(); - clearTimeout(waitQueueMember.timer); - if (!waitQueueMember[kCancelled]) { - waitQueueMember.callback(new MongoError('connection pool closed')); - } - } - - // clear the min pool size timer - if (this[kMinPoolSizeTimer]) { - clearTimeout(this[kMinPoolSizeTimer]); - } - - // end the connection counter - if (typeof this[kConnectionCounter].return === 'function') { - this[kConnectionCounter].return(); - } - - // mark the pool as closed immediately - this.closed = true; - - eachAsync( - this[kConnections].toArray(), - (conn, cb) => { - this.emit('connectionClosed', new ConnectionClosedEvent(this, conn, 'poolClosed')); - conn.destroy(options, cb); - }, - err => { - this[kConnections].clear(); - this.emit('connectionPoolClosed', new ConnectionPoolClosedEvent(this)); - callback(err); - } - ); - } - - /** - * Runs a lambda with an implicitly checked out connection, checking that connection back in when the lambda - * has completed by calling back. - * - * NOTE: please note the required signature of `fn` - * - * @param {ConnectionPool~withConnectionCallback} fn A function which operates on a managed connection - * @param {Function} callback The original callback - * @return {Promise} - */ - withConnection(fn, callback) { - this.checkOut((err, conn) => { - // don't callback with `err` here, we might want to act upon it inside `fn` - - fn(err, conn, (fnErr, result) => { - if (typeof callback === 'function') { - if (fnErr) { - callback(fnErr); - } else { - callback(undefined, result); - } - } - - if (conn) { - this.checkIn(conn); - } - }); - }); - } -} - -function ensureMinPoolSize(pool) { - if (pool.closed || pool.options.minPoolSize === 0) { - return; - } - - const minPoolSize = pool.options.minPoolSize; - for (let i = pool.totalConnectionCount; i < minPoolSize; ++i) { - createConnection(pool); - } - - pool[kMinPoolSizeTimer] = setTimeout(() => ensureMinPoolSize(pool), 10); -} - -function connectionIsStale(pool, connection) { - return connection.generation !== pool[kGeneration]; -} - -function connectionIsIdle(pool, connection) { - return !!(pool.options.maxIdleTimeMS && connection.idleTime > pool.options.maxIdleTimeMS); -} - -function createConnection(pool, callback) { - const connectOptions = Object.assign( - { - id: pool[kConnectionCounter].next().value, - generation: pool[kGeneration] - }, - pool.options - ); - - pool[kPermits]--; - connect(connectOptions, pool[kCancellationToken], (err, connection) => { - if (err) { - pool[kPermits]++; - pool[kLogger].debug(`connection attempt failed with error [${JSON.stringify(err)}]`); - if (typeof callback === 'function') { - callback(err); - } - - return; - } - - // The pool might have closed since we started trying to create a connection - if (pool.closed) { - connection.destroy({ force: true }); - return; - } - - // forward all events from the connection to the pool - relayEvents(connection, pool, [ - 'commandStarted', - 'commandFailed', - 'commandSucceeded', - 'clusterTimeReceived' - ]); - - pool.emit('connectionCreated', new ConnectionCreatedEvent(pool, connection)); - - connection.markAvailable(); - pool.emit('connectionReady', new ConnectionReadyEvent(pool, connection)); - - // if a callback has been provided, check out the connection immediately - if (typeof callback === 'function') { - callback(undefined, connection); - return; - } - - // otherwise add it to the pool for later acquisition, and try to process the wait queue - pool[kConnections].push(connection); - processWaitQueue(pool); - }); -} - -function destroyConnection(pool, connection, reason) { - pool.emit('connectionClosed', new ConnectionClosedEvent(pool, connection, reason)); - - // allow more connections to be created - pool[kPermits]++; - - // destroy the connection - process.nextTick(() => connection.destroy()); -} - -function processWaitQueue(pool) { - if (pool.closed) { - return; - } - - while (pool[kWaitQueue].length && pool.availableConnectionCount) { - const waitQueueMember = pool[kWaitQueue].peekFront(); - if (waitQueueMember[kCancelled]) { - pool[kWaitQueue].shift(); - continue; - } - - const connection = pool[kConnections].shift(); - const isStale = connectionIsStale(pool, connection); - const isIdle = connectionIsIdle(pool, connection); - if (!isStale && !isIdle && !connection.closed) { - pool.emit('connectionCheckedOut', new ConnectionCheckedOutEvent(pool, connection)); - clearTimeout(waitQueueMember.timer); - pool[kWaitQueue].shift(); - waitQueueMember.callback(undefined, connection); - return; - } - - const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; - destroyConnection(pool, connection, reason); - } - - const maxPoolSize = pool.options.maxPoolSize; - if (pool[kWaitQueue].length && (maxPoolSize <= 0 || pool.totalConnectionCount < maxPoolSize)) { - createConnection(pool, (err, connection) => { - const waitQueueMember = pool[kWaitQueue].shift(); - if (waitQueueMember == null) { - if (err == null) { - pool[kConnections].push(connection); - } - - return; - } - - if (waitQueueMember[kCancelled]) { - return; - } - - if (err) { - pool.emit('connectionCheckOutFailed', new ConnectionCheckOutFailedEvent(pool, err)); - } else { - pool.emit('connectionCheckedOut', new ConnectionCheckedOutEvent(pool, connection)); - } - - clearTimeout(waitQueueMember.timer); - waitQueueMember.callback(err, connection); - }); - - return; - } -} - -/** - * A callback provided to `withConnection` - * - * @callback ConnectionPool~withConnectionCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Connection} connection The managed connection which was checked out of the pool. - * @param {Function} callback A function to call back after connection management is complete - */ - -/** - * A callback provided to `checkOut` - * - * @callback ConnectionPool~checkOutCallback - * @param {MongoError} error An error instance representing the error during checkout - * @param {Connection} connection A connection from the pool - */ - -/** - * Emitted once when the connection pool is created - * - * @event ConnectionPool#connectionPoolCreated - * @type {PoolCreatedEvent} - */ - -/** - * Emitted once when the connection pool is closed - * - * @event ConnectionPool#connectionPoolClosed - * @type {PoolClosedEvent} - */ - -/** - * Emitted each time a connection is created - * - * @event ConnectionPool#connectionCreated - * @type {ConnectionCreatedEvent} - */ - -/** - * Emitted when a connection becomes established, and is ready to use - * - * @event ConnectionPool#connectionReady - * @type {ConnectionReadyEvent} - */ - -/** - * Emitted when a connection is closed - * - * @event ConnectionPool#connectionClosed - * @type {ConnectionClosedEvent} - */ - -/** - * Emitted when an attempt to check out a connection begins - * - * @event ConnectionPool#connectionCheckOutStarted - * @type {ConnectionCheckOutStartedEvent} - */ - -/** - * Emitted when an attempt to check out a connection fails - * - * @event ConnectionPool#connectionCheckOutFailed - * @type {ConnectionCheckOutFailedEvent} - */ - -/** - * Emitted each time a connection is successfully checked out of the connection pool - * - * @event ConnectionPool#connectionCheckedOut - * @type {ConnectionCheckedOutEvent} - */ - -/** - * Emitted each time a connection is successfully checked into the connection pool - * - * @event ConnectionPool#connectionCheckedIn - * @type {ConnectionCheckedInEvent} - */ - -/** - * Emitted each time the connection pool is cleared and it's generation incremented - * - * @event ConnectionPool#connectionPoolCleared - * @type {PoolClearedEvent} - */ - -module.exports = { - ConnectionPool -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/cmap/errors.js b/node_modules/mongoose/node_modules/mongodb/lib/cmap/errors.js deleted file mode 100644 index d933019..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/cmap/errors.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; -const MongoError = require('../core/error').MongoError; - -/** - * An error indicating a connection pool is closed - * - * @property {string} address The address of the connection pool - * @extends MongoError - */ -class PoolClosedError extends MongoError { - constructor(pool) { - super('Attempted to check out a connection from closed connection pool'); - this.name = 'MongoPoolClosedError'; - this.address = pool.address; - } -} - -/** - * An error thrown when a request to check out a connection times out - * - * @property {string} address The address of the connection pool - * @extends MongoError - */ -class WaitQueueTimeoutError extends MongoError { - constructor(pool) { - super('Timed out while checking out a connection from connection pool'); - this.name = 'MongoWaitQueueTimeoutError'; - this.address = pool.address; - } -} - -module.exports = { - PoolClosedError, - WaitQueueTimeoutError -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/cmap/events.js b/node_modules/mongoose/node_modules/mongodb/lib/cmap/events.js deleted file mode 100644 index dcc8b67..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/cmap/events.js +++ /dev/null @@ -1,154 +0,0 @@ -'use strict'; - -/** - * The base class for all monitoring events published from the connection pool - * - * @property {number} time A timestamp when the event was created - * @property {string} address The address (host/port pair) of the pool - */ -class ConnectionPoolMonitoringEvent { - constructor(pool) { - this.time = new Date(); - this.address = pool.address; - } -} - -/** - * An event published when a connection pool is created - * - * @property {Object} options The options used to create this connection pool - */ -class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); - this.options = pool.options; - } -} - -/** - * An event published when a connection pool is closed - */ -class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); - } -} - -/** - * An event published when a connection pool creates a new connection - * - * @property {number} connectionId A monotonically increasing, per-pool id for the newly created connection - */ -class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection) { - super(pool); - this.connectionId = connection.id; - } -} - -/** - * An event published when a connection is ready for use - * - * @property {number} connectionId The id of the connection - */ -class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection) { - super(pool); - this.connectionId = connection.id; - } -} - -/** - * An event published when a connection is closed - * - * @property {number} connectionId The id of the connection - * @property {string} reason The reason the connection was closed - */ -class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection, reason) { - super(pool); - this.connectionId = connection.id; - this.reason = reason || 'unknown'; - } -} - -/** - * An event published when a request to check a connection out begins - */ -class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); - } -} - -/** - * An event published when a request to check a connection out fails - * - * @property {string} reason The reason the attempt to check out failed - */ -class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, reason) { - super(pool); - this.reason = reason; - } -} - -/** - * An event published when a connection is checked out of the connection pool - * - * @property {number} connectionId The id of the connection - */ -class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection) { - super(pool); - this.connectionId = connection.id; - } -} - -/** - * An event published when a connection is checked into the connection pool - * - * @property {number} connectionId The id of the connection - */ -class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent { - constructor(pool, connection) { - super(pool); - this.connectionId = connection.id; - } -} - -/** - * An event published when a connection pool is cleared - */ -class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent { - constructor(pool) { - super(pool); - } -} - -const CMAP_EVENT_NAMES = [ - 'connectionPoolCreated', - 'connectionPoolClosed', - 'connectionCreated', - 'connectionReady', - 'connectionClosed', - 'connectionCheckOutStarted', - 'connectionCheckOutFailed', - 'connectionCheckedOut', - 'connectionCheckedIn', - 'connectionPoolCleared' -]; - -module.exports = { - CMAP_EVENT_NAMES, - ConnectionPoolCreatedEvent, - ConnectionPoolClosedEvent, - ConnectionCreatedEvent, - ConnectionReadyEvent, - ConnectionClosedEvent, - ConnectionCheckOutStartedEvent, - ConnectionCheckOutFailedEvent, - ConnectionCheckedOutEvent, - ConnectionCheckedInEvent, - ConnectionPoolClearedEvent -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/cmap/message_stream.js b/node_modules/mongoose/node_modules/mongodb/lib/cmap/message_stream.js deleted file mode 100644 index c8f458e..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/cmap/message_stream.js +++ /dev/null @@ -1,196 +0,0 @@ -'use strict'; - -const Duplex = require('stream').Duplex; -const BufferList = require('bl'); -const MongoParseError = require('../core/error').MongoParseError; -const decompress = require('../core/wireprotocol/compression').decompress; -const Response = require('../core/connection/commands').Response; -const BinMsg = require('../core/connection/msg').BinMsg; -const MongoError = require('../core/error').MongoError; -const OP_COMPRESSED = require('../core/wireprotocol/shared').opcodes.OP_COMPRESSED; -const OP_MSG = require('../core/wireprotocol/shared').opcodes.OP_MSG; -const MESSAGE_HEADER_SIZE = require('../core/wireprotocol/shared').MESSAGE_HEADER_SIZE; -const COMPRESSION_DETAILS_SIZE = require('../core/wireprotocol/shared').COMPRESSION_DETAILS_SIZE; -const opcodes = require('../core/wireprotocol/shared').opcodes; -const compress = require('../core/wireprotocol/compression').compress; -const compressorIDs = require('../core/wireprotocol/compression').compressorIDs; -const uncompressibleCommands = require('../core/wireprotocol/compression').uncompressibleCommands; -const Msg = require('../core/connection/msg').Msg; - -const kDefaultMaxBsonMessageSize = 1024 * 1024 * 16 * 4; -const kBuffer = Symbol('buffer'); - -/** - * A duplex stream that is capable of reading and writing raw wire protocol messages, with - * support for optional compression - */ -class MessageStream extends Duplex { - constructor(options) { - options = options || {}; - super(options); - - this.bson = options.bson; - this.maxBsonMessageSize = options.maxBsonMessageSize || kDefaultMaxBsonMessageSize; - - this[kBuffer] = new BufferList(); - } - - _write(chunk, _, callback) { - const buffer = this[kBuffer]; - buffer.append(chunk); - - processIncomingData(this, callback); - } - - _read(/* size */) { - // NOTE: This implementation is empty because we explicitly push data to be read - // when `writeMessage` is called. - return; - } - - writeCommand(command, operationDescription) { - // TODO: agreed compressor should live in `StreamDescription` - const shouldCompress = operationDescription && !!operationDescription.agreedCompressor; - if (!shouldCompress || !canCompress(command)) { - const data = command.toBin(); - this.push(Array.isArray(data) ? Buffer.concat(data) : data); - return; - } - - // otherwise, compress the message - const concatenatedOriginalCommandBuffer = Buffer.concat(command.toBin()); - const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); - - // Extract information needed for OP_COMPRESSED from the uncompressed message - const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); - - // Compress the message body - compress({ options: operationDescription }, messageToBeCompressed, (err, compressedMessage) => { - if (err) { - operationDescription.cb(err, null); - return; - } - - // Create the msgHeader of OP_COMPRESSED - const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); - msgHeader.writeInt32LE( - MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, - 0 - ); // messageLength - msgHeader.writeInt32LE(command.requestId, 4); // requestID - msgHeader.writeInt32LE(0, 8); // responseTo (zero) - msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode - - // Create the compression details of OP_COMPRESSED - const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); - compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode - compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader - compressionDetails.writeUInt8(compressorIDs[operationDescription.agreedCompressor], 8); // compressorID - - this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); - }); - } -} - -// Return whether a command contains an uncompressible command term -// Will return true if command contains no uncompressible command terms -function canCompress(command) { - const commandDoc = command instanceof Msg ? command.command : command.query; - const commandName = Object.keys(commandDoc)[0]; - return !uncompressibleCommands.has(commandName); -} - -function processIncomingData(stream, callback) { - const buffer = stream[kBuffer]; - if (buffer.length < 4) { - callback(); - return; - } - - const sizeOfMessage = buffer.readInt32LE(0); - if (sizeOfMessage < 0) { - callback(new MongoParseError(`Invalid message size: ${sizeOfMessage}`)); - return; - } - - if (sizeOfMessage > stream.maxBsonMessageSize) { - callback( - new MongoParseError( - `Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}` - ) - ); - return; - } - - if (sizeOfMessage > buffer.length) { - callback(); - return; - } - - const message = buffer.slice(0, sizeOfMessage); - buffer.consume(sizeOfMessage); - - const messageHeader = { - length: message.readInt32LE(0), - requestId: message.readInt32LE(4), - responseTo: message.readInt32LE(8), - opCode: message.readInt32LE(12) - }; - - let ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; - const responseOptions = stream.responseOptions; - if (messageHeader.opCode !== OP_COMPRESSED) { - const messageBody = message.slice(MESSAGE_HEADER_SIZE); - stream.emit( - 'message', - new ResponseType(stream.bson, message, messageHeader, messageBody, responseOptions) - ); - - if (buffer.length >= 4) { - processIncomingData(stream, callback); - } else { - callback(); - } - - return; - } - - messageHeader.fromCompressed = true; - messageHeader.opCode = message.readInt32LE(MESSAGE_HEADER_SIZE); - messageHeader.length = message.readInt32LE(MESSAGE_HEADER_SIZE + 4); - const compressorID = message[MESSAGE_HEADER_SIZE + 8]; - const compressedBuffer = message.slice(MESSAGE_HEADER_SIZE + 9); - - // recalculate based on wrapped opcode - ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; - - decompress(compressorID, compressedBuffer, (err, messageBody) => { - if (err) { - callback(err); - return; - } - - if (messageBody.length !== messageHeader.length) { - callback( - new MongoError( - 'Decompressing a compressed message from the server failed. The message is corrupt.' - ) - ); - - return; - } - - stream.emit( - 'message', - new ResponseType(stream.bson, message, messageHeader, messageBody, responseOptions) - ); - - if (buffer.length >= 4) { - processIncomingData(stream, callback); - } else { - callback(); - } - }); -} - -module.exports = MessageStream; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/cmap/stream_description.js b/node_modules/mongoose/node_modules/mongodb/lib/cmap/stream_description.js deleted file mode 100644 index e806a5f..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/cmap/stream_description.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; -const parseServerType = require('../core/sdam/server_description').parseServerType; - -const RESPONSE_FIELDS = [ - 'minWireVersion', - 'maxWireVersion', - 'maxBsonObjectSize', - 'maxMessageSizeBytes', - 'maxWriteBatchSize', - '__nodejs_mock_server__' -]; - -class StreamDescription { - constructor(address, options) { - this.address = address; - this.type = parseServerType(null); - this.minWireVersion = undefined; - this.maxWireVersion = undefined; - this.maxBsonObjectSize = 16777216; - this.maxMessageSizeBytes = 48000000; - this.maxWriteBatchSize = 100000; - this.compressors = - options && options.compression && Array.isArray(options.compression.compressors) - ? options.compression.compressors - : []; - } - - receiveResponse(response) { - this.type = parseServerType(response); - - RESPONSE_FIELDS.forEach(field => { - if (typeof response[field] !== 'undefined') { - this[field] = response[field]; - } - }); - - if (response.compression) { - this.compressor = this.compressors.filter(c => response.compression.indexOf(c) !== -1)[0]; - } - } -} - -module.exports = { - StreamDescription -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/collection.js b/node_modules/mongoose/node_modules/mongodb/lib/collection.js deleted file mode 100644 index bf4861d..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/collection.js +++ /dev/null @@ -1,2201 +0,0 @@ -'use strict'; - -const deprecate = require('util').deprecate; -const deprecateOptions = require('./utils').deprecateOptions; -const checkCollectionName = require('./utils').checkCollectionName; -const ObjectID = require('./core').BSON.ObjectID; -const MongoError = require('./core').MongoError; -const toError = require('./utils').toError; -const normalizeHintField = require('./utils').normalizeHintField; -const decorateCommand = require('./utils').decorateCommand; -const decorateWithCollation = require('./utils').decorateWithCollation; -const decorateWithReadConcern = require('./utils').decorateWithReadConcern; -const formattedOrderClause = require('./utils').formattedOrderClause; -const ReadPreference = require('./core').ReadPreference; -const unordered = require('./bulk/unordered'); -const ordered = require('./bulk/ordered'); -const ChangeStream = require('./change_stream'); -const executeLegacyOperation = require('./utils').executeLegacyOperation; -const resolveReadPreference = require('./utils').resolveReadPreference; -const WriteConcern = require('./write_concern'); -const ReadConcern = require('./read_concern'); -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const AggregationCursor = require('./aggregation_cursor'); -const CommandCursor = require('./command_cursor'); - -// Operations -const checkForAtomicOperators = require('./operations/collection_ops').checkForAtomicOperators; -const ensureIndex = require('./operations/collection_ops').ensureIndex; -const group = require('./operations/collection_ops').group; -const parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan; -const removeDocuments = require('./operations/common_functions').removeDocuments; -const save = require('./operations/collection_ops').save; -const updateDocuments = require('./operations/common_functions').updateDocuments; - -const AggregateOperation = require('./operations/aggregate'); -const BulkWriteOperation = require('./operations/bulk_write'); -const CountDocumentsOperation = require('./operations/count_documents'); -const CreateIndexOperation = require('./operations/create_index'); -const CreateIndexesOperation = require('./operations/create_indexes'); -const DeleteManyOperation = require('./operations/delete_many'); -const DeleteOneOperation = require('./operations/delete_one'); -const DistinctOperation = require('./operations/distinct'); -const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; -const DropIndexOperation = require('./operations/drop_index'); -const DropIndexesOperation = require('./operations/drop_indexes'); -const EstimatedDocumentCountOperation = require('./operations/estimated_document_count'); -const FindOperation = require('./operations/find'); -const FindOneOperation = require('./operations/find_one'); -const FindAndModifyOperation = require('./operations/find_and_modify'); -const FindOneAndDeleteOperation = require('./operations/find_one_and_delete'); -const FindOneAndReplaceOperation = require('./operations/find_one_and_replace'); -const FindOneAndUpdateOperation = require('./operations/find_one_and_update'); -const GeoHaystackSearchOperation = require('./operations/geo_haystack_search'); -const IndexesOperation = require('./operations/indexes'); -const IndexExistsOperation = require('./operations/index_exists'); -const IndexInformationOperation = require('./operations/index_information'); -const InsertManyOperation = require('./operations/insert_many'); -const InsertOneOperation = require('./operations/insert_one'); -const IsCappedOperation = require('./operations/is_capped'); -const ListIndexesOperation = require('./operations/list_indexes'); -const MapReduceOperation = require('./operations/map_reduce'); -const OptionsOperation = require('./operations/options_operation'); -const RenameOperation = require('./operations/rename'); -const ReIndexOperation = require('./operations/re_index'); -const ReplaceOneOperation = require('./operations/replace_one'); -const StatsOperation = require('./operations/stats'); -const UpdateManyOperation = require('./operations/update_many'); -const UpdateOneOperation = require('./operations/update_one'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection - * allowing for insert/update/remove/find and other command operation on that MongoDB collection. - * - * **COLLECTION Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - */ - -const mergeKeys = ['ignoreUndefined']; - -/** - * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) - * @class - */ -function Collection(db, topology, dbName, name, pkFactory, options) { - checkCollectionName(name); - - // Unpack variables - const internalHint = null; - const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; - const serializeFunctions = - options == null || options.serializeFunctions == null - ? db.s.options.serializeFunctions - : options.serializeFunctions; - const raw = options == null || options.raw == null ? db.s.options.raw : options.raw; - const promoteLongs = - options == null || options.promoteLongs == null - ? db.s.options.promoteLongs - : options.promoteLongs; - const promoteValues = - options == null || options.promoteValues == null - ? db.s.options.promoteValues - : options.promoteValues; - const promoteBuffers = - options == null || options.promoteBuffers == null - ? db.s.options.promoteBuffers - : options.promoteBuffers; - const collectionHint = null; - - const namespace = new MongoDBNamespace(dbName, name); - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Set custom primary key factory if provided - pkFactory = pkFactory == null ? ObjectID : pkFactory; - - // Internal state - this.s = { - // Set custom primary key factory if provided - pkFactory: pkFactory, - // Db - db: db, - // Topology - topology: topology, - // Options - options: options, - // Namespace - namespace: namespace, - // Read preference - readPreference: ReadPreference.fromOptions(options), - // SlaveOK - slaveOk: slaveOk, - // Serialize functions - serializeFunctions: serializeFunctions, - // Raw - raw: raw, - // promoteLongs - promoteLongs: promoteLongs, - // promoteValues - promoteValues: promoteValues, - // promoteBuffers - promoteBuffers: promoteBuffers, - // internalHint - internalHint: internalHint, - // collectionHint - collectionHint: collectionHint, - // Promise library - promiseLibrary: promiseLibrary, - // Read Concern - readConcern: ReadConcern.fromOptions(options), - // Write Concern - writeConcern: WriteConcern.fromOptions(options) - }; -} - -/** - * The name of the database this collection belongs to - * @member {string} dbName - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'dbName', { - enumerable: true, - get: function() { - return this.s.namespace.db; - } -}); - -/** - * The name of this collection - * @member {string} collectionName - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'collectionName', { - enumerable: true, - get: function() { - return this.s.namespace.collection; - } -}); - -/** - * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` - * @member {string} namespace - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'namespace', { - enumerable: true, - get: function() { - return this.s.namespace.toString(); - } -}); - -/** - * The current readConcern of the collection. If not explicitly defined for - * this collection, will be inherited from the parent DB - * @member {ReadConcern} [readConcern] - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'readConcern', { - enumerable: true, - get: function() { - if (this.s.readConcern == null) { - return this.s.db.readConcern; - } - return this.s.readConcern; - } -}); - -/** - * The current readPreference of the collection. If not explicitly defined for - * this collection, will be inherited from the parent DB - * @member {ReadPreference} [readPreference] - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'readPreference', { - enumerable: true, - get: function() { - if (this.s.readPreference == null) { - return this.s.db.readPreference; - } - - return this.s.readPreference; - } -}); - -/** - * The current writeConcern of the collection. If not explicitly defined for - * this collection, will be inherited from the parent DB - * @member {WriteConcern} [writeConcern] - * @memberof Collection# - * @readonly - */ -Object.defineProperty(Collection.prototype, 'writeConcern', { - enumerable: true, - get: function() { - if (this.s.writeConcern == null) { - return this.s.db.writeConcern; - } - return this.s.writeConcern; - } -}); - -/** - * The current index hint for the collection - * @member {object} [hint] - * @memberof Collection# - */ -Object.defineProperty(Collection.prototype, 'hint', { - enumerable: true, - get: function() { - return this.s.collectionHint; - }, - set: function(v) { - this.s.collectionHint = normalizeHintField(v); - } -}); - -const DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot']; - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB - * @method - * @param {object} [query={}] The cursor query object. - * @param {object} [options] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.projection] The fields to return in the query. Object of fields to either include or exclude (one of, not both), {'a':1, 'b': 1} **or** {'a': 0, 'b': 0} - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * @param {boolean} [options.explain=false] Explain the query instead of returning the data. - * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. - * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. - * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. - * @param {boolean} [options.awaitData=false] Specify if the cursor is a a tailable-await cursor. Requires `tailable` to be true - * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {boolean} [options.returnKey=false] Only return the index key. - * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. - * @param {number} [options.min] Set index bounds. - * @param {number} [options.max] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true - * @param {boolean} [options.noCursorTimeout] The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @throws {MongoError} - * @return {Cursor} - */ -Collection.prototype.find = deprecateOptions( - { - name: 'collection.find', - deprecatedOptions: DEPRECATED_FIND_OPTIONS, - optionsIndex: 1 - }, - function(query, options, callback) { - if (typeof callback === 'object') { - // TODO(MAJOR): throw in the future - console.warn('Third parameter to `find()` must be a callback or undefined'); - } - - let selector = query; - // figuring out arguments - if (typeof callback !== 'function') { - if (typeof options === 'function') { - callback = options; - options = undefined; - } else if (options == null) { - callback = typeof selector === 'function' ? selector : undefined; - selector = typeof selector === 'object' ? selector : undefined; - } - } - - // Ensure selector is not null - selector = selector == null ? {} : selector; - // Validate correctness off the selector - const object = selector; - if (Buffer.isBuffer(object)) { - const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24); - if (object_size !== object.length) { - const error = new Error( - 'query selector raw message size does not match message header size [' + - object.length + - '] != [' + - object_size + - ']' - ); - error.name = 'MongoError'; - throw error; - } - } - - // Check special case where we are using an objectId - if (selector != null && selector._bsontype === 'ObjectID') { - selector = { _id: selector }; - } - - if (!options) options = {}; - - let projection = options.projection || options.fields; - - if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) { - projection = projection.length - ? projection.reduce((result, field) => { - result[field] = 1; - return result; - }, {}) - : { _id: 1 }; - } - - // Make a shallow copy of options - let newOptions = Object.assign({}, options); - - // Make a shallow copy of the collection options - for (let key in this.s.options) { - if (mergeKeys.indexOf(key) !== -1) { - newOptions[key] = this.s.options[key]; - } - } - - // Unpack options - newOptions.skip = options.skip ? options.skip : 0; - newOptions.limit = options.limit ? options.limit : 0; - newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw; - newOptions.hint = - options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; - newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout; - // // If we have overridden slaveOk otherwise use the default db setting - newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; - - // Add read preference if needed - newOptions.readPreference = resolveReadPreference(this, newOptions); - - // Set slave ok to true if read preference different from primary - if ( - newOptions.readPreference != null && - (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary') - ) { - newOptions.slaveOk = true; - } - - // Ensure the query is an object - if (selector != null && typeof selector !== 'object') { - throw MongoError.create({ message: 'query selector must be an object', driver: true }); - } - - // Build the find command - const findCommand = { - find: this.s.namespace.toString(), - limit: newOptions.limit, - skip: newOptions.skip, - query: selector - }; - - // Ensure we use the right await data option - if (typeof newOptions.awaitdata === 'boolean') { - newOptions.awaitData = newOptions.awaitdata; - } - - // Translate to new command option noCursorTimeout - if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout; - - decorateCommand(findCommand, newOptions, ['session', 'collation']); - - if (projection) findCommand.fields = projection; - - // Add db object to the new options - newOptions.db = this.s.db; - - // Add the promise library - newOptions.promiseLibrary = this.s.promiseLibrary; - - // Set raw if available at collection level - if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw; - // Set promoteLongs if available at collection level - if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean') - newOptions.promoteLongs = this.s.promoteLongs; - if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean') - newOptions.promoteValues = this.s.promoteValues; - if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean') - newOptions.promoteBuffers = this.s.promoteBuffers; - - // Sort options - if (findCommand.sort) { - findCommand.sort = formattedOrderClause(findCommand.sort); - } - - // Set the readConcern - decorateWithReadConcern(findCommand, this, options); - - // Decorate find command with collation options - try { - decorateWithCollation(findCommand, this, options); - } catch (err) { - if (typeof callback === 'function') return callback(err, null); - throw err; - } - - const cursor = this.s.topology.cursor( - new FindOperation(this, this.s.namespace, findCommand, newOptions), - newOptions - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; - } -); - -/** - * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object} doc Document to insert. - * @param {object} [options] Optional settings. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertOne = function(doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const insertOneOperation = new InsertOneOperation(this, doc, options); - - return executeOperation(this.s.topology, insertOneOperation, callback); -}; - -/** - * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} docs Documents to insert. - * @param {object} [options] Optional settings. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertMany = function(docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : { ordered: true }; - - const insertManyOperation = new InsertManyOperation(this, docs, options); - - return executeOperation(this.s.topology, insertManyOperation, callback); -}; - -/** - * @typedef {Object} Collection~BulkWriteOpResult - * @property {number} insertedCount Number of documents inserted. - * @property {number} matchedCount Number of documents matched for update. - * @property {number} modifiedCount Number of documents modified. - * @property {number} deletedCount Number of documents deleted. - * @property {number} upsertedCount Number of documents upserted. - * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation - * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~bulkWriteOpCallback - * @param {BulkWriteError} error An error instance representing the error during the execution. - * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Perform a bulkWrite operation without a fluent API - * - * Legal operation types are - * - * { insertOne: { document: { a: 1 } } } - * - * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } - * - * { deleteOne: { filter: {c:1} } } - * - * { deleteMany: { filter: {c:1} } } - * - * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} - * - * If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} operations Bulk operations to perform. - * @param {object} [options] Optional settings. - * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object[]} [options.arrayFilters] Determines which array elements to modify for update operation in MongoDB 3.6 or higher. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~bulkWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.bulkWrite = function(operations, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || { ordered: true }; - - if (!Array.isArray(operations)) { - throw MongoError.create({ message: 'operations must be an array of documents', driver: true }); - } - - const bulkWriteOperation = new BulkWriteOperation(this, operations, options); - - return executeOperation(this.s.topology, bulkWriteOperation, callback); -}; - -/** - * @typedef {Object} Collection~WriteOpResult - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {object} connection The connection object used for the operation. - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~writeOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * @typedef {Object} Collection~insertWriteOpResult - * @property {number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {Object.} insertedIds Map of the index of the inserted document to the id of the inserted document. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {number} result.ok Is 1 if the command executed correctly. - * @property {number} result.n The total count of documents inserted. - */ - -/** - * @typedef {Object} Collection~insertOneWriteOpResult - * @property {number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {number} result.ok Is 1 if the command executed correctly. - * @property {number} result.n The total count of documents inserted. - */ - -/** - * The callback format for inserts - * @callback Collection~insertWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * The callback format for inserts - * @callback Collection~insertOneWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {(object|object[])} docs Documents to insert. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated Use insertOne, insertMany or bulkWrite - */ -Collection.prototype.insert = deprecate(function(docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || { ordered: false }; - docs = !Array.isArray(docs) ? [docs] : docs; - - if (options.keepGoing === true) { - options.ordered = false; - } - - return this.insertMany(docs, options, callback); -}, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); - -/** - * @typedef {Object} Collection~updateWriteOpResult - * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents scanned. - * @property {Number} result.nModified The total count of documents modified. - * @property {Object} connection The connection object used for the operation. - * @property {Number} matchedCount The number of documents that matched the filter. - * @property {Number} modifiedCount The number of documents that were modified. - * @property {Number} upsertedCount The number of documents upserted. - * @property {Object} upsertedId The upserted id. - * @property {ObjectId} upsertedId._id The upserted _id returned from the server. - * @property {Object} message The raw msg response wrapped in an internal class - * @property {object[]} [ops] In a response to {@link Collection#replaceOne replaceOne}, contains the new value of the document on the server. This is the same document that was originally passed in, and is only here for legacy purposes. - */ - -/** - * The callback format for inserts - * @callback Collection~updateWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Update a single document in a collection - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update The update operations to be applied to the document - * @param {object} [options] Optional settings. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query.. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateOne = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const updateOneOperation = new UpdateOneOperation(this, filter, update, options); - - return executeOperation(this.s.topology, updateOneOperation, callback); -}; - -/** - * Replace a document in a collection with another document - * @method - * @param {object} filter The Filter used to select the document to replace - * @param {object} doc The Document that replaces the matching document - * @param {object} [options] Optional settings. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.replaceOne = function(filter, doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const replaceOneOperation = new ReplaceOneOperation(this, filter, doc, options); - - return executeOperation(this.s.topology, replaceOneOperation, callback); -}; - -/** - * Update multiple documents in a collection - * @method - * @param {object} filter The Filter used to select the documents to update - * @param {object} update The update operations to be applied to the documents - * @param {object} [options] Optional settings. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query.. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateMany = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const updateManyOperation = new UpdateManyOperation(this, filter, update, options); - - return executeOperation(this.s.topology, updateManyOperation, callback); -}; - -/** - * Updates documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} update The update operations to be applied to the documents - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {boolean} [options.multi=false] Update one/all documents with operation. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - * @deprecated use updateOne, updateMany or bulkWrite - */ -Collection.prototype.update = deprecate(function(selector, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, updateDocuments, [ - this, - selector, - update, - options, - callback - ]); -}, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); - -/** - * @typedef {Object} Collection~deleteWriteOpResult - * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents deleted. - * @property {Object} connection The connection object used for the operation. - * @property {Number} deletedCount The number of documents deleted. - */ - -/** - * The callback format for deletes - * @callback Collection~deleteWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Delete a document from a collection - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteOne = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const deleteOneOperation = new DeleteOneOperation(this, filter, options); - - return executeOperation(this.s.topology, deleteOneOperation, callback); -}; - -Collection.prototype.removeOne = Collection.prototype.deleteOne; - -/** - * Delete multiple documents from a collection - * @method - * @param {object} filter The Filter used to select the documents to remove - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteMany = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const deleteManyOperation = new DeleteManyOperation(this, filter, options); - - return executeOperation(this.s.topology, deleteManyOperation, callback); -}; - -Collection.prototype.removeMany = Collection.prototype.deleteMany; - -/** - * Remove documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.single=false] Removes the first document found. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use deleteOne, deleteMany or bulkWrite - */ -Collection.prototype.remove = deprecate(function(selector, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, removeDocuments, [ - this, - selector, - options, - callback - ]); -}, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); - -/** - * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic - * operators and update instead for more efficient operations. - * @method - * @param {object} doc Document to save - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -Collection.prototype.save = deprecate(function(doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, save, [this, doc, options, callback]); -}, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.'); - -/** - * The callback format for results - * @callback Collection~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * The callback format for an aggregation call - * @callback Collection~aggregationCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. - */ - -/** - * Fetches the first document that matches the query - * @method - * @param {object} query Query for find Operation - * @param {object} [options] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * @param {boolean} [options.explain=false] Explain the query instead of returning the data. - * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. - * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. - * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. - * @param {number} [options.batchSize=1] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {boolean} [options.returnKey=false] Only return the index key. - * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. - * @param {number} [options.min] Set index bounds. - * @param {number} [options.max] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOne = deprecateOptions( - { - name: 'collection.find', - deprecatedOptions: DEPRECATED_FIND_OPTIONS, - optionsIndex: 1 - }, - function(query, options, callback) { - if (typeof callback === 'object') { - // TODO(MAJOR): throw in the future - console.warn('Third parameter to `findOne()` must be a callback or undefined'); - } - - if (typeof query === 'function') (callback = query), (query = {}), (options = {}); - if (typeof options === 'function') (callback = options), (options = {}); - query = query || {}; - options = options || {}; - - const findOneOperation = new FindOneOperation(this, query, options); - - return executeOperation(this.s.topology, findOneOperation, callback); - } -); - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Collection~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * Rename the collection. - * - * @method - * @param {string} newName New name of of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.rename = function(newName, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - const renameOperation = new RenameOperation(this, newName, options); - - return executeOperation(this.s.topology, renameOperation, callback); -}; - -/** - * Drop the collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {object} [options] Optional settings. - * @param {WriteConcern} [options.writeConcern] A full WriteConcern object - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j] The journal write concern - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.drop = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropCollectionOperation = new DropCollectionOperation( - this.s.db, - this.collectionName, - options - ); - - return executeOperation(this.s.topology, dropCollectionOperation, callback); -}; - -/** - * Returns the options of the collection. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.options = function(opts, callback) { - if (typeof opts === 'function') (callback = opts), (opts = {}); - opts = opts || {}; - - const optionsOperation = new OptionsOperation(this, opts); - - return executeOperation(this.s.topology, optionsOperation, callback); -}; - -/** - * Returns if the collection is a capped collection - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.isCapped = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const isCappedOperation = new IsCappedOperation(this, options); - - return executeOperation(this.s.topology, isCappedOperation, callback); -}; - -/** - * Creates an index on the db and collection collection. - * @method - * @param {(string|array|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @example - * const collection = client.db('foo').collection('bar'); - * - * await collection.createIndex({ a: 1, b: -1 }); - * - * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes - * await collection.createIndex([ [c, 1], [d, -1] ]); - * - * // Equivalent to { e: 1 } - * await collection.createIndex('e'); - * - * // Equivalent to { f: 1, g: 1 } - * await collection.createIndex(['f', 'g']) - * - * // Equivalent to { h: 1, i: -1 } - * await collection.createIndex([ { h: 1 }, { i: -1 } ]); - * - * // Equivalent to { j: 1, k: -1, l: 2d } - * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) - */ -Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const createIndexOperation = new CreateIndexOperation( - this.s.db, - this.collectionName, - fieldOrSpec, - options - ); - - return executeOperation(this.s.topology, createIndexOperation, callback); -}; - -/** - * @typedef {object} Collection~IndexDefinition - * @description A definition for an index. Used by the createIndex command. - * @see https://docs.mongodb.com/manual/reference/command/createIndexes/ - */ - -/** - * Creates multiple indexes in the collection, this method is only supported for - * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported - * error. - * - * **Note**: Unlike {@link Collection#createIndex createIndex}, this function takes in raw index specifications. - * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/ here}. - * - * @method - * @param {Collection~IndexDefinition[]} indexSpecs An array of index specifications to be created - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @example - * const collection = client.db('foo').collection('bar'); - * await collection.createIndexes([ - * // Simple index on field fizz - * { - * key: { fizz: 1 }, - * } - * // wildcard index - * { - * key: { '$**': 1 } - * }, - * // named index on darmok and jalad - * { - * key: { darmok: 1, jalad: -1 } - * name: 'tanagra' - * } - * ]); - */ -Collection.prototype.createIndexes = function(indexSpecs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - - options = options ? Object.assign({}, options) : {}; - if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; - - const createIndexesOperation = new CreateIndexesOperation(this, indexSpecs, options); - - return executeOperation(this.s.topology, createIndexesOperation, callback); -}; - -/** - * Drops an index from this collection. - * @method - * @param {string} indexName Name of the index to drop. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndex = function(indexName, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - options = args.length ? args.shift() || {} : {}; - // Run only against primary - options.readPreference = ReadPreference.PRIMARY; - - const dropIndexOperation = new DropIndexOperation(this, indexName, options); - - return executeOperation(this.s.topology, dropIndexOperation, callback); -}; - -/** - * Drops all indexes from this collection. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndexes = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : {}; - - if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; - - const dropIndexesOperation = new DropIndexesOperation(this, options); - - return executeOperation(this.s.topology, dropIndexesOperation, callback); -}; - -/** - * Drops all indexes from this collection. - * @method - * @deprecated use dropIndexes - * @param {Collection~resultCallback} callback The command result callback - * @return {Promise} returns Promise if no [callback] passed - */ -Collection.prototype.dropAllIndexes = deprecate( - Collection.prototype.dropIndexes, - 'collection.dropAllIndexes is deprecated. Use dropIndexes instead.' -); - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.reIndex = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const reIndexOperation = new ReIndexOperation(this, options); - - return executeOperation(this.s.topology, reIndexOperation, callback); -}; - -/** - * Get the list of all indexes information for the collection. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {CommandCursor} - */ -Collection.prototype.listIndexes = function(options) { - const cursor = new CommandCursor( - this.s.topology, - new ListIndexesOperation(this, options), - options - ); - - return cursor; -}; - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated use createIndexes instead - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.ensureIndex = deprecate(function(fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, ensureIndex, [ - this, - fieldOrSpec, - options, - callback - ]); -}, 'collection.ensureIndex is deprecated. Use createIndexes instead.'); - -/** - * Checks if one or more indexes exist on the collection, fails on first non-existing index - * @method - * @param {(string|array)} indexes One or more index names to check. - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexExists = function(indexes, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexExistsOperation = new IndexExistsOperation(this, indexes, options); - - return executeOperation(this.s.topology, indexExistsOperation, callback); -}; - -/** - * Retrieves this collections index info. - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexInformation = function(options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const indexInformationOperation = new IndexInformationOperation( - this.s.db, - this.collectionName, - options - ); - - return executeOperation(this.s.topology, indexInformationOperation, callback); -}; - -/** - * The callback format for results - * @callback Collection~countCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} result The count of documents that matched the query. - */ - -/** - * An estimated count of matching documents in the db to a query. - * - * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents - * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments countDocuments}. - * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount estimatedDocumentCount}. - * - * @method - * @param {object} [query={}] The query for the count. - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {boolean} [options.limit] The limit of documents to count. - * @param {boolean} [options.skip] The number of documents to skip for the count. - * @param {string} [options.hint] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~countCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use {@link Collection#countDocuments countDocuments} or {@link Collection#estimatedDocumentCount estimatedDocumentCount} instead - */ -Collection.prototype.count = deprecate(function(query, options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation( - this.s.topology, - new EstimatedDocumentCountOperation(this, query, options), - callback - ); -}, 'collection.count is deprecated, and will be removed in a future version.' + - ' Use Collection.countDocuments or Collection.estimatedDocumentCount instead'); - -/** - * Gets an estimate of the count of documents in a collection using collection metadata. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. - * @param {Collection~countCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed. - */ -Collection.prototype.estimatedDocumentCount = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const estimatedDocumentCountOperation = new EstimatedDocumentCountOperation(this, options); - - return executeOperation(this.s.topology, estimatedDocumentCountOperation, callback); -}; - -/** - * Gets the number of documents matching the filter. - * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount estimatedDocumentCount}. - * **Note**: When migrating from {@link Collection#count count} to {@link Collection#countDocuments countDocuments} - * the following query operators must be replaced: - * - * | Operator | Replacement | - * | -------- | ----------- | - * | `$where` | [`$expr`][1] | - * | `$near` | [`$geoWithin`][2] with [`$center`][3] | - * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | - * - * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ - * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ - * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center - * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere - * - * @param {object} [query] the query for the count - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specifies a collation. - * @param {string|object} [options.hint] The index to use. - * @param {number} [options.limit] The maximum number of document to count. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. - * @param {number} [options.skip] The number of documents to skip before counting. - * @param {Collection~countCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed. - * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ - * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ - * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center - * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere - */ - -Collection.prototype.countDocuments = function(query, options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - const countDocumentsOperation = new CountDocumentsOperation(this, query, options); - - return executeOperation(this.s.topology, countDocumentsOperation, callback); -}; - -/** - * The distinct command returns a list of distinct values for the given key across a collection. - * @method - * @param {string} key Field of the document to find distinct values for. - * @param {object} [query] The query for filtering the set of documents to which we apply the distinct filter. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.distinct = function(key, query, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - const queryOption = args.length ? args.shift() || {} : {}; - const optionsOption = args.length ? args.shift() || {} : {}; - - const distinctOperation = new DistinctOperation(this, key, queryOption, optionsOption); - - return executeOperation(this.s.topology, distinctOperation, callback); -}; - -/** - * Retrieve all the indexes on the collection. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexes = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexesOperation = new IndexesOperation(this, options); - - return executeOperation(this.s.topology, indexesOperation, callback); -}; - -/** - * Get all the collection statistics. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.scale] Divide the returned sizes by scale value. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.stats = function(options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const statsOperation = new StatsOperation(this, options); - - return executeOperation(this.s.topology, statsOperation, callback); -}; - -/** - * @typedef {Object} Collection~findAndModifyWriteOpResult - * @property {object} value Document returned from the `findAndModify` command. If no documents were found, `value` will be `null` by default (`returnOriginal: true`), even if a document was upserted; if `returnOriginal` was false, the upserted document will be returned in that case. - * @property {object} lastErrorObject The raw lastErrorObject returned from the command. See {@link https://docs.mongodb.com/manual/reference/command/findAndModify/index.html#lasterrorobject|findAndModify command documentation}. - * @property {Number} ok Is 1 if the command executed correctly. - */ - -/** - * The callback format for inserts - * @callback Collection~findAndModifyCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndDelete = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - - const findOneAndDeleteOperation = new FindOneAndDeleteOperation(this, filter, options); - - return executeOperation(this.s.topology, findOneAndDeleteOperation, callback); -}; - -/** - * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to replace - * @param {object} replacement The Document that replaces the matching document - * @param {object} [options] Optional settings. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - if (replacement == null || typeof replacement !== 'object') - throw toError('replacement parameter must be an object'); - - // Check that there are no atomic operators - const keys = Object.keys(replacement); - - if (keys[0] && keys[0][0] === '$') { - throw toError('The replacement document must not contain atomic operators.'); - } - - const findOneAndReplaceOperation = new FindOneAndReplaceOperation( - this, - filter, - replacement, - options - ); - - return executeOperation(this.s.topology, findOneAndReplaceOperation, callback); -}; - -/** - * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update Update operations to be performed on the document - * @param {object} [options] Optional settings. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - if (update == null || typeof update !== 'object') - throw toError('update parameter must be an object'); - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - const findOneAndUpdateOperation = new FindOneAndUpdateOperation(this, filter, update, options); - - return executeOperation(this.s.topology, findOneAndUpdateOperation, callback); -}; - -/** - * Find and update a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} doc The fields/vals to be updated. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.remove=false] Set to true to remove the object before returning. - * @param {boolean} [options.upsert=false] Perform an upsert operation. - * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. - * @param {object} [options.projection] Object containing the field projection for the result returned from the operation. - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {Collection~findAndModifyCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -Collection.prototype.findAndModify = deprecate( - _findAndModify, - 'collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.' -); - -/** - * @ignore - */ - -Collection.prototype._findAndModify = _findAndModify; - -function _findAndModify(query, sort, doc, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - sort = args.length ? args.shift() || [] : []; - doc = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Clone options - options = Object.assign({}, options); - // Force read preference primary - options.readPreference = ReadPreference.PRIMARY; - - return executeOperation( - this.s.topology, - new FindAndModifyOperation(this, query, sort, doc, options), - callback - ); -} - -/** - * Find and remove a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndDelete instead - */ -Collection.prototype.findAndRemove = deprecate(function(query, sort, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - sort = args.length ? args.shift() || [] : []; - options = args.length ? args.shift() || {} : {}; - - // Add the remove option - options.remove = true; - - return executeOperation( - this.s.topology, - new FindAndModifyOperation(this, query, sort, null, options), - callback - ); -}, 'collection.findAndRemove is deprecated. Use findOneAndDelete instead.'); - -/** - * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 - * @method - * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * @param {number} [options.cursor.batchSize=1000] Deprecated. Use `options.batchSize` - * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). - * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {string} [options.comment] Add a comment to an aggregation command - * @param {string|object} [options.hint] Add an index selection hint to an aggregation command - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~aggregationCallback} callback The command result callback - * @return {(null|AggregationCursor)} - */ -Collection.prototype.aggregate = function(pipeline, options, callback) { - if (Array.isArray(pipeline)) { - // Set up callback if one is provided - if (typeof options === 'function') { - callback = options; - options = {}; - } - - // If we have no options or callback we are doing - // a cursor based aggregation - if (options == null && callback == null) { - options = {}; - } - } else { - // Aggregation pipeline passed as arguments on the method - const args = Array.prototype.slice.call(arguments, 0); - // Get the callback - callback = args.pop(); - // Get the possible options object - const opts = args[args.length - 1]; - // If it contains any of the admissible options pop it of the args - options = - opts && - (opts.readPreference || - opts.explain || - opts.cursor || - opts.out || - opts.maxTimeMS || - opts.hint || - opts.allowDiskUse) - ? args.pop() - : {}; - // Left over arguments is the pipeline - pipeline = args; - } - - const cursor = new AggregationCursor( - this.s.topology, - new AggregateOperation(this, pipeline, options), - options - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; -}; - -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. - * @method - * @since 3.0.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -Collection.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * The callback format for results - * @callback Collection~parallelCollectionScanCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. - */ - -/** - * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are - * no ordering guarantees for returned results. - * @method - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) - * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.parallelCollectionScan = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = { numCursors: 1 }); - // Set number of cursors to 1 - options.numCursors = options.numCursors || 1; - options.batchSize = options.batchSize || 1000; - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(this, options); - - // Add a promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - if (options.session) { - options.session = undefined; - } - - return executeLegacyOperation( - this.s.topology, - parallelCollectionScan, - [this, options, callback], - { skipSessions: true } - ); -}, 'parallelCollectionScan is deprecated in MongoDB v4.1'); - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @method - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxDistance] Include results up to maxDistance from the point. - * @param {object} [options.search] Filter the results by a query. - * @param {number} [options.limit=false] Max number of results to return. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { - const args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const geoHaystackSearchOperation = new GeoHaystackSearchOperation(this, x, y, options); - - return executeOperation(this.s.topology, geoHaystackSearchOperation, callback); -}; - -/** - * Run a group command across a collection - * - * @method - * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. - * @param {object} condition An optional condition that must be true for a row to be considered. - * @param {object} initial Initial value of the aggregation counter object. - * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated - * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. - * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. - */ -Collection.prototype.group = deprecate(function( - keys, - condition, - initial, - reduce, - finalize, - command, - options, - callback -) { - const args = Array.prototype.slice.call(arguments, 3); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - reduce = args.length ? args.shift() : null; - finalize = args.length ? args.shift() : null; - command = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Make sure we are backward compatible - if (!(typeof finalize === 'function')) { - command = finalize; - finalize = null; - } - - if ( - !Array.isArray(keys) && - keys instanceof Object && - typeof keys !== 'function' && - !(keys._bsontype === 'Code') - ) { - keys = Object.keys(keys); - } - - if (typeof reduce === 'function') { - reduce = reduce.toString(); - } - - if (typeof finalize === 'function') { - finalize = finalize.toString(); - } - - // Set up the command as default - command = command == null ? true : command; - - return executeLegacyOperation(this.s.topology, group, [ - this, - keys, - condition, - initial, - reduce, - finalize, - command, - options, - callback - ]); -}, -'MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.'); - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * @method - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.out] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* - * @param {object} [options.query] Query filter object. - * @param {object} [options.sort] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. - * @param {number} [options.limit] Number of objects to return from collection. - * @param {boolean} [options.keeptemp=false] Keep temporary data. - * @param {(function|string)} [options.finalize] Finalize function. - * @param {object} [options.scope] Can pass in variables that can be access from map/reduce/finalize. - * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. - * @param {boolean} [options.verbose=false] Provide statistics on job execution time. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.mapReduce = function(map, reduce, options, callback) { - if ('function' === typeof options) (callback = options), (options = {}); - // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) - if (null == options.out) { - throw new Error( - 'the out option parameter must be defined, see mongodb docs for possible values' - ); - } - - if ('function' === typeof map) { - map = map.toString(); - } - - if ('function' === typeof reduce) { - reduce = reduce.toString(); - } - - if ('function' === typeof options.finalize) { - options.finalize = options.finalize.toString(); - } - const mapReduceOperation = new MapReduceOperation(this, map, reduce, options); - - return executeOperation(this.s.topology, mapReduceOperation, callback); -}; - -/** - * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. - * - * @method - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {UnorderedBulkOperation} - */ -Collection.prototype.initializeUnorderedBulkOp = function(options) { - options = options || {}; - // Give function's options precedence over session options. - if (options.ignoreUndefined == null) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - options.promiseLibrary = this.s.promiseLibrary; - return unordered(this.s.topology, this, options); -}; - -/** - * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. - * - * @method - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {OrderedBulkOperation} callback The command result callback - * @return {null} - */ -Collection.prototype.initializeOrderedBulkOp = function(options) { - options = options || {}; - // Give function's options precedence over session's options. - if (options.ignoreUndefined == null) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - options.promiseLibrary = this.s.promiseLibrary; - return ordered(this.s.topology, this, options); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -Collection.prototype.getLogger = function() { - return this.s.db.s.logger; -}; - -module.exports = Collection; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js deleted file mode 100644 index cd0f9d7..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/command_cursor.js +++ /dev/null @@ -1,269 +0,0 @@ -'use strict'; - -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const CursorState = require('./core/cursor').CursorState; - -/** - * @fileOverview The **CommandCursor** class is an internal class that embodies a - * generalized cursor based on a MongoDB command allowing for iteration over the - * results returned. It supports one by one document iteration, conversion to an - * array or can be iterated as a Node 0.10.X or higher stream - * - * **CommandCursor Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('listCollectionsExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // List the database collections available - * db.listCollections().toArray(function(err, items) { - * test.equal(null, err); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class CommandCursor - * @extends external:Readable - * @fires CommandCursor#data - * @fires CommandCursor#end - * @fires CommandCursor#close - * @fires CommandCursor#readable - * @return {CommandCursor} an CommandCursor instance. - */ -class CommandCursor extends Cursor { - constructor(topology, ns, cmd, options) { - super(topology, ns, cmd, options); - } - - /** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ - setReadPreference(readPreference) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (this.s.state !== CursorState.INIT) { - throw MongoError.create({ - message: 'cannot change cursor readPreference after cursor has been accessed', - driver: true - }); - } - - if (readPreference instanceof ReadPreference) { - this.options.readPreference = readPreference; - } else if (typeof readPreference === 'string') { - this.options.readPreference = new ReadPreference(readPreference); - } else { - throw new TypeError('Invalid read preference: ' + readPreference); - } - - return this; - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. - * @throws {MongoError} - * @return {CommandCursor} - */ - batchSize(value) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - if (this.cmd.cursor) { - this.cmd.cursor.batchSize = value; - } - - this.setCursorBatchSize(value); - return this; - } - - /** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {CommandCursor} - */ - maxTimeMS(value) { - if (this.topology.lastIsMaster().minWireVersion > 2) { - this.cmd.maxTimeMS = value; - } - - return this; - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -// aliases -CommandCursor.prototype.get = CommandCursor.prototype.toArray; - -/** - * CommandCursor stream data event, fired for each document in the cursor. - * - * @event CommandCursor#data - * @type {object} - */ - -/** - * CommandCursor stream end event - * - * @event CommandCursor#end - * @type {null} - */ - -/** - * CommandCursor stream close event - * - * @event CommandCursor#close - * @type {null} - */ - -/** - * CommandCursor stream readable event - * - * @event CommandCursor#readable - * @type {null} - */ - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function CommandCursor.prototype.next - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function CommandCursor.prototype.hasNext - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previously accessed. - * @method CommandCursor.prototype.toArray - * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method CommandCursor.prototype.each - * @param {CommandCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a KillCursor command and emitting close. - * @method CommandCursor.prototype.close - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method CommandCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Clone the cursor - * @function CommandCursor.prototype.clone - * @return {CommandCursor} - */ - -/** - * Resets the cursor - * @function CommandCursor.prototype.rewind - * @return {CommandCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback CommandCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback CommandCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/* - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method CommandCursor.prototype.forEach - * @param {CommandCursor~iteratorCallback} iterator The iteration callback. - * @param {CommandCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -module.exports = CommandCursor; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/constants.js b/node_modules/mongoose/node_modules/mongodb/lib/constants.js deleted file mode 100644 index d6cc68a..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/constants.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -module.exports = { - SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces', - SYSTEM_INDEX_COLLECTION: 'system.indexes', - SYSTEM_PROFILE_COLLECTION: 'system.profile', - SYSTEM_USER_COLLECTION: 'system.users', - SYSTEM_COMMAND_COLLECTION: '$cmd', - SYSTEM_JS_COLLECTION: 'system.js' -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/auth_provider.js b/node_modules/mongoose/node_modules/mongodb/lib/core/auth/auth_provider.js deleted file mode 100644 index 7597b72..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/auth_provider.js +++ /dev/null @@ -1,158 +0,0 @@ -'use strict'; - -const MongoError = require('../error').MongoError; - -/** - * Creates a new AuthProvider, which dictates how to authenticate for a given - * mechanism. - * @class - */ -class AuthProvider { - constructor(bson) { - this.bson = bson; - this.authStore = []; - } - - /** - * Authenticate - * @method - * @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection - * @param {Connection[]} connections Connections to authenticate using this authenticator - * @param {MongoCredentials} credentials Authentication credentials - * @param {authResultCallback} callback The callback to return the result from the authentication - */ - auth(sendAuthCommand, connections, credentials, callback) { - // Total connections - let count = connections.length; - - if (count === 0) { - callback(null, null); - return; - } - - // Valid connections - let numberOfValidConnections = 0; - let errorObject = null; - - const execute = connection => { - this._authenticateSingleConnection(sendAuthCommand, connection, credentials, (err, r) => { - // Adjust count - count = count - 1; - - // If we have an error - if (err) { - errorObject = new MongoError(err); - } else if (r && (r.$err || r.errmsg)) { - errorObject = new MongoError(r); - } else { - numberOfValidConnections = numberOfValidConnections + 1; - } - - // Still authenticating against other connections. - if (count !== 0) { - return; - } - - // We have authenticated all connections - if (numberOfValidConnections > 0) { - // Store the auth details - this.addCredentials(credentials); - // Return correct authentication - callback(null, true); - } else { - if (errorObject == null) { - errorObject = new MongoError(`failed to authenticate using ${credentials.mechanism}`); - } - callback(errorObject, false); - } - }); - }; - - const executeInNextTick = _connection => process.nextTick(() => execute(_connection)); - - // For each connection we need to authenticate - while (connections.length > 0) { - executeInNextTick(connections.shift()); - } - } - - /** - * Implementation of a single connection authenticating. Is meant to be overridden. - * Will error if called directly - * @ignore - */ - _authenticateSingleConnection(/*sendAuthCommand, connection, credentials, callback*/) { - throw new Error('_authenticateSingleConnection must be overridden'); - } - - /** - * Adds credentials to store only if it does not exist - * @param {MongoCredentials} credentials credentials to add to store - */ - addCredentials(credentials) { - const found = this.authStore.some(cred => cred.equals(credentials)); - - if (!found) { - this.authStore.push(credentials); - } - } - - /** - * Re authenticate pool - * @method - * @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection - * @param {Connection[]} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - */ - reauthenticate(sendAuthCommand, connections, callback) { - const authStore = this.authStore.slice(0); - let count = authStore.length; - if (count === 0) { - return callback(null, null); - } - - for (let i = 0; i < authStore.length; i++) { - this.auth(sendAuthCommand, connections, authStore[i], function(err) { - count = count - 1; - if (count === 0) { - callback(err, null); - } - }); - } - } - - /** - * Remove credentials that have been previously stored in the auth provider - * @method - * @param {string} source Name of database we are removing authStore details about - * @return {object} - */ - logout(source) { - this.authStore = this.authStore.filter(credentials => credentials.source !== source); - } -} - -/** - * A function that writes authentication commands to a specific connection - * @callback SendAuthCommand - * @param {Connection} connection The connection to write to - * @param {Command} command A command with a toBin method that can be written to a connection - * @param {AuthWriteCallback} callback Callback called when command response is received - */ - -/** - * A callback for a specific auth command - * @callback AuthWriteCallback - * @param {Error} err If command failed, an error from the server - * @param {object} r The response from the server - */ - -/** - * This is a result from an authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = { AuthProvider }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js b/node_modules/mongoose/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js deleted file mode 100644 index fc5f4c2..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -const MongoCR = require('./mongocr'); -const X509 = require('./x509'); -const Plain = require('./plain'); -const GSSAPI = require('./gssapi'); -const SSPI = require('./sspi'); -const ScramSHA1 = require('./scram').ScramSHA1; -const ScramSHA256 = require('./scram').ScramSHA256; - -/** - * Returns the default authentication providers. - * - * @param {BSON} bson Bson definition - * @returns {Object} a mapping of auth names to auth types - */ -function defaultAuthProviders(bson) { - return { - mongocr: new MongoCR(bson), - x509: new X509(bson), - plain: new Plain(bson), - gssapi: new GSSAPI(bson), - sspi: new SSPI(bson), - 'scram-sha-1': new ScramSHA1(bson), - 'scram-sha-256': new ScramSHA256(bson) - }; -} - -module.exports = { defaultAuthProviders }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/gssapi.js b/node_modules/mongoose/node_modules/mongodb/lib/core/auth/gssapi.js deleted file mode 100644 index 936fb65..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/gssapi.js +++ /dev/null @@ -1,241 +0,0 @@ -'use strict'; - -const AuthProvider = require('./auth_provider').AuthProvider; -const retrieveKerberos = require('../utils').retrieveKerberos; -let kerberos; - -/** - * Creates a new GSSAPI authentication mechanism - * @class - * @extends AuthProvider - */ -class GSSAPI extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const source = credentials.source; - const username = credentials.username; - const password = credentials.password; - const mechanismProperties = credentials.mechanismProperties; - const gssapiServiceName = - mechanismProperties['gssapiservicename'] || - mechanismProperties['gssapiServiceName'] || - 'mongodb'; - - GSSAPIInitialize( - this, - kerberos.processes.MongoAuthProcess, - source, - username, - password, - source, - gssapiServiceName, - sendAuthCommand, - connection, - mechanismProperties, - callback - ); - } - - /** - * Authenticate - * @override - * @method - */ - auth(sendAuthCommand, connections, credentials, callback) { - if (kerberos == null) { - try { - kerberos = retrieveKerberos(); - } catch (e) { - return callback(e, null); - } - } - - super.auth(sendAuthCommand, connections, credentials, callback); - } -} - -// -// Initialize step -var GSSAPIInitialize = function( - self, - MongoAuthProcess, - db, - username, - password, - authdb, - gssapiServiceName, - sendAuthCommand, - connection, - options, - callback -) { - // Create authenticator - var mongo_auth_process = new MongoAuthProcess( - connection.host, - connection.port, - gssapiServiceName, - options - ); - - // Perform initialization - mongo_auth_process.init(username, password, function(err) { - if (err) return callback(err, false); - - // Perform the first step - mongo_auth_process.transition('', function(err, payload) { - if (err) return callback(err, false); - - // Call the next db step - MongoDBGSSAPIFirstStep( - self, - mongo_auth_process, - payload, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback - ); - }); - }); -}; - -// -// Perform first step against mongodb -var MongoDBGSSAPIFirstStep = function( - self, - mongo_auth_process, - payload, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback -) { - // Build the sasl start command - var command = { - saslStart: 1, - mechanism: 'GSSAPI', - payload: payload, - autoAuthorize: 1 - }; - - // Write the commmand on the connection - sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => { - if (err) return callback(err, false); - // Execute mongodb transition - mongo_auth_process.transition(doc.payload, function(err, payload) { - if (err) return callback(err, false); - - // MongoDB API Second Step - MongoDBGSSAPISecondStep( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback - ); - }); - }); -}; - -// -// Perform first step against mongodb -var MongoDBGSSAPISecondStep = function( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback -) { - // Build Authentication command to send to MongoDB - var command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload: payload - }; - - // Execute the command - // Write the commmand on the connection - sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => { - if (err) return callback(err, false); - // Call next transition for kerberos - mongo_auth_process.transition(doc.payload, function(err, payload) { - if (err) return callback(err, false); - - // Call the last and third step - MongoDBGSSAPIThirdStep( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback - ); - }); - }); -}; - -var MongoDBGSSAPIThirdStep = function( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback -) { - // Build final command - var command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload: payload - }; - - // Execute the command - sendAuthCommand(connection, '$external.$cmd', command, (err, r) => { - if (err) return callback(err, false); - mongo_auth_process.transition(null, function(err) { - if (err) return callback(err, null); - callback(null, r); - }); - }); -}; - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = GSSAPI; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/mongo_credentials.js b/node_modules/mongoose/node_modules/mongodb/lib/core/auth/mongo_credentials.js deleted file mode 100644 index 13c00b1..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/mongo_credentials.js +++ /dev/null @@ -1,81 +0,0 @@ -'use strict'; - -// Resolves the default auth mechanism according to -// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst -function getDefaultAuthMechanism(ismaster) { - if (ismaster) { - // If ismaster contains saslSupportedMechs, use scram-sha-256 - // if it is available, else scram-sha-1 - if (Array.isArray(ismaster.saslSupportedMechs)) { - return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0 - ? 'scram-sha-256' - : 'scram-sha-1'; - } - - // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 - if (ismaster.maxWireVersion >= 3) { - return 'scram-sha-1'; - } - } - - // Default for wireprotocol < 3 - return 'mongocr'; -} - -/** - * A representation of the credentials used by MongoDB - * @class - * @property {string} mechanism The method used to authenticate - * @property {string} [username] The username used for authentication - * @property {string} [password] The password used for authentication - * @property {string} [source] The database that the user should authenticate against - * @property {object} [mechanismProperties] Special properties used by some types of auth mechanisms - */ -class MongoCredentials { - /** - * Creates a new MongoCredentials object - * @param {object} [options] - * @param {string} [options.username] The username used for authentication - * @param {string} [options.password] The password used for authentication - * @param {string} [options.source] The database that the user should authenticate against - * @param {string} [options.mechanism] The method used to authenticate - * @param {object} [options.mechanismProperties] Special properties used by some types of auth mechanisms - */ - constructor(options) { - options = options || {}; - this.username = options.username; - this.password = options.password; - this.source = options.source || options.db; - this.mechanism = options.mechanism || 'default'; - this.mechanismProperties = options.mechanismProperties; - } - - /** - * Determines if two MongoCredentials objects are equivalent - * @param {MongoCredentials} other another MongoCredentials object - * @returns {boolean} true if the two objects are equal. - */ - equals(other) { - return ( - this.mechanism === other.mechanism && - this.username === other.username && - this.password === other.password && - this.source === other.source - ); - } - - /** - * If the authentication mechanism is set to "default", resolves the authMechanism - * based on the server version and server supported sasl mechanisms. - * - * @param {Object} [ismaster] An ismaster response from the server - */ - resolveAuthMechanism(ismaster) { - // If the mechanism is not "default", then it does not need to be resolved - if (this.mechanism.toLowerCase() === 'default') { - this.mechanism = getDefaultAuthMechanism(ismaster); - } - } -} - -module.exports = { MongoCredentials }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/mongocr.js b/node_modules/mongoose/node_modules/mongodb/lib/core/auth/mongocr.js deleted file mode 100644 index be8fcb6..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/mongocr.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); -const AuthProvider = require('./auth_provider').AuthProvider; - -/** - * Creates a new MongoCR authentication mechanism - * - * @extends AuthProvider - */ -class MongoCR extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const username = credentials.username; - const password = credentials.password; - const source = credentials.source; - - sendAuthCommand(connection, `${source}.$cmd`, { getnonce: 1 }, (err, r) => { - let nonce = null; - let key = null; - - // Get nonce - if (err == null) { - nonce = r.nonce; - // Use node md5 generator - let md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password, 'utf8'); - const hash_password = md5.digest('hex'); - // Final key - md5 = crypto.createHash('md5'); - md5.update(nonce + username + hash_password, 'utf8'); - key = md5.digest('hex'); - } - - const authenticateCommand = { - authenticate: 1, - user: username, - nonce, - key - }; - - sendAuthCommand(connection, `${source}.$cmd`, authenticateCommand, callback); - }); - } -} - -module.exports = MongoCR; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/plain.js b/node_modules/mongoose/node_modules/mongodb/lib/core/auth/plain.js deleted file mode 100644 index 240de75..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/plain.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const retrieveBSON = require('../connection/utils').retrieveBSON; -const AuthProvider = require('./auth_provider').AuthProvider; - -// TODO: can we get the Binary type from this.bson instead? -const BSON = retrieveBSON(); -const Binary = BSON.Binary; - -/** - * Creates a new Plain authentication mechanism - * - * @extends AuthProvider - */ -class Plain extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const username = credentials.username; - const password = credentials.password; - const payload = new Binary(`\x00${username}\x00${password}`); - const command = { - saslStart: 1, - mechanism: 'PLAIN', - payload: payload, - autoAuthorize: 1 - }; - - sendAuthCommand(connection, '$external.$cmd', command, callback); - } -} - -module.exports = Plain; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/scram.js b/node_modules/mongoose/node_modules/mongodb/lib/core/auth/scram.js deleted file mode 100644 index 32fb4cd..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/scram.js +++ /dev/null @@ -1,329 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); -const Buffer = require('safe-buffer').Buffer; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const AuthProvider = require('./auth_provider').AuthProvider; - -const BSON = retrieveBSON(); -const Binary = BSON.Binary; - -let saslprep; -try { - saslprep = require('saslprep'); -} catch (e) { - // don't do anything; -} - -var parsePayload = function(payload) { - var dict = {}; - var parts = payload.split(','); - for (var i = 0; i < parts.length; i++) { - var valueParts = parts[i].split('='); - dict[valueParts[0]] = valueParts[1]; - } - - return dict; -}; - -var passwordDigest = function(username, password) { - if (typeof username !== 'string') throw new MongoError('username must be a string'); - if (typeof password !== 'string') throw new MongoError('password must be a string'); - if (password.length === 0) throw new MongoError('password cannot be empty'); - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password, 'utf8'); - return md5.digest('hex'); -}; - -// XOR two buffers -function xor(a, b) { - if (!Buffer.isBuffer(a)) a = Buffer.from(a); - if (!Buffer.isBuffer(b)) b = Buffer.from(b); - const length = Math.max(a.length, b.length); - const res = []; - - for (let i = 0; i < length; i += 1) { - res.push(a[i] ^ b[i]); - } - - return Buffer.from(res).toString('base64'); -} - -function H(method, text) { - return crypto - .createHash(method) - .update(text) - .digest(); -} - -function HMAC(method, key, text) { - return crypto - .createHmac(method, key) - .update(text) - .digest(); -} - -var _hiCache = {}; -var _hiCacheCount = 0; -var _hiCachePurge = function() { - _hiCache = {}; - _hiCacheCount = 0; -}; - -const hiLengthMap = { - sha256: 32, - sha1: 20 -}; - -function HI(data, salt, iterations, cryptoMethod) { - // omit the work if already generated - const key = [data, salt.toString('base64'), iterations].join('_'); - if (_hiCache[key] !== undefined) { - return _hiCache[key]; - } - - // generate the salt - const saltedData = crypto.pbkdf2Sync( - data, - salt, - iterations, - hiLengthMap[cryptoMethod], - cryptoMethod - ); - - // cache a copy to speed up the next lookup, but prevent unbounded cache growth - if (_hiCacheCount >= 200) { - _hiCachePurge(); - } - - _hiCache[key] = saltedData; - _hiCacheCount += 1; - return saltedData; -} - -function compareDigest(lhs, rhs) { - if (lhs.length !== rhs.length) { - return false; - } - - if (typeof crypto.timingSafeEqual === 'function') { - return crypto.timingSafeEqual(lhs, rhs); - } - - let result = 0; - for (let i = 0; i < lhs.length; i++) { - result |= lhs[i] ^ rhs[i]; - } - - return result === 0; -} - -/** - * Creates a new ScramSHA authentication mechanism - * @class - * @extends AuthProvider - */ -class ScramSHA extends AuthProvider { - constructor(bson, cryptoMethod) { - super(bson); - this.cryptoMethod = cryptoMethod || 'sha1'; - } - - static _getError(err, r) { - if (err) { - return err; - } - - if (r.$err || r.errmsg) { - return new MongoError(r); - } - } - - /** - * @ignore - */ - _executeScram(sendAuthCommand, connection, credentials, nonce, callback) { - let username = credentials.username; - const password = credentials.password; - const db = credentials.source; - - const cryptoMethod = this.cryptoMethod; - let mechanism = 'SCRAM-SHA-1'; - let processedPassword; - - if (cryptoMethod === 'sha256') { - mechanism = 'SCRAM-SHA-256'; - - processedPassword = saslprep ? saslprep(password) : password; - } else { - try { - processedPassword = passwordDigest(username, password); - } catch (e) { - return callback(e); - } - } - - // Clean up the user - username = username.replace('=', '=3D').replace(',', '=2C'); - - // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. - // Since the username is not sasl-prep-d, we need to do this here. - const firstBare = Buffer.concat([ - Buffer.from('n=', 'utf8'), - Buffer.from(username, 'utf8'), - Buffer.from(',r=', 'utf8'), - Buffer.from(nonce, 'utf8') - ]); - - // Build command structure - const saslStartCmd = { - saslStart: 1, - mechanism, - payload: new Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), firstBare])), - autoAuthorize: 1 - }; - - // Write the commmand on the connection - sendAuthCommand(connection, `${db}.$cmd`, saslStartCmd, (err, r) => { - let tmpError = ScramSHA._getError(err, r); - if (tmpError) { - return callback(tmpError, null); - } - - const payload = Buffer.isBuffer(r.payload) ? new Binary(r.payload) : r.payload; - const dict = parsePayload(payload.value()); - - const iterations = parseInt(dict.i, 10); - if (iterations && iterations < 4096) { - callback(new MongoError(`Server returned an invalid iteration count ${iterations}`), false); - return; - } - - const salt = dict.s; - const rnonce = dict.r; - if (rnonce.startsWith('nonce')) { - callback(new MongoError(`Server returned an invalid nonce: ${rnonce}`), false); - return; - } - - // Set up start of proof - const withoutProof = `c=biws,r=${rnonce}`; - const saltedPassword = HI( - processedPassword, - Buffer.from(salt, 'base64'), - iterations, - cryptoMethod - ); - - const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); - const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key'); - const storedKey = H(cryptoMethod, clientKey); - const authMessage = [firstBare, payload.value().toString('base64'), withoutProof].join(','); - - const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); - const clientProof = `p=${xor(clientKey, clientSignature)}`; - const clientFinal = [withoutProof, clientProof].join(','); - - const serverSignature = HMAC(cryptoMethod, serverKey, authMessage); - - const saslContinueCmd = { - saslContinue: 1, - conversationId: r.conversationId, - payload: new Binary(Buffer.from(clientFinal)) - }; - - sendAuthCommand(connection, `${db}.$cmd`, saslContinueCmd, (err, r) => { - if (err || (r && typeof r.ok === 'number' && r.ok === 0)) { - callback(err, r); - return; - } - - const parsedResponse = parsePayload(r.payload.value()); - if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) { - callback(new MongoError('Server returned an invalid signature')); - return; - } - - if (!r || r.done !== false) { - return callback(err, r); - } - - const retrySaslContinueCmd = { - saslContinue: 1, - conversationId: r.conversationId, - payload: Buffer.alloc(0) - }; - - sendAuthCommand(connection, `${db}.$cmd`, retrySaslContinueCmd, callback); - }); - }); - } - - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - // Create a random nonce - crypto.randomBytes(24, (err, buff) => { - if (err) { - return callback(err, null); - } - - return this._executeScram( - sendAuthCommand, - connection, - credentials, - buff.toString('base64'), - callback - ); - }); - } - - /** - * Authenticate - * @override - * @method - */ - auth(sendAuthCommand, connections, credentials, callback) { - this._checkSaslprep(); - super.auth(sendAuthCommand, connections, credentials, callback); - } - - _checkSaslprep() { - const cryptoMethod = this.cryptoMethod; - - if (cryptoMethod === 'sha256') { - if (!saslprep) { - console.warn('Warning: no saslprep library specified. Passwords will not be sanitized'); - } - } - } -} - -/** - * Creates a new ScramSHA1 authentication mechanism - * @class - * @extends ScramSHA - */ -class ScramSHA1 extends ScramSHA { - constructor(bson) { - super(bson, 'sha1'); - } -} - -/** - * Creates a new ScramSHA256 authentication mechanism - * @class - * @extends ScramSHA - */ -class ScramSHA256 extends ScramSHA { - constructor(bson) { - super(bson, 'sha256'); - } -} - -module.exports = { ScramSHA1, ScramSHA256 }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/sspi.js b/node_modules/mongoose/node_modules/mongodb/lib/core/auth/sspi.js deleted file mode 100644 index 8a3f544..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/sspi.js +++ /dev/null @@ -1,131 +0,0 @@ -'use strict'; - -const AuthProvider = require('./auth_provider').AuthProvider; -const retrieveKerberos = require('../utils').retrieveKerberos; -let kerberos; - -/** - * Creates a new SSPI authentication mechanism - * @class - * @extends AuthProvider - */ -class SSPI extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - // TODO: Destructure this - const username = credentials.username; - const password = credentials.password; - const mechanismProperties = credentials.mechanismProperties; - const gssapiServiceName = - mechanismProperties['gssapiservicename'] || - mechanismProperties['gssapiServiceName'] || - 'mongodb'; - - SSIPAuthenticate( - this, - kerberos.processes.MongoAuthProcess, - username, - password, - gssapiServiceName, - sendAuthCommand, - connection, - mechanismProperties, - callback - ); - } - - /** - * Authenticate - * @override - * @method - */ - auth(sendAuthCommand, connections, credentials, callback) { - if (kerberos == null) { - try { - kerberos = retrieveKerberos(); - } catch (e) { - return callback(e, null); - } - } - - super.auth(sendAuthCommand, connections, credentials, callback); - } -} - -function SSIPAuthenticate( - self, - MongoAuthProcess, - username, - password, - gssapiServiceName, - sendAuthCommand, - connection, - options, - callback -) { - const authProcess = new MongoAuthProcess( - connection.host, - connection.port, - gssapiServiceName, - options - ); - - function authCommand(command, authCb) { - sendAuthCommand(connection, '$external.$cmd', command, authCb); - } - - authProcess.init(username, password, err => { - if (err) return callback(err, false); - - authProcess.transition('', (err, payload) => { - if (err) return callback(err, false); - - const command = { - saslStart: 1, - mechanism: 'GSSAPI', - payload, - autoAuthorize: 1 - }; - - authCommand(command, (err, doc) => { - if (err) return callback(err, false); - - authProcess.transition(doc.payload, (err, payload) => { - if (err) return callback(err, false); - const command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload - }; - - authCommand(command, (err, doc) => { - if (err) return callback(err, false); - - authProcess.transition(doc.payload, (err, payload) => { - if (err) return callback(err, false); - const command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload - }; - - authCommand(command, (err, response) => { - if (err) return callback(err, false); - - authProcess.transition(null, err => { - if (err) return callback(err, null); - callback(null, response); - }); - }); - }); - }); - }); - }); - }); - }); -} - -module.exports = SSPI; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/x509.js b/node_modules/mongoose/node_modules/mongodb/lib/core/auth/x509.js deleted file mode 100644 index 10d5b58..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/auth/x509.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -const AuthProvider = require('./auth_provider').AuthProvider; - -/** - * Creates a new X509 authentication mechanism - * @class - * @extends AuthProvider - */ -class X509 extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const username = credentials.username; - const command = { authenticate: 1, mechanism: 'MONGODB-X509' }; - if (username) { - command.user = username; - } - - sendAuthCommand(connection, '$external.$cmd', command, callback); - } -} - -module.exports = X509; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/apm.js b/node_modules/mongoose/node_modules/mongodb/lib/core/connection/apm.js deleted file mode 100644 index 82858ef..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/apm.js +++ /dev/null @@ -1,251 +0,0 @@ -'use strict'; -const Msg = require('../connection/msg').Msg; -const KillCursor = require('../connection/commands').KillCursor; -const GetMore = require('../connection/commands').GetMore; -const calculateDurationInMs = require('../utils').calculateDurationInMs; - -/** Commands that we want to redact because of the sensitive nature of their contents */ -const SENSITIVE_COMMANDS = new Set([ - 'authenticate', - 'saslStart', - 'saslContinue', - 'getnonce', - 'createUser', - 'updateUser', - 'copydbgetnonce', - 'copydbsaslstart', - 'copydb' -]); - -// helper methods -const extractCommandName = commandDoc => Object.keys(commandDoc)[0]; -const namespace = command => command.ns; -const databaseName = command => command.ns.split('.')[0]; -const collectionName = command => command.ns.split('.')[1]; -const generateConnectionId = pool => - pool.options ? `${pool.options.host}:${pool.options.port}` : pool.address; -const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result); -const isLegacyPool = pool => pool.s && pool.queue; - -const LEGACY_FIND_QUERY_MAP = { - $query: 'filter', - $orderby: 'sort', - $hint: 'hint', - $comment: 'comment', - $maxScan: 'maxScan', - $max: 'max', - $min: 'min', - $returnKey: 'returnKey', - $showDiskLoc: 'showRecordId', - $maxTimeMS: 'maxTimeMS', - $snapshot: 'snapshot' -}; - -const LEGACY_FIND_OPTIONS_MAP = { - numberToSkip: 'skip', - numberToReturn: 'batchSize', - returnFieldsSelector: 'projection' -}; - -const OP_QUERY_KEYS = [ - 'tailable', - 'oplogReplay', - 'noCursorTimeout', - 'awaitData', - 'partial', - 'exhaust' -]; - -/** - * Extract the actual command from the query, possibly upconverting if it's a legacy - * format - * - * @param {Object} command the command - */ -const extractCommand = command => { - if (command instanceof GetMore) { - return { - getMore: command.cursorId, - collection: collectionName(command), - batchSize: command.numberToReturn - }; - } - - if (command instanceof KillCursor) { - return { - killCursors: collectionName(command), - cursors: command.cursorIds - }; - } - - if (command instanceof Msg) { - return command.command; - } - - if (command.query && command.query.$query) { - let result; - if (command.ns === 'admin.$cmd') { - // upconvert legacy command - result = Object.assign({}, command.query.$query); - } else { - // upconvert legacy find command - result = { find: collectionName(command) }; - Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { - if (typeof command.query[key] !== 'undefined') - result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key]; - }); - } - - Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { - if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key]; - }); - - OP_QUERY_KEYS.forEach(key => { - if (command[key]) result[key] = command[key]; - }); - - if (typeof command.pre32Limit !== 'undefined') { - result.limit = command.pre32Limit; - } - - if (command.query.$explain) { - return { explain: result }; - } - - return result; - } - - return command.query ? command.query : command; -}; - -const extractReply = (command, reply) => { - if (command instanceof GetMore) { - return { - ok: 1, - cursor: { - id: reply.message.cursorId, - ns: namespace(command), - nextBatch: reply.message.documents - } - }; - } - - if (command instanceof KillCursor) { - return { - ok: 1, - cursorsUnknown: command.cursorIds - }; - } - - // is this a legacy find command? - if (command.query && typeof command.query.$query !== 'undefined') { - return { - ok: 1, - cursor: { - id: reply.message.cursorId, - ns: namespace(command), - firstBatch: reply.message.documents - } - }; - } - - return reply && reply.result ? reply.result : reply; -}; - -const extractConnectionDetails = pool => { - if (isLegacyPool(pool)) { - return { - connectionId: generateConnectionId(pool) - }; - } - - // APM in the modern pool is done at the `Connection` level, so we rename it here for - // readability. - const connection = pool; - return { - address: connection.address, - connectionId: connection.id - }; -}; - -/** An event indicating the start of a given command */ -class CommandStartedEvent { - /** - * Create a started event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - */ - constructor(pool, command) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - const connectionDetails = extractConnectionDetails(pool); - - // NOTE: remove in major revision, this is not spec behavior - if (SENSITIVE_COMMANDS.has(commandName)) { - this.commandObj = {}; - this.commandObj[commandName] = true; - } - - Object.assign(this, connectionDetails, { - requestId: command.requestId, - databaseName: databaseName(command), - commandName, - command: cmd - }); - } -} - -/** An event indicating the success of a given command */ -class CommandSucceededEvent { - /** - * Create a succeeded event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - * @param {Object} reply the reply for this command from the server - * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration - */ - constructor(pool, command, reply, started) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - const connectionDetails = extractConnectionDetails(pool); - - Object.assign(this, connectionDetails, { - requestId: command.requestId, - commandName, - duration: calculateDurationInMs(started), - reply: maybeRedact(commandName, extractReply(command, reply)) - }); - } -} - -/** An event indicating the failure of a given command */ -class CommandFailedEvent { - /** - * Create a failure event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - * @param {MongoError|Object} error the generated error or a server error response - * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration - */ - constructor(pool, command, error, started) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - const connectionDetails = extractConnectionDetails(pool); - - Object.assign(this, connectionDetails, { - requestId: command.requestId, - commandName, - duration: calculateDurationInMs(started), - failure: maybeRedact(commandName, error) - }); - } -} - -module.exports = { - CommandStartedEvent, - CommandSucceededEvent, - CommandFailedEvent -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/command_result.js b/node_modules/mongoose/node_modules/mongodb/lib/core/connection/command_result.js deleted file mode 100644 index 762aa3f..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/command_result.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -/** - * Creates a new CommandResult instance - * @class - * @param {object} result CommandResult object - * @param {Connection} connection A connection instance associated with this result - * @return {CommandResult} A cursor instance - */ -var CommandResult = function(result, connection, message) { - this.result = result; - this.connection = connection; - this.message = message; -}; - -/** - * Convert CommandResult to JSON - * @method - * @return {object} - */ -CommandResult.prototype.toJSON = function() { - let result = Object.assign({}, this, this.result); - delete result.message; - return result; -}; - -/** - * Convert CommandResult to String representation - * @method - * @return {string} - */ -CommandResult.prototype.toString = function() { - return JSON.stringify(this.toJSON()); -}; - -module.exports = CommandResult; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/commands.js b/node_modules/mongoose/node_modules/mongodb/lib/core/connection/commands.js deleted file mode 100644 index b24ff84..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/commands.js +++ /dev/null @@ -1,507 +0,0 @@ -'use strict'; - -var retrieveBSON = require('./utils').retrieveBSON; -var BSON = retrieveBSON(); -var Long = BSON.Long; -const Buffer = require('safe-buffer').Buffer; - -// Incrementing request id -var _requestId = 0; - -// Wire command operation ids -var opcodes = require('../wireprotocol/shared').opcodes; - -// Query flags -var OPTS_TAILABLE_CURSOR = 2; -var OPTS_SLAVE = 4; -var OPTS_OPLOG_REPLAY = 8; -var OPTS_NO_CURSOR_TIMEOUT = 16; -var OPTS_AWAIT_DATA = 32; -var OPTS_EXHAUST = 64; -var OPTS_PARTIAL = 128; - -// Response flags -var CURSOR_NOT_FOUND = 1; -var QUERY_FAILURE = 2; -var SHARD_CONFIG_STALE = 4; -var AWAIT_CAPABLE = 8; - -/************************************************************** - * QUERY - **************************************************************/ -var Query = function(bson, ns, query, options) { - var self = this; - // Basic options needed to be passed in - if (ns == null) throw new Error('ns must be specified for query'); - if (query == null) throw new Error('query must be specified for query'); - - // Validate that we are not passing 0x00 in the collection name - if (ns.indexOf('\x00') !== -1) { - throw new Error('namespace cannot contain a null character'); - } - - // Basic options - this.bson = bson; - this.ns = ns; - this.query = query; - - // Additional options - this.numberToSkip = options.numberToSkip || 0; - this.numberToReturn = options.numberToReturn || 0; - this.returnFieldSelector = options.returnFieldSelector || null; - this.requestId = Query.getRequestId(); - - // special case for pre-3.2 find commands, delete ASAP - this.pre32Limit = options.pre32Limit; - - // Serialization option - this.serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; - this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true; - this.batchSize = self.numberToReturn; - - // Flags - this.tailable = false; - this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; - this.oplogReplay = false; - this.noCursorTimeout = false; - this.awaitData = false; - this.exhaust = false; - this.partial = false; -}; - -// -// Assign a new request Id -Query.prototype.incRequestId = function() { - this.requestId = _requestId++; -}; - -// -// Assign a new request Id -Query.nextRequestId = function() { - return _requestId + 1; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -Query.prototype.toBin = function() { - var self = this; - var buffers = []; - var projection = null; - - // Set up the flags - var flags = 0; - if (this.tailable) { - flags |= OPTS_TAILABLE_CURSOR; - } - - if (this.slaveOk) { - flags |= OPTS_SLAVE; - } - - if (this.oplogReplay) { - flags |= OPTS_OPLOG_REPLAY; - } - - if (this.noCursorTimeout) { - flags |= OPTS_NO_CURSOR_TIMEOUT; - } - - if (this.awaitData) { - flags |= OPTS_AWAIT_DATA; - } - - if (this.exhaust) { - flags |= OPTS_EXHAUST; - } - - if (this.partial) { - flags |= OPTS_PARTIAL; - } - - // If batchSize is different to self.numberToReturn - if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize; - - // Allocate write protocol header buffer - var header = Buffer.alloc( - 4 * 4 + // Header - 4 + // Flags - Buffer.byteLength(self.ns) + - 1 + // namespace - 4 + // numberToSkip - 4 // numberToReturn - ); - - // Add header to buffers - buffers.push(header); - - // Serialize the query - var query = self.bson.serialize(this.query, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - - // Add query document - buffers.push(query); - - if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { - // Serialize the projection document - projection = self.bson.serialize(this.returnFieldSelector, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - // Add projection document - buffers.push(projection); - } - - // Total message size - var totalLength = header.length + query.length + (projection ? projection.length : 0); - - // Set up the index - var index = 4; - - // Write total document length - header[3] = (totalLength >> 24) & 0xff; - header[2] = (totalLength >> 16) & 0xff; - header[1] = (totalLength >> 8) & 0xff; - header[0] = totalLength & 0xff; - - // Write header information requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = this.requestId & 0xff; - index = index + 4; - - // Write header information responseTo - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = 0 & 0xff; - index = index + 4; - - // Write header information OP_QUERY - header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff; - header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff; - header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff; - header[index] = opcodes.OP_QUERY & 0xff; - index = index + 4; - - // Write header information flags - header[index + 3] = (flags >> 24) & 0xff; - header[index + 2] = (flags >> 16) & 0xff; - header[index + 1] = (flags >> 8) & 0xff; - header[index] = flags & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Write header information flags numberToSkip - header[index + 3] = (this.numberToSkip >> 24) & 0xff; - header[index + 2] = (this.numberToSkip >> 16) & 0xff; - header[index + 1] = (this.numberToSkip >> 8) & 0xff; - header[index] = this.numberToSkip & 0xff; - index = index + 4; - - // Write header information flags numberToReturn - header[index + 3] = (this.numberToReturn >> 24) & 0xff; - header[index + 2] = (this.numberToReturn >> 16) & 0xff; - header[index + 1] = (this.numberToReturn >> 8) & 0xff; - header[index] = this.numberToReturn & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -}; - -Query.getRequestId = function() { - return ++_requestId; -}; - -/************************************************************** - * GETMORE - **************************************************************/ -var GetMore = function(bson, ns, cursorId, opts) { - opts = opts || {}; - this.numberToReturn = opts.numberToReturn || 0; - this.requestId = _requestId++; - this.bson = bson; - this.ns = ns; - this.cursorId = cursorId; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -GetMore.prototype.toBin = function() { - var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; - // Create command buffer - var index = 0; - // Allocate buffer - var _buffer = Buffer.alloc(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = length & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = this.requestId & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_GETMORE); - _buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff; - _buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff; - _buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff; - _buffer[index] = opcodes.OP_GETMORE & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // Write collection name - index = index + _buffer.write(this.ns, index, 'utf8') + 1; - _buffer[index - 1] = 0; - - // Write batch size - // index = write32bit(index, _buffer, numberToReturn); - _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; - _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; - _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; - _buffer[index] = this.numberToReturn & 0xff; - index = index + 4; - - // Write cursor id - // index = write32bit(index, _buffer, cursorId.getLowBits()); - _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; - _buffer[index] = this.cursorId.getLowBits() & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorId.getHighBits()); - _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; - _buffer[index] = this.cursorId.getHighBits() & 0xff; - index = index + 4; - - // Return buffer - return _buffer; -}; - -/************************************************************** - * KILLCURSOR - **************************************************************/ -var KillCursor = function(bson, ns, cursorIds) { - this.ns = ns; - this.requestId = _requestId++; - this.cursorIds = cursorIds; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -KillCursor.prototype.toBin = function() { - var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; - - // Create command buffer - var index = 0; - var _buffer = Buffer.alloc(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = length & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = this.requestId & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_KILL_CURSORS); - _buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff; - _buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff; - _buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff; - _buffer[index] = opcodes.OP_KILL_CURSORS & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // Write batch size - // index = write32bit(index, _buffer, this.cursorIds.length); - _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; - _buffer[index] = this.cursorIds.length & 0xff; - index = index + 4; - - // Write all the cursor ids into the array - for (var i = 0; i < this.cursorIds.length; i++) { - // Write cursor id - // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); - _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; - _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); - _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; - _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; - index = index + 4; - } - - // Return buffer - return _buffer; -}; - -var Response = function(bson, message, msgHeader, msgBody, opts) { - opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; - this.parsed = false; - this.raw = message; - this.data = msgBody; - this.bson = bson; - this.opts = opts; - - // Read the message header - this.length = msgHeader.length; - this.requestId = msgHeader.requestId; - this.responseTo = msgHeader.responseTo; - this.opCode = msgHeader.opCode; - this.fromCompressed = msgHeader.fromCompressed; - - // Read the message body - this.responseFlags = msgBody.readInt32LE(0); - this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); - this.startingFrom = msgBody.readInt32LE(12); - this.numberReturned = msgBody.readInt32LE(16); - - // Preallocate document array - this.documents = new Array(this.numberReturned); - - // Flag values - this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; - this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; - this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; - this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; - this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; - this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; - this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; -}; - -Response.prototype.isParsed = function() { - return this.parsed; -}; - -Response.prototype.parse = function(options) { - // Don't parse again if not needed - if (this.parsed) return; - options = options || {}; - - // Allow the return of raw documents instead of parsing - var raw = options.raw || false; - var documentsReturnedIn = options.documentsReturnedIn || null; - var promoteLongs = - typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; - var promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; - var promoteBuffers = - typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers; - var bsonSize, _options; - - // Set up the options - _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers - }; - - // Position within OP_REPLY at which documents start - // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) - this.index = 20; - - // - // Parse Body - // - for (var i = 0; i < this.numberReturned; i++) { - bsonSize = - this.data[this.index] | - (this.data[this.index + 1] << 8) | - (this.data[this.index + 2] << 16) | - (this.data[this.index + 3] << 24); - - // If we have raw results specified slice the return document - if (raw) { - this.documents[i] = this.data.slice(this.index, this.index + bsonSize); - } else { - this.documents[i] = this.bson.deserialize( - this.data.slice(this.index, this.index + bsonSize), - _options - ); - } - - // Adjust the index - this.index = this.index + bsonSize; - } - - if (this.documents.length === 1 && documentsReturnedIn != null && raw) { - const fieldsAsRaw = {}; - fieldsAsRaw[documentsReturnedIn] = true; - _options.fieldsAsRaw = fieldsAsRaw; - - const doc = this.bson.deserialize(this.documents[0], _options); - this.documents = [doc]; - } - - // Set parsed - this.parsed = true; -}; - -module.exports = { - Query: Query, - GetMore: GetMore, - Response: Response, - KillCursor: KillCursor -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js b/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js deleted file mode 100644 index b096e21..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connect.js +++ /dev/null @@ -1,416 +0,0 @@ -'use strict'; -const net = require('net'); -const tls = require('tls'); -const Connection = require('./connection'); -const Query = require('./commands').Query; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; -const WIRE_CONSTANTS = require('../wireprotocol/constants'); -const makeClientMetadata = require('../utils').makeClientMetadata; -const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; -const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; -const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; -const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; -let AUTH_PROVIDERS; - -function connect(options, cancellationToken, callback) { - if (typeof cancellationToken === 'function') { - callback = cancellationToken; - cancellationToken = undefined; - } - - const ConnectionType = options && options.connectionType ? options.connectionType : Connection; - if (AUTH_PROVIDERS == null) { - AUTH_PROVIDERS = defaultAuthProviders(options.bson); - } - - const family = options.family !== void 0 ? options.family : 0; - makeConnection(family, options, cancellationToken, (err, socket) => { - if (err) { - callback(err, socket); // in the error case, `socket` is the originating error event name - return; - } - - performInitialHandshake(new ConnectionType(socket, options), options, callback); - }); -} - -function isModernConnectionType(conn) { - return typeof conn.command === 'function'; -} - -function getSaslSupportedMechs(options) { - if (!(options && options.credentials)) { - return {}; - } - - const credentials = options.credentials; - - // TODO: revisit whether or not items like `options.user` and `options.dbName` should be checked here - const authMechanism = credentials.mechanism; - const authSource = credentials.source || options.dbName || 'admin'; - const user = credentials.username || options.user; - - if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') { - return {}; - } - - if (!user) { - return {}; - } - - return { saslSupportedMechs: `${authSource}.${user}` }; -} - -function checkSupportedServer(ismaster, options) { - const serverVersionHighEnough = - ismaster && - typeof ismaster.maxWireVersion === 'number' && - ismaster.maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION; - const serverVersionLowEnough = - ismaster && - typeof ismaster.minWireVersion === 'number' && - ismaster.minWireVersion <= MAX_SUPPORTED_WIRE_VERSION; - - if (serverVersionHighEnough) { - if (serverVersionLowEnough) { - return null; - } - - const message = `Server at ${options.host}:${options.port} reports minimum wire version ${ismaster.minWireVersion}, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; - return new MongoError(message); - } - - const message = `Server at ${options.host}:${ - options.port - } reports maximum wire version ${ismaster.maxWireVersion || - 0}, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`; - return new MongoError(message); -} - -function performInitialHandshake(conn, options, _callback) { - const callback = function(err, ret) { - if (err && conn) { - conn.destroy(); - } - _callback(err, ret); - }; - - let compressors = []; - if (options.compression && options.compression.compressors) { - compressors = options.compression.compressors; - } - - const handshakeDoc = Object.assign( - { - ismaster: true, - client: options.metadata || makeClientMetadata(options), - compression: compressors - }, - getSaslSupportedMechs(options) - ); - - const handshakeOptions = Object.assign({}, options); - - // The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS - if (options.connectTimeoutMS || options.connectionTimeout) { - handshakeOptions.socketTimeout = options.connectTimeoutMS || options.connectionTimeout; - } - - const start = new Date().getTime(); - runCommand(conn, 'admin.$cmd', handshakeDoc, handshakeOptions, (err, ismaster) => { - if (err) { - callback(err); - return; - } - - if (ismaster.ok === 0) { - callback(new MongoError(ismaster)); - return; - } - - const supportedServerErr = checkSupportedServer(ismaster, options); - if (supportedServerErr) { - callback(supportedServerErr); - return; - } - - if (!isModernConnectionType(conn)) { - // resolve compression - if (ismaster.compression) { - const agreedCompressors = compressors.filter( - compressor => ismaster.compression.indexOf(compressor) !== -1 - ); - - if (agreedCompressors.length) { - conn.agreedCompressor = agreedCompressors[0]; - } - - if (options.compression && options.compression.zlibCompressionLevel) { - conn.zlibCompressionLevel = options.compression.zlibCompressionLevel; - } - } - } - - // NOTE: This is metadata attached to the connection while porting away from - // handshake being done in the `Server` class. Likely, it should be - // relocated, or at very least restructured. - conn.ismaster = ismaster; - conn.lastIsMasterMS = new Date().getTime() - start; - - const credentials = options.credentials; - if (!ismaster.arbiterOnly && credentials) { - credentials.resolveAuthMechanism(ismaster); - authenticate(conn, credentials, callback); - return; - } - - callback(undefined, conn); - }); -} - -const LEGAL_SSL_SOCKET_OPTIONS = [ - 'pfx', - 'key', - 'passphrase', - 'cert', - 'ca', - 'ciphers', - 'NPNProtocols', - 'ALPNProtocols', - 'servername', - 'ecdhCurve', - 'secureProtocol', - 'secureContext', - 'session', - 'minDHSize', - 'crl', - 'rejectUnauthorized' -]; - -function parseConnectOptions(family, options) { - const host = typeof options.host === 'string' ? options.host : 'localhost'; - if (host.indexOf('/') !== -1) { - return { path: host }; - } - - const result = { - family, - host, - port: typeof options.port === 'number' ? options.port : 27017, - rejectUnauthorized: false - }; - - return result; -} - -function parseSslOptions(family, options) { - const result = parseConnectOptions(family, options); - - // Merge in valid SSL options - for (const name in options) { - if (options[name] != null && LEGAL_SSL_SOCKET_OPTIONS.indexOf(name) !== -1) { - result[name] = options[name]; - } - } - - // Override checkServerIdentity behavior - if (options.checkServerIdentity === false) { - // Skip the identiy check by retuning undefined as per node documents - // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback - result.checkServerIdentity = function() { - return undefined; - }; - } else if (typeof options.checkServerIdentity === 'function') { - result.checkServerIdentity = options.checkServerIdentity; - } - - // Set default sni servername to be the same as host - if (result.servername == null) { - result.servername = result.host; - } - - return result; -} - -const SOCKET_ERROR_EVENTS = new Set(['error', 'close', 'timeout', 'parseError']); -function makeConnection(family, options, cancellationToken, _callback) { - const useSsl = typeof options.ssl === 'boolean' ? options.ssl : false; - const keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; - let keepAliveInitialDelay = - typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; - const noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true; - const connectionTimeout = - typeof options.connectionTimeout === 'number' - ? options.connectionTimeout - : typeof options.connectTimeoutMS === 'number' - ? options.connectTimeoutMS - : 30000; - const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - const rejectUnauthorized = - typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true; - - if (keepAliveInitialDelay > socketTimeout) { - keepAliveInitialDelay = Math.round(socketTimeout / 2); - } - - let socket; - const callback = function(err, ret) { - if (err && socket) { - socket.destroy(); - } - - _callback(err, ret); - }; - - try { - if (useSsl) { - socket = tls.connect(parseSslOptions(family, options)); - if (typeof socket.disableRenegotiation === 'function') { - socket.disableRenegotiation(); - } - } else { - socket = net.createConnection(parseConnectOptions(family, options)); - } - } catch (err) { - return callback(err); - } - - socket.setKeepAlive(keepAlive, keepAliveInitialDelay); - socket.setTimeout(connectionTimeout); - socket.setNoDelay(noDelay); - - const connectEvent = useSsl ? 'secureConnect' : 'connect'; - let cancellationHandler; - function errorHandler(eventName) { - return err => { - SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); - if (cancellationHandler) { - cancellationToken.removeListener('cancel', cancellationHandler); - } - - socket.removeListener(connectEvent, connectHandler); - callback(connectionFailureError(eventName, err)); - }; - } - - function connectHandler() { - SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event)); - if (cancellationHandler) { - cancellationToken.removeListener('cancel', cancellationHandler); - } - - if (socket.authorizationError && rejectUnauthorized) { - return callback(socket.authorizationError); - } - - socket.setTimeout(socketTimeout); - callback(null, socket); - } - - SOCKET_ERROR_EVENTS.forEach(event => socket.once(event, errorHandler(event))); - if (cancellationToken) { - cancellationHandler = errorHandler('cancel'); - cancellationToken.once('cancel', cancellationHandler); - } - - socket.once(connectEvent, connectHandler); -} - -const CONNECTION_ERROR_EVENTS = ['error', 'close', 'timeout', 'parseError']; -function runCommand(conn, ns, command, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - - // are we using the new connection type? if so, no need to simulate a rpc `command` method - if (isModernConnectionType(conn)) { - conn.command(ns, command, options, (err, result) => { - if (err) { - callback(err); - return; - } - - // NODE-2382: raw wire protocol messages, or command results should not be used anymore - callback(undefined, result.result); - }); - - return; - } - - const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - const bson = conn.options.bson; - const query = new Query(bson, ns, command, { - numberToSkip: 0, - numberToReturn: 1 - }); - - const noop = () => {}; - function _callback(err, result) { - callback(err, result); - callback = noop; - } - - function errorHandler(err) { - conn.resetSocketTimeout(); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); - conn.removeListener('message', messageHandler); - - if (err == null) { - err = new MongoError(`runCommand failed for connection to '${conn.address}'`); - } - - // ignore all future errors - conn.on('error', noop); - - _callback(err); - } - - function messageHandler(msg) { - if (msg.responseTo !== query.requestId) { - return; - } - - conn.resetSocketTimeout(); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); - conn.removeListener('message', messageHandler); - - msg.parse({ promoteValues: true }); - _callback(undefined, msg.documents[0]); - } - - conn.setSocketTimeout(socketTimeout); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.once(eventName, errorHandler)); - conn.on('message', messageHandler); - conn.write(query.toBin()); -} - -function authenticate(conn, credentials, callback) { - const mechanism = credentials.mechanism; - if (!AUTH_PROVIDERS[mechanism]) { - callback(new MongoError(`authMechanism '${mechanism}' not supported`)); - return; - } - - const provider = AUTH_PROVIDERS[mechanism]; - provider.auth(runCommand, [conn], credentials, err => { - if (err) return callback(err); - callback(undefined, conn); - }); -} - -function connectionFailureError(type, err) { - switch (type) { - case 'error': - return new MongoNetworkError(err); - case 'timeout': - return new MongoNetworkError(`connection timed out`); - case 'close': - return new MongoNetworkError(`connection closed`); - case 'cancel': - return new MongoNetworkError(`connection establishment was cancelled`); - default: - return new MongoNetworkError(`unknown network error`); - } -} - -module.exports = connect; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connection.js b/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connection.js deleted file mode 100644 index c1c5a3b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/connection.js +++ /dev/null @@ -1,644 +0,0 @@ -'use strict'; - -const EventEmitter = require('events').EventEmitter; -const crypto = require('crypto'); -const debugOptions = require('./utils').debugOptions; -const parseHeader = require('../wireprotocol/shared').parseHeader; -const decompress = require('../wireprotocol/compression').decompress; -const Response = require('./commands').Response; -const BinMsg = require('./msg').BinMsg; -const MongoNetworkError = require('../error').MongoNetworkError; -const MongoError = require('../error').MongoError; -const Logger = require('./logger'); -const OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED; -const OP_MSG = require('../wireprotocol/shared').opcodes.OP_MSG; -const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; -const Buffer = require('safe-buffer').Buffer; - -let _id = 0; - -const DEFAULT_MAX_BSON_MESSAGE_SIZE = 1024 * 1024 * 16 * 4; -const DEBUG_FIELDS = [ - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'checkServerIdentity' -]; - -let connectionAccountingSpy = undefined; -let connectionAccounting = false; -let connections = {}; - -/** - * A class representing a single connection to a MongoDB server - * - * @fires Connection#connect - * @fires Connection#close - * @fires Connection#error - * @fires Connection#timeout - * @fires Connection#parseError - * @fires Connection#message - */ -class Connection extends EventEmitter { - /** - * Creates a new Connection instance - * - * **NOTE**: Internal class, do not instantiate directly - * - * @param {Socket} socket The socket this connection wraps - * @param {Object} options Various settings - * @param {object} options.bson An implementation of bson serialize and deserialize - * @param {string} [options.host='localhost'] The host the socket is connected to - * @param {number} [options.port=27017] The port used for the socket connection - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {boolean} [options.promoteLongs] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers] Promotes Binary BSON values to native Node Buffers. - * @param {number} [options.maxBsonMessageSize=0x4000000] Largest possible size of a BSON message (for legacy purposes) - */ - constructor(socket, options) { - super(); - - options = options || {}; - if (!options.bson) { - throw new TypeError('must pass in valid bson parser'); - } - - this.id = _id++; - this.options = options; - this.logger = Logger('Connection', options); - this.bson = options.bson; - this.tag = options.tag; - this.maxBsonMessageSize = options.maxBsonMessageSize || DEFAULT_MAX_BSON_MESSAGE_SIZE; - - this.port = options.port || 27017; - this.host = options.host || 'localhost'; - this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - - // These values are inspected directly in tests, but maybe not necessary to keep around - this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; - this.keepAliveInitialDelay = - typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; - this.connectionTimeout = - typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; - if (this.keepAliveInitialDelay > this.socketTimeout) { - this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2); - } - - // Debug information - if (this.logger.isDebug()) { - this.logger.debug( - `creating connection ${this.id} with options [${JSON.stringify( - debugOptions(DEBUG_FIELDS, options) - )}]` - ); - } - - // Response options - this.responseOptions = { - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false - }; - - // Flushing - this.flushing = false; - this.queue = []; - - // Internal state - this.writeStream = null; - this.destroyed = false; - this.timedOut = false; - - // Create hash method - const hash = crypto.createHash('sha1'); - hash.update(this.address); - this.hashedName = hash.digest('hex'); - - // All operations in flight on the connection - this.workItems = []; - - // setup socket - this.socket = socket; - this.socket.once('error', errorHandler(this)); - this.socket.once('timeout', timeoutHandler(this)); - this.socket.once('close', closeHandler(this)); - this.socket.on('data', dataHandler(this)); - - if (connectionAccounting) { - addConnection(this.id, this); - } - } - - setSocketTimeout(value) { - if (this.socket) { - this.socket.setTimeout(value); - } - } - - resetSocketTimeout() { - if (this.socket) { - this.socket.setTimeout(this.socketTimeout); - } - } - - static enableConnectionAccounting(spy) { - if (spy) { - connectionAccountingSpy = spy; - } - - connectionAccounting = true; - connections = {}; - } - - static disableConnectionAccounting() { - connectionAccounting = false; - connectionAccountingSpy = undefined; - } - - static connections() { - return connections; - } - - get address() { - return `${this.host}:${this.port}`; - } - - /** - * Unref this connection - * @method - * @return {boolean} - */ - unref() { - if (this.socket == null) { - this.once('connect', () => this.socket.unref()); - return; - } - - this.socket.unref(); - } - - /** - * Flush all work Items on this connection - * - * @param {*} err The error to propagate to the flushed work items - */ - flush(err) { - while (this.workItems.length > 0) { - const workItem = this.workItems.shift(); - if (workItem.cb) { - workItem.cb(err); - } - } - } - - /** - * Destroy connection - * @method - */ - destroy(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = Object.assign({ force: false }, options); - - if (connectionAccounting) { - deleteConnection(this.id); - } - - if (this.socket == null) { - this.destroyed = true; - return; - } - - if (options.force || this.timedOut) { - this.socket.destroy(); - this.destroyed = true; - if (typeof callback === 'function') callback(null, null); - return; - } - - this.socket.end(err => { - this.destroyed = true; - if (typeof callback === 'function') callback(err, null); - }); - } - - /** - * Write to connection - * @method - * @param {Command} command Command to write out need to implement toBin and toBinUnified - */ - write(buffer) { - // Debug Log - if (this.logger.isDebug()) { - if (!Array.isArray(buffer)) { - this.logger.debug(`writing buffer [${buffer.toString('hex')}] to ${this.address}`); - } else { - for (let i = 0; i < buffer.length; i++) - this.logger.debug(`writing buffer [${buffer[i].toString('hex')}] to ${this.address}`); - } - } - - // Double check that the connection is not destroyed - if (this.socket.destroyed === false) { - // Write out the command - if (!Array.isArray(buffer)) { - this.socket.write(buffer, 'binary'); - return true; - } - - // Iterate over all buffers and write them in order to the socket - for (let i = 0; i < buffer.length; i++) { - this.socket.write(buffer[i], 'binary'); - } - - return true; - } - - // Connection is destroyed return write failed - return false; - } - - /** - * Return id of connection as a string - * @method - * @return {string} - */ - toString() { - return '' + this.id; - } - - /** - * Return json object of connection - * @method - * @return {object} - */ - toJSON() { - return { id: this.id, host: this.host, port: this.port }; - } - - /** - * Is the connection connected - * @method - * @return {boolean} - */ - isConnected() { - if (this.destroyed) return false; - return !this.socket.destroyed && this.socket.writable; - } -} - -function deleteConnection(id) { - // console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : '')) - delete connections[id]; - - if (connectionAccountingSpy) { - connectionAccountingSpy.deleteConnection(id); - } -} - -function addConnection(id, connection) { - // console.log("=== added connection " + id + " :: " + connection.port) - connections[id] = connection; - - if (connectionAccountingSpy) { - connectionAccountingSpy.addConnection(id, connection); - } -} - -// -// Connection handlers -function errorHandler(conn) { - return function(err) { - if (connectionAccounting) deleteConnection(conn.id); - // Debug information - if (conn.logger.isDebug()) { - conn.logger.debug( - `connection ${conn.id} for [${conn.address}] errored out with [${JSON.stringify(err)}]` - ); - } - - conn.emit('error', new MongoNetworkError(err), conn); - }; -} - -function timeoutHandler(conn) { - return function() { - if (connectionAccounting) deleteConnection(conn.id); - - if (conn.logger.isDebug()) { - conn.logger.debug(`connection ${conn.id} for [${conn.address}] timed out`); - } - - conn.timedOut = true; - conn.emit( - 'timeout', - new MongoNetworkError(`connection ${conn.id} to ${conn.address} timed out`), - conn - ); - }; -} - -function closeHandler(conn) { - return function(hadError) { - if (connectionAccounting) deleteConnection(conn.id); - - if (conn.logger.isDebug()) { - conn.logger.debug(`connection ${conn.id} with for [${conn.address}] closed`); - } - - if (!hadError) { - conn.emit( - 'close', - new MongoNetworkError(`connection ${conn.id} to ${conn.address} closed`), - conn - ); - } - }; -} - -// Handle a message once it is received -function processMessage(conn, message) { - const msgHeader = parseHeader(message); - if (msgHeader.opCode !== OP_COMPRESSED) { - const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; - conn.emit( - 'message', - new ResponseConstructor( - conn.bson, - message, - msgHeader, - message.slice(MESSAGE_HEADER_SIZE), - conn.responseOptions - ), - conn - ); - - return; - } - - msgHeader.fromCompressed = true; - let index = MESSAGE_HEADER_SIZE; - msgHeader.opCode = message.readInt32LE(index); - index += 4; - msgHeader.length = message.readInt32LE(index); - index += 4; - const compressorID = message[index]; - index++; - - decompress(compressorID, message.slice(index), (err, decompressedMsgBody) => { - if (err) { - conn.emit('error', err); - return; - } - - if (decompressedMsgBody.length !== msgHeader.length) { - conn.emit( - 'error', - new MongoError( - 'Decompressing a compressed message from the server failed. The message is corrupt.' - ) - ); - - return; - } - - const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; - conn.emit( - 'message', - new ResponseConstructor( - conn.bson, - message, - msgHeader, - decompressedMsgBody, - conn.responseOptions - ), - conn - ); - }); -} - -function dataHandler(conn) { - return function(data) { - // Parse until we are done with the data - while (data.length > 0) { - // If we still have bytes to read on the current message - if (conn.bytesRead > 0 && conn.sizeOfMessage > 0) { - // Calculate the amount of remaining bytes - const remainingBytesToRead = conn.sizeOfMessage - conn.bytesRead; - // Check if the current chunk contains the rest of the message - if (remainingBytesToRead > data.length) { - // Copy the new data into the exiting buffer (should have been allocated when we know the message size) - data.copy(conn.buffer, conn.bytesRead); - // Adjust the number of bytes read so it point to the correct index in the buffer - conn.bytesRead = conn.bytesRead + data.length; - - // Reset state of buffer - data = Buffer.alloc(0); - } else { - // Copy the missing part of the data into our current buffer - data.copy(conn.buffer, conn.bytesRead, 0, remainingBytesToRead); - // Slice the overflow into a new buffer that we will then re-parse - data = data.slice(remainingBytesToRead); - - // Emit current complete message - const emitBuffer = conn.buffer; - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - - processMessage(conn, emitBuffer); - } - } else { - // Stub buffer is kept in case we don't get enough bytes to determine the - // size of the message (< 4 bytes) - if (conn.stubBuffer != null && conn.stubBuffer.length > 0) { - // If we have enough bytes to determine the message size let's do it - if (conn.stubBuffer.length + data.length > 4) { - // Prepad the data - const newData = Buffer.alloc(conn.stubBuffer.length + data.length); - conn.stubBuffer.copy(newData, 0); - data.copy(newData, conn.stubBuffer.length); - // Reassign for parsing - data = newData; - - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - } else { - // Add the the bytes to the stub buffer - const newStubBuffer = Buffer.alloc(conn.stubBuffer.length + data.length); - // Copy existing stub buffer - conn.stubBuffer.copy(newStubBuffer, 0); - // Copy missing part of the data - data.copy(newStubBuffer, conn.stubBuffer.length); - // Exit parsing loop - data = Buffer.alloc(0); - } - } else { - if (data.length > 4) { - // Retrieve the message size - const sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); - // If we have a negative sizeOfMessage emit error and return - if (sizeOfMessage < 0 || sizeOfMessage > conn.maxBsonMessageSize) { - const errorObject = { - err: 'socketHandler', - trace: '', - bin: conn.buffer, - parseState: { - sizeOfMessage: sizeOfMessage, - bytesRead: conn.bytesRead, - stubBuffer: conn.stubBuffer - } - }; - // We got a parse Error fire it off then keep going - conn.emit('parseError', errorObject, conn); - return; - } - - // Ensure that the size of message is larger than 0 and less than the max allowed - if ( - sizeOfMessage > 4 && - sizeOfMessage < conn.maxBsonMessageSize && - sizeOfMessage > data.length - ) { - conn.buffer = Buffer.alloc(sizeOfMessage); - // Copy all the data into the buffer - data.copy(conn.buffer, 0); - // Update bytes read - conn.bytesRead = data.length; - // Update sizeOfMessage - conn.sizeOfMessage = sizeOfMessage; - // Ensure stub buffer is null - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - } else if ( - sizeOfMessage > 4 && - sizeOfMessage < conn.maxBsonMessageSize && - sizeOfMessage === data.length - ) { - const emitBuffer = data; - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - // Emit the message - processMessage(conn, emitBuffer); - } else if (sizeOfMessage <= 4 || sizeOfMessage > conn.maxBsonMessageSize) { - const errorObject = { - err: 'socketHandler', - trace: null, - bin: data, - parseState: { - sizeOfMessage: sizeOfMessage, - bytesRead: 0, - buffer: null, - stubBuffer: null - } - }; - // We got a parse Error fire it off then keep going - conn.emit('parseError', errorObject, conn); - - // Clear out the state of the parser - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - } else { - const emitBuffer = data.slice(0, sizeOfMessage); - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Copy rest of message - data = data.slice(sizeOfMessage); - // Emit the message - processMessage(conn, emitBuffer); - } - } else { - // Create a buffer that contains the space for the non-complete message - conn.stubBuffer = Buffer.alloc(data.length); - // Copy the data to the stub buffer - data.copy(conn.stubBuffer, 0); - // Exit parsing loop - data = Buffer.alloc(0); - } - } - } - } - }; -} - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Connection#connect - * @type {Connection} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Connection#close - * @type {Connection} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Connection#error - * @type {Connection} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Connection#timeout - * @type {Connection} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Connection#parseError - * @type {Connection} - */ - -/** - * An event emitted each time the connection receives a parsed message from the wire - * - * @event Connection#message - * @type {Connection} - */ - -module.exports = Connection; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/logger.js b/node_modules/mongoose/node_modules/mongodb/lib/core/connection/logger.js deleted file mode 100644 index 3b0be90..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/logger.js +++ /dev/null @@ -1,251 +0,0 @@ -'use strict'; - -var f = require('util').format, - MongoError = require('../error').MongoError; - -// Filters for classes -var classFilters = {}; -var filteredClasses = {}; -var level = null; -// Save the process id -var pid = process.pid; -// current logger -var currentLogger = null; - -/** - * @callback Logger~loggerCallback - * @param {string} msg message being logged - * @param {object} state an object containing more metadata about the logging message - */ - -/** - * Creates a new Logger instance - * @class - * @param {string} className The Class name associated with the logging instance - * @param {object} [options=null] Optional settings. - * @param {Logger~loggerCallback} [options.logger=null] Custom logger function; - * @param {string} [options.loggerLevel=error] Override default global log level. - */ -var Logger = function(className, options) { - if (!(this instanceof Logger)) return new Logger(className, options); - options = options || {}; - - // Current reference - this.className = className; - - // Current logger - if (options.logger) { - currentLogger = options.logger; - } else if (currentLogger == null) { - currentLogger = console.log; - } - - // Set level of logging, default is error - if (options.loggerLevel) { - level = options.loggerLevel || 'error'; - } - - // Add all class names - if (filteredClasses[this.className] == null) classFilters[this.className] = true; -}; - -/** - * Log a message at the debug level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.debug = function(message, object) { - if ( - this.isDebug() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); - var state = { - type: 'debug', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } -}; - -/** - * Log a message at the warn level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -(Logger.prototype.warn = function(message, object) { - if ( - this.isWarn() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); - var state = { - type: 'warn', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } -}), - /** - * Log a message at the info level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ - (Logger.prototype.info = function(message, object) { - if ( - this.isInfo() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); - var state = { - type: 'info', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } - }), - /** - * Log a message at the error level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ - (Logger.prototype.error = function(message, object) { - if ( - this.isError() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); - var state = { - type: 'error', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } - }), - /** - * Is the logger set at info level - * @method - * @return {boolean} - */ - (Logger.prototype.isInfo = function() { - return level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at error level - * @method - * @return {boolean} - */ - (Logger.prototype.isError = function() { - return level === 'error' || level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at error level - * @method - * @return {boolean} - */ - (Logger.prototype.isWarn = function() { - return level === 'error' || level === 'warn' || level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at debug level - * @method - * @return {boolean} - */ - (Logger.prototype.isDebug = function() { - return level === 'debug'; - }); - -/** - * Resets the logger to default settings, error and no filtered classes - * @method - * @return {null} - */ -Logger.reset = function() { - level = 'error'; - filteredClasses = {}; -}; - -/** - * Get the current logger function - * @method - * @return {Logger~loggerCallback} - */ -Logger.currentLogger = function() { - return currentLogger; -}; - -/** - * Set the current logger function - * @method - * @param {Logger~loggerCallback} logger Logger function. - * @return {null} - */ -Logger.setCurrentLogger = function(logger) { - if (typeof logger !== 'function') throw new MongoError('current logger must be a function'); - currentLogger = logger; -}; - -/** - * Set what classes to log. - * @method - * @param {string} type The type of filter (currently only class) - * @param {string[]} values The filters to apply - * @return {null} - */ -Logger.filter = function(type, values) { - if (type === 'class' && Array.isArray(values)) { - filteredClasses = {}; - - values.forEach(function(x) { - filteredClasses[x] = true; - }); - } -}; - -/** - * Set the current log level - * @method - * @param {string} level Set current log level (debug, info, error) - * @return {null} - */ -Logger.setLevel = function(_level) { - if (_level !== 'info' && _level !== 'error' && _level !== 'debug' && _level !== 'warn') { - throw new Error(f('%s is an illegal logging level', _level)); - } - - level = _level; -}; - -module.exports = Logger; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/msg.js b/node_modules/mongoose/node_modules/mongodb/lib/core/connection/msg.js deleted file mode 100644 index 9f15a81..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/msg.js +++ /dev/null @@ -1,222 +0,0 @@ -'use strict'; - -// Implementation of OP_MSG spec: -// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst -// -// struct Section { -// uint8 payloadType; -// union payload { -// document document; // payloadType == 0 -// struct sequence { // payloadType == 1 -// int32 size; -// cstring identifier; -// document* documents; -// }; -// }; -// }; - -// struct OP_MSG { -// struct MsgHeader { -// int32 messageLength; -// int32 requestID; -// int32 responseTo; -// int32 opCode = 2013; -// }; -// uint32 flagBits; -// Section+ sections; -// [uint32 checksum;] -// }; - -const Buffer = require('safe-buffer').Buffer; -const opcodes = require('../wireprotocol/shared').opcodes; -const databaseNamespace = require('../wireprotocol/shared').databaseNamespace; -const ReadPreference = require('../topologies/read_preference'); - -// Incrementing request id -let _requestId = 0; - -// Msg Flags -const OPTS_CHECKSUM_PRESENT = 1; -const OPTS_MORE_TO_COME = 2; -const OPTS_EXHAUST_ALLOWED = 1 << 16; - -class Msg { - constructor(bson, ns, command, options) { - // Basic options needed to be passed in - if (command == null) throw new Error('query must be specified for query'); - - // Basic options - this.bson = bson; - this.ns = ns; - this.command = command; - this.command.$db = databaseNamespace(ns); - - if (options.readPreference && options.readPreference.mode !== ReadPreference.PRIMARY) { - this.command.$readPreference = options.readPreference.toJSON(); - } - - // Ensure empty options - this.options = options || {}; - - // Additional options - this.requestId = options.requestId ? options.requestId : Msg.getRequestId(); - - // Serialization option - this.serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; - - // flags - this.checksumPresent = false; - this.moreToCome = options.moreToCome || false; - this.exhaustAllowed = - typeof options.exhaustAllowed === 'boolean' ? options.exhaustAllowed : false; - } - - toBin() { - const buffers = []; - let flags = 0; - - if (this.checksumPresent) { - flags |= OPTS_CHECKSUM_PRESENT; - } - - if (this.moreToCome) { - flags |= OPTS_MORE_TO_COME; - } - - if (this.exhaustAllowed) { - flags |= OPTS_EXHAUST_ALLOWED; - } - - const header = Buffer.alloc( - 4 * 4 + // Header - 4 // Flags - ); - - buffers.push(header); - - let totalLength = header.length; - const command = this.command; - totalLength += this.makeDocumentSegment(buffers, command); - - header.writeInt32LE(totalLength, 0); // messageLength - header.writeInt32LE(this.requestId, 4); // requestID - header.writeInt32LE(0, 8); // responseTo - header.writeInt32LE(opcodes.OP_MSG, 12); // opCode - header.writeUInt32LE(flags, 16); // flags - return buffers; - } - - makeDocumentSegment(buffers, document) { - const payloadTypeBuffer = Buffer.alloc(1); - payloadTypeBuffer[0] = 0; - - const documentBuffer = this.serializeBson(document); - buffers.push(payloadTypeBuffer); - buffers.push(documentBuffer); - - return payloadTypeBuffer.length + documentBuffer.length; - } - - serializeBson(document) { - return this.bson.serialize(document, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - } -} - -Msg.getRequestId = function() { - _requestId = (_requestId + 1) & 0x7fffffff; - return _requestId; -}; - -class BinMsg { - constructor(bson, message, msgHeader, msgBody, opts) { - opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; - this.parsed = false; - this.raw = message; - this.data = msgBody; - this.bson = bson; - this.opts = opts; - - // Read the message header - this.length = msgHeader.length; - this.requestId = msgHeader.requestId; - this.responseTo = msgHeader.responseTo; - this.opCode = msgHeader.opCode; - this.fromCompressed = msgHeader.fromCompressed; - - // Read response flags - this.responseFlags = msgBody.readInt32LE(0); - this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; - this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; - this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; - this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; - this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; - this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; - - this.documents = []; - } - - isParsed() { - return this.parsed; - } - - parse(options) { - // Don't parse again if not needed - if (this.parsed) return; - options = options || {}; - - this.index = 4; - // Allow the return of raw documents instead of parsing - const raw = options.raw || false; - const documentsReturnedIn = options.documentsReturnedIn || null; - const promoteLongs = - typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; - const promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; - const promoteBuffers = - typeof options.promoteBuffers === 'boolean' - ? options.promoteBuffers - : this.opts.promoteBuffers; - - // Set up the options - const _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers - }; - - while (this.index < this.data.length) { - const payloadType = this.data.readUInt8(this.index++); - if (payloadType === 1) { - console.error('TYPE 1'); - } else if (payloadType === 0) { - const bsonSize = this.data.readUInt32LE(this.index); - const bin = this.data.slice(this.index, this.index + bsonSize); - this.documents.push(raw ? bin : this.bson.deserialize(bin, _options)); - - this.index += bsonSize; - } - } - - if (this.documents.length === 1 && documentsReturnedIn != null && raw) { - const fieldsAsRaw = {}; - fieldsAsRaw[documentsReturnedIn] = true; - _options.fieldsAsRaw = fieldsAsRaw; - - const doc = this.bson.deserialize(this.documents[0], _options); - this.documents = [doc]; - } - - this.parsed = true; - } -} - -module.exports = { Msg, BinMsg }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/pool.js b/node_modules/mongoose/node_modules/mongodb/lib/core/connection/pool.js deleted file mode 100644 index 56d427e..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/pool.js +++ /dev/null @@ -1,1280 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const EventEmitter = require('events').EventEmitter; -const MongoError = require('../error').MongoError; -const MongoTimeoutError = require('../error').MongoTimeoutError; -const MongoWriteConcernError = require('../error').MongoWriteConcernError; -const Logger = require('./logger'); -const f = require('util').format; -const Msg = require('./msg').Msg; -const CommandResult = require('./command_result'); -const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; -const COMPRESSION_DETAILS_SIZE = require('../wireprotocol/shared').COMPRESSION_DETAILS_SIZE; -const opcodes = require('../wireprotocol/shared').opcodes; -const compress = require('../wireprotocol/compression').compress; -const compressorIDs = require('../wireprotocol/compression').compressorIDs; -const uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands; -const apm = require('./apm'); -const Buffer = require('safe-buffer').Buffer; -const connect = require('./connect'); -const updateSessionFromResponse = require('../sessions').updateSessionFromResponse; -const eachAsync = require('../utils').eachAsync; -const makeStateMachine = require('../utils').makeStateMachine; - -const DISCONNECTED = 'disconnected'; -const CONNECTING = 'connecting'; -const CONNECTED = 'connected'; -const DRAINING = 'draining'; -const DESTROYING = 'destroying'; -const DESTROYED = 'destroyed'; -const stateTransition = makeStateMachine({ - [DISCONNECTED]: [CONNECTING, DRAINING, DISCONNECTED], - [CONNECTING]: [CONNECTING, CONNECTED, DRAINING, DISCONNECTED], - [CONNECTED]: [CONNECTED, DISCONNECTED, DRAINING], - [DRAINING]: [DRAINING, DESTROYING, DESTROYED], - [DESTROYING]: [DESTROYING, DESTROYED], - [DESTROYED]: [DESTROYED] -}); - -const CONNECTION_EVENTS = new Set([ - 'error', - 'close', - 'timeout', - 'parseError', - 'connect', - 'message' -]); - -var _id = 0; - -/** - * Creates a new Pool instance - * @class - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Max server connection pool size - * @param {number} [options.minSize=0] Minimum server connection pool size - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @fires Pool#connect - * @fires Pool#close - * @fires Pool#error - * @fires Pool#timeout - * @fires Pool#parseError - * @return {Pool} A cursor instance - */ -var Pool = function(topology, options) { - // Add event listener - EventEmitter.call(this); - - // Store topology for later use - this.topology = topology; - - this.s = { - state: DISCONNECTED, - cancellationToken: new EventEmitter() - }; - - // we don't care how many connections are listening for cancellation - this.s.cancellationToken.setMaxListeners(Infinity); - - // Add the options - this.options = Object.assign( - { - // Host and port settings - host: 'localhost', - port: 27017, - // Pool default max size - size: 5, - // Pool default min size - minSize: 0, - // socket settings - connectionTimeout: 30000, - socketTimeout: 360000, - keepAlive: true, - keepAliveInitialDelay: 300000, - noDelay: true, - // SSL Settings - ssl: false, - checkServerIdentity: true, - ca: null, - crl: null, - cert: null, - key: null, - passphrase: null, - rejectUnauthorized: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - // Reconnection options - reconnect: true, - reconnectInterval: 1000, - reconnectTries: 30, - // Enable domains - domainsEnabled: false, - // feature flag for determining if we are running with the unified topology or not - legacyCompatMode: true - }, - options - ); - - // Identification information - this.id = _id++; - // Current reconnect retries - this.retriesLeft = this.options.reconnectTries; - this.reconnectId = null; - this.reconnectError = null; - // No bson parser passed in - if ( - !options.bson || - (options.bson && - (typeof options.bson.serialize !== 'function' || - typeof options.bson.deserialize !== 'function')) - ) { - throw new Error('must pass in valid bson parser'); - } - - // Logger instance - this.logger = Logger('Pool', options); - // Connections - this.availableConnections = []; - this.inUseConnections = []; - this.connectingConnections = 0; - // Currently executing - this.executing = false; - // Operation work queue - this.queue = []; - - // Number of consecutive timeouts caught - this.numberOfConsecutiveTimeouts = 0; - // Current pool Index - this.connectionIndex = 0; - - // event handlers - const pool = this; - this._messageHandler = messageHandler(this); - this._connectionCloseHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'close', err, connection); - }; - - this._connectionErrorHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'error', err, connection); - }; - - this._connectionTimeoutHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'timeout', err, connection); - }; - - this._connectionParseErrorHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'parseError', err, connection); - }; -}; - -inherits(Pool, EventEmitter); - -Object.defineProperty(Pool.prototype, 'size', { - enumerable: true, - get: function() { - return this.options.size; - } -}); - -Object.defineProperty(Pool.prototype, 'minSize', { - enumerable: true, - get: function() { - return this.options.minSize; - } -}); - -Object.defineProperty(Pool.prototype, 'connectionTimeout', { - enumerable: true, - get: function() { - return this.options.connectionTimeout; - } -}); - -Object.defineProperty(Pool.prototype, 'socketTimeout', { - enumerable: true, - get: function() { - return this.options.socketTimeout; - } -}); - -Object.defineProperty(Pool.prototype, 'state', { - enumerable: true, - get: function() { - return this.s.state; - } -}); - -// clears all pool state -function resetPoolState(pool) { - pool.inUseConnections = []; - pool.availableConnections = []; - pool.connectingConnections = 0; - pool.executing = false; - pool.numberOfConsecutiveTimeouts = 0; - pool.connectionIndex = 0; - pool.retriesLeft = pool.options.reconnectTries; - pool.reconnectId = null; -} - -function connectionFailureHandler(pool, event, err, conn) { - if (conn) { - if (conn._connectionFailHandled) { - return; - } - - conn._connectionFailHandled = true; - conn.destroy(); - - // Remove the connection - removeConnection(pool, conn); - - // flush remaining work items - conn.flush(err); - } - - // Did we catch a timeout, increment the numberOfConsecutiveTimeouts - if (event === 'timeout') { - pool.numberOfConsecutiveTimeouts = pool.numberOfConsecutiveTimeouts + 1; - - // Have we timed out more than reconnectTries in a row ? - // Force close the pool as we are trying to connect to tcp sink hole - if (pool.numberOfConsecutiveTimeouts > pool.options.reconnectTries) { - pool.numberOfConsecutiveTimeouts = 0; - // Destroy all connections and pool - pool.destroy(true); - // Emit close event - return pool.emit('close', pool); - } - } - - // No more socket available propegate the event - if (pool.socketCount() === 0) { - if (pool.state !== DESTROYED && pool.state !== DESTROYING && pool.state !== DRAINING) { - if (pool.options.reconnect) { - stateTransition(pool, DISCONNECTED); - } - } - - // Do not emit error events, they are always close events - // do not trigger the low level error handler in node - event = event === 'error' ? 'close' : event; - pool.emit(event, err); - } - - // Start reconnection attempts - if (!pool.reconnectId && pool.options.reconnect) { - pool.reconnectError = err; - pool.reconnectId = setTimeout(attemptReconnect(pool), pool.options.reconnectInterval); - } - - // Do we need to do anything to maintain the minimum pool size - const totalConnections = totalConnectionCount(pool); - if (totalConnections < pool.minSize) { - createConnection(pool); - } -} - -function attemptReconnect(pool, callback) { - return function() { - pool.emit('attemptReconnect', pool); - - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Cannot create connection when pool is destroyed')); - } - - return; - } - - pool.retriesLeft = pool.retriesLeft - 1; - if (pool.retriesLeft <= 0) { - pool.destroy(); - - const error = new MongoTimeoutError( - `failed to reconnect after ${pool.options.reconnectTries} attempts with interval ${pool.options.reconnectInterval} ms`, - pool.reconnectError - ); - - pool.emit('reconnectFailed', error); - if (typeof callback === 'function') { - callback(error); - } - - return; - } - - // clear the reconnect id on retry - pool.reconnectId = null; - - // now retry creating a connection - createConnection(pool, (err, conn) => { - if (err == null) { - pool.reconnectId = null; - pool.retriesLeft = pool.options.reconnectTries; - pool.emit('reconnect', pool); - } - - if (typeof callback === 'function') { - callback(err, conn); - } - }); - }; -} - -function moveConnectionBetween(connection, from, to) { - var index = from.indexOf(connection); - // Move the connection from connecting to available - if (index !== -1) { - from.splice(index, 1); - to.push(connection); - } -} - -function messageHandler(self) { - return function(message, connection) { - // workItem to execute - var workItem = null; - - // Locate the workItem - for (var i = 0; i < connection.workItems.length; i++) { - if (connection.workItems[i].requestId === message.responseTo) { - // Get the callback - workItem = connection.workItems[i]; - // Remove from list of workItems - connection.workItems.splice(i, 1); - } - } - - if (workItem && workItem.monitoring) { - moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); - } - - // Reset timeout counter - self.numberOfConsecutiveTimeouts = 0; - - // Reset the connection timeout if we modified it for - // this operation - if (workItem && workItem.socketTimeout) { - connection.resetSocketTimeout(); - } - - // Log if debug enabled - if (self.logger.isDebug()) { - self.logger.debug( - f( - 'message [%s] received from %s:%s', - message.raw.toString('hex'), - self.options.host, - self.options.port - ) - ); - } - - function handleOperationCallback(self, cb, err, result) { - // No domain enabled - if (!self.options.domainsEnabled) { - return process.nextTick(function() { - return cb(err, result); - }); - } - - // Domain enabled just call the callback - cb(err, result); - } - - // Keep executing, ensure current message handler does not stop execution - if (!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } - - // Time to dispatch the message if we have a callback - if (workItem && !workItem.immediateRelease) { - try { - // Parse the message according to the provided options - message.parse(workItem); - } catch (err) { - return handleOperationCallback(self, workItem.cb, new MongoError(err)); - } - - if (message.documents[0]) { - const document = message.documents[0]; - const session = workItem.session; - if (session) { - updateSessionFromResponse(session, document); - } - - if (self.topology && document.$clusterTime) { - self.topology.clusterTime = document.$clusterTime; - } - } - - // Establish if we have an error - if (workItem.command && message.documents[0]) { - const responseDoc = message.documents[0]; - - if (responseDoc.writeConcernError) { - const err = new MongoWriteConcernError(responseDoc.writeConcernError, responseDoc); - return handleOperationCallback(self, workItem.cb, err); - } - - if (responseDoc.ok === 0 || responseDoc.$err || responseDoc.errmsg || responseDoc.code) { - return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc)); - } - } - - // Add the connection details - message.hashedName = connection.hashedName; - - // Return the documents - handleOperationCallback( - self, - workItem.cb, - null, - new CommandResult(workItem.fullResult ? message : message.documents[0], connection, message) - ); - } - }; -} - -/** - * Return the total socket count in the pool. - * @method - * @return {Number} The number of socket available. - */ -Pool.prototype.socketCount = function() { - return this.availableConnections.length + this.inUseConnections.length; - // + this.connectingConnections.length; -}; - -function totalConnectionCount(pool) { - return ( - pool.availableConnections.length + pool.inUseConnections.length + pool.connectingConnections - ); -} - -/** - * Return all pool connections - * @method - * @return {Connection[]} The pool connections - */ -Pool.prototype.allConnections = function() { - return this.availableConnections.concat(this.inUseConnections); -}; - -/** - * Get a pool connection (round-robin) - * @method - * @return {Connection} - */ -Pool.prototype.get = function() { - return this.allConnections()[0]; -}; - -/** - * Is the pool connected - * @method - * @return {boolean} - */ -Pool.prototype.isConnected = function() { - // We are in a destroyed state - if (this.state === DESTROYED || this.state === DESTROYING) { - return false; - } - - // Get connections - var connections = this.availableConnections.concat(this.inUseConnections); - - // Check if we have any connected connections - for (var i = 0; i < connections.length; i++) { - if (connections[i].isConnected()) return true; - } - - // Not connected - return false; -}; - -/** - * Was the pool destroyed - * @method - * @return {boolean} - */ -Pool.prototype.isDestroyed = function() { - return this.state === DESTROYED || this.state === DESTROYING; -}; - -/** - * Is the pool in a disconnected state - * @method - * @return {boolean} - */ -Pool.prototype.isDisconnected = function() { - return this.state === DISCONNECTED; -}; - -/** - * Connect pool - */ -Pool.prototype.connect = function(callback) { - if (this.state !== DISCONNECTED) { - throw new MongoError('connection in unlawful state ' + this.state); - } - - stateTransition(this, CONNECTING); - createConnection(this, (err, conn) => { - if (err) { - if (typeof callback === 'function') { - this.destroy(); - callback(err); - return; - } - - if (this.state === CONNECTING) { - this.emit('error', err); - } - - this.destroy(); - return; - } - - stateTransition(this, CONNECTED); - - // create min connections - if (this.minSize) { - for (let i = 0; i < this.minSize; i++) { - createConnection(this); - } - } - - if (typeof callback === 'function') { - callback(null, conn); - } else { - this.emit('connect', this, conn); - } - }); -}; - -/** - * Authenticate using a specified mechanism - * @param {authResultCallback} callback A callback function - */ -Pool.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Logout all users against a database - * @param {authResultCallback} callback A callback function - */ -Pool.prototype.logout = function(dbName, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Unref the pool - * @method - */ -Pool.prototype.unref = function() { - // Get all the known connections - var connections = this.availableConnections.concat(this.inUseConnections); - - connections.forEach(function(c) { - c.unref(); - }); -}; - -// Destroy the connections -function destroy(self, connections, options, callback) { - stateTransition(self, DESTROYING); - - // indicate that in-flight connections should cancel - self.s.cancellationToken.emit('cancel'); - - eachAsync( - connections, - (conn, cb) => { - for (const eventName of CONNECTION_EVENTS) { - conn.removeAllListeners(eventName); - } - - // ignore any errors during destruction - conn.on('error', () => {}); - - conn.destroy(options, cb); - }, - err => { - if (err) { - if (typeof callback === 'function') callback(err, null); - return; - } - - resetPoolState(self); - self.queue = []; - - stateTransition(self, DESTROYED); - if (typeof callback === 'function') callback(null, null); - } - ); -} - -/** - * Destroy pool - * @method - */ -Pool.prototype.destroy = function(force, callback) { - var self = this; - if (typeof force === 'function') { - callback = force; - force = false; - } - - // Do not try again if the pool is already dead - if (this.state === DESTROYED || self.state === DESTROYING) { - if (typeof callback === 'function') callback(null, null); - return; - } - - // Set state to draining - stateTransition(this, DRAINING); - - // Are we force closing - if (force) { - // Get all the known connections - var connections = self.availableConnections.concat(self.inUseConnections); - - // Flush any remaining work items with - // an error - while (self.queue.length > 0) { - var workItem = self.queue.shift(); - if (typeof workItem.cb === 'function') { - workItem.cb(new MongoError('Pool was force destroyed')); - } - } - - // Destroy the topology - return destroy(self, connections, { force: true }, callback); - } - - // Clear out the reconnect if set - if (this.reconnectId) { - clearTimeout(this.reconnectId); - } - - // Wait for the operations to drain before we close the pool - function checkStatus() { - if (self.state === DESTROYED || self.state === DESTROYING) { - if (typeof callback === 'function') { - callback(); - } - - return; - } - - flushMonitoringOperations(self.queue); - - if (self.queue.length === 0) { - // Get all the known connections - var connections = self.availableConnections.concat(self.inUseConnections); - - // Check if we have any in flight operations - for (var i = 0; i < connections.length; i++) { - // There is an operation still in flight, reschedule a - // check waiting for it to drain - if (connections[i].workItems.length > 0) { - return setTimeout(checkStatus, 1); - } - } - - destroy(self, connections, { force: false }, callback); - } else { - // Ensure we empty the queue - _execute(self)(); - // Set timeout - setTimeout(checkStatus, 1); - } - } - - // Initiate drain of operations - checkStatus(); -}; - -/** - * Reset all connections of this pool - * - * @param {function} [callback] - */ -Pool.prototype.reset = function(callback) { - if (this.s.state !== CONNECTED) { - if (typeof callback === 'function') { - callback(new MongoError('pool is not connected, reset aborted')); - } - - return; - } - - // signal in-flight connections should be cancelled - this.s.cancellationToken.emit('cancel'); - - // destroy existing connections - const connections = this.availableConnections.concat(this.inUseConnections); - eachAsync( - connections, - (conn, cb) => { - for (const eventName of CONNECTION_EVENTS) { - conn.removeAllListeners(eventName); - } - - conn.destroy({ force: true }, cb); - }, - err => { - if (err) { - if (typeof callback === 'function') { - callback(err, null); - return; - } - } - - resetPoolState(this); - - // create a new connection, this will ultimately trigger execution - createConnection(this, () => { - if (typeof callback === 'function') { - callback(null, null); - } - }); - } - ); -}; - -// Prepare the buffer that Pool.prototype.write() uses to send to the server -function serializeCommand(self, command, callback) { - const originalCommandBuffer = command.toBin(); - - // Check whether we and the server have agreed to use a compressor - const shouldCompress = !!self.options.agreedCompressor; - if (!shouldCompress || !canCompress(command)) { - return callback(null, originalCommandBuffer); - } - - // Transform originalCommandBuffer into OP_COMPRESSED - const concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer); - const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); - - // Extract information needed for OP_COMPRESSED from the uncompressed message - const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); - - // Compress the message body - compress(self, messageToBeCompressed, function(err, compressedMessage) { - if (err) return callback(err, null); - - // Create the msgHeader of OP_COMPRESSED - const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); - msgHeader.writeInt32LE( - MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, - 0 - ); // messageLength - msgHeader.writeInt32LE(command.requestId, 4); // requestID - msgHeader.writeInt32LE(0, 8); // responseTo (zero) - msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode - - // Create the compression details of OP_COMPRESSED - const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); - compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode - compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader - compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID - - return callback(null, [msgHeader, compressionDetails, compressedMessage]); - }); -} - -/** - * Write a message to MongoDB - * @method - * @return {Connection} - */ -Pool.prototype.write = function(command, options, cb) { - var self = this; - // Ensure we have a callback - if (typeof options === 'function') { - cb = options; - } - - // Always have options - options = options || {}; - - // We need to have a callback function unless the message returns no response - if (!(typeof cb === 'function') && !options.noResponse) { - throw new MongoError('write method must provide a callback'); - } - - // Pool was destroyed error out - if (this.state === DESTROYED || this.state === DESTROYING) { - cb(new MongoError('pool destroyed')); - return; - } - - if (this.state === DRAINING) { - cb(new MongoError('pool is draining, new operations prohibited')); - return; - } - - if (this.options.domainsEnabled && process.domain && typeof cb === 'function') { - // if we have a domain bind to it - var oldCb = cb; - cb = process.domain.bind(function() { - // v8 - argumentsToArray one-liner - var args = new Array(arguments.length); - for (var i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } - // bounce off event loop so domain switch takes place - process.nextTick(function() { - oldCb.apply(null, args); - }); - }); - } - - // Do we have an operation - var operation = { - cb: cb, - raw: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - fullResult: false - }; - - // Set the options for the parsing - operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true; - operation.promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : true; - operation.promoteBuffers = - typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false; - operation.raw = typeof options.raw === 'boolean' ? options.raw : false; - operation.immediateRelease = - typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false; - operation.documentsReturnedIn = options.documentsReturnedIn; - operation.command = typeof options.command === 'boolean' ? options.command : false; - operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false; - operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false; - operation.session = options.session || null; - - // Optional per operation socketTimeout - operation.socketTimeout = options.socketTimeout; - operation.monitoring = options.monitoring; - - // Get the requestId - operation.requestId = command.requestId; - - // If command monitoring is enabled we need to modify the callback here - if (self.options.monitorCommands) { - this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); - - operation.started = process.hrtime(); - operation.cb = (err, reply) => { - if (err) { - self.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, err, operation.started) - ); - } else { - if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { - self.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, reply.result, operation.started) - ); - } else { - self.emit( - 'commandSucceeded', - new apm.CommandSucceededEvent(this, command, reply, operation.started) - ); - } - } - - if (typeof cb === 'function') cb(err, reply); - }; - } - - // Prepare the operation buffer - serializeCommand(self, command, (err, serializedBuffers) => { - if (err) throw err; - - // Set the operation's buffer to the serialization of the commands - operation.buffer = serializedBuffers; - - // If we have a monitoring operation schedule as the very first operation - // Otherwise add to back of queue - if (options.monitoring) { - self.queue.unshift(operation); - } else { - self.queue.push(operation); - } - - // Attempt to execute the operation - if (!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } - }); -}; - -// Return whether a command contains an uncompressible command term -// Will return true if command contains no uncompressible command terms -function canCompress(command) { - const commandDoc = command instanceof Msg ? command.command : command.query; - const commandName = Object.keys(commandDoc)[0]; - return !uncompressibleCommands.has(commandName); -} - -// Remove connection method -function remove(connection, connections) { - for (var i = 0; i < connections.length; i++) { - if (connections[i] === connection) { - connections.splice(i, 1); - return true; - } - } -} - -function removeConnection(self, connection) { - if (remove(connection, self.availableConnections)) return; - if (remove(connection, self.inUseConnections)) return; -} - -function createConnection(pool, callback) { - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Cannot create connection when pool is destroyed')); - } - - return; - } - - pool.connectingConnections++; - connect(pool.options, pool.s.cancellationToken, (err, connection) => { - pool.connectingConnections--; - - if (err) { - if (pool.logger.isDebug()) { - pool.logger.debug(`connection attempt failed with error [${JSON.stringify(err)}]`); - } - - // check if reconnect is enabled, and attempt retry if so - if (!pool.reconnectId && pool.options.reconnect) { - if (pool.state === CONNECTING && pool.options.legacyCompatMode) { - callback(err); - return; - } - - pool.reconnectError = err; - pool.reconnectId = setTimeout( - attemptReconnect(pool, callback), - pool.options.reconnectInterval - ); - - return; - } - - if (typeof callback === 'function') { - callback(err); - } - - return; - } - - // the pool might have been closed since we started creating the connection - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Pool was destroyed after connection creation')); - } - - connection.destroy(); - return; - } - - // otherwise, connect relevant event handlers and add it to our available connections - connection.on('error', pool._connectionErrorHandler); - connection.on('close', pool._connectionCloseHandler); - connection.on('timeout', pool._connectionTimeoutHandler); - connection.on('parseError', pool._connectionParseErrorHandler); - connection.on('message', pool._messageHandler); - - pool.availableConnections.push(connection); - - // if a callback was provided, return the connection - if (typeof callback === 'function') { - callback(null, connection); - } - - // immediately execute any waiting work - _execute(pool)(); - }); -} - -function flushMonitoringOperations(queue) { - for (var i = 0; i < queue.length; i++) { - if (queue[i].monitoring) { - var workItem = queue[i]; - queue.splice(i, 1); - workItem.cb( - new MongoError({ message: 'no connection available for monitoring', driver: true }) - ); - } - } -} - -function _execute(self) { - return function() { - if (self.state === DESTROYED) return; - // Already executing, skip - if (self.executing) return; - // Set pool as executing - self.executing = true; - - // New pool connections are in progress, wait them to finish - // before executing any more operation to ensure distribution of - // operations - if (self.connectingConnections > 0) { - self.executing = false; - return; - } - - // As long as we have available connections - // eslint-disable-next-line - while (true) { - // Total availble connections - const totalConnections = totalConnectionCount(self); - - // No available connections available, flush any monitoring ops - if (self.availableConnections.length === 0) { - // Flush any monitoring operations - flushMonitoringOperations(self.queue); - - // Try to create a new connection to execute stuck operation - if (totalConnections < self.options.size && self.queue.length > 0) { - createConnection(self); - } - - break; - } - - // No queue break - if (self.queue.length === 0) { - break; - } - - var connection = null; - const connections = self.availableConnections.filter(conn => conn.workItems.length === 0); - - // No connection found that has no work on it, just pick one for pipelining - if (connections.length === 0) { - connection = - self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; - } else { - connection = connections[self.connectionIndex++ % connections.length]; - } - - // Is the connection connected - if (!connection.isConnected()) { - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - break; - } - - // Get the next work item - var workItem = self.queue.shift(); - - // If we are monitoring we need to use a connection that is not - // running another operation to avoid socket timeout changes - // affecting an existing operation - if (workItem.monitoring) { - var foundValidConnection = false; - - for (let i = 0; i < self.availableConnections.length; i++) { - // If the connection is connected - // And there are no pending workItems on it - // Then we can safely use it for monitoring. - if ( - self.availableConnections[i].isConnected() && - self.availableConnections[i].workItems.length === 0 - ) { - foundValidConnection = true; - connection = self.availableConnections[i]; - break; - } - } - - // No safe connection found, attempt to grow the connections - // if possible and break from the loop - if (!foundValidConnection) { - // Put workItem back on the queue - self.queue.unshift(workItem); - - // Attempt to grow the pool if it's not yet maxsize - if (totalConnections < self.options.size && self.queue.length > 0) { - // Create a new connection - createConnection(self); - } - - // Re-execute the operation - setTimeout(() => _execute(self)(), 10); - break; - } - } - - // Don't execute operation until we have a full pool - if (totalConnections < self.options.size) { - // Connection has work items, then put it back on the queue - // and create a new connection - if (connection.workItems.length > 0) { - // Lets put the workItem back on the list - self.queue.unshift(workItem); - // Create a new connection - createConnection(self); - // Break from the loop - break; - } - } - - // Get actual binary commands - var buffer = workItem.buffer; - - // If we are monitoring take the connection of the availableConnections - if (workItem.monitoring) { - moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); - } - - // Track the executing commands on the mongo server - // as long as there is an expected response - if (!workItem.noResponse) { - connection.workItems.push(workItem); - } - - // We have a custom socketTimeout - if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') { - connection.setSocketTimeout(workItem.socketTimeout); - } - - // Capture if write was successful - var writeSuccessful = true; - - // Put operation on the wire - if (Array.isArray(buffer)) { - for (let i = 0; i < buffer.length; i++) { - writeSuccessful = connection.write(buffer[i]); - } - } else { - writeSuccessful = connection.write(buffer); - } - - // if the command is designated noResponse, call the callback immeditely - if (workItem.noResponse && typeof workItem.cb === 'function') { - workItem.cb(null, null); - } - - if (writeSuccessful === false) { - // If write not successful put back on queue - self.queue.unshift(workItem); - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - break; - } - } - - self.executing = false; - }; -} - -// Make execution loop available for testing -Pool._execute = _execute; - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Pool#connect - * @type {Pool} - */ - -/** - * A server reconnect event, used to verify that pool reconnected. - * - * @event Pool#reconnect - * @type {Pool} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Pool#close - * @type {Pool} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Pool#error - * @type {Pool} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Pool#timeout - * @type {Pool} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Pool#parseError - * @type {Pool} - */ - -/** - * The driver attempted to reconnect - * - * @event Pool#attemptReconnect - * @type {Pool} - */ - -/** - * The driver exhausted all reconnect attempts - * - * @event Pool#reconnectFailed - * @type {Pool} - */ - -module.exports = Pool; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/utils.js b/node_modules/mongoose/node_modules/mongodb/lib/core/connection/utils.js deleted file mode 100644 index 2f3d889..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/connection/utils.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -const require_optional = require('require_optional'); - -function debugOptions(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -} - -function retrieveBSON() { - var BSON = require('bson'); - BSON.native = false; - - try { - var optionalBSON = require_optional('bson-ext'); - if (optionalBSON) { - optionalBSON.native = true; - return optionalBSON; - } - } catch (err) {} // eslint-disable-line - - return BSON; -} - -// Throw an error if an attempt to use Snappy is made when Snappy is not installed -function noSnappyWarning() { - throw new Error( - 'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.' - ); -} - -// Facilitate loading Snappy optionally -function retrieveSnappy() { - var snappy = null; - try { - snappy = require_optional('snappy'); - } catch (error) {} // eslint-disable-line - if (!snappy) { - snappy = { - compress: noSnappyWarning, - uncompress: noSnappyWarning, - compressSync: noSnappyWarning, - uncompressSync: noSnappyWarning - }; - } - return snappy; -} - -module.exports = { - debugOptions, - retrieveBSON, - retrieveSnappy -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/core/cursor.js deleted file mode 100644 index 72d309e..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/cursor.js +++ /dev/null @@ -1,877 +0,0 @@ -'use strict'; - -const Logger = require('./connection/logger'); -const retrieveBSON = require('./connection/utils').retrieveBSON; -const MongoError = require('./error').MongoError; -const MongoNetworkError = require('./error').MongoNetworkError; -const mongoErrorContextSymbol = require('./error').mongoErrorContextSymbol; -const collationNotSupported = require('./utils').collationNotSupported; -const ReadPreference = require('./topologies/read_preference'); -const isUnifiedTopology = require('./utils').isUnifiedTopology; -const executeOperation = require('../operations/execute_operation'); -const Readable = require('stream').Readable; -const SUPPORTS = require('../utils').SUPPORTS; -const MongoDBNamespace = require('../utils').MongoDBNamespace; -const OperationBase = require('../operations/operation').OperationBase; - -const BSON = retrieveBSON(); -const Long = BSON.Long; - -// Possible states for a cursor -const CursorState = { - INIT: 0, - OPEN: 1, - CLOSED: 2, - GET_MORE: 3 -}; - -// -// Handle callback (including any exceptions thrown) -function handleCallback(callback, err, result) { - try { - callback(err, result); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } -} - -/** - * This is a cursor results callback - * - * @callback resultCallback - * @param {error} error An error object. Set to null if no error present - * @param {object} document - */ - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. - * - * **CURSORS Cannot directly be instantiated** - */ - -/** - * The core cursor class. All cursors in the driver build off of this one. - * - * @property {number} cursorBatchSize The current cursorBatchSize for the cursor - * @property {number} cursorLimit The current cursorLimit for the cursor - * @property {number} cursorSkip The current cursorSkip for the cursor - */ -class CoreCursor extends Readable { - /** - * Create a new core `Cursor` instance. - * **NOTE** Not to be instantiated directly - * - * @param {object} topology The server topology instance. - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|Long} cmd The selector (can be a command or a cursorId) - * @param {object} [options=null] Optional settings. - * @param {object} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/| find command documentation} and {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {object} [options.transforms=null] Transform methods for the cursor results - * @param {function} [options.transforms.query] Transform the value returned from the initial query - * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype._next - */ - constructor(topology, ns, cmd, options) { - super({ objectMode: true }); - options = options || {}; - - if (ns instanceof OperationBase) { - this.operation = ns; - ns = this.operation.ns.toString(); - options = this.operation.options; - cmd = this.operation.cmd ? this.operation.cmd : {}; - } - - // Cursor pool - this.pool = null; - // Cursor server - this.server = null; - - // Do we have a not connected handler - this.disconnectHandler = options.disconnectHandler; - - // Set local values - this.bson = topology.s.bson; - this.ns = ns; - this.namespace = MongoDBNamespace.fromString(ns); - this.cmd = cmd; - this.options = options; - this.topology = topology; - - // All internal state - this.cursorState = { - cursorId: null, - cmd, - documents: options.documents || [], - cursorIndex: 0, - dead: false, - killed: false, - init: false, - notified: false, - limit: options.limit || cmd.limit || 0, - skip: options.skip || cmd.skip || 0, - batchSize: options.batchSize || cmd.batchSize || 1000, - currentLimit: 0, - // Result field name if not a cursor (contains the array of results) - transforms: options.transforms, - raw: options.raw || (cmd && cmd.raw) - }; - - if (typeof options.session === 'object') { - this.cursorState.session = options.session; - } - - // Add promoteLong to cursor state - const topologyOptions = topology.s.options; - if (typeof topologyOptions.promoteLongs === 'boolean') { - this.cursorState.promoteLongs = topologyOptions.promoteLongs; - } else if (typeof options.promoteLongs === 'boolean') { - this.cursorState.promoteLongs = options.promoteLongs; - } - - // Add promoteValues to cursor state - if (typeof topologyOptions.promoteValues === 'boolean') { - this.cursorState.promoteValues = topologyOptions.promoteValues; - } else if (typeof options.promoteValues === 'boolean') { - this.cursorState.promoteValues = options.promoteValues; - } - - // Add promoteBuffers to cursor state - if (typeof topologyOptions.promoteBuffers === 'boolean') { - this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; - } else if (typeof options.promoteBuffers === 'boolean') { - this.cursorState.promoteBuffers = options.promoteBuffers; - } - - if (topologyOptions.reconnect) { - this.cursorState.reconnect = topologyOptions.reconnect; - } - - // Logger - this.logger = Logger('Cursor', topologyOptions); - - // - // Did we pass in a cursor id - if (typeof cmd === 'number') { - this.cursorState.cursorId = Long.fromNumber(cmd); - this.cursorState.lastCursorId = this.cursorState.cursorId; - } else if (cmd instanceof Long) { - this.cursorState.cursorId = cmd; - this.cursorState.lastCursorId = cmd; - } - - // TODO: remove as part of NODE-2104 - if (this.operation) { - this.operation.cursorState = this.cursorState; - } - } - - setCursorBatchSize(value) { - this.cursorState.batchSize = value; - } - - cursorBatchSize() { - return this.cursorState.batchSize; - } - - setCursorLimit(value) { - this.cursorState.limit = value; - } - - cursorLimit() { - return this.cursorState.limit; - } - - setCursorSkip(value) { - this.cursorState.skip = value; - } - - cursorSkip() { - return this.cursorState.skip; - } - - /** - * Retrieve the next document from the cursor - * @method - * @param {resultCallback} callback A callback function - */ - _next(callback) { - nextFunction(this, callback); - } - - /** - * Clone the cursor - * @method - * @return {Cursor} - */ - clone() { - return this.topology.cursor(this.ns, this.cmd, this.options); - } - - /** - * Checks if the cursor is dead - * @method - * @return {boolean} A boolean signifying if the cursor is dead or not - */ - isDead() { - return this.cursorState.dead === true; - } - - /** - * Checks if the cursor was killed by the application - * @method - * @return {boolean} A boolean signifying if the cursor was killed by the application - */ - isKilled() { - return this.cursorState.killed === true; - } - - /** - * Checks if the cursor notified it's caller about it's death - * @method - * @return {boolean} A boolean signifying if the cursor notified the callback - */ - isNotified() { - return this.cursorState.notified === true; - } - - /** - * Returns current buffered documents length - * @method - * @return {number} The number of items in the buffered documents - */ - bufferedCount() { - return this.cursorState.documents.length - this.cursorState.cursorIndex; - } - - /** - * Returns current buffered documents - * @method - * @return {Array} An array of buffered documents - */ - readBufferedDocuments(number) { - const unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; - const length = number < unreadDocumentsLength ? number : unreadDocumentsLength; - let elements = this.cursorState.documents.slice( - this.cursorState.cursorIndex, - this.cursorState.cursorIndex + length - ); - - // Transform the doc with passed in transformation method if provided - if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') { - // Transform all the elements - for (let i = 0; i < elements.length; i++) { - elements[i] = this.cursorState.transforms.doc(elements[i]); - } - } - - // Ensure we do not return any more documents than the limit imposed - // Just return the number of elements up to the limit - if ( - this.cursorState.limit > 0 && - this.cursorState.currentLimit + elements.length > this.cursorState.limit - ) { - elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit); - this.kill(); - } - - // Adjust current limit - this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; - this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; - - // Return elements - return elements; - } - - /** - * Resets local state for this cursor instance, and issues a `killCursors` command to the server - * - * @param {resultCallback} callback A callback function - */ - kill(callback) { - // Set cursor to dead - this.cursorState.dead = true; - this.cursorState.killed = true; - // Remove documents - this.cursorState.documents = []; - - // If no cursor id just return - if ( - this.cursorState.cursorId == null || - this.cursorState.cursorId.isZero() || - this.cursorState.init === false - ) { - if (callback) callback(null, null); - return; - } - - this.server.killCursors(this.ns, this.cursorState, callback); - } - - /** - * Resets the cursor - */ - rewind() { - if (this.cursorState.init) { - if (!this.cursorState.dead) { - this.kill(); - } - - this.cursorState.currentLimit = 0; - this.cursorState.init = false; - this.cursorState.dead = false; - this.cursorState.killed = false; - this.cursorState.notified = false; - this.cursorState.documents = []; - this.cursorState.cursorId = null; - this.cursorState.cursorIndex = 0; - } - } - - // Internal methods - _read() { - if ((this.s && this.s.state === CursorState.CLOSED) || this.isDead()) { - return this.push(null); - } - - // Get the next item - this._next((err, result) => { - if (err) { - if (this.listeners('error') && this.listeners('error').length > 0) { - this.emit('error', err); - } - if (!this.isDead()) this.close(); - - // Emit end event - this.emit('end'); - return this.emit('finish'); - } - - // If we provided a transformation method - if ( - this.cursorState.streamOptions && - typeof this.cursorState.streamOptions.transform === 'function' && - result != null - ) { - return this.push(this.cursorState.streamOptions.transform(result)); - } - - // Return the result - this.push(result); - - if (result === null && this.isDead()) { - this.once('end', () => { - this.close(); - this.emit('finish'); - }); - } - }); - } - - _endSession(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - - const session = this.cursorState.session; - - if (session && (options.force || session.owner === this)) { - this.cursorState.session = undefined; - - if (this.operation) { - this.operation.clearSession(); - } - - session.endSession(callback); - return true; - } - - if (callback) { - callback(); - } - - return false; - } - - _getMore(callback) { - if (this.logger.isDebug()) { - this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`); - } - - // Set the current batchSize - let batchSize = this.cursorState.batchSize; - if ( - this.cursorState.limit > 0 && - this.cursorState.currentLimit + batchSize > this.cursorState.limit - ) { - batchSize = this.cursorState.limit - this.cursorState.currentLimit; - } - - this.server.getMore(this.ns, this.cursorState, batchSize, this.options, callback); - } - - _initializeCursor(callback) { - const cursor = this; - - // NOTE: this goes away once cursors use `executeOperation` - if (isUnifiedTopology(cursor.topology) && cursor.topology.shouldCheckForSessionSupport()) { - cursor.topology.selectServer(ReadPreference.primaryPreferred, err => { - if (err) { - callback(err); - return; - } - - this._initializeCursor(callback); - }); - - return; - } - - function done(err, result) { - if ( - cursor.cursorState.cursorId && - cursor.cursorState.cursorId.isZero() && - cursor._endSession - ) { - cursor._endSession(); - } - - if ( - cursor.cursorState.documents.length === 0 && - cursor.cursorState.cursorId && - cursor.cursorState.cursorId.isZero() && - !cursor.cmd.tailable && - !cursor.cmd.awaitData - ) { - return setCursorNotified(cursor, callback); - } - - callback(err, result); - } - - const queryCallback = (err, r) => { - if (err) { - return done(err); - } - - const result = r.message; - if (result.queryFailure) { - return done(new MongoError(result.documents[0]), null); - } - - // Check if we have a command cursor - if ( - Array.isArray(result.documents) && - result.documents.length === 1 && - (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) && - (typeof result.documents[0].cursor !== 'string' || - result.documents[0]['$err'] || - result.documents[0]['errmsg'] || - Array.isArray(result.documents[0].result)) - ) { - // We have an error document, return the error - if (result.documents[0]['$err'] || result.documents[0]['errmsg']) { - return done(new MongoError(result.documents[0]), null); - } - - // We have a cursor document - if (result.documents[0].cursor != null && typeof result.documents[0].cursor !== 'string') { - const id = result.documents[0].cursor.id; - // If we have a namespace change set the new namespace for getmores - if (result.documents[0].cursor.ns) { - cursor.ns = result.documents[0].cursor.ns; - } - // Promote id to long if needed - cursor.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; - cursor.cursorState.lastCursorId = cursor.cursorState.cursorId; - cursor.cursorState.operationTime = result.documents[0].operationTime; - - // If we have a firstBatch set it - if (Array.isArray(result.documents[0].cursor.firstBatch)) { - cursor.cursorState.documents = result.documents[0].cursor.firstBatch; //.reverse(); - } - - // Return after processing command cursor - return done(null, result); - } - - if (Array.isArray(result.documents[0].result)) { - cursor.cursorState.documents = result.documents[0].result; - cursor.cursorState.cursorId = Long.ZERO; - return done(null, result); - } - } - - // Otherwise fall back to regular find path - const cursorId = result.cursorId || 0; - cursor.cursorState.cursorId = cursorId instanceof Long ? cursorId : Long.fromNumber(cursorId); - cursor.cursorState.documents = result.documents; - cursor.cursorState.lastCursorId = result.cursorId; - - // Transform the results with passed in transformation method if provided - if ( - cursor.cursorState.transforms && - typeof cursor.cursorState.transforms.query === 'function' - ) { - cursor.cursorState.documents = cursor.cursorState.transforms.query(result); - } - - done(null, result); - }; - - if (cursor.operation) { - if (cursor.logger.isDebug()) { - cursor.logger.debug( - `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( - cursor.query - )}]` - ); - } - - executeOperation(cursor.topology, cursor.operation, (err, result) => { - if (err) { - done(err); - return; - } - - cursor.server = cursor.operation.server; - cursor.cursorState.init = true; - - // NOTE: this is a special internal method for cloning a cursor, consider removing - if (cursor.cursorState.cursorId != null) { - return done(); - } - - queryCallback(err, result); - }); - - return; - } - - // Very explicitly choose what is passed to selectServer - const serverSelectOptions = {}; - if (cursor.cursorState.session) { - serverSelectOptions.session = cursor.cursorState.session; - } - - if (cursor.operation) { - serverSelectOptions.readPreference = cursor.operation.readPreference; - } else if (cursor.options.readPreference) { - serverSelectOptions.readPreference = cursor.options.readPreference; - } - - return cursor.topology.selectServer(serverSelectOptions, (err, server) => { - if (err) { - const disconnectHandler = cursor.disconnectHandler; - if (disconnectHandler != null) { - return disconnectHandler.addObjectAndMethod( - 'cursor', - cursor, - 'next', - [callback], - callback - ); - } - - return callback(err); - } - - cursor.server = server; - cursor.cursorState.init = true; - if (collationNotSupported(cursor.server, cursor.cmd)) { - return callback(new MongoError(`server ${cursor.server.name} does not support collation`)); - } - - // NOTE: this is a special internal method for cloning a cursor, consider removing - if (cursor.cursorState.cursorId != null) { - return done(); - } - - if (cursor.logger.isDebug()) { - cursor.logger.debug( - `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( - cursor.query - )}]` - ); - } - - if (cursor.cmd.find != null) { - server.query(cursor.ns, cursor.cmd, cursor.cursorState, cursor.options, queryCallback); - return; - } - - const commandOptions = Object.assign({ session: cursor.cursorState.session }, cursor.options); - server.command(cursor.ns, cursor.cmd, commandOptions, queryCallback); - }); - } -} - -if (SUPPORTS.ASYNC_ITERATOR) { - CoreCursor.prototype[Symbol.asyncIterator] = require('../async/async_iterator').asyncIterator; -} - -/** - * Validate if the pool is dead and return error - */ -function isConnectionDead(self, callback) { - if (self.pool && self.pool.isDestroyed()) { - self.cursorState.killed = true; - const err = new MongoNetworkError( - `connection to host ${self.pool.host}:${self.pool.port} was destroyed` - ); - - _setCursorNotifiedImpl(self, () => callback(err)); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead but was not explicitly killed by user - */ -function isCursorDeadButNotkilled(self, callback) { - // Cursor is dead but not marked killed, return null - if (self.cursorState.dead && !self.cursorState.killed) { - self.cursorState.killed = true; - setCursorNotified(self, callback); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead and was killed by user - */ -function isCursorDeadAndKilled(self, callback) { - if (self.cursorState.dead && self.cursorState.killed) { - handleCallback(callback, new MongoError('cursor is dead')); - return true; - } - - return false; -} - -/** - * Validate if the cursor was killed by the user - */ -function isCursorKilled(self, callback) { - if (self.cursorState.killed) { - setCursorNotified(self, callback); - return true; - } - - return false; -} - -/** - * Mark cursor as being dead and notified - */ -function setCursorDeadAndNotified(self, callback) { - self.cursorState.dead = true; - setCursorNotified(self, callback); -} - -/** - * Mark cursor as being notified - */ -function setCursorNotified(self, callback) { - _setCursorNotifiedImpl(self, () => handleCallback(callback, null, null)); -} - -function _setCursorNotifiedImpl(self, callback) { - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - - if (self._endSession) { - self._endSession(undefined, () => callback()); - return; - } - - return callback(); -} - -function nextFunction(self, callback) { - // We have notified about it - if (self.cursorState.notified) { - return callback(new Error('cursor is exhausted')); - } - - // Cursor is killed return null - if (isCursorKilled(self, callback)) return; - - // Cursor is dead but not marked killed, return null - if (isCursorDeadButNotkilled(self, callback)) return; - - // We have a dead and killed cursor, attempting to call next should error - if (isCursorDeadAndKilled(self, callback)) return; - - // We have just started the cursor - if (!self.cursorState.init) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if (!self.topology.isConnected(self.options)) { - // Only need this for single server, because repl sets and mongos - // will always continue trying to reconnect - if (self.topology._type === 'server' && !self.topology.s.options.reconnect) { - // Reconnect is disabled, so we'll never reconnect - return callback(new MongoError('no connection available')); - } - - if (self.disconnectHandler != null) { - if (self.topology.isDestroyed()) { - // Topology was destroyed, so don't try to wait for it to reconnect - return callback(new MongoError('Topology was destroyed')); - } - - self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); - return; - } - } - - self._initializeCursor((err, result) => { - if (err || result === null) { - callback(err, result); - return; - } - - nextFunction(self, callback); - }); - - return; - } - - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } else if ( - self.cursorState.cursorIndex === self.cursorState.documents.length && - !Long.ZERO.equals(self.cursorState.cursorId) - ) { - // Ensure an empty cursor state - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - - // Check if topology is destroyed - if (self.topology.isDestroyed()) - return callback( - new MongoNetworkError('connection destroyed, not possible to instantiate cursor') - ); - - // Check if connection is dead and return if not possible to - // execute a getMore on this connection - if (isConnectionDead(self, callback)) return; - - // Execute the next get more - self._getMore(function(err, doc, connection) { - if (err) { - if (err instanceof MongoError) { - err[mongoErrorContextSymbol].isGetMore = true; - } - - return handleCallback(callback, err); - } - - if (self.cursorState.cursorId && self.cursorState.cursorId.isZero() && self._endSession) { - self._endSession(); - } - - // Save the returned connection to ensure all getMore's fire over the same connection - self.connection = connection; - - // Tailable cursor getMore result, notify owner about it - // No attempt is made here to retry, this is left to the user of the - // core module to handle to keep core simple - if ( - self.cursorState.documents.length === 0 && - self.cmd.tailable && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - // No more documents in the tailed cursor - return handleCallback( - callback, - new MongoError({ - message: 'No more documents in tailed cursor', - tailable: self.cmd.tailable, - awaitData: self.cmd.awaitData - }) - ); - } else if ( - self.cursorState.documents.length === 0 && - self.cmd.tailable && - !Long.ZERO.equals(self.cursorState.cursorId) - ) { - return nextFunction(self, callback); - } - - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - return setCursorDeadAndNotified(self, callback); - } - - nextFunction(self, callback); - }); - } else if ( - self.cursorState.documents.length === self.cursorState.cursorIndex && - self.cmd.tailable && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - return handleCallback( - callback, - new MongoError({ - message: 'No more documents in tailed cursor', - tailable: self.cmd.tailable, - awaitData: self.cmd.awaitData - }) - ); - } else if ( - self.cursorState.documents.length === self.cursorState.cursorIndex && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - setCursorDeadAndNotified(self, callback); - } else { - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } - - // Increment the current cursor limit - self.cursorState.currentLimit += 1; - - // Get the document - let doc = self.cursorState.documents[self.cursorState.cursorIndex++]; - - // Doc overflow - if (!doc || doc.$err) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, function() { - handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); - }); - } - - // Transform the doc with passed in transformation method if provided - if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') { - doc = self.cursorState.transforms.doc(doc); - } - - // Return the document - handleCallback(callback, null, doc); - } -} - -module.exports = { - CursorState, - CoreCursor -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/error.js b/node_modules/mongoose/node_modules/mongodb/lib/core/error.js deleted file mode 100644 index 38fbb37..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/error.js +++ /dev/null @@ -1,270 +0,0 @@ -'use strict'; - -const mongoErrorContextSymbol = Symbol('mongoErrorContextSymbol'); - -/** - * Creates a new MongoError - * - * @augments Error - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @property {string} stack The error call stack - */ -class MongoError extends Error { - constructor(message) { - if (message instanceof Error) { - super(message.message); - this.stack = message.stack; - } else { - if (typeof message === 'string') { - super(message); - } else { - super(message.message || message.errmsg || message.$err || 'n/a'); - for (var name in message) { - this[name] = message[name]; - } - } - - Error.captureStackTrace(this, this.constructor); - } - - this.name = 'MongoError'; - this[mongoErrorContextSymbol] = this[mongoErrorContextSymbol] || {}; - } - - /** - * Creates a new MongoError object - * - * @param {Error|string|object} options The options used to create the error. - * @return {MongoError} A MongoError instance - * @deprecated Use `new MongoError()` instead. - */ - static create(options) { - return new MongoError(options); - } - - /** - * Checks the error to see if it has an error label - * @param {string} label The error label to check for - * @returns {boolean} returns true if the error has the provided error label - */ - hasErrorLabel(label) { - return this.errorLabels && this.errorLabels.indexOf(label) !== -1; - } -} - -/** - * An error indicating an issue with the network, including TCP - * errors and timeouts. - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @property {string} stack The error call stack - * @extends MongoError - */ -class MongoNetworkError extends MongoError { - constructor(message) { - super(message); - this.name = 'MongoNetworkError'; - } -} - -/** - * An error used when attempting to parse a value (like a connection string) - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @extends MongoError - */ -class MongoParseError extends MongoError { - constructor(message) { - super(message); - this.name = 'MongoParseError'; - } -} - -/** - * An error signifying a client-side timeout event - * - * @param {Error|string|object} message The error message - * @param {string|object} [reason] The reason the timeout occured - * @property {string} message The error message - * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers - * @extends MongoError - */ -class MongoTimeoutError extends MongoError { - constructor(message, reason) { - if (reason && reason.error) { - super(reason.error.message || reason.error); - } else { - super(message); - } - - this.name = 'MongoTimeoutError'; - if (reason) { - this.reason = reason; - } - } -} - -/** - * An error signifying a client-side server selection error - * - * @param {Error|string|object} message The error message - * @param {string|object} [reason] The reason the timeout occured - * @property {string} message The error message - * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers - * @extends MongoError - */ -class MongoServerSelectionError extends MongoTimeoutError { - constructor(message, reason) { - super(message, reason); - this.name = 'MongoServerSelectionError'; - } -} - -function makeWriteConcernResultObject(input) { - const output = Object.assign({}, input); - - if (output.ok === 0) { - output.ok = 1; - delete output.errmsg; - delete output.code; - delete output.codeName; - } - - return output; -} - -/** - * An error thrown when the server reports a writeConcernError - * - * @param {Error|string|object} message The error message - * @param {object} result The result document (provided if ok: 1) - * @property {string} message The error message - * @property {object} [result] The result document (provided if ok: 1) - * @extends MongoError - */ -class MongoWriteConcernError extends MongoError { - constructor(message, result) { - super(message); - this.name = 'MongoWriteConcernError'; - - if (result != null) { - this.result = makeWriteConcernResultObject(result); - } - } -} - -// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms -const RETRYABLE_ERROR_CODES = new Set([ - 6, // HostUnreachable - 7, // HostNotFound - 89, // NetworkTimeout - 91, // ShutdownInProgress - 189, // PrimarySteppedDown - 9001, // SocketException - 10107, // NotMaster - 11600, // InterruptedAtShutdown - 11602, // InterruptedDueToReplStateChange - 13435, // NotMasterNoSlaveOk - 13436 // NotMasterOrSecondary -]); - -/** - * Determines whether an error is something the driver should attempt to retry - * - * @ignore - * @param {MongoError|Error} error - */ -function isRetryableError(error) { - return ( - RETRYABLE_ERROR_CODES.has(error.code) || - error instanceof MongoNetworkError || - error.message.match(/not master/) || - error.message.match(/node is recovering/) - ); -} - -const SDAM_RECOVERING_CODES = new Set([ - 91, // ShutdownInProgress - 189, // PrimarySteppedDown - 11600, // InterruptedAtShutdown - 11602, // InterruptedDueToReplStateChange - 13436 // NotMasterOrSecondary -]); - -const SDAM_NOTMASTER_CODES = new Set([ - 10107, // NotMaster - 13435 // NotMasterNoSlaveOk -]); - -const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ - 11600, // InterruptedAtShutdown - 91 // ShutdownInProgress -]); - -function isRecoveringError(err) { - if (err.code && SDAM_RECOVERING_CODES.has(err.code)) { - return true; - } - - return err.message.match(/not master or secondary/) || err.message.match(/node is recovering/); -} - -function isNotMasterError(err) { - if (err.code && SDAM_NOTMASTER_CODES.has(err.code)) { - return true; - } - - if (isRecoveringError(err)) { - return false; - } - - return err.message.match(/not master/); -} - -function isNodeShuttingDownError(err) { - return err.code && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code); -} - -/** - * Determines whether SDAM can recover from a given error. If it cannot - * then the pool will be cleared, and server state will completely reset - * locally. - * - * @ignore - * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering - * @param {MongoError|Error} error - */ -function isSDAMUnrecoverableError(error) { - // NOTE: null check is here for a strictly pre-CMAP world, a timeout or - // close event are considered unrecoverable - if (error instanceof MongoParseError || error == null) { - return true; - } - - if (isRecoveringError(error) || isNotMasterError(error)) { - return true; - } - - return false; -} - -function isNetworkTimeoutError(err) { - return err instanceof MongoNetworkError && err.message.match(/timed out/); -} - -module.exports = { - MongoError, - MongoNetworkError, - MongoParseError, - MongoTimeoutError, - MongoServerSelectionError, - MongoWriteConcernError, - mongoErrorContextSymbol, - isRetryableError, - isSDAMUnrecoverableError, - isNodeShuttingDownError, - isNetworkTimeoutError -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/index.js b/node_modules/mongoose/node_modules/mongodb/lib/core/index.js deleted file mode 100644 index 2da5573..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/index.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -let BSON = require('bson'); -const require_optional = require('require_optional'); -const EJSON = require('./utils').retrieveEJSON(); - -try { - // Attempt to grab the native BSON parser - const BSONNative = require_optional('bson-ext'); - // If we got the native parser, use it instead of the - // Javascript one - if (BSONNative) { - BSON = BSONNative; - } -} catch (err) {} // eslint-disable-line - -module.exports = { - // Errors - MongoError: require('./error').MongoError, - MongoNetworkError: require('./error').MongoNetworkError, - MongoParseError: require('./error').MongoParseError, - MongoTimeoutError: require('./error').MongoTimeoutError, - MongoServerSelectionError: require('./error').MongoServerSelectionError, - MongoWriteConcernError: require('./error').MongoWriteConcernError, - mongoErrorContextSymbol: require('./error').mongoErrorContextSymbol, - // Core - Connection: require('./connection/connection'), - Server: require('./topologies/server'), - ReplSet: require('./topologies/replset'), - Mongos: require('./topologies/mongos'), - Logger: require('./connection/logger'), - Cursor: require('./cursor').CoreCursor, - ReadPreference: require('./topologies/read_preference'), - Sessions: require('./sessions'), - BSON: BSON, - EJSON: EJSON, - Topology: require('./sdam/topology').Topology, - // Raw operations - Query: require('./connection/commands').Query, - // Auth mechanisms - MongoCredentials: require('./auth/mongo_credentials').MongoCredentials, - defaultAuthProviders: require('./auth/defaultAuthProviders').defaultAuthProviders, - MongoCR: require('./auth/mongocr'), - X509: require('./auth/x509'), - Plain: require('./auth/plain'), - GSSAPI: require('./auth/gssapi'), - ScramSHA1: require('./auth/scram').ScramSHA1, - ScramSHA256: require('./auth/scram').ScramSHA256, - // Utilities - parseConnectionString: require('./uri_parser') -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/common.js b/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/common.js deleted file mode 100644 index c99b01c..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/common.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -// shared state names -const STATE_CLOSING = 'closing'; -const STATE_CLOSED = 'closed'; -const STATE_CONNECTING = 'connecting'; -const STATE_CONNECTED = 'connected'; - -// An enumeration of topology types we know about -const TopologyType = { - Single: 'Single', - ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', - ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', - Sharded: 'Sharded', - Unknown: 'Unknown' -}; - -// An enumeration of server types we know about -const ServerType = { - Standalone: 'Standalone', - Mongos: 'Mongos', - PossiblePrimary: 'PossiblePrimary', - RSPrimary: 'RSPrimary', - RSSecondary: 'RSSecondary', - RSArbiter: 'RSArbiter', - RSOther: 'RSOther', - RSGhost: 'RSGhost', - Unknown: 'Unknown' -}; - -const TOPOLOGY_DEFAULTS = { - useUnifiedTopology: true, - localThresholdMS: 15, - serverSelectionTimeoutMS: 30000, - heartbeatFrequencyMS: 10000, - minHeartbeatFrequencyMS: 500 -}; - -function drainTimerQueue(queue) { - queue.forEach(clearTimeout); - queue.clear(); -} - -function clearAndRemoveTimerFrom(timer, timers) { - clearTimeout(timer); - return timers.delete(timer); -} - -module.exports = { - STATE_CLOSING, - STATE_CLOSED, - STATE_CONNECTING, - STATE_CONNECTED, - TOPOLOGY_DEFAULTS, - TopologyType, - ServerType, - drainTimerQueue, - clearAndRemoveTimerFrom -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/events.js b/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/events.js deleted file mode 100644 index 08a14ad..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/events.js +++ /dev/null @@ -1,124 +0,0 @@ -'use strict'; - -/** - * Published when server description changes, but does NOT include changes to the RTT. - * - * @property {Object} topologyId A unique identifier for the topology - * @property {ServerAddress} address The address (host/port pair) of the server - * @property {ServerDescription} previousDescription The previous server description - * @property {ServerDescription} newDescription The new server description - */ -class ServerDescriptionChangedEvent { - constructor(topologyId, address, previousDescription, newDescription) { - Object.assign(this, { topologyId, address, previousDescription, newDescription }); - } -} - -/** - * Published when server is initialized. - * - * @property {Object} topologyId A unique identifier for the topology - * @property {ServerAddress} address The address (host/port pair) of the server - */ -class ServerOpeningEvent { - constructor(topologyId, address) { - Object.assign(this, { topologyId, address }); - } -} - -/** - * Published when server is closed. - * - * @property {ServerAddress} address The address (host/port pair) of the server - * @property {Object} topologyId A unique identifier for the topology - */ -class ServerClosedEvent { - constructor(topologyId, address) { - Object.assign(this, { topologyId, address }); - } -} - -/** - * Published when topology description changes. - * - * @property {Object} topologyId - * @property {TopologyDescription} previousDescription The old topology description - * @property {TopologyDescription} newDescription The new topology description - */ -class TopologyDescriptionChangedEvent { - constructor(topologyId, previousDescription, newDescription) { - Object.assign(this, { topologyId, previousDescription, newDescription }); - } -} - -/** - * Published when topology is initialized. - * - * @param {Object} topologyId A unique identifier for the topology - */ -class TopologyOpeningEvent { - constructor(topologyId) { - Object.assign(this, { topologyId }); - } -} - -/** - * Published when topology is closed. - * - * @param {Object} topologyId A unique identifier for the topology - */ -class TopologyClosedEvent { - constructor(topologyId) { - Object.assign(this, { topologyId }); - } -} - -/** - * Fired when the server monitor’s ismaster command is started - immediately before - * the ismaster command is serialized into raw BSON and written to the socket. - * - * @property {Object} connectionId The connection id for the command - */ -class ServerHeartbeatStartedEvent { - constructor(connectionId) { - Object.assign(this, { connectionId }); - } -} - -/** - * Fired when the server monitor’s ismaster succeeds. - * - * @param {Number} duration The execution time of the event in ms - * @param {Object} reply The command reply - * @param {Object} connectionId The connection id for the command - */ -class ServerHeartbeatSucceededEvent { - constructor(duration, reply, connectionId) { - Object.assign(this, { connectionId, duration, reply }); - } -} - -/** - * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. - * - * @param {Number} duration The execution time of the event in ms - * @param {MongoError|Object} failure The command failure - * @param {Object} connectionId The connection id for the command - */ -class ServerHeartbeatFailedEvent { - constructor(duration, failure, connectionId) { - Object.assign(this, { connectionId, duration, failure }); - } -} - -module.exports = { - ServerDescriptionChangedEvent, - ServerOpeningEvent, - ServerClosedEvent, - TopologyDescriptionChangedEvent, - TopologyOpeningEvent, - TopologyClosedEvent, - ServerHeartbeatStartedEvent, - ServerHeartbeatSucceededEvent, - ServerHeartbeatFailedEvent -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/monitor.js b/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/monitor.js deleted file mode 100644 index a5ddff8..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/monitor.js +++ /dev/null @@ -1,251 +0,0 @@ -'use strict'; - -const ServerType = require('./common').ServerType; -const calculateDurationInMs = require('../utils').calculateDurationInMs; -const EventEmitter = require('events'); -const connect = require('../connection/connect'); -const Connection = require('../../cmap/connection').Connection; -const common = require('./common'); -const makeStateMachine = require('../utils').makeStateMachine; -const MongoError = require('../error').MongoError; - -const sdamEvents = require('./events'); -const ServerHeartbeatStartedEvent = sdamEvents.ServerHeartbeatStartedEvent; -const ServerHeartbeatSucceededEvent = sdamEvents.ServerHeartbeatSucceededEvent; -const ServerHeartbeatFailedEvent = sdamEvents.ServerHeartbeatFailedEvent; - -const kServer = Symbol('server'); -const kMonitorId = Symbol('monitorId'); -const kConnection = Symbol('connection'); -const kCancellationToken = Symbol('cancellationToken'); -const kLastCheckTime = Symbol('lastCheckTime'); - -const STATE_CLOSED = common.STATE_CLOSED; -const STATE_CLOSING = common.STATE_CLOSING; -const STATE_IDLE = 'idle'; -const STATE_MONITORING = 'monitoring'; -const stateTransition = makeStateMachine({ - [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED], - [STATE_CLOSED]: [STATE_CLOSED, STATE_MONITORING], - [STATE_IDLE]: [STATE_IDLE, STATE_MONITORING, STATE_CLOSING], - [STATE_MONITORING]: [STATE_MONITORING, STATE_IDLE, STATE_CLOSING] -}); - -const INVALID_REQUEST_CHECK_STATES = new Set([STATE_CLOSING, STATE_CLOSED, STATE_MONITORING]); - -class Monitor extends EventEmitter { - constructor(server, options) { - super(options); - - this[kServer] = server; - this[kConnection] = undefined; - this[kCancellationToken] = new EventEmitter(); - this[kCancellationToken].setMaxListeners(Infinity); - this.s = { - state: STATE_CLOSED - }; - - this.address = server.description.address; - this.options = Object.freeze({ - connectTimeoutMS: - typeof options.connectionTimeout === 'number' - ? options.connectionTimeout - : typeof options.connectTimeoutMS === 'number' - ? options.connectTimeoutMS - : 10000, - heartbeatFrequencyMS: - typeof options.heartbeatFrequencyMS === 'number' ? options.heartbeatFrequencyMS : 10000, - minHeartbeatFrequencyMS: - typeof options.minHeartbeatFrequencyMS === 'number' ? options.minHeartbeatFrequencyMS : 500 - }); - - // TODO: refactor this to pull it directly from the pool, requires new ConnectionPool integration - const addressParts = server.description.address.split(':'); - this.connectOptions = Object.freeze( - Object.assign( - { - id: '', - host: addressParts[0], - port: parseInt(addressParts[1], 10), - bson: server.s.bson, - connectionType: Connection - }, - server.s.options, - this.options, - - // force BSON serialization options - { - raw: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: true - } - ) - ); - } - - connect() { - if (this.s.state !== STATE_CLOSED) { - return; - } - - monitorServer(this); - } - - requestCheck() { - if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { - return; - } - - const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; - const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; - const remainingTime = heartbeatFrequencyMS - calculateDurationInMs(this[kLastCheckTime]); - if (remainingTime > minHeartbeatFrequencyMS && this[kMonitorId]) { - clearTimeout(this[kMonitorId]); - rescheduleMonitoring(this, minHeartbeatFrequencyMS); - return; - } - - if (this[kMonitorId]) { - clearTimeout(this[kMonitorId]); - } - - monitorServer(this); - } - - close() { - if (this.s.state === STATE_CLOSED || this.s.state === STATE_CLOSING) { - return; - } - - stateTransition(this, STATE_CLOSING); - this[kCancellationToken].emit('cancel'); - if (this[kMonitorId]) { - clearTimeout(this[kMonitorId]); - } - - if (this[kConnection]) { - this[kConnection].destroy({ force: true }); - } - - this.emit('close'); - stateTransition(this, STATE_CLOSED); - } -} - -function checkServer(monitor, callback) { - if (monitor[kConnection] && monitor[kConnection].closed) { - monitor[kConnection] = undefined; - } - - const start = process.hrtime(); - monitor.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(monitor.address)); - - function failureHandler(err) { - monitor.emit( - 'serverHeartbeatFailed', - new ServerHeartbeatFailedEvent(calculateDurationInMs(start), err, monitor.address) - ); - - callback(err); - } - - function successHandler(isMaster) { - monitor.emit( - 'serverHeartbeatSucceeded', - new ServerHeartbeatSucceededEvent(calculateDurationInMs(start), isMaster, monitor.address) - ); - - return callback(undefined, isMaster); - } - - if (monitor[kConnection] != null) { - const connectTimeoutMS = monitor.options.connectTimeoutMS; - monitor[kConnection].command( - 'admin.$cmd', - { ismaster: true }, - { socketTimeout: connectTimeoutMS }, - (err, result) => { - if (err) { - failureHandler(err); - return; - } - - successHandler(result.result); - } - ); - - return; - } - - // connecting does an implicit `ismaster` - connect(monitor.connectOptions, monitor[kCancellationToken], (err, conn) => { - if (err) { - monitor[kConnection] = undefined; - failureHandler(err); - return; - } - - if (monitor.s.state === STATE_CLOSING || monitor.s.state === STATE_CLOSED) { - conn.destroy({ force: true }); - failureHandler(new MongoError('monitor was destroyed')); - return; - } - - monitor[kConnection] = conn; - successHandler(conn.ismaster); - }); -} - -function monitorServer(monitor) { - stateTransition(monitor, STATE_MONITORING); - - // TODO: the next line is a legacy event, remove in v4 - process.nextTick(() => monitor.emit('monitoring', monitor[kServer])); - - checkServer(monitor, e0 => { - if (e0 == null) { - rescheduleMonitoring(monitor); - return; - } - - // otherwise an error occured on initial discovery, also bail - if (monitor[kServer].description.type === ServerType.Unknown) { - monitor.emit('resetServer', e0); - rescheduleMonitoring(monitor); - return; - } - - // According to the SDAM specification's "Network error during server check" section, if - // an ismaster call fails we reset the server's pool. If a server was once connected, - // change its type to `Unknown` only after retrying once. - monitor.emit('resetConnectionPool'); - - checkServer(monitor, e1 => { - if (e1) { - monitor.emit('resetServer', e1); - } - - rescheduleMonitoring(monitor); - }); - }); -} - -function rescheduleMonitoring(monitor, ms) { - const heartbeatFrequencyMS = monitor.options.heartbeatFrequencyMS; - if (monitor.s.state === STATE_CLOSING || monitor.s.state === STATE_CLOSED) { - return; - } - - stateTransition(monitor, STATE_IDLE); - - monitor[kLastCheckTime] = process.hrtime(); - monitor[kMonitorId] = setTimeout(() => { - monitor[kMonitorId] = undefined; - monitor.requestCheck(); - }, ms || heartbeatFrequencyMS); -} - -module.exports = { - Monitor -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/server.js b/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/server.js deleted file mode 100644 index 031d34d..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/server.js +++ /dev/null @@ -1,495 +0,0 @@ -'use strict'; -const EventEmitter = require('events'); -const ConnectionPool = require('../../cmap/connection_pool').ConnectionPool; -const CMAP_EVENT_NAMES = require('../../cmap/events').CMAP_EVENT_NAMES; -const MongoError = require('../error').MongoError; -const relayEvents = require('../utils').relayEvents; -const BSON = require('../connection/utils').retrieveBSON(); -const Logger = require('../connection/logger'); -const ServerDescription = require('./server_description').ServerDescription; -const ReadPreference = require('../topologies/read_preference'); -const Monitor = require('./monitor').Monitor; -const MongoNetworkError = require('../error').MongoNetworkError; -const collationNotSupported = require('../utils').collationNotSupported; -const debugOptions = require('../connection/utils').debugOptions; -const isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError; -const isNetworkTimeoutError = require('../error').isNetworkTimeoutError; -const isNodeShuttingDownError = require('../error').isNodeShuttingDownError; -const maxWireVersion = require('../utils').maxWireVersion; -const makeStateMachine = require('../utils').makeStateMachine; -const common = require('./common'); - -// Used for filtering out fields for logging -const DEBUG_FIELDS = [ - 'reconnect', - 'reconnectTries', - 'reconnectInterval', - 'emitError', - 'cursorFactory', - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'checkServerIdentity', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'key', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'servername' -]; - -const STATE_CLOSING = common.STATE_CLOSING; -const STATE_CLOSED = common.STATE_CLOSED; -const STATE_CONNECTING = common.STATE_CONNECTING; -const STATE_CONNECTED = common.STATE_CONNECTED; -const stateTransition = makeStateMachine({ - [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], - [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], - [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], - [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] -}); - -const kMonitor = Symbol('monitor'); - -/** - * - * @fires Server#serverHeartbeatStarted - * @fires Server#serverHeartbeatSucceeded - * @fires Server#serverHeartbeatFailed - */ -class Server extends EventEmitter { - /** - * Create a server - * - * @param {ServerDescription} description - * @param {Object} options - */ - constructor(description, options, topology) { - super(); - - this.s = { - // the server description - description, - // a saved copy of the incoming options - options, - // the server logger - logger: Logger('Server', options), - // the bson parser - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // the server state - state: STATE_CLOSED, - credentials: options.credentials, - topology - }; - - // create the connection pool - // NOTE: this used to happen in `connect`, we supported overriding pool options there - const addressParts = this.description.address.split(':'); - const poolOptions = Object.assign( - { host: addressParts[0], port: parseInt(addressParts[1], 10), bson: this.s.bson }, - options - ); - - this.s.pool = new ConnectionPool(poolOptions); - relayEvents( - this.s.pool, - this, - ['commandStarted', 'commandSucceeded', 'commandFailed'].concat(CMAP_EVENT_NAMES) - ); - - this.s.pool.on('clusterTimeReceived', clusterTime => { - this.clusterTime = clusterTime; - }); - - // create the monitor - this[kMonitor] = new Monitor(this, this.s.options); - relayEvents(this[kMonitor], this, [ - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - - // legacy events - 'monitoring' - ]); - - this[kMonitor].on('resetConnectionPool', () => { - this.s.pool.clear(); - }); - - this[kMonitor].on('resetServer', error => markServerUnknown(this, error)); - this[kMonitor].on('serverHeartbeatSucceeded', event => { - this.emit( - 'descriptionReceived', - new ServerDescription(this.description.address, event.reply, { - roundTripTime: calculateRoundTripTime(this.description.roundTripTime, event.duration) - }) - ); - - if (this.s.state === STATE_CONNECTING) { - stateTransition(this, STATE_CONNECTED); - this.emit('connect', this); - } - }); - } - - get description() { - return this.s.description; - } - - get name() { - return this.s.description.address; - } - - get autoEncrypter() { - if (this.s.options && this.s.options.autoEncrypter) { - return this.s.options.autoEncrypter; - } - return null; - } - - /** - * Initiate server connect - */ - connect() { - if (this.s.state !== STATE_CLOSED) { - return; - } - - stateTransition(this, STATE_CONNECTING); - this[kMonitor].connect(); - } - - /** - * Destroy the server connection - * - * @param {object} [options] Optional settings - * @param {Boolean} [options.force=false] Force destroy the pool - */ - destroy(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { force: false }, options); - - if (this.s.state === STATE_CLOSED) { - if (typeof callback === 'function') { - callback(); - } - - return; - } - - stateTransition(this, STATE_CLOSING); - - this[kMonitor].close(); - this.s.pool.close(options, err => { - stateTransition(this, STATE_CLOSED); - this.emit('closed'); - if (typeof callback === 'function') { - callback(err); - } - }); - } - - /** - * Immediately schedule monitoring of this server. If there already an attempt being made - * this will be a no-op. - */ - requestCheck() { - this[kMonitor].requestCheck(); - } - - /** - * Execute a command - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {object} [options] Optional settings - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. - * @param {ClientSession} [options.session] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - command(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { - callback(new MongoError('server is closed')); - return; - } - - const error = basicReadValidations(this, options); - if (error) { - return callback(error); - } - - // Clone the options - options = Object.assign({}, options, { wireProtocolCommand: false }); - - // Debug log - if (this.s.logger.isDebug()) { - this.s.logger.debug( - `executing command [${JSON.stringify({ - ns, - cmd, - options: debugOptions(DEBUG_FIELDS, options) - })}] against ${this.name}` - ); - } - - // error if collation not supported - if (collationNotSupported(this, cmd)) { - callback(new MongoError(`server ${this.name} does not support collation`)); - return; - } - - this.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(this, err); - return cb(err); - } - - conn.command(ns, cmd, options, makeOperationHandler(this, options, cb)); - }, callback); - } - - /** - * Execute a query against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command document for the query - * @param {object} options Optional settings - * @param {function} callback - */ - query(ns, cmd, cursorState, options, callback) { - if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { - callback(new MongoError('server is closed')); - return; - } - - this.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(this, err); - return cb(err); - } - - conn.query(ns, cmd, cursorState, options, makeOperationHandler(this, options, cb)); - }, callback); - } - - /** - * Execute a `getMore` against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {object} options Optional settings - * @param {function} callback - */ - getMore(ns, cursorState, batchSize, options, callback) { - if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { - callback(new MongoError('server is closed')); - return; - } - - this.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(this, err); - return cb(err); - } - - conn.getMore(ns, cursorState, batchSize, options, makeOperationHandler(this, options, cb)); - }, callback); - } - - /** - * Execute a `killCursors` command against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {function} callback - */ - killCursors(ns, cursorState, callback) { - if (this.s.state === STATE_CLOSING || this.s.state === STATE_CLOSED) { - if (typeof callback === 'function') { - callback(new MongoError('server is closed')); - } - - return; - } - - this.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(this, err); - return cb(err); - } - - conn.killCursors(ns, cursorState, makeOperationHandler(this, null, cb)); - }, callback); - } - - /** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - insert(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback); - } - - /** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - update(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback); - } - - /** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - remove(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback); - } -} - -Object.defineProperty(Server.prototype, 'clusterTime', { - get: function() { - return this.s.topology.clusterTime; - }, - set: function(clusterTime) { - this.s.topology.clusterTime = clusterTime; - } -}); - -function calculateRoundTripTime(oldRtt, duration) { - const alpha = 0.2; - return alpha * duration + (1 - alpha) * oldRtt; -} - -function basicReadValidations(server, options) { - if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { - return new MongoError('readPreference must be an instance of ReadPreference'); - } -} - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const server = args.server; - const op = args.op; - const ns = args.ns; - const ops = Array.isArray(args.ops) ? args.ops : [args.ops]; - - if (server.s.state === STATE_CLOSING || server.s.state === STATE_CLOSED) { - callback(new MongoError('server is closed')); - return; - } - - if (collationNotSupported(server, options)) { - callback(new MongoError(`server ${server.name} does not support collation`)); - return; - } - - server.s.pool.withConnection((err, conn, cb) => { - if (err) { - markServerUnknown(server, err); - return cb(err); - } - - conn[op](ns, ops, options, makeOperationHandler(server, options, cb)); - }, callback); -} - -function markServerUnknown(server, error) { - server.emit( - 'descriptionReceived', - new ServerDescription(server.description.address, null, { error }) - ); -} - -function makeOperationHandler(server, options, callback) { - const session = options && options.session; - - return function handleOperationResult(err, result) { - if (err) { - if (err instanceof MongoNetworkError) { - if (session && !session.hasEnded) { - session.serverSession.isDirty = true; - } - - if (!isNetworkTimeoutError(err)) { - markServerUnknown(server, err); - server.s.pool.clear(); - } - } else if (isSDAMUnrecoverableError(err)) { - if (maxWireVersion(server) <= 7 || isNodeShuttingDownError(err)) { - server.s.pool.clear(); - } - - markServerUnknown(server, err); - process.nextTick(() => server.requestCheck()); - } - } - - callback(err, result); - }; -} - -module.exports = { - Server -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/server_description.js b/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/server_description.js deleted file mode 100644 index 1a26c06..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/server_description.js +++ /dev/null @@ -1,181 +0,0 @@ -'use strict'; - -const arrayStrictEqual = require('../utils').arrayStrictEqual; -const tagsStrictEqual = require('../utils').tagsStrictEqual; -const errorStrictEqual = require('../utils').errorStrictEqual; -const ServerType = require('./common').ServerType; - -const WRITABLE_SERVER_TYPES = new Set([ - ServerType.RSPrimary, - ServerType.Standalone, - ServerType.Mongos -]); - -const DATA_BEARING_SERVER_TYPES = new Set([ - ServerType.RSPrimary, - ServerType.RSSecondary, - ServerType.Mongos, - ServerType.Standalone -]); - -const ISMASTER_FIELDS = [ - 'minWireVersion', - 'maxWireVersion', - 'maxBsonObjectSize', - 'maxMessageSizeBytes', - 'maxWriteBatchSize', - 'compression', - 'me', - 'hosts', - 'passives', - 'arbiters', - 'tags', - 'setName', - 'setVersion', - 'electionId', - 'primary', - 'logicalSessionTimeoutMinutes', - 'saslSupportedMechs', - '__nodejs_mock_server__', - '$clusterTime' -]; - -/** - * The client's view of a single server, based on the most recent ismaster outcome. - * - * Internal type, not meant to be directly instantiated - */ -class ServerDescription { - /** - * Create a ServerDescription - * @param {String} address The address of the server - * @param {Object} [ismaster] An optional ismaster response for this server - * @param {Object} [options] Optional settings - * @param {Number} [options.roundTripTime] The round trip time to ping this server (in ms) - */ - constructor(address, ismaster, options) { - options = options || {}; - ismaster = Object.assign( - { - minWireVersion: 0, - maxWireVersion: 0, - hosts: [], - passives: [], - arbiters: [], - tags: [] - }, - ismaster - ); - - this.address = address; - this.error = options.error; - this.roundTripTime = options.roundTripTime || -1; - this.lastUpdateTime = Date.now(); - this.lastWriteDate = ismaster.lastWrite ? ismaster.lastWrite.lastWriteDate : null; - this.opTime = ismaster.lastWrite ? ismaster.lastWrite.opTime : null; - this.type = parseServerType(ismaster); - - // direct mappings - ISMASTER_FIELDS.forEach(field => { - if (typeof ismaster[field] !== 'undefined') this[field] = ismaster[field]; - }); - - // normalize case for hosts - if (this.me) this.me = this.me.toLowerCase(); - this.hosts = this.hosts.map(host => host.toLowerCase()); - this.passives = this.passives.map(host => host.toLowerCase()); - this.arbiters = this.arbiters.map(host => host.toLowerCase()); - } - - get allHosts() { - return this.hosts.concat(this.arbiters).concat(this.passives); - } - - /** - * @return {Boolean} Is this server available for reads - */ - get isReadable() { - return this.type === ServerType.RSSecondary || this.isWritable; - } - - /** - * @return {Boolean} Is this server data bearing - */ - get isDataBearing() { - return DATA_BEARING_SERVER_TYPES.has(this.type); - } - - /** - * @return {Boolean} Is this server available for writes - */ - get isWritable() { - return WRITABLE_SERVER_TYPES.has(this.type); - } - - /** - * Determines if another `ServerDescription` is equal to this one per the rules defined - * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec} - * - * @param {ServerDescription} other - * @return {Boolean} - */ - equals(other) { - return ( - other != null && - errorStrictEqual(this.error, other.error) && - this.type === other.type && - this.minWireVersion === other.minWireVersion && - this.me === other.me && - arrayStrictEqual(this.hosts, other.hosts) && - tagsStrictEqual(this.tags, other.tags) && - this.setName === other.setName && - this.setVersion === other.setVersion && - (this.electionId - ? other.electionId && this.electionId.equals(other.electionId) - : this.electionId === other.electionId) && - this.primary === other.primary && - this.logicalSessionTimeoutMinutes === other.logicalSessionTimeoutMinutes - ); - } -} - -/** - * Parses an `ismaster` message and determines the server type - * - * @param {Object} ismaster The `ismaster` message to parse - * @return {ServerType} - */ -function parseServerType(ismaster) { - if (!ismaster || !ismaster.ok) { - return ServerType.Unknown; - } - - if (ismaster.isreplicaset) { - return ServerType.RSGhost; - } - - if (ismaster.msg && ismaster.msg === 'isdbgrid') { - return ServerType.Mongos; - } - - if (ismaster.setName) { - if (ismaster.hidden) { - return ServerType.RSOther; - } else if (ismaster.ismaster) { - return ServerType.RSPrimary; - } else if (ismaster.secondary) { - return ServerType.RSSecondary; - } else if (ismaster.arbiterOnly) { - return ServerType.RSArbiter; - } else { - return ServerType.RSOther; - } - } - - return ServerType.Standalone; -} - -module.exports = { - ServerDescription, - parseServerType -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/server_selection.js b/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/server_selection.js deleted file mode 100644 index 46657d3..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/server_selection.js +++ /dev/null @@ -1,250 +0,0 @@ -'use strict'; -const ServerType = require('./common').ServerType; -const TopologyType = require('./common').TopologyType; -const ReadPreference = require('../topologies/read_preference'); -const MongoError = require('../error').MongoError; - -// max staleness constants -const IDLE_WRITE_PERIOD = 10000; -const SMALLEST_MAX_STALENESS_SECONDS = 90; - -/** - * Returns a server selector that selects for writable servers - */ -function writableServerSelector() { - return function(topologyDescription, servers) { - return latencyWindowReducer( - topologyDescription, - servers.filter(s => s.isWritable) - ); - }; -} - -/** - * Reduces the passed in array of servers by the rules of the "Max Staleness" specification - * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst - * - * @param {ReadPreference} readPreference The read preference providing max staleness guidance - * @param {topologyDescription} topologyDescription The topology description - * @param {ServerDescription[]} servers The list of server descriptions to be reduced - * @return {ServerDescription[]} The list of servers that satisfy the requirements of max staleness - */ -function maxStalenessReducer(readPreference, topologyDescription, servers) { - if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { - return servers; - } - - const maxStaleness = readPreference.maxStalenessSeconds; - const maxStalenessVariance = - (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; - if (maxStaleness < maxStalenessVariance) { - throw new MongoError(`maxStalenessSeconds must be at least ${maxStalenessVariance} seconds`); - } - - if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { - throw new MongoError( - `maxStalenessSeconds must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` - ); - } - - if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { - const primary = servers.filter(primaryFilter)[0]; - return servers.reduce((result, server) => { - const stalenessMS = - server.lastUpdateTime - - server.lastWriteDate - - (primary.lastUpdateTime - primary.lastWriteDate) + - topologyDescription.heartbeatFrequencyMS; - - const staleness = stalenessMS / 1000; - if (staleness <= readPreference.maxStalenessSeconds) result.push(server); - return result; - }, []); - } else if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { - const sMax = servers.reduce((max, s) => (s.lastWriteDate > max.lastWriteDate ? s : max)); - return servers.reduce((result, server) => { - const stalenessMS = - sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; - - const staleness = stalenessMS / 1000; - if (staleness <= readPreference.maxStalenessSeconds) result.push(server); - return result; - }, []); - } - - return servers; -} - -/** - * Determines whether a server's tags match a given set of tags - * - * @param {String[]} tagSet The requested tag set to match - * @param {String[]} serverTags The server's tags - */ -function tagSetMatch(tagSet, serverTags) { - const keys = Object.keys(tagSet); - const serverTagKeys = Object.keys(serverTags); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { - return false; - } - } - - return true; -} - -/** - * Reduces a set of server descriptions based on tags requested by the read preference - * - * @param {ReadPreference} readPreference The read preference providing the requested tags - * @param {ServerDescription[]} servers The list of server descriptions to reduce - * @return {ServerDescription[]} The list of servers matching the requested tags - */ -function tagSetReducer(readPreference, servers) { - if ( - readPreference.tags == null || - (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) - ) { - return servers; - } - - for (let i = 0; i < readPreference.tags.length; ++i) { - const tagSet = readPreference.tags[i]; - const serversMatchingTagset = servers.reduce((matched, server) => { - if (tagSetMatch(tagSet, server.tags)) matched.push(server); - return matched; - }, []); - - if (serversMatchingTagset.length) { - return serversMatchingTagset; - } - } - - return []; -} - -/** - * Reduces a list of servers to ensure they fall within an acceptable latency window. This is - * further specified in the "Server Selection" specification, found here: - * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst - * - * @param {topologyDescription} topologyDescription The topology description - * @param {ServerDescription[]} servers The list of servers to reduce - * @returns {ServerDescription[]} The servers which fall within an acceptable latency window - */ -function latencyWindowReducer(topologyDescription, servers) { - const low = servers.reduce( - (min, server) => (min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min)), - -1 - ); - - const high = low + topologyDescription.localThresholdMS; - - return servers.reduce((result, server) => { - if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); - return result; - }, []); -} - -// filters -function primaryFilter(server) { - return server.type === ServerType.RSPrimary; -} - -function secondaryFilter(server) { - return server.type === ServerType.RSSecondary; -} - -function nearestFilter(server) { - return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; -} - -function knownFilter(server) { - return server.type !== ServerType.Unknown; -} - -/** - * Returns a function which selects servers based on a provided read preference - * - * @param {ReadPreference} readPreference The read preference to select with - */ -function readPreferenceServerSelector(readPreference) { - if (!readPreference.isValid()) { - throw new TypeError('Invalid read preference specified'); - } - - return function(topologyDescription, servers) { - const commonWireVersion = topologyDescription.commonWireVersion; - if ( - commonWireVersion && - readPreference.minWireVersion && - readPreference.minWireVersion > commonWireVersion - ) { - throw new MongoError( - `Minimum wire version '${readPreference.minWireVersion}' required, but found '${commonWireVersion}'` - ); - } - - if (topologyDescription.type === TopologyType.Unknown) { - return []; - } - - if ( - topologyDescription.type === TopologyType.Single || - topologyDescription.type === TopologyType.Sharded - ) { - return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); - } - - if (readPreference.mode === ReadPreference.PRIMARY) { - return servers.filter(primaryFilter); - } - - if (readPreference.mode === ReadPreference.SECONDARY) { - return latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(secondaryFilter); - } else if (readPreference.mode === ReadPreference.NEAREST) { - return latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(nearestFilter); - } else if (readPreference.mode === ReadPreference.SECONDARY_PREFERRED) { - const result = latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(secondaryFilter); - - return result.length === 0 ? servers.filter(primaryFilter) : result; - } else if (readPreference.mode === ReadPreference.PRIMARY_PREFERRED) { - const result = servers.filter(primaryFilter); - if (result.length) { - return result; - } - - return latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(secondaryFilter); - } - }; -} - -module.exports = { - writableServerSelector, - readPreferenceServerSelector -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/srv_polling.js b/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/srv_polling.js deleted file mode 100644 index 2c0b6ee..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/srv_polling.js +++ /dev/null @@ -1,135 +0,0 @@ -'use strict'; - -const Logger = require('../connection/logger'); -const EventEmitter = require('events').EventEmitter; -const dns = require('dns'); -/** - * Determines whether a provided address matches the provided parent domain in order - * to avoid certain attack vectors. - * - * @param {String} srvAddress The address to check against a domain - * @param {String} parentDomain The domain to check the provided address against - * @return {Boolean} Whether the provided address matches the parent domain - */ -function matchesParentDomain(srvAddress, parentDomain) { - const regex = /^.*?\./; - const srv = `.${srvAddress.replace(regex, '')}`; - const parent = `.${parentDomain.replace(regex, '')}`; - return srv.endsWith(parent); -} - -class SrvPollingEvent { - constructor(srvRecords) { - this.srvRecords = srvRecords; - } - - addresses() { - return new Set(this.srvRecords.map(record => `${record.name}:${record.port}`)); - } -} - -class SrvPoller extends EventEmitter { - /** - * @param {object} options - * @param {string} options.srvHost - * @param {number} [options.heartbeatFrequencyMS] - * @param {function} [options.logger] - * @param {string} [options.loggerLevel] - */ - constructor(options) { - super(); - - if (!options || !options.srvHost) { - throw new TypeError('options for SrvPoller must exist and include srvHost'); - } - - this.srvHost = options.srvHost; - this.rescanSrvIntervalMS = 60000; - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - this.logger = Logger('srvPoller', options); - - this.haMode = false; - this.generation = 0; - - this._timeout = null; - } - - get srvAddress() { - return `_mongodb._tcp.${this.srvHost}`; - } - - get intervalMS() { - return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMS; - } - - start() { - if (!this._timeout) { - this.schedule(); - } - } - - stop() { - if (this._timeout) { - clearTimeout(this._timeout); - this.generation += 1; - this._timeout = null; - } - } - - schedule() { - clearTimeout(this._timeout); - this._timeout = setTimeout(() => this._poll(), this.intervalMS); - } - - success(srvRecords) { - this.haMode = false; - this.schedule(); - this.emit('srvRecordDiscovery', new SrvPollingEvent(srvRecords)); - } - - failure(message, obj) { - this.logger.warn(message, obj); - this.haMode = true; - this.schedule(); - } - - parentDomainMismatch(srvRecord) { - this.logger.warn( - `parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`, - srvRecord - ); - } - - _poll() { - const generation = this.generation; - dns.resolveSrv(this.srvAddress, (err, srvRecords) => { - if (generation !== this.generation) { - return; - } - - if (err) { - this.failure('DNS error', err); - return; - } - - const finalAddresses = []; - srvRecords.forEach(record => { - if (matchesParentDomain(record.name, this.srvHost)) { - finalAddresses.push(record); - } else { - this.parentDomainMismatch(record); - } - }); - - if (!finalAddresses.length) { - this.failure('No valid addresses found at host'); - return; - } - - this.success(finalAddresses); - }); - } -} - -module.exports.SrvPollingEvent = SrvPollingEvent; -module.exports.SrvPoller = SrvPoller; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/topology.js b/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/topology.js deleted file mode 100644 index cdd9a47..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/topology.js +++ /dev/null @@ -1,1131 +0,0 @@ -'use strict'; -const Denque = require('denque'); -const EventEmitter = require('events'); -const ServerDescription = require('./server_description').ServerDescription; -const ServerType = require('./common').ServerType; -const TopologyDescription = require('./topology_description').TopologyDescription; -const TopologyType = require('./common').TopologyType; -const events = require('./events'); -const Server = require('./server').Server; -const relayEvents = require('../utils').relayEvents; -const ReadPreference = require('../topologies/read_preference'); -const isRetryableWritesSupported = require('../topologies/shared').isRetryableWritesSupported; -const CoreCursor = require('../cursor').CoreCursor; -const deprecate = require('util').deprecate; -const BSON = require('../connection/utils').retrieveBSON(); -const createCompressionInfo = require('../topologies/shared').createCompressionInfo; -const isRetryableError = require('../error').isRetryableError; -const ClientSession = require('../sessions').ClientSession; -const MongoError = require('../error').MongoError; -const MongoServerSelectionError = require('../error').MongoServerSelectionError; -const resolveClusterTime = require('../topologies/shared').resolveClusterTime; -const SrvPoller = require('./srv_polling').SrvPoller; -const getMMAPError = require('../topologies/shared').getMMAPError; -const makeStateMachine = require('../utils').makeStateMachine; -const eachAsync = require('../utils').eachAsync; -const emitDeprecationWarning = require('../../utils').emitDeprecationWarning; -const ServerSessionPool = require('../sessions').ServerSessionPool; -const makeClientMetadata = require('../utils').makeClientMetadata; -const CMAP_EVENT_NAMES = require('../../cmap/events').CMAP_EVENT_NAMES; - -const common = require('./common'); -const drainTimerQueue = common.drainTimerQueue; -const clearAndRemoveTimerFrom = common.clearAndRemoveTimerFrom; - -const serverSelection = require('./server_selection'); -const readPreferenceServerSelector = serverSelection.readPreferenceServerSelector; -const writableServerSelector = serverSelection.writableServerSelector; - -// Global state -let globalTopologyCounter = 0; - -// events that we relay to the `Topology` -const SERVER_RELAY_EVENTS = [ - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - - // NOTE: Legacy events - 'monitoring' -].concat(CMAP_EVENT_NAMES); - -// all events we listen to from `Server` instances -const LOCAL_SERVER_EVENTS = ['connect', 'descriptionReceived', 'close', 'ended']; - -const STATE_CLOSING = common.STATE_CLOSING; -const STATE_CLOSED = common.STATE_CLOSED; -const STATE_CONNECTING = common.STATE_CONNECTING; -const STATE_CONNECTED = common.STATE_CONNECTED; -const stateTransition = makeStateMachine({ - [STATE_CLOSED]: [STATE_CLOSED, STATE_CONNECTING], - [STATE_CONNECTING]: [STATE_CONNECTING, STATE_CLOSING, STATE_CONNECTED, STATE_CLOSED], - [STATE_CONNECTED]: [STATE_CONNECTED, STATE_CLOSING, STATE_CLOSED], - [STATE_CLOSING]: [STATE_CLOSING, STATE_CLOSED] -}); - -const DEPRECATED_OPTIONS = new Set([ - 'autoReconnect', - 'reconnectTries', - 'reconnectInterval', - 'bufferMaxEntries' -]); - -const kCancelled = Symbol('cancelled'); -const kWaitQueue = Symbol('waitQueue'); - -/** - * A container of server instances representing a connection to a MongoDB topology. - * - * @fires Topology#serverOpening - * @fires Topology#serverClosed - * @fires Topology#serverDescriptionChanged - * @fires Topology#topologyOpening - * @fires Topology#topologyClosed - * @fires Topology#topologyDescriptionChanged - * @fires Topology#serverHeartbeatStarted - * @fires Topology#serverHeartbeatSucceeded - * @fires Topology#serverHeartbeatFailed - */ -class Topology extends EventEmitter { - /** - * Create a topology - * - * @param {Array|String} [seedlist] a string list, or array of Server instances to connect to - * @param {Object} [options] Optional settings - * @param {Number} [options.localThresholdMS=15] The size of the latency window for selecting among multiple suitable servers - * @param {Number} [options.serverSelectionTimeoutMS=30000] How long to block for server selection before throwing an error - * @param {Number} [options.heartbeatFrequencyMS=10000] The frequency with which topology updates are scheduled - */ - constructor(seedlist, options) { - super(); - if (typeof options === 'undefined' && typeof seedlist !== 'string') { - options = seedlist; - seedlist = []; - - // this is for legacy single server constructor support - if (options.host) { - seedlist.push({ host: options.host, port: options.port }); - } - } - - seedlist = seedlist || []; - if (typeof seedlist === 'string') { - seedlist = parseStringSeedlist(seedlist); - } - - options = Object.assign({}, common.TOPOLOGY_DEFAULTS, options); - options = Object.freeze( - Object.assign(options, { - metadata: makeClientMetadata(options), - compression: { compressors: createCompressionInfo(options) } - }) - ); - - DEPRECATED_OPTIONS.forEach(optionName => { - if (options[optionName]) { - emitDeprecationWarning( - `The option \`${optionName}\` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6`, - 'DeprecationWarning' - ); - } - }); - - const topologyType = topologyTypeFromSeedlist(seedlist, options); - const topologyId = globalTopologyCounter++; - const serverDescriptions = seedlist.reduce((result, seed) => { - if (seed.domain_socket) seed.host = seed.domain_socket; - const address = seed.port ? `${seed.host}:${seed.port}` : `${seed.host}:27017`; - result.set(address, new ServerDescription(address)); - return result; - }, new Map()); - - this[kWaitQueue] = new Denque(); - this.s = { - // the id of this topology - id: topologyId, - // passed in options - options, - // initial seedlist of servers to connect to - seedlist: seedlist, - // initial state - state: STATE_CLOSED, - // the topology description - description: new TopologyDescription( - topologyType, - serverDescriptions, - options.replicaSet, - null, - null, - null, - options - ), - serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, - heartbeatFrequencyMS: options.heartbeatFrequencyMS, - minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS, - // allow users to override the cursor factory - Cursor: options.cursorFactory || CoreCursor, - // the bson parser - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // a map of server instances to normalized addresses - servers: new Map(), - // Server Session Pool - sessionPool: new ServerSessionPool(this), - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise, - credentials: options.credentials, - clusterTime: null, - - // timer management - connectionTimers: new Set() - }; - - if (options.srvHost) { - this.s.srvPoller = - options.srvPoller || - new SrvPoller({ - heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, - srvHost: options.srvHost, // TODO: GET THIS - logger: options.logger, - loggerLevel: options.loggerLevel - }); - this.s.detectTopologyDescriptionChange = ev => { - const previousType = ev.previousDescription.type; - const newType = ev.newDescription.type; - - if (previousType !== TopologyType.Sharded && newType === TopologyType.Sharded) { - this.s.handleSrvPolling = srvPollingHandler(this); - this.s.srvPoller.on('srvRecordDiscovery', this.s.handleSrvPolling); - this.s.srvPoller.start(); - } - }; - - this.on('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); - } - - // NOTE: remove this when NODE-1709 is resolved - this.setMaxListeners(Infinity); - } - - /** - * @return A `TopologyDescription` for this topology - */ - get description() { - return this.s.description; - } - - get parserType() { - return BSON.native ? 'c++' : 'js'; - } - - /** - * Initiate server connect - * - * @param {Object} [options] Optional settings - * @param {Array} [options.auth=null] Array of auth options to apply on connect - * @param {function} [callback] An optional callback called once on the first connected server - */ - connect(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - if (this.s.state === STATE_CONNECTED) { - if (typeof callback === 'function') { - callback(); - } - - return; - } - - stateTransition(this, STATE_CONNECTING); - - // emit SDAM monitoring events - this.emit('topologyOpening', new events.TopologyOpeningEvent(this.s.id)); - - // emit an event for the topology change - this.emit( - 'topologyDescriptionChanged', - new events.TopologyDescriptionChangedEvent( - this.s.id, - new TopologyDescription(TopologyType.Unknown), // initial is always Unknown - this.s.description - ) - ); - - // connect all known servers, then attempt server selection to connect - connectServers(this, Array.from(this.s.description.servers.values())); - - translateReadPreference(options); - const readPreference = options.readPreference || ReadPreference.primary; - this.selectServer(readPreferenceServerSelector(readPreference), options, err => { - if (err) { - this.close(); - - if (typeof callback === 'function') { - callback(err); - } else { - this.emit('error', err); - } - - return; - } - - stateTransition(this, STATE_CONNECTED); - this.emit('open', err, this); - this.emit('connect', this); - - if (typeof callback === 'function') callback(err, this); - }); - } - - /** - * Close this topology - */ - close(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - if (typeof options === 'boolean') { - options = { force: options }; - } - - options = options || {}; - if (this.s.state === STATE_CLOSED || this.s.state === STATE_CLOSING) { - if (typeof callback === 'function') { - callback(); - } - - return; - } - - stateTransition(this, STATE_CLOSING); - - drainWaitQueue(this[kWaitQueue], new MongoError('Topology closed')); - drainTimerQueue(this.s.connectionTimers); - - if (this.s.srvPoller) { - this.s.srvPoller.stop(); - if (this.s.handleSrvPolling) { - this.s.srvPoller.removeListener('srvRecordDiscovery', this.s.handleSrvPolling); - delete this.s.handleSrvPolling; - } - } - - if (this.s.detectTopologyDescriptionChange) { - this.removeListener('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); - delete this.s.detectTopologyDescriptionChange; - } - - this.s.sessions.forEach(session => session.endSession()); - this.s.sessionPool.endAllPooledSessions(() => { - eachAsync( - Array.from(this.s.servers.values()), - (server, cb) => destroyServer(server, this, options, cb), - err => { - this.s.servers.clear(); - - // emit an event for close - this.emit('topologyClosed', new events.TopologyClosedEvent(this.s.id)); - - stateTransition(this, STATE_CLOSED); - this.emit('close'); - - if (typeof callback === 'function') { - callback(err); - } - } - ); - }); - } - - /** - * Selects a server according to the selection predicate provided - * - * @param {function} [selector] An optional selector to select servers by, defaults to a random selection within a latency window - * @param {object} [options] Optional settings related to server selection - * @param {number} [options.serverSelectionTimeoutMS] How long to block for server selection before throwing an error - * @param {function} callback The callback used to indicate success or failure - * @return {Server} An instance of a `Server` meeting the criteria of the predicate provided - */ - selectServer(selector, options, callback) { - if (typeof options === 'function') { - callback = options; - if (typeof selector !== 'function') { - options = selector; - - let readPreference; - if (selector instanceof ReadPreference) { - readPreference = selector; - } else if (typeof selector === 'string') { - readPreference = new ReadPreference(selector); - } else { - translateReadPreference(options); - readPreference = options.readPreference || ReadPreference.primary; - } - - selector = readPreferenceServerSelector(readPreference); - } else { - options = {}; - } - } - - options = Object.assign( - {}, - { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, - options - ); - - const isSharded = this.description.type === TopologyType.Sharded; - const session = options.session; - const transaction = session && session.transaction; - - if (isSharded && transaction && transaction.server) { - callback(undefined, transaction.server); - return; - } - - // support server selection by options with readPreference - let serverSelector = selector; - if (typeof selector === 'object') { - const readPreference = selector.readPreference - ? selector.readPreference - : ReadPreference.primary; - - serverSelector = readPreferenceServerSelector(readPreference); - } - - const waitQueueMember = { - serverSelector, - transaction, - callback - }; - - const serverSelectionTimeoutMS = options.serverSelectionTimeoutMS; - if (serverSelectionTimeoutMS) { - waitQueueMember.timer = setTimeout(() => { - waitQueueMember[kCancelled] = true; - waitQueueMember.timer = undefined; - const timeoutError = new MongoServerSelectionError( - `Server selection timed out after ${serverSelectionTimeoutMS} ms`, - this.description - ); - - waitQueueMember.callback(timeoutError); - }, serverSelectionTimeoutMS); - } - - this[kWaitQueue].push(waitQueueMember); - processWaitQueue(this); - } - - // Sessions related methods - - /** - * @return Whether the topology should initiate selection to determine session support - */ - shouldCheckForSessionSupport() { - if (this.description.type === TopologyType.Single) { - return !this.description.hasKnownServers; - } - - return !this.description.hasDataBearingServers; - } - - /** - * @return Whether sessions are supported on the current topology - */ - hasSessionSupport() { - return this.description.logicalSessionTimeoutMinutes != null; - } - - /** - * Start a logical session - */ - startSession(options, clientOptions) { - const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); - session.once('ended', () => { - this.s.sessions.delete(session); - }); - - this.s.sessions.add(session); - return session; - } - - /** - * Send endSessions command(s) with the given session ids - * - * @param {Array} sessions The sessions to end - * @param {function} [callback] - */ - endSessions(sessions, callback) { - if (!Array.isArray(sessions)) { - sessions = [sessions]; - } - - this.command( - 'admin.$cmd', - { endSessions: sessions }, - { readPreference: ReadPreference.primaryPreferred, noResponse: true }, - () => { - // intentionally ignored, per spec - if (typeof callback === 'function') callback(); - } - ); - } - - /** - * Update the internal TopologyDescription with a ServerDescription - * - * @param {object} serverDescription The server to update in the internal list of server descriptions - */ - serverUpdateHandler(serverDescription) { - if (!this.s.description.hasServer(serverDescription.address)) { - return; - } - - // these will be used for monitoring events later - const previousTopologyDescription = this.s.description; - const previousServerDescription = this.s.description.servers.get(serverDescription.address); - - // Driver Sessions Spec: "Whenever a driver receives a cluster time from - // a server it MUST compare it to the current highest seen cluster time - // for the deployment. If the new cluster time is higher than the - // highest seen cluster time it MUST become the new highest seen cluster - // time. Two cluster times are compared using only the BsonTimestamp - // value of the clusterTime embedded field." - const clusterTime = serverDescription.$clusterTime; - if (clusterTime) { - resolveClusterTime(this, clusterTime); - } - - // If we already know all the information contained in this updated description, then - // we don't need to emit SDAM events, but still need to update the description, in order - // to keep client-tracked attributes like last update time and round trip time up to date - const equalDescriptions = - previousServerDescription && previousServerDescription.equals(serverDescription); - - // first update the TopologyDescription - this.s.description = this.s.description.update(serverDescription); - if (this.s.description.compatibilityError) { - this.emit('error', new MongoError(this.s.description.compatibilityError)); - return; - } - - // emit monitoring events for this change - if (!equalDescriptions) { - this.emit( - 'serverDescriptionChanged', - new events.ServerDescriptionChangedEvent( - this.s.id, - serverDescription.address, - previousServerDescription, - this.s.description.servers.get(serverDescription.address) - ) - ); - } - - // update server list from updated descriptions - updateServers(this, serverDescription); - - // attempt to resolve any outstanding server selection attempts - if (this[kWaitQueue].length > 0) { - processWaitQueue(this); - } - - if (!equalDescriptions) { - this.emit( - 'topologyDescriptionChanged', - new events.TopologyDescriptionChangedEvent( - this.s.id, - previousTopologyDescription, - this.s.description - ) - ); - } - } - - auth(credentials, callback) { - if (typeof credentials === 'function') (callback = credentials), (credentials = null); - if (typeof callback === 'function') callback(null, true); - } - - logout(callback) { - if (typeof callback === 'function') callback(null, true); - } - - // Basic operation support. Eventually this should be moved into command construction - // during the command refactor. - - /** - * Insert one or more documents - * - * @param {String} ns The full qualified namespace for this operation - * @param {Array} ops An array of documents to insert - * @param {Boolean} [options.ordered=true] Execute in order or out of order - * @param {Object} [options.writeConcern] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {ClientSession} [options.session] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - insert(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'insert', ns, ops }, options, callback); - } - - /** - * Perform one or more update operations - * - * @param {string} ns The fully qualified namespace for this operation - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {ClientSession} [options.session] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - update(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'update', ns, ops }, options, callback); - } - - /** - * Perform one or more remove operations - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - remove(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'remove', ns, ops }, options, callback); - } - - /** - * Execute a command - * - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - command(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - translateReadPreference(options); - const readPreference = options.readPreference || ReadPreference.primary; - - this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { - if (err) { - callback(err); - return; - } - - const willRetryWrite = - !options.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(this) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, options, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - server.command(ns, cmd, options, cb); - }); - } - - /** - * Create a new cursor - * - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ - cursor(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - const CursorClass = options.cursorFactory || this.s.Cursor; - translateReadPreference(options); - - return new CursorClass(topology, ns, cmd, options); - } - - get clientMetadata() { - return this.s.options.metadata; - } - - isConnected() { - return this.s.state === STATE_CONNECTED; - } - - isDestroyed() { - return this.s.state === STATE_CLOSED; - } - - unref() { - console.log('not implemented: `unref`'); - } - - // NOTE: There are many places in code where we explicitly check the last isMaster - // to do feature support detection. This should be done any other way, but for - // now we will just return the first isMaster seen, which should suffice. - lastIsMaster() { - const serverDescriptions = Array.from(this.description.servers.values()); - if (serverDescriptions.length === 0) return {}; - - const sd = serverDescriptions.filter(sd => sd.type !== ServerType.Unknown)[0]; - const result = sd || { maxWireVersion: this.description.commonWireVersion }; - return result; - } - - get logicalSessionTimeoutMinutes() { - return this.description.logicalSessionTimeoutMinutes; - } - - get bson() { - return this.s.bson; - } -} - -Object.defineProperty(Topology.prototype, 'clusterTime', { - enumerable: true, - get: function() { - return this.s.clusterTime; - }, - set: function(clusterTime) { - this.s.clusterTime = clusterTime; - } -}); - -// legacy aliases -Topology.prototype.destroy = deprecate( - Topology.prototype.close, - 'destroy() is deprecated, please use close() instead' -); - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Destroys a server, and removes all event listeners from the instance - * - * @param {Server} server - */ -function destroyServer(server, topology, options, callback) { - options = options || {}; - LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); - - server.destroy(options, () => { - topology.emit( - 'serverClosed', - new events.ServerClosedEvent(topology.s.id, server.description.address) - ); - - SERVER_RELAY_EVENTS.forEach(event => server.removeAllListeners(event)); - if (typeof callback === 'function') { - callback(); - } - }); -} - -/** - * Parses a basic seedlist in string form - * - * @param {string} seedlist The seedlist to parse - */ -function parseStringSeedlist(seedlist) { - return seedlist.split(',').map(seed => ({ - host: seed.split(':')[0], - port: seed.split(':')[1] || 27017 - })); -} - -function topologyTypeFromSeedlist(seedlist, options) { - const replicaSet = options.replicaSet || options.setName || options.rs_name; - if (seedlist.length === 1 && !replicaSet) return TopologyType.Single; - if (replicaSet) return TopologyType.ReplicaSetNoPrimary; - return TopologyType.Unknown; -} - -function randomSelection(array) { - return array[Math.floor(Math.random() * array.length)]; -} - -function createAndConnectServer(topology, serverDescription, connectDelay) { - topology.emit( - 'serverOpening', - new events.ServerOpeningEvent(topology.s.id, serverDescription.address) - ); - - const server = new Server(serverDescription, topology.s.options, topology); - relayEvents(server, topology, SERVER_RELAY_EVENTS); - - server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); - - if (connectDelay) { - const connectTimer = setTimeout(() => { - clearAndRemoveTimerFrom(connectTimer, topology.s.connectionTimers); - server.connect(); - }, connectDelay); - - topology.s.connectionTimers.add(connectTimer); - return server; - } - - server.connect(); - return server; -} - -/** - * Create `Server` instances for all initially known servers, connect them, and assign - * them to the passed in `Topology`. - * - * @param {Topology} topology The topology responsible for the servers - * @param {ServerDescription[]} serverDescriptions A list of server descriptions to connect - */ -function connectServers(topology, serverDescriptions) { - topology.s.servers = serverDescriptions.reduce((servers, serverDescription) => { - const server = createAndConnectServer(topology, serverDescription); - servers.set(serverDescription.address, server); - return servers; - }, new Map()); -} - -function updateServers(topology, incomingServerDescription) { - // update the internal server's description - if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { - const server = topology.s.servers.get(incomingServerDescription.address); - server.s.description = incomingServerDescription; - } - - // add new servers for all descriptions we currently don't know about locally - for (const serverDescription of topology.description.servers.values()) { - if (!topology.s.servers.has(serverDescription.address)) { - const server = createAndConnectServer(topology, serverDescription); - topology.s.servers.set(serverDescription.address, server); - } - } - - // for all servers no longer known, remove their descriptions and destroy their instances - for (const entry of topology.s.servers) { - const serverAddress = entry[0]; - if (topology.description.hasServer(serverAddress)) { - continue; - } - - const server = topology.s.servers.get(serverAddress); - topology.s.servers.delete(serverAddress); - - // prepare server for garbage collection - destroyServer(server, topology); - } -} - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const topology = args.topology; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(topology) && - !options.session.inTransaction(); - - topology.selectServer(writableServerSelector(), options, (err, server) => { - if (err) { - callback(err, null); - return; - } - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - err = getMMAPError(err); - return callback(err); - } - - if (willRetryWrite) { - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - } - - return callback(err); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // execute the write operation - server[op](ns, ops, options, handler); - }); -} - -function translateReadPreference(options) { - if (options.readPreference == null) { - return; - } - - let r = options.readPreference; - if (typeof r === 'string') { - options.readPreference = new ReadPreference(r); - } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { - const mode = r.mode || r.preference; - if (mode && typeof mode === 'string') { - options.readPreference = new ReadPreference(mode, r.tags, { - maxStalenessSeconds: r.maxStalenessSeconds - }); - } - } else if (!(r instanceof ReadPreference)) { - throw new TypeError('Invalid read preference: ' + r); - } - - return options; -} - -function srvPollingHandler(topology) { - return function handleSrvPolling(ev) { - const previousTopologyDescription = topology.s.description; - topology.s.description = topology.s.description.updateFromSrvPollingEvent(ev); - if (topology.s.description === previousTopologyDescription) { - // Nothing changed, so return - return; - } - - updateServers(topology); - - topology.emit( - 'topologyDescriptionChanged', - new events.TopologyDescriptionChangedEvent( - topology.s.id, - previousTopologyDescription, - topology.s.description - ) - ); - }; -} - -function drainWaitQueue(queue, err) { - while (queue.length) { - const waitQueueMember = queue.shift(); - clearTimeout(waitQueueMember.timer); - if (!waitQueueMember[kCancelled]) { - waitQueueMember.callback(err); - } - } -} - -function processWaitQueue(topology) { - if (topology.s.state === STATE_CLOSED) { - drainWaitQueue(topology[kWaitQueue], new MongoError('Topology is closed, please connect')); - return; - } - - const serverDescriptions = Array.from(topology.description.servers.values()); - const membersToProcess = topology[kWaitQueue].length; - for (let i = 0; i < membersToProcess && topology[kWaitQueue].length; ++i) { - const waitQueueMember = topology[kWaitQueue].shift(); - if (waitQueueMember[kCancelled]) { - continue; - } - - let selectedDescriptions; - try { - const serverSelector = waitQueueMember.serverSelector; - selectedDescriptions = serverSelector - ? serverSelector(topology.description, serverDescriptions) - : serverDescriptions; - } catch (e) { - clearTimeout(waitQueueMember.timer); - waitQueueMember.callback(e); - continue; - } - - if (selectedDescriptions.length === 0) { - topology[kWaitQueue].push(waitQueueMember); - continue; - } - - const selectedServerDescription = randomSelection(selectedDescriptions); - const selectedServer = topology.s.servers.get(selectedServerDescription.address); - const transaction = waitQueueMember.transaction; - const isSharded = topology.description.type === TopologyType.Sharded; - if (isSharded && transaction && transaction.isActive) { - transaction.pinServer(selectedServer); - } - - clearTimeout(waitQueueMember.timer); - waitQueueMember.callback(undefined, selectedServer); - } - - if (topology[kWaitQueue].length > 0) { - // ensure all server monitors attempt monitoring soon - topology.s.servers.forEach(server => process.nextTick(() => server.requestCheck())); - } -} - -/** - * A server opening SDAM monitoring event - * - * @event Topology#serverOpening - * @type {ServerOpeningEvent} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Topology#serverClosed - * @type {ServerClosedEvent} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Topology#serverDescriptionChanged - * @type {ServerDescriptionChangedEvent} - */ - -/** - * A topology open SDAM event - * - * @event Topology#topologyOpening - * @type {TopologyOpeningEvent} - */ - -/** - * A topology closed SDAM event - * - * @event Topology#topologyClosed - * @type {TopologyClosedEvent} - */ - -/** - * A topology structure SDAM change event - * - * @event Topology#topologyDescriptionChanged - * @type {TopologyDescriptionChangedEvent} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event Topology#serverHeartbeatStarted - * @type {ServerHeartbeatStartedEvent} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event Topology#serverHeartbeatFailed - * @type {ServerHearbeatFailedEvent} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event Topology#serverHeartbeatSucceeded - * @type {ServerHeartbeatSucceededEvent} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Topology#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Topology#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Topology#commandFailed - * @type {object} - */ - -module.exports = { - Topology -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/topology_description.js b/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/topology_description.js deleted file mode 100644 index d1beb22..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/sdam/topology_description.js +++ /dev/null @@ -1,423 +0,0 @@ -'use strict'; -const ServerType = require('./common').ServerType; -const ServerDescription = require('./server_description').ServerDescription; -const WIRE_CONSTANTS = require('../wireprotocol/constants'); -const TopologyType = require('./common').TopologyType; - -// contstants related to compatability checks -const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; -const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; -const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; -const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; - -// Representation of a deployment of servers -class TopologyDescription { - /** - * Create a TopologyDescription - * - * @param {string} topologyType - * @param {Map} serverDescriptions the a map of address to ServerDescription - * @param {string} setName - * @param {number} maxSetVersion - * @param {ObjectId} maxElectionId - */ - constructor( - topologyType, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - options - ) { - options = options || {}; - - // TODO: consider assigning all these values to a temporary value `s` which - // we use `Object.freeze` on, ensuring the internal state of this type - // is immutable. - this.type = topologyType || TopologyType.Unknown; - this.setName = setName || null; - this.maxSetVersion = maxSetVersion || null; - this.maxElectionId = maxElectionId || null; - this.servers = serverDescriptions || new Map(); - this.stale = false; - this.compatible = true; - this.compatibilityError = null; - this.logicalSessionTimeoutMinutes = null; - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 0; - this.localThresholdMS = options.localThresholdMS || 0; - this.commonWireVersion = commonWireVersion || null; - - // save this locally, but don't display when printing the instance out - Object.defineProperty(this, 'options', { value: options, enumberable: false }); - - // determine server compatibility - for (const serverDescription of this.servers.values()) { - if (serverDescription.type === ServerType.Unknown) continue; - - if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { - this.compatible = false; - this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${serverDescription.minWireVersion}, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; - } - - if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { - this.compatible = false; - this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${serverDescription.maxWireVersion}, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; - break; - } - } - - // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set - // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes - // value among ServerDescriptions of all data-bearing server types. If any have a null - // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be - // set to null. - const readableServers = Array.from(this.servers.values()).filter(s => s.isReadable); - this.logicalSessionTimeoutMinutes = readableServers.reduce((result, server) => { - if (server.logicalSessionTimeoutMinutes == null) return null; - if (result == null) return server.logicalSessionTimeoutMinutes; - return Math.min(result, server.logicalSessionTimeoutMinutes); - }, null); - } - - /** - * Returns a new TopologyDescription based on the SrvPollingEvent - * @param {SrvPollingEvent} ev The event - */ - updateFromSrvPollingEvent(ev) { - const newAddresses = ev.addresses(); - const serverDescriptions = new Map(this.servers); - for (const server of this.servers) { - if (newAddresses.has(server[0])) { - newAddresses.delete(server[0]); - } else { - serverDescriptions.delete(server[0]); - } - } - - if (serverDescriptions.size === this.servers.size && newAddresses.size === 0) { - return this; - } - - for (const address of newAddresses) { - serverDescriptions.set(address, new ServerDescription(address)); - } - - return new TopologyDescription( - this.type, - serverDescriptions, - this.setName, - this.maxSetVersion, - this.maxElectionId, - this.commonWireVersion, - this.options, - null - ); - } - - /** - * Returns a copy of this description updated with a given ServerDescription - * - * @param {ServerDescription} serverDescription - */ - update(serverDescription) { - const address = serverDescription.address; - // NOTE: there are a number of prime targets for refactoring here - // once we support destructuring assignments - - // potentially mutated values - let topologyType = this.type; - let setName = this.setName; - let maxSetVersion = this.maxSetVersion; - let maxElectionId = this.maxElectionId; - let commonWireVersion = this.commonWireVersion; - - const serverType = serverDescription.type; - let serverDescriptions = new Map(this.servers); - - // update common wire version - if (serverDescription.maxWireVersion !== 0) { - if (commonWireVersion == null) { - commonWireVersion = serverDescription.maxWireVersion; - } else { - commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); - } - } - - // update the actual server description - serverDescriptions.set(address, serverDescription); - - if (topologyType === TopologyType.Single) { - // once we are defined as single, that never changes - return new TopologyDescription( - TopologyType.Single, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - this.options - ); - } - - if (topologyType === TopologyType.Unknown) { - if (serverType === ServerType.Standalone) { - serverDescriptions.delete(address); - } else { - topologyType = topologyTypeForServerType(serverType); - } - } - - if (topologyType === TopologyType.Sharded) { - if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1) { - serverDescriptions.delete(address); - } - } - - if (topologyType === TopologyType.ReplicaSetNoPrimary) { - if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { - serverDescriptions.delete(address); - } - - if (serverType === ServerType.RSPrimary) { - const result = updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId - ); - - (topologyType = result[0]), - (setName = result[1]), - (maxSetVersion = result[2]), - (maxElectionId = result[3]); - } else if ( - [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 - ) { - const result = updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription); - (topologyType = result[0]), (setName = result[1]); - } - } - - if (topologyType === TopologyType.ReplicaSetWithPrimary) { - if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { - serverDescriptions.delete(address); - topologyType = checkHasPrimary(serverDescriptions); - } else if (serverType === ServerType.RSPrimary) { - const result = updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId - ); - - (topologyType = result[0]), - (setName = result[1]), - (maxSetVersion = result[2]), - (maxElectionId = result[3]); - } else if ( - [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 - ) { - topologyType = updateRsWithPrimaryFromMember( - serverDescriptions, - setName, - serverDescription - ); - } else { - topologyType = checkHasPrimary(serverDescriptions); - } - } - - return new TopologyDescription( - topologyType, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - this.options - ); - } - - get error() { - const descriptionsWithError = Array.from(this.servers.values()).filter(sd => sd.error); - if (descriptionsWithError.length > 0) { - return descriptionsWithError[0].error; - } - } - - /** - * Determines if the topology description has any known servers - */ - get hasKnownServers() { - return Array.from(this.servers.values()).some(sd => sd.type !== ServerType.Unknown); - } - - /** - * Determines if this topology description has a data-bearing server available. - */ - get hasDataBearingServers() { - return Array.from(this.servers.values()).some(sd => sd.isDataBearing); - } - - /** - * Determines if the topology has a definition for the provided address - * - * @param {String} address - * @return {Boolean} Whether the topology knows about this server - */ - hasServer(address) { - return this.servers.has(address); - } -} - -function topologyTypeForServerType(serverType) { - if (serverType === ServerType.Mongos) return TopologyType.Sharded; - if (serverType === ServerType.RSPrimary) return TopologyType.ReplicaSetWithPrimary; - return TopologyType.ReplicaSetNoPrimary; -} - -function compareObjectId(oid1, oid2) { - if (oid1 == null) { - return -1; - } - - if (oid2 == null) { - return 1; - } - - if (oid1.id instanceof Buffer && oid2.id instanceof Buffer) { - const oid1Buffer = oid1.id; - const oid2Buffer = oid2.id; - return oid1Buffer.compare(oid2Buffer); - } - - const oid1String = oid1.toString(); - const oid2String = oid2.toString(); - return oid1String.localeCompare(oid2String); -} - -function updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId -) { - setName = setName || serverDescription.setName; - if (setName !== serverDescription.setName) { - serverDescriptions.delete(serverDescription.address); - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; - } - - const electionId = serverDescription.electionId ? serverDescription.electionId : null; - if (serverDescription.setVersion && electionId) { - if (maxSetVersion && maxElectionId) { - if ( - maxSetVersion > serverDescription.setVersion || - compareObjectId(maxElectionId, electionId) > 0 - ) { - // this primary is stale, we must remove it - serverDescriptions.set( - serverDescription.address, - new ServerDescription(serverDescription.address) - ); - - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; - } - } - - maxElectionId = serverDescription.electionId; - } - - if ( - serverDescription.setVersion != null && - (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) - ) { - maxSetVersion = serverDescription.setVersion; - } - - // We've heard from the primary. Is it the same primary as before? - for (const address of serverDescriptions.keys()) { - const server = serverDescriptions.get(address); - - if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { - // Reset old primary's type to Unknown. - serverDescriptions.set(address, new ServerDescription(server.address)); - - // There can only be one primary - break; - } - } - - // Discover new hosts from this primary's response. - serverDescription.allHosts.forEach(address => { - if (!serverDescriptions.has(address)) { - serverDescriptions.set(address, new ServerDescription(address)); - } - }); - - // Remove hosts not in the response. - const currentAddresses = Array.from(serverDescriptions.keys()); - const responseAddresses = serverDescription.allHosts; - currentAddresses - .filter(addr => responseAddresses.indexOf(addr) === -1) - .forEach(address => { - serverDescriptions.delete(address); - }); - - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; -} - -function updateRsWithPrimaryFromMember(serverDescriptions, setName, serverDescription) { - if (setName == null) { - throw new TypeError('setName is required'); - } - - if ( - setName !== serverDescription.setName || - (serverDescription.me && serverDescription.address !== serverDescription.me) - ) { - serverDescriptions.delete(serverDescription.address); - } - - return checkHasPrimary(serverDescriptions); -} - -function updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription) { - let topologyType = TopologyType.ReplicaSetNoPrimary; - - setName = setName || serverDescription.setName; - if (setName !== serverDescription.setName) { - serverDescriptions.delete(serverDescription.address); - return [topologyType, setName]; - } - - serverDescription.allHosts.forEach(address => { - if (!serverDescriptions.has(address)) { - serverDescriptions.set(address, new ServerDescription(address)); - } - }); - - if (serverDescription.me && serverDescription.address !== serverDescription.me) { - serverDescriptions.delete(serverDescription.address); - } - - return [topologyType, setName]; -} - -function checkHasPrimary(serverDescriptions) { - for (const addr of serverDescriptions.keys()) { - if (serverDescriptions.get(addr).type === ServerType.RSPrimary) { - return TopologyType.ReplicaSetWithPrimary; - } - } - - return TopologyType.ReplicaSetNoPrimary; -} - -module.exports = { - TopologyDescription -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/sessions.js b/node_modules/mongoose/node_modules/mongodb/lib/core/sessions.js deleted file mode 100644 index 9cc6b5b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/sessions.js +++ /dev/null @@ -1,787 +0,0 @@ -'use strict'; - -const retrieveBSON = require('./connection/utils').retrieveBSON; -const EventEmitter = require('events'); -const BSON = retrieveBSON(); -const Binary = BSON.Binary; -const uuidV4 = require('./utils').uuidV4; -const MongoError = require('./error').MongoError; -const isRetryableError = require('././error').isRetryableError; -const MongoNetworkError = require('./error').MongoNetworkError; -const MongoWriteConcernError = require('./error').MongoWriteConcernError; -const Transaction = require('./transactions').Transaction; -const TxnState = require('./transactions').TxnState; -const isPromiseLike = require('./utils').isPromiseLike; -const ReadPreference = require('./topologies/read_preference'); -const isTransactionCommand = require('./transactions').isTransactionCommand; -const resolveClusterTime = require('./topologies/shared').resolveClusterTime; -const isSharded = require('./wireprotocol/shared').isSharded; -const maxWireVersion = require('./utils').maxWireVersion; - -const minWireVersionForShardedTransactions = 8; - -function assertAlive(session, callback) { - if (session.serverSession == null) { - const error = new MongoError('Cannot use a session that has ended'); - if (typeof callback === 'function') { - callback(error, null); - return false; - } - - throw error; - } - - return true; -} - -/** - * Options to pass when creating a Client Session - * @typedef {Object} SessionOptions - * @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session - * @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session. - */ - -/** - * A BSON document reflecting the lsid of a {@link ClientSession} - * @typedef {Object} SessionId - */ - -const kServerSession = Symbol('serverSession'); - -/** - * A class representing a client session on the server - * WARNING: not meant to be instantiated directly. - * @class - * @hideconstructor - */ -class ClientSession extends EventEmitter { - /** - * Create a client session. - * WARNING: not meant to be instantiated directly - * - * @param {Topology} topology The current client's topology (Internal Class) - * @param {ServerSessionPool} sessionPool The server session pool (Internal Class) - * @param {SessionOptions} [options] Optional settings - * @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver - */ - constructor(topology, sessionPool, options, clientOptions) { - super(); - - if (topology == null) { - throw new Error('ClientSession requires a topology'); - } - - if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { - throw new Error('ClientSession requires a ServerSessionPool'); - } - - options = options || {}; - clientOptions = clientOptions || {}; - - this.topology = topology; - this.sessionPool = sessionPool; - this.hasEnded = false; - this.clientOptions = clientOptions; - this[kServerSession] = undefined; - - this.supports = { - causalConsistency: - typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true - }; - - this.clusterTime = options.initialClusterTime; - - this.operationTime = null; - this.explicit = !!options.explicit; - this.owner = options.owner; - this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); - this.transaction = new Transaction(); - } - - /** - * The server id associated with this session - * @type {SessionId} - */ - get id() { - return this.serverSession.id; - } - - get serverSession() { - if (this[kServerSession] == null) { - this[kServerSession] = this.sessionPool.acquire(); - } - - return this[kServerSession]; - } - - /** - * Ends this session on the server - * - * @param {Object} [options] Optional settings. Currently reserved for future use - * @param {Function} [callback] Optional callback for completion of this operation - */ - endSession(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (this.hasEnded) { - if (typeof callback === 'function') callback(null, null); - return; - } - - if (this.serverSession && this.inTransaction()) { - this.abortTransaction(); // pass in callback? - } - - // release the server session back to the pool - this.sessionPool.release(this.serverSession); - this[kServerSession] = undefined; - - // mark the session as ended, and emit a signal - this.hasEnded = true; - this.emit('ended', this); - - // spec indicates that we should ignore all errors for `endSessions` - if (typeof callback === 'function') callback(null, null); - } - - /** - * Advances the operationTime for a ClientSession. - * - * @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to - */ - advanceOperationTime(operationTime) { - if (this.operationTime == null) { - this.operationTime = operationTime; - return; - } - - if (operationTime.greaterThan(this.operationTime)) { - this.operationTime = operationTime; - } - } - - /** - * Used to determine if this session equals another - * @param {ClientSession} session - * @return {boolean} true if the sessions are equal - */ - equals(session) { - if (!(session instanceof ClientSession)) { - return false; - } - - return this.id.id.buffer.equals(session.id.id.buffer); - } - - /** - * Increment the transaction number on the internal ServerSession - */ - incrementTransactionNumber() { - this.serverSession.txnNumber++; - } - - /** - * @returns {boolean} whether this session is currently in a transaction or not - */ - inTransaction() { - return this.transaction.isActive; - } - - /** - * Starts a new transaction with the given options. - * - * @param {TransactionOptions} options Options for the transaction - */ - startTransaction(options) { - assertAlive(this); - if (this.inTransaction()) { - throw new MongoError('Transaction already in progress'); - } - - const topologyMaxWireVersion = maxWireVersion(this.topology); - if ( - isSharded(this.topology) && - topologyMaxWireVersion != null && - topologyMaxWireVersion < minWireVersionForShardedTransactions - ) { - throw new MongoError('Transactions are not supported on sharded clusters in MongoDB < 4.2.'); - } - - // increment txnNumber - this.incrementTransactionNumber(); - - // create transaction state - this.transaction = new Transaction( - Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions) - ); - - this.transaction.transition(TxnState.STARTING_TRANSACTION); - } - - /** - * Commits the currently active transaction in this session. - * - * @param {Function} [callback] optional callback for completion of this operation - * @return {Promise} A promise is returned if no callback is provided - */ - commitTransaction(callback) { - if (typeof callback === 'function') { - endTransaction(this, 'commitTransaction', callback); - return; - } - - return new Promise((resolve, reject) => { - endTransaction(this, 'commitTransaction', (err, reply) => - err ? reject(err) : resolve(reply) - ); - }); - } - - /** - * Aborts the currently active transaction in this session. - * - * @param {Function} [callback] optional callback for completion of this operation - * @return {Promise} A promise is returned if no callback is provided - */ - abortTransaction(callback) { - if (typeof callback === 'function') { - endTransaction(this, 'abortTransaction', callback); - return; - } - - return new Promise((resolve, reject) => { - endTransaction(this, 'abortTransaction', (err, reply) => - err ? reject(err) : resolve(reply) - ); - }); - } - - /** - * This is here to ensure that ClientSession is never serialized to BSON. - * @ignore - */ - toBSON() { - throw new Error('ClientSession cannot be serialized to BSON.'); - } - - /** - * A user provided function to be run within a transaction - * - * @callback WithTransactionCallback - * @param {ClientSession} session The parent session of the transaction running the operation. This should be passed into each operation within the lambda. - * @returns {Promise} The resulting Promise of operations run within this transaction - */ - - /** - * Runs a provided lambda within a transaction, retrying either the commit operation - * or entire transaction as needed (and when the error permits) to better ensure that - * the transaction can complete successfully. - * - * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not - * return a Promise will result in undefined behavior. - * - * @param {WithTransactionCallback} fn - * @param {TransactionOptions} [options] Optional settings for the transaction - */ - withTransaction(fn, options) { - const startTime = Date.now(); - return attemptTransaction(this, startTime, fn, options); - } -} - -const MAX_WITH_TRANSACTION_TIMEOUT = 120000; -const UNSATISFIABLE_WRITE_CONCERN_CODE = 100; -const UNKNOWN_REPL_WRITE_CONCERN_CODE = 79; -const MAX_TIME_MS_EXPIRED_CODE = 50; -const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ - 'CannotSatisfyWriteConcern', - 'UnknownReplWriteConcern', - 'UnsatisfiableWriteConcern' -]); - -function hasNotTimedOut(startTime, max) { - return Date.now() - startTime < max; -} - -function isUnknownTransactionCommitResult(err) { - return ( - isMaxTimeMSExpiredError(err) || - (!NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName) && - err.code !== UNSATISFIABLE_WRITE_CONCERN_CODE && - err.code !== UNKNOWN_REPL_WRITE_CONCERN_CODE) - ); -} - -function isMaxTimeMSExpiredError(err) { - if (err == null) return false; - return ( - err.code === MAX_TIME_MS_EXPIRED_CODE || - (err.writeConcernError && err.writeConcernError.code === MAX_TIME_MS_EXPIRED_CODE) - ); -} - -function attemptTransactionCommit(session, startTime, fn, options) { - return session.commitTransaction().catch(err => { - if ( - err instanceof MongoError && - hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && - !isMaxTimeMSExpiredError(err) - ) { - if (err.hasErrorLabel('UnknownTransactionCommitResult')) { - return attemptTransactionCommit(session, startTime, fn, options); - } - - if (err.hasErrorLabel('TransientTransactionError')) { - return attemptTransaction(session, startTime, fn, options); - } - } - - throw err; - }); -} - -const USER_EXPLICIT_TXN_END_STATES = new Set([ - TxnState.NO_TRANSACTION, - TxnState.TRANSACTION_COMMITTED, - TxnState.TRANSACTION_ABORTED -]); - -function userExplicitlyEndedTransaction(session) { - return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); -} - -function attemptTransaction(session, startTime, fn, options) { - session.startTransaction(options); - - let promise; - try { - promise = fn(session); - } catch (err) { - promise = Promise.reject(err); - } - - if (!isPromiseLike(promise)) { - session.abortTransaction(); - throw new TypeError('Function provided to `withTransaction` must return a Promise'); - } - - return promise - .then(() => { - if (userExplicitlyEndedTransaction(session)) { - return; - } - - return attemptTransactionCommit(session, startTime, fn, options); - }) - .catch(err => { - function maybeRetryOrThrow(err) { - if ( - err instanceof MongoError && - err.hasErrorLabel('TransientTransactionError') && - hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) - ) { - return attemptTransaction(session, startTime, fn, options); - } - - if (isMaxTimeMSExpiredError(err)) { - if (err.errorLabels == null) { - err.errorLabels = []; - } - err.errorLabels.push('UnknownTransactionCommitResult'); - } - - throw err; - } - - if (session.transaction.isActive) { - return session.abortTransaction().then(() => maybeRetryOrThrow(err)); - } - - return maybeRetryOrThrow(err); - }); -} - -function endTransaction(session, commandName, callback) { - if (!assertAlive(session, callback)) { - // checking result in case callback was called - return; - } - - // handle any initial problematic cases - let txnState = session.transaction.state; - - if (txnState === TxnState.NO_TRANSACTION) { - callback(new MongoError('No transaction started')); - return; - } - - if (commandName === 'commitTransaction') { - if ( - txnState === TxnState.STARTING_TRANSACTION || - txnState === TxnState.TRANSACTION_COMMITTED_EMPTY - ) { - // the transaction was never started, we can safely exit here - session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); - callback(null, null); - return; - } - - if (txnState === TxnState.TRANSACTION_ABORTED) { - callback(new MongoError('Cannot call commitTransaction after calling abortTransaction')); - return; - } - } else { - if (txnState === TxnState.STARTING_TRANSACTION) { - // the transaction was never started, we can safely exit here - session.transaction.transition(TxnState.TRANSACTION_ABORTED); - callback(null, null); - return; - } - - if (txnState === TxnState.TRANSACTION_ABORTED) { - callback(new MongoError('Cannot call abortTransaction twice')); - return; - } - - if ( - txnState === TxnState.TRANSACTION_COMMITTED || - txnState === TxnState.TRANSACTION_COMMITTED_EMPTY - ) { - callback(new MongoError('Cannot call abortTransaction after calling commitTransaction')); - return; - } - } - - // construct and send the command - const command = { [commandName]: 1 }; - - // apply a writeConcern if specified - let writeConcern; - if (session.transaction.options.writeConcern) { - writeConcern = Object.assign({}, session.transaction.options.writeConcern); - } else if (session.clientOptions && session.clientOptions.w) { - writeConcern = { w: session.clientOptions.w }; - } - - if (txnState === TxnState.TRANSACTION_COMMITTED) { - writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' }); - } - - if (writeConcern) { - Object.assign(command, { writeConcern }); - } - - if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { - Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); - } - - function commandHandler(e, r) { - if (commandName === 'commitTransaction') { - session.transaction.transition(TxnState.TRANSACTION_COMMITTED); - - if ( - e && - (e instanceof MongoNetworkError || - e instanceof MongoWriteConcernError || - isRetryableError(e) || - isMaxTimeMSExpiredError(e)) - ) { - if (e.errorLabels) { - const idx = e.errorLabels.indexOf('TransientTransactionError'); - if (idx !== -1) { - e.errorLabels.splice(idx, 1); - } - } else { - e.errorLabels = []; - } - - if (isUnknownTransactionCommitResult(e)) { - e.errorLabels.push('UnknownTransactionCommitResult'); - - // per txns spec, must unpin session in this case - session.transaction.unpinServer(); - } - } - } else { - session.transaction.transition(TxnState.TRANSACTION_ABORTED); - } - - callback(e, r); - } - - // The spec indicates that we should ignore all errors on `abortTransaction` - function transactionError(err) { - return commandName === 'commitTransaction' ? err : null; - } - - if ( - // Assumption here that commandName is "commitTransaction" or "abortTransaction" - session.transaction.recoveryToken && - supportsRecoveryToken(session) - ) { - command.recoveryToken = session.transaction.recoveryToken; - } - - // send the command - session.topology.command('admin.$cmd', command, { session }, (err, reply) => { - if (err && isRetryableError(err)) { - // SPEC-1185: apply majority write concern when retrying commitTransaction - if (command.commitTransaction) { - // per txns spec, must unpin session in this case - session.transaction.unpinServer(); - - command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { - w: 'majority' - }); - } - - return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) => - commandHandler(transactionError(_err), _reply) - ); - } - - commandHandler(transactionError(err), reply); - }); -} - -function supportsRecoveryToken(session) { - const topology = session.topology; - return !!topology.s.options.useRecoveryToken; -} - -/** - * Reflects the existence of a session on the server. Can be reused by the session pool. - * WARNING: not meant to be instantiated directly. For internal use only. - * @ignore - */ -class ServerSession { - constructor() { - this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; - this.lastUse = Date.now(); - this.txnNumber = 0; - this.isDirty = false; - } - - /** - * Determines if the server session has timed out. - * @ignore - * @param {Date} sessionTimeoutMinutes The server's "logicalSessionTimeoutMinutes" - * @return {boolean} true if the session has timed out. - */ - hasTimedOut(sessionTimeoutMinutes) { - // Take the difference of the lastUse timestamp and now, which will result in a value in - // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` - const idleTimeMinutes = Math.round( - (((Date.now() - this.lastUse) % 86400000) % 3600000) / 60000 - ); - - return idleTimeMinutes > sessionTimeoutMinutes - 1; - } -} - -/** - * Maintains a pool of Server Sessions. - * For internal use only - * @ignore - */ -class ServerSessionPool { - constructor(topology) { - if (topology == null) { - throw new Error('ServerSessionPool requires a topology'); - } - - this.topology = topology; - this.sessions = []; - } - - /** - * Ends all sessions in the session pool. - * @ignore - */ - endAllPooledSessions(callback) { - if (this.sessions.length) { - this.topology.endSessions( - this.sessions.map(session => session.id), - () => { - this.sessions = []; - if (typeof callback === 'function') { - callback(); - } - } - ); - - return; - } - - if (typeof callback === 'function') { - callback(); - } - } - - /** - * Acquire a Server Session from the pool. - * Iterates through each session in the pool, removing any stale sessions - * along the way. The first non-stale session found is removed from the - * pool and returned. If no non-stale session is found, a new ServerSession - * is created. - * @ignore - * @returns {ServerSession} - */ - acquire() { - const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; - while (this.sessions.length) { - const session = this.sessions.shift(); - if (!session.hasTimedOut(sessionTimeoutMinutes)) { - return session; - } - } - - return new ServerSession(); - } - - /** - * Release a session to the session pool - * Adds the session back to the session pool if the session has not timed out yet. - * This method also removes any stale sessions from the pool. - * @ignore - * @param {ServerSession} session The session to release to the pool - */ - release(session) { - const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; - while (this.sessions.length) { - const pooledSession = this.sessions[this.sessions.length - 1]; - if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) { - this.sessions.pop(); - } else { - break; - } - } - - if (!session.hasTimedOut(sessionTimeoutMinutes)) { - if (session.isDirty) { - return; - } - - // otherwise, readd this session to the session pool - this.sessions.unshift(session); - } - } -} - -// TODO: this should be codified in command construction -// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern -function commandSupportsReadConcern(command, options) { - if ( - command.aggregate || - command.count || - command.distinct || - command.find || - command.parallelCollectionScan || - command.geoNear || - command.geoSearch - ) { - return true; - } - - if (command.mapReduce && options.out && (options.out.inline === 1 || options.out === 'inline')) { - return true; - } - - return false; -} - -/** - * Optionally decorate a command with sessions specific keys - * - * @ignore - * @param {ClientSession} session the session tracking transaction state - * @param {Object} command the command to decorate - * @param {Object} topology the topology for tracking the cluster time - * @param {Object} [options] Optional settings passed to calling operation - * @return {MongoError|null} An error, if some error condition was met - */ -function applySession(session, command, options) { - if (session.hasEnded) { - // TODO: merge this with `assertAlive`, did not want to throw a try/catch here - return new MongoError('Cannot use a session that has ended'); - } - - const serverSession = session.serverSession; - serverSession.lastUse = Date.now(); - command.lsid = serverSession.id; - - // first apply non-transaction-specific sessions data - const inTransaction = session.inTransaction() || isTransactionCommand(command); - const isRetryableWrite = options.willRetryWrite; - const shouldApplyReadConcern = commandSupportsReadConcern(command); - - if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { - command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber); - } - - // now attempt to apply transaction-specific sessions data - if (!inTransaction) { - if (session.transaction.state !== TxnState.NO_TRANSACTION) { - session.transaction.transition(TxnState.NO_TRANSACTION); - } - - // TODO: the following should only be applied to read operation per spec. - // for causal consistency - if (session.supports.causalConsistency && session.operationTime && shouldApplyReadConcern) { - command.readConcern = command.readConcern || {}; - Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); - } - - return; - } - - if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) { - return new MongoError( - `Read preference in a transaction must be primary, not: ${options.readPreference.mode}` - ); - } - - // `autocommit` must always be false to differentiate from retryable writes - command.autocommit = false; - - if (session.transaction.state === TxnState.STARTING_TRANSACTION) { - session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); - command.startTransaction = true; - - const readConcern = - session.transaction.options.readConcern || session.clientOptions.readConcern; - if (readConcern) { - command.readConcern = readConcern; - } - - if (session.supports.causalConsistency && session.operationTime) { - command.readConcern = command.readConcern || {}; - Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); - } - } -} - -function updateSessionFromResponse(session, document) { - if (document.$clusterTime) { - resolveClusterTime(session, document.$clusterTime); - } - - if (document.operationTime && session && session.supports.causalConsistency) { - session.advanceOperationTime(document.operationTime); - } - - if (document.recoveryToken && session && session.inTransaction()) { - session.transaction._recoveryToken = document.recoveryToken; - } -} - -module.exports = { - ClientSession, - ServerSession, - ServerSessionPool, - TxnState, - applySession, - updateSessionFromResponse, - commandSupportsReadConcern -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/tools/smoke_plugin.js b/node_modules/mongoose/node_modules/mongodb/lib/core/tools/smoke_plugin.js deleted file mode 100644 index 22d0298..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/tools/smoke_plugin.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -var fs = require('fs'); - -/* Note: because this plugin uses process.on('uncaughtException'), only one - * of these can exist at any given time. This plugin and anything else that - * uses process.on('uncaughtException') will conflict. */ -exports.attachToRunner = function(runner, outputFile) { - var smokeOutput = { results: [] }; - var runningTests = {}; - - var integraPlugin = { - beforeTest: function(test, callback) { - test.startTime = Date.now(); - runningTests[test.name] = test; - callback(); - }, - afterTest: function(test, callback) { - smokeOutput.results.push({ - status: test.status, - start: test.startTime, - end: Date.now(), - test_file: test.name, - exit_code: 0, - url: '' - }); - delete runningTests[test.name]; - callback(); - }, - beforeExit: function(obj, callback) { - fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { - callback(); - }); - } - }; - - // In case of exception, make sure we write file - process.on('uncaughtException', function(err) { - // Mark all currently running tests as failed - for (var testName in runningTests) { - smokeOutput.results.push({ - status: 'fail', - start: runningTests[testName].startTime, - end: Date.now(), - test_file: testName, - exit_code: 0, - url: '' - }); - } - - // write file - fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); - - // Standard NodeJS uncaught exception handler - console.error(err.stack); - process.exit(1); - }); - - runner.plugin(integraPlugin); - return integraPlugin; -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/mongos.js b/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/mongos.js deleted file mode 100644 index 2937193..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/mongos.js +++ /dev/null @@ -1,1384 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const f = require('util').format; -const EventEmitter = require('events').EventEmitter; -const CoreCursor = require('../cursor').CoreCursor; -const Logger = require('../connection/logger'); -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const Server = require('./server'); -const diff = require('./shared').diff; -const cloneOptions = require('./shared').cloneOptions; -const SessionMixins = require('./shared').SessionMixins; -const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; -const relayEvents = require('../utils').relayEvents; -const isRetryableError = require('../error').isRetryableError; -const BSON = retrieveBSON(); -const getMMAPError = require('./shared').getMMAPError; -const makeClientMetadata = require('../utils').makeClientMetadata; - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - */ - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYING = 'destroying'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYING, DESTROYED, DISCONNECTED], - connecting: [CONNECTING, DESTROYING, DESTROYED, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYING, DESTROYED, UNREFERENCED], - unreferenced: [UNREFERENCED, DESTROYING, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.state = newState; - } else { - self.s.logger.error( - f( - 'Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * Creates a new Mongos instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {Mongos} A cursor instance - * @fires Mongos#connect - * @fires Mongos#reconnect - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#failed - * @fires Mongos#fullsetup - * @fires Mongos#all - * @fires Mongos#serverHeartbeatStarted - * @fires Mongos#serverHeartbeatSucceeded - * @fires Mongos#serverHeartbeatFailed - * @fires Mongos#topologyOpening - * @fires Mongos#topologyClosed - * @fires Mongos#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Mongos = function(seedlist, options) { - options = options || {}; - - // Get replSet Id - this.id = id++; - - // Internal state - this.s = { - options: Object.assign({ metadata: makeClientMetadata(options) }, options), - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // Logger instance - logger: Logger('Mongos', options), - // Seedlist - seedlist: seedlist, - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug === 'boolean' ? options.debug : false, - // localThresholdMS - localThresholdMS: options.localThresholdMS || 15 - }; - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if ( - this.s.logger.isWarn() && - this.s.options.socketTimeout !== 0 && - this.s.options.socketTimeout < this.s.haInterval - ) { - this.s.logger.warn( - f( - 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', - this.s.options.socketTimeout, - this.s.haInterval - ) - ); - } - - // Disconnected state - this.state = DISCONNECTED; - - // Current proxies we are connecting to - this.connectingProxies = []; - // Currently connected proxies - this.connectedProxies = []; - // Disconnected proxies - this.disconnectedProxies = []; - // Index of proxy to run operations against - this.index = 0; - // High availability timeout id - this.haTimeoutId = null; - // Last ismaster - this.ismaster = null; - - // Description of the Replicaset - this.topologyDescription = { - topologyType: 'Unknown', - servers: [] - }; - - // Highest clusterTime seen in responses from the current deployment - this.clusterTime = null; - - // Add event listener - EventEmitter.call(this); -}; - -inherits(Mongos, EventEmitter); -Object.assign(Mongos.prototype, SessionMixins); - -Object.defineProperty(Mongos.prototype, 'type', { - enumerable: true, - get: function() { - return 'mongos'; - } -}); - -Object.defineProperty(Mongos.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(Mongos.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - if (!this.ismaster) return null; - return this.ismaster.logicalSessionTimeoutMinutes || null; - } -}); - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -const SERVER_EVENTS = ['serverDescriptionChanged', 'error', 'close', 'timeout', 'parseError']; -function destroyServer(server, options, callback) { - options = options || {}; - SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); - server.destroy(options, callback); -} - -/** - * Initiate server connect - */ -Mongos.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - - // Set connecting state - stateTransition(this, CONNECTING); - - // Create server instances - var servers = this.s.seedlist.map(function(x) { - const server = new Server( - Object.assign({}, self.s.options, x, options, { - reconnect: false, - monitoring: false, - parent: self - }) - ); - - relayEvents(server, self, ['serverDescriptionChanged']); - return server; - }); - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - - // Start all server connections - connectProxies(self, servers); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -Mongos.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -function handleEvent(self) { - return function() { - if (self.state === DESTROYED || self.state === DESTROYING) { - return; - } - - // Move to list of disconnectedProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Emit the left signal - self.emit('left', 'mongos', this); - // Emit the sdam event - self.emit('serverClosed', { - topologyId: self.id, - address: this.name - }); - }; -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - - // Destroy the instance - if (self.state === DESTROYED) { - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - return this.destroy(); - } - - // Check the type of server - if (event === 'connect') { - // Get last known ismaster - self.ismaster = _this.lastIsMaster(); - - // Is this not a proxy, remove t - if (self.ismaster.msg === 'isdbgrid') { - // Add to the connectd list - for (let i = 0; i < self.connectedProxies.length; i++) { - if (self.connectedProxies[i].name === _this.name) { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - _this.destroy(); - return self.emit('failed', _this); - } - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Move from connecting proxies connected - moveServerFrom(self.connectingProxies, self.connectedProxies, _this); - // Emit the joined event - self.emit('joined', 'mongos', _this); - } else { - // Print warning if we did not find a mongos proxy - if (self.s.logger.isWarn()) { - var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; - // We have a standalone server - if (!self.ismaster.hosts) { - message = 'expected mongos proxy, but found standalone mongod for server %s'; - } - - self.s.logger.warn(f(message, _this.name)); - } - - // This is not a mongos proxy, destroy and remove it completely - _this.destroy(true); - removeProxyFrom(self.connectingProxies, _this); - // Emit the left event - self.emit('left', 'server', _this); - // Emit failed event - self.emit('failed', _this); - } - } else { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - // Emit the left event - self.emit('left', 'mongos', this); - // Emit failed event - self.emit('failed', this); - } - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Trigger topologyMonitor - if (self.connectingProxies.length === 0) { - // Emit connected if we are connected - if (self.connectedProxies.length > 0 && self.state === CONNECTING) { - // Set the state to connected - stateTransition(self, CONNECTED); - // Emit the connect event - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if (self.disconnectedProxies.length === 0) { - // Print warning if we did not find a mongos proxy - if (self.s.logger.isWarn()) { - self.s.logger.warn( - f('no mongos proxies found in seed list, did you mean to connect to a replicaset') - ); - } - - // Emit the error that no proxies were found - return self.emit('error', new MongoError('no mongos proxies found in seed list')); - } - - // Topology monitor - topologyMonitor(self, { firstConnect: true }); - } - }; -} - -function connectProxies(self, servers) { - // Update connectingProxies - self.connectingProxies = self.connectingProxies.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Emit opening server event - self.emit('serverOpening', { - topologyId: self.id, - address: server.name - }); - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - - // Start all the servers - servers.forEach(server => connect(server, timeoutInterval++)); -} - -function pickProxy(self, session) { - // TODO: Destructure :) - const transaction = session && session.transaction; - - if (transaction && transaction.server) { - if (transaction.server.isConnected()) { - return transaction.server; - } else { - transaction.unpinServer(); - } - } - - // Get the currently connected Proxies - var connectedProxies = self.connectedProxies.slice(0); - - // Set lower bound - var lowerBoundLatency = Number.MAX_VALUE; - - // Determine the lower bound for the Proxies - for (var i = 0; i < connectedProxies.length; i++) { - if (connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { - lowerBoundLatency = connectedProxies[i].lastIsMasterMS; - } - } - - // Filter out the possible servers - connectedProxies = connectedProxies.filter(function(server) { - if ( - server.lastIsMasterMS <= lowerBoundLatency + self.s.localThresholdMS && - server.isConnected() - ) { - return true; - } - }); - - let proxy; - - // We have no connectedProxies pick first of the connected ones - if (connectedProxies.length === 0) { - proxy = self.connectedProxies[0]; - } else { - // Get proxy - proxy = connectedProxies[self.index % connectedProxies.length]; - // Update the index - self.index = (self.index + 1) % connectedProxies.length; - } - - if (transaction && transaction.isActive && proxy && proxy.isConnected()) { - transaction.pinServer(proxy); - } - - // Return the proxy - return proxy; -} - -function moveServerFrom(from, to, proxy) { - for (var i = 0; i < from.length; i++) { - if (from[i].name === proxy.name) { - from.splice(i, 1); - } - } - - for (i = 0; i < to.length; i++) { - if (to[i].name === proxy.name) { - to.splice(i, 1); - } - } - - to.push(proxy); -} - -function removeProxyFrom(from, proxy) { - for (var i = 0; i < from.length; i++) { - if (from[i].name === proxy.name) { - from.splice(i, 1); - } - } -} - -function reconnectProxies(self, proxies, callback) { - // Count lefts - var count = proxies.length; - - // Handle events - var _handleEvent = function(self, event) { - return function() { - var _self = this; - count = count - 1; - - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - return this.destroy(); - } - - if (event === 'connect') { - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - return _self.destroy(); - } - - // Remove the handlers - for (var i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Move to the connected servers - moveServerFrom(self.connectingProxies, self.connectedProxies, _self); - // Emit topology Change - emitTopologyDescriptionChanged(self); - // Emit joined event - self.emit('joined', 'mongos', _self); - } else { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - this.destroy(); - } - - // Are we done finish up callback - if (count === 0) { - callback(); - } - }; - }; - - // No new servers - if (count === 0) { - return callback(); - } - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Create a new server instance - var server = new Server( - Object.assign({}, self.s.options, { - host: _server.name.split(':')[0], - port: parseInt(_server.name.split(':')[1], 10), - reconnect: false, - monitoring: false, - parent: self - }) - ); - - destroyServer(_server, { force: true }); - removeProxyFrom(self.disconnectedProxies, _server); - - // Relay the server description change - relayEvents(server, self, ['serverDescriptionChanged']); - - // Emit opening server event - self.emit('serverOpening', { - topologyId: server.s.topologyId !== -1 ? server.s.topologyId : self.id, - address: server.name - }); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Connect to proxy - self.connectingProxies.push(server); - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for (var i = 0; i < proxies.length; i++) { - execute(proxies[i], i); - } -} - -function topologyMonitor(self, options) { - options = options || {}; - - // no need to set up the monitor if we're already closed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Set momitoring timeout - self.haTimeoutId = setTimeout(function() { - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // If we have a primary and a disconnect handler, execute - // buffered operations - if (self.isConnected() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } - - // Get the connectingServers - var proxies = self.connectedProxies.slice(0); - // Get the count - var count = proxies.length; - - // If the count is zero schedule a new fast - function pingServer(_self, _server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); - - // Execute ismaster - _server.command( - 'admin.$cmd', - { - ismaster: true - }, - { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000 - }, - function(err, r) { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - // Move from connectingProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - _server.destroy(); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - - // We had an error, remove it from the state - if (err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: _server.name - }); - // Move from connected proxies to disconnected proxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - } else { - // Update the server ismaster - _server.ismaster = r.result; - _server.lastIsMasterMS = latencyMS; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: _server.name - }); - } - - cb(err, r); - } - ); - } - - // No proxies initiate monitor again - if (proxies.length === 0) { - // Emit close event if any listeners registered - if (self.listeners('close').length > 0 && self.state === CONNECTING) { - self.emit('error', new MongoError('no mongos proxy available')); - } else { - self.emit('close', self); - } - - // Attempt to connect to any unknown servers - return reconnectProxies(self, self.disconnectedProxies, function() { - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Are we connected ? emit connect event - if (self.state === CONNECTING && options.firstConnect) { - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if (self.isConnected()) { - self.emit('reconnect', self); - } else if (!self.isConnected() && self.listeners('close').length > 0) { - self.emit('close', self); - } - - // Perform topology monitor - topologyMonitor(self); - }); - } - - // Ping all servers - for (var i = 0; i < proxies.length; i++) { - pingServer(self, proxies[i], function() { - count = count - 1; - - if (count === 0) { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - return; - } - - // Attempt to connect to any unknown servers - reconnectProxies(self, self.disconnectedProxies, function() { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - return; - } - - // Perform topology monitor - topologyMonitor(self); - }); - } - }); - } - }, self.s.haInterval); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Mongos.prototype.lastIsMaster = function() { - return this.ismaster; -}; - -/** - * Unref all connections belong to this server - * @method - */ -Mongos.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - // Get all proxies - var proxies = this.connectedProxies.concat(this.connectingProxies); - proxies.forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -}; - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -Mongos.prototype.destroy = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - - stateTransition(this, DESTROYING); - if (this.haTimeoutId) { - clearTimeout(this.haTimeoutId); - } - - const proxies = this.connectedProxies.concat(this.connectingProxies); - let serverCount = proxies.length; - const serverDestroyed = () => { - serverCount--; - if (serverCount > 0) { - return; - } - - emitTopologyDescriptionChanged(this); - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); - stateTransition(this, DESTROYED); - if (typeof callback === 'function') { - callback(null, null); - } - }; - - if (serverCount === 0) { - serverDestroyed(); - return; - } - - // Destroy all connecting servers - proxies.forEach(server => { - // Emit the sdam event - this.emit('serverClosed', { - topologyId: this.id, - address: server.name - }); - - destroyServer(server, options, serverDestroyed); - moveServerFrom(this.connectedProxies, this.disconnectedProxies, server); - }); -}; - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Mongos.prototype.isConnected = function() { - return this.connectedProxies.length > 0; -}; - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Mongos.prototype.isDestroyed = function() { - return this.state === DESTROYED; -}; - -// -// Operations -// - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const self = args.self; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - // Pick a server - let server = pickProxy(self, options.session); - // No server found error out - if (!server) return callback(new MongoError('no mongos proxy available')); - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction(); - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err) || !willRetryWrite) { - err = getMMAPError(err); - return callback(err); - } - - // Pick another server - server = pickProxy(self, options.session); - - // No server found error out with original error - if (!server) { - return callback(err); - } - - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // rerun the operation - server[op](ns, ops, options, handler); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.insert = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.update = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.remove = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); -}; - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; - -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.command = function(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - var self = this; - - // Pick a proxy - var server = pickProxy(self, options.session); - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if ((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // No server returned we had an error - if (server == null) { - return callback(new MongoError('no mongos proxy available')); - } - - // Cloned options - var clonedOptions = cloneOptions(options); - clonedOptions.topology = self; - - const willRetryWrite = - !options.retrying && - options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, clonedOptions, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // Execute the command - server.command(ns, cmd, clonedOptions, cb); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -Mongos.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * Selects a server - * - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Unused - * @param {ClientSession} [options.session] Specify a session if it is being used - * @param {function} callback - */ -Mongos.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') - (callback = options), (options = selector), (selector = undefined); - options = options || {}; - - const server = pickProxy(this, options.session); - if (server == null) { - callback(new MongoError('server selection failed')); - return; - } - - if (this.s.debug) this.emit('pickedServer', null, server); - callback(null, server); -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Mongos.prototype.connections = function() { - var connections = []; - - for (var i = 0; i < this.connectedProxies.length; i++) { - connections = connections.concat(this.connectedProxies[i].connections()); - } - - return connections; -}; - -function emitTopologyDescriptionChanged(self) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - if (self.connectedProxies.length > 0) { - topology = 'Sharded'; - } - - // Generate description - var description = { - topologyType: topology, - servers: [] - }; - - // All proxies - var proxies = self.disconnectedProxies.concat(self.connectingProxies); - - // Add all the disconnected proxies - description.servers = description.servers.concat( - proxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Unknown'; - return description; - }) - ); - - // Add all the connected proxies - description.servers = description.servers.concat( - self.connectedProxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Mongos'; - return description; - }) - ); - - // Get the diff - var diffResult = diff(self.topologyDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.topologyDescription, - newDescription: description, - diff: diffResult - }; - - // Emit the topologyDescription change - if (diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - } - - // Set the new description - self.topologyDescription = description; - } -} - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * A mongos reconnect event, used to verify that the mongos topology has reconnected - * - * @event Mongos#reconnect - * @type {Mongos} - */ - -/** - * A mongos fullsetup event, used to signal that all topology members have been contacted. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * A mongos all event, used to signal that all topology members have been contacted. - * - * @event Mongos#all - * @type {Mongos} - */ - -/** - * A server member left the mongos list - * - * @event Mongos#left - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos list - * - * @event Mongos#joined - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that joined - */ - -/** - * A server opening SDAM monitoring event - * - * @event Mongos#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Mongos#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Mongos#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Mongos#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Mongos#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Mongos#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event Mongos#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event Mongos#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event Mongos#serverHeartbeatSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Mongos#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Mongos#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Mongos#commandFailed - * @type {object} - */ - -module.exports = Mongos; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/read_preference.js b/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/read_preference.js deleted file mode 100644 index a813ec4..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/read_preference.js +++ /dev/null @@ -1,202 +0,0 @@ -'use strict'; - -/** - * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is - * used to construct connections. - * @class - * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) - * @param {array} tags The tags object - * @param {object} [options] Additional read preference options - * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds. - * @see https://docs.mongodb.com/manual/core/read-preference/ - * @return {ReadPreference} - */ -const ReadPreference = function(mode, tags, options) { - if (!ReadPreference.isValid(mode)) { - throw new TypeError(`Invalid read preference mode ${mode}`); - } - - // TODO(major): tags MUST be an array of tagsets - if (tags && !Array.isArray(tags)) { - console.warn( - 'ReadPreference tags must be an array, this will change in the next major version' - ); - - if (typeof tags.maxStalenessSeconds !== 'undefined') { - // this is likely an options object - options = tags; - tags = undefined; - } else { - tags = [tags]; - } - } - - this.mode = mode; - this.tags = tags; - - options = options || {}; - if (options.maxStalenessSeconds != null) { - if (options.maxStalenessSeconds <= 0) { - throw new TypeError('maxStalenessSeconds must be a positive integer'); - } - - this.maxStalenessSeconds = options.maxStalenessSeconds; - - // NOTE: The minimum required wire version is 5 for this read preference. If the existing - // topology has a lower value then a MongoError will be thrown during server selection. - this.minWireVersion = 5; - } - - if (this.mode === ReadPreference.PRIMARY) { - if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { - throw new TypeError('Primary read preference cannot be combined with tags'); - } - - if (this.maxStalenessSeconds) { - throw new TypeError('Primary read preference cannot be combined with maxStalenessSeconds'); - } - } -}; - -// Support the deprecated `preference` property introduced in the porcelain layer -Object.defineProperty(ReadPreference.prototype, 'preference', { - enumerable: true, - get: function() { - return this.mode; - } -}); - -/* - * Read preference mode constants - */ -ReadPreference.PRIMARY = 'primary'; -ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; -ReadPreference.SECONDARY = 'secondary'; -ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; -ReadPreference.NEAREST = 'nearest'; - -const VALID_MODES = [ - ReadPreference.PRIMARY, - ReadPreference.PRIMARY_PREFERRED, - ReadPreference.SECONDARY, - ReadPreference.SECONDARY_PREFERRED, - ReadPreference.NEAREST, - null -]; - -/** - * Construct a ReadPreference given an options object. - * - * @param {object} options The options object from which to extract the read preference. - * @return {ReadPreference} - */ -ReadPreference.fromOptions = function(options) { - const readPreference = options.readPreference; - const readPreferenceTags = options.readPreferenceTags; - - if (readPreference == null) { - return null; - } - - if (typeof readPreference === 'string') { - return new ReadPreference(readPreference, readPreferenceTags); - } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { - const mode = readPreference.mode || readPreference.preference; - if (mode && typeof mode === 'string') { - return new ReadPreference(mode, readPreference.tags, { - maxStalenessSeconds: readPreference.maxStalenessSeconds - }); - } - } - - return readPreference; -}; - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} True if a mode is valid - */ -ReadPreference.isValid = function(mode) { - return VALID_MODES.indexOf(mode) !== -1; -}; - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} True if a mode is valid - */ -ReadPreference.prototype.isValid = function(mode) { - return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); -}; - -const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; - -/** - * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire - * @method - * @return {boolean} - * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query - */ -ReadPreference.prototype.slaveOk = function() { - return needSlaveOk.indexOf(this.mode) !== -1; -}; - -/** - * Are the two read preference equal - * @method - * @param {ReadPreference} readPreference The read preference with which to check equality - * @return {boolean} True if the two ReadPreferences are equivalent - */ -ReadPreference.prototype.equals = function(readPreference) { - return readPreference.mode === this.mode; -}; - -/** - * Return JSON representation - * @method - * @return {Object} A JSON representation of the ReadPreference - */ -ReadPreference.prototype.toJSON = function() { - const readPreference = { mode: this.mode }; - if (Array.isArray(this.tags)) readPreference.tags = this.tags; - if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; - return readPreference; -}; - -/** - * Primary read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.primary = new ReadPreference('primary'); -/** - * Primary Preferred read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); -/** - * Secondary read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.secondary = new ReadPreference('secondary'); -/** - * Secondary Preferred read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); -/** - * Nearest read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.nearest = new ReadPreference('nearest'); - -module.exports = ReadPreference; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/replset.js b/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/replset.js deleted file mode 100644 index b289d59..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/replset.js +++ /dev/null @@ -1,1559 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const f = require('util').format; -const EventEmitter = require('events').EventEmitter; -const ReadPreference = require('./read_preference'); -const CoreCursor = require('../cursor').CoreCursor; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const Logger = require('../connection/logger'); -const MongoError = require('../error').MongoError; -const Server = require('./server'); -const ReplSetState = require('./replset_state'); -const Timeout = require('./shared').Timeout; -const Interval = require('./shared').Interval; -const SessionMixins = require('./shared').SessionMixins; -const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; -const relayEvents = require('../utils').relayEvents; -const isRetryableError = require('../error').isRetryableError; -const BSON = retrieveBSON(); -const calculateDurationInMs = require('../utils').calculateDurationInMs; -const getMMAPError = require('./shared').getMMAPError; -const makeClientMetadata = require('../utils').makeClientMetadata; - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYED, DISCONNECTED], - connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], - unreferenced: [UNREFERENCED, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.state = newState; - } else { - self.s.logger.error( - f( - 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * Creates a new Replset instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {boolean} options.setName The Replicaset set name - * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {boolean} [options.emitError=false] Server will emit errors events - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers - * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {ReplSet} A cursor instance - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#failed - * @fires ReplSet#fullsetup - * @fires ReplSet#all - * @fires ReplSet#error - * @fires ReplSet#serverHeartbeatStarted - * @fires ReplSet#serverHeartbeatSucceeded - * @fires ReplSet#serverHeartbeatFailed - * @fires ReplSet#topologyOpening - * @fires ReplSet#topologyClosed - * @fires ReplSet#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var ReplSet = function(seedlist, options) { - var self = this; - options = options || {}; - - // Validate seedlist - if (!Array.isArray(seedlist)) throw new MongoError('seedlist must be an array'); - // Validate list - if (seedlist.length === 0) throw new MongoError('seedlist must contain at least one entry'); - // Validate entries - seedlist.forEach(function(e) { - if (typeof e.host !== 'string' || typeof e.port !== 'number') - throw new MongoError('seedlist entry must contain a host and port'); - }); - - // Add event listener - EventEmitter.call(this); - - // Get replSet Id - this.id = id++; - - // Get the localThresholdMS - var localThresholdMS = options.localThresholdMS || 15; - // Backward compatibility - if (options.acceptableLatency) localThresholdMS = options.acceptableLatency; - - // Create a logger - var logger = Logger('ReplSet', options); - - // Internal state - this.s = { - options: Object.assign({ metadata: makeClientMetadata(options) }, options), - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // Logger instance - logger: logger, - // Seedlist - seedlist: seedlist, - // Replicaset state - replicaSetState: new ReplSetState({ - id: this.id, - setName: options.setName, - acceptableLatency: localThresholdMS, - heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, - logger: logger - }), - // Current servers we are connecting to - connectingServers: [], - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Minimum heartbeat frequency used if we detect a server close - minHeartbeatFrequencyMS: 500, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug === 'boolean' ? options.debug : false - }; - - // Add handler for topology change - this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { - self.emit('topologyDescriptionChanged', r); - }); - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if ( - this.s.logger.isWarn() && - this.s.options.socketTimeout !== 0 && - this.s.options.socketTimeout < this.s.haInterval - ) { - this.s.logger.warn( - f( - 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', - this.s.options.socketTimeout, - this.s.haInterval - ) - ); - } - - // Add forwarding of events from state handler - var types = ['joined', 'left']; - types.forEach(function(x) { - self.s.replicaSetState.on(x, function(t, s) { - self.emit(x, t, s); - }); - }); - - // Connect stat - this.initialConnectState = { - connect: false, - fullsetup: false, - all: false - }; - - // Disconnected state - this.state = DISCONNECTED; - this.haTimeoutId = null; - // Last ismaster - this.ismaster = null; - // Contains the intervalId - this.intervalIds = []; - - // Highest clusterTime seen in responses from the current deployment - this.clusterTime = null; -}; - -inherits(ReplSet, EventEmitter); -Object.assign(ReplSet.prototype, SessionMixins); - -Object.defineProperty(ReplSet.prototype, 'type', { - enumerable: true, - get: function() { - return 'replset'; - } -}); - -Object.defineProperty(ReplSet.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - return this.s.replicaSetState.logicalSessionTimeoutMinutes || null; - } -}); - -function rexecuteOperations(self) { - // If we have a primary and a disconnect handler, execute - // buffered operations - if (self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } else if (self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executePrimary: true }); - } else if (self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executeSecondary: true }); - } -} - -function connectNewServers(self, servers, callback) { - // No new servers - if (servers.length === 0) { - return callback(); - } - - // Count lefts - var count = servers.length; - var error = null; - - function done() { - count = count - 1; - if (count === 0) { - callback(error); - } - } - - // Handle events - var _handleEvent = function(self, event) { - return function(err) { - var _self = this; - - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - this.destroy({ force: true }); - return done(); - } - - if (event === 'connect') { - // Update the state - var result = self.s.replicaSetState.update(_self); - // Update the state with the new server - if (result) { - // Primary lastIsMaster store it - if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) { - self.ismaster = _self.lastIsMaster(); - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Enalbe the monitoring of the new server - monitorServer(_self.lastIsMaster().me, self, {}); - - // Rexecute any stalled operation - rexecuteOperations(self); - } else { - _self.destroy({ force: true }); - } - } else if (event === 'error') { - error = err; - } - - // Rexecute any stalled operation - rexecuteOperations(self); - done(); - }; - }; - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - // remove existing connecting server if it's failed to connect, otherwise - // wait for that server to connect - const existingServerIdx = self.s.connectingServers.findIndex(s => s.name === _server); - if (existingServerIdx >= 0) { - const connectingServer = self.s.connectingServers[existingServerIdx]; - connectingServer.destroy({ force: true }); - - self.s.connectingServers.splice(existingServerIdx, 1); - return done(); - } - - // Create a new server instance - var server = new Server( - Object.assign({}, self.s.options, { - host: _server.split(':')[0], - port: parseInt(_server.split(':')[1], 10), - reconnect: false, - monitoring: false, - parent: self - }) - ); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // SDAM Monitoring events - server.on('serverOpening', e => self.emit('serverOpening', e)); - server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); - server.on('serverClosed', e => self.emit('serverClosed', e)); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - self.s.connectingServers.push(server); - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for (var i = 0; i < servers.length; i++) { - execute(servers[i], i); - } -} - -// Ping the server -var pingServer = function(self, server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); - - // Execute ismaster - // Set the socketTimeout for a monitoring message to a low number - // Ensuring ismaster calls are timed out quickly - server.command( - 'admin.$cmd', - { - ismaster: true - }, - { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000 - }, - function(err, r) { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - server.destroy({ force: true }); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - - // Set the last updatedTime - var hrtime = process.hrtime(); - server.lastUpdateTime = (hrtime[0] * 1e9 + hrtime[1]) / 1e6; - - // We had an error, remove it from the state - if (err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: server.name - }); - - // Remove server from the state - self.s.replicaSetState.remove(server); - } else { - // Update the server ismaster - server.ismaster = r.result; - - // Check if we have a lastWriteDate convert it to MS - // and store on the server instance for later use - if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { - server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); - } - - // Do we have a brand new server - if (server.lastIsMasterMS === -1) { - server.lastIsMasterMS = latencyMS; - } else if (server.lastIsMasterMS) { - // After the first measurement, average RTT MUST be computed using an - // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. - // If the prior average is denoted old_rtt, then the new average (new_rtt) is - // computed from a new RTT measurement (x) using the following formula: - // alpha = 0.2 - // new_rtt = alpha * x + (1 - alpha) * old_rtt - server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; - } - - if (self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if (server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: server.name - }); - } - - // Calculate the staleness for this server - self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); - - // Callback - cb(err, r); - } - ); -}; - -// Each server is monitored in parallel in their own timeout loop -var monitorServer = function(host, self, options) { - // If this is not the initial scan - // Is this server already being monitoried, then skip monitoring - if (!options.haInterval) { - for (var i = 0; i < self.intervalIds.length; i++) { - if (self.intervalIds[i].__host === host) { - return; - } - } - } - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - // Create the interval - var intervalId = new _process(function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - // clearInterval(intervalId); - intervalId.stop(); - return; - } - - // Do we already have server connection available for this host - var _server = self.s.replicaSetState.get(host); - - // Check if we have a known server connection and reuse - if (_server) { - // Ping the server - return pingServer(self, _server, function(err) { - if (err) { - // NOTE: should something happen here? - return; - } - - if (self.state === DESTROYED || self.state === UNREFERENCED) { - intervalId.stop(); - return; - } - - // Filter out all called intervaliIds - self.intervalIds = self.intervalIds.filter(function(intervalId) { - return intervalId.isRunning(); - }); - - // Initial sweep - if (_process === Timeout) { - if ( - self.state === CONNECTING && - ((self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed) || - self.s.replicaSetState.hasPrimary()) - ) { - self.state = CONNECTED; - - // Emit connected sign - process.nextTick(function() { - self.emit('connect', self); - }); - - // Start topology interval check - topologyMonitor(self, {}); - } - } else { - if ( - self.state === DISCONNECTED && - ((self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed) || - self.s.replicaSetState.hasPrimary()) - ) { - self.state = CONNECTED; - - // Rexecute any stalled operation - rexecuteOperations(self); - - // Emit connected sign - process.nextTick(function() { - self.emit('reconnect', self); - }); - } - } - - if ( - self.initialConnectState.connect && - !self.initialConnectState.fullsetup && - self.s.replicaSetState.hasPrimaryAndSecondary() - ) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - }); - } - }, _haInterval); - - // Start the interval - intervalId.start(); - // Add the intervalId host name - intervalId.__host = host; - // Add the intervalId to our list of intervalIds - self.intervalIds.push(intervalId); -}; - -function topologyMonitor(self, options) { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - options = options || {}; - - // Get the servers - var servers = Object.keys(self.s.replicaSetState.set); - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - if (_process === Timeout) { - return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) { - // Don't emit errors if the connection was already - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { - if (err) { - return self.emit('error', err); - } - - self.emit( - 'error', - new MongoError('no primary found in replicaset or invalid replica set name') - ); - return self.destroy({ force: true }); - } else if ( - !self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed - ) { - if (err) { - return self.emit('error', err); - } - - self.emit( - 'error', - new MongoError('no secondary found in replicaset or invalid replica set name') - ); - return self.destroy({ force: true }); - } - - for (var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - }); - } else { - for (var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - } - - // Run the reconnect process - function executeReconnect(self) { - return function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - connectNewServers(self, self.s.replicaSetState.unknownServers, function() { - var monitoringFrequencey = self.s.replicaSetState.hasPrimary() - ? _haInterval - : self.s.minHeartbeatFrequencyMS; - - // Create a timeout - self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); - }); - }; - } - - // Decide what kind of interval to use - var intervalTime = !self.s.replicaSetState.hasPrimary() - ? self.s.minHeartbeatFrequencyMS - : _haInterval; - - self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start()); -} - -function addServerToList(list, server) { - for (var i = 0; i < list.length; i++) { - if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true; - } - - list.push(server); -} - -function handleEvent(self, event) { - return function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id) - ); - } - - // Remove from the replicaset state - self.s.replicaSetState.remove(this); - - // Are we in a destroyed state return - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - - // If no primary and secondary available - if ( - !self.s.replicaSetState.hasPrimary() && - !self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed - ) { - stateTransition(self, DISCONNECTED); - } else if (!self.s.replicaSetState.hasPrimary()) { - stateTransition(self, DISCONNECTED); - } - - addServerToList(self.s.connectingServers, this); - }; -} - -function shouldTriggerConnect(self) { - const isConnecting = self.state === CONNECTING; - const hasPrimary = self.s.replicaSetState.hasPrimary(); - const hasSecondary = self.s.replicaSetState.hasSecondary(); - const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed; - const readPreferenceSecondary = - self.s.connectOptions.readPreference && - self.s.connectOptions.readPreference.equals(ReadPreference.secondary); - - return ( - (isConnecting && - ((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) || - (hasSecondary && secondaryOnlyConnectionAllowed) - ); -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f( - 'handleInitialConnectEvent %s from server %s in replset with id %s', - event, - this.name, - self.id - ) - ); - } - - // Destroy the instance - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return this.destroy({ force: true }); - } - - // Check the type of server - if (event === 'connect') { - // Update the state - var result = self.s.replicaSetState.update(_this); - if (result === true) { - // Primary lastIsMaster store it - if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) { - self.ismaster = _this.lastIsMaster(); - } - - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f( - 'handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', - event, - _this.name, - self.id, - JSON.stringify(self.s.replicaSetState.set) - ) - ); - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Do we have a primary or primaryAndSecondary - if (shouldTriggerConnect(self)) { - // We are connected - self.state = CONNECTED; - - // Set initial connect state - self.initialConnectState.connect = true; - // Emit connect event - process.nextTick(function() { - self.emit('connect', self); - }); - - topologyMonitor(self, {}); - } - } else if (result instanceof MongoError) { - _this.destroy({ force: true }); - self.destroy({ force: true }); - return self.emit('error', result); - } else { - _this.destroy({ force: true }); - } - } else { - // Emit failure to connect - self.emit('failed', this); - - addServerToList(self.s.connectingServers, this); - // Remove from the state - self.s.replicaSetState.remove(this); - } - - if ( - self.initialConnectState.connect && - !self.initialConnectState.fullsetup && - self.s.replicaSetState.hasPrimaryAndSecondary() - ) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - - // Remove from the list from connectingServers - for (var i = 0; i < self.s.connectingServers.length; i++) { - if (self.s.connectingServers[i].equals(this)) { - self.s.connectingServers.splice(i, 1); - } - } - - // Trigger topologyMonitor - if (self.s.connectingServers.length === 0 && self.state === CONNECTING) { - topologyMonitor(self, { haInterval: 1 }); - } - }; -} - -function connectServers(self, servers) { - // Update connectingServers - self.s.connectingServers = self.s.connectingServers.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Add the server to the state - if (self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if (server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - - // SDAM Monitoring events - server.on('serverOpening', e => self.emit('serverOpening', e)); - server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); - server.on('serverClosed', e => self.emit('serverClosed', e)); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - - // Start all the servers - while (servers.length > 0) { - connect(servers.shift(), timeoutInterval++); - } -} - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -/** - * Initiate server connect - */ -ReplSet.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - - // Set connecting state - stateTransition(this, CONNECTING); - - // Create server instances - var servers = this.s.seedlist.map(function(x) { - return new Server( - Object.assign({}, self.s.options, x, options, { - reconnect: false, - monitoring: false, - parent: self - }) - ); - }); - - // Error out as high availbility interval must be < than socketTimeout - if ( - this.s.options.socketTimeout > 0 && - this.s.options.socketTimeout <= this.s.options.haInterval - ) { - return self.emit( - 'error', - new MongoError( - f( - 'haInterval [%s] MS must be set to less than socketTimeout [%s] MS', - this.s.options.haInterval, - this.s.options.socketTimeout - ) - ) - ); - } - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - // Start all server connections - connectServers(self, servers); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -ReplSet.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -ReplSet.prototype.destroy = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - - let destroyCount = this.s.connectingServers.length + 1; // +1 for the callback from `replicaSetState.destroy` - const serverDestroyed = () => { - destroyCount--; - if (destroyCount > 0) { - return; - } - - // Emit toplogy closing event - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); - - // Transition state - stateTransition(this, DESTROYED); - - if (typeof callback === 'function') { - callback(null, null); - } - }; - - // Clear out any monitoring process - if (this.haTimeoutId) clearTimeout(this.haTimeoutId); - - // Clear out all monitoring - for (var i = 0; i < this.intervalIds.length; i++) { - this.intervalIds[i].stop(); - } - - // Reset list of intervalIds - this.intervalIds = []; - - if (destroyCount === 0) { - serverDestroyed(); - return; - } - - // Destroy the replicaset - this.s.replicaSetState.destroy(options, serverDestroyed); - - // Destroy all connecting servers - this.s.connectingServers.forEach(function(x) { - x.destroy(options, serverDestroyed); - }); -}; - -/** - * Unref all connections belong to this server - * @method - */ -ReplSet.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - - this.s.replicaSetState.allServers().forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -}; - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -ReplSet.prototype.lastIsMaster = function() { - // If secondaryOnlyConnectionAllowed and no primary but secondary - // return the secondaries ismaster result. - if ( - this.s.options.secondaryOnlyConnectionAllowed && - !this.s.replicaSetState.hasPrimary() && - this.s.replicaSetState.hasSecondary() - ) { - return this.s.replicaSetState.secondaries[0].lastIsMaster(); - } - - return this.s.replicaSetState.primary - ? this.s.replicaSetState.primary.lastIsMaster() - : this.ismaster; -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -ReplSet.prototype.connections = function() { - var servers = this.s.replicaSetState.allServers(); - var connections = []; - for (var i = 0; i < servers.length; i++) { - connections = connections.concat(servers[i].connections()); - } - - return connections; -}; - -/** - * Figure out if the server is connected - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {boolean} - */ -ReplSet.prototype.isConnected = function(options) { - options = options || {}; - - // If we specified a read preference check if we are connected to something - // than can satisfy this - if (options.readPreference && options.readPreference.equals(ReadPreference.secondary)) { - return this.s.replicaSetState.hasSecondary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.primary)) { - return this.s.replicaSetState.hasPrimary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.primaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.secondaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if (this.s.options.secondaryOnlyConnectionAllowed && this.s.replicaSetState.hasSecondary()) { - return true; - } - - return this.s.replicaSetState.hasPrimary(); -}; - -/** - * Figure out if the replicaset instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -ReplSet.prototype.isDestroyed = function() { - return this.state === DESTROYED; -}; - -const SERVER_SELECTION_TIMEOUT_MS = 10000; // hardcoded `serverSelectionTimeoutMS` for legacy topology -const SERVER_SELECTION_INTERVAL_MS = 1000; // time to wait between selection attempts -/** - * Selects a server - * - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {ClientSession} [options.session] Unused - * @param {function} callback - */ -ReplSet.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') (callback = options), (options = selector); - options = options || {}; - - let readPreference; - if (selector instanceof ReadPreference) { - readPreference = selector; - } else { - readPreference = options.readPreference || ReadPreference.primary; - } - - let lastError; - const start = process.hrtime(); - const _selectServer = () => { - if (calculateDurationInMs(start) >= SERVER_SELECTION_TIMEOUT_MS) { - if (lastError != null) { - callback(lastError, null); - } else { - callback(new MongoError('Server selection timed out')); - } - - return; - } - - const server = this.s.replicaSetState.pickServer(readPreference); - if (server == null) { - setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); - return; - } - - if (!(server instanceof Server)) { - lastError = server; - setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); - return; - } - - if (this.s.debug) this.emit('pickedServer', options.readPreference, server); - callback(null, server); - }; - - _selectServer(); -}; - -/** - * Get all connected servers - * @method - * @return {Server[]} - */ -ReplSet.prototype.getServers = function() { - return this.s.replicaSetState.allServers(); -}; - -// -// Execute write operation -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const self = args.self; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - if (self.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction(); - - if (!self.s.replicaSetState.hasPrimary()) { - if (self.s.disconnectHandler) { - // Not connected but we have a disconnecthandler - return self.s.disconnectHandler.add(op, ns, ops, options, callback); - } else if (!willRetryWrite) { - // No server returned we had an error - return callback(new MongoError('no primary server found')); - } - } - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - err = getMMAPError(err); - return callback(err); - } - - if (willRetryWrite) { - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - } - - // Per SDAM, remove primary from replicaset - if (self.s.replicaSetState.primary) { - self.s.replicaSetState.primary.destroy(); - self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); - } - - return callback(err); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - self.s.replicaSetState.primary[op](ns, ops, options, handler); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.insert = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.update = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.remove = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); -}; - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; - -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.command = function(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - var self = this; - - // Establish readPreference - var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; - - // If the readPreference is primary and we have no primary, store it - if ( - readPreference.preference === 'primary' && - !this.s.replicaSetState.hasPrimary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if ( - readPreference.preference === 'secondary' && - !this.s.replicaSetState.hasSecondary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if ( - readPreference.preference !== 'primary' && - !this.s.replicaSetState.hasSecondary() && - !this.s.replicaSetState.hasPrimary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // Pick a server - var server = this.s.replicaSetState.pickServer(readPreference); - // We received an error, return it - if (!(server instanceof Server)) return callback(server); - // Emit debug event - if (self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); - - // No server returned we had an error - if (server == null) { - return callback( - new MongoError( - f('no server found that matches the provided readPreference %s', readPreference) - ) - ); - } - - const willRetryWrite = - !options.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, options, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - // Per SDAM, remove primary from replicaset - if (this.s.replicaSetState.primary) { - this.s.replicaSetState.primary.destroy(); - this.s.replicaSetState.remove(this.s.replicaSetState.primary, { force: true }); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // Execute the command - server.command(ns, cmd, options, cb); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -ReplSet.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * A replset reconnect event, used to verify that the topology reconnected - * - * @event ReplSet#reconnect - * @type {ReplSet} - */ - -/** - * A replset fullsetup event, used to signal that all topology members have been contacted. - * - * @event ReplSet#fullsetup - * @type {ReplSet} - */ - -/** - * A replset all event, used to signal that all topology members have been contacted. - * - * @event ReplSet#all - * @type {ReplSet} - */ - -/** - * A replset failed event, used to signal that initial replset connection failed. - * - * @event ReplSet#failed - * @type {ReplSet} - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * A server opening SDAM monitoring event - * - * @event ReplSet#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event ReplSet#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event ReplSet#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event ReplSet#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event ReplSet#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event ReplSet#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event ReplSet#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event ReplSet#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event ReplSet#serverHeartbeatSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event ReplSet#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event ReplSet#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event ReplSet#commandFailed - * @type {object} - */ - -module.exports = ReplSet; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/replset_state.js b/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/replset_state.js deleted file mode 100644 index 24c16d6..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/replset_state.js +++ /dev/null @@ -1,1121 +0,0 @@ -'use strict'; - -var inherits = require('util').inherits, - f = require('util').format, - diff = require('./shared').diff, - EventEmitter = require('events').EventEmitter, - Logger = require('../connection/logger'), - ReadPreference = require('./read_preference'), - MongoError = require('../error').MongoError, - Buffer = require('safe-buffer').Buffer; - -var TopologyType = { - Single: 'Single', - ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', - ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', - Sharded: 'Sharded', - Unknown: 'Unknown' -}; - -var ServerType = { - Standalone: 'Standalone', - Mongos: 'Mongos', - PossiblePrimary: 'PossiblePrimary', - RSPrimary: 'RSPrimary', - RSSecondary: 'RSSecondary', - RSArbiter: 'RSArbiter', - RSOther: 'RSOther', - RSGhost: 'RSGhost', - Unknown: 'Unknown' -}; - -var ReplSetState = function(options) { - options = options || {}; - // Add event listener - EventEmitter.call(this); - // Topology state - this.topologyType = TopologyType.ReplicaSetNoPrimary; - this.setName = options.setName; - - // Server set - this.set = {}; - - // Unpacked options - this.id = options.id; - this.setName = options.setName; - - // Replicaset logger - this.logger = options.logger || Logger('ReplSet', options); - - // Server selection index - this.index = 0; - // Acceptable latency - this.acceptableLatency = options.acceptableLatency || 15; - - // heartbeatFrequencyMS - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - - // Server side - this.primary = null; - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - // Current unknown hosts - this.unknownServers = []; - // In set status - this.set = {}; - // Status - this.maxElectionId = null; - this.maxSetVersion = 0; - // Description of the Replicaset - this.replicasetDescription = { - topologyType: 'Unknown', - servers: [] - }; - - this.logicalSessionTimeoutMinutes = undefined; -}; - -inherits(ReplSetState, EventEmitter); - -ReplSetState.prototype.hasPrimaryAndSecondary = function() { - return this.primary != null && this.secondaries.length > 0; -}; - -ReplSetState.prototype.hasPrimaryOrSecondary = function() { - return this.hasPrimary() || this.hasSecondary(); -}; - -ReplSetState.prototype.hasPrimary = function() { - return this.primary != null; -}; - -ReplSetState.prototype.hasSecondary = function() { - return this.secondaries.length > 0; -}; - -ReplSetState.prototype.get = function(host) { - var servers = this.allServers(); - - for (var i = 0; i < servers.length; i++) { - if (servers[i].name.toLowerCase() === host.toLowerCase()) { - return servers[i]; - } - } - - return null; -}; - -ReplSetState.prototype.allServers = function(options) { - options = options || {}; - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - if (!options.ignoreArbiters) servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - return servers; -}; - -ReplSetState.prototype.destroy = function(options, callback) { - const serversToDestroy = this.secondaries - .concat(this.arbiters) - .concat(this.passives) - .concat(this.ghosts); - if (this.primary) serversToDestroy.push(this.primary); - - let serverCount = serversToDestroy.length; - const serverDestroyed = () => { - serverCount--; - if (serverCount > 0) { - return; - } - - // Clear out the complete state - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - this.unknownServers = []; - this.set = {}; - this.primary = null; - - // Emit the topology changed - emitTopologyDescriptionChanged(this); - - if (typeof callback === 'function') { - callback(null, null); - } - }; - - if (serverCount === 0) { - serverDestroyed(); - return; - } - - serversToDestroy.forEach(server => server.destroy(options, serverDestroyed)); -}; - -ReplSetState.prototype.remove = function(server, options) { - options = options || {}; - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // Only remove if the current server is not connected - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - - // Check if it's active and this is just a failed connection attempt - for (var i = 0; i < servers.length; i++) { - if ( - !options.force && - servers[i].equals(server) && - servers[i].isConnected && - servers[i].isConnected() - ) { - return; - } - } - - // If we have it in the set remove it - if (this.set[serverName]) { - this.set[serverName].type = ServerType.Unknown; - this.set[serverName].electionId = null; - this.set[serverName].setName = null; - this.set[serverName].setVersion = null; - } - - // Remove type - var removeType = null; - - // Remove from any lists - if (this.primary && this.primary.equals(server)) { - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - removeType = 'primary'; - } - - // Remove from any other server lists - removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; - removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; - removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; - removeFrom(server, this.ghosts); - removeFrom(server, this.unknownServers); - - // Push to unknownServers - this.unknownServers.push(serverName); - - // Do we have a removeType - if (removeType) { - this.emit('left', removeType, server); - } -}; - -const isArbiter = ismaster => ismaster.arbiterOnly && ismaster.setName; - -ReplSetState.prototype.update = function(server) { - var self = this; - // Get the current ismaster - var ismaster = server.lastIsMaster(); - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // - // Add any hosts - // - if (ismaster) { - // Join all the possible new hosts - var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; - hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); - hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); - hosts = hosts.map(function(s) { - return s.toLowerCase(); - }); - - // Add all hosts as unknownServers - for (var i = 0; i < hosts.length; i++) { - // Add to the list of unknown server - if ( - this.unknownServers.indexOf(hosts[i]) === -1 && - (!this.set[hosts[i]] || this.set[hosts[i]].type === ServerType.Unknown) - ) { - this.unknownServers.push(hosts[i].toLowerCase()); - } - - if (!this.set[hosts[i]]) { - this.set[hosts[i]] = { - type: ServerType.Unknown, - electionId: null, - setName: null, - setVersion: null - }; - } - } - } - - // - // Unknown server - // - if (!ismaster && !inList(ismaster, server, this.unknownServers)) { - self.set[serverName] = { - type: ServerType.Unknown, - setVersion: null, - electionId: null, - setName: null - }; - // Update set information about the server instance - self.set[serverName].type = ServerType.Unknown; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - - if (self.unknownServers.indexOf(server.name) === -1) { - self.unknownServers.push(serverName); - } - - // Set the topology - return false; - } - - // Update logicalSessionTimeoutMinutes - if (ismaster.logicalSessionTimeoutMinutes !== undefined && !isArbiter(ismaster)) { - if ( - self.logicalSessionTimeoutMinutes === undefined || - ismaster.logicalSessionTimeoutMinutes === null - ) { - self.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; - } else { - self.logicalSessionTimeoutMinutes = Math.min( - self.logicalSessionTimeoutMinutes, - ismaster.logicalSessionTimeoutMinutes - ); - } - } - - // - // Is this a mongos - // - if (ismaster && ismaster.msg === 'isdbgrid') { - if (this.primary && this.primary.name === serverName) { - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - return false; - } - - // A RSGhost instance - if (ismaster.isreplicaset) { - self.set[serverName] = { - type: ServerType.RSGhost, - setVersion: null, - electionId: null, - setName: ismaster.setName - }; - - if (this.primary && this.primary.name === serverName) { - this.primary = null; - } - - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - - // Set the topology - return false; - } - - // A RSOther instance - if ( - (ismaster.setName && ismaster.hidden) || - (ismaster.setName && - !ismaster.ismaster && - !ismaster.secondary && - !ismaster.arbiterOnly && - !ismaster.passive) - ) { - self.set[serverName] = { - type: ServerType.RSOther, - setVersion: null, - electionId: null, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - return false; - } - - // - // Standalone server, destroy and return - // - if (ismaster && ismaster.ismaster && !ismaster.setName) { - this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown; - this.remove(server, { force: true }); - return false; - } - - // - // Server in maintanance mode - // - if (ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { - this.remove(server, { force: true }); - return false; - } - - // - // If the .me field does not match the passed in server - // - if (ismaster.me && ismaster.me.toLowerCase() !== serverName) { - if (this.logger.isWarn()) { - this.logger.warn( - f( - 'the seedlist server was removed due to its address %s not matching its ismaster.me address %s', - server.name, - ismaster.me - ) - ); - } - - // Delete from the set - delete this.set[serverName]; - // Delete unknown servers - removeFrom(server, self.unknownServers); - - // Destroy the instance - server.destroy({ force: true }); - - // Set the type of topology we have - if (this.primary && !this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - // - // We have a potential primary - // - if (!this.primary && ismaster.primary) { - this.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, - setName: null, - electionId: null, - setVersion: null - }; - } - - return false; - } - - // - // Primary handling - // - if (!this.primary && ismaster.ismaster && ismaster.setName) { - var ismasterElectionId = server.lastIsMaster().electionId; - if (this.setName && this.setName !== ismaster.setName) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return new MongoError( - f( - 'setName from ismaster does not match provided connection setName [%s] != [%s]', - ismaster.setName, - this.setName - ) - ); - } - - if (!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if (this.maxElectionId && ismasterElectionId) { - var result = compareObjectIds(this.maxElectionId, ismasterElectionId); - // Get the electionIds - var ismasterSetVersion = server.lastIsMaster().setVersion; - - if (result === 1) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } else if (result === 0 && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - } - - this.maxSetVersion = ismasterSetVersion; - this.maxElectionId = ismasterElectionId; - } - - // Hande normalization of server names - var normalizedHosts = ismaster.hosts.map(function(x) { - return x.toLowerCase(); - }); - var locationIndex = normalizedHosts.indexOf(serverName); - - // Validate that the server exists in the host list - if (locationIndex !== -1) { - self.primary = server; - self.set[serverName] = { - type: ServerType.RSPrimary, - setVersion: ismaster.setVersion, - electionId: ismaster.electionId, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - emitTopologyDescriptionChanged(self); - return true; - } else if (ismaster.ismaster && ismaster.setName) { - // Get the electionIds - var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; - var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; - var currentSetName = self.set[self.primary.name.toLowerCase()].setName; - ismasterElectionId = server.lastIsMaster().electionId; - ismasterSetVersion = server.lastIsMaster().setVersion; - var ismasterSetName = server.lastIsMaster().setName; - - // Is it the same server instance - if (this.primary.equals(server) && currentSetName === ismasterSetName) { - return false; - } - - // If we do not have the same rs name - if (currentSetName && currentSetName !== ismasterSetName) { - if (!this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - return false; - } - - // Check if we need to replace the server - if (currentElectionId && ismasterElectionId) { - result = compareObjectIds(currentElectionId, ismasterElectionId); - - if (result === 1) { - return false; - } else if (result === 0 && currentSetVersion > ismasterSetVersion) { - return false; - } - } else if (!currentElectionId && ismasterElectionId && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - if (!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if (this.maxElectionId && ismasterElectionId) { - result = compareObjectIds(this.maxElectionId, ismasterElectionId); - - if (result === 1) { - return false; - } else if (result === 0 && currentSetVersion && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } else { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - this.maxElectionId = ismasterElectionId; - this.maxSetVersion = ismasterSetVersion; - } else { - this.maxSetVersion = ismasterSetVersion; - } - - // Modify the entry to unknown - self.set[self.primary.name.toLowerCase()] = { - type: ServerType.Unknown, - setVersion: null, - electionId: null, - setName: null - }; - - // Signal primary left - self.emit('left', 'primary', this.primary); - // Destroy the instance - self.primary.destroy({ force: true }); - // Set the new instance - self.primary = server; - // Set the set information - self.set[serverName] = { - type: ServerType.RSPrimary, - setVersion: ismaster.setVersion, - electionId: ismaster.electionId, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // A possible instance - if (!this.primary && ismaster.primary) { - self.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, - setVersion: null, - electionId: null, - setName: null - }; - } - - // - // Secondary handling - // - if ( - ismaster.secondary && - ismaster.setName && - !inList(ismaster, server, this.secondaries) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if (this.primary && this.primary.name.toLowerCase() === serverName) { - server.destroy({ force: true }); - this.primary = null; - self.emit('left', 'primary', server); - } - - // Emit secondary joined replicaset - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Arbiter handling - // - if ( - isArbiter(ismaster) && - !inList(ismaster, server, this.arbiters) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - self.emit('joined', 'arbiter', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Passive handling - // - if ( - ismaster.passive && - ismaster.setName && - !inList(ismaster, server, this.passives) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if (this.primary && this.primary.name.toLowerCase() === serverName) { - server.destroy({ force: true }); - this.primary = null; - self.emit('left', 'primary', server); - } - - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Remove the primary - // - if (this.set[serverName] && this.set[serverName].type === ServerType.RSPrimary) { - self.emit('left', 'primary', this.primary); - this.primary.destroy({ force: true }); - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - return false; -}; - -/** - * Recalculate single server max staleness - * @method - */ -ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { - // Locate the max secondary lastwrite - var max = 0; - // Go over all secondaries - for (var i = 0; i < this.secondaries.length; i++) { - max = Math.max(max, this.secondaries[i].lastWriteDate); - } - - // Perform this servers staleness calculation - if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary && this.hasPrimary()) { - server.staleness = - server.lastUpdateTime - - server.lastWriteDate - - (this.primary.lastUpdateTime - this.primary.lastWriteDate) + - haInterval; - } else if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary) { - server.staleness = max - server.lastWriteDate + haInterval; - } -}; - -/** - * Recalculate all the staleness values for secodaries - * @method - */ -ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { - for (var i = 0; i < this.secondaries.length; i++) { - this.updateServerMaxStaleness(this.secondaries[i], haInterval); - } -}; - -/** - * Pick a server by the passed in ReadPreference - * @method - * @param {ReadPreference} readPreference The ReadPreference instance to use - */ -ReplSetState.prototype.pickServer = function(readPreference) { - // If no read Preference set to primary by default - readPreference = readPreference || ReadPreference.primary; - - // maxStalenessSeconds is not allowed with a primary read - if (readPreference.preference === 'primary' && readPreference.maxStalenessSeconds != null) { - return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); - } - - // Check if we have any non compatible servers for maxStalenessSeconds - var allservers = this.primary ? [this.primary] : []; - allservers = allservers.concat(this.secondaries); - - // Does any of the servers not support the right wire protocol version - // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out - if (readPreference.maxStalenessSeconds != null) { - for (var i = 0; i < allservers.length; i++) { - if (allservers[i].ismaster.maxWireVersion < 5) { - return new MongoError( - 'maxStalenessSeconds not supported by at least one of the replicaset members' - ); - } - } - } - - // Do we have the nearest readPreference - if (readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds == null) { - return pickNearest(this, readPreference); - } else if ( - readPreference.preference === 'nearest' && - readPreference.maxStalenessSeconds != null - ) { - return pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Get all the secondaries - var secondaries = this.secondaries; - - // Check if we can satisfy and of the basic read Preferences - if (readPreference.equals(ReadPreference.secondary) && secondaries.length === 0) { - return new MongoError('no secondary server available'); - } - - if ( - readPreference.equals(ReadPreference.secondaryPreferred) && - secondaries.length === 0 && - this.primary == null - ) { - return new MongoError('no secondary or primary server available'); - } - - if (readPreference.equals(ReadPreference.primary) && this.primary == null) { - return new MongoError('no primary server available'); - } - - // Secondary preferred or just secondaries - if ( - readPreference.equals(ReadPreference.secondaryPreferred) || - readPreference.equals(ReadPreference.secondary) - ) { - if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - // Pick nearest of any other servers available - var server = pickNearest(this, readPreference); - // No server in the window return primary - if (server) { - return server; - } - } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - // Pick nearest of any other servers available - server = pickNearestMaxStalenessSeconds(this, readPreference); - // No server in the window return primary - if (server) { - return server; - } - } - - if (readPreference.equals(ReadPreference.secondaryPreferred)) { - return this.primary; - } - - return null; - } - - // Primary preferred - if (readPreference.equals(ReadPreference.primaryPreferred)) { - server = null; - - // We prefer the primary if it's available - if (this.primary) { - return this.primary; - } - - // Pick a secondary - if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - server = pickNearest(this, readPreference); - } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - server = pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Did we find a server - if (server) return server; - } - - // Return the primary - return this.primary; -}; - -// -// Filter serves by tags -var filterByTags = function(readPreference, servers) { - if (readPreference.tags == null) return servers; - var filteredServers = []; - var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; - - // Iterate over the tags - for (var j = 0; j < tagsArray.length; j++) { - var tags = tagsArray[j]; - - // Iterate over all the servers - for (var i = 0; i < servers.length; i++) { - var serverTag = servers[i].lastIsMaster().tags || {}; - - // Did we find the a matching server - var found = true; - // Check if the server is valid - for (var name in tags) { - if (serverTag[name] !== tags[name]) { - found = false; - } - } - - // Add to candidate list - if (found) { - filteredServers.push(servers[i]); - } - } - } - - // Returned filtered servers - return filteredServers; -}; - -function pickNearestMaxStalenessSeconds(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - - // Get the maxStalenessMS - var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; - - // Check if the maxStalenessMS > 90 seconds - if (maxStalenessMS < 90 * 1000) { - return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); - } - - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== 'secondary' && - readPreference.preference !== 'secondaryPreferred' - ) { - servers.push(self.primary); - } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if (self.primary && servers.length === 0 && readPreference.preference !== 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Filter by latency - servers = servers.filter(function(s) { - return s.staleness <= maxStalenessMS; - }); - - // Sort by time - servers.sort(function(a, b) { - return a.lastIsMasterMS - b.lastIsMasterMS; - }); - - // No servers, default to primary - if (servers.length === 0) { - return null; - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function pickNearest(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== 'secondary' && - readPreference.preference !== 'secondaryPreferred' - ) { - servers.push(self.primary); - } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if (servers.length === 0 && self.primary && readPreference.preference !== 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Sort by time - servers.sort(function(a, b) { - return a.lastIsMasterMS - b.lastIsMasterMS; - }); - - // Locate lowest time (picked servers are lowest time + acceptable Latency margin) - var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; - - // Filter by latency - servers = servers.filter(function(s) { - return s.lastIsMasterMS <= lowest + self.acceptableLatency; - }); - - // No servers, default to primary - if (servers.length === 0) { - return null; - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function inList(ismaster, server, list) { - for (var i = 0; i < list.length; i++) { - if (list[i] && list[i].name && list[i].name.toLowerCase() === server.name.toLowerCase()) - return true; - } - - return false; -} - -function addToList(self, type, ismaster, server, list) { - var serverName = server.name.toLowerCase(); - // Update set information about the server instance - self.set[serverName].type = type; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - // Add to the list - list.push(server); -} - -function compareObjectIds(id1, id2) { - var a = Buffer.from(id1.toHexString(), 'hex'); - var b = Buffer.from(id2.toHexString(), 'hex'); - - if (a === b) { - return 0; - } - - if (typeof Buffer.compare === 'function') { - return Buffer.compare(a, b); - } - - var x = a.length; - var y = b.length; - var len = Math.min(x, y); - - for (var i = 0; i < len; i++) { - if (a[i] !== b[i]) { - break; - } - } - - if (i !== len) { - x = a[i]; - y = b[i]; - } - - return x < y ? -1 : y < x ? 1 : 0; -} - -function removeFrom(server, list) { - for (var i = 0; i < list.length; i++) { - if (list[i].equals && list[i].equals(server)) { - list.splice(i, 1); - return true; - } else if (typeof list[i] === 'string' && list[i].toLowerCase() === server.name.toLowerCase()) { - list.splice(i, 1); - return true; - } - } - - return false; -} - -function emitTopologyDescriptionChanged(self) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - var setName = self.setName; - - if (self.hasPrimaryAndSecondary()) { - topology = 'ReplicaSetWithPrimary'; - } else if (!self.hasPrimary() && self.hasSecondary()) { - topology = 'ReplicaSetNoPrimary'; - } - - // Generate description - var description = { - topologyType: topology, - setName: setName, - servers: [] - }; - - // Add the primary to the list - if (self.hasPrimary()) { - var desc = self.primary.getDescription(); - desc.type = 'RSPrimary'; - description.servers.push(desc); - } - - // Add all the secondaries - description.servers = description.servers.concat( - self.secondaries.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - }) - ); - - // Add all the arbiters - description.servers = description.servers.concat( - self.arbiters.map(function(x) { - var description = x.getDescription(); - description.type = 'RSArbiter'; - return description; - }) - ); - - // Add all the passives - description.servers = description.servers.concat( - self.passives.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - }) - ); - - // Get the diff - var diffResult = diff(self.replicasetDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.replicasetDescription, - newDescription: description, - diff: diffResult - }; - - // Emit the topologyDescription change - // if(diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - // } - - // Set the new description - self.replicasetDescription = description; - } -} - -module.exports = ReplSetState; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/server.js b/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/server.js deleted file mode 100644 index 6f6de12..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/server.js +++ /dev/null @@ -1,990 +0,0 @@ -'use strict'; - -var inherits = require('util').inherits, - f = require('util').format, - EventEmitter = require('events').EventEmitter, - ReadPreference = require('./read_preference'), - Logger = require('../connection/logger'), - debugOptions = require('../connection/utils').debugOptions, - retrieveBSON = require('../connection/utils').retrieveBSON, - Pool = require('../connection/pool'), - MongoError = require('../error').MongoError, - MongoNetworkError = require('../error').MongoNetworkError, - wireProtocol = require('../wireprotocol'), - CoreCursor = require('../cursor').CoreCursor, - sdam = require('./shared'), - createCompressionInfo = require('./shared').createCompressionInfo, - resolveClusterTime = require('./shared').resolveClusterTime, - SessionMixins = require('./shared').SessionMixins, - relayEvents = require('../utils').relayEvents; - -const collationNotSupported = require('../utils').collationNotSupported; -const makeClientMetadata = require('../utils').makeClientMetadata; - -// Used for filtering out fields for loggin -var debugFields = [ - 'reconnect', - 'reconnectTries', - 'reconnectInterval', - 'emitError', - 'cursorFactory', - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'checkServerIdentity', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'key', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'servername' -]; - -// Server instance id -var id = 0; -var serverAccounting = false; -var servers = {}; -var BSON = retrieveBSON(); - -function topologyId(server) { - return server.s.parent == null ? server.id : server.s.parent.id; -} - -/** - * Creates a new Server instance - * @class - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) - * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {Server} A cursor instance - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @fires Server#reconnectFailed - * @fires Server#serverHeartbeatStarted - * @fires Server#serverHeartbeatSucceeded - * @fires Server#serverHeartbeatFailed - * @fires Server#topologyOpening - * @fires Server#topologyClosed - * @fires Server#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Server = function(options) { - options = options || {}; - - // Add event listener - EventEmitter.call(this); - - // Server instance id - this.id = id++; - - // Internal state - this.s = { - // Options - options: Object.assign({ metadata: makeClientMetadata(options) }, options), - // Logger - logger: Logger('Server', options), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Pool - pool: null, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Monitor thread (keeps the connection alive) - monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, - // Is the server in a topology - inTopology: !!options.parent, - // Monitoring timeout - monitoringInterval: - typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, - compression: { compressors: createCompressionInfo(options) }, - // Optional parent topology - parent: options.parent - }; - - // If this is a single deployment we need to track the clusterTime here - if (!this.s.parent) { - this.s.clusterTime = null; - } - - // Curent ismaster - this.ismaster = null; - // Current ping time - this.lastIsMasterMS = -1; - // The monitoringProcessId - this.monitoringProcessId = null; - // Initial connection - this.initialConnect = true; - // Default type - this._type = 'server'; - - // Max Stalleness values - // last time we updated the ismaster state - this.lastUpdateTime = 0; - // Last write time - this.lastWriteDate = 0; - // Stalleness - this.staleness = 0; -}; - -inherits(Server, EventEmitter); -Object.assign(Server.prototype, SessionMixins); - -Object.defineProperty(Server.prototype, 'type', { - enumerable: true, - get: function() { - return this._type; - } -}); - -Object.defineProperty(Server.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - if (!this.ismaster) return null; - return this.ismaster.logicalSessionTimeoutMinutes || null; - } -}); - -Object.defineProperty(Server.prototype, 'clientMetadata', { - enumerable: true, - get: function() { - return this.s.options.metadata; - } -}); - -// In single server deployments we track the clusterTime directly on the topology, however -// in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the -// tracking objects so we can ensure we are gossiping the maximum time received from the -// server. -Object.defineProperty(Server.prototype, 'clusterTime', { - enumerable: true, - set: function(clusterTime) { - const settings = this.s.parent ? this.s.parent : this.s; - resolveClusterTime(settings, clusterTime); - }, - get: function() { - const settings = this.s.parent ? this.s.parent : this.s; - return settings.clusterTime || null; - } -}); - -Server.enableServerAccounting = function() { - serverAccounting = true; - servers = {}; -}; - -Server.disableServerAccounting = function() { - serverAccounting = false; -}; - -Server.servers = function() { - return servers; -}; - -Object.defineProperty(Server.prototype, 'name', { - enumerable: true, - get: function() { - return this.s.options.host + ':' + this.s.options.port; - } -}); - -function disconnectHandler(self, type, ns, cmd, options, callback) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if ( - !self.s.pool.isConnected() && - self.s.options.reconnect && - self.s.disconnectHandler != null && - !options.monitoring - ) { - self.s.disconnectHandler.add(type, ns, cmd, options, callback); - return true; - } - - // If we have no connection error - if (!self.s.pool.isConnected()) { - callback(new MongoError(f('no connection available to server %s', self.name))); - return true; - } -} - -function monitoringProcess(self) { - return function() { - // Pool was destroyed do not continue process - if (self.s.pool.isDestroyed()) return; - // Emit monitoring Process event - self.emit('monitoring', self); - // Perform ismaster call - // Get start time - var start = new Date().getTime(); - - // Execute the ismaster query - self.command( - 'admin.$cmd', - { ismaster: true }, - { - socketTimeout: - typeof self.s.options.connectionTimeout !== 'number' - ? 2000 - : self.s.options.connectionTimeout, - monitoring: true - }, - (err, result) => { - // Set initial lastIsMasterMS - self.lastIsMasterMS = new Date().getTime() - start; - if (self.s.pool.isDestroyed()) return; - // Update the ismaster view if we have a result - if (result) { - self.ismaster = result.result; - } - // Re-schedule the monitoring process - self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); - } - ); - }; -} - -var eventHandler = function(self, event) { - return function(err, conn) { - // Log information of received information if in info mode - if (self.s.logger.isInfo()) { - var object = err instanceof MongoError ? JSON.stringify(err) : {}; - self.s.logger.info( - f('server %s fired event %s out with message %s', self.name, event, object) - ); - } - - // Handle connect event - if (event === 'connect') { - self.initialConnect = false; - self.ismaster = conn.ismaster; - self.lastIsMasterMS = conn.lastIsMasterMS; - if (conn.agreedCompressor) { - self.s.pool.options.agreedCompressor = conn.agreedCompressor; - } - - if (conn.zlibCompressionLevel) { - self.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel; - } - - if (conn.ismaster.$clusterTime) { - const $clusterTime = conn.ismaster.$clusterTime; - self.clusterTime = $clusterTime; - } - - // It's a proxy change the type so - // the wireprotocol will send $readPreference - if (self.ismaster.msg === 'isdbgrid') { - self._type = 'mongos'; - } - - // Have we defined self monitoring - if (self.s.monitoring) { - self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); - } - - // Emit server description changed if something listening - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - }); - - if (!self.s.inTopology) { - // Emit topology description changed if something listening - sdam.emitTopologyDescriptionChanged(self, { - topologyType: 'Single', - servers: [ - { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - } - ] - }); - } - - // Log the ismaster if available - if (self.s.logger.isInfo()) { - self.s.logger.info( - f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster)) - ); - } - - // Emit connect - self.emit('connect', self); - } else if ( - event === 'error' || - event === 'parseError' || - event === 'close' || - event === 'timeout' || - event === 'reconnect' || - event === 'attemptReconnect' || - 'reconnectFailed' - ) { - // Remove server instance from accounting - if ( - serverAccounting && - ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1 - ) { - // Emit toplogy opening event if not in topology - if (!self.s.inTopology) { - self.emit('topologyOpening', { topologyId: self.id }); - } - - delete servers[self.id]; - } - - if (event === 'close') { - // Closing emits a server description changed event going to unknown. - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - }); - } - - // Reconnect failed return error - if (event === 'reconnectFailed') { - self.emit('reconnectFailed', err); - // Emit error if any listeners - if (self.listeners('error').length > 0) { - self.emit('error', err); - } - // Terminate - return; - } - - // On first connect fail - if ( - ['disconnected', 'connecting'].indexOf(self.s.pool.state) !== -1 && - self.initialConnect && - ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1 - ) { - self.initialConnect = false; - return self.emit( - 'error', - new MongoNetworkError( - f('failed to connect to server [%s] on first connect [%s]', self.name, err) - ) - ); - } - - // Reconnect event, emit the server - if (event === 'reconnect') { - // Reconnecting emits a server description changed event going from unknown to the - // current server type. - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - }); - return self.emit(event, self); - } - - // Emit the event - self.emit(event, err); - } - }; -}; - -/** - * Initiate server connect - */ -Server.prototype.connect = function(options) { - var self = this; - options = options || {}; - - // Set the connections - if (serverAccounting) servers[this.id] = this; - - // Do not allow connect to be called on anything that's not disconnected - if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { - throw new MongoError(f('server instance in invalid state %s', self.s.pool.state)); - } - - // Create a pool - self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson })); - - // Set up listeners - self.s.pool.on('close', eventHandler(self, 'close')); - self.s.pool.on('error', eventHandler(self, 'error')); - self.s.pool.on('timeout', eventHandler(self, 'timeout')); - self.s.pool.on('parseError', eventHandler(self, 'parseError')); - self.s.pool.on('connect', eventHandler(self, 'connect')); - self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); - self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); - - // Set up listeners for command monitoring - relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Emit toplogy opening event if not in topology - if (!self.s.inTopology) { - this.emit('topologyOpening', { topologyId: topologyId(self) }); - } - - // Emit opening server event - self.emit('serverOpening', { topologyId: topologyId(self), address: self.name }); - - self.s.pool.connect(); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -Server.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Get the server description - * @method - * @return {object} - */ -Server.prototype.getDescription = function() { - var ismaster = this.ismaster || {}; - var description = { - type: sdam.getTopologyType(this), - address: this.name - }; - - // Add fields if available - if (ismaster.hosts) description.hosts = ismaster.hosts; - if (ismaster.arbiters) description.arbiters = ismaster.arbiters; - if (ismaster.passives) description.passives = ismaster.passives; - if (ismaster.setName) description.setName = ismaster.setName; - return description; -}; - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Server.prototype.lastIsMaster = function() { - return this.ismaster; -}; - -/** - * Unref all connections belong to this server - * @method - */ -Server.prototype.unref = function() { - this.s.pool.unref(); -}; - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Server.prototype.isConnected = function() { - if (!this.s.pool) return false; - return this.s.pool.isConnected(); -}; - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Server.prototype.isDestroyed = function() { - if (!this.s.pool) return false; - return this.s.pool.isDestroyed(); -}; - -function basicWriteValidations(self) { - if (!self.s.pool) return new MongoError('server instance is not connected'); - if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed'); -} - -function basicReadValidations(self, options) { - basicWriteValidations(self, options); - - if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { - throw new Error('readPreference must be an instance of ReadPreference'); - } -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.command = function(ns, cmd, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicReadValidations(self, options); - if (result) return callback(result); - - // Clone the options - options = Object.assign({}, options, { wireProtocolCommand: false }); - - // Debug log - if (self.s.logger.isDebug()) - self.s.logger.debug( - f( - 'executing command [%s] against %s', - JSON.stringify({ - ns: ns, - cmd: cmd, - options: debugOptions(debugFields, options) - }), - self.name - ) - ); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, cmd)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - wireProtocol.command(self, ns, cmd, options, callback); -}; - -/** - * Execute a query against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command document for the query - * @param {object} options Optional settings - * @param {function} callback - */ -Server.prototype.query = function(ns, cmd, cursorState, options, callback) { - wireProtocol.query(this, ns, cmd, cursorState, options, callback); -}; - -/** - * Execute a `getMore` against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {object} options Optional settings - * @param {function} callback - */ -Server.prototype.getMore = function(ns, cursorState, batchSize, options, callback) { - wireProtocol.getMore(this, ns, cursorState, batchSize, options, callback); -}; - -/** - * Execute a `killCursors` command against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {function} callback - */ -Server.prototype.killCursors = function(ns, cursorState, callback) { - wireProtocol.killCursors(this, ns, cursorState, callback); -}; - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.insert = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return; - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - - // Execute write - return wireProtocol.insert(self, ns, ops, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.update = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'update', ns, ops, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, options)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return wireProtocol.update(self, ns, ops, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.remove = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, options)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return wireProtocol.remove(self, ns, ops, options, callback); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -Server.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * Compare two server instances - * @method - * @param {Server} server Server to compare equality against - * @return {boolean} - */ -Server.prototype.equals = function(server) { - if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase(); - if (server.name) return this.name.toLowerCase() === server.name.toLowerCase(); - return false; -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Server.prototype.connections = function() { - return this.s.pool.allConnections(); -}; - -/** - * Selects a server - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Unused - * @param {ClientSession} [options.session] Unused - * @return {Server} - */ -Server.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') - (callback = options), (options = selector), (selector = undefined); - - callback(null, this); -}; - -var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; - -/** - * Destroy the server connection - * @method - * @param {boolean} [options.emitClose=false] Emit close event on destroy - * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy - * @param {boolean} [options.force=false] Force destroy the pool - */ -Server.prototype.destroy = function(options, callback) { - if (this._destroyed) { - if (typeof callback === 'function') callback(null, null); - return; - } - - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - var self = this; - - // Set the connections - if (serverAccounting) delete servers[this.id]; - - // Destroy the monitoring process if any - if (this.monitoringProcessId) { - clearTimeout(this.monitoringProcessId); - } - - // No pool, return - if (!self.s.pool) { - this._destroyed = true; - if (typeof callback === 'function') callback(null, null); - return; - } - - // Emit close event - if (options.emitClose) { - self.emit('close', self); - } - - // Emit destroy event - if (options.emitDestroy) { - self.emit('destroy', self); - } - - // Remove all listeners - listeners.forEach(function(event) { - self.s.pool.removeAllListeners(event); - }); - - // Emit opening server event - if (self.listeners('serverClosed').length > 0) - self.emit('serverClosed', { topologyId: topologyId(self), address: self.name }); - - // Emit toplogy opening event if not in topology - if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { - self.emit('topologyClosed', { topologyId: topologyId(self) }); - } - - if (self.s.logger.isDebug()) { - self.s.logger.debug(f('destroy called on server %s', self.name)); - } - - // Destroy the pool - this.s.pool.destroy(options.force, callback); - this._destroyed = true; -}; - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Server#connect - * @type {Server} - */ - -/** - * A server reconnect event, used to verify that the server topology has reconnected - * - * @event Server#reconnect - * @type {Server} - */ - -/** - * A server opening SDAM monitoring event - * - * @event Server#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Server#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Server#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Server#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Server#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Server#topologyDescriptionChanged - * @type {object} - */ - -/** - * Server reconnect failed - * - * @event Server#reconnectFailed - * @type {Error} - */ - -/** - * Server connection pool closed - * - * @event Server#close - * @type {object} - */ - -/** - * Server connection pool caused an error - * - * @event Server#error - * @type {Error} - */ - -/** - * Server destroyed was called - * - * @event Server#destroy - * @type {Server} - */ - -module.exports = Server; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/shared.js b/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/shared.js deleted file mode 100644 index 590004b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/topologies/shared.js +++ /dev/null @@ -1,433 +0,0 @@ -'use strict'; -const ReadPreference = require('./read_preference'); -const TopologyType = require('../sdam/common').TopologyType; -const MongoError = require('../error').MongoError; - -const MMAPv1_RETRY_WRITES_ERROR_CODE = 20; - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -function createCompressionInfo(options) { - if (!options.compression || !options.compression.compressors) { - return []; - } - - // Check that all supplied compressors are valid - options.compression.compressors.forEach(function(compressor) { - if (compressor !== 'snappy' && compressor !== 'zlib') { - throw new Error('compressors must be at least one of snappy or zlib'); - } - }); - - return options.compression.compressors; -} - -function clone(object) { - return JSON.parse(JSON.stringify(object)); -} - -var getPreviousDescription = function(self) { - if (!self.s.serverDescription) { - self.s.serverDescription = { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - }; - } - - return self.s.serverDescription; -}; - -var emitServerDescriptionChanged = function(self, description) { - if (self.listeners('serverDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('serverDescriptionChanged', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name, - previousDescription: getPreviousDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -}; - -var getPreviousTopologyDescription = function(self) { - if (!self.s.topologyDescription) { - self.s.topologyDescription = { - topologyType: 'Unknown', - servers: [ - { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - } - ] - }; - } - - return self.s.topologyDescription; -}; - -var emitTopologyDescriptionChanged = function(self, description) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('topologyDescriptionChanged', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name, - previousDescription: getPreviousTopologyDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -}; - -var changedIsMaster = function(self, currentIsmaster, ismaster) { - var currentType = getTopologyType(self, currentIsmaster); - var newType = getTopologyType(self, ismaster); - if (newType !== currentType) return true; - return false; -}; - -var getTopologyType = function(self, ismaster) { - if (!ismaster) { - ismaster = self.ismaster; - } - - if (!ismaster) return 'Unknown'; - if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos'; - if (ismaster.ismaster && !ismaster.hosts) return 'Standalone'; - if (ismaster.ismaster) return 'RSPrimary'; - if (ismaster.secondary) return 'RSSecondary'; - if (ismaster.arbiterOnly) return 'RSArbiter'; - return 'Unknown'; -}; - -var inquireServerState = function(self) { - return function(callback) { - if (self.s.state === 'destroyed') return; - // Record response time - var start = new Date().getTime(); - - // emitSDAMEvent - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); - - // Attempt to execute ismaster command - self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) { - if (!err) { - // Legacy event sender - self.emit('ismaster', r, self); - - // Calculate latencyMS - var latencyMS = new Date().getTime() - start; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: self.name - }); - - // Did the server change - if (changedIsMaster(self, self.s.ismaster, r.result)) { - // Emit server description changed if something listening - emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) - }); - } - - // Updat ismaster view - self.s.ismaster = r.result; - - // Set server response time - self.s.isMasterLatencyMS = latencyMS; - } else { - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: self.name - }); - } - - // Peforming an ismaster monitoring callback operation - if (typeof callback === 'function') { - return callback(err, r); - } - - // Perform another sweep - self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); - }); - }; -}; - -// -// Clone the options -var cloneOptions = function(options) { - var opts = {}; - for (var name in options) { - opts[name] = options[name]; - } - return opts; -}; - -function Interval(fn, time) { - var timer = false; - - this.start = function() { - if (!this.isRunning()) { - timer = setInterval(fn, time); - } - - return this; - }; - - this.stop = function() { - clearInterval(timer); - timer = false; - return this; - }; - - this.isRunning = function() { - return timer !== false; - }; -} - -function Timeout(fn, time) { - var timer = false; - var func = () => { - if (timer) { - clearTimeout(timer); - timer = false; - - fn(); - } - }; - - this.start = function() { - if (!this.isRunning()) { - timer = setTimeout(func, time); - } - return this; - }; - - this.stop = function() { - clearTimeout(timer); - timer = false; - return this; - }; - - this.isRunning = function() { - return timer !== false; - }; -} - -function diff(previous, current) { - // Difference document - var diff = { - servers: [] - }; - - // Previous entry - if (!previous) { - previous = { servers: [] }; - } - - // Check if we have any previous servers missing in the current ones - for (var i = 0; i < previous.servers.length; i++) { - var found = false; - - for (var j = 0; j < current.servers.length; j++) { - if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) { - found = true; - break; - } - } - - if (!found) { - // Add to the diff - diff.servers.push({ - address: previous.servers[i].address, - from: previous.servers[i].type, - to: 'Unknown' - }); - } - } - - // Check if there are any severs that don't exist - for (j = 0; j < current.servers.length; j++) { - found = false; - - // Go over all the previous servers - for (i = 0; i < previous.servers.length; i++) { - if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) { - found = true; - break; - } - } - - // Add the server to the diff - if (!found) { - diff.servers.push({ - address: current.servers[j].address, - from: 'Unknown', - to: current.servers[j].type - }); - } - } - - // Got through all the servers - for (i = 0; i < previous.servers.length; i++) { - var prevServer = previous.servers[i]; - - // Go through all current servers - for (j = 0; j < current.servers.length; j++) { - var currServer = current.servers[j]; - - // Matching server - if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) { - // We had a change in state - if (prevServer.type !== currServer.type) { - diff.servers.push({ - address: prevServer.address, - from: prevServer.type, - to: currServer.type - }); - } - } - } - } - - // Return difference - return diff; -} - -/** - * Shared function to determine clusterTime for a given topology - * - * @param {*} topology - * @param {*} clusterTime - */ -function resolveClusterTime(topology, $clusterTime) { - if (topology.clusterTime == null) { - topology.clusterTime = $clusterTime; - } else { - if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { - topology.clusterTime = $clusterTime; - } - } -} - -// NOTE: this is a temporary move until the topologies can be more formally refactored -// to share code. -const SessionMixins = { - endSessions: function(sessions, callback) { - if (!Array.isArray(sessions)) { - sessions = [sessions]; - } - - // TODO: - // When connected to a sharded cluster the endSessions command - // can be sent to any mongos. When connected to a replica set the - // endSessions command MUST be sent to the primary if the primary - // is available, otherwise it MUST be sent to any available secondary. - // Is it enough to use: ReadPreference.primaryPreferred ? - this.command( - 'admin.$cmd', - { endSessions: sessions }, - { readPreference: ReadPreference.primaryPreferred }, - () => { - // intentionally ignored, per spec - if (typeof callback === 'function') callback(); - } - ); - } -}; - -function topologyType(topology) { - if (topology.description) { - return topology.description.type; - } - - if (topology.type === 'mongos') { - return TopologyType.Sharded; - } else if (topology.type === 'replset') { - return TopologyType.ReplicaSetWithPrimary; - } - - return TopologyType.Single; -} - -const RETRYABLE_WIRE_VERSION = 6; - -/** - * Determines whether the provided topology supports retryable writes - * - * @param {Mongos|Replset} topology - */ -const isRetryableWritesSupported = function(topology) { - const maxWireVersion = topology.lastIsMaster().maxWireVersion; - if (maxWireVersion < RETRYABLE_WIRE_VERSION) { - return false; - } - - if (!topology.logicalSessionTimeoutMinutes) { - return false; - } - - if (topologyType(topology) === TopologyType.Single) { - return false; - } - - return true; -}; - -const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = - 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; - -function getMMAPError(err) { - if (err.code !== MMAPv1_RETRY_WRITES_ERROR_CODE || !err.errmsg.includes('Transaction numbers')) { - return err; - } - - // According to the retryable writes spec, we must replace the error message in this case. - // We need to replace err.message so the thrown message is correct and we need to replace err.errmsg to meet the spec requirement. - const newErr = new MongoError({ - message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, - errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, - originalError: err - }); - return newErr; -} - -module.exports.SessionMixins = SessionMixins; -module.exports.resolveClusterTime = resolveClusterTime; -module.exports.inquireServerState = inquireServerState; -module.exports.getTopologyType = getTopologyType; -module.exports.emitServerDescriptionChanged = emitServerDescriptionChanged; -module.exports.emitTopologyDescriptionChanged = emitTopologyDescriptionChanged; -module.exports.cloneOptions = cloneOptions; -module.exports.createCompressionInfo = createCompressionInfo; -module.exports.clone = clone; -module.exports.diff = diff; -module.exports.Interval = Interval; -module.exports.Timeout = Timeout; -module.exports.isRetryableWritesSupported = isRetryableWritesSupported; -module.exports.getMMAPError = getMMAPError; -module.exports.topologyType = topologyType; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/transactions.js b/node_modules/mongoose/node_modules/mongodb/lib/core/transactions.js deleted file mode 100644 index d0b0b73..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/transactions.js +++ /dev/null @@ -1,179 +0,0 @@ -'use strict'; -const MongoError = require('./error').MongoError; -const ReadPreference = require('./topologies/read_preference'); -const ReadConcern = require('../read_concern'); -const WriteConcern = require('../write_concern'); - -let TxnState; -let stateMachine; - -(() => { - const NO_TRANSACTION = 'NO_TRANSACTION'; - const STARTING_TRANSACTION = 'STARTING_TRANSACTION'; - const TRANSACTION_IN_PROGRESS = 'TRANSACTION_IN_PROGRESS'; - const TRANSACTION_COMMITTED = 'TRANSACTION_COMMITTED'; - const TRANSACTION_COMMITTED_EMPTY = 'TRANSACTION_COMMITTED_EMPTY'; - const TRANSACTION_ABORTED = 'TRANSACTION_ABORTED'; - - TxnState = { - NO_TRANSACTION, - STARTING_TRANSACTION, - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - TRANSACTION_ABORTED - }; - - stateMachine = { - [NO_TRANSACTION]: [NO_TRANSACTION, STARTING_TRANSACTION], - [STARTING_TRANSACTION]: [ - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - TRANSACTION_ABORTED - ], - [TRANSACTION_IN_PROGRESS]: [ - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_ABORTED - ], - [TRANSACTION_COMMITTED]: [ - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - STARTING_TRANSACTION, - NO_TRANSACTION - ], - [TRANSACTION_ABORTED]: [STARTING_TRANSACTION, NO_TRANSACTION], - [TRANSACTION_COMMITTED_EMPTY]: [TRANSACTION_COMMITTED_EMPTY, NO_TRANSACTION] - }; -})(); - -/** - * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties - * of the data read from replica sets and replica set shards. - * @typedef {Object} ReadConcern - * @property {'local'|'available'|'majority'|'linearizable'|'snapshot'} level The readConcern Level - * @see https://docs.mongodb.com/manual/reference/read-concern/ - */ - -/** - * A MongoDB WriteConcern, which describes the level of acknowledgement - * requested from MongoDB for write operations. - * @typedef {Object} WriteConcern - * @property {number|'majority'|string} [w=1] requests acknowledgement that the write operation has - * propagated to a specified number of mongod hosts - * @property {boolean} [j=false] requests acknowledgement from MongoDB that the write operation has - * been written to the journal - * @property {number} [wtimeout] a time limit, in milliseconds, for the write concern - * @see https://docs.mongodb.com/manual/reference/write-concern/ - */ - -/** - * Configuration options for a transaction. - * @typedef {Object} TransactionOptions - * @property {ReadConcern} [readConcern] A default read concern for commands in this transaction - * @property {WriteConcern} [writeConcern] A default writeConcern for commands in this transaction - * @property {ReadPreference} [readPreference] A default read preference for commands in this transaction - */ - -/** - * A class maintaining state related to a server transaction. Internal Only - * @ignore - */ -class Transaction { - /** - * Create a transaction - * - * @ignore - * @param {TransactionOptions} [options] Optional settings - */ - constructor(options) { - options = options || {}; - - this.state = TxnState.NO_TRANSACTION; - this.options = {}; - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern) { - if (writeConcern.w <= 0) { - throw new MongoError('Transactions do not support unacknowledged write concern'); - } - - this.options.writeConcern = writeConcern; - } - - if (options.readConcern) { - this.options.readConcern = ReadConcern.fromOptions(options); - } - - if (options.readPreference) { - this.options.readPreference = ReadPreference.fromOptions(options); - } - - if (options.maxCommitTimeMS) { - this.options.maxTimeMS = options.maxCommitTimeMS; - } - - // TODO: This isn't technically necessary - this._pinnedServer = undefined; - this._recoveryToken = undefined; - } - - get server() { - return this._pinnedServer; - } - - get recoveryToken() { - return this._recoveryToken; - } - - get isPinned() { - return !!this.server; - } - - /** - * @ignore - * @return Whether this session is presently in a transaction - */ - get isActive() { - return ( - [TxnState.STARTING_TRANSACTION, TxnState.TRANSACTION_IN_PROGRESS].indexOf(this.state) !== -1 - ); - } - - /** - * Transition the transaction in the state machine - * @ignore - * @param {TxnState} state The new state to transition to - */ - transition(nextState) { - const nextStates = stateMachine[this.state]; - if (nextStates && nextStates.indexOf(nextState) !== -1) { - this.state = nextState; - if (this.state === TxnState.NO_TRANSACTION || this.state === TxnState.STARTING_TRANSACTION) { - this.unpinServer(); - } - return; - } - - throw new MongoError( - `Attempted illegal state transition from [${this.state}] to [${nextState}]` - ); - } - - pinServer(server) { - if (this.isActive) { - this._pinnedServer = server; - } - } - - unpinServer() { - this._pinnedServer = undefined; - } -} - -function isTransactionCommand(command) { - return !!(command.commitTransaction || command.abortTransaction); -} - -module.exports = { TxnState, Transaction, isTransactionCommand }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/uri_parser.js b/node_modules/mongoose/node_modules/mongodb/lib/core/uri_parser.js deleted file mode 100644 index 01685f5..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/uri_parser.js +++ /dev/null @@ -1,688 +0,0 @@ -'use strict'; -const URL = require('url'); -const qs = require('querystring'); -const dns = require('dns'); -const MongoParseError = require('./error').MongoParseError; -const ReadPreference = require('./topologies/read_preference'); - -/** - * The following regular expression validates a connection string and breaks the - * provide string into the following capture groups: [protocol, username, password, hosts] - */ -const HOSTS_RX = /(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/; - -/** - * Determines whether a provided address matches the provided parent domain in order - * to avoid certain attack vectors. - * - * @param {String} srvAddress The address to check against a domain - * @param {String} parentDomain The domain to check the provided address against - * @return {Boolean} Whether the provided address matches the parent domain - */ -function matchesParentDomain(srvAddress, parentDomain) { - const regex = /^.*?\./; - const srv = `.${srvAddress.replace(regex, '')}`; - const parent = `.${parentDomain.replace(regex, '')}`; - return srv.endsWith(parent); -} - -/** - * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal - * connection string. - * - * @param {string} uri The connection string to parse - * @param {object} options Optional user provided connection string options - * @param {function} callback - */ -function parseSrvConnectionString(uri, options, callback) { - const result = URL.parse(uri, true); - - if (result.hostname.split('.').length < 3) { - return callback(new MongoParseError('URI does not have hostname, domain name and tld')); - } - - result.domainLength = result.hostname.split('.').length; - if (result.pathname && result.pathname.match(',')) { - return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); - } - - if (result.port) { - return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); - } - - // Resolve the SRV record and use the result as the list of hosts to connect to. - const lookupAddress = result.host; - dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { - if (err) return callback(err); - - if (addresses.length === 0) { - return callback(new MongoParseError('No addresses found at host')); - } - - for (let i = 0; i < addresses.length; i++) { - if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { - return callback( - new MongoParseError('Server record does not share hostname with parent URI') - ); - } - } - - // Convert the original URL to a non-SRV URL. - result.protocol = 'mongodb'; - result.host = addresses.map(address => `${address.name}:${address.port}`).join(','); - - // Default to SSL true if it's not specified. - if ( - !('ssl' in options) && - (!result.search || !('ssl' in result.query) || result.query.ssl === null) - ) { - result.query.ssl = true; - } - - // Resolve TXT record and add options from there if they exist. - dns.resolveTxt(lookupAddress, (err, record) => { - if (err) { - if (err.code !== 'ENODATA') { - return callback(err); - } - record = null; - } - - if (record) { - if (record.length > 1) { - return callback(new MongoParseError('Multiple text records not allowed')); - } - - record = qs.parse(record[0].join('')); - if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) { - return callback( - new MongoParseError('Text record must only set `authSource` or `replicaSet`') - ); - } - - result.query = Object.assign({}, record, result.query); - } - - // Set completed options back into the URL object. - result.search = qs.stringify(result.query); - - const finalString = URL.format(result); - parseConnectionString(finalString, options, (err, ret) => { - if (err) { - callback(err); - return; - } - - callback(null, Object.assign({}, ret, { srvHost: lookupAddress })); - }); - }); - }); -} - -/** - * Parses a query string item according to the connection string spec - * - * @param {string} key The key for the parsed value - * @param {Array|String} value The value to parse - * @return {Array|Object|String} The parsed value - */ -function parseQueryStringItemValue(key, value) { - if (Array.isArray(value)) { - // deduplicate and simplify arrays - value = value.filter((v, idx) => value.indexOf(v) === idx); - if (value.length === 1) value = value[0]; - } else if (value.indexOf(':') > 0) { - value = value.split(',').reduce((result, pair) => { - const parts = pair.split(':'); - result[parts[0]] = parseQueryStringItemValue(key, parts[1]); - return result; - }, {}); - } else if (value.indexOf(',') > 0) { - value = value.split(',').map(v => { - return parseQueryStringItemValue(key, v); - }); - } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { - value = value.toLowerCase() === 'true'; - } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { - const numericValue = parseFloat(value); - if (!Number.isNaN(numericValue)) { - value = parseFloat(value); - } - } - - return value; -} - -// Options that are known boolean types -const BOOLEAN_OPTIONS = new Set([ - 'slaveok', - 'slave_ok', - 'sslvalidate', - 'fsync', - 'safe', - 'retrywrites', - 'j' -]); - -// Known string options, only used to bypass Number coercion in `parseQueryStringItemValue` -const STRING_OPTIONS = new Set(['authsource', 'replicaset']); - -// Supported text representations of auth mechanisms -// NOTE: this list exists in native already, if it is merged here we should deduplicate -const AUTH_MECHANISMS = new Set([ - 'GSSAPI', - 'MONGODB-X509', - 'MONGODB-CR', - 'DEFAULT', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256', - 'PLAIN' -]); - -// Lookup table used to translate normalized (lower-cased) forms of connection string -// options to their expected camelCase version -const CASE_TRANSLATION = { - replicaset: 'replicaSet', - connecttimeoutms: 'connectTimeoutMS', - sockettimeoutms: 'socketTimeoutMS', - maxpoolsize: 'maxPoolSize', - minpoolsize: 'minPoolSize', - maxidletimems: 'maxIdleTimeMS', - waitqueuemultiple: 'waitQueueMultiple', - waitqueuetimeoutms: 'waitQueueTimeoutMS', - wtimeoutms: 'wtimeoutMS', - readconcern: 'readConcern', - readconcernlevel: 'readConcernLevel', - readpreference: 'readPreference', - maxstalenessseconds: 'maxStalenessSeconds', - readpreferencetags: 'readPreferenceTags', - authsource: 'authSource', - authmechanism: 'authMechanism', - authmechanismproperties: 'authMechanismProperties', - gssapiservicename: 'gssapiServiceName', - localthresholdms: 'localThresholdMS', - serverselectiontimeoutms: 'serverSelectionTimeoutMS', - serverselectiontryonce: 'serverSelectionTryOnce', - heartbeatfrequencyms: 'heartbeatFrequencyMS', - retrywrites: 'retryWrites', - uuidrepresentation: 'uuidRepresentation', - zlibcompressionlevel: 'zlibCompressionLevel', - tlsallowinvalidcertificates: 'tlsAllowInvalidCertificates', - tlsallowinvalidhostnames: 'tlsAllowInvalidHostnames', - tlsinsecure: 'tlsInsecure', - tlscafile: 'tlsCAFile', - tlscertificatekeyfile: 'tlsCertificateKeyFile', - tlscertificatekeyfilepassword: 'tlsCertificateKeyFilePassword', - wtimeout: 'wTimeoutMS', - j: 'journal' -}; - -/** - * Sets the value for `key`, allowing for any required translation - * - * @param {object} obj The object to set the key on - * @param {string} key The key to set the value for - * @param {*} value The value to set - * @param {object} options The options used for option parsing - */ -function applyConnectionStringOption(obj, key, value, options) { - // simple key translation - if (key === 'journal') { - key = 'j'; - } else if (key === 'wtimeoutms') { - key = 'wtimeout'; - } - - // more complicated translation - if (BOOLEAN_OPTIONS.has(key)) { - value = value === 'true' || value === true; - } else if (key === 'appname') { - value = decodeURIComponent(value); - } else if (key === 'readconcernlevel') { - obj['readConcernLevel'] = value; - key = 'readconcern'; - value = { level: value }; - } - - // simple validation - if (key === 'compressors') { - value = Array.isArray(value) ? value : [value]; - - if (!value.every(c => c === 'snappy' || c === 'zlib')) { - throw new MongoParseError( - 'Value for `compressors` must be at least one of: `snappy`, `zlib`' - ); - } - } - - if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { - throw new MongoParseError( - 'Value for `authMechanism` must be one of: `DEFAULT`, `GSSAPI`, `PLAIN`, `MONGODB-X509`, `SCRAM-SHA-1`, `SCRAM-SHA-256`' - ); - } - - if (key === 'readpreference' && !ReadPreference.isValid(value)) { - throw new MongoParseError( - 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' - ); - } - - if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { - throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); - } - - // special cases - if (key === 'compressors' || key === 'zlibcompressionlevel') { - obj.compression = obj.compression || {}; - obj = obj.compression; - } - - if (key === 'authmechanismproperties') { - if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; - if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; - if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { - obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; - } - } - - if (key === 'readpreferencetags') { - value = Array.isArray(value) ? splitArrayOfMultipleReadPreferenceTags(value) : [value]; - } - - // set the actual value - if (options.caseTranslate && CASE_TRANSLATION[key]) { - obj[CASE_TRANSLATION[key]] = value; - return; - } - - obj[key] = value; -} - -const USERNAME_REQUIRED_MECHANISMS = new Set([ - 'GSSAPI', - 'MONGODB-CR', - 'PLAIN', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256' -]); - -function splitArrayOfMultipleReadPreferenceTags(value) { - const parsedTags = []; - - for (let i = 0; i < value.length; i++) { - parsedTags[i] = {}; - value[i].split(',').forEach(individualTag => { - const splitTag = individualTag.split(':'); - parsedTags[i][splitTag[0]] = splitTag[1]; - }); - } - - return parsedTags; -} - -/** - * Modifies the parsed connection string object taking into account expectations we - * have for authentication-related options. - * - * @param {object} parsed The parsed connection string result - * @return The parsed connection string result possibly modified for auth expectations - */ -function applyAuthExpectations(parsed) { - if (parsed.options == null) { - return; - } - - const options = parsed.options; - const authSource = options.authsource || options.authSource; - if (authSource != null) { - parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); - } - - const authMechanism = options.authmechanism || options.authMechanism; - if (authMechanism != null) { - if ( - USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && - (!parsed.auth || parsed.auth.username == null) - ) { - throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); - } - - if (authMechanism === 'GSSAPI') { - if (authSource != null && authSource !== '$external') { - throw new MongoParseError( - `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` - ); - } - - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - - if (authMechanism === 'MONGODB-X509') { - if (parsed.auth && parsed.auth.password != null) { - throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); - } - - if (authSource != null && authSource !== '$external') { - throw new MongoParseError( - `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` - ); - } - - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - - if (authMechanism === 'PLAIN') { - if (parsed.auth && parsed.auth.db == null) { - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - } - } - - // default to `admin` if nothing else was resolved - if (parsed.auth && parsed.auth.db == null) { - parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); - } - - return parsed; -} - -/** - * Parses a query string according the connection string spec. - * - * @param {String} query The query string to parse - * @param {object} [options] The options used for options parsing - * @return {Object|Error} The parsed query string as an object, or an error if one was encountered - */ -function parseQueryString(query, options) { - const result = {}; - let parsedQueryString = qs.parse(query); - - checkTLSOptions(parsedQueryString); - - for (const key in parsedQueryString) { - const value = parsedQueryString[key]; - if (value === '' || value == null) { - throw new MongoParseError('Incomplete key value pair for option'); - } - - const normalizedKey = key.toLowerCase(); - const parsedValue = parseQueryStringItemValue(normalizedKey, value); - applyConnectionStringOption(result, normalizedKey, parsedValue, options); - } - - // special cases for known deprecated options - if (result.wtimeout && result.wtimeoutms) { - delete result.wtimeout; - console.warn('Unsupported option `wtimeout` specified'); - } - - return Object.keys(result).length ? result : null; -} - -/// Adds support for modern `tls` variants of out `ssl` options -function translateTLSOptions(queryString) { - if (queryString.tls) { - queryString.ssl = queryString.tls; - } - - if (queryString.tlsInsecure) { - queryString.checkServerIdentity = false; - queryString.sslValidate = false; - } else { - Object.assign(queryString, { - checkServerIdentity: queryString.tlsAllowInvalidHostnames ? false : true, - sslValidate: queryString.tlsAllowInvalidCertificates ? false : true - }); - } - - if (queryString.tlsCAFile) { - queryString.ssl = true; - queryString.sslCA = queryString.tlsCAFile; - } - - if (queryString.tlsCertificateKeyFile) { - queryString.ssl = true; - if (queryString.tlsCertificateFile) { - queryString.sslCert = queryString.tlsCertificateFile; - queryString.sslKey = queryString.tlsCertificateKeyFile; - } else { - queryString.sslKey = queryString.tlsCertificateKeyFile; - queryString.sslCert = queryString.tlsCertificateKeyFile; - } - } - - if (queryString.tlsCertificateKeyFilePassword) { - queryString.ssl = true; - queryString.sslPass = queryString.tlsCertificateKeyFilePassword; - } - - return queryString; -} - -/** - * Checks a query string for invalid tls options according to the URI options spec. - * - * @param {string} queryString The query string to check - * @throws {MongoParseError} - */ -function checkTLSOptions(queryString) { - const queryStringKeys = Object.keys(queryString); - if ( - queryStringKeys.indexOf('tlsInsecure') !== -1 && - (queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 || - queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1) - ) { - throw new MongoParseError( - 'The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.' - ); - } - - const tlsValue = assertTlsOptionsAreEqual('tls', queryString, queryStringKeys); - const sslValue = assertTlsOptionsAreEqual('ssl', queryString, queryStringKeys); - - if (tlsValue != null && sslValue != null) { - if (tlsValue !== sslValue) { - throw new MongoParseError('All values of `tls` and `ssl` must be the same.'); - } - } -} - -/** - * Checks a query string to ensure all tls/ssl options are the same. - * - * @param {string} key The key (tls or ssl) to check - * @param {string} queryString The query string to check - * @throws {MongoParseError} - * @return The value of the tls/ssl option - */ -function assertTlsOptionsAreEqual(optionName, queryString, queryStringKeys) { - const queryStringHasTLSOption = queryStringKeys.indexOf(optionName) !== -1; - - let optionValue; - if (Array.isArray(queryString[optionName])) { - optionValue = queryString[optionName][0]; - } else { - optionValue = queryString[optionName]; - } - - if (queryStringHasTLSOption) { - if (Array.isArray(queryString[optionName])) { - const firstValue = queryString[optionName][0]; - queryString[optionName].forEach(tlsValue => { - if (tlsValue !== firstValue) { - throw new MongoParseError(`All values of ${optionName} must be the same.`); - } - }); - } - } - - return optionValue; -} - -const PROTOCOL_MONGODB = 'mongodb'; -const PROTOCOL_MONGODB_SRV = 'mongodb+srv'; -const SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV]; - -/** - * Parses a MongoDB connection string - * - * @param {*} uri the MongoDB connection string to parse - * @param {object} [options] Optional settings. - * @param {boolean} [options.caseTranslate] Whether the parser should translate options back into camelCase after normalization - * @param {parseCallback} callback - */ -function parseConnectionString(uri, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { caseTranslate: true }, options); - - // Check for bad uris before we parse - try { - URL.parse(uri); - } catch (e) { - return callback(new MongoParseError('URI malformed, cannot be parsed')); - } - - const cap = uri.match(HOSTS_RX); - if (!cap) { - return callback(new MongoParseError('Invalid connection string')); - } - - const protocol = cap[1]; - if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) { - return callback(new MongoParseError('Invalid protocol provided')); - } - - if (protocol === PROTOCOL_MONGODB_SRV) { - return parseSrvConnectionString(uri, options, callback); - } - - const dbAndQuery = cap[4].split('?'); - const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null; - const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null; - - let parsedOptions; - try { - parsedOptions = parseQueryString(query, options); - } catch (parseError) { - return callback(parseError); - } - - parsedOptions = Object.assign({}, parsedOptions, options); - const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null }; - if (parsedOptions.auth) { - // maintain support for legacy options passed into `MongoClient` - if (parsedOptions.auth.username) auth.username = parsedOptions.auth.username; - if (parsedOptions.auth.user) auth.username = parsedOptions.auth.user; - if (parsedOptions.auth.password) auth.password = parsedOptions.auth.password; - } else { - if (parsedOptions.username) auth.username = parsedOptions.username; - if (parsedOptions.user) auth.username = parsedOptions.user; - if (parsedOptions.password) auth.password = parsedOptions.password; - } - - if (cap[4].split('?')[0].indexOf('@') !== -1) { - return callback(new MongoParseError('Unescaped slash in userinfo section')); - } - - const authorityParts = cap[3].split('@'); - if (authorityParts.length > 2) { - return callback(new MongoParseError('Unescaped at-sign in authority section')); - } - - if (authorityParts[0] == null || authorityParts[0] === '') { - return callback(new MongoParseError('No username provided in authority section')); - } - - if (authorityParts.length > 1) { - const authParts = authorityParts.shift().split(':'); - if (authParts.length > 2) { - return callback(new MongoParseError('Unescaped colon in authority section')); - } - - if (authParts[0] === '') { - return callback(new MongoParseError('Invalid empty username provided')); - } - - if (!auth.username) auth.username = qs.unescape(authParts[0]); - if (!auth.password) auth.password = authParts[1] ? qs.unescape(authParts[1]) : null; - } - - let hostParsingError = null; - const hosts = authorityParts - .shift() - .split(',') - .map(host => { - let parsedHost = URL.parse(`mongodb://${host}`); - if (parsedHost.path === '/:') { - hostParsingError = new MongoParseError('Double colon in host identifier'); - return null; - } - - // heuristically determine if we're working with a domain socket - if (host.match(/\.sock/)) { - parsedHost.hostname = qs.unescape(host); - parsedHost.port = null; - } - - if (Number.isNaN(parsedHost.port)) { - hostParsingError = new MongoParseError('Invalid port (non-numeric string)'); - return; - } - - const result = { - host: parsedHost.hostname, - port: parsedHost.port ? parseInt(parsedHost.port) : 27017 - }; - - if (result.port === 0) { - hostParsingError = new MongoParseError('Invalid port (zero) with hostname'); - return; - } - - if (result.port > 65535) { - hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname'); - return; - } - - if (result.port < 0) { - hostParsingError = new MongoParseError('Invalid port (negative number)'); - return; - } - - return result; - }) - .filter(host => !!host); - - if (hostParsingError) { - return callback(hostParsingError); - } - - if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) { - return callback(new MongoParseError('No hostname or hostnames provided in connection string')); - } - - const result = { - hosts: hosts, - auth: auth.db || auth.username ? auth : null, - options: Object.keys(parsedOptions).length ? parsedOptions : null - }; - - if (result.auth && result.auth.db) { - result.defaultDatabase = result.auth.db; - } else { - result.defaultDatabase = 'test'; - } - - // support modern `tls` variants to SSL options - result.options = translateTLSOptions(result.options); - - try { - applyAuthExpectations(result); - } catch (authError) { - return callback(authError); - } - - callback(null, result); -} - -module.exports = parseConnectionString; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/utils.js b/node_modules/mongoose/node_modules/mongodb/lib/core/utils.js deleted file mode 100644 index ab778bf..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/utils.js +++ /dev/null @@ -1,277 +0,0 @@ -'use strict'; -const os = require('os'); -const crypto = require('crypto'); -const requireOptional = require('require_optional'); - -/** - * Generate a UUIDv4 - */ -const uuidV4 = () => { - const result = crypto.randomBytes(16); - result[6] = (result[6] & 0x0f) | 0x40; - result[8] = (result[8] & 0x3f) | 0x80; - return result; -}; - -/** - * Returns the duration calculated from two high resolution timers in milliseconds - * - * @param {Object} started A high resolution timestamp created from `process.hrtime()` - * @returns {Number} The duration in milliseconds - */ -const calculateDurationInMs = started => { - const hrtime = process.hrtime(started); - return (hrtime[0] * 1e9 + hrtime[1]) / 1e6; -}; - -/** - * Relays events for a given listener and emitter - * - * @param {EventEmitter} listener the EventEmitter to listen to the events from - * @param {EventEmitter} emitter the EventEmitter to relay the events to - */ -function relayEvents(listener, emitter, events) { - events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); -} - -function retrieveKerberos() { - let kerberos; - - try { - kerberos = requireOptional('kerberos'); - } catch (err) { - if (err.code === 'MODULE_NOT_FOUND') { - throw new Error('The `kerberos` module was not found. Please install it and try again.'); - } - - throw err; - } - - return kerberos; -} - -// Throw an error if an attempt to use EJSON is made when it is not installed -const noEJSONError = function() { - throw new Error('The `mongodb-extjson` module was not found. Please install it and try again.'); -}; - -// Facilitate loading EJSON optionally -function retrieveEJSON() { - let EJSON = null; - try { - EJSON = requireOptional('mongodb-extjson'); - } catch (error) {} // eslint-disable-line - if (!EJSON) { - EJSON = { - parse: noEJSONError, - deserialize: noEJSONError, - serialize: noEJSONError, - stringify: noEJSONError, - setBSONModule: noEJSONError, - BSON: noEJSONError - }; - } - - return EJSON; -} - -/** - * A helper function for determining `maxWireVersion` between legacy and new topology - * instances - * - * @private - * @param {(Topology|Server)} topologyOrServer - */ -function maxWireVersion(topologyOrServer) { - if (topologyOrServer.ismaster) { - return topologyOrServer.ismaster.maxWireVersion; - } - - if (typeof topologyOrServer.lastIsMaster === 'function') { - const lastIsMaster = topologyOrServer.lastIsMaster(); - if (lastIsMaster) { - return lastIsMaster.maxWireVersion; - } - } - - if (topologyOrServer.description) { - return topologyOrServer.description.maxWireVersion; - } - - return null; -} - -/* - * Checks that collation is supported by server. - * - * @param {Server} [server] to check against - * @param {object} [cmd] object where collation may be specified - * @param {function} [callback] callback function - * @return true if server does not support collation - */ -function collationNotSupported(server, cmd) { - return cmd && cmd.collation && maxWireVersion(server) < 5; -} - -/** - * Checks if a given value is a Promise - * - * @param {*} maybePromise - * @return true if the provided value is a Promise - */ -function isPromiseLike(maybePromise) { - return maybePromise && typeof maybePromise.then === 'function'; -} - -/** - * Applies the function `eachFn` to each item in `arr`, in parallel. - * - * @param {array} arr an array of items to asynchronusly iterate over - * @param {function} eachFn A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete. - * @param {function} callback The callback called after every item has been iterated - */ -function eachAsync(arr, eachFn, callback) { - arr = arr || []; - - let idx = 0; - let awaiting = 0; - for (idx = 0; idx < arr.length; ++idx) { - awaiting++; - eachFn(arr[idx], eachCallback); - } - - if (awaiting === 0) { - callback(); - return; - } - - function eachCallback(err) { - awaiting--; - if (err) { - callback(err); - return; - } - - if (idx === arr.length && awaiting <= 0) { - callback(); - } - } -} - -function isUnifiedTopology(topology) { - return topology.description != null; -} - -function arrayStrictEqual(arr, arr2) { - if (!Array.isArray(arr) || !Array.isArray(arr2)) { - return false; - } - - return arr.length === arr2.length && arr.every((elt, idx) => elt === arr2[idx]); -} - -function tagsStrictEqual(tags, tags2) { - const tagsKeys = Object.keys(tags); - const tags2Keys = Object.keys(tags2); - return tagsKeys.length === tags2Keys.length && tagsKeys.every(key => tags2[key] === tags[key]); -} - -function errorStrictEqual(lhs, rhs) { - if (lhs === rhs) { - return true; - } - - if ((lhs == null && rhs != null) || (lhs != null && rhs == null)) { - return false; - } - - if (lhs.constructor.name !== rhs.constructor.name) { - return false; - } - - if (lhs.message !== rhs.message) { - return false; - } - - return true; -} - -function makeStateMachine(stateTable) { - return function stateTransition(target, newState) { - const legalStates = stateTable[target.s.state]; - if (legalStates && legalStates.indexOf(newState) < 0) { - throw new TypeError( - `illegal state transition from [${target.s.state}] => [${newState}], allowed: [${legalStates}]` - ); - } - - target.emit('stateChanged', target.s.state, newState); - target.s.state = newState; - }; -} - -function makeClientMetadata(options) { - options = options || {}; - - const metadata = { - driver: { - name: 'nodejs', - version: require('../../package.json').version - }, - os: { - type: os.type(), - name: process.platform, - architecture: process.arch, - version: os.release() - }, - platform: `'Node.js ${process.version}, ${os.endianness} (${ - options.useUnifiedTopology ? 'unified' : 'legacy' - })` - }; - - // support optionally provided wrapping driver info - if (options.driverInfo) { - if (options.driverInfo.name) { - metadata.driver.name = `${metadata.driver.name}|${options.driverInfo.name}`; - } - - if (options.driverInfo.version) { - metadata.version = `${metadata.driver.version}|${options.driverInfo.version}`; - } - - if (options.driverInfo.platform) { - metadata.platform = `${metadata.platform}|${options.driverInfo.platform}`; - } - } - - if (options.appname) { - // MongoDB requires the appname not exceed a byte length of 128 - const buffer = Buffer.from(options.appname); - metadata.application = { - name: buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname - }; - } - - return metadata; -} - -const noop = () => {}; - -module.exports = { - uuidV4, - calculateDurationInMs, - relayEvents, - collationNotSupported, - retrieveEJSON, - retrieveKerberos, - maxWireVersion, - isPromiseLike, - eachAsync, - isUnifiedTopology, - arrayStrictEqual, - tagsStrictEqual, - errorStrictEqual, - makeStateMachine, - makeClientMetadata, - noop -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/command.js b/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/command.js deleted file mode 100644 index 214385b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/command.js +++ /dev/null @@ -1,185 +0,0 @@ -'use strict'; - -const Query = require('../connection/commands').Query; -const Msg = require('../connection/msg').Msg; -const MongoError = require('../error').MongoError; -const getReadPreference = require('./shared').getReadPreference; -const isSharded = require('./shared').isSharded; -const databaseNamespace = require('./shared').databaseNamespace; -const isTransactionCommand = require('../transactions').isTransactionCommand; -const applySession = require('../sessions').applySession; -const MongoNetworkError = require('../error').MongoNetworkError; -const maxWireVersion = require('../utils').maxWireVersion; - -function isClientEncryptionEnabled(server) { - const wireVersion = maxWireVersion(server); - return wireVersion && server.autoEncrypter; -} - -function command(server, ns, cmd, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (cmd == null) { - return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); - } - - if (!isClientEncryptionEnabled(server)) { - _command(server, ns, cmd, options, callback); - return; - } - - const wireVersion = maxWireVersion(server); - if (typeof wireVersion !== 'number' || wireVersion < 8) { - callback(new MongoError('Auto-encryption requires a minimum MongoDB version of 4.2')); - return; - } - - _cryptCommand(server, ns, cmd, options, callback); -} - -function _command(server, ns, cmd, options, callback) { - const bson = server.s.bson; - const pool = server.s.pool; - const readPreference = getReadPreference(cmd, options); - const shouldUseOpMsg = supportsOpMsg(server); - const session = options.session; - - let clusterTime = server.clusterTime; - let finalCmd = Object.assign({}, cmd); - if (hasSessionSupport(server) && session) { - if ( - session.clusterTime && - session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime) - ) { - clusterTime = session.clusterTime; - } - - const err = applySession(session, finalCmd, options); - if (err) { - return callback(err); - } - } - - // if we have a known cluster time, gossip it - if (clusterTime) { - finalCmd.$clusterTime = clusterTime; - } - - if ( - isSharded(server) && - !shouldUseOpMsg && - readPreference && - readPreference.preference !== 'primary' - ) { - finalCmd = { - $query: finalCmd, - $readPreference: readPreference.toJSON() - }; - } - - const commandOptions = Object.assign( - { - command: true, - numberToSkip: 0, - numberToReturn: -1, - checkKeys: false - }, - options - ); - - // This value is not overridable - commandOptions.slaveOk = readPreference.slaveOk(); - - const cmdNs = `${databaseNamespace(ns)}.$cmd`; - const message = shouldUseOpMsg - ? new Msg(bson, cmdNs, finalCmd, commandOptions) - : new Query(bson, cmdNs, finalCmd, commandOptions); - - const inTransaction = session && (session.inTransaction() || isTransactionCommand(finalCmd)); - const commandResponseHandler = inTransaction - ? function(err) { - // We need to add a TransientTransactionError errorLabel, as stated in the transaction spec. - if ( - err && - err instanceof MongoNetworkError && - !err.hasErrorLabel('TransientTransactionError') - ) { - if (err.errorLabels == null) { - err.errorLabels = []; - } - err.errorLabels.push('TransientTransactionError'); - } - - if ( - !cmd.commitTransaction && - err && - err instanceof MongoError && - err.hasErrorLabel('TransientTransactionError') - ) { - session.transaction.unpinServer(); - } - - return callback.apply(null, arguments); - } - : callback; - - try { - pool.write(message, commandOptions, commandResponseHandler); - } catch (err) { - commandResponseHandler(err); - } -} - -function hasSessionSupport(topology) { - if (topology == null) return false; - if (topology.description) { - return topology.description.maxWireVersion >= 6; - } - - return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6; -} - -function supportsOpMsg(topologyOrServer) { - const description = topologyOrServer.ismaster - ? topologyOrServer.ismaster - : topologyOrServer.description; - - if (description == null) { - return false; - } - - return description.maxWireVersion >= 6 && description.__nodejs_mock_server__ == null; -} - -function _cryptCommand(server, ns, cmd, options, callback) { - const autoEncrypter = server.autoEncrypter; - function commandResponseHandler(err, response) { - if (err || response == null) { - callback(err, response); - return; - } - - autoEncrypter.decrypt(response.result, options, (err, decrypted) => { - if (err) { - callback(err, null); - return; - } - - response.result = decrypted; - response.message.documents = [decrypted]; - callback(null, response); - }); - } - - autoEncrypter.encrypt(ns, cmd, options, (err, encrypted) => { - if (err) { - callback(err, null); - return; - } - - _command(server, ns, encrypted, options, commandResponseHandler); - }); -} - -module.exports = command; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/compression.js b/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/compression.js deleted file mode 100644 index b1e1583..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/compression.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict'; - -const Snappy = require('../connection/utils').retrieveSnappy(); -const zlib = require('zlib'); - -const compressorIDs = { - snappy: 1, - zlib: 2 -}; - -const uncompressibleCommands = new Set([ - 'ismaster', - 'saslStart', - 'saslContinue', - 'getnonce', - 'authenticate', - 'createUser', - 'updateUser', - 'copydbSaslStart', - 'copydbgetnonce', - 'copydb' -]); - -// Facilitate compressing a message using an agreed compressor -function compress(self, dataToBeCompressed, callback) { - switch (self.options.agreedCompressor) { - case 'snappy': - Snappy.compress(dataToBeCompressed, callback); - break; - case 'zlib': - // Determine zlibCompressionLevel - var zlibOptions = {}; - if (self.options.zlibCompressionLevel) { - zlibOptions.level = self.options.zlibCompressionLevel; - } - zlib.deflate(dataToBeCompressed, zlibOptions, callback); - break; - default: - throw new Error( - 'Attempt to compress message using unknown compressor "' + - self.options.agreedCompressor + - '".' - ); - } -} - -// Decompress a message using the given compressor -function decompress(compressorID, compressedData, callback) { - if (compressorID < 0 || compressorID > compressorIDs.length) { - throw new Error( - 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' + - compressorID + - ')' - ); - } - switch (compressorID) { - case compressorIDs.snappy: - Snappy.uncompress(compressedData, callback); - break; - case compressorIDs.zlib: - zlib.inflate(compressedData, callback); - break; - default: - callback(null, compressedData); - } -} - -module.exports = { - compressorIDs, - uncompressibleCommands, - compress, - decompress -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/constants.js b/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/constants.js deleted file mode 100644 index df2293b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/constants.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -const MIN_SUPPORTED_SERVER_VERSION = '2.6'; -const MAX_SUPPORTED_SERVER_VERSION = '4.2'; -const MIN_SUPPORTED_WIRE_VERSION = 2; -const MAX_SUPPORTED_WIRE_VERSION = 8; - -module.exports = { - MIN_SUPPORTED_SERVER_VERSION, - MAX_SUPPORTED_SERVER_VERSION, - MIN_SUPPORTED_WIRE_VERSION, - MAX_SUPPORTED_WIRE_VERSION -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/get_more.js b/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/get_more.js deleted file mode 100644 index b2db320..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/get_more.js +++ /dev/null @@ -1,90 +0,0 @@ -'use strict'; - -const GetMore = require('../connection/commands').GetMore; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const BSON = retrieveBSON(); -const Long = BSON.Long; -const collectionNamespace = require('./shared').collectionNamespace; -const maxWireVersion = require('../utils').maxWireVersion; -const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; -const command = require('./command'); - -function getMore(server, ns, cursorState, batchSize, options, callback) { - options = options || {}; - - const wireVersion = maxWireVersion(server); - function queryCallback(err, result) { - if (err) return callback(err); - const response = result.message; - - // If we have a timed out query or a cursor that was killed - if (response.cursorNotFound) { - return callback(new MongoNetworkError('cursor killed or timed out'), null); - } - - if (wireVersion < 4) { - const cursorId = - typeof response.cursorId === 'number' - ? Long.fromNumber(response.cursorId) - : response.cursorId; - - cursorState.documents = response.documents; - cursorState.cursorId = cursorId; - - callback(null, null, response.connection); - return; - } - - // We have an error detected - if (response.documents[0].ok === 0) { - return callback(new MongoError(response.documents[0])); - } - - // Ensure we have a Long valid cursor id - const cursorId = - typeof response.documents[0].cursor.id === 'number' - ? Long.fromNumber(response.documents[0].cursor.id) - : response.documents[0].cursor.id; - - cursorState.documents = response.documents[0].cursor.nextBatch; - cursorState.cursorId = cursorId; - - callback(null, response.documents[0], response.connection); - } - - if (wireVersion < 4) { - const bson = server.s.bson; - const getMoreOp = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize }); - const queryOptions = applyCommonQueryOptions({}, cursorState); - server.s.pool.write(getMoreOp, queryOptions, queryCallback); - return; - } - - const getMoreCmd = { - getMore: cursorState.cursorId, - collection: collectionNamespace(ns), - batchSize: Math.abs(batchSize) - }; - - if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') { - getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; - } - - const commandOptions = Object.assign( - { - returnFieldSelector: null, - documentsReturnedIn: 'nextBatch' - }, - options - ); - - if (cursorState.session) { - commandOptions.session = cursorState.session; - } - - command(server, ns, getMoreCmd, commandOptions, queryCallback); -} - -module.exports = getMore; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/index.js b/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/index.js deleted file mode 100644 index b6ffda7..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; -const writeCommand = require('./write_command'); - -module.exports = { - insert: function insert(server, ns, ops, options, callback) { - writeCommand(server, 'insert', 'documents', ns, ops, options, callback); - }, - update: function update(server, ns, ops, options, callback) { - writeCommand(server, 'update', 'updates', ns, ops, options, callback); - }, - remove: function remove(server, ns, ops, options, callback) { - writeCommand(server, 'delete', 'deletes', ns, ops, options, callback); - }, - killCursors: require('./kill_cursors'), - getMore: require('./get_more'), - query: require('./query'), - command: require('./command') -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js b/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js deleted file mode 100644 index bb13477..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js +++ /dev/null @@ -1,70 +0,0 @@ -'use strict'; - -const KillCursor = require('../connection/commands').KillCursor; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const collectionNamespace = require('./shared').collectionNamespace; -const maxWireVersion = require('../utils').maxWireVersion; -const command = require('./command'); - -function killCursors(server, ns, cursorState, callback) { - callback = typeof callback === 'function' ? callback : () => {}; - const cursorId = cursorState.cursorId; - - if (maxWireVersion(server) < 4) { - const bson = server.s.bson; - const pool = server.s.pool; - const killCursor = new KillCursor(bson, ns, [cursorId]); - const options = { - immediateRelease: true, - noResponse: true - }; - - if (typeof cursorState.session === 'object') { - options.session = cursorState.session; - } - - if (pool && pool.isConnected()) { - try { - pool.write(killCursor, options, callback); - } catch (err) { - if (typeof callback === 'function') { - callback(err, null); - } else { - console.warn(err); - } - } - } - - return; - } - - const killCursorCmd = { - killCursors: collectionNamespace(ns), - cursors: [cursorId] - }; - - const options = {}; - if (typeof cursorState.session === 'object') options.session = cursorState.session; - - command(server, ns, killCursorCmd, options, (err, result) => { - if (err) { - return callback(err); - } - - const response = result.message; - if (response.cursorNotFound) { - return callback(new MongoNetworkError('cursor killed or timed out'), null); - } - - if (!Array.isArray(response.documents) || response.documents.length === 0) { - return callback( - new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`) - ); - } - - callback(null, response.documents[0]); - }); -} - -module.exports = killCursors; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/query.js b/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/query.js deleted file mode 100644 index c501b50..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/query.js +++ /dev/null @@ -1,231 +0,0 @@ -'use strict'; - -const Query = require('../connection/commands').Query; -const MongoError = require('../error').MongoError; -const getReadPreference = require('./shared').getReadPreference; -const collectionNamespace = require('./shared').collectionNamespace; -const isSharded = require('./shared').isSharded; -const maxWireVersion = require('../utils').maxWireVersion; -const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; -const command = require('./command'); - -function query(server, ns, cmd, cursorState, options, callback) { - options = options || {}; - if (cursorState.cursorId != null) { - return callback(); - } - - if (cmd == null) { - return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); - } - - if (maxWireVersion(server) < 4) { - const query = prepareLegacyFindQuery(server, ns, cmd, cursorState, options); - const queryOptions = applyCommonQueryOptions({}, cursorState); - if (typeof query.documentsReturnedIn === 'string') { - queryOptions.documentsReturnedIn = query.documentsReturnedIn; - } - - server.s.pool.write(query, queryOptions, callback); - return; - } - - const readPreference = getReadPreference(cmd, options); - const findCmd = prepareFindCommand(server, ns, cmd, cursorState, options); - - // NOTE: This actually modifies the passed in cmd, and our code _depends_ on this - // side-effect. Change this ASAP - cmd.virtual = false; - - const commandOptions = Object.assign( - { - documentsReturnedIn: 'firstBatch', - numberToReturn: 1, - slaveOk: readPreference.slaveOk() - }, - options - ); - - if (cmd.readPreference) { - commandOptions.readPreference = readPreference; - } - - if (cursorState.session) { - commandOptions.session = cursorState.session; - } - - command(server, ns, findCmd, commandOptions, callback); -} - -function prepareFindCommand(server, ns, cmd, cursorState) { - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - let findCmd = { - find: collectionNamespace(ns) - }; - - if (cmd.query) { - if (cmd.query['$query']) { - findCmd.filter = cmd.query['$query']; - } else { - findCmd.filter = cmd.query; - } - } - - let sortValue = cmd.sort; - if (Array.isArray(sortValue)) { - const sortObject = {}; - - if (sortValue.length > 0 && !Array.isArray(sortValue[0])) { - let sortDirection = sortValue[1]; - if (sortDirection === 'asc') { - sortDirection = 1; - } else if (sortDirection === 'desc') { - sortDirection = -1; - } - - sortObject[sortValue[0]] = sortDirection; - } else { - for (let i = 0; i < sortValue.length; i++) { - let sortDirection = sortValue[i][1]; - if (sortDirection === 'asc') { - sortDirection = 1; - } else if (sortDirection === 'desc') { - sortDirection = -1; - } - - sortObject[sortValue[i][0]] = sortDirection; - } - } - - sortValue = sortObject; - } - - if (cmd.sort) findCmd.sort = sortValue; - if (cmd.fields) findCmd.projection = cmd.fields; - if (cmd.hint) findCmd.hint = cmd.hint; - if (cmd.skip) findCmd.skip = cmd.skip; - if (cmd.limit) findCmd.limit = cmd.limit; - if (cmd.limit < 0) { - findCmd.limit = Math.abs(cmd.limit); - findCmd.singleBatch = true; - } - - if (typeof cmd.batchSize === 'number') { - if (cmd.batchSize < 0) { - if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) { - findCmd.limit = Math.abs(cmd.batchSize); - } - - findCmd.singleBatch = true; - } - - findCmd.batchSize = Math.abs(cmd.batchSize); - } - - if (cmd.comment) findCmd.comment = cmd.comment; - if (cmd.maxScan) findCmd.maxScan = cmd.maxScan; - if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; - if (cmd.min) findCmd.min = cmd.min; - if (cmd.max) findCmd.max = cmd.max; - findCmd.returnKey = cmd.returnKey ? cmd.returnKey : false; - findCmd.showRecordId = cmd.showDiskLoc ? cmd.showDiskLoc : false; - if (cmd.snapshot) findCmd.snapshot = cmd.snapshot; - if (cmd.tailable) findCmd.tailable = cmd.tailable; - if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; - if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; - if (cmd.awaitData) findCmd.awaitData = cmd.awaitData; - if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; - if (cmd.partial) findCmd.partial = cmd.partial; - if (cmd.collation) findCmd.collation = cmd.collation; - if (cmd.readConcern) findCmd.readConcern = cmd.readConcern; - - // If we have explain, we need to rewrite the find command - // to wrap it in the explain command - if (cmd.explain) { - findCmd = { - explain: findCmd - }; - } - - return findCmd; -} - -function prepareLegacyFindQuery(server, ns, cmd, cursorState, options) { - options = options || {}; - const bson = server.s.bson; - const readPreference = getReadPreference(cmd, options); - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - - let numberToReturn = 0; - if ( - cursorState.limit < 0 || - (cursorState.limit !== 0 && cursorState.limit < cursorState.batchSize) || - (cursorState.limit > 0 && cursorState.batchSize === 0) - ) { - numberToReturn = cursorState.limit; - } else { - numberToReturn = cursorState.batchSize; - } - - const numberToSkip = cursorState.skip || 0; - - const findCmd = {}; - if (isSharded(server) && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - } - - if (cmd.sort) findCmd['$orderby'] = cmd.sort; - if (cmd.hint) findCmd['$hint'] = cmd.hint; - if (cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot; - if (typeof cmd.returnKey !== 'undefined') findCmd['$returnKey'] = cmd.returnKey; - if (cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan; - if (cmd.min) findCmd['$min'] = cmd.min; - if (cmd.max) findCmd['$max'] = cmd.max; - if (typeof cmd.showDiskLoc !== 'undefined') findCmd['$showDiskLoc'] = cmd.showDiskLoc; - if (cmd.comment) findCmd['$comment'] = cmd.comment; - if (cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS; - if (cmd.explain) { - // nToReturn must be 0 (match all) or negative (match N and close cursor) - // nToReturn > 0 will give explain results equivalent to limit(0) - numberToReturn = -Math.abs(cmd.limit || 0); - findCmd['$explain'] = true; - } - - findCmd['$query'] = cmd.query; - if (cmd.readConcern && cmd.readConcern.level !== 'local') { - throw new MongoError( - `server find command does not support a readConcern level of ${cmd.readConcern.level}` - ); - } - - if (cmd.readConcern) { - cmd = Object.assign({}, cmd); - delete cmd['readConcern']; - } - - const serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - - const query = new Query(bson, ns, findCmd, { - numberToSkip: numberToSkip, - numberToReturn: numberToReturn, - pre32Limit: typeof cmd.limit !== 'undefined' ? cmd.limit : undefined, - checkKeys: false, - returnFieldSelector: cmd.fields, - serializeFunctions: serializeFunctions, - ignoreUndefined: ignoreUndefined - }); - - if (typeof cmd.tailable === 'boolean') query.tailable = cmd.tailable; - if (typeof cmd.oplogReplay === 'boolean') query.oplogReplay = cmd.oplogReplay; - if (typeof cmd.noCursorTimeout === 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; - if (typeof cmd.awaitData === 'boolean') query.awaitData = cmd.awaitData; - if (typeof cmd.partial === 'boolean') query.partial = cmd.partial; - - query.slaveOk = readPreference.slaveOk(); - return query; -} - -module.exports = query; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/shared.js b/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/shared.js deleted file mode 100644 index c586f05..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/shared.js +++ /dev/null @@ -1,115 +0,0 @@ -'use strict'; - -const ReadPreference = require('../topologies/read_preference'); -const MongoError = require('../error').MongoError; -const ServerType = require('../sdam/common').ServerType; -const TopologyDescription = require('../sdam/topology_description').TopologyDescription; - -const MESSAGE_HEADER_SIZE = 16; -const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID - -// OPCODE Numbers -// Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes -var opcodes = { - OP_REPLY: 1, - OP_UPDATE: 2001, - OP_INSERT: 2002, - OP_QUERY: 2004, - OP_GETMORE: 2005, - OP_DELETE: 2006, - OP_KILL_CURSORS: 2007, - OP_COMPRESSED: 2012, - OP_MSG: 2013 -}; - -var getReadPreference = function(cmd, options) { - // Default to command version of the readPreference - var readPreference = cmd.readPreference || new ReadPreference('primary'); - // If we have an option readPreference override the command one - if (options.readPreference) { - readPreference = options.readPreference; - } - - if (typeof readPreference === 'string') { - readPreference = new ReadPreference(readPreference); - } - - if (!(readPreference instanceof ReadPreference)) { - throw new MongoError('read preference must be a ReadPreference instance'); - } - - return readPreference; -}; - -// Parses the header of a wire protocol message -var parseHeader = function(message) { - return { - length: message.readInt32LE(0), - requestId: message.readInt32LE(4), - responseTo: message.readInt32LE(8), - opCode: message.readInt32LE(12) - }; -}; - -function applyCommonQueryOptions(queryOptions, options) { - Object.assign(queryOptions, { - raw: typeof options.raw === 'boolean' ? options.raw : false, - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, - monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, - fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false - }); - - if (typeof options.socketTimeout === 'number') { - queryOptions.socketTimeout = options.socketTimeout; - } - - if (options.session) { - queryOptions.session = options.session; - } - - if (typeof options.documentsReturnedIn === 'string') { - queryOptions.documentsReturnedIn = options.documentsReturnedIn; - } - - return queryOptions; -} - -function isSharded(topologyOrServer) { - if (topologyOrServer.type === 'mongos') return true; - if (topologyOrServer.description && topologyOrServer.description.type === ServerType.Mongos) { - return true; - } - - // NOTE: This is incredibly inefficient, and should be removed once command construction - // happens based on `Server` not `Topology`. - if (topologyOrServer.description && topologyOrServer.description instanceof TopologyDescription) { - const servers = Array.from(topologyOrServer.description.servers.values()); - return servers.some(server => server.type === ServerType.Mongos); - } - - return false; -} - -function databaseNamespace(ns) { - return ns.split('.')[0]; -} -function collectionNamespace(ns) { - return ns - .split('.') - .slice(1) - .join('.'); -} - -module.exports = { - getReadPreference, - MESSAGE_HEADER_SIZE, - COMPRESSION_DETAILS_SIZE, - opcodes, - parseHeader, - applyCommonQueryOptions, - isSharded, - databaseNamespace, - collectionNamespace -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/write_command.js b/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/write_command.js deleted file mode 100644 index e334d51..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/core/wireprotocol/write_command.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -const MongoError = require('../error').MongoError; -const collectionNamespace = require('./shared').collectionNamespace; -const command = require('./command'); - -function writeCommand(server, type, opsField, ns, ops, options, callback) { - if (ops.length === 0) throw new MongoError(`${type} must contain at least one document`); - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; - const writeConcern = options.writeConcern; - - const writeCommand = {}; - writeCommand[type] = collectionNamespace(ns); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - - if (writeConcern && Object.keys(writeConcern).length > 0) { - writeCommand.writeConcern = writeConcern; - } - - if (options.collation) { - for (let i = 0; i < writeCommand[opsField].length; i++) { - if (!writeCommand[opsField][i].collation) { - writeCommand[opsField][i].collation = options.collation; - } - } - } - - if (options.bypassDocumentValidation === true) { - writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; - } - - const commandOptions = Object.assign( - { - checkKeys: type === 'insert', - numberToReturn: 1 - }, - options - ); - - command(server, ns, writeCommand, commandOptions, callback); -} - -module.exports = writeCommand; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/cursor.js b/node_modules/mongoose/node_modules/mongodb/lib/cursor.js deleted file mode 100644 index 0e8d062..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/cursor.js +++ /dev/null @@ -1,1158 +0,0 @@ -'use strict'; - -const Transform = require('stream').Transform; -const PassThrough = require('stream').PassThrough; -const deprecate = require('util').deprecate; -const handleCallback = require('./utils').handleCallback; -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const CoreCursor = require('./core/cursor').CoreCursor; -const CursorState = require('./core/cursor').CursorState; -const Map = require('./core').BSON.Map; -const maybePromise = require('./utils').maybePromise; -const executeOperation = require('./operations/execute_operation'); -const formattedOrderClause = require('./utils').formattedOrderClause; - -const each = require('./operations/cursor_ops').each; -const CountOperation = require('./operations/count'); - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 4.X - * or higher stream - * - * **CURSORS Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the code module - * @external CoreCursor - * @external Readable - */ - -// Flags allowed for cursor -const flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; -const fields = ['numberOfRetries', 'tailableRetryInterval']; - -/** - * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class Cursor - * @extends external:CoreCursor - * @extends external:Readable - * @property {string} sortValue Cursor query sort setting. - * @property {boolean} timeout Is Cursor able to time out. - * @property {ReadPreference} readPreference Get cursor ReadPreference. - * @fires Cursor#data - * @fires Cursor#end - * @fires Cursor#close - * @fires Cursor#readable - * @return {Cursor} a Cursor instance. - * @example - * Cursor cursor options. - * - * collection.find({}).project({a:1}) // Create a projection of field a - * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 - * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 - * collection.find({}).filter({a:1}) // Set query on the cursor - * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries - * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable - * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay - * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout - * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData - * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial - * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} - * collection.find({}).max(10) // Set the cursor max - * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS - * collection.find({}).min(100) // Set the cursor min - * collection.find({}).returnKey(true) // Set the cursor returnKey - * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference - * collection.find({}).showRecordId(true) // Set the cursor showRecordId - * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query - * collection.find({}).hint('a_1') // Set the cursor hint - * - * All options are chainable, so one can do the following. - * - * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) - */ -class Cursor extends CoreCursor { - constructor(topology, ns, cmd, options) { - super(topology, ns, cmd, options); - if (this.operation) { - options = this.operation.options; - } - - // Tailable cursor options - const numberOfRetries = options.numberOfRetries || 5; - const tailableRetryInterval = options.tailableRetryInterval || 500; - const currentNumberOfRetries = numberOfRetries; - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Internal cursor state - this.s = { - // Tailable cursor options - numberOfRetries: numberOfRetries, - tailableRetryInterval: tailableRetryInterval, - currentNumberOfRetries: currentNumberOfRetries, - // State - state: CursorState.INIT, - // Promise library - promiseLibrary, - // explicitlyIgnoreSession - explicitlyIgnoreSession: !!options.explicitlyIgnoreSession - }; - - // Optional ClientSession - if (!options.explicitlyIgnoreSession && options.session) { - this.cursorState.session = options.session; - } - - // Translate correctly - if (this.options.noCursorTimeout === true) { - this.addCursorFlag('noCursorTimeout', true); - } - - // Get the batchSize - let batchSize = 1000; - if (this.cmd.cursor && this.cmd.cursor.batchSize) { - batchSize = this.cmd.cursor.batchSize; - } else if (options.cursor && options.cursor.batchSize) { - batchSize = options.cursor.batchSize; - } else if (typeof options.batchSize === 'number') { - batchSize = options.batchSize; - } - - // Set the batchSize - this.setCursorBatchSize(batchSize); - } - - get readPreference() { - if (this.operation) { - return this.operation.readPreference; - } - - return this.options.readPreference; - } - - get sortValue() { - return this.cmd.sort; - } - - _initializeCursor(callback) { - if (this.operation && this.operation.session != null) { - this.cursorState.session = this.operation.session; - } else { - // implicitly create a session if one has not been provided - if ( - !this.s.explicitlyIgnoreSession && - !this.cursorState.session && - this.topology.hasSessionSupport() - ) { - this.cursorState.session = this.topology.startSession({ owner: this }); - - if (this.operation) { - this.operation.session = this.cursorState.session; - } - } - } - - super._initializeCursor(callback); - } - - /** - * Check if there is any document still available in the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - hasNext(callback) { - if (this.s.state === CursorState.CLOSED || (this.isDead && this.isDead())) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - return maybePromise(this, callback, cb => { - const cursor = this; - if (cursor.isNotified()) { - return cb(null, false); - } - - cursor._next((err, doc) => { - if (err) return cb(err); - if (doc == null || cursor.s.state === Cursor.CLOSED || cursor.isDead()) { - return cb(null, false); - } - - cursor.s.state = CursorState.OPEN; - - // NODE-2482: merge this into the core cursor implementation - cursor.cursorState.cursorIndex--; - if (cursor.cursorState.limit > 0) { - cursor.cursorState.currentLimit--; - } - - cb(null, true); - }); - }); - } - - /** - * Get the next available document from the cursor, returns null if no more documents are available. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - next(callback) { - return maybePromise(this, callback, cb => { - const cursor = this; - if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) { - cb(MongoError.create({ message: 'Cursor is closed', driver: true })); - return; - } - - if (cursor.s.state === CursorState.INIT && cursor.cmd.sort) { - try { - cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); - } catch (err) { - return cb(err); - } - } - - cursor._next((err, doc) => { - if (err) return cb(err); - cursor.s.state = CursorState.OPEN; - cb(null, doc); - }); - }); - } - - /** - * Set the cursor query - * @method - * @param {object} filter The filter object used for the cursor. - * @return {Cursor} - */ - filter(filter) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.query = filter; - return this; - } - - /** - * Set the cursor maxScan - * @method - * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query - * @deprecated as of MongoDB 4.0 - * @return {Cursor} - */ - maxScan(maxScan) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxScan = maxScan; - return this; - } - - /** - * Set the cursor hint - * @method - * @param {object} hint If specified, then the query system will only consider plans using the hinted index. - * @return {Cursor} - */ - hint(hint) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.hint = hint; - return this; - } - - /** - * Set the cursor min - * @method - * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. - * @return {Cursor} - */ - min(min) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.min = min; - return this; - } - - /** - * Set the cursor max - * @method - * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. - * @return {Cursor} - */ - max(max) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.max = max; - return this; - } - - /** - * Set the cursor returnKey. If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. - * @method - * @param {bool} returnKey the returnKey value. - * @return {Cursor} - */ - returnKey(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.returnKey = value; - return this; - } - - /** - * Set the cursor showRecordId - * @method - * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. - * @return {Cursor} - */ - showRecordId(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.showDiskLoc = value; - return this; - } - - /** - * Set the cursor snapshot - * @method - * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. - * @deprecated as of MongoDB 4.0 - * @return {Cursor} - */ - snapshot(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.snapshot = value; - return this; - } - - /** - * Set a node.js specific cursor option - * @method - * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. - * @param {object} value The field value. - * @throws {MongoError} - * @return {Cursor} - */ - setCursorOption(field, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (fields.indexOf(field) === -1) { - throw MongoError.create({ - message: `option ${field} is not a supported option ${fields}`, - driver: true - }); - } - - this.s[field] = value; - if (field === 'numberOfRetries') this.s.currentNumberOfRetries = value; - return this; - } - - /** - * Add a cursor flag to the cursor - * @method - * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial']. - * @param {boolean} value The flag boolean value. - * @throws {MongoError} - * @return {Cursor} - */ - addCursorFlag(flag, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (flags.indexOf(flag) === -1) { - throw MongoError.create({ - message: `flag ${flag} is not a supported flag ${flags}`, - driver: true - }); - } - - if (typeof value !== 'boolean') { - throw MongoError.create({ message: `flag ${flag} must be a boolean value`, driver: true }); - } - - this.cmd[flag] = value; - return this; - } - - /** - * Add a query modifier to the cursor query - * @method - * @param {string} name The query modifier (must start with $, such as $orderby etc) - * @param {string|boolean|number} value The modifier value. - * @throws {MongoError} - * @return {Cursor} - */ - addQueryModifier(name, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (name[0] !== '$') { - throw MongoError.create({ message: `${name} is not a valid query modifier`, driver: true }); - } - - // Strip of the $ - const field = name.substr(1); - // Set on the command - this.cmd[field] = value; - // Deal with the special case for sort - if (field === 'orderby') this.cmd.sort = this.cmd[field]; - return this; - } - - /** - * Add a comment to the cursor query allowing for tracking the comment in the log. - * @method - * @param {string} value The comment attached to this query. - * @throws {MongoError} - * @return {Cursor} - */ - comment(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.comment = value; - return this; - } - - /** - * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) - * @method - * @param {number} value Number of milliseconds to wait before aborting the tailed query. - * @throws {MongoError} - * @return {Cursor} - */ - maxAwaitTimeMS(value) { - if (typeof value !== 'number') { - throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxAwaitTimeMS = value; - return this; - } - - /** - * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) - * @method - * @param {number} value Number of milliseconds to wait before aborting the query. - * @throws {MongoError} - * @return {Cursor} - */ - maxTimeMS(value) { - if (typeof value !== 'number') { - throw MongoError.create({ message: 'maxTimeMS must be a number', driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxTimeMS = value; - return this; - } - - /** - * Sets a field projection for the query. - * @method - * @param {object} value The field projection object. - * @throws {MongoError} - * @return {Cursor} - */ - project(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.fields = value; - return this; - } - - /** - * Sets the sort order of the cursor query. - * @method - * @param {(string|array|object)} keyOrList The key or keys set for the sort. - * @param {number} [direction] The direction of the sorting (1 or -1). - * @throws {MongoError} - * @return {Cursor} - */ - sort(keyOrList, direction) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support sorting", driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - let order = keyOrList; - - // We have an array of arrays, we need to preserve the order of the sort - // so we will us a Map - if (Array.isArray(order) && Array.isArray(order[0])) { - order = new Map( - order.map(x => { - const value = [x[0], null]; - if (x[1] === 'asc') { - value[1] = 1; - } else if (x[1] === 'desc') { - value[1] = -1; - } else if (x[1] === 1 || x[1] === -1 || x[1].$meta) { - value[1] = x[1]; - } else { - throw new MongoError( - "Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" - ); - } - - return value; - }) - ); - } - - if (direction != null) { - order = [[keyOrList, direction]]; - } - - this.cmd.sort = order; - return this; - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. - * @throws {MongoError} - * @return {Cursor} - */ - batchSize(value) { - if (this.options.tailable) { - throw MongoError.create({ - message: "Tailable cursor doesn't support batchSize", - driver: true - }); - } - - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - this.cmd.batchSize = value; - this.setCursorBatchSize(value); - return this; - } - - /** - * Set the collation options for the cursor. - * @method - * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @throws {MongoError} - * @return {Cursor} - */ - collation(value) { - this.cmd.collation = value; - return this; - } - - /** - * Set the limit for the cursor. - * @method - * @param {number} value The limit for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ - limit(value) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support limit", driver: true }); - } - - if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'limit requires an integer', driver: true }); - } - - this.cmd.limit = value; - this.setCursorLimit(value); - return this; - } - - /** - * Set the skip for the cursor. - * @method - * @param {number} value The skip for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ - skip(value) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support skip", driver: true }); - } - - if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'skip requires an integer', driver: true }); - } - - this.cmd.skip = value; - this.setCursorSkip(value); - return this; - } - - /** - * The callback format for results - * @callback Cursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null|boolean)} result The result object if the command was executed successfully. - */ - - /** - * Clone the cursor - * @function external:CoreCursor#clone - * @return {Cursor} - */ - - /** - * Resets the cursor - * @function external:CoreCursor#rewind - * @return {null} - */ - - /** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method - * @deprecated - * @param {Cursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - each(callback) { - // Rewind cursor state - this.rewind(); - // Set current cursor to INIT - this.s.state = CursorState.INIT; - // Run the query - each(this, callback); - } - - /** - * The callback format for the forEach iterator method - * @callback Cursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - - /** - * The callback error format for the forEach iterator method - * @callback Cursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - - /** - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method - * @param {Cursor~iteratorCallback} iterator The iteration callback. - * @param {Cursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {Promise} if no callback supplied - */ - forEach(iterator, callback) { - // Rewind cursor state - this.rewind(); - - // Set current cursor to INIT - this.s.state = CursorState.INIT; - - if (typeof callback === 'function') { - each(this, (err, doc) => { - if (err) { - callback(err); - return false; - } - if (doc != null) { - iterator(doc); - return true; - } - if (doc == null && callback) { - const internalCallback = callback; - callback = null; - internalCallback(null); - return false; - } - }); - } else { - return new this.s.promiseLibrary((fulfill, reject) => { - each(this, (err, doc) => { - if (err) { - reject(err); - return false; - } else if (doc == null) { - fulfill(null); - return false; - } else { - iterator(doc); - return true; - } - }); - }); - } - } - - /** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ - setReadPreference(readPreference) { - if (this.s.state !== CursorState.INIT) { - throw MongoError.create({ - message: 'cannot change cursor readPreference after cursor has been accessed', - driver: true - }); - } - - if (readPreference instanceof ReadPreference) { - this.options.readPreference = readPreference; - } else if (typeof readPreference === 'string') { - this.options.readPreference = new ReadPreference(readPreference); - } else { - throw new TypeError('Invalid read preference: ' + readPreference); - } - - return this; - } - - /** - * The callback format for results - * @callback Cursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - - /** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contains partial - * results when this cursor had been previously accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - toArray(callback) { - if (this.options.tailable) { - throw MongoError.create({ - message: 'Tailable cursor cannot be converted to array', - driver: true - }); - } - - return maybePromise(this, callback, cb => { - const cursor = this; - const items = []; - - // Reset cursor - cursor.rewind(); - cursor.s.state = CursorState.INIT; - - // Fetch all the documents - const fetchDocs = () => { - cursor._next((err, doc) => { - if (err) { - return cursor._endSession - ? cursor._endSession(() => handleCallback(cb, err)) - : handleCallback(cb, err); - } - - if (doc == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(cb, null, items)); - } - - // Add doc to items - items.push(doc); - - // Get all buffered objects - if (cursor.bufferedCount() > 0) { - let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); - Array.prototype.push.apply(items, docs); - } - - // Attempt a fetch - fetchDocs(); - }); - }; - - fetchDocs(); - }); - } - - /** - * The callback format for results - * @callback Cursor~countResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} count The count of documents. - */ - - /** - * Get the count of documents for this cursor - * @method - * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. - * @param {object} [options] Optional settings. - * @param {number} [options.skip] The number of documents to skip. - * @param {number} [options.limit] The maximum amounts to count before aborting. - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {string} [options.hint] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Cursor~countResultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - count(applySkipLimit, opts, callback) { - if (this.cmd.query == null) - throw MongoError.create({ - message: 'count can only be used with find command', - driver: true - }); - if (typeof opts === 'function') (callback = opts), (opts = {}); - opts = opts || {}; - - if (typeof applySkipLimit === 'function') { - callback = applySkipLimit; - applySkipLimit = true; - } - - if (this.cursorState.session) { - opts = Object.assign({}, opts, { session: this.cursorState.session }); - } - - const countOperation = new CountOperation(this, applySkipLimit, opts); - - return executeOperation(this.topology, countOperation, callback); - } - - /** - * Close the cursor, sending a KillCursor command and emitting close. - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor. - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - close(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { skipKillCursors: false }, options); - - this.s.state = CursorState.CLOSED; - if (!options.skipKillCursors) { - // Kill the cursor - this.kill(); - } - - const completeClose = () => { - // Emit the close event for the cursor - this.emit('close'); - - // Callback if provided - if (typeof callback === 'function') { - return handleCallback(callback, null, this); - } - - // Return a Promise - return new this.s.promiseLibrary(resolve => { - resolve(); - }); - }; - - if (this.cursorState.session) { - if (typeof callback === 'function') { - return this._endSession(() => completeClose()); - } - - return new this.s.promiseLibrary(resolve => { - this._endSession(() => completeClose().then(resolve)); - }); - } - - return completeClose(); - } - - /** - * Map all documents using the provided function - * @method - * @param {function} [transform] The mapping transformation method. - * @return {Cursor} - */ - map(transform) { - if (this.cursorState.transforms && this.cursorState.transforms.doc) { - const oldTransform = this.cursorState.transforms.doc; - this.cursorState.transforms.doc = doc => { - return transform(oldTransform(doc)); - }; - } else { - this.cursorState.transforms = { doc: transform }; - } - - return this; - } - - /** - * Is the cursor closed - * @method - * @return {boolean} - */ - isClosed() { - return this.isDead(); - } - - destroy(err) { - if (err) this.emit('error', err); - this.pause(); - this.close(); - } - - /** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - * TODO: replace this method with transformStream in next major release - */ - stream(options) { - this.cursorState.streamOptions = options || {}; - return this; - } - - /** - * Return a modified Readable stream that applies a given transform function, if supplied. If none supplied, - * returns a stream of unmodified docs. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {stream} - */ - transformStream(options) { - const streamOptions = options || {}; - if (typeof streamOptions.transform === 'function') { - const stream = new Transform({ - objectMode: true, - transform: function(chunk, encoding, callback) { - this.push(streamOptions.transform(chunk)); - callback(); - } - }); - - return this.pipe(stream); - } - - return this.pipe(new PassThrough({ objectMode: true })); - } - - /** - * Execute the explain for the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - explain(callback) { - // NOTE: the next line includes a special case for operations which do not - // subclass `CommandOperationV2`. To be removed asap. - if (this.operation && this.operation.cmd == null) { - this.operation.options.explain = true; - this.operation.fullResponse = false; - return executeOperation(this.topology, this.operation, callback); - } - - this.cmd.explain = true; - - // Do we have a readConcern - if (this.cmd.readConcern) { - delete this.cmd['readConcern']; - } - return maybePromise(this, callback, cb => { - CoreCursor.prototype._next.apply(this, [cb]); - }); - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -/** - * Cursor stream data event, fired for each document in the cursor. - * - * @event Cursor#data - * @type {object} - */ - -/** - * Cursor stream end event - * - * @event Cursor#end - * @type {null} - */ - -/** - * Cursor stream close event - * - * @event Cursor#close - * @type {null} - */ - -/** - * Cursor stream readable event - * - * @event Cursor#readable - * @type {null} - */ - -// aliases -Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; - -// deprecated methods -deprecate(Cursor.prototype.each, 'Cursor.each is deprecated. Use Cursor.forEach instead.'); -deprecate( - Cursor.prototype.maxScan, - 'Cursor.maxScan is deprecated, and will be removed in a later version' -); - -deprecate( - Cursor.prototype.snapshot, - 'Cursor Snapshot is deprecated, and will be removed in a later version' -); - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Readable#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Readable#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Readable#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Readable#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Readable#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Readable#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Readable#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Readable#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -module.exports = Cursor; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/db.js b/node_modules/mongoose/node_modules/mongodb/lib/db.js deleted file mode 100644 index e28d25a..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/db.js +++ /dev/null @@ -1,1031 +0,0 @@ -'use strict'; - -const EventEmitter = require('events').EventEmitter; -const inherits = require('util').inherits; -const getSingleProperty = require('./utils').getSingleProperty; -const CommandCursor = require('./command_cursor'); -const handleCallback = require('./utils').handleCallback; -const filterOptions = require('./utils').filterOptions; -const toError = require('./utils').toError; -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const ObjectID = require('./core').ObjectID; -const Logger = require('./core').Logger; -const Collection = require('./collection'); -const mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern; -const executeLegacyOperation = require('./utils').executeLegacyOperation; -const resolveReadPreference = require('./utils').resolveReadPreference; -const ChangeStream = require('./change_stream'); -const deprecate = require('util').deprecate; -const deprecateOptions = require('./utils').deprecateOptions; -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const CONSTANTS = require('./constants'); -const WriteConcern = require('./write_concern'); -const ReadConcern = require('./read_concern'); -const AggregationCursor = require('./aggregation_cursor'); - -// Operations -const createListener = require('./operations/db_ops').createListener; -const ensureIndex = require('./operations/db_ops').ensureIndex; -const evaluate = require('./operations/db_ops').evaluate; -const profilingInfo = require('./operations/db_ops').profilingInfo; -const validateDatabaseName = require('./operations/db_ops').validateDatabaseName; - -const AggregateOperation = require('./operations/aggregate'); -const AddUserOperation = require('./operations/add_user'); -const CollectionsOperation = require('./operations/collections'); -const CommandOperation = require('./operations/command'); -const CreateCollectionOperation = require('./operations/create_collection'); -const CreateIndexOperation = require('./operations/create_index'); -const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; -const DropDatabaseOperation = require('./operations/drop').DropDatabaseOperation; -const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); -const IndexInformationOperation = require('./operations/index_information'); -const ListCollectionsOperation = require('./operations/list_collections'); -const ProfilingLevelOperation = require('./operations/profiling_level'); -const RemoveUserOperation = require('./operations/remove_user'); -const RenameOperation = require('./operations/rename'); -const SetProfilingLevelOperation = require('./operations/set_profiling_level'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Db** class is a class that represents a MongoDB Database. - * - * @example - * const MongoClient = require('mongodb').MongoClient; - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Select the database by name - * const testDb = client.db(dbName); - * client.close(); - * }); - */ - -// Allowed parameters -const legalOptionNames = [ - 'w', - 'wtimeout', - 'fsync', - 'j', - 'readPreference', - 'readPreferenceTags', - 'native_parser', - 'forceServerObjectId', - 'pkFactory', - 'serializeFunctions', - 'raw', - 'bufferMaxEntries', - 'authSource', - 'ignoreUndefined', - 'promoteLongs', - 'promiseLibrary', - 'readConcern', - 'retryMiliSeconds', - 'numberOfRetries', - 'parentDb', - 'noListener', - 'loggerLevel', - 'logger', - 'promoteBuffers', - 'promoteLongs', - 'promoteValues', - 'compression', - 'retryWrites' -]; - -/** - * Creates a new Db instance - * @class - * @param {string} databaseName The name of the database this instance represents. - * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. - * @param {object} [options] Optional settings. - * @param {string} [options.authSource] If the database authentication is dependent on another databaseName. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. - * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database - * @property {string} databaseName The name of the database this instance represents. - * @property {object} options The options associated with the db instance. - * @property {boolean} native_parser The current value of the parameter native_parser. - * @property {boolean} slaveOk The current slaveOk value for the db instance. - * @property {object} writeConcern The current write concern values. - * @property {object} topology Access the topology object (single server, replicaset or mongos). - * @fires Db#close - * @fires Db#reconnect - * @fires Db#error - * @fires Db#timeout - * @fires Db#parseError - * @fires Db#fullsetup - * @return {Db} a Db instance. - */ -function Db(databaseName, topology, options) { - options = options || {}; - if (!(this instanceof Db)) return new Db(databaseName, topology, options); - EventEmitter.call(this); - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure we put the promiseLib in the options - options.promiseLibrary = promiseLibrary; - - // Internal state of the db object - this.s = { - // DbCache - dbCache: {}, - // Children db's - children: [], - // Topology - topology: topology, - // Options - options: options, - // Logger instance - logger: Logger('Db', options), - // Get the bson parser - bson: topology ? topology.bson : null, - // Unpack read preference - readPreference: ReadPreference.fromOptions(options), - // Set buffermaxEntries - bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1, - // Parent db (if chained) - parentDb: options.parentDb || null, - // Set up the primary key factory or fallback to ObjectID - pkFactory: options.pkFactory || ObjectID, - // Get native parser - nativeParser: options.nativeParser || options.native_parser, - // Promise library - promiseLibrary: promiseLibrary, - // No listener - noListener: typeof options.noListener === 'boolean' ? options.noListener : false, - // ReadConcern - readConcern: ReadConcern.fromOptions(options), - writeConcern: WriteConcern.fromOptions(options), - // Namespace - namespace: new MongoDBNamespace(databaseName) - }; - - // Ensure we have a valid db name - validateDatabaseName(databaseName); - - // Add a read Only property - getSingleProperty(this, 'serverConfig', this.s.topology); - getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries); - getSingleProperty(this, 'databaseName', this.s.namespace.db); - - // This is a child db, do not register any listeners - if (options.parentDb) return; - if (this.s.noListener) return; - - // Add listeners - topology.on('error', createListener(this, 'error', this)); - topology.on('timeout', createListener(this, 'timeout', this)); - topology.on('close', createListener(this, 'close', this)); - topology.on('parseError', createListener(this, 'parseError', this)); - topology.once('open', createListener(this, 'open', this)); - topology.once('fullsetup', createListener(this, 'fullsetup', this)); - topology.once('all', createListener(this, 'all', this)); - topology.on('reconnect', createListener(this, 'reconnect', this)); -} - -inherits(Db, EventEmitter); - -// Topology -Object.defineProperty(Db.prototype, 'topology', { - enumerable: true, - get: function() { - return this.s.topology; - } -}); - -// Options -Object.defineProperty(Db.prototype, 'options', { - enumerable: true, - get: function() { - return this.s.options; - } -}); - -// slaveOk specified -Object.defineProperty(Db.prototype, 'slaveOk', { - enumerable: true, - get: function() { - if ( - this.s.options.readPreference != null && - (this.s.options.readPreference !== 'primary' || - this.s.options.readPreference.mode !== 'primary') - ) { - return true; - } - return false; - } -}); - -Object.defineProperty(Db.prototype, 'readConcern', { - enumerable: true, - get: function() { - return this.s.readConcern; - } -}); - -Object.defineProperty(Db.prototype, 'readPreference', { - enumerable: true, - get: function() { - if (this.s.readPreference == null) { - // TODO: check client - return ReadPreference.primary; - } - - return this.s.readPreference; - } -}); - -// get the write Concern -Object.defineProperty(Db.prototype, 'writeConcern', { - enumerable: true, - get: function() { - return this.s.writeConcern; - } -}); - -Object.defineProperty(Db.prototype, 'namespace', { - enumerable: true, - get: function() { - return this.s.namespace.toString(); - } -}); - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.command = function(command, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - const commandOperation = new CommandOperation(this, options, null, command); - - return executeOperation(this.s.topology, commandOperation, callback); -}; - -/** - * Execute an aggregation framework pipeline against the database, needs MongoDB >= 3.6 - * @method - * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * @param {number} [options.cursor.batchSize=1000] Deprecated. Use `options.batchSize` - * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). - * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {string} [options.comment] Add a comment to an aggregation command - * @param {string|object} [options.hint] Add an index selection hint to an aggregation command - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Database~aggregationCallback} callback The command result callback - * @return {(null|AggregationCursor)} - */ -Db.prototype.aggregate = function(pipeline, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - // If we have no options or callback we are doing - // a cursor based aggregation - if (options == null && callback == null) { - options = {}; - } - - const cursor = new AggregationCursor( - this.s.topology, - new AggregateOperation(this, pipeline, options), - options - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; -}; - -/** - * Return the Admin db instance - * @method - * @return {Admin} return the new Admin db instance - */ -Db.prototype.admin = function() { - const Admin = require('./admin'); - - return new Admin(this, this.s.topology, this.s.promiseLibrary); -}; - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Db~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * The callback format for an aggregation call - * @callback Database~aggregationCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. - */ - -const collectionKeys = [ - 'pkFactory', - 'readPreference', - 'serializeFunctions', - 'strict', - 'readConcern', - 'ignoreUndefined', - 'promoteValues', - 'promoteBuffers', - 'promoteLongs' -]; - -/** - * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you - * can use it without a callback in the following way: `const collection = db.collection('mycollection');` - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @param {Db~collectionResultCallback} [callback] The collection result callback - * @return {Collection} return the new Collection instance if not in strict mode - */ -Db.prototype.collection = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options = Object.assign({}, options); - - // Set the promise library - options.promiseLibrary = this.s.promiseLibrary; - - // If we have not set a collection level readConcern set the db level one - options.readConcern = options.readConcern - ? new ReadConcern(options.readConcern.level) - : this.readConcern; - - // Do we have ignoreUndefined set - if (this.s.options.ignoreUndefined) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Merge in all needed options and ensure correct writeConcern merging from db level - options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true); - - // Execute - if (options == null || !options.strict) { - try { - const collection = new Collection( - this, - this.s.topology, - this.databaseName, - name, - this.s.pkFactory, - options - ); - if (callback) callback(null, collection); - return collection; - } catch (err) { - if (err instanceof MongoError && callback) return callback(err); - throw err; - } - } - - // Strict mode - if (typeof callback !== 'function') { - throw toError(`A callback is required in strict mode. While getting collection ${name}`); - } - - // Did the user destroy the topology - if (this.serverConfig && this.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - const listCollectionOptions = Object.assign({}, options, { nameOnly: true }); - - // Strict mode - this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => { - if (err != null) return handleCallback(callback, err, null); - if (collections.length === 0) - return handleCallback( - callback, - toError(`Collection ${name} does not exist. Currently in strict mode.`), - null - ); - - try { - return handleCallback( - callback, - null, - new Collection(this, this.s.topology, this.databaseName, name, this.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err, null); - } - }); -}; - -/** - * Create a new collection on a server with the specified options. Use this to create capped collections. - * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {boolean} [options.capped=false] Create a capped collection. - * @param {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 - * @param {number} [options.size] The size of the capped collection in bytes. - * @param {number} [options.max] The maximum number of documents in the capped collection. - * @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag. - * @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher. - * @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher. - * @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher. - * @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher. - * @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher. - * @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher. - * @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createCollection = deprecateOptions( - { - name: 'Db.createCollection', - deprecatedOptions: ['autoIndexId'], - optionsIndex: 1 - }, - function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; - options.readConcern = options.readConcern - ? new ReadConcern(options.readConcern.level) - : this.readConcern; - const createCollectionOperation = new CreateCollectionOperation(this, name, options); - - return executeOperation(this.s.topology, createCollectionOperation, callback); - } -); - -/** - * Get all the db statistics. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.scale] Divide the returned sizes by scale value. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.stats = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - // Build command object - const commandObject = { dbStats: true }; - // Check if we have the scale value - if (options['scale'] != null) commandObject['scale'] = options['scale']; - - // If we have a readPreference set - if (options.readPreference == null && this.s.readPreference) { - options.readPreference = this.s.readPreference; - } - - const statsOperation = new CommandOperation(this, options, null, commandObject); - - // Execute the command - return executeOperation(this.s.topology, statsOperation, callback); -}; - -/** - * Get the list of all collection information for the specified db. - * - * @method - * @param {object} [filter={}] Query to filter collections by - * @param {object} [options] Optional settings. - * @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info - * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {CommandCursor} - */ -Db.prototype.listCollections = function(filter, options) { - filter = filter || {}; - options = options || {}; - - return new CommandCursor( - this.s.topology, - new ListCollectionsOperation(this, filter, options), - options - ); -}; - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options] Optional settings. - * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaluation of the javascript. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.eval = deprecate(function(code, parameters, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - parameters = args.length ? args.shift() : parameters; - options = args.length ? args.shift() || {} : {}; - - return executeLegacyOperation(this.s.topology, evaluate, [ - this, - code, - parameters, - options, - callback - ]); -}, 'Db.eval is deprecated as of MongoDB version 3.2'); - -/** - * Rename a collection. - * - * @method - * @param {string} fromCollection Name of current collection to rename. - * @param {string} toCollection New name of of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Add return new collection - options.new_collection = true; - - const renameOperation = new RenameOperation( - this.collection(fromCollection), - toCollection, - options - ); - - return executeOperation(this.s.topology, renameOperation, callback); -}; - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {string} name Name of collection to drop - * @param {Object} [options] Optional settings - * @param {WriteConcern} [options.writeConcern] A full WriteConcern object - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j] The journal write concern - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropCollection = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropCollectionOperation = new DropCollectionOperation(this, name, options); - - return executeOperation(this.s.topology, dropCollectionOperation, callback); -}; - -/** - * Drop a database, removing it permanently from the server. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropDatabase = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropDatabaseOperation = new DropDatabaseOperation(this, options); - - return executeOperation(this.s.topology, dropDatabaseOperation, callback); -}; - -/** - * Fetch all collections for the current db. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionsResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.collections = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const collectionsOperation = new CollectionsOperation(this, options); - - return executeOperation(this.s.topology, collectionsOperation, callback); -}; - -/** - * Runs a command on the database as admin. - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.executeDbAdminCommand = function(selector, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options.readPreference = resolveReadPreference(this, options); - - const executeDbAdminCommandOperation = new ExecuteDbAdminCommandOperation( - this, - selector, - options - ); - - return executeOperation(this.s.topology, executeDbAdminCommandOperation, callback); -}; - -/** - * Creates an index on the db and collection. - * @method - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : {}; - - const createIndexOperation = new CreateIndexOperation(this, name, fieldOrSpec, options); - - return executeOperation(this.s.topology, createIndexOperation, callback); -}; - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated since version 2.0 - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, ensureIndex, [ - this, - name, - fieldOrSpec, - options, - callback - ]); -}, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0'); - -Db.prototype.addChild = function(db) { - if (this.s.parentDb) return this.s.parentDb.addChild(db); - this.s.children.push(db); -}; - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.addUser = function(username, password, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Special case where there is no password ($external users) - if (typeof username === 'string' && password != null && typeof password === 'object') { - options = password; - password = null; - } - - const addUserOperation = new AddUserOperation(this, username, password, options); - - return executeOperation(this.s.topology, addUserOperation, callback); -}; - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.removeUser = function(username, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const removeUserOperation = new RemoveUserOperation(this, username, options); - - return executeOperation(this.s.topology, removeUserOperation, callback); -}; - -/** - * Set the current profiling level of MongoDB - * - * @param {string} level The new profiling level (off, slow_only, all). - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.setProfilingLevel = function(level, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const setProfilingLevelOperation = new SetProfilingLevelOperation(this, level, options); - - return executeOperation(this.s.topology, setProfilingLevelOperation, callback); -}; - -/** - * Retrieve the current profiling information for MongoDB - * - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Query the system.profile collection directly. - */ -Db.prototype.profilingInfo = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, profilingInfo, [this, options, callback]); -}, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.'); - -/** - * Retrieve the current profiling Level for MongoDB - * - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.profilingLevel = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const profilingLevelOperation = new ProfilingLevelOperation(this, options); - - return executeOperation(this.s.topology, profilingLevelOperation, callback); -}; - -/** - * Retrieves this collections index info. - * @method - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.indexInformation = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexInformationOperation = new IndexInformationOperation(this, name, options); - - return executeOperation(this.s.topology, indexInformationOperation, callback); -}; - -/** - * Unref all sockets - * @method - */ -Db.prototype.unref = function() { - this.s.topology.unref(); -}; - -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections. - * @method - * @since 3.1.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -Db.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -Db.prototype.getLogger = function() { - return this.s.logger; -}; - -/** - * Db close event - * - * Emitted after a socket closed against a single server or mongos proxy. - * - * @event Db#close - * @type {MongoError} - */ - -/** - * Db reconnect event - * - * * Server: Emitted when the driver has reconnected and re-authenticated. - * * ReplicaSet: N/A - * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. - * - * @event Db#reconnect - * @type {object} - */ - -/** - * Db error event - * - * Emitted after an error occurred against a single server or mongos proxy. - * - * @event Db#error - * @type {MongoError} - */ - -/** - * Db timeout event - * - * Emitted after a socket timeout occurred against a single server or mongos proxy. - * - * @event Db#timeout - * @type {MongoError} - */ - -/** - * Db parseError event - * - * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. - * - * @event Db#parseError - * @type {MongoError} - */ - -/** - * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. - * - * * Server: Emitted when the driver has connected to the single server and has authenticated. - * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. - * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. - * - * @event Db#fullsetup - * @type {Db} - */ - -// Constants -Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; -Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; -Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; -Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; -Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; -Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; - -module.exports = Db; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/dynamic_loaders.js b/node_modules/mongoose/node_modules/mongodb/lib/dynamic_loaders.js deleted file mode 100644 index c461002..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/dynamic_loaders.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -let collection; -let cursor; -let db; - -function loadCollection() { - if (!collection) { - collection = require('./collection'); - } - return collection; -} - -function loadCursor() { - if (!cursor) { - cursor = require('./cursor'); - } - return cursor; -} - -function loadDb() { - if (!db) { - db = require('./db'); - } - return db; -} - -module.exports = { - loadCollection, - loadCursor, - loadDb -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/error.js b/node_modules/mongoose/node_modules/mongodb/lib/error.js deleted file mode 100644 index 4d104e9..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/error.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -const MongoNetworkError = require('./core').MongoNetworkError; -const mongoErrorContextSymbol = require('./core').mongoErrorContextSymbol; - -const GET_MORE_NON_RESUMABLE_CODES = new Set([ - 136, // CappedPositionLost - 237, // CursorKilled - 11601 // Interrupted -]); - -// From spec@https://github.com/mongodb/specifications/blob/7a2e93d85935ee4b1046a8d2ad3514c657dc74fa/source/change-streams/change-streams.rst#resumable-error: -// -// An error is considered resumable if it meets any of the following criteria: -// - any error encountered which is not a server error (e.g. a timeout error or network error) -// - any server error response from a getMore command excluding those containing the error label -// NonRetryableChangeStreamError and those containing the following error codes: -// - Interrupted: 11601 -// - CappedPositionLost: 136 -// - CursorKilled: 237 -// -// An error on an aggregate command is not a resumable error. Only errors on a getMore command may be considered resumable errors. - -function isGetMoreError(error) { - if (error[mongoErrorContextSymbol]) { - return error[mongoErrorContextSymbol].isGetMore; - } -} - -function isResumableError(error) { - if (!isGetMoreError(error)) { - return false; - } - - if (error instanceof MongoNetworkError) { - return true; - } - - return !( - GET_MORE_NON_RESUMABLE_CODES.has(error.code) || - error.hasErrorLabel('NonRetryableChangeStreamError') - ); -} - -module.exports = { GET_MORE_NON_RESUMABLE_CODES, isResumableError }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/download.js b/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/download.js deleted file mode 100644 index 2c060fd..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/download.js +++ /dev/null @@ -1,422 +0,0 @@ -'use strict'; - -var stream = require('stream'), - util = require('util'); - -module.exports = GridFSBucketReadStream; - -/** - * A readable stream that enables you to read buffers from GridFS. - * - * Do not instantiate this class directly. Use `openDownloadStream()` instead. - * - * @class - * @extends external:Readable - * @param {Collection} chunks Handle for chunks collection - * @param {Collection} files Handle for files collection - * @param {Object} readPreference The read preference to use - * @param {Object} filter The query to use to find the file document - * @param {Object} [options] Optional settings. - * @param {Number} [options.sort] Optional sort for the file find query - * @param {Number} [options.skip] Optional skip for the file find query - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @fires GridFSBucketReadStream#error - * @fires GridFSBucketReadStream#file - */ -function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { - this.s = { - bytesRead: 0, - chunks: chunks, - cursor: null, - expected: 0, - files: files, - filter: filter, - init: false, - expectedEnd: 0, - file: null, - options: options, - readPreference: readPreference - }; - - stream.Readable.call(this); -} - -util.inherits(GridFSBucketReadStream, stream.Readable); - -/** - * An error occurred - * - * @event GridFSBucketReadStream#error - * @type {Error} - */ - -/** - * Fires when the stream loaded the file document corresponding to the - * provided id. - * - * @event GridFSBucketReadStream#file - * @type {object} - */ - -/** - * Emitted when a chunk of data is available to be consumed. - * - * @event GridFSBucketReadStream#data - * @type {object} - */ - -/** - * Fired when the stream is exhausted (no more data events). - * - * @event GridFSBucketReadStream#end - * @type {object} - */ - -/** - * Fired when the stream is exhausted and the underlying cursor is killed - * - * @event GridFSBucketReadStream#close - * @type {object} - */ - -/** - * Reads from the cursor and pushes to the stream. - * Private Impl, do not call directly - * @ignore - * @method - */ - -GridFSBucketReadStream.prototype._read = function() { - var _this = this; - if (this.destroyed) { - return; - } - - waitForFile(_this, function() { - doRead(_this); - }); -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} start Offset in bytes to start reading at - * @return {GridFSBucketReadStream} Reference to Self - */ - -GridFSBucketReadStream.prototype.start = function(start) { - throwIfInitialized(this); - this.s.options.start = start; - return this; -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} end Offset in bytes to stop reading at - * @return {GridFSBucketReadStream} Reference to self - */ - -GridFSBucketReadStream.prototype.end = function(end) { - throwIfInitialized(this); - this.s.options.end = end; - return this; -}; - -/** - * Marks this stream as aborted (will never push another `data` event) - * and kills the underlying cursor. Will emit the 'end' event, and then - * the 'close' event once the cursor is successfully killed. - * - * @method - * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. - * @fires GridFSBucketWriteStream#close - * @fires GridFSBucketWriteStream#end - */ - -GridFSBucketReadStream.prototype.abort = function(callback) { - var _this = this; - this.push(null); - this.destroyed = true; - if (this.s.cursor) { - this.s.cursor.close(function(error) { - _this.emit('close'); - callback && callback(error); - }); - } else { - if (!this.s.init) { - // If not initialized, fire close event because we will never - // get a cursor - _this.emit('close'); - } - callback && callback(); - } -}; - -/** - * @ignore - */ - -function throwIfInitialized(self) { - if (self.s.init) { - throw new Error('You cannot change options after the stream has entered' + 'flowing mode!'); - } -} - -/** - * @ignore - */ - -function doRead(_this) { - if (_this.destroyed) { - return; - } - - _this.s.cursor.next(function(error, doc) { - if (_this.destroyed) { - return; - } - if (error) { - return __handleError(_this, error); - } - if (!doc) { - _this.push(null); - - process.nextTick(() => { - _this.s.cursor.close(function(error) { - if (error) { - __handleError(_this, error); - return; - } - - _this.emit('close'); - }); - }); - - return; - } - - var bytesRemaining = _this.s.file.length - _this.s.bytesRead; - var expectedN = _this.s.expected++; - var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining); - - if (doc.n > expectedN) { - var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - if (doc.n < expectedN) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; - - if (buf.length !== expectedLength) { - if (bytesRemaining <= 0) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; - return __handleError(_this, new Error(errmsg)); - } - - errmsg = - 'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength; - return __handleError(_this, new Error(errmsg)); - } - - _this.s.bytesRead += buf.length; - - if (buf.length === 0) { - return _this.push(null); - } - - var sliceStart = null; - var sliceEnd = null; - - if (_this.s.bytesToSkip != null) { - sliceStart = _this.s.bytesToSkip; - _this.s.bytesToSkip = 0; - } - - const atEndOfStream = expectedN === _this.s.expectedEnd - 1; - const bytesLeftToRead = _this.s.options.end - _this.s.bytesToSkip; - if (atEndOfStream && _this.s.bytesToTrim != null) { - sliceEnd = _this.s.file.chunkSize - _this.s.bytesToTrim; - } else if (_this.s.options.end && bytesLeftToRead < doc.data.length()) { - sliceEnd = bytesLeftToRead; - } - - if (sliceStart != null || sliceEnd != null) { - buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); - } - - _this.push(buf); - }); -} - -/** - * @ignore - */ - -function init(self) { - var findOneOptions = {}; - if (self.s.readPreference) { - findOneOptions.readPreference = self.s.readPreference; - } - if (self.s.options && self.s.options.sort) { - findOneOptions.sort = self.s.options.sort; - } - if (self.s.options && self.s.options.skip) { - findOneOptions.skip = self.s.options.skip; - } - - self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { - if (error) { - return __handleError(self, error); - } - if (!doc) { - var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename; - var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; - var err = new Error(errmsg); - err.code = 'ENOENT'; - return __handleError(self, err); - } - - // If document is empty, kill the stream immediately and don't - // execute any reads - if (doc.length <= 0) { - self.push(null); - return; - } - - if (self.destroyed) { - // If user destroys the stream before we have a cursor, wait - // until the query is done to say we're 'closed' because we can't - // cancel a query. - self.emit('close'); - return; - } - - self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); - - var filter = { files_id: doc._id }; - - // Currently (MongoDB 3.4.4) skip function does not support the index, - // it needs to retrieve all the documents first and then skip them. (CS-25811) - // As work around we use $gte on the "n" field. - if (self.s.options && self.s.options.start != null) { - var skip = Math.floor(self.s.options.start / doc.chunkSize); - if (skip > 0) { - filter['n'] = { $gte: skip }; - } - } - self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); - - if (self.s.readPreference) { - self.s.cursor.setReadPreference(self.s.readPreference); - } - - self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); - self.s.file = doc; - self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options); - self.emit('file', doc); - }); -} - -/** - * @ignore - */ - -function waitForFile(_this, callback) { - if (_this.s.file) { - return callback(); - } - - if (!_this.s.init) { - init(_this); - _this.s.init = true; - } - - _this.once('file', function() { - callback(); - }); -} - -/** - * @ignore - */ - -function handleStartOption(stream, doc, options) { - if (options && options.start != null) { - if (options.start > doc.length) { - throw new Error( - 'Stream start (' + - options.start + - ') must not be ' + - 'more than the length of the file (' + - doc.length + - ')' - ); - } - if (options.start < 0) { - throw new Error('Stream start (' + options.start + ') must not be ' + 'negative'); - } - if (options.end != null && options.end < options.start) { - throw new Error( - 'Stream start (' + - options.start + - ') must not be ' + - 'greater than stream end (' + - options.end + - ')' - ); - } - - stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; - stream.s.expected = Math.floor(options.start / doc.chunkSize); - - return options.start - stream.s.bytesRead; - } -} - -/** - * @ignore - */ - -function handleEndOption(stream, doc, cursor, options) { - if (options && options.end != null) { - if (options.end > doc.length) { - throw new Error( - 'Stream end (' + - options.end + - ') must not be ' + - 'more than the length of the file (' + - doc.length + - ')' - ); - } - if (options.start < 0) { - throw new Error('Stream end (' + options.end + ') must not be ' + 'negative'); - } - - var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; - - cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); - - stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); - - return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; - } -} - -/** - * @ignore - */ - -function __handleError(_this, error) { - _this.emit('error', error); -} diff --git a/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/index.js b/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/index.js deleted file mode 100644 index 6509839..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/index.js +++ /dev/null @@ -1,359 +0,0 @@ -'use strict'; - -var Emitter = require('events').EventEmitter; -var GridFSBucketReadStream = require('./download'); -var GridFSBucketWriteStream = require('./upload'); -var shallowClone = require('../utils').shallowClone; -var toError = require('../utils').toError; -var util = require('util'); -var executeLegacyOperation = require('../utils').executeLegacyOperation; - -var DEFAULT_GRIDFS_BUCKET_OPTIONS = { - bucketName: 'fs', - chunkSizeBytes: 255 * 1024 -}; - -module.exports = GridFSBucket; - -/** - * Constructor for a streaming GridFS interface - * @class - * @extends external:EventEmitter - * @param {Db} db A db handle - * @param {object} [options] Optional settings. - * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. - * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB - * @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }` - * @param {object} [options.readPreference] Optional read preference to be passed to read operations - * @fires GridFSBucketWriteStream#index - */ - -function GridFSBucket(db, options) { - Emitter.apply(this); - this.setMaxListeners(0); - - if (options && typeof options === 'object') { - options = shallowClone(options); - var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); - for (var i = 0; i < keys.length; ++i) { - if (!options[keys[i]]) { - options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; - } - } - } else { - options = DEFAULT_GRIDFS_BUCKET_OPTIONS; - } - - this.s = { - db: db, - options: options, - _chunksCollection: db.collection(options.bucketName + '.chunks'), - _filesCollection: db.collection(options.bucketName + '.files'), - checkedIndexes: false, - calledOpenUploadStream: false, - promiseLibrary: db.s.promiseLibrary || Promise - }; -} - -util.inherits(GridFSBucket, Emitter); - -/** - * When the first call to openUploadStream is made, the upload stream will - * check to see if it needs to create the proper indexes on the chunks and - * files collections. This event is fired either when 1) it determines that - * no index creation is necessary, 2) when it successfully creates the - * necessary indexes. - * - * @event GridFSBucket#index - * @type {Error} - */ - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStream = function(filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - return new GridFSBucketWriteStream(this, filename, options); -}; - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string|number|object} id A custom id used to identify the file - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - - options.id = id; - - return new GridFSBucketWriteStream(this, filename, options); -}; - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming file - * data from GridFS. - * @method - * @param {ObjectId} id The id of the file doc - * @param {Object} [options] Optional settings. - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStream = function(id, options) { - var filter = { _id: id }; - options = { - start: options && options.start, - end: options && options.end - }; - - return new GridFSBucketReadStream( - this.s._chunksCollection, - this.s._filesCollection, - this.s.options.readPreference, - filter, - options - ); -}; - -/** - * Deletes a file with the given id - * @method - * @param {ObjectId} id The id of the file doc - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.delete = function(id, callback) { - return executeLegacyOperation(this.s.db.s.topology, _delete, [this, id, callback], { - skipSessions: true - }); -}; - -/** - * @ignore - */ - -function _delete(_this, id, callback) { - _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { - if (error) { - return callback(error); - } - - _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { - if (error) { - return callback(error); - } - - // Delete orphaned chunks before returning FileNotFound - if (!res.result.n) { - var errmsg = 'FileNotFound: no file with id ' + id + ' found'; - return callback(new Error(errmsg)); - } - - callback(); - }); - }); -} - -/** - * Convenience wrapper around find on the files collection - * @method - * @param {Object} filter - * @param {Object} [options] Optional settings for cursor - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find|find command documentation}. - * @param {number} [options.limit] Optional limit for cursor - * @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor - * @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag - * @param {number} [options.skip] Optional skip for cursor - * @param {object} [options.sort] Optional sort for cursor - * @return {Cursor} - */ - -GridFSBucket.prototype.find = function(filter, options) { - filter = filter || {}; - options = options || {}; - - var cursor = this.s._filesCollection.find(filter); - - if (options.batchSize != null) { - cursor.batchSize(options.batchSize); - } - if (options.limit != null) { - cursor.limit(options.limit); - } - if (options.maxTimeMS != null) { - cursor.maxTimeMS(options.maxTimeMS); - } - if (options.noCursorTimeout != null) { - cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); - } - if (options.skip != null) { - cursor.skip(options.skip); - } - if (options.sort != null) { - cursor.sort(options.sort); - } - - return cursor; -}; - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming the - * file with the given name from GridFS. If there are multiple files with - * the same name, this will stream the most recent file with the given name - * (as determined by the `uploadDate` field). You can set the `revision` - * option to change this behavior. - * @method - * @param {String} filename The name of the file to stream - * @param {Object} [options] Optional settings - * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { - var sort = { uploadDate: -1 }; - var skip = null; - if (options && options.revision != null) { - if (options.revision >= 0) { - sort = { uploadDate: 1 }; - skip = options.revision; - } else { - skip = -options.revision - 1; - } - } - - var filter = { filename: filename }; - options = { - sort: sort, - skip: skip, - start: options && options.start, - end: options && options.end - }; - return new GridFSBucketReadStream( - this.s._chunksCollection, - this.s._filesCollection, - this.s.options.readPreference, - filter, - options - ); -}; - -/** - * Renames the file with the given _id to the given string - * @method - * @param {ObjectId} id the id of the file to rename - * @param {String} filename new name for the file - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.rename = function(id, filename, callback) { - return executeLegacyOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], { - skipSessions: true - }); -}; - -/** - * @ignore - */ - -function _rename(_this, id, filename, callback) { - var filter = { _id: id }; - var update = { $set: { filename: filename } }; - _this.s._filesCollection.updateOne(filter, update, function(error, res) { - if (error) { - return callback(error); - } - if (!res.result.n) { - return callback(toError('File with id ' + id + ' not found')); - } - callback(); - }); -} - -/** - * Removes this bucket's files collection, followed by its chunks collection. - * @method - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.drop = function(callback) { - return executeLegacyOperation(this.s.db.s.topology, _drop, [this, callback], { - skipSessions: true - }); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -GridFSBucket.prototype.getLogger = function() { - return this.s.db.s.logger; -}; - -/** - * @ignore - */ - -function _drop(_this, callback) { - _this.s._filesCollection.drop(function(error) { - if (error) { - return callback(error); - } - _this.s._chunksCollection.drop(function(error) { - if (error) { - return callback(error); - } - - return callback(); - }); - }); -} - -/** - * Callback format for all GridFSBucket methods that can accept a callback. - * @callback GridFSBucket~errorCallback - * @param {MongoError|undefined} error If present, an error instance representing any errors that occurred - * @param {*} result If present, a returned result for the method - */ diff --git a/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/upload.js b/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/upload.js deleted file mode 100644 index 578949a..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/gridfs-stream/upload.js +++ /dev/null @@ -1,538 +0,0 @@ -'use strict'; - -var core = require('../core'); -var crypto = require('crypto'); -var stream = require('stream'); -var util = require('util'); -var Buffer = require('safe-buffer').Buffer; - -var ERROR_NAMESPACE_NOT_FOUND = 26; - -module.exports = GridFSBucketWriteStream; - -/** - * A writable stream that enables you to write buffers to GridFS. - * - * Do not instantiate this class directly. Use `openUploadStream()` instead. - * - * @class - * @extends external:Writable - * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {string|number|object} [options.id] Custom file id for the GridFS file. - * @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes - * @param {number} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {number} [options.j] The journal write concern - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @fires GridFSBucketWriteStream#error - * @fires GridFSBucketWriteStream#finish - */ - -function GridFSBucketWriteStream(bucket, filename, options) { - options = options || {}; - this.bucket = bucket; - this.chunks = bucket.s._chunksCollection; - this.filename = filename; - this.files = bucket.s._filesCollection; - this.options = options; - // Signals the write is all done - this.done = false; - - this.id = options.id ? options.id : core.BSON.ObjectId(); - this.chunkSizeBytes = this.options.chunkSizeBytes; - this.bufToStore = Buffer.alloc(this.chunkSizeBytes); - this.length = 0; - this.md5 = !options.disableMD5 && crypto.createHash('md5'); - this.n = 0; - this.pos = 0; - this.state = { - streamEnd: false, - outstandingRequests: 0, - errored: false, - aborted: false, - promiseLibrary: this.bucket.s.promiseLibrary - }; - - if (!this.bucket.s.calledOpenUploadStream) { - this.bucket.s.calledOpenUploadStream = true; - - var _this = this; - checkIndexes(this, function() { - _this.bucket.s.checkedIndexes = true; - _this.bucket.emit('index'); - }); - } -} - -util.inherits(GridFSBucketWriteStream, stream.Writable); - -/** - * An error occurred - * - * @event GridFSBucketWriteStream#error - * @type {Error} - */ - -/** - * `end()` was called and the write stream successfully wrote the file - * metadata and all the chunks to MongoDB. - * - * @event GridFSBucketWriteStream#finish - * @type {object} - */ - -/** - * Write a buffer to the stream. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {GridFSBucket~errorCallback} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. - * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. - */ - -GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { - var _this = this; - return waitForIndexes(this, function() { - return doWrite(_this, chunk, encoding, callback); - }); -}; - -/** - * Places this write stream into an aborted state (all future writes fail) - * and deletes all chunks that have already been written. - * - * @method - * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred - * @return {Promise} if no callback specified - */ - -GridFSBucketWriteStream.prototype.abort = function(callback) { - if (this.state.streamEnd) { - var error = new Error('Cannot abort a stream that has already completed'); - if (typeof callback === 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - if (this.state.aborted) { - error = new Error('Cannot call abort() on a stream twice'); - if (typeof callback === 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - this.state.aborted = true; - this.chunks.deleteMany({ files_id: this.id }, function(error) { - if (typeof callback === 'function') callback(error); - }); -}; - -/** - * Tells the stream that no more data will be coming in. The stream will - * persist the remaining data to MongoDB, write the files document, and - * then emit a 'finish' event. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {GridFSBucket~errorCallback} callback Function to call when all files and chunks have been persisted to MongoDB - */ - -GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { - var _this = this; - if (typeof chunk === 'function') { - (callback = chunk), (chunk = null), (encoding = null); - } else if (typeof encoding === 'function') { - (callback = encoding), (encoding = null); - } - - if (checkAborted(this, callback)) { - return; - } - this.state.streamEnd = true; - - if (callback) { - this.once('finish', function(result) { - callback(null, result); - }); - } - - if (!chunk) { - waitForIndexes(this, function() { - writeRemnant(_this); - }); - return; - } - - this.write(chunk, encoding, function() { - writeRemnant(_this); - }); -}; - -/** - * @ignore - */ - -function __handleError(_this, error, callback) { - if (_this.state.errored) { - return; - } - _this.state.errored = true; - if (callback) { - return callback(error); - } - _this.emit('error', error); -} - -/** - * @ignore - */ - -function createChunkDoc(filesId, n, data) { - return { - _id: core.BSON.ObjectId(), - files_id: filesId, - n: n, - data: data - }; -} - -/** - * @ignore - */ - -function checkChunksIndex(_this, callback) { - _this.chunks.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === ERROR_NAMESPACE_NOT_FOUND) { - var index = { files_id: 1, n: 1 }; - _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - return; - } - return callback(error); - } - - var hasChunksIndex = false; - indexes.forEach(function(index) { - if (index.key) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { - hasChunksIndex = true; - } - } - }); - - if (hasChunksIndex) { - callback(); - } else { - index = { files_id: 1, n: 1 }; - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - indexOptions.unique = true; - - _this.chunks.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - } - }); -} - -/** - * @ignore - */ - -function checkDone(_this, callback) { - if (_this.done) return true; - if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) { - // Set done so we dont' trigger duplicate createFilesDoc - _this.done = true; - // Create a new files doc - var filesDoc = createFilesDoc( - _this.id, - _this.length, - _this.chunkSizeBytes, - _this.md5 && _this.md5.digest('hex'), - _this.filename, - _this.options.contentType, - _this.options.aliases, - _this.options.metadata - ); - - if (checkAborted(_this, callback)) { - return false; - } - - _this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error, callback); - } - _this.emit('finish', filesDoc); - }); - - return true; - } - - return false; -} - -/** - * @ignore - */ - -function checkIndexes(_this, callback) { - _this.files.findOne({}, { _id: 1 }, function(error, doc) { - if (error) { - return callback(error); - } - if (doc) { - return callback(); - } - - _this.files.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === ERROR_NAMESPACE_NOT_FOUND) { - var index = { filename: 1, uploadDate: 1 }; - _this.files.createIndex(index, { background: false }, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - return; - } - return callback(error); - } - - var hasFileIndex = false; - indexes.forEach(function(index) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { - hasFileIndex = true; - } - }); - - if (hasFileIndex) { - checkChunksIndex(_this, callback); - } else { - index = { filename: 1, uploadDate: 1 }; - - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - - _this.files.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - } - }); - }); -} - -/** - * @ignore - */ - -function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) { - var ret = { - _id: _id, - length: length, - chunkSize: chunkSize, - uploadDate: new Date(), - filename: filename - }; - - if (md5) { - ret.md5 = md5; - } - - if (contentType) { - ret.contentType = contentType; - } - - if (aliases) { - ret.aliases = aliases; - } - - if (metadata) { - ret.metadata = metadata; - } - - return ret; -} - -/** - * @ignore - */ - -function doWrite(_this, chunk, encoding, callback) { - if (checkAborted(_this, callback)) { - return false; - } - - var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); - - _this.length += inputBuf.length; - - // Input is small enough to fit in our buffer - if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { - inputBuf.copy(_this.bufToStore, _this.pos); - _this.pos += inputBuf.length; - - callback && callback(); - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // True means client can keep writing. - return true; - } - - // Otherwise, buffer is too big for current chunk, so we need to flush - // to MongoDB. - var inputBufRemaining = inputBuf.length; - var spaceRemaining = _this.chunkSizeBytes - _this.pos; - var numToCopy = Math.min(spaceRemaining, inputBuf.length); - var outstandingRequests = 0; - while (inputBufRemaining > 0) { - var inputBufPos = inputBuf.length - inputBufRemaining; - inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy); - _this.pos += numToCopy; - spaceRemaining -= numToCopy; - if (spaceRemaining === 0) { - if (_this.md5) { - _this.md5.update(_this.bufToStore); - } - var doc = createChunkDoc(_this.id, _this.n, Buffer.from(_this.bufToStore)); - ++_this.state.outstandingRequests; - ++outstandingRequests; - - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - --outstandingRequests; - - if (!outstandingRequests) { - _this.emit('drain', doc); - callback && callback(); - checkDone(_this); - } - }); - - spaceRemaining = _this.chunkSizeBytes; - _this.pos = 0; - ++_this.n; - } - inputBufRemaining -= numToCopy; - numToCopy = Math.min(spaceRemaining, inputBufRemaining); - } - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // False means the client should wait for the 'drain' event. - return false; -} - -/** - * @ignore - */ - -function getWriteOptions(_this) { - var obj = {}; - if (_this.options.writeConcern) { - obj.w = _this.options.writeConcern.w; - obj.wtimeout = _this.options.writeConcern.wtimeout; - obj.j = _this.options.writeConcern.j; - } - return obj; -} - -/** - * @ignore - */ - -function waitForIndexes(_this, callback) { - if (_this.bucket.s.checkedIndexes) { - return callback(false); - } - - _this.bucket.once('index', function() { - callback(true); - }); - - return true; -} - -/** - * @ignore - */ - -function writeRemnant(_this, callback) { - // Buffer is empty, so don't bother to insert - if (_this.pos === 0) { - return checkDone(_this, callback); - } - - ++_this.state.outstandingRequests; - - // Create a new buffer to make sure the buffer isn't bigger than it needs - // to be. - var remnant = Buffer.alloc(_this.pos); - _this.bufToStore.copy(remnant, 0, 0, _this.pos); - if (_this.md5) { - _this.md5.update(remnant); - } - var doc = createChunkDoc(_this.id, _this.n, remnant); - - // If the stream was aborted, do not write remnant - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - checkDone(_this); - }); -} - -/** - * @ignore - */ - -function checkAborted(_this, callback) { - if (_this.state.aborted) { - if (typeof callback === 'function') { - callback(new Error('this stream has been aborted')); - } - return true; - } - return false; -} diff --git a/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js b/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js deleted file mode 100644 index d276d72..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/gridfs/chunk.js +++ /dev/null @@ -1,236 +0,0 @@ -'use strict'; - -var Binary = require('../core').BSON.Binary, - ObjectID = require('../core').BSON.ObjectID; - -var Buffer = require('safe-buffer').Buffer; - -/** - * Class for representing a single chunk in GridFS. - * - * @class - * - * @param file {GridStore} The {@link GridStore} object holding this chunk. - * @param mongoObject {object} The mongo object representation of this chunk. - * - * @throws Error when the type of data field for {@link mongoObject} is not - * supported. Currently supported types for data field are instances of - * {@link String}, {@link Array}, {@link Binary} and {@link Binary} - * from the bson module - * - * @see Chunk#buildMongoObject - */ -var Chunk = function(file, mongoObject, writeConcern) { - if (!(this instanceof Chunk)) return new Chunk(file, mongoObject); - - this.file = file; - var mongoObjectFinal = mongoObject == null ? {} : mongoObject; - this.writeConcern = writeConcern || { w: 1 }; - this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; - this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; - this.data = new Binary(); - - if (typeof mongoObjectFinal.data === 'string') { - var buffer = Buffer.alloc(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); - this.data = new Binary(buffer); - } else if (Array.isArray(mongoObjectFinal.data)) { - buffer = Buffer.alloc(mongoObjectFinal.data.length); - var data = mongoObjectFinal.data.join(''); - buffer.write(data, 0, data.length, 'binary'); - this.data = new Binary(buffer); - } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { - this.data = mongoObjectFinal.data; - } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { - throw Error('Illegal chunk format'); - } - - // Update position - this.internalPosition = 0; -}; - -/** - * Writes a data to this object and advance the read/write head. - * - * @param data {string} the data to write - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.write = function(data, callback) { - this.data.write(data, this.internalPosition, data.length, 'binary'); - this.internalPosition = this.data.length(); - if (callback != null) return callback(null, this); - return this; -}; - -/** - * Reads data and advances the read/write head. - * - * @param length {number} The length of data to read. - * - * @return {string} The data read if the given length will not exceed the end of - * the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.read = function(length) { - // Default to full read if no index defined - length = length == null || length === 0 ? this.length() : length; - - if (this.length() - this.internalPosition + 1 >= length) { - var data = this.data.read(this.internalPosition, length); - this.internalPosition = this.internalPosition + length; - return data; - } else { - return ''; - } -}; - -Chunk.prototype.readSlice = function(length) { - if (this.length() - this.internalPosition >= length) { - var data = null; - if (this.data.buffer != null) { - //Pure BSON - data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); - } else { - //Native BSON - data = Buffer.alloc(length); - length = this.data.readInto(data, this.internalPosition); - } - this.internalPosition = this.internalPosition + length; - return data; - } else { - return null; - } -}; - -/** - * Checks if the read/write head is at the end. - * - * @return {boolean} Whether the read/write head has reached the end of this - * chunk. - */ -Chunk.prototype.eof = function() { - return this.internalPosition === this.length() ? true : false; -}; - -/** - * Reads one character from the data of this chunk and advances the read/write - * head. - * - * @return {string} a single character data read if the the read/write head is - * not at the end of the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.getc = function() { - return this.read(1); -}; - -/** - * Clears the contents of the data in this chunk and resets the read/write head - * to the initial position. - */ -Chunk.prototype.rewind = function() { - this.internalPosition = 0; - this.data = new Binary(); -}; - -/** - * Saves this chunk to the database. Also overwrites existing entries having the - * same id as this chunk. - * - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.save = function(options, callback) { - var self = this; - if (typeof options === 'function') { - callback = options; - options = {}; - } - - self.file.chunkCollection(function(err, collection) { - if (err) return callback(err); - - // Merge the options - var writeOptions = { upsert: true }; - for (var name in options) writeOptions[name] = options[name]; - for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; - - if (self.data.length() > 0) { - self.buildMongoObject(function(mongoObject) { - var options = { forceServerObjectId: true }; - for (var name in self.writeConcern) { - options[name] = self.writeConcern[name]; - } - - collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) { - callback(err, self); - }); - }); - } else { - callback(null, self); - } - // }); - }); -}; - -/** - * Creates a mongoDB object representation of this chunk. - * - * @param callback {function(Object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *

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

- *        {
- *          '_id' : , // {number} id for this file
- *          'filename' : , // {string} name for this file
- *          'contentType' : , // {string} mime type for this file
- *          'length' : , // {number} size of this file?
- *          'chunksize' : , // {number} chunk size used by this file
- *          'uploadDate' : , // {Date}
- *          'aliases' : , // {array of string}
- *          'metadata' : , // {string}
- *        }
- *        
- * - * @ignore - */ -var buildMongoObject = function(self, callback) { - // Calcuate the length - var mongoObject = { - _id: self.fileId, - filename: self.filename, - contentType: self.contentType, - length: self.position ? self.position : 0, - chunkSize: self.chunkSize, - uploadDate: self.uploadDate, - aliases: self.aliases, - metadata: self.metadata - }; - - var md5Command = { filemd5: self.fileId, root: self.root }; - self.db.command(md5Command, function(err, results) { - if (err) return callback(err); - - mongoObject.md5 = results.md5; - callback(null, mongoObject); - }); -}; - -/** - * Gets the nth chunk of this file. - * @ignore - */ -var nthChunk = function(self, chunkNumber, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - options.readPreference = self.readPreference; - // Get the nth chunk - self - .chunkCollection() - .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) { - if (err) return callback(err); - - var finalChunk = chunk == null ? {} : chunk; - callback(null, new Chunk(self, finalChunk, self.writeConcern)); - }); -}; - -/** - * @ignore - */ -var lastChunkNumber = function(self) { - return Math.floor((self.length ? self.length - 1 : 0) / self.chunkSize); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @ignore - */ -var deleteChunks = function(self, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - - if (self.fileId != null) { - self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) { - if (err) return callback(err, false); - callback(null, true); - }); - } else { - callback(null, true); - } -}; - -/** - * The collection to be used for holding the files and chunks collection. - * - * @classconstant DEFAULT_ROOT_COLLECTION - */ -GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; - -/** - * Default file mime type - * - * @classconstant DEFAULT_CONTENT_TYPE - */ -GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; - -/** - * Seek mode where the given length is absolute. - * - * @classconstant IO_SEEK_SET - */ -GridStore.IO_SEEK_SET = 0; - -/** - * Seek mode where the given length is an offset to the current read/write head. - * - * @classconstant IO_SEEK_CUR - */ -GridStore.IO_SEEK_CUR = 1; - -/** - * Seek mode where the given length is an offset to the end of the file. - * - * @classconstant IO_SEEK_END - */ -GridStore.IO_SEEK_END = 2; - -/** - * Checks if a file exists in the database. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file to look for. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - exists, - [db, fileIdObject, rootCollection, options, callback], - { skipSessions: true } - ); -}; - -var exists = function(db, fileIdObject, rootCollection, options, callback) { - // Establish read preference - var readPreference = options.readPreference || ReadPreference.PRIMARY; - // Fetch collection - var rootCollectionFinal = - rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - db.collection(rootCollectionFinal + '.files', function(err, collection) { - if (err) return callback(err); - - // Build query - var query = - typeof fileIdObject === 'string' || - Object.prototype.toString.call(fileIdObject) === '[object RegExp]' - ? { filename: fileIdObject } - : { _id: fileIdObject }; // Attempt to locate file - - // We have a specific query - if ( - fileIdObject != null && - typeof fileIdObject === 'object' && - Object.prototype.toString.call(fileIdObject) !== '[object RegExp]' - ) { - query = fileIdObject; - } - - // Check if the entry exists - collection.findOne(query, { readPreference: readPreference }, function(err, item) { - if (err) return callback(err); - callback(null, item == null ? false : true); - }); - }); -}; - -/** - * Gets the list of files stored in the GridFS. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.list = function(db, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation(db.s.topology, list, [db, rootCollection, options, callback], { - skipSessions: true - }); -}; - -var list = function(db, rootCollection, options, callback) { - // Ensure we have correct values - if (rootCollection != null && typeof rootCollection === 'object') { - options = rootCollection; - rootCollection = null; - } - - // Establish read preference - var readPreference = options.readPreference || ReadPreference.primary; - // Check if we are returning by id not filename - var byId = options['id'] != null ? options['id'] : false; - // Fetch item - var rootCollectionFinal = - rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - var items = []; - db.collection(rootCollectionFinal + '.files', function(err, collection) { - if (err) return callback(err); - - collection.find({}, { readPreference: readPreference }, function(err, cursor) { - if (err) return callback(err); - - cursor.each(function(err, item) { - if (item != null) { - items.push(byId ? item._id : item.filename); - } else { - callback(err, items); - } - }); - }); - }); -}; - -/** - * Reads the contents of a file. - * - * This method has the following signatures - * - * (db, name, callback) - * (db, name, length, callback) - * (db, name, length, offset, callback) - * (db, name, length, offset, options, callback) - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file. - * @param {number} [length] The size of data to read. - * @param {number} [offset] The offset from the head of the file of which to start reading from. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.read = function(db, name, length, offset, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - length = args.length ? args.shift() : null; - offset = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - readStatic, - [db, name, length, offset, options, callback], - { skipSessions: true } - ); -}; - -var readStatic = function(db, name, length, offset, options, callback) { - new GridStore(db, name, 'r', options).open(function(err, gridStore) { - if (err) return callback(err); - // Make sure we are not reading out of bounds - if (offset && offset >= gridStore.length) - return callback('offset larger than size of file', null); - if (length && length > gridStore.length) - return callback('length is larger than the size of the file', null); - if (offset && length && offset + length > gridStore.length) - return callback('offset and length is larger than the size of the file', null); - - if (offset != null) { - gridStore.seek(offset, function(err, gridStore) { - if (err) return callback(err); - gridStore.read(length, callback); - }); - } else { - gridStore.read(length, callback); - } - }); -}; - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {(String|object)} name the name of the file. - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.readlines = function(db, name, separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - separator = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - readlinesStatic, - [db, name, separator, options, callback], - { skipSessions: true } - ); -}; - -var readlinesStatic = function(db, name, separator, options, callback) { - var finalSeperator = separator == null ? '\n' : separator; - new GridStore(db, name, 'r', options).open(function(err, gridStore) { - if (err) return callback(err); - gridStore.readlines(finalSeperator, callback); - }); -}; - -/** - * Deletes the chunks and metadata information of a file from GridFS. - * - * @method - * @static - * @param {Db} db The database to query. - * @param {(string|array)} names The name/names of the files to delete. - * @param {object} [options] Optional settings. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.unlink = function(db, names, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation(db.s.topology, unlinkStatic, [this, db, names, options, callback], { - skipSessions: true - }); -}; - -var unlinkStatic = function(self, db, names, options, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(db, options); - - // List of names - if (names.constructor === Array) { - var tc = 0; - for (var i = 0; i < names.length; i++) { - ++tc; - GridStore.unlink(db, names[i], options, function() { - if (--tc === 0) { - callback(null, self); - } - }); - } - } else { - new GridStore(db, names, 'w', options).open(function(err, gridStore) { - if (err) return callback(err); - deleteChunks(gridStore, function(err) { - if (err) return callback(err); - gridStore.collection(function(err, collection) { - if (err) return callback(err); - collection.remove({ _id: gridStore.fileId }, writeConcern, function(err) { - callback(err, self); - }); - }); - }); - }); - } -}; - -/** - * @ignore - */ -var _writeNormal = function(self, data, close, options, callback) { - // If we have a buffer write it using the writeBuffer method - if (Buffer.isBuffer(data)) { - return writeBuffer(self, data, close, callback); - } else { - return writeBuffer(self, Buffer.from(data, 'binary'), close, callback); - } -}; - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if (options.w != null) finalOptions.w = options.w; - if (options.journal === true) finalOptions.j = options.journal; - if (options.j === true) finalOptions.j = options.j; - if (options.fsync === true) finalOptions.fsync = options.fsync; - if (options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -}; - -/** - * @ignore - */ -var _getWriteConcern = function(self, options) { - // Final options - var finalOptions = { w: 1 }; - options = options || {}; - - // Local options verification - if ( - options.w != null || - typeof options.j === 'boolean' || - typeof options.journal === 'boolean' || - typeof options.fsync === 'boolean' - ) { - finalOptions = _setWriteConcernHash(options); - } else if (options.safe != null && typeof options.safe === 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if (typeof options.safe === 'boolean') { - finalOptions = { w: options.safe ? 1 : 0 }; - } else if ( - self.options.w != null || - typeof self.options.j === 'boolean' || - typeof self.options.journal === 'boolean' || - typeof self.options.fsync === 'boolean' - ) { - finalOptions = _setWriteConcernHash(self.options); - } else if ( - self.safe && - (self.safe.w != null || - typeof self.safe.j === 'boolean' || - typeof self.safe.journal === 'boolean' || - typeof self.safe.fsync === 'boolean') - ) { - finalOptions = _setWriteConcernHash(self.safe); - } else if (typeof self.safe === 'boolean') { - finalOptions = { w: self.safe ? 1 : 0 }; - } - - // Ensure we don't have an invalid combination of write concerns - if ( - finalOptions.w < 1 && - (finalOptions.journal === true || finalOptions.j === true || finalOptions.fsync === true) - ) - throw MongoError.create({ - message: 'No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true', - driver: true - }); - - // Return the options - return finalOptions; -}; - -/** - * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @extends external:Duplex - * @return {GridStoreStream} a GridStoreStream instance. - * @deprecated Use GridFSBucket API instead - */ -var GridStoreStream = function(gs) { - // Initialize the duplex stream - Duplex.call(this); - - // Get the gridstore - this.gs = gs; - - // End called - this.endCalled = false; - - // If we have a seek - this.totalBytesToRead = this.gs.length - this.gs.position; - this.seekPosition = this.gs.position; -}; - -// -// Inherit duplex -inherits(GridStoreStream, Duplex); - -GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; - -// Set up override -GridStoreStream.prototype.pipe = function(destination) { - var self = this; - - // Only open gridstore if not already open - if (!self.gs.isOpen) { - self.gs.open(function(err) { - if (err) return self.emit('error', err); - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - }); - } else { - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - } - - return destination; -}; - -// Called by stream -GridStoreStream.prototype._read = function() { - var self = this; - - var read = function() { - // Read data - self.gs.read(length, function(err, buffer) { - if (err && !self.endCalled) return self.emit('error', err); - - // Stream is closed - if (self.endCalled || buffer == null) return self.push(null); - // Remove bytes read - if (buffer.length <= self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer.length; - self.push(buffer); - } else if (buffer.length > self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer._index; - self.push(buffer.slice(0, buffer._index)); - } - - // Finished reading - if (self.totalBytesToRead <= 0) { - self.endCalled = true; - } - }); - }; - - // Set read length - var length = - self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; - if (!self.gs.isOpen) { - self.gs.open(function(err) { - self.totalBytesToRead = self.gs.length - self.gs.position; - if (err) return self.emit('error', err); - read(); - }); - } else { - read(); - } -}; - -GridStoreStream.prototype.destroy = function() { - this.pause(); - this.endCalled = true; - this.gs.close(); - this.emit('end'); -}; - -GridStoreStream.prototype.write = function(chunk) { - var self = this; - if (self.endCalled) - return self.emit( - 'error', - MongoError.create({ message: 'attempting to write to stream after end called', driver: true }) - ); - // Do we have to open the gridstore - if (!self.gs.isOpen) { - self.gs.open(function() { - self.gs.isOpen = true; - self.gs.write(chunk, function() { - process.nextTick(function() { - self.emit('drain'); - }); - }); - }); - return false; - } else { - self.gs.write(chunk, function() { - self.emit('drain'); - }); - return true; - } -}; - -GridStoreStream.prototype.end = function(chunk, encoding, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - chunk = args.length ? args.shift() : null; - encoding = args.length ? args.shift() : null; - self.endCalled = true; - - if (chunk) { - self.gs.write(chunk, function() { - self.gs.close(function() { - if (typeof callback === 'function') callback(); - self.emit('end'); - }); - }); - } - - self.gs.close(function() { - if (typeof callback === 'function') callback(); - self.emit('end'); - }); -}; - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Duplex#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Duplex#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Duplex#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Duplex#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Duplex#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Duplex#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Duplex#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Duplex#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -/** - * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. - * @function external:Duplex#write - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {boolean} - */ - -/** - * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. - * @function external:Duplex#end - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {null} - */ - -/** - * GridStoreStream stream data event, fired for each document in the cursor. - * - * @event GridStoreStream#data - * @type {object} - */ - -/** - * GridStoreStream stream end event - * - * @event GridStoreStream#end - * @type {null} - */ - -/** - * GridStoreStream stream close event - * - * @event GridStoreStream#close - * @type {null} - */ - -/** - * GridStoreStream stream readable event - * - * @event GridStoreStream#readable - * @type {null} - */ - -/** - * GridStoreStream stream drain event - * - * @event GridStoreStream#drain - * @type {null} - */ - -/** - * GridStoreStream stream finish event - * - * @event GridStoreStream#finish - * @type {null} - */ - -/** - * GridStoreStream stream pipe event - * - * @event GridStoreStream#pipe - * @type {null} - */ - -/** - * GridStoreStream stream unpipe event - * - * @event GridStoreStream#unpipe - * @type {null} - */ - -/** - * GridStoreStream stream error event - * - * @event GridStoreStream#error - * @type {null} - */ - -/** - * @ignore - */ -module.exports = GridStore; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js b/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js deleted file mode 100644 index db19e70..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/mongo_client.js +++ /dev/null @@ -1,532 +0,0 @@ -'use strict'; - -const ChangeStream = require('./change_stream'); -const Db = require('./db'); -const EventEmitter = require('events').EventEmitter; -const inherits = require('util').inherits; -const MongoError = require('./core').MongoError; -const deprecate = require('util').deprecate; -const WriteConcern = require('./write_concern'); -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const ReadPreference = require('./core/topologies/read_preference'); -const maybePromise = require('./utils').maybePromise; -const NativeTopology = require('./topologies/native_topology'); -const connect = require('./operations/connect').connect; -const validOptions = require('./operations/connect').validOptions; - -/** - * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. - * - * @example - * // Connect using a MongoClient instance - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * const mongoClient = new MongoClient(url); - * mongoClient.connect(function(err, client) { - * const db = client.db(dbName); - * client.close(); - * }); - * - * @example - * // Connect using the MongoClient.connect static method - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * const db = client.db(dbName); - * client.close(); - * }); - */ - -/** - * A string specifying the level of a ReadConcern - * @typedef {'local'|'available'|'majority'|'linearizable'|'snapshot'} ReadConcernLevel - * @see https://docs.mongodb.com/manual/reference/read-concern/index.html#read-concern-levels - */ - -/** - * Configuration options for drivers wrapping the node driver. - * - * @typedef {Object} DriverInfoOptions - * @property {string} [name] The name of the driver - * @property {string} [version] The version of the driver - * @property {string} [platform] Optional platform information - */ - -/** - * Configuration options for drivers wrapping the node driver. - * - * @typedef {Object} DriverInfoOptions - * @property {string} [name] The name of the driver - * @property {string} [version] The version of the driver - * @property {string} [platform] Optional platform information - */ - -/** - * Creates a new MongoClient instance - * @class - * @param {string} url The connection URI string - * @param {object} [options] Optional settings - * @param {number} [options.poolSize=5] The maximum size of the individual server pool - * @param {boolean} [options.ssl=false] Enable SSL connection. *deprecated* use `tls` variants - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority - * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer *deprecated* use `tls` variants - * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer *deprecated* use `tls` variants - * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer *deprecated* use `tls` variants - * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase *deprecated* use `tls` variants - * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer *deprecated* use `tls` variants - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. *deprecated* use `tls` variants - * @param {boolean} [options.tls=false] Enable TLS connections - * @param {boolean} [options.tlsInsecure=false] Relax TLS constraints, disabling validation - * @param {string} [options.tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection - * @param {string} [options.tlsCertificateKeyFile] A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated - * @param {string} [options.tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections - * @param {boolean} [options.tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid - * @param {boolean} [options.tlsAllowInvalidHostnames] Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate - * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out - * @param {number} [options.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out - * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). - * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {string} [options.replicaSet=undefined] The Replicaset set name - * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {string} [options.authSource=undefined] Define the database to authenticate against - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j=false] Specify a journal write concern - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) - * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) - * @param {object} [options.logger=undefined] Custom logger object - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers - * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit - * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness - * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections - * @param {string} [options.auth.user=undefined] The username for auth - * @param {string} [options.auth.password=undefined] The password for auth - * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 - * @param {object} [options.compression] Type of compression to use: snappy or zlib - * @param {boolean} [options.fsync=false] Specify a file sync write concern - * @param {array} [options.readPreferenceTags] Read preference tags - * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor - * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client - * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections - * @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser. - * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer - * @param {Number} [options.localThresholdMS=15] **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers - * @param {Number} [options.serverSelectionTimeoutMS=30000] **Only applies to the unified topology** How long to block for server selection before throwing an error - * @param {Number} [options.heartbeatFrequencyMS=10000] **Only applies to the unified topology** The frequency with which topology updates are scheduled - * @param {AutoEncrypter~AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption - * @param {DriverInfoOptions} [options.driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {MongoClient} a MongoClient instance - */ -function MongoClient(url, options) { - if (!(this instanceof MongoClient)) return new MongoClient(url, options); - // Set up event emitter - EventEmitter.call(this); - - // The internal state - this.s = { - url: url, - options: options || {}, - promiseLibrary: (options && options.promiseLibrary) || Promise, - dbCache: new Map(), - sessions: new Set(), - writeConcern: WriteConcern.fromOptions(options), - namespace: new MongoDBNamespace('admin') - }; -} - -/** - * @ignore - */ -inherits(MongoClient, EventEmitter); - -Object.defineProperty(MongoClient.prototype, 'writeConcern', { - enumerable: true, - get: function() { - return this.s.writeConcern; - } -}); - -Object.defineProperty(MongoClient.prototype, 'readPreference', { - enumerable: true, - get: function() { - return ReadPreference.primary; - } -}); - -/** - * The callback format for results - * @callback MongoClient~connectCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {MongoClient} client The connected client. - */ - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.prototype.connect = function(callback) { - if (typeof callback === 'string') { - throw new TypeError('`connect` only accepts a callback'); - } - - const client = this; - return maybePromise(this, callback, cb => { - const err = validOptions(client.s.options); - if (err) return cb(err); - - connect(client, client.s.url, client.s.options, err => { - if (err) return cb(err); - cb(null, client); - }); - }); -}; - -MongoClient.prototype.logout = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - if (typeof callback === 'function') callback(null, true); -}, 'Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient'); - -/** - * Close the db and its underlying connections - * @method - * @param {boolean} [force=false] Force close, emitting no events - * @param {Db~noResultCallback} [callback] The result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.prototype.close = function(force, callback) { - if (typeof force === 'function') { - callback = force; - force = false; - } - - const client = this; - return maybePromise(this, callback, cb => { - const completeClose = err => { - client.emit('close', client); - - if (!(client.topology instanceof NativeTopology)) { - for (const item of client.s.dbCache) { - item[1].emit('close', client); - } - } - - client.removeAllListeners('close'); - cb(err); - }; - - if (client.topology == null) { - completeClose(); - return; - } - - client.topology.close(force, err => { - const autoEncrypter = client.topology.s.options.autoEncrypter; - if (!autoEncrypter) { - completeClose(err); - return; - } - - autoEncrypter.teardown(force, err2 => completeClose(err || err2)); - }); - }); -}; - -/** - * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are - * related in a parent-child relationship to the original instance so that events are correctly emitted on child - * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. - * You can control these behaviors with the options noListener and returnNonCachedInstance. - * - * @method - * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string. - * @param {object} [options] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {Db} - */ -MongoClient.prototype.db = function(dbName, options) { - options = options || {}; - - // Default to db from connection string if not provided - if (!dbName) { - dbName = this.s.options.dbName; - } - - // Copy the options and add out internal override of the not shared flag - const finalOptions = Object.assign({}, this.s.options, options); - - // Do we have the db in the cache already - if (this.s.dbCache.has(dbName) && finalOptions.returnNonCachedInstance !== true) { - return this.s.dbCache.get(dbName); - } - - // Add promiseLibrary - finalOptions.promiseLibrary = this.s.promiseLibrary; - - // If no topology throw an error message - if (!this.topology) { - throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'); - } - - // Return the db object - const db = new Db(dbName, this.topology, finalOptions); - - // Add the db to the cache - this.s.dbCache.set(dbName, db); - // Return the database - return db; -}; - -/** - * Check if MongoClient is connected - * - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {boolean} - */ -MongoClient.prototype.isConnected = function(options) { - options = options || {}; - - if (!this.topology) return false; - return this.topology.isConnected(options); -}; - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @static - * @param {string} url The connection URI string - * @param {object} [options] Optional settings - * @param {number} [options.poolSize=5] The maximum size of the individual server pool - * @param {boolean} [options.ssl=false] Enable SSL connection. *deprecated* use `tls` variants - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority - * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer *deprecated* use `tls` variants - * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer *deprecated* use `tls` variants - * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer *deprecated* use `tls` variants - * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase *deprecated* use `tls` variants - * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer *deprecated* use `tls` variants - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. *deprecated* use `tls` variants - * @param {boolean} [options.tls=false] Enable TLS connections - * @param {boolean} [options.tlsInsecure=false] Relax TLS constraints, disabling validation - * @param {string} [options.tlsCAFile] A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection - * @param {string} [options.tlsCertificateKeyFile] A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated - * @param {string} [options.tlsCertificateKeyFilePassword] The password to decrypt the client private key to be used for TLS connections - * @param {boolean} [options.tlsAllowInvalidCertificates] Specifies whether or not the driver should error when the server’s TLS certificate is invalid - * @param {boolean} [options.tlsAllowInvalidHostnames] Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate - * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out - * @param {number} [options.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out - * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). - * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {string} [options.replicaSet=undefined] The Replicaset set name - * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {string} [options.authSource=undefined] Define the database to authenticate against - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j=false] Specify a journal write concern - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) - * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) - * @param {object} [options.logger=undefined] Custom logger object - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers - * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit - * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness - * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections - * @param {string} [options.auth.user=undefined] The username for auth - * @param {string} [options.auth.password=undefined] The password for auth - * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 - * @param {object} [options.compression] Type of compression to use: snappy or zlib - * @param {boolean} [options.fsync=false] Specify a file sync write concern - * @param {array} [options.readPreferenceTags] Read preference tags - * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor - * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client - * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections - * @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser. - * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer - * @param {Number} [options.localThresholdMS=15] **Only applies to the unified topology** The size of the latency window for selecting among multiple suitable servers - * @param {Number} [options.serverSelectionTimeoutMS=30000] **Only applies to the unified topology** How long to block for server selection before throwing an error - * @param {Number} [options.heartbeatFrequencyMS=10000] **Only applies to the unified topology** The frequency with which topology updates are scheduled - * @param {AutoEncrypter~AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption - * @param {DriverInfoOptions} [options.driverInfo] Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.connect = function(url, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : null; - options = options || {}; - - // Create client - const mongoClient = new MongoClient(url, options); - // Execute the connect method - return mongoClient.connect(callback); -}; - -/** - * Starts a new session on the server - * - * @param {SessionOptions} [options] optional settings for a driver session - * @return {ClientSession} the newly established session - */ -MongoClient.prototype.startSession = function(options) { - options = Object.assign({ explicit: true }, options); - if (!this.topology) { - throw new MongoError('Must connect to a server before calling this method'); - } - - if (!this.topology.hasSessionSupport()) { - throw new MongoError('Current topology does not support sessions'); - } - - return this.topology.startSession(options, this.s.options); -}; - -/** - * Runs a given operation with an implicitly created session. The lifetime of the session - * will be handled without the need for user interaction. - * - * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function) - * - * @param {Object} [options] Optional settings to be appled to implicitly created session - * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}` - * @return {Promise} - */ -MongoClient.prototype.withSession = function(options, operation) { - if (typeof options === 'function') (operation = options), (options = undefined); - const session = this.startSession(options); - - let cleanupHandler = (err, result, opts) => { - // prevent multiple calls to cleanupHandler - cleanupHandler = () => { - throw new ReferenceError('cleanupHandler was called too many times'); - }; - - opts = Object.assign({ throw: true }, opts); - session.endSession(); - - if (err) { - if (opts.throw) throw err; - return Promise.reject(err); - } - }; - - try { - const result = operation(session); - return Promise.resolve(result) - .then(result => cleanupHandler(null, result)) - .catch(err => cleanupHandler(err, null, { throw: true })); - } catch (err) { - return cleanupHandler(err, null, { throw: false }); - } -}; -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin, - * and config databases. - * @method - * @since 3.1.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -MongoClient.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * Return the mongo client logger - * @method - * @return {Logger} return the mongo client logger - * @ignore - */ -MongoClient.prototype.getLogger = function() { - return this.s.options.logger; -}; - -module.exports = MongoClient; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/add_user.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/add_user.js deleted file mode 100644 index 1f3f3a6..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/add_user.js +++ /dev/null @@ -1,96 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const crypto = require('crypto'); -const handleCallback = require('../utils').handleCallback; -const toError = require('../utils').toError; - -class AddUserOperation extends CommandOperation { - constructor(db, username, password, options) { - super(db, options); - - this.username = username; - this.password = password; - } - - _buildCommand() { - const db = this.db; - const username = this.username; - const password = this.password; - const options = this.options; - - // Get additional values - let roles = Array.isArray(options.roles) ? options.roles : []; - - // If not roles defined print deprecated message - // TODO: handle deprecation properly - if (roles.length === 0) { - console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); - } - - // Check the db name and add roles if needed - if ( - (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && - !Array.isArray(options.roles) - ) { - roles = ['root']; - } else if (!Array.isArray(options.roles)) { - roles = ['dbOwner']; - } - - const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; - - let userPassword = password; - - if (!digestPassword) { - // Use node md5 generator - const md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password); - userPassword = md5.digest('hex'); - } - - // Build the command to execute - const command = { - createUser: username, - customData: options.customData || {}, - roles: roles, - digestPassword - }; - - // No password - if (typeof password === 'string') { - command.pwd = userPassword; - } - - return command; - } - - execute(callback) { - const options = this.options; - - // Error out if digestPassword set - if (options.digestPassword != null) { - return callback( - toError( - "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." - ) - ); - } - - // Attempt to execute auth command - super.execute((err, r) => { - if (!err) { - return handleCallback(callback, err, r); - } - - return handleCallback(callback, err, null); - }); - } -} - -defineAspects(AddUserOperation, Aspect.WRITE_OPERATION); - -module.exports = AddUserOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/admin_ops.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/admin_ops.js deleted file mode 100644 index b08071c..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/admin_ops.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; - -const executeCommand = require('./db_ops').executeCommand; -const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; - -/** - * Get ReplicaSet status - * - * @param {Admin} a collection instance. - * @param {Object} [options] Optional settings. See Admin.prototype.replSetGetStatus for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback. - */ -function replSetGetStatus(admin, options, callback) { - executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback); -} - -/** - * Retrieve this db's server status. - * - * @param {Admin} a collection instance. - * @param {Object} [options] Optional settings. See Admin.prototype.serverStatus for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback - */ -function serverStatus(admin, options, callback) { - executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback); -} - -/** - * Validate an existing collection - * - * @param {Admin} a collection instance. - * @param {string} collectionName The name of the collection to validate. - * @param {Object} [options] Optional settings. See Admin.prototype.validateCollection for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback. - */ -function validateCollection(admin, collectionName, options, callback) { - const command = { validate: collectionName }; - const keys = Object.keys(options); - - // Decorate command with extra options - for (let i = 0; i < keys.length; i++) { - if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { - command[keys[i]] = options[keys[i]]; - } - } - - executeCommand(admin.s.db, command, options, (err, doc) => { - if (err != null) return callback(err, null); - - if (doc.ok === 0) return callback(new Error('Error with validate command'), null); - if (doc.result != null && doc.result.constructor !== String) - return callback(new Error('Error with validation data'), null); - if (doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error('Error: invalid collection ' + collectionName), null); - if (doc.valid != null && !doc.valid) - return callback(new Error('Error: invalid collection ' + collectionName), null); - - return callback(null, doc); - }); -} - -module.exports = { replSetGetStatus, serverStatus, validateCollection }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/aggregate.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/aggregate.js deleted file mode 100644 index e0f2da8..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/aggregate.js +++ /dev/null @@ -1,106 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const MongoError = require('../core').MongoError; -const maxWireVersion = require('../core/utils').maxWireVersion; -const ReadPreference = require('../core').ReadPreference; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; - -const DB_AGGREGATE_COLLECTION = 1; -const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8; - -class AggregateOperation extends CommandOperationV2 { - constructor(parent, pipeline, options) { - super(parent, options, { fullResponse: true }); - - this.target = - parent.s.namespace && parent.s.namespace.collection - ? parent.s.namespace.collection - : DB_AGGREGATE_COLLECTION; - - this.pipeline = pipeline; - - // determine if we have a write stage, override read preference if so - this.hasWriteStage = false; - if (typeof options.out === 'string') { - this.pipeline = this.pipeline.concat({ $out: options.out }); - this.hasWriteStage = true; - } else if (pipeline.length > 0) { - const finalStage = pipeline[pipeline.length - 1]; - if (finalStage.$out || finalStage.$merge) { - this.hasWriteStage = true; - } - } - - if (this.hasWriteStage) { - this.readPreference = ReadPreference.primary; - } - - if (options.explain && (this.readConcern || this.writeConcern)) { - throw new MongoError( - '"explain" cannot be used on an aggregate call with readConcern/writeConcern' - ); - } - - if (options.cursor != null && typeof options.cursor !== 'object') { - throw new MongoError('cursor options must be an object'); - } - } - - get canRetryRead() { - return !this.hasWriteStage; - } - - addToPipeline(stage) { - this.pipeline.push(stage); - } - - execute(server, callback) { - const options = this.options; - const serverWireVersion = maxWireVersion(server); - const command = { aggregate: this.target, pipeline: this.pipeline }; - - if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { - this.readConcern = null; - } - - if (serverWireVersion >= 5) { - if (this.hasWriteStage && this.writeConcern) { - Object.assign(command, { writeConcern: this.writeConcern }); - } - } - - if (options.bypassDocumentValidation === true) { - command.bypassDocumentValidation = options.bypassDocumentValidation; - } - - if (typeof options.allowDiskUse === 'boolean') { - command.allowDiskUse = options.allowDiskUse; - } - - if (options.hint) { - command.hint = options.hint; - } - - if (options.explain) { - options.full = false; - command.explain = options.explain; - } - - command.cursor = options.cursor || {}; - if (options.batchSize && !this.hasWriteStage) { - command.cursor.batchSize = options.batchSize; - } - - super.executeCommand(server, command, callback); - } -} - -defineAspects(AggregateOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = AggregateOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/bulk_write.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/bulk_write.js deleted file mode 100644 index 8f14f02..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/bulk_write.js +++ /dev/null @@ -1,104 +0,0 @@ -'use strict'; - -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const MongoError = require('../core').MongoError; -const OperationBase = require('./operation').OperationBase; - -class BulkWriteOperation extends OperationBase { - constructor(collection, operations, options) { - super(options); - - this.collection = collection; - this.operations = operations; - } - - execute(callback) { - const coll = this.collection; - const operations = this.operations; - let options = this.options; - - // Add ignoreUndfined - if (coll.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = coll.s.options.ignoreUndefined; - } - - // Create the bulk operation - const bulk = - options.ordered === true || options.ordered == null - ? coll.initializeOrderedBulkOp(options) - : coll.initializeUnorderedBulkOp(options); - - // Do we have a collation - let collation = false; - - // for each op go through and add to the bulk - try { - for (let i = 0; i < operations.length; i++) { - // Get the operation type - const key = Object.keys(operations[i])[0]; - // Check if we have a collation - if (operations[i][key].collation) { - collation = true; - } - - // Pass to the raw bulk - bulk.raw(operations[i]); - } - } catch (err) { - return callback(err, null); - } - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; - const capabilities = coll.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - // Execute the bulk - bulk.execute(writeCon, finalOptions, (err, r) => { - // We have connection level error - if (!r && err) { - return callback(err, null); - } - - r.insertedCount = r.nInserted; - r.matchedCount = r.nMatched; - r.modifiedCount = r.nModified || 0; - r.deletedCount = r.nRemoved; - r.upsertedCount = r.getUpsertedIds().length; - r.upsertedIds = {}; - r.insertedIds = {}; - - // Update the n - r.n = r.insertedCount; - - // Inserted documents - const inserted = r.getInsertedIds(); - // Map inserted ids - for (let i = 0; i < inserted.length; i++) { - r.insertedIds[inserted[i].index] = inserted[i]._id; - } - - // Upserted documents - const upserted = r.getUpsertedIds(); - // Map upserted ids - for (let i = 0; i < upserted.length; i++) { - r.upsertedIds[upserted[i].index] = upserted[i]._id; - } - - // Return the results - callback(null, r); - }); - } -} - -module.exports = BulkWriteOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/collection_ops.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/collection_ops.js deleted file mode 100644 index df5995d..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/collection_ops.js +++ /dev/null @@ -1,374 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const createIndexDb = require('./db_ops').createIndex; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const ensureIndexDb = require('./db_ops').ensureIndex; -const evaluate = require('./db_ops').evaluate; -const executeCommand = require('./db_ops').executeCommand; -const resolveReadPreference = require('../utils').resolveReadPreference; -const handleCallback = require('../utils').handleCallback; -const indexInformationDb = require('./db_ops').indexInformation; -const Long = require('../core').BSON.Long; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const insertDocuments = require('./common_functions').insertDocuments; -const updateDocuments = require('./common_functions').updateDocuments; - -/** - * Group function helper - * @ignore - */ -// var groupFunction = function () { -// var c = db[ns].find(condition); -// var map = new Map(); -// var reduce_function = reduce; -// -// while (c.hasNext()) { -// var obj = c.next(); -// var key = {}; -// -// for (var i = 0, len = keys.length; i < len; ++i) { -// var k = keys[i]; -// key[k] = obj[k]; -// } -// -// var aggObj = map.get(key); -// -// if (aggObj == null) { -// var newObj = Object.extend({}, key); -// aggObj = Object.extend(newObj, initial); -// map.put(key, aggObj); -// } -// -// reduce_function(obj, aggObj); -// } -// -// return { "result": map.values() }; -// }.toString(); -const groupFunction = - 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; - -// Check the update operation to ensure it has atomic operators. -function checkForAtomicOperators(update) { - if (Array.isArray(update)) { - return update.reduce((err, u) => err || checkForAtomicOperators(u), null); - } - - const keys = Object.keys(update); - - // same errors as the server would give for update doc lacking atomic operators - if (keys.length === 0) { - return toError('The update operation document must contain at least one atomic operator.'); - } - - if (keys[0][0] !== '$') { - return toError('the update operation document must contain atomic operators.'); - } -} - -/** - * Create an index on the db and collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function createIndex(coll, fieldOrSpec, options, callback) { - createIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); -} - -/** - * Create multiple indexes in the collection. This method is only supported for - * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported - * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. - * - * @method - * @param {Collection} a Collection instance. - * @param {array} indexSpecs An array of index specifications to be created - * @param {Object} [options] Optional settings. See Collection.prototype.createIndexes for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function createIndexes(coll, indexSpecs, options, callback) { - const capabilities = coll.s.topology.capabilities(); - - // Ensure we generate the correct name if the parameter is not set - for (let i = 0; i < indexSpecs.length; i++) { - if (indexSpecs[i].name == null) { - const keys = []; - - // Did the user pass in a collation, check if our write server supports it - if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - for (let name in indexSpecs[i].key) { - keys.push(`${name}_${indexSpecs[i].key[name]}`); - } - - // Set the name - indexSpecs[i].name = keys.join('_'); - } - } - - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Execute the index - executeCommand( - coll.s.db, - { - createIndexes: coll.collectionName, - indexes: indexSpecs - }, - options, - callback - ); -} - -/** - * Ensure that an index exists. If the index does not exist, this function creates it. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function ensureIndex(coll, fieldOrSpec, options, callback) { - ensureIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); -} - -/** - * Run a group command across a collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. - * @param {object} condition An optional condition that must be true for a row to be considered. - * @param {object} initial Initial value of the aggregation counter object. - * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated - * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. - * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. - * @param {object} [options] Optional settings. See Collection.prototype.group for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework. - */ -function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) { - // Execute using the command - if (command) { - const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); - - const selector = { - group: { - ns: coll.collectionName, - $reduce: reduceFunction, - cond: condition, - initial: initial, - out: 'inline' - } - }; - - // if finalize is defined - if (finalize != null) selector.group['finalize'] = finalize; - // Set up group selector - if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) { - selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); - } else { - const hash = {}; - keys.forEach(key => { - hash[key] = 1; - }); - selector.group.key = hash; - } - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(coll, options); - - // Do we have a readConcern specified - decorateWithReadConcern(selector, coll, options); - - // Have we specified collation - try { - decorateWithCollation(selector, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute command - executeCommand(coll.s.db, selector, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.retval); - }); - } else { - // Create execution scope - const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; - - scope.ns = coll.collectionName; - scope.keys = keys; - scope.condition = condition; - scope.initial = initial; - - // Pass in the function text to execute within mongodb. - const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); - - evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, results.result || results); - }); - } -} - -/** - * Retrieve all the indexes on the collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexes(coll, options, callback) { - options = Object.assign({}, { full: true }, options); - indexInformationDb(coll.s.db, coll.collectionName, options, callback); -} - -/** - * Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|array)} indexes One or more index names to check. - * @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexExists(coll, indexes, options, callback) { - indexInformation(coll, options, (err, indexInformation) => { - // If we have an error return - if (err != null) return handleCallback(callback, err, null); - // Let's check for the index names - if (!Array.isArray(indexes)) - return handleCallback(callback, null, indexInformation[indexes] != null); - // Check in list of indexes - for (let i = 0; i < indexes.length; i++) { - if (indexInformation[indexes[i]] == null) { - return handleCallback(callback, null, false); - } - } - - // All keys found return true - return handleCallback(callback, null, true); - }); -} - -/** - * Retrieve this collection's index info. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexInformation(coll, options, callback) { - indexInformationDb(coll.s.db, coll.collectionName, options, callback); -} - -/** - * Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are - * no ordering guarantees for returned results. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - */ -function parallelCollectionScan(coll, options, callback) { - // Create command object - const commandObject = { - parallelCollectionScan: coll.collectionName, - numCursors: options.numCursors - }; - - // Do we have a readConcern specified - decorateWithReadConcern(commandObject, coll, options); - - // Store the raw value - const raw = options.raw; - delete options['raw']; - - // Execute the command - executeCommand(coll.s.db, commandObject, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result == null) - return handleCallback( - callback, - new Error('no result returned for parallelCollectionScan'), - null - ); - - options = Object.assign({ explicitlyIgnoreSession: true }, options); - - const cursors = []; - // Add the raw back to the option - if (raw) options.raw = raw; - // Create command cursors for each item - for (let i = 0; i < result.cursors.length; i++) { - const rawId = result.cursors[i].cursor.id; - // Convert cursorId to Long if needed - const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; - // Add a command cursor - cursors.push(coll.s.topology.cursor(coll.namespace, cursorId, options)); - } - - handleCallback(callback, null, cursors); - }); -} - -/** - * Save a document. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} doc Document to save - * @param {object} [options] Optional settings. See Collection.prototype.save for a list of options. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -function save(coll, doc, options, callback) { - // Get the write concern options - const finalOptions = applyWriteConcern( - Object.assign({}, options), - { db: coll.s.db, collection: coll }, - options - ); - // Establish if we need to perform an insert or update - if (doc._id != null) { - finalOptions.upsert = true; - return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback); - } - - // Insert the document - insertDocuments(coll, [doc], finalOptions, (err, result) => { - if (callback == null) return; - if (doc == null) return handleCallback(callback, null, null); - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); -} - -module.exports = { - checkForAtomicOperators, - createIndex, - createIndexes, - ensureIndex, - group, - indexes, - indexExists, - indexInformation, - parallelCollectionScan, - save -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/collections.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/collections.js deleted file mode 100644 index eac690a..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/collections.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; - -let collection; -function loadCollection() { - if (!collection) { - collection = require('../collection'); - } - return collection; -} - -class CollectionsOperation extends OperationBase { - constructor(db, options) { - super(options); - - this.db = db; - } - - execute(callback) { - const db = this.db; - let options = this.options; - - let Collection = loadCollection(); - - options = Object.assign({}, options, { nameOnly: true }); - // Let's get the collection names - db.listCollections({}, options).toArray((err, documents) => { - if (err != null) return handleCallback(callback, err, null); - // Filter collections removing any illegal ones - documents = documents.filter(doc => { - return doc.name.indexOf('$') === -1; - }); - - // Return the collection objects - handleCallback( - callback, - null, - documents.map(d => { - return new Collection( - db, - db.s.topology, - db.databaseName, - d.name, - db.s.pkFactory, - db.s.options - ); - }) - ); - }); - } -} - -module.exports = CollectionsOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/command.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/command.js deleted file mode 100644 index 3c795be..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/command.js +++ /dev/null @@ -1,120 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const applyWriteConcern = require('../utils').applyWriteConcern; -const debugOptions = require('../utils').debugOptions; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const resolveReadPreference = require('../utils').resolveReadPreference; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -const debugFields = [ - 'authSource', - 'w', - 'wtimeout', - 'j', - 'native_parser', - 'forceServerObjectId', - 'serializeFunctions', - 'raw', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bufferMaxEntries', - 'numberOfRetries', - 'retryMiliSeconds', - 'readPreference', - 'pkFactory', - 'parentDb', - 'promiseLibrary', - 'noListener' -]; - -class CommandOperation extends OperationBase { - constructor(db, options, collection, command) { - super(options); - - if (!this.hasAspect(Aspect.WRITE_OPERATION)) { - if (collection != null) { - this.options.readPreference = resolveReadPreference(collection, options); - } else { - this.options.readPreference = resolveReadPreference(db, options); - } - } else { - if (collection != null) { - applyWriteConcern(this.options, { db, coll: collection }, this.options); - } else { - applyWriteConcern(this.options, { db }, this.options); - } - this.options.readPreference = ReadPreference.primary; - } - - this.db = db; - - if (command != null) { - this.command = command; - } - - if (collection != null) { - this.collection = collection; - } - } - - _buildCommand() { - if (this.command != null) { - return this.command; - } - } - - execute(callback) { - const db = this.db; - const options = Object.assign({}, this.options); - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - let command; - try { - command = this._buildCommand(); - } catch (e) { - return callback(e); - } - - // Get the db name we are executing against - const dbName = options.dbName || options.authdb || db.databaseName; - - // Convert the readPreference if its not a write - if (this.hasAspect(Aspect.WRITE_OPERATION)) { - if (options.writeConcern && (!options.session || !options.session.inTransaction())) { - command.writeConcern = options.writeConcern; - } - } - - // Debug information - if (db.s.logger.isDebug()) { - db.s.logger.debug( - `executing command ${JSON.stringify( - command - )} against ${dbName}.$cmd with options [${JSON.stringify( - debugOptions(debugFields, options) - )}]` - ); - } - - const namespace = - this.namespace != null ? this.namespace : new MongoDBNamespace(dbName, '$cmd'); - - // Execute command - db.s.topology.command(namespace, command, options, (err, result) => { - if (err) return handleCallback(callback, err); - if (options.full) return handleCallback(callback, null, result); - handleCallback(callback, null, result.result); - }); - } -} - -module.exports = CommandOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/command_v2.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/command_v2.js deleted file mode 100644 index 8081d90..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/command_v2.js +++ /dev/null @@ -1,107 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const resolveReadPreference = require('../utils').resolveReadPreference; -const ReadConcern = require('../read_concern'); -const WriteConcern = require('../write_concern'); -const maxWireVersion = require('../core/utils').maxWireVersion; -const commandSupportsReadConcern = require('../core/sessions').commandSupportsReadConcern; -const MongoError = require('../error').MongoError; - -const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; - -class CommandOperationV2 extends OperationBase { - constructor(parent, options, operationOptions) { - super(options); - - this.ns = parent.s.namespace.withCollection('$cmd'); - this.readPreference = resolveReadPreference(parent, this.options); - this.readConcern = resolveReadConcern(parent, this.options); - this.writeConcern = resolveWriteConcern(parent, this.options); - this.explain = false; - - if (operationOptions && typeof operationOptions.fullResponse === 'boolean') { - this.fullResponse = true; - } - - // TODO: A lot of our code depends on having the read preference in the options. This should - // go away, but also requires massive test rewrites. - this.options.readPreference = this.readPreference; - - // TODO(NODE-2056): make logger another "inheritable" property - if (parent.s.logger) { - this.logger = parent.s.logger; - } else if (parent.s.db && parent.s.db.logger) { - this.logger = parent.s.db.logger; - } - } - - executeCommand(server, cmd, callback) { - // TODO: consider making this a non-enumerable property - this.server = server; - - const options = this.options; - const serverWireVersion = maxWireVersion(server); - const inTransaction = this.session && this.session.inTransaction(); - - if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) { - Object.assign(cmd, { readConcern: this.readConcern }); - } - - if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { - callback( - new MongoError( - `Server ${server.name}, which reports wire version ${serverWireVersion}, does not support collation` - ) - ); - return; - } - - if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { - if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION)) { - Object.assign(cmd, { writeConcern: this.writeConcern }); - } - - if (options.collation && typeof options.collation === 'object') { - Object.assign(cmd, { collation: options.collation }); - } - } - - if (typeof options.maxTimeMS === 'number') { - cmd.maxTimeMS = options.maxTimeMS; - } - - if (typeof options.comment === 'string') { - cmd.comment = options.comment; - } - - if (this.logger && this.logger.isDebug()) { - this.logger.debug(`executing command ${JSON.stringify(cmd)} against ${this.ns}`); - } - - server.command(this.ns.toString(), cmd, this.options, (err, result) => { - if (err) { - callback(err, null); - return; - } - - if (this.fullResponse) { - callback(null, result); - return; - } - - callback(null, result.result); - }); - } -} - -function resolveWriteConcern(parent, options) { - return WriteConcern.fromOptions(options) || parent.writeConcern; -} - -function resolveReadConcern(parent, options) { - return ReadConcern.fromOptions(options) || parent.readConcern; -} - -module.exports = CommandOperationV2; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/common_functions.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/common_functions.js deleted file mode 100644 index c027697..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/common_functions.js +++ /dev/null @@ -1,409 +0,0 @@ -'use strict'; - -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const CursorState = require('../core/cursor').CursorState; - -/** - * Build the count command. - * - * @method - * @param {collectionOrCursor} an instance of a collection or cursor - * @param {object} query The query for the count. - * @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options. - */ -function buildCountCommand(collectionOrCursor, query, options) { - const skip = options.skip; - const limit = options.limit; - let hint = options.hint; - const maxTimeMS = options.maxTimeMS; - query = query || {}; - - // Final query - const cmd = { - count: options.collectionName, - query: query - }; - - if (collectionOrCursor.s.numberOfRetries) { - // collectionOrCursor is a cursor - if (collectionOrCursor.options.hint) { - hint = collectionOrCursor.options.hint; - } else if (collectionOrCursor.cmd.hint) { - hint = collectionOrCursor.cmd.hint; - } - decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.cmd); - } else { - decorateWithCollation(cmd, collectionOrCursor, options); - } - - // Add limit, skip and maxTimeMS if defined - if (typeof skip === 'number') cmd.skip = skip; - if (typeof limit === 'number') cmd.limit = limit; - if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; - if (hint) cmd.hint = hint; - - // Do we have a readConcern specified - decorateWithReadConcern(cmd, collectionOrCursor); - - return cmd; -} - -function deleteCallback(err, r, callback) { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - r.deletedCount = r.result.n; - if (callback) callback(null, r); -} - -/** - * Find and update a document. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} doc The fields/vals to be updated. - * @param {object} [options] Optional settings. See Collection.prototype.findAndModify for a list of options. - * @param {Collection~findAndModifyCallback} [callback] The command result callback - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -function findAndModify(coll, query, sort, doc, options, callback) { - // Create findAndModify command object - const queryObject = { - findAndModify: coll.collectionName, - query: query - }; - - sort = formattedOrderClause(sort); - if (sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; - - const projection = options.projection || options.fields; - - if (projection) { - queryObject.fields = projection; - } - - if (options.arrayFilters) { - queryObject.arrayFilters = options.arrayFilters; - delete options.arrayFilters; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; - - // Either use override on the function, or go back to default on either the collection - // level or db - options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // No check on the documents - options.checkKeys = false; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // Decorate the findAndModify command with the write Concern - if (finalOptions.writeConcern) { - queryObject.writeConcern = finalOptions.writeConcern; - } - - // Have we specified bypassDocumentValidation - if (finalOptions.bypassDocumentValidation === true) { - queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; - } - - finalOptions.readPreference = ReadPreference.primary; - - // Have we specified collation - try { - decorateWithCollation(queryObject, coll, finalOptions); - } catch (err) { - return callback(err, null); - } - - // Execute the command - executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { - if (err) return handleCallback(callback, err, null); - - return handleCallback(callback, null, result); - }); -} - -/** - * Retrieves this collections index info. - * - * @method - * @param {Db} db The Db instance on which to retrieve the index info. - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function indexInformation(db, name, options, callback) { - // If we specified full information - const full = options['full'] == null ? false : options['full']; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Process all the results from the index command and collection - function processResults(indexes) { - // Contains all the information - let info = {}; - // Process all the indexes - for (let i = 0; i < indexes.length; i++) { - const index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for (let name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - db.collection(name) - .listIndexes(options) - .toArray((err, indexes) => { - if (err) return callback(toError(err)); - if (!Array.isArray(indexes)) return handleCallback(callback, null, []); - if (full) return handleCallback(callback, null, indexes); - handleCallback(callback, null, processResults(indexes)); - }); -} - -function prepareDocs(coll, docs, options) { - const forceServerObjectId = - typeof options.forceServerObjectId === 'boolean' - ? options.forceServerObjectId - : coll.s.db.options.forceServerObjectId; - - // no need to modify the docs if server sets the ObjectId - if (forceServerObjectId === true) { - return docs; - } - - return docs.map(doc => { - if (forceServerObjectId !== true && doc._id == null) { - doc._id = coll.s.pkFactory.createPk(); - } - - return doc; - }); -} - -// Get the next available document from the cursor, returns null if no more documents are available. -function nextObject(cursor, callback) { - if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) { - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - } - - if (cursor.s.state === CursorState.INIT && cursor.cmd && cursor.cmd.sort) { - try { - cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); - } catch (err) { - return handleCallback(callback, err); - } - } - - // Get the next object - cursor._next((err, doc) => { - cursor.s.state = CursorState.OPEN; - if (err) return handleCallback(callback, err); - handleCallback(callback, null, doc); - }); -} - -function insertDocuments(coll, docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - // Ensure we are operating on an array op docs - docs = Array.isArray(docs) ? docs : [docs]; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // If keep going set unordered - if (finalOptions.keepGoing === true) finalOptions.ordered = false; - finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - docs = prepareDocs(coll, docs, options); - - // File inserts - coll.s.topology.insert(coll.s.namespace, docs, finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) - return handleCallback(callback, toError(result.result.writeErrors[0])); - // Add docs to the list - result.ops = docs; - // Return the results - handleCallback(callback, null, result); - }); -} - -function removeDocuments(coll, selector, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}); - } else if (typeof selector === 'function') { - callback = selector; - options = {}; - selector = {}; - } - - // Create an empty options object if the provided one is null - options = options || {}; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // If selector is null set empty - if (selector == null) selector = {}; - - // Build the op - const op = { q: selector, limit: 0 }; - if (options.single) { - op.limit = 1; - } else if (finalOptions.retryWrites) { - finalOptions.retryWrites = false; - } - - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute the remove - coll.s.topology.remove(coll.s.namespace, [op], finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) { - return handleCallback(callback, toError(result.result.writeErrors[0])); - } - - // Return the results - handleCallback(callback, null, result); - }); -} - -function updateDocuments(coll, selector, document, options, callback) { - if ('function' === typeof options) (callback = options), (options = null); - if (options == null) options = {}; - if (!('function' === typeof callback)) callback = null; - - // If we are not providing a selector or document throw - if (selector == null || typeof selector !== 'object') - return callback(toError('selector must be a valid JavaScript object')); - if (document == null || typeof document !== 'object') - return callback(toError('document must be a valid JavaScript object')); - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // Do we return the actual result document - // Either use override on the function, or go back to default on either the collection - // level or db - finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // Execute the operation - const op = { q: selector, u: document }; - op.upsert = options.upsert !== void 0 ? !!options.upsert : false; - op.multi = options.multi !== void 0 ? !!options.multi : false; - - if (options.hint) { - op.hint = options.hint; - } - - if (finalOptions.arrayFilters) { - op.arrayFilters = finalOptions.arrayFilters; - delete finalOptions.arrayFilters; - } - - if (finalOptions.retryWrites && op.multi) { - finalOptions.retryWrites = false; - } - - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } - - // Update options - coll.s.topology.update(coll.s.namespace, [op], finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) - return handleCallback(callback, toError(result.result.writeErrors[0])); - // Return the results - handleCallback(callback, null, result); - }); -} - -function updateCallback(err, r, callback) { - if (callback == null) return; - if (err) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - callback(null, r); -} - -module.exports = { - buildCountCommand, - deleteCallback, - findAndModify, - indexInformation, - nextObject, - prepareDocs, - insertDocuments, - removeDocuments, - updateDocuments, - updateCallback -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/connect.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/connect.js deleted file mode 100644 index bcdd3eb..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/connect.js +++ /dev/null @@ -1,798 +0,0 @@ -'use strict'; - -const deprecate = require('util').deprecate; -const Logger = require('../core').Logger; -const MongoCredentials = require('../core').MongoCredentials; -const MongoError = require('../core').MongoError; -const Mongos = require('../topologies/mongos'); -const NativeTopology = require('../topologies/native_topology'); -const parse = require('../core').parseConnectionString; -const ReadConcern = require('../read_concern'); -const ReadPreference = require('../core').ReadPreference; -const ReplSet = require('../topologies/replset'); -const Server = require('../topologies/server'); -const ServerSessionPool = require('../core').Sessions.ServerSessionPool; -const emitDeprecationWarning = require('../utils').emitDeprecationWarning; -const fs = require('fs'); -const BSON = require('../core/connection/utils').retrieveBSON(); -const CMAP_EVENT_NAMES = require('../cmap/events').CMAP_EVENT_NAMES; - -let client; -function loadClient() { - if (!client) { - client = require('../mongo_client'); - } - return client; -} - -const legacyParse = deprecate( - require('../url_parser'), - 'current URL string parser is deprecated, and will be removed in a future version. ' + - 'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.' -); - -const AUTH_MECHANISM_INTERNAL_MAP = { - DEFAULT: 'default', - 'MONGODB-CR': 'mongocr', - PLAIN: 'plain', - 'MONGODB-X509': 'x509', - 'SCRAM-SHA-1': 'scram-sha-1', - 'SCRAM-SHA-256': 'scram-sha-256' -}; - -const monitoringEvents = [ - 'timeout', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha', - 'all', - 'fullsetup', - 'open' -]; - -const VALID_AUTH_MECHANISMS = new Set([ - 'DEFAULT', - 'MONGODB-CR', - 'PLAIN', - 'MONGODB-X509', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256', - 'GSSAPI' -]); - -const validOptionNames = [ - 'poolSize', - 'ssl', - 'sslValidate', - 'sslCA', - 'sslCert', - 'sslKey', - 'sslPass', - 'sslCRL', - 'autoReconnect', - 'noDelay', - 'keepAlive', - 'keepAliveInitialDelay', - 'connectTimeoutMS', - 'family', - 'socketTimeoutMS', - 'reconnectTries', - 'reconnectInterval', - 'ha', - 'haInterval', - 'replicaSet', - 'secondaryAcceptableLatencyMS', - 'acceptableLatencyMS', - 'connectWithNoPrimary', - 'authSource', - 'w', - 'wtimeout', - 'j', - 'forceServerObjectId', - 'serializeFunctions', - 'ignoreUndefined', - 'raw', - 'bufferMaxEntries', - 'readPreference', - 'pkFactory', - 'promiseLibrary', - 'readConcern', - 'maxStalenessSeconds', - 'loggerLevel', - 'logger', - 'promoteValues', - 'promoteBuffers', - 'promoteLongs', - 'domainsEnabled', - 'checkServerIdentity', - 'validateOptions', - 'appname', - 'auth', - 'user', - 'password', - 'authMechanism', - 'compression', - 'fsync', - 'readPreferenceTags', - 'numberOfRetries', - 'auto_reconnect', - 'minSize', - 'monitorCommands', - 'retryWrites', - 'retryReads', - 'useNewUrlParser', - 'useUnifiedTopology', - 'serverSelectionTimeoutMS', - 'useRecoveryToken', - 'autoEncryption', - 'driverInfo', - 'tls', - 'tlsInsecure', - 'tlsinsecure', - 'tlsAllowInvalidCertificates', - 'tlsAllowInvalidHostnames', - 'tlsCAFile', - 'tlsCertificateFile', - 'tlsCertificateKeyFile', - 'tlsCertificateKeyFilePassword', - 'minHeartbeatFrequencyMS', - 'heartbeatFrequencyMS', - 'waitQueueTimeoutMS' -]; - -const ignoreOptionNames = ['native_parser']; -const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db']; - -// Validate options object -function validOptions(options) { - const _validOptions = validOptionNames.concat(legacyOptionNames); - - for (const name in options) { - if (ignoreOptionNames.indexOf(name) !== -1) { - continue; - } - - if (_validOptions.indexOf(name) === -1) { - if (options.validateOptions) { - return new MongoError(`option ${name} is not supported`); - } else { - console.warn(`the options [${name}] is not supported`); - } - } - - if (legacyOptionNames.indexOf(name) !== -1) { - console.warn( - `the server/replset/mongos/db options are deprecated, ` + - `all their options are supported at the top level of the options object [${validOptionNames}]` - ); - } - } -} - -const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => { - obj[name.toLowerCase()] = name; - return obj; -}, {}); - -function addListeners(mongoClient, topology) { - topology.on('authenticated', createListener(mongoClient, 'authenticated')); - topology.on('error', createListener(mongoClient, 'error')); - topology.on('timeout', createListener(mongoClient, 'timeout')); - topology.on('close', createListener(mongoClient, 'close')); - topology.on('parseError', createListener(mongoClient, 'parseError')); - topology.once('open', createListener(mongoClient, 'open')); - topology.once('fullsetup', createListener(mongoClient, 'fullsetup')); - topology.once('all', createListener(mongoClient, 'all')); - topology.on('reconnect', createListener(mongoClient, 'reconnect')); -} - -function assignTopology(client, topology) { - client.topology = topology; - - if (!(topology instanceof NativeTopology)) { - topology.s.sessionPool = new ServerSessionPool(topology.s.coreTopology); - } -} - -// Clear out all events -function clearAllEvents(topology) { - monitoringEvents.forEach(event => topology.removeAllListeners(event)); -} - -// Collect all events in order from SDAM -function collectEvents(mongoClient, topology) { - let MongoClient = loadClient(); - const collectedEvents = []; - - if (mongoClient instanceof MongoClient) { - monitoringEvents.forEach(event => { - topology.on(event, (object1, object2) => { - if (event === 'open') { - collectedEvents.push({ event: event, object1: mongoClient }); - } else { - collectedEvents.push({ event: event, object1: object1, object2: object2 }); - } - }); - }); - } - - return collectedEvents; -} - -function resolveTLSOptions(options) { - if (options.tls == null) { - return; - } - - ['sslCA', 'sslKey', 'sslCert'].forEach(optionName => { - if (options[optionName]) { - options[optionName] = fs.readFileSync(options[optionName]); - } - }); -} - -const emitDeprecationForNonUnifiedTopology = deprecate(() => {}, -'current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. ' + 'To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.'); - -function connect(mongoClient, url, options, callback) { - options = Object.assign({}, options); - - // If callback is null throw an exception - if (callback == null) { - throw new Error('no callback function provided'); - } - - let didRequestAuthentication = false; - const logger = Logger('MongoClient', options); - - // Did we pass in a Server/ReplSet/Mongos - if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) { - return connectWithUrl(mongoClient, url, options, connectCallback); - } - - const useNewUrlParser = options.useNewUrlParser !== false; - - const parseFn = useNewUrlParser ? parse : legacyParse; - const transform = useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions; - - parseFn(url, options, (err, _object) => { - // Do not attempt to connect if parsing error - if (err) return callback(err); - - // Flatten - const object = transform(_object); - - // Parse the string - const _finalOptions = createUnifiedOptions(object, options); - - // Check if we have connection and socket timeout set - if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000; - if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 10000; - if (_finalOptions.retryWrites == null) _finalOptions.retryWrites = true; - if (_finalOptions.useRecoveryToken == null) _finalOptions.useRecoveryToken = true; - if (_finalOptions.readPreference == null) _finalOptions.readPreference = 'primary'; - - if (_finalOptions.db_options && _finalOptions.db_options.auth) { - delete _finalOptions.db_options.auth; - } - - // resolve tls options if needed - resolveTLSOptions(_finalOptions); - - // Store the merged options object - mongoClient.s.options = _finalOptions; - - // Failure modes - if (object.servers.length === 0) { - return callback(new Error('connection string must contain at least one seed host')); - } - - if (_finalOptions.auth && !_finalOptions.credentials) { - try { - didRequestAuthentication = true; - _finalOptions.credentials = generateCredentials( - mongoClient, - _finalOptions.auth.user, - _finalOptions.auth.password, - _finalOptions - ); - } catch (err) { - return callback(err); - } - } - - if (_finalOptions.useUnifiedTopology) { - return createTopology(mongoClient, 'unified', _finalOptions, connectCallback); - } - - emitDeprecationForNonUnifiedTopology(); - - // Do we have a replicaset then skip discovery and go straight to connectivity - if (_finalOptions.replicaSet || _finalOptions.rs_name) { - return createTopology(mongoClient, 'replicaset', _finalOptions, connectCallback); - } else if (object.servers.length > 1) { - return createTopology(mongoClient, 'mongos', _finalOptions, connectCallback); - } else { - return createServer(mongoClient, _finalOptions, connectCallback); - } - }); - - function connectCallback(err, topology) { - const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`; - if (err && err.message === 'no mongos proxies found in seed list') { - if (logger.isWarn()) { - logger.warn(warningMessage); - } - - // Return a more specific error message for MongoClient.connect - return callback(new MongoError(warningMessage)); - } - - if (didRequestAuthentication) { - mongoClient.emit('authenticated', null, true); - } - - // Return the error and db instance - callback(err, topology); - } -} - -function connectWithUrl(mongoClient, url, options, connectCallback) { - // Set the topology - assignTopology(mongoClient, url); - - // Add listeners - addListeners(mongoClient, url); - - // Propagate the events to the client - relayEvents(mongoClient, url); - - let finalOptions = Object.assign({}, options); - - // If we have a readPreference passed in by the db options, convert it from a string - if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { - finalOptions.readPreference = new ReadPreference( - options.readPreference || options.read_preference - ); - } - - const isDoingAuth = finalOptions.user || finalOptions.password || finalOptions.authMechanism; - if (isDoingAuth && !finalOptions.credentials) { - try { - finalOptions.credentials = generateCredentials( - mongoClient, - finalOptions.user, - finalOptions.password, - finalOptions - ); - } catch (err) { - return connectCallback(err, url); - } - } - - return url.connect(finalOptions, connectCallback); -} - -function createListener(mongoClient, event) { - const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']); - return (v1, v2) => { - if (eventSet.has(event)) { - return mongoClient.emit(event, mongoClient); - } - - mongoClient.emit(event, v1, v2); - }; -} - -function createServer(mongoClient, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; - - // Set default options - const servers = translateOptions(options); - - const server = servers[0]; - - // Propagate the events to the client - const collectedEvents = collectEvents(mongoClient, server); - - // Connect to topology - server.connect(options, (err, topology) => { - if (err) { - server.close(true); - return callback(err); - } - // Clear out all the collected event listeners - clearAllEvents(server); - - // Relay all the events - relayEvents(mongoClient, server); - // Add listeners - addListeners(mongoClient, server); - // Check if we are really speaking to a mongos - const ismaster = topology.lastIsMaster(); - - // Set the topology - assignTopology(mongoClient, topology); - - // Do we actually have a mongos - if (ismaster && ismaster.msg === 'isdbgrid') { - // Destroy the current connection - topology.close(); - // Create mongos connection instead - return createTopology(mongoClient, 'mongos', options, callback); - } - - // Fire all the events - replayEvents(mongoClient, collectedEvents); - // Otherwise callback - callback(err, topology); - }); -} - -const DEPRECATED_UNIFIED_EVENTS = new Set([ - 'reconnect', - 'reconnectFailed', - 'attemptReconnect', - 'joined', - 'left', - 'ping', - 'ha', - 'all', - 'fullsetup', - 'open' -]); - -function registerDeprecatedEventNotifiers(client) { - client.on('newListener', eventName => { - if (DEPRECATED_UNIFIED_EVENTS.has(eventName)) { - emitDeprecationWarning( - `The \`${eventName}\` event is no longer supported by the unified topology, please read more by visiting http://bit.ly/2D8WfT6`, - 'DeprecationWarning' - ); - } - }); -} - -function createTopology(mongoClient, topologyType, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; - - const translationOptions = {}; - if (topologyType === 'unified') translationOptions.createServers = false; - - // Set default options - const servers = translateOptions(options, translationOptions); - - // determine CSFLE support - if (options.autoEncryption != null) { - let AutoEncrypter; - try { - require.resolve('mongodb-client-encryption'); - } catch (err) { - callback( - new MongoError( - 'Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project' - ) - ); - return; - } - - try { - let mongodbClientEncryption = require('mongodb-client-encryption'); - if (typeof mongodbClientEncryption.extension !== 'function') { - callback( - new MongoError( - 'loaded version of `mongodb-client-encryption` does not have property `extension`. Please make sure you are loading the correct version of `mongodb-client-encryption`' - ) - ); - } - AutoEncrypter = mongodbClientEncryption.extension(require('../../index')).AutoEncrypter; - } catch (err) { - callback(err); - return; - } - - const mongoCryptOptions = Object.assign( - { - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]) - }, - options.autoEncryption - ); - - options.autoEncrypter = new AutoEncrypter(mongoClient, mongoCryptOptions); - } - - // Create the topology - let topology; - if (topologyType === 'mongos') { - topology = new Mongos(servers, options); - } else if (topologyType === 'replicaset') { - topology = new ReplSet(servers, options); - } else if (topologyType === 'unified') { - topology = new NativeTopology(options.servers, options); - registerDeprecatedEventNotifiers(mongoClient); - } - - // Add listeners - addListeners(mongoClient, topology); - - // Propagate the events to the client - relayEvents(mongoClient, topology); - - // Open the connection - assignTopology(mongoClient, topology); - - // initialize CSFLE if requested - if (options.autoEncrypter) { - options.autoEncrypter.init(err => { - if (err) { - callback(err); - return; - } - - topology.connect(options, err => { - if (err) { - topology.close(true); - callback(err); - return; - } - - callback(undefined, topology); - }); - }); - - return; - } - - // otherwise connect normally - topology.connect(options, err => { - if (err) { - topology.close(true); - return callback(err); - } - - callback(undefined, topology); - return; - }); -} - -function createUnifiedOptions(finalOptions, options) { - const childOptions = [ - 'mongos', - 'server', - 'db', - 'replset', - 'db_options', - 'server_options', - 'rs_options', - 'mongos_options' - ]; - const noMerge = ['readconcern', 'compression', 'autoencryption']; - - for (const name in options) { - if (noMerge.indexOf(name.toLowerCase()) !== -1) { - finalOptions[name] = options[name]; - } else if (childOptions.indexOf(name.toLowerCase()) !== -1) { - finalOptions = mergeOptions(finalOptions, options[name], false); - } else { - if ( - options[name] && - typeof options[name] === 'object' && - !Buffer.isBuffer(options[name]) && - !Array.isArray(options[name]) - ) { - finalOptions = mergeOptions(finalOptions, options[name], true); - } else { - finalOptions[name] = options[name]; - } - } - } - - return finalOptions; -} - -function generateCredentials(client, username, password, options) { - options = Object.assign({}, options); - - // the default db to authenticate against is 'self' - // if authententicate is called from a retry context, it may be another one, like admin - const source = options.authSource || options.authdb || options.dbName; - - // authMechanism - const authMechanismRaw = options.authMechanism || 'DEFAULT'; - const authMechanism = authMechanismRaw.toUpperCase(); - - if (!VALID_AUTH_MECHANISMS.has(authMechanism)) { - throw MongoError.create({ - message: `authentication mechanism ${authMechanismRaw} not supported', options.authMechanism`, - driver: true - }); - } - - if (authMechanism === 'GSSAPI') { - return new MongoCredentials({ - mechanism: process.platform === 'win32' ? 'sspi' : 'gssapi', - mechanismProperties: options, - source, - username, - password - }); - } - - return new MongoCredentials({ - mechanism: AUTH_MECHANISM_INTERNAL_MAP[authMechanism], - source, - username, - password - }); -} - -function legacyTransformUrlOptions(object) { - return mergeOptions(createUnifiedOptions({}, object), object, false); -} - -function mergeOptions(target, source, flatten) { - for (const name in source) { - if (source[name] && typeof source[name] === 'object' && flatten) { - target = mergeOptions(target, source[name], flatten); - } else { - target[name] = source[name]; - } - } - - return target; -} - -function relayEvents(mongoClient, topology) { - const serverOrCommandEvents = [ - // APM - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - - // SDAM - 'serverOpening', - 'serverClosed', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - - // Legacy - 'joined', - 'left', - 'ping', - 'ha' - ].concat(CMAP_EVENT_NAMES); - - serverOrCommandEvents.forEach(event => { - topology.on(event, (object1, object2) => { - mongoClient.emit(event, object1, object2); - }); - }); -} - -// -// Replay any events due to single server connection switching to Mongos -// -function replayEvents(mongoClient, events) { - for (let i = 0; i < events.length; i++) { - mongoClient.emit(events[i].event, events[i].object1, events[i].object2); - } -} - -function transformUrlOptions(_object) { - let object = Object.assign({ servers: _object.hosts }, _object.options); - for (let name in object) { - const camelCaseName = LEGACY_OPTIONS_MAP[name]; - if (camelCaseName) { - object[camelCaseName] = object[name]; - } - } - - const hasUsername = _object.auth && _object.auth.username; - const hasAuthMechanism = _object.options && _object.options.authMechanism; - if (hasUsername || hasAuthMechanism) { - object.auth = Object.assign({}, _object.auth); - if (object.auth.db) { - object.authSource = object.authSource || object.auth.db; - } - - if (object.auth.username) { - object.auth.user = object.auth.username; - } - } - - if (_object.defaultDatabase) { - object.dbName = _object.defaultDatabase; - } - - if (object.maxPoolSize) { - object.poolSize = object.maxPoolSize; - } - - if (object.readConcernLevel) { - object.readConcern = new ReadConcern(object.readConcernLevel); - } - - if (object.wTimeoutMS) { - object.wtimeout = object.wTimeoutMS; - } - - if (_object.srvHost) { - object.srvHost = _object.srvHost; - } - - return object; -} - -function translateOptions(options, translationOptions) { - translationOptions = Object.assign({}, { createServers: true }, translationOptions); - - // If we have a readPreference passed in by the db options - if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { - options.readPreference = new ReadPreference(options.readPreference || options.read_preference); - } - - // Do we have readPreference tags, add them - if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { - options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; - } - - // Do we have maxStalenessSeconds - if (options.maxStalenessSeconds) { - options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; - } - - // Set the socket and connection timeouts - if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000; - if (options.connectTimeoutMS == null) options.connectTimeoutMS = 10000; - - if (!translationOptions.createServers) { - return; - } - - // Create server instances - return options.servers.map(serverObj => { - return serverObj.domain_socket - ? new Server(serverObj.domain_socket, 27017, options) - : new Server(serverObj.host, serverObj.port, options); - }); -} - -module.exports = { validOptions, connect }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/count.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/count.js deleted file mode 100644 index a7216d6..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/count.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict'; - -const buildCountCommand = require('./common_functions').buildCountCommand; -const OperationBase = require('./operation').OperationBase; - -class CountOperation extends OperationBase { - constructor(cursor, applySkipLimit, options) { - super(options); - - this.cursor = cursor; - this.applySkipLimit = applySkipLimit; - } - - execute(callback) { - const cursor = this.cursor; - const applySkipLimit = this.applySkipLimit; - const options = this.options; - - if (applySkipLimit) { - if (typeof cursor.cursorSkip() === 'number') options.skip = cursor.cursorSkip(); - if (typeof cursor.cursorLimit() === 'number') options.limit = cursor.cursorLimit(); - } - - // Ensure we have the right read preference inheritance - if (options.readPreference) { - cursor.setReadPreference(options.readPreference); - } - - if ( - typeof options.maxTimeMS !== 'number' && - cursor.cmd && - typeof cursor.cmd.maxTimeMS === 'number' - ) { - options.maxTimeMS = cursor.cmd.maxTimeMS; - } - - let finalOptions = {}; - finalOptions.skip = options.skip; - finalOptions.limit = options.limit; - finalOptions.hint = options.hint; - finalOptions.maxTimeMS = options.maxTimeMS; - - // Command - finalOptions.collectionName = cursor.namespace.collection; - - let command; - try { - command = buildCountCommand(cursor, cursor.cmd.query, finalOptions); - } catch (err) { - return callback(err); - } - - // Set cursor server to the same as the topology - cursor.server = cursor.topology.s.coreTopology; - - // Execute the command - cursor.topology.command( - cursor.namespace.withCollection('$cmd'), - command, - cursor.options, - (err, result) => { - callback(err, result ? result.result.n : null); - } - ); - } -} - -module.exports = CountOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/count_documents.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/count_documents.js deleted file mode 100644 index d043abf..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/count_documents.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -const AggregateOperation = require('./aggregate'); - -class CountDocumentsOperation extends AggregateOperation { - constructor(collection, query, options) { - const pipeline = [{ $match: query }]; - if (typeof options.skip === 'number') { - pipeline.push({ $skip: options.skip }); - } - - if (typeof options.limit === 'number') { - pipeline.push({ $limit: options.limit }); - } - - pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); - - super(collection, pipeline, options); - } - - execute(server, callback) { - super.execute(server, (err, result) => { - if (err) { - callback(err, null); - return; - } - - // NOTE: We're avoiding creating a cursor here to reduce the callstack. - const response = result.result; - if (response.cursor == null || response.cursor.firstBatch == null) { - callback(null, 0); - return; - } - - const docs = response.cursor.firstBatch; - callback(null, docs.length ? docs[0].n : 0); - }); - } -} - -module.exports = CountDocumentsOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/create_collection.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/create_collection.js deleted file mode 100644 index d8ab4ae..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/create_collection.js +++ /dev/null @@ -1,117 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperation = require('./command'); -const applyWriteConcern = require('../utils').applyWriteConcern; -const handleCallback = require('../utils').handleCallback; -const loadCollection = require('../dynamic_loaders').loadCollection; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; - -// Filter out any write concern options -const illegalCommandFields = [ - 'w', - 'wtimeout', - 'j', - 'fsync', - 'autoIndexId', - 'strict', - 'serializeFunctions', - 'pkFactory', - 'raw', - 'readPreference', - 'session', - 'readConcern', - 'writeConcern' -]; - -class CreateCollectionOperation extends CommandOperation { - constructor(db, name, options) { - super(db, options); - - this.name = name; - } - - _buildCommand() { - const name = this.name; - const options = this.options; - - // Create collection command - const cmd = { create: name }; - // Add all optional parameters - for (let n in options) { - if ( - options[n] != null && - typeof options[n] !== 'function' && - illegalCommandFields.indexOf(n) === -1 - ) { - cmd[n] = options[n]; - } - } - - return cmd; - } - - execute(callback) { - const db = this.db; - const name = this.name; - const options = this.options; - - let Collection = loadCollection(); - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - let listCollectionOptions = Object.assign({}, options, { nameOnly: true }); - listCollectionOptions = applyWriteConcern(listCollectionOptions, { db }, listCollectionOptions); - - // Check if we have the name - db.listCollections({ name }, listCollectionOptions) - .setReadPreference(ReadPreference.PRIMARY) - .toArray((err, collections) => { - if (err != null) return handleCallback(callback, err, null); - if (collections.length > 0 && listCollectionOptions.strict) { - return handleCallback( - callback, - MongoError.create({ - message: `Collection ${name} already exists. Currently in strict mode.`, - driver: true - }), - null - ); - } else if (collections.length > 0) { - try { - return handleCallback( - callback, - null, - new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err); - } - } - - // Execute command - super.execute(err => { - if (err) return handleCallback(callback, err); - - try { - return handleCallback( - callback, - null, - new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err); - } - }); - }); - } -} - -defineAspects(CreateCollectionOperation, Aspect.WRITE_OPERATION); - -module.exports = CreateCollectionOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/create_index.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/create_index.js deleted file mode 100644 index 98bba71..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/create_index.js +++ /dev/null @@ -1,92 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const parseIndexOptions = require('../utils').parseIndexOptions; - -const keysToOmit = new Set([ - 'name', - 'key', - 'writeConcern', - 'w', - 'wtimeout', - 'j', - 'fsync', - 'readPreference', - 'session' -]); - -class CreateIndexOperation extends CommandOperation { - constructor(db, name, fieldOrSpec, options) { - super(db, options); - - // Build the index - const indexParameters = parseIndexOptions(fieldOrSpec); - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - // Set up the index - const indexesObject = { name: indexName, key: indexParameters.fieldHash }; - - this.name = name; - this.fieldOrSpec = fieldOrSpec; - this.indexes = indexesObject; - } - - _buildCommand() { - const options = this.options; - const name = this.name; - const indexes = this.indexes; - - // merge all the options - for (let optionName in options) { - if (!keysToOmit.has(optionName)) { - indexes[optionName] = options[optionName]; - } - } - - // Create command, apply write concern to command - const cmd = { createIndexes: name, indexes: [indexes] }; - - return cmd; - } - - execute(callback) { - const db = this.db; - const options = this.options; - const indexes = this.indexes; - - // Get capabilities - const capabilities = db.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (options.collation && capabilities && !capabilities.commandsTakeCollation) { - // Create a new error - const error = new MongoError('server/primary/mongos does not support collation'); - error.code = 67; - // Return the error - return callback(error); - } - - // Ensure we have a callback - if (options.writeConcern && typeof callback !== 'function') { - throw MongoError.create({ - message: 'Cannot use a writeConcern without a provided callback', - driver: true - }); - } - - // Attempt to run using createIndexes command - super.execute((err, result) => { - if (err == null) return handleCallback(callback, err, indexes.name); - - return handleCallback(callback, err, result); - }); - } -} - -defineAspects(CreateIndexOperation, Aspect.WRITE_OPERATION); - -module.exports = CreateIndexOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/create_indexes.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/create_indexes.js deleted file mode 100644 index 46228e8..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/create_indexes.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; -const executeCommand = require('./db_ops').executeCommand; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; - -class CreateIndexesOperation extends OperationBase { - constructor(collection, indexSpecs, options) { - super(options); - - this.collection = collection; - this.indexSpecs = indexSpecs; - } - - execute(callback) { - const coll = this.collection; - const indexSpecs = this.indexSpecs; - let options = this.options; - - const capabilities = coll.s.topology.capabilities(); - - // Ensure we generate the correct name if the parameter is not set - for (let i = 0; i < indexSpecs.length; i++) { - if (indexSpecs[i].name == null) { - const keys = []; - - // Did the user pass in a collation, check if our write server supports it - if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - for (let name in indexSpecs[i].key) { - keys.push(`${name}_${indexSpecs[i].key[name]}`); - } - - // Set the name - indexSpecs[i].name = keys.join('_'); - } - } - - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Execute the index - executeCommand( - coll.s.db, - { - createIndexes: coll.collectionName, - indexes: indexSpecs - }, - options, - callback - ); - } -} - -defineAspects(CreateIndexesOperation, Aspect.WRITE_OPERATION); - -module.exports = CreateIndexesOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/cursor_ops.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/cursor_ops.js deleted file mode 100644 index 98df606..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/cursor_ops.js +++ /dev/null @@ -1,168 +0,0 @@ -'use strict'; - -const buildCountCommand = require('./collection_ops').buildCountCommand; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const push = Array.prototype.push; -const CursorState = require('../core/cursor').CursorState; - -/** - * Get the count of documents for this cursor. - * - * @method - * @param {Cursor} cursor The Cursor instance on which to count. - * @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options. - * @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options. - * @param {Cursor~countResultCallback} [callback] The result callback. - */ -function count(cursor, applySkipLimit, opts, callback) { - if (applySkipLimit) { - if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip(); - if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit(); - } - - // Ensure we have the right read preference inheritance - if (opts.readPreference) { - cursor.setReadPreference(opts.readPreference); - } - - if ( - typeof opts.maxTimeMS !== 'number' && - cursor.cmd && - typeof cursor.cmd.maxTimeMS === 'number' - ) { - opts.maxTimeMS = cursor.cmd.maxTimeMS; - } - - let options = {}; - options.skip = opts.skip; - options.limit = opts.limit; - options.hint = opts.hint; - options.maxTimeMS = opts.maxTimeMS; - - // Command - options.collectionName = cursor.namespace.collection; - - let command; - try { - command = buildCountCommand(cursor, cursor.cmd.query, options); - } catch (err) { - return callback(err); - } - - // Set cursor server to the same as the topology - cursor.server = cursor.topology.s.coreTopology; - - // Execute the command - cursor.topology.command( - cursor.namespace.withCollection('$cmd'), - command, - cursor.options, - (err, result) => { - callback(err, result ? result.result.n : null); - } - ); -} - -/** - * Iterates over all the documents for this cursor. See Cursor.prototype.each for more information. - * - * @method - * @deprecated - * @param {Cursor} cursor The Cursor instance on which to run. - * @param {Cursor~resultCallback} callback The result callback. - */ -function each(cursor, callback) { - if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); - if (cursor.isNotified()) return; - if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) { - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - } - - if (cursor.s.state === CursorState.INIT) { - cursor.s.state = CursorState.OPEN; - } - - // Define function to avoid global scope escape - let fn = null; - // Trampoline all the entries - if (cursor.bufferedCount() > 0) { - while ((fn = loop(cursor, callback))) fn(cursor, callback); - each(cursor, callback); - } else { - cursor.next((err, item) => { - if (err) return handleCallback(callback, err); - if (item == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); - } - - if (handleCallback(callback, null, item) === false) return; - each(cursor, callback); - }); - } -} - -// Trampoline emptying the number of retrieved items -// without incurring a nextTick operation -function loop(cursor, callback) { - // No more items we are done - if (cursor.bufferedCount() === 0) return; - // Get the next document - cursor._next(callback); - // Loop - return loop; -} - -/** - * Returns an array of documents. See Cursor.prototype.toArray for more information. - * - * @method - * @param {Cursor} cursor The Cursor instance from which to get the next document. - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - */ -function toArray(cursor, callback) { - const items = []; - - // Reset cursor - cursor.rewind(); - cursor.s.state = CursorState.INIT; - - // Fetch all the documents - const fetchDocs = () => { - cursor._next((err, doc) => { - if (err) { - return cursor._endSession - ? cursor._endSession(() => handleCallback(callback, err)) - : handleCallback(callback, err); - } - if (doc == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); - } - - // Add doc to items - items.push(doc); - - // Get all buffered objects - if (cursor.bufferedCount() > 0) { - let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); - - // Transform the doc if transform method added - if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { - docs = docs.map(cursor.s.transforms.doc); - } - - push.apply(items, docs); - } - - // Attempt a fetch - fetchDocs(); - }); - }; - - fetchDocs(); -} - -module.exports = { count, each, toArray }; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/db_ops.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/db_ops.js deleted file mode 100644 index 8fc458a..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/db_ops.js +++ /dev/null @@ -1,468 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const resolveReadPreference = require('../utils').resolveReadPreference; -const debugOptions = require('../utils').debugOptions; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const parseIndexOptions = require('../utils').parseIndexOptions; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const CONSTANTS = require('../constants'); -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -const debugFields = [ - 'authSource', - 'w', - 'wtimeout', - 'j', - 'native_parser', - 'forceServerObjectId', - 'serializeFunctions', - 'raw', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bufferMaxEntries', - 'numberOfRetries', - 'retryMiliSeconds', - 'readPreference', - 'pkFactory', - 'parentDb', - 'promiseLibrary', - 'noListener' -]; - -/** - * Creates an index on the db and collection. - * @method - * @param {Db} db The Db instance on which to create an index. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function createIndex(db, name, fieldOrSpec, options, callback) { - // Get the write concern options - let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); - finalOptions = applyWriteConcern(finalOptions, { db }, options); - - // Ensure we have a callback - if (finalOptions.writeConcern && typeof callback !== 'function') { - throw MongoError.create({ - message: 'Cannot use a writeConcern without a provided callback', - driver: true - }); - } - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // Attempt to run using createIndexes command - createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => { - if (err == null) return handleCallback(callback, err, result); - - /** - * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert: - * 67 = 'CannotCreateIndex' (malformed index options) - * 85 = 'IndexOptionsConflict' (index already exists with different options) - * 86 = 'IndexKeySpecsConflict' (index already exists with the same name) - * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) - * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) - * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`) - */ - if ( - err.code === 67 || - err.code === 11000 || - err.code === 85 || - err.code === 86 || - err.code === 11600 || - err.code === 197 - ) { - return handleCallback(callback, err, result); - } - - // Create command - const doc = createCreateIndexCommand(db, name, fieldOrSpec, options); - // Set no key checking - finalOptions.checkKeys = false; - // Insert document - db.s.topology.insert( - db.s.namespace.withCollection(CONSTANTS.SYSTEM_INDEX_COLLECTION), - doc, - finalOptions, - (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err); - if (result == null) return handleCallback(callback, null, null); - if (result.result.writeErrors) - return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); - handleCallback(callback, null, doc.name); - } - ); - }); -} - -// Add listeners to topology -function createListener(db, e, object) { - function listener(err) { - if (object.listeners(e).length > 0) { - object.emit(e, err, db); - - // Emit on all associated db's if available - for (let i = 0; i < db.s.children.length; i++) { - db.s.children[i].emit(e, err, db.s.children[i]); - } - } - } - return listener; -} - -/** - * Ensures that an index exists. If it does not, creates it. - * - * @method - * @param {Db} db The Db instance on which to ensure the index. - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function ensureIndex(db, name, fieldOrSpec, options, callback) { - // Get the write concern options - const finalOptions = applyWriteConcern({}, { db }, options); - // Create command - const selector = createCreateIndexCommand(db, name, fieldOrSpec, options); - const index_name = selector.name; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // Merge primary readPreference - finalOptions.readPreference = ReadPreference.PRIMARY; - - // Check if the index already exists - indexInformation(db, name, finalOptions, (err, indexInformation) => { - if (err != null && err.code !== 26) return handleCallback(callback, err, null); - // If the index does not exist, create it - if (indexInformation == null || !indexInformation[index_name]) { - createIndex(db, name, fieldOrSpec, options, callback); - } else { - if (typeof callback === 'function') return handleCallback(callback, null, index_name); - } - }); -} - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Db} db The Db instance. - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options] Optional settings. See Db.prototype.eval for a list of options. - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - */ -function evaluate(db, code, parameters, options, callback) { - let finalCode = code; - let finalParameters = []; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // If not a code object translate to one - if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode); - // Ensure the parameters are correct - if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = [parameters]; - } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = parameters; - } - - // Create execution selector - let cmd = { $eval: finalCode, args: finalParameters }; - // Check if the nolock parameter is passed in - if (options['nolock']) { - cmd['nolock'] = options['nolock']; - } - - // Set primary read preference - options.readPreference = new ReadPreference(ReadPreference.PRIMARY); - - // Execute the command - executeCommand(db, cmd, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result && result.ok === 1) return handleCallback(callback, null, result.retval); - if (result) - return handleCallback( - callback, - MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }), - null - ); - handleCallback(callback, err, result); - }); -} - -/** - * Execute a command - * - * @method - * @param {Db} db The Db instance on which to execute the command. - * @param {object} command The command hash - * @param {object} [options] Optional settings. See Db.prototype.command for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeCommand(db, command, options, callback) { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Get the db name we are executing against - const dbName = options.dbName || options.authdb || db.databaseName; - - // Convert the readPreference if its not a write - options.readPreference = resolveReadPreference(db, options); - - // Debug information - if (db.s.logger.isDebug()) - db.s.logger.debug( - `executing command ${JSON.stringify( - command - )} against ${dbName}.$cmd with options [${JSON.stringify( - debugOptions(debugFields, options) - )}]` - ); - - // Execute command - db.s.topology.command(db.s.namespace.withCollection('$cmd'), command, options, (err, result) => { - if (err) return handleCallback(callback, err); - if (options.full) return handleCallback(callback, null, result); - handleCallback(callback, null, result.result); - }); -} - -/** - * Runs a command on the database as admin. - * - * @method - * @param {Db} db The Db instance on which to execute the command. - * @param {object} command The command hash - * @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeDbAdminCommand(db, command, options, callback) { - const namespace = new MongoDBNamespace('admin', '$cmd'); - - db.s.topology.command(namespace, command, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); -} - -/** - * Retrieves this collections index info. - * - * @method - * @param {Db} db The Db instance on which to retrieve the index info. - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function indexInformation(db, name, options, callback) { - // If we specified full information - const full = options['full'] == null ? false : options['full']; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Process all the results from the index command and collection - function processResults(indexes) { - // Contains all the information - let info = {}; - // Process all the indexes - for (let i = 0; i < indexes.length; i++) { - const index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for (let name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - db.collection(name) - .listIndexes(options) - .toArray((err, indexes) => { - if (err) return callback(toError(err)); - if (!Array.isArray(indexes)) return handleCallback(callback, null, []); - if (full) return handleCallback(callback, null, indexes); - handleCallback(callback, null, processResults(indexes)); - }); -} - -/** - * Retrieve the current profiling information for MongoDB - * - * @method - * @param {Db} db The Db instance on which to retrieve the profiling info. - * @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options. - * @param {Db~resultCallback} [callback] The command result callback. - * @deprecated Query the system.profile collection directly. - */ -function profilingInfo(db, options, callback) { - try { - db.collection('system.profile') - .find({}, options) - .toArray(callback); - } catch (err) { - return callback(err, null); - } -} - -// Validate the database name -function validateDatabaseName(databaseName) { - if (typeof databaseName !== 'string') - throw MongoError.create({ message: 'database name must be a string', driver: true }); - if (databaseName.length === 0) - throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); - if (databaseName === '$external') return; - - const invalidChars = [' ', '.', '$', '/', '\\']; - for (let i = 0; i < invalidChars.length; i++) { - if (databaseName.indexOf(invalidChars[i]) !== -1) - throw MongoError.create({ - message: "database names cannot contain the character '" + invalidChars[i] + "'", - driver: true - }); - } -} - -/** - * Create the command object for Db.prototype.createIndex. - * - * @param {Db} db The Db instance on which to create the command. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @return {Object} The insert command object. - */ -function createCreateIndexCommand(db, name, fieldOrSpec, options) { - const indexParameters = parseIndexOptions(fieldOrSpec); - const fieldHash = indexParameters.fieldHash; - - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - const selector = { - ns: db.s.namespace.withCollection(name).toString(), - key: fieldHash, - name: indexName - }; - - // Ensure we have a correct finalUnique - const finalUnique = options == null || 'object' === typeof options ? false : options; - // Set up options - options = options == null || typeof options === 'boolean' ? {} : options; - - // Add all the options - const keysToOmit = Object.keys(selector); - for (let optionName in options) { - if (keysToOmit.indexOf(optionName) === -1) { - selector[optionName] = options[optionName]; - } - } - - if (selector['unique'] == null) selector['unique'] = finalUnique; - - // Remove any write concern operations - const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session']; - for (let i = 0; i < removeKeys.length; i++) { - delete selector[removeKeys[i]]; - } - - // Return the command creation selector - return selector; -} - -/** - * Create index using the createIndexes command. - * - * @param {Db} db The Db instance on which to execute the command. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback. - */ -function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) { - // Build the index - const indexParameters = parseIndexOptions(fieldOrSpec); - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - // Set up the index - const indexes = [{ name: indexName, key: indexParameters.fieldHash }]; - // merge all the options - const keysToOmit = Object.keys(indexes[0]).concat([ - 'writeConcern', - 'w', - 'wtimeout', - 'j', - 'fsync', - 'readPreference', - 'session' - ]); - - for (let optionName in options) { - if (keysToOmit.indexOf(optionName) === -1) { - indexes[0][optionName] = options[optionName]; - } - } - - // Get capabilities - const capabilities = db.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { - // Create a new error - const error = new MongoError('server/primary/mongos does not support collation'); - error.code = 67; - // Return the error - return callback(error); - } - - // Create command, apply write concern to command - const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options); - - // ReadPreference primary - options.readPreference = ReadPreference.PRIMARY; - - // Build the command - executeCommand(db, cmd, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result.ok === 0) return handleCallback(callback, toError(result), null); - // Return the indexName for backward compatibility - handleCallback(callback, null, indexName); - }); -} - -module.exports = { - createListener, - createIndex, - ensureIndex, - evaluate, - executeCommand, - executeDbAdminCommand, - indexInformation, - profilingInfo, - validateDatabaseName -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/delete_many.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/delete_many.js deleted file mode 100644 index d881f67..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/delete_many.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const deleteCallback = require('./common_functions').deleteCallback; -const removeDocuments = require('./common_functions').removeDocuments; - -class DeleteManyOperation extends OperationBase { - constructor(collection, filter, options) { - super(options); - - this.collection = collection; - this.filter = filter; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const options = this.options; - - options.single = false; - removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); - } -} - -module.exports = DeleteManyOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/delete_one.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/delete_one.js deleted file mode 100644 index b05597f..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/delete_one.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const deleteCallback = require('./common_functions').deleteCallback; -const removeDocuments = require('./common_functions').removeDocuments; - -class DeleteOneOperation extends OperationBase { - constructor(collection, filter, options) { - super(options); - - this.collection = collection; - this.filter = filter; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const options = this.options; - - options.single = true; - removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); - } -} - -module.exports = DeleteOneOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/distinct.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/distinct.js deleted file mode 100644 index dcf4f7e..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/distinct.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperationV2 = require('./command_v2'); -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; - -/** - * Return a list of distinct values for the given key across a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {string} key Field of the document to find distinct values for. - * @property {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @property {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. - */ -class DistinctOperation extends CommandOperationV2 { - /** - * Construct a Distinct operation. - * - * @param {Collection} a Collection instance. - * @param {string} key Field of the document to find distinct values for. - * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @param {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. - */ - constructor(collection, key, query, options) { - super(collection, options); - - this.collection = collection; - this.key = key; - this.query = query; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(server, callback) { - const coll = this.collection; - const key = this.key; - const query = this.query; - const options = this.options; - - // Distinct command - const cmd = { - distinct: coll.collectionName, - key: key, - query: query - }; - - // Add maxTimeMS if defined - if (typeof options.maxTimeMS === 'number') { - cmd.maxTimeMS = options.maxTimeMS; - } - - // Do we have a readConcern specified - decorateWithReadConcern(cmd, coll, options); - - // Have we specified collation - try { - decorateWithCollation(cmd, coll, options); - } catch (err) { - return callback(err, null); - } - - super.executeCommand(server, cmd, (err, result) => { - if (err) { - callback(err); - return; - } - - callback(null, this.options.full ? result : result.values); - }); - } -} - -defineAspects(DistinctOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = DistinctOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/drop.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/drop.js deleted file mode 100644 index be03716..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/drop.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; - -class DropOperation extends CommandOperation { - constructor(db, options) { - const finalOptions = Object.assign({}, options, db.s.options); - - if (options.session) { - finalOptions.session = options.session; - } - - super(db, finalOptions); - } - - execute(callback) { - super.execute((err, result) => { - if (err) return handleCallback(callback, err); - if (result.ok) return handleCallback(callback, null, true); - handleCallback(callback, null, false); - }); - } -} - -defineAspects(DropOperation, Aspect.WRITE_OPERATION); - -class DropCollectionOperation extends DropOperation { - constructor(db, name, options) { - super(db, options); - - this.name = name; - this.namespace = `${db.namespace}.${name}`; - } - - _buildCommand() { - return { drop: this.name }; - } -} - -class DropDatabaseOperation extends DropOperation { - _buildCommand() { - return { dropDatabase: 1 }; - } -} - -module.exports = { - DropOperation, - DropCollectionOperation, - DropDatabaseOperation -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/drop_index.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/drop_index.js deleted file mode 100644 index a6ca783..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/drop_index.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperation = require('./command'); -const applyWriteConcern = require('../utils').applyWriteConcern; -const handleCallback = require('../utils').handleCallback; - -class DropIndexOperation extends CommandOperation { - constructor(collection, indexName, options) { - super(collection.s.db, options, collection); - - this.collection = collection; - this.indexName = indexName; - } - - _buildCommand() { - const collection = this.collection; - const indexName = this.indexName; - const options = this.options; - - let cmd = { dropIndexes: collection.collectionName, index: indexName }; - - // Decorate command with writeConcern if supported - cmd = applyWriteConcern(cmd, { db: collection.s.db, collection }, options); - - return cmd; - } - - execute(callback) { - // Execute command - super.execute((err, result) => { - if (typeof callback !== 'function') return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); - } -} - -defineAspects(DropIndexOperation, Aspect.WRITE_OPERATION); - -module.exports = DropIndexOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/drop_indexes.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/drop_indexes.js deleted file mode 100644 index ed404ee..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/drop_indexes.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const DropIndexOperation = require('./drop_index'); -const handleCallback = require('../utils').handleCallback; - -class DropIndexesOperation extends DropIndexOperation { - constructor(collection, options) { - super(collection, '*', options); - } - - execute(callback) { - super.execute(err => { - if (err) return handleCallback(callback, err, false); - handleCallback(callback, null, true); - }); - } -} - -defineAspects(DropIndexesOperation, Aspect.WRITE_OPERATION); - -module.exports = DropIndexesOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/estimated_document_count.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/estimated_document_count.js deleted file mode 100644 index e2d6556..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/estimated_document_count.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperationV2 = require('./command_v2'); - -class EstimatedDocumentCountOperation extends CommandOperationV2 { - constructor(collection, query, options) { - if (typeof options === 'undefined') { - options = query; - query = undefined; - } - - super(collection, options); - this.collectionName = collection.s.namespace.collection; - if (query) { - this.query = query; - } - } - - execute(server, callback) { - const options = this.options; - const cmd = { count: this.collectionName }; - - if (this.query) { - cmd.query = this.query; - } - - if (typeof options.skip === 'number') { - cmd.skip = options.skip; - } - - if (typeof options.limit === 'number') { - cmd.limit = options.limit; - } - - if (options.hint) { - cmd.hint = options.hint; - } - - super.executeCommand(server, cmd, (err, response) => { - if (err) { - callback(err); - return; - } - - callback(null, response.n); - }); - } -} - -defineAspects(EstimatedDocumentCountOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = EstimatedDocumentCountOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/execute_db_admin_command.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/execute_db_admin_command.js deleted file mode 100644 index d15fc8e..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/execute_db_admin_command.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -class ExecuteDbAdminCommandOperation extends OperationBase { - constructor(db, selector, options) { - super(options); - - this.db = db; - this.selector = selector; - } - - execute(callback) { - const db = this.db; - const selector = this.selector; - const options = this.options; - - const namespace = new MongoDBNamespace('admin', '$cmd'); - db.s.topology.command(namespace, selector, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); - } -} - -module.exports = ExecuteDbAdminCommandOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/execute_operation.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/execute_operation.js deleted file mode 100644 index 80d5785..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/execute_operation.js +++ /dev/null @@ -1,186 +0,0 @@ -'use strict'; - -const MongoError = require('../core/error').MongoError; -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const ReadPreference = require('../core/topologies/read_preference'); -const isRetryableError = require('../core/error').isRetryableError; -const maxWireVersion = require('../core/utils').maxWireVersion; -const isUnifiedTopology = require('../core/utils').isUnifiedTopology; - -/** - * Executes the given operation with provided arguments. - * - * This method reduces large amounts of duplication in the entire codebase by providing - * a single point for determining whether callbacks or promises should be used. Additionally - * it allows for a single point of entry to provide features such as implicit sessions, which - * are required by the Driver Sessions specification in the event that a ClientSession is - * not provided - * - * @param {object} topology The topology to execute this operation on - * @param {Operation} operation The operation to execute - * @param {function} callback The command result callback - */ -function executeOperation(topology, operation, callback) { - if (topology == null) { - throw new TypeError('This method requires a valid topology instance'); - } - - if (!(operation instanceof OperationBase)) { - throw new TypeError('This method requires a valid operation instance'); - } - - if (isUnifiedTopology(topology) && topology.shouldCheckForSessionSupport()) { - return selectServerForSessionSupport(topology, operation, callback); - } - - const Promise = topology.s.promiseLibrary; - - // The driver sessions spec mandates that we implicitly create sessions for operations - // that are not explicitly provided with a session. - let session, owner; - if (topology.hasSessionSupport()) { - if (operation.session == null) { - owner = Symbol(); - session = topology.startSession({ owner }); - operation.session = session; - } else if (operation.session.hasEnded) { - throw new MongoError('Use of expired sessions is not permitted'); - } - } - - let result; - if (typeof callback !== 'function') { - result = new Promise((resolve, reject) => { - callback = (err, res) => { - if (err) return reject(err); - resolve(res); - }; - }); - } - - function executeCallback(err, result) { - if (session && session.owner === owner) { - session.endSession(); - if (operation.session === session) { - operation.clearSession(); - } - } - - callback(err, result); - } - - try { - if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) { - executeWithServerSelection(topology, operation, executeCallback); - } else { - operation.execute(executeCallback); - } - } catch (e) { - if (session && session.owner === owner) { - session.endSession(); - if (operation.session === session) { - operation.clearSession(); - } - } - - throw e; - } - - return result; -} - -function supportsRetryableReads(server) { - return maxWireVersion(server) >= 6; -} - -function executeWithServerSelection(topology, operation, callback) { - const readPreference = operation.readPreference || ReadPreference.primary; - const inTransaction = operation.session && operation.session.inTransaction(); - - if (inTransaction && !readPreference.equals(ReadPreference.primary)) { - callback( - new MongoError( - `Read preference in a transaction must be primary, not: ${readPreference.mode}` - ) - ); - - return; - } - - const serverSelectionOptions = { - readPreference, - session: operation.session - }; - - function callbackWithRetry(err, result) { - if (err == null) { - return callback(null, result); - } - - if (!isRetryableError(err)) { - return callback(err); - } - - // select a new server, and attempt to retry the operation - topology.selectServer(serverSelectionOptions, (err, server) => { - if (err || !supportsRetryableReads(server)) { - callback(err, null); - return; - } - - operation.execute(server, callback); - }); - } - - // select a server, and execute the operation against it - topology.selectServer(serverSelectionOptions, (err, server) => { - if (err) { - callback(err, null); - return; - } - - const shouldRetryReads = - topology.s.options.retryReads !== false && - operation.session && - !inTransaction && - supportsRetryableReads(server) && - operation.canRetryRead; - - if (operation.hasAspect(Aspect.RETRYABLE) && shouldRetryReads) { - operation.execute(server, callbackWithRetry); - return; - } - - operation.execute(server, callback); - }); -} - -// TODO: This is only supported for unified topology, it should go away once -// we remove support for legacy topology types. -function selectServerForSessionSupport(topology, operation, callback) { - const Promise = topology.s.promiseLibrary; - - let result; - if (typeof callback !== 'function') { - result = new Promise((resolve, reject) => { - callback = (err, result) => { - if (err) return reject(err); - resolve(result); - }; - }); - } - - topology.selectServer(ReadPreference.primaryPreferred, err => { - if (err) { - callback(err); - return; - } - - executeOperation(topology, operation, callback); - }); - - return result; -} - -module.exports = executeOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/find.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/find.js deleted file mode 100644 index 5d47db6..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/find.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const resolveReadPreference = require('../utils').resolveReadPreference; - -class FindOperation extends OperationBase { - constructor(collection, ns, command, options) { - super(options); - - this.ns = ns; - this.cmd = command; - this.readPreference = resolveReadPreference(collection, this.options); - } - - execute(server, callback) { - // copied from `CommandOperationV2`, to be subclassed in the future - this.server = server; - - const cursorState = this.cursorState || {}; - - // TOOD: use `MongoDBNamespace` through and through - server.query(this.ns.toString(), this.cmd, cursorState, this.options, callback); - } -} - -defineAspects(FindOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = FindOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/find_and_modify.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/find_and_modify.js deleted file mode 100644 index 8965eb4..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/find_and_modify.js +++ /dev/null @@ -1,98 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const decorateWithCollation = require('../utils').decorateWithCollation; -const executeCommand = require('./db_ops').executeCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const handleCallback = require('../utils').handleCallback; -const ReadPreference = require('../core').ReadPreference; - -class FindAndModifyOperation extends OperationBase { - constructor(collection, query, sort, doc, options) { - super(options); - - this.collection = collection; - this.query = query; - this.sort = sort; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const query = this.query; - const sort = formattedOrderClause(this.sort); - const doc = this.doc; - let options = this.options; - - // Create findAndModify command object - const queryObject = { - findAndModify: coll.collectionName, - query: query - }; - - if (sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; - - const projection = options.projection || options.fields; - - if (projection) { - queryObject.fields = projection; - } - - if (options.arrayFilters) { - queryObject.arrayFilters = options.arrayFilters; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; - - // Either use override on the function, or go back to default on either the collection - // level or db - options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // No check on the documents - options.checkKeys = false; - - // Final options for retryable writes and write concern - options = applyRetryableWrites(options, coll.s.db); - options = applyWriteConcern(options, { db: coll.s.db, collection: coll }, options); - - // Decorate the findAndModify command with the write Concern - if (options.writeConcern) { - queryObject.writeConcern = options.writeConcern; - } - - // Have we specified bypassDocumentValidation - if (options.bypassDocumentValidation === true) { - queryObject.bypassDocumentValidation = options.bypassDocumentValidation; - } - - options.readPreference = ReadPreference.primary; - - // Have we specified collation - try { - decorateWithCollation(queryObject, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute the command - executeCommand(coll.s.db, queryObject, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - - return handleCallback(callback, null, result); - }); - } -} - -module.exports = FindAndModifyOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/find_one.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/find_one.js deleted file mode 100644 index b584db6..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/find_one.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -const handleCallback = require('../utils').handleCallback; -const OperationBase = require('./operation').OperationBase; -const toError = require('../utils').toError; - -class FindOneOperation extends OperationBase { - constructor(collection, query, options) { - super(options); - - this.collection = collection; - this.query = query; - } - - execute(callback) { - const coll = this.collection; - const query = this.query; - const options = this.options; - - try { - const cursor = coll - .find(query, options) - .limit(-1) - .batchSize(1); - - // Return the item - cursor.next((err, item) => { - if (err != null) return handleCallback(callback, toError(err), null); - handleCallback(callback, null, item); - }); - } catch (e) { - callback(e); - } - } -} - -module.exports = FindOneOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/find_one_and_delete.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/find_one_and_delete.js deleted file mode 100644 index 1c7527d..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/find_one_and_delete.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -const FindAndModifyOperation = require('./find_and_modify'); - -class FindOneAndDeleteOperation extends FindAndModifyOperation { - constructor(collection, filter, options) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.remove = true; - - super(collection, filter, finalOptions.sort, null, finalOptions); - } -} - -module.exports = FindOneAndDeleteOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/find_one_and_replace.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/find_one_and_replace.js deleted file mode 100644 index ae37df5..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/find_one_and_replace.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -const FindAndModifyOperation = require('./find_and_modify'); - -class FindOneAndReplaceOperation extends FindAndModifyOperation { - constructor(collection, filter, replacement, options) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false; - finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false; - - super(collection, filter, finalOptions.sort, replacement, finalOptions); - } -} - -module.exports = FindOneAndReplaceOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/find_one_and_update.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/find_one_and_update.js deleted file mode 100644 index 6a19965..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/find_one_and_update.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const FindAndModifyOperation = require('./find_and_modify'); - -class FindOneAndUpdateOperation extends FindAndModifyOperation { - constructor(collection, filter, update, options) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = - typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false; - finalOptions.upsert = typeof options.upsert === 'boolean' ? options.upsert : false; - - super(collection, filter, finalOptions.sort, update, finalOptions); - } -} - -module.exports = FindOneAndUpdateOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/geo_haystack_search.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/geo_haystack_search.js deleted file mode 100644 index edd1fb1..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/geo_haystack_search.js +++ /dev/null @@ -1,79 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; -const decorateCommand = require('../utils').decorateCommand; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const handleCallback = require('../utils').handleCallback; -const resolveReadPreference = require('../utils').resolveReadPreference; -const toError = require('../utils').toError; - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @property {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @property {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. - */ -class GeoHaystackSearchOperation extends OperationBase { - /** - * Construct a GeoHaystackSearch operation. - * - * @param {Collection} a Collection instance. - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. - */ - constructor(collection, x, y, options) { - super(options); - - this.collection = collection; - this.x = x; - this.y = y; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(callback) { - const coll = this.collection; - const x = this.x; - const y = this.y; - let options = this.options; - - // Build command object - let commandObject = { - geoSearch: coll.collectionName, - near: [x, y] - }; - - // Remove read preference from hash if it exists - commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']); - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(coll, options); - - // Do we have a readConcern specified - decorateWithReadConcern(commandObject, coll, options); - - // Execute the command - executeCommand(coll.s.db, commandObject, options, (err, res) => { - if (err) return handleCallback(callback, err); - if (res.err || res.errmsg) handleCallback(callback, toError(res)); - // should we only be returning res.results here? Not sure if the user - // should see the other return information - handleCallback(callback, null, res); - }); - } -} - -defineAspects(GeoHaystackSearchOperation, Aspect.READ_OPERATION); - -module.exports = GeoHaystackSearchOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/index_exists.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/index_exists.js deleted file mode 100644 index bd9dc0e..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/index_exists.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const indexInformationDb = require('./db_ops').indexInformation; - -class IndexExistsOperation extends OperationBase { - constructor(collection, indexes, options) { - super(options); - - this.collection = collection; - this.indexes = indexes; - } - - execute(callback) { - const coll = this.collection; - const indexes = this.indexes; - const options = this.options; - - indexInformationDb(coll.s.db, coll.collectionName, options, (err, indexInformation) => { - // If we have an error return - if (err != null) return handleCallback(callback, err, null); - // Let's check for the index names - if (!Array.isArray(indexes)) - return handleCallback(callback, null, indexInformation[indexes] != null); - // Check in list of indexes - for (let i = 0; i < indexes.length; i++) { - if (indexInformation[indexes[i]] == null) { - return handleCallback(callback, null, false); - } - } - - // All keys found return true - return handleCallback(callback, null, true); - }); - } -} - -module.exports = IndexExistsOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/index_information.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/index_information.js deleted file mode 100644 index b18a603..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/index_information.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const indexInformation = require('./common_functions').indexInformation; - -class IndexInformationOperation extends OperationBase { - constructor(db, name, options) { - super(options); - - this.db = db; - this.name = name; - } - - execute(callback) { - const db = this.db; - const name = this.name; - const options = this.options; - - indexInformation(db, name, options, callback); - } -} - -module.exports = IndexInformationOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/indexes.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/indexes.js deleted file mode 100644 index e29a88a..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/indexes.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const indexInformation = require('./common_functions').indexInformation; - -class IndexesOperation extends OperationBase { - constructor(collection, options) { - super(options); - - this.collection = collection; - } - - execute(callback) { - const coll = this.collection; - let options = this.options; - - options = Object.assign({}, { full: true }, options); - indexInformation(coll.s.db, coll.collectionName, options, callback); - } -} - -module.exports = IndexesOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/insert_many.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/insert_many.js deleted file mode 100644 index 460a535..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/insert_many.js +++ /dev/null @@ -1,63 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const BulkWriteOperation = require('./bulk_write'); -const MongoError = require('../core').MongoError; -const prepareDocs = require('./common_functions').prepareDocs; - -class InsertManyOperation extends OperationBase { - constructor(collection, docs, options) { - super(options); - - this.collection = collection; - this.docs = docs; - } - - execute(callback) { - const coll = this.collection; - let docs = this.docs; - const options = this.options; - - if (!Array.isArray(docs)) { - return callback( - MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) - ); - } - - // If keep going set unordered - options['serializeFunctions'] = options['serializeFunctions'] || coll.s.serializeFunctions; - - docs = prepareDocs(coll, docs, options); - - // Generate the bulk write operations - const operations = [ - { - insertMany: docs - } - ]; - - const bulkWriteOperation = new BulkWriteOperation(coll, operations, options); - - bulkWriteOperation.execute((err, result) => { - if (err) return callback(err, null); - callback(null, mapInsertManyResults(docs, result)); - }); - } -} - -function mapInsertManyResults(docs, r) { - const finalResult = { - result: { ok: 1, n: r.insertedCount }, - ops: docs, - insertedCount: r.insertedCount, - insertedIds: r.insertedIds - }; - - if (r.getLastOp()) { - finalResult.result.opTime = r.getLastOp(); - } - - return finalResult; -} - -module.exports = InsertManyOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/insert_one.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/insert_one.js deleted file mode 100644 index 5e70880..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/insert_one.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const MongoError = require('../core').MongoError; -const OperationBase = require('./operation').OperationBase; -const insertDocuments = require('./common_functions').insertDocuments; - -class InsertOneOperation extends OperationBase { - constructor(collection, doc, options) { - super(options); - - this.collection = collection; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const doc = this.doc; - const options = this.options; - - if (Array.isArray(doc)) { - return callback( - MongoError.create({ message: 'doc parameter must be an object', driver: true }) - ); - } - - insertDocuments(coll, [doc], options, (err, r) => { - if (callback == null) return; - if (err && callback) return callback(err); - // Workaround for pre 2.6 servers - if (r == null) return callback(null, { result: { ok: 1 } }); - // Add values to top level to ensure crud spec compatibility - r.insertedCount = r.result.n; - r.insertedId = doc._id; - if (callback) callback(null, r); - }); - } -} - -module.exports = InsertOneOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/is_capped.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/is_capped.js deleted file mode 100644 index 3bfd9ff..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/is_capped.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const OptionsOperation = require('./options_operation'); -const handleCallback = require('../utils').handleCallback; - -class IsCappedOperation extends OptionsOperation { - constructor(collection, options) { - super(collection, options); - } - - execute(callback) { - super.execute((err, document) => { - if (err) return handleCallback(callback, err); - handleCallback(callback, null, !!(document && document.capped)); - }); - } -} - -module.exports = IsCappedOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/list_collections.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/list_collections.js deleted file mode 100644 index ee01d31..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/list_collections.js +++ /dev/null @@ -1,106 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const maxWireVersion = require('../core/utils').maxWireVersion; -const CONSTANTS = require('../constants'); - -const LIST_COLLECTIONS_WIRE_VERSION = 3; - -function listCollectionsTransforms(databaseName) { - const matching = `${databaseName}.`; - - return { - doc: doc => { - const index = doc.name.indexOf(matching); - // Remove database name if available - if (doc.name && index === 0) { - doc.name = doc.name.substr(index + matching.length); - } - - return doc; - } - }; -} - -class ListCollectionsOperation extends CommandOperationV2 { - constructor(db, filter, options) { - super(db, options, { fullResponse: true }); - - this.db = db; - this.filter = filter; - this.nameOnly = !!this.options.nameOnly; - - if (typeof this.options.batchSize === 'number') { - this.batchSize = this.options.batchSize; - } - } - - execute(server, callback) { - if (maxWireVersion(server) < LIST_COLLECTIONS_WIRE_VERSION) { - let filter = this.filter; - const databaseName = this.db.s.namespace.db; - - // If we have legacy mode and have not provided a full db name filter it - if ( - typeof filter.name === 'string' && - !new RegExp('^' + databaseName + '\\.').test(filter.name) - ) { - filter = Object.assign({}, filter); - filter.name = this.db.s.namespace.withCollection(filter.name).toString(); - } - - // No filter, filter by current database - if (filter == null) { - filter.name = `/${databaseName}/`; - } - - // Rewrite the filter to use $and to filter out indexes - if (filter.name) { - filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; - } else { - filter = { name: /^((?!\$).)*$/ }; - } - - const transforms = listCollectionsTransforms(databaseName); - server.query( - `${databaseName}.${CONSTANTS.SYSTEM_NAMESPACE_COLLECTION}`, - { query: filter }, - { batchSize: this.batchSize || 1000 }, - {}, - (err, result) => { - if ( - result && - result.message && - result.message.documents && - Array.isArray(result.message.documents) - ) { - result.message.documents = result.message.documents.map(transforms.doc); - } - - callback(err, result); - } - ); - - return; - } - - const command = { - listCollections: 1, - filter: this.filter, - cursor: this.batchSize ? { batchSize: this.batchSize } : {}, - nameOnly: this.nameOnly - }; - - return super.executeCommand(server, command, callback); - } -} - -defineAspects(ListCollectionsOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListCollectionsOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/list_databases.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/list_databases.js deleted file mode 100644 index 62b2606..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/list_databases.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -class ListDatabasesOperation extends CommandOperationV2 { - constructor(db, options) { - super(db, options); - this.ns = new MongoDBNamespace('admin', '$cmd'); - } - - execute(server, callback) { - const cmd = { listDatabases: 1 }; - if (this.options.nameOnly) { - cmd.nameOnly = Number(cmd.nameOnly); - } - - if (this.options.filter) { - cmd.filter = this.options.filter; - } - - if (typeof this.options.authorizedDatabases === 'boolean') { - cmd.authorizedDatabases = this.options.authorizedDatabases; - } - - super.executeCommand(server, cmd, callback); - } -} - -defineAspects(ListDatabasesOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListDatabasesOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/list_indexes.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/list_indexes.js deleted file mode 100644 index 302a31b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/list_indexes.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const maxWireVersion = require('../core/utils').maxWireVersion; - -const LIST_INDEXES_WIRE_VERSION = 3; - -class ListIndexesOperation extends CommandOperationV2 { - constructor(collection, options) { - super(collection, options, { fullResponse: true }); - - this.collectionNamespace = collection.s.namespace; - } - - execute(server, callback) { - const serverWireVersion = maxWireVersion(server); - if (serverWireVersion < LIST_INDEXES_WIRE_VERSION) { - const systemIndexesNS = this.collectionNamespace.withCollection('system.indexes').toString(); - const collectionNS = this.collectionNamespace.toString(); - - server.query(systemIndexesNS, { query: { ns: collectionNS } }, {}, this.options, callback); - return; - } - - const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; - super.executeCommand( - server, - { listIndexes: this.collectionNamespace.collection, cursor }, - callback - ); - } -} - -defineAspects(ListIndexesOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListIndexesOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/map_reduce.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/map_reduce.js deleted file mode 100644 index 4ea2ac7..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/map_reduce.js +++ /dev/null @@ -1,190 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const handleCallback = require('../utils').handleCallback; -const isObject = require('../utils').isObject; -const loadDb = require('../dynamic_loaders').loadDb; -const OperationBase = require('./operation').OperationBase; -const resolveReadPreference = require('../utils').resolveReadPreference; -const toError = require('../utils').toError; - -const exclusionList = [ - 'readPreference', - 'session', - 'bypassDocumentValidation', - 'w', - 'wtimeout', - 'j', - 'writeConcern' -]; - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {(function|string)} map The mapping function. - * @property {(function|string)} reduce The reduce function. - * @property {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. - */ -class MapReduceOperation extends OperationBase { - /** - * Constructs a MapReduce operation. - * - * @param {Collection} a Collection instance. - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. - */ - constructor(collection, map, reduce, options) { - super(options); - - this.collection = collection; - this.map = map; - this.reduce = reduce; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(callback) { - const coll = this.collection; - const map = this.map; - const reduce = this.reduce; - let options = this.options; - - const mapCommandHash = { - mapreduce: coll.collectionName, - map: map, - reduce: reduce - }; - - // Add any other options passed in - for (let n in options) { - if ('scope' === n) { - mapCommandHash[n] = processScope(options[n]); - } else { - // Only include if not in exclusion list - if (exclusionList.indexOf(n) === -1) { - mapCommandHash[n] = options[n]; - } - } - } - - options = Object.assign({}, options); - - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(coll, options); - - // If we have a read preference and inline is not set as output fail hard - if ( - options.readPreference !== false && - options.readPreference !== 'primary' && - options['out'] && - options['out'].inline !== 1 && - options['out'] !== 'inline' - ) { - // Force readPreference to primary - options.readPreference = 'primary'; - // Decorate command with writeConcern if supported - applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); - } else { - decorateWithReadConcern(mapCommandHash, coll, options); - } - - // Is bypassDocumentValidation specified - if (options.bypassDocumentValidation === true) { - mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Have we specified collation - try { - decorateWithCollation(mapCommandHash, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute command - executeCommand(coll.s.db, mapCommandHash, options, (err, result) => { - if (err) return handleCallback(callback, err); - // Check if we have an error - if (1 !== result.ok || result.err || result.errmsg) { - return handleCallback(callback, toError(result)); - } - - // Create statistics value - const stats = {}; - if (result.timeMillis) stats['processtime'] = result.timeMillis; - if (result.counts) stats['counts'] = result.counts; - if (result.timing) stats['timing'] = result.timing; - - // invoked with inline? - if (result.results) { - // If we wish for no verbosity - if (options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, null, result.results); - } - - return handleCallback(callback, null, { results: result.results, stats: stats }); - } - - // The returned collection - let collection = null; - - // If we have an object it's a different db - if (result.result != null && typeof result.result === 'object') { - const doc = result.result; - // Return a collection from another db - let Db = loadDb(); - collection = new Db(doc.db, coll.s.db.s.topology, coll.s.db.s.options).collection( - doc.collection - ); - } else { - // Create a collection object that wraps the result collection - collection = coll.s.db.collection(result.result); - } - - // If we wish for no verbosity - if (options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, err, collection); - } - - // Return stats as third set of values - handleCallback(callback, err, { collection: collection, stats: stats }); - }); - } -} - -/** - * Functions that are passed as scope args must - * be converted to Code instances. - * @ignore - */ -function processScope(scope) { - if (!isObject(scope) || scope._bsontype === 'ObjectID') { - return scope; - } - - const keys = Object.keys(scope); - let key; - const new_scope = {}; - - for (let i = keys.length - 1; i >= 0; i--) { - key = keys[i]; - if ('function' === typeof scope[key]) { - new_scope[key] = new Code(String(scope[key])); - } else { - new_scope[key] = processScope(scope[key]); - } - } - - return new_scope; -} - -module.exports = MapReduceOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/operation.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/operation.js deleted file mode 100644 index fd82e66..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/operation.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -const Aspect = { - READ_OPERATION: Symbol('READ_OPERATION'), - WRITE_OPERATION: Symbol('WRITE_OPERATION'), - RETRYABLE: Symbol('RETRYABLE'), - EXECUTE_WITH_SELECTION: Symbol('EXECUTE_WITH_SELECTION') -}; - -/** - * This class acts as a parent class for any operation and is responsible for setting this.options, - * as well as setting and getting a session. - * Additionally, this class implements `hasAspect`, which determines whether an operation has - * a specific aspect. - */ -class OperationBase { - constructor(options) { - this.options = Object.assign({}, options); - } - - hasAspect(aspect) { - if (this.constructor.aspects == null) { - return false; - } - return this.constructor.aspects.has(aspect); - } - - set session(session) { - Object.assign(this.options, { session }); - } - - get session() { - return this.options.session; - } - - clearSession() { - delete this.options.session; - } - - get canRetryRead() { - return true; - } - - execute() { - throw new TypeError('`execute` must be implemented for OperationBase subclasses'); - } -} - -function defineAspects(operation, aspects) { - if (!Array.isArray(aspects) && !(aspects instanceof Set)) { - aspects = [aspects]; - } - aspects = new Set(aspects); - Object.defineProperty(operation, 'aspects', { - value: aspects, - writable: false - }); - return aspects; -} - -module.exports = { - Aspect, - defineAspects, - OperationBase -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/options_operation.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/options_operation.js deleted file mode 100644 index 9a739a5..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/options_operation.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; - -class OptionsOperation extends OperationBase { - constructor(collection, options) { - super(options); - - this.collection = collection; - } - - execute(callback) { - const coll = this.collection; - const opts = this.options; - - coll.s.db.listCollections({ name: coll.collectionName }, opts).toArray((err, collections) => { - if (err) return handleCallback(callback, err); - if (collections.length === 0) { - return handleCallback( - callback, - MongoError.create({ message: `collection ${coll.namespace} not found`, driver: true }) - ); - } - - handleCallback(callback, err, collections[0].options || null); - }); - } -} - -module.exports = OptionsOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/profiling_level.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/profiling_level.js deleted file mode 100644 index 3f7639b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/profiling_level.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); - -class ProfilingLevelOperation extends CommandOperation { - constructor(db, command, options) { - super(db, options); - } - - _buildCommand() { - const command = { profile: -1 }; - - return command; - } - - execute(callback) { - super.execute((err, doc) => { - if (err == null && doc.ok === 1) { - const was = doc.was; - if (was === 0) return callback(null, 'off'); - if (was === 1) return callback(null, 'slow_only'); - if (was === 2) return callback(null, 'all'); - return callback(new Error('Error: illegal profiling level value ' + was), null); - } else { - err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); - } - }); - } -} - -module.exports = ProfilingLevelOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/re_index.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/re_index.js deleted file mode 100644 index 89437fe..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/re_index.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); -const handleCallback = require('../utils').handleCallback; - -class ReIndexOperation extends CommandOperation { - constructor(collection, options) { - super(collection.s.db, options, collection); - } - - _buildCommand() { - const collection = this.collection; - - const cmd = { reIndex: collection.collectionName }; - - return cmd; - } - - execute(callback) { - super.execute((err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); - } -} - -module.exports = ReIndexOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/remove_user.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/remove_user.js deleted file mode 100644 index 9e8376b..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/remove_user.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; -const WriteConcern = require('../write_concern'); - -class RemoveUserOperation extends CommandOperation { - constructor(db, username, options) { - const commandOptions = {}; - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern != null) { - commandOptions.writeConcern = writeConcern; - } - - if (options.dbName) { - commandOptions.dbName = options.dbName; - } - - // Add maxTimeMS to options if set - if (typeof options.maxTimeMS === 'number') { - commandOptions.maxTimeMS = options.maxTimeMS; - } - - super(db, commandOptions); - - this.username = username; - } - - _buildCommand() { - const username = this.username; - - // Build the command to execute - const command = { dropUser: username }; - - return command; - } - - execute(callback) { - // Attempt to execute command - super.execute((err, result) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, err, result.ok ? true : false); - }); - } -} - -defineAspects(RemoveUserOperation, Aspect.WRITE_OPERATION); - -module.exports = RemoveUserOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/rename.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/rename.js deleted file mode 100644 index 8098fe6..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/rename.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const applyWriteConcern = require('../utils').applyWriteConcern; -const checkCollectionName = require('../utils').checkCollectionName; -const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; -const handleCallback = require('../utils').handleCallback; -const loadCollection = require('../dynamic_loaders').loadCollection; -const toError = require('../utils').toError; - -class RenameOperation extends OperationBase { - constructor(collection, newName, options) { - super(options); - - this.collection = collection; - this.newName = newName; - } - - execute(callback) { - const coll = this.collection; - const newName = this.newName; - const options = this.options; - - let Collection = loadCollection(); - // Check the collection name - checkCollectionName(newName); - // Build the command - const renameCollection = coll.namespace; - const toCollection = coll.s.namespace.withCollection(newName).toString(); - const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; - const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; - - // Decorate command with writeConcern if supported - applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); - - // Execute against admin - executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => { - if (err) return handleCallback(callback, err, null); - // We have an error - if (doc.errmsg) return handleCallback(callback, toError(doc), null); - try { - return handleCallback( - callback, - null, - new Collection( - coll.s.db, - coll.s.topology, - coll.s.namespace.db, - newName, - coll.s.pkFactory, - coll.s.options - ) - ); - } catch (err) { - return handleCallback(callback, toError(err), null); - } - }); - } -} - -module.exports = RenameOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/replace_one.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/replace_one.js deleted file mode 100644 index a5aa760..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/replace_one.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateDocuments = require('./common_functions').updateDocuments; - -class ReplaceOneOperation extends OperationBase { - constructor(collection, filter, doc, options) { - super(options); - - this.collection = collection; - this.filter = filter; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const doc = this.doc; - const options = this.options; - - // Set single document update - options.multi = false; - - // Execute update - updateDocuments(coll, filter, doc, options, (err, r) => replaceCallback(err, r, doc, callback)); - } -} - -function replaceCallback(err, r, doc, callback) { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - r.ops = [doc]; // TODO: Should we still have this? - if (callback) callback(null, r); -} - -module.exports = ReplaceOneOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/set_profiling_level.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/set_profiling_level.js deleted file mode 100644 index b31cc13..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/set_profiling_level.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); -const levelValues = new Set(['off', 'slow_only', 'all']); - -class SetProfilingLevelOperation extends CommandOperation { - constructor(db, level, options) { - let profile = 0; - - if (level === 'off') { - profile = 0; - } else if (level === 'slow_only') { - profile = 1; - } else if (level === 'all') { - profile = 2; - } - - super(db, options); - this.level = level; - this.profile = profile; - } - - _buildCommand() { - const profile = this.profile; - - // Set up the profile number - const command = { profile }; - - return command; - } - - execute(callback) { - const level = this.level; - - if (!levelValues.has(level)) { - return callback(new Error('Error: illegal profiling level value ' + level)); - } - - super.execute((err, doc) => { - if (err == null && doc.ok === 1) return callback(null, level); - return err != null - ? callback(err, null) - : callback(new Error('Error with profile command'), null); - }); - } -} - -module.exports = SetProfilingLevelOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/stats.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/stats.js deleted file mode 100644 index ff79126..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/stats.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; - -/** - * Get all the collection statistics. - * - * @class - * @property {Collection} a Collection instance. - * @property {object} [options] Optional settings. See Collection.prototype.stats for a list of options. - */ -class StatsOperation extends CommandOperation { - /** - * Construct a Stats operation. - * - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.stats for a list of options. - */ - constructor(collection, options) { - super(collection.s.db, options, collection); - } - - _buildCommand() { - const collection = this.collection; - const options = this.options; - - // Build command object - const command = { - collStats: collection.collectionName - }; - - // Check if we have the scale value - if (options['scale'] != null) { - command['scale'] = options['scale']; - } - - return command; - } -} - -defineAspects(StatsOperation, Aspect.READ_OPERATION); - -module.exports = StatsOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/update_many.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/update_many.js deleted file mode 100644 index 9a18d25..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/update_many.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateCallback = require('./common_functions').updateCallback; -const updateDocuments = require('./common_functions').updateDocuments; - -class UpdateManyOperation extends OperationBase { - constructor(collection, filter, update, options) { - super(options); - - this.collection = collection; - this.filter = filter; - this.update = update; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const update = this.update; - const options = this.options; - - // Set single document update - options.multi = true; - // Execute update - updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); - } -} - -module.exports = UpdateManyOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/update_one.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/update_one.js deleted file mode 100644 index b1c1bc1..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/update_one.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateDocuments = require('./common_functions').updateDocuments; - -class UpdateOneOperation extends OperationBase { - constructor(collection, filter, update, options) { - super(options); - - this.collection = collection; - this.filter = filter; - this.update = update; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const update = this.update; - const options = this.options; - - // Set single document update - options.multi = false; - // Execute update - updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); - } -} - -function updateCallback(err, r, callback) { - if (callback == null) return; - if (err) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - callback(null, r); -} - -module.exports = UpdateOneOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/operations/validate_collection.js b/node_modules/mongoose/node_modules/mongodb/lib/operations/validate_collection.js deleted file mode 100644 index 133c6c4..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/operations/validate_collection.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); - -class ValidateCollectionOperation extends CommandOperation { - constructor(admin, collectionName, options) { - // Decorate command with extra options - let command = { validate: collectionName }; - const keys = Object.keys(options); - for (let i = 0; i < keys.length; i++) { - if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { - command[keys[i]] = options[keys[i]]; - } - } - - super(admin.s.db, options, null, command); - - this.collectionName; - } - - execute(callback) { - const collectionName = this.collectionName; - - super.execute((err, doc) => { - if (err != null) return callback(err, null); - - if (doc.ok === 0) return callback(new Error('Error with validate command'), null); - if (doc.result != null && doc.result.constructor !== String) - return callback(new Error('Error with validation data'), null); - if (doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error('Error: invalid collection ' + collectionName), null); - if (doc.valid != null && !doc.valid) - return callback(new Error('Error: invalid collection ' + collectionName), null); - - return callback(null, doc); - }); - } -} - -module.exports = ValidateCollectionOperation; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/read_concern.js b/node_modules/mongoose/node_modules/mongodb/lib/read_concern.js deleted file mode 100644 index b48b8e0..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/read_concern.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -/** - * The **ReadConcern** class is a class that represents a MongoDB ReadConcern. - * @class - * @property {string} level The read concern level - * @see https://docs.mongodb.com/manual/reference/read-concern/index.html - */ -class ReadConcern { - /** - * Constructs a ReadConcern from the read concern properties. - * @param {string} [level] The read concern level ({'local'|'available'|'majority'|'linearizable'|'snapshot'}) - */ - constructor(level) { - if (level != null) { - this.level = level; - } - } - - /** - * Construct a ReadConcern given an options object. - * - * @param {object} options The options object from which to extract the write concern. - * @return {ReadConcern} - */ - static fromOptions(options) { - if (options == null) { - return; - } - - if (options.readConcern) { - if (options.readConcern instanceof ReadConcern) { - return options.readConcern; - } - - return new ReadConcern(options.readConcern.level); - } - - if (options.level) { - return new ReadConcern(options.level); - } - } - - static get MAJORITY() { - return 'majority'; - } - - static get AVAILABLE() { - return 'available'; - } - - static get LINEARIZABLE() { - return 'linearizable'; - } - - static get SNAPSHOT() { - return 'snapshot'; - } -} - -module.exports = ReadConcern; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/topologies/mongos.js b/node_modules/mongoose/node_modules/mongodb/lib/topologies/mongos.js deleted file mode 100644 index 10e66d2..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/topologies/mongos.js +++ /dev/null @@ -1,445 +0,0 @@ -'use strict'; - -const TopologyBase = require('./topology_base').TopologyBase; -const MongoError = require('../core').MongoError; -const CMongos = require('../core').Mongos; -const Cursor = require('../cursor'); -const Server = require('./server'); -const Store = require('./topology_base').Store; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - * - * **Mongos Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'acceptableLatencyMS', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCRL', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'promiseLibrary', - 'monitorCommands' -]; - -/** - * Creates a new Mongos instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options] Optional settings. - * @param {booelan} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=5000] Time between each replicaset status check. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out - * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires Mongos#connect - * @fires Mongos#ha - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#fullsetup - * @fires Mongos#open - * @fires Mongos#close - * @fires Mongos#error - * @fires Mongos#timeout - * @fires Mongos#parseError - * @fires Mongos#commandStarted - * @fires Mongos#commandSucceeded - * @fires Mongos#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {Mongos} a Mongos instance. - */ -class Mongos extends TopologyBase { - constructor(servers, options) { - super(); - - options = options || {}; - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for (var i = 0; i < servers.length; i++) { - if (!(servers[i] instanceof Server)) { - throw MongoError.create({ - message: 'all seed list instances must be of the Server type', - driver: true - }); - } - } - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Build seed list - var seedlist = servers.map(function(x) { - return { host: x.host, port: x.port }; - }); - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Internal state - this.s = { - // Create the Mongos - coreTopology: new CMongos(seedlist, clonedOptions), - // Server capabilities - sCapabilities: null, - // Debug turned on - debug: clonedOptions.debug, - // Store option defaults - storeOptions: storeOptions, - // Cloned options - clonedOptions: clonedOptions, - // Actual store of callbacks - store: store, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise - }; - } - - // Connect - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = {}; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.removeListener(e, connectErrorHandler); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - // Force close the topology - self.close(true); - - // Try to callback - try { - callback(err); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Error handler - var reconnectHandler = function() { - self.emit('reconnect'); - self.s.store.execute(); - }; - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - var events = ['timeout', 'error', 'close', 'fullsetup']; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up listeners - self.s.coreTopology.on('timeout', errorHandler('timeout')); - self.s.coreTopology.on('error', errorHandler('error')); - self.s.coreTopology.on('close', errorHandler('close')); - - // Set up serverConfig listeners - self.s.coreTopology.on('fullsetup', function() { - self.emit('fullsetup', self); - }); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Clear out all the current handlers left over - var events = [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed' - ]; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - - // Set up listeners - self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); - self.s.coreTopology.once('error', connectErrorHandler('error')); - self.s.coreTopology.once('close', connectErrorHandler('close')); - self.s.coreTopology.once('connect', connectHandler); - // Join and leave events - self.s.coreTopology.on('joined', relay('joined')); - self.s.coreTopology.on('left', relay('left')); - - // Reconnect server - self.s.coreTopology.on('reconnect', reconnectHandler); - - // Start connection - self.s.coreTopology.connect(_options); - } -} - -Object.defineProperty(Mongos.prototype, 'haInterval', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.haInterval; - } -}); - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * The mongos high availability event - * - * @event Mongos#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the mongos set - * - * @event Mongos#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos set - * - * @event Mongos#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * Mongos open event, emitted when mongos can start processing commands. - * - * @event Mongos#open - * @type {Mongos} - */ - -/** - * Mongos close event - * - * @event Mongos#close - * @type {object} - */ - -/** - * Mongos error event, emitted if there is an error listener. - * - * @event Mongos#error - * @type {MongoError} - */ - -/** - * Mongos timeout event - * - * @event Mongos#timeout - * @type {object} - */ - -/** - * Mongos parseError event - * - * @event Mongos#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Mongos#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Mongos#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Mongos#commandFailed - * @type {object} - */ - -module.exports = Mongos; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/topologies/native_topology.js b/node_modules/mongoose/node_modules/mongodb/lib/topologies/native_topology.js deleted file mode 100644 index 778ddc9..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/topologies/native_topology.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict'; - -const Topology = require('../core').Topology; -const ServerCapabilities = require('./topology_base').ServerCapabilities; -const Cursor = require('../cursor'); -const translateOptions = require('../utils').translateOptions; - -class NativeTopology extends Topology { - constructor(servers, options) { - options = options || {}; - - let clonedOptions = Object.assign( - {}, - { - cursorFactory: Cursor, - reconnect: false, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - maxPoolSize: typeof options.poolSize === 'number' ? options.poolSize : 5, - minPoolSize: typeof options.minSize === 'number' ? options.minSize : 0, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - super(servers, clonedOptions); - } - - capabilities() { - if (this.s.sCapabilities) return this.s.sCapabilities; - if (this.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.lastIsMaster()); - return this.s.sCapabilities; - } - - // Command - command(ns, cmd, options, callback) { - super.command(ns.toString(), cmd, options, callback); - } - - // Insert - insert(ns, ops, options, callback) { - super.insert(ns.toString(), ops, options, callback); - } - - // Update - update(ns, ops, options, callback) { - super.update(ns.toString(), ops, options, callback); - } - - // Remove - remove(ns, ops, options, callback) { - super.remove(ns.toString(), ops, options, callback); - } -} - -module.exports = NativeTopology; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/topologies/replset.js b/node_modules/mongoose/node_modules/mongodb/lib/topologies/replset.js deleted file mode 100644 index 69df26d..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/topologies/replset.js +++ /dev/null @@ -1,489 +0,0 @@ -'use strict'; - -const Server = require('./server'); -const Cursor = require('../cursor'); -const MongoError = require('../core').MongoError; -const TopologyBase = require('./topology_base').TopologyBase; -const Store = require('./topology_base').Store; -const CReplSet = require('../core').ReplSet; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is - * used to construct connections. - * - * **ReplSet Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'replicaSet', - 'rs_name', - 'secondaryAcceptableLatencyMS', - 'connectWithNoPrimary', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslCRL', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'strategy', - 'debug', - 'family', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'maxStalenessSeconds', - 'promiseLibrary', - 'minSize', - 'monitorCommands' -]; - -/** - * Creates a new ReplSet instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options] Optional settings. - * @param {boolean} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=10000] Time between each replicaset status check. - * @param {string} [options.replicaSet] The name of the replicaset to connect to. - * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher. - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out - * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#fullsetup - * @fires ReplSet#open - * @fires ReplSet#close - * @fires ReplSet#error - * @fires ReplSet#timeout - * @fires ReplSet#parseError - * @fires ReplSet#commandStarted - * @fires ReplSet#commandSucceeded - * @fires ReplSet#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {ReplSet} a ReplSet instance. - */ -class ReplSet extends TopologyBase { - constructor(servers, options) { - super(); - - options = options || {}; - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for (var i = 0; i < servers.length; i++) { - if (!(servers[i] instanceof Server)) { - throw MongoError.create({ - message: 'all seed list instances must be of the Server type', - driver: true - }); - } - } - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Build seed list - var seedlist = servers.map(function(x) { - return { host: x.host, port: x.port }; - }); - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: false, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Create the ReplSet - var coreTopology = new CReplSet(seedlist, clonedOptions); - - // Listen to reconnect event - coreTopology.on('reconnect', function() { - self.emit('reconnect'); - store.execute(); - }); - - // Internal state - this.s = { - // Replicaset - coreTopology: coreTopology, - // Server capabilities - sCapabilities: null, - // Debug tag - tag: options.tag, - // Store options - storeOptions: storeOptions, - // Cloned options - clonedOptions: clonedOptions, - // Store - store: store, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise - }; - - // Debug - if (clonedOptions.debug) { - // Last ismaster - Object.defineProperty(this, 'replset', { - enumerable: true, - get: function() { - return coreTopology; - } - }); - } - } - - // Connect method - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = {}; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Clear out all the current handlers left over - var events = [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha' - ]; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Replset events relay - var replsetRelay = function(event) { - return function(t, server) { - self.emit(event, t, server.lastIsMaster(), server); - }; - }; - - // Relay ha - var relayHa = function(t, state) { - self.emit('ha', t, state); - - if (t === 'start') { - self.emit('ha_connect', t, state); - } else if (t === 'end') { - self.emit('ha_ismaster', t, state); - } - }; - - // Set up serverConfig listeners - self.s.coreTopology.on('joined', replsetRelay('joined')); - self.s.coreTopology.on('left', relay('left')); - self.s.coreTopology.on('ping', relay('ping')); - self.s.coreTopology.on('ha', relayHa); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - - self.s.coreTopology.on('fullsetup', function() { - self.emit('fullsetup', self, self); - }); - - self.s.coreTopology.on('all', function() { - self.emit('all', null, self); - }); - - // Connect handler - var connectHandler = function() { - // Set up listeners - self.s.coreTopology.once('timeout', errorHandler('timeout')); - self.s.coreTopology.once('error', errorHandler('error')); - self.s.coreTopology.once('close', errorHandler('close')); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - ['timeout', 'error', 'close'].forEach(function(e) { - self.s.coreTopology.removeListener(e, connectErrorHandler); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - // Destroy the replset - self.s.coreTopology.destroy(); - - // Try to callback - try { - callback(err); - } catch (err) { - if (!self.s.coreTopology.isConnected()) - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Set up listeners - self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); - self.s.coreTopology.once('error', connectErrorHandler('error')); - self.s.coreTopology.once('close', connectErrorHandler('close')); - self.s.coreTopology.once('connect', connectHandler); - - // Start connection - self.s.coreTopology.connect(_options); - } - - close(forceClosed, callback) { - ['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e)); - super.close(forceClosed, callback); - } -} - -Object.defineProperty(ReplSet.prototype, 'haInterval', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.haInterval; - } -}); - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * The replset high availability event - * - * @event ReplSet#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * ReplSet open event, emitted when replicaset can start processing commands. - * - * @event ReplSet#open - * @type {Replset} - */ - -/** - * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. - * - * @event ReplSet#fullsetup - * @type {Replset} - */ - -/** - * ReplSet close event - * - * @event ReplSet#close - * @type {object} - */ - -/** - * ReplSet error event, emitted if there is an error listener. - * - * @event ReplSet#error - * @type {MongoError} - */ - -/** - * ReplSet timeout event - * - * @event ReplSet#timeout - * @type {object} - */ - -/** - * ReplSet parseError event - * - * @event ReplSet#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event ReplSet#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event ReplSet#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event ReplSet#commandFailed - * @type {object} - */ - -module.exports = ReplSet; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/topologies/server.js b/node_modules/mongoose/node_modules/mongodb/lib/topologies/server.js deleted file mode 100644 index 3079cb9..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/topologies/server.js +++ /dev/null @@ -1,448 +0,0 @@ -'use strict'; - -const CServer = require('../core').Server; -const Cursor = require('../cursor'); -const TopologyBase = require('./topology_base').TopologyBase; -const Store = require('./topology_base').Store; -const MongoError = require('../core').MongoError; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **Server** class is a class that represents a single server topology and is - * used to construct connections. - * - * **Server Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'acceptableLatencyMS', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCRL', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'family', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'reconnectInterval', - 'monitoring', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'compression', - 'promiseLibrary', - 'monitorCommands' -]; - -/** - * Creates a new Server instance - * @class - * @deprecated - * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. - * @param {number} [port] The server port if IP4. - * @param {object} [options] Optional settings. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error. - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=10000] How long to wait for a connection to be established before timing out - * @param {number} [options.socketOptions.socketTimeoutMS=360000] How long a send or receive on a socket can take before timing out - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.monitoring=true] Triggers the server instance to call ismaster - * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @fires Server#commandStarted - * @fires Server#commandSucceeded - * @fires Server#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {Server} a Server instance. - */ -class Server extends TopologyBase { - constructor(host, port, options) { - super(); - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Promise library - const promiseLibrary = options.promiseLibrary; - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Detect if we have a socket connection - if (host.indexOf('/') !== -1) { - if (port != null && typeof port === 'object') { - options = port; - port = null; - } - } else if (port == null) { - throw MongoError.create({ message: 'port must be specified', driver: true }); - } - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - host: host, - port: port, - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Define the internal properties - this.s = { - // Create an instance of a server instance from core module - coreTopology: new CServer(clonedOptions), - // Server capabilities - sCapabilities: null, - // Cloned options - clonedOptions: clonedOptions, - // Reconnect - reconnect: clonedOptions.reconnect, - // Emit error - emitError: clonedOptions.emitError, - // Pool size - poolSize: clonedOptions.size, - // Store Options - storeOptions: storeOptions, - // Store - store: store, - // Host - host: host, - // Port - port: port, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: promiseLibrary || Promise - }; - } - - // Connect - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = this.s.clonedOptions; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.s.coreTopology.removeListener(e, connectHandlers[e]); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - - // Try to callback - try { - callback(err); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Error handler - var reconnectHandler = function() { - self.emit('reconnect', self); - self.s.store.execute(); - }; - - // Reconnect failed - var reconnectFailedHandler = function(err) { - self.emit('reconnectFailed', err); - self.s.store.flush(err); - }; - - // Destroy called on topology, perform cleanup - var destroyHandler = function() { - self.s.store.flush(); - }; - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - ['timeout', 'error', 'close', 'destroy'].forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up listeners - self.s.coreTopology.on('timeout', errorHandler('timeout')); - self.s.coreTopology.once('error', errorHandler('error')); - self.s.coreTopology.on('close', errorHandler('close')); - // Only called on destroy - self.s.coreTopology.on('destroy', destroyHandler); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Set up listeners - var connectHandlers = { - timeout: connectErrorHandler('timeout'), - error: connectErrorHandler('error'), - close: connectErrorHandler('close') - }; - - // Clear out all the current handlers left over - [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed' - ].forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Add the event handlers - self.s.coreTopology.once('timeout', connectHandlers.timeout); - self.s.coreTopology.once('error', connectHandlers.error); - self.s.coreTopology.once('close', connectHandlers.close); - self.s.coreTopology.once('connect', connectHandler); - // Reconnect server - self.s.coreTopology.on('reconnect', reconnectHandler); - self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect')); - self.s.coreTopology.on('monitoring', relay('monitoring')); - - // Start connection - self.s.coreTopology.connect(_options); - } -} - -Object.defineProperty(Server.prototype, 'poolSize', { - enumerable: true, - get: function() { - return this.s.coreTopology.connections().length; - } -}); - -Object.defineProperty(Server.prototype, 'autoReconnect', { - enumerable: true, - get: function() { - return this.s.reconnect; - } -}); - -Object.defineProperty(Server.prototype, 'host', { - enumerable: true, - get: function() { - return this.s.host; - } -}); - -Object.defineProperty(Server.prototype, 'port', { - enumerable: true, - get: function() { - return this.s.port; - } -}); - -/** - * Server connect event - * - * @event Server#connect - * @type {object} - */ - -/** - * Server close event - * - * @event Server#close - * @type {object} - */ - -/** - * Server reconnect event - * - * @event Server#reconnect - * @type {object} - */ - -/** - * Server error event - * - * @event Server#error - * @type {MongoError} - */ - -/** - * Server timeout event - * - * @event Server#timeout - * @type {object} - */ - -/** - * Server parseError event - * - * @event Server#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Server#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Server#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Server#commandFailed - * @type {object} - */ - -module.exports = Server; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/topologies/topology_base.js b/node_modules/mongoose/node_modules/mongodb/lib/topologies/topology_base.js deleted file mode 100644 index 967b4cd..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/topologies/topology_base.js +++ /dev/null @@ -1,417 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'), - MongoError = require('../core').MongoError, - f = require('util').format, - translateReadPreference = require('../utils').translateReadPreference, - ClientSession = require('../core').Sessions.ClientSession; - -// The store of ops -var Store = function(topology, storeOptions) { - var self = this; - var storedOps = []; - storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; - - // Internal state - this.s = { - storedOps: storedOps, - storeOptions: storeOptions, - topology: topology - }; - - Object.defineProperty(this, 'length', { - enumerable: true, - get: function() { - return self.s.storedOps.length; - } - }); -}; - -Store.prototype.add = function(opType, ns, ops, options, callback) { - if (this.s.storeOptions.force) { - return callback(MongoError.create({ message: 'db closed by application', driver: true })); - } - - if (this.s.storeOptions.bufferMaxEntries === 0) { - return callback( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - if ( - this.s.storeOptions.bufferMaxEntries > 0 && - this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries - ) { - while (this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - return; - } - - this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback }); -}; - -Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { - if (this.s.storeOptions.force) { - return callback(MongoError.create({ message: 'db closed by application', driver: true })); - } - - if (this.s.storeOptions.bufferMaxEntries === 0) { - return callback( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - if ( - this.s.storeOptions.bufferMaxEntries > 0 && - this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries - ) { - while (this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - return; - } - - this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback }); -}; - -Store.prototype.flush = function(err) { - while (this.s.storedOps.length > 0) { - this.s.storedOps - .shift() - .c( - err || - MongoError.create({ message: f('no connection available for operation'), driver: true }) - ); - } -}; - -var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; -var secondaryOptions = ['secondary', 'secondaryPreferred']; - -Store.prototype.execute = function(options) { - options = options || {}; - // Get current ops - var ops = this.s.storedOps; - // Reset the ops - this.s.storedOps = []; - - // Unpack options - var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true; - var executeSecondary = - typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true; - - // Execute all the stored ops - while (ops.length > 0) { - var op = ops.shift(); - - if (op.t === 'cursor') { - if (executePrimary && executeSecondary) { - op.o[op.m].apply(op.o, op.p); - } else if ( - executePrimary && - op.o.options && - op.o.options.readPreference && - primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 - ) { - op.o[op.m].apply(op.o, op.p); - } else if ( - !executePrimary && - executeSecondary && - op.o.options && - op.o.options.readPreference && - secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 - ) { - op.o[op.m].apply(op.o, op.p); - } - } else if (op.t === 'auth') { - this.s.topology[op.t].apply(this.s.topology, op.o); - } else { - if (executePrimary && executeSecondary) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if ( - executePrimary && - op.op && - op.op.readPreference && - primaryOptions.indexOf(op.op.readPreference.mode) !== -1 - ) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if ( - !executePrimary && - executeSecondary && - op.op && - op.op.readPreference && - secondaryOptions.indexOf(op.op.readPreference.mode) !== -1 - ) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } - } - } -}; - -Store.prototype.all = function() { - return this.s.storedOps; -}; - -// Server capabilities -var ServerCapabilities = function(ismaster) { - var setup_get_property = function(object, name, value) { - Object.defineProperty(object, name, { - enumerable: true, - get: function() { - return value; - } - }); - }; - - // Capabilities - var aggregationCursor = false; - var writeCommands = false; - var textSearch = false; - var authCommands = false; - var listCollections = false; - var listIndexes = false; - var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; - var commandsTakeWriteConcern = false; - var commandsTakeCollation = false; - - if (ismaster.minWireVersion >= 0) { - textSearch = true; - } - - if (ismaster.maxWireVersion >= 1) { - aggregationCursor = true; - authCommands = true; - } - - if (ismaster.maxWireVersion >= 2) { - writeCommands = true; - } - - if (ismaster.maxWireVersion >= 3) { - listCollections = true; - listIndexes = true; - } - - if (ismaster.maxWireVersion >= 5) { - commandsTakeWriteConcern = true; - commandsTakeCollation = true; - } - - // If no min or max wire version set to 0 - if (ismaster.minWireVersion == null) { - ismaster.minWireVersion = 0; - } - - if (ismaster.maxWireVersion == null) { - ismaster.maxWireVersion = 0; - } - - // Map up read only parameters - setup_get_property(this, 'hasAggregationCursor', aggregationCursor); - setup_get_property(this, 'hasWriteCommands', writeCommands); - setup_get_property(this, 'hasTextSearch', textSearch); - setup_get_property(this, 'hasAuthCommands', authCommands); - setup_get_property(this, 'hasListCollectionsCommand', listCollections); - setup_get_property(this, 'hasListIndexesCommand', listIndexes); - setup_get_property(this, 'minWireVersion', ismaster.minWireVersion); - setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion); - setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch); - setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern); - setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation); -}; - -class TopologyBase extends EventEmitter { - constructor() { - super(); - this.setMaxListeners(Infinity); - } - - // Sessions related methods - hasSessionSupport() { - return this.logicalSessionTimeoutMinutes != null; - } - - startSession(options, clientOptions) { - const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); - - session.once('ended', () => { - this.s.sessions.delete(session); - }); - - this.s.sessions.add(session); - return session; - } - - endSessions(sessions, callback) { - return this.s.coreTopology.endSessions(sessions, callback); - } - - get clientMetadata() { - return this.s.coreTopology.s.options.metadata; - } - - // Server capabilities - capabilities() { - if (this.s.sCapabilities) return this.s.sCapabilities; - if (this.s.coreTopology.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster()); - return this.s.sCapabilities; - } - - // Command - command(ns, cmd, options, callback) { - this.s.coreTopology.command(ns.toString(), cmd, translateReadPreference(options), callback); - } - - // Insert - insert(ns, ops, options, callback) { - this.s.coreTopology.insert(ns.toString(), ops, options, callback); - } - - // Update - update(ns, ops, options, callback) { - this.s.coreTopology.update(ns.toString(), ops, options, callback); - } - - // Remove - remove(ns, ops, options, callback) { - this.s.coreTopology.remove(ns.toString(), ops, options, callback); - } - - // IsConnected - isConnected(options) { - options = options || {}; - options = translateReadPreference(options); - - return this.s.coreTopology.isConnected(options); - } - - // IsDestroyed - isDestroyed() { - return this.s.coreTopology.isDestroyed(); - } - - // Cursor - cursor(ns, cmd, options) { - options = options || {}; - options = translateReadPreference(options); - options.disconnectHandler = this.s.store; - options.topology = this; - - return this.s.coreTopology.cursor(ns, cmd, options); - } - - lastIsMaster() { - return this.s.coreTopology.lastIsMaster(); - } - - selectServer(selector, options, callback) { - return this.s.coreTopology.selectServer(selector, options, callback); - } - - /** - * Unref all sockets - * @method - */ - unref() { - return this.s.coreTopology.unref(); - } - - /** - * All raw connections - * @method - * @return {array} - */ - connections() { - return this.s.coreTopology.connections(); - } - - close(forceClosed, callback) { - // If we have sessions, we want to individually move them to the session pool, - // and then send a single endSessions call. - this.s.sessions.forEach(session => session.endSession()); - - if (this.s.sessionPool) { - this.s.sessionPool.endAllPooledSessions(); - } - - // We need to wash out all stored processes - if (forceClosed === true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } - - this.s.coreTopology.destroy( - { - force: typeof forceClosed === 'boolean' ? forceClosed : false - }, - callback - ); - } -} - -// Properties -Object.defineProperty(TopologyBase.prototype, 'bson', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.bson; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'parserType', { - enumerable: true, - get: function() { - return this.s.coreTopology.parserType; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - return this.s.coreTopology.logicalSessionTimeoutMinutes; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'type', { - enumerable: true, - get: function() { - return this.s.coreTopology.type; - } -}); - -exports.Store = Store; -exports.ServerCapabilities = ServerCapabilities; -exports.TopologyBase = TopologyBase; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js b/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js deleted file mode 100644 index c0f10b4..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/url_parser.js +++ /dev/null @@ -1,623 +0,0 @@ -'use strict'; - -const ReadPreference = require('./core').ReadPreference, - parser = require('url'), - f = require('util').format, - Logger = require('./core').Logger, - dns = require('dns'); -const ReadConcern = require('./read_concern'); - -module.exports = function(url, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - let result; - try { - result = parser.parse(url, true); - } catch (e) { - return callback(new Error('URL malformed, cannot be parsed')); - } - - if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') { - return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`')); - } - - if (result.protocol === 'mongodb:') { - return parseHandler(url, options, callback); - } - - // Otherwise parse this as an SRV record - if (result.hostname.split('.').length < 3) { - return callback(new Error('URI does not have hostname, domain name and tld')); - } - - result.domainLength = result.hostname.split('.').length; - - if (result.pathname && result.pathname.match(',')) { - return callback(new Error('Invalid URI, cannot contain multiple hostnames')); - } - - if (result.port) { - return callback(new Error('Ports not accepted with `mongodb+srv` URIs')); - } - - let srvAddress = `_mongodb._tcp.${result.host}`; - dns.resolveSrv(srvAddress, function(err, addresses) { - if (err) return callback(err); - - if (addresses.length === 0) { - return callback(new Error('No addresses found at host')); - } - - for (let i = 0; i < addresses.length; i++) { - if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { - return callback(new Error('Server record does not share hostname with parent URI')); - } - } - - let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; - let connectionStrings = addresses.map(function(address, i) { - if (i === 0) return `${base}${address.name}:${address.port}`; - else return `${address.name}:${address.port}`; - }); - - let connectionString = connectionStrings.join(',') + '/'; - let connectionStringOptions = []; - - // Add the default database if needed - if (result.path) { - let defaultDb = result.path.slice(1); - if (defaultDb.indexOf('?') !== -1) { - defaultDb = defaultDb.slice(0, defaultDb.indexOf('?')); - } - - connectionString += defaultDb; - } - - // Default to SSL true - if (!options.ssl && !result.search) { - connectionStringOptions.push('ssl=true'); - } else if (!options.ssl && result.search && !result.search.match('ssl')) { - connectionStringOptions.push('ssl=true'); - } - - // Keep original uri options - if (result.search) { - connectionStringOptions.push(result.search.replace('?', '')); - } - - dns.resolveTxt(result.host, function(err, record) { - if (err && err.code !== 'ENODATA') return callback(err); - if (err && err.code === 'ENODATA') record = null; - - if (record) { - if (record.length > 1) { - return callback(new Error('Multiple text records not allowed')); - } - - record = record[0]; - if (record.length > 1) record = record.join(''); - else record = record[0]; - - if (!record.includes('authSource') && !record.includes('replicaSet')) { - return callback(new Error('Text record must only set `authSource` or `replicaSet`')); - } - - connectionStringOptions.push(record); - } - - // Add any options to the connection string - if (connectionStringOptions.length) { - connectionString += `?${connectionStringOptions.join('&')}`; - } - - parseHandler(connectionString, options, callback); - }); - }); -}; - -function matchesParentDomain(srvAddress, parentDomain) { - let regex = /^.*?\./; - let srv = `.${srvAddress.replace(regex, '')}`; - let parent = `.${parentDomain.replace(regex, '')}`; - if (srv.endsWith(parent)) return true; - else return false; -} - -function parseHandler(address, options, callback) { - let result, err; - try { - result = parseConnectionString(address, options); - } catch (e) { - err = e; - } - - return err ? callback(err, null) : callback(null, result); -} - -function parseConnectionString(url, options) { - // Variables - let connection_part = ''; - let auth_part = ''; - let query_string_part = ''; - let dbName = 'admin'; - - // Url parser result - let result = parser.parse(url, true); - if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) { - throw new Error('No hostname or hostnames provided in connection string'); - } - - if (result.port === '0') { - throw new Error('Invalid port (zero) with hostname'); - } - - if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { - throw new Error('Invalid port (larger than 65535) with hostname'); - } - - if ( - result.path && - result.path.length > 0 && - result.path[0] !== '/' && - url.indexOf('.sock') === -1 - ) { - throw new Error('Missing delimiting slash between hosts and options'); - } - - if (result.query) { - for (let name in result.query) { - if (name.indexOf('::') !== -1) { - throw new Error('Double colon in host identifier'); - } - - if (result.query[name] === '') { - throw new Error('Query parameter ' + name + ' is an incomplete value pair'); - } - } - } - - if (result.auth) { - let parts = result.auth.split(':'); - if (url.indexOf(result.auth) !== -1 && parts.length > 2) { - throw new Error('Username with password containing an unescaped colon'); - } - - if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) { - throw new Error('Username containing an unescaped at-sign'); - } - } - - // Remove query - let clean = url.split('?').shift(); - - // Extract the list of hosts - let strings = clean.split(','); - let hosts = []; - - for (let i = 0; i < strings.length; i++) { - let hostString = strings[i]; - - if (hostString.indexOf('mongodb') !== -1) { - if (hostString.indexOf('@') !== -1) { - hosts.push(hostString.split('@').pop()); - } else { - hosts.push(hostString.substr('mongodb://'.length)); - } - } else if (hostString.indexOf('/') !== -1) { - hosts.push(hostString.split('/').shift()); - } else if (hostString.indexOf('/') === -1) { - hosts.push(hostString.trim()); - } - } - - for (let i = 0; i < hosts.length; i++) { - let r = parser.parse(f('mongodb://%s', hosts[i].trim())); - if (r.path && r.path.indexOf('.sock') !== -1) continue; - if (r.path && r.path.indexOf(':') !== -1) { - // Not connecting to a socket so check for an extra slash in the hostname. - // Using String#split as perf is better than match. - if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) { - throw new Error('Slash in host identifier'); - } else { - throw new Error('Double colon in host identifier'); - } - } - } - - // If we have a ? mark cut the query elements off - if (url.indexOf('?') !== -1) { - query_string_part = url.substr(url.indexOf('?') + 1); - connection_part = url.substring('mongodb://'.length, url.indexOf('?')); - } else { - connection_part = url.substring('mongodb://'.length); - } - - // Check if we have auth params - if (connection_part.indexOf('@') !== -1) { - auth_part = connection_part.split('@')[0]; - connection_part = connection_part.split('@')[1]; - } - - // Check there is not more than one unescaped slash - if (connection_part.split('/').length > 2) { - throw new Error( - "Unsupported host '" + - connection_part.split('?')[0] + - "', hosts must be URL encoded and contain at most one unencoded slash" - ); - } - - // Check if the connection string has a db - if (connection_part.indexOf('.sock') !== -1) { - if (connection_part.indexOf('.sock/') !== -1) { - dbName = connection_part.split('.sock/')[1]; - // Check if multiple database names provided, or just an illegal trailing backslash - if (dbName.indexOf('/') !== -1) { - if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - connection_part = connection_part.split( - '/', - connection_part.indexOf('.sock') + '.sock'.length - ); - } - } else if (connection_part.indexOf('/') !== -1) { - // Check if multiple database names provided, or just an illegal trailing backslash - if (connection_part.split('/').length > 2) { - if (connection_part.split('/')[2].length === 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - dbName = connection_part.split('/')[1]; - connection_part = connection_part.split('/')[0]; - } - - // URI decode the host information - connection_part = decodeURIComponent(connection_part); - - // Result object - let object = {}; - - // Pick apart the authentication part of the string - let authPart = auth_part || ''; - let auth = authPart.split(':', 2); - - // Decode the authentication URI components and verify integrity - let user = decodeURIComponent(auth[0]); - if (auth[0] !== encodeURIComponent(user)) { - throw new Error('Username contains an illegal unescaped character'); - } - auth[0] = user; - - if (auth[1]) { - let pass = decodeURIComponent(auth[1]); - if (auth[1] !== encodeURIComponent(pass)) { - throw new Error('Password contains an illegal unescaped character'); - } - auth[1] = pass; - } - - // Add auth to final object if we have 2 elements - if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] }; - // if user provided auth options, use that - if (options && options.auth != null) object.auth = options.auth; - - // Variables used for temporary storage - let hostPart; - let urlOptions; - let servers; - let compression; - let serverOptions = { socketOptions: {} }; - let dbOptions = { read_preference_tags: [] }; - let replSetServersOptions = { socketOptions: {} }; - let mongosOptions = { socketOptions: {} }; - // Add server options to final object - object.server_options = serverOptions; - object.db_options = dbOptions; - object.rs_options = replSetServersOptions; - object.mongos_options = mongosOptions; - - // Let's check if we are using a domain socket - if (url.match(/\.sock/)) { - // Split out the socket part - let domainSocket = url.substring( - url.indexOf('mongodb://') + 'mongodb://'.length, - url.lastIndexOf('.sock') + '.sock'.length - ); - // Clean out any auth stuff if any - if (domainSocket.indexOf('@') !== -1) domainSocket = domainSocket.split('@')[1]; - domainSocket = decodeURIComponent(domainSocket); - servers = [{ domain_socket: domainSocket }]; - } else { - // Split up the db - hostPart = connection_part; - // Deduplicate servers - let deduplicatedServers = {}; - - // Parse all server results - servers = hostPart - .split(',') - .map(function(h) { - let _host, _port, ipv6match; - //check if it matches [IPv6]:port, where the port number is optional - if ((ipv6match = /\[([^\]]+)\](?::(.+))?/.exec(h))) { - _host = ipv6match[1]; - _port = parseInt(ipv6match[2], 10) || 27017; - } else { - //otherwise assume it's IPv4, or plain hostname - let hostPort = h.split(':', 2); - _host = hostPort[0] || 'localhost'; - _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; - // Check for localhost?safe=true style case - if (_host.indexOf('?') !== -1) _host = _host.split(/\?/)[0]; - } - - // No entry returned for duplicate server - if (deduplicatedServers[_host + '_' + _port]) return null; - deduplicatedServers[_host + '_' + _port] = 1; - - // Return the mapped object - return { host: _host, port: _port }; - }) - .filter(function(x) { - return x != null; - }); - } - - // Get the db name - object.dbName = dbName || 'admin'; - // Split up all the options - urlOptions = (query_string_part || '').split(/[&;]/); - // Ugh, we have to figure out which options go to which constructor manually. - urlOptions.forEach(function(opt) { - if (!opt) return; - var splitOpt = opt.split('='), - name = splitOpt[0], - value = splitOpt[1]; - - // Options implementations - switch (name) { - case 'slaveOk': - case 'slave_ok': - serverOptions.slave_ok = value === 'true'; - dbOptions.slaveOk = value === 'true'; - break; - case 'maxPoolSize': - case 'poolSize': - serverOptions.poolSize = parseInt(value, 10); - replSetServersOptions.poolSize = parseInt(value, 10); - break; - case 'appname': - object.appname = decodeURIComponent(value); - break; - case 'autoReconnect': - case 'auto_reconnect': - serverOptions.auto_reconnect = value === 'true'; - break; - case 'ssl': - if (value === 'prefer') { - serverOptions.ssl = value; - replSetServersOptions.ssl = value; - mongosOptions.ssl = value; - break; - } - serverOptions.ssl = value === 'true'; - replSetServersOptions.ssl = value === 'true'; - mongosOptions.ssl = value === 'true'; - break; - case 'sslValidate': - serverOptions.sslValidate = value === 'true'; - replSetServersOptions.sslValidate = value === 'true'; - mongosOptions.sslValidate = value === 'true'; - break; - case 'replicaSet': - case 'rs_name': - replSetServersOptions.rs_name = value; - break; - case 'reconnectWait': - replSetServersOptions.reconnectWait = parseInt(value, 10); - break; - case 'retries': - replSetServersOptions.retries = parseInt(value, 10); - break; - case 'readSecondary': - case 'read_secondary': - replSetServersOptions.read_secondary = value === 'true'; - break; - case 'fsync': - dbOptions.fsync = value === 'true'; - break; - case 'journal': - dbOptions.j = value === 'true'; - break; - case 'safe': - dbOptions.safe = value === 'true'; - break; - case 'nativeParser': - case 'native_parser': - dbOptions.native_parser = value === 'true'; - break; - case 'readConcernLevel': - dbOptions.readConcern = new ReadConcern(value); - break; - case 'connectTimeoutMS': - serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - break; - case 'socketTimeoutMS': - serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - break; - case 'w': - dbOptions.w = parseInt(value, 10); - if (isNaN(dbOptions.w)) dbOptions.w = value; - break; - case 'authSource': - dbOptions.authSource = value; - break; - case 'gssapiServiceName': - dbOptions.gssapiServiceName = value; - break; - case 'authMechanism': - if (value === 'GSSAPI') { - // If no password provided decode only the principal - if (object.auth == null) { - let urlDecodeAuthPart = decodeURIComponent(authPart); - if (urlDecodeAuthPart.indexOf('@') === -1) - throw new Error('GSSAPI requires a provided principal'); - object.auth = { user: urlDecodeAuthPart, password: null }; - } else { - object.auth.user = decodeURIComponent(object.auth.user); - } - } else if (value === 'MONGODB-X509') { - object.auth = { user: decodeURIComponent(authPart) }; - } - - // Only support GSSAPI or MONGODB-CR for now - if ( - value !== 'GSSAPI' && - value !== 'MONGODB-X509' && - value !== 'MONGODB-CR' && - value !== 'DEFAULT' && - value !== 'SCRAM-SHA-1' && - value !== 'SCRAM-SHA-256' && - value !== 'PLAIN' - ) - throw new Error( - 'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism' - ); - - // Authentication mechanism - dbOptions.authMechanism = value; - break; - case 'authMechanismProperties': - { - // Split up into key, value pairs - let values = value.split(','); - let o = {}; - // For each value split into key, value - values.forEach(function(x) { - let v = x.split(':'); - o[v[0]] = v[1]; - }); - - // Set all authMechanismProperties - dbOptions.authMechanismProperties = o; - // Set the service name value - if (typeof o.SERVICE_NAME === 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; - if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; - if (typeof o.CANONICALIZE_HOST_NAME === 'string') - dbOptions.gssapiCanonicalizeHostName = - o.CANONICALIZE_HOST_NAME === 'true' ? true : false; - } - break; - case 'wtimeoutMS': - dbOptions.wtimeout = parseInt(value, 10); - break; - case 'readPreference': - if (!ReadPreference.isValid(value)) - throw new Error( - 'readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest' - ); - dbOptions.readPreference = value; - break; - case 'maxStalenessSeconds': - dbOptions.maxStalenessSeconds = parseInt(value, 10); - break; - case 'readPreferenceTags': - { - // Decode the value - value = decodeURIComponent(value); - // Contains the tag object - let tagObject = {}; - if (value == null || value === '') { - dbOptions.read_preference_tags.push(tagObject); - break; - } - - // Split up the tags - let tags = value.split(/,/); - for (let i = 0; i < tags.length; i++) { - let parts = tags[i].trim().split(/:/); - tagObject[parts[0]] = parts[1]; - } - - // Set the preferences tags - dbOptions.read_preference_tags.push(tagObject); - } - break; - case 'compressors': - { - compression = serverOptions.compression || {}; - let compressors = value.split(','); - if ( - !compressors.every(function(compressor) { - return compressor === 'snappy' || compressor === 'zlib'; - }) - ) { - throw new Error('Compressors must be at least one of snappy or zlib'); - } - - compression.compressors = compressors; - serverOptions.compression = compression; - } - break; - case 'zlibCompressionLevel': - { - compression = serverOptions.compression || {}; - let zlibCompressionLevel = parseInt(value, 10); - if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) { - throw new Error('zlibCompressionLevel must be an integer between -1 and 9'); - } - - compression.zlibCompressionLevel = zlibCompressionLevel; - serverOptions.compression = compression; - } - break; - case 'retryWrites': - dbOptions.retryWrites = value === 'true'; - break; - case 'minSize': - dbOptions.minSize = parseInt(value, 10); - break; - default: - { - let logger = Logger('URL Parser'); - logger.warn(`${name} is not supported as a connection string option`); - } - break; - } - }); - - // No tags: should be null (not []) - if (dbOptions.read_preference_tags.length === 0) { - dbOptions.read_preference_tags = null; - } - - // Validate if there are an invalid write concern combinations - if ( - (dbOptions.w === -1 || dbOptions.w === 0) && - (dbOptions.journal === true || dbOptions.fsync === true || dbOptions.safe === true) - ) - throw new Error('w set to -1 or 0 cannot be combined with safe/w/journal/fsync'); - - // If no read preference set it to primary - if (!dbOptions.readPreference) { - dbOptions.readPreference = 'primary'; - } - - // make sure that user-provided options are applied with priority - dbOptions = Object.assign(dbOptions, options); - - // Add servers to result - object.servers = servers; - - // Returned parsed object - return object; -} diff --git a/node_modules/mongoose/node_modules/mongodb/lib/utils.js b/node_modules/mongoose/node_modules/mongodb/lib/utils.js deleted file mode 100644 index 1eded66..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/utils.js +++ /dev/null @@ -1,768 +0,0 @@ -'use strict'; -const MongoError = require('./core/error').MongoError; -const ReadPreference = require('./core/topologies/read_preference'); -const WriteConcern = require('./write_concern'); - -var shallowClone = function(obj) { - var copy = {}; - for (var name in obj) copy[name] = obj[name]; - return copy; -}; - -// Figure out the read preference -var translateReadPreference = function(options) { - var r = null; - if (options.readPreference) { - r = options.readPreference; - } else { - return options; - } - - if (typeof r === 'string') { - options.readPreference = new ReadPreference(r); - } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { - const mode = r.mode || r.preference; - if (mode && typeof mode === 'string') { - options.readPreference = new ReadPreference(mode, r.tags, { - maxStalenessSeconds: r.maxStalenessSeconds - }); - } - } else if (!(r instanceof ReadPreference)) { - throw new TypeError('Invalid read preference: ' + r); - } - - return options; -}; - -// Set simple property -var getSingleProperty = function(obj, name, value) { - Object.defineProperty(obj, name, { - enumerable: true, - get: function() { - return value; - } - }); -}; - -var formatSortValue = (exports.formatSortValue = function(sortDirection) { - var value = ('' + sortDirection).toLowerCase(); - - switch (value) { - case 'ascending': - case 'asc': - case '1': - return 1; - case 'descending': - case 'desc': - case '-1': - return -1; - default: - throw new Error( - 'Illegal sort clause, must be of the form ' + - "[['field1', '(ascending|descending)'], " + - "['field2', '(ascending|descending)']]" - ); - } -}); - -var formattedOrderClause = (exports.formattedOrderClause = function(sortValue) { - var orderBy = {}; - if (sortValue == null) return null; - if (Array.isArray(sortValue)) { - if (sortValue.length === 0) { - return null; - } - - for (var i = 0; i < sortValue.length; i++) { - if (sortValue[i].constructor === String) { - orderBy[sortValue[i]] = 1; - } else { - orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); - } - } - } else if (sortValue != null && typeof sortValue === 'object') { - orderBy = sortValue; - } else if (typeof sortValue === 'string') { - orderBy[sortValue] = 1; - } else { - throw new Error( - 'Illegal sort clause, must be of the form ' + - "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" - ); - } - - return orderBy; -}); - -var checkCollectionName = function checkCollectionName(collectionName) { - if ('string' !== typeof collectionName) { - throw new MongoError('collection name must be a String'); - } - - if (!collectionName || collectionName.indexOf('..') !== -1) { - throw new MongoError('collection names cannot be empty'); - } - - if ( - collectionName.indexOf('$') !== -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null - ) { - throw new MongoError("collection names must not contain '$'"); - } - - if (collectionName.match(/^\.|\.$/) != null) { - throw new MongoError("collection names must not start or end with '.'"); - } - - // Validate that we are not passing 0x00 in the collection name - if (collectionName.indexOf('\x00') !== -1) { - throw new MongoError('collection names cannot contain a null character'); - } -}; - -var handleCallback = function(callback, err, value1, value2) { - try { - if (callback == null) return; - - if (callback) { - return value2 ? callback(err, value1, value2) : callback(err, value1); - } - } catch (err) { - process.nextTick(function() { - throw err; - }); - return false; - } - - return true; -}; - -/** - * Wrap a Mongo error document in an Error instance - * @ignore - * @api private - */ -var toError = function(error) { - if (error instanceof Error) return error; - - var msg = error.err || error.errmsg || error.errMessage || error; - var e = MongoError.create({ message: msg, driver: true }); - - // Get all object keys - var keys = typeof error === 'object' ? Object.keys(error) : []; - - for (var i = 0; i < keys.length; i++) { - try { - e[keys[i]] = error[keys[i]]; - } catch (err) { - // continue - } - } - - return e; -}; - -/** - * @ignore - */ -var normalizeHintField = function normalizeHintField(hint) { - var finalHint = null; - - if (typeof hint === 'string') { - finalHint = hint; - } else if (Array.isArray(hint)) { - finalHint = {}; - - hint.forEach(function(param) { - finalHint[param] = 1; - }); - } else if (hint != null && typeof hint === 'object') { - finalHint = {}; - for (var name in hint) { - finalHint[name] = hint[name]; - } - } - - return finalHint; -}; - -/** - * Create index name based on field spec - * - * @ignore - * @api private - */ -var parseIndexOptions = function(fieldOrSpec) { - var fieldHash = {}; - var indexes = []; - var keys; - - // Get all the fields accordingly - if ('string' === typeof fieldOrSpec) { - // 'type' - indexes.push(fieldOrSpec + '_' + 1); - fieldHash[fieldOrSpec] = 1; - } else if (Array.isArray(fieldOrSpec)) { - fieldOrSpec.forEach(function(f) { - if ('string' === typeof f) { - // [{location:'2d'}, 'type'] - indexes.push(f + '_' + 1); - fieldHash[f] = 1; - } else if (Array.isArray(f)) { - // [['location', '2d'],['type', 1]] - indexes.push(f[0] + '_' + (f[1] || 1)); - fieldHash[f[0]] = f[1] || 1; - } else if (isObject(f)) { - // [{location:'2d'}, {type:1}] - keys = Object.keys(f); - keys.forEach(function(k) { - indexes.push(k + '_' + f[k]); - fieldHash[k] = f[k]; - }); - } else { - // undefined (ignore) - } - }); - } else if (isObject(fieldOrSpec)) { - // {location:'2d', type:1} - keys = Object.keys(fieldOrSpec); - keys.forEach(function(key) { - indexes.push(key + '_' + fieldOrSpec[key]); - fieldHash[key] = fieldOrSpec[key]; - }); - } - - return { - name: indexes.join('_'), - keys: keys, - fieldHash: fieldHash - }; -}; - -var isObject = (exports.isObject = function(arg) { - return '[object Object]' === Object.prototype.toString.call(arg); -}); - -var debugOptions = function(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -}; - -var decorateCommand = function(command, options, exclude) { - for (var name in options) { - if (exclude.indexOf(name) === -1) command[name] = options[name]; - } - - return command; -}; - -var mergeOptions = function(target, source) { - for (var name in source) { - target[name] = source[name]; - } - - return target; -}; - -// Merge options with translation -var translateOptions = function(target, source) { - var translations = { - // SSL translation options - sslCA: 'ca', - sslCRL: 'crl', - sslValidate: 'rejectUnauthorized', - sslKey: 'key', - sslCert: 'cert', - sslPass: 'passphrase', - // SocketTimeout translation options - socketTimeoutMS: 'socketTimeout', - connectTimeoutMS: 'connectionTimeout', - // Replicaset options - replicaSet: 'setName', - rs_name: 'setName', - secondaryAcceptableLatencyMS: 'acceptableLatency', - connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', - // Mongos options - acceptableLatencyMS: 'localThresholdMS' - }; - - for (var name in source) { - if (translations[name]) { - target[translations[name]] = source[name]; - } else { - target[name] = source[name]; - } - } - - return target; -}; - -var filterOptions = function(options, names) { - var filterOptions = {}; - - for (var name in options) { - if (names.indexOf(name) !== -1) filterOptions[name] = options[name]; - } - - // Filtered options - return filterOptions; -}; - -// Write concern keys -var writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync']; - -// Merge the write concern options -var mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) { - // Mix in any allowed options - for (var i = 0; i < keys.length; i++) { - if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) { - targetOptions[keys[i]] = sourceOptions[keys[i]]; - } - } - - // No merging of write concern - if (!mergeWriteConcern) return targetOptions; - - // Found no write Concern options - var found = false; - for (i = 0; i < writeConcernKeys.length; i++) { - if (targetOptions[writeConcernKeys[i]]) { - found = true; - break; - } - } - - if (!found) { - for (i = 0; i < writeConcernKeys.length; i++) { - if (sourceOptions[writeConcernKeys[i]]) { - targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; - } - } - } - - return targetOptions; -}; - -/** - * Executes the given operation with provided arguments. - * - * This method reduces large amounts of duplication in the entire codebase by providing - * a single point for determining whether callbacks or promises should be used. Additionally - * it allows for a single point of entry to provide features such as implicit sessions, which - * are required by the Driver Sessions specification in the event that a ClientSession is - * not provided - * - * @param {object} topology The topology to execute this operation on - * @param {function} operation The operation to execute - * @param {array} args Arguments to apply the provided operation - * @param {object} [options] Options that modify the behavior of the method - */ -const executeLegacyOperation = (topology, operation, args, options) => { - if (topology == null) { - throw new TypeError('This method requires a valid topology instance'); - } - - if (!Array.isArray(args)) { - throw new TypeError('This method requires an array of arguments to apply'); - } - - options = options || {}; - const Promise = topology.s.promiseLibrary; - let callback = args[args.length - 1]; - - // The driver sessions spec mandates that we implicitly create sessions for operations - // that are not explicitly provided with a session. - let session, opOptions, owner; - if (!options.skipSessions && topology.hasSessionSupport()) { - opOptions = args[args.length - 2]; - if (opOptions == null || opOptions.session == null) { - owner = Symbol(); - session = topology.startSession({ owner }); - const optionsIndex = args.length - 2; - args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session }); - } else if (opOptions.session && opOptions.session.hasEnded) { - throw new MongoError('Use of expired sessions is not permitted'); - } - } - - const makeExecuteCallback = (resolve, reject) => - function executeCallback(err, result) { - if (session && session.owner === owner && !options.returnsCursor) { - session.endSession(() => { - delete opOptions.session; - if (err) return reject(err); - resolve(result); - }); - } else { - if (err) return reject(err); - resolve(result); - } - }; - - // Execute using callback - if (typeof callback === 'function') { - callback = args.pop(); - const handler = makeExecuteCallback( - result => callback(null, result), - err => callback(err, null) - ); - args.push(handler); - - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - throw e; - } - } - - // Return a Promise - if (args[args.length - 1] != null) { - throw new TypeError('final argument to `executeLegacyOperation` must be a callback'); - } - - return new Promise(function(resolve, reject) { - const handler = makeExecuteCallback(resolve, reject); - args[args.length - 1] = handler; - - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - } - }); -}; - -/** - * Applies retryWrites: true to a command if retryWrites is set on the command's database. - * - * @param {object} target The target command to which we will apply retryWrites. - * @param {object} db The database from which we can inherit a retryWrites value. - */ -function applyRetryableWrites(target, db) { - if (db && db.s.options.retryWrites) { - target.retryWrites = true; - } - - return target; -} - -/** - * Applies a write concern to a command based on well defined inheritance rules, optionally - * detecting support for the write concern in the first place. - * - * @param {Object} target the target command we will be applying the write concern to - * @param {Object} sources sources where we can inherit default write concerns from - * @param {Object} [options] optional settings passed into a command for write concern overrides - * @returns {Object} the (now) decorated target - */ -function applyWriteConcern(target, sources, options) { - options = options || {}; - const db = sources.db; - const coll = sources.collection; - - if (options.session && options.session.inTransaction()) { - // writeConcern is not allowed within a multi-statement transaction - if (target.writeConcern) { - delete target.writeConcern; - } - - return target; - } - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern) { - return Object.assign(target, { writeConcern }); - } - - if (coll && coll.writeConcern) { - return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); - } - - if (db && db.writeConcern) { - return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); - } - - return target; -} - -/** - * Resolves a read preference based on well-defined inheritance rules. This method will not only - * determine the read preference (if there is one), but will also ensure the returned value is a - * properly constructed instance of `ReadPreference`. - * - * @param {Collection|Db|MongoClient} parent The parent of the operation on which to determine the read - * preference, used for determining the inherited read preference. - * @param {Object} options The options passed into the method, potentially containing a read preference - * @returns {(ReadPreference|null)} The resolved read preference - */ -function resolveReadPreference(parent, options) { - options = options || {}; - const session = options.session; - - const inheritedReadPreference = parent.readPreference; - - let readPreference; - if (options.readPreference) { - readPreference = ReadPreference.fromOptions(options); - } else if (session && session.inTransaction() && session.transaction.options.readPreference) { - // The transaction’s read preference MUST override all other user configurable read preferences. - readPreference = session.transaction.options.readPreference; - } else if (inheritedReadPreference != null) { - readPreference = inheritedReadPreference; - } else { - throw new Error('No readPreference was provided or inherited.'); - } - - return typeof readPreference === 'string' ? new ReadPreference(readPreference) : readPreference; -} - -/** - * Checks if a given value is a Promise - * - * @param {*} maybePromise - * @return true if the provided value is a Promise - */ -function isPromiseLike(maybePromise) { - return maybePromise && typeof maybePromise.then === 'function'; -} - -/** - * Applies collation to a given command. - * - * @param {object} [command] the command on which to apply collation - * @param {(Cursor|Collection)} [target] target of command - * @param {object} [options] options containing collation settings - */ -function decorateWithCollation(command, target, options) { - const topology = (target.s && target.s.topology) || target.topology; - - if (!topology) { - throw new TypeError('parameter "target" is missing a topology'); - } - - const capabilities = topology.capabilities(); - if (options.collation && typeof options.collation === 'object') { - if (capabilities && capabilities.commandsTakeCollation) { - command.collation = options.collation; - } else { - throw new MongoError(`Current topology does not support collation`); - } - } -} - -/** - * Applies a read concern to a given command. - * - * @param {object} command the command on which to apply the read concern - * @param {Collection} coll the parent collection of the operation calling this method - */ -function decorateWithReadConcern(command, coll, options) { - if (options && options.session && options.session.inTransaction()) { - return; - } - let readConcern = Object.assign({}, command.readConcern || {}); - if (coll.s.readConcern) { - Object.assign(readConcern, coll.s.readConcern); - } - - if (Object.keys(readConcern).length > 0) { - Object.assign(command, { readConcern: readConcern }); - } -} - -const emitProcessWarning = msg => process.emitWarning(msg, 'DeprecationWarning'); -const emitConsoleWarning = msg => console.error(msg); -const emitDeprecationWarning = process.emitWarning ? emitProcessWarning : emitConsoleWarning; - -/** - * Default message handler for generating deprecation warnings. - * - * @param {string} name function name - * @param {string} option option name - * @return {string} warning message - * @ignore - * @api private - */ -function defaultMsgHandler(name, option) { - return `${name} option [${option}] is deprecated and will be removed in a later version.`; -} - -/** - * Deprecates a given function's options. - * - * @param {object} config configuration for deprecation - * @param {string} config.name function name - * @param {Array} config.deprecatedOptions options to deprecate - * @param {number} config.optionsIndex index of options object in function arguments array - * @param {function} [config.msgHandler] optional custom message handler to generate warnings - * @param {function} fn the target function of deprecation - * @return {function} modified function that warns once per deprecated option, and executes original function - * @ignore - * @api private - */ -function deprecateOptions(config, fn) { - if (process.noDeprecation === true) { - return fn; - } - - const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; - - const optionsWarned = new Set(); - function deprecated() { - const options = arguments[config.optionsIndex]; - - // ensure options is a valid, non-empty object, otherwise short-circuit - if (!isObject(options) || Object.keys(options).length === 0) { - return fn.apply(this, arguments); - } - - config.deprecatedOptions.forEach(deprecatedOption => { - if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) { - optionsWarned.add(deprecatedOption); - const msg = msgHandler(config.name, deprecatedOption); - emitDeprecationWarning(msg); - if (this && this.getLogger) { - const logger = this.getLogger(); - if (logger) { - logger.warn(msg); - } - } - } - }); - - return fn.apply(this, arguments); - } - - // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 - // The wrapper will keep the same prototype as fn to maintain prototype chain - Object.setPrototypeOf(deprecated, fn); - if (fn.prototype) { - // Setting this (rather than using Object.setPrototype, as above) ensures - // that calling the unwrapped constructor gives an instanceof the wrapped - // constructor. - deprecated.prototype = fn.prototype; - } - - return deprecated; -} - -const SUPPORTS = {}; -// Test asyncIterator support -try { - require('./async/async_iterator'); - SUPPORTS.ASYNC_ITERATOR = true; -} catch (e) { - SUPPORTS.ASYNC_ITERATOR = false; -} - -class MongoDBNamespace { - constructor(db, collection) { - this.db = db; - this.collection = collection; - } - - toString() { - return this.collection ? `${this.db}.${this.collection}` : this.db; - } - - withCollection(collection) { - return new MongoDBNamespace(this.db, collection); - } - - static fromString(namespace) { - if (!namespace) { - throw new Error(`Cannot parse namespace from "${namespace}"`); - } - - const index = namespace.indexOf('.'); - return new MongoDBNamespace(namespace.substring(0, index), namespace.substring(index + 1)); - } -} - -function* makeCounter(seed) { - let count = seed || 0; - while (true) { - const newCount = count; - count += 1; - yield newCount; - } -} - -/** - * Helper function for either accepting a callback, or returning a promise - * - * @param {Object} parent an instance of parent with promiseLibrary. - * @param {object} parent.s an object containing promiseLibrary. - * @param {function} parent.s.promiseLibrary an object containing promiseLibrary. - * @param {[Function]} callback an optional callback. - * @param {Function} fn A function that takes a callback - * @returns {Promise|void} Returns nothing if a callback is supplied, else returns a Promise. - */ -function maybePromise(parent, callback, fn) { - const PromiseLibrary = (parent && parent.s && parent.s.promiseLibrary) || Promise; - - let result; - if (typeof callback !== 'function') { - result = new PromiseLibrary((resolve, reject) => { - callback = (err, res) => { - if (err) return reject(err); - resolve(res); - }; - }); - } - - fn(function(err, res) { - if (err != null) { - try { - callback(err); - } catch (error) { - return process.nextTick(() => { - throw error; - }); - } - return; - } - - callback(err, res); - }); - - return result; -} - -module.exports = { - filterOptions, - mergeOptions, - translateOptions, - shallowClone, - getSingleProperty, - checkCollectionName, - toError, - formattedOrderClause, - parseIndexOptions, - normalizeHintField, - handleCallback, - decorateCommand, - isObject, - debugOptions, - MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1, - mergeOptionsAndWriteConcern, - translateReadPreference, - executeLegacyOperation, - applyRetryableWrites, - applyWriteConcern, - isPromiseLike, - decorateWithCollation, - decorateWithReadConcern, - deprecateOptions, - SUPPORTS, - MongoDBNamespace, - resolveReadPreference, - emitDeprecationWarning, - makeCounter, - maybePromise -}; diff --git a/node_modules/mongoose/node_modules/mongodb/lib/write_concern.js b/node_modules/mongoose/node_modules/mongodb/lib/write_concern.js deleted file mode 100644 index 79b0f09..0000000 --- a/node_modules/mongoose/node_modules/mongodb/lib/write_concern.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -/** - * The **WriteConcern** class is a class that represents a MongoDB WriteConcern. - * @class - * @property {(number|string)} w The write concern - * @property {number} wtimeout The write concern timeout - * @property {boolean} j The journal write concern - * @property {boolean} fsync The file sync write concern - * @see https://docs.mongodb.com/manual/reference/write-concern/index.html - */ -class WriteConcern { - /** - * Constructs a WriteConcern from the write concern properties. - * @param {(number|string)} [w] The write concern - * @param {number} [wtimeout] The write concern timeout - * @param {boolean} [j] The journal write concern - * @param {boolean} [fsync] The file sync write concern - */ - constructor(w, wtimeout, j, fsync) { - if (w != null) { - this.w = w; - } - if (wtimeout != null) { - this.wtimeout = wtimeout; - } - if (j != null) { - this.j = j; - } - if (fsync != null) { - this.fsync = fsync; - } - } - - /** - * Construct a WriteConcern given an options object. - * - * @param {object} options The options object from which to extract the write concern. - * @return {WriteConcern} - */ - static fromOptions(options) { - if ( - options == null || - (options.writeConcern == null && - options.w == null && - options.wtimeout == null && - options.j == null && - options.fsync == null) - ) { - return; - } - - if (options.writeConcern) { - return new WriteConcern( - options.writeConcern.w, - options.writeConcern.wtimeout, - options.writeConcern.j, - options.writeConcern.fsync - ); - } - - return new WriteConcern(options.w, options.wtimeout, options.j, options.fsync); - } -} - -module.exports = WriteConcern; diff --git a/node_modules/mongoose/node_modules/mongodb/package.json b/node_modules/mongoose/node_modules/mongodb/package.json deleted file mode 100644 index e2e1dd0..0000000 --- a/node_modules/mongoose/node_modules/mongodb/package.json +++ /dev/null @@ -1,107 +0,0 @@ -{ - "_from": "mongodb@3.5.7", - "_id": "mongodb@3.5.7", - "_inBundle": false, - "_integrity": "sha512-lMtleRT+vIgY/JhhTn1nyGwnSMmJkJELp+4ZbrjctrnBxuLbj6rmLuJFz8W2xUzUqWmqoyVxJLYuC58ZKpcTYQ==", - "_location": "/mongoose/mongodb", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "mongodb@3.5.7", - "name": "mongodb", - "escapedName": "mongodb", - "rawSpec": "3.5.7", - "saveSpec": null, - "fetchSpec": "3.5.7" - }, - "_requiredBy": [ - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.5.7.tgz", - "_shasum": "6dcfff3bdbf67a53263dcca1647c265eea1d065d", - "_spec": "mongodb@3.5.7", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mongoose", - "bugs": { - "url": "https://github.com/mongodb/node-mongodb-native/issues" - }, - "bundleDependencies": false, - "dependencies": { - "bl": "^2.2.0", - "bson": "^1.1.4", - "denque": "^1.4.1", - "require_optional": "^1.0.1", - "safe-buffer": "^5.1.2", - "saslprep": "^1.0.0" - }, - "deprecated": false, - "description": "The official MongoDB driver for Node.js", - "devDependencies": { - "chai": "^4.1.1", - "chai-subset": "^1.6.0", - "chalk": "^2.4.2", - "co": "4.6.0", - "coveralls": "^2.11.6", - "eslint": "^4.5.0", - "eslint-plugin-prettier": "^2.2.0", - "istanbul": "^0.4.5", - "jsdoc": "3.5.5", - "lodash.camelcase": "^4.3.0", - "mocha": "5.2.0", - "mocha-sinon": "^2.1.0", - "mongodb-extjson": "^2.1.1", - "mongodb-mock-server": "^1.0.1", - "prettier": "^1.19.1", - "semver": "^5.5.0", - "sinon": "^4.3.0", - "sinon-chai": "^3.2.0", - "snappy": "^6.3.4", - "standard-version": "^4.4.0", - "util.promisify": "^1.0.1", - "worker-farm": "^1.5.0", - "wtfnode": "^0.8.0", - "yargs": "^14.2.0" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "index.js", - "lib" - ], - "homepage": "https://github.com/mongodb/node-mongodb-native", - "keywords": [ - "mongodb", - "driver", - "official" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "mongodb", - "optionalDependencies": { - "saslprep": "^1.0.0" - }, - "peerOptionalDependencies": { - "kerberos": "^1.1.0", - "mongodb-client-encryption": "^1.0.0", - "mongodb-extjson": "^2.1.2", - "snappy": "^6.3.4", - "bson-ext": "^2.0.0" - }, - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" - }, - "scripts": { - "atlas": "node ./test/tools/atlas_connectivity_tests.js", - "bench": "node test/benchmarks/driverBench/", - "coverage": "istanbul cover mongodb-test-runner -- -t 60000 test/core test/unit test/functional", - "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", - "generate-evergreen": "node .evergreen/generate_evergreen_tasks.js", - "lint": "eslint lib test", - "release": "standard-version -i HISTORY.md", - "test": "npm run lint && mocha --recursive test/functional test/unit test/core", - "test-nolint": "mocha --recursive test/functional test/unit test/core" - }, - "version": "3.5.7" -} diff --git a/node_modules/mongoose/node_modules/safe-buffer/LICENSE b/node_modules/mongoose/node_modules/safe-buffer/LICENSE deleted file mode 100644 index 0c068ce..0000000 --- a/node_modules/mongoose/node_modules/safe-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -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/mongoose/node_modules/safe-buffer/README.md b/node_modules/mongoose/node_modules/safe-buffer/README.md deleted file mode 100644 index e9a81af..0000000 --- a/node_modules/mongoose/node_modules/safe-buffer/README.md +++ /dev/null @@ -1,584 +0,0 @@ -# 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/mongoose/node_modules/safe-buffer/index.d.ts b/node_modules/mongoose/node_modules/safe-buffer/index.d.ts deleted file mode 100644 index e9fed80..0000000 --- a/node_modules/mongoose/node_modules/safe-buffer/index.d.ts +++ /dev/null @@ -1,187 +0,0 @@ -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/mongoose/node_modules/safe-buffer/index.js b/node_modules/mongoose/node_modules/safe-buffer/index.js deleted file mode 100644 index 22438da..0000000 --- a/node_modules/mongoose/node_modules/safe-buffer/index.js +++ /dev/null @@ -1,62 +0,0 @@ -/* 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/mongoose/node_modules/safe-buffer/package.json b/node_modules/mongoose/node_modules/safe-buffer/package.json deleted file mode 100644 index 22bfd28..0000000 --- a/node_modules/mongoose/node_modules/safe-buffer/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "_from": "safe-buffer@5.1.2", - "_id": "safe-buffer@5.1.2", - "_inBundle": false, - "_integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "_location": "/mongoose/safe-buffer", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "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": [ - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "_shasum": "991ec69d296e0313747d59bdfd2b745c35f8828d", - "_spec": "safe-buffer@5.1.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mongoose", - "author": { - "name": "Feross Aboukhadijeh", - "email": "feross@feross.org", - "url": "http://feross.org" - }, - "bugs": { - "url": "https://github.com/feross/safe-buffer/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Safer Node.js Buffer API", - "devDependencies": { - "standard": "*", - "tape": "^4.0.0" - }, - "homepage": "https://github.com/feross/safe-buffer", - "keywords": [ - "buffer", - "buffer allocate", - "node security", - "safe", - "safe-buffer", - "security", - "uninitialized" - ], - "license": "MIT", - "main": "index.js", - "name": "safe-buffer", - "repository": { - "type": "git", - "url": "git://github.com/feross/safe-buffer.git" - }, - "scripts": { - "test": "standard && tape test/*.js" - }, - "types": "index.d.ts", - "version": "5.1.2" -} diff --git a/node_modules/mongoose/package.json b/node_modules/mongoose/package.json deleted file mode 100644 index 649927e..0000000 --- a/node_modules/mongoose/package.json +++ /dev/null @@ -1,256 +0,0 @@ -{ - "_from": "mongoose", - "_id": "mongoose@5.9.14", - "_inBundle": false, - "_integrity": "sha512-LScxCruQv0YpU/9DasKdThd+3r3PFQbCgesmfa6g0pTDOIiD1A9N9OQsGYrDf+dyUksfLCxJYYF9qpBHLvS1tg==", - "_location": "/mongoose", - "_phantomChildren": {}, - "_requested": { - "type": "tag", - "registry": true, - "raw": "mongoose", - "name": "mongoose", - "escapedName": "mongoose", - "rawSpec": "", - "saveSpec": null, - "fetchSpec": "latest" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/mongoose/-/mongoose-5.9.14.tgz", - "_shasum": "73dff38457c254f6a0eff2741642a62c5138b4c8", - "_spec": "mongoose", - "_where": "/Users/kai/Desktop/node-course/dbproject", - "author": { - "name": "Guillermo Rauch", - "email": "guillermo@learnboost.com" - }, - "browser": "./dist/browser.umd.js", - "bugs": { - "url": "https://github.com/Automattic/mongoose/issues/new" - }, - "bundleDependencies": false, - "dependencies": { - "bson": "^1.1.4", - "kareem": "2.3.1", - "mongodb": "3.5.7", - "mongoose-legacy-pluralize": "1.0.2", - "mpath": "0.7.0", - "mquery": "3.2.2", - "ms": "2.1.2", - "regexp-clone": "1.0.0", - "safe-buffer": "5.1.2", - "sift": "7.0.1", - "sliced": "1.0.1" - }, - "deprecated": false, - "description": "Mongoose MongoDB ODM", - "devDependencies": { - "acquit": "1.x", - "acquit-ignore": "0.1.x", - "acquit-require": "0.1.x", - "async": "2.6.2", - "babel-loader": "7.1.4", - "babel-preset-es2015": "6.24.1", - "benchmark": "2.1.4", - "bluebird": "3.5.5", - "chalk": "2.4.2", - "cheerio": "1.0.0-rc.2", - "co": "4.6.0", - "dox": "0.3.1", - "eslint": "6.8.0", - "eslint-plugin-mocha-no-only": "1.1.0", - "highlight.js": "9.1.0", - "lodash.isequal": "4.5.0", - "lodash.isequalwith": "4.4.0", - "marked": "0.6.2", - "mocha": "5.x", - "moment": "2.x", - "mongodb-topology-manager": "1.0.11", - "mongoose-long": "0.2.1", - "node-static": "0.7.11", - "object-sizeof": "1.3.0", - "pug": "2.0.3", - "q": "1.5.1", - "semver": "5.5.0", - "uuid": "2.0.3", - "uuid-parse": "1.0.0", - "validator": "10.8.0", - "webpack": "4.16.4" - }, - "directories": { - "lib": "./lib/mongoose" - }, - "engines": { - "node": ">=4.0.0" - }, - "eslintConfig": { - "extends": [ - "eslint:recommended" - ], - "plugins": [ - "mocha-no-only" - ], - "parserOptions": { - "ecmaVersion": 2015 - }, - "env": { - "node": true, - "es6": true - }, - "rules": { - "comma-style": "error", - "indent": [ - "error", - 2, - { - "SwitchCase": 1, - "VariableDeclarator": 2 - } - ], - "keyword-spacing": "error", - "no-whitespace-before-property": "error", - "no-buffer-constructor": "warn", - "no-console": "off", - "no-multi-spaces": "error", - "no-constant-condition": "off", - "func-call-spacing": "error", - "no-trailing-spaces": "error", - "no-undef": "error", - "no-unneeded-ternary": "error", - "no-const-assign": "error", - "no-useless-rename": "error", - "no-dupe-keys": "error", - "space-in-parens": [ - "error", - "never" - ], - "spaced-comment": [ - "error", - "always", - { - "block": { - "markers": [ - "!" - ], - "balanced": true - } - } - ], - "key-spacing": [ - "error", - { - "beforeColon": false, - "afterColon": true - } - ], - "comma-spacing": [ - "error", - { - "before": false, - "after": true - } - ], - "array-bracket-spacing": 1, - "arrow-spacing": [ - "error", - { - "before": true, - "after": true - } - ], - "object-curly-spacing": [ - "error", - "always" - ], - "comma-dangle": [ - "error", - "never" - ], - "no-unreachable": "error", - "quotes": [ - "error", - "single" - ], - "quote-props": [ - "error", - "as-needed" - ], - "semi": "error", - "no-extra-semi": "error", - "semi-spacing": "error", - "no-spaced-func": "error", - "no-throw-literal": "error", - "space-before-blocks": "error", - "space-before-function-paren": [ - "error", - "never" - ], - "space-infix-ops": "error", - "space-unary-ops": "error", - "no-var": "warn", - "prefer-const": "warn", - "strict": [ - "error", - "global" - ], - "no-restricted-globals": [ - "error", - { - "name": "context", - "message": "Don't use Mocha's global context" - } - ], - "no-prototype-builtins": "off", - "mocha-no-only/mocha-no-only": [ - "error" - ] - } - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/mongoose" - }, - "homepage": "https://mongoosejs.com", - "keywords": [ - "mongodb", - "document", - "model", - "schema", - "database", - "odm", - "data", - "datastore", - "query", - "nosql", - "orm", - "db" - ], - "license": "MIT", - "main": "./index.js", - "mocha": { - "extension": [ - "test.js" - ], - "watch-files": [ - "test/**/*.js" - ] - }, - "name": "mongoose", - "repository": { - "type": "git", - "url": "git://github.com/Automattic/mongoose.git" - }, - "scripts": { - "build-browser": "node build-browser.js", - "lint": "eslint .", - "prepublishOnly": "npm run build-browser", - "release": "git pull && git push origin master --tags && npm publish", - "release-legacy": "git pull origin 4.x && git push origin 4.x --tags && npm publish --tag legacy", - "test": "mocha --exit", - "test-cov": "nyc --reporter=html --reporter=text npm test" - }, - "version": "5.9.14" -} diff --git a/node_modules/mongoose/tools/auth.js b/node_modules/mongoose/tools/auth.js deleted file mode 100644 index 967f5e1..0000000 --- a/node_modules/mongoose/tools/auth.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -const Server = require('mongodb-topology-manager').Server; -const co = require('co'); -const mongodb = require('mongodb'); - -co(function*() { - // Create new instance - var server = new Server('mongod', { - auth: null, - dbpath: '/data/db/27017' - }); - - // Purge the directory - yield server.purge(); - - // Start process - yield server.start(); - - const db = yield mongodb.MongoClient.connect('mongodb://localhost:27017/admin'); - - yield db.addUser('passwordIsTaco', 'taco', { - roles: ['dbOwner'] - }); - - console.log('done'); -}).catch(error => { - console.error(error); - process.exit(-1); -}); diff --git a/node_modules/mongoose/tools/repl.js b/node_modules/mongoose/tools/repl.js deleted file mode 100644 index ca3b6de..0000000 --- a/node_modules/mongoose/tools/repl.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -const co = require('co'); - -co(function*() { - var ReplSet = require('mongodb-topology-manager').ReplSet; - - // Create new instance - var topology = new ReplSet('mongod', [{ - // mongod process options - options: { - bind_ip: 'localhost', port: 31000, dbpath: `/data/db/31000` - } - }, { - // mongod process options - options: { - bind_ip: 'localhost', port: 31001, dbpath: `/data/db/31001` - } - }, { - // Type of node - arbiterOnly: true, - // mongod process options - options: { - bind_ip: 'localhost', port: 31002, dbpath: `/data/db/31002` - } - }], { - replSet: 'rs' - }); - - yield topology.start(); - - console.log('done'); -}).catch(error => { - console.error(error); - process.exit(-1); -}); diff --git a/node_modules/mongoose/tools/sharded.js b/node_modules/mongoose/tools/sharded.js deleted file mode 100644 index 82cad14..0000000 --- a/node_modules/mongoose/tools/sharded.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -const co = require('co'); - -co(function*() { - var Sharded = require('mongodb-topology-manager').Sharded; - - // Create new instance - var topology = new Sharded({ - mongod: 'mongod', - mongos: 'mongos' - }); - - yield topology.addShard([{ - options: { - bind_ip: 'localhost', port: 31000, dbpath: `/data/db/31000`, shardsvr: null - } - }], { replSet: 'rs1' }); - - yield topology.addConfigurationServers([{ - options: { - bind_ip: 'localhost', port: 35000, dbpath: `/data/db/35000` - } - }], { replSet: 'rs0' }); - - yield topology.addProxies([{ - bind_ip: 'localhost', port: 51000, configdb: 'localhost:35000' - }], { - binary: 'mongos' - }); - - console.log('Start...'); - // Start up topology - yield topology.start(); - - console.log('Started'); - - // Shard db - yield topology.enableSharding('test'); - - console.log('done'); -}).catch(error => { - console.error(error); - process.exit(-1); -}); diff --git a/node_modules/mongoose/webpack.base.config.js b/node_modules/mongoose/webpack.base.config.js deleted file mode 100644 index 3332761..0000000 --- a/node_modules/mongoose/webpack.base.config.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -module.exports = { - module: { - rules: [ - { - test: /\.js$/, - include: [ - /\/mongoose\//i, - /\/kareem\//i - ], - loader: 'babel-loader', - options: { - presets: ['es2015'] - } - } - ] - }, - node: { - // Replace these Node.js native modules with empty objects, Mongoose's - // browser library does not use them. - // See https://webpack.js.org/configuration/node/ - dns: 'empty', - fs: 'empty', - module: 'empty', - net: 'empty', - tls: 'empty' - }, - target: 'web', - mode: 'production' -}; - - diff --git a/node_modules/mongoose/webpack.config.js b/node_modules/mongoose/webpack.config.js deleted file mode 100644 index b6c6cca..0000000 --- a/node_modules/mongoose/webpack.config.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -const paths = require('path'); - -const base = require('./webpack.base.config.js'); - -const webpackConfig = Object.assign({}, base, { - entry: require.resolve('./browser.js'), - output: { - filename: './dist/browser.umd.js', - path: paths.resolve(__dirname, ''), - library: 'mongoose', - libraryTarget: 'umd', - // override default 'window' globalObject so browser build will work in SSR environments - // may become unnecessary in webpack 5 - globalObject: 'typeof self !== \'undefined\' ? self : this' - }, - externals: [ - /^node_modules\/.+$/ - ] -}); - -module.exports = webpackConfig; - diff --git a/node_modules/mpath/.travis.yml b/node_modules/mpath/.travis.yml deleted file mode 100644 index 9bdf212..0000000 --- a/node_modules/mpath/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: node_js -node_js: - - "4" - - "5" - - "6" - - "7" - - "8" - - "9" - - "10" diff --git a/node_modules/mpath/History.md b/node_modules/mpath/History.md deleted file mode 100644 index cf03b39..0000000 --- a/node_modules/mpath/History.md +++ /dev/null @@ -1,63 +0,0 @@ -0.7.0 / 2020-03-24 -================== - * BREAKING CHANGE: remove `component.json` #9 [AlexeyGrigorievBoost](https://github.com/AlexeyGrigorievBoost) - -0.6.0 / 2019-05-01 -================== - * feat: support setting dotted paths within nested arrays - -0.5.2 / 2019-04-25 -================== - * fix: avoid using subclassed array constructor when doing `map()` - -0.5.1 / 2018-08-30 -================== - * fix: prevent writing to constructor and prototype as well as __proto__ - -0.5.0 / 2018-08-30 -================== - * BREAKING CHANGE: disallow setting/unsetting __proto__ properties - * feat: re-add support for Node < 4 for this release - -0.4.1 / 2018-04-08 -================== - * fix: allow opting out of weird `$` set behavior re: Automattic/mongoose#6273 - -0.4.0 / 2018-03-27 -================== - * feat: add support for ES6 maps - * BREAKING CHANGE: drop support for Node < 4 - -0.3.0 / 2017-06-05 -================== - * feat: add has() and unset() functions - -0.2.1 / 2013-03-22 -================== - - * test; added for #5 - * fix typo that breaks set #5 [Contra](https://github.com/Contra) - -0.2.0 / 2013-03-15 -================== - - * added; adapter support for set - * added; adapter support for get - * add basic benchmarks - * add support for using module as a component #2 [Contra](https://github.com/Contra) - -0.1.1 / 2012-12-21 -================== - - * added; map support - -0.1.0 / 2012-12-13 -================== - - * added; set('array.property', val, object) support - * added; get('array.property', object) support - -0.0.1 / 2012-11-03 -================== - - * initial release diff --git a/node_modules/mpath/LICENSE b/node_modules/mpath/LICENSE deleted file mode 100644 index 38c529d..0000000 --- a/node_modules/mpath/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.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/mpath/Makefile b/node_modules/mpath/Makefile deleted file mode 100644 index 8d6a79c..0000000 --- a/node_modules/mpath/Makefile +++ /dev/null @@ -1,4 +0,0 @@ -bench: - node bench.js - -.PHONY: test diff --git a/node_modules/mpath/README.md b/node_modules/mpath/README.md deleted file mode 100644 index 9831dd0..0000000 --- a/node_modules/mpath/README.md +++ /dev/null @@ -1,278 +0,0 @@ -#mpath - -{G,S}et javascript object values using MongoDB-like path notation. - -###Getting - -```js -var mpath = require('mpath'); - -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.get('comments.1.title', obj) // 'exciting!' -``` - -`mpath.get` supports array property notation as well. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.get('comments.title', obj) // ['funny', 'exciting!'] -``` - -Array property and indexing syntax, when used together, are very powerful. - -```js -var obj = { - array: [ - { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} - , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} - , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; -} - -var found = mpath.get('array.o.array.x.b.1', obj); - -console.log(found); // prints.. - - [ [6, undefined] - , [2, undefined, undefined] - , [null, 1] - , [null] - , [undefined] - , [undefined, undefined, undefined] - , undefined - ] - -``` - -#####Field selection rules: - -The following rules are iteratively applied to each `segment` in the passed `path`. For example: - -```js -var path = 'one.two.14'; // path -'one' // segment 0 -'two' // segment 1 -14 // segment 2 -``` - -- 1) when value of the segment parent is not an array, return the value of `parent.segment` -- 2) when value of the segment parent is an array - - a) if the segment is an integer, replace the parent array with the value at `parent[segment]` - - b) if not an integer, keep the array but replace each array `item` with the value returned from calling `get(remainingSegments, item)` or undefined if falsey. - -#####Maps - -`mpath.get` also accepts an optional `map` argument which receives each individual found value. The value returned from the `map` function will be used in the original found values place. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.get('comments.title', obj, function (val) { - return 'funny' == val - ? 'amusing' - : val; -}); -// ['amusing', 'exciting!'] -``` - -###Setting - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.1.title', 'hilarious', obj) -console.log(obj.comments[1].title) // 'hilarious' -``` - -`mpath.set` supports the same array property notation as `mpath.get`. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.title', ['hilarious', 'fruity'], obj); - -console.log(obj); // prints.. - - { comments: [ - { title: 'hilarious' }, - { title: 'fruity' } - ]} -``` - -Array property and indexing syntax can be used together also when setting. - -```js -var obj = { - array: [ - { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} - , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} - , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ] -} - -mpath.set('array.1.o', 'this was changed', obj); - -console.log(require('util').inspect(obj, false, 1000)); // prints.. - -{ - array: [ - { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} - , { o: 'this was changed' } - , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; -} - -mpath.set('array.o.array.x', 'this was changed too', obj); - -console.log(require('util').inspect(obj, false, 1000)); // prints.. - -{ - array: [ - { o: { array: [{x: 'this was changed too'}, { y: 10, x: 'this was changed too'} ] }} - , { o: 'this was changed' } - , { o: { array: [{x: 'this was changed too'}, { x: 'this was changed too'}] }} - , { o: { array: [{x: 'this was changed too'}] }} - , { o: { array: [{x: 'this was changed too', y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; -} -``` - -####Setting arrays - -By default, setting a property within an array to another array results in each element of the new array being set to the item in the destination array at the matching index. An example is helpful. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.title', ['hilarious', 'fruity'], obj); - -console.log(obj); // prints.. - - { comments: [ - { title: 'hilarious' }, - { title: 'fruity' } - ]} -``` - -If we do not desire this destructuring-like assignment behavior we may instead specify the `$` operator in the path being set to force the array to be copied directly. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.$.title', ['hilarious', 'fruity'], obj); - -console.log(obj); // prints.. - - { comments: [ - { title: ['hilarious', 'fruity'] }, - { title: ['hilarious', 'fruity'] } - ]} -``` - -####Field assignment rules - -The rules utilized mirror those used on `mpath.get`, meaning we can take values returned from `mpath.get`, update them, and reassign them using `mpath.set`. Note that setting nested arrays of arrays can get unweildy quickly. Check out the [tests](https://github.com/aheckmann/mpath/blob/master/test/index.js) for more extreme examples. - -#####Maps - -`mpath.set` also accepts an optional `map` argument which receives each individual value being set. The value returned from the `map` function will be used in the original values place. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.title', ['hilarious', 'fruity'], obj, function (val) { - return val.length; -}); - -console.log(obj); // prints.. - - { comments: [ - { title: 9 }, - { title: 6 } - ]} -``` - -### Custom object types - -Sometimes you may want to enact the same functionality on custom object types that store all their real data internally, say for an ODM type object. No fear, `mpath` has you covered. Simply pass the name of the property being used to store the internal data and it will be traversed instead: - -```js -var mpath = require('mpath'); - -var obj = { - comments: [ - { title: 'exciting!', _doc: { title: 'great!' }} - ] -} - -mpath.get('comments.0.title', obj, '_doc') // 'great!' -mpath.set('comments.0.title', 'nov 3rd', obj, '_doc') -mpath.get('comments.0.title', obj, '_doc') // 'nov 3rd' -mpath.get('comments.0.title', obj) // 'exciting' -``` - -When used with a `map`, the `map` argument comes last. - -```js -mpath.get(path, obj, '_doc', map); -mpath.set(path, val, obj, '_doc', map); -``` - -[LICENSE](https://github.com/aheckmann/mpath/blob/master/LICENSE) - diff --git a/node_modules/mpath/bench.js b/node_modules/mpath/bench.js deleted file mode 100644 index 7ec6a87..0000000 --- a/node_modules/mpath/bench.js +++ /dev/null @@ -1,109 +0,0 @@ - -var mpath = require('./') -var Bench = require('benchmark'); -var sha = require('child_process').exec("git log --pretty=format:'%h' -n 1", function (err, sha) { - if (err) throw err; - - var fs = require('fs') - var filename = __dirname + '/bench.out'; - var out = fs.createWriteStream(filename, { flags: 'a', encoding: 'utf8' }); - - /** - * test doc creator - */ - - function doc () { - var o = { first: { second: { third: [3,{ name: 'aaron' }, 9] }}}; - o.comments = [ - { name: 'one' } - , { name: 'two', _doc: { name: '2' }} - , { name: 'three' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} - ]; - o.name = 'jiro'; - o.array = [ - { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} - , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] }} - , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; - o.arr = [ - { arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true } - ] - return o; - } - - var o = doc(); - - var s = new Bench.Suite; - s.add('mpath.get("first", obj)', function () { - mpath.get('first', o); - }) - s.add('mpath.get("first.second", obj)', function () { - mpath.get('first.second', o); - }) - s.add('mpath.get("first.second.third.1.name", obj)', function () { - mpath.get('first.second.third.1.name', o); - }) - s.add('mpath.get("comments", obj)', function () { - mpath.get('comments', o); - }) - s.add('mpath.get("comments.1", obj)', function () { - mpath.get('comments.1', o); - }) - s.add('mpath.get("comments.2.name", obj)', function () { - mpath.get('comments.2.name', o); - }) - s.add('mpath.get("comments.2.comments.1.comments.0.val", obj)', function () { - mpath.get('comments.2.comments.1.comments.0.val', o); - }) - s.add('mpath.get("comments.name", obj)', function () { - mpath.get('comments.name', o); - }) - - s.add('mpath.set("first", obj, val)', function () { - mpath.set('first', o, 1); - }) - s.add('mpath.set("first.second", obj, val)', function () { - mpath.set('first.second', o, 1); - }) - s.add('mpath.set("first.second.third.1.name", obj, val)', function () { - mpath.set('first.second.third.1.name', o, 1); - }) - s.add('mpath.set("comments", obj, val)', function () { - mpath.set('comments', o, 1); - }) - s.add('mpath.set("comments.1", obj, val)', function () { - mpath.set('comments.1', o, 1); - }) - s.add('mpath.set("comments.2.name", obj, val)', function () { - mpath.set('comments.2.name', o, 1); - }) - s.add('mpath.set("comments.2.comments.1.comments.0.val", obj, val)', function () { - mpath.set('comments.2.comments.1.comments.0.val', o, 1); - }) - s.add('mpath.set("comments.name", obj, val)', function () { - mpath.set('comments.name', o, 1); - }) - - s.on('start', function () { - console.log('starting...'); - out.write('*' + sha + ': ' + String(new Date()) + '\n'); - }); - s.on('cycle', function (e) { - var s = String(e.target); - console.log(s); - out.write(s + '\n'); - }) - s.on('complete', function () { - console.log('done') - out.end(''); - }) - s.run() -}) - diff --git a/node_modules/mpath/bench.log b/node_modules/mpath/bench.log deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mpath/bench.out b/node_modules/mpath/bench.out deleted file mode 100644 index b9b0371..0000000 --- a/node_modules/mpath/bench.out +++ /dev/null @@ -1,52 +0,0 @@ -*b566c26: Fri Mar 15 2013 14:14:04 GMT-0700 (PDT) -mpath.get("first", obj) x 3,827,405 ops/sec ±0.91% (90 runs sampled) -mpath.get("first.second", obj) x 4,930,222 ops/sec ±1.92% (91 runs sampled) -mpath.get("first.second.third.1.name", obj) x 3,070,837 ops/sec ±1.45% (97 runs sampled) -mpath.get("comments", obj) x 3,649,771 ops/sec ±1.71% (93 runs sampled) -mpath.get("comments.1", obj) x 3,846,728 ops/sec ±0.86% (94 runs sampled) -mpath.get("comments.2.name", obj) x 3,527,680 ops/sec ±0.95% (96 runs sampled) -mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,046,982 ops/sec ±0.80% (96 runs sampled) -mpath.get("comments.name", obj) x 625,546 ops/sec ±2.02% (82 runs sampled) -*e42bdb1: Fri Mar 15 2013 14:19:28 GMT-0700 (PDT) -mpath.get("first", obj) x 3,700,783 ops/sec ±1.30% (95 runs sampled) -mpath.get("first.second", obj) x 4,621,795 ops/sec ±0.86% (95 runs sampled) -mpath.get("first.second.third.1.name", obj) x 3,012,671 ops/sec ±1.21% (100 runs sampled) -mpath.get("comments", obj) x 3,677,694 ops/sec ±0.80% (96 runs sampled) -mpath.get("comments.1", obj) x 3,798,862 ops/sec ±0.81% (91 runs sampled) -mpath.get("comments.2.name", obj) x 3,489,356 ops/sec ±0.66% (98 runs sampled) -mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,004,076 ops/sec ±0.85% (99 runs sampled) -mpath.get("comments.name", obj) x 613,270 ops/sec ±1.33% (83 runs sampled) -*0521aac: Fri Mar 15 2013 16:37:16 GMT-0700 (PDT) -mpath.get("first", obj) x 3,834,755 ops/sec ±0.70% (100 runs sampled) -mpath.get("first.second", obj) x 4,999,965 ops/sec ±1.01% (98 runs sampled) -mpath.get("first.second.third.1.name", obj) x 3,125,953 ops/sec ±0.97% (100 runs sampled) -mpath.get("comments", obj) x 3,759,233 ops/sec ±0.81% (97 runs sampled) -mpath.get("comments.1", obj) x 3,894,893 ops/sec ±0.76% (96 runs sampled) -mpath.get("comments.2.name", obj) x 3,576,929 ops/sec ±0.68% (98 runs sampled) -mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,149,610 ops/sec ±0.67% (97 runs sampled) -mpath.get("comments.name", obj) x 629,259 ops/sec ±1.30% (87 runs sampled) -mpath.set("first", obj, val) x 2,869,477 ops/sec ±0.63% (97 runs sampled) -mpath.set("first.second", obj, val) x 2,418,751 ops/sec ±0.62% (98 runs sampled) -mpath.set("first.second.third.1.name", obj, val) x 2,313,099 ops/sec ±0.69% (94 runs sampled) -mpath.set("comments", obj, val) x 2,680,882 ops/sec ±0.76% (99 runs sampled) -mpath.set("comments.1", obj, val) x 2,401,829 ops/sec ±0.68% (98 runs sampled) -mpath.set("comments.2.name", obj, val) x 2,335,081 ops/sec ±1.07% (96 runs sampled) -mpath.set("comments.2.comments.1.comments.0.val", obj, val) x 2,245,436 ops/sec ±0.76% (92 runs sampled) -mpath.set("comments.name", obj, val) x 2,356,278 ops/sec ±1.15% (100 runs sampled) -*97e85d3: Fri Mar 15 2013 16:39:21 GMT-0700 (PDT) -mpath.get("first", obj) x 3,837,614 ops/sec ±0.74% (99 runs sampled) -mpath.get("first.second", obj) x 4,991,779 ops/sec ±1.01% (94 runs sampled) -mpath.get("first.second.third.1.name", obj) x 3,078,455 ops/sec ±1.17% (96 runs sampled) -mpath.get("comments", obj) x 3,770,961 ops/sec ±0.45% (101 runs sampled) -mpath.get("comments.1", obj) x 3,832,814 ops/sec ±0.67% (92 runs sampled) -mpath.get("comments.2.name", obj) x 3,536,436 ops/sec ±0.49% (100 runs sampled) -mpath.get("comments.2.comments.1.comments.0.val", obj) x 2,141,947 ops/sec ±0.72% (98 runs sampled) -mpath.get("comments.name", obj) x 667,898 ops/sec ±1.62% (85 runs sampled) -mpath.set("first", obj, val) x 2,642,517 ops/sec ±0.72% (98 runs sampled) -mpath.set("first.second", obj, val) x 2,502,124 ops/sec ±1.28% (99 runs sampled) -mpath.set("first.second.third.1.name", obj, val) x 2,426,804 ops/sec ±0.55% (99 runs sampled) -mpath.set("comments", obj, val) x 2,699,478 ops/sec ±0.85% (98 runs sampled) -mpath.set("comments.1", obj, val) x 2,494,454 ops/sec ±1.05% (96 runs sampled) -mpath.set("comments.2.name", obj, val) x 2,463,894 ops/sec ±0.86% (98 runs sampled) -mpath.set("comments.2.comments.1.comments.0.val", obj, val) x 2,320,398 ops/sec ±0.82% (95 runs sampled) -mpath.set("comments.name", obj, val) x 2,512,408 ops/sec ±0.77% (95 runs sampled) diff --git a/node_modules/mpath/index.js b/node_modules/mpath/index.js deleted file mode 100644 index f7b65dd..0000000 --- a/node_modules/mpath/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = exports = require('./lib'); diff --git a/node_modules/mpath/lib/index.js b/node_modules/mpath/lib/index.js deleted file mode 100644 index e5479de..0000000 --- a/node_modules/mpath/lib/index.js +++ /dev/null @@ -1,308 +0,0 @@ -// These properties are special and can open client libraries to security -// issues -var ignoreProperties = ['__proto__', 'constructor', 'prototype']; - -/** - * Returns the value of object `o` at the given `path`. - * - * ####Example: - * - * var obj = { - * comments: [ - * { title: 'exciting!', _doc: { title: 'great!' }} - * , { title: 'number dos' } - * ] - * } - * - * mpath.get('comments.0.title', o) // 'exciting!' - * mpath.get('comments.0.title', o, '_doc') // 'great!' - * mpath.get('comments.title', o) // ['exciting!', 'number dos'] - * - * // summary - * mpath.get(path, o) - * mpath.get(path, o, special) - * mpath.get(path, o, map) - * mpath.get(path, o, special, map) - * - * @param {String} path - * @param {Object} o - * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. - * @param {Function} [map] Optional function which receives each individual found value. The value returned from `map` is used in the original values place. - */ - -exports.get = function (path, o, special, map) { - var lookup; - - if ('function' == typeof special) { - if (special.length < 2) { - map = special; - special = undefined; - } else { - lookup = special; - special = undefined; - } - } - - map || (map = K); - - var parts = 'string' == typeof path - ? path.split('.') - : path - - if (!Array.isArray(parts)) { - throw new TypeError('Invalid `path`. Must be either string or array'); - } - - var obj = o - , part; - - for (var i = 0; i < parts.length; ++i) { - part = parts[i]; - - if (Array.isArray(obj) && !/^\d+$/.test(part)) { - // reading a property from the array items - var paths = parts.slice(i); - - // Need to `concat()` to avoid `map()` calling a constructor of an array - // subclass - return [].concat(obj).map(function (item) { - return item - ? exports.get(paths, item, special || lookup, map) - : map(undefined); - }); - } - - if (lookup) { - obj = lookup(obj, part); - } else { - var _from = special && obj[special] ? obj[special] : obj; - obj = _from instanceof Map ? - _from.get(part) : - _from[part]; - } - - if (!obj) return map(obj); - } - - return map(obj); -}; - -/** - * Returns true if `in` returns true for every piece of the path - * - * @param {String} path - * @param {Object} o - */ - -exports.has = function (path, o) { - var parts = typeof path === 'string' ? - path.split('.') : - path; - - if (!Array.isArray(parts)) { - throw new TypeError('Invalid `path`. Must be either string or array'); - } - - var len = parts.length; - var cur = o; - for (var i = 0; i < len; ++i) { - if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) { - return false; - } - cur = cur[parts[i]]; - } - - return true; -}; - -/** - * Deletes the last piece of `path` - * - * @param {String} path - * @param {Object} o - */ - -exports.unset = function (path, o) { - var parts = typeof path === 'string' ? - path.split('.') : - path; - - if (!Array.isArray(parts)) { - throw new TypeError('Invalid `path`. Must be either string or array'); - } - - var len = parts.length; - var cur = o; - for (var i = 0; i < len; ++i) { - if (cur == null || typeof cur !== 'object' || !(parts[i] in cur)) { - return false; - } - // Disallow any updates to __proto__ or special properties. - if (ignoreProperties.indexOf(parts[i]) !== -1) { - return false; - } - if (i === len - 1) { - delete cur[parts[i]]; - return true; - } - cur = cur instanceof Map ? cur.get(parts[i]) : cur[parts[i]]; - } - - return true; -}; - -/** - * Sets the `val` at the given `path` of object `o`. - * - * @param {String} path - * @param {Anything} val - * @param {Object} o - * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. - * @param {Function} [map] Optional function which is passed each individual value before setting it. The value returned from `map` is used in the original values place. - */ - -exports.set = function (path, val, o, special, map, _copying) { - var lookup; - - if ('function' == typeof special) { - if (special.length < 2) { - map = special; - special = undefined; - } else { - lookup = special; - special = undefined; - } - } - - map || (map = K); - - var parts = 'string' == typeof path - ? path.split('.') - : path - - if (!Array.isArray(parts)) { - throw new TypeError('Invalid `path`. Must be either string or array'); - } - - if (null == o) return; - - for (var i = 0; i < parts.length; ++i) { - // Silently ignore any updates to `__proto__`, these are potentially - // dangerous if using mpath with unsanitized data. - if (ignoreProperties.indexOf(parts[i]) !== -1) { - return; - } - } - - // the existance of $ in a path tells us if the user desires - // the copying of an array instead of setting each value of - // the array to the one by one to matching positions of the - // current array. Unless the user explicitly opted out by passing - // false, see Automattic/mongoose#6273 - var copy = _copying || (/\$/.test(path) && _copying !== false) - , obj = o - , part - - for (var i = 0, len = parts.length - 1; i < len; ++i) { - part = parts[i]; - - if ('$' == part) { - if (i == len - 1) { - break; - } else { - continue; - } - } - - if (Array.isArray(obj) && !/^\d+$/.test(part)) { - var paths = parts.slice(i); - if (!copy && Array.isArray(val)) { - for (var j = 0; j < obj.length && j < val.length; ++j) { - // assignment of single values of array - exports.set(paths, val[j], obj[j], special || lookup, map, copy); - } - } else { - for (var j = 0; j < obj.length; ++j) { - // assignment of entire value - exports.set(paths, val, obj[j], special || lookup, map, copy); - } - } - return; - } - - if (lookup) { - obj = lookup(obj, part); - } else { - var _to = special && obj[special] ? obj[special] : obj; - obj = _to instanceof Map ? - _to.get(part) : - _to[part]; - } - - if (!obj) return; - } - - // process the last property of the path - - part = parts[len]; - - // use the special property if exists - if (special && obj[special]) { - obj = obj[special]; - } - - // set the value on the last branch - if (Array.isArray(obj) && !/^\d+$/.test(part)) { - if (!copy && Array.isArray(val)) { - _setArray(obj, val, part, lookup, special, map); - } else { - for (var j = 0; j < obj.length; ++j) { - item = obj[j]; - if (item) { - if (lookup) { - lookup(item, part, map(val)); - } else { - if (item[special]) item = item[special]; - item[part] = map(val); - } - } - } - } - } else { - if (lookup) { - lookup(obj, part, map(val)); - } else if (obj instanceof Map) { - obj.set(part, map(val)); - } else { - obj[part] = map(val); - } - } -} - -/*! - * Recursively set nested arrays - */ - -function _setArray(obj, val, part, lookup, special, map) { - for (var item, j = 0; j < obj.length && j < val.length; ++j) { - item = obj[j]; - if (Array.isArray(item) && Array.isArray(val[j])) { - _setArray(item, val[j], part, lookup, special, map); - } else if (item) { - if (lookup) { - lookup(item, part, map(val[j])); - } else { - if (item[special]) item = item[special]; - item[part] = map(val[j]); - } - } - } -} - -/*! - * Returns the value passed to it. - */ - -function K (v) { - return v; -} diff --git a/node_modules/mpath/package.json b/node_modules/mpath/package.json deleted file mode 100644 index bfe15ed..0000000 --- a/node_modules/mpath/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "_from": "mpath@0.7.0", - "_id": "mpath@0.7.0", - "_inBundle": false, - "_integrity": "sha512-Aiq04hILxhz1L+f7sjGyn7IxYzWm1zLNNXcfhDtx04kZ2Gk7uvFdgZ8ts1cWa/6d0TQmag2yR8zSGZUmp0tFNg==", - "_location": "/mpath", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "mpath@0.7.0", - "name": "mpath", - "escapedName": "mpath", - "rawSpec": "0.7.0", - "saveSpec": null, - "fetchSpec": "0.7.0" - }, - "_requiredBy": [ - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/mpath/-/mpath-0.7.0.tgz", - "_shasum": "20e8102e276b71709d6e07e9f8d4d0f641afbfb8", - "_spec": "mpath@0.7.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mongoose", - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "bugs": { - "url": "https://github.com/aheckmann/mpath/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "{G,S}et object values using MongoDB-like path notation", - "devDependencies": { - "benchmark": "~1.0.0", - "mocha": "5.x" - }, - "engines": { - "node": ">=4.0.0" - }, - "homepage": "https://github.com/aheckmann/mpath#readme", - "keywords": [ - "mongodb", - "path", - "get", - "set" - ], - "license": "MIT", - "main": "index.js", - "name": "mpath", - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mpath.git" - }, - "scripts": { - "test": "mocha test/*" - }, - "version": "0.7.0" -} diff --git a/node_modules/mpath/test/index.js b/node_modules/mpath/test/index.js deleted file mode 100644 index f12bdc9..0000000 --- a/node_modules/mpath/test/index.js +++ /dev/null @@ -1,1879 +0,0 @@ -'use strict'; - -/** - * Test dependencies. - */ - -var mpath = require('../') -var assert = require('assert') - -/** - * logging helper - */ - -function log (o) { - console.log(); - console.log(require('util').inspect(o, false, 1000)); -} - -/** - * special path for override tests - */ - -var special = '_doc'; - -/** - * Tests - */ - -describe('mpath', function(){ - - /** - * test doc creator - */ - - function doc () { - var o = { first: { second: { third: [3,{ name: 'aaron' }, 9] }}}; - o.comments = [ - { name: 'one' } - , { name: 'two', _doc: { name: '2' }} - , { name: 'three' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} - ]; - o.name = 'jiro'; - o.array = [ - { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} - , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] }} - , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; - o.arr = [ - { arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true } - ] - return o; - } - - describe('get', function(){ - var o = doc(); - - it('`path` must be a string or array', function(done){ - assert.throws(function () { - mpath.get({}, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(4, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(function(){}, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(/asdf/, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(Math, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(Buffer, o); - }, /Must be either string or array/); - assert.doesNotThrow(function () { - mpath.get('string', o); - }); - assert.doesNotThrow(function () { - mpath.get([], o); - }); - done(); - }) - - describe('without `special`', function(){ - it('works', function(done){ - assert.equal('jiro', mpath.get('name', o)); - - assert.deepEqual( - { second: { third: [3,{ name: 'aaron' }, 9] }} - , mpath.get('first', o) - ); - - assert.deepEqual( - { third: [3,{ name: 'aaron' }, 9] } - , mpath.get('first.second', o) - ); - - assert.deepEqual( - [3,{ name: 'aaron' }, 9] - , mpath.get('first.second.third', o) - ); - - assert.deepEqual( - 3 - , mpath.get('first.second.third.0', o) - ); - - assert.deepEqual( - 9 - , mpath.get('first.second.third.2', o) - ); - - assert.deepEqual( - { name: 'aaron' } - , mpath.get('first.second.third.1', o) - ); - - assert.deepEqual( - 'aaron' - , mpath.get('first.second.third.1.name', o) - ); - - assert.deepEqual([ - { name: 'one' } - , { name: 'two', _doc: { name: '2' }} - , { name: 'three' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], - mpath.get('comments', o)); - - assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o)); - assert.deepEqual('one', mpath.get('comments.0.name', o)); - assert.deepEqual('two', mpath.get('comments.1.name', o)); - assert.deepEqual('three', mpath.get('comments.2.name', o)); - - assert.deepEqual([{},{ comments: [{val: 'twoo'}]}] - , mpath.get('comments.2.comments', o)); - - assert.deepEqual({ comments: [{val: 'twoo'}]} - , mpath.get('comments.2.comments.1', o)); - - assert.deepEqual('twoo', mpath.get('comments.2.comments.1.comments.0.val', o)); - - done(); - }) - - it('handles array.property dot-notation', function(done){ - assert.deepEqual( - ['one', 'two', 'three'] - , mpath.get('comments.name', o) - ); - done(); - }) - - it('handles array.array notation', function(done){ - assert.deepEqual( - [undefined, undefined, [{}, {comments:[{val:'twoo'}]}]] - , mpath.get('comments.comments', o) - ); - done(); - }) - - it('handles prop.prop.prop.arrayProperty notation', function(done){ - assert.deepEqual( - [undefined, 'aaron', undefined] - , mpath.get('first.second.third.name', o) - ); - assert.deepEqual( - [1, 'aaron', 1] - , mpath.get('first.second.third.name', o, function (v) { - return undefined === v ? 1 : v; - }) - ); - done(); - }) - - it('handles array.prop.array', function(done){ - assert.deepEqual( - [ [{x: {b: [4,6,8]}}, { y: 10} ] - , [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] - , [{x: {b: null }}, { x: { b: [null, 1]}}] - , [{x: null }] - , [{y: 3 }] - , [3, 0, null] - , undefined - ] - , mpath.get('array.o.array', o) - ); - done(); - }) - - it('handles array.prop.array.index', function(done){ - assert.deepEqual( - [ {x: {b: [4,6,8]}} - , {x: {b: [1,2,3]}} - , {x: {b: null }} - , {x: null } - , {y: 3 } - , 3 - , undefined - ] - , mpath.get('array.o.array.0', o) - ); - done(); - }) - - it('handles array.prop.array.index.prop', function(done){ - assert.deepEqual( - [ {b: [4,6,8]} - , {b: [1,2,3]} - , {b: null } - , null - , undefined - , undefined - , undefined - ] - , mpath.get('array.o.array.0.x', o) - ); - done(); - }) - - it('handles array.prop.array.prop', function(done){ - assert.deepEqual( - [ [undefined, 10 ] - , [undefined, undefined, undefined] - , [undefined, undefined] - , [undefined] - , [3] - , [undefined, undefined, undefined] - , undefined - ] - , mpath.get('array.o.array.y', o) - ); - assert.deepEqual( - [ [{b: [4,6,8]}, undefined] - , [{b: [1,2,3]}, {z: 10 }, {b: 'hi'}] - , [{b: null }, { b: [null, 1]}] - , [null] - , [undefined] - , [undefined, undefined, undefined] - , undefined - ] - , mpath.get('array.o.array.x', o) - ); - done(); - }) - - it('handles array.prop.array.prop.prop', function(done){ - assert.deepEqual( - [ [[4,6,8], undefined] - , [[1,2,3], undefined, 'hi'] - , [null, [null, 1]] - , [null] - , [undefined] - , [undefined, undefined, undefined] - , undefined - ] - , mpath.get('array.o.array.x.b', o) - ); - done(); - }) - - it('handles array.prop.array.prop.prop.index', function(done){ - assert.deepEqual( - [ [6, undefined] - , [2, undefined, 'i'] // undocumented feature (string indexing) - , [null, 1] - , [null] - , [undefined] - , [undefined, undefined, undefined] - , undefined - ] - , mpath.get('array.o.array.x.b.1', o) - ); - assert.deepEqual( - [ [6, 0] - , [2, 0, 'i'] // undocumented feature (string indexing) - , [null, 1] - , [null] - , [0] - , [0, 0, 0] - , 0 - ] - , mpath.get('array.o.array.x.b.1', o, function (v) { - return undefined === v ? 0 : v; - }) - ); - done(); - }) - - it('handles array.index.prop.prop', function(done){ - assert.deepEqual( - [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] - , mpath.get('array.1.o.array', o) - ); - assert.deepEqual( - ['hi','hi','hi'] - , mpath.get('array.1.o.array', o, function (v) { - if (Array.isArray(v)) { - return v.map(function (val) { - return 'hi'; - }) - } - return v; - }) - ); - done(); - }) - - it('handles array.array.index', function(done){ - assert.deepEqual( - [{ a: { c: 48 }}, undefined] - , mpath.get('arr.arr.1', o) - ); - assert.deepEqual( - ['woot', undefined] - , mpath.get('arr.arr.1', o, function (v) { - if (v && v.a && v.a.c) return 'woot'; - return v; - }) - ); - done(); - }) - - it('handles array.array.index.prop', function(done){ - assert.deepEqual( - [{ c: 48 }, 'woot'] - , mpath.get('arr.arr.1.a', o, function (v) { - if (undefined === v) return 'woot'; - return v; - }) - ); - assert.deepEqual( - [{ c: 48 }, undefined] - , mpath.get('arr.arr.1.a', o) - ); - mpath.set('arr.arr.1.a', [{c:49},undefined], o) - assert.deepEqual( - [{ c: 49 }, undefined] - , mpath.get('arr.arr.1.a', o) - ); - mpath.set('arr.arr.1.a', [{c:48},undefined], o) - done(); - }) - - it('handles array.array.index.prop.prop', function(done){ - assert.deepEqual( - [48, undefined] - , mpath.get('arr.arr.1.a.c', o) - ); - assert.deepEqual( - [48, 'woot'] - , mpath.get('arr.arr.1.a.c', o, function (v) { - if (undefined === v) return 'woot'; - return v; - }) - ); - done(); - }) - - }) - - describe('with `special`', function(){ - describe('that is a string', function(){ - it('works', function(done){ - assert.equal('jiro', mpath.get('name', o, special)); - - assert.deepEqual( - { second: { third: [3,{ name: 'aaron' }, 9] }} - , mpath.get('first', o, special) - ); - - assert.deepEqual( - { third: [3,{ name: 'aaron' }, 9] } - , mpath.get('first.second', o, special) - ); - - assert.deepEqual( - [3,{ name: 'aaron' }, 9] - , mpath.get('first.second.third', o, special) - ); - - assert.deepEqual( - 3 - , mpath.get('first.second.third.0', o, special) - ); - - assert.deepEqual( - 4 - , mpath.get('first.second.third.0', o, special, function (v) { - return 3 === v ? 4 : v; - }) - ); - - assert.deepEqual( - 9 - , mpath.get('first.second.third.2', o, special) - ); - - assert.deepEqual( - { name: 'aaron' } - , mpath.get('first.second.third.1', o, special) - ); - - assert.deepEqual( - 'aaron' - , mpath.get('first.second.third.1.name', o, special) - ); - - assert.deepEqual([ - { name: 'one' } - , { name: 'two', _doc: { name: '2' }} - , { name: 'three' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], - mpath.get('comments', o, special)); - - assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o, special)); - assert.deepEqual('one', mpath.get('comments.0.name', o, special)); - assert.deepEqual('2', mpath.get('comments.1.name', o, special)); - assert.deepEqual('3', mpath.get('comments.2.name', o, special)); - assert.deepEqual('nice', mpath.get('comments.2.name', o, special, function (v) { - return '3' === v ? 'nice' : v; - })); - - assert.deepEqual([{},{ _doc: { comments: [{ val: 2 }] }}] - , mpath.get('comments.2.comments', o, special)); - - assert.deepEqual({ _doc: { comments: [{val: 2}]}} - , mpath.get('comments.2.comments.1', o, special)); - - assert.deepEqual(2, mpath.get('comments.2.comments.1.comments.0.val', o, special)); - done(); - }) - - it('handles array.property dot-notation', function(done){ - assert.deepEqual( - ['one', '2', '3'] - , mpath.get('comments.name', o, special) - ); - assert.deepEqual( - ['one', 2, '3'] - , mpath.get('comments.name', o, special, function (v) { - return '2' === v ? 2 : v - }) - ); - done(); - }) - - it('handles array.array notation', function(done){ - assert.deepEqual( - [undefined, undefined, [{}, {_doc: { comments:[{val:2}]}}]] - , mpath.get('comments.comments', o, special) - ); - done(); - }) - - it('handles array.array.index.array', function(done){ - assert.deepEqual( - [undefined, undefined, [{val:2}]] - , mpath.get('comments.comments.1.comments', o, special) - ); - done(); - }) - - it('handles array.array.index.array.prop', function(done){ - assert.deepEqual( - [undefined, undefined, [2]] - , mpath.get('comments.comments.1.comments.val', o, special) - ); - assert.deepEqual( - ['nil', 'nil', [2]] - , mpath.get('comments.comments.1.comments.val', o, special, function (v) { - return undefined === v ? 'nil' : v; - }) - ); - done(); - }) - }) - - describe('that is a function', function(){ - var special = function (obj, key) { - return obj[key] - } - - it('works', function(done){ - assert.equal('jiro', mpath.get('name', o, special)); - - assert.deepEqual( - { second: { third: [3,{ name: 'aaron' }, 9] }} - , mpath.get('first', o, special) - ); - - assert.deepEqual( - { third: [3,{ name: 'aaron' }, 9] } - , mpath.get('first.second', o, special) - ); - - assert.deepEqual( - [3,{ name: 'aaron' }, 9] - , mpath.get('first.second.third', o, special) - ); - - assert.deepEqual( - 3 - , mpath.get('first.second.third.0', o, special) - ); - - assert.deepEqual( - 4 - , mpath.get('first.second.third.0', o, special, function (v) { - return 3 === v ? 4 : v; - }) - ); - - assert.deepEqual( - 9 - , mpath.get('first.second.third.2', o, special) - ); - - assert.deepEqual( - { name: 'aaron' } - , mpath.get('first.second.third.1', o, special) - ); - - assert.deepEqual( - 'aaron' - , mpath.get('first.second.third.1.name', o, special) - ); - - assert.deepEqual([ - { name: 'one' } - , { name: 'two', _doc: { name: '2' }} - , { name: 'three' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], - mpath.get('comments', o, special)); - - assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o, special)); - assert.deepEqual('one', mpath.get('comments.0.name', o, special)); - assert.deepEqual('two', mpath.get('comments.1.name', o, special)); - assert.deepEqual('three', mpath.get('comments.2.name', o, special)); - assert.deepEqual('nice', mpath.get('comments.2.name', o, special, function (v) { - return 'three' === v ? 'nice' : v; - })); - - assert.deepEqual([{},{ comments: [{ val: 'twoo' }] }] - , mpath.get('comments.2.comments', o, special)); - - assert.deepEqual({ comments: [{val: 'twoo'}]} - , mpath.get('comments.2.comments.1', o, special)); - - assert.deepEqual('twoo', mpath.get('comments.2.comments.1.comments.0.val', o, special)); - - var overide = false; - assert.deepEqual('twoo', mpath.get('comments.8.comments.1.comments.0.val', o, function (obj, path) { - if (Array.isArray(obj) && 8 == path) { - overide = true; - return obj[2]; - } - return obj[path]; - })); - assert.ok(overide); - - done(); - }) - - it('in combination with map', function(done){ - var special = function (obj, key) { - if (Array.isArray(obj)) return obj[key]; - return obj.mpath; - } - var map = function (val) { - return 'convert' == val - ? 'mpath' - : val; - } - var o = { mpath: [{ mpath: 'converse' }, { mpath: 'convert' }] } - - assert.equal('mpath', mpath.get('something.1.kewl', o, special, map)); - done(); - }) - }) - }) - }) - - describe('set', function() { - it('prevents writing to __proto__', function() { - var obj = {}; - mpath.set('__proto__.x', 'foobar', obj); - assert.ok(!({}.x)); - - mpath.set('constructor.prototype.x', 'foobar', obj); - assert.ok(!({}.x)); - }); - - describe('without `special`', function() { - var o = doc(); - - it('works', function(done) { - mpath.set('name', 'a new val', o, function(v) { - return 'a new val' === v ? 'changed' : v; - }); - assert.deepEqual('changed', o.name); - - mpath.set('name', 'changed', o); - assert.deepEqual('changed', o.name); - - mpath.set('first.second.third', [1,{name:'x'},9], o); - assert.deepEqual([1,{name:'x'},9], o.first.second.third); - - mpath.set('first.second.third.1.name', 'y', o) - assert.deepEqual([1,{name:'y'},9], o.first.second.third); - - mpath.set('comments.1.name', 'ttwwoo', o); - assert.deepEqual({ name: 'ttwwoo', _doc: { name: '2' }}, o.comments[1]); - - mpath.set('comments.2.comments.1.comments.0.expand', 'added', o); - assert.deepEqual( - { val: 'twoo', expand: 'added'} - , o.comments[2].comments[1].comments[0]); - - mpath.set('comments.2.comments.1.comments.2', 'added', o); - assert.equal(3, o.comments[2].comments[1].comments.length); - assert.deepEqual( - { val: 'twoo', expand: 'added'} - , o.comments[2].comments[1].comments[0]); - assert.deepEqual( - undefined - , o.comments[2].comments[1].comments[1]); - assert.deepEqual( - 'added' - , o.comments[2].comments[1].comments[2]); - - done(); - }) - - describe('array.path', function(){ - describe('with single non-array value', function(){ - it('works', function(done){ - mpath.set('arr.yep', false, o, function (v) { - return false === v ? true: v; - }); - assert.deepEqual([ - { yep: true, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true } - ], o.arr); - - mpath.set('arr.yep', false, o); - - assert.deepEqual([ - { yep: false, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: false } - ], o.arr); - - done(); - }) - }) - describe('with array of values', function(){ - it('that are equal in length', function(done){ - mpath.set('arr.yep', ['one',2], o, function (v) { - return 'one' === v ? 1 : v; - }); - assert.deepEqual([ - { yep: 1, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 2 } - ], o.arr); - mpath.set('arr.yep', ['one',2], o); - - assert.deepEqual([ - { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 2 } - ], o.arr); - - done(); - }) - - it('that is less than length', function(done){ - mpath.set('arr.yep', [47], o, function (v) { - return 47 === v ? 4 : v; - }); - assert.deepEqual([ - { yep: 4, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 2 } - ], o.arr); - - mpath.set('arr.yep', [47], o); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 2 } - ], o.arr); - - done(); - }) - - it('that is greater than length', function(done){ - mpath.set('arr.yep', [5,6,7], o, function (v) { - return 5 === v ? 'five' : v; - }); - assert.deepEqual([ - { yep: 'five', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 6 } - ], o.arr); - - mpath.set('arr.yep', [5,6,7], o); - assert.deepEqual([ - { yep: 5, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 6 } - ], o.arr); - - done(); - }) - }) - }) - - describe('array.$.path', function(){ - describe('with single non-array value', function(){ - it('copies the value to each item in array', function(done){ - mpath.set('arr.$.yep', {xtra: 'double good'}, o, function (v) { - return v && v.xtra ? 'hi' : v; - }); - assert.deepEqual([ - { yep: 'hi', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 'hi'} - ], o.arr); - - mpath.set('arr.$.yep', {xtra: 'double good'}, o); - assert.deepEqual([ - { yep: {xtra:'double good'}, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: {xtra:'double good'}} - ], o.arr); - - done(); - }) - }) - describe('with array of values', function(){ - it('copies the value to each item in array', function(done){ - mpath.set('arr.$.yep', [15], o, function (v) { - return v.length === 1 ? [] : v; - }); - assert.deepEqual([ - { yep: [], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: []} - ], o.arr); - - mpath.set('arr.$.yep', [15], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: [15]} - ], o.arr); - - done(); - }) - }) - }) - - describe('array.index.path', function(){ - it('works', function(done){ - mpath.set('arr.1.yep', 0, o, function (v) { - return 0 === v ? 'zero' : v; - }); - assert.deepEqual([ - { yep: [15] , arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 'zero' } - ], o.arr); - - mpath.set('arr.1.yep', 0, o); - assert.deepEqual([ - { yep: [15] , arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.e', 35, o, function (v) { - return 35 === v ? 3 : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }, e: 3}, { a: { c: 48 }, e: 3}, { d: 'yep', e: 3 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.e', 35, o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }, e: 35}, { a: { c: 48 }, e: 35}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.e', ['a','b'], o, function (v) { - return 'a' === v ? 'x' : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }, e: 'x'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.e', ['a','b'], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }, e: 'a'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.path.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.a.b', 36, o, function (v) { - return 36 === v ? 3 : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 3 }, e: 'a'}, { a: { c: 48, b: 3 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.a.b', 36, o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 36 }, e: 'a'}, { a: { c: 48, b: 36 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.a.b', [1,2,3,4], o, function (v) { - return 2 === v ? 'two' : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 'two' }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.a.b', [1,2,3,4], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 2 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.$.path.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.$.a.b', '$', o, function (v) { - return '$' === v ? 'dolla billz' : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 'dolla billz' }, e: 'a'}, { a: { c: 48, b: 'dolla billz' }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.$.a.b', '$', o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: '$' }, e: 'a'}, { a: { c: 48, b: '$' }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.$.a.b', [1], o, function (v) { - return Array.isArray(v) ? {} : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: {} }, e: 'a'}, { a: { c: 48, b: {} }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.$.a.b', [1], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: [1] }, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - }) - - describe('array.array.index.path', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.0.a', 'single', o, function (v) { - return 'single' === v ? 'double' : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'double', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.arr.0.a', 'single', o); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, function (v) { - return 4 === v ? 3 : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: 3, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: false } - ], o.arr); - - mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: 4, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: false } - ], o.arr); - - done(); - }) - }) - - describe('array.array.$.index.path', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.$.0.a', 'singles', o, function (v) { - return 0; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: 0, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.arr.$.0.a', 'singles', o); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'singles', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('$.arr.arr.0.a', 'single', o); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, function (v) { - return 'nope' - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'nope', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - mpath.set('arr.$.arr.0.a', [4,8,15,16,23,42,108], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42,108], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - done(); - }) - }) - - describe('array.array.path.index', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.a.7', 47, o, function (v) { - return 1 - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,1], e: 'a'}, { a: { c: 48, b: [1], '7': 1 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - mpath.set('arr.arr.a.7', 47, o); - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,47], e: 'a'}, { a: { c: 48, b: [1], '7': 47 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - done(); - }) - it('with array', function(done){ - o.arr[1].arr = [{ a: [] }, { a: [] }, { a: null }]; - mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o); - - var a1 = []; - var a2 = []; - a1[7] = undefined; - a2[7] = 'woot'; - - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0, arr: [{a:a1},{a:a2},{a:null}] } - ], o.arr); - - done(); - }) - }) - - describe('handles array.array.path', function(){ - it('with single', function(done){ - o.arr[1].arr = [{},{}]; - assert.deepEqual([{},{}], o.arr[1].arr); - o.arr.push({ arr: 'something else' }); - o.arr.push({ arr: ['something else'] }); - o.arr.push({ arr: [[]] }); - o.arr.push({ arr: [5] }); - - var weird = []; - weird.e = 'xmas'; - - // test - mpath.set('arr.arr.e', 47, o, function (v) { - return 'xmas' - }); - assert.deepEqual([ - { yep: [15], arr: [ - { a: [4,8,15,16,23,42,108,null], e: 'xmas'} - , { a: { c: 48, b: [1], '7': 46 }, e: 'xmas'} - , { d: 'yep', e: 'xmas' } - ] - } - , { yep: 0, arr: [{e: 'xmas'}, {e:'xmas'}] } - , { arr: 'something else' } - , { arr: ['something else'] } - , { arr: [weird] } - , { arr: [5] } - ] - , o.arr); - - weird.e = 47; - - mpath.set('arr.arr.e', 47, o); - assert.deepEqual([ - { yep: [15], arr: [ - { a: [4,8,15,16,23,42,108,null], e: 47} - , { a: { c: 48, b: [1], '7': 46 }, e: 47} - , { d: 'yep', e: 47 } - ] - } - , { yep: 0, arr: [{e: 47}, {e:47}] } - , { arr: 'something else' } - , { arr: ['something else'] } - , { arr: [weird] } - , { arr: [5] } - ] - , o.arr); - - done(); - }) - it('with arrays', function(done){ - mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o, function (v) { - return 10; - }); - - var weird = []; - weird.e = 10; - - assert.deepEqual([ - { yep: [15], arr: [ - { a: [4,8,15,16,23,42,108,null], e: 10} - , { a: { c: 48, b: [1], '7': 46 }, e: 10} - , { d: 'yep', e: 10 } - ] - } - , { yep: 0, arr: [{e: 10}, {e:10}] } - , { arr: 'something else' } - , { arr: ['something else'] } - , { arr: [weird] } - , { arr: [5] } - ] - , o.arr); - - mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o); - - weird.e = 6; - - assert.deepEqual([ - { yep: [15], arr: [ - { a: [4,8,15,16,23,42,108,null], e: 1} - , { a: { c: 48, b: [1], '7': 46 }, e: 2} - , { d: 'yep', e: 3 } - ] - } - , { yep: 0, arr: [{e: 4}, {e:5}] } - , { arr: 'something else' } - , { arr: ['something else'] } - , { arr: [weird] } - , { arr: [5] } - ] - , o.arr); - - done(); - }) - }) - }) - - describe('with `special`', function(){ - var o = doc(); - - it('works', function(done){ - mpath.set('name', 'chan', o, special, function (v) { - return 'hi'; - }); - assert.deepEqual('hi', o.name); - - mpath.set('name', 'changer', o, special); - assert.deepEqual('changer', o.name); - - mpath.set('first.second.third', [1,{name:'y'},9], o, special); - assert.deepEqual([1,{name:'y'},9], o.first.second.third); - - mpath.set('first.second.third.1.name', 'z', o, special) - assert.deepEqual([1,{name:'z'},9], o.first.second.third); - - mpath.set('comments.1.name', 'ttwwoo', o, special); - assert.deepEqual({ name: 'two', _doc: { name: 'ttwwoo' }}, o.comments[1]); - - mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special, function (v) { - return 'super' - }); - assert.deepEqual( - { val: 2, expander: 'super'} - , o.comments[2]._doc.comments[1]._doc.comments[0]); - - mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special); - assert.deepEqual( - { val: 2, expander: 'adder'} - , o.comments[2]._doc.comments[1]._doc.comments[0]); - - mpath.set('comments.2.comments.1.comments.2', 'set', o, special); - assert.equal(3, o.comments[2]._doc.comments[1]._doc.comments.length); - assert.deepEqual( - { val: 2, expander: 'adder'} - , o.comments[2]._doc.comments[1]._doc.comments[0]); - assert.deepEqual( - undefined - , o.comments[2]._doc.comments[1]._doc.comments[1]); - assert.deepEqual( - 'set' - , o.comments[2]._doc.comments[1]._doc.comments[2]); - done(); - }) - - describe('array.path', function(){ - describe('with single non-array value', function(){ - it('works', function(done){ - o.arr[1]._doc = { special: true } - - mpath.set('arr.yep', false, o, special, function (v) { - return 'yes'; - }); - assert.deepEqual([ - { yep: 'yes', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 'yes'}} - ], o.arr); - - mpath.set('arr.yep', false, o, special); - assert.deepEqual([ - { yep: false, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: false }} - ], o.arr); - - done(); - }) - }) - describe('with array of values', function(){ - it('that are equal in length', function(done){ - mpath.set('arr.yep', ['one',2], o, special, function (v) { - return 2 === v ? 20 : v; - }); - assert.deepEqual([ - { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 20}} - ], o.arr); - - mpath.set('arr.yep', ['one',2], o, special); - assert.deepEqual([ - { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 2}} - ], o.arr); - - done(); - }) - - it('that is less than length', function(done){ - mpath.set('arr.yep', [47], o, special, function (v) { - return 80; - }); - assert.deepEqual([ - { yep: 80, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 2}} - ], o.arr); - - mpath.set('arr.yep', [47], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 2}} - ], o.arr); - - // add _doc to first element - o.arr[0]._doc = { yep: 46, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - - mpath.set('arr.yep', [20], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 20, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 2}} - ], o.arr); - - done(); - }) - - it('that is greater than length', function(done){ - mpath.set('arr.yep', [5,6,7], o, special, function () { - return 'x'; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 'x', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 'x'}} - ], o.arr); - - mpath.set('arr.yep', [5,6,7], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 5, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 6}} - ], o.arr); - - done(); - }) - }) - }) - - describe('array.$.path', function(){ - describe('with single non-array value', function(){ - it('copies the value to each item in array', function(done){ - mpath.set('arr.$.yep', {xtra: 'double good'}, o, special, function (v) { - return 9; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: 9, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 9}} - ], o.arr); - - mpath.set('arr.$.yep', {xtra: 'double good'}, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: {xtra:'double good'}, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: {xtra:'double good'}}} - ], o.arr); - - done(); - }) - }) - describe('with array of values', function(){ - it('copies the value to each item in array', function(done){ - mpath.set('arr.$.yep', [15], o, special, function (v) { - return 'array' - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: 'array', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 'array'}} - ], o.arr); - - mpath.set('arr.$.yep', [15], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: [15]}} - ], o.arr); - - done(); - }) - }) - }) - - describe('array.index.path', function(){ - it('works', function(done){ - mpath.set('arr.1.yep', 0, o, special, function (v) { - return 1; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 1}} - ], o.arr); - - mpath.set('arr.1.yep', 0, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.e', 35, o, special, function (v) { - return 30 - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 30}, { a: { c: 48 }, e: 30}, { d: 'yep', e: 30 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.e', 35, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 35}, { a: { c: 48 }, e: 35}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.e', ['a','b'], o, special, function (v) { - return 'a' === v ? 'A' : v; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'A'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.e', ['a','b'], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'a'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.path.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.a.b', 36, o, special, function (v) { - return 20 - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 20 }, e: 'a'}, { a: { c: 48, b: 20 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.a.b', 36, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 36 }, e: 'a'}, { a: { c: 48, b: 36 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.a.b', [1,2,3,4], o, special, function (v) { - return v*2; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 2 }, e: 'a'}, { a: { c: 48, b: 4 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.a.b', [1,2,3,4], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 2 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.$.path.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.$.a.b', '$', o, special, function (v) { - return 'dollaz' - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 'dollaz' }, e: 'a'}, { a: { c: 48, b: 'dollaz' }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.$.a.b', '$', o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: '$' }, e: 'a'}, { a: { c: 48, b: '$' }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.$.a.b', [1], o, special, function (v) { - return {}; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: {} }, e: 'a'}, { a: { c: 48, b: {} }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.$.a.b', [1], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: [1] }, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.array.index.path', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.0.a', 'single', o, special, function (v) { - return 88; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 88, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.0.a', 'single', o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, special, function (v) { - return v*2; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 8, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 4, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.array.$.index.path', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.$.0.a', 'singles', o, special, function (v) { - return v.toUpperCase(); - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 'SINGLES', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.$.0.a', 'singles', o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 'singles', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('$.arr.arr.0.a', 'single', o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, special, function (v) { - return Array - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: Array, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.$.arr.0.a', [4,8,15,16,23,42,108], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.array.path.index', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.a.7', 47, o, special, function (v) { - return Object; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,Object], e: 'a'}, { a: { c: 48, b: [1], '7': Object }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.a.7', 47, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,47], e: 'a'}, { a: { c: 48, b: [1], '7': 47 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - o.arr[1]._doc.arr = [{ a: [] }, { a: [] }, { a: null }]; - mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o, special, function (v) { - return undefined === v ? 'nope' : v; - }); - - var a1 = []; - var a2 = []; - a1[7] = 'nope'; - a2[7] = 'woot'; - - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { arr: [{a:a1},{a:a2},{a:null}], special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o, special); - - a1[7] = undefined; - - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { arr: [{a:a1},{a:a2},{a:null}], special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('handles array.array.path', function(){ - it('with single', function(done){ - o.arr[1]._doc.arr = [{},{}]; - assert.deepEqual([{},{}], o.arr[1]._doc.arr); - o.arr.push({ _doc: { arr: 'something else' }}); - o.arr.push({ _doc: { arr: ['something else'] }}); - o.arr.push({ _doc: { arr: [[]] }}); - o.arr.push({ _doc: { arr: [5] }}); - - // test - mpath.set('arr.arr.e', 47, o, special); - - var weird = []; - weird.e = 47; - - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { - yep: [15] - , arr: [ - { a: [4,8,15,16,23,42,108,null], e: 47} - , { a: { c: 48, b: [1], '7': 46 }, e: 47} - , { d: 'yep', e: 47 } - ] - } - } - , { yep: true - , _doc: { - arr: [ - {e:47} - , {e:47} - ] - , special: true - , yep: 0 - } - } - , { _doc: { arr: 'something else' }} - , { _doc: { arr: ['something else'] }} - , { _doc: { arr: [weird] }} - , { _doc: { arr: [5] }} - ] - , o.arr); - - done(); - }) - it('with arrays', function(done){ - mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o, special); - - var weird = []; - weird.e = 6; - - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { - yep: [15] - , arr: [ - { a: [4,8,15,16,23,42,108,null], e: 1} - , { a: { c: 48, b: [1], '7': 46 }, e: 2} - , { d: 'yep', e: 3 } - ] - } - } - , { yep: true - , _doc: { - arr: [ - {e:4} - , {e:5} - ] - , special: true - , yep: 0 - } - } - , { _doc: { arr: 'something else' }} - , { _doc: { arr: ['something else'] }} - , { _doc: { arr: [weird] }} - , { _doc: { arr: [5] }} - ] - , o.arr); - - done(); - }) - }) - - describe('that is a function', function(){ - describe('without map', function(){ - it('works on array value', function(done){ - var o = { hello: { world: [{ how: 'are' }, { you: '?' }] }}; - var special = function (obj, key, val) { - if (val) { - obj[key] = val; - } else { - return 'thing' == key - ? obj.world - : obj[key] - } - } - mpath.set('hello.thing.how', 'arrrr', o, special); - assert.deepEqual(o, { hello: { world: [{ how: 'arrrr' }, { you: '?', how: 'arrrr' }] }}); - done(); - }) - it('works on non-array value', function(done){ - var o = { hello: { world: { how: 'are you' }}}; - var special = function (obj, key, val) { - if (val) { - obj[key] = val; - } else { - return 'thing' == key - ? obj.world - : obj[key] - } - } - mpath.set('hello.thing.how', 'RU', o, special); - assert.deepEqual(o, { hello: { world: { how: 'RU' }}}); - done(); - }) - }) - it('works with map', function(done){ - var o = { hello: { world: [{ how: 'are' }, { you: '?' }] }}; - var special = function (obj, key, val) { - if (val) { - obj[key] = val; - } else { - return 'thing' == key - ? obj.world - : obj[key] - } - } - var map = function (val) { - return 'convert' == val - ? 'ºº' - : val - } - mpath.set('hello.thing.how', 'convert', o, special, map); - assert.deepEqual(o, { hello: { world: [{ how: 'ºº' }, { you: '?', how: 'ºº' }] }}); - done(); - }) - }) - - }) - - describe('get/set integration', function(){ - var o = doc(); - - it('works', function(done){ - var vals = mpath.get('array.o.array.x.b', o); - - vals[0][0][2] = 10; - vals[1][0][1] = 0; - vals[1][1] = 'Rambaldi'; - vals[1][2] = [12,14]; - vals[2] = [{changed:true}, [null, ['changed','to','array']]]; - - mpath.set('array.o.array.x.b', vals, o); - - var t = [ - { o: { array: [{x: {b: [4,6,10]}}, { y: 10} ] }} - , { o: { array: [{x: {b: [1,0,3]}}, { x: {b:'Rambaldi',z: 10 }}, { x: {b: [12,14]}}] }} - , { o: { array: [{x: {b: {changed:true}}}, { x: { b: [null, ['changed','to','array']]}}]}} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; - assert.deepEqual(t, o.array); - done(); - }); - - it('array.prop', function(done){ - mpath.set('comments.name', ['this', 'was', 'changed'], o); - - assert.deepEqual([ - { name: 'this' } - , { name: 'was', _doc: { name: '2' }} - , { name: 'changed' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} - ], o.comments); - - mpath.set('comments.name', ['also', 'changed', 'this'], o, special); - - assert.deepEqual([ - { name: 'also' } - , { name: 'was', _doc: { name: 'changed' }} - , { name: 'changed' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: 'this', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} - ], o.comments); - - done(); - }); - - it('nested array', function(done) { - const obj = { arr: [[{ test: 41 }]] }; - mpath.set('arr.test', [[42]], obj); - assert.deepEqual(obj.arr, [[{ test: 42 }]]); - done(); - }); - }); - - describe('multiple $ use', function(){ - var o = doc(); - it('is ok', function(done){ - assert.doesNotThrow(function () { - mpath.set('arr.$.arr.$.a', 35, o); - }); - done(); - }); - }); - - it('has', function(done) { - assert.ok(mpath.has('a', { a: 1 })); - assert.ok(mpath.has('a', { a: undefined })); - assert.ok(!mpath.has('a', {})); - assert.ok(!mpath.has('a', null)); - - assert.ok(mpath.has('a.b', { a: { b: 1 } })); - assert.ok(mpath.has('a.b', { a: { b: undefined } })); - assert.ok(!mpath.has('a.b', { a: 1 })); - assert.ok(!mpath.has('a.b', { a: null })); - - done(); - }); - - it('underneath a map', function(done) { - if (!global.Map) { - done(); - return; - } - assert.equal(mpath.get('a.b', { a: new Map([['b', 1]]) }), 1); - - var m = new Map([['b', 1]]); - var obj = { a: m }; - mpath.set('a.c', 2, obj); - assert.equal(m.get('c'), 2); - - done(); - }); - - it('unset', function(done) { - var o = { a: 1 }; - mpath.unset('a', o); - assert.deepEqual(o, {}); - - o = { a: { b: 1 } }; - mpath.unset('a.b', o); - assert.deepEqual(o, { a: {} }); - - o = { a: null }; - mpath.unset('a.b', o); - assert.deepEqual(o, { a: null }); - - done(); - }); - - it('unset with __proto__', function(done) { - // Should refuse to set __proto__ - function Clazz() {} - Clazz.prototype.foobar = true; - - mpath.unset('__proto__.foobar', new Clazz()); - assert.ok(Clazz.prototype.foobar); - - mpath.unset('constructor.prototype.foobar', new Clazz()); - assert.ok(Clazz.prototype.foobar); - - done(); - }); - - it('get() underneath subclassed array', function(done) { - class MyArray extends Array {} - - const obj = { - arr: new MyArray() - }; - obj.arr.push({ test: 2 }); - - const arr = mpath.get('arr.test', obj); - assert.equal(arr.constructor.name, 'Array'); - assert.ok(!(arr instanceof MyArray)); - - done(); - }); - - it('ignores setting a nested path that doesnt exist', function(done){ - var o = doc(); - assert.doesNotThrow(function(){ - mpath.set('thing.that.is.new', 10, o); - }) - done(); - }); - }); -}); diff --git a/node_modules/mquery/.eslintignore b/node_modules/mquery/.eslintignore deleted file mode 100644 index 4b4d863..0000000 --- a/node_modules/mquery/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -coverage/ \ No newline at end of file diff --git a/node_modules/mquery/.travis.yml b/node_modules/mquery/.travis.yml deleted file mode 100644 index 3d207e1..0000000 --- a/node_modules/mquery/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -language: node_js -node_js: - - "8" - - "10" - - "12" -matrix: - include: - - node_js: "13" - env: "NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/nightly" - allow_failures: - # Allow the nightly installs to fail - - env: "NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/nightly" -script: - - npm test - - npm run lint -services: - - mongodb diff --git a/node_modules/mquery/History.md b/node_modules/mquery/History.md deleted file mode 100644 index bc6a3c3..0000000 --- a/node_modules/mquery/History.md +++ /dev/null @@ -1,342 +0,0 @@ -3.2.2 / 2019-09-22 -================== - * fix: dont re-call setOptions() when pulling base class options Automattic/mongoose#8159 - -3.2.1 / 2018-08-24 -================== - * chore: upgrade deps - -3.2.0 / 2018-08-24 -================== - * feat: add $useProjection to opt in to using `projection` instead of `fields` re: MongoDB deprecation warnings Automattic/mongoose#6880 - -3.1.2 / 2018-08-01 -================== - * chore: move eslint to devDependencies #110 [jakesjews](https://github.com/jakesjews) - -3.1.1 / 2018-07-30 -================== - * chore: add eslint #107 [Fonger](https://github.com/Fonger) - * docs: clean up readConcern docs #106 [Fonger](https://github.com/Fonger) - -3.1.0 / 2018-07-29 -================== - * feat: add `readConcern()` helper #105 [Fonger](https://github.com/Fonger) - * feat: add `maxTimeMS()` as alias of `maxTime()` #105 [Fonger](https://github.com/Fonger) - * feat: add `collation()` helper #105 [Fonger](https://github.com/Fonger) - -3.0.1 / 2018-07-02 -================== - * fix: parse sort array options correctly #103 #102 [Fonger](https://github.com/Fonger) - -3.0.0 / 2018-01-20 -================== - * chore: upgrade deps and add nsp - -3.0.0-rc0 / 2017-12-06 -====================== - * BREAKING CHANGE: remove support for node < 4 - * BREAKING CHANGE: remove support for retainKeyOrder, will always be true by default re: Automattic/mongoose#2749 - -2.3.3 / 2017-11-19 -================== - * fixed; catch sync errors in cursor.toArray() re: Automattic/mongoose#5812 - -2.3.2 / 2017-09-27 -================== - * fixed; bumped debug -> 2.6.9 re: #89 - -2.3.1 / 2017-05-22 -================== - * fixed; bumped debug -> 2.6.7 re: #86 - -2.3.0 / 2017-03-05 -================== - * added; replaceOne function - * added; deleteOne and deleteMany functions - -2.2.3 / 2017-01-31 -================== - * fixed; throw correct error when passing incorrectly formatted array to sort() - -2.2.2 / 2017-01-31 -================== - * fixed; allow passing maps to sort() - -2.2.1 / 2017-01-29 -================== - * fixed; allow passing string to hint() - -2.2.0 / 2017-01-08 -================== - * added; updateOne and updateMany functions - -2.1.0 / 2016-12-22 -================== - * added; ability to pass an array to select() #81 [dciccale](https://github.com/dciccale) - -2.0.0 / 2016-09-25 -================== - * added; support for mongodb driver 2.0 streams - -1.12.0 / 2016-09-25 -=================== - * added; `retainKeyOrder` option re: Automattic/mongoose#4542 - -1.11.0 / 2016-06-04 -=================== - * added; `.minDistance()` helper and minDistance for `.near()` Automattic/mongoose#4179 - -1.10.1 / 2016-04-26 -=================== - * fixed; ensure conditions is an object before assigning #75 - -1.10.0 / 2016-03-16 -================== - - * updated; bluebird to latest 2.10.2 version #74 [matskiv](https://github.com/matskiv) - -1.9.0 / 2016-03-15 -================== - * added; `.eq` as a shortcut for `.equals` #72 [Fonger](https://github.com/Fonger) - * added; ability to use array syntax for sort re: https://jira.mongodb.org/browse/NODE-578 #67 - -1.8.0 / 2016-03-01 -================== - * fixed; dont throw an error if count used with sort or select Automattic/mongoose#3914 - -1.7.0 / 2016-02-23 -================== - * fixed; don't treat objects with a length property as argument objects #70 - * added; `.findCursor()` method #69 [nswbmw](https://github.com/nswbmw) - * added; `_compiledUpdate` property #68 [nswbmw](https://github.com/nswbmw) - -1.6.2 / 2015-07-12 -================== - - * fixed; support exec cb being called synchronously #66 - -1.6.1 / 2015-06-16 -================== - - * fixed; do not treat $meta projection as inclusive [vkarpov15](https://github.com/vkarpov15) - -1.6.0 / 2015-05-27 -================== - - * update dependencies #65 [bachp](https://github.com/bachp) - -1.5.0 / 2015-03-31 -================== - - * fixed; debug output - * fixed; allow hint usage with count #61 [trueinsider](https://github.com/trueinsider) - -1.4.0 / 2015-03-29 -================== - - * added; object support to slice() #60 [vkarpov15](https://github.com/vkarpov15) - * debug; improved output #57 [flyvictor](https://github.com/flyvictor) - -1.3.0 / 2014-11-06 -================== - - * added; setTraceFunction() #53 from [jlai](https://github.com/jlai) - -1.2.1 / 2014-09-26 -================== - - * fixed; distinct assignment in toConstructor() #51 from [esco](https://github.com/esco) - -1.2.0 / 2014-09-18 -================== - - * added; stream() support for find() - -1.1.0 / 2014-09-15 -================== - - * add #then for co / koa support - * start checking code coverage - -1.0.0 / 2014-07-07 -================== - - * Remove broken require() calls until they're actually implemented #48 [vkarpov15](https://github.com/vkarpov15) - -0.9.0 / 2014-05-22 -================== - - * added; thunk() support - * release 0.8.0 - -0.8.0 / 2014-05-15 -================== - - * added; support for maxTimeMS #44 [yoitsro](https://github.com/yoitsro) - * updated; devDependency (driver to 1.4.4) - -0.7.0 / 2014-05-02 -================== - - * fixed; pass $maxDistance in $near object as described in docs #43 [vkarpov15](https://github.com/vkarpov15) - * fixed; cloning buffers #42 [gjohnson](https://github.com/gjohnson) - * tests; a little bit more `mongodb` agnostic #34 [refack](https://github.com/refack) - -0.6.0 / 2014-04-01 -================== - - * fixed; Allow $meta args in sort() so text search sorting works #37 [vkarpov15](https://github.com/vkarpov15) - -0.5.3 / 2014-02-22 -================== - - * fixed; cloning mongodb.Binary - -0.5.2 / 2014-01-30 -================== - - * fixed; cloning ObjectId constructors - * fixed; cloning of ReadPreferences #30 [ashtuchkin](https://github.com/ashtuchkin) - * tests; use specific mongodb version #29 [AvianFlu](https://github.com/AvianFlu) - * tests; remove dependency on ObjectId #28 [refack](https://github.com/refack) - * tests; add failing ReadPref test - -0.5.1 / 2014-01-17 -================== - - * added; deprecation notice to tags parameter #27 [ashtuchkin](https://github.com/ashtuchkin) - * readme; add links - -0.5.0 / 2014-01-16 -================== - - * removed; mongodb driver dependency #26 [ashtuchkin](https://github.com/ashtuchkin) - * removed; first class support of read preference tags #26 (still supported though) [ashtuchkin](https://github.com/ashtuchkin) - * added; better ObjectId clone support - * fixed; cloning objects that have no constructor #21 - * docs; cleaned up [ashtuchkin](https://github.com/ashtuchkin) - -0.4.2 / 2014-01-08 -================== - - * updated; debug module 0.7.4 [refack](https://github.com/refack) - -0.4.1 / 2014-01-07 -================== - - * fixed; inclusive/exclusive logic - -0.4.0 / 2014-01-06 -================== - - * added; selected() - * added; selectedInclusively() - * added; selectedExclusively() - -0.3.3 / 2013-11-14 -================== - - * Fix Mongo DB Dependency #20 [rschmukler](https://github.com/rschmukler) - -0.3.2 / 2013-09-06 -================== - - * added; geometry support for near() - -0.3.1 / 2013-08-22 -================== - - * fixed; update retains key order #19 - -0.3.0 / 2013-08-22 -================== - - * less hardcoded isNode env detection #18 [vshulyak](https://github.com/vshulyak) - * added; validation of findAndModify varients - * clone update doc before execution - * stricter env checks - -0.2.7 / 2013-08-2 -================== - - * Now support GeoJSON point values for Query#near - -0.2.6 / 2013-07-30 -================== - - * internally, 'asc' and 'desc' for sorts are now converted into 1 and -1, respectively - -0.2.5 / 2013-07-30 -================== - - * updated docs - * changed internal representation of `sort` to use objects instead of arrays - -0.2.4 / 2013-07-25 -================== - - * updated; sliced to 0.0.5 - -0.2.3 / 2013-07-09 -================== - - * now using a callback in collection.find instead of directly calling toArray() on the cursor [ebensing](https://github.com/ebensing) - -0.2.2 / 2013-07-09 -================== - - * now exposing mongodb export to allow for better testing [ebensing](https://github.com/ebensing) - -0.2.1 / 2013-07-08 -================== - - * select no longer accepts arrays as parameters [ebensing](https://github.com/ebensing) - -0.2.0 / 2013-07-05 -================== - - * use $geoWithin by default - -0.1.2 / 2013-07-02 -================== - - * added use$geoWithin flag [ebensing](https://github.com/ebensing) - * fix read preferences typo [ebensing](https://github.com/ebensing) - * fix reference to old param name in exists() [ebensing](https://github.com/ebensing) - -0.1.1 / 2013-06-24 -================== - - * fixed; $intersects -> $geoIntersects #14 [ebensing](https://github.com/ebensing) - * fixed; Retain key order when copying objects #15 [ebensing](https://github.com/ebensing) - * bump mongodb dev dep - -0.1.0 / 2013-05-06 -================== - - * findAndModify; return the query - * move mquery.proto.canMerge to mquery.canMerge - * overwrite option now works with non-empty objects - * use strict mode - * validate count options - * validate distinct options - * add aggregate to base collection methods - * clone merge arguments - * clone merged update arguments - * move subclass to mquery.prototype.toConstructor - * fixed; maxScan casing - * use regexp-clone - * added; geometry/intersects support - * support $and - * near: do not use "radius" - * callbacks always fire on next turn of loop - * defined collection interface - * remove time from tests - * clarify goals - * updated docs; - -0.0.1 / 2012-12-15 -================== - - * initial release diff --git a/node_modules/mquery/LICENSE b/node_modules/mquery/LICENSE deleted file mode 100644 index 38c529d..0000000 --- a/node_modules/mquery/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.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/mquery/Makefile b/node_modules/mquery/Makefile deleted file mode 100644 index 587655d..0000000 --- a/node_modules/mquery/Makefile +++ /dev/null @@ -1,26 +0,0 @@ - -test: - @NODE_ENV=test ./node_modules/.bin/mocha $(T) $(TESTS) - -test-cov: - @NODE_ENV=test node \ - node_modules/.bin/istanbul cover \ - ./node_modules/.bin/_mocha \ - -- -u exports \ - -open-cov: - open coverage/lcov-report/index.html - -lint: - @NODE_ENV=test node ./node_modules/eslint/bin/eslint.js . - -test-travis: - @NODE_ENV=test node \ - node_modules/.bin/istanbul cover \ - ./node_modules/.bin/_mocha \ - --report lcovonly \ - --bail - @NODE_ENV=test node \ - ./node_modules/eslint/bin/eslint.js . - -.PHONY: test test-cov open-cov lint test-travis diff --git a/node_modules/mquery/README.md b/node_modules/mquery/README.md deleted file mode 100644 index 58d6322..0000000 --- a/node_modules/mquery/README.md +++ /dev/null @@ -1,1375 +0,0 @@ -# mquery - -`mquery` is a fluent mongodb query builder designed to run in multiple environments. - -[![Build Status](https://travis-ci.org/aheckmann/mquery.svg?branch=master)](https://travis-ci.org/aheckmann/mquery) -[![NPM version](https://badge.fury.io/js/mquery.svg)](http://badge.fury.io/js/mquery) - -[![npm](https://nodei.co/npm/mquery.png)](https://www.npmjs.com/package/mquery) - -## Features - - - fluent query builder api - - custom base query support - - MongoDB 2.4 geoJSON support - - method + option combinations validation - - node.js driver compatibility - - environment detection - - [debug](https://github.com/visionmedia/debug) support - - separated collection implementations for maximum flexibility - -## Use - -```js -require('mongodb').connect(uri, function (err, db) { - if (err) return handleError(err); - - // get a collection - var collection = db.collection('artists'); - - // pass it to the constructor - mquery(collection).find({..}, callback); - - // or pass it to the collection method - mquery().find({..}).collection(collection).exec(callback) - - // or better yet, create a custom query constructor that has it always set - var Artist = mquery(collection).toConstructor(); - Artist().find(..).where(..).exec(callback) -}) -``` - -`mquery` requires a collection object to work with. In the example above we just pass the collection object created using the official [MongoDB driver](https://github.com/mongodb/node-mongodb-native). - - -## Fluent API - -- [find](#find) -- [findOne](#findOne) -- [count](#count) -- [remove](#remove) -- [update](#update) -- [findOneAndUpdate](#findoneandupdate) -- [findOneAndDelete, findOneAndRemove](#findoneandremove) -- [distinct](#distinct) -- [exec](#exec) -- [stream](#stream) -- [all](#all) -- [and](#and) -- [box](#box) -- [circle](#circle) -- [elemMatch](#elemmatch) -- [equals](#equals) -- [exists](#exists) -- [geometry](#geometry) -- [gt](#gt) -- [gte](#gte) -- [in](#in) -- [intersects](#intersects) -- [lt](#lt) -- [lte](#lte) -- [maxDistance](#maxdistance) -- [mod](#mod) -- [ne](#ne) -- [nin](#nin) -- [nor](#nor) -- [near](#near) -- [or](#or) -- [polygon](#polygon) -- [regex](#regex) -- [select](#select) -- [selected](#selected) -- [selectedInclusively](#selectedinclusively) -- [selectedExclusively](#selectedexclusively) -- [size](#size) -- [slice](#slice) -- [within](#within) -- [where](#where) -- [$where](#where-1) -- [batchSize](#batchsize) -- [collation](#collation) -- [comment](#comment) -- [hint](#hint) -- [j](#j) -- [limit](#limit) -- [maxScan](#maxscan) -- [maxTime, maxTimeMS](#maxtime) -- [skip](#skip) -- [sort](#sort) -- [read, setReadPreference](#read) -- [readConcern, r](#readconcern) -- [slaveOk](#slaveok) -- [snapshot](#snapshot) -- [tailable](#tailable) -- [writeConcern, w](#writeconcern) -- [wtimeout, wTimeout](#wtimeout) - -## Helpers - -- [collection](#collection) -- [then](#then) -- [thunk](#thunk) -- [merge](#mergeobject) -- [setOptions](#setoptionsoptions) -- [setTraceFunction](#settracefunctionfunc) -- [mquery.setGlobalTraceFunction](#mquerysetglobaltracefunctionfunc) -- [mquery.canMerge](#mquerycanmerge) -- [mquery.use$geoWithin](#mqueryusegeowithin) - -### find() - -Declares this query a _find_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. - -```js -mquery().find() -mquery().find(match) -mquery().find(callback) -mquery().find(match, function (err, docs) { - assert(Array.isArray(docs)); -}) -``` - -### findOne() - -Declares this query a _findOne_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. - -```js -mquery().findOne() -mquery().findOne(match) -mquery().findOne(callback) -mquery().findOne(match, function (err, doc) { - if (doc) { - // the document may not be found - console.log(doc); - } -}) -``` - -### count() - -Declares this query a _count_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. - -```js -mquery().count() -mquery().count(match) -mquery().count(callback) -mquery().count(match, function (err, number){ - console.log('we found %d matching documents', number); -}) -``` - -### remove() - -Declares this query a _remove_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. - -```js -mquery().remove() -mquery().remove(match) -mquery().remove(callback) -mquery().remove(match, function (err){}) -``` - -### update() - -Declares this query an _update_ query. Optionally pass an update document, match clause, options or callback. If a callback is passed, the query is executed. To force execution without passing a callback, run `update(true)`. - -```js -mquery().update() -mquery().update(match, updateDocument) -mquery().update(match, updateDocument, options) - -// the following all execute the command -mquery().update(callback) -mquery().update({$set: updateDocument, callback) -mquery().update(match, updateDocument, callback) -mquery().update(match, updateDocument, options, function (err, result){}) -mquery().update(true) // executes (unsafe write) -``` - -##### the update document - -All paths passed that are not `$atomic` operations will become `$set` ops. For example: - -```js -mquery(collection).where({ _id: id }).update({ title: 'words' }, callback) -``` - -becomes - -```js -collection.update({ _id: id }, { $set: { title: 'words' }}, callback) -``` - -This behavior can be overridden using the `overwrite` option (see below). - -##### options - -Options are passed to the `setOptions()` method. - -- overwrite - -Passing an empty object `{ }` as the update document will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option, the update operation will be ignored and the callback executed without sending the command to MongoDB to prevent accidently overwritting documents in the collection. - -```js -var q = mquery(collection).where({ _id: id }).setOptions({ overwrite: true }); -q.update({ }, callback); // overwrite with an empty doc -``` - -The `overwrite` option isn't just for empty objects, it also provides a means to override the default `$set` conversion and send the update document as is. - -```js -// create a base query -var base = mquery({ _id: 108 }).collection(collection).toConstructor(); - -base().findOne(function (err, doc) { - console.log(doc); // { _id: 108, name: 'cajon' }) - - base().setOptions({ overwrite: true }).update({ changed: true }, function (err) { - base.findOne(function (err, doc) { - console.log(doc); // { _id: 108, changed: true }) - the doc was overwritten - }); - }); -}) -``` - -- multi - -Updates only modify a single document by default. To update multiple documents, set the `multi` option to `true`. - -```js -mquery() - .collection(coll) - .update({ name: /^match/ }, { $addToSet: { arr: 4 }}, { multi: true }, callback) - -// another way of doing it -mquery({ name: /^match/ }) - .collection(coll) - .setOptions({ multi: true }) - .update({ $addToSet: { arr: 4 }}, callback) - -// update multiple documents with an empty doc -var q = mquery(collection).where({ name: /^match/ }); -q.setOptions({ multi: true, overwrite: true }) -q.update({ }); -q.update(function (err, result) { - console.log(arguments); -}); -``` - -### findOneAndUpdate() - -Declares this query a _findAndModify_ with update query. Optionally pass a match clause, update document, options, or callback. If a callback is passed, the query is executed. - -When executed, the first matching document (if found) is modified according to the update document and passed back to the callback. - -##### options - -Options are passed to the `setOptions()` method. - -- `new`: boolean - true to return the modified document rather than the original. defaults to true -- `upsert`: boolean - creates the object if it doesn't exist. defaults to false -- `sort`: if multiple docs are found by the match condition, sets the sort order to choose which doc to update - -```js -query.findOneAndUpdate() -query.findOneAndUpdate(updateDocument) -query.findOneAndUpdate(match, updateDocument) -query.findOneAndUpdate(match, updateDocument, options) - -// the following all execute the command -query.findOneAndUpdate(callback) -query.findOneAndUpdate(updateDocument, callback) -query.findOneAndUpdate(match, updateDocument, callback) -query.findOneAndUpdate(match, updateDocument, options, function (err, doc) { - if (doc) { - // the document may not be found - console.log(doc); - } -}) - ``` - -### findOneAndRemove() - -Declares this query a _findAndModify_ with remove query. Alias of findOneAndDelete. -Optionally pass a match clause, options, or callback. If a callback is passed, the query is executed. - -When executed, the first matching document (if found) is modified according to the update document, removed from the collection and passed to the callback. - -##### options - -Options are passed to the `setOptions()` method. - -- `sort`: if multiple docs are found by the condition, sets the sort order to choose which doc to modify and remove - -```js -A.where().findOneAndDelete() -A.where().findOneAndRemove() -A.where().findOneAndRemove(match) -A.where().findOneAndRemove(match, options) - -// the following all execute the command -A.where().findOneAndRemove(callback) -A.where().findOneAndRemove(match, callback) -A.where().findOneAndRemove(match, options, function (err, doc) { - if (doc) { - // the document may not be found - console.log(doc); - } -}) - ``` - -### distinct() - -Declares this query a _distinct_ query. Optionally pass the distinct field, a match clause or callback. If a callback is passed the query is executed. - -```js -mquery().distinct() -mquery().distinct(match) -mquery().distinct(match, field) -mquery().distinct(field) - -// the following all execute the command -mquery().distinct(callback) -mquery().distinct(field, callback) -mquery().distinct(match, callback) -mquery().distinct(match, field, function (err, result) { - console.log(result); -}) -``` - -### exec() - -Executes the query. - -```js -mquery().findOne().where('route').intersects(polygon).exec(function (err, docs){}) -``` - -### stream() - -Executes the query and returns a stream. - -```js -var stream = mquery().find().stream(options); -stream.on('data', cb); -stream.on('close', fn); -``` - -Note: this only works with `find()` operations. - -Note: returns the stream object directly from the node-mongodb-native driver. (currently streams1 type stream). Any options will be passed along to the [driver method](http://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#stream). - -------------- - -### all() - -Specifies an `$all` query condition - -```js -mquery().where('permission').all(['read', 'write']) -``` - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/all/) - -### and() - -Specifies arguments for an `$and` condition - -```js -mquery().and([{ color: 'green' }, { status: 'ok' }]) -``` - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/and/) - -### box() - -Specifies a `$box` condition - -```js -var lowerLeft = [40.73083, -73.99756] -var upperRight= [40.741404, -73.988135] - -mquery().where('location').within().box(lowerLeft, upperRight) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/box/) - -### circle() - -Specifies a `$center` or `$centerSphere` condition. - -```js -var area = { center: [50, 50], radius: 10, unique: true } -query.where('loc').within().circle(area) -query.circle('loc', area); - -// for spherical calculations -var area = { center: [50, 50], radius: 10, unique: true, spherical: true } -query.where('loc').within().circle(area) -query.circle('loc', area); -``` - -- [MongoDB Documentation - center](http://docs.mongodb.org/manual/reference/operator/center/) -- [MongoDB Documentation - centerSphere](http://docs.mongodb.org/manual/reference/operator/centerSphere/) - -### elemMatch() - -Specifies an `$elemMatch` condition - -```js -query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) - -query.elemMatch('comment', function (elem) { - elem.where('author').equals('autobot'); - elem.where('votes').gte(5); -}) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/elemMatch/) - -### equals() - -Specifies the complementary comparison value for the path specified with `where()`. - -```js -mquery().where('age').equals(49); - -// is the same as - -mquery().where({ 'age': 49 }); -``` - -### exists() - -Specifies an `$exists` condition - -```js -// { name: { $exists: true }} -mquery().where('name').exists() -mquery().where('name').exists(true) -mquery().exists('name') - -// { name: { $exists: false }} -mquery().where('name').exists(false); -mquery().exists('name', false); -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/exists/) - -### geometry() - -Specifies a `$geometry` condition - -```js -var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] -query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) - -// or -var polyB = [[ 0, 0 ], [ 1, 1 ]] -query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) - -// or -var polyC = [ 0, 0 ] -query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) - -// or -query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) - -// or -query.where('loc').near().geometry({ type: 'Point', coordinates: [3,5] }) -``` - -`geometry()` **must** come after `intersects()`, `within()`, or `near()`. - -The `object` argument must contain `type` and `coordinates` properties. - -- type `String` -- coordinates `Array` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geometry/) - -### gt() - -Specifies a `$gt` query condition. - -```js -mquery().where('clicks').gt(999) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gt/) - -### gte() - -Specifies a `$gte` query condition. - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gte/) - -```js -mquery().where('clicks').gte(1000) -``` - -### in() - -Specifies an `$in` query condition. - -```js -mquery().where('author_id').in([3, 48901, 761]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/in/) - -### intersects() - -Declares an `$geoIntersects` query for `geometry()`. - -```js -query.where('path').intersects().geometry({ - type: 'LineString' - , coordinates: [[180.0, 11.0], [180, 9.0]] -}) - -// geometry arguments are supported -query.where('path').intersects({ - type: 'LineString' - , coordinates: [[180.0, 11.0], [180, 9.0]] -}) -``` - -**Must** be used after `where()`. - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoIntersects/) - -### lt() - -Specifies a `$lt` query condition. - -```js -mquery().where('clicks').lt(50) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lt/) - -### lte() - -Specifies a `$lte` query condition. - -```js -mquery().where('clicks').lte(49) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lte/) - -### maxDistance() - -Specifies a `$maxDistance` query condition. - -```js -mquery().where('location').near({ center: [139, 74.3] }).maxDistance(5) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/maxDistance/) - -### mod() - -Specifies a `$mod` condition - -```js -mquery().where('count').mod(2, 0) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/mod/) - -### ne() - -Specifies a `$ne` query condition. - -```js -mquery().where('status').ne('ok') -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/ne/) - -### nin() - -Specifies an `$nin` query condition. - -```js -mquery().where('author_id').nin([3, 48901, 761]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nin/) - -### nor() - -Specifies arguments for an `$nor` condition. - -```js -mquery().nor([{ color: 'green' }, { status: 'ok' }]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nor/) - -### near() - -Specifies arguments for a `$near` or `$nearSphere` condition. - -These operators return documents sorted by distance. - -#### Example - -```js -query.where('loc').near({ center: [10, 10] }); -query.where('loc').near({ center: [10, 10], maxDistance: 5 }); -query.near('loc', { center: [10, 10], maxDistance: 5 }); - -// GeoJSON -query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }}); -query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }, maxDistance: 5, spherical: true }); -query.where('loc').near().geometry({ type: 'Point', coordinates: [10, 10] }); - -// For a $nearSphere condition, pass the `spherical` option. -query.near({ center: [10, 10], maxDistance: 5, spherical: true }); -``` - -[MongoDB Documentation](http://www.mongodb.org/display/DOCS/Geospatial+Indexing) - -### or() - -Specifies arguments for an `$or` condition. - -```js -mquery().or([{ color: 'red' }, { status: 'emergency' }]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/or/) - -### polygon() - -Specifies a `$polygon` condition - -```js -mquery().where('loc').within().polygon([10,20], [13, 25], [7,15]) -mquery().polygon('loc', [10,20], [13, 25], [7,15]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/polygon/) - -### regex() - -Specifies a `$regex` query condition. - -```js -mquery().where('name').regex(/^sixstepsrecords/) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/regex/) - -### select() - -Specifies which document fields to include or exclude - -```js -// 1 means include, 0 means exclude -mquery().select({ name: 1, address: 1, _id: 0 }) - -// or - -mquery().select('name address -_id') -``` - -##### String syntax - -When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. - -```js -// include a and b, exclude c -query.select('a b -c'); - -// or you may use object notation, useful when -// you have keys already prefixed with a "-" -query.select({a: 1, b: 1, c: 0}); -``` - -_Cannot be used with `distinct()`._ - -### selected() - -Determines if the query has selected any fields. - -```js -var query = mquery(); -query.selected() // false -query.select('-name'); -query.selected() // true -``` - -### selectedInclusively() - -Determines if the query has selected any fields inclusively. - -```js -var query = mquery().select('name'); -query.selectedInclusively() // true - -var query = mquery(); -query.selected() // false -query.select('-name'); -query.selectedInclusively() // false -query.selectedExclusively() // true -``` - -### selectedExclusively() - -Determines if the query has selected any fields exclusively. - -```js -var query = mquery().select('-name'); -query.selectedExclusively() // true - -var query = mquery(); -query.selected() // false -query.select('name'); -query.selectedExclusively() // false -query.selectedInclusively() // true -``` - -### size() - -Specifies a `$size` query condition. - -```js -mquery().where('someArray').size(6) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/size/) - -### slice() - -Specifies a `$slice` projection for a `path` - -```js -mquery().where('comments').slice(5) -mquery().where('comments').slice(-5) -mquery().where('comments').slice([-10, 5]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/projection/slice/) - -### within() - -Sets a `$geoWithin` or `$within` argument for geo-spatial queries. - -```js -mquery().within().box() -mquery().within().circle() -mquery().within().geometry() - -mquery().where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); -mquery().where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); -mquery().where('loc').within({ polygon: [[],[],[],[]] }); - -mquery().where('loc').within([], [], []) // polygon -mquery().where('loc').within([], []) // box -mquery().where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry -``` - -As of mquery 2.0, `$geoWithin` is used by default. This impacts you if running MongoDB < 2.4. To alter this behavior, see [mquery.use$geoWithin](#mqueryusegeowithin). - -**Must** be used after `where()`. - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoWithin/) - -### where() - -Specifies a `path` for use with chaining - -```js -// instead of writing: -mquery().find({age: {$gte: 21, $lte: 65}}); - -// we can instead write: -mquery().where('age').gte(21).lte(65); - -// passing query conditions is permitted too -mquery().find().where({ name: 'vonderful' }) - -// chaining -mquery() -.where('age').gte(21).lte(65) -.where({ 'name': /^vonderful/i }) -.where('friends').slice(10) -.exec(callback) -``` - -### $where() - -Specifies a `$where` condition. - -Use `$where` when you need to select documents using a JavaScript expression. - -```js -query.$where('this.comments.length > 10 || this.name.length > 5').exec(callback) - -query.$where(function () { - return this.comments.length > 10 || this.name.length > 5; -}) -``` - -Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using. - ------------ - -### batchSize() - -Specifies the batchSize option. - -```js -query.batchSize(100) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.batchSize/) - -### collation() - -Specifies the collation option. - -```js -query.collation({ locale: "en_US", strength: 1 }) -``` - -[MongoDB documentation](https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation) - -### comment() - -Specifies the comment option. - -```js -query.comment('login query'); -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/) - -### hint() - -Sets query hints. - -```js -mquery().hint({ indexA: 1, indexB: -1 }) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/hint/) - -### j() - -Requests acknowledgement that this operation has been persisted to MongoDB's on-disk journal. - -This option is only valid for operations that write to the database: - -- `deleteOne()` -- `deleteMany()` -- `findOneAndDelete()` -- `findOneAndUpdate()` -- `remove()` -- `update()` -- `updateOne()` -- `updateMany()` - -Defaults to the `j` value if it is specified in [writeConcern](#writeconcern) - -```js -mquery().j(true); -``` - -### limit() - -Specifies the limit option. - -```js -query.limit(20) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.limit/) - -### maxScan() - -Specifies the maxScan option. - -```js -query.maxScan(100) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/maxScan/) - -### maxTime() - -Specifies the maxTimeMS option. - -```js -query.maxTime(100) -query.maxTimeMS(100) -``` - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.maxTimeMS/) - - -### skip() - -Specifies the skip option. - -```js -query.skip(100).limit(20) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.skip/) - -### sort() - -Sets the query sort order. - -If an object is passed, key values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. - -If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. - -```js -// these are equivalent -query.sort({ field: 'asc', test: -1 }); -query.sort('field -test'); -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.sort/) - -### read() - -Sets the readPreference option for the query. - -```js -mquery().read('primary') -mquery().read('p') // same as primary - -mquery().read('primaryPreferred') -mquery().read('pp') // same as primaryPreferred - -mquery().read('secondary') -mquery().read('s') // same as secondary - -mquery().read('secondaryPreferred') -mquery().read('sp') // same as secondaryPreferred - -mquery().read('nearest') -mquery().read('n') // same as nearest - -mquery().setReadPreference('primary') // alias of .read() -``` - -##### Preferences: - -- `primary` - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. -- `secondary` - Read from secondary if available, otherwise error. -- `primaryPreferred` - Read from primary if available, otherwise a secondary. -- `secondaryPreferred` - Read from a secondary if available, otherwise read from the primary. -- `nearest` - All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. - -Aliases - -- `p` primary -- `pp` primaryPreferred -- `s` secondary -- `sp` secondaryPreferred -- `n` nearest - -##### Preference Tags: - -To keep the separation of concerns between `mquery` and your driver -clean, `mquery#read()` no longer handles specifying a second `tags` argument as of version 0.5. -If you need to specify tags, pass any non-string argument as the first argument. -`mquery` will pass this argument untouched to your collections methods later. -For example: - -```js -// example of specifying tags using the Node.js driver -var ReadPref = require('mongodb').ReadPreference; -var preference = new ReadPref('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]); -mquery(..).read(preference).exec(); -``` - -Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). - - -### readConcern() - -Sets the readConcern option for the query. - -```js -// local -mquery().readConcern('local') -mquery().readConcern('l') -mquery().r('l') - -// available -mquery().readConcern('available') -mquery().readConcern('a') -mquery().r('a') - -// majority -mquery().readConcern('majority') -mquery().readConcern('m') -mquery().r('m') - -// linearizable -mquery().readConcern('linearizable') -mquery().readConcern('lz') -mquery().r('lz') - -// snapshot -mquery().readConcern('snapshot') -mquery().readConcern('s') -mquery().r('s') -``` - -##### Read Concern Level: - -- `local` - The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). (MongoDB 3.2+) -- `available` - The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). (MongoDB 3.6+) -- `majority` - The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. (MongoDB 3.2+) -- `linearizable` - The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. (MongoDB 3.4+) -- `snapshot` - Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. (MongoDB 4.0+) - -Aliases - -- `l` local -- `a` available -- `m` majority -- `lz` linearizable -- `s` snapshot - -Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). - -### writeConcern() - -Sets the writeConcern option for the query. - -This option is only valid for operations that write to the database: - -- `deleteOne()` -- `deleteMany()` -- `findOneAndDelete()` -- `findOneAndUpdate()` -- `remove()` -- `update()` -- `updateOne()` -- `updateMany()` - -```js -mquery().writeConcern(0) -mquery().writeConcern(1) -mquery().writeConcern({ w: 1, j: true, wtimeout: 2000 }) -mquery().writeConcern('majority') -mquery().writeConcern('m') // same as majority -mquery().writeConcern('tagSetName') // if the tag set is 'm', use .writeConcern({ w: 'm' }) instead -mquery().w(1) // w is alias of writeConcern -``` - -##### Write Concern: - -writeConcern({ w: ``, j: ``, wtimeout: `` }`) - -- the w option to request acknowledgement that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags -- the j option to request acknowledgement that the write operation has been written to the journal -- the wtimeout option to specify a time limit to prevent write operations from blocking indefinitely - -Can be break down to use the following syntax: - -mquery().w(``).j(``).wtimeout(``) - -Read more about how to use write concern [here](https://docs.mongodb.com/manual/reference/write-concern/) - -### slaveOk() - -Sets the slaveOk option. `true` allows reading from secondaries. - -**deprecated** use [read()](#read) preferences instead if on mongodb >= 2.2 - -```js -query.slaveOk() // true -query.slaveOk(true) -query.slaveOk(false) -``` - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/rs.slaveOk/) - -### snapshot() - -Specifies this query as a snapshot query. - -```js -mquery().snapshot() // true -mquery().snapshot(true) -mquery().snapshot(false) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/snapshot/) - -### tailable() - -Sets tailable option. - -```js -mquery().tailable() <== true -mquery().tailable(true) -mquery().tailable(false) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB Documentation](http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/) - -### wtimeout() - -Specifies a time limit, in milliseconds, for the write concern. If `w > 1`, it is maximum amount of time to -wait for this write to propagate through the replica set before this operation fails. The default is `0`, which means no timeout. - -This option is only valid for operations that write to the database: - -- `deleteOne()` -- `deleteMany()` -- `findOneAndDelete()` -- `findOneAndUpdate()` -- `remove()` -- `update()` -- `updateOne()` -- `updateMany()` - -Defaults to `wtimeout` value if it is specified in [writeConcern](#writeconcern) - -```js -mquery().wtimeout(2000) -mquery().wTimeout(2000) -``` - -## Helpers - -### collection() - -Sets the querys collection. - -```js -mquery().collection(aCollection) -``` - -### then() - -Executes the query and returns a promise which will be resolved with the query results or rejected if the query responds with an error. - -```js -mquery().find(..).then(success, error); -``` - -This is very useful when combined with [co](https://github.com/visionmedia/co) or [koa](https://github.com/koajs/koa), which automatically resolve promise-like objects for you. - -```js -co(function*(){ - var doc = yield mquery().findOne({ _id: 499 }); - console.log(doc); // { _id: 499, name: 'amazing', .. } -})(); -``` - -_NOTE_: -The returned promise is a [bluebird](https://github.com/petkaantonov/bluebird/) promise but this is customizable. If you want to -use your favorite promise library, simply set `mquery.Promise = YourPromiseConstructor`. -Your `Promise` must be [promises A+](http://promisesaplus.com/) compliant. - -### thunk() - -Returns a thunk which when called runs the query's `exec` method passing the results to the callback. - -```js -var thunk = mquery(collection).find({..}).thunk(); - -thunk(function(err, results) { - -}) -``` - -### merge(object) - -Merges other mquery or match condition objects into this one. When an mquery instance is passed, its match conditions, field selection and options are merged. - -```js -var drum = mquery({ type: 'drum' }).collection(instruments); -var redDrum = mquery({ color: 'red' }).merge(drum); -redDrum.count(function (err, n) { - console.log('there are %d red drums', n); -}) -``` - -Internally uses `mquery.canMerge` to determine validity. - -### setOptions(options) - -Sets query options. - -```js -mquery().setOptions({ collection: coll, limit: 20 }) -``` - -##### options - -- [tailable](#tailable) * -- [sort](#sort) * -- [limit](#limit) * -- [skip](#skip) * -- [maxScan](#maxscan) * -- [maxTime](#maxtime) * -- [batchSize](#batchSize) * -- [comment](#comment) * -- [snapshot](#snapshot) * -- [hint](#hint) * -- [slaveOk](#slaveOk) * -- [safe](http://docs.mongodb.org/manual/reference/write-concern/): Boolean - passed through to the collection. Setting to `true` is equivalent to `{ w: 1 }` -- [collection](#collection): the collection to query against - -_* denotes a query helper method is also available_ - -### setTraceFunction(func) - -Set a function to trace this query. Useful for profiling or logging. - -```js -function traceFunction (method, queryInfo, query) { - console.log('starting ' + method + ' query'); - - return function (err, result, millis) { - console.log('finished ' + method + ' query in ' + millis + 'ms'); - }; -} - -mquery().setTraceFunction(traceFunction).findOne({name: 'Joe'}, cb); -``` - -The trace function is passed (method, queryInfo, query) - -- method is the name of the method being called (e.g. findOne) -- queryInfo contains information about the query: - - conditions: query conditions/criteria - - options: options such as sort, fields, etc - - doc: document being updated -- query is the query object - -The trace function should return a callback function which accepts: -- err: error, if any -- result: result, if any -- millis: time spent waiting for query result - -NOTE: stream requests are not traced. - -### mquery.setGlobalTraceFunction(func) - -Similar to `setTraceFunction()` but automatically applied to all queries. - -```js -mquery.setTraceFunction(traceFunction); -``` - -### mquery.canMerge(conditions) - -Determines if `conditions` can be merged using `mquery().merge()`. - -```js -var query = mquery({ type: 'drum' }); -var okToMerge = mquery.canMerge(anObject) -if (okToMerge) { - query.merge(anObject); -} -``` - -## mquery.use$geoWithin - -MongoDB 2.4 introduced the `$geoWithin` operator which replaces and is 100% backward compatible with `$within`. As of mquery 0.2, we default to using `$geoWithin` for all `within()` calls. - -If you are running MongoDB < 2.4 this will be problematic. To force `mquery` to be backward compatible and always use `$within`, set the `mquery.use$geoWithin` flag to `false`. - -```js -mquery.use$geoWithin = false; -``` - -## Custom Base Queries - -Often times we want custom base queries that encapsulate predefined criteria. With `mquery` this is easy. First create the query you want to reuse and call its `toConstructor()` method which returns a new subclass of `mquery` that retains all options and criteria of the original. - -```js -var greatMovies = mquery(movieCollection).where('rating').gte(4.5).toConstructor(); - -// use it! -greatMovies().count(function (err, n) { - console.log('There are %d great movies', n); -}); - -greatMovies().where({ name: /^Life/ }).select('name').find(function (err, docs) { - console.log(docs); -}); -``` - -## Validation - -Method and options combinations are checked for validity at runtime to prevent creation of invalid query constructs. For example, a `distinct` query does not support specifying options like `hint` or field selection. In this case an error will be thrown so you can catch these mistakes in development. - -## Debug support - -Debug mode is provided through the use of the [debug](https://github.com/visionmedia/debug) module. To enable: - - DEBUG=mquery node yourprogram.js - -Read the debug module documentation for more details. - -## General compatibility - -#### ObjectIds - -`mquery` clones query arguments before passing them to a `collection` method for execution. -This prevents accidental side-affects to the objects you pass. -To clone `ObjectIds` we need to make some assumptions. - -First, to check if an object is an `ObjectId`, we check its constructors name. If it matches either -`ObjectId` or `ObjectID` we clone it. - -To clone `ObjectIds`, we call its optional `clone` method. If a `clone` method does not exist, we fall -back to calling `new obj.constructor(obj.id)`. We assume, for compatibility with the -Node.js driver, that the `ObjectId` instance has a public `id` property and that -when creating an `ObjectId` instance we can pass that `id` as an argument. - -#### Read Preferences - -`mquery` supports specifying [Read Preferences]() to control from which MongoDB node your query will read. -The Read Preferences spec also support specifying tags. To pass tags, some -drivers (Node.js driver) require passing a special constructor that handles both the read preference and its tags. -If you need to specify tags, pass an instance of your drivers ReadPreference constructor or roll your own. `mquery` will store whatever you provide and pass later to your collection during execution. - -## Future goals - - - mongo shell compatibility - - browser compatibility - -## Installation - - $ npm install mquery - -## License - -[MIT](https://github.com/aheckmann/mquery/blob/master/LICENSE) - diff --git a/node_modules/mquery/lib/collection/collection.js b/node_modules/mquery/lib/collection/collection.js deleted file mode 100644 index 0f39c76..0000000 --- a/node_modules/mquery/lib/collection/collection.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -/** - * methods a collection must implement - */ - -var methods = [ - 'find', - 'findOne', - 'update', - 'updateMany', - 'updateOne', - 'replaceOne', - 'remove', - 'count', - 'distinct', - 'findAndModify', - 'aggregate', - 'findStream', - 'deleteOne', - 'deleteMany' -]; - -/** - * Collection base class from which implementations inherit - */ - -function Collection() {} - -for (var i = 0, len = methods.length; i < len; ++i) { - var method = methods[i]; - Collection.prototype[method] = notImplemented(method); -} - -module.exports = exports = Collection; -Collection.methods = methods; - -/** - * creates a function which throws an implementation error - */ - -function notImplemented(method) { - return function() { - throw new Error('collection.' + method + ' not implemented'); - }; -} diff --git a/node_modules/mquery/lib/collection/index.js b/node_modules/mquery/lib/collection/index.js deleted file mode 100644 index 1992e20..0000000 --- a/node_modules/mquery/lib/collection/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var env = require('../env'); - -if ('unknown' == env.type) { - throw new Error('Unknown environment'); -} - -module.exports = - env.isNode ? require('./node') : - env.isMongo ? require('./collection') : - require('./collection'); - diff --git a/node_modules/mquery/lib/collection/node.js b/node_modules/mquery/lib/collection/node.js deleted file mode 100644 index cc07d60..0000000 --- a/node_modules/mquery/lib/collection/node.js +++ /dev/null @@ -1,151 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ - -var Collection = require('./collection'); -var utils = require('../utils'); - -function NodeCollection(col) { - this.collection = col; - this.collectionName = col.collectionName; -} - -/** - * inherit from collection base class - */ - -utils.inherits(NodeCollection, Collection); - -/** - * find(match, options, function(err, docs)) - */ - -NodeCollection.prototype.find = function(match, options, cb) { - this.collection.find(match, options, function(err, cursor) { - if (err) return cb(err); - - try { - cursor.toArray(cb); - } catch (error) { - cb(error); - } - }); -}; - -/** - * findOne(match, options, function(err, doc)) - */ - -NodeCollection.prototype.findOne = function(match, options, cb) { - this.collection.findOne(match, options, cb); -}; - -/** - * count(match, options, function(err, count)) - */ - -NodeCollection.prototype.count = function(match, options, cb) { - this.collection.count(match, options, cb); -}; - -/** - * distinct(prop, match, options, function(err, count)) - */ - -NodeCollection.prototype.distinct = function(prop, match, options, cb) { - this.collection.distinct(prop, match, options, cb); -}; - -/** - * update(match, update, options, function(err[, result])) - */ - -NodeCollection.prototype.update = function(match, update, options, cb) { - this.collection.update(match, update, options, cb); -}; - -/** - * update(match, update, options, function(err[, result])) - */ - -NodeCollection.prototype.updateMany = function(match, update, options, cb) { - this.collection.updateMany(match, update, options, cb); -}; - -/** - * update(match, update, options, function(err[, result])) - */ - -NodeCollection.prototype.updateOne = function(match, update, options, cb) { - this.collection.updateOne(match, update, options, cb); -}; - -/** - * replaceOne(match, update, options, function(err[, result])) - */ - -NodeCollection.prototype.replaceOne = function(match, update, options, cb) { - this.collection.replaceOne(match, update, options, cb); -}; - -/** - * deleteOne(match, options, function(err[, result]) - */ - -NodeCollection.prototype.deleteOne = function(match, options, cb) { - this.collection.deleteOne(match, options, cb); -}; - -/** - * deleteMany(match, options, function(err[, result]) - */ - -NodeCollection.prototype.deleteMany = function(match, options, cb) { - this.collection.deleteMany(match, options, cb); -}; - -/** - * remove(match, options, function(err[, result]) - */ - -NodeCollection.prototype.remove = function(match, options, cb) { - this.collection.remove(match, options, cb); -}; - -/** - * findAndModify(match, update, options, function(err, doc)) - */ - -NodeCollection.prototype.findAndModify = function(match, update, options, cb) { - var sort = Array.isArray(options.sort) ? options.sort : []; - this.collection.findAndModify(match, sort, update, options, cb); -}; - -/** - * var stream = findStream(match, findOptions, streamOptions) - */ - -NodeCollection.prototype.findStream = function(match, findOptions, streamOptions) { - return this.collection.find(match, findOptions).stream(streamOptions); -}; - -/** - * var cursor = findCursor(match, findOptions) - */ - -NodeCollection.prototype.findCursor = function(match, findOptions) { - return this.collection.find(match, findOptions); -}; - -/** - * aggregation(operators..., function(err, doc)) - * TODO - */ - -/** - * Expose - */ - -module.exports = exports = NodeCollection; diff --git a/node_modules/mquery/lib/env.js b/node_modules/mquery/lib/env.js deleted file mode 100644 index d3d225b..0000000 --- a/node_modules/mquery/lib/env.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -exports.isNode = 'undefined' != typeof process - && 'object' == typeof module - && 'object' == typeof global - && 'function' == typeof Buffer - && process.argv; - -exports.isMongo = !exports.isNode - && 'function' == typeof printjson - && 'function' == typeof ObjectId - && 'function' == typeof rs - && 'function' == typeof sh; - -exports.isBrowser = !exports.isNode - && !exports.isMongo - && 'undefined' != typeof window; - -exports.type = exports.isNode ? 'node' - : exports.isMongo ? 'mongo' - : exports.isBrowser ? 'browser' - : 'unknown'; diff --git a/node_modules/mquery/lib/mquery.js b/node_modules/mquery/lib/mquery.js deleted file mode 100644 index 8fdd9e1..0000000 --- a/node_modules/mquery/lib/mquery.js +++ /dev/null @@ -1,3252 +0,0 @@ -'use strict'; - -/** - * Dependencies - */ - -var slice = require('sliced'); -var assert = require('assert'); -var util = require('util'); -var utils = require('./utils'); -var debug = require('debug')('mquery'); - -/* global Map */ - -/** - * Query constructor used for building queries. - * - * ####Example: - * - * var query = new Query({ name: 'mquery' }); - * query.setOptions({ collection: moduleCollection }) - * query.where('age').gte(21).exec(callback); - * - * @param {Object} [criteria] - * @param {Object} [options] - * @api public - */ - -function Query(criteria, options) { - if (!(this instanceof Query)) - return new Query(criteria, options); - - var proto = this.constructor.prototype; - - this.op = proto.op || undefined; - - this.options = Object.assign({}, proto.options); - - this._conditions = proto._conditions - ? utils.clone(proto._conditions) - : {}; - - this._fields = proto._fields - ? utils.clone(proto._fields) - : undefined; - - this._update = proto._update - ? utils.clone(proto._update) - : undefined; - - this._path = proto._path || undefined; - this._distinct = proto._distinct || undefined; - this._collection = proto._collection || undefined; - this._traceFunction = proto._traceFunction || undefined; - - if (options) { - this.setOptions(options); - } - - if (criteria) { - if (criteria.find && criteria.remove && criteria.update) { - // quack quack! - this.collection(criteria); - } else { - this.find(criteria); - } - } -} - -/** - * This is a parameter that the user can set which determines if mquery - * uses $within or $geoWithin for queries. It defaults to true which - * means $geoWithin will be used. If using MongoDB < 2.4 you should - * set this to false. - * - * @api public - * @property use$geoWithin - */ - -var $withinCmd = '$geoWithin'; -Object.defineProperty(Query, 'use$geoWithin', { - get: function( ) { return $withinCmd == '$geoWithin'; }, - set: function(v) { - if (true === v) { - // mongodb >= 2.4 - $withinCmd = '$geoWithin'; - } else { - $withinCmd = '$within'; - } - } -}); - -/** - * Converts this query to a constructor function with all arguments and options retained. - * - * ####Example - * - * // Create a query that will read documents with a "video" category from - * // `aCollection` on the primary node in the replica-set unless it is down, - * // in which case we'll read from a secondary node. - * var query = mquery({ category: 'video' }) - * query.setOptions({ collection: aCollection, read: 'primaryPreferred' }); - * - * // create a constructor based off these settings - * var Video = query.toConstructor(); - * - * // Video is now a subclass of mquery() and works the same way but with the - * // default query parameters and options set. - * - * // run a query with the previous settings but filter for movies with names - * // that start with "Life". - * Video().where({ name: /^Life/ }).exec(cb); - * - * @return {Query} new Query - * @api public - */ - -Query.prototype.toConstructor = function toConstructor() { - function CustomQuery(criteria, options) { - if (!(this instanceof CustomQuery)) - return new CustomQuery(criteria, options); - Query.call(this, criteria, options); - } - - utils.inherits(CustomQuery, Query); - - // set inherited defaults - var p = CustomQuery.prototype; - - p.options = {}; - p.setOptions(this.options); - - p.op = this.op; - p._conditions = utils.clone(this._conditions); - p._fields = utils.clone(this._fields); - p._update = utils.clone(this._update); - p._path = this._path; - p._distinct = this._distinct; - p._collection = this._collection; - p._traceFunction = this._traceFunction; - - return CustomQuery; -}; - -/** - * Sets query options. - * - * ####Options: - * - * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * - * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * - * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * - * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * - * - [maxScan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) * - * - [maxTime](http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS) * - * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * - * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * - * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * - * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * - * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) * - * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) - * - collection the collection to query against - * - * _* denotes a query helper method is also available_ - * - * @param {Object} options - * @api public - */ - -Query.prototype.setOptions = function(options) { - if (!(options && utils.isObject(options))) - return this; - - // set arbitrary options - var methods = utils.keys(options), - method; - - for (var i = 0; i < methods.length; ++i) { - method = methods[i]; - - // use methods if exist (safer option manipulation) - if ('function' == typeof this[method]) { - var args = utils.isArray(options[method]) - ? options[method] - : [options[method]]; - this[method].apply(this, args); - } else { - this.options[method] = options[method]; - } - } - - return this; -}; - -/** - * Sets this Querys collection. - * - * @param {Collection} coll - * @return {Query} this - */ - -Query.prototype.collection = function collection(coll) { - this._collection = new Query.Collection(coll); - - return this; -}; - -/** - * Adds a collation to this op (MongoDB 3.4 and up) - * - * ####Example - * - * query.find().collation({ locale: "en_US", strength: 1 }) - * - * @param {Object} value - * @return {Query} this - * @see MongoDB docs https://docs.mongodb.com/manual/reference/method/cursor.collation/#cursor.collation - * @api public - */ - -Query.prototype.collation = function(value) { - this.options.collation = value; - return this; -}; - -/** - * Specifies a `$where` condition - * - * Use `$where` when you need to select documents using a JavaScript expression. - * - * ####Example - * - * query.$where('this.comments.length > 10 || this.name.length > 5') - * - * query.$where(function () { - * return this.comments.length > 10 || this.name.length > 5; - * }) - * - * @param {String|Function} js javascript string or function - * @return {Query} this - * @memberOf Query - * @method $where - * @api public - */ - -Query.prototype.$where = function(js) { - this._conditions.$where = js; - return this; -}; - -/** - * Specifies a `path` for use with chaining. - * - * ####Example - * - * // instead of writing: - * User.find({age: {$gte: 21, $lte: 65}}, callback); - * - * // we can instead write: - * User.where('age').gte(21).lte(65); - * - * // passing query conditions is permitted - * User.find().where({ name: 'vonderful' }) - * - * // chaining - * User - * .where('age').gte(21).lte(65) - * .where('name', /^vonderful/i) - * .where('friends').slice(10) - * .exec(callback) - * - * @param {String} [path] - * @param {Object} [val] - * @return {Query} this - * @api public - */ - -Query.prototype.where = function() { - if (!arguments.length) return this; - if (!this.op) this.op = 'find'; - - var type = typeof arguments[0]; - - if ('string' == type) { - this._path = arguments[0]; - - if (2 === arguments.length) { - this._conditions[this._path] = arguments[1]; - } - - return this; - } - - if ('object' == type && !Array.isArray(arguments[0])) { - return this.merge(arguments[0]); - } - - throw new TypeError('path must be a string or object'); -}; - -/** - * Specifies the complementary comparison value for paths specified with `where()` - * - * ####Example - * - * User.where('age').equals(49); - * - * // is the same as - * - * User.where('age', 49); - * - * @param {Object} val - * @return {Query} this - * @api public - */ - -Query.prototype.equals = function equals(val) { - this._ensurePath('equals'); - var path = this._path; - this._conditions[path] = val; - return this; -}; - -/** - * Specifies the complementary comparison value for paths specified with `where()` - * This is alias of `equals` - * - * ####Example - * - * User.where('age').eq(49); - * - * // is the same as - * - * User.shere('age').equals(49); - * - * // is the same as - * - * User.where('age', 49); - * - * @param {Object} val - * @return {Query} this - * @api public - */ - -Query.prototype.eq = function eq(val) { - this._ensurePath('eq'); - var path = this._path; - this._conditions[path] = val; - return this; -}; - -/** - * Specifies arguments for an `$or` condition. - * - * ####Example - * - * query.or([{ color: 'red' }, { status: 'emergency' }]) - * - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -Query.prototype.or = function or(array) { - var or = this._conditions.$or || (this._conditions.$or = []); - if (!utils.isArray(array)) array = [array]; - or.push.apply(or, array); - return this; -}; - -/** - * Specifies arguments for a `$nor` condition. - * - * ####Example - * - * query.nor([{ color: 'green' }, { status: 'ok' }]) - * - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -Query.prototype.nor = function nor(array) { - var nor = this._conditions.$nor || (this._conditions.$nor = []); - if (!utils.isArray(array)) array = [array]; - nor.push.apply(nor, array); - return this; -}; - -/** - * Specifies arguments for a `$and` condition. - * - * ####Example - * - * query.and([{ color: 'green' }, { status: 'ok' }]) - * - * @see $and http://docs.mongodb.org/manual/reference/operator/and/ - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -Query.prototype.and = function and(array) { - var and = this._conditions.$and || (this._conditions.$and = []); - if (!Array.isArray(array)) array = [array]; - and.push.apply(and, array); - return this; -}; - -/** - * Specifies a $gt query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example - * - * Thing.find().where('age').gt(21) - * - * // or - * Thing.find().gt('age', 21) - * - * @method gt - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $gte query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method gte - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $lt query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lt - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $lte query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lte - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $ne query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method ne - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $in query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method in - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $nin query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method nin - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $all query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method all - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $size query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method size - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $regex query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method regex - * @memberOf Query - * @param {String} [path] - * @param {String|RegExp} val - * @api public - */ - -/** - * Specifies a $maxDistance query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method maxDistance - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/*! - * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance - * - * Thing.where('type').nin(array) - */ - -'gt gte lt lte ne in nin all regex size maxDistance minDistance'.split(' ').forEach(function($conditional) { - Query.prototype[$conditional] = function() { - var path, val; - - if (1 === arguments.length) { - this._ensurePath($conditional); - val = arguments[0]; - path = this._path; - } else { - val = arguments[1]; - path = arguments[0]; - } - - var conds = this._conditions[path] === null || typeof this._conditions[path] === 'object' ? - this._conditions[path] : - (this._conditions[path] = {}); - conds['$' + $conditional] = val; - return this; - }; -}); - -/** - * Specifies a `$mod` condition - * - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @api public - */ - -Query.prototype.mod = function() { - var val, path; - - if (1 === arguments.length) { - this._ensurePath('mod'); - val = arguments[0]; - path = this._path; - } else if (2 === arguments.length && !utils.isArray(arguments[1])) { - this._ensurePath('mod'); - val = slice(arguments); - path = this._path; - } else if (3 === arguments.length) { - val = slice(arguments, 1); - path = arguments[0]; - } else { - val = arguments[1]; - path = arguments[0]; - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$mod = val; - return this; -}; - -/** - * Specifies an `$exists` condition - * - * ####Example - * - * // { name: { $exists: true }} - * Thing.where('name').exists() - * Thing.where('name').exists(true) - * Thing.find().exists('name') - * - * // { name: { $exists: false }} - * Thing.where('name').exists(false); - * Thing.find().exists('name', false); - * - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @api public - */ - -Query.prototype.exists = function() { - var path, val; - - if (0 === arguments.length) { - this._ensurePath('exists'); - path = this._path; - val = true; - } else if (1 === arguments.length) { - if ('boolean' === typeof arguments[0]) { - this._ensurePath('exists'); - path = this._path; - val = arguments[0]; - } else { - path = arguments[0]; - val = true; - } - } else if (2 === arguments.length) { - path = arguments[0]; - val = arguments[1]; - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$exists = val; - return this; -}; - -/** - * Specifies an `$elemMatch` condition - * - * ####Example - * - * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) - * - * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) - * - * query.elemMatch('comment', function (elem) { - * elem.where('author').equals('autobot'); - * elem.where('votes').gte(5); - * }) - * - * query.where('comment').elemMatch(function (elem) { - * elem.where({ author: 'autobot' }); - * elem.where('votes').gte(5); - * }) - * - * @param {String|Object|Function} path - * @param {Object|Function} criteria - * @return {Query} this - * @api public - */ - -Query.prototype.elemMatch = function() { - if (null == arguments[0]) - throw new TypeError('Invalid argument'); - - var fn, path, criteria; - - if ('function' === typeof arguments[0]) { - this._ensurePath('elemMatch'); - path = this._path; - fn = arguments[0]; - } else if (utils.isObject(arguments[0])) { - this._ensurePath('elemMatch'); - path = this._path; - criteria = arguments[0]; - } else if ('function' === typeof arguments[1]) { - path = arguments[0]; - fn = arguments[1]; - } else if (arguments[1] && utils.isObject(arguments[1])) { - path = arguments[0]; - criteria = arguments[1]; - } else { - throw new TypeError('Invalid argument'); - } - - if (fn) { - criteria = new Query; - fn(criteria); - criteria = criteria._conditions; - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$elemMatch = criteria; - return this; -}; - -// Spatial queries - -/** - * Sugar for geo-spatial queries. - * - * ####Example - * - * query.within().box() - * query.within().circle() - * query.within().geometry() - * - * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); - * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); - * query.where('loc').within({ polygon: [[],[],[],[]] }); - * - * query.where('loc').within([], [], []) // polygon - * query.where('loc').within([], []) // box - * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry - * - * ####NOTE: - * - * Must be used after `where()`. - * - * @memberOf Query - * @return {Query} this - * @api public - */ - -Query.prototype.within = function within() { - // opinionated, must be used after where - this._ensurePath('within'); - this._geoComparison = $withinCmd; - - if (0 === arguments.length) { - return this; - } - - if (2 === arguments.length) { - return this.box.apply(this, arguments); - } else if (2 < arguments.length) { - return this.polygon.apply(this, arguments); - } - - var area = arguments[0]; - - if (!area) - throw new TypeError('Invalid argument'); - - if (area.center) - return this.circle(area); - - if (area.box) - return this.box.apply(this, area.box); - - if (area.polygon) - return this.polygon.apply(this, area.polygon); - - if (area.type && area.coordinates) - return this.geometry(area); - - throw new TypeError('Invalid argument'); -}; - -/** - * Specifies a $box condition - * - * ####Example - * - * var lowerLeft = [40.73083, -73.99756] - * var upperRight= [40.741404, -73.988135] - * - * query.where('loc').within().box(lowerLeft, upperRight) - * query.box('loc', lowerLeft, upperRight ) - * - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @see Query#within #query_Query-within - * @param {String} path - * @param {Object} val - * @return {Query} this - * @api public - */ - -Query.prototype.box = function() { - var path, box; - - if (3 === arguments.length) { - // box('loc', [], []) - path = arguments[0]; - box = [arguments[1], arguments[2]]; - } else if (2 === arguments.length) { - // box([], []) - this._ensurePath('box'); - path = this._path; - box = [arguments[0], arguments[1]]; - } else { - throw new TypeError('Invalid argument'); - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds[this._geoComparison || $withinCmd] = { '$box': box }; - return this; -}; - -/** - * Specifies a $polygon condition - * - * ####Example - * - * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) - * query.polygon('loc', [10,20], [13, 25], [7,15]) - * - * @param {String|Array} [path] - * @param {Array|Object} [val] - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -Query.prototype.polygon = function() { - var val, path; - - if ('string' == typeof arguments[0]) { - // polygon('loc', [],[],[]) - path = arguments[0]; - val = slice(arguments, 1); - } else { - // polygon([],[],[]) - this._ensurePath('polygon'); - path = this._path; - val = slice(arguments); - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds[this._geoComparison || $withinCmd] = { '$polygon': val }; - return this; -}; - -/** - * Specifies a $center or $centerSphere condition. - * - * ####Example - * - * var area = { center: [50, 50], radius: 10, unique: true } - * query.where('loc').within().circle(area) - * query.center('loc', area); - * - * // for spherical calculations - * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } - * query.where('loc').within().circle(area) - * query.center('loc', area); - * - * @param {String} [path] - * @param {Object} area - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -Query.prototype.circle = function() { - var path, val; - - if (1 === arguments.length) { - this._ensurePath('circle'); - path = this._path; - val = arguments[0]; - } else if (2 === arguments.length) { - path = arguments[0]; - val = arguments[1]; - } else { - throw new TypeError('Invalid argument'); - } - - if (!('radius' in val && val.center)) - throw new Error('center and radius are required'); - - var conds = this._conditions[path] || (this._conditions[path] = {}); - - var type = val.spherical - ? '$centerSphere' - : '$center'; - - var wKey = this._geoComparison || $withinCmd; - conds[wKey] = {}; - conds[wKey][type] = [val.center, val.radius]; - - if ('unique' in val) - conds[wKey].$uniqueDocs = !!val.unique; - - return this; -}; - -/** - * Specifies a `$near` or `$nearSphere` condition - * - * These operators return documents sorted by distance. - * - * ####Example - * - * query.where('loc').near({ center: [10, 10] }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); - * query.near('loc', { center: [10, 10], maxDistance: 5 }); - * query.near({ center: { type: 'Point', coordinates: [..] }}) - * query.near().geometry({ type: 'Point', coordinates: [..] }) - * - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -Query.prototype.near = function near() { - var path, val; - - this._geoComparison = '$near'; - - if (0 === arguments.length) { - return this; - } else if (1 === arguments.length) { - this._ensurePath('near'); - path = this._path; - val = arguments[0]; - } else if (2 === arguments.length) { - path = arguments[0]; - val = arguments[1]; - } else { - throw new TypeError('Invalid argument'); - } - - if (!val.center) { - throw new Error('center is required'); - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - - var type = val.spherical - ? '$nearSphere' - : '$near'; - - // center could be a GeoJSON object or an Array - if (Array.isArray(val.center)) { - conds[type] = val.center; - - var radius = 'maxDistance' in val - ? val.maxDistance - : null; - - if (null != radius) { - conds.$maxDistance = radius; - } - if (null != val.minDistance) { - conds.$minDistance = val.minDistance; - } - } else { - // GeoJSON? - if (val.center.type != 'Point' || !Array.isArray(val.center.coordinates)) { - throw new Error(util.format('Invalid GeoJSON specified for %s', type)); - } - conds[type] = { $geometry : val.center }; - - // MongoDB 2.6 insists on maxDistance being in $near / $nearSphere - if ('maxDistance' in val) { - conds[type]['$maxDistance'] = val.maxDistance; - } - if ('minDistance' in val) { - conds[type]['$minDistance'] = val.minDistance; - } - } - - return this; -}; - -/** - * Declares an intersects query for `geometry()`. - * - * ####Example - * - * query.where('path').intersects().geometry({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * query.where('path').intersects({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * @param {Object} [arg] - * @return {Query} this - * @api public - */ - -Query.prototype.intersects = function intersects() { - // opinionated, must be used after where - this._ensurePath('intersects'); - - this._geoComparison = '$geoIntersects'; - - if (0 === arguments.length) { - return this; - } - - var area = arguments[0]; - - if (null != area && area.type && area.coordinates) - return this.geometry(area); - - throw new TypeError('Invalid argument'); -}; - -/** - * Specifies a `$geometry` condition - * - * ####Example - * - * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] - * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) - * - * // or - * var polyB = [[ 0, 0 ], [ 1, 1 ]] - * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) - * - * // or - * var polyC = [ 0, 0 ] - * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) - * - * // or - * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) - * - * ####NOTE: - * - * `geometry()` **must** come after either `intersects()` or `within()`. - * - * The `object` argument must contain `type` and `coordinates` properties. - * - type {String} - * - coordinates {Array} - * - * The most recent path passed to `where()` is used. - * - * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. - * @return {Query} this - * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @api public - */ - -Query.prototype.geometry = function geometry() { - if (!('$within' == this._geoComparison || - '$geoWithin' == this._geoComparison || - '$near' == this._geoComparison || - '$geoIntersects' == this._geoComparison)) { - throw new Error('geometry() must come after `within()`, `intersects()`, or `near()'); - } - - var val, path; - - if (1 === arguments.length) { - this._ensurePath('geometry'); - path = this._path; - val = arguments[0]; - } else { - throw new TypeError('Invalid argument'); - } - - if (!(val.type && Array.isArray(val.coordinates))) { - throw new TypeError('Invalid argument'); - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds[this._geoComparison] = { $geometry: val }; - - return this; -}; - -// end spatial - -/** - * Specifies which document fields to include or exclude - * - * ####String syntax - * - * When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. - * - * ####Example - * - * // include a and b, exclude c - * query.select('a b -c'); - * - * // or you may use object notation, useful when - * // you have keys already prefixed with a "-" - * query.select({a: 1, b: 1, c: 0}); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|String} arg - * @return {Query} this - * @see SchemaType - * @api public - */ - -Query.prototype.select = function select() { - var arg = arguments[0]; - if (!arg) return this; - - if (arguments.length !== 1) { - throw new Error('Invalid select: select only takes 1 argument'); - } - - this._validate('select'); - - var fields = this._fields || (this._fields = {}); - var type = typeof arg; - var i, len; - - if (('string' == type || utils.isArgumentsObject(arg)) && - 'number' == typeof arg.length || Array.isArray(arg)) { - if ('string' == type) - arg = arg.split(/\s+/); - - for (i = 0, len = arg.length; i < len; ++i) { - var field = arg[i]; - if (!field) continue; - var include = '-' == field[0] ? 0 : 1; - if (include === 0) field = field.substring(1); - fields[field] = include; - } - - return this; - } - - if (utils.isObject(arg)) { - var keys = utils.keys(arg); - for (i = 0; i < keys.length; ++i) { - fields[keys[i]] = arg[keys[i]]; - } - return this; - } - - throw new TypeError('Invalid select() argument. Must be string or object.'); -}; - -/** - * Specifies a $slice condition for a `path` - * - * ####Example - * - * query.slice('comments', 5) - * query.slice('comments', -5) - * query.slice('comments', [10, 5]) - * query.where('comments').slice(5) - * query.where('comments').slice([-10, 5]) - * - * @param {String} [path] - * @param {Number} val number/range of elements to slice - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements - * @api public - */ - -Query.prototype.slice = function() { - if (0 === arguments.length) - return this; - - this._validate('slice'); - - var path, val; - - if (1 === arguments.length) { - var arg = arguments[0]; - if (typeof arg === 'object' && !Array.isArray(arg)) { - var keys = Object.keys(arg); - var numKeys = keys.length; - for (var i = 0; i < numKeys; ++i) { - this.slice(keys[i], arg[keys[i]]); - } - return this; - } - this._ensurePath('slice'); - path = this._path; - val = arguments[0]; - } else if (2 === arguments.length) { - if ('number' === typeof arguments[0]) { - this._ensurePath('slice'); - path = this._path; - val = slice(arguments); - } else { - path = arguments[0]; - val = arguments[1]; - } - } else if (3 === arguments.length) { - path = arguments[0]; - val = slice(arguments, 1); - } - - var myFields = this._fields || (this._fields = {}); - myFields[path] = { '$slice': val }; - return this; -}; - -/** - * Sets the sort order - * - * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1. - * - * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. - * - * ####Example - * - * // these are equivalent - * query.sort({ field: 'asc', test: -1 }); - * query.sort('field -test'); - * query.sort([['field', 1], ['test', -1]]); - * - * ####Note - * - * - The array syntax `.sort([['field', 1], ['test', -1]])` can only be used with [mongodb driver >= 2.0.46](https://github.com/mongodb/node-mongodb-native/blob/2.1/HISTORY.md#2046-2015-10-15). - * - Cannot be used with `distinct()` - * - * @param {Object|String|Array} arg - * @return {Query} this - * @api public - */ - -Query.prototype.sort = function(arg) { - if (!arg) return this; - var i, len, field; - - this._validate('sort'); - - var type = typeof arg; - - // .sort([['field', 1], ['test', -1]]) - if (Array.isArray(arg)) { - len = arg.length; - for (i = 0; i < arg.length; ++i) { - if (!Array.isArray(arg[i])) { - throw new Error('Invalid sort() argument, must be array of arrays'); - } - _pushArr(this.options, arg[i][0], arg[i][1]); - } - return this; - } - - // .sort('field -test') - if (1 === arguments.length && 'string' == type) { - arg = arg.split(/\s+/); - len = arg.length; - for (i = 0; i < len; ++i) { - field = arg[i]; - if (!field) continue; - var ascend = '-' == field[0] ? -1 : 1; - if (ascend === -1) field = field.substring(1); - push(this.options, field, ascend); - } - - return this; - } - - // .sort({ field: 1, test: -1 }) - if (utils.isObject(arg)) { - var keys = utils.keys(arg); - for (i = 0; i < keys.length; ++i) { - field = keys[i]; - push(this.options, field, arg[field]); - } - - return this; - } - - if (typeof Map !== 'undefined' && arg instanceof Map) { - _pushMap(this.options, arg); - return this; - } - throw new TypeError('Invalid sort() argument. Must be a string, object, or array.'); -}; - -/*! - * @ignore - */ - -var _validSortValue = { - '1': 1, - '-1': -1, - 'asc': 1, - 'ascending': 1, - 'desc': -1, - 'descending': -1 -}; - -function push(opts, field, value) { - if (Array.isArray(opts.sort)) { - throw new TypeError('Can\'t mix sort syntaxes. Use either array or object:' + - '\n- `.sort([[\'field\', 1], [\'test\', -1]])`' + - '\n- `.sort({ field: 1, test: -1 })`'); - } - - var s; - if (value && value.$meta) { - s = opts.sort || (opts.sort = {}); - s[field] = { $meta : value.$meta }; - return; - } - - s = opts.sort || (opts.sort = {}); - var val = String(value || 1).toLowerCase(); - val = _validSortValue[val]; - if (!val) throw new TypeError('Invalid sort value: { ' + field + ': ' + value + ' }'); - - s[field] = val; -} - -function _pushArr(opts, field, value) { - opts.sort = opts.sort || []; - if (!Array.isArray(opts.sort)) { - throw new TypeError('Can\'t mix sort syntaxes. Use either array or object:' + - '\n- `.sort([[\'field\', 1], [\'test\', -1]])`' + - '\n- `.sort({ field: 1, test: -1 })`'); - } - - var val = String(value || 1).toLowerCase(); - val = _validSortValue[val]; - if (!val) throw new TypeError('Invalid sort value: [ ' + field + ', ' + value + ' ]'); - - opts.sort.push([field, val]); -} - -function _pushMap(opts, map) { - opts.sort = opts.sort || new Map(); - if (!(opts.sort instanceof Map)) { - throw new TypeError('Can\'t mix sort syntaxes. Use either array or ' + - 'object or map consistently'); - } - map.forEach(function(value, key) { - var val = String(value || 1).toLowerCase(); - val = _validSortValue[val]; - if (!val) throw new TypeError('Invalid sort value: < ' + key + ': ' + value + ' >'); - - opts.sort.set(key, val); - }); -} - - - -/** - * Specifies the limit option. - * - * ####Example - * - * query.limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method limit - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D - * @api public - */ -/** - * Specifies the skip option. - * - * ####Example - * - * query.skip(100).limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method skip - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D - * @api public - */ -/** - * Specifies the maxScan option. - * - * ####Example - * - * query.maxScan(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method maxScan - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan - * @api public - */ -/** - * Specifies the batchSize option. - * - * ####Example - * - * query.batchSize(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method batchSize - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D - * @api public - */ -/** - * Specifies the `comment` option. - * - * ####Example - * - * query.comment('login query') - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method comment - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment - * @api public - */ - -/*! - * limit, skip, maxScan, batchSize, comment - * - * Sets these associated options. - * - * query.comment('feed query'); - */ - -['limit', 'skip', 'maxScan', 'batchSize', 'comment'].forEach(function(method) { - Query.prototype[method] = function(v) { - this._validate(method); - this.options[method] = v; - return this; - }; -}); - -/** - * Specifies the maxTimeMS option. - * - * ####Example - * - * query.maxTime(100) - * query.maxTimeMS(100) - * - * @method maxTime - * @memberOf Query - * @param {Number} ms - * @see mongodb http://docs.mongodb.org/manual/reference/operator/meta/maxTimeMS/#op._S_maxTimeMS - * @api public - */ - -Query.prototype.maxTime = Query.prototype.maxTimeMS = function(ms) { - this._validate('maxTime'); - this.options.maxTimeMS = ms; - return this; -}; - -/** - * Specifies this query as a `snapshot` query. - * - * ####Example - * - * mquery().snapshot() // true - * mquery().snapshot(true) - * mquery().snapshot(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D - * @return {Query} this - * @api public - */ - -Query.prototype.snapshot = function() { - this._validate('snapshot'); - - this.options.snapshot = arguments.length - ? !!arguments[0] - : true; - - return this; -}; - -/** - * Sets query hints. - * - * ####Example - * - * query.hint({ indexA: 1, indexB: -1}); - * query.hint('indexA_1_indexB_1'); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|string} val a hint object or the index name - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint - * @api public - */ - -Query.prototype.hint = function() { - if (0 === arguments.length) return this; - - this._validate('hint'); - - var arg = arguments[0]; - if (utils.isObject(arg)) { - var hint = this.options.hint || (this.options.hint = {}); - - // must keep object keys in order so don't use Object.keys() - for (var k in arg) { - hint[k] = arg[k]; - } - - return this; - } - if (typeof arg === 'string') { - this.options.hint = arg; - return this; - } - - throw new TypeError('Invalid hint. ' + arg); -}; - -/** - * Requests acknowledgement that this operation has been persisted to MongoDB's - * on-disk journal. - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the `j` value if it is specified in writeConcern options - * - * ####Example: - * - * mquery().w(2).j(true).wtimeout(2000); - * - * @method j - * @memberOf Query - * @instance - * @param {boolean} val - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#j-option - * @return {Query} this - * @api public - */ - -Query.prototype.j = function j(val) { - this.options.j = val; - return this; -}; - -/** - * Sets the slaveOk option. _Deprecated_ in MongoDB 2.2 in favor of read preferences. - * - * ####Example: - * - * query.slaveOk() // true - * query.slaveOk(true) - * query.slaveOk(false) - * - * @deprecated use read() preferences instead if on mongodb >= 2.2 - * @param {Boolean} v defaults to true - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see read() - * @return {Query} this - * @api public - */ - -Query.prototype.slaveOk = function(v) { - this.options.slaveOk = arguments.length ? !!v : true; - return this; -}; - -/** - * Sets the readPreference option for the query. - * - * ####Example: - * - * new Query().read('primary') - * new Query().read('p') // same as primary - * - * new Query().read('primaryPreferred') - * new Query().read('pp') // same as primaryPreferred - * - * new Query().read('secondary') - * new Query().read('s') // same as secondary - * - * new Query().read('secondaryPreferred') - * new Query().read('sp') // same as secondaryPreferred - * - * new Query().read('nearest') - * new Query().read('n') // same as nearest - * - * // you can also use mongodb.ReadPreference class to also specify tags - * new Query().read(mongodb.ReadPreference('secondary', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])) - * - * new Query().setReadPreference('primary') // alias of .read() - * - * ####Preferences: - * - * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. - * secondary Read from secondary if available, otherwise error. - * primaryPreferred Read from primary if available, otherwise a secondary. - * secondaryPreferred Read from a secondary if available, otherwise read from the primary. - * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. - * - * Aliases - * - * p primary - * pp primaryPreferred - * s secondary - * sp secondaryPreferred - * n nearest - * - * Read more about how to use read preferences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). - * - * @param {String|ReadPreference} pref one of the listed preference options or their aliases - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences - * @return {Query} this - * @api public - */ - -Query.prototype.read = Query.prototype.setReadPreference = function(pref) { - if (arguments.length > 1 && !Query.prototype.read.deprecationWarningIssued) { - console.error('Deprecation warning: \'tags\' argument is not supported anymore in Query.read() method. Please use mongodb.ReadPreference object instead.'); - Query.prototype.read.deprecationWarningIssued = true; - } - this.options.readPreference = utils.readPref(pref); - return this; -}; - -/** - * Sets the readConcern option for the query. - * - * ####Example: - * - * new Query().readConcern('local') - * new Query().readConcern('l') // same as local - * - * new Query().readConcern('available') - * new Query().readConcern('a') // same as available - * - * new Query().readConcern('majority') - * new Query().readConcern('m') // same as majority - * - * new Query().readConcern('linearizable') - * new Query().readConcern('lz') // same as linearizable - * - * new Query().readConcern('snapshot') - * new Query().readConcern('s') // same as snapshot - * - * new Query().r('s') // r is alias of readConcern - * - * - * ####Read Concern Level: - * - * local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). - * available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back). - * majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure. - * linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results. - * snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data. - - - * - * - * Aliases - * - * l local - * a available - * m majority - * lz linearizable - * s snapshot - * - * Read more about how to use read concern [here](https://docs.mongodb.com/manual/reference/read-concern/). - * - * @param {String} level one of the listed read concern level or their aliases - * @see mongodb https://docs.mongodb.com/manual/reference/read-concern/ - * @return {Query} this - * @api public - */ - -Query.prototype.readConcern = Query.prototype.r = function(level) { - this.options.readConcern = utils.readConcern(level); - return this; -}; - -/** - * Sets tailable option. - * - * ####Example - * - * query.tailable() <== true - * query.tailable(true) - * query.tailable(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Boolean} v defaults to true - * @see mongodb http://www.mongodb.org/display/DOCS/Tailable+Cursors - * @api public - */ - -Query.prototype.tailable = function() { - this._validate('tailable'); - - this.options.tailable = arguments.length - ? !!arguments[0] - : true; - - return this; -}; - -/** - * Sets the specified number of `mongod` servers, or tag set of `mongod` servers, - * that must acknowledge this write before this write is considered successful. - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to the `w` value if it is specified in writeConcern options - * - * ####Example: - * - * mquery().writeConcern(0) - * mquery().writeConcern(1) - * mquery().writeConcern({ w: 1, j: true, wtimeout: 2000 }) - * mquery().writeConcern('majority') - * mquery().writeConcern('m') // same as majority - * mquery().writeConcern('tagSetName') // if the tag set is 'm', use .writeConcern({ w: 'm' }) instead - * mquery().w(1) // w is alias of writeConcern - * - * @method writeConcern - * @memberOf Query - * @instance - * @param {String|number|object} concern 0 for fire-and-forget, 1 for acknowledged by one server, 'majority' for majority of the replica set, or [any of the more advanced options](https://docs.mongodb.com/manual/reference/write-concern/#w-option). - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#w-option - * @return {Query} this - * @api public - */ - -Query.prototype.writeConcern = Query.prototype.w = function writeConcern(concern) { - if ('object' === typeof concern) { - if ('undefined' !== typeof concern.j) this.options.j = concern.j; - if ('undefined' !== typeof concern.w) this.options.w = concern.w; - if ('undefined' !== typeof concern.wtimeout) this.options.wtimeout = concern.wtimeout; - } else { - this.options.w = 'm' === concern ? 'majority' : concern; - } - return this; -}; - -/** - * Specifies a time limit, in milliseconds, for the write concern. - * If `ms > 1`, it is maximum amount of time to wait for this write - * to propagate through the replica set before this operation fails. - * The default is `0`, which means no timeout. - * - * This option is only valid for operations that write to the database: - * - * - `deleteOne()` - * - `deleteMany()` - * - `findOneAndDelete()` - * - `findOneAndUpdate()` - * - `remove()` - * - `update()` - * - `updateOne()` - * - `updateMany()` - * - * Defaults to `wtimeout` value if it is specified in writeConcern - * - * ####Example: - * - * mquery().w(2).j(true).wtimeout(2000) - * - * @method wtimeout - * @memberOf Query - * @instance - * @param {number} ms number of milliseconds to wait - * @see mongodb https://docs.mongodb.com/manual/reference/write-concern/#wtimeout - * @return {Query} this - * @api public - */ - -Query.prototype.wtimeout = Query.prototype.wTimeout = function wtimeout(ms) { - this.options.wtimeout = ms; - return this; -}; - -/** - * Merges another Query or conditions object into this one. - * - * When a Query is passed, conditions, field selection and options are merged. - * - * @param {Query|Object} source - * @return {Query} this - */ - -Query.prototype.merge = function(source) { - if (!source) - return this; - - if (!Query.canMerge(source)) - throw new TypeError('Invalid argument. Expected instanceof mquery or plain object'); - - if (source instanceof Query) { - // if source has a feature, apply it to ourselves - - if (source._conditions) { - utils.merge(this._conditions, source._conditions); - } - - if (source._fields) { - this._fields || (this._fields = {}); - utils.merge(this._fields, source._fields); - } - - if (source.options) { - this.options || (this.options = {}); - utils.merge(this.options, source.options); - } - - if (source._update) { - this._update || (this._update = {}); - utils.mergeClone(this._update, source._update); - } - - if (source._distinct) { - this._distinct = source._distinct; - } - - return this; - } - - // plain object - utils.merge(this._conditions, source); - - return this; -}; - -/** - * Finds documents. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * query.find() - * query.find(callback) - * query.find({ name: 'Burning Lights' }, callback) - * - * @param {Object} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.find = function(criteria, callback) { - this.op = 'find'; - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (!callback) return this; - - var conds = this._conditions; - var options = this._optionsForExec(); - - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - options.fields = this._fieldsForExec(); - } - - debug('find', this._collection.collectionName, conds, options); - callback = this._wrapCallback('find', callback, { - conditions: conds, - options: options - }); - - this._collection.find(conds, options, utils.tick(callback)); - return this; -}; - -/** - * Returns the query cursor - * - * ####Examples - * - * query.find().cursor(); - * query.cursor({ name: 'Burning Lights' }); - * - * @param {Object} [criteria] mongodb selector - * @return {Object} cursor - * @api public - */ - -Query.prototype.cursor = function cursor(criteria) { - if (this.op) { - if (this.op !== 'find') { - throw new TypeError('.cursor only support .find method'); - } - } else { - this.find(criteria); - } - - var conds = this._conditions; - var options = this._optionsForExec(); - - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - options.fields = this._fieldsForExec(); - } - - debug('findCursor', this._collection.collectionName, conds, options); - return this._collection.findCursor(conds, options); -}; - -/** - * Executes the query as a findOne() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * query.findOne().where('name', /^Burning/); - * - * query.findOne({ name: /^Burning/ }) - * - * query.findOne({ name: /^Burning/ }, callback); // executes - * - * query.findOne(function (err, doc) { - * if (err) return handleError(err); - * if (doc) { - * // doc may be null if no document matched - * - * } - * }); - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.findOne = function(criteria, callback) { - this.op = 'findOne'; - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (!callback) return this; - - var conds = this._conditions; - var options = this._optionsForExec(); - - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - options.fields = this._fieldsForExec(); - } - - debug('findOne', this._collection.collectionName, conds, options); - callback = this._wrapCallback('findOne', callback, { - conditions: conds, - options: options - }); - - this._collection.findOne(conds, options, utils.tick(callback)); - - return this; -}; - -/** - * Exectues the query as a count() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * query.count().where('color', 'black').exec(callback); - * - * query.count({ color: 'black' }).count(callback) - * - * query.count({ color: 'black' }, callback) - * - * query.where('color', 'black').count(function (err, count) { - * if (err) return handleError(err); - * console.log('there are %d kittens', count); - * }) - * - * @param {Object} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Count - * @api public - */ - -Query.prototype.count = function(criteria, callback) { - this.op = 'count'; - this._validate(); - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (!callback) return this; - - var conds = this._conditions, - options = this._optionsForExec(); - - debug('count', this._collection.collectionName, conds, options); - callback = this._wrapCallback('count', callback, { - conditions: conds, - options: options - }); - - this._collection.count(conds, options, utils.tick(callback)); - return this; -}; - -/** - * Declares or executes a distinct() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * distinct(criteria, field, fn) - * distinct(criteria, field) - * distinct(field, fn) - * distinct(field) - * distinct(fn) - * distinct() - * - * @param {Object|Query} [criteria] - * @param {String} [field] - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct - * @api public - */ - -Query.prototype.distinct = function(criteria, field, callback) { - this.op = 'distinct'; - this._validate(); - - if (!callback) { - switch (typeof field) { - case 'function': - callback = field; - if ('string' == typeof criteria) { - field = criteria; - criteria = undefined; - } - break; - case 'undefined': - case 'string': - break; - default: - throw new TypeError('Invalid `field` argument. Must be string or function'); - } - - switch (typeof criteria) { - case 'function': - callback = criteria; - criteria = field = undefined; - break; - case 'string': - field = criteria; - criteria = undefined; - break; - } - } - - if ('string' == typeof field) { - this._distinct = field; - } - - if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (!callback) { - return this; - } - - if (!this._distinct) { - throw new Error('No value for `distinct` has been declared'); - } - - var conds = this._conditions, - options = this._optionsForExec(); - - debug('distinct', this._collection.collectionName, conds, options); - callback = this._wrapCallback('distinct', callback, { - conditions: conds, - options: options - }); - - this._collection.distinct(this._distinct, conds, options, utils.tick(callback)); - - return this; -}; - -/** - * Declare and/or execute this query as an update() operation. By default, - * `update()` only modifies the _first_ document that matches `criteria`. - * - * _All paths passed that are not $atomic operations will become $set ops._ - * - * ####Example - * - * mquery({ _id: id }).update({ title: 'words' }, ...) - * - * becomes - * - * collection.update({ _id: id }, { $set: { title: 'words' }}, ...) - * - * ####Note - * - * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. - * - * var q = mquery(collection).where({ _id: id }); - * q.update({ $set: { name: 'bob' }}).update(); // not executed - * - * var q = mquery(collection).where({ _id: id }); - * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe - * - * // keys that are not $atomic ops become $set. - * // this executes the same command as the previous example. - * q.update({ name: 'bob' }).where({ _id: id }).exec(); - * - * var q = mquery(collection).update(); // not executed - * - * // overwriting with empty docs - * var q.where({ _id: id }).setOptions({ overwrite: true }) - * q.update({ }, callback); // executes - * - * // multi update with overwrite to empty doc - * var q = mquery(collection).where({ _id: id }); - * q.setOptions({ multi: true, overwrite: true }) - * q.update({ }); - * q.update(callback); // executed - * - * // multi updates - * mquery() - * .collection(coll) - * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) - * // more multi updates - * mquery({ }) - * .collection(coll) - * .setOptions({ multi: true }) - * .update({ $set: { arr: [] }}, callback) - * - * // single update by default - * mquery({ email: 'address@example.com' }) - * .collection(coll) - * .update({ $inc: { counter: 1 }}, callback) - * - * // summary - * update(criteria, doc, opts, cb) // executes - * update(criteria, doc, opts) - * update(criteria, doc, cb) // executes - * update(criteria, doc) - * update(doc, cb) // executes - * update(doc) - * update(cb) // executes - * update(true) // executes (unsafe write) - * update() - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.update = function update(criteria, doc, options, callback) { - var force; - - switch (arguments.length) { - case 3: - if ('function' == typeof options) { - callback = options; - options = undefined; - } - break; - case 2: - if ('function' == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - break; - case 1: - switch (typeof criteria) { - case 'function': - callback = criteria; - criteria = options = doc = undefined; - break; - case 'boolean': - // execution with no callback (unsafe write) - force = criteria; - criteria = undefined; - break; - default: - doc = criteria; - criteria = options = undefined; - break; - } - } - - return _update(this, 'update', criteria, doc, options, force, callback); -}; - -/** - * Declare and/or execute this query as an `updateMany()` operation. Identical - * to `update()` except `updateMany()` will update _all_ documents that match - * `criteria`, rather than just the first one. - * - * _All paths passed that are not $atomic operations will become $set ops._ - * - * ####Example - * - * // Update every document whose `title` contains 'test' - * mquery().updateMany({ title: /test/ }, { year: 2017 }) - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.updateMany = function updateMany(criteria, doc, options, callback) { - var force; - - switch (arguments.length) { - case 3: - if ('function' == typeof options) { - callback = options; - options = undefined; - } - break; - case 2: - if ('function' == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - break; - case 1: - switch (typeof criteria) { - case 'function': - callback = criteria; - criteria = options = doc = undefined; - break; - case 'boolean': - // execution with no callback (unsafe write) - force = criteria; - criteria = undefined; - break; - default: - doc = criteria; - criteria = options = undefined; - break; - } - } - - return _update(this, 'updateMany', criteria, doc, options, force, callback); -}; - -/** - * Declare and/or execute this query as an `updateOne()` operation. Identical - * to `update()` except `updateOne()` will _always_ update just one document, - * regardless of the `multi` option. - * - * _All paths passed that are not $atomic operations will become $set ops._ - * - * ####Example - * - * // Update the first document whose `title` contains 'test' - * mquery().updateMany({ title: /test/ }, { year: 2017 }) - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.updateOne = function updateOne(criteria, doc, options, callback) { - var force; - - switch (arguments.length) { - case 3: - if ('function' == typeof options) { - callback = options; - options = undefined; - } - break; - case 2: - if ('function' == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - break; - case 1: - switch (typeof criteria) { - case 'function': - callback = criteria; - criteria = options = doc = undefined; - break; - case 'boolean': - // execution with no callback (unsafe write) - force = criteria; - criteria = undefined; - break; - default: - doc = criteria; - criteria = options = undefined; - break; - } - } - - return _update(this, 'updateOne', criteria, doc, options, force, callback); -}; - -/** - * Declare and/or execute this query as an `replaceOne()` operation. Similar - * to `updateOne()`, except `replaceOne()` is not allowed to use atomic - * modifiers (`$set`, `$push`, etc.). Calling `replaceOne()` will always - * replace the existing doc. - * - * ####Example - * - * // Replace the document with `_id` 1 with `{ _id: 1, year: 2017 }` - * mquery().replaceOne({ _id: 1 }, { year: 2017 }) - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.replaceOne = function replaceOne(criteria, doc, options, callback) { - var force; - - switch (arguments.length) { - case 3: - if ('function' == typeof options) { - callback = options; - options = undefined; - } - break; - case 2: - if ('function' == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - break; - case 1: - switch (typeof criteria) { - case 'function': - callback = criteria; - criteria = options = doc = undefined; - break; - case 'boolean': - // execution with no callback (unsafe write) - force = criteria; - criteria = undefined; - break; - default: - doc = criteria; - criteria = options = undefined; - break; - } - } - - this.setOptions({ overwrite: true }); - return _update(this, 'replaceOne', criteria, doc, options, force, callback); -}; - - -/*! - * Internal helper for update, updateMany, updateOne - */ - -function _update(query, op, criteria, doc, options, force, callback) { - query.op = op; - - if (Query.canMerge(criteria)) { - query.merge(criteria); - } - - if (doc) { - query._mergeUpdate(doc); - } - - if (utils.isObject(options)) { - // { overwrite: true } - query.setOptions(options); - } - - // we are done if we don't have callback and they are - // not forcing an unsafe write. - if (!(force || callback)) { - return query; - } - - if (!query._update || - !query.options.overwrite && 0 === utils.keys(query._update).length) { - callback && utils.soon(callback.bind(null, null, 0)); - return query; - } - - options = query._optionsForExec(); - if (!callback) options.safe = false; - - criteria = query._conditions; - doc = query._updateForExec(); - - debug('update', query._collection.collectionName, criteria, doc, options); - callback = query._wrapCallback(op, callback, { - conditions: criteria, - doc: doc, - options: options - }); - - query._collection[op](criteria, doc, options, utils.tick(callback)); - - return query; -} - -/** - * Declare and/or execute this query as a remove() operation. - * - * ####Example - * - * mquery(collection).remove({ artist: 'Anne Murray' }, callback) - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method. - * - * // not executed - * var query = mquery(collection).remove({ name: 'Anne Murray' }) - * - * // executed - * mquery(collection).remove({ name: 'Anne Murray' }, callback) - * mquery(collection).remove({ name: 'Anne Murray' }).remove(callback) - * - * // executed without a callback (unsafe write) - * query.exec() - * - * // summary - * query.remove(conds, fn); // executes - * query.remove(conds) - * query.remove(fn) // executes - * query.remove() - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.remove = function(criteria, callback) { - this.op = 'remove'; - var force; - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } else if (true === criteria) { - force = criteria; - criteria = undefined; - } - - if (!(force || callback)) - return this; - - var options = this._optionsForExec(); - if (!callback) options.safe = false; - - var conds = this._conditions; - - debug('remove', this._collection.collectionName, conds, options); - callback = this._wrapCallback('remove', callback, { - conditions: conds, - options: options - }); - - this._collection.remove(conds, options, utils.tick(callback)); - - return this; -}; - -/** - * Declare and/or execute this query as a `deleteOne()` operation. Behaves like - * `remove()`, except for ignores the `justOne` option and always deletes at - * most one document. - * - * ####Example - * - * mquery(collection).deleteOne({ artist: 'Anne Murray' }, callback) - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.deleteOne = function(criteria, callback) { - this.op = 'deleteOne'; - var force; - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } else if (true === criteria) { - force = criteria; - criteria = undefined; - } - - if (!(force || callback)) - return this; - - var options = this._optionsForExec(); - if (!callback) options.safe = false; - delete options.justOne; - - var conds = this._conditions; - - debug('deleteOne', this._collection.collectionName, conds, options); - callback = this._wrapCallback('deleteOne', callback, { - conditions: conds, - options: options - }); - - this._collection.deleteOne(conds, options, utils.tick(callback)); - - return this; -}; - -/** - * Declare and/or execute this query as a `deleteMany()` operation. Behaves like - * `remove()`, except for ignores the `justOne` option and always deletes - * _every_ document that matches `criteria`. - * - * ####Example - * - * mquery(collection).deleteMany({ artist: 'Anne Murray' }, callback) - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.deleteMany = function(criteria, callback) { - this.op = 'deleteMany'; - var force; - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } else if (true === criteria) { - force = criteria; - criteria = undefined; - } - - if (!(force || callback)) - return this; - - var options = this._optionsForExec(); - if (!callback) options.safe = false; - delete options.justOne; - - var conds = this._conditions; - - debug('deleteOne', this._collection.collectionName, conds, options); - callback = this._wrapCallback('deleteOne', callback, { - conditions: conds, - options: options - }); - - this._collection.deleteMany(conds, options, utils.tick(callback)); - - return this; -}; - -/** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. - * - * ####Available options - * - * - `new`: bool - true to return the modified document rather than the original. defaults to true - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Examples - * - * query.findOneAndUpdate(conditions, update, options, callback) // executes - * query.findOneAndUpdate(conditions, update, options) // returns Query - * query.findOneAndUpdate(conditions, update, callback) // executes - * query.findOneAndUpdate(conditions, update) // returns Query - * query.findOneAndUpdate(update, callback) // returns Query - * query.findOneAndUpdate(update) // returns Query - * query.findOneAndUpdate(callback) // executes - * query.findOneAndUpdate() // returns Query - * - * @param {Object|Query} [query] - * @param {Object} [doc] - * @param {Object} [options] - * @param {Function} [callback] - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @return {Query} this - * @api public - */ - -Query.prototype.findOneAndUpdate = function(criteria, doc, options, callback) { - this.op = 'findOneAndUpdate'; - this._validate(); - - switch (arguments.length) { - case 3: - if ('function' == typeof options) { - callback = options; - options = {}; - } - break; - case 2: - if ('function' == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - options = undefined; - break; - case 1: - if ('function' == typeof criteria) { - callback = criteria; - criteria = options = doc = undefined; - } else { - doc = criteria; - criteria = options = undefined; - } - } - - if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - // apply doc - if (doc) { - this._mergeUpdate(doc); - } - - options && this.setOptions(options); - - if (!callback) return this; - return this._findAndModify('update', callback); -}; - -/** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Examples - * - * A.where().findOneAndRemove(conditions, options, callback) // executes - * A.where().findOneAndRemove(conditions, options) // return Query - * A.where().findOneAndRemove(conditions, callback) // executes - * A.where().findOneAndRemove(conditions) // returns Query - * A.where().findOneAndRemove(callback) // executes - * A.where().findOneAndRemove() // returns Query - * A.where().findOneAndDelete() // alias of .findOneAndRemove() - * - * @param {Object} [conditions] - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Query.prototype.findOneAndRemove = Query.prototype.findOneAndDelete = function(conditions, options, callback) { - this.op = 'findOneAndRemove'; - this._validate(); - - if ('function' == typeof options) { - callback = options; - options = undefined; - } else if ('function' == typeof conditions) { - callback = conditions; - conditions = undefined; - } - - // apply conditions - if (Query.canMerge(conditions)) { - this.merge(conditions); - } - - // apply options - options && this.setOptions(options); - - if (!callback) return this; - - return this._findAndModify('remove', callback); -}; - -/** - * _findAndModify - * - * @param {String} type - either "remove" or "update" - * @param {Function} callback - * @api private - */ - -Query.prototype._findAndModify = function(type, callback) { - assert.equal('function', typeof callback); - - var options = this._optionsForExec(); - var fields; - var doc; - - if ('remove' == type) { - options.remove = true; - } else { - if (!('new' in options)) options.new = true; - if (!('upsert' in options)) options.upsert = false; - - doc = this._updateForExec(); - if (!doc) { - if (options.upsert) { - // still need to do the upsert to empty doc - doc = { $set: {} }; - } else { - return this.findOne(callback); - } - } - } - - fields = this._fieldsForExec(); - if (fields != null) { - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - options.fields = this._fieldsForExec(); - } - } - - var conds = this._conditions; - - debug('findAndModify', this._collection.collectionName, conds, doc, options); - callback = this._wrapCallback('findAndModify', callback, { - conditions: conds, - doc: doc, - options: options - }); - - this._collection.findAndModify(conds, doc, options, utils.tick(callback)); - - return this; -}; - -/** - * Wrap callback to add tracing - * - * @param {Function} callback - * @param {Object} [queryInfo] - * @api private - */ -Query.prototype._wrapCallback = function(method, callback, queryInfo) { - var traceFunction = this._traceFunction || Query.traceFunction; - - if (traceFunction) { - queryInfo.collectionName = this._collection.collectionName; - - var traceCallback = traceFunction && - traceFunction.call(null, method, queryInfo, this); - - var startTime = new Date().getTime(); - - return function wrapperCallback(err, result) { - if (traceCallback) { - var millis = new Date().getTime() - startTime; - traceCallback.call(null, err, result, millis); - } - - if (callback) { - callback.apply(null, arguments); - } - }; - } - - return callback; -}; - -/** - * Add trace function that gets called when the query is executed. - * The function will be called with (method, queryInfo, query) and - * should return a callback function which will be called - * with (err, result, millis) when the query is complete. - * - * queryInfo is an object containing: { - * collectionName: , - * conditions: , - * options: , - * doc: [document to update, if applicable] - * } - * - * NOTE: Does not trace stream queries. - * - * @param {Function} traceFunction - * @return {Query} this - * @api public - */ -Query.prototype.setTraceFunction = function(traceFunction) { - this._traceFunction = traceFunction; - return this; -}; - -/** - * Executes the query - * - * ####Examples - * - * query.exec(); - * query.exec(callback); - * query.exec('update'); - * query.exec('find', callback); - * - * @param {String|Function} [operation] - * @param {Function} [callback] - * @api public - */ - -Query.prototype.exec = function exec(op, callback) { - switch (typeof op) { - case 'function': - callback = op; - op = null; - break; - case 'string': - this.op = op; - break; - } - - assert.ok(this.op, 'Missing query type: (find, update, etc)'); - - if ('update' == this.op || 'remove' == this.op) { - callback || (callback = true); - } - - var _this = this; - - if ('function' == typeof callback) { - this[this.op](callback); - } else { - return new Query.Promise(function(success, error) { - _this[_this.op](function(err, val) { - if (err) error(err); - else success(val); - success = error = null; - }); - }); - } -}; - -/** - * Returns a thunk which when called runs this.exec() - * - * The thunk receives a callback function which will be - * passed to `this.exec()` - * - * @return {Function} - * @api public - */ - -Query.prototype.thunk = function() { - var _this = this; - return function(cb) { - _this.exec(cb); - }; -}; - -/** - * Executes the query returning a `Promise` which will be - * resolved with either the doc(s) or rejected with the error. - * - * @param {Function} [resolve] - * @param {Function} [reject] - * @return {Promise} - * @api public - */ - -Query.prototype.then = function(resolve, reject) { - var _this = this; - var promise = new Query.Promise(function(success, error) { - _this.exec(function(err, val) { - if (err) error(err); - else success(val); - success = error = null; - }); - }); - return promise.then(resolve, reject); -}; - -/** - * Returns a stream for the given find query. - * - * @throws Error if operation is not a find - * @returns {Stream} Node 0.8 style - */ - -Query.prototype.stream = function(streamOptions) { - if ('find' != this.op) - throw new Error('stream() is only available for find'); - - var conds = this._conditions; - - var options = this._optionsForExec(); - if (this.$useProjection) { - options.projection = this._fieldsForExec(); - } else { - options.fields = this._fieldsForExec(); - } - - debug('stream', this._collection.collectionName, conds, options, streamOptions); - - return this._collection.findStream(conds, options, streamOptions); -}; - -/** - * Determines if field selection has been made. - * - * @return {Boolean} - * @api public - */ - -Query.prototype.selected = function selected() { - return !!(this._fields && Object.keys(this._fields).length > 0); -}; - -/** - * Determines if inclusive field selection has been made. - * - * query.selectedInclusively() // false - * query.select('name') - * query.selectedInclusively() // true - * query.selectedExlusively() // false - * - * @returns {Boolean} - */ - -Query.prototype.selectedInclusively = function selectedInclusively() { - if (!this._fields) return false; - - var keys = Object.keys(this._fields); - if (0 === keys.length) return false; - - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (0 === this._fields[key]) return false; - if (this._fields[key] && - typeof this._fields[key] === 'object' && - this._fields[key].$meta) { - return false; - } - } - - return true; -}; - -/** - * Determines if exclusive field selection has been made. - * - * query.selectedExlusively() // false - * query.select('-name') - * query.selectedExlusively() // true - * query.selectedInclusively() // false - * - * @returns {Boolean} - */ - -Query.prototype.selectedExclusively = function selectedExclusively() { - if (!this._fields) return false; - - var keys = Object.keys(this._fields); - if (0 === keys.length) return false; - - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (0 === this._fields[key]) return true; - } - - return false; -}; - -/** - * Merges `doc` with the current update object. - * - * @param {Object} doc - */ - -Query.prototype._mergeUpdate = function(doc) { - if (!this._update) this._update = {}; - if (doc instanceof Query) { - if (doc._update) { - utils.mergeClone(this._update, doc._update); - } - } else { - utils.mergeClone(this._update, doc); - } -}; - -/** - * Returns default options. - * - * @return {Object} - * @api private - */ - -Query.prototype._optionsForExec = function() { - var options = utils.clone(this.options); - return options; -}; - -/** - * Returns fields selection for this query. - * - * @return {Object} - * @api private - */ - -Query.prototype._fieldsForExec = function() { - return utils.clone(this._fields); -}; - -/** - * Return an update document with corrected $set operations. - * - * @api private - */ - -Query.prototype._updateForExec = function() { - var update = utils.clone(this._update), - ops = utils.keys(update), - i = ops.length, - ret = {}; - - while (i--) { - var op = ops[i]; - - if (this.options.overwrite) { - ret[op] = update[op]; - continue; - } - - if ('$' !== op[0]) { - // fix up $set sugar - if (!ret.$set) { - if (update.$set) { - ret.$set = update.$set; - } else { - ret.$set = {}; - } - } - ret.$set[op] = update[op]; - ops.splice(i, 1); - if (!~ops.indexOf('$set')) ops.push('$set'); - } else if ('$set' === op) { - if (!ret.$set) { - ret[op] = update[op]; - } - } else { - ret[op] = update[op]; - } - } - - this._compiledUpdate = ret; - return ret; -}; - -/** - * Make sure _path is set. - * - * @parmam {String} method - */ - -Query.prototype._ensurePath = function(method) { - if (!this._path) { - var msg = method + '() must be used after where() ' - + 'when called with these arguments'; - throw new Error(msg); - } -}; - -/*! - * Permissions - */ - -Query.permissions = require('./permissions'); - -Query._isPermitted = function(a, b) { - var denied = Query.permissions[b]; - if (!denied) return true; - return true !== denied[a]; -}; - -Query.prototype._validate = function(action) { - var fail; - var validator; - - if (undefined === action) { - - validator = Query.permissions[this.op]; - if ('function' != typeof validator) return true; - - fail = validator(this); - - } else if (!Query._isPermitted(action, this.op)) { - fail = action; - } - - if (fail) { - throw new Error(fail + ' cannot be used with ' + this.op); - } -}; - -/** - * Determines if `conds` can be merged using `mquery().merge()` - * - * @param {Object} conds - * @return {Boolean} - */ - -Query.canMerge = function(conds) { - return conds instanceof Query || utils.isObject(conds); -}; - -/** - * Set a trace function that will get called whenever a - * query is executed. - * - * See `setTraceFunction()` for details. - * - * @param {Object} conds - * @return {Boolean} - */ -Query.setGlobalTraceFunction = function(traceFunction) { - Query.traceFunction = traceFunction; -}; - -/*! - * Exports. - */ - -Query.utils = utils; -Query.env = require('./env'); -Query.Collection = require('./collection'); -Query.BaseCollection = require('./collection/collection'); -Query.Promise = require('bluebird'); -module.exports = exports = Query; - -// TODO -// test utils diff --git a/node_modules/mquery/lib/permissions.js b/node_modules/mquery/lib/permissions.js deleted file mode 100644 index c306f3a..0000000 --- a/node_modules/mquery/lib/permissions.js +++ /dev/null @@ -1,88 +0,0 @@ -'use strict'; - -var denied = exports; - -denied.distinct = function(self) { - if (self._fields && Object.keys(self._fields).length > 0) { - return 'field selection and slice'; - } - - var keys = Object.keys(denied.distinct); - var err; - - keys.every(function(option) { - if (self.options[option]) { - err = option; - return false; - } - return true; - }); - - return err; -}; -denied.distinct.select = -denied.distinct.slice = -denied.distinct.sort = -denied.distinct.limit = -denied.distinct.skip = -denied.distinct.batchSize = -denied.distinct.comment = -denied.distinct.maxScan = -denied.distinct.snapshot = -denied.distinct.hint = -denied.distinct.tailable = true; - - -// aggregation integration - - -denied.findOneAndUpdate = -denied.findOneAndRemove = function(self) { - var keys = Object.keys(denied.findOneAndUpdate); - var err; - - keys.every(function(option) { - if (self.options[option]) { - err = option; - return false; - } - return true; - }); - - return err; -}; -denied.findOneAndUpdate.limit = -denied.findOneAndUpdate.skip = -denied.findOneAndUpdate.batchSize = -denied.findOneAndUpdate.maxScan = -denied.findOneAndUpdate.snapshot = -denied.findOneAndUpdate.hint = -denied.findOneAndUpdate.tailable = -denied.findOneAndUpdate.comment = true; - - -denied.count = function(self) { - if (self._fields && Object.keys(self._fields).length > 0) { - return 'field selection and slice'; - } - - var keys = Object.keys(denied.count); - var err; - - keys.every(function(option) { - if (self.options[option]) { - err = option; - return false; - } - return true; - }); - - return err; -}; - -denied.count.slice = -denied.count.batchSize = -denied.count.comment = -denied.count.maxScan = -denied.count.snapshot = -denied.count.tailable = true; diff --git a/node_modules/mquery/lib/utils.js b/node_modules/mquery/lib/utils.js deleted file mode 100644 index ef51712..0000000 --- a/node_modules/mquery/lib/utils.js +++ /dev/null @@ -1,356 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -var Buffer = require('safe-buffer').Buffer; -var RegExpClone = require('regexp-clone'); - -/** - * Clones objects - * - * @param {Object} obj the object to clone - * @param {Object} options - * @return {Object} the cloned object - * @api private - */ - -var clone = exports.clone = function clone(obj, options) { - if (obj === undefined || obj === null) - return obj; - - if (Array.isArray(obj)) - return exports.cloneArray(obj, options); - - if (obj.constructor) { - if (/ObjectI[dD]$/.test(obj.constructor.name)) { - return 'function' == typeof obj.clone - ? obj.clone() - : new obj.constructor(obj.id); - } - - if (obj.constructor.name === 'ReadPreference') { - return new obj.constructor(obj.mode, clone(obj.tags, options)); - } - - if ('Binary' == obj._bsontype && obj.buffer && obj.value) { - return 'function' == typeof obj.clone - ? obj.clone() - : new obj.constructor(obj.value(true), obj.sub_type); - } - - if ('Date' === obj.constructor.name || 'Function' === obj.constructor.name) - return new obj.constructor(+obj); - - if ('RegExp' === obj.constructor.name) - return RegExpClone(obj); - - if ('Buffer' === obj.constructor.name) - return exports.cloneBuffer(obj); - } - - if (isObject(obj)) - return exports.cloneObject(obj, options); - - if (obj.valueOf) - return obj.valueOf(); -}; - -/*! - * ignore - */ - -exports.cloneObject = function cloneObject(obj, options) { - var minimize = options && options.minimize; - var ret = {}; - var hasKeys; - var val; - var k; - - for (k in obj) { - val = clone(obj[k], options); - - if (!minimize || ('undefined' !== typeof val)) { - hasKeys || (hasKeys = true); - ret[k] = val; - } - } - - return minimize - ? hasKeys && ret - : ret; -}; - -exports.cloneArray = function cloneArray(arr, options) { - var ret = []; - for (var i = 0, l = arr.length; i < l; i++) - ret.push(clone(arr[i], options)); - return ret; -}; - -/** - * process.nextTick helper. - * - * Wraps the given `callback` in a try/catch. If an error is - * caught it will be thrown on nextTick. - * - * node-mongodb-native had a habit of state corruption when - * an error was immediately thrown from within a collection - * method (find, update, etc) callback. - * - * @param {Function} [callback] - * @api private - */ - -exports.tick = function tick(callback) { - if ('function' !== typeof callback) return; - return function() { - // callbacks should always be fired on the next - // turn of the event loop. A side benefit is - // errors thrown from executing the callback - // will not cause drivers state to be corrupted - // which has historically been a problem. - var args = arguments; - soon(function() { - callback.apply(this, args); - }); - }; -}; - -/** - * Merges `from` into `to` without overwriting existing properties. - * - * @param {Object} to - * @param {Object} from - * @api private - */ - -exports.merge = function merge(to, from) { - var keys = Object.keys(from), - i = keys.length, - key; - - while (i--) { - key = keys[i]; - if ('undefined' === typeof to[key]) { - to[key] = from[key]; - } else { - if (exports.isObject(from[key])) { - merge(to[key], from[key]); - } else { - to[key] = from[key]; - } - } - } -}; - -/** - * Same as merge but clones the assigned values. - * - * @param {Object} to - * @param {Object} from - * @api private - */ - -exports.mergeClone = function mergeClone(to, from) { - var keys = Object.keys(from), - i = keys.length, - key; - - while (i--) { - key = keys[i]; - if ('undefined' === typeof to[key]) { - to[key] = clone(from[key]); - } else { - if (exports.isObject(from[key])) { - mergeClone(to[key], from[key]); - } else { - to[key] = clone(from[key]); - } - } - } -}; - -/** - * Read pref helper (mongo 2.2 drivers support this) - * - * Allows using aliases instead of full preference names: - * - * p primary - * pp primaryPreferred - * s secondary - * sp secondaryPreferred - * n nearest - * - * @param {String} pref - */ - -exports.readPref = function readPref(pref) { - switch (pref) { - case 'p': - pref = 'primary'; - break; - case 'pp': - pref = 'primaryPreferred'; - break; - case 's': - pref = 'secondary'; - break; - case 'sp': - pref = 'secondaryPreferred'; - break; - case 'n': - pref = 'nearest'; - break; - } - - return pref; -}; - - -/** - * Read Concern helper (mongo 3.2 drivers support this) - * - * Allows using string to specify read concern level: - * - * local 3.2+ - * available 3.6+ - * majority 3.2+ - * linearizable 3.4+ - * snapshot 4.0+ - * - * @param {String|Object} concern - */ - -exports.readConcern = function readConcern(concern) { - if ('string' === typeof concern) { - switch (concern) { - case 'l': - concern = 'local'; - break; - case 'a': - concern = 'available'; - break; - case 'm': - concern = 'majority'; - break; - case 'lz': - concern = 'linearizable'; - break; - case 's': - concern = 'snapshot'; - break; - } - concern = { level: concern }; - } - return concern; -}; - -/** - * Object.prototype.toString.call helper - */ - -var _toString = Object.prototype.toString; -exports.toString = function(arg) { - return _toString.call(arg); -}; - -/** - * Determines if `arg` is an object. - * - * @param {Object|Array|String|Function|RegExp|any} arg - * @return {Boolean} - */ - -var isObject = exports.isObject = function(arg) { - return '[object Object]' == exports.toString(arg); -}; - -/** - * Determines if `arg` is an array. - * - * @param {Object} - * @return {Boolean} - * @see nodejs utils - */ - -exports.isArray = function(arg) { - return Array.isArray(arg) || - 'object' == typeof arg && '[object Array]' == exports.toString(arg); -}; - -/** - * Object.keys helper - */ - -exports.keys = Object.keys || function(obj) { - var keys = []; - for (var k in obj) if (obj.hasOwnProperty(k)) { - keys.push(k); - } - return keys; -}; - -/** - * Basic Object.create polyfill. - * Only one argument is supported. - * - * Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create - */ - -exports.create = 'function' == typeof Object.create - ? Object.create - : create; - -function create(proto) { - if (arguments.length > 1) { - throw new Error('Adding properties is not supported'); - } - - function F() {} - F.prototype = proto; - return new F; -} - -/** - * inheritance - */ - -exports.inherits = function(ctor, superCtor) { - ctor.prototype = exports.create(superCtor.prototype); - ctor.prototype.constructor = ctor; -}; - -/** - * nextTick helper - * compat with node 0.10 which behaves differently than previous versions - */ - -var soon = exports.soon = 'function' == typeof setImmediate - ? setImmediate - : process.nextTick; - -/** - * Clones the contents of a buffer. - * - * @param {Buffer} buff - * @return {Buffer} - */ - -exports.cloneBuffer = function(buff) { - var dupe = Buffer.alloc(buff.length); - buff.copy(dupe, 0, 0, buff.length); - return dupe; -}; - -/** - * Check if this object is an arguments object - * - * @param {Any} v - * @return {Boolean} - */ - -exports.isArgumentsObject = function(v) { - return Object.prototype.toString.call(v) === '[object Arguments]'; -}; diff --git a/node_modules/mquery/node_modules/safe-buffer/LICENSE b/node_modules/mquery/node_modules/safe-buffer/LICENSE deleted file mode 100644 index 0c068ce..0000000 --- a/node_modules/mquery/node_modules/safe-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -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/mquery/node_modules/safe-buffer/README.md b/node_modules/mquery/node_modules/safe-buffer/README.md deleted file mode 100644 index e9a81af..0000000 --- a/node_modules/mquery/node_modules/safe-buffer/README.md +++ /dev/null @@ -1,584 +0,0 @@ -# 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/mquery/node_modules/safe-buffer/index.d.ts b/node_modules/mquery/node_modules/safe-buffer/index.d.ts deleted file mode 100644 index e9fed80..0000000 --- a/node_modules/mquery/node_modules/safe-buffer/index.d.ts +++ /dev/null @@ -1,187 +0,0 @@ -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/mquery/node_modules/safe-buffer/index.js b/node_modules/mquery/node_modules/safe-buffer/index.js deleted file mode 100644 index 22438da..0000000 --- a/node_modules/mquery/node_modules/safe-buffer/index.js +++ /dev/null @@ -1,62 +0,0 @@ -/* 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/mquery/node_modules/safe-buffer/package.json b/node_modules/mquery/node_modules/safe-buffer/package.json deleted file mode 100644 index b3b48b1..0000000 --- a/node_modules/mquery/node_modules/safe-buffer/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "_from": "safe-buffer@5.1.2", - "_id": "safe-buffer@5.1.2", - "_inBundle": false, - "_integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "_location": "/mquery/safe-buffer", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "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": [ - "/mquery" - ], - "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "_shasum": "991ec69d296e0313747d59bdfd2b745c35f8828d", - "_spec": "safe-buffer@5.1.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mquery", - "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/mquery/package.json b/node_modules/mquery/package.json deleted file mode 100644 index 948626a..0000000 --- a/node_modules/mquery/package.json +++ /dev/null @@ -1,112 +0,0 @@ -{ - "_from": "mquery@3.2.2", - "_id": "mquery@3.2.2", - "_inBundle": false, - "_integrity": "sha512-XB52992COp0KP230I3qloVUbkLUxJIu328HBP2t2EsxSFtf4W1HPSOBWOXf1bqxK4Xbb66lfMJ+Bpfd9/yZE1Q==", - "_location": "/mquery", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "mquery@3.2.2", - "name": "mquery", - "escapedName": "mquery", - "rawSpec": "3.2.2", - "saveSpec": null, - "fetchSpec": "3.2.2" - }, - "_requiredBy": [ - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/mquery/-/mquery-3.2.2.tgz", - "_shasum": "e1383a3951852ce23e37f619a9b350f1fb3664e7", - "_spec": "mquery@3.2.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mongoose", - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "bugs": { - "url": "https://github.com/aheckmann/mquery/issues/new" - }, - "bundleDependencies": false, - "dependencies": { - "bluebird": "3.5.1", - "debug": "3.1.0", - "regexp-clone": "^1.0.0", - "safe-buffer": "5.1.2", - "sliced": "1.0.1" - }, - "deprecated": false, - "description": "Expressive query building for MongoDB", - "devDependencies": { - "eslint": "5.x", - "mocha": "4.1.0", - "mongodb": "3.1.1" - }, - "engines": { - "node": ">=4.0.0" - }, - "eslintConfig": { - "env": { - "node": true, - "mocha": true, - "es6": false - }, - "extends": "eslint:recommended", - "parserOptions": { - "ecmaVersion": 5 - }, - "rules": { - "comma-style": "error", - "consistent-this": [ - "error", - "_this" - ], - "indent": [ - "error", - 2, - { - "SwitchCase": 1, - "VariableDeclarator": 2 - } - ], - "keyword-spacing": "error", - "no-console": "off", - "no-multi-spaces": "error", - "func-call-spacing": "error", - "no-trailing-spaces": "error", - "quotes": [ - "error", - "single" - ], - "semi": "error", - "space-before-blocks": "error", - "space-before-function-paren": [ - "error", - "never" - ], - "space-infix-ops": "error", - "space-unary-ops": "error" - } - }, - "homepage": "https://github.com/aheckmann/mquery/", - "keywords": [ - "mongodb", - "query", - "builder" - ], - "license": "MIT", - "main": "lib/mquery.js", - "name": "mquery", - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mquery.git" - }, - "scripts": { - "fix-lint": "eslint . --fix", - "lint": "eslint .", - "test": "mocha test/index.js test/*.test.js" - }, - "version": "3.2.2" -} diff --git a/node_modules/mquery/test/collection/browser.js b/node_modules/mquery/test/collection/browser.js deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mquery/test/collection/mongo.js b/node_modules/mquery/test/collection/mongo.js deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mquery/test/collection/node.js b/node_modules/mquery/test/collection/node.js deleted file mode 100644 index 8ac380b..0000000 --- a/node_modules/mquery/test/collection/node.js +++ /dev/null @@ -1,28 +0,0 @@ - -var assert = require('assert'); -var mongo = require('mongodb'); - -var uri = process.env.MQUERY_URI || 'mongodb://localhost/mquery'; -var client; -var db; - -exports.getCollection = function(cb) { - mongo.MongoClient.connect(uri, function(err, _client) { - assert.ifError(err); - client = _client; - db = client.db(); - - var collection = db.collection('stuff'); - - // clean test db before starting - db.dropDatabase(function() { - cb(null, collection); - }); - }); -}; - -exports.dropCollection = function(cb) { - db.dropDatabase(function() { - client.close(cb); - }); -}; diff --git a/node_modules/mquery/test/env.js b/node_modules/mquery/test/env.js deleted file mode 100644 index 38385b0..0000000 --- a/node_modules/mquery/test/env.js +++ /dev/null @@ -1,21 +0,0 @@ - -var env = require('../').env; - -console.log('environment: %s', env.type); - -var col; -switch (env.type) { - case 'node': - col = require('./collection/node'); - break; - case 'mongo': - col = require('./collection/mongo'); - break; - case 'browser': - col = require('./collection/browser'); - break; - default: - throw new Error('missing collection implementation for environment: ' + env.type); -} - -module.exports = exports = col; diff --git a/node_modules/mquery/test/index.js b/node_modules/mquery/test/index.js deleted file mode 100644 index 44adb17..0000000 --- a/node_modules/mquery/test/index.js +++ /dev/null @@ -1,3076 +0,0 @@ -var mquery = require('../'); -var assert = require('assert'); - -/* global Map */ - -describe('mquery', function() { - var col; - - before(function(done) { - // get the env specific collection interface - require('./env').getCollection(function(err, collection) { - assert.ifError(err); - col = collection; - done(); - }); - }); - - after(function(done) { - require('./env').dropCollection(done); - }); - - describe('mquery', function() { - it('is a function', function() { - assert.equal('function', typeof mquery); - }); - it('creates instances with the `new` keyword', function() { - assert.ok(mquery() instanceof mquery); - }); - describe('defaults', function() { - it('are set', function() { - var m = mquery(); - assert.strictEqual(undefined, m.op); - assert.deepEqual({}, m.options); - }); - }); - describe('criteria', function() { - it('if collection-like is used as collection', function() { - var m = mquery(col); - assert.equal(col, m._collection.collection); - }); - it('non-collection-like is used as criteria', function() { - var m = mquery({ works: true }); - assert.ok(!m._collection); - assert.deepEqual({ works: true }, m._conditions); - }); - }); - describe('options', function() { - it('are merged when passed', function() { - var m; - m = mquery(col, { safe: true }); - assert.deepEqual({ safe: true }, m.options); - m = mquery({ name: 'mquery' }, { safe: true }); - assert.deepEqual({ safe: true }, m.options); - }); - }); - }); - - describe('toConstructor', function() { - it('creates subclasses of mquery', function() { - var opts = { safe: { w: 'majority' }, readPreference: 'p' }; - var match = { name: 'test', count: { $gt: 101 }}; - var select = { name: 1, count: 0 }; - var update = { $set: { x: true }}; - var path = 'street'; - - var q = mquery().setOptions(opts); - q.where(match); - q.select(select); - q.update(update); - q.where(path); - q.find(); - - var M = q.toConstructor(); - var m = M(); - - assert.ok(m instanceof mquery); - assert.deepEqual(opts, m.options); - assert.deepEqual(match, m._conditions); - assert.deepEqual(select, m._fields); - assert.deepEqual(update, m._update); - assert.equal(path, m._path); - assert.equal('find', m.op); - }); - }); - - describe('setOptions', function() { - it('calls associated methods', function() { - var m = mquery(); - assert.equal(m._collection, null); - m.setOptions({ collection: col }); - assert.equal(m._collection.collection, col); - }); - it('directly sets option when no method exists', function() { - var m = mquery(); - assert.equal(m.options.woot, null); - m.setOptions({ woot: 'yay' }); - assert.equal(m.options.woot, 'yay'); - }); - it('is chainable', function() { - var m = mquery(), - n; - - n = m.setOptions(); - assert.equal(m, n); - n = m.setOptions({ x: 1 }); - assert.equal(m, n); - }); - }); - - describe('collection', function() { - it('sets the _collection', function() { - var m = mquery(); - m.collection(col); - assert.equal(m._collection.collection, col); - }); - it('is chainable', function() { - var m = mquery(); - var n = m.collection(col); - assert.equal(m, n); - }); - }); - - describe('$where', function() { - it('sets the $where condition', function() { - var m = mquery(); - function go() {} - m.$where(go); - assert.ok(go === m._conditions.$where); - }); - it('is chainable', function() { - var m = mquery(); - var n = m.$where('x'); - assert.equal(m, n); - }); - }); - - describe('where', function() { - it('without arguments', function() { - var m = mquery(); - m.where(); - assert.deepEqual({}, m._conditions); - }); - it('with non-string/object argument', function() { - var m = mquery(); - - assert.throws(function() { - m.where([]); - }, /path must be a string or object/); - }); - describe('with one argument', function() { - it('that is an object', function() { - var m = mquery(); - m.where({ name: 'flawed' }); - assert.strictEqual(m._conditions.name, 'flawed'); - }); - it('that is a query', function() { - var m = mquery({ name: 'first' }); - var n = mquery({ name: 'changed' }); - m.where(n); - assert.strictEqual(m._conditions.name, 'changed'); - }); - it('that is a string', function() { - var m = mquery(); - m.where('name'); - assert.equal('name', m._path); - assert.strictEqual(m._conditions.name, undefined); - }); - }); - it('with two arguments', function() { - var m = mquery(); - m.where('name', 'The Great Pumpkin'); - assert.equal('name', m._path); - assert.strictEqual(m._conditions.name, 'The Great Pumpkin'); - }); - it('is chainable', function() { - var m = mquery(), - n; - - n = m.where('x', 'y'); - assert.equal(m, n); - n = m.where(); - assert.equal(m, n); - }); - }); - describe('equals', function() { - it('must be called after where()', function() { - var m = mquery(); - assert.throws(function() { - m.equals(); - }, /must be used after where/); - }); - it('sets value of path set with where()', function() { - var m = mquery(); - m.where('age').equals(1000); - assert.deepEqual({ age: 1000 }, m._conditions); - }); - it('is chainable', function() { - var m = mquery(); - var n = m.where('x').equals(3); - assert.equal(m, n); - }); - }); - describe('eq', function() { - it('is alias of equals', function() { - var m = mquery(); - m.where('age').eq(1000); - assert.deepEqual({ age: 1000 }, m._conditions); - }); - }); - describe('or', function() { - it('pushes onto the internal $or condition', function() { - var m = mquery(); - m.or({ 'Nightmare Before Christmas': true }); - assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$or); - }); - it('allows passing arrays', function() { - var m = mquery(); - var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; - m.or(arg); - assert.deepEqual(arg, m._conditions.$or); - }); - it('allows calling multiple times', function() { - var m = mquery(); - var arg = [{ looper: true }, { x: 1 }]; - m.or(arg); - m.or({ y: 1 }); - m.or([{ w: 'oo' }, { z: 'oo'} ]); - assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$or); - }); - it('is chainable', function() { - var m = mquery(); - m.or({ o: 'k'}).where('name', 'table'); - assert.deepEqual({ name: 'table', $or: [{ o: 'k' }] }, m._conditions); - }); - }); - - describe('nor', function() { - it('pushes onto the internal $nor condition', function() { - var m = mquery(); - m.nor({ 'Nightmare Before Christmas': true }); - assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$nor); - }); - it('allows passing arrays', function() { - var m = mquery(); - var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; - m.nor(arg); - assert.deepEqual(arg, m._conditions.$nor); - }); - it('allows calling multiple times', function() { - var m = mquery(); - var arg = [{ looper: true }, { x: 1 }]; - m.nor(arg); - m.nor({ y: 1 }); - m.nor([{ w: 'oo' }, { z: 'oo'} ]); - assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$nor); - }); - it('is chainable', function() { - var m = mquery(); - m.nor({ o: 'k'}).where('name', 'table'); - assert.deepEqual({ name: 'table', $nor: [{ o: 'k' }] }, m._conditions); - }); - }); - - describe('and', function() { - it('pushes onto the internal $and condition', function() { - var m = mquery(); - m.and({ 'Nightmare Before Christmas': true }); - assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$and); - }); - it('allows passing arrays', function() { - var m = mquery(); - var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; - m.and(arg); - assert.deepEqual(arg, m._conditions.$and); - }); - it('allows calling multiple times', function() { - var m = mquery(); - var arg = [{ looper: true }, { x: 1 }]; - m.and(arg); - m.and({ y: 1 }); - m.and([{ w: 'oo' }, { z: 'oo'} ]); - assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$and); - }); - it('is chainable', function() { - var m = mquery(); - m.and({ o: 'k'}).where('name', 'table'); - assert.deepEqual({ name: 'table', $and: [{ o: 'k' }] }, m._conditions); - }); - }); - - function generalCondition(type) { - return function() { - it('accepts 2 args', function() { - var m = mquery()[type]('count', 3); - var check = {}; - check['$' + type] = 3; - assert.deepEqual(m._conditions.count, check); - }); - it('uses previously set `where` path if 1 arg passed', function() { - var m = mquery().where('count')[type](3); - var check = {}; - check['$' + type] = 3; - assert.deepEqual(m._conditions.count, check); - }); - it('throws if 1 arg was passed but no previous `where` was used', function() { - assert.throws(function() { - mquery()[type](3); - }, /must be used after where/); - }); - it('is chainable', function() { - var m = mquery().where('count')[type](3).where('x', 8); - var check = {x: 8, count: {}}; - check.count['$' + type] = 3; - assert.deepEqual(m._conditions, check); - }); - it('overwrites previous value', function() { - var m = mquery().where('count')[type](3)[type](8); - var check = {}; - check['$' + type] = 8; - assert.deepEqual(m._conditions.count, check); - }); - }; - } - - 'gt gte lt lte ne in nin regex size maxDistance minDistance'.split(' ').forEach(function(type) { - describe(type, generalCondition(type)); - }); - - describe('mod', function() { - describe('with 1 argument', function() { - it('requires a previous where()', function() { - assert.throws(function() { - mquery().mod([30, 10]); - }, /must be used after where/); - }); - it('works', function() { - var m = mquery().where('madmen').mod([10,20]); - assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}); - }); - }); - - describe('with 2 arguments and second is non-Array', function() { - it('requires a previous where()', function() { - assert.throws(function() { - mquery().mod('x', 10); - }, /must be used after where/); - }); - it('works', function() { - var m = mquery().where('madmen').mod(10, 20); - assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}); - }); - }); - - it('with 2 arguments and second is an array', function() { - var m = mquery().mod('madmen', [10,20]); - assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}); - }); - - it('with 3 arguments', function() { - var m = mquery().mod('madmen', 10, 20); - assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}); - }); - - it('is chainable', function() { - var m = mquery().mod('madmen', 10, 20).where('x', 8); - var check = { madmen: { $mod: [10,20] }, x: 8}; - assert.deepEqual(m._conditions, check); - }); - }); - - describe('exists', function() { - it('with 0 args', function() { - it('throws if not used after where()', function() { - assert.throws(function() { - mquery().exists(); - }, /must be used after where/); - }); - it('works', function() { - var m = mquery().where('name').exists(); - var check = { name: { $exists: true }}; - assert.deepEqual(m._conditions, check); - }); - }); - - describe('with 1 arg', function() { - describe('that is boolean', function() { - it('throws if not used after where()', function() { - assert.throws(function() { - mquery().exists(); - }, /must be used after where/); - }); - it('works', function() { - var m = mquery().exists('name', false); - var check = { name: { $exists: false }}; - assert.deepEqual(m._conditions, check); - }); - }); - describe('that is not boolean', function() { - it('sets the value to `true`', function() { - var m = mquery().where('name').exists('yummy'); - var check = { yummy: { $exists: true }}; - assert.deepEqual(m._conditions, check); - }); - }); - }); - - describe('with 2 args', function() { - it('works', function() { - var m = mquery().exists('yummy', false); - var check = { yummy: { $exists: false }}; - assert.deepEqual(m._conditions, check); - }); - }); - - it('is chainable', function() { - var m = mquery().where('name').exists().find({ x: 1 }); - var check = { name: { $exists: true }, x: 1}; - assert.deepEqual(m._conditions, check); - }); - }); - - describe('elemMatch', function() { - describe('with null/undefined first argument', function() { - assert.throws(function() { - mquery().elemMatch(); - }, /Invalid argument/); - assert.throws(function() { - mquery().elemMatch(null); - }, /Invalid argument/); - assert.doesNotThrow(function() { - mquery().elemMatch('', {}); - }); - }); - - describe('with 1 argument', function() { - it('throws if not a function or object', function() { - assert.throws(function() { - mquery().elemMatch([]); - }, /Invalid argument/); - }); - - describe('that is an object', function() { - it('throws if no previous `where` was used', function() { - assert.throws(function() { - mquery().elemMatch({}); - }, /must be used after where/); - }); - it('works', function() { - var m = mquery().where('comment').elemMatch({ author: 'joe', votes: {$gte: 3 }}); - assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); - }); - }); - describe('that is a function', function() { - it('throws if no previous `where` was used', function() { - assert.throws(function() { - mquery().elemMatch(function() {}); - }, /must be used after where/); - }); - it('works', function() { - var m = mquery().where('comment').elemMatch(function(query) { - query.where({ author: 'joe', votes: {$gte: 3 }}); - }); - assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); - }); - }); - }); - - describe('with 2 arguments', function() { - describe('and the 2nd is an object', function() { - it('works', function() { - var m = mquery().elemMatch('comment', { author: 'joe', votes: {$gte: 3 }}); - assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); - }); - }); - describe('and the 2nd is a function', function() { - it('works', function() { - var m = mquery().elemMatch('comment', function(query) { - query.where({ author: 'joe', votes: {$gte: 3 }}); - }); - assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); - }); - }); - it('and the 2nd is not a function or object', function() { - assert.throws(function() { - mquery().elemMatch('comment', []); - }, /Invalid argument/); - }); - }); - }); - - describe('within', function() { - it('is chainable', function() { - var m = mquery(); - assert.equal(m.where('a').within(), m); - }); - describe('when called with arguments', function() { - it('must follow where()', function() { - assert.throws(function() { - mquery().within([]); - }, /must be used after where/); - }); - - describe('of length 1', function() { - it('throws if not a recognized shape', function() { - assert.throws(function() { - mquery().where('loc').within({}); - }, /Invalid argument/); - assert.throws(function() { - mquery().where('loc').within(null); - }, /Invalid argument/); - }); - it('delegates to circle when center exists', function() { - var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); - assert.deepEqual({ $geoWithin: {$center:[[10,10], 3]}}, m._conditions.loc); - }); - it('delegates to box when exists', function() { - var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); - assert.deepEqual({ $geoWithin: {$box:[[10,10], [11,14]]}}, m._conditions.loc); - }); - it('delegates to polygon when exists', function() { - var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); - assert.deepEqual({ $geoWithin: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); - }); - it('delegates to geometry when exists', function() { - var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); - assert.deepEqual({ $geoWithin: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); - }); - }); - - describe('of length 2', function() { - it('delegates to box()', function() { - var m = mquery().where('loc').within([1,2],[2,5]); - assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[2,5]]}}); - }); - }); - - describe('of length > 2', function() { - it('delegates to polygon()', function() { - var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); - assert.deepEqual(m._conditions.loc, { $geoWithin: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); - }); - }); - }); - }); - - describe('geoWithin', function() { - before(function() { - mquery.use$geoWithin = false; - }); - after(function() { - mquery.use$geoWithin = true; - }); - describe('when called with arguments', function() { - describe('of length 1', function() { - it('delegates to circle when center exists', function() { - var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); - assert.deepEqual({ $within: {$center:[[10,10], 3]}}, m._conditions.loc); - }); - it('delegates to box when exists', function() { - var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); - assert.deepEqual({ $within: {$box:[[10,10], [11,14]]}}, m._conditions.loc); - }); - it('delegates to polygon when exists', function() { - var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); - assert.deepEqual({ $within: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); - }); - it('delegates to geometry when exists', function() { - var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); - assert.deepEqual({ $within: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); - }); - }); - - describe('of length 2', function() { - it('delegates to box()', function() { - var m = mquery().where('loc').within([1,2],[2,5]); - assert.deepEqual(m._conditions.loc, { $within: { $box: [[1,2],[2,5]]}}); - }); - }); - - describe('of length > 2', function() { - it('delegates to polygon()', function() { - var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); - assert.deepEqual(m._conditions.loc, { $within: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); - }); - }); - }); - }); - - describe('box', function() { - describe('with 1 argument', function() { - it('throws', function() { - assert.throws(function() { - mquery().box('sometihng'); - }, /Invalid argument/); - }); - }); - describe('with > 3 arguments', function() { - it('throws', function() { - assert.throws(function() { - mquery().box(1,2,3,4); - }, /Invalid argument/); - }); - }); - - describe('with 2 arguments', function() { - it('throws if not used after where()', function() { - assert.throws(function() { - mquery().box([],[]); - }, /must be used after where/); - }); - it('works', function() { - var m = mquery().where('loc').box([1,2],[3,4]); - assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); - }); - }); - - describe('with 3 arguments', function() { - it('works', function() { - var m = mquery().box('loc', [1,2],[3,4]); - assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); - }); - }); - }); - - describe('polygon', function() { - describe('when first argument is not a string', function() { - it('throws if not used after where()', function() { - assert.throws(function() { - mquery().polygon({}); - }, /must be used after where/); - - assert.doesNotThrow(function() { - mquery().where('loc').polygon([1,2], [2,3], [3,6]); - }); - }); - - it('assigns arguments to within polygon condition', function() { - var m = mquery().where('loc').polygon([1,2], [2,3], [3,6]); - assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); - }); - }); - - describe('when first arg is a string', function() { - it('assigns remaining arguments to within polygon condition', function() { - var m = mquery().polygon('loc', [1,2], [2,3], [3,6]); - assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); - }); - }); - }); - - describe('circle', function() { - describe('with one arg', function() { - it('must follow where()', function() { - assert.throws(function() { - mquery().circle('x'); - }, /must be used after where/); - assert.doesNotThrow(function() { - mquery().where('loc').circle({center:[0,0], radius: 3 }); - }); - }); - it('works', function() { - var m = mquery().where('loc').circle({center:[0,0], radius: 3 }); - assert.deepEqual(m._conditions, { loc: { $geoWithin: {$center: [[0,0],3] }}}); - }); - }); - describe('with 3 args', function() { - it('throws', function() { - assert.throws(function() { - mquery().where('loc').circle(1,2,3); - }, /Invalid argument/); - }); - }); - describe('requires radius and center', function() { - assert.throws(function() { - mquery().circle('loc', { center: 1 }); - }, /center and radius are required/); - assert.throws(function() { - mquery().circle('loc', { radius: 1 }); - }, /center and radius are required/); - assert.doesNotThrow(function() { - mquery().circle('loc', { center: [1,2], radius: 1 }); - }); - }); - }); - - describe('geometry', function() { - // within + intersects - var point = { type: 'Point', coordinates: [[0,0],[1,1]] }; - - it('must be called after within or intersects', function(done) { - assert.throws(function() { - mquery().where('a').geometry(point); - }, /must come after/); - - assert.doesNotThrow(function() { - mquery().where('a').within().geometry(point); - }); - - assert.doesNotThrow(function() { - mquery().where('a').intersects().geometry(point); - }); - - done(); - }); - - describe('when called with one argument', function() { - describe('after within()', function() { - it('and arg quacks like geoJSON', function(done) { - var m = mquery().where('a').within().geometry(point); - assert.deepEqual({ a: { $geoWithin: { $geometry: point }}}, m._conditions); - done(); - }); - }); - - describe('after intersects()', function() { - it('and arg quacks like geoJSON', function(done) { - var m = mquery().where('a').intersects().geometry(point); - assert.deepEqual({ a: { $geoIntersects: { $geometry: point }}}, m._conditions); - done(); - }); - }); - - it('and arg does not quack like geoJSON', function(done) { - assert.throws(function() { - mquery().where('b').within().geometry({type:1, coordinates:2}); - }, /Invalid argument/); - done(); - }); - }); - - describe('when called with zero arguments', function() { - it('throws', function(done) { - assert.throws(function() { - mquery().where('a').within().geometry(); - }, /Invalid argument/); - - done(); - }); - }); - - describe('when called with more than one arguments', function() { - it('throws', function(done) { - assert.throws(function() { - mquery().where('a').within().geometry({type:'a',coordinates:[]}, 2); - }, /Invalid argument/); - done(); - }); - }); - }); - - describe('intersects', function() { - it('must be used after where()', function(done) { - var m = mquery(); - assert.throws(function() { - m.intersects(); - }, /must be used after where/); - done(); - }); - - it('sets geo comparison to "$intersects"', function(done) { - var n = mquery().where('a').intersects(); - assert.equal('$geoIntersects', n._geoComparison); - done(); - }); - - it('is chainable', function() { - var m = mquery(); - assert.equal(m.where('a').intersects(), m); - }); - - it('calls geometry if argument quacks like geojson', function(done) { - var m = mquery(); - var o = { type: 'LineString', coordinates: [[0,1],[3,40]] }; - var ran = false; - - m.geometry = function(arg) { - ran = true; - assert.deepEqual(o, arg); - }; - - m.where('a').intersects(o); - assert.ok(ran); - - done(); - }); - - it('throws if argument is not geometry-like', function(done) { - var m = mquery().where('a'); - - assert.throws(function() { - m.intersects(null); - }, /Invalid argument/); - - assert.throws(function() { - m.intersects(undefined); - }, /Invalid argument/); - - assert.throws(function() { - m.intersects(false); - }, /Invalid argument/); - - assert.throws(function() { - m.intersects({}); - }, /Invalid argument/); - - assert.throws(function() { - m.intersects([]); - }, /Invalid argument/); - - assert.throws(function() { - m.intersects(function() {}); - }, /Invalid argument/); - - assert.throws(function() { - m.intersects(NaN); - }, /Invalid argument/); - - done(); - }); - }); - - describe('near', function() { - // near nearSphere - describe('with 0 args', function() { - it('is compatible with geometry()', function(done) { - var q = mquery().where('x').near().geometry({ type: 'Point', coordinates: [180, 11] }); - assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [180,11]}}}, q._conditions.x); - done(); - }); - }); - - describe('with 1 arg', function() { - it('throws if not used after where()', function() { - assert.throws(function() { - mquery().near(1); - }, /must be used after where/); - }); - it('does not throw if used after where()', function() { - assert.doesNotThrow(function() { - mquery().where('loc').near({center:[1,1]}); - }); - }); - }); - describe('with > 2 args', function() { - it('throws', function() { - assert.throws(function() { - mquery().near(1,2,3); - }, /Invalid argument/); - }); - }); - - it('creates $geometry args for GeoJSON', function() { - var m = mquery().where('loc').near({ center: { type: 'Point', coordinates: [10,10] }}); - assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [10,10]}}}, m._conditions.loc); - }); - - it('expects `center`', function() { - assert.throws(function() { - mquery().near('loc', { maxDistance: 3 }); - }, /center is required/); - assert.doesNotThrow(function() { - mquery().near('loc', { center: [3,4] }); - }); - }); - - it('accepts spherical conditions', function() { - var m = mquery().where('loc').near({ center: [1,2], spherical: true }); - assert.deepEqual(m._conditions, { loc: { $nearSphere: [1,2]}}); - }); - - it('is non-spherical by default', function() { - var m = mquery().where('loc').near({ center: [1,2] }); - assert.deepEqual(m._conditions, { loc: { $near: [1,2]}}); - }); - - it('supports maxDistance', function() { - var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }); - assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}}); - }); - - it('supports minDistance', function() { - var m = mquery().where('loc').near({ center: [1,2], minDistance:4 }); - assert.deepEqual(m._conditions, { loc: { $near: [1,2], $minDistance: 4}}); - }); - - it('is chainable', function() { - var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }).find({ x: 1 }); - assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}, x: 1}); - }); - - describe('supports passing GeoJSON, gh-13', function() { - it('with center', function() { - var m = mquery().where('loc').near({ - center: { type: 'Point', coordinates: [1,1] }, - maxDistance: 2 - }); - - var expect = { - loc: { - $near: { - $geometry: { - type: 'Point', - coordinates : [1,1] - }, - $maxDistance : 2 - } - } - }; - - assert.deepEqual(m._conditions, expect); - }); - }); - }); - - // fields - - describe('select', function() { - describe('with 0 args', function() { - it('is chainable', function() { - var m = mquery(); - assert.equal(m, m.select()); - }); - }); - - it('accepts an object', function() { - var o = { x: 1, y: 1 }; - var m = mquery().select(o); - assert.deepEqual(m._fields, o); - }); - - it('accepts a string', function() { - var o = 'x -y'; - var m = mquery().select(o); - assert.deepEqual(m._fields, { x: 1, y: 0 }); - }); - - it('does accept an array', function() { - var o = ['x', '-y']; - var m = mquery().select(o); - assert.deepEqual(m._fields, { x: 1, y: 0 }); - }); - - it('merges previous arguments', function() { - var o = { x: 1, y: 0, a: 1 }; - var m = mquery().select(o); - m.select('z -u w').select({ x: 0 }); - assert.deepEqual(m._fields, { - x: 0, - y: 0, - z: 1, - u: 0, - w: 1, - a: 1 - }); - }); - - it('rejects non-string, object, arrays', function() { - assert.throws(function() { - mquery().select(function() {}); - }, /Invalid select\(\) argument/); - }); - - it('accepts arguments objects', function() { - var m = mquery(); - function t() { - m.select(arguments); - assert.deepEqual(m._fields, { x: 1, y: 0 }); - } - t('x', '-y'); - }); - - noDistinct('select'); - }); - - describe('selected', function() { - it('returns true when fields have been selected', function(done) { - var m; - - m = mquery().select({ name: 1 }); - assert.ok(m.selected()); - - m = mquery().select('name'); - assert.ok(m.selected()); - - done(); - }); - - it('returns false when no fields have been selected', function(done) { - var m = mquery(); - assert.strictEqual(false, m.selected()); - done(); - }); - }); - - describe('selectedInclusively', function() { - describe('returns false', function() { - it('when no fields have been selected', function(done) { - assert.strictEqual(false, mquery().selectedInclusively()); - assert.equal(false, mquery().select({}).selectedInclusively()); - done(); - }); - it('when any fields have been excluded', function(done) { - assert.strictEqual(false, mquery().select('-name').selectedInclusively()); - assert.strictEqual(false, mquery().select({ name: 0 }).selectedInclusively()); - assert.strictEqual(false, mquery().select('name bio -_id').selectedInclusively()); - assert.strictEqual(false, mquery().select({ name: 1, _id: 0 }).selectedInclusively()); - done(); - }); - it('when using $meta', function(done) { - assert.strictEqual(false, mquery().select({ name: { $meta: 'textScore' } }).selectedInclusively()); - done(); - }); - }); - - describe('returns true', function() { - it('when fields have been included', function(done) { - assert.equal(true, mquery().select('name').selectedInclusively()); - assert.equal(true, mquery().select({ name:1 }).selectedInclusively()); - done(); - }); - }); - }); - - describe('selectedExclusively', function() { - describe('returns false', function() { - it('when no fields have been selected', function(done) { - assert.equal(false, mquery().selectedExclusively()); - assert.equal(false, mquery().select({}).selectedExclusively()); - done(); - }); - it('when fields have only been included', function(done) { - assert.equal(false, mquery().select('name').selectedExclusively()); - assert.equal(false, mquery().select({ name: 1 }).selectedExclusively()); - done(); - }); - }); - - describe('returns true', function() { - it('when any field has been excluded', function(done) { - assert.equal(true, mquery().select('-name').selectedExclusively()); - assert.equal(true, mquery().select({ name:0 }).selectedExclusively()); - assert.equal(true, mquery().select('-_id').selectedExclusively()); - assert.strictEqual(true, mquery().select('name bio -_id').selectedExclusively()); - assert.strictEqual(true, mquery().select({ name: 1, _id: 0 }).selectedExclusively()); - done(); - }); - }); - }); - - describe('slice', function() { - describe('with 0 args', function() { - it('is chainable', function() { - var m = mquery(); - assert.equal(m, m.slice()); - }); - it('is a noop', function() { - var m = mquery().slice(); - assert.deepEqual(m._fields, undefined); - }); - }); - - describe('with 1 arg', function() { - it('throws if not called after where()', function() { - assert.throws(function() { - mquery().slice(1); - }, /must be used after where/); - assert.doesNotThrow(function() { - mquery().where('a').slice(1); - }); - }); - it('that is a number', function() { - var query = mquery(); - query.where('collection').slice(5); - assert.deepEqual(query._fields, {collection: {$slice: 5}}); - }); - it('that is an array', function() { - var query = mquery(); - query.where('collection').slice([5,10]); - assert.deepEqual(query._fields, {collection: {$slice: [5,10]}}); - }); - it('that is an object', function() { - var query = mquery(); - query.slice({ collection: [5, 10] }); - assert.deepEqual(query._fields, {collection: {$slice: [5,10]}}); - }); - }); - - describe('with 2 args', function() { - describe('and first is a number', function() { - it('throws if not called after where', function() { - assert.throws(function() { - mquery().slice(2,3); - }, /must be used after where/); - }); - it('does not throw if used after where', function() { - var query = mquery(); - query.where('collection').slice(2,3); - assert.deepEqual(query._fields, {collection: {$slice: [2,3]}}); - }); - }); - it('and first is not a number', function() { - var query = mquery().slice('collection', [-5, 2]); - assert.deepEqual(query._fields, {collection: {$slice: [-5,2]}}); - }); - }); - - describe('with 3 args', function() { - it('works', function() { - var query = mquery(); - query.slice('collection', 14, 10); - assert.deepEqual(query._fields, {collection: {$slice: [14, 10]}}); - }); - }); - - noDistinct('slice'); - no('count', 'slice'); - }); - - // options - - describe('sort', function() { - describe('with 0 args', function() { - it('chains', function() { - var m = mquery(); - assert.equal(m, m.sort()); - }); - it('has no affect', function() { - var m = mquery(); - assert.equal(m.options.sort, undefined); - }); - }); - - it('works', function() { - var query = mquery(); - query.sort('a -c b'); - assert.deepEqual(query.options.sort, { a : 1, b: 1, c : -1}); - - query = mquery(); - query.sort({'a': 1, 'c': -1, 'b': 'asc', e: 'descending', f: 'ascending'}); - assert.deepEqual(query.options.sort, {'a': 1, 'c': -1, 'b': 1, 'e': -1, 'f': 1}); - - query = mquery(); - query.sort([['a', -1], ['c', 1], ['b', 'desc'], ['e', 'ascending'], ['f', 'descending']]); - assert.deepEqual(query.options.sort, [['a', -1], ['c', 1], ['b', -1], ['e', 1], ['f', -1]]); - - query = mquery(); - var e = undefined; - try { - query.sort([['a', 1], { 'b': 5 }]); - } catch (err) { - e = err; - } - assert.ok(e, 'uh oh. no error was thrown'); - assert.equal(e.message, 'Invalid sort() argument, must be array of arrays'); - - query = mquery(); - e = undefined; - - try { - query.sort('a', 1, 'c', -1, 'b', 1); - } catch (err) { - e = err; - } - assert.ok(e, 'uh oh. no error was thrown'); - assert.equal(e.message, 'Invalid sort() argument. Must be a string, object, or array.'); - }); - - it('handles $meta sort options', function() { - var query = mquery(); - query.sort({ score: { $meta : 'textScore' } }); - assert.deepEqual(query.options.sort, { score : { $meta : 'textScore' } }); - }); - - it('array syntax', function() { - var query = mquery(); - query.sort([['field', 1], ['test', -1]]); - assert.deepEqual(query.options.sort, [['field', 1], ['test', -1]]); - }); - - it('throws with mixed array/object syntax', function() { - var query = mquery(); - assert.throws(function() { - query.sort({ field: 1 }).sort([['test', -1]]); - }, /Can't mix sort syntaxes/); - assert.throws(function() { - query.sort([['field', 1]]).sort({ test: 1 }); - }, /Can't mix sort syntaxes/); - }); - - it('works with maps', function() { - if (typeof Map === 'undefined') { - return this.skip(); - } - var query = mquery(); - query.sort(new Map().set('field', 1).set('test', -1)); - assert.deepEqual(query.options.sort, new Map().set('field', 1).set('test', -1)); - }); - }); - - function simpleOption(type, options) { - describe(type, function() { - it('sets the ' + type + ' option', function() { - var m = mquery()[type](2); - var optionName = options.name || type; - assert.equal(2, m.options[optionName]); - }); - it('is chainable', function() { - var m = mquery(); - assert.equal(m[type](3), m); - }); - - if (!options.distinct) noDistinct(type); - if (!options.count) no('count', type); - }); - } - - var negated = { - limit: {distinct: false, count: true}, - skip: {distinct: false, count: true}, - maxScan: {distinct: false, count: false}, - batchSize: {distinct: false, count: false}, - maxTime: {distinct: true, count: true, name: 'maxTimeMS' }, - comment: {distinct: false, count: false} - }; - Object.keys(negated).forEach(function(key) { - simpleOption(key, negated[key]); - }); - - describe('snapshot', function() { - it('works', function() { - var query; - - query = mquery(); - query.snapshot(); - assert.equal(true, query.options.snapshot); - - query = mquery(); - query.snapshot(true); - assert.equal(true, query.options.snapshot); - - query = mquery(); - query.snapshot(false); - assert.equal(false, query.options.snapshot); - }); - noDistinct('snapshot'); - no('count', 'snapshot'); - }); - - describe('hint', function() { - it('accepts an object', function() { - var query2 = mquery(); - query2.hint({'a': 1, 'b': -1}); - assert.deepEqual(query2.options.hint, {'a': 1, 'b': -1}); - }); - - it('accepts a string', function() { - var query2 = mquery(); - query2.hint('a'); - assert.deepEqual(query2.options.hint, 'a'); - }); - - it('rejects everything else', function() { - assert.throws(function() { - mquery().hint(['c']); - }, /Invalid hint./); - assert.throws(function() { - mquery().hint(1); - }, /Invalid hint./); - }); - - describe('does not have side affects', function() { - it('on invalid arg', function() { - var m = mquery(); - try { - m.hint(1); - } catch (err) { - // ignore - } - assert.equal(undefined, m.options.hint); - }); - it('on missing arg', function() { - var m = mquery().hint(); - assert.equal(undefined, m.options.hint); - }); - }); - - noDistinct('hint'); - }); - - describe('j', function() { - it('works', function() { - var m = mquery().j(true); - assert.equal(true, m.options.j); - }); - }); - - describe('slaveOk', function() { - it('works', function() { - var query; - - query = mquery(); - query.slaveOk(); - assert.equal(true, query.options.slaveOk); - - query = mquery(); - query.slaveOk(true); - assert.equal(true, query.options.slaveOk); - - query = mquery(); - query.slaveOk(false); - assert.equal(false, query.options.slaveOk); - }); - }); - - describe('read', function() { - it('sets associated readPreference option', function() { - var m = mquery(); - m.read('p'); - assert.equal('primary', m.options.readPreference); - }); - it('is chainable', function() { - var m = mquery(); - assert.equal(m, m.read('sp')); - }); - }); - - describe('readConcern', function() { - it('sets associated readConcern option', function() { - var m; - - m = mquery(); - m.readConcern('s'); - assert.deepEqual({ level: 'snapshot' }, m.options.readConcern); - - m = mquery(); - m.r('local'); - assert.deepEqual({ level: 'local' }, m.options.readConcern); - }); - it('is chainable', function() { - var m = mquery(); - assert.equal(m, m.readConcern('lz')); - }); - }); - - describe('tailable', function() { - it('works', function() { - var query; - - query = mquery(); - query.tailable(); - assert.equal(true, query.options.tailable); - - query = mquery(); - query.tailable(true); - assert.equal(true, query.options.tailable); - - query = mquery(); - query.tailable(false); - assert.equal(false, query.options.tailable); - }); - it('is chainable', function() { - var m = mquery(); - assert.equal(m, m.tailable()); - }); - noDistinct('tailable'); - no('count', 'tailable'); - }); - - describe('writeConcern', function() { - it('sets associated writeConcern option', function() { - var m; - m = mquery(); - m.writeConcern('majority'); - assert.equal('majority', m.options.w); - - m = mquery(); - m.writeConcern('m'); // m is alias of majority - assert.equal('majority', m.options.w); - - m = mquery(); - m.writeConcern(1); - assert.equal(1, m.options.w); - }); - it('accepts object', function() { - var m; - - m = mquery().writeConcern({ w: 'm', j: true, wtimeout: 1000 }); - assert.equal('m', m.options.w); // check it does not convert m to majority - assert.equal(true, m.options.j); - assert.equal(1000, m.options.wtimeout); - - m = mquery().w('m').w({j: false, wtimeout: 0 }); - assert.equal('majority', m.options.w); - assert.strictEqual(false, m.options.j); - assert.strictEqual(0, m.options.wtimeout); - }); - it('is chainable', function() { - var m = mquery(); - assert.equal(m, m.writeConcern('majority')); - }); - }); - - // query utilities - - describe('merge', function() { - describe('with falsy arg', function() { - it('returns itself', function() { - var m = mquery(); - assert.equal(m, m.merge()); - assert.equal(m, m.merge(null)); - assert.equal(m, m.merge(0)); - }); - }); - describe('with an argument', function() { - describe('that is not a query or plain object', function() { - it('throws', function() { - assert.throws(function() { - mquery().merge([]); - }, /Invalid argument/); - assert.throws(function() { - mquery().merge('merge'); - }, /Invalid argument/); - assert.doesNotThrow(function() { - mquery().merge({}); - }, /Invalid argument/); - }); - }); - - describe('that is a query', function() { - it('merges conditions, field selection, and options', function() { - var m = mquery({ x: 'hi' }, { select: 'x y', another: true }); - var n = mquery().merge(m); - assert.deepEqual(n._conditions, m._conditions); - assert.deepEqual(n._fields, m._fields); - assert.deepEqual(n.options, m.options); - }); - it('clones update arguments', function(done) { - var original = { $set: { iTerm: true }}; - var m = mquery().update(original); - var n = mquery().merge(m); - m.update({ $set: { x: 2 }}); - assert.notDeepEqual(m._update, n._update); - done(); - }); - it('is chainable', function() { - var m = mquery({ x: 'hi' }); - var n = mquery(); - assert.equal(n, n.merge(m)); - }); - }); - - describe('that is an object', function() { - it('merges', function() { - var m = { x: 'hi' }; - var n = mquery().merge(m); - assert.deepEqual(n._conditions, { x: 'hi' }); - }); - it('clones update arguments', function(done) { - var original = { $set: { iTerm: true }}; - var m = mquery().update(original); - var n = mquery().merge(original); - m.update({ $set: { x: 2 }}); - assert.notDeepEqual(m._update, n._update); - done(); - }); - it('is chainable', function() { - var m = { x: 'hi' }; - var n = mquery(); - assert.equal(n, n.merge(m)); - }); - }); - }); - }); - - // queries - - describe('find', function() { - describe('with no callback', function() { - it('does not execute', function() { - var m = mquery(); - assert.doesNotThrow(function() { - m.find(); - }); - assert.doesNotThrow(function() { - m.find({ x: 1 }); - }); - }); - }); - - it('is chainable', function() { - var m = mquery().find({ x: 1 }).find().find({ y: 2 }); - assert.deepEqual(m._conditions, {x:1,y:2}); - }); - - it('merges other queries', function() { - var m = mquery({ name: 'mquery' }); - m.tailable(); - m.select('_id'); - var a = mquery().find(m); - assert.deepEqual(a._conditions, m._conditions); - assert.deepEqual(a.options, m.options); - assert.deepEqual(a._fields, m._fields); - }); - - describe('executes', function() { - before(function(done) { - col.insert({ name: 'mquery' }, { safe: true }, done); - }); - - after(function(done) { - col.remove({ name: 'mquery' }, done); - }); - - it('when criteria is passed with a callback', function(done) { - mquery(col).find({ name: 'mquery' }, function(err, docs) { - assert.ifError(err); - assert.equal(1, docs.length); - done(); - }); - }); - it('when Query is passed with a callback', function(done) { - var m = mquery({ name: 'mquery' }); - mquery(col).find(m, function(err, docs) { - assert.ifError(err); - assert.equal(1, docs.length); - done(); - }); - }); - it('when just a callback is passed', function(done) { - mquery({ name: 'mquery' }).collection(col).find(function(err, docs) { - assert.ifError(err); - assert.equal(1, docs.length); - done(); - }); - }); - }); - }); - - describe('findOne', function() { - describe('with no callback', function() { - it('does not execute', function() { - var m = mquery(); - assert.doesNotThrow(function() { - m.findOne(); - }); - assert.doesNotThrow(function() { - m.findOne({ x: 1 }); - }); - }); - }); - - it('is chainable', function() { - var m = mquery(); - var n = m.findOne({ x: 1 }).findOne().findOne({ y: 2 }); - assert.equal(m, n); - assert.deepEqual(m._conditions, {x:1,y:2}); - assert.equal('findOne', m.op); - }); - - it('merges other queries', function() { - var m = mquery({ name: 'mquery' }); - m.read('nearest'); - m.select('_id'); - var a = mquery().findOne(m); - assert.deepEqual(a._conditions, m._conditions); - assert.deepEqual(a.options, m.options); - assert.deepEqual(a._fields, m._fields); - }); - - describe('executes', function() { - before(function(done) { - col.insert({ name: 'mquery findone' }, { safe: true }, done); - }); - - after(function(done) { - col.remove({ name: 'mquery findone' }, done); - }); - - it('when criteria is passed with a callback', function(done) { - mquery(col).findOne({ name: 'mquery findone' }, function(err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal('mquery findone', doc.name); - done(); - }); - }); - it('when Query is passed with a callback', function(done) { - var m = mquery(col).where({ name: 'mquery findone' }); - mquery(col).findOne(m, function(err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal('mquery findone', doc.name); - done(); - }); - }); - it('when just a callback is passed', function(done) { - mquery({ name: 'mquery findone' }).collection(col).findOne(function(err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal('mquery findone', doc.name); - done(); - }); - }); - }); - }); - - describe('count', function() { - describe('with no callback', function() { - it('does not execute', function() { - var m = mquery(); - assert.doesNotThrow(function() { - m.count(); - }); - assert.doesNotThrow(function() { - m.count({ x: 1 }); - }); - }); - }); - - it('is chainable', function() { - var m = mquery(); - var n = m.count({ x: 1 }).count().count({ y: 2 }); - assert.equal(m, n); - assert.deepEqual(m._conditions, {x:1,y:2}); - assert.equal('count', m.op); - }); - - it('merges other queries', function() { - var m = mquery({ name: 'mquery' }); - m.read('nearest'); - m.select('_id'); - var a = mquery().count(m); - assert.deepEqual(a._conditions, m._conditions); - assert.deepEqual(a.options, m.options); - assert.deepEqual(a._fields, m._fields); - }); - - describe('executes', function() { - before(function(done) { - col.insert({ name: 'mquery count' }, { safe: true }, done); - }); - - after(function(done) { - col.remove({ name: 'mquery count' }, done); - }); - - it('when criteria is passed with a callback', function(done) { - mquery(col).count({ name: 'mquery count' }, function(err, count) { - assert.ifError(err); - assert.ok(count); - assert.ok(1 === count); - done(); - }); - }); - it('when Query is passed with a callback', function(done) { - var m = mquery({ name: 'mquery count' }); - mquery(col).count(m, function(err, count) { - assert.ifError(err); - assert.ok(count); - assert.ok(1 === count); - done(); - }); - }); - it('when just a callback is passed', function(done) { - mquery({ name: 'mquery count' }).collection(col).count(function(err, count) { - assert.ifError(err); - assert.ok(1 === count); - done(); - }); - }); - }); - - describe('validates its option', function() { - it('sort', function(done) { - assert.doesNotThrow(function() { - mquery().sort('x').count(); - }); - done(); - }); - - it('select', function(done) { - assert.throws(function() { - mquery().select('x').count(); - }, /field selection and slice cannot be used with count/); - done(); - }); - - it('slice', function(done) { - assert.throws(function() { - mquery().where('x').slice(-3).count(); - }, /field selection and slice cannot be used with count/); - done(); - }); - - it('limit', function(done) { - assert.doesNotThrow(function() { - mquery().limit(3).count(); - }); - done(); - }); - - it('skip', function(done) { - assert.doesNotThrow(function() { - mquery().skip(3).count(); - }); - done(); - }); - - it('batchSize', function(done) { - assert.throws(function() { - mquery({}, { batchSize: 3 }).count(); - }, /batchSize cannot be used with count/); - done(); - }); - - it('comment', function(done) { - assert.throws(function() { - mquery().comment('mquery').count(); - }, /comment cannot be used with count/); - done(); - }); - - it('maxScan', function(done) { - assert.throws(function() { - mquery().maxScan(300).count(); - }, /maxScan cannot be used with count/); - done(); - }); - - it('snapshot', function(done) { - assert.throws(function() { - mquery().snapshot().count(); - }, /snapshot cannot be used with count/); - done(); - }); - - it('tailable', function(done) { - assert.throws(function() { - mquery().tailable().count(); - }, /tailable cannot be used with count/); - done(); - }); - }); - }); - - describe('distinct', function() { - describe('with no callback', function() { - it('does not execute', function() { - var m = mquery(); - assert.doesNotThrow(function() { - m.distinct(); - }); - assert.doesNotThrow(function() { - m.distinct('name'); - }); - assert.doesNotThrow(function() { - m.distinct({ name: 'mquery distinct' }); - }); - assert.doesNotThrow(function() { - m.distinct({ name: 'mquery distinct' }, 'name'); - }); - }); - }); - - it('is chainable', function() { - var m = mquery({x:1}).distinct('name'); - var n = m.distinct({y:2}); - assert.equal(m, n); - assert.deepEqual(n._conditions, {x:1, y:2}); - assert.equal('name', n._distinct); - assert.equal('distinct', n.op); - }); - - it('overwrites field', function() { - var m = mquery({ name: 'mquery' }).distinct('name'); - m.distinct('rename'); - assert.equal(m._distinct, 'rename'); - m.distinct({x:1}, 'renamed'); - assert.equal(m._distinct, 'renamed'); - }); - - it('merges other queries', function() { - var m = mquery().distinct({ name: 'mquery' }, 'age'); - m.read('nearest'); - var a = mquery().distinct(m); - assert.deepEqual(a._conditions, m._conditions); - assert.deepEqual(a.options, m.options); - assert.deepEqual(a._fields, m._fields); - assert.deepEqual(a._distinct, m._distinct); - }); - - describe('executes', function() { - before(function(done) { - col.insert({ name: 'mquery distinct', age: 1 }, { safe: true }, done); - }); - - after(function(done) { - col.remove({ name: 'mquery distinct' }, done); - }); - - it('when distinct arg is passed with a callback', function(done) { - mquery(col).distinct('distinct', function(err, doc) { - assert.ifError(err); - assert.ok(doc); - done(); - }); - }); - describe('when criteria is passed with a callback', function() { - it('if distinct arg was declared', function(done) { - mquery(col).distinct('age').distinct({ name: 'mquery distinct' }, function(err, doc) { - assert.ifError(err); - assert.ok(doc); - done(); - }); - }); - it('but not if distinct arg was not declared', function() { - assert.throws(function() { - mquery(col).distinct({ name: 'mquery distinct' }, function() {}); - }, /No value for `distinct`/); - }); - }); - describe('when Query is passed with a callback', function() { - var m = mquery({ name: 'mquery distinct' }); - it('if distinct arg was declared', function(done) { - mquery(col).distinct('age').distinct(m, function(err, doc) { - assert.ifError(err); - assert.ok(doc); - done(); - }); - }); - it('but not if distinct arg was not declared', function() { - assert.throws(function() { - mquery(col).distinct(m, function() {}); - }, /No value for `distinct`/); - }); - }); - describe('when just a callback is passed', function() { - it('if distinct arg was declared', function(done) { - var m = mquery({ name: 'mquery distinct' }); - m.collection(col); - m.distinct('age'); - m.distinct(function(err, doc) { - assert.ifError(err); - assert.ok(doc); - done(); - }); - }); - it('but not if no distinct arg was declared', function() { - var m = mquery(); - m.collection(col); - assert.throws(function() { - m.distinct(function() {}); - }, /No value for `distinct`/); - }); - }); - }); - - describe('validates its option', function() { - it('sort', function(done) { - assert.throws(function() { - mquery().sort('x').distinct(); - }, /sort cannot be used with distinct/); - done(); - }); - - it('select', function(done) { - assert.throws(function() { - mquery().select('x').distinct(); - }, /field selection and slice cannot be used with distinct/); - done(); - }); - - it('slice', function(done) { - assert.throws(function() { - mquery().where('x').slice(-3).distinct(); - }, /field selection and slice cannot be used with distinct/); - done(); - }); - - it('limit', function(done) { - assert.throws(function() { - mquery().limit(3).distinct(); - }, /limit cannot be used with distinct/); - done(); - }); - - it('skip', function(done) { - assert.throws(function() { - mquery().skip(3).distinct(); - }, /skip cannot be used with distinct/); - done(); - }); - - it('batchSize', function(done) { - assert.throws(function() { - mquery({}, { batchSize: 3 }).distinct(); - }, /batchSize cannot be used with distinct/); - done(); - }); - - it('comment', function(done) { - assert.throws(function() { - mquery().comment('mquery').distinct(); - }, /comment cannot be used with distinct/); - done(); - }); - - it('maxScan', function(done) { - assert.throws(function() { - mquery().maxScan(300).distinct(); - }, /maxScan cannot be used with distinct/); - done(); - }); - - it('snapshot', function(done) { - assert.throws(function() { - mquery().snapshot().distinct(); - }, /snapshot cannot be used with distinct/); - done(); - }); - - it('hint', function(done) { - assert.throws(function() { - mquery().hint({ x: 1 }).distinct(); - }, /hint cannot be used with distinct/); - done(); - }); - - it('tailable', function(done) { - assert.throws(function() { - mquery().tailable().distinct(); - }, /tailable cannot be used with distinct/); - done(); - }); - }); - }); - - describe('update', function() { - describe('with no callback', function() { - it('does not execute', function() { - var m = mquery(); - assert.doesNotThrow(function() { - m.update({ name: 'old' }, { name: 'updated' }, { multi: true }); - }); - assert.doesNotThrow(function() { - m.update({ name: 'old' }, { name: 'updated' }); - }); - assert.doesNotThrow(function() { - m.update({ name: 'updated' }); - }); - assert.doesNotThrow(function() { - m.update(); - }); - }); - }); - - it('is chainable', function() { - var m = mquery({x:1}).update({ y: 2 }); - var n = m.where({y:2}); - assert.equal(m, n); - assert.deepEqual(n._conditions, {x:1, y:2}); - assert.deepEqual({ y: 2 }, n._update); - assert.equal('update', n.op); - }); - - it('merges update doc arg', function() { - var a = [1,2]; - var m = mquery().where({ name: 'mquery' }).update({ x: 'stuff', a: a }); - m.update({ z: 'stuff' }); - assert.deepEqual(m._update, { z: 'stuff', x: 'stuff', a: a }); - assert.deepEqual(m._conditions, { name: 'mquery' }); - assert.ok(!m.options.overwrite); - m.update({}, { z: 'renamed' }, { overwrite: true }); - assert.ok(m.options.overwrite === true); - assert.deepEqual(m._conditions, { name: 'mquery' }); - assert.deepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); - a.push(3); - assert.notDeepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); - }); - - it('merges other options', function() { - var m = mquery(); - m.setOptions({ overwrite: true }); - m.update({ age: 77 }, { name: 'pagemill' }, { multi: true }); - assert.deepEqual({ age: 77 }, m._conditions); - assert.deepEqual({ name: 'pagemill' }, m._update); - assert.deepEqual({ overwrite: true, multi: true }, m.options); - }); - - describe('executes', function() { - var id; - before(function(done) { - col.insert({ name: 'mquery update', age: 1 }, { safe: true }, function(err, res) { - id = res.insertedIds[0]; - done(); - }); - }); - - after(function(done) { - col.remove({ _id: id }, done); - }); - - describe('when conds + doc + opts + callback passed', function() { - it('works', function(done) { - var m = mquery(col).where({ _id: id }); - m.update({}, { name: 'Sparky' }, { safe: true }, function(err, res) { - assert.ifError(err); - assert.equal(res.result.n, 1); - m.findOne(function(err, doc) { - assert.ifError(err); - assert.equal(doc.name, 'Sparky'); - done(); - }); - }); - }); - }); - - describe('when conds + doc + callback passed', function() { - it('works', function(done) { - var m = mquery(col).update({ _id: id }, { name: 'fairgrounds' }, function(err, num) { - assert.ifError(err); - assert.ok(1, num); - m.findOne(function(err, doc) { - assert.ifError(err); - assert.equal(doc.name, 'fairgrounds'); - done(); - }); - }); - }); - }); - - describe('when doc + callback passed', function() { - it('works', function(done) { - var m = mquery(col).where({ _id: id }).update({ name: 'changed' }, function(err, num) { - assert.ifError(err); - assert.ok(1, num); - m.findOne(function(err, doc) { - assert.ifError(err); - assert.equal(doc.name, 'changed'); - done(); - }); - }); - }); - }); - - describe('when just callback passed', function() { - it('works', function(done) { - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true }); - m.update({ name: 'Frankenweenie' }); - m.update(function(err, res) { - assert.ifError(err); - assert.equal(res.result.n, 1); - m.findOne(function(err, doc) { - assert.ifError(err); - assert.equal(doc.name, 'Frankenweenie'); - done(); - }); - }); - }); - }); - - describe('without a callback', function() { - it('when forced by exec()', function(done) { - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true, multi: true }); - m.update({ name: 'forced' }); - - var update = m._collection.update; - m._collection.update = function(conds, doc, opts) { - m._collection.update = update; - - assert.ok(opts.safe); - assert.ok(true === opts.multi); - assert.equal('forced', doc.$set.name); - done(); - }; - - m.exec(); - }); - }); - - describe('except when update doc is empty and missing overwrite flag', function() { - it('works', function(done) { - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true }); - m.update({ }, function(err, num) { - assert.ifError(err); - assert.ok(0 === num); - setTimeout(function() { - m.findOne(function(err, doc) { - assert.ifError(err); - assert.equal(3, mquery.utils.keys(doc).length); - assert.equal(id, doc._id.toString()); - assert.equal('Frankenweenie', doc.name); - done(); - }); - }, 300); - }); - }); - }); - - describe('when update doc is set with overwrite flag', function() { - it('works', function(done) { - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true, overwrite: true }); - m.update({ all: 'yep', two: 2 }, function(err, res) { - assert.ifError(err); - assert.equal(res.result.n, 1); - m.findOne(function(err, doc) { - assert.ifError(err); - assert.equal(3, mquery.utils.keys(doc).length); - assert.equal('yep', doc.all); - assert.equal(2, doc.two); - assert.equal(id, doc._id.toString()); - done(); - }); - }); - }); - }); - - describe('when update doc is empty with overwrite flag', function() { - it('works', function(done) { - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true, overwrite: true }); - m.update({ }, function(err, res) { - assert.ifError(err); - assert.equal(res.result.n, 1); - m.findOne(function(err, doc) { - assert.ifError(err); - assert.equal(1, mquery.utils.keys(doc).length); - assert.equal(id, doc._id.toString()); - done(); - }); - }); - }); - }); - - describe('when boolean (true) - exec()', function() { - it('works', function(done) { - var m = mquery(col).where({ _id: id }); - m.update({ name: 'bool' }).update(true); - setTimeout(function() { - m.findOne(function(err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal('bool', doc.name); - done(); - }); - }, 300); - }); - }); - }); - }); - - describe('remove', function() { - describe('with 0 args', function() { - var name = 'remove: no args test'; - before(function(done) { - col.insert({ name: name }, { safe: true }, done); - }); - after(function(done) { - col.remove({ name: name }, { safe: true }, done); - }); - - it('does not execute', function(done) { - var remove = col.remove; - col.remove = function() { - col.remove = remove; - done(new Error('remove executed!')); - }; - - mquery(col).where({ name: name }).remove(); - setTimeout(function() { - col.remove = remove; - done(); - }, 10); - }); - - it('chains', function() { - var m = mquery(); - assert.equal(m, m.remove()); - }); - }); - - describe('with 1 argument', function() { - var name = 'remove: 1 arg test'; - before(function(done) { - col.insert({ name: name }, { safe: true }, done); - }); - after(function(done) { - col.remove({ name: name }, { safe: true }, done); - }); - - describe('that is a', function() { - it('plain object', function() { - var m = mquery(col).remove({ name: 'Whiskers' }); - m.remove({ color: '#fff' }); - assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); - }); - - it('query', function() { - var q = mquery({ color: '#fff' }); - var m = mquery(col).remove({ name: 'Whiskers' }); - m.remove(q); - assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); - }); - - it('function', function(done) { - mquery(col, { safe: true }).where({name: name}).remove(function(err) { - assert.ifError(err); - mquery(col).findOne({ name: name }, function(err, doc) { - assert.ifError(err); - assert.equal(null, doc); - done(); - }); - }); - }); - - it('boolean (true) - execute', function(done) { - col.insert({ name: name }, { safe: true }, function(err) { - assert.ifError(err); - mquery(col).findOne({ name: name }, function(err, doc) { - assert.ifError(err); - assert.ok(doc); - mquery(col).remove(true); - setTimeout(function() { - mquery(col).find(function(err, docs) { - assert.ifError(err); - assert.ok(docs); - assert.equal(0, docs.length); - done(); - }); - }, 300); - }); - }); - }); - }); - }); - - describe('with 2 arguments', function() { - var name = 'remove: 2 arg test'; - beforeEach(function(done) { - col.remove({}, { safe: true }, function(err) { - assert.ifError(err); - col.insert([{ name: 'shelly' }, { name: name }], { safe: true }, function(err) { - assert.ifError(err); - mquery(col).find(function(err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }); - }); - }); - }); - - describe('plain object + callback', function() { - it('works', function(done) { - mquery(col).remove({ name: name }, function(err) { - assert.ifError(err); - mquery(col).find(function(err, docs) { - assert.ifError(err); - assert.ok(docs); - assert.equal(1, docs.length); - assert.equal('shelly', docs[0].name); - done(); - }); - }); - }); - }); - - describe('mquery + callback', function() { - it('works', function(done) { - var m = mquery({ name: name }); - mquery(col).remove(m, function(err) { - assert.ifError(err); - mquery(col).find(function(err, docs) { - assert.ifError(err); - assert.ok(docs); - assert.equal(1, docs.length); - assert.equal('shelly', docs[0].name); - done(); - }); - }); - }); - }); - }); - }); - - function validateFindAndModifyOptions(method) { - describe('validates its option', function() { - it('sort', function(done) { - assert.doesNotThrow(function() { - mquery().sort('x')[method](); - }); - done(); - }); - - it('select', function(done) { - assert.doesNotThrow(function() { - mquery().select('x')[method](); - }); - done(); - }); - - it('limit', function(done) { - assert.throws(function() { - mquery().limit(3)[method](); - }, new RegExp('limit cannot be used with ' + method)); - done(); - }); - - it('skip', function(done) { - assert.throws(function() { - mquery().skip(3)[method](); - }, new RegExp('skip cannot be used with ' + method)); - done(); - }); - - it('batchSize', function(done) { - assert.throws(function() { - mquery({}, { batchSize: 3 })[method](); - }, new RegExp('batchSize cannot be used with ' + method)); - done(); - }); - - it('maxScan', function(done) { - assert.throws(function() { - mquery().maxScan(300)[method](); - }, new RegExp('maxScan cannot be used with ' + method)); - done(); - }); - - it('snapshot', function(done) { - assert.throws(function() { - mquery().snapshot()[method](); - }, new RegExp('snapshot cannot be used with ' + method)); - done(); - }); - - it('hint', function(done) { - assert.throws(function() { - mquery().hint({ x: 1 })[method](); - }, new RegExp('hint cannot be used with ' + method)); - done(); - }); - - it('tailable', function(done) { - assert.throws(function() { - mquery().tailable()[method](); - }, new RegExp('tailable cannot be used with ' + method)); - done(); - }); - - it('comment', function(done) { - assert.throws(function() { - mquery().comment('mquery')[method](); - }, new RegExp('comment cannot be used with ' + method)); - done(); - }); - }); - } - - describe('findOneAndUpdate', function() { - var name = 'findOneAndUpdate + fn'; - - validateFindAndModifyOptions('findOneAndUpdate'); - - describe('with 0 args', function() { - it('makes no changes', function() { - var m = mquery(); - var n = m.findOneAndUpdate(); - assert.deepEqual(m, n); - }); - }); - describe('with 1 arg', function() { - describe('that is an object', function() { - it('updates the doc', function() { - var m = mquery(); - var n = m.findOneAndUpdate({ $set: { name: '1 arg' }}); - assert.deepEqual(n._update, { $set: { name: '1 arg' }}); - }); - }); - describe('that is a query', function() { - it('updates the doc', function() { - var m = mquery({ name: name }).update({ x: 1 }); - var n = mquery().findOneAndUpdate(m); - assert.deepEqual(n._update, { x: 1 }); - }); - }); - it('that is a function', function(done) { - col.insert({ name: name }, { safe: true }, function(err) { - assert.ifError(err); - var m = mquery({ name: name }).collection(col); - name = '1 arg'; - var n = m.update({ $set: { name: name }}); - n.findOneAndUpdate(function(err, res) { - assert.ifError(err); - assert.ok(res.value); - assert.equal(name, res.value.name); - done(); - }); - }); - }); - }); - describe('with 2 args', function() { - it('conditions + update', function() { - var m = mquery(col); - m.findOneAndUpdate({ name: name }, { age: 100 }); - assert.deepEqual({ name: name }, m._conditions); - assert.deepEqual({ age: 100 }, m._update); - }); - it('query + update', function() { - var n = mquery({ name: name }); - var m = mquery(col); - m.findOneAndUpdate(n, { age: 100 }); - assert.deepEqual({ name: name }, m._conditions); - assert.deepEqual({ age: 100 }, m._update); - }); - it('update + callback', function(done) { - var m = mquery(col).where({ name: name }); - m.findOneAndUpdate({}, { $inc: { age: 10 }}, { new: true }, function(err, res) { - assert.ifError(err); - assert.equal(10, res.value.age); - done(); - }); - }); - }); - describe('with 3 args', function() { - it('conditions + update + options', function() { - var m = mquery(); - var n = m.findOneAndUpdate({ name: name }, { works: true }, { new: false }); - assert.deepEqual({ name: name}, n._conditions); - assert.deepEqual({ works: true }, n._update); - assert.deepEqual({ new: false }, n.options); - }); - it('conditions + update + callback', function(done) { - var m = mquery(col); - m.findOneAndUpdate({ name: name }, { works: true }, { new: true }, function(err, res) { - assert.ifError(err); - assert.ok(res.value); - assert.equal(name, res.value.name); - assert.ok(true === res.value.works); - done(); - }); - }); - }); - describe('with 4 args', function() { - it('conditions + update + options + callback', function(done) { - var m = mquery(col); - m.findOneAndUpdate({ name: name }, { works: false }, { new: false }, function(err, res) { - assert.ifError(err); - assert.ok(res.value); - assert.equal(name, res.value.name); - assert.ok(true === res.value.works); - done(); - }); - }); - }); - }); - - describe('findOneAndRemove', function() { - var name = 'findOneAndRemove'; - - validateFindAndModifyOptions('findOneAndRemove'); - - describe('with 0 args', function() { - it('makes no changes', function() { - var m = mquery(); - var n = m.findOneAndRemove(); - assert.deepEqual(m, n); - }); - }); - describe('with 1 arg', function() { - describe('that is an object', function() { - it('updates the doc', function() { - var m = mquery(); - var n = m.findOneAndRemove({ name: '1 arg' }); - assert.deepEqual(n._conditions, { name: '1 arg' }); - }); - }); - describe('that is a query', function() { - it('updates the doc', function() { - var m = mquery({ name: name }); - var n = m.findOneAndRemove(m); - assert.deepEqual(n._conditions, { name: name }); - }); - }); - it('that is a function', function(done) { - col.insert({ name: name }, { safe: true }, function(err) { - assert.ifError(err); - var m = mquery({ name: name }).collection(col); - m.findOneAndRemove(function(err, res) { - assert.ifError(err); - assert.ok(res.value); - assert.equal(name, res.value.name); - done(); - }); - }); - }); - }); - describe('with 2 args', function() { - it('conditions + options', function() { - var m = mquery(col); - m.findOneAndRemove({ name: name }, { new: false }); - assert.deepEqual({ name: name }, m._conditions); - assert.deepEqual({ new: false }, m.options); - }); - it('query + options', function() { - var n = mquery({ name: name }); - var m = mquery(col); - m.findOneAndRemove(n, { sort: { x: 1 }}); - assert.deepEqual({ name: name }, m._conditions); - assert.deepEqual({ sort: { 'x': 1 }}, m.options); - }); - it('conditions + callback', function(done) { - col.insert({ name: name }, { safe: true }, function(err) { - assert.ifError(err); - var m = mquery(col); - m.findOneAndRemove({ name: name }, function(err, res) { - assert.ifError(err); - assert.equal(name, res.value.name); - done(); - }); - }); - }); - it('query + callback', function(done) { - col.insert({ name: name }, { safe: true }, function(err) { - assert.ifError(err); - var n = mquery({ name: name }); - var m = mquery(col); - m.findOneAndRemove(n, function(err, res) { - assert.ifError(err); - assert.equal(name, res.value.name); - done(); - }); - }); - }); - }); - describe('with 3 args', function() { - it('conditions + options + callback', function(done) { - name = 'findOneAndRemove + conds + options + cb'; - col.insert([{ name: name }, { name: 'a' }], { safe: true }, function(err) { - assert.ifError(err); - var m = mquery(col); - m.findOneAndRemove({ name: name }, { sort: { name: 1 }}, function(err, res) { - assert.ifError(err); - assert.ok(res.value); - assert.equal(name, res.value.name); - done(); - }); - }); - }); - }); - }); - - describe('exec', function() { - beforeEach(function(done) { - col.insert([{ name: 'exec', age: 1 }, { name: 'exec', age: 2 }], done); - }); - - afterEach(function(done) { - mquery(col).remove(done); - }); - - it('requires an op', function() { - assert.throws(function() { - mquery().exec(); - }, /Missing query type/); - }); - - describe('find', function() { - it('works', function(done) { - var m = mquery(col).find({ name: 'exec' }); - m.exec(function(err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }); - }); - - it('works with readPreferences', function(done) { - var m = mquery(col).find({ name: 'exec' }); - try { - var rp = new require('mongodb').ReadPreference('primary'); - m.read(rp); - } catch (e) { - done(e.code === 'MODULE_NOT_FOUND' ? null : e); - return; - } - m.exec(function(err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }); - }); - - it('works with hint', function(done) { - mquery(col).hint({ _id: 1 }).find({ name: 'exec' }).exec(function(err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - - mquery(col).hint('_id_').find({ age: 1 }).exec(function(err, docs) { - assert.ifError(err); - assert.equal(1, docs.length); - done(); - }); - }); - }); - - it('works with readConcern', function(done) { - var m = mquery(col).find({ name: 'exec' }); - m.readConcern('l'); - m.exec(function(err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }); - }); - - it('works with collation', function(done) { - var m = mquery(col).find({ name: 'EXEC' }); - m.collation({ locale: 'en_US', strength: 1 }); - m.exec(function(err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }); - }); - }); - - it('findOne', function(done) { - var m = mquery(col).findOne({ age: 2 }); - m.exec(function(err, doc) { - assert.ifError(err); - assert.equal(2, doc.age); - done(); - }); - }); - - it('count', function(done) { - var m = mquery(col).count({ name: 'exec' }); - m.exec(function(err, count) { - assert.ifError(err); - assert.equal(2, count); - done(); - }); - }); - - it('distinct', function(done) { - var m = mquery({ name: 'exec' }); - m.collection(col); - m.distinct('age'); - m.exec(function(err, array) { - assert.ifError(err); - assert.ok(Array.isArray(array)); - assert.equal(2, array.length); - assert(~array.indexOf(1)); - assert(~array.indexOf(2)); - done(); - }); - }); - - describe('update', function() { - var num; - - it('with a callback', function(done) { - var m = mquery(col); - m.where({ name: 'exec' }); - - m.count(function(err, _num) { - assert.ifError(err); - num = _num; - m.setOptions({ multi: true }); - m.update({ name: 'exec + update' }); - m.exec(function(err, res) { - assert.ifError(err); - assert.equal(num, res.result.n); - mquery(col).find({ name: 'exec + update' }, function(err, docs) { - assert.ifError(err); - assert.equal(num, docs.length); - done(); - }); - }); - }); - }); - - describe('updateMany', function() { - it('works', function(done) { - mquery(col).updateMany({ name: 'exec' }, { name: 'test' }). - exec(function(error) { - assert.ifError(error); - mquery(col).count({ name: 'test' }).exec(function(error, res) { - assert.ifError(error); - assert.equal(res, 2); - done(); - }); - }); - }); - it('works with write concern', function(done) { - mquery(col).updateMany({ name: 'exec' }, { name: 'test' }) - .w(1).j(true).wtimeout(1000) - .exec(function(error) { - assert.ifError(error); - mquery(col).count({ name: 'test' }).exec(function(error, res) { - assert.ifError(error); - assert.equal(res, 2); - done(); - }); - }); - }); - }); - - describe('updateOne', function() { - it('works', function(done) { - mquery(col).updateOne({ name: 'exec' }, { name: 'test' }). - exec(function(error) { - assert.ifError(error); - mquery(col).count({ name: 'test' }).exec(function(error, res) { - assert.ifError(error); - assert.equal(res, 1); - done(); - }); - }); - }); - }); - - describe('replaceOne', function() { - it('works', function(done) { - mquery(col).replaceOne({ name: 'exec' }, { name: 'test' }). - exec(function(error) { - assert.ifError(error); - mquery(col).findOne({ name: 'test' }).exec(function(error, res) { - assert.ifError(error); - assert.equal(res.name, 'test'); - assert.ok(res.age == null); - done(); - }); - }); - }); - }); - - it('without a callback', function(done) { - var m = mquery(col); - m.where({ name: 'exec + update' }).setOptions({ multi: true }); - m.update({ name: 'exec' }); - - // unsafe write - m.exec(); - - setTimeout(function() { - mquery(col).find({ name: 'exec' }, function(err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }); - }, 200); - }); - it('preserves key ordering', function(done) { - var m = mquery(col); - - var m2 = m.update({ _id : 'something' }, { '1' : 1, '2' : 2, '3' : 3}); - var doc = m2._updateForExec().$set; - var count = 0; - for (var i in doc) { - if (count == 0) { - assert.equal('1', i); - } else if (count == 1) { - assert.equal('2', i); - } else if (count == 2) { - assert.equal('3', i); - } - count++; - } - done(); - }); - }); - - describe('remove', function() { - it('with a callback', function(done) { - var m = mquery(col).where({ age: 2 }).remove(); - m.exec(function(err, res) { - assert.ifError(err); - assert.equal(1, res.result.n); - done(); - }); - }); - - it('without a callback', function(done) { - var m = mquery(col).where({ age: 1 }).remove(); - m.exec(); - - setTimeout(function() { - mquery(col).where('name', 'exec').count(function(err, num) { - assert.equal(1, num); - done(); - }); - }, 200); - }); - }); - - describe('deleteOne', function() { - it('with a callback', function(done) { - var m = mquery(col).where({ age: { $gte: 0 } }).deleteOne(); - m.exec(function(err, res) { - assert.ifError(err); - assert.equal(res.result.n, 1); - done(); - }); - }); - - it('with justOne set', function(done) { - var m = mquery(col).where({ age: { $gte: 0 } }). - // Should ignore `justOne` - setOptions({ justOne: false }). - deleteOne(); - m.exec(function(err, res) { - assert.ifError(err); - assert.equal(res.result.n, 1); - done(); - }); - }); - }); - - describe('deleteMany', function() { - it('with a callback', function(done) { - var m = mquery(col).where({ age: { $gte: 0 } }).deleteMany(); - m.exec(function(err, res) { - assert.ifError(err); - assert.equal(res.result.n, 2); - done(); - }); - }); - }); - - describe('findOneAndUpdate', function() { - it('with a callback', function(done) { - var m = mquery(col); - m.findOneAndUpdate({ name: 'exec', age: 1 }, { $set: { name: 'findOneAndUpdate' }}); - m.exec(function(err, res) { - assert.ifError(err); - assert.equal('findOneAndUpdate', res.value.name); - done(); - }); - }); - }); - - describe('findOneAndRemove', function() { - it('with a callback', function(done) { - var m = mquery(col); - m.findOneAndRemove({ name: 'exec', age: 2 }); - m.exec(function(err, res) { - assert.ifError(err); - assert.equal('exec', res.value.name); - assert.equal(2, res.value.age); - mquery(col).count({ name: 'exec' }, function(err, num) { - assert.ifError(err); - assert.equal(1, num); - done(); - }); - }); - }); - }); - }); - - describe('setTraceFunction', function() { - beforeEach(function(done) { - col.insert([{ name: 'trace', age: 93 }], done); - }); - - it('calls trace function when executing query', function(done) { - var m = mquery(col); - - var resultTraceCalled; - - m.setTraceFunction(function(method, queryInfo) { - try { - assert.equal('findOne', method); - assert.equal('trace', queryInfo.conditions.name); - } catch (e) { - done(e); - } - - return function(err, result, millis) { - try { - assert.equal(93, result.age); - assert.ok(typeof millis === 'number'); - } catch (e) { - done(e); - } - resultTraceCalled = true; - }; - }); - - m.findOne({name: 'trace'}, function(err, doc) { - assert.ifError(err); - assert.equal(resultTraceCalled, true); - assert.equal(93, doc.age); - done(); - }); - }); - - it('inherits trace function when calling toConstructor', function(done) { - function traceFunction() { return function() {}; } - - var tracedQuery = mquery().setTraceFunction(traceFunction).toConstructor(); - - var query = tracedQuery(); - assert.equal(traceFunction, query._traceFunction); - - done(); - }); - }); - - describe('thunk', function() { - it('returns a function', function(done) { - assert.equal('function', typeof mquery().thunk()); - done(); - }); - - it('passes the fn arg to `exec`', function(done) { - function cb() {} - var m = mquery(); - - m.exec = function testing(fn) { - assert.equal(this, m); - assert.equal(cb, fn); - done(); - }; - - m.thunk()(cb); - }); - }); - - describe('then', function() { - before(function(done) { - col.insert([{ name: 'then', age: 1 }, { name: 'then', age: 2 }], done); - }); - - after(function(done) { - mquery(col).remove({ name: 'then' }).exec(done); - }); - - it('returns a promise A+ compat object', function(done) { - var m = mquery(col).find(); - assert.equal('function', typeof m.then); - done(); - }); - - it('creates a promise that is resolved on success', function(done) { - var promise = mquery(col).count({ name: 'then' }).then(); - promise.then(function(count) { - assert.equal(2, count); - done(); - }, done); - }); - - it('supports exec() cb being called synchronously #66', function(done) { - var query = mquery(col).count({ name: 'then' }); - query.exec = function(cb) { - cb(null, 66); - }; - - query.then(success, done); - function success(count) { - assert.equal(66, count); - done(); - } - }); - - it('supports other Promise libs', function(done) { - var bluebird = mquery.Promise; - - // hack for testing - mquery.Promise = function P() { - mquery.Promise = bluebird; - this.then = function(x, y) { - return x + y; - }; - }; - - var val = mquery(col).count({ name: 'exec' }).then(1, 2); - assert.equal(val, 3); - done(); - }); - }); - - describe('stream', function() { - before(function(done) { - col.insert([{ name: 'stream', age: 1 }, { name: 'stream', age: 2 }], done); - }); - - after(function(done) { - mquery(col).remove({ name: 'stream' }).exec(done); - }); - - describe('throws', function() { - describe('if used with non-find operations', function() { - var ops = ['update', 'findOneAndUpdate', 'remove', 'count', 'distinct']; - - ops.forEach(function(op) { - assert.throws(function() { - mquery(col)[op]().stream(); - }); - }); - }); - }); - - it('returns a stream', function(done) { - var stream = mquery(col).find({ name: 'stream' }).stream(); - var count = 0; - var err; - - stream.on('data', function(doc) { - assert.equal('stream', doc.name); - ++count; - }); - - stream.on('error', function(er) { - err = er; - }); - - stream.on('end', function() { - if (err) return done(err); - assert.equal(2, count); - done(); - }); - }); - }); - - function noDistinct(type) { - it('cannot be used with distinct()', function(done) { - assert.throws(function() { - mquery().distinct('name')[type](4); - }, new RegExp(type + ' cannot be used with distinct')); - done(); - }); - } - - function no(method, type) { - it('cannot be used with ' + method + '()', function(done) { - assert.throws(function() { - mquery()[method]()[type](4); - }, new RegExp(type + ' cannot be used with ' + method)); - done(); - }); - } - - // query internal - - describe('_updateForExec', function() { - it('returns a clone of the update object with same key order #19', function(done) { - var update = {}; - update.$push = { n: { $each: [{x:10}], $slice: -1, $sort: {x:1}}}; - - var q = mquery().update({ x: 1 }, update); - - // capture original key order - var order = []; - var key; - for (key in q._update.$push.n) { - order.push(key); - } - - // compare output - var doc = q._updateForExec(); - var i = 0; - for (key in doc.$push.n) { - assert.equal(key, order[i]); - i++; - } - - done(); - }); - }); -}); diff --git a/node_modules/mquery/test/utils.test.js b/node_modules/mquery/test/utils.test.js deleted file mode 100644 index ff95f33..0000000 --- a/node_modules/mquery/test/utils.test.js +++ /dev/null @@ -1,144 +0,0 @@ -'use strict'; - -var Buffer = require('safe-buffer').Buffer; -var utils = require('../lib/utils'); -var assert = require('assert'); -var debug = require('debug'); - -var mongo; -try { - mongo = new require('mongodb'); -} catch (e) { - debug('mongo', 'cannot construct mongodb instance'); -} - -describe('lib/utils', function() { - describe('clone', function() { - it('clones constructors named ObjectId', function(done) { - function ObjectId(id) { - this.id = id; - } - - var o1 = new ObjectId('1234'); - var o2 = utils.clone(o1); - assert.ok(o2 instanceof ObjectId); - - done(); - }); - - it('clones constructors named ObjectID', function(done) { - function ObjectID(id) { - this.id = id; - } - - var o1 = new ObjectID('1234'); - var o2 = utils.clone(o1); - - assert.ok(o2 instanceof ObjectID); - done(); - }); - - it('does not clone constructors named ObjectIdd', function(done) { - function ObjectIdd(id) { - this.id = id; - } - - var o1 = new ObjectIdd('1234'); - var o2 = utils.clone(o1); - assert.ok(!(o2 instanceof ObjectIdd)); - - done(); - }); - - it('optionally clones ObjectId constructors using its clone method', function(done) { - function ObjectID(id) { - this.id = id; - this.cloned = false; - } - - ObjectID.prototype.clone = function() { - var ret = new ObjectID(this.id); - ret.cloned = true; - return ret; - }; - - var id = 1234; - var o1 = new ObjectID(id); - assert.equal(id, o1.id); - assert.equal(false, o1.cloned); - - var o2 = utils.clone(o1); - assert.ok(o2 instanceof ObjectID); - assert.equal(id, o2.id); - assert.ok(o2.cloned); - done(); - }); - - it('clones mongodb.ReadPreferences', function(done) { - if (!mongo) return done(); - - var tags = [ - {dc: 'tag1'} - ]; - var prefs = [ - new mongo.ReadPreference('primary'), - new mongo.ReadPreference(mongo.ReadPreference.PRIMARY_PREFERRED), - new mongo.ReadPreference('secondary', tags) - ]; - - var prefsCloned = utils.clone(prefs); - - for (var i = 0; i < prefsCloned.length; i++) { - assert.notEqual(prefs[i], prefsCloned[i]); - if (prefs[i].tags) { - assert.ok(prefsCloned[i].tags); - assert.notEqual(prefs[i].tags, prefsCloned[i].tags); - assert.notEqual(prefs[i].tags[0], prefsCloned[i].tags[0]); - } else { - assert.equal(prefsCloned[i].tags, null); - } - } - - done(); - }); - - it('clones mongodb.Binary', function(done) { - if (!mongo) return done(); - var buf = Buffer.from('hi'); - var binary = new mongo.Binary(buf, 2); - var clone = utils.clone(binary); - assert.equal(binary.sub_type, clone.sub_type); - assert.equal(String(binary.buffer), String(buf)); - assert.ok(binary !== clone); - done(); - }); - - it('handles objects with no constructor', function(done) { - var name = '335'; - - var o = Object.create(null); - o.name = name; - - var clone; - assert.doesNotThrow(function() { - clone = utils.clone(o); - }); - - assert.equal(name, clone.name); - assert.ok(o != clone); - done(); - }); - - it('handles buffers', function(done) { - var buff = Buffer.alloc(10); - buff.fill(1); - var clone = utils.clone(buff); - - for (var i = 0; i < buff.length; i++) { - assert.equal(buff[i], clone[i]); - } - - done(); - }); - }); -}); diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js deleted file mode 100644 index c4498bc..0000000 --- a/node_modules/ms/index.js +++ /dev/null @@ -1,162 +0,0 @@ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -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' && isFinite(val)) { - 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|weeks?|w|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 'weeks': - case 'week': - case 'w': - return n * w; - 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) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md deleted file mode 100644 index 69b6125..0000000 --- a/node_modules/ms/license.md +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index 77cc990..0000000 --- a/node_modules/ms/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "_from": "ms@2.1.2", - "_id": "ms@2.1.2", - "_inBundle": false, - "_integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "_location": "/ms", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "ms@2.1.2", - "name": "ms", - "escapedName": "ms", - "rawSpec": "2.1.2", - "saveSpec": null, - "fetchSpec": "2.1.2" - }, - "_requiredBy": [ - "/mongoose" - ], - "_resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "_shasum": "d09d1f357b443f493382a8eb3ccd183872ae6009", - "_spec": "ms@2.1.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/mongoose", - "bugs": { - "url": "https://github.com/zeit/ms/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Tiny millisecond conversion utility", - "devDependencies": { - "eslint": "4.12.1", - "expect.js": "0.3.1", - "husky": "0.14.3", - "lint-staged": "5.0.0", - "mocha": "4.0.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.1.2" -} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md deleted file mode 100644 index 9a1996b..0000000 --- a/node_modules/ms/readme.md +++ /dev/null @@ -1,60 +0,0 @@ -# ms - -[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) -[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit) - -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 -ms('-3 days') // -259200000 -ms('-1h') // -3600000 -ms('-200') // -200 -``` - -### Convert from Milliseconds - -```js -ms(60000) // "1m" -ms(2 * 60000) // "2m" -ms(-3 * 60000) // "-3m" -ms(ms('10 hours')) // "10h" -``` - -### Time Format Written-Out - -```js -ms(60000, { long: true }) // "1 minute" -ms(2 * 60000, { long: true }) // "2 minutes" -ms(-3 * 60000, { long: true }) // "-3 minutes" -ms(ms('10 hours'), { long: true }) // "10 hours" -``` - -## Features - -- Works both in [Node.js](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 milliseconds is returned - -## Related Packages - -- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. - -## 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.js will now use your clone of ms! - -As always, you can run the tests using: `npm test` diff --git a/node_modules/nan/CHANGELOG.md b/node_modules/nan/CHANGELOG.md deleted file mode 100644 index 44858c7..0000000 --- a/node_modules/nan/CHANGELOG.md +++ /dev/null @@ -1,533 +0,0 @@ -# NAN ChangeLog - -**Version 2.14.1: current Node 14.0.0, Node 0.12: 0.12.18, Node 0.10: 0.10.48, iojs: 3.3.1** - -### 2.14.1 Apr 21 2020 - - - Bugfix: use GetBackingStore() instead of GetContents() (#888) 2c023bd447661a61071da318b0ff4003c3858d39 - -### 2.14.0 May 16 2019 - - - Feature: Add missing methods to Nan::Maybe (#852) 4e962489fb84a184035b9fa74f245f650249aca6 - -### 2.13.2 Mar 24 2019 - - - Bugfix: remove usage of deprecated `IsNearDeath` (#842) fbaf42252af279c3d867c6b193571f9711c39847 - -### 2.13.1 Mar 14 2019 - - - Bugfix: check V8 version directly instead of inferring from NMV (#840) 12f9df9f393285de8fb4a8cd01478dc4fe3b089d - -### 2.13.0 Mar 13 2019 - - - Feature: add support for node master (#831) 113c0282072e7ff4f9dfc98b432fd894b798c2c - -### 2.12.1 Dec 18 2018 - - - Bugfix: Fix build breakage with Node.js 10.0.0-10.9.0. (#833) 625e90e8fef8d39ffa7247250a76a100b2487474 - -### 2.12.0 Dec 16 2018 - - - Bugfix: Add scope.Escape() to Call() (#817) 2e5ed4fc3a8ac80a6ef1f2a55099ab3ac8800dc6 - - Bugfix: Fix Node.js v10.12.0 deprecation warnings. 509859cc23b1770376b56550a027840a2ce0f73d - - Feature: Allow SetWeak() for non-object persistent handles. (#824) e6ef6a48e7e671fe3e4b7dddaa8912a3f8262ecd - -### 2.11.1 Sep 29 2018 - - - Fix: adapt to V8 7.0 24a22c3b25eeeec2016c6ec239bdd6169e985447 - -### 2.11.0 Aug 25 2018 - - - Removal: remove `FunctionCallbackInfo::Callee` for nodejs `>= 10` 1a56c0a6efd4fac944cb46c30912a8e023bda7d4 - - Bugfix: Fix `AsyncProgressWorkerBase::WorkProgress` sends invalid data b0c764d1dab11e9f8b37ffb81e2560a4498aad5e - - Feature: Introduce `GetCurrentEventLoop` b4911b0bb1f6d47d860e10ec014d941c51efac5e - - Feature: Add `NAN_MODULE_WORKER_ENABLED` macro as a replacement for `NAN_MODULE` b058fb047d18a58250e66ae831444441c1f2ac7a - -### 2.10.0 Mar 16 2018 - - - Deprecation: Deprecate `MakeCallback` 5e92b19a59e194241d6a658bd6ff7bfbda372950 - - Feature: add `Nan::Call` overload 4482e1242fe124d166fc1a5b2be3c1cc849fe452 - - Feature: add more `Nan::Call` overloads 8584e63e6d04c7d2eb8c4a664e4ef57d70bf672b - - Feature: Fix deprecation warnings for Node 10 1caf258243b0602ed56922bde74f1c91b0cbcb6a - -### 2.9.2 Feb 22 2018 - - - Bugfix: Bandaid for async hooks 212bd2f849be14ef1b02fc85010b053daa24252b - -### 2.9.1 Feb 22 2018 - - - Bugfix: Avoid deprecation warnings in deprecated `Nan::Callback::operator()` 372b14d91289df4604b0f81780709708c45a9aa4 - - Bugfix: Avoid deprecation warnings in `Nan::JSON` 3bc294bce0b7d0a3ee4559926303e5ed4866fda2 - -### 2.9.0 Feb 22 2018 - - - Deprecation: Deprecate legacy `Callback::Call` 6dd5fa690af61ca3523004b433304c581b3ea309 - - Feature: introduce `AsyncResource` class 90c0a179c0d8cb5fd26f1a7d2b1d6231eb402d48o - - Feature: Add context aware `Nan::Callback::Call` functions 7169e09fb088418b6e388222e88b4c13f07ebaee - - Feature: Make `AsyncWorker` context aware 066ba21a6fb9e2b5230c9ed3a6fc51f1211736a4 - - Feature: add `Callback` overload to `Nan::Call` 5328daf66e202658c1dc0d916c3aaba99b3cc606 - - Bugfix: fix warning: suggest parentheses around `&&` within `||` b2bb63d68b8ae623a526b542764e1ac82319cb2c - - Bugfix: Fix compilation on io.js 3 d06114dba0a522fb436f0c5f47b994210968cd7b - -### 2.8.0 Nov 15 2017 - - - Deprecation: Deprecate `Nan::ForceSet` in favor of `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7 - - Feature: Add `Nan::AsyncProgressQueueWorker` a976636ecc2ef617d1b061ce4a6edf39923691cb - - Feature: Add `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7 - - Bugfix: Fix compiling on io.js 1 & 2 82705a64503ce60c62e98df5bd02972bba090900 - - Bugfix: Use DefineOwnProperty instead of ForceSet 95cbb976d6fbbba88ba0f86dd188223a8591b4e7 - -### 2.7.0 Aug 30 2017 - - - Feature: Add `Nan::To()` overload. b93280670c9f6da42ed4cf6cbf085ffdd87bd65b - - Bugfix: Fix ternary in `Nan::MaybeLocal::FromMaybe()`. 79a26f7d362e756a9524e672a82c3d603b542867 - -### 2.6.2 Apr 12 2017 - - - Bugfix: Fix v8::JSON::Parse() deprecation warning. 87f6a3c65815fa062296a994cc863e2fa124867d - -### 2.6.1 Apr 6 2017 - - - Bugfix: nan_json.h: fix build breakage in Node 6 ac8d47dc3c10bfbf3f15a6b951633120c0ee6d51 - -### 2.6.0 Apr 6 2017 - - - Feature: nan: add support for JSON::Parse & Stringify b533226c629cce70e1932a873bb6f849044a56c5 - -### 2.5.1 Jan 23 2017 - - - Bugfix: Fix disappearing handle for private value 6a80995694f162ef63dbc9948fbefd45d4485aa0 - - Bugfix: Add missing scopes a93b8bae6bc7d32a170db6e89228b7f60ee57112 - - Bugfix: Use string::data instead of string::front in NewOneByteString d5f920371e67e1f3b268295daee6e83af86b6e50 - -### 2.5.0 Dec 21 2016 - - - Feature: Support Private accessors a86255cb357e8ad8ccbf1f6a4a901c921e39a178 - - Bugfix: Abort in delete operators that shouldn't be called 0fe38215ff8581703967dfd26c12793feb960018 - -### 2.4.0 Jul 10 2016 - - - Feature: Rewrite Callback to add Callback::Reset c4cf44d61f8275cd5f7b0c911d7a806d4004f649 - - Feature: AsyncProgressWorker: add template types for .send 1242c9a11a7ed481c8f08ec06316385cacc513d0 - - Bugfix: Add constness to old Persistent comparison operators bd43cb9982c7639605d60fd073efe8cae165d9b2 - -### 2.3.5 May 31 2016 - - - Bugfix: Replace NAN_INLINE with 'inline' keyword. 71819d8725f822990f439479c9aba3b240804909 - -### 2.3.4 May 31 2016 - - - Bugfix: Remove V8 deprecation warnings 0592fb0a47f3a1c7763087ebea8e1138829f24f9 - - Bugfix: Fix new versions not to use WeakCallbackInfo::IsFirstPass 615c19d9e03d4be2049c10db0151edbc3b229246 - - Bugfix: Make ObjectWrap::handle() const d19af99595587fe7a26bd850af6595c2a7145afc - - Bugfix: Fix compilation errors related to 0592fb0a47f3a1c7763087ebea8e1138829f24f9 e9191c525b94f652718325e28610a1adcf90fed8 - -### 2.3.3 May 4 2016 - - - Bugfix: Refactor SetMethod() to deal with v8::Templates (#566) b9083cf6d5de6ebe6bcb49c7502fbb7c0d9ddda8 - -### 2.3.2 Apr 27 2016 - - - Bugfix: Fix compilation on outdated versions due to Handle removal f8b7c875d04d425a41dfd4f3f8345bc3a11e6c52 - -### 2.3.1 Apr 27 2016 - - - Bugfix: Don't use deprecated v8::Template::Set() in SetMethod a90951e9ea70fa1b3836af4b925322919159100e - -### 2.3.0 Apr 27 2016 - - - Feature: added Signal() for invoking async callbacks without sending data from AsyncProgressWorker d8adba45f20e077d00561b20199133620c990b38 - - Bugfix: Don't use deprecated v8::Template::Set() 00dacf0a4b86027415867fa7f1059acc499dcece - -### 2.2.1 Mar 29 2016 - - - Bugfix: Use NewFromUnsigned in ReturnValue::Set(uint32_t i) for pre_12 3a18f9bdce29826e0e4c217854bc476918241a58 - - Performance: Remove unneeeded nullptr checks b715ef44887931c94f0d1605b3b1a4156eebece9 - -### 2.2.0 Jan 9 2016 - - - Feature: Add Function::Call wrapper 4c157474dacf284d125c324177b45aa5dabc08c6 - - Feature: Rename GC*logueCallback to GCCallback for > 4.0 3603435109f981606d300eb88004ca101283acec - - Bugfix: Fix Global::Pass for old versions 367e82a60fbaa52716232cc89db1cc3f685d77d9 - - Bugfix: Remove weird MaybeLocal wrapping of what already is a MaybeLocal 23b4590db10c2ba66aee2338aebe9751c4cb190b - -### 2.1.0 Oct 8 2015 - - - Deprecation: Deprecate NanErrnoException in favor of ErrnoException 0af1ca4cf8b3f0f65ed31bc63a663ab3319da55c - - Feature: added helper class for accessing contents of typedarrays 17b51294c801e534479d5463697a73462d0ca555 - - Feature: [Maybe types] Add MakeMaybe(...) 48d7b53d9702b0c7a060e69ea10fea8fb48d814d - - Feature: new: allow utf16 string with length 66ac6e65c8ab9394ef588adfc59131b3b9d8347b - - Feature: Introduce SetCallHandler and SetCallAsFunctionHandler 7764a9a115d60ba10dc24d86feb0fbc9b4f75537 - - Bugfix: Enable creating Locals from Globals under Node 0.10. 9bf9b8b190821af889790fdc18ace57257e4f9ff - - Bugfix: Fix issue #462 where PropertyCallbackInfo data is not stored safely. 55f50adedd543098526c7b9f4fffd607d3f9861f - -### 2.0.9 Sep 8 2015 - - - Bugfix: EscapableHandleScope in Nan::NewBuffer for Node 0.8 and 0.10 b1654d7 - -### 2.0.8 Aug 28 2015 - - - Work around duplicate linking bug in clang 11902da - -### 2.0.7 Aug 26 2015 - - - Build: Repackage - -### 2.0.6 Aug 26 2015 - - - Bugfix: Properly handle null callback in FunctionTemplate factory 6e99cb1 - - Bugfix: Remove unused static std::map instances 525bddc - - Bugfix: Make better use of maybe versions of APIs bfba85b - - Bugfix: Fix shadowing issues with handle in ObjectWrap 0a9072d - -### 2.0.5 Aug 10 2015 - - - Bugfix: Reimplement weak callback in ObjectWrap 98d38c1 - - Bugfix: Make sure callback classes are not assignable, copyable or movable 81f9b1d - -### 2.0.4 Aug 6 2015 - - - Build: Repackage - -### 2.0.3 Aug 6 2015 - - - Bugfix: Don't use clang++ / g++ syntax extension. 231450e - -### 2.0.2 Aug 6 2015 - - - Build: Repackage - -### 2.0.1 Aug 6 2015 - - - Bugfix: Add workaround for missing REPLACE_INVALID_UTF8 60d6687 - - Bugfix: Reimplement ObjectWrap from scratch to prevent memory leaks 6484601 - - Bugfix: Fix Persistent leak in FunctionCallbackInfo and PropertyCallbackInfo 641ef5f - - Bugfix: Add missing overload for Nan::NewInstance that takes argc/argv 29450ed - -### 2.0.0 Jul 31 2015 - - - Change: Renamed identifiers with leading underscores b5932b4 - - Change: Replaced NanObjectWrapHandle with class NanObjectWrap 464f1e1 - - Change: Replace NanScope and NanEscpableScope macros with classes 47751c4 - - Change: Rename NanNewBufferHandle to NanNewBuffer 6745f99 - - Change: Rename NanBufferUse to NanNewBuffer 3e8b0a5 - - Change: Rename NanNewBuffer to NanCopyBuffer d6af78d - - Change: Remove Nan prefix from all names 72d1f67 - - Change: Update Buffer API for new upstream changes d5d3291 - - Change: Rename Scope and EscapableScope to HandleScope and EscapableHandleScope 21a7a6a - - Change: Get rid of Handles e6c0daf - - Feature: Support io.js 3 with V8 4.4 - - Feature: Introduce NanPersistent 7fed696 - - Feature: Introduce NanGlobal 4408da1 - - Feature: Added NanTryCatch 10f1ca4 - - Feature: Update for V8 v4.3 4b6404a - - Feature: Introduce NanNewOneByteString c543d32 - - Feature: Introduce namespace Nan 67ed1b1 - - Removal: Remove NanLocker and NanUnlocker dd6e401 - - Removal: Remove string converters, except NanUtf8String, which now follows the node implementation b5d00a9 - - Removal: Remove NanReturn* macros d90a25c - - Removal: Remove HasInstance e8f84fe - - -### 1.9.0 Jul 31 2015 - - - Feature: Added `NanFatalException` 81d4a2c - - Feature: Added more error types 4265f06 - - Feature: Added dereference and function call operators to NanCallback c4b2ed0 - - Feature: Added indexed GetFromPersistent and SaveToPersistent edd510c - - Feature: Added more overloads of SaveToPersistent and GetFromPersistent 8b1cef6 - - Feature: Added NanErrnoException dd87d9e - - Correctness: Prevent assign, copy, and move for classes that do not support it 1f55c59, 4b808cb, c96d9b2, fba4a29, 3357130 - - Deprecation: Deprecate `NanGetPointerSafe` and `NanSetPointerSafe` 81d4a2c - - Deprecation: Deprecate `NanBooleanOptionValue` and `NanUInt32OptionValue` 0ad254b - -### 1.8.4 Apr 26 2015 - - - Build: Repackage - -### 1.8.3 Apr 26 2015 - - - Bugfix: Include missing header 1af8648 - -### 1.8.2 Apr 23 2015 - - - Build: Repackage - -### 1.8.1 Apr 23 2015 - - - Bugfix: NanObjectWrapHandle should take a pointer 155f1d3 - -### 1.8.0 Apr 23 2015 - - - Feature: Allow primitives with NanReturnValue 2e4475e - - Feature: Added comparison operators to NanCallback 55b075e - - Feature: Backport thread local storage 15bb7fa - - Removal: Remove support for signatures with arguments 8a2069d - - Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59 - -### 1.7.0 Feb 28 2015 - - - Feature: Made NanCallback::Call accept optional target 8d54da7 - - Feature: Support atom-shell 0.21 0b7f1bb - -### 1.6.2 Feb 6 2015 - - - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639 - -### 1.6.1 Jan 23 2015 - - - Build: version bump - -### 1.5.3 Jan 23 2015 - - - Build: repackage - -### 1.6.0 Jan 23 2015 - - - Deprecated `NanNewContextHandle` in favor of `NanNew` 49259af - - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179 - - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9 - -### 1.5.2 Jan 23 2015 - - - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4 - - Bugfix: Readded missing String constructors 18d828f - - Bugfix: Add overload handling NanNew(..) 5ef813b - - Bugfix: Fix uv_work_cb versioning 997e4ae - - Bugfix: Add function factory and test 4eca89c - - Bugfix: Add object template factory and test cdcb951 - - Correctness: Lifted an io.js related typedef c9490be - - Correctness: Make explicit downcasts of String lengths 00074e6 - - Windows: Limit the scope of disabled warning C4530 83d7deb - -### 1.5.1 Jan 15 2015 - - - Build: version bump - -### 1.4.3 Jan 15 2015 - - - Build: version bump - -### 1.4.2 Jan 15 2015 - - - Feature: Support io.js 0dbc5e8 - -### 1.5.0 Jan 14 2015 - - - Feature: Support io.js b003843 - - Correctness: Improved NanNew internals 9cd4f6a - - Feature: Implement progress to NanAsyncWorker 8d6a160 - -### 1.4.1 Nov 8 2014 - - - Bugfix: Handle DEBUG definition correctly - - Bugfix: Accept int as Boolean - -### 1.4.0 Nov 1 2014 - - - Feature: Added NAN_GC_CALLBACK 6a5c245 - - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8 - - Correctness: Added constness to references in NanHasInstance 02c61cd - - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6 - - Windoze: Shut Visual Studio up when compiling 8d558c1 - - License: Switch to plain MIT from custom hacked MIT license 11de983 - - Build: Added test target to Makefile e232e46 - - Performance: Removed superfluous scope in NanAsyncWorker f4b7821 - - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208 - - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450 - -### 1.3.0 Aug 2 2014 - - - Added NanNew(std::string) - - Added NanNew(std::string&) - - Added NanAsciiString helper class - - Added NanUtf8String helper class - - Added NanUcs2String helper class - - Deprecated NanRawString() - - Deprecated NanCString() - - Added NanGetIsolateData(v8::Isolate *isolate) - - Added NanMakeCallback(v8::Handle target, v8::Handle func, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, v8::Handle symbol, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, const char* method, int argc, v8::Handle* argv) - - Added NanSetTemplate(v8::Handle templ, v8::Handle name , v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetPrototypeTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetInstanceTemplate(v8::Local templ, const char *name, v8::Handle value) - - Added NanSetInstanceTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - -### 1.2.0 Jun 5 2014 - - - Add NanSetPrototypeTemplate - - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, - introduced _NanWeakCallbackDispatcher - - Removed -Wno-unused-local-typedefs from test builds - - Made test builds Windows compatible ('Sleep()') - -### 1.1.2 May 28 2014 - - - Release to fix more stuff-ups in 1.1.1 - -### 1.1.1 May 28 2014 - - - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 - -### 1.1.0 May 25 2014 - - - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead - - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), - (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, - v8::String::ExternalAsciiStringResource* - - Deprecate NanSymbol() - - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker - -### 1.0.0 May 4 2014 - - - Heavy API changes for V8 3.25 / Node 0.11.13 - - Use cpplint.py - - Removed NanInitPersistent - - Removed NanPersistentToLocal - - Removed NanFromV8String - - Removed NanMakeWeak - - Removed NanNewLocal - - Removed NAN_WEAK_CALLBACK_OBJECT - - Removed NAN_WEAK_CALLBACK_DATA - - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions - - Introduce NanUndefined, NanNull, NanTrue and NanFalse - - Introduce NanEscapableScope and NanEscapeScope - - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) - - Introduce NanMakeCallback for node::MakeCallback - - Introduce NanSetTemplate - - Introduce NanGetCurrentContext - - Introduce NanCompileScript and NanRunScript - - Introduce NanAdjustExternalMemory - - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback - - Introduce NanGetHeapStatistics - - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() - -### 0.8.0 Jan 9 2014 - - - NanDispose -> NanDisposePersistent, deprecate NanDispose - - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() - -### 0.7.1 Jan 9 2014 - - - Fixes to work against debug builds of Node - - Safer NanPersistentToLocal (avoid reinterpret_cast) - - Speed up common NanRawString case by only extracting flattened string when necessary - -### 0.7.0 Dec 17 2013 - - - New no-arg form of NanCallback() constructor. - - NanCallback#Call takes Handle rather than Local - - Removed deprecated NanCallback#Run method, use NanCallback#Call instead - - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS - - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() - - Introduce NanRawString() for char* (or appropriate void*) from v8::String - (replacement for NanFromV8String) - - Introduce NanCString() for null-terminated char* from v8::String - -### 0.6.0 Nov 21 2013 - - - Introduce NanNewLocal(v8::Handle value) for use in place of - v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 - -### 0.5.2 Nov 16 2013 - - - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public - -### 0.5.1 Nov 12 2013 - - - Use node::MakeCallback() instead of direct v8::Function::Call() - -### 0.5.0 Nov 11 2013 - - - Added @TooTallNate as collaborator - - New, much simpler, "include_dirs" for binding.gyp - - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros - -### 0.4.4 Nov 2 2013 - - - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ - -### 0.4.3 Nov 2 2013 - - - Include node_object_wrap.h, removed from node.h for Node 0.11.8. - -### 0.4.2 Nov 2 2013 - - - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for - Node 0.11.8 release. - -### 0.4.1 Sep 16 2013 - - - Added explicit `#include ` as it was removed from node.h for v0.11.8 - -### 0.4.0 Sep 2 2013 - - - Added NAN_INLINE and NAN_DEPRECATED and made use of them - - Added NanError, NanTypeError and NanRangeError - - Cleaned up code - -### 0.3.2 Aug 30 2013 - - - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent - in NanAsyncWorker - -### 0.3.1 Aug 20 2013 - - - fix "not all control paths return a value" compile warning on some platforms - -### 0.3.0 Aug 19 2013 - - - Made NAN work with NPM - - Lots of fixes to NanFromV8String, pulling in features from new Node core - - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API - - Added optional error number argument for NanThrowError() - - Added NanInitPersistent() - - Added NanReturnNull() and NanReturnEmptyString() - - Added NanLocker and NanUnlocker - - Added missing scopes - - Made sure to clear disposed Persistent handles - - Changed NanAsyncWorker to allocate error messages on the heap - - Changed NanThrowError(Local) to NanThrowError(Handle) - - Fixed leak in NanAsyncWorker when errmsg is used - -### 0.2.2 Aug 5 2013 - - - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() - -### 0.2.1 Aug 5 2013 - - - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for - NanFromV8String() - -### 0.2.0 Aug 5 2013 - - - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, - NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY - - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, - _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, - _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, - _NAN_PROPERTY_QUERY_ARGS - - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer - - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, - NAN_WEAK_CALLBACK_DATA, NanMakeWeak - - Renamed THROW_ERROR to _NAN_THROW_ERROR - - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) - - Added NanBufferUse(char*, uint32_t) - - Added NanNewContextHandle(v8::ExtensionConfiguration*, - v8::Handle, v8::Handle) - - Fixed broken NanCallback#GetFunction() - - Added optional encoding and size arguments to NanFromV8String() - - Added NanGetPointerSafe() and NanSetPointerSafe() - - Added initial test suite (to be expanded) - - Allow NanUInt32OptionValue to convert any Number object - -### 0.1.0 Jul 21 2013 - - - Added `NAN_GETTER`, `NAN_SETTER` - - Added `NanThrowError` with single Local argument - - Added `NanNewBufferHandle` with single uint32_t argument - - Added `NanHasInstance(Persistent&, Handle)` - - Added `Local NanCallback#GetFunction()` - - Added `NanCallback#Call(int, Local[])` - - Deprecated `NanCallback#Run(int, Local[])` in favour of Call diff --git a/node_modules/nan/LICENSE.md b/node_modules/nan/LICENSE.md deleted file mode 100644 index dddd13d..0000000 --- a/node_modules/nan/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -The MIT License (MIT) -===================== - -Copyright (c) 2018 NAN contributors ------------------------------------ - -*NAN contributors listed at * - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/nan/README.md b/node_modules/nan/README.md deleted file mode 100644 index 9b5f38a..0000000 --- a/node_modules/nan/README.md +++ /dev/null @@ -1,455 +0,0 @@ -Native Abstractions for Node.js -=============================== - -**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10, 0.12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 and 14.** - -***Current version: 2.14.1*** - -*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* - -[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/) - -[![Build Status](https://api.travis-ci.org/nodejs/nan.svg?branch=master)](https://travis-ci.org/nodejs/nan) -[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan) - -Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12 to 4.0, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle. - -This project also contains some helper utilities that make addon development a bit more pleasant. - - * **[News & Updates](#news)** - * **[Usage](#usage)** - * **[Example](#example)** - * **[API](#api)** - * **[Tests](#tests)** - * **[Known issues](#issues)** - * **[Governance & Contributing](#governance)** - - - -## News & Updates - - - -## Usage - -Simply add **NAN** as a dependency in the *package.json* of your Node addon: - -``` bash -$ npm install --save nan -``` - -Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include ` in your *.cpp* files: - -``` python -"include_dirs" : [ - "` when compiling your addon. - - - -## Example - -Just getting started with Nan? Take a look at the **[Node Add-on Examples](https://github.com/nodejs/node-addon-examples)**. - -Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality. - -For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**. - -Yet another example is **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon. - -Also take a look at our comprehensive **[C++ test suite](https://github.com/nodejs/nan/tree/master/test/cpp)** which has a plethora of code snippets for your pasting pleasure. - - - -## API - -Additional to the NAN documentation below, please consult: - -* [The V8 Getting Started * Guide](https://v8.dev/docs/embed) -* [V8 API Documentation](https://v8docs.nodesource.com/) -* [Node Add-on Documentation](https://nodejs.org/api/addons.html) - - - -### JavaScript-accessible methods - -A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information. - -In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. - -* **Method argument types** - - Nan::FunctionCallbackInfo - - Nan::PropertyCallbackInfo - - Nan::ReturnValue -* **Method declarations** - - Method declaration - - Getter declaration - - Setter declaration - - Property getter declaration - - Property setter declaration - - Property enumerator declaration - - Property deleter declaration - - Property query declaration - - Index getter declaration - - Index setter declaration - - Index enumerator declaration - - Index deleter declaration - - Index query declaration -* Method and template helpers - - Nan::SetMethod() - - Nan::SetPrototypeMethod() - - Nan::SetAccessor() - - Nan::SetNamedPropertyHandler() - - Nan::SetIndexedPropertyHandler() - - Nan::SetTemplate() - - Nan::SetPrototypeTemplate() - - Nan::SetInstanceTemplate() - - Nan::SetCallHandler() - - Nan::SetCallAsFunctionHandler() - -### Scopes - -A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. - -A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. - -The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. - - - Nan::HandleScope - - Nan::EscapableHandleScope - -Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection). - -### Persistent references - -An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. - -Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. - - - Nan::PersistentBase & v8::PersistentBase - - Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits - - Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits - - Nan::Persistent - - Nan::Global - - Nan::WeakCallbackInfo - - Nan::WeakCallbackType - -Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). - -### New - -NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. - - - Nan::New() - - Nan::Undefined() - - Nan::Null() - - Nan::True() - - Nan::False() - - Nan::EmptyString() - - -### Converters - -NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. - - - Nan::To() - -### Maybe Types - -The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. - -* **Maybe Types** - - Nan::MaybeLocal - - Nan::Maybe - - Nan::Nothing - - Nan::Just -* **Maybe Helpers** - - Nan::Call() - - Nan::ToDetailString() - - Nan::ToArrayIndex() - - Nan::Equals() - - Nan::NewInstance() - - Nan::GetFunction() - - Nan::Set() - - Nan::DefineOwnProperty() - - Nan::ForceSet() - - Nan::Get() - - Nan::GetPropertyAttributes() - - Nan::Has() - - Nan::Delete() - - Nan::GetPropertyNames() - - Nan::GetOwnPropertyNames() - - Nan::SetPrototype() - - Nan::ObjectProtoToString() - - Nan::HasOwnProperty() - - Nan::HasRealNamedProperty() - - Nan::HasRealIndexedProperty() - - Nan::HasRealNamedCallbackProperty() - - Nan::GetRealNamedPropertyInPrototypeChain() - - Nan::GetRealNamedProperty() - - Nan::CallAsFunction() - - Nan::CallAsConstructor() - - Nan::GetSourceLine() - - Nan::GetLineNumber() - - Nan::GetStartColumn() - - Nan::GetEndColumn() - - Nan::CloneElementAt() - - Nan::HasPrivate() - - Nan::GetPrivate() - - Nan::SetPrivate() - - Nan::DeletePrivate() - - Nan::MakeMaybe() - -### Script - -NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8. - - - Nan::CompileScript() - - Nan::RunScript() - - -### JSON - -The _JSON_ object provides the c++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object. - - - Nan::JSON.Parse - - Nan::JSON.Stringify - -Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments. - -### Errors - -NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. - -Note that an Error object is simply a specialized form of `v8::Value`. - -Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. - - - Nan::Error() - - Nan::RangeError() - - Nan::ReferenceError() - - Nan::SyntaxError() - - Nan::TypeError() - - Nan::ThrowError() - - Nan::ThrowRangeError() - - Nan::ThrowReferenceError() - - Nan::ThrowSyntaxError() - - Nan::ThrowTypeError() - - Nan::FatalException() - - Nan::ErrnoException() - - Nan::TryCatch - - -### Buffers - -NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. - - - Nan::NewBuffer() - - Nan::CopyBuffer() - - Nan::FreeCallback() - -### Nan::Callback - -`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. - - - Nan::Callback - -### Asynchronous work helpers - -`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier. - - - Nan::AsyncWorker - - Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker - - Nan::AsyncProgressQueueWorker - - Nan::AsyncQueueWorker - -### Strings & Bytes - -Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. - - - Nan::Encoding - - Nan::Encode() - - Nan::DecodeBytes() - - Nan::DecodeWrite() - - -### Object Wrappers - -The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects. - - - Nan::ObjectWrap - - -### V8 internals - -The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. - - - NAN_GC_CALLBACK() - - Nan::AddGCEpilogueCallback() - - Nan::RemoveGCEpilogueCallback() - - Nan::AddGCPrologueCallback() - - Nan::RemoveGCPrologueCallback() - - Nan::GetHeapStatistics() - - Nan::SetCounterFunction() - - Nan::SetCreateHistogramFunction() - - Nan::SetAddHistogramSampleFunction() - - Nan::IdleNotification() - - Nan::LowMemoryNotification() - - Nan::ContextDisposedNotification() - - Nan::GetInternalFieldPointer() - - Nan::SetInternalFieldPointer() - - Nan::AdjustExternalMemory() - - -### Miscellaneous V8 Helpers - - - Nan::Utf8String - - Nan::GetCurrentContext() - - Nan::SetIsolateData() - - Nan::GetIsolateData() - - Nan::TypedArrayContents - - -### Miscellaneous Node Helpers - - - Nan::AsyncResource - - Nan::MakeCallback() - - NAN_MODULE_INIT() - - Nan::Export() - - - - - - -### Tests - -To run the NAN tests do: - -``` sh -npm install -npm run-script rebuild-tests -npm test -``` - -Or just: - -``` sh -npm install -make test -``` - - - -## Known issues - -### Compiling against Node.js 0.12 on OSX - -With new enough compilers available on OSX, the versions of V8 headers corresponding to Node.js 0.12 -do not compile anymore. The error looks something like: - -``` -❯ CXX(target) Release/obj.target/accessors/cpp/accessors.o -In file included from ../cpp/accessors.cpp:9: -In file included from ../../nan.h:51: -In file included from /Users/ofrobots/.node-gyp/0.12.18/include/node/node.h:61: -/Users/ofrobots/.node-gyp/0.12.18/include/node/v8.h:5800:54: error: 'CreateHandle' is a protected member of 'v8::HandleScope' - return Handle(reinterpret_cast(HandleScope::CreateHandle( - ~~~~~~~~~~~~~^~~~~~~~~~~~ -``` - -This can be worked around by patching your local versions of v8.h corresponding to Node 0.12 to make -`v8::Handle` a friend of `v8::HandleScope`. Since neither Node.js not V8 support this release line anymore -this patch cannot be released by either project in an official release. - -For this reason, we do not test against Node.js 0.12 on OSX in this project's CI. If you need to support -that configuration, you will need to either get an older compiler, or apply a source patch to the version -of V8 headers as a workaround. - - - -## Governance & Contributing - -NAN is governed by the [Node.js Addon API Working Group](https://github.com/nodejs/CTC/blob/master/WORKING_GROUPS.md#addon-api) - -### Addon API Working Group (WG) - -The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project. - -Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other Node.js projects. - -The WG has final authority over this project including: - -* Technical direction -* Project governance and process (including this policy) -* Contribution policy -* GitHub repository hosting -* Maintaining the list of additional Collaborators - -For the current list of WG members, see the project [README.md](./README.md#collaborators). - -Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote. - -_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly. - -For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators). - -### Consensus Seeking Process - -The WG follows a [Consensus Seeking](https://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. - -Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification. - -If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins. - - - -## Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -* (a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -* (b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -* (c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -* (d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. - - - -### WG Members / Collaborators - - - - - - - - - - -
Rod VaggGitHub/rvaggTwitter/@rvagg
Benjamin ByholmGitHub/kkoopa-
Trevor NorrisGitHub/trevnorrisTwitter/@trevnorris
Nathan RajlichGitHub/TooTallNateTwitter/@TooTallNate
Brett LawsonGitHub/brett19Twitter/@brett19x
Ben NoordhuisGitHub/bnoordhuisTwitter/@bnoordhuis
David SiegelGitHub/agnatTwitter/@agnat
Michael Ira KrufkyGitHub/mkrufkyTwitter/@mkrufky
- -## Licence & copyright - -Copyright (c) 2018 NAN WG Members / Collaborators (listed above). - -Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/node_modules/nan/doc/asyncworker.md b/node_modules/nan/doc/asyncworker.md deleted file mode 100644 index 04231f8..0000000 --- a/node_modules/nan/doc/asyncworker.md +++ /dev/null @@ -1,146 +0,0 @@ -## Asynchronous work helpers - -`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier. - - - Nan::AsyncWorker - - Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker - - Nan::AsyncProgressQueueWorker - - Nan::AsyncQueueWorker - - -### Nan::AsyncWorker - -`Nan::AsyncWorker` is an _abstract_ class that you can subclass to have much of the annoying asynchronous queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the asynchronous work is in progress. - -This class internally handles the details of creating an [`AsyncResource`][AsyncResource], and running the callback in the -correct async context. To be able to identify the async resources created by this class in async-hooks, provide a -`resource_name` to the constructor. It is recommended that the module name be used as a prefix to the `resource_name` to avoid -collisions in the names. For more details see [`AsyncResource`][AsyncResource] documentation. The `resource_name` needs to stay valid for the lifetime of the worker instance. - -Definition: - -```c++ -class AsyncWorker { - public: - explicit AsyncWorker(Callback *callback_, const char* resource_name = "nan:AsyncWorker"); - - virtual ~AsyncWorker(); - - virtual void WorkComplete(); - - void SaveToPersistent(const char *key, const v8::Local &value); - - void SaveToPersistent(const v8::Local &key, - const v8::Local &value); - - void SaveToPersistent(uint32_t index, - const v8::Local &value); - - v8::Local GetFromPersistent(const char *key) const; - - v8::Local GetFromPersistent(const v8::Local &key) const; - - v8::Local GetFromPersistent(uint32_t index) const; - - virtual void Execute() = 0; - - uv_work_t request; - - virtual void Destroy(); - - protected: - Persistent persistentHandle; - - Callback *callback; - - virtual void HandleOKCallback(); - - virtual void HandleErrorCallback(); - - void SetErrorMessage(const char *msg); - - const char* ErrorMessage(); -}; -``` - - -### Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker - -`Nan::AsyncProgressWorkerBase` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript. - -Previously the definition of `Nan::AsyncProgressWorker` only allowed sending `const char` data. Now extending `Nan::AsyncProgressWorker` will yield an instance of the implicit `Nan::AsyncProgressWorkerBase` template with type `` for compatibility. - -`Nan::AsyncProgressWorkerBase` & `Nan::AsyncProgressWorker` is intended for best-effort delivery of nonessential progress messages, e.g. a progress bar. The last event sent before the main thread is woken will be delivered. - -Definition: - -```c++ -template -class AsyncProgressWorkerBase : public AsyncWorker { - public: - explicit AsyncProgressWorkerBase(Callback *callback_, const char* resource_name = ...); - - virtual ~AsyncProgressWorkerBase(); - - void WorkProgress(); - - class ExecutionProgress { - public: - void Signal() const; - void Send(const T* data, size_t count) const; - }; - - virtual void Execute(const ExecutionProgress& progress) = 0; - - virtual void HandleProgressCallback(const T *data, size_t count) = 0; - - virtual void Destroy(); -}; - -typedef AsyncProgressWorkerBase AsyncProgressWorker; -``` - - -### Nan::AsyncProgressQueueWorker - -`Nan::AsyncProgressQueueWorker` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript. - -`Nan::AsyncProgressQueueWorker` behaves exactly the same as `Nan::AsyncProgressWorker`, except all events are queued and delivered to the main thread. - -Definition: - -```c++ -template -class AsyncProgressQueueWorker : public AsyncWorker { - public: - explicit AsyncProgressQueueWorker(Callback *callback_, const char* resource_name = "nan:AsyncProgressQueueWorker"); - - virtual ~AsyncProgressQueueWorker(); - - void WorkProgress(); - - class ExecutionProgress { - public: - void Send(const T* data, size_t count) const; - }; - - virtual void Execute(const ExecutionProgress& progress) = 0; - - virtual void HandleProgressCallback(const T *data, size_t count) = 0; - - virtual void Destroy(); -}; -``` - - -### Nan::AsyncQueueWorker - -`Nan::AsyncQueueWorker` will run a `Nan::AsyncWorker` asynchronously via libuv. Both the `execute` and `after_work` steps are taken care of for you. Most of the logic for this is embedded in `Nan::AsyncWorker`. - -Definition: - -```c++ -void AsyncQueueWorker(AsyncWorker *); -``` - -[AsyncResource]: node_misc.md#api_nan_asyncresource diff --git a/node_modules/nan/doc/buffers.md b/node_modules/nan/doc/buffers.md deleted file mode 100644 index 8d8d25c..0000000 --- a/node_modules/nan/doc/buffers.md +++ /dev/null @@ -1,54 +0,0 @@ -## Buffers - -NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. - - - Nan::NewBuffer() - - Nan::CopyBuffer() - - Nan::FreeCallback() - - -### Nan::NewBuffer() - -Allocate a new `node::Buffer` object with the specified size and optional data. Calls `node::Buffer::New()`. - -Note that when creating a `Buffer` using `Nan::NewBuffer()` and an existing `char*`, it is assumed that the ownership of the pointer is being transferred to the new `Buffer` for management. -When a `node::Buffer` instance is garbage collected and a `FreeCallback` has not been specified, `data` will be disposed of via a call to `free()`. -You _must not_ free the memory space manually once you have created a `Buffer` in this way. - -Signature: - -```c++ -Nan::MaybeLocal Nan::NewBuffer(uint32_t size) -Nan::MaybeLocal Nan::NewBuffer(char* data, uint32_t size) -Nan::MaybeLocal Nan::NewBuffer(char *data, - size_t length, - Nan::FreeCallback callback, - void *hint) -``` - - - -### Nan::CopyBuffer() - -Similar to [`Nan::NewBuffer()`](#api_nan_new_buffer) except that an implicit memcpy will occur within Node. Calls `node::Buffer::Copy()`. - -Management of the `char*` is left to the user, you should manually free the memory space if necessary as the new `Buffer` will have its own copy. - -Signature: - -```c++ -Nan::MaybeLocal Nan::CopyBuffer(const char *data, uint32_t size) -``` - - - -### Nan::FreeCallback() - -A free callback that can be provided to [`Nan::NewBuffer()`](#api_nan_new_buffer). -The supplied callback will be invoked when the `Buffer` undergoes garbage collection. - -Signature: - -```c++ -typedef void (*FreeCallback)(char *data, void *hint); -``` diff --git a/node_modules/nan/doc/callback.md b/node_modules/nan/doc/callback.md deleted file mode 100644 index f7af0bf..0000000 --- a/node_modules/nan/doc/callback.md +++ /dev/null @@ -1,76 +0,0 @@ -## Nan::Callback - -`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. - - - Nan::Callback - - -### Nan::Callback - -```c++ -class Callback { - public: - Callback(); - - explicit Callback(const v8::Local &fn); - - ~Callback(); - - bool operator==(const Callback &other) const; - - bool operator!=(const Callback &other) const; - - v8::Local operator*() const; - - MaybeLocal operator()(AsyncResource* async_resource, - v8::Local target, - int argc = 0, - v8::Local argv[] = 0) const; - - MaybeLocal operator()(AsyncResource* async_resource, - int argc = 0, - v8::Local argv[] = 0) const; - - void SetFunction(const v8::Local &fn); - - v8::Local GetFunction() const; - - bool IsEmpty() const; - - void Reset(const v8::Local &fn); - - void Reset(); - - MaybeLocal Call(v8::Local target, - int argc, - v8::Local argv[], - AsyncResource* async_resource) const; - MaybeLocal Call(int argc, - v8::Local argv[], - AsyncResource* async_resource) const; - - // Deprecated versions. Use the versions that accept an async_resource instead - // as they run the callback in the correct async context as specified by the - // resource. If you want to call a synchronous JS function (i.e. on a - // non-empty JS stack), you can use Nan::Call instead. - v8::Local operator()(v8::Local target, - int argc = 0, - v8::Local argv[] = 0) const; - - v8::Local operator()(int argc = 0, - v8::Local argv[] = 0) const; - v8::Local Call(v8::Local target, - int argc, - v8::Local argv[]) const; - - v8::Local Call(int argc, v8::Local argv[]) const; -}; -``` - -Example usage: - -```c++ -v8::Local function; -Nan::Callback callback(function); -callback.Call(0, 0); -``` diff --git a/node_modules/nan/doc/converters.md b/node_modules/nan/doc/converters.md deleted file mode 100644 index d20861b..0000000 --- a/node_modules/nan/doc/converters.md +++ /dev/null @@ -1,41 +0,0 @@ -## Converters - -NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. - - - Nan::To() - - -### Nan::To() - -Converts a `v8::Local` to a different subtype of `v8::Value` or to a native data type. Returns a `Nan::MaybeLocal<>` or a `Nan::Maybe<>` accordingly. - -See [maybe_types.md](./maybe_types.md) for more information on `Nan::Maybe` types. - -Signatures: - -```c++ -// V8 types -Nan::MaybeLocal Nan::To(v8::Local val); -Nan::MaybeLocal Nan::To(v8::Local val); -Nan::MaybeLocal Nan::To(v8::Local val); -Nan::MaybeLocal Nan::To(v8::Local val); -Nan::MaybeLocal Nan::To(v8::Local val); -Nan::MaybeLocal Nan::To(v8::Local val); -Nan::MaybeLocal Nan::To(v8::Local val); - -// Native types -Nan::Maybe Nan::To(v8::Local val); -Nan::Maybe Nan::To(v8::Local val); -Nan::Maybe Nan::To(v8::Local val); -Nan::Maybe Nan::To(v8::Local val); -Nan::Maybe Nan::To(v8::Local val); -``` - -### Example - -```c++ -v8::Local val; -Nan::MaybeLocal str = Nan::To(val); -Nan::Maybe d = Nan::To(val); -``` - diff --git a/node_modules/nan/doc/errors.md b/node_modules/nan/doc/errors.md deleted file mode 100644 index 843435b..0000000 --- a/node_modules/nan/doc/errors.md +++ /dev/null @@ -1,226 +0,0 @@ -## Errors - -NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. - -Note that an Error object is simply a specialized form of `v8::Value`. - -Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. - - - Nan::Error() - - Nan::RangeError() - - Nan::ReferenceError() - - Nan::SyntaxError() - - Nan::TypeError() - - Nan::ThrowError() - - Nan::ThrowRangeError() - - Nan::ThrowReferenceError() - - Nan::ThrowSyntaxError() - - Nan::ThrowTypeError() - - Nan::FatalException() - - Nan::ErrnoException() - - Nan::TryCatch - - - -### Nan::Error() - -Create a new Error object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. - -Note that an Error object is simply a specialized form of `v8::Value`. - -Signature: - -```c++ -v8::Local Nan::Error(const char *msg); -v8::Local Nan::Error(v8::Local msg); -``` - - - -### Nan::RangeError() - -Create a new RangeError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. - -Note that an RangeError object is simply a specialized form of `v8::Value`. - -Signature: - -```c++ -v8::Local Nan::RangeError(const char *msg); -v8::Local Nan::RangeError(v8::Local msg); -``` - - - -### Nan::ReferenceError() - -Create a new ReferenceError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. - -Note that an ReferenceError object is simply a specialized form of `v8::Value`. - -Signature: - -```c++ -v8::Local Nan::ReferenceError(const char *msg); -v8::Local Nan::ReferenceError(v8::Local msg); -``` - - - -### Nan::SyntaxError() - -Create a new SyntaxError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. - -Note that an SyntaxError object is simply a specialized form of `v8::Value`. - -Signature: - -```c++ -v8::Local Nan::SyntaxError(const char *msg); -v8::Local Nan::SyntaxError(v8::Local msg); -``` - - - -### Nan::TypeError() - -Create a new TypeError object using the [v8::Exception](https://v8docs.nodesource.com/node-8.16/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. - -Note that an TypeError object is simply a specialized form of `v8::Value`. - -Signature: - -```c++ -v8::Local Nan::TypeError(const char *msg); -v8::Local Nan::TypeError(v8::Local msg); -``` - - - -### Nan::ThrowError() - -Throw an Error object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new Error object will be created. - -Signature: - -```c++ -void Nan::ThrowError(const char *msg); -void Nan::ThrowError(v8::Local msg); -void Nan::ThrowError(v8::Local error); -``` - - - -### Nan::ThrowRangeError() - -Throw an RangeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new RangeError object will be created. - -Signature: - -```c++ -void Nan::ThrowRangeError(const char *msg); -void Nan::ThrowRangeError(v8::Local msg); -void Nan::ThrowRangeError(v8::Local error); -``` - - - -### Nan::ThrowReferenceError() - -Throw an ReferenceError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new ReferenceError object will be created. - -Signature: - -```c++ -void Nan::ThrowReferenceError(const char *msg); -void Nan::ThrowReferenceError(v8::Local msg); -void Nan::ThrowReferenceError(v8::Local error); -``` - - - -### Nan::ThrowSyntaxError() - -Throw an SyntaxError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new SyntaxError object will be created. - -Signature: - -```c++ -void Nan::ThrowSyntaxError(const char *msg); -void Nan::ThrowSyntaxError(v8::Local msg); -void Nan::ThrowSyntaxError(v8::Local error); -``` - - - -### Nan::ThrowTypeError() - -Throw an TypeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new TypeError object will be created. - -Signature: - -```c++ -void Nan::ThrowTypeError(const char *msg); -void Nan::ThrowTypeError(v8::Local msg); -void Nan::ThrowTypeError(v8::Local error); -``` - - -### Nan::FatalException() - -Replaces `node::FatalException()` which has a different API across supported versions of Node. For use with [`Nan::TryCatch`](#api_nan_try_catch). - -Signature: - -```c++ -void Nan::FatalException(const Nan::TryCatch& try_catch); -``` - - -### Nan::ErrnoException() - -Replaces `node::ErrnoException()` which has a different API across supported versions of Node. - -Signature: - -```c++ -v8::Local Nan::ErrnoException(int errorno, - const char* syscall = NULL, - const char* message = NULL, - const char* path = NULL); -``` - - - -### Nan::TryCatch - -A simple wrapper around [`v8::TryCatch`](https://v8docs.nodesource.com/node-8.16/d4/dc6/classv8_1_1_try_catch.html) compatible with all supported versions of V8. Can be used as a direct replacement in most cases. See also [`Nan::FatalException()`](#api_nan_fatal_exception) for an internal use compatible with `node::FatalException`. - -Signature: - -```c++ -class Nan::TryCatch { - public: - Nan::TryCatch(); - - bool HasCaught() const; - - bool CanContinue() const; - - v8::Local ReThrow(); - - v8::Local Exception() const; - - // Nan::MaybeLocal for older versions of V8 - v8::MaybeLocal StackTrace() const; - - v8::Local Message() const; - - void Reset(); - - void SetVerbose(bool value); - - void SetCaptureMessage(bool value); -}; -``` - diff --git a/node_modules/nan/doc/json.md b/node_modules/nan/doc/json.md deleted file mode 100644 index d142597..0000000 --- a/node_modules/nan/doc/json.md +++ /dev/null @@ -1,62 +0,0 @@ -## JSON - -The _JSON_ object provides the c++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object. - - - Nan::JSON.Parse - - Nan::JSON.Stringify - -Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments. - - - -### Nan::JSON.Parse - -A simple wrapper around [`v8::JSON::Parse`](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html#a936310d2540fb630ed37d3ee3ffe4504). - -Definition: - -```c++ -Nan::MaybeLocal Nan::JSON::Parse(v8::Local json_string); -``` - -Use `JSON.Parse(json_string)` to parse a string into a `v8::Value`. - -Example: - -```c++ -v8::Local json_string = Nan::New("{ \"JSON\": \"object\" }").ToLocalChecked(); - -Nan::JSON NanJSON; -Nan::MaybeLocal result = NanJSON.Parse(json_string); -if (!result.IsEmpty()) { - v8::Local val = result.ToLocalChecked(); -} -``` - - - -### Nan::JSON.Stringify - -A simple wrapper around [`v8::JSON::Stringify`](https://v8docs.nodesource.com/node-8.16/da/d6f/classv8_1_1_j_s_o_n.html#a44b255c3531489ce43f6110209138860). - -Definition: - -```c++ -Nan::MaybeLocal Nan::JSON::Stringify(v8::Local json_object, v8::Local gap = v8::Local()); -``` - -Use `JSON.Stringify(value)` to stringify a `v8::Object`. - -Example: - -```c++ -// using `v8::Local val` from the `JSON::Parse` example -v8::Local obj = Nan::To(val).ToLocalChecked(); - -Nan::JSON NanJSON; -Nan::MaybeLocal result = NanJSON.Stringify(obj); -if (!result.IsEmpty()) { - v8::Local stringified = result.ToLocalChecked(); -} -``` - diff --git a/node_modules/nan/doc/maybe_types.md b/node_modules/nan/doc/maybe_types.md deleted file mode 100644 index 142851a..0000000 --- a/node_modules/nan/doc/maybe_types.md +++ /dev/null @@ -1,583 +0,0 @@ -## Maybe Types - -The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. - -* **Maybe Types** - - Nan::MaybeLocal - - Nan::Maybe - - Nan::Nothing - - Nan::Just -* **Maybe Helpers** - - Nan::Call() - - Nan::ToDetailString() - - Nan::ToArrayIndex() - - Nan::Equals() - - Nan::NewInstance() - - Nan::GetFunction() - - Nan::Set() - - Nan::DefineOwnProperty() - - Nan::ForceSet() - - Nan::Get() - - Nan::GetPropertyAttributes() - - Nan::Has() - - Nan::Delete() - - Nan::GetPropertyNames() - - Nan::GetOwnPropertyNames() - - Nan::SetPrototype() - - Nan::ObjectProtoToString() - - Nan::HasOwnProperty() - - Nan::HasRealNamedProperty() - - Nan::HasRealIndexedProperty() - - Nan::HasRealNamedCallbackProperty() - - Nan::GetRealNamedPropertyInPrototypeChain() - - Nan::GetRealNamedProperty() - - Nan::CallAsFunction() - - Nan::CallAsConstructor() - - Nan::GetSourceLine() - - Nan::GetLineNumber() - - Nan::GetStartColumn() - - Nan::GetEndColumn() - - Nan::CloneElementAt() - - Nan::HasPrivate() - - Nan::GetPrivate() - - Nan::SetPrivate() - - Nan::DeletePrivate() - - Nan::MakeMaybe() - - -### Nan::MaybeLocal - -A `Nan::MaybeLocal` is a wrapper around [`v8::Local`](https://v8docs.nodesource.com/node-8.16/de/deb/classv8_1_1_local.html) that enforces a check that determines whether the `v8::Local` is empty before it can be used. - -If an API method returns a `Nan::MaybeLocal`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, an empty `Nan::MaybeLocal` is returned. - -Definition: - -```c++ -template class Nan::MaybeLocal { - public: - MaybeLocal(); - - template MaybeLocal(v8::Local that); - - bool IsEmpty() const; - - template bool ToLocal(v8::Local *out); - - // Will crash if the MaybeLocal<> is empty. - v8::Local ToLocalChecked(); - - template v8::Local FromMaybe(v8::Local default_value) const; -}; -``` - -See the documentation for [`v8::MaybeLocal`](https://v8docs.nodesource.com/node-8.16/d8/d7d/classv8_1_1_maybe_local.html) for further details. - - -### Nan::Maybe - -A simple `Nan::Maybe` type, representing an object which may or may not have a value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html. - -If an API method returns a `Nan::Maybe<>`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, a "Nothing" value is returned. - -Definition: - -```c++ -template class Nan::Maybe { - public: - bool IsNothing() const; - bool IsJust() const; - - // Will crash if the Maybe<> is nothing. - T FromJust(); - - T FromMaybe(const T& default_value); - - bool operator==(const Maybe &other); - - bool operator!=(const Maybe &other); -}; -``` - -See the documentation for [`v8::Maybe`](https://v8docs.nodesource.com/node-8.16/d9/d4b/classv8_1_1_maybe.html) for further details. - - -### Nan::Nothing - -Construct an empty `Nan::Maybe` type representing _nothing_. - -```c++ -template Nan::Maybe Nan::Nothing(); -``` - - -### Nan::Just - -Construct a `Nan::Maybe` type representing _just_ a value. - -```c++ -template Nan::Maybe Nan::Just(const T &t); -``` - - -### Nan::Call() - -A helper method for calling a synchronous [`v8::Function#Call()`](https://v8docs.nodesource.com/node-8.16/d5/d54/classv8_1_1_function.html#a9c3d0e4e13ddd7721fce238aa5b94a11) in a way compatible across supported versions of V8. - -For asynchronous callbacks, use Nan::Callback::Call along with an AsyncResource. - -Signature: - -```c++ -Nan::MaybeLocal Nan::Call(v8::Local fun, v8::Local recv, int argc, v8::Local argv[]); -Nan::MaybeLocal Nan::Call(const Nan::Callback& callback, v8::Local recv, - int argc, v8::Local argv[]); -Nan::MaybeLocal Nan::Call(const Nan::Callback& callback, int argc, v8::Local argv[]); -``` - - - -### Nan::ToDetailString() - -A helper method for calling [`v8::Value#ToDetailString()`](https://v8docs.nodesource.com/node-8.16/dc/d0a/classv8_1_1_value.html#a2f9770296dc2c8d274bc8cc0dca243e5) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::ToDetailString(v8::Local val); -``` - - - -### Nan::ToArrayIndex() - -A helper method for calling [`v8::Value#ToArrayIndex()`](https://v8docs.nodesource.com/node-8.16/dc/d0a/classv8_1_1_value.html#acc5bbef3c805ec458470c0fcd6f13493) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::ToArrayIndex(v8::Local val); -``` - - - -### Nan::Equals() - -A helper method for calling [`v8::Value#Equals()`](https://v8docs.nodesource.com/node-8.16/dc/d0a/classv8_1_1_value.html#a08fba1d776a59bbf6864b25f9152c64b) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::Equals(v8::Local a, v8::Local(b)); -``` - - - -### Nan::NewInstance() - -A helper method for calling [`v8::Function#NewInstance()`](https://v8docs.nodesource.com/node-8.16/d5/d54/classv8_1_1_function.html#ae477558b10c14b76ed00e8dbab44ce5b) and [`v8::ObjectTemplate#NewInstance()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#ad605a7543cfbc5dab54cdb0883d14ae4) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::NewInstance(v8::Local h); -Nan::MaybeLocal Nan::NewInstance(v8::Local h, int argc, v8::Local argv[]); -Nan::MaybeLocal Nan::NewInstance(v8::Local h); -``` - - - -### Nan::GetFunction() - -A helper method for calling [`v8::FunctionTemplate#GetFunction()`](https://v8docs.nodesource.com/node-8.16/d8/d83/classv8_1_1_function_template.html#a56d904662a86eca78da37d9bb0ed3705) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetFunction(v8::Local t); -``` - - - -### Nan::Set() - -A helper method for calling [`v8::Object#Set()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a67604ea3734f170c66026064ea808f20) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::Set(v8::Local obj, - v8::Local key, - v8::Local value) -Nan::Maybe Nan::Set(v8::Local obj, - uint32_t index, - v8::Local value); -``` - - - -### Nan::DefineOwnProperty() - -A helper method for calling [`v8::Object#DefineOwnProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a6f76b2ed605cb8f9185b92de0033a820) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::DefineOwnProperty(v8::Local obj, - v8::Local key, - v8::Local value, - v8::PropertyAttribute attribs = v8::None); -``` - - - -### Nan::ForceSet() - -Deprecated, use Nan::DefineOwnProperty(). - -A helper method for calling [`v8::Object#ForceSet()`](https://v8docs.nodesource.com/node-0.12/db/d85/classv8_1_1_object.html#acfbdfd7427b516ebdb5c47c4df5ed96c) in a way compatible across supported versions of V8. - -Signature: - -```c++ -NAN_DEPRECATED Nan::Maybe Nan::ForceSet(v8::Local obj, - v8::Local key, - v8::Local value, - v8::PropertyAttribute attribs = v8::None); -``` - - - -### Nan::Get() - -A helper method for calling [`v8::Object#Get()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a2565f03e736694f6b1e1cf22a0b4eac2) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::Get(v8::Local obj, - v8::Local key); -Nan::MaybeLocal Nan::Get(v8::Local obj, uint32_t index); -``` - - - -### Nan::GetPropertyAttributes() - -A helper method for calling [`v8::Object#GetPropertyAttributes()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a9b898894da3d1db2714fd9325a54fe57) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::GetPropertyAttributes( - v8::Local obj, - v8::Local key); -``` - - - -### Nan::Has() - -A helper method for calling [`v8::Object#Has()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ab3c3d89ea7c2f9afd08965bd7299a41d) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::Has(v8::Local obj, v8::Local key); -Nan::Maybe Nan::Has(v8::Local obj, uint32_t index); -``` - - - -### Nan::Delete() - -A helper method for calling [`v8::Object#Delete()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a48e4a19b2cedff867eecc73ddb7d377f) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::Delete(v8::Local obj, - v8::Local key); -Nan::Maybe Nan::Delete(v8::Local obj, uint32_t index); -``` - - - -### Nan::GetPropertyNames() - -A helper method for calling [`v8::Object#GetPropertyNames()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#aced885270cfd2c956367b5eedc7fbfe8) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetPropertyNames(v8::Local obj); -``` - - - -### Nan::GetOwnPropertyNames() - -A helper method for calling [`v8::Object#GetOwnPropertyNames()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a79a6e4d66049b9aa648ed4dfdb23e6eb) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetOwnPropertyNames(v8::Local obj); -``` - - - -### Nan::SetPrototype() - -A helper method for calling [`v8::Object#SetPrototype()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a442706b22fceda6e6d1f632122a9a9f4) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::SetPrototype(v8::Local obj, - v8::Local prototype); -``` - - - -### Nan::ObjectProtoToString() - -A helper method for calling [`v8::Object#ObjectProtoToString()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ab7a92b4dcf822bef72f6c0ac6fea1f0b) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::ObjectProtoToString(v8::Local obj); -``` - - - -### Nan::HasOwnProperty() - -A helper method for calling [`v8::Object#HasOwnProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ab7b7245442ca6de1e1c145ea3fd653ff) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::HasOwnProperty(v8::Local obj, - v8::Local key); -``` - - - -### Nan::HasRealNamedProperty() - -A helper method for calling [`v8::Object#HasRealNamedProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ad8b80a59c9eb3c1e6c3cd6c84571f767) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::HasRealNamedProperty(v8::Local obj, - v8::Local key); -``` - - - -### Nan::HasRealIndexedProperty() - -A helper method for calling [`v8::Object#HasRealIndexedProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#af94fc1135a5e74a2193fb72c3a1b9855) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::HasRealIndexedProperty(v8::Local obj, - uint32_t index); -``` - - - -### Nan::HasRealNamedCallbackProperty() - -A helper method for calling [`v8::Object#HasRealNamedCallbackProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#af743b7ea132b89f84d34d164d0668811) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::HasRealNamedCallbackProperty( - v8::Local obj, - v8::Local key); -``` - - - -### Nan::GetRealNamedPropertyInPrototypeChain() - -A helper method for calling [`v8::Object#GetRealNamedPropertyInPrototypeChain()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a8700b1862e6b4783716964ba4d5e6172) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetRealNamedPropertyInPrototypeChain( - v8::Local obj, - v8::Local key); -``` - - - -### Nan::GetRealNamedProperty() - -A helper method for calling [`v8::Object#GetRealNamedProperty()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a84471a824576a5994fdd0ffcbf99ccc0) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetRealNamedProperty(v8::Local obj, - v8::Local key); -``` - - - -### Nan::CallAsFunction() - -A helper method for calling [`v8::Object#CallAsFunction()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ad3ffc36f3dfc3592ce2a96bc047ee2cd) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::CallAsFunction(v8::Local obj, - v8::Local recv, - int argc, - v8::Local argv[]); -``` - - - -### Nan::CallAsConstructor() - -A helper method for calling [`v8::Object#CallAsConstructor()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a50d571de50d0b0dfb28795619d07a01b) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::CallAsConstructor(v8::Local obj, - int argc, - v8::Local argv[]); -``` - - - -### Nan::GetSourceLine() - -A helper method for calling [`v8::Message#GetSourceLine()`](https://v8docs.nodesource.com/node-8.16/d9/d28/classv8_1_1_message.html#a849f7a6c41549d83d8159825efccd23a) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetSourceLine(v8::Local msg); -``` - - - -### Nan::GetLineNumber() - -A helper method for calling [`v8::Message#GetLineNumber()`](https://v8docs.nodesource.com/node-8.16/d9/d28/classv8_1_1_message.html#adbe46c10a88a6565f2732a2d2adf99b9) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::GetLineNumber(v8::Local msg); -``` - - - -### Nan::GetStartColumn() - -A helper method for calling [`v8::Message#GetStartColumn()`](https://v8docs.nodesource.com/node-8.16/d9/d28/classv8_1_1_message.html#a60ede616ba3822d712e44c7a74487ba6) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::GetStartColumn(v8::Local msg); -``` - - - -### Nan::GetEndColumn() - -A helper method for calling [`v8::Message#GetEndColumn()`](https://v8docs.nodesource.com/node-8.16/d9/d28/classv8_1_1_message.html#aaa004cf19e529da980bc19fcb76d93be) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::GetEndColumn(v8::Local msg); -``` - - - -### Nan::CloneElementAt() - -A helper method for calling [`v8::Array#CloneElementAt()`](https://v8docs.nodesource.com/node-4.8/d3/d32/classv8_1_1_array.html#a1d3a878d4c1c7cae974dd50a1639245e) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::CloneElementAt(v8::Local array, uint32_t index); -``` - - -### Nan::HasPrivate() - -A helper method for calling [`v8::Object#HasPrivate()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#af68a0b98066cfdeb8f943e98a40ba08d) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::HasPrivate(v8::Local object, v8::Local key); -``` - - -### Nan::GetPrivate() - -A helper method for calling [`v8::Object#GetPrivate()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a169f2da506acbec34deadd9149a1925a) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::GetPrivate(v8::Local object, v8::Local key); -``` - - -### Nan::SetPrivate() - -A helper method for calling [`v8::Object#SetPrivate()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ace1769b0f3b86bfe9fda1010916360ee) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::SetPrivate(v8::Local object, v8::Local key, v8::Local value); -``` - - -### Nan::DeletePrivate() - -A helper method for calling [`v8::Object#DeletePrivate()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a138bb32a304f3982be02ad499693b8fd) in a way compatible across supported versions of V8. - -Signature: - -```c++ -Nan::Maybe Nan::DeletePrivate(v8::Local object, v8::Local key); -``` - - -### Nan::MakeMaybe() - -Wraps a `v8::Local<>` in a `Nan::MaybeLocal<>`. When called with a `Nan::MaybeLocal<>` it just returns its argument. This is useful in generic template code that builds on NAN. - -Synopsis: - -```c++ - MaybeLocal someNumber = MakeMaybe(New(3.141592654)); - MaybeLocal someString = MakeMaybe(New("probably")); -``` - -Signature: - -```c++ -template class MaybeMaybe> -Nan::MaybeLocal Nan::MakeMaybe(MaybeMaybe v); -``` diff --git a/node_modules/nan/doc/methods.md b/node_modules/nan/doc/methods.md deleted file mode 100644 index 9642d02..0000000 --- a/node_modules/nan/doc/methods.md +++ /dev/null @@ -1,664 +0,0 @@ -## JavaScript-accessible methods - -A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information. - -In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. - -* **Method argument types** - - Nan::FunctionCallbackInfo - - Nan::PropertyCallbackInfo - - Nan::ReturnValue -* **Method declarations** - - Method declaration - - Getter declaration - - Setter declaration - - Property getter declaration - - Property setter declaration - - Property enumerator declaration - - Property deleter declaration - - Property query declaration - - Index getter declaration - - Index setter declaration - - Index enumerator declaration - - Index deleter declaration - - Index query declaration -* Method and template helpers - - Nan::SetMethod() - - Nan::SetPrototypeMethod() - - Nan::SetAccessor() - - Nan::SetNamedPropertyHandler() - - Nan::SetIndexedPropertyHandler() - - Nan::SetTemplate() - - Nan::SetPrototypeTemplate() - - Nan::SetInstanceTemplate() - - Nan::SetCallHandler() - - Nan::SetCallAsFunctionHandler() - - -### Nan::FunctionCallbackInfo - -`Nan::FunctionCallbackInfo` should be used in place of [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.16/dd/d0d/classv8_1_1_function_callback_info.html), even with older versions of Node where `v8::FunctionCallbackInfo` does not exist. - -Definition: - -```c++ -template class FunctionCallbackInfo { - public: - ReturnValue GetReturnValue() const; - v8::Local Callee(); // NOTE: Not available in NodeJS >= 10.0.0 - v8::Local Data(); - v8::Local Holder(); - bool IsConstructCall(); - int Length() const; - v8::Local operator[](int i) const; - v8::Local This() const; - v8::Isolate *GetIsolate() const; -}; -``` - -See the [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.16/dd/d0d/classv8_1_1_function_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from methods. - -**Note:** `FunctionCallbackInfo::Callee` is removed in Node.js after `10.0.0` because it is was deprecated in V8. Consider using `info.Data()` to pass any information you need. - - -### Nan::PropertyCallbackInfo - -`Nan::PropertyCallbackInfo` should be used in place of [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.16/d7/dc5/classv8_1_1_property_callback_info.html), even with older versions of Node where `v8::PropertyCallbackInfo` does not exist. - -Definition: - -```c++ -template class PropertyCallbackInfo : public PropertyCallbackInfoBase { - public: - ReturnValue GetReturnValue() const; - v8::Isolate* GetIsolate() const; - v8::Local Data() const; - v8::Local This() const; - v8::Local Holder() const; -}; -``` - -See the [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.16/d7/dc5/classv8_1_1_property_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from property accessor methods. - - -### Nan::ReturnValue - -`Nan::ReturnValue` is used in place of [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.16/da/da7/classv8_1_1_return_value.html) on both [`Nan::FunctionCallbackInfo`](#api_nan_function_callback_info) and [`Nan::PropertyCallbackInfo`](#api_nan_property_callback_info) as the return type of `GetReturnValue()`. - -Example usage: - -```c++ -void EmptyArray(const Nan::FunctionCallbackInfo& info) { - info.GetReturnValue().Set(Nan::New()); -} -``` - -Definition: - -```c++ -template class ReturnValue { - public: - // Handle setters - template void Set(const v8::Local &handle); - template void Set(const Nan::Global &handle); - - // Fast primitive setters - void Set(bool value); - void Set(double i); - void Set(int32_t i); - void Set(uint32_t i); - - // Fast JS primitive setters - void SetNull(); - void SetUndefined(); - void SetEmptyString(); - - // Convenience getter for isolate - v8::Isolate *GetIsolate() const; -}; -``` - -See the documentation on [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.16/da/da7/classv8_1_1_return_value.html) for further information on this. - - -### Method declaration - -JavaScript-accessible methods should be declared with the following signature to form a `Nan::FunctionCallback`: - -```c++ -typedef void(*FunctionCallback)(const FunctionCallbackInfo&); -``` - -Example: - -```c++ -void MethodName(const Nan::FunctionCallbackInfo& info) { - ... -} -``` - -You do not need to declare a new `HandleScope` within a method as one is implicitly created for you. - -**Example usage** - -```c++ -// .h: -class Foo : public Nan::ObjectWrap { - ... - - static void Bar(const Nan::FunctionCallbackInfo& info); - static void Baz(const Nan::FunctionCallbackInfo& info); -} - - -// .cc: -void Foo::Bar(const Nan::FunctionCallbackInfo& info) { - ... -} - -void Foo::Baz(const Nan::FunctionCallbackInfo& info) { - ... -} -``` - -A helper macro `NAN_METHOD(methodname)` exists, compatible with NAN v1 method declarations. - -**Example usage with `NAN_METHOD(methodname)`** - -```c++ -// .h: -class Foo : public Nan::ObjectWrap { - ... - - static NAN_METHOD(Bar); - static NAN_METHOD(Baz); -} - - -// .cc: -NAN_METHOD(Foo::Bar) { - ... -} - -NAN_METHOD(Foo::Baz) { - ... -} -``` - -Use [`Nan::SetPrototypeMethod`](#api_nan_set_prototype_method) to attach a method to a JavaScript function prototype or [`Nan::SetMethod`](#api_nan_set_method) to attach a method directly on a JavaScript object. - - -### Getter declaration - -JavaScript-accessible getters should be declared with the following signature to form a `Nan::GetterCallback`: - -```c++ -typedef void(*GetterCallback)(v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void GetterName(v8::Local property, - const Nan::PropertyCallbackInfo& info) { - ... -} -``` - -You do not need to declare a new `HandleScope` within a getter as one is implicitly created for you. - -A helper macro `NAN_GETTER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors). - - -### Setter declaration - -JavaScript-accessible setters should be declared with the following signature to form a Nan::SetterCallback: - -```c++ -typedef void(*SetterCallback)(v8::Local, - v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void SetterName(v8::Local property, - v8::Local value, - const Nan::PropertyCallbackInfo& info) { - ... -} -``` - -You do not need to declare a new `HandleScope` within a setter as one is implicitly created for you. - -A helper macro `NAN_SETTER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors). - - -### Property getter declaration - -JavaScript-accessible property getters should be declared with the following signature to form a Nan::PropertyGetterCallback: - -```c++ -typedef void(*PropertyGetterCallback)(v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void PropertyGetterName(v8::Local property, - const Nan::PropertyCallbackInfo& info) { - ... -} -``` - -You do not need to declare a new `HandleScope` within a property getter as one is implicitly created for you. - -A helper macro `NAN_PROPERTY_GETTER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Property setter declaration - -JavaScript-accessible property setters should be declared with the following signature to form a Nan::PropertySetterCallback: - -```c++ -typedef void(*PropertySetterCallback)(v8::Local, - v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void PropertySetterName(v8::Local property, - v8::Local value, - const Nan::PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a property setter as one is implicitly created for you. - -A helper macro `NAN_PROPERTY_SETTER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Property enumerator declaration - -JavaScript-accessible property enumerators should be declared with the following signature to form a Nan::PropertyEnumeratorCallback: - -```c++ -typedef void(*PropertyEnumeratorCallback)(const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void PropertyEnumeratorName(const Nan::PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a property enumerator as one is implicitly created for you. - -A helper macro `NAN_PROPERTY_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Property deleter declaration - -JavaScript-accessible property deleters should be declared with the following signature to form a Nan::PropertyDeleterCallback: - -```c++ -typedef void(*PropertyDeleterCallback)(v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void PropertyDeleterName(v8::Local property, - const Nan::PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a property deleter as one is implicitly created for you. - -A helper macro `NAN_PROPERTY_DELETER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Property query declaration - -JavaScript-accessible property query methods should be declared with the following signature to form a Nan::PropertyQueryCallback: - -```c++ -typedef void(*PropertyQueryCallback)(v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void PropertyQueryName(v8::Local property, - const Nan::PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a property query method as one is implicitly created for you. - -A helper macro `NAN_PROPERTY_QUERY(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Index getter declaration - -JavaScript-accessible index getter methods should be declared with the following signature to form a Nan::IndexGetterCallback: - -```c++ -typedef void(*IndexGetterCallback)(uint32_t, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void IndexGetterName(uint32_t index, const PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a index getter as one is implicitly created for you. - -A helper macro `NAN_INDEX_GETTER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Index setter declaration - -JavaScript-accessible index setter methods should be declared with the following signature to form a Nan::IndexSetterCallback: - -```c++ -typedef void(*IndexSetterCallback)(uint32_t, - v8::Local, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void IndexSetterName(uint32_t index, - v8::Local value, - const PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a index setter as one is implicitly created for you. - -A helper macro `NAN_INDEX_SETTER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Index enumerator declaration - -JavaScript-accessible index enumerator methods should be declared with the following signature to form a Nan::IndexEnumeratorCallback: - -```c++ -typedef void(*IndexEnumeratorCallback)(const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void IndexEnumeratorName(const PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a index enumerator as one is implicitly created for you. - -A helper macro `NAN_INDEX_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Index deleter declaration - -JavaScript-accessible index deleter methods should be declared with the following signature to form a Nan::IndexDeleterCallback: - -```c++ -typedef void(*IndexDeleterCallback)(uint32_t, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void IndexDeleterName(uint32_t index, const PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a index deleter as one is implicitly created for you. - -A helper macro `NAN_INDEX_DELETER(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Index query declaration - -JavaScript-accessible index query methods should be declared with the following signature to form a Nan::IndexQueryCallback: - -```c++ -typedef void(*IndexQueryCallback)(uint32_t, - const PropertyCallbackInfo&); -``` - -Example: - -```c++ -void IndexQueryName(uint32_t index, const PropertyCallbackInfo& info); -``` - -You do not need to declare a new `HandleScope` within a index query method as one is implicitly created for you. - -A helper macro `NAN_INDEX_QUERY(methodname)` exists, compatible with NAN v1 method declarations. - -Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). - - -### Nan::SetMethod() - -Sets a method with a given name directly on a JavaScript object where the method has the `Nan::FunctionCallback` signature (see Method declaration). - -Signature: - -```c++ -void Nan::SetMethod(v8::Local recv, - const char *name, - Nan::FunctionCallback callback, - v8::Local data = v8::Local()) -void Nan::SetMethod(v8::Local templ, - const char *name, - Nan::FunctionCallback callback, - v8::Local data = v8::Local()) -``` - - -### Nan::SetPrototypeMethod() - -Sets a method with a given name on a `FunctionTemplate`'s prototype where the method has the `Nan::FunctionCallback` signature (see Method declaration). - -Signature: - -```c++ -void Nan::SetPrototypeMethod(v8::Local recv, - const char* name, - Nan::FunctionCallback callback, - v8::Local data = v8::Local()) -``` - - -### Nan::SetAccessor() - -Sets getters and setters for a property with a given name on an `ObjectTemplate` or a plain `Object`. Accepts getters with the `Nan::GetterCallback` signature (see Getter declaration) and setters with the `Nan::SetterCallback` signature (see Setter declaration). - -Signature: - -```c++ -void SetAccessor(v8::Local tpl, - v8::Local name, - Nan::GetterCallback getter, - Nan::SetterCallback setter = 0, - v8::Local data = v8::Local(), - v8::AccessControl settings = v8::DEFAULT, - v8::PropertyAttribute attribute = v8::None, - imp::Sig signature = imp::Sig()); -bool SetAccessor(v8::Local obj, - v8::Local name, - Nan::GetterCallback getter, - Nan::SetterCallback setter = 0, - v8::Local data = v8::Local(), - v8::AccessControl settings = v8::DEFAULT, - v8::PropertyAttribute attribute = v8::None) -``` - -See the V8 [`ObjectTemplate#SetAccessor()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#aca0ed196f8a9adb1f68b1aadb6c9cd77) and [`Object#SetAccessor()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ae91b3b56b357f285288c89fbddc46d1b) for further information about how to use `Nan::SetAccessor()`. - - -### Nan::SetNamedPropertyHandler() - -Sets named property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts: - -* Property getters with the `Nan::PropertyGetterCallback` signature (see Property getter declaration) -* Property setters with the `Nan::PropertySetterCallback` signature (see Property setter declaration) -* Property query methods with the `Nan::PropertyQueryCallback` signature (see Property query declaration) -* Property deleters with the `Nan::PropertyDeleterCallback` signature (see Property deleter declaration) -* Property enumerators with the `Nan::PropertyEnumeratorCallback` signature (see Property enumerator declaration) - -Signature: - -```c++ -void SetNamedPropertyHandler(v8::Local tpl, - Nan::PropertyGetterCallback getter, - Nan::PropertySetterCallback setter = 0, - Nan::PropertyQueryCallback query = 0, - Nan::PropertyDeleterCallback deleter = 0, - Nan::PropertyEnumeratorCallback enumerator = 0, - v8::Local data = v8::Local()) -``` - -See the V8 [`ObjectTemplate#SetNamedPropertyHandler()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#a33b3ebd7de641f6cc6414b7de01fc1c7) for further information about how to use `Nan::SetNamedPropertyHandler()`. - - -### Nan::SetIndexedPropertyHandler() - -Sets indexed property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts: - -* Indexed property getters with the `Nan::IndexGetterCallback` signature (see Index getter declaration) -* Indexed property setters with the `Nan::IndexSetterCallback` signature (see Index setter declaration) -* Indexed property query methods with the `Nan::IndexQueryCallback` signature (see Index query declaration) -* Indexed property deleters with the `Nan::IndexDeleterCallback` signature (see Index deleter declaration) -* Indexed property enumerators with the `Nan::IndexEnumeratorCallback` signature (see Index enumerator declaration) - -Signature: - -```c++ -void SetIndexedPropertyHandler(v8::Local tpl, - Nan::IndexGetterCallback getter, - Nan::IndexSetterCallback setter = 0, - Nan::IndexQueryCallback query = 0, - Nan::IndexDeleterCallback deleter = 0, - Nan::IndexEnumeratorCallback enumerator = 0, - v8::Local data = v8::Local()) -``` - -See the V8 [`ObjectTemplate#SetIndexedPropertyHandler()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#ac89f06d634add0e890452033f7d17ff1) for further information about how to use `Nan::SetIndexedPropertyHandler()`. - - -### Nan::SetTemplate() - -Adds properties on an `Object`'s or `Function`'s template. - -Signature: - -```c++ -void Nan::SetTemplate(v8::Local templ, - const char *name, - v8::Local value); -void Nan::SetTemplate(v8::Local templ, - v8::Local name, - v8::Local value, - v8::PropertyAttribute attributes) -``` - -Calls the `Template`'s [`Set()`](https://v8docs.nodesource.com/node-8.16/db/df7/classv8_1_1_template.html#ae3fbaff137557aa6a0233bc7e52214ac). - - -### Nan::SetPrototypeTemplate() - -Adds properties on an `Object`'s or `Function`'s prototype template. - -Signature: - -```c++ -void Nan::SetPrototypeTemplate(v8::Local templ, - const char *name, - v8::Local value); -void Nan::SetPrototypeTemplate(v8::Local templ, - v8::Local name, - v8::Local value, - v8::PropertyAttribute attributes) -``` - -Calls the `FunctionTemplate`'s _PrototypeTemplate's_ [`Set()`](https://v8docs.nodesource.com/node-8.16/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf). - - -### Nan::SetInstanceTemplate() - -Use to add instance properties on `FunctionTemplate`'s. - -Signature: - -```c++ -void Nan::SetInstanceTemplate(v8::Local templ, - const char *name, - v8::Local value); -void Nan::SetInstanceTemplate(v8::Local templ, - v8::Local name, - v8::Local value, - v8::PropertyAttribute attributes) -``` - -Calls the `FunctionTemplate`'s _InstanceTemplate's_ [`Set()`](https://v8docs.nodesource.com/node-8.16/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf). - - -### Nan::SetCallHandler() - -Set the call-handler callback for a `v8::FunctionTemplate`. -This callback is called whenever the function created from this FunctionTemplate is called. - -Signature: - -```c++ -void Nan::SetCallHandler(v8::Local templ, Nan::FunctionCallback callback, v8::Local data = v8::Local()) -``` - -Calls the `FunctionTemplate`'s [`SetCallHandler()`](https://v8docs.nodesource.com/node-8.16/d8/d83/classv8_1_1_function_template.html#ab7574b298db3c27fbc2ed465c08ea2f8). - - -### Nan::SetCallAsFunctionHandler() - -Sets the callback to be used when calling instances created from the `v8::ObjectTemplate` as a function. -If no callback is set, instances behave like normal JavaScript objects that cannot be called as a function. - -Signature: - -```c++ -void Nan::SetCallAsFunctionHandler(v8::Local templ, Nan::FunctionCallback callback, v8::Local data = v8::Local()) -``` - -Calls the `ObjectTemplate`'s [`SetCallAsFunctionHandler()`](https://v8docs.nodesource.com/node-8.16/db/d5f/classv8_1_1_object_template.html#a5e9612fc80bf6db8f2da199b9b0bd04e). - diff --git a/node_modules/nan/doc/new.md b/node_modules/nan/doc/new.md deleted file mode 100644 index 0f28a0e..0000000 --- a/node_modules/nan/doc/new.md +++ /dev/null @@ -1,147 +0,0 @@ -## New - -NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. - - - Nan::New() - - Nan::Undefined() - - Nan::Null() - - Nan::True() - - Nan::False() - - Nan::EmptyString() - - - -### Nan::New() - -`Nan::New()` should be used to instantiate new JavaScript objects. - -Refer to the specific V8 type in the [V8 documentation](https://v8docs.nodesource.com/node-8.16/d1/d83/classv8_1_1_data.html) for information on the types of arguments required for instantiation. - -Signatures: - -Return types are mostly omitted from the signatures for simplicity. In most cases the type will be contained within a `v8::Local`. The following types will be contained within a `Nan::MaybeLocal`: `v8::String`, `v8::Date`, `v8::RegExp`, `v8::Script`, `v8::UnboundScript`. - -Empty objects: - -```c++ -Nan::New(); -``` - -Generic single and multiple-argument: - -```c++ -Nan::New(A0 arg0); -Nan::New(A0 arg0, A1 arg1); -Nan::New(A0 arg0, A1 arg1, A2 arg2); -Nan::New(A0 arg0, A1 arg1, A2 arg2, A3 arg3); -``` - -For creating `v8::FunctionTemplate` and `v8::Function` objects: - -_The definition of `Nan::FunctionCallback` can be found in the [Method declaration](./methods.md#api_nan_method) documentation._ - -```c++ -Nan::New(Nan::FunctionCallback callback, - v8::Local data = v8::Local()); -Nan::New(Nan::FunctionCallback callback, - v8::Local data = v8::Local(), - A2 a2 = A2()); -``` - -Native number types: - -```c++ -v8::Local Nan::New(bool value); -v8::Local Nan::New(int32_t value); -v8::Local Nan::New(uint32_t value); -v8::Local Nan::New(double value); -``` - -String types: - -```c++ -Nan::MaybeLocal Nan::New(std::string const& value); -Nan::MaybeLocal Nan::New(const char * value, int length); -Nan::MaybeLocal Nan::New(const char * value); -Nan::MaybeLocal Nan::New(const uint16_t * value); -Nan::MaybeLocal Nan::New(const uint16_t * value, int length); -``` - -Specialized types: - -```c++ -v8::Local Nan::New(v8::String::ExternalStringResource * value); -v8::Local Nan::New(Nan::ExternalOneByteStringResource * value); -v8::Local Nan::New(v8::Local pattern, v8::RegExp::Flags flags); -``` - -Note that `Nan::ExternalOneByteStringResource` maps to [`v8::String::ExternalOneByteStringResource`](https://v8docs.nodesource.com/node-8.16/d9/db3/classv8_1_1_string_1_1_external_one_byte_string_resource.html), and `v8::String::ExternalAsciiStringResource` in older versions of V8. - - - -### Nan::Undefined() - -A helper method to reference the `v8::Undefined` object in a way that is compatible across all supported versions of V8. - -Signature: - -```c++ -v8::Local Nan::Undefined() -``` - - -### Nan::Null() - -A helper method to reference the `v8::Null` object in a way that is compatible across all supported versions of V8. - -Signature: - -```c++ -v8::Local Nan::Null() -``` - - -### Nan::True() - -A helper method to reference the `v8::Boolean` object representing the `true` value in a way that is compatible across all supported versions of V8. - -Signature: - -```c++ -v8::Local Nan::True() -``` - - -### Nan::False() - -A helper method to reference the `v8::Boolean` object representing the `false` value in a way that is compatible across all supported versions of V8. - -Signature: - -```c++ -v8::Local Nan::False() -``` - - -### Nan::EmptyString() - -Call [`v8::String::Empty`](https://v8docs.nodesource.com/node-8.16/d2/db3/classv8_1_1_string.html#a7c1bc8886115d7ee46f1d571dd6ebc6d) to reference the empty string in a way that is compatible across all supported versions of V8. - -Signature: - -```c++ -v8::Local Nan::EmptyString() -``` - - - -### Nan::NewOneByteString() - -An implementation of [`v8::String::NewFromOneByte()`](https://v8docs.nodesource.com/node-8.16/d2/db3/classv8_1_1_string.html#a5264d50b96d2c896ce525a734dc10f09) provided for consistent availability and API across supported versions of V8. Allocates a new string from Latin-1 data. - -Signature: - -```c++ -Nan::MaybeLocal Nan::NewOneByteString(const uint8_t * value, - int length = -1) -``` diff --git a/node_modules/nan/doc/node_misc.md b/node_modules/nan/doc/node_misc.md deleted file mode 100644 index 17578e3..0000000 --- a/node_modules/nan/doc/node_misc.md +++ /dev/null @@ -1,123 +0,0 @@ -## Miscellaneous Node Helpers - - - Nan::AsyncResource - - Nan::MakeCallback() - - NAN_MODULE_INIT() - - Nan::Export() - - -### Nan::AsyncResource - -This class is analogous to the `AsyncResource` JavaScript class exposed by Node's [async_hooks][] API. - -When calling back into JavaScript asynchronously, special care must be taken to ensure that the runtime can properly track -async hops. `Nan::AsyncResource` is a class that provides an RAII wrapper around `node::EmitAsyncInit`, `node::EmitAsyncDestroy`, -and `node::MakeCallback`. Using this mechanism to call back into JavaScript, as opposed to `Nan::MakeCallback` or -`v8::Function::Call` ensures that the callback is executed in the correct async context. This ensures that async mechanisms -such as domains and [async_hooks][] function correctly. - -Definition: - -```c++ -class AsyncResource { - public: - AsyncResource(v8::Local name, - v8::Local resource = New()); - AsyncResource(const char* name, - v8::Local resource = New()); - ~AsyncResource(); - - v8::MaybeLocal runInAsyncScope(v8::Local target, - v8::Local func, - int argc, - v8::Local* argv); - v8::MaybeLocal runInAsyncScope(v8::Local target, - v8::Local symbol, - int argc, - v8::Local* argv); - v8::MaybeLocal runInAsyncScope(v8::Local target, - const char* method, - int argc, - v8::Local* argv); -}; -``` - -* `name`: Identifier for the kind of resource that is being provided for diagnostics information exposed by the [async_hooks][] - API. This will be passed to the possible `init` hook as the `type`. To avoid name collisions with other modules we recommend - that the name include the name of the owning module as a prefix. For example `mysql` module could use something like - `mysql:batch-db-query-resource`. -* `resource`: An optional object associated with the async work that will be passed to the possible [async_hooks][] - `init` hook. If this parameter is omitted, or an empty handle is provided, this object will be created automatically. -* When calling JS on behalf of this resource, one can use `runInAsyncScope`. This will ensure that the callback runs in the - correct async execution context. -* `AsyncDestroy` is automatically called when an AsyncResource object is destroyed. - -For more details, see the Node [async_hooks][] documentation. You might also want to take a look at the documentation for the -[N-API counterpart][napi]. For example usage, see the `asyncresource.cpp` example in the `test/cpp` directory. - - -### Nan::MakeCallback() - -Deprecated wrappers around the legacy `node::MakeCallback()` APIs. Node.js 10+ -has deprecated these legacy APIs as they do not provide a mechanism to preserve -async context. - -We recommend that you use the `AsyncResource` class and `AsyncResource::runInAsyncScope` instead of using `Nan::MakeCallback` or -`v8::Function#Call()` directly. `AsyncResource` properly takes care of running the callback in the correct async execution -context – something that is essential for functionality like domains, async_hooks and async debugging. - -Signatures: - -```c++ -NAN_DEPRECATED -v8::Local Nan::MakeCallback(v8::Local target, - v8::Local func, - int argc, - v8::Local* argv); -NAN_DEPRECATED -v8::Local Nan::MakeCallback(v8::Local target, - v8::Local symbol, - int argc, - v8::Local* argv); -NAN_DEPRECATED -v8::Local Nan::MakeCallback(v8::Local target, - const char* method, - int argc, - v8::Local* argv); -``` - - - -### NAN_MODULE_INIT() - -Used to define the entry point function to a Node add-on. Creates a function with a given `name` that receives a `target` object representing the equivalent of the JavaScript `exports` object. - -See example below. - - -### Nan::Export() - -A simple helper to register a `v8::FunctionTemplate` from a JavaScript-accessible method (see [Methods](./methods.md)) as a property on an object. Can be used in a way similar to assigning properties to `module.exports` in JavaScript. - -Signature: - -```c++ -void Export(v8::Local target, const char *name, Nan::FunctionCallback f) -``` - -Also available as the shortcut `NAN_EXPORT` macro. - -Example: - -```c++ -NAN_METHOD(Foo) { - ... -} - -NAN_MODULE_INIT(Init) { - NAN_EXPORT(target, Foo); -} -``` - -[async_hooks]: https://nodejs.org/dist/latest-v9.x/docs/api/async_hooks.html -[napi]: https://nodejs.org/dist/latest-v9.x/docs/api/n-api.html#n_api_custom_asynchronous_operations diff --git a/node_modules/nan/doc/object_wrappers.md b/node_modules/nan/doc/object_wrappers.md deleted file mode 100644 index 07d8c05..0000000 --- a/node_modules/nan/doc/object_wrappers.md +++ /dev/null @@ -1,263 +0,0 @@ -## Object Wrappers - -The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects. - - - Nan::ObjectWrap - - - -### Nan::ObjectWrap() - -A reimplementation of `node::ObjectWrap` that adds some API not present in older versions of Node. Should be preferred over `node::ObjectWrap` in all cases for consistency. - -Definition: - -```c++ -class ObjectWrap { - public: - ObjectWrap(); - - virtual ~ObjectWrap(); - - template - static inline T* Unwrap(v8::Local handle); - - inline v8::Local handle(); - - inline Nan::Persistent& persistent(); - - protected: - inline void Wrap(v8::Local handle); - - inline void MakeWeak(); - - /* Ref() marks the object as being attached to an event loop. - * Refed objects will not be garbage collected, even if - * all references are lost. - */ - virtual void Ref(); - - /* Unref() marks an object as detached from the event loop. This is its - * default state. When an object with a "weak" reference changes from - * attached to detached state it will be freed. Be careful not to access - * the object after making this call as it might be gone! - * (A "weak reference" means an object that only has a - * persistent handle.) - * - * DO NOT CALL THIS FROM DESTRUCTOR - */ - virtual void Unref(); - - int refs_; // ro -}; -``` - -See the Node documentation on [Wrapping C++ Objects](https://nodejs.org/api/addons.html#addons_wrapping_c_objects) for more details. - -### This vs. Holder - -When calling `Unwrap`, it is important that the argument is indeed some JavaScript object which got wrapped by a `Wrap` call for this class or any derived class. -The `Signature` installed by [`Nan::SetPrototypeMethod()`](methods.md#api_nan_set_prototype_method) does ensure that `info.Holder()` is just such an instance. -In Node 0.12 and later, `info.This()` will also be of such a type, since otherwise the invocation will get rejected. -However, in Node 0.10 and before it was possible to invoke a method on a JavaScript object which just had the extension type in its prototype chain. -In such a situation, calling `Unwrap` on `info.This()` will likely lead to a failed assertion causing a crash, but could lead to even more serious corruption. - -On the other hand, calling `Unwrap` in an [accessor](methods.md#api_nan_set_accessor) should not use `Holder()` if the accessor is defined on the prototype. -So either define your accessors on the instance template, -or use `This()` after verifying that it is indeed a valid object. - -### Examples - -#### Basic - -```c++ -class MyObject : public Nan::ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - v8::Local tpl = Nan::New(New); - tpl->SetClassName(Nan::New("MyObject").ToLocalChecked()); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - Nan::SetPrototypeMethod(tpl, "getHandle", GetHandle); - Nan::SetPrototypeMethod(tpl, "getValue", GetValue); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - Nan::Set(target, Nan::New("MyObject").ToLocalChecked(), - Nan::GetFunction(tpl).ToLocalChecked()); - } - - private: - explicit MyObject(double value = 0) : value_(value) {} - ~MyObject() {} - - static NAN_METHOD(New) { - if (info.IsConstructCall()) { - double value = info[0]->IsUndefined() ? 0 : Nan::To(info[0]).FromJust(); - MyObject *obj = new MyObject(value); - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } else { - const int argc = 1; - v8::Local argv[argc] = {info[0]}; - v8::Local cons = Nan::New(constructor()); - info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); - } - } - - static NAN_METHOD(GetHandle) { - MyObject* obj = Nan::ObjectWrap::Unwrap(info.Holder()); - info.GetReturnValue().Set(obj->handle()); - } - - static NAN_METHOD(GetValue) { - MyObject* obj = Nan::ObjectWrap::Unwrap(info.Holder()); - info.GetReturnValue().Set(obj->value_); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - double value_; -}; - -NODE_MODULE(objectwrapper, MyObject::Init) -``` - -To use in Javascript: - -```Javascript -var objectwrapper = require('bindings')('objectwrapper'); - -var obj = new objectwrapper.MyObject(5); -console.log('Should be 5: ' + obj.getValue()); -``` - -#### Factory of wrapped objects - -```c++ -class MyFactoryObject : public Nan::ObjectWrap { - public: - static NAN_MODULE_INIT(Init) { - v8::Local tpl = Nan::New(New); - tpl->InstanceTemplate()->SetInternalFieldCount(1); - - Nan::SetPrototypeMethod(tpl, "getValue", GetValue); - - constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); - } - - static NAN_METHOD(NewInstance) { - v8::Local cons = Nan::New(constructor()); - double value = info[0]->IsNumber() ? Nan::To(info[0]).FromJust() : 0; - const int argc = 1; - v8::Local argv[1] = {Nan::New(value)}; - info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); - } - - // Needed for the next example: - inline double value() const { - return value_; - } - - private: - explicit MyFactoryObject(double value = 0) : value_(value) {} - ~MyFactoryObject() {} - - static NAN_METHOD(New) { - if (info.IsConstructCall()) { - double value = info[0]->IsNumber() ? Nan::To(info[0]).FromJust() : 0; - MyFactoryObject * obj = new MyFactoryObject(value); - obj->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); - } else { - const int argc = 1; - v8::Local argv[argc] = {info[0]}; - v8::Local cons = Nan::New(constructor()); - info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); - } - } - - static NAN_METHOD(GetValue) { - MyFactoryObject* obj = ObjectWrap::Unwrap(info.Holder()); - info.GetReturnValue().Set(obj->value_); - } - - static inline Nan::Persistent & constructor() { - static Nan::Persistent my_constructor; - return my_constructor; - } - - double value_; -}; - -NAN_MODULE_INIT(Init) { - MyFactoryObject::Init(target); - Nan::Set(target, - Nan::New("newFactoryObjectInstance").ToLocalChecked(), - Nan::GetFunction( - Nan::New(MyFactoryObject::NewInstance)).ToLocalChecked() - ); -} - -NODE_MODULE(wrappedobjectfactory, Init) -``` - -To use in Javascript: - -```Javascript -var wrappedobjectfactory = require('bindings')('wrappedobjectfactory'); - -var obj = wrappedobjectfactory.newFactoryObjectInstance(10); -console.log('Should be 10: ' + obj.getValue()); -``` - -#### Passing wrapped objects around - -Use the `MyFactoryObject` class above along with the following: - -```c++ -static NAN_METHOD(Sum) { - Nan::MaybeLocal maybe1 = Nan::To(info[0]); - Nan::MaybeLocal maybe2 = Nan::To(info[1]); - - // Quick check: - if (maybe1.IsEmpty() || maybe2.IsEmpty()) { - // return value is undefined by default - return; - } - - MyFactoryObject* obj1 = - Nan::ObjectWrap::Unwrap(maybe1.ToLocalChecked()); - MyFactoryObject* obj2 = - Nan::ObjectWrap::Unwrap(maybe2.ToLocalChecked()); - - info.GetReturnValue().Set(Nan::New(obj1->value() + obj2->value())); -} - -NAN_MODULE_INIT(Init) { - MyFactoryObject::Init(target); - Nan::Set(target, - Nan::New("newFactoryObjectInstance").ToLocalChecked(), - Nan::GetFunction( - Nan::New(MyFactoryObject::NewInstance)).ToLocalChecked() - ); - Nan::Set(target, - Nan::New("sum").ToLocalChecked(), - Nan::GetFunction(Nan::New(Sum)).ToLocalChecked() - ); -} - -NODE_MODULE(myaddon, Init) -``` - -To use in Javascript: - -```Javascript -var myaddon = require('bindings')('myaddon'); - -var obj1 = myaddon.newFactoryObjectInstance(5); -var obj2 = myaddon.newFactoryObjectInstance(10); -console.log('sum of object values: ' + myaddon.sum(obj1, obj2)); -``` diff --git a/node_modules/nan/doc/persistent.md b/node_modules/nan/doc/persistent.md deleted file mode 100644 index 2e13f6b..0000000 --- a/node_modules/nan/doc/persistent.md +++ /dev/null @@ -1,296 +0,0 @@ -## Persistent references - -An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. - -Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. - - - Nan::PersistentBase & v8::PersistentBase - - Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits - - Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits - - Nan::Persistent - - Nan::Global - - Nan::WeakCallbackInfo - - Nan::WeakCallbackType - -Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). - - -### Nan::PersistentBase & v8::PersistentBase - -A persistent handle contains a reference to a storage cell in V8 which holds an object value and which is updated by the garbage collector whenever the object is moved. A new storage cell can be created using the constructor or `Nan::PersistentBase::Reset()`. Existing handles can be disposed using an argument-less `Nan::PersistentBase::Reset()`. - -Definition: - -_(note: this is implemented as `Nan::PersistentBase` for older versions of V8 and the native `v8::PersistentBase` is used for newer versions of V8)_ - -```c++ -template class PersistentBase { - public: - /** - * If non-empty, destroy the underlying storage cell - */ - void Reset(); - - /** - * If non-empty, destroy the underlying storage cell and create a new one with - * the contents of another if it is also non-empty - */ - template void Reset(const v8::Local &other); - - /** - * If non-empty, destroy the underlying storage cell and create a new one with - * the contents of another if it is also non-empty - */ - template void Reset(const PersistentBase &other); - - /** Returns true if the handle is empty. */ - bool IsEmpty() const; - - /** - * If non-empty, destroy the underlying storage cell - * IsEmpty() will return true after this call. - */ - void Empty(); - - template bool operator==(const PersistentBase &that); - - template bool operator==(const v8::Local &that); - - template bool operator!=(const PersistentBase &that); - - template bool operator!=(const v8::Local &that); - - /** - * Install a finalization callback on this object. - * NOTE: There is no guarantee as to *when* or even *if* the callback is - * invoked. The invocation is performed solely on a best effort basis. - * As always, GC-based finalization should *not* be relied upon for any - * critical form of resource management! At the moment you can either - * specify a parameter for the callback or the location of two internal - * fields in the dying object. - */ - template - void SetWeak(P *parameter, - typename WeakCallbackInfo

::Callback callback, - WeakCallbackType type); - - void ClearWeak(); - - /** - * Marks the reference to this object independent. Garbage collector is free - * to ignore any object groups containing this object. Weak callback for an - * independent handle should not assume that it will be preceded by a global - * GC prologue callback or followed by a global GC epilogue callback. - */ - void MarkIndependent() const; - - bool IsIndependent() const; - - /** Checks if the handle holds the only reference to an object. */ - bool IsNearDeath() const; - - /** Returns true if the handle's reference is weak. */ - bool IsWeak() const -}; -``` - -See the V8 documentation for [`PersistentBase`](https://v8docs.nodesource.com/node-8.16/d4/dca/classv8_1_1_persistent_base.html) for further information. - -**Tip:** To get a `v8::Local` reference to the original object back from a `PersistentBase` or `Persistent` object: - -```c++ -v8::Local object = Nan::New(persistent); -``` - - -### Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits - -Default traits for `Nan::Persistent`. This class does not allow use of the a copy constructor or assignment operator. At present `kResetInDestructor` is not set, but that will change in a future version. - -Definition: - -_(note: this is implemented as `Nan::NonCopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_ - -```c++ -template class NonCopyablePersistentTraits { - public: - typedef Persistent > NonCopyablePersistent; - - static const bool kResetInDestructor = false; - - template - static void Copy(const Persistent &source, - NonCopyablePersistent *dest); - - template static void Uncompilable(); -}; -``` - -See the V8 documentation for [`NonCopyablePersistentTraits`](https://v8docs.nodesource.com/node-8.16/de/d73/classv8_1_1_non_copyable_persistent_traits.html) for further information. - - -### Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits - -A helper class of traits to allow copying and assignment of `Persistent`. This will clone the contents of storage cell, but not any of the flags, etc.. - -Definition: - -_(note: this is implemented as `Nan::CopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_ - -```c++ -template -class CopyablePersistentTraits { - public: - typedef Persistent > CopyablePersistent; - - static const bool kResetInDestructor = true; - - template - static void Copy(const Persistent &source, - CopyablePersistent *dest); -}; -``` - -See the V8 documentation for [`CopyablePersistentTraits`](https://v8docs.nodesource.com/node-8.16/da/d5c/structv8_1_1_copyable_persistent_traits.html) for further information. - - -### Nan::Persistent - -A type of `PersistentBase` which allows copy and assignment. Copy, assignment and destructor behavior is controlled by the traits class `M`. - -Definition: - -```c++ -template > -class Persistent; - -template class Persistent : public PersistentBase { - public: - /** - * A Persistent with no storage cell. - */ - Persistent(); - - /** - * Construct a Persistent from a v8::Local. When the v8::Local is non-empty, a - * new storage cell is created pointing to the same object, and no flags are - * set. - */ - template Persistent(v8::Local that); - - /** - * Construct a Persistent from a Persistent. When the Persistent is non-empty, - * a new storage cell is created pointing to the same object, and no flags are - * set. - */ - Persistent(const Persistent &that); - - /** - * The copy constructors and assignment operator create a Persistent exactly - * as the Persistent constructor, but the Copy function from the traits class - * is called, allowing the setting of flags based on the copied Persistent. - */ - Persistent &operator=(const Persistent &that); - - template - Persistent &operator=(const Persistent &that); - - /** - * The destructor will dispose the Persistent based on the kResetInDestructor - * flags in the traits class. Since not calling dispose can result in a - * memory leak, it is recommended to always set this flag. - */ - ~Persistent(); -}; -``` - -See the V8 documentation for [`Persistent`](https://v8docs.nodesource.com/node-8.16/d2/d78/classv8_1_1_persistent.html) for further information. - - -### Nan::Global - -A type of `PersistentBase` which has move semantics. - -```c++ -template class Global : public PersistentBase { - public: - /** - * A Global with no storage cell. - */ - Global(); - - /** - * Construct a Global from a v8::Local. When the v8::Local is non-empty, a new - * storage cell is created pointing to the same object, and no flags are set. - */ - template Global(v8::Local that); - /** - * Construct a Global from a PersistentBase. When the Persistent is non-empty, - * a new storage cell is created pointing to the same object, and no flags are - * set. - */ - template Global(const PersistentBase &that); - - /** - * Pass allows returning globals from functions, etc. - */ - Global Pass(); -}; -``` - -See the V8 documentation for [`Global`](https://v8docs.nodesource.com/node-8.16/d5/d40/classv8_1_1_global.html) for further information. - - -### Nan::WeakCallbackInfo - -`Nan::WeakCallbackInfo` is used as an argument when setting a persistent reference as weak. You may need to free any external resources attached to the object. It is a mirror of `v8:WeakCallbackInfo` as found in newer versions of V8. - -Definition: - -```c++ -template class WeakCallbackInfo { - public: - typedef void (*Callback)(const WeakCallbackInfo& data); - - v8::Isolate *GetIsolate() const; - - /** - * Get the parameter that was associated with the weak handle. - */ - T *GetParameter() const; - - /** - * Get pointer from internal field, index can be 0 or 1. - */ - void *GetInternalField(int index) const; -}; -``` - -Example usage: - -```c++ -void weakCallback(const WeakCallbackInfo &data) { - int *parameter = data.GetParameter(); - delete parameter; -} - -Persistent obj; -int *data = new int(0); -obj.SetWeak(data, callback, WeakCallbackType::kParameter); -``` - -See the V8 documentation for [`WeakCallbackInfo`](https://v8docs.nodesource.com/node-8.16/d8/d06/classv8_1_1_weak_callback_info.html) for further information. - - -### Nan::WeakCallbackType - -Represents the type of a weak callback. -A weak callback of type `kParameter` makes the supplied parameter to `Nan::PersistentBase::SetWeak` available through `WeakCallbackInfo::GetParameter`. -A weak callback of type `kInternalFields` uses up to two internal fields at indices 0 and 1 on the `Nan::PersistentBase` being made weak. -Note that only `v8::Object`s and derivatives can have internal fields. - -Definition: - -```c++ -enum class WeakCallbackType { kParameter, kInternalFields }; -``` diff --git a/node_modules/nan/doc/scopes.md b/node_modules/nan/doc/scopes.md deleted file mode 100644 index 84000ee..0000000 --- a/node_modules/nan/doc/scopes.md +++ /dev/null @@ -1,73 +0,0 @@ -## Scopes - -A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. - -A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. - -The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. - - - Nan::HandleScope - - Nan::EscapableHandleScope - -Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection). - - -### Nan::HandleScope - -A simple wrapper around [`v8::HandleScope`](https://v8docs.nodesource.com/node-8.16/d3/d95/classv8_1_1_handle_scope.html). - -Definition: - -```c++ -class Nan::HandleScope { - public: - Nan::HandleScope(); - static int NumberOfHandles(); -}; -``` - -Allocate a new `Nan::HandleScope` whenever you are creating new V8 JavaScript objects. Note that an implicit `HandleScope` is created for you on JavaScript-accessible methods so you do not need to insert one yourself. - -Example: - -```c++ -// new object is created, it needs a new scope: -void Pointless() { - Nan::HandleScope scope; - v8::Local obj = Nan::New(); -} - -// JavaScript-accessible method already has a HandleScope -NAN_METHOD(Pointless2) { - v8::Local obj = Nan::New(); -} -``` - - -### Nan::EscapableHandleScope - -Similar to [`Nan::HandleScope`](#api_nan_handle_scope) but should be used in cases where a function needs to return a V8 JavaScript type that has been created within it. - -Definition: - -```c++ -class Nan::EscapableHandleScope { - public: - Nan::EscapableHandleScope(); - static int NumberOfHandles(); - template v8::Local Escape(v8::Local value); -} -``` - -Use `Escape(value)` to return the object. - -Example: - -```c++ -v8::Local EmptyObj() { - Nan::EscapableHandleScope scope; - v8::Local obj = Nan::New(); - return scope.Escape(obj); -} -``` - diff --git a/node_modules/nan/doc/script.md b/node_modules/nan/doc/script.md deleted file mode 100644 index 213320a..0000000 --- a/node_modules/nan/doc/script.md +++ /dev/null @@ -1,38 +0,0 @@ -## Script - -NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8. - - - Nan::CompileScript() - - Nan::RunScript() - - - -### Nan::CompileScript() - -A wrapper around [`v8::ScriptCompiler::Compile()`](https://v8docs.nodesource.com/node-8.16/da/da5/classv8_1_1_script_compiler.html#a93f5072a0db55d881b969e9fc98e564b). - -Note that `Nan::BoundScript` is an alias for `v8::Script`. - -Signature: - -```c++ -Nan::MaybeLocal Nan::CompileScript( - v8::Local s, - const v8::ScriptOrigin& origin); -Nan::MaybeLocal Nan::CompileScript(v8::Local s); -``` - - - -### Nan::RunScript() - -Calls `script->Run()` or `script->BindToCurrentContext()->Run(Nan::GetCurrentContext())`. - -Note that `Nan::BoundScript` is an alias for `v8::Script` and `Nan::UnboundScript` is an alias for `v8::UnboundScript` where available and `v8::Script` on older versions of V8. - -Signature: - -```c++ -Nan::MaybeLocal Nan::RunScript(v8::Local script) -Nan::MaybeLocal Nan::RunScript(v8::Local script) -``` diff --git a/node_modules/nan/doc/string_bytes.md b/node_modules/nan/doc/string_bytes.md deleted file mode 100644 index 7c1bd32..0000000 --- a/node_modules/nan/doc/string_bytes.md +++ /dev/null @@ -1,62 +0,0 @@ -## Strings & Bytes - -Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. - - - Nan::Encoding - - Nan::Encode() - - Nan::DecodeBytes() - - Nan::DecodeWrite() - - - -### Nan::Encoding - -An enum representing the supported encoding types. A copy of `node::encoding` that is consistent across versions of Node. - -Definition: - -```c++ -enum Nan::Encoding { ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER } -``` - - - -### Nan::Encode() - -A wrapper around `node::Encode()` that provides a consistent implementation across supported versions of Node. - -Signature: - -```c++ -v8::Local Nan::Encode(const void *buf, - size_t len, - enum Nan::Encoding encoding = BINARY); -``` - - - -### Nan::DecodeBytes() - -A wrapper around `node::DecodeBytes()` that provides a consistent implementation across supported versions of Node. - -Signature: - -```c++ -ssize_t Nan::DecodeBytes(v8::Local val, - enum Nan::Encoding encoding = BINARY); -``` - - - -### Nan::DecodeWrite() - -A wrapper around `node::DecodeWrite()` that provides a consistent implementation across supported versions of Node. - -Signature: - -```c++ -ssize_t Nan::DecodeWrite(char *buf, - size_t len, - v8::Local val, - enum Nan::Encoding encoding = BINARY); -``` diff --git a/node_modules/nan/doc/v8_internals.md b/node_modules/nan/doc/v8_internals.md deleted file mode 100644 index 08dd6d0..0000000 --- a/node_modules/nan/doc/v8_internals.md +++ /dev/null @@ -1,199 +0,0 @@ -## V8 internals - -The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. - - - NAN_GC_CALLBACK() - - Nan::AddGCEpilogueCallback() - - Nan::RemoveGCEpilogueCallback() - - Nan::AddGCPrologueCallback() - - Nan::RemoveGCPrologueCallback() - - Nan::GetHeapStatistics() - - Nan::SetCounterFunction() - - Nan::SetCreateHistogramFunction() - - Nan::SetAddHistogramSampleFunction() - - Nan::IdleNotification() - - Nan::LowMemoryNotification() - - Nan::ContextDisposedNotification() - - Nan::GetInternalFieldPointer() - - Nan::SetInternalFieldPointer() - - Nan::AdjustExternalMemory() - - - -### NAN_GC_CALLBACK(callbackname) - -Use `NAN_GC_CALLBACK` to declare your callbacks for `Nan::AddGCPrologueCallback()` and `Nan::AddGCEpilogueCallback()`. Your new method receives the arguments `v8::GCType type` and `v8::GCCallbackFlags flags`. - -```c++ -static Nan::Persistent callback; - -NAN_GC_CALLBACK(gcPrologueCallback) { - v8::Local argv[] = { Nan::New("prologue").ToLocalChecked() }; - Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(callback), 1, argv); -} - -NAN_METHOD(Hook) { - callback.Reset(To(args[0]).ToLocalChecked()); - Nan::AddGCPrologueCallback(gcPrologueCallback); - info.GetReturnValue().Set(info.Holder()); -} -``` - - -### Nan::AddGCEpilogueCallback() - -Signature: - -```c++ -void Nan::AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback, v8::GCType gc_type_filter = v8::kGCTypeAll) -``` - -Calls V8's [`AddGCEpilogueCallback()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a580f976e4290cead62c2fc4dd396be3e). - - -### Nan::RemoveGCEpilogueCallback() - -Signature: - -```c++ -void Nan::RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback) -``` - -Calls V8's [`RemoveGCEpilogueCallback()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#adca9294555a3908e9f23c7bb0f0f284c). - - -### Nan::AddGCPrologueCallback() - -Signature: - -```c++ -void Nan::AddGCPrologueCallback(v8::Isolate::GCPrologueCallback, v8::GCType gc_type_filter callback) -``` - -Calls V8's [`AddGCPrologueCallback()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a6dbef303603ebdb03da6998794ea05b8). - - -### Nan::RemoveGCPrologueCallback() - -Signature: - -```c++ -void Nan::RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback) -``` - -Calls V8's [`RemoveGCPrologueCallback()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a5f72c7cda21415ce062bbe5c58abe09e). - - -### Nan::GetHeapStatistics() - -Signature: - -```c++ -void Nan::GetHeapStatistics(v8::HeapStatistics *heap_statistics) -``` - -Calls V8's [`GetHeapStatistics()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a5593ac74687b713095c38987e5950b34). - - -### Nan::SetCounterFunction() - -Signature: - -```c++ -void Nan::SetCounterFunction(v8::CounterLookupCallback cb) -``` - -Calls V8's [`SetCounterFunction()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a045d7754e62fa0ec72ae6c259b29af94). - - -### Nan::SetCreateHistogramFunction() - -Signature: - -```c++ -void Nan::SetCreateHistogramFunction(v8::CreateHistogramCallback cb) -``` - -Calls V8's [`SetCreateHistogramFunction()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a542d67e85089cb3f92aadf032f99e732). - - -### Nan::SetAddHistogramSampleFunction() - -Signature: - -```c++ -void Nan::SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) -``` - -Calls V8's [`SetAddHistogramSampleFunction()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#aeb420b690bc2c216882d6fdd00ddd3ea). - - -### Nan::IdleNotification() - -Signature: - -```c++ -bool Nan::IdleNotification(int idle_time_in_ms) -``` - -Calls V8's [`IdleNotification()` or `IdleNotificationDeadline()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#ad6a2a02657f5425ad460060652a5a118) depending on V8 version. - - -### Nan::LowMemoryNotification() - -Signature: - -```c++ -void Nan::LowMemoryNotification() -``` - -Calls V8's [`LowMemoryNotification()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a24647f61d6b41f69668094bdcd6ea91f). - - -### Nan::ContextDisposedNotification() - -Signature: - -```c++ -void Nan::ContextDisposedNotification() -``` - -Calls V8's [`ContextDisposedNotification()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#ad7f5dc559866343fe6cd8db1f134d48b). - - -### Nan::GetInternalFieldPointer() - -Gets a pointer to the internal field with at `index` from a V8 `Object` handle. - -Signature: - -```c++ -void* Nan::GetInternalFieldPointer(v8::Local object, int index) -``` - -Calls the Object's [`GetAlignedPointerFromInternalField()` or `GetPointerFromInternalField()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#a580ea84afb26c005d6762eeb9e3c308f) depending on the version of V8. - - -### Nan::SetInternalFieldPointer() - -Sets the value of the internal field at `index` on a V8 `Object` handle. - -Signature: - -```c++ -void Nan::SetInternalFieldPointer(v8::Local object, int index, void* value) -``` - -Calls the Object's [`SetAlignedPointerInInternalField()` or `SetPointerInInternalField()`](https://v8docs.nodesource.com/node-8.16/db/d85/classv8_1_1_object.html#ab3c57184263cf29963ef0017bec82281) depending on the version of V8. - - -### Nan::AdjustExternalMemory() - -Signature: - -```c++ -int Nan::AdjustExternalMemory(int bytesChange) -``` - -Calls V8's [`AdjustAmountOfExternalAllocatedMemory()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#ae1a59cac60409d3922582c4af675473e). - diff --git a/node_modules/nan/doc/v8_misc.md b/node_modules/nan/doc/v8_misc.md deleted file mode 100644 index 1bd46d3..0000000 --- a/node_modules/nan/doc/v8_misc.md +++ /dev/null @@ -1,85 +0,0 @@ -## Miscellaneous V8 Helpers - - - Nan::Utf8String - - Nan::GetCurrentContext() - - Nan::SetIsolateData() - - Nan::GetIsolateData() - - Nan::TypedArrayContents - - - -### Nan::Utf8String - -Converts an object to a UTF-8-encoded character array. If conversion to a string fails (e.g. due to an exception in the toString() method of the object) then the length() method returns 0 and the * operator returns NULL. The underlying memory used for this object is managed by the object. - -An implementation of [`v8::String::Utf8Value`](https://v8docs.nodesource.com/node-8.16/d4/d1b/classv8_1_1_string_1_1_utf8_value.html) that is consistent across all supported versions of V8. - -Definition: - -```c++ -class Nan::Utf8String { - public: - Nan::Utf8String(v8::Local from); - - int length() const; - - char* operator*(); - const char* operator*() const; -}; -``` - - -### Nan::GetCurrentContext() - -A call to [`v8::Isolate::GetCurrent()->GetCurrentContext()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a81c7a1ed7001ae2a65e89107f75fd053) that works across all supported versions of V8. - -Signature: - -```c++ -v8::Local Nan::GetCurrentContext() -``` - - -### Nan::SetIsolateData() - -A helper to provide a consistent API to [`v8::Isolate#SetData()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#a7acadfe7965997e9c386a05f098fbe36). - -Signature: - -```c++ -void Nan::SetIsolateData(v8::Isolate *isolate, T *data) -``` - - - -### Nan::GetIsolateData() - -A helper to provide a consistent API to [`v8::Isolate#GetData()`](https://v8docs.nodesource.com/node-8.16/d5/dda/classv8_1_1_isolate.html#aabd223436bc1100a787dadaa024c6257). - -Signature: - -```c++ -T *Nan::GetIsolateData(v8::Isolate *isolate) -``` - - -### Nan::TypedArrayContents - -A helper class for accessing the contents of an ArrayBufferView (aka a typedarray) from C++. If the input array is not a valid typedarray, then the data pointer of TypedArrayContents will default to `NULL` and the length will be 0. If the data pointer is not compatible with the alignment requirements of type, an assertion error will fail. - -Note that you must store a reference to the `array` object while you are accessing its contents. - -Definition: - -```c++ -template -class Nan::TypedArrayContents { - public: - TypedArrayContents(v8::Local array); - - size_t length() const; - - T* const operator*(); - const T* const operator*() const; -}; -``` diff --git a/node_modules/nan/include_dirs.js b/node_modules/nan/include_dirs.js deleted file mode 100644 index 4f1dfb4..0000000 --- a/node_modules/nan/include_dirs.js +++ /dev/null @@ -1 +0,0 @@ -console.log(require('path').relative('.', __dirname)); diff --git a/node_modules/nan/nan.h b/node_modules/nan/nan.h deleted file mode 100644 index 648e6e2..0000000 --- a/node_modules/nan/nan.h +++ /dev/null @@ -1,2891 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors: - * - Rod Vagg - * - Benjamin Byholm - * - Trevor Norris - * - Nathan Rajlich - * - Brett Lawson - * - Ben Noordhuis - * - David Siegel - * - Michael Ira Krufky - * - * MIT License - * - * Version 2.14.1: current Node 14.0.0, Node 0.12: 0.12.18, Node 0.10: 0.10.48, iojs: 3.3.1 - * - * See https://github.com/nodejs/nan for the latest update to this file - **********************************************************************************/ - -#ifndef NAN_H_ -#define NAN_H_ - -#include - -#define NODE_0_10_MODULE_VERSION 11 -#define NODE_0_12_MODULE_VERSION 14 -#define ATOM_0_21_MODULE_VERSION 41 -#define IOJS_1_0_MODULE_VERSION 42 -#define IOJS_1_1_MODULE_VERSION 43 -#define IOJS_2_0_MODULE_VERSION 44 -#define IOJS_3_0_MODULE_VERSION 45 -#define NODE_4_0_MODULE_VERSION 46 -#define NODE_5_0_MODULE_VERSION 47 -#define NODE_6_0_MODULE_VERSION 48 -#define NODE_7_0_MODULE_VERSION 51 -#define NODE_8_0_MODULE_VERSION 57 -#define NODE_9_0_MODULE_VERSION 59 -#define NODE_10_0_MODULE_VERSION 64 -#define NODE_11_0_MODULE_VERSION 67 -#define NODE_12_0_MODULE_VERSION 72 -#define NODE_13_0_MODULE_VERSION 79 -#define NODE_14_0_MODULE_VERSION 83 - -#ifdef _MSC_VER -# define NAN_HAS_CPLUSPLUS_11 (_MSC_VER >= 1800) -#else -# define NAN_HAS_CPLUSPLUS_11 (__cplusplus >= 201103L) -#endif - -#if NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION && !NAN_HAS_CPLUSPLUS_11 -# error This version of node/NAN/v8 requires a C++11 compiler -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if defined(_MSC_VER) -# pragma warning( push ) -# pragma warning( disable : 4530 ) -# include -# include -# include -# pragma warning( pop ) -#else -# include -# include -# include -#endif - -// uv helpers -#ifdef UV_VERSION_MAJOR -# ifndef UV_VERSION_PATCH -# define UV_VERSION_PATCH 0 -# endif -# define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \ - (UV_VERSION_MINOR << 8) | \ - (UV_VERSION_PATCH)) -#else -# define NAUV_UVVERSION 0x000b00 -#endif - -#if NAUV_UVVERSION < 0x000b0b -# ifdef WIN32 -# include -# else -# include -# endif -#endif - -namespace Nan { - -#define NAN_CONCAT(a, b) NAN_CONCAT_HELPER(a, b) -#define NAN_CONCAT_HELPER(a, b) a##b - -#define NAN_INLINE inline // TODO(bnoordhuis) Remove in v3.0.0. - -#if defined(__GNUC__) && \ - !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) -# define NAN_DEPRECATED __attribute__((deprecated)) -#elif defined(_MSC_VER) && \ - !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) -# define NAN_DEPRECATED __declspec(deprecated) -#else -# define NAN_DEPRECATED -#endif - -#if NAN_HAS_CPLUSPLUS_11 -# define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete; -# define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete; -# define NAN_DISALLOW_MOVE(CLASS) \ - CLASS(CLASS&&) = delete; /* NOLINT(build/c++11) */ \ - void operator=(CLASS&&) = delete; -#else -# define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&); -# define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&); -# define NAN_DISALLOW_MOVE(CLASS) -#endif - -#define NAN_DISALLOW_ASSIGN_COPY(CLASS) \ - NAN_DISALLOW_ASSIGN(CLASS) \ - NAN_DISALLOW_COPY(CLASS) - -#define NAN_DISALLOW_ASSIGN_MOVE(CLASS) \ - NAN_DISALLOW_ASSIGN(CLASS) \ - NAN_DISALLOW_MOVE(CLASS) - -#define NAN_DISALLOW_COPY_MOVE(CLASS) \ - NAN_DISALLOW_COPY(CLASS) \ - NAN_DISALLOW_MOVE(CLASS) - -#define NAN_DISALLOW_ASSIGN_COPY_MOVE(CLASS) \ - NAN_DISALLOW_ASSIGN(CLASS) \ - NAN_DISALLOW_COPY(CLASS) \ - NAN_DISALLOW_MOVE(CLASS) - -#define TYPE_CHECK(T, S) \ - while (false) { \ - *(static_cast(0)) = static_cast(0); \ - } - -//=== RegistrationFunction ===================================================== - -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - typedef v8::Handle ADDON_REGISTER_FUNCTION_ARGS_TYPE; -#else - typedef v8::Local ADDON_REGISTER_FUNCTION_ARGS_TYPE; -#endif - -#define NAN_MODULE_INIT(name) \ - void name(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) - -#if NODE_MAJOR_VERSION >= 10 || \ - NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3 -#define NAN_MODULE_WORKER_ENABLED(module_name, registration) \ - extern "C" NODE_MODULE_EXPORT void \ - NAN_CONCAT(node_register_module_v, NODE_MODULE_VERSION)( \ - v8::Local exports, v8::Local module, \ - v8::Local context) \ - { \ - registration(exports); \ - } -#else -#define NAN_MODULE_WORKER_ENABLED(module_name, registration) \ - NODE_MODULE(module_name, registration) -#endif - -//=== CallbackInfo ============================================================= - -#include "nan_callbacks.h" // NOLINT(build/include) - -//============================================================================== - -#if (NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION) -typedef v8::Script UnboundScript; -typedef v8::Script BoundScript; -#else -typedef v8::UnboundScript UnboundScript; -typedef v8::Script BoundScript; -#endif - -#if (NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION) -typedef v8::String::ExternalAsciiStringResource - ExternalOneByteStringResource; -#else -typedef v8::String::ExternalOneByteStringResource - ExternalOneByteStringResource; -#endif - -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) -template -class NonCopyablePersistentTraits : - public v8::NonCopyablePersistentTraits {}; -template -class CopyablePersistentTraits : - public v8::CopyablePersistentTraits {}; - -template -class PersistentBase : - public v8::PersistentBase {}; - -template > -class Persistent; -#else -template class NonCopyablePersistentTraits; -template class PersistentBase; -template class WeakCallbackData; -template > -class Persistent; -#endif // NODE_MODULE_VERSION - -template -class Maybe { - public: - inline bool IsNothing() const { return !has_value_; } - inline bool IsJust() const { return has_value_; } - - inline T ToChecked() const { return FromJust(); } - inline void Check() const { FromJust(); } - - inline bool To(T* out) const { - if (IsJust()) *out = value_; - return IsJust(); - } - - inline T FromJust() const { -#if defined(V8_ENABLE_CHECKS) - assert(IsJust() && "FromJust is Nothing"); -#endif // V8_ENABLE_CHECKS - return value_; - } - - inline T FromMaybe(const T& default_value) const { - return has_value_ ? value_ : default_value; - } - - inline bool operator==(const Maybe &other) const { - return (IsJust() == other.IsJust()) && - (!IsJust() || FromJust() == other.FromJust()); - } - - inline bool operator!=(const Maybe &other) const { - return !operator==(other); - } - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - // Allow implicit conversions from v8::Maybe to Nan::Maybe. - Maybe(const v8::Maybe& that) // NOLINT(runtime/explicit) - : has_value_(that.IsJust()) - , value_(that.FromMaybe(T())) {} -#endif - - private: - Maybe() : has_value_(false) {} - explicit Maybe(const T& t) : has_value_(true), value_(t) {} - bool has_value_; - T value_; - - template - friend Maybe Nothing(); - template - friend Maybe Just(const U& u); -}; - -template -inline Maybe Nothing() { - return Maybe(); -} - -template -inline Maybe Just(const T& t) { - return Maybe(t); -} - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -# include "nan_maybe_43_inl.h" // NOLINT(build/include) -#else -# include "nan_maybe_pre_43_inl.h" // NOLINT(build/include) -#endif - -#include "nan_converters.h" // NOLINT(build/include) -#include "nan_new.h" // NOLINT(build/include) - -#if NAUV_UVVERSION < 0x000b17 -#define NAUV_WORK_CB(func) \ - void func(uv_async_t *async, int) -#else -#define NAUV_WORK_CB(func) \ - void func(uv_async_t *async) -#endif - -#if NAUV_UVVERSION >= 0x000b0b - -typedef uv_key_t nauv_key_t; - -inline int nauv_key_create(nauv_key_t *key) { - return uv_key_create(key); -} - -inline void nauv_key_delete(nauv_key_t *key) { - uv_key_delete(key); -} - -inline void* nauv_key_get(nauv_key_t *key) { - return uv_key_get(key); -} - -inline void nauv_key_set(nauv_key_t *key, void *value) { - uv_key_set(key, value); -} - -#else - -/* Implement thread local storage for older versions of libuv. - * This is essentially a backport of libuv commit 5d2434bf - * written by Ben Noordhuis, adjusted for names and inline. - */ - -#ifndef WIN32 - -typedef pthread_key_t nauv_key_t; - -inline int nauv_key_create(nauv_key_t* key) { - return -pthread_key_create(key, NULL); -} - -inline void nauv_key_delete(nauv_key_t* key) { - if (pthread_key_delete(*key)) - abort(); -} - -inline void* nauv_key_get(nauv_key_t* key) { - return pthread_getspecific(*key); -} - -inline void nauv_key_set(nauv_key_t* key, void* value) { - if (pthread_setspecific(*key, value)) - abort(); -} - -#else - -typedef struct { - DWORD tls_index; -} nauv_key_t; - -inline int nauv_key_create(nauv_key_t* key) { - key->tls_index = TlsAlloc(); - if (key->tls_index == TLS_OUT_OF_INDEXES) - return UV_ENOMEM; - return 0; -} - -inline void nauv_key_delete(nauv_key_t* key) { - if (TlsFree(key->tls_index) == FALSE) - abort(); - key->tls_index = TLS_OUT_OF_INDEXES; -} - -inline void* nauv_key_get(nauv_key_t* key) { - void* value = TlsGetValue(key->tls_index); - if (value == NULL) - if (GetLastError() != ERROR_SUCCESS) - abort(); - return value; -} - -inline void nauv_key_set(nauv_key_t* key, void* value) { - if (TlsSetValue(key->tls_index, value) == FALSE) - abort(); -} - -#endif -#endif - -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION -template -v8::Local New(v8::Handle); -#endif - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - typedef v8::WeakCallbackType WeakCallbackType; -#else -struct WeakCallbackType { - enum E {kParameter, kInternalFields}; - E type; - WeakCallbackType(E other) : type(other) {} // NOLINT(runtime/explicit) - inline bool operator==(E other) { return other == this->type; } - inline bool operator!=(E other) { return !operator==(other); } -}; -#endif - -template class WeakCallbackInfo; - -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION -# include "nan_persistent_12_inl.h" // NOLINT(build/include) -#else -# include "nan_persistent_pre_12_inl.h" // NOLINT(build/include) -#endif - -namespace imp { - static const size_t kMaxLength = 0x3fffffff; - // v8::String::REPLACE_INVALID_UTF8 was introduced - // in node.js v0.10.29 and v0.8.27. -#if NODE_MAJOR_VERSION > 0 || \ - NODE_MINOR_VERSION > 10 || \ - NODE_MINOR_VERSION == 10 && NODE_PATCH_VERSION >= 29 || \ - NODE_MINOR_VERSION == 8 && NODE_PATCH_VERSION >= 27 - static const unsigned kReplaceInvalidUtf8 = v8::String::REPLACE_INVALID_UTF8; -#else - static const unsigned kReplaceInvalidUtf8 = 0; -#endif -} // end of namespace imp - -//=== HandleScope ============================================================== - -class HandleScope { - v8::HandleScope scope; - - public: -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - inline HandleScope() : scope(v8::Isolate::GetCurrent()) {} - inline static int NumberOfHandles() { - return v8::HandleScope::NumberOfHandles(v8::Isolate::GetCurrent()); - } -#else - inline HandleScope() : scope() {} - inline static int NumberOfHandles() { - return v8::HandleScope::NumberOfHandles(); - } -#endif - - private: - // Make it hard to create heap-allocated or illegal handle scopes by - // disallowing certain operations. - HandleScope(const HandleScope &); - void operator=(const HandleScope &); - void *operator new(size_t size); - void operator delete(void *, size_t) { - abort(); - } -}; - -class EscapableHandleScope { - public: -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - inline EscapableHandleScope() : scope(v8::Isolate::GetCurrent()) {} - - inline static int NumberOfHandles() { - return v8::EscapableHandleScope::NumberOfHandles(v8::Isolate::GetCurrent()); - } - - template - inline v8::Local Escape(v8::Local value) { - return scope.Escape(value); - } - - private: - v8::EscapableHandleScope scope; -#else - inline EscapableHandleScope() : scope() {} - - inline static int NumberOfHandles() { - return v8::HandleScope::NumberOfHandles(); - } - - template - inline v8::Local Escape(v8::Local value) { - return scope.Close(value); - } - - private: - v8::HandleScope scope; -#endif - - private: - // Make it hard to create heap-allocated or illegal handle scopes by - // disallowing certain operations. - EscapableHandleScope(const EscapableHandleScope &); - void operator=(const EscapableHandleScope &); - void *operator new(size_t size); - void operator delete(void *, size_t) { - abort(); - } -}; - -//=== TryCatch ================================================================= - -class TryCatch { - v8::TryCatch try_catch_; - friend void FatalException(const TryCatch&); - - public: -#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION - TryCatch() : try_catch_(v8::Isolate::GetCurrent()) {} -#endif - - inline bool HasCaught() const { return try_catch_.HasCaught(); } - - inline bool CanContinue() const { return try_catch_.CanContinue(); } - - inline v8::Local ReThrow() { -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - return New(try_catch_.ReThrow()); -#else - return try_catch_.ReThrow(); -#endif - } - - inline v8::Local Exception() const { - return try_catch_.Exception(); - } - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - inline v8::MaybeLocal StackTrace() const { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(try_catch_.StackTrace(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); - } -#else - inline MaybeLocal StackTrace() const { - return try_catch_.StackTrace(); - } -#endif - - inline v8::Local Message() const { - return try_catch_.Message(); - } - - inline void Reset() { try_catch_.Reset(); } - - inline void SetVerbose(bool value) { try_catch_.SetVerbose(value); } - - inline void SetCaptureMessage(bool value) { - try_catch_.SetCaptureMessage(value); - } -}; - -v8::Local MakeCallback(v8::Local target, - v8::Local func, - int argc, - v8::Local* argv); -v8::Local MakeCallback(v8::Local target, - v8::Local symbol, - int argc, - v8::Local* argv); -v8::Local MakeCallback(v8::Local target, - const char* method, - int argc, - v8::Local* argv); - -// === AsyncResource =========================================================== - -class AsyncResource { - public: - AsyncResource( - v8::Local name - , v8::Local resource = New()) { -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - - if (resource.IsEmpty()) { - resource = New(); - } - - context = node::EmitAsyncInit(isolate, resource, name); -#endif - } - - AsyncResource( - const char* name - , v8::Local resource = New()) { -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - - if (resource.IsEmpty()) { - resource = New(); - } - - v8::Local name_string = - New(name).ToLocalChecked(); - context = node::EmitAsyncInit(isolate, resource, name_string); -#endif - } - - ~AsyncResource() { -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - node::EmitAsyncDestroy(isolate, context); -#endif - } - - inline MaybeLocal runInAsyncScope( - v8::Local target - , v8::Local func - , int argc - , v8::Local* argv) { -#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION - return MakeCallback(target, func, argc, argv); -#else - return node::MakeCallback( - v8::Isolate::GetCurrent(), target, func, argc, argv, context); -#endif - } - - inline MaybeLocal runInAsyncScope( - v8::Local target - , v8::Local symbol - , int argc - , v8::Local* argv) { -#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION - return MakeCallback(target, symbol, argc, argv); -#else - return node::MakeCallback( - v8::Isolate::GetCurrent(), target, symbol, argc, argv, context); -#endif - } - - inline MaybeLocal runInAsyncScope( - v8::Local target - , const char* method - , int argc - , v8::Local* argv) { -#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION - return MakeCallback(target, method, argc, argv); -#else - return node::MakeCallback( - v8::Isolate::GetCurrent(), target, method, argc, argv, context); -#endif - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncResource) -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - node::async_context context; -#endif -}; - -inline uv_loop_t* GetCurrentEventLoop() { -#if NODE_MAJOR_VERSION >= 10 || \ - NODE_MAJOR_VERSION == 9 && NODE_MINOR_VERSION >= 3 || \ - NODE_MAJOR_VERSION == 8 && NODE_MINOR_VERSION >= 10 - return node::GetCurrentEventLoop(v8::Isolate::GetCurrent()); -#else - return uv_default_loop(); -#endif -} - -//============ ================================================================= - -/* node 0.12 */ -#if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION - inline - void SetCounterFunction(v8::CounterLookupCallback cb) { - v8::Isolate::GetCurrent()->SetCounterFunction(cb); - } - - inline - void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) { - v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb); - } - - inline - void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { - v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb); - } - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - inline bool IdleNotification(int idle_time_in_ms) { - return v8::Isolate::GetCurrent()->IdleNotificationDeadline( - idle_time_in_ms * 0.001); - } -# else - inline bool IdleNotification(int idle_time_in_ms) { - return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms); - } -#endif - - inline void LowMemoryNotification() { - v8::Isolate::GetCurrent()->LowMemoryNotification(); - } - - inline void ContextDisposedNotification() { - v8::Isolate::GetCurrent()->ContextDisposedNotification(); - } -#else - inline - void SetCounterFunction(v8::CounterLookupCallback cb) { - v8::V8::SetCounterFunction(cb); - } - - inline - void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) { - v8::V8::SetCreateHistogramFunction(cb); - } - - inline - void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { - v8::V8::SetAddHistogramSampleFunction(cb); - } - - inline bool IdleNotification(int idle_time_in_ms) { - return v8::V8::IdleNotification(idle_time_in_ms); - } - - inline void LowMemoryNotification() { - v8::V8::LowMemoryNotification(); - } - - inline void ContextDisposedNotification() { - v8::V8::ContextDisposedNotification(); - } -#endif - -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) // Node 0.12 - inline v8::Local Undefined() { -# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(v8::Undefined(v8::Isolate::GetCurrent()))); -# else - return v8::Undefined(v8::Isolate::GetCurrent()); -# endif - } - - inline v8::Local Null() { -# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(v8::Null(v8::Isolate::GetCurrent()))); -# else - return v8::Null(v8::Isolate::GetCurrent()); -# endif - } - - inline v8::Local True() { -# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(v8::True(v8::Isolate::GetCurrent()))); -# else - return v8::True(v8::Isolate::GetCurrent()); -# endif - } - - inline v8::Local False() { -# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(v8::False(v8::Isolate::GetCurrent()))); -# else - return v8::False(v8::Isolate::GetCurrent()); -# endif - } - - inline v8::Local EmptyString() { - return v8::String::Empty(v8::Isolate::GetCurrent()); - } - - inline int AdjustExternalMemory(int bc) { - return static_cast( - v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc)); - } - - inline void SetTemplate( - v8::Local templ - , const char *name - , v8::Local value) { - templ->Set(v8::Isolate::GetCurrent(), name, value); - } - - inline void SetTemplate( - v8::Local templ - , v8::Local name - , v8::Local value - , v8::PropertyAttribute attributes) { - templ->Set(name, value, attributes); - } - - inline v8::Local GetCurrentContext() { - return v8::Isolate::GetCurrent()->GetCurrentContext(); - } - - inline void* GetInternalFieldPointer( - v8::Local object - , int index) { - return object->GetAlignedPointerFromInternalField(index); - } - - inline void SetInternalFieldPointer( - v8::Local object - , int index - , void* value) { - object->SetAlignedPointerInInternalField(index, value); - } - -# define NAN_GC_CALLBACK(name) \ - void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags) - -#if NODE_MODULE_VERSION <= NODE_4_0_MODULE_VERSION - typedef v8::Isolate::GCEpilogueCallback GCEpilogueCallback; - typedef v8::Isolate::GCPrologueCallback GCPrologueCallback; -#else - typedef v8::Isolate::GCCallback GCEpilogueCallback; - typedef v8::Isolate::GCCallback GCPrologueCallback; -#endif - - inline void AddGCEpilogueCallback( - GCEpilogueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter); - } - - inline void RemoveGCEpilogueCallback( - GCEpilogueCallback callback) { - v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback); - } - - inline void AddGCPrologueCallback( - GCPrologueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter); - } - - inline void RemoveGCPrologueCallback( - GCPrologueCallback callback) { - v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback); - } - - inline void GetHeapStatistics( - v8::HeapStatistics *heap_statistics) { - v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics); - } - -# define X(NAME) \ - inline v8::Local NAME(const char *msg) { \ - EscapableHandleScope scope; \ - return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \ - } \ - \ - inline \ - v8::Local NAME(v8::Local msg) { \ - return v8::Exception::NAME(msg); \ - } \ - \ - inline void Throw ## NAME(const char *msg) { \ - HandleScope scope; \ - v8::Isolate::GetCurrent()->ThrowException( \ - v8::Exception::NAME(New(msg).ToLocalChecked())); \ - } \ - \ - inline void Throw ## NAME(v8::Local msg) { \ - HandleScope scope; \ - v8::Isolate::GetCurrent()->ThrowException( \ - v8::Exception::NAME(msg)); \ - } - - X(Error) - X(RangeError) - X(ReferenceError) - X(SyntaxError) - X(TypeError) - -# undef X - - inline void ThrowError(v8::Local error) { - v8::Isolate::GetCurrent()->ThrowException(error); - } - - inline MaybeLocal NewBuffer( - char *data - , size_t length -#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION - , node::Buffer::FreeCallback callback -#else - , node::smalloc::FreeCallback callback -#endif - , void *hint - ) { - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(length <= imp::kMaxLength && "too large buffer"); -#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION - return node::Buffer::New( - v8::Isolate::GetCurrent(), data, length, callback, hint); -#else - return node::Buffer::New(v8::Isolate::GetCurrent(), data, length, callback, - hint); -#endif - } - - inline MaybeLocal CopyBuffer( - const char *data - , uint32_t size - ) { - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(size <= imp::kMaxLength && "too large buffer"); -#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION - return node::Buffer::Copy( - v8::Isolate::GetCurrent(), data, size); -#else - return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); -#endif - } - - inline MaybeLocal NewBuffer(uint32_t size) { - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(size <= imp::kMaxLength && "too large buffer"); -#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION - return node::Buffer::New( - v8::Isolate::GetCurrent(), size); -#else - return node::Buffer::New(v8::Isolate::GetCurrent(), size); -#endif - } - - inline MaybeLocal NewBuffer( - char* data - , uint32_t size - ) { - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(size <= imp::kMaxLength && "too large buffer"); -#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION - return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); -#else - return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size); -#endif - } - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - inline MaybeLocal - NewOneByteString(const uint8_t * value, int length = -1) { - return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value, - v8::NewStringType::kNormal, length); - } - - inline MaybeLocal CompileScript( - v8::Local s - , const v8::ScriptOrigin& origin - ) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::ScriptCompiler::Source source(s, origin); - return scope.Escape( - v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source) - .FromMaybe(v8::Local())); - } - - inline MaybeLocal CompileScript( - v8::Local s - ) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::ScriptCompiler::Source source(s); - return scope.Escape( - v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source) - .FromMaybe(v8::Local())); - } - - inline MaybeLocal RunScript( - v8::Local script - ) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(script->BindToCurrentContext() - ->Run(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); - } - - inline MaybeLocal RunScript( - v8::Local script - ) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(script->Run(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); - } -#else - inline MaybeLocal - NewOneByteString(const uint8_t * value, int length = -1) { - return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); - } - - inline MaybeLocal CompileScript( - v8::Local s - , const v8::ScriptOrigin& origin - ) { - v8::ScriptCompiler::Source source(s, origin); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); - } - - inline MaybeLocal CompileScript( - v8::Local s - ) { - v8::ScriptCompiler::Source source(s); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); - } - - inline MaybeLocal RunScript( - v8::Local script - ) { - EscapableHandleScope scope; - return scope.Escape(script->BindToCurrentContext()->Run()); - } - - inline MaybeLocal RunScript( - v8::Local script - ) { - return script->Run(); - } -#endif - - NAN_DEPRECATED inline v8::Local MakeCallback( - v8::Local target - , v8::Local func - , int argc - , v8::Local* argv) { -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(node::MakeCallback( - v8::Isolate::GetCurrent(), target, func, argc, argv))); -#else -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource res("nan:makeCallback"); - return res.runInAsyncScope(target, func, argc, argv) - .FromMaybe(v8::Local()); -# else - return node::MakeCallback( - v8::Isolate::GetCurrent(), target, func, argc, argv); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - } - - NAN_DEPRECATED inline v8::Local MakeCallback( - v8::Local target - , v8::Local symbol - , int argc - , v8::Local* argv) { -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(node::MakeCallback( - v8::Isolate::GetCurrent(), target, symbol, argc, argv))); -#else -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource res("nan:makeCallback"); - return res.runInAsyncScope(target, symbol, argc, argv) - .FromMaybe(v8::Local()); -# else - return node::MakeCallback( - v8::Isolate::GetCurrent(), target, symbol, argc, argv); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - } - - NAN_DEPRECATED inline v8::Local MakeCallback( - v8::Local target - , const char* method - , int argc - , v8::Local* argv) { -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - return scope.Escape(New(node::MakeCallback( - v8::Isolate::GetCurrent(), target, method, argc, argv))); -#else -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource res("nan:makeCallback"); - return res.runInAsyncScope(target, method, argc, argv) - .FromMaybe(v8::Local()); -# else - return node::MakeCallback( - v8::Isolate::GetCurrent(), target, method, argc, argv); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - } - - inline void FatalException(const TryCatch& try_catch) { - node::FatalException(v8::Isolate::GetCurrent(), try_catch.try_catch_); - } - - inline v8::Local ErrnoException( - int errorno - , const char* syscall = NULL - , const char* message = NULL - , const char* path = NULL) { - return node::ErrnoException(v8::Isolate::GetCurrent(), errorno, syscall, - message, path); - } - - NAN_DEPRECATED inline v8::Local NanErrnoException( - int errorno - , const char* syscall = NULL - , const char* message = NULL - , const char* path = NULL) { - return ErrnoException(errorno, syscall, message, path); - } - - template - inline void SetIsolateData( - v8::Isolate *isolate - , T *data - ) { - isolate->SetData(0, data); - } - - template - inline T *GetIsolateData( - v8::Isolate *isolate - ) { - return static_cast(isolate->GetData(0)); - } - -class Utf8String { - public: - inline explicit Utf8String(v8::Local from) : - length_(0), str_(str_st_) { - HandleScope scope; - if (!from.IsEmpty()) { -#if NODE_MAJOR_VERSION >= 10 - v8::Local context = GetCurrentContext(); - v8::Local string = - from->ToString(context).FromMaybe(v8::Local()); -#else - v8::Local string = from->ToString(); -#endif - if (!string.IsEmpty()) { - size_t len = 3 * string->Length() + 1; - assert(len <= INT_MAX); - if (len > sizeof (str_st_)) { - str_ = static_cast(malloc(len)); - assert(str_ != 0); - } - const int flags = - v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8; -#if NODE_MAJOR_VERSION >= 11 - length_ = string->WriteUtf8(v8::Isolate::GetCurrent(), str_, - static_cast(len), 0, flags); -#else - // See https://github.com/nodejs/nan/issues/832. - // Disable the warning as there is no way around it. -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4996) -#endif -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#endif - length_ = string->WriteUtf8(str_, static_cast(len), 0, flags); -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif -#ifdef _MSC_VER -#pragma warning(pop) -#endif -#endif // NODE_MAJOR_VERSION < 11 - str_[length_] = '\0'; - } - } - } - - inline int length() const { - return length_; - } - - inline char* operator*() { return str_; } - inline const char* operator*() const { return str_; } - - inline ~Utf8String() { - if (str_ != str_st_) { - free(str_); - } - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String) - - int length_; - char *str_; - char str_st_[1024]; -}; - -#else // Node 0.8 and 0.10 - inline v8::Local Undefined() { - EscapableHandleScope scope; - return scope.Escape(New(v8::Undefined())); - } - - inline v8::Local Null() { - EscapableHandleScope scope; - return scope.Escape(New(v8::Null())); - } - - inline v8::Local True() { - EscapableHandleScope scope; - return scope.Escape(New(v8::True())); - } - - inline v8::Local False() { - EscapableHandleScope scope; - return scope.Escape(New(v8::False())); - } - - inline v8::Local EmptyString() { - return v8::String::Empty(); - } - - inline int AdjustExternalMemory(int bc) { - return static_cast(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc)); - } - - inline void SetTemplate( - v8::Local templ - , const char *name - , v8::Local value) { - templ->Set(name, value); - } - - inline void SetTemplate( - v8::Local templ - , v8::Local name - , v8::Local value - , v8::PropertyAttribute attributes) { - templ->Set(name, value, attributes); - } - - inline v8::Local GetCurrentContext() { - return v8::Context::GetCurrent(); - } - - inline void* GetInternalFieldPointer( - v8::Local object - , int index) { - return object->GetPointerFromInternalField(index); - } - - inline void SetInternalFieldPointer( - v8::Local object - , int index - , void* value) { - object->SetPointerInInternalField(index, value); - } - -# define NAN_GC_CALLBACK(name) \ - void name(v8::GCType type, v8::GCCallbackFlags flags) - - inline void AddGCEpilogueCallback( - v8::GCEpilogueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::V8::AddGCEpilogueCallback(callback, gc_type_filter); - } - inline void RemoveGCEpilogueCallback( - v8::GCEpilogueCallback callback) { - v8::V8::RemoveGCEpilogueCallback(callback); - } - inline void AddGCPrologueCallback( - v8::GCPrologueCallback callback - , v8::GCType gc_type_filter = v8::kGCTypeAll) { - v8::V8::AddGCPrologueCallback(callback, gc_type_filter); - } - inline void RemoveGCPrologueCallback( - v8::GCPrologueCallback callback) { - v8::V8::RemoveGCPrologueCallback(callback); - } - inline void GetHeapStatistics( - v8::HeapStatistics *heap_statistics) { - v8::V8::GetHeapStatistics(heap_statistics); - } - -# define X(NAME) \ - inline v8::Local NAME(const char *msg) { \ - EscapableHandleScope scope; \ - return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \ - } \ - \ - inline \ - v8::Local NAME(v8::Local msg) { \ - return v8::Exception::NAME(msg); \ - } \ - \ - inline void Throw ## NAME(const char *msg) { \ - HandleScope scope; \ - v8::ThrowException(v8::Exception::NAME(New(msg).ToLocalChecked())); \ - } \ - \ - inline \ - void Throw ## NAME(v8::Local errmsg) { \ - HandleScope scope; \ - v8::ThrowException(v8::Exception::NAME(errmsg)); \ - } - - X(Error) - X(RangeError) - X(ReferenceError) - X(SyntaxError) - X(TypeError) - -# undef X - - inline void ThrowError(v8::Local error) { - v8::ThrowException(error); - } - - inline MaybeLocal NewBuffer( - char *data - , size_t length - , node::Buffer::free_callback callback - , void *hint - ) { - EscapableHandleScope scope; - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(length <= imp::kMaxLength && "too large buffer"); - return scope.Escape( - New(node::Buffer::New(data, length, callback, hint)->handle_)); - } - - inline MaybeLocal CopyBuffer( - const char *data - , uint32_t size - ) { - EscapableHandleScope scope; - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(size <= imp::kMaxLength && "too large buffer"); -#if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION - return scope.Escape(New(node::Buffer::New(data, size)->handle_)); -#else - return scope.Escape( - New(node::Buffer::New(const_cast(data), size)->handle_)); -#endif - } - - inline MaybeLocal NewBuffer(uint32_t size) { - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - EscapableHandleScope scope; - assert(size <= imp::kMaxLength && "too large buffer"); - return scope.Escape(New(node::Buffer::New(size)->handle_)); - } - - inline void FreeData(char *data, void *hint) { - (void) hint; // unused - delete[] data; - } - - inline MaybeLocal NewBuffer( - char* data - , uint32_t size - ) { - EscapableHandleScope scope; - // arbitrary buffer lengths requires - // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION - assert(size <= imp::kMaxLength && "too large buffer"); - return scope.Escape( - New(node::Buffer::New(data, size, FreeData, NULL)->handle_)); - } - -namespace imp { -inline void -widenString(std::vector *ws, const uint8_t *s, int l) { - size_t len = static_cast(l); - if (l < 0) { - len = strlen(reinterpret_cast(s)); - } - assert(len <= INT_MAX && "string too long"); - ws->resize(len); - std::copy(s, s + len, ws->begin()); // NOLINT(build/include_what_you_use) -} -} // end of namespace imp - - inline MaybeLocal - NewOneByteString(const uint8_t * value, int length = -1) { - std::vector wideString; // NOLINT(build/include_what_you_use) - imp::widenString(&wideString, value, length); - return v8::String::New(wideString.data(), - static_cast(wideString.size())); - } - - inline MaybeLocal CompileScript( - v8::Local s - , const v8::ScriptOrigin& origin - ) { - return v8::Script::Compile(s, const_cast(&origin)); - } - - inline MaybeLocal CompileScript( - v8::Local s - ) { - return v8::Script::Compile(s); - } - - inline - MaybeLocal RunScript(v8::Local script) { - return script->Run(); - } - - inline v8::Local MakeCallback( - v8::Local target - , v8::Local func - , int argc - , v8::Local* argv) { - v8::HandleScope scope; - return scope.Close(New(node::MakeCallback(target, func, argc, argv))); - } - - inline v8::Local MakeCallback( - v8::Local target - , v8::Local symbol - , int argc - , v8::Local* argv) { - v8::HandleScope scope; - return scope.Close(New(node::MakeCallback(target, symbol, argc, argv))); - } - - inline v8::Local MakeCallback( - v8::Local target - , const char* method - , int argc - , v8::Local* argv) { - v8::HandleScope scope; - return scope.Close(New(node::MakeCallback(target, method, argc, argv))); - } - - inline void FatalException(const TryCatch& try_catch) { - node::FatalException(const_cast(try_catch.try_catch_)); - } - - inline v8::Local ErrnoException( - int errorno - , const char* syscall = NULL - , const char* message = NULL - , const char* path = NULL) { - return node::ErrnoException(errorno, syscall, message, path); - } - - NAN_DEPRECATED inline v8::Local NanErrnoException( - int errorno - , const char* syscall = NULL - , const char* message = NULL - , const char* path = NULL) { - return ErrnoException(errorno, syscall, message, path); - } - - - template - inline void SetIsolateData( - v8::Isolate *isolate - , T *data - ) { - isolate->SetData(data); - } - - template - inline T *GetIsolateData( - v8::Isolate *isolate - ) { - return static_cast(isolate->GetData()); - } - -class Utf8String { - public: - inline explicit Utf8String(v8::Local from) : - length_(0), str_(str_st_) { - v8::HandleScope scope; - if (!from.IsEmpty()) { - v8::Local string = from->ToString(); - if (!string.IsEmpty()) { - size_t len = 3 * string->Length() + 1; - assert(len <= INT_MAX); - if (len > sizeof (str_st_)) { - str_ = static_cast(malloc(len)); - assert(str_ != 0); - } - const int flags = - v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8; - length_ = string->WriteUtf8(str_, static_cast(len), 0, flags); - str_[length_] = '\0'; - } - } - } - - inline int length() const { - return length_; - } - - inline char* operator*() { return str_; } - inline const char* operator*() const { return str_; } - - inline ~Utf8String() { - if (str_ != str_st_) { - free(str_); - } - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String) - - int length_; - char *str_; - char str_st_[1024]; -}; - -#endif // NODE_MODULE_VERSION - -typedef void (*FreeCallback)(char *data, void *hint); - -typedef const FunctionCallbackInfo& NAN_METHOD_ARGS_TYPE; -typedef void NAN_METHOD_RETURN_TYPE; - -typedef const PropertyCallbackInfo& NAN_GETTER_ARGS_TYPE; -typedef void NAN_GETTER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& NAN_SETTER_ARGS_TYPE; -typedef void NAN_SETTER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_PROPERTY_GETTER_ARGS_TYPE; -typedef void NAN_PROPERTY_GETTER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_PROPERTY_SETTER_ARGS_TYPE; -typedef void NAN_PROPERTY_SETTER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_PROPERTY_ENUMERATOR_ARGS_TYPE; -typedef void NAN_PROPERTY_ENUMERATOR_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_PROPERTY_DELETER_ARGS_TYPE; -typedef void NAN_PROPERTY_DELETER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_PROPERTY_QUERY_ARGS_TYPE; -typedef void NAN_PROPERTY_QUERY_RETURN_TYPE; - -typedef const PropertyCallbackInfo& NAN_INDEX_GETTER_ARGS_TYPE; -typedef void NAN_INDEX_GETTER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& NAN_INDEX_SETTER_ARGS_TYPE; -typedef void NAN_INDEX_SETTER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_INDEX_ENUMERATOR_ARGS_TYPE; -typedef void NAN_INDEX_ENUMERATOR_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_INDEX_DELETER_ARGS_TYPE; -typedef void NAN_INDEX_DELETER_RETURN_TYPE; - -typedef const PropertyCallbackInfo& - NAN_INDEX_QUERY_ARGS_TYPE; -typedef void NAN_INDEX_QUERY_RETURN_TYPE; - -#define NAN_METHOD(name) \ - Nan::NAN_METHOD_RETURN_TYPE name(Nan::NAN_METHOD_ARGS_TYPE info) -#define NAN_GETTER(name) \ - Nan::NAN_GETTER_RETURN_TYPE name( \ - v8::Local property \ - , Nan::NAN_GETTER_ARGS_TYPE info) -#define NAN_SETTER(name) \ - Nan::NAN_SETTER_RETURN_TYPE name( \ - v8::Local property \ - , v8::Local value \ - , Nan::NAN_SETTER_ARGS_TYPE info) -#define NAN_PROPERTY_GETTER(name) \ - Nan::NAN_PROPERTY_GETTER_RETURN_TYPE name( \ - v8::Local property \ - , Nan::NAN_PROPERTY_GETTER_ARGS_TYPE info) -#define NAN_PROPERTY_SETTER(name) \ - Nan::NAN_PROPERTY_SETTER_RETURN_TYPE name( \ - v8::Local property \ - , v8::Local value \ - , Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info) -#define NAN_PROPERTY_ENUMERATOR(name) \ - Nan::NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name( \ - Nan::NAN_PROPERTY_ENUMERATOR_ARGS_TYPE info) -#define NAN_PROPERTY_DELETER(name) \ - Nan::NAN_PROPERTY_DELETER_RETURN_TYPE name( \ - v8::Local property \ - , Nan::NAN_PROPERTY_DELETER_ARGS_TYPE info) -#define NAN_PROPERTY_QUERY(name) \ - Nan::NAN_PROPERTY_QUERY_RETURN_TYPE name( \ - v8::Local property \ - , Nan::NAN_PROPERTY_QUERY_ARGS_TYPE info) -# define NAN_INDEX_GETTER(name) \ - Nan::NAN_INDEX_GETTER_RETURN_TYPE name( \ - uint32_t index \ - , Nan::NAN_INDEX_GETTER_ARGS_TYPE info) -#define NAN_INDEX_SETTER(name) \ - Nan::NAN_INDEX_SETTER_RETURN_TYPE name( \ - uint32_t index \ - , v8::Local value \ - , Nan::NAN_INDEX_SETTER_ARGS_TYPE info) -#define NAN_INDEX_ENUMERATOR(name) \ - Nan::NAN_INDEX_ENUMERATOR_RETURN_TYPE \ - name(Nan::NAN_INDEX_ENUMERATOR_ARGS_TYPE info) -#define NAN_INDEX_DELETER(name) \ - Nan::NAN_INDEX_DELETER_RETURN_TYPE name( \ - uint32_t index \ - , Nan::NAN_INDEX_DELETER_ARGS_TYPE info) -#define NAN_INDEX_QUERY(name) \ - Nan::NAN_INDEX_QUERY_RETURN_TYPE name( \ - uint32_t index \ - , Nan::NAN_INDEX_QUERY_ARGS_TYPE info) - -class Callback { - public: - Callback() {} - - explicit Callback(const v8::Local &fn) : handle_(fn) {} - - ~Callback() { - handle_.Reset(); - } - - bool operator==(const Callback &other) const { - return handle_ == other.handle_; - } - - bool operator!=(const Callback &other) const { - return !operator==(other); - } - - inline - v8::Local operator*() const { return GetFunction(); } - - NAN_DEPRECATED inline v8::Local operator()( - v8::Local target - , int argc = 0 - , v8::Local argv[] = 0) const { -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource async("nan:Callback:operator()"); - return Call_(isolate, target, argc, argv, &async) - .FromMaybe(v8::Local()); -# else - return Call_(isolate, target, argc, argv); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#else - return Call_(target, argc, argv); -#endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - } - - NAN_DEPRECATED inline v8::Local operator()( - int argc = 0 - , v8::Local argv[] = 0) const { -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource async("nan:Callback:operator()"); - return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(), - argc, argv, &async) - .FromMaybe(v8::Local())); -# else - return scope.Escape( - Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv)); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#else - v8::HandleScope scope; - return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv)); -#endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - } - - inline MaybeLocal operator()( - AsyncResource* resource - , int argc = 0 - , v8::Local argv[] = 0) const { - return this->Call(argc, argv, resource); - } - - inline MaybeLocal operator()( - AsyncResource* resource - , v8::Local target - , int argc = 0 - , v8::Local argv[] = 0) const { - return this->Call(target, argc, argv, resource); - } - - // TODO(kkoopa): remove - inline void SetFunction(const v8::Local &fn) { - Reset(fn); - } - - inline void Reset(const v8::Local &fn) { - handle_.Reset(fn); - } - - inline void Reset() { - handle_.Reset(); - } - - inline v8::Local GetFunction() const { - return New(handle_); - } - - inline bool IsEmpty() const { - return handle_.IsEmpty(); - } - - // Deprecated: For async callbacks Use the versions that accept an - // AsyncResource. If this callback does not correspond to an async resource, - // that is, it is a synchronous function call on a non-empty JS stack, you - // should Nan::Call instead. - NAN_DEPRECATED inline v8::Local - Call(v8::Local target - , int argc - , v8::Local argv[]) const { -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource async("nan:Callback:Call"); - return Call_(isolate, target, argc, argv, &async) - .FromMaybe(v8::Local()); -# else - return Call_(isolate, target, argc, argv); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#else - return Call_(target, argc, argv); -#endif - } - - // Deprecated: For async callbacks Use the versions that accept an - // AsyncResource. If this callback does not correspond to an async resource, - // that is, it is a synchronous function call on a non-empty JS stack, you - // should Nan::Call instead. - NAN_DEPRECATED inline v8::Local - Call(int argc, v8::Local argv[]) const { -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); -# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - AsyncResource async("nan:Callback:Call"); - return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(), - argc, argv, &async) - .FromMaybe(v8::Local())); -# else - return scope.Escape( - Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv)); -# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION -#else - v8::HandleScope scope; - return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv)); -#endif - } - - inline MaybeLocal - Call(v8::Local target - , int argc - , v8::Local argv[] - , AsyncResource* resource) const { -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - return Call_(isolate, target, argc, argv, resource); -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - return Call_(isolate, target, argc, argv); -#else - return Call_(target, argc, argv); -#endif - } - - inline MaybeLocal - Call(int argc, v8::Local argv[], AsyncResource* resource) const { -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - return Call(isolate->GetCurrentContext()->Global(), argc, argv, resource); -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape( - Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv)); -#else - v8::HandleScope scope; - return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv)); -#endif - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(Callback) - Persistent handle_; - -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - MaybeLocal Call_(v8::Isolate *isolate - , v8::Local target - , int argc - , v8::Local argv[] - , AsyncResource* resource) const { - EscapableHandleScope scope; - v8::Local func = New(handle_); - auto maybe = resource->runInAsyncScope(target, func, argc, argv); - v8::Local local; - if (!maybe.ToLocal(&local)) return MaybeLocal(); - return scope.Escape(local); - } -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Local Call_(v8::Isolate *isolate - , v8::Local target - , int argc - , v8::Local argv[]) const { - EscapableHandleScope scope; - - v8::Local callback = New(handle_); -# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION - return scope.Escape(New(node::MakeCallback( - isolate - , target - , callback - , argc - , argv - ))); -# else - return scope.Escape(node::MakeCallback( - isolate - , target - , callback - , argc - , argv - )); -# endif - } -#else - v8::Local Call_(v8::Local target - , int argc - , v8::Local argv[]) const { - EscapableHandleScope scope; - - v8::Local callback = New(handle_); - return scope.Escape(New(node::MakeCallback( - target - , callback - , argc - , argv - ))); - } -#endif -}; - -inline MaybeLocal Call( - const Nan::Callback& callback - , v8::Local recv - , int argc - , v8::Local argv[]) { - return Call(*callback, recv, argc, argv); -} - -inline MaybeLocal Call( - const Nan::Callback& callback - , int argc - , v8::Local argv[]) { -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape( - Call(*callback, isolate->GetCurrentContext()->Global(), argc, argv) - .FromMaybe(v8::Local())); -#else - EscapableHandleScope scope; - return scope.Escape( - Call(*callback, v8::Context::GetCurrent()->Global(), argc, argv) - .FromMaybe(v8::Local())); -#endif -} - -inline MaybeLocal Call( - v8::Local symbol - , v8::Local recv - , int argc - , v8::Local argv[]) { - EscapableHandleScope scope; - v8::Local fn_v = - Get(recv, symbol).FromMaybe(v8::Local()); - if (fn_v.IsEmpty() || !fn_v->IsFunction()) return v8::Local(); - v8::Local fn = fn_v.As(); - return scope.Escape( - Call(fn, recv, argc, argv).FromMaybe(v8::Local())); -} - -inline MaybeLocal Call( - const char* method - , v8::Local recv - , int argc - , v8::Local argv[]) { - EscapableHandleScope scope; - v8::Local method_string = - New(method).ToLocalChecked(); - return scope.Escape( - Call(method_string, recv, argc, argv).FromMaybe(v8::Local())); -} - -/* abstract */ class AsyncWorker { - public: - explicit AsyncWorker(Callback *callback_, - const char* resource_name = "nan:AsyncWorker") - : callback(callback_), errmsg_(NULL) { - request.data = this; - - HandleScope scope; - v8::Local obj = New(); - persistentHandle.Reset(obj); - async_resource = new AsyncResource(resource_name, obj); - } - - virtual ~AsyncWorker() { - HandleScope scope; - - if (!persistentHandle.IsEmpty()) - persistentHandle.Reset(); - delete callback; - delete[] errmsg_; - delete async_resource; - } - - virtual void WorkComplete() { - HandleScope scope; - - if (errmsg_ == NULL) - HandleOKCallback(); - else - HandleErrorCallback(); - delete callback; - callback = NULL; - } - - inline void SaveToPersistent( - const char *key, const v8::Local &value) { - HandleScope scope; - Set(New(persistentHandle), New(key).ToLocalChecked(), value).FromJust(); - } - - inline void SaveToPersistent( - const v8::Local &key, const v8::Local &value) { - HandleScope scope; - Set(New(persistentHandle), key, value).FromJust(); - } - - inline void SaveToPersistent( - uint32_t index, const v8::Local &value) { - HandleScope scope; - Set(New(persistentHandle), index, value).FromJust(); - } - - inline v8::Local GetFromPersistent(const char *key) const { - EscapableHandleScope scope; - return scope.Escape( - Get(New(persistentHandle), New(key).ToLocalChecked()) - .FromMaybe(v8::Local())); - } - - inline v8::Local - GetFromPersistent(const v8::Local &key) const { - EscapableHandleScope scope; - return scope.Escape( - Get(New(persistentHandle), key) - .FromMaybe(v8::Local())); - } - - inline v8::Local GetFromPersistent(uint32_t index) const { - EscapableHandleScope scope; - return scope.Escape( - Get(New(persistentHandle), index) - .FromMaybe(v8::Local())); - } - - virtual void Execute() = 0; - - uv_work_t request; - - virtual void Destroy() { - delete this; - } - - protected: - Persistent persistentHandle; - Callback *callback; - AsyncResource *async_resource; - - virtual void HandleOKCallback() { - HandleScope scope; - - callback->Call(0, NULL, async_resource); - } - - virtual void HandleErrorCallback() { - HandleScope scope; - - v8::Local argv[] = { - v8::Exception::Error(New(ErrorMessage()).ToLocalChecked()) - }; - callback->Call(1, argv, async_resource); - } - - void SetErrorMessage(const char *msg) { - delete[] errmsg_; - - size_t size = strlen(msg) + 1; - errmsg_ = new char[size]; - memcpy(errmsg_, msg, size); - } - - const char* ErrorMessage() const { - return errmsg_; - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncWorker) - char *errmsg_; -}; - -/* abstract */ class AsyncBareProgressWorkerBase : public AsyncWorker { - public: - explicit AsyncBareProgressWorkerBase( - Callback *callback_, - const char* resource_name = "nan:AsyncBareProgressWorkerBase") - : AsyncWorker(callback_, resource_name) { - uv_async_init( - GetCurrentEventLoop() - , &async - , AsyncProgress_ - ); - async.data = this; - } - - virtual ~AsyncBareProgressWorkerBase() { - } - - virtual void WorkProgress() = 0; - - virtual void Destroy() { - uv_close(reinterpret_cast(&async), AsyncClose_); - } - - private: - inline static NAUV_WORK_CB(AsyncProgress_) { - AsyncBareProgressWorkerBase *worker = - static_cast(async->data); - worker->WorkProgress(); - } - - inline static void AsyncClose_(uv_handle_t* handle) { - AsyncBareProgressWorkerBase *worker = - static_cast(handle->data); - delete worker; - } - - protected: - uv_async_t async; -}; - -template -/* abstract */ -class AsyncBareProgressWorker : public AsyncBareProgressWorkerBase { - public: - explicit AsyncBareProgressWorker( - Callback *callback_, - const char* resource_name = "nan:AsyncBareProgressWorker") - : AsyncBareProgressWorkerBase(callback_, resource_name) { - uv_mutex_init(&async_lock); - } - - virtual ~AsyncBareProgressWorker() { - uv_mutex_destroy(&async_lock); - } - - class ExecutionProgress { - friend class AsyncBareProgressWorker; - public: - void Signal() const { - uv_mutex_lock(&that_->async_lock); - uv_async_send(&that_->async); - uv_mutex_unlock(&that_->async_lock); - } - - void Send(const T* data, size_t count) const { - that_->SendProgress_(data, count); - } - - private: - explicit ExecutionProgress(AsyncBareProgressWorker *that) : that_(that) {} - NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress) - AsyncBareProgressWorker* const that_; - }; - - virtual void Execute(const ExecutionProgress& progress) = 0; - virtual void HandleProgressCallback(const T *data, size_t size) = 0; - - protected: - uv_mutex_t async_lock; - - private: - void Execute() /*final override*/ { - ExecutionProgress progress(this); - Execute(progress); - } - - virtual void SendProgress_(const T *data, size_t count) = 0; -}; - -template -/* abstract */ -class AsyncProgressWorkerBase : public AsyncBareProgressWorker { - public: - explicit AsyncProgressWorkerBase( - Callback *callback_, - const char* resource_name = "nan:AsyncProgressWorkerBase") - : AsyncBareProgressWorker(callback_, resource_name), asyncdata_(NULL), - asyncsize_(0) { - } - - virtual ~AsyncProgressWorkerBase() { - delete[] asyncdata_; - } - - void WorkProgress() { - uv_mutex_lock(&this->async_lock); - T *data = asyncdata_; - size_t size = asyncsize_; - asyncdata_ = NULL; - asyncsize_ = 0; - uv_mutex_unlock(&this->async_lock); - - // Don't send progress events after we've already completed. - if (this->callback) { - this->HandleProgressCallback(data, size); - } - delete[] data; - } - - private: - void SendProgress_(const T *data, size_t count) { - T *new_data = new T[count]; - std::copy(data, data + count, new_data); - - uv_mutex_lock(&this->async_lock); - T *old_data = asyncdata_; - asyncdata_ = new_data; - asyncsize_ = count; - uv_async_send(&this->async); - uv_mutex_unlock(&this->async_lock); - - delete[] old_data; - } - - T *asyncdata_; - size_t asyncsize_; -}; - -// This ensures compatibility to the previous un-templated AsyncProgressWorker -// class definition. -typedef AsyncProgressWorkerBase AsyncProgressWorker; - -template -/* abstract */ -class AsyncBareProgressQueueWorker : public AsyncBareProgressWorkerBase { - public: - explicit AsyncBareProgressQueueWorker( - Callback *callback_, - const char* resource_name = "nan:AsyncBareProgressQueueWorker") - : AsyncBareProgressWorkerBase(callback_, resource_name) { - } - - virtual ~AsyncBareProgressQueueWorker() { - } - - class ExecutionProgress { - friend class AsyncBareProgressQueueWorker; - public: - void Send(const T* data, size_t count) const { - that_->SendProgress_(data, count); - } - - private: - explicit ExecutionProgress(AsyncBareProgressQueueWorker *that) - : that_(that) {} - NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress) - AsyncBareProgressQueueWorker* const that_; - }; - - virtual void Execute(const ExecutionProgress& progress) = 0; - virtual void HandleProgressCallback(const T *data, size_t size) = 0; - - private: - void Execute() /*final override*/ { - ExecutionProgress progress(this); - Execute(progress); - } - - virtual void SendProgress_(const T *data, size_t count) = 0; -}; - -template -/* abstract */ -class AsyncProgressQueueWorker : public AsyncBareProgressQueueWorker { - public: - explicit AsyncProgressQueueWorker( - Callback *callback_, - const char* resource_name = "nan:AsyncProgressQueueWorker") - : AsyncBareProgressQueueWorker(callback_) { - uv_mutex_init(&async_lock); - } - - virtual ~AsyncProgressQueueWorker() { - uv_mutex_lock(&async_lock); - - while (!asyncdata_.empty()) { - std::pair &datapair = asyncdata_.front(); - T *data = datapair.first; - - asyncdata_.pop(); - - delete[] data; - } - - uv_mutex_unlock(&async_lock); - uv_mutex_destroy(&async_lock); - } - - void WorkComplete() { - WorkProgress(); - AsyncWorker::WorkComplete(); - } - - void WorkProgress() { - uv_mutex_lock(&async_lock); - - while (!asyncdata_.empty()) { - std::pair &datapair = asyncdata_.front(); - - T *data = datapair.first; - size_t size = datapair.second; - - asyncdata_.pop(); - uv_mutex_unlock(&async_lock); - - // Don't send progress events after we've already completed. - if (this->callback) { - this->HandleProgressCallback(data, size); - } - - delete[] data; - - uv_mutex_lock(&async_lock); - } - - uv_mutex_unlock(&async_lock); - } - - private: - void SendProgress_(const T *data, size_t count) { - T *new_data = new T[count]; - std::copy(data, data + count, new_data); - - uv_mutex_lock(&async_lock); - asyncdata_.push(std::pair(new_data, count)); - uv_mutex_unlock(&async_lock); - - uv_async_send(&this->async); - } - - uv_mutex_t async_lock; - std::queue > asyncdata_; -}; - -inline void AsyncExecute (uv_work_t* req) { - AsyncWorker *worker = static_cast(req->data); - worker->Execute(); -} - -inline void AsyncExecuteComplete (uv_work_t* req) { - AsyncWorker* worker = static_cast(req->data); - worker->WorkComplete(); - worker->Destroy(); -} - -inline void AsyncQueueWorker (AsyncWorker* worker) { - uv_queue_work( - GetCurrentEventLoop() - , &worker->request - , AsyncExecute - , reinterpret_cast(AsyncExecuteComplete) - ); -} - -namespace imp { - -inline -ExternalOneByteStringResource const* -GetExternalResource(v8::Local str) { -#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION - return str->GetExternalAsciiStringResource(); -#else - return str->GetExternalOneByteStringResource(); -#endif -} - -inline -bool -IsExternal(v8::Local str) { -#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION - return str->IsExternalAscii(); -#else - return str->IsExternalOneByte(); -#endif -} - -} // end of namespace imp - -enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; - -#if NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION -# include "nan_string_bytes.h" // NOLINT(build/include) -#endif - -inline v8::Local Encode( - const void *buf, size_t len, enum Encoding encoding = BINARY) { -#if (NODE_MODULE_VERSION >= ATOM_0_21_MODULE_VERSION) - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - node::encoding node_enc = static_cast(encoding); - - if (encoding == UCS2) { - return node::Encode( - isolate - , reinterpret_cast(buf) - , len / 2); - } else { - return node::Encode( - isolate - , reinterpret_cast(buf) - , len - , node_enc); - } -#elif (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - return node::Encode( - v8::Isolate::GetCurrent() - , buf, len - , static_cast(encoding)); -#else -# if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION - return node::Encode(buf, len, static_cast(encoding)); -# else - return imp::Encode(reinterpret_cast(buf), len, encoding); -# endif -#endif -} - -inline ssize_t DecodeBytes( - v8::Local val, enum Encoding encoding = BINARY) { -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - return node::DecodeBytes( - v8::Isolate::GetCurrent() - , val - , static_cast(encoding)); -#else -# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) - if (encoding == BUFFER) { - return node::DecodeBytes(val, node::BINARY); - } -# endif - return node::DecodeBytes(val, static_cast(encoding)); -#endif -} - -inline ssize_t DecodeWrite( - char *buf - , size_t len - , v8::Local val - , enum Encoding encoding = BINARY) { -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - return node::DecodeWrite( - v8::Isolate::GetCurrent() - , buf - , len - , val - , static_cast(encoding)); -#else -# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) - if (encoding == BUFFER) { - return node::DecodeWrite(buf, len, val, node::BINARY); - } -# endif - return node::DecodeWrite( - buf - , len - , val - , static_cast(encoding)); -#endif -} - -inline void SetPrototypeTemplate( - v8::Local templ - , const char *name - , v8::Local value -) { - HandleScope scope; - SetTemplate(templ->PrototypeTemplate(), name, value); -} - -inline void SetPrototypeTemplate( - v8::Local templ - , v8::Local name - , v8::Local value - , v8::PropertyAttribute attributes -) { - HandleScope scope; - SetTemplate(templ->PrototypeTemplate(), name, value, attributes); -} - -inline void SetInstanceTemplate( - v8::Local templ - , const char *name - , v8::Local value -) { - HandleScope scope; - SetTemplate(templ->InstanceTemplate(), name, value); -} - -inline void SetInstanceTemplate( - v8::Local templ - , v8::Local name - , v8::Local value - , v8::PropertyAttribute attributes -) { - HandleScope scope; - SetTemplate(templ->InstanceTemplate(), name, value, attributes); -} - -namespace imp { - -// Note(@agnat): Helper to distinguish different receiver types. The first -// version deals with receivers derived from v8::Template. The second version -// handles everything else. The final argument only serves as discriminator and -// is unused. -template -inline -void -SetMethodAux(T recv, - v8::Local name, - v8::Local tpl, - v8::Template *) { - recv->Set(name, tpl); -} - -template -inline -void -SetMethodAux(T recv, - v8::Local name, - v8::Local tpl, - ...) { - Set(recv, name, GetFunction(tpl).ToLocalChecked()); -} - -} // end of namespace imp - -template class HandleType> -inline void SetMethod( - HandleType recv - , const char *name - , FunctionCallback callback - , v8::Local data = v8::Local()) { - HandleScope scope; - v8::Local t = New(callback, data); - v8::Local fn_name = New(name).ToLocalChecked(); - t->SetClassName(fn_name); - // Note(@agnat): Pass an empty T* as discriminator. See note on - // SetMethodAux(...) above - imp::SetMethodAux(recv, fn_name, t, static_cast(0)); -} - -inline void SetPrototypeMethod( - v8::Local recv - , const char* name - , FunctionCallback callback - , v8::Local data = v8::Local()) { - HandleScope scope; - v8::Local t = New( - callback - , data - , New(recv)); - v8::Local fn_name = New(name).ToLocalChecked(); - recv->PrototypeTemplate()->Set(fn_name, t); - t->SetClassName(fn_name); -} - -//=== Accessors and Such ======================================================= - -inline void SetAccessor( - v8::Local tpl - , v8::Local name - , GetterCallback getter - , SetterCallback setter = 0 - , v8::Local data = v8::Local() - , v8::AccessControl settings = v8::DEFAULT - , v8::PropertyAttribute attribute = v8::None - , imp::Sig signature = imp::Sig()) { - HandleScope scope; - - imp::NativeGetter getter_ = - imp::GetterCallbackWrapper; - imp::NativeSetter setter_ = - setter ? imp::SetterCallbackWrapper : 0; - - v8::Local otpl = New(); - otpl->SetInternalFieldCount(imp::kAccessorFieldCount); - v8::Local obj = NewInstance(otpl).ToLocalChecked(); - - obj->SetInternalField( - imp::kGetterIndex - , New(reinterpret_cast(getter))); - - if (setter != 0) { - obj->SetInternalField( - imp::kSetterIndex - , New(reinterpret_cast(setter))); - } - - if (!data.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, data); - } - - tpl->SetAccessor( - name - , getter_ - , setter_ - , obj - , settings - , attribute - , signature); -} - -inline bool SetAccessor( - v8::Local obj - , v8::Local name - , GetterCallback getter - , SetterCallback setter = 0 - , v8::Local data = v8::Local() - , v8::AccessControl settings = v8::DEFAULT - , v8::PropertyAttribute attribute = v8::None) { - HandleScope scope; - - imp::NativeGetter getter_ = - imp::GetterCallbackWrapper; - imp::NativeSetter setter_ = - setter ? imp::SetterCallbackWrapper : 0; - - v8::Local otpl = New(); - otpl->SetInternalFieldCount(imp::kAccessorFieldCount); - v8::Local dataobj = NewInstance(otpl).ToLocalChecked(); - - dataobj->SetInternalField( - imp::kGetterIndex - , New(reinterpret_cast(getter))); - - if (!data.IsEmpty()) { - dataobj->SetInternalField(imp::kDataIndex, data); - } - - if (setter) { - dataobj->SetInternalField( - imp::kSetterIndex - , New(reinterpret_cast(setter))); - } - -#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION) - return obj->SetAccessor( - GetCurrentContext() - , name - , getter_ - , setter_ - , dataobj - , settings - , attribute).FromMaybe(false); -#else - return obj->SetAccessor( - name - , getter_ - , setter_ - , dataobj - , settings - , attribute); -#endif -} - -inline void SetNamedPropertyHandler( - v8::Local tpl - , PropertyGetterCallback getter - , PropertySetterCallback setter = 0 - , PropertyQueryCallback query = 0 - , PropertyDeleterCallback deleter = 0 - , PropertyEnumeratorCallback enumerator = 0 - , v8::Local data = v8::Local()) { - HandleScope scope; - - imp::NativePropertyGetter getter_ = - imp::PropertyGetterCallbackWrapper; - imp::NativePropertySetter setter_ = - setter ? imp::PropertySetterCallbackWrapper : 0; - imp::NativePropertyQuery query_ = - query ? imp::PropertyQueryCallbackWrapper : 0; - imp::NativePropertyDeleter *deleter_ = - deleter ? imp::PropertyDeleterCallbackWrapper : 0; - imp::NativePropertyEnumerator enumerator_ = - enumerator ? imp::PropertyEnumeratorCallbackWrapper : 0; - - v8::Local otpl = New(); - otpl->SetInternalFieldCount(imp::kPropertyFieldCount); - v8::Local obj = NewInstance(otpl).ToLocalChecked(); - obj->SetInternalField( - imp::kPropertyGetterIndex - , New(reinterpret_cast(getter))); - - if (setter) { - obj->SetInternalField( - imp::kPropertySetterIndex - , New(reinterpret_cast(setter))); - } - - if (query) { - obj->SetInternalField( - imp::kPropertyQueryIndex - , New(reinterpret_cast(query))); - } - - if (deleter) { - obj->SetInternalField( - imp::kPropertyDeleterIndex - , New(reinterpret_cast(deleter))); - } - - if (enumerator) { - obj->SetInternalField( - imp::kPropertyEnumeratorIndex - , New(reinterpret_cast(enumerator))); - } - - if (!data.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, data); - } - -#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION - tpl->SetHandler(v8::NamedPropertyHandlerConfiguration( - getter_, setter_, query_, deleter_, enumerator_, obj)); -#else - tpl->SetNamedPropertyHandler( - getter_ - , setter_ - , query_ - , deleter_ - , enumerator_ - , obj); -#endif -} - -inline void SetIndexedPropertyHandler( - v8::Local tpl - , IndexGetterCallback getter - , IndexSetterCallback setter = 0 - , IndexQueryCallback query = 0 - , IndexDeleterCallback deleter = 0 - , IndexEnumeratorCallback enumerator = 0 - , v8::Local data = v8::Local()) { - HandleScope scope; - - imp::NativeIndexGetter getter_ = - imp::IndexGetterCallbackWrapper; - imp::NativeIndexSetter setter_ = - setter ? imp::IndexSetterCallbackWrapper : 0; - imp::NativeIndexQuery query_ = - query ? imp::IndexQueryCallbackWrapper : 0; - imp::NativeIndexDeleter deleter_ = - deleter ? imp::IndexDeleterCallbackWrapper : 0; - imp::NativeIndexEnumerator enumerator_ = - enumerator ? imp::IndexEnumeratorCallbackWrapper : 0; - - v8::Local otpl = New(); - otpl->SetInternalFieldCount(imp::kIndexPropertyFieldCount); - v8::Local obj = NewInstance(otpl).ToLocalChecked(); - obj->SetInternalField( - imp::kIndexPropertyGetterIndex - , New(reinterpret_cast(getter))); - - if (setter) { - obj->SetInternalField( - imp::kIndexPropertySetterIndex - , New(reinterpret_cast(setter))); - } - - if (query) { - obj->SetInternalField( - imp::kIndexPropertyQueryIndex - , New(reinterpret_cast(query))); - } - - if (deleter) { - obj->SetInternalField( - imp::kIndexPropertyDeleterIndex - , New(reinterpret_cast(deleter))); - } - - if (enumerator) { - obj->SetInternalField( - imp::kIndexPropertyEnumeratorIndex - , New(reinterpret_cast(enumerator))); - } - - if (!data.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, data); - } - -#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION - tpl->SetHandler(v8::IndexedPropertyHandlerConfiguration( - getter_, setter_, query_, deleter_, enumerator_, obj)); -#else - tpl->SetIndexedPropertyHandler( - getter_ - , setter_ - , query_ - , deleter_ - , enumerator_ - , obj); -#endif -} - -inline void SetCallHandler( - v8::Local tpl - , FunctionCallback callback - , v8::Local data = v8::Local()) { - HandleScope scope; - - v8::Local otpl = New(); - otpl->SetInternalFieldCount(imp::kFunctionFieldCount); - v8::Local obj = NewInstance(otpl).ToLocalChecked(); - - obj->SetInternalField( - imp::kFunctionIndex - , New(reinterpret_cast(callback))); - - if (!data.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, data); - } - - tpl->SetCallHandler(imp::FunctionCallbackWrapper, obj); -} - - -inline void SetCallAsFunctionHandler( - v8::Local tpl, - FunctionCallback callback, - v8::Local data = v8::Local()) { - HandleScope scope; - - v8::Local otpl = New(); - otpl->SetInternalFieldCount(imp::kFunctionFieldCount); - v8::Local obj = NewInstance(otpl).ToLocalChecked(); - - obj->SetInternalField( - imp::kFunctionIndex - , New(reinterpret_cast(callback))); - - if (!data.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, data); - } - - tpl->SetCallAsFunctionHandler(imp::FunctionCallbackWrapper, obj); -} - -//=== Weak Persistent Handling ================================================= - -#include "nan_weak.h" // NOLINT(build/include) - -//=== ObjectWrap =============================================================== - -#include "nan_object_wrap.h" // NOLINT(build/include) - -//=== HiddenValue/Private ====================================================== - -#include "nan_private.h" // NOLINT(build/include) - -//=== Export ================================================================== - -inline -void -Export(ADDON_REGISTER_FUNCTION_ARGS_TYPE target, const char *name, - FunctionCallback f) { - HandleScope scope; - - Set(target, New(name).ToLocalChecked(), - GetFunction(New(f)).ToLocalChecked()); -} - -//=== Tap Reverse Binding ===================================================== - -struct Tap { - explicit Tap(v8::Local t) : t_() { - HandleScope scope; - - t_.Reset(To(t).ToLocalChecked()); - } - - ~Tap() { t_.Reset(); } // not sure if necessary - - inline void plan(int i) { - HandleScope scope; - v8::Local arg = New(i); - Call("plan", New(t_), 1, &arg); - } - - inline void ok(bool isOk, const char *msg = NULL) { - HandleScope scope; - v8::Local args[2]; - args[0] = New(isOk); - if (msg) args[1] = New(msg).ToLocalChecked(); - Call("ok", New(t_), msg ? 2 : 1, args); - } - - inline void pass(const char * msg = NULL) { - HandleScope scope; - v8::Local hmsg; - if (msg) hmsg = New(msg).ToLocalChecked(); - Call("pass", New(t_), msg ? 1 : 0, &hmsg); - } - - inline void end() { - HandleScope scope; - Call("end", New(t_), 0, NULL); - } - - private: - Persistent t_; -}; - -#define NAN_STRINGIZE2(x) #x -#define NAN_STRINGIZE(x) NAN_STRINGIZE2(x) -#define NAN_TEST_EXPRESSION(expression) \ - ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression - -#define NAN_EXPORT(target, function) Export(target, #function, function) - -#undef TYPE_CHECK - -//=== Generic Maybefication =================================================== - -namespace imp { - -template struct Maybefier; - -template struct Maybefier > { - inline static MaybeLocal convert(v8::Local v) { - return v; - } -}; - -template struct Maybefier > { - inline static MaybeLocal convert(MaybeLocal v) { - return v; - } -}; - -} // end of namespace imp - -template class MaybeMaybe> -inline MaybeLocal -MakeMaybe(MaybeMaybe v) { - return imp::Maybefier >::convert(v); -} - -//=== TypedArrayContents ======================================================= - -#include "nan_typedarray_contents.h" // NOLINT(build/include) - -//=== JSON ===================================================================== - -#include "nan_json.h" // NOLINT(build/include) - -} // end of namespace Nan - -#endif // NAN_H_ diff --git a/node_modules/nan/nan_callbacks.h b/node_modules/nan/nan_callbacks.h deleted file mode 100644 index 53ede84..0000000 --- a/node_modules/nan/nan_callbacks.h +++ /dev/null @@ -1,88 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_CALLBACKS_H_ -#define NAN_CALLBACKS_H_ - -template class FunctionCallbackInfo; -template class PropertyCallbackInfo; -template class Global; - -typedef void(*FunctionCallback)(const FunctionCallbackInfo&); -typedef void(*GetterCallback) - (v8::Local, const PropertyCallbackInfo&); -typedef void(*SetterCallback)( - v8::Local, - v8::Local, - const PropertyCallbackInfo&); -typedef void(*PropertyGetterCallback)( - v8::Local, - const PropertyCallbackInfo&); -typedef void(*PropertySetterCallback)( - v8::Local, - v8::Local, - const PropertyCallbackInfo&); -typedef void(*PropertyEnumeratorCallback) - (const PropertyCallbackInfo&); -typedef void(*PropertyDeleterCallback)( - v8::Local, - const PropertyCallbackInfo&); -typedef void(*PropertyQueryCallback)( - v8::Local, - const PropertyCallbackInfo&); -typedef void(*IndexGetterCallback)( - uint32_t, - const PropertyCallbackInfo&); -typedef void(*IndexSetterCallback)( - uint32_t, - v8::Local, - const PropertyCallbackInfo&); -typedef void(*IndexEnumeratorCallback) - (const PropertyCallbackInfo&); -typedef void(*IndexDeleterCallback)( - uint32_t, - const PropertyCallbackInfo&); -typedef void(*IndexQueryCallback)( - uint32_t, - const PropertyCallbackInfo&); - -namespace imp { -typedef v8::Local Sig; - -static const int kDataIndex = 0; - -static const int kFunctionIndex = 1; -static const int kFunctionFieldCount = 2; - -static const int kGetterIndex = 1; -static const int kSetterIndex = 2; -static const int kAccessorFieldCount = 3; - -static const int kPropertyGetterIndex = 1; -static const int kPropertySetterIndex = 2; -static const int kPropertyEnumeratorIndex = 3; -static const int kPropertyDeleterIndex = 4; -static const int kPropertyQueryIndex = 5; -static const int kPropertyFieldCount = 6; - -static const int kIndexPropertyGetterIndex = 1; -static const int kIndexPropertySetterIndex = 2; -static const int kIndexPropertyEnumeratorIndex = 3; -static const int kIndexPropertyDeleterIndex = 4; -static const int kIndexPropertyQueryIndex = 5; -static const int kIndexPropertyFieldCount = 6; - -} // end of namespace imp - -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION -# include "nan_callbacks_12_inl.h" // NOLINT(build/include) -#else -# include "nan_callbacks_pre_12_inl.h" // NOLINT(build/include) -#endif - -#endif // NAN_CALLBACKS_H_ diff --git a/node_modules/nan/nan_callbacks_12_inl.h b/node_modules/nan/nan_callbacks_12_inl.h deleted file mode 100644 index c27b18d..0000000 --- a/node_modules/nan/nan_callbacks_12_inl.h +++ /dev/null @@ -1,514 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_CALLBACKS_12_INL_H_ -#define NAN_CALLBACKS_12_INL_H_ - -template -class ReturnValue { - v8::ReturnValue value_; - - public: - template - explicit inline ReturnValue(const v8::ReturnValue &value) : - value_(value) {} - template - explicit inline ReturnValue(const ReturnValue& that) - : value_(that.value_) { - TYPE_CHECK(T, S); - } - - // Handle setters - template inline void Set(const v8::Local &handle) { - TYPE_CHECK(T, S); - value_.Set(handle); - } - - template inline void Set(const Global &handle) { - TYPE_CHECK(T, S); -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && \ - (V8_MINOR_VERSION > 5 || (V8_MINOR_VERSION == 5 && \ - defined(V8_BUILD_NUMBER) && V8_BUILD_NUMBER >= 8)))) - value_.Set(handle); -#else - value_.Set(*reinterpret_cast*>(&handle)); - const_cast &>(handle).Reset(); -#endif - } - - // Fast primitive setters - inline void Set(bool value) { - TYPE_CHECK(T, v8::Boolean); - value_.Set(value); - } - - inline void Set(double i) { - TYPE_CHECK(T, v8::Number); - value_.Set(i); - } - - inline void Set(int32_t i) { - TYPE_CHECK(T, v8::Integer); - value_.Set(i); - } - - inline void Set(uint32_t i) { - TYPE_CHECK(T, v8::Integer); - value_.Set(i); - } - - // Fast JS primitive setters - inline void SetNull() { - TYPE_CHECK(T, v8::Primitive); - value_.SetNull(); - } - - inline void SetUndefined() { - TYPE_CHECK(T, v8::Primitive); - value_.SetUndefined(); - } - - inline void SetEmptyString() { - TYPE_CHECK(T, v8::String); - value_.SetEmptyString(); - } - - // Convenience getter for isolate - inline v8::Isolate *GetIsolate() const { - return value_.GetIsolate(); - } - - // Pointer setter: Uncompilable to prevent inadvertent misuse. - template - inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); } -}; - -template -class FunctionCallbackInfo { - const v8::FunctionCallbackInfo &info_; - const v8::Local data_; - - public: - explicit inline FunctionCallbackInfo( - const v8::FunctionCallbackInfo &info - , v8::Local data) : - info_(info) - , data_(data) {} - - inline ReturnValue GetReturnValue() const { - return ReturnValue(info_.GetReturnValue()); - } - -#if NODE_MAJOR_VERSION < 10 - inline v8::Local Callee() const { return info_.Callee(); } -#endif - inline v8::Local Data() const { return data_; } - inline v8::Local Holder() const { return info_.Holder(); } - inline bool IsConstructCall() const { return info_.IsConstructCall(); } - inline int Length() const { return info_.Length(); } - inline v8::Local operator[](int i) const { return info_[i]; } - inline v8::Local This() const { return info_.This(); } - inline v8::Isolate *GetIsolate() const { return info_.GetIsolate(); } - - - protected: - static const int kHolderIndex = 0; - static const int kIsolateIndex = 1; - static const int kReturnValueDefaultValueIndex = 2; - static const int kReturnValueIndex = 3; - static const int kDataIndex = 4; - static const int kCalleeIndex = 5; - static const int kContextSaveIndex = 6; - static const int kArgsLength = 7; - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo) -}; - -template -class PropertyCallbackInfo { - const v8::PropertyCallbackInfo &info_; - const v8::Local data_; - - public: - explicit inline PropertyCallbackInfo( - const v8::PropertyCallbackInfo &info - , const v8::Local data) : - info_(info) - , data_(data) {} - - inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); } - inline v8::Local Data() const { return data_; } - inline v8::Local This() const { return info_.This(); } - inline v8::Local Holder() const { return info_.Holder(); } - inline ReturnValue GetReturnValue() const { - return ReturnValue(info_.GetReturnValue()); - } - - protected: - static const int kHolderIndex = 0; - static const int kIsolateIndex = 1; - static const int kReturnValueDefaultValueIndex = 2; - static const int kReturnValueIndex = 3; - static const int kDataIndex = 4; - static const int kThisIndex = 5; - static const int kArgsLength = 6; - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfo) -}; - -namespace imp { -static -void FunctionCallbackWrapper(const v8::FunctionCallbackInfo &info) { - v8::Local obj = info.Data().As(); - FunctionCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kFunctionIndex).As()->Value())); - FunctionCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - callback(cbinfo); -} - -typedef void (*NativeFunction)(const v8::FunctionCallbackInfo &); - -#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION -static -void GetterCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - GetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kGetterIndex).As()->Value())); - callback(property.As(), cbinfo); -} - -typedef void (*NativeGetter) - (v8::Local, const v8::PropertyCallbackInfo &); - -static -void SetterCallbackWrapper( - v8::Local property - , v8::Local value - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - SetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kSetterIndex).As()->Value())); - callback(property.As(), value, cbinfo); -} - -typedef void (*NativeSetter)( - v8::Local - , v8::Local - , const v8::PropertyCallbackInfo &); -#else -static -void GetterCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - GetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kGetterIndex).As()->Value())); - callback(property, cbinfo); -} - -typedef void (*NativeGetter) - (v8::Local, const v8::PropertyCallbackInfo &); - -static -void SetterCallbackWrapper( - v8::Local property - , v8::Local value - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - SetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kSetterIndex).As()->Value())); - callback(property, value, cbinfo); -} - -typedef void (*NativeSetter)( - v8::Local - , v8::Local - , const v8::PropertyCallbackInfo &); -#endif - -#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION -static -void PropertyGetterCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyGetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyGetterIndex) - .As()->Value())); - callback(property.As(), cbinfo); -} - -typedef void (*NativePropertyGetter) - (v8::Local, const v8::PropertyCallbackInfo &); - -static -void PropertySetterCallbackWrapper( - v8::Local property - , v8::Local value - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertySetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertySetterIndex) - .As()->Value())); - callback(property.As(), value, cbinfo); -} - -typedef void (*NativePropertySetter)( - v8::Local - , v8::Local - , const v8::PropertyCallbackInfo &); - -static -void PropertyEnumeratorCallbackWrapper( - const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyEnumeratorCallback callback = - reinterpret_cast(reinterpret_cast( - obj->GetInternalField(kPropertyEnumeratorIndex) - .As()->Value())); - callback(cbinfo); -} - -typedef void (*NativePropertyEnumerator) - (const v8::PropertyCallbackInfo &); - -static -void PropertyDeleterCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyDeleterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyDeleterIndex) - .As()->Value())); - callback(property.As(), cbinfo); -} - -typedef void (NativePropertyDeleter) - (v8::Local, const v8::PropertyCallbackInfo &); - -static -void PropertyQueryCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyQueryCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyQueryIndex) - .As()->Value())); - callback(property.As(), cbinfo); -} - -typedef void (*NativePropertyQuery) - (v8::Local, const v8::PropertyCallbackInfo &); -#else -static -void PropertyGetterCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyGetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyGetterIndex) - .As()->Value())); - callback(property, cbinfo); -} - -typedef void (*NativePropertyGetter) - (v8::Local, const v8::PropertyCallbackInfo &); - -static -void PropertySetterCallbackWrapper( - v8::Local property - , v8::Local value - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertySetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertySetterIndex) - .As()->Value())); - callback(property, value, cbinfo); -} - -typedef void (*NativePropertySetter)( - v8::Local - , v8::Local - , const v8::PropertyCallbackInfo &); - -static -void PropertyEnumeratorCallbackWrapper( - const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyEnumeratorCallback callback = - reinterpret_cast(reinterpret_cast( - obj->GetInternalField(kPropertyEnumeratorIndex) - .As()->Value())); - callback(cbinfo); -} - -typedef void (*NativePropertyEnumerator) - (const v8::PropertyCallbackInfo &); - -static -void PropertyDeleterCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyDeleterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyDeleterIndex) - .As()->Value())); - callback(property, cbinfo); -} - -typedef void (NativePropertyDeleter) - (v8::Local, const v8::PropertyCallbackInfo &); - -static -void PropertyQueryCallbackWrapper( - v8::Local property - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyQueryCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyQueryIndex) - .As()->Value())); - callback(property, cbinfo); -} - -typedef void (*NativePropertyQuery) - (v8::Local, const v8::PropertyCallbackInfo &); -#endif - -static -void IndexGetterCallbackWrapper( - uint32_t index, const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexGetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyGetterIndex) - .As()->Value())); - callback(index, cbinfo); -} - -typedef void (*NativeIndexGetter) - (uint32_t, const v8::PropertyCallbackInfo &); - -static -void IndexSetterCallbackWrapper( - uint32_t index - , v8::Local value - , const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexSetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertySetterIndex) - .As()->Value())); - callback(index, value, cbinfo); -} - -typedef void (*NativeIndexSetter)( - uint32_t - , v8::Local - , const v8::PropertyCallbackInfo &); - -static -void IndexEnumeratorCallbackWrapper( - const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexEnumeratorCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField( - kIndexPropertyEnumeratorIndex).As()->Value())); - callback(cbinfo); -} - -typedef void (*NativeIndexEnumerator) - (const v8::PropertyCallbackInfo &); - -static -void IndexDeleterCallbackWrapper( - uint32_t index, const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexDeleterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyDeleterIndex) - .As()->Value())); - callback(index, cbinfo); -} - -typedef void (*NativeIndexDeleter) - (uint32_t, const v8::PropertyCallbackInfo &); - -static -void IndexQueryCallbackWrapper( - uint32_t index, const v8::PropertyCallbackInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexQueryCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyQueryIndex) - .As()->Value())); - callback(index, cbinfo); -} - -typedef void (*NativeIndexQuery) - (uint32_t, const v8::PropertyCallbackInfo &); -} // end of namespace imp - -#endif // NAN_CALLBACKS_12_INL_H_ diff --git a/node_modules/nan/nan_callbacks_pre_12_inl.h b/node_modules/nan/nan_callbacks_pre_12_inl.h deleted file mode 100644 index c9ba499..0000000 --- a/node_modules/nan/nan_callbacks_pre_12_inl.h +++ /dev/null @@ -1,520 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_CALLBACKS_PRE_12_INL_H_ -#define NAN_CALLBACKS_PRE_12_INL_H_ - -namespace imp { -template class ReturnValueImp; -} // end of namespace imp - -template -class ReturnValue { - v8::Isolate *isolate_; - v8::Persistent *value_; - friend class imp::ReturnValueImp; - - public: - template - explicit inline ReturnValue(v8::Isolate *isolate, v8::Persistent *p) : - isolate_(isolate), value_(p) {} - template - explicit inline ReturnValue(const ReturnValue& that) - : isolate_(that.isolate_), value_(that.value_) { - TYPE_CHECK(T, S); - } - - // Handle setters - template inline void Set(const v8::Local &handle) { - TYPE_CHECK(T, S); - value_->Dispose(); - *value_ = v8::Persistent::New(handle); - } - - template inline void Set(const Global &handle) { - TYPE_CHECK(T, S); - value_->Dispose(); - *value_ = v8::Persistent::New(handle.persistent); - const_cast &>(handle).Reset(); - } - - // Fast primitive setters - inline void Set(bool value) { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::Boolean); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::Boolean::New(value)); - } - - inline void Set(double i) { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::Number); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::Number::New(i)); - } - - inline void Set(int32_t i) { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::Integer); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::Int32::New(i)); - } - - inline void Set(uint32_t i) { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::Integer); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::Uint32::NewFromUnsigned(i)); - } - - // Fast JS primitive setters - inline void SetNull() { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::Primitive); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::Null()); - } - - inline void SetUndefined() { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::Primitive); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::Undefined()); - } - - inline void SetEmptyString() { - v8::HandleScope scope; - - TYPE_CHECK(T, v8::String); - value_->Dispose(); - *value_ = v8::Persistent::New(v8::String::Empty()); - } - - // Convenience getter for isolate - inline v8::Isolate *GetIsolate() const { - return isolate_; - } - - // Pointer setter: Uncompilable to prevent inadvertent misuse. - template - inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); } -}; - -template -class FunctionCallbackInfo { - const v8::Arguments &args_; - v8::Local data_; - ReturnValue return_value_; - v8::Persistent retval_; - - public: - explicit inline FunctionCallbackInfo( - const v8::Arguments &args - , v8::Local data) : - args_(args) - , data_(data) - , return_value_(args.GetIsolate(), &retval_) - , retval_(v8::Persistent::New(v8::Undefined())) {} - - inline ~FunctionCallbackInfo() { - retval_.Dispose(); - retval_.Clear(); - } - - inline ReturnValue GetReturnValue() const { - return ReturnValue(return_value_); - } - - inline v8::Local Callee() const { return args_.Callee(); } - inline v8::Local Data() const { return data_; } - inline v8::Local Holder() const { return args_.Holder(); } - inline bool IsConstructCall() const { return args_.IsConstructCall(); } - inline int Length() const { return args_.Length(); } - inline v8::Local operator[](int i) const { return args_[i]; } - inline v8::Local This() const { return args_.This(); } - inline v8::Isolate *GetIsolate() const { return args_.GetIsolate(); } - - - protected: - static const int kHolderIndex = 0; - static const int kIsolateIndex = 1; - static const int kReturnValueDefaultValueIndex = 2; - static const int kReturnValueIndex = 3; - static const int kDataIndex = 4; - static const int kCalleeIndex = 5; - static const int kContextSaveIndex = 6; - static const int kArgsLength = 7; - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo) -}; - -template -class PropertyCallbackInfoBase { - const v8::AccessorInfo &info_; - const v8::Local data_; - - public: - explicit inline PropertyCallbackInfoBase( - const v8::AccessorInfo &info - , const v8::Local data) : - info_(info) - , data_(data) {} - - inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); } - inline v8::Local Data() const { return data_; } - inline v8::Local This() const { return info_.This(); } - inline v8::Local Holder() const { return info_.Holder(); } - - protected: - static const int kHolderIndex = 0; - static const int kIsolateIndex = 1; - static const int kReturnValueDefaultValueIndex = 2; - static const int kReturnValueIndex = 3; - static const int kDataIndex = 4; - static const int kThisIndex = 5; - static const int kArgsLength = 6; - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfoBase) -}; - -template -class PropertyCallbackInfo : public PropertyCallbackInfoBase { - ReturnValue return_value_; - v8::Persistent retval_; - - public: - explicit inline PropertyCallbackInfo( - const v8::AccessorInfo &info - , const v8::Local data) : - PropertyCallbackInfoBase(info, data) - , return_value_(info.GetIsolate(), &retval_) - , retval_(v8::Persistent::New(v8::Undefined())) {} - - inline ~PropertyCallbackInfo() { - retval_.Dispose(); - retval_.Clear(); - } - - inline ReturnValue GetReturnValue() const { return return_value_; } -}; - -template<> -class PropertyCallbackInfo : - public PropertyCallbackInfoBase { - ReturnValue return_value_; - v8::Persistent retval_; - - public: - explicit inline PropertyCallbackInfo( - const v8::AccessorInfo &info - , const v8::Local data) : - PropertyCallbackInfoBase(info, data) - , return_value_(info.GetIsolate(), &retval_) - , retval_(v8::Persistent::New(v8::Local())) {} - - inline ~PropertyCallbackInfo() { - retval_.Dispose(); - retval_.Clear(); - } - - inline ReturnValue GetReturnValue() const { - return return_value_; - } -}; - -template<> -class PropertyCallbackInfo : - public PropertyCallbackInfoBase { - ReturnValue return_value_; - v8::Persistent retval_; - - public: - explicit inline PropertyCallbackInfo( - const v8::AccessorInfo &info - , const v8::Local data) : - PropertyCallbackInfoBase(info, data) - , return_value_(info.GetIsolate(), &retval_) - , retval_(v8::Persistent::New(v8::Local())) {} - - inline ~PropertyCallbackInfo() { - retval_.Dispose(); - retval_.Clear(); - } - - inline ReturnValue GetReturnValue() const { - return return_value_; - } -}; - -template<> -class PropertyCallbackInfo : - public PropertyCallbackInfoBase { - ReturnValue return_value_; - v8::Persistent retval_; - - public: - explicit inline PropertyCallbackInfo( - const v8::AccessorInfo &info - , const v8::Local data) : - PropertyCallbackInfoBase(info, data) - , return_value_(info.GetIsolate(), &retval_) - , retval_(v8::Persistent::New(v8::Local())) {} - - inline ~PropertyCallbackInfo() { - retval_.Dispose(); - retval_.Clear(); - } - - inline ReturnValue GetReturnValue() const { - return return_value_; - } -}; - -namespace imp { -template -class ReturnValueImp : public ReturnValue { - public: - explicit ReturnValueImp(ReturnValue that) : - ReturnValue(that) {} - inline v8::Handle Value() { - return *ReturnValue::value_; - } -}; - -static -v8::Handle FunctionCallbackWrapper(const v8::Arguments &args) { - v8::Local obj = args.Data().As(); - FunctionCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kFunctionIndex).As()->Value())); - FunctionCallbackInfo - cbinfo(args, obj->GetInternalField(kDataIndex)); - callback(cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeFunction)(const v8::Arguments &); - -static -v8::Handle GetterCallbackWrapper( - v8::Local property, const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - GetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kGetterIndex).As()->Value())); - callback(property, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeGetter) - (v8::Local, const v8::AccessorInfo &); - -static -void SetterCallbackWrapper( - v8::Local property - , v8::Local value - , const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - SetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kSetterIndex).As()->Value())); - callback(property, value, cbinfo); -} - -typedef void (*NativeSetter) - (v8::Local, v8::Local, const v8::AccessorInfo &); - -static -v8::Handle PropertyGetterCallbackWrapper( - v8::Local property, const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyGetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyGetterIndex) - .As()->Value())); - callback(property, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativePropertyGetter) - (v8::Local, const v8::AccessorInfo &); - -static -v8::Handle PropertySetterCallbackWrapper( - v8::Local property - , v8::Local value - , const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertySetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertySetterIndex) - .As()->Value())); - callback(property, value, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativePropertySetter) - (v8::Local, v8::Local, const v8::AccessorInfo &); - -static -v8::Handle PropertyEnumeratorCallbackWrapper( - const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyEnumeratorCallback callback = - reinterpret_cast(reinterpret_cast( - obj->GetInternalField(kPropertyEnumeratorIndex) - .As()->Value())); - callback(cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativePropertyEnumerator) - (const v8::AccessorInfo &); - -static -v8::Handle PropertyDeleterCallbackWrapper( - v8::Local property - , const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyDeleterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyDeleterIndex) - .As()->Value())); - callback(property, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (NativePropertyDeleter) - (v8::Local, const v8::AccessorInfo &); - -static -v8::Handle PropertyQueryCallbackWrapper( - v8::Local property, const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - PropertyQueryCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kPropertyQueryIndex) - .As()->Value())); - callback(property, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativePropertyQuery) - (v8::Local, const v8::AccessorInfo &); - -static -v8::Handle IndexGetterCallbackWrapper( - uint32_t index, const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexGetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyGetterIndex) - .As()->Value())); - callback(index, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeIndexGetter) - (uint32_t, const v8::AccessorInfo &); - -static -v8::Handle IndexSetterCallbackWrapper( - uint32_t index - , v8::Local value - , const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexSetterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertySetterIndex) - .As()->Value())); - callback(index, value, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeIndexSetter) - (uint32_t, v8::Local, const v8::AccessorInfo &); - -static -v8::Handle IndexEnumeratorCallbackWrapper( - const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexEnumeratorCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyEnumeratorIndex) - .As()->Value())); - callback(cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeIndexEnumerator) - (const v8::AccessorInfo &); - -static -v8::Handle IndexDeleterCallbackWrapper( - uint32_t index, const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexDeleterCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyDeleterIndex) - .As()->Value())); - callback(index, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeIndexDeleter) - (uint32_t, const v8::AccessorInfo &); - -static -v8::Handle IndexQueryCallbackWrapper( - uint32_t index, const v8::AccessorInfo &info) { - v8::Local obj = info.Data().As(); - PropertyCallbackInfo - cbinfo(info, obj->GetInternalField(kDataIndex)); - IndexQueryCallback callback = reinterpret_cast( - reinterpret_cast( - obj->GetInternalField(kIndexPropertyQueryIndex) - .As()->Value())); - callback(index, cbinfo); - return ReturnValueImp(cbinfo.GetReturnValue()).Value(); -} - -typedef v8::Handle (*NativeIndexQuery) - (uint32_t, const v8::AccessorInfo &); -} // end of namespace imp - -#endif // NAN_CALLBACKS_PRE_12_INL_H_ diff --git a/node_modules/nan/nan_converters.h b/node_modules/nan/nan_converters.h deleted file mode 100644 index c0b3272..0000000 --- a/node_modules/nan/nan_converters.h +++ /dev/null @@ -1,72 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_CONVERTERS_H_ -#define NAN_CONVERTERS_H_ - -namespace imp { -template struct ToFactoryBase { - typedef MaybeLocal return_t; -}; -template struct ValueFactoryBase { typedef Maybe return_t; }; - -template struct ToFactory; - -template<> -struct ToFactory : ToFactoryBase { - static inline return_t convert(v8::Local val) { - if (val.IsEmpty() || !val->IsFunction()) return MaybeLocal(); - return MaybeLocal(val.As()); - } -}; - -#define X(TYPE) \ - template<> \ - struct ToFactory : ToFactoryBase { \ - static inline return_t convert(v8::Local val); \ - }; - -X(Boolean) -X(Number) -X(String) -X(Object) -X(Integer) -X(Uint32) -X(Int32) - -#undef X - -#define X(TYPE) \ - template<> \ - struct ToFactory : ValueFactoryBase { \ - static inline return_t convert(v8::Local val); \ - }; - -X(bool) -X(double) -X(int64_t) -X(uint32_t) -X(int32_t) - -#undef X -} // end of namespace imp - -template -inline -typename imp::ToFactory::return_t To(v8::Local val) { - return imp::ToFactory::convert(val); -} - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -# include "nan_converters_43_inl.h" -#else -# include "nan_converters_pre_43_inl.h" -#endif - -#endif // NAN_CONVERTERS_H_ diff --git a/node_modules/nan/nan_converters_43_inl.h b/node_modules/nan/nan_converters_43_inl.h deleted file mode 100644 index 41b72de..0000000 --- a/node_modules/nan/nan_converters_43_inl.h +++ /dev/null @@ -1,68 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_CONVERTERS_43_INL_H_ -#define NAN_CONVERTERS_43_INL_H_ - -#define X(TYPE) \ -imp::ToFactory::return_t \ -imp::ToFactory::convert(v8::Local val) { \ - v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ - v8::EscapableHandleScope scope(isolate); \ - return scope.Escape( \ - val->To ## TYPE(isolate->GetCurrentContext()) \ - .FromMaybe(v8::Local())); \ -} - -X(Number) -X(String) -X(Object) -X(Integer) -X(Uint32) -X(Int32) -// V8 <= 7.0 -#if V8_MAJOR_VERSION < 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION == 0) -X(Boolean) -#else -imp::ToFactory::return_t \ -imp::ToFactory::convert(v8::Local val) { \ - v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ - v8::EscapableHandleScope scope(isolate); \ - return scope.Escape(val->ToBoolean(isolate)); \ -} -#endif - -#undef X - -#define X(TYPE, NAME) \ -imp::ToFactory::return_t \ -imp::ToFactory::convert(v8::Local val) { \ - v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ - v8::HandleScope scope(isolate); \ - return val->NAME ## Value(isolate->GetCurrentContext()); \ -} - -X(double, Number) -X(int64_t, Integer) -X(uint32_t, Uint32) -X(int32_t, Int32) -// V8 <= 7.0 -#if V8_MAJOR_VERSION < 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION == 0) -X(bool, Boolean) -#else -imp::ToFactory::return_t \ -imp::ToFactory::convert(v8::Local val) { \ - v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ - v8::HandleScope scope(isolate); \ - return Just(val->BooleanValue(isolate)); \ -} -#endif - -#undef X - -#endif // NAN_CONVERTERS_43_INL_H_ diff --git a/node_modules/nan/nan_converters_pre_43_inl.h b/node_modules/nan/nan_converters_pre_43_inl.h deleted file mode 100644 index ae0518a..0000000 --- a/node_modules/nan/nan_converters_pre_43_inl.h +++ /dev/null @@ -1,42 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_CONVERTERS_PRE_43_INL_H_ -#define NAN_CONVERTERS_PRE_43_INL_H_ - -#define X(TYPE) \ -imp::ToFactory::return_t \ -imp::ToFactory::convert(v8::Local val) { \ - return val->To ## TYPE(); \ -} - -X(Boolean) -X(Number) -X(String) -X(Object) -X(Integer) -X(Uint32) -X(Int32) - -#undef X - -#define X(TYPE, NAME) \ -imp::ToFactory::return_t \ -imp::ToFactory::convert(v8::Local val) { \ - return Just(val->NAME ## Value()); \ -} - -X(bool, Boolean) -X(double, Number) -X(int64_t, Integer) -X(uint32_t, Uint32) -X(int32_t, Int32) - -#undef X - -#endif // NAN_CONVERTERS_PRE_43_INL_H_ diff --git a/node_modules/nan/nan_define_own_property_helper.h b/node_modules/nan/nan_define_own_property_helper.h deleted file mode 100644 index d710ef2..0000000 --- a/node_modules/nan/nan_define_own_property_helper.h +++ /dev/null @@ -1,29 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_DEFINE_OWN_PROPERTY_HELPER_H_ -#define NAN_DEFINE_OWN_PROPERTY_HELPER_H_ - -namespace imp { - -inline Maybe DefineOwnPropertyHelper( - v8::PropertyAttribute current - , v8::Handle obj - , v8::Handle key - , v8::Handle value - , v8::PropertyAttribute attribs = v8::None) { - return !(current & v8::DontDelete) || // configurable OR - (!(current & v8::ReadOnly) && // writable AND - !((attribs ^ current) & ~v8::ReadOnly)) // same excluding RO - ? Just(obj->ForceSet(key, value, attribs)) - : Nothing(); -} - -} // end of namespace imp - -#endif // NAN_DEFINE_OWN_PROPERTY_HELPER_H_ diff --git a/node_modules/nan/nan_implementation_12_inl.h b/node_modules/nan/nan_implementation_12_inl.h deleted file mode 100644 index 255293a..0000000 --- a/node_modules/nan/nan_implementation_12_inl.h +++ /dev/null @@ -1,430 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_IMPLEMENTATION_12_INL_H_ -#define NAN_IMPLEMENTATION_12_INL_H_ -//============================================================================== -// node v0.11 implementation -//============================================================================== - -namespace imp { - -//=== Array ==================================================================== - -Factory::return_t -Factory::New() { - return v8::Array::New(v8::Isolate::GetCurrent()); -} - -Factory::return_t -Factory::New(int length) { - return v8::Array::New(v8::Isolate::GetCurrent(), length); -} - -//=== Boolean ================================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::Boolean::New(v8::Isolate::GetCurrent(), value); -} - -//=== Boolean Object =========================================================== - -Factory::return_t -Factory::New(bool value) { -#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION) - return v8::BooleanObject::New( - v8::Isolate::GetCurrent(), value).As(); -#else - return v8::BooleanObject::New(value).As(); -#endif -} - -//=== Context ================================================================== - -Factory::return_t -Factory::New( v8::ExtensionConfiguration* extensions - , v8::Local tmpl - , v8::Local obj) { - return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj); -} - -//=== Date ===================================================================== - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -Factory::return_t -Factory::New(double value) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(v8::Date::New(isolate->GetCurrentContext(), value) - .FromMaybe(v8::Local()).As()); -} -#else -Factory::return_t -Factory::New(double value) { - return v8::Date::New(v8::Isolate::GetCurrent(), value).As(); -} -#endif - -//=== External ================================================================= - -Factory::return_t -Factory::New(void * value) { - return v8::External::New(v8::Isolate::GetCurrent(), value); -} - -//=== Function ================================================================= - -Factory::return_t -Factory::New( FunctionCallback callback - , v8::Local data) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::Local tpl = v8::ObjectTemplate::New(isolate); - tpl->SetInternalFieldCount(imp::kFunctionFieldCount); - v8::Local obj = NewInstance(tpl).ToLocalChecked(); - - obj->SetInternalField( - imp::kFunctionIndex - , v8::External::New(isolate, reinterpret_cast(callback))); - - v8::Local val = v8::Local::New(isolate, data); - - if (!val.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, val); - } - -#if NODE_MAJOR_VERSION >= 10 - v8::Local context = isolate->GetCurrentContext(); - v8::Local function = - v8::Function::New(context, imp::FunctionCallbackWrapper, obj) - .ToLocalChecked(); -#else - v8::Local function = - v8::Function::New(isolate, imp::FunctionCallbackWrapper, obj); -#endif - - return scope.Escape(function); -} - -//=== Function Template ======================================================== - -Factory::return_t -Factory::New( FunctionCallback callback - , v8::Local data - , v8::Local signature) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - if (callback) { - v8::EscapableHandleScope scope(isolate); - v8::Local tpl = v8::ObjectTemplate::New(isolate); - tpl->SetInternalFieldCount(imp::kFunctionFieldCount); - v8::Local obj = NewInstance(tpl).ToLocalChecked(); - - obj->SetInternalField( - imp::kFunctionIndex - , v8::External::New(isolate, reinterpret_cast(callback))); - v8::Local val = v8::Local::New(isolate, data); - - if (!val.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, val); - } - - return scope.Escape(v8::FunctionTemplate::New( isolate - , imp::FunctionCallbackWrapper - , obj - , signature)); - } else { - return v8::FunctionTemplate::New(isolate, 0, data, signature); - } -} - -//=== Number =================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Number::New(v8::Isolate::GetCurrent(), value); -} - -//=== Number Object ============================================================ - -Factory::return_t -Factory::New(double value) { - return v8::NumberObject::New( v8::Isolate::GetCurrent() - , value).As(); -} - -//=== Integer, Int32 and Uint32 ================================================ - -template -typename IntegerFactory::return_t -IntegerFactory::New(int32_t value) { - return To(T::New(v8::Isolate::GetCurrent(), value)); -} - -template -typename IntegerFactory::return_t -IntegerFactory::New(uint32_t value) { - return To(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -Factory::return_t -Factory::New(int32_t value) { - return To( - v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -Factory::return_t -Factory::New(uint32_t value) { - return To( - v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); -} - -//=== Object =================================================================== - -Factory::return_t -Factory::New() { - return v8::Object::New(v8::Isolate::GetCurrent()); -} - -//=== Object Template ========================================================== - -Factory::return_t -Factory::New() { - return v8::ObjectTemplate::New(v8::Isolate::GetCurrent()); -} - -//=== RegExp =================================================================== - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -Factory::return_t -Factory::New( - v8::Local pattern - , v8::RegExp::Flags flags) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape( - v8::RegExp::New(isolate->GetCurrentContext(), pattern, flags) - .FromMaybe(v8::Local())); -} -#else -Factory::return_t -Factory::New( - v8::Local pattern - , v8::RegExp::Flags flags) { - return v8::RegExp::New(pattern, flags); -} -#endif - -//=== Script =================================================================== - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -Factory::return_t -Factory::New( v8::Local source) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::ScriptCompiler::Source src(source); - return scope.Escape( - v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src) - .FromMaybe(v8::Local())); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::ScriptCompiler::Source src(source, origin); - return scope.Escape( - v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src) - .FromMaybe(v8::Local())); -} -#else -Factory::return_t -Factory::New( v8::Local source) { - v8::ScriptCompiler::Source src(source); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::ScriptCompiler::Source src(source, origin); - return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); -} -#endif - -//=== Signature ================================================================ - -Factory::return_t -Factory::New(Factory::FTH receiver) { - return v8::Signature::New(v8::Isolate::GetCurrent(), receiver); -} - -//=== String =================================================================== - -Factory::return_t -Factory::New() { - return v8::String::Empty(v8::Isolate::GetCurrent()); -} - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -Factory::return_t -Factory::New(const char * value, int length) { - return v8::String::NewFromUtf8( - v8::Isolate::GetCurrent(), value, v8::NewStringType::kNormal, length); -} - -Factory::return_t -Factory::New(std::string const& value) { - assert(value.size() <= INT_MAX && "string too long"); - return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), - value.data(), v8::NewStringType::kNormal, static_cast(value.size())); -} - -Factory::return_t -Factory::New(const uint16_t * value, int length) { - return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value, - v8::NewStringType::kNormal, length); -} - -Factory::return_t -Factory::New(v8::String::ExternalStringResource * value) { - return v8::String::NewExternalTwoByte(v8::Isolate::GetCurrent(), value); -} - -Factory::return_t -Factory::New(ExternalOneByteStringResource * value) { - return v8::String::NewExternalOneByte(v8::Isolate::GetCurrent(), value); -} -#else -Factory::return_t -Factory::New(const char * value, int length) { - return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); -} - -Factory::return_t -Factory::New( - std::string const& value) /* NOLINT(build/include_what_you_use) */ { - assert(value.size() <= INT_MAX && "string too long"); - return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value.data(), - v8::String::kNormalString, - static_cast(value.size())); -} - -Factory::return_t -Factory::New(const uint16_t * value, int length) { - return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value, - v8::String::kNormalString, length); -} - -Factory::return_t -Factory::New(v8::String::ExternalStringResource * value) { - return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); -} - -Factory::return_t -Factory::New(ExternalOneByteStringResource * value) { - return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); -} -#endif - -//=== String Object ============================================================ - -// See https://github.com/nodejs/nan/pull/811#discussion_r224594980. -// Disable the warning as there is no way around it. -// TODO(bnoordhuis) Use isolate-based version in Node.js v12. -Factory::return_t -Factory::New(v8::Local value) { -// V8 > 7.0 -#if V8_MAJOR_VERSION > 7 || (V8_MAJOR_VERSION == 7 && V8_MINOR_VERSION > 0) - return v8::StringObject::New(v8::Isolate::GetCurrent(), value) - .As(); -#else -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4996) -#endif -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wdeprecated-declarations" -#endif - return v8::StringObject::New(value).As(); -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif -#ifdef _MSC_VER -#pragma warning(pop) -#endif -#endif -} - -//=== Unbound Script =========================================================== - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -Factory::return_t -Factory::New(v8::Local source) { - v8::ScriptCompiler::Source src(source); - return v8::ScriptCompiler::CompileUnboundScript( - v8::Isolate::GetCurrent(), &src); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::ScriptCompiler::Source src(source, origin); - return v8::ScriptCompiler::CompileUnboundScript( - v8::Isolate::GetCurrent(), &src); -} -#else -Factory::return_t -Factory::New(v8::Local source) { - v8::ScriptCompiler::Source src(source); - return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); -} - -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - v8::ScriptCompiler::Source src(source, origin); - return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); -} -#endif - -} // end of namespace imp - -//=== Presistents and Handles ================================================== - -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION -template -inline v8::Local New(v8::Handle h) { - return v8::Local::New(v8::Isolate::GetCurrent(), h); -} -#endif - -template -inline v8::Local New(v8::Persistent const& p) { - return v8::Local::New(v8::Isolate::GetCurrent(), p); -} - -template -inline v8::Local New(Persistent const& p) { - return v8::Local::New(v8::Isolate::GetCurrent(), p); -} - -template -inline v8::Local New(Global const& p) { - return v8::Local::New(v8::Isolate::GetCurrent(), p); -} - -#endif // NAN_IMPLEMENTATION_12_INL_H_ diff --git a/node_modules/nan/nan_implementation_pre_12_inl.h b/node_modules/nan/nan_implementation_pre_12_inl.h deleted file mode 100644 index 1472421..0000000 --- a/node_modules/nan/nan_implementation_pre_12_inl.h +++ /dev/null @@ -1,263 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_ -#define NAN_IMPLEMENTATION_PRE_12_INL_H_ - -//============================================================================== -// node v0.10 implementation -//============================================================================== - -namespace imp { - -//=== Array ==================================================================== - -Factory::return_t -Factory::New() { - return v8::Array::New(); -} - -Factory::return_t -Factory::New(int length) { - return v8::Array::New(length); -} - -//=== Boolean ================================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::Boolean::New(value)->ToBoolean(); -} - -//=== Boolean Object =========================================================== - -Factory::return_t -Factory::New(bool value) { - return v8::BooleanObject::New(value).As(); -} - -//=== Context ================================================================== - -Factory::return_t -Factory::New( v8::ExtensionConfiguration* extensions - , v8::Local tmpl - , v8::Local obj) { - v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); - v8::Local lctx = v8::Local::New(ctx); - ctx.Dispose(); - return lctx; -} - -//=== Date ===================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Date::New(value).As(); -} - -//=== External ================================================================= - -Factory::return_t -Factory::New(void * value) { - return v8::External::New(value); -} - -//=== Function ================================================================= - -Factory::return_t -Factory::New( FunctionCallback callback - , v8::Local data) { - v8::HandleScope scope; - - return scope.Close(Factory::New( - callback, data, v8::Local()) - ->GetFunction()); -} - - -//=== FunctionTemplate ========================================================= - -Factory::return_t -Factory::New( FunctionCallback callback - , v8::Local data - , v8::Local signature) { - if (callback) { - v8::HandleScope scope; - - v8::Local tpl = v8::ObjectTemplate::New(); - tpl->SetInternalFieldCount(imp::kFunctionFieldCount); - v8::Local obj = tpl->NewInstance(); - - obj->SetInternalField( - imp::kFunctionIndex - , v8::External::New(reinterpret_cast(callback))); - - v8::Local val = v8::Local::New(data); - - if (!val.IsEmpty()) { - obj->SetInternalField(imp::kDataIndex, val); - } - - // Note(agnat): Emulate length argument here. Unfortunately, I couldn't find - // a way. Have at it though... - return scope.Close( - v8::FunctionTemplate::New(imp::FunctionCallbackWrapper - , obj - , signature)); - } else { - return v8::FunctionTemplate::New(0, data, signature); - } -} - -//=== Number =================================================================== - -Factory::return_t -Factory::New(double value) { - return v8::Number::New(value); -} - -//=== Number Object ============================================================ - -Factory::return_t -Factory::New(double value) { - return v8::NumberObject::New(value).As(); -} - -//=== Integer, Int32 and Uint32 ================================================ - -template -typename IntegerFactory::return_t -IntegerFactory::New(int32_t value) { - return To(T::New(value)); -} - -template -typename IntegerFactory::return_t -IntegerFactory::New(uint32_t value) { - return To(T::NewFromUnsigned(value)); -} - -Factory::return_t -Factory::New(int32_t value) { - return To(v8::Uint32::NewFromUnsigned(value)); -} - -Factory::return_t -Factory::New(uint32_t value) { - return To(v8::Uint32::NewFromUnsigned(value)); -} - - -//=== Object =================================================================== - -Factory::return_t -Factory::New() { - return v8::Object::New(); -} - -//=== Object Template ========================================================== - -Factory::return_t -Factory::New() { - return v8::ObjectTemplate::New(); -} - -//=== RegExp =================================================================== - -Factory::return_t -Factory::New( - v8::Local pattern - , v8::RegExp::Flags flags) { - return v8::RegExp::New(pattern, flags); -} - -//=== Script =================================================================== - -Factory::return_t -Factory::New( v8::Local source) { - return v8::Script::New(source); -} -Factory::return_t -Factory::New( v8::Local source - , v8::ScriptOrigin const& origin) { - return v8::Script::New(source, const_cast(&origin)); -} - -//=== Signature ================================================================ - -Factory::return_t -Factory::New(Factory::FTH receiver) { - return v8::Signature::New(receiver); -} - -//=== String =================================================================== - -Factory::return_t -Factory::New() { - return v8::String::Empty(); -} - -Factory::return_t -Factory::New(const char * value, int length) { - return v8::String::New(value, length); -} - -Factory::return_t -Factory::New( - std::string const& value) /* NOLINT(build/include_what_you_use) */ { - assert(value.size() <= INT_MAX && "string too long"); - return v8::String::New(value.data(), static_cast(value.size())); -} - -Factory::return_t -Factory::New(const uint16_t * value, int length) { - return v8::String::New(value, length); -} - -Factory::return_t -Factory::New(v8::String::ExternalStringResource * value) { - return v8::String::NewExternal(value); -} - -Factory::return_t -Factory::New(v8::String::ExternalAsciiStringResource * value) { - return v8::String::NewExternal(value); -} - -//=== String Object ============================================================ - -Factory::return_t -Factory::New(v8::Local value) { - return v8::StringObject::New(value).As(); -} - -} // end of namespace imp - -//=== Presistents and Handles ================================================== - -template -inline v8::Local New(v8::Handle h) { - return v8::Local::New(h); -} - -template -inline v8::Local New(v8::Persistent const& p) { - return v8::Local::New(p); -} - -template -inline v8::Local New(Persistent const& p) { - return v8::Local::New(p.persistent); -} - -template -inline v8::Local New(Global const& p) { - return v8::Local::New(p.persistent); -} - -#endif // NAN_IMPLEMENTATION_PRE_12_INL_H_ diff --git a/node_modules/nan/nan_json.h b/node_modules/nan/nan_json.h deleted file mode 100644 index 33ac8ba..0000000 --- a/node_modules/nan/nan_json.h +++ /dev/null @@ -1,166 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_JSON_H_ -#define NAN_JSON_H_ - -#if NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION -#define NAN_JSON_H_NEED_PARSE 1 -#else -#define NAN_JSON_H_NEED_PARSE 0 -#endif // NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION - -#if NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION -#define NAN_JSON_H_NEED_STRINGIFY 0 -#else -#define NAN_JSON_H_NEED_STRINGIFY 1 -#endif // NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION - -class JSON { - public: - JSON() { -#if NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY - Nan::HandleScope scope; - - Nan::MaybeLocal maybe_global_json = Nan::Get( - Nan::GetCurrentContext()->Global(), - Nan::New("JSON").ToLocalChecked() - ); - - assert(!maybe_global_json.IsEmpty() && "global JSON is empty"); - v8::Local val_global_json = maybe_global_json.ToLocalChecked(); - - assert(val_global_json->IsObject() && "global JSON is not an object"); - Nan::MaybeLocal maybe_obj_global_json = - Nan::To(val_global_json); - - assert(!maybe_obj_global_json.IsEmpty() && "global JSON object is empty"); - v8::Local global_json = maybe_obj_global_json.ToLocalChecked(); - -#if NAN_JSON_H_NEED_PARSE - Nan::MaybeLocal maybe_parse_method = Nan::Get( - global_json, Nan::New("parse").ToLocalChecked() - ); - - assert(!maybe_parse_method.IsEmpty() && "JSON.parse is empty"); - v8::Local parse_method = maybe_parse_method.ToLocalChecked(); - - assert(parse_method->IsFunction() && "JSON.parse is not a function"); - parse_cb_.Reset(parse_method.As()); -#endif // NAN_JSON_H_NEED_PARSE - -#if NAN_JSON_H_NEED_STRINGIFY - Nan::MaybeLocal maybe_stringify_method = Nan::Get( - global_json, Nan::New("stringify").ToLocalChecked() - ); - - assert(!maybe_stringify_method.IsEmpty() && "JSON.stringify is empty"); - v8::Local stringify_method = - maybe_stringify_method.ToLocalChecked(); - - assert( - stringify_method->IsFunction() && "JSON.stringify is not a function" - ); - stringify_cb_.Reset(stringify_method.As()); -#endif // NAN_JSON_H_NEED_STRINGIFY -#endif // NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY - } - - inline - Nan::MaybeLocal Parse(v8::Local json_string) { - Nan::EscapableHandleScope scope; -#if NAN_JSON_H_NEED_PARSE - return scope.Escape(parse(json_string)); -#else - Nan::MaybeLocal result; -#if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION && \ - NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION - result = v8::JSON::Parse(json_string); -#else -#if NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION - v8::Local context_or_isolate = Nan::GetCurrentContext(); -#else - v8::Isolate* context_or_isolate = v8::Isolate::GetCurrent(); -#endif // NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION - result = v8::JSON::Parse(context_or_isolate, json_string); -#endif // NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION && - // NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION - if (result.IsEmpty()) return v8::Local(); - return scope.Escape(result.ToLocalChecked()); -#endif // NAN_JSON_H_NEED_PARSE - } - - inline - Nan::MaybeLocal Stringify(v8::Local json_object) { - Nan::EscapableHandleScope scope; - Nan::MaybeLocal result = -#if NAN_JSON_H_NEED_STRINGIFY - Nan::To(stringify(json_object)); -#else - v8::JSON::Stringify(Nan::GetCurrentContext(), json_object); -#endif // NAN_JSON_H_NEED_STRINGIFY - if (result.IsEmpty()) return v8::Local(); - return scope.Escape(result.ToLocalChecked()); - } - - inline - Nan::MaybeLocal Stringify(v8::Local json_object, - v8::Local gap) { - Nan::EscapableHandleScope scope; - Nan::MaybeLocal result = -#if NAN_JSON_H_NEED_STRINGIFY - Nan::To(stringify(json_object, gap)); -#else - v8::JSON::Stringify(Nan::GetCurrentContext(), json_object, gap); -#endif // NAN_JSON_H_NEED_STRINGIFY - if (result.IsEmpty()) return v8::Local(); - return scope.Escape(result.ToLocalChecked()); - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(JSON) -#if NAN_JSON_H_NEED_PARSE - Nan::Callback parse_cb_; -#endif // NAN_JSON_H_NEED_PARSE -#if NAN_JSON_H_NEED_STRINGIFY - Nan::Callback stringify_cb_; -#endif // NAN_JSON_H_NEED_STRINGIFY - -#if NAN_JSON_H_NEED_PARSE - inline v8::Local parse(v8::Local arg) { - assert(!parse_cb_.IsEmpty() && "parse_cb_ is empty"); - AsyncResource resource("nan:JSON.parse"); - return parse_cb_.Call(1, &arg, &resource).FromMaybe(v8::Local()); - } -#endif // NAN_JSON_H_NEED_PARSE - -#if NAN_JSON_H_NEED_STRINGIFY - inline v8::Local stringify(v8::Local arg) { - assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty"); - AsyncResource resource("nan:JSON.stringify"); - return stringify_cb_.Call(1, &arg, &resource) - .FromMaybe(v8::Local()); - } - - inline v8::Local stringify(v8::Local arg, - v8::Local gap) { - assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty"); - - v8::Local argv[] = { - arg, - Nan::Null(), - gap - }; - AsyncResource resource("nan:JSON.stringify"); - return stringify_cb_.Call(3, argv, &resource) - .FromMaybe(v8::Local()); - } -#endif // NAN_JSON_H_NEED_STRINGIFY -}; - -#endif // NAN_JSON_H_ diff --git a/node_modules/nan/nan_maybe_43_inl.h b/node_modules/nan/nan_maybe_43_inl.h deleted file mode 100644 index c04ce30..0000000 --- a/node_modules/nan/nan_maybe_43_inl.h +++ /dev/null @@ -1,356 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_MAYBE_43_INL_H_ -#define NAN_MAYBE_43_INL_H_ - -template -using MaybeLocal = v8::MaybeLocal; - -inline -MaybeLocal ToDetailString(v8::Local val) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(val->ToDetailString(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline -MaybeLocal ToArrayIndex(v8::Local val) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(val->ToArrayIndex(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline -Maybe Equals(v8::Local a, v8::Local(b)) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return a->Equals(isolate->GetCurrentContext(), b); -} - -inline -MaybeLocal NewInstance(v8::Local h) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(h->NewInstance(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline -MaybeLocal NewInstance( - v8::Local h - , int argc - , v8::Local argv[]) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(h->NewInstance(isolate->GetCurrentContext(), argc, argv) - .FromMaybe(v8::Local())); -} - -inline -MaybeLocal NewInstance(v8::Local h) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(h->NewInstance(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - - -inline MaybeLocal GetFunction( - v8::Local t) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(t->GetFunction(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline Maybe Set( - v8::Local obj - , v8::Local key - , v8::Local value) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->Set(isolate->GetCurrentContext(), key, value); -} - -inline Maybe Set( - v8::Local obj - , uint32_t index - , v8::Local value) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->Set(isolate->GetCurrentContext(), index, value); -} - -#if NODE_MODULE_VERSION < NODE_4_0_MODULE_VERSION -#include "nan_define_own_property_helper.h" // NOLINT(build/include) -#endif - -inline Maybe DefineOwnProperty( - v8::Local obj - , v8::Local key - , v8::Local value - , v8::PropertyAttribute attribs = v8::None) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); -#if NODE_MODULE_VERSION >= NODE_4_0_MODULE_VERSION - return obj->DefineOwnProperty(isolate->GetCurrentContext(), key, value, - attribs); -#else - Maybe maybeCurrent = - obj->GetPropertyAttributes(isolate->GetCurrentContext(), key); - if (maybeCurrent.IsNothing()) { - return Nothing(); - } - v8::PropertyAttribute current = maybeCurrent.FromJust(); - return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs); -#endif -} - -NAN_DEPRECATED inline Maybe ForceSet( - v8::Local obj - , v8::Local key - , v8::Local value - , v8::PropertyAttribute attribs = v8::None) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); -#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION - return key->IsName() - ? obj->DefineOwnProperty(isolate->GetCurrentContext(), - key.As(), value, attribs) - : Nothing(); -#else - return obj->ForceSet(isolate->GetCurrentContext(), key, value, attribs); -#endif -} - -inline MaybeLocal Get( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(obj->Get(isolate->GetCurrentContext(), key) - .FromMaybe(v8::Local())); -} - -inline -MaybeLocal Get(v8::Local obj, uint32_t index) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(obj->Get(isolate->GetCurrentContext(), index) - .FromMaybe(v8::Local())); -} - -inline v8::PropertyAttribute GetPropertyAttributes( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->GetPropertyAttributes(isolate->GetCurrentContext(), key) - .FromJust(); -} - -inline Maybe Has( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->Has(isolate->GetCurrentContext(), key); -} - -inline Maybe Has(v8::Local obj, uint32_t index) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->Has(isolate->GetCurrentContext(), index); -} - -inline Maybe Delete( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->Delete(isolate->GetCurrentContext(), key); -} - -inline -Maybe Delete(v8::Local obj, uint32_t index) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->Delete(isolate->GetCurrentContext(), index); -} - -inline -MaybeLocal GetPropertyNames(v8::Local obj) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(obj->GetPropertyNames(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline -MaybeLocal GetOwnPropertyNames(v8::Local obj) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(obj->GetOwnPropertyNames(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline Maybe SetPrototype( - v8::Local obj - , v8::Local prototype) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->SetPrototype(isolate->GetCurrentContext(), prototype); -} - -inline MaybeLocal ObjectProtoToString( - v8::Local obj) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(obj->ObjectProtoToString(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline Maybe HasOwnProperty( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->HasOwnProperty(isolate->GetCurrentContext(), key); -} - -inline Maybe HasRealNamedProperty( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->HasRealNamedProperty(isolate->GetCurrentContext(), key); -} - -inline Maybe HasRealIndexedProperty( - v8::Local obj - , uint32_t index) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->HasRealIndexedProperty(isolate->GetCurrentContext(), index); -} - -inline Maybe HasRealNamedCallbackProperty( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return obj->HasRealNamedCallbackProperty(isolate->GetCurrentContext(), key); -} - -inline MaybeLocal GetRealNamedPropertyInPrototypeChain( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(obj->GetRealNamedPropertyInPrototypeChain( - isolate->GetCurrentContext(), key) - .FromMaybe(v8::Local())); -} - -inline MaybeLocal GetRealNamedProperty( - v8::Local obj - , v8::Local key) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape( - obj->GetRealNamedProperty(isolate->GetCurrentContext(), key) - .FromMaybe(v8::Local())); -} - -inline MaybeLocal CallAsFunction( - v8::Local obj - , v8::Local recv - , int argc - , v8::Local argv[]) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape( - obj->CallAsFunction(isolate->GetCurrentContext(), recv, argc, argv) - .FromMaybe(v8::Local())); -} - -inline MaybeLocal CallAsConstructor( - v8::Local obj - , int argc, v8::Local argv[]) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape( - obj->CallAsConstructor(isolate->GetCurrentContext(), argc, argv) - .FromMaybe(v8::Local())); -} - -inline -MaybeLocal GetSourceLine(v8::Local msg) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(msg->GetSourceLine(isolate->GetCurrentContext()) - .FromMaybe(v8::Local())); -} - -inline Maybe GetLineNumber(v8::Local msg) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return msg->GetLineNumber(isolate->GetCurrentContext()); -} - -inline Maybe GetStartColumn(v8::Local msg) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return msg->GetStartColumn(isolate->GetCurrentContext()); -} - -inline Maybe GetEndColumn(v8::Local msg) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - return msg->GetEndColumn(isolate->GetCurrentContext()); -} - -inline MaybeLocal CloneElementAt( - v8::Local array - , uint32_t index) { -#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION) - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::Local context = isolate->GetCurrentContext(); - v8::Local elem; - v8::Local obj; - if (!array->Get(context, index).ToLocal(&elem)) { - return scope.Escape(obj); - } - if (!elem->ToObject(context).ToLocal(&obj)) { - return scope.Escape(v8::Local()); - } - return scope.Escape(obj->Clone()); -#else - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(array->CloneElementAt(isolate->GetCurrentContext(), index) - .FromMaybe(v8::Local())); -#endif -} - -inline MaybeLocal Call( - v8::Local fun - , v8::Local recv - , int argc - , v8::Local argv[]) { - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - return scope.Escape(fun->Call(isolate->GetCurrentContext(), recv, argc, argv) - .FromMaybe(v8::Local())); -} - -#endif // NAN_MAYBE_43_INL_H_ diff --git a/node_modules/nan/nan_maybe_pre_43_inl.h b/node_modules/nan/nan_maybe_pre_43_inl.h deleted file mode 100644 index 83325ae..0000000 --- a/node_modules/nan/nan_maybe_pre_43_inl.h +++ /dev/null @@ -1,268 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_MAYBE_PRE_43_INL_H_ -#define NAN_MAYBE_PRE_43_INL_H_ - -template -class MaybeLocal { - public: - inline MaybeLocal() : val_(v8::Local()) {} - - template -# if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION - inline - MaybeLocal(v8::Local that) : val_(that) {} // NOLINT(runtime/explicit) -# else - inline - MaybeLocal(v8::Local that) : // NOLINT(runtime/explicit) - val_(*reinterpret_cast*>(&that)) {} -# endif - - inline bool IsEmpty() const { return val_.IsEmpty(); } - - template - inline bool ToLocal(v8::Local *out) const { - *out = val_; - return !IsEmpty(); - } - - inline v8::Local ToLocalChecked() const { -#if defined(V8_ENABLE_CHECKS) - assert(!IsEmpty() && "ToLocalChecked is Empty"); -#endif // V8_ENABLE_CHECKS - return val_; - } - - template - inline v8::Local FromMaybe(v8::Local default_value) const { - return IsEmpty() ? default_value : v8::Local(val_); - } - - private: - v8::Local val_; -}; - -inline -MaybeLocal ToDetailString(v8::Handle val) { - return MaybeLocal(val->ToDetailString()); -} - -inline -MaybeLocal ToArrayIndex(v8::Handle val) { - return MaybeLocal(val->ToArrayIndex()); -} - -inline -Maybe Equals(v8::Handle a, v8::Handle(b)) { - return Just(a->Equals(b)); -} - -inline -MaybeLocal NewInstance(v8::Handle h) { - return MaybeLocal(h->NewInstance()); -} - -inline -MaybeLocal NewInstance( - v8::Local h - , int argc - , v8::Local argv[]) { - return MaybeLocal(h->NewInstance(argc, argv)); -} - -inline -MaybeLocal NewInstance(v8::Handle h) { - return MaybeLocal(h->NewInstance()); -} - -inline -MaybeLocal GetFunction(v8::Handle t) { - return MaybeLocal(t->GetFunction()); -} - -inline Maybe Set( - v8::Handle obj - , v8::Handle key - , v8::Handle value) { - return Just(obj->Set(key, value)); -} - -inline Maybe Set( - v8::Handle obj - , uint32_t index - , v8::Handle value) { - return Just(obj->Set(index, value)); -} - -#include "nan_define_own_property_helper.h" // NOLINT(build/include) - -inline Maybe DefineOwnProperty( - v8::Handle obj - , v8::Handle key - , v8::Handle value - , v8::PropertyAttribute attribs = v8::None) { - v8::PropertyAttribute current = obj->GetPropertyAttributes(key); - return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs); -} - -NAN_DEPRECATED inline Maybe ForceSet( - v8::Handle obj - , v8::Handle key - , v8::Handle value - , v8::PropertyAttribute attribs = v8::None) { - return Just(obj->ForceSet(key, value, attribs)); -} - -inline MaybeLocal Get( - v8::Handle obj - , v8::Handle key) { - return MaybeLocal(obj->Get(key)); -} - -inline MaybeLocal Get( - v8::Handle obj - , uint32_t index) { - return MaybeLocal(obj->Get(index)); -} - -inline Maybe GetPropertyAttributes( - v8::Handle obj - , v8::Handle key) { - return Just(obj->GetPropertyAttributes(key)); -} - -inline Maybe Has( - v8::Handle obj - , v8::Handle key) { - return Just(obj->Has(key)); -} - -inline Maybe Has( - v8::Handle obj - , uint32_t index) { - return Just(obj->Has(index)); -} - -inline Maybe Delete( - v8::Handle obj - , v8::Handle key) { - return Just(obj->Delete(key)); -} - -inline Maybe Delete( - v8::Handle obj - , uint32_t index) { - return Just(obj->Delete(index)); -} - -inline -MaybeLocal GetPropertyNames(v8::Handle obj) { - return MaybeLocal(obj->GetPropertyNames()); -} - -inline -MaybeLocal GetOwnPropertyNames(v8::Handle obj) { - return MaybeLocal(obj->GetOwnPropertyNames()); -} - -inline Maybe SetPrototype( - v8::Handle obj - , v8::Handle prototype) { - return Just(obj->SetPrototype(prototype)); -} - -inline MaybeLocal ObjectProtoToString( - v8::Handle obj) { - return MaybeLocal(obj->ObjectProtoToString()); -} - -inline Maybe HasOwnProperty( - v8::Handle obj - , v8::Handle key) { - return Just(obj->HasOwnProperty(key)); -} - -inline Maybe HasRealNamedProperty( - v8::Handle obj - , v8::Handle key) { - return Just(obj->HasRealNamedProperty(key)); -} - -inline Maybe HasRealIndexedProperty( - v8::Handle obj - , uint32_t index) { - return Just(obj->HasRealIndexedProperty(index)); -} - -inline Maybe HasRealNamedCallbackProperty( - v8::Handle obj - , v8::Handle key) { - return Just(obj->HasRealNamedCallbackProperty(key)); -} - -inline MaybeLocal GetRealNamedPropertyInPrototypeChain( - v8::Handle obj - , v8::Handle key) { - return MaybeLocal( - obj->GetRealNamedPropertyInPrototypeChain(key)); -} - -inline MaybeLocal GetRealNamedProperty( - v8::Handle obj - , v8::Handle key) { - return MaybeLocal(obj->GetRealNamedProperty(key)); -} - -inline MaybeLocal CallAsFunction( - v8::Handle obj - , v8::Handle recv - , int argc - , v8::Handle argv[]) { - return MaybeLocal(obj->CallAsFunction(recv, argc, argv)); -} - -inline MaybeLocal CallAsConstructor( - v8::Handle obj - , int argc - , v8::Local argv[]) { - return MaybeLocal(obj->CallAsConstructor(argc, argv)); -} - -inline -MaybeLocal GetSourceLine(v8::Handle msg) { - return MaybeLocal(msg->GetSourceLine()); -} - -inline Maybe GetLineNumber(v8::Handle msg) { - return Just(msg->GetLineNumber()); -} - -inline Maybe GetStartColumn(v8::Handle msg) { - return Just(msg->GetStartColumn()); -} - -inline Maybe GetEndColumn(v8::Handle msg) { - return Just(msg->GetEndColumn()); -} - -inline MaybeLocal CloneElementAt( - v8::Handle array - , uint32_t index) { - return MaybeLocal(array->CloneElementAt(index)); -} - -inline MaybeLocal Call( - v8::Local fun - , v8::Local recv - , int argc - , v8::Local argv[]) { - return MaybeLocal(fun->Call(recv, argc, argv)); -} - -#endif // NAN_MAYBE_PRE_43_INL_H_ diff --git a/node_modules/nan/nan_new.h b/node_modules/nan/nan_new.h deleted file mode 100644 index cdf8bbe..0000000 --- a/node_modules/nan/nan_new.h +++ /dev/null @@ -1,340 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_NEW_H_ -#define NAN_NEW_H_ - -namespace imp { // scnr - -// TODO(agnat): Generalize -template v8::Local To(v8::Local i); - -template <> -inline -v8::Local -To(v8::Local i) { - return Nan::To(i).ToLocalChecked(); -} - -template <> -inline -v8::Local -To(v8::Local i) { - return Nan::To(i).ToLocalChecked(); -} - -template <> -inline -v8::Local -To(v8::Local i) { - return Nan::To(i).ToLocalChecked(); -} - -template struct FactoryBase { - typedef v8::Local return_t; -}; - -template struct MaybeFactoryBase { - typedef MaybeLocal return_t; -}; - -template struct Factory; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); - static inline return_t New(int length); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(bool value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(bool value); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( v8::ExtensionConfiguration* extensions = NULL - , v8::Local tmpl = v8::Local() - , v8::Local obj = v8::Local()); -}; - -template <> -struct Factory : MaybeFactoryBase { - static inline return_t New(double value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(void *value); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( FunctionCallback callback - , v8::Local data = v8::Local()); -}; - -template <> -struct Factory : FactoryBase { - static inline - return_t - New( FunctionCallback callback = NULL - , v8::Local data = v8::Local() - , v8::Local signature = v8::Local()); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(double value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(double value); -}; - -template -struct IntegerFactory : FactoryBase { - typedef typename FactoryBase::return_t return_t; - static inline return_t New(int32_t value); - static inline return_t New(uint32_t value); -}; - -template <> -struct Factory : IntegerFactory {}; - -template <> -struct Factory : IntegerFactory {}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(int32_t value); - static inline return_t New(uint32_t value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(); -}; - -template <> -struct Factory : MaybeFactoryBase { - static inline return_t New( - v8::Local pattern, v8::RegExp::Flags flags); -}; - -template <> -struct Factory : MaybeFactoryBase { - static inline return_t New( v8::Local source); - static inline return_t New( v8::Local source - , v8::ScriptOrigin const& origin); -}; - -template <> -struct Factory : FactoryBase { - typedef v8::Local FTH; - static inline return_t New(FTH receiver = FTH()); -}; - -template <> -struct Factory : MaybeFactoryBase { - static inline return_t New(); - static inline return_t New(const char *value, int length = -1); - static inline return_t New(const uint16_t *value, int length = -1); - static inline return_t New(std::string const& value); - - static inline return_t New(v8::String::ExternalStringResource * value); - static inline return_t New(ExternalOneByteStringResource * value); -}; - -template <> -struct Factory : FactoryBase { - static inline return_t New(v8::Local value); -}; - -} // end of namespace imp - -#if (NODE_MODULE_VERSION >= 12) - -namespace imp { - -template <> -struct Factory : MaybeFactoryBase { - static inline return_t New( v8::Local source); - static inline return_t New( v8::Local source - , v8::ScriptOrigin const& origin); -}; - -} // end of namespace imp - -# include "nan_implementation_12_inl.h" - -#else // NODE_MODULE_VERSION >= 12 - -# include "nan_implementation_pre_12_inl.h" - -#endif - -//=== API ====================================================================== - -template -typename imp::Factory::return_t -New() { - return imp::Factory::New(); -} - -template -typename imp::Factory::return_t -New(A0 arg0) { - return imp::Factory::New(arg0); -} - -template -typename imp::Factory::return_t -New(A0 arg0, A1 arg1) { - return imp::Factory::New(arg0, arg1); -} - -template -typename imp::Factory::return_t -New(A0 arg0, A1 arg1, A2 arg2) { - return imp::Factory::New(arg0, arg1, arg2); -} - -template -typename imp::Factory::return_t -New(A0 arg0, A1 arg1, A2 arg2, A3 arg3) { - return imp::Factory::New(arg0, arg1, arg2, arg3); -} - -// Note(agnat): When passing overloaded function pointers to template functions -// as generic arguments the compiler needs help in picking the right overload. -// These two functions handle New and New with -// all argument variations. - -// v8::Function and v8::FunctionTemplate with one or two arguments -template -typename imp::Factory::return_t -New( FunctionCallback callback - , v8::Local data = v8::Local()) { - return imp::Factory::New(callback, data); -} - -// v8::Function and v8::FunctionTemplate with three arguments -template -typename imp::Factory::return_t -New( FunctionCallback callback - , v8::Local data = v8::Local() - , A2 a2 = A2()) { - return imp::Factory::New(callback, data, a2); -} - -// Convenience - -#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION -template inline v8::Local New(v8::Handle h); -#endif - -#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION -template - inline v8::Local New(v8::Persistent const& p); -#else -template inline v8::Local New(v8::Persistent const& p); -#endif -template -inline v8::Local New(Persistent const& p); -template -inline v8::Local New(Global const& p); - -inline -imp::Factory::return_t -New(bool value) { - return New(value); -} - -inline -imp::Factory::return_t -New(int32_t value) { - return New(value); -} - -inline -imp::Factory::return_t -New(uint32_t value) { - return New(value); -} - -inline -imp::Factory::return_t -New(double value) { - return New(value); -} - -inline -imp::Factory::return_t -New(std::string const& value) { // NOLINT(build/include_what_you_use) - return New(value); -} - -inline -imp::Factory::return_t -New(const char * value, int length) { - return New(value, length); -} - -inline -imp::Factory::return_t -New(const uint16_t * value, int length) { - return New(value, length); -} - -inline -imp::Factory::return_t -New(const char * value) { - return New(value); -} - -inline -imp::Factory::return_t -New(const uint16_t * value) { - return New(value); -} - -inline -imp::Factory::return_t -New(v8::String::ExternalStringResource * value) { - return New(value); -} - -inline -imp::Factory::return_t -New(ExternalOneByteStringResource * value) { - return New(value); -} - -inline -imp::Factory::return_t -New(v8::Local pattern, v8::RegExp::Flags flags) { - return New(pattern, flags); -} - -#endif // NAN_NEW_H_ diff --git a/node_modules/nan/nan_object_wrap.h b/node_modules/nan/nan_object_wrap.h deleted file mode 100644 index 78712f9..0000000 --- a/node_modules/nan/nan_object_wrap.h +++ /dev/null @@ -1,156 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_OBJECT_WRAP_H_ -#define NAN_OBJECT_WRAP_H_ - -class ObjectWrap { - public: - ObjectWrap() { - refs_ = 0; - } - - - virtual ~ObjectWrap() { - if (persistent().IsEmpty()) { - return; - } - - persistent().ClearWeak(); - persistent().Reset(); - } - - - template - static inline T* Unwrap(v8::Local object) { - assert(!object.IsEmpty()); - assert(object->InternalFieldCount() > 0); - // Cast to ObjectWrap before casting to T. A direct cast from void - // to T won't work right when T has more than one base class. - void* ptr = GetInternalFieldPointer(object, 0); - ObjectWrap* wrap = static_cast(ptr); - return static_cast(wrap); - } - - - inline v8::Local handle() const { - return New(handle_); - } - - - inline Persistent& persistent() { - return handle_; - } - - - protected: - inline void Wrap(v8::Local object) { - assert(persistent().IsEmpty()); - assert(object->InternalFieldCount() > 0); - SetInternalFieldPointer(object, 0, this); - persistent().Reset(object); - MakeWeak(); - } - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - - inline void MakeWeak() { - persistent().v8::PersistentBase::SetWeak( - this, WeakCallback, v8::WeakCallbackType::kParameter); -#if NODE_MAJOR_VERSION < 10 - // FIXME(bnoordhuis) Probably superfluous in older Node.js versions too. - persistent().MarkIndependent(); -#endif - } - -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - - inline void MakeWeak() { - persistent().v8::PersistentBase::SetWeak(this, WeakCallback); - persistent().MarkIndependent(); - } - -#else - - inline void MakeWeak() { - persistent().persistent.MakeWeak(this, WeakCallback); - persistent().MarkIndependent(); - } - -#endif - - /* Ref() marks the object as being attached to an event loop. - * Refed objects will not be garbage collected, even if - * all references are lost. - */ - virtual void Ref() { - assert(!persistent().IsEmpty()); - persistent().ClearWeak(); - refs_++; - } - - /* Unref() marks an object as detached from the event loop. This is its - * default state. When an object with a "weak" reference changes from - * attached to detached state it will be freed. Be careful not to access - * the object after making this call as it might be gone! - * (A "weak reference" means an object that only has a - * persistent handle.) - * - * DO NOT CALL THIS FROM DESTRUCTOR - */ - virtual void Unref() { - assert(!persistent().IsEmpty()); - assert(!persistent().IsWeak()); - assert(refs_ > 0); - if (--refs_ == 0) - MakeWeak(); - } - - int refs_; // ro - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(ObjectWrap) -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - - static void - WeakCallback(v8::WeakCallbackInfo const& info) { - ObjectWrap* wrap = info.GetParameter(); - assert(wrap->refs_ == 0); - wrap->handle_.Reset(); - delete wrap; - } - -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - - static void - WeakCallback(v8::WeakCallbackData const& data) { - ObjectWrap* wrap = data.GetParameter(); - assert(wrap->refs_ == 0); - assert(wrap->handle_.IsNearDeath()); - wrap->handle_.Reset(); - delete wrap; - } - -#else - - static void WeakCallback(v8::Persistent value, void *data) { - ObjectWrap *wrap = static_cast(data); - assert(wrap->refs_ == 0); - assert(wrap->handle_.IsNearDeath()); - wrap->handle_.Reset(); - delete wrap; - } - -#endif - Persistent handle_; -}; - - -#endif // NAN_OBJECT_WRAP_H_ diff --git a/node_modules/nan/nan_persistent_12_inl.h b/node_modules/nan/nan_persistent_12_inl.h deleted file mode 100644 index d9649e8..0000000 --- a/node_modules/nan/nan_persistent_12_inl.h +++ /dev/null @@ -1,132 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_PERSISTENT_12_INL_H_ -#define NAN_PERSISTENT_12_INL_H_ - -template class Persistent : - public v8::Persistent { - public: - inline Persistent() : v8::Persistent() {} - - template inline Persistent(v8::Local that) : - v8::Persistent(v8::Isolate::GetCurrent(), that) {} - - template - inline - Persistent(const v8::Persistent &that) : // NOLINT(runtime/explicit) - v8::Persistent(v8::Isolate::GetCurrent(), that) {} - - inline void Reset() { v8::PersistentBase::Reset(); } - - template - inline void Reset(const v8::Local &other) { - v8::PersistentBase::Reset(v8::Isolate::GetCurrent(), other); - } - - template - inline void Reset(const v8::PersistentBase &other) { - v8::PersistentBase::Reset(v8::Isolate::GetCurrent(), other); - } - - template - inline void SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type); - - private: - inline T *operator*() const { return *PersistentBase::persistent; } - - template - inline void Copy(const Persistent &that) { - TYPE_CHECK(T, S); - - this->Reset(); - - if (!that.IsEmpty()) { - this->Reset(that); - M::Copy(that, this); - } - } -}; - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -template -class Global : public v8::Global { - public: - inline Global() : v8::Global() {} - - template inline Global(v8::Local that) : - v8::Global(v8::Isolate::GetCurrent(), that) {} - - template - inline - Global(const v8::PersistentBase &that) : // NOLINT(runtime/explicit) - v8::Global(v8::Isolate::GetCurrent(), that) {} - - inline void Reset() { v8::PersistentBase::Reset(); } - - template - inline void Reset(const v8::Local &other) { - v8::PersistentBase::Reset(v8::Isolate::GetCurrent(), other); - } - - template - inline void Reset(const v8::PersistentBase &other) { - v8::PersistentBase::Reset(v8::Isolate::GetCurrent(), other); - } - - template - inline void SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - reinterpret_cast*>(this)->SetWeak( - parameter, callback, type); - } -}; -#else -template -class Global : public v8::UniquePersistent { - public: - inline Global() : v8::UniquePersistent() {} - - template inline Global(v8::Local that) : - v8::UniquePersistent(v8::Isolate::GetCurrent(), that) {} - - template - inline - Global(const v8::PersistentBase &that) : // NOLINT(runtime/explicit) - v8::UniquePersistent(v8::Isolate::GetCurrent(), that) {} - - inline void Reset() { v8::PersistentBase::Reset(); } - - template - inline void Reset(const v8::Local &other) { - v8::PersistentBase::Reset(v8::Isolate::GetCurrent(), other); - } - - template - inline void Reset(const v8::PersistentBase &other) { - v8::PersistentBase::Reset(v8::Isolate::GetCurrent(), other); - } - - template - inline void SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - reinterpret_cast*>(this)->SetWeak( - parameter, callback, type); - } -}; -#endif - -#endif // NAN_PERSISTENT_12_INL_H_ diff --git a/node_modules/nan/nan_persistent_pre_12_inl.h b/node_modules/nan/nan_persistent_pre_12_inl.h deleted file mode 100644 index 4c9c59d..0000000 --- a/node_modules/nan/nan_persistent_pre_12_inl.h +++ /dev/null @@ -1,242 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_PERSISTENT_PRE_12_INL_H_ -#define NAN_PERSISTENT_PRE_12_INL_H_ - -template -class PersistentBase { - v8::Persistent persistent; - template - friend v8::Local New(const PersistentBase &p); - template - friend v8::Local New(const Persistent &p); - template - friend v8::Local New(const Global &p); - template friend class ReturnValue; - - public: - inline PersistentBase() : - persistent() {} - - inline void Reset() { - persistent.Dispose(); - persistent.Clear(); - } - - template - inline void Reset(const v8::Local &other) { - TYPE_CHECK(T, S); - - if (!persistent.IsEmpty()) { - persistent.Dispose(); - } - - if (other.IsEmpty()) { - persistent.Clear(); - } else { - persistent = v8::Persistent::New(other); - } - } - - template - inline void Reset(const PersistentBase &other) { - TYPE_CHECK(T, S); - - if (!persistent.IsEmpty()) { - persistent.Dispose(); - } - - if (other.IsEmpty()) { - persistent.Clear(); - } else { - persistent = v8::Persistent::New(other.persistent); - } - } - - inline bool IsEmpty() const { return persistent.IsEmpty(); } - - inline void Empty() { persistent.Clear(); } - - template - inline bool operator==(const PersistentBase &that) const { - return this->persistent == that.persistent; - } - - template - inline bool operator==(const v8::Local &that) const { - return this->persistent == that; - } - - template - inline bool operator!=(const PersistentBase &that) const { - return !operator==(that); - } - - template - inline bool operator!=(const v8::Local &that) const { - return !operator==(that); - } - - template - inline void SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type); - - inline void ClearWeak() { persistent.ClearWeak(); } - - inline void MarkIndependent() { persistent.MarkIndependent(); } - - inline bool IsIndependent() const { return persistent.IsIndependent(); } - - inline bool IsNearDeath() const { return persistent.IsNearDeath(); } - - inline bool IsWeak() const { return persistent.IsWeak(); } - - private: - inline explicit PersistentBase(v8::Persistent that) : - persistent(that) { } - inline explicit PersistentBase(T *val) : persistent(val) {} - template friend class Persistent; - template friend class Global; - friend class ObjectWrap; -}; - -template -class NonCopyablePersistentTraits { - public: - typedef Persistent > - NonCopyablePersistent; - static const bool kResetInDestructor = false; - template - inline static void Copy(const Persistent &source, - NonCopyablePersistent *dest) { - Uncompilable(); - } - - template inline static void Uncompilable() { - TYPE_CHECK(O, v8::Primitive); - } -}; - -template -struct CopyablePersistentTraits { - typedef Persistent > CopyablePersistent; - static const bool kResetInDestructor = true; - template - static inline void Copy(const Persistent &source, - CopyablePersistent *dest) {} -}; - -template class Persistent : - public PersistentBase { - public: - inline Persistent() {} - - template inline Persistent(v8::Handle that) - : PersistentBase(v8::Persistent::New(that)) { - TYPE_CHECK(T, S); - } - - inline Persistent(const Persistent &that) : PersistentBase() { - Copy(that); - } - - template - inline Persistent(const Persistent &that) : - PersistentBase() { - Copy(that); - } - - inline Persistent &operator=(const Persistent &that) { - Copy(that); - return *this; - } - - template - inline Persistent &operator=(const Persistent &that) { - Copy(that); - return *this; - } - - inline ~Persistent() { - if (M::kResetInDestructor) this->Reset(); - } - - private: - inline T *operator*() const { return *PersistentBase::persistent; } - - template - inline void Copy(const Persistent &that) { - TYPE_CHECK(T, S); - - this->Reset(); - - if (!that.IsEmpty()) { - this->persistent = v8::Persistent::New(that.persistent); - M::Copy(that, this); - } - } -}; - -template -class Global : public PersistentBase { - struct RValue { - inline explicit RValue(Global* obj) : object(obj) {} - Global* object; - }; - - public: - inline Global() : PersistentBase(0) { } - - template - inline Global(v8::Local that) // NOLINT(runtime/explicit) - : PersistentBase(v8::Persistent::New(that)) { - TYPE_CHECK(T, S); - } - - template - inline Global(const PersistentBase &that) // NOLINT(runtime/explicit) - : PersistentBase(that) { - TYPE_CHECK(T, S); - } - /** - * Move constructor. - */ - inline Global(RValue rvalue) // NOLINT(runtime/explicit) - : PersistentBase(rvalue.object->persistent) { - rvalue.object->Reset(); - } - inline ~Global() { this->Reset(); } - /** - * Move via assignment. - */ - template - inline Global &operator=(Global rhs) { - TYPE_CHECK(T, S); - this->Reset(rhs.persistent); - rhs.Reset(); - return *this; - } - /** - * Cast operator for moves. - */ - inline operator RValue() { return RValue(this); } - /** - * Pass allows returning uniques from functions, etc. - */ - Global Pass() { return Global(RValue(this)); } - - private: - Global(Global &); - void operator=(Global &); - template friend class ReturnValue; -}; - -#endif // NAN_PERSISTENT_PRE_12_INL_H_ diff --git a/node_modules/nan/nan_private.h b/node_modules/nan/nan_private.h deleted file mode 100644 index 15f44cc..0000000 --- a/node_modules/nan/nan_private.h +++ /dev/null @@ -1,73 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_PRIVATE_H_ -#define NAN_PRIVATE_H_ - -inline Maybe -HasPrivate(v8::Local object, v8::Local key) { - HandleScope scope; -#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::Local context = isolate->GetCurrentContext(); - v8::Local private_key = v8::Private::ForApi(isolate, key); - return object->HasPrivate(context, private_key); -#else - return Just(!object->GetHiddenValue(key).IsEmpty()); -#endif -} - -inline MaybeLocal -GetPrivate(v8::Local object, v8::Local key) { -#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::EscapableHandleScope scope(isolate); - v8::Local context = isolate->GetCurrentContext(); - v8::Local private_key = v8::Private::ForApi(isolate, key); - v8::MaybeLocal v = object->GetPrivate(context, private_key); - return scope.Escape(v.ToLocalChecked()); -#else - EscapableHandleScope scope; - v8::Local v = object->GetHiddenValue(key); - if (v.IsEmpty()) { - v = Undefined(); - } - return scope.Escape(v); -#endif -} - -inline Maybe SetPrivate( - v8::Local object, - v8::Local key, - v8::Local value) { -#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION - HandleScope scope; - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::Local context = isolate->GetCurrentContext(); - v8::Local private_key = v8::Private::ForApi(isolate, key); - return object->SetPrivate(context, private_key, value); -#else - return Just(object->SetHiddenValue(key, value)); -#endif -} - -inline Maybe DeletePrivate( - v8::Local object, - v8::Local key) { -#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION - HandleScope scope; - v8::Isolate *isolate = v8::Isolate::GetCurrent(); - v8::Local private_key = v8::Private::ForApi(isolate, key); - return object->DeletePrivate(isolate->GetCurrentContext(), private_key); -#else - return Just(object->DeleteHiddenValue(key)); -#endif -} - -#endif // NAN_PRIVATE_H_ - diff --git a/node_modules/nan/nan_string_bytes.h b/node_modules/nan/nan_string_bytes.h deleted file mode 100644 index a2e6437..0000000 --- a/node_modules/nan/nan_string_bytes.h +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -#ifndef NAN_STRING_BYTES_H_ -#define NAN_STRING_BYTES_H_ - -// Decodes a v8::Local or Buffer to a raw char* - -namespace imp { - -using v8::Local; -using v8::Object; -using v8::String; -using v8::Value; - - -//// Base 64 //// - -#define base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) - - - -//// HEX //// - -static bool contains_non_ascii_slow(const char* buf, size_t len) { - for (size_t i = 0; i < len; ++i) { - if (buf[i] & 0x80) return true; - } - return false; -} - - -static bool contains_non_ascii(const char* src, size_t len) { - if (len < 16) { - return contains_non_ascii_slow(src, len); - } - - const unsigned bytes_per_word = sizeof(void*); - const unsigned align_mask = bytes_per_word - 1; - const unsigned unaligned = reinterpret_cast(src) & align_mask; - - if (unaligned > 0) { - const unsigned n = bytes_per_word - unaligned; - if (contains_non_ascii_slow(src, n)) return true; - src += n; - len -= n; - } - - -#if defined(__x86_64__) || defined(_WIN64) - const uintptr_t mask = 0x8080808080808080ll; -#else - const uintptr_t mask = 0x80808080l; -#endif - - const uintptr_t* srcw = reinterpret_cast(src); - - for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { - if (srcw[i] & mask) return true; - } - - const unsigned remainder = len & align_mask; - if (remainder > 0) { - const size_t offset = len - remainder; - if (contains_non_ascii_slow(src + offset, remainder)) return true; - } - - return false; -} - - -static void force_ascii_slow(const char* src, char* dst, size_t len) { - for (size_t i = 0; i < len; ++i) { - dst[i] = src[i] & 0x7f; - } -} - - -static void force_ascii(const char* src, char* dst, size_t len) { - if (len < 16) { - force_ascii_slow(src, dst, len); - return; - } - - const unsigned bytes_per_word = sizeof(void*); - const unsigned align_mask = bytes_per_word - 1; - const unsigned src_unalign = reinterpret_cast(src) & align_mask; - const unsigned dst_unalign = reinterpret_cast(dst) & align_mask; - - if (src_unalign > 0) { - if (src_unalign == dst_unalign) { - const unsigned unalign = bytes_per_word - src_unalign; - force_ascii_slow(src, dst, unalign); - src += unalign; - dst += unalign; - len -= src_unalign; - } else { - force_ascii_slow(src, dst, len); - return; - } - } - -#if defined(__x86_64__) || defined(_WIN64) - const uintptr_t mask = ~0x8080808080808080ll; -#else - const uintptr_t mask = ~0x80808080l; -#endif - - const uintptr_t* srcw = reinterpret_cast(src); - uintptr_t* dstw = reinterpret_cast(dst); - - for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { - dstw[i] = srcw[i] & mask; - } - - const unsigned remainder = len & align_mask; - if (remainder > 0) { - const size_t offset = len - remainder; - force_ascii_slow(src + offset, dst + offset, remainder); - } -} - - -static size_t base64_encode(const char* src, - size_t slen, - char* dst, - size_t dlen) { - // We know how much we'll write, just make sure that there's space. - assert(dlen >= base64_encoded_size(slen) && - "not enough space provided for base64 encode"); - - dlen = base64_encoded_size(slen); - - unsigned a; - unsigned b; - unsigned c; - unsigned i; - unsigned k; - unsigned n; - - static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - - i = 0; - k = 0; - n = slen / 3 * 3; - - while (i < n) { - a = src[i + 0] & 0xff; - b = src[i + 1] & 0xff; - c = src[i + 2] & 0xff; - - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; - dst[k + 2] = table[((b & 0x0f) << 2) | (c >> 6)]; - dst[k + 3] = table[c & 0x3f]; - - i += 3; - k += 4; - } - - if (n != slen) { - switch (slen - n) { - case 1: - a = src[i + 0] & 0xff; - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[(a & 3) << 4]; - dst[k + 2] = '='; - dst[k + 3] = '='; - break; - - case 2: - a = src[i + 0] & 0xff; - b = src[i + 1] & 0xff; - dst[k + 0] = table[a >> 2]; - dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; - dst[k + 2] = table[(b & 0x0f) << 2]; - dst[k + 3] = '='; - break; - } - } - - return dlen; -} - - -static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) { - // We know how much we'll write, just make sure that there's space. - assert(dlen >= slen * 2 && - "not enough space provided for hex encode"); - - dlen = slen * 2; - for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) { - static const char hex[] = "0123456789abcdef"; - uint8_t val = static_cast(src[i]); - dst[k + 0] = hex[val >> 4]; - dst[k + 1] = hex[val & 15]; - } - - return dlen; -} - - - -static Local Encode(const char* buf, - size_t buflen, - enum Encoding encoding) { - assert(buflen <= node::Buffer::kMaxLength); - if (!buflen && encoding != BUFFER) - return New("").ToLocalChecked(); - - Local val; - switch (encoding) { - case BUFFER: - return CopyBuffer(buf, buflen).ToLocalChecked(); - - case ASCII: - if (contains_non_ascii(buf, buflen)) { - char* out = new char[buflen]; - force_ascii(buf, out, buflen); - val = New(out, buflen).ToLocalChecked(); - delete[] out; - } else { - val = New(buf, buflen).ToLocalChecked(); - } - break; - - case UTF8: - val = New(buf, buflen).ToLocalChecked(); - break; - - case BINARY: { - // TODO(isaacs) use ExternalTwoByteString? - const unsigned char *cbuf = reinterpret_cast(buf); - uint16_t * twobytebuf = new uint16_t[buflen]; - for (size_t i = 0; i < buflen; i++) { - // XXX is the following line platform independent? - twobytebuf[i] = cbuf[i]; - } - val = New(twobytebuf, buflen).ToLocalChecked(); - delete[] twobytebuf; - break; - } - - case BASE64: { - size_t dlen = base64_encoded_size(buflen); - char* dst = new char[dlen]; - - size_t written = base64_encode(buf, buflen, dst, dlen); - assert(written == dlen); - - val = New(dst, dlen).ToLocalChecked(); - delete[] dst; - break; - } - - case UCS2: { - const uint16_t* data = reinterpret_cast(buf); - val = New(data, buflen / 2).ToLocalChecked(); - break; - } - - case HEX: { - size_t dlen = buflen * 2; - char* dst = new char[dlen]; - size_t written = hex_encode(buf, buflen, dst, dlen); - assert(written == dlen); - - val = New(dst, dlen).ToLocalChecked(); - delete[] dst; - break; - } - - default: - assert(0 && "unknown encoding"); - break; - } - - return val; -} - -#undef base64_encoded_size - -} // end of namespace imp - -#endif // NAN_STRING_BYTES_H_ diff --git a/node_modules/nan/nan_typedarray_contents.h b/node_modules/nan/nan_typedarray_contents.h deleted file mode 100644 index c6ac8a4..0000000 --- a/node_modules/nan/nan_typedarray_contents.h +++ /dev/null @@ -1,96 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_TYPEDARRAY_CONTENTS_H_ -#define NAN_TYPEDARRAY_CONTENTS_H_ - -template -class TypedArrayContents { - public: - inline explicit TypedArrayContents(v8::Local from) : - length_(0), data_(NULL) { - HandleScope scope; - - size_t length = 0; - void* data = NULL; - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - - if (from->IsArrayBufferView()) { - v8::Local array = - v8::Local::Cast(from); - - const size_t byte_length = array->ByteLength(); - const ptrdiff_t byte_offset = array->ByteOffset(); - v8::Local buffer = array->Buffer(); - - length = byte_length / sizeof(T); -// Actually it's 7.9 here but this would lead to ABI issues with Node.js 13 -// using 7.8 till 13.2.0. -#if (V8_MAJOR_VERSION >= 8) - data = static_cast(buffer->GetBackingStore()->Data()) + byte_offset; -#else - data = static_cast(buffer->GetContents().Data()) + byte_offset; -#endif - } - -#else - - if (from->IsObject() && !from->IsNull()) { - v8::Local array = v8::Local::Cast(from); - - MaybeLocal buffer = Get(array, - New("buffer").ToLocalChecked()); - MaybeLocal byte_length = Get(array, - New("byteLength").ToLocalChecked()); - MaybeLocal byte_offset = Get(array, - New("byteOffset").ToLocalChecked()); - - if (!buffer.IsEmpty() && - !byte_length.IsEmpty() && byte_length.ToLocalChecked()->IsUint32() && - !byte_offset.IsEmpty() && byte_offset.ToLocalChecked()->IsUint32()) { - data = array->GetIndexedPropertiesExternalArrayData(); - if(data) { - length = byte_length.ToLocalChecked()->Uint32Value() / sizeof(T); - } - } - } - -#endif - -#if defined(_MSC_VER) && _MSC_VER >= 1900 || __cplusplus >= 201103L - assert(reinterpret_cast(data) % alignof (T) == 0); -#elif defined(_MSC_VER) && _MSC_VER >= 1600 || defined(__GNUC__) - assert(reinterpret_cast(data) % __alignof(T) == 0); -#else - assert(reinterpret_cast(data) % sizeof (T) == 0); -#endif - - length_ = length; - data_ = static_cast(data); - } - - inline size_t length() const { return length_; } - inline T* operator*() { return data_; } - inline const T* operator*() const { return data_; } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(TypedArrayContents) - - //Disable heap allocation - void *operator new(size_t size); - void operator delete(void *, size_t) { - abort(); - } - - size_t length_; - T* data_; -}; - -#endif // NAN_TYPEDARRAY_CONTENTS_H_ diff --git a/node_modules/nan/nan_weak.h b/node_modules/nan/nan_weak.h deleted file mode 100644 index 7e7ab07..0000000 --- a/node_modules/nan/nan_weak.h +++ /dev/null @@ -1,437 +0,0 @@ -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -#ifndef NAN_WEAK_H_ -#define NAN_WEAK_H_ - -static const int kInternalFieldsInWeakCallback = 2; -static const int kNoInternalFieldIndex = -1; - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \ - v8::WeakCallbackInfo > const& -# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \ - NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ -#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION -# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \ - v8::PhantomCallbackData > const& -# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \ - NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ -#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION -# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \ - v8::PhantomCallbackData > const& -# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \ - v8::InternalFieldsCallbackData, void> const& -# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION -# define NAN_WEAK_CALLBACK_DATA_TYPE_ \ - v8::WeakCallbackData > const& -# define NAN_WEAK_CALLBACK_SIG_ NAN_WEAK_CALLBACK_DATA_TYPE_ -#else -# define NAN_WEAK_CALLBACK_DATA_TYPE_ void * -# define NAN_WEAK_CALLBACK_SIG_ \ - v8::Persistent, NAN_WEAK_CALLBACK_DATA_TYPE_ -#endif - -template -class WeakCallbackInfo { - public: - typedef void (*Callback)(const WeakCallbackInfo& data); - WeakCallbackInfo( - Persistent *persistent - , Callback callback - , void *parameter - , void *field1 = 0 - , void *field2 = 0) : - callback_(callback), isolate_(0), parameter_(parameter) { - std::memcpy(&persistent_, persistent, sizeof (v8::Persistent)); - internal_fields_[0] = field1; - internal_fields_[1] = field2; - } - inline v8::Isolate *GetIsolate() const { return isolate_; } - inline T *GetParameter() const { return static_cast(parameter_); } - inline void *GetInternalField(int index) const { - assert((index == 0 || index == 1) && "internal field index out of bounds"); - if (index == 0) { - return internal_fields_[0]; - } else { - return internal_fields_[1]; - } - } - - private: - NAN_DISALLOW_ASSIGN_COPY_MOVE(WeakCallbackInfo) - Callback callback_; - v8::Isolate *isolate_; - void *parameter_; - void *internal_fields_[kInternalFieldsInWeakCallback]; - v8::Persistent persistent_; - template friend class Persistent; - template friend class PersistentBase; -#if NODE_MODULE_VERSION <= NODE_0_12_MODULE_VERSION -# if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - template - static void invoke(NAN_WEAK_CALLBACK_SIG_ data); - template - static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data); -# else - static void invoke(NAN_WEAK_CALLBACK_SIG_ data); - static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data); -# endif -#else -# if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - template - static void invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data); - template - static void invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data); -# else - static void invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data); - static void invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data); -# endif - static WeakCallbackInfo *unwrapparameter( - NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data); - static WeakCallbackInfo *unwraptwofield( - NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data); -#endif -}; - - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - -template -template -void -WeakCallbackInfo::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) { - WeakCallbackInfo *cbinfo = unwrapparameter(data); - if (isFirstPass) { - cbinfo->persistent_.Reset(); - data.SetSecondPassCallback(invokeparameter); - } else { - cbinfo->callback_(*cbinfo); - delete cbinfo; - } -} - -template -template -void -WeakCallbackInfo::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) { - WeakCallbackInfo *cbinfo = unwraptwofield(data); - if (isFirstPass) { - cbinfo->persistent_.Reset(); - data.SetSecondPassCallback(invoketwofield); - } else { - cbinfo->callback_(*cbinfo); - delete cbinfo; - } -} - -template -WeakCallbackInfo *WeakCallbackInfo::unwrapparameter( - NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) { - WeakCallbackInfo *cbinfo = - static_cast*>(data.GetParameter()); - cbinfo->isolate_ = data.GetIsolate(); - return cbinfo; -} - -template -WeakCallbackInfo *WeakCallbackInfo::unwraptwofield( - NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) { - WeakCallbackInfo *cbinfo = - static_cast*>(data.GetInternalField(0)); - cbinfo->isolate_ = data.GetIsolate(); - return cbinfo; -} - -#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_ -#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_ -#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ -# elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION - -template -void -WeakCallbackInfo::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) { - WeakCallbackInfo *cbinfo = unwrapparameter(data); - cbinfo->persistent_.Reset(); - cbinfo->callback_(*cbinfo); - delete cbinfo; -} - -template -void -WeakCallbackInfo::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) { - WeakCallbackInfo *cbinfo = unwraptwofield(data); - cbinfo->persistent_.Reset(); - cbinfo->callback_(*cbinfo); - delete cbinfo; -} - -template -WeakCallbackInfo *WeakCallbackInfo::unwrapparameter( - NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) { - WeakCallbackInfo *cbinfo = - static_cast*>(data.GetParameter()); - cbinfo->isolate_ = data.GetIsolate(); - return cbinfo; -} - -template -WeakCallbackInfo *WeakCallbackInfo::unwraptwofield( - NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) { - WeakCallbackInfo *cbinfo = - static_cast*>(data.GetInternalField1()); - cbinfo->isolate_ = data.GetIsolate(); - return cbinfo; -} - -#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_ -#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_ -#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ -#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION - -template -template -void WeakCallbackInfo::invoke(NAN_WEAK_CALLBACK_SIG_ data) { - WeakCallbackInfo *cbinfo = unwrap(data); - cbinfo->persistent_.Reset(); - cbinfo->callback_(*cbinfo); - delete cbinfo; -} - -template -template -WeakCallbackInfo *WeakCallbackInfo::unwrap( - NAN_WEAK_CALLBACK_DATA_TYPE_ data) { - void *parameter = data.GetParameter(); - WeakCallbackInfo *cbinfo = - static_cast*>(parameter); - cbinfo->isolate_ = data.GetIsolate(); - return cbinfo; -} - -#undef NAN_WEAK_CALLBACK_SIG_ -#undef NAN_WEAK_CALLBACK_DATA_TYPE_ -#else - -template -void WeakCallbackInfo::invoke(NAN_WEAK_CALLBACK_SIG_ data) { - WeakCallbackInfo *cbinfo = unwrap(data); - cbinfo->persistent_.Dispose(); - cbinfo->persistent_.Clear(); - cbinfo->callback_(*cbinfo); - delete cbinfo; -} - -template -WeakCallbackInfo *WeakCallbackInfo::unwrap( - NAN_WEAK_CALLBACK_DATA_TYPE_ data) { - WeakCallbackInfo *cbinfo = - static_cast*>(data); - cbinfo->isolate_ = v8::Isolate::GetCurrent(); - return cbinfo; -} - -#undef NAN_WEAK_CALLBACK_SIG_ -#undef NAN_WEAK_CALLBACK_DATA_TYPE_ -#endif - -#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) -template -template -inline void Persistent::SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - WeakCallbackInfo

*wcbd; - if (type == WeakCallbackType::kParameter) { - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , parameter); - v8::PersistentBase::SetWeak( - wcbd - , WeakCallbackInfo

::template invokeparameter - , type); - } else { - v8::Local* self_v(reinterpret_cast*>(this)); - assert((*self_v)->IsObject()); - v8::Local self((*self_v).As()); - int count = self->InternalFieldCount(); - void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; - for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { - internal_fields[i] = self->GetAlignedPointerFromInternalField(i); - } - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , 0 - , internal_fields[0] - , internal_fields[1]); - self->SetAlignedPointerInInternalField(0, wcbd); - v8::PersistentBase::SetWeak( - static_cast*>(0) - , WeakCallbackInfo

::template invoketwofield - , type); - } -} -#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION -template -template -inline void Persistent::SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - WeakCallbackInfo

*wcbd; - if (type == WeakCallbackType::kParameter) { - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , parameter); - v8::PersistentBase::SetPhantom( - wcbd - , WeakCallbackInfo

::invokeparameter); - } else { - v8::Local* self_v(reinterpret_cast*>(this)); - assert((*self_v)->IsObject()); - v8::Local self((*self_v).As()); - int count = self->InternalFieldCount(); - void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; - for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { - internal_fields[i] = self->GetAlignedPointerFromInternalField(i); - } - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , 0 - , internal_fields[0] - , internal_fields[1]); - self->SetAlignedPointerInInternalField(0, wcbd); - v8::PersistentBase::SetPhantom( - static_cast*>(0) - , WeakCallbackInfo

::invoketwofield - , 0 - , count > 1 ? 1 : kNoInternalFieldIndex); - } -} -#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION -template -template -inline void Persistent::SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - WeakCallbackInfo

*wcbd; - if (type == WeakCallbackType::kParameter) { - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , parameter); - v8::PersistentBase::SetPhantom( - wcbd - , WeakCallbackInfo

::invokeparameter); - } else { - v8::Local* self_v(reinterpret_cast*>(this)); - assert((*self_v)->IsObject()); - v8::Local self((*self_v).As()); - int count = self->InternalFieldCount(); - void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; - for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { - internal_fields[i] = self->GetAlignedPointerFromInternalField(i); - } - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , 0 - , internal_fields[0] - , internal_fields[1]); - self->SetAlignedPointerInInternalField(0, wcbd); - v8::PersistentBase::SetPhantom( - WeakCallbackInfo

::invoketwofield - , 0 - , count > 1 ? 1 : kNoInternalFieldIndex); - } -} -#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION -template -template -inline void Persistent::SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - WeakCallbackInfo

*wcbd; - if (type == WeakCallbackType::kParameter) { - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , parameter); - v8::PersistentBase::SetWeak(wcbd, WeakCallbackInfo

::invoke); - } else { - v8::Local* self_v(reinterpret_cast*>(this)); - assert((*self_v)->IsObject()); - v8::Local self((*self_v).As()); - int count = self->InternalFieldCount(); - void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; - for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { - internal_fields[i] = self->GetAlignedPointerFromInternalField(i); - } - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , 0 - , internal_fields[0] - , internal_fields[1]); - v8::PersistentBase::SetWeak(wcbd, WeakCallbackInfo

::invoke); - } -} -#else -template -template -inline void PersistentBase::SetWeak( - P *parameter - , typename WeakCallbackInfo

::Callback callback - , WeakCallbackType type) { - WeakCallbackInfo

*wcbd; - if (type == WeakCallbackType::kParameter) { - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , parameter); - persistent.MakeWeak(wcbd, WeakCallbackInfo

::invoke); - } else { - v8::Local* self_v(reinterpret_cast*>(this)); - assert((*self_v)->IsObject()); - v8::Local self((*self_v).As()); - int count = self->InternalFieldCount(); - void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; - for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { - internal_fields[i] = self->GetPointerFromInternalField(i); - } - wcbd = new WeakCallbackInfo

( - reinterpret_cast*>(this) - , callback - , 0 - , internal_fields[0] - , internal_fields[1]); - persistent.MakeWeak(wcbd, WeakCallbackInfo

::invoke); - } -} -#endif - -#endif // NAN_WEAK_H_ diff --git a/node_modules/nan/package.json b/node_modules/nan/package.json deleted file mode 100644 index 263027c..0000000 --- a/node_modules/nan/package.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "_from": "nan@^2.14.0", - "_id": "nan@2.14.1", - "_inBundle": false, - "_integrity": "sha512-isWHgVjnFjh2x2yuJ/tj3JbwoHu3UC2dX5G/88Cm24yB6YopVgxvBObDY7n5xW6ExmFhJpSEQqFPvq9zaXc8Jw==", - "_location": "/nan", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "nan@^2.14.0", - "name": "nan", - "escapedName": "nan", - "rawSpec": "^2.14.0", - "saveSpec": null, - "fetchSpec": "^2.14.0" - }, - "_requiredBy": [ - "/kerberos" - ], - "_resolved": "https://registry.npmjs.org/nan/-/nan-2.14.1.tgz", - "_shasum": "d7be34dfa3105b91494c3147089315eff8874b01", - "_spec": "nan@^2.14.0", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/kerberos", - "bugs": { - "url": "https://github.com/nodejs/nan/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Rod Vagg", - "email": "r@va.gg", - "url": "https://github.com/rvagg" - }, - { - "name": "Benjamin Byholm", - "email": "bbyholm@abo.fi", - "url": "https://github.com/kkoopa/" - }, - { - "name": "Trevor Norris", - "email": "trev.norris@gmail.com", - "url": "https://github.com/trevnorris" - }, - { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net", - "url": "https://github.com/TooTallNate" - }, - { - "name": "Brett Lawson", - "email": "brett19@gmail.com", - "url": "https://github.com/brett19" - }, - { - "name": "Ben Noordhuis", - "email": "info@bnoordhuis.nl", - "url": "https://github.com/bnoordhuis" - }, - { - "name": "David Siegel", - "email": "david@artcom.de", - "url": "https://github.com/agnat" - }, - { - "name": "Michael Ira Krufky", - "email": "mkrufky@gmail.com", - "url": "https://github.com/mkrufky" - } - ], - "deprecated": false, - "description": "Native Abstractions for Node.js: C++ header for Node 0.8 -> 14 compatibility", - "devDependencies": { - "bindings": "~1.2.1", - "commander": "^2.8.1", - "glob": "^5.0.14", - "node-gyp": "~3.6.2", - "readable-stream": "^2.1.4", - "request": "=2.81.0", - "tap": "~0.7.1", - "xtend": "~4.0.0" - }, - "homepage": "https://github.com/nodejs/nan#readme", - "license": "MIT", - "main": "include_dirs.js", - "name": "nan", - "repository": { - "type": "git", - "url": "git://github.com/nodejs/nan.git" - }, - "scripts": { - "docs": "doc/.build.sh", - "rebuild-tests": "node-gyp rebuild --msvs_version=2015 --directory test", - "test": "tap --gc --stderr test/js/*-test.js", - "test:worker": "node --experimental-worker test/tap-as-worker.js --gc --stderr test/js/*-test.js" - }, - "version": "2.14.1" -} diff --git a/node_modules/nan/tools/1to2.js b/node_modules/nan/tools/1to2.js deleted file mode 100755 index 6af2505..0000000 --- a/node_modules/nan/tools/1to2.js +++ /dev/null @@ -1,412 +0,0 @@ -#!/usr/bin/env node -/********************************************************************* - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2018 NAN contributors - * - * MIT License - ********************************************************************/ - -var commander = require('commander'), - fs = require('fs'), - glob = require('glob'), - groups = [], - total = 0, - warning1 = '/* ERROR: Rewrite using Buffer */\n', - warning2 = '\\/\\* ERROR\\: Rewrite using Buffer \\*\\/\\n', - length, - i; - -fs.readFile(__dirname + '/package.json', 'utf8', function (err, data) { - if (err) { - throw err; - } - - commander - .version(JSON.parse(data).version) - .usage('[options] ') - .parse(process.argv); - - if (!process.argv.slice(2).length) { - commander.outputHelp(); - } -}); - -/* construct strings representing regular expressions - each expression contains a unique group allowing for identification of the match - the index of this key group, relative to the regular expression in question, - is indicated by the first array member */ - -/* simple substistutions, key group is the entire match, 0 */ -groups.push([0, [ - '_NAN_', - 'NODE_SET_METHOD', - 'NODE_SET_PROTOTYPE_METHOD', - 'NanAsciiString', - 'NanEscapeScope', - 'NanReturnValue', - 'NanUcs2String'].join('|')]); - -/* substitutions of parameterless macros, key group is 1 */ -groups.push([1, ['(', [ - 'NanEscapableScope', - 'NanReturnNull', - 'NanReturnUndefined', - 'NanScope'].join('|'), ')\\(\\)'].join('')]); - -/* replace TryCatch with NanTryCatch once, gobbling possible namespace, key group 2 */ -groups.push([2, '(?:(?:v8\\:\\:)?|(Nan)?)(TryCatch)']); - -/* NanNew("string") will likely not fail a ToLocalChecked(), key group 1 */ -groups.push([1, ['(NanNew)', '(\\("[^\\"]*"[^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]); - -/* Removed v8 APIs, warn that the code needs rewriting using node::Buffer, key group 2 */ -groups.push([2, ['(', warning2, ')?', '^.*?(', [ - 'GetIndexedPropertiesExternalArrayDataLength', - 'GetIndexedPropertiesExternalArrayData', - 'GetIndexedPropertiesExternalArrayDataType', - 'GetIndexedPropertiesPixelData', - 'GetIndexedPropertiesPixelDataLength', - 'HasIndexedPropertiesInExternalArrayData', - 'HasIndexedPropertiesInPixelData', - 'SetIndexedPropertiesToExternalArrayData', - 'SetIndexedPropertiesToPixelData'].join('|'), ')'].join('')]); - -/* No need for NanScope in V8-exposed methods, key group 2 */ -groups.push([2, ['((', [ - 'NAN_METHOD', - 'NAN_GETTER', - 'NAN_SETTER', - 'NAN_PROPERTY_GETTER', - 'NAN_PROPERTY_SETTER', - 'NAN_PROPERTY_ENUMERATOR', - 'NAN_PROPERTY_DELETER', - 'NAN_PROPERTY_QUERY', - 'NAN_INDEX_GETTER', - 'NAN_INDEX_SETTER', - 'NAN_INDEX_ENUMERATOR', - 'NAN_INDEX_DELETER', - 'NAN_INDEX_QUERY'].join('|'), ')\\([^\\)]*\\)\\s*\\{)\\s*NanScope\\(\\)\\s*;'].join('')]); - -/* v8::Value::ToXXXXXXX returns v8::MaybeLocal, key group 3 */ -groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->(', [ - 'Boolean', - 'Number', - 'String', - 'Object', - 'Integer', - 'Uint32', - 'Int32'].join('|'), ')\\('].join('')]); - -/* v8::Value::XXXXXXXValue returns v8::Maybe, key group 3 */ -groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->((?:', [ - 'Boolean', - 'Number', - 'Integer', - 'Uint32', - 'Int32'].join('|'), ')Value)\\('].join('')]); - -/* NAN_WEAK_CALLBACK macro was removed, write out callback definition, key group 1 */ -groups.push([1, '(NAN_WEAK_CALLBACK)\\(([^\\s\\)]+)\\)']); - -/* node::ObjectWrap and v8::Persistent have been replaced with Nan implementations, key group 1 */ -groups.push([1, ['(', [ - 'NanDisposePersistent', - 'NanObjectWrapHandle'].join('|'), ')\\s*\\(\\s*([^\\s\\)]+)'].join('')]); - -/* Since NanPersistent there is no need for NanMakeWeakPersistent, key group 1 */ -groups.push([1, '(NanMakeWeakPersistent)\\s*\\(\\s*([^\\s,]+)\\s*,\\s*']); - -/* Many methods of v8::Object and others now return v8::MaybeLocal, key group 3 */ -groups.push([3, ['([\\s])([^\\s]+)->(', [ - 'GetEndColumn', - 'GetFunction', - 'GetLineNumber', - 'NewInstance', - 'GetPropertyNames', - 'GetOwnPropertyNames', - 'GetSourceLine', - 'GetStartColumn', - 'ObjectProtoToString', - 'ToArrayIndex', - 'ToDetailString', - 'CallAsConstructor', - 'CallAsFunction', - 'CloneElementAt', - 'Delete', - 'ForceSet', - 'Get', - 'GetPropertyAttributes', - 'GetRealNamedProperty', - 'GetRealNamedPropertyInPrototypeChain', - 'Has', - 'HasOwnProperty', - 'HasRealIndexedProperty', - 'HasRealNamedCallbackProperty', - 'HasRealNamedProperty', - 'Set', - 'SetAccessor', - 'SetIndexedPropertyHandler', - 'SetNamedPropertyHandler', - 'SetPrototype'].join('|'), ')\\('].join('')]); - -/* You should get an error if any of these fail anyways, - or handle the error better, it is indicated either way, key group 2 */ -groups.push([2, ['NanNew(<(?:v8\\:\\:)?(', ['Date', 'String', 'RegExp'].join('|'), ')>)(\\([^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]); - -/* v8::Value::Equals now returns a v8::Maybe, key group 3 */ -groups.push([3, '([\\s\\(\\)])([^\\s\\(\\)]+)->(Equals)\\(([^\\s\\)]+)']); - -/* NanPersistent makes this unnecessary, key group 1 */ -groups.push([1, '(NanAssignPersistent)(?:]+>)?\\(([^,]+),\\s*']); - -/* args has been renamed to info, key group 2 */ -groups.push([2, '(\\W)(args)(\\W)']) - -/* node::ObjectWrap was replaced with NanObjectWrap, key group 2 */ -groups.push([2, '(\\W)(?:node\\:\\:)?(ObjectWrap)(\\W)']); - -/* v8::Persistent was replaced with NanPersistent, key group 2 */ -groups.push([2, '(\\W)(?:v8\\:\\:)?(Persistent)(\\W)']); - -/* counts the number of capturing groups in a well-formed regular expression, - ignoring non-capturing groups and escaped parentheses */ -function groupcount(s) { - var positive = s.match(/\((?!\?)/g), - negative = s.match(/\\\(/g); - return (positive ? positive.length : 0) - (negative ? negative.length : 0); -} - -/* compute the absolute position of each key group in the joined master RegExp */ -for (i = 1, length = groups.length; i < length; i++) { - total += groupcount(groups[i - 1][1]); - groups[i][0] += total; -} - -/* create the master RegExp, whis is the union of all the groups' expressions */ -master = new RegExp(groups.map(function (a) { return a[1]; }).join('|'), 'gm'); - -/* replacement function for String.replace, receives 21 arguments */ -function replace() { - /* simple expressions */ - switch (arguments[groups[0][0]]) { - case '_NAN_': - return 'NAN_'; - case 'NODE_SET_METHOD': - return 'NanSetMethod'; - case 'NODE_SET_PROTOTYPE_METHOD': - return 'NanSetPrototypeMethod'; - case 'NanAsciiString': - return 'NanUtf8String'; - case 'NanEscapeScope': - return 'scope.Escape'; - case 'NanReturnNull': - return 'info.GetReturnValue().SetNull'; - case 'NanReturnValue': - return 'info.GetReturnValue().Set'; - case 'NanUcs2String': - return 'v8::String::Value'; - default: - } - - /* macros without arguments */ - switch (arguments[groups[1][0]]) { - case 'NanEscapableScope': - return 'NanEscapableScope scope' - case 'NanReturnUndefined': - return 'return'; - case 'NanScope': - return 'NanScope scope'; - default: - } - - /* TryCatch, emulate negative backref */ - if (arguments[groups[2][0]] === 'TryCatch') { - return arguments[groups[2][0] - 1] ? arguments[0] : 'NanTryCatch'; - } - - /* NanNew("foo") --> NanNew("foo").ToLocalChecked() */ - if (arguments[groups[3][0]] === 'NanNew') { - return [arguments[0], '.ToLocalChecked()'].join(''); - } - - /* insert warning for removed functions as comment on new line above */ - switch (arguments[groups[4][0]]) { - case 'GetIndexedPropertiesExternalArrayData': - case 'GetIndexedPropertiesExternalArrayDataLength': - case 'GetIndexedPropertiesExternalArrayDataType': - case 'GetIndexedPropertiesPixelData': - case 'GetIndexedPropertiesPixelDataLength': - case 'HasIndexedPropertiesInExternalArrayData': - case 'HasIndexedPropertiesInPixelData': - case 'SetIndexedPropertiesToExternalArrayData': - case 'SetIndexedPropertiesToPixelData': - return arguments[groups[4][0] - 1] ? arguments[0] : [warning1, arguments[0]].join(''); - default: - } - - /* remove unnecessary NanScope() */ - switch (arguments[groups[5][0]]) { - case 'NAN_GETTER': - case 'NAN_METHOD': - case 'NAN_SETTER': - case 'NAN_INDEX_DELETER': - case 'NAN_INDEX_ENUMERATOR': - case 'NAN_INDEX_GETTER': - case 'NAN_INDEX_QUERY': - case 'NAN_INDEX_SETTER': - case 'NAN_PROPERTY_DELETER': - case 'NAN_PROPERTY_ENUMERATOR': - case 'NAN_PROPERTY_GETTER': - case 'NAN_PROPERTY_QUERY': - case 'NAN_PROPERTY_SETTER': - return arguments[groups[5][0] - 1]; - default: - } - - /* Value conversion */ - switch (arguments[groups[6][0]]) { - case 'Boolean': - case 'Int32': - case 'Integer': - case 'Number': - case 'Object': - case 'String': - case 'Uint32': - return [arguments[groups[6][0] - 2], 'NanTo(', arguments[groups[6][0] - 1]].join(''); - default: - } - - /* other value conversion */ - switch (arguments[groups[7][0]]) { - case 'BooleanValue': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - case 'Int32Value': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - case 'IntegerValue': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - case 'Uint32Value': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - default: - } - - /* NAN_WEAK_CALLBACK */ - if (arguments[groups[8][0]] === 'NAN_WEAK_CALLBACK') { - return ['template\nvoid ', - arguments[groups[8][0] + 1], '(const NanWeakCallbackInfo &data)'].join(''); - } - - /* use methods on NAN classes instead */ - switch (arguments[groups[9][0]]) { - case 'NanDisposePersistent': - return [arguments[groups[9][0] + 1], '.Reset('].join(''); - case 'NanObjectWrapHandle': - return [arguments[groups[9][0] + 1], '->handle('].join(''); - default: - } - - /* use method on NanPersistent instead */ - if (arguments[groups[10][0]] === 'NanMakeWeakPersistent') { - return arguments[groups[10][0] + 1] + '.SetWeak('; - } - - /* These return Maybes, the upper ones take no arguments */ - switch (arguments[groups[11][0]]) { - case 'GetEndColumn': - case 'GetFunction': - case 'GetLineNumber': - case 'GetOwnPropertyNames': - case 'GetPropertyNames': - case 'GetSourceLine': - case 'GetStartColumn': - case 'NewInstance': - case 'ObjectProtoToString': - case 'ToArrayIndex': - case 'ToDetailString': - return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1]].join(''); - case 'CallAsConstructor': - case 'CallAsFunction': - case 'CloneElementAt': - case 'Delete': - case 'ForceSet': - case 'Get': - case 'GetPropertyAttributes': - case 'GetRealNamedProperty': - case 'GetRealNamedPropertyInPrototypeChain': - case 'Has': - case 'HasOwnProperty': - case 'HasRealIndexedProperty': - case 'HasRealNamedCallbackProperty': - case 'HasRealNamedProperty': - case 'Set': - case 'SetAccessor': - case 'SetIndexedPropertyHandler': - case 'SetNamedPropertyHandler': - case 'SetPrototype': - return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1], ', '].join(''); - default: - } - - /* Automatic ToLocalChecked(), take it or leave it */ - switch (arguments[groups[12][0]]) { - case 'Date': - case 'String': - case 'RegExp': - return ['NanNew', arguments[groups[12][0] - 1], arguments[groups[12][0] + 1], '.ToLocalChecked()'].join(''); - default: - } - - /* NanEquals is now required for uniformity */ - if (arguments[groups[13][0]] === 'Equals') { - return [arguments[groups[13][0] - 1], 'NanEquals(', arguments[groups[13][0] - 1], ', ', arguments[groups[13][0] + 1]].join(''); - } - - /* use method on replacement class instead */ - if (arguments[groups[14][0]] === 'NanAssignPersistent') { - return [arguments[groups[14][0] + 1], '.Reset('].join(''); - } - - /* args --> info */ - if (arguments[groups[15][0]] === 'args') { - return [arguments[groups[15][0] - 1], 'info', arguments[groups[15][0] + 1]].join(''); - } - - /* ObjectWrap --> NanObjectWrap */ - if (arguments[groups[16][0]] === 'ObjectWrap') { - return [arguments[groups[16][0] - 1], 'NanObjectWrap', arguments[groups[16][0] + 1]].join(''); - } - - /* Persistent --> NanPersistent */ - if (arguments[groups[17][0]] === 'Persistent') { - return [arguments[groups[17][0] - 1], 'NanPersistent', arguments[groups[17][0] + 1]].join(''); - } - - /* This should not happen. A switch is probably missing a case if it does. */ - throw 'Unhandled match: ' + arguments[0]; -} - -/* reads a file, runs replacement and writes it back */ -function processFile(file) { - fs.readFile(file, {encoding: 'utf8'}, function (err, data) { - if (err) { - throw err; - } - - /* run replacement twice, might need more runs */ - fs.writeFile(file, data.replace(master, replace).replace(master, replace), function (err) { - if (err) { - throw err; - } - }); - }); -} - -/* process file names from command line and process the identified files */ -for (i = 2, length = process.argv.length; i < length; i++) { - glob(process.argv[i], function (err, matches) { - if (err) { - throw err; - } - matches.forEach(processFile); - }); -} diff --git a/node_modules/nan/tools/README.md b/node_modules/nan/tools/README.md deleted file mode 100644 index 7f07e4b..0000000 --- a/node_modules/nan/tools/README.md +++ /dev/null @@ -1,14 +0,0 @@ -1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions, -false positives and missed opportunities. The input files are rewritten in place. Make sure that -you have backups. You will have to manually review the changes afterwards and do some touchups. - -```sh -$ tools/1to2.js - - Usage: 1to2 [options] - - Options: - - -h, --help output usage information - -V, --version output the version number -``` diff --git a/node_modules/nan/tools/package.json b/node_modules/nan/tools/package.json deleted file mode 100644 index 2dcdd78..0000000 --- a/node_modules/nan/tools/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "1to2", - "version": "1.0.0", - "description": "NAN 1 -> 2 Migration Script", - "main": "1to2.js", - "repository": { - "type": "git", - "url": "git://github.com/nodejs/nan.git" - }, - "contributors": [ - "Benjamin Byholm (https://github.com/kkoopa/)", - "Mathias Küsel (https://github.com/mathiask88/)" - ], - "dependencies": { - "glob": "~5.0.10", - "commander": "~2.8.1" - }, - "license": "MIT" -} diff --git a/node_modules/napi-build-utils/LICENSE b/node_modules/napi-build-utils/LICENSE deleted file mode 100644 index 8e0248a..0000000 --- a/node_modules/napi-build-utils/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 inspiredware - -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/napi-build-utils/README.md b/node_modules/napi-build-utils/README.md deleted file mode 100644 index f056002..0000000 --- a/node_modules/napi-build-utils/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# napi-build-utils - -[![npm](https://img.shields.io/npm/v/napi-build-utils.svg)](https://www.npmjs.com/package/napi-build-utils) -![Node version](https://img.shields.io/node/v/prebuild.svg) -[![Build Status](https://travis-ci.org/inspiredware/napi-build-utils.svg?branch=master)](https://travis-ci.org/inspiredware/napi-build-utils) -[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) - -A set of utilities to assist developers of tools that build [N-API](https://nodejs.org/api/n-api.html#n_api_n_api) native add-ons. - -## Background - -This module is targeted to developers creating tools that build N-API native add-ons. - -It implements a set of functions that aid in determining the N-API version supported by the currently running Node instance and the set of N-API versions against which the N-API native add-on is designed to be built. Other functions determine whether a particular N-API version can be built and can issue console warnings for unsupported N-API versions. - -Unlike the modules this code is designed to facilitate building, this module is written entirely in JavaScript. - -## Quick start - -```bash -$ npm install napi-build-utils -``` - -The module exports a set of functions documented [here](./index.md). For example: - -```javascript -var napiBuildUtils = require('napi-build-utils'); -var napiVersion = napiBuildUtils.getNapiVersion(); // N-API version supported by Node, or undefined. -``` - -## Declaring supported N-API versions - -Native modules that are designed to work with [N-API](https://nodejs.org/api/n-api.html#n_api_n_api) must explicitly declare the N-API version(s) against which they are coded to build. This is accomplished by including a `binary.napi_versions` property in the module's `package.json` file. For example: - -```json -"binary": { - "napi_versions": [2,3] -} -``` - -In the absence of a need to compile against a specific N-API version, the value `3` is a good choice as this is the N-API version that was supported when N-API left experimental status. - -Modules that are built against a specific N-API version will continue to operate indefinitely, even as later versions of N-API are introduced. - -## Support - -If you run into problems or limitations, please file an issue and we'll take a look. Pull requests are also welcome. diff --git a/node_modules/napi-build-utils/index.js b/node_modules/napi-build-utils/index.js deleted file mode 100644 index 1643994..0000000 --- a/node_modules/napi-build-utils/index.js +++ /dev/null @@ -1,213 +0,0 @@ -'use strict' -// Copyright (c) 2018 inspiredware - -var path = require('path') -var pkg = require(path.resolve('package.json')) - -var versionArray = process.version - .substr(1) - .replace(/-.*$/, '') - .split('.') - .map(function (item) { - return +item - }) - -/** - * - * A set of utilities to assist developers of tools that build - * [N-API](https://nodejs.org/api/n-api.html#n_api_n_api) native add-ons. - * - * The main repository can be found - * [here](https://github.com/inspiredware/napi-build-utils#napi-build-utils). - * - * @module napi-build-utils - */ - -/** - * Implements a consistent name of `napi` for N-API runtimes. - * - * @param {string} runtime The runtime string. - * @returns {boolean} - */ -exports.isNapiRuntime = function (runtime) { - return runtime === 'napi' -} - -/** - * Determines whether the specified N-API version is supported - * by both the currently running Node instance and the package. - * - * @param {string} napiVersion The N-API version to check. - * @returns {boolean} - */ -exports.isSupportedVersion = function (napiVersion) { - var version = parseInt(napiVersion, 10) - return version <= exports.getNapiVersion() && exports.packageSupportsVersion(version) -} - -/** - * Determines whether the specified N-API version is supported by the package. - * The N-API version must be preseent in the `package.json` - * `binary.napi_versions` array. - * - * @param {number} napiVersion The N-API version to check. - * @returns {boolean} - * @private - */ -exports.packageSupportsVersion = function (napiVersion) { - if (pkg.binary && pkg.binary.napi_versions && - pkg.binary.napi_versions instanceof Array) { - for (var i = 0; i < pkg.binary.napi_versions.length; i++) { - if (pkg.binary.napi_versions[i] === napiVersion) return true - }; - }; - return false -} - -/** - * Issues a warning to the supplied log if the N-API version is not supported - * by the current Node instance or if the N-API version is not supported - * by the package. - * - * @param {string} napiVersion The N-API version to check. - * @param {Object} log The log object to which the warnings are to be issued. - * Must implement the `warn` method. - */ -exports.logUnsupportedVersion = function (napiVersion, log) { - if (!exports.isSupportedVersion(napiVersion)) { - if (exports.packageSupportsVersion(napiVersion)) { - log.warn('This Node instance does not support N-API version ' + napiVersion) - } else { - log.warn('This package does not support N-API version ' + napiVersion) - } - } -} - -/** - * Issues warnings to the supplied log for those N-API versions not supported - * by the N-API runtime or the package. - * - * Note that this function is specific to the - * [`prebuild`](https://github.com/prebuild/prebuild#prebuild) package. - * - * `target` is the list of targets to be built and is determined in one of - * three ways from the command line arguments: - * (1) `--target` specifies a specific target to build. - * (2) `--all` specifies all N-API versions supported by the package. - * (3) Neither of these specifies to build the single "best version available." - * - * `prebuild` is an array of objects in the form `{runtime: 'napi', target: '2'}`. - * The array contains the list of N-API versions that are supported by both the - * package being built and the currently running Node instance. - * - * The objective of this function is to issue a warning for those items that appear - * in the `target` argument but not in the `prebuild` argument. - * If a specific target is supported by the package (`packageSupportsVersion`) but - * but note in `prebuild`, the assumption is that the target is not supported by - * Node. - * - * @param {(Array|string)} target The N-API version(s) to check. Target is - * @param {Array} prebuild A config object created by the `prebuild` package. - * @param {Object} log The log object to which the warnings are to be issued. - * Must implement the `warn` method. - * @private - */ -exports.logMissingNapiVersions = function (target, prebuild, log) { - if (exports.getNapiBuildVersions()) { - var targets = [].concat(target) - targets.forEach(function (napiVersion) { - if (!prebuildExists(prebuild, napiVersion)) { - if (exports.packageSupportsVersion(parseInt(napiVersion, 10))) { - log.warn('This Node instance does not support N-API version ' + napiVersion) - } else { - log.warn('This package does not support N-API version ' + napiVersion) - } - } - }) - } else { - log.error('Builds with runtime \'napi\' require a binary.napi_versions ' + - 'property on the package.json file') - } -} - -/** - * Determines whether the specified N-API version exists in the prebuild - * configuration object. - * - * Note that this function is speicifc to the `prebuild` and `prebuild-install` - * packages. - * - * @param {Object} prebuild A config object created by the `prebuild` package. - * @param {string} napiVersion The N-APi version to be checked. - * @return {boolean} - * @private - */ -var prebuildExists = function (prebuild, napiVersion) { - if (prebuild) { - for (var i = 0; i < prebuild.length; i++) { - if (prebuild[i].target === napiVersion) return true - } - } - return false -} - -/** - * Returns the best N-API version to build given the highest N-API - * version supported by the current Node instance and the N-API versions - * supported by the package, or undefined if a suitable N-API version - * cannot be determined. - * - * The best build version is the greatest N-API version supported by - * the package that is less than or equal to the highest N-API version - * supported by the current Node instance. - * - * @returns {number|undefined} - */ -exports.getBestNapiBuildVersion = function () { - var bestNapiBuildVersion = 0 - var napiBuildVersions = exports.getNapiBuildVersions(pkg) - if (napiBuildVersions) { - var ourNapiVersion = exports.getNapiVersion() - napiBuildVersions.forEach(function (napiBuildVersion) { - if (napiBuildVersion > bestNapiBuildVersion && - napiBuildVersion <= ourNapiVersion) { - bestNapiBuildVersion = napiBuildVersion - } - }) - } - return bestNapiBuildVersion === 0 ? undefined : bestNapiBuildVersion -} - -/** - * Returns an array of N-API versions supported by the package. - * - * @returns {Array} - */ -exports.getNapiBuildVersions = function () { - var napiBuildVersions = [] - // remove duplicates, convert to text - if (pkg.binary && pkg.binary.napi_versions) { - pkg.binary.napi_versions.forEach(function (napiVersion) { - var duplicated = napiBuildVersions.indexOf('' + napiVersion) !== -1 - if (!duplicated) { - napiBuildVersions.push('' + napiVersion) - } - }) - } - return napiBuildVersions.length ? napiBuildVersions : undefined -} - -/** - * Returns the highest N-API version supported by the current node instance - * or undefined if N-API is not supported. - * - * @returns {string|undefined} - */ -exports.getNapiVersion = function () { - var version = process.versions.napi // string, can be undefined - if (!version) { // this code should never need to be updated - if (versionArray[0] === 9 && versionArray[1] >= 3) version = '2' // 9.3.0+ - else if (versionArray[0] === 8) version = '1' // 8.0.0+ - } - return version -} diff --git a/node_modules/napi-build-utils/index.md b/node_modules/napi-build-utils/index.md deleted file mode 100644 index ce8d3e8..0000000 --- a/node_modules/napi-build-utils/index.md +++ /dev/null @@ -1,81 +0,0 @@ - - -## napi-build-utils -A set of utilities to assist developers of tools that build -[N-API](https://nodejs.org/api/n-api.html#n_api_n_api) native add-ons. - -The main repository can be found -[here](https://github.com/inspiredware/napi-build-utils#napi-build-utils). - - -* [napi-build-utils](#module_napi-build-utils) - * [.isNapiRuntime(runtime)](#module_napi-build-utils.isNapiRuntime) ⇒ boolean - * [.isSupportedVersion(napiVersion)](#module_napi-build-utils.isSupportedVersion) ⇒ boolean - * [.logUnsupportedVersion(napiVersion, log)](#module_napi-build-utils.logUnsupportedVersion) - * [.getBestNapiBuildVersion()](#module_napi-build-utils.getBestNapiBuildVersion) ⇒ number \| undefined - * [.getNapiBuildVersions()](#module_napi-build-utils.getNapiBuildVersions) ⇒ Array.<string> - * [.getNapiVersion()](#module_napi-build-utils.getNapiVersion) ⇒ string \| undefined - - - -### napi-build-utils.isNapiRuntime(runtime) ⇒ boolean -Implements a consistent name of `napi` for N-API runtimes. - -**Kind**: static method of [napi-build-utils](#module_napi-build-utils) - -| Param | Type | Description | -| --- | --- | --- | -| runtime | string | The runtime string. | - - - -### napi-build-utils.isSupportedVersion(napiVersion) ⇒ boolean -Determines whether the specified N-API version is supported -by both the currently running Node instance and the package. - -**Kind**: static method of [napi-build-utils](#module_napi-build-utils) - -| Param | Type | Description | -| --- | --- | --- | -| napiVersion | string | The N-API version to check. | - - - -### napi-build-utils.logUnsupportedVersion(napiVersion, log) -Issues a warning to the supplied log if the N-API version is not supported -by the current Node instance or if the N-API version is not supported -by the package. - -**Kind**: static method of [napi-build-utils](#module_napi-build-utils) - -| Param | Type | Description | -| --- | --- | --- | -| napiVersion | string | The N-API version to check. | -| log | Object | The log object to which the warnings are to be issued. Must implement the `warn` method. | - - - -### napi-build-utils.getBestNapiBuildVersion() ⇒ number \| undefined -Returns the best N-API version to build given the highest N-API -version supported by the current Node instance and the N-API versions -supported by the package, or undefined if a suitable N-API version -cannot be determined. - -The best build version is the greatest N-API version supported by -the package that is less than or equal to the highest N-API version -supported by the current Node instance. - -**Kind**: static method of [napi-build-utils](#module_napi-build-utils) - - -### napi-build-utils.getNapiBuildVersions() ⇒ Array.<string> -Returns an array of N-API versions supported by the package. - -**Kind**: static method of [napi-build-utils](#module_napi-build-utils) - - -### napi-build-utils.getNapiVersion() ⇒ string \| undefined -Returns the highest N-API version supported by the current node instance -or undefined if N-API is not supported. - -**Kind**: static method of [napi-build-utils](#module_napi-build-utils) diff --git a/node_modules/napi-build-utils/package.json b/node_modules/napi-build-utils/package.json deleted file mode 100644 index 5a10f3e..0000000 --- a/node_modules/napi-build-utils/package.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "_from": "napi-build-utils@^1.0.1", - "_id": "napi-build-utils@1.0.2", - "_inBundle": false, - "_integrity": "sha512-ONmRUqK7zj7DWX0D9ADe03wbwOBZxNAfF20PlGfCWQcD3+/MakShIHrMqx9YwPTfxDdF1zLeL+RGZiR9kGMLdg==", - "_location": "/napi-build-utils", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "napi-build-utils@^1.0.1", - "name": "napi-build-utils", - "escapedName": "napi-build-utils", - "rawSpec": "^1.0.1", - "saveSpec": null, - "fetchSpec": "^1.0.1" - }, - "_requiredBy": [ - "/prebuild-install" - ], - "_resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-1.0.2.tgz", - "_shasum": "b1fddc0b2c46e380a0b7a76f984dd47c41a13806", - "_spec": "napi-build-utils@^1.0.1", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/prebuild-install", - "author": { - "name": "Jim Schlight" - }, - "binary": { - "note": "napi-build-tools is not an N-API module. This entry is for unit testing.", - "napi_versions": [ - 2, - 2, - 3 - ] - }, - "bugs": { - "url": "https://github.com/inspiredware/napi-build-utils/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "A set of utilities to assist developers of tools that build N-API native add-ons", - "devDependencies": { - "chai": "^4.1.2", - "jsdoc-to-markdown": "^4.0.1", - "mocha": "^5.2.0", - "standard": "^12.0.1" - }, - "homepage": "https://github.com/inspiredware/napi-build-utils#readme", - "keywords": [ - "n-api", - "prebuild", - "prebuild-install" - ], - "license": "MIT", - "main": "index.js", - "name": "napi-build-utils", - "repository": { - "type": "git", - "url": "git+https://github.com/inspiredware/napi-build-utils.git" - }, - "scripts": { - "doc": "jsdoc2md index.js >index.md", - "lint": "standard", - "prepublishOnly": "npm run test && npm run doc", - "test": "mocha test/ && npm run lint" - }, - "version": "1.0.2" -} diff --git a/node_modules/negotiator/HISTORY.md b/node_modules/negotiator/HISTORY.md deleted file mode 100644 index 6d06c76..0000000 --- a/node_modules/negotiator/HISTORY.md +++ /dev/null @@ -1,103 +0,0 @@ -0.6.2 / 2019-04-29 -================== - - * Fix sorting charset, encoding, and language with extra parameters - -0.6.1 / 2016-05-02 -================== - - * perf: improve `Accept` parsing speed - * perf: improve `Accept-Charset` parsing speed - * perf: improve `Accept-Encoding` parsing speed - * perf: improve `Accept-Language` parsing speed - -0.6.0 / 2015-09-29 -================== - - * Fix including type extensions in parameters in `Accept` parsing - * Fix parsing `Accept` parameters with quoted equals - * Fix parsing `Accept` parameters with quoted semicolons - * Lazy-load modules from main entry point - * perf: delay type concatenation until needed - * perf: enable strict mode - * perf: hoist regular expressions - * perf: remove closures getting spec properties - * perf: remove a closure from media type parsing - * perf: remove property delete from media type parsing - -0.5.3 / 2015-05-10 -================== - - * Fix media type parameter matching to be case-insensitive - -0.5.2 / 2015-05-06 -================== - - * Fix comparing media types with quoted values - * Fix splitting media types with quoted commas - -0.5.1 / 2015-02-14 -================== - - * Fix preference sorting to be stable for long acceptable lists - -0.5.0 / 2014-12-18 -================== - - * Fix list return order when large accepted list - * Fix missing identity encoding when q=0 exists - * Remove dynamic building of Negotiator class - -0.4.9 / 2014-10-14 -================== - - * Fix error when media type has invalid parameter - -0.4.8 / 2014-09-28 -================== - - * Fix all negotiations to be case-insensitive - * Stable sort preferences of same quality according to client order - * Support Node.js 0.6 - -0.4.7 / 2014-06-24 -================== - - * Handle invalid provided languages - * Handle invalid provided media types - -0.4.6 / 2014-06-11 -================== - - * Order by specificity when quality is the same - -0.4.5 / 2014-05-29 -================== - - * Fix regression in empty header handling - -0.4.4 / 2014-05-29 -================== - - * Fix behaviors when headers are not present - -0.4.3 / 2014-04-16 -================== - - * Handle slashes on media params correctly - -0.4.2 / 2014-02-28 -================== - - * Fix media type sorting - * Handle media types params strictly - -0.4.1 / 2014-01-16 -================== - - * Use most specific matches - -0.4.0 / 2014-01-09 -================== - - * Remove preferred prefix from methods diff --git a/node_modules/negotiator/LICENSE b/node_modules/negotiator/LICENSE deleted file mode 100644 index ea6b9e2..0000000 --- a/node_modules/negotiator/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2012-2014 Federico Romero -Copyright (c) 2012-2014 Isaac Z. Schlueter -Copyright (c) 2014-2015 Douglas Christopher Wilson - -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/negotiator/README.md b/node_modules/negotiator/README.md deleted file mode 100644 index 04a67ff..0000000 --- a/node_modules/negotiator/README.md +++ /dev/null @@ -1,203 +0,0 @@ -# negotiator - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -An HTTP content negotiator for Node.js - -## Installation - -```sh -$ npm install negotiator -``` - -## API - -```js -var Negotiator = require('negotiator') -``` - -### Accept Negotiation - -```js -availableMediaTypes = ['text/html', 'text/plain', 'application/json'] - -// The negotiator constructor receives a request object -negotiator = new Negotiator(request) - -// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' - -negotiator.mediaTypes() -// -> ['text/html', 'image/jpeg', 'application/*'] - -negotiator.mediaTypes(availableMediaTypes) -// -> ['text/html', 'application/json'] - -negotiator.mediaType(availableMediaTypes) -// -> 'text/html' -``` - -You can check a working example at `examples/accept.js`. - -#### Methods - -##### mediaType() - -Returns the most preferred media type from the client. - -##### mediaType(availableMediaType) - -Returns the most preferred media type from a list of available media types. - -##### mediaTypes() - -Returns an array of preferred media types ordered by the client preference. - -##### mediaTypes(availableMediaTypes) - -Returns an array of preferred media types ordered by priority from a list of -available media types. - -### Accept-Language Negotiation - -```js -negotiator = new Negotiator(request) - -availableLanguages = ['en', 'es', 'fr'] - -// Let's say Accept-Language header is 'en;q=0.8, es, pt' - -negotiator.languages() -// -> ['es', 'pt', 'en'] - -negotiator.languages(availableLanguages) -// -> ['es', 'en'] - -language = negotiator.language(availableLanguages) -// -> 'es' -``` - -You can check a working example at `examples/language.js`. - -#### Methods - -##### language() - -Returns the most preferred language from the client. - -##### language(availableLanguages) - -Returns the most preferred language from a list of available languages. - -##### languages() - -Returns an array of preferred languages ordered by the client preference. - -##### languages(availableLanguages) - -Returns an array of preferred languages ordered by priority from a list of -available languages. - -### Accept-Charset Negotiation - -```js -availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] - -negotiator = new Negotiator(request) - -// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' - -negotiator.charsets() -// -> ['utf-8', 'iso-8859-1', 'utf-7'] - -negotiator.charsets(availableCharsets) -// -> ['utf-8', 'iso-8859-1'] - -negotiator.charset(availableCharsets) -// -> 'utf-8' -``` - -You can check a working example at `examples/charset.js`. - -#### Methods - -##### charset() - -Returns the most preferred charset from the client. - -##### charset(availableCharsets) - -Returns the most preferred charset from a list of available charsets. - -##### charsets() - -Returns an array of preferred charsets ordered by the client preference. - -##### charsets(availableCharsets) - -Returns an array of preferred charsets ordered by priority from a list of -available charsets. - -### Accept-Encoding Negotiation - -```js -availableEncodings = ['identity', 'gzip'] - -negotiator = new Negotiator(request) - -// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' - -negotiator.encodings() -// -> ['gzip', 'identity', 'compress'] - -negotiator.encodings(availableEncodings) -// -> ['gzip', 'identity'] - -negotiator.encoding(availableEncodings) -// -> 'gzip' -``` - -You can check a working example at `examples/encoding.js`. - -#### Methods - -##### encoding() - -Returns the most preferred encoding from the client. - -##### encoding(availableEncodings) - -Returns the most preferred encoding from a list of available encodings. - -##### encodings() - -Returns an array of preferred encodings ordered by the client preference. - -##### encodings(availableEncodings) - -Returns an array of preferred encodings ordered by priority from a list of -available encodings. - -## See Also - -The [accepts](https://npmjs.org/package/accepts#readme) module builds on -this module and provides an alternative interface, mime type validation, -and more. - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/negotiator.svg -[npm-url]: https://npmjs.org/package/negotiator -[node-version-image]: https://img.shields.io/node/v/negotiator.svg -[node-version-url]: https://nodejs.org/en/download/ -[travis-image]: https://img.shields.io/travis/jshttp/negotiator/master.svg -[travis-url]: https://travis-ci.org/jshttp/negotiator -[coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator/master.svg -[coveralls-url]: https://coveralls.io/r/jshttp/negotiator?branch=master -[downloads-image]: https://img.shields.io/npm/dm/negotiator.svg -[downloads-url]: https://npmjs.org/package/negotiator diff --git a/node_modules/negotiator/index.js b/node_modules/negotiator/index.js deleted file mode 100644 index 8d4f6a2..0000000 --- a/node_modules/negotiator/index.js +++ /dev/null @@ -1,124 +0,0 @@ -/*! - * negotiator - * Copyright(c) 2012 Federico Romero - * Copyright(c) 2012-2014 Isaac Z. Schlueter - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Cached loaded submodules. - * @private - */ - -var modules = Object.create(null); - -/** - * Module exports. - * @public - */ - -module.exports = Negotiator; -module.exports.Negotiator = Negotiator; - -/** - * Create a Negotiator instance from a request. - * @param {object} request - * @public - */ - -function Negotiator(request) { - if (!(this instanceof Negotiator)) { - return new Negotiator(request); - } - - this.request = request; -} - -Negotiator.prototype.charset = function charset(available) { - var set = this.charsets(available); - return set && set[0]; -}; - -Negotiator.prototype.charsets = function charsets(available) { - var preferredCharsets = loadModule('charset').preferredCharsets; - return preferredCharsets(this.request.headers['accept-charset'], available); -}; - -Negotiator.prototype.encoding = function encoding(available) { - var set = this.encodings(available); - return set && set[0]; -}; - -Negotiator.prototype.encodings = function encodings(available) { - var preferredEncodings = loadModule('encoding').preferredEncodings; - return preferredEncodings(this.request.headers['accept-encoding'], available); -}; - -Negotiator.prototype.language = function language(available) { - var set = this.languages(available); - return set && set[0]; -}; - -Negotiator.prototype.languages = function languages(available) { - var preferredLanguages = loadModule('language').preferredLanguages; - return preferredLanguages(this.request.headers['accept-language'], available); -}; - -Negotiator.prototype.mediaType = function mediaType(available) { - var set = this.mediaTypes(available); - return set && set[0]; -}; - -Negotiator.prototype.mediaTypes = function mediaTypes(available) { - var preferredMediaTypes = loadModule('mediaType').preferredMediaTypes; - return preferredMediaTypes(this.request.headers.accept, available); -}; - -// Backwards compatibility -Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; -Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; -Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; -Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; -Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; -Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; -Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; -Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; - -/** - * Load the given module. - * @private - */ - -function loadModule(moduleName) { - var module = modules[moduleName]; - - if (module !== undefined) { - return module; - } - - // This uses a switch for static require analysis - switch (moduleName) { - case 'charset': - module = require('./lib/charset'); - break; - case 'encoding': - module = require('./lib/encoding'); - break; - case 'language': - module = require('./lib/language'); - break; - case 'mediaType': - module = require('./lib/mediaType'); - break; - default: - throw new Error('Cannot find module \'' + moduleName + '\''); - } - - // Store to prevent invoking require() - modules[moduleName] = module; - - return module; -} diff --git a/node_modules/negotiator/lib/charset.js b/node_modules/negotiator/lib/charset.js deleted file mode 100644 index cdd0148..0000000 --- a/node_modules/negotiator/lib/charset.js +++ /dev/null @@ -1,169 +0,0 @@ -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module exports. - * @public - */ - -module.exports = preferredCharsets; -module.exports.preferredCharsets = preferredCharsets; - -/** - * Module variables. - * @private - */ - -var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; - -/** - * Parse the Accept-Charset header. - * @private - */ - -function parseAcceptCharset(accept) { - var accepts = accept.split(','); - - for (var i = 0, j = 0; i < accepts.length; i++) { - var charset = parseCharset(accepts[i].trim(), i); - - if (charset) { - accepts[j++] = charset; - } - } - - // trim accepts - accepts.length = j; - - return accepts; -} - -/** - * Parse a charset from the Accept-Charset header. - * @private - */ - -function parseCharset(str, i) { - var match = simpleCharsetRegExp.exec(str); - if (!match) return null; - - var charset = match[1]; - var q = 1; - if (match[2]) { - var params = match[2].split(';') - for (var j = 0; j < params.length; j++) { - var p = params[j].trim().split('='); - if (p[0] === 'q') { - q = parseFloat(p[1]); - break; - } - } - } - - return { - charset: charset, - q: q, - i: i - }; -} - -/** - * Get the priority of a charset. - * @private - */ - -function getCharsetPriority(charset, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; - - for (var i = 0; i < accepted.length; i++) { - var spec = specify(charset, accepted[i], index); - - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } - - return priority; -} - -/** - * Get the specificity of the charset. - * @private - */ - -function specify(charset, spec, index) { - var s = 0; - if(spec.charset.toLowerCase() === charset.toLowerCase()){ - s |= 1; - } else if (spec.charset !== '*' ) { - return null - } - - return { - i: index, - o: spec.i, - q: spec.q, - s: s - } -} - -/** - * Get the preferred charsets from an Accept-Charset header. - * @public - */ - -function preferredCharsets(accept, provided) { - // RFC 2616 sec 14.2: no header = * - var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); - - if (!provided) { - // sorted list of all charsets - return accepts - .filter(isQuality) - .sort(compareSpecs) - .map(getFullCharset); - } - - var priorities = provided.map(function getPriority(type, index) { - return getCharsetPriority(type, accepts, index); - }); - - // sorted list of accepted charsets - return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { - return provided[priorities.indexOf(priority)]; - }); -} - -/** - * Compare two specs. - * @private - */ - -function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} - -/** - * Get full charset string. - * @private - */ - -function getFullCharset(spec) { - return spec.charset; -} - -/** - * Check if a spec has any quality. - * @private - */ - -function isQuality(spec) { - return spec.q > 0; -} diff --git a/node_modules/negotiator/lib/encoding.js b/node_modules/negotiator/lib/encoding.js deleted file mode 100644 index 8432cd7..0000000 --- a/node_modules/negotiator/lib/encoding.js +++ /dev/null @@ -1,184 +0,0 @@ -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module exports. - * @public - */ - -module.exports = preferredEncodings; -module.exports.preferredEncodings = preferredEncodings; - -/** - * Module variables. - * @private - */ - -var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; - -/** - * Parse the Accept-Encoding header. - * @private - */ - -function parseAcceptEncoding(accept) { - var accepts = accept.split(','); - var hasIdentity = false; - var minQuality = 1; - - for (var i = 0, j = 0; i < accepts.length; i++) { - var encoding = parseEncoding(accepts[i].trim(), i); - - if (encoding) { - accepts[j++] = encoding; - hasIdentity = hasIdentity || specify('identity', encoding); - minQuality = Math.min(minQuality, encoding.q || 1); - } - } - - if (!hasIdentity) { - /* - * If identity doesn't explicitly appear in the accept-encoding header, - * it's added to the list of acceptable encoding with the lowest q - */ - accepts[j++] = { - encoding: 'identity', - q: minQuality, - i: i - }; - } - - // trim accepts - accepts.length = j; - - return accepts; -} - -/** - * Parse an encoding from the Accept-Encoding header. - * @private - */ - -function parseEncoding(str, i) { - var match = simpleEncodingRegExp.exec(str); - if (!match) return null; - - var encoding = match[1]; - var q = 1; - if (match[2]) { - var params = match[2].split(';'); - for (var j = 0; j < params.length; j++) { - var p = params[j].trim().split('='); - if (p[0] === 'q') { - q = parseFloat(p[1]); - break; - } - } - } - - return { - encoding: encoding, - q: q, - i: i - }; -} - -/** - * Get the priority of an encoding. - * @private - */ - -function getEncodingPriority(encoding, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; - - for (var i = 0; i < accepted.length; i++) { - var spec = specify(encoding, accepted[i], index); - - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } - - return priority; -} - -/** - * Get the specificity of the encoding. - * @private - */ - -function specify(encoding, spec, index) { - var s = 0; - if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ - s |= 1; - } else if (spec.encoding !== '*' ) { - return null - } - - return { - i: index, - o: spec.i, - q: spec.q, - s: s - } -}; - -/** - * Get the preferred encodings from an Accept-Encoding header. - * @public - */ - -function preferredEncodings(accept, provided) { - var accepts = parseAcceptEncoding(accept || ''); - - if (!provided) { - // sorted list of all encodings - return accepts - .filter(isQuality) - .sort(compareSpecs) - .map(getFullEncoding); - } - - var priorities = provided.map(function getPriority(type, index) { - return getEncodingPriority(type, accepts, index); - }); - - // sorted list of accepted encodings - return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) { - return provided[priorities.indexOf(priority)]; - }); -} - -/** - * Compare two specs. - * @private - */ - -function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} - -/** - * Get full encoding string. - * @private - */ - -function getFullEncoding(spec) { - return spec.encoding; -} - -/** - * Check if a spec has any quality. - * @private - */ - -function isQuality(spec) { - return spec.q > 0; -} diff --git a/node_modules/negotiator/lib/language.js b/node_modules/negotiator/lib/language.js deleted file mode 100644 index 62f737f..0000000 --- a/node_modules/negotiator/lib/language.js +++ /dev/null @@ -1,179 +0,0 @@ -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module exports. - * @public - */ - -module.exports = preferredLanguages; -module.exports.preferredLanguages = preferredLanguages; - -/** - * Module variables. - * @private - */ - -var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; - -/** - * Parse the Accept-Language header. - * @private - */ - -function parseAcceptLanguage(accept) { - var accepts = accept.split(','); - - for (var i = 0, j = 0; i < accepts.length; i++) { - var language = parseLanguage(accepts[i].trim(), i); - - if (language) { - accepts[j++] = language; - } - } - - // trim accepts - accepts.length = j; - - return accepts; -} - -/** - * Parse a language from the Accept-Language header. - * @private - */ - -function parseLanguage(str, i) { - var match = simpleLanguageRegExp.exec(str); - if (!match) return null; - - var prefix = match[1], - suffix = match[2], - full = prefix; - - if (suffix) full += "-" + suffix; - - var q = 1; - if (match[3]) { - var params = match[3].split(';') - for (var j = 0; j < params.length; j++) { - var p = params[j].split('='); - if (p[0] === 'q') q = parseFloat(p[1]); - } - } - - return { - prefix: prefix, - suffix: suffix, - q: q, - i: i, - full: full - }; -} - -/** - * Get the priority of a language. - * @private - */ - -function getLanguagePriority(language, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; - - for (var i = 0; i < accepted.length; i++) { - var spec = specify(language, accepted[i], index); - - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } - - return priority; -} - -/** - * Get the specificity of the language. - * @private - */ - -function specify(language, spec, index) { - var p = parseLanguage(language) - if (!p) return null; - var s = 0; - if(spec.full.toLowerCase() === p.full.toLowerCase()){ - s |= 4; - } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { - s |= 2; - } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { - s |= 1; - } else if (spec.full !== '*' ) { - return null - } - - return { - i: index, - o: spec.i, - q: spec.q, - s: s - } -}; - -/** - * Get the preferred languages from an Accept-Language header. - * @public - */ - -function preferredLanguages(accept, provided) { - // RFC 2616 sec 14.4: no header = * - var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); - - if (!provided) { - // sorted list of all languages - return accepts - .filter(isQuality) - .sort(compareSpecs) - .map(getFullLanguage); - } - - var priorities = provided.map(function getPriority(type, index) { - return getLanguagePriority(type, accepts, index); - }); - - // sorted list of accepted languages - return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { - return provided[priorities.indexOf(priority)]; - }); -} - -/** - * Compare two specs. - * @private - */ - -function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} - -/** - * Get full language string. - * @private - */ - -function getFullLanguage(spec) { - return spec.full; -} - -/** - * Check if a spec has any quality. - * @private - */ - -function isQuality(spec) { - return spec.q > 0; -} diff --git a/node_modules/negotiator/lib/mediaType.js b/node_modules/negotiator/lib/mediaType.js deleted file mode 100644 index 67309dd..0000000 --- a/node_modules/negotiator/lib/mediaType.js +++ /dev/null @@ -1,294 +0,0 @@ -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict'; - -/** - * Module exports. - * @public - */ - -module.exports = preferredMediaTypes; -module.exports.preferredMediaTypes = preferredMediaTypes; - -/** - * Module variables. - * @private - */ - -var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; - -/** - * Parse the Accept header. - * @private - */ - -function parseAccept(accept) { - var accepts = splitMediaTypes(accept); - - for (var i = 0, j = 0; i < accepts.length; i++) { - var mediaType = parseMediaType(accepts[i].trim(), i); - - if (mediaType) { - accepts[j++] = mediaType; - } - } - - // trim accepts - accepts.length = j; - - return accepts; -} - -/** - * Parse a media type from the Accept header. - * @private - */ - -function parseMediaType(str, i) { - var match = simpleMediaTypeRegExp.exec(str); - if (!match) return null; - - var params = Object.create(null); - var q = 1; - var subtype = match[2]; - var type = match[1]; - - if (match[3]) { - var kvps = splitParameters(match[3]).map(splitKeyValuePair); - - for (var j = 0; j < kvps.length; j++) { - var pair = kvps[j]; - var key = pair[0].toLowerCase(); - var val = pair[1]; - - // get the value, unwrapping quotes - var value = val && val[0] === '"' && val[val.length - 1] === '"' - ? val.substr(1, val.length - 2) - : val; - - if (key === 'q') { - q = parseFloat(value); - break; - } - - // store parameter - params[key] = value; - } - } - - return { - type: type, - subtype: subtype, - params: params, - q: q, - i: i - }; -} - -/** - * Get the priority of a media type. - * @private - */ - -function getMediaTypePriority(type, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; - - for (var i = 0; i < accepted.length; i++) { - var spec = specify(type, accepted[i], index); - - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } - - return priority; -} - -/** - * Get the specificity of the media type. - * @private - */ - -function specify(type, spec, index) { - var p = parseMediaType(type); - var s = 0; - - if (!p) { - return null; - } - - if(spec.type.toLowerCase() == p.type.toLowerCase()) { - s |= 4 - } else if(spec.type != '*') { - return null; - } - - if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { - s |= 2 - } else if(spec.subtype != '*') { - return null; - } - - var keys = Object.keys(spec.params); - if (keys.length > 0) { - if (keys.every(function (k) { - return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); - })) { - s |= 1 - } else { - return null - } - } - - return { - i: index, - o: spec.i, - q: spec.q, - s: s, - } -} - -/** - * Get the preferred media types from an Accept header. - * @public - */ - -function preferredMediaTypes(accept, provided) { - // RFC 2616 sec 14.2: no header = */* - var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); - - if (!provided) { - // sorted list of all types - return accepts - .filter(isQuality) - .sort(compareSpecs) - .map(getFullType); - } - - var priorities = provided.map(function getPriority(type, index) { - return getMediaTypePriority(type, accepts, index); - }); - - // sorted list of accepted types - return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { - return provided[priorities.indexOf(priority)]; - }); -} - -/** - * Compare two specs. - * @private - */ - -function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} - -/** - * Get full type string. - * @private - */ - -function getFullType(spec) { - return spec.type + '/' + spec.subtype; -} - -/** - * Check if a spec has any quality. - * @private - */ - -function isQuality(spec) { - return spec.q > 0; -} - -/** - * Count the number of quotes in a string. - * @private - */ - -function quoteCount(string) { - var count = 0; - var index = 0; - - while ((index = string.indexOf('"', index)) !== -1) { - count++; - index++; - } - - return count; -} - -/** - * Split a key value pair. - * @private - */ - -function splitKeyValuePair(str) { - var index = str.indexOf('='); - var key; - var val; - - if (index === -1) { - key = str; - } else { - key = str.substr(0, index); - val = str.substr(index + 1); - } - - return [key, val]; -} - -/** - * Split an Accept header into media types. - * @private - */ - -function splitMediaTypes(accept) { - var accepts = accept.split(','); - - for (var i = 1, j = 0; i < accepts.length; i++) { - if (quoteCount(accepts[j]) % 2 == 0) { - accepts[++j] = accepts[i]; - } else { - accepts[j] += ',' + accepts[i]; - } - } - - // trim accepts - accepts.length = j + 1; - - return accepts; -} - -/** - * Split a string of parameters. - * @private - */ - -function splitParameters(str) { - var parameters = str.split(';'); - - for (var i = 1, j = 0; i < parameters.length; i++) { - if (quoteCount(parameters[j]) % 2 == 0) { - parameters[++j] = parameters[i]; - } else { - parameters[j] += ';' + parameters[i]; - } - } - - // trim parameters - parameters.length = j + 1; - - for (var i = 0; i < parameters.length; i++) { - parameters[i] = parameters[i].trim(); - } - - return parameters; -} diff --git a/node_modules/negotiator/package.json b/node_modules/negotiator/package.json deleted file mode 100644 index 8fa08c6..0000000 --- a/node_modules/negotiator/package.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "_from": "negotiator@0.6.2", - "_id": "negotiator@0.6.2", - "_inBundle": false, - "_integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==", - "_location": "/negotiator", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "negotiator@0.6.2", - "name": "negotiator", - "escapedName": "negotiator", - "rawSpec": "0.6.2", - "saveSpec": null, - "fetchSpec": "0.6.2" - }, - "_requiredBy": [ - "/accepts" - ], - "_resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", - "_shasum": "feacf7ccf525a77ae9634436a64883ffeca346fb", - "_spec": "negotiator@0.6.2", - "_where": "/Users/kai/Desktop/node-course/dbproject/node_modules/accepts", - "bugs": { - "url": "https://github.com/jshttp/negotiator/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "Federico Romero", - "email": "federico.romero@outboxlabs.com" - }, - { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - } - ], - "deprecated": false, - "description": "HTTP content negotiation", - "devDependencies": { - "eslint": "5.16.0", - "eslint-plugin-markdown": "1.0.0", - "mocha": "6.1.4", - "nyc": "14.0.0" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "lib/", - "HISTORY.md", - "LICENSE", - "index.js", - "README.md" - ], - "homepage": "https://github.com/jshttp/negotiator#readme", - "keywords": [ - "http", - "content negotiation", - "accept", - "accept-language", - "accept-encoding", - "accept-charset" - ], - "license": "MIT", - "name": "negotiator", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/negotiator.git" - }, - "scripts": { - "lint": "eslint --plugin markdown --ext js,md .", - "test": "mocha --reporter spec --check-leaks --bail test/", - "test-cov": "nyc --reporter=html --reporter=text npm test", - "test-travis": "nyc --reporter=text npm test" - }, - "version": "0.6.2" -} diff --git a/node_modules/node-abi/.travis.yml b/node_modules/node-abi/.travis.yml deleted file mode 100644 index 6f637f7..0000000 --- a/node_modules/node-abi/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -language: node_js -cache: - directories: - - ~/.npm -notifications: - email: false -node_js: - - '10' - - '9' - - '8' - - '6' - - '4' - - '0.12' - - '0.10' -after_success: - - npm run travis-deploy-once "npm run semantic-release" -branches: - except: - - /^v\d+\.\d+\.\d+$/ diff --git a/node_modules/node-abi/CODE_OF_CONDUCT.md b/node_modules/node-abi/CODE_OF_CONDUCT.md deleted file mode 100644 index a28ec15..0000000 --- a/node_modules/node-abi/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,73 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or - advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at lukas.geiger94@gmail.com. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct/ - -[homepage]: https://www.contributor-covenant.org diff --git a/node_modules/node-abi/CONTRIBUTING.md b/node_modules/node-abi/CONTRIBUTING.md deleted file mode 100644 index 3a83ae9..0000000 --- a/node_modules/node-abi/CONTRIBUTING.md +++ /dev/null @@ -1,53 +0,0 @@ -# Contributing to `node-abi` - -:+1::tada: First off, thanks for taking the time to contribute to `node-abi`! :tada::+1: - -## Commit Message Guidelines - -This module uses [`semantic-release`](https://github.com/semantic-release/semantic-release) to automatically release new versions via Travis. -Therefor we have very precise rules over how our git commit messages can be formatted. - -Each commit message consists of a **header**, a **body** and a **footer**. The header has a special -format that includes a **type**, a **scope** and a **subject** ([full explanation](https://github.com/stevemao/conventional-changelog-angular/blob/master/convention.md)): - -``` -(): - - - -